From 42e94c2a616946ab34e689027ee1dda0a061779f Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:08:35 -0500 Subject: [PATCH 01/26] dt-bindings: mailbox: apple,mailbox: Allow the ANE mailbox variant The T6021 (M2 Max) ANE coprocessor mailbox is an ASC mailbox, but only one of its interrupts is known: the Apple device tree gives the ANE a single interrupt line. The binding requires the four ASC mailbox interrupts in a fixed order, so a node for this mailbox fails dtbs_check. Add the apple,t6021-ane-mailbox compatible with the apple,asc-mailbox-v4 fallback. For it, recv-not-empty is the only required interrupt; send-empty, send-not-empty and recv-empty may follow in that order. Without send-empty, the OS must poll the FIFO status before it sends. The other variants keep their constraints. The four-interrupt rule moves into a condition that excludes the ANE and AOP setup mailboxes, and the AOP setup mailbox states its minimum of two interrupts, which the top-level limit gave it before. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- .../bindings/mailbox/apple,mailbox.yaml | 42 +++++++++++++++++-- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index ee40e13c9a2b9..96675c53c3dd0 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -36,6 +36,13 @@ properties: - apple,t6020-asc-mailbox - const: apple,asc-mailbox-v4 + - description: + The T6021 ANE coprocessor mailbox is an ASC mailbox. Only its + recv-not-empty interrupt is known. + items: + - const: apple,t6021-ane-mailbox + - const: apple,asc-mailbox-v4 + - description: AOP setup-port mailbox with a separate register layout. const: apple,t8140-aop-setup-mailbox @@ -62,11 +69,11 @@ properties: maxItems: 1 interrupts: - minItems: 2 + minItems: 1 maxItems: 4 interrupt-names: - minItems: 2 + minItems: 1 maxItems: 4 iommus: @@ -95,6 +102,7 @@ allOf: then: properties: interrupts: + minItems: 2 maxItems: 2 interrupt-names: items: @@ -104,6 +112,34 @@ allOf: - iommus - apple,dma-range else: + properties: + iommus: false + apple,dma-range: false + + - if: + properties: + compatible: + contains: + const: apple,t6021-ane-mailbox + then: + properties: + interrupt-names: + minItems: 1 + items: + - const: recv-not-empty + - const: send-empty + - const: send-not-empty + - const: recv-empty + + - if: + properties: + compatible: + not: + contains: + enum: + - apple,t6021-ane-mailbox + - apple,t8140-aop-setup-mailbox + then: properties: interrupts: minItems: 4 @@ -113,8 +149,6 @@ allOf: - const: send-not-empty - const: recv-empty - const: recv-not-empty - iommus: false - apple,dma-range: false required: - compatible From 5e51767dde52355c207df48a9a61d32d5c91fca8 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:08:36 -0500 Subject: [PATCH 02/26] soc: apple: mailbox: Make the send-empty IRQ optional (poll TX) The T6021 (M2 Max) ANE coprocessor mailbox has one known AIC line, which the device tree names recv-not-empty. apple-mailbox insists on a send-empty IRQ as well, so it cannot bind that mailbox. Look send-empty up with platform_get_irq_byname_optional(). When the node has none (-ENXIO), do not request it, and let apple_mbox_send() wait for FIFO space by polling the A2I control register, the way its atomic path already does (100 us steps, 500 ms timeout, under tx_lock). Any other lookup error still fails the probe with -ENODEV. A mailbox whose node names send-empty takes the old path unchanged: the IRQ is requested at the same point with the same flags and name, and a non-atomic send still sleeps on tx_empty. All 71 apple-mailbox nodes in arch/arm64/boot/dts/apple name send-empty today. The Rust wrapper (RUST_APPLE_MAILBOX) needs no change. It only calls apple_mbox_get_byname(), apple_mbox_start(), apple_mbox_send() and apple_mbox_stop(), and never reads the IRQ fields, so a Rust client gets the poll through apple_mbox_send(). An equivalent change ran on an M2 Max lab kernel (Asahi 7.1.13 base) from 2026-09-24 to 2026-09-30, where apple-mailbox bound the one-interrupt ANE mailbox. The FIFO-full poll itself did not run there: with the ANE firmware in use (from macOS 13.5), the host sends no mailbox message after probe. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/soc/apple/mailbox.c | 33 ++++++++++++++++++++----------- include/linux/soc/apple/mailbox.h | 2 +- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index 16631fc352f44..4a4df15707ce3 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -121,7 +121,7 @@ int apple_mbox_send(struct apple_mbox *mbox, const struct apple_mbox_msg msg, mbox_ctrl = readl_relaxed(mbox->regs + mbox->hw->a2i_control); while (mbox_ctrl & mbox->hw->control_full) { - if (atomic) { + if (atomic || mbox->irq_send_empty < 0) { ret = readl_poll_timeout_atomic( mbox->regs + mbox->hw->a2i_control, mbox_ctrl, !(mbox_ctrl & mbox->hw->control_full), 100, @@ -397,8 +397,13 @@ static int apple_mbox_probe(struct platform_device *pdev) if (mbox->irq_recv_not_empty < 0) return -ENODEV; - mbox->irq_send_empty = platform_get_irq_byname(pdev, "send-empty"); - if (mbox->irq_send_empty < 0) + /* + * Some coprocessors (e.g. the T6021 ANE ASC) have no send-empty line. + * apple_mbox_send then polls the A2I control register instead. + */ + mbox->irq_send_empty = + platform_get_irq_byname_optional(pdev, "send-empty"); + if (mbox->irq_send_empty < 0 && mbox->irq_send_empty != -ENXIO) return -ENODEV; spin_lock_init(&mbox->rx_lock); @@ -415,15 +420,19 @@ static int apple_mbox_probe(struct platform_device *pdev) if (ret) return ret; - irqname = devm_kasprintf(dev, GFP_KERNEL, "%s-send", dev_name(dev)); - if (!irqname) - return -ENOMEM; - - ret = devm_request_irq(dev, mbox->irq_send_empty, - apple_mbox_send_empty_irq, - IRQF_NO_AUTOEN | IRQF_NO_SUSPEND, irqname, mbox); - if (ret) - return ret; + if (mbox->irq_send_empty >= 0) { + irqname = devm_kasprintf(dev, GFP_KERNEL, "%s-send", + dev_name(dev)); + if (!irqname) + return -ENOMEM; + + ret = devm_request_irq(dev, mbox->irq_send_empty, + apple_mbox_send_empty_irq, + IRQF_NO_AUTOEN | IRQF_NO_SUSPEND, + irqname, mbox); + if (ret) + return ret; + } ret = devm_pm_runtime_enable(dev); if (ret) diff --git a/include/linux/soc/apple/mailbox.h b/include/linux/soc/apple/mailbox.h index 9cfbbac411b8e..f7e76b554272c 100644 --- a/include/linux/soc/apple/mailbox.h +++ b/include/linux/soc/apple/mailbox.h @@ -24,7 +24,7 @@ struct apple_mbox { bool active; int irq_recv_not_empty; - int irq_send_empty; + int irq_send_empty; /* < 0: no send-empty IRQ, TX polls */ spinlock_t rx_lock; spinlock_t tx_lock; From 88af7870bb374252151e2f4a348fdbe5e264bccb Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:17:01 -0500 Subject: [PATCH 03/26] dt-bindings: npu: apple,ane: Add the Apple Neural Engine Add a binding for the Neural Engine (ANE) of the Apple T8103 (M1), T6000 (M1 Pro, Max and Ultra), T6020, T6021, T6022 (M2 Pro, Max and Ultra) and T8112 (M2). These are the compatibles that the ane and ane_t6021 drivers match. On T8103 and T6000 the node has the engine register window, one interrupt, the three ANE DARTs and five power domains. On T602x a coprocessor runs the ANE firmware, so the node also has the PMGR and power state windows, eight power domains, the coprocessor reset and mailbox, and an IOVA-only reservation for the firmware entry alias. The T8112 node has the T602x windows plus the two eFuse words that give the SoC revision to the firmware, seven power domains and the mailbox. The schema goes in npu/ with the other neural processing units, and in the ARM/APPLE MACHINE SUPPORT entry with the other Apple bindings. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- .../devicetree/bindings/npu/apple,ane.yaml | 198 ++++++++++++++++++ MAINTAINERS | 1 + 2 files changed, 199 insertions(+) create mode 100644 Documentation/devicetree/bindings/npu/apple,ane.yaml diff --git a/Documentation/devicetree/bindings/npu/apple,ane.yaml b/Documentation/devicetree/bindings/npu/apple,ane.yaml new file mode 100644 index 0000000000000..ebca460a81bc1 --- /dev/null +++ b/Documentation/devicetree/bindings/npu/apple,ane.yaml @@ -0,0 +1,198 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/npu/apple,ane.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple Neural Engine + +maintainers: + - Joshua Warren <816217+joshuaswarren@users.noreply.github.com> + +description: + The Apple Neural Engine (ANE) is the neural network accelerator of Apple + SoCs. It accesses memory through three DARTs. On T8103 and T6000 the host + drives the engine through its register window. On T602x and T8112 a + coprocessor runs the ANE firmware and the host talks to it through an ASC + mailbox. + +properties: + compatible: + enum: + - apple,t8103-ane + - apple,t6000-ane + - apple,t6020-ane + - apple,t6021-ane + - apple,t6022-ane + - apple,t8112-ane + + reg: + minItems: 1 + items: + - description: Engine registers. On T602x and T8112 this is the whole + ANE block, including the coprocessor. + - description: Power manager (PMGR) registers of the ANE + - description: ANE power state registers in the PMGR + - description: eFuse words that give the SoC revision to the ANE + firmware + + reg-names: + minItems: 1 + items: + - const: engine + - const: pmgr + - const: set + - const: fuse + + interrupts: + maxItems: 1 + + interrupt-names: + items: + - const: ane + + iommus: + maxItems: 3 + + power-domains: + description: + The power states the engine needs, five on T8103 and T6000, eight on + T602x and seven on T8112. + minItems: 5 + maxItems: 8 + + resets: + maxItems: 1 + description: Reset of the ANE coprocessor + + mboxes: + maxItems: 1 + description: Mailbox of the ANE coprocessor + + memory-region: + maxItems: 1 + description: + IOVA-only reservation of the firmware entry alias in the ANE DART + address space. + +required: + - compatible + - reg + - reg-names + - interrupts + - interrupt-names + - iommus + - power-domains + +allOf: + - if: + properties: + compatible: + contains: + enum: + - apple,t8103-ane + - apple,t6000-ane + then: + properties: + reg: + maxItems: 1 + reg-names: + maxItems: 1 + power-domains: + maxItems: 5 + resets: false + mboxes: false + memory-region: false + + - if: + properties: + compatible: + contains: + enum: + - apple,t6020-ane + - apple,t6021-ane + - apple,t6022-ane + then: + properties: + reg: + minItems: 3 + maxItems: 3 + reg-names: + minItems: 3 + maxItems: 3 + power-domains: + minItems: 8 + required: + - resets + - mboxes + - memory-region + + - if: + properties: + compatible: + contains: + const: apple,t8112-ane + then: + properties: + reg: + minItems: 4 + reg-names: + minItems: 4 + power-domains: + minItems: 7 + maxItems: 7 + resets: false + memory-region: false + required: + - mboxes + +additionalProperties: false + +examples: + - | + #include + #include + + soc { + #address-cells = <2>; + #size-cells = <2>; + + ane@26bc04000 { + compatible = "apple,t8103-ane"; + reg = <0x2 0x6bc04000 0x0 0x24000>; + reg-names = "engine"; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "ane"; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_set1>, <&ps_ane_set2>, + <&ps_ane_set3>, <&ps_ane_set4>, <&ps_ane_set5>; + }; + }; + + - | + #include + #include + + soc { + #address-cells = <2>; + #size-cells = <2>; + + ane@284000000 { + compatible = "apple,t6021-ane"; + reg = <0x2 0x84000000 0x0 0x2000000>, + <0x2 0x8e080000 0x0 0x4034>, + <0x2 0x8e08c000 0x0 0x4000>; + reg-names = "engine", "pmgr", "set"; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "ane"; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_sys_mpm>, <&ps_ane_td>, + <&ps_ane_base>, <&ps_ane_set1>, <&ps_ane_set2>, + <&ps_ane_set3>, <&ps_ane_set4>, <&ps_ane_cpu>; + resets = <&ps_ane_cpu>; + mboxes = <&ane_mbox>; + memory-region = <&ane_alias_iova>; + }; + }; diff --git a/MAINTAINERS b/MAINTAINERS index 368bf2b43af1c..6cbc8ab2d3679 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2570,6 +2570,7 @@ F: Documentation/devicetree/bindings/leds/backlight/apple,dwi-bl.yaml F: Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml F: Documentation/devicetree/bindings/mfd/apple,smc.yaml F: Documentation/devicetree/bindings/net/bluetooth/brcm,bcm4377-bluetooth.yaml +F: Documentation/devicetree/bindings/npu/apple,ane.yaml F: Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml F: Documentation/devicetree/bindings/nvmem/apple,efuses.yaml F: Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml From 7a18e9d53b12ad80b4ec4a40eaef05cc0cb31b38 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:17:02 -0500 Subject: [PATCH 04/26] dt-bindings: mailbox: apple,mailbox: Add the T8112 ANE mailbox The T8112 (M2) ANE coprocessor has an ASC mailbox at the same offset in its block as the T6021 ANE, and the Apple device tree also gives that ANE a single interrupt line (520). Add apple,t8112-ane-mailbox to the ANE mailbox variant, with the same interrupt rules as apple,t6021-ane-mailbox. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- .../devicetree/bindings/mailbox/apple,mailbox.yaml | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index 96675c53c3dd0..32fb3acb8c99f 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -37,10 +37,12 @@ properties: - const: apple,asc-mailbox-v4 - description: - The T6021 ANE coprocessor mailbox is an ASC mailbox. Only its - recv-not-empty interrupt is known. + The T6021 and T8112 ANE coprocessor mailboxes are ASC mailboxes. + Only their recv-not-empty interrupt is known. items: - - const: apple,t6021-ane-mailbox + - enum: + - apple,t6021-ane-mailbox + - apple,t8112-ane-mailbox - const: apple,asc-mailbox-v4 - description: @@ -120,7 +122,9 @@ allOf: properties: compatible: contains: - const: apple,t6021-ane-mailbox + enum: + - apple,t6021-ane-mailbox + - apple,t8112-ane-mailbox then: properties: interrupt-names: @@ -138,6 +142,7 @@ allOf: contains: enum: - apple,t6021-ane-mailbox + - apple,t8112-ane-mailbox - apple,t8140-aop-setup-mailbox then: properties: From 35a088238be14af6500c84662c017ddf06999b2c Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:22:08 -0500 Subject: [PATCH 05/26] accel/ane: Add the Apple Neural Engine driver Add a DRM accel driver for the Apple Neural Engine (ANE). One Kconfig symbol, DRM_ACCEL_ANE, builds two modules from this directory: - ane binds apple,t8103-ane and apple,t6000-ane (M1, and die 0 of the M1 Pro, Max and Ultra). Linux starts no ANE firmware on these SoCs: the host writes task descriptors to the engine's task queue and maps the buffers through the three ANE DARTs (ABI 1, DRM_IOCTL_ANE_SUBMIT). - ane_t6021 binds apple,t6020-ane, apple,t6021-ane, apple,t6022-ane and apple,t8112-ane (M2 Pro, Max and Ultra die 0, and M2). On these SoCs Linux must start the ANE coprocessor. The driver loads the firmware with request_firmware(), checks it against a SHA-256 pin, copies it to its own DMA memory, starts the coprocessor, and sends LOAD, CREATE and CALL commands on the firmware's command ring (ABI 2, DRM_IOCTL_ANE_PROG_LOAD, DRM_IOCTL_ANE_PROC_CREATE and DRM_IOCTL_ANE_EXEC). Both register /dev/accel/accel*. include/uapi/drm/ane_accel.h has the ioctls of both ABIs, and the DRM major version tells userspace which ABI the device has. The sources are those of the out-of-tree omarchy-ane driver at tag v0.4.0 (16d13ef52dc6), which started from the ane driver of Eileen Yoon. The move changes only the build glue: the SPDX comment style, the include path of the UAPI header, an include of drm.h and the Linux-syscall-note in the UAPI header, and the module version, which the out-of-tree build took from git describe (MODULE_VERSION and one log line). Compiled for arm64, every object has the same code as the out-of-tree build, except for the argument list of that log line. The out-of-tree build of this code ran on T8103 (M1), T6001 (M1 Max) and T6021 (M2 Max) with linux-asahi 7.1.13. T6000, T6002, T6020, T6022 and T8112 have not run it. ane also matches apple,t6020-ane and apple,t6021-ane and refuses them at probe; ane_t6021 binds them. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- MAINTAINERS | 9 + drivers/accel/Kconfig | 1 + drivers/accel/Makefile | 1 + drivers/accel/ane/Kconfig | 23 + drivers/accel/ane/Makefile | 14 + drivers/accel/ane/ane.h | 160 ++ drivers/accel/ane/ane_boost.c | 145 ++ drivers/accel/ane/ane_dart.c | 271 +++ drivers/accel/ane/ane_drv.c | 1234 ++++++++++ drivers/accel/ane/ane_fw_validate.h | 480 ++++ drivers/accel/ane/ane_t6021.h | 796 +++++++ drivers/accel/ane/ane_t6021_boot.c | 557 +++++ drivers/accel/ane/ane_t6021_boot.h | 832 +++++++ drivers/accel/ane/ane_t6021_fwload.c | 645 +++++ drivers/accel/ane/ane_t6021_rtclient_main.c | 2363 +++++++++++++++++++ drivers/accel/ane/ane_tm.c | 652 +++++ drivers/accel/ane/ane_tm.h | 20 + include/uapi/drm/ane_accel.h | 130 + 18 files changed, 8333 insertions(+) create mode 100644 drivers/accel/ane/Kconfig create mode 100644 drivers/accel/ane/Makefile create mode 100644 drivers/accel/ane/ane.h create mode 100644 drivers/accel/ane/ane_boost.c create mode 100644 drivers/accel/ane/ane_dart.c create mode 100644 drivers/accel/ane/ane_drv.c create mode 100644 drivers/accel/ane/ane_fw_validate.h create mode 100644 drivers/accel/ane/ane_t6021.h create mode 100644 drivers/accel/ane/ane_t6021_boot.c create mode 100644 drivers/accel/ane/ane_t6021_boot.h create mode 100644 drivers/accel/ane/ane_t6021_fwload.c create mode 100644 drivers/accel/ane/ane_t6021_rtclient_main.c create mode 100644 drivers/accel/ane/ane_tm.c create mode 100644 drivers/accel/ane/ane_tm.h create mode 100644 include/uapi/drm/ane_accel.h diff --git a/MAINTAINERS b/MAINTAINERS index 6cbc8ab2d3679..9b91fa8f0f987 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7898,6 +7898,15 @@ S: Maintained F: drivers/soc/ti/smartreflex.c F: include/linux/power/smartreflex.h +DRM ACCEL DRIVER FOR APPLE NEURAL ENGINE +M: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> +L: asahi@lists.linux.dev +L: dri-devel@lists.freedesktop.org +S: Maintained +F: Documentation/devicetree/bindings/npu/apple,ane.yaml +F: drivers/accel/ane/ +F: include/uapi/drm/ane_accel.h + DRM ACCEL DRIVERS FOR INTEL VPU M: Maciej Falkowski M: Karol Wachowski diff --git a/drivers/accel/Kconfig b/drivers/accel/Kconfig index bdf48ccafcf21..9e641c2c30ae1 100644 --- a/drivers/accel/Kconfig +++ b/drivers/accel/Kconfig @@ -25,6 +25,7 @@ menuconfig DRM_ACCEL and debugfs). source "drivers/accel/amdxdna/Kconfig" +source "drivers/accel/ane/Kconfig" source "drivers/accel/ethosu/Kconfig" source "drivers/accel/habanalabs/Kconfig" source "drivers/accel/ivpu/Kconfig" diff --git a/drivers/accel/Makefile b/drivers/accel/Makefile index 1d3a7251b950f..235ebf723025c 100644 --- a/drivers/accel/Makefile +++ b/drivers/accel/Makefile @@ -1,6 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only obj-$(CONFIG_DRM_ACCEL_AMDXDNA) += amdxdna/ +obj-$(CONFIG_DRM_ACCEL_ANE) += ane/ obj-$(CONFIG_DRM_ACCEL_ARM_ETHOSU) += ethosu/ obj-$(CONFIG_DRM_ACCEL_HABANALABS) += habanalabs/ obj-$(CONFIG_DRM_ACCEL_IVPU) += ivpu/ diff --git a/drivers/accel/ane/Kconfig b/drivers/accel/ane/Kconfig new file mode 100644 index 0000000000000..a1e8766340621 --- /dev/null +++ b/drivers/accel/ane/Kconfig @@ -0,0 +1,23 @@ +# SPDX-License-Identifier: GPL-2.0-only + +config DRM_ACCEL_ANE + tristate "Apple Neural Engine (ANE)" + depends on DRM_ACCEL + depends on ARCH_APPLE || COMPILE_TEST + depends on APPLE_RTKIT + depends on APPLE_DART || COMPILE_TEST + depends on MMU + select CRYPTO_LIB_SHA256 + help + Choose this option if you have an Apple SoC with a Neural Engine: + M1 (T8103), M1 Pro, Max and Ultra (T6000, T6001, T6002), M2 + (T8112), or M2 Pro, Max and Ultra (T6020, T6021, T6022). + + The interface exposed to userspace is described in + include/uapi/drm/ane_accel.h. + + If unsure, say N. + + To compile this driver as modules, choose M here: the module for + the M1 family will be called ane, and the module for the M2 family + will be called ane_t6021. diff --git a/drivers/accel/ane/Makefile b/drivers/accel/ane/Makefile new file mode 100644 index 0000000000000..c0ad4a43bc0c3 --- /dev/null +++ b/drivers/accel/ane/Makefile @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: GPL-2.0-only + +obj-$(CONFIG_DRM_ACCEL_ANE) += ane.o ane_t6021.o + +ane-y := \ + ane_drv.o \ + ane_tm.o \ + ane_dart.o \ + ane_boost.o + +ane_t6021-y := \ + ane_t6021_rtclient_main.o \ + ane_t6021_fwload.o \ + ane_t6021_boot.o diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h new file mode 100644 index 0000000000000..10fee2864728c --- /dev/null +++ b/drivers/accel/ane/ane.h @@ -0,0 +1,160 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* Copyright 2022 Eileen Yoon */ + +#ifndef __ANE_H__ +#define __ANE_H__ + +#include +#include +#include +#include +#include + +#include +#include + +#include + +struct ane_device { + struct drm_device drm; + struct device *dev; + + struct device **pd_dev; + struct device_link **pd_link; + int pd_count; + + void __iomem *engine; + + /* The ane SET block (m1n1 ANE.ps_map): pmgr power-state words for + * this engine, mapped at probe on every SoC. Read-only, always: + * pmgr reads give recovery its ACTUAL evidence, while direct SET + * writes are firmware-locked and external-abort the SoC (T6001 + * netconsole-named 2026-09-16; T8103 same mechanism). + */ + phys_addr_t ps_base; + void __iomem *ps; + + struct drm_mm mm; + struct iommu_domain *domain; + unsigned long shift; + struct ane_dart { + void __iomem *regs; + int irq; + u32 sid; + bool masked; + } darts[3]; + int dart_count; + + int irq; + struct mutex iommu_lock; + struct mutex engine_lock; + struct list_head bo_list; + + /* + * Wedge-preserved BO ranges, tied to their still-inserted drm_mm + * nodes (see ane_reclaim_preserved). Registered under engine_lock. + */ + struct list_head preserved_list; + bool removed; + + /* + * Set under engine_lock once a task manager timeout leaves the queue + * state unknown and DMA possibly still active. A wedged engine refuses + * new work while recovery (ane_tm_recover) power-cycles it; the + * preserve-until-reboot behaviour applies only when that reset fails. + */ + atomic_t wedged; + + /* + * Set under engine_lock for the duration of a recovery power cycle, + * so runtime suspend may gate an engine that the reset itself is + * quiescing. + */ + bool recovering; + + /* + * TM_STATUS sampled right after the first tm_enable at probe: the + * engine's fresh, idle-state signature. Recovery accepts a reset + * whose post-cycle status matches it, since the register reset + * value is not documented. + */ + u32 tm_status_fresh; + bool tm_status_known; + + /* + * SoC descriptor fact: the set0/base islands hold the tm/tq + * register file in retention through any genpd power cycle + * (T6001 bisect evidence 2026-09-16: TQ_EN still reads 0x3000 + * after a 2 s gate), so recovery must drain retained task-manager + * state itself instead of expecting a power-on reset to clear it. + * False on T8103, where the cycle is a full POR of the file. + */ + bool tm_retention; + + /* + * Engine-busy CPU cluster boost (ane_boost.c): min-frequency QoS on + * every cpufreq policy while a submit runs and until boost_idle_ms + * after the last one completes: on T8103 bandwidth-bound programs + * run ~2x slower while schedutil parks the idle clusters low. + */ + struct ane_boost { + struct mutex lock; + struct delayed_work off; + struct freq_qos_request *legs; + int nlegs; + int held; + unsigned long last_end; + bool busy; + bool on; + } boost; +}; + +struct ane_request { + int qid; + u32 nid; + u32 td_size; + u32 td_count; + u32 btsp_iova; + u32 bar[ANE_TILE_COUNT]; +}; + +/* + * Drop the wedge pin (module refcount) without requiring a successful + * recovery. Used by ane_drm_postclose so a wedged engine cannot leave + * the module un-unloadable after a clean session close. Recovery stays + * safe to call afterwards; if it returns error, the postclose path has + * already unlocked the module count so the operator can swap the ko. + */ +void ane_wedge_clear(struct ane_device *ane); + +/* + * Reclaim wedge-preserved BO ranges (unmap, release nodes and pages). + * Only legal once DMA is provably quiescent: after a successful + * recovery power cycle, or at driver remove. Callers hold engine_lock. + */ +void ane_reclaim_preserved(struct ane_device *ane); + +int ane_boost_init(struct ane_device *ane); +void ane_boost_exit(struct ane_device *ane); +void ane_boost_begin(struct ane_device *ane); +void ane_boost_end(struct ane_device *ane); + +#define ANE_DART_MAX 3 +#define ANE_DART_SCRATCH_MAX 16 + +struct ane_dart_scratch { + u64 iova; + struct page *page; + struct drm_mm_node *node; +}; + +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); +void ane_dart_release_scratch(struct ane_device *ane, + struct ane_dart_scratch *scratch, int pages); + +#endif /* __ANE_H__ */ diff --git a/drivers/accel/ane/ane_boost.c b/drivers/accel/ane/ane_boost.c new file mode 100644 index 0000000000000..a13d706f4bc3c --- /dev/null +++ b/drivers/accel/ane/ane_boost.c @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Engine-busy CPU cluster boost. + * + * Bandwidth-bound programs run at a speed set by the CPU cluster + * p-states. Measured on jwm1 (T8103, 2026-09-25, ane-linux-experiments + * receipt jwm1-ane-dvfs-boost): with a mostly-sleeping submitter at + * normal priority, 75 of 489 Qwen decode steps take 100-175 ms instead + * of 70, every program in a slow step ~2x its normal wall, the + * submitter's CPU time and run delay unchanged; both clusters pinned + * at their top p-state (performance governor, or SCHED_FIFO for the + * submitter, which schedutil boosts the same way) -> 0 of 489. The + * whole-encoder Parakeet program (140 ms) moves too once the QoS lapses + * mid-submit: timed from submit start, the hold dropped 100 ms into + * every encoder run, median 171 ms (140-238); held to completion, 138.0 + * (137.7-138.7), jwm1 2026-09-25. The likely + * mechanism is the second p-state field apple-soc-cpufreq writes with + * the cluster p-state on T8103 only (DVFS_CMD PS2, has_ps2); the + * memory-controller tuning its author named as unimplemented is still + * absent from the tree. Whatever the field drives, the cure is the + * cluster p-state, which cpufreq lets a driver request. + * + * So hold a min-frequency QoS at the top of every cpufreq policy while a + * submit runs, and drop it boost_idle_ms after the last one completes. + * The QoS goes through cpufreq's own constraint object, so it composes + * with any governor and never touches the DVFS registers. + */ +#include +#include +#include +#include +#include +#include + +#include "ane.h" + +static unsigned int boost_idle_ms = 100; +module_param(boost_idle_ms, uint, 0644); +MODULE_PARM_DESC(boost_idle_ms, + "hold every CPU cluster at its top p-state while a submit runs and this long after the last one completes (0 = off)"); + +/* Lock held. */ +static void ane_boost_set(struct ane_device *ane, bool on) +{ + struct ane_boost *b = &ane->boost; + int cpu, n = 0; + + if (on) { + for_each_possible_cpu(cpu) { + struct cpufreq_policy *policy = cpufreq_cpu_get(cpu); + int err; + + if (!policy) + continue; + if (cpu != cpumask_first(policy->related_cpus) || + n >= b->nlegs) { + cpufreq_cpu_put(policy); + continue; + } + err = freq_qos_add_request(&policy->constraints, + &b->legs[n], FREQ_QOS_MIN, + policy->cpuinfo.max_freq); + cpufreq_cpu_put(policy); + if (err >= 0) + n++; + } + b->held = n; + } else { + for (n = 0; n < b->held; n++) + freq_qos_remove_request(&b->legs[n]); + b->held = 0; + } + b->on = on; +} + +static void ane_boost_off_work(struct work_struct *work) +{ + struct ane_device *ane = + container_of(work, struct ane_device, boost.off.work); + struct ane_boost *b = &ane->boost; + + mutex_lock(&b->lock); + /* A submit that began or ended after this expiry was armed keeps + * the boost on; its own completion re-arms the drop. + */ + if (b->on && !b->busy && + time_after_eq(jiffies, b->last_end + msecs_to_jiffies(boost_idle_ms))) + ane_boost_set(ane, false); + mutex_unlock(&b->lock); +} + +/* Engine lock held: submits never overlap, so busy is a flag. */ +void ane_boost_begin(struct ane_device *ane) +{ + struct ane_boost *b = &ane->boost; + + if (!b->legs || !boost_idle_ms) + return; + mutex_lock(&b->lock); + b->busy = true; + if (!b->on) + ane_boost_set(ane, true); + mutex_unlock(&b->lock); +} + +void ane_boost_end(struct ane_device *ane) +{ + struct ane_boost *b = &ane->boost; + + if (!b->legs) + return; + mutex_lock(&b->lock); + b->busy = false; + b->last_end = jiffies; + if (b->on) + mod_delayed_work(system_wq, &b->off, + msecs_to_jiffies(boost_idle_ms)); + mutex_unlock(&b->lock); +} + +int ane_boost_init(struct ane_device *ane) +{ + struct ane_boost *b = &ane->boost; + + mutex_init(&b->lock); + INIT_DELAYED_WORK(&b->off, ane_boost_off_work); + b->nlegs = num_possible_cpus(); + b->legs = kcalloc(b->nlegs, sizeof(*b->legs), GFP_KERNEL); + return b->legs ? 0 : -ENOMEM; +} + +void ane_boost_exit(struct ane_device *ane) +{ + struct ane_boost *b = &ane->boost; + + if (!b->legs) + return; + cancel_delayed_work_sync(&b->off); + mutex_lock(&b->lock); + if (b->on) + ane_boost_set(ane, false); + mutex_unlock(&b->lock); + kfree(b->legs); + b->legs = NULL; +} diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c new file mode 100644 index 0000000000000..aea8cd9eff182 --- /dev/null +++ b/drivers/accel/ane/ane_dart.c @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Joshua Warren */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ane.h" + +/* + * T8103 DART is the T8020 register block (apple_dart_hw_t8103 in + * drivers/iommu/apple-dart.c), pagesized 0x4000. Containment policy: + * during a job the apple-dart fault IRQ is masked so the latch survives + * for this driver to read, the completion poll checks that latch before + * every engine access (engine reads hang the SoC once a fault has + * landed), and a faulted IOVA is handed a throwaway page so the retried + * transaction completes and the engine drains. Mapping itself stays + * provider-owned; the page tables are never rewritten here. + */ +#define DART_STREAM_COMMAND 0x20 +#define DART_STREAM_COMMAND_BUSY BIT(2) +#define DART_STREAM_COMMAND_INVALIDATE BIT(20) +#define DART_STREAM_SELECT 0x34 +#define DART_ERROR 0x40 +#define DART_ERROR_FLAG BIT(31) +#define DART_ERROR_ADDR_LO 0x50 +#define DART_ERROR_ADDR_HI 0x54 +#define DART_STREAMS_ENABLE 0xfc +#define DART_TCR 0x100 +#define DART_TTBR 0x200 +#define DART_TTBR_COUNT 4 + +#define DART_TCR_SID(sid) (DART_TCR + ((sid) << 2)) +#define DART_TTBR_SID(sid, idx) \ + (DART_TTBR + ((((sid) * DART_TTBR_COUNT) + (idx)) << 2)) + +static bool dart_contain = true; +module_param(dart_contain, bool, 0444); +MODULE_PARM_DESC(dart_contain, + "Mask ANE DART fault IRQs during a job and restore the stream after a fault (default: on)"); + +static int ane_dart_invalidate(struct ane_device *ane, struct ane_dart *dart) +{ + void __iomem *regs = dart->regs; + u32 cmd; + int ret; + + if (dart->sid >= 32) + return -EINVAL; + writel(BIT(dart->sid), regs + DART_STREAM_SELECT); + writel(DART_STREAM_COMMAND_INVALIDATE, regs + DART_STREAM_COMMAND); + ret = readl_poll_timeout(regs + DART_STREAM_COMMAND, cmd, + !(cmd & DART_STREAM_COMMAND_BUSY), 1, 100); + if (ret) + dev_err(ane->dev, "DART sid %u TLB invalidate timed out\n", + dart->sid); + return ret; +} + +int ane_dart_init(struct ane_device *ane) +{ + struct device_node *np = ane->dev->of_node; + int count, i; + + ane->dart_count = 0; + if (!dart_contain) + return 0; + count = of_count_phandle_with_args(np, "iommus", "#iommu-cells"); + if (count < 0) + return 0; + for (i = 0; i < count && ane->dart_count < ANE_DART_MAX; i++) { + struct of_phandle_args args; + struct platform_device *pdev; + struct resource *res; + struct ane_dart *dart; + void __iomem *regs; + int irq; + + if (of_parse_phandle_with_args(np, "iommus", "#iommu-cells", + i, &args)) + break; + if (!of_device_is_compatible(args.np, "apple,t8103-dart")) { + of_node_put(args.np); + continue; + } + pdev = of_find_device_by_node(args.np); + if (!pdev) { + of_node_put(args.np); + continue; + } + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + irq = platform_get_irq(pdev, 0); + if (!res || irq < 0) { + put_device(&pdev->dev); + of_node_put(args.np); + continue; + } + regs = devm_ioremap(ane->dev, res->start, resource_size(res)); + if (!regs) { + put_device(&pdev->dev); + of_node_put(args.np); + return -ENOMEM; + } + dart = &ane->darts[ane->dart_count++]; + dart->regs = regs; + dart->irq = irq; + dart->sid = args.args_count ? args.args[0] : 0; + dart->masked = false; + dev_info(ane->dev, "DART containment: %pOFn sid %u irq %d\n", + args.np, dart->sid, irq); + put_device(&pdev->dev); + of_node_put(args.np); + } + dev_info(ane->dev, "DART containment armed: %d\n", ane->dart_count); + return 0; +} + +void ane_dart_mask(struct ane_device *ane) +{ + int i; + + for (i = 0; i < ane->dart_count; i++) { + struct ane_dart *dart = &ane->darts[i]; + + if (dart->masked) + continue; + disable_irq(dart->irq); + dart->masked = true; + } +} + +void ane_dart_unmask(struct ane_device *ane) +{ + int i; + + for (i = 0; i < ane->dart_count; i++) { + struct ane_dart *dart = &ane->darts[i]; + + if (!dart->masked) + continue; + enable_irq(dart->irq); + dart->masked = false; + } +} + +bool ane_dart_faulted(struct ane_device *ane, u64 *iova, u32 *status) +{ + int i; + + for (i = 0; i < ane->dart_count; i++) { + void __iomem *regs = ane->darts[i].regs; + u32 err = readl(regs + DART_ERROR); + + if (!(err & DART_ERROR_FLAG)) + continue; + if (status) + *status = err; + if (iova) + *iova = readl(regs + DART_ERROR_ADDR_LO) | + ((u64)readl(regs + DART_ERROR_ADDR_HI) << 32); + return true; + } + return false; +} + +/* + * 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 + * time is the wrong tool mid-job (register surgery while the faulting + * transaction is retried is what killed jwm1 twice). Instead the faulted + * IOVA is handed a throwaway DART page, so the retried transaction + * 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 dies in dart_init_pte's "we require an + * unmap first" WARN (m1-test-host 2026-09-25, iommu_map failed at 0x4000). 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): refuse and + * let the caller wedge, fail closed. + */ +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 page *page; + u64 iova; + int ret, i; + + page = alloc_page(GFP_KERNEL); + if (!page) + return -ENOMEM; + iova = fault_iova & ~((1ULL << ane->shift) - 1); + + node = kzalloc(sizeof(*node), GFP_KERNEL); + 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 = 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; + } + scratch[*pages].iova = iova; + scratch[*pages].page = page; + scratch[*pages].node = node; + (*pages)++; + for (i = 0; i < ane->dart_count; i++) + ane_dart_invalidate(ane, &ane->darts[i]); + return 0; +} + +void ane_dart_release_scratch(struct ane_device *ane, + struct ane_dart_scratch *scratch, int pages) +{ + int i, d; + + mutex_lock(&ane->iommu_lock); + for (i = 0; i < pages; i++) { + size_t unmapped; + + unmapped = iommu_unmap(ane->domain, scratch[i].iova, + BIT(ane->shift)); + if (unmapped != BIT(ane->shift)) + 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); + scratch[i].node = NULL; + __free_page(scratch[i].page); + scratch[i].page = NULL; + } + mutex_unlock(&ane->iommu_lock); + if (pages) + for (d = 0; d < ane->dart_count; d++) + ane_dart_invalidate(ane, &ane->darts[d]); +} diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c new file mode 100644 index 0000000000000..db03774c9e25a --- /dev/null +++ b/drivers/accel/ane/ane_drv.c @@ -0,0 +1,1234 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2022 Eileen Yoon */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "ane.h" +#include "ane_tm.h" + +/* + * BO mapping mode, runtime-switchable per device (/sys/module/ane/parameters/ + * map_mode) and read at BO-mmap/iommu-map time: + * bit 0 — mark DART descriptors IOMMU_CACHE (cacheable, inner-shareable) + * bit 1 — map the CPU vma cacheable instead of write-combine + * 0 = today's WC CPU vmas + NC descriptors; 3 = both cacheable (device + * accesses cohere with the CPU caches). Each axis is toggleable alone for + * attribution. + * + * Coherency evidence for mode 3, both SoCs: + * - T6001/t6001-test-host (apple,t6000-dart x3, APPLE_DART2 PTEs): (1) the ANE sits in + * the dma-coherent DART class every SoC DMA-API device uses on + * arm64/Asahi, where dma-iommu itself programs descriptors with + * IOMMU_CACHE; (2) eiln's pre-GEM driver (4566c89^) mapped BOs cacheable + * on the CPU while DMAing them through this same iommu_map() path for + * months with no maintenance; (3) empirically, an alternating-pattern + * 16-rep buffer-reuse battery over 6 programs in both directions is + * byte-identical WC+NC vs cached on every rep — stale cache lines would + * surface as the previous pattern's bytes. + * - T8103/m1-test-host (apple,t8103-dart x3, APPLE_DART1 PTEs): the DART1 PTE + * format has no cacheability field (io-pgtable-dart.c dart_prot_to_pte), + * so bit 0 is a structural no-op there and the lever is the cached CPU + * vma alone. eiln's pre-GEM precedent ran exactly that on M1 for months. + * The same reuse battery is byte-identical (14/14) and the certified + * Parakeet E2E pins hold bit-for-bit with ane_exec 2561.2 -> 2402.0 ms. + * + * Default 3 (cached both sides). 0 is the documented rollback: runtime via + * /sys/module/ane/parameters/map_mode, or by loading the retained prior + * module (ane-96d5a88.ko on both hosts). + */ +static int map_mode = 3; +module_param(map_mode, int, 0644); +MODULE_PARM_DESC(map_mode, + "BO mapping: bit0=IOMMU_CACHE DART descriptors, bit1=cacheable CPU vmas (default 3 = cached; 0 = writecombine + non-cacheable rollback)"); + +#define CMD_BUF_BDX 0 +#define KRN_BUF_BDX 1 + +struct ane_bo { + struct drm_gem_object base; + struct list_head node; + struct drm_mm_node *mm; + u32 npages; + struct page **pages; + dma_addr_t iova; +}; + +#define to_bo(gem) (container_of(gem, struct ane_bo, base)) + +static struct ane_bo *bo_lookup(struct drm_file *file, u32 handle) +{ + struct drm_gem_object *gem = drm_gem_object_lookup(file, handle); + + if (!gem) + return NULL; + return to_bo(gem); +} + +/* + * Buffers are mapped and unmapped only through the kernel-owned IOMMU + * domain the device was attached to by its providers. apple-dart + * programs every DART in the device's "iommus" list (TTBRs, stream + * 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. + */ +static int ane_iommu_map_pages(struct ane_device *ane, struct ane_bo *bo) +{ + int err; + + lockdep_assert_held(&ane->engine_lock); + if (bo->mm) + return -EBUSY; + + bo->mm = kzalloc(sizeof(*bo->mm), GFP_KERNEL); + 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, + bo->npages << ane->shift, + 1UL << ane->shift, 0, 0); + if (err < 0) { + dev_err(ane->dev, "out of ANE space: %d\n", err); + goto unlock; + } + + bo->iova = bo->mm->start; + + /* map into ANE address space */ + for (u32 i = 0; i < bo->npages; i++) { + dma_addr_t iova = bo->iova + (i << ane->shift); + int prot = IOMMU_READ | IOMMU_WRITE; + bool healed = false; + int prot_cache = map_mode & 1; + +retry: + if (prot_cache) + prot |= IOMMU_CACHE; + err = iommu_map(ane->domain, iova, page_to_phys(bo->pages[i]), + 1UL << ane->shift, prot, GFP_KERNEL); + if (err < 0) { + dev_err(ane->dev, "iommu_map failed at 0x%llx", iova); + /* Every PTE inside a reserved drm_mm node must be + * ours-or-absent: scratch drains reserve before + * mapping and wedge-preserved nodes stay inserted. + * A VALID PTE in a just-reserved range is therefore + * a stray from a torn-down session or a lost + * unmap. Clear it once and retry instead of + * poisoning every later BO_INIT until reload + * (m1-test-host 2026-09-25: dart_init_pte -EEXIST at + * 0x4000 for the rest of the session). + */ + if (err == -EEXIST && !healed && + iommu_iova_to_phys(ane->domain, iova)) { + dev_warn(ane->dev, + "clearing stray DART PTE at 0x%llx (no node owns it)\n", + iova); + iommu_unmap(ane->domain, iova, + 1UL << ane->shift); + healed = true; + goto retry; + } + while (i-- > 0) { + size_t unmapped; + + unmapped = iommu_unmap(ane->domain, + bo->iova + + (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), + unmapped); + } + drm_mm_remove_node(bo->mm); + bo->iova = 0; + break; + } + } + + mutex_unlock(&ane->iommu_lock); + + if (err < 0) { + kfree(bo->mm); + bo->mm = NULL; + return err; + } + + return 0; + +unlock: + mutex_unlock(&ane->iommu_lock); + kfree(bo->mm); + bo->mm = NULL; + return err; +} + +static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) +{ + struct drm_mm_node *mm = bo->mm; + + lockdep_assert_held(&ane->engine_lock); + + if (!mm) + return; + + 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); + 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; + mutex_unlock(&ane->iommu_lock); + + kfree(mm); +} + +/* + * 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 + * range's drm_mm node and the page array outlive it here, still linked + * into the allocator, until DMA is provably quiescent: recovery + * (ane_reclaim_preserved after the quiescing power cycle) or remove. + * The node stays reserved the whole time, so the IOVA can never be + * handed to a later BO_INIT while its PTEs are live. + */ +struct ane_preserved { + struct list_head list; + struct drm_mm_node *mm; + struct page **pages; + u32 npages; +}; + +static void ane_preserve_bo(struct ane_device *ane, struct ane_bo *bo) +{ + struct ane_preserved *p; + + p = kzalloc(sizeof(*p), GFP_KERNEL); + if (!p) { + /* Fail closed the old way: the node stays inserted and the + * pages leak until reboot - safe, just unreclaimable. + */ + dev_err(ane->dev, "wedged: preserve registry full, leaking\n"); + bo->mm = NULL; + bo->pages = NULL; + return; + } + p->mm = bo->mm; + p->pages = bo->pages; + p->npages = bo->npages; + list_add_tail(&p->list, &ane->preserved_list); + bo->mm = NULL; + bo->pages = NULL; +} + +void ane_reclaim_preserved(struct ane_device *ane) +{ + struct ane_preserved *p, *tmp; + unsigned long count = 0; + + lockdep_assert_held(&ane->engine_lock); + + list_for_each_entry_safe(p, tmp, &ane->preserved_list, list) { + u64 iova = p->mm->start; + + mutex_lock(&ane->iommu_lock); + for (u32 i = 0; i < p->npages; i++) { + size_t unmapped; + + unmapped = iommu_unmap(ane->domain, + iova + (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); + } + drm_mm_remove_node(p->mm); + mutex_unlock(&ane->iommu_lock); + + kfree(p->mm); + for (u32 i = 0; i < p->npages; i++) + put_page(p->pages[i]); + kfree(p->pages); + list_del(&p->list); + kfree(p); + count++; + } + if (count) + dev_info(ane->dev, + "reclaimed %lu wedge-preserved mapping(s) after quiesce\n", + count); +} + +static vm_fault_t ane_gem_vm_fault(struct vm_fault *vmf) +{ + struct vm_area_struct *vma = vmf->vma; + struct drm_gem_object *gem = vma->vm_private_data; + struct ane_bo *bo = to_bo(gem); + struct page *page; + pgoff_t offset; + + if (!bo->pages) + return VM_FAULT_SIGBUS; + + offset = (vmf->address - vma->vm_start) >> PAGE_SHIFT; + if (offset >= bo->npages) + return VM_FAULT_SIGBUS; + page = bo->pages[offset]; + + return vmf_insert_page(vma, vmf->address, page); +} + +static const struct vm_operations_struct drm_gem_ane_vm_ops = { + .open = drm_gem_vm_open, + .close = drm_gem_vm_close, + .fault = ane_gem_vm_fault, +}; + +/* + * Sole destruction path for buffer objects: every reference (handles, + * mmap vmas, lookups) funnels here. Nothing is reclaimed while the + * engine is wedged, since DMA may still be reading the IOVA. + */ +static void ane_gem_free_object(struct drm_gem_object *gem) +{ + struct ane_device *ane = gem->dev->dev_private; + struct ane_bo *bo = to_bo(gem); + + mutex_lock(&ane->engine_lock); + if (bo->mm) { + if (atomic_read(&ane->wedged)) { + /* 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 is what turned + * into dart_init_pte -EEXIST WARNs on m1-test-host). + */ + dev_err(ane->dev, "wedged: preserving bo mapping\n"); + list_del_init(&bo->node); + ane_preserve_bo(ane, bo); + } else { + ane_iommu_unmap_pages(ane, bo); + } + } + mutex_unlock(&ane->engine_lock); + + if (bo->pages) { + drm_gem_put_pages(gem, bo->pages, true, true); + bo->pages = NULL; + } + drm_gem_object_release(gem); + kfree(bo); +} + +static const struct drm_gem_object_funcs ane_gem_object_funcs = { + .free = ane_gem_free_object, + .vm_ops = &drm_gem_ane_vm_ops, +}; + +static int ane_bo_init(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct ane_device *ane = drm->dev_private; + struct drm_ane_bo_init *args = data; + struct drm_gem_object *gem; + struct ane_bo *bo; + int err; + + if (args->pad || !args->size) + return -EINVAL; + + bo = kzalloc(sizeof(struct ane_bo), GFP_KERNEL); + if (!bo) + return -ENOMEM; + INIT_LIST_HEAD(&bo->node); + + gem = &bo->base; + gem->funcs = &ane_gem_object_funcs; + err = drm_gem_object_init(drm, gem, round_up(args->size, PAGE_SIZE)); + if (err < 0) { + drm_gem_private_object_fini(gem); + goto free; + } + + err = drm_gem_create_mmap_offset(gem); + if (err < 0) + goto put; + + args->offset = drm_vma_node_offset_addr(&gem->vma_node); + + bo->npages = gem->size >> PAGE_SHIFT; + bo->pages = drm_gem_get_pages(gem); + if (IS_ERR(bo->pages)) { + err = PTR_ERR(bo->pages); + bo->pages = NULL; + goto put; + } + + mutex_lock(&ane->engine_lock); + if (ane->removed) { + err = -ENODEV; + goto unlock_put; + } + if (atomic_read(&ane->wedged)) { + dev_err_ratelimited(ane->dev, "wedged: refusing bo init\n"); + err = -ENODEV; + goto unlock_put; + } + + err = ane_iommu_map_pages(ane, bo); + if (err < 0) + goto unlock_put; + list_add_tail(&bo->node, &ane->bo_list); + + err = drm_gem_handle_create(file, gem, &args->handle); + mutex_unlock(&ane->engine_lock); + drm_gem_object_put(gem); /* handle (or error path) owns it now */ + return err; + +unlock_put: + mutex_unlock(&ane->engine_lock); +put: + drm_gem_object_put(gem); /* routes through ane_gem_free_object() */ + return err; +free: + kfree(bo); + return err; +} + +static int ane_bo_free(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct ane_device *ane = drm->dev_private; + struct drm_ane_bo_free *args = data; + struct ane_bo *bo; + + if (args->pad) + return -EINVAL; + + mutex_lock(&ane->engine_lock); + if (ane->removed) { + mutex_unlock(&ane->engine_lock); + return -ENODEV; + } + if (atomic_read(&ane->wedged)) { + dev_err_ratelimited(ane->dev, "wedged: refusing bo free\n"); + mutex_unlock(&ane->engine_lock); + return -ENODEV; + } + + bo = bo_lookup(file, args->handle); + mutex_unlock(&ane->engine_lock); + if (!bo) + return -EINVAL; + + /* Keep reference drops outside engine_lock: the final put enters + * ane_gem_free_object(), which owns that lock while unmapping. + */ + drm_gem_handle_delete(file, args->handle); + drm_gem_object_put(&bo->base); + return 0; +} + +static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) +{ + struct ane_device *ane = drm->dev_private; + struct drm_ane_submit *args = data; + struct drm_gem_object *gem[ANE_TILE_COUNT] = { 0 }; + struct drm_gem_object *btsp = NULL; + struct ane_bo *bo; + struct ane_request req; + int err; + + memset(&req, 0, sizeof(req)); + + if (args->pad || !args->tsk_size || !args->td_count || + args->td_count > 0xffff || args->td_size < 4 || + args->td_size > 0x40000 || (args->td_size & 3) || + !args->handles[CMD_BUF_BDX] || args->handles[KRN_BUF_BDX] || + !args->btsp_handle) { + return -EINVAL; + } + + /* Fail closed: never queue work behind a wedged engine. */ + if (atomic_read(&ane->wedged)) { + dev_err_ratelimited(ane->dev, "wedged: refusing submit\n"); + return -ECANCELED; + } + + req.qid = 4; + req.nid = ANE_FIFO_NID; + req.td_size = args->td_size; + req.td_count = args->td_count; + + for (int bdx = 0; bdx < ANE_TILE_COUNT; bdx++) { + if (!args->handles[bdx]) + continue; + bo = bo_lookup(file, args->handles[bdx]); + if (!bo) { + err = -EINVAL; + goto put; + } + gem[bdx] = &bo->base; + if (!bo->iova || + ((bdx == CMD_BUF_BDX) && + (args->tsk_size >= (bo->npages << ane->shift)))) { + err = -EINVAL; + goto put; + } + req.bar[bdx] = lower_32_bits(bo->iova); + } + + /* + * The microcode and weights are packed @ 16 gran for bank aligned + * access. Since this isn't page aligned, we represent the two as one + * buffer and calculate the delimiter (where the weights would start). + */ + req.bar[KRN_BUF_BDX] = + req.bar[CMD_BUF_BDX] + round_up(args->tsk_size, ANE_CMD_GRAN); + + bo = bo_lookup(file, args->btsp_handle); + if (!bo) { + err = -EINVAL; + goto put; + } + btsp = &bo->base; + if (!bo->iova || args->td_size > bo->base.size) { + err = -EINVAL; + goto put; + } + req.btsp_iova = lower_32_bits(bo->iova); + + /* + * 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. + */ + mutex_lock(&ane->engine_lock); + if (ane->removed) { + err = -ENODEV; + goto unlock; + } + if (atomic_read(&ane->wedged)) { + dev_err_ratelimited(ane->dev, "wedged: refusing submit\n"); + err = -ECANCELED; + goto unlock; + } + + err = ane_tm_enqueue(ane, &req); + if (err < 0) + goto unlock; + + ane_boost_begin(ane); + err = ane_tm_execute(ane, &req); + ane_boost_end(ane); + +unlock: + mutex_unlock(&ane->engine_lock); +put: + drm_gem_object_put(btsp); + for (int bdx = 0; bdx < ANE_TILE_COUNT; bdx++) { + if (gem[bdx]) + drm_gem_object_put(gem[bdx]); + } + return err; +} + +static const struct drm_ioctl_desc ane_drm_ioctls[] = { + DRM_IOCTL_DEF_DRV(ANE_BO_INIT, ane_bo_init, 0), + DRM_IOCTL_DEF_DRV(ANE_BO_FREE, ane_bo_free, 0), + DRM_IOCTL_DEF_DRV(ANE_SUBMIT, ane_submit, 0), +}; + +static ssize_t wedged_show(struct device *dev, struct device_attribute *attr, + char *buf) +{ + struct ane_device *ane = dev_get_drvdata(dev); + + return sysfs_emit(buf, "%d\n", atomic_read(&ane->wedged)); +} +static DEVICE_ATTR_RO(wedged); + +/* Operator retry for a wedge whose automatic recovery failed: one more + * bounded power-cycle attempt. No-op when not wedged. + */ +static ssize_t reset_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + struct ane_device *ane = dev_get_drvdata(dev); + int err = 0; + + mutex_lock(&ane->engine_lock); + if (!ane->removed) + err = ane_tm_recover(ane); + mutex_unlock(&ane->engine_lock); + if (err) + return err; + return count; +} +static DEVICE_ATTR_WO(reset); + +static struct attribute *ane_dev_attrs[] = { + &dev_attr_wedged.attr, + &dev_attr_reset.attr, + NULL, +}; +ATTRIBUTE_GROUPS(ane_dev); + +static int ane_drm_open(struct drm_device *drm, struct drm_file *file) +{ + struct ane_device *ane = drm->dev_private; + int err; + + /* Bring up power while the file context is created. A failed + * resume propagates; nothing is released that was not acquired. + */ + err = pm_runtime_resume_and_get(ane->dev); + if (err < 0) + return err; + + pm_runtime_put(ane->dev); + return 0; +} + +/* + * Per-session teardown: every file context open is a fresh boundary. + * Anything the previous session left on the device (wedged flag, tm + * completion counters, in-flight recovery state) belongs to that + * session and must not survive into the next one. + * + * drm_gem_release runs before us and has dropped every handle this + * file held. BOs leaked by `ane_gem_free_object under wedge` stay on + * ane->bo_list until module teardown (their backing `drm_gem_object`s + * are already gone, and touching them here would be use-after-free). + * We do not try to drain them; we only clear the session-leaving + * state (wedged + tm counters + recovering flag) so the next opener + * sees a clean device. The orphan BOs remain inert: they are not in + * any drm_file's handle table. + */ +static void ane_drm_postclose(struct drm_device *drm, struct drm_file *file) +{ + struct ane_device *ane = drm->dev_private; + + mutex_lock(&ane->engine_lock); + if (ane->removed) { + mutex_unlock(&ane->engine_lock); + return; + } + + /* Drop the wedge pin first: a wedged engine that cannot be + * recovered in software must NOT keep the module pinned, or the + * operator cannot unload the ko for an updated build without a + * reboot. ane_wedge_clear releases both the wedged flag and the + * module_refcount; ane_tm_recover then attempts a power-cycle + * recovery (succeeds only if the engine is actually idle-able). + */ + ane_wedge_clear(ane); + ane_tm_recover(ane); + + mutex_unlock(&ane->engine_lock); +} + +/* + * The driver only owns three ioctls (ANE_BO_INIT, ANE_BO_FREE, + * ANE_SUBMIT). Anything outside that table would otherwise fall through + * the standard drm_ioctl path to legacy primary-node handlers that + * dereference drm_device.unique, which an accel node never sets. Reject + * such callers explicitly so they fail with -ENOTTY instead of oopsing. + * + * The accel pattern uses ane_drm_ioctls[] via drm_ioctl() (legacy pattern + * from before DRM_ACCEL_FOPS landed drm_ioctl defaults), so this is a + * belt-and-suspenders gate on top of the existing ioctls table. + */ +static long ane_drm_unlocked_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + struct drm_file *filp = file->private_data; + struct drm_device *drm = filp->minor->dev; + struct ane_device *ane = drm->dev_private; + long err; + + /* Reject anything outside the drm type ('d') namespace outright, and + * core ioctls that would read a DRM master the accel node does not + * have (GET_UNIQUE, GET_MAP, ... dereference NULL); clients need + * only VERSION from the core set. + * + * _IOC_TYPEMASK is the low 8 bits, which encode the *nr*, not the + * *type*. The type byte lives at offset _IOC_TYPESHIFT (8). Use + * _IOC_TYPE(cmd) to extract the right field; misuse here returns + * -ENOTTY for every legitimate ane_ioctl, which is exactly the + * regression committed and reverted in the lifecycle-reset series. + */ + if (_IOC_TYPE(cmd) != DRM_IOCTL_BASE || + (_IOC_NR(cmd) < DRM_COMMAND_BASE && + _IOC_NR(cmd) != _IOC_NR(DRM_IOCTL_VERSION)) || + _IOC_NR(cmd) >= DRM_COMMAND_END) + return -ENOTTY; + + err = pm_runtime_resume_and_get(ane->dev); + if (err < 0) + return err; + + err = drm_ioctl(file, cmd, arg); + + pm_runtime_put(ane->dev); + + return err; +} + +static int ane_drm_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct drm_gem_object *gem; + struct ane_bo *bo; + int err; + + err = drm_gem_mmap(file, vma); + if (err < 0) + return err; + + /* + * Set vm_pgoff (used as a fake buffer offset by DRM) to 0 and map the + * whole buffer from the start. + */ + vma->vm_pgoff = 0; + gem = vma->vm_private_data; + bo = to_bo(gem); + + if (vma_pages(vma) == 0) + return -ENXIO; + + /* + * Cacheable CPU mapping when bit 1 of map_mode is set, paired with + * IOMMU_CACHE DART descriptors: device accesses cohere with the CPU + * caches and read-back stops paying uncached-mode DRAM latency. + * Default (bit clear) keeps the write-combine mapping. VM_IO stays + * set either way (no struct-page identity is promised). + */ + vm_flags_mod(vma, VM_IO | VM_DONTEXPAND | VM_DONTDUMP, VM_PFNMAP); + + if (map_mode & 2) + vma->vm_page_prot = + pgprot_decrypted(vm_get_page_prot(vma->vm_flags)); + else { + vma->vm_page_prot = + pgprot_writecombine(vm_get_page_prot(vma->vm_flags)); + vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot); + } + + return vm_map_pages(vma, bo->pages, bo->npages); +} + +static const struct file_operations ane_drm_fops = { + .owner = THIS_MODULE, + .fop_flags = FOP_UNSIGNED_OFFSET, + .open = accel_open, + .release = drm_release, + .unlocked_ioctl = ane_drm_unlocked_ioctl, + .compat_ioctl = drm_compat_ioctl, + .poll = drm_poll, + .read = drm_read, + .llseek = noop_llseek, + .mmap = ane_drm_mmap, +}; + +static const struct drm_driver ane_drm_driver = { + .driver_features = DRIVER_GEM | DRIVER_COMPUTE_ACCEL, + .open = ane_drm_open, + .postclose = ane_drm_postclose, + .ioctls = ane_drm_ioctls, + .num_ioctls = ARRAY_SIZE(ane_drm_ioctls), + .fops = &ane_drm_fops, + .major = ANE_ABI_MAJOR, + .name = "ane", + .desc = "Apple Neural Engine driver", +}; + +static int ane_iommu_domain_init(struct ane_device *ane) +{ + u64 min_iova, limit; + + struct iommu_domain *domain = iommu_get_domain_for_dev(ane->dev); + + if (!domain) + return -EPROBE_DEFER; + + if (!(domain->pgsize_bitmap & PAGE_SIZE) || + !domain->geometry.force_aperture) + return -EINVAL; + min_iova = max_t(u64, domain->geometry.aperture_start, PAGE_SIZE); + limit = round_down(min_t(u64, domain->geometry.aperture_end, U32_MAX) + 1, + PAGE_SIZE); + if (min_iova >= limit) + return -EINVAL; + min_iova = round_up(min_iova, PAGE_SIZE); + if (min_iova >= limit) + return -EINVAL; + ane->domain = domain; + ane->shift = PAGE_SHIFT; + drm_mm_init(&ane->mm, min_iova, limit - min_iova); + + return 0; +} + +/* + * The DART page table belongs to the IOMMU domain, which outlives this + * module: a mapping a previous instance never unmapped (a wedge preserves + * them) survives a reload, and the first BO_INIT onto it fails with + * -EEXIST. Clear every mapping inside the still-empty allocator range. + * The unmap flushes the DART TLBs, so this runs only after runtime + * resume has powered the engine and its DARTs, and before registration + * lets a client map anything. + */ +static void ane_iommu_purge_stale(struct ane_device *ane) +{ + struct drm_mm_node *hole; + u64 start, end, iova; + unsigned long stale = 0; + + drm_mm_for_each_hole(hole, &ane->mm, start, end) { + for (iova = start; iova < end; iova += 1UL << ane->shift) { + if (!iommu_iova_to_phys(ane->domain, iova)) + continue; + iommu_unmap(ane->domain, iova, 1UL << ane->shift); + stale++; + } + } + if (stale) + dev_warn(ane->dev, + "cleared %lu stale DART mappings from a previous instance\n", + stale); +} + +static void ane_detach_genpd(struct ane_device *ane) +{ + if (ane->pd_count <= 1) + return; + + for (int i = ane->pd_count - 1; i >= 0; i--) { + if (ane->pd_link[i]) + device_link_del(ane->pd_link[i]); + if (!IS_ERR_OR_NULL(ane->pd_dev[i])) + dev_pm_domain_detach(ane->pd_dev[i], true); + } +} + +static int ane_attach_genpd(struct ane_device *ane) +{ + struct device *dev = ane->dev; + + ane->pd_count = of_count_phandle_with_args( + dev->of_node, "power-domains", "#power-domain-cells"); + if (ane->pd_count < 1) + return ane->pd_count < 0 ? ane->pd_count : -EINVAL; + if (ane->pd_count == 1) + return dev->pm_domain ? 0 : -EPROBE_DEFER; + + ane->pd_dev = devm_kcalloc(dev, ane->pd_count, sizeof(*ane->pd_dev), + GFP_KERNEL); + if (!ane->pd_dev) + return -ENOMEM; + + ane->pd_link = devm_kcalloc(dev, ane->pd_count, sizeof(*ane->pd_link), + GFP_KERNEL); + if (!ane->pd_link) + return -ENOMEM; + + for (int i = 0; i < ane->pd_count; i++) { + ane->pd_dev[i] = dev_pm_domain_attach_by_id(dev, i); + if (IS_ERR(ane->pd_dev[i])) { + ane_detach_genpd(ane); + return PTR_ERR(ane->pd_dev[i]); + } + + ane->pd_link[i] = + device_link_add(dev, ane->pd_dev[i], + DL_FLAG_STATELESS | DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE); + if (!ane->pd_link[i]) { + ane_detach_genpd(ane); + return -EINVAL; + } + } + + return 0; +} + +/* + * Per-SoC support descriptor, one per Linux `compatible`. + * + * Everything the probe needs except the SET block is derived from the + * device tree by design: DART topology from "iommus", power wiring from + * "power-domains", the engine window from "reg", the IRQ by name. Board + * facts belong in the overlay, not in compiled constants. The SET block + * is the one exception: the live overlays carry no range for it, so it + * is compiled in per SoC — and only from a source that has proven the + * address on hardware (m1n1 proxyclient ANE.ps_map, then a bound device). + * A guessed SET base is not a bug but a brick: direct writes to the + * block external-abort the SoC (T6001 named by netconsole 2026-09-16, + * PS_SET0 down at 0x28e08c000; T8103 same mechanism at 0x23b70c000), + * which is why a SoC without proven constants must refuse to bind + * instead of carrying a guess. + * + * Qualification tiers: + * ANE_QUALIFIED — execution proven on this silicon; binds normally. + * ANE_RECOGNIZED — constants present, never run on hardware; binds + * only with ane.allow_unqualified=1, loudly. + * ANE_UNSUPPORTED — no proven constants; refuses and names the data + * needed to advance the port. + */ +enum ane_qual { + ANE_QUALIFIED, + ANE_RECOGNIZED, + ANE_UNSUPPORTED, +}; + +struct ane_soc { + phys_addr_t ps_base; + enum ane_qual qual; + /* True when the tm/tq register file survives a genpd cycle in + * retention and recovery must drain it (see ane_tm_drain_retained). + */ + bool tm_retention; +}; + +static bool allow_unqualified; +module_param(allow_unqualified, bool, 0444); +MODULE_PARM_DESC(allow_unqualified, + "Bind recognized-but-unproven ANE SoCs (unverified SET base: external-abort risk)"); + +static const struct ane_soc ane_soc_t8103 = { + /* M1 (m1-test-host). SET block mapped read-only for the recovery ACTUAL + * log and the powered-on guard. Execution proven in the fleet. + */ + .ps_base = 0x23b70c000ULL, + .qual = ANE_QUALIFIED, +}; + +static const struct ane_soc ane_soc_t6000 = { + /* M1 Pro, M1 Max and M1 Ultra die 0 share this compatible and SET base + * (proven on T6001/t6001-test-host); M1 Pro and M1 Ultra are untested. + */ + .ps_base = 0x28e08c000ULL, + .qual = ANE_QUALIFIED, + .tm_retention = true, +}; + +static const struct ane_soc ane_soc_t6020 = { + /* M2 Pro (t6020). Community device-tree captures exist, but the + * SET base is unproven and the H14 compiler backend is unqualified: + * no constants may enter here yet. + */ + .ps_base = 0, + .qual = ANE_UNSUPPORTED, +}; + +static const struct ane_soc ane_soc_t6021 = { + /* M2 Max (T6021, t6021-test-host). SET window 0x8e08c000 = pmgr base + * 0x8e080000 + 0xc000, present in ane0's own reg on macOS captures + * of both 26.6.2 and 27.0 (2026-09-18, 11/11 derivation-input + * checks each, zero delta); the Linux translation reuses the pmgr + * high bits proven on T6000/T6020 rows (low-32 match) -> + * 0x28e08c000. Recognized, not qualified: constants complete, but + * no Linux execution yet, and the t6021 pwrstate word layout + * (which of set0/base/set1..4 sits at which offset — macOS-side + * capture cannot see it) is unverified; the first probe resume + * logs the ACTUAL nibbles through this window as the Linux-side + * probe (receipt 2026-09-18-t6021-driver-entry-prepared.md). + * Promotion to ANE_QUALIFIED needs an exact run on this silicon. + */ + .ps_base = 0x28e08c000ULL, + .qual = ANE_RECOGNIZED, +}; + +static const struct of_device_id ane_of_match[] = { + { .compatible = "apple,t8103-ane", .data = &ane_soc_t8103 }, + { .compatible = "apple,t6000-ane", .data = &ane_soc_t6000 }, + { .compatible = "apple,t6020-ane", .data = &ane_soc_t6020 }, + { .compatible = "apple,t6021-ane", .data = &ane_soc_t6021 }, + {} +}; + +MODULE_DEVICE_TABLE(of, ane_of_match); + +static int ane_platform_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + const struct of_device_id *id = of_match_device(ane_of_match, dev); + const struct ane_soc *soc = id->data; + struct ane_device *ane; + struct drm_device *drm; + int err; + + /* Tier gate before any power-domain, MMIO or IRQ interaction: an + * unqualified SoC must fail cleanly, never half-probe. + */ + if (soc->qual == ANE_UNSUPPORTED) { + dev_err(dev, + "%s: unsupported ANE: no proven SET-block base (a guessed base external-aborts the SoC); not binding. To advance this port, run the mlx-omarchy quick collector (scripts/collect_quick.py: captures ANE/DART/PMGR/AIC device-tree data, no driver needed) and submit the capture\n", + id->compatible); + return -ENODEV; + } + if (soc->qual == ANE_RECOGNIZED && !allow_unqualified) { + dev_err(dev, + "%s: recognized but unqualified: constants present, execution never proven on this silicon; not binding. Override with ane.allow_unqualified=1, or prove a run and report it\n", + id->compatible); + return -ENODEV; + } + if (soc->qual == ANE_RECOGNIZED) + dev_warn(dev, + "%s: UNQUALIFIED bind forced by allow_unqualified: no execution proven on this silicon — SET-block base and board topology unverified\n", + id->compatible); + + ane = devm_drm_dev_alloc(dev, &ane_drm_driver, struct ane_device, drm); + if (IS_ERR(ane)) + return PTR_ERR(ane); + + platform_set_drvdata(pdev, ane); + ane->dev = dev; + + drm = &ane->drm; + drm->dev_private = ane; + + atomic_set(&ane->wedged, 0); + ane->tm_retention = soc->tm_retention; + + /* Managed power first: genpd links hold the ANE/DART supplier + * topology awake before any register is touched. + */ + err = ane_attach_genpd(ane); + if (err < 0) { + dev_err(dev, "failed to attach power domains\n"); + return err; + } + + ane->irq = platform_get_irq_byname(pdev, "ane"); + if (ane->irq < 0) { + err = ane->irq; + goto detach_genpd; + } + /* Polled completion design: the engine IRQ is validated but never + * requested here. A DART fault IRQ stays owned by apple-dart. During + * a job this driver masks it, and on a fault restores that stream. + */ + + /* Mapping only; no register access happens while unpowered. */ + ane->engine = devm_platform_ioremap_resource_byname(pdev, "engine"); + if (IS_ERR(ane->engine)) { + err = PTR_ERR(ane->engine); + goto detach_genpd; + } + + /* m1n1 keys the SET block by ADT node name (ANE.ps_map); the live + * overlays carry no range for it, so the SoC descriptor picks the + * base (see the tier table above). Mapped read-only, always: + * recovery logs its ACTUAL nibbles beside every engine write and + * refuses engine MMIO unless the islands read powered on. Unmapped + * is tolerated: recovery then just skips the check. + */ + ane->ps_base = soc->ps_base; + if (ane->ps_base) + ane->ps = devm_ioremap(dev, ane->ps_base, 0x38); + + mutex_init(&ane->iommu_lock); + mutex_init(&ane->engine_lock); + INIT_LIST_HEAD(&ane->bo_list); + INIT_LIST_HEAD(&ane->preserved_list); + err = ane_boost_init(ane); + if (err < 0) + goto detach_genpd; + + /* + * Kernel-owned IOMMU domain. Defers until every "iommus" provider + * has attached. There is deliberately no fallback to direct DART + * programming for mappings: without providers this driver must not + * bind. Fault recovery only rewrites the TTBR and TCR the provider + * already installed. + */ + err = ane_iommu_domain_init(ane); + if (err < 0) + goto detach_genpd; + + /* + * Managed runtime PM from here on. This resume is what raises the + * ANE partition: genpd powers the domain when the device resumes + * (through the platform bus for one power-domain entry, through the + * supplier links for several), and .runtime_resume then does the + * first engine MMIO. Marking the device active up front skips that + * resume, and on T6001 the engine window external-aborts while its + * partition is gated. The reference is held until remove: the device + * stays powered for the whole lifetime, autosuspend stays disabled. + */ + pm_runtime_enable(dev); + err = pm_runtime_resume_and_get(dev); + if (err < 0) + goto disable_pm; + + ane_iommu_purge_stale(ane); + err = ane_dart_init(ane); + if (err < 0) + goto put_pm; + + err = drm_dev_register(drm, 0); + if (err < 0) + goto put_pm; + + dev_info(dev, "loaded ane\n"); + + return 0; + +put_pm: + pm_runtime_put_noidle(dev); +disable_pm: + pm_runtime_disable(dev); + drm_mm_takedown(&ane->mm); +detach_genpd: + ane_boost_exit(ane); + ane_detach_genpd(ane); + return err; +} + +static void ane_platform_remove(struct platform_device *pdev) +{ + struct ane_device *ane = platform_get_drvdata(pdev); + struct ane_bo *bo, *tmp; + + mutex_lock(&ane->engine_lock); + ane->removed = true; + drm_dev_unplug(&ane->drm); + + if (atomic_read(&ane->wedged)) { + dev_err(ane->dev, + "forced removal of a wedged device is unsafe; reboot required\n"); + mutex_unlock(&ane->engine_lock); + return; + } + + 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_boost_exit(ane); + ane_detach_genpd(ane); + + pm_runtime_disable(ane->dev); + pm_runtime_put_noidle(ane->dev); + mutex_unlock(&ane->engine_lock); +} + +static int __maybe_unused ane_runtime_suspend(struct device *dev) +{ + struct ane_device *ane = dev_get_drvdata(dev); + + /* Veto gating while the engine may be DMA-active: there is no + * documented abort/reset to establish quiescence first -- except + * when recovery is power-cycling a wedged engine to establish + * exactly that quiescence. + */ + if (atomic_read(&ane->wedged) && !ane->recovering) + return -EBUSY; + + return 0; +} + +static int __maybe_unused ane_runtime_resume(struct device *dev) +{ + struct ane_device *ane = dev_get_drvdata(dev); + bool first = !ane->tm_status_known; + + /* The only path that touches the engine while its partition comes + * up: probe's first resume and every later ungate land here. Every + * translation is owned by the IOMMU providers. + */ + if (first) { + /* Bisect order, each stage named before it runs: genpd + * raise is already complete when this callback runs; the + * SET window reads come first (pmgr class, always safe + * per T6001/T8103 bisect evidence), then the engine. A + * hard reset after the last off-box line names the + * killing access exactly (T6021 console bring-up). + */ + struct resource *eng = platform_get_resource_byname( + to_platform_device(dev), IORESOURCE_MEM, "engine"); + + dev_info(dev, + "ANE-resume: genpd raise complete; SET window probe next\n"); + ane_ps_act_probe(ane); + + dev_info(dev, + "ANE-resume: SET window probed; first engine access next (TM_TQ_EN tm+0x0c @ engine %pr + 0x2000c)\n", + eng); + } + + ane_tm_enable(ane, first); + + /* First enable is the engine's fresh signature; recovery compares + * its post-reset status against it. + */ + if (!ane->tm_status_known) { + dev_info(dev, "ANE-resume: enable writes survived; TM_STATUS read next\n"); + ane->tm_status_fresh = ane_tm_status(ane); + ane->tm_status_known = true; + /* Linux-side pwrstate probe: ACTUAL nibbles read through + * the SoC descriptor's SET window while the partition is + * raised. 0xffffff means the mapped window is the live + * pmgr SET block with every word on; anything else names + * the t6021 word layout to fix before promotion. + */ + dev_info(dev, "ANERD ps probe act=%#x\n", ane_ps_act(ane)); + } + + return 0; +} + +// clang-format off +static const struct dev_pm_ops ane_pm_ops = { + SET_RUNTIME_PM_OPS(ane_runtime_suspend, ane_runtime_resume, NULL) + SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume) +}; + +// clang-format on + +static struct platform_driver ane_platform_driver = { + .probe = ane_platform_probe, + .remove = ane_platform_remove, + .driver = { + .name = "ane", + .suppress_bind_attrs = true, + .dev_groups = ane_dev_groups, + .pm = pm_ptr(&ane_pm_ops), + .of_match_table = ane_of_match, + }, +}; + +module_platform_driver(ane_platform_driver); + +MODULE_AUTHOR("Eileen Yoon "); +MODULE_DESCRIPTION("Apple Neural Engine driver"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_validate.h b/drivers/accel/ane/ane_fw_validate.h new file mode 100644 index 0000000000000..00ef2982c67e4 --- /dev/null +++ b/drivers/accel/ane/ane_fw_validate.h @@ -0,0 +1,480 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * ane_fw_validate.h — pinned ANE firmware images, their validator, and + * iBoot's runtime patches. + * + * Single source of truth shared by the kernel loader + * (ane_t6021_fwload.c) and the offline regression + * (tools/h14_boot_regression.c). Strict EXACT-image assertions (no + * generic Mach-O parsing). + * + * The images are the macOS 13.5 (22G74) payloads that iBoot preloads on + * the stub every Omarchy install boots: selene for T6020/T6021/T6022 + * (byte-verified live at SEG0 on T6021, notebook 20260926T230146Z) and + * bia for T8112 (receipts/2026-10-01-t8112-ane). Both have 5 load + * commands (2 segments + LC_SYMTAB + LC_UUID + LC_UNIXTHREAD), entry 0. + * + * Userspace consumers typedef u8/u32/u64/size_t/bool and provide + * get_unaligned_le32/64, memcmp and memcpy (see that tool's source); + * kernel consumers get these from linux/types.h + linux/string.h. + * This header intentionally includes nothing. + */ +#ifndef __ANE_FW_VALIDATE_H__ +#define __ANE_FW_VALIDATE_H__ + +/* FWIM surface size = config+0x138 byte-count = 0x500000 (Main + * 2026-09-20, audit 751caa4, T6021). Covers the selene vmsize 0x4fc000 + * and the bia vmsize 0x4ec000; NOT derivable from the blob length. + */ +#define ANE_FW_BUF_SIZE 0x500000 +#define ANE_FW_ENTRY_PC 0x0 + +#define MH_MAGIC_64 0xfeedfacfU +#define MH_PRELOAD 5 +#define CPU_TYPE_ARM64 0x0100000cU +#define LC_SEGMENT_64 0x19 +#define LC_UNIXTHREAD 0x5 +#define ARM_THREAD_STATE64 6 + +#define ANE_FW_NCMDS 5 +#define ANE_FW_SIZEOF_CMDS 0x960 +#define ANE_FW_FLAGS 0x1 +#define ANE_FW_NSEGS 2 +#define ANE_FW_RTK_PATCHES 5 + +struct ane_fw_seg { + u64 vmaddr; + u64 vmsize; + u64 fileoff; + u64 filesize; + char name[17]; /* 16 + NUL */ +}; + +/* One pinned image. The patch fields are the payload's LC_SYMTAB + * addresses: the __rtk_patch records _rtk_stack_guard, RTK_soc, + * RTK_soc_revision, RTK_cpu_physical_address and + * RTK_cpu_wrapper_physical_address, then the type-1 + * __rtk_platform_asc_tunables_block. + */ +struct ane_fw_image { + const char *name; /* request_firmware() path */ + u8 sha256[32]; + u32 size; + struct ane_fw_seg segs[ANE_FW_NSEGS]; + u32 rtk_vm[ANE_FW_RTK_PATCHES]; + u32 tunables_vm; +}; + +static const struct ane_fw_image ane_fw_selene = { + .name = "apple/ane/t602x_ane0_fw_selene_rc4x.macho", + .sha256 = { + 0xa9, 0xc4, 0xb7, 0x71, 0x29, 0x4a, 0x6b, 0x11, + 0x56, 0x24, 0xd9, 0x48, 0x0a, 0x62, 0x48, 0xd0, + 0x89, 0x9a, 0x16, 0x81, 0xa5, 0x75, 0xe8, 0x65, + 0x07, 0x0b, 0x87, 0xa3, 0x24, 0x84, 0x27, 0xbc, + }, + .size = 0x4c5b28, + .segs = { + { 0x000000, 0x0c4000, 0x004000, 0x0c4000, "__TEXT" }, + { 0x0c4000, 0x438000, 0x0c8000, 0x3e8000, "__DATA" }, + }, + .rtk_vm = { 0xca848, 0xca9b3, 0xca9bf, 0xca9cb, 0xca9db }, + .tunables_vm = 0xdcd78, +}; + +static const struct ane_fw_image ane_fw_bia = { + .name = "apple/ane/h14_ane_fw_bia_j4xx.macho", + .sha256 = { + 0xaf, 0x58, 0x7d, 0xfa, 0x96, 0xb1, 0xe0, 0x1d, + 0x2b, 0x2e, 0x0f, 0x9f, 0x77, 0x6e, 0x5d, 0xbe, + 0xfe, 0xbb, 0x44, 0xc7, 0x96, 0x8b, 0x86, 0xff, + 0xf7, 0xd2, 0xb1, 0x9c, 0x4c, 0xbe, 0xf0, 0xdd, + }, + .size = 0x4b5b38, + .segs = { + { 0x000000, 0x0b4000, 0x004000, 0x0b4000, "__TEXT" }, + { 0x0b4000, 0x438000, 0x0b8000, 0x3e8000, "__DATA" }, + }, + .rtk_vm = { 0xba688, 0xba7f3, 0xba7ff, 0xba80b, 0xba81b }, + .tunables_vm = 0xccbb8, +}; + +/* Validate a candidate payload against image FW. Returns 0 on pass, + * else -1 with *reason set. actual_sha = caller-computed SHA-256 of + * blob. + */ +static inline int +ane_fw_validate_blob(const u8 *blob, size_t size, + const struct ane_fw_image *fw, const u8 actual_sha[32], + struct ane_fw_seg *segs_out, u64 *entry_out, + const char **reason) +{ + u32 magic, cputype, filetype, ncmds, sizeofcmds, flags; + u32 off, i, nsegs = 0; + u64 entry = (u64)~0ULL; + + if (size != fw->size) { + *reason = "size != pinned image"; + return -1; + } + if (memcmp(fw->sha256, actual_sha, 32) != 0) { + *reason = "sha256 != pinned payload hash"; + return -1; + } + + magic = get_unaligned_le32(blob + 0); + cputype = get_unaligned_le32(blob + 4); + filetype = get_unaligned_le32(blob + 12); + ncmds = get_unaligned_le32(blob + 16); + sizeofcmds = get_unaligned_le32(blob + 20); + flags = get_unaligned_le32(blob + 24); + + if (magic != MH_MAGIC_64) { + *reason = "magic"; + return -1; + } + if (cputype != CPU_TYPE_ARM64) { + *reason = "cputype"; + return -1; + } + if (filetype != MH_PRELOAD) { + *reason = "filetype != MH_PRELOAD"; + return -1; + } + if (ncmds != ANE_FW_NCMDS || sizeofcmds != ANE_FW_SIZEOF_CMDS || + flags != ANE_FW_FLAGS) { + *reason = "header fields != pinned image"; + return -1; + } + + off = 32; + for (i = 0; i < ncmds; i++) { + u32 cmd, cmdsize; + + if (off + 8 > 32 + sizeofcmds || off + 8 > size) { + *reason = "load command header out of bounds"; + return -1; + } + cmd = get_unaligned_le32(blob + off); + cmdsize = get_unaligned_le32(blob + off + 4); + if (cmdsize < 8 || off + cmdsize > 32 + sizeofcmds || + off + cmdsize > size) { + *reason = "cmdsize out of bounds"; + return -1; + } + + if (cmd == LC_SEGMENT_64) { + u64 vmaddr = get_unaligned_le64(blob + off + 24); + u64 vmsize = get_unaligned_le64(blob + off + 32); + u64 fileoff = get_unaligned_le64(blob + off + 40); + u64 filesize = get_unaligned_le64(blob + off + 48); + const char *sname = (const char *)blob + off + 8; + unsigned int k; + + if (fileoff > size || filesize > size - fileoff) { + *reason = "segment file range out of bounds"; + return -1; + } + if (filesize > vmsize) { + *reason = "filesize > vmsize"; + return -1; + } + for (k = 0; k < ANE_FW_NSEGS; k++) { + if (vmaddr == fw->segs[k].vmaddr && + vmsize == fw->segs[k].vmsize && + fileoff == fw->segs[k].fileoff && + filesize == fw->segs[k].filesize && + !memcmp(sname, fw->segs[k].name, 16)) { + if (segs_out) + segs_out[nsegs] = fw->segs[k]; + break; + } + } + if (k == ANE_FW_NSEGS) { + *reason = "segment != pinned layout"; + return -1; + } + nsegs++; + } else if (cmd == LC_UNIXTHREAD) { + u32 p = off + 8; + + /* thread commands: flavor u32, count u32 + * (count = number of 32-bit words in state) + */ + while (p + 8 <= off + cmdsize) { + u32 flavor = get_unaligned_le32(blob + p); + u32 count = get_unaligned_le32(blob + p + 4); + + if (count > (cmdsize - (p - off) - 8) / 4) { + *reason = "thread state count out of bounds"; + return -1; + } + if (flavor == ARM_THREAD_STATE64) { + /* 33 u64 registers; PC at index 32: + * requires count*4 >= 33*8 bytes + */ + if (count < 66 || + p + 8 + count * 4 > off + cmdsize) { + *reason = "thread state too small for pc"; + return -1; + } + entry = get_unaligned_le64(blob + p + 8 + + 32 * 8); + } + p += 8 + count * 4; + } + } + off += cmdsize; + } + + if (nsegs != ANE_FW_NSEGS) { + *reason = "segment count != 2"; + return -1; + } + if (entry != ANE_FW_ENTRY_PC) { + *reason = "entry pc != 0"; + return -1; + } + + if (segs_out) { + for (i = 0; i < ANE_FW_NSEGS; i++) + segs_out[i] = fw->segs[i]; + } + if (entry_out) + *entry_out = entry; + return 0; +} + +/* + * iBoot runtime patches. iBoot places the image at its Mach-O vm layout + * (TEXT vm 0, DATA vm segs[1].vmaddr) and then writes the fields below. + * The 17 pre-Linux T6021 captures (receipts/2026-10-01-t602x-independent) + * differ from the archive in these bytes only; only the stack guard + * changes between boots. A driver that runs its own copy writes them + * itself. + * + * Each __rtk_patch_* record is {u32 tag, u32 value length, value}. + */ +#define ANE_FW_DATA_BASE_VM 0x423c /* TEXT u64: IOVA of DATA (both images) */ +#define ANE_FW_TUNABLES_MAX 0x24 /* type-1 block capacity (header byte 2) */ + +/* + * iBoot's ASC tunables for the ANE (coprocessor id 4): one record list + * and the chip-revision keys of the entries that carry it, highest + * first. iBoot fills the firmware's type-1 block from the first entry + * whose key <= the chip revision: header {type 1, flags 3 (20-byte + * records), capacity 0x24, count, u32 key}, then {u32 offset, u64 mask, + * u64 value} per record (iBoot table offsets carry flag bit 30; the + * block does not). Source: iBootStage2 macOS 26.6.2 (25G83), LZFSE, not + * encrypted (receipts/2026-10-01-t8112-optin). The 13.5 iBoot2 that + * preloads the 13.5 image is encrypted; on T6021 its block (the + * captures) equals the 25G83 records exactly. + */ +struct ane_asc_tunable { + u32 off; + u64 mask; + u64 val; +}; + +struct ane_asc_tunables { + u8 keys[4]; + u8 nkeys; + u8 n; + struct ane_asc_tunable r[ANE_FW_TUNABLES_MAX]; +}; + +/* T6021, T6022: j414c/j416c/j180d/j475d 25G83, type-1 key 0x10 (the + * 0x150010 record) then type-3 key 0x10 (the rest), which is the T6021 + * capture block byte for byte (header key 0x10). 25G83 adds key 0x11; + * the capture (RTK_soc_revision 0x11, block key 0x10) shows 13.5 has + * none, so it is left out. + */ +static const struct ane_asc_tunables ane_t602x_asc_tunables = { + .keys = { 0x10, 0x01, 0x00 }, + .nkeys = 3, + .n = 24, + .r = { + { 0x150010, 0x000000000000003f, 0x0000000000000010 }, + { 0x051c08, 0x0000000010000000, 0x0000000010000000 }, + { 0x051c18, 0x0010000000000000, 0x0010000000000000 }, + { 0x140020, 0x0000000000f00000, 0x0000000000700000 }, + { 0x140120, 0x0000000000002eff, 0x00000000000002b1 }, + { 0x140130, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140138, 0x0000000000007fff, 0x0000000000000064 }, + { 0x140140, 0x0000000000003fff, 0x000000000000002f }, + { 0x140148, 0x0000000000007fff, 0x00000000000000c8 }, + { 0x140150, 0x0000000000003fff, 0x000000000000004f }, + { 0x140158, 0x0000000000007fff, 0x000000000000014e }, + { 0x140160, 0x0000000000003fff, 0x000000000000004f }, + { 0x140168, 0x0000000000007fff, 0x000000000000014e }, + { 0x140170, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140178, 0x0000000000007fff, 0x0000000000000064 }, + { 0x140180, 0x0000000000003fff, 0x0000000000000028 }, + { 0x140188, 0x0000000000007fff, 0x00000000000000a7 }, + { 0x140190, 0x0000000000003fff, 0x0000000000000028 }, + { 0x140198, 0x0000000000007fff, 0x00000000000000a7 }, + { 0x1401a0, 0x0000000000003fff, 0x000000000000004f }, + { 0x1401a8, 0x0000000000007fff, 0x000000000000014e }, + { 0x145010, 0x000000000008000c, 0x000000000000000c }, + { 0x14a008, 0x000000000ff0ffff, 0x0000000000002520 }, + { 0x14a010, 0x000000000ff0ffff, 0x0000000002002520 }, + }, +}; + +/* T6020: j414s/j416s 25G83, one type-1 entry, key 0x00. The offsets of + * T6021; 13 values differ. + */ +static const struct ane_asc_tunables ane_t6020_asc_tunables = { + .keys = { 0x00 }, + .nkeys = 1, + .n = 24, + .r = { + { 0x150010, 0x000000000000003f, 0x0000000000000010 }, + { 0x051c08, 0x0000000010000000, 0x0000000010000000 }, + { 0x051c18, 0x0010000000000000, 0x0010000000000000 }, + { 0x140020, 0x0000000000f00000, 0x0000000000700000 }, + { 0x140120, 0x0000000000002eff, 0x00000000000002b1 }, + { 0x140130, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140138, 0x0000000000007fff, 0x0000000000000064 }, + { 0x140140, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140148, 0x0000000000007fff, 0x0000000000000064 }, + { 0x140150, 0x0000000000003fff, 0x0000000000000020 }, + { 0x140158, 0x0000000000007fff, 0x0000000000000086 }, + { 0x140160, 0x0000000000003fff, 0x000000000000004f }, + { 0x140168, 0x0000000000007fff, 0x000000000000014e }, + { 0x140170, 0x0000000000003fff, 0x0000000000000008 }, + { 0x140178, 0x0000000000007fff, 0x0000000000000022 }, + { 0x140180, 0x0000000000003fff, 0x0000000000000008 }, + { 0x140188, 0x0000000000007fff, 0x0000000000000022 }, + { 0x140190, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140198, 0x0000000000007fff, 0x0000000000000064 }, + { 0x1401a0, 0x0000000000003fff, 0x0000000000000018 }, + { 0x1401a8, 0x0000000000007fff, 0x0000000000000064 }, + { 0x145010, 0x000000000008000c, 0x000000000000000c }, + { 0x14a008, 0x000000000ff0ffff, 0x0000000000002520 }, + { 0x14a010, 0x000000000ff0ffff, 0x0000000001002520 }, + }, +}; + +/* T8112: j413/j415/j473/j493 25G83, one type-1 table under keys 0x10 + * and 0x00, no type-3 entry. The T6021 offsets without 0x150010. + */ +static const struct ane_asc_tunables ane_t8112_asc_tunables = { + .keys = { 0x10, 0x00 }, + .nkeys = 2, + .n = 23, + .r = { + { 0x051c08, 0x0000000010000000, 0x0000000010000000 }, + { 0x051c18, 0x0010000000000000, 0x0010000000000000 }, + { 0x140020, 0x4000000000f80000, 0x4000000000780000 }, + { 0x140120, 0x0000000000002eff, 0x00000000000002b1 }, + { 0x140130, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140138, 0x0000000000007fff, 0x0000000000000064 }, + { 0x140140, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140148, 0x0000000000007fff, 0x0000000000000064 }, + { 0x140150, 0x0000000000003fff, 0x0000000000000020 }, + { 0x140158, 0x0000000000007fff, 0x0000000000000086 }, + { 0x140160, 0x0000000000003fff, 0x0000000000000028 }, + { 0x140168, 0x0000000000007fff, 0x00000000000000a7 }, + { 0x140170, 0x0000000000003fff, 0x0000000000000010 }, + { 0x140178, 0x0000000000007fff, 0x0000000000000043 }, + { 0x140180, 0x0000000000003fff, 0x0000000000000010 }, + { 0x140188, 0x0000000000007fff, 0x0000000000000043 }, + { 0x140190, 0x0000000000003fff, 0x0000000000000018 }, + { 0x140198, 0x0000000000007fff, 0x0000000000000064 }, + { 0x1401a0, 0x0000000000003fff, 0x0000000000000028 }, + { 0x1401a8, 0x0000000000007fff, 0x00000000000000a7 }, + { 0x145010, 0x000000000008000c, 0x000000000008000c }, + { 0x14a008, 0x000000000ff0ffff, 0x0000000000002520 }, + { 0x14a010, 0x000000000ff0ffff, 0x0000000003002520 }, + }, +}; + +/* T8112 RTK_soc_revision from its two eFuse words at 0x23d2c8060, as + * iBootStage2 25G83 j413 0x40270 (and j415/j473/j493) computes it: + * bits 2:0 = w0[29:27], bits 6:4 = {w1[0], w0[31:30]}. + */ +static inline u32 ane_t8112_fuse_revision(u32 w0, u32 w1) +{ + return ((w0 >> 27) & 7) | ((((w0 >> 30) | (w1 << 2)) & 7) << 4); +} + +struct ane_fw_boot_patch { + u64 exec_base; /* IOVA the ASC runs vm 0 at */ + u64 stack_guard; + u32 soc; + u32 soc_revision; + u64 cpu_pa; /* ASC core block, engine + 0x1000000 */ + u64 wrapper_pa; /* ASC wrapper, engine + 0x1400000 */ +}; + +static inline void ane_fw_put_le(u8 *p, u64 v, unsigned int n) +{ + while (n--) { + *p++ = (u8)v; + v >>= 8; + } +} + +/* Patch the staged image FW in place (vm-indexed, at least + * ANE_FW_BUF_SIZE bytes). Every precondition is checked before the first + * write, so a refusal leaves the image untouched. Returns 0, or -1 with + * *reason set. + */ +static inline int +ane_fw_apply_boot_patches(u8 *img, const struct ane_fw_image *fw, + const struct ane_asc_tunables *t, + const struct ane_fw_boot_patch *p, const char **reason) +{ + static const u8 tunables_unset[8] = { + 0x01, 0x03, ANE_FW_TUNABLES_MAX, 0x00, 0xff, 0xff, 0xff, 0xff }; + static const struct { u32 tag, len; } rec[ANE_FW_RTK_PATCHES] = { + { 0x53544b47, 8 }, /* _rtk_stack_guard */ + { 0x534f435f, 4 }, /* RTK_soc */ + { 0x534f4352, 4 }, /* RTK_soc_revision */ + { 0x43704164, 8 }, /* RTK_cpu_physical_address */ + { 0x57724164, 8 }, /* ..._wrapper_physical_address */ + }; + const u64 val[ANE_FW_RTK_PATCHES] = { + p->stack_guard, p->soc, p->soc_revision, p->cpu_pa, + p->wrapper_pa, + }; + u8 *blk = img + fw->tunables_vm; + unsigned int i, k; + + for (k = 0; k < t->nkeys && t->keys[k] > p->soc_revision; k++) + ; + if (k == t->nkeys || t->n > ANE_FW_TUNABLES_MAX) { + *reason = "no ASC tunables for this chip revision"; + return -1; + } + if (get_unaligned_le64(img + ANE_FW_DATA_BASE_VM)) { + *reason = "DATA base field is not the archive zero"; + return -1; + } + for (i = 0; i < ANE_FW_RTK_PATCHES; i++) { + if (get_unaligned_le32(img + fw->rtk_vm[i]) != rec[i].tag || + get_unaligned_le32(img + fw->rtk_vm[i] + 4) != rec[i].len) { + *reason = "__rtk_patch record != pinned image"; + return -1; + } + } + if (memcmp(blk, tunables_unset, 8)) { + *reason = "tunables block header != pinned image"; + return -1; + } + + ane_fw_put_le(img + ANE_FW_DATA_BASE_VM, + p->exec_base + fw->segs[1].vmaddr, 8); + for (i = 0; i < ANE_FW_RTK_PATCHES; i++) + ane_fw_put_le(img + fw->rtk_vm[i] + 8, val[i], rec[i].len); + blk[3] = t->n; + ane_fw_put_le(blk + 4, t->keys[k], 4); + for (i = 0; i < t->n; i++) { + ane_fw_put_le(blk + 8 + 20 * i, t->r[i].off, 4); + ane_fw_put_le(blk + 12 + 20 * i, t->r[i].mask, 8); + ane_fw_put_le(blk + 20 + 20 * i, t->r[i].val, 8); + } + return 0; +} +#endif /* __ANE_FW_VALIDATE_H__ */ diff --git a/drivers/accel/ane/ane_t6021.h b/drivers/accel/ane/ane_t6021.h new file mode 100644 index 0000000000000..5e0ecc6d471f7 --- /dev/null +++ b/drivers/accel/ane/ane_t6021.h @@ -0,0 +1,796 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* T6021 (H14 / J414c) Apple Neural Engine — skeleton constants and types. + * + * Every constant below is static-decode provenance, no device writes: + * - reg windows, IRQ, pmgr islands: ADT j414c (DeviceTree.j414cap.im4p, + * receipts/2026-09-18-t6021-engine-layout-mined §2), Linux translation + * +0x200000000 (proven class, pmgr low-32 match). + * - ASC cpu block (+0x1400000 h14g) + MBI transport (SCRATCH, channel + * table, +0x1844000 doorbell): K14 kext disasm, W4-fix receipt + * (initializeANESoCConfig h14g blocks + InitializeRTBuddy + + * doorbell setter 0x…95ebdd0); m1n1 ASCRegs = t8103 cross-ref only + * - RTKit MGMT protocol: Asahi rtkit.c semantics, u64 message halves as + * staged in omarchy-ane rtkit/h14_rtkit_hello.py (commit 6ad26b7). + * - RTBuddy endpoint table + doorbell word: K14 kext cfg table + * __DATA_CONST.__const+0x814e520 and HandleRTBuddyMessage + * (receipts/2026-09-18-h14-w2-protocol-decode §3). + * + * DT binding (driver + packaging/dt/t6021-ane.dts are the two halves): + * compatible = "apple,t6021-ane" (also "apple,t6020-ane", the + * T6022 die-0 "apple,t6022-ane" and "apple,t8112-ane": + * struct ane_t602x_soc). The T6021 values follow; T8112 + * (packaging/dt/t8112-ane.dts) has engine 0x26a000000, + * pmgr 0x23b700000+0x18000, set 0x23b724000+0x4000, + * IRQ 520, seven power states 0xc008..0xc038, and a + * fourth window "fuse" (0x23d2c8060+8, chip revision). + * reg/reg-names = "engine" (whole 32 MiB ADT range0, 0x284000000; + * the H13-style +0x1c04000 engine delta does not exist + * on this SoC — kext never computes it and first touch + * external-aborted, proven 2026-09-18), + * "pmgr" (0x28e080000+0x4034, pmgr1,t6021 island words), + * "set" (0x28e08c000+0x4000, SET window — read-only by + * repo rule: direct SET writes external-abort the SoC) + * interrupts = one AIC2 level-high interrupt named "ane" (raw 884; + * [INFERENCE W2 §3: the ANE MBI doorbell IRQ]. + * dart-ane0 carries raw 885, provider-owned, never + * fetched here) + * iommus = dart-ane0 streams (apple,t6020-dart/apple,t8110-dart + * nodes). The ADT dart-ane0 is one hardware block with a + * four-window quartet (0x85800000/85810000/85820000/ + * 85804000, each 0x4000); the installed overlay's + * three-node split (t6001-proven pattern) is kept. + * power-domains = eight, phase1 raise order (sys_mpm→td→base→set1..4, + * ane_cpu last): ane_sys_mpm@4000, ane_td@4008, + * ane_base@4010, ane_set1..4@4018-4030, ane_cpu@2e0. + * ane_td/ane_base were the W3 chain gap (six consumed, + * block access reset the machine); receipt + * 2026-09-19-h14-init-sequence-kext-trace §3. + */ + +#ifndef __ANE_T6021_H__ +#define __ANE_T6021_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ane_t6021_boot.h" + +/* reg windows (packaging/dt/t6021-ane.dts reg-names order) */ +enum { + ANE_T6021_REG_ENGINE, + ANE_T6021_REG_PMGR, + ANE_T6021_REG_SET, + ANE_T6021_REG_COUNT +}; + +/* pmgr ps-word fields (apple-pmgr-pwrstate layout). */ +#define ANE_PS_ON 0xf +#define ANE_PS_TARGET GENMASK(3, 0) +#define ANE_PS_ACTUAL GENMASK(7, 4) +#define ANE_PS_WAS_GATED GENMASK(9, 8) +#define ANE_PS_BUSY BIT(11) +#define ANE_PS_AUTO_ENABLE BIT(28) + +/* ANE-block-relative ASC/RTBuddy addresses. CPU block = ANE+0x1400000 + * for h14g (K14 initializeANESoCConfig h14g blocks 0x…961365c / + * 0x…9614084 build 0x1400044 with NO 0x200000 orr — the 0x1600044 + * phase-1 §2 quote is the h16g/h17/h18g variant block 0x…9613458; + * runtime h14g-shaped sites 0x…95d2968 write RUN there). CPU_STATUS + * +0x48 keeps the m1n1 ASCRegs +4 shape (config field dev+0x49c = + * 0x1400048; kext poll 0x…95ecfb4). + * + * W10 (2026-09-19) CORRECTS the claim that stood here — that the m1n1 + * t8103 mailbox (INBOX_CTRL +0x8110 / INBOX0 +0x8800) "has NO h14g + * analog". It has one, and it is live: see ANE_ASC_MBOX_* below. The + * earlier live test read +0x1608114, the h16g base, which is simply + * the wrong address on this part; and the absence of 0x1408xxx + * constants from the kext text means only that the mailbox belongs to + * the RTBuddy provider kext, not to AppleH11ANEInterface. + * + * W10 also read the CPU block for the first time, on a Linux boot with + * all eight pmgr domains at ACTUAL=0xf and the W8 grant applied: + * CPU_CONTROL 0x285400044 = 0x00000000 RUN=0 + * CPU_STATUS 0x285400048 = 0x0000002a RUNNING=0 STOPPED=1 IDLE=1 + * RVBAR 0x285050000 = 0x00000001 valid bit set, entry addr 0 + * The IOP has never been started and no firmware image is programmed, + * so nothing on this transport can answer the host until it is. + */ +#define ANE_ASC_CPU_CONTROL 0x1400044 /* RUN = BIT(4) */ +#define ANE_ASC_CPU_STATUS 0x1400048 /* m1n1 R_CPU_STATUS shape */ +#define ANE_ASC_RVBAR 0x1050000 /* fw entry | valid bit0 */ +#define ANE_ASC_EDPRCR 0x1010310 /* phase1 S2 whitelist */ +#define ANE_ASC_VERS 0x1840000 +#define ANE_ASC_RTB_STATUS 0x1840088 /* K14 poll: value < 2 */ +#define ANE_ASC_RTB_STATUS_UNK7C 0x184007c /* phase1 S2 whitelist */ + +/* ASC blocks iBoot names in the firmware's __rtk_patch records + * (RTK_cpu_physical_address 0x285000000 and RTK_cpu_wrapper_physical_address + * 0x285400000 on the T6021 preload), as engine-relative offsets. + */ +#define ANE_ASC_CPU_BASE 0x1000000 +#define ANE_ASC_WRAPPER_BASE 0x1400000 + +/* The real ASC mailbox, mapped live by W10 (read-only) at ASC+0x8000. + * Three independent sources agree on the offsets: the live DT sibling + * mbox@2a2408000 ("apple,t6020-asc-mailbox" / "apple,asc-mailbox-v4", + * size 0x4000, IRQs send-empty/send-not-empty/recv-empty/ + * recv-not-empty) fixes mailbox = asc_base + 0x8000; upstream + * drivers/soc/apple/mailbox.c apple_mbox_asc_hw fixes the register + * offsets; m1n1 proxyclient/m1n1/hw/asc.py ASCRegs gives the same set + * ASC-relative plus the R_MBOX_CTRL field layout. + * + * Observed on jw14m2 (2026-09-19), both directions identical: + * a2i_control 0x285408110 = 0x00020001 + * i2a_control 0x285408114 = 0x00020001 + * -> ENABLE=1 EMPTY=1 FULL=0 OVERFLOW=0 FIFOCNT=0 WPTR=0 RPTR=0 + * Enabled, and never used: both pointer pairs are still at the origin, + * so not one message has crossed either way since reset. 600 polls of + * i2a_control over 30 s produced zero changes. + * + * Receive is POP-ON-READ and 64-bit: upstream does + * while (!(i2a_control & EMPTY)) { readq(RECV0); readq(RECV1); } + * A 32-bit or memcpy-based read would eat messages. + */ +#define ANE_ASC_MBOX 0x1408000 +#define ANE_ASC_MBOX_A2I_CTRL 0x1408110 /* m1n1 INBOX_CTRL */ +#define ANE_ASC_MBOX_I2A_CTRL 0x1408114 /* m1n1 OUTBOX_CTRL */ +#define ANE_ASC_MBOX_A2I_SEND0 0x1408800 /* m1n1 INBOX0, u64 */ +#define ANE_ASC_MBOX_A2I_SEND1 0x1408808 /* m1n1 INBOX1, u64 */ +#define ANE_ASC_MBOX_I2A_RECV0 0x1408830 /* m1n1 OUTBOX0, u64 */ +#define ANE_ASC_MBOX_I2A_RECV1 0x1408838 /* m1n1 OUTBOX1, u64 */ + +/* R_MBOX_CTRL fields (m1n1 hw/asc.py) */ +#define ANE_ASC_MBOX_CTRL_FIFOCNT GENMASK(23, 20) +#define ANE_ASC_MBOX_CTRL_OVERFLOW BIT(18) +#define ANE_ASC_MBOX_CTRL_EMPTY BIT(17) +#define ANE_ASC_MBOX_CTRL_FULL BIT(16) +#define ANE_ASC_MBOX_CTRL_RPTR GENMASK(15, 12) +#define ANE_ASC_MBOX_CTRL_WPTR GENMASK(11, 8) +#define ANE_ASC_MBOX_CTRL_ENABLE BIT(0) + +/* W10 hazard: a plain READ of ANE+0x1854000 is fabric-fatal (watchdog + * reset ~63 s later, netconsole pinned the pre-log and no value line). + * Nothing may touch 0x1854000..0x1c04000; the old engine kill window + * 0x1c04000..0x1c28000 still stands. + */ +#define ANE_FATAL_READ_LO 0x1854000 +#define ANE_FATAL_READ_HI 0x1c04000 + +/* MBI transport (K14 h14g config: socinit stores the SCRATCH register + * offsets as q-blobs @0x…7503a40/0x…7503a50/0x…7503a60 into dev+0x438 + * and the message-register offsets @0x…7503860 into dev+0x488; runtime + * handshake in InitializeRTBuddy 0x…95e942c: cmd buffer base -> + * SCRATCH0/1 (0x…95eaa94), wake 0xf7fbdff9 -> SCRATCH7 (0x…95eab24), + * poll SCRATCH7 == 0x08042006 "channel description table ready" + * (0x…95eab74), table base read back from SCRATCH0/1 (0x…95ead04), + * per-channel {type,bit,size,phys} entries registered with the + * doorbell setter 0x…95ebdd0 writing (1 << bit) to +0x1844000. Host + * ack = SCRATCH3 = 0x08042006 (0x…95eaee4). + * + * PROVIDER DECODE (2026-09-19, kernelcache.release.mac14j): in + * RTBuddy mode the TX gate lives in com.apple.driver.RTBuddy 1.0.0 + * (carved from the KC, 46088 B, __TEXT_EXEC 0x…b696860). RTBuddy + * publishes per-ANE nubs named "%sEndpoint%u" (0x…7cc7d3f) with the + * role string "ANE" -> ANEEndpoint1..ANEEndpoint5, class + * RTBuddyEndpointService (0x98 B) wrapping RTBuddyEndpoint (0xE8 B), + * over the kernel IOSlaveEndpoint family; K14 EnableRTBuddyEndpoints + * (0x…95feb30) formats the name ("%s%d" @0x…74c481f), waits 10 s + * (x1 = 10^10 ns) for the match and takes the gate from [svc+0x88], + * registering its rx callback at gate+0xd0. The gate's per-message + * send is the vtable+0x1e8 slot; its body ends in the AKF mailbox + * write (AKF_AP_MAILBOX_SET = the +0x1844000 doorbell; RTBuddy dump + * fn 0x…b69d9c8 prints "AKF_KIC_INBOX_CTRL / AKF_KIC_MAILBOX_SET / + * AKF_AP_OUTBOX_CTRL / AKF_AP_MAILBOX_SET" and guards + * "INBOX%d not ready"/"Inbox%d overflow"). Endpoint number = + * doorbell bit: EP0 is RTBuddyManagementEndpoint (_handleHello / + * _handleEPRollCall / _handlePowerAck), EP1..5 the ANE data channels. + * [INFERENCE: the fw->host doorbell/IRQ bit numbering mirrors the + * host->fw SET bit per Asahi rtkit semantics; pinned live by W5.] + */ +#define ANE_MBI_SCRATCH0 0x1840048 /* SCRATCH0..7 = +0x48..+0x64 */ +#define ANE_MBI_SCRATCH6 0x1840060 +#define ANE_MBI_SCRATCH7 0x1840064 +/* Wake/ack handshake words live in ane_t6021_boot.h + * (ANE_T6021_BOOT_WAKE_REQ / ANE_T6021_BOOT_ACK) — single source, shared + * with the userspace boot regression. + */ +#define ANE_MBI_DOORBELL 0x1844000 /* write32 (1 << endpoint id) */ +/* NOT a message pair. W10 proved this is a mirror of the 24 MHz + * architectural counter: across 32 samples the absolute difference + * against CNTVCT_EL0 is a constant 13-18 counts (the MRS-to-MMIO + * instruction gap), aggregate drift 0.054 ppm over 55.2M counts. The + * "type-0 heartbeat, ~29 ticks/3 s" that W6/W9 recorded as firmware + * liveness was this clock plus a poll count: the RTKit type field + * GENMASK_ULL(59,52) is structurally zero until the counter passes + * 2^52 (~6 years of uptime). Kept only so the old reads stay + * identifiable in the logs; do not treat as transport. + */ +#define ANE_MBI_TIMEBASE_LO 0x1170000 /* was ANE_MBI_MSG_I2A_LO */ +#define ANE_MBI_TIMEBASE_HI 0x1170004 /* was ANE_MBI_MSG_I2A_HI */ +#define ANE_MBI_MSG_I2A_LO ANE_MBI_TIMEBASE_LO +#define ANE_MBI_MSG_I2A_HI ANE_MBI_TIMEBASE_HI +#define ANE_MBI_MSG_A2I_RD 0x184c000 /* host->fw message read peer */ +#define ANE_MBI_MSG_A2I_WR 0x1850000 /* host->fw message write */ + +/* Per-message MBI word (48-bit ring notification, K14 + * rtbuddyEndpointSendMessage 0x…95f3bf4-c30): offset = ring write + * cursor [23:0], length [47:24]. NOT the 54-bit surface-announce + * word (ane_ep_doorbell_encode below) — that one rides SetupEndpoints + * buffer mapping; this one is what the gate sends per command: the + * gate call is send(&msg48, 0, 1) at vtable+0x1e8, after the command + * bytes are already memcpy'd into the shared ring at ring_base + + * cursor. Length is capped at 0xffffff by the encoder field. + */ +#define ANE_MBI_MSG48_OFF GENMASK_ULL(23, 0) +#define ANE_MBI_MSG48_LEN GENMASK_ULL(47, 24) + +static inline u64 ane_mbi_msg48_encode(u32 cursor, u32 len) +{ + return (cursor & ANE_MBI_MSG48_OFF) | + FIELD_PREP(ANE_MBI_MSG48_LEN, len); +} + +/* Host->fw TX sequence (RTBuddy mode, all static-decode proven): + * 1. fail if len > ring_size (K14 0xe00002c2 @0x…95f3a24) + * 2. cursor = write_cursor; if (cursor + len >= ring_size) cursor = 0 + * (exact fit wraps: csel lo @0x…95f3b04) + * 3. memcpy(ring + cursor, cmd, len) (DMA-coherent ring) + * 4. dma_wmb() (ring visible before bell) + * 5. write32(ANE_MBI_MSG_A2I_WR, lo) + write32(+4, hi) — 32-bit + * halves (the AKF message register is word-shaped; W6 proved the + * W5-live abort was NOT the 64-bit writeq — the halves abort too) + * 6. write32(ANE_MBI_DOORBELL, 1 << ep) + * 7. on send success only: write_cursor = cursor + len (K14 + * 0x…95f3c70-c); the cursors at rec+0x40/rec+0x58 track the last + * issued slot. + * CSNE_CMD_PING = header-only 0x11 on EP1 (INIT) -> doorbell bit + * 1 << 1 = 0x2. Only the a2i message register + doorbell are + * touched, and only behind the mbi_doorbell opt-in (both stay + * host-write-fatal even behind the W8 grant, W9; SCRATCH family is + * host-writable granted, W9 nonzero latch). + */ + +/* MBI channel-table entry (kext stride 0x100, fields at +0x40 family: + * type @+0x40, doorbell bit @+0x44, size @+0x48, phys @+0x50 — + * InitializeRTBuddy 0x…95eade8-0x…95eae58) + */ +#define ANE_MBI_CHAN_STRIDE 0x100 +#define ANE_MBI_CHAN_MAX_DUMP 8 + +/* RTKit MGMT (EP 0); type bits [59:52], u64 message halves */ +#define ANE_RTKIT_TYPE GENMASK_ULL(59, 52) +#define ANE_RTKIT_MGMT_HELLO 1 +#define ANE_RTKIT_MGMT_HELLO_REPLY 2 +#define ANE_RTKIT_MGMT_STARTEP 5 +#define ANE_RTKIT_MGMT_SET_IOP_PWR_STATE 6 +#define ANE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK 7 +#define ANE_RTKIT_MGMT_EPMAP 8 +#define ANE_RTKIT_MGMT_SET_AP_PWR_STATE 0xb +#define ANE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK 0xb + +#define ANE_RTKIT_HELLO_MINVER GENMASK_ULL(15, 0) +#define ANE_RTKIT_HELLO_MAXVER GENMASK_ULL(31, 16) +#define ANE_RTKIT_EPMAP_LAST BIT_ULL(51) +#define ANE_RTKIT_EPMAP_BASE GENMASK_ULL(34, 32) +#define ANE_RTKIT_EPMAP_BITMAP GENMASK_ULL(31, 0) +#define ANE_RTKIT_EPMAP_REPLY_MORE BIT_ULL(0) +#define ANE_RTKIT_STARTEP_EP GENMASK_ULL(39, 32) +#define ANE_RTKIT_STARTEP_FLAG BIT_ULL(1) +#define ANE_RTKIT_PWR_STATE GENMASK_ULL(15, 0) +#define ANE_RTKIT_PWR_STATE_ON 0x20 + +#define ANE_RTKIT_VER_MIN 11 +#define ANE_RTKIT_VER_MAX 12 + +/* RTKit system endpoints rtkit.c starts when announced */ +#define ANE_RTKIT_EP_CRASHLOG 1 +#define ANE_RTKIT_EP_SYSLOG 2 +#define ANE_RTKIT_EP_DEBUG 3 +#define ANE_RTKIT_EP_IOREPORT 4 +#define ANE_RTKIT_EP_OSLOG 8 +#define ANE_RTKIT_EP_TRACEKIT 0xa + +/* RTBuddy app endpoints — K14 InitializeRTBuddyEndpoints opens ids 1..6; + * ring sizes + fourccs from the per-EP config table (W2 §3). fourcc is + * byte-reversed in the table (0x54324643 = "T2FC"). + */ +enum ane_t6021_eps { + ANE_T6021_EP_INIT = 1, /* INIT — CSNE_CMD controller channel (W4) */ + ANE_T6021_EP_T2FC, /* fw->host commands */ + ANE_T6021_EP_T2FH, /* fw->host commands */ + ANE_T6021_EP_T2HS, + ANE_T6021_EP_T2HC, + ANE_T6021_EP_T2HT, /* polled on the host */ + ANE_T6021_EP_COUNT = ANE_T6021_EP_T2HT + 1 /* arrays index by id */ +}; + +/* CSNE command ids — selene id->name table, vaddr 0xea430, 96 entries + * (full set: receipts/2026-09-18-h14-w2-protocol-decode §4 and + * receipts/2026-09-18-h14-w2-protocol-decode/fw_cmd_table.json). The + * fw parses the id as u16 at wire offset +4 (W4 correction of the W2 + * §4 "offset 0" claim: fw sites 0x4d244/0x4d264/0x5246c); the kext + * controller header for the fw->host direction is a different shape + * (u32 id @ +0x8, 0x24 bytes) and never rides host->fw submission. + */ +enum ane_t6021_csne_cmd { + CSNE_CMD_START = 0x0000, + CSNE_CMD_STOP = 0x0001, + CSNE_CMD_REG_FILE_LOAD = 0x0005, /* fw _rtk_tunables 1456 B */ + CSNE_CMD_BUILDINFO = 0x0006, + CSNE_CMD_BOOT = 0x0010, + CSNE_CMD_PING = 0x0011, + CSNE_CMD_POWER_DEVICE_ON = 0x0013, + CSNE_CMD_IPC_ENDPOINT_SET = 0x0015, + CSNE_CMD_IPC_ENDPOINT_UNSET = 0x0016, + CSNE_CMD_LOAD_PROGRAM = 0x0200, + CSNE_CMD_CREATE_PROCESS = 0x0202, + CSNE_CMD_PROCEDURE_CALL = 0x0204, + CSNE_CMD_INFERENCE_CALL = 0x0404, + CSNE_CMD_BACK_CHANNEL_RPC = 0x7000, +}; + +/* fw buffer word (selene builder 0x982b4/0x98f84, decoder 0x98fc8; the + * K14 SetupEndpoints word is the same shape): addr[43:0] | + * size_code[51:44] | unit[53:52], unit 0 = no size, 1 = code*4K, + * 2 = code*1M, 3 = code*2M. The fw encoder picks unit 1 below 1 MiB + * and unit 2 at or above, size code = CEILING division (cinc on the + * remainder), so the decoded size is the rounded-up value. rtkit.c's + * BUFFER_REQUEST is this word with unit 1. + */ +#define ANE_EP_DOORBELL_OFFSET GENMASK_ULL(43, 0) +#define ANE_EP_DOORBELL_SIZE GENMASK_ULL(51, 44) +#define ANE_EP_DOORBELL_UNIT GENMASK_ULL(53, 52) + +static const u8 ane_ep_doorbell_shift[] = { 0, 12, 20, 21 }; + +static inline u64 ane_ep_doorbell_encode(u64 offset, u32 size) +{ + u64 unit = (size >= SZ_1M) ? 2 : 1; + u32 code = DIV_ROUND_UP(size, 1u << ane_ep_doorbell_shift[unit]); + + return (offset & ANE_EP_DOORBELL_OFFSET) | + FIELD_PREP(ANE_EP_DOORBELL_SIZE, code) | + FIELD_PREP(ANE_EP_DOORBELL_UNIT, unit); +} + +static inline u32 ane_ep_doorbell_size(u64 msg) +{ + u32 unit = FIELD_GET(ANE_EP_DOORBELL_UNIT, msg); + + return FIELD_GET(ANE_EP_DOORBELL_SIZE, msg) << ane_ep_doorbell_shift[unit]; +} + +struct ane_t6021_ep { + u8 id; + const char *name; + u32 fourcc; + u32 ring_size; + u32 write_cursor; /* next ring slot (K14 rec+0x20) */ + void *ring; /* dma_alloc_coherent, ring_size */ + dma_addr_t ring_iova; + bool started; +}; + +struct reset_control; + +struct ane_t6021 { + struct device *dev; + void __iomem *base[ANE_T6021_REG_COUNT]; + int irq; + + struct device **pd_dev; + struct device_link **pd_link; + int pd_count; + + /* Single MBI consumer (threaded IRQ + probe drain serialize + * here) + */ + struct mutex mbox_lock; + + /* Bring-up state machine — honest semantics (W15): + * power_gated: first_resume passed (eight-island gate + + * whitelist; block access proven-safe), + * cpu_started: RVBAR programmed + CPU RUN released (fw_boot=1), + * fw_alive: fw first-alive ack observed on SCRATCH7 — NOT + * the init handshake, + * booted: full init handshake observed. CSNE/MGMT sessions + * gate on this flag only. + */ + bool power_gated; + bool cpu_started; + bool fw_alive; + bool booted; + + /* W10: the mailbox does exist — at +0x1408xxx, not the h16g + * +0x1608xxx that read-aborted in 2026-09-19 — and it reads a + * live, enabled, permanently-empty ASC v4 control pair. It is + * empty because the ASC CPU is STOPPED with RUN clear and RVBAR + * entry 0, i.e. no firmware was ever started. Default off = + * status-only bring-up. Opt-in runs the kext-evidenced MBI + * handshake (SCRATCH wake -> fw channel table), capture-only. + */ + bool transport; + bool doorbell; /* mbi_doorbell=1: EP rings may write the +0x1844000 + * doorbell + a2i message register (decoded 2026-09-19) + */ + bool irq_requested; + + struct ane_t6021_ep ep[ANE_T6021_EP_COUNT]; + + /* W13 fw surface (fw_load=1): coherent, DART-mapped via the + * device's iommu group. NULL unless loaded. + */ + void *fw_buf; + dma_addr_t fw_iova; + u32 fw_size; + /* W16 entry alias: IOVA the fw pages are aliased at (the latched + * RVBAR entry); 0 = no alias mapped. The DMA allocator has no + * runtime reservation API on this kernel, so instead of a prose + * collision bound every DMA allocation site must pass its iova + * through ane_t6021_fw_alias_iova_ok() and refuse overlaps. + */ + u64 fw_alias_iova; + /* Per-window mapped extents (iova, bytes) — teardown unmaps + * exactly these, because the windows are not assumed adjacent + * (live trace: hole between SEG0 and SEGi) and unmapping a page + * that was never mapped trips dart_unmap_pages (io-pgtable-dart + * .c:319 WARN, 2026-09-26 state-report unwind). Set only on + * successful map. + */ +#define ANE_FW_ALIAS_MAX_WIN 3 + u64 fw_alias_ext_iova[ANE_FW_ALIAS_MAX_WIN]; + size_t fw_alias_ext_len[ANE_FW_ALIAS_MAX_WIN]; + int fw_alias_extn; + /* W16 pass-3: ane_cpu reset controller (ps RESET via the pmgr + * pwrstate reset_controller ops); NULL when the DT carries no + * resets property. + */ + struct reset_control *cpu_rst; + + /* W15 boot allocations (gate-gated: never exist until the + * preflight opens and the sequence passes poll A). Ownership per + * the wedged-pin rule: held, never freed, while cpu_started. + */ + void *boot_pool; /* 'DDM ' pool, 0x40000 (Params word0) */ + dma_addr_t boot_pool_iova; + void *boot_ipc; /* 'IPC ' surface, max(0x4000, ord+1) */ + dma_addr_t boot_ipc_iova; + u64 boot_ipc_size; + void *boot_heap; /* fw-requested HEAP surface or NULL */ + dma_addr_t boot_heap_iova; + u64 boot_heap_size; + u32 prev_fw_len; /* [0x30]: previous fw image length + * (0 first boot; updated per reload) + */ + u64 boot_scratch_result; /* SCRATCH1<<32 | SCRATCH0 captured + * at DONE — raw; success semantics + * UNSOURCED (never inferred) + */ + bool response_validated; + bool hybrid_pinned; /* FALSE until the DONE response + * semantics are sourced AND the + * raw address is range/length + * validated against owned + * windows — transport/CSNE + * sessions stay fenced on first + * boot regardless of booted + */ +}; + +/* Enforced alias-window invariant (W16): the DMA allocator has no + * runtime IOVA reservation on this kernel, so every DMA allocation + * site must refuse a mapping that overlaps the fw entry alias. + */ +static inline bool ane_t6021_fw_alias_iova_ok(const struct ane_t6021 *ane, + dma_addr_t iova, size_t size) +{ + u64 lo = ane->fw_alias_iova; + + if (!lo) + return true; + return iova + size <= lo || iova >= lo + ane->fw_size; +} + +/* ane_t6021_rtkit.c */ +int ane_t6021_rtkit_init(struct ane_t6021 *ane); +void ane_t6021_rtkit_shutdown(struct ane_t6021 *ane); +void ane_t6021_rtkit_drain(struct ane_t6021 *ane); +irqreturn_t ane_t6021_rtkit_irq_thread(int irq, void *data); + +/* ane_t6021_boot.c — W15 boot state resolution (fw_boot=1). An + * explicit boot request fails the probe while the prerequisites in + * ane_t6021_boot.c hold (-ENODATA); fw_boot=0 binds status-only. + * ane_t6021_boot_start() is the sequence dispatcher proper (all gates + * must already hold): it owns the wedged-pin module lifetime once the + * CPU is released; stop_after = 0 full run, 1..4 = fw-start-debug + * step bisect (stop after that step, -ECANCELED, clean unwind while + * no CPU started). + */ +int ane_t6021_boot_start(struct ane_t6021 *ane, int stop_after, int table_mode, + int rtb_mode); + +/* ---- CSNE_CMD wire structs (host->fw on the INIT channel) ---- + * + * W4 static decode, extending W2 §4 (the receipt's "fw parses a u16 id + * at header offset 0" was WRONG — three independent fw parse sites read + * the id as u16 at offset +4: the generic CSNE processor @0x4d264, its + * preload @0x4d244, and the LOAD_PROGRAM/CREATE_PROCESS/PROCEDURE_CALL + * pre-parse @0x5246c, all `ldrh wN, [xM, #4]` in selene). Wire is + * little-endian; this module is arm64-only so host order is wire order. + * + * The generic processor takes commands < 0x1b89 bytes (work-item size + * bound @0x4d134-0x4d158) and writes completion state back into the + * command block (strb @0x4d324 byte +6, str @0x4d3b0 qword +8) — the + * ring slot doubles as the response area. PING/BUILDINFO/BOOT/ + * REG_FILE_LOAD/IPC_ENDPOINT_SET fall through the processor's id tree + * to the default path (0x4e65c): carried without field parsing, so + * their payloads beyond the header are opaque until the W1 live + * exchange pins them. + */ +struct ane_csne_hdr { + u32 rsvd0; /* bytes 0..3: never read by the fw processor; 0 */ + u16 id; /* PROVEN u16 @ +4 (sites above) */ + u8 flags; /* fw-written byte @ +6 (status/scratch) [INFERENCE] */ + u8 rsvd7; +}; + +static_assert(sizeof(struct ane_csne_hdr) == 8); + +static inline void ane_csne_hdr_init(struct ane_csne_hdr *h, u16 id) +{ + memset(h, 0, sizeof(*h)); + h->id = id; +} + +/* Header-only CSNE_CMDs: BOOT (0x10 — boot-arg surfaces ride + * SCRATCH0-7 / SetupFWInitBootArgs, not the command, phase1 §2.5), + * PING (0x11), BUILDINFO (0x06). sizeof(struct ane_csne_hdr) bytes. + */ + +/* REG_FILE_LOAD (0x05) payload: the 1456 B blob is the fw's own + * __DATA._rtk_tunables section (@0x100590, size 0x5b0) — its transport + * (inline vs shared-memory iova) is [INFERENCE], pinned by W1. + */ +struct ane_csne_cmd_reg_file_load { + struct ane_csne_hdr hdr; + u8 blob[]; +}; + +/* IPC_ENDPOINT_SET (0x15) payload: binds a host RTBuddy endpoint to a + * fw channel. No field parsed by the fw processor — layout + * [INFERENCE], pinned by W1. + */ +struct ane_csne_cmd_ipc_endpoint_set { + struct ane_csne_hdr hdr; + u8 payload[]; +}; + +/* PROCEDURE_CALL (0x204) / INFERENCE_CALL (0x404) — the kext + * CANE_SUB_PACKET_CMD_PROCEDURE_CALL family. Field offsets PROVEN from + * the fw parse; field semantics named only where the kext asserts name + * them (programId, procedureId, numIoBuffers in assert order, W2 §4): + * +0x08/+0x0c u32 pair validated together (ldp @0x4d654) + * +0x10 u64 passed to the fw validator (0x4d6d4) + * +0x18 u32 stats/priority, fw-valid [2,7]; 2 is the value + * proven end-to-end (binding.json stats_type; the + * first-inference receipt's bare calls) + * +0x28 u32 element count (loop bound @0x524bc-0x524c4) + * +0x60 count × 0x30-byte io-buffer records (@0x524a8-0x524b4) + * The kext `size % sizeof(sCSneCmdProcedureCall) == 0` assert says + * commands form same-shape arrays in the ring; this driver submits one + * command per slot. INFERENCE_CALL shares the shape [INFERENCE: the + * 0x404 id is not in the decoded id tree — it is the W4 submission + * endpoint per the phase-1 workstream plan]. + */ +struct ane_csne_io_elem { + u8 bytes[0x30]; /* internal layout not decoded */ +}; + +struct ane_csne_cmd_procedure_call { + struct ane_csne_hdr hdr; + u32 program_id; /* +0x08 */ + u32 procedure_id; /* +0x0c */ + u64 field_10; + u32 field_18; /* fw requires 8..15 */ + u32 rsvd_1c; + u64 field_20; + u32 num_io_buffers; /* +0x28 = element count */ + u32 rsvd_2c; + u8 gap_30[0x30]; + struct ane_csne_io_elem io[]; +}; + +static_assert(offsetof(struct ane_csne_cmd_procedure_call, program_id) == 0x08); +static_assert(offsetof(struct ane_csne_cmd_procedure_call, procedure_id) == 0x0c); +static_assert(offsetof(struct ane_csne_cmd_procedure_call, field_10) == 0x10); +static_assert(offsetof(struct ane_csne_cmd_procedure_call, field_18) == 0x18); +static_assert(offsetof(struct ane_csne_cmd_procedure_call, num_io_buffers) == 0x28); +static_assert(offsetof(struct ane_csne_cmd_procedure_call, io) == 0x60); + +static inline size_t +ane_csne_cmd_procedure_call_size(unsigned int num_io_buffers) +{ + return sizeof(struct ane_csne_cmd_procedure_call) + + num_io_buffers * sizeof(struct ane_csne_io_elem); +} + +/* Fw-side bound: the generic CSNE processor rejects work items of + * 0x1b89 bytes and above (@0x4d134 cmp x2, #0x1b89). What x2 names + * beyond "the command's size" is [INFERENCE] — enforced here as a + * fail-fast so an oversized command cannot enter the ring. + */ +#define ANE_CSNE_CMD_MAX_SIZE 0x1b88 + +/* ---- LOAD_PROGRAM (0x200) wire contract (selene 0x4e44c hook + + * 0x4e53c worker + 0x4e640 registration; decode 2026-09-26, entry + * item 23/23b/23c/23e): the payload is NINE 0x30-byte named section + * records at +0x08. Registration publishes ".bin" into the fw + * program-info symbol table (format "%s.bin" @0xa733f, + * CAneProgramInfo.cpp) with value = record+0x18 and aux = + * u32(record+0x20). The fw dereferences record+0x18 (0x5d0c8), so it + * carries a fw-addressable pointer — in this driver, the IOVA of a + * host-authored section object (below). Absent sections (flags bit0 + * clear) are skipped by every decoded parser. ---- + */ +enum ane_t6021_load_section { + ANE_SEC_GENERIC = 0, + ANE_SEC_KERNEL, + ANE_SEC_TEXT, + ANE_SEC_OPERATION, + ANE_SEC_PROCEDURE, + ANE_SEC_KERNELPROP, + ANE_SEC_TEXTPROP, + ANE_SEC_OPDBG, + ANE_SEC_PROCPROP, + ANE_SEC_COUNT /* 9 */ +}; + +#define ANE_T6021_LOAD_SEC_COUNT 9 + +static const char * const +ane_t6021_load_sec_name[ANE_T6021_LOAD_SEC_COUNT] = { + "genericSection", "kernelSection", "textSection", + "operationSection", "procedureSection", "kernelPropSection", + "textPropSection", "opDbgSection", "procPropSection", +}; + +struct ane_csne_cmd_load_program { + struct ane_csne_hdr hdr; /* id 0x200 @ +4 */ + struct ane_csne_io_elem sec[ANE_T6021_LOAD_SEC_COUNT]; +}; + +static_assert(sizeof(struct ane_csne_cmd_load_program) == + 0x08 + 9 * 0x30); + +/* Section-record wire accessors over the 0x30-byte io_elem (the only + * bytes any decoded parser reads; the rest is unread pass-through): + * +0x00 u8 flags — bit0 present; +0x18 u64 obj — fw-addressable + * pointer, validated by 0x5d0c8 to land inside a registered program + * object's entry table; +0x20 u64 key — per-section lookup key. + */ +#define ANE_SEC_F_PRESENT BIT(0) + +static inline void ane_sec_record_init(void *rec, u64 obj, u64 key) +{ + u8 *r = rec; + + memset(r, 0, 0x30); + r[0] |= ANE_SEC_F_PRESENT; + *(u64 *)(r + 0x18) = obj; + *(u64 *)(r + 0x20) = key; +} + +/* Host-authored PROGRAM OBJECT (the thing section records point at; + * 0x5d0c8 validates: magic 1 @+0, count <= 0x10 @+4, table entry + * count in [0x201, 0x400] @+0x204, 0x30-byte entry table @+0x208 with + * the recorded pointer bounded inside it). Minimum object = header + + * 0x201 zeroed entries; entries are the same 0x30-byte shape. + */ +#define ANE_PROGOBJ_MIN_ENTRIES 0x201 +#define ANE_PROGOBJ_MAX_ENTRIES 0x400 +#define ANE_PROGOBJ_TABLE_OFF 0x208 +#define ANE_PROGOBJ_HDR_SZ 0x208 + +static inline size_t ane_progobj_size(u32 entries) +{ + return ANE_PROGOBJ_TABLE_OFF + (size_t)entries * 0x30; +} + +static inline void ane_progobj_init(void *obj, u32 entries) +{ + struct { u32 magic; u32 count; u32 rsvd[2]; u32 entries; } *h = obj; + + h->magic = 1; + h->count = 0; + h->rsvd[0] = 0; + h->rsvd[1] = 0; + h->entries = entries; + /* caller zeroes the tail: entries table starts at +0x208 */ +} + +/* Host-authored OPERATION-SECTION image (0x5d290: u32 op_count @+0, + * <= 0x80; then op_count 0x40c-byte operation records at +4; the + * section KEY is an offset past the array, >= op_count*0x40c + 4). + * Operation record fields decoded: +0x00 u32 type <= 4; +0x04 u16 + * <= 0x10; +0x08 u32 procedure_count <= 0x80 (non-zero); +0x0c.. + * u32 procedure indices, each <= 0x3c. + */ +#define ANE_OPSEC_OP_REC_SIZE 0x40c +#define ANE_OPSEC_MAX_OPS 0x80 + +static inline size_t ane_opsec_size(u32 ops) +{ + return 4 + (size_t)ops * ANE_OPSEC_OP_REC_SIZE; +} + +/* Submit one CSNE command block on the INIT (EP1) ring: K14 + * rtbuddyEndpointSendMessage semantics (W2 §3) — slot alloc with wrap, + * memcpy into the ring, 54-bit doorbell word, cursor + * advanced only on doorbell success. No synchronous response matching: + * fw->host responses arrive on the T2F* channels and are not walked + * yet (W2 §3). Sleeps (mutex) — process context only. + */ +int ane_t6021_csne_submit(struct ane_t6021 *ane, const void *cmd, size_t size); + +/* Probe-time one-shot CSNE_CMD_PING on EP1 (W5-live), behind + * mbi_doorbell=1 only; watches the fw response surfaces for 3 s. + */ +void ane_t6021_csne_ping_attempt(struct ane_t6021 *ane); + +/* W13/W14 firmware loader (ane_t6021_fwload.c): validate + stage + + * dart-ane0-map the 13.5 PRELOAD payload behind fw_load=1. This is + * the staging half of the boot contract: the Params+0x18 producer + * chain and the RVBAR fold are closed (mapper-callchain audit, commits + * 3762aee/12be074); ane_t6021_boot.c consumes the staged surface. + */ +int ane_t6021_fwload_probe(struct ane_t6021 *ane); +void ane_t6021_fwload_remove(struct ane_t6021 *ane); +bool ane_t6021_fwload_options_ok(void); +bool ane_t6021_fwload_placement_ok(struct device *dev); +bool ane_t6021_fwload_requested(void); + +struct ane_fw_image; +struct ane_asc_tunables; + +/* Per-SoC of_match data (defined in ane_t6021_fwload.c). + * soc, soc_revision: what iBoot writes to RTK_soc and RTK_soc_revision. + * revision_fuse: read the revision from the DT "fuse" window as iBoot + * does instead (T8112). + * preload_placement: the iBoot SEG0/SEGi physical placement is recorded + * for this SoC (T6021 only), so fw_alias_reserved=1 may map it; the + * other SoCs always run the firmware from driver-owned memory. + * ps_cpu_off: the ANE CPU ps word in the DT "pmgr" window (probe guard). + * pwgate_off: the kext's PWGATE word in the DT "set" window, checked + * open before any engine read; 0 = not checked. + * pmu_pa: the page of the seven ANE ps words; the firmware's power + * service writes them through its DART at IOVA == PA. ps_off: the + * first of the seven in that page. + * trace_td_off: engine offset of the TM last-committed-TD word read by + * trace_td; 0 = trace_td unsupported. + */ +struct ane_t602x_soc { + u32 soc; + u32 soc_revision; + bool revision_fuse; + bool preload_placement; + const struct ane_fw_image *fw; + const struct ane_asc_tunables *tunables; + u32 ps_cpu_off; + u32 pwgate_off; + u64 pmu_pa; + u32 ps_off; + u32 trace_td_off; +}; + +extern const struct ane_t602x_soc ane_t6020_soc, ane_t6021_soc, + ane_t6022_soc, ane_t8112_soc; + +#endif /* __ANE_T6021_H__ */ diff --git a/drivers/accel/ane/ane_t6021_boot.c b/drivers/accel/ane/ane_t6021_boot.c new file mode 100644 index 0000000000000..066d2a799851a --- /dev/null +++ b/drivers/accel/ane/ane_t6021_boot.c @@ -0,0 +1,557 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * ane_t6021_boot.c — T6021 boot state reporter (W15). + * + * READ-ONLY. Main review 2026-09-20: the unresolved pre-CPU power and + * config-table prerequisites BLOCK every boot write, so this unit + * performs no MMIO write at all — it resolves the boot-input state, + * reports it with per-read whitelist provenance, and names the exact + * missing lifecycle datum. The write path (RVBAR entry fold + CPU RUN + * release + first-alive ack) lands only after the prerequisites below + * are pinned; its pure contract units (entry fold, latch/entry decode, + * SCRATCH u64 split, init-structure fill) live in ane_t6021_boot.h and + * are regression-tested host-side (tools/h14_boot_regression.c). + * + * Blocked boot writes, with the blocking prerequisite each one waits on: + * - RVBAR entry fold (ENTRY_BASE | fw DVA & ADDR_MASK; single u64 + * store, width_proof 0x95e9860→0x9622b0c read / 0x95e9988→0x9622c94 + * write): semantics of the observed RVBAR read 0x1 are unresolved + * (see the rvbar lifecycle fork) AND the pre-CPU block + * below applies regardless. + * - CPU_CONTROL write32 0 then 0x10 (rvbar-width local order): waits + * on the same pre-CPU block; releasing RUN with an unresolved + * entry state is the exact blind start the lane forbids. + * - SCRATCH0/1 publication + SCRATCH7 wake: init-structure fields + * [0x08] and [0x10,0x38) have no pinned selene fn 0x71A4 consumer + * read-set; zero-filling unknown fields and calling the structure + * valid is forbidden (Main 2026-09-20). + * + * Pre-CPU prerequisites, updated for pass4 (receipts 2026-09-20 + * mapper-callchain pass4 + tools/check_power_anchors.py 33/33, commit + * 04630ef): + * RESOLVED (pass4): the CPU-power branch selector — H14g SoCConfig + * zeroes dev+0x3EA0 (0x9613e14, the block that also sets + * dev+0x4A0=0x01400044), so EnableCPUClocksAndPower takes the + * PLAIN branch: write32(PMGR+0x2e0, 0x0000000f), validate 0xff — + * AUTO_ENABLE bit28 never set. On Linux this END STATE is exactly + * what the first_resume stage-2/3 gate verifies (act=0xf, + * AUTO_ENABLE clear) before any of this code runs — the write is + * therefore not replicated (ps-word writes are forbidden by the + * standing rule and froze the box 2026-09-19); the gate IS the + * equivalence check. + * STILL OPEN (each blocks its write below): + * 1. CLOSED (pass5 c364f24): the pre-CPU engine table writels + * eng+0xb38/0xb98/0xbf8 <- 0x01ff01ff are REQUIRED every + * EnableANEClocksAndPower — dev+0x784 bit0 has no writer, so the + * always-open gate runs the loop unconditionally; the + * order-vs-start question is moot. Receiver PROVEN pass4 + * (dev+0x188 accessor = engine reg[0]); count = config+0x150 = + * 3. Armed below; the first live firing must ride netconsole + * behind the seam logs. + * 2. Provider first-enable enableDeviceClock(1,dev+0x8F0)/ + * enableDevicePower(1,&out,dev+0x8F0) (0x95d1d48/0x95d1d90): + * internal gate-ID arrays are runtime-populated (open). Linux + * substitutes the genpd raise + supplier links (islands verified + * ACTUAL=0xf by the gate); the equivalence datum is the open + * half. + * 3. RVBAR lifecycle — RESOLVED (M2ResetLifecycle, + * rvbar-lifecycle-evidence.json, anchors 38/38 + * check_rvbar_lifecycle_anchors.py): live bit0-set + entry 0 is + * the STALE state; the kext-lawful transition is power_off + * (ANE_deInit when dev+0x3FB, then PMGR ps 0x2e0 ← 0x00000000 via + * the dev+0x190 PMGR accessor) → power_on → re-init, NEVER an + * RVBAR write while bit0 is set. RVBAR (engine accessor, + * 0x1050000, u64) is written only after a read64 with bit0 == 0; + * CPU_CONTROL write32 0 then 0x10 runs on BOTH paths; success = + * SCRATCH7 (dev+0x454 selector) read32 == 0x08042006. Open edge: + * whether ps-off clears bit0 — one live read-only read64 after a + * domain-off answers it. IMPLEMENTATION CAVEAT: the ps-word write + * is the class that froze this host from kernel context + * (2026-09-19 receipt) and the W3 gate demands act=0xf + + * AUTO_ENABLE clear afterwards — the reset vehicle (userspace + * stage vs in-kernel) is a Main decision, so the fold+start path + * stays behind the itemized preflight gates. + * 3. Ack model — TWO-PHASE, SINGLE REGISTER, TRANSITION-BASED + * (rvbar-lifecycle receipt 6288b0b, 57/57 anchors; supersedes the + * pass6 SCRATCH0-beacon reading): pre-CPU, SCRATCH cells are + * cleared and SCRATCH7 is PULSED 1 -> 0 (stale READY/wake + * cleared); after CPU_CONTROL 0 -> 0x10, poll A demands a FRESH + * SCRATCH7 READY 0x08042006 (fw alive; fw_alive). Publication + * (init suballoc DVA -> SCRATCH0/1, dsb st) happens ONLY after + * poll A; then wake 0xf7fbdff9 -> SCRATCH7 releases the fw; poll + * B awaits SCRATCH7 DONE 0x08042006 (booted) and reads back + * SCRATCH0/1. Because of the pulse, a post-CPU READY is + * unambiguous — no stale-ack hazard. The SCRATCH0 marker (fn + * 0x86EC) is not a gate. + * Selene raw anchors: READY write idx7 @0x7360-0x7388 (movz + * 0x2006 @0x7364, mov w1,#7 @0x7368, movk 0x804 @0x736c, slot + * byte48 @0x7380, salt 0x5bdd @0x7384, blraa @0x7388); poll loop + * READ32 idx7 @0x73c4-0x73e4, cmp wake 0xf7fbdff9 @0x73e8, + * sleep(1000) @0x73f8-0x73fc; DONE ack @0x77cc-0x77f0. + * 4. Linux allocation map (legacy branch sizes): FWIM surface = + * config+0x138 byte-count = 0x500000 (Main, audit 751caa4); + * Linux fw_buf is ANE_FW_BUF_SIZE = 0x500000 — the semantic is + * honored directly, covering the image vmsize 0x36c000. 'IPC ' + * surface = min(config+4, dev+0x3A70 + * cap) — the numeric cap needs the h14g config blob field map + * (open prerequisite). Init suballoc = 0x174 from a Linux-owned + * pool standing in for the kext dev+0x968/dev+0x980 pool (pool + * total size open). RTBuddy FW_INIT sizes (64K…) are the OTHER + * branch — never used here. + * 5. Init publication: the fw consumes [0x08]..[0x68] (pass5) and + * the Linux sources of those fields are not pinned ([0x08] = + * *(dev+0x988+0x18) = the 'IPC ' surface DVA — the surface + * itself is CLOSED (pass5c/5d), its Linux allocation size open + * per item 4; [0x10]/[0x18] = config-size terms with + * config+0x138 = image byte-count closed; [0x30] = dev+0x990 + * load-progress word) — publication cannot fire until every + * fw-read field has a pinned Linux source. + * + * Read whitelist — every MMIO read below, individually: + * - RVBAR eng+0x01050000: read64 width-proven (rvbar-width + * width_proof); W8 and W10 live Linux reads, value 0x1 each. + * - CPU_STATUS eng+0x1400048: phase-1 S2 whitelist; kext poll site + * 0x…95ecfb4 (config field dev+0x49c = 0x1400048); W10 live read + * 0x2a. + * - ASC mailbox controls eng+0x1408110/0x1408114: W10 live reads + * (both 0x00020001; 600 polls / 30 s, zero changes, zero aborts). + * The FATAL mailbox-class reads were the +0x1608xxx h16g analog — + * a different address never touched here; the 0x1854000..0x1c04000 + * fabric-fatal window is likewise never touched. + * - SCRATCH eng+0x1840048..0x1840064: phase-1 S2 whitelist + * (all-zero pre-attach), W5 pre-read log clean, first_resume + * re-reads all eight on every load. + * - TICK eng+0x1160008 (PROGRESS dump only): 24 MHz domain tick, + * proven readable post-release (2026-09-25 handshake receipt); + * two reads 20 ms apart for a delta. engine+0x1140008 is + * deliberately NOT read (readability/width/reset semantics + * unproven, no pre-release baseline — Main review 2026-09-26). + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ane_t6021.h" + +#include "ane_t6021_boot.h" + +/* Retain the firmware nap-prevention counter via the init resource bit + * (lab boot_prevent_nap=1, the proven add-path value). + */ +static bool boot_prevent_nap = true; +module_param(boot_prevent_nap, bool, 0444); +MODULE_PARM_DESC(boot_prevent_nap, + "Retain firmware nap-prevention counter via init resource bit (default on: proven add-path value)"); + +/* This object links into both ane_t6021.ko and ane_t6021_rtclient.ko; + * per-object metadata keeps modpost happy for either composition. + */ +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("T6021 ANE contract-pinned boot sequence core"); + +/* Boot-write gates — ITEMIZED, each a HARD gate: the ENTIRE write + * sequence (preboot engine table, scratch clear + pulse, RVBAR + * resolution, CPU release, publication, wake) runs start-to-finish + * only when EVERY gate below is true, checked BEFORE any write (Main + * 2026-09-20: no partial boot; remaining semantics stay hard gates, + * not comments). Each flips only with cited proof in a Main-reviewed + * commit that also populates the sources and adds the kernel io + * backend — never a runtime knob. + */ +/* Provider equivalence — CLOSED (Main provider review 2026-09-20): + * Linux genpd attachment + supplier links accepted INSTEAD of + * reproducing Apple runtime index arrays, CONDITIONAL on the live + * first_resume verifying all 8 islands ACTUAL=0xf, BUSY=0, CPU + * AUTO_ENABLE clear before the sequence — that verification runs on + * every probe and the driver performs no direct kernel PMGR writes. + */ +static const bool pf_provider_genpd_strategy = true; +static const bool pf_pool_word0_proven = true; /* CONFIRMED (Main raw + + * Reset 183fd50, chain + * 0x67dc/0x6824/0x68d8/ + * 0x70dc/0x736c): DDM Params + * word0 = requested bytes = + * 0x40000 — sourced, not + * synthesized + */ +static const bool pf_heap_floor_pinned = true; /* CLOSED: floor = + * getPageSize() return = + * DART page size 0x4000 + * (store chain 0x9602e68-90 + * + dart-ane0 page-size + * 0x4000 node, pass6h); + * sourced in boot_sources + */ +static const bool pf_dart_page_floor = true; /* CLOSED (Main raw, + * pass6h + exact-node + * linkage): dtree-j414c.txt + * sha256 dd2955…d504, ane0 + * iommu-parent 363 (line + * 11499), dart-ane0 + * page-size 0x4000 (line + * 11510), child mapper-ane0 + * phandle 363 (line 11527). + * Runnable linkage check: + * ane-linux-experiments + * tools/ + * check_dart_ane_pagesize_linkage.py + */ +static const bool pf_rvbar_lifecycle = true; /* 6288b0b, 57/57 anchors */ +static const bool pf_pass6_init_contract = true; /* cd25b46, 87/87 */ + +/* FINAL authorization gate — CLOSED (Main provider review + pass6h + * numeric closure + 183fd50 word0 confirmation + netconsole Wi-Fi + * marker m2-wifi-check-1789937086 @ 15:44:47.121595Z). Source + * contract closure complete; live attempt authorized by user + * override (autonomous boot/recovery loop). + */ +/* Table-block mode selection (2026-09-20 16:23:07 wedge): + * mode 0 = ABORT before any write (accidental-repeat prevention), + * mode 1 = write the table (kext-faithful; selected per-run via the + * rtclient fw_start_table_mode param), + * mode 2 = SKIP the table (default: the shipped diagnostic). + * W8 write-grant tunables are mode-independent (proven no-abort + * class, w8-run.out: APERTURE_UNLOCKED) and run in every armed mode. + */ + +static const bool pf_main_lifetime_review = true; + +static bool ane_t6021_boot_preflight_complete(void) +{ + /* pf_preboot_table_safe is INTENTIONALLY NOT in this product: + * mode 2 (table skip) is the authorized diagnostic state — + * the preflight covers the source contract, the mode selector + * covers the live-fault table gating. + */ + return pf_provider_genpd_strategy && pf_pool_word0_proven && + pf_heap_floor_pinned && pf_dart_page_floor && + pf_rvbar_lifecycle && pf_pass6_init_contract && + pf_main_lifetime_review; +} + +/* STATIC boot sources — populated per the pinned contract (Main + * authorization 2026-09-20). Object layout (Main raw correction, + * superseding audit 018abdb): the OSValueObject at +0x10 POINTS to + * the Params; Params+0x00 = size, +0x18 = DVA, +0x38 = hostVA. + * dev+0x980 is the 'DDM ' Params pool (size 0x40000); dev+0x968 is a + * SEPARATE DMM manager constructed over the pool hostVA — never + * conflate the two. Runtime fields (fw_dva, ipc_dva, pool_dma) are + * filled by ane_t6021_boot_prepare() at sequence time (after poll A, + * per "dynamic allocations occur after READY"); heap_floor stays 0 + * here and is supplied together with pf_heap_floor_pinned — NEVER + * used unpinned (the gate above keeps the whole sequence unrun until + * then). + */ +static const struct ane_t6021_init_sources boot_sources = { + .cfg_size = 0x500000, /* config+0x138 (0x9613da8/ dac) */ + .prev_fw_len = 0, /* first boot; static per reload */ + .heap_floor = 0x4000, /* DART page size: dev+0x3A90 = + * getPageSize() return; node + * authority dart-ane0 page-size + * 0x4000 (exact linkage check + * passing) + */ + .pool_word0 = 0x40000, /* DDM Params word0 = requested + * bytes (CONFIRMED, 183fd50) + */ +}; + +/* Poll A/B bound: the kext polls <=1000 x sleep(1ms) (selene poll + * loop 0x73c4-0x73fc analog; rvbar-lifecycle step 6/10). + */ +#define ANE_BOOT_ACK_POLL_US 1000 +#define ANE_BOOT_POLL_MS 1000 + +/* The COMPLETE resolved legacy-boot sequence is implemented ONCE in + * ane_t6021_boot.h (ane_t6021_boot_run) against an io backend, so the + * fake-MMIO trace check exercises the exact code the device will run + * (Main: runnable trace check; implement the device wiring only after + * ALL sources close — until then this file performs no boot write). + * The kernel backend (readl/writeq/udelay wrappers + prepare hook + * doing the pool/IPC allocations and the sourced fill) is the small + * reviewed increment that lands with the gate flip. + */ + +/* ---- kernel io backend for ane_t6021_boot_run() ---- */ + +struct ane_t6021_boot_mmio { + struct ane_t6021 *ane; +}; + +static u32 ane_boot_rd32(void *ctx, unsigned int off) +{ + struct ane_t6021_boot_mmio *mm = ctx; + + return readl(mm->ane->base[ANE_T6021_REG_ENGINE] + off); +} + +static u64 ane_boot_rd64(void *ctx, unsigned int off) +{ + struct ane_t6021_boot_mmio *mm = ctx; + + return readq(mm->ane->base[ANE_T6021_REG_ENGINE] + off); +} + +static void ane_boot_wr32(void *ctx, unsigned int off, u32 v) +{ + struct ane_t6021_boot_mmio *mm = ctx; + + writel(v, mm->ane->base[ANE_T6021_REG_ENGINE] + off); +} + +static void ane_boot_wr64(void *ctx, unsigned int off, u64 v) +{ + struct ane_t6021_boot_mmio *mm = ctx; + + writeq(v, mm->ane->base[ANE_T6021_REG_ENGINE] + off); +} + +static void ane_boot_publish_barrier(void *ctx) +{ + (void)ctx; + /* dma_wmb() = dmb oshst on arm64: orders the coherent pool fill + * before the device publish. ORDERING guarantee — not the kext's + * dsb st (completion). Sufficient for the Linux coherent-DMA + + * writel doorbell contract (writel orders prior accesses before + * the MMIO store). + */ + dma_wmb(); +} + +static void ane_boot_wait(void *ctx) +{ + (void)ctx; + usleep_range(1000, 1500); /* kext poll: sleep(1000us) */ +} + +static void ane_boot_phase(void *ctx, const char *what) +{ + struct ane_t6021_boot_mmio *mm = ctx; + + /* bounded phase marker: one line per block boundary, survives + * netconsole for crash attribution (never per-poll). KERN_EMERG + * + a short drain so the line reaches tty0/netconsole/ssh + * BEFORE the risky write it announces (fw-start-debug + * 2026-09-22: fwstart#2 died with zero capture — the marker + * must beat the write). + */ + dev_emerg(mm->ane->dev, "BOOT-PHASE %s\n", what); + msleep(30); +} + +/* S5 prepare — runs strictly AFTER poll A (fw alive), BEFORE the + * SCRATCH0/1 publish. Dynamic allocations occur here per "dynamic + * allocations occur after READY" (Main): the 'DDM ' pool, the 'IPC ' + * surface, and the trust-bounded fw-requested HEAP surface. Every + * allocation is wedged-pin owned from here on (held while + * cpu_started; reboot reclaims). Publishes the pool DVA (suballoc at + * offset 0) as the SCRATCH0/1 halves. + */ +static void *ane_boot_alloc(void *ctx, u64 size, u64 *iova) +{ + struct ane_t6021 *ane = ctx; + dma_addr_t d = 0; + void *p = dma_alloc_coherent(ane->dev, size, &d, GFP_KERNEL); + + if (p && !ane_t6021_fw_alias_iova_ok(ane, d, size)) { + dev_err(ane->dev, + "boot alloc %#llx+%#llx overlaps fw alias — refusing\n", + (u64)d, size); + dma_free_coherent(ane->dev, size, p, d); + return NULL; + } + + *iova = p ? d : 0; + return p; +} + +/* Kernel prepare: live SCRATCH3/SCRATCH1 reads feed the SHARED + * assembly (ane_t6021_boot_prepare_publish) with the dma_alloc hook — + * the same path the fake-MMIO trace test exercises. Allocations are + * wedged-pin owned from creation (held while cpu_started). + */ +static int ane_t6021_boot_prepare(void *ctx, u32 *lo, u32 *hi) +{ + struct ane_t6021_boot_mmio *mm = ctx; + struct ane_t6021 *ane = mm->ane; + void __iomem *eng = ane->base[ANE_T6021_REG_ENGINE]; + struct ane_t6021_init_sources src = boot_sources; + struct ane_t6021_boot_allocs a; + u32 request, scratch0, scratch1; + int err; + + if (!ane_t6021_boot_preflight_complete()) + return -ENODATA; /* belt: run() already gated */ + + /* dynamic reads (post-READY, live cells — never hardcoded): + * read order SCRATCH0 then SCRATCH1 (0x95ea0d8/0x95ea100); + * SCRATCH0 >= 0x21 refuses before allocations/publication; + * SCRATCH3 = fw extra-heap request; SCRATCH1+1 = ordinal. + */ + scratch0 = readl(eng + ANE_MBI_SCRATCH0); + scratch1 = readl(eng + ANE_MBI_SCRATCH0 + 4); + request = readl(eng + ANE_MBI_SCRATCH0 + 4 * 3); + + src.fw_dva = ane->fw_iova; + err = ane_t6021_boot_prepare_publish(&src, request, scratch0, + scratch1, 0x4000, + ANE_T6021_BOOT_IPC_CEILING, + ANE_T6021_BOOT_HEAP_CEILING, + ane, ane_boot_alloc, &a, + lo, hi); + if (!err && boot_prevent_nap) { + ((u8 *)a.pool)[ANE_T6021_INIT_TEMPLATE_OFF + 0x84] |= 1; + dev_info(ane->dev, "LAB init resource[0x84] bit0=1: prevent nap\n"); + } + /* OWNERSHIP TRANSFER on EVERY path (Main lifetime review): an + * error after the pool/ipc allocations must NOT lose them — a + * started CPU may already be fetching, so partial allocations + * are RETAINED (wedged-pin holds them; reboot reclaims), never + * freed on this path. + */ + ane->boot_pool = a.pool; + ane->boot_pool_iova = a.pool_dva; + ane->boot_ipc = a.ipc; + ane->boot_ipc_iova = a.ipc_dva; + ane->boot_ipc_size = a.ipc_size; + ane->boot_heap = a.heap; + ane->boot_heap_iova = a.heap_dva; + ane->boot_heap_size = a.heap_size; + return err; +} + +/* Dispatch the resolved sequence against the kernel io backend. All + * gates were checked by the caller; the run() core re-checks. After + * the CPU release there is NO ordinary unwind: failures HOLD state + * (wedged-pin cleanup refuses to free under a started CPU) and the + * probe binds fenced. + */ +/* Poll-A-timeout progress dump — PROVEN-readable observables ONLY + * (Main review 2026-09-26): all eight SCRATCH cells (pulse-cleared to 0 + * pre-release, so any nonzero word with SCRATCH7 != READY/WAKE is a + * candidate firmware store), RVBAR, CPU_STATUS, and the 24 MHz domain + * tick at engine+0x1160008 (watched advancing post-release in the + * 2026-09-25 handshake receipt; a static tick separates "ASC domain + * unclocked" from "clocked but silent"). + * + * Deliberately NOT read: engine+0x1140008 (the 13.5 stub's VM 0x30c + * store target). Its readability, width and reset value are unproven + * and no pre-release baseline exists, so an after-value would not + * locate PC (could be preexisting iBoot state, write-only, or + * normalized). + */ +static void ane_t6021_boot_progress_dump(struct ane_t6021 *ane) +{ + void __iomem *eng = ane->base[ANE_T6021_REG_ENGINE]; + u32 tick0 = readl(eng + ANE_T6021_BOOT_REG_TICK); + u32 tick1; + unsigned int i; + + msleep(20); + tick1 = readl(eng + ANE_T6021_BOOT_REG_TICK); + + for (i = 0; i < 8; i++) + dev_emerg(ane->dev, "PROGRESS SCRATCH%u=%08x\n", i, + readl(eng + ANE_T6021_BOOT_REG_SCRATCH0 + 4 * i)); + dev_emerg(ane->dev, + "PROGRESS rvbar=%016llx cpu_status=%08x tick %08x->%08x (%s)\n", + readq(eng + ANE_ASC_RVBAR), + readl(eng + ANE_ASC_CPU_STATUS), + tick0, tick1, + tick1 != tick0 ? "24MHz domain clocked" : "tick STATIC"); +} + +int ane_t6021_boot_start(struct ane_t6021 *ane, int stop_after, int table_mode, int rtb_mode) +{ + struct ane_t6021_boot_mmio mm = { .ane = ane }; + struct ane_t6021_boot_io io = { + .ctx = &mm, + .rd32 = ane_boot_rd32, .rd64 = ane_boot_rd64, + .wr32 = ane_boot_wr32, .wr64 = ane_boot_wr64, + .publish_barrier = ane_boot_publish_barrier, .poll_wait = ane_boot_wait, + .phase = ane_boot_phase, + .prepare = ane_t6021_boot_prepare, + }; + struct ane_t6021_boot_cfg cfg = { + .preflight_ok = ane_t6021_boot_preflight_complete(), + .preboot_table_mode = table_mode, + .fw_dva = ane->fw_iova, + .stop_after = stop_after, + .rtb_mode = rtb_mode, + }; + int cs = 0, fa = 0, bo = 0; + u64 sres = 0; + int r; + + /* Wedged-pin module lifetime (Main lifetime review): the ref is + * acquired BEFORE the first write — a started CPU can never + * outlive the pin, and a dying module refuses the boot before + * any write happens. Retained on CPU start (never released: + * intentional); released only if no CPU start occurred. + */ + if (!try_module_get(THIS_MODULE)) { + dev_err(ane->dev, + "boot: REFUSED before any write — module ref unavailable (dying); no CPU start possible from a dying module\n"); + return -EBUSY; + } + + dev_emerg(ane->dev, + "BOOT-PHASE dispatch (stop_after=%d%s)\n", stop_after, + stop_after ? " BISECT STOP ARMED" : ""); + + r = ane_t6021_boot_run(&io, &cfg, &cs, &fa, &bo, &sres); + + ane->cpu_started = cs; + ane->fw_alive = fa; + ane->booted = bo; + ane->boot_scratch_result = sres; + + /* Released CPU without READY (poll-A timeout, either transport + * mode): capture the 13.5 execution-progress observables NOW, + * while the islands are powered — this is the exact-progress + * datum the next pre-Linux capture cross-checks. + */ + if (cs && !fa) + ane_t6021_boot_progress_dump(ane); + + if (!cs) { + /* no CPU start: full release path, normal ownership */ + module_put(THIS_MODULE); + dev_emerg(ane->dev, + "BOOT-PHASE done r=%d cpu_started=0 (no CPU release: state clean, module unpinned)\n", + r); + return r; + } + + /* started CPU: retain the pin for the whole wedged lifetime. + * Residual: DT hotplug unbind cannot be fully prevented; devm + * release order frees irq before ioremap (probe-order reverse); + * DMA surfaces are wedge-held, never freed. + */ + dev_warn(ane->dev, + "boot: module PINNED until reboot (started CPU; wedged-pin)\n"); + + if (r == -ENODATA) + return r; /* unreachable: the caller gated */ + if (r && cs) { + dev_err(ane->dev, + "boot: sequence error %d AFTER CPU start (cpu_started=%u fw_alive=%u booted=%u scratch_result=%016llx) — WEDGED-PIN HOLD: all surfaces/rings/IRQ/links preserved; reboot is the only reclamation; no retry. HANDSHAKE state only: the result word has NO sourced success semantics\n", + r, cs, fa, bo, sres); + return 0; /* bind fenced, state held */ + } + if (!r) + dev_info(ane->dev, + "boot: run returned 0 (booted=%u fw_alive=%u) — %s; scratch_result=%016llx (raw device address, semantics UNSOURCED — not a success claim; transport stays fenced until response validation)\n", + bo, fa, + bo ? "DONE observed — handshake complete" + : "rc 0 WITHOUT DONE (rtb_mode: HELLO-gated; DONE not part of this mode)", + sres); + return r; +} + diff --git a/drivers/accel/ane/ane_t6021_boot.h b/drivers/accel/ane/ane_t6021_boot.h new file mode 100644 index 0000000000000..ced0c997439dd --- /dev/null +++ b/drivers/accel/ane/ane_t6021_boot.h @@ -0,0 +1,832 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * ane_t6021_boot.h — T6021 legacy-boot contract units (pure, shared by + * the kernel sequencer and the userspace regression). + * + * Byte anchors (KC kernelcache.release.mac14j sha256 8304156f…, selene + * sha256 9f7915c4…; receipts under ane-linux-experiments/receipts/, + * commits 3762aee + 12be074): + * - RVBAR fold: ANEHWDevice::ANE_Init 0x95e9850–0x95e9988 (K13 + * 0x93203b0–0x93204e0 identical). Read64 of eng+0x01050000; bit0 + * set skips the write (live jw14m2 read 0x1). Otherwise write64 + * ENTRY_BASE | (fw DVA & ADDR_MASK) — single u64 store + * (2026-09-20-h14-rvbar-width.json width_proof). + * - fw DVA = ANESharedMemorySurfaceParams("FWIM")+0x18, produced by + * dartMapMemoryDescriptor (vtable slot 0x8a8, genIOVMSegments) for + * the out-param installed at start+0x336c (mapper-callchain audit + * pass1–3). Linux correspondence: dma_alloc_coherent on the ane + * platform device is dart-ane0-translated (live iommu group 6, + * three apple,t6020-dart streams, DMA domain). + * - SCRATCH0/1 u64 split: low32 → 0x01840048 first, high32 → + * 0x0184004c, dsb st before (legacy-init-publication receipt, + * accessor write32 width-proven at 0x9622d4c). + * - 0x174 init suballocation: header[0x00] u64 = fw DVA (legacy + * branch, dev+0x780 bit0 clear = observed AppleARMIODevice + * provider), [0x68] u32 = 64 count, template 256 B at + * [0x6C,0x16C) with template+0xC0 = 4 RESOLVED (Main raw anchors + * 0x9612b78/7c/80 on the dev+0x998 template; conditional |=0x10 + * separate, unqualified, not set). + * + * This header intentionally includes nothing. Kernel consumers have + * already; userspace consumers typedef u8/u32/u64 and + * include first (tools/h14_boot_regression.c in this + * repository is the shipped runnable check). + */ +#ifndef __ANE_T6021_BOOT_H__ +#define __ANE_T6021_BOOT_H__ + +/* RVBAR entry fold (ANE_Init 0x95e9868–0x95e988c). The mask clears + * bits 0–10, 48 and 55 — bit 11 IS retained (0xf800 keeps 0x800); the + * base supplies bit0 and the fixed upper pattern. + */ +#define ANE_T6021_RVBAR_ENTRY_BASE 0x0081000000000001ULL +#define ANE_T6021_RVBAR_ADDR_MASK 0xff7efffffffff800ULL + +/* CPU_CONTROL release (rvbar-width local order: write32 0 then 0x10; + * h14g config selects eng+0x01400044). RUN = BIT(4). + */ +#define ANE_T6021_CPU_RUN_RELEASE 0x10 + +/* SCRATCH7 handshake words (InitializeRTBuddy / legacy ANE_Init + * publication; selene ack writer 0x77c8). + */ +/* SCRATCH0 request band (pass9-corrected, Main raw trace): post-READY + * SCRATCH0 >= 0x21 REFUSES the boot preparation; below 0x21 proceeds + * to the MAX/alloc path. + */ +#define ANE_T6021_BOOT_IPC_REQ_THRESHOLD 0x21U + +#define ANE_T6021_BOOT_WAKE_REQ 0xf7fbdff9U +#define ANE_T6021_BOOT_ACK 0x08042006U + +/* Init suballocation geometry (ANE_Init 0x95ea710–0x95ea97c; + * legacy-init-publication receipt). + */ +#define ANE_T6021_INIT_STRUCT_SIZE 0x174 +#define ANE_T6021_INIT_FW_DVA_OFF 0x00 /* u64, legacy branch */ +#define ANE_T6021_INIT_COUNT_OFF 0x68 /* u32 = 64 */ +#define ANE_T6021_INIT_COUNT 0x40 +#define ANE_T6021_INIT_TEMPLATE_OFF 0x6c /* 256 B at [0x6C,0x16C) */ +#define ANE_T6021_INIT_TEMPLATE_SIZE 0x100 +#define ANE_T6021_INIT_TBIT_OFF 0xc0 /* template-relative */ +#define ANE_T6021_INIT_TBIT_VAL 0x4 /* RESOLVED (Main raw + * anchors 0x9612b78/7c/80: + * ldr/orr#4/str on the dev+0x998 + * template); the conditional + * |=0x10 is a separate, still + * unqualified mutation and is + * NOT set + */ + +static inline u64 ane_t6021_rvbar_compose(u64 iova) +{ + return ANE_T6021_RVBAR_ENTRY_BASE | (iova & ANE_T6021_RVBAR_ADDR_MASK); +} + +/* The kext skip condition: bit0 of the RVBAR read (tbnz w0,#0 at + * ANE_Init 0x95e9878; live jw14m2 reads have been 0x1). What a set + * bit names in boot-mode terms is the open lifecycle fork — see + * ane_t6021_boot.c; this predicate only decodes the bit. + */ +static inline bool ane_t6021_rvbar_latched(u64 rd) +{ + return rd & 1; +} + +/* Entry bits of an RVBAR read (what the fold would have named). */ +static inline u64 ane_t6021_rvbar_entry_bits(u64 rd) +{ + return rd & ANE_T6021_RVBAR_ADDR_MASK; +} + +/* Boot acceptance predicate — the EXACT check the boot path applies + * to a staged fw DVA: the fold must lose nothing. Bit 11 is retained; + * bits 0-10, 48 and 55 are not, so an iova with any of them set is + * rejected rather than silently truncated. + */ +static inline bool ane_t6021_rvbar_entry_ok(u64 iova) +{ + return (iova & (u64)~ANE_T6021_RVBAR_ADDR_MASK) == 0; +} + +/* Publication convention: low32 → SCRATCH0 (0x01840048) first, then + * high32 → SCRATCH1, after dsb st. + */ +static inline void ane_t6021_scratch64_split(u64 v, u32 *lo, u32 *hi) +{ + *lo = (u32)(v & 0xffffffffU); + *hi = (u32)(v >> 32); +} + +static inline u64 ane_t6021_scratch64_join(u32 lo, u32 hi) +{ + return ((u64)hi << 32) | lo; +} + +/* Linux sources for the init-suballocation fields (pass5b/5c/5d + * b8b7c35 + pass6c 75a017b; validator tools/check_init_contract.py + * 68/68). EVERY fw-read field is explicitly sourced from the struct + * below — nothing is silently zero: [0x00] FWIM DVA, [0x08] 'IPC ' + * surface DVA (Linux alloc, size = ane_t6021_ipc_size), [0x10] + * config+0x138 = 0x500000, [0x18] = 0x10000000 - size, [0x20] obj2 + * DVA, [0x28] w22, [0x30] fw-load progress, [0x50] zext [x23+4], + * [0x58] pool DMA base, [0x60] pool word0, [0x68] count 64, + * template[0x00] = 0, template+0xC0 = 4. The struct values pin BEFORE + * the preflight gate can open (Main: no unresolved field silently + * zero; no partial boot). The caller MUST zero the full 0x174 block + * first (coherent alloc): gaps [0x34..37]/[0x64..67] get no kext + * store and sit inside fw-read u64 units. + */ +/* Init-suballocation contract — pass6 producer semantics + * (rvbar-lifecycle-evidence.json pass6_init_header_producers, commit + * cd25b46, anchors G1-G26; 87/87 total): + * + * STATIC sources (pinned before the preflight can open): + * fw_dva -> [0x00] staged selene ('FWIM') surface DVA, + * ipc_dva -> [0x08] 'IPC ' surface DVA (its size calc remains + * the audit lane's open item), + * cfg_size -> [0x10] config+0x138 = 0x500000; [0x18] = + * 0x10000000 - cfg_size = 0x0fb00000, + * prev_fw_len -> [0x30] previous fw image length (0 on first boot; + * driver-static, updated on each reload), + * heap_floor -> [0x28] floor = config field dev+0x3A90 (value + * pinned by the audit lane at preflight close), + * pool_dma -> [0x58] the 'DDM ' pool surface DVA (Linux allocates + * its own 0x40000-byte DDM pool — the kext size), + * pool_word0 -> [0x60] first qword of the Linux pool-descriptor + * struct. NOT CLOSED: the fw-side consumer of + * pool+0x00 is untraced and the kext never stores it + * (free-list head at manager+0 untouched by + * Allocate). This value is a HARD-GATED source — the + * sequence cannot run until a producer/consumer proof + * pins it; no hypothesis value is shipped. + * PRODUCER OPEN (Main, superseding b21e23f): the + * "pool+0x00 = manager free-list head" claim is + * REJECTED — manager dev+0x968 != Params pool + * dev+0x980 (wrong-object alias likely), and + * Reset6cb048d shows the consumer stores word0 + * VERBATIM at image ops 68 (possible extent use). + * Wait for the exact same-Params producer. + * + * DYNAMIC inputs (read AFTER poll A — the fw publishes its extra-heap + * request into SCRATCH3 (cell idx3) and its boot ordinal is + * SCRATCH1+1; both read from the live cells, never hardcoded): + * scratch3_req -> the fw extra-heap request; 0 = no heap surface, + * scratch1_read -> SCRATCH1 read; [0x50] = (u32)read + 1 (boot + * ordinal). + * + * TRUST BOUNDARY: scratch3_req is firmware-supplied. The heap size + * must pass ane_t6021_heap_size() bounds BEFORE any allocation; the + * heap DVA and size are written to [0x20]/[0x28] only on success. + */ +struct ane_t6021_init_sources { + u64 fw_dva; + u64 ipc_dva; + u32 cfg_size; + u32 prev_fw_len; + u64 heap_floor; + u64 pool_dma; + u64 pool_word0; +}; + +/* 'IPC ' surface size (CURRENT_CONTRACT f9602e0; operands proven: + * u64[dev+0x3A90] = IODARTMapper::getPageSize() — 0x4000, one 16K + * DART page, typical; u32[x23+4] = captured SCRATCH1 + 1, the boot + * ordinal): size = max(page_size, ordinal + 1). Used by the kernel + * prepare hook to size the 'IPC ' allocation. + */ +/* SCRATCH0 read-order note (pass9 phase-1: SCRATCH0 then SCRATCH1 + * after READY): Main raw branch proof SUPERSEDES the audit's + * "SCRATCH0 >= 0x21 arms IPC" reading — 0x95ea1dc b.cc(low) branches + * TO the MAX+IPC-alloc path and >=0x21 goes to logging/error, so + * scratch0 < 33 is likely a VALIDITY gate, not an optional-IPC + * condition. Header [0x08] unconditionally dereferences + * dev+0x988+0x18. Allocation stays UNCONDITIONAL until Reset corrects + * the source; the threshold is NOT implemented. + */ +static inline u64 ane_t6021_ipc_size(u64 page_size, u32 captured) +{ + /* EXACT u32 semantics: the fw-visible ordinal is the captured + * SCRATCH1 value + 1 in 32-bit arithmetic (kext add w8,w0,#1) — + * it wraps. Callers pass the CAPTURED value, never pre-incremented. + * The result is then bounded by ANE_T6021_BOOT_IPC_CEILING at the + * allocation site: captured is fw-supplied and untrusted. + */ + u32 ord = captured + 1; + + return page_size > (u64)ord ? page_size : (u64)ord; +} + +/* Operational ceiling for the fw-influenced 'IPC ' allocation + * (captured is untrusted; the max() can otherwise be forced to an + * arbitrary size). Distinct from ABI width — documented budget. + */ +#define ANE_T6021_BOOT_IPC_CEILING 0x100000ULL /* 1 MiB */ + +/* Trust boundary for the firmware-supplied heap request: 0 disables + * the heap surface; otherwise the size is MAX(request, floor) and is + * refused (negative) when the request exceeds the ceiling. + * + * ANE_T6021_BOOT_HEAP_CEILING is an OPERATIONAL RESOURCE BUDGET, kept + * distinct from ABI width: header [0x28] is a u64 field and can + * express far larger values — the u64-ness says nothing about what is + * safe to allocate. The dart-ane0 vm window only bounds ADDRESSABILITY, + * not allocation safety, so it is deliberately not used as the + * ceiling. 32 MiB is the documented budget bounding a firmware-supplied + * allocation to a size the host can honor without starving; re-anchor + * to a config field when the h14g blob map lands. + */ +#define ANE_T6021_BOOT_HEAP_CEILING 0x02000000ULL /* 32 MiB budget */ + +static inline long long +ane_t6021_heap_size(u32 scratch3_req, u64 floor, u64 max_size) +{ + u64 req = scratch3_req; + + if (!req) + return 0; + if (req > max_size) + return -E2BIG; + return (long long)(req > floor ? req : floor); +} + +/* Fill the COMPLETE init suballocation from the static sources plus + * the post-READY dynamic values. The caller MUST zero the full 0x174 + * block first (coherent alloc): the gap bytes [0x34..37]/[0x64..67] + * get no kext store and sit inside fw-read u64 units. + */ +static inline void +ane_t6021_init_struct_fill(u8 *buf, const struct ane_t6021_init_sources *s, + long long heap_size, u64 heap_dva, + u32 boot_ordinal) +{ + u64 size = s->cfg_size; + int i; + + for (i = 0; i < 8; i++) { + buf[ANE_T6021_INIT_FW_DVA_OFF + i] = + (u8)(s->fw_dva >> (8 * i)); + buf[0x08 + i] = (u8)(s->ipc_dva >> (8 * i)); + buf[0x10 + i] = (u8)(size >> (8 * i)); + buf[0x18 + i] = (u8)((0x10000000ULL - size) >> (8 * i)); + buf[0x20 + i] = (u8)(heap_dva >> (8 * i)); + buf[0x50 + i] = (u8)((u64)boot_ordinal >> (8 * i)); + buf[0x58 + i] = (u8)(s->pool_dma >> (8 * i)); + buf[0x60 + i] = (u8)(s->pool_word0 >> (8 * i)); + } + + /* [0x28] u64 heap size (0 when the fw requested none) */ + for (i = 0; i < 8; i++) + buf[0x28 + i] = (u8)((u64)heap_size >> (8 * i)); + + /* [0x30] u32 FULL width: previous fw image length (0 first + * boot). Main review: low-byte-only serialization dropped the + * upper length bits. + */ + buf[0x30] = (u8)s->prev_fw_len; + buf[0x31] = (u8)(s->prev_fw_len >> 8); + buf[0x32] = (u8)(s->prev_fw_len >> 16); + buf[0x33] = (u8)(s->prev_fw_len >> 24); + + buf[ANE_T6021_INIT_COUNT_OFF + 0] = (u8)ANE_T6021_INIT_COUNT; + buf[ANE_T6021_INIT_COUNT_OFF + 1] = 0; + buf[ANE_T6021_INIT_COUNT_OFF + 2] = 0; + buf[ANE_T6021_INIT_COUNT_OFF + 3] = 0; + + /* template[0x00] = config word [dev+0x1D8], pinned value 0 + * (pass5d); [0x04..0x0B] zero via the caller's zeroing. + */ + buf[ANE_T6021_INIT_TEMPLATE_OFF + 0] = 0; + buf[ANE_T6021_INIT_TEMPLATE_OFF + 1] = 0; + buf[ANE_T6021_INIT_TEMPLATE_OFF + 2] = 0; + buf[ANE_T6021_INIT_TEMPLATE_OFF + 3] = 0; + + /* template+0xC0 = 4: RESOLVED initial state (Main raw anchors + * 0x9612b78/7c/80). The conditional |=0x10 remains unset. + */ + buf[ANE_T6021_INIT_TEMPLATE_OFF + ANE_T6021_INIT_TBIT_OFF + 0] = + ANE_T6021_INIT_TBIT_VAL; +} + +/* ---- Shared prepare-source assembly ---- + * + * The ALLOCATION-SIZING + HEADER-FILL + PUBLISH-VALUE path used by the + * kernel prepare hook AND the fake-MMIO trace test — one + * implementation, so wrong-DVA / double-increment / unbounded-size + * classes fail in the host trace test instead of only on hardware. + * + * Allocation contract: alloc(ctx, size, &iova) is called in the order + * pool (0x40000), 'IPC ' (max(DART page 0x4000, ordinal+1)), HEAP + * (0 when the fw requested none); each must return NULL on failure + * and set *iova to the device-visible address of the returned memory + * (the DMA address, NOT a recorded constant). Refusal classes: the + * fw-supplied request and captured value are UNTRUSTED — over-ceiling + * heap requests and over-budget IPC sizes are refused BEFORE any + * allocation. + */ +struct ane_t6021_boot_allocs { + u64 pool_dva, ipc_dva, heap_dva; + u64 ipc_size, heap_size; + void *pool, *ipc, *heap; +}; + +static inline int +ane_t6021_boot_prepare_publish(const struct ane_t6021_init_sources *s, + u32 scratch3_req, u32 scratch0_read, + u32 scratch1_read, + u64 page_size, u64 ipc_ceiling, + u64 heap_ceiling, + void *alloc_ctx, + void *(*alloc)(void *ctx, u64 size, + u64 *iova), + struct ane_t6021_boot_allocs *a, + u32 *lo, u32 *hi) +{ + int i; + + for (i = 0; i < (int)(sizeof(*a) / sizeof(u64)); i++) + ((u64 *)a)[i] = 0; + + /* SCRATCH0 band check — REFUSAL before allocations/publication + * (Main raw trace: >= 0x21 -> 0x95ea2a0 log -> 0x2c4 -> 0x3330 + * error, w21 = 0xE00002DA; < 0x21 -> 0x214 MAX -> 0x25c alloc -> + * 0x260 -> 0x2c8). Boundary: 0x20 accepted, 0x21 refused. + * Read order: SCRATCH0 first, then SCRATCH1 (0x95ea0d8/0x95ea100). + * Untrusted-input sizing after the band check; heap_size() + * returns SIGNED (negative = refused) — kept local so a refusal + * cannot wrap into the u64 record. + */ + if (scratch0_read >= ANE_T6021_BOOT_IPC_REQ_THRESHOLD) + return -EPROTO; + a->ipc_size = ane_t6021_ipc_size(page_size, scratch1_read); + if (a->ipc_size > ipc_ceiling) + return -E2BIG; + { + long long heap = ane_t6021_heap_size(scratch3_req, + s->heap_floor, + heap_ceiling); + + if (heap < 0) + return (int)heap; + a->heap_size = (u64)heap; + } + + a->pool = alloc(alloc_ctx, 0x40000, &a->pool_dva); + if (!a->pool) + return -ENOMEM; + a->ipc = alloc(alloc_ctx, a->ipc_size, &a->ipc_dva); + if (!a->ipc) + return -ENOMEM; + if (a->heap_size) { + a->heap = alloc(alloc_ctx, a->heap_size, &a->heap_dva); + if (!a->heap) + return -ENOMEM; + } + + /* ordinal: exact u32 +1 on the READ SCRATCH1 value (kext add + * w8,w0,#1; callers pass the read value, never pre-incremented). + * HEADER SOURCES come from the ALLOCATIONS: s->ipc_dva/pool_dma + * may be zero in the caller's static sources — fill from the + * allocator outputs (a->ipc_dva/a->pool_dva), never from s + * (Main review: zero-DVA header bug). + */ + { + struct ane_t6021_init_sources filled = *s; + + filled.ipc_dva = a->ipc_dva; + filled.pool_dma = a->pool_dva; + ane_t6021_init_struct_fill(a->pool, &filled, a->heap_size, + a->heap_dva, + (u32)(scratch1_read + 1)); + } + *lo = (u32)(a->pool_dva & 0xffffffffU); + *hi = (u32)(a->pool_dva >> 32); + return 0; +} + +/* Post-DONE SCRATCH1:SCRATCH0 (read SCRATCH1 first, then SCRATCH0) + * is a fw-produced DEVICE ADDRESS (pass9 phase-2), NOT a return code — + * never dereference it raw. WHITELIST (Main 2026-09-20): only the + * Linux-owned FWIM and 'IPC ' windows may ever be matched against it; + * the 'DDM ' pool is NOT whitelisted. No consumption until range AND + * length checks are proven; until then the raw u64 is stored and + * logged only. + */ + +/* ---- Fake-MMIO-testable sequence core ---- + * + * Register offsets (ENGINE-relative; the Linux driver maps the engine + * window, so kernel offsets == trace offsets) and the io backend. + * ane_t6021_boot_run() executes the resolved total order against ANY + * backend: the kernel wraps readl/writeq/udelay; the host regression + * wraps a recording fake (trace asserts: full order, no writes when + * the preflight gate is closed, publish strictly after poll A). + */ + +#define ANE_T6021_BOOT_REG_TABLE0 0x00000b38 +#define ANE_T6021_BOOT_REG_TABLE1 0x00000b98 +#define ANE_T6021_BOOT_REG_TABLE2 0x00000bf8 +#define ANE_T6021_BOOT_REG_RVBAR 0x01050000 +#define ANE_T6021_BOOT_REG_CPUCTRL 0x01400044 +#define ANE_T6021_BOOT_REG_SCRATCH0 0x01840048 +#define ANE_T6021_BOOT_REG_SCRATCH1 0x0184004c +#define ANE_T6021_BOOT_REG_SCRATCH6 0x01840060 +#define ANE_T6021_BOOT_REG_SCRATCH7 0x01840064 +/* 13.5 stub execution-progress observables (M2StartupRecovery 2026-09-26 + * decode of a9c4b771294a6b11…). Only PROVEN-readable engine-window + * registers: the 24 MHz domain tick at VM 0x1160008 (watched advancing + * ~24 MHz post-release, 2026-09-25 handshake receipt) plus SCRATCH, + * RVBAR and CPU_STATUS already on the whitelist. The stub's VM 0x30c + * store to engine+0x1140008 is real, but the register's readability, + * width and reset state are UNPROVEN and no pre-release baseline exists + * — it is deliberately NOT read here (Main review 2026-09-26). + */ +#define ANE_T6021_BOOT_REG_TICK 0x01160008 +#define ANE_T6021_BOOT_TABLE_VALUE 0x01ff01ffU +#define ANE_T6021_BOOT_TABLE_POLLS 1000 + +struct ane_t6021_boot_io { + void *ctx; + u32 (*rd32)(void *ctx, unsigned int off); + u64 (*rd64)(void *ctx, unsigned int off); + void (*wr32)(void *ctx, unsigned int off, u32 v); + void (*wr64)(void *ctx, unsigned int off, u64 v); + void (*publish_barrier)(void *ctx); /* orders the coherent fill + * before the device publish: + * dma_wmb() = dmb oshst on + * arm64; NOT claimed as dsb st + * (completion) + */ + void (*phase)(void *ctx, const char *what); /* bounded phase log: + * emitted ONCE before each + * write/poll block so a crash + * source survives netconsole + * (never per-poll) + */ + void (*poll_wait)(void *ctx); /* 1 ms poll delay */ + /* prepare(): called once, strictly AFTER poll A and BEFORE the + * SCRATCH0/1 publish; returns the suballoc DVA halves. Kernel + * backend: allocate pool/IPC + fill from pinned sources. + */ + int (*prepare)(void *ctx, u32 *lo, u32 *hi); +}; + +struct ane_t6021_boot_cfg { + int preflight_ok; /* EVERY prerequisite closed (Main: no + * partial boot — the whole sequence or + * nothing) + */ + int preboot_table_mode; /* LIVE-FAULT gating of the pre-CPU table + * block (2026-09-20 wedge): + * 0 = ABORT: -EAGAIN, zero writes + * (accidental-repeat prevention), + * 1 = WRITE the table block (re-armed + * after the table-base analysis), + * 2 = SKIP the table block, run the rest + * (diagnostic: tests fw-alive without + * the kext pre-CPU config). + */ + u64 fw_dva; /* staged surface DVA (fold input) */ + int rtb_mode; /* 1 = S1 writes SCRATCH6=0 (RTBuddy/RTKit-app- + * endpoint select, fw 0x42c8) instead of 1 + * (legacy ChMan/MBI). In RTBuddy mode the fw + * may skip READY/DONE; listen on mailbox. + * Run contract: P4 READY is recorded, not + * required; no legacy publish/wake runs; + * aliveness is gated by the RTKit HELLO. + */ + int stop_after; /* fw-start-debug step bisect (2026-09-22): + * 0 = full run; N in 1..4 = stop AFTER + * step N completes, return -ECANCELED + * (1 grant tunables, 2 scratch, 3 rvbar, + * 4 cpu release + poll A). A poll-A + * timeout inside step 4 still returns + * -ETIMEDOUT — the timeout is the + * answer. Steps complete = writes done; + * the stop never splits a step. + */ +}; + +/* Ownership: a started CPU may be fetching from the staged surfaces — + * the DMA memory is NOT reclaimable on failure/remove while + * cpu_started; reclaimable only via the domain-off reset (reboot). + */ +static inline int ane_t6021_boot_dma_reclaimable(int cpu_started) +{ + return !cpu_started; +} + +/* The cleanup decision the predicate implements: while cpu_started, + * remove() is HELD (H13 wedged-pin pattern — surfaces, rings, IRQ and + * power-domain links preserved; reboot reclaims). + */ +static inline int ane_t6021_boot_remove_held(int cpu_started) +{ + return cpu_started; +} + +/* Returns 0 (DONE observed, booted), -ENODATA (preflight closed: ZERO + * io writes), or -ETIMEDOUT (poll A/B: cpu_started holds, DMA stays + * unreclaimable, no publish/wake happened on poll A timeout). + */ +static inline int +ane_t6021_boot_run(const struct ane_t6021_boot_io *io, + const struct ane_t6021_boot_cfg *cfg, + int *cpu_started, int *fw_alive, int *booted, + u64 *scratch_result) +{ + unsigned int i; + u32 v; + u64 rvbar; + + *cpu_started = 0; + *fw_alive = 0; + *booted = 0; + *scratch_result = 0; + + /* Main: all gates checked BEFORE any boot write — no partial + * sequence when the preflight is closed. + */ + if (!cfg->preflight_ok) + return -ENODATA; + + /* pre-CPU engine table (pass4 receiver, pass5 gate: REQUIRED + * every EnableANEClocksAndPower; residual alias/indirect writer + * risk documented in the preflight list). + * LIVE-FAULT 2026-09-20: this block wedged the machine (P0 then + * silence — stall could be the FIRST write; P1 never reached; + * hardware reset 16:24:08) — pf_preboot_table_safe gates it + * OFF; nothing below runs until re-armed. + */ + switch (cfg->preboot_table_mode) { + case 0: + return -EAGAIN; /* BEFORE any write: accidental-repeat + * prevention (Main 2026-09-20) + */ + case 1: + io->phase(io->ctx, "P0 preboot-table"); + io->phase(io->ctx, "P0-1 eng+0xb38"); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_TABLE0, + ANE_T6021_BOOT_TABLE_VALUE); + io->phase(io->ctx, "P0-2 eng+0xb98"); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_TABLE1, + ANE_T6021_BOOT_TABLE_VALUE); + io->phase(io->ctx, "P0-3 eng+0xbf8"); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_TABLE2, + ANE_T6021_BOOT_TABLE_VALUE); + break; + case 2: + default: + /* diagnostic skip: NO table writes — tests fw-alive + * without the kext pre-CPU config (user override + * 2026-09-20). + */ + io->phase(io->ctx, "P0 table SKIPPED (diagnostic)"); + break; + } + + /* P-1: W8 write-grant tunables (proven no-abort class, + * w8-run.out: APERTURE_UNLOCKED — 12 engine-aperture writes + * preparing the aperture; replayed verbatim). + * Per-write before/after discrimination (Main: attempt 3 stalled + * LAST phase = P-1, possibly FIRST tunable write). + */ + { + static const struct { u32 off; u32 val; } tun[] = { + { 0x000, 0x00000010 }, { 0x038, 0x00050020 }, + { 0x03c, 0x000a0030 }, { 0x400, 0x40010001 }, + { 0x600, 0x01ffffff }, { 0x738, 0x00200020 }, + { 0x798, 0x00100030 }, { 0x7f8, 0x0100000a }, + { 0x900, 0x00000101 }, { 0x410, 0x00001100 }, + { 0x420, 0x00001100 }, { 0x430, 0x00001100 }, + }; + unsigned int ti; + + io->phase(io->ctx, "P-1 grant-tunables begin"); + for (ti = 0; ti < sizeof(tun) / sizeof(tun[0]); ti++) { + io->phase(io->ctx, tun[ti].off == 0x000 ? + "P-1a eng+0x000" : + tun[ti].off == 0x038 ? "P-1b eng+0x038" : + tun[ti].off == 0x03c ? "P-1c eng+0x03c" : + tun[ti].off == 0x400 ? "P-1d eng+0x400" : + tun[ti].off == 0x600 ? "P-1e eng+0x600" : + tun[ti].off == 0x738 ? "P-1f eng+0x738" : + tun[ti].off == 0x798 ? "P-1g eng+0x798" : + tun[ti].off == 0x7f8 ? "P-1h eng+0x7f8" : + tun[ti].off == 0x900 ? "P-1i eng+0x900" : + tun[ti].off == 0x410 ? "P-1j eng+0x410" : + tun[ti].off == 0x420 ? "P-1k eng+0x420" : + "P-1l eng+0x430"); + io->wr32(io->ctx, tun[ti].off, tun[ti].val); + io->phase(io->ctx, "P-1 write done"); + } + io->phase(io->ctx, "P-1 grant-tunables end"); + } + if (cfg->stop_after == 1) + return -ECANCELED; /* tunables done, nothing else fired */ + + io->phase(io->ctx, "P1 scratch-clear+pulse"); + /* S1: InitANEScratchRegisters — clear ALL cells, SCRATCH6 = rtb_mode ? 0 (RTBuddy) : 1 + * (legacy ChMan/MBI); pulse SCRATCH7 1 -> 0 (stale cleared). + */ + for (i = 0; i < 8; i++) + io->wr32(io->ctx, + ANE_T6021_BOOT_REG_SCRATCH0 + 4 * i, 0); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH6, + cfg->rtb_mode ? 0 : 1); + io->phase(io->ctx, cfg->rtb_mode ? + "P1 S1 SCRATCH6=0 (RTBuddy select)" : + "P1 S1 SCRATCH6=1 (legacy ChMan/MBI select)"); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH7, 1); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH7, 0); + if (cfg->stop_after == 2) + return -ECANCELED; /* scratch programmed, CPU untouched */ + + io->phase(io->ctx, "P2 rvbar"); + /* S2: RVBAR skip-or-fold (bit0 set = lawful skip branch; no + * latch override, no reset before first attempt). + */ + rvbar = io->rd64(io->ctx, ANE_T6021_BOOT_REG_RVBAR); + if (!ane_t6021_rvbar_latched(rvbar)) + io->wr64(io->ctx, ANE_T6021_BOOT_REG_RVBAR, + ane_t6021_rvbar_compose(cfg->fw_dva)); + if (cfg->stop_after == 3) + return -ECANCELED; /* entry decision recorded, no RUN */ + + io->phase(io->ctx, "P3 cpu-release"); + /* S3: CPU release — both paths, strictly 0 then 0x10. */ + io->wr32(io->ctx, ANE_T6021_BOOT_REG_CPUCTRL, 0); + io->phase(io->ctx, "P3b cpu-release RUN=0x10"); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_CPUCTRL, + ANE_T6021_CPU_RUN_RELEASE); + *cpu_started = 1; + + io->phase(io->ctx, "P4 pollA-READY"); + /* S4: poll A — FRESH READY (the pulse made it unambiguous). + * RTBuddy mode (SCRATCH6=0, kext fw 0x42c8: rtbuddyFW when + * SCRATCH6 == 0): the fw does not publish BOOT_ACK to SCRATCH7 + * and no legacy publication follows — aliveness is gated by the + * RTKit HELLO after boot_run returns (selene InitializeRTBuddy + * 0x95ead04). A missing READY is recorded, not fatal, and + * *fw_alive stays 0 — never fabricated. + */ + for (i = 0; i < ANE_T6021_BOOT_TABLE_POLLS; i++) { + v = io->rd32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH7); + if (v == ANE_T6021_BOOT_ACK) + break; + io->poll_wait(io->ctx); + } + if (v == ANE_T6021_BOOT_ACK) { + *fw_alive = 1; + io->phase(io->ctx, "P4 pollA READY observed"); + } else if (cfg->rtb_mode) { + io->phase(io->ctx, + "P4 pollA no READY (RTBuddy: HELLO-gated)"); + return 0; /* RTBuddy: no legacy publish/wake */ + } else { + return -ETIMEDOUT; + } + if (cfg->stop_after == 4) + return -ECANCELED; /* fw alive, publish/wake withheld */ + if (cfg->rtb_mode) + return 0; /* RTBuddy: no legacy publish/wake */ + + io->phase(io->ctx, "P5 prepare+publish"); + /* S5-S6: prepare (alloc/fill; kernel backend owns DMA), then the + * publish barrier, then publish suballoc DVA low32/high32, then + * wake. Barrier semantics (Main review 2026-09-20): the kernel + * backend's dma_wmb() is dmb oshst — it ORDERS the coherent fill + * before the device publish; it is NOT the kext's dsb st (which + * additionally waits for completion). Ordering suffices for the + * Linux coherent-DMA + writel doorbell contract (writel itself + * orders prior accesses before the MMIO store); the kext dsb st + * choice is a completion guarantee this driver does not claim. + */ + { + u32 lo = 0, hi = 0; + int err = io->prepare(io->ctx, &lo, &hi); + + if (err) + return err; + io->publish_barrier(io->ctx); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH0, lo); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH1, hi); + } + io->phase(io->ctx, "P6 wake"); + io->wr32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH7, + ANE_T6021_BOOT_WAKE_REQ); + + io->phase(io->ctx, "P7 pollB-DONE"); + /* S7: poll B — DONE; read back the SCRATCH0/1 result u64. */ + for (i = 0; i < ANE_T6021_BOOT_TABLE_POLLS; i++) { + v = io->rd32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH7); + if (v == ANE_T6021_BOOT_ACK) + break; + io->poll_wait(io->ctx); + } + if (v != ANE_T6021_BOOT_ACK) + return -ETIMEDOUT; + *booted = 1; + io->phase(io->ctx, "P7 pollB DONE observed"); + + /* HANDSHAKE COMPLETE != firmware result success: the DONE ack is + * the fw's handshake word; the SCRATCH0/1 result u64 it leaves + * behind has UNSOURCED success semantics (pass6: the fw writes a + * "result" at 0x77a0 whose meaning is not decoded). Expose it + * raw; never infer success from booted alone. + */ + *scratch_result = + ((u64)io->rd32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH1) << 32) | + io->rd32(io->ctx, ANE_T6021_BOOT_REG_SCRATCH0); + return 0; +} + +/* Pinned 13.5 firmware's eight channel descriptors, captured before ACK. + * Type 0 is host-to-firmware; type 1 is firmware-to-host. + * Each ring slot is 64 bytes. The descriptor table uses 256-byte entries. + */ +#define ANE_T6021_CHMAN_ENTRY_SIZE 0x100 +#define ANE_T6021_CHMAN_NAME_LEN 0x40 +#define ANE_T6021_CHMAN_COUNT 8 +#define ANE_T6021_CHMAN_TOTAL 0x10440 + +struct ane_t6021_chman_desc { + char name[ANE_T6021_CHMAN_NAME_LEN]; + u32 type; + u32 bit; + u64 size; + u64 ring; + u8 pad[ANE_T6021_CHMAN_ENTRY_SIZE - ANE_T6021_CHMAN_NAME_LEN - 0x18]; +}; + +struct ane_t6021_chman_static { + const char *name; + u32 type; + u32 bit; + u64 size; + u32 off; /* ring offset from the IPC DVA */ +}; + +static const struct ane_t6021_chman_static +ane_t6021_chman_layout[ANE_T6021_CHMAN_COUNT] = { + { "TERMINAL", 2, 0, 0x300, 0x0800 }, + { "IO", 0, 1, 0x010, 0xc800 }, + { "DEBUG", 0, 2, 0x008, 0xcc00 }, + { "BUF_H2T", 0, 3, 0x040, 0xce00 }, + { "BUF_T2H", 1, 4, 0x040, 0xde00 }, + { "SHAREDMALLOC", 1, 5, 0x008, 0xee00 }, + { "IO_T2H", 1, 6, 0x040, 0xf000 }, + { "DATA_CHAIN_H2T", 0, 7, 0x010, 0x10000 }, +}; + +/* True when entry i of a table read from the IPC surface matches the + * static layout with the rings based at ipc_dva. + */ +static inline bool +ane_t6021_chman_entry_ok(const struct ane_t6021_chman_desc *d, + unsigned int i, u64 ipc_dva) +{ + const struct ane_t6021_chman_static *s = &ane_t6021_chman_layout[i]; + + return !strncmp(d->name, s->name, ANE_T6021_CHMAN_NAME_LEN) && + d->type == s->type && d->bit == s->bit && d->size == s->size && + d->ring == ipc_dva + s->off; +} + +/* Bitmask of mismatching entries (0 = the whole table validated). */ +static inline unsigned int +ane_t6021_chman_check(const struct ane_t6021_chman_desc *t, u64 ipc_dva) +{ + unsigned int i, bad = 0; + + for (i = 0; i < ANE_T6021_CHMAN_COUNT; i++) + if (!ane_t6021_chman_entry_ok(&t[i], i, ipc_dva)) + bad |= 1U << i; + return bad; +} + +/* Before ACK, ownership value 1 prevents firmware from consuming empty H2T slots. */ +static inline bool ane_t6021_chman_host_init(void *ipc, u64 size, u64 dva) +{ + unsigned int i, slot; + + if (!ipc || size < ANE_T6021_CHMAN_TOTAL || + dva > ~(u64)0 - ANE_T6021_CHMAN_TOTAL || + ane_t6021_chman_check(ipc, dva)) + return false; + for (i = 0; i < ANE_T6021_CHMAN_COUNT; i++) { + const struct ane_t6021_chman_static *s = &ane_t6021_chman_layout[i]; + + if (s->type != 0) + continue; + for (slot = 0; slot < s->size; slot++) { + u8 *entry = (u8 *)ipc + s->off + slot * 0x40; + + memset(entry, 0, 24); + entry[0] = 1; + } + } + return true; +} + +#endif /* __ANE_T6021_BOOT_H__ */ diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c new file mode 100644 index 0000000000000..1e44f0355b485 --- /dev/null +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -0,0 +1,645 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * T602x/T8112 ANE firmware loader — installed-module port of the proven lab + * staging unit (receipts 2026-09-19-h14-w13-boot-contract.md, + * -w14-staging-proven.md; add-path proof + * 2026-09-28-h14-fsm-secure-park-decode/first-inference.md). + * + * Implements, behind fw_load=1 (default on): + * 1. request_firmware() of the SoC's pinned 13.5 image + * (ane_t602x_soc.fw: selene on T602x, bia on T8112) + * 2. Validation via ane_fw_validate.h (shared with the offline + * regression tools/h14_boot_regression.c): sha256 pin, strict + * exact-image assertions (5 load commands, 2 pinned segments, + * entry 0, bounded LC walk). + * 3. dma_alloc_coherent on the ANE platform device: the buffer is + * DART-mapped through the device's iommu group (stream 0 of the + * three bound instances, H14DartAudit). 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. + * 4. Which copy runs. By default the staged copy (own memory). The lab + * option fw_alias_reserved=1 (T6021 only) maps the copy iBoot + * preloaded at SEG0/SEGi; probe refuses it unless no-map + * /reserved-memory nodes cover both windows (the lab m1n1 adds them, + * the packaged m1n1 1.6.1 does not). The staged copy + * runs: ane_fw_apply_boot_patches() first writes iBoot's runtime + * patches into it (DATA base, RTK_soc, revision, ASC addresses, + * stack guard, ASC tunables), and then it equals the preload byte + * for byte except the random guard (17 captures, + * receipts/2026-10-01-t602x-independent). That needs no reserved + * memory and no preload address, so it is the only mode on SoCs + * without a recorded placement (T6020, T6022, T8112). + * 5. W16 entry alias: the staged fw pages are ALIASED at the latched + * RVBAR entry on the device's default DMA domain. Placement + * contract, receipt receipts/2026-09-20-t6021-entry-alias.md: + * - live RVBAR read64 = 0x10000000001 (bit0 latched, entry + * bits 0x10000000000 = dart-ane vm base); kext law + * (rvbar-lifecycle 6288b0b): bit0 set => the RVBAR write + * branch is skipped, so the ASC fetches AT the latched entry; + * - netconsole 2026-09-20T17:48:19: apple-dart 285800000.iommu + * "translation fault ... code:0x2 (NO PGD FOR IOVA) at + * 0x100000dca10" from the pre-module userspace CPU release — + * the ASC fetched the entry region while nothing was mapped; + * - current-state table walk (kcore, 2026-09-20): entry + * pgd[16] = 0 while the fw leaves are valid -> the region the + * hardware fetches is unmapped and the fw surface is + * physically NON-contiguous (consecutive leaf PAs differ by + * -0x4000). The alias therefore copies each page's PA from + * the live fw translation (iommu_iova_to_phys), never from + * the kernel VA, and verifies every target page unmapped + * before mapping it. + * Driver-managed only: iommu_map() on the attached domain — + * apple_dart implements .map_pages + .iotlb_sync_map, so the + * driver flushes the DART TLB; no raw TTBR/TCR writes. + * Collision ceiling: the iovad allocates top-down from ~4 TiB + * and total mappable RAM is 94.9 GiB (/proc/iomem), so the + * allocator floor 4 TiB - 96 GiB = 0x3e800000000 is far above + * the alias ceiling 0x10005000000; the per-page zero-check + * additionally guards each map. + * + * NOT implemented: the boot step (CPU release + SCRATCH). The userspace + * hybrid stage owns the W8 grant writes; with the alias in place a + * release no longer faults the entry fetch. + * + * Error ownership: every failure path releases the firmware and, once + * allocated, the coherent buffer, and clears ane->fw_buf — remove() + * frees only what fw_buf still names. Load is non-fatal to probe. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ane_t6021.h" +#include "ane_t6021_boot.h" +#include "ane_fw_validate.h" + +/* This object links into both ane_t6021.ko and ane_t6021_rtclient.ko; + * per-object metadata keeps modpost happy for either composition. + */ +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("T6021 ANE firmware staging + entry alias"); + +static bool fw_load = true; +module_param(fw_load, bool, 0444); +MODULE_PARM_DESC(fw_load, + "Validate + DART-map the 13.5 PRELOAD payload (default on: " + "the proven add-path configuration)."); + +static unsigned int fw_extra_ram = 0x200000; +module_param(fw_extra_ram, uint, 0444); +MODULE_PARM_DESC(fw_extra_ram, + "Page-aligned owned RAM after the 5 MiB firmware allocation " + "(default 0x200000, the proven add-path grant; maximum 16 MiB)."); + +/* Preloaded-placement alias, lab only: map the iBoot-reserved SEG0/SEGi + * phys at the entry IOVAs (the preload, with iBoot's patches in place). + * Default off: the own-memory copy needs no reserved RAM, so it runs with + * the packaged m1n1 (T6021 own-memory boot: receipts/2026-10-01-t602x- + * independent, "Boot B"). Only SoCs whose placement is recorded honor it + * (ane_t602x_soc.preload_placement), and only over reserved RAM + * (ane_t6021_fwload_placement_ok). + */ +static bool fw_alias_reserved; +module_param(fw_alias_reserved, bool, 0444); +MODULE_PARM_DESC(fw_alias_reserved, + "Lab, T6021: map reserved SEG0 0x10000848000+0xc4000 at entry and " + "SEG1 0x10001400000+0x438000 after it (probe refuses unless no-map " + "/reserved-memory nodes cover both); 0 (default) = run the staged " + "copy with iBoot's patches replayed (own memory, the only mode on " + "T6020/T6022)."); + +static bool ane_t6021_fw_alias_is_reserved(struct device *dev) +{ + const struct ane_t602x_soc *soc = of_device_get_match_data(dev); + + return fw_alias_reserved && soc->preload_placement; +} + +/* iBoot's T6021 SEG0/SEGi placement (pinned ADT segment-ranges record): + * the physical pages fw_alias_reserved=1 hands to the ASC. + */ +static const struct { u64 phys, len; } ane_t6021_fw_preload[] = { + { 0x10000848000ull, 0xc4000ull }, + { 0x10001400000ull, 0x438000ull }, +}; + +/* Only a no-map /reserved-memory node that the kernel took at boot keeps + * it off those pages. The lab m1n1 adds ane-firmware@ nodes; the packaged + * m1n1 1.6.1 adds none (receipts/2026-10-01-t6021-disk-boot, "Limits"). + */ +static bool ane_t6021_fw_preload_reserved(void) +{ + struct device_node *parent = of_find_node_by_path("/reserved-memory"); + unsigned int i, covered = 0; + + for (i = 0; parent && i < ARRAY_SIZE(ane_t6021_fw_preload); i++) { + u64 phys = ane_t6021_fw_preload[i].phys; + u64 end = phys + ane_t6021_fw_preload[i].len; + struct device_node *np; + + for_each_available_child_of_node(parent, np) { + struct reserved_mem *rmem = of_reserved_mem_lookup(np); + + if (rmem && of_property_read_bool(np, "no-map") && + rmem->base <= phys && end <= rmem->base + rmem->size) { + covered++; + of_node_put(np); + break; + } + } + } + of_node_put(parent); + return covered == ARRAY_SIZE(ane_t6021_fw_preload); +} + +bool ane_t6021_fwload_placement_ok(struct device *dev) +{ + /* BINDING probe-top predicate, as ane_t6021_fwload_options_ok(): + * reserved mode never maps RAM the kernel may own. + */ + return !fw_load || !ane_t6021_fw_alias_is_reserved(dev) || + ane_t6021_fw_preload_reserved(); +} + +bool ane_t6021_fwload_requested(void) +{ + return fw_load; +} + +/* DART page size on t6021 (apple_dart probe line: "pagesize 4000"); + * fw_size is a multiple. Shared with the probe-top predicate below. + */ +#define ANE_T6021_FW_ALIAS_PAGE 0x4000 + +bool ane_t6021_fwload_options_ok(void) +{ + /* BINDING probe-top predicate. MUST be called before + * devm_kzalloc / power / CPU release at every probe site. + * The alloc-time check below runs as defense in depth. + * The lab envelope rule: 16 KiB-aligned, <= 16 MiB. Both alias + * modes map the whole allocation, so the grant needs no mode. + */ + return fw_extra_ram <= SZ_16M && + IS_ALIGNED(fw_extra_ram, ANE_T6021_FW_ALIAS_PAGE); +} + +/* Per-SoC data. RTK_soc_revision on T602x is a measured constant: m1n1 + * gives Linux no chip-revision. T6021: the 17 preload captures (0x11); + * T6020: ANEMinorVersion 1 on community rows 4e8224a39f40, dc53badc436a, + * ea8c35bd20bf, e6069fe959ad; T6022: 17 on row 90c6b9bf3e03 + * (receipts/2026-10-01-community-rows). T6020 and T6022 have the T6021 + * die-0 addresses (13.5 ADTs, t602x-ane.dtsi). + * + * pmu_pa: the firmware's power service programs the seven ANE ps words + * through its DART at IOVA == PA (SetPMUBaseAddress stores the ANE_TD + * word: selene 0x28e084008, bia 0x23b70c010, receipts/2026-10-01-t8112-kit). + * macOS maps the page first; without it the first access faults (NO PMD + * FOR IOVA 0x28e084008, 2026-09-29) and the firmware halts. + * + * T8112 (receipts/2026-10-01-t8112-optin): the revision comes from the + * eFuse words iBoot reads, the ANE_SYS_CPU word is pmgr +0xc008, and the + * kext (type 0x70) opens PWGATE "set" +0x8b8 before the ps words. The TM + * TD word is not known there, so trace_td is off. + */ +const struct ane_t602x_soc ane_t6020_soc = { + .soc = 0x6020, .soc_revision = 0x01, + .fw = &ane_fw_selene, .tunables = &ane_t6020_asc_tunables, + .ps_cpu_off = 0x2e0, .pmu_pa = 0x28e084000ull, + .trace_td_off = 0x1c20458, +}; + +const struct ane_t602x_soc ane_t6021_soc = { + .soc = 0x6021, .soc_revision = 0x11, .preload_placement = true, + .fw = &ane_fw_selene, .tunables = &ane_t602x_asc_tunables, + .ps_cpu_off = 0x2e0, .pmu_pa = 0x28e084000ull, + .trace_td_off = 0x1c20458, +}; + +const struct ane_t602x_soc ane_t6022_soc = { + .soc = 0x6022, .soc_revision = 0x11, + .fw = &ane_fw_selene, .tunables = &ane_t602x_asc_tunables, + .ps_cpu_off = 0x2e0, .pmu_pa = 0x28e084000ull, + .trace_td_off = 0x1c20458, +}; + +const struct ane_t602x_soc ane_t8112_soc = { + .soc = 0x8112, .revision_fuse = true, + .fw = &ane_fw_bia, .tunables = &ane_t8112_asc_tunables, + .ps_cpu_off = 0xc008, .pwgate_off = 0x8b8, + .pmu_pa = 0x23b70c000ull, .ps_off = 0x8, +}; + +static int ane_t6021_pmu_map(struct ane_t6021 *ane, struct iommu_domain *dom) +{ + const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); + int prot = IOMMU_READ | IOMMU_WRITE; + int ret; + + if (dev_is_dma_coherent(ane->dev)) + prot |= IOMMU_CACHE; + ret = iommu_map(dom, soc->pmu_pa, soc->pmu_pa, ANE_T6021_FW_ALIAS_PAGE, + prot, GFP_KERNEL); + if (!ret && iommu_iova_to_phys(dom, soc->pmu_pa) != soc->pmu_pa) + ret = -EIO; + dev_info(ane->dev, "pmu: DART map %#llx (IOVA == PA, %#x bytes): %d\n", + soc->pmu_pa, ANE_T6021_FW_ALIAS_PAGE, ret); + return ret; +} + +static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) +{ + 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); + u64 entry = ane_t6021_rvbar_entry_bits(rvbar); + phys_addr_t pa0 = 0; + int prot = IOMMU_READ | IOMMU_WRITE; + u64 off; + int ret; + + if (!dom) + return -ENODEV; + if (!ane_t6021_rvbar_latched(rvbar) || !entry) { + /* Unlatched branch: the boot path programs RVBAR to the + * fw DVA itself (ane_t6021_rvbar_compose), no alias. + */ + dev_info(ane->dev, + "fwalias: rvbar %016llx not latched/entry 0 — skip (boot reprograms RVBAR)\n", + rvbar); + return 0; + } + if (!ane_t6021_rvbar_entry_ok(entry) || + entry & (ANE_T6021_FW_ALIAS_PAGE - 1)) { + dev_err(ane->dev, + "fwalias: entry %#llx not %#x-aligned in fold\n", + entry, ANE_T6021_FW_ALIAS_PAGE); + return -EINVAL; + } + if (entry + ane->fw_size - 1 > dom->geometry.aperture_end) { + dev_err(ane->dev, + "fwalias: entry %#llx+%#x outside aperture %#llx\n", + entry, ane->fw_size, + (unsigned long long)dom->geometry.aperture_end); + return -ERANGE; + } + if (dev_is_dma_coherent(ane->dev)) + prot |= IOMMU_CACHE; + + if (reserved) { + /* Preloaded placement: the two reserved windows mapped at + * the entry IOVAs. SEG0 0xc4000 is TEXT and SEG1 0x438000 + * is DATA (the 13.5 layout, ane_fw_selene.segs). + * The windows are adjacent, so the mapping is one + * contiguous run of `mapped` bytes starting at entry — + * tracked exactly, because teardown must never unmap a + * page that was not mapped (dart_unmap_pages WARNs on + * holes and the 2026-09-26 state-report unwind hit it). + * SEG1 IOVA = entry + 0xc4000 = 0x100000c4000 per the + * pinned ADT segment-ranges record (0x10000000000 -> + * 0x10000848000 0xc4000; 0x100000c4000 -> 0x10001400000 + * 0x438000). Commit e6612e9 shipped 0x1000000c4000 — one + * hex digit off, mapping DATA at 16 TiB instead: every + * fw_alias_reserved boot since 2026-09-24 left the fw + * DATA section unmapped past the SEG0 head. + */ + struct { u64 iova, phys, len; } win[] = { + { 0x10000000000ull, ane_t6021_fw_preload[0].phys, ane_t6021_fw_preload[0].len }, + { 0, ane_t6021_fw_preload[1].phys, ane_t6021_fw_preload[1].len }, + { entry + 0x4fc000, 0, fw_extra_ram ? ane->fw_size - 0x4fc000 : 0 }, + }; + unsigned int w, windows = fw_extra_ram ? ARRAY_SIZE(win) : 2; + + /* The remap is contiguous: SEG1 base = SEG0 base + SEG0 + * len (segment-ranges order). Derived, never hand-written + * — the standalone literal 0x1000000c4000 that shipped in + * e6612e9 was one digit off and mapped DATA at 16 TiB. + * The remap base must also equal the latched entry, or + * the fetch head is not where we mapped. + */ + win[1].iova = win[0].iova + win[0].len; + if (win[0].iova != entry) { + dev_err(ane->dev, + "fwalias: remap base %#llx != latched entry %#llx\n", + win[0].iova, entry); + return -EINVAL; + } + + for (w = 0; w < windows; w++) { + u64 o; + + for (o = 0; o < win[w].len; o += ANE_T6021_FW_ALIAS_PAGE) { + phys_addr_t pa = w < 2 ? win[w].phys + o : + iommu_iova_to_phys(dom, ane->fw_iova + win[w].iova + o - entry); + if (!pa || !IS_ALIGNED(pa, ANE_T6021_FW_ALIAS_PAGE)) { + ret = -EFAULT; + goto err_unmap_mapped; + } + if (iommu_iova_to_phys(dom, win[w].iova + o)) { + dev_err(ane->dev, + "fwalias: reserved entry +%#llx mapped — refusing\n", + win[w].iova + o - entry); + ret = -EEXIST; + goto err_unmap_mapped; + } + ret = iommu_map(dom, win[w].iova + o, + pa, + ANE_T6021_FW_ALIAS_PAGE, prot, + GFP_KERNEL); + if (ret) { + dev_err(ane->dev, + "fwalias: reserved map +%#llx: %d\n", + win[w].iova + o - entry, ret); + goto err_unmap_mapped; + } + /* per-window successfully mapped bytes */ + ane->fw_alias_ext_len[w] = o + ANE_T6021_FW_ALIAS_PAGE; + ane->fw_alias_ext_iova[w] = win[w].iova; + if (iommu_iova_to_phys(dom, win[w].iova + o) != pa) { + ret = -EIO; + goto err_unmap_mapped; + } + } + } + ane->fw_alias_extn = windows; + ane->fw_alias_iova = entry; + dev_info(ane->dev, + "fwalias: reserved SEG0/SEGi at entry %#llx (%llx+%zx %llx+%zx, preloaded placement)\n", + entry, + ane->fw_alias_ext_iova[0], ane->fw_alias_ext_len[0], + ane->fw_alias_ext_iova[1], ane->fw_alias_ext_len[1]); + if (fw_extra_ram) + dev_info(ane->dev, "fwalias: owned heap [%#llx,%#llx) roundtrip verified\n", + win[2].iova, win[2].iova + win[2].len); + return ane_t6021_pmu_map(ane, dom); + +err_unmap_mapped: + /* Cleanup exactly the per-window bytes we mapped; windows + * are not assumed adjacent (live trace: a hole between + * SEG0 and SEGi), and foreign collision mappings are + * never touched. + */ + for (w = 0; w < windows; w++) + if (ane->fw_alias_ext_len[w]) + iommu_unmap(dom, ane->fw_alias_ext_iova[w], + ane->fw_alias_ext_len[w]); + memset(ane->fw_alias_ext_len, 0, sizeof(ane->fw_alias_ext_len)); + ane->fw_alias_extn = 0; + return ret; + } + + for (off = 0; off < ane->fw_size; off += ANE_T6021_FW_ALIAS_PAGE) { + phys_addr_t pa = iommu_iova_to_phys(dom, ane->fw_iova + off); + + if (!pa || pa & (ANE_T6021_FW_ALIAS_PAGE - 1)) { + dev_err(ane->dev, + "fwalias: fw +%#llx untranslated (%pa)\n", + off, &pa); + ret = -EFAULT; + goto err_unmap; + } + if (iommu_iova_to_phys(dom, entry + off)) { + dev_err(ane->dev, + "fwalias: entry +%#llx already mapped — refusing\n", + off); + ret = -EEXIST; + goto err_unmap; + } + ret = iommu_map(dom, entry + off, pa, + ANE_T6021_FW_ALIAS_PAGE, prot, GFP_KERNEL); + if (ret) { + dev_err(ane->dev, "fwalias: iommu_map +%#llx: %d\n", + off, ret); + goto err_unmap; + } + if (!off) + pa0 = pa; + } + + /* full per-page roundtrip: every alias page must resolve to the + * same PA as its fw source page (not just page 0) + */ + for (off = 0; off < ane->fw_size; off += ANE_T6021_FW_ALIAS_PAGE) { + if (iommu_iova_to_phys(dom, entry + off) != + iommu_iova_to_phys(dom, ane->fw_iova + off)) { + dev_err(ane->dev, + "fwalias: roundtrip mismatch at +%#llx\n", off); + ret = -EIO; + /* Mapping finished: unwind every page, not only the + * prefix already checked by this verification loop. + */ + off = ane->fw_size; + goto err_unmap; + } + } + + ane->fw_alias_iova = entry; + ane->fw_alias_ext_iova[0] = entry; + ane->fw_alias_ext_len[0] = ane->fw_size; + ane->fw_alias_extn = 1; + dev_info(ane->dev, + "fwalias: entry %#llx <- %u dart pages aliased from fw %pad (first %pa, roundtrip OK)\n", + entry, ane->fw_size / ANE_T6021_FW_ALIAS_PAGE, + &ane->fw_iova, &pa0); + /* The firmware's power service needs the pmgr sub-block mapped + * IOVA == PA in every vehicle (NO PMD FOR IOVA 0x28e084008, + * 2026-09-29); the staged-DMA alias branch skipped it and left + * a bisect run booting a halting fw. + */ + return ane_t6021_pmu_map(ane, dom); + +err_unmap: + if (off) + iommu_unmap(dom, entry, off); + return ret; +} + +/* RTK_soc_revision. T8112 reads it as iBoot does: the two eFuse words + * of the DT "fuse" window (0x23d2c8060, 8 bytes), decoded by + * ane_t8112_fuse_revision(). Two non-posted 32-bit reads and nothing + * else: the eFuse block (ADT pmgr reg[36]) is always on, and m1n1 reads + * its ATC and GPU fuses at 0x23d2c8484 and 0x23d2c84dc on every T8112 + * boot. Without the window the revision is unknown, so the load refuses. + */ +static int ane_t6021_soc_revision(struct ane_t6021 *ane, + const struct ane_t602x_soc *soc, u32 *rev) +{ + struct resource *res; + void __iomem *fuse; + u32 w0, w1; + + if (!soc->revision_fuse) { + *rev = soc->soc_revision; + return 0; + } + res = platform_get_resource_byname(to_platform_device(ane->dev), + IORESOURCE_MEM, "fuse"); + if (!res || resource_size(res) != 8) { + dev_err(ane->dev, + "fwload: no 8-byte \"fuse\" window: chip revision unknown, refusing\n"); + return -ENODEV; + } + fuse = ioremap_np(res->start, 8); + if (!fuse) + return -ENOMEM; + w0 = readl(fuse); + w1 = readl(fuse + 4); + iounmap(fuse); + *rev = ane_t8112_fuse_revision(w0, w1); + dev_info(ane->dev, "fwload: chip revision %#x (fuse %#llx: %08x %08x)\n", + *rev, (u64)res->start, w0, w1); + return 0; +} + +/* Own memory (header item 4): iBoot's runtime patches, with values from + * the running system: the latched entry (or the staged DVA that the boot + * path programs when RVBAR is not latched), the DT engine window (probe + * already refused a node without it), the compatible, a fresh guard. + */ +static int ane_t6021_fw_patch(struct ane_t6021 *ane, u8 *img) +{ + const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); + struct resource *res = platform_get_resource(to_platform_device(ane->dev), + IORESOURCE_MEM, 0); + u64 rvbar = readq(ane->base[ANE_T6021_REG_ENGINE] + ANE_ASC_RVBAR); + u64 entry = ane_t6021_rvbar_latched(rvbar) ? + ane_t6021_rvbar_entry_bits(rvbar) : 0; + u64 guard = get_random_u64(); + struct ane_fw_boot_patch p = { + .exec_base = entry ?: ane->fw_iova, + /* iBoot's guards have one zero byte at a random position */ + .stack_guard = guard & ~(0xffull << (8 * (guard >> 61))), + .soc = soc->soc, + .cpu_pa = res->start + ANE_ASC_CPU_BASE, + .wrapper_pa = res->start + ANE_ASC_WRAPPER_BASE, + }; + const char *reason = NULL; + int ret; + + ret = ane_t6021_soc_revision(ane, soc, &p.soc_revision); + if (ret) + return ret; + if (ane_fw_apply_boot_patches(img, soc->fw, soc->tunables, &p, &reason)) { + dev_err(ane->dev, "fwload: own memory: %s (rev %#x)\n", reason, + p.soc_revision); + return -EINVAL; + } + dev_info(ane->dev, + "fwload: own memory: iBoot patches replayed (soc %#x rev %#x DATA %#llx cpu %#llx wrapper %#llx)\n", + p.soc, p.soc_revision, + p.exec_base + soc->fw->segs[1].vmaddr, p.cpu_pa, + p.wrapper_pa); + return 0; +} + +int ane_t6021_fwload_probe(struct ane_t6021 *ane) +{ + const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); + const struct ane_fw_image *img = soc->fw; + const struct firmware *fw = NULL; + struct ane_fw_seg segs[ANE_FW_NSEGS]; + u64 entry = 0; + u8 actual_sha[32]; + void *buf; + dma_addr_t iova; + unsigned int i; + const char *reason = NULL; + u32 alloc_size = ANE_FW_BUF_SIZE + fw_extra_ram; + int ret; + bool reserved = ane_t6021_fw_alias_is_reserved(ane->dev); + + if (!fw_load) + return 0; + if (fw_extra_ram > SZ_16M || !IS_ALIGNED(fw_extra_ram, ANE_T6021_FW_ALIAS_PAGE)) + return -EINVAL; + /* The 64-bit coherent mask is set once in ane_t6021_probe, + * BEFORE rtkit_init allocates the rings (W15 review). + */ + + ret = request_firmware(&fw, img->name, ane->dev); + if (ret) { + dev_err(ane->dev, + "fwload: request_firmware(%s): %d — stage the payload " + "with omarchy-ane-firmware-fetch\n", img->name, ret); + return ret; + } + + sha256(fw->data, fw->size, actual_sha); + ret = ane_fw_validate_blob(fw->data, fw->size, img, actual_sha, + segs, &entry, &reason); + if (ret) { + dev_err(ane->dev, "fwload: validation failed: %s\n", + reason ? reason : "?"); + release_firmware(fw); + return ret; + } + + buf = dma_alloc_coherent(ane->dev, alloc_size, &iova, GFP_KERNEL); + if (!buf) { + dev_err(ane->dev, "fwload: coherent alloc %#x failed\n", + alloc_size); + release_firmware(fw); + return -ENOMEM; + } + + for (i = 0; i < ANE_FW_NSEGS; i++) { + if (segs[i].filesize) + memcpy(buf + segs[i].vmaddr, + fw->data + segs[i].fileoff, segs[i].filesize); + } + + ane->fw_buf = buf; + ane->fw_iova = iova; + ane->fw_size = alloc_size; + + dev_info(ane->dev, + "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); + if (!ret) + ret = ane_t6021_fw_alias_map(ane, reserved); + if (ret) { + ane_t6021_fwload_remove(ane); + release_firmware(fw); + return ret; + } + + release_firmware(fw); + return 0; +} + +void ane_t6021_fwload_remove(struct ane_t6021 *ane) +{ + if (ane->fw_alias_extn) { + struct iommu_domain *dom = iommu_get_domain_for_dev(ane->dev); + int i; + + /* Unmap exactly the per-window recorded extents: the + * reserved-alias windows are not assumed adjacent (live + * trace hole between SEG0 and SEGi) and unmapping bytes + * that were never mapped trips dart_unmap_pages + * (io-pgtable-dart.c:319 WARN, 2026-09-26). + */ + if (dom) + for (i = 0; i < ane->fw_alias_extn; i++) + iommu_unmap(dom, ane->fw_alias_ext_iova[i], + ane->fw_alias_ext_len[i]); + ane->fw_alias_extn = 0; + } + if (!ane->fw_buf) + return; + dma_free_coherent(ane->dev, ane->fw_size, ane->fw_buf, ane->fw_iova); + ane->fw_buf = NULL; + ane->fw_size = 0; +} diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c new file mode 100644 index 0000000000000..9d1e43ecc508b --- /dev/null +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -0,0 +1,2363 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * ane_t6021_rtclient.c — T6021 (H14 / M2) installed ANE driver. + * + * One module, two surfaces: + * - boot/transport: fenced Linux-context firmware start (fw_start=1 + * default — the proven add-path config), shared boot/fwload + * contract units, then the legacy 13.5 ChMan transport for the + * three load-time commands (LOAD_PROGRAM 0x200, 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 + * 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 (the sequencer's per-step drain). + * + * Compiled defaults are the load-run.sh parameter list — a bare + * `insmod ane_t6021.ko` is the proven add-path configuration on + * boot 3ab812a3 (fw_load=1 fw_start=1 fw_start_dapf=0 legacy_only=1 + * legacy_query=1 scratch3_ack=1 poll_rx=1 ...) — except hello_wait_ms, + * 1000 in that list and 0 here (see its definition). + * Remaining parameters are overridable from sysfs for bisection only. + * + * Division of labor (receipts/2026-09-22-t6021-rtkit-port): + * - CPU start: kernel-context start is the proven-safe route on this + * box — m1n1 RTBuddy path is dormant (W5/W6 MGMT session wall) and + * the 13.5 (22G74) selene image brings up the legacy ChMan + * transport after DONE without RTKit. Boot is fenced in + * ane_t6021_boot.c (entry fold, RVBAR skip-or-fold, scratch, + * RUN, poll A/B, publish/wake) and audited in + * tools/h14_boot_regression.c. + * - genpd/pmgr: Runtime PM + the DT power-domains binding owns the + * raise; probe verifies ACTUAL on ane_cpu (pmgr window) before + * the first engine read (G1 gate). The pre-CPU engine table block + * is intentionally NOT written (preboot_table_mode = 2 = SKIP, the + * 2026-09-20-era live-fault discriminator). macOS-form mpm_off is + * skipped: with fw_start_mpm_off=0 (the proven config) the + * boot-raised ane_sys_mpm stays on; the boot writes do not depend + * on it. + * - mailbox: ane_rtclient_validate_chman sees the 'IPC ' surface the + * fw published during boot; the three load-time commands travel + * the IO ring (channel 1) over ane_rtclient_legacy_exchange. Each + * command advances the cursor on the next 64-byte slot — resending + * to slot 0 wedges the ring (sequencer rule). + * - non-posted MMIO (DT "nonposted-mmio" -> IORESOURCE_MEM_NONPOSTED) + * is mandatory throughout the ANE aperture; posted writel froze the + * box. + * - Firmware alias: the staged copy (own memory, default) or, with the + * lab option fw_alias_reserved=1, the iBoot-reserved SEG0/SEGi phys + * is aliased at the latched RVBAR entry; the subsequent kernel writes + * into the entry region translate through dart-ane0 instead of + * faulting. + */ + +#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 +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ane_t6021.h" +#include "ane_t6021_boot.h" + +#include + +/* Doorbell (IPI) block, engine + 0x1844000: set +0, pending +0x8000, + * ack +0xc000 (kext aneInterruptHandler reads +0x184c000 and writes + * +0x1850000 with no SoC branch, receipts/2026-10-01-t8112-ane). + */ +#define ANE_IPI_OFF 0x1844000 + +/* CPU_STATUS bits (m1n1 ASCRegs shape) */ +#define ANE_ASC_CPU_STATUS_RUNNING BIT(0) +#define ANE_ASC_CPU_STATUS_STOPPED BIT(1) + +/* Boot-time module parameters — defaults are the proven add-path + * parameter list (boot 3ab812a3 / load-run.sh), except fw_alias_reserved, + * which defaults to own memory (receipts/2026-10-01-t602x-independent, + * "Boot B"). fw_load, fw_extra_ram and fw_alias_reserved live in + * ane_t6021_fwload.c and boot_prevent_nap in ane_t6021_boot.c (single + * registration each). Remaining knobs are overridable from sysfs for + * bisection only. + */ +static bool fw_start = true; +module_param(fw_start, bool, 0444); +MODULE_PARM_DESC(fw_start, + "Fenced Linux-context firmware start: stage + alias, then the boot sequence; default on (proven add-path config)."); + +static int fw_start_table_mode = 2; +module_param(fw_start_table_mode, int, 0444); +MODULE_PARM_DESC(fw_start_table_mode, + "Pre-CPU engine table block: 0 abort, 1 write, 2 skip (default, proven config)."); + +static bool fw_start_rtb_mode; +module_param(fw_start_rtb_mode, bool, 0444); +MODULE_PARM_DESC(fw_start_rtb_mode, + "RTBuddy/RTKit-app-endpoint select; default off (legacy ChMan transport)."); + +/* Drive RX by apple_rtkit_poll from a workqueue even though a recv + * IRQ exists (lab poll_rx=1, the proven add-path value: the raw recv + * line is unproven, so the worker is what services HELLO/EPMAP). + */ +static bool poll_rx = true; +module_param(poll_rx, bool, 0444); +MODULE_PARM_DESC(poll_rx, + "Drive RX by apple_rtkit_poll from a workqueue (default on, proven config)."); + +/* STARTEP every fw-announced app endpoint (>= 0x20) after a successful + * RTKit handshake (lab start_app_eps=1 default). + */ +static bool start_app_eps = true; +module_param(start_app_eps, bool, 0444); +MODULE_PARM_DESC(start_app_eps, + "STARTEP every fw-announced app endpoint after the handshake (default on)."); + +static bool scratch3_ack = true; +module_param(scratch3_ack, bool, 0444); +MODULE_PARM_DESC(scratch3_ack, + "After DONE, write SCRATCH3 = 0x08042006 (selene 0x7edc, kext 0x95eaee4). Default on; 0 withholds."); + +static bool legacy_only = true; +module_param(legacy_only, bool, 0444); +MODULE_PARM_DESC(legacy_only, + "Use the pinned 13.5 legacy ChMan transport (default on, proven add-path config)."); + +static bool legacy_query = true; +module_param(legacy_query, bool, 0444); +MODULE_PARM_DESC(legacy_query, + "Service bounded startup allocations and CONFIG_GET; default on (proven config)."); + +/* 0 (default) skips RTKit in legacy mode, so the ANE mailbox never + * starts. Measured 2026-09-30 (receipts/2026-09-30-t6021-stock-mailbox): + * the 13.5 firmware sent no HELLO on any recorded boot (-ETIME after + * 1000 ms), and starting the mailbox enables AIC2 884, a level line + * that then fired ~700,000 times/s (one CPU of hardirq time). A + * firmware that speaks RTKit needs hello_wait_ms=1000. + */ +static unsigned int hello_wait_ms; +module_param(hello_wait_ms, uint, 0444); +MODULE_PARM_DESC(hello_wait_ms, + "RTKit HELLO wait in legacy mode; 0 (default) skips RTKit and leaves the mailbox stopped. A firmware that speaks RTKit needs 1000."); + +#define ANE_LEGACY_ALLOCS 8192 +#define ANE_LEGACY_BYTES SZ_512M + +struct ane_legacy_buffer { + void *cpu; + dma_addr_t dma; + size_t size; +}; + +struct ane_rtclient { + struct device *dev; + void __iomem *engine; + void __iomem *pmgr; + const struct ane_t602x_soc *soc; + struct apple_rtkit *rtk; + struct reset_control *cpu_rst; + struct delayed_work poll_work; + + /* fw_start=1 view over the shared boot/fwload contract units. */ + struct ane_t6021 *fw; + + /* A CPU we released is (or may be) running: state HELD — surfaces, + * rings, IRQ, power links preserved; no unwind; reboot reclaims + * (wedged-pin rule). + */ + bool held; + + bool boot_done; + + /* ChMan descriptor table validated against the 'IPC ' surface. */ + bool chman_ok; + struct ane_legacy_buffer *legacy_buffers; + u32 legacy_allocated; + size_t legacy_bytes; + u32 legacy_malloc_cursor; + u32 legacy_cmd_cursor[ANE_T6021_CHMAN_COUNT]; + /* One reusable 16 KiB command buffer for every host command + * (CONFIG_GET + the three ioctls). Protocol-legal to reuse: an + * exchange returns 0 only after the IO slot flipped back to + * host-owned with a zero status (the lab's own completion + * predicate), so the firmware has fully consumed the previous + * command. The legacy_buffers table stays for fw MALLOC replies, + * which the firmware may reference forever (held until reboot). + */ + struct ane_legacy_buffer *cmd_buf; +}; + +/* Per-open BO ownership (drm_file->driver_priv). Handles live in the + * fd's list; closing the fd drops its handles (postclose). The + * coherent buffers themselves live as long as something references + * them: a user mapping, or the firmware (see ane_t6021_bo_release). + */ +struct ane_t6021_fd { + struct list_head bos; +}; + +/* 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 reboot, an io BO is parked + * for reuse (see ane_t6021_bo_release). Every other BO frees at its last + * reference. + * + * Per-BO cap raised 2026-09-30: the 256 KiB Qwen-class matvec weights seen + * by the H14 compiler are bounded by `reduction * columns * 2`, which + * reaches 20 MiB at (K,N)=(2048,5120). The same cap serves the + * Qwen4-attention (K,N)=(4096,4096) constant at 32 MiB 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 reboot, and the 38 Qwen programs alone hold about 2.6 GiB. + * 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 + * allocations fail with -ENOMEM near that bound whatever the cap. + * 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; + struct ane_t6021_fd *owner; + u32 handle; + struct kref refcount; /* handle + user mappings */ + void *cpu; /* coherent mapping */ + dma_addr_t dma; + size_t size; + bool fw_ref; /* the firmware received this IOVA */ + bool fw_program; /* a loaded program keeps this IOVA */ + struct device *dev; +}; + +static DEFINE_MUTEX(ane_t6021_bo_lock); +static u32 ane_t6021_next_handle = 1; +static atomic64_t ane_t6021_bo_total_bytes = ATOMIC64_INIT(0); + +static unsigned int bo_total_max_mb = 12288; +module_param(bo_total_max_mb, uint, 0444); +MODULE_PARM_DESC(bo_total_max_mb, + "Cap on the BO bytes held at one time, in MiB (default 12288)"); + +static int ane_t6021_bo_total_get(char *buf, const struct kernel_param *kp) +{ + return sysfs_emit(buf, "%lld\n", + (long long)atomic64_read(&ane_t6021_bo_total_bytes)); +} + +static int ane_t6021_bo_total_set(const char *val, + const struct kernel_param *kp) +{ + return -EPERM; +} + +static const struct kernel_param_ops ane_t6021_bo_total_ops = { + .set = ane_t6021_bo_total_set, + .get = ane_t6021_bo_total_get, +}; +module_param_cb(bo_total_bytes, &ane_t6021_bo_total_ops, NULL, 0444); +MODULE_PARM_DESC(bo_total_bytes, + "Read only: the BO bytes counted against bo_total_max_mb now"); + +/* Mark the device quarantined: a timed-out command left the firmware + * queue state unknown. The only safe next step is to refuse further + * ioctls until a reboot reclaims the surfaces (wedged-pin rule). + */ +static atomic_t ane_t6021_quarantined = ATOMIC_INIT(0); + +/* Parked io BOs: their last user is gone, the IOVA stays mapped and the + * bytes stay counted. BO_INIT of the same page-aligned size takes one, + * so held memory stays at the peak of concurrent io BOs instead of + * growing with every process until the BO cap refuses BO_INIT. + */ +static LIST_HEAD(ane_t6021_bo_pool); +static DEFINE_SPINLOCK(ane_t6021_bo_pool_lock); + +/* Final put: the last handle or mapping is gone. The firmware never sees + * a freed IOVA (lab rule), so a fw_ref BO is never freed: 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. + */ +static void ane_t6021_bo_release(struct kref *ref) +{ + struct ane_t6021_bo *bo = container_of(ref, struct ane_t6021_bo, + refcount); + + if (!bo->fw_ref) { + atomic64_sub(PAGE_ALIGN(bo->size), &ane_t6021_bo_total_bytes); + dma_free_coherent(bo->dev, bo->size, bo->cpu, bo->dma); + kfree(bo); + } else if (bo->fw_program || atomic_read(&ane_t6021_quarantined)) { + kfree(bo); + } else { + spin_lock(&ane_t6021_bo_pool_lock); + list_add(&bo->node, &ane_t6021_bo_pool); + spin_unlock(&ane_t6021_bo_pool_lock); + } +} + +/* A parked io BO of SIZE's page-aligned size, or NULL. */ +static struct ane_t6021_bo *ane_t6021_bo_pool_take(size_t size) +{ + struct ane_t6021_bo *bo; + + if (atomic_read(&ane_t6021_quarantined)) + return NULL; + spin_lock(&ane_t6021_bo_pool_lock); + list_for_each_entry(bo, &ane_t6021_bo_pool, node) { + if (PAGE_ALIGN(bo->size) == PAGE_ALIGN(size)) { + list_del(&bo->node); + spin_unlock(&ane_t6021_bo_pool_lock); + return bo; + } + } + spin_unlock(&ane_t6021_bo_pool_lock); + return NULL; +} + +/* A user mapping holds its BO's memory until it is torn down: open + * (fork, mremap split) takes a reference, close drops it. A BO the + * user freed while mapped stays allocated until the last mapping + * goes away. + */ +static void ane_t6021_vm_open(struct vm_area_struct *vma) +{ + kref_get(&((struct ane_t6021_bo *)vma->vm_private_data)->refcount); +} + +static void ane_t6021_vm_close(struct vm_area_struct *vma) +{ + kref_put(&((struct ane_t6021_bo *)vma->vm_private_data)->refcount, + ane_t6021_bo_release); +} + +static const struct vm_operations_struct ane_t6021_vm_ops = { + .open = ane_t6021_vm_open, + .close = ane_t6021_vm_close, +}; + +/* Serializes every firmware command (LOAD/CREATE/CALL) so the + * cursor-on-next-64-byte-slot rule and the PMGR/TM gate cannot race. + */ +static DEFINE_MUTEX(ane_t6021_fw_lock); + +/* Forward declaration (defined below). */ +static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, + struct ane_legacy_buffer *command, + size_t length, u16 opcode, + unsigned int channel, + unsigned int timeout_ms); + +/* ---- boot-contract helpers (shared with boot.c / fwload.c) ---- */ + +static int ane_rtclient_legacy_alloc(struct ane_rtclient *ane, u64 size) +{ + struct ane_legacy_buffer *buffer; + + if (!size || !IS_ALIGNED(size, SZ_16K) || size > SZ_2M || + ane->legacy_allocated == ANE_LEGACY_ALLOCS || + size > ANE_LEGACY_BYTES - ane->legacy_bytes) + return -E2BIG; + buffer = &ane->legacy_buffers[ane->legacy_allocated]; + buffer->cpu = dma_alloc_coherent(ane->dev, size, &buffer->dma, + GFP_KERNEL); + if (!buffer->cpu) + return -ENOMEM; + if (!IS_ALIGNED(buffer->dma, SZ_16K) || + (ane->fw && !ane_t6021_fw_alias_iova_ok(ane->fw, buffer->dma, size))) { + dma_free_coherent(ane->dev, size, buffer->cpu, buffer->dma); + buffer->cpu = NULL; + return -ERANGE; + } + memset(buffer->cpu, 0, size); + buffer->size = size; + ane->legacy_bytes += size; + ane->legacy_allocated++; + return 0; +} + +/* Validate the chman table the fw published in the 'IPC ' surface. */ +static void ane_rtclient_validate_chman(struct ane_rtclient *ane) +{ + struct ane_t6021 *a = ane->fw; + const struct ane_t6021_chman_desc *t; + unsigned int i, bad; + + if (!a || !a->boot_ipc) { + dev_info(ane->dev, + "chman: no host IPC surface — table not validated\n"); + return; + } + if (a->boot_ipc_size < ANE_T6021_CHMAN_TOTAL) { + dev_warn(ane->dev, + "chman: IPC surface %#llx bytes < fw layout %#x — table not validated\n", + a->boot_ipc_size, ANE_T6021_CHMAN_TOTAL); + return; + } + + dma_rmb(); + t = a->boot_ipc; + bad = ane_t6021_chman_check(t, a->boot_ipc_iova); + for (i = 0; i < ANE_T6021_CHMAN_COUNT; i++) { + const struct ane_t6021_chman_desc *d = &t[i]; + const struct ane_t6021_chman_static *s = &ane_t6021_chman_layout[i]; + + dev_info(ane->dev, + "chman[%u]: name=\"%.*s\" type=%u bit=%u size=%#llx %s (static: %s/%u/%u/%#llx/ipc+%#x)\n", + i, ANE_T6021_CHMAN_NAME_LEN, d->name, d->type, d->bit, + d->size, + (bad & BIT(i)) ? "MISMATCH" : "OK", + s->name, s->type, s->bit, s->size, s->off); + } + + ane->chman_ok = !bad; + dev_info(ane->dev, "chman: table %s (mismatch mask %#x)\n", + bad ? "NOT VALIDATED" : "VALIDATED", bad); +} + +/* Legacy ChMan exchange (post-DONE 13.5 transport). Resends to the same + * 64-byte IO slot would wedge the ring; cursor advances after each + * completed command (selene fw decodes bit0 = host-owned). + */ +static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, + struct ane_legacy_buffer *command, + size_t length, u16 opcode, + unsigned int channel, + unsigned int timeout_ms) +{ + struct ane_t6021 *a = ane->fw; + u64 *io, *malloc_ring, header; + u64 *t2h_buf, *t2h_ioq; + void __iomem *ipi = ane->engine + ANE_IPI_OFF; + unsigned int cursor = ane->legacy_malloc_cursor; + unsigned long deadline; + u32 *reply; + int result = -ETIMEDOUT; + + if (!ane->held || !ane->chman_ok || + ane_t6021_chman_check(a->boot_ipc, a->boot_ipc_iova)) + return -EPROTO; + if (length < 8 || length > command->size || + channel >= ANE_T6021_CHMAN_COUNT) { + result = -EINVAL; + goto out; + } + io = a->boot_ipc + ane_t6021_chman_layout[channel].off + + (size_t)ane->legacy_cmd_cursor[channel] * 64; + malloc_ring = a->boot_ipc + ane_t6021_chman_layout[5].off; + t2h_buf = a->boot_ipc + ane_t6021_chman_layout[4].off; + t2h_ioq = a->boot_ipc + ane_t6021_chman_layout[6].off; + + if (!(READ_ONCE(io[0]) & 1)) { + result = -EBUSY; + goto out; + } + reply = command->cpu; + ((u16 *)reply)[2] = opcode; + WRITE_ONCE(io[1], length); + WRITE_ONCE(io[2], length); + dma_wmb(); + WRITE_ONCE(io[0], command->dma); + dma_wmb(); + writel(BIT(ane_t6021_chman_layout[channel].bit), ipi); + deadline = jiffies + msecs_to_jiffies(timeout_ms); + while (time_before(jiffies, deadline)) { + u32 pending = readl(ipi + 0x8000); + + if (pending) { + writel(pending, ipi + 0xc000); + mb(); + } + header = READ_ONCE(io[0]); + if (!(header & 1)) { + /* malloc-ring service: the fw may ask for an + * allocation while we wait; service those until + * the command slot flips back. + */ + u64 *slot = malloc_ring + cursor * 8; + u64 alloc_hdr = READ_ONCE(slot[0]); + + if (!(alloc_hdr & 1)) { + u64 size, tag; + struct ane_legacy_buffer *buf; + + dma_rmb(); + size = READ_ONCE(slot[1]); + tag = READ_ONCE(slot[2]); + /* Lab rule: a valid MALLOC slot carries + * header 0 and a u32 tag; anything else + * is a malformed ring and we stop. + */ + if (alloc_hdr || tag > U32_MAX) { + result = -EOPNOTSUPP; + goto out; + } + if (ane_rtclient_legacy_alloc(ane, size)) { + result = -ENOMEM; + goto out; + } + buf = &ane->legacy_buffers[ane->legacy_allocated - 1]; + WRITE_ONCE(slot[1], 0); + WRITE_ONCE(slot[2], ane->legacy_allocated); + dma_wmb(); + WRITE_ONCE(slot[0], buf->dma | 1); + dma_wmb(); + writel(BIT(5), ipi); + cursor = (cursor + 1) % + ane_t6021_chman_layout[5].size; + } + } + header = READ_ONCE(io[0]); + if (header & 1) { + dma_rmb(); + result = (header == (command->dma | 1) && + READ_ONCE(io[1]) == length && + READ_ONCE(io[2]) == 0 && + ((u16 *)reply)[2] == opcode && + ((u16 *)reply)[3] == 0) ? 0 : -EPROTO; + ane->legacy_cmd_cursor[channel] = + (ane->legacy_cmd_cursor[channel] + 1) % + ane_t6021_chman_layout[channel].size; + goto out; + } + /* legacy_fast_poll=1 (the proven add-path cadence): poll + * the rings every 50 us instead of sleeping 1-2 ms. + */ + udelay(50); + } + dev_info(ane->dev, "LEGACY timeout ch=%u io=%016llx\n", + channel, READ_ONCE(io[0])); +out: + ane->legacy_malloc_cursor = cursor; + return result; +} + +/* Time to let the output writes land after the completion signal. + * Measured 2026-09-29 on some boots: the fw ack, the TD counter and the + * TQ words all report done ~0.13 ms before the output reaches DRAM (the + * output read as zeros in about 1 of 5 calls). The finish event arrives + * at the same time for short programs. No signal for "output landed" is + * known, so the wait is a fixed margin of about 8x the lag. + */ +static unsigned int call_settle_us = 1000; +module_param(call_settle_us, uint, 0644); +MODULE_PARM_DESC(call_settle_us, + "Microseconds to wait after a CALL completes so its output lands (default 1000, 0 = none)"); + +/* trace_td: a read-only timeline of each CALL for performance work. Off + * by default; switch it at runtime with + * /sys/module/ane_t6021/parameters/trace_td (no device needed). Off, the + * CALL path is unchanged. On, the completion wait polls every 20-40 us + * and also reads the last-committed-TD word. It reads that word only + * while the seven ANE pmgr PS words read 0x3ff. No register is written. + * + * Provenance (omarchy-ane commits): + * - The TD word: engine + ane_t602x_soc.trace_td_off; on T602x TM + * 0x285c00000 + TD window 0x20400 + 0x58, the word the CALL wait polled + * from be2cf130d761ed675ad86f12b21ac1d53d906e1d until + * 3a942d6cf6278526fbc02bf0c4743c5c1b276cdb. 3a942d6 measured its + * layout: the call's nid in bits 23:16 (+1 per call), the index of the + * last task taken in bits 15:0 (receipts/2026-09-30-t6021-call-wait). + * Not known on T8112, so trace_td records nothing there. + * - The seven ANE power-state words at ane_t602x_soc.pmu_pa + ps_off + * (T602x: DT power-domains ane_sys_mpm 0x4000 .. ane_set4 0x4030 of + * the pmgr at 0x28e080000). The guard "PS words 0x3ff before any TM + * read; a TM read while the compute domains are off hangs the SoC" is + * ane_rtclient_pm_pwrstate_ok in 27e996a6de544a803a71d7a5c4ed11d828d4d049, + * and the CALL wait applied it until 3a942d6. + * + * Each record has a ktime_get_ns() stamp: CALL before the exchange, ACK + * when the firmware acked it, TD for each new TD word value (word = the + * value), EVENT for each IO_T2H event of the CALL (word = its state), + * GATE when a PS word reads other than 0x3ff (word = its offset), DONE + * when the wait ends (word = the TD samples taken). The buffer is + * allocated at the first switch-on and kept until unload; each switch-on + * empties it, and records past its end are counted in `dropped`. Read + * it, while no CALL runs, from debugfs ane_t6021/trace_td (0400). All + * trace state is protected by ane_t6021_fw_lock. + */ +#define ANE_TRACE_MAGIC 0x31445441 /* "ATD1" */ +#define ANE_TRACE_RECS (1U << 18) +#define ANE_PMGR_PS_LAST_OFF 0x30 + +enum { + ANE_TR_CALL = 1, + ANE_TR_ACK, + ANE_TR_TD, + ANE_TR_EVENT, + ANE_TR_GATE, + ANE_TR_DONE, +}; + +struct ane_t6021_trace_rec { + u64 t_ns; + u32 word; + u16 kind; + u16 call; +}; + +struct ane_t6021_trace { + u32 magic; + u32 rec_size; + u32 capacity; + u32 n; + u32 dropped; + u32 calls; + u64 reserved; + struct ane_t6021_trace_rec r[]; +}; + +static bool trace_td; +static bool ane_t6021_tracing; /* the running CALL is traced */ +static struct ane_t6021_trace *ane_t6021_trace; +static struct debugfs_blob_wrapper ane_t6021_trace_blob; +static struct dentry *ane_t6021_trace_dir; + +static void ane_t6021_trace_add(u16 kind, u32 word) +{ + struct ane_t6021_trace *t = ane_t6021_trace; + + if (t->n == t->capacity) { + t->dropped++; + return; + } + t->r[t->n++] = (struct ane_t6021_trace_rec){ + .t_ns = ktime_get_ns(), .word = word, .kind = kind, + .call = t->calls, + }; +} + +static int ane_t6021_trace_set(const char *val, const struct kernel_param *kp) +{ + size_t size = struct_size_t(struct ane_t6021_trace, r, ANE_TRACE_RECS); + bool on; + int ret; + + ret = kstrtobool(val, &on); + if (ret) + return ret; + mutex_lock(&ane_t6021_fw_lock); + if (on && !ane_t6021_trace) { + ane_t6021_trace = vzalloc(size); + if (!ane_t6021_trace) { + ret = -ENOMEM; + goto out; + } + ane_t6021_trace->magic = ANE_TRACE_MAGIC; + ane_t6021_trace->rec_size = sizeof(struct ane_t6021_trace_rec); + ane_t6021_trace->capacity = ANE_TRACE_RECS; + ane_t6021_trace_blob.data = ane_t6021_trace; + ane_t6021_trace_blob.size = size; + ane_t6021_trace_dir = debugfs_create_dir("ane_t6021", NULL); + debugfs_create_blob("trace_td", 0400, ane_t6021_trace_dir, + &ane_t6021_trace_blob); + } + if (on && !trace_td) { + ane_t6021_trace->n = 0; + ane_t6021_trace->dropped = 0; + ane_t6021_trace->calls = 0; + } + trace_td = on; +out: + mutex_unlock(&ane_t6021_fw_lock); + return ret; +} + +static const struct kernel_param_ops ane_t6021_trace_ops = { + .set = ane_t6021_trace_set, + .get = param_get_bool, +}; +module_param_cb(trace_td, &ane_t6021_trace_ops, &trace_td, 0644); +MODULE_PARM_DESC(trace_td, + "Record a read-only per-CALL TD-word timeline in debugfs ane_t6021/trace_td (default 0; T602x only)"); + +static void ane_t6021_trace_free(void) +{ + debugfs_remove_recursive(ane_t6021_trace_dir); + vfree(ane_t6021_trace); +} + +/* The CALL cookie (CALL +0x20); the firmware returns it in the call's + * IO_T2H events. + */ +#define ANE_CALL_COOKIE 0xADD0 + +/* IO_T2H event of a PROCEDURE_CALL, 0x28 bytes (measured 2026-09-30, + * receipts/2026-09-30-t6021-call-wait): u32 sequence, u32 0x300, u64 + * cookie, u32 program id, u32 process id, u32 0, u32 state. The firmware + * posts two per call: state 0 about 0.2-0.5 ms after the ack whatever the + * program length (a 3,597-task program takes its last task 252 ms later; + * receipts/2026-10-01-t6021-trace-td), and state 1 when the procedure has + * finished. + */ +#define ANE_T2H_CALL_COOKIE_OFF 0x08 +#define ANE_T2H_CALL_STATE_OFF 0x1c +#define ANE_T2H_CALL_FINISHED 1 + +/* The CPU address of LEN bytes at the firmware IOVA, or NULL. The firmware + * places T2H payloads in memory the host gave it: a SHAREDMALLOC buffer or + * the 'IPC ' surface. + */ +static const void *ane_rtclient_fw_cpu(struct ane_rtclient *ane, u64 iova, + size_t len) +{ + u32 i; + + for (i = 0; i < ane->legacy_allocated; i++) { + const struct ane_legacy_buffer *b = &ane->legacy_buffers[i]; + + if (iova >= b->dma && iova - b->dma + len <= b->size) + return b->cpu + (iova - b->dma); + } + if (iova >= ane->fw->boot_ipc_iova && + iova - ane->fw->boot_ipc_iova + len <= ane->fw->boot_ipc_size) + return ane->fw->boot_ipc + (iova - ane->fw->boot_ipc_iova); + return NULL; +} + +/* Return every firmware-owned slot on a target-to-host ring to the fw + * (legacy_t2h_ack=1, the lab default): the fw publishes by writing the + * DMA address with bit0 clear; the host returns the slot by setting + * bit0 and ringing the channel's doorbell bit, as the allocation ring + * does. The sequencer drained channels 4/6 after every step; the + * ioctls drain them after every completed exchange. Returns true when + * an IO_T2H slot held the finish event of a CALL. + */ +static bool ane_rtclient_drain_t2h(struct ane_rtclient *ane, + unsigned int channel) +{ + const struct ane_t6021_chman_static *c = &ane_t6021_chman_layout[channel]; + unsigned int n = 0, slot_i = ane->legacy_cmd_cursor[channel]; + void __iomem *ipi = ane->engine + ANE_IPI_OFF; + bool finished = false; + + if (!ane->fw || !ane->fw->boot_ipc) + return false; + while (n < c->size) { + u64 *slot = ane->fw->boot_ipc + c->off + (size_t)slot_i * 64; + u64 hdr = READ_ONCE(slot[0]), len = READ_ONCE(slot[1]); + + if (hdr & 1) + break; + dma_rmb(); + dev_dbg(ane->dev, "T2H ch=%s slot=%u hdr=%016llx len=%#llx\n", + c->name, slot_i, hdr, len); + if (channel == 6 && len >= ANE_T2H_CALL_STATE_OFF + 4) { + const u8 *ev = ane_rtclient_fw_cpu(ane, hdr, + ANE_T2H_CALL_STATE_OFF + 4); + + if (ev && + get_unaligned_le64(ev + ANE_T2H_CALL_COOKIE_OFF) == + ANE_CALL_COOKIE) { + u32 state = get_unaligned_le32(ev + + ANE_T2H_CALL_STATE_OFF); + + if (ane_t6021_tracing) + ane_t6021_trace_add(ANE_TR_EVENT, state); + if (state == ANE_T2H_CALL_FINISHED) + finished = true; + } + } + n++; + WRITE_ONCE(slot[0], hdr | 1); + dma_wmb(); + writel(BIT(c->bit), ipi); + slot_i = (slot_i + 1) % c->size; + ane->legacy_cmd_cursor[channel] = slot_i; + } + return finished; +} + +/* The completion wait with trace_td on: the same finish-event test with a + * 20-40 us poll, and one TD-word sample per poll under the PS-word guard + * (see trace_td). + */ +static int ane_rtclient_call_wait_traced(struct ane_rtclient *ane, + unsigned long deadline) +{ + void __iomem *td = ane->engine + ane->soc->trace_td_off; + void __iomem *ps = ioremap_np(ane->soc->pmu_pa + ane->soc->ps_off, + ANE_PMGR_PS_LAST_OFF + 4); + unsigned int i, gate = ANE_PMGR_PS_LAST_OFF + 8; + u32 last = U32_MAX, samples = 0; + int ret = -ETIMEDOUT; + + do { + if (ane_rtclient_drain_t2h(ane, 6)) { + ret = 0; + break; + } + if (ps) { + for (i = 0; i <= ANE_PMGR_PS_LAST_OFF; i += 8) + if ((readl(ps + i) & 0x3ff) != 0x3ff) + break; + if (i > ANE_PMGR_PS_LAST_OFF) { + u32 w = readl(td); + + samples++; + if (w != last) + ane_t6021_trace_add(ANE_TR_TD, w); + last = w; + } else if (i != gate) { + ane_t6021_trace_add(ANE_TR_GATE, i); + } + gate = i; + } + usleep_range(20, 40); + } while (time_before(jiffies, deadline)); + if (ret && ane_rtclient_drain_t2h(ane, 6)) + ret = 0; + ane_t6021_trace_add(ANE_TR_DONE, samples); + if (ps) + iounmap(ps); + return ret; +} + +/* Completion wait for one PROCEDURE_CALL: the finish event on IO_T2H + * (channel 6). The ack, the eight TQ status words and the last-committed + * TD word (TM +0x20458: the call's nid in bits 23:16 and the index of the + * last task taken in bits 15:0) all report done once the last task has + * been dispatched, not when it has run: measured 2026-09-30, Qwen program + * 20 (20 tasks) showed its last task index 0.22 ms after the ack, posted + * its finish event 3.5 ms after the ack, and a caller that returned at + * the first signal read an all-zero output. Returns 0 when the event + * arrived, -ETIMEDOUT else. + */ +static int ane_rtclient_call_wait(struct ane_rtclient *ane, + unsigned int timeout_ms) +{ + unsigned long deadline = jiffies + msecs_to_jiffies(timeout_ms); + + if (ane_t6021_tracing) + return ane_rtclient_call_wait_traced(ane, deadline); + + do { + if (ane_rtclient_drain_t2h(ane, 6)) + return 0; + usleep_range(50, 100); + } while (time_before(jiffies, deadline)); + return ane_rtclient_drain_t2h(ane, 6) ? 0 : -ETIMEDOUT; +} + +static int ane_rtclient_command(struct ane_rtclient *ane, + struct ane_legacy_buffer *command, + size_t length, u16 opcode, + unsigned int channel, + unsigned int timeout_ms) +{ + int ret; + + ane_t6021_tracing = opcode == CSNE_CMD_PROCEDURE_CALL && trace_td && + ane->soc->trace_td_off; + if (ane_t6021_tracing) { + ane_t6021_trace->calls++; + ane_t6021_trace_add(ANE_TR_CALL, 0); + } + ret = ane_rtclient_legacy_exchange(ane, command, length, opcode, + channel, timeout_ms); + if (ret) { + ane_t6021_tracing = false; + dev_info(ane->dev, "EXCH op=%#x failed %d (fw allocs %u, %zu bytes)\n", + opcode, ret, ane->legacy_allocated, ane->legacy_bytes); + atomic_set(&ane_t6021_quarantined, 1); + return ret; + } + if (opcode == CSNE_CMD_PROCEDURE_CALL) { + if (ane_t6021_tracing) + ane_t6021_trace_add(ANE_TR_ACK, 0); + ret = ane_rtclient_call_wait(ane, timeout_ms); + ane_t6021_tracing = false; + if (!ret && call_settle_us) + usleep_range(call_settle_us, call_settle_us + 100); + if (ret) { + dev_info(ane->dev, "call completion wait failed %d\n", + ret); + atomic_set(&ane_t6021_quarantined, 1); + return ret; + } + } + /* The fw talks back on the target-to-host rings (fwlog, perf); + * hand those slots back so the rings never fill (the sequencer + * did this per step; same ack, channels 4 and 6). + */ + ane_rtclient_drain_t2h(ane, 4); + ane_rtclient_drain_t2h(ane, 6); + /* BOs are dma_alloc_coherent memory mapped write-combined for the + * CPU, so no cache maintenance is needed on either side. + */ + return 0; +} + +/* ---- LOAD / CREATE / CALL wrappers ---- */ + +/* The firmware never frees a program or a process, and its program table + * holds 256 entries: measured 2026-09-29, the 257th LOAD_PROGRAM on one + * boot answered with a protocol error and quarantined the device. Two + * loads of byte-identical sections therefore share one firmware 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. Protected by ane_t6021_fw_lock. + */ +#define ANE_T6021_MAX_PROGRAMS 250 + +struct ane_t6021_prog { + u8 digest[SHA256_DIGEST_SIZE]; + u32 prog_id; + u32 proc_id; /* U32_MAX until a process exists */ +}; + +static struct ane_t6021_prog ane_t6021_progs[ANE_T6021_MAX_PROGRAMS]; +static unsigned int ane_t6021_nprogs; + +static struct ane_t6021_prog *ane_t6021_prog_find(const u8 *digest) +{ + unsigned int i; + + for (i = 0; i < ane_t6021_nprogs; i++) + if (!memcmp(ane_t6021_progs[i].digest, digest, + SHA256_DIGEST_SIZE)) + return &ane_t6021_progs[i]; + return NULL; +} + +static struct ane_t6021_prog *ane_t6021_prog_by_id(u32 prog_id) +{ + unsigned int i; + + for (i = 0; i < ane_t6021_nprogs; i++) + if (ane_t6021_progs[i].prog_id == prog_id) + return &ane_t6021_progs[i]; + 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. + */ +static int ane_rtclient_load_program(struct ane_rtclient *ane, + struct drm_file *file, + const struct drm_ane_prog_load *user, + __u32 *prog_id) +{ + struct drm_ane_section *sections; + struct drm_ane_generic_bind *binds; + struct ane_legacy_buffer *command; + struct ane_t6021_fd *fd = file->driver_priv; + struct ane_t6021_prog *cached; + u8 digest[SHA256_DIGEST_SIZE]; + size_t binds_size; + int ret, i, j; + + if (user->section_count < 1 || + user->section_count > ANE_T6021_LOAD_SEC_COUNT || + user->generic_count > ANE_M2_MAX_BINDS || !fd) + return -EINVAL; + + sections = kmalloc_array(user->section_count, sizeof(*sections), + GFP_KERNEL); + binds = kmalloc_array(user->generic_count, sizeof(*binds), + GFP_KERNEL); + if (!sections || !binds) { + ret = -ENOMEM; + goto out; + } + if (copy_from_user(sections, + u64_to_user_ptr(user->sections_ptr), + user->section_count * sizeof(*sections))) { + ret = -EFAULT; + goto out; + } + binds_size = user->generic_count * sizeof(*binds); + if (binds_size && copy_from_user(binds, + u64_to_user_ptr(user->generic_ptr), + binds_size)) { + ret = -EFAULT; + goto out; + } + + /* Lab contract: the record slot IS the section identity (slot = + * id - 1; tdprop id 7 lands at slot 6 and slot 5 stays empty, + * exactly the proven add-path image). Reject out-of-range and + * duplicate ids before building the wire image. + */ + for (i = 0; i < user->section_count; i++) { + if (sections[i].id < 1 || + sections[i].id > ANE_T6021_LOAD_SEC_COUNT) { + ret = -EINVAL; + goto out; + } + for (j = i + 1; j < user->section_count; j++) { + if (sections[i].id == sections[j].id) { + ret = -EINVAL; + goto out; + } + } + } + + /* 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. + */ + { + struct sha256_ctx sha; + void *scratch; + + sha256_init(&sha); + scratch = kvmalloc(ANE_T6021_BO_HASH_CHUNK, GFP_KERNEL); + if (!scratch) { + ret = -ENOMEM; + 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; + + 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)); + left = sections[i].size; + while (left) { + size_t n = min(left, (size_t)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); + } + kvfree(scratch); + sha256_final(&sha, digest); + } + cached = ane_t6021_prog_find(digest); + if (cached) { + *prog_id = cached->prog_id; + ret = 0; + goto out; + } + if (ane_t6021_nprogs == ANE_T6021_MAX_PROGRAMS) { + ret = -ENOSPC; + goto out; + } + + command = ane->cmd_buf; + if (!command) { + ret = -ENODEV; + goto out; + } + memset(command->cpu, 0, SZ_16K); + /* One 0x30-byte section record per supplied section, placed at + * its IDENTITY slot: slot = id - 1 (tdprop id 7 lands at slot + * 6, slot 5 stays empty — exactly the proven add-path image: + * six populated records, ids 1,2,3,4,5 then 7). Unsupplied + * slots stay zero-filled (flags = 0). flags bit0 = 1, id at + * +0x04, iova at +0x18, size at +0x20. + */ + for (i = 0; i < user->section_count; i++) { + struct ane_t6021_bo *bo = NULL, *b; + u64 slot_base, iova; + u8 *cmd = command->cpu; + + 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) { + /* The IOVA below is about to be published to the + * firmware, so mark the BO before the exchange: + * the fw may read the section any time after the + * doorbell rings, including during a timeout. + * Under bo_lock the handle reference cannot go + * away, so no kref is needed here. + */ + bo->fw_ref = true; + bo->fw_program = true; + iova = bo->dma + sections[i].offset; + } else { + bo = NULL; + } + mutex_unlock(&ane_t6021_bo_lock); + if (!bo) { + ret = -EINVAL; + goto out; + } + slot_base = 0x8 + (u64)(sections[i].id - 1) * 0x30; + *(u32 *)(cmd + slot_base + 0x00) = cpu_to_le32(1); + *(u32 *)(cmd + slot_base + 0x04) = + cpu_to_le32(sections[i].id); + *(u64 *)(cmd + slot_base + 0x18) = cpu_to_le64(iova); + *(u64 *)(cmd + slot_base + 0x20) = + cpu_to_le64(sections[i].size); + } + /* 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 (the proven add path + * ships it inside the section bytes, generic.bin). + */ + + /* ProgramId placeholder; the firmware writes the assigned id + * back at +0x1b8. + */ + { + u8 *cmd = command->cpu; + + *(u32 *)(cmd + 0x1b8) = cpu_to_le32(U32_MAX); + } + + /* The proven add-path LOAD command is 0x1C0 bytes: the nine + * 0x30 records end at 0x1b8, ProgramId at +0x1b8, 8 bytes of + * zero tail. sizeof(struct ane_csne_cmd_load_program) is only + * 0x1b8, so the length is pinned here (h14_seq_first_add.py + * load_step). + */ + BUILD_BUG_ON(sizeof(struct ane_csne_cmd_load_program) != 0x1b8); + ret = ane_rtclient_command(ane, command, + 0x1c0, + CSNE_CMD_LOAD_PROGRAM, + 1, 5000); + if (!ret) { + u8 *cmd = command->cpu; + + *prog_id = le32_to_cpu(*(u32 *)(cmd + 0x1b8)); + if (*prog_id == U32_MAX) { + ret = -EPROTO; + goto out; + } + memcpy(ane_t6021_progs[ane_t6021_nprogs].digest, digest, + SHA256_DIGEST_SIZE); + ane_t6021_progs[ane_t6021_nprogs].prog_id = *prog_id; + ane_t6021_progs[ane_t6021_nprogs].proc_id = U32_MAX; + ane_t6021_nprogs++; + } + +out: + kfree(sections); + kfree(binds); + return ret; +} + +static int ane_rtclient_create_process(struct ane_rtclient *ane, + __u32 prog_id, __u32 *proc_id) +{ + struct ane_legacy_buffer *command; + struct ane_t6021_prog *prog = ane_t6021_prog_by_id(prog_id); + int ret; + + if (!prog) + return -ENOENT; + if (prog->proc_id != U32_MAX) { + *proc_id = prog->proc_id; + return 0; + } + command = ane->cmd_buf; + if (!command) + return -ENODEV; + memset(command->cpu, 0, SZ_16K); + { + u8 *cmd = command->cpu; + + *(u32 *)(cmd + 0x08) = cpu_to_le32(prog_id); + *(u32 *)(cmd + 0x0c) = cpu_to_le32(U32_MAX); + } + ret = ane_rtclient_command(ane, command, 0x10, + CSNE_CMD_CREATE_PROCESS, + 1, 3000); + if (!ret) { + u8 *cmd = command->cpu; + + *proc_id = le32_to_cpu(*(u32 *)(cmd + 0x0c)); + if (*proc_id == U32_MAX) + ret = -EPROTO; + else + prog->proc_id = *proc_id; + } + return ret; +} + +static int ane_rtclient_procedure_call(struct ane_rtclient *ane, + struct drm_file *file, + const struct drm_ane_exec *user) +{ + struct drm_ane_exec_io *ios; + struct ane_legacy_buffer *command; + struct ane_t6021_fd *fd = file->driver_priv; + size_t ios_size; + size_t cmd_size; + int ret, i; + + if (user->count < 1 || user->count > ANE_M2_MAX_BINDS || + user->priority < 2 || user->priority > 7 || !fd) + return -EINVAL; + + ios_size = (size_t)user->count * sizeof(*ios); + ios = kmalloc(ios_size, GFP_KERNEL); + if (!ios) + return -ENOMEM; + if (copy_from_user(ios, u64_to_user_ptr(user->io_ptr), ios_size)) { + kfree(ios); + return -EFAULT; + } + + cmd_size = sizeof(struct ane_csne_cmd_procedure_call) + + (size_t)user->count * sizeof(struct ane_csne_io_elem); + if (cmd_size > SZ_16K) { + kfree(ios); + return -E2BIG; + } + + mutex_lock(&ane_t6021_fw_lock); + if (atomic_read(&ane_t6021_quarantined)) { + mutex_unlock(&ane_t6021_fw_lock); + kfree(ios); + return -ETIMEDOUT; + } + command = ane->cmd_buf; + if (!command) { + mutex_unlock(&ane_t6021_fw_lock); + kfree(ios); + return -ENODEV; + } + memset(command->cpu, 0, SZ_16K); + { + u8 *cmd = command->cpu; + + *(u32 *)(cmd + 0x08) = cpu_to_le32(user->prog_id); + *(u32 *)(cmd + 0x0c) = cpu_to_le32(user->proc_id); + *(u64 *)(cmd + 0x10) = cpu_to_le64(0); + *(u32 *)(cmd + 0x18) = cpu_to_le32(user->priority); + *(u64 *)(cmd + 0x20) = cpu_to_le64(ANE_CALL_COOKIE); + *(u32 *)(cmd + 0x28) = cpu_to_le32(user->count); + for (i = 0; i < user->count; i++) { + struct ane_t6021_bo *bo = NULL, *b; + u64 slot_base = 0x60 + (u64)i * 0x30; + u64 iova; + + mutex_lock(&ane_t6021_bo_lock); + list_for_each_entry(b, &fd->bos, node) { + if (b->handle == ios[i].bo_handle) { + bo = b; + break; + } + } + if (!bo || ios[i].size > bo->size) { + mutex_unlock(&ane_t6021_bo_lock); + ret = -EINVAL; + goto unlock; + } + /* The IOVA below is about to be published to the + * firmware, so mark the BO before the exchange. + * Under bo_lock the handle reference cannot go + * away, so no kref is needed here. + */ + bo->fw_ref = true; + iova = bo->dma; + mutex_unlock(&ane_t6021_bo_lock); + *(u32 *)(cmd + slot_base + 0x00) = cpu_to_le32(1); + *(u32 *)(cmd + slot_base + 0x04) = + cpu_to_le32(ios[i].buffer_id); + *(u32 *)(cmd + slot_base + 0x08) = + cpu_to_le32(ios[i].type); + *(u64 *)(cmd + slot_base + 0x18) = + cpu_to_le64(iova); + *(u64 *)(cmd + slot_base + 0x20) = + cpu_to_le64(ios[i].size); + } + /* Drain the CPU write buffers so the input BOs the user + * filled through its uncached mapping are in DRAM before + * the fw starts reading them. + */ + wmb(); + ret = ane_rtclient_command(ane, command, + cmd_size, + CSNE_CMD_PROCEDURE_CALL, + 1, + user->timeout_ms ? + user->timeout_ms : 5000); + } +unlock: + mutex_unlock(&ane_t6021_fw_lock); + kfree(ios); + return ret; +} + +/* ---- DRM accel glue (minimal BO + ioctl table) ---- */ + +struct ane_t6021_drm { + struct drm_device drm; + struct device *dev; + struct ane_rtclient *ane; +}; + +static struct ane_t6021_drm *to_ane_t6021_drm(struct drm_device *drm) +{ + return container_of(drm, struct ane_t6021_drm, drm); +} + +static int ane_t6021_bo_init_ioctl(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct drm_ane_bo_init *args = data; + struct ane_t6021_fd *fd = file->driver_priv; + struct ane_t6021_bo *bo; + struct ane_rtclient *ane; + + if (args->size == 0 || args->size > ANE_T6021_BO_MAX || !fd) + return -EINVAL; + /* A parked io BO is already mapped and counted; its old contents + * belong to another process, so it is zeroed like a new one. + */ + bo = ane_t6021_bo_pool_take(args->size); + if (bo) { + memset(bo->cpu, 0, PAGE_ALIGN(args->size)); + goto publish; + } + /* Global coherent-memory accounting. Each BO is 16 KiB-aligned; + * a BO whose IOVA reaches the firmware is never freed (held or + * pooled), so this bound caps the memory that outlives its + * users. + */ + if (atomic64_add_return(PAGE_ALIGN(args->size), &ane_t6021_bo_total_bytes) > + (s64)bo_total_max_mb << 20) { + atomic64_sub(PAGE_ALIGN(args->size), &ane_t6021_bo_total_bytes); + return -ENOSPC; + } + ane = to_ane_t6021_drm(drm)->ane; + bo = kzalloc(sizeof(*bo), GFP_KERNEL); + if (!bo) { + atomic64_sub(PAGE_ALIGN(args->size), &ane_t6021_bo_total_bytes); + return -ENOMEM; + } + bo->cpu = dma_alloc_coherent(drm->dev, args->size, &bo->dma, + GFP_KERNEL); + if (!bo->cpu) { + atomic64_sub(PAGE_ALIGN(args->size), &ane_t6021_bo_total_bytes); + kfree(bo); + return -ENOMEM; + } + /* Every fw-visible DMA surface must be 16 KiB aligned and clear + * of the firmware entry alias (receipt 2026-09-20-t6021-entry-alias: + * the same invariant ane_rtclient_legacy_alloc enforces). + */ + if (!IS_ALIGNED(bo->dma, SZ_16K) || + (ane->fw && !ane_t6021_fw_alias_iova_ok(ane->fw, bo->dma, + args->size))) { + dma_free_coherent(drm->dev, args->size, bo->cpu, bo->dma); + atomic64_sub(PAGE_ALIGN(args->size), &ane_t6021_bo_total_bytes); + kfree(bo); + return -ERANGE; + } +publish: + bo->size = args->size; + bo->owner = fd; + bo->dev = drm->dev; + kref_init(&bo->refcount); /* the handle holds this reference */ + mutex_lock(&ane_t6021_bo_lock); + bo->handle = ane_t6021_next_handle++; + if (bo->handle == 0) + bo->handle = ane_t6021_next_handle++; + list_add_tail(&bo->node, &fd->bos); + mutex_unlock(&ane_t6021_bo_lock); + args->handle = bo->handle; + /* mmap offset = the handle; libane mmaps the fd at exactly this + * offset and ane_t6021_mmap resolves the BO from vm_pgoff. + */ + args->offset = (u64)bo->handle << PAGE_SHIFT; + return 0; +} + +/* Drop one handle owned by this fd. The kref may keep the memory + * alive past this call — a user mapping still holds a reference — so + * the final ane_t6021_bo_release makes the free-or-hold decision. + */ +static void ane_t6021_bo_drop(struct ane_t6021_bo *bo) +{ + list_del(&bo->node); + kref_put(&bo->refcount, ane_t6021_bo_release); +} + +static int ane_t6021_bo_free_ioctl(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct drm_ane_bo_free *args = data; + struct ane_t6021_fd *fd = file->driver_priv; + struct ane_t6021_bo *bo = NULL, *b; + + if (!fd) + return -ENODEV; + mutex_lock(&ane_t6021_bo_lock); + list_for_each_entry(b, &fd->bos, node) { + if (b->handle == args->handle) { + bo = b; + break; + } + } + if (bo) + ane_t6021_bo_drop(bo); + mutex_unlock(&ane_t6021_bo_lock); + return bo ? 0 : -ENOENT; +} + +/* Resolve the BO a user mmap names (BO_INIT returned offset = handle + * << PAGE_SHIFT) and map the coherent buffer cacheably — the device + * half coheres through the DART (IOMMU_CACHE), so reads after EXEC + * observe the firmware's writes without extra sync. The mapping takes + * one BO reference: it survives BO_FREE until the vma is gone. + */ +static int ane_t6021_mmap(struct file *filp, struct vm_area_struct *vma) +{ + struct drm_file *file = filp->private_data; + struct ane_t6021_fd *fd = file->driver_priv; + struct drm_device *drm = file->minor->dev; + struct ane_t6021_bo *bo = NULL, *b; + size_t size = vma->vm_end - vma->vm_start; + u32 handle; + int ret; + + if (!fd) + return -ENODEV; + /* vm_pgoff is the BO_INIT offset in pages: handle << PAGE_SHIFT + * >> PAGE_SHIFT == handle. + */ + handle = (u32)vma->vm_pgoff; + if (!handle) + return -EINVAL; + mutex_lock(&ane_t6021_bo_lock); + list_for_each_entry(b, &fd->bos, node) { + if (b->handle == handle && b->owner == fd) { + kref_get(&b->refcount); + bo = b; + break; + } + } + if (!bo || size > PAGE_ALIGN(bo->size)) { + mutex_unlock(&ane_t6021_bo_lock); + if (bo) + kref_put(&bo->refcount, ane_t6021_bo_release); + return -ENOENT; + } + vma->vm_pgoff = 0; + ret = dma_mmap_coherent(drm->dev, vma, bo->cpu, bo->dma, size); + mutex_unlock(&ane_t6021_bo_lock); + if (ret) { + kref_put(&bo->refcount, ane_t6021_bo_release); + return ret; + } + /* The vma owns the lookup reference: close (and open on fork) + * go through ane_t6021_vm_ops. + */ + vma->vm_private_data = bo; + vma->vm_ops = &ane_t6021_vm_ops; + return 0; +} + +static int ane_t6021_open(struct drm_device *drm, struct drm_file *file) +{ + struct ane_t6021_fd *fd; + + fd = kzalloc(sizeof(*fd), GFP_KERNEL); + if (!fd) + return -ENOMEM; + INIT_LIST_HEAD(&fd->bos); + file->driver_priv = fd; + return 0; +} + +static void ane_t6021_postclose(struct drm_device *drm, struct drm_file *file) +{ + struct ane_t6021_fd *fd = file->driver_priv; + struct ane_t6021_bo *bo, *tmp; + + if (!fd) + return; + mutex_lock(&ane_t6021_bo_lock); + list_for_each_entry_safe(bo, tmp, &fd->bos, node) + ane_t6021_bo_drop(bo); + mutex_unlock(&ane_t6021_bo_lock); + kfree(fd); + file->driver_priv = NULL; +} + +static int ane_t6021_submit_ioctl(struct drm_device *drm, void *data, + struct drm_file *file) +{ + return -ENOTTY; /* ABI 1 SUBMIT is rejected on T6021/M2 */ +} + +static int ane_t6021_prog_load_ioctl(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct ane_t6021_drm *adrm = to_ane_t6021_drm(drm); + struct drm_ane_prog_load *args = data; + int ret; + + mutex_lock(&ane_t6021_fw_lock); + if (atomic_read(&ane_t6021_quarantined)) { + mutex_unlock(&ane_t6021_fw_lock); + return -ETIMEDOUT; + } + ret = ane_rtclient_load_program(adrm->ane, file, args, + &args->prog_id_out); + mutex_unlock(&ane_t6021_fw_lock); + return ret; +} + +/* Firmware perf mode: CSNE_CMD_CH_PROPERTY_WRITE (0x1f), channel 0, + * property 0x10aa, value 1. macOS sends it once during power-on (H13 + * kext evidence in the omarchy-ane perf-mode receipt); the selene 13.5 + * fw routes it to CAneEngineExeLoop::setPerfMode. It is a runtime + * switch (write 1 to /sys/module/ane_t6021/parameters/fw_perf_mode) so + * its effect on call time can be measured on one boot. Only 1 is + * accepted: no other value is known to be safe. + */ +static struct ane_rtclient *ane_t6021_perf_ane; +static bool fw_perf_mode; + +static int ane_t6021_perf_mode_set(const char *val, + const struct kernel_param *kp) +{ + struct ane_rtclient *ane = READ_ONCE(ane_t6021_perf_ane); + struct ane_legacy_buffer *command; + bool on; + int ret; + + ret = kstrtobool(val, &on); + if (ret) + return ret; + if (!on || fw_perf_mode) + return on ? 0 : -EINVAL; + if (!ane) + return -ENODEV; + mutex_lock(&ane_t6021_fw_lock); + if (atomic_read(&ane_t6021_quarantined)) { + mutex_unlock(&ane_t6021_fw_lock); + return -ETIMEDOUT; + } + command = ane->cmd_buf; + if (!command) { + mutex_unlock(&ane_t6021_fw_lock); + return -ENODEV; + } + memset(command->cpu, 0, SZ_16K); + *(u32 *)((u8 *)command->cpu + 0x08) = cpu_to_le32(0); + *(u32 *)((u8 *)command->cpu + 0x0c) = cpu_to_le32(0x10aa); + *(u32 *)((u8 *)command->cpu + 0x10) = cpu_to_le32(1); + ret = ane_rtclient_command(ane, command, 0x14, 0x001f, 1, 3000); + if (!ret) { + fw_perf_mode = true; + dev_info(ane->dev, "fw perf mode set (property 0x10aa = 1)\n"); + } + mutex_unlock(&ane_t6021_fw_lock); + return ret; +} + +static const struct kernel_param_ops ane_t6021_perf_mode_ops = { + .set = ane_t6021_perf_mode_set, + .get = param_get_bool, +}; +module_param_cb(fw_perf_mode, &ane_t6021_perf_mode_ops, &fw_perf_mode, 0644); +MODULE_PARM_DESC(fw_perf_mode, + "Write 1 once to send CH_PROPERTY_WRITE 0x10aa = 1 (fw perf mode); reads back whether it was sent"); + +static int ane_t6021_proc_create_ioctl(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct ane_t6021_drm *adrm = to_ane_t6021_drm(drm); + struct drm_ane_proc_create *args = data; + int ret; + + mutex_lock(&ane_t6021_fw_lock); + if (atomic_read(&ane_t6021_quarantined)) { + mutex_unlock(&ane_t6021_fw_lock); + return -ETIMEDOUT; + } + args->proc_id_out = 0; + ret = ane_rtclient_create_process(adrm->ane, args->prog_id, + &args->proc_id_out); + mutex_unlock(&ane_t6021_fw_lock); + return ret; +} + +static int ane_t6021_exec_ioctl(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct ane_t6021_drm *adrm = to_ane_t6021_drm(drm); + struct drm_ane_exec *args = data; + + return ane_rtclient_procedure_call(adrm->ane, file, args); +} + +static const struct drm_ioctl_desc ane_t6021_ioctls[] = { + DRM_IOCTL_DEF_DRV(ANE_BO_INIT, ane_t6021_bo_init_ioctl, 0), + DRM_IOCTL_DEF_DRV(ANE_BO_FREE, ane_t6021_bo_free_ioctl, 0), + DRM_IOCTL_DEF_DRV(ANE_SUBMIT, ane_t6021_submit_ioctl, 0), + DRM_IOCTL_DEF_DRV(ANE_PROG_LOAD, ane_t6021_prog_load_ioctl, 0), + DRM_IOCTL_DEF_DRV(ANE_PROC_CREATE, ane_t6021_proc_create_ioctl, 0), + DRM_IOCTL_DEF_DRV(ANE_EXEC, ane_t6021_exec_ioctl, 0), +}; + +/* Driver fops: the accel-core entry points plus our BO mmap (the core + * default maps only GEM objects; this driver keeps its own BO table, + * so .mmap resolves the handle from BO_INIT's returned offset). + */ +static const struct file_operations ane_t6021_fops = { + .owner = THIS_MODULE, + .fop_flags = FOP_UNSIGNED_OFFSET, + .open = accel_open, + .release = drm_release, + .unlocked_ioctl = drm_ioctl, + .compat_ioctl = drm_compat_ioctl, + .poll = drm_poll, + .read = drm_read, + .llseek = noop_llseek, + .mmap = ane_t6021_mmap, +}; + +/* Version reported through DRM_IOCTL_VERSION: ABI 2 (T6021). + * DRIVER_COMPUTE_ACCEL puts the node at /dev/accel/accelN. + */ +static const struct drm_driver ane_t6021_drm_driver = { + .driver_features = DRIVER_GEM | DRIVER_COMPUTE_ACCEL, + .open = ane_t6021_open, + .postclose = ane_t6021_postclose, + .ioctls = ane_t6021_ioctls, + .num_ioctls = ARRAY_SIZE(ane_t6021_ioctls), + .fops = &ane_t6021_fops, + .major = ANE_ABI_M2_MAJOR, + .minor = 0, + .name = "ane", + .desc = "Apple Neural Engine (T6021/M2)", +}; + +/* ---- RTKit ops (kept on the boot path; the legacy ChMan transport + * is used by the ioctls once probe confirms legacy_only / chman_ok). + */ + +static void ane_rtclient_recv(void *cookie, u8 ep, u64 message) +{ + struct ane_rtclient *ane = cookie; + + dev_info(ane->dev, + "rtkit app msg: ep=%#x msg=%016llx\n", ep, message); +} + +static void ane_rtclient_crashed(void *cookie, const void *crashlog, + size_t size) +{ + struct ane_rtclient *ane = cookie; + + dev_err(ane->dev, "rtkit: coprocessor crashed (crashlog %zu bytes)\n", + size); + print_hex_dump(KERN_ERR, "ANE crashlog: ", DUMP_PREFIX_OFFSET, 16, 1, + crashlog, min_t(size_t, size, 256), false); +} + +static int ane_rtclient_shmem_setup(void *cookie, + struct apple_rtkit_shmem *bfr) +{ + struct ane_rtclient *ane = cookie; + + if (bfr->iova) { + dev_warn(ane->dev, + "rtkit: fw-provided shmem iova=%pad size=%#zx — refused\n", + &bfr->iova, bfr->size); + return -EINVAL; + } + bfr->buffer = dma_alloc_coherent(ane->dev, bfr->size, &bfr->iova, + GFP_KERNEL); + if (!bfr->buffer) + return -ENOMEM; + if (ane->fw && !ane_t6021_fw_alias_iova_ok(ane->fw, bfr->iova, + bfr->size)) { + dev_err(ane->dev, + "rtkit: shmem grant %pad+%#zx overlaps the fw alias — refusing\n", + &bfr->iova, bfr->size); + dma_free_coherent(ane->dev, bfr->size, bfr->buffer, bfr->iova); + bfr->buffer = NULL; + return -EBUSY; + } + return 0; +} + +static void ane_rtclient_shmem_destroy(void *cookie, + struct apple_rtkit_shmem *bfr) +{ + struct ane_rtclient *ane = cookie; + + if (!bfr->buffer) + return; + if (ane->held) { + dev_warn(ane->dev, + "rtkit: shmem %pad HELD (CPU started) — not freed\n", + &bfr->iova); + return; + } + dma_free_coherent(ane->dev, bfr->size, bfr->buffer, bfr->iova); +} + +static const struct apple_rtkit_ops ane_rtclient_rtkit_ops = { + .crashed = ane_rtclient_crashed, + .recv_message = ane_rtclient_recv, + .shmem_setup = ane_rtclient_shmem_setup, + .shmem_destroy = ane_rtclient_shmem_destroy, +}; + +/* ---- poll worker: RX fallback while the recv line is unproven ---- + * (lab poll_rx=1). Runs every 10 ms until the handshake completes, + * then every second while poll_rx stays on. Armed BEFORE the host ack + * so the fw's HELLO is never missed. + */ +static void ane_rtclient_post_boot(struct work_struct *w) +{ + struct ane_rtclient *ane = + container_of(to_delayed_work(w), struct ane_rtclient, + poll_work); + + apple_rtkit_poll(ane->rtk); + + if (!ane->boot_done) { + schedule_delayed_work(&ane->poll_work, msecs_to_jiffies(10)); + return; + } + + if (poll_rx) + schedule_delayed_work(&ane->poll_work, HZ); +} + +/* STARTEP every fw-announced app endpoint (>= 0x20; the fw mgmt + * dispatcher starts an endpoint on flag bit 1). Same call every Asahi + * RTKit client makes; the lab ran it with start_app_eps=1. + */ +static void ane_rtclient_start_app_eps(struct ane_rtclient *ane) +{ + int ep; + + for (ep = 0x20; ep < 0x100; ep++) { + int ret; + + if (!apple_rtkit_has_endpoint(ane->rtk, ep)) + continue; + ret = apple_rtkit_start_ep(ane->rtk, ep); + dev_info(ane->dev, "rtkit: STARTEP app ep %#x -> %pe\n", + ep, ERR_PTR(ret)); + } +} + +/* Multi-domain genpd attach, ownership-correct and idempotent. */ +struct ane_rtclient_pd { + struct list_head list; + struct device *dev; + struct device **pd_dev; + struct device_link **pd_link; + int count; +}; + +static LIST_HEAD(ane_rtclient_pd_list); +static DEFINE_MUTEX(ane_rtclient_pd_lock); +static bool ane_rtclient_pinned; + +static void ane_rtclient_pd_free(struct ane_rtclient_pd *pd) +{ + list_del(&pd->list); + kfree(pd->pd_dev); + kfree(pd->pd_link); + kfree(pd); +} + +static int ane_rtclient_attach_genpd(struct ane_rtclient *ane) +{ + struct device *dev = ane->dev; + struct ane_rtclient_pd *pd = NULL; + int count, i, err = 0; + + count = of_count_phandle_with_args(dev->of_node, "power-domains", + "#power-domain-cells"); + if (count == -ENOENT) + return 0; + if (count < 0) + return count; + if (count <= 1) + return 0; + + mutex_lock(&ane_rtclient_pd_lock); + list_for_each_entry(pd, &ane_rtclient_pd_list, list) + if (pd->dev == dev) + goto found; + + pd = kzalloc(sizeof(*pd), GFP_KERNEL); + if (!pd) { + err = -ENOMEM; + goto out; + } + INIT_LIST_HEAD(&pd->list); + pd->dev = dev; + pd->pd_dev = kcalloc(count, sizeof(*pd->pd_dev), GFP_KERNEL); + pd->pd_link = kcalloc(count, sizeof(*pd->pd_link), GFP_KERNEL); + if (!pd->pd_dev || !pd->pd_link) { + ane_rtclient_pd_free(pd); + pd = NULL; + err = -ENOMEM; + goto out; + } + list_add_tail(&pd->list, &ane_rtclient_pd_list); + +found: + for (i = pd->count; i < count; i++) { + if (!pd->pd_dev[i]) { + pd->pd_dev[i] = dev_pm_domain_attach_by_id(dev, i); + if (IS_ERR_OR_NULL(pd->pd_dev[i])) { + err = IS_ERR(pd->pd_dev[i]) ? + PTR_ERR(pd->pd_dev[i]) : -ENODEV; + pd->pd_dev[i] = NULL; + goto out; + } + } + if (!pd->pd_link[i]) { + if (!ane_rtclient_pinned) { + if (!try_module_get(THIS_MODULE)) { + err = -ENODEV; + goto out; + } + ane_rtclient_pinned = true; + } + pd->pd_link[i] = + device_link_add(dev, pd->pd_dev[i], + DL_FLAG_STATELESS | + DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE); + if (!pd->pd_link[i]) { + err = -EINVAL; + goto out; + } + } + pd->count = i + 1; + } + + dev_emerg(dev, "BOOT-PHASE genpd domains attached: %d\n", count); +out: + mutex_unlock(&ane_rtclient_pd_lock); + return err; +} + +static int ane_rtclient_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct resource *res; + struct ane_rtclient *ane; + struct ane_t6021 *a; + u32 cpu_status, ps_cpu; + u64 rvbar; + int ret; + + if (!ane_t6021_fwload_options_ok()) { + dev_err(dev, + "invalid firmware RAM-grant options; refusing before power access\n"); + return -EINVAL; + } + + if (!ane_t6021_fwload_placement_ok(dev)) { + dev_err(dev, + "fw_alias_reserved=1, but no no-map /reserved-memory node covers the iBoot firmware windows (this m1n1 does not reserve them); refusing before power access, ANE off\n"); + return -ENODEV; + } + + /* Early, BEFORE any allocation/power: legacy_only must never be + * rejected after the CPU release, where an unwind could drop + * domains under a running ASC (lab probe order). + */ + if (legacy_only && (!fw_start || fw_start_rtb_mode)) { + dev_err(dev, + "legacy_only=1 requires fw_start=1 and fw_start_rtb_mode=0\n"); + return -EINVAL; + } + if (legacy_query && !legacy_only) { + dev_err(dev, "legacy_query requires legacy_only=1\n"); + return -EINVAL; + } + + ane = devm_kzalloc(dev, sizeof(*ane), GFP_KERNEL); + if (!ane) + return -ENOMEM; + ane->legacy_buffers = devm_kcalloc(dev, ANE_LEGACY_ALLOCS, + sizeof(*ane->legacy_buffers), + GFP_KERNEL); + if (!ane->legacy_buffers) + return -ENOMEM; + ane->dev = dev; + ane->soc = of_device_get_match_data(dev); + platform_set_drvdata(pdev, ane); + INIT_DELAYED_WORK(&ane->poll_work, ane_rtclient_post_boot); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + if (!(res->flags & IORESOURCE_MEM_NONPOSTED)) + dev_warn(dev, "engine window is not flagged non-posted\n"); + ane->engine = ioremap_np(res->start, resource_size(res)); + if (!ane->engine) + return -ENOMEM; + ane->cpu_rst = devm_reset_control_get_optional_exclusive(dev, NULL); + if (IS_ERR(ane->cpu_rst)) + return dev_err_probe(dev, PTR_ERR(ane->cpu_rst), + "ane_cpu reset control\n"); + + ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32)); + if (ret) + return ret; + + ret = ane_rtclient_attach_genpd(ane); + if (ret) + return dev_err_probe(dev, ret, "extra genpd attach\n"); + pm_runtime_enable(dev); + ret = pm_runtime_resume_and_get(dev); + if (ret) + return dev_err_probe(dev, ret, "genpd raise failed\n"); + + ane->pmgr = devm_of_iomap(dev, dev->of_node, 1, NULL); + if (IS_ERR(ane->pmgr)) { + ret = PTR_ERR(ane->pmgr); + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return dev_err_probe(dev, ret, + "pmgr window map failed; G1 gate cannot run\n"); + } + ps_cpu = readl(ane->pmgr + ane->soc->ps_cpu_off); + dev_emerg(dev, "ane_cpu ACTUAL = 0x%x\n", ps_cpu); + if (FIELD_GET(ANE_PS_ACTUAL, ps_cpu) != ANE_PS_ON) { + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return -EPROBE_DEFER; + } + /* T8112: the kext (type 0x70) opens PWGATE (bits 29:28 = 0) before + * the ps words. This driver only reads it: an engine read behind a + * closed gate is untested, so it refuses first. + */ + if (ane->soc->pwgate_off) { + void __iomem *set = devm_of_iomap(dev, dev->of_node, 2, NULL); + u32 gate = IS_ERR(set) ? U32_MAX : + readl(set + ane->soc->pwgate_off); + + dev_emerg(dev, "PWGATE = 0x%x\n", gate); + if (gate & GENMASK(29, 28)) { + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return dev_err_probe(dev, -ENODEV, + "PWGATE closed; refusing before any engine read\n"); + } + } + + cpu_status = readl(ane->engine + ANE_ASC_CPU_STATUS); + rvbar = readq(ane->engine + ANE_ASC_RVBAR); + dev_emerg(dev, + "BOOT-PHASE engine reads ok: CPU_STATUS = 0x%x, RVBAR = %016llx (bit0=%u)\n", + cpu_status, rvbar, (u32)(rvbar & 1)); + + if (!(cpu_status & ANE_ASC_CPU_STATUS_RUNNING)) { + if (!fw_start) { + dev_err(dev, + "ANE firmware not alive (CPU_STATUS 0x%x) — start it from a quiesce context, or retry with fw_start=1\n", + cpu_status); + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return -EPROBE_DEFER; + } + + /* Lab fw_start order: staging requires fw_load and an + * IOMMU-mapped device BEFORE any allocation/staging. + */ + if (!ane_t6021_fwload_requested()) { + dev_err(dev, + "fw_start: requires fw_load=1 (no staged firmware)\n"); + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return -EINVAL; + } + if (!device_iommu_mapped(dev)) { + dev_err(dev, + "fw_start: device not IOMMU-mapped — a staged DVA/entry alias would be untranslated; refusing\n"); + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return -EINVAL; + } + + a = devm_kzalloc(dev, sizeof(*a), GFP_KERNEL); + if (!a) { + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return -ENOMEM; + } + a->dev = dev; + a->base[ANE_T6021_REG_ENGINE] = ane->engine; + a->irq = -1; + a->power_gated = true; + ane->fw = a; + + dev_emerg(dev, "BOOT-PHASE fwload stage+alias begin\n"); + ret = ane_t6021_fwload_probe(a); + if (ret) { + dev_err_probe(dev, ret, "fw_start: staging failed\n"); + ane_t6021_fwload_remove(a); + ane->fw = NULL; + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return ret; + } + if (!ane_t6021_rvbar_entry_ok(a->fw_iova)) { + dev_err(dev, "fw_start: staged iova %pad invalid\n", + &a->fw_iova); + ane_t6021_fwload_remove(a); + ane->fw = NULL; + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return -EINVAL; + } + + dev_emerg(dev, "BOOT-PHASE dispatch (table_mode=%d)\n", + fw_start_table_mode); + ret = ane_t6021_boot_start(a, 0, fw_start_table_mode, + fw_start_rtb_mode); + if (ret == -ENODATA || ret == -EAGAIN || + ret == -EBUSY || ret == -ECANCELED) { + ane_t6021_fwload_remove(a); + ane->fw = NULL; + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + return ret; + } + + ane->held = true; + cpu_status = readl(ane->engine + ANE_ASC_CPU_STATUS); + dev_emerg(dev, + "BOOT-PHASE sequence returned %pe (cpu_started=%u fw_alive=%u booted=%u) CPU_STATUS=0x%x\n", + ERR_PTR(ret), a->cpu_started, a->fw_alive, a->booted, + cpu_status); + if (!a->fw_alive && !fw_start_rtb_mode) { + dev_err(dev, + "fw_start: poll A timeout, no READY — HELD until reboot, RTKit handshake skipped\n"); + return 0; + } + } + + if (legacy_only) { + int cfg_err = 0; + + ane_rtclient_validate_chman(ane); + if (ane->fw && ane->fw->booted && scratch3_ack && + ane->chman_ok && + ane_t6021_chman_host_init(ane->fw->boot_ipc, + ane->fw->boot_ipc_size, + ane->fw->boot_ipc_iova)) { + int hello_ret = 0; + + dma_wmb(); + dev_emerg(dev, + "LEGACY P8 host ack: SCRATCH3 <- %08x\n", + ANE_T6021_BOOT_ACK); + /* hello_wait_ms > 0 only: init rtkit and arm the RX + * poll worker BEFORE writing the ack, so a HELLO + * after the ack is not missed. The 13.5 fw sent none + * on any recorded boot. + */ + if (hello_wait_ms && !ane->rtk) { + ane->rtk = devm_apple_rtkit_init(dev, ane, + NULL, 0, + &ane_rtclient_rtkit_ops); + if (IS_ERR(ane->rtk)) { + dev_err(dev, + "LEGACY hello: rtkit init %pe\n", + ane->rtk); + ane->rtk = NULL; + } else { + schedule_delayed_work(&ane->poll_work, + msecs_to_jiffies(10)); + } + } + writel(ANE_T6021_BOOT_ACK, + ane->engine + ANE_MBI_SCRATCH0 + 4 * 3); + if (ane->rtk) { + unsigned long hello_deadline = + jiffies + msecs_to_jiffies(hello_wait_ms); + + dev_emerg(dev, "LEGACY hello: boot begin (%u ms)\n", + hello_wait_ms); + do { + hello_ret = apple_rtkit_boot(ane->rtk); + } while (hello_ret == -ETIME && + time_before(jiffies, hello_deadline)); + dev_emerg(dev, + "LEGACY hello: boot %pe running=%d crashed=%d\n", + ERR_PTR(hello_ret), + apple_rtkit_is_running(ane->rtk), + apple_rtkit_is_crashed(ane->rtk)); + if (!hello_ret) { + ane->boot_done = true; + if (start_app_eps) + ane_rtclient_start_app_eps(ane); + } else { + cancel_delayed_work_sync(&ane->poll_work); + } + } + } else { + dev_warn(dev, + "LEGACY ack withheld (booted=%u scratch3_ack=%u chman_ok=%u)\n", + ane->fw ? ane->fw->booted : 0, + scratch3_ack, ane->chman_ok); + } + if (ane->chman_ok) { + /* One reusable command buffer for the transport + * (CONFIG_GET + every ioctl); reuse is legal + * because each exchange completes with the slot + * host-owned again. The 128-entry table stays + * for fw MALLOC replies only. + */ + if (ane_rtclient_legacy_alloc(ane, SZ_16K) == 0) + ane->cmd_buf = + &ane->legacy_buffers[ane->legacy_allocated - 1]; + else + cfg_err = -ENOMEM; + } + if (!cfg_err && legacy_query && ane->chman_ok) { + /* CONFIG_GET (opcode 0x03) keeps the legacy ChMan + * transport armed for the ioctls; the reply's + * word +0x08 must be nonzero (lab rule). The + * boot heap + 'IPC ' allocations stay HELD until + * reboot. + */ + struct ane_legacy_buffer *command = ane->cmd_buf; + int qret; + + if (command) { + memset(command->cpu, 0, SZ_16K); + qret = ane_rtclient_legacy_exchange(ane, + command, + 16, 0x03, + 1, 3000); + dev_info(dev, + "LEGACY CONFIG_GET words %08x %08x result=%d (DMA remains held)\n", + READ_ONCE(((u32 *)command->cpu)[1]), + READ_ONCE(((u32 *)command->cpu)[2]), + qret); + if (qret) + cfg_err = qret; + else if (!READ_ONCE(((u32 *)command->cpu)[2])) { + dev_err(dev, + "LEGACY CONFIG_GET reply word +0x08 zero\n"); + cfg_err = -EPROTO; + } + } else { + cfg_err = -ENOMEM; + } + } + ane->boot_done = true; + if (cfg_err) { + dev_err(dev, + "install: CONFIG_GET failed (%d) — refusing to register DRM device (ioctls would run on an unproven ring)\n", + cfg_err); + if (!ane->held) { + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + } + return cfg_err; + } + } else { + unsigned long deadline; + int boot_ret; + + ane->rtk = devm_apple_rtkit_init(dev, ane, NULL, 0, + &ane_rtclient_rtkit_ops); + if (IS_ERR(ane->rtk)) { + ret = PTR_ERR(ane->rtk); + ane->rtk = NULL; + dev_err_probe(dev, ret, "apple_rtkit_init failed\n"); + goto err_pm_or_hold; + } + /* RX fallback worker first: the fw's HELLO must not be + * missed while the recv line is unproven. + */ + schedule_delayed_work(&ane->poll_work, msecs_to_jiffies(10)); + deadline = jiffies + msecs_to_jiffies(hello_wait_ms); + do { + boot_ret = apple_rtkit_boot(ane->rtk); + } while (boot_ret == -ETIME && time_before(jiffies, deadline)); + if (boot_ret) { + dev_err(dev, "rtkit boot handshake failed: %pe\n", + ERR_PTR(boot_ret)); + cancel_delayed_work_sync(&ane->poll_work); + ret = boot_ret; + goto err_pm_or_hold; + } + ane->boot_done = true; + if (start_app_eps) + ane_rtclient_start_app_eps(ane); + } + + if (!ane->chman_ok) { + dev_err(dev, + "install: ChMan table not validated — refusing to register DRM device (ioctls would stall the ring)\n"); + cancel_delayed_work_sync(&ane->poll_work); + if (!ane->held) { + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + } + return -EPROTO; + } + + { + struct ane_t6021_drm *adrm; + int drmret; + + /* This kernel dropped drm_dev_init; the resource-managed + * alloc registers the same ABI-2 device. + */ + adrm = devm_drm_dev_alloc(dev, &ane_t6021_drm_driver, + struct ane_t6021_drm, drm); + if (IS_ERR(adrm)) { + ret = dev_err_probe(dev, PTR_ERR(adrm), + "drm device alloc\n"); + goto err_pm_or_hold; + } + adrm->dev = dev; + adrm->ane = ane; + WRITE_ONCE(ane_t6021_perf_ane, ane); + drmret = drm_dev_register(&adrm->drm, 0); + if (drmret) { + dev_err_probe(dev, drmret, "drm_dev_register\n"); + ret = drmret; + goto err_pm_or_hold; + } + dev_info(dev, + "loaded ane_t6021 (DRM major %d minor %d; ABI 2; legacy_only=%u chman_ok=%u booted=%u; state %s; BO cap %u MiB)\n", + ANE_ABI_M2_MAJOR, 0, + legacy_only, ane->chman_ok, + ane->fw ? ane->fw->booted : 0, + ane->held ? "HELD" : "ready", bo_total_max_mb); + } + + return 0; + +err_pm_or_hold: + if (ane->held) + dev_warn(dev, + "probe failed after CPU start (%pe) — binding fenced; power/rings/IRQ HELD until reboot\n", + ERR_PTR(ret)); + else { + pm_runtime_put_sync_suspend(dev); + pm_runtime_disable(dev); + } + return ret; +} + +static void ane_rtclient_remove(struct platform_device *pdev) +{ + struct ane_rtclient *ane = platform_get_drvdata(pdev); + + if (READ_ONCE(ane_t6021_perf_ane) == ane) + WRITE_ONCE(ane_t6021_perf_ane, NULL); + + cancel_delayed_work_sync(&ane->poll_work); + + if (ane->held) + dev_warn(&pdev->dev, + "remove HELD: no teardown — reboot reclaims\n"); +} + +static const struct of_device_id ane_rtclient_of_match[] = { + { .compatible = "apple,t6020-ane", .data = &ane_t6020_soc }, + { .compatible = "apple,t6021-ane", .data = &ane_t6021_soc }, + { .compatible = "apple,t6022-ane", .data = &ane_t6022_soc }, + { .compatible = "apple,t8112-ane", .data = &ane_t8112_soc }, + { } +}; +MODULE_DEVICE_TABLE(of, ane_rtclient_of_match); + +static struct platform_driver ane_rtclient_driver = { + .driver = { + .name = "ane_t6021", + .of_match_table = ane_rtclient_of_match, + .suppress_bind_attrs = true, + }, + .probe = ane_rtclient_probe, + .remove = ane_rtclient_remove, +}; + +static int __init ane_rtclient_init(void) +{ + int ret = platform_driver_register(&ane_rtclient_driver); + + if (ret) + ane_t6021_trace_free(); + return ret; +} +module_init(ane_rtclient_init); + +static void __exit ane_rtclient_exit(void) +{ + platform_driver_unregister(&ane_rtclient_driver); + ane_t6021_trace_free(); +} +module_exit(ane_rtclient_exit); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("Apple Neural Engine (T6021/M2) installed module"); diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c new file mode 100644 index 0000000000000..0e98c48d2aff1 --- /dev/null +++ b/drivers/accel/ane/ane_tm.c @@ -0,0 +1,652 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2022 Eileen Yoon */ + +#include +#include +#include +#include +#include "ane_tm.h" + +#define ANE_TQ_COUNT 8 +static const int TQ_PRTY_TABLE[ANE_TQ_COUNT] = { 0x1, 0x2, 0x3, 0x4, + 0x5, 0x6, 0x1e, 0x1f }; + +#define ANE_TM_BASE 0x20000 +#define ANE_TQ_BASE 0x21000 + +#define TM_ADDR 0x0 +#define TM_INFO 0x4 +#define TM_PUSH 0x8 +#define TM_TQ_EN 0xc + +#define TM_IRQ_EVTC(line) (0x14 + (line * 0x14)) +#define TM_IRQ_INFO(line) (0x18 + (line * 0x14)) +#define TM_IRQ_UNK1(line) (0x1c + (line * 0x14)) +#define TM_IRQ_TMST(line) (0x20 + (line * 0x14)) +#define TM_IRQ_UNK2(line) (0x24 + (line * 0x14)) + +#define TM_COMMITTED 0x44 +#define TM_STATUS 0x54 +#define TM_ERROR1 0x58 +#define TM_ERROR2 0x5c +#define TM_ERROR3 0x60 +#define TM_IRQ_EN1 0x68 +#define TM_IRQ_ACK 0x6c +#define TM_IRQ_EN2 0x70 + +#define TQ_STATUS(qid) (0x000 + (qid * 0x148)) +#define TQ_PRTY(qid) (0x010 + (qid * 0x148)) +#define TQ_VACANT(qid) (0x014 + (qid * 0x148)) +#define TQ_INFO(qid) (0x01c + (qid * 0x148)) + +#define TQ_BAR1(qid, bdx) (0x020 + (qid * 0x148) + (bdx * 0x4)) +#define TQ_NID1(qid) (0x0a0 + (qid * 0x148)) +#define TQ_SIZE2(qid) (0x0a4 + (qid * 0x148)) +#define TQ_ADDR2(qid) (0x0a8 + (qid * 0x148)) + +#define TQ_BAR2(qid, bdx) (0x0ac + (qid * 0x148) + (bdx * 0x4)) +#define TQ_NID2(qid) (0x12c + (qid * 0x148)) +#define TQ_SIZE1(qid) (0x130 + (qid * 0x148)) +#define TQ_ADDR1(qid) (0x134 + (qid * 0x148)) + +#define TM_IS_IDLE 0x1 +#define TM_IS_FINE 0x22222222 + +#define tm_read32(ane, off) (readl(ane->engine + ANE_TM_BASE + off)) +#define tq_read32(ane, off) (readl(ane->engine + ANE_TQ_BASE + off)) +#define tm_write32(ane, off, val) (writel(val, ane->engine + ANE_TM_BASE + off)) +#define tq_write32(ane, off, val) (writel(val, ane->engine + ANE_TQ_BASE + off)) + +/* The ane SET block (m1n1 ANE.ps_map) maps the pmgr power-state words + * for this engine (set0, base, set1..4). pmgr reads are always safe and + * give recovery its ACTUAL power evidence; the SET words themselves are + * firmware-locked: a direct write external-aborts the SoC. Bisect + * evidence, 2026-09-16: the T6001 kill is netconsole-named at + * 0x28e08c000 (PS_SET0 down, all sets gated); T8103 hard-reset the same + * way at 0x23b70c000 with the 95dbcf3-era gate armed. No code here ever + * writes the SET block. + */ +#define ANE_PS_ACTUAL_MASK 0xf0 +#define ANE_PS_WORDS 6 /* set0, base, set1..4 */ + +/* ACTUAL nibble of each SET word, word 0 in the low nibble; 0 when the + * SET block is unmapped. pmgr registers only: engine MMIO is never + * read for power state (a readl through a warm gate external-aborts + * and hard-resets the machine). + */ +u32 ane_ps_act(struct ane_device *ane) +{ + u32 v = 0; + int i; + + if (!ane->ps) + return 0; + for (i = 0; i < ANE_PS_WORDS; i++) + v |= ((readl(ane->ps + i * 8) & ANE_PS_ACTUAL_MASK) >> 4) + << (i * 4); + return v; +} + +/* Bisect probe: per-word named reads of the SET window. Each word logs + * before its readl, so a window whose address does not decode on this + * SoC is named by the last off-box line (word index + byte offset) + * instead of a silent hard reset between two other prints. + */ +u32 ane_ps_act_probe(struct ane_device *ane) +{ + u32 v = 0; + int i; + + if (!ane->ps) { + dev_info(ane->dev, "ps probe: SET window unmapped\n"); + return 0; + } + dev_info(ane->dev, "ps probe: SET window at %pap, %d words\n", + &ane->ps_base, ANE_PS_WORDS); + for (i = 0; i < ANE_PS_WORDS; i++) { + u32 w; + + dev_info(ane->dev, "ps probe: word %d @ ps+0x%02x reading\n", + i, i * 8); + w = readl(ane->ps + i * 8); + v |= ((w & ANE_PS_ACTUAL_MASK) >> 4) << (i * 4); + dev_info(ane->dev, "ps probe: word %d -> %#x\n", i, w); + } + return v; +} + +/* Recovery-path MMIO logging. Every write prints before and after, and + * every engine read prints its value, each line carrying the pmgr + * ACTUAL of the owning partitions. A write that external-aborts the + * SoC is then named by the last line the off-box netconsole carried, + * and the bisect starts from that register instead of a guess. + */ +static void ane_rec_writel(struct ane_device *ane, const char *reg, + void __iomem *addr, u32 val) +{ + dev_info(ane->dev, "ANEWR %s <- %#x (ps act %#x)\n", reg, val, + ane_ps_act(ane)); + writel(val, addr); + dev_info(ane->dev, "ANEWR %s wrote (ps act %#x)\n", reg, + ane_ps_act(ane)); +} + +static u32 ane_rec_read32(struct ane_device *ane, const char *reg, + void __iomem *addr) +{ + u32 val = readl(addr); + + dev_info(ane->dev, "ANERD %s -> %#x (ps act %#x)\n", reg, val, + ane_ps_act(ane)); + return val; +} + +u32 ane_tm_ps_act(struct ane_device *ane) +{ + return ane_ps_act(ane); +} + +void ane_tm_enable(struct ane_device *ane, bool rec) +{ + void __iomem *tq_en = ane->engine + ANE_TM_BASE + TM_TQ_EN; + u32 val = rec ? ane_rec_read32(ane, "TM_TQ_EN tm+0x0c", tq_en) + : readl(tq_en); + char reg[24]; + + val |= 0x1000; + if (rec) + ane_rec_writel(ane, "TM_TQ_EN tm+0x0c", tq_en, val); + else + writel(val, tq_en); + + for (int qid = 0; qid < ANE_TQ_COUNT; qid++) { + void __iomem *prty = + ane->engine + ANE_TQ_BASE + TQ_PRTY(qid); + + if (rec) { + snprintf(reg, sizeof(reg), "TQ_PRTY[%d] tq+%#x", qid, + TQ_PRTY(qid)); + ane_rec_writel(ane, reg, prty, TQ_PRTY_TABLE[qid]); + } else { + writel(TQ_PRTY_TABLE[qid], prty); + } + } + + if (rec) { + ane_rec_writel(ane, "TM_IRQ_EN1 tm+0x68", + ane->engine + ANE_TM_BASE + TM_IRQ_EN1, + 0x4000000); + ane_rec_writel(ane, "TM_IRQ_EN2 tm+0x70", + ane->engine + ANE_TM_BASE + TM_IRQ_EN2, 0x6); + } else { + tm_write32(ane, TM_IRQ_EN1, 0x4000000); + tm_write32(ane, TM_IRQ_EN2, 0x6); + } +} + +u32 ane_tm_status(struct ane_device *ane) +{ + return tm_read32(ane, TM_STATUS); +} + +int ane_tm_enqueue(struct ane_device *ane, struct ane_request *req) +{ + int qid = req->qid; + + tq_write32(ane, TQ_STATUS(qid), 0x1); + + for (int bdx = 0; bdx < ANE_TILE_COUNT; bdx++) { + tq_write32(ane, TQ_BAR1(qid, bdx), req->bar[bdx]); + } + + tq_write32(ane, TQ_SIZE1(qid), ((req->td_size >> 2) - 1) << 0x10); + tq_write32(ane, TQ_ADDR1(qid), req->btsp_iova); + tq_write32(ane, TQ_NID1(qid), (req->nid & 0xff) << 8 | 1); + + return 0; +} + +static void ane_tm_push_tq(struct ane_device *ane, struct ane_request *req) +{ + int qid = req->qid; + + tm_write32(ane, TM_ADDR, tq_read32(ane, TQ_ADDR1(qid))); + tm_write32(ane, TM_INFO, tq_read32(ane, TQ_SIZE1(qid)) | req->td_count); + tm_write32(ane, TM_PUSH, TQ_PRTY_TABLE[qid] | (qid & 7) << 8); // magic +} + +static int ane_tm_collect_events(struct ane_device *ane, + struct ane_request *req, u32 *finished) +{ + for (unsigned int line = 0; line < 2; line++) { + u32 count = tm_read32(ane, TM_IRQ_EVTC(line)); + + if (count > 64) + return -EIO; + for (u32 n = 0; n < count; n++) { + u32 info = tm_read32(ane, TM_IRQ_INFO(line)); + + tm_read32(ane, TM_IRQ_UNK1(line)); + tm_read32(ane, TM_IRQ_TMST(line)); + tm_read32(ane, TM_IRQ_UNK2(line)); + if (req && info == (0x05000000 | (req->nid << 16) | + (req->td_count - 1))) + *finished |= BIT(line); + } + } + tm_write32(ane, TM_IRQ_ACK, tm_read32(ane, TM_IRQ_ACK) | 2); + return *finished == 3 && (tm_read32(ane, TM_STATUS) & TM_IS_IDLE); +} + +/* read_poll_timeout op: consult the DART latch before any engine access. + * Returns 1 to end the poll when a fault is latched; the caller then + * handles the fault without ever reading the wedged engine. + */ +static int ane_tm_poll_step(struct ane_device *ane, struct ane_request *req, + u32 *finished) +{ + if (ane_dart_faulted(ane, NULL, NULL)) + return 1; + return ane_tm_collect_events(ane, req, finished); +} + +int ane_tm_execute(struct ane_device *ane, struct ane_request *req) +{ + u32 finished = 0; + u32 fault_status = 0; + u64 fault_iova = 0; + struct ane_dart_scratch scratch[ANE_DART_SCRATCH_MAX]; + int scratch_pages = 0; + bool faulted = false; + int err, status; + + lockdep_assert_held(&ane->engine_lock); + ane_dart_mask(ane); + + err = ane_tm_collect_events(ane, NULL, &finished); + if (err < 0) + goto wedge; + wmb(); + ane_tm_push_tq(ane, req); + + for (;;) { + /* Latch-first completion poll. Engine register reads hang + * jwm1 once a DART fault has landed (lockups 1 and 3: the + * journal ends inside the 1-microsecond completion poll, + * before any fault handling ran), so the poll op consults + * the DART error latch first and stops the poll before the + * engine is touched. Residual hazard: a fault landing + * between one iteration's latch read and engine read. + */ + err = read_poll_timeout(ane_tm_poll_step, status, + status != 0, 1, 1000000, false, + ane, req, &finished); + if (!err && status < 0) + err = status; + if (ane_dart_faulted(ane, &fault_iova, &fault_status)) { + faulted = true; + if (scratch_pages >= ANE_DART_SCRATCH_MAX) + break; + if (ane_dart_drain_fault(ane, fault_iova, scratch, + &scratch_pages)) + break; + /* The retried transaction now completes; poll on. */ + continue; + } + break; + } + + if (faulted) { + /* The faulting program drained through the scratch pages + * and the engine is idle again (the latch is clear or the + * poll would still be running). Gate the queue with the + * normal completion writes, hand the scratch pages back, + * and fail this request. No partition power cycle, no + * stream disable: the page tables were never changed by + * the fault. + */ + if (err || ane_dart_faulted(ane, NULL, NULL)) { + /* Drain failed or the drained program never reached + * completion: the engine is not idle and access is + * off the table. wedge releases the scratch. + */ + err = err ?: -EIO; + goto wedge; + } + status = tq_read32(ane, TQ_NID1(req->qid)); + tq_write32(ane, TQ_NID1(req->qid), status & ~1U); + rmb(); + tq_write32(ane, TQ_STATUS(req->qid), 0x0); + ane_dart_release_scratch(ane, scratch, scratch_pages); + ane_dart_unmask(ane); + dev_err(ane->dev, + "DART fault contained: status=%#x iova=%#llx scratch=%d\n", + fault_status, fault_iova, scratch_pages); + return -EIO; + } + if (err) + goto wedge; + status = tq_read32(ane, TQ_NID1(req->qid)); + if (((status >> 8) & 0xff) != req->nid) { + err = -EIO; + goto wedge; + } + tq_write32(ane, TQ_NID1(req->qid), status & ~1U); + rmb(); + tq_write32(ane, TQ_STATUS(req->qid), 0x0); + ane_dart_unmask(ane); + return 0; + +wedge: + ane_dart_release_scratch(ane, scratch, scratch_pages); + ane_dart_unmask(ane); + if (atomic_xchg(&ane->wedged, 1) == 0) { + __module_get(THIS_MODULE); + dev_err(ane->dev, + "tm completion failed: %d, finish lines=%x (q%d nid=%#x)\n", + err, finished, req->qid, req->nid); + } + + /* One bounded recovery attempt: stop the tm, power-cycle the engine + * and return to accepting work. Only a failed reset preserves + * resources until reboot. + */ + if (ane_tm_recover(ane) < 0) { + if (ane->tm_retention) + dev_err(ane->dev, + "recovery failed; preserving resources until module reload or reboot (tm/tq file retained through the cycle: the latched task error parks the TM in place; rmmod+insmod restores service)\n"); + else + dev_err(ane->dev, + "recovery failed; preserving resources until reboot\n"); + } + return err; +} + +/* + * Bounded recovery after a failed task. The only reset this driver knows + * is the partition power cycle system sleep already performs on this + * hardware. With the several ANE power partitions attached as genpd + * devices (T8103 five, T6001 similar), gating happens on those devices; + * with a single domain attached directly to the device, on the device + * itself. Gating the partitions stops any DMA still fetching the dead + * task and clears the tm register file; ungating brings the engine back + * through the probe resume path (ane_tm_enable), then the task manager + * must report idle. BO mappings deliberately stay in place: they remain + * coherent through the cycle and valid for the next submit, and once the + * wedge clears, BO_FREE unmaps them through the normal path again. + * Callers hold engine_lock. + * + * T6001 note, bisect evidence 2026-09-16: its set0/base islands are + * firmware-locked (direct pmgr writes external-abort; see the SET block + * comment above) and hold the tm/tq file in retention through any + * genpd cycle - TQ_EN still reads 0x3000 after a 20 ms and a 2 s gate, + * and tasks dispatched afterwards complete but compute nondeterministic + * garbage. The idle-or-fresh poll below therefore fails on T6001 and + * recovery preserves until reboot instead of serving wrong data. + */ + +/* No engine MMIO unless the owning partitions read powered on (ACTUAL + * nibble per word): a readl through a warm gate external-aborts and + * hard resets the machine. Covers set0, base and set1..4 from the SET + * block map; sys_cpu rides its own genpd resume and has no cell in + * this block on T6001. + */ +static int ane_ps_verify_on(struct ane_device *ane) +{ + u32 act = 0; + int err = -ETIMEDOUT; + int i; + + if (!ane->ps) + return 0; + for (i = 0; i < 100; i++) { + act = ane_ps_act(ane); + if (act == ANE_PS_ALL_ON) { + err = 0; + break; + } + usleep_range(1000, 2000); + } + dev_info(ane->dev, "ANERD ps verify act=%#x err=%d\n", act, err); + return err; +} + +static int ane_pd_cycle(struct ane_device *ane) +{ + int err = 0; + + ane->recovering = true; + if (ane->pd_count > 1) { + int gated = 0; + + for (int i = 0; i < ane->pd_count; i++) { + pm_runtime_get_noresume(ane->pd_dev[i]); + gated = i + 1; + dev_info(ane->dev, + "ANERD pd[%d] %s force_suspend begin (ps act %#x)\n", + i, dev_name(ane->pd_dev[i]), ane_ps_act(ane)); + err = pm_runtime_force_suspend(ane->pd_dev[i]); + dev_info(ane->dev, + "ANERD pd[%d] force_suspend -> %d (ps act %#x)\n", + i, err, ane_ps_act(ane)); + if (err) + break; + } + if (!err) + for (int i = 0; i < ane->pd_count; i++) { + dev_info(ane->dev, + "ANERD pd[%d] %s force_resume begin (ps act %#x)\n", + i, dev_name(ane->pd_dev[i]), + ane_ps_act(ane)); + err = pm_runtime_force_resume(ane->pd_dev[i]); + dev_info(ane->dev, + "ANERD pd[%d] force_resume -> %d (ps act %#x)\n", + i, err, ane_ps_act(ane)); + if (err) + break; + } + while (gated--) + pm_runtime_put_noidle(ane->pd_dev[gated]); + } else { + /* Pin a second usage ref for the cycle: force_suspend only + * marks needs_force_resume when a ref beyond the probe one + * is held, and without that mark force_resume would leave + * the partition gated. + */ + pm_runtime_get_noresume(ane->dev); + dev_info(ane->dev, "ANERD dev force_suspend begin\n"); + err = pm_runtime_force_suspend(ane->dev); + dev_info(ane->dev, "ANERD dev force_suspend -> %d\n", err); + if (!err) { + dev_info(ane->dev, "ANERD dev force_resume begin\n"); + err = pm_runtime_force_resume(ane->dev); + dev_info(ane->dev, "ANERD dev force_resume -> %d\n", + err); + } + pm_runtime_put_noidle(ane->dev); + } + ane->recovering = false; + + return err; +} + +/* + * Drain the task-manager state a timed-out task leaves behind when the + * tm/tq file survives the power cycle in retention (T6001; descriptor + * tm_retention). T8103 never runs this: its cycle is a full POR of the + * file, and the re-arm below starts it clean. + * + * Two things must go, or the retained TM never reads idle again: + * - pending events on both IRQ lines. Each event pops by reading + * INFO/UNK1/TMST/UNK2, exactly as ane_tm_collect_events pops them; + * a stale backlog (or one over the 64-entry collect cap) would make + * the next submit's completion poll miss or fail. + * - the latched queue entry of the dead task. TQ_STATUS/NID1 get the + * same clear the normal completion path gives a finished queue. + */ +static void ane_tm_drain_retained(struct ane_device *ane) +{ + int line, qid; + + /* Stop the TM first: the cycle leaves the enable|halt latch set + * (TQ_EN 0x3000, 2026-09-16 evidence). Clear both bits so the + * re-arm below starts the TM from a defined stopped state. + */ + ane_rec_writel(ane, "TM_TQ_EN stop tm+0x0c", + ane->engine + ANE_TM_BASE + TM_TQ_EN, + tm_read32(ane, TM_TQ_EN) & ~0x3000U); + + for (line = 0; line < 2; line++) { + u32 count = tm_read32(ane, TM_IRQ_EVTC(line)); + u32 n; + + if (count > 64) + count = 64; + for (n = 0; n < count; n++) { + tm_read32(ane, TM_IRQ_INFO(line)); + tm_read32(ane, TM_IRQ_UNK1(line)); + tm_read32(ane, TM_IRQ_TMST(line)); + tm_read32(ane, TM_IRQ_UNK2(line)); + } + } + tm_write32(ane, TM_IRQ_ACK, tm_read32(ane, TM_IRQ_ACK) | 3); + + /* The dead task leaves per-queue error codes latched here (seen + * 0x22222222 / 0x2222: four-bit code 2 per TQ slot). While any + * latch is set the TM stays halted and TM_STATUS reads 0. Try the + * W1C convention first (write the read value back), fall back to + * plain zero-clear, and log what this silicon answered to. + */ + { + static const u16 err_reg[3] = { TM_ERROR1, TM_ERROR2, + TM_ERROR3 }; + char reg[24]; + int ei; + + for (ei = 0; ei < 3; ei++) { + void __iomem *addr = + ane->engine + ANE_TM_BASE + err_reg[ei]; + u32 val = readl(addr); + + if (!val) + continue; + writel(val, addr); + if (readl(addr)) + writel(0x0, addr); + snprintf(reg, sizeof(reg), "TM_ERROR%d clear tm+%#x", + ei + 1, err_reg[ei]); + ane_rec_read32(ane, reg, addr); + } + } + + for (qid = 0; qid < ANE_TQ_COUNT; qid++) { + u32 nid = tq_read32(ane, TQ_NID1(qid)); + + tq_write32(ane, TQ_STATUS(qid), 0x0); + if (nid & 1) + tq_write32(ane, TQ_NID1(qid), nid & ~1U); + } + + /* Retention evidence for the off-box console: what the dead task + * left in the committed counter and the error latches. + */ + ane_rec_read32(ane, "TM_COMMITTED tm+0x44 (drain)", + ane->engine + ANE_TM_BASE + TM_COMMITTED); + ane_rec_read32(ane, "TM_ERROR1 tm+0x58 (drain)", + ane->engine + ANE_TM_BASE + TM_ERROR1); + ane_rec_read32(ane, "TM_ERROR2 tm+0x5c (drain)", + ane->engine + ANE_TM_BASE + TM_ERROR2); + ane_rec_read32(ane, "TM_ERROR3 tm+0x60 (drain)", + ane->engine + ANE_TM_BASE + TM_ERROR3); +} + +int ane_tm_recover(struct ane_device *ane) +{ + u32 status; + int err; + + lockdep_assert_held(&ane->engine_lock); + if (!atomic_read(&ane->wedged)) + return 0; + + dev_err(ane->dev, "recovering: power-cycling engine partitions\n"); + + err = ane_pd_cycle(ane); + if (err) { + dev_err(ane->dev, "recovery: engine power cycle failed: %d\n", + err); + return err; + } + + /* No engine MMIO before the islands read powered on. */ + err = ane_ps_verify_on(ane); + if (err) { + dev_err(ane->dev, + "recovery: ane set islands not powered on: %d\n", err); + return err; + } + + /* T6001 (tm_retention): the cycle did NOT clear the tm/tq file — + * the timed-out task's events and queue entry are still latched. + * Drain them, or the TM below never reads idle and recovery + * degrades to preserve-until-reboot. + */ + if (ane->tm_retention) + ane_tm_drain_retained(ane); + + /* Power-on reset cleared the tm register file; re-arm it exactly + * like the probe resume path does. + */ + ane_tm_enable(ane, true); + + err = readl_poll_timeout(ane->engine + ANE_TM_BASE + TM_STATUS, + status, + (status & TM_IS_IDLE) || + status == ane->tm_status_fresh, + 100, 1000000); + status = ane_rec_read32(ane, "TM_STATUS tm+0x54", + ane->engine + ANE_TM_BASE + TM_STATUS); + if (err) { + dev_err(ane->dev, "recovery: tm not idle after reset: %#x\n", + status); + return err; + } + + if (atomic_xchg(&ane->wedged, 0)) { + module_put(THIS_MODULE); /* drop the wedge pin */ + /* The power cycle above quiesced every transaction, so the + * wedge-preserved mappings (dead BOs kept alive only to + * stop IOVA teardown under active DMA) can now be unmapped + * and their ranges handed back to the allocator. Without + * this reclaim the ranges would stay pinned for the whole + * module lifetime. + */ + ane_reclaim_preserved(ane); + dev_info(ane->dev, "tm recovered: idle, accepting work again\n"); + } + return 0; +} + +/* + * Drop the wedge pin on demand. The recovery path in ane_tm_recover + * does an atomic_xchg + module_put, but only on its success branch - + * a real -110 with the engine stuck leaves ane->wedged set and the + * module refcount one too high, so rmmod fails forever and the bug + * becomes a kernel-brick-without-reboot. ane_drm_postclose calls + * this unconditionally so every session close releases the pin, + * letting the operator unload the ko for an updated build even when + * the engine itself cannot be cleared in software. + * + * Pair count: must follow an ane_wedge_set() that called + * __module_get(THIS_MODULE). Today the only such set is in the wedge: + * branch of ane_tm_execute(); future sets must call this in their + * clean-up path too. + */ +void ane_wedge_clear(struct ane_device *ane) +{ + if (atomic_xchg(&ane->wedged, 0)) { + module_put(THIS_MODULE); + dev_info(ane->dev, + "wedge pin released (engine state unknown)\n"); + } +} diff --git a/drivers/accel/ane/ane_tm.h b/drivers/accel/ane/ane_tm.h new file mode 100644 index 0000000000000..94d425ab8d8b7 --- /dev/null +++ b/drivers/accel/ane/ane_tm.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* Copyright 2022 Eileen Yoon */ + +#ifndef __ANE_TM_H__ +#define __ANE_TM_H__ + +#include "ane.h" + +void ane_tm_enable(struct ane_device *ane, bool rec); +u32 ane_tm_status(struct ane_device *ane); +u32 ane_ps_act(struct ane_device *ane); +u32 ane_ps_act_probe(struct ane_device *ane); +bool ane_tm_islands_on(struct ane_device *ane, u32 *act); +int ane_tm_enqueue(struct ane_device *ane, struct ane_request *req); +int ane_tm_execute(struct ane_device *ane, struct ane_request *req); +int ane_tm_recover(struct ane_device *ane); +#define ANE_PS_ALL_ON ((1U << (4 * 6)) - 1) +u32 ane_tm_ps_act(struct ane_device *ane); + +#endif /* __ANE_TM_H__ */ diff --git a/include/uapi/drm/ane_accel.h b/include/uapi/drm/ane_accel.h new file mode 100644 index 0000000000000..e5fd9d12d1d63 --- /dev/null +++ b/include/uapi/drm/ane_accel.h @@ -0,0 +1,130 @@ +/* SPDX-License-Identifier: (GPL-2.0-only WITH Linux-syscall-note) OR MIT */ +/* Copyright 2022 Eileen Yoon */ + +#ifndef __ANE_ACCEL_H__ +#define __ANE_ACCEL_H__ + +#include "drm.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +#define ANE_TILE_COUNT 0x20 +#define ANE_FIFO_NID 0x40 +#define ANE_CMD_GRAN 0x10 + +/* ABI 1: successful SUBMIT guarantees terminal completion and CPU visibility. */ +#define ANE_ABI_MAJOR 1 + +/* + * ABI 2 (T6021 / M2, H14 firmware programs): the driver reports + * DRM_IOCTL_VERSION major 2 and rejects DRM_ANE_SUBMIT. The M1 libane + * requires major 1, so it cannot submit M1 frames to an M2 device. + * A successful DRM_ANE_EXEC guarantees terminal completion (firmware ack + * and task-queue idle) and CPU visibility of the output buffers. + */ +#define ANE_ABI_M2_MAJOR 2 +#define ANE_M2_MAX_SECTIONS 16 +#define ANE_M2_MAX_BINDS 64 + +#define DRM_ANE_BO_INIT 0x1 +#define DRM_ANE_BO_FREE 0x2 +#define DRM_ANE_SUBMIT 0x3 +#define DRM_ANE_PROG_LOAD 0x4 +#define DRM_ANE_PROC_CREATE 0x5 +#define DRM_ANE_EXEC 0x6 + +struct drm_ane_bo_init { + __u32 handle; + __u32 pad; + __u64 size; + __u64 offset; +}; + +struct drm_ane_bo_free { + __u32 handle; + __u32 pad; +}; + +struct drm_ane_submit { + __u64 tsk_size; + __u32 td_count; + __u32 td_size; + __u32 handles[ANE_TILE_COUNT]; + __u32 btsp_handle; + __u32 pad; +}; + +/* One firmware program section, already built by userspace, held in a BO. */ +struct drm_ane_section { + __u32 id; /* firmware section id */ + __u32 bo_handle; /* BO holding the bytes */ + __u64 size; + __u64 offset; /* byte offset inside the BO */ +}; + +/* A buffer whose IOVA and size the driver patches into a generic entry. */ +struct drm_ane_generic_bind { + __u32 buffer_id; + __u32 bo_handle; + __u32 type; + __u32 pad; + __u64 size; +}; + +struct drm_ane_prog_load { + __u64 sections_ptr; /* struct drm_ane_section[section_count] */ + __u64 generic_ptr; /* struct drm_ane_generic_bind[generic_count] */ + __u32 section_count; + __u32 generic_count; + __u32 prog_id_out; + __u32 pad; +}; + +struct drm_ane_proc_create { + __u32 prog_id; + __u32 proc_id_out; +}; + +/* Per-call buffer binding: an input or output for one procedure call. */ +struct drm_ane_exec_io { + __u32 buffer_id; + __u32 bo_handle; + __u32 type; + __u32 flags; + __u64 dma; /* in only, reserved: the driver binds the + * IOVA from bo_handle + */ + __u64 size; +}; + +struct drm_ane_exec { + __u32 prog_id; + __u32 proc_id; + __u32 priority; /* 2..7 */ + __u32 timeout_ms; + __u32 count; /* 1..ANE_M2_MAX_BINDS */ + __u32 pad; + __u64 io_ptr; /* struct drm_ane_exec_io[count] */ +}; + +#define DRM_IOCTL_ANE_BO_INIT \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_BO_INIT, struct drm_ane_bo_init) +#define DRM_IOCTL_ANE_BO_FREE \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_BO_FREE, struct drm_ane_bo_free) +#define DRM_IOCTL_ANE_SUBMIT \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_SUBMIT, struct drm_ane_submit) + +#define DRM_IOCTL_ANE_PROG_LOAD \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_PROG_LOAD, struct drm_ane_prog_load) +#define DRM_IOCTL_ANE_PROC_CREATE \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_PROC_CREATE, struct drm_ane_proc_create) +#define DRM_IOCTL_ANE_EXEC \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_EXEC, struct drm_ane_exec) + +#if defined(__cplusplus) +} +#endif + +#endif /* __ANE_ACCEL_H__ */ From f790ae9b5801bcccbfae025e89e7b0445041f8af Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:27:34 -0500 Subject: [PATCH 06/26] arm64: dts: apple: t8103: Add the ANE, its DARTs and power states Describe the M1 Neural Engine: the engine window at 0x26bc04000, the three ANE DARTs, and the ane_base and ane_set1..5 power states (ane_sys_cpu -> ane_base -> ane_set1..5). apple-dart owns the DARTs and the engine maps through their IOMMU domain. The ane driver binds these nodes. They equal, property for property with phandles compared by target path, the live device tree of a MacBook Pro 13" M1 (j293) on which the out-of-tree build of the same driver code was bound on 2026-09-30 (linux-asahi 7.1.13): 80 properties over the ane node, its DARTs and the eight ANE power states. Enabled: Linux starts no ANE firmware on T8103. Until the ane module loads, apple-dart binds the three DARTs and apple-pmgr-pwrstate registers the new states, as on that machine. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t8103-pmgr.dtsi | 54 +++++++++++++++++++++++ arch/arm64/boot/dts/apple/t8103.dtsi | 46 +++++++++++++++++++ 2 files changed, 100 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi index 4a399bc8f0276..252c6914d690d 100644 --- a/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi @@ -1003,6 +1003,60 @@ power-domains = <&ps_ane_sys>; }; + ps_ane_base: power-controller@c008 { + compatible = "apple,t8103-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc008 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_base"; + power-domains = <&ps_ane_sys_cpu>; + }; + + ps_ane_set1: power-controller@c010 { + compatible = "apple,t8103-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc010 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set1"; + power-domains = <&ps_ane_base>; + }; + + ps_ane_set2: power-controller@c018 { + compatible = "apple,t8103-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc018 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set2"; + power-domains = <&ps_ane_base>; + }; + + ps_ane_set3: power-controller@c020 { + compatible = "apple,t8103-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc020 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set3"; + power-domains = <&ps_ane_base>; + }; + + ps_ane_set4: power-controller@c028 { + compatible = "apple,t8103-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc028 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set4"; + power-domains = <&ps_ane_base>; + }; + + ps_ane_set5: power-controller@c030 { + compatible = "apple,t8103-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc030 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set5"; + power-domains = <&ps_ane_base>; + }; + ps_disp0_cpu0: power-controller@10018 { compatible = "apple,t8103-pmgr-pwrstate", "apple,pmgr-pwrstate"; reg = <0x10018 4>; diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 4682da893992c..16ac8bb5e206d 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -1445,6 +1445,52 @@ power-domains = <&ps_avd_sys>; }; + ane_dart0: iommu@26b800000 { + compatible = "apple,t8103-dart"; + reg = <0x2 0x6b800000 0x0 0x4000>; + #iommu-cells = <1>; + apple,dma-range = <0x0 0x0 0x0 0xe0000000>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys>; + status = "okay"; + }; + + ane_dart1: iommu@26b810000 { + compatible = "apple,t8103-dart"; + reg = <0x2 0x6b810000 0x0 0x4000>; + #iommu-cells = <1>; + apple,dma-range = <0x0 0x0 0x0 0xe0000000>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys>; + status = "okay"; + }; + + ane_dart2: iommu@26b820000 { + compatible = "apple,t8103-dart"; + reg = <0x2 0x6b820000 0x0 0x4000>; + #iommu-cells = <1>; + apple,dma-range = <0x0 0x0 0x0 0xe0000000>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys>; + status = "okay"; + }; + + ane: ane@26bc04000 { + compatible = "apple,t8103-ane"; + reg = <0x2 0x6bc04000 0x0 0x24000>; + reg-names = "engine"; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "ane"; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_set1>, <&ps_ane_set2>, + <&ps_ane_set3>, <&ps_ane_set4>, <&ps_ane_set5>; + status = "okay"; + }; + dispext0_dart: iommu@271304000 { compatible = "apple,t8103-dart"; reg = <0x2 0x71304000 0x0 0x4000>; From 148d9aca7f3ce68f0a47ef12d6da46873ddd5016 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:27:34 -0500 Subject: [PATCH 07/26] arm64: dts: apple: t600x: Add the die 0 ANE, its DARTs and power states Describe the die 0 Neural Engine of the M1 Pro, Max and Ultra: the engine window at 0x285c04000, the three ANE DARTs, and the ane_set0, ane_base and ane_set1..5 power states (ane_sys_cpu -> ane_set0 -> ane_base -> ane_set1..5). ane_set5 is described but the ane node does not use it: it lies past the end of the ADT ANE pmgr range (0xc02c). The states are added on die 0 only; the M1 Ultra die 1 ANE stays undescribed. The pmgr window already spans 0x1c000 here, so it covers 0xc000..0xc030 without change. These nodes equal the packaged omarchy-ane device-tree overlay that booted on a MacBook Pro 16" M1 Max (j316c) on 2026-09-30 (linux-asahi 7.1.13): the out-of-tree build of the ane driver bound at 285c04000.ane and an inference smoke test matched its reference output hash. Property for property, with phandles compared by target path, the subtree is identical. One name differs: the overlay calls the node ane@284000000 (the ADT engine block base), which dtc W=1 flags (simple_bus_reg) because reg starts at 0x285c04000. It is ane@285c04000 here. The driver matches on the compatible. Enabled: Linux starts no ANE firmware on T6000. Until the ane module loads, apple-dart binds the three DARTs and apple-pmgr-pwrstate registers the new states, as on that machine. The M1 Pro and M1 Ultra share this die 0 block; only the M1 Max has run it. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t600x-die0.dtsi | 43 ++++++++++++++ arch/arm64/boot/dts/apple/t600x-pmgr.dtsi | 69 +++++++++++++++++++++++ 2 files changed, 112 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t600x-die0.dtsi b/arch/arm64/boot/dts/apple/t600x-die0.dtsi index 1be41d6ff5fca..5a4641fa26c59 100644 --- a/arch/arm64/boot/dts/apple/t600x-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t600x-die0.dtsi @@ -7,6 +7,49 @@ */ + ane_dart0: iommu@285800000 { + compatible = "apple,t6000-dart"; + reg = <0x2 0x85800000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys>; + status = "okay"; + }; + + ane_dart1: iommu@285810000 { + compatible = "apple,t6000-dart"; + reg = <0x2 0x85810000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys_cpu>; + status = "okay"; + }; + + ane_dart2: iommu@285820000 { + compatible = "apple,t6000-dart"; + reg = <0x2 0x85820000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys_cpu>; + status = "okay"; + }; + + ane: ane@285c04000 { + compatible = "apple,t6000-ane"; + reg = <0x2 0x85c04000 0x0 0x24000>; + reg-names = "engine"; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "ane"; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_sys_cpu>, <&ps_ane_set1>, + <&ps_ane_set2>, <&ps_ane_set3>, <&ps_ane_set4>; + status = "okay"; + }; + nco: clock-controller@28e03c000 { compatible = "apple,t6000-nco", "apple,nco"; reg = <0x2 0x8e03c000 0x0 0x14000>; diff --git a/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi b/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi index 8b2c2cacce8c1..fed2d79a8ba8a 100644 --- a/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi @@ -675,6 +675,75 @@ #reset-cells = <0>; label = DIE_LABEL(trace_fab); }; + +#if DIE_NO == 0 + /* + * Only the die 0 ANE is described. The ane node leaves set5 out: + * it lies past the end of the ADT ANE pmgr range (0xc02c). + */ + DIE_NODE(ps_ane_set0): power-controller@c000 { + compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc000 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = DIE_LABEL(ane_set0); + power-domains = <&DIE_NODE(ps_ane_sys_cpu)>; + }; + + DIE_NODE(ps_ane_base): power-controller@c008 { + compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc008 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = DIE_LABEL(ane_base); + power-domains = <&DIE_NODE(ps_ane_set0)>; + }; + + DIE_NODE(ps_ane_set1): power-controller@c010 { + compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc010 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = DIE_LABEL(ane_set1); + power-domains = <&DIE_NODE(ps_ane_base)>; + }; + + DIE_NODE(ps_ane_set2): power-controller@c018 { + compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc018 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = DIE_LABEL(ane_set2); + power-domains = <&DIE_NODE(ps_ane_base)>; + }; + + DIE_NODE(ps_ane_set3): power-controller@c020 { + compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc020 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = DIE_LABEL(ane_set3); + power-domains = <&DIE_NODE(ps_ane_base)>; + }; + + DIE_NODE(ps_ane_set4): power-controller@c028 { + compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc028 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = DIE_LABEL(ane_set4); + power-domains = <&DIE_NODE(ps_ane_base)>; + }; + + DIE_NODE(ps_ane_set5): power-controller@c030 { + compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc030 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = DIE_LABEL(ane_set5); + power-domains = <&DIE_NODE(ps_ane_base)>; + }; +#endif }; &DIE_NODE(pmgr_east) { From 534ae2229d938da4c63a96e701939dc87c5d826e Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:27:34 -0500 Subject: [PATCH 08/26] arm64: dts: apple: t602x: Add the die 0 ANE Describe the die 0 Neural Engine of the M2 Pro, Max and Ultra: the whole 32 MiB engine range at 0x284000000 plus the PMGR state words and the SET window, IRQ 884, three ANE DARTs, the eight existing ANE power states with ane_cpu as the reset, the ANE coprocessor mailbox at 0x285408000, and an IOVA-only reservation for the firmware entry alias (16 MiB at 0x10000000000 in the ANE DART domain). The shared die 0 file uses apple,t6021-ane. t6020.dtsi and t6022.dtsi change it to apple,t6020-ane and apple,t6022-ane, because ane_t6021 has per-SoC data, for example the SoC revision it gives the firmware. The Apple device tree gives the ANE one interrupt line, so the mailbox names only recv-not-empty, and apple-mailbox polls for TX space. ane_dart0 is in the always-on pmp domain, as in the tree that booted; ane_sys was never booted for this DART. The nodes are enabled. By default ane_t6021 runs the firmware from its own memory (fw_alias_reserved=0), so it needs no reserved-memory node from the bootloader, and it does not start the mailbox (hello_wait_ms=0). The memory-region is an IOVA reservation only. Tested with the out-of-tree build of the same driver code: a MacBook Pro 14" M2 Max (j414c) ran linux-asahi 7.1.13 with these node values from an overlay and the packaged m1n1 1.6.1, and its test programs gave bit-exact results. That tree had two differences: the mailbox also named a placeholder send-empty line (AIC 1833), which the stock apple-mailbox needs, and the nodes came from an overlay. Earlier runs on the same machine used a one-interrupt mailbox node with a poll-TX apple-mailbox. Not tested: this kernel tree was not booted, and no M2 Pro or M2 Ultra ran these nodes. Their values are from the macOS 13.5 device trees of those machines, which give the same die 0 ANE values as the M2 Max. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6020.dtsi | 4 ++ arch/arm64/boot/dts/apple/t6022.dtsi | 4 ++ arch/arm64/boot/dts/apple/t602x-common.dtsi | 5 ++ arch/arm64/boot/dts/apple/t602x-die0.dtsi | 59 +++++++++++++++++++++ 4 files changed, 72 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6020.dtsi b/arch/arm64/boot/dts/apple/t6020.dtsi index 500726e697a89..e9af24b25ab68 100644 --- a/arch/arm64/boot/dts/apple/t6020.dtsi +++ b/arch/arm64/boot/dts/apple/t6020.dtsi @@ -26,6 +26,10 @@ /delete-node/ &pmp_report_afnc4_ioa; /delete-node/ &pmp_report_afnc5_ioa; +&ane { + compatible = "apple,t6020-ane"; +}; + &gpu { compatible = "apple,agx-t6020", "apple,agx-g14x", "apple,agx-g14s"; diff --git a/arch/arm64/boot/dts/apple/t6022.dtsi b/arch/arm64/boot/dts/apple/t6022.dtsi index fe065d48726a3..875eb875e907c 100644 --- a/arch/arm64/boot/dts/apple/t6022.dtsi +++ b/arch/arm64/boot/dts/apple/t6022.dtsi @@ -328,6 +328,10 @@ #undef DIE #undef DIE_NO +&ane { + compatible = "apple,t6022-ane"; +}; + &aic { affinities { e-core-pmu-affinity { diff --git a/arch/arm64/boot/dts/apple/t602x-common.dtsi b/arch/arm64/boot/dts/apple/t602x-common.dtsi index c985e0e8d1c3f..295a46647de4b 100644 --- a/arch/arm64/boot/dts/apple/t602x-common.dtsi +++ b/arch/arm64/boot/dts/apple/t602x-common.dtsi @@ -627,5 +627,10 @@ uat_ttbs: uat-ttbs { reg = <0 0 0 0>; }; + + /* IOVA-only: the ANE firmware entry alias, 16 MiB at 0x10000000000 */ + ane_alias_iova: ane-alias-iova { + iommu-addresses = <&ane 0x100 0x0 0x0 0x1000000>; + }; }; }; diff --git a/arch/arm64/boot/dts/apple/t602x-die0.dtsi b/arch/arm64/boot/dts/apple/t602x-die0.dtsi index 852b33a88b813..a465b6f44fb2f 100644 --- a/arch/arm64/boot/dts/apple/t602x-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t602x-die0.dtsi @@ -6,6 +6,65 @@ * Copyright The Asahi Linux Contributors */ + ane_mbox: mailbox@285408000 { + compatible = "apple,t6021-ane-mailbox", "apple,asc-mailbox-v4"; + reg = <0x2 0x85408000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "recv-not-empty"; + #mbox-cells = <0>; + status = "okay"; + }; + + ane_dart0: iommu@285800000 { + compatible = "apple,t6020-dart", "apple,t8110-dart"; + reg = <0x2 0x85800000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_pmp>; + status = "okay"; + }; + + ane_dart1: iommu@285810000 { + compatible = "apple,t6020-dart", "apple,t8110-dart"; + reg = <0x2 0x85810000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_cpu>; + status = "okay"; + }; + + ane_dart2: iommu@285820000 { + compatible = "apple,t6020-dart", "apple,t8110-dart"; + reg = <0x2 0x85820000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_cpu>; + status = "okay"; + }; + + ane: ane@284000000 { + compatible = "apple,t6021-ane"; + reg = <0x2 0x84000000 0x0 0x2000000>, + <0x2 0x8e080000 0x0 0x4034>, + <0x2 0x8e08c000 0x0 0x4000>; + reg-names = "engine", "pmgr", "set"; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "ane"; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_sys_mpm>, <&ps_ane_td>, + <&ps_ane_base>, <&ps_ane_set1>, <&ps_ane_set2>, + <&ps_ane_set3>, <&ps_ane_set4>, <&ps_ane_cpu>; + resets = <&ps_ane_cpu>; + mboxes = <&ane_mbox>; + memory-region = <&ane_alias_iova>; + status = "okay"; + }; + nco: clock-controller@28e03c000 { compatible = "apple,t6020-nco", "apple,t8103-nco", "apple,nco"; reg = <0x2 0x8e03c000 0x0 0x14000>; From aa1255181fea403ff940544bf53d8a524dd7f2dd Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:28:59 -0500 Subject: [PATCH 09/26] arm64: dts: apple: t8112: Add the ANE, disabled Describe the M2 Neural Engine: the whole 32 MiB engine range at 0x26a000000 plus the PMGR window, the SET window and the two eFuse words that give the SoC revision to the firmware, IRQ 520, three ANE DARTs (IRQ 521, in ane_sys), the ANE coprocessor mailbox at 0x26b408000, and the seven ANE power states ane_sys_cpu, ane_td, ane_base and ane_set1..4 (0xc008..0xc038). ane_sys_cpu is a child of ane_sys, and each later state is a child of the one before. The values are those of the omarchy-ane T8112 overlay. Its sources are the /arm-io/ane and /arm-io/dart-ane nodes of the macOS 13.5 and 27.0 device trees, which are the same on j413, j415, j473 and j493, and the power-on order of the macOS 13.5 ANE kext. The mailbox sits at the same offset in the ANE block as on T6021 and names only recv-not-empty (the ANE interrupt); the overlay adds a placeholder send-empty line, which this tree does not need because apple-mailbox polls for TX. The mailbox, the DARTs and the ane node stay disabled: no T8112 has run the ane_t6021 driver or booted these nodes. The other ANE nodes in this series have the values of trees that ran the driver on an M1, an M1 Max or an M2 Max. A board or overlay that tests the driver enables the five nodes. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t8112-pmgr.dtsi | 63 +++++++++++++++++++++++ arch/arm64/boot/dts/apple/t8112.dtsi | 58 +++++++++++++++++++++ 2 files changed, 121 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi index 128a560dbac73..0e8df1cfa21f6 100644 --- a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi @@ -1132,6 +1132,69 @@ power-domains = <&ps_venc_pipe5>, <&ps_venc_pipe4>; }; + ps_ane_sys_cpu: power-controller@c008 { + compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc008 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_sys_cpu"; + power-domains = <&ps_ane_sys>; + }; + + ps_ane_td: power-controller@c010 { + compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc010 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_td"; + power-domains = <&ps_ane_sys_cpu>; + }; + + ps_ane_base: power-controller@c018 { + compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc018 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_base"; + power-domains = <&ps_ane_td>; + }; + + ps_ane_set1: power-controller@c020 { + compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc020 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set1"; + power-domains = <&ps_ane_base>; + }; + + ps_ane_set2: power-controller@c028 { + compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc028 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set2"; + power-domains = <&ps_ane_set1>; + }; + + ps_ane_set3: power-controller@c030 { + compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc030 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set3"; + power-domains = <&ps_ane_set2>; + }; + + ps_ane_set4: power-controller@c038 { + compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; + reg = <0xc038 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_set4"; + power-domains = <&ps_ane_set3>; + }; + ps_disp0_cpu0: power-controller@10000 { compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; reg = <0x10000 4>; diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index 76a9fa23709d0..5f3db6baa77c5 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -1707,6 +1707,64 @@ power-domains = <&ps_avd_sys>; }; + ane_mbox: mailbox@26b408000 { + compatible = "apple,t8112-ane-mailbox", "apple,asc-mailbox-v4"; + reg = <0x2 0x6b408000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "recv-not-empty"; + #mbox-cells = <0>; + status = "disabled"; + }; + + ane_dart0: iommu@26b800000 { + compatible = "apple,t8112-dart", "apple,t8110-dart"; + reg = <0x2 0x6b800000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys>; + status = "disabled"; + }; + + ane_dart1: iommu@26b810000 { + compatible = "apple,t8112-dart", "apple,t8110-dart"; + reg = <0x2 0x6b810000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys>; + status = "disabled"; + }; + + ane_dart2: iommu@26b820000 { + compatible = "apple,t8112-dart", "apple,t8110-dart"; + reg = <0x2 0x6b820000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_ane_sys>; + status = "disabled"; + }; + + ane: ane@26a000000 { + compatible = "apple,t8112-ane"; + reg = <0x2 0x6a000000 0x0 0x2000000>, + <0x2 0x3b700000 0x0 0x18000>, + <0x2 0x3b724000 0x0 0x4000>, + <0x2 0x3d2c8060 0x0 0x8>; + reg-names = "engine", "pmgr", "set", "fuse"; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-names = "ane"; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_sys_cpu>, <&ps_ane_td>, + <&ps_ane_base>, <&ps_ane_set1>, <&ps_ane_set2>, + <&ps_ane_set3>, <&ps_ane_set4>; + mboxes = <&ane_mbox>; + status = "disabled"; + }; + dispext0_dart: iommu@271304000 { compatible = "apple,t8112-dart", "apple,t8110-dart"; reg = <0x2 0x71304000 0x0 0x4000>; From b74fa4deaae4a6cd09fc62d304d1aad541c6e095 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:23:13 -0500 Subject: [PATCH 10/26] accel/ane: Bind only the M1 family in the ane module The ane module matched apple,t6020-ane and apple,t6021-ane, but it refused to bind both: T6020 had no proven SET-block base, and T6021 bound only with the allow_unqualified module parameter. The M2 family does not use the host-driven task manager of this module. Its coprocessor runs the ANE firmware, and the ane_t6021 module drives it for T6020, T6021, T6022 and T8112. The two entries made udev load both modules for every T602x ANE node, and the ane probe, when it ran first, failed with -ENODEV and logged an error. Remove the two entries and their SoC descriptors. Every remaining SoC has proven constants, so also remove the qualification tiers and the allow_unqualified parameter, and get the descriptor with of_device_get_match_data(). Each compatible of the apple,ane binding, and each ANE node in the apple device trees, now matches exactly one of the two match tables. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_drv.c | 94 +++++-------------------------------- 1 file changed, 11 insertions(+), 83 deletions(-) diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index db03774c9e25a..5b269b0f8729f 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -880,54 +880,33 @@ static int ane_attach_genpd(struct ane_device *ane) } /* - * Per-SoC support descriptor, one per Linux `compatible`. + * Per-SoC descriptor, one per Linux `compatible`. * * Everything the probe needs except the SET block is derived from the * device tree by design: DART topology from "iommus", power wiring from - * "power-domains", the engine window from "reg", the IRQ by name. Board - * facts belong in the overlay, not in compiled constants. The SET block - * is the one exception: the live overlays carry no range for it, so it - * is compiled in per SoC — and only from a source that has proven the + * "power-domains", the engine window from "reg", the IRQ by name. The SET + * block is the one exception: the device tree carries no range for it, so + * it is compiled in per SoC, and only from a source that has proven the * address on hardware (m1n1 proxyclient ANE.ps_map, then a bound device). * A guessed SET base is not a bug but a brick: direct writes to the * block external-abort the SoC (T6001 named by netconsole 2026-09-16, - * PS_SET0 down at 0x28e08c000; T8103 same mechanism at 0x23b70c000), - * which is why a SoC without proven constants must refuse to bind - * instead of carrying a guess. - * - * Qualification tiers: - * ANE_QUALIFIED — execution proven on this silicon; binds normally. - * ANE_RECOGNIZED — constants present, never run on hardware; binds - * only with ane.allow_unqualified=1, loudly. - * ANE_UNSUPPORTED — no proven constants; refuses and names the data - * needed to advance the port. + * PS_SET0 down at 0x28e08c000; T8103 same mechanism at 0x23b70c000). + * The M2 family (T602x, T8112) runs the ANE firmware and binds to + * ane_t6021 instead. */ -enum ane_qual { - ANE_QUALIFIED, - ANE_RECOGNIZED, - ANE_UNSUPPORTED, -}; - struct ane_soc { phys_addr_t ps_base; - enum ane_qual qual; /* True when the tm/tq register file survives a genpd cycle in * retention and recovery must drain it (see ane_tm_drain_retained). */ bool tm_retention; }; -static bool allow_unqualified; -module_param(allow_unqualified, bool, 0444); -MODULE_PARM_DESC(allow_unqualified, - "Bind recognized-but-unproven ANE SoCs (unverified SET base: external-abort risk)"); - static const struct ane_soc ane_soc_t8103 = { /* M1 (m1-test-host). SET block mapped read-only for the recovery ACTUAL * log and the powered-on guard. Execution proven in the fleet. */ .ps_base = 0x23b70c000ULL, - .qual = ANE_QUALIFIED, }; static const struct ane_soc ane_soc_t6000 = { @@ -935,42 +914,12 @@ static const struct ane_soc ane_soc_t6000 = { * (proven on T6001/t6001-test-host); M1 Pro and M1 Ultra are untested. */ .ps_base = 0x28e08c000ULL, - .qual = ANE_QUALIFIED, .tm_retention = true, }; -static const struct ane_soc ane_soc_t6020 = { - /* M2 Pro (t6020). Community device-tree captures exist, but the - * SET base is unproven and the H14 compiler backend is unqualified: - * no constants may enter here yet. - */ - .ps_base = 0, - .qual = ANE_UNSUPPORTED, -}; - -static const struct ane_soc ane_soc_t6021 = { - /* M2 Max (T6021, t6021-test-host). SET window 0x8e08c000 = pmgr base - * 0x8e080000 + 0xc000, present in ane0's own reg on macOS captures - * of both 26.6.2 and 27.0 (2026-09-18, 11/11 derivation-input - * checks each, zero delta); the Linux translation reuses the pmgr - * high bits proven on T6000/T6020 rows (low-32 match) -> - * 0x28e08c000. Recognized, not qualified: constants complete, but - * no Linux execution yet, and the t6021 pwrstate word layout - * (which of set0/base/set1..4 sits at which offset — macOS-side - * capture cannot see it) is unverified; the first probe resume - * logs the ACTUAL nibbles through this window as the Linux-side - * probe (receipt 2026-09-18-t6021-driver-entry-prepared.md). - * Promotion to ANE_QUALIFIED needs an exact run on this silicon. - */ - .ps_base = 0x28e08c000ULL, - .qual = ANE_RECOGNIZED, -}; - static const struct of_device_id ane_of_match[] = { { .compatible = "apple,t8103-ane", .data = &ane_soc_t8103 }, { .compatible = "apple,t6000-ane", .data = &ane_soc_t6000 }, - { .compatible = "apple,t6020-ane", .data = &ane_soc_t6020 }, - { .compatible = "apple,t6021-ane", .data = &ane_soc_t6021 }, {} }; @@ -979,32 +928,11 @@ MODULE_DEVICE_TABLE(of, ane_of_match); static int ane_platform_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; - const struct of_device_id *id = of_match_device(ane_of_match, dev); - const struct ane_soc *soc = id->data; + const struct ane_soc *soc = of_device_get_match_data(dev); struct ane_device *ane; struct drm_device *drm; int err; - /* Tier gate before any power-domain, MMIO or IRQ interaction: an - * unqualified SoC must fail cleanly, never half-probe. - */ - if (soc->qual == ANE_UNSUPPORTED) { - dev_err(dev, - "%s: unsupported ANE: no proven SET-block base (a guessed base external-aborts the SoC); not binding. To advance this port, run the mlx-omarchy quick collector (scripts/collect_quick.py: captures ANE/DART/PMGR/AIC device-tree data, no driver needed) and submit the capture\n", - id->compatible); - return -ENODEV; - } - if (soc->qual == ANE_RECOGNIZED && !allow_unqualified) { - dev_err(dev, - "%s: recognized but unqualified: constants present, execution never proven on this silicon; not binding. Override with ane.allow_unqualified=1, or prove a run and report it\n", - id->compatible); - return -ENODEV; - } - if (soc->qual == ANE_RECOGNIZED) - dev_warn(dev, - "%s: UNQUALIFIED bind forced by allow_unqualified: no execution proven on this silicon — SET-block base and board topology unverified\n", - id->compatible); - ane = devm_drm_dev_alloc(dev, &ane_drm_driver, struct ane_device, drm); if (IS_ERR(ane)) return PTR_ERR(ane); @@ -1172,7 +1100,7 @@ static int __maybe_unused ane_runtime_resume(struct device *dev) * SET window reads come first (pmgr class, always safe * per T6001/T8103 bisect evidence), then the engine. A * hard reset after the last off-box line names the - * killing access exactly (T6021 console bring-up). + * killing access exactly. */ struct resource *eng = platform_get_resource_byname( to_platform_device(dev), IORESOURCE_MEM, "engine"); @@ -1198,8 +1126,8 @@ static int __maybe_unused ane_runtime_resume(struct device *dev) /* Linux-side pwrstate probe: ACTUAL nibbles read through * the SoC descriptor's SET window while the partition is * raised. 0xffffff means the mapped window is the live - * pmgr SET block with every word on; anything else names - * the t6021 word layout to fix before promotion. + * pmgr SET block with every word on; anything else means + * the window does not match the expected word layout. */ dev_info(dev, "ANERD ps probe act=%#x\n", ane_ps_act(ane)); } From cfb77b6fc67fe44f2ed7a0c88605f3140128870e Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:29:44 -0500 Subject: [PATCH 11/26] accel/ane: Clean up the UAPI and add DRM_IOCTL_ANE_GET_CAPS Prepare include/uapi/drm/ane_accel.h for a stable in-tree ABI. Prefix every macro of the header with DRM_ANE_, as other DRM UAPI headers do: ANE_TILE_COUNT, ANE_FIFO_NID and ANE_CMD_GRAN become DRM_ANE_TILE_COUNT, DRM_ANE_FIFO_NID and DRM_ANE_CMD_GRAN, ANE_ABI_MAJOR and ANE_ABI_M2_MAJOR become DRM_ANE_ABI_V1 and DRM_ANE_ABI_V2, and ANE_M2_MAX_BINDS becomes DRM_ANE_MAX_BINDS. ANE_M2_MAX_SECTIONS was 16, but the driver accepts at most 9 sections (ids 1 to 9). It becomes DRM_ANE_MAX_SECTIONS with the value 9, and a BUILD_BUG_ON() keeps it equal to the firmware LOAD record count. Add DRM_IOCTL_ANE_GET_CAPS (number 0x00, free until now) to both drivers. It reports the ABI version, the chip family (H13 or H14), and the size of each array entry that PROG_LOAD and EXEC read through a user pointer. Its flags field has no defined flag and must be zero. Its size field gives the number of bytes that the driver filled in, so the structure can grow at its end. Reject a nonzero pad or reserved field with -EINVAL in every ioctl: BO_INIT and BO_FREE on ABI version 2 (ABI version 1 already did), the pad of PROG_LOAD, of each generic bind and of EXEC, and the flags and reserved fields of each EXEC buffer. The field drm_ane_exec_io.dma was already reserved: the driver gives the firmware the address of bo_handle. Rename it to reserved. Add kernel-doc for every structure. Keep one header with an explicit ABI version, not one header per ABI. The two drivers share the DRM driver name, the accel node, the BO_INIT/BO_FREE structures and the ioctl number space. One header per ABI would either duplicate the shared structures under two names or need a third header for them, and it would let the two headers give one ioctl number to two structures. Userspace already supports both ABI versions from one binary and selects by the version major. The version is explicit: DRM_IOCTL_VERSION major and drm_ane_get_caps.abi_version both report DRM_ANE_ABI_V1 or DRM_ANE_ABI_V2, an ioctl number is never reused, and a driver rejects the ioctls of the other version. The ioctl numbers and the layout of every existing structure do not change: an aarch64 offsetof()/sizeof() check of the old and new header gives identical values for all existing structures, fields and ioctl command values. Userspace that left a pad field of BO_FREE or of a generic bind uninitialised can now get -EINVAL on ABI version 2. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane.h | 2 +- drivers/accel/ane/ane_drv.c | 37 +++- drivers/accel/ane/ane_t6021_rtclient_main.c | 48 ++++- drivers/accel/ane/ane_tm.c | 3 +- include/uapi/drm/ane_accel.h | 207 ++++++++++++++++---- 5 files changed, 238 insertions(+), 59 deletions(-) diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index 10fee2864728c..c644ec45e67d4 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -115,7 +115,7 @@ struct ane_request { u32 td_size; u32 td_count; u32 btsp_iova; - u32 bar[ANE_TILE_COUNT]; + u32 bar[DRM_ANE_TILE_COUNT]; }; /* diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 5b269b0f8729f..8b38416c20b36 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -352,6 +352,22 @@ static const struct drm_gem_object_funcs ane_gem_object_funcs = { .vm_ops = &drm_gem_ane_vm_ops, }; +static int ane_get_caps(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct drm_ane_get_caps *args = data; + + if (args->flags || args->pad) + return -EINVAL; + + *args = (struct drm_ane_get_caps) { + .size = sizeof(*args), + .abi_version = DRM_ANE_ABI_V1, + .chip_family = DRM_ANE_CHIP_H13, + }; + return 0; +} + static int ane_bo_init(struct drm_device *drm, void *data, struct drm_file *file) { @@ -460,7 +476,7 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) { struct ane_device *ane = drm->dev_private; struct drm_ane_submit *args = data; - struct drm_gem_object *gem[ANE_TILE_COUNT] = { 0 }; + struct drm_gem_object *gem[DRM_ANE_TILE_COUNT] = { 0 }; struct drm_gem_object *btsp = NULL; struct ane_bo *bo; struct ane_request req; @@ -483,11 +499,11 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) } req.qid = 4; - req.nid = ANE_FIFO_NID; + req.nid = DRM_ANE_FIFO_NID; req.td_size = args->td_size; req.td_count = args->td_count; - for (int bdx = 0; bdx < ANE_TILE_COUNT; bdx++) { + for (int bdx = 0; bdx < DRM_ANE_TILE_COUNT; bdx++) { if (!args->handles[bdx]) continue; bo = bo_lookup(file, args->handles[bdx]); @@ -510,8 +526,8 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) * access. Since this isn't page aligned, we represent the two as one * buffer and calculate the delimiter (where the weights would start). */ - req.bar[KRN_BUF_BDX] = - req.bar[CMD_BUF_BDX] + round_up(args->tsk_size, ANE_CMD_GRAN); + req.bar[KRN_BUF_BDX] = req.bar[CMD_BUF_BDX] + + round_up(args->tsk_size, DRM_ANE_CMD_GRAN); bo = bo_lookup(file, args->btsp_handle); if (!bo) { @@ -553,7 +569,7 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) mutex_unlock(&ane->engine_lock); put: drm_gem_object_put(btsp); - for (int bdx = 0; bdx < ANE_TILE_COUNT; bdx++) { + for (int bdx = 0; bdx < DRM_ANE_TILE_COUNT; bdx++) { if (gem[bdx]) drm_gem_object_put(gem[bdx]); } @@ -561,6 +577,7 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) } static const struct drm_ioctl_desc ane_drm_ioctls[] = { + DRM_IOCTL_DEF_DRV(ANE_GET_CAPS, ane_get_caps, 0), DRM_IOCTL_DEF_DRV(ANE_BO_INIT, ane_bo_init, 0), DRM_IOCTL_DEF_DRV(ANE_BO_FREE, ane_bo_free, 0), DRM_IOCTL_DEF_DRV(ANE_SUBMIT, ane_submit, 0), @@ -656,9 +673,9 @@ static void ane_drm_postclose(struct drm_device *drm, struct drm_file *file) } /* - * The driver only owns three ioctls (ANE_BO_INIT, ANE_BO_FREE, - * ANE_SUBMIT). Anything outside that table would otherwise fall through - * the standard drm_ioctl path to legacy primary-node handlers that + * The driver only owns four ioctls (ANE_GET_CAPS, ANE_BO_INIT, + * ANE_BO_FREE, ANE_SUBMIT). The standard drm_ioctl path would otherwise + * pass anything outside that table to legacy primary-node handlers that * dereference drm_device.unique, which an accel node never sets. Reject * such callers explicitly so they fail with -ENOTTY instead of oopsing. * @@ -764,7 +781,7 @@ static const struct drm_driver ane_drm_driver = { .ioctls = ane_drm_ioctls, .num_ioctls = ARRAY_SIZE(ane_drm_ioctls), .fops = &ane_drm_fops, - .major = ANE_ABI_MAJOR, + .major = DRM_ANE_ABI_V1, .name = "ane", .desc = "Apple Neural Engine driver", }; diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index 9d1e43ecc508b..e5cda3d046ed6 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -990,9 +990,10 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, size_t binds_size; int ret, i, j; - if (user->section_count < 1 || + BUILD_BUG_ON(DRM_ANE_MAX_SECTIONS != ANE_T6021_LOAD_SEC_COUNT); + if (user->pad || user->section_count < 1 || user->section_count > ANE_T6021_LOAD_SEC_COUNT || - user->generic_count > ANE_M2_MAX_BINDS || !fd) + user->generic_count > DRM_ANE_MAX_BINDS || !fd) return -EINVAL; sections = kmalloc_array(user->section_count, sizeof(*sections), @@ -1016,6 +1017,12 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, ret = -EFAULT; goto out; } + for (i = 0; i < user->generic_count; i++) { + if (binds[i].pad) { + ret = -EINVAL; + goto out; + } + } /* Lab contract: the record slot IS the section identity (slot = * id - 1; tdprop id 7 lands at slot 6 and slot 5 stays empty, @@ -1248,7 +1255,7 @@ static int ane_rtclient_procedure_call(struct ane_rtclient *ane, size_t cmd_size; int ret, i; - if (user->count < 1 || user->count > ANE_M2_MAX_BINDS || + if (user->pad || user->count < 1 || user->count > DRM_ANE_MAX_BINDS || user->priority < 2 || user->priority > 7 || !fd) return -EINVAL; @@ -1260,6 +1267,12 @@ static int ane_rtclient_procedure_call(struct ane_rtclient *ane, kfree(ios); return -EFAULT; } + for (i = 0; i < user->count; i++) { + if (ios[i].flags || ios[i].reserved) { + kfree(ios); + return -EINVAL; + } + } cmd_size = sizeof(struct ane_csne_cmd_procedure_call) + (size_t)user->count * sizeof(struct ane_csne_io_elem); @@ -1364,7 +1377,8 @@ static int ane_t6021_bo_init_ioctl(struct drm_device *drm, void *data, struct ane_t6021_bo *bo; struct ane_rtclient *ane; - if (args->size == 0 || args->size > ANE_T6021_BO_MAX || !fd) + if (args->pad || args->size == 0 || args->size > ANE_T6021_BO_MAX || + !fd) return -EINVAL; /* A parked io BO is already mapped and counted; its old contents * belong to another process, so it is zeroed like a new one. @@ -1447,6 +1461,8 @@ static int ane_t6021_bo_free_ioctl(struct drm_device *drm, void *data, if (!fd) return -ENODEV; + if (args->pad) + return -EINVAL; mutex_lock(&ane_t6021_bo_lock); list_for_each_entry(b, &fd->bos, node) { if (b->handle == args->handle) { @@ -1540,6 +1556,25 @@ static void ane_t6021_postclose(struct drm_device *drm, struct drm_file *file) file->driver_priv = NULL; } +static int ane_t6021_get_caps_ioctl(struct drm_device *drm, void *data, + struct drm_file *file) +{ + struct drm_ane_get_caps *args = data; + + if (args->flags || args->pad) + return -EINVAL; + + *args = (struct drm_ane_get_caps) { + .size = sizeof(*args), + .abi_version = DRM_ANE_ABI_V2, + .chip_family = DRM_ANE_CHIP_H14, + .section_size = sizeof(struct drm_ane_section), + .bind_size = sizeof(struct drm_ane_generic_bind), + .exec_io_size = sizeof(struct drm_ane_exec_io), + }; + return 0; +} + static int ane_t6021_submit_ioctl(struct drm_device *drm, void *data, struct drm_file *file) { @@ -1650,6 +1685,7 @@ static int ane_t6021_exec_ioctl(struct drm_device *drm, void *data, } static const struct drm_ioctl_desc ane_t6021_ioctls[] = { + DRM_IOCTL_DEF_DRV(ANE_GET_CAPS, ane_t6021_get_caps_ioctl, 0), DRM_IOCTL_DEF_DRV(ANE_BO_INIT, ane_t6021_bo_init_ioctl, 0), DRM_IOCTL_DEF_DRV(ANE_BO_FREE, ane_t6021_bo_free_ioctl, 0), DRM_IOCTL_DEF_DRV(ANE_SUBMIT, ane_t6021_submit_ioctl, 0), @@ -1685,7 +1721,7 @@ static const struct drm_driver ane_t6021_drm_driver = { .ioctls = ane_t6021_ioctls, .num_ioctls = ARRAY_SIZE(ane_t6021_ioctls), .fops = &ane_t6021_fops, - .major = ANE_ABI_M2_MAJOR, + .major = DRM_ANE_ABI_V2, .minor = 0, .name = "ane", .desc = "Apple Neural Engine (T6021/M2)", @@ -2289,7 +2325,7 @@ static int ane_rtclient_probe(struct platform_device *pdev) } dev_info(dev, "loaded ane_t6021 (DRM major %d minor %d; ABI 2; legacy_only=%u chman_ok=%u booted=%u; state %s; BO cap %u MiB)\n", - ANE_ABI_M2_MAJOR, 0, + DRM_ANE_ABI_V2, 0, legacy_only, ane->chman_ok, ane->fw ? ane->fw->booted : 0, ane->held ? "HELD" : "ready", bo_total_max_mb); diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index 0e98c48d2aff1..e81af0a7b96db 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -195,9 +195,8 @@ int ane_tm_enqueue(struct ane_device *ane, struct ane_request *req) tq_write32(ane, TQ_STATUS(qid), 0x1); - for (int bdx = 0; bdx < ANE_TILE_COUNT; bdx++) { + for (int bdx = 0; bdx < DRM_ANE_TILE_COUNT; bdx++) tq_write32(ane, TQ_BAR1(qid, bdx), req->bar[bdx]); - } tq_write32(ane, TQ_SIZE1(qid), ((req->td_size >> 2) - 1) << 0x10); tq_write32(ane, TQ_ADDR1(qid), req->btsp_iova); diff --git a/include/uapi/drm/ane_accel.h b/include/uapi/drm/ane_accel.h index e5fd9d12d1d63..76577277b70eb 100644 --- a/include/uapi/drm/ane_accel.h +++ b/include/uapi/drm/ane_accel.h @@ -1,8 +1,8 @@ /* SPDX-License-Identifier: (GPL-2.0-only WITH Linux-syscall-note) OR MIT */ /* Copyright 2022 Eileen Yoon */ -#ifndef __ANE_ACCEL_H__ -#define __ANE_ACCEL_H__ +#ifndef __DRM_UAPI_ANE_ACCEL_H__ +#define __DRM_UAPI_ANE_ACCEL_H__ #include "drm.h" @@ -10,31 +10,85 @@ extern "C" { #endif -#define ANE_TILE_COUNT 0x20 -#define ANE_FIFO_NID 0x40 -#define ANE_CMD_GRAN 0x10 +/** + * DOC: ABI versions + * + * Two drivers implement this interface on an accel node, both with the DRM + * driver name "ane": + * + * - ane (H13 family: T8103, T6000, T6001, T6002) implements ABI version + * %DRM_ANE_ABI_V1: GET_CAPS, BO_INIT, BO_FREE and SUBMIT. + * - ane_t6021 (H14 family: T6020, T6021, T6022, T8112) implements ABI + * version %DRM_ANE_ABI_V2: GET_CAPS, BO_INIT, BO_FREE, PROG_LOAD, + * PROC_CREATE and EXEC. + * + * The DRM_IOCTL_VERSION major and &drm_ane_get_caps.abi_version both give + * the ABI version. The two versions share the ioctl numbers and the + * structures, and a number is never given to a second ioctl. A driver + * rejects the ioctls of the other version. A structure grows only at its + * end; &drm_ane_get_caps.size tells which fields the driver filled in. + * + * Every pad and reserved field, and every flags field with no flags + * defined, must be zero. The drivers reject a nonzero value with -EINVAL. + */ +#define DRM_ANE_ABI_V1 1 +#define DRM_ANE_ABI_V2 2 -/* ABI 1: successful SUBMIT guarantees terminal completion and CPU visibility. */ -#define ANE_ABI_MAJOR 1 +#define DRM_ANE_CHIP_H13 13 +#define DRM_ANE_CHIP_H14 14 -/* - * ABI 2 (T6021 / M2, H14 firmware programs): the driver reports - * DRM_IOCTL_VERSION major 2 and rejects DRM_ANE_SUBMIT. The M1 libane - * requires major 1, so it cannot submit M1 frames to an M2 device. - * A successful DRM_ANE_EXEC guarantees terminal completion (firmware ack - * and task-queue idle) and CPU visibility of the output buffers. - */ -#define ANE_ABI_M2_MAJOR 2 -#define ANE_M2_MAX_SECTIONS 16 -#define ANE_M2_MAX_BINDS 64 +/* ABI version 1: entries of &drm_ane_submit.handles */ +#define DRM_ANE_TILE_COUNT 0x20 +/* ABI version 1: network id of the queue that SUBMIT uses */ +#define DRM_ANE_FIFO_NID 0x40 +/* ABI version 1: the weights start at round_up(tsk_size, DRM_ANE_CMD_GRAN) */ +#define DRM_ANE_CMD_GRAN 0x10 + +/* ABI version 2: highest section id, and most sections per PROG_LOAD */ +#define DRM_ANE_MAX_SECTIONS 9 +/* ABI version 2: most generic binds per PROG_LOAD and buffers per EXEC */ +#define DRM_ANE_MAX_BINDS 64 -#define DRM_ANE_BO_INIT 0x1 -#define DRM_ANE_BO_FREE 0x2 -#define DRM_ANE_SUBMIT 0x3 -#define DRM_ANE_PROG_LOAD 0x4 -#define DRM_ANE_PROC_CREATE 0x5 -#define DRM_ANE_EXEC 0x6 +#define DRM_ANE_GET_CAPS 0x00 +#define DRM_ANE_BO_INIT 0x01 +#define DRM_ANE_BO_FREE 0x02 +#define DRM_ANE_SUBMIT 0x03 +#define DRM_ANE_PROG_LOAD 0x04 +#define DRM_ANE_PROC_CREATE 0x05 +#define DRM_ANE_EXEC 0x06 + +/** + * struct drm_ane_get_caps - DRM_IOCTL_ANE_GET_CAPS argument + * @flags: In. No flags are defined: must be zero. + * @size: Out. Bytes of this structure that the driver filled in. + * @abi_version: Out. %DRM_ANE_ABI_V1 or %DRM_ANE_ABI_V2. + * @chip_family: Out. %DRM_ANE_CHIP_H13 or %DRM_ANE_CHIP_H14. + * @section_size: Out. Size of the &drm_ane_section entries that PROG_LOAD + * reads, or 0 if the driver has no PROG_LOAD. + * @bind_size: Out. Size of the &drm_ane_generic_bind entries that PROG_LOAD + * reads, or 0 if the driver has no PROG_LOAD. + * @exec_io_size: Out. Size of the &drm_ane_exec_io entries that EXEC reads, + * or 0 if the driver has no EXEC. + * @pad: Must be zero. + */ +struct drm_ane_get_caps { + __u32 flags; + __u32 size; + __u32 abi_version; + __u32 chip_family; + __u32 section_size; + __u32 bind_size; + __u32 exec_io_size; + __u32 pad; +}; +/** + * struct drm_ane_bo_init - DRM_IOCTL_ANE_BO_INIT argument + * @handle: Out. Handle of the new buffer. + * @pad: Must be zero. + * @size: In. Size of the buffer in bytes, not zero. + * @offset: Out. Offset to give to mmap() on the accel node. + */ struct drm_ane_bo_init { __u32 handle; __u32 pad; @@ -42,29 +96,65 @@ struct drm_ane_bo_init { __u64 offset; }; +/** + * struct drm_ane_bo_free - DRM_IOCTL_ANE_BO_FREE argument + * @handle: In. Handle from BO_INIT. + * @pad: Must be zero. + */ struct drm_ane_bo_free { __u32 handle; __u32 pad; }; +/** + * struct drm_ane_submit - DRM_IOCTL_ANE_SUBMIT argument (ABI version 1) + * @tsk_size: In. Size of the task microcode at the start of handles[0], not + * zero. + * @td_count: In. Number of task descriptors, 1 to 0xffff. + * @td_size: In. Size of a task descriptor: a multiple of 4, 4 to 0x40000. + * @handles: In. Buffer per tile: handles[0] holds the microcode and the + * weights, handles[1] must be 0 (the driver sets it from handles[0]), + * and 0 marks an unused tile. + * @btsp_handle: In. Buffer with the bootstrap task descriptor. + * @pad: Must be zero. + * + * A successful SUBMIT returns after the engine completed the work, with the + * output buffers visible to the CPU. + */ struct drm_ane_submit { __u64 tsk_size; __u32 td_count; __u32 td_size; - __u32 handles[ANE_TILE_COUNT]; + __u32 handles[DRM_ANE_TILE_COUNT]; __u32 btsp_handle; __u32 pad; }; -/* One firmware program section, already built by userspace, held in a BO. */ +/** + * struct drm_ane_section - one firmware program section (ABI version 2) + * @id: Section id, 1 to %DRM_ANE_MAX_SECTIONS, unique in one PROG_LOAD. + * @bo_handle: Buffer that holds the section bytes. + * @size: Size of the section in bytes. + * @offset: Offset of the section in the buffer. + */ struct drm_ane_section { - __u32 id; /* firmware section id */ - __u32 bo_handle; /* BO holding the bytes */ + __u32 id; + __u32 bo_handle; __u64 size; - __u64 offset; /* byte offset inside the BO */ + __u64 offset; }; -/* A buffer whose IOVA and size the driver patches into a generic entry. */ +/** + * struct drm_ane_generic_bind - buffer of a program (ABI version 2) + * @buffer_id: Firmware buffer id. + * @bo_handle: Buffer handle. + * @type: Buffer type. + * @pad: Must be zero. + * @size: Size of the buffer in bytes. + * + * The driver checks @pad and ignores the other fields: the sections that + * userspace builds already hold this information. + */ struct drm_ane_generic_bind { __u32 buffer_id; __u32 bo_handle; @@ -73,49 +163,86 @@ struct drm_ane_generic_bind { __u64 size; }; +/** + * struct drm_ane_prog_load - DRM_IOCTL_ANE_PROG_LOAD argument (ABI version 2) + * @sections_ptr: In. Pointer to struct drm_ane_section[@section_count]. + * @generic_ptr: In. Pointer to struct drm_ane_generic_bind[@generic_count]. + * @section_count: In. 1 to %DRM_ANE_MAX_SECTIONS. + * @generic_count: In. 0 to %DRM_ANE_MAX_BINDS. + * @prog_id_out: Out. Firmware program id. Identical sections give the same + * program id. + * @pad: Must be zero. + */ struct drm_ane_prog_load { - __u64 sections_ptr; /* struct drm_ane_section[section_count] */ - __u64 generic_ptr; /* struct drm_ane_generic_bind[generic_count] */ + __u64 sections_ptr; + __u64 generic_ptr; __u32 section_count; __u32 generic_count; __u32 prog_id_out; __u32 pad; }; +/** + * struct drm_ane_proc_create - DRM_IOCTL_ANE_PROC_CREATE argument + * (ABI version 2) + * @prog_id: In. Program id from PROG_LOAD. + * @proc_id_out: Out. Firmware process id. + */ struct drm_ane_proc_create { __u32 prog_id; __u32 proc_id_out; }; -/* Per-call buffer binding: an input or output for one procedure call. */ +/** + * struct drm_ane_exec_io - input or output buffer of one EXEC + * (ABI version 2) + * @buffer_id: Firmware buffer id. + * @bo_handle: Buffer handle. The driver gives its address to the firmware. + * @type: Buffer type. + * @flags: No flags are defined: must be zero. + * @reserved: Must be zero. + * @size: Size of the buffer in bytes. + */ struct drm_ane_exec_io { __u32 buffer_id; __u32 bo_handle; __u32 type; __u32 flags; - __u64 dma; /* in only, reserved: the driver binds the - * IOVA from bo_handle - */ + __u64 reserved; __u64 size; }; +/** + * struct drm_ane_exec - DRM_IOCTL_ANE_EXEC argument (ABI version 2) + * @prog_id: In. Program id from PROG_LOAD. + * @proc_id: In. Process id from PROC_CREATE. + * @priority: In. 2 to 7. + * @timeout_ms: In. Firmware completion timeout, 0 for 5000 ms. + * @count: In. 1 to %DRM_ANE_MAX_BINDS. + * @pad: Must be zero. + * @io_ptr: In. Pointer to struct drm_ane_exec_io[@count]. + * + * A successful EXEC returns after the firmware acknowledged completion and + * the task queue is idle, with the output buffers visible to the CPU. + */ struct drm_ane_exec { __u32 prog_id; __u32 proc_id; - __u32 priority; /* 2..7 */ + __u32 priority; __u32 timeout_ms; - __u32 count; /* 1..ANE_M2_MAX_BINDS */ + __u32 count; __u32 pad; - __u64 io_ptr; /* struct drm_ane_exec_io[count] */ + __u64 io_ptr; }; +#define DRM_IOCTL_ANE_GET_CAPS \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_GET_CAPS, struct drm_ane_get_caps) #define DRM_IOCTL_ANE_BO_INIT \ DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_BO_INIT, struct drm_ane_bo_init) #define DRM_IOCTL_ANE_BO_FREE \ DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_BO_FREE, struct drm_ane_bo_free) #define DRM_IOCTL_ANE_SUBMIT \ DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_SUBMIT, struct drm_ane_submit) - #define DRM_IOCTL_ANE_PROG_LOAD \ DRM_IOWR(DRM_COMMAND_BASE + DRM_ANE_PROG_LOAD, struct drm_ane_prog_load) #define DRM_IOCTL_ANE_PROC_CREATE \ @@ -127,4 +254,4 @@ struct drm_ane_exec { } #endif -#endif /* __ANE_ACCEL_H__ */ +#endif /* __DRM_UAPI_ANE_ACCEL_H__ */ From 332e297b0e93060421891e8992c1aa4bc8ec260e Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:34:03 -0500 Subject: [PATCH 12/26] accel/ane: Parenthesize the register macro arguments checkpatch --strict reports 27 MACRO_ARG_PRECEDENCE checks for the task manager and task queue register macros. Put each macro argument in parentheses. No functional change: all callers pass simple expressions, and the non-debug sections of all seven objects are byte-identical before and after this change (arm64, gcc 12.2.0). Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_tm.c | 44 ++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index e81af0a7b96db..7898c1dd93aaa 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -19,11 +19,11 @@ static const int TQ_PRTY_TABLE[ANE_TQ_COUNT] = { 0x1, 0x2, 0x3, 0x4, #define TM_PUSH 0x8 #define TM_TQ_EN 0xc -#define TM_IRQ_EVTC(line) (0x14 + (line * 0x14)) -#define TM_IRQ_INFO(line) (0x18 + (line * 0x14)) -#define TM_IRQ_UNK1(line) (0x1c + (line * 0x14)) -#define TM_IRQ_TMST(line) (0x20 + (line * 0x14)) -#define TM_IRQ_UNK2(line) (0x24 + (line * 0x14)) +#define TM_IRQ_EVTC(line) (0x14 + ((line) * 0x14)) +#define TM_IRQ_INFO(line) (0x18 + ((line) * 0x14)) +#define TM_IRQ_UNK1(line) (0x1c + ((line) * 0x14)) +#define TM_IRQ_TMST(line) (0x20 + ((line) * 0x14)) +#define TM_IRQ_UNK2(line) (0x24 + ((line) * 0x14)) #define TM_COMMITTED 0x44 #define TM_STATUS 0x54 @@ -34,28 +34,30 @@ static const int TQ_PRTY_TABLE[ANE_TQ_COUNT] = { 0x1, 0x2, 0x3, 0x4, #define TM_IRQ_ACK 0x6c #define TM_IRQ_EN2 0x70 -#define TQ_STATUS(qid) (0x000 + (qid * 0x148)) -#define TQ_PRTY(qid) (0x010 + (qid * 0x148)) -#define TQ_VACANT(qid) (0x014 + (qid * 0x148)) -#define TQ_INFO(qid) (0x01c + (qid * 0x148)) +#define TQ_STATUS(qid) (0x000 + ((qid) * 0x148)) +#define TQ_PRTY(qid) (0x010 + ((qid) * 0x148)) +#define TQ_VACANT(qid) (0x014 + ((qid) * 0x148)) +#define TQ_INFO(qid) (0x01c + ((qid) * 0x148)) -#define TQ_BAR1(qid, bdx) (0x020 + (qid * 0x148) + (bdx * 0x4)) -#define TQ_NID1(qid) (0x0a0 + (qid * 0x148)) -#define TQ_SIZE2(qid) (0x0a4 + (qid * 0x148)) -#define TQ_ADDR2(qid) (0x0a8 + (qid * 0x148)) +#define TQ_BAR1(qid, bdx) (0x020 + ((qid) * 0x148) + ((bdx) * 0x4)) +#define TQ_NID1(qid) (0x0a0 + ((qid) * 0x148)) +#define TQ_SIZE2(qid) (0x0a4 + ((qid) * 0x148)) +#define TQ_ADDR2(qid) (0x0a8 + ((qid) * 0x148)) -#define TQ_BAR2(qid, bdx) (0x0ac + (qid * 0x148) + (bdx * 0x4)) -#define TQ_NID2(qid) (0x12c + (qid * 0x148)) -#define TQ_SIZE1(qid) (0x130 + (qid * 0x148)) -#define TQ_ADDR1(qid) (0x134 + (qid * 0x148)) +#define TQ_BAR2(qid, bdx) (0x0ac + ((qid) * 0x148) + ((bdx) * 0x4)) +#define TQ_NID2(qid) (0x12c + ((qid) * 0x148)) +#define TQ_SIZE1(qid) (0x130 + ((qid) * 0x148)) +#define TQ_ADDR1(qid) (0x134 + ((qid) * 0x148)) #define TM_IS_IDLE 0x1 #define TM_IS_FINE 0x22222222 -#define tm_read32(ane, off) (readl(ane->engine + ANE_TM_BASE + off)) -#define tq_read32(ane, off) (readl(ane->engine + ANE_TQ_BASE + off)) -#define tm_write32(ane, off, val) (writel(val, ane->engine + ANE_TM_BASE + off)) -#define tq_write32(ane, off, val) (writel(val, ane->engine + ANE_TQ_BASE + off)) +#define tm_read32(ane, off) (readl((ane)->engine + ANE_TM_BASE + (off))) +#define tq_read32(ane, off) (readl((ane)->engine + ANE_TQ_BASE + (off))) +#define tm_write32(ane, off, val) \ + (writel(val, (ane)->engine + ANE_TM_BASE + (off))) +#define tq_write32(ane, off, val) \ + (writel(val, (ane)->engine + ANE_TQ_BASE + (off))) /* The ane SET block (m1n1 ANE.ps_map) maps the pmgr power-state words * for this engine (set0, base, set1..4). pmgr reads are always safe and From 52d07a56701734163bbe0221789080dd804a3066 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:37:14 -0500 Subject: [PATCH 13/26] accel/ane: Comment the memory barriers and the mutexes checkpatch reports a MEMORY_BARRIER warning for the four barriers without a comment, and an UNCOMMENTED_DEFINITION check for the three mutexes. Say what each barrier orders and what each mutex protects. Comments only. The non-debug sections of all seven objects are byte-identical before and after this change, except the line number in the one __dyndbg entry of ane_t6021_rtclient_main.o (arm64, gcc 12.2.0). Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane.h | 7 ++++++- drivers/accel/ane/ane_t6021_rtclient_main.c | 3 +++ drivers/accel/ane/ane_tm.c | 8 ++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index c644ec45e67d4..db30a3e103fff 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -46,7 +46,12 @@ struct ane_device { int dart_count; int irq; + /* Protects mm and the iommu_map()/iommu_unmap() calls on domain. */ struct mutex iommu_lock; + /* + * Serializes engine access (submit, BO mapping, recovery, removal) + * and protects bo_list, preserved_list and removed. + */ struct mutex engine_lock; struct list_head bo_list; @@ -98,7 +103,7 @@ struct ane_device { * run ~2x slower while schedutil parks the idle clusters low. */ struct ane_boost { - struct mutex lock; + struct mutex lock; /* protects the fields below */ struct delayed_work off; struct freq_qos_request *legs; int nlegs; diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index e5cda3d046ed6..abe477879d27d 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -506,6 +506,9 @@ static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, if (pending) { writel(pending, ipi + 0xc000); + /* Complete the IPI acknowledgment before the + * next reads of the command and malloc rings. + */ mb(); } header = READ_ONCE(io[0]); diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index 7898c1dd93aaa..9364ae1469b9d 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -267,6 +267,9 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) err = ane_tm_collect_events(ane, NULL, &finished); if (err < 0) goto wedge; + /* Order the CPU writes to the request buffers and the event + * acknowledgments before the queue writes that start the engine. + */ wmb(); ane_tm_push_tq(ane, req); @@ -316,6 +319,10 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) } status = tq_read32(ane, TQ_NID1(req->qid)); tq_write32(ane, TQ_NID1(req->qid), status & ~1U); + /* Kept from the qualified completion sequence (clear the + * NID valid bit, then the queue status). writel() already + * orders the two writes to the engine. + */ rmb(); tq_write32(ane, TQ_STATUS(req->qid), 0x0); ane_dart_release_scratch(ane, scratch, scratch_pages); @@ -333,6 +340,7 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) goto wedge; } tq_write32(ane, TQ_NID1(req->qid), status & ~1U); + /* Same completion sequence as the contained-fault path above. */ rmb(); tq_write32(ane, TQ_STATUS(req->qid), 0x0); ane_dart_unmask(ane); From ee1732f2fcc4850c10a21a9c6b1f75e5d6e550f4 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:38:44 -0500 Subject: [PATCH 14/26] accel/ane: Use kzalloc_obj() checkpatch reports seven ALLOC_WITH_SIZEOF warnings and one ALLOC_SIZEOF_STRUCT check. Allocate the single objects with kzalloc_obj(), which uses GFP_KERNEL when no flags are given. No functional change: kzalloc_obj() expands to kzalloc() of the same size and flags, and the non-debug sections of all seven objects are byte-identical before and after this change (arm64, gcc 12.2.0). Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_dart.c | 2 +- drivers/accel/ane/ane_drv.c | 6 +++--- drivers/accel/ane/ane_t6021_rtclient_main.c | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c index aea8cd9eff182..f66bfbe15af55 100644 --- a/drivers/accel/ane/ane_dart.c +++ b/drivers/accel/ane/ane_dart.c @@ -206,7 +206,7 @@ int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, return -ENOMEM; iova = fault_iova & ~((1ULL << ane->shift) - 1); - node = kzalloc(sizeof(*node), GFP_KERNEL); + node = kzalloc_obj(*node); if (!node) { __free_page(page); return -ENOMEM; diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 8b38416c20b36..054c69c3764d6 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -92,7 +92,7 @@ static int ane_iommu_map_pages(struct ane_device *ane, struct ane_bo *bo) if (bo->mm) return -EBUSY; - bo->mm = kzalloc(sizeof(*bo->mm), GFP_KERNEL); + bo->mm = kzalloc_obj(*bo->mm); if (!bo->mm) return -ENOMEM; @@ -227,7 +227,7 @@ static void ane_preserve_bo(struct ane_device *ane, struct ane_bo *bo) { struct ane_preserved *p; - p = kzalloc(sizeof(*p), GFP_KERNEL); + p = kzalloc_obj(*p); if (!p) { /* Fail closed the old way: the node stays inserted and the * pages leak until reboot - safe, just unreclaimable. @@ -380,7 +380,7 @@ static int ane_bo_init(struct drm_device *drm, void *data, if (args->pad || !args->size) return -EINVAL; - bo = kzalloc(sizeof(struct ane_bo), GFP_KERNEL); + bo = kzalloc_obj(*bo); if (!bo) return -ENOMEM; INIT_LIST_HEAD(&bo->node); diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index abe477879d27d..eb72dbce48814 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -1402,7 +1402,7 @@ static int ane_t6021_bo_init_ioctl(struct drm_device *drm, void *data, return -ENOSPC; } ane = to_ane_t6021_drm(drm)->ane; - bo = kzalloc(sizeof(*bo), GFP_KERNEL); + bo = kzalloc_obj(*bo); if (!bo) { atomic64_sub(PAGE_ALIGN(args->size), &ane_t6021_bo_total_bytes); return -ENOMEM; @@ -1536,7 +1536,7 @@ static int ane_t6021_open(struct drm_device *drm, struct drm_file *file) { struct ane_t6021_fd *fd; - fd = kzalloc(sizeof(*fd), GFP_KERNEL); + fd = kzalloc_obj(*fd); if (!fd) return -ENOMEM; INIT_LIST_HEAD(&fd->bos); @@ -1885,7 +1885,7 @@ static int ane_rtclient_attach_genpd(struct ane_rtclient *ane) if (pd->dev == dev) goto found; - pd = kzalloc(sizeof(*pd), GFP_KERNEL); + pd = kzalloc_obj(*pd); if (!pd) { err = -ENOMEM; goto out; From ef8534228ca6f7fa7300aa7b2803efe575d14220 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:41:16 -0500 Subject: [PATCH 15/26] accel/ane: Fix the remaining coding style issues Fix the style issues that checkpatch --strict reports and that need no change to the generated code: - join the split MODULE_PARM_DESC() strings of ane_t6021_fwload.c (SPLIT_STRING), - wrap three lines longer than 100 columns (LONG_LINE, LONG_LINE_STRING), - move two multi-line trailing comments in ane_t6021_boot.h and one after a #define above the code they describe (BLOCK_COMMENT_STYLE), - use ARRAY_SIZE(), min_t() and BIT() (ARRAY_SIZE, MINMAX, BIT_MACRO), - add braces to the unbalanced if/else statements (BRACES), - remove a pair of unnecessary parentheses (UNNECESSARY_PARENTHESES), - do not end a line with an open parenthesis (OPEN_ENDED_LINE), - reword a comment that checkpatch reads as a fall-through annotation (PREFER_FALLTHROUGH). No functional change: the non-debug sections of all seven objects are byte-identical before and after this change (arm64, gcc 12.2.0). Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_drv.c | 20 +++++++----- drivers/accel/ane/ane_t6021.h | 6 ++-- drivers/accel/ane/ane_t6021_boot.c | 4 +-- drivers/accel/ane/ane_t6021_boot.h | 35 +++++++++------------ drivers/accel/ane/ane_t6021_fwload.c | 18 +++++------ drivers/accel/ane/ane_t6021_rtclient_main.c | 13 ++++---- 6 files changed, 45 insertions(+), 51 deletions(-) diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 054c69c3764d6..738fa5d17b1fa 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -513,8 +513,8 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) } gem[bdx] = &bo->base; if (!bo->iova || - ((bdx == CMD_BUF_BDX) && - (args->tsk_size >= (bo->npages << ane->shift)))) { + (bdx == CMD_BUF_BDX && + args->tsk_size >= (bo->npages << ane->shift))) { err = -EINVAL; goto put; } @@ -749,10 +749,10 @@ static int ane_drm_mmap(struct file *file, struct vm_area_struct *vma) */ vm_flags_mod(vma, VM_IO | VM_DONTEXPAND | VM_DONTDUMP, VM_PFNMAP); - if (map_mode & 2) + if (map_mode & 2) { vma->vm_page_prot = pgprot_decrypted(vm_get_page_prot(vma->vm_flags)); - else { + } else { vma->vm_page_prot = pgprot_writecombine(vm_get_page_prot(vma->vm_flags)); vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot); @@ -859,8 +859,9 @@ static int ane_attach_genpd(struct ane_device *ane) { struct device *dev = ane->dev; - ane->pd_count = of_count_phandle_with_args( - dev->of_node, "power-domains", "#power-domain-cells"); + ane->pd_count = of_count_phandle_with_args(dev->of_node, + "power-domains", + "#power-domain-cells"); if (ane->pd_count < 1) return ane->pd_count < 0 ? ane->pd_count : -EINVAL; if (ane->pd_count == 1) @@ -1119,8 +1120,11 @@ static int __maybe_unused ane_runtime_resume(struct device *dev) * hard reset after the last off-box line names the * killing access exactly. */ - struct resource *eng = platform_get_resource_byname( - to_platform_device(dev), IORESOURCE_MEM, "engine"); + struct platform_device *pdev = to_platform_device(dev); + struct resource *eng; + + eng = platform_get_resource_byname(pdev, IORESOURCE_MEM, + "engine"); dev_info(dev, "ANE-resume: genpd raise complete; SET window probe next\n"); diff --git a/drivers/accel/ane/ane_t6021.h b/drivers/accel/ane/ane_t6021.h index 5e0ecc6d471f7..03d9ee35cdd96 100644 --- a/drivers/accel/ane/ane_t6021.h +++ b/drivers/accel/ane/ane_t6021.h @@ -529,9 +529,9 @@ int ane_t6021_boot_start(struct ane_t6021 *ane, int stop_after, int table_mode, * The generic processor takes commands < 0x1b89 bytes (work-item size * bound @0x4d134-0x4d158) and writes completion state back into the * command block (strb @0x4d324 byte +6, str @0x4d3b0 qword +8) — the - * ring slot doubles as the response area. PING/BUILDINFO/BOOT/ - * REG_FILE_LOAD/IPC_ENDPOINT_SET fall through the processor's id tree - * to the default path (0x4e65c): carried without field parsing, so + * ring slot doubles as the response area. The processor's id tree + * sends PING/BUILDINFO/BOOT/REG_FILE_LOAD/IPC_ENDPOINT_SET on to the + * default path (0x4e65c): carried without field parsing, so * their payloads beyond the header are opaque until the W1 live * exchange pins them. */ diff --git a/drivers/accel/ane/ane_t6021_boot.c b/drivers/accel/ane/ane_t6021_boot.c index 066d2a799851a..de11bb8f095fa 100644 --- a/drivers/accel/ane/ane_t6021_boot.c +++ b/drivers/accel/ane/ane_t6021_boot.c @@ -549,8 +549,8 @@ int ane_t6021_boot_start(struct ane_t6021 *ane, int stop_after, int table_mode, dev_info(ane->dev, "boot: run returned 0 (booted=%u fw_alive=%u) — %s; scratch_result=%016llx (raw device address, semantics UNSOURCED — not a success claim; transport stays fenced until response validation)\n", bo, fa, - bo ? "DONE observed — handshake complete" - : "rc 0 WITHOUT DONE (rtb_mode: HELLO-gated; DONE not part of this mode)", + bo ? "DONE observed — handshake complete" : + "rc 0 WITHOUT DONE (rtb_mode: HELLO-gated; DONE not part of this mode)", sres); return r; } diff --git a/drivers/accel/ane/ane_t6021_boot.h b/drivers/accel/ane/ane_t6021_boot.h index ced0c997439dd..aba267e453f13 100644 --- a/drivers/accel/ane/ane_t6021_boot.h +++ b/drivers/accel/ane/ane_t6021_boot.h @@ -69,14 +69,11 @@ #define ANE_T6021_INIT_TEMPLATE_OFF 0x6c /* 256 B at [0x6C,0x16C) */ #define ANE_T6021_INIT_TEMPLATE_SIZE 0x100 #define ANE_T6021_INIT_TBIT_OFF 0xc0 /* template-relative */ -#define ANE_T6021_INIT_TBIT_VAL 0x4 /* RESOLVED (Main raw - * anchors 0x9612b78/7c/80: - * ldr/orr#4/str on the dev+0x998 - * template); the conditional - * |=0x10 is a separate, still - * unqualified mutation and is - * NOT set - */ +/* RESOLVED (Main raw anchors 0x9612b78/7c/80: ldr/orr#4/str on the + * dev+0x998 template); the conditional |=0x10 is a separate, still + * unqualified mutation and is NOT set. + */ +#define ANE_T6021_INIT_TBIT_VAL 0x4 static inline u64 ane_t6021_rvbar_compose(u64 iova) { @@ -451,18 +448,14 @@ struct ane_t6021_boot_io { u64 (*rd64)(void *ctx, unsigned int off); void (*wr32)(void *ctx, unsigned int off, u32 v); void (*wr64)(void *ctx, unsigned int off, u64 v); - void (*publish_barrier)(void *ctx); /* orders the coherent fill - * before the device publish: - * dma_wmb() = dmb oshst on - * arm64; NOT claimed as dsb st - * (completion) - */ - void (*phase)(void *ctx, const char *what); /* bounded phase log: - * emitted ONCE before each - * write/poll block so a crash - * source survives netconsole - * (never per-poll) - */ + /* Orders the coherent fill before the device publish: dma_wmb() = + * dmb oshst on arm64; NOT claimed as dsb st (completion). + */ + void (*publish_barrier)(void *ctx); + /* Bounded phase log: emitted ONCE before each write/poll block so a + * crash source survives netconsole (never per-poll). + */ + void (*phase)(void *ctx, const char *what); void (*poll_wait)(void *ctx); /* 1 ms poll delay */ /* prepare(): called once, strictly AFTER poll A and BEFORE the * SCRATCH0/1 publish; returns the suballoc DVA halves. Kernel @@ -603,7 +596,7 @@ ane_t6021_boot_run(const struct ane_t6021_boot_io *io, unsigned int ti; io->phase(io->ctx, "P-1 grant-tunables begin"); - for (ti = 0; ti < sizeof(tun) / sizeof(tun[0]); ti++) { + for (ti = 0; ti < ARRAY_SIZE(tun); ti++) { io->phase(io->ctx, tun[ti].off == 0x000 ? "P-1a eng+0x000" : tun[ti].off == 0x038 ? "P-1b eng+0x038" : diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index 1e44f0355b485..d677962a828b7 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -93,14 +93,12 @@ MODULE_DESCRIPTION("T6021 ANE firmware staging + entry alias"); static bool fw_load = true; module_param(fw_load, bool, 0444); MODULE_PARM_DESC(fw_load, - "Validate + DART-map the 13.5 PRELOAD payload (default on: " - "the proven add-path configuration)."); + "Validate + DART-map the 13.5 PRELOAD payload (default on: the proven add-path configuration)."); static unsigned int fw_extra_ram = 0x200000; module_param(fw_extra_ram, uint, 0444); MODULE_PARM_DESC(fw_extra_ram, - "Page-aligned owned RAM after the 5 MiB firmware allocation " - "(default 0x200000, the proven add-path grant; maximum 16 MiB)."); + "Page-aligned owned RAM after the 5 MiB firmware allocation (default 0x200000, the proven add-path grant; maximum 16 MiB)."); /* Preloaded-placement alias, lab only: map the iBoot-reserved SEG0/SEGi * phys at the entry IOVAs (the preload, with iBoot's patches in place). @@ -113,11 +111,7 @@ MODULE_PARM_DESC(fw_extra_ram, static bool fw_alias_reserved; module_param(fw_alias_reserved, bool, 0444); MODULE_PARM_DESC(fw_alias_reserved, - "Lab, T6021: map reserved SEG0 0x10000848000+0xc4000 at entry and " - "SEG1 0x10001400000+0x438000 after it (probe refuses unless no-map " - "/reserved-memory nodes cover both); 0 (default) = run the staged " - "copy with iBoot's patches replayed (own memory, the only mode on " - "T6020/T6022)."); + "Lab, T6021: map reserved SEG0 0x10000848000+0xc4000 at entry and SEG1 0x10001400000+0x438000 after it (probe refuses unless no-map /reserved-memory nodes cover both); 0 (default) = run the staged copy with iBoot's patches replayed (own memory, the only mode on T6020/T6022)."); static bool ane_t6021_fw_alias_is_reserved(struct device *dev) { @@ -314,7 +308,8 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) * DATA section unmapped past the SEG0 head. */ struct { u64 iova, phys, len; } win[] = { - { 0x10000000000ull, ane_t6021_fw_preload[0].phys, ane_t6021_fw_preload[0].len }, + { 0x10000000000ull, ane_t6021_fw_preload[0].phys, + ane_t6021_fw_preload[0].len }, { 0, ane_t6021_fw_preload[1].phys, ane_t6021_fw_preload[1].len }, { entry + 0x4fc000, 0, fw_extra_ram ? ane->fw_size - 0x4fc000 : 0 }, }; @@ -340,7 +335,8 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) for (o = 0; o < win[w].len; o += ANE_T6021_FW_ALIAS_PAGE) { phys_addr_t pa = w < 2 ? win[w].phys + o : - iommu_iova_to_phys(dom, ane->fw_iova + win[w].iova + o - entry); + iommu_iova_to_phys(dom, ane->fw_iova + + win[w].iova + o - entry); if (!pa || !IS_ALIGNED(pa, ANE_T6021_FW_ALIAS_PAGE)) { ret = -EFAULT; goto err_unmap_mapped; diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index eb72dbce48814..676029a9e7b27 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -620,7 +620,7 @@ MODULE_PARM_DESC(call_settle_us, * trace state is protected by ane_t6021_fw_lock. */ #define ANE_TRACE_MAGIC 0x31445441 /* "ATD1" */ -#define ANE_TRACE_RECS (1U << 18) +#define ANE_TRACE_RECS BIT(18) #define ANE_PMGR_PS_LAST_OFF 0x30 enum { @@ -1085,7 +1085,8 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, sha256_update(&sha, (const u8 *)hdr, sizeof(hdr)); left = sections[i].size; while (left) { - size_t n = min(left, (size_t)ANE_T6021_BO_HASH_CHUNK); + size_t n = min_t(size_t, left, + ANE_T6021_BO_HASH_CHUNK); memcpy(scratch, (const u8 *)bo->cpu + sections[i].offset + @@ -2238,9 +2239,9 @@ static int ane_rtclient_probe(struct platform_device *pdev) READ_ONCE(((u32 *)command->cpu)[1]), READ_ONCE(((u32 *)command->cpu)[2]), qret); - if (qret) + if (qret) { cfg_err = qret; - else if (!READ_ONCE(((u32 *)command->cpu)[2])) { + } else if (!READ_ONCE(((u32 *)command->cpu)[2])) { dev_err(dev, "LEGACY CONFIG_GET reply word +0x08 zero\n"); cfg_err = -EPROTO; @@ -2337,11 +2338,11 @@ static int ane_rtclient_probe(struct platform_device *pdev) return 0; err_pm_or_hold: - if (ane->held) + if (ane->held) { dev_warn(dev, "probe failed after CPU start (%pe) — binding fenced; power/rings/IRQ HELD until reboot\n", ERR_PTR(ret)); - else { + } else { pm_runtime_put_sync_suspend(dev); pm_runtime_disable(dev); } From 2cdb92de79575062c6e043dc5daf10f403410fe7 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:29:18 -0500 Subject: [PATCH 16/26] accel/ane: Declare the M2 ANE firmware files ane_t6021 loads apple/ane/t602x_ane0_fw_selene_rc4x.macho on T602x and apple/ane/h14_ane_fw_bia_j4xx.macho on T8112. Declare both with MODULE_FIRMWARE() and keep each name in one macro. The firmware is a distribution concern: omarchy-ane-firmware-fetch installs these files under /lib/firmware/apple/ane. When request_firmware() fails, name the file and how to install it. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_fw_validate.h | 8 ++++++-- drivers/accel/ane/ane_t6021_fwload.c | 6 ++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/drivers/accel/ane/ane_fw_validate.h b/drivers/accel/ane/ane_fw_validate.h index 00ef2982c67e4..f4f723a3f33df 100644 --- a/drivers/accel/ane/ane_fw_validate.h +++ b/drivers/accel/ane/ane_fw_validate.h @@ -50,6 +50,10 @@ struct ane_fw_seg { char name[17]; /* 16 + NUL */ }; +/* request_firmware() names */ +#define ANE_FW_SELENE_NAME "apple/ane/t602x_ane0_fw_selene_rc4x.macho" +#define ANE_FW_BIA_NAME "apple/ane/h14_ane_fw_bia_j4xx.macho" + /* One pinned image. The patch fields are the payload's LC_SYMTAB * addresses: the __rtk_patch records _rtk_stack_guard, RTK_soc, * RTK_soc_revision, RTK_cpu_physical_address and @@ -66,7 +70,7 @@ struct ane_fw_image { }; static const struct ane_fw_image ane_fw_selene = { - .name = "apple/ane/t602x_ane0_fw_selene_rc4x.macho", + .name = ANE_FW_SELENE_NAME, .sha256 = { 0xa9, 0xc4, 0xb7, 0x71, 0x29, 0x4a, 0x6b, 0x11, 0x56, 0x24, 0xd9, 0x48, 0x0a, 0x62, 0x48, 0xd0, @@ -83,7 +87,7 @@ static const struct ane_fw_image ane_fw_selene = { }; static const struct ane_fw_image ane_fw_bia = { - .name = "apple/ane/h14_ane_fw_bia_j4xx.macho", + .name = ANE_FW_BIA_NAME, .sha256 = { 0xaf, 0x58, 0x7d, 0xfa, 0x96, 0xb1, 0xe0, 0x1d, 0x2b, 0x2e, 0x0f, 0x9f, 0x77, 0x6e, 0x5d, 0xbe, diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index d677962a828b7..c8a7ad8d7bee8 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -89,6 +89,8 @@ */ MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("T6021 ANE firmware staging + entry alias"); +MODULE_FIRMWARE(ANE_FW_SELENE_NAME); +MODULE_FIRMWARE(ANE_FW_BIA_NAME); static bool fw_load = true; module_param(fw_load, bool, 0444); @@ -565,8 +567,8 @@ int ane_t6021_fwload_probe(struct ane_t6021 *ane) ret = request_firmware(&fw, img->name, ane->dev); if (ret) { dev_err(ane->dev, - "fwload: request_firmware(%s): %d — stage the payload " - "with omarchy-ane-firmware-fetch\n", img->name, ret); + "cannot load firmware %s: %d; install it with omarchy-ane-firmware-fetch (or equivalent for your distribution)\n", + img->name, ret); return ret; } From b5e8553dfb03e56ab7126053843019b2c910542f Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:51:13 -0500 Subject: [PATCH 17/26] accel/ane: Add the ane_stats counters and ane_timeline Add producer-side statistics to both ANE drivers. /sys/class/accel/accel/device/ane_stats is a read-only (0444) file with two cumulative counters, one "key value" pair per line: - busy_ns: the nanoseconds the engine was busy since bind. A busy period opens when the first submission arrives on an idle engine and closes when the last one completes. Overlapping submissions share a period, so busy_ns is the union of the submit-to-completion windows, not their sum. ane serializes submissions behind engine_lock, so there the union is the sum. A read adds the time of the open period, so the value also increases while work is in flight. - jobs: the completed engine submissions since bind. ane counts each ANE_SUBMIT. ane_t6021 counts only CSNE_CMD_PROCEDURE_CALL. The control-plane commands on the same path and the boot transport are not engine work and do not count. A submission that fails still completes its begin/complete pair, so the counters stay balanced. Documentation/ABI/testing/sysfs-class-accel-ane describes the file. The ane_timeline debugfs file shows the latest submissions from a ring that the driver allocates at probe: seq, submit_ns, start_ns, end_ns, tasks, rc and tmst. Each slot has a sequence number, so a reader skips a slot that is in flight or that a later submission reuses. ane records the raw TM tick as tmst. ane_t6021 has no host TM path and records 0. Both drivers create the file with drm_debugfs_add_file(). The producer uses atomics only. It does not allocate, lock or format. A transition sentinel in the inflight count keeps the fold of one busy period and the start of the next apart. The next period starts at or after the fold end of the previous one. Both modules have a read-only stats parameter, default 1, that the driver reads at probe. With stats=0, or when the ring allocation fails, the driver creates no stats files and the submission path skips the counters. Testing: in the tree, this code is compile-verified only (arm64 W=1, =m and =y, and checkpatch --strict). A host test of the accounting through a kernel API shim passes. It includes a model check of all orders of three jobs, with a preemption at each atomic operation. The out-of-tree omarchy-ane driver with the same accounting passed the hardware gates on T8103 (M1) and T6001 (M1 Max). That version read max_end for the period start before it took the transition sentinel; this commit reads it after. The T6021 (M2 Max) path is in test. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- .../ABI/testing/sysfs-class-accel-ane | 50 ++ MAINTAINERS | 1 + drivers/accel/ane/ane.h | 12 + drivers/accel/ane/ane_drv.c | 84 +++- drivers/accel/ane/ane_stats.h | 431 ++++++++++++++++++ drivers/accel/ane/ane_t6021_rtclient_main.c | 125 +++++ drivers/accel/ane/ane_tm.c | 9 +- drivers/accel/ane/ane_tm.h | 3 + 8 files changed, 713 insertions(+), 2 deletions(-) create mode 100644 Documentation/ABI/testing/sysfs-class-accel-ane create mode 100644 drivers/accel/ane/ane_stats.h diff --git a/Documentation/ABI/testing/sysfs-class-accel-ane b/Documentation/ABI/testing/sysfs-class-accel-ane new file mode 100644 index 0000000000000..668bed9c7cb38 --- /dev/null +++ b/Documentation/ABI/testing/sysfs-class-accel-ane @@ -0,0 +1,50 @@ +What: /sys/class/accel/accel/device/ane_stats +Date: October 2026 +KernelVersion: 7.1 +Contact: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> +Description: + Cumulative Apple Neural Engine (ANE) producer counters for + this device, one ASCII "key value" pair per line, mode + 0444 (readable without root): + + busy_ns: nanoseconds the engine was busy since the + device was bound, sampled with a consistent + close/open snapshot. A busy period opens + when the first submission lands on an idle + engine and closes when the last one + completes; its whole span folds once at + close, and overlapping submissions share + the period, so a serialized engine + (ane.ko, behind engine_lock) reports + sum(end - start) and a parallel engine + (ane_t6021) reports the union, never the + sum. The show callback adds the live tail + of the still-open period, so the value + advances while engine work is in flight. + + jobs: completed engine submissions since the + device was bound. On ane.ko every ANE_SUBMIT + counts (one per libane ane_exec, N per + ane_exec_loop). On ane_t6021 only + CSNE_CMD_PROCEDURE_CALL counts (one per + engine PROCEDURE_CALL); the control-plane + exchanges that ride the same path + (LOAD_PROGRAM, CREATE_PROCESS, + CH_PROPERTY_WRITE, install-time CONFIG_GET) + and the boot transport are not engine + work and are not counted. A submission + that completes with an error still + completes its begin/complete pair, so the + counter stays balanced. + + Neither counter resets while the device is bound. + + 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. + +Users: performance samplers that compute engine utilization + and job rate from the two counters. + + diff --git a/MAINTAINERS b/MAINTAINERS index 9b91fa8f0f987..1846894899917 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7903,6 +7903,7 @@ M: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> L: asahi@lists.linux.dev L: dri-devel@lists.freedesktop.org S: Maintained +F: Documentation/ABI/testing/sysfs-class-accel-ane F: Documentation/devicetree/bindings/npu/apple,ane.yaml F: drivers/accel/ane/ F: include/uapi/drm/ane_accel.h diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index db30a3e103fff..eac81bdab9f74 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -15,6 +15,8 @@ #include +#include "ane_stats.h" + struct ane_device { struct drm_device drm; struct device *dev; @@ -112,6 +114,16 @@ struct ane_device { bool busy; bool on; } boost; + + /* + * Producer-side stats (sysfs ane_stats, debugfs ane_timeline; + * see ane_stats.h). stats=0 or a failed ring allocation leaves + * stats_slots NULL, which is the one hot-path gate: no files, + * no counter updates. + */ + struct ane_stats_counters stats_ctrs; + struct ane_stats_ring stats_ring; + struct ane_stats_ring_entry *stats_slots; }; struct ane_request { diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 738fa5d17b1fa..20e32a76f190a 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -2,7 +2,9 @@ /* Copyright 2022 Eileen Yoon */ #include +#include #include +#include #include #include #include @@ -11,6 +13,7 @@ #include #include +#include #include #include #include @@ -53,6 +56,16 @@ module_param(map_mode, int, 0644); MODULE_PARM_DESC(map_mode, "BO mapping: bit0=IOMMU_CACHE DART descriptors, bit1=cacheable CPU vmas (default 3 = cached; 0 = writecombine + non-cacheable rollback)"); +/* + * Producer-side stats (ane_stats sysfs, ane_timeline debugfs), read + * once at probe. stats=0 keeps the hot path at its single predictable + * branch (the NULL stats_slots check) and no files are created. + */ +static bool stats = true; +module_param(stats, bool, 0444); +MODULE_PARM_DESC(stats, + "Expose ane_stats sysfs and ane_timeline debugfs (default 1; 0 = no files and the hot path skips the counters)"); + #define CMD_BUF_BDX 0 #define KRN_BUF_BDX 1 @@ -480,6 +493,7 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) struct drm_gem_object *btsp = NULL; struct ane_bo *bo; struct ane_request req; + u64 stats_idx = 0; int err; memset(&req, 0, sizeof(req)); @@ -561,10 +575,19 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) if (err < 0) goto unlock; + if (ane->stats_slots) + stats_idx = ane_stats_begin(&ane->stats_ctrs, &ane->stats_ring, + ktime_get_ns(), req.td_count); + ane_boost_begin(ane); err = ane_tm_execute(ane, &req); ane_boost_end(ane); + if (ane->stats_slots) + ane_stats_complete(&ane->stats_ctrs, &ane->stats_ring, + stats_idx, ktime_get_ns(), + err ? (u32)err : 0, ane_last_tmst); + unlock: mutex_unlock(&ane->engine_lock); put: @@ -611,12 +634,47 @@ static ssize_t reset_store(struct device *dev, struct device_attribute *attr, } static DEVICE_ATTR_WO(reset); +/* + * ane_stats: cumulative busy_ns/jobs for this device (mode 0444, no + * root needed). Formatting lives in ane_stats_emit() (ane_stats.h), + * shared with ane_t6021.ko. + */ +static ssize_t ane_stats_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct ane_device *ane = dev_get_drvdata(dev); + + return ane_stats_emit(buf, &ane->stats_ctrs); +} +static DEVICE_ATTR_RO(ane_stats); + static struct attribute *ane_dev_attrs[] = { &dev_attr_wedged.attr, &dev_attr_reset.attr, + &dev_attr_ane_stats.attr, + NULL, +}; + +/* ane_stats appears only when stats=1 gave the device a ring. */ +static umode_t ane_dev_attr_is_visible(struct kobject *kobj, + struct attribute *attr, int n) +{ + struct ane_device *ane = dev_get_drvdata(kobj_to_dev(kobj)); + + if (attr == &dev_attr_ane_stats.attr && !ane->stats_slots) + return 0; + return attr->mode; +} + +static const struct attribute_group ane_dev_group = { + .attrs = ane_dev_attrs, + .is_visible = ane_dev_attr_is_visible, +}; + +static const struct attribute_group *ane_dev_groups[] = { + &ane_dev_group, NULL, }; -ATTRIBUTE_GROUPS(ane_dev); static int ane_drm_open(struct drm_device *drm, struct drm_file *file) { @@ -964,6 +1022,25 @@ static int ane_platform_probe(struct platform_device *pdev) atomic_set(&ane->wedged, 0); ane->tm_retention = soc->tm_retention; + /* Producer-side stats: preallocate the ring at probe; the files + * and the hot-path branch key off stats_slots. + */ + if (stats) { + ane->stats_slots = devm_kcalloc(dev, + 1u << ANE_STATS_RING_ORDER_DEFAULT, + sizeof(*ane->stats_slots), + GFP_KERNEL); + if (ane->stats_slots) { + ane_stats_counters_init(&ane->stats_ctrs, + &ane->stats_ring, + ANE_STATS_RING_ORDER_DEFAULT); + ane->stats_ring.slots = ane->stats_slots; + } else { + dev_warn(dev, + "ane_stats ring allocation failed; stats disabled\n"); + } + } + /* Managed power first: genpd links hold the ANE/DART supplier * topology awake before any register is touched. */ @@ -1040,6 +1117,11 @@ static int ane_platform_probe(struct platform_device *pdev) if (err < 0) goto put_pm; + if (ane->stats_slots) + drm_debugfs_add_file(drm, "ane_timeline", + ane_timeline_show, + &ane->stats_ring); + err = drm_dev_register(drm, 0); if (err < 0) goto put_pm; diff --git a/drivers/accel/ane/ane_stats.h b/drivers/accel/ane/ane_stats.h new file mode 100644 index 0000000000000..768fe97846edc --- /dev/null +++ b/drivers/accel/ane/ane_stats.h @@ -0,0 +1,431 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Producer-side ANE counters and submission ring, shared by ane.ko and + * ane_t6021.ko. + * + * Contract: + * - sysfs under /sys/class/accel/accel/device/ane_stats, + * mode 0444, ASCII "key value" lines, integers only: busy_ns + * (cumulative u64), jobs (cumulative u64). busy_ns counts only + * nanoseconds the engine was busy (union of submit-to-completion + * windows) since the device was bound, and advances while work is + * in flight: the show callback adds the open period's live tail. + * - debugfs ane_timeline: preallocated ring of the last N submissions + * with seq, submit_ns, start_ns, end_ns, tasks, rc (and tmst raw + * when known). Head counter is atomic; per-slot seqlock so the + * reader never blocks the producer and torn reads are detected. + * - `stats` module parameter bool, default 1; stats=0 makes the hot + * path one predictable branch and skips sysfs/debugfs creation. + * + * No allocation, locking, or formatting in the hot path. The sysfs + * show callback formats in process context; the ring writer commits + * the slot with a release store, and the reader does an acquire load + * on begin/end. Counters update with atomics only. busy_ns is the + * union of busy intervals: a busy period opens when the first + * submission lands on an idle engine and closes when the last one + * completes, and its whole span folds once at close; overlapping + * submissions share the period, so a serialized engine (ane.ko, + * behind engine_lock) reports sum(end - start) and a parallel engine + * (ane_t6021) reports the union, never the sum. + */ + +#ifndef __ANE_STATS_H__ +#define __ANE_STATS_H__ + +#include +#include +#include +#include +#include +#include +#include + +/* + * Per-device counters. busy_ns holds the busy time folded from closed + * busy periods: a period opens when the first submission arrives on an + * idle engine and closes when the last one completes, and its whole + * span folds once at close. Overlapping submissions share the period, + * so busy_ns is the union of the submit-to-completion intervals, not + * their sum. The show callback adds the live tail of the still-open + * period, so the reported value advances while engine work is in + * flight. jobs counts completed submissions. last_busy_end is the open + * period's start timestamp; inflight is the number of in-flight + * submissions, with ANE_STATS_INFLIGHT_TRANS as the transient close/ + * open sentinel that keeps a fold and a period start from interleaving. + * + * Module-level `stats` parameter governs whether these counters and + * the ring are created and whether the hot path branches out. + */ +#define ANE_STATS_INFLIGHT_TRANS 0xFFFFFFFFu + +struct ane_stats_counters { + atomic64_t busy_ns; + atomic64_t jobs; + atomic64_t last_busy_end; + atomic64_t max_end; + atomic_t inflight; +}; + +/* + * max_end tracks the latest completion sample fed to complete(); the + * draining completion folds against max(end_ns, max_end) so a stale + * sample on the last completer cannot truncate the period. + */ +static inline void ane_stats_atomic64_max(u64 i, atomic64_t *v) +{ + u64 old = atomic64_read(v); + + while (i > old && !atomic64_try_cmpxchg(v, &old, i)) + ; +} + +/* + * Ring slot: seqlock-style per-slot sequence. Writer bumps seq at + * entry (odd) and again on commit (even); reader loads begin/end + * inside acquire load and the order relative to begin/end is preserved + * by release. begin/end 0 means the slot is empty. submit_ns, end_ns, + * tasks, rc, tmst are the diagnostic fields; tmst is the raw TM tick + * on ane.ko (unknown unit) and 0 on ane_t6021 (unavailable, marked so + * in the file header line). + */ +struct ane_stats_ring_entry { + atomic64_t seq; /* even = committed; odd = writing */ + atomic64_t submit_ns; + atomic64_t start_ns; + atomic64_t end_ns; + atomic_t tasks; + atomic_t rc; + atomic64_t tmst; /* raw TM tick on ane.ko; 0 = unavailable */ +}; + +/* + * Ring container. head is the next slot to write (increments mod N). + * N is a power of two preallocated at probe. slots is the array. + * Reader takes begin/end under acquire and the seqlock protects + * against torn writes. + */ +struct ane_stats_ring { + atomic64_t head; + u32 n; /* power of two */ + u32 mask; /* n - 1 */ + struct ane_stats_ring_entry *slots; +}; + +/* + * Initialize counters and ring from zero. The ring slots array must + * be preallocated (probe-time) and zeroed. Named + * ane_stats_counters_init (not ane_stats_init) so the per-driver + * glue function (ane_stats_init(struct ane_device *) etc.) can name + * its own static initializer without conflicting with the prototype. + */ +static inline void ane_stats_counters_init(struct ane_stats_counters *ctrs, + struct ane_stats_ring *ring, + u32 n_shift) +{ + u32 n_total = (1u << n_shift); + + memset(ctrs, 0, sizeof(*ctrs)); + memset(ring, 0, sizeof(*ring)); + ring->n = n_total; + ring->mask = n_total - 1u; + atomic64_set_release(&ring->head, 0ull); +} + +/* + * Hot-path submission start. Caller holds the device's submission + * serialization if the engine is single-producer (ane.ko); concurrent + * drivers (ane_t6021) pass ring/ctrs and rely on the cmpxchg loops. + * Returns the submission ticket (head + 1, starting at 1) for the + * caller to later call ane_stats_complete() with. The ticket, not a + * slot index, identifies the submission: slots are shared after wrap, + * tickets are not. + * + * Counter side: the first submission onto an idle engine opens a busy + * period by latching last_busy_end = submit_ns under the transition + * sentinel; later overlapping submissions only increment inflight. + * The sentinel window is a handful of instructions, so the bounded + * cmpxchg retries never observe a half-open period. + * + * A period never starts before the previous one folded: a caller + * sample can be stale (taken before the transition), so the latch is + * max(submit_ns, max_end), with max_end read under the transition + * sentinel. + */ +static inline u64 ane_stats_begin(struct ane_stats_counters *ctrs, + struct ane_stats_ring *ring, + u64 submit_ns, u32 tasks) +{ + u64 ticket = atomic64_fetch_add(1ull, &ring->head) + 1ull; + struct ane_stats_ring_entry *e = + &ring->slots[(size_t)(ticket - 1ull) & ring->mask]; + u64 latch; + u32 cur = atomic_read(&ctrs->inflight); + + for (;;) { + if (cur == ANE_STATS_INFLIGHT_TRANS) { + cur = atomic_read(&ctrs->inflight); + } else if (!cur) { + if (atomic_cmpxchg(&ctrs->inflight, 0u, + ANE_STATS_INFLIGHT_TRANS) != 0u) { + cur = atomic_read(&ctrs->inflight); + continue; + } + /* + * Read max_end only now. The drainer of the previous + * period fed its end sample into max_end before its + * release store of inflight = 0, and every other + * member fed before its decrement. The fully ordered + * cmpxchg above read that 0, so this read sees every + * feed and the latch is never below the previous + * fold end: periods cannot overlap. + */ + latch = atomic64_read(&ctrs->max_end); + if (submit_ns > latch) + latch = submit_ns; + atomic64_set_release(&ctrs->last_busy_end, latch); + atomic_set_release(&ctrs->inflight, 1u); + break; + } else if (atomic_try_cmpxchg(&ctrs->inflight, &cur, + cur + 1u)) { + break; + } + } + + /* + * Order the counter stores above (last_busy_end, inflight) before + * the slot stores below. + */ + smp_wmb(); + (void)atomic64_read_acquire(&e->seq); /* pair with reader */ + /* + * In flight: seq stays odd (2*ticket - 1) until complete() + * commits the even final value 2*ticket. The reader only prints + * even seqs it can match, so an unfinished submission never + * prints and a torn write is never visible. + */ + atomic64_set_release(&e->seq, 2ull * ticket - 1ull); + atomic64_set_release(&e->submit_ns, submit_ns); + /* + * start_ns is the busy-period start this submission is counted + * from (the latch), not the caller's sample: a sample taken + * before the transition can predate period entry, and the + * union reference must use consumed values. + */ + atomic64_set_release(&e->start_ns, + atomic64_read(&ctrs->last_busy_end)); + atomic64_set_release(&e->end_ns, submit_ns); + atomic_set(&e->tasks, tasks); + atomic_set(&e->rc, (u32)0xFFFFFFFFu); /* sentinel: not done */ + atomic64_set_release(&e->tmst, 0ull); + return ticket; +} + +/* + * Hot-path submission completion. The last submission out of a busy + * period closes it: under the transition sentinel it folds the whole + * period span [last_busy_end, end_ns] into busy_ns before reopening + * the counter, so no reader can see a period both live and folded. + * Overlapping submissions share the period, so busy_ns is the union + * of the submit-to-completion intervals, not their sum. Updates the + * slot's end_ns/rc/tmst and increments jobs. + */ +static inline void ane_stats_complete(struct ane_stats_counters *ctrs, + struct ane_stats_ring *ring, + u64 ticket, u64 end_ns, + u32 rc, u64 tmst) +{ + struct ane_stats_ring_entry *e = + &ring->slots[(size_t)(ticket - 1ull) & ring->mask]; + u32 cur = atomic_read(&ctrs->inflight); + u64 fold_end = 0ull; + + /* + * Feed this completion's end sample before the transition: a + * drainer can only observe inflight == 1 after every other + * completer has fed, so the fold below sees the whole period. + */ + ane_stats_atomic64_max(end_ns, &ctrs->max_end); + + for (;;) { + if (cur == ANE_STATS_INFLIGHT_TRANS) { + cur = atomic_read(&ctrs->inflight); + } else if (cur > 1u) { + if (atomic_try_cmpxchg(&ctrs->inflight, &cur, + cur - 1u)) + break; + } else if (!cur) { + /* + * Unbalanced complete (cannot happen with the + * documented one-begin-per-complete pairing): + * count the job, fold nothing, never hang. + */ + break; + } else if (atomic_cmpxchg(&ctrs->inflight, 1u, + ANE_STATS_INFLIGHT_TRANS) != 1u) { + cur = atomic_read(&ctrs->inflight); + } else { + u64 s = atomic64_read(&ctrs->last_busy_end); + + /* + * The period ends at the latest completion sample + * in it, not at this caller's (possibly stale) + * sample: every member fed max_end before the + * drain could observe inflight == 1. + */ + fold_end = atomic64_read(&ctrs->max_end); + if (fold_end < end_ns) + fold_end = end_ns; + if (fold_end > s) + atomic64_add(fold_end - s, &ctrs->busy_ns); + atomic_set_release(&ctrs->inflight, 0u); + break; + } + } + atomic64_add(1ull, &ctrs->jobs); + + /* Order the counter stores above before the slot stores below. */ + smp_wmb(); + /* + * The drainer records the consumed fold end, not its own sample, + * so the slot union equals busy_ns exactly. + */ + if (fold_end) + atomic64_set_release(&e->end_ns, fold_end); + else + atomic64_set_release(&e->end_ns, end_ns); + atomic_set(&e->rc, rc); + atomic64_set_release(&e->tmst, tmst); + /* + * Order the slot field stores before the even seq store that + * publishes them; pairs with the acquire load of e->seq in + * ane_timeline_show(). + */ + smp_wmb(); + /* + * Commit the slot with the even final seq 2*ticket. The value + * must not depend on the current ring->head: concurrent + * submissions (ane_t6021) advance it, and a head-derived seq + * would mislabel the slot. + */ + atomic64_set_release(&e->seq, 2ull * ticket); +} + +/* + * The timeline formatter is header-only so each module gets its own + * copy: kbuild rejects one object linked into two modules, and with + * both drivers built-in a shared object would duplicate symbols at + * vmlinux link. Both drivers register it with drm_debugfs_add_file(), + * so m->private is the struct drm_debugfs_entry and the ring is the + * data pointer given at registration. + */ +static inline int ane_timeline_show(struct seq_file *m, void *v) +{ + struct drm_debugfs_entry *entry = m->private; + struct ane_stats_ring *ring = entry->file.data; + struct ane_stats_ring_entry *ring_slots = ring->slots; + u32 mask = ring->mask; + u64 head = atomic64_read(&ring->head); + u64 live = head < (u64)mask + 1ull ? head : (u64)mask + 1ull; + u64 i; + + seq_puts(m, + "# ane_timeline: seq submit_ns start_ns end_ns tasks rc tmst (tmst raw tick on ane.ko, 0 = unavailable on ane_t6021)\n"); + /* + * Newest first. Submission ticket t lives in slot (t - 1) & mask + * and prints once complete() commits seq = 2*t; anything else + * (odd in-flight seq, stale slot) is skipped. + */ + for (i = 0; i < live; i++) { + u64 ticket = head - i; + struct ane_stats_ring_entry *e = + &ring_slots[(size_t)(ticket - 1ull) & mask]; + u64 seq = atomic64_read_acquire(&e->seq); + u64 submit = atomic64_read(&e->submit_ns); + u64 st = atomic64_read(&e->start_ns); + u64 en = atomic64_read(&e->end_ns); + u32 tasks = atomic_read(&e->tasks); + u32 rc = atomic_read(&e->rc); + u64 tmst = atomic64_read(&e->tmst); + + if (seq != 2ull * ticket) + continue; /* in flight or stale; never printed */ + seq_printf(m, "%llu %llu %llu %llu %u %u %llu\n", + 2ull * ticket, submit, st, en, tasks, rc, tmst); + } + return 0; +} + +#define ANE_STATS_RING_ORDER_DEFAULT 8 /* 256 slots */ + +/* + * Accounting rule (coreglass producer contract): jobs counts completed + * submissions, one begin/complete pair per engine submission — one per + * ANE_SUBMIT on ane.ko (so libane ane_exec is 1 job and ane_exec_loop + * with N iterations is N jobs) and one per firmware PROCEDURE_CALL + * (CSNE_CMD_PROCEDURE_CALL) on ane_t6021.ko: that opcode is the only + * engine work on the shared ane_rtclient_command path. The control- + * plane exchanges that ride the same function — LOAD_PROGRAM, + * CREATE_PROCESS, CH_PROPERTY_WRITE, install-time CONFIG_GET — and the + * boot transport are not engine submissions and are not counted; jobs + * must match the number of engine calls the workload made (+-1 at the + * sampler boundary). A submission that completes with an error still + * completes its begin/complete pair, so the counter stays balanced. + * + * Typed sysfs formatter for the ane_stats attribute. The per-driver + * show callbacks fetch the counters from their real drvdata type + * (struct ane_device * on ane.ko, struct ane_rtclient * on + * ane_t6021.ko) and pass &...->stats_ctrs here. The formatter never + * sees the device pointer, so the drvdata type confusion that shipped + * in the first round (reading the head of ane_device as counters) + * cannot compile again: there is no cast to remove. + */ +/* + * Consistent counter snapshot across the tiny close/open transition: + * the transition sentinel is never accepted, and (inflight, busy_ns) + * must read back unchanged, so a value is only reported between + * transitions. The value is busy_ns plus the live tail of the + * still-open period, so it advances while engine work is in flight. + * Over the timeline the reported value is non-decreasing: folds only + * add, and at a close the live tail equals the fold. + */ +static inline u64 ane_stats_snapshot(const struct ane_stats_counters *ctrs) +{ + u64 raw, busy = 0, now, s = 0; + u32 inflight; + + for (;;) { + inflight = atomic_read_acquire(&ctrs->inflight); + if (inflight == ANE_STATS_INFLIGHT_TRANS) + continue; /* close/open in progress: spin it out */ + raw = atomic64_read(&ctrs->busy_ns); + if (inflight) + s = atomic64_read(&ctrs->last_busy_end); + now = ktime_get_ns(); + /* + * Recheck after the timestamp: a fold that landed before + * `now` changes busy_ns and retries; one that lands + * after is genuinely later than `now`, so the value is + * exact, never an overshoot. + */ + if (atomic64_read(&ctrs->busy_ns) != raw || + atomic_read(&ctrs->inflight) != inflight || + (inflight && + atomic64_read(&ctrs->last_busy_end) != s)) + continue; + busy = raw; + if (inflight && now > s) + busy += now - s; + break; + } + return busy; +} + +static inline ssize_t ane_stats_emit(char *buf, + const struct ane_stats_counters *ctrs) +{ + return sysfs_emit(buf, "busy_ns %llu\njobs %llu\n", + (unsigned long long)ane_stats_snapshot(ctrs), + (unsigned long long)atomic64_read(&ctrs->jobs)); +} + +#endif /* __ANE_STATS_H__ */ diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index 676029a9e7b27..18d0ecf6b2f6e 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -87,6 +87,7 @@ #include #include +#include #include #include #include @@ -95,6 +96,7 @@ #include #include +#include "ane_stats.h" #include "ane_t6021.h" #include "ane_t6021_boot.h" @@ -177,6 +179,17 @@ module_param(hello_wait_ms, uint, 0444); MODULE_PARM_DESC(hello_wait_ms, "RTKit HELLO wait in legacy mode; 0 (default) skips RTKit and leaves the mailbox stopped. A firmware that speaks RTKit needs 1000."); +/* + * Producer-side stats (ane_stats sysfs, ane_timeline debugfs), read + * once at probe. stats=0 keeps the hot path at its single predictable + * branch (the NULL stats_slots check) and no files are created. Same + * name and meaning as ane.ko's parameter. + */ +static bool stats = true; +module_param(stats, bool, 0444); +MODULE_PARM_DESC(stats, + "Expose ane_stats sysfs and ane_timeline debugfs (default 1; 0 = no files and the hot path skips the counters)"); + #define ANE_LEGACY_ALLOCS 8192 #define ANE_LEGACY_BYTES SZ_512M @@ -222,6 +235,15 @@ struct ane_rtclient { * which the firmware may reference forever (held until reboot). */ struct ane_legacy_buffer *cmd_buf; + + /* + * Producer-side stats (see ane_stats.h). stats=0 or a failed + * ring allocation leaves stats_slots NULL, which is the one + * hot-path gate: no files, no counter updates. + */ + struct ane_stats_counters stats_ctrs; + struct ane_stats_ring stats_ring; + struct ane_stats_ring_entry *stats_slots; }; /* Per-open BO ownership (drm_file->driver_priv). Handles live in the @@ -889,6 +911,8 @@ static int ane_rtclient_command(struct ane_rtclient *ane, unsigned int timeout_ms) { int ret; + u64 stats_ticket = 0; + u64 stats_submit_ns = 0; ane_t6021_tracing = opcode == CSNE_CMD_PROCEDURE_CALL && trace_td && ane->soc->trace_td_off; @@ -896,10 +920,38 @@ static int ane_rtclient_command(struct ane_rtclient *ane, ane_t6021_trace->calls++; ane_t6021_trace_add(ANE_TR_CALL, 0); } + /* Producer contract hot path (ane_stats.h): record submit at + * command enqueue, completion after the call returns, one + * begin/complete pair per engine submission. Only + * CSNE_CMD_PROCEDURE_CALL is engine work; the control-plane + * exchanges that ride this function (LOAD_PROGRAM, + * CREATE_PROCESS, CH_PROPERTY_WRITE, CONFIG_GET) are not + * counted, so jobs matches the engine calls the workload made. + * The T6021 path can run concurrently (MBI per-channel rings), + * so overlapping calls share a busy period and busy_ns is the + * union of the submit-to-completion windows. tmst is 0 (no + * host TM on T6021; documented in the file header line). + * tasks = 1 (one call per submission); rc = ret. The gate is the + * ring, as on ane.ko: stats=0 or a failed probe allocation leaves + * stats_slots NULL, and the hooks must not run on a NULL ring. + */ + bool stats_call = ane->stats_slots && + opcode == CSNE_CMD_PROCEDURE_CALL; + + if (stats_call) { + stats_submit_ns = ktime_get_ns(); + stats_ticket = ane_stats_begin(&ane->stats_ctrs, + &ane->stats_ring, + stats_submit_ns, 1); + } ret = ane_rtclient_legacy_exchange(ane, command, length, opcode, channel, timeout_ms); if (ret) { ane_t6021_tracing = false; + if (stats_call) + ane_stats_complete(&ane->stats_ctrs, + &ane->stats_ring, stats_ticket, + ktime_get_ns(), (u32)ret, 0); dev_info(ane->dev, "EXCH op=%#x failed %d (fw allocs %u, %zu bytes)\n", opcode, ret, ane->legacy_allocated, ane->legacy_bytes); atomic_set(&ane_t6021_quarantined, 1); @@ -913,12 +965,21 @@ static int ane_rtclient_command(struct ane_rtclient *ane, if (!ret && call_settle_us) usleep_range(call_settle_us, call_settle_us + 100); if (ret) { + if (stats_call) + ane_stats_complete(&ane->stats_ctrs, + &ane->stats_ring, + stats_ticket, + ktime_get_ns(), + (u32)ret, 0); dev_info(ane->dev, "call completion wait failed %d\n", ret); atomic_set(&ane_t6021_quarantined, 1); return ret; } } + if (stats_call) + ane_stats_complete(&ane->stats_ctrs, &ane->stats_ring, + stats_ticket, ktime_get_ns(), 0, 0); /* The fw talks back on the target-to-host rings (fwlog, perf); * hand those slots back so the rings never fill (the sequencer * did this per step; same ack, channels 4 and 6). @@ -2304,6 +2365,25 @@ static int ane_rtclient_probe(struct platform_device *pdev) return -EPROTO; } + /* Producer-side stats: preallocate the ring at probe; the files + * and the hot-path branch key off stats_slots. + */ + if (stats) { + ane->stats_slots = devm_kcalloc(dev, + 1u << ANE_STATS_RING_ORDER_DEFAULT, + sizeof(*ane->stats_slots), + GFP_KERNEL); + if (ane->stats_slots) { + ane_stats_counters_init(&ane->stats_ctrs, + &ane->stats_ring, + ANE_STATS_RING_ORDER_DEFAULT); + ane->stats_ring.slots = ane->stats_slots; + } else { + dev_warn(dev, + "ane_stats ring allocation failed; stats disabled\n"); + } + } + { struct ane_t6021_drm *adrm; int drmret; @@ -2320,6 +2400,10 @@ static int ane_rtclient_probe(struct platform_device *pdev) } adrm->dev = dev; adrm->ane = ane; + if (ane->stats_slots) + drm_debugfs_add_file(&adrm->drm, "ane_timeline", + ane_timeline_show, + &ane->stats_ring); WRITE_ONCE(ane_t6021_perf_ane, ane); drmret = drm_dev_register(&adrm->drm, 0); if (drmret) { @@ -2372,10 +2456,51 @@ static const struct of_device_id ane_rtclient_of_match[] = { }; MODULE_DEVICE_TABLE(of, ane_rtclient_of_match); +/* + * ane_stats: cumulative busy_ns/jobs for this device (mode 0444, no + * root needed). Formatting lives in ane_stats_emit() (ane_stats.h), + * shared with ane.ko. + */ +static ssize_t ane_stats_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct ane_rtclient *ane = dev_get_drvdata(dev); + + return ane_stats_emit(buf, &ane->stats_ctrs); +} +static DEVICE_ATTR_RO(ane_stats); + +static struct attribute *ane_t6021_stats_attrs[] = { + &dev_attr_ane_stats.attr, + NULL, +}; + +/* ane_stats appears only when stats=1 gave the device a ring. */ +static umode_t ane_t6021_stats_is_visible(struct kobject *kobj, + struct attribute *attr, int n) +{ + struct ane_rtclient *ane = dev_get_drvdata(kobj_to_dev(kobj)); + + if (attr == &dev_attr_ane_stats.attr && !ane->stats_slots) + return 0; + return attr->mode; +} + +static const struct attribute_group ane_t6021_stats_group = { + .attrs = ane_t6021_stats_attrs, + .is_visible = ane_t6021_stats_is_visible, +}; + +static const struct attribute_group *ane_t6021_stats_groups[] = { + &ane_t6021_stats_group, + NULL, +}; + static struct platform_driver ane_rtclient_driver = { .driver = { .name = "ane_t6021", .of_match_table = ane_rtclient_of_match, + .dev_groups = ane_t6021_stats_groups, .suppress_bind_attrs = true, }, .probe = ane_rtclient_probe, diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index 9364ae1469b9d..7a0ade69c395b 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -216,6 +216,13 @@ static void ane_tm_push_tq(struct ane_device *ane, struct ane_request *req) tm_write32(ane, TM_PUSH, TQ_PRTY_TABLE[qid] | (qid & 7) << 8); // magic } +/* + * Last raw TM tick read from TM_IRQ_TMST in the latest event drain. + * Diagnostic only (unit unknown; the timeline file labels it as a + * raw tick); unsynchronized by design. + */ +u32 ane_last_tmst; + static int ane_tm_collect_events(struct ane_device *ane, struct ane_request *req, u32 *finished) { @@ -228,7 +235,7 @@ static int ane_tm_collect_events(struct ane_device *ane, u32 info = tm_read32(ane, TM_IRQ_INFO(line)); tm_read32(ane, TM_IRQ_UNK1(line)); - tm_read32(ane, TM_IRQ_TMST(line)); + ane_last_tmst = tm_read32(ane, TM_IRQ_TMST(line)); tm_read32(ane, TM_IRQ_UNK2(line)); if (req && info == (0x05000000 | (req->nid << 16) | (req->td_count - 1))) diff --git a/drivers/accel/ane/ane_tm.h b/drivers/accel/ane/ane_tm.h index 94d425ab8d8b7..84520c149bd52 100644 --- a/drivers/accel/ane/ane_tm.h +++ b/drivers/accel/ane/ane_tm.h @@ -17,4 +17,7 @@ int ane_tm_recover(struct ane_device *ane); #define ANE_PS_ALL_ON ((1U << (4 * 6)) - 1) u32 ane_tm_ps_act(struct ane_device *ane); +/* Last raw TM tick captured by ane_tm_collect_events (diagnostic). */ +extern u32 ane_last_tmst; + #endif /* __ANE_TM_H__ */ From 59823d3a237ff755b5afe300308f99062865b46b Mon Sep 17 00:00:00 2001 From: Chris Kearney Date: Fri, 2 Oct 2026 14:15:46 -0700 Subject: [PATCH 18/26] arm64: dts: apple: t600x: drop the ANE set5 power state The die 0 ANE power states that came with the ANE support in Joshua Warren's aurora-silicon/linux#155 include ps_ane_set5 at 0xc030, but the comment above them puts the end of the ANE's pmgr range at 0xc02c. The ane node does not use it either: it lists set1 to set4, and the driver takes its power domains from that list. The node was still live on every M1 Pro, Max and Ultra. The pmgr driver probes each enabled power-controller: it reads the register, sets the auto-PM enable bit if the state is active, and genpd turns unused domains off late in boot. Linux should not do any of that to a register outside the block it describes. Drop the node, and say in the comment why there is no set5. Found in a review of #155. Signed-off-by: Chris Kearney Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FwdG63dRaMrRbYrUBkSa1i (cherry picked from commit 7280b1168af21b04adde3a38ae8fa07a1ab54f84) --- arch/arm64/boot/dts/apple/t600x-pmgr.dtsi | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi b/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi index fed2d79a8ba8a..a1c8748ee7cf9 100644 --- a/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi @@ -678,8 +678,8 @@ #if DIE_NO == 0 /* - * Only the die 0 ANE is described. The ane node leaves set5 out: - * it lies past the end of the ADT ANE pmgr range (0xc02c). + * Only the die 0 ANE is described. Its pmgr range ends at 0xc02c, + * with set4, so no set5 is described at 0xc030. */ DIE_NODE(ps_ane_set0): power-controller@c000 { compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; @@ -734,15 +734,6 @@ label = DIE_LABEL(ane_set4); power-domains = <&DIE_NODE(ps_ane_base)>; }; - - DIE_NODE(ps_ane_set5): power-controller@c030 { - compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; - reg = <0xc030 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = DIE_LABEL(ane_set5); - power-domains = <&DIE_NODE(ps_ane_base)>; - }; #endif }; From cf7a8977cf82e314ee4e1dba9dae9b7c79ba78c7 Mon Sep 17 00:00:00 2001 From: Chris Kearney Date: Fri, 2 Oct 2026 14:24:57 -0700 Subject: [PATCH 19/26] arm64: dts: apple: enable the ANE only on the M1 Max and M2 Max The ANE support from Joshua Warren's aurora-silicon/linux#155 enables the ANE on every chip that describes it except the M2 (T8112): the M1 (T8103) directly, and every M1 Pro/Max/Ultra (T6000/T6001/T6002) and M2 Pro/Max/Ultra (T6020/T6021/T6022) through the shared die 0 files. The driver has run on the M1 Max (T6001) and the M2 Max (T6021) only, and these device tree nodes have not booted on any machine yet. On an untested chip that means the ANE's DARTs, mailbox and power states probe and touch the hardware on every boot, and the driver binds, which on the M2 family starts the ANE firmware by default. Make the ANE node, its DARTs and mailbox, and the power states added for it default to disabled where they are described, and enable them per SoC: - t6001.dtsi enables them on the M1 Max: MacBook Pro j314c and j316c, and Mac Studio j375c. - t6021.dtsi enables them on the M2 Max: MacBook Pro j414c and j416c, and Mac Studio j475c. - t6000.dtsi and t6020.dtsi include those files, so they define APPLE_ANE_UNTESTED first and the M1 Pro and M2 Pro stay off. - t6002 and t6022 (Ultra) build die 0 from the shared files and never see an enable, so they stay off. - t8103.dtsi gets the same enable block behind a one-line APPLE_ANE_UNTESTED define, so enabling the M1 ANE after a supervised boot is a one-line deletion. Power states that predate #155 (ane_sys and ane_sys_cpu on t600x and t8103, and the ANE states in t602x-pmgr.dtsi) keep their status. Where the ANE stays off, each device tree is the pre-#155 one plus disabled nodes, apart from the inert ane-alias-iova reserved-memory entry on t602x, which has no reg or size and is only read through the ANE's memory-region. On the M1 Max and M2 Max the device tree is unchanged, except that the t600x ANE power states now carry an explicit status = "okay". Found in a review of #155. Signed-off-by: Chris Kearney Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FwdG63dRaMrRbYrUBkSa1i (cherry picked from commit ecf86ec16ece1313dd16e135779bf7d93469f16f) --- arch/arm64/boot/dts/apple/t6000.dtsi | 3 ++ arch/arm64/boot/dts/apple/t6001.dtsi | 47 +++++++++++++++++++ arch/arm64/boot/dts/apple/t600x-die0.dtsi | 8 ++-- arch/arm64/boot/dts/apple/t600x-pmgr.dtsi | 10 +++- arch/arm64/boot/dts/apple/t6020.dtsi | 3 ++ arch/arm64/boot/dts/apple/t6021.dtsi | 27 +++++++++++ arch/arm64/boot/dts/apple/t602x-die0.dtsi | 10 ++-- arch/arm64/boot/dts/apple/t8103-pmgr.dtsi | 6 +++ arch/arm64/boot/dts/apple/t8103.dtsi | 57 +++++++++++++++++++++-- 9 files changed, 157 insertions(+), 14 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6000.dtsi b/arch/arm64/boot/dts/apple/t6000.dtsi index db7ea6eac5a6f..22cb23931e0b3 100644 --- a/arch/arm64/boot/dts/apple/t6000.dtsi +++ b/arch/arm64/boot/dts/apple/t6000.dtsi @@ -11,6 +11,9 @@ #define GPU_REPEAT(x) +/* The ANE has only run on the M1 Max so far: leave it off on the M1 Pro */ +#define APPLE_ANE_UNTESTED + #include "t6001.dtsi" / { diff --git a/arch/arm64/boot/dts/apple/t6001.dtsi b/arch/arm64/boot/dts/apple/t6001.dtsi index dc2d9f14fb060..f044ff6980c1b 100644 --- a/arch/arm64/boot/dts/apple/t6001.dtsi +++ b/arch/arm64/boot/dts/apple/t6001.dtsi @@ -88,3 +88,50 @@ &gpu { compatible = "apple,agx-t6001", "apple,agx-g13c", "apple,agx-g13s"; }; + +/* + * The ANE has run on the M1 Max, so enable it here with its DARTs and the + * power states only it uses. t6000.dtsi defines APPLE_ANE_UNTESTED before + * including this file: the ANE has not run on the M1 Pro yet. + */ +#ifndef APPLE_ANE_UNTESTED +&ane { + status = "okay"; +}; + +&ane_dart0 { + status = "okay"; +}; + +&ane_dart1 { + status = "okay"; +}; + +&ane_dart2 { + status = "okay"; +}; + +&ps_ane_base { + status = "okay"; +}; + +&ps_ane_set0 { + status = "okay"; +}; + +&ps_ane_set1 { + status = "okay"; +}; + +&ps_ane_set2 { + status = "okay"; +}; + +&ps_ane_set3 { + status = "okay"; +}; + +&ps_ane_set4 { + status = "okay"; +}; +#endif diff --git a/arch/arm64/boot/dts/apple/t600x-die0.dtsi b/arch/arm64/boot/dts/apple/t600x-die0.dtsi index 5a4641fa26c59..67bd1530ffe94 100644 --- a/arch/arm64/boot/dts/apple/t600x-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t600x-die0.dtsi @@ -14,7 +14,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_sys>; - status = "okay"; + status = "disabled"; }; ane_dart1: iommu@285810000 { @@ -24,7 +24,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_sys_cpu>; - status = "okay"; + status = "disabled"; }; ane_dart2: iommu@285820000 { @@ -34,7 +34,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_sys_cpu>; - status = "okay"; + status = "disabled"; }; ane: ane@285c04000 { @@ -47,7 +47,7 @@ iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; power-domains = <&ps_ane_sys_cpu>, <&ps_ane_set1>, <&ps_ane_set2>, <&ps_ane_set3>, <&ps_ane_set4>; - status = "okay"; + status = "disabled"; }; nco: clock-controller@28e03c000 { diff --git a/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi b/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi index a1c8748ee7cf9..77469a62242a6 100644 --- a/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t600x-pmgr.dtsi @@ -679,7 +679,9 @@ #if DIE_NO == 0 /* * Only the die 0 ANE is described. Its pmgr range ends at 0xc02c, - * with set4, so no set5 is described at 0xc030. + * with set4, so no set5 is described at 0xc030. These states serve + * only the ANE and are disabled with it; the SoC file that enables + * the ANE enables them too. */ DIE_NODE(ps_ane_set0): power-controller@c000 { compatible = "apple,t6000-pmgr-pwrstate", "apple,pmgr-pwrstate"; @@ -688,6 +690,7 @@ #reset-cells = <0>; label = DIE_LABEL(ane_set0); power-domains = <&DIE_NODE(ps_ane_sys_cpu)>; + status = "disabled"; }; DIE_NODE(ps_ane_base): power-controller@c008 { @@ -697,6 +700,7 @@ #reset-cells = <0>; label = DIE_LABEL(ane_base); power-domains = <&DIE_NODE(ps_ane_set0)>; + status = "disabled"; }; DIE_NODE(ps_ane_set1): power-controller@c010 { @@ -706,6 +710,7 @@ #reset-cells = <0>; label = DIE_LABEL(ane_set1); power-domains = <&DIE_NODE(ps_ane_base)>; + status = "disabled"; }; DIE_NODE(ps_ane_set2): power-controller@c018 { @@ -715,6 +720,7 @@ #reset-cells = <0>; label = DIE_LABEL(ane_set2); power-domains = <&DIE_NODE(ps_ane_base)>; + status = "disabled"; }; DIE_NODE(ps_ane_set3): power-controller@c020 { @@ -724,6 +730,7 @@ #reset-cells = <0>; label = DIE_LABEL(ane_set3); power-domains = <&DIE_NODE(ps_ane_base)>; + status = "disabled"; }; DIE_NODE(ps_ane_set4): power-controller@c028 { @@ -733,6 +740,7 @@ #reset-cells = <0>; label = DIE_LABEL(ane_set4); power-domains = <&DIE_NODE(ps_ane_base)>; + status = "disabled"; }; #endif }; diff --git a/arch/arm64/boot/dts/apple/t6020.dtsi b/arch/arm64/boot/dts/apple/t6020.dtsi index e9af24b25ab68..0fa3630e2849d 100644 --- a/arch/arm64/boot/dts/apple/t6020.dtsi +++ b/arch/arm64/boot/dts/apple/t6020.dtsi @@ -11,6 +11,9 @@ #define GPU_REPEAT(x) +/* The ANE has only run on the M2 Max so far: leave it off on the M2 Pro */ +#define APPLE_ANE_UNTESTED + #include "t6021.dtsi" / { diff --git a/arch/arm64/boot/dts/apple/t6021.dtsi b/arch/arm64/boot/dts/apple/t6021.dtsi index 889728010c84d..11521dc6091a6 100644 --- a/arch/arm64/boot/dts/apple/t6021.dtsi +++ b/arch/arm64/boot/dts/apple/t6021.dtsi @@ -85,3 +85,30 @@ apple,ppm-filter-time-constant-ms = <34>; apple,ppm-ki = <18.0>; }; + +/* + * The ANE has run on the M2 Max, so enable it here with its mailbox and + * DARTs. t6020.dtsi defines APPLE_ANE_UNTESTED before including this + * file: the ANE has not run on the M2 Pro yet. + */ +#ifndef APPLE_ANE_UNTESTED +&ane { + status = "okay"; +}; + +&ane_dart0 { + status = "okay"; +}; + +&ane_dart1 { + status = "okay"; +}; + +&ane_dart2 { + status = "okay"; +}; + +&ane_mbox { + status = "okay"; +}; +#endif diff --git a/arch/arm64/boot/dts/apple/t602x-die0.dtsi b/arch/arm64/boot/dts/apple/t602x-die0.dtsi index a465b6f44fb2f..91a1e3c6958f5 100644 --- a/arch/arm64/boot/dts/apple/t602x-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t602x-die0.dtsi @@ -13,7 +13,7 @@ interrupts = ; interrupt-names = "recv-not-empty"; #mbox-cells = <0>; - status = "okay"; + status = "disabled"; }; ane_dart0: iommu@285800000 { @@ -23,7 +23,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_pmp>; - status = "okay"; + status = "disabled"; }; ane_dart1: iommu@285810000 { @@ -33,7 +33,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_cpu>; - status = "okay"; + status = "disabled"; }; ane_dart2: iommu@285820000 { @@ -43,7 +43,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_cpu>; - status = "okay"; + status = "disabled"; }; ane: ane@284000000 { @@ -62,7 +62,7 @@ resets = <&ps_ane_cpu>; mboxes = <&ane_mbox>; memory-region = <&ane_alias_iova>; - status = "okay"; + status = "disabled"; }; nco: clock-controller@28e03c000 { diff --git a/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi index 252c6914d690d..c3230cd4bb81a 100644 --- a/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi @@ -1010,6 +1010,7 @@ #reset-cells = <0>; label = "ane_base"; power-domains = <&ps_ane_sys_cpu>; + status = "disabled"; }; ps_ane_set1: power-controller@c010 { @@ -1019,6 +1020,7 @@ #reset-cells = <0>; label = "ane_set1"; power-domains = <&ps_ane_base>; + status = "disabled"; }; ps_ane_set2: power-controller@c018 { @@ -1028,6 +1030,7 @@ #reset-cells = <0>; label = "ane_set2"; power-domains = <&ps_ane_base>; + status = "disabled"; }; ps_ane_set3: power-controller@c020 { @@ -1037,6 +1040,7 @@ #reset-cells = <0>; label = "ane_set3"; power-domains = <&ps_ane_base>; + status = "disabled"; }; ps_ane_set4: power-controller@c028 { @@ -1046,6 +1050,7 @@ #reset-cells = <0>; label = "ane_set4"; power-domains = <&ps_ane_base>; + status = "disabled"; }; ps_ane_set5: power-controller@c030 { @@ -1055,6 +1060,7 @@ #reset-cells = <0>; label = "ane_set5"; power-domains = <&ps_ane_base>; + status = "disabled"; }; ps_disp0_cpu0: power-controller@10018 { diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 16ac8bb5e206d..3ad699a0321c6 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -1453,7 +1453,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_sys>; - status = "okay"; + status = "disabled"; }; ane_dart1: iommu@26b810000 { @@ -1464,7 +1464,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_sys>; - status = "okay"; + status = "disabled"; }; ane_dart2: iommu@26b820000 { @@ -1475,7 +1475,7 @@ interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_ane_sys>; - status = "okay"; + status = "disabled"; }; ane: ane@26bc04000 { @@ -1488,7 +1488,7 @@ iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; power-domains = <&ps_ane_set1>, <&ps_ane_set2>, <&ps_ane_set3>, <&ps_ane_set4>, <&ps_ane_set5>; - status = "okay"; + status = "disabled"; }; dispext0_dart: iommu@271304000 { @@ -2173,3 +2173,52 @@ }; #include "t8103-pmgr.dtsi" + +/* + * The ANE has not run on the M1 yet, so it stays off together with its + * DARTs and the power states only it uses. Drop this define to enable + * them once it has. + */ +#define APPLE_ANE_UNTESTED + +#ifndef APPLE_ANE_UNTESTED +&ane { + status = "okay"; +}; + +&ane_dart0 { + status = "okay"; +}; + +&ane_dart1 { + status = "okay"; +}; + +&ane_dart2 { + status = "okay"; +}; + +&ps_ane_base { + status = "okay"; +}; + +&ps_ane_set1 { + status = "okay"; +}; + +&ps_ane_set2 { + status = "okay"; +}; + +&ps_ane_set3 { + status = "okay"; +}; + +&ps_ane_set4 { + status = "okay"; +}; + +&ps_ane_set5 { + status = "okay"; +}; +#endif From 679d8202f46c6dec740cb0a6532a2701d4947df6 Mon Sep 17 00:00:00 2001 From: Chris Kearney Date: Fri, 2 Oct 2026 14:24:57 -0700 Subject: [PATCH 20/26] arm64: dts: apple: t8112: disable the ANE power states with the ANE Joshua Warren's aurora-silicon/linux#155 adds the M2 (T8112) ANE with its node, mailbox and DARTs disabled, since it has not run there. The seven power states added for it (ane_sys_cpu, ane_td, ane_base and ane_set1 to ane_set4) have no status, though, so they are live on every boot of an M2 MacBook Air, 13" MacBook Pro or Mac mini. The pmgr driver probes each of them: it reads the register, sets the auto-PM enable bit if the state is active, and genpd turns unused domains off late in boot. Nothing consumes them while the ANE is disabled. Disable them as well, so the ANE and everything only it uses are off together, and say so above them. ane_sys predates #155 and keeps its status. Found in a review of #155. Signed-off-by: Chris Kearney Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FwdG63dRaMrRbYrUBkSa1i (cherry picked from commit 72c7bd0c7a03d768daf7774e9481d9024825434c) --- arch/arm64/boot/dts/apple/t8112-pmgr.dtsi | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi index 0e8df1cfa21f6..26ab30e219f12 100644 --- a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi @@ -1132,6 +1132,10 @@ power-domains = <&ps_venc_pipe5>, <&ps_venc_pipe4>; }; + /* + * These states serve only the ANE. They stay disabled with the ane + * node in t8112.dtsi; enable them together with it. + */ ps_ane_sys_cpu: power-controller@c008 { compatible = "apple,t8112-pmgr-pwrstate", "apple,pmgr-pwrstate"; reg = <0xc008 4>; @@ -1139,6 +1143,7 @@ #reset-cells = <0>; label = "ane_sys_cpu"; power-domains = <&ps_ane_sys>; + status = "disabled"; }; ps_ane_td: power-controller@c010 { @@ -1148,6 +1153,7 @@ #reset-cells = <0>; label = "ane_td"; power-domains = <&ps_ane_sys_cpu>; + status = "disabled"; }; ps_ane_base: power-controller@c018 { @@ -1157,6 +1163,7 @@ #reset-cells = <0>; label = "ane_base"; power-domains = <&ps_ane_td>; + status = "disabled"; }; ps_ane_set1: power-controller@c020 { @@ -1166,6 +1173,7 @@ #reset-cells = <0>; label = "ane_set1"; power-domains = <&ps_ane_base>; + status = "disabled"; }; ps_ane_set2: power-controller@c028 { @@ -1175,6 +1183,7 @@ #reset-cells = <0>; label = "ane_set2"; power-domains = <&ps_ane_set1>; + status = "disabled"; }; ps_ane_set3: power-controller@c030 { @@ -1184,6 +1193,7 @@ #reset-cells = <0>; label = "ane_set3"; power-domains = <&ps_ane_set2>; + status = "disabled"; }; ps_ane_set4: power-controller@c038 { @@ -1193,6 +1203,7 @@ #reset-cells = <0>; label = "ane_set4"; power-domains = <&ps_ane_set3>; + status = "disabled"; }; ps_disp0_cpu0: power-controller@10000 { From e987e572635a05adab3d127442527a235430d896 Mon Sep 17 00:00:00 2001 From: Chris Kearney Date: Fri, 2 Oct 2026 14:24:57 -0700 Subject: [PATCH 21/26] accel/ane: t6021: stop logging boot progress at emergency level The M2 ANE module from Joshua Warren's aurora-silicon/linux#155 logs its probe and firmware boot progress with dev_emerg(). These lines came from bring-up, where each one had to reach the console before the write it announced. With fw_start on by default, an M2 Max now prints about twenty emergency-level lines on every boot, which go to every console and terminal regardless of loglevel and bury real emergencies. Use the level each message deserves: - the per-phase BOOT-PHASE markers and the probe register readouts (ane_cpu ACTUAL, PWGATE, the engine reads, staging and dispatch, the legacy ack and hello start) become dev_dbg(); dynamic debug still gets them for crash attribution; - the outcome lines (sequence returned, done without a CPU start, the legacy hello result) become dev_info(); - the SCRATCH/RVBAR/tick dump, printed only when the ANE CPU was released but never reported READY, becomes dev_err(). The 30 ms drain after each phase marker is left as it is, and the comment above it now says how to see the marker. No other drivers/accel/ane code logs at emergency, alert or critical level. Found in a review of #155. Signed-off-by: Chris Kearney Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FwdG63dRaMrRbYrUBkSa1i (cherry picked from commit d7ec38757843b95b2414d385965358d615647f01) --- drivers/accel/ane/ane_t6021_boot.c | 43 +++++++++---------- drivers/accel/ane/ane_t6021_rtclient_main.c | 46 ++++++++++----------- 2 files changed, 45 insertions(+), 44 deletions(-) diff --git a/drivers/accel/ane/ane_t6021_boot.c b/drivers/accel/ane/ane_t6021_boot.c index de11bb8f095fa..1ae368ae3e55f 100644 --- a/drivers/accel/ane/ane_t6021_boot.c +++ b/drivers/accel/ane/ane_t6021_boot.c @@ -334,14 +334,15 @@ static void ane_boot_phase(void *ctx, const char *what) { struct ane_t6021_boot_mmio *mm = ctx; - /* bounded phase marker: one line per block boundary, survives - * netconsole for crash attribution (never per-poll). KERN_EMERG - * + a short drain so the line reaches tty0/netconsole/ssh - * BEFORE the risky write it announces (fw-start-debug - * 2026-09-22: fwstart#2 died with zero capture — the marker - * must beat the write). + /* bounded phase marker: one line per block boundary (never + * per-poll), for crash attribution. It is a debug message: turn + * it on with dynamic debug, and raise the console loglevel to + * see it there. The short drain lets the line reach + * tty0/netconsole/ssh BEFORE the risky write it announces + * (fw-start-debug 2026-09-22: fwstart#2 died with zero capture — + * the marker must beat the write). */ - dev_emerg(mm->ane->dev, "BOOT-PHASE %s\n", what); + dev_dbg(mm->ane->dev, "BOOT-PHASE %s\n", what); msleep(30); } @@ -457,14 +458,14 @@ static void ane_t6021_boot_progress_dump(struct ane_t6021 *ane) tick1 = readl(eng + ANE_T6021_BOOT_REG_TICK); for (i = 0; i < 8; i++) - dev_emerg(ane->dev, "PROGRESS SCRATCH%u=%08x\n", i, - readl(eng + ANE_T6021_BOOT_REG_SCRATCH0 + 4 * i)); - dev_emerg(ane->dev, - "PROGRESS rvbar=%016llx cpu_status=%08x tick %08x->%08x (%s)\n", - readq(eng + ANE_ASC_RVBAR), - readl(eng + ANE_ASC_CPU_STATUS), - tick0, tick1, - tick1 != tick0 ? "24MHz domain clocked" : "tick STATIC"); + dev_err(ane->dev, "PROGRESS SCRATCH%u=%08x\n", i, + readl(eng + ANE_T6021_BOOT_REG_SCRATCH0 + 4 * i)); + dev_err(ane->dev, + "PROGRESS rvbar=%016llx cpu_status=%08x tick %08x->%08x (%s)\n", + readq(eng + ANE_ASC_RVBAR), + readl(eng + ANE_ASC_CPU_STATUS), + tick0, tick1, + tick1 != tick0 ? "24MHz domain clocked" : "tick STATIC"); } int ane_t6021_boot_start(struct ane_t6021 *ane, int stop_after, int table_mode, int rtb_mode) @@ -501,9 +502,9 @@ int ane_t6021_boot_start(struct ane_t6021 *ane, int stop_after, int table_mode, return -EBUSY; } - dev_emerg(ane->dev, - "BOOT-PHASE dispatch (stop_after=%d%s)\n", stop_after, - stop_after ? " BISECT STOP ARMED" : ""); + dev_dbg(ane->dev, + "BOOT-PHASE dispatch (stop_after=%d%s)\n", stop_after, + stop_after ? " BISECT STOP ARMED" : ""); r = ane_t6021_boot_run(&io, &cfg, &cs, &fa, &bo, &sres); @@ -523,9 +524,9 @@ int ane_t6021_boot_start(struct ane_t6021 *ane, int stop_after, int table_mode, if (!cs) { /* no CPU start: full release path, normal ownership */ module_put(THIS_MODULE); - dev_emerg(ane->dev, - "BOOT-PHASE done r=%d cpu_started=0 (no CPU release: state clean, module unpinned)\n", - r); + dev_info(ane->dev, + "BOOT-PHASE done r=%d cpu_started=0 (no CPU release: state clean, module unpinned)\n", + r); return r; } diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index 18d0ecf6b2f6e..f9eb131a4f30e 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -1996,7 +1996,7 @@ static int ane_rtclient_attach_genpd(struct ane_rtclient *ane) pd->count = i + 1; } - dev_emerg(dev, "BOOT-PHASE genpd domains attached: %d\n", count); + dev_dbg(dev, "BOOT-PHASE genpd domains attached: %d\n", count); out: mutex_unlock(&ane_rtclient_pd_lock); return err; @@ -2085,7 +2085,7 @@ static int ane_rtclient_probe(struct platform_device *pdev) "pmgr window map failed; G1 gate cannot run\n"); } ps_cpu = readl(ane->pmgr + ane->soc->ps_cpu_off); - dev_emerg(dev, "ane_cpu ACTUAL = 0x%x\n", ps_cpu); + dev_dbg(dev, "ane_cpu ACTUAL = 0x%x\n", ps_cpu); if (FIELD_GET(ANE_PS_ACTUAL, ps_cpu) != ANE_PS_ON) { pm_runtime_put_sync_suspend(dev); pm_runtime_disable(dev); @@ -2100,7 +2100,7 @@ static int ane_rtclient_probe(struct platform_device *pdev) u32 gate = IS_ERR(set) ? U32_MAX : readl(set + ane->soc->pwgate_off); - dev_emerg(dev, "PWGATE = 0x%x\n", gate); + dev_dbg(dev, "PWGATE = 0x%x\n", gate); if (gate & GENMASK(29, 28)) { pm_runtime_put_sync_suspend(dev); pm_runtime_disable(dev); @@ -2111,9 +2111,9 @@ static int ane_rtclient_probe(struct platform_device *pdev) cpu_status = readl(ane->engine + ANE_ASC_CPU_STATUS); rvbar = readq(ane->engine + ANE_ASC_RVBAR); - dev_emerg(dev, - "BOOT-PHASE engine reads ok: CPU_STATUS = 0x%x, RVBAR = %016llx (bit0=%u)\n", - cpu_status, rvbar, (u32)(rvbar & 1)); + dev_dbg(dev, + "BOOT-PHASE engine reads ok: CPU_STATUS = 0x%x, RVBAR = %016llx (bit0=%u)\n", + cpu_status, rvbar, (u32)(rvbar & 1)); if (!(cpu_status & ANE_ASC_CPU_STATUS_RUNNING)) { if (!fw_start) { @@ -2155,7 +2155,7 @@ static int ane_rtclient_probe(struct platform_device *pdev) a->power_gated = true; ane->fw = a; - dev_emerg(dev, "BOOT-PHASE fwload stage+alias begin\n"); + dev_dbg(dev, "BOOT-PHASE fwload stage+alias begin\n"); ret = ane_t6021_fwload_probe(a); if (ret) { dev_err_probe(dev, ret, "fw_start: staging failed\n"); @@ -2175,8 +2175,8 @@ static int ane_rtclient_probe(struct platform_device *pdev) return -EINVAL; } - dev_emerg(dev, "BOOT-PHASE dispatch (table_mode=%d)\n", - fw_start_table_mode); + dev_dbg(dev, "BOOT-PHASE dispatch (table_mode=%d)\n", + fw_start_table_mode); ret = ane_t6021_boot_start(a, 0, fw_start_table_mode, fw_start_rtb_mode); if (ret == -ENODATA || ret == -EAGAIN || @@ -2190,10 +2190,10 @@ static int ane_rtclient_probe(struct platform_device *pdev) ane->held = true; cpu_status = readl(ane->engine + ANE_ASC_CPU_STATUS); - dev_emerg(dev, - "BOOT-PHASE sequence returned %pe (cpu_started=%u fw_alive=%u booted=%u) CPU_STATUS=0x%x\n", - ERR_PTR(ret), a->cpu_started, a->fw_alive, a->booted, - cpu_status); + dev_info(dev, + "BOOT-PHASE sequence returned %pe (cpu_started=%u fw_alive=%u booted=%u) CPU_STATUS=0x%x\n", + ERR_PTR(ret), a->cpu_started, a->fw_alive, a->booted, + cpu_status); if (!a->fw_alive && !fw_start_rtb_mode) { dev_err(dev, "fw_start: poll A timeout, no READY — HELD until reboot, RTKit handshake skipped\n"); @@ -2213,9 +2213,9 @@ static int ane_rtclient_probe(struct platform_device *pdev) int hello_ret = 0; dma_wmb(); - dev_emerg(dev, - "LEGACY P8 host ack: SCRATCH3 <- %08x\n", - ANE_T6021_BOOT_ACK); + dev_dbg(dev, + "LEGACY P8 host ack: SCRATCH3 <- %08x\n", + ANE_T6021_BOOT_ACK); /* hello_wait_ms > 0 only: init rtkit and arm the RX * poll worker BEFORE writing the ack, so a HELLO * after the ack is not missed. The 13.5 fw sent none @@ -2241,17 +2241,17 @@ static int ane_rtclient_probe(struct platform_device *pdev) unsigned long hello_deadline = jiffies + msecs_to_jiffies(hello_wait_ms); - dev_emerg(dev, "LEGACY hello: boot begin (%u ms)\n", - hello_wait_ms); + dev_dbg(dev, "LEGACY hello: boot begin (%u ms)\n", + hello_wait_ms); do { hello_ret = apple_rtkit_boot(ane->rtk); } while (hello_ret == -ETIME && time_before(jiffies, hello_deadline)); - dev_emerg(dev, - "LEGACY hello: boot %pe running=%d crashed=%d\n", - ERR_PTR(hello_ret), - apple_rtkit_is_running(ane->rtk), - apple_rtkit_is_crashed(ane->rtk)); + dev_info(dev, + "LEGACY hello: boot %pe running=%d crashed=%d\n", + ERR_PTR(hello_ret), + apple_rtkit_is_running(ane->rtk), + apple_rtkit_is_crashed(ane->rtk)); if (!hello_ret) { ane->boot_done = true; if (start_app_eps) From 4e315c497273216da8e6e6c6fa122a2ac8e1b77b Mon Sep 17 00:00:00 2001 From: Chris Kearney Date: Fri, 2 Oct 2026 14:24:57 -0700 Subject: [PATCH 22/26] accel/ane: t6021: keep one MODULE_LICENSE and MODULE_DESCRIPTION ane_t6021.ko is built from ane_t6021_rtclient_main.o, ane_t6021_fwload.o and ane_t6021_boot.o, and each of the three carries its own MODULE_LICENSE() and MODULE_DESCRIPTION(), so modinfo reports three licenses and three descriptions for the one module. The comment on the extra copies says the objects also link into an ane_t6021_rtclient.ko, but the Makefile from Joshua Warren's aurora-silicon/linux#155 builds no such module. Keep the set next to module_init() in ane_t6021_rtclient_main.c and drop the copies, and their comment, from the fwload and boot objects. The MODULE_FIRMWARE() lines stay with the firmware loader. Found in a review of #155. Signed-off-by: Chris Kearney Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FwdG63dRaMrRbYrUBkSa1i (cherry picked from commit 9b8b60c4c8a11c969a547f3f8805664ae176ed72) --- drivers/accel/ane/ane_t6021_boot.c | 6 ------ drivers/accel/ane/ane_t6021_fwload.c | 5 ----- 2 files changed, 11 deletions(-) diff --git a/drivers/accel/ane/ane_t6021_boot.c b/drivers/accel/ane/ane_t6021_boot.c index 1ae368ae3e55f..ec2bb466133c4 100644 --- a/drivers/accel/ane/ane_t6021_boot.c +++ b/drivers/accel/ane/ane_t6021_boot.c @@ -149,12 +149,6 @@ module_param(boot_prevent_nap, bool, 0444); MODULE_PARM_DESC(boot_prevent_nap, "Retain firmware nap-prevention counter via init resource bit (default on: proven add-path value)"); -/* This object links into both ane_t6021.ko and ane_t6021_rtclient.ko; - * per-object metadata keeps modpost happy for either composition. - */ -MODULE_LICENSE("Dual MIT/GPL"); -MODULE_DESCRIPTION("T6021 ANE contract-pinned boot sequence core"); - /* Boot-write gates — ITEMIZED, each a HARD gate: the ENTIRE write * sequence (preboot engine table, scratch clear + pulse, RVBAR * resolution, CPU release, publication, wake) runs start-to-finish diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index c8a7ad8d7bee8..04153a2a4d576 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -84,11 +84,6 @@ #include "ane_t6021_boot.h" #include "ane_fw_validate.h" -/* This object links into both ane_t6021.ko and ane_t6021_rtclient.ko; - * per-object metadata keeps modpost happy for either composition. - */ -MODULE_LICENSE("Dual MIT/GPL"); -MODULE_DESCRIPTION("T6021 ANE firmware staging + entry alias"); MODULE_FIRMWARE(ANE_FW_SELENE_NAME); MODULE_FIRMWARE(ANE_FW_BIA_NAME); From f227145f50e4e29e8eb52b46ff6ce51b56229bb4 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 18:03:39 -0500 Subject: [PATCH 23/26] accel/ane: Log register and address tracing at debug level Both modules log bring-up tracing at info level on every probe: the ANERD/ANEWR recovery trace and the ps probe SET window reads in ane_tm.c, the ANE-resume progress lines and the first ps probe in ane_drv.c, one line for each DART in ane_dart.c, and in ane_t6021 each ChMan table entry, each RTKit endpoint start and app message, the CONFIG_GET words, and the firmware alias, PMU map and staging addresses. Make them dev_dbg(). Dynamic debug still shows them for crash attribution. The outcome lines stay at info level: DART containment armed, loaded ane, tm recovered, the ChMan table result, the chip revision, the boot result lines and loaded ane_t6021. Faults stay at error and warning level. No other code changes. After this change, the only info lines on the ane probe path are "DART containment armed" and "loaded ane". Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_dart.c | 4 +- drivers/accel/ane/ane_drv.c | 14 ++--- drivers/accel/ane/ane_t6021_fwload.c | 48 +++++++-------- drivers/accel/ane/ane_t6021_rtclient_main.c | 30 ++++----- drivers/accel/ane/ane_tm.c | 68 +++++++++++---------- 5 files changed, 83 insertions(+), 81 deletions(-) diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c index f66bfbe15af55..0dc0e955182da 100644 --- a/drivers/accel/ane/ane_dart.c +++ b/drivers/accel/ane/ane_dart.c @@ -113,8 +113,8 @@ int ane_dart_init(struct ane_device *ane) dart->irq = irq; dart->sid = args.args_count ? args.args[0] : 0; dart->masked = false; - dev_info(ane->dev, "DART containment: %pOFn sid %u irq %d\n", - args.np, dart->sid, irq); + dev_dbg(ane->dev, "DART containment: %pOFn sid %u irq %d\n", + args.np, dart->sid, irq); put_device(&pdev->dev); of_node_put(args.np); } diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 20e32a76f190a..52e720aad356c 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -1208,13 +1208,13 @@ static int __maybe_unused ane_runtime_resume(struct device *dev) eng = platform_get_resource_byname(pdev, IORESOURCE_MEM, "engine"); - dev_info(dev, - "ANE-resume: genpd raise complete; SET window probe next\n"); + dev_dbg(dev, + "ANE-resume: genpd raise complete; SET window probe next\n"); ane_ps_act_probe(ane); - dev_info(dev, - "ANE-resume: SET window probed; first engine access next (TM_TQ_EN tm+0x0c @ engine %pr + 0x2000c)\n", - eng); + dev_dbg(dev, + "ANE-resume: SET window probed; first engine access next (TM_TQ_EN tm+0x0c @ engine %pr + 0x2000c)\n", + eng); } ane_tm_enable(ane, first); @@ -1223,7 +1223,7 @@ static int __maybe_unused ane_runtime_resume(struct device *dev) * its post-reset status against it. */ if (!ane->tm_status_known) { - dev_info(dev, "ANE-resume: enable writes survived; TM_STATUS read next\n"); + dev_dbg(dev, "ANE-resume: enable writes survived; TM_STATUS read next\n"); ane->tm_status_fresh = ane_tm_status(ane); ane->tm_status_known = true; /* Linux-side pwrstate probe: ACTUAL nibbles read through @@ -1232,7 +1232,7 @@ static int __maybe_unused ane_runtime_resume(struct device *dev) * pmgr SET block with every word on; anything else means * the window does not match the expected word layout. */ - dev_info(dev, "ANERD ps probe act=%#x\n", ane_ps_act(ane)); + dev_dbg(dev, "ANERD ps probe act=%#x\n", ane_ps_act(ane)); } return 0; diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index 04153a2a4d576..44be0d3e72ecc 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -243,8 +243,8 @@ static int ane_t6021_pmu_map(struct ane_t6021 *ane, struct iommu_domain *dom) prot, GFP_KERNEL); if (!ret && iommu_iova_to_phys(dom, soc->pmu_pa) != soc->pmu_pa) ret = -EIO; - dev_info(ane->dev, "pmu: DART map %#llx (IOVA == PA, %#x bytes): %d\n", - soc->pmu_pa, ANE_T6021_FW_ALIAS_PAGE, ret); + dev_dbg(ane->dev, "pmu: DART map %#llx (IOVA == PA, %#x bytes): %d\n", + soc->pmu_pa, ANE_T6021_FW_ALIAS_PAGE, ret); return ret; } @@ -265,9 +265,9 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) /* Unlatched branch: the boot path programs RVBAR to the * fw DVA itself (ane_t6021_rvbar_compose), no alias. */ - dev_info(ane->dev, - "fwalias: rvbar %016llx not latched/entry 0 — skip (boot reprograms RVBAR)\n", - rvbar); + dev_dbg(ane->dev, + "fwalias: rvbar %016llx not latched/entry 0 — skip (boot reprograms RVBAR)\n", + rvbar); return 0; } if (!ane_t6021_rvbar_entry_ok(entry) || @@ -366,14 +366,14 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) } ane->fw_alias_extn = windows; ane->fw_alias_iova = entry; - dev_info(ane->dev, - "fwalias: reserved SEG0/SEGi at entry %#llx (%llx+%zx %llx+%zx, preloaded placement)\n", - entry, - ane->fw_alias_ext_iova[0], ane->fw_alias_ext_len[0], - ane->fw_alias_ext_iova[1], ane->fw_alias_ext_len[1]); + dev_dbg(ane->dev, + "fwalias: reserved SEG0/SEGi at entry %#llx (%llx+%zx %llx+%zx, preloaded placement)\n", + entry, + ane->fw_alias_ext_iova[0], ane->fw_alias_ext_len[0], + ane->fw_alias_ext_iova[1], ane->fw_alias_ext_len[1]); if (fw_extra_ram) - dev_info(ane->dev, "fwalias: owned heap [%#llx,%#llx) roundtrip verified\n", - win[2].iova, win[2].iova + win[2].len); + dev_dbg(ane->dev, "fwalias: owned heap [%#llx,%#llx) roundtrip verified\n", + win[2].iova, win[2].iova + win[2].len); return ane_t6021_pmu_map(ane, dom); err_unmap_mapped: @@ -440,10 +440,10 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) ane->fw_alias_ext_iova[0] = entry; ane->fw_alias_ext_len[0] = ane->fw_size; ane->fw_alias_extn = 1; - dev_info(ane->dev, - "fwalias: entry %#llx <- %u dart pages aliased from fw %pad (first %pa, roundtrip OK)\n", - entry, ane->fw_size / ANE_T6021_FW_ALIAS_PAGE, - &ane->fw_iova, &pa0); + dev_dbg(ane->dev, + "fwalias: entry %#llx <- %u dart pages aliased from fw %pad (first %pa, roundtrip OK)\n", + entry, ane->fw_size / ANE_T6021_FW_ALIAS_PAGE, + &ane->fw_iova, &pa0); /* The firmware's power service needs the pmgr sub-block mapped * IOVA == PA in every vehicle (NO PMD FOR IOVA 0x28e084008, * 2026-09-29); the staged-DMA alias branch skipped it and left @@ -527,11 +527,11 @@ static int ane_t6021_fw_patch(struct ane_t6021 *ane, u8 *img) p.soc_revision); return -EINVAL; } - dev_info(ane->dev, - "fwload: own memory: iBoot patches replayed (soc %#x rev %#x DATA %#llx cpu %#llx wrapper %#llx)\n", - p.soc, p.soc_revision, - p.exec_base + soc->fw->segs[1].vmaddr, p.cpu_pa, - p.wrapper_pa); + dev_dbg(ane->dev, + "fwload: own memory: iBoot patches replayed (soc %#x rev %#x DATA %#llx cpu %#llx wrapper %#llx)\n", + p.soc, p.soc_revision, + p.exec_base + soc->fw->segs[1].vmaddr, p.cpu_pa, + p.wrapper_pa); return 0; } @@ -595,9 +595,9 @@ int ane_t6021_fwload_probe(struct ane_t6021 *ane) ane->fw_iova = iova; ane->fw_size = alloc_size; - dev_info(ane->dev, - "fwload: %s PRELOAD validated + DART-mapped: entry %#llx, iova %pad size %#x\n", - img->name, entry, &iova, alloc_size); + dev_dbg(ane->dev, + "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); if (!ret) diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index f9eb131a4f30e..be21e4c1b0eb1 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -464,12 +464,12 @@ static void ane_rtclient_validate_chman(struct ane_rtclient *ane) const struct ane_t6021_chman_desc *d = &t[i]; const struct ane_t6021_chman_static *s = &ane_t6021_chman_layout[i]; - dev_info(ane->dev, - "chman[%u]: name=\"%.*s\" type=%u bit=%u size=%#llx %s (static: %s/%u/%u/%#llx/ipc+%#x)\n", - i, ANE_T6021_CHMAN_NAME_LEN, d->name, d->type, d->bit, - d->size, - (bad & BIT(i)) ? "MISMATCH" : "OK", - s->name, s->type, s->bit, s->size, s->off); + dev_dbg(ane->dev, + "chman[%u]: name=\"%.*s\" type=%u bit=%u size=%#llx %s (static: %s/%u/%u/%#llx/ipc+%#x)\n", + i, ANE_T6021_CHMAN_NAME_LEN, d->name, d->type, d->bit, + d->size, + (bad & BIT(i)) ? "MISMATCH" : "OK", + s->name, s->type, s->bit, s->size, s->off); } ane->chman_ok = !bad; @@ -1800,8 +1800,8 @@ static void ane_rtclient_recv(void *cookie, u8 ep, u64 message) { struct ane_rtclient *ane = cookie; - dev_info(ane->dev, - "rtkit app msg: ep=%#x msg=%016llx\n", ep, message); + dev_dbg(ane->dev, + "rtkit app msg: ep=%#x msg=%016llx\n", ep, message); } static void ane_rtclient_crashed(void *cookie, const void *crashlog, @@ -1901,8 +1901,8 @@ static void ane_rtclient_start_app_eps(struct ane_rtclient *ane) if (!apple_rtkit_has_endpoint(ane->rtk, ep)) continue; ret = apple_rtkit_start_ep(ane->rtk, ep); - dev_info(ane->dev, "rtkit: STARTEP app ep %#x -> %pe\n", - ep, ERR_PTR(ret)); + dev_dbg(ane->dev, "rtkit: STARTEP app ep %#x -> %pe\n", + ep, ERR_PTR(ret)); } } @@ -2295,11 +2295,11 @@ static int ane_rtclient_probe(struct platform_device *pdev) command, 16, 0x03, 1, 3000); - dev_info(dev, - "LEGACY CONFIG_GET words %08x %08x result=%d (DMA remains held)\n", - READ_ONCE(((u32 *)command->cpu)[1]), - READ_ONCE(((u32 *)command->cpu)[2]), - qret); + dev_dbg(dev, + "LEGACY CONFIG_GET words %08x %08x result=%d (DMA remains held)\n", + READ_ONCE(((u32 *)command->cpu)[1]), + READ_ONCE(((u32 *)command->cpu)[2]), + qret); if (qret) { cfg_err = qret; } else if (!READ_ONCE(((u32 *)command->cpu)[2])) { diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index 7a0ade69c395b..52f3781b8cc15 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -92,7 +92,8 @@ u32 ane_ps_act(struct ane_device *ane) /* Bisect probe: per-word named reads of the SET window. Each word logs * before its readl, so a window whose address does not decode on this * SoC is named by the last off-box line (word index + byte offset) - * instead of a silent hard reset between two other prints. + * instead of a silent hard reset between two other prints. The lines + * are debug messages: dynamic debug turns them on. */ u32 ane_ps_act_probe(struct ane_device *ane) { @@ -100,19 +101,19 @@ u32 ane_ps_act_probe(struct ane_device *ane) int i; if (!ane->ps) { - dev_info(ane->dev, "ps probe: SET window unmapped\n"); + dev_dbg(ane->dev, "ps probe: SET window unmapped\n"); return 0; } - dev_info(ane->dev, "ps probe: SET window at %pap, %d words\n", - &ane->ps_base, ANE_PS_WORDS); + dev_dbg(ane->dev, "ps probe: SET window at %pap, %d words\n", + &ane->ps_base, ANE_PS_WORDS); for (i = 0; i < ANE_PS_WORDS; i++) { u32 w; - dev_info(ane->dev, "ps probe: word %d @ ps+0x%02x reading\n", - i, i * 8); + dev_dbg(ane->dev, "ps probe: word %d @ ps+0x%02x reading\n", + i, i * 8); w = readl(ane->ps + i * 8); v |= ((w & ANE_PS_ACTUAL_MASK) >> 4) << (i * 4); - dev_info(ane->dev, "ps probe: word %d -> %#x\n", i, w); + dev_dbg(ane->dev, "ps probe: word %d -> %#x\n", i, w); } return v; } @@ -121,16 +122,17 @@ u32 ane_ps_act_probe(struct ane_device *ane) * every engine read prints its value, each line carrying the pmgr * ACTUAL of the owning partitions. A write that external-aborts the * SoC is then named by the last line the off-box netconsole carried, - * and the bisect starts from that register instead of a guess. + * and the bisect starts from that register instead of a guess. The + * lines are debug messages: dynamic debug turns them on. */ static void ane_rec_writel(struct ane_device *ane, const char *reg, void __iomem *addr, u32 val) { - dev_info(ane->dev, "ANEWR %s <- %#x (ps act %#x)\n", reg, val, - ane_ps_act(ane)); + dev_dbg(ane->dev, "ANEWR %s <- %#x (ps act %#x)\n", reg, val, + ane_ps_act(ane)); writel(val, addr); - dev_info(ane->dev, "ANEWR %s wrote (ps act %#x)\n", reg, - ane_ps_act(ane)); + dev_dbg(ane->dev, "ANEWR %s wrote (ps act %#x)\n", reg, + ane_ps_act(ane)); } static u32 ane_rec_read32(struct ane_device *ane, const char *reg, @@ -138,8 +140,8 @@ static u32 ane_rec_read32(struct ane_device *ane, const char *reg, { u32 val = readl(addr); - dev_info(ane->dev, "ANERD %s -> %#x (ps act %#x)\n", reg, val, - ane_ps_act(ane)); + dev_dbg(ane->dev, "ANERD %s -> %#x (ps act %#x)\n", reg, val, + ane_ps_act(ane)); return val; } @@ -423,7 +425,7 @@ static int ane_ps_verify_on(struct ane_device *ane) } usleep_range(1000, 2000); } - dev_info(ane->dev, "ANERD ps verify act=%#x err=%d\n", act, err); + dev_dbg(ane->dev, "ANERD ps verify act=%#x err=%d\n", act, err); return err; } @@ -438,26 +440,26 @@ static int ane_pd_cycle(struct ane_device *ane) for (int i = 0; i < ane->pd_count; i++) { pm_runtime_get_noresume(ane->pd_dev[i]); gated = i + 1; - dev_info(ane->dev, - "ANERD pd[%d] %s force_suspend begin (ps act %#x)\n", - i, dev_name(ane->pd_dev[i]), ane_ps_act(ane)); + dev_dbg(ane->dev, + "ANERD pd[%d] %s force_suspend begin (ps act %#x)\n", + i, dev_name(ane->pd_dev[i]), ane_ps_act(ane)); err = pm_runtime_force_suspend(ane->pd_dev[i]); - dev_info(ane->dev, - "ANERD pd[%d] force_suspend -> %d (ps act %#x)\n", - i, err, ane_ps_act(ane)); + dev_dbg(ane->dev, + "ANERD pd[%d] force_suspend -> %d (ps act %#x)\n", + i, err, ane_ps_act(ane)); if (err) break; } if (!err) for (int i = 0; i < ane->pd_count; i++) { - dev_info(ane->dev, - "ANERD pd[%d] %s force_resume begin (ps act %#x)\n", - i, dev_name(ane->pd_dev[i]), - ane_ps_act(ane)); + dev_dbg(ane->dev, + "ANERD pd[%d] %s force_resume begin (ps act %#x)\n", + i, dev_name(ane->pd_dev[i]), + ane_ps_act(ane)); err = pm_runtime_force_resume(ane->pd_dev[i]); - dev_info(ane->dev, - "ANERD pd[%d] force_resume -> %d (ps act %#x)\n", - i, err, ane_ps_act(ane)); + dev_dbg(ane->dev, + "ANERD pd[%d] force_resume -> %d (ps act %#x)\n", + i, err, ane_ps_act(ane)); if (err) break; } @@ -470,14 +472,14 @@ static int ane_pd_cycle(struct ane_device *ane) * the partition gated. */ pm_runtime_get_noresume(ane->dev); - dev_info(ane->dev, "ANERD dev force_suspend begin\n"); + dev_dbg(ane->dev, "ANERD dev force_suspend begin\n"); err = pm_runtime_force_suspend(ane->dev); - dev_info(ane->dev, "ANERD dev force_suspend -> %d\n", err); + dev_dbg(ane->dev, "ANERD dev force_suspend -> %d\n", err); if (!err) { - dev_info(ane->dev, "ANERD dev force_resume begin\n"); + dev_dbg(ane->dev, "ANERD dev force_resume begin\n"); err = pm_runtime_force_resume(ane->dev); - dev_info(ane->dev, "ANERD dev force_resume -> %d\n", - err); + dev_dbg(ane->dev, "ANERD dev force_resume -> %d\n", + err); } pm_runtime_put_noidle(ane->dev); } From 0a8b54f5b4dc5e1c607024600fd449004b26d08d Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 2 Oct 2026 20:10:14 -0500 Subject: [PATCH 24/26] accel/ane: Power the ANE off when it is idle The ane module takes a runtime PM reference in probe and holds it until remove, so the ANE power domains and its three DARTs stay powered for as long as the driver is bound, also when no process uses the ANE. Drop the probe reference at the end of probe and use runtime PM autosuspend. The device suspends autosuspend_ms (default 1500) after the last file open, ioctl or close, and the next one resumes it through ane_runtime_resume(), which enables the task manager again. The new module parameter autosuspend_ms=0 keeps the device powered while the driver is bound. power/autosuspend_delay_ms and power/control change the behavior at run time. Every path that touches the engine or the ANE's own DART registers now holds a reference: - the ioctls, through one wrapper for the native and the 32-bit compat entry points, so both get the command filter and the reference; - the reset sysfs attribute, which power-cycles the partitions and then writes the engine; - the file release, which frees the BOs of the file (each unmap flushes the DART TLBs) and can run the recovery in postclose. It keeps a reference to the struct device, because drm_release() can free the ane_device; - remove, which unmaps the remaining BOs and detaches the power domains. apple-dart saves and restores the stream TCR and TTBR registers in its own runtime PM callbacks, and the ANE is its consumer through a DL_FLAG_PM_RUNTIME device link, so the IOMMU state survives the suspend. Measurements on hardware are pending. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_drv.c | 90 +++++++++++++++++++++++++++++++++---- drivers/accel/ane/ane_tm.c | 6 +-- 2 files changed, 84 insertions(+), 12 deletions(-) diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 52e720aad356c..2147d6a5e7d83 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -66,6 +66,19 @@ module_param(stats, bool, 0444); MODULE_PARM_DESC(stats, "Expose ane_stats sysfs and ane_timeline debugfs (default 1; 0 = no files and the hot path skips the counters)"); +/* + * Runtime PM autosuspend delay. The ANE power domains and its DARTs go + * off this long after the last file open, ioctl or close, and the next + * one powers them up again through ane_runtime_resume(). 0 keeps the + * device powered while the driver is bound. The live value is + * power/autosuspend_delay_ms, and "on" in power/control keeps the + * device powered without a reload. + */ +static int autosuspend_ms = 1500; +module_param(autosuspend_ms, int, 0444); +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)"); + #define CMD_BUF_BDX 0 #define KRN_BUF_BDX 1 @@ -624,10 +637,18 @@ static ssize_t reset_store(struct device *dev, struct device_attribute *attr, struct ane_device *ane = dev_get_drvdata(dev); int err = 0; + /* Recovery power-cycles the partitions and then writes the engine: + * hold a reference so that autosuspend cannot gate it in between. + */ + err = pm_runtime_resume_and_get(dev); + if (err < 0) + return err; + mutex_lock(&ane->engine_lock); if (!ane->removed) err = ane_tm_recover(ane); mutex_unlock(&ane->engine_lock); + pm_runtime_put_autosuspend(dev); if (err) return err; return count; @@ -688,7 +709,7 @@ static int ane_drm_open(struct drm_device *drm, struct drm_file *file) if (err < 0) return err; - pm_runtime_put(ane->dev); + pm_runtime_put_autosuspend(ane->dev); return 0; } @@ -741,8 +762,10 @@ static void ane_drm_postclose(struct drm_device *drm, struct drm_file *file) * from before DRM_ACCEL_FOPS landed drm_ioctl defaults), so this is a * belt-and-suspenders gate on top of the existing ioctls table. */ -static long ane_drm_unlocked_ioctl(struct file *file, unsigned int cmd, - unsigned long arg) +static long ane_drm_ioctl(struct file *file, unsigned int cmd, + unsigned long arg, + long (*dispatch)(struct file *, unsigned int, + unsigned long)) { struct drm_file *filp = file->private_data; struct drm_device *drm = filp->minor->dev; @@ -770,10 +793,47 @@ static long ane_drm_unlocked_ioctl(struct file *file, unsigned int cmd, if (err < 0) return err; - err = drm_ioctl(file, cmd, arg); + err = dispatch(file, cmd, arg); + + pm_runtime_put_autosuspend(ane->dev); + + return err; +} + +static long ane_drm_unlocked_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + return ane_drm_ioctl(file, cmd, arg, drm_ioctl); +} + +/* 32-bit callers get the same command filter and PM reference. */ +#ifdef CONFIG_COMPAT +static long ane_drm_compat_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + return ane_drm_ioctl(file, cmd, arg, drm_compat_ioctl); +} +#else +#define ane_drm_compat_ioctl NULL +#endif - pm_runtime_put(ane->dev); +/* + * Hold power across the close: drm_release() frees the BOs of the file, + * and each unmap flushes the DART TLBs. With the device suspended, + * apple-dart would power the DARTs up and down again for every page. + * The device reference outlives drm_release(), which can drop the last + * drm_device reference and free ane. + */ +static int ane_drm_release(struct inode *inode, struct file *file) +{ + struct drm_file *priv = file->private_data; + struct device *dev = get_device(priv->minor->dev->dev); + int err; + pm_runtime_get_sync(dev); + err = drm_release(inode, file); + pm_runtime_put_autosuspend(dev); + put_device(dev); return err; } @@ -823,9 +883,9 @@ static const struct file_operations ane_drm_fops = { .owner = THIS_MODULE, .fop_flags = FOP_UNSIGNED_OFFSET, .open = accel_open, - .release = drm_release, + .release = ane_drm_release, .unlocked_ioctl = ane_drm_unlocked_ioctl, - .compat_ioctl = drm_compat_ioctl, + .compat_ioctl = ane_drm_compat_ioctl, .poll = drm_poll, .read = drm_read, .llseek = noop_llseek, @@ -1104,9 +1164,13 @@ static int ane_platform_probe(struct platform_device *pdev) * supplier links for several), and .runtime_resume then does the * first engine MMIO. Marking the device active up front skips that * resume, and on T6001 the engine window external-aborts while its - * partition is gated. The reference is held until remove: the device - * stays powered for the whole lifetime, autosuspend stays disabled. + * partition is gated. Probe drops its reference at the end, and the + * device autosuspends autosuspend_ms after its last use. A negative + * delay (autosuspend_ms=0) makes the PM core keep it powered. */ + pm_runtime_set_autosuspend_delay(dev, + autosuspend_ms > 0 ? autosuspend_ms : -1); + pm_runtime_use_autosuspend(dev); pm_runtime_enable(dev); err = pm_runtime_resume_and_get(dev); if (err < 0) @@ -1128,12 +1192,14 @@ static int ane_platform_probe(struct platform_device *pdev) dev_info(dev, "loaded ane\n"); + pm_runtime_put_autosuspend(dev); return 0; put_pm: pm_runtime_put_noidle(dev); disable_pm: pm_runtime_disable(dev); + pm_runtime_dont_use_autosuspend(dev); drm_mm_takedown(&ane->mm); detach_genpd: ane_boost_exit(ane); @@ -1146,6 +1212,11 @@ static void ane_platform_remove(struct platform_device *pdev) struct ane_device *ane = platform_get_drvdata(pdev); struct ane_bo *bo, *tmp; + /* Powered and pinned for the teardown: the unmaps below flush the + * DART TLBs, and no autosuspend may race the genpd detach. + */ + pm_runtime_get_sync(ane->dev); + mutex_lock(&ane->engine_lock); ane->removed = true; drm_dev_unplug(&ane->drm); @@ -1166,6 +1237,7 @@ static void ane_platform_remove(struct platform_device *pdev) ane_detach_genpd(ane); pm_runtime_disable(ane->dev); + pm_runtime_dont_use_autosuspend(ane->dev); pm_runtime_put_noidle(ane->dev); mutex_unlock(&ane->engine_lock); } diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index 52f3781b8cc15..703d595b612a9 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -467,9 +467,9 @@ static int ane_pd_cycle(struct ane_device *ane) pm_runtime_put_noidle(ane->pd_dev[gated]); } else { /* Pin a second usage ref for the cycle: force_suspend only - * marks needs_force_resume when a ref beyond the probe one - * is held, and without that mark force_resume would leave - * the partition gated. + * marks needs_force_resume when a ref beyond the caller's + * one (submit ioctl or reset write) is held, and without + * that mark force_resume would leave the partition gated. */ pm_runtime_get_noresume(ane->dev); dev_dbg(ane->dev, "ANERD dev force_suspend begin\n"); From 363166515c05fb099ad8d5752d99432244e40e60 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:06:51 -0500 Subject: [PATCH 25/26] accel/ane: Map a buffer object with one DART TLB sync BO_INIT maps a buffer object one page at a time with iommu_map(). Each call syncs the TLB of every DART in the domain, so a buffer of N pages costs 3 * N TLB invalidates on the three ANE DARTs. A 458 MB buffer has 27,955 pages and needs 83,865 invalidates. Map the buffer with one iommu_map_sgtable() instead. iommu_map_sg() writes the PTEs of each physically contiguous run and syncs the TLBs once for the whole range. Keep the old per-page path behind the new module parameter map_batch (default 1; 0 selects the old path). BOs mapped either way unmap the same way. Keep the stray PTE recovery on both paths. iommu_map_sg() unmaps what it mapped before it returns an error, so after -EEXIST every valid PTE left in the reserved range is a stray: clear the range page by page and try once more. A short return would give a BO whose tail has no PTEs, so clear the range page by page and fail BO_INIT with -EIO. The page by page clear also serves the stale-mapping purge in probe. Measured with map_batch=1 against map_batch=0, with bit-exact program outputs and exact job counts: M1 (T8103) laptop: BO_INIT 179.85 ms -> 22.77 ms, cold open 165 to 173 ms faster M1 Max (T6001) laptop: BO_INIT 232.7 ms -> 24.7 ms, open 787.9 ms -> 574.3 ms A stress run was clean on both. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/accel/ane/ane_drv.c | 197 +++++++++++++++++++++++++----------- 1 file changed, 137 insertions(+), 60 deletions(-) diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 2147d6a5e7d83..70f0d9bd9b365 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -79,6 +80,18 @@ module_param(autosuspend_ms, int, 0444); 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 + * 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. + */ +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"); + #define CMD_BUF_BDX 0 #define KRN_BUF_BDX 1 @@ -102,63 +115,44 @@ static struct ane_bo *bo_lookup(struct drm_file *file, u32 handle) return to_bo(gem); } -/* - * Buffers are mapped and unmapped only through the kernel-owned IOMMU - * domain the device was attached to by its providers. apple-dart - * programs every DART in the device's "iommus" list (TTBRs, stream - * 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. - */ -static int ane_iommu_map_pages(struct ane_device *ane, struct ane_bo *bo) +/* 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) { - int err; + unsigned long cleared = 0; - lockdep_assert_held(&ane->engine_lock); - if (bo->mm) - return -EBUSY; - - 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, - bo->npages << ane->shift, - 1UL << ane->shift, 0, 0); - if (err < 0) { - dev_err(ane->dev, "out of ANE space: %d\n", err); - goto unlock; + for (u64 iova = start; iova < end; iova += 1UL << ane->shift) { + if (!iommu_iova_to_phys(ane->domain, iova)) + continue; + iommu_unmap(ane->domain, iova, 1UL << ane->shift); + cleared++; } + return cleared; +} - bo->iova = bo->mm->start; +/* + * Every PTE inside a reserved drm_mm node must be ours-or-absent: + * scratch drains reserve before mapping and wedge-preserved nodes stay + * inserted. A VALID PTE in a just-reserved range is therefore a stray + * from a torn-down session or a lost unmap. Both map paths clear it once + * and retry instead of poisoning every later BO_INIT until reload + * (m1-test-host 2026-09-25: dart_init_pte -EEXIST at 0x4000 for the rest + * of the session). + */ +static int ane_iommu_map_each(struct ane_device *ane, struct ane_bo *bo, + int prot) +{ + int err = 0; - /* map into ANE address space */ for (u32 i = 0; i < bo->npages; i++) { dma_addr_t iova = bo->iova + (i << ane->shift); - int prot = IOMMU_READ | IOMMU_WRITE; bool healed = false; - int prot_cache = map_mode & 1; retry: - if (prot_cache) - prot |= IOMMU_CACHE; err = iommu_map(ane->domain, iova, page_to_phys(bo->pages[i]), 1UL << ane->shift, prot, GFP_KERNEL); if (err < 0) { dev_err(ane->dev, "iommu_map failed at 0x%llx", iova); - /* Every PTE inside a reserved drm_mm node must be - * ours-or-absent: scratch drains reserve before - * mapping and wedge-preserved nodes stay inserted. - * A VALID PTE in a just-reserved range is therefore - * a stray from a torn-down session or a lost - * unmap. Clear it once and retry instead of - * poisoning every later BO_INIT until reload - * (m1-test-host 2026-09-25: dart_init_pte -EEXIST at - * 0x4000 for the rest of the session). - */ if (err == -EEXIST && !healed && iommu_iova_to_phys(ane->domain, iova)) { dev_warn(ane->dev, @@ -182,26 +176,115 @@ static int ane_iommu_map_pages(struct ane_device *ane, struct ane_bo *bo) bo->iova + (i << ane->shift), unmapped); } - drm_mm_remove_node(bo->mm); - bo->iova = 0; break; } } + return err; +} - mutex_unlock(&ane->iommu_lock); +/* + * iommu_map_sg() writes the PTEs of each physically contiguous run and + * syncs the DART TLBs once for the whole range. On failure it has + * already unmapped everything it mapped, so after an -EEXIST every valid + * PTE left in the range is a stray. + */ +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; + struct sg_table sgt; + unsigned long strays; + ssize_t mapped; + int err; - if (err < 0) { - kfree(bo->mm); - bo->mm = NULL; + err = sg_alloc_table_from_pages(&sgt, bo->pages, bo->npages, 0, size, + GFP_KERNEL); + if (err) return err; + + mapped = iommu_map_sgtable(ane->domain, bo->iova, &sgt, prot); + if (mapped == -EEXIST) { + strays = ane_iommu_clear_range(ane, bo->iova, bo->iova + size); + if (strays) { + dev_warn(ane->dev, + "cleared %lu stray DART PTE(s) in %#llx+%#zx (no node owns them)\n", + strays, bo->iova, size); + mapped = iommu_map_sgtable(ane->domain, bo->iova, &sgt, + prot); + } } + sg_free_table(&sgt); + /* + * A short map would hand out a BO whose tail has no PTEs. The + * mapped part can have holes, so clear page by page, not with one + * range unmap that stops at the first hole. + */ + if (mapped >= 0 && (size_t)mapped != size) { + ane_iommu_clear_range(ane, bo->iova, bo->iova + size); + mapped = -EIO; + } + + if (mapped < 0) { + dev_err(ane->dev, "iommu_map_sg failed at %#llx+%#zx: %zd\n", + bo->iova, size, mapped); + return mapped; + } return 0; +} + +/* + * Buffers are mapped and unmapped only through the kernel-owned IOMMU + * domain the device was attached to by its providers. apple-dart + * programs every DART in the device's "iommus" list (TTBRs, stream + * 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. + */ +static int ane_iommu_map_pages(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; + + if (map_mode & 1) + 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, + bo->npages << ane->shift, + 1UL << ane->shift, 0, 0); + if (err < 0) { + dev_err(ane->dev, "out of ANE space: %d\n", err); + goto unlock; + } + + bo->iova = bo->mm->start; + + if (READ_ONCE(map_batch)) + err = ane_iommu_map_batch(ane, bo, prot); + else + err = ane_iommu_map_each(ane, bo, prot); + if (err < 0) { + drm_mm_remove_node(bo->mm); + bo->iova = 0; + } unlock: mutex_unlock(&ane->iommu_lock); - kfree(bo->mm); - bo->mm = NULL; + if (err < 0) { + kfree(bo->mm); + bo->mm = NULL; + } return err; } @@ -943,17 +1026,11 @@ static int ane_iommu_domain_init(struct ane_device *ane) static void ane_iommu_purge_stale(struct ane_device *ane) { struct drm_mm_node *hole; - u64 start, end, iova; + u64 start, end; unsigned long stale = 0; - drm_mm_for_each_hole(hole, &ane->mm, start, end) { - for (iova = start; iova < end; iova += 1UL << ane->shift) { - if (!iommu_iova_to_phys(ane->domain, iova)) - continue; - iommu_unmap(ane->domain, iova, 1UL << ane->shift); - stale++; - } - } + drm_mm_for_each_hole(hole, &ane->mm, start, end) + stale += ane_iommu_clear_range(ane, start, end); if (stale) dev_warn(ane->dev, "cleared %lu stale DART mappings from a previous instance\n", From efe6e359d456724cb0a7292d867bac147d9a5cd3 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Sat, 3 Oct 2026 13:59:19 -0500 Subject: [PATCH 26/26] arm64: dts: apple: enable the ANE on t8103, t6000 and t6020 The ANE node, its DARTs, its mailbox and the power states only it uses are disabled on the M1 (T8103), the M1 Pro (T6000) and the M2 Pro (T6020) behind APPLE_ANE_UNTESTED, because the driver had run only on the M1 Max and the M2 Max. It has now run with this tree's own driver on all three. Each chip has a passing row in the public community dataset (promotion_check --remote: judged, driver_source=intree, 20 smoke calls that match the golden bit for bit, no ANE, DART or mailbox fault): M1 (T8103) row 3559e0f328ba M1 Pro (T6000) row 6eb94f49985b M2 Pro (T6020) row 3c9389040f51 Remove the define from t6000.dtsi, t6020.dtsi and t8103.dtsi. No file defines it after this, so also remove the #ifndef APPLE_ANE_UNTESTED guards in t6001.dtsi, t6021.dtsi and t8103.dtsi, and correct the comments that said the ANE had not run on the M1 Pro and the M2 Pro. The ANE is now enabled on the t8103 boards (j274, j293, j313, j456, j457), the t6000 boards (j314s, j316s) and the t6020 boards (j414s, j416s, j474s). The DTBs of the t6001, t6002, t6021, t6022 and t8112 boards do not change: t6002.dtsi and t6022.dtsi include neither t6001.dtsi nor t6021.dtsi, so the ANE stays disabled on the M1 Ultra (T6002), the M2 Ultra (T6022) and the M2 (T8112). Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6000.dtsi | 3 --- arch/arm64/boot/dts/apple/t6001.dtsi | 7 ++----- arch/arm64/boot/dts/apple/t6020.dtsi | 3 --- arch/arm64/boot/dts/apple/t6021.dtsi | 7 ++----- arch/arm64/boot/dts/apple/t8103.dtsi | 9 ++------- 5 files changed, 6 insertions(+), 23 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6000.dtsi b/arch/arm64/boot/dts/apple/t6000.dtsi index 22cb23931e0b3..db7ea6eac5a6f 100644 --- a/arch/arm64/boot/dts/apple/t6000.dtsi +++ b/arch/arm64/boot/dts/apple/t6000.dtsi @@ -11,9 +11,6 @@ #define GPU_REPEAT(x) -/* The ANE has only run on the M1 Max so far: leave it off on the M1 Pro */ -#define APPLE_ANE_UNTESTED - #include "t6001.dtsi" / { diff --git a/arch/arm64/boot/dts/apple/t6001.dtsi b/arch/arm64/boot/dts/apple/t6001.dtsi index f044ff6980c1b..f14bd14518042 100644 --- a/arch/arm64/boot/dts/apple/t6001.dtsi +++ b/arch/arm64/boot/dts/apple/t6001.dtsi @@ -90,11 +90,9 @@ }; /* - * The ANE has run on the M1 Max, so enable it here with its DARTs and the - * power states only it uses. t6000.dtsi defines APPLE_ANE_UNTESTED before - * including this file: the ANE has not run on the M1 Pro yet. + * The ANE has run on the M1 Pro and the M1 Max, so enable it here with its + * DARTs and the power states only it uses. t6000.dtsi includes this file. */ -#ifndef APPLE_ANE_UNTESTED &ane { status = "okay"; }; @@ -134,4 +132,3 @@ &ps_ane_set4 { status = "okay"; }; -#endif diff --git a/arch/arm64/boot/dts/apple/t6020.dtsi b/arch/arm64/boot/dts/apple/t6020.dtsi index 0fa3630e2849d..e9af24b25ab68 100644 --- a/arch/arm64/boot/dts/apple/t6020.dtsi +++ b/arch/arm64/boot/dts/apple/t6020.dtsi @@ -11,9 +11,6 @@ #define GPU_REPEAT(x) -/* The ANE has only run on the M2 Max so far: leave it off on the M2 Pro */ -#define APPLE_ANE_UNTESTED - #include "t6021.dtsi" / { diff --git a/arch/arm64/boot/dts/apple/t6021.dtsi b/arch/arm64/boot/dts/apple/t6021.dtsi index 11521dc6091a6..53bd36ef4b843 100644 --- a/arch/arm64/boot/dts/apple/t6021.dtsi +++ b/arch/arm64/boot/dts/apple/t6021.dtsi @@ -87,11 +87,9 @@ }; /* - * The ANE has run on the M2 Max, so enable it here with its mailbox and - * DARTs. t6020.dtsi defines APPLE_ANE_UNTESTED before including this - * file: the ANE has not run on the M2 Pro yet. + * The ANE has run on the M2 Pro and the M2 Max, so enable it here with its + * mailbox and DARTs. t6020.dtsi includes this file. */ -#ifndef APPLE_ANE_UNTESTED &ane { status = "okay"; }; @@ -111,4 +109,3 @@ &ane_mbox { status = "okay"; }; -#endif diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 3ad699a0321c6..89022ae4811a3 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -2175,13 +2175,9 @@ #include "t8103-pmgr.dtsi" /* - * The ANE has not run on the M1 yet, so it stays off together with its - * DARTs and the power states only it uses. Drop this define to enable - * them once it has. + * The ANE has run on the M1, so enable it here with its DARTs and the + * power states only it uses. */ -#define APPLE_ANE_UNTESTED - -#ifndef APPLE_ANE_UNTESTED &ane { status = "okay"; }; @@ -2221,4 +2217,3 @@ &ps_ane_set5 { status = "okay"; }; -#endif