diff --git a/Documentation/ABI/testing/sysfs-class-power b/Documentation/ABI/testing/sysfs-class-power index 32697b926cc8c2..a68e36832c2506 100644 --- a/Documentation/ABI/testing/sysfs-class-power +++ b/Documentation/ABI/testing/sysfs-class-power @@ -513,6 +513,11 @@ Description: inhibit-charge: Do not charge while AC is attached inhibit-charge-awake: inhibit-charge only when device is awake force-discharge: Force discharge while AC is attached + auto-discharge: auto, but actively discharge down to + the charge control end threshold. + Needs an end threshold below 100; + an end threshold of 100 returns to + auto ===================== ======================================== What: /sys/class/power_supply//technology diff --git a/Documentation/devicetree/bindings/dma/apple,sio.yaml b/Documentation/devicetree/bindings/dma/apple,sio.yaml index 0e3780ad9dd79a..dbaaa2d3d1a1a9 100644 --- a/Documentation/devicetree/bindings/dma/apple,sio.yaml +++ b/Documentation/devicetree/bindings/dma/apple,sio.yaml @@ -22,6 +22,7 @@ properties: items: - enum: - apple,t6000-sio + - apple,t6030-sio - apple,t8103-sio - const: apple,sio diff --git a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml index d86c8b68d1b48a..7800f0f106f2cd 100644 --- a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml @@ -79,6 +79,16 @@ properties: Forces this power domain to always be powered up. type: boolean + apple,no-auto-pm: + description: | + Never enables automatic power management (auto-enable) for this + domain: once powered up it stays at its requested state until + Linux changes it. Required for a coprocessor CPU domain whose + firmware is started cold by Linux and must not be clock or power + gated behind its back, such as the T6030 external display + coprocessors' CPU domains. + type: boolean + apple,firmware-owned: description: The boot loader hands over the coprocessor in this domain running, and its @@ -86,6 +96,17 @@ properties: domain on and never changes its power target, automatic gating or reset. type: boolean + apple,inherited-on: + description: | + The boot loader leaves this domain powered, with the coprocessor it + feeds running (the internal display chain of the T6030, T6031 and + T8122 MacBook Pros: DISP_SYS, DISP_FE and DISP_CPU). The power state + driver treats it as any domain found on; the display handoff requires + the marker before it adds the PMP and sets apple,min-state on the + chain, so the PMP cannot power the running display coprocessor down. + Unlike apple,firmware-owned, the domain's register is still written. + type: boolean + apple,min-state: description: Specifies the minimum power state for auto-PM. diff --git a/Documentation/networking/strparser.rst b/Documentation/networking/strparser.rst index 372106b61e6512..d0804c88ad0a04 100644 --- a/Documentation/networking/strparser.rst +++ b/Documentation/networking/strparser.rst @@ -77,7 +77,7 @@ Functions strp_done is called to release any resources held by the stream parser instance. This must be called after the stream processor - has been stopped. + has been stopped. The socket lock must not be held. :: diff --git a/MAINTAINERS b/MAINTAINERS index fb7a61279c2f81..1d10b8f9158edc 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2631,6 +2631,10 @@ F: Documentation/devicetree/bindings/dma/apple,sio.yaml F: Documentation/devicetree/bindings/sound/apple,* F: Documentation/devicetree/bindings/sound/cirrus,cs42l84.yaml F: Documentation/devicetree/bindings/sound/trivial-codec.yaml +F: drivers/dma/apple-sio-probe-test.c +F: drivers/dma/apple-sio-probe-test.dtso +F: drivers/dma/apple-sio-t6030-test.dtso +F: drivers/dma/apple-sio-test.c F: drivers/dma/apple-sio.c F: sound/soc/apple/* F: sound/soc/codecs/cs42l83-i2c.c diff --git a/Makefile b/Makefile index be413b167b2443..4b60c83ab75c17 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 VERSION = 7 PATCHLEVEL = 2 -SUBLEVEL = 10 +SUBLEVEL = 11 EXTRAVERSION = NAME = Baby Opossum Posse diff --git a/arch/arm64/boot/dts/apple/t6030-dcp.dtsi b/arch/arm64/boot/dts/apple/t6030-dcp.dtsi index 9dacebbc8de10d..461533b3dc3826 100644 --- a/arch/arm64/boot/dts/apple/t6030-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t6030-dcp.dtsi @@ -144,8 +144,14 @@ <&atcphy2 PHY_TYPE_DP>; phy-names = "typec0", "typec1", "typec2"; mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>, - <&atcphy2_xbar 0>; - mux-control-names = "typec0", "typec1", "typec2"; + <&atcphy2_xbar 0>, + <&atcphy0_xbar 1>, <&atcphy0_xbar 2>, + <&atcphy1_xbar 1>, <&atcphy1_xbar 2>, + <&atcphy2_xbar 1>, <&atcphy2_xbar 2>; + mux-control-names = "typec0", "typec1", "typec2", + "typec0-dpin0", "typec0-dpin1", + "typec1-dpin0", "typec1-dpin1", + "typec2-dpin0", "typec2-dpin1"; apple,connector-type = "USB-C"; apple,dcp-index = <1>; apple,typec-dptx-phys = <0 1 2>; @@ -243,8 +249,14 @@ <&atcphy2 PHY_TYPE_DP>; phy-names = "typec0", "typec1", "typec2"; mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>, - <&atcphy2_xbar 0>; - mux-control-names = "typec0", "typec1", "typec2"; + <&atcphy2_xbar 0>, + <&atcphy0_xbar 1>, <&atcphy0_xbar 2>, + <&atcphy1_xbar 1>, <&atcphy1_xbar 2>, + <&atcphy2_xbar 1>, <&atcphy2_xbar 2>; + mux-control-names = "typec0", "typec1", "typec2", + "typec0-dpin0", "typec0-dpin1", + "typec1-dpin0", "typec1-dpin1", + "typec2-dpin0", "typec2-dpin1"; apple,connector-type = "USB-C"; apple,dcp-index = <2>; apple,typec-dptx-phys = <0 1 2>; diff --git a/arch/arm64/boot/dts/apple/t6030-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6030-pmgr.dtsi index 36050ececce29f..6be636c3577bed 100644 --- a/arch/arm64/boot/dts/apple/t6030-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t6030-pmgr.dtsi @@ -197,7 +197,11 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "sio_cpu"; - power-domains = <&ps_sio>; + /* + * The SIO firmware sets up the SPI, UART and audio DMA shims + * however few of them its clients use. + */ + power-domains = <&ps_sio &ps_uart_p &ps_spi_p &ps_audio_p>; }; ps_fpwm0: power-controller@1d8 { diff --git a/arch/arm64/boot/dts/apple/t6030.dtsi b/arch/arm64/boot/dts/apple/t6030.dtsi index 557949060da4cb..cedc08f69e1d3d 100644 --- a/arch/arm64/boot/dts/apple/t6030.dtsi +++ b/arch/arm64/boot/dts/apple/t6030.dtsi @@ -585,6 +585,33 @@ power-domains = <&ps_sio>; }; + sio_mbox: mbox@289c08000 { + compatible = "apple,t6030-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x2 0x89c08000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + power-domains = <&ps_sio_cpu>; + status = "disabled"; + }; + + /* Enabled by the boot loader with its firmware and parameters. */ + sio: sio@289c00000 { + compatible = "apple,t6030-sio", "apple,sio"; + reg = <0x2 0x89c00000 0x0 0x8000>; + dma-channels = <128>; + #dma-cells = <1>; + mboxes = <&sio_mbox>; + iommus = <&sio_dart 0>; + power-domains = <&ps_sio_cpu>; + status = "disabled"; + }; + admac: dma-controller@28b200000 { compatible = "apple,t6030-admac", "apple,t8122-admac"; reg = <0x2 0x8b200000 0x0 0x34000>; diff --git a/arch/arm64/boot/dts/apple/t603x-j514s-j516s-hdmi.dtsi b/arch/arm64/boot/dts/apple/t603x-j514s-j516s-hdmi.dtsi index 0a92185de199d7..10314dba091bc4 100644 --- a/arch/arm64/boot/dts/apple/t603x-j514s-j516s-hdmi.dtsi +++ b/arch/arm64/boot/dts/apple/t603x-j514s-j516s-hdmi.dtsi @@ -10,8 +10,20 @@ * * The processor stays a hybrid pipeline: while no HDMI display is attached * it can still be lent to a USB-C port. + * + * The HDMI port's audio is the processor's audio service with DPA1, the + * DisplayPort audio interface its port@0 links (no AP-side registers): SIO + * channel 0x66 carries the samples, as on the M1 Pro/Max HDMI port. The + * loader reserves the SIO firmware and enables the SIO with its parameters. */ +/ { + aliases { + /* The boot loader looks the SIO up by this alias. */ + sio = &sio; + }; +}; + &atcphy3 { status = "okay"; @@ -44,8 +56,14 @@ <&atcphy1 PHY_TYPE_DP>, <&atcphy2 PHY_TYPE_DP>; phy-names = "dp-phy", "typec0", "typec1", "typec2"; mux-controls = <&atcphy3_xbar 0>, <&atcphy0_xbar 0>, - <&atcphy1_xbar 0>, <&atcphy2_xbar 0>; - mux-control-names = "dp-xbar", "typec0", "typec1", "typec2"; + <&atcphy1_xbar 0>, <&atcphy2_xbar 0>, + <&atcphy0_xbar 1>, <&atcphy0_xbar 2>, + <&atcphy1_xbar 1>, <&atcphy1_xbar 2>, + <&atcphy2_xbar 1>, <&atcphy2_xbar 2>; + mux-control-names = "dp-xbar", "typec0", "typec1", "typec2", + "typec0-dpin0", "typec0-dpin1", + "typec1-dpin0", "typec1-dpin1", + "typec2-dpin0", "typec2-dpin1"; mux-index = <0>; apple,dptx-phy = <3>; @@ -53,6 +71,13 @@ #address-cells = <1>; #size-cells = <0>; + port@0 { + reg = <0>; + dcpext_audio: endpoint { + remote-endpoint = <&dpaudio1_dcpext>; + }; + }; + port@1 { reg = <1>; dcpext_dpout: endpoint { @@ -62,6 +87,33 @@ }; }; +/* DPA1: the HDMI port's DisplayPort audio, SIO channel 0x66. */ +&soc { + dpaudio1: audio-controller-1 { + compatible = "apple,t6030-dpaudio", "apple,dpaudio"; + dmas = <&sio 0x66>; + dma-names = "tx"; + power-domains = <&ps_dpa1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + dpaudio1_dcpext: endpoint { + remote-endpoint = <&dcpext_audio>; + }; + }; + }; + }; +}; + +/* The SIO's mailbox; the boot loader enables the SIO with its firmware. */ +&sio_mbox { + status = "okay"; +}; + /* * ATC3 has no USB consumer that would hold its common block on, so across * system sleep it would power down and lose the HDMI PHY state. diff --git a/arch/arm64/boot/dts/freescale/fsl-lx2160a.dtsi b/arch/arm64/boot/dts/freescale/fsl-lx2160a.dtsi index 1d73abffa6b72b..6ead557a8cf19f 100644 --- a/arch/arm64/boot/dts/freescale/fsl-lx2160a.dtsi +++ b/arch/arm64/boot/dts/freescale/fsl-lx2160a.dtsi @@ -1783,7 +1783,7 @@ }; dspi2_miso_mosi_pins: iic5-spi3-pins { - pinctrl-single,bits = <0x3 (0x2 << 9) (0x7 << 9)>; + pinctrl-single,bits = <0x0 (0x3 << 9) (0x7 << 9)>; }; i2c5_pins: iic6-i2c-pins { @@ -1803,7 +1803,7 @@ }; gpio1_31_28_pins: xspi1-data74-gpio-pins { - pinctrl-single,bits = <0x0 0x1 (0x7 << 15)>; + pinctrl-single,bits = <0x0 (0x1 << 15) (0x7 << 15)>; }; fspi_data30_pins: xspi1-data30-pins { @@ -1811,7 +1811,7 @@ }; gpio1_27_24_pins: xspi1-data30-gpio-pins { - pinctrl-single,bits = <0x0 0x1 (0x7 << 18)>; + pinctrl-single,bits = <0x0 (0x1 << 18) (0x7 << 18)>; }; fspi_dqs_sck_cs10_pins: xspi1-base-pins { @@ -1819,7 +1819,7 @@ }; gpio1_23_20_pins: xspi1-base-gpio-pins { - pinctrl-single,bits = <0x0 0x1 (0x7 << 21)>; + pinctrl-single,bits = <0x0 (0x1 << 21) (0x7 << 21)>; }; esdhc0_cmd_data30_clk_vsel_pins: sdhc1-base-sdhc-vsel-pins { @@ -1868,12 +1868,19 @@ }; /* RCWSR14 */ + /* + * IIC1_PMUX is a single bit at RCWSR14[10], but bit-per-mux + * uses the mask for the field to clear before applying the + * value. + * So bits 11 and 12, which are reserved, are written as 0 + * on every mux switch, it is harmless. + */ i2c0_pins: iic1-i2c-pins { - pinctrl-single,bits = <0x8 0x0 (0x1 << 10)>; + pinctrl-single,bits = <0x8 0x0 (0x7 << 10)>; }; gpio0_3_2_pins: iic1-gpio-pins { - pinctrl-single,bits = <0x8 (0x1 << 10) (0x1 << 10)>; + pinctrl-single,bits = <0x8 (0x1 << 10) (0x7 << 10)>; }; }; diff --git a/arch/arm64/configs/asahi.config b/arch/arm64/configs/asahi.config index fdff6b4acb02ca..98f9a98ab90285 100644 --- a/arch/arm64/configs/asahi.config +++ b/arch/arm64/configs/asahi.config @@ -73,13 +73,13 @@ CONFIG_USB_DWC3_APPLE=m CONFIG_TYPEC=m CONFIG_USB4=m CONFIG_USB4_APPLE_SOC=m -CONFIG_RESET_APPLE_CIO=y CONFIG_USB_XHCI_PCI_ASMEDIA=y CONFIG_TYPEC_SN201202X=m CONFIG_RTC_DRV_MACSMC=m CONFIG_RTC_DRV_APPLE_PMU=m CONFIG_APPLE_ADMAC=m CONFIG_APPLE_SIO=m +CONFIG_APPLE_SIO_T6030=y CONFIG_MFD_MACSMC=m CONFIG_COMMON_CLK_APPLE_NCO=m CONFIG_APPLE_DART=y @@ -113,6 +113,8 @@ CONFIG_APPLE_M1_CPU_PMU=y CONFIG_NVMEM_APPLE_EFUSES=m CONFIG_NVMEM_APPLE_SPMI=m CONFIG_MUX_APPLE_DPXBAR=m +CONFIG_TYPEC_TPS6598X=m +CONFIG_RESET_APPLE_CIO=y CONFIG_INFINIBAND=m CONFIG_INFINIBAND_USER_ACCESS=m CONFIG_INFINIBAND_USER_MAD=m diff --git a/arch/arm64/include/asm/el2_setup.h b/arch/arm64/include/asm/el2_setup.h index 87560d8b254e67..1da277baacf78c 100644 --- a/arch/arm64/include/asm/el2_setup.h +++ b/arch/arm64/include/asm/el2_setup.h @@ -421,8 +421,9 @@ mov x2, xzr mrs x1, id_aa64dfr0_el1 ubfx x1, x1, #ID_AA64DFR0_EL1_PMUVer_SHIFT, #4 - cmp x1, #ID_AA64DFR0_EL1_PMUVer_V3P9 - b.lt .Lskip_pmuv3p9_\@ + cmp x1, #ID_AA64DFR0_EL1_PMUVer_IMP_DEF + ccmp x1, #ID_AA64DFR0_EL1_PMUVer_V3P9, #8, ne + b.lt .Lskip_pmuv3p9_\@ // Skip if < PMUv3p9 or IMP_DEF orr x0, x0, #HDFGRTR2_EL2_nPMICNTR_EL0 orr x0, x0, #HDFGRTR2_EL2_nPMICFILTR_EL0 diff --git a/arch/arm64/kernel/Makefile b/arch/arm64/kernel/Makefile index cfc2122819d1df..4b9ff74af30914 100644 --- a/arch/arm64/kernel/Makefile +++ b/arch/arm64/kernel/Makefile @@ -25,6 +25,9 @@ KASAN_SANITIZE_stacktrace.o := n KCOV_INSTRUMENT_entry-common.o := n KCOV_INSTRUMENT_idle.o := n +# Softirq stack switching can run outside interrupt context. +KCOV_INSTRUMENT_irq.o := n + # Object file lists. obj-y := debug-monitors.o entry.o irq.o fpsimd.o \ entry-common.o process.o ptrace.o \ diff --git a/arch/arm64/mm/flush.c b/arch/arm64/mm/flush.c index fbf08b543c3fd0..8f106e38ac9e40 100644 --- a/arch/arm64/mm/flush.c +++ b/arch/arm64/mm/flush.c @@ -15,6 +15,9 @@ #include #include +/* Explicit publication of retained coprocessor page tables before ASC start (asahi G15). */ +EXPORT_SYMBOL_GPL(dcache_clean_poc); + void sync_icache_aliases(unsigned long start, unsigned long end) { if (icache_is_aliasing()) { diff --git a/arch/arm64/mm/user4k-test.c b/arch/arm64/mm/user4k-test.c index 4f8d5ec709b77b..891222d058a406 100644 --- a/arch/arm64/mm/user4k-test.c +++ b/arch/arm64/mm/user4k-test.c @@ -1885,7 +1885,7 @@ static void user4k_vma_copy_shrink_test(struct kunit *test) struct vm_page_offset pos = vm_page_offset_add(initial, i == 2 ? 0 : (i + 1) * SZ_4K); mmap_write_lock(mm); - dest = copy_vma(&source, addr, SZ_4K, pos, &need_locks); + dest = copy_vma(&source, addr, SZ_4K, pos, &need_locks, false); mmap_write_unlock(mm); KUNIT_ASSERT_NOT_NULL(test, dest); KUNIT_EXPECT_EQ(test, mm->map_count, 2); diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig index f7028caaeae06e..e5166df510bb64 100644 --- a/arch/riscv/Kconfig +++ b/arch/riscv/Kconfig @@ -450,9 +450,10 @@ config SMP config NR_CPUS int "Maximum number of CPUs (2-512)" depends on SMP - range 2 512 if !RISCV_SBI_V01 - range 2 32 if RISCV_SBI_V01 && 32BIT + range 2 512 if !RISCV_SBI_V01 && 64BIT + range 2 128 if !RISCV_SBI_V01 && 32BIT range 2 64 if RISCV_SBI_V01 && 64BIT + range 2 32 if RISCV_SBI_V01 && 32BIT default "32" if 32BIT default "64" if RISCV_SBI_V01 && 64BIT default "256" if !RISCV_SBI_V01 && 64BIT diff --git a/arch/riscv/Kconfig.errata b/arch/riscv/Kconfig.errata index 3c945d086c7d02..6121ba83cfa6b6 100644 --- a/arch/riscv/Kconfig.errata +++ b/arch/riscv/Kconfig.errata @@ -146,6 +146,7 @@ config ERRATA_THEAD_PMU config ERRATA_THEAD_GHOSTWRITE bool "Apply T-Head Ghostwrite errata" depends on ERRATA_THEAD && RISCV_ISA_XTHEADVECTOR + select RISCV_ALTERNATIVE_EARLY default y help The T-Head C9xx cores have a vulnerability in the xtheadvector diff --git a/arch/riscv/include/asm/futex.h b/arch/riscv/include/asm/futex.h index 90c86b115e008a..6f3bc9bdb85e39 100644 --- a/arch/riscv/include/asm/futex.h +++ b/arch/riscv/include/asm/futex.h @@ -40,6 +40,7 @@ arch_futex_atomic_op_inuser(int op, int oparg, int *oval, u32 __user *uaddr) if (!access_ok(uaddr, sizeof(u32))) return -EFAULT; + uaddr = untagged_addr(uaddr); switch (op) { case FUTEX_OP_SET: @@ -82,6 +83,7 @@ futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr, if (!access_ok(uaddr, sizeof(u32))) return -EFAULT; + uaddr = untagged_addr(uaddr); __enable_user_access(); __asm__ __volatile__ ( diff --git a/arch/riscv/include/asm/scs.h b/arch/riscv/include/asm/scs.h index 023a412fe38d37..49e40eef4ed7b2 100644 --- a/arch/riscv/include/asm/scs.h +++ b/arch/riscv/include/asm/scs.h @@ -4,6 +4,7 @@ #ifdef __ASSEMBLER__ #include +#include #ifdef CONFIG_SHADOW_CALL_STACK @@ -22,9 +23,17 @@ REG_L gp, TASK_TI_SCS_SP(tp) .endm -/* Load task_scs_sp(current) to gp, but only if tp has changed. */ -.macro scs_load_current_if_task_changed prev - beq \prev, tp, _skip_scs +/* + * Load task_scs_sp(current) to gp, but only when the trap came from U-mode. + * The source privilege level is taken from the saved sstatus.SPP bit (written + * by hardware on trap entry), not by comparing tp. tp is a user-writable + * register, so gating the shadow call stack reload on it let a user task that + * set tp == ¤t skip the reload and run the kernel with an attacker + * controlled gp (the shadow call stack pointer). + */ +.macro scs_load_current_if_from_user status, tmp + andi \tmp, \status, SR_SPP + bnez \tmp, _skip_scs scs_load_current _skip_scs: .endm @@ -42,7 +51,7 @@ .endm .macro scs_load_current .endm -.macro scs_load_current_if_task_changed prev +.macro scs_load_current_if_from_user status, tmp .endm .macro scs_save_current .endm diff --git a/arch/riscv/include/asm/vector.h b/arch/riscv/include/asm/vector.h index 00cb9c0982b1ae..8d736e826d84d2 100644 --- a/arch/riscv/include/asm/vector.h +++ b/arch/riscv/include/asm/vector.h @@ -132,8 +132,8 @@ static __always_inline void __vstate_csr_save(struct __riscv_v_ext_state *dest) "csrr %0, " __stringify(CSR_VSTART) "\n\t" "csrr %1, " __stringify(CSR_VTYPE) "\n\t" "csrr %2, " __stringify(CSR_VL) "\n\t" - : "=r" (dest->vstart), "=r" (dest->vtype), "=r" (dest->vl), - "=r" (dest->vcsr) : :); + : "=r" (dest->vstart), "=r" (dest->vtype), "=r" (dest->vl) + : :); if (has_xtheadvector()) { unsigned long status; @@ -225,7 +225,7 @@ static inline void __riscv_v_vstate_save(struct __riscv_v_ext_state *save_to, "add %1, %1, %0\n\t" "vse8.v v24, (%1)\n\t" ".option pop\n\t" - : "=&r" (vl) : "r" (datap) : "memory"); + : "=&r" (vl), "+r" (datap) : : "memory"); } riscv_v_disable(); } @@ -261,7 +261,7 @@ static inline void __riscv_v_vstate_restore(struct __riscv_v_ext_state *restore_ "add %1, %1, %0\n\t" "vle8.v v24, (%1)\n\t" ".option pop\n\t" - : "=&r" (vl) : "r" (datap) : "memory"); + : "=&r" (vl), "+r" (datap) : : "memory"); } __vstate_csr_restore(restore_from); riscv_v_disable(); diff --git a/arch/riscv/include/uapi/asm/vendor/mips.h b/arch/riscv/include/uapi/asm/vendor/mips.h index e65ab268b26551..a31c23afe74fb2 100644 --- a/arch/riscv/include/uapi/asm/vendor/mips.h +++ b/arch/riscv/include/uapi/asm/vendor/mips.h @@ -1,3 +1,5 @@ /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ -#define RISCV_HWPROBE_VENDOR_EXT_XMIPSEXECTL BIT(0) +#include + +#define RISCV_HWPROBE_VENDOR_EXT_XMIPSEXECTL _BITULL(0) diff --git a/arch/riscv/kernel/entry.S b/arch/riscv/kernel/entry.S index d799c4e56f8049..61b7a77166971d 100644 --- a/arch/riscv/kernel/entry.S +++ b/arch/riscv/kernel/entry.S @@ -208,7 +208,7 @@ SYM_CODE_START(handle_exception) load_global_pointer /* Load the kernel shadow call stack pointer if coming from userspace */ - scs_load_current_if_task_changed s5 + scs_load_current_if_from_user s1, s5 #ifdef CONFIG_RISCV_ISA_V_PREEMPTIVE move a0, sp diff --git a/arch/riscv/kernel/patch.c b/arch/riscv/kernel/patch.c index 16b243376f3621..1e8f1ac5a755f9 100644 --- a/arch/riscv/kernel/patch.c +++ b/arch/riscv/kernel/patch.c @@ -46,7 +46,7 @@ static __always_inline void *patch_map(void *addr, const unsigned int fixmap) if (core_kernel_text(uintaddr) || is_kernel_exittext(uintaddr)) { phys = __pa_symbol(addr); - } else if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX)) { + } else if (IS_ENABLED(CONFIG_EXECMEM)) { struct page *page = vmalloc_to_page(addr); BUG_ON(!page); diff --git a/arch/riscv/kernel/ptrace.c b/arch/riscv/kernel/ptrace.c index f336a183667eb8..a0055743d3ba50 100644 --- a/arch/riscv/kernel/ptrace.c +++ b/arch/riscv/kernel/ptrace.c @@ -230,6 +230,7 @@ static int riscv_vr_set(struct task_struct *target, return -ENODATA; /* Copy rest of the vstate except datap */ + memset(&ptrace_vstate, 0, sizeof(ptrace_vstate)); ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &ptrace_vstate, 0, sizeof(struct __riscv_v_regset_state)); if (unlikely(ret)) @@ -299,6 +300,9 @@ static int riscv_cfi_get(struct task_struct *target, struct user_cfi_state user_cfi; struct pt_regs *regs; + if (!is_user_lpad_enabled() && !is_user_shstk_enabled()) + return -EINVAL; + memset(&user_cfi, 0, sizeof(user_cfi)); regs = task_pt_regs(target); @@ -337,8 +341,12 @@ static int riscv_cfi_set(struct task_struct *target, struct user_cfi_state user_cfi; struct pt_regs *regs; + if (!is_user_lpad_enabled() && !is_user_shstk_enabled()) + return -EINVAL; + regs = task_pt_regs(target); + memset(&user_cfi, 0, sizeof(user_cfi)); ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &user_cfi, 0, -1); if (ret) return ret; diff --git a/arch/riscv/lib/strnlen.S b/arch/riscv/lib/strnlen.S index a8911605c24801..5b3bbf0a30987a 100644 --- a/arch/riscv/lib/strnlen.S +++ b/arch/riscv/lib/strnlen.S @@ -87,9 +87,25 @@ strnlen_zbb: * Aligned boundary. Use the address of the last valid byte * (s + count - 1) to avoid loading a word past the count * boundary in the loop below. count == 0 is handled above. + * + * Saturate the boundary when s + count would wrap around (very + * large counts, e.g. SIZE_MAX passed by FORTIFY strcat/strlcat + * with a destination whose size is unknown at compile time). + * Without this, the wrapped boundary lands before s and the + * pre-loop guard below always exits, returning a truncated + * length. + * + * Clamping the increment to ~s (== SIZE_MAX - s) keeps the + * computation branchless and wrap-free: + * + * s + min(count - 1, ~s) == saturating_add(s, count - 1) + * + * Saturating makes the scan equivalent to strlen(). */ - add t4, a0, a1 - addi t4, t4, -1 + addi t4, a1, -1 /* count - 1 */ + not t1, a0 /* SIZE_MAX - s */ + minu t4, t4, t1 /* clamp, so s + t4 can never wrap */ + add t4, a0, t4 /* saturated s + count - 1 */ andi t4, t4, -SZREG /* Get the first word. */ diff --git a/arch/riscv/mm/extable.c b/arch/riscv/mm/extable.c index dd1530af3ef15b..e252eba55edece 100644 --- a/arch/riscv/mm/extable.c +++ b/arch/riscv/mm/extable.c @@ -68,8 +68,8 @@ ex_handler_load_unaligned_zeropad(const struct exception_table_entry *ex, addr = regs_get_gpr(regs, reg_addr * sizeof(unsigned long)); - offset = addr & 0x7UL; - addr &= ~0x7UL; + offset = addr & (sizeof(data) - 1); + addr &= ~(sizeof(data) - 1); data = *(unsigned long *)addr >> (offset * 8); diff --git a/arch/um/drivers/vector_transports.c b/arch/um/drivers/vector_transports.c index ddd127ee96785d..e1fb2a76fdff59 100644 --- a/arch/um/drivers/vector_transports.c +++ b/arch/um/drivers/vector_transports.c @@ -209,6 +209,7 @@ static int raw_verify_header( if ((vheader->flags & VIRTIO_NET_HDR_F_DATA_VALID) > 0) return 1; + skb_set_network_header(skb, ETH_HLEN); virtio_net_hdr_to_skb(skb, vheader, virtio_legacy_is_little_endian()); return 0; } diff --git a/arch/x86/include/asm/cpufeatures.h b/arch/x86/include/asm/cpufeatures.h index 1b4a48bff18f75..caca69a4e6d5a4 100644 --- a/arch/x86/include/asm/cpufeatures.h +++ b/arch/x86/include/asm/cpufeatures.h @@ -465,6 +465,8 @@ #define X86_FEATURE_NO_NESTED_DATA_BP (20*32+ 0) /* No Nested Data Breakpoints */ #define X86_FEATURE_WRMSR_XX_BASE_NS (20*32+ 1) /* WRMSR to {FS,GS,KERNEL_GS}_BASE is non-serializing */ #define X86_FEATURE_LFENCE_RDTSC (20*32+ 2) /* LFENCE always serializing / synchronizes RDTSC */ + +#define X86_FEATURE_TLBSYNC_SFW_NO (20*32+ 4) /* TLBI Erratum #1718 fixed in microcode */ #define X86_FEATURE_VERW_CLEAR (20*32+ 5) /* The memory form of VERW mitigates TSA */ #define X86_FEATURE_NULL_SEL_CLR_BASE (20*32+ 6) /* Null Selector Clears Base */ @@ -575,4 +577,5 @@ #define X86_BUG_TSA X86_BUG( 1*32+ 9) /* "tsa" CPU is affected by Transient Scheduler Attacks */ #define X86_BUG_VMSCAPE X86_BUG( 1*32+10) /* "vmscape" CPU is affected by VMSCAPE attacks from guests */ #define X86_BUG_SEAMRET_INVD_VMCS X86_BUG( 1*32+11) /* "seamret_invd_vmcs" SEAMRET from P-SEAMLDR clears the current VMCS */ +#define X86_BUG_TLBI X86_BUG( 1*32+12) /* "tlbi" AMD TLBI Erratum #1718 */ #endif /* _ASM_X86_CPUFEATURES_H */ diff --git a/arch/x86/include/asm/tlb.h b/arch/x86/include/asm/tlb.h index 866ea78ba156ae..eba925c85f522b 100644 --- a/arch/x86/include/asm/tlb.h +++ b/arch/x86/include/asm/tlb.h @@ -110,6 +110,12 @@ static inline void __tlbsync(void) /* TLBSYNC: supported in binutils >= 0.36. */ asm volatile(".byte 0x0f, 0x01, 0xff" ::: "memory"); + + if (!static_cpu_has_bug(X86_BUG_TLBI)) + return; + + /* TLBSYNC: supported in binutils >= 0.36. */ + asm volatile(".byte 0x0f, 0x01, 0xff" ::: "memory"); } #else /* Some compilers (I'm looking at you clang!) simply can't do DCE */ diff --git a/arch/x86/kernel/cpu/amd.c b/arch/x86/kernel/cpu/amd.c index d61df70d6875ef..89e3280475a9d9 100644 --- a/arch/x86/kernel/cpu/amd.c +++ b/arch/x86/kernel/cpu/amd.c @@ -1047,6 +1047,10 @@ static void init_amd_zen5(struct cpuinfo_x86 *c) msr_clear_bit(MSR_AMD64_CPUID_FN_7, 18); pr_emerg_once("RDSEED32 is broken. Disabling the corresponding CPUID bit.\n"); } + + if (cpu_has(c, X86_FEATURE_INVLPGB) && + !cpu_has(c, X86_FEATURE_TLBSYNC_SFW_NO)) + set_cpu_bug(c, X86_BUG_TLBI); } static void init_amd(struct cpuinfo_x86 *c) diff --git a/drivers/android/binder/node.rs b/drivers/android/binder/node.rs index c10148e9069f3b..8f7aa867ce68bc 100644 --- a/drivers/android/binder/node.rs +++ b/drivers/android/binder/node.rs @@ -49,9 +49,9 @@ pub(crate) struct CouldNotDeliverCriticalIncrement; /// about to drop the weak reference, then the strong increment could be processed after the /// other thread has already exited, which would be too late. /// -/// Note that trying to create a `ListArc` to the node can succeed even if `has_normal_push` is +/// Note that trying to create a `ListArc` to the node can succeed even if `has_pushed_node` is /// set. This is because another thread might just have popped the node from a todo list, but not -/// yet called `do_work`. However, if `has_normal_push` is false, then creating a `ListArc` should +/// yet called `do_work`. However, if `has_pushed_node` is false, then creating a `ListArc` should /// always succeed. /// /// Like the other fields in `NodeInner`, the delivery state is protected by the process lock. @@ -733,7 +733,21 @@ impl DeliverToRead for Node { self.do_work_locked(writer, owner_inner) } - fn cancel(self: DArc) {} + fn cancel(self: DArc) { + let _drop_outside_lock; + let mut owner_inner = self.owner.inner.lock(); + + // We only do something on BINDER_THREAD_EXIT, not process exit. + if owner_inner.is_dead { + return; + } + + // If BINDER_THREAD_EXIT is invoked on a thread with a pending node refcount update, we + // should move ourselves to ensure the refcount update is still delivered. + if let Some(node) = ListArc::try_from_arc_borrow(self.as_arc_borrow()) { + _drop_outside_lock = owner_inner.push_work(node); + } + } fn should_sync_wakeup(&self) -> bool { false diff --git a/drivers/android/binder/node/wrapper.rs b/drivers/android/binder/node/wrapper.rs index 43294c05050292..aeda07ff7218bc 100644 --- a/drivers/android/binder/node/wrapper.rs +++ b/drivers/android/binder/node/wrapper.rs @@ -57,7 +57,39 @@ impl DeliverToRead for NodeWrapper { node.do_work_locked(writer, owner_inner) } - fn cancel(self: DArc) {} + fn cancel(self: DArc) { + let _drop_outside_lock; + let node = &self.node; + let mut owner_inner = node.owner.inner.lock(); + + // We only do something on BINDER_THREAD_EXIT, not process exit. + if owner_inner.is_dead { + return; + } + + // We transfer the responsibility of the node refcount update to the scheduled Node because + // NodeWrapper has no way to re-create the ListArc. + let inner = node.inner.access_mut(&mut owner_inner); + + let ds = &mut inner.delivery_state; + assert!(ds.has_pushed_wrapper); + assert!(ds.has_strong_zero2one); + ds.has_pushed_wrapper = false; + + // We are changing the state to one where the Node is the strong zero2one update instead of + // the wrapper. + ds.has_weak_zero2one = false; + + if !ds.has_pushed_node { + if let Some(node2) = ListArc::try_from_arc_borrow(node.as_arc_borrow()) { + ds.has_pushed_node = true; + _drop_outside_lock = owner_inner.push_work(node2); + } else { + // This can't actually happen. + ds.has_strong_zero2one = false; + } + } + } fn should_sync_wakeup(&self) -> bool { false diff --git a/drivers/ata/libata-scsi.c b/drivers/ata/libata-scsi.c index 3559485b503495..d06062abca9cef 100644 --- a/drivers/ata/libata-scsi.c +++ b/drivers/ata/libata-scsi.c @@ -3026,10 +3026,15 @@ static void atapi_qc_complete(struct ata_queued_cmd *qc) if (qc->cdb[0] == ALLOW_MEDIUM_REMOVAL && qc->dev->sdev) qc->dev->sdev->locked = 0; - if (cmd->result) - ata_scsi_qc_done(qc, false, 0); - else - ata_scsi_qc_done(qc, true, SAM_STAT_CHECK_CONDITION); + /* + * Report CHECK CONDITION unless the command was terminated + * with a host byte set. Only set the status byte, so that the + * SCSI midlayer internal byte, which scsi_check_sense() may + * have set from the sense data, is preserved. + */ + if (get_host_byte(cmd) == DID_OK) + set_status_byte(cmd, SAM_STAT_CHECK_CONDITION); + ata_scsi_qc_done(qc, false, 0); goto schedule_deferred; } diff --git a/drivers/block/zloop.c b/drivers/block/zloop.c index 1333fae05ac5dd..a011f3e518a551 100644 --- a/drivers/block/zloop.c +++ b/drivers/block/zloop.c @@ -799,6 +799,27 @@ static void zloop_cmd_workfn(struct work_struct *work) current->flags = orig_flags; } +static void zloop_fill_zero_rq(struct request *rq, unsigned int zero_from) +{ + struct req_iterator iter; + struct bio_vec bv; + unsigned int pos = 0; + unsigned int end, off; + + rq_for_each_segment(bv, rq, iter) { + end = pos + bv.bv_len; + if (end > zero_from) { + if (pos < zero_from) + off = zero_from - pos; + else + off = 0; + memzero_page(bv.bv_page, bv.bv_offset + off, + bv.bv_len - off); + } + pos = end; + } +} + static void zloop_complete_rq(struct request *rq) { struct zloop_cmd *cmd = blk_mq_rq_to_pdu(rq); @@ -813,13 +834,9 @@ static void zloop_complete_rq(struct request *rq) pr_err("Zone %u: failed read sector %llu, %llu sectors\n", zone_no, cmd->sector, cmd->nr_sectors); - if (cmd->ret >= 0 && cmd->ret != blk_rq_bytes(rq)) { - /* short read */ - struct bio *bio; - - __rq_for_each_bio(bio, rq) - zero_fill_bio(bio); - } + /* Short read. Zero out the unread tail beyond cmd->ret. */ + if (cmd->ret >= 0 && cmd->ret != blk_rq_bytes(rq)) + zloop_fill_zero_rq(rq, cmd->ret); break; case REQ_OP_WRITE: case REQ_OP_ZONE_APPEND: diff --git a/drivers/bluetooth/btintel_pcie.c b/drivers/bluetooth/btintel_pcie.c index fdc1fd2586b9ec..ed4ba2e469ac79 100644 --- a/drivers/bluetooth/btintel_pcie.c +++ b/drivers/bluetooth/btintel_pcie.c @@ -401,7 +401,7 @@ static int btintel_pcie_send_sync(struct btintel_pcie_data *data, tfd_index = data->ia.tr_hia[BTINTEL_PCIE_TXQ_NUM]; - if (tfd_index > txq->count) + if (tfd_index >= txq->count) return -ERANGE; if (skb->len > BTINTEL_PCIE_BUFFER_SIZE - BTINTEL_PCIE_HCI_TYPE_LEN) { @@ -1715,7 +1715,7 @@ static irqreturn_t btintel_pcie_irq_msix_handler(int irq, void *dev_id) static int btintel_pcie_setup_irq(struct btintel_pcie_data *data) { int err; - int num_irqs, i; + int num_irqs, i, j; for (i = 0; i < BTINTEL_PCIE_MSIX_VEC_MAX; i++) data->msix_entries[i].entry = i; @@ -1744,6 +1744,10 @@ static int btintel_pcie_setup_irq(struct btintel_pcie_data *data) KBUILD_MODNAME, msix_entry); if (err) { + for (j = 0; j < i; j++) + devm_free_irq(&data->pdev->dev, + data->msix_entries[j].vector, + &data->msix_entries[j]); pci_free_irq_vectors(data->pdev); data->alloc_vecs = 0; return err; @@ -1815,6 +1819,13 @@ static int btintel_pcie_config_pcie(struct pci_dev *pdev, if (IS_ERR(data->base_addr)) return PTR_ERR(data->base_addr); + /* Do shared hardware reset to ensure a clean start before + * configuring interrupts. + */ + err = btintel_pcie_reset_bt(data); + if (err) + return err; + err = btintel_pcie_setup_irq(data); if (err) return err; @@ -3003,7 +3014,7 @@ static void btintel_pcie_remove(struct pci_dev *pdev) struct msix_entry *msix_entry; msix_entry = &data->msix_entries[i]; - free_irq(msix_entry->vector, msix_entry); + devm_free_irq(&pdev->dev, msix_entry->vector, msix_entry); } pci_free_irq_vectors(pdev); diff --git a/drivers/clk/qcom/gcc-eliza.c b/drivers/clk/qcom/gcc-eliza.c index 3e26c7a1e5b546..fe18942a59ac45 100644 --- a/drivers/clk/qcom/gcc-eliza.c +++ b/drivers/clk/qcom/gcc-eliza.c @@ -3010,8 +3010,6 @@ static const u32 gcc_eliza_critical_cbcrs[] = { 0x26034, /* GCC_CAMERA_XO_CLK */ 0x27004, /* GCC_DISP_AHB_CLK */ 0x71004, /* GCC_GPU_CFG_AHB_CLK */ - 0x52010, /* GCC_PCIE_RSCC_CFG_AHB_CLK */ - 0x52010, /* GCC_PCIE_RSCC_XO_CLK */ 0x32004, /* GCC_VIDEO_AHB_CLK */ 0x32038, /* GCC_VIDEO_XO_CLK */ }; @@ -3045,6 +3043,10 @@ static const struct regmap_config gcc_eliza_regmap_config = { static void clk_eliza_regs_configure(struct device *dev, struct regmap *regmap) { + /* Keep clocks always enabled */ + regmap_update_bits(regmap, 0x52010, BIT(20), BIT(20)); /* GCC_PCIE_RSCC_CFG_AHB_CLK */ + regmap_update_bits(regmap, 0x52010, BIT(21), BIT(21)); /* GCC_PCIE_RSCC_XO_CLK */ + /* FORCE_MEM_CORE_ON for ufs phy ice core and gcc ufs phy axi clocks */ qcom_branch_set_force_mem_core(regmap, gcc_ufs_phy_ice_core_clk, true); qcom_branch_set_force_mem_core(regmap, gcc_ufs_phy_axi_clk, true); diff --git a/drivers/clk/qcom/gcc-kaanapali.c b/drivers/clk/qcom/gcc-kaanapali.c index 842c1a70c69168..5bcbcd17865774 100644 --- a/drivers/clk/qcom/gcc-kaanapali.c +++ b/drivers/clk/qcom/gcc-kaanapali.c @@ -3464,8 +3464,6 @@ static const u32 gcc_kaanapali_critical_cbcrs[] = { 0x9f004, /* GCC_EVA_AHB_CLK */ 0x9f024, /* GCC_EVA_XO_CLK */ 0x71004, /* GCC_GPU_CFG_AHB_CLK */ - 0x52010, /* GCC_PCIE_RSCC_CFG_AHB_CLK */ - 0x52010, /* GCC_PCIE_RSCC_XO_CLK */ 0x32004, /* GCC_VIDEO_AHB_CLK */ 0x32040, /* GCC_VIDEO_XO_CLK */ }; @@ -3480,6 +3478,10 @@ static const struct regmap_config gcc_kaanapali_regmap_config = { static void clk_kaanapali_regs_configure(struct device *dev, struct regmap *regmap) { + /* Keep clocks always enabled */ + regmap_update_bits(regmap, 0x52010, BIT(20), BIT(20)); /* GCC_PCIE_RSCC_CFG_AHB_CLK */ + regmap_update_bits(regmap, 0x52010, BIT(21), BIT(21)); /* GCC_PCIE_RSCC_XO_CLK */ + /* FORCE_MEM_CORE_ON for ufs phy ice core clocks */ qcom_branch_set_force_mem_core(regmap, gcc_ufs_phy_ice_core_clk, true); } diff --git a/drivers/clk/qcom/gpucc-glymur.c b/drivers/clk/qcom/gpucc-glymur.c index 001b2454786a0c..cac51de20b2950 100644 --- a/drivers/clk/qcom/gpucc-glymur.c +++ b/drivers/clk/qcom/gpucc-glymur.c @@ -510,7 +510,7 @@ static struct gdsc gpu_cc_cx_gdsc = { .name = "gpu_cc_cx_gdsc", }, .pwrsts = PWRSTS_OFF_ON, - .flags = POLL_CFG_GDSCR | RETAIN_FF_ENABLE, + .flags = RETAIN_FF_ENABLE | VOTABLE, }; static struct clk_regmap *gpu_cc_glymur_clocks[] = { diff --git a/drivers/clk/qcom/gpucc-kaanapali.c b/drivers/clk/qcom/gpucc-kaanapali.c index ae5563e516f677..f75f2caa2205c4 100644 --- a/drivers/clk/qcom/gpucc-kaanapali.c +++ b/drivers/clk/qcom/gpucc-kaanapali.c @@ -380,7 +380,7 @@ static struct gdsc gpu_cc_cx_gdsc = { .name = "gpu_cc_cx_gdsc", }, .pwrsts = PWRSTS_OFF_ON, - .flags = POLL_CFG_GDSCR | RETAIN_FF_ENABLE, + .flags = RETAIN_FF_ENABLE | VOTABLE, }; static struct clk_regmap *gpu_cc_kaanapali_clocks[] = { diff --git a/drivers/dma/Kconfig b/drivers/dma/Kconfig index b65fcd35fa6898..94f9c2e2860d95 100644 --- a/drivers/dma/Kconfig +++ b/drivers/dma/Kconfig @@ -99,10 +99,45 @@ config APPLE_SIO depends on APPLE_RTKIT depends on OF_ADDRESS select DMA_ENGINE + select DMA_VIRTUAL_CHANNELS help Enable support for the SIO coprocessor found on Apple Silicon SoCs where it provides DMA services. +config APPLE_SIO_KUNIT_TEST + bool "KUnit tests for the Apple SIO probe" if !KUNIT_ALL_TESTS + depends on APPLE_SIO=y && KUNIT=y + depends on OF_OVERLAY + default KUNIT_ALL_TESTS + help + Check which SIO device-tree nodes the probe goes on with: the + generic SIO of the M1 and M2 in every configuration, and a T6030 + SIO only with APPLE_SIO_T6030 and protocol-10 boot tables. Run it + both with and without APPLE_SIO_T6030. + +config APPLE_SIO_T6030 + bool "Apple SIO on the M3 Pro (T6030)" + depends on APPLE_SIO + help + Configure the SIO channels of the T6030 (apple,t6030-sio) the way + its firmware expects them: the DisplayPort audio channels refill + their FIFO at the threshold the system's device tree records for + them (0x600 bytes, not 0x800), and every period descriptor is + published whole. The firmware's boot tables come from the boot + loader, as on the other SoCs; the SIO is only started when they + are protocol-10 tables, which a boot loader without T6030 support + does not build. Without this option a T6030 SIO is left stopped. + +config APPLE_SIO_T6030_KUNIT_TEST + bool "KUnit tests for the T6030 SIO boot-table check" if !KUNIT_ALL_TESTS + depends on APPLE_SIO=y && APPLE_SIO_T6030 && KUNIT=y + depends on OF_OVERLAY + default KUNIT_ALL_TESTS + help + Check the protocol-10 boot-table admission of the T6030 SIO + against tables a T6030-aware boot loader builds, an earlier + loader's tables, and malformed, truncated and out-of-window ones. + config ARM_DMA350 tristate "Arm DMA-350 support" depends on ARM || ARM64 || COMPILE_TEST diff --git a/drivers/dma/Makefile b/drivers/dma/Makefile index edea48f908e96f..b3b59d224e1904 100644 --- a/drivers/dma/Makefile +++ b/drivers/dma/Makefile @@ -18,6 +18,8 @@ obj-$(CONFIG_AMBA_PL08X) += amba-pl08x.o obj-$(CONFIG_AMCC_PPC440SPE_ADMA) += ppc4xx/ obj-$(CONFIG_APPLE_ADMAC) += apple-admac.o obj-$(CONFIG_APPLE_SIO) += apple-sio.o +obj-$(CONFIG_APPLE_SIO_KUNIT_TEST) += apple-sio-probe-test.dtbo.o +obj-$(CONFIG_APPLE_SIO_T6030_KUNIT_TEST) += apple-sio-t6030-test.dtbo.o obj-$(CONFIG_ARM_DMA350) += arm-dma350.o obj-$(CONFIG_AT_HDMAC) += at_hdmac.o obj-$(CONFIG_AT_XDMAC) += at_xdmac.o diff --git a/drivers/dma/apple-sio-probe-test.c b/drivers/dma/apple-sio-probe-test.c new file mode 100644 index 00000000000000..7049c8acb532a3 --- /dev/null +++ b/drivers/dma/apple-sio-probe-test.c @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by apple-sio.c: which SIO nodes the probe goes on with, with and + * without APPLE_SIO_T6030. The test devices have no register range, so a probe + * that goes on toward the hardware stops there with -EINVAL; a refused node + * returns -ENODEV first. + */ +#include +#include +#include + +OF_OVERLAY_DECLARE(apple_sio_probe_test); + +static void sio_probe_nodes_test(struct kunit *test) +{ + const bool t6030 = IS_ENABLED(CONFIG_APPLE_SIO_T6030); + const struct { + const char *path; + int err; + } cases[] = { + /* M1/M2: the generic SIO, either way */ + { "/sio-probe-test/sio-probe-test-t8103", -EINVAL }, + /* T6030: only with its support built, and with protocol-10 tables */ + { "/sio-probe-test/sio-probe-test-t6030-v10", t6030 ? -EINVAL : -ENODEV }, + { "/sio-probe-test/sio-probe-test-t6030-earlier", -ENODEV }, + }; + unsigned int i; + + KUNIT_ASSERT_EQ(test, 0, of_overlay_apply_kunit(test, apple_sio_probe_test)); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + struct platform_device *pdev; + u64 mask; + + pdev = kunit_platform_device_alloc(test, "apple-sio-probe-test", i); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdev); + /* The device's release drops this reference */ + pdev->dev.of_node = of_find_node_by_path(cases[i].path); + KUNIT_ASSERT_NOT_NULL_MSG(test, pdev->dev.of_node, "%s", cases[i].path); + mask = pdev->dev.coherent_dma_mask; + KUNIT_EXPECT_EQ_MSG(test, sio_probe(pdev), cases[i].err, "%s", cases[i].path); + /* Without its support, a T6030 is refused before its DMA is set up */ + if (!t6030 && cases[i].err == -ENODEV) + KUNIT_EXPECT_EQ_MSG(test, pdev->dev.coherent_dma_mask, mask, "%s", + cases[i].path); + } +} + +static struct kunit_case sio_probe_test_cases[] = { + KUNIT_CASE(sio_probe_nodes_test), + {} +}; + +static struct kunit_suite sio_probe_test_suite = { + .name = "apple-sio-probe", + .test_cases = sio_probe_test_cases, +}; + +kunit_test_suite(sio_probe_test_suite); diff --git a/drivers/dma/apple-sio-probe-test.dtso b/drivers/dma/apple-sio-probe-test.dtso new file mode 100644 index 00000000000000..79f3346beaad8c --- /dev/null +++ b/drivers/dma/apple-sio-probe-test.dtso @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/dts-v1/; +/plugin/; + +/* + * SIO nodes for the probe test: an M1 one, and T6030 ones with the tables of a + * T6030-aware boot loader and of an earlier one. The container is not a bus, so + * nothing binds to them; the test calls the probe itself. + */ +&{/} { + sio-probe-test { + #address-cells = <2>; + #size-cells = <2>; + + sio-probe-test-t8103 { + compatible = "apple,t8103-sio", "apple,sio"; + dma-channels = <8>; + }; + + v10_w: v10-w { + iommu-addresses = <&v10 0x0 0x30000 0x0 0x4000>, <&v10 0x0 0x34000 0x0 0x20000>, + <&v10 0x0 0x54000 0x0 0x4000>, <&v10 0x0 0x58000 0x0 0x4000>; + }; + + v10: sio-probe-test-t6030-v10 { + compatible = "apple,t6030-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&v10_w>; + apple,sio-firmware-params = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + + old_w: old-w { iommu-addresses = <&earlier 0x0 0x30000 0x0 0x2c000>; }; + + earlier: sio-probe-test-t6030-earlier { + compatible = "apple,t6030-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&old_w>; + apple,sio-firmware-params = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xa0 + 0x1c 0x5a 0x1d 0x40>; + }; + }; +}; diff --git a/drivers/dma/apple-sio-t6030-test.dtso b/drivers/dma/apple-sio-t6030-test.dtso new file mode 100644 index 00000000000000..df42f31a2a8d13 --- /dev/null +++ b/drivers/dma/apple-sio-t6030-test.dtso @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/dts-v1/; +/plugin/; + +/* + * T6030 SIO nodes as boot loaders leave them: parameters in apple,sio-firmware-params and the + * firmware data mapped through memory regions with iommu-addresses. The v10 node carries the + * tables a T6030-aware loader builds; the earlier node the tables of a loader without + * protocol-10 support, in the same windows. The container is not a bus, so nothing binds to + * them; the probe test calls the probe itself, on a device without registers. + */ +&{/} { + sio-t6030-test { + #address-cells = <2>; + #size-cells = <2>; + + v10_w0: v10-w0 { iommu-addresses = <&v10 0x0 0x30000 0x0 0x4000>; }; + v10_w1: v10-w1 { iommu-addresses = <&v10 0x0 0x34000 0x0 0x20000>; }; + v10_w2: v10-w2 { iommu-addresses = <&v10 0x0 0x54000 0x0 0x4000>; }; + v10_w3: v10-w3 { iommu-addresses = <&v10 0x0 0x58000 0x0 0x4000>; }; + + v10: sio-t6030-test-v10 { + compatible = "apple,t6030-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&v10_w0 &v10_w1 &v10_w2 &v10_w3>; + apple,sio-firmware-params = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + + old_w: old-w { iommu-addresses = <&earlier 0x0 0x30000 0x0 0x2c000>; }; + + earlier: sio-t6030-test-earlier { + compatible = "apple,t6030-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&old_w>; + apple,sio-firmware-params = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xa0 + 0x1c 0x5a 0x1d 0x40>; + }; + + sio-t6030-test-unmapped { + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + + other_w: other-w { iommu-addresses = <&v10 0x0 0x30000 0x0 0x2c000>; }; + + sio-t6030-test-other-owner { + memory-region = <&other_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + + nop_w: nop-w { iommu-addresses = <&no_params 0x0 0x30000 0x0 0x2c000>; }; + + no_params: sio-t6030-test-no-params { + memory-region = <&nop_w>; + }; + + odd_w: odd-w { iommu-addresses = <&odd 0x0 0x30000 0x0 0x2c000>; }; + + odd: sio-t6030-test-odd { + memory-region = <&odd_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d>; + }; + + /* A window entry cut short, after the window that holds the tables */ + bad_w: bad-w { iommu-addresses = <&bad 0x0 0x58000 0x0 0x4000>, <&bad 0x0 0x30000 0x0>; }; + + bad: sio-t6030-test-bad-window { + memory-region = <&bad_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + + /* + * An entry whose owner phandle does not resolve (none, or no such + * node), after the window that holds the tables + */ + noown0_w: noown0-w { iommu-addresses = <&noown0 0x0 0x58000 0x0 0x4000>, + <0x0 0x0 0x30000 0x0 0x1000>; }; + + noown0: sio-t6030-test-owner-none { + memory-region = <&noown0_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + + noown1_w: noown1-w { iommu-addresses = <&noown1 0x0 0x58000 0x0 0x4000>, + <0xfffffff0 0x0 0x30000 0x0 0x1000>; }; + + noown1: sio-t6030-test-owner-unknown { + memory-region = <&noown1_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + + /* More windows than any loader maps; the first one holds the tables */ + many_w: many-w { + iommu-addresses = <&many 0x0 0x58000 0x0 0x4000>, <&many 0x0 0x10000 0x0 0x1000>, + <&many 0x0 0x11000 0x0 0x1000>, <&many 0x0 0x12000 0x0 0x1000>, + <&many 0x0 0x13000 0x0 0x1000>, <&many 0x0 0x14000 0x0 0x1000>, + <&many 0x0 0x15000 0x0 0x1000>, <&many 0x0 0x16000 0x0 0x1000>, + <&many 0x0 0x17000 0x0 0x1000>; + }; + + many: sio-t6030-test-many-windows { + memory-region = <&many_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 + 0x1c 0x5a 0x1d 0x48>; + }; + }; +}; diff --git a/drivers/dma/apple-sio-test.c b/drivers/dma/apple-sio-test.c new file mode 100644 index 00000000000000..1088b967686386 --- /dev/null +++ b/drivers/dma/apple-sio-test.c @@ -0,0 +1,329 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by apple-sio.c: the T6030 SIO boot-table check. + * + * sio_t6030_build() lays the tables out the way the boot loader does (m1n1's add_fwdata(): a + * table shares the previous mapping while it fits in that mapping's 16K, the mappings start at + * IOVA 0x30000 and end up 16K-aligned). It builds both a T6030-aware loader's protocol-10 tables + * and an earlier loader's. + */ +#include +#include +#include + +#define SIO_TEST_PARAMS 32 + +struct sio_t6030_layout { + u32 params[SIO_TEST_PARAMS]; + unsigned int nparams; + struct sio_t6030_window windows[SIO_T6030_WINDOWS_MAX]; + unsigned int nwindows; +}; + +static void sio_t6030_add(struct sio_t6030_layout *l, u32 key, u32 size) +{ + struct sio_t6030_window *last = l->nwindows ? &l->windows[l->nwindows - 1] : NULL; + u64 iova; + + if (last && ALIGN(last->size, SZ_16K) >= last->size + size) { + iova = last->start + last->size; + last->size = ALIGN(last->size + size, SZ_4K); + } else { + iova = last ? ALIGN(last->start + last->size, SZ_16K) : 0x30000; + l->windows[l->nwindows].start = iova; + l->windows[l->nwindows].size = ALIGN(size, SZ_4K); + l->nwindows++; + } + l->params[l->nparams++] = key; + l->params[l->nparams++] = iova >> 12; + l->params[l->nparams++] = key + 1; + l->params[l->nparams++] = size; +} + +/* shims and types: the DMA shim and device-type table sizes this loader builds */ +static void sio_t6030_build(struct sio_t6030_layout *l, u32 shims, u32 types) +{ + unsigned int i; + + memset(l, 0, sizeof(*l)); + sio_t6030_add(l, 0x1e, 0x300); /* tunables, from the ADT */ + sio_t6030_add(l, 0x0b, 0x1b80); + sio_t6030_add(l, 0x0f, 0x1e000); /* panic buffer */ + sio_t6030_add(l, 0x30d, 0x4000); + sio_t6030_add(l, 0x1a, 4 * 16); /* map ranges */ + sio_t6030_add(l, 0x22, shims); + sio_t6030_add(l, 0x1c, types); + for (i = 0; i < l->nwindows; i++) + l->windows[i].size = ALIGN(l->windows[i].size, SZ_16K); +} + +static int sio_t6030_check(const struct sio_t6030_layout *l) +{ + return sio_t6030_check_params(l->params, l->nparams, l->windows, l->nwindows); +} + +static u32 *sio_t6030_value(struct sio_t6030_layout *l, u32 key) +{ + unsigned int i; + + for (i = 0; i < l->nparams; i += 2) + if (l->params[i] == key) + return &l->params[i + 1]; + return NULL; +} + +/* A T6030-aware loader's tables (six 36-byte shims, nine types) are admitted. */ +static void sio_t6030_protocol10_test(struct kunit *test) +{ + struct sio_t6030_layout l; + + sio_t6030_build(&l, 6 * 36, 9 * 8); + KUNIT_EXPECT_EQ(test, l.nwindows, 4U); + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), 0); +} + +/* An earlier loader's tables (five 32-byte shims, eight types) are refused. */ +static void sio_t6030_earlier_loader_test(struct kunit *test) +{ + struct sio_t6030_layout l; + + sio_t6030_build(&l, 5 * 32, 8 * 8); + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + /* Either table alone of the earlier size refuses too */ + sio_t6030_build(&l, 5 * 32, 9 * 8); + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + sio_t6030_build(&l, 6 * 36, 8 * 8); + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); +} + +/* Other record counts, such as a later protocol's, are refused. */ +static void sio_t6030_wrong_counts_test(struct kunit *test) +{ + static const u32 sizes[][2] = { + { 5 * 36, 9 * 8 }, { 7 * 36, 9 * 8 }, { 6 * 32, 9 * 8 }, { 6 * 40, 9 * 8 }, + { 6 * 36, 10 * 8 }, { 6 * 36, 9 * 16 }, { 0, 9 * 8 }, { 6 * 36, 0 }, + }; + struct sio_t6030_layout l; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(sizes); i++) { + sio_t6030_build(&l, sizes[i][0], sizes[i][1]); + KUNIT_EXPECT_EQ_MSG(test, sio_t6030_check(&l), -EINVAL, "case %u", i); + } + sio_t6030_build(&l, 6 * 36, 9 * 8); + *sio_t6030_value(&l, 0x1b) = 5 * 16; /* map ranges */ + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); +} + +/* Malformed and truncated parameter lists are refused. */ +static void sio_t6030_malformed_test(struct kunit *test) +{ + struct sio_t6030_layout l; + unsigned int i; + + sio_t6030_build(&l, 6 * 36, 9 * 8); + KUNIT_EXPECT_EQ(test, sio_t6030_check_params(l.params, 0, l.windows, l.nwindows), -EINVAL); + KUNIT_EXPECT_EQ(test, sio_t6030_check_params(l.params, l.nparams - 1, l.windows, + l.nwindows), -EINVAL); + /* Truncated after any pair: the last table's size is always lost */ + for (i = 2; i < l.nparams; i += 2) + KUNIT_EXPECT_EQ_MSG(test, sio_t6030_check_params(l.params, i, l.windows, + l.nwindows), + -EINVAL, "cut at %u", i); + /* A key twice, even with the same value, for a table or any other parameter */ + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.params[l.nparams] = 0x22; + l.params[l.nparams + 1] = *sio_t6030_value(&l, 0x22); + l.nparams += 2; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.params[l.nparams] = 0x1e; + l.params[l.nparams + 1] = *sio_t6030_value(&l, 0x1e); + l.nparams += 2; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + /* A table without its size, or its size without the table */ + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.params[l.nparams - 2] = 0x40; /* 0x1d replaced */ + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.params[l.nparams - 4] = 0x41; /* 0x1c replaced */ + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + /* More pairs than the controller takes */ + { + static u32 many[2 * (SIO_T6030_PARAMS_MAX + 1)]; + + sio_t6030_build(&l, 6 * 36, 9 * 8); + memset(many, 0, sizeof(many)); + memcpy(many, l.params, l.nparams * sizeof(u32)); + for (i = l.nparams; i < ARRAY_SIZE(many); i += 2) + many[i] = 0x1000 + i; + KUNIT_EXPECT_EQ(test, sio_t6030_check_params(many, ARRAY_SIZE(many), l.windows, + l.nwindows), -EINVAL); + KUNIT_EXPECT_EQ(test, sio_t6030_check_params(many, ARRAY_SIZE(many) - 2, + l.windows, l.nwindows), 0); + } +} + +/* + * A key wider than 16 bits is refused: the firmware gets its low 16 bits as + * the endpoint and parameter bytes, so it would overwrite a checked parameter. + */ +static void sio_t6030_key_alias_test(struct kunit *test) +{ + static const u32 aliases[] = { 0x1001a, 0xff00001a, 0x1000022, 0x10023, 0x1001c, 0x1001d }; + struct sio_t6030_layout l; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(aliases); i++) { + u32 key = aliases[i], checked; + + /* A run-time value, as the driver has: FIELD_PREP() masks it */ + OPTIMIZER_HIDE_VAR(key); + checked = key & 0xffff; + /* The setup message sio_send_dt_params() sends is that of the checked key */ + KUNIT_EXPECT_EQ(test, FIELD_PREP(SIOMSG_PARAM, key & 0xff) | + FIELD_PREP(SIOMSG_EP, key >> 8), + FIELD_PREP(SIOMSG_PARAM, checked & 0xff) | + FIELD_PREP(SIOMSG_EP, checked >> 8)); + sio_t6030_build(&l, 6 * 36, 9 * 8); + KUNIT_ASSERT_NOT_NULL(test, sio_t6030_value(&l, checked)); + l.params[l.nparams] = key; + l.params[l.nparams + 1] = 0x80; + l.nparams += 2; + KUNIT_EXPECT_EQ_MSG(test, sio_t6030_check(&l), -EINVAL, "key %#x", key); + } + /* Wider than 16 bits but aliasing no listed key: refused all the same */ + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.params[l.nparams] = 0x10099; + l.params[l.nparams + 1] = 0; + l.nparams += 2; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + /* Any 16-bit key is its own message, and is admitted */ + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.params[l.nparams] = 0xffff; + l.params[l.nparams + 1] = 0; + l.nparams += 2; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), 0); +} + +/* Each table must lie inside one mapped window; spans must not overflow. */ +static void sio_t6030_spans_test(struct kunit *test) +{ + struct sio_t6030_layout l; + + sio_t6030_build(&l, 6 * 36, 9 * 8); + KUNIT_EXPECT_EQ(test, sio_t6030_check_params(l.params, l.nparams, l.windows, 0), -EINVAL); + /* The shims' page outside every window */ + *sio_t6030_value(&l, 0x22) = 0x80; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + /* + * Ending exactly at the end of their window, and one byte past it. The window + * keeps the map ranges and the shims; the types get a window of their own. + */ + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.windows[3].size = 0x59000 - 0x58000 + 6 * 36; + l.windows[4].start = 0x5a000; + l.windows[4].size = SZ_16K; + l.nwindows = 5; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), 0); + l.windows[3].size--; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + /* Starting at the start of their window, and one byte before it */ + l.windows[3].size++; + l.windows[3].start += SZ_4K; + l.windows[3].size -= SZ_4K; + *sio_t6030_value(&l, 0x1a) = 0x59; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), 0); + l.windows[3].start += 1; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + /* Beyond the controller's 42-bit DMA range, or in a window that wraps around */ + sio_t6030_build(&l, 6 * 36, 9 * 8); + *sio_t6030_value(&l, 0x22) = U32_MAX; + l.windows[3].start = 0; + l.windows[3].size = U64_MAX; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); + sio_t6030_build(&l, 6 * 36, 9 * 8); + l.windows[3].start = U64_MAX - 0xfff; + l.windows[3].size = 0x2000; + KUNIT_EXPECT_EQ(test, sio_t6030_check(&l), -EINVAL); +} + +OF_OVERLAY_DECLARE(apple_sio_t6030_test); + +/* The device-tree side: the parameters and windows a loader writes, read back. */ +static void sio_t6030_device_tree_test(struct kunit *test) +{ + static const char *const nodes[][2] = { + { "/sio-t6030-test/sio-t6030-test-v10", "admitted" }, + { "/sio-t6030-test/sio-t6030-test-earlier", "refused" }, + { "/sio-t6030-test/sio-t6030-test-unmapped", "refused" }, + { "/sio-t6030-test/sio-t6030-test-other-owner", "refused" }, + { "/sio-t6030-test/sio-t6030-test-no-params", "refused" }, + { "/sio-t6030-test/sio-t6030-test-odd", "refused" }, + { "/sio-t6030-test/sio-t6030-test-bad-window", "refused" }, + { "/sio-t6030-test/sio-t6030-test-owner-none", "refused" }, + { "/sio-t6030-test/sio-t6030-test-owner-unknown", "refused" }, + { "/sio-t6030-test/sio-t6030-test-many-windows", "refused" }, + }; + unsigned int i; + + KUNIT_ASSERT_EQ(test, 0, of_overlay_apply_kunit(test, apple_sio_t6030_test)); + for (i = 0; i < ARRAY_SIZE(nodes); i++) { + struct device_node *np __free(device_node) = of_find_node_by_path(nodes[i][0]); + int ret; + + KUNIT_ASSERT_NOT_NULL_MSG(test, np, "%s", nodes[i][0]); + ret = sio_t6030_check_node(np); + if (!strcmp(nodes[i][1], "admitted")) + KUNIT_EXPECT_EQ_MSG(test, ret, 0, "%s", nodes[i][0]); + else + KUNIT_EXPECT_NE_MSG(test, ret, 0, "%s", nodes[i][0]); + } +} + +/* + * The probe refuses an earlier loader's tables before it maps a register. The test devices + * have no register range, so a probe that gets past the check stops there with -EINVAL. + */ +static void sio_t6030_probe_test(struct kunit *test) +{ + static const struct { + const char *path; + int err; + } cases[] = { + { "/sio-t6030-test/sio-t6030-test-earlier", -ENODEV }, + { "/sio-t6030-test/sio-t6030-test-v10", -EINVAL }, + }; + unsigned int i; + + KUNIT_ASSERT_EQ(test, 0, of_overlay_apply_kunit(test, apple_sio_t6030_test)); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + struct platform_device *pdev; + + pdev = kunit_platform_device_alloc(test, "apple-sio-t6030-test", i); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdev); + /* The device's release drops this reference */ + pdev->dev.of_node = of_find_node_by_path(cases[i].path); + KUNIT_ASSERT_NOT_NULL_MSG(test, pdev->dev.of_node, "%s", cases[i].path); + KUNIT_EXPECT_EQ_MSG(test, sio_probe(pdev), cases[i].err, "%s", cases[i].path); + } +} + +static struct kunit_case sio_t6030_test_cases[] = { + KUNIT_CASE(sio_t6030_protocol10_test), + KUNIT_CASE(sio_t6030_earlier_loader_test), + KUNIT_CASE(sio_t6030_wrong_counts_test), + KUNIT_CASE(sio_t6030_malformed_test), + KUNIT_CASE(sio_t6030_key_alias_test), + KUNIT_CASE(sio_t6030_spans_test), + KUNIT_CASE(sio_t6030_device_tree_test), + KUNIT_CASE(sio_t6030_probe_test), + {} +}; + +static struct kunit_suite sio_t6030_test_suite = { + .name = "apple-sio-t6030", + .test_cases = sio_t6030_test_cases, +}; + +kunit_test_suite(sio_t6030_test_suite); diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 511f91999ed3de..0c06e0264b7b60 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -13,8 +13,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -128,6 +130,9 @@ struct sio_data { } tags; int nchannels; +#if IS_ENABLED(CONFIG_APPLE_SIO_T6030) + bool t6030; +#endif struct sio_chan channels[]; }; @@ -150,6 +155,173 @@ static int sio_send_siomsg_atomic(struct sio_data *sio, u64 msg, void *cookie); static int sio_call(struct sio_data *sio, u64 msg); +static inline bool sio_is_t6030(struct sio_data *sio) +{ +#if IS_ENABLED(CONFIG_APPLE_SIO_T6030) + return sio->t6030; +#else + return false; +#endif +} + +#if IS_ENABLED(CONFIG_APPLE_SIO_T6030) +/* + * Boot tables of the T6030 SIO firmware, protocol 10. The boot loader builds them from the ADT + * and passes each one as two apple,sio-firmware-params: the table's IOVA page under its key and + * its size in bytes under key + 1. Protocol 10 takes six 36-byte DMA shim records and nine device + * types. A loader without protocol-10 support builds five 32-byte records and eight types, which + * this firmware cannot use, so the SIO is not started with them. + */ +#define SIO_T6030_PARAMS_MAX 64 /* key and value pairs */ +#define SIO_T6030_WINDOWS_MAX 8 +#define SIO_T6030_IOVA_LIMIT BIT_ULL(42) +/* + * A parameter goes to the firmware as an endpoint byte (key >> 8) and a + * parameter byte (key & 0xff), so a wider key would alias another one. + */ +#define SIO_T6030_KEY_MAX 0xffff + +struct sio_t6030_window { + u64 start; + u64 size; +}; + +static const struct { + u32 key; + u32 size; +} sio_t6030_tables[] = { + { 0x1a, 4 * 16 }, /* map ranges */ + { 0x1c, 9 * 8 }, /* device types */ + { 0x22, 6 * 36 }, /* DMA shims */ +}; + +/* + * 0 when the parameters hold each protocol-10 table once, at its exact size, entirely inside one + * of the windows the boot loader mapped for the SIO; -EINVAL otherwise. + */ +static int sio_t6030_check_params(const u32 *params, unsigned int nparams, + const struct sio_t6030_window *windows, unsigned int nwindows) +{ + unsigned int i, j, t; + + if (!nparams || nparams % 2 || nparams > 2 * SIO_T6030_PARAMS_MAX) + return -EINVAL; + for (i = 0; i < nparams; i += 2) + if (params[i] > SIO_T6030_KEY_MAX) + return -EINVAL; + for (i = 0; i < nparams; i += 2) + for (j = i + 2; j < nparams; j += 2) + if (params[i] == params[j]) + return -EINVAL; + + for (t = 0; t < ARRAY_SIZE(sio_t6030_tables); t++) { + bool have_page = false, have_size = false, inside = false; + u64 start = 0, size = 0, end; + + for (i = 0; i < nparams; i += 2) { + if (params[i] == sio_t6030_tables[t].key) { + start = (u64)params[i + 1] << 12; + have_page = true; + } else if (params[i] == sio_t6030_tables[t].key + 1) { + size = params[i + 1]; + have_size = true; + } + } + if (!have_page || !have_size || size != sio_t6030_tables[t].size) + return -EINVAL; + if (check_add_overflow(start, size, &end) || end > SIO_T6030_IOVA_LIMIT) + return -EINVAL; + for (j = 0; j < nwindows && !inside; j++) { + u64 window_end; + + if (check_add_overflow(windows[j].start, windows[j].size, &window_end)) + continue; + inside = start >= windows[j].start && end <= window_end; + } + if (!inside) + return -EINVAL; + } + return 0; +} + +/* The IOVA windows of this device's memory regions, from their iommu-addresses */ +static int sio_t6030_windows(struct device_node *np, struct sio_t6030_window *windows, + unsigned int max) +{ + struct of_phandle_iterator it; + unsigned int n = 0; + int err; + + of_for_each_phandle(&it, err, np, "memory-region", NULL, 0) { + const __be32 *maps, *end; + int size; + + maps = of_get_property(it.node, "iommu-addresses", &size); + if (!maps) + continue; + if (size % sizeof(*maps)) { + of_node_put(it.node); + return -EINVAL; + } + end = maps + size / sizeof(*maps); + while (maps < end) { + struct device_node *owner __free(device_node) = + of_find_node_by_phandle(be32_to_cpup(maps++)); + phys_addr_t iova; + size_t length; + + /* An entry whose owner does not resolve is malformed, as a short one is */ + if (!owner) { + of_node_put(it.node); + return -EINVAL; + } + maps = of_translate_dma_region_checked(owner, maps, end - maps, &iova, + &length); + if (!maps) { + of_node_put(it.node); + return -EINVAL; + } + if (owner != np) + continue; + if (n == max) { + of_node_put(it.node); + return -EINVAL; + } + windows[n].start = iova; + windows[n].size = length; + n++; + } + } + return err == -ENOENT ? n : err; +} + +/* 0 when the node's boot tables are protocol-10 tables inside its mapped windows */ +static int sio_t6030_check_node(struct device_node *np) +{ + struct sio_t6030_window windows[SIO_T6030_WINDOWS_MAX]; + u32 params[2 * SIO_T6030_PARAMS_MAX]; + int nparams, nwindows; + + nparams = of_property_count_u32_elems(np, "apple,sio-firmware-params"); + if (nparams <= 0 || nparams > ARRAY_SIZE(params) || + of_property_read_u32_array(np, "apple,sio-firmware-params", params, nparams)) + return -EINVAL; + nwindows = sio_t6030_windows(np, windows, ARRAY_SIZE(windows)); + if (nwindows < 0) + return nwindows; + return sio_t6030_check_params(params, nparams, windows, nwindows); +} + +static int sio_t6030_check_boot_tables(struct device *dev) +{ + if (sio_t6030_check_node(dev->of_node)) { + dev_err(dev, "boot tables are not for SIO protocol 10; leaving the SIO stopped\n"); + return -ENODEV; + } + return 0; +} +#endif + static struct sio_chan *to_sio_chan(struct dma_chan *chan) { return container_of(chan, struct sio_chan, vc.chan); @@ -283,6 +455,12 @@ static struct dma_async_tx_descriptor *sio_prep_dma_cyclic( return NULL; } + /* + * T6030: publish the whole descriptor, its other fields zero; + * a slot may come back from an earlier transfer. + */ + if (sio_is_t6030(siochan->host)) + memset(d, 0, sizeof(*d)); d->flag = 1; /* not sure what's up with this */ d->iova = buf_addr + period_len * i; d->size = period_len; @@ -656,7 +834,12 @@ static int sio_device_config(struct dma_chan *chan, cfg.timeout = 0; cfg.fifo = 0x800; cfg.limit = 0x800; - cfg.threshold = 0x800; + /* + * The ADT records each client's channel configuration with it (the + * dp-audioN dma-channels: channel, data shape, timeout, FIFO size, + * threshold). T6030's DisplayPort audio channels refill at 0x600. + */ + cfg.threshold = sio_is_t6030(sio) ? 0x600 : 0x800; /* * Dmaengine prescribes we ought to apply the new configuration only @@ -789,6 +972,16 @@ static int sio_probe(struct platform_device *pdev) int nchannels; int err, i; + /* + * Only APPLE_SIO_T6030 checks a T6030's boot tables and configures its + * channels: without it, leave the SIO stopped rather than start it as + * the generic one. + */ + if (!IS_ENABLED(CONFIG_APPLE_SIO_T6030) && + of_device_is_compatible(np, "apple,t6030-sio")) + return dev_err_probe(&pdev->dev, -ENODEV, + "T6030 SIO support (APPLE_SIO_T6030) not built; leaving the SIO stopped\n"); + err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(42)); if (err) return dev_err_probe(&pdev->dev, err, "Failed to set DMA mask\n"); @@ -805,6 +998,15 @@ static int sio_probe(struct platform_device *pdev) platform_set_drvdata(pdev, sio); sio->dev = &pdev->dev; sio->nchannels = nchannels; +#if IS_ENABLED(CONFIG_APPLE_SIO_T6030) + sio->t6030 = of_device_is_compatible(np, "apple,t6030-sio"); + /* Before any register, power or firmware access */ + if (sio->t6030) { + err = sio_t6030_check_boot_tables(&pdev->dev); + if (err) + return err; + } +#endif sio->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(sio->base)) @@ -940,3 +1142,11 @@ module_platform_driver(apple_sio_driver); MODULE_AUTHOR("Martin PoviÅ¡er "); MODULE_DESCRIPTION("Driver for SIO coprocessor on Apple SoCs"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_APPLE_SIO_T6030_KUNIT_TEST) +#include "apple-sio-test.c" +#endif + +#if IS_ENABLED(CONFIG_APPLE_SIO_KUNIT_TEST) +#include "apple-sio-probe-test.c" +#endif diff --git a/drivers/edac/amd64_edac.c b/drivers/edac/amd64_edac.c index 475235c402e888..0c0d11c7292598 100644 --- a/drivers/edac/amd64_edac.c +++ b/drivers/edac/amd64_edac.c @@ -2796,13 +2796,13 @@ static inline void decode_bus_error(int node_id, struct mce *m) * the instance_id. For example, instance_id=0xYXXXXX where Y is the channel * number. * - * For DRAM ECC errors, the Chip Select number is given in bits [2:0] of + * For DRAM ECC errors, the Chip Select number is given in bits [1:0] of * the MCA_SYND[ErrorInformation] field. */ static void umc_get_err_info(struct mce *m, struct err_info *err) { err->channel = (m->ipid & GENMASK(31, 0)) >> 20; - err->csrow = m->synd & 0x7; + err->csrow = m->synd & 0x3; } static void decode_umc_error(int node_id, struct mce *m) diff --git a/drivers/gpio/gpio-exar.c b/drivers/gpio/gpio-exar.c index 9053662f18177f..f629cc526f3ee7 100644 --- a/drivers/gpio/gpio-exar.c +++ b/drivers/gpio/gpio-exar.c @@ -199,6 +199,7 @@ static int gpio_exar_probe(struct platform_device *pdev) index = ida_alloc(&ida_index, GFP_KERNEL); if (index < 0) return index; + exar_gpio->index = index; ret = devm_add_action_or_reset(dev, exar_devm_ida_free, exar_gpio); if (ret) @@ -214,7 +215,6 @@ static int gpio_exar_probe(struct platform_device *pdev) exar_gpio->gpio_chip.set = exar_set_value; exar_gpio->gpio_chip.base = -1; exar_gpio->gpio_chip.ngpio = ngpios; - exar_gpio->index = index; exar_gpio->first_pin = first_pin; ret = devm_gpiochip_add_data(dev, &exar_gpio->gpio_chip, exar_gpio); diff --git a/drivers/gpio/gpio-mpsse.c b/drivers/gpio/gpio-mpsse.c index a859deab2bca80..5ce822c0ddcf49 100644 --- a/drivers/gpio/gpio-mpsse.c +++ b/drivers/gpio/gpio-mpsse.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -24,6 +25,7 @@ struct mpsse_priv { raw_spinlock_t irq_spin; /* protects worker list */ atomic_t irq_type[16]; /* pin -> edge detection type */ atomic_t irq_enabled; + atomic_t dying; /* no new workers after disconnect */ int id; u8 gpio_outputs[2]; /* Output states for GPIOs [L, H] */ @@ -46,6 +48,7 @@ struct mpsse_worker { atomic_t cancelled; struct list_head list; /* linked list */ struct list_head destroy; /* teardown linked list */ + struct rcu_head rcu; /* deferred free for dying path */ }; struct bulk_desc { @@ -525,10 +528,24 @@ static void gpio_mpsse_irq_enable(struct irq_data *irqd) worker->priv = priv; INIT_LIST_HEAD(&worker->list); INIT_WORK(&worker->work, gpio_mpsse_poll); - schedule_work(&worker->work); - scoped_guard(raw_spinlock_irqsave, &priv->irq_spin) + scoped_guard(raw_spinlock_irqsave, &priv->irq_spin) { + if (atomic_read(&priv->dying)) { + /* + * Cannot kfree() here: this callback + * runs with the IRQ descriptor's raw + * spinlock held and kfree() may sleep + * on PREEMPT_RT. The worker is not + * yet published, so the deferred free + * is unobservable. + */ + kfree_rcu(worker, rcu); + return; + } + list_add(&worker->list, &priv->workers); + schedule_work(&worker->work); + } } } @@ -704,6 +721,9 @@ static void gpio_mpsse_disconnect(struct usb_interface *intf) { struct mpsse_priv *priv = usb_get_intfdata(intf); + scoped_guard(raw_spinlock_irqsave, &priv->irq_spin) + atomic_set(&priv->dying, 1); + /* * Lock prevents double-free of worker from here and the teardown * step at the beginning of gpio_mpsse_poll diff --git a/drivers/gpio/gpio-xilinx.c b/drivers/gpio/gpio-xilinx.c index 532205175827a0..9406ce85f93308 100644 --- a/drivers/gpio/gpio-xilinx.c +++ b/drivers/gpio/gpio-xilinx.c @@ -271,14 +271,7 @@ static void xgpio_save_regs(struct xgpio_instance *chip) static int xgpio_request(struct gpio_chip *chip, unsigned int offset) { - int ret; - - ret = pm_runtime_get_sync(chip->parent); - /* - * If the device is already active pm_runtime_get() will return 1 on - * success, but gpio_request still needs to return 0. - */ - return ret < 0 ? ret : 0; + return pm_runtime_resume_and_get(chip->parent); } static void xgpio_free(struct gpio_chip *chip, unsigned int offset) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c index 4b29e7eee61053..299baecb83ebda 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c @@ -597,14 +597,18 @@ int amdgpu_amdkfd_get_dmabuf_info(struct amdgpu_device *adev, int dma_buf_fd, /* first get metadata_size by buffer = NULL */ r = amdgpu_bo_get_metadata(bo, NULL, 0, metadata_size, NULL); + if (r) + goto out_put; /* user buf_size is bigger than bo metadata_size * allocate a buf at kernel space and copy */ if (*metadata_size <= buffer_size) { *metadata_buffer = kzalloc(*metadata_size, GFP_KERNEL); - if (!*metadata_buffer) - return -ENOMEM; + if (!*metadata_buffer) { + r = -ENOMEM; + goto out_put; + } r = amdgpu_bo_get_metadata(bo, *metadata_buffer, *metadata_size, NULL, &metadata_flags); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c index 4536d46b7f21b5..40b34770414b78 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c @@ -120,6 +120,20 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f, *pos &= (1UL << 22) - 1; + if (size > PAGE_SIZE) + return -EINVAL; + + /* + * Access the user buffer only while none of the locks below are held: + * a fault takes mmap_lock, and grbm_idx_mutex and srbm_mutex nest + * inside it. + */ + u32 *data __free(kfree) = kmalloc(size, GFP_KERNEL); + if (!data) + return -ENOMEM; + if (!read && copy_from_user(data, buf, size)) + return -EFAULT; + r = pm_runtime_get_sync(adev_to_drm(adev)->dev); if (r < 0) { pm_runtime_put_autosuspend(adev_to_drm(adev)->dev); @@ -151,28 +165,16 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f, mutex_lock(&adev->pm.mutex); while (size) { - uint32_t value; - - if (read) { - value = RREG32(*pos >> 2); - r = put_user(value, (uint32_t *)buf); - } else { - r = get_user(value, (uint32_t *)buf); - if (!r) - amdgpu_mm_wreg_mmio_rlc(adev, *pos >> 2, value, 0); - } - if (r) { - result = r; - goto end; - } + if (read) + data[result >> 2] = RREG32(*pos >> 2); + else + amdgpu_mm_wreg_mmio_rlc(adev, *pos >> 2, data[result >> 2], 0); result += 4; - buf += 4; *pos += 4; size -= 4; } -end: if (use_bank) { amdgpu_gfx_select_se_sh(adev, 0xffffffff, 0xffffffff, 0xffffffff, 0); mutex_unlock(&adev->grbm_idx_mutex); @@ -187,6 +189,10 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f, pm_runtime_put_autosuspend(adev_to_drm(adev)->dev); amdgpu_virt_disable_access_debugfs(adev); + + if (read && copy_to_user(buf, data, result)) + return -EFAULT; + return result; } @@ -237,11 +243,24 @@ static ssize_t amdgpu_debugfs_regs2_op(struct file *f, char __user *buf, u32 off struct amdgpu_device *adev = rd->adev; ssize_t result = 0; int r; - uint32_t value; if (size & 0x3 || offset & 0x3) return -EINVAL; + if (size > PAGE_SIZE) + return -EINVAL; + + /* + * Access the user buffer only while none of the locks below are held: + * a fault takes mmap_lock, and grbm_idx_mutex and srbm_mutex nest + * inside it. + */ + u32 *data __free(kfree) = kmalloc(size, GFP_KERNEL); + if (!data) + return -ENOMEM; + if (write_en && copy_from_user(data, buf, size)) + return -EFAULT; + r = pm_runtime_get_sync(adev_to_drm(adev)->dev); if (r < 0) { pm_runtime_put_autosuspend(adev_to_drm(adev)->dev); @@ -280,24 +299,16 @@ static ssize_t amdgpu_debugfs_regs2_op(struct file *f, char __user *buf, u32 off mutex_lock(&adev->pm.mutex); while (size) { - if (!write_en) { - value = RREG32(offset >> 2); - r = put_user(value, (uint32_t *)buf); - } else { - r = get_user(value, (uint32_t *)buf); - if (!r) - amdgpu_mm_wreg_mmio_rlc(adev, offset >> 2, value, rd->id.xcc_id); - } - if (r) { - result = r; - goto end; - } + if (!write_en) + data[result >> 2] = RREG32(offset >> 2); + else + amdgpu_mm_wreg_mmio_rlc(adev, offset >> 2, data[result >> 2], + rd->id.xcc_id); offset += 4; size -= 4; result += 4; - buf += 4; } -end: + if (rd->id.use_grbm) { amdgpu_gfx_select_se_sh(adev, 0xffffffff, 0xffffffff, 0xffffffff, rd->id.xcc_id); mutex_unlock(&adev->grbm_idx_mutex); @@ -316,6 +327,10 @@ static ssize_t amdgpu_debugfs_regs2_op(struct file *f, char __user *buf, u32 off pm_runtime_put_autosuspend(adev_to_drm(adev)->dev); amdgpu_virt_disable_access_debugfs(adev); + + if (!write_en && copy_to_user(buf, data, result)) + return -EFAULT; + return result; } diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c index 5d6149ba7ab78e..8fb3ebe4c2990d 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c @@ -1089,20 +1089,17 @@ void amdgpu_gmc_init_vga_resv_regions(struct amdgpu_device *adev) case CHIP_RENOIR: adev->mman.keep_stolen_vga_memory = true; break; - case CHIP_POLARIS10: - case CHIP_POLARIS11: - case CHIP_POLARIS12: - /* MacBookPros with switchable graphics put VRAM at 0 when - * the iGPU is enabled which results in cursor issues if - * the cursor ends up at 0. Reserve vram at 0 in that case. - */ - if (adev->gmc.vram_start == 0) - adev->mman.keep_stolen_vga_memory = true; - break; default: adev->mman.keep_stolen_vga_memory = false; break; } + /* MacBookPros with switchable graphics put VRAM at 0 when + * the iGPU is enabled which results in cursor issues if + * the cursor ends up at 0. Reserve vram at 0 in that case. + */ + if ((adev->pdev->subsystem_vendor == PCI_VENDOR_ID_APPLE) && + (adev->gmc.vram_start == 0)) + adev->mman.keep_stolen_vga_memory = true; if (amdgpu_sriov_vf(adev) || !amdgpu_device_has_display_hardware(adev)) { diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c index 8bb9c198ddec13..872cce1115a915 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c @@ -30,6 +30,7 @@ #include #include #include +#include #include "amdgpu_uvd.h" #include "amdgpu_vce.h" #include "atom.h" @@ -1631,6 +1632,9 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) DRM_ERROR("Invalid crtc %u\n", pipe); return -EINVAL; } + if (!down_read_trylock(&adev->reset_domain->sem)) + return drm_crtc_vblank_count(crtc); + /* The hw increments its frame counter at start of vsync, not at start * of vblank, as is required by DRM core vblank counter handling. @@ -1676,6 +1680,7 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) DRM_DEBUG_VBL("NULL mode info! Returned count may be wrong.\n"); } + up_read(&adev->reset_domain->sem); return count; } diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c index 655429c4035181..0c3fa2d60555a9 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c @@ -439,6 +439,7 @@ amdgpu_userq_get_doorbell_index(struct amdgpu_userq_mgr *uq_mgr, u64 doorbell_index; struct drm_gem_object *gobj; struct amdgpu_userq_obj *db_obj = db_info->db_obj; + struct amdgpu_bo *abo; int r, db_size; gobj = drm_gem_object_lookup(filp, db_info->doorbell_handle); @@ -447,7 +448,17 @@ amdgpu_userq_get_doorbell_index(struct amdgpu_userq_mgr *uq_mgr, return -EINVAL; } - db_obj->obj = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj)); + /* + * Pinning a regular BO into the doorbell domain would discard its + * contents, possibly those of a buffer shared by another client. + */ + abo = gem_to_amdgpu_bo(gobj); + if (!(abo->preferred_domains & AMDGPU_GEM_DOMAIN_DOORBELL)) { + drm_gem_object_put(gobj); + return -EINVAL; + } + + db_obj->obj = amdgpu_bo_ref(abo); drm_gem_object_put(gobj); r = amdgpu_bo_reserve(db_obj->obj, true); diff --git a/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c b/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c index 4e44a581a78a21..e4bd6e5509b529 100644 --- a/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c +++ b/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c @@ -304,8 +304,7 @@ static int mes_userq_mqd_create(struct amdgpu_usermode_queue *queue, compute_mqd = memdup_user(u64_to_user_ptr(mqd_user->mqd), mqd_user->mqd_size); if (IS_ERR(compute_mqd)) { - DRM_ERROR("Failed to read user MQD\n"); - r = -ENOMEM; + r = PTR_ERR(compute_mqd); goto free_mqd; } @@ -349,8 +348,7 @@ static int mes_userq_mqd_create(struct amdgpu_usermode_queue *queue, mqd_gfx_v11 = memdup_user(u64_to_user_ptr(mqd_user->mqd), mqd_user->mqd_size); if (IS_ERR(mqd_gfx_v11)) { - DRM_ERROR("Failed to read user MQD\n"); - r = -ENOMEM; + r = PTR_ERR(mqd_gfx_v11); goto free_mqd; } @@ -394,8 +392,7 @@ static int mes_userq_mqd_create(struct amdgpu_usermode_queue *queue, mqd_sdma_v11 = memdup_user(u64_to_user_ptr(mqd_user->mqd), mqd_user->mqd_size); if (IS_ERR(mqd_sdma_v11)) { - DRM_ERROR("Failed to read sdma user MQD\n"); - r = -ENOMEM; + r = PTR_ERR(mqd_sdma_v11); goto free_mqd; } diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c index 487cf746c45045..ed934425907906 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c @@ -599,12 +599,32 @@ static int allocate_doorbell(struct qcm_process_device *qpd, * we need the physical sdma engine id in order to get the * correct doorbell offset. */ - uint32_t valid_id = idx_offset[qpd->dqm->dev->node_id * - get_num_all_sdma_engines(qpd->dqm) + - q->properties.sdma_engine_id] - + (q->properties.sdma_queue_id & 1) - * KFD_QUEUE_DOORBELL_MIRROR_OFFSET - + (q->properties.sdma_queue_id >> 1); + u32 engine_base = idx_offset[dev->node_id * + get_num_all_sdma_engines(qpd->dqm) + + q->properties.sdma_engine_id]; + u32 valid_id; + + /* + * With the aqua_vanjaram doorbell layout, a shader doorbell + * write whose 32-byte block starts in the previous engine's + * range rings that engine instead. Engine ranges are 10 + * indices apart (sdma_doorbell_range = 20 dwords, halved for + * 8-byte doorbells, in aqua_vanjaram_doorbell_index_init()), + * which puts odd engines 2 indices into a shared block. + * Aligning costs at most 2 indices, and 8 queues per engine use + * only 4 of the 10, so the aligned base stays in range. The + * 512-index mirror offset keeps the alignment. + */ + if (KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 3) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 4) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 5, 0)) + engine_base = ALIGN(engine_base, + KFD_SDMA_SHADER_DOORBELL_GRANULARITY); + + valid_id = engine_base + + (q->properties.sdma_queue_id & 1) * + KFD_QUEUE_DOORBELL_MIRROR_OFFSET + + (q->properties.sdma_queue_id >> 1); if (restore_id && *restore_id != valid_id) return -EINVAL; diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h index 4d65f94da4d818..993d98374253ba 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h @@ -132,6 +132,13 @@ */ #define KFD_QUEUE_DOORBELL_MIRROR_OFFSET 512 +/* + * On GC 9.4.3, 9.4.4 and 9.5.0, doorbell writes issued from shaders are + * routed to an SDMA engine at 32-byte granularity, i.e. 4 indices with the + * 8-byte SDMA doorbells used on SOC15. + */ +#define KFD_SDMA_SHADER_DOORBELL_GRANULARITY 4 + /** * enum kfd_ioctl_flags - KFD ioctl flags * Various flags that can be set in &amdkfd_ioctl_desc.flags to control how diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index 4ee7db8a6a2267..b92d129962b2a8 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -7260,10 +7260,15 @@ decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode, const struct drm_display_mode *native_mode, bool scale_enabled) { + /* Inserted modes copy the native sync; a sink mode with equal totals may not */ if (scale_enabled || ( native_mode->clock == drm_mode->clock && native_mode->htotal == drm_mode->htotal && - native_mode->vtotal == drm_mode->vtotal)) { + native_mode->vtotal == drm_mode->vtotal && + native_mode->hsync_start == drm_mode->hsync_start && + native_mode->hsync_end == drm_mode->hsync_end && + native_mode->vsync_start == drm_mode->vsync_start && + native_mode->vsync_end == drm_mode->vsync_end)) { if (native_mode->crtc_clock) copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode); } else { @@ -10397,6 +10402,13 @@ static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm, struct amdgpu_dm_connector *aconn = (struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context; + if (!acrtc_state->base.async_flip) { + amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false, + psr_event_immediate_flip, false); + amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false, + replay_event_immediate_flip, false); + } + /* Decrement skip count when SR is enabled and we're doing fast updates. */ if (acrtc_state->update_type == UPDATE_TYPE_FAST && (psr->psr_feature_enabled || pr->replay_feature_enabled)) { @@ -10810,6 +10822,18 @@ static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state, spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags); } mutex_lock(&dm->dc_lock); + /* + * Tearing (immediate) flips cannot work with panel self-refresh + * features. The event is cleared by + * amdgpu_dm_enable_self_refresh() once async flips stop. + */ + if (immediate_flip) { + dc_exit_ips_for_hw_access(dm->dc); + amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true, + psr_event_immediate_flip, true); + amdgpu_dm_replay_set_event(dm, acrtc_state->stream, true, + replay_event_immediate_flip, true); + } update_planes_and_stream_adapter(dm->dc, acrtc_state->update_type, planes_count, diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_plane.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_plane.c index cfd76c54f652bd..1d69ecae10a478 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_plane.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_plane.c @@ -110,25 +110,7 @@ void amdgpu_dm_plane_fill_blending_from_plane_state(const struct drm_plane_state if (plane_state->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI || plane_state->pixel_blend_mode == DRM_MODE_BLEND_COVERAGE) { - static const uint32_t alpha_formats[] = { - DRM_FORMAT_ARGB8888, - DRM_FORMAT_RGBA8888, - DRM_FORMAT_ABGR8888, - DRM_FORMAT_ARGB2101010, - DRM_FORMAT_ABGR2101010, - DRM_FORMAT_ARGB16161616, - DRM_FORMAT_ABGR16161616, - DRM_FORMAT_ARGB16161616F, - }; - uint32_t format = plane_state->fb->format->format; - unsigned int i; - - for (i = 0; i < ARRAY_SIZE(alpha_formats); ++i) { - if (format == alpha_formats[i]) { - *per_pixel_alpha = true; - break; - } - } + *per_pixel_alpha = plane_state->fb->format->has_alpha; if (*per_pixel_alpha && plane_state->pixel_blend_mode == DRM_MODE_BLEND_COVERAGE) *pre_multiplied_alpha = false; diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index 57a1ce69e74470..0675e5ac1b2e3c 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -29,6 +29,18 @@ config DRM_APPLE_AUDIO select SND_PCM select SND_DMAENGINE_PCM +config DRM_APPLE_DCP_T6030_AUDIO + bool "HDMI audio through the T6030 external display processor" + default y + depends on DRM_APPLE_AUDIO + help + DP/HDMI audio of the external display processors of the M3 Pro + (T6030, MacBook Pro J514S/J516S built-in HDMI port), whose DCP + firmware 14.7 external role takes 32-byte audio link data and the + native driver's link lifecycle. The audio service of every other + DCP is driven unchanged. Say N to build the audio and element + parser code exactly as before. + config DRM_APPLE_DEBUG bool "Enable additional driver debugging" depends on DRM_APPLE diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index e21650d949859c..b796645b471d80 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -44,3 +44,4 @@ obj-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += afkv2-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += parser-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += hotplug-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += v14-board-test.o +appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += audio-no-sio-test.dtbo.o diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index b97ec275e25eac..de9c3846b15b8e 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -462,6 +462,8 @@ static void afk_service_worker(struct work_struct *work) afk_retry_service_init(ep); } +static void afk_recv_handle_teardown(struct apple_dcp_afkep *ep, u32 channel); + static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, u8 *payload, size_t payload_size) { @@ -479,6 +481,15 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, size_t props_size = payload_size - sizeof(name); previous = afk_epic_find_service(ep, channel); + /* + * The 14.7 external role announces its AV service again on the same + * channel after a replug: that is a new instance, and the old one is + * gone with the sink it served. + */ + if (previous && dcp_is_v14_7_external(ep->dcp) && ep == ep->dcp->dcpavservep) { + afk_recv_handle_teardown(ep, channel); + previous = afk_epic_find_service(ep, channel); + } if (previous) { spin_lock_irqsave(&previous->lock, flags); retired = previous->torndown; @@ -1675,6 +1686,9 @@ static int afk_send_epic_token(struct apple_dcp_afkep *ep, u32 channel, u16 tag, eshdr->type = cpu_to_le16(stype); eshdr->timestamp = cpu_to_le64(0); eshdr->tag = cpu_to_le16(tag); + /* The 14.7 external role's callback replies carry 8 in byte 35. */ + if (ecat == EPIC_CAT_REPLY && dcp_is_v14_7_external(ep->dcp)) + eshdr->unk = cpu_to_le16(8 << 8); if (ecat == EPIC_CAT_REPLY) eshdr->inline_len = cpu_to_le32(payload_len - 4); else diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index d1cda95aa9833d..8bf6d56f708e04 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -13,11 +13,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -54,6 +56,55 @@ struct apple_drm_private { struct drm_device drm; }; +/* Component readiness is later than platform probe/bind. */ +static DEFINE_MUTEX(apple_t6030_display_lock); +static struct device *apple_t6030_display; + +static int apple_t6030_display_publish(struct device *dev) +{ + if (!of_device_is_compatible(dev->of_node, "apple,t6030-display-subsystem")) + return 0; + guard(mutex)(&apple_t6030_display_lock); + if (apple_t6030_display) + return apple_t6030_display == dev ? 0 : -EBUSY; + apple_t6030_display = get_device(dev); + return 0; +} + +static void apple_t6030_display_withdraw(struct device *dev) +{ + struct device *old = NULL; + + scoped_guard(mutex, &apple_t6030_display_lock) { + if (apple_t6030_display == dev) { + old = apple_t6030_display; + apple_t6030_display = NULL; + } + } + put_device(old); +} + +/* Initial G15 firmware startup must follow successful native display setup. + * The component's device lock does not serialize component bind/unbind, so + * publish separately. This lock protects only publication and a device link; + * no display calls or firmware RPC run while it is held. + */ +int apple_drm_t6030_link_device(struct device *consumer) +{ + struct device_link *link; + + if (!of_machine_is_compatible("apple,t6030") || !consumer->of_node || + !of_device_is_compatible(consumer->of_node, "apple,agx-t6030")) + return -ENODEV; + guard(mutex)(&apple_t6030_display_lock); + if (!apple_t6030_display) + return -EPROBE_DEFER; + link = device_link_add(consumer, apple_t6030_display, + DL_FLAG_AUTOREMOVE_CONSUMER); + return link ? 0 : -EINVAL; +} +EXPORT_SYMBOL_GPL(apple_drm_t6030_link_device); + DEFINE_DRM_GEM_DMA_FOPS(apple_fops); #define DART_PAGE_SIZE 16384 @@ -551,6 +602,7 @@ static int apple_probe_per_dcp(struct device *dev, struct apple_encoder *enc; struct drm_plane *planes[DCP_MAX_PLANES]; unsigned long *iomfb_surfaces = dcp_get_iomfb_surfaces(dcp); + unsigned long top_surf = find_last_bit(iomfb_surfaces, DCP_MAX_PLANES); int ret; int connector_type; u32 surf; @@ -559,9 +611,16 @@ static int apple_probe_per_dcp(struct device *dev, struct apple_dcp *dcp_data = platform_get_drvdata(dcp); bool supports_xrgb2101010; enum drm_plane_type plane_type; + bool interchange; + bool supports_interchange; supports_xrgb2101010 = dcp_data->fw_compat != DCP_FIRMWARE_H17P || dcp_data->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G; + /* + * Interchange scanout has not been qualified with the H17P firmware + * (T8140 and T8122): advertise linear framebuffers only there. + */ + supports_interchange = dcp_data->fw_compat != DCP_FIRMWARE_H17P; if (bitmap_empty(iomfb_surfaces, DCP_MAX_PLANES)) return dev_err_probe(dev, -EINVAL, "No usable display surfaces\n"); @@ -576,14 +635,27 @@ static int apple_probe_per_dcp(struct device *dev, zpos = 1; } + /* + * BUG: + * Some DCPs support more than two surfaces. For some reason, these + * will crash if the topmost layer is Interchange *and* the surface + * is cleared *while content is being scanned out on the middle one*. + * They do not do this with linear framebuffers, nor do they do this + * when the middle surface is not in use. We therefore hide Interchange + * from the surface. + */ for_each_set_bit(surf, iomfb_surfaces, DCP_MAX_PLANES) { if (dcp_fw_compat_is_14_7(dcp)) break; plane_type = (zpos == 0) ? DRM_PLANE_TYPE_PRIMARY : DRM_PLANE_TYPE_OVERLAY; + interchange = supports_interchange && + (zpos <= 1 || surf != top_surf); + planes[zpos] = apple_plane_init(drm, 1U << num, surf, supports_l10r, supports_xrgb2101010, - plane_type); + plane_type, interchange); + if (IS_ERR(planes[zpos])) return PTR_ERR(planes[zpos]); @@ -708,15 +780,13 @@ static int apple_probe_typec_ports(struct drm_device *drm, * lowest-indexed Type-C-only pipeline (dcpext1). Fix the * connector to it: compositors read possible_crtcs once * and would otherwise pair it with a pipeline the stream - * can never be routed to. + * can never be routed to. T6030 instead narrows both + * connectors to the native processor holding their route. */ - if (secondary) { - if (dcp_is_typec_only(dcp[i]) && - (!mask || crtc_mask[i] < mask)) - mask = crtc_mask[i]; - continue; - } - mask |= crtc_mask[i]; + mask = dcp_fabric_port_crtc_mask(secondary, + dcp_typec_ordered_dual_stream(), + dcp_is_typec_only(dcp[i]), + mask, crtc_mask[i]); } if (!mask) { @@ -1018,6 +1088,13 @@ static int apple_drm_init(struct device *dev) drm_client_setup_with_fourcc(&apple->drm, DRM_FORMAT_XRGB8888); + /* A subsequent successful platform probe retries deferred GPU probes. */ + ret = apple_t6030_display_publish(dev); + if (ret) { + drm_dev_unregister(&apple->drm); + goto err_unbind; + } + return 0; err_unbind: @@ -1034,6 +1111,8 @@ static void apple_drm_uninit(struct device *dev) { struct apple_drm_private *apple = dev_get_drvdata(dev); + apple_t6030_display_withdraw(dev); + apple_drm_quiesce_connectors(&apple->drm); drm_dev_unplug(&apple->drm); drm_atomic_helper_shutdown(&apple->drm); diff --git a/drivers/gpu/drm/apple/audio-link-test.c b/drivers/gpu/drm/apple/audio-link-test.c new file mode 100644 index 00000000000000..a90d85f221ead2 --- /dev/null +++ b/drivers/gpu/drm/apple/audio-link-test.c @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by audio.c: a Terminate's link release ends only the link of the + * instance it is for. The production dcpaud_release_link() runs; the audio + * service's answer to which instance the link is on, and its link calls, + * are stubbed. + */ +#include +#include +#include + +struct dcpaud_link_test { + bool link_on; + u64 asked; + unsigned int completes; + unsigned int stops; +}; + +static struct dcpaud_link_test *dcpaud_link_current; + +static bool dcpaud_link_test_on(struct device *dev, u64 gen) +{ + dcpaud_link_current->asked = gen; + return dcpaud_link_current->link_on; +} + +static int dcpaud_link_test_call(struct device *dev, enum dcp_audio_link op, + const struct dcp_sound_cookie *cookie) +{ + if (op == DCP_AUDIO_LINK_COMPLETE) + dcpaud_link_current->completes++; + else if (op == DCP_AUDIO_LINK_STOP) + dcpaud_link_current->stops++; + return 0; +} + +static struct dcp_audio *dcpaud_link_setup(struct kunit *test, struct platform_device **pdev) +{ + struct dcpaud_link_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + struct dcp_audio *dcpaud = kunit_kzalloc(test, sizeof(*dcpaud), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, t); + KUNIT_ASSERT_NOT_NULL(test, dcpaud); + *pdev = kunit_platform_device_alloc(test, "dcpaud-link", PLATFORM_DEVID_AUTO); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, *pdev); + platform_set_drvdata(*pdev, dcpaud); + dcpaud->dev = &(*pdev)->dev; + dcpaud->dcp_dev = &(*pdev)->dev; + dcpaud->native_link = true; + mutex_init(&dcpaud->link_lock); + dcpaud_link_current = t; + kunit_activate_static_stub(test, dcp_audiosrv_link_on, dcpaud_link_test_on); + kunit_activate_static_stub(test, dcp_audiosrv_link, dcpaud_link_test_call); + return dcpaud; +} + +static void dcpaud_link_release_instance(struct kunit *test) +{ + struct platform_device *pdev; + struct dcp_audio *dcpaud = dcpaud_link_setup(test, &pdev); + u64 gen = 7; + + /* The link is on another instance: left as it is */ + dcpaud->link_prepared = true; + dcpaud->link_started = true; + dcpaud_release_link(pdev, &gen); + KUNIT_EXPECT_EQ(test, dcpaud_link_current->asked, 7ULL); + KUNIT_EXPECT_TRUE(test, dcpaud->link_prepared); + KUNIT_EXPECT_TRUE(test, dcpaud->link_started); + KUNIT_EXPECT_EQ(test, dcpaud_link_current->stops + dcpaud_link_current->completes, 0U); + + /* On the instance asked for: stopped and completed */ + dcpaud_link_current->link_on = true; + dcpaud_release_link(pdev, &gen); + KUNIT_EXPECT_FALSE(test, dcpaud->link_prepared); + KUNIT_EXPECT_FALSE(test, dcpaud->link_started); + KUNIT_EXPECT_EQ(test, dcpaud_link_current->stops, 1U); + KUNIT_EXPECT_EQ(test, dcpaud_link_current->completes, 1U); + + /* Without an instance (the display's own power-off): whichever link */ + dcpaud_link_current->link_on = false; + dcpaud->link_prepared = true; + dcpaud_release_link(pdev, NULL); + KUNIT_EXPECT_FALSE(test, dcpaud->link_prepared); + KUNIT_EXPECT_EQ(test, dcpaud_link_current->completes, 2U); +} + +static struct kunit_case dcpaud_link_cases[] = { + KUNIT_CASE(dcpaud_link_release_instance), + {} +}; + +static struct kunit_suite dcpaud_link_suite = { + .name = "apple-dcpaud-release-link", + .test_cases = dcpaud_link_cases, +}; + +kunit_test_suite(dcpaud_link_suite); diff --git a/drivers/gpu/drm/apple/audio-no-sio-test.c b/drivers/gpu/drm/apple/audio-no-sio-test.c new file mode 100644 index 00000000000000..8ea2387ff47415 --- /dev/null +++ b/drivers/gpu/drm/apple/audio-no-sio-test.c @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by audio.c: a DP audio interface whose SIO never registers its + * DMA controller (refused for an earlier boot loader's tables) gets no TX + * channel; a PCM open fails with -ENXIO, each time, and nothing is kept. + */ +#include +#include +#include + +OF_OVERLAY_DECLARE(audio_no_sio_test); + +static void dcpaud_no_sio_put(void *data) +{ + struct device *dev = data; + + of_node_put(dev->of_node); + dev->of_node = NULL; +} + +static void dcpaud_no_sio_test(struct kunit *test) +{ + struct dcp_audio *dcpaud = kunit_kzalloc(test, sizeof(*dcpaud), GFP_KERNEL); + struct device *dev; + + KUNIT_ASSERT_NOT_NULL(test, dcpaud); + KUNIT_ASSERT_EQ(test, 0, of_overlay_apply_kunit(test, audio_no_sio_test)); + dev = kunit_device_register(test, "dcpaud-no-sio"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dev->of_node = of_find_node_by_path("/dcpaud-no-sio-test/dpaudio-no-sio"); + KUNIT_ASSERT_NOT_NULL(test, dev->of_node); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcpaud_no_sio_put, dev), 0); + dcpaud->dev = dev; + mutex_init(&dcpaud->data_lock); + + KUNIT_EXPECT_EQ(test, dcpaud_init_dma(dcpaud), -ENXIO); + KUNIT_EXPECT_NULL(test, dcpaud->chan); + /* Every later open fails the same way, with nothing left behind */ + KUNIT_EXPECT_EQ(test, dcpaud_init_dma(dcpaud), -ENXIO); + KUNIT_EXPECT_NULL(test, dcpaud->chan); +} + +static struct kunit_case dcpaud_no_sio_cases[] = { + KUNIT_CASE(dcpaud_no_sio_test), + {} +}; + +static struct kunit_suite dcpaud_no_sio_suite = { + .name = "apple-dcpaud-no-sio", + .test_cases = dcpaud_no_sio_cases, +}; + +kunit_test_suite(dcpaud_no_sio_suite); diff --git a/drivers/gpu/drm/apple/audio-no-sio-test.dtso b/drivers/gpu/drm/apple/audio-no-sio-test.dtso new file mode 100644 index 00000000000000..9719e7078b3928 --- /dev/null +++ b/drivers/gpu/drm/apple/audio-no-sio-test.dtso @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/dts-v1/; +/plugin/; + +/* + * A DP audio interface whose DMA controller never registers, as the T6030 + * SIO with an earlier boot loader's tables: its probe refuses it. Nothing + * binds to these nodes; the test requests the channel itself. + */ +&{/} { + dcpaud-no-sio-test { + #address-cells = <2>; + #size-cells = <2>; + + sio_stub: sio-stub { + #dma-cells = <1>; + }; + + dpaudio-no-sio { + dmas = <&sio_stub 0x66>; + dma-names = "tx"; + }; + }; +}; diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index cc54ae2a9b5874..2b507dc1fa1b00 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -11,6 +11,7 @@ #define DEBUG +#include #include #include #include @@ -32,6 +33,8 @@ #define DCPAUD_ELEMENTS_MAXSIZE 16384 #define DCPAUD_PRODUCTATTRS_MAXSIZE 1024 +/* The native element catalog capacity (14.7 external role). */ +#define DCPAUD_ELEMENTS_V14_7 SZ_256K /* * SIO takes one of its 64 descriptor slots per period, shared by all its @@ -68,8 +71,34 @@ struct dcp_audio { void *productattrs; struct snd_pcm_chmap *chmap_info; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* + * DCP firmware 14.7, external role (T6030 external processor): the + * native link lifecycle, one link per stream start + * (dcp_native_playback_ops). + */ + bool native_link; + struct mutex link_lock; + bool link_prepared; + bool link_started; +#endif }; +/* The 14.7 external role's audio service (DRM_APPLE_DCP_T6030_AUDIO only). */ +static inline bool dcpaud_native_link(struct dcp_audio *dcpaud) +{ +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + return dcpaud->native_link; +#else + return false; +#endif +} + +static inline size_t dcpaud_elements_size(struct dcp_audio *dcpaud) +{ + return dcpaud_native_link(dcpaud) ? DCPAUD_ELEMENTS_V14_7 : DCPAUD_ELEMENTS_MAXSIZE; +} + static const struct snd_pcm_hardware dcp_pcm_hw = { .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_INTERLEAVED, @@ -118,7 +147,7 @@ static int dcpaud_read_remote_info(struct dcp_audio *dcpaud) int ret; ret = dcp_audiosrv_get_elements(dcpaud->dcp_dev, dcpaud->elements, - DCPAUD_ELEMENTS_MAXSIZE); + dcpaud_elements_size(dcpaud)); if (ret < 0) return ret; @@ -175,8 +204,11 @@ static void dcpaud_consult_elements(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = DCPAUD_ELEMENTS_MAXSIZE - 4, + .len = dcpaud_elements_size(dcpaud) - 4, .pos = 0, +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + .v14_7_audio = dcpaud->native_link, +#endif }; dcpaud_fill_fmt_sieve(params, &sieve); @@ -192,8 +224,11 @@ static int dcpaud_select_cookie(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = DCPAUD_ELEMENTS_MAXSIZE - 4, + .len = dcpaud_elements_size(dcpaud) - 4, .pos = 0, +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + .v14_7_audio = dcpaud->native_link, +#endif }; dcpaud_fill_fmt_sieve(params, &sieve); @@ -557,6 +592,239 @@ struct snd_pcm_ops dcp_playback_ops = { .pointer = dcp_pcm_pointer, }; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* + * DCP firmware 14.7, external role (the T6030 external processor, J514S + * built-in HDMI): the link lifecycle of the native audio driver: + * + * prepare: the DMA channel configured, then the link prepared, once; + * START: the cyclic DMA issued, then the link started; + * STOP: the DMA terminated; + * sync_stop: the DMA drained, then the link stopped and completed; + * hw_free: a link prepared but never started, completed. + * + * Every link method carries the selected element's link data. A link of an + * earlier connection went with its service: its state is dropped unsent. + * The audio service itself is open only while the PCM is. + */ +static int dcp_pcm_native_open(struct snd_pcm_substream *substream) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + bool live; + int ret; + + scoped_guard(mutex, &dcpaud->data_lock) + live = dcpaud->connected; + if (live) { + ret = dcp_audiosrv_open(dcpaud->dcp_dev); + if (ret) + return ret; + } + + ret = dcp_pcm_open(substream); + if (ret && live) + dcp_audiosrv_close(dcpaud->dcp_dev); + + return ret; +} + +static int dcp_pcm_native_close(struct snd_pcm_substream *substream) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + int ret = dcp_pcm_close(substream); + + dcp_audiosrv_close(dcpaud->dcp_dev); + + return ret; +} + +/* + * Stop and complete the link held, on the open audio service (@live), or + * drop both unsent with a service that went away. + */ +static void dcpaud_link_teardown(struct dcp_audio *dcpaud, bool live) +{ + int ret; + + lockdep_assert_held(&dcpaud->link_lock); + if (dcpaud->link_started && live) { + ret = dcp_audiosrv_link(dcpaud->dcp_dev, DCP_AUDIO_LINK_STOP, + &dcpaud->selected_cookie); + if (ret) + dev_err(dcpaud->dev, "audio link stop failed: %d\n", ret); + } + dcpaud->link_started = false; + if (dcpaud->link_prepared && live) { + ret = dcp_audiosrv_link(dcpaud->dcp_dev, DCP_AUDIO_LINK_COMPLETE, + &dcpaud->selected_cookie); + if (ret) + dev_err(dcpaud->dev, "audio link complete failed: %d\n", ret); + } + dcpaud->link_prepared = false; +} + +/* New parameters select a new element: the link of the old one ends first. */ +static int dcp_pcm_native_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + + scoped_guard(mutex, &dcpaud->link_lock) + dcpaud_link_teardown(dcpaud, dcpaud_connection_up(dcpaud)); + + return dcp_pcm_hw_params(substream, params); +} + +static int dcp_pcm_native_hw_free(struct snd_pcm_substream *substream) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + + guard(mutex)(&dcpaud->link_lock); + dcpaud_link_teardown(dcpaud, dcpaud_connection_up(dcpaud)); + + return 0; +} + +static int dcp_pcm_native_prepare(struct snd_pcm_substream *substream) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + struct dma_slave_config slave_config = { + .direction = DMA_MEM_TO_DEV, + /* One 32-bit DPA entry per sample word, as in hw_params. */ + .dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES, + }; + int ret; + + if (dcpaud->open_unplugged) + return 0; + + if (!dcpaud_connection_up(dcpaud)) + return -ENXIO; + + guard(mutex)(&dcpaud->link_lock); + if (dcpaud->link_prepared) + return 0; + + /* The SIO channel is configured again before every link prepare. */ + ret = dmaengine_slave_config(snd_dmaengine_pcm_get_chan(substream), + &slave_config); + if (ret) + return ret; + + ret = dcp_audiosrv_link(dcpaud->dcp_dev, DCP_AUDIO_LINK_PREPARE, + &dcpaud->selected_cookie); + if (ret) + return ret; + + dcpaud->link_prepared = true; + return 0; +} + +static int dcp_pcm_native_start(struct snd_pcm_substream *substream, int cmd) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + int ret; + + if (!dcpaud_connection_up(dcpaud)) + return -ENXIO; + + /* The first period descriptor is issued before the link starts. */ + ret = snd_dmaengine_pcm_trigger(substream, cmd); + if (ret) + return ret; + + guard(mutex)(&dcpaud->link_lock); + if (!dcpaud->link_prepared) + return -EBADFD; + if (dcpaud->link_started) + return 0; + ret = dcp_audiosrv_link(dcpaud->dcp_dev, DCP_AUDIO_LINK_START, + &dcpaud->selected_cookie); + dcpaud->link_started = !ret; + return ret; +} + +static int dcp_pcm_native_trigger(struct snd_pcm_substream *substream, int cmd) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + int ret; + + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + /* + * Balanced by STOP, which the PCM core also sends after a + * failed start; sync_stop then drains the DMA and completes + * the link. + */ + WARN_ON(pm_runtime_get_sync(dcpaud->dev) < 0); + return dcp_pcm_native_start(substream, cmd); + + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_SUSPEND: + ret = snd_dmaengine_pcm_trigger(substream, cmd); + pm_runtime_mark_last_busy(dcpaud->dev); + __pm_runtime_put_autosuspend(dcpaud->dev); + return ret; + + default: + return -EINVAL; + } +} + +static int dcp_pcm_native_sync_stop(struct snd_pcm_substream *substream) +{ + struct dcp_audio *dcpaud = substream->pcm->private_data; + int ret; + + /* SIO TERMINATE acknowledged and the issued periods reported back. */ + ret = snd_dmaengine_pcm_sync_stop(substream); + + guard(mutex)(&dcpaud->link_lock); + dcpaud_link_teardown(dcpaud, dcpaud_connection_up(dcpaud)); + + return ret; +} + +/* + * The card was disconnected (its stream stopped) while the audio service + * stays: the display was powered off or the sink released, and the service + * is about to be closed. Its link is completed first, the DMA drained + * before: the firmware keeps a link prepared by a client that closes without + * completing it, and refuses every later link prepare of that service + * (0xe00002ea), so every later open failed. + */ +void dcpaud_release_link(struct platform_device *pdev, const u64 *gen) +{ + struct dcp_audio *dcpaud; + + KUNIT_STATIC_STUB_REDIRECT(dcpaud_release_link, pdev, gen); + dcpaud = platform_get_drvdata(pdev); + if (!dcpaud->native_link) + return; + guard(mutex)(&dcpaud->link_lock); + if (!dcpaud->link_prepared && !dcpaud->link_started) + return; + /* Only that instance's link: a later instance's PCM keeps its own. */ + if (gen && !dcp_audiosrv_link_on(dcpaud->dcp_dev, *gen)) + return; + if (dcpaud->chan) + dmaengine_synchronize(dcpaud->chan); + dcpaud_link_teardown(dcpaud, true); +} + +static const struct snd_pcm_ops dcp_native_playback_ops = { + .open = dcp_pcm_native_open, + .close = dcp_pcm_native_close, + .hw_params = dcp_pcm_native_hw_params, + .hw_free = dcp_pcm_native_hw_free, + .prepare = dcp_pcm_native_prepare, + .trigger = dcp_pcm_native_trigger, + .sync_stop = dcp_pcm_native_sync_stop, + .pointer = snd_dmaengine_pcm_pointer, +}; +#endif + // Transitional workaround: for the chmap control TLV, advertise options // copied from hdmi-codec.c #include "hdmi-codec-chmap.h" @@ -608,6 +876,11 @@ static int dcpaud_create_pcm(struct dcp_audio *dcpaud) if (ret) return ret; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + if (dcpaud_native_link(dcpaud)) + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &dcp_native_playback_ops); + else +#endif snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &dcp_playback_ops); dcpaud->substream = pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream; pcm->nonatomic = true; @@ -726,8 +999,10 @@ void dcpaud_connect(struct platform_device *pdev, bool connected) void dcpaud_disconnect(struct platform_device *pdev) { - struct dcp_audio *dcpaud = platform_get_drvdata(pdev); + struct dcp_audio *dcpaud; + KUNIT_STATIC_STUB_REDIRECT(dcpaud_disconnect, pdev); + dcpaud = platform_get_drvdata(pdev); mutex_lock(&dcpaud->data_lock); dcpaud_report_hotplug(dcpaud, false); @@ -781,6 +1056,19 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) } dcpaud->dcp_dev = &dcp_pdev->dev; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* The 14.7 external role: its native links and element catalog. */ + if (dcp_audiosrv_native_link(dcpaud->dcp_dev)) { + void *elements = devm_kzalloc(dev, DCPAUD_ELEMENTS_V14_7, GFP_KERNEL); + + if (!elements) + goto rpm_put; + devm_kfree(dev, dcpaud->elements); + dcpaud->elements = elements; + dcpaud->native_link = true; + } +#endif + dma_pdev = of_find_device_by_node(dma_spec.np); of_node_put(dma_spec.np); if (!dma_pdev) { @@ -801,7 +1089,7 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) dcpaud_expose_debugfs_blob(dcpaud, "selected_cookie", &dcpaud->selected_cookie, sizeof(dcpaud->selected_cookie)); dcpaud_expose_debugfs_blob(dcpaud, "elements", dcpaud->elements, - DCPAUD_ELEMENTS_MAXSIZE); + dcpaud_elements_size(dcpaud)); dcpaud_expose_debugfs_blob(dcpaud, "product_attrs", dcpaud->productattrs, DCPAUD_PRODUCTATTRS_MAXSIZE); } @@ -849,6 +1137,9 @@ static int dcpaud_probe(struct platform_device *pdev) dcpaud->dev = &pdev->dev; mutex_init(&dcpaud->data_lock); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + mutex_init(&dcpaud->link_lock); +#endif INIT_DELAYED_WORK(&dcpaud->void_work, dcpaud_void_work); platform_set_drvdata(pdev, dcpaud); @@ -908,3 +1199,9 @@ void dcp_audio_unregister(void) platform_driver_unregister(&dcpaud_driver); } +#if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) +#include "audio-no-sio-test.c" +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +#include "audio-link-test.c" +#endif +#endif diff --git a/drivers/gpu/drm/apple/audio.h b/drivers/gpu/drm/apple/audio.h index 83b990dc6c343f..58633598253eaa 100644 --- a/drivers/gpu/drm/apple/audio.h +++ b/drivers/gpu/drm/apple/audio.h @@ -17,4 +17,24 @@ int dcp_audiosrv_get_product_attrs(struct device *dev, void *attrs, size_t maxsi void dcpaud_connect(struct platform_device *pdev, bool connected); void dcpaud_disconnect(struct platform_device *pdev); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* The native link methods of the DCP firmware 14.7 external role. */ +enum dcp_audio_link { + DCP_AUDIO_LINK_PREPARE, + DCP_AUDIO_LINK_START, + DCP_AUDIO_LINK_STOP, + DCP_AUDIO_LINK_COMPLETE, +}; + +bool dcp_audiosrv_native_link(struct device *dev); +int dcp_audiosrv_open(struct device *dev); +void dcp_audiosrv_close(struct device *dev); +int dcp_audiosrv_link(struct device *dev, enum dcp_audio_link op, + const struct dcp_sound_cookie *cookie); +/* @gen: only a link prepared on that instance, still the open one (NULL: any) */ +void dcpaud_release_link(struct platform_device *pdev, const u64 *gen); +/* Whether the link prepared last is on instance @gen, still the open one */ +bool dcp_audiosrv_link_on(struct device *dev, u64 gen); +#endif + #endif /* __AUDIO_H__ */ diff --git a/drivers/gpu/drm/apple/av-lifetime-test.c b/drivers/gpu/drm/apple/av-lifetime-test.c new file mode 100644 index 00000000000000..0232dfb670bbda --- /dev/null +++ b/drivers/gpu/drm/apple/av-lifetime-test.c @@ -0,0 +1,690 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by av.c. Real workqueue lifetime for audiosrv_data: quiesce drains + * owner work before the owner is marked dead, an ERR_PTR endpoint is not + * dereferenced, and skipping the drain lets the callback observe the dead + * owner. The deliberate no-drain control validates the test boundary; + * production-body mutation runs separately verify the real drain. + */ +#include +#include +#include +#include +#include + +struct av_life_test { + struct device *dev; + void *group; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; + struct apple_dcp_afkep *ep; + struct workqueue_struct *wq; + struct work_struct ep_work; + struct work_struct stop_work; + struct workqueue_struct *stop_wq; + atomic_t owner_runs; + atomic_t owner_saw; + int ep_runs; + int ep_saw; + int dead; + struct completion entered; + struct completion release; + struct completion owner_done; + struct completion stop_entered; + struct completion stop_done; + bool stop_saw_owner_done; + bool stop_unbind; + bool stop_release_group; + struct audiosrv_data *release_owner; + struct apple_dcp_afkep *release_ep; + bool endpoint_released; + bool release_saw_stopped; + bool release_saw_quiesced; + bool group_released; +}; + +static struct av_life_test *av_life_current; +static void av_life_release_group(struct av_life_test *t); + +static void av_life_owner_fn(struct work_struct *work) +{ + struct av_life_test *t = av_life_current; + + atomic_set(&t->owner_saw, READ_ONCE(t->dead)); + atomic_inc(&t->owner_runs); + complete(&t->owner_done); +} + +static void av_life_stop_fn(struct work_struct *work) +{ + struct av_life_test *t = container_of(work, struct av_life_test, stop_work); + + complete(&t->stop_entered); + if (t->stop_release_group) + av_life_release_group(t); + else if (t->stop_unbind) + dcp_comp_unbind(t->dcp->dev, NULL, NULL); + else + av_audiosrv_quiesce(t->dcp); + t->stop_saw_owner_done = completion_done(&t->owner_done); + complete(&t->stop_done); +} + +static void av_life_cleanup(void *data) +{ + struct av_life_test *t = data; + + /* Assertion failure must not strand a blocked system worker. */ + complete_all(&t->release); + if (t->stop_unbind) + cancel_work_sync(&t->dcp->external_audio_work); + if (t->stop_wq) { + flush_work(&t->stop_work); + destroy_workqueue(t->stop_wq); + } + if (t->group) + av_life_release_group(t); + if (t->group_released) { + t->dcp->audiosrv = NULL; + t->dcp->avep = NULL; + } + av_audiosrv_quiesce(t->dcp); + /* Keep deliberately broken production mutants safe after assertions. */ + if (t->asrv && t->asrv->works_live) { + disable_work_sync(&t->asrv->start_av_service_wq); + disable_work_sync(&t->asrv->terminate_wq); + } + if (t->wq) + destroy_workqueue(t->wq); + if (t->ep && !IS_ERR(t->ep)) + t->ep->wq = NULL; + av_life_current = NULL; +} + +static void av_life_ep_fn(struct work_struct *work) +{ + struct av_life_test *t = av_life_current; + + t->ep_saw = READ_ONCE(t->dead); + t->ep_runs++; +} + +static void av_life_blocked_fn(struct work_struct *work) +{ + struct av_life_test *t = av_life_current; + + complete(&t->entered); + wait_for_completion(&t->release); + atomic_set(&t->owner_saw, READ_ONCE(t->dead)); + atomic_inc(&t->owner_runs); + complete(&t->owner_done); +} + +static void av_life_queue_blocker_fn(struct work_struct *work) +{ + struct av_life_test *t = av_life_current; + + complete(&t->entered); + wait_for_completion(&t->release); +} + +static void av_life_producer_fn(struct work_struct *work) +{ + struct av_life_test *t = av_life_current; + + complete(&t->entered); + wait_for_completion(&t->release); + /* Model only the initializer publication boundary, with real works. */ + t->dcp->audiosrv = t->asrv; + schedule_work(&t->asrv->start_av_service_wq); +} + +static struct av_life_test *av_life_setup(struct kunit *test, work_func_t owner_fn) +{ + struct av_life_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, t); + t->dev = kunit_device_register(test, "av-lifetime"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->dev); + t->dcp = kunit_kzalloc(test, sizeof(*t->dcp), GFP_KERNEL); + t->asrv = kunit_kzalloc(test, sizeof(*t->asrv), GFP_KERNEL); + t->ep = kunit_kzalloc(test, sizeof(*t->ep), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->dcp); + KUNIT_ASSERT_NOT_NULL(test, t->asrv); + KUNIT_ASSERT_NOT_NULL(test, t->ep); + t->dcp->dev = t->dev; + dev_set_drvdata(t->dev, t->dcp); + spin_lock_init(&t->ep->lock); + init_rwsem(&t->asrv->srv_rwsem); + INIT_WORK(&t->asrv->start_av_service_wq, owner_fn); + INIT_WORK(&t->asrv->terminate_wq, owner_fn); + INIT_WORK(&t->dcp->external_audio_work, av_life_owner_fn); + t->asrv->works_live = true; + t->dcp->audiosrv = t->asrv; + atomic_set(&t->owner_saw, -1); + init_completion(&t->entered); + init_completion(&t->release); + init_completion(&t->owner_done); + init_completion(&t->stop_entered); + init_completion(&t->stop_done); + INIT_WORK(&t->stop_work, av_life_stop_fn); + av_life_current = t; + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, av_life_cleanup, t), 0); + return t; +} + +static bool av_life_wait_reports_stopped(struct av_life_test *t) +{ + unsigned long deadline = jiffies + HZ; + bool stopped; + + do { + down_read(&t->asrv->srv_rwsem); + stopped = t->asrv->reports_stopped; + up_read(&t->asrv->srv_rwsem); + if (stopped) + return true; + usleep_range(50, 100); + } while (time_before(jiffies, deadline)); + return false; +} + +static void av_life_parallel_stop(struct kunit *test, struct av_life_test *t) +{ + unsigned long left; + + t->stop_wq = alloc_ordered_workqueue("av-lifetime-stop", 0); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->stop_wq); + KUNIT_ASSERT_TRUE(test, queue_work(t->stop_wq, &t->stop_work)); + left = wait_for_completion_timeout(&t->stop_entered, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + /* Observe entry into the real drain, rather than just its caller. */ + KUNIT_ASSERT_TRUE(test, av_life_wait_reports_stopped(t)); + /* The owner is deliberately still running: quiesce must wait. */ + left = wait_for_completion_timeout(&t->stop_done, msecs_to_jiffies(20)); + KUNIT_EXPECT_EQ(test, left, 0UL); + complete(&t->release); + left = wait_for_completion_timeout(&t->stop_done, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + KUNIT_EXPECT_TRUE(test, t->stop_saw_owner_done); +} + +/* Quiesce waits for owner work and flushes a live endpoint before dead. */ +static void av_lifetime_drain_before_dead(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_blocked_fn); + unsigned long left; + + t->wq = alloc_ordered_workqueue("av-lifetime-test", 0); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->wq); + t->ep->wq = t->wq; + t->dcp->avep = t->ep; + INIT_WORK(&t->ep_work, av_life_ep_fn); + + KUNIT_EXPECT_TRUE(test, queue_work(t->wq, &t->ep_work)); + KUNIT_EXPECT_TRUE(test, schedule_work(&t->asrv->terminate_wq)); + left = wait_for_completion_timeout(&t->entered, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + av_life_parallel_stop(test, t); + KUNIT_EXPECT_EQ(test, t->ep_runs, 1); + KUNIT_EXPECT_EQ(test, t->ep_saw, 0); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_saw), 0); + WRITE_ONCE(t->dead, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_saw), 0); + KUNIT_EXPECT_EQ(test, t->ep_saw, 0); + KUNIT_EXPECT_TRUE(test, t->asrv->work_disabled); + KUNIT_EXPECT_TRUE(test, t->asrv->reports_stopped); +} + +/* + * afk_init publishes ERR_PTR. Quiesce still drains owner work and must not + * dereference that pointer or clear it. + */ +static void av_lifetime_err_ptr_endpoint(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_blocked_fn); + unsigned long left; + + t->dcp->avep = ERR_PTR(-EINVAL); + KUNIT_EXPECT_TRUE(test, schedule_work(&t->asrv->start_av_service_wq)); + left = wait_for_completion_timeout(&t->entered, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + av_life_parallel_stop(test, t); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_saw), 0); + WRITE_ONCE(t->dead, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_saw), 0); + KUNIT_EXPECT_TRUE(test, IS_ERR(t->dcp->avep)); + KUNIT_EXPECT_EQ(test, PTR_ERR(t->dcp->avep), -EINVAL); + KUNIT_EXPECT_TRUE(test, t->asrv->work_disabled); +} + +/* Pending items are cancelled; only already-running callbacks must finish. */ +static void av_lifetime_pending_owner_cancelled(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_owner_fn); + unsigned long left; + + t->wq = alloc_ordered_workqueue("av-lifetime-pending", 0); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->wq); + INIT_WORK(&t->ep_work, av_life_queue_blocker_fn); + KUNIT_ASSERT_TRUE(test, queue_work(t->wq, &t->ep_work)); + left = wait_for_completion_timeout(&t->entered, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + KUNIT_ASSERT_TRUE(test, queue_work(t->wq, &t->asrv->start_av_service_wq)); + KUNIT_ASSERT_TRUE(test, queue_work(t->wq, &t->asrv->terminate_wq)); + av_audiosrv_quiesce(t->dcp); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 0); + KUNIT_EXPECT_FALSE(test, work_pending(&t->asrv->start_av_service_wq)); + KUNIT_EXPECT_FALSE(test, work_pending(&t->asrv->terminate_wq)); + WRITE_ONCE(t->dead, 1); + complete(&t->release); + flush_workqueue(t->wq); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 0); +} + +/* The real common-unbind entry must stop initialization before owner drain. */ +static void av_lifetime_unbind_waits_for_initializer(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_owner_fn); + unsigned long left; + unsigned long deadline; + bool disabled = false; + + t->dcp->external_native = true; + t->dcp->ext_dead = true; + t->dcp->audiosrv = NULL; + t->stop_unbind = true; + INIT_WORK(&t->dcp->external_audio_work, av_life_producer_fn); + KUNIT_ASSERT_TRUE(test, schedule_work(&t->dcp->external_audio_work)); + left = wait_for_completion_timeout(&t->entered, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + t->stop_wq = alloc_ordered_workqueue("av-lifetime-unbind", 0); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->stop_wq); + KUNIT_ASSERT_TRUE(test, queue_work(t->stop_wq, &t->stop_work)); + left = wait_for_completion_timeout(&t->stop_entered, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + /* + * The running producer cannot finish yet. Queue rejection with no + * pending requeue proves unbind reached disable_work_sync, rather + * than merely pausing before its first statement. Any admitted + * requeue is cancelled by the real disable before this succeeds. + */ + deadline = jiffies + HZ; + do { + if (!schedule_work(&t->dcp->external_audio_work) && + !work_pending(&t->dcp->external_audio_work)) { + disabled = true; + break; + } + usleep_range(50, 100); + } while (time_before(jiffies, deadline)); + KUNIT_EXPECT_TRUE(test, disabled); + left = wait_for_completion_timeout(&t->stop_done, msecs_to_jiffies(20)); + KUNIT_EXPECT_EQ(test, left, 0UL); + complete(&t->release); + left = wait_for_completion_timeout(&t->stop_done, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, t->asrv); + KUNIT_EXPECT_TRUE(test, t->asrv->reports_stopped); + KUNIT_EXPECT_TRUE(test, t->asrv->work_disabled); + KUNIT_EXPECT_FALSE(test, work_busy(&t->asrv->start_av_service_wq)); + KUNIT_EXPECT_FALSE(test, schedule_work(&t->asrv->start_av_service_wq)); + KUNIT_EXPECT_FALSE(test, schedule_work(&t->asrv->terminate_wq)); +} + +/* Two quiesces are one disable; one restart arms a single queue. */ +static void av_lifetime_quiesce_once_restart_once(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_owner_fn); + + av_audiosrv_quiesce(t->dcp); + av_audiosrv_quiesce(t->dcp); + KUNIT_EXPECT_FALSE(test, schedule_work(&t->asrv->terminate_wq)); + av_audiosrv_reports_restart(t->dcp); + /* A second restart must not underflow either work's disable count. */ + av_audiosrv_reports_restart(t->dcp); + KUNIT_EXPECT_FALSE(test, t->asrv->reports_stopped); + KUNIT_EXPECT_FALSE(test, t->asrv->work_disabled); + KUNIT_EXPECT_TRUE(test, schedule_work(&t->asrv->terminate_wq)); + flush_work(&t->asrv->terminate_wq); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_saw), 0); + av_audiosrv_quiesce(t->dcp); +} + +static void av_lifetime_report_after_stop(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_owner_fn); + struct apple_epic_service svc = { }; + struct epic_service_call call = { + .group = cpu_to_le16(2), + .command = cpu_to_le32(1), + .magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC), + }; + t->dcp->fw_compat = DCP_FIRMWARE_V_14_7; + t->dcp->external_native = true; + t->ep->dcp = t->dcp; + svc.ep = t->ep; + t->asrv->srv = &svc; + + av_audiosrv_quiesce(t->dcp); + av_audiosrv_quiesce(t->dcp); + av_audiosrv_report(&svc, 0, &call, sizeof(call)); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 0); + KUNIT_EXPECT_FALSE(test, work_busy(&t->asrv->terminate_wq)); + + av_audiosrv_reports_restart(t->dcp); + av_audiosrv_report(&svc, 0, &call, sizeof(call)); + flush_work(&t->asrv->terminate_wq); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); + av_audiosrv_quiesce(t->dcp); +} + +/* + * Negative control. The owner is marked dead with the callback blocked and + * without quiesce. The callback must observe that dead owner. + */ +static void av_lifetime_control_without_drain(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_blocked_fn); + unsigned long left; + + KUNIT_EXPECT_TRUE(test, schedule_work(&t->asrv->terminate_wq)); + left = wait_for_completion_timeout(&t->entered, HZ); + if (!left) { + complete(&t->release); + flush_work(&t->asrv->terminate_wq); + KUNIT_FAIL(test, "terminate work did not start"); + return; + } + WRITE_ONCE(t->dead, 1); + complete(&t->release); + flush_work(&t->asrv->terminate_wq); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_saw), 1); +} + +/* Never-initialized owner work is not passed to the workqueue. */ +static void av_lifetime_never_inited(struct kunit *test) +{ + struct av_life_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, t); + t->dcp = kunit_kzalloc(test, sizeof(*t->dcp), GFP_KERNEL); + t->asrv = kunit_kzalloc(test, sizeof(*t->asrv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->dcp); + KUNIT_ASSERT_NOT_NULL(test, t->asrv); + t->dcp->audiosrv = t->asrv; + t->dcp->avep = ERR_PTR(-ENODEV); + av_audiosrv_quiesce(t->dcp); + av_audiosrv_reports_restart(t->dcp); + KUNIT_EXPECT_FALSE(test, t->asrv->works_live); + KUNIT_EXPECT_FALSE(test, t->asrv->work_disabled); + KUNIT_EXPECT_FALSE(test, t->asrv->reports_stopped); + KUNIT_EXPECT_EQ(test, PTR_ERR(t->dcp->avep), -ENODEV); +} + +/* Failed start stays disarmed across a bind restart. */ +static void av_lifetime_failed_start_stays_stopped(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_owner_fn); + + t->dcp->avep = ERR_PTR(-EIO); + av_audiosrv_block_owner_restart(t->asrv); + av_audiosrv_quiesce(t->dcp); + av_audiosrv_reports_restart(t->dcp); + KUNIT_EXPECT_TRUE(test, t->asrv->work_disabled); + KUNIT_EXPECT_TRUE(test, t->asrv->reports_stopped); + KUNIT_EXPECT_FALSE(test, schedule_work(&t->asrv->terminate_wq)); + KUNIT_EXPECT_EQ(test, PTR_ERR(t->dcp->avep), -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 0); +} + + +/* The fake context action runs where afk_release_context would run. */ +static void av_life_endpoint_release(void *data) +{ + struct av_life_test *t = data; + + t->release_saw_stopped = t->release_owner->reports_stopped && + t->release_owner->work_disabled; + t->release_saw_quiesced = !t->release_ep->wq; + t->endpoint_released = true; + /* Keep a missing-quiesce mutant from leaking the actual queue. */ + afk_quiesce(t->release_ep); +} + +static void av_life_release_group(struct av_life_test *t) +{ + devres_release_group(t->dev, t->group); + t->group = NULL; + t->group_released = true; + t->asrv = NULL; + t->ep = NULL; + t->wq = NULL; +} + +static struct av_life_test *av_life_group_setup(struct kunit *test, + work_func_t fn, int endpoint) +{ + struct av_life_test *t = av_life_setup(test, fn); + + t->group = devres_open_group(t->dev, NULL, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->group); + t->asrv = devm_kzalloc(t->dev, sizeof(*t->asrv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->asrv); + init_rwsem(&t->asrv->srv_rwsem); + INIT_WORK(&t->asrv->start_av_service_wq, fn); + INIT_WORK(&t->asrv->terminate_wq, fn); + t->asrv->works_live = true; + t->dcp->audiosrv = t->asrv; + if (endpoint > 0) { + t->ep = devm_kzalloc(t->dev, sizeof(*t->ep), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->ep); + spin_lock_init(&t->ep->lock); + t->ep->dcp = t->dcp; + t->wq = alloc_ordered_workqueue("av-lifetime-devres", 0); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->wq); + t->ep->wq = t->wq; + t->release_ep = t->ep; + t->release_owner = t->asrv; + KUNIT_ASSERT_EQ(test, devm_add_action_or_reset(t->dev, + av_life_endpoint_release, t), 0); + } else { + t->ep = endpoint < 0 ? ERR_PTR(endpoint) : NULL; + } + t->dcp->avep = t->ep; + return t; +} + +static void av_lifetime_devres_order(struct kunit *test) +{ + struct av_life_test *t = av_life_group_setup(test, av_life_blocked_fn, 1); + unsigned long left; + + KUNIT_ASSERT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, t->ep), 0); + devres_close_group(t->dev, t->group); + KUNIT_ASSERT_TRUE(test, schedule_work(&t->asrv->terminate_wq)); + left = wait_for_completion_timeout(&t->entered, HZ); + KUNIT_ASSERT_NE(test, left, 0UL); + t->stop_release_group = true; + av_life_parallel_stop(test, t); + KUNIT_EXPECT_TRUE(test, t->endpoint_released); + KUNIT_EXPECT_TRUE(test, t->release_saw_stopped); + KUNIT_EXPECT_TRUE(test, t->release_saw_quiesced); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, NULL); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->avep, NULL); + if (!t->dcp->audiosrv) + av_audiosrv_quiesce(t->dcp); +} + +static void av_lifetime_devres_null_endpoint(struct kunit *test) +{ + struct av_life_test *t = av_life_group_setup(test, av_life_owner_fn, 0); + + KUNIT_ASSERT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, NULL), 0); + devres_close_group(t->dev, t->group); + av_life_release_group(t); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, NULL); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->avep, NULL); +} + +static void av_lifetime_devres_error_endpoint(struct kunit *test) +{ + struct av_life_test *t = av_life_group_setup(test, av_life_owner_fn, -ENOMEM); + + KUNIT_ASSERT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, t->ep), 0); + devres_close_group(t->dev, t->group); + av_life_release_group(t); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, NULL); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->avep, NULL); +} + +/* Model only devm's allocation boundary; execute its real reset callback. */ +static int av_life_fail_add_action(struct device *dev, void (*action)(void *), void *data) +{ + action(data); + return -ENOMEM; +} + +static void av_lifetime_add_action_reset(struct kunit *test) +{ + struct av_life_test *t = av_life_group_setup(test, av_life_owner_fn, 1); + + kunit_activate_static_stub(test, av_audiosrv_add_action, av_life_fail_add_action); + KUNIT_EXPECT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, t->ep), -ENOMEM); + KUNIT_EXPECT_TRUE(test, t->asrv->restart_blocked); + KUNIT_EXPECT_TRUE(test, t->asrv->work_disabled); + KUNIT_EXPECT_TRUE(test, t->asrv->reports_stopped); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, NULL); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->avep, NULL); + KUNIT_EXPECT_PTR_EQ(test, t->ep->wq, NULL); + /* The endpoint action still belongs to this group and is idempotent. */ + devres_close_group(t->dev, t->group); + av_life_release_group(t); + KUNIT_EXPECT_TRUE(test, t->release_saw_stopped); + KUNIT_EXPECT_TRUE(test, t->release_saw_quiesced); +} + +static void av_lifetime_stale_owner_shared_error(struct kunit *test) +{ + struct av_life_test *t = av_life_group_setup(test, av_life_owner_fn, -ENOMEM); + struct audiosrv_data *next = kunit_kzalloc(test, sizeof(*next), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, next); + KUNIT_ASSERT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, t->ep), 0); + devres_close_group(t->dev, t->group); + t->dcp->audiosrv = next; + /* A shared ERR_PTR value identifies no particular endpoint owner. */ + t->dcp->avep = ERR_PTR(-ENOMEM); + av_life_release_group(t); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, next); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->avep, ERR_PTR(-ENOMEM)); +} + +static void av_lifetime_devres_preserves_successor(struct kunit *test) +{ + struct av_life_test *t = av_life_group_setup(test, av_life_owner_fn, 1); + struct audiosrv_data *next = kunit_kzalloc(test, sizeof(*next), GFP_KERNEL); + struct apple_dcp_afkep *ep = kunit_kzalloc(test, sizeof(*ep), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, next); + KUNIT_ASSERT_NOT_NULL(test, ep); + KUNIT_ASSERT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, t->ep), 0); + devres_close_group(t->dev, t->group); + t->dcp->audiosrv = next; + t->dcp->avep = ep; + av_life_release_group(t); + KUNIT_EXPECT_TRUE(test, t->release_saw_stopped); + KUNIT_EXPECT_TRUE(test, t->release_saw_quiesced); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, next); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->avep, ep); + KUNIT_EXPECT_FALSE(test, next->reports_stopped); + KUNIT_EXPECT_FALSE(test, next->work_disabled); +} + + +/* Releasing one group cannot leave restart state on the next owner. */ +static void av_lifetime_devres_fresh_rebind(struct kunit *test) +{ + struct av_life_test *t = av_life_group_setup(test, av_life_owner_fn, 0); + + KUNIT_ASSERT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, NULL), 0); + devres_close_group(t->dev, t->group); + av_life_release_group(t); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, NULL); + t->group = devres_open_group(t->dev, NULL, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->group); + t->group_released = false; + t->asrv = devm_kzalloc(t->dev, sizeof(*t->asrv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->asrv); + init_rwsem(&t->asrv->srv_rwsem); + INIT_WORK(&t->asrv->start_av_service_wq, av_life_owner_fn); + INIT_WORK(&t->asrv->terminate_wq, av_life_owner_fn); + t->asrv->works_live = true; + t->dcp->audiosrv = t->asrv; + KUNIT_ASSERT_EQ(test, av_audiosrv_register_cleanup(t->dcp, t->asrv, NULL), 0); + devres_close_group(t->dev, t->group); + av_audiosrv_reports_restart(t->dcp); + KUNIT_EXPECT_FALSE(test, t->asrv->work_disabled); + KUNIT_EXPECT_FALSE(test, t->asrv->restart_blocked); + KUNIT_ASSERT_TRUE(test, schedule_work(&t->asrv->start_av_service_wq)); + flush_work(&t->asrv->start_av_service_wq); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); + av_life_release_group(t); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->audiosrv, NULL); +} + +/* Common unbind owns one producer disable, balanced by one bind enable. */ +static void av_lifetime_producer_rebind_balance(struct kunit *test) +{ + struct av_life_test *t = av_life_setup(test, av_life_owner_fn); + + t->dcp->external_native = true; + t->dcp->ext_dead = true; + t->stop_unbind = true; + dcp_comp_unbind(t->dev, NULL, NULL); + KUNIT_EXPECT_FALSE(test, schedule_work(&t->dcp->external_audio_work)); + KUNIT_EXPECT_TRUE(test, enable_work(&t->dcp->external_audio_work)); + av_audiosrv_reports_restart(t->dcp); + KUNIT_EXPECT_TRUE(test, schedule_work(&t->dcp->external_audio_work)); + flush_work(&t->dcp->external_audio_work); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); + dcp_comp_unbind(t->dev, NULL, NULL); + KUNIT_EXPECT_FALSE(test, schedule_work(&t->dcp->external_audio_work)); + KUNIT_EXPECT_TRUE(test, enable_work(&t->dcp->external_audio_work)); + av_audiosrv_reports_restart(t->dcp); + KUNIT_EXPECT_TRUE(test, schedule_work(&t->dcp->external_audio_work)); + flush_work(&t->dcp->external_audio_work); + KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 2); +} + +static struct kunit_case av_lifetime_cases[] = { + KUNIT_CASE(av_lifetime_devres_fresh_rebind), + KUNIT_CASE(av_lifetime_producer_rebind_balance), + KUNIT_CASE(av_lifetime_devres_order), + KUNIT_CASE(av_lifetime_devres_null_endpoint), + KUNIT_CASE(av_lifetime_devres_error_endpoint), + KUNIT_CASE(av_lifetime_add_action_reset), + KUNIT_CASE(av_lifetime_stale_owner_shared_error), + KUNIT_CASE(av_lifetime_devres_preserves_successor), + KUNIT_CASE(av_lifetime_drain_before_dead), + KUNIT_CASE(av_lifetime_err_ptr_endpoint), + KUNIT_CASE(av_lifetime_pending_owner_cancelled), + KUNIT_CASE(av_lifetime_unbind_waits_for_initializer), + KUNIT_CASE(av_lifetime_quiesce_once_restart_once), + KUNIT_CASE(av_lifetime_report_after_stop), + KUNIT_CASE(av_lifetime_control_without_drain), + KUNIT_CASE(av_lifetime_never_inited), + KUNIT_CASE(av_lifetime_failed_start_stays_stopped), + {} +}; + +static struct kunit_suite av_lifetime_suite = { + .name = "apple-av-audio-lifetime", + .test_cases = av_lifetime_cases, +}; + +kunit_test_suite(av_lifetime_suite); diff --git a/drivers/gpu/drm/apple/av-v14-test.c b/drivers/gpu/drm/apple/av-v14-test.c new file mode 100644 index 00000000000000..8d78113fb8f173 --- /dev/null +++ b/drivers/gpu/drm/apple/av-v14-test.c @@ -0,0 +1,345 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by av.c: which instance the 14.7 external role's audio client + * opens and closes. One reusable service slot is published, torn down and + * published again by the production init and teardown; the production open, + * close, Terminate report and Terminate work run on it, with only the + * service calls stubbed. The works are disabled for the workqueue and run + * here, in test context, where the stubs apply. + */ +#include +#include +#include + +struct av_v14_test { + struct apple_dcp *dcp; + struct audiosrv_data *asrv; + struct apple_dcp_afkep ep; + struct apple_epic_service svc; + struct apple_epic_service other; + /* Service calls: the command, and the instance generation it went to */ + u32 calls[8]; + u64 call_gens[8]; + unsigned int ncalls; + /* The card's disconnects, and link releases with the instance asked for */ + unsigned int disconnects; + unsigned int releases; + u64 release_gen; + /* Within a link release: the old PCM closes, a successor is published and opened */ + bool successor_during_release; +}; + +static struct av_v14_test *av_v14_current; + +static int av_v14_call(struct apple_epic_service *srv, u32 command, const void *body, + size_t body_len, size_t body_pad, void *reply, size_t reply_len) +{ + struct av_v14_test *t = av_v14_current; + + if (t->ncalls < ARRAY_SIZE(t->calls)) { + t->calls[t->ncalls] = command; + t->call_gens[t->ncalls] = t->asrv->gen; + } + t->ncalls++; + memset(reply, 0, reply_len); + /* Open: status 0 at +0, opened at +16 */ + if (command == t->asrv->cmds.open && reply_len >= 24) + put_unaligned_le64(1, reply + 16); + return 0; +} + +static void av_v14_card_disconnect(struct platform_device *pdev) +{ + av_v14_current->disconnects++; +} + +static void av_v14_replace(struct av_v14_test *t); + +static void av_v14_release_link(struct platform_device *pdev, const u64 *gen) +{ + struct av_v14_test *t = av_v14_current; + + t->releases++; + t->release_gen = gen ? *gen : 0; + if (!t->successor_during_release) + return; + t->successor_during_release = false; + dcp_audiosrv_close(t->dcp->dev); + av_v14_replace(t); + KUNIT_EXPECT_EQ(kunit_get_current_test(), dcp_audiosrv_open(t->dcp->dev), 0); +} + +static void av_v14_publish(struct av_v14_test *t) +{ + t->svc.enabled = true; + t->svc.torndown = false; + av_audiosrv_init(&t->svc, "DCPAVAudioInterface", "test", 0); +} + +/* The instance removed, and its successor published in the same slot */ +static void av_v14_replace(struct av_v14_test *t) +{ + av_audiosrv_teardown(&t->svc); + av_v14_publish(t); +} + +static void av_v14_terminate(struct av_v14_test *t, struct apple_epic_service *service) +{ + struct epic_service_call call = { + .group = cpu_to_le16(2), + .command = cpu_to_le32(1), + .magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC), + }; + + av_audiosrv_report(service, 0, &call, sizeof(call)); +} + +static void av_v14_run_terminate_work(struct av_v14_test *t) +{ + av_work_service_terminate(&t->asrv->terminate_wq); +} + +static struct av_v14_test *av_v14_setup(struct kunit *test) +{ + struct av_v14_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + struct audiosrv_data *asrv; + struct device *dev; + + KUNIT_ASSERT_NOT_NULL(test, t); + t->dcp = kunit_kzalloc(test, sizeof(*t->dcp), GFP_KERNEL); + asrv = kunit_kzalloc(test, sizeof(*asrv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->dcp); + KUNIT_ASSERT_NOT_NULL(test, asrv); + dev = kunit_device_register(test, "av-v14"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dev_set_drvdata(dev, t->dcp); + t->dcp->dev = dev; + t->dcp->fw_compat = DCP_FIRMWARE_V_14_7; + t->dcp->external = true; + t->dcp->external_native = true; + + init_rwsem(&asrv->srv_rwsem); + mutex_init(&asrv->plug_lock); + mutex_init(&asrv->open_lock); + asrv->cmds = dcp_av_audio_cmds_v13_5; + INIT_WORK(&asrv->start_av_service_wq, av_work_service_start); + disable_work(&asrv->start_av_service_wq); + INIT_WORK(&asrv->terminate_wq, av_work_service_terminate); + disable_work(&asrv->terminate_wq); + t->asrv = asrv; + t->dcp->audiosrv = asrv; + + t->ep.dcp = t->dcp; + spin_lock_init(&t->svc.lock); + t->svc.ep = &t->ep; + spin_lock_init(&t->other.lock); + t->other.ep = &t->ep; + t->other.enabled = true; + av_v14_current = t; + kunit_activate_static_stub(test, av_audiosrv_call, av_v14_call); + kunit_activate_static_stub(test, dcpaud_disconnect, av_v14_card_disconnect); + kunit_activate_static_stub(test, dcpaud_release_link, av_v14_release_link); + /* A card, never dereferenced: its disconnect and link release are stubbed */ + asrv->audio_dev = (struct platform_device *)t; + av_v14_publish(t); + return t; +} + +/* Serial: one Open per instance while a PCM is open, one Close after it. */ +static void av_v14_open_close(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + KUNIT_EXPECT_EQ(test, t->svc.users, 2U); /* published, and open */ + dcp_audiosrv_close(t->dcp->dev); + dcp_audiosrv_close(t->dcp->dev); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->calls[0], t->asrv->cmds.open); + KUNIT_EXPECT_EQ(test, t->calls[1], t->asrv->cmds.close); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* A successor in the slot of an instance left open is opened, not skipped. */ +static void av_v14_successor_opened(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + av_v14_replace(t); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->calls[1], t->asrv->cmds.open); + KUNIT_EXPECT_EQ(test, t->call_gens[1], t->asrv->gen); + KUNIT_EXPECT_NE(test, t->call_gens[1], t->call_gens[0]); + /* Its Close goes to it */ + dcp_audiosrv_close(t->dcp->dev); + KUNIT_ASSERT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, t->calls[2], t->asrv->cmds.close); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* The Close of an instance gone is not sent to its successor in the same slot. */ +static void av_v14_old_close_not_to_successor(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + av_v14_replace(t); + dcp_audiosrv_close(t->dcp->dev); + KUNIT_EXPECT_EQ(test, t->ncalls, 1U); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* + * A Terminate's work, queued for an instance, runs after its successor took + * the slot and was opened: the successor stays open. The successor's own + * Terminate closes it. + */ +static void av_v14_old_terminate_vs_successor(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + av_v14_terminate(t, &t->svc); + av_v14_replace(t); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + av_v14_run_terminate_work(t); + KUNIT_EXPECT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_PTR_EQ(test, t->asrv->open_srv, &t->svc); + KUNIT_EXPECT_EQ(test, t->asrv->open_gen, t->asrv->gen); + + av_v14_terminate(t, &t->svc); + av_v14_run_terminate_work(t); + KUNIT_ASSERT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, t->calls[2], t->asrv->cmds.close); + KUNIT_EXPECT_EQ(test, t->call_gens[2], t->asrv->gen); + KUNIT_EXPECT_NULL(test, t->asrv->open_srv); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* An instance published over the open one, without a teardown, is opened too. */ +static void av_v14_republished(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + av_v14_publish(t); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + KUNIT_EXPECT_EQ(test, t->ncalls, 2U); + dcp_audiosrv_close(t->dcp->dev); + KUNIT_EXPECT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* + * A Terminate's disconnect is past its instance check when, within its link + * release, the old PCM closes and a successor is published in the same slot + * and opened: the Terminate's final Close leaves the successor open. + */ +static void av_v14_successor_during_release(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + u64 old; + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + old = t->asrv->gen; + av_v14_terminate(t, &t->svc); + t->successor_during_release = true; + av_v14_run_terminate_work(t); + /* The Terminate's, and the old instance's teardown's */ + KUNIT_EXPECT_EQ(test, t->disconnects, 2U); + KUNIT_EXPECT_EQ(test, t->releases, 1U); + KUNIT_EXPECT_EQ(test, t->release_gen, old); + /* Open, the old PCM's Close, the successor's Open; no Close after it */ + KUNIT_ASSERT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, t->calls[1], t->asrv->cmds.close); + KUNIT_EXPECT_EQ(test, t->call_gens[1], old); + KUNIT_EXPECT_EQ(test, t->calls[2], t->asrv->cmds.open); + KUNIT_EXPECT_NE(test, t->call_gens[2], old); + KUNIT_EXPECT_PTR_EQ(test, t->asrv->open_srv, &t->svc); + KUNIT_EXPECT_EQ(test, t->asrv->open_gen, t->asrv->gen); + dcp_audiosrv_close(t->dcp->dev); + KUNIT_EXPECT_EQ(test, t->ncalls, 4U); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* A Terminate that finds a successor published does nothing to it or the card. */ +static void av_v14_terminate_after_successor(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + av_v14_terminate(t, &t->svc); + av_v14_replace(t); + av_v14_run_terminate_work(t); + /* The old instance's teardown's only */ + KUNIT_EXPECT_EQ(test, t->disconnects, 1U); + KUNIT_EXPECT_EQ(test, t->releases, 0U); +} + +/* + * A link ends on the instance it was prepared on: once a successor is open, + * the old link's stop and complete are not sent, and its link is not on any + * open instance; a link prepared on the successor is. + */ +static void av_v14_link_instance(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + struct dcp_sound_cookie cookie = {}; + u64 old; + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + old = t->asrv->gen; + KUNIT_EXPECT_EQ(test, dcp_audiosrv_link(t->dcp->dev, DCP_AUDIO_LINK_PREPARE, &cookie), 0); + KUNIT_EXPECT_TRUE(test, dcp_audiosrv_link_on(t->dcp->dev, old)); + av_v14_replace(t); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + KUNIT_ASSERT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_link(t->dcp->dev, DCP_AUDIO_LINK_STOP, &cookie), -ENODEV); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_link(t->dcp->dev, DCP_AUDIO_LINK_COMPLETE, &cookie), + -ENODEV); + KUNIT_EXPECT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_FALSE(test, dcp_audiosrv_link_on(t->dcp->dev, old)); + KUNIT_EXPECT_FALSE(test, dcp_audiosrv_link_on(t->dcp->dev, t->asrv->gen)); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_link(t->dcp->dev, DCP_AUDIO_LINK_PREPARE, &cookie), 0); + KUNIT_EXPECT_TRUE(test, dcp_audiosrv_link_on(t->dcp->dev, t->asrv->gen)); + KUNIT_EXPECT_EQ(test, dcp_audiosrv_link(t->dcp->dev, DCP_AUDIO_LINK_COMPLETE, &cookie), 0); + KUNIT_EXPECT_EQ(test, t->ncalls, 5U); +} + +/* A Terminate from an instance that is not the published one does nothing. */ +static void av_v14_terminate_unpublished(struct kunit *test) +{ + struct av_v14_test *t = av_v14_setup(test); + + KUNIT_EXPECT_EQ(test, dcp_audiosrv_open(t->dcp->dev), 0); + av_v14_terminate(t, &t->other); + av_v14_run_terminate_work(t); + KUNIT_EXPECT_EQ(test, t->ncalls, 1U); + KUNIT_EXPECT_PTR_EQ(test, t->asrv->open_srv, &t->svc); + dcp_audiosrv_close(t->dcp->dev); + KUNIT_EXPECT_EQ(test, t->ncalls, 2U); +} + +static struct kunit_case av_v14_cases[] = { + KUNIT_CASE(av_v14_open_close), + KUNIT_CASE(av_v14_successor_opened), + KUNIT_CASE(av_v14_old_close_not_to_successor), + KUNIT_CASE(av_v14_old_terminate_vs_successor), + KUNIT_CASE(av_v14_republished), + KUNIT_CASE(av_v14_successor_during_release), + KUNIT_CASE(av_v14_terminate_after_successor), + KUNIT_CASE(av_v14_link_instance), + KUNIT_CASE(av_v14_terminate_unpublished), + {} +}; + +static struct kunit_suite av_v14_suite = { + .name = "apple-av-v14-audio", + .test_cases = av_v14_cases, +}; + +kunit_test_suite(av_v14_suite); diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index 8a19f2a295bbce..461d162e2c6e92 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -4,7 +4,10 @@ // #define DEBUG #include +#include #include +#include +#include #include #include #include @@ -53,7 +56,16 @@ static const struct dcp_av_audio_cmds dcp_av_audio_cmds_v13_5 = { .get_product_attrs = 18, }; +struct audiosrv_data; + +struct av_audiosrv_cleanup { + struct apple_dcp *dcp; + struct audiosrv_data *owner; + struct apple_dcp_afkep *ep; +}; + struct audiosrv_data { + struct av_audiosrv_cleanup cleanup; struct platform_device *audio_dev; bool plugged; struct mutex plug_lock; @@ -62,12 +74,41 @@ struct audiosrv_data { struct rw_semaphore srv_rwsem; /* Workqueue for starting the audio service */ struct work_struct start_av_service_wq; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* The 14.7 external role: let a terminated audio interface go. */ + struct work_struct terminate_wq; + /* + * The instance generation, changed when an instance is published or + * removed (srv_rwsem), so a slot reused for the next instance is not + * taken for the old one; the Terminate work's instance. + */ + u64 gen; + u64 terminate_gen; + /* + * The 14.7 external role: the instance the PCM opened and its + * generation (open_lock); open_srv holds a pin, so its slot is not + * reused while it is open. + */ + struct mutex open_lock; + struct apple_epic_service *open_srv; + u64 open_gen; + /* The instance the link was last prepared on (open_lock) */ + u64 link_gen; +#endif struct dcp_av_audio_cmds cmds; bool warned_get_elements; bool warned_get_product_attrs; bool is_open; + /* INIT_WORK has run for the embedded owner works. */ + bool works_live; + /* Report and service-start admission. Writers hold srv_rwsem. */ + bool reports_stopped; + /* One disable_work_sync is outstanding. Restart enables once. */ + bool work_disabled; + /* afk_init/afk_start failed. Rebind must not enable these works. */ + bool restart_blocked; }; static void av_interface_init(struct apple_epic_service *service, const char *name, @@ -97,6 +138,7 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam struct apple_dcp *dcp = service->ep->dcp; struct audiosrv_data *asrv = dcp->audiosrv; struct apple_epic_service *old; + bool queue_start; /* The owner pin keeps the slot from being recycled while published. */ service = afk_service_get(service); @@ -108,13 +150,18 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam down_write(&asrv->srv_rwsem); old = asrv->srv; asrv->srv = service; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + asrv->gen++; +#endif + queue_start = !asrv->reports_stopped; up_write(&asrv->srv_rwsem); if (old) afk_service_put(old); asrv->plugged = true; mutex_unlock(&asrv->plug_lock); - schedule_work(&asrv->start_av_service_wq); + if (queue_start) + schedule_work(&asrv->start_av_service_wq); } static void av_audiosrv_teardown(struct apple_epic_service *service) @@ -127,8 +174,12 @@ static void av_audiosrv_teardown(struct apple_epic_service *service) down_write(&asrv->srv_rwsem); owned = asrv->srv == service; - if (owned) + if (owned) { asrv->srv = NULL; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + asrv->gen++; +#endif + } up_write(&asrv->srv_rwsem); /* A stale generation must not unplug its successor. */ @@ -202,6 +253,190 @@ int dcp_audiosrv_unprepare(struct device *dev) return ret; } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* The audio service of the 14.7 external role, known before it starts. */ +bool dcp_audiosrv_native_link(struct device *dev) +{ + return dcp_is_v14_7_external(dev_get_drvdata(dev)); +} + +/* The 14.7 external role's audio service calls; KUnit stubs them. */ +static int av_audiosrv_call(struct apple_epic_service *srv, u32 command, const void *body, + size_t body_len, size_t body_pad, void *reply, size_t reply_len) +{ + KUNIT_STATIC_STUB_REDIRECT(av_audiosrv_call, srv, command, body, body_len, body_pad, + reply, reply_len); + return afk_service_call(srv, 0, command, body, body_len, body_pad, reply, reply_len, 0); +} + +/* + * The 14.7 external role: the service is open while a PCM is (see + * av_service_connect()). The instance the PCM opened is kept under open_lock, + * which the endpoint's receive path never takes, and the calls are made + * without srv_rwsem: a teardown arriving meanwhile goes through, and so do + * the replies. The audio slots are reusable, so the open instance is kept + * pinned, with its generation: its slot cannot be reused while it is open, + * a successor is opened even in the same slot, and a removed instance is + * never closed (it took its open with it), so no Close goes to a successor. + */ +int dcp_audiosrv_open(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_epic_service *srv; + u8 reply[32] = {}; + u64 gen; + int ret; + + if (!asrv) + return -ENODEV; + + guard(mutex)(&asrv->open_lock); + scoped_guard(rwsem_read, &asrv->srv_rwsem) { + srv = afk_service_get(asrv->srv); + gen = asrv->gen; + } + if (!srv) + return -ENODEV; + if (asrv->open_srv) { + if (asrv->open_gen == gen) { + afk_service_put(srv); + return 0; + } + /* An earlier instance's open went with that instance. */ + afk_service_put(asrv->open_srv); + asrv->open_srv = NULL; + } + + /* Open: a zero body; status at +0, the opened Boolean at +16. */ + ret = av_audiosrv_call(srv, asrv->cmds.open, NULL, 0, 32, reply, sizeof(reply)); + if (!ret && (get_unaligned_le32(reply) || !get_unaligned_le64(reply + 16))) { + dev_err(dev, "audiosrv: open answered %#x, opened %llu\n", + get_unaligned_le32(reply), get_unaligned_le64(reply + 16)); + ret = -EIO; + } + if (ret) { + afk_service_put(srv); + return ret; + } + asrv->open_srv = srv; + asrv->open_gen = gen; + return 0; +} + +/* @gen: only the client of that instance (NULL: whichever is open) */ +static void av_audiosrv_close(struct apple_dcp *dcp, struct audiosrv_data *asrv, + const u64 *gen) +{ + struct apple_epic_service *srv; + u8 reply[16] = {}; + bool published; + int ret; + + guard(mutex)(&asrv->open_lock); + /* Checked here, at the Close: a later instance may be open by now. */ + if (gen && asrv->open_gen != *gen) + return; + srv = asrv->open_srv; + asrv->open_srv = NULL; + if (!srv) + return; + scoped_guard(rwsem_read, &asrv->srv_rwsem) + published = asrv->srv == srv && asrv->gen == asrv->open_gen; + + /* Close: a zero body; status at +0. Only the instance still published. */ + ret = published ? av_audiosrv_call(srv, asrv->cmds.close, NULL, 0, 16, reply, + sizeof(reply)) : -ENODEV; + afk_service_put(srv); + if (ret == -ENODEV) + return; + if (ret || get_unaligned_le32(reply)) + dev_err(dcp->dev, "audiosrv: close failed: %d, answered %#x\n", ret, + get_unaligned_le32(reply)); +} + +void dcp_audiosrv_close(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + + if (dcp->audiosrv) + av_audiosrv_close(dcp, dcp->audiosrv, NULL); +} + +bool dcp_audiosrv_link_on(struct device *dev, u64 gen) +{ + struct apple_dcp *dcp; + struct audiosrv_data *asrv; + + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_link_on, dev, gen); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; + if (!asrv) + return false; + guard(mutex)(&asrv->open_lock); + return asrv->open_srv && asrv->open_gen == gen && asrv->link_gen == gen; +} + +/* + * The link commands of the 14.7 external role's audio service, the native + * audio driver's: prepare, start, stop and complete all take the selected + * element's 32-byte link data at body+0 and link source 0 at +32, and + * answer a status at body+48. + */ +int dcp_audiosrv_link(struct device *dev, enum dcp_audio_link op, + const struct dcp_sound_cookie *cookie) +{ + struct apple_dcp *dcp; + struct audiosrv_data *asrv; + u8 body[64] = {}, reply[64]; + u32 command, status; + int ret; + + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_link, dev, op, cookie); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; + + switch (op) { + case DCP_AUDIO_LINK_PREPARE: + command = asrv->cmds.prepare; + break; + case DCP_AUDIO_LINK_START: + command = asrv->cmds.start_link; + break; + case DCP_AUDIO_LINK_STOP: + command = asrv->cmds.stop_link; + break; + case DCP_AUDIO_LINK_COMPLETE: + command = asrv->cmds.unprepare; + break; + default: + return -EINVAL; + } + static_assert(sizeof(*cookie) == DCP_SOUND_COOKIE_SIZE_V14_7); + memcpy(body, cookie, sizeof(*cookie)); + + scoped_guard(mutex, &asrv->open_lock) { + if (!asrv->open_srv) + return -ENODEV; + /* A link ends on the instance it was prepared on; one gone took it along. */ + if (op != DCP_AUDIO_LINK_PREPARE && asrv->link_gen != asrv->open_gen) + return -ENODEV; + ret = av_audiosrv_call(asrv->open_srv, command, body, sizeof(body), 0, + reply, sizeof(reply)); + if (!ret && op == DCP_AUDIO_LINK_PREPARE) + asrv->link_gen = asrv->open_gen; + } + if (ret) + return ret; + status = get_unaligned_le32(reply + 48); + if (status) { + dev_err(dev, "audiosrv: link method %u answered %#x\n", command, status); + return -EIO; + } + return 0; +} +#endif + static int dcp_audiosrv_osobject_call(struct apple_epic_service *service, u16 group, u32 command, void *output, size_t output_maxsize, @@ -283,9 +518,46 @@ int dcp_audiosrv_get_product_attrs(struct device *dev, void *attrs, size_t maxsi return ret; } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* A DCPAV report (group 2) with command 1: Terminate. */ +static bool av_report_terminate(const void *data, size_t size) +{ + const struct epic_service_call *call = data; + + return size >= sizeof(*call) && le32_to_cpu(call->magic) == EPIC_SERVICE_CALL_MAGIC && + le16_to_cpu(call->group) == 2 && le32_to_cpu(call->command) == 1; +} +#endif + static int av_audiosrv_report(struct apple_epic_service *service, u32 idx, const void *data, size_t data_size) { +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + struct apple_dcp *dcp = service->ep->dcp; + + /* + * The 14.7 external role terminates an open audio interface when the + * sink changes (after it reports the sink's physical address). Its + * client must close it (Close, command 5): the firmware waits up to + * 10 s for that before it removes the interface, and the sink's link + * with it. A later publication brings the new instance. + */ + if (dcp_is_v14_7_external(dcp) && av_report_terminate(data, data_size)) { + struct audiosrv_data *asrv = dcp->audiosrv; + bool published; + + /* The work acts on this instance only, not on a later one. */ + scoped_guard(rwsem_read, &asrv->srv_rwsem) { + published = asrv->srv == service && !asrv->reports_stopped; + if (published) + WRITE_ONCE(asrv->terminate_gen, asrv->gen); + } + if (published) { + dev_info(dcp->dev, "audio interface terminated\n"); + schedule_work(&asrv->terminate_wq); + } + } +#endif dev_dbg(service->ep->dcp->dev, "got audio report %d size %zx\n", idx, data_size); #ifdef DEBUG print_hex_dump(KERN_DEBUG, "audio report: ", DUMP_PREFIX_NONE, 16, 1, data, data_size, true); @@ -294,6 +566,30 @@ static int av_audiosrv_report(struct apple_epic_service *service, u32 idx, return 0; } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* + * The 14.7 external role behind a DP-to-HDMI converter (the J514S HDMI + * port) also publishes a CEC interface on this endpoint. The host makes no + * use of CEC; the interface's event reports (group 2: the sink's physical + * address, link training, link start and stop) are taken and dropped. + */ +static void av_cec_init(struct apple_epic_service *service, const char *name, + const char *class, s64 unit) +{ +} + +static int av_cec_report(struct apple_epic_service *service, enum epic_subtype type, + const void *data, size_t data_size) +{ + return 0; +} + +static void av_cec_teardown(struct apple_epic_service *service) +{ + afk_service_disable(service); +} +#endif + static const struct apple_epic_service_ops avep_ops[] = { { .name = "DCPAVSimpleVideoInterface", @@ -308,6 +604,14 @@ static const struct apple_epic_service_ops avep_ops[] = { .report = av_audiosrv_report, .teardown = av_audiosrv_teardown, }, +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + { + .name = "DCPDPCECInterface", + .init = av_cec_init, + .report = av_cec_report, + .teardown = av_cec_teardown, + }, +#endif {} }; @@ -328,6 +632,26 @@ void av_service_connect(struct apple_dcp *dcp) if (asrv->is_open) goto out; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* + * The 14.7 external role opens its audio service only while a PCM is + * (dcp_audiosrv_open()): an open audio interface is a client the + * firmware must wait for whenever the sink changes (see + * av_audiosrv_report()); an idle one need not be. The card follows + * the display's power (A472 on): the CRTC enable connects before the + * mode is set, and the modeset connects again once the display is on. + */ + if (dcp_is_v14_7_external(dcp)) { + if (!iomfb_v14_7_external_powered(dcp)) + goto out; + scoped_guard(mutex, &asrv->plug_lock) { + if (asrv->audio_dev) + dcpaud_connect(asrv->audio_dev, asrv->plugged); + } + goto out; + } +#endif + ret = afk_service_call(service, 0, asrv->cmds.open, NULL, 0, 32, NULL, 0, 32); if (ret) { @@ -344,13 +668,18 @@ void av_service_connect(struct apple_dcp *dcp) afk_service_put(service); } -void av_service_disconnect(struct apple_dcp *dcp) +/* @gen: only while that instance is published (NULL: whichever is) */ +static void __av_service_disconnect(struct apple_dcp *dcp, const u64 *gen) { struct apple_epic_service *service; struct audiosrv_data *asrv = dcp->audiosrv; int ret; scoped_guard(rwsem_write, &asrv->srv_rwsem) { +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + if (gen && asrv->gen != *gen) + return; +#endif service = afk_service_pin(asrv->srv); if (!service) return; @@ -358,6 +687,39 @@ void av_service_disconnect(struct apple_dcp *dcp) /* close AV audio service */ dev_info(dcp->dev, "%s: stopping audio service\n", __func__); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* The 14.7 external role's card goes with the display, and an open PCM's service. */ + if (dcp_is_v14_7_external(dcp)) { + struct platform_device *audio_dev = NULL; + bool published = true; + + /* + * Each step acts on instance @gen only, checked as it is taken: + * a successor may be published and opened in between. + */ + scoped_guard(mutex, &asrv->plug_lock) { + if (gen) { + scoped_guard(rwsem_read, &asrv->srv_rwsem) + published = asrv->gen == *gen; + } + if (published) { + audio_dev = asrv->audio_dev; + if (audio_dev) + dcpaud_disconnect(audio_dev); + } + } + if (!published) + goto out; + /* + * The open PCM's link ends on the service, before its Close; + * outside plug_lock, which the endpoint's receive path takes. + */ + if (audio_dev) + dcpaud_release_link(audio_dev, gen); + av_audiosrv_close(dcp, asrv, gen); + goto out; + } +#endif if (!asrv->is_open) goto out; @@ -380,6 +742,28 @@ void av_service_disconnect(struct apple_dcp *dcp) afk_service_put(service); } +void av_service_disconnect(struct apple_dcp *dcp) +{ + __av_service_disconnect(dcp, NULL); +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* The instance the Terminate came from, if it is still published. */ +static void av_work_service_terminate(struct work_struct *work) +{ + struct audiosrv_data *asrv = container_of(work, struct audiosrv_data, terminate_wq); + u64 gen = READ_ONCE(asrv->terminate_gen); + struct apple_dcp *dcp = NULL; + + scoped_guard(rwsem_read, &asrv->srv_rwsem) { + if (asrv->srv && asrv->srv->ep && asrv->gen == gen) + dcp = asrv->srv->ep->dcp; + } + if (dcp) + __av_service_disconnect(dcp, &gen); +} +#endif + static void av_work_service_start(struct work_struct *work) { struct audiosrv_data *audiosrv_data; @@ -400,12 +784,146 @@ static void av_work_service_start(struct work_struct *work) av_service_connect(dcp); } +static void av_audiosrv_flush_owner(struct audiosrv_data *asrv) +{ + flush_work(&asrv->start_av_service_wq); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + flush_work(&asrv->terminate_wq); +#endif +} + +/* Drain the captured owner, without following a later dcp publication. */ +static bool av_audiosrv_drain_owner(struct audiosrv_data *asrv) +{ + bool first_stop; + + if (!asrv || !asrv->works_live) + return false; + + down_write(&asrv->srv_rwsem); + first_stop = !asrv->work_disabled; + asrv->reports_stopped = true; + asrv->work_disabled = true; + up_write(&asrv->srv_rwsem); + + /* + * Queue admission is already refused. disable_work_sync then raises + * the work disable count and waits. No audio lock is held: the + * callback takes srv_rwsem and may RPC. A later call only flushes, + * so the disable count stays one for the rebind enable. + */ + if (first_stop) { + disable_work_sync(&asrv->start_av_service_wq); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + disable_work_sync(&asrv->terminate_wq); +#endif + } else { + av_audiosrv_flush_owner(asrv); + } + return true; +} + +static void av_audiosrv_block_owner_restart(struct audiosrv_data *asrv) +{ + if (!asrv) + return; + down_write(&asrv->srv_rwsem); + asrv->restart_blocked = true; + up_write(&asrv->srv_rwsem); +} + +void av_audiosrv_quiesce(struct apple_dcp *dcp) +{ + struct audiosrv_data *asrv; + struct apple_dcp_afkep *ep; + struct workqueue_struct *wq; + + if (!dcp) + return; + /* Lifecycle callers stop the native initializer before this snapshot. */ + asrv = dcp->audiosrv; + ep = dcp->avep; + if (!av_audiosrv_drain_owner(asrv)) + return; + if (IS_ERR_OR_NULL(ep)) + return; + wq = ep->wq; + if (!wq) + return; + flush_workqueue(wq); + av_audiosrv_flush_owner(asrv); +} + +static void av_audiosrv_cleanup(void *data) +{ + struct av_audiosrv_cleanup *cleanup = data; + struct audiosrv_data *asrv = cleanup->owner; + struct apple_dcp *dcp = cleanup->dcp; + + /* Keep RX alive until any owner work that may make an RPC has left. */ + if (asrv && asrv->works_live) { + av_audiosrv_block_owner_restart(asrv); + av_audiosrv_drain_owner(asrv); + } + afk_quiesce(cleanup->ep); + /* An old devres group must not unpublish a later session. */ + if (dcp->audiosrv == asrv) { + if (dcp->avep == cleanup->ep) + dcp->avep = NULL; + dcp->audiosrv = NULL; + } +} + +static int av_audiosrv_add_action(struct device *dev, void (*action)(void *), + void *data) +{ + KUNIT_STATIC_STUB_REDIRECT(av_audiosrv_add_action, dev, action, data); + return devm_add_action_or_reset(dev, action, data); +} + +static int av_audiosrv_register_cleanup(struct apple_dcp *dcp, + struct audiosrv_data *owner, + struct apple_dcp_afkep *ep) +{ + owner->cleanup = (struct av_audiosrv_cleanup) { + .dcp = dcp, + .owner = owner, + .ep = ep, + }; + return av_audiosrv_add_action(dcp->dev, av_audiosrv_cleanup, &owner->cleanup); +} + +void av_audiosrv_reports_restart(struct apple_dcp *dcp) +{ + struct audiosrv_data *asrv; + + if (!dcp) + return; + asrv = dcp->audiosrv; + if (!asrv || !asrv->works_live || asrv->restart_blocked) + return; + + down_write(&asrv->srv_rwsem); + if (!asrv->work_disabled || asrv->restart_blocked) { + up_write(&asrv->srv_rwsem); + return; + } + asrv->work_disabled = false; + enable_work(&asrv->start_av_service_wq); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + enable_work(&asrv->terminate_wq); +#endif + asrv->reports_stopped = false; + up_write(&asrv->srv_rwsem); +} + int avep_init(struct apple_dcp *dcp) { struct audiosrv_data *audiosrv_data; struct platform_device *audio_pdev; struct device *dev = dcp->dev; struct device_node *endpoint, *audio_node = NULL; + int ret; audiosrv_data = devm_kzalloc(dcp->dev, sizeof(*audiosrv_data), GFP_KERNEL); if (!audiosrv_data) @@ -422,12 +940,28 @@ int avep_init(struct apple_dcp *dcp) audiosrv_data->cmds = dcp_av_audio_cmds_v13_5; break; default: +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* + * The 14.7 external role (T6030 external processor) numbers its + * methods as 13.5 does: open 4, close 5, prepare 6, start 7, + * stop 10, complete 11, elements 1/16, product attributes 1/18. + */ + if (dcp_is_v14_7_external(dcp)) { + audiosrv_data->cmds = dcp_av_audio_cmds_v13_5; + break; + } +#endif dev_err(dcp->dev, "Audio not supported for firmware\n"); return -ENODEV; } - dcp->audiosrv = audiosrv_data; INIT_WORK(&audiosrv_data->start_av_service_wq, av_work_service_start); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + INIT_WORK(&audiosrv_data->terminate_wq, av_work_service_terminate); + mutex_init(&audiosrv_data->open_lock); +#endif + audiosrv_data->works_live = true; + dcp->audiosrv = audiosrv_data; endpoint = of_graph_get_endpoint_by_regs(dev->of_node, 0, 0); if (endpoint) { @@ -437,14 +971,14 @@ int avep_init(struct apple_dcp *dcp) if (!audio_node || !of_device_is_available(audio_node)) { of_node_put(audio_node); dev_info(dev, "No audio support\n"); - return 0; + return av_audiosrv_register_cleanup(dcp, audiosrv_data, NULL); } audio_pdev = of_find_device_by_node(audio_node); of_node_put(audio_node); if (!audio_pdev) { dev_info(dev, "No DP/HDMI audio device not ready\n"); - return 0; + return av_audiosrv_register_cleanup(dcp, audiosrv_data, NULL); } dcp->audiosrv->audio_dev = audio_pdev; @@ -452,8 +986,24 @@ int avep_init(struct apple_dcp *dcp) DL_FLAG_STATELESS | DL_FLAG_PM_RUNTIME); dcp->avep = afk_init(dcp, AV_ENDPOINT, avep_ops); - if (IS_ERR(dcp->avep)) - return PTR_ERR(dcp->avep); + if (IS_ERR(dcp->avep)) { + ret = PTR_ERR(dcp->avep); + if (!av_audiosrv_register_cleanup(dcp, audiosrv_data, dcp->avep)) + av_audiosrv_cleanup(&audiosrv_data->cleanup); + return ret; + } + /* Newer than afk_release_context, so owner work drains before RX dies. */ + ret = av_audiosrv_register_cleanup(dcp, audiosrv_data, dcp->avep); + if (ret) + return ret; dcp->avep->debugfs_entry = dcp->ep_debugfs[AV_ENDPOINT - 0x20]; - return afk_start(dcp->avep); + ret = afk_start(dcp->avep); + if (ret) + av_audiosrv_cleanup(&audiosrv_data->cleanup); + return ret; } + +#if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) && IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +#include "av-v14-test.c" +#include "av-lifetime-test.c" +#endif diff --git a/drivers/gpu/drm/apple/av.h b/drivers/gpu/drm/apple/av.h index c00cbef549fd2e..1d710b0f706f36 100644 --- a/drivers/gpu/drm/apple/av.h +++ b/drivers/gpu/drm/apple/av.h @@ -6,12 +6,21 @@ //int avep_audiosrv_startlink(struct apple_dcp *dcp, struct dcp_sound_cookie *cookie); //int avep_audiosrv_stoplink(struct apple_dcp *dcp); +/* dcp.c: the opt-in to DP/HDMI audio (appledrm.hdmi_audio). */ +extern bool hdmi_audio; + #if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) void av_service_connect(struct apple_dcp *dcp); void av_service_disconnect(struct apple_dcp *dcp); +/* Stop and drain owner work after the caller stops its native initializer. */ +void av_audiosrv_quiesce(struct apple_dcp *dcp); +/* Pair of av_audiosrv_quiesce after a later successful bind. */ +void av_audiosrv_reports_restart(struct apple_dcp *dcp); #else static inline void av_service_connect(struct apple_dcp *dcp) { } static inline void av_service_disconnect(struct apple_dcp *dcp) { } +static inline void av_audiosrv_quiesce(struct apple_dcp *dcp) { } +static inline void av_audiosrv_reports_restart(struct apple_dcp *dcp) { } #endif #endif /* __AV_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-fabric-core.c b/drivers/gpu/drm/apple/dcp-fabric-core.c index dccb400a9ff0f5..8c952dc0245605 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-core.c +++ b/drivers/gpu/drm/apple/dcp-fabric-core.c @@ -28,8 +28,9 @@ EXPORT_SYMBOL_GPL(dcp_fabric_t6020_flow); u8 dcp_fabric_tunnel_clock_blocked(bool t6030, unsigned int source) { - return t6030 ? BIT(1) | - (dcp_fabric_t6030_pclk(source, 0) < 0 ? BIT(0) : 0) : 0; + return t6030 ? + (dcp_fabric_t6030_pclk(source, 0) < 0 ? BIT(0) : 0) | + (dcp_fabric_t6030_pclk(source, 1) < 0 ? BIT(1) : 0) : 0; } EXPORT_SYMBOL_GPL(dcp_fabric_tunnel_clock_blocked); @@ -155,6 +156,13 @@ bool dcp_fabric_keep_order(bool dual_stream, bool ready, bool frozen) } EXPORT_SYMBOL_GPL(dcp_fabric_keep_order); +/* T6030 native pipelines retain their route; the encoder follows that owner. */ +bool dcp_fabric_ordered_dual_stream(bool wired, bool t6030) +{ + return wired && !t6030; +} +EXPORT_SYMBOL_GPL(dcp_fabric_ordered_dual_stream); + bool dcp_fabric_waiting(const struct dcp_fabric_port *port) { return !port->owner[0] && port->wanted && port->hpd; @@ -501,6 +509,15 @@ u32 dcp_fabric_connector_mask(bool dual_stream, bool bound, bool routed, } EXPORT_SYMBOL_GPL(dcp_fabric_connector_mask); +u32 dcp_fabric_port_crtc_mask(bool secondary, bool ordered_dual, bool typec_only, + u32 mask, u32 candidate) +{ + if (secondary && ordered_dual) + return typec_only && (!mask || candidate < mask) ? candidate : mask; + return mask | candidate; +} +EXPORT_SYMBOL_GPL(dcp_fabric_port_crtc_mask); + enum dcp_fabric_attach_action dcp_fabric_attach_action(bool external) { return external ? DCP_FABRIC_ATTACH_WORK : DCP_FABRIC_ATTACH_OOB; diff --git a/drivers/gpu/drm/apple/dcp-fabric-core.h b/drivers/gpu/drm/apple/dcp-fabric-core.h index e4eae1f785efa0..1b8c59ac15a540 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-core.h +++ b/drivers/gpu/drm/apple/dcp-fabric-core.h @@ -77,13 +77,13 @@ enum dcp_fabric_wiring dcp_fabric_wiring(bool dpin0, bool dpin1, bool legacy, unsigned int endpoints); bool dcp_fabric_t6020_flow(bool usb4, bool soc_support, bool connector_wired); /* - * T6030's even external sources feed DP IN0 through DPTX PCLK1. A local copy - * of apple_dp_tunnel_t6030_pclk() (linux/soc/apple/dp-tunnel.h, 170-usb), - * which the dp-tunnel.h this tree builds against does not have yet. + * T6030's even external sources feed DP IN0/1 through DPTX PCLK1/2. Keep this + * pure policy helper independent of OF/PHY header dependencies. The fabric + * tests check parity with apple_dp_tunnel_t6030_pclk() in dp-tunnel.h. */ static inline int dcp_fabric_t6030_pclk(unsigned int source, unsigned int dpin) { - return !dpin && (source == 0 || source == 2) ? 0 : -EOPNOTSUPP; + return dpin < 2 && (source == 0 || source == 2) ? (int)dpin : -EOPNOTSUPP; } u8 dcp_fabric_tunnel_clock_blocked(bool t6030, unsigned int source); @@ -170,6 +170,7 @@ bool dcp_fabric_fits(const struct dcp_fabric_pipeline *pipeline, const struct dcp_fabric_policy *policy, u32 mask, bool connector_present); bool dcp_fabric_keep_order(bool dual_stream, bool ready, bool frozen); +bool dcp_fabric_ordered_dual_stream(bool wired, bool t6030); bool dcp_fabric_waiting(const struct dcp_fabric_port *port); bool dcp_fabric_movable(const struct dcp_fabric_route *owner, const struct dcp_fabric_route *target); @@ -191,6 +192,8 @@ unsigned int dcp_fabric_fixed_steps(bool has_fixed, bool owned, bool needs_mux, enum dcp_fabric_fixed_step steps[2]); u32 dcp_fabric_connector_mask(bool dual_stream, bool bound, bool routed, unsigned int index, u32 candidates); +u32 dcp_fabric_port_crtc_mask(bool secondary, bool ordered_dual, bool typec_only, + u32 mask, u32 candidate); enum dcp_fabric_attach_action dcp_fabric_attach_action(bool external); bool dcp_fabric_t6030_link(bool tunnel, bool has_xbar, bool t6030_dpin); diff --git a/drivers/gpu/drm/apple/dcp-fabric-test.c b/drivers/gpu/drm/apple/dcp-fabric-test.c index bdf42c35bd3617..2d2fab58136b6b 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-test.c +++ b/drivers/gpu/drm/apple/dcp-fabric-test.c @@ -1910,8 +1910,9 @@ static void fabric_t6030_init(struct fabric_fixture *f) { unsigned int p; - fabric_init(f, false); + fabric_init(f, dcp_fabric_ordered_dual_stream(true, true)); for (p = 0; p < 3; p++) { + f->port[p].candidate_crtcs[1] = BIT(1) | BIT(2); f->route[p][0].tunnel_clock_blocked = dcp_fabric_tunnel_clock_blocked(true, 0); f->route[p][1].tunnel_clock_blocked = @@ -1919,6 +1920,73 @@ static void fabric_t6030_init(struct fabric_fixture *f) } } +static void fabric_t6030_dual_policy_test(struct kunit *test) +{ + struct fabric_fake f; + u32 mask; + + fabric_fake_init(&f, test, dcp_fabric_ordered_dual_stream(true, true)); + KUNIT_EXPECT_FALSE(test, f.f.policy.dual_stream); + KUNIT_EXPECT_TRUE(test, dcp_fabric_ordered_dual_stream(true, false)); + KUNIT_EXPECT_FALSE(test, dcp_fabric_ordered_dual_stream(false, true)); + /* A primary dock stream leaves the fixed processor free for HDMI. */ + KUNIT_ASSERT_EQ(test, fabric_tunnel(&f.f, 0, 0), 0); + KUNIT_EXPECT_PTR_EQ(test, f.f.port[0].owner[0], &f.f.route[0][1]); + f.borrowed = f.f.pipeline[0].owned; + f.frozen = true; + f.levels[0] = f.levels[1] = 1; + dcp_fabric_run_hdmi(&fabric_fake_hdmi_ops, &f); + KUNIT_ASSERT_EQ(test, f.count, 4U); + KUNIT_EXPECT_EQ(test, f.trace[3], FX_CONNECT_FIXED); + /* HDMI owns one processor; the other still takes the first tunnel. */ + fabric_release(&f.f, 0, 0); + f.f.pipeline[0].fixed_busy = true; + KUNIT_ASSERT_EQ(test, fabric_tunnel(&f.f, 0, 0), 0); + KUNIT_EXPECT_PTR_EQ(test, f.f.port[0].owner[0], &f.f.route[0][1]); + f.f.pipeline[0].fixed_busy = false; + f.f.port[0].candidate_crtcs[1] = BIT(1) | BIT(2); + KUNIT_ASSERT_EQ(test, fabric_tunnel(&f.f, 0, 1), 0); + KUNIT_EXPECT_PTR_EQ(test, f.f.port[0].owner[1], &f.f.route[0][0]); + /* Both encoders expose candidates, then narrow to the actual owner. */ + mask = dcp_fabric_port_crtc_mask(true, false, false, 0, BIT(1)); + mask = dcp_fabric_port_crtc_mask(true, false, true, mask, BIT(2)); + KUNIT_EXPECT_EQ(test, mask, (u32)(BIT(1) | BIT(2))); + KUNIT_EXPECT_EQ(test, dcp_fabric_connector_mask(false, true, true, 1, mask), (u32)BIT(1)); + KUNIT_EXPECT_EQ(test, dcp_fabric_connector_mask(false, true, true, 2, mask), (u32)BIT(2)); + /* Ordered M2 secondary connectors retain the Type-C-only processor. */ + mask = dcp_fabric_port_crtc_mask(true, true, false, 0, BIT(1)); + mask = dcp_fabric_port_crtc_mask(true, true, true, mask, BIT(2)); + KUNIT_EXPECT_EQ(test, mask, (u32)BIT(2)); + mask = dcp_fabric_port_crtc_mask(false, true, false, mask, BIT(1)); + KUNIT_EXPECT_EQ(test, mask, (u32)(BIT(1) | BIT(2))); +} + +static void fabric_t6030_clock_header_parity_test(struct kunit *test) +{ + static const struct { + unsigned int source; + unsigned int dpin; + int pclk; + } cases[] = { + { 0, 0, 0 }, { 0, 1, 1 }, { 2, 0, 0 }, { 2, 1, 1 }, + { 1, 0, -EOPNOTSUPP }, { 1, 1, -EOPNOTSUPP }, + { 3, 0, -EOPNOTSUPP }, { 4, 0, -EOPNOTSUPP }, + { UINT_MAX, 0, -EOPNOTSUPP }, + { 0, 2, -EOPNOTSUPP }, { 2, 2, -EOPNOTSUPP }, + { 0, UINT_MAX, -EOPNOTSUPP }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + KUNIT_EXPECT_EQ(test, + apple_dp_tunnel_t6030_pclk(cases[i].source, cases[i].dpin), + cases[i].pclk); + KUNIT_EXPECT_EQ(test, + dcp_fabric_t6030_pclk(cases[i].source, cases[i].dpin), + cases[i].pclk); + } +} + static void fabric_t6030_clock_routes_test(struct kunit *test) { struct fabric_fixture f; @@ -1959,9 +2027,16 @@ static void fabric_t6030_clock_routes_test(struct kunit *test) KUNIT_ASSERT_EQ(test, fabric_tunnel(&f, 0, 0), 0); KUNIT_EXPECT_PTR_EQ(test, f.port[0].owner[0], &f.route[0][1]); fabric_release(&f, 0, 0); - /* A second stream on the same dock is still unsupported on T6030. */ - KUNIT_EXPECT_EQ(test, fabric_tunnel(&f, 0, 1), -EOPNOTSUPP); - KUNIT_EXPECT_PTR_EQ(test, f.port[0].owner[1], NULL); + /* Separate dock monitors hold separate processors and pixel clocks. */ + f.pipeline[0].services_ready = true; + f.pipeline[1].services_ready = true; + KUNIT_ASSERT_EQ(test, fabric_tunnel(&f, 0, 0), 0); + KUNIT_ASSERT_EQ(test, fabric_tunnel(&f, 0, 1), 0); + KUNIT_EXPECT_PTR_EQ(test, f.port[0].owner[0], &f.route[0][1]); + KUNIT_EXPECT_PTR_EQ(test, f.port[0].owner[1], &f.route[0][0]); + fabric_release(&f, 0, 0); + KUNIT_EXPECT_PTR_EQ(test, f.port[0].owner[1], &f.route[0][0]); + fabric_release(&f, 0, 1); KUNIT_EXPECT_EQ(test, dcp_fabric_tunnel_clock_blocked(true, 1), (u8)3); KUNIT_EXPECT_EQ(test, dcp_fabric_tunnel_clock_blocked(true, 4), (u8)3); KUNIT_EXPECT_EQ(test, dcp_fabric_tunnel_clock_blocked(false, 0), (u8)0); @@ -1998,7 +2073,7 @@ static void fabric_t6030_follow_test(struct kunit *test) NULL, NULL, false, &f.policy), DCP_FABRIC_FOLLOW_MOVE); f.route[0][0].dpin = 1; KUNIT_EXPECT_EQ(test, dcp_fabric_follow(&f.route[0][0], &f.route[0][1], - NULL, NULL, false, &f.policy), DCP_FABRIC_FOLLOW_REFUSE); + NULL, NULL, false, &f.policy), DCP_FABRIC_FOLLOW_MOVE); f.route[0][0].tunnel = false; KUNIT_EXPECT_EQ(test, dcp_fabric_follow(&f.route[0][0], &f.route[0][1], NULL, NULL, false, &f.policy), DCP_FABRIC_FOLLOW_MOVE); @@ -2275,7 +2350,9 @@ static struct kunit_case fabric_tests[] = { KUNIT_CASE(relink_budget_test), KUNIT_CASE(relink_disabled_test), KUNIT_CASE(relink_stamp_test), + KUNIT_CASE(fabric_t6030_dual_policy_test), KUNIT_CASE(fabric_t6030_clock_routes_test), + KUNIT_CASE(fabric_t6030_clock_header_parity_test), KUNIT_CASE(fabric_t6030_plan_test), KUNIT_CASE(fabric_t6030_follow_test), KUNIT_CASE(fabric_reclaim_transaction_test), diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index c0e469592eac41..29321f8032a490 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -191,7 +191,7 @@ static bool dcp_typec_route_available(struct apple_dcp_typec_route *route) .fixed_busy = dcp_typec_route_busy(route), }; - struct dcp_fabric_policy policy = { .dual_stream = dcp_typec_dual_stream() }; + struct dcp_fabric_policy policy = { .dual_stream = dcp_typec_ordered_dual_stream() }; pipeline.presence = dcp_hdmi_presence(route->dcp); return dcp_fabric_available(&pipeline, &policy); @@ -207,6 +207,13 @@ bool dcp_typec_dual_stream(void) return atomic_read(&dcp_dual_stream_routes) > 0; } +/* Keep native T6030 routes pinned to their owning processor, on either DPIN. */ +bool dcp_typec_ordered_dual_stream(void) +{ + return dcp_fabric_ordered_dual_stream(dcp_typec_dual_stream(), + of_machine_is_compatible("apple,t6030")); +} + /* * Do the Type-C routes of @dcp follow the CRTC a modeset pairs them with * (see dcp_typec_follow_crtc())? Direct routes and Thunderbolt tunnels, @@ -602,7 +609,7 @@ static bool dcp_typec_keep_order(void) { struct drm_device *drm; - if (!dcp_typec_dual_stream()) + if (!dcp_typec_ordered_dual_stream()) return false; drm = dcp_typec_drm(); if (!drm || !READ_ONCE(drm->registered)) @@ -617,7 +624,7 @@ static bool dcp_hdmi_settle_enabled(struct apple_dcp *dcp) { return dcp->hdmi_hpd && dcp_fabric_hdmi_settle_enabled(!!dcp->fixed_phy, dcp->nr_typec_routes, - dcp_typec_dual_stream()); + dcp_typec_ordered_dual_stream()); } static enum dcp_fabric_presence_state dcp_hdmi_presence(struct apple_dcp *dcp) @@ -982,7 +989,7 @@ static struct apple_dcp_typec_route * dcp_typec_free_route(struct apple_dcp_typec_port *port) { struct dcp_fabric_policy policy = { - .dual_stream = dcp_typec_dual_stream(), + .dual_stream = dcp_typec_ordered_dual_stream(), .follow = dcp_typec_port_follows(port), }; @@ -1259,7 +1266,7 @@ static void dcp_typec_pipeline_freed(void) */ void dcp_typec_reorder(void) { - if (!dcp_typec_dual_stream()) + if (!dcp_typec_ordered_dual_stream()) return; guard(mutex)(&dcp_typec_fabric_lock); @@ -1799,7 +1806,9 @@ int dcp_tunnel_set_rate(struct apple_dcp *dcp, struct phy *phy, u32 unit, if (!dcp_fabric_callback_valid(route->tunnel_generation, dcp->tb_generation)) return -ESTALE; if (of_machine_is_compatible("apple,t6030") && - (unit || dcp->dptx_dfp_port != 1)) + (unit || dcp->dptx_dfp_port != 1 + route->tunnel_dpin || + apple_dp_tunnel_t6030_pclk(route->mux_index, + route->tunnel_dpin) < 0)) return -EOPNOTSUPP; if (unit) { /* Each DP IN owns a reference, including on a shared clock. */ @@ -1928,7 +1937,7 @@ static int dcp_tb_candidate(void *data) { struct dcp_fabric_policy policy = { - .dual_stream = dcp_typec_dual_stream(), + .dual_stream = dcp_typec_ordered_dual_stream(), .follow = dcp_typec_port_follows(port), }; struct dcp_fabric_route *chosen; @@ -2189,6 +2198,24 @@ static int dcp_tb_split_join_locked(struct apple_dcp_typec_port *port, return ret; } +/* + * Can no pipeline that drives @port take the second half of a tiled display? + * A tile joins DPTX port 1 of the pipeline that drives dpin0, which an + * external display processor never does (see dcp_tb_split_locked()). That is + * fixed when the processor probes, before its routes are registered, so it + * holds before any of its services are up. On T6030 every Type-C pipeline is + * an external processor. A port with no routes is not judged here. + */ +static bool dcp_typec_port_untileable(struct apple_dcp_typec_port *port) +{ + struct apple_dcp_typec_route *route; + + list_for_each_entry(route, &port->routes, port_link) + if (!route->dcp->external) + return false; + return !list_empty(&port->routes); +} + /* -EOPNOTSUPP: not a tile, route dpin1 as a display of its own. */ static int dcp_tb_split_locked(struct apple_dcp_typec_port *port, const struct dcp_tb_attach_context *req) @@ -2221,6 +2248,9 @@ static int dcp_tb_split_locked(struct apple_dcp_typec_port *port, } if (!req->active) return -EOPNOTSUPP; + /* No tile is possible here: there is no dpin0 to wait for. */ + if (dcp_typec_port_untileable(port)) + return -EOPNOTSUPP; /* dpin0 first: the Thunderbolt side retries on -ENODEV */ if (!route || !route->tunnel || route->tunnel_dpin != 0) return -ENODEV; @@ -2640,7 +2670,7 @@ static int dcp_typec_follow_decide(struct apple_dcp *dcp, struct drm_crtc *crtc, struct apple_connector *connector, struct dcp_typec_follow *follow) { - struct dcp_fabric_policy policy = { .dual_stream = dcp_typec_dual_stream() }; + struct dcp_fabric_policy policy = { .dual_stream = dcp_typec_ordered_dual_stream() }; struct apple_dcp_typec_route *from, *to, *holder, *back = NULL; struct apple_dcp_typec_port *port, *other = NULL; bool secondary, off = false; @@ -3413,6 +3443,13 @@ static int dcp_typec_route_wiring(struct apple_dcp_typec_route *route, return -EINVAL; } } + if (!named[0] && !named[1] && !legacy && + apple_dp_tunnel_t6030_legacy_mux(dev->of_node, index)) { + if (route->xbar != &route->xbar->chip->mux[0] || + route->xbar->chip->controllers < 3) + return -EINVAL; + legacy = &route->xbar->chip->mux[1]; + } wiring = dcp_fabric_wiring(named[0], named[1], !!legacy, dcp_typec_route_endpoints(connector_np)); if (wiring == DCP_FABRIC_INVALID_WIRING) @@ -3422,7 +3459,7 @@ static int dcp_typec_route_wiring(struct apple_dcp_typec_route *route, /* Old j414/j416 ESP DTBs name cell 1 but never name cell 2. */ route->dpin[0] = legacy; route->dpin[1] = &route->xbar->chip->mux[2]; - dev_warn_once(dev, "legacy typecN-usb4 DPIN wiring; update the device tree\n"); + dev_warn_once(dev, "implicit DPIN wiring; update the device tree\n"); } return 0; } @@ -3676,7 +3713,7 @@ static bool dcp_hdmi_keep_order(void *ctx) static bool dcp_hdmi_dual_stream(void *ctx) { - return dcp_typec_dual_stream(); + return dcp_typec_ordered_dual_stream(); } static int dcp_hdmi_read_hpd(void *ctx) @@ -3860,7 +3897,7 @@ static bool dcp_typec_hdmi_reclaim(struct apple_dcp *dcp) struct dcp_hdmi_reclaim_context ctx; lockdep_assert_held(&dcp_typec_fabric_lock); - if (!owner || dcp_typec_dual_stream()) + if (!owner || dcp_typec_ordered_dual_stream()) return false; port = owner->port; /* A port in SAFE keeps its owner until the mux set phase completes. */ diff --git a/drivers/gpu/drm/apple/dcp-fabric.h b/drivers/gpu/drm/apple/dcp-fabric.h index 62b1a72d5946aa..1176ef56874f35 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.h +++ b/drivers/gpu/drm/apple/dcp-fabric.h @@ -71,6 +71,7 @@ bool dcp_typec_port_unusable(unsigned int idx); void dcp_typec_port_set_connector(unsigned int idx, bool secondary, struct apple_connector *connector); bool dcp_typec_dual_stream(void); +bool dcp_typec_ordered_dual_stream(void); void dcp_typec_reorder(void); bool dcp_typec_follows_crtc(struct apple_dcp *dcp); bool dcp_typec_follow_holder_off(struct drm_atomic_commit *state, struct drm_crtc *crtc, diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 5aedd1acb59451..d22b9a638169c9 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -303,6 +303,12 @@ struct apple_dcp { */ bool external_detached; atomic_t external_requested; + /* + * Native: the DP/HDMI audio endpoint (EP 0x29) starts once per + * session, after the first display's EDID; see dcp_external_audio_start(). + */ + struct work_struct external_audio_work; + bool external_audio_started; /* DCP_FIRMWARE_V_14_7 state; outlives this device once RTKit runs. */ struct apple_dcp_v14 *v14; @@ -721,6 +727,27 @@ static inline bool dcp_fw_is_14_7(const struct apple_dcp *dcp) dcp->hw.fw_14_7_endpoints); } +/* + * The T6030 external processor (the J514S/J516S built-in HDMI port and + * USB-C displays) driven natively through Aurora's DCPLink session: DCP + * firmware 14.7's external role, whose DP/HDMI audio service differs from + * the M1/M2 one (see av.c). The manual diagnostic pipe (dcpext_scanout) and + * the T8122 template path are not this. + */ +static inline bool dcp_is_v14_7_external(const struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_V_14_7 && dcp->external_native; +} + +/* The 14.7 internal panel (J514S/J516S), presented through DCPLink. */ +static inline bool dcp_is_v14_7_panel(const struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_V_14_7 && !dcp->external; +} + +/* Native external pipe: start its audio endpoint, once, after the first EDID. */ +void dcp_external_audio_start(struct apple_dcp *dcp); + /* * The T8122 dcpext connects its DPTX port as AsahiLinux/linux#607 does, * the kernel this firmware was first driven with: no validation of the diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index e84af350c7e081..8c877d0c2434b9 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2533,6 +2533,56 @@ int dcp_start(struct platform_device *pdev) return ret; } +/* + * A native T6030 external processor: its DP/HDMI audio endpoint (EP 0x29) + * on the driver's opt-in (hdmi_audio), as the other DCPs start it, for a + * processor whose port@0 links an audio device; once per session, and after + * the first display's EDID was read: with the endpoint's interfaces + * published, an EDID copy (dcpavserv_copy_edid()) has the firmware rebuild + * them and re-plug the sink, so the endpoint starts only once the first + * EDID is cached. + */ +static void dcp_external_audio_work(struct work_struct *work) +{ + struct apple_dcp *dcp = container_of(work, struct apple_dcp, external_audio_work); + + /* Queued after an EDID came through the running session: RTKit is up. */ + if (!IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) || !hdmi_audio || !dcp->external_native || + dcp->external_audio_started || READ_ONCE(dcp->crashed) || !dcp->rtk) + return; + dcp->external_audio_started = true; + if (!apple_rtkit_has_endpoint(dcp->rtk, AV_ENDPOINT)) { + dev_info(dcp->dev, "no AV audio endpoint\n"); + return; + } +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) + { + int ret = avep_init(dcp); + + if (ret) + dev_warn(dcp->dev, "AV audio endpoint not started: %d\n", ret); + } +#endif +} + +void dcp_external_audio_start(struct apple_dcp *dcp) +{ + if (!dcp->external_native || dcp->external_audio_started) + return; + queue_work(system_freezable_wq, &dcp->external_audio_work); +} + +/* Probe: the audio work, disabled until a native external pipe's bind. */ +static void dcp_external_audio_init(struct apple_dcp *dcp) +{ + INIT_WORK(&dcp->external_audio_work, dcp_external_audio_work); + /* + * A native external pipe's bind enables it (its first EDID queues + * it, through the connector); unbind and suspend disable it again. + */ + disable_work(&dcp->external_audio_work); +} + static void _dcp_poweroff(struct apple_dcp *dcp) { switch (dcp->fw_compat) { @@ -3650,8 +3700,10 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat dcp->vblank_works_disabled = false; } - if (dcp->external_prepared) + if (dcp->external_prepared) { + av_audiosrv_reports_restart(dcp); return 0; + } /* A timed-out prior session may still scan these mappings. */ mutex_lock(&dcp->swapped_out_fbs_lock); @@ -3736,8 +3788,10 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat if (dcp->fw_compat == DCP_FIRMWARE_V_26_6) { ret = iomfb_v26_6_bind(dcp); - if (!ret) + if (!ret) { enable_work(&dcp->dimensions_wq); + av_audiosrv_reports_restart(dcp); + } return ret; } @@ -3746,19 +3800,24 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat if (dcp->external_native) { WRITE_ONCE(dcp->external_detached, false); enable_work(&dcp->vblank_wq); + enable_work(&dcp->external_audio_work); enable_delayed_work(&dcp->swap_watchdog_wq); enable_delayed_work(&dcp->external_retry_wq); enable_work(&dcp->dimensions_wq); dcp_enable_typec_work(dcp); + av_audiosrv_reports_restart(dcp); return 0; } - if (dcp->external) + if (dcp->external) { + av_audiosrv_reports_restart(dcp); return 0; + } ret = iomfb_v14_7_bind(dcp); /* Balances the disable at probe, as below. */ if (!ret) { enable_work(&dcp->dimensions_wq); dcp_enable_typec_work(dcp); + av_audiosrv_reports_restart(dcp); } return ret; } @@ -3865,6 +3924,7 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat enable_work(&dcp->dimensions_wq); schedule_work(&dcp->dimensions_wq); dcp_enable_typec_work(dcp); + av_audiosrv_reports_restart(dcp); return 0; err_piodma: @@ -3901,7 +3961,17 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v { struct apple_dcp *dcp = dev_get_drvdata(dev); - if (!dcp || READ_ONCE(dcp->ext_dead)) + if (!dcp) + return; + /* + * Stop the native initializer before looking up its owner, including + * the dead-session path. Owner allocation may have landed in an open + * bind devres group; finish its RPC work while endpoint RX is alive. + */ + if (dcp->external_native) + disable_work_sync(&dcp->external_audio_work); + av_audiosrv_quiesce(dcp); + if (READ_ONCE(dcp->ext_dead)) return; disable_work_sync(&dcp->dimensions_wq); @@ -3997,7 +4067,7 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v } } - if (dcp->avep) { + if (!IS_ERR_OR_NULL(dcp->avep)) { av_service_disconnect(dcp); afk_shutdown(dcp->avep); dcp->avep = NULL; @@ -4162,6 +4232,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->ext_failsafe = of_device_is_compatible(dev->of_node, "apple,t8122-dcpext"); dcp->external = of_device_is_compatible(dev->of_node, "apple,t6030-dcpext"); dcp->external_native = dcp->external && dcp_t6030_ext_native(dev->of_node); + dcp_external_audio_init(dcp); dcp->dev = dev; /* * Type-C and Thunderbolt routes can be activated as soon as they are @@ -4181,6 +4252,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) spin_lock_init(&dcp->mode_state.lock); spin_lock_init(&dcp->metadata.lock); mutex_init(&dcp->dcpavserv.lock); + INIT_WORK(&dcp->dcpavserv.close_wq, dcpavserv_close_work); dcp->hw = *(struct apple_dcp_hw_data *)of_device_get_match_data(dev); if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) { @@ -4457,14 +4529,18 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) ret = dcp_comp_bind(dev, NULL, NULL); if (ret) { dcp_disable_typec_work(dcp, true); + av_audiosrv_quiesce(dcp); return ret; } WRITE_ONCE(dcp->external_prepared, true); } if (dcp->external_native) { ret = iomfb_v14_7_external_prepare(dcp); - if (ret) + if (ret) { + disable_work_sync(&dcp->external_audio_work); + av_audiosrv_quiesce(dcp); return ret; + } if (routes_failed) iomfb_v14_7_external_refuse(dcp, "its Type-C display routes did not register"); } @@ -4473,6 +4549,12 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) if (ret && dcp->external_prepared) { dcp_disable_typec_work(dcp, true); } + /* component_add failure does not unbind. Stop owner work first. */ + if (ret) { + if (dcp->external_native) + disable_work_sync(&dcp->external_audio_work); + av_audiosrv_quiesce(dcp); + } if (ret && dcp->fw_compat == DCP_FIRMWARE_V_26_6) iomfb_v26_6_unbind(dcp); /* A failed bind run from here may already have started RTKit. */ @@ -4594,11 +4676,21 @@ static void dcp_platform_remove(struct platform_device *pdev) struct apple_dcp *dcp = platform_get_drvdata(pdev); if (dcp && dcp->external && !dcp->external_native) { - /* Enabled for the external start at probe. */ + /* Enabled for the external start at probe. No component unbind. */ disable_delayed_work_sync(&dcp->typec_reconnect_wq); + av_audiosrv_quiesce(dcp); iomfb_v14_7_remove(dcp); return; } + if (dcp && dcp->external_native) + disable_work_sync(&dcp->external_audio_work); + /* + * Finish audio RPCs before component_del's unbind flushes RX, and + * before iomfb_v14_7_remove() clears v14->dcp. Unbind repeats the + * helper; the second call does not disable the works again. + */ + if (dcp) + av_audiosrv_quiesce(dcp); component_del(&pdev->dev, &dcp_comp_ops); if (dcp && dcp->fw_compat == DCP_FIRMWARE_V_26_6) iomfb_v26_6_unbind(dcp); @@ -4845,6 +4937,8 @@ static int dcp_platform_suspend(struct device *dev) */ dcp_disable_typec_work(dcp, false); cancel_delayed_work_sync(&dcp->swap_watchdog_wq); + if (dcp->external_native) + disable_work_sync(&dcp->external_audio_work); if (dcp->avep) av_service_disconnect(dcp); @@ -4883,6 +4977,8 @@ static int dcp_platform_resume(struct device *dev) /* Observe future edges before sampling any edges lost in sleep. */ if (dcp->hdmi_hpd_irq) dcp_fabric_run_resume(&dcp_resume_ops, dcp); + if (dcp->external_native) + enable_work(&dcp->external_audio_work); if (dcp->avep) av_service_connect(dcp); @@ -5017,3 +5113,7 @@ void dcp_unregister(void) { platform_driver_unregister(&apple_platform_driver); } + +#if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) +#include "dcp_external_audio_test.c" +#endif diff --git a/drivers/gpu/drm/apple/dcp_external_audio_test.c b/drivers/gpu/drm/apple/dcp_external_audio_test.c new file mode 100644 index 00000000000000..c1c32e2c32d3ca --- /dev/null +++ b/drivers/gpu/drm/apple/dcp_external_audio_test.c @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by dcp.c: the native external pipe's audio work across probe, + * bind, sleep and unbind. The work function is swapped for a counter, so a + * start that queued it shows. + */ +#include + +static atomic_t dcp_ext_audio_runs; + +static void dcp_ext_audio_count(struct work_struct *work) +{ + atomic_inc(&dcp_ext_audio_runs); +} + +static unsigned int dcp_ext_audio_start_runs(struct apple_dcp *dcp) +{ + atomic_set(&dcp_ext_audio_runs, 0); + dcp_external_audio_start(dcp); + flush_work(&dcp->external_audio_work); + return atomic_read(&dcp_ext_audio_runs); +} + +static void dcp_ext_audio_stop(void *data) +{ + struct apple_dcp *dcp = data; + + disable_work_sync(&dcp->external_audio_work); +} + +static struct apple_dcp *dcp_ext_audio_probe(struct kunit *test, bool native) +{ + struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, dcp); + dcp->fw_compat = DCP_FIRMWARE_V_14_7; + dcp->external = native; + dcp->external_native = native; + dcp_external_audio_init(dcp); + dcp->external_audio_work.func = dcp_ext_audio_count; + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcp_ext_audio_stop, dcp), 0); + return dcp; +} + +/* + * Probe leaves the work disabled: a first EDID before bind queues nothing, + * and bind's single enable is balanced. Suspend and resume, unbind and a + * second bind keep it so. + */ +static void dcp_ext_audio_lifecycle(struct kunit *test) +{ + struct apple_dcp *dcp = dcp_ext_audio_probe(test, true); + + KUNIT_EXPECT_EQ(test, dcp_ext_audio_start_runs(dcp), 0U); + /* bind */ + KUNIT_EXPECT_TRUE(test, enable_work(&dcp->external_audio_work)); + KUNIT_EXPECT_EQ(test, dcp_ext_audio_start_runs(dcp), 1U); + /* suspend, then resume */ + disable_work_sync(&dcp->external_audio_work); + KUNIT_EXPECT_EQ(test, dcp_ext_audio_start_runs(dcp), 0U); + KUNIT_EXPECT_TRUE(test, enable_work(&dcp->external_audio_work)); + /* unbind, then bind again */ + disable_work_sync(&dcp->external_audio_work); + KUNIT_EXPECT_TRUE(test, enable_work(&dcp->external_audio_work)); + KUNIT_EXPECT_EQ(test, dcp_ext_audio_start_runs(dcp), 1U); +} + +/* Only a native external pipe starts it, and only once per session. */ +static void dcp_ext_audio_start_gates(struct kunit *test) +{ + struct apple_dcp *other = dcp_ext_audio_probe(test, false); + struct apple_dcp *dcp = dcp_ext_audio_probe(test, true); + + KUNIT_EXPECT_TRUE(test, enable_work(&other->external_audio_work)); + KUNIT_EXPECT_EQ(test, dcp_ext_audio_start_runs(other), 0U); + KUNIT_EXPECT_TRUE(test, enable_work(&dcp->external_audio_work)); + dcp->external_audio_started = true; + KUNIT_EXPECT_EQ(test, dcp_ext_audio_start_runs(dcp), 0U); +} + +static struct kunit_case dcp_ext_audio_cases[] = { + KUNIT_CASE(dcp_ext_audio_lifecycle), + KUNIT_CASE(dcp_ext_audio_start_gates), + {} +}; + +static struct kunit_suite dcp_ext_audio_suite = { + .name = "apple-dcp-external-audio-work", + .test_cases = dcp_ext_audio_cases, +}; + +kunit_test_suite(dcp_ext_audio_suite); diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index d61b28e04546a0..741f40bc8c9ed5 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -200,6 +200,7 @@ int dptxport_request_display(struct apple_epic_service *service) int dptxport_release_display(struct apple_epic_service *service) { dcp_180hz_invalidate(service->ep->dcp); + dcpavserv_v14_close(service->ep->dcp); return afk_service_call(service, 0, 7, NULL, 0, 16, NULL, 0, 16); } @@ -210,6 +211,9 @@ int dptxport_set_hpd_timeout(struct apple_epic_service *service, bool hpd, size_t received; int ret; + /* The 14.7 external role completes an HPD low only once its AV client closed. */ + if (!hpd) + dcpavserv_v14_close(service->ep->dcp); memset(&cmd, 0, sizeof(cmd)); if (hpd) diff --git a/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c b/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c new file mode 100644 index 00000000000000..1912f87454e5d6 --- /dev/null +++ b/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c @@ -0,0 +1,508 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by dpavservep.c: the AV client of the DCP 14.7 external role. + * The production open, close, Terminate, Close work and EDID copy run on a + * fake service instance; only the client calls and the EDID read are + * stubbed. The Close work is disabled for the workqueue and run here, in + * test context, where the stubs apply; the Open stub can act while the Open + * is on its way, to run each interleaving. + */ +#include +#include +#include + +#define AV14_OPEN 4 +#define AV14_CLOSE 5 + +enum av14_meanwhile { + AV14_NOTHING, + AV14_HPD_LOW, /* dcpavserv_v14_close(), as before an HPD low */ + AV14_TERMINATE, /* the firmware's Terminate report */ + AV14_REPLACED, /* teardown, and a successor in the same slot */ + AV14_COPY, /* another EDID copy */ +}; + +struct av14_test { + struct apple_dcp *dcp; + struct apple_dcp_afkep ep; + struct apple_epic_service svc; + /* Client calls, as group << 16 | command, and the epoch each went to */ + u32 calls[8]; + u64 call_epochs[8]; + unsigned int ncalls; + int call_ret; + u32 open_status; + u64 open_opened; + u32 close_status; + enum av14_meanwhile during_open; + unsigned int reads; + bool read_valid; +}; + +static struct av14_test *av14_current; + +static void av14_report(struct av14_test *t, u16 group, u32 command, u32 magic, size_t size); +static void av14_replace(struct av14_test *t); + +static int av14_call(struct apple_epic_service *service, u16 group, u32 command, + void *reply, size_t size) +{ + struct av14_test *t = av14_current; + enum av14_meanwhile meanwhile = AV14_NOTHING; + + if (t->ncalls < ARRAY_SIZE(t->calls)) { + t->calls[t->ncalls] = (u32)group << 16 | command; + t->call_epochs[t->ncalls] = t->dcp->dcpavserv.epoch; + } + t->ncalls++; + if (command == AV14_OPEN) { + meanwhile = t->during_open; + t->during_open = AV14_NOTHING; + } + switch (meanwhile) { + case AV14_HPD_LOW: + dcpavserv_v14_close(t->dcp); + break; + case AV14_TERMINATE: + av14_report(t, 2, 1, EPIC_SERVICE_CALL_MAGIC, sizeof(struct epic_service_call)); + break; + case AV14_REPLACED: + av14_replace(t); + break; + case AV14_COPY: { + u64 epoch; + const struct drm_edid *edid = dcpavserv_copy_edid(t->dcp, 0, &epoch); + + if (!IS_ERR_OR_NULL(edid)) + drm_edid_free(edid); + break; + } + case AV14_NOTHING: + break; + } + if (t->call_ret) + return t->call_ret; + memset(reply, 0, size); + if (command == AV14_OPEN && size >= 24) { + put_unaligned_le32(t->open_status, reply); + put_unaligned_le64(t->open_opened, reply + 16); + } else if (command == AV14_CLOSE && size >= 4) { + put_unaligned_le32(t->close_status, reply); + } + return 0; +} + +/* One EDID base block: valid, or with its checksum off by one */ +static const struct drm_edid *av14_read(struct apple_epic_service *service) +{ + u8 block[EDID_LENGTH] = { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 }; + unsigned int i; + u8 sum = 0; + + av14_current->reads++; + block[18] = 1; /* EDID 1.3 */ + block[19] = 3; + for (i = 0; i < EDID_LENGTH - 1; i++) + sum += block[i]; + block[EDID_LENGTH - 1] = 0x100 - sum + (av14_current->read_valid ? 0 : 1); + return drm_edid_alloc(block, sizeof(block)); +} + +static void av14_stop(void *data) +{ + struct apple_dcp *dcp = data; + + cancel_work_sync(&dcp->dcpavserv.close_wq); +} + +/* Publish the instance in the slot, as dcpavserv_init() does */ +static void av14_publish(struct av14_test *t) +{ + t->svc.enabled = true; + t->svc.torndown = false; + guard(mutex)(&t->dcp->dcpavserv.lock); + t->dcp->dcpavserv.service = afk_service_get(&t->svc); + t->dcp->dcpavserv.enabled = true; + t->dcp->dcpavserv.epoch++; + t->dcp->dcpavserv.opened = NULL; + t->dcp->dcpavserv.opened_epoch = 0; +} + +/* The instance torn down (production teardown) and a successor in its slot */ +static void av14_replace(struct av14_test *t) +{ + dcpavserv_teardown(&t->svc); + av14_publish(t); +} + +/* A published AV instance, on the 14.7 external role or (!native) not */ +static struct av14_test *av14_setup(struct kunit *test, bool native) +{ + struct av14_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + struct device *dev; + + KUNIT_ASSERT_NOT_NULL(test, t); + t->dcp = kunit_kzalloc(test, sizeof(*t->dcp), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->dcp); + dev = kunit_device_register(test, native ? "dcpavserv-v14" : "dcpavserv-v14-other"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + t->dcp->dev = dev; + t->dcp->fw_compat = DCP_FIRMWARE_V_14_7; + t->dcp->external = native; + t->dcp->external_native = native; + mutex_init(&t->dcp->hpd_mutex); + mutex_init(&t->dcp->dcpavserv.lock); + INIT_WORK(&t->dcp->dcpavserv.close_wq, dcpavserv_close_work); + /* Queued work runs here, in test context: av14_run_close_work() */ + disable_work(&t->dcp->dcpavserv.close_wq); + t->ep.dcp = t->dcp; + spin_lock_init(&t->svc.lock); + t->svc.ep = &t->ep; + av14_publish(t); + t->open_opened = 1; + t->read_valid = true; + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, av14_stop, t->dcp), 0); + av14_current = t; + kunit_activate_static_stub(test, dcpavserv_v14_call, av14_call); + kunit_activate_static_stub(test, dcpavserv_read_edid_legacy, av14_read); + return t; +} + +static int av14_copy(struct kunit *test, struct av14_test *t) +{ + const struct drm_edid *edid; + u64 epoch; + + edid = dcpavserv_copy_edid(t->dcp, 0, &epoch); + if (IS_ERR(edid)) + return PTR_ERR(edid); + KUNIT_EXPECT_NOT_NULL(test, edid); + drm_edid_free(edid); + return 0; +} + +static void av14_run_close_work(struct av14_test *t) +{ + dcpavserv_close_work(&t->dcp->dcpavserv.close_wq); +} + +static void av14_report(struct av14_test *t, u16 group, u32 command, u32 magic, size_t size) +{ + struct epic_service_call call = { + .group = cpu_to_le16(group), + .command = cpu_to_le32(command), + .magic = cpu_to_le32(magic), + }; + + dcpavserv_report(&t->svc, EPIC_SUBTYPE_STD_SERVICE, &call, size); +} + +static void av14_terminate(struct av14_test *t) +{ + av14_report(t, 2, 1, EPIC_SERVICE_CALL_MAGIC, sizeof(struct epic_service_call)); +} + +/* Each instance is opened once (DCPAV Open, group 0), before its first EDID read. */ +static void av14_open_once(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_EQ(test, t->ncalls, 1U); + KUNIT_EXPECT_EQ(test, t->calls[0], (u32)AV14_OPEN); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->dcpavserv.opened, &t->svc); + KUNIT_EXPECT_EQ(test, t->dcp->dcpavserv.opened_epoch, t->dcp->dcpavserv.epoch); + KUNIT_EXPECT_FALSE(test, t->dcp->dcpavserv.opening); + KUNIT_EXPECT_EQ(test, t->reads, 2U); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* A refused open is not recorded: the read goes on, the next copy opens again. */ +static void av14_open_refused(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + t->open_status = 0xe00002bc; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + t->open_status = 0; + t->open_opened = 0; /* answered, but not opened */ + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + t->call_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + KUNIT_EXPECT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, t->reads, 3U); + KUNIT_EXPECT_FALSE(test, t->dcp->dcpavserv.opening); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* Not the 14.7 external role (as the T8122 dcpext): no client calls, EDID as read. */ +static void av14_other_role(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, false); + + t->read_valid = false; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + dcpavserv_v14_close(t->dcp); + av14_terminate(t); + KUNIT_EXPECT_EQ(test, t->ncalls, 0U); + KUNIT_EXPECT_EQ(test, t->reads, 1U); +} + +/* The 14.7 external role's EDID is checked block by block before it is published. */ +static void av14_edid_checked(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + t->read_valid = false; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -EPROTO); + t->read_valid = true; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); +} + +/* Close (group 0, command 5) goes only to the instance that was opened, once. */ +static void av14_close_opened_only(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + dcpavserv_v14_close(t->dcp); + KUNIT_EXPECT_EQ(test, t->ncalls, 0U); + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + dcpavserv_v14_close(t->dcp); + dcpavserv_v14_close(t->dcp); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->calls[1], (u32)AV14_CLOSE); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + /* A Close the firmware refuses still leaves nothing recorded open */ + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + t->close_status = 0xe00002bc; + dcpavserv_v14_close(t->dcp); + KUNIT_EXPECT_EQ(test, t->ncalls, 4U); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* + * Terminate (report group 2, command 1) on the opened instance queues its + * Close; the instance gets no new use, before or after that Close, until a + * successor is published. Other reports change nothing. + */ +static void av14_terminate_opened(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + u64 epoch = t->dcp->dcpavserv.epoch; + + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + av14_report(t, 2, 2, EPIC_SERVICE_CALL_MAGIC, sizeof(struct epic_service_call)); + av14_report(t, 1, 1, EPIC_SERVICE_CALL_MAGIC, sizeof(struct epic_service_call)); + av14_report(t, 2, 1, 0, sizeof(struct epic_service_call)); + av14_report(t, 2, 1, EPIC_SERVICE_CALL_MAGIC, sizeof(struct epic_service_call) - 1); + KUNIT_EXPECT_EQ(test, t->dcp->dcpavserv.terminated_epoch, 0ULL); + + av14_terminate(t); + KUNIT_EXPECT_EQ(test, t->dcp->dcpavserv.terminated_epoch, epoch); + KUNIT_EXPECT_EQ(test, t->dcp->dcpavserv.close_epoch, epoch); + /* While its Close is queued: no EDID, no new open */ + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + av14_run_close_work(t); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->calls[1], (u32)AV14_CLOSE); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + /* Closed: still no new use of the terminated instance */ + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + av14_run_close_work(t); + KUNIT_EXPECT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->reads, 1U); + /* Its successor, in the same slot, is opened and read */ + av14_replace(t); + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* + * A Close (as before an HPD low) after a Terminate does not end the + * Terminate: whether it comes after the queued Close ran or before it, no + * EDID copy opens or reads the terminated instance again. The successor, a + * new epoch in the same slot, is opened. + */ +static void av14_terminate_then_close(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + u64 epoch; + int round; + + for (round = 0; round < 2; round++) { + unsigned int calls = t->ncalls, reads = t->reads; + + epoch = t->dcp->dcpavserv.epoch; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + av14_terminate(t); + if (!round) + av14_run_close_work(t); + dcpavserv_v14_close(t->dcp); + if (round) + av14_run_close_work(t); + /* One Open, one Close, in this instance */ + KUNIT_ASSERT_EQ(test, t->ncalls, calls + 2); + KUNIT_EXPECT_EQ(test, t->calls[calls], (u32)AV14_OPEN); + KUNIT_EXPECT_EQ(test, t->calls[calls + 1], (u32)AV14_CLOSE); + KUNIT_EXPECT_EQ(test, t->dcp->dcpavserv.terminated_epoch, epoch); + /* Not opened or read again */ + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + KUNIT_EXPECT_EQ(test, t->ncalls, calls + 2); + KUNIT_EXPECT_EQ(test, t->reads, reads + 1); + /* Its successor in the same slot: a new epoch, opened */ + av14_replace(t); + KUNIT_EXPECT_NE(test, t->dcp->dcpavserv.epoch, epoch); + } + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_EQ(test, t->calls[4], (u32)AV14_OPEN); + KUNIT_EXPECT_EQ(test, t->call_epochs[4], t->dcp->dcpavserv.epoch); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* An HPD low's Close while the Open is on its way: its opener closes the client. */ +static void av14_open_vs_close(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + t->during_open = AV14_HPD_LOW; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->calls[0], (u32)AV14_OPEN); + KUNIT_EXPECT_EQ(test, t->calls[1], (u32)AV14_CLOSE); + KUNIT_EXPECT_EQ(test, t->call_epochs[1], t->call_epochs[0]); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + KUNIT_EXPECT_FALSE(test, t->dcp->dcpavserv.opening); + KUNIT_EXPECT_EQ(test, t->reads, 0U); + /* The next EDID copy opens the instance again */ + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->dcpavserv.opened, &t->svc); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* A Terminate while the Open is on its way: closed by its opener, no new use. */ +static void av14_open_vs_terminate(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + t->during_open = AV14_TERMINATE; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->calls[1], (u32)AV14_CLOSE); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + /* No Close work was queued for it, and running one sends nothing */ + av14_run_close_work(t); + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + KUNIT_EXPECT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->reads, 0U); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* + * The instance torn down and its slot reused while the Open is on its way: + * the old open went with the old instance; nothing is closed, and the + * successor is opened by the next copy. + */ +static void av14_open_vs_replaced(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + t->during_open = AV14_REPLACED; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), -ENODEV); + KUNIT_EXPECT_EQ(test, t->ncalls, 1U); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_EQ(test, t->calls[1], (u32)AV14_OPEN); + KUNIT_EXPECT_NE(test, t->call_epochs[1], t->call_epochs[0]); + KUNIT_EXPECT_EQ(test, t->dcp->dcpavserv.opened_epoch, t->dcp->dcpavserv.epoch); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* + * An old instance's Close work, queued at its Terminate, runs after its + * successor took the same slot and was opened: the successor stays open. + */ +static void av14_old_close_work_vs_successor(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + av14_terminate(t); + av14_replace(t); + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_ASSERT_EQ(test, t->ncalls, 2U); + av14_run_close_work(t); + KUNIT_EXPECT_EQ(test, t->ncalls, 2U); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->dcpavserv.opened, &t->svc); + KUNIT_EXPECT_EQ(test, t->dcp->dcpavserv.opened_epoch, t->dcp->dcpavserv.epoch); + /* A Terminate of the successor closes the successor */ + av14_terminate(t); + av14_run_close_work(t); + KUNIT_ASSERT_EQ(test, t->ncalls, 3U); + KUNIT_EXPECT_EQ(test, t->calls[2], (u32)AV14_CLOSE); + KUNIT_EXPECT_EQ(test, t->call_epochs[2], t->dcp->dcpavserv.epoch); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* Another EDID copy while the Open is on its way does not open the instance again. */ +static void av14_open_vs_copy(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + t->during_open = AV14_COPY; + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + KUNIT_EXPECT_EQ(test, t->ncalls, 1U); + KUNIT_EXPECT_EQ(test, t->reads, 2U); + KUNIT_EXPECT_PTR_EQ(test, t->dcp->dcpavserv.opened, &t->svc); + KUNIT_EXPECT_FALSE(test, t->dcp->dcpavserv.opening); + KUNIT_EXPECT_EQ(test, t->svc.users, 1U); +} + +/* Detach drops the open and waits for the Close work; the slot's pin goes. */ +static void av14_detach(struct kunit *test) +{ + struct av14_test *t = av14_setup(test, true); + + KUNIT_EXPECT_EQ(test, av14_copy(test, t), 0); + av14_terminate(t); + dpavservep_detach(t->dcp); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.opened); + KUNIT_EXPECT_NULL(test, t->dcp->dcpavserv.service); + /* The Close work for the detached instance sends nothing */ + av14_run_close_work(t); + KUNIT_EXPECT_EQ(test, t->ncalls, 1U); + KUNIT_EXPECT_EQ(test, t->svc.users, 0U); + KUNIT_EXPECT_TRUE(test, t->svc.torndown); +} + +static struct kunit_case av14_cases[] = { + KUNIT_CASE(av14_open_once), + KUNIT_CASE(av14_open_refused), + KUNIT_CASE(av14_other_role), + KUNIT_CASE(av14_edid_checked), + KUNIT_CASE(av14_close_opened_only), + KUNIT_CASE(av14_terminate_opened), + KUNIT_CASE(av14_terminate_then_close), + KUNIT_CASE(av14_open_vs_close), + KUNIT_CASE(av14_open_vs_terminate), + KUNIT_CASE(av14_open_vs_replaced), + KUNIT_CASE(av14_old_close_work_vs_successor), + KUNIT_CASE(av14_open_vs_copy), + KUNIT_CASE(av14_detach), + {} +}; + +static struct kunit_suite av14_suite = { + .name = "apple-dcpavserv-v14", + .test_cases = av14_cases, +}; + +kunit_test_suite(av14_suite); diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index bec8f711fbd14a..ed94c48c80d1a4 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -7,10 +7,12 @@ #define EDID_EXT_BLOCK_COUNT_OFFSET 0x7E #include +#include #include #include #include +#include #include "../afk.h" #include "../dcp.h" @@ -121,6 +123,9 @@ static void dcpavserv_init(struct apple_epic_service *service, const char *name, if (dcp->dcpavserv.service) { dcp->dcpavserv.enabled = true; dcp->dcpavserv.epoch++; + /* A new instance: the host is no client of it yet. */ + dcp->dcpavserv.opened = NULL; + dcp->dcpavserv.opened_epoch = 0; service->cookie = &dcp->dcpavserv; complete(&dcp->dcpavserv.enable_completion); published = true; @@ -168,7 +173,9 @@ static void dcpavserv_teardown(struct apple_epic_service *service) dcp->dcpavserv.enabled = false; dcp->dcpavserv.service = NULL; dcp->dcpavserv.epoch++; + /* A removed instance took its open with it. */ dcp->dcpavserv.opened = NULL; + dcp->dcpavserv.opened_epoch = 0; dcpavserv_invalidate_edid(dcp); reinit_completion(&dcp->dcpavserv.enable_completion); owned = true; @@ -189,12 +196,14 @@ void dpavservep_detach(struct apple_dcp *dcp) /* Also reject an in-flight prepare/OPEN with no published owner yet. */ dcp->dcpavserv.epoch++; dcp->dcpavserv.opened = NULL; + dcp->dcpavserv.opened_epoch = 0; reinit_completion(&dcp->dcpavserv.enable_completion); if (service) { afk_service_retire(service); dcpavserv_invalidate_edid(dcp); } mutex_unlock(&dcp->dcpavserv.lock); + cancel_work_sync(&dcp->dcpavserv.close_wq); if (service) afk_service_put(service); } @@ -296,10 +305,180 @@ static int parse_report(struct apple_epic_service *service, enum epic_subtype ty return 0; } +/* + * The 14.7 external role: the host opens the published AV instance as a + * client (DCPAV Open, command 4, a zero 32-byte body; the reply carries a + * status at +0 and the opened Boolean at +16) to read the sink's EDID + * through it. An open client is one the firmware waits for, up to 10 s, + * before it removes the instance: it holds the reply to the sink's HPD low + * until the instance's device has closed, and with it the sink's release and + * the next sink. So the client is closed (DCPAV Close, command 5, a zero + * 16-byte body, status at +0) before every HPD low and when the firmware + * terminates the instance (report group 2, command 1). Close goes only to the + * instance that was opened; a removed instance took its open with it. + * Neither call is made under dcpavserv.lock, which never waits for firmware. + * + * Each instance is named by its epoch, which changes even when its slot is + * reused for the next one. A Close or a Terminate that comes while an Open + * is on its way cancels that Open's publication (close_gen): its opener + * then closes the client itself, if the instance is still the current one. + * Work queued for an instance acts on that instance only. + */ +static int dcpavserv_v14_call(struct apple_epic_service *service, u16 group, u32 command, + void *reply, size_t size) +{ + KUNIT_STATIC_STUB_REDIRECT(dcpavserv_v14_call, service, group, command, reply, size); + return afk_service_call(service, group, command, NULL, 0, size, reply, size, 0); +} + +/* Close the client of @service, pinned by the caller; drops that pin. */ +static void dcpavserv_v14_send_close(struct apple_dcp *dcp, struct apple_epic_service *service) +{ + u8 reply[16] = {}; + int ret; + + ret = dcpavserv_v14_call(service, 0, 5, reply, sizeof(reply)); + afk_service_put(service); + /* Removed while the Close was on its way: nothing is left open. */ + if (ret == -ENODEV) + return; + if (!ret && get_unaligned_le32(reply)) + ret = -EIO; + if (ret) + dev_err(dcp->dev, "DCPAVSERV: AV client close failed: %d\n", ret); + else + dev_info(dcp->dev, "DCPAVSERV: AV client closed\n"); +} + +/* + * The open client of instance @epoch, pinned, if that instance is still the + * published one; the client is no longer recorded open either way. + */ +static struct apple_epic_service *dcpavserv_v14_take_opened(struct apple_dcp *dcp, u64 epoch) +{ + struct apple_epic_service *service = NULL; + + lockdep_assert_held(&dcp->dcpavserv.lock); + if (!dcp->dcpavserv.opened || dcp->dcpavserv.opened_epoch != epoch) + return NULL; + if (dcp->dcpavserv.epoch == epoch && dcp->dcpavserv.opened == dcp->dcpavserv.service) + service = afk_service_get(dcp->dcpavserv.service); + dcp->dcpavserv.opened = NULL; + dcp->dcpavserv.opened_epoch = 0; + return service; +} + +/* + * Open the client of @service, instance @epoch, pinned by the caller, for an + * Open admitted at close generation @gen. 0 once it is recorded open; + * -ECANCELED when a Close or a Terminate came meanwhile (the client opened + * is closed again here) or the instance went; otherwise the Open's error. + */ +static int dcpavserv_v14_open(struct apple_dcp *dcp, struct apple_epic_service *service, + u64 epoch, u64 gen) +{ + struct apple_epic_service *close = NULL; + u8 reply[32] = {}; + bool still; + int ret; + + ret = dcpavserv_v14_call(service, 0, 4, reply, sizeof(reply)); + if (!ret && (get_unaligned_le32(reply) || !get_unaligned_le64(reply + 16))) { + dev_err(dcp->dev, "DCPAVSERV: open answered %#x, opened %llu\n", + get_unaligned_le32(reply), get_unaligned_le64(reply + 16)); + ret = -EIO; + } + mutex_lock(&dcp->dcpavserv.lock); + dcp->dcpavserv.opening = false; + still = dcp->dcpavserv.service == service && dcp->dcpavserv.epoch == epoch; + if (!ret && still && dcp->dcpavserv.close_gen == gen) { + dcp->dcpavserv.opened = service; + dcp->dcpavserv.opened_epoch = epoch; + } else if (!ret) { + /* An instance gone meanwhile took its open with it. */ + if (still) + close = afk_service_get(service); + ret = -ECANCELED; + } + mutex_unlock(&dcp->dcpavserv.lock); + if (close) + dcpavserv_v14_send_close(dcp, close); + else if (!ret) + dev_info(dcp->dev, "DCPAVSERV: AV client open\n"); + return ret; +} + +void dcpavserv_v14_close(struct apple_dcp *dcp) +{ + struct apple_epic_service *service; + + if (!dcp_is_v14_7_external(dcp)) + return; + mutex_lock(&dcp->dcpavserv.lock); + /* An Open on its way is closed again by its opener. */ + dcp->dcpavserv.close_gen++; + service = dcpavserv_v14_take_opened(dcp, dcp->dcpavserv.epoch); + /* Any older instance's open went with that instance. */ + dcp->dcpavserv.opened = NULL; + dcp->dcpavserv.opened_epoch = 0; + mutex_unlock(&dcp->dcpavserv.lock); + if (service) + dcpavserv_v14_send_close(dcp, service); +} + +/* The Close a Terminate queued: for that instance only, if it is still published. */ +void dcpavserv_close_work(struct work_struct *work) +{ + struct dcpavserv *av = container_of(work, struct dcpavserv, close_wq); + struct apple_dcp *dcp = container_of(av, struct apple_dcp, dcpavserv); + struct apple_epic_service *service; + + mutex_lock(&av->lock); + service = dcpavserv_v14_take_opened(dcp, av->close_epoch); + mutex_unlock(&av->lock); + if (service) + dcpavserv_v14_send_close(dcp, service); +} + +/* + * Terminate on the published instance: no new use of it, an Open on its way + * cancelled, and the open client's Close, queued for that instance. + */ +static void dcpavserv_v14_report(struct apple_epic_service *service, enum epic_subtype type, + const void *data, size_t size) +{ + struct apple_dcp *dcp = service->ep->dcp; + const struct epic_service_call *call = data; + bool close = false; + u64 epoch; + + if (type != EPIC_SUBTYPE_STD_SERVICE || size < sizeof(*call) || + le32_to_cpu(call->magic) != EPIC_SERVICE_CALL_MAGIC || + le16_to_cpu(call->group) != 2 || le32_to_cpu(call->command) != 1) + return; + mutex_lock(&dcp->dcpavserv.lock); + epoch = dcp->dcpavserv.epoch; + if (dcp->dcpavserv.service == service && dcp->dcpavserv.terminated_epoch != epoch) { + dcp->dcpavserv.terminated_epoch = epoch; + dcp->dcpavserv.close_gen++; + if (dcp->dcpavserv.opened == service && dcp->dcpavserv.opened_epoch == epoch) { + dcp->dcpavserv.close_epoch = epoch; + close = true; + } + } + mutex_unlock(&dcp->dcpavserv.lock); + if (!close) + return; + dev_info(dcp->dev, "DCPAVSERV: AV instance terminated: closing the client\n"); + schedule_work(&dcp->dcpavserv.close_wq); +} + static int dcpavserv_report(struct apple_epic_service *service, enum epic_subtype type, const void *data, size_t data_size) { + if (dcp_is_v14_7_external(service->ep->dcp)) + dcpavserv_v14_report(service, type, data, data_size); return parse_report(service, type, data, data_size); } @@ -320,6 +499,7 @@ static const struct drm_edid *dcpavserv_read_edid_legacy(struct apple_epic_servi u64 data_size; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcpavserv_read_edid_legacy, service); memset(&cmd, 0, sizeof(cmd)); cmd.max_size = cpu_to_le64(EDID_BUF_SIZE); resp = kzalloc(resp_size, GFP_KERNEL); @@ -405,8 +585,11 @@ bool dcpavserv_edid_service_current(struct apple_dcp *dcp, u64 epoch) const struct drm_edid *dcpavserv_copy_edid(struct apple_dcp *dcp, u64 generation, u64 *epoch) { + bool v14_7_ext = dcp_is_v14_7_external(dcp); struct apple_epic_service *service; const struct drm_edid *edid; + bool open = false; + u64 gen = 0; scoped_guard(mutex, &dcp->hpd_mutex) { if (!dcpavserv_edid_current(dcp, generation)) @@ -415,13 +598,27 @@ const struct drm_edid *dcpavserv_copy_edid(struct apple_dcp *dcp, u64 generation mutex_lock(&dcp->dcpavserv.lock); service = dcp->dcpavserv.enabled ? afk_service_get(dcp->dcpavserv.service) : NULL; *epoch = dcp->dcpavserv.epoch; + if (service && v14_7_ext) { + /* A terminated instance gets no new use; its successor is published. */ + if (dcp->dcpavserv.terminated_epoch == *epoch) { + afk_service_put(service); + service = NULL; + } else if (dcp->dcpavserv.opened_epoch != *epoch && !dcp->dcpavserv.opening) { + dcp->dcpavserv.opening = true; + gen = dcp->dcpavserv.close_gen; + open = true; + } + } mutex_unlock(&dcp->dcpavserv.lock); if (!service) return ERR_PTR(-ENODEV); /* * The 14.7 firmware of an external processor answers EDID requests - * once its service has been opened; open each announced instance once. + * through an instance its client has opened (DCPAV Open): open each + * announced instance once, and close it again before the sink's + * release (dcpavserv_v14_close()). An open the firmware refuses is + * reported; the read that follows validates its own result. * * Only on Aurora's DCPLink session (T6030). The T8122 dcpext, which * Linux starts and drives through the IOMFB template, reads the EDID @@ -429,19 +626,26 @@ const struct drm_edid *dcpavserv_copy_edid(struct apple_dcp *dcp, u64 generation * open call and drops the display link instead, about 50 ms after it, * which brings the display back 4 s later: hotplug in a loop. */ - if (dcp->fw_compat == DCP_FIRMWARE_V_14_7 && - READ_ONCE(dcp->dcpavserv.opened) != service) { - int ret = afk_service_call(service, 4, 6, NULL, 0, 32, NULL, 0, 32); + if (open) { + int ret = dcpavserv_v14_open(dcp, service, *epoch, gen); - if (ret) { + /* Closed, terminated or gone meanwhile: no read through it. */ + if (ret == -ECANCELED) { afk_service_put(service); - return ERR_PTR(ret); + return ERR_PTR(-ENODEV); } - WRITE_ONCE(dcp->dcpavserv.opened, service); + if (ret) + dev_warn(dcp->dev, "DCPAVSERV: AV client not opened: %d\n", ret); } edid = service->ep->wire_v2 ? dcpavserv_read_edid_inline(service) : dcpavserv_read_edid_legacy(service); + /* The 14.7 external role: every block's header and checksum. */ + if (v14_7_ext && !IS_ERR(edid) && !drm_edid_valid(edid)) { + dev_warn(dcp->dev, "DCPAVSERV: the sink's EDID is not valid\n"); + drm_edid_free(edid); + edid = ERR_PTR(-EPROTO); + } mutex_lock(&dcp->dcpavserv.lock); if (dcp->dcpavserv.service != service || !dcpavserv_edid_service_current(dcp, *epoch)) { @@ -527,3 +731,7 @@ int dpavservep_init(struct apple_dcp *dcp) return 0; } + +#if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) +#include "dpavservep-v14-test.c" +#endif diff --git a/drivers/gpu/drm/apple/epic/dpavservep.h b/drivers/gpu/drm/apple/epic/dpavservep.h index 001e211feeb6b4..bf1762963c98a4 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.h +++ b/drivers/gpu/drm/apple/epic/dpavservep.h @@ -7,6 +7,7 @@ #include #include #include +#include struct drm_edid; struct apple_epic_service; @@ -22,10 +23,34 @@ struct dcpavserv { struct completion enable_completion; u32 unit; struct apple_epic_service *service; - /* The service instance last opened; compared only, never used. */ + /* + * The 14.7 external role's AV client, per instance: an instance is + * named by the epoch it was published in, so a slot reused for its + * successor is not mistaken for it. + * + * opened/opened_epoch: the instance the host opened as a client (DCPAV + * Open), closed again before the sink's HPD low or at its Terminate; + * the pointer is compared, and pinned before use. + * opening: an Open is on its way. close_gen: bumped by every Close and + * Terminate; an Open that sees it change was cancelled, and its opener + * closes what it opened. + * terminated_epoch: Terminate reported; that instance gets no new use. + * close_epoch: the instance the Close work was queued for. + */ struct apple_epic_service *opened; + u64 opened_epoch; + bool opening; + u64 close_gen; + u64 terminated_epoch; + u64 close_epoch; + struct work_struct close_wq; }; +/* The 14.7 external role: close the AV client before the sink is released. */ +void dcpavserv_v14_close(struct apple_dcp *dcp); +/* Its Terminate work; set up once with the DCP (dcp_platform_probe_pipe()). */ +void dcpavserv_close_work(struct work_struct *work); + bool dcpavserv_edid_current(struct apple_dcp *dcp, u64 generation); bool dcpavserv_edid_service_current(struct apple_dcp *dcp, u64 epoch); const struct drm_edid *dcpavserv_copy_edid(struct apple_dcp *dcp, u64 generation, diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index f8e068fff0b650..1efc58efd6f620 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -1865,6 +1865,8 @@ int dcp_get_modes(struct drm_connector *connector) apple_connector->drm_edid = edid; apple_connector->drm_edid_generation = edid_generation; apple_connector->drm_edid_service_epoch = service_epoch; + /* A native T6030 pipe: its audio, after the first EDID. */ + dcp_external_audio_start(dcp); } } if (nr_modes && apple_connector->drm_edid) { diff --git a/drivers/gpu/drm/apple/iomfb_plane.h b/drivers/gpu/drm/apple/iomfb_plane.h index 73f104059d29cc..31a2ddc9525bb3 100644 --- a/drivers/gpu/drm/apple/iomfb_plane.h +++ b/drivers/gpu/drm/apple/iomfb_plane.h @@ -15,6 +15,7 @@ #define DCP_FORMAT_BGRA fourcc_code('A', 'R', 'G', 'B') #define DCP_FORMAT_RGBA fourcc_code('A', 'B', 'G', 'R') +#define DCP_FORMAT_AhGR fourcc_code('A', 'h', 'G', 'R') /* 16-bit half float ABGR */ #define DCP_FORMAT_W30R fourcc_code('r', '0', '3', 'w') // wide gamut packed 10-bit RGB without alpha #define DCP_FORMAT_L10R fourcc_code('r', '0', '1', 'l') // full range packed 10-bit RGB with alpha @@ -34,6 +35,14 @@ #define DCP_FORMAT_XF22 fourcc_code('2', '2', 'f', 'x') // P210 full range 2 plane 10-bit YCbCR #define DCP_FORMAT_XF44 fourcc_code('4', '4', 'f', 'x') // P410 full range 2 plane 10-bit YCbCR +#define DCP_FORMAT_P420 fourcc_code('0', '2', '4', 'p') /* P030 video range 2 plane 10-bit YCbCr, 3x1 blocks */ +#define DCP_FORMAT_P422 fourcc_code('2', '2', '4', 'p') /* P230 video range 2 plane 10-bit YCbCr, 3x1 blocks */ +#define DCP_FORMAT_P444 fourcc_code('4', '4', '4', 'p') /* P430 video range 2 plane 10-bit YCbCr, 3x1 blocks */ + +#define DCP_FORMAT_PF20 fourcc_code('0', '2', 'f', 'p') /* P030 full range 2 plane 10-bit YCbCr, 3x1 blocks */ +#define DCP_FORMAT_PF22 fourcc_code('2', '2', 'f', 'p') /* P230 full range 2 plane 10-bit YCbCr, 3x1 blocks */ +#define DCP_FORMAT_PF44 fourcc_code('4', '4', 'f', 'p') /* P430 full range 2 plane 10-bit YCbCr, 3x1 blocks */ + enum dcp_colorspace { DCP_COLORSPACE_BG_SRGB = 0, DCP_COLORSPACE_BT601 = 1, @@ -49,6 +58,24 @@ enum dcp_xfer_func { DCP_XFER_FUNC_HDR = 16, }; +enum dcp_addr_fmt { + DCP_ADDR_FMT_LINEAR = 0, + /* Twiddled layout supported by AGX */ + DCP_ADDR_FMT_GPU_TWIDDLED = 2, + /* Tiled layout supported by AGX */ + DCP_ADDR_FMT_GPU_TILED = 3, + /* Tiled layout used for buffers shared between hardware blocks */ + DCP_ADDR_FMT_INTERCHANGE_TILED = 5, +}; + +enum dcp_compression_type { + DCP_COMPRESSION_NONE = 0, + /* Optional for GPU_TWIDDLED and GPU_TILED */ + DCP_COMPRESSION_AGX = 2, + /* Always required for INTERCHANGE_TILED */ + DCP_COMPRESSION_INTERCHANGE = 3, +}; + struct dcp_rect { u32 x; u32 y; @@ -68,7 +95,7 @@ struct dcp_plane_info { u8 tile_w; u8 tile_h; u8 unk[0xd]; - u8 unk2; + u8 address_fmt; u8 unk3[0x26]; } __packed; @@ -94,6 +121,18 @@ struct dcp_compression_info { u8 pad2; } __packed; +struct dcp_image_layout { + u32 tile_w; + u32 tile_h; + u32 width_tiles; + u32 height_tiles; + u32 tile_bytes; + /* For compressed layouts */ + u32 meta_offset; + u32 meta_size; + u32 meta_tile_bytes; +}; + /* Information describing a surface */ struct dcp_surface { u8 is_tiled; diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 784542caec14f5..c1b0e21b65e5e6 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -1795,9 +1795,14 @@ static void last_client_closed_poff(struct apple_dcp *dcp, void *out, void *cook static void aborted_swaps_dcp_poff(struct apple_dcp *dcp, void *out, void *cookie) { +#if DCP_FW_VER >= DCP_FW_VERSION(14, 7, 0) + /* iomfb_last_client_close times out on 14.7 */ + last_client_closed_poff(dcp, NULL, cookie); +#else struct iomfb_last_client_close_req last_client_req = {}; iomfb_last_client_close(dcp, false, &last_client_req, last_client_closed_poff, cookie); +#endif } void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index 743c14cbbf63b9..474841ff8d0aec 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -31,6 +31,7 @@ #include #include #include +#include #include "afk.h" #include "dcp.h" @@ -42,6 +43,7 @@ #include "iomfb_v14_7_board.h" #include "iomfb_v14_7_link.h" #include "iomfb_v14_7_swap.h" +#include "av.h" #include "parser.h" #define A(n) DCP_V14_TAG('A', n) @@ -76,7 +78,16 @@ static int dcp_v14_pmp_wait_ready(struct device_node *entry, #define DCP_V14_RTKIT_RETRIES 4 #define DCP_V14_MAX_PROPERTIES 256 #define DCP_V14_MAX_RAW 32 +/* + * The size of one raw property and of all of them. An external processor + * publishes an HDMI 2.1 (FRL) sink's TimingElements as one chunked transfer + * of more than 1 MiB (1.38 MB for a 4K120 TV), so it keeps up to 8 MiB per + * property and 24 MiB in all; the panel's properties stay small. + */ +#define DCP_V14_MAX_RAW_SIZE SZ_1M #define DCP_V14_MAX_RAW_BYTES SZ_8M +#define DCP_V14_EXT_MAX_RAW_SIZE SZ_8M +#define DCP_V14_EXT_MAX_RAW_BYTES (24 * SZ_1M) #define DCP_V14_MAX_BUFFERS 64 #define DCP_V14_MAX_BUFFER SZ_16M #define DCP_V14_MAX_BUFFER_BYTES SZ_64M @@ -150,11 +161,30 @@ static const struct dcp_v14_board dcp_v14_board_j516c = { .log_bringup = true, }; +/* + * J514C (MacBook Pro 14", M3 Max): the T6031 DCP running the J516C image + * (the DCP image is the SoC's; its UUID is checked at probe), in the J514S + * chassis, so the J514 panel: the board file names the J514S panel values, + * not yet read from a J514C, and the panel size comes from the boot + * framebuffer. Every panel timing and the display clock are logged. + */ +static const struct dcp_v14_board dcp_v14_board_j514c = { + .name = "J514C", + .debugfs = "dcp-j514c", + .dcp_compatible = "apple,t6031-dcp", + .machine = "apple,j514c", + .firmware_uuid = DCP_V14_J516C_FIRMWARE_UUID, + .handoff = "apple,t6031-handoff", + .promotion = true, + .log_bringup = true, +}; + static const struct dcp_v14_board *const dcp_v14_boards[] = { &dcp_v14_board_t6030, &dcp_v14_board_j613, &dcp_v14_board_j615, &dcp_v14_board_j516c, + &dcp_v14_board_j514c, }; struct dcp_v14_property { @@ -364,13 +394,23 @@ static struct dcp_v14_property *dcp_v14_property(struct apple_dcp_v14 *v14, u32 return p; } +static u32 dcp_v14_raw_limit(const struct apple_dcp_v14 *v14) +{ + return v14->external ? DCP_V14_EXT_MAX_RAW_SIZE : DCP_V14_MAX_RAW_SIZE; +} + +static u32 dcp_v14_raw_total(const struct apple_dcp_v14 *v14) +{ + return v14->external ? DCP_V14_EXT_MAX_RAW_BYTES : DCP_V14_MAX_RAW_BYTES; +} + static int dcp_v14_raw_property(struct apple_dcp_v14 *v14, u32 service, const u8 *key, const void *data, u32 size) { u32 i, old_size = 0; void *copy; - if (!memchr(key, 0, 64) || size > SZ_1M) + if (!memchr(key, 0, 64) || size > dcp_v14_raw_limit(v14)) return -EINVAL; for (i = 0; i < v14->raw_count; i++) if (v14->raw[i].service == service && !strcmp(v14->raw[i].key, key)) @@ -379,7 +419,7 @@ static int dcp_v14_raw_property(struct apple_dcp_v14 *v14, u32 service, const u8 return -ENOSPC; if (i < v14->raw_count) old_size = v14->raw[i].size; - if (v14->raw_bytes - old_size + size > DCP_V14_MAX_RAW_BYTES) + if (v14->raw_bytes - old_size + size > dcp_v14_raw_total(v14)) return -ENOSPC; copy = kvmemdup(data, size ?: 1, GFP_KERNEL); if (!copy) @@ -817,7 +857,8 @@ static int dcp_v14_external_callback(struct apple_dcp_v14 *v14, u32 tag, const u if (tag == D(127) && SHAPE(4, 4)) { count = get_unaligned_le32(in); ret = -EINVAL; - if (!v14->chunk && count && count <= 0x100001) { + /* The announced count includes one byte that is never sent. */ + if (!v14->chunk && count && count <= dcp_v14_raw_limit(v14) + 1) { v14->chunk_size = count - 1; v14->chunk_offset = 0; v14->chunk = kvzalloc(max_t(u32, 1, v14->chunk_size), GFP_KERNEL); @@ -983,7 +1024,7 @@ static int dcp_v14_callback(void *cookie, u32 tag, const void *input, u32 in_siz /* Chunked property transfer: start, chunk, end. */ if (tag == D(127) && SHAPE(4, 4)) { count = get_unaligned_le32(in); - if (v14->chunk || !count || count > 0x100001) + if (v14->chunk || !count || count > dcp_v14_raw_limit(v14) + 1) return -EINVAL; v14->chunk_size = count - 1; v14->chunk_offset = 0; @@ -1617,25 +1658,17 @@ enum { static void dcpext_bringup(struct work_struct *work); /* - * The bounded translator (900-config-tooling) is optional at link time; - * without it, refuse a tuple that does not fit before using the unbounded one. + * Translate one iommu-addresses tuple, refusing a truncated one. + * of_translate_dma_region_checked() is an ordinary exported symbol and + * DRM_APPLE depends on OF_ADDRESS, so it is always linked: call it directly. + * The former symbol_get() could never resolve it -- symbol_get() takes only + * GPL-only symbols -- so the bounded check was silently skipped. */ static const __be32 *dcpext_translate_region(struct device_node *np, const __be32 *maps, size_t cells, phys_addr_t *iova, size_t *length) { - typeof(&of_translate_dma_region_checked) checked; - const __be32 *next; - - checked = symbol_get(of_translate_dma_region_checked); - if (checked) { - next = checked(np, maps, cells, iova, length); - symbol_put(of_translate_dma_region_checked); - return next; - } - if (cells < (size_t)(of_n_addr_cells(np) + of_n_size_cells(np))) - return NULL; - return of_translate_dma_region(np, maps, iova, length); + return of_translate_dma_region_checked(np, maps, cells, iova, length); } /* @@ -2843,15 +2876,45 @@ bool iomfb_v14_7_external_showing(struct apple_dcp *dcp, return live; } +bool iomfb_v14_7_external_powered(struct apple_dcp *dcp) +{ + struct apple_dcp_v14 *v14 = dcp->v14; + + return dcp->external && v14 && READ_ONCE(v14->powered) && !READ_ONCE(v14->failed); +} + +/* The sink's audio around an external mode set. */ +static void dcp_v14_audio_off(struct apple_dcp *dcp) +{ + KUNIT_STATIC_STUB_REDIRECT(dcp_v14_audio_off, dcp); + av_service_disconnect(dcp); +} + +static void dcp_v14_audio_on(struct apple_dcp *dcp) +{ + KUNIT_STATIC_STUB_REDIRECT(dcp_v14_audio_on, dcp); + av_service_connect(dcp); +} + /* An external display: power down, set the new mode, power up. */ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { struct apple_dcp_v14 *v14 = dcp->v14; struct dcp_display_mode mode = {}; + bool audio_off = false; int ret = 0; if (!v14 || READ_ONCE(v14->failed) || !v14->opened) return -EIO; + /* + * The sink's audio stops before the display is powered down for the + * mode change (as dcp_poweroff() has it), outside the RPC lock; it is + * connected again once the display is on, below. + */ + if (READ_ONCE(v14->powered) && dcp->avep) { + dcp_v14_audio_off(dcp); + audio_off = true; + } ret = dcp_v14_external_settle(dcp, v14); if (ret) goto out; @@ -2872,6 +2935,8 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state DRM_MODE_ARG(&crtc_state->mode), mode.timing_mode_id, mode.color_mode_id); atomic_set(&dcp->external_retries, 0); dcp_mode_set_valid(&dcp->mode_state, true); + if (dcp->avep) + dcp_v14_audio_on(dcp); return 0; } if (v14->powered && dcp_v14_set_power(v14, false)) @@ -2895,13 +2960,23 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state dev_info(dcp->dev, "display mode " DRM_MODE_FMT " (timing %u, color %u): %d\n", DRM_MODE_ARG(&crtc_state->mode), mode.timing_mode_id, mode.color_mode_id, ret); if (ret) { - /* A mode that is gone, or a description that never settled. */ + /* + * A mode that is gone, or a description that never settled: + * nothing was powered down, and the display goes on in its old + * mode. So does its audio; no plug event would bring it back + * if the retries fail too. + */ + if (audio_off && iomfb_v14_7_external_powered(dcp)) + dcp_v14_audio_on(dcp); dcp_external_retry(dcp, "display mode not set", ret, 500); return ret; } atomic_set(&dcp->external_retries, 0); scoped_guard(spinlock_irqsave, &dcp->mode_state.lock) dcp->mode_state.valid = true; + /* A472 on: the sink's audio again. */ + if (dcp->avep) + dcp_v14_audio_on(dcp); return 0; } @@ -2961,6 +3036,9 @@ void iomfb_v14_7_poweroff(struct apple_dcp *dcp) /* An external display is powered down; the next enable sets its mode again. */ if (dcp->external) { + /* Audio stops with the display, as dcp_poweroff() has it. */ + if (dcp->avep) + av_service_disconnect(dcp); if (v14 && v14->opened && !READ_ONCE(v14->failed)) { mutex_lock(&v14->lock); if (v14->powered && dcp_v14_set_power(v14, false)) @@ -2974,3 +3052,7 @@ void iomfb_v14_7_poweroff(struct apple_dcp *dcp) if (v14 && v14->started) dcp_v14_present(v14, NULL, 0, 0, 0, NULL); } + +#if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) +#include "iomfb_v14_7_external_audio_test.c" +#endif diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.h b/drivers/gpu/drm/apple/iomfb_v14_7.h index f6fe9e199b0149..f9bef6ed0f109f 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.h +++ b/drivers/gpu/drm/apple/iomfb_v14_7.h @@ -47,6 +47,8 @@ int iomfb_v14_7_external_open(struct apple_dcp *dcp); const char *iomfb_v14_7_external_busy(struct apple_dcp *dcp); /* The external session can no longer be used until reboot. */ bool iomfb_v14_7_external_failed(struct apple_dcp *dcp); +/* The attached display is powered (A472 on) in the mode last set. */ +bool iomfb_v14_7_external_powered(struct apple_dcp *dcp); /* The firmware runs this mode, set last, and shows swaps in it. */ bool iomfb_v14_7_external_showing(struct apple_dcp *dcp, const struct drm_display_mode *mode); diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_external_audio_test.c b/drivers/gpu/drm/apple/iomfb_v14_7_external_audio_test.c new file mode 100644 index 00000000000000..a20810109fca21 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_v14_7_external_audio_test.c @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The sink's audio around a failed external mode set, included at the end + * of iomfb_v14_7.c so that the production dcp_v14_external_modeset() runs. + * Only the audio service is stubbed. The mode lookup fails on an empty + * catalog after a complete description, before anything is powered down. + */ +#include +#include +#include + +struct v14_ext_audio { + struct apple_dcp *dcp; + struct apple_dcp_v14 *v14; + unsigned int offs, ons; +}; + +static struct v14_ext_audio *v14_ext_audio_current; + +static void v14_ext_audio_off(struct apple_dcp *dcp) +{ + v14_ext_audio_current->offs++; +} + +static void v14_ext_audio_on(struct apple_dcp *dcp) +{ + v14_ext_audio_current->ons++; +} + +static void v14_ext_audio_retry(struct work_struct *work) +{ +} + +static void v14_ext_audio_stop(void *data) +{ + struct apple_dcp *dcp = data; + + cancel_delayed_work_sync(&dcp->external_retry_wq); +} + +/* A started, described native external session, its display @powered. */ +static struct v14_ext_audio *v14_ext_audio_setup(struct kunit *test, bool powered) +{ + struct v14_ext_audio *s = kunit_kzalloc(test, sizeof(*s), GFP_KERNEL); + struct device *dev; + + KUNIT_ASSERT_NOT_NULL(test, s); + dev = kunit_device_register(test, "dcp-v14-ext-audio"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + s->dcp = devm_kzalloc(dev, sizeof(*s->dcp), GFP_KERNEL); + s->v14 = devm_kzalloc(dev, sizeof(*s->v14), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, s->dcp); + KUNIT_ASSERT_NOT_NULL(test, s->v14); + s->dcp->dev = dev; + s->dcp->fw_compat = DCP_FIRMWARE_V_14_7; + s->dcp->external = true; + s->dcp->external_native = true; + /* Never dereferenced: the audio service is stubbed. */ + s->dcp->avep = (struct apple_dcp_afkep *)s; + mutex_init(&s->dcp->modes_lock); + INIT_DELAYED_WORK(&s->dcp->external_retry_wq, v14_ext_audio_retry); + s->dcp->v14 = s->v14; + s->v14->dev = dev; + s->v14->dcp = s->dcp; + s->v14->external = true; + s->v14->started = true; + s->v14->opened = true; + s->v14->powered = powered; + s->v14->described = DCP_V14_DESC_ALL; + mutex_init(&s->v14->lock); + init_waitqueue_head(&s->v14->described_wait); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, v14_ext_audio_stop, s->dcp), 0); + v14_ext_audio_current = s; + kunit_activate_static_stub(test, dcp_v14_audio_off, v14_ext_audio_off); + kunit_activate_static_stub(test, dcp_v14_audio_on, v14_ext_audio_on); + return s; +} + +/* The mode is gone, the display stays on in its old mode: so does its audio. */ +static void v14_ext_audio_failed_modeset_keeps_audio(struct kunit *test) +{ + struct v14_ext_audio *s = v14_ext_audio_setup(test, true); + struct drm_crtc_state *state = kunit_kzalloc(test, sizeof(*state), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, state); + KUNIT_EXPECT_EQ(test, dcp_v14_external_modeset(s->dcp, state), -EINVAL); + KUNIT_EXPECT_EQ(test, s->offs, 1U); + KUNIT_EXPECT_EQ(test, s->ons, 1U); + KUNIT_EXPECT_TRUE(test, s->v14->powered); + KUNIT_EXPECT_FALSE(test, s->v14->failed); + /* The mode set is still retried. */ + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&s->dcp->external_retry_wq)); + KUNIT_EXPECT_FALSE(test, mutex_is_locked(&s->v14->lock)); +} + +/* A display that was off has no audio to stop, and none comes back. */ +static void v14_ext_audio_failed_modeset_display_off(struct kunit *test) +{ + struct v14_ext_audio *s = v14_ext_audio_setup(test, false); + struct drm_crtc_state *state = kunit_kzalloc(test, sizeof(*state), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, state); + KUNIT_EXPECT_EQ(test, dcp_v14_external_modeset(s->dcp, state), -EINVAL); + KUNIT_EXPECT_EQ(test, s->offs, 0U); + KUNIT_EXPECT_EQ(test, s->ons, 0U); +} + +/* + * Out of retries: the display stays on in its old mode, and so does its + * audio. Nothing else would connect the sink again. + */ +static void v14_ext_audio_no_retry_left(struct kunit *test) +{ + struct v14_ext_audio *s = v14_ext_audio_setup(test, true); + struct drm_crtc_state *state = kunit_kzalloc(test, sizeof(*state), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, state); + /* Past any retry budget (DCP_EXTERNAL_RETRIES in dcp.c). */ + atomic_set(&s->dcp->external_retries, 100); + KUNIT_EXPECT_EQ(test, dcp_v14_external_modeset(s->dcp, state), -EINVAL); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&s->dcp->external_retry_wq)); + KUNIT_EXPECT_EQ(test, s->offs, 1U); + KUNIT_EXPECT_EQ(test, s->ons, 1U); +} + +static struct kunit_case v14_ext_audio_cases[] = { + KUNIT_CASE(v14_ext_audio_failed_modeset_keeps_audio), + KUNIT_CASE(v14_ext_audio_failed_modeset_display_off), + KUNIT_CASE(v14_ext_audio_no_retry_left), + {} +}; + +static struct kunit_suite v14_ext_audio_suite = { + .name = "dcp_v14_external_audio", + .test_cases = v14_ext_audio_cases, +}; + +kunit_test_suite(v14_ext_audio_suite); diff --git a/drivers/gpu/drm/apple/parser-test.c b/drivers/gpu/drm/apple/parser-test.c index d7cdc1544b3fc6..9cf57af1b3c94c 100644 --- a/drivers/gpu/drm/apple/parser-test.c +++ b/drivers/gpu/drm/apple/parser-test.c @@ -1077,7 +1077,9 @@ static void parser_optional_flag_extent(struct kunit *test) static void parser_attribute_deferred(struct kunit *test) { struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); - struct apple_connector *connector = kunit_kzalloc(test, sizeof(*connector), GFP_KERNEL); + struct parser_catalog_observer *observer = + kunit_kzalloc(test, sizeof(*observer), GFP_KERNEL); + struct apple_connector *connector = observer ? &observer->connector : NULL; struct drm_device *dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); struct dcp_parse_ctx ctx; @@ -1088,6 +1090,8 @@ static void parser_attribute_deferred(struct kunit *test) KUNIT_ASSERT_NOT_NULL(test, dev); KUNIT_ASSERT_NOT_NULL(test, blob); dcp_modes_init(dcp); + observer->dcp = dcp; + INIT_WORK(&connector->hotplug_wq, parser_catalog_ready); mutex_init(&dev->mode_config.mutex); connector->base.dev = dev; dcp->connector = connector; @@ -1109,6 +1113,8 @@ static void parser_attribute_deferred(struct kunit *test) KUNIT_EXPECT_EQ(test, dcp->modes[0].mode.width_mm, 520); mutex_unlock(&dev->mode_config.mutex); flush_work(&dcp->dimensions_wq); + flush_work(&connector->hotplug_wq); + KUNIT_EXPECT_EQ(test, observer->notifications, 1U); KUNIT_EXPECT_EQ(test, connector->base.display_info.width_mm, 520U); KUNIT_EXPECT_EQ(test, connector->base.display_info.height_mm, 290U); dcp_modes_release(dcp); diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 0de67aa8fe710e..1d0638360251c6 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -1776,14 +1776,19 @@ static int parse_mode_in_avep_element(struct dcp_parse_ctx *handle, return ret; } } else if (consume_string(it.handle, "ElementData")) { + size_t size = DCP_SOUND_COOKIE_SIZE; const u8 *blob; - ret = parse_blob(it.handle, sizeof(*cookie), &blob); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + if (dcp_parse_v14_7_audio(handle)) + size = DCP_SOUND_COOKIE_SIZE_V14_7; +#endif + ret = parse_blob(it.handle, size, &blob); if (ret) return ret; if (cookie) - memcpy(cookie, blob, sizeof(*cookie)); + memcpy(cookie, blob, size); } else { ret = skip_pair(it.handle); if (ret) diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index 0557cc09e63e44..2ba2c22a070266 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -21,8 +21,26 @@ struct dcp_parse_ctx { /* External H17P candidates require separate publication/lookup proof. */ bool automatic_1080p180_rgb8; bool ambiguous_180hz; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* + * T6030 external processor audio elements (DCP firmware 14.7, external + * role): an element's ElementData, the link data the audio service + * takes, is 32 bytes. + */ + bool v14_7_audio; +#endif }; +/* The T6030 external processor's audio elements (DRM_APPLE_DCP_T6030_AUDIO only). */ +static inline bool dcp_parse_v14_7_audio(const struct dcp_parse_ctx *ctx) +{ +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + return ctx->v14_7_audio; +#else + return false; +#endif +} + enum dcp_color_eotf { DCP_EOTF_SDR_GAMMA = 0, // "SDR gamma" DCP_EOTF_HDR_GAMMA = 1, // "HDR gamma" @@ -178,8 +196,20 @@ struct dcp_sound_format_mask { unsigned int nchans; }; +/* + * An audio element's ElementData, the link data of the audio service's link + * methods: 24 bytes up to DCP firmware 13.5, 32 on the 14.7 external role. + */ +#define DCP_SOUND_COOKIE_SIZE 24 +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +#define DCP_SOUND_COOKIE_SIZE_V14_7 32 +#define DCP_SOUND_COOKIE_MAX DCP_SOUND_COOKIE_SIZE_V14_7 +#else +#define DCP_SOUND_COOKIE_MAX DCP_SOUND_COOKIE_SIZE +#endif + struct dcp_sound_cookie { - u8 data[24]; + u8 data[DCP_SOUND_COOKIE_MAX]; }; struct snd_pcm_chmap_elem; diff --git a/drivers/gpu/drm/apple/plane.c b/drivers/gpu/drm/apple/plane.c index aa5bbc9551d2ce..cde215f62b1436 100644 --- a/drivers/gpu/drm/apple/plane.c +++ b/drivers/gpu/drm/apple/plane.c @@ -8,6 +8,7 @@ #include "dcp-internal.h" #include "iomfb_internal.h" +#include "iomfb_plane.h" #include #include #include @@ -18,14 +19,206 @@ #include #include +#include +#include +#include + +#define APPLE_GPU_CACHELINE 16 #define FRAC_16_16(mult, div) (((mult) << 16) / (div)) +struct apple_plane_layout { + struct dcp_image_layout image; + u32 width; + u32 height; + u32 offset; + u32 stride; + u32 size; + u32 tile_size; +}; + +static int apple_plane_ix_bpp(const struct drm_format_info *fmt, u32 plane, + u32 *bpp) +{ + u32 bw = drm_format_info_block_width(fmt, plane); + u32 bh = drm_format_info_block_height(fmt, plane); + u32 bits = fmt->char_per_block[plane] * 8; + u32 block_pixels; + + /* + * P030/P230 pack three pixels per block. Neither an integer bpp + * (which would be zero) nor a truncated bpp describes their tiles. + * Keep these formats linear until their interchange packing is known. + */ + if (!bw || !bh || check_mul_overflow(bw, bh, &block_pixels) || !bits || + bits % block_pixels) + return -EINVAL; + *bpp = bits / block_pixels; + + return 0; +} + +static bool apple_plane_format_mod_supported(struct drm_plane *plane, + u32 format, u64 modifier) +{ + const struct drm_format_info *fmt = drm_format_info(format); + u32 bpp; + unsigned int i; + + if (!fmt) + return false; + + /* The callback replaces DRM's generic modifier-list validation. */ + for (i = 0; i < plane->modifier_count; i++) + if (modifier == plane->modifiers[i]) + break; + if (i == plane->modifier_count) + return false; + + switch (modifier) { + case DRM_FORMAT_MOD_LINEAR: + case DRM_FORMAT_MOD_INVALID: + return true; + case DRM_FORMAT_MOD_APPLE_INTERCHANGE: + for (u32 i = 0; i < fmt->num_planes; i++) + if (apple_plane_ix_bpp(fmt, i, &bpp)) + return false; + return true; + default: + return false; + } +} + +static int apple_get_ix_layout(u32 width, u32 height, + const struct drm_format_info *fmt, u32 plane, + struct apple_plane_layout *out) +{ + struct dcp_image_layout *layout = &out->image; + u32 bpp, meta_tile_w, meta_tile_h, tiles, bytes; + int ret; + + ret = apple_plane_ix_bpp(fmt, plane, &bpp); + if (ret) + return ret; + + /* + * Compression subtiles are always 16x16 with 8 bytes of metadata, + * but IOMFB requires values relative to the image tile dimensions. + */ + if (fmt->is_yuv && plane == 0) { + layout->tile_w = 32; + layout->tile_h = 32; + layout->meta_tile_bytes = 32; + } else { + layout->tile_w = 16; + layout->tile_h = 16; + layout->meta_tile_bytes = 8; + } + + layout->width_tiles = (width - 1) / layout->tile_w + 1; + layout->height_tiles = (height - 1) / layout->tile_h + 1; + layout->tile_bytes = layout->tile_w * layout->tile_h * bpp / 8; + if (layout->tile_bytes > U16_MAX || + check_mul_overflow(layout->width_tiles, layout->tile_bytes, + &out->stride) || + check_mul_overflow(out->stride, layout->height_tiles, &bytes) || + check_add_overflow(bytes, APPLE_GPU_CACHELINE - 1, &bytes)) + return -EINVAL; + layout->meta_offset = bytes & ~(APPLE_GPU_CACHELINE - 1); + + /* The rounded dimensions and all wire-format sizes must fit u32. */ + if (width > BIT(31) || height > BIT(31)) + return -EINVAL; + meta_tile_w = DIV_ROUND_UP(roundup_pow_of_two(width), layout->tile_w); + meta_tile_h = DIV_ROUND_UP(roundup_pow_of_two(height), layout->tile_h); + if (check_mul_overflow(meta_tile_w, meta_tile_h, &tiles) || + check_mul_overflow(tiles, layout->meta_tile_bytes, &bytes) || + check_add_overflow(bytes, APPLE_GPU_CACHELINE - 1, &bytes)) + return -EINVAL; + layout->meta_size = bytes & ~(APPLE_GPU_CACHELINE - 1); + if (check_add_overflow(layout->meta_offset, layout->meta_size, + &out->size)) + return -EINVAL; + out->tile_size = layout->tile_bytes; + + return 0; +} + +/* Use exactly the same geometry for admission and surface construction. */ +static int apple_plane_get_fb_layout(struct drm_framebuffer *fb, + struct apple_plane_layout *planes, + u32 *buf_size) +{ + const struct drm_format_info *fmt = fb->format; + struct drm_gem_dma_object *first; + u32 end; + int ret; + + if (!fb->width || !fb->height || !fmt->hsub || !fmt->vsub || + !fmt->num_planes || fmt->num_planes > DCP_SURF_MAX_PLANES) + return -EINVAL; + first = drm_fb_dma_get_gem_obj(fb, 0); + if (!first) + return -EINVAL; + + *buf_size = 0; + for (u32 i = 0; i < fmt->num_planes; i++) { + struct apple_plane_layout *p = &planes[i]; + struct drm_gem_dma_object *obj = drm_fb_dma_get_gem_obj(fb, i); + + /* DCP currently uses one GEM object for the whole surface. */ + if (obj != first || fb->offsets[i] < fb->offsets[0]) + return -EINVAL; + *p = (struct apple_plane_layout){ + .width = i ? DIV_ROUND_UP_ULL(fb->width, fmt->hsub) : + fb->width, + .height = i ? DIV_ROUND_UP_ULL(fb->height, fmt->vsub) : + fb->height, + .offset = fb->offsets[i] - fb->offsets[0], + }; + if (!p->width || !p->height) + return -EINVAL; + + switch (fb->modifier) { + case DRM_FORMAT_MOD_APPLE_INTERCHANGE: + ret = apple_get_ix_layout(p->width, p->height, fmt, i, + p); + if (ret) + return ret; + break; + case DRM_FORMAT_MOD_INVALID: + case DRM_FORMAT_MOD_LINEAR: + if (!fb->pitches[i] || fb->pitches[i] & 63 || + check_mul_overflow(p->height, fb->pitches[i], + &p->size)) + return -EINVAL; + p->image.tile_w = drm_format_info_block_width(fmt, i); + p->image.tile_h = drm_format_info_block_height(fmt, i); + p->tile_size = p->image.tile_w * p->image.tile_h; + p->stride = fb->pitches[i]; + break; + default: + return -EINVAL; + } + + if (check_add_overflow(p->offset, p->size, &end) || + (u64)fb->offsets[i] + p->size > obj->base.size || + check_add_overflow(*buf_size, p->size, buf_size)) + return -EINVAL; + } + if ((u64)fb->offsets[0] + *buf_size > first->base.size) + return -EINVAL; + + return 0; +} + static int apple_plane_atomic_check(struct drm_plane *plane, struct drm_atomic_commit *commit) { struct drm_plane_state *new_plane_state; struct drm_crtc_state *crtc_state; struct drm_rect *dst; + struct apple_plane_layout layouts[DCP_SURF_MAX_PLANES]; + u32 buf_size; int ret; new_plane_state = drm_atomic_get_new_plane_state(commit, plane); @@ -56,6 +249,10 @@ static int apple_plane_atomic_check(struct drm_plane *plane, if (ret < 0) return ret; + ret = apple_plane_get_fb_layout(new_plane_state->fb, layouts, &buf_size); + if (ret) + return ret; + if (!new_plane_state->visible) return 0; @@ -84,29 +281,6 @@ static int apple_plane_atomic_check(struct drm_plane *plane, return -EINVAL; } - /* - * Pitches have to be 64-byte aligned. - */ - for (u32 i = 0; i < new_plane_state->fb->format->num_planes; i++) - if (new_plane_state->fb->pitches[i] & 63) - return -EINVAL; - - /* - * FIXME: dcp can currently only use multi-planar buffers using the same - * object for all planes. It has a mandatory iommu so it should - * be no problem to map multiple objects "linearly" into DCP - * virtual address space and calculate the offsets accordingly. - * Or maybe it can accept multiple BOs via the per plane field - * `base`. - */ - if (new_plane_state->fb->format->num_planes > 1) { - const struct drm_gem_object *first = new_plane_state->fb->obj[0]; - for (u32 i = 1; i < new_plane_state->fb->format->num_planes; i++) - if (new_plane_state->fb->obj[i] != NULL && - new_plane_state->fb->obj[i] != first) - return -EINVAL; - } - return 0; } @@ -147,6 +321,9 @@ static u32 drm_format_to_dcp(u32 drm, enum drm_color_range range) case DRM_FORMAT_ARGB2101010: return DCP_FORMAT_L10R; + case DRM_FORMAT_ABGR16161616F: + return DCP_FORMAT_AhGR; + /* semi planar YCbCr formats, limited and full range */ case DRM_FORMAT_NV12: return fr ? DCP_FORMAT_420F : DCP_FORMAT_420V; @@ -160,12 +337,21 @@ static u32 drm_format_to_dcp(u32 drm, enum drm_color_range range) return fr ? DCP_FORMAT_XF20 : DCP_FORMAT_X420; case DRM_FORMAT_P210: return fr ? DCP_FORMAT_XF22 : DCP_FORMAT_X422; + /* semi planar 10-bit YCbCr formats, 3x1 blocks, limited and full range */ + case DRM_FORMAT_P030: + return fr ? DCP_FORMAT_PF20 : DCP_FORMAT_P420; + case DRM_FORMAT_P230: + return fr ? DCP_FORMAT_PF22 : DCP_FORMAT_P422; /* - * TODO: missing DRM fourcc for P410 + * TODO: missing DRM fourccs for P410 / P430 */ #if defined(DRM_FORMAT_P410) case DRM_FORMAT_P410: return fr ? DCP_FORMAT_XF44 : DCP_FORMAT_X444; +#endif +#if defined(DRM_FORMAT_P430) + case DRM_FORMAT_P430: + return fr ? DCP_FORMAT_PF44 : DCP_FORMAT_P444; #endif } @@ -213,6 +399,8 @@ static void apple_plane_atomic_update(struct drm_plane *plane, struct drm_plane_state *base = drm_atomic_get_new_plane_state(commit, plane); struct apple_plane_state *new_state; struct drm_gem_dma_object *obj; + struct apple_plane_layout layouts[DCP_SURF_MAX_PLANES]; + u32 buf_size; bool is_premultiplied = false; if (!base) @@ -227,6 +415,12 @@ static void apple_plane_atomic_update(struct drm_plane *plane, struct drm_framebuffer *fb = base->fb; const struct drm_format_info *fmt = fb->format; + + if (WARN_ON_ONCE(apple_plane_get_fb_layout(fb, layouts, &buf_size))) { + memset(&new_state->surf, 0, sizeof(new_state->surf)); + return; + } + /* * DCP doesn't support XBGR8 / XRGB8 / XBGR2101010 natively. Blending as * pre-multiplied alpha with a black background can be used as @@ -250,8 +444,8 @@ static void apple_plane_atomic_update(struct drm_plane *plane, .stride = fb->pitches[0], .width = fb->width, .height = fb->height, - .buf_size = fb->height * fb->pitches[0], .surface_id = plane->base.id, + .buf_size = buf_size, /* Only used for compressed or multiplanar surfaces */ .pix_size = 1, @@ -259,30 +453,51 @@ static void apple_plane_atomic_update(struct drm_plane *plane, .pel_h = 1, .has_comp = 1, .has_planes = 1, + .has_compr_info = 1, }; /* Populate plane information for planar formats */ struct dcp_surface *surf = &new_state->surf; for (int i = 0; fb->format->num_planes && i < fb->format->num_planes; i++) { - u32 width = drm_format_info_plane_width(fb->format, fb->width, i); - u32 height = drm_format_info_plane_height(fb->format, fb->height, i); - u32 bh = drm_format_info_block_height(fb->format, i); - u32 bw = drm_format_info_block_width(fb->format, i); + const struct apple_plane_layout *p = &layouts[i]; + const struct dcp_image_layout *layout = &p->image; surf->planes[i] = (struct dcp_plane_info){ - .width = width, - .height = height, - .base = fb->offsets[i] - fb->offsets[0], - .offset = fb->offsets[i] - fb->offsets[0], - .stride = fb->pitches[i], - .size = height * fb->pitches[i], - .tile_size = bw * bh, - .tile_w = bw, - .tile_h = bh, + .width = p->width, + .height = p->height, + .base = p->offset, + .offset = p->offset, + .tile_w = layout->tile_w, + .tile_h = layout->tile_h, + .stride = p->stride, + .size = p->size, + .tile_size = p->tile_size, }; - if (i > 0) - surf->buf_size += surf->planes[i].size; + switch (fb->modifier) { + case DRM_FORMAT_MOD_APPLE_INTERCHANGE: + surf->planes[i].address_fmt = DCP_ADDR_FMT_INTERCHANGE_TILED; + + surf->compression_info[i] = (struct dcp_compression_info) { + .tile_w = layout->tile_w, + .tile_h = layout->tile_h, + .data_offset = surf->planes[i].offset, + .metadata_offset = surf->planes[i].offset + layout->meta_offset, + .meta_bytes = layout->meta_tile_bytes, + .tiles_w = layout->width_tiles, + .tiles_h = layout->height_tiles, + .tile_bytes = layout->tile_bytes, + .row_stride = p->stride, + .compression_type = DCP_COMPRESSION_INTERCHANGE, + }; + break; + case DRM_FORMAT_MOD_INVALID: + case DRM_FORMAT_MOD_LINEAR: + surf->planes[i].address_fmt = DCP_ADDR_FMT_LINEAR; + break; + default: + break; + } } /* the obvious helper call drm_fb_dma_get_gem_addr() adjusts @@ -400,6 +615,7 @@ static const struct drm_plane_funcs apple_plane_funcs = { .reset = apple_plane_reset, .atomic_duplicate_state = apple_plane_duplicate_state, .atomic_destroy_state = apple_plane_destroy_state, + .format_mod_supported = apple_plane_format_mod_supported, }; /* @@ -414,6 +630,7 @@ static const struct drm_plane_funcs apple_plane_funcs = { * advertise formats without alpha. */ static const u32 dcp_primary_formats[] = { + DRM_FORMAT_ABGR16161616F, DRM_FORMAT_XRGB2101010, DRM_FORMAT_ARGB2101010, DRM_FORMAT_XRGB8888, @@ -427,6 +644,11 @@ static const u32 dcp_primary_formats[] = { DRM_FORMAT_P210, #if defined(DRM_FORMAT_P410) DRM_FORMAT_P410, +#endif + DRM_FORMAT_P030, + DRM_FORMAT_P230, +#if defined(DRM_FORMAT_P430) + DRM_FORMAT_P430, #endif }; @@ -448,6 +670,7 @@ static const u32 dcp_primary_formats_h17p[] = { }; static const u32 dcp_overlay_formats[] = { + DRM_FORMAT_ABGR16161616F, DRM_FORMAT_ARGB2101010, DRM_FORMAT_ARGB8888, DRM_FORMAT_ABGR8888, @@ -458,6 +681,11 @@ static const u32 dcp_overlay_formats[] = { DRM_FORMAT_P210, #if defined(DRM_FORMAT_P410) DRM_FORMAT_P410, +#endif + DRM_FORMAT_P030, + DRM_FORMAT_P230, +#if defined(DRM_FORMAT_P430) + DRM_FORMAT_P430, #endif }; @@ -492,7 +720,13 @@ static const u32 dcp_overlay_formats_12_x[] = { #endif }; -u64 apple_format_modifiers[] = { +static u64 format_modifiers[] = { + DRM_FORMAT_MOD_APPLE_INTERCHANGE, + DRM_FORMAT_MOD_LINEAR, + DRM_FORMAT_MOD_INVALID +}; + +static u64 format_modifiers_no_ix[] = { DRM_FORMAT_MOD_LINEAR, DRM_FORMAT_MOD_INVALID }; @@ -502,7 +736,8 @@ struct drm_plane *apple_plane_init(struct drm_device *dev, u32 iomfb_surf, bool supports_l10r, bool supports_xrgb2101010, - enum drm_plane_type type) + enum drm_plane_type type, + bool interchange) { struct apple_plane *plane; const u32 *fmts; @@ -522,7 +757,8 @@ struct drm_plane *apple_plane_init(struct drm_device *dev, } plane = drmm_universal_plane_alloc(dev, struct apple_plane, base, possible_crtcs, &apple_plane_funcs, fmts, num_fmts, - apple_format_modifiers, type, NULL); + interchange ? format_modifiers : format_modifiers_no_ix, + type, NULL); break; case DRM_PLANE_TYPE_OVERLAY: case DRM_PLANE_TYPE_CURSOR: @@ -535,7 +771,8 @@ struct drm_plane *apple_plane_init(struct drm_device *dev, } plane = drmm_universal_plane_alloc(dev, struct apple_plane, base, possible_crtcs, &apple_plane_funcs, fmts, num_fmts, - apple_format_modifiers, type, NULL); + interchange ? format_modifiers : format_modifiers_no_ix, + type, NULL); break; default: return ERR_PTR(-EINVAL); @@ -579,7 +816,7 @@ struct drm_plane *apple_plane_init_v14_7(struct drm_device *dev, plane = drmm_universal_plane_alloc(dev, struct apple_plane, base, possible_crtcs, &apple_plane_funcs, dcp_primary_formats_14_7, ARRAY_SIZE(dcp_primary_formats_14_7), - apple_format_modifiers, type, NULL); + format_modifiers_no_ix, type, NULL); if (IS_ERR(plane)) return ERR_CAST(plane); diff --git a/drivers/gpu/drm/apple/plane.h b/drivers/gpu/drm/apple/plane.h index ebb2420bf4041d..d7905573276f42 100644 --- a/drivers/gpu/drm/apple/plane.h +++ b/drivers/gpu/drm/apple/plane.h @@ -37,7 +37,8 @@ struct drm_plane *apple_plane_init(struct drm_device *dev, u32 iomfb_surf, bool supports_l10r, bool supports_xrgb2101010, - enum drm_plane_type type); + enum drm_plane_type type, + bool interchange); struct drm_plane *apple_plane_init_v14_7(struct drm_device *dev, unsigned long possible_crtcs, u32 iomfb_surf, diff --git a/drivers/gpu/drm/apple/v14-board-test.c b/drivers/gpu/drm/apple/v14-board-test.c index aa95cd2580857a..801ed2f623a4c5 100644 --- a/drivers/gpu/drm/apple/v14-board-test.c +++ b/drivers/gpu/drm/apple/v14-board-test.c @@ -73,13 +73,39 @@ static void v14_board_j516c(struct kunit *test) KUNIT_EXPECT_EQ(test, b->ctm_get, 0); } -/* A T6031 DCP on another board, or on a T6034, has no record: refused. */ -static void v14_board_t6031_other_boards(struct kunit *test) +/* + * The J514C: the same T6031 DCP and image, the panel from the boot + * framebuffer, the first boots logged. + */ +static void v14_board_j514c(struct kunit *test) { + const struct dcp_v14_board *b; bool known; - KUNIT_EXPECT_NULL(test, board_for("apple,t6031-dcp", j514c, &known)); + b = board_for("apple,t6031-dcp", j514c, &known); + KUNIT_ASSERT_NOT_NULL(test, b); KUNIT_EXPECT_TRUE(test, known); + KUNIT_EXPECT_STREQ(test, b->name, "J514C"); + KUNIT_EXPECT_STREQ(test, b->debugfs, "dcp-j514c"); + KUNIT_EXPECT_STREQ(test, b->machine, "apple,j514c"); + KUNIT_EXPECT_STREQ(test, b->handoff, "apple,t6031-handoff"); + KUNIT_EXPECT_STREQ(test, b->firmware_uuid, J516C_DCP_IMAGE); + KUNIT_EXPECT_EQ(test, b->panel_width, 0); + KUNIT_EXPECT_EQ(test, b->panel_height, 0); + KUNIT_EXPECT_TRUE(test, b->promotion); + KUNIT_EXPECT_TRUE(test, b->log_bringup); + KUNIT_EXPECT_EQ(test, b->ctm_set, 0); + KUNIT_EXPECT_TRUE(test, dcp_v14_board_admits(b, J516C_DCP_IMAGE)); + KUNIT_EXPECT_FALSE(test, dcp_v14_board_admits(b, T6030_DCP_IMAGE)); + /* Not the J516C record. */ + KUNIT_EXPECT_PTR_NE(test, b, board_for("apple,t6031-dcp", j516c, &known)); +} + +/* A T6031 DCP on a T6034 has no record: refused. */ +static void v14_board_t6031_other_boards(struct kunit *test) +{ + bool known; + KUNIT_EXPECT_NULL(test, board_for("apple,t6031-dcp", j516m, &known)); KUNIT_EXPECT_TRUE(test, known); /* Not a 14.x internal DCP at all. */ @@ -150,6 +176,7 @@ static void v14_board_unchanged(struct kunit *test) static struct kunit_case v14_board_cases[] = { KUNIT_CASE(v14_board_j516c), + KUNIT_CASE(v14_board_j514c), KUNIT_CASE(v14_board_t6031_other_boards), KUNIT_CASE(v14_board_j516c_image), KUNIT_CASE(v14_board_unchanged), diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index 4281f72993baeb..958600a91b06bd 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -35,3 +35,18 @@ config DRM_ASAHI_DEBUG_ALLOCATOR Say N unless you are debugging firmware structures or porting to a new firmware version. + +config DRM_ASAHI_G15 + bool "Native G15 firmware backend (M3 Pro/Max)" + depends on DRM_ASAHI + depends on DRM_APPLE=y || (DRM_APPLE=m && DRM_ASAHI=m) + select APPLE_T6030_GPU_PMP_LINK + select CRYPTO_LIB_SHA256 + default n + help + Enable the native G15 backend for explicitly admitted M3 Pro/Max + firmware and boards. Other GPUs keep the maintained backend. + The firmware session is retained until reboot once started. + The native display driver must be built in, or both drivers must + be modules, so a modular display provider finishes initialization + before the GPU module can probe through its direct helper import. diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index a3aff32eea1608..e1987914e0956e 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -2,3 +2,5 @@ obj-$(CONFIG_DRM_ASAHI) += asahi.o asahi-y := asahi_core.o sysfs.o + +asahi-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 4dca72fb85dc07..73a798fc69c00c 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -15,6 +15,8 @@ mod float; mod fw; mod gem; mod g17; +#[cfg(CONFIG_DRM_ASAHI_G15)] +mod g15; mod gpu; mod hw; mod initdata; @@ -36,12 +38,21 @@ mod workqueue; use kernel::prelude::*; +#[cfg(CONFIG_DRM_ASAHI_G15)] +type G15Registration = + kernel::driver::Registration>>; + #[pin_data] struct DriverModule { + #[cfg(CONFIG_DRM_ASAHI_G15)] + #[pin] + _g15: G15Registration, // Field drop order unregisters/joins driver producers before queue teardown. #[pin] _driver: kernel::driver::Registration>, _cleanup: cleanup::QueueOwner, + #[cfg(CONFIG_DRM_ASAHI_G15)] + _g15_ready: (), } impl kernel::InPlaceModule for DriverModule { @@ -49,10 +60,15 @@ impl kernel::InPlaceModule for DriverModule { try_pin_init!(Self { // Initialize the queue first, before registration can invoke probe. _cleanup: cleanup::QueueOwner::new()?, + #[cfg(CONFIG_DRM_ASAHI_G15)] + _g15 <- kernel::driver::Registration::new(c"asahi-g15", module), _driver <- kernel::driver::Registration::new( ::NAME, module, ), + // All fallible fields are initialized. This final unit initializer cannot fail. + #[cfg(CONFIG_DRM_ASAHI_G15)] + _g15_ready: g15::activate(), }) } } @@ -87,6 +103,50 @@ module! { // permissions: 0o644, description: "Fully isolate GPU contexts (limits performance)", }, + g15_deadline_ms: u32 { + default: 5000, + description: "G15: host deadline of a published prefix without progress, ms (min 100)", + }, + g15_compute_deadline_ms: u32 { + default: 1000, + description: "G15: no-progress budget of a started compute before the class-2 kill, ms", + }, + g15_repoll_us: u32 { + default: 15, + description: "G15: repoll interval while a ready prefix waits for record consumption, us (5..100)", + }, + g15_resnap_us: u32 { + default: 100, + description: "G15: completion repoll interval, us (25..1000)", + }, + g15_idle_standby_us: u32 { + default: 0, + description: "G15: firmware idle standby time override, us (Globals +0x7a8, 100..100000; 0: the device tree's, else the tuned value)", + }, + g15_idle_min_conf: u32 { + default: 500, + description: "G15: firmware idle minimum confidence, permille (Globals +0x7c4)", + }, + g15_recovery: u32 { + default: 1, + description: "G15: answer firmware halts with the halt/resume handshake (0: fail-stop)", + }, + g15_stream_gate: u32 { + default: 1, + description: "G15: admit only known CDM/VDM stream records (0: bring-up only)", + }, + g15_pb_max_blocks: u32 { + default: 3072, + description: "G15: parameter-buffer growth maximum given to the firmware, blocks of 128 KiB (1024..4095 in effect; the blocks above it, up to 4095, answer partial renders; the 512 MiB heap is allocated either way)", + }, + g15_early_tiling: u32 { + default: 0, + description: "G15: advertise FRAGMENT_BARRIERS, mapped to early tiling (slower on 2419)", + }, + g15_accept_text_prefix: u64 { + default: 0, + description: "G15: admit an unpinned GPU firmware build whose TEXT SHA-256 starts with these 8 bytes (bring-up only)", + }, stats_export: u8 { default: 1, // permissions: 0, diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 510a70ba4f0bd9..c092595180cf89 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -182,10 +182,12 @@ kernel::of_device_table!( of::DeviceId::new(c"apple,agx-t8122"), ProbeConfig::M3(crate::m3::Chip::T8122) ), + #[cfg(not(CONFIG_DRM_ASAHI_G15))] ( of::DeviceId::new(c"apple,agx-t6030"), ProbeConfig::M3(crate::m3::Chip::T6030) ), + #[cfg(not(CONFIG_DRM_ASAHI_G15))] ( of::DeviceId::new(c"apple,agx-t6031"), ProbeConfig::M3(crate::m3::Chip::T6031) @@ -305,6 +307,33 @@ impl platform::Driver for AsahiPlatformDriver { } impl AsahiPlatformDriver { + #[cfg(CONFIG_DRM_ASAHI_G15)] + pub(crate) fn probe_g15<'bound>( + pdev: &'bound platform::Device>, + cfg: &'static crate::g15::Config, + ) -> Result> { + // SAFETY: Admission checks the SoC and the UAT output width before DMA starts. + unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; + let resources = regs::Resources::new(pdev)?; + let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; + let gpu = crate::g15::Gpu::new(pdev, &drm, cfg)?; + let data = try_pin_init!(AsahiDrmRegistrationData { + gpu: gpu as Arc, + resources, + }); + // SAFETY: The registration is stored and unregistered by platform data destruction. + // G15 retains its firmware-visible state independently until reboot, even on error. + let reg = unsafe { drm::Registration::new(pdev.as_ref(), drm, data, 0)? }; + Ok(AsahiPlatformDriverData { + _device: reg.device().into(), + _reg: reg, + g17: None, + raw_dev: core::ptr::null_mut(), + raw_stats: core::ptr::null_mut(), + stats: None, + }) + } + fn probe_g17<'bound>( pdev: &'bound platform::Device>, cfg: &'static g17::Config, diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 49e5166092fd2b..608864949c976c 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -17,7 +17,6 @@ use crate::{ }, gem, mmu, - module_parameters, queue, util::{ align, @@ -252,7 +251,7 @@ impl drm::file::DriverFile for File { device.registration_data_with(|reg_data| { let gpu = ®_data.gpu; let id = gpu.ids().file.next(); - let user_range = gpu.uat_geometry().user_usable_range(); + let user_range = gpu.user_range(); mod_dev_dbg!(device, "[File {}]: DRM device opened\n", id); Ok(KBox::pin_init(File::new(id, user_range), GFP_KERNEL)?) @@ -374,17 +373,7 @@ impl File { gpu.get_params(&mut params)?; - if gpu.supports_vm_status() { - params.features |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 - | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS_MIRROR as u64; - } - if gpu.queue_limits().is_some() { - params.features |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES as u64; - } - - if *module_parameters::fault_control.value() == 0xb { - params.features |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SOFT_FAULTS as u64; - } + params.features |= gpu.feature_flags(); let size = core::mem::size_of::().min(data.size.try_into()?); @@ -577,7 +566,7 @@ impl File { /// IOCTL: vm_destroy: Destroy a `Vm`. pub(crate) fn vm_destroy( _device: &AsahiDrmDevice, - _reg_data: &driver::AsahiDrmRegistrationData<'_>, + reg_data: &driver::AsahiDrmRegistrationData<'_>, data: &mut uapi::drm_asahi_vm_destroy, file: &DrmFile, ) -> Result { @@ -585,6 +574,8 @@ impl File { if vm.is_none() { Err(ENOENT) } else { + drop(vm); + reg_data.gpu.vm_closed(); Ok(0) } } @@ -592,7 +583,7 @@ impl File { /// IOCTL: gem_create: Create a new GEM object. pub(crate) fn gem_create( device: &AsahiDrmDevice, - _reg_data: &driver::AsahiDrmRegistrationData<'_>, + reg_data: &driver::AsahiDrmRegistrationData<'_>, data: &mut uapi::drm_asahi_gem_create, file: &DrmFile, ) -> Result { @@ -629,6 +620,9 @@ impl File { let gem = gem::new_object(device, data.size.try_into()?, data.flags, resv_obj, reclaim_cpu)?; + if reg_data.gpu.prepare_new_objects() { + gem::prepare_new_object(&gem)?; + } let handle = gem.create_handle(file)?; data.handle = handle; @@ -704,7 +698,13 @@ impl File { return Err(EINVAL); } - if reg_data.gpu.as_any().is::() { + if let Some(limit) = reg_data.gpu.bind_batch_limit() { + if data.num_binds == 0 || data.num_binds > limit || data.userptr == 0 + || data.stride % 8 != 0 || data.stride as usize > kernel::page::PAGE_SIZE { + return Err(EINVAL); + } + } + if reg_data.gpu.as_any().is::() || reg_data.gpu.tracked_submission() { return Self::vm_bind_g17(data, file); } @@ -1284,7 +1284,7 @@ impl File { .reader() .read_all(bytes, GFP_KERNEL) }; - let guarded = gpu.as_any().is::(); + let guarded = gpu.as_any().is::() || gpu.tracked_submission(); // Once G17 output syncobjs are resolved, its queue must install a fence // on every failure. Take the fallible userspace snapshot before that point. if guarded { diff --git a/drivers/gpu/drm/asahi/g15/SOURCES.json b/drivers/gpu/drm/asahi/g15/SOURCES.json new file mode 100644 index 00000000000000..13deae13107361 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/SOURCES.json @@ -0,0 +1,229 @@ +{ + "schema": 1, + "source_pins": { + "target": "10ff0fe408d83936d6c7783b0382a3092e520ea5", + "pr148": "ee4f0f3ee2958ddc0243bb5e71a0bea88215d01b", + "sf": "65cd54ba0da8f93e4530f851382ccb5187ab794c" + }, + "scope": "Public native G15 subtree only. No private notes, whole-driver replacement, global UAPI selector, display/PMGR/memory-floor policy or branding.", + "source_carries": [ + { + "source": "04795f0d9600a3a695b3bd96fdb023720bea2883", + "commit": "54f7d6904f8d935781b79b7175b556b1ceeb9619", + "author": "Eryk Wieliczko", + "note": "G15 subtree snapshot including the preceding firmware/engine/recovery commits a8b817ef0614,39e7cf0bfdaa,01812cc4894f; no shared APIs or display/PMP policy imported." + }, + { + "source": "d8422e044e37f5d366422b2f37db8571fa64d11b", + "commit": "41275bfd985b7ccbcad6cb6650d94696fb0b29c3", + "author": "Naeem Malik", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "7c2857681b843ddab2c66abc8c04d12746efcba4", + "commit": "1f28f12c5e11608a8d7694d3b8db8a867f058f45", + "author": "Naeem Malik", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "0c98b7e731e8c42189593d7b9b9835785e4f6b07", + "commit": "bcb43bb61412df2808079f05fa684938c5e26528", + "author": "Naeem Malik", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "d3283ae4798ebd8c5e0de418dcbe9adb5b09327d", + "commit": "9538af3d5d3911ddd4762e7cc3b026180e193a88", + "author": "Naeem Malik", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "2a2def4ae6625d4a09d0cc944fc72b6682a2cf0c", + "commit": "e3d7591ae5f8135a4a3915c76cc849fcc1c2c996", + "author": "Naeem Malik", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "b091ba71dfe11dc66c83542131420027f1a13281", + "commit": "4d38ccc69d4781336ce5263f32365436abe35c2c", + "author": "Naeem Malik", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "ad229034eb4300fcbfe40c658d22f38f34454438", + "commit": "113194ca413fc0b05c2ffd5e7d26ab4c5224baf5", + "author": "DjDeveloperr", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "fa62b3345de5d8887201d3750e4f8ecc83a20778", + "commit": "369360537e628e7b04ebf24ac1d2a90786cf6c89", + "author": "DjDeveloperr", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "0da467881effc823ee51616f361c2e446b540cf5", + "commit": "2371dbf829c408917d6b4c52095931c0166a5331", + "author": "DjDeveloperr", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "897412529e3941f99e159a2585f2574179b38307", + "commit": "d9f1f541cd7ab5a5f01b60d9523c6e51db1113b1", + "author": "DjDeveloperr", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "90dc887b72d791809cfc8e2b92fcf42a186cf716", + "commit": "b58306ce0518bf0982166e3acfcce8661eb8d852", + "author": "DjDeveloperr", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "ee4f0f3ee2958ddc0243bb5e71a0bea88215d01b", + "commit": "2cdad45526fb46273dcd03474c3ab074eb97af7d", + "author": "DjDeveloperr", + "note": "G15 subtree only; shared layers and registration adapted separately." + }, + { + "source": "0fcf28d2cd305c6622475a01b81b334adf65a422", + "commit": "1903ae11e30a93f39fa39c0172cb5b3022e12ccb", + "author": "Chris Kearney", + "note": "G15 subtree only from the public native-profile bridge. Includes existing maintained loader/PMP admission adaptations 9333b0728dc4,674fd94f0b20,19cebe363276,d68cf5c0040f and c70e30b60623; no Rust API or global profile/header switch imported." + }, + { + "source": "16a4b74b0d7912cbb174c0a4c4503776391ccf8a", + "commit": "029d221c3d49284f593198165befb74a892baf39", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "d3b664b79b70f099630f48437af134682a1b11d7", + "commit": "1426152ddedbecc3766942256810560163522980", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "52705c9919c94bcd86a7278ef4b99c150f26c0b5", + "commit": "be6a5b4303fb1403c70c666aa98e06fb24109baa", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "c77b143bc5161fa19354aeb9dd3ae6f323e6d851", + "commit": "2173a9adef3f0eb7eb3111c6faafca4286dd0eee", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "1a49fbfaafff0c9693bfbe3d1847305725d6787b", + "commit": "45953c21d0f3711f629c9f332ca37adaa13416ef", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "ca6e846e41e364f343257de50a0fdce7a2ed4586", + "commit": "a63a953ee1d887bb339bbd4d29121aedf6949eb2", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "ea93a3d4d2ff7c8bc24fe4796b98fc7ba9627072", + "commit": "bf160c16ec91df92f9b1442724010ad4595feb41", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "186c30e76a428ca80197fa91444fbb44a7712f79", + "commit": "6a1c99e7b960305fae441f20f2bcd95ae4eca80d", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "20d359950d0c981e762fbb43c315866fc86c271b", + "commit": "1d769b3d9f606505230a5780f14930cf40269025", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "bec6e4f83afd815b38803e754333b8954ce7bc29", + "commit": "5c597f936e919a31db34aa74a9a7782522f31c2b", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "3be092a24989523cab10253243981ab32c92193a", + "commit": "5c490e10e442cca145bc3a9847bd6d14982cc5b3", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "2c8d031fccc0ce4b125318dc011884de342325c7", + "commit": "fea7b79a3aa5c41799ba8a3410616a7d51d06c9f", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "d0fc3c53d90f0be24644c0f3d8e3ba46bf9a0e0d", + "commit": "4b7929dfe546b9ae829458051350d07b1d1d3fe1", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "e2a97e967bea7b45c02801fa9afc4ae450be5a40", + "commit": "77528f1df378237950a3a6f85c9021b0129a4523", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "1a16318bc89c0658152405a3f587436b06c15157", + "commit": "44fdda4028002d93514879505903cf6cc8e02240", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "dba2a110de00743eeecd41edf23e54ede4491d5e", + "commit": "571e1d0c9da42d15fd7b4a023fb84cefde0904c0", + "author": "Naeem Malik", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "3d247356aa8a4ee5f50b24d3d6fd4afc89cf5c6f", + "commit": "f3893274d2a6d559be1b9d4e99c4f1294d2f3bbe", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "f3668549340d6cb9bb84f2bc5719b78abdf4b5bb", + "commit": "bc29e6b988e2d597b0c5338d8891dfd473901644", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "6fef6f3820ba34a2c2cbd0b0ee95ec473def4ffc", + "commit": "83aa75f592b015fb940109ee7578c674999348c6", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "d5317ea1542d42382a7d6e3dbcdc3d611d5c5237", + "commit": "1d1702b49ef6a72062da37c1fa98f6cb72fb8fdf", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + }, + { + "source": "9e67aed169c3cc6a0388d0184d8db76936299385", + "commit": "c739064a9d1a7c388ae8bb74dde4ee099b374b68", + "author": "Chris Kearney", + "note": "G15 subtree hunks only; asahi-m3 path becomes maintained asahi/g15; tests carried in the dedicated test adaptation." + } + ], + "adaptation_notes": { + "registration": "Separate no-alias G15 adapter in the maintained asahi module; retained failed probe and manual-unbind suppression. Existing normal/G17 paths kept.", + "drm": "Uses target RegistrationData and current DRM/GEM/GPUVM APIs; no Uninit conversion or forged registered context.", + "mmio": "G15 retained Mapping owns its register windows; target regs::Resources remains borrowed by RegistrationData.", + "sg_table": "Target held_sg_table permanently pins backing and owns SG lifetime inside GEM; G15 HeldPages retains a GEM reference, not the removed owned-SG wrapper.", + "page_tables": "Only adopted G15 page tables enable point-of-coherency publication; normal/G17 default remains false.", + "wire": "Native per-device wire facade is separately supplied; canonical normal/G17 UAPI unchanged." + } +} diff --git a/drivers/gpu/drm/asahi/g15/adt.rs b/drivers/gpu/drm/asahi/g15/adt.rs new file mode 100644 index 00000000000000..aece4f083c0ad4 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/adt.rs @@ -0,0 +1,498 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The GPU regions, firmware segments and performance states: from the boot loader's ADT +//! export (T6030), or from the GPU device tree node the boot loader fills (T6031). +//! +//! # T6030: the ADT export +//! +//! The GPU node that the PMP/ADT handoff (`drivers/soc/apple/j514s-pmp-handoff.c`) synthesizes +//! has only `compatible = "apple,agx-t6030"`, `reg`/`reg-names` (`asc`, `sgx`), `mboxes`/ +//! `mbox-names` (`mbox`), `power-domains` and `apple,pmp`; it has no memory regions, operating +//! points or firmware-compat. Regions, segments and performance states come from the ADT: +//! `/reserved-memory` child `compatible = "phram"`, `label = "adt"` (16 KiB aligned, at most +//! 2 MiB; copied, never parsed in place). Properties: `/arm-io/sgx` `compatible == "gpu,t6030"`, +//! `{gpu-region,gfx-shared-region,gfx-handoff,gfx-shared-l2-region}-{base,size}`, +//! `perf-states`/`perf-states-sram` (14 x {u32 Hz, u32 mV}) and the fixed constants checked by +//! `collect_perf`; `/arm-io/gfx-asc` `segment-ranges` (2 x 32 bytes) and `segment-names` +//! (`__TEXT;__DATA`); `/arm-io/gfx-asc/iop-gfx-nub` `segment-ranges` (identical, length +//! checked too) and `pre-loaded == 1`; `/chosen` `dram-base`/`dram-size`. +//! Admission: every region page-aligned, inside DRAM and disjoint from the others; +//! TEXT at [`super::hw::UPPER`], DATA right after it. Firmware stays outside System RAM. +//! The maintained native-GPU profile also admits the four UAT regions as reserved RAM, +//! only with their exact enabled reserved-memory owners and every page PageReserved. +//! +//! # T6031: the device tree node +//! +//! The boot loader fills the kernel's GPU node from the machine's ADT: `memory-region` entries +//! `ttbs`, `pagetables`, `handoff` and `pagetables-l2` (the UAT regions), `fw-text` and +//! `fw-data` (the loaded segments, no-map), `apple,firmware-segment-vas` (their two VAs) and +//! the `operating-points-v2` table (one `opp-hz` per performance state, `opp-microvolt` with +//! one cell per cluster). The same admission applies, without the DRAM bounds, and the four UAT +//! regions may lie in System RAM: they are reserved-memory nodes without `no-map`, which the +//! kernel maps, so the driver reaches them through its own mapping ([`super::regs::Mapping`]). + +use core::ops::Range; +use kernel::{c_str, device, prelude::*}; + +use super::boot::glue; +use super::hw; + +/// Number of ADT performance states of the board-image layout. +pub(crate) const PERF_STATES: usize = 14; + +/// What the driver takes from the ADT. +pub(crate) struct GpuAdt { + /// TTBAT page. + pub(crate) ttbs: Range, + /// Firmware kernel root and its tables. + pub(crate) tables: Range, + /// PPL handoff page. + pub(crate) handoff: Range, + /// Shared L2 page: the table of root entry 2 (the host window). + pub(crate) shared_l2: Range, + /// Loaded firmware TEXT and DATA, physical. + pub(crate) text: Range, + pub(crate) data: Range, + /// Performance states: MHz, core mV, SRAM mV. + pub(crate) perf_mhz: [u32; PERF_STATES], + pub(crate) perf_mv: [u32; PERF_STATES], + pub(crate) sram_mv: [u32; PERF_STATES], + /// Per-cluster core mV of each state, rounded up from the device tree's microvolts, how + /// many voltage cells the node has (1 on the ADT path), and the state's power in mW (0 on + /// the ADT path). + pub(crate) cluster_mv: [[u32; CLUSTERS]; PERF_STATES], + pub(crate) cluster_cells: usize, + pub(crate) perf_mw: [u32; PERF_STATES], +} + +/// Voltage cells the layout keeps per state. +pub(crate) const CLUSTERS: usize = 4; + +/// A private copy of the ADT. +struct Adt<'a> { + data: &'a [u8], +} + +fn le32(b: &[u8], off: usize) -> Option { + Some(u32::from_le_bytes(b.get(off..off + 4)?.try_into().ok()?)) +} + +fn le64(b: &[u8], off: usize) -> Option { + Some(u64::from_le_bytes(b.get(off..off + 8)?.try_into().ok()?)) +} + +/// `strncmp(a, b, n) == 0` for a byte field `a` and a string `b`, both treated as +/// NUL-terminated (bytes past the end of either count as NUL). +fn strncmp_eq(a: &[u8], b: &str, n: usize) -> bool { + let b = b.as_bytes(); + for i in 0..n { + let x = a.get(i).copied().unwrap_or(0); + let y = b.get(i).copied().unwrap_or(0); + if x != y { + return false; + } + if x == 0 { + return true; + } + } + true +} + +impl Adt<'_> { + /// Returns the end of the node at `off`, or `None` on a malformed node. + fn node_end(&self, mut off: usize, depth: u32) -> Option { + let size = self.data.len(); + if depth > 32 || off > size || size - off < 8 { + return None; + } + let props = le32(self.data, off)?; + let children = le32(self.data, off + 4)?; + if props > 4096 || children > 1024 { + return None; + } + off += 8; + for _ in 0..props { + if size - off < 36 { + return None; + } + let len = (le32(self.data, off + 32)? & 0x7fffffff) as usize; + off += 36; + if len > size - off { + return None; + } + off += len.next_multiple_of(4); + if off > size { + return None; + } + } + for _ in 0..children { + off = self.node_end(off, depth + 1)?; + } + Some(off) + } + + /// The value of property `name` of `node`. + fn prop(&self, node: usize, name: &str) -> Option<&[u8]> { + let props = le32(self.data, node)?; + let mut off = node + 8; + for _ in 0..props { + let len = (le32(self.data, off + 32)? & 0x7fffffff) as usize; + if strncmp_eq(self.data.get(off..off + 32)?, name, 32) { + return self.data.get(off + 36..off + 36 + len); + } + off += 36 + len.next_multiple_of(4); + } + None + } + + /// The child named `name` of `node`. + fn child(&self, node: usize, name: &str) -> Option { + let props = le32(self.data, node)?; + let children = le32(self.data, node + 4)?; + let mut off = node + 8; + for _ in 0..props { + off += 36 + ((le32(self.data, off + 32)? & 0x7fffffff) as usize).next_multiple_of(4); + } + for _ in 0..children { + if let Some(n) = self.prop(off, "name") { + if !n.is_empty() && strncmp_eq(n, name, n.len()) { + return Some(off); + } + } + off = self.node_end(off, 1)?; + } + None + } + + fn u64(&self, node: usize, name: &str) -> Option { + let p = self.prop(node, name)?; + if p.len() != 8 { + return None; + } + le64(p, 0) + } + + fn u32(&self, node: usize, name: &str) -> Option { + let p = self.prop(node, name)?; + if p.len() != 4 { + return None; + } + le32(p, 0) + } +} + +/// This machine's GPU performance states (per-chip binning): ADT sgx `perf-states` and +/// `perf-states-sram`, (frequency Hz, millivolt) pairs. The board-image layout implements one +/// table shape; another shape is refused. Values the board-image layout takes as given are +/// compared, not trusted. +fn collect_perf(dev: &device::Device, adt: &Adt<'_>, sgx: usize, out: &mut GpuAdt) -> Result { + const FIXED: [(&str, u32); 5] = [ + ("perf-state-count", PERF_STATES as u32), + ("gpu-num-perf-states", PERF_STATES as u32 - 1), + ("perf-state-table-count", 1), + ("gpu-power-sample-period", 8), + ("gpu-pwr-sample-period-aic-clks", 200000), + ]; + for (name, value) in FIXED { + if adt.u32(sgx, name) != Some(value) { + dev_err!(dev, "ADT sgx {} is not the supported {}\n", name, value); + return Err(EINVAL); + } + } + let (Some(core), Some(sram)) = ( + adt.prop(sgx, "perf-states"), + adt.prop(sgx, "perf-states-sram"), + ) else { + dev_err!(dev, "ADT perf-state tables missing or of another shape\n"); + return Err(EINVAL); + }; + if core.len() != 8 * PERF_STATES || sram.len() != core.len() { + dev_err!(dev, "ADT perf-state tables missing or of another shape\n"); + return Err(EINVAL); + } + for i in 0..PERF_STATES { + let hz = le32(core, 8 * i).ok_or(EINVAL)?; + if le32(sram, 8 * i) != Some(hz) + || hz % 1000000 != 0 + || hz > 3000000000 + || ((i == 0) != (hz == 0)) + { + dev_err!(dev, "ADT perf-state {} ({} Hz) not usable\n", i, hz); + return Err(EINVAL); + } + out.perf_mhz[i] = hz / 1000000; + out.perf_mv[i] = le32(core, 8 * i + 4).ok_or(EINVAL)?; + out.sram_mv[i] = le32(sram, 8 * i + 4).ok_or(EINVAL)?; + if !(100..=1100).contains(&out.perf_mv[i]) || !(100..=1100).contains(&out.sram_mv[i]) { + dev_err!( + dev, + "ADT perf-state {} voltage {}/{} mV out of range\n", + i, + out.perf_mv[i], + out.sram_mv[i] + ); + return Err(EINVAL); + } + } + Ok(()) +} + +/// Region names of the admission messages. +const REGION_NAMES: [&str; 6] = ["ttbs", "tables", "handoff", "shared-l2", "text", "data"]; + +/// Parses the private ADT copy. +fn parse(dev: &device::Device, adt: &Adt<'_>) -> Result { + const PROPS: [(&str, &str); 4] = [ + ("gpu-region-base", "gpu-region-size"), + ("gfx-shared-region-base", "gfx-shared-region-size"), + ("gfx-handoff-base", "gfx-handoff-size"), + ("gfx-shared-l2-region-base", "gfx-shared-l2-region-size"), + ]; + if adt.node_end(0, 0).is_none() { + return Err(EINVAL); + } + let armio = adt.child(0, "arm-io").ok_or(EINVAL)?; + let sgx = adt.child(armio, "sgx").ok_or(EINVAL)?; + let asc = adt.child(armio, "gfx-asc").ok_or(EINVAL)?; + let nub = adt.child(asc, "iop-gfx-nub").ok_or(EINVAL)?; + let compatible = adt.prop(sgx, "compatible").ok_or(EINVAL)?; + let nul = compatible.iter().position(|&b| b == 0).ok_or(EINVAL)?; + if &compatible[..nul] != b"gpu,t6030" { + return Err(EINVAL); + } + let mut region: [Range; 6] = Default::default(); + for (i, (base_key, size_key)) in PROPS.iter().enumerate() { + let base = adt.u64(sgx, base_key).ok_or(EINVAL)?; + let size = adt.u64(sgx, size_key).ok_or(EINVAL)?; + region[i] = base..base.checked_add(size).ok_or(EINVAL)?; + } + let ranges = adt.prop(asc, "segment-ranges").ok_or(EINVAL)?; + let nub_ranges = adt.prop(nub, "segment-ranges").ok_or(EINVAL)?; + let names = adt.prop(asc, "segment-names").ok_or(EINVAL)?; + // Both range tables must be exactly 2 x 32 bytes and identical. + if ranges.len() != 64 || nub_ranges.len() != 64 || ranges != nub_ranges { + return Err(EINVAL); + } + if !strncmp_eq(names, "__TEXT;__DATA", names.len()) { + return Err(EINVAL); + } + let preloaded = adt.prop(nub, "pre-loaded").ok_or(EINVAL)?; + if preloaded.len() != 4 || le32(preloaded, 0) != Some(1) { + return Err(EINVAL); + } + let mut va = [0u64; 2]; + for i in 0..2 { + let r = &ranges[32 * i..32 * i + 32]; + let pa = le64(r, 0).ok_or(EINVAL)?; + va[i] = le64(r, 8).ok_or(EINVAL)?; + if le64(r, 0x10) != Some(pa) || le32(r, 0x1c) != Some(if i != 0 { 0 } else { 1 }) { + return Err(EINVAL); + } + let size = le32(r, 0x18).ok_or(EINVAL)? as u64; + region[4 + i] = pa..pa.checked_add(size).ok_or(EINVAL)?; + } + // Firmware ABI: TEXT at the base of the upper half, DATA right after it. + let text_size = region[4].end - region[4].start; + if va[0] != hw::UPPER || va[1] != va[0] + text_size { + return Err(EINVAL); + } + let chosen = adt.child(0, "chosen"); + let dram = chosen + .and_then(|chosen| Some((adt.u64(chosen, "dram-base")?, adt.u64(chosen, "dram-size")?))); + let Some((dram_base, dram_size)) = + dram.filter(|&(base, size)| size != 0 && base.checked_add(size).is_some()) + else { + dev_err!(dev, "ADT DRAM bounds unreadable\n"); + return Err(EINVAL); + }; + // The maintained loader deliberately retains the UAT's linear mapping. + // Cross-check every ADT range against its exact enabled FDT reservation; + // admit_regions still rejects holes, allocator-owned pages and overlaps. + for (i, r) in region[..4].iter().enumerate() { + if !glue::reserved_uat(i as u32, r.start, r.end - r.start) { + dev_err!(dev, "GPU UAT {} has no matching boot reservation\n", REGION_NAMES[i]); + return Err(EINVAL); + } + } + admit_regions(dev, ®ion, Some(dram_base..dram_base + dram_size), true)?; + let [ttbs, tables, handoff, shared_l2, text, data] = region; + let mut out = GpuAdt { + ttbs, + tables, + handoff, + shared_l2, + text, + data, + perf_mhz: [0; PERF_STATES], + perf_mv: [0; PERF_STATES], + sram_mv: [0; PERF_STATES], + cluster_mv: [[0; CLUSTERS]; PERF_STATES], + cluster_cells: 1, + perf_mw: [0; PERF_STATES], + }; + collect_perf(dev, adt, sgx, &mut out)?; + for i in 0..PERF_STATES { + out.cluster_mv[i][0] = out.perf_mv[i]; + } + Ok(out) +} + +/// Structural admission of the six regions (same order as [`REGION_NAMES`]): page-aligned, +/// addressable, the fixed UAT sizes, disjoint from each other, and either outside System RAM +/// (the T6030 carveouts) or, with `reserved_ram` and for the four UAT regions only, lying +/// entirely in System RAM as reserved memory the GPU node names (the T6031 device tree). The +/// firmware segments are always outside System RAM. +fn admit_regions( + dev: &device::Device, + region: &[Range; 6], + dram: Option>, + reserved_ram: bool, +) -> Result { + let fixed = [ + hw::TTBS_SIZE, + hw::TABLES_SIZE, + hw::HANDOFF_SIZE, + hw::SHARED_L2_SIZE, + ]; + for i in 0..region.len() { + let r = ®ion[i]; + let size = r.end - r.start; + let end = r.end.wrapping_sub(1); + let outside_dram = match &dram { + Some(dram) => r.start < dram.start || end > dram.end - 1, + None => false, + }; + let placed = if reserved_ram && i < 4 { + glue::ram_disjoint(r.start, size) || glue::ram_within(r.start, size) + } else { + glue::ram_disjoint(r.start, size) + }; + if size == 0 + || (r.start | size) & (hw::PAGE - 1) != 0 + || end > (hw::PA_MASK | (hw::PAGE - 1)) + || outside_dram + || (i < 4 && size != fixed[i]) + || !placed + { + dev_err!( + dev, + "GPU region {} ({}) [mem {:#x}-{:#x}] not admissible\n", + i, + REGION_NAMES[i], + r.start, + end + ); + return Err(EINVAL); + } + for j in 0..i { + if r.start < region[j].end && region[j].start < r.end { + dev_err!(dev, "GPU regions {} and {} overlap\n", j, i); + return Err(EINVAL); + } + } + } + Ok(()) +} + +/// The GPU node's regions, segments and operating points (T6031). +fn from_device_tree(dev: &device::Device) -> Result { + const NAMES: [&CStr; 6] = [ + c_str!("ttbs"), + c_str!("pagetables"), + c_str!("handoff"), + c_str!("pagetables-l2"), + c_str!("fw-text"), + c_str!("fw-data"), + ]; + let node = dev.of_node().ok_or(ENODEV)?; + let mut region: [Range; 6] = Default::default(); + for (i, name) in NAMES.iter().enumerate() { + let r = node + .reserved_mem_region_to_resource_byname(name) + .inspect_err(|_| dev_err!(dev, "GPU node has no {} memory region\n", REGION_NAMES[i]))?; + let start = r.start() as u64; + let size = r.size() as u64; + region[i] = start..start.checked_add(size).ok_or(EINVAL)?; + } + // Firmware ABI: TEXT at the base of the upper half, DATA right after it. + let vas: KVec = node + .get_property(c_str!("apple,firmware-segment-vas")) + .inspect_err(|_| dev_err!(dev, "GPU node has no apple,firmware-segment-vas\n"))?; + let text_size = region[4].end - region[4].start; + if vas.len() != 2 || vas[0] != hw::UPPER || vas[1] != vas[0] + text_size { + dev_err!(dev, "GPU firmware segment VAs are not the firmware ABI's\n"); + return Err(EINVAL); + } + admit_regions(dev, ®ion, None, true)?; + let [ttbs, tables, handoff, shared_l2, text, data] = region; + let mut out = GpuAdt { + ttbs, + tables, + handoff, + shared_l2, + text, + data, + perf_mhz: [0; PERF_STATES], + perf_mv: [0; PERF_STATES], + sram_mv: [0; PERF_STATES], + cluster_mv: [[0; CLUSTERS]; PERF_STATES], + cluster_cells: 0, + perf_mw: [0; PERF_STATES], + }; + // Operating points: MHz, the highest cluster voltage of each and the clusters' voltages + // (rounded up) and power for the hardware record; the SRAM voltage is not in the device + // tree. + let opps = node + .parse_phandle(c_str!("operating-points-v2"), 0) + .ok_or(EINVAL) + .inspect_err(|_| dev_err!(dev, "GPU node has no operating points\n"))?; + let mut count = 0; + for opp in opps.children() { + let hz: u64 = opp.get_property(c_str!("opp-hz"))?; + let uv: KVec = opp.get_property(c_str!("opp-microvolt"))?; + let uw: Option = opp.get_opt_property(c_str!("opp-microwatt"))?; + let mv = uv.iter().max().copied().unwrap_or(0) / 1000; + if uv.is_empty() || uv.len() > CLUSTERS || (count > 0 && uv.len() != out.cluster_cells) { + dev_err!(dev, "GPU operating point {} has {} voltage cells\n", count, uv.len()); + return Err(EINVAL); + } + if count < PERF_STATES { + out.perf_mhz[count] = u32::try_from(hz / 1_000_000).map_err(|_| { + dev_err!(dev, "GPU operating point {} is {} Hz\n", count, hz); + EINVAL + })?; + out.perf_mv[count] = mv; + out.sram_mv[count] = mv; + for (c, v) in uv.iter().enumerate() { + out.cluster_mv[count][c] = v.div_ceil(1000); + } + out.cluster_cells = uv.len(); + out.perf_mw[count] = uw.unwrap_or(0) / 1000; + } + count += 1; + } + if count != PERF_STATES { + dev_err!( + dev, + "GPU node has {} operating points, not {}\n", + count, + PERF_STATES + ); + return Err(EINVAL); + } + Ok(out) +} + +/// Reads and admits the GPU's regions, segments and performance states (read-only), from the +/// source the SoC configuration names. +pub(crate) fn read(dev: &device::Device, cfg: &super::Config) -> Result { + if cfg.platform == hw::Platform::DeviceTree { + return from_device_tree(dev); + } + let (start, size) = glue::adt_phram()?; + if size == 0 || size > 0x200000 || start & 0x3fff != 0 { + return Err(EINVAL); + } + let copy = super::identity::copy_physical(start, usize::try_from(size)?)?; + parse(dev, &Adt { data: © }) +} diff --git a/drivers/gpu/drm/asahi/g15/board.rs b/drivers/gpu/drm/asahi/g15/board.rs new file mode 100644 index 00000000000000..da0a7408575bfb --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/board.rs @@ -0,0 +1,273 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Board-data templates of the supported firmware build. +//! +//! Sparse 16-byte-line images (HardwareData 35,332 B, Globals 15,868 B, Power 2,292 B), each +//! with its SHA-256: [`expand`] expands and verifies them, [`from_adt`] rebuilds DVFS tables A/B +//! from the ADT performance states (`DVFS_A` {0,1,2,3,5,7,9,11,13}, `DVFS_B` +//! {0,1,2,3,4,6,8,10,12}; MHz at +0xb5c, +0xf9c, +0x1350, core mV +0xb9c, SRAM mV +0xd9c, top +//! MHz +0x4dc4). The tables in [`data`] are generated, and every expanded image is checked +//! against its hash at boot. +//! +//! A SoC whose board data comes from its device tree ([`super::hw::Platform::DeviceTree`]) gets +//! its hardware record from [`hardware_record`] ([`record`]) and its Globals and Power from +//! [`device_tree`]: the G15S templates with the GPU node's power words and the hardware +//! record's maximum power ([`words`]). + +pub(crate) mod blob; +pub(crate) mod data; +pub(crate) mod record; +pub(crate) mod template; +pub(crate) mod words; + +use kernel::{c_str, device, prelude::*}; + +use super::adt::{self, GpuAdt}; +use super::boot::glue; +use super::fw::initdata::{globals, hwdata, power}; +use super::hw::{self, va}; +pub(crate) use template::{Line, Template}; + +static_assert!(words::GLOBALS_SIZE == globals::SIZE); +static_assert!(words::POWER_SIZE == power::SIZE); +static_assert!(words::HWDATA_A == hwdata::HWDATA_A); +static_assert!(words::HWDATA_A_MAX_POWER == hwdata::MAX_POWER_A); +static_assert!(words::TOP_STATE as usize == DVFS_STATES - 1); +static_assert!(record::HWDATA_A == hwdata::HWDATA_A); +static_assert!(record::MAX_POWER == hwdata::HWDATA_A + hwdata::MAX_POWER_A); +static_assert!(record::IOMAPS == hwdata::IOMAPS); +static_assert!(record::PERF_STATES == adt::PERF_STATES); +static_assert!(record::CLUSTERS == adt::CLUSTERS); + +/// Expands a template into `out` and verifies its hash. +pub(crate) fn expand(template: &Template, out: &mut [u8]) -> Result { + template::fill(template, out).map_err(|_| EINVAL)?; + if glue::sha256(&out[..template.size]) != template.sha256 { + return Err(EINVAL); + } + Ok(()) +} + +/// The GPU node's power words ([`words::PROPS`] and [`words::ZONES`]). +fn power_words(dev: &device::Device) -> Result { + let node = dev.of_node().ok_or(ENODEV)?; + let mut values = [0u32; words::PROPS.len()]; + for (value, name) in values.iter_mut().zip(words::PROPS.iter()) { + *value = node + .get_property(name) + .inspect_err(|_| dev_err!(dev, "GPU node has no u32 {}\n", name))?; + } + let zones: KVec = node.get_opt_property(words::ZONES)?.unwrap_or_default(); + words::PowerWords::new(values, &zones).map_err(|why| { + dev_err!(dev, "GPU node power words: {}\n", why); + EINVAL + }) +} + +/// A CS or AFR operating-point table of the GPU node (`name`): MHz and one voltage cell per +/// state, at most `max` states. +fn aux_opps( + dev: &device::Device, + node: &kernel::of::Node, + name: &CStr, + out: &mut [record::Opp], +) -> Result { + let table = node + .parse_phandle(name, 0) + .ok_or(EINVAL) + .inspect_err(|_| dev_err!(dev, "GPU node has no {}\n", name))?; + let mut n = 0; + for opp in table.children() { + let hz: u64 = opp.get_property(c_str!("opp-hz"))?; + let uv: KVec = opp.get_property(c_str!("opp-microvolt"))?; + if uv.len() != 1 || n >= out.len() { + dev_err!( + dev, + "GPU {} table: state {} has {} cells\n", + name, + n, + uv.len() + ); + return Err(EINVAL); + } + let mhz = u32::try_from(hz / 1_000_000).map_err(|_| { + dev_err!(dev, "GPU {} table: state {} is {} Hz\n", name, n, hz); + EINVAL + })?; + out[n] = record::Opp { + mhz, + mv: [uv[0].div_ceil(1000), 0, 0, 0], + cells: 1, + mw: 0, + }; + n += 1; + } + if n == 0 { + dev_err!(dev, "GPU {} table is empty\n", name); + return Err(EINVAL); + } + Ok(n) +} + +/// The hardware record of a device-tree SoC ([`record`]): built from the GPU node's properties +/// and operating-point tables, the layout's IOMapping table and the ADT regions, with the +/// words the device tree does not carry copied from `file`, the machine's own record. +pub(crate) fn hardware_record( + dev: &device::Device, + cfg: &super::Config, + adt: &GpuAdt, + file: &[u8], +) -> Result> { + let layout = cfg.layout; + let node = dev.of_node().ok_or(ENODEV)?; + let mut props = [0u32; record::PROPS.len()]; + for (value, (name, default)) in props.iter_mut().zip(record::PROPS.iter()) { + *value = match node.get_opt_property(name)? { + Some(v) => v, + None => default + .ok_or(EINVAL) + .inspect_err(|_| dev_err!(dev, "GPU node has no u32 {}\n", name))?, + }; + } + let zones: KVec = node.get_opt_property(words::ZONES)?.unwrap_or_default(); + let mut main = [record::Opp::default(); record::PERF_STATES]; + for (i, o) in main.iter_mut().enumerate() { + *o = record::Opp { + mhz: adt.perf_mhz[i], + mv: adt.cluster_mv[i], + cells: adt.cluster_cells, + mw: adt.perf_mw[i], + }; + } + let mut cs = [record::Opp::default(); 16]; + let mut afr = [record::Opp::default(); 8]; + let ncs = aux_opps(dev, &node, c_str!("apple,cs-opp"), &mut cs)?; + let nafr = aux_opps(dev, &node, c_str!("apple,afr-opp"), &mut afr)?; + if layout.record_slots.len() != layout.iomaps.len() { + return Err(EINVAL); + } + let mut slots = [record::IoSlot::default(); record::IOMAP_SLOTS]; + for (k, (map, &(total, element, writable))) in + layout.iomaps.iter().zip(layout.record_slots).enumerate() + { + slots[k] = record::IoSlot { + slot: map.slot, + pa: map.pa + map.delta, + va: map.va + map.delta, + total, + element, + writable, + }; + } + let max_power_mw = u32::from_le_bytes( + file.get(record::MAX_POWER..record::MAX_POWER + 4) + .ok_or(EINVAL)? + .try_into() + .map_err(|_| EINVAL)?, + ); + let inputs = record::Inputs { + props, + zones: &zones, + main: &main, + cs: &cs[..ncs], + afr: &afr[..nafr], + slots: &slots[..layout.iomaps.len()], + empty_writable: layout.record_empty_writable, + ttbat: adt.ttbs.start, + usc_base: hw::client::COMPACT_WINDOW.start, + user_end: hw::USER_RANGE.end, + timestamps: va::TIMESTAMPS, + max_power_mw, + }; + let mut out = KVVec::from_elem(0u8, record::SIZE, GFP_KERNEL)?; + record::from_file(&mut out, file) + .and_then(|()| record::build(&mut out, &inputs)) + .map_err(|why| { + dev_err!(dev, "hardware record from the device tree: {}\n", why); + EINVAL + })?; + Ok(out) +} + +/// Globals and Power of a device-tree SoC: the verified G15S templates with the GPU node's +/// power words and the maximum power of `hardware`, this machine's hardware record. Returns the +/// two images and that maximum power in mW. +pub(crate) fn device_tree( + dev: &device::Device, + hardware: &[u8], +) -> Result<(KVVec, KVVec, u32)> { + let w = power_words(dev)?; + let at = hwdata::HWDATA_A + hwdata::MAX_POWER_A; + let max_power_mw = u32::from_le_bytes( + hardware + .get(at..at + 4) + .ok_or(EINVAL)? + .try_into() + .map_err(|_| EINVAL)?, + ); + let mut glob = KVVec::from_elem(0u8, globals::SIZE, GFP_KERNEL)?; + let mut pwr = KVVec::from_elem(0u8, power::SIZE, GFP_KERNEL)?; + if expand(&data::GLOBALS, &mut glob).is_err() || expand(&data::POWER, &mut pwr).is_err() { + dev_err!(dev, "board data template hash mismatch\n"); + return Err(EINVAL); + } + words::globals(&mut glob, max_power_mw, &w) + .and_then(|()| words::power(&mut pwr, max_power_mw, &w)) + .map_err(|why| { + dev_err!(dev, "board data from the device tree: {}\n", why); + EINVAL + })?; + Ok((glob, pwr, max_power_mw)) +} + +/// DVFS states of the firmware tables. +pub(crate) const DVFS_STATES: usize = 9; +const DVFS_A: [usize; DVFS_STATES] = [0, 1, 2, 3, 5, 7, 9, 11, 13]; +const DVFS_B: [usize; DVFS_STATES] = [0, 1, 2, 3, 4, 6, 8, 10, 12]; + +/// Table A's frequency of each firmware DVFS state, MHz: the ADT (or device-tree) operating +/// points the firmware's state indices name. +pub(crate) fn table_a_mhz(adt: &GpuAdt) -> [u32; DVFS_STATES] { + DVFS_A.map(|i| adt.perf_mhz[i]) +} + +fn put32(hw: &mut [u8], offset: usize, value: u32) -> Result { + hw.get_mut(offset..offset + 4) + .ok_or(EINVAL)? + .copy_from_slice(&value.to_le_bytes()); + Ok(()) +} + +/// The machine-specific part of HardwareData, rebuilt from this machine's ADT performance +/// states over the template: the firmware's two DVFS tables take the three shared low states, +/// then per voltage level the higher (table A) and the lower (table B) frequency of the ADT +/// pair. Table A carries the core and SRAM voltages (eight identical lanes per state) and its top +/// frequency. With the reference machine's ADT this reproduces the template exactly. Returns the +/// top frequency in kHz. +pub(crate) fn from_adt(dev: &device::Device, adt: &GpuAdt, hw: &mut [u8]) -> Result { + for s in 1..DVFS_STATES { + let (a, pa) = (DVFS_A[s], DVFS_A[s - 1]); + let (b, pb) = (DVFS_B[s], DVFS_B[s - 1]); + if adt.perf_mhz[a] <= adt.perf_mhz[pa] + || adt.perf_mhz[b] <= adt.perf_mhz[pb] + || adt.perf_mv[a] < adt.perf_mv[pa] + || adt.sram_mv[a] < adt.sram_mv[pa] + { + dev_err!(dev, "ADT perf-states do not form ordered DVFS tables\n"); + return Err(EINVAL); + } + } + for s in 0..DVFS_STATES { + let (a, b) = (DVFS_A[s], DVFS_B[s]); + put32(hw, 0xb5c + 4 * s, adt.perf_mhz[a])?; + put32(hw, 0xf9c + 4 * s, adt.perf_mhz[b])?; + put32(hw, 0x1350 + 4 * s, adt.perf_mhz[b])?; + for k in 0..8 { + put32(hw, 0xb9c + 0x20 * s + 4 * k, adt.perf_mv[a])?; + put32(hw, 0xd9c + 0x20 * s + 4 * k, adt.sram_mv[a])?; + } + } + let top = adt.perf_mhz[DVFS_A[DVFS_STATES - 1]]; + put32(hw, 0x4dc4, top)?; + Ok(top * 1000) +} diff --git a/drivers/gpu/drm/asahi/g15/board/blob.rs b/drivers/gpu/drm/asahi/g15/board/blob.rs new file mode 100644 index 00000000000000..04cff8bbaa3d99 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/board/blob.rs @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Board images from a firmware file. +//! +//! A SoC whose board images are not built-in templates names a firmware file +//! ([`super::super::hw::Board::Blob`]), built into the kernel with `CONFIG_EXTRA_FIRMWARE` or +//! loaded from `/lib/firmware`, and pins its SHA-256. The file holds the three images as the +//! firmware of that machine accepted them; the build then writes the pointers and policy words +//! it owns into them (TTBAT, IOMapping VAs, the timestamp arena, the idle policy). +//! +//! Layout, little-endian: the magic `T6031BRD`, u32 format version (1), u32 image count (3), +//! then per image `u32 kind, u32 size` with kinds 0 (HardwareData), 1 (Globals) and +//! 2 (Power), then the images' bytes in that order. Sizes must match the SoC's layout. + +use kernel::{device, firmware::Firmware, prelude::*}; + +use super::super::boot::glue; +use super::super::identity::Hex; + +const MAGIC: &[u8; 8] = b"T6031BRD"; +const VERSION: u32 = 1; +const IMAGES: usize = 3; + +/// The three images. +pub(crate) struct Images { + pub(crate) hardware: KVVec, + pub(crate) globals: KVVec, + pub(crate) power: KVVec, +} + +fn le32(b: &[u8], off: usize) -> Result { + Ok(u32::from_le_bytes( + b.get(off..off + 4) + .ok_or(EINVAL)? + .try_into() + .map_err(|_| EINVAL)?, + )) +} + +fn copy(b: &[u8], range: core::ops::Range) -> Result> { + let src = b.get(range).ok_or(EINVAL)?; + let mut out = KVVec::from_elem(0u8, src.len(), GFP_KERNEL)?; + out.copy_from_slice(src); + Ok(out) +} + +/// Requests `name`, verifies its digest against `sha256` and splits it into the images, each +/// of the size `sizes` gives for its kind. +pub(crate) fn load( + dev: &device::Device, + name: &CStr, + sha256: &[u8; 32], + sizes: [usize; IMAGES], +) -> Result { + let fw = Firmware::request(name, dev).inspect_err(|e| { + dev_err!(dev, "board images {}: not available ({:?})\n", name, e) + })?; + let data = fw.data(); + let digest = glue::sha256(data); + if digest != *sha256 { + dev_err!( + dev, + "board images {}: sha256 {} is not the pinned one\n", + name, + Hex(&digest) + ); + return Err(EINVAL); + } + if data.len() < 16 || &data[..8] != MAGIC || le32(data, 8)? != VERSION { + dev_err!(dev, "board images {}: unknown header\n", name); + return Err(EINVAL); + } + if le32(data, 12)? as usize != IMAGES { + dev_err!(dev, "board images {}: not {} images\n", name, IMAGES); + return Err(EINVAL); + } + let mut at = 16 + IMAGES * 8; + let mut images: [Option>; IMAGES] = [None, None, None]; + for i in 0..IMAGES { + let kind = le32(data, 16 + i * 8)? as usize; + let size = le32(data, 16 + i * 8 + 4)? as usize; + if kind != i || size != sizes[i] { + dev_err!( + dev, + "board images {}: image {} is kind {} of {} bytes, need {}\n", + name, + i, + kind, + size, + sizes[i] + ); + return Err(EINVAL); + } + images[i] = Some(copy(data, at..at + size)?); + at += size; + } + if at != data.len() { + dev_err!(dev, "board images {}: trailing bytes\n", name); + return Err(EINVAL); + } + let [hardware, globals, power] = images; + dev_info!( + dev, + "board images {}: sha256 {} accepted\n", + name, + Hex(&digest) + ); + Ok(Images { + hardware: hardware.ok_or(EINVAL)?, + globals: globals.ok_or(EINVAL)?, + power: power.ok_or(EINVAL)?, + }) +} diff --git a/drivers/gpu/drm/asahi/g15/board/data.rs b/drivers/gpu/drm/asahi/g15/board/data.rs new file mode 100644 index 00000000000000..15dc6fc86ade74 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/board/data.rs @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +// Generated tables. Do not edit. + +//! G15S initial board data (hardware, globals, power) of the supported firmware build: +//! configuration and calibration templates. Sparse: only nonzero 16-byte lines are listed; +//! everything else is zero. Verified by SHA-256 at boot ([`super::expand`]). + +use super::{Line, Template}; + +/// Hardware template (35332 bytes, 207 lines). +#[rustfmt::skip] +pub(crate) static HARDWARE: Template = Template { + size: 35332, + sha256: [ + 0x3b, 0xef, 0x05, 0x37, 0xfb, 0x82, 0x89, 0xe6, + 0x8d, 0xec, 0x7c, 0x78, 0x9f, 0xdc, 0x93, 0xad, + 0x01, 0x50, 0x95, 0x61, 0x48, 0x7c, 0xbf, 0xfb, + 0xca, 0xfb, 0xb0, 0xe3, 0x3f, 0x50, 0x1b, 0x38, + ], + lines: &[ + Line { offset: 0x0, data: [0x00, 0x00, 0x00, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x10, data: [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00] }, + Line { offset: 0x20, data: [0x00, 0x80, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x20, 0xfc, 0xff, 0xff] }, + Line { offset: 0x640, data: [0x00, 0x00, 0xd0, 0x90, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x650, data: [0x00, 0x40, 0x14, 0x00, 0x00, 0x40, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x660, data: [0x00, 0x10, 0x10, 0x0e, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x670, data: [0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x680, data: [0x00, 0x40, 0x01, 0x51, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x690, data: [0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x6a0, data: [0x00, 0x00, 0x00, 0x90, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x6b0, data: [0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x720, data: [0x00, 0xc0, 0x2b, 0x50, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x730, data: [0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x760, data: [0x00, 0x80, 0xe0, 0x90, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x770, data: [0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x7a0, data: [0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x7b0, data: [0x00, 0xa0, 0x12, 0x00, 0x00, 0x50, 0x09, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x7c0, data: [0x00, 0xc0, 0x04, 0x51, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x7d0, data: [0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x880, data: [0x00, 0x00, 0x3d, 0x50, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x890, data: [0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x8a0, data: [0x00, 0x00, 0x3c, 0x50, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x8b0, data: [0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x8c0, data: [0x00, 0x80, 0x3d, 0x50, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x8d0, data: [0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x920, data: [0x00, 0x00, 0x00, 0x93, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x930, data: [0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x960, data: [0x00, 0xc0, 0x45, 0x09, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x970, data: [0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x980, data: [0x00, 0x00, 0x28, 0x50, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x990, data: [0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x9e0, data: [0x00, 0xc0, 0xe5, 0x90, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x9f0, data: [0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xa20, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0xa30, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0xa40, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xa50, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xa60, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x5d, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0xa70, data: [0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0xa80, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xa90, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00] }, + Line { offset: 0xab0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00] }, + Line { offset: 0xac0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0xad0, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xae0, data: [0x00, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xb20, data: [0x14, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xb40, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00] }, + Line { offset: 0xb50, data: [0x04, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xb60, data: [0x52, 0x01, 0x00, 0x00, 0x6a, 0x02, 0x00, 0x00, 0x1c, 0x03, 0x00, 0x00, 0x9c, 0x03, 0x00, 0x00] }, + Line { offset: 0xb70, data: [0x20, 0x04, 0x00, 0x00, 0x9e, 0x04, 0x00, 0x00, 0x20, 0x05, 0x00, 0x00, 0x64, 0x05, 0x00, 0x00] }, + Line { offset: 0xb90, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00] }, + Line { offset: 0xba0, data: [0x7d, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00] }, + Line { offset: 0xbb0, data: [0x7d, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x8f, 0x02, 0x00, 0x00] }, + Line { offset: 0xbc0, data: [0x8f, 0x02, 0x00, 0x00, 0x8f, 0x02, 0x00, 0x00, 0x8f, 0x02, 0x00, 0x00, 0x8f, 0x02, 0x00, 0x00] }, + Line { offset: 0xbd0, data: [0x8f, 0x02, 0x00, 0x00, 0x8f, 0x02, 0x00, 0x00, 0x8f, 0x02, 0x00, 0x00, 0xb7, 0x02, 0x00, 0x00] }, + Line { offset: 0xbe0, data: [0xb7, 0x02, 0x00, 0x00, 0xb7, 0x02, 0x00, 0x00, 0xb7, 0x02, 0x00, 0x00, 0xb7, 0x02, 0x00, 0x00] }, + Line { offset: 0xbf0, data: [0xb7, 0x02, 0x00, 0x00, 0xb7, 0x02, 0x00, 0x00, 0xb7, 0x02, 0x00, 0x00, 0xbc, 0x02, 0x00, 0x00] }, + Line { offset: 0xc00, data: [0xbc, 0x02, 0x00, 0x00, 0xbc, 0x02, 0x00, 0x00, 0xbc, 0x02, 0x00, 0x00, 0xbc, 0x02, 0x00, 0x00] }, + Line { offset: 0xc10, data: [0xbc, 0x02, 0x00, 0x00, 0xbc, 0x02, 0x00, 0x00, 0xbc, 0x02, 0x00, 0x00, 0xdf, 0x02, 0x00, 0x00] }, + Line { offset: 0xc20, data: [0xdf, 0x02, 0x00, 0x00, 0xdf, 0x02, 0x00, 0x00, 0xdf, 0x02, 0x00, 0x00, 0xdf, 0x02, 0x00, 0x00] }, + Line { offset: 0xc30, data: [0xdf, 0x02, 0x00, 0x00, 0xdf, 0x02, 0x00, 0x00, 0xdf, 0x02, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00] }, + Line { offset: 0xc40, data: [0x1b, 0x03, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00] }, + Line { offset: 0xc50, data: [0x1b, 0x03, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00] }, + Line { offset: 0xc60, data: [0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00] }, + Line { offset: 0xc70, data: [0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00] }, + Line { offset: 0xc80, data: [0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00] }, + Line { offset: 0xc90, data: [0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00] }, + Line { offset: 0xca0, data: [0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00] }, + Line { offset: 0xcb0, data: [0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xd90, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xda0, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xdb0, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xdc0, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xdd0, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xde0, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xdf0, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xe00, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xe10, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xe20, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xe30, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xe40, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00] }, + Line { offset: 0xe50, data: [0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x2a, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00] }, + Line { offset: 0xe60, data: [0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00] }, + Line { offset: 0xe70, data: [0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x66, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00] }, + Line { offset: 0xe80, data: [0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00] }, + Line { offset: 0xe90, data: [0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0x9d, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00] }, + Line { offset: 0xea0, data: [0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00] }, + Line { offset: 0xeb0, data: [0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0xbb, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xfa0, data: [0x52, 0x01, 0x00, 0x00, 0x6a, 0x02, 0x00, 0x00, 0x1c, 0x03, 0x00, 0x00, 0x40, 0x03, 0x00, 0x00] }, + Line { offset: 0xfb0, data: [0xb8, 0x03, 0x00, 0x00, 0x28, 0x04, 0x00, 0x00, 0x9e, 0x04, 0x00, 0x00, 0xda, 0x04, 0x00, 0x00] }, + Line { offset: 0xfd0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x8f, 0x82, 0x3f] }, + Line { offset: 0xfe0, data: [0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f] }, + Line { offset: 0xff0, data: [0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f] }, + Line { offset: 0x1060, data: [0x0f, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00] }, + Line { offset: 0x1070, data: [0x34, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00] }, + Line { offset: 0x10a0, data: [0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00] }, + Line { offset: 0x10b0, data: [0x44, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x5d, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00] }, + Line { offset: 0x10e0, data: [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00] }, + Line { offset: 0x10f0, data: [0x07, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00] }, + Line { offset: 0x1120, data: [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00] }, + Line { offset: 0x1130, data: [0x06, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00] }, + Line { offset: 0x1340, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00] }, + Line { offset: 0x1350, data: [0x00, 0x00, 0x00, 0x00, 0x52, 0x01, 0x00, 0x00, 0x6a, 0x02, 0x00, 0x00, 0x1c, 0x03, 0x00, 0x00] }, + Line { offset: 0x1360, data: [0x40, 0x03, 0x00, 0x00, 0xb8, 0x03, 0x00, 0x00, 0x28, 0x04, 0x00, 0x00, 0x9e, 0x04, 0x00, 0x00] }, + Line { offset: 0x1370, data: [0xda, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1390, data: [0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x13b0, data: [0x8f, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x13d0, data: [0xb7, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x13f0, data: [0xbc, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1410, data: [0xdf, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1430, data: [0x1b, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1450, data: [0x66, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1470, data: [0x9d, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1490, data: [0xbb, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1590, data: [0x2a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x15b0, data: [0x2a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x15d0, data: [0x2a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x15f0, data: [0x2a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1610, data: [0x2a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1630, data: [0x2a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1650, data: [0x66, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1670, data: [0x9d, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1690, data: [0xbb, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x17b0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x17c0, data: [0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x17e0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x17f0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0x1800, data: [0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1810, data: [0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x1820, data: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] }, + Line { offset: 0x1830, data: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] }, + Line { offset: 0x1840, data: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] }, + Line { offset: 0x1860, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4580, data: [0x00, 0x00, 0x00, 0x00, 0x40, 0x0d, 0x03, 0x00, 0x40, 0x0d, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4590, data: [0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x45a0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0x45b0, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x45c0, data: [0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00] }, + Line { offset: 0x45d0, data: [0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4600, data: [0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f] }, + Line { offset: 0x4610, data: [0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f, 0x5c, 0x8f, 0x82, 0x3f] }, + Line { offset: 0x4620, data: [0x5c, 0x8f, 0x82, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4bd0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4be0, data: [0x00, 0x00, 0x00, 0x00, 0x9f, 0x2e, 0x7f, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x54, 0x61, 0x51, 0x3b] }, + Line { offset: 0x4bf0, data: [0x00, 0x00, 0x00, 0x00, 0x86, 0x95, 0xa5, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4c00, data: [0x00, 0x7c, 0x36, 0x47, 0xdb, 0x0f, 0xa9, 0x40, 0x00, 0x00, 0x00, 0x00, 0x36, 0x49, 0x8c, 0xbc] }, + Line { offset: 0x4c10, data: [0x08, 0xfd, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4c20, data: [0x00, 0x00, 0x00, 0x00, 0x7c, 0xb6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4c50, data: [0x00, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4c70, data: [0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x3f] }, + Line { offset: 0x4c80, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x42, 0x60, 0x65, 0x3e] }, + Line { offset: 0x4c90, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x47, 0xcd, 0xcc, 0xcc, 0x3d] }, + Line { offset: 0x4ca0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00] }, + Line { offset: 0x4cb0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xb6, 0x00, 0x00] }, + Line { offset: 0x4cc0, data: [0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x0b, 0x00] }, + Line { offset: 0x4d00, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4d10, data: [0x5a, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4d20, data: [0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcd, 0xcc, 0x4c, 0x3f] }, + Line { offset: 0x4d30, data: [0x52, 0xb8, 0x7e, 0x3f, 0xcd, 0xcc, 0x4c, 0x3e, 0x0a, 0xd7, 0xa3, 0x3b, 0xd7, 0xa3, 0xe0, 0x3f] }, + Line { offset: 0x4d40, data: [0xd7, 0xa3, 0xe0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbe, 0x42, 0x33, 0x33, 0xbb, 0x40] }, + Line { offset: 0x4d50, data: [0x33, 0x33, 0xbb, 0x40, 0x1b, 0xca, 0xeb, 0x40, 0x64, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00] }, + Line { offset: 0x4d60, data: [0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00] }, + Line { offset: 0x4d90, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00] }, + Line { offset: 0x4db0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x47, 0x00, 0x00, 0x20, 0x42] }, + Line { offset: 0x4dc0, data: [0x00, 0x00, 0x48, 0x44, 0x64, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4dd0, data: [0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4de0, data: [0x00, 0x00, 0xc8, 0x42, 0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcd, 0xcc, 0x4c, 0x3f] }, + Line { offset: 0x4df0, data: [0xcd, 0xcc, 0x4c, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4e20, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x2a, 0x40] }, + Line { offset: 0x4e30, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00] }, + Line { offset: 0x4e50, data: [0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xa7, 0x46, 0x41, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4e60, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x47, 0x00, 0x00, 0x14, 0x42, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4e70, data: [0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00] }, + Line { offset: 0x4e80, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x4eb0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5160, data: [0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5400, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xb6, 0x00, 0x00, 0x7c, 0xb6, 0x00, 0x00] }, + Line { offset: 0x5410, data: [0x7c, 0xb6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5420, data: [0x00, 0x00, 0x80, 0x3f, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0xee, 0x02, 0x00] }, + Line { offset: 0x54f0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00] }, + Line { offset: 0x5500, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcd, 0xcc, 0x4c, 0x3f, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5510, data: [0xcd, 0xcc, 0x4c, 0x3e, 0x00, 0x00, 0x00, 0x00, 0xec, 0x51, 0xb8, 0x3e, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5520, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x47, 0x33, 0x33, 0xb3, 0x3f, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5530, data: [0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00] }, + Line { offset: 0x5540, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x36, 0x47, 0x7c, 0xb6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5550, data: [0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5570, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5670, data: [0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5680, data: [0x39, 0x8e, 0x63, 0x3f, 0xab, 0xaa, 0x2a, 0x3f, 0x39, 0x8e, 0xe3, 0x3d, 0xab, 0xaa, 0xaa, 0x3e] }, + Line { offset: 0x5690, data: [0xcd, 0xcc, 0xcc, 0xbe, 0xcd, 0xcc, 0x4c, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x47] }, + Line { offset: 0x56a0, data: [0x00, 0x00, 0xa0, 0xc0, 0x00, 0x00, 0x20, 0xc1, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00] }, + Line { offset: 0x56b0, data: [0x20, 0x03, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfa, 0x45] }, + Line { offset: 0x56c0, data: [0x78, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00] }, + Line { offset: 0x56d0, data: [0x00, 0x5e, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xca, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x56e0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5700, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x1f, 0x00, 0x00] }, + Line { offset: 0x5710, data: [0x04, 0x00, 0x00, 0x00, 0xc4, 0x09, 0x00, 0x00, 0x58, 0x02, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] }, + Line { offset: 0x5720, data: [0x04, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5750, data: [0x00, 0x00, 0x80, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5760, data: [0x28, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5800, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x2a, 0x40, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x5810, data: [0x7d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x6020, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x8020, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x87c0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x6e, 0x01] }, + Line { offset: 0x8810, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0x8820, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x4f, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + ], +}; + +/// Globals template (15868 bytes, 17 lines). +#[rustfmt::skip] +pub(crate) static GLOBALS: Template = Template { + size: 15868, + sha256: [ + 0x95, 0x1b, 0xc7, 0x79, 0x0c, 0x61, 0xe3, 0x5a, + 0x51, 0xfd, 0x33, 0x48, 0x5a, 0x78, 0x45, 0x41, + 0x50, 0xfb, 0xfb, 0x09, 0xf1, 0xa9, 0x56, 0x20, + 0x22, 0xff, 0x4a, 0x58, 0x5e, 0xe5, 0x50, 0x2a, + ], + lines: &[ + Line { offset: 0x20, data: [0xb8, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0x30, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x50, data: [0xff, 0xff, 0x28, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00] }, + Line { offset: 0x70, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xb6, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00] }, + Line { offset: 0x80, data: [0x20, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00] }, + Line { offset: 0x7a0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x02, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f] }, + Line { offset: 0x7b0, data: [0xcd, 0xcc, 0x4c, 0x3f, 0xcd, 0xcc, 0x4c, 0x3e, 0x66, 0x66, 0x66, 0x3f, 0xcd, 0xcc, 0xcc, 0x3d] }, + Line { offset: 0x7c0, data: [0x00, 0x00, 0x80, 0x3e, 0x33, 0x33, 0x33, 0x3f, 0x66, 0x66, 0x66, 0x3f, 0x06, 0x00, 0x00, 0x00] }, + Line { offset: 0x7d0, data: [0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00] }, + Line { offset: 0x970, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00] }, + Line { offset: 0x980, data: [0x0a, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0x990, data: [0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x9a0, data: [0x02, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0x9b0, data: [0x28, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00] }, + Line { offset: 0x9c0, data: [0x00, 0x00, 0x01, 0x02, 0x01, 0x01, 0x5a, 0x4b, 0x01, 0x01, 0x01, 0x02, 0x5a, 0x4b, 0x01, 0x01] }, + Line { offset: 0x9d0, data: [0x01, 0x01, 0x5a, 0x4b, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xdf0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + ], +}; + +/// Power template (2292 bytes, 7 lines). +#[rustfmt::skip] +pub(crate) static POWER: Template = Template { + size: 2292, + sha256: [ + 0xf8, 0x96, 0x12, 0x0a, 0xb1, 0xad, 0xdc, 0x0c, + 0xf7, 0x50, 0xe0, 0xf2, 0x78, 0x48, 0x4a, 0xde, + 0xb0, 0x14, 0xfc, 0x7a, 0x05, 0x02, 0x60, 0xa4, + 0xa4, 0x12, 0x3d, 0xf2, 0x5c, 0x6d, 0xcb, 0x62, + ], + lines: &[ + Line { offset: 0x10, data: [0x05, 0x00, 0x00, 0x00, 0xec, 0x51, 0xb8, 0x3e, 0x33, 0x33, 0xb3, 0x3f, 0x28, 0x00, 0x00, 0x00] }, + Line { offset: 0x20, data: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xa0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xb0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x42, 0xf0, 0xa7, 0x46, 0x41] }, + Line { offset: 0xc0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + Line { offset: 0xd0, data: [0x7c, 0xb6, 0x00, 0x00, 0xcd, 0xcc, 0xcc, 0x3d, 0x42, 0x60, 0x65, 0x3e, 0x00, 0x00, 0x00, 0x00] }, + Line { offset: 0xe0, data: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00] }, + ], +}; diff --git a/drivers/gpu/drm/asahi/g15/board/record.rs b/drivers/gpu/drm/asahi/g15/board/record.rs new file mode 100644 index 00000000000000..959bc6a4ab0a2c --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/board/record.rs @@ -0,0 +1,1402 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The J516C hardware record (0xb480 bytes) from the device tree. +//! +//! The record is HardwareDataB (identity, IOMapping records, the DVFS tables) at 0, HardwareDataA +//! (the power, performance and thermal controllers) at [`HWDATA_A`], and the G15C tail (sensor +//! keys). Every word is one of: +//! +//! - a device-tree value or a function of one ([`PROPS`], the operating-point tables, the +//! reserved `ttbs` region): the controller gains, time constants and their derived filter +//! words (`(tc - 1) / tc`, `1 / tc`, gain x period, periods x 4, periods x period, clocks), +//! the two voltage-sorted DVFS tables with per-cluster voltages, the CS and AFR tables, the +//! state cap and base state; +//! - a layout constant of the 2419 firmware's G15C record: flags, the IOMapping flag words, +//! the identity words, fixed factors (65536, 95, 100, 1.02, 0.8/0.2, 625, 11000, 125, 5); +//! - a word the device tree does not carry ([`FROM_FILE`]), copied from the machine's board file +//! by [`from_file`] and listed with its rule in the project notes: the maximum power +//! (HardwareDataA +0x6a4; every other maximum-power word derives from it), the MTR sensor +//! masks, the relative-power table (the device tree's operating-point powers are a boot-loader +//! stand-in) and the tail's six sensor rows; +//! - a word the file carries and the firmware was shown not to need ([`UNNEEDED`]): zero. +//! +//! HardwareDataA has the G15S shape of the T6030 templates with insertions ([`a`]): 8 bytes +//! before the fast-die controller (+0x8bc), 16-wide instead of 8-wide coefficient rows (+0x200 +//! twice), 16-byte instead of 8-byte sensor masks (+8 twice), 0x600 and 0x2000 bytes of zero +//! blocks further on. The driver still writes the TTBAT, the IOMapping VAs, the timestamp arena +//! and the initdata timestamp as it does for the templates. +//! +//! Core-only (no `kernel` imports): this file is compiled by the host test harness as well. + +use core::ffi::CStr; + +use super::words::{f32_div, f32_from_u32, f32_mul}; + +pub(crate) const SIZE: usize = 0xb480; +pub(crate) const HWDATA_A: usize = 0x4580; +/// IOMapping records: 32 bytes per slot. +pub(crate) const IOMAPS: usize = 0x640; +pub(crate) const IOMAP_SLOTS: usize = 31; +/// DVFS table entries. +pub(crate) const STATES: usize = 16; +/// Entries of the CS and AFR tables. +const CS_STATES: usize = 16; +const AFR_STATES: usize = 8; +/// Operating points of the layout and voltage lanes per state. +pub(crate) const PERF_STATES: usize = 14; +pub(crate) const CLUSTERS: usize = 4; +const LANES: usize = 8; +/// The AIC timer base clock, kHz. +const BASE_CLOCK_KHZ: u32 = 24000; + +// IEEE single bit patterns of the record's fixed factors. +const F_1: u32 = 0x3f800000; +const F_0_2: u32 = 0x3e4ccccd; +const F_0_8: u32 = 0x3f4ccccd; +const F_0_95: u32 = 0x3f733333; +const F_1_02: u32 = 0x3f828f5c; +const F_5: u32 = 0x40a00000; +const F_95: u32 = 0x42be0000; +const F_100: u32 = 0x42c80000; +const F_8000: u32 = 0x45fa0000; +const F_65536: u32 = 0x47800000; + +/// The GPU node's properties the record takes, each one u32 (gains are IEEE single bits), with +/// the value a node without the property gets (`None`: required). +pub(crate) const PROPS: [(&CStr, Option); 43] = [ + (c"apple,power-sample-period", None), + (c"apple,perf-base-pstate", None), + (c"apple,min-sram-microvolt", None), + (c"apple,csafr-min-sram-microvolt", None), + (c"apple,avg-power-filter-tc-ms", None), + (c"apple,avg-power-ki-only", None), + (c"apple,avg-power-kp", None), + (c"apple,avg-power-min-duty-cycle", None), + (c"apple,avg-power-target-filter-tc", None), + (c"apple,fast-die0-integral-gain", None), + (c"apple,fast-die0-proportional-gain", None), + (c"apple,fast-die0-prop-tgt-delta", Some(0)), + (c"apple,perf-boost-ce-step", None), + (c"apple,perf-boost-min-util", None), + (c"apple,perf-filter-drop-threshold", None), + (c"apple,perf-filter-time-constant", None), + (c"apple,perf-filter-time-constant2", None), + (c"apple,perf-integral-gain", None), + (c"apple,perf-integral-gain2", None), + (c"apple,perf-integral-min-clamp", None), + (c"apple,perf-proportional-gain", None), + (c"apple,perf-proportional-gain2", None), + (c"apple,perf-reset-iters", Some(6)), + (c"apple,perf-tgt-utilization", None), + (c"apple,ppm-filter-time-constant-ms", None), + (c"apple,ppm-ki", None), + (c"apple,ppm-kp", None), + (c"apple,pwr-filter-time-constant", None), + (c"apple,pwr-integral-gain", None), + (c"apple,pwr-integral-min-clamp", None), + (c"apple,pwr-min-duty-cycle", None), + (c"apple,pwr-proportional-gain", None), + (c"apple,pwr-sample-period-aic-clks", None), + (c"apple,se-engagement-criteria", None), + (c"apple,se-filter-time-constant", None), + (c"apple,se-filter-time-constant-1", None), + (c"apple,se-inactive-threshold", None), + (c"apple,se-ki", None), + (c"apple,se-ki-1", None), + (c"apple,se-kp", None), + (c"apple,se-kp-1", None), + (c"apple,se-reset-criteria", None), + (c"apple,se-target", None), +]; +const PERIOD_MS: usize = 0; +const BASE_PSTATE: usize = 1; +const MIN_SRAM_UV: usize = 2; +const CSAFR_MIN_SRAM_UV: usize = 3; +const AVG_TC_MS: usize = 4; +const AVG_KI: usize = 5; +const AVG_KP: usize = 6; +const AVG_MIN_DUTY: usize = 7; +const AVG_TGT_TC: usize = 8; +const FD_KI: usize = 9; +const FD_KP: usize = 10; +const FD_DELTA: usize = 11; +const BOOST_CE: usize = 12; +const BOOST_MIN: usize = 13; +const PERF_DROP: usize = 14; +const PERF_TC: usize = 15; +const PERF_TC2: usize = 16; +const PERF_KI: usize = 17; +const PERF_KI2: usize = 18; +const PERF_MIN_CLAMP: usize = 19; +const PERF_KP: usize = 20; +const PERF_KP2: usize = 21; +const PERF_RESET: usize = 22; +const PERF_TGT: usize = 23; +const PPM_TC_MS: usize = 24; +const PPM_KI: usize = 25; +const PPM_KP: usize = 26; +const PWR_TC: usize = 27; +const PWR_KI: usize = 28; +const PWR_MIN_CLAMP: usize = 29; +const PWR_MIN_DUTY: usize = 30; +const PWR_KP: usize = 31; +const AIC_CLKS: usize = 32; +const SE_CRIT: usize = 33; +const SE_TC: usize = 34; +const SE_TC1: usize = 35; +const SE_INACT: usize = 36; +const SE_KI: usize = 37; +const SE_KI1: usize = 38; +const SE_KP: usize = 39; +const SE_KP1: usize = 40; +const SE_RESET: usize = 41; +const SE_TARGET: usize = 42; + +/// One operating point: MHz, the clusters' voltages in mV (rounded up from microvolts), how +/// many voltage cells the node had, and mW. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Opp { + pub(crate) mhz: u32, + pub(crate) mv: [u32; CLUSTERS], + pub(crate) cells: usize, + pub(crate) mw: u32, +} + +impl Opp { + fn max_mv(&self) -> u32 { + self.mv[..self.cells].iter().copied().max().unwrap_or(0) + } +} + +/// One IOMapping record: slot, physical address and firmware VA (both with the in-page offset), +/// mapped bytes, element bytes, writable. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct IoSlot { + pub(crate) slot: u8, + pub(crate) pa: u64, + pub(crate) va: u64, + pub(crate) total: u32, + pub(crate) element: u32, + pub(crate) writable: bool, +} + +/// Everything the record is built from. +pub(crate) struct Inputs<'a> { + pub(crate) props: [u32; PROPS.len()], + /// `apple,power-zones` cells (triples). + pub(crate) zones: &'a [u32], + pub(crate) main: &'a [Opp], + pub(crate) cs: &'a [Opp], + pub(crate) afr: &'a [Opp], + pub(crate) slots: &'a [IoSlot], + /// Unmapped slots whose flag word the record nevertheless holds as 1. + pub(crate) empty_writable: &'a [u8], + /// The TTBAT page (the `ttbs` region). + pub(crate) ttbat: u64, + /// Firmware VAs the record repeats: the USC base, the page past the user range, the + /// timestamp arena. + pub(crate) usc_base: u64, + pub(crate) user_end: u64, + pub(crate) timestamps: u64, + /// The maximum GPU power in mW ([`MAX_POWER`], a word the device tree does not carry). + pub(crate) max_power_mw: u32, +} + +/// HardwareDataA's maximum-power word (= `fw::initdata::hwdata::MAX_POWER_A`). +pub(crate) const MAX_POWER: usize = HWDATA_A + 0x6a4; + +/// Words the device tree does not carry, copied from the board file. Record offsets. +#[rustfmt::skip] +pub(crate) const FROM_FILE: [usize; 32] = [ + // The relative powers of states 1..7 (state 8 is 100): the device tree's operating-point + // powers are a boot-loader stand-in. + 0x1060, 0x1064, 0x1068, 0x106c, 0x1070, 0x1074, 0x1078, + // HardwareDataA: the maximum power, the MTR fast-die masks (+0x8ac, +0x1490) and the alarm + // mask (+0x24a8); the device tree's apple,fast-die0-sensor-mask is another value. + MAX_POWER, + HWDATA_A + 0x8ac, HWDATA_A + 0x8b0, + HWDATA_A + 0x1490, HWDATA_A + 0x1494, + HWDATA_A + 0x24a8, HWDATA_A + 0x24ac, + // The tail's six sensor rows (key, id, kind; 12 bytes each; the boot loader does not export + // the aon-ptd table). + HWDATA_A + 0x6c58, HWDATA_A + 0x6c5c, HWDATA_A + 0x6c60, + HWDATA_A + 0x6c64, HWDATA_A + 0x6c68, HWDATA_A + 0x6c6c, + HWDATA_A + 0x6c70, HWDATA_A + 0x6c74, HWDATA_A + 0x6c78, + HWDATA_A + 0x6c7c, HWDATA_A + 0x6c80, HWDATA_A + 0x6c84, + HWDATA_A + 0x6c88, HWDATA_A + 0x6c8c, HWDATA_A + 0x6c90, + HWDATA_A + 0x6c94, HWDATA_A + 0x6c98, HWDATA_A + 0x6c9c, +]; + +/// Words the board file carries that the record leaves zero: the firmware ran, passed every +/// check and reached its top state without them (one boot each). The cross-check accepts the +/// file's value there. 27 words in the HardwareDataB +0x38..+0x638 block and two all-ones words +/// after it (zero in the G15S templates); the tail's thirteen readings (a single at +/// HardwareDataA +0x6d34, twelve singles after +0x6d80). +#[rustfmt::skip] +pub(crate) const UNNEEDED: [usize; 42] = [ + 0xe0, 0xe8, 0xf4, 0xf8, 0xfc, 0x100, 0x104, 0x108, 0x10c, 0x2d8, 0x2dc, 0x2e0, 0x2e4, + 0x2e8, 0x2ec, 0x3e0, 0x3e8, 0x3f4, 0x3f8, 0x400, 0x40c, 0x5d8, 0x5dc, 0x5e0, 0x5e4, + 0x5e8, 0x5ec, 0x30d8, 0x30f0, + HWDATA_A + 0x6d34, + HWDATA_A + 0x6d8c, HWDATA_A + 0x6d90, HWDATA_A + 0x6d94, HWDATA_A + 0x6d98, + HWDATA_A + 0x6dcc, HWDATA_A + 0x6dd0, HWDATA_A + 0x6dd4, HWDATA_A + 0x6dd8, + HWDATA_A + 0x6dec, HWDATA_A + 0x6df4, HWDATA_A + 0x6dfc, HWDATA_A + 0x6e04, +]; + +/// The tail's sensor rows: six rows of {key, id, kind} from [`SENSOR_ROWS`]; the keys of the +/// rows whose kind byte is `g`, their presence mask, then the `r` and `f` rows' keys with a +/// count of one each. +const SENSOR_ROWS: usize = HWDATA_A + 0x6c58; +const SENSOR_ROW_COUNT: usize = 6; +const SENSOR_G_KEYS: usize = HWDATA_A + 0x6cdc; +const SENSOR_G_MASK: usize = HWDATA_A + 0x6cfc; +const SENSOR_R_KEY: usize = HWDATA_A + 0x6d04; +const SENSOR_R_COUNT: usize = HWDATA_A + 0x6d0c; +const SENSOR_F_KEY: usize = HWDATA_A + 0x6d14; +const SENSOR_F_COUNT: usize = HWDATA_A + 0x6d18; + +type R = Result; + +fn get32(b: &[u8], at: usize) -> R { + let w = b.get(at..at + 4).ok_or("record too short")?; + Ok(u32::from_le_bytes([w[0], w[1], w[2], w[3]])) +} + +fn put32(b: &mut [u8], at: usize, v: u32) -> R<()> { + b.get_mut(at..at + 4) + .ok_or("record too short")? + .copy_from_slice(&v.to_le_bytes()); + Ok(()) +} + +fn put64(b: &mut [u8], at: usize, v: u64) -> R<()> { + b.get_mut(at..at + 8) + .ok_or("record too short")? + .copy_from_slice(&v.to_le_bytes()); + Ok(()) +} + +/// `1 / n` as a single. +fn inv(n: u32) -> R { + f32_div(F_1, f32_from_u32(n)).ok_or("a time constant is 0") +} + +/// `(n - 1) / n` as a single (the filter's complement, `1 - 1/n`). +fn complement(n: u32) -> R { + if n == 0 { + return Err("a time constant is 0"); + } + f32_div(f32_from_u32(n - 1), f32_from_u32(n)).ok_or("a time constant is 0") +} + +/// `a * b` of device-tree words: refused, not wrapped (and no overflow panic), when it does not +/// fit the record's u32. +fn mul(a: u32, b: u32) -> R { + a.checked_mul(b).ok_or(OVERFLOW) +} + +const OVERFLOW: &str = "a device-tree value overflows the hardware record's u32 arithmetic"; + +/// The G15C HardwareDataA offset of a G15S-layout word. +pub(crate) const fn a(off: usize) -> usize { + let shifted = if off < 0x8bc { + off + } else if off < 0x970 { + off + 8 + } else if off < 0xb70 { + // The coefficient tables, 16 instead of 8 singles per row: not written here. + off + 8 + } else if off < 0x1290 { + off + 0x208 + } else if off < 0x14b4 { + off + 0x210 + } else if off < 0x1aa0 { + off + 0xa10 + } else if off < 0x3aa4 { + off + 0xa18 + } else { + off + 0x2a18 + }; + HWDATA_A + shifted +} + +/// The two voltage-sorted DVFS tables of the operating points: entry 0 is state 0 (off), then +/// per distinct maximum voltage, ascending, the highest-frequency state (table A, `primary`) +/// and the lowest-frequency one (table B, `secondary`). States sharing a voltage must share +/// their cluster voltages; frequencies must rise along both tables and every cluster's voltage +/// along table A. +pub(crate) struct Tables { + pub(crate) len: usize, + pub(crate) primary: [u8; STATES], + pub(crate) secondary: [u8; STATES], +} + +impl Tables { + pub(crate) fn top(&self) -> usize { + self.len - 1 + } +} + +pub(crate) fn tables(main: &[Opp]) -> R { + if main.len() < 2 || main.len() > u8::MAX as usize { + return Err("operating points: fewer than 2 or more than 255"); + } + if main[0].mhz != 0 || main[1..].iter().any(|s| s.mhz == 0) { + return Err("operating points: state 0 is not the only 0 MHz state"); + } + let mut t = Tables { + len: 1, + primary: [0; STATES], + secondary: [0; STATES], + }; + let mut last_mv = 0; + loop { + let Some(mv) = main[1..] + .iter() + .map(Opp::max_mv) + .filter(|&mv| mv > last_mv) + .min() + else { + break; + }; + let group = (1..main.len()).filter(|&i| main[i].max_mv() == mv); + let (mut first, mut hi, mut lo) = (0usize, 0usize, 0usize); + for i in group { + if first == 0 { + first = i; + } + if hi == 0 || main[i].mhz > main[hi].mhz { + hi = i; + } + if lo == 0 || main[i].mhz < main[lo].mhz { + lo = i; + } + if main[i].mv != main[first].mv { + return Err("operating points at one voltage differ per cluster"); + } + } + if t.len >= STATES { + return Err("operating points: more than 16 voltages"); + } + let (pp, ps) = ( + &main[t.primary[t.len - 1] as usize], + &main[t.secondary[t.len - 1] as usize], + ); + if main[hi].mhz <= pp.mhz || main[lo].mhz <= ps.mhz { + return Err("operating points: frequency does not rise with voltage"); + } + if t.len > 1 && (0..main[hi].cells).any(|c| main[hi].mv[c] <= pp.mv[c]) { + return Err("operating points: a cluster's voltage does not rise with the table"); + } + t.primary[t.len] = hi as u8; + t.secondary[t.len] = lo as u8; + t.len += 1; + last_mv = mv; + } + if t.len < 2 { + return Err("operating points: no usable state"); + } + Ok(t) +} + +/// A voltage lane of a state: the cluster's voltage, or cluster 0's past the node's cells. +fn lane(s: &Opp, j: usize) -> u32 { + if j < s.cells { + s.mv[j] + } else { + s.mv[0] + } +} + +fn hwdata_b(out: &mut [u8], i: &Inputs<'_>, t: &Tables) -> R<()> { + let p = &i.props; + put64(out, 0x0, 0x6f_0000_0000)?; + put64(out, 0x8, 0xffc0_0000)?; + put64(out, 0x10, i.usc_base)?; + put64(out, 0x18, i.usc_base)?; + put64(out, 0x20, i.user_end)?; + put64(out, 0x28, i.timestamps)?; + for s in i.slots { + if s.slot as usize >= IOMAP_SLOTS { + return Err("IOMapping slot past the table"); + } + let r = IOMAPS + 32 * s.slot as usize; + put64(out, r, s.pa)?; + put64(out, r + 8, s.va)?; + put32(out, r + 0x10, s.total)?; + put32(out, r + 0x14, s.element)?; + put32(out, r + 0x18, s.writable as u32)?; + } + for &slot in i.empty_writable { + if slot as usize >= IOMAP_SLOTS || i.slots.iter().any(|s| s.slot == slot) { + return Err("an empty-writable slot is mapped or past the table"); + } + put32(out, IOMAPS + 32 * slot as usize + 0x18, 1)?; + } + // Identity and flags. + put32(out, 0xa28, 0x6031)?; + put32(out, 0xa2c, 1)?; + put32(out, 0xa30, 2)?; + for at in [0xa38, 0xa3c, 0xa40, 0xa50, 0xa58, 0xa60] { + put32(out, at, 1)?; + } + put32(out, 0xa68, BASE_CLOCK_KHZ)?; + put32(out, 0xa6c, 1)?; + put32(out, 0xa70, p[PERIOD_MS])?; + put32(out, 0xa78, 1)?; + put64(out, 0xa7c, 0x1_0000_0001)?; + put32(out, 0xa9c, 0x1f)?; + put64(out, 0xabc, 4)?; + put32(out, 0xacc, 1)?; + put32(out, 0xad0, 1)?; + put32(out, 0xae4, 0x31)?; + put32(out, 0xb04, 1)?; + put32(out, 0xb20, 0x28)?; + put32(out, 0xb24, 0xff)?; + put32(out, 0xb40, 1)?; + put64(out, 0xb44, i.ttbat)?; + // GPU core 24 (G15C), revision 4, 40 core slots. + put32(out, 0xb4c, 24)?; + put32(out, 0xb50, 4)?; + put32(out, 0xb54, 40)?; + put32(out, 0xb58, t.top() as u32)?; + let min_sram = p[MIN_SRAM_UV].div_ceil(1000); + let top = &i.main[t.primary[t.top()] as usize]; + let base_index = p[BASE_PSTATE] as usize; + let base = i + .main + .get(base_index) + .ok_or("perf-base-pstate past the states")?; + if t.primary[base_index] as usize != base_index { + return Err("perf-base-pstate is not its own table-A entry"); + } + if top.mhz <= base.mhz { + return Err("the top state is not above the base state"); + } + for k in 0..t.len { + let ps = &i.main[t.primary[k] as usize]; + let ss = &i.main[t.secondary[k] as usize]; + put32(out, 0xb5c + 4 * k, ps.mhz)?; + put32(out, 0xf9c + 4 * k, ss.mhz)?; + put32(out, 0x1350 + 4 * k, ss.mhz)?; + for j in 0..LANES { + let v = lane(ps, j); + put32(out, 0xb9c + 0x20 * k + 4 * j, v)?; + put32(out, 0xd9c + 0x20 * k + 4 * j, v.max(min_sram))?; + } + for j in 0..ss.cells { + put32(out, 0x1390 + 0x20 * k + 4 * j, ss.mv[j])?; + put32(out, 0x1590 + 0x20 * k + 4 * j, ss.mv[j].max(min_sram))?; + } + put32(out, 0xfdc + 4 * k, F_1_02)?; + put32(out, 0x10dc + 4 * k, t.primary[k] as u32)?; + put32(out, 0x111c + 4 * k, t.secondary[k] as u32)?; + if k > 0 { + // Relative power (a FROM_FILE word on the J516C) and relative boost frequency. + if top.mw != 0 { + put32( + out, + 0x105c + 4 * k, + u32::try_from(100 * u64::from(ps.mw) / u64::from(top.mw)) + .map_err(|_| "a relative power does not fit its u32 word")?, + )?; + } + if ps.mhz > base.mhz { + let span = u64::from(top.mhz - base.mhz); + put32( + out, + 0x109c + 4 * k, + (100 * u64::from(ps.mhz - base.mhz) / span) as u32, + )?; + } + } + } + put32(out, 0x134c, t.top() as u32)?; + // The CS and AFR tables: the top state twice, frequencies, voltages, SRAM voltages. + let cs_sram = p[CSAFR_MIN_SRAM_UV] / 1000; + let mut aux = |base: usize, tab: &[Opp], n: usize| -> R { + if tab.is_empty() || tab.len() > n { + return Err("CS/AFR table empty or longer than its layout"); + } + let top = (tab.len() - 1) as u32; + put32(out, base, top)?; + put32(out, base + 4, top)?; + let (fr, vo, sr) = (base + 8, base + 8 + 4 * n, base + 8 + 12 * n); + for (k, s) in tab.iter().enumerate() { + put32(out, fr + 4 * k, s.mhz)?; + for j in 0..s.cells.min(2) { + put32(out, vo + 8 * k + 4 * j, s.mv[j])?; + put32(out, sr + 8 * k + 4 * j, s.mv[j].max(cs_sram))?; + } + } + Ok(sr + 8 * n) + }; + let end = aux(0x115c, i.cs, CS_STATES)?; + if end != 0x12a4 { + return Err("CS table layout"); + } + let end = aux(0x12a4, i.afr, AFR_STATES)?; + if end != 0x134c { + return Err("AFR table layout"); + } + put32(out, 0x17b8, 5)?; + put32(out, 0x17c0, 3)?; + put32(out, 0x17c4, 7)?; + put32(out, 0x17c8, 7)?; + for at in [ + 0x17e8, 0x17fc, 0x1800, 0x1804, 0x1808, 0x1810, 0x1814, 0x1818, 0x1860, + ] { + put32(out, at, 1)?; + } + for at in (0x1820..0x1850).step_by(4) { + put32(out, at, u32::MAX)?; + } + Ok(()) +} + +fn hwdata_a(out: &mut [u8], i: &Inputs<'_>, t: &Tables) -> R<()> { + let p = &i.props; + let period_ms = p[PERIOD_MS]; + if period_ms == 0 { + return Err("the power sample period is 0"); + } + let period_s = f32_div(f32_from_u32(period_ms), f32_from_u32(1000)).ok_or("period")?; + let per_period = + |gain: usize| f32_mul(p[gain], period_s).ok_or("a gain is not a finite normal single"); + let max_scaled = 100 * t.top() as u32; + let base_scaled = mul(100, p[BASE_PSTATE])?; + let max_power = i.max_power_mw; + let max_power_f = f32_from_u32(max_power); + let mut w = |off: usize, v: u32| put32(out, a(off), v); + w(0x4, p[AIC_CLKS])?; + w(0x8, p[AIC_CLKS])?; + w(0x10, 4)?; + w(0x14, F_1)?; + w(0x2c, 1)?; + w(0x30, 1)?; + w(0x44, base_scaled)?; + w(0x48, 1)?; + w(0x4c, max_scaled)?; + w(0x54, 100)?; + for k in 0..t.len { + w(0x80 + 4 * k, F_1_02)?; + } + w(0x658, 625)?; + // Power controller. + w(0x664, complement(p[PWR_TC])?)?; + w(0x66c, inv(p[PWR_TC])?)?; + w(0x674, p[PWR_KI])?; + w(0x67c, f32_from_u32(p[PWR_MIN_CLAMP]))?; + w(0x680, max_power_f)?; + w(0x684, p[PWR_KP])?; + let k = f32_div(f32_from_u32(max_scaled), max_power_f).ok_or("maximum power is 0")?; + w(0x68c, k ^ 0x8000_0000)?; + w(0x690, p[PWR_MIN_DUTY].wrapping_sub(max_scaled))?; + w(0x698, max_scaled)?; + w(0x6a4, max_power)?; + w(0x6d4, max_scaled)?; + // PPM controller. + let ppm_tc = p[PPM_TC_MS] / period_ms; + w(0x6f0, mul(4, ppm_tc)?)?; + w(0x6fc, complement(ppm_tc)?)?; + w(0x704, inv(ppm_tc)?)?; + w(0x70c, per_period(PPM_KI)?)?; + w(0x718, F_65536)?; + w(0x71c, p[PPM_KP])?; + w(0x728, p[PWR_MIN_DUTY])?; + w(0x72c, max_scaled)?; + w(0x73c, max_power)?; + w(0x744, p[PPM_TC_MS])?; + w(0x74c, mul(mul(ppm_tc, period_ms)?, BASE_CLOCK_KHZ)?)?; + // Performance controller. + w(0x788, p[PERF_TGT])?; + w(0x790, p[BOOST_MIN])?; + w(0x794, p[BOOST_CE])?; + w(0x798, p[PERF_RESET])?; + w(0x7a0, 6)?; + w(0x7a4, 1)?; + w(0x7a8, p[PERF_DROP])?; + w(0x7ac, complement(p[PERF_TC])?)?; + w(0x7b0, complement(p[PERF_TC2])?)?; + w(0x7b4, inv(p[PERF_TC])?)?; + w(0x7b8, inv(p[PERF_TC2])?)?; + w(0x7bc, p[PERF_KI])?; + w(0x7c0, p[PERF_KI2])?; + w(0x7c4, f32_from_u32(p[PERF_MIN_CLAMP]))?; + w(0x7c8, F_95)?; + w(0x7cc, p[PERF_KP])?; + w(0x7d0, p[PERF_KP2])?; + let boost = (t.top() as u32) + .checked_sub(p[BASE_PSTATE]) + .ok_or("perf-base-pstate above the top state")?; + w(0x7d4, f32_div(f32_from_u32(boost), F_0_95).ok_or("boost")?)?; + w(0x7d8, base_scaled)?; + w(0x7dc, max_scaled)?; + w(0x7e0, base_scaled)?; + w(0x7ec, p[PERF_TGT])?; + w(0x81c, base_scaled)?; + w(0x838, F_65536)?; + w(0x83c, f32_from_u32(p[PWR_MIN_DUTY]))?; + w(0x840, f32_from_u32(max_scaled))?; + w(0x844, i.main.iter().map(|s| s.mhz).max().unwrap_or(0))?; + w(0x854, p[PWR_MIN_DUTY])?; + w(0x860, F_100)?; + w(0x864, max_scaled)?; + w(0x86c, F_0_8)?; + w(0x870, F_0_2)?; + // Fast-die controller (its sensor mask is a FROM_FILE word). + w(0x8bc, 4)?; + w(0x8d0, F_1)?; + w(0x8d8, per_period(FD_KI)?)?; + w(0x8e4, F_65536)?; + w(0x8e8, p[FD_KP])?; + w(0x8f4, p[PWR_MIN_DUTY])?; + w(0x8f8, max_scaled)?; + w(0x8fc, max_scaled)?; + w(0x900, mul(100, p[FD_DELTA])?)?; + w(0x908, 11000)?; + w(0x938, max_scaled)?; + w(0xbe0, max_scaled)?; + // Power zones and the average-power controller. + w(0xe80, 1)?; + w(0xe84, (i.zones.len() / 3) as u32)?; + for at in [0xe88, 0xe8c, 0xe90] { + w(at, max_power)?; + } + let tgt_tc = p[AVG_TGT_TC]; + w(0xe9c, complement(tgt_tc)?)?; + w(0xea0, inv(tgt_tc)?)?; + w(0xea4, mul(4, tgt_tc)?)?; + w(0xea8, mul(period_ms, tgt_tc)?)?; + w(0xeac, mul(mul(period_ms, tgt_tc)?, BASE_CLOCK_KHZ)?)?; + if i.zones.len() % 3 != 0 || i.zones.len() > 15 { + return Err("the power zones are not up to five u32 triples"); + } + for (z, zone) in i.zones.chunks_exact(3).enumerate() { + let at = 0xeb4 + 0x28 * z; + let (target, offset, tc) = (zone[0], zone[1], zone[2]); + w(at + 0x4, target)?; + w( + at + 0x8, + target + .checked_sub(offset) + .ok_or("a power zone's offset is larger than its target")?, + )?; + w(at + 0xc, mul(4, tc)?)?; + w(at + 0x10, mul(period_ms, tc)?)?; + w(at + 0x14, 1_320_000_000)?; + w(at + 0x1c, complement(tc)?)?; + w(at + 0x20, inv(tc)?)?; + } + let avg_tc = p[AVG_TC_MS] / period_ms; + w(0xf7c, mul(4, avg_tc)?)?; + w(0xf88, complement(avg_tc)?)?; + w(0xf90, inv(avg_tc)?)?; + w(0xf98, per_period(AVG_KI)?)?; + w(0xfa4, F_65536)?; + w(0xfa8, p[AVG_KP])?; + w(0xfb4, p[AVG_MIN_DUTY])?; + w(0xfb8, max_scaled)?; + w(0xfbc, max_scaled)?; + w(0xfc4, max_power_f)?; + w(0xfc8, max_power)?; + w(0xfd0, p[AVG_TC_MS])?; + w(0xfd8, mul(mul(avg_tc, period_ms)?, BASE_CLOCK_KHZ)?)?; + w(0xff8, max_scaled)?; + // The shader-engine controller block at +0x10b4. + const SE: usize = 0x10b4; + let clocks = mul(BASE_CLOCK_KHZ, period_ms)?; + w(SE + 0x40, 50)?; + w(SE + 0x44, 1)?; + w(SE + 0x4c, complement(p[SE_TC])?)?; + w(SE + 0x50, complement(p[SE_TC1])?)?; + w(SE + 0x54, inv(p[SE_TC])?)?; + w(SE + 0x58, inv(p[SE_TC1])?)?; + w(SE + 0x5c, per_period(SE_KI)?)?; + w(SE + 0x60, per_period(SE_KI1)?)?; + w(SE + 0x68, F_65536)?; + w(SE + 0x6c, p[SE_KP])?; + w(SE + 0x70, p[SE_KP1])?; + w(SE + 0x78, 100)?; + w(SE + 0x7c, max_scaled)?; + w(SE + 0x80, 100)?; + w(SE + 0x88, F_8000)?; + w(SE + 0x8c, p[SE_TARGET])?; + w(SE + 0x94, mul(p[SE_TC], period_ms)?)?; + w(SE + 0x98, mul(p[SE_TC1], period_ms)?)?; + w(SE + 0x9c, mul(p[SE_TC], clocks)?)?; + w(SE + 0xa4, mul(p[SE_TC1], clocks)?)?; + w(SE + 0xb0, F_65536)?; + w(SE + 0xd8, 8000)?; + w(SE + 0xdc, 4)?; + w(SE + 0xe0, p[SE_INACT])?; + w(SE + 0xe4, p[SE_CRIT])?; + w(SE + 0xe8, 2)?; + w(SE + 0xec, 4)?; + w(SE + 0xf0, p[SE_RESET])?; + w(SE + 0x11c, F_65536)?; + w(SE + 0x12c, 40)?; + w(SE + 0x130, max_scaled)?; + // Past the second sensor mask (FROM_FILE), the alarm mask (FROM_FILE) and the end flag. + w(0x1290, 125)?; + w(0x1294, 1)?; + w(0x1aa0, 1)?; + w(0x3aa4, F_5)?; + Ok(()) +} + +/// The tail's sensor keys from the six rows (which [`from_file`] fills). +fn tail(out: &mut [u8]) -> R<()> { + let mut g = 0usize; + for row in 0..SENSOR_ROW_COUNT { + let key = get32(out, SENSOR_ROWS + 12 * row)?; + match (key >> 24) as u8 { + b'g' => { + put32(out, SENSOR_G_KEYS + 4 * g, key)?; + g += 1; + } + b'r' => { + put32(out, SENSOR_R_KEY, key)?; + put32(out, SENSOR_R_COUNT, 1)?; + } + b'f' => { + put32(out, SENSOR_F_KEY, key)?; + put32(out, SENSOR_F_COUNT, 1)?; + } + _ => return Err("a sensor row has an unknown kind"), + } + } + if g > 4 { + return Err("more than four g sensor rows"); + } + put32(out, SENSOR_G_MASK, (1u32 << g) - 1)?; + put32(out, HWDATA_A + 0x6d80, 1)?; + put32(out, HWDATA_A + 0x6d84, 1)?; + Ok(()) +} + +/// Copies the [`FROM_FILE`] words of `file` (the board file's record) into `out`. +pub(crate) fn from_file(out: &mut [u8], file: &[u8]) -> R<()> { + for &at in FROM_FILE.iter() { + put32(out, at, get32(file, at)?)?; + } + Ok(()) +} + +/// The first word at which the built record differs from the file's, except the [`UNNEEDED`] +/// words, where the file's value is accepted as long as the built word is zero. +pub(crate) fn cross_check(built: &[u8], file: &[u8]) -> Option<(usize, u32, u32)> { + let word = |s: &[u8], at: usize| -> u32 { + let mut w = [0u8; 4]; + for (i, out) in w.iter_mut().enumerate() { + *out = s.get(at + i).copied().unwrap_or(0); + } + u32::from_le_bytes(w) + }; + (0..built.len().max(file.len())) + .step_by(4) + .map(|at| (at, word(built, at), word(file, at))) + .find(|&(at, b, f)| b != f && !(b == 0 && UNNEEDED.contains(&at))) +} + +/// Builds the record into `out` (zeroed first) from the device-tree inputs; the [`FROM_FILE`] +/// words must have been copied in first ([`from_file`]) or are left as they are. +pub(crate) fn build(out: &mut [u8], i: &Inputs<'_>) -> R<()> { + if out.len() != SIZE { + return Err("record of another size"); + } + let mut keep = [0u32; FROM_FILE.len()]; + for (k, &at) in FROM_FILE.iter().enumerate() { + keep[k] = get32(out, at)?; + } + out.fill(0); + let t = tables(i.main)?; + hwdata_b(out, i, &t)?; + hwdata_a(out, i, &t)?; + // The kept words win over what the rules put there (the relative powers, the masks). + for (k, &at) in FROM_FILE.iter().enumerate() { + put32(out, at, keep[k])?; + } + tail(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn get(b: &[u8], o: usize) -> u32 { + get32(b, o).unwrap() + } + + fn opp(mhz: u32, mv: [u32; 4], mw: u32) -> Opp { + Opp { + mhz, + mv, + cells: 4, + mw, + } + } + + /// Operating points shaped like the J516C's: eight voltages, the upper five with two states. + fn main_opps() -> Vec { + let mut v = vec![opp(0, [125; 4], 0)]; + let groups: [(u32, [u32; 4], &[u32]); 8] = [ + (605, [605, 605, 615, 615], &[338]), + (680, [680, 680, 665, 665], &[618]), + (730, [730, 730, 715, 715], &[796]), + (770, [770, 770, 755, 755], &[832, 924]), + (800, [800, 800, 785, 785], &[952, 1056]), + (860, [855, 860, 845, 845], &[1064, 1182]), + (930, [915, 930, 915, 915], &[1182, 1312]), + (955, [940, 955, 940, 940], &[1242, 1380]), + ]; + for (_, mv, mhz) in groups { + for &m in mhz { + v.push(opp(m, mv, m * 40)); + } + } + v + } + + fn props() -> [u32; PROPS.len()] { + let mut p = [0u32; PROPS.len()]; + p[PERIOD_MS] = 8; + p[BASE_PSTATE] = 1; + p[MIN_SRAM_UV] = 815000; + p[CSAFR_MIN_SRAM_UV] = 815000; + p[AVG_TC_MS] = 32; + p[AVG_KI] = 0x41480000; + p[AVG_KP] = 0x3e99999a; + p[AVG_MIN_DUTY] = 40; + p[AVG_TGT_TC] = 1; + p[FD_KI] = 0x443b8000; + p[FD_KP] = 0x42080000; + p[PERF_TC] = 5; + p[PERF_TC2] = 200; + p[PERF_RESET] = 6; + p[PPM_TC_MS] = 34; + p[PPM_KI] = 0x4198cccd; + p[PPM_KP] = 0x3e99999a; + p[PWR_TC] = 313; + p[PWR_MIN_DUTY] = 40; + p[AIC_CLKS] = 200000; + p[SE_TC] = 9; + p[SE_TC1] = 3; + p[SE_KI] = (-50.0f32).to_bits(); + p[SE_KI1] = (-100.0f32).to_bits(); + p[SE_TARGET] = 1400; + p + } + + fn inputs<'a>(main: &'a [Opp], cs: &'a [Opp], slots: &'a [IoSlot]) -> Inputs<'a> { + Inputs { + props: props(), + zones: &[], + main, + cs, + afr: cs, + slots, + empty_writable: &[4, 6], + ttbat: 0x10bfffb8000, + usc_base: 0x10_0000_0000, + user_end: 0x2ff_ffff_8000, + timestamps: 0xfffffc2ffc000000, + max_power_mw: 54321, + } + } + + #[test] + fn factors() { + assert_eq!(F_1, 1.0f32.to_bits()); + assert_eq!(F_0_2, 0.2f32.to_bits()); + assert_eq!(F_0_8, 0.8f32.to_bits()); + assert_eq!(F_0_95, 0.95f32.to_bits()); + assert_eq!(F_1_02, 1.02f32.to_bits()); + assert_eq!(F_5, 5.0f32.to_bits()); + assert_eq!(F_95, 95.0f32.to_bits()); + assert_eq!(F_100, 100.0f32.to_bits()); + assert_eq!(F_8000, 8000.0f32.to_bits()); + assert_eq!(F_65536, 65536.0f32.to_bits()); + // The filter complement is the correctly rounded (n - 1) / n, also where 1 - 1/n is + // a rounding tie. + assert_eq!(complement(3).unwrap(), (2.0f32 / 3.0).to_bits()); + assert_eq!(complement(313).unwrap(), (312.0f32 / 313.0).to_bits()); + assert_eq!(inv(9).unwrap(), (1.0f32 / 9.0).to_bits()); + assert!(inv(0).is_err()); + } + + #[test] + fn unneeded() { + // No UNNEEDED word is a FROM_FILE word; the cross-check accepts the file's value there + // only against a zero built word, and nothing else. + assert!(UNNEEDED.iter().all(|at| !FROM_FILE.contains(at))); + assert!(UNNEEDED.iter().all(|&at| at % 4 == 0 && at + 4 <= SIZE)); + let mut file = vec![0u8; SIZE]; + for (k, &at) in UNNEEDED.iter().enumerate() { + put32(&mut file, at, 0x2000 + k as u32).unwrap(); + } + let built = vec![0u8; SIZE]; + assert_eq!(cross_check(&built, &file), None); + let mut built = built; + put32(&mut built, UNNEEDED[0], 1).unwrap(); + assert_eq!(cross_check(&built, &file), Some((UNNEEDED[0], 1, 0x2000))); + let mut built = vec![0u8; SIZE]; + put32(&mut built, 0x10, 5).unwrap(); + assert_eq!(cross_check(&built, &file), Some((0x10, 5, 0))); + } + + #[test] + fn layout() { + assert_eq!(a(0x8b8), HWDATA_A + 0x8b8); + assert_eq!(a(0x8bc), HWDATA_A + 0x8c4); + assert_eq!(a(0x938), HWDATA_A + 0x940); + assert_eq!(a(0xbe0), HWDATA_A + 0xde8); + assert_eq!(a(0x1288), HWDATA_A + 0x1490); + assert_eq!(a(0x1290), HWDATA_A + 0x14a0); + assert_eq!(a(0x1a98), HWDATA_A + 0x24a8); + assert_eq!(a(0x1aa0), HWDATA_A + 0x24b8); + assert_eq!(a(0x3aa4), HWDATA_A + 0x64bc); + assert_eq!(MAX_POWER, a(0x6a4)); + // FROM_FILE is sorted, unique and inside the record. + assert!(FROM_FILE.windows(2).all(|w| w[0] < w[1])); + assert!(FROM_FILE.iter().all(|&o| o % 4 == 0 && o + 4 <= SIZE)); + } + + #[test] + fn dvfs_tables() { + let main = main_opps(); + let t = tables(&main).unwrap(); + assert_eq!(t.len, 9); + assert_eq!(&t.primary[..9], &[0, 1, 2, 3, 5, 7, 9, 11, 13]); + assert_eq!(&t.secondary[..9], &[0, 1, 2, 3, 4, 6, 8, 10, 12]); + // One state: nothing to sort. + assert!(tables(&main[..1]).is_err()); + // Frequency falling with voltage. + let mut bad = main.clone(); + bad[2].mhz = 300; + assert!(tables(&bad).is_err()); + // Two states at one voltage with different cluster voltages. + let mut bad = main.clone(); + bad[5].mv[2] = 760; + assert!(tables(&bad).is_err()); + // A cluster whose voltage does not rise. + let mut bad = main.clone(); + bad[13].mv[3] = 915; + assert!(tables(&bad).is_err()); + } + + #[test] + fn record_words() { + let main = main_opps(); + let cs: Vec = [24u32, 480, 624, 810, 1024, 1140, 1236] + .iter() + .zip([635, 635, 680, 720, 790, 855, 875]) + .map(|(&mhz, mv)| Opp { + mhz, + mv: [mv, 0, 0, 0], + cells: 1, + mw: 0, + }) + .collect(); + let slots = [ + IoSlot { + slot: 0, + pa: 0x408d00000, + va: 0xfffffc2068000000, + total: 0x144000, + element: 0x144000, + writable: true, + }, + IoSlot { + slot: 1, + pa: 0x20e101000, + va: 0xfffffc2068149000, + total: 0x4000, + element: 0x4000, + writable: false, + }, + ]; + let i = inputs(&main, &cs, &slots); + let mut r = vec![0u8; SIZE]; + // FROM_FILE words survive the build; the sensor rows feed the tail. + for (k, &at) in FROM_FILE.iter().enumerate() { + put32(&mut r, at, 0x1000 + k as u32).unwrap(); + } + // The file's maximum power is what the input repeats. + put32(&mut r, MAX_POWER, 54321).unwrap(); + let rows = [b"RT0g", b"RT1g", b"RT2g", b"RT3g", b"RT0r", b"RT0f"]; + for (k, row) in rows.iter().enumerate() { + put32(&mut r, SENSOR_ROWS + 12 * k, u32::from_le_bytes(**row)).unwrap(); + } + build(&mut r, &i).unwrap(); + let good = r.clone(); + assert_eq!(get(&r, 0x1060), 0x1000); + assert_eq!(get(&r, 0x30f0), 0); + // Identity, IOMapping records, flags. + assert_eq!(get(&r, 0xa28), 0x6031); + assert_eq!(get(&r, 0x640), 0x08d00000); + assert_eq!(get(&r, 0x644), 4); + assert_eq!(get(&r, 0x648), 0x68000000); + assert_eq!(get(&r, 0x658), 1); + assert_eq!(get(&r, 0x660), 0x0e101000); + assert_eq!(get(&r, 0x678), 0); + assert_eq!(get(&r, 0x640 + 32 * 4 + 0x18), 1); + assert_eq!(get(&r, 0x640 + 32 * 5 + 0x18), 0); + assert_eq!(get(&r, 0xb44), 0xfffb8000); + assert_eq!(get(&r, 0xb48), 0x10b); + assert_eq!(get(&r, 0xb58), 8); + // Tables: A frequencies, B frequencies, per-cluster lanes, SRAM floor, index maps. + assert_eq!(get(&r, 0xb5c + 4 * 8), 1380); + assert_eq!(get(&r, 0xf9c + 4 * 8), 1242); + assert_eq!(get(&r, 0x1350 + 4 * 4), 832); + assert_eq!(get(&r, 0xb9c + 0x20 + 4 * 2), 615); + assert_eq!(get(&r, 0xb9c + 0x20 + 4 * 5), 605); + assert_eq!(get(&r, 0xd9c + 0x20 + 4 * 2), 815); + assert_eq!(get(&r, 0x1390 + 0x20 * 8 + 4 * 1), 955); + assert_eq!(get(&r, 0x10dc + 4 * 8), 13); + assert_eq!(get(&r, 0x111c + 4 * 8), 12); + assert_eq!(get(&r, 0x107c), 100); + assert_eq!(get(&r, 0x109c + 4 * 8), 100); + // CS table: top twice, then the arrays with the SRAM floor. + assert_eq!(get(&r, 0x115c), 6); + assert_eq!(get(&r, 0x1160), 6); + assert_eq!(get(&r, 0x1164), 24); + assert_eq!(get(&r, 0x11a4), 635); + assert_eq!(get(&r, 0x1224), 815); + assert_eq!(get(&r, 0x12a4), 6); + assert_eq!(get(&r, 0x12ac), 24); + // HardwareDataA: scaled states, the maximum power and its derivatives, filters, SE. + assert_eq!(get(&r, a(0x4c)), 800); + assert_eq!(get(&r, a(0x680)), 54321.0f32.to_bits()); + assert_eq!(get(&r, a(0x68c)), (-800.0f32 / 54321.0).to_bits()); + assert_eq!(get(&r, a(0x690)), (40i32 - 800) as u32); + assert_eq!(get(&r, MAX_POWER), 54321); + assert_eq!(get(&r, a(0x6fc)), (3.0f32 / 4.0).to_bits()); + assert_eq!(get(&r, a(0x74c)), 4 * 8 * 24000); + assert_eq!(get(&r, a(0x7d4)), (7.0f32 / 0.95).to_bits()); + assert_eq!(get(&r, a(0x844)), 1380); + assert_eq!(get(&r, a(0x8d8)), 0x40c00001); + assert_eq!(get(&r, a(0x8e8)), 0x42080000); + assert_eq!(get(&r, a(0xe88)), 54321); + assert_eq!(get(&r, a(0xf88)), 0x3f400000); + assert_eq!(get(&r, a(0xfd8)), 4 * 8 * 24000); + assert_eq!(get(&r, a(0x10b4 + 0x4c)), (8.0f32 / 9.0).to_bits()); + assert_eq!(get(&r, a(0x10b4 + 0x5c)), (-50.0f32 * 0.008).to_bits()); + assert_eq!(get(&r, a(0x10b4 + 0x9c)), 9 * 192000); + assert_eq!(get(&r, a(0x3aa4)), F_5); + // Tail keys. + assert_eq!(get(&r, SENSOR_G_KEYS), u32::from_le_bytes(*b"RT0g")); + assert_eq!(get(&r, SENSOR_G_KEYS + 12), u32::from_le_bytes(*b"RT3g")); + assert_eq!(get(&r, SENSOR_G_MASK), 0xf); + assert_eq!(get(&r, SENSOR_R_KEY), u32::from_le_bytes(*b"RT0r")); + assert_eq!(get(&r, SENSOR_F_COUNT), 1); + // Refusals. + let mut short = vec![0u8; SIZE - 4]; + assert!(build(&mut short, &i).is_err()); + let mut j = inputs(&main, &cs, &slots); + j.props[PERIOD_MS] = 0; + assert!(build(&mut r, &j).is_err()); + let mut j = inputs(&main, &cs, &slots); + j.empty_writable = &[0]; + assert!(build(&mut r, &j).is_err()); + let mut j = inputs(&main, &cs, &slots); + j.max_power_mw = 0; + assert!(build(&mut r, &j).is_err()); + let mut j = inputs(&main, &cs, &slots); + j.zones = &[100, 101, 1]; + assert!(build(&mut r, &j).is_err()); + // Device-tree values whose arithmetic leaves u32 are refused, not wrapped or panicking: + // each on a copy of the record that built, so that nothing else refuses it first. + let refused = |j: &Inputs<'_>| { + let mut x = good.clone(); + build(&mut x, j) + }; + assert_eq!(refused(&i), Ok(())); + for (prop, value) in [ + (AVG_TGT_TC, 0x4000_0000), + (PPM_TC_MS, u32::MAX), + (AVG_TC_MS, u32::MAX), + (SE_TC, 0x2000_0000), + (SE_TC1, 0x2000_0000), + (FD_DELTA, 0x0300_0000), + ] { + let mut j = inputs(&main, &cs, &slots); + j.props[prop] = value; + assert_eq!(refused(&j), Err(OVERFLOW), "prop {prop} = {value:#x}"); + } + let mut j = inputs(&main, &cs, &slots); + j.zones = &[5000, 200, 0x4000_0000]; + assert_eq!(refused(&j), Err(OVERFLOW)); + let mut skewed = main.clone(); + skewed[1].mw = u32::MAX; + skewed[13].mw = 1; + assert_eq!( + refused(&inputs(&skewed, &cs, &slots)), + Err("a relative power does not fit its u32 word") + ); + // The admission cross-check as initdata::blob() composes it: the FROM_FILE words from + // the file, the rest built, then the first differing word against the file. A file the + // inputs reproduce passes; a rule word the file holds differently is found at its + // offset; a FROM_FILE word follows the file and is never a difference. + let first_difference = super::super::words::first_difference; + let checked = |file: &[u8]| { + let mut built = vec![0u8; SIZE]; + from_file(&mut built, file).unwrap(); + build(&mut built, &i).unwrap(); + (first_difference(&built, file), built) + }; + assert_eq!(checked(&good).0, None); + let mut file = good.clone(); + put32(&mut file, a(0x4c), 801).unwrap(); + assert_eq!(checked(&file).0, Some((a(0x4c), 800, 801))); + let mut file = good.clone(); + assert!(FROM_FILE.contains(&0x1064)); + put32(&mut file, 0x1064, get(&good, 0x1064) ^ 0x5a).unwrap(); + let (difference, built) = checked(&file); + assert_eq!(difference, None); + assert_eq!(get(&built, 0x1064), get(&good, 0x1064) ^ 0x5a); + } + + // --- The fixture: a saved copy of a J516C's device tree and its private board file. --- + + fn be32(b: &[u8], o: usize) -> u32 { + u32::from_be_bytes(b[o..o + 4].try_into().unwrap()) + } + + /// All nodes of a flattened device tree: path -> properties. + fn fdt(dtb: &[u8]) -> Vec<(String, Vec<(String, Vec)>)> { + assert_eq!(be32(dtb, 0), 0xd00dfeed); + let strings = be32(dtb, 12) as usize; + let mut at = be32(dtb, 8) as usize; + let mut path: Vec = Vec::new(); + let mut out: Vec<(String, Vec<(String, Vec)>)> = Vec::new(); + loop { + let token = be32(dtb, at); + at += 4; + match token { + 1 => { + let end = dtb[at..].iter().position(|&b| b == 0).unwrap(); + path.push(String::from_utf8(dtb[at..at + end].to_vec()).unwrap()); + at = (at + end + 1).next_multiple_of(4); + out.push((path.join("/"), Vec::new())); + } + 2 => { + path.pop(); + } + 3 => { + let len = be32(dtb, at) as usize; + let name_off = strings + be32(dtb, at + 4) as usize; + let name_end = dtb[name_off..].iter().position(|&b| b == 0).unwrap(); + let name = + String::from_utf8(dtb[name_off..name_off + name_end].to_vec()).unwrap(); + let value = dtb[at + 8..at + 8 + len].to_vec(); + at = (at + 8 + len).next_multiple_of(4); + let node = path.join("/"); + out.iter_mut() + .rev() + .find(|(p, _)| *p == node) + .unwrap() + .1 + .push((name, value)); + } + 4 => {} + 9 => return out, + _ => panic!("fdt token {token}"), + } + } + } + + fn prop<'a>(props: &'a [(String, Vec)], name: &str) -> Option<&'a [u8]> { + props + .iter() + .find(|(n, _)| n == name) + .map(|(_, v)| v.as_slice()) + } + + fn opp_table( + nodes: &[(String, Vec<(String, Vec)>)], + phandle: u32, + cells: usize, + ) -> Vec { + let (table, _) = nodes + .iter() + .find(|(_, p)| prop(p, "phandle").map(|v| be32(v, 0)) == Some(phandle)) + .unwrap(); + let mut rows: Vec<(String, Opp)> = nodes + .iter() + .filter(|(p, _)| { + p.starts_with(&format!("{table}/")) + && p.matches('/').count() == table.matches('/').count() + 1 + }) + .map(|(p, props)| { + let hz = u64::from_be_bytes(prop(props, "opp-hz").unwrap().try_into().unwrap()); + let uv = prop(props, "opp-microvolt").unwrap(); + assert_eq!(uv.len(), 4 * cells); + let mut mv = [0u32; CLUSTERS]; + for (c, m) in mv.iter_mut().enumerate().take(cells) { + *m = be32(uv, 4 * c).div_ceil(1000); + } + let mw = prop(props, "opp-microwatt").map_or(0, |w| be32(w, 0) / 1000); + ( + p.clone(), + Opp { + mhz: (hz / 1_000_000) as u32, + mv, + cells, + mw, + }, + ) + }) + .collect(); + rows.sort_by(|x, y| x.0.cmp(&y.0)); + rows.into_iter().map(|(_, o)| o).collect() + } + + /// No GPU node property value panics the builder (CONFIG_RUST_OVERFLOW_CHECKS is on in our + /// kernels): each of the properties at the u32 and single-precision boundaries, on a copy + /// of a seed record that builds. A value may be refused; it must not panic. + #[test] + fn device_tree_u32_boundaries_do_not_panic() { + let main = main_opps(); + let cs = [Opp { + mhz: 24, + mv: [635, 0, 0, 0], + cells: 1, + mw: 0, + }]; + let mut seed = vec![0u8; SIZE]; + put32(&mut seed, MAX_POWER, 54321).unwrap(); + for (k, key) in [b"RT0g", b"RT1g", b"RT2g", b"RT3g", b"RT0r", b"RT0f"] + .iter() + .enumerate() + { + put32(&mut seed, SENSOR_ROWS + 12 * k, u32::from_le_bytes(**key)).unwrap(); + } + assert_eq!(build(&mut seed, &inputs(&main, &cs, &[])), Ok(())); + for prop in 0..PROPS.len() { + for value in [ + 0, 1, 7, 8, 31, 0x3f80_0000, 0x4000_0000, 0x7f80_0000, 0x7fc0_0000, 0x8000_0000, + u32::MAX, + ] { + let mut i = inputs(&main, &cs, &[]); + i.props[prop] = value; + let mut image = seed.clone(); + let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + build(&mut image, &i) + })); + assert!(built.is_ok(), "prop {} value {:#x}", prop, value); + } + } + } + + /// Builder on the saved device tree + the file's FROM_FILE words == the file's hardware + /// record, byte for byte. Needs `G15_J516C_FIXTURES=` with `j516c.dtb` and + /// `t6031-j516c-board.bin` (off the tree): ignored by default, `--ignored` runs it. + #[test] + #[ignore = "needs the off-tree J516C fixtures (G15_J516C_FIXTURES)"] + fn j516c_fixture() { + let dir = std::env::var_os("G15_J516C_FIXTURES") + .expect("G15_J516C_FIXTURES names the directory with j516c.dtb and the board file"); + let dir = std::path::Path::new(&dir); + let dtb = std::fs::read(dir.join("j516c.dtb")).unwrap(); + let blob = std::fs::read(dir.join("t6031-j516c-board.bin")).unwrap(); + assert_eq!(&blob[..8], b"T6031BRD"); + let at = 16 + 3 * 8; + let file = &blob[at..at + SIZE]; + + let nodes = fdt(&dtb); + let (_, gpu) = nodes + .iter() + .find(|(_, p)| { + prop(p, "compatible") + .is_some_and(|c| c.split(|&b| b == 0).any(|s| s == b"apple,agx-t6031")) + }) + .expect("a T6031 GPU node"); + let mut props = [0u32; PROPS.len()]; + for (v, (name, default)) in props.iter_mut().zip(PROPS.iter()) { + *v = match prop(gpu, name.to_str().unwrap()) { + Some(b) => be32(b, 0), + None => default.unwrap_or_else(|| panic!("GPU node has no {name:?}")), + }; + } + let zones: Vec = prop(gpu, "apple,power-zones") + .map(|b| b.chunks(4).map(|c| be32(c, 0)).collect()) + .unwrap_or_default(); + let main = opp_table( + &nodes, + be32(prop(gpu, "operating-points-v2").unwrap(), 0), + 4, + ); + let cs = opp_table(&nodes, be32(prop(gpu, "apple,cs-opp").unwrap(), 0), 1); + let afr = opp_table(&nodes, be32(prop(gpu, "apple,afr-opp").unwrap(), 0), 1); + assert_eq!(main.len(), PERF_STATES); + // The ttbs region: the first memory-region phandle's reserved-memory node. + let regions = prop(gpu, "memory-region").unwrap(); + let (_, ttbs) = nodes + .iter() + .find(|(_, p)| prop(p, "phandle").map(|v| be32(v, 0)) == Some(be32(regions, 0))) + .unwrap(); + let reg = prop(ttbs, "reg").unwrap(); + let ttbat = u64::from_be_bytes(reg[..8].try_into().unwrap()); + // The IOMapping slots: the T6031 table's addresses and sizes with the file's VAs (the + // VAs are the driver's; the layout packs them from a base with a page gap). + let slots_table: [(u8, u64, u32, u32, bool); 17] = [ + (0, 0x408d00000, 0x144000, 0x144000, true), + (1, 0x20e100000, 0x4000, 0x4000, false), + (2, 0x292414000, 0x4000, 0x4000, true), + (3, 0x408000000, 0x20000, 0x20000, true), + (7, 0x290444000, 0x4000, 0x4000, false), + (9, 0x408e08000, 0x8000, 0x8000, true), + (11, 0x220000000, 8 * 0xd8000, 0xd8000, true), + (12, 0x29244c000, 0x4000, 0x4000, false), + (18, 0x2903d0000, 0x4000, 0x4000, true), + (19, 0x2903c0000, 0x4000, 0x4000, false), + (20, 0x2903d8000, 0x4000, 0x4000, true), + (21, 0x408eb4000, 0x4000, 0x4000, true), + (24, 0x409000000, 0x8000, 0x8000, true), + (25, 0x3c945c000, 0x4000, 0x4000, true), + (26, 0x290400000, 0x8000, 0x8000, false), + (28, 0x2a4dc0000, 0x24000, 0x24000, false), + (29, 0x408e1c000, 0x4000, 0x4000, false), + ]; + let mut va = 0xfffffc2068000000u64; + let slots: Vec = slots_table + .iter() + .map(|&(slot, pa, total, element, writable)| { + let delta = pa & 0x3fff; + let s = IoSlot { + slot, + pa, + va: va + delta, + total, + element, + writable, + }; + va += (delta + u64::from(total) + 0x3fff) & !0x3fff; + va += 0x4000; + s + }) + .collect(); + let i = Inputs { + props, + zones: &zones, + main: &main, + cs: &cs, + afr: &afr, + slots: &slots, + empty_writable: &[4, 6, 8, 10, 13, 14, 15, 16, 17], + ttbat, + usc_base: 0x10_0000_0000, + user_end: 0x2ff_ffff_8000, + timestamps: 0xfffffc2ffc000000, + max_power_mw: get(file, MAX_POWER), + }; + let mut built = vec![0u8; SIZE]; + from_file(&mut built, file).unwrap(); + build(&mut built, &i).unwrap(); + assert_eq!(cross_check(&built, file), None, "(offset, built, file)"); + for &at in UNNEEDED.iter() { + assert_eq!(get(&built, at), 0); + } + } +} diff --git a/drivers/gpu/drm/asahi/g15/board/template.rs b/drivers/gpu/drm/asahi/g15/board/template.rs new file mode 100644 index 00000000000000..3a53939ae08c0d --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/board/template.rs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Sparse board-image templates: 16-byte lines over a zero image. +//! +//! Core-only (no `kernel` imports): this file is compiled by the host test harness as well. +//! The hash check of an expanded template is the kernel side's ([`super::expand`]). + +/// One template line: 16 bytes at `offset`. +pub(crate) struct Line { + pub(crate) offset: u32, + pub(crate) data: [u8; 16], +} + +/// A sparse template. +pub(crate) struct Template { + pub(crate) size: usize, + pub(crate) lines: &'static [Line], + pub(crate) sha256: [u8; 32], +} + +/// Fills the first `template.size` bytes of `out` with the template: zero, then its lines. `Err` +/// when `out` is too short or a line starts past the end. +pub(crate) fn fill(template: &Template, out: &mut [u8]) -> Result<(), ()> { + let out = out.get_mut(..template.size).ok_or(())?; + out.fill(0); + for line in template.lines { + let offset = line.offset as usize; + if offset >= template.size { + return Err(()); + } + let n = 16.min(template.size - offset); + out[offset..offset + n].copy_from_slice(&line.data[..n]); + } + Ok(()) +} diff --git a/drivers/gpu/drm/asahi/g15/board/words.rs b/drivers/gpu/drm/asahi/g15/board/words.rs new file mode 100644 index 00000000000000..4c5082465d428f --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/board/words.rs @@ -0,0 +1,653 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The J516C Globals and Power images from the device tree. +//! +//! The 2419 firmware's Globals (15,868 bytes) and Power (2,292 bytes) are, on the J516C, the G15S +//! templates ([`super::data`]) with these words of its own: +//! +//! - The GPU node's power words ([`PROPS`]): `apple,idleoff-standby-timer` (Globals +0x7a8); +//! in Power the average-power controller (+0x10 filter periods = `apple,avg-power-filter-tc-ms` +//! / `apple,power-sample-period`, +0x14 `apple,avg-power-ki-only` x period, +0x18 +//! `apple,avg-power-kp`, +0x1c `apple,avg-power-min-duty-cycle`, +0x20 +//! `apple,avg-power-target-filter-tc`), the power zones (+0xc count, +0x24 up to five +//! {target, target - offset, filter} rows of `apple,power-zones`), the fast-die controller +//! (+0xb8 `apple,fast-die0-proportional-gain`, +0xbc `apple,fast-die0-integral-gain` x period) +//! and the PPM controller (+0xd4 `apple,ppm-kp`, +0xd8 `apple,ppm-ki` x period). A gain x +//! period is the IEEE single product of the gain and `period_ms / 1000`, each rounded to +//! single ([`f32_mul`], [`f32_div`]). +//! - The maximum power: the hardware record's HardwareDataA +0x6a4 word (Globals +0x78, Power +//! +0xd0). The G15S template carries its own machine's there too. +//! - The performance-state cap: 100 x the top firmware DVFS state, 8 (Globals +0x7c, +0x80, +//! +0x8c). +//! - Words the device tree does not carry: command submission enabled at initdata (Globals +//! +0x70 = 1; the G15S template has 0), the start path's +0x980 = 100 (written again at +//! start on every SoC), the soft-fault word (u32 3 at the unaligned +0xdf9 of the G15S image) +//! at +0x1201, where the G15C Globals has it, and the Power +0x244 flag = 1. +//! +//! Core-only (no `kernel` imports): this file is compiled by the host test harness as well. + +use core::ffi::CStr; + +pub(crate) const GLOBALS_SIZE: usize = 15868; +pub(crate) const POWER_SIZE: usize = 2292; + +/// HardwareDataA in the hardware record (= `fw::initdata::hwdata::HWDATA_A`) and its maximum +/// power word (= `fw::initdata::hwdata::MAX_POWER_A`). +pub(crate) const HWDATA_A: usize = 0x4580; +pub(crate) const HWDATA_A_MAX_POWER: usize = 0x6a4; + +/// The top firmware DVFS state (= `board::DVFS_STATES - 1`). +pub(crate) const TOP_STATE: u32 = 8; + +/// Globals words. +mod globals { + pub(super) const COMMAND_SUBMISSION: usize = 0x70; + pub(super) const MAX_POWER: usize = 0x78; + /// The power-interface targets 1 and 2 and the performance-state cap. + pub(super) const STATE_CAP: [usize; 3] = [0x7c, 0x80, 0x8c]; + pub(super) const STANDBY_TIMER: usize = 0x7a8; + pub(super) const UNK_980: usize = 0x980; + /// The soft-fault word: unaligned, in the G15S and the G15C image. + pub(super) const SOFT_FAULT_G15S: usize = 0xdf9; + pub(super) const SOFT_FAULT_G15C: usize = 0x1201; + pub(super) const SOFT_FAULT: u32 = 3; +} + +/// Power words. +mod power { + pub(super) const ZONE_COUNT: usize = 0x0c; + pub(super) const AVG_FILTER_PERIODS: usize = 0x10; + pub(super) const AVG_KI_DT: usize = 0x14; + pub(super) const AVG_KP: usize = 0x18; + pub(super) const AVG_MIN_DUTY_CYCLE: usize = 0x1c; + pub(super) const AVG_TARGET_FILTER_TC: usize = 0x20; + pub(super) const ZONES: usize = 0x24; + pub(super) const ZONE_STRIDE: usize = 12; + pub(super) const FAST_DIE_KP: usize = 0xb8; + pub(super) const FAST_DIE_KI_DT: usize = 0xbc; + pub(super) const MAX_POWER: usize = 0xd0; + pub(super) const PPM_KP: usize = 0xd4; + pub(super) const PPM_KI_DT: usize = 0xd8; + pub(super) const FLAG_244: usize = 0x244; +} + +/// The GPU node's power properties, each one u32 (gains are IEEE single bits), in the order of +/// [`PowerWords::values`]. +pub(crate) const PROPS: [&CStr; 11] = [ + c"apple,power-sample-period", + c"apple,idleoff-standby-timer", + c"apple,avg-power-filter-tc-ms", + c"apple,avg-power-ki-only", + c"apple,avg-power-kp", + c"apple,avg-power-min-duty-cycle", + c"apple,avg-power-target-filter-tc", + c"apple,fast-die0-proportional-gain", + c"apple,fast-die0-integral-gain", + c"apple,ppm-kp", + c"apple,ppm-ki", +]; +pub(crate) const PERIOD_MS: usize = 0; +pub(crate) const STANDBY_TIMER: usize = 1; +pub(crate) const AVG_POWER_FILTER_TC_MS: usize = 2; +pub(crate) const AVG_POWER_KI_ONLY: usize = 3; +pub(crate) const AVG_POWER_KP: usize = 4; +pub(crate) const AVG_POWER_MIN_DUTY_CYCLE: usize = 5; +pub(crate) const AVG_POWER_TARGET_FILTER_TC: usize = 6; +pub(crate) const FAST_DIE0_PROPORTIONAL_GAIN: usize = 7; +pub(crate) const FAST_DIE0_INTEGRAL_GAIN: usize = 8; +pub(crate) const PPM_KP: usize = 9; +pub(crate) const PPM_KI: usize = 10; + +/// The power zones, u32 triples {target, offset, filter time constant}; at most five. +pub(crate) const ZONES: &CStr = c"apple,power-zones"; +pub(crate) const MAX_ZONES: usize = 5; + +/// The GPU node's power words. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct PowerWords { + pub(crate) values: [u32; PROPS.len()], + pub(crate) zones: [[u32; 3]; MAX_ZONES], + pub(crate) zone_count: u32, +} + +impl PowerWords { + /// `values` in [`PROPS`] order and the `apple,power-zones` cells. + pub(crate) fn new(values: [u32; PROPS.len()], zones: &[u32]) -> Result { + if values[PERIOD_MS] == 0 { + return Err("the power sample period is 0"); + } + if zones.len() % 3 != 0 || zones.len() > 3 * MAX_ZONES { + return Err("the power zones are not up to five u32 triples"); + } + let mut out = Self { + values, + zones: [[0; 3]; MAX_ZONES], + zone_count: (zones.len() / 3) as u32, + }; + for (row, cells) in out.zones.iter_mut().zip(zones.chunks_exact(3)) { + row.copy_from_slice(cells); + } + Ok(out) + } + + /// The sample period in seconds, IEEE single bits. + fn period_s(&self) -> Result { + f32_div(f32_from_u32(self.values[PERIOD_MS]), f32_from_u32(1000)) + .ok_or("the power sample period has no single-precision quotient") + } + + /// A gain x the sample period, IEEE single bits. + fn per_period(&self, gain: usize) -> Result { + f32_mul(self.values[gain], self.period_s()?) + .ok_or("a gain is not a finite normal single, or its product with the period is not") + } +} + +fn get32(b: &[u8], offset: usize) -> Result { + let w = b.get(offset..offset + 4).ok_or("image too short")?; + Ok(u32::from_le_bytes([w[0], w[1], w[2], w[3]])) +} + +fn put32(b: &mut [u8], offset: usize, value: u32) -> Result<(), &'static str> { + b.get_mut(offset..offset + 4) + .ok_or("image too short")? + .copy_from_slice(&value.to_le_bytes()); + Ok(()) +} + +/// Writes the J516C words into `image`, the expanded G15S Globals template. +pub(crate) fn globals( + image: &mut [u8], + max_power_mw: u32, + w: &PowerWords, +) -> Result<(), &'static str> { + if image.len() != GLOBALS_SIZE { + return Err("Globals image of another size"); + } + put32(image, globals::COMMAND_SUBMISSION, 1)?; + put32(image, globals::MAX_POWER, max_power_mw)?; + for at in globals::STATE_CAP { + put32(image, at, 100 * TOP_STATE)?; + } + put32(image, globals::STANDBY_TIMER, w.values[STANDBY_TIMER])?; + put32(image, globals::UNK_980, 100)?; + if get32(image, globals::SOFT_FAULT_G15S)? != globals::SOFT_FAULT { + return Err("Globals template without the soft-fault word at its G15S place"); + } + put32(image, globals::SOFT_FAULT_G15S, 0)?; + put32(image, globals::SOFT_FAULT_G15C, globals::SOFT_FAULT)?; + Ok(()) +} + +/// Writes the J516C words into `image`, the expanded G15S Power template. +pub(crate) fn power( + image: &mut [u8], + max_power_mw: u32, + w: &PowerWords, +) -> Result<(), &'static str> { + if image.len() != POWER_SIZE { + return Err("Power image of another size"); + } + let periods = w.values[AVG_POWER_FILTER_TC_MS] / w.values[PERIOD_MS]; + if periods == 0 { + return Err("the average-power filter time constant is shorter than the sample period"); + } + put32(image, power::ZONE_COUNT, w.zone_count)?; + put32(image, power::AVG_FILTER_PERIODS, periods)?; + put32(image, power::AVG_KI_DT, w.per_period(AVG_POWER_KI_ONLY)?)?; + put32(image, power::AVG_KP, w.values[AVG_POWER_KP])?; + put32( + image, + power::AVG_MIN_DUTY_CYCLE, + w.values[AVG_POWER_MIN_DUTY_CYCLE], + )?; + put32( + image, + power::AVG_TARGET_FILTER_TC, + w.values[AVG_POWER_TARGET_FILTER_TC], + )?; + for (i, zone) in w.zones.iter().enumerate() { + let at = power::ZONES + power::ZONE_STRIDE * i; + let (target, offset, filter) = (zone[0], zone[1], zone[2]); + let target_off = target + .checked_sub(offset) + .ok_or("a power zone's offset is larger than its target")?; + put32(image, at, target)?; + put32(image, at + 4, target_off)?; + put32(image, at + 8, filter)?; + } + put32( + image, + power::FAST_DIE_KP, + w.values[FAST_DIE0_PROPORTIONAL_GAIN], + )?; + put32( + image, + power::FAST_DIE_KI_DT, + w.per_period(FAST_DIE0_INTEGRAL_GAIN)?, + )?; + put32(image, power::MAX_POWER, max_power_mw)?; + put32(image, power::PPM_KP, w.values[PPM_KP])?; + put32(image, power::PPM_KI_DT, w.per_period(PPM_KI)?)?; + put32(image, power::FLAG_244, 1)?; + Ok(()) +} + +/// The first word (4-byte aligned offset) at which `a` and `b` differ, with both values; a +/// missing word reads 0. `None` when they are equal. +pub(crate) fn first_difference(a: &[u8], b: &[u8]) -> Option<(usize, u32, u32)> { + let word = |s: &[u8], at: usize| -> u32 { + let mut w = [0u8; 4]; + for (i, out) in w.iter_mut().enumerate() { + *out = s.get(at + i).copied().unwrap_or(0); + } + u32::from_le_bytes(w) + }; + let len = a.len().max(b.len()); + (0..len) + .step_by(4) + .map(|at| (at, word(a, at), word(b, at))) + .find(|&(_, x, y)| x != y) +} + +// --- IEEE binary32 arithmetic on bit patterns (the kernel has no floating point) --- +// +// Operands and results are finite normal numbers or zero; anything else is `None`. +// Rounding is to nearest, ties to even. + +/// Sign, unbiased exponent of the leading bit and mantissa with its implicit bit; zero is +/// `(sign, 0, 0)`. +fn unpack(bits: u32) -> Option<(bool, i32, u32)> { + let sign = bits >> 31 != 0; + let exponent = ((bits >> 23) & 0xff) as i32; + let mantissa = bits & 0x7f_ffff; + match exponent { + 0 if mantissa == 0 => Some((sign, 0, 0)), + 0 | 0xff => None, + _ => Some((sign, exponent - 127, mantissa | 0x80_0000)), + } +} + +/// The single nearest to `sign * m * 2^exp`, `m` with its leading bit anywhere; a sticky bit in +/// the lowest bit of `m` may stand for a nonzero remainder below it. +fn pack(sign: bool, exp: i32, m: u64) -> Option { + if m == 0 { + return Some((sign as u32) << 31); + } + let shift = m.leading_zeros(); + let m = m << shift; + let exp = exp - shift as i32 + 63; + let mut mantissa = (m >> 40) as u32; + let rest = m & ((1u64 << 40) - 1); + let half = 1u64 << 39; + if rest > half || (rest == half && mantissa & 1 == 1) { + mantissa += 1; + } + let mut exp = exp; + if mantissa == 1 << 24 { + mantissa >>= 1; + exp += 1; + } + let biased = exp + 127; + if !(1..=254).contains(&biased) { + return None; + } + Some((sign as u32) << 31 | (biased as u32) << 23 | (mantissa & 0x7f_ffff)) +} + +/// `n` as a single. +pub(crate) fn f32_from_u32(n: u32) -> u32 { + // Every u32 rounds to a normal single or zero. + pack(false, 0, n as u64).unwrap_or(0) +} + +/// `a * b`. +pub(crate) fn f32_mul(a: u32, b: u32) -> Option { + let (sa, ea, ma) = unpack(a)?; + let (sb, eb, mb) = unpack(b)?; + if ma == 0 || mb == 0 { + return Some(((sa ^ sb) as u32) << 31); + } + pack(sa ^ sb, ea + eb - 46, ma as u64 * mb as u64) +} + +/// `a / b`. +pub(crate) fn f32_div(a: u32, b: u32) -> Option { + let (sa, ea, ma) = unpack(a)?; + let (sb, eb, mb) = unpack(b)?; + if mb == 0 { + return None; + } + if ma == 0 { + return Some(((sa ^ sb) as u32) << 31); + } + // ma < 2^24, so ma << 40 fits; the quotient has at least 40 bits, 16 and more below the + // rounding position, so a sticky lowest bit stands in for a nonzero remainder. + let n = (ma as u64) << 40; + let mut q = n / mb as u64; + if n % mb as u64 != 0 { + q |= 1; + } + pack(sa ^ sb, ea - eb - 40, q) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn get32(b: &[u8], o: usize) -> u32 { + u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) + } + + /// The J516C GPU node's power words, as the saved device tree of that machine carries them. + fn j516c_words() -> PowerWords { + PowerWords::new( + [ + 8, // apple,power-sample-period + 1500, // apple,idleoff-standby-timer + 32, // apple,avg-power-filter-tc-ms + 0x41480000, // apple,avg-power-ki-only (12.5) + 0x3e99999a, // apple,avg-power-kp (0.3) + 40, // apple,avg-power-min-duty-cycle + 1, // apple,avg-power-target-filter-tc + 0x42080000, // apple,fast-die0-proportional-gain (34.0) + 0x443b8000, // apple,fast-die0-integral-gain (750.0) + 0x3e99999a, // apple,ppm-kp (0.3) + 0x4198cccd, // apple,ppm-ki (19.1) + ], + &[], + ) + .unwrap() + } + + #[test] + fn single_arithmetic() { + // The products the power words need, against the host's IEEE singles. + let dt = f32_div(f32_from_u32(8), f32_from_u32(1000)).unwrap(); + assert_eq!(dt, (8.0f32 / 1000.0).to_bits()); + for ki in [0x443b8000u32, 0x41480000, 0x4198cccd] { + assert_eq!( + f32_mul(ki, dt).unwrap(), + (f32::from_bits(ki) * f32::from_bits(dt)).to_bits() + ); + } + // A sweep of normal operands, both signs. + let mut x = 0x2545f491u32; + for _ in 0..20000 { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let a = f32::from_bits(x); + let b = f32::from_bits(x.rotate_left(11) ^ 0x5a5a5a5a); + if !a.is_normal() || !b.is_normal() { + continue; + } + let p = a * b; + if p.is_normal() { + assert_eq!( + f32_mul(a.to_bits(), b.to_bits()), + Some(p.to_bits()), + "{a} * {b}" + ); + } + let q = a / b; + if q.is_normal() { + assert_eq!( + f32_div(a.to_bits(), b.to_bits()), + Some(q.to_bits()), + "{a} / {b}" + ); + } + } + for n in [ + 0u32, + 1, + 8, + 1000, + 1500, + 0xffffff, + 0x1000000, + 0x1000001, + u32::MAX, + ] { + assert_eq!(f32_from_u32(n), (n as f32).to_bits()); + } + assert_eq!(f32_mul(0, 0x3f800000), Some(0)); + assert_eq!(f32_mul(0x3f800000, 0x80000000), Some(0x80000000)); + assert_eq!(f32_div(0x3f800000, 0), None); + assert_eq!(f32_div(0, 0x3f800000), Some(0)); + // Infinities, NaNs and subnormals are not operands. + assert_eq!(f32_mul(0x7f800000, 0x3f800000), None); + assert_eq!(f32_mul(0x00000001, 0x3f800000), None); + // Overflow and underflow of the result are refused, not rounded. + assert_eq!(f32_mul(0x7f000000, 0x7f000000), None); + assert_eq!(f32_mul(0x00800000, 0x00800000), None); + } + + #[test] + fn words_shape() { + let w = j516c_words(); + assert_eq!(w.zone_count, 0); + assert_eq!(PowerWords::new(w.values, &[1, 2, 3]).unwrap().zone_count, 1); + assert_eq!( + PowerWords::new(w.values, &[1, 2, 3]).unwrap().zones[0], + [1, 2, 3] + ); + assert!(PowerWords::new(w.values, &[1, 2]).is_err()); + assert!(PowerWords::new(w.values, &[0; 18]).is_err()); + let mut v = w.values; + v[PERIOD_MS] = 0; + assert!(PowerWords::new(v, &[]).is_err()); + assert_eq!(PROPS.len(), w.values.len()); + assert_eq!(PROPS[PERIOD_MS], c"apple,power-sample-period"); + assert_eq!(PROPS[STANDBY_TIMER], c"apple,idleoff-standby-timer"); + } + + #[test] + fn globals_words() { + let w = j516c_words(); + let mut img = vec![0u8; GLOBALS_SIZE]; + // A G15S-shaped image: the soft-fault word at its unaligned place. + img[0xdf9] = 3; + globals(&mut img, 54321, &w).unwrap(); + assert_eq!(get32(&img, 0x70), 1); + assert_eq!(get32(&img, 0x78), 54321); + assert_eq!(get32(&img, 0x7c), 800); + assert_eq!(get32(&img, 0x80), 800); + assert_eq!(get32(&img, 0x8c), 800); + assert_eq!(get32(&img, 0x7a8), 1500); + assert_eq!(get32(&img, 0x980), 100); + assert_eq!(get32(&img, 0xdf8), 0); + assert_eq!(get32(&img, 0x1200), 0x300); + // Everything else untouched. + let touched = [0x70, 0x78, 0x7c, 0x80, 0x8c, 0x7a8, 0x980, 0xdf8, 0x1200]; + for o in (0..GLOBALS_SIZE).step_by(4) { + if !touched.contains(&o) { + assert_eq!(get32(&img, o), 0, "+{o:#x}"); + } + } + // Without the soft-fault word where the G15S image has it, the image is not the one + // this rule is written for. + let mut bad = vec![0u8; GLOBALS_SIZE]; + assert!(globals(&mut bad, 1, &w).is_err()); + let mut short = vec![0u8; GLOBALS_SIZE - 1]; + assert!(globals(&mut short, 1, &w).is_err()); + } + + #[test] + fn power_words() { + let w = j516c_words(); + let mut img = vec![0u8; POWER_SIZE]; + power(&mut img, 54321, &w).unwrap(); + assert_eq!(get32(&img, 0x0c), 0); + assert_eq!(get32(&img, 0x10), 4); + assert_eq!(get32(&img, 0x14), 0x3dcccccd); + assert_eq!(get32(&img, 0x18), 0x3e99999a); + assert_eq!(get32(&img, 0x1c), 40); + assert_eq!(get32(&img, 0x20), 1); + assert_eq!(get32(&img, 0xb8), 0x42080000); + assert_eq!(get32(&img, 0xbc), 0x40c00001); + assert_eq!(get32(&img, 0xd0), 54321); + assert_eq!(get32(&img, 0xd4), 0x3e99999a); + assert_eq!(get32(&img, 0xd8), 0x3e1c779b); + assert_eq!(get32(&img, 0x244), 1); + let touched = [ + 0x10, 0x14, 0x18, 0x1c, 0x20, 0xb8, 0xbc, 0xd0, 0xd4, 0xd8, 0x244, + ]; + for o in (0..POWER_SIZE).step_by(4) { + if !touched.contains(&o) { + assert_eq!(get32(&img, o), 0, "+{o:#x}"); + } + } + // Power zones: count and {target, target - offset, filter} rows. + let z = PowerWords::new(w.values, &[5000, 200, 7, 9000, 1000, 3]).unwrap(); + let mut img = vec![0u8; POWER_SIZE]; + power(&mut img, 1, &z).unwrap(); + assert_eq!(get32(&img, 0x0c), 2); + assert_eq!(get32(&img, 0x24), 5000); + assert_eq!(get32(&img, 0x28), 4800); + assert_eq!(get32(&img, 0x2c), 7); + assert_eq!(get32(&img, 0x30), 9000); + assert_eq!(get32(&img, 0x34), 8000); + assert_eq!(get32(&img, 0x38), 3); + assert_eq!(get32(&img, 0x3c), 0); + // An offset larger than its target has no target - offset word. + let under = PowerWords::new(w.values, &[100, 101, 1]).unwrap(); + let mut img = vec![0u8; POWER_SIZE]; + assert!(power(&mut img, 1, &under).is_err()); + // A filter time constant shorter than the sample period has no period count. + let mut v = w.values; + v[AVG_POWER_FILTER_TC_MS] = 4; + let mut img = vec![0u8; POWER_SIZE]; + assert!(power(&mut img, 1, &PowerWords::new(v, &[]).unwrap()).is_err()); + let mut short = vec![0u8; POWER_SIZE - 1]; + assert!(power(&mut short, 1, &w).is_err()); + } + + #[test] + fn differences() { + let a = [1u8, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]; + let mut b = a; + assert_eq!(first_difference(&a, &b), None); + b[9] = 1; + assert_eq!(first_difference(&a, &b), Some((8, 3, 0x103))); + assert_eq!(first_difference(&a, &b[..8]), Some((8, 3, 0))); + assert_eq!(first_difference(&a[..8], &b), Some((8, 0, 0x103))); + } + + // --- The fixture: a saved copy of a J516C's device tree and its private board file. --- + + fn be32(b: &[u8], o: usize) -> u32 { + u32::from_be_bytes(b[o..o + 4].try_into().unwrap()) + } + + /// Properties of the flattened device tree's node whose `compatible` names `compatible`. + fn fdt_node_props(dtb: &[u8], compatible: &[u8]) -> Option)>> { + assert_eq!(be32(dtb, 0), 0xd00dfeed); + let strings = be32(dtb, 12) as usize; + let mut at = be32(dtb, 8) as usize; + let mut stack: Vec)>> = Vec::new(); + loop { + let token = be32(dtb, at); + at += 4; + match token { + 1 => { + let end = dtb[at..].iter().position(|&b| b == 0).unwrap(); + at = (at + end + 1).next_multiple_of(4); + stack.push(Vec::new()); + } + 2 => { + let props = stack.pop().unwrap(); + let hit = props.iter().any(|(n, v)| { + n == "compatible" && v.split(|&b| b == 0).any(|s| s == compatible) + }); + if hit { + return Some(props); + } + } + 3 => { + let len = be32(dtb, at) as usize; + let name_off = strings + be32(dtb, at + 4) as usize; + let name_end = dtb[name_off..].iter().position(|&b| b == 0).unwrap(); + let name = + String::from_utf8(dtb[name_off..name_off + name_end].to_vec()).unwrap(); + let value = dtb[at + 8..at + 8 + len].to_vec(); + at = (at + 8 + len).next_multiple_of(4); + stack.last_mut().unwrap().push((name, value)); + } + 4 => {} + 9 => return None, + _ => panic!("fdt token {token}"), + } + } + } + + /// Builder on the saved device tree == the private file's Globals and Power, byte for byte. + /// Needs `G15_J516C_FIXTURES=` with `j516c.dtb` (`/sys/firmware/fdt` of the machine) + /// and `t6031-j516c-board.bin` (its board file); both stay off the tree, so the test is + /// ignored by default (`--ignored` runs it) and fails, rather than passes, without them. + #[test] + #[ignore = "needs the off-tree J516C fixtures (G15_J516C_FIXTURES)"] + fn j516c_fixture() { + let dir = std::env::var_os("G15_J516C_FIXTURES") + .expect("G15_J516C_FIXTURES names the directory with j516c.dtb and the board file"); + let dir = std::path::Path::new(&dir); + let dtb = std::fs::read(dir.join("j516c.dtb")).unwrap(); + let blob = std::fs::read(dir.join("t6031-j516c-board.bin")).unwrap(); + + // The board file: magic, version, count, 3 x (kind, size), images (board/blob.rs). + assert_eq!(&blob[..8], b"T6031BRD"); + assert_eq!(get32(&blob, 8), 1); + assert_eq!(get32(&blob, 12), 3); + let mut at = 16 + 3 * 8; + let mut images = Vec::new(); + for i in 0..3 { + assert_eq!(get32(&blob, 16 + i * 8) as usize, i); + let size = get32(&blob, 16 + i * 8 + 4) as usize; + images.push(blob[at..at + size].to_vec()); + at += size; + } + assert_eq!(at, blob.len()); + let (hardware, file_globals, file_power) = (&images[0], &images[1], &images[2]); + assert_eq!(hardware.len(), 0xb480); + assert_eq!(file_globals.len(), GLOBALS_SIZE); + assert_eq!(file_power.len(), POWER_SIZE); + + // The GPU node's words. + let props = fdt_node_props(&dtb, b"apple,agx-t6031").expect("a T6031 GPU node"); + let prop = |name: &core::ffi::CStr| -> Option<&[u8]> { + let name = name.to_str().unwrap(); + props + .iter() + .find(|(n, _)| n == name) + .map(|(_, v)| v.as_slice()) + }; + let mut values = [0u32; PROPS.len()]; + for (v, name) in values.iter_mut().zip(PROPS.iter()) { + let bytes = prop(name).unwrap_or_else(|| panic!("GPU node has no {name:?}")); + assert_eq!(bytes.len(), 4, "{name:?}"); + *v = be32(bytes, 0); + } + let zones: Vec = prop(ZONES) + .map(|b| b.chunks(4).map(|c| be32(c, 0)).collect()) + .unwrap_or_default(); + let words = PowerWords::new(values, &zones).unwrap(); + + // The images: the G15S templates with the J516C words, the hardware record's maximum + // power and the top state. + let max_power = get32(hardware, HWDATA_A + HWDATA_A_MAX_POWER); + let mut built_globals = vec![0u8; GLOBALS_SIZE]; + super::super::template::fill(&super::super::data::GLOBALS, &mut built_globals).unwrap(); + globals(&mut built_globals, max_power, &words).unwrap(); + let mut built_power = vec![0u8; POWER_SIZE]; + super::super::template::fill(&super::super::data::POWER, &mut built_power).unwrap(); + power(&mut built_power, max_power, &words).unwrap(); + + assert_eq!( + first_difference(&built_globals, file_globals), + None, + "Globals" + ); + assert_eq!(first_difference(&built_power, file_power), None, "Power"); + } +} diff --git a/drivers/gpu/drm/asahi/g15/boot.rs b/drivers/gpu/drm/asahi/g15/boot.rs new file mode 100644 index 00000000000000..e6278690d5f14a --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/boot.rs @@ -0,0 +1,729 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Admission and firmware start to READY. +//! +//! Admission (no firmware-visible writes): machine check (the T6030 board check +//! `apple_pmp_t6030_board`, or the SoC's machine compatible), the PMP supplier on a SoC with +//! the PMP AGX vote (`apple_pmp_j514s_gpu_prepare`, may return EPROBE_DEFER), the GPU regions and +//! segments ([`super::adt`]: the ADT export, or the GPU device tree node), exact firmware TEXT +//! identity ([`super::identity`]), MMIO windows, runtime-PM hold of the GFX domain. +//! +//! Start: PMP AGX vote (`apple_pmp_j514s_gpu_get`) where the SoC takes one, hardware identity +//! and core masks (one word, or two above 32 core slots), `sgx_open` +//! 0x70001, cold-only check (ASC RUN clear, TTBAT all zero), UAT adoption and the PTE self-check +//! (nothing firmware-visible yet), RTKit init (the node's mailbox), wake, endpoints 0x20/0x21, +//! PPL/UAT bootstrap ([`super::uat`]), initdata graph ([`super::initdata`]), EP 0x20 +//! `0x0081 << 48 | ROOT`, DEVCTL 0x13 then 9, readiness (`Runtime+0x314 == 0xabcdabcd` and +//! `Flags+4 == 1`, 2 s, draining rings), DEVCTL 0x13 again. +//! +//! RTKit receive: EP 0x20 `0x0042 << 48` in interrupt context only kicks the poll work +//! ([`super::Shared::kick`]); a crash latches fail-stop. The callbacks are registered through +//! the C RTKit API directly: the only RTKit buffer accepted is the inherited one inside firmware +//! DATA, mapped as I/O memory, which the Rust RTKit abstraction (buffers in system memory only) +//! cannot express. +//! +//! Once the firmware has been touched nothing it can reach is ever freed: a failed start, or a +//! failed backend start, keeps the session as an [`Orphan`] whose rings are still drained. + +use core::ffi::c_void; +use core::sync::atomic::Ordering; + +use kernel::{ + bindings, device, + device::Core, + error::{from_err_ptr, to_result}, + platform, + prelude::*, + sync::{aref::ARef, Arc, ArcBorrow}, + time::{delay::fsleep, Delta, Instant, Monotonic}, +}; + +use super::adt::{self, GpuAdt}; +use super::channel::{self, Channel, Channels}; +use super::event::Events; +use super::fw::channels::{devctl, DevCtl}; +use super::fw::initdata::runtime; +use super::hw; +use super::initdata::{self, InitData}; +use super::object::Objects; +use super::{identity, regs, uat, Config, Shared}; +use crate::driver::AsahiDrmDevice as AsahiDevice; +use crate::mmu; + +/// The C shim (`g15/glue.c`): helpers without Rust bindings. +pub(crate) mod glue { + use core::sync::atomic::{AtomicBool, Ordering}; + use kernel::{device, prelude::*}; + + extern "C" { + fn asahi_g15_sha256(data: *const u8, len: usize, out: *mut u8); + fn asahi_g15_board() -> bool; + fn asahi_g15_machine(compatible: *const core::ffi::c_char) -> bool; + fn asahi_g15_hold_power(dev: *mut core::ffi::c_void); + fn asahi_g15_release_power(dev: *mut core::ffi::c_void); + fn asahi_g15_module_get(); + pub(crate) fn asahi_g15_reprobe(); + fn asahi_g15_adt_phram(start: *mut u64, size: *mut u64) -> core::ffi::c_int; + fn asahi_g15_ram_disjoint(start: u64, size: u64) -> bool; + fn asahi_g15_ram_within(start: u64, size: u64) -> bool; + fn asahi_g15_memory_mode(start: u64, size: u64) -> u32; + fn asahi_g15_ioremap_wc(start: u64, size: usize) -> *mut core::ffi::c_void; + fn asahi_g15_dma_coherent(dev: *mut core::ffi::c_void) -> bool; + pub(crate) fn asahi_g15_pmp_prepare(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + pub(crate) fn asahi_g15_pmp_get(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + pub(crate) fn asahi_g15_pmp_put(dev: *mut core::ffi::c_void); + fn asahi_g15_reserved_uat(index: u32, start: u64, size: u64) -> bool; + } + + /// SHA-256 (`sha256()`). + pub(crate) fn sha256(data: &[u8]) -> [u8; 32] { + let mut out = [0u8; 32]; + // SAFETY: `data` is valid for its length and `out` holds the 32-byte digest. + unsafe { asahi_g15_sha256(data.as_ptr(), data.len(), out.as_mut_ptr()) }; + out + } + + /// A J514S/J516S T6030 board (`apple_pmp_t6030_board()`). + pub(crate) fn board() -> bool { + // SAFETY: Reads the machine compatible strings only. + unsafe { asahi_g15_board() } + } + + /// Exact enabled UAT reservation from the maintained boot-loader handoff. + pub(crate) fn reserved_uat(index: u32, start: u64, size: u64) -> bool { + // SAFETY: Queries and releases OF nodes; no physical memory is accessed. + unsafe { asahi_g15_reserved_uat(index, start, size) } + } + + /// Whether the machine carries `compatible` (`of_machine_is_compatible()`). + pub(crate) fn machine(compatible: &CStr) -> bool { + // SAFETY: Reads the machine compatible strings only; the string is NUL-terminated. + unsafe { asahi_g15_machine(compatible.as_char_ptr()) } + } + + /// Holds the GFX power domain for the retained session. + pub(crate) fn hold_power(dev: &device::Device) { + // SAFETY: `dev` is a valid device; runtime-PM accounting on it has no other requirement. + unsafe { asahi_g15_hold_power(dev.as_raw().cast()) }; + } + + /// Gives the GFX power domain hold back after a start that touched nothing firmware-visible. + pub(crate) fn release_power(dev: &device::Device) { + // SAFETY: `dev` is the device `hold_power` was called with. + unsafe { asahi_g15_release_power(dev.as_raw().cast()) }; + } + + static RETAINED: AtomicBool = AtomicBool::new(false); + + /// Whether the module is pinned: the firmware has been touched. + pub(crate) fn retained() -> bool { + RETAINED.load(Ordering::Acquire) + } + + /// Pins this module until reboot, once (`__module_get(THIS_MODULE)`). + pub(crate) fn retain_module() { + if !RETAINED.swap(true, Ordering::AcqRel) { + // SAFETY: The module is live while its code runs; the reference is never put. + unsafe { asahi_g15_module_get() }; + } + } + + /// The phram "adt" export: start and size. + pub(crate) fn adt_phram() -> Result<(u64, u64)> { + let (mut start, mut size) = (0u64, 0u64); + // SAFETY: Both pointers are valid for a u64 write. + kernel::error::to_result(unsafe { asahi_g15_adt_phram(&mut start, &mut size) })?; + Ok((start, size)) + } + + /// The physical range is disjoint from System RAM. + pub(crate) fn ram_disjoint(start: u64, size: u64) -> bool { + // SAFETY: Only queries the resource tree. + unsafe { asahi_g15_ram_disjoint(start, size) } + } + + /// Every page is valid System RAM and remains reserved from the allocator. + pub(crate) fn ram_within(start: u64, size: u64) -> bool { + // SAFETY: Only queries the resource tree. + unsafe { asahi_g15_ram_within(start, size) } + } + + /// WB for complete reserved RAM, WC for aligned non-RAM carveouts; reject everything else. + pub(crate) fn memory_mode(start: u64, size: u64) -> Result { + // SAFETY: Only queries resources and page metadata; it does not create a mapping. + match unsafe { asahi_g15_memory_mode(start, size) } { + 0 => Err(EINVAL), + mode => Ok(mode), + } + } + + /// Whether the device's DMA mappings skip cache maintenance. + pub(crate) fn dma_coherent(dev: &device::Device) -> bool { + // SAFETY: Reads a flag of a valid device. + unsafe { asahi_g15_dma_coherent(dev.as_raw().cast()) } + } + + /// `ioremap_wc`, for the RTKit crash buffer. + pub(crate) fn ioremap_wc(start: u64, size: usize) -> *mut core::ffi::c_void { + // SAFETY: Creates a new mapping of a device range; no other effect. + unsafe { asahi_g15_ioremap_wc(start, size) } + } +} + +/// The PMP AGX vote of a start, released on drop until the session is retained ([`Vote::keep`]). +struct Vote(Option>); + +impl Vote { + /// The session is retained: the vote stays with it until reboot. + fn keep(mut self) { + self.0 = None; + } +} + +impl Drop for Vote { + fn drop(&mut self) { + // The vote is a level, not a count: never give it back under a retained session. + if let Some(d) = self.0.take().filter(|_| !glue::retained()) { + // SAFETY: `d` is the device `asahi_g15_pmp_get` voted for. + unsafe { glue::asahi_g15_pmp_put(d.as_raw().cast()) }; + } + } +} + +/// `EPROTO` (not among the Rust kernel's named error codes). +pub(crate) fn eproto() -> Error { + Error::from_errno(-(bindings::EPROTO as i32)) +} + +/// `Shared` from an RTKit cookie. +/// +/// # Safety +/// +/// `cookie` must be the pointer [`Rtkit::new`] registered. +unsafe fn shared<'a>(cookie: *mut c_void) -> ArcBorrow<'a, Shared> { + // SAFETY: The cookie is a leaked `Arc` (see `Rtkit::new`), live until reboot. + unsafe { ArcBorrow::from_raw(cookie as *const Shared) } +} + +/// RTKit crash callback: latches fail-stop. +unsafe extern "C" fn rtkit_crashed(cookie: *mut c_void, _log: *const c_void, _size: usize) { + // SAFETY: RTKit passes back the registered cookie. + let shared = unsafe { shared(cookie) }; + dev_err!( + shared.dev, + "GPU firmware crashed; retaining session until reboot\n" + ); + shared.fail_stop(EIO); +} + +/// RTKit message callback. +unsafe extern "C" fn rtkit_recv(cookie: *mut c_void, endpoint: u8, message: u64) { + // SAFETY: RTKit passes back the registered cookie. + let shared = unsafe { shared(cookie) }; + // EP 0x20 0x0042... asks for receive-ring draining; nothing else expected. + if endpoint == hw::ep::FIRMWARE && message == hw::ep::RING_SERVICE { + if shared.started.load(Ordering::Acquire) { + Arc::::from(shared).kick(); + } + return; + } + dev_info!( + shared.dev, + "firmware EP{:#x} message {:#x}\n", + endpoint, + message + ); +} + +/// EP 0x20 ring-service request, in the mailbox interrupt: wake only. The drain and the +/// backend's completion check run in the poll work; the shared state outlives the mailbox. +unsafe extern "C" fn rtkit_recv_early(cookie: *mut c_void, endpoint: u8, message: u64) -> bool { + // SAFETY: RTKit passes back the registered cookie. + let shared = unsafe { shared(cookie) }; + if !hw::tuning::EARLY_WAKE + || endpoint != hw::ep::FIRMWARE + || message != hw::ep::RING_SERVICE + || !shared.started.load(Ordering::Acquire) + { + return false; + } + Arc::::from(shared).kick(); + true +} + +/// Only the inherited crash buffer inside this session's firmware DATA, once. +unsafe extern "C" fn rtkit_shmem_setup( + cookie: *mut c_void, + bfr: *mut bindings::apple_rtkit_shmem, +) -> core::ffi::c_int { + // SAFETY: RTKit passes back the registered cookie. + let shared = unsafe { shared(cookie) }; + // SAFETY: RTKit passes a valid buffer descriptor it owns for the duration of the call. + let bfr = unsafe { &mut *bfr }; + let (iova, size) = (bfr.iova as u64, bfr.size as u64); + let data = &shared.data; + let data_size = data.end - data.start; + if shared.rtkit_buffer.load(Ordering::Acquire) != 0 + || iova == 0 + || size == 0 + || (iova | size) & 0xfff != 0 + || iova < data.start + || size > data_size + || iova - data.start > data_size - size + { + dev_err!( + shared.dev, + "refusing RTKit buffer {:#x}/{:#x}\n", + iova, + size + ); + shared.fail_stop(EINVAL); + return EINVAL.to_errno(); + } + let iomem = glue::ioremap_wc(iova, bfr.size); + if iomem.is_null() { + return ENOMEM.to_errno(); + } + bfr.iomem = iomem; + bfr.is_mapped = true; + shared.rtkit_buffer.store(iova, Ordering::Release); + dev_info!( + shared.dev, + "mapped firmware crash storage {:#x}/{:#x}\n", + iova, + size + ); + 0 +} + +/// Retained until reboot: no qualified stop path. +unsafe extern "C" fn rtkit_shmem_destroy( + _cookie: *mut c_void, + _bfr: *mut bindings::apple_rtkit_shmem, +) { +} + +/// The GPU's RTKit callbacks. +static RTKIT_OPS: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { + flags: 0, + crashed: Some(rtkit_crashed), + recv_message: Some(rtkit_recv), + recv_message_early: Some(rtkit_recv_early), + shmem_setup: Some(rtkit_shmem_setup), + shmem_destroy: Some(rtkit_shmem_destroy), +}; + +/// The GPU's RTKit client. Never freed: the firmware session lasts until reboot. +/// +/// # Invariants +/// +/// `rtk` is a live `struct apple_rtkit` whose cookie is a leaked `Arc`. +pub(crate) struct Rtkit { + rtk: *mut bindings::apple_rtkit, +} + +// SAFETY: The C RTKit API is callable from any thread; mutating calls take `&mut self`. +unsafe impl Send for Rtkit {} +// SAFETY: Shared calls (`has_endpoint`) only read RTKit state. +unsafe impl Sync for Rtkit {} + +impl Rtkit { + /// Initializes RTKit on the maintained GPU node's first, unnamed mailbox. + /// The session is not device-managed because it is retained until reboot. + fn new(dev: &device::Device, shared: &Arc) -> Result { + let cookie = Arc::into_raw(shared.clone()) as *mut c_void; + // SAFETY: `dev` is valid, the name is a NUL-terminated string or null and the ops are + // static. + let rtk = from_err_ptr(unsafe { + bindings::apple_rtkit_init(dev.as_raw(), cookie, core::ptr::null(), 0, &RTKIT_OPS) + }); + match rtk { + // INVARIANT: The cookie stays leaked from here on. + Ok(rtk) => Ok(Self { rtk }), + Err(e) => { + // SAFETY: Init failed, so RTKit holds no copy of the cookie from `into_raw`. + drop(unsafe { Arc::from_raw(cookie as *const Shared) }); + Err(e) + } + } + } + + fn wake(&mut self) -> Result { + // SAFETY: `rtk` is live by the type invariant. + to_result(unsafe { bindings::apple_rtkit_wake(self.rtk) }) + } + + fn has_endpoint(&self, endpoint: u8) -> bool { + // SAFETY: `rtk` is live by the type invariant. + unsafe { bindings::apple_rtkit_has_endpoint(self.rtk, endpoint) } + } + + fn start_endpoint(&mut self, endpoint: u8) -> Result { + // SAFETY: `rtk` is live by the type invariant. + to_result(unsafe { bindings::apple_rtkit_start_ep(self.rtk, endpoint) }) + } + + /// Sends a message without waiting. + pub(crate) fn send(&mut self, endpoint: u8, message: u64) -> Result { + // SAFETY: `rtk` is live by the type invariant. + to_result(unsafe { + bindings::apple_rtkit_send_message( + self.rtk, + endpoint, + message, + core::ptr::null_mut(), + false, + ) + }) + } +} + +/// The result of admission: everything probe-time checks established, nothing written. +pub(crate) struct Admitted { + pub(crate) regs: regs::Regs, + pub(crate) adt: GpuAdt, + pub(crate) board_images: initdata::BoardImages, +} + +/// The running firmware session: RTKit, MMIO and the adopted UAT. (The +/// host window lives in [`Objects`], which maps through it.) +pub(crate) struct Session { + pub(crate) dev: ARef, + pub(crate) shared: Arc, + pub(crate) rtkit: Rtkit, + pub(crate) regs: regs::Regs, + pub(crate) adt: GpuAdt, + uat: Arc, +} + +impl Session { + /// The adopted UAT (user VMs are created and bound through it). + pub(crate) fn uat(&self) -> Arc { + self.uat.clone() + } + + /// The latched error, if any. + pub(crate) fn check(&self) -> Result { + self.shared.check() + } + + /// Sends a mailbox message. + pub(crate) fn send(&mut self, endpoint: u8, message: u64) -> Result { + self.rtkit.send(endpoint, message) + } + + /// Rings a submit channel's doorbell: EP 0x21 `0x0083 << 48 | channel`. + pub(crate) fn ring(&mut self, channel: Channel) -> Result { + self.send(hw::ep::DOORBELL, hw::engine::DOORBELL | channel as u64) + } +} + +/// The firmware at READY. +pub(crate) struct Booted { + pub(crate) session: Session, + pub(crate) init: InitData, + pub(crate) objects: Objects, + pub(crate) channels: Channels, + pub(crate) events: Events, + pub(crate) id: regs::Identity, + pub(crate) max_frequency_khz: u32, +} + +/// A firmware session that did not complete: retained until reboot, its receive rings still +/// drained so the firmware never waits on the host. +pub(crate) struct Orphan { + pub(crate) session: Session, + /// Retained only: the firmware may still use them. + pub(crate) _objects: Objects, + pub(crate) channels: Option, + pub(crate) _init: Option, + pub(crate) events: Events, +} + +impl Orphan { + /// Drains the receive rings, if they exist. + pub(crate) fn drain(&mut self) -> Result { + if let Some(channels) = &mut self.channels { + channels.drain_rings(&self.session.dev, &mut self.events)?; + } + Ok(()) + } +} + +/// Probe-time admission. +pub(crate) fn admit( + pdev: &platform::Device>, + _dev: &AsahiDevice, + cfg: &'static Config, +) -> Result { + let dev = pdev.as_ref(); + let pmp = cfg.platform == hw::Platform::AdtWithPmp; + if pmp { + if !glue::board() { + return Err(ENODEV); + } + // Retain the PMP supplier (and its AGX bridge) before any vote. + // SAFETY: `dev` is the bound GPU device. + let ret = unsafe { glue::asahi_g15_pmp_prepare(dev.as_raw().cast()) }; + if ret != 0 { + let err = Error::from_errno(ret); + if err != EPROBE_DEFER { + dev_err!(dev, "PMP supplier not ready: {:?}\n", err); + } + return Err(err); + } + } else if !glue::machine(cfg.machine) { + dev_err!(dev, "G15: not a {} machine\n", cfg.name); + return Err(ENODEV); + } + let adt = adt::read(dev, cfg) + .inspect_err(|e| dev_err!(dev, "GPU regions not admitted: {:?}\n", e))?; + identity::firmware(dev, &adt, cfg.firmware) + .inspect_err(|e| dev_err!(dev, "loaded GFX TEXT identity mismatch: {:?}\n", e))?; + dev_info!(dev, "M3: firmware identity accepted\n"); + if cfg.board == hw::Board::None { + dev_err!( + dev, + "G15: no board data for the {}; the firmware is left as the boot loader left it\n", + cfg.name + ); + return Err(ENODEV); + } + // Firmware objects are cleaned to the point of coherency by their DMA mapping: that needs + // a device that is not DMA-coherent, as the synthesized node is. + if glue::dma_coherent(dev) { + dev_err!( + dev, + "G15: the GPU device is DMA-coherent; firmware objects would not be cleaned\n" + ); + return Err(EINVAL); + } + let board_images = initdata::prepare_board(dev, cfg, &adt)?; + let regs = regs::Regs::new(pdev)?; + // Keep the GFX domain powered for the whole (retained) session. + glue::hold_power(dev); + dev_info!(dev, "{} admitted, ASC={:#x}\n", cfg.name, regs.asc_control()?); + Ok(Admitted { regs, adt, board_images }) +} + +/// Posts one device control with only the opcode and waits for it. +fn devctl_op( + session: &mut Session, + channels: &mut Channels, + events: &mut Events, + init: &InitData, + opcode: u32, +) -> Result { + channel::devctl_submit(session, channels, events, init, &DevCtl::op(opcode), true) +} + +/// From the wake to READY. On failure the caller keeps everything as an [`Orphan`]. +fn run( + session: &mut Session, + cfg: &Config, + objects: &mut Objects, + events: &mut Events, + built: &mut Option<(InitData, Channels, u32)>, + board_images: initdata::BoardImages, +) -> Result { + let dev = session.dev.clone(); + session.rtkit.wake()?; + if !session.rtkit.has_endpoint(hw::ep::FIRMWARE) + || !session.rtkit.has_endpoint(hw::ep::DOORBELL) + { + return Err(ENODEV); + } + session.rtkit.start_endpoint(hw::ep::FIRMWARE)?; + session.rtkit.start_endpoint(hw::ep::DOORBELL)?; + let uat = session.uat.clone(); + objects.window.bootstrap(&dev, &uat)?; + let (init, channels, _) = built.insert(initdata::build(&dev, cfg, &session.adt, objects, board_images)?); + uat::tlbi_all(); + dev_info!( + dev, + "M3: publishing owned initdata root {:#x} ({} pages, {} L3)\n", + hw::va::ROOT, + objects.pages(), + objects.window.l3_count() + ); + session.send( + hw::ep::FIRMWARE, + hw::ep::INITDATA | (hw::va::ROOT & hw::ep::INITDATA_ADDR_MASK), + )?; + devctl_op(session, channels, events, init, devctl::IMPORT_GLOBALS)?; + devctl_op(session, channels, events, init, devctl::START)?; + let start = Instant::::now(); + loop { + let (magic, ready) = init.readiness()?; + if magic == runtime::READY_MAGIC && ready == 1 { + break; + } + channels.drain_rings(&dev, events)?; + session.check()?; + if start.elapsed() > Delta::from_millis(2000) { + let (magic, ready) = init.readiness()?; + dev_err!( + dev, + "readiness: runtime+0x314={:#x} flags+4={:#x}\n", + magic, + ready + ); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_micros(1000)); + } + let (magic, ready) = init.readiness()?; + dev_info!( + dev, + "M3 firmware readiness: magic={:#x} flags={}\n", + magic, + ready + ); + devctl_op(session, channels, events, init, devctl::IMPORT_GLOBALS)?; + channels.drain_rings(&dev, events)?; + dev_info!( + dev, + "M3: firmware accepted owned initdata and device controls\n" + ); + Ok(()) +} + +/// Brings the firmware to READY. +pub(crate) fn start( + admitted: Admitted, + dev: &AsahiDevice, + cfg: &'static Config, + shared: &Arc, +) -> Result { + let Admitted { regs, adt, board_images } = admitted; + let d: ARef = shared.dev.clone(); + // Released by an early failure below, until the session is retained. + let mut vote = Vote(None); + if cfg.platform == hw::Platform::AdtWithPmp { + // SAFETY: `d` is the bound GPU device. + let ret = unsafe { glue::asahi_g15_pmp_get(d.as_raw().cast()) }; + if ret != 0 { + dev_err!(d, "PMP AGX vote failed: {}\n", ret); + return Err(Error::from_errno(ret)); + } + vote = Vote(Some(d.clone())); + } + let id = regs.identity(cfg)?; + dev_info!( + d, + "{}: power acknowledged, version={:#x} counts={:#x} core-mask={:#x}\n", + cfg.name, + id.version, + id.counts, + id.cores + ); + if !cfg + .hw_ids + .iter() + .any(|h| h.version == id.version && h.counts == id.counts) + { + dev_err!( + d, + "unsupported {} hardware: version {:#x} counts {:#x}\n", + cfg.name, + id.version, + id.counts + ); + return Err(eproto()); + } + // Binning: any non-empty enabled set in each cluster, nothing above the core slots. + let clusters = cfg.num_clusters as usize; + let slots = cfg.core_slots(); + if clusters > regs::MAX_CLUSTERS + || id.core_masks[..clusters].iter().any(|m| *m == 0) + || (slots < 64 && id.cores >> slots != 0) + { + dev_err!(d, "implausible {} core mask {:#x}\n", cfg.name, id.cores); + return Err(eproto()); + } + let mut enabled = [0u32; regs::MAX_CLUSTERS]; + for (count, mask) in enabled.iter_mut().zip(id.core_masks.iter()) { + *count = mask.count_ones(); + } + dev_info!( + d, + "{}: cores enabled per cluster: {:?}\n", + cfg.name, + &enabled[..clusters] + ); + regs.open()?; + // Cold only: ASC RUN clear and an all-zero TTBAT before ownership. + let control = regs.asc_control()?; + if control & regs::ASC_RUN != 0 { + return Err(EBUSY); + } + let window = uat::Window::new(&adt)?; + if !window.ttbat_is_clear()? { + return Err(EBUSY); + } + // Adopt the UAT and prove the leaf words before anything firmware-visible is written: no + // context names the shadow window or the lower root yet. + let uat = uat::adopt(dev, cfg, &adt)?; + let mut objects = Objects::new(dev, uat.clone(), window); + if let Err(e) = objects.self_check() { + // Mapped with cached firmware classes: never unmapped. + core::mem::forget(objects); + return Err(e); + } + + // From here on the firmware is touched: nothing it can reach is freed, the vote included. + glue::retain_module(); + vote.keep(); + let rtkit = match Rtkit::new(&d, shared) { + Ok(rtkit) => rtkit, + Err(e) => { + dev_err!(d, "G15: RTKit mailbox initialization failed: {:?}\n", e); + core::mem::forget(objects); + return Err(e); + } + }; + shared.started.store(true, Ordering::Release); + let mut session = Session { + dev: d.clone(), + shared: shared.clone(), + rtkit, + regs, + adt, + uat, + }; + let mut events = Events::new(); + let mut built = None; + let result = events + .reserve() + .and_then(|_| session.regs.set_asc_control(control | regs::ASC_RUN)) + .and_then(|_| run(&mut session, cfg, &mut objects, &mut events, &mut built, board_images)); + if let Err(e) = result { + dev_err!( + d, + "G15 start failed: {:?}; session retained until reboot\n", + e + ); + let (init, channels) = match built { + Some((init, channels, _)) => (Some(init), Some(channels)), + None => (None, None), + }; + shared.orphan(Orphan { + session, + _objects: objects, + channels, + _init: init, + events, + }); + return Err(e); + } + let (init, channels, max_frequency_khz) = built.ok_or(EINVAL)?; + Ok(Booted { + session, + init, + objects, + channels, + events, + id, + max_frequency_khz, + }) +} diff --git a/drivers/gpu/drm/asahi/g15/channel.rs b/drivers/gpu/drm/asahi/g15/channel.rs new file mode 100644 index 00000000000000..60090f140081c2 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/channel.rs @@ -0,0 +1,400 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Submit channels, the device-control ring, the receive rings and the doorbells. +//! +//! - Submit channels 0 (TA), 1 (FS), 2 (compute) of 12 allocated, 256 x 0x18 records each. +//! Posting writes the record, a write barrier, then the producer (+0x20 of the state block), +//! and another barrier. Doorbell: EP 0x21 `0x0083 << 48 | channel`. Records may be posted +//! behind unconsumed ones (submit-ahead, at most [`super::hw::sizes::AHEAD_RECORDS`]), never +//! over an unconsumed slot ([`Channels::post_ahead`]). +//! - Device-control ring: 256 x 0x38 records; doorbell EP 0x21 `0x0083000000000011`. +//! [`Firmware::devctl`] with `wait` posts and waits for consumption and completion (2 s); +//! without it, it does not wait (the kill request). Both return EBUSY while Control+0x4590 +//! says the firmware is halted, and wait for an earlier posted record's consumption first. +//! - Receive rings (event, 6 log sub-rings, trace, stats): consumed by setting read = producer; +//! the event ring is decoded by [`super::event`], the stats ring's tags and power-state +//! records are noted ([`super::power::pstate`]) before it is consumed. +//! - FwCtl ring: 256 x 0x18 = 0x1800 bytes (the 2419 firmware uses a 0x18 stride). Never used +//! by the host: no firmware cache flush path exists. + +use kernel::{ + prelude::*, + sync::Arc, + time::{delay::fsleep, Delta, Instant, Monotonic}, +}; + +use super::boot::Session; +use super::event::Events; +use super::fw::channels::{ + DevCtl, SubmitRecord, RING_SLOTS, STATE_COMPLETION, STATE_READ, STATE_WRITE, +}; +use super::hw::{self, rings, va}; +use super::initdata::InitData; +use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::power::pstate::{self, StatsSeen}; +use super::regs::{mb, rmb, wmb}; +use super::Firmware; + +/// A submit channel. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Channel { + Ta = 0, + Fs = 1, + Compute = 2, +} + +/// A ring and its state block. +pub(crate) struct Ring { + pub(crate) state: Arc, + pub(crate) ring: Arc, +} + +impl Ring { + /// The consumer's read index (state +0x00). + pub(crate) fn read(&self) -> Result { + self.state.r32(STATE_READ) + } + + /// The completion index (state +0x10). + pub(crate) fn completion(&self) -> Result { + self.state.r32(STATE_COMPLETION) + } + + /// The producer's write index (state +0x20). + pub(crate) fn write(&self) -> Result { + self.state.r32(STATE_WRITE) + } +} + +/// The channels and rings. +pub(crate) struct Channels { + /// The 12 submit channels (TA, FS and compute are used). + pub(crate) submit: KVec, + pub(crate) devctl: Ring, + pub(crate) event: Ring, + /// The six log sub-rings share one state object (6 x 0x30) and one ring object. + pub(crate) log: Ring, + pub(crate) trace: Ring, + pub(crate) stats: Ring, + /// What the stats ring carried, up to its consumer. + pub(crate) stats_seen: StatsSeen, + /// Allocated for the firmware; the host never uses it. + _fwctl: Ring, + /// Host producers of channels 0 TA, 1 FS, 2 compute. + producer: [u32; 3], + /// Host producer of the device-control ring. + devctl_producer: u32, +} + +fn fw_object(objects: &mut Objects, at: u64, size: usize) -> Result> { + objects.alloc(Request { + size, + class: Class::Fw, + placement: Placement::At(at), + offset: 0, + client: None, + lower: None, + cpu: true, + }) +} + +fn ring( + objects: &mut Objects, + state: u64, + state_size: usize, + ring: u64, + ring_size: usize, +) -> Result { + Ok(Ring { + state: fw_object(objects, state, state_size)?, + ring: fw_object(objects, ring, ring_size)?, + }) +} + +impl Channels { + /// Allocates every channel and ring of the initdata graph, firmware-only and uncached. + pub(crate) fn alloc(objects: &mut Objects) -> Result { + let mut submit = KVec::with_capacity(rings::CHANNELS as usize, GFP_KERNEL)?; + for i in 0..rings::CHANNELS { + submit.push( + ring( + objects, + va::ch_state(i), + rings::STATE_SIZE, + va::ch_ring(i), + rings::CHANNEL_RING_SIZE, + )?, + GFP_KERNEL, + )?; + } + Ok(Self { + submit, + devctl: ring( + objects, + va::DEVCTL_STATE, + rings::STATE_SIZE, + va::DEVCTL_RING, + rings::DEVCTL_RING_SIZE, + )?, + event: ring( + objects, + va::EVENT_STATE, + rings::STATE_SIZE, + va::EVENT_RING, + rings::EVENT_RING_SIZE, + )?, + log: ring( + objects, + va::LOG_STATE, + rings::LOG_STATE_SIZE, + va::LOG_RING, + rings::LOG_RING_SIZE, + )?, + trace: ring( + objects, + va::TRACE_STATE, + rings::STATE_SIZE, + va::TRACE_RING, + rings::TRACE_RING_SIZE, + )?, + stats: ring( + objects, + va::STATS_STATE, + rings::STATE_SIZE, + va::STATS_RING, + rings::STATS_RING_SIZE, + )?, + _fwctl: ring( + objects, + va::FWCTL_STATE, + rings::STATE_SIZE, + va::FWCTL_RING, + rings::FWCTL_RING_SIZE, + )?, + stats_seen: StatsSeen::default(), + producer: [0; 3], + devctl_producer: 0, + }) + } + + /// A submit channel's ring. + pub(crate) fn channel(&self, channel: Channel) -> &Ring { + &self.submit[channel as usize] + } + + /// The host producer of `channel`. + pub(crate) fn producer(&self, channel: Channel) -> u32 { + self.producer[channel as usize] + } + + /// The firmware's read index of `channel`. + pub(crate) fn read(&self, channel: Channel) -> Result { + self.channel(channel).read() + } + + /// The channel's write cell (state +0x20). + pub(crate) fn write_cell(&self, channel: Channel) -> Result { + self.channel(channel).write() + } + + /// Writes one submit record at the channel's producer and advances it, only if every earlier + /// record was consumed. Returns the new producer: the read index at which this record has + /// been consumed. + pub(crate) fn post(&mut self, channel: Channel, record: &SubmitRecord) -> Result { + self.post_inner(channel, record, false) + } + + /// Like [`Self::post`], but behind unconsumed records while fewer than + /// [`hw::sizes::AHEAD_RECORDS`] are outstanding. + pub(crate) fn post_ahead(&mut self, channel: Channel, record: &SubmitRecord) -> Result { + self.post_inner(channel, record, true) + } + + fn post_inner(&mut self, channel: Channel, record: &SubmitRecord, ahead: bool) -> Result { + let ch = channel as usize; + let producer = self.producer[ch]; + let ring = &self.submit[ch]; + let consumer = ring.read()?; + // Never over an unconsumed record: behind them only with room (ahead). + let busy = if ahead { + producer.wrapping_sub(consumer) % RING_SLOTS >= hw::sizes::AHEAD_RECORDS + } else { + consumer != producer + }; + if busy || ring.write()? != producer { + return Err(EBUSY); + } + ring.ring.write( + producer as usize * rings::CHANNEL_RECORD, + &record.to_bytes(), + )?; + wmb(); + let producer = (producer + 1) % RING_SLOTS; + ring.state.w32(STATE_WRITE, producer)?; + wmb(); + self.producer[ch] = producer; + Ok(producer) + } + + /// Consumes a receive ring to its firmware producer. + fn drain_one(ring: &Ring, offset: usize) -> Result { + let producer = ring.state.r32(offset + STATE_WRITE)?; + if ring.state.r32(offset + STATE_READ)? != producer { + ring.state.w32(offset + STATE_READ, producer)?; + wmb(); + } + Ok(()) + } + + /// Notes the stats records from the consumer to the producer into `seen`; returns the + /// producer, or `None` when an index is out of the ring. + fn note_stats(ring: &Ring, seen: &mut StatsSeen) -> Result> { + let producer = ring.state.r32(STATE_WRITE)?; + let read = ring.state.r32(STATE_READ)?; + let Some(slots) = pstate::pending(read, producer) else { + return Ok(None); + }; + rmb(); + for slot in slots { + let at = slot as usize * pstate::STATS_RECORD; + seen.note( + ring.ring.r32(at + pstate::STATS_TAG)?, + ring.ring.r32(at + pstate::POWER_STATE_INDEX)?, + ); + } + Ok(Some(producer)) + } + + /// The stats ring noted up to its producer, without consuming it. + pub(crate) fn peek_stats(&self) -> Result { + let mut seen = self.stats_seen; + Self::note_stats(&self.stats, &mut seen)?; + Ok(seen) + } + + /// Drains every receive ring: events (decoded into `events`), the six log sub-rings, trace + /// and stats (noted into [`Self::stats_seen`] first). + pub(crate) fn drain_rings( + &mut self, + dev: &kernel::device::Device, + events: &mut Events, + ) -> Result { + events.drain(dev, &self.event)?; + for i in 0..rings::LOG_RINGS { + Self::drain_one(&self.log, i * 0x30)?; + } + Self::drain_one(&self.trace, 0)?; + let mut seen = self.stats_seen; + if let Some(producer) = Self::note_stats(&self.stats, &mut seen)? { + self.stats_seen = seen; + if self.stats.read()? != producer { + // The record loads complete before the slots go back to the firmware. + mb(); + self.stats.state.w32(STATE_READ, producer)?; + wmb(); + } + return Ok(()); + } + Self::drain_one(&self.stats, 0) + } +} + +/// Posts one 0x38-byte device-control record (EP 0x21 `0x0083000000000011`) behind the earlier +/// ones (one posted without waiting may still be pending: wait for its consumption first) and, +/// with `wait`, waits for its consumption and completion. A firmware halted for recovery consumes +/// nothing until the host's resume: EBUSY then, so the caller can answer the halt instead of +/// timing out. Callers serialize (the device lock once the backend runs). +pub(crate) fn devctl_submit( + session: &mut Session, + channels: &mut Channels, + events: &mut Events, + init: &InitData, + record: &DevCtl, + wait: bool, +) -> Result { + let dev = session.dev.clone(); + let producer = channels.devctl_producer; + let next = (producer + 1) % RING_SLOTS; + let start = Instant::::now(); + let expired = || start.elapsed() > Delta::from_millis(2000); + let opcode = record.opcode(); + while channels.devctl.read()? != producer { + channels.drain_rings(&dev, events)?; + session.check()?; + if init.halted()? { + return Err(EBUSY); + } + if expired() { + dev_err!( + dev, + "control {:#x}: earlier record not consumed (read={} producer={})\n", + opcode, + channels.devctl.read()?, + producer + ); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_micros(1000)); + } + channels + .devctl + .ring + .write(producer as usize * rings::DEVCTL_RECORD, &record.to_bytes())?; + wmb(); + channels.devctl.state.w32(STATE_WRITE, next)?; + wmb(); + channels.devctl_producer = next; + session.send(hw::ep::DOORBELL, hw::engine::DEVCTL_DOORBELL)?; + if !wait { + return Ok(()); + } + loop { + channels.drain_rings(&dev, events)?; + session.check()?; + if channels.devctl.read()? == next && channels.devctl.completion()? == next { + return Ok(()); + } + if init.halted()? { + return Err(EBUSY); + } + if expired() { + dev_err!( + dev, + "control {:#x}: read={} completion={} producer={}\n", + opcode, + channels.devctl.read()?, + channels.devctl.completion()?, + next + ); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_micros(1000)); + } +} + +impl Firmware { + /// Posts a device-control record; with `wait` waits for its consumption and completion, + /// otherwise returns once posted. EBUSY while the firmware is halted; the transport error if + /// the session failed. + pub(crate) fn devctl(&mut self, record: &DevCtl, wait: bool) -> Result { + devctl_submit( + &mut self.session, + &mut self.channels, + &mut self.events, + &self.init, + record, + wait, + ) + } + + /// The latched transport error: an RTKit crash or a refused RTKit buffer. + pub(crate) fn transport_error(&self) -> Option { + self.session.check().err() + } + + /// Drains the receive rings and decodes events. Called first in every poll pass. + pub(crate) fn drain_rings(&mut self) -> Result { + let dev = self.session.dev.clone(); + self.channels.drain_rings(&dev, &mut self.events) + } +} diff --git a/drivers/gpu/drm/asahi/g15/command.rs b/drivers/gpu/drm/asahi/g15/command.rs new file mode 100644 index 00000000000000..45b65d1ddc026f --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/command.rs @@ -0,0 +1,707 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! SUBMIT parsing and validation into engine commands. +//! +//! The rules, checked in this order: the whole stream's structure ([`check_stream`]), then the +//! timestamp handles and the historical priors ([`prepare`]), then each command's mapped spans +//! and gates ([`Prepared::validate`]): +//! +//! - Headers 8 bytes, payloads multiples of 8, at most 4 MiB; short payloads zero-filled, bytes +//! past the known struct must be zero; 1..=64 render+compute commands; attachments (types +//! 2..4) with NONE barriers, at most 16 x 24 bytes, pad/flags zero, inside the VM range. +//! - Header barriers: NONE or at most the number of earlier same-engine commands in this +//! SUBMIT; `prior_vdm`/`prior_cdm` at most the commands of that engine accepted on the queue +//! before this ioctl (from 1); NONE does not suppress a prior ([`check_order`], the semantics +//! of `g17::job::Order`). Validated only: the total order satisfies them. +//! - Render (256, 272 with EXACT_PRIOR, up to 384 bytes): flags PROCESS_EMPTY_TILES, +//! NO_VERTEX_CLUSTERING, RSRC_SPEC_HI, DBIAS_IS_INT (+ FRAGMENT_BARRIERS only with +//! `g15_early_tiling`); VERTEX_SCRATCH, FEW_PRIMITIVES, helpers, sampler heap/count, +//! `ray_query`, nonzero partial-EOT high word: EINVAL; RSRC_SPEC_HI needs >= 256 bytes; +//! without it every `*_spec_hi` is zero; utile 16 or 32; `sample_size_B` multiple of 8 within +//! the tile buffer; `ppp_ctrl & !0x203 == 0`; stencil compression, or depth compression with +//! layers or samples != 1: EOPNOTSUPP; VDM base 4-aligned inside the compact window; scissor +//! 8-aligned; every referenced span mapped with the right access (ENOENT/EACCES); geometry +//! too large: E2BIG. +//! - Compute (64, 136 bytes): flags, `scs_layout`, `cdm_auxiliary_allocation`, `reserved`, +//! `intersection_*`, helpers, samplers zero; stream base/end 4-aligned. +//! - Timestamps resolve BIND_OBJECT handles to firmware arena VAs ([`super::timestamp`]). +//! - Stream gates ([`super::gate`]) when `g15_stream_gate`. + +use core::mem::{offset_of, size_of}; +use core::ops::Range; +use kernel::{prelude::*, sync::Arc, xarray}; + +use super::wire as uapi; + +use super::{gate, hw}; +use crate::{file, mmu, util::AnyBitPattern, util::Reader}; + +/// Largest command buffer. +pub(crate) const MAX_CMDBUF: usize = 4 << 20; +/// Most input plus output syncs of one SUBMIT. +pub(crate) const MAX_SYNCS: usize = 4096; +/// Hardware commands per SUBMIT. +const MAX_COMMANDS: u32 = crate::file::MAX_COMMANDS_PER_SUBMISSION; + +const HEADER_SIZE: usize = size_of::(); +const ATTACHMENT_SIZE: usize = size_of::(); +/// A render payload with RSRC_SPEC_HI carries every high word. +const RSRC_SPEC_HI_MIN: usize = + offset_of!(uapi::drm_asahi_cmd_render, bg_partial_rsrc_spec_hi) + size_of::(); +/// Render payload bytes from the ray-query stages on (RENDER_RAY_QUERY is never advertised). +const RAY_QUERY: usize = offset_of!(uapi::drm_asahi_cmd_render, ray_query); +const NONE: u16 = uapi::DRM_ASAHI_BARRIER_NONE as u16; + +const VERTEX_SCRATCH: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_VERTEX_SCRATCH; +const PROCESS_EMPTY_TILES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES; +const NO_VERTEX_CLUSTERING: u32 = + uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING; +const RSRC_SPEC_HI: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_RSRC_SPEC_HI; +const DBIAS_IS_INT: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_DBIAS_IS_INT; +const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; + +const CMD_RENDER: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER; +const CMD_COMPUTE: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_COMPUTE; +const SET_VERTEX_ATTACHMENTS: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_VERTEX_ATTACHMENTS; +const SET_FRAGMENT_ATTACHMENTS: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_FRAGMENT_ATTACHMENTS; +const SET_COMPUTE_ATTACHMENTS: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_COMPUTE_ATTACHMENTS; + +const MAX_DIMENSION: u16 = 16384; +const MAX_LAYERS: u16 = 2048; +const MAX_TILE_BUFFER: u32 = 32768; +/// Size of a queue's USC window. +pub(crate) const USC_WINDOW: u64 = 1 << 32; + +/// Engine index of render commands (VDM) in the accepted counts. +pub(crate) const RENDER: usize = 0; +/// Engine index of compute commands (CDM). +pub(crate) const COMPUTE: usize = 1; + +/// Checks the ordering of one command (the semantics of `g17::job::Order`) after `preceding` +/// commands of this SUBMIT, on a queue that accepted `base` commands before it. A zero barrier +/// waits for every earlier SUBMIT; NONE waits for nothing in this SUBMIT; a prior names an +/// ordinal accepted before it. The ordinals themselves are not kept: the engine's total order +/// satisfies every valid one. +fn check_order(base: [u64; 2], preceding: [u16; 2], barriers: [u16; 2], prior: [u64; 2]) -> Result { + for index in 0..2 { + // Earlier commands in this ioctl are not historical commands. + if prior[index] > base[index] { + return Err(EINVAL); + } + base[index] + .checked_add(u64::from(preceding[index])) + .and_then(|value| value.checked_add(1)) + .ok_or(EOVERFLOW)?; + if barriers[index] != NONE { + if barriers[index] > preceding[index] { + return Err(EINVAL); + } + base[index] + .checked_add(u64::from(barriers[index])) + .ok_or(EOVERFLOW)?; + } + } + Ok(()) +} + +/// A validated render command. +pub(crate) struct RenderCommand { + /// The payload, zero-extended to the full UAPI structure. + pub(crate) cmd: uapi::drm_asahi_cmd_render, + /// Firmware arena VAs of the timestamp slots (vertex start/end, fragment start/end), 0 if + /// unused. + pub(crate) timestamps: [u64; 4], +} + +/// A validated compute command. +pub(crate) struct ComputeCommand { + pub(crate) cmd: uapi::drm_asahi_cmd_compute, + /// The compute attachments in effect (validated writable). + pub(crate) attachments: KVec, + /// Firmware arena VAs of the start and end timestamp slots, 0 if unused. + pub(crate) timestamps: [u64; 2], +} + +/// A validated command. +pub(crate) enum Command { + Render(KBox), + Compute(KBox), +} + +/// A validated SUBMIT. +pub(crate) struct Submission { + /// The commands, in submission order. + pub(crate) commands: KVec, + /// Render and compute commands, for the queue's EXACT_PRIOR ordinals. + pub(crate) counts: [u64; 2], + /// The timestamp buffers the commands name, retained with the job. + pub(crate) timestamps: KVec>, +} + +/// What the per-command checks need. +pub(crate) struct Context<'a> { + /// The submitting VM. + pub(crate) vm: &'a mmu::Vm, + /// The queue's USC window base. + pub(crate) usc_base: u64, +} + +/// A stream whose timestamps and ordinals are resolved ([`prepare`]), before its spans are +/// checked ([`Prepared::validate`]). +pub(crate) struct Prepared<'a> { + bytes: &'a [u8], + /// Arena VAs of each command's timestamp slots. + resolved: KVec<[u64; 4]>, + counts: [u64; 2], + timestamps: KVec>, +} + +/// One command of the stream. +struct Entry<'a> { + kind: u32, + barriers: [u16; 2], + payload: &'a [u8], +} + +/// Iterates the commands of a structurally valid stream. +struct Stream<'a> { + bytes: &'a [u8], +} + +impl<'a> Iterator for Stream<'a> { + type Item = Result>; + + fn next(&mut self) -> Option { + if self.bytes.is_empty() { + return None; + } + let entry = (|| { + if self.bytes.len() < HEADER_SIZE { + return Err(EINVAL); + } + let header: uapi::drm_asahi_cmd_header = Reader::new(self.bytes).read()?; + let size = header.size as usize; + let payload = self + .bytes + .get(HEADER_SIZE..HEADER_SIZE + size) + .ok_or(EINVAL)?; + if size % 8 != 0 { + return Err(EINVAL); + } + self.bytes = &self.bytes[HEADER_SIZE + size..]; + Ok(Entry { + kind: header.cmd_type.into(), + barriers: [header.vdm_barrier, header.cdm_barrier], + payload, + }) + })(); + if entry.is_err() { + self.bytes = &[]; + } + Some(entry) + } +} + +fn stream(bytes: &[u8]) -> Stream<'_> { + Stream { bytes } +} + +/// Decodes a payload: short ones are zero-filled, bytes past the known structure must be zero. +fn payload(bytes: &[u8]) -> Result { + if bytes + .get(size_of::()..) + .is_some_and(|tail| tail.iter().any(|&byte| byte != 0)) + { + return Err(EINVAL); + } + Reader::new(bytes).read_up_to(bytes.len()) +} + +/// Whether `[start, start + size)` is a nonempty range inside `range`. +fn inside(start: u64, size: u64, range: &Range) -> bool { + size != 0 && start >= range.start && start < range.end && size <= range.end - start +} + +fn helper_is_empty(helper: &uapi::drm_asahi_helper_program) -> bool { + helper.binary == 0 && helper.cfg == 0 && helper.data == 0 +} + +/// Structural validation of a whole command stream, before anything is looked up. +pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { + if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { + return Err(EINVAL); + } + let range = hw::USER_RANGE; + let mut counts = [0u32; 2]; + for entry in stream(bytes) { + let entry = entry?; + match entry.kind { + SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { + if entry.barriers != [NONE; 2] + || entry.payload.len() % ATTACHMENT_SIZE != 0 + || entry.payload.len() / ATTACHMENT_SIZE > hw::sizes::MAX_ATTACHMENTS + { + return Err(EINVAL); + } + for bytes in entry.payload.chunks_exact(ATTACHMENT_SIZE) { + let attachment: uapi::drm_asahi_attachment = Reader::new(bytes).read()?; + if attachment.pad != 0 + || attachment.flags != 0 + || !inside(attachment.pointer, attachment.size, &range) + { + return Err(EINVAL); + } + } + continue; + } + _ => {} + } + if (entry.barriers[RENDER] != NONE && u32::from(entry.barriers[RENDER]) > counts[RENDER]) + || (entry.barriers[COMPUTE] != NONE + && u32::from(entry.barriers[COMPUTE]) > counts[COMPUTE]) + { + return Err(EINVAL); + } + match entry.kind { + CMD_RENDER => { + let cmd: uapi::drm_asahi_cmd_render = payload(entry.payload)?; + // G15S resource words are 64-bit: RSRC_SPEC_HI is always accepted. + let allowed = VERTEX_SCRATCH + | PROCESS_EMPTY_TILES + | NO_VERTEX_CLUSTERING + | DBIAS_IS_INT + | RSRC_SPEC_HI + | if early_tiling { FRAGMENT_BARRIERS } else { 0 }; + if cmd.flags & !allowed != 0 + || !(1..=MAX_DIMENSION).contains(&cmd.width_px) + || !(1..=MAX_DIMENSION).contains(&cmd.height_px) + || !(1..=MAX_LAYERS).contains(&cmd.layers) + || !matches!(cmd.samples, 1 | 2 | 4) + { + return Err(EINVAL); + } + // RENDER_RAY_QUERY is never advertised. + if entry + .payload + .get(RAY_QUERY..) + .is_some_and(|tail| tail.iter().any(|&byte| byte != 0)) + { + return Err(EINVAL); + } + // Never discard unflagged high words, nor accept the flag without them. + if cmd.flags & RSRC_SPEC_HI != 0 && entry.payload.len() < RSRC_SPEC_HI_MIN { + return Err(EINVAL); + } + if cmd.flags & RSRC_SPEC_HI == 0 + && (cmd.bg_eot_rsrc_spec_hi != 0 + || cmd.bg_eot_partial_rsrc_spec_hi != 0 + || cmd.bg_rsrc_spec_hi != 0 + || cmd.bg_partial_rsrc_spec_hi != 0) + { + return Err(EINVAL); + } + counts[RENDER] += 1; + } + CMD_COMPUTE => { + let cmd: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; + if cmd.flags != 0 + || cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base + || !inside( + cmd.cdm_ctrl_stream_base, + cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, + &range, + ) + { + return Err(EINVAL); + } + // The G17P scratch layout and intersection tables: never on G15. + if cmd.scs_layout != 0 + || cmd.cdm_auxiliary_allocation != 0 + || cmd.reserved != 0 + || cmd.intersection_pool != 0 + || cmd.intersection_pool_bytes != 0 + || cmd.intersection_first != 0 + || cmd.intersection_count != 0 + || cmd.intersection_default_program != 0 + || cmd.intersection_default_control != 0 + { + return Err(EINVAL); + } + counts[COMPUTE] += 1; + } + _ => return Err(EINVAL), + } + if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { + return Err(EINVAL); + } + } + if counts == [0; 2] { + return Err(EINVAL); + } + Ok(()) +} + +/// The timestamp buffers named by a submission, resolved to firmware arena VAs. +struct Timestamps<'a> { + objects: Pin<&'a xarray::XArray>>, + held: KVec>, +} + +impl Timestamps<'_> { + /// The arena VA of one requested timestamp, 0 if none: unknown handle ENOENT; offset not + /// 8-aligned or not 8 bytes inside the bound range EINVAL. + fn resolve(&mut self, timestamp: &uapi::drm_asahi_timestamp) -> Result { + if timestamp.handle == 0 { + return Ok(0); + } + let object = self + .objects + .lock() + .get(timestamp.handle.try_into()?) + .ok_or(ENOENT)? + .clone(); + let file::Object::TimestampBuffer(mapping) = object; + let offset = timestamp.offset as usize; + if offset % 8 != 0 || offset >= mapping.size() || mapping.size() - offset < 8 { + return Err(EINVAL); + } + let va = mapping.iova() + offset as u64; + if !self.held.iter().any(|held| Arc::ptr_eq(held, &mapping)) { + self.held.push(mapping, GFP_KERNEL)?; + } + Ok(va) + } +} + +/// Checks that `[start, end)` (rounded out to pages) is user memory mapped with the requested +/// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a +/// page without the access EACCES. +pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { + let mask = mmu::UAT_PGMSK as u64; + if end <= start { + return Err(EINVAL); + } + let first = start & !mask; + let last = end.checked_add(mask).ok_or(EINVAL)? & !mask; + // Every G15 driver mapping of a user VM is a client alias inside the fixed reserved ranges + // (`vm::ClientAlias::check`), so testing those three ranges finds every driver range without + // walking the alias mappings under the VM's lifetime lock on each span. + if super::vm::reserved_ranges() + .iter() + .any(|reserved| first < reserved.end && reserved.start < last) + { + return Err(ENOENT); + } + let range = hw::USER_RANGE; + if first < range.start || last > range.end { + return Err(EINVAL); + } + if vm.covers_range(first, last - first, read, write) { + Ok(()) + } else if vm.covers_range(first, last - first, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + } +} + +/// Attachment spans, 128-byte granular, actually mapped with `write` or read access. +fn check_attachments(vm: &mmu::Vm, list: &[uapi::drm_asahi_attachment], write: bool) -> Result { + for attachment in list { + let end = attachment + .pointer + .checked_add(attachment.size) + .ok_or(EINVAL)?; + if end > u64::MAX - 127 { + return Err(EINVAL); + } + let first = attachment.pointer & !127; + let last = (end + 127) & !127; + if (last - first) / 128 > u64::from(u32::MAX) { + return Err(EINVAL); + } + cover(vm, first, last, !write, write)?; + } + Ok(()) +} + +/// Parses the attachment list of a SET_*_ATTACHMENTS command. +fn attachment_list(bytes: &[u8]) -> Result> { + let mut list = KVec::with_capacity(bytes.len() / ATTACHMENT_SIZE, GFP_KERNEL)?; + for bytes in bytes.chunks_exact(ATTACHMENT_SIZE) { + list.push(Reader::new(bytes).read()?, GFP_KERNEL)?; + } + Ok(list) +} + +fn copy_list(lists: &[&[uapi::drm_asahi_attachment]]) -> Result> { + let mut copy = KVec::with_capacity(lists.iter().map(|list| list.len()).sum(), GFP_KERNEL)?; + for list in lists { + for attachment in list.iter() { + copy.push(*attachment, GFP_KERNEL)?; + } + } + Ok(copy) +} + +/// Whether a GVA can be named by a 32-bit compact pointer. +fn compact(gva: u64) -> bool { + hw::client::COMPACT_WINDOW.contains(&gva) +} + +/// TPC and tilemap bytes of a render pass (the encoder computes the full geometry with the same +/// formulas). +fn geometry_bytes(cmd: &uapi::drm_asahi_cmd_render) -> (u64, u64) { + let tiles_x = u64::from(cmd.width_px).div_ceil(32); + let tiles_y = u64::from(cmd.height_px).div_ceil(32); + let blocks_x = tiles_x.div_ceil(4).next_multiple_of(4); + let blocks_y = tiles_y.div_ceil(4).next_multiple_of(4); + let sx = blocks_x * if cmd.utile_width_px == 16 { 2 } else { 1 }; + let sy = blocks_y * if cmd.utile_height_px == 16 { 2 } else { 1 }; + let e = (4 * sx) * (4 * sy); + let layers = u64::from(cmd.layers); + let tilemap = (5 * e * layers).next_multiple_of(0x1000); + let tpc = 2 * e * 8 * layers; + (tpc, tilemap) +} + +/// Per-command render admission. +fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { + let vm = context.vm; + let allowed = PROCESS_EMPTY_TILES + | NO_VERTEX_CLUSTERING + | RSRC_SPEC_HI + | DBIAS_IS_INT + | if super::params::early_tiling() { + FRAGMENT_BARRIERS + } else { + 0 + }; + let tile_buffer = u32::from(cmd.sample_size_B) + * u32::from(cmd.utile_width_px) + * u32::from(cmd.utile_height_px) + * u32::from(cmd.samples); + if cmd.flags & !allowed != 0 + || !(1..=MAX_DIMENSION).contains(&cmd.width_px) + || !(1..=MAX_DIMENSION).contains(&cmd.height_px) + || !(1..=MAX_LAYERS).contains(&cmd.layers) + || !matches!(cmd.samples, 1 | 2 | 4) + || !matches!(cmd.utile_width_px, 16 | 32) + || !matches!(cmd.utile_height_px, 16 | 32) + || cmd.sample_size_B % 8 != 0 + || tile_buffer > MAX_TILE_BUFFER + || cmd.sampler_heap != 0 + || cmd.sampler_count != 0 + || !helper_is_empty(&cmd.vertex_helper) + || !helper_is_empty(&cmd.fragment_helper) + || cmd.ppp_ctrl & !0x203 != 0 + { + return Err(EINVAL); + } + if cmd.stencil.comp_base != 0 + || cmd.stencil.comp_stride != 0 + || (cmd.depth.comp_base != 0 && (cmd.layers != 1 || cmd.samples != 1)) + { + return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); + } + // The FS work's partial-EOT resource slots are 32 bits wide: a high word could only be + // dropped. + if cmd.flags & RSRC_SPEC_HI != 0 && cmd.bg_eot_partial_rsrc_spec_hi != 0 { + return Err(EINVAL); + } + // VDM: compact-addressable and readable; scissor: 8-aligned and readable. + let vdm = cmd.vdm_ctrl_stream_base; + let scissor = cmd.isp_scissor_base; + if vdm & 3 != 0 || !compact(vdm) || scissor == 0 || scissor & 7 != 0 { + return Err(EINVAL); + } + cover(vm, vdm, vdm + 4, true, false)?; + gate::vdm(vm, vdm)?; + cover(vm, scissor, scissor.checked_add(8).ok_or(EINVAL)?, true, false)?; + if cmd.isp_dbias_base != 0 { + let base = cmd.isp_dbias_base; + cover(vm, base, base.checked_add(8).ok_or(EINVAL)?, true, false)?; + } + if cmd.isp_oclqry_base != 0 { + let base = cmd.isp_oclqry_base & !15; + cover(vm, base, base.checked_add(8).ok_or(EINVAL)?, false, true)?; + } + for program in [&cmd.bg, &cmd.eot, &cmd.partial_bg, &cmd.partial_eot] { + if program.usc == 0 { + continue; + } + let address = context + .usc_base + .checked_add(u64::from(program.usc & !63)) + .ok_or(EINVAL)?; + cover( + vm, + address, + address.checked_add(64).ok_or(EINVAL)?, + true, + false, + )?; + } + let (tpc, tilemap) = geometry_bytes(cmd); + if tpc > hw::client::TPC_SIZE || tilemap > hw::client::TILEMAP_SIZE { + return Err(E2BIG); + } + Ok(()) +} + +/// Per-command compute admission. +fn check_compute( + context: &Context<'_>, + cmd: &uapi::drm_asahi_cmd_compute, + attachments: &[uapi::drm_asahi_attachment], +) -> Result { + let vm = context.vm; + let (base, end) = (cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end); + if cmd.flags != 0 + || cmd.sampler_count != 0 + || cmd.sampler_heap != 0 + || !helper_is_empty(&cmd.helper) + || base & 3 != 0 + || end & 3 != 0 + || end <= base + { + return Err(EINVAL); + } + cover(vm, base, end, true, false)?; + gate::cdm(vm, context.usc_base, base)?; + check_attachments(vm, attachments, true) +} + +/// Resolves the timestamps and EXACT_PRIOR ordinals of a structurally valid stream +/// ([`check_stream`]) for a queue that accepted `accepted` render and compute commands before +/// this ioctl. +pub(crate) fn prepare<'a>( + bytes: &'a [u8], + accepted: [u64; 2], + objects: Pin<&xarray::XArray>>, +) -> Result> { + // Timestamps of every command first. + let mut timestamps = Timestamps { + objects, + held: KVec::new(), + }; + let mut resolved: KVec<[u64; 4]> = KVec::new(); + for entry in stream(bytes) { + let entry = entry?; + let slots = match entry.kind { + CMD_RENDER => { + let cmd: uapi::drm_asahi_cmd_render = payload(entry.payload)?; + [ + timestamps.resolve(&cmd.ts_vtx.start)?, + timestamps.resolve(&cmd.ts_vtx.end)?, + timestamps.resolve(&cmd.ts_frag.start)?, + timestamps.resolve(&cmd.ts_frag.end)?, + ] + } + CMD_COMPUTE => { + let cmd: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; + [ + timestamps.resolve(&cmd.ts.start)?, + timestamps.resolve(&cmd.ts.end)?, + 0, + 0, + ] + } + _ => continue, + }; + resolved.push(slots, GFP_KERNEL)?; + } + + // Historical priors and header barriers. + let mut preceding = [0u16; 2]; + for entry in stream(bytes) { + let entry = entry?; + let (engine, prior) = match entry.kind { + CMD_RENDER => { + let cmd: uapi::drm_asahi_cmd_render = payload(entry.payload)?; + (RENDER, [cmd.prior_vdm, cmd.prior_cdm]) + } + CMD_COMPUTE => { + let cmd: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; + (COMPUTE, [cmd.prior_vdm, cmd.prior_cdm]) + } + _ => continue, + }; + check_order(accepted, preceding, entry.barriers, prior)?; + preceding[engine] += 1; + } + + Ok(Prepared { + bytes, + resolved, + counts: [u64::from(preceding[RENDER]), u64::from(preceding[COMPUTE])], + timestamps: timestamps.held, + }) +} + +impl Prepared<'_> { + /// Checks each command's spans, programs and stream gates, with a job reference on the VM + /// already held so that the checked mappings are retained until the job retires. + pub(crate) fn validate(self, context: &Context<'_>) -> Result { + let Prepared { + bytes, + resolved, + counts, + timestamps, + } = self; + let mut commands = KVec::with_capacity(resolved.len(), GFP_KERNEL)?; + let mut compute = KVec::new(); + let mut index = 0; + for entry in stream(bytes) { + let entry = entry?; + match entry.kind { + SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS => { + // Validated readable, never serialized on G15. + check_attachments(context.vm, &attachment_list(entry.payload)?, false)?; + } + SET_COMPUTE_ATTACHMENTS => compute = attachment_list(entry.payload)?, + CMD_RENDER => { + let cmd: uapi::drm_asahi_cmd_render = payload(entry.payload)?; + check_render(context, &cmd)?; + commands.push( + Command::Render(KBox::new( + RenderCommand { + cmd, + timestamps: *resolved.get(index).ok_or(EINVAL)?, + }, + GFP_KERNEL, + )?), + GFP_KERNEL, + )?; + index += 1; + } + CMD_COMPUTE => { + let cmd: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; + check_compute(context, &cmd, &compute)?; + let slots = resolved.get(index).ok_or(EINVAL)?; + commands.push( + Command::Compute(KBox::new( + ComputeCommand { + cmd, + attachments: copy_list(&[&compute])?, + timestamps: [slots[0], slots[1]], + }, + GFP_KERNEL, + )?), + GFP_KERNEL, + )?; + index += 1; + } + _ => return Err(EINVAL), + } + } + if commands.is_empty() { + return Err(EINVAL); + } + Ok(Submission { + counts, + commands, + timestamps, + }) + } +} diff --git a/drivers/gpu/drm/asahi/g15/encode.rs b/drivers/gpu/drm/asahi/g15/encode.rs new file mode 100644 index 00000000000000..e46ecd05bdf78b --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/encode.rs @@ -0,0 +1,1017 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Work-image and microsequence encoders. +//! +//! Stamps for ordinal n start from the seeds compute 0xc1000000, TA 0x7a000000 and FS +//! 0x3d000000. The compute image sets the compute fault mask at start +0x30 = 1 and interior +//! +0x804 = 1. [`Geometry`] holds the tiling geometry and register words derived from +//! `drm_asahi_cmd_render`; [`ClusterLayout`] the 64 segments and M1..M4 of clustered tiling. +//! Program addresses are `usc_base + (usc & !63)`; resource words take optional high 32 bits +//! (G15S resource words are 64-bit). The TA image sets register #33 PBREQ = initial PB size and +//! interior +0x880 = 1; the FS image carries the partial background/EOT programs for partial +//! renders (the partial-EOT resource word is 32-bit). The scene and InitBM records prefix a +//! render. +//! +//! Pure byte builders over [`super::fw::work`] layouts: no locks, no allocation, no +//! publication. Every address an image names comes in through [`ComputeRefs`], [`RenderRefs`] +//! and [`PassRefs`], resolved by the engine from its firmware objects; the firmware writes +//! timestamps in ns directly through the timestamp arena VAs. The words are written at literal +//! offsets in image order. This file only depends on `core`, the UAPI and the `hw`/`fw::work` +//! constants. + +use super::wire as uapi; + +use super::fw::work::{self, barrier, compute, fs, initbm, scene, ta, tail, ts_record, REG_RECORD}; +use super::hw; + +/// Stores `v` little-endian at `off`. Every offset is a literal inside a fixed-size image; an +/// out-of-range store is dropped rather than panicking. +#[inline(always)] +fn put(b: &mut [u8], off: usize, v: &[u8]) { + if let Some(dst) = b.get_mut(off..off + v.len()) { + dst.copy_from_slice(v); + } +} + +#[inline(always)] +fn put8(b: &mut [u8], off: usize, v: u8) { + put(b, off, &[v]); +} + +#[inline(always)] +fn put16(b: &mut [u8], off: usize, v: u16) { + put(b, off, &v.to_le_bytes()); +} + +#[inline(always)] +fn put32(b: &mut [u8], off: usize, v: u32) { + put(b, off, &v.to_le_bytes()); +} + +#[inline(always)] +fn put64(b: &mut [u8], off: usize, v: u64) { + put(b, off, &v.to_le_bytes()); +} + +/// `DIV_ROUND_UP`. +const fn div_round_up(n: u64, d: u64) -> u64 { + n.div_ceil(d) +} + +/// `round_up` / `ALIGN` to a power of two, wrapping on overflow (no panic). +const fn align(n: u64, a: u64) -> u64 { + n.wrapping_add(a - 1) & !(a - 1) +} + +/// Firmware stamp value of ordinal `n` on the queue with this seed. +/// Stamps step by 0x100 through 0xffffff values and never read 0. +pub(crate) const fn stamp_seed(seed: u32, n: u64) -> u32 { + let base = (seed / 0x100) as u64; + ((((base - 1 + n % 0xffffff) % 0xffffff) + 1) * 0x100) as u32 +} + +/// Compute stamp of ordinal `n`. +pub(crate) const fn stamp(n: u64) -> u32 { + stamp_seed(hw::engine::COMPUTE_SEED, n) +} + +/// 32-bit compact pointer of a GVA in the compact window. +pub(crate) const fn compact(gva: u64) -> u64 { + gva.wrapping_sub(0x1000000000) +} + +/// Addresses the compute encoder names: compute graph and compute slot buffers. +#[derive(Copy, Clone, Default)] +pub(crate) struct ComputeRefs { + /// HardwareData (firmware VA): the activity records the sequence names. + pub(crate) hwdata: u64, + /// Graph: notifier, queue info, user/firmware stamps, UMA manager (firmware VAs). + pub(crate) notifier: u64, + pub(crate) qinfo: u64, + pub(crate) user_stamp: u64, + pub(crate) fw_stamp: u64, + pub(crate) manager: u64, + /// Slot: work image (firmware VA and client GVA of the payload), sequence, preemption + /// buffer (client GVA), internal timestamp cells, tail and sequence scratch (firmware VAs). + pub(crate) work: u64, + pub(crate) work_gva: u64, + pub(crate) seq: u64, + pub(crate) preempt_gva: u64, + pub(crate) its: u64, + pub(crate) tail: u64, + pub(crate) scratch: [u64; 5], +} + +/// Encodes compute command `c` as ordinal `n`. The engine copies the result into the slot +/// after zeroing the slot's images. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_compute( + r: &ComputeRefs, + regs_cfg: &hw::ComputeRegs, + c: &uapi::drm_asahi_cmd_compute, + att: &[uapi::drm_asahi_attachment], + ts_va: &[u64; 2], + ctx: u32, + n: u64, + fault_mask: u32, + w: &mut [u8; compute::WORK_SIZE], + q: &mut [u8; compute::SEQ_SIZE], +) { + let (wv, qv, h, pre) = (r.work, r.qinfo, r.hwdata, r.preempt_gva); + let t = stamp(n); + let att_count = att.len().min(hw::sizes::MAX_ATTACHMENTS); + // The saved-state pointers into the preemption buffer and the two 0x1c words; a SoC + // encoded "fresh" carries zero in all six, as a first command does. + let (saved, word) = if regs_cfg.fresh { + (0, 0) + } else { + (pre + regs_cfg.tail, 0x1c) + }; + let step = |i: u64| if saved == 0 { 0 } else { saved + 8 * i }; + let val: [u64; 22] = [ + pre, + c.cdm_ctrl_stream_base, + step(0), + step(1), + step(2), + step(3), + 0x154024201, + 0x10c08860, + word, + word, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + regs_cfg.reg_1a0e9, + 0xff0000, + regs_cfg.ptc, + regs_cfg.dupm, + ]; + + w.fill(0); + q.fill(0); + + // Work image. + put32(w, 0x0, work::work_type::COMPUTE); + put64(w, 0x4, (n as u32).wrapping_sub(1) as u64); + put32(w, 0x10, ctx); + put64(w, 0x14, r.notifier); + regs(&mut w[compute::REGS..], &compute::SEL, &val); + put64(w, 0x720, r.work_gva + compute::REGS as u64); + put16(w, 0x728, 22); + put16(w, 0x72a, (22 * REG_RECORD) as u16); + put64(w, 0x760, r.seq); + put32(w, 0x768, compute::SEQ_SIZE as u32); + put64(w, 0x794, pre); + put64(w, 0x79c, c.cdm_ctrl_stream_end.wrapping_sub(4)); + put64(w, 0x7c4, 0x154024201); + put32(w, 0x7e0, 0xffffffff); + put64(w, 0x7e8, r.user_stamp); + put64(w, 0x7f0, r.fw_stamp); + put32(w, 0x7f8, t); + put32(w, 0x7fc, hw::engine::EVENT_SLOT); + put32(w, 0x804, 1); + put32(w, 0x808, hw::engine::COMPUTE_UUID); + put32(w, 0x80c, (n as u32).wrapping_sub(1)); + put64(w, 0x818, r.its); + put64(w, 0x820, r.its + 8); + put64(w, 0x828, ts_va[0]); + put64(w, 0x830, ts_va[1]); + put64(w, 0x83e, r.manager); + put8(w, 0x846, 1); + put64(w, 0x847, 0xad0000); + put64(w, 0x84f, 0x1600000); + put64(w, 0x857, r.tail); + put8(w, 0x85f, 1); + + // Microsequence: start. + put32(q, 0x0, work::op::COMPUTE_START); + put64(q, 0x14, wv + 0x20); + put64(q, 0x1c, h + compute::HWDATA); + put64(q, 0x24, qv); + put32(q, 0x2c, ctx); + put32(q, 0x30, if fault_mask != 0 { 1 } else { 0 }); + put32(q, 0x34, 0); + put64(q, 0x44, wv + 0x76c); + put32(q, 0x50, hw::engine::COMPUTE_UUID); + for (a, at) in att.iter().take(att_count).enumerate() { + let base = at.pointer & !127; + let end = align(at.pointer.wrapping_add(at.size), 128); + let rec = compute::ATTACHMENTS + compute::ATTACHMENT_STRIDE * a; + + put64(q, rec, base); + put32(q, rec + 8, (end.wrapping_sub(base) / 128) as u32); + put16(q, rec + 0xc, 0x17); + put16(q, rec + 0xe, 1); + } + put32(q, 0x154, att_count as u32); + put64(q, 0x15c, r.manager); + put64(q, 0x174, r.scratch[0]); + put64(q, 0x184, r.scratch[1]); + put64(q, 0x18c, r.scratch[2]); + put64(q, 0x194, r.scratch[3]); + put64(q, 0x19c, r.scratch[4]); + put64(q, 0x1a4, wv + 0x880); + put64(q, 0x1b4, r.notifier + 0xa8); + // Start and end timestamp records: the 0x3c record over the cells at W + 0x810. Both + // records name the user pair base when any output is held. + let requested = ts_va[0] != 0 || ts_va[1] != 0; + for t_end in [false, true] { + let at = if t_end { + compute::TS_END + } else { + compute::TS_START + }; + ts_record( + &mut q[at..], + t_end, + wv, + compute::TS_CELLS, + qv, + requested, + hw::engine::COMPUTE_UUID, + ); + } + put32(q, 0x1f8, 1); + // Finalize and END. + let f = compute::FINALIZE; + put32(q, f, work::op::COMPUTE_FINALIZE); + put64(q, f + 0x4, h + compute::HWDATA); + put64(q, f + 0xc, qv); + put32(q, f + 0x14, ctx); + put64(q, f + 0x18, wv + 0x76c); + put32(q, f + 0x24, hw::engine::COMPUTE_UUID); + put64(q, f + 0x28, r.fw_stamp); + put32(q, f + 0x30, t); + put64(q, f + 0x58, wv + 0x83e); + put32(q, f + 0x60, 0u32.wrapping_sub(f as u32)); + put8(q, f + 0x64, if att_count != 0 { 1 } else { 0 }); + put64(q, f + 0x65, wv + 0x880); + put64(q, f + 0x6d, wv + 0x860); + put32(q, compute::END, work::op::END); +} + +/// Tiling geometry and register words of a render (accelerator count 2). +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)] +pub(crate) struct Geometry { + pub(crate) tx: u32, + pub(crate) ty: u32, + pub(crate) bx: u32, + pub(crate) by: u32, + pub(crate) sx: u32, + pub(crate) sy: u32, + pub(crate) pixels: u32, + pub(crate) screen: u32, + pub(crate) blocks: u32, + pub(crate) tiles: u32, + pub(crate) region_stride: u32, + pub(crate) tpc_stride: u32, + pub(crate) isp_blocks: u32, + pub(crate) utile_config: u32, + pub(crate) layer_mode: u32, + pub(crate) tilebuffer_control: u32, + pub(crate) tile_mode: u32, + pub(crate) isp_control: u32, + pub(crate) e: u64, + pub(crate) x_blocks: u64, + pub(crate) y_blocks: u64, + pub(crate) tilemap_bytes: u64, + pub(crate) tpc_bytes: u64, + pub(crate) layer_metadata: u64, + pub(crate) native_tiles: u64, +} + +impl Geometry { + /// The geometry of render `u` with layer metadata at `heap`. The render was validated + /// (width, height, layers >= 1, samples 1, 2 or 4, utiles 16 or 32). + pub(crate) fn new(u: &uapi::drm_asahi_cmd_render, heap: u64) -> Self { + let (w, h, l) = (u.width_px as u32, u.height_px as u32, u.layers as u32); + let empty = + u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES != 0; + let log2s = (u.samples as u32).max(1).ilog2(); + let mut g = Geometry::default(); + + g.tx = div_round_up(w as u64, 32) as u32; + g.ty = div_round_up(h as u64, 32) as u32; + g.bx = align(div_round_up(g.tx as u64, 4), 4) as u32; + g.by = align(div_round_up(g.ty as u64, 4), 4) as u32; + g.sx = g.bx * if u.utile_width_px == 16 { 2 } else { 1 }; + g.sy = g.by * if u.utile_height_px == 16 { 2 } else { 1 }; + g.e = (4 * g.sx as u64) * (4 * g.sy as u64); + g.pixels = w.wrapping_sub(1) | h.wrapping_sub(1) << 16; + g.screen = g.tx.wrapping_sub(1) | g.ty.wrapping_sub(1) << 12; + g.x_blocks = (g.bx as u64) << 10 | (g.bx as u64) << 18 | 3 * g.bx as u64; + g.y_blocks = (g.by as u64) << 18 | (g.by as u64) << 10 | 3 * g.by as u64; + g.blocks = g.bx * g.by; + g.tiles = g.tx * g.ty; + g.region_stride = (5 * g.e / 64) as u32; + g.tpc_stride = (g.e / 8) as u32; + g.isp_blocks = ((g.sx & 0x3fd) << 16) | (g.sy & 0x3fd); + let utile_w = if u.utile_width_px == 32 { + 0x2000 + } else { + 0x1000 + }; + let utile_h = if u.utile_height_px == 32 { + 0x8000 + } else { + 0x4000 + }; + g.utile_config = utile_w | utile_h | log2s; + g.tilemap_bytes = align(5 * g.e * l as u64, 0x1000); + g.tpc_bytes = 2 * g.e * 8 * l as u64; + g.layer_metadata = heap + if l > 1 { 0x200 } else { 0 }; + g.layer_mode = if l == 1 { + 0x8000 + } else { + 0xc000 | (if empty { 0x2000 } else { 0x1000 }) | l.wrapping_sub(1) + }; + g.tilebuffer_control = div_round_up( + u.sample_size_B as u64 + * u.utile_width_px as u64 + * u.utile_height_px as u64 + * u.samples as u64, + 2048, + ) as u32 + | log2s << 17; + g.tile_mode = 0x280 | (l > 1) as u32 | if empty { 1 << 16 } else { 0 }; + g.isp_control = 0xc000 | (u.flags & (1 << 18)); + g.native_tiles = 221201u64 + | ((l > 1) as u64) << 32 + | (g.tx.wrapping_sub(1) as u64) << 44 + | (g.ty.wrapping_sub(1) as u64) << 53 + | 137438953472u64 + | ((g.utile_config & 0xf000) as u64) << 28; + g + } +} + +/// Clustered tiling layout from `base`: 64 segments of 5E bytes, then M2 (0xc00), M3 (0xa00), +/// M4 ((Q + 1) x 512 for Q = pages of the owned PB / 0x1800, rounded up) and the 128-aligned +/// 0x80-byte M1. +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)] +pub(crate) struct ClusterLayout { + pub(crate) ct: u64, + pub(crate) m1: u64, + pub(crate) m2: u64, + pub(crate) m3: u64, + pub(crate) m4: u64, + pub(crate) bytes: u64, +} + +impl ClusterLayout { + pub(crate) fn new(geo: &Geometry, base: u64) -> Self { + let q = div_round_up(div_round_up(hw::client::PB_HEAP_SIZE, 0x8000), 0x1800); + let ct = base; + let m2 = base + align(64 * 5 * geo.e, 32); + let m3 = m2 + 0xc00; + let m4 = m3 + 0xa00; + let m1 = base + align(m4 - base + (q + 1) * 8 * 64, 128); + ClusterLayout { + ct, + m1, + m2, + m3, + m4, + bytes: m1 + 0x80 - base, + } + } +} + +/// Clustered tiling eligibility: one layer, one sample, 32x32 utiles, unless the submission +/// asked for single-cluster vertex work. The engine then also needs a clustering buffer that +/// holds [`ClusterLayout::bytes`]. +pub(crate) fn cluster_eligible(u: &uapi::drm_asahi_cmd_render, geo: &Geometry) -> bool { + hw::tuning::VERTEX_CLUSTERING + && u.layers == 1 + && geo.utile_config == 0xa000 + && u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING == 0 +} + +/// Program address. +pub(crate) fn prog_addr(usc_base: u64, p: &uapi::drm_asahi_bg_eot) -> u64 { + usc_base.wrapping_add((p.usc & !63) as u64) +} + +/// Program resource word, 64-bit with RSRC_SPEC_HI. +pub(crate) fn prog_rsrc( + u: &uapi::drm_asahi_cmd_render, + p: &uapi::drm_asahi_bg_eot, + hi: u32, +) -> u64 { + if u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_RSRC_SPEC_HI != 0 { + (hi as u64) << 32 | p.rsrc_spec as u64 + } else { + p.rsrc_spec as u64 + } +} + +/// Register records. +pub(crate) fn regs(dst: &mut [u8], sel: &[u32], val: &[u64]) { + for (i, (s, v)) in sel.iter().zip(val.iter()).enumerate() { + put32(dst, REG_RECORD * i, *s); + put64(dst, REG_RECORD * i + 4, *v); + } +} + +/// The 0x3c timestamp record. +pub(crate) fn ts_record( + rec: &mut [u8], + end: bool, + w: u64, + b: u64, + q: u64, + requested: bool, + uuid: u32, +) { + let rec = match rec.get_mut(..ts_record::SIZE) { + Some(rec) => rec, + None => return, + }; + put32( + rec, + 0x0, + if end { + work::op::TIMESTAMP_END + } else { + work::op::TIMESTAMP + }, + ); + put64(rec, 0x4, w + b); + put64(rec, 0xc, w + b + 8); + put64(rec, 0x14, w + b + if end { 0x10 } else { 8 }); + put64(rec, 0x1c, q); + put64(rec, 0x24, if requested { w + b + 0x18 } else { 0 }); + put64(rec, 0x2c, w + b + 0x58); + put32(rec, 0x34, uuid); +} + +/// Shared work tail (TA +0x8a8, FS +0xbf0); mirrors the compute tail. +pub(crate) fn work_tail( + t: &mut [u8], + its_start: u64, + its_end: u64, + user_start: u64, + user_end: u64, + uma_mgr: u64, + scratch: u64, +) { + put64(t, tail::ITS_START, its_start); + put64(t, tail::ITS_END, its_end); + put64(t, tail::USER_START, user_start); + put64(t, tail::USER_END, user_end); + put64(t, tail::UMA_MANAGER, uma_mgr); + put8(t, 0x36, 1); + put64(t, 0x37, 0xad0000); + put64(t, 0x3f, 0x1600000); + put64(t, tail::SCRATCH, scratch); + put8(t, 0x4f, 1); +} + +/// A barrier record waiting until the stamp at `stamp_va` reaches `wait`: +/// `event` names the producing engine (0 TA, 1 FS, 2 compute), `own` is the waiter's stamp. +pub(crate) fn barrier( + stamp_va: u64, + wait: u32, + event: u32, + own: u32, + uuid: u32, + ty: work::BarrierType, +) -> [u8; barrier::SIZE] { + let mut x = [0u8; barrier::SIZE]; + + put32(&mut x, 0x0, work::op::BARRIER); + put64(&mut x, barrier::STAMP_VA, stamp_va); + put64(&mut x, barrier::STAMP_VA2, stamp_va); + put32(&mut x, barrier::WAIT, wait); + put32(&mut x, barrier::EVENT, event); + put32(&mut x, barrier::OWN, own); + put32(&mut x, barrier::UUID, uuid); + put32(&mut x, barrier::TYPE, ty as u32); + x +} + +/// Addresses the render encoders name that belong to the render graph and its allocators +/// (the UMA/PB objects are in `Pools`). +#[derive(Copy, Clone, Default)] +pub(crate) struct RenderRefs { + /// HardwareData (firmware VA): the activity records the sequences name. + pub(crate) hwdata: u64, + pub(crate) notifier: u64, + pub(crate) legacy_empty: u64, + /// Queue info, user and firmware stamps of the TA (0) and FS (1) queues. + pub(crate) qinfo: [u64; 2], + pub(crate) user_stamp: [u64; 2], + pub(crate) fw_stamp: [u64; 2], + /// Allocators in use (after a rebuild possibly the spare set): UMA managers of TA and FS, + /// PB manager, scene list, misc record; and the initial PB blocks. + pub(crate) uma_mgr: [u64; 2], + pub(crate) pb_mgr: u64, + pub(crate) scene_list: u64, + pub(crate) mgr_misc: u64, + pub(crate) pb_init_blocks: u32, +} + +/// Addresses of one pass slot. +#[derive(Copy, Clone, Default)] +pub(crate) struct PassRefs { + /// Work images: firmware VA and client GVA of the payload. + pub(crate) ta_work: u64, + pub(crate) ta_work_gva: u64, + pub(crate) fs_work: u64, + pub(crate) fs_work_gva: u64, + pub(crate) ta_seq: u64, + pub(crate) fs_seq: u64, + pub(crate) scene: u64, + /// Client GVAs. + pub(crate) tpc_gva: u64, + pub(crate) tilemap_gva: u64, + pub(crate) heap_gva: u64, + pub(crate) scene_user_gva: u64, + pub(crate) pre_gva: [u64; 3], + pub(crate) fs_scratch_gva: u64, + pub(crate) aux_gva: u64, + /// Firmware VAs. + pub(crate) its: u64, + pub(crate) ta_scratch: u64, +} + +/// Encodes the TA work image and microsequence of a render. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_ta( + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + tta: u32, + geo: &Geometry, + cl: Option<&ClusterLayout>, + w: &mut [u8; ta::WORK_SIZE], + q: &mut [u8; ta::SEQ_SIZE], +) { + let (wv, uv, qv, h) = (p.ta_work, p.ta_seq, r.qinfo[0], r.hwdata); + let (heap, su) = (p.heap_gva, p.scene_user_gva); + let ts = ts_va[0] != 0 || ts_va[1] != 0; + let mut val: [u64; 72] = [ + 1, + 0x200, + compact(p.tilemap_gva), + compact(p.tilemap_gva), + 0, + 0, + compact(p.tpc_gva), + compact(heap) | 1 << 63, + compact(heap) | 1 << 63, + 0x003a0012006b0003, + 1, + geo.utile_config as u64, + u.ppp_multisamplectl, + compact(p.pre_gva[0]), + compact(p.pre_gva[0]), + compact(p.pre_gva[1]), + compact(p.pre_gva[1]), + 1, + compact(p.pre_gva[2]) | 1 << 50, + 0, + compact(u.vdm_ctrl_stream_base), + 0, + 0, + 0, + 1, + 0, + compact(geo.layer_metadata), + compact(geo.layer_metadata), + 0, + 0, + 0, + 0, + 4 * r.pb_init_blocks as u64, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0x8860, + geo.region_stride as u64, + geo.region_stride as u64, + 0x88, + (2 | (u.ppp_ctrl & 0x201)) as u64, + geo.pixels as u64, + geo.screen as u64, + geo.x_blocks, + geo.y_blocks, + geo.blocks as u64, + geo.tpc_stride as u64, + 0x100, + geo.layer_mode as u64, + 0x1c, + 0x1c, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 8, + 0xff0000, + 0x7f00400020, + 0x200000001, + 0, + compact(su + 0x40), + compact(su + 0x40), + 0xa000000000 | ((r.scene_list + 4) & 0xfffffffff) | 1, + ]; + + if let Some(cl) = cl { + // The ten clustered TA values, compact form. + val[4] = compact(cl.ct); + val[5] = compact(cl.ct); + val[22] = compact(cl.m2); + val[23] = compact(cl.m3); + val[24] = 0x200440; + val[25] = 4; + val[30] = compact(cl.m4); + val[31] = compact(cl.m4); + val[ta::REG_PBREQ] = hw::sizes::CLUSTER_PB_PAGES as u64; + val[33] = compact(cl.m1); + } + + w.fill(0); + q.fill(0); + + // TA work image. + put32(w, 0x0, work::work_type::TA); + put64(w, 0x4, 1); + put32(w, 0xc, ctx); + put64(w, 0x14, r.notifier); + put64(w, 0x24, r.pb_mgr); + put64(w, 0x2c, p.scene); + put64(w, 0x34, r.legacy_empty); + regs(&mut w[ta::REGS..], &ta::SEL, &val); + put64(w, 0x740, p.ta_work_gva + ta::REGS as u64); + put16(w, 0x748, 72); + put16(w, 0x74a, (72 * REG_RECORD) as u16); + put64(w, 0x760, p.tpc_gva); + put64(w, 0x768, geo.tpc_bytes); + put64(w, 0x770, uv); + put32(w, 0x778, ta::SEQ_SIZE as u32); + put32(w, 0x77c, 1); + put32(w, 0x780, tta); + put64(w, 0x7a8, compact(p.pre_gva[0])); + put32(w, 0x840, 0x67); + put32(w, 0x848, 0xffffffff); + put32(w, 0x854, 1); + put64(w, 0x864, r.user_stamp[0]); + put64(w, 0x86c, r.fw_stamp[0]); + put32(w, 0x874, tta); + put32(w, 0x880, 1); + put32(w, 0x884, hw::engine::TA_UUID); + work_tail( + &mut w[ta::TAIL..], + p.its, + p.its + 8, + ts_va[0], + ts_va[1], + r.uma_mgr[0], + p.ta_scratch, + ); + + // TA microsequence. + put32(q, 0x0, work::op::TA_START); + put64(q, 0x14, wv + 0x40); + put64(q, 0x1c, r.pb_mgr); + put64(q, 0x24, p.scene); + put64(q, 0x2c, h + ta::HWDATA); + put64(q, 0x34, qv); + put64(q, 0x3c, wv + 0x84c); + put32(q, 0x44, ctx); + put64(q, 0x64, wv + 0x784); + put64(q, 0x6c, wv + 0x890); + put64(q, 0x78, (hw::engine::TA_UUID as u64) << 32); + put64(q, 0x18c, r.uma_mgr[0]); + put64(q, 0x1a4, p.ta_scratch); + put64(q, 0x1b4, 1); + put64(q, 0x1bc, r.notifier + 0xa8); + ts_record( + &mut q[ta::TS_START..], + false, + wv, + ta::TAIL as u64, + qv, + ts, + hw::engine::TA_UUID, + ); + put32(q, 0x208, 1); + ts_record( + &mut q[ta::TS_END..], + true, + wv, + ta::TAIL as u64, + qv, + ts, + hw::engine::TA_UUID, + ); + let f = ta::FINALIZE; + put32(q, f, work::op::TA_FINALIZE); + put64(q, f + 0x4, p.scene); + put64(q, f + 0xc, r.pb_mgr); + put64(q, f + 0x14, h + ta::HWDATA); + put64(q, f + 0x1c, qv); + put64(q, f + 0x24, wv + 0x84c); + put32(q, f + 0x2c, ctx); + put64(q, f + 0x34, wv + 0x784); + put32(q, f + 0x40, hw::engine::TA_UUID); + put64(q, f + 0x44, r.fw_stamp[0]); + put32(q, f + 0x4c, tta); + put64(q, f + 0x74, uv + 0x18c); + put32(q, f + 0x7c, 0u32.wrapping_sub(f as u32)); + put64(q, f + 0x84, wv + 0x8f8); + put32(q, ta::END, work::op::END); +} + +/// Encodes the FS work image and microsequence of a render. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_fs( + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + usc: u64, + n: u64, + tfs: u32, + geo: &Geometry, + w: &mut [u8; fs::WORK_SIZE], + q: &mut [u8; fs::SEQ_SIZE], +) { + let (wv, uv, qv, h) = (p.fs_work, p.fs_seq, r.qinfo[1], r.hwdata); + let (heap, su) = (p.heap_gva, p.scene_user_gva); + let ts = ts_va[2] != 0 || ts_va[3] != 0; + let (d, s) = (&u.depth, &u.stencil); + let val: [u64; 79] = [ + 1, + geo.utile_config as u64, + prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi), + prog_addr(usc, &u.eot), + prog_rsrc(u, &u.bg, u.bg_rsrc_spec_hi), + prog_addr(usc, &u.bg), + u.isp_merge_upper_x as u64, + u.isp_merge_upper_y as u64, + 0, + 0, + 0, + 0, + u.ppp_multisamplectl, + geo.isp_blocks as u64, + geo.isp_blocks as u64, + geo.screen as u64, + 0xff0200, + heap, + u.isp_scissor_base, + u.isp_dbias_base, + geo.isp_control as u64, + (u.height_px as u64) << 32 | u.width_px as u64, + 0x100000, + geo.tilebuffer_control as u64, + u.isp_zls_pixels as u64, + u.isp_bgobjdepth as u64, + u.isp_bgobjvals as u64, + u.isp_oclqry_base & !15, + u.zls_ctrl, + 0x04040404, + 0, + d.base, + d.base, + s.base, + s.base, + 0, + 0, + 0, + 0, + d.stride as u64, + d.stride as u64, + s.stride as u64, + s.stride as u64, + d.comp_base, + d.comp_stride as u64, + d.comp_base, + d.comp_stride as u64, + s.comp_base, + s.comp_stride as u64, + s.comp_base, + s.comp_stride as u64, + p.tilemap_gva, + geo.layer_metadata, + (4 * geo.region_stride as u64) << 24, + geo.tile_mode as u64, + 0, + 0, + 0, + 0x8860, + p.aux_gva, + p.aux_gva, + 0x1c, + 0x1c, + 0, + geo.native_tiles, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 8, + 0, + compact(su + 0x40) & !15, + 0x6000400020, + 0x200000001, + ]; + let pbg_r = prog_rsrc(u, &u.partial_bg, u.bg_partial_rsrc_spec_hi); + let pbg_a = prog_addr(usc, &u.partial_bg); + let peot_a = prog_addr(usc, &u.partial_eot); + let pp = fs::PARAMS; + + w.fill(0); + q.fill(0); + + // FS work image. + put32(w, 0x0, work::work_type::FS); + put64(w, 0x4, 0); + put32(w, 0xc, ctx); + put64(w, 0x14, uv); + put32(w, 0x1c, fs::SEQ_SIZE as u32); + put64(w, 0x20, r.notifier); + put64(w, 0x28, r.pb_mgr); + put64(w, 0x30, p.scene); + put64(w, 0x38, r.legacy_empty); + put64(w, 0x40, p.tilemap_gva); + put64(w, 0x48, 0x88); + put32(w, 0x50, 1); + put16(w, 0x54, (geo.y_blocks >> 18) as u16); + put16(w, 0x56, (geo.x_blocks >> 18) as u16); + put32(w, 0x68, u.isp_merge_upper_x); + put32(w, 0x6c, u.isp_merge_upper_y); + put64(w, 0x78, geo.tiles as u64); + regs(&mut w[fs::REGS..], &fs::SEL, &val); + put64(w, 0x780, p.fs_work_gva + fs::REGS as u64); + put16(w, 0x788, 79); + put16(w, 0x78a, (79 * REG_RECORD) as u16); + // Parameters / firmware mirrors at +0x790. + put64(w, pp + 0x0, u.isp_dbias_base); + put64(w, pp + 0x10, u.isp_scissor_base); + put64(w, pp + 0x20, u.isp_oclqry_base); + put64(w, pp + 0x168, pbg_r); + put64(w, pp + 0x170, pbg_a); + put64(w, pp + 0x198, pbg_r); + put64(w, pp + 0x1a0, pbg_a); + put64(w, pp + 0x1a8, u.zls_ctrl); + put32(w, pp + 0x1b0, 0x04040404); + put64(w, pp + 0x1b8, d.base); + put64(w, pp + 0x1c0, d.stride as u64); + put64(w, pp + 0x1c8, d.comp_stride as u64); + put64(w, pp + 0x1d0, d.base); + put64(w, pp + 0x1d8, d.base); + put64(w, pp + 0x1e0, d.comp_base); + put64(w, pp + 0x1e8, s.base); + put64(w, pp + 0x1f0, s.stride as u64); + put64(w, pp + 0x1f8, s.comp_stride as u64); + put64(w, pp + 0x200, s.base); + put64(w, pp + 0x208, s.base); + put64(w, pp + 0x210, s.comp_base); + put32(w, pp + 0x228, geo.tilebuffer_control); + put32(w, pp + 0x230, geo.isp_control); + put32(w, pp + 0x238, u.width_px as u32); + put32(w, pp + 0x23c, u.height_px as u32); + put32(w, pp + 0x240, 0x100000); + put32(w, pp + 0x248, geo.tile_mode); + put32(w, pp + 0x264, u.partial_eot.rsrc_spec); + put64(w, pp + 0x26c, peot_a); + put32(w, pp + 0x284, u.partial_eot.rsrc_spec); + put64(w, pp + 0x28c, peot_a); + put32(w, pp + 0x298, u.isp_bgobjdepth); + put32(w, pp + 0x29c, u.isp_bgobjvals); + put32(w, pp + 0x2a0, u.sample_size_B as u32); + put64(w, pp + 0x2c0, u.isp_zls_pixels as u64); + put32(w, 0xb88, 0x67); + put32(w, 0xb90, 0xffffffff); + put32( + w, + 0xb94, + (u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES != 0) as u32, + ); + put32(w, 0xb98, 1); + put64(w, 0xbac, r.user_stamp[1]); + put64(w, 0xbb4, r.fw_stamp[1]); + put32(w, 0xbbc, tfs); + put32(w, 0xbc0, 1); + put32(w, 0xbc8, 1); + put32(w, 0xbcc, hw::engine::FS_UUID); + put32(w, 0xbe8, 1); + work_tail( + &mut w[fs::TAIL..], + p.its + 0x10, + p.its + 0x18, + ts_va[2], + ts_va[3], + r.uma_mgr[1], + p.fs_scratch_gva, + ); + + // FS microsequence. + put32(q, 0x0, work::op::FS_START); + put64(q, 0x14, wv + 0x80); + put64(q, 0x1c, p.scene); + put64(q, 0x24, h + fs::HWDATA); + put64(q, 0x2c, wv + 0xb70); + put64(q, 0x34, wv + 0xb74); + put64(q, 0x3c, wv + 0xba0); + put64(q, 0x44, qv); + put64(q, 0x4c, wv); + put32(q, 0x54, ctx); + put32(q, 0x58, 1); + put64(q, 0x68, (n as u32).wrapping_sub(1) as u64); + put64(q, 0x74, wv + 0xa58); + put64(q, 0x7c, wv + 0xbd8); + put32(q, 0x98, hw::engine::FS_UUID); + put64(q, 0x1a4, r.uma_mgr[1]); + put64(q, 0x1bc, p.fs_scratch_gva); + put64(q, 0x1d4, r.notifier + 0xa8); + ts_record( + &mut q[fs::TS_START..], + false, + wv, + fs::TAIL as u64, + qv, + ts, + hw::engine::FS_UUID, + ); + put32(q, 0x218, 1); + ts_record( + &mut q[fs::TS_END..], + true, + wv, + fs::TAIL as u64, + qv, + ts, + hw::engine::FS_UUID, + ); + let f = fs::FINALIZE; + put32(q, f, work::op::FS_FINALIZE); + put32(q, f + 0x4, hw::engine::FS_UUID); + put64(q, f + 0xc, r.fw_stamp[1]); + put32(q, f + 0x14, tfs); + put64(q, f + 0x1c, p.scene); + put64(q, f + 0x24, r.pb_mgr); + put64(q, f + 0x2c, 1); + put64(q, f + 0x34, h + fs::HWDATA); + put64(q, f + 0x3c, wv + 0xba0); + put64(q, f + 0x44, wv + 0xb70); + put64(q, f + 0x4c, qv); + put64(q, f + 0x54, wv); + put64(q, f + 0x5c, ctx as u64); + put64(q, f + 0x64, wv + 0xa58); + put64(q, f + 0x9c, uv + 0x1a4); + put32(q, f + 0xa4, 0u32.wrapping_sub(f as u32)); + put32(q, f + 0xa8, 1); + put64(q, f + 0xac, wv + 0xc40); + put32(q, fs::END, work::op::END); +} + +/// The pass slot's scene record for draw ordinal `n`. +pub(crate) fn scene(r: &RenderRefs, p: &PassRefs, n: u64) -> [u8; scene::SIZE] { + let mut x = [0u8; scene::SIZE]; + let list = r.scene_list + 4 * (n % scene::LIST_SLOTS); + + put64(&mut x, 0x0, list); + put64(&mut x, 0x8, list); + put64(&mut x, 0x28, compact(p.scene_user_gva + 0x40)); + put32(&mut x, 0x30, compact(p.scene_user_gva + 0x900) as u32); + put64(&mut x, 0x40, r.mgr_misc); + x +} + +/// The InitBM record that (re)initializes the PB before a render. +pub(crate) fn initbm(ctx: u32, pb_init_blocks: u32, pb_mgr: u64, tta: u32) -> [u8; initbm::SIZE] { + let mut x = [0u8; initbm::SIZE]; + + put32(&mut x, 0x0, work::op::INIT_BM); + put32(&mut x, initbm::CTX, ctx); + put32(&mut x, initbm::BLOCKS, pb_init_blocks); + put64(&mut x, initbm::PB_MANAGER, pb_mgr); + put32(&mut x, initbm::STAMP, tta); + x +} diff --git a/drivers/gpu/drm/asahi/g15/engine.rs b/drivers/gpu/drm/asahi/g15/engine.rs new file mode 100644 index 00000000000000..e5c18a15e0c3b3 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/engine.rs @@ -0,0 +1,1460 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The prefix/horizon/flight engine. +//! +//! One device-global compute queue and one TA+FS queue pair serve every logical queue and VM. +//! Jobs (one per SUBMIT) wait in `pending`; pick order: priority, then the least recently +//! served queue, then FIFO. A *prefix* is a run of consecutive commands of one job (up to 16 +//! computes and [`super::hw::tuning::PREFIX_RENDERS`] renders) published together: images, +//! then thresholds/counters once per prefix, then one queue WRITE per queue, then channel +//! records, then doorbells (compute, FS, TA). A compute-only job that ends its prefix pulls +//! further ready compute-only jobs of the same queue and VM into a *horizon* (up to 16, posted +//! ahead at the observed depth). At most [`super::hw::sizes::FLIGHTS`] prefixes are in flight, +//! the second only of the same VM, posted behind the first's unconsumed records +//! (submit-ahead). Ordering is a total order, which satisfies the header barriers and +//! EXACT_PRIOR ordinals validated at submission. Priming: after a recovered abort and for the +//! first render prefix after boot, an exclusive one-render prefix rebuilds the render +//! allocators and blocks publication behind it until it retires. +//! +//! Barrier types per edge (type 0 = firmware stamp only, 1 = also the predecessor job hold): +//! FS -> own TA 0; TA -> previous FS 0 only inside a prefix after a render with no +//! InitBM/resync, else 1; compute -> TA 1 on class 2; FS -> compute 1 (`CROSS_ENGINE_HOLD` +//! bit 0); compute -> compute 1 on class 2; early tiling (off) TA -> TA and FS -> FS 1. +//! +//! Completions: rather than signalling a fence under the device lock, the engine pushes the job +//! to [`Completions`] and the caller signals after dropping the lock; [`Job::complete`] runs +//! once per job, so a job may be pushed again when its last engine reference is released. + +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +use kernel::{prelude::*, sync::Arc, uapi}; + +use super::channel::Channel; +use super::command::{Command, ComputeCommand, RenderCommand}; +use super::encode::{self, ClusterLayout, ComputeRefs, Geometry, RenderRefs}; +use super::fw::channels::SubmitRecord; +use super::fw::graph::qstate; +use super::fw::work::{self, barrier::RENDER_WAIT_UUID, BarrierType}; +use super::hw::{engine as ids, sizes, tuning}; +use super::job::{Completions, Job}; +use super::slots::Claims; +use super::{params, Firmware, Shared}; + +/// `wmb()`: `dsb st` (a full fence on other architectures). +#[inline(always)] +pub(crate) fn wmb() { + #[cfg(target_arch = "aarch64")] + // SAFETY: A barrier instruction with no other effects. + unsafe { + core::arch::asm!("dsb st", options(nostack, preserves_flags)) + }; + #[cfg(not(target_arch = "aarch64"))] + core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst); +} + +/// `rmb()`: `dsb ld` (a full fence on other architectures). +#[inline(always)] +pub(crate) fn rmb() { + #[cfg(target_arch = "aarch64")] + // SAFETY: A barrier instruction with no other effects. + unsafe { + core::arch::asm!("dsb ld", options(nostack, preserves_flags)) + }; + #[cfg(not(target_arch = "aarch64"))] + core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst); +} + +/// `ktime_get_ns()`. +pub(crate) fn now_ns() -> u64 { + ::ktime_get() as u64 +} + +/// The engine's bookkeeping of one job, embedded in [`Job`]. Only the engine changes it, always +/// under the device lock (the atomics only make the shared `Arc` mutable). +pub(crate) struct Progress { + /// Commands still to run: the job's command count, cut to `sent` when a failure drops its + /// unpublished commands. + pub(crate) count: AtomicU32, + /// First command not yet published. + pub(crate) sent: AtomicU32, + /// First command not yet retired. + pub(crate) next: AtomicU32, + /// Waiting in `Engine::pending`. + pub(crate) pending: AtomicBool, + /// The fence was signalled: [`Job::complete`] runs once. + pub(crate) signaled: AtomicBool, +} + +impl Progress { + pub(crate) fn new(commands: usize) -> Self { + Self { + count: AtomicU32::new(commands as u32), + sent: AtomicU32::new(0), + next: AtomicU32::new(0), + pending: AtomicBool::new(false), + signaled: AtomicBool::new(false), + } + } + + pub(crate) fn count(&self) -> u32 { + self.count.load(Ordering::Relaxed) + } + + pub(crate) fn sent(&self) -> u32 { + self.sent.load(Ordering::Relaxed) + } + + pub(crate) fn next(&self) -> u32 { + self.next.load(Ordering::Relaxed) + } + + pub(crate) fn is_pending(&self) -> bool { + self.pending.load(Ordering::Relaxed) + } + + fn set_sent(&self, v: u32) { + self.sent.store(v, Ordering::Relaxed) + } + + fn set_pending(&self, v: bool) { + self.pending.store(v, Ordering::Relaxed) + } +} + +/// Engine of the previous member. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub(crate) enum Prev { + #[default] + None, + Compute, + Render, +} + +/// A published prefix: its job and commands, its own receipts (final +/// targets, exclusive ring ends and the ring positions before it, channel producers after its +/// records) and the storage it holds until its own retirement. +pub(crate) struct Flight { + /// The job whose commands the prefix holds, and horizon jobs folded into it (in order). + pub(crate) job: Arc, + pub(crate) group: KVec>, + /// Index of the first command of the job in this prefix, and the number of commands. + pub(crate) first: usize, + pub(crate) count: usize, + pub(crate) computes: u32, + pub(crate) renders: u32, + /// Compute: final FW stamp, ring end (exclusive) and ring position before the prefix. + pub(crate) target: u32, + pub(crate) head: u32, + pub(crate) c_start: u32, + /// Render: final TA/FS stamps, ring ends and ring positions before the prefix. + pub(crate) ta_target: u32, + pub(crate) fs_target: u32, + pub(crate) ta_head: u32, + pub(crate) fs_head: u32, + pub(crate) ta_start: u32, + pub(crate) fs_start: u32, + /// Channel producers (TA, FS, compute) after the prefix's records. + pub(crate) rec: [u32; 3], + /// Compute member j's FW stamp target, and the FS target it waits on directly (0: none): + /// its predecessors in the prefix (for the compute-hang check). + pub(crate) cstamp: [u32; sizes::COMPUTE_SLOTS], + pub(crate) cwait: [u32; sizes::COMPUTE_SLOTS], + /// Compute slots, pass slots and clustering buffers it holds. + pub(crate) claims: Claims, + /// The prefix rebuilds the render allocators (priming); nothing is published behind it. + pub(crate) rebuild: bool, + /// A kill or recovery ended this prefix's VM: later prefixes of it fail with EIO. + pub(crate) doomed: bool, + /// Publication time, ns. + pub(crate) published_ns: u64, +} + +impl Flight { + fn new(job: Arc) -> Self { + Self { + job, + group: KVec::new(), + first: 0, + count: 0, + computes: 0, + renders: 0, + target: 0, + head: 0, + c_start: 0, + ta_target: 0, + fs_target: 0, + ta_head: 0, + fs_head: 0, + ta_start: 0, + fs_start: 0, + rec: [0; 3], + cstamp: [0; sizes::COMPUTE_SLOTS], + cwait: [0; sizes::COMPUTE_SLOTS], + claims: Claims::new(), + rebuild: false, + doomed: false, + published_ns: 0, + } + } +} + +/// A prefix under preparation: members in API order, each in a claimed +/// compute or pass slot. `prev` is the engine of the previous member, of this prefix or else +/// the last member of the newest published one; `last_ct`/`last_fs` its compute/FS target. +#[derive(Default)] +struct Prefix { + computes: u32, + renders: u32, + prev: Prev, + /// This prefix (re)initializes the PB with InitBM. + initbm: bool, + c_head: u32, + ta_head: u32, + fs_head: u32, + /// Last compute ordinal / last draw ordinal. + n: u64, + draw: u64, + last_ct: u32, + last_fs: u32, + /// The last compute / render member has API timestamps. + ct_ts: bool, + fs_ts: bool, +} + +/// Engine statistics, printed by `asahi-g15/stats`. +#[derive(Default)] +pub(crate) struct Stats { + pub(crate) pub_ns: u64, + pub(crate) idle_from_ns: u64, + pub(crate) starve_from_ns: u64, + pub(crate) prep_from_ns: u64, + /// Idle with nothing ready; prefix preparation. + pub(crate) starved_ns: u64, + pub(crate) prep_ns: u64, + /// Internal stage durations of retired prefixes (24 MHz ticks). + pub(crate) ta_ticks: u64, + pub(crate) fs_ticks: u64, + pub(crate) cdm_ticks: u64, + pub(crate) span_ticks: u64, + /// [0] compute, [1] render, [2] mixed. + pub(crate) count: [u64; 3], + pub(crate) prefixes: [u64; 3], + pub(crate) busy_ns: [u64; 3], + pub(crate) max_ns: [u64; 3], + pub(crate) first_ns: [u64; 3], + pub(crate) last_ns: [u64; 3], + pub(crate) gap_ns: u64, + pub(crate) gaps: u64, + pub(crate) yields: u64, + /// Prefixes published while another ran. + pub(crate) overlaps: u64, + pub(crate) jobs: u64, + pub(crate) job_cmds: u64, + pub(crate) job_max: u64, + pub(crate) early: u64, + /// Type-0 FS->compute / compute->TA waits. + pub(crate) fs2c0: u64, + pub(crate) c2ta0: u64, + pub(crate) clustered: u64, + /// Jobs published behind another in a compute horizon. + pub(crate) grouped: u64, + /// Compute-only prefixes by jobs; why grouping stopped (no further ready job, the cap, + /// compute slots, a job of the queue that does not qualify); behind a running prefix; of + /// those behind its unconsumed record. + pub(crate) hz: [u64; sizes::HORIZON_JOBS as usize], + pub(crate) hz_stop: [u64; 4], + pub(crate) hz_behind: u64, + pub(crate) hz_ahead: u64, + /// Why ready jobs stayed unpublished: both flights published, a channel record unconsumed, + /// no free slot. + pub(crate) hold: [u64; 3], +} + +/// Host-side phase timers of publication and polling, on with `debug_flags` bit 49 +/// (`Debug1`); printed as the `prof:` line of `asahi-g15/stats`. A measurement aid: nothing is +/// timed while the flag is off. +#[derive(Default)] +pub(crate) struct Prof { + /// Published prefixes timed. + pub(crate) prefixes: u64, + /// Member selection, channel checks, allocator and ring-head setup. + pub(crate) select_ns: u64, + /// Encoders (images into the scratch buffers). + pub(crate) encode_ns: u64, + /// Slot, pass and clustering-buffer claims, with synchronous scrubs and flush waits. + pub(crate) claim_ns: u64, + /// Object writes: images, scene, barriers, InitBM, ring entries. + pub(crate) write_ns: u64, + /// Thresholds, queue WRITEs, channel records and doorbells. + pub(crate) post_ns: u64, + /// Poll passes, and the time of their drain, retirement and whole pass. + pub(crate) polls: u64, + pub(crate) drain_ns: u64, + pub(crate) retire_ns: u64, + pub(crate) poll_ns: u64, +} + +/// A phase timer: reads the clock only while profiling is on. +pub(crate) struct Lap(Option); + +impl Lap { + pub(crate) fn start() -> Self { + Lap(crate::debug::debug_enabled(crate::debug::DebugFlags::Debug1).then(now_ns)) + } + + /// Adds the time since the start or the last lap to `acc`. + pub(crate) fn lap(&mut self, acc: &mut u64) { + if let Some(t) = self.0 { + let now = now_ns(); + *acc += now.wrapping_sub(t); + self.0 = Some(now); + } + } + + pub(crate) fn on(&self) -> bool { + self.0.is_some() + } +} + +/// Encoder output buffers, allocated once rather than per publication. +struct Scratch { + cw: KVec, + cq: KVec, + ta: KVec, + tas: KVec, + fs: KVec, + fss: KVec, +} + +impl Scratch { + fn new() -> Result { + let z = |n| KVec::from_elem(0u8, n, GFP_KERNEL); + Ok(Self { + cw: z(work::compute::WORK_SIZE)?, + cq: z(work::compute::SEQ_SIZE)?, + ta: z(work::ta::WORK_SIZE)?, + tas: z(work::ta::SEQ_SIZE)?, + fs: z(work::fs::WORK_SIZE)?, + fss: z(work::fs::SEQ_SIZE)?, + }) + } +} + +/// `&mut KVec` as a fixed-size image buffer. +fn image(v: &mut KVec) -> Result<&mut [u8; N]> { + <&mut [u8; N]>::try_from(&mut v[..]).map_err(|_| EINVAL) +} + +/// Engine state. +pub(crate) struct Engine { + /// Runnable jobs of every queue, in arrival order. + pub(crate) pending: KVec>, + /// Published prefixes, oldest first. + pub(crate) flights: KVec, + /// Jobs whose storage a failed prefix may still reference, retained until reboot. + pub(crate) retained: KVec>, + /// Publication frozen by a kill request (recovery may use this or `Recovery::armed`; both + /// freeze publication). + pub(crate) frozen: bool, + /// Service turn counter for the least-recently-served pick. + pub(crate) turn: u64, + /// The device's shared state, for the transport-error latch; set by the first poll or + /// submission. + pub(crate) shared: Option>, + /// Host compute ordinal and draw ordinal of the last publication. + pub(crate) ordinal: u64, + pub(crate) draw: u64, + /// Newest published receipts, the tail. + pub(crate) target: u32, + pub(crate) head: u32, + pub(crate) ta_target: u32, + pub(crate) fs_target: u32, + pub(crate) ta_head: u32, + pub(crate) fs_head: u32, + /// Event counts at the tail's publication. + pub(crate) events: u32, + pub(crate) stage_seen: u32, + /// Last member of the newest prefix. + pub(crate) tail_prev: Prev, + pub(crate) tail_ct: u32, + pub(crate) tail_fs: u32, + /// The compute queue / render queues were registered by a first record (`new_queue`). + pub(crate) queue_registered: bool, + pub(crate) render_registered: bool, + /// The rebuild (priming) prefix is published and not yet retired. + pub(crate) rebuild_live: bool, + /// A ready prefix waits only for a record's consumption: repoll sooner. + pub(crate) chan_wait: bool, + /// Progress tracking of the oldest prefix. + pub(crate) progress_flight: u64, + pub(crate) progress: [u32; 3], + pub(crate) stats: Stats, + /// Phase timers (debug_flags bit 49). + pub(crate) prof: Prof, + /// The `asahi-g15/stats` file. + pub(crate) debugfs: Option>>>>, + /// The `asahi-g15/pstate` file. + pub(crate) debugfs_pstate: Option>>>>, + scratch: Option>, +} + +impl Engine { + pub(crate) fn new() -> Self { + Self { + pending: KVec::new(), + flights: KVec::new(), + retained: KVec::new(), + frozen: false, + turn: 0, + shared: None, + ordinal: 0, + draw: 0, + target: 0, + head: 0, + ta_target: 0, + fs_target: 0, + ta_head: 0, + fs_head: 0, + events: 0, + stage_seen: 0, + tail_prev: Prev::None, + tail_ct: 0, + tail_fs: 0, + queue_registered: false, + render_registered: false, + rebuild_live: false, + chan_wait: false, + progress_flight: 0, + progress: [0; 3], + stats: Stats::default(), + prof: Prof::default(), + debugfs: None, + debugfs_pstate: None, + scratch: None, + } + } + + /// The oldest published prefix. + pub(crate) fn oldest(&self) -> Option<&Flight> { + self.flights.first() + } + + /// Jobs of the queue in published prefixes. + fn queue_published(&self, job: &Job) -> u32 { + self.flights + .iter() + .filter(|f| Arc::ptr_eq(&f.job.queue, &job.queue)) + .map(|f| 1 + f.group.len() as u32) + .sum() + } + + /// Index in `pending` of the next ready job: highest queue priority, then the queue served + /// least recently, then submission order. `QueueState::priority` is + /// `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it, so a smaller value + /// outranks. + fn pick(&self) -> Option { + let mut best: Option = None; + for (i, job) in self.pending.iter().enumerate() { + let better = match best { + None => true, + Some(b) => { + let (q, bq) = (&job.queue, &self.pending[b].queue); + let (t, bt) = ( + q.turn.load(Ordering::Relaxed), + bq.turn.load(Ordering::Relaxed), + ); + q.priority < bq.priority || (q.priority == bq.priority && t < bt) + } + }; + if better { + best = Some(i); + } + } + best + } + + /// Removes `job` from `pending`. + fn unpend(&mut self, job: &Arc) { + job.progress.set_pending(false); + self.pending.retain(|j| !Arc::ptr_eq(j, job)); + } +} + +/// The job's command `k`. +fn command(job: &Job, k: u32) -> Option<&Command> { + job.commands.get(k as usize) +} + +fn is_render(job: &Job, k: u32) -> bool { + matches!(command(job, k), Some(Command::Render(_))) +} + +/// Whole compute-only job. +fn compute_only(job: &Job) -> bool { + (0..job.progress.count()).all(|k| !is_render(job, k)) +} + +/// Pushes a job's completion; [`Job::complete`] only acts the first time. +pub(crate) fn complete(done: &mut Completions, job: &Arc, result: Result) { + if done.push((job.clone(), result), GFP_KERNEL).is_err() { + // Signalling must not be lost: complete in place, under the caller's device lock. + job.complete(result); + } +} + +impl Firmware { + /// Accepts a job from the scheduler; it is published by [`Self::publish`]. Records how many + /// jobs the queue owns at this arrival for the compute horizon. + pub(crate) fn enqueue(&mut self, job: Arc) -> Result { + if self.recovery.failed().is_some() { + return Err(EIO); + } + if job.progress.count() == 0 || job.commands.is_empty() { + return Err(EINVAL); + } + if self.engine.flights.capacity() < sizes::FLIGHTS { + self.engine.flights.reserve(sizes::FLIGHTS, GFP_KERNEL)?; + } + self.engine.pending.push(job.clone(), GFP_KERNEL)?; + job.progress.set_pending(true); + let q = &job.queue; + let owned = self.engine.queue_published(&job) + + self + .engine + .pending + .iter() + .filter(|j| Arc::ptr_eq(&j.queue, q)) + .count() as u32; + let i = q.owned_index.fetch_add(1, Ordering::Relaxed) as usize % q.owned.len(); + q.owned[i].store(owned.min(255), Ordering::Relaxed); + Ok(()) + } + + /// Publishes further prefixes: with nothing published any ready job; behind published + /// prefixes only the next job of the same VM, up to `max_inflight`, and not while recovery + /// state is pending: neither the prefix that rebuilds the render allocators after an abort + /// is published behind another one, nor anything behind it until it has retired. Jobs + /// whose first publication failed before any visible record complete with an error. + /// Returns Err only when this call latched the engine failed (a publication error after a + /// queue WRITE advanced, or a partly sent job): the caller latches the fail-stop. + pub(crate) fn publish(&mut self, done: &mut Completions) -> Result { + let max_inflight = tuning::MAX_INFLIGHT.clamp(1, sizes::FLIGHTS as u32) as usize; + let mut result = Ok(()); + + self.engine.chan_wait = false; + // Nothing is published while a hang request is armed. + while self.recovery.failed().is_none() + && !self.engine.frozen + && self.recovery.armed.is_none() + && !self.engine.pending.is_empty() + { + let Some(index) = self.engine.pick() else { + break; + }; + let job = self.engine.pending[index].clone(); + if let Some(tail) = self.engine.flights.last() { + if self.engine.flights.len() >= max_inflight + || !Arc::ptr_eq(&job.vm, &tail.job.vm) + || self.recovery.reinit + || self.recovery.fs_resync + || self.engine.rebuild_live + { + self.engine.stats.hold[0] += (self.engine.flights.len() >= max_inflight) as u64; + break; + } + if !Arc::ptr_eq(&tail.job, &job) && tail.job.progress.is_pending() { + self.engine.stats.yields += 1; // another queue's turn at a prefix boundary + } + } + self.engine.turn += 1; + job.queue.turn.store(self.engine.turn, Ordering::Relaxed); + match self.publish_prefix(&job, done) { + Ok(()) => { + if job.progress.sent() == job.progress.count() { + self.engine.unpend(&job); // fully published + } + continue; + } + Err(e) if e == EAGAIN => { + let i = if self.engine.chan_wait { 1 } else { 2 }; + self.engine.stats.hold[i] += 1; + break; // storage or channel still held: on a later retirement + } + Err(e) => { + self.engine.unpend(&job); + if e == EIO || job.progress.sent() != 0 { + // Uncertain, or earlier commands ran: retain, stop the engine. No + // recovery: every VM is lost, also those with no failed job. + dev_err!( + self.graph.dev.as_ref(), + "G15: publication of ctx {} failed after a queue WRITE ({:?})\n", + job.vm.slot, + e + ); + complete(done, &job, Err(EIO)); + self.retain(&job); + self.fail_stop(EIO, done); + result = Err(EIO); + break; + } + complete(done, &job, Err(e)); + } + } + } + result + } + + /// Whether some of `job`'s commands were published: such a job is retained after a + /// fail-stop. + pub(crate) fn job_partly_published(&self, job: &Job) -> bool { + job.progress.sent() != 0 + } + + /// Ready jobs the compute horizon of `job` could take now, besides `job` itself: the + /// grouping rules of [`Self::publish_prefix`], at most `max - 1`. + fn horizon_ready(&self, job: &Arc, mut computes: u32, free_c: u32, max: u32) -> u32 { + let mut n = 0; + for j2 in self.engine.pending.iter() { + if 1 + n >= max { + break; + } + if Arc::ptr_eq(j2, job) || !Arc::ptr_eq(&j2.queue, &job.queue) { + continue; + } + let count = j2.progress.count(); + if !compute_only(j2) + || !Arc::ptr_eq(&j2.vm, &job.vm) + || j2.progress.sent() != 0 + || count == 0 + || computes + count > free_c + { + break; + } + computes += count; + n += 1; + } + n + } + + /// The allocator and graph addresses the render encoders name. + fn render_refs(&self) -> RenderRefs { + let r = &self.graph.render; + let a = self.pools.allocator_refs(); + RenderRefs { + hwdata: self.cfg.layout.hwdata_va, + notifier: r.notifier.va, + legacy_empty: r.legacy_empty.va, + qinfo: [r.qinfo[0].va, r.qinfo[1].va], + user_stamp: [r.user_stamp[0].va, r.user_stamp[1].va], + fw_stamp: [r.fw_stamp[0].va, r.fw_stamp[1].va], + uma_mgr: a.uma_mgr, + pb_mgr: a.pb_mgr, + scene_list: a.scene_list, + mgr_misc: a.mgr_misc, + pb_init_blocks: a.init_blocks, + } + } + + /// Publishes the next prefix of `job`, from its first unpublished command. Members: + /// consecutive commands of one engine, or with `MIXED_PREFIX` of both engines in API order, + /// each in a free compute or pass slot. All images and ring entries precede one WRITE per + /// participating queue and the kicks (compute, FS, TA); host thresholds and counters name + /// the final ordinals. + /// + /// With prefixes already published (same VM only), the new one is appended behind them on + /// the running queues: it takes only slots they do not hold, its first member waits on + /// their last member like any member on its predecessor, and its SubmitQueue records + /// extend the queues' horizons (`new_queue` 0). Returns EAGAIN when it cannot be appended + /// yet (no free slot, or a channel record still unconsumed); EIO once a queue WRITE + /// advanced; any other error means nothing was published. + fn publish_prefix(&mut self, job: &Arc, done: &mut Completions) -> Result { + let mut f = Flight::new(job.clone()); + let result = self.publish_prefix_into(job, &mut f); + match result { + Err(e) if e != EIO => { + // Never published: its storage is free again, and horizon jobs taken into it + // fail with it. + self.slots.release(&mut f.claims); + for j2 in f.group.iter() { + complete(done, j2, Err(e)); + } + } + _ => {} + } + result + } + + fn publish_prefix_into(&mut self, job: &Arc, f: &mut Flight) -> Result { + // The PB backing is mapped into the job's VM before anything of the prefix is changed. + // Nothing is published when that fails, so the error must not be EIO (which reports a + // queue WRITE that advanced). + self.map_pb(&job.vm) + .map_err(|e| if e == EIO { EFAULT } else { e })?; + let overlap = !self.engine.flights.is_empty(); + let mut mixed = tuning::MIXED_PREFIX; + let mut pf = Prefix { + n: self.engine.ordinal, + draw: self.engine.draw, + ..Default::default() + }; + let i = job.progress.sent(); + let count = job.progress.count(); + let render0 = is_render(job, i); + let (mut computes, mut renders, mut end) = (0u32, 0u32, i); + let mut last_render = None; + let mut hz_stop: Option = None; + let mut rebuild = false; + let prefix_renders = tuning::PREFIX_RENDERS.clamp(1, sizes::RENDER_SLOTS as u32); + + self.engine.stats.prep_from_ns = now_ns(); + let mut lap = Lap::start(); + let free_c = self.slots.free_compute(); + // After an abort the prefix that rebuilds the render allocators holds renders only (see + // `publish`): a compute published with it, or behind it before it retired, crashed the + // 2419 firmware in its progress path (F+0x35568, FAR 0x58) after a recovered hang whose + // prefix had a compute waiting on the hung FS. + if self.recovery.reinit || self.recovery.fs_resync { + mixed = false; + } + while end < count { + let cmd = command(job, end).ok_or(EINVAL)?; + let render = matches!(cmd, Command::Render(_)); + if render != render0 && !mixed { + break; + } + match cmd { + Command::Compute(_) => { + if computes == free_c { + break; + } + computes += 1; + } + Command::Render(r) => { + if renders >= prefix_renders { + break; + } + // The prefix that primes freshly initialized render allocators (the first + // after boot, or after an abort's re-init) holds one render: their + // submitted cell is 1 and their completed count 0, so the first completed + // TA (FS) catches its allocator up and clears its registration. A second + // render of the prefix then holds a position of that allocator with no + // registered manager until it completes, and the firmware's + // progress/preemption path dereferences the missing manager: RTKit crash + // at F+0x35568, FAR 0x58. + if renders != 0 && (self.recovery.reinit || self.engine.draw == 0) { + break; + } + let geo = Geometry::new(&r.cmd, 0); + let Some(k) = self.slots.pick_pass(&geo, f.claims.pass_mask) else { + break; + }; + f.claims.pass_mask |= 1 << k; + f.claims.pass[renders as usize] = k as u32; + renders += 1; + } + } + end += 1; + } + if end == i { + // Idle: every slot is free. + return Err(if overlap { EAGAIN } else { E2BIG }); + } + // The picked pass slots are not claimed yet: an early return below must not release + // them. + let picked = f.claims.pass_mask; + f.claims.pass_mask = 0; + // Participating channels: every earlier record consumed, or (a prefix with renders + // behind a running one, SUBMIT_AHEAD) room behind the unconsumed ones. Behind a running + // prefix the firmware takes its record within microseconds: retry soon rather than at + // that prefix's retirement. + let mut ahead = overlap && renders != 0 && tuning::SUBMIT_AHEAD; + if overlap && renders == 0 && end == count && tuning::SUBMIT_AHEAD { + let max = tuning::COMPUTE_HORIZON.clamp(1, sizes::HORIZON_JOBS); + let ready = 1 + self.horizon_ready(job, computes, free_c, max); + let depth = job + .queue + .owned + .iter() + .map(|o| o.load(Ordering::Relaxed)) + .max() + .unwrap_or(0); + ahead = ready >= max || ready + self.engine.queue_published(job) >= depth; + } + for ch in [Channel::Ta, Channel::Fs, Channel::Compute] { + let used = if ch == Channel::Compute { + computes != 0 + } else { + renders != 0 + }; + if !used { + continue; + } + let consumer = self.channels.read(ch)?; + let producer = self.channels.producer(ch); + let busy = if ahead { + producer.wrapping_sub(consumer) % 256 >= sizes::AHEAD_RECORDS + } else { + consumer != producer + }; + if busy || self.channels.write_cell(ch)? != producer { + self.engine.chan_wait = overlap; + return Err(if overlap { EAGAIN } else { EBUSY }); + } + } + f.claims.pass_mask = picked; + self.slots.pass_busy |= f.claims.pass_mask; + if renders != 0 { + let cursor = match f.claims.pass[renders as usize - 1] { + 0 => self.slots.pass_cursor, + k => k, + }; + self.slots.pass_cursor = cursor % (sizes::RENDER_SLOTS as u32 - 1).max(1); + // After a recovered render abort the allocator state is not trusted. The priming + // prefix (also the first after boot) retires before anything is published behind + // it. + rebuild = self.recovery.reinit || self.engine.draw == 0; + if self.recovery.reinit { + self.init_render_pools(true)?; + dev_info!( + self.graph.dev.as_ref(), + "G15: render allocators re-initialized; InitBM at draw {}\n", + self.engine.draw + 1 + ); + } + } + if self.engine.scratch.is_none() { + self.engine.scratch = Some(KBox::new(Scratch::new()?, GFP_KERNEL)?); + } + if overlap { + pf.prev = self.engine.tail_prev; + pf.last_ct = self.engine.tail_ct; + pf.last_fs = self.engine.tail_fs; + } + let cap = sizes::QUEUE_CAP; + pf.c_head = self.graph.compute.qstate.r32(qstate::WRITE)? % cap; + pf.ta_head = self.graph.render.qstate[0].r32(qstate::WRITE)? % cap; + pf.fs_head = self.graph.render.qstate[1].r32(qstate::WRITE)? % cap; + f.c_start = pf.c_head; + f.ta_start = pf.ta_head; + f.fs_start = pf.fs_head; + for k in i..end { + if is_render(job, k) { + last_render = Some(k); + } + } + let refs = self.render_refs(); + lap.lap(&mut self.engine.prof.select_ns); + for k in i..end { + match command(job, k).ok_or(EINVAL)? { + Command::Render(r) => self.prefix_render(job, r, &refs, &mut pf, f)?, + Command::Compute(c) => { + let later_render = last_render.is_some_and(|l| k < l); + self.prefix_compute(job, c, &mut pf, f, later_render)? + } + } + } + // Compute horizon: whole compute-only jobs of the same queue and VM that already wait + // ready (their inputs resolved before the scheduler ran them), in queue order, into + // slots still free. A job of that queue that does not qualify ends the group: no later + // job overtakes it. + if renders == 0 && end == count { + let max = tuning::COMPUTE_HORIZON.clamp(1, sizes::HORIZON_JOBS); + let mut idx = 0; + hz_stop = Some(0); + while idx < self.engine.pending.len() { + if 1 + f.group.len() as u32 >= max { + hz_stop = Some(1); + break; + } + let j2 = self.engine.pending[idx].clone(); + if Arc::ptr_eq(&j2, job) || !Arc::ptr_eq(&j2.queue, &job.queue) { + idx += 1; + continue; + } + let n2 = j2.progress.count(); + if !compute_only(&j2) + || !Arc::ptr_eq(&j2.vm, &job.vm) + || j2.progress.sent() != 0 + || n2 == 0 + { + hz_stop = Some(3); + break; + } + if computes + n2 > free_c { + hz_stop = Some(2); + break; + } + // Without room for another group entry the horizon ends here: the base job + // is published already, and nothing of `j2` has been touched or sent, so a + // transient allocation failure must not fail the prefix (which, after a queue + // WRITE, would be taken for an uncertain post-WRITE state and stop the engine). + if f.group.reserve(1, GFP_KERNEL).is_err() { + hz_stop = Some(1); + break; + } + for k in 0..n2 { + match command(&j2, k).ok_or(EINVAL)? { + Command::Compute(c) => self.prefix_compute(&j2, c, &mut pf, f, false)?, + Command::Render(_) => return Err(EINVAL), + } + } + computes += n2; + j2.progress.set_sent(n2); + self.engine.turn += 1; + j2.queue.turn.store(self.engine.turn, Ordering::Relaxed); + j2.progress.set_pending(false); + let _ = self.engine.pending.remove(idx); + // Reserved above. + let _ = f.group.push(j2, GFP_KERNEL); + self.engine.stats.grouped += 1; + } + } + // Host thresholds/counters after the whole prefix. The notifiers' context (+0x24) is + // not ours to write: every completing work stores its own context there before the + // service reads it. + let mut lap = Lap::start(); + if computes != 0 { + self.graph.compute.threshold.w32(0, pf.n as u32)?; + self.graph.compute.counter.w32(0, pf.n as u32)?; + } + if renders != 0 { + self.graph + .render + .threshold + .w32(0, 2u32.wrapping_mul(pf.draw as u32))?; + // pb_counter = draw, then C1 once per (re)initialization. + self.publish_pb(pf.draw as u32)?; + } + wmb(); + // The queue WRITEs: from here on a failure is uncertain (EIO). + let writes = (|| -> Result { + if computes != 0 { + self.graph.compute.qstate.w32(qstate::WRITE, pf.c_head)?; + } + if renders != 0 { + self.graph.render.qstate[0].w32(qstate::WRITE, pf.ta_head)?; + self.graph.render.qstate[1].w32(qstate::WRITE, pf.fs_head)?; + } + Ok(()) + })(); + wmb(); + + f.first = i as usize; + f.count = (end - i) as usize; + f.computes = computes; + f.renders = renders; + if computes != 0 { + self.engine.ordinal = pf.n; + f.target = pf.last_ct; + self.engine.target = pf.last_ct; + f.head = pf.c_head; + self.engine.head = pf.c_head; + } + if renders != 0 { + f.ta_target = encode::stamp_seed(ids::TA_SEED, pf.draw); + self.engine.ta_target = f.ta_target; + f.fs_target = pf.last_fs; + self.engine.fs_target = pf.last_fs; + f.ta_head = pf.ta_head; + self.engine.ta_head = pf.ta_head; + f.fs_head = pf.fs_head; + self.engine.fs_head = pf.fs_head; + self.engine.draw = pf.draw; + self.recovery.fs_resync = false; + self.recovery.reinit = false; + } + self.engine.tail_prev = pf.prev; + self.engine.tail_ct = pf.last_ct; + self.engine.tail_fs = pf.last_fs; + self.engine.events = self.events.compute_events; + self.engine.stage_seen = self.events.stage_events; + self.stat_publish(f); + if overlap { + self.engine.stats.overlaps += 1; + } else { + self.renew_deadlines(); + } + job.progress.set_sent(end); + if let Some(stop) = hz_stop { + let s = &mut self.engine.stats; + s.hz[f.group.len()] += 1; + s.hz_stop[stop] += 1; + s.hz_behind += overlap as u64; + s.hz_ahead += ahead as u64; + } + if rebuild { + f.rebuild = true; + self.engine.rebuild_live = true; + } + // Compute on channel 2, then FS on channel 1, then TA on channel 0. + let mut posted = writes; + if posted.is_ok() && computes != 0 { + let rec = SubmitRecord { + qinfo: self.graph.compute.qinfo.va, + kind: 2, + head: pf.c_head as u16, + event: ids::EVENT_SLOT as u8, + new_queue: !self.engine.queue_registered as u8, + ..Default::default() + }; + posted = self.post(Channel::Compute, &rec, ahead); + if posted.is_ok() { + self.engine.queue_registered = true; + posted = self.session.ring(Channel::Compute); + } + } + if posted.is_ok() && renders != 0 { + let new_queue = !self.engine.render_registered as u8; + let fs_rec = SubmitRecord { + qinfo: self.graph.render.qinfo[1].va, + kind: 1, + head: pf.fs_head as u16, + event: 1, + new_queue, + ..Default::default() + }; + let ta_rec = SubmitRecord { + qinfo: self.graph.render.qinfo[0].va, + kind: 0, + head: pf.ta_head as u16, + event: 0, + new_queue, + ..Default::default() + }; + posted = self.post(Channel::Fs, &fs_rec, ahead); + if posted.is_ok() { + posted = self.session.ring(Channel::Fs); + } + if posted.is_ok() { + posted = self.post(Channel::Ta, &ta_rec, ahead); + } + if posted.is_ok() { + posted = self.session.ring(Channel::Ta); + } + self.engine.render_registered = true; + } + f.rec = [ + self.channels.producer(Channel::Ta), + self.channels.producer(Channel::Fs), + self.channels.producer(Channel::Compute), + ]; + if lap.on() { + lap.lap(&mut self.engine.prof.post_ns); + self.engine.prof.prefixes += 1; + } + // The flight is published: move it into the engine (capacity reserved in `enqueue`). + let mut flight = Flight::new(job.clone()); + core::mem::swap(&mut flight, f); + let _ = self.engine.flights.push(flight, GFP_KERNEL); + crate::cls_dev_dbg!( + Queue, + self.graph.dev, + "G15: prefix ctx={} computes {} (n={} head {}) renders {} (draw {} ta/fs head {}/{}) behind {}: {:?}\n", + job.vm.slot, + computes, + pf.n, + pf.c_head, + renders, + pf.draw, + pf.ta_head, + pf.fs_head, + self.engine.flights.len() - 1, + posted + ); + // A queue WRITE already advanced: any later failure is uncertain. + posted.map_err(|_| EIO) + } + + /// Posts a submit record, behind unconsumed ones with `ahead`. + fn post(&mut self, channel: Channel, record: &SubmitRecord, ahead: bool) -> Result { + if ahead { + self.channels.post_ahead(channel, record)?; + } else { + self.channels.post(channel, record)?; + } + Ok(()) + } + + /// Compute member: encode into its slot and append to the CDM ring. After a render of the + /// same prefix it first waits on that render's FS: a distinct barrier entry ahead of the + /// work. + fn prefix_compute( + &mut self, + job: &Arc, + cmd: &ComputeCommand, + pf: &mut Prefix, + f: &mut Flight, + later_render: bool, + ) -> Result { + let n = pf.n + 1; + let t = encode::stamp(n); + let ctx = job.vm.slot; + let ts = &cmd.timestamps; + let mut lap = Lap::start(); + // Nothing published yet on failure. + let index = self + .slots + .claim_compute(&mut f.claims, pf.computes)? + .ok_or(EBUSY)?; + lap.lap(&mut self.engine.prof.claim_ns); + let scrub = self.slots.scrub.clone(); + let s = &scrub.compute[index]; + let g = &self.graph.compute; + let refs = ComputeRefs { + hwdata: self.cfg.layout.hwdata_va, + notifier: g.notifier.va, + qinfo: g.qinfo.va, + user_stamp: g.user_stamp.va, + fw_stamp: g.fw_stamp.va, + manager: g.manager.va, + work: s.work.va, + work_gva: s.work.gva.unwrap_or(0), + seq: s.seq.va, + preempt_gva: s.preempt.gva.unwrap_or(0), + its: s.its.va, + tail: s.tail.va, + scratch: [ + s.scratch[0].va, + s.scratch[1].va, + s.scratch[2].va, + s.scratch[3].va, + s.scratch[4].va, + ], + }; + let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; + let (w, q) = (&mut scratch.cw, &mut scratch.cq); + encode::encode_compute( + &refs, + &self.cfg.compute, + &cmd.cmd, + &cmd.attachments, + ts, + ctx, + n, + tuning::COMPUTE_FAULT_MASK, + image(w)?, + image(q)?, + ); + lap.lap(&mut self.engine.prof.encode_ns); + // Rewrite the slot's images (its runtime storage is already scrubbed). + s.work.fill(0, 0, work::compute::WORK_SIZE)?; + s.seq.fill(0, 0, work::compute::SEQ_OBJECT)?; + s.work.write(0, &w[..])?; + s.seq.write(0, &q[..])?; + + let g = &self.graph.compute; + if pf.prev == Prev::Render { + // Type 0 when the FS is of this prefix and a later render of the prefix follows + // it: its X names a later scene, so this FS takes no PB catch-up at this point. + let type0 = pf.renders != 0 + && later_render + && !pf.initbm + && !self.recovery.fs_resync + && !pf.fs_ts + && ts[0] == 0 + && ts[1] == 0 + && tuning::CROSS_ENGINE_HOLD & 1 == 0; + let b = encode::barrier( + self.graph.render.fw_stamp[1].va, + pf.last_fs, + 1, + t, + ids::COMPUTE_UUID, + BarrierType::from_stamp_only(type0), + ); + s.barrier.write(0, &b)?; + self.engine.stats.fs2c0 += type0 as u64; + g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; + pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; + } else if pf.prev == Prev::Compute && tuning::COMPUTE_QUEUE_CLASS != 0 { + // Class 2 runs computes of the queue concurrently: keep the ring order with a wait + // on the previous compute's FW stamp. Type 1: a successor admitted with only the + // stamp wait makes the firmware decline the compute request that ends a hang. + let b = encode::barrier( + g.fw_stamp.va, + pf.last_ct, + ids::EVENT_SLOT, + t, + ids::COMPUTE_UUID, + BarrierType::Hold, + ); + s.barrier.write(0, &b)?; + g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; + pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; + } + let j = pf.computes as usize; + f.cstamp[j] = t; + f.cwait[j] = if pf.prev == Prev::Render { + pf.last_fs + } else { + 0 + }; + g.ring.w64(8 * pf.c_head as usize, s.work.va)?; + pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; + lap.lap(&mut self.engine.prof.write_ns); + if n <= 4 { + crate::cls_dev_dbg!( + Compute, + self.graph.dev, + "G15: compute n={} slot {} ctx={} cdm {:#x}..{:#x} att={} ts={:#x}/{:#x}\n", + n, + index, + ctx, + cmd.cmd.cdm_ctrl_stream_base, + cmd.cmd.cdm_ctrl_stream_end, + cmd.attachments.len(), + ts[0], + ts[1] + ); + } + pf.computes += 1; + pf.n = n; + pf.last_ct = t; + pf.ct_ts = ts[0] != 0 || ts[1] != 0; + pf.prev = Prev::Compute; + Ok(()) + } + + /// Render member: TA and FS work, sequences, scene and barriers in its pass slot, appended + /// to the TA and FS rings. Its TA waits on the previous FS (full order), on the previous + /// TA (early tiling: a flagged later render after a render, its FS then also waiting on the + /// previous FS), or on the previous compute of the prefix; its FS always waits on its own + /// TA. + fn prefix_render( + &mut self, + job: &Arc, + cmd: &RenderCommand, + refs: &RenderRefs, + pf: &mut Prefix, + f: &mut Flight, + ) -> Result { + let u = &cmd.cmd; + let ts = &cmd.timestamps; + let k = f.claims.pass[pf.renders as usize] as usize; + let n = pf.draw + 1; + let usc = job.queue.usc_base; + let ctx = job.vm.slot; + let tta = encode::stamp_seed(ids::TA_SEED, n); + let tfs = encode::stamp_seed(ids::FS_SEED, n); + // Early tiling: a later render member after a render of the same prefix whose render + // dependencies are fragment-only (FRAGMENT_BARRIERS) and that has no start timestamps + // lets its TA wait for the previous TA; its FS still waits for the previous FS, then + // its own TA. Compute dependencies are already ahead of the previous render's TA. + let early = pf.computes + pf.renders != 0 + && pf.prev == Prev::Render + && params::early_tiling() + && u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS != 0 + && ts[0] == 0 + && ts[2] == 0; + let scrub = self.slots.scrub.clone(); + let p = &scrub.passes[k]; + let pass = p.refs(); + let mut lap = Lap::start(); + let geo = Geometry::new(u, pass.heap_gva); + // Clustered tiling: one layer, one sample, 32x32 utiles, unless the submission asked + // for single-cluster vertex work, and a zeroed buffer holds this geometry. + let mut cl = None; + if encode::cluster_eligible(u, &geo) { + let bytes = ClusterLayout::new(&geo, 0).bytes; + if let Some(c) = self.slots.claim_ct(&mut f.claims, bytes)? { + let base = scrub.cts[c].gva.unwrap_or(0); + cl = Some(ClusterLayout::new(&geo, base)); + } + } + lap.lap(&mut self.engine.prof.claim_ns); + let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; + encode::encode_ta( + refs, + &pass, + u, + ts, + ctx, + tta, + &geo, + cl.as_ref(), + image(&mut scratch.ta)?, + image(&mut scratch.tas)?, + ); + encode::encode_fs( + refs, + &pass, + u, + ts, + ctx, + usc, + n, + tfs, + &geo, + image(&mut scratch.fs)?, + image(&mut scratch.fss)?, + ); + + lap.lap(&mut self.engine.prof.encode_ns); + // The slot is unpublished: its previous prefix fully retired. Its storage was reset in + // the background since then (flight release), or is reset here. + self.slots.claim_pass(k)?; + self.slots + .set_pass_dirty(k, geo.tpc_bytes, geo.tilemap_bytes); + lap.lap(&mut self.engine.prof.claim_ns); + if cl.is_some() { + self.engine.stats.clustered += 1; // its buffer is zero: cleared since its last use + } + let scratch = self.engine.scratch.as_deref().ok_or(ENOMEM)?; + p.ta_work.write(0, &scratch.ta[..])?; + p.fs_work.write(0, &scratch.fs[..])?; + p.ta_seq.write(0, &scratch.tas[..])?; + p.fs_seq.write(0, &scratch.fss[..])?; + p.scene.write(0, &encode::scene(refs, &pass, n))?; + + let r = &self.graph.render; + if pf.prev == Prev::Compute { + // Compute -> render: the TA waits on the previous compute; type 0 when that compute + // is of this prefix and this render starts no InitBM, on the class-0 compute queue + // only (on class 2 a TA admitted with only the stamp wait makes the firmware + // decline the request that ends a hung compute). + let type0 = pf.computes != 0 + && !pf.initbm + && !self.recovery.fs_resync + && n != 1 + && !(pf.renders == 0 && self.recovery.reinit) + && !pf.ct_ts + && ts.iter().all(|t| *t == 0) + && tuning::CROSS_ENGINE_HOLD & 2 == 0 + && tuning::COMPUTE_QUEUE_CLASS == 0; + let b = encode::barrier( + self.graph.compute.fw_stamp.va, + pf.last_ct, + ids::EVENT_SLOT, + tta, + RENDER_WAIT_UUID, + BarrierType::from_stamp_only(type0), + ); + p.prev_barrier.write(0, &b)?; + self.engine.stats.c2ta0 += type0 as u64; + } else if early { + let b = encode::barrier( + r.fw_stamp[0].va, + encode::stamp_seed(ids::TA_SEED, n - 1), + 0, + tta, + RENDER_WAIT_UUID, + BarrierType::Hold, + ); + p.prev_barrier.write(0, &b)?; + let b = encode::barrier( + r.fw_stamp[1].va, + pf.last_fs, + 1, + tfs, + RENDER_WAIT_UUID, + BarrierType::Hold, + ); + p.fs_dep.write(0, &b)?; + self.engine.stats.early += 1; + } else { + let mut prev_fs = if pf.prev != Prev::None { + pf.last_fs + } else if n == 1 { + ids::FS_SEED + } else { + encode::stamp_seed(ids::FS_SEED, n - 1) + }; + // Restricted type 0: predecessor render in this prefix, no InitBM/resync. + let internal = pf.prev == Prev::Render + && pf.renders != 0 + && !pf.initbm + && !self.recovery.fs_resync + && tuning::RENDER_INTERNAL_HOLD == 0; + // After a recovered failure the previous FS may never have written. + if pf.prev == Prev::None && self.recovery.fs_resync { + prev_fs = r.fw_stamp[1].r32(0)?; + } + let b = encode::barrier( + r.fw_stamp[1].va, + prev_fs, + 1, + tta, + RENDER_WAIT_UUID, + BarrierType::from_stamp_only(internal), + ); + p.prev_barrier.write(0, &b)?; + } + let b = encode::barrier( + r.fw_stamp[0].va, + tta, + 0, + tfs, + ids::FS_UUID, + BarrierType::Stamp, + ); + p.own_barrier.write(0, &b)?; + let cap = sizes::QUEUE_CAP; + if n == 1 || (pf.renders == 0 && self.recovery.reinit) { + pf.initbm = true; + let bm = encode::initbm(ctx, refs.pb_init_blocks, refs.pb_mgr, tta); + r.initbm.write(0, &bm)?; + r.ring[0].w64(8 * pf.ta_head as usize, r.initbm.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + } + // Rings: TA [InitBM,] predecessor wait, TA; FS [prior-FS wait if early,] own-TA wait, + // FS. + r.ring[0].w64(8 * pf.ta_head as usize, p.prev_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + r.ring[0].w64(8 * pf.ta_head as usize, p.ta_work.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + if early { + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_dep.va)?; + pf.fs_head = (pf.fs_head + 1) % cap; + } + r.ring[1].w64(8 * pf.fs_head as usize, p.own_barrier.va)?; + pf.fs_head = (pf.fs_head + 1) % cap; + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_work.va)?; + pf.fs_head = (pf.fs_head + 1) % cap; + lap.lap(&mut self.engine.prof.write_ns); + if n <= 4 { + crate::cls_dev_dbg!( + Render, + self.graph.dev, + "G15: render n={} slot {} ctx={} {}x{} L{} s{} utile {}x{} ss{} flags={:#x} vdm {:#x} ta/fs head {}/{} tpc {:#x} tilemap {:#x}\n", + n, + k, + ctx, + u.width_px, + u.height_px, + u.layers, + u.samples, + u.utile_width_px, + u.utile_height_px, + u.sample_size_B, + u.flags, + u.vdm_ctrl_stream_base, + pf.ta_head, + pf.fs_head, + geo.tpc_bytes, + geo.tilemap_bytes + ); + } + pf.renders += 1; + pf.draw = n; + pf.last_fs = tfs; + pf.fs_ts = ts.iter().any(|t| *t != 0); + pf.prev = Prev::Render; + Ok(()) + } + + /// Records the publication time of `f` and the preparation, gap and starvation times. + fn stat_publish(&mut self, f: &mut Flight) { + let s = &mut self.engine.stats; + s.pub_ns = now_ns(); + f.published_ns = s.pub_ns; + s.prep_ns += s.pub_ns.wrapping_sub(s.prep_from_ns); + if s.idle_from_ns != 0 { + s.gap_ns += s.pub_ns.wrapping_sub(s.idle_from_ns); + s.gaps += 1; + s.idle_from_ns = 0; + } else if s.starve_from_ns != 0 { + s.starved_ns += s.pub_ns.wrapping_sub(s.starve_from_ns); + } + s.starve_from_ns = 0; + } +} diff --git a/drivers/gpu/drm/asahi/g15/event.rs b/drivers/gpu/drm/asahi/g15/event.rs new file mode 100644 index 00000000000000..d8883476e3c254 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/event.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Decoded firmware events. +//! +//! Event ring records are 0x38 bytes: type 1 stage flags (u64 at +4: bit 0 TA, bit 1 FS, bit 2 +//! compute), type 0 fault, type 4 timeout (i32 culprit slot at +0xc), type 7 PB growth request +//! (copied whole into an 8-entry queue; never answered by the drain itself), type 8 channel +//! error. The drain runs under the device lock from the poll work (and inline in the boot and +//! device-control waits); the EP 0x20 interrupt only kicks the poll. Notifications only: +//! retirement has its own receipts. + +use kernel::{bindings, device, prelude::*}; + +use super::channel::Ring; +use super::fw::channels::{event, RING_SLOTS, STATE_READ, STATE_WRITE}; +use super::hw::rings; +use super::regs::{mb, rmb, wmb}; + +/// Number of queued PB growth requests. +pub(crate) const GROW_QUEUE: usize = 8; + +/// A copied firmware error event (type 0 fault or type 4 timeout). +#[derive(Copy, Clone, Default)] +pub(crate) struct ErrorEvent { + pub(crate) kind: u32, + pub(crate) raw: [u32; 14], + /// Type 4: the culprit event slot (possibly -1); -1 for type 0. + pub(crate) slot: i32, +} + +/// Event state consumed by the engine, recovery and growth. +pub(crate) struct Events { + /// Compute completions and stage events seen. + pub(crate) compute_events: u32, + pub(crate) stage_events: u32, + /// Error events seen, and the last one. + pub(crate) errors: u32, + pub(crate) last_error: Option, + /// Channel errors seen. + pub(crate) channel_errors: u32, + /// Last firing time per stage bit (TA, FS, compute), ns. + pub(crate) event_ns: [u64; 3], + /// PB growth requests, oldest first; at most [`GROW_QUEUE`]. + pub(crate) grow: KVec<[u32; 14]>, + /// Requests dropped because the queue was full. + pub(crate) grow_lost: u32, +} + +impl Events { + pub(crate) fn new() -> Self { + Self { + compute_events: 0, + stage_events: 0, + errors: 0, + last_error: None, + channel_errors: 0, + event_ns: [0; 3], + grow: KVec::new(), + grow_lost: 0, + } + } + + /// Reserves the growth queue, so that the drain never allocates. + pub(crate) fn reserve(&mut self) -> Result { + self.grow.reserve(GROW_QUEUE, GFP_KERNEL)?; + Ok(()) + } + + fn words(ring: &Ring, index: u32) -> Result<[u32; 14]> { + let base = index as usize * rings::EVENT_RECORD; + let mut w = [0u32; 14]; + for (j, word) in w.iter_mut().enumerate() { + *word = ring.ring.r32(base + 4 * j)?; + } + Ok(w) + } + + /// Decodes and consumes the event ring. + pub(crate) fn drain(&mut self, dev: &device::Device, ring: &Ring) -> Result { + let producer = ring.state.r32(STATE_WRITE)?; + let mut read = ring.state.r32(STATE_READ)?; + // SAFETY: ktime_get() has no preconditions. + let now = unsafe { bindings::ktime_get() } as u64; + if producer >= RING_SLOTS || read >= RING_SLOTS { + return Ok(()); + } + rmb(); + while read != producer { + let w = Self::words(ring, read)?; + let kind = w[0]; + let flags = w[1] as u64 | (w[2] as u64) << 32; + if kind == event::STAGE { + for b in 0..3 { + if flags & (1 << b) != 0 { + self.event_ns[b] = now; + } + } + if flags & (1 << 2) != 0 { + self.compute_events = self.compute_events.wrapping_add(1); + } + self.stage_events = self.stage_events.wrapping_add((flags & 7).count_ones()); + } + if kind == event::FAULT || kind == event::TIMEOUT { + self.last_error = Some(ErrorEvent { + kind, + raw: w, + slot: if kind == event::TIMEOUT { + w[3] as i32 + } else { + -1 + }, + }); + self.errors = self.errors.wrapping_add(1); + dev_err!( + dev, + "firmware event {}: {:08x} {:08x} {:08x} {:08x} {:08x} {:08x}\n", + kind, + w[1], + w[2], + w[3], + w[4], + w[5], + w[6] + ); + } else if kind == event::PB_GROW { + if self.grow.len() < GROW_QUEUE { + self.grow.push(w, GFP_KERNEL)?; + } else { + self.grow_lost = self.grow_lost.wrapping_add(1); + } + dev_dbg!( + dev, + "firmware event 7 (PB growth): ctx {} slot {} counter {} position {} epoch {:#x}\n", + w[1], + w[2], + w[3], + w[4], + w[5] as u64 | (w[6] as u64) << 32 + ); + } else if kind == event::CHANNEL_ERROR { + // Channel error (DMKill): needs a DEVCTL 8 acknowledgement. + dev_warn!( + dev, + "firmware event 8: {:08x} {:08x} {:08x} {:08x} {:08x}\n", + w[1], + w[2], + w[3], + w[4], + w[5] + ); + self.channel_errors = self.channel_errors.wrapping_add(1); + } else { + dev_dbg!(dev, "firmware event {} flags {:#x}\n", kind, flags); + } + read = (read + 1) % RING_SLOTS; + } + mb(); + ring.state.w32(STATE_READ, producer)?; + wmb(); + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/g15/fence.rs b/drivers/gpu/drm/asahi/g15/fence.rs new file mode 100644 index 00000000000000..a959ff00d4bb13 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/fence.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Job fences. +//! +//! One fence per job (= per SUBMIT, the aggregate of its commands) on a per-queue context +//! ([`Timeline`]), signalled strictly in queue order. The VM status is latched (and mirrored) +//! before a failed job's fence signals ([`super::job::Job`]). Signalling happens after the device +//! lock is dropped. +//! +//! The engine retires a queue's jobs in order, but a later job may still be completed first +//! (a prefix failed before an earlier job's last prefix retired, or a never-run job cancelled at +//! queue teardown). Fences of one context must signal in order, so a [`Timeline`] holds a +//! completed fence back until every earlier fence of the queue has completed. + +use kernel::{ + c_str, + dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, + new_mutex, + prelude::*, + str::CStr, + sync::{Arc, LockClassKey, Mutex}, +}; + +use crate::file::SyncItem; + +static TIMELINE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); +static ERROR_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); + +/// Fence operations of G15 job fences. +pub(crate) struct JobFenceOps; + +#[vtable] +impl FenceOps for JobFenceOps { + fn get_driver_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("asahi") + } + + fn get_timeline_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("g15") + } +} + +/// An accepted fence of a timeline that has not signalled yet. +struct Pending { + fence: UserFence, + /// The result, once the job completed. + result: Option, +} + +/// The fence timeline of one logical queue. +#[pin_data] +pub(crate) struct Timeline { + /// One context for job fences, signalled in creation order. + jobs: FenceContexts, + /// One context for the error fences of refused submissions, each signalled at creation. + errors: FenceContexts, + /// Accepted fences that have not signalled, oldest first. + #[pin] + pending: Mutex>, + /// Pre-signalled ENOMEM fence for a refused submission when no error fence can be allocated. + allocation_failure: Fence, +} + +impl Timeline { + pub(crate) fn new() -> Result> { + let errors = FenceContexts::new(1, c_str!("asahi_g15_refused"), ERROR_KEY)?; + let allocation_failure = error_fence(&errors, ENOMEM)?; + Arc::pin_init( + try_pin_init!(Self { + jobs: FenceContexts::new(1, c_str!("asahi_g15_queue"), TIMELINE_KEY)?, + errors, + pending <- new_mutex!(KVec::new(), "g15::Timeline::pending"), + allocation_failure, + }), + GFP_KERNEL, + ) + } + + /// Creates the fence of the next accepted job. Fences are created in submission order: the + /// caller holds the queue (SUBMIT is serialized per queue). + pub(crate) fn next(self: &Arc) -> Result { + let mut pending = self.pending.lock(); + pending.reserve(1, GFP_KERNEL)?; + let fence: UserFence = self.jobs.new_fence(0, JobFenceOps)?.into(); + pending + .push_within_capacity(Pending { + fence: fence.clone(), + result: None, + }) + .map_err(|_| ENOMEM)?; + Ok(JobFence { + fence, + timeline: self.clone(), + }) + } + + /// Records the result of `fence` and signals every completed fence at the head, in order. + fn complete(&self, fence: &UserFence, result: Result) { + let mut pending = self.pending.lock(); + let Some(entry) = pending + .iter_mut() + .find(|entry| entry.fence.raw() == fence.raw()) + else { + // Already signalled. + return; + }; + if entry.result.is_some() { + return; + } + entry.result = Some(result); + let mut signalled = 0; + for entry in pending.iter() { + let Some(result) = entry.result else { + break; + }; + if let Err(error) = result { + entry.fence.set_error(error); + } + entry.fence.signal(); + signalled += 1; + } + drop(pending.drain(..signalled)); + } + + /// A signalled fence carrying `error`, for the output syncs of a refused submission. + pub(crate) fn refused(&self, error: Error) -> Fence { + error_fence(&self.errors, error).unwrap_or_else(|_| self.allocation_failure.clone()) + } +} + +/// A fence on `contexts` signalled with `error`. Every fence of an error context signals at +/// creation, so the context's fences signal in order. +fn error_fence(contexts: &FenceContexts, error: Error) -> Result { + let fence = contexts.new_fence(0, JobFenceOps)?; + fence.set_error(error); + fence.signal(); + Ok(Fence::from_fence(&fence)) +} + +/// The hardware fence of one job. +pub(crate) struct JobFence { + fence: UserFence, + timeline: Arc, +} + +impl JobFence { + /// Signals the fence, with an error on failure, after every earlier fence of the queue. Only + /// the first call has an effect. + pub(crate) fn signal(&self, result: Result) { + self.timeline.complete(&self.fence, result); + } + + /// A reference to the fence. + pub(crate) fn fence(&self) -> Fence { + Fence::from_fence(&self.fence) + } +} + +impl Drop for JobFence { + fn drop(&mut self) { + // Every fence of a timeline must complete, or no later fence of the queue would signal. + // A no-op for a completed fence (a job that was never accepted, or a bug, is cancelled). + self.timeline.complete(&self.fence, Err(ECANCELED)); + } +} + +/// Installs a fence in the output syncs of a submission. +fn install(outputs: impl Iterator, fence: &Fence) { + for mut sync in outputs { + if let Some(chain) = sync.chain_fence.take() { + sync.syncobj.add_point(chain, fence, sync.timeline_value); + } else { + sync.syncobj.replace_fence(Some(fence)); + } + } +} + +/// The syncs of one SUBMIT. Every output sync gets a fence: the job's fence once the job is +/// accepted, a signalled error fence when the submission is refused (the shared `file.rs` +/// contract of `tracked_submission`). +pub(crate) struct Syncs { + syncs: KVec, + input_count: usize, +} + +impl Syncs { + pub(crate) fn new(syncs: KVec, input_count: usize) -> Self { + Self { syncs, input_count } + } + + /// The input syncs (all resolved to fences or already signalled). + pub(crate) fn inputs(&self) -> &[SyncItem] { + &self.syncs[..self.input_count.min(self.syncs.len())] + } + + /// Publishes the accepted job's fence in every output sync. + pub(crate) fn accept(mut self, fence: &Fence) { + let first = self.input_count.min(self.syncs.len()); + install(self.syncs.drain(first..), fence); + } + + /// Publishes a signalled error fence in every output sync of a refused submission. + pub(crate) fn refuse(mut self, timeline: &Timeline, error: Error) { + let first = self.input_count.min(self.syncs.len()); + if first < self.syncs.len() { + install(self.syncs.drain(first..), &timeline.refused(error)); + } + } +} diff --git a/drivers/gpu/drm/asahi/g15/fw/buffer.rs b/drivers/gpu/drm/asahi/g15/fw/buffer.rs new file mode 100644 index 00000000000000..37d2ffb09ef8a9 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/fw/buffer.rs @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Parameter-buffer and UMA allocator records of the 2419 firmware. +//! +//! The PB is one 512 MiB heap of [`MAX_PAGES`] pages of 0x8000 bytes in [`MAX_BLOCKS`] blocks of +//! four pages. The firmware sees it through the page list (u32 records `G >> 15` of compact +//! addresses `G = gva - 0x1000000000`, one per page), the block list (8-byte records, the low +//! word `G >> 15` of the block's first page) and the PB manager P: P+0x28 = 4 * blocks pages, +//! P+0x2c K = 4096 (truthful: 8 * K bytes is the block-list span the firmware synchronizes on +//! PB reconstruction, also during recovery), P+0x30 = blocks, P+0x48 = 4 * blocks - 1, +//! P+0x70/+0x74 = 4 * the firmware's growth maximum in pages (its asynchronous growth stops +//! there; a partial render may still ask for more). block_ctl +0 = blocks, +4 = the host +//! producer of block-list records, modulo K, advanced by every growth answer. +//! +//! Nothing here allocates, locks or publishes: the functions build the exact record bytes (a +//! zero fill followed by the field stores) and are host-tested. + +/// Bytes of one PB page. +pub(crate) const PAGE_BYTES: u64 = 0x8000; +/// Pages per block, and bytes of one block. +pub(crate) const PAGES_PER_BLOCK: u32 = 4; +pub(crate) const BLOCK_BYTES: u64 = 0x20000; +/// Blocks and pages of the mapped 512 MiB heap. +pub(crate) const MAX_BLOCKS: u32 = 4096; +pub(crate) const MAX_PAGES: u32 = 16384; +/// Records of the 0x8000-byte block list: the truthful K. +pub(crate) const BLOCK_LIST_RECORDS: u32 = 4096; +/// Sizes of the page list and the block list. +pub(crate) const PAGE_LIST_SIZE: usize = 0x28000; +pub(crate) const BLOCK_LIST_SIZE: usize = 0x8000; +/// Bytes of one block-list record. +pub(crate) const BLOCK_RECORD_BYTES: usize = 8; +/// Blocks per growth request (the native growImmediately). +pub(crate) const GROW_STEP: u32 = 10; +/// Smallest initial PB with growth. +pub(crate) const MIN_BLOCKS: u32 = 64; +/// Base of the 32-bit compact pointer window. +pub(crate) const COMPACT_BASE: u64 = 0x1000000000; + +/// Compact pointer of a GPU VA. +pub(crate) const fn compact(gva: u64) -> u64 { + gva.wrapping_sub(COMPACT_BASE) +} + +/// Page-list record of PB page `page` of the heap at `heap_gva`. +pub(crate) const fn page_record(heap_gva: u64, page: u32) -> u32 { + (compact(heap_gva + page as u64 * PAGE_BYTES) / PAGE_BYTES) as u32 +} + +/// Block-list record of PB block `block`: `(G - 0x1000000000) >> 15` of its first page. +pub(crate) const fn block_record(heap_gva: u64, block: u32) -> u32 { + (compact(heap_gva + block as u64 * BLOCK_BYTES) / PAGE_BYTES) as u32 +} + +/// Byte offset of the block-list record that block `block` goes to: `8 * (block % K)`. +pub(crate) const fn block_record_offset(block: u32) -> usize { + BLOCK_RECORD_BYTES * (block % BLOCK_LIST_RECORDS) as usize +} + +/// PB manager offsets (0xac bytes, firmware-only). +pub(crate) mod pb_manager { + pub(crate) const SIZE: usize = 0xac; + /// u64 page-list GVA, and its size in bytes. + pub(crate) const PAGE_LIST: usize = 0x1c; + pub(crate) const PAGE_LIST_BYTES: usize = 0x24; + pub(crate) const PAGES: usize = 0x28; + pub(crate) const K: usize = 0x2c; + pub(crate) const K_VALUE: u32 = super::BLOCK_LIST_RECORDS; + pub(crate) const BLOCKS: usize = 0x30; + /// u64 block-list GVA. + pub(crate) const BLOCK_LIST: usize = 0x38; + /// u64 block_ctl firmware VA. + pub(crate) const BLOCK_CTL: usize = 0x40; + pub(crate) const LAST_PAGE: usize = 0x48; + pub(crate) const BLOCK_BYTES: usize = 0x4c; + /// u64 PB counter firmware VA. + pub(crate) const COUNTER: usize = 0x58; + pub(crate) const MAX_PAGES_A: usize = 0x70; + pub(crate) const MAX_PAGES_B: usize = 0x74; +} + +/// UMA allocator manager offsets (0x84 bytes; render managers firmware+GPU class). +pub(crate) mod uma_manager { + pub(crate) const SIZE: usize = 0x84; + pub(crate) const ID: usize = 0x00; + pub(crate) const INDEX: usize = 0x08; + pub(crate) const ONE: usize = 0x0c; + /// u64 freelist GVA. + pub(crate) const FREELIST: usize = 0x14; + pub(crate) const UNK_1C: usize = 0x1c; + pub(crate) const UNK_1C_VALUE: u32 = 0x80000; + /// Freelist seeds available and total. + pub(crate) const SEEDS_A: usize = 0x24; + pub(crate) const SEEDS_B: usize = 0x2c; + pub(crate) const SEEDS: u32 = 8192; + /// u64 pool-table GVA. + pub(crate) const POOL_TABLE: usize = 0x34; + pub(crate) const UNK_44: usize = 0x44; + pub(crate) const UNK_44_VALUE: u32 = 0x40; + /// u64 counter firmware VA. + pub(crate) const COUNTER: usize = 0x48; +} + +/// UMA pools of one render engine: eight 4 MiB pools seeded 0x1000 at a time into the freelist +/// (8 * 1024 = [`uma_manager::SEEDS`] u64 records), pool-table rows of 0x40 bytes. +pub(crate) mod uma_pools { + pub(crate) const POOLS: usize = 8; + pub(crate) const POOL_SIZE: u64 = 0x400000; + pub(crate) const SEED_BYTES: u64 = 0x1000; + pub(crate) const FREELIST_SIZE: usize = 0x400000; + pub(crate) const POOL_TABLE_SIZE: usize = 0x1000; + pub(crate) const POOL_TABLE_OFFSET: usize = 0x3000; + pub(crate) const POOL_TABLE_STRIDE: usize = 0x40; + /// Pool-table row: the pool's GVA with bit 62. + pub(crate) const fn row(pool_gva: u64) -> u64 { + pool_gva | (1 << 62) + } +} + +/// Block control (0x40 bytes): +0 blocks, +4 the live producer of block-list records. +pub(crate) mod block_ctl { + pub(crate) const SIZE: usize = 0x40; + pub(crate) const BLOCKS: usize = 0; + pub(crate) const PRODUCER: usize = 4; +} + +/// Misc record (0x40 bytes): +0x20 = 1. +pub(crate) mod misc { + pub(crate) const SIZE: usize = 0x40; + pub(crate) const ENABLE: usize = 0x20; +} + +/// UMA and PB counters (0x40 bytes): +0 = 1 at initialization. +pub(crate) mod counter { + pub(crate) const SIZE: usize = 0x40; +} + +/// Scene list (0xc0 bytes), zeroed at initialization. +pub(crate) const SCENE_LIST_SIZE: usize = 0xc0; + +/// PB growth reply (DEVCTL 7) words. +pub(crate) mod grow_reply { + pub(crate) const OPCODE: usize = 0; + /// 1: grown, 0: refused (no new pages). + pub(crate) const GREW: usize = 1; + pub(crate) const SLOT: usize = 2; + pub(crate) const CONTEXT: usize = 3; + pub(crate) const COUNTER: usize = 4; + pub(crate) const POSITION: usize = 5; + /// u64 epoch (the Control halt count) at words 6..7. + pub(crate) const EPOCH: usize = 6; +} + +/// PB growth request (event type 7) words, copied whole by the event drain. +pub(crate) mod grow_request { + pub(crate) const TYPE: usize = 0; + pub(crate) const CONTEXT: usize = 1; + pub(crate) const SLOT: usize = 2; + /// The firmware's request counter (P+0x60 before its increment). + pub(crate) const COUNTER: usize = 3; + /// The TA position. + pub(crate) const POSITION: usize = 4; + /// u64 halt epoch at words 5..6. + pub(crate) const EPOCH: usize = 5; +} + +/// The C1 record written once per (re)initialization before the first render prefix that +/// follows it: {0x07400000, 4 * initial blocks}. +pub(crate) const fn c1_record(initial_blocks: u32) -> [u8; 16] { + let a = 0x07400000u32.to_le_bytes(); + let b = (PAGES_PER_BLOCK * initial_blocks).to_le_bytes(); + [ + a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3], 0, 0, 0, 0, 0, 0, 0, 0, + ] +} + +fn put32(image: &mut [u8], offset: usize, value: u32) { + image[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn put64(image: &mut [u8], offset: usize, value: u64) { + image[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +/// The PB manager image. +pub(crate) fn pb_manager_image( + initial: u32, + max: u32, + page_list_gva: u64, + block_list_gva: u64, + block_ctl_va: u64, + counter_va: u64, +) -> [u8; pb_manager::SIZE] { + let mut p = [0u8; pb_manager::SIZE]; + put64(&mut p, pb_manager::PAGE_LIST, page_list_gva); + put32(&mut p, pb_manager::PAGE_LIST_BYTES, PAGE_LIST_SIZE as u32); + put32(&mut p, pb_manager::PAGES, PAGES_PER_BLOCK * initial); + put32(&mut p, pb_manager::K, pb_manager::K_VALUE); + put32(&mut p, pb_manager::BLOCKS, initial); + put64(&mut p, pb_manager::BLOCK_LIST, block_list_gva); + put64(&mut p, pb_manager::BLOCK_CTL, block_ctl_va); + put32(&mut p, pb_manager::LAST_PAGE, PAGES_PER_BLOCK * initial - 1); + put32(&mut p, pb_manager::BLOCK_BYTES, BLOCK_BYTES as u32); + put64(&mut p, pb_manager::COUNTER, counter_va); + put32(&mut p, pb_manager::MAX_PAGES_A, PAGES_PER_BLOCK * max); + put32(&mut p, pb_manager::MAX_PAGES_B, PAGES_PER_BLOCK * max); + p +} + +/// A UMA manager image. The render managers have `id` = engine + 1, `index` = engine; the +/// compute graph's manager is id 3, index 2. +pub(crate) fn uma_manager_image( + id: u32, + index: u32, + freelist_gva: u64, + pool_table_gva: u64, + counter_va: u64, +) -> [u8; uma_manager::SIZE] { + let mut m = [0u8; uma_manager::SIZE]; + put32(&mut m, uma_manager::ID, id); + put32(&mut m, uma_manager::INDEX, index); + put32(&mut m, uma_manager::ONE, 1); + put64(&mut m, uma_manager::FREELIST, freelist_gva); + put32(&mut m, uma_manager::UNK_1C, uma_manager::UNK_1C_VALUE); + put32(&mut m, uma_manager::SEEDS_A, uma_manager::SEEDS); + put32(&mut m, uma_manager::SEEDS_B, uma_manager::SEEDS); + put64(&mut m, uma_manager::POOL_TABLE, pool_table_gva); + put32(&mut m, uma_manager::UNK_44, uma_manager::UNK_44_VALUE); + put64(&mut m, uma_manager::COUNTER, counter_va); + m +} + +/// The block-control image. +pub(crate) fn block_ctl_image(initial: u32) -> [u8; block_ctl::SIZE] { + let mut b = [0u8; block_ctl::SIZE]; + put32(&mut b, block_ctl::BLOCKS, initial); + put32(&mut b, block_ctl::PRODUCER, initial); + b +} + +/// The DEVCTL 7 reply to growth request `request`. +pub(crate) fn grow_reply_words(request: &[u32; 14], grew: bool) -> [u32; 14] { + let mut w = [0u32; 14]; + w[grow_reply::OPCODE] = super::channels::devctl::GROW_REPLY; + w[grow_reply::GREW] = u32::from(grew); + w[grow_reply::SLOT] = request[grow_request::SLOT]; + w[grow_reply::CONTEXT] = request[grow_request::CONTEXT]; + w[grow_reply::COUNTER] = request[grow_request::COUNTER]; + w[grow_reply::POSITION] = request[grow_request::POSITION]; + w[grow_reply::EPOCH] = request[grow_request::EPOCH]; + w[grow_reply::EPOCH + 1] = request[grow_request::EPOCH + 1]; + w +} + +#[cfg(test)] +mod tests { + use super::*; + + fn get32(b: &[u8], o: usize) -> u32 { + u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) + } + + fn get64(b: &[u8], o: usize) -> u64 { + u64::from_le_bytes(b[o..o + 8].try_into().unwrap()) + } + + const HEAP: u64 = 0x70c0000000; + + #[test] + fn records() { + // (0x70c0000000 - 0x1000000000) >> 15 = 0xc18000. + assert_eq!(page_record(HEAP, 0), 0xc18000); + assert_eq!(page_record(HEAP, 1), 0xc18001); + assert_eq!(block_record(HEAP, 0), 0xc18000); + assert_eq!(block_record(HEAP, 1), 0xc18004); + assert_eq!(block_record(HEAP, 2047), 0xc18000 + 4 * 2047); + // The last page of the 512 MiB heap. + assert_eq!(page_record(HEAP, MAX_PAGES - 1), 0xc18000 + 16383); + assert_eq!(block_record_offset(0), 0); + assert_eq!(block_record_offset(1023), 8 * 1023); + assert_eq!(block_record_offset(4096), 0); + assert_eq!(block_record_offset(4097), 8); + // The block list holds K records exactly. + assert_eq!( + BLOCK_LIST_RECORDS as usize * BLOCK_RECORD_BYTES, + BLOCK_LIST_SIZE + ); + // The page list holds every page of the heap. + assert!(MAX_PAGES as usize * 4 <= PAGE_LIST_SIZE); + assert_eq!(MAX_BLOCKS as u64 * BLOCK_BYTES, 0x20000000); + } + + #[test] + fn pb_manager() { + let p = pb_manager_image( + 1024, + 2048, + 0x1074000000, + 0x70e0000000, + 0xfffffc2d00010000, + 0xfffffc2d00020000, + ); + assert_eq!(get64(&p, 0x1c), 0x1074000000); + assert_eq!(get32(&p, 0x24), 0x28000); + assert_eq!(get32(&p, 0x28), 4096); + assert_eq!(get32(&p, 0x2c), 4096); + assert_eq!(get32(&p, 0x30), 1024); + assert_eq!(get64(&p, 0x38), 0x70e0000000); + assert_eq!(get64(&p, 0x40), 0xfffffc2d00010000); + assert_eq!(get32(&p, 0x48), 4095); + assert_eq!(get32(&p, 0x4c), 0x20000); + assert_eq!(get64(&p, 0x58), 0xfffffc2d00020000); + assert_eq!(get32(&p, 0x70), 8192); + assert_eq!(get32(&p, 0x74), 8192); + // Every other byte is zero (the zero fill). + let written = [ + (0x1c, 8), + (0x24, 4), + (0x28, 4), + (0x2c, 4), + (0x30, 4), + (0x38, 8), + (0x40, 8), + (0x48, 4), + (0x4c, 4), + (0x58, 8), + (0x70, 4), + (0x74, 4), + ]; + for (i, byte) in p.iter().enumerate() { + if !written.iter().any(|&(o, n)| i >= o && i < o + n) { + assert_eq!(*byte, 0, "byte {i:#x}"); + } + } + } + + #[test] + fn uma_manager() { + let m = uma_manager_image(2, 1, 0x7014490000, 0x701489b000, 0xfffffc2d00030000); + assert_eq!(get32(&m, 0), 2); + assert_eq!(get32(&m, 8), 1); + assert_eq!(get32(&m, 0xc), 1); + assert_eq!(get64(&m, 0x14), 0x7014490000); + assert_eq!(get32(&m, 0x1c), 0x80000); + assert_eq!(get32(&m, 0x24), 8192); + assert_eq!(get32(&m, 0x2c), 8192); + assert_eq!(get64(&m, 0x34), 0x701489b000); + assert_eq!(get32(&m, 0x44), 0x40); + assert_eq!(get64(&m, 0x48), 0xfffffc2d00030000); + assert_eq!(&m[0x50..], &[0u8; 0x84 - 0x50][..]); + // Freelist seeds = 8 pools of 4 MiB in 0x1000 units. + assert_eq!( + uma_pools::POOLS as u64 * uma_pools::POOL_SIZE / uma_pools::SEED_BYTES, + uma_manager::SEEDS as u64 + ); + // The seeded records fit the freelist. + assert!(uma_manager::SEEDS as usize * 8 <= uma_pools::FREELIST_SIZE); + } + + #[test] + fn small_records() { + let b = block_ctl_image(1024); + assert_eq!(get32(&b, 0), 1024); + assert_eq!(get32(&b, 4), 1024); + assert!(b[8..].iter().all(|&x| x == 0)); + assert_eq!(uma_pools::row(0x7010000000), 0x4000007010000000); + let c1 = c1_record(1024); + assert_eq!(get32(&c1, 0), 0x07400000); + assert_eq!(get32(&c1, 4), 4096); + assert!(c1[8..].iter().all(|&x| x == 0)); + } + + #[test] + fn reply() { + let mut q = [0u32; 14]; + q[0] = 7; + q[1] = 5; // context + q[2] = 0; // slot + q[3] = 12; // counter + q[4] = 0x345; // position + q[5] = 3; // epoch low + q[6] = 1; // epoch high + let w = grow_reply_words(&q, true); + assert_eq!(&w[..8], &[7, 1, 0, 5, 12, 0x345, 3, 1]); + assert!(w[8..].iter().all(|&x| x == 0)); + let w = grow_reply_words(&q, false); + assert_eq!(w[1], 0); + } +} diff --git a/drivers/gpu/drm/asahi/g15/fw/channels.rs b/drivers/gpu/drm/asahi/g15/fw/channels.rs new file mode 100644 index 00000000000000..7a002d0836c473 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/fw/channels.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Channel, device-control and event records. + +use kernel::prelude::*; + +/// Records per ring. +pub(crate) const RING_SLOTS: u32 = 256; + +/// Ring state cells (offsets in a 0x30-byte state block): the consumer's read index, the +/// completion index and the producer's write index. +pub(crate) const STATE_READ: usize = 0x00; +pub(crate) const STATE_COMPLETION: usize = 0x10; +pub(crate) const STATE_WRITE: usize = 0x20; + +/// A submit channel record. +#[repr(C)] +#[derive(Copy, Clone, Default)] +pub(crate) struct SubmitRecord { + pub(crate) unk_0: u64, + /// Queue-info VA of the queue to run. + pub(crate) qinfo: u64, + pub(crate) kind: u32, + /// Work-ring head the queue runs to. + pub(crate) head: u16, + pub(crate) event: u8, + pub(crate) new_queue: u8, +} + +static_assert!(core::mem::size_of::() == 0x18); +static_assert!(core::mem::offset_of!(SubmitRecord, qinfo) == 0x8); +static_assert!(core::mem::offset_of!(SubmitRecord, kind) == 0x10); +static_assert!(core::mem::offset_of!(SubmitRecord, head) == 0x14); +static_assert!(core::mem::offset_of!(SubmitRecord, event) == 0x16); +static_assert!(core::mem::offset_of!(SubmitRecord, new_queue) == 0x17); + +impl SubmitRecord { + /// The little-endian record bytes. + pub(crate) fn to_bytes(&self) -> [u8; 0x18] { + let mut b = [0u8; 0x18]; + b[0..8].copy_from_slice(&self.unk_0.to_le_bytes()); + b[8..16].copy_from_slice(&self.qinfo.to_le_bytes()); + b[16..20].copy_from_slice(&self.kind.to_le_bytes()); + b[20..22].copy_from_slice(&self.head.to_le_bytes()); + b[22] = self.event; + b[23] = self.new_queue; + b + } +} + +/// Device-control opcodes used with 2419. +pub(crate) mod devctl { + /// Re-import Globals. + pub(crate) const IMPORT_GLOBALS: u32 = 0x13; + /// Start. + pub(crate) const START: u32 = 9; + /// PB growth reply. + pub(crate) const GROW_REPLY: u32 = 7; +} + +/// A device-control record (0x38 bytes, opcode first). +#[repr(C)] +#[derive(Copy, Clone)] +pub(crate) struct DevCtl { + pub(crate) words: [u32; 14], +} + +static_assert!(core::mem::size_of::() == 0x38); + +impl DevCtl { + pub(crate) const fn op(opcode: u32) -> Self { + let mut words = [0; 14]; + words[0] = opcode; + Self { words } + } + + /// The opcode. + pub(crate) const fn opcode(&self) -> u32 { + self.words[0] + } + + /// The little-endian record bytes. + pub(crate) fn to_bytes(&self) -> [u8; 0x38] { + let mut b = [0u8; 0x38]; + for (i, w) in self.words.iter().enumerate() { + b[4 * i..4 * i + 4].copy_from_slice(&w.to_le_bytes()); + } + b + } +} + +/// Event types. +pub(crate) mod event { + pub(crate) const FAULT: u32 = 0; + pub(crate) const STAGE: u32 = 1; + pub(crate) const TIMEOUT: u32 = 4; + pub(crate) const PB_GROW: u32 = 7; + pub(crate) const CHANNEL_ERROR: u32 = 8; +} + +/// An event record. +#[repr(C)] +#[derive(Copy, Clone)] +pub(crate) struct EventRecord { + pub(crate) words: [u32; 14], +} + +static_assert!(core::mem::size_of::() == 0x38); diff --git a/drivers/gpu/drm/asahi/g15/fw/graph.rs b/drivers/gpu/drm/asahi/g15/fw/graph.rs new file mode 100644 index 00000000000000..d88b0fc0f6c153 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/fw/graph.rs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Queue-info rows, queue state, scheduling contexts, notifiers and the compute UMA manager. +//! +//! Queue-info scheduling row 2 (class 2, used for render and compute): +0x30 = 2, +0x34 = 2, +//! +0x38 = 0xffff000000000000, +0x40 = 0, +0x44 = 0, +0x48 = 2. Notifiers are initialized +//! once before first exposure and never written by the host again; the threshold is a +//! separate host-written uncached cell. + +/// Queue info (0xb4 bytes, firmware-only, ASC-cached). +pub(crate) mod qinfo { + pub(crate) const SIZE: usize = 0xb4; + /// u64 VAs of the queue state, the work ring, the job list and the queue scratch. + pub(crate) const STATE: usize = 0x00; + pub(crate) const RING: usize = 0x08; + pub(crate) const JOB_LIST: usize = 0x10; + pub(crate) const SCRATCH: usize = 0x18; + pub(crate) const UNK_2C: usize = 0x2c; + pub(crate) const UNK_4C: usize = 0x4c; + pub(crate) const UUID: usize = 0x50; + /// u64 scheduling context VA, then u64 4. + pub(crate) const SCHED_CTX: usize = 0xa4; + pub(crate) const UNK_AC: usize = 0xac; +} + +/// Queue-info scheduling rows (the firmware's recognized policy rows). +pub(crate) mod qinfo_row2 { + pub(crate) const CLASS: usize = 0x30; + pub(crate) const CLASS_B: usize = 0x34; + pub(crate) const MASK: usize = 0x38; + pub(crate) const MASK_VALUE: u64 = 0xffff000000000000; + pub(crate) const UNK_40: usize = 0x40; + pub(crate) const UNK_44: usize = 0x44; + pub(crate) const UNK_48: usize = 0x48; + /// Row 0 (class 0): +0x38 mask, +0x40 = 1, +0x48 = 1. + pub(crate) const ROW0_MASK_VALUE: u64 = 0xffffffffffff0000; +} + +/// Queue state (0x60 bytes, firmware-only, never cached). +pub(crate) mod qstate { + pub(crate) const SIZE: usize = 0x60; + /// Firmware DONE cursor. + pub(crate) const DONE: usize = 0x00; + /// Firmware READ cursor. + pub(crate) const READ: usize = 0x30; + /// Host WRITE cursor. + pub(crate) const WRITE: usize = 0x40; + /// Ring capacity in entries. + pub(crate) const CAP: usize = 0x50; +} + +/// Scheduling context (0x40 bytes): 0xff at +0..+1, 1 at +5, 0xff at +0x1e, 2 at +0x23. +pub(crate) mod sched_ctx { + pub(crate) const SIZE: usize = 0x40; +} + +/// Notifier (0x108 bytes): u64 threshold VA at +0, 0x50 at +0x10, 8 x 0xff at +0xa8; the +/// completing works store their context at +0x24 (firmware-owned once exposed). +pub(crate) mod notifier { + pub(crate) const SIZE: usize = 0x108; + pub(crate) const THRESHOLD: usize = 0x00; + pub(crate) const UNK_10: usize = 0x10; + pub(crate) const UNK_10_VALUE: u32 = 0x50; + /// The 8-byte mask the microsequences name (notifier + 0xa8). + pub(crate) const MASK: usize = 0xa8; +} + +/// Job list (0x18 bytes): u64 self VA at +8. +pub(crate) mod job_list { + pub(crate) const SIZE: usize = 0x18; + pub(crate) const SELF: usize = 0x08; +} + +/// The compute UMA allocator manager (0x84 bytes). The render managers have the same layout +/// (`fw::buffer`). +pub(crate) mod manager { + pub(crate) const SIZE: usize = 0x84; + pub(crate) const ID: usize = 0x00; + pub(crate) const INDEX: usize = 0x08; + pub(crate) const ONE: usize = 0x0c; + pub(crate) const FREELIST: usize = 0x14; + pub(crate) const UNK_1C: usize = 0x1c; + pub(crate) const UNK_1C_VALUE: u32 = 0x80000; + pub(crate) const SEEDS_A: usize = 0x24; + pub(crate) const SEEDS_B: usize = 0x2c; + pub(crate) const POOL_TABLE: usize = 0x34; + pub(crate) const UNK_44: usize = 0x44; + pub(crate) const UNK_44_VALUE: u32 = 0x40; + pub(crate) const COUNTER: usize = 0x48; + /// Compute manager identity: id 3, index 2. + pub(crate) const COMPUTE_ID: u32 = 3; + pub(crate) const COMPUTE_INDEX: u32 = 2; +} + +/// Compute pool table rows (0x40 bytes each, `gva | 1 << 62`) and freelist seeds (u64 VAs of +/// 0x1000-byte units of every pool). Seeding only the first eight pools (8192 pages, 32 MiB) let +/// ten compute workgroups of more than ~576 threads run at once and hung the eleventh (ticket +/// malik-na/linux-aurora#69): such groups take their memory from this pool. +pub(crate) mod pools { + pub(crate) const TABLE_STRIDE: usize = 0x40; + pub(crate) const TABLE_VALID: u64 = 1 << 62; + pub(crate) const SEED_BYTES: u64 = 0x1000; + pub(crate) const SEEDED_POOLS: usize = crate::g15::hw::sizes::POOLS; + /// Seeds in the freelist. + pub(crate) const SEEDS: u32 = + (SEEDED_POOLS as u64 * crate::g15::hw::sizes::POOL_SIZE / SEED_BYTES) as u32; +} diff --git a/drivers/gpu/drm/asahi/g15/fw/initdata.rs b/drivers/gpu/drm/asahi/g15/fw/initdata.rs new file mode 100644 index 00000000000000..d5a1f0188b3682 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/fw/initdata.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Initdata layout of the 2419 build. +//! +//! The driver writes sparse words into large objects and board images, so this module holds the +//! offsets that the initdata build and recovery use, not full structure definitions. Several +//! canonical objects (Runtime, HardwareData, Globals, Power, Control) start at unaligned VAs, so +//! their words are written as bytes. + +/// Root object (0xc0 bytes). +pub(crate) mod root { + pub(crate) const SIZE: usize = 0xc0; + pub(crate) const MAGIC: u64 = 0x0c08e21e83800490; + pub(crate) const REGION_A: usize = 0x08; + pub(crate) const RUNTIME: usize = 0x18; + pub(crate) const GLOBALS: usize = 0x20; + /// u32 1. + pub(crate) const ENABLE: usize = 0x2c; + /// u16 page size, u8 page shift, u8 levels. + pub(crate) const GEOMETRY: usize = 0x30; + /// Three 0x20-byte level descriptors. + pub(crate) const LEVELS: usize = 0x34; + pub(crate) const LEVEL_STRIDE: usize = 0x20; + pub(crate) const FLAGS: usize = 0xa8; + pub(crate) const CONTROL: usize = 0xb0; + pub(crate) const POWER: usize = 0xb8; +} + +/// Region A (one page). +pub(crate) mod region_a { + pub(crate) const SIZE: usize = 0x4000; +} + +/// Runtime object (0x4b3 bytes). +pub(crate) mod runtime { + pub(crate) const SIZE: usize = 0x4b3; + pub(crate) const HWDATA: usize = 0x00; + pub(crate) const PAIR: usize = 0x08; + pub(crate) const PAIR2: usize = 0x10; + /// 13 x {state, completion cell, write cell, ring}: the 12 submit channels, then DEVCTL. + pub(crate) const CHANNELS: usize = 0x18; + pub(crate) const CHANNEL_STRIDE: usize = 0x20; + /// 4 x {state, ring}: event, log, trace, stats. + pub(crate) const RX: usize = 0x1b8; + pub(crate) const RX_STRIDE: usize = 0x10; + pub(crate) const SMALL: usize = 0x1f8; + pub(crate) const TA_ACTIVITY: usize = 0x234; + pub(crate) const FS_ACTIVITY: usize = 0x23c; + pub(crate) const COMPUTE_ACTIVITY: usize = 0x244; + pub(crate) const FAULT_INFO: usize = 0x24c; + pub(crate) const C0: usize = 0x2a8; + pub(crate) const C1: usize = 0x2b0; + pub(crate) const C1_2: usize = 0x2b8; + pub(crate) const C3: usize = 0x2c0; + pub(crate) const C3_2: usize = 0x2c8; + /// u32 4. + pub(crate) const UNK_2D0: usize = 0x2d0; + /// Readiness magic written by the firmware. + pub(crate) const READY: usize = 0x314; + pub(crate) const READY_MAGIC: u32 = 0xabcdabcd; + /// u32 0xff. + pub(crate) const UNK_3B0: usize = 0x3b0; + pub(crate) const HWDATA_A: usize = 0x441; +} + +/// Pair (0x100 bytes) and Small (0x10 bytes). +pub(crate) mod pair { + pub(crate) const SIZE: usize = 0x100; +} +pub(crate) mod small { + pub(crate) const SIZE: usize = 0x10; +} + +/// C0 (0x1000 bytes), C1 and C3 (one page each): firmware + GPU shared. +pub(crate) mod cbuf { + pub(crate) const C0_SIZE: usize = 0x1000; + pub(crate) const C1_SIZE: usize = 0x4000; + pub(crate) const C3_SIZE: usize = 0x4000; +} + +/// Control object (0xc3d0 bytes). +pub(crate) mod control { + pub(crate) const SIZE: usize = 0xc3d0; + /// u32 1 at initdata. + pub(crate) const ENABLE: usize = 0x4; + pub(crate) const PENDING: usize = 0x40a0; + pub(crate) const FWCTL_STATE: usize = 0x4568; + pub(crate) const FWCTL_RING: usize = 0x4570; + pub(crate) const HALT_COUNT: usize = 0x4580; + /// u32: firmware halted for recovery (it sets 1, the host clears). + pub(crate) const HALTED: usize = 0x4590; + pub(crate) const RESUME: usize = 0x45a0; + pub(crate) const FLAG: usize = 0x45b0; + /// u32 1 at initdata. + pub(crate) const ENABLE2: usize = 0x45c4; +} + +/// Globals (15,868 bytes) words used after READY. +pub(crate) mod globals { + pub(crate) const SIZE: usize = 15868; + pub(crate) const COMPUTE_KILL: usize = 0x1c; + pub(crate) const FRAGMENT_KILL: usize = 0x24; + pub(crate) const IDLE_ENABLE: usize = 0x2c; + pub(crate) const IDLE_PREDICTIVE: usize = 0x30; + pub(crate) const IDLE_STANDBY_US: usize = 0x7a8; + pub(crate) const IDLE_MIN_CONF: usize = 0x7c4; + /// Template 10, written 100. + pub(crate) const UNK_980: usize = 0x980; + pub(crate) const IDLE_DELAY: usize = 0x9a0; + pub(crate) const COMPUTE_MONITOR: usize = 0x9b0; +} + +/// Power (2,292 bytes). +pub(crate) mod power { + pub(crate) const SIZE: usize = 2292; +} + +/// HardwareData (35,332 bytes). +pub(crate) mod hwdata { + pub(crate) const SIZE: usize = 35332; + /// Bytes of the first pages mapped ASC-cached (HardwareDataB and the activity records): + /// up to the end of the page after the one holding byte 0. + pub(crate) const CACHED: usize = 0x4a04; + pub(crate) const TIMESTAMPS: usize = 0x28; + /// IOMapping records: 32 bytes per slot, the firmware VA at +8. + pub(crate) const IOMAPS: usize = 0x640; + pub(crate) const IOMAP_STRIDE: usize = 32; + pub(crate) const IOMAP_VA: usize = 8; + /// Template checks: u32 1, and the number of DVFS states minus one. + pub(crate) const CHECK_A38: usize = 0xa38; + pub(crate) const DVFS_COUNT: usize = 0xb58; + pub(crate) const TTBAT: usize = 0xb44; + pub(crate) const TA_ACTIVITY: usize = 0x1880; + pub(crate) const FS_ACTIVITY: usize = 0x24c0; + pub(crate) const COMPUTE_ACTIVITY: usize = 0x3740; + /// HardwareDataA: the maintained S8 request words. + pub(crate) const HWDATA_A: usize = 0x4580; + /// HardwareDataA word holding the machine's maximum GPU power in mW (Globals +0x78 and + /// Power +0xd0 repeat it). + pub(crate) const MAX_POWER_A: usize = 0x6a4; + pub(crate) const FAULT_INFO: usize = 0x8900; +} + +/// Flags (0x40 bytes). +pub(crate) mod flags { + pub(crate) const SIZE: usize = 0x40; + pub(crate) const READY: usize = 4; +} diff --git a/drivers/gpu/drm/asahi/g15/fw/mod.rs b/drivers/gpu/drm/asahi/g15/fw/mod.rs new file mode 100644 index 00000000000000..234805b0819234 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/fw/mod.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G15 firmware 2419 structures. +//! +//! Layouts of the records, work images and objects the host shares with the 2419 firmware, +//! in the style of `g17/fw`: `#[repr(C)]` structures with `static_assert!` offsets where the +//! layout is a fixed record, and offset constants where the driver writes sparse words into a +//! larger image. Nothing here allocates, locks or publishes. + +pub(crate) mod buffer; +pub(crate) mod channels; +pub(crate) mod graph; +pub(crate) mod initdata; +pub(crate) mod work; diff --git a/drivers/gpu/drm/asahi/g15/fw/work.rs b/drivers/gpu/drm/asahi/g15/fw/work.rs new file mode 100644 index 00000000000000..929101852333f0 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/fw/work.rs @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Compute, TA and FS work images and microsequence records of the 2419 firmware. +//! +//! Compute work: 0x893 bytes at client +0x3760, sequence 0x2b8. TA work: 0x92b bytes, 72 +//! register records, sequence 0x2d8. FS work: 0xc73 bytes, 79 register records and the +//! parameter block, sequence 0x310. Register records are 12-byte `(u32 selector, u64 value)` +//! pairs; timestamp records are 0x3c bytes (0x80000003/3). Barrier records are 0x3e bytes: +4 +//! wait stamp VA, +0x14 value, +0x18 producing engine, +0x1c own stamp, +0x20 UUID, +0x2a type +//! (0 = firmware-stamp wait only, 1 = also the predecessor software-job hold). +//! +//! Microsequence opcodes: compute start 0x0b / finalize 0x0c, TA 5 / 6, FS 7 / 8, barrier 4, +//! InitBM 6, END 0x40000002. Work type word: compute 3, TA 0, FS 1. HardwareData references: +//! compute +0x3740, TA +0x1884, FS +0x24c8. +//! +//! The encoders ([`super::super::encode`]) write the sparse words of these images at literal +//! offsets (kept inline there); this module holds the sizes, the fixed records and the register +//! selector tables. + +/// Microsequence opcodes. +pub(crate) mod op { + pub(crate) const COMPUTE_START: u32 = 0x0b; + pub(crate) const COMPUTE_FINALIZE: u32 = 0x0c; + pub(crate) const TA_START: u32 = 5; + pub(crate) const TA_FINALIZE: u32 = 6; + pub(crate) const FS_START: u32 = 7; + pub(crate) const FS_FINALIZE: u32 = 8; + pub(crate) const BARRIER: u32 = 4; + pub(crate) const INIT_BM: u32 = 6; + pub(crate) const END: u32 = 0x40000002; + /// Start timestamp record; the end record is `TIMESTAMP & 0xff` (3). + pub(crate) const TIMESTAMP: u32 = 0x80000003; + pub(crate) const TIMESTAMP_END: u32 = 3; +} + +/// Barrier wait types (+0x2a of a barrier record). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum BarrierType { + /// Wait for the producer's firmware stamp only. + Stamp = 0, + /// Also hold for the predecessor software job (0x537/0x538). + Hold = 1, +} + +impl BarrierType { + /// Type 0 if `stamp_only`, else type 1. + pub(crate) const fn from_stamp_only(stamp_only: bool) -> Self { + if stamp_only { + BarrierType::Stamp + } else { + BarrierType::Hold + } + } +} + +/// Work type words. +pub(crate) mod work_type { + pub(crate) const TA: u32 = 0; + pub(crate) const FS: u32 = 1; + pub(crate) const COMPUTE: u32 = 3; +} + +/// One `(u32 selector, u64 value)` register record. +pub(crate) const REG_RECORD: usize = 12; + +/// Compute work image and microsequence. +pub(crate) mod compute { + /// Work image bytes. + pub(crate) const WORK_SIZE: usize = 0x893; + /// Microsequence bytes; the sequence object is 0x1000 bytes. + pub(crate) const SEQ_SIZE: usize = 0x2b8; + pub(crate) const SEQ_OBJECT: usize = 0x1000; + /// Register records at +0x20. + pub(crate) const REGS: usize = 0x20; + /// HardwareData compute activity record. + pub(crate) const HWDATA: u64 = 0x3740; + /// Attachment records in the start record (+0x54, 16 bytes each). + pub(crate) const ATTACHMENTS: usize = 0x54; + pub(crate) const ATTACHMENT_STRIDE: usize = 16; + /// Start/end timestamp records and the base of their cells in the work image. + pub(crate) const TS_START: usize = 0x1bc; + pub(crate) const TS_END: usize = 0x1fc; + pub(crate) const TS_CELLS: u64 = 0x810; + /// Finalize record. + pub(crate) const FINALIZE: usize = 0x238; + pub(crate) const END: usize = 0x2b4; + + /// Register selectors of the compute work image. + pub(crate) const SEL: [u32; 22] = [ + 0x1a510, 0x1a420, 0x1a4d0, 0x1a4d8, 0x1a4e0, 0x1a4e8, 0x1a440, 0x1a458, 0x12091, 0x101d9, + 0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1, 0x101d1, 0xd479, 0x1a0e9, 0x107a1, + 0xa599, 0xd411, + ]; +} + +/// TA work image and microsequence. +pub(crate) mod ta { + pub(crate) const WORK_SIZE: usize = 0x92b; + pub(crate) const SEQ_SIZE: usize = 0x2d8; + pub(crate) const SEQ_OBJECT: usize = 0x1000; + /// Register records at +0x40. + pub(crate) const REGS: usize = 0x40; + pub(crate) const HWDATA: u64 = 0x1884; + /// Work tail (shared layout, [`super::tail`]). + pub(crate) const TAIL: usize = 0x8a8; + pub(crate) const TS_START: usize = 0x1cc; + pub(crate) const TS_END: usize = 0x20c; + pub(crate) const FINALIZE: usize = 0x248; + pub(crate) const END: usize = 0x2d4; + + /// Register selectors of the TA work image. + pub(crate) const SEL: [u32; 72] = [ + 0x1748, 0x10141, 0x1c039, 0x1c9c8, 0x1c041, 0x1c9d0, 0x1c0a1, 0x1c031, 0x1c9c0, 0x1c051, + 0x1c061, 0x10149, 0x10139, 0x10111, 0x1c9b0, 0x10119, 0x1c9b8, 0x1c958, 0x1c950, 0x1c930, + 0x1c880, 0x1c898, 0x1c948, 0x1c888, 0x1c890, 0x1c918, 0x1c079, 0x1c9d8, 0x1c089, 0x1c9e0, + 0x16c41, 0x1ca40, 0x1c9a8, 0x1c920, 0x10151, 0x1c199, 0x1c1a1, 0x1c1a9, 0x1c1b1, 0x1c1b9, + 0x1c8f8, 0x1c0b1, 0x1c850, 0x10131, 0x10121, 0x10129, 0x101b9, 0x1c069, 0x1c071, 0x1c081, + 0x1c0a9, 0x10171, 0x10169, 0x12099, 0x101e1, 0x1c9e8, 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, + 0x1a0c9, 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799, 0xa5a1, 0xd419, 0x1c830, 0x1ca30, + 0x16c39, 0x1c910, + ]; + + /// Index of register #33 (PBREQ: the initial PB size in pages, 0x3c when clustered). + pub(crate) const REG_PBREQ: usize = 32; +} + +/// FS work image and microsequence. +pub(crate) mod fs { + pub(crate) const WORK_SIZE: usize = 0xc73; + pub(crate) const SEQ_SIZE: usize = 0x310; + pub(crate) const SEQ_OBJECT: usize = 0x1000; + /// Register records at +0x80. + pub(crate) const REGS: usize = 0x80; + /// Parameter block / firmware mirrors. + pub(crate) const PARAMS: usize = 0x790; + pub(crate) const HWDATA: u64 = 0x24c8; + pub(crate) const TAIL: usize = 0xbf0; + pub(crate) const TS_START: usize = 0x1dc; + pub(crate) const TS_END: usize = 0x21c; + pub(crate) const FINALIZE: usize = 0x258; + pub(crate) const END: usize = 0x30c; + + /// Register selectors of the FS work image. + pub(crate) const SEL: [u32; 79] = [ + 0x1739, 0x10009, 0x15379, 0x15381, 0x15369, 0x15371, 0x15131, 0x15139, 0x100a1, 0x15069, + 0x15071, 0x16058, 0x10019, 0x100b1, 0x16030, 0x100d9, 0x10791, 0x16098, 0x15109, 0x15101, + 0x15021, 0x15211, 0x15049, 0x10051, 0x15321, 0x15301, 0x15309, 0x15311, 0x15319, 0x15349, + 0x15351, 0x15329, 0x15331, 0x15339, 0x15341, 0x15231, 0x15221, 0x15239, 0x15229, 0x15401, + 0x15421, 0x15409, 0x15429, 0x153c1, 0x15411, 0x153c9, 0x15431, 0x153d1, 0x15419, 0x153d9, + 0x15439, 0x16429, 0x16060, 0x16431, 0x10039, 0x16020, 0x16451, 0x15359, 0x100b8, 0x16461, + 0x16090, 0x120a1, 0x101e9, 0x160a8, 0x16068, 0x160b8, 0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, + 0x1a0d9, 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0x1c838, 0x1ca28, 0xa5a9, 0xd429, + ]; +} + +/// The 0x3c timestamp record: `+0` opcode, `+4/+0xc/+0x14` cells of the work image at `B`, +/// `+0x1c` queue info, `+0x24` user pair (0 unless requested), `+0x2c` `W + B + 0x58`, `+0x34` +/// UUID. +pub(crate) mod ts_record { + pub(crate) const SIZE: usize = 0x3c; +} + +/// The work tail shared by TA (+0x8a8) and FS (+0xbf0); the compute image has the same layout +/// at +0x810. +pub(crate) mod tail { + pub(crate) const ITS_START: usize = 0x8; + pub(crate) const ITS_END: usize = 0x10; + pub(crate) const USER_START: usize = 0x18; + pub(crate) const USER_END: usize = 0x20; + pub(crate) const UMA_MANAGER: usize = 0x2e; + pub(crate) const SCRATCH: usize = 0x47; +} + +/// Barrier record. +pub(crate) mod barrier { + pub(crate) const SIZE: usize = 0x3e; + pub(crate) const STAMP_VA: usize = 0x4; + pub(crate) const STAMP_VA2: usize = 0xc; + pub(crate) const WAIT: usize = 0x14; + pub(crate) const EVENT: usize = 0x18; + pub(crate) const OWN: usize = 0x1c; + pub(crate) const UUID: usize = 0x20; + pub(crate) const TYPE: usize = 0x2a; + /// UUID of render predecessor waits. + pub(crate) const RENDER_WAIT_UUID: u32 = 0x3d420; +} + +/// InitBM record (0x20 bytes). +pub(crate) mod initbm { + pub(crate) const SIZE: usize = 0x20; + pub(crate) const CTX: usize = 0x4; + pub(crate) const BLOCKS: usize = 0x10; + pub(crate) const PB_MANAGER: usize = 0x14; + pub(crate) const STAMP: usize = 0x1c; +} + +/// Per-pass scene record (0x80 bytes). +pub(crate) mod scene { + pub(crate) const SIZE: usize = 0x80; + /// Scene-list slots cycled by draw ordinal (`scene_list + 4 * (n % 48)`). + pub(crate) const LIST_SLOTS: u64 = 48; +} diff --git a/drivers/gpu/drm/asahi/g15/gate.rs b/drivers/gpu/drm/asahi/g15/gate.rs new file mode 100644 index 00000000000000..f41b2e3f75f57c --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/gate.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Stream admission gates (safety nets for userspace encoders). +//! +//! VDM: the root stream's first word is 0x21000960. CDM walk from `cdm_ctrl_stream_base` through +//! links until TERMINATE (0x40000000), at most 8192 records and 64 links (a longer or cyclic +//! stream is rejected): barriers 0x60000160, 0x60001560, 0x600215fe, 0x600201fe; +//! link 0x2000XXXX; direct launch (40 B, the G15 layout), indirect launches 36 B +//! (`w0 & 0xff7fffff == 0x08080000`) and 24 B (0x10080000); every program VA inside the queue's +//! 4 GiB USC window, 64-aligned, first 64 bytes readable. Client memory is read through the VM's +//! page tables with a point-of-coherency clean+invalidate of the lines ([`mmu::Vm::read_user`]: +//! the GPU may have written it). `g15_stream_gate=0` disables both gates (encoder bring-up only). + +use core::sync::atomic::{AtomicU32, Ordering}; +use kernel::prelude::*; + +use super::{command::cover, command::USC_WINDOW, params}; +use crate::mmu; + +const VDM_ROOT: u32 = 0x21000960; +const CDM_TERMINATE: u32 = 0x40000000; +const CDM_BARRIERS: [u32; 4] = [0x60000160, 0x600215fe, 0x60001560, 0x600201fe]; +const CDM_LINK: u32 = 0x20000000; +const CDM_DIRECT: u32 = 0x00080000; +const CDM_INDIRECT_SIZES: u32 = 0x08080000; +const CDM_INDIRECT: u32 = 0x10080000; +const CDM_MAX_RECORDS: u32 = 8192; +const CDM_MAX_LINKS: u32 = 64; +/// Rejections logged per boot. +const MAX_REPORTS: u32 = 32; + +static REPORTS: AtomicU32 = AtomicU32::new(0); + +/// Logs a refused record and refuses it. +fn reject(what: &str, va: u64, w: &[u32]) -> Error { + if REPORTS.fetch_add(1, Ordering::Relaxed) < MAX_REPORTS { + let word = |i: usize| w.get(i).copied().unwrap_or(0); + pr_warn!( + "G15: rejecting {} record at {:#x}: {:08x} {:08x} {:08x} {:08x}\n", + what, + va, + word(0), + word(1), + word(2), + word(3) + ); + } + EINVAL +} + +/// Up to 256 stream bytes read at once. +struct Window { + va: u64, + len: usize, + bytes: [u8; 256], +} + +impl Window { + /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page + /// unless the record crosses it). Unreadable memory: EFAULT. + fn words(&mut self, vm: &mmu::Vm, va: u64, count: usize) -> Result<[u32; 10]> { + let n = count * 4; + let cached = self.len != 0 + && va >= self.va + && va + .checked_add(n as u64) + .is_some_and(|end| end <= self.va + self.len as u64); + if !cached { + let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); + let len = n.max(self.bytes.len().min(in_page)); + self.len = 0; + vm.read_user(va, &mut self.bytes[..len]) + .map_err(|_| EFAULT)?; + self.va = va; + self.len = len; + } + let start = (va - self.va) as usize; + let mut words = [0u32; 10]; + for (index, word) in words.iter_mut().take(count).enumerate() { + let at = start + index * 4; + let mut le = [0u8; 4]; + le.copy_from_slice(&self.bytes[at..at + 4]); + *word = u32::from_le_bytes(le); + } + Ok(words) + } +} + +/// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. +/// `checked` caches the last proven program page. +fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> Result { + if address < usc || address - usc >= USC_WINDOW || address & 63 != 0 { + return Err(EINVAL); + } + // 64-aligned: the block never crosses its page. + let page = address & !(mmu::UAT_PGMSK as u64); + if *checked == Some(page) { + return Ok(()); + } + cover(vm, address, address + 64, true, false)?; + *checked = Some(page); + Ok(()) +} + +/// VDM admission: a normal root stream opens with exactly the G15 barrier. +pub(crate) fn vdm(vm: &mmu::Vm, va: u64) -> Result { + if !params::stream_gate() { + return Ok(()); + } + let mut bytes = [0u8; 4]; + vm.read_user(va, &mut bytes).map_err(|_| EFAULT)?; + let word = u32::from_le_bytes(bytes); + if word != VDM_ROOT { + return Err(reject("VDM root", va, &[word])); + } + Ok(()) +} + +/// CDM admission: walks the stream from its base through no-return links until TERMINATE, +/// admitting only the known G15S records: direct launch (40), indirect launch (36/24), barriers +/// (4), link (8). +pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64) -> Result { + if !params::stream_gate() { + return Ok(()); + } + let mut window = Window { + va: 0, + len: 0, + bytes: [0; 256], + }; + let mut checked = None; + let mut va = base; + let mut links = 0; + let mut records = 0; + while records < CDM_MAX_RECORDS { + records += 1; + let w = window.words(vm, va, 1)?; + if CDM_BARRIERS.contains(&w[0]) { + va += 4; + continue; + } + if w[0] == CDM_TERMINATE { + return Ok(()); + } + if w[0] & 0xffff0000 == CDM_LINK { + let w = window.words(vm, va, 2)?; + links += 1; + if links > CDM_MAX_LINKS { + return Err(reject("CDM link budget", va, &w)); + } + va = (u64::from(w[0] & 0xffff) << 32) | u64::from(w[1]); + if va & 3 != 0 { + return Err(reject("CDM link", va, &w)); + } + continue; + } + if w[0] == CDM_DIRECT { + let w = window.words(vm, va, 10)?; + let address = (u64::from(w[1] >> 16) << 32) | (u64::from(w[2]) << 6); + if w[1] & 0xffff != 0 || w[3] != 0x40 || (w[2] >> 26) != ((w[1] >> 16) & 0x3f) { + return Err(reject("CDM direct launch", va, &w)); + } + match program(vm, usc, address, &mut checked) { + Err(error) if error == EINVAL => return Err(reject("CDM program", va, &w)), + result => result?, + } + va += 40; + continue; + } + let kind = w[0] & 0xff7fffff; + if kind == CDM_INDIRECT_SIZES || kind == CDM_INDIRECT { + let sizes = kind == CDM_INDIRECT_SIZES; + let w = window.words(vm, va, if sizes { 9 } else { 6 })?; + let address = (u64::from(w[1] >> 22) << 38) | (u64::from(w[2]) << 6); + let indirect = (u64::from(w[4] & 0xffff) << 32) | u64::from(w[5]); + let bad_size = |size: u32| size == 0 || size > 0x7ff; + if w[3] != (0x40000000 | ((address >> 40) & 0xff) as u32) + || w[4] >> 16 != 0 + || indirect & 3 != 0 + || (sizes && (bad_size(w[6]) || bad_size(w[7]) || bad_size(w[8]))) + { + return Err(reject("CDM indirect launch", va, &w)); + } + let result = program(vm, usc, address, &mut checked) + .and_then(|()| cover(vm, indirect, indirect + 12, true, false)); + match result { + Err(error) if error == EINVAL => return Err(reject("CDM indirect", va, &w)), + result => result?, + } + va += if sizes { 36 } else { 24 }; + continue; + } + return Err(reject("CDM", va, &w)); + } + Err(reject("CDM record budget", va, &[])) +} diff --git a/drivers/gpu/drm/asahi/g15/glue.c b/drivers/gpu/drm/asahi/g15/glue.c new file mode 100644 index 00000000000000..662c9c8258e213 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/glue.c @@ -0,0 +1,278 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * G15 (T6030/T6031, M3 Pro/Max) helpers that have no Rust bindings: static inlines, + * macros and THIS_MODULE. Built only with CONFIG_DRM_ASAHI_G15. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void asahi_g15_sha256(const u8 *data, size_t len, u8 *out); +bool asahi_g15_board(void); +bool asahi_g15_machine(const char *compatible); +void asahi_g15_hold_power(struct device *dev); +void asahi_g15_release_power(struct device *dev); +void asahi_g15_module_get(void); +void asahi_g15_reprobe(void); +int asahi_g15_adt_phram(u64 *start, u64 *size); +bool asahi_g15_ram_disjoint(u64 start, u64 size); +bool asahi_g15_ram_within(u64 start, u64 size); +unsigned int asahi_g15_memory_mode(u64 start, u64 size); +void __iomem *asahi_g15_ioremap_wc(u64 start, size_t size); +bool asahi_g15_dma_coherent(struct device *dev); +int asahi_g15_pmp_prepare(struct device *dev); +int asahi_g15_pmp_get(struct device *dev); +void asahi_g15_pmp_put(struct device *dev); +bool asahi_g15_reserved_uat(u32 index, u64 start, u64 size); + +/* + * The maintained m1n1 handoff keeps these four UAT regions in the linear map. + * Require the exact enabled reserved-memory owner, in addition to the ADT + * bounds/size/disjointness and per-page PageReserved checks in admission. + */ +bool asahi_g15_reserved_uat(u32 index, u64 start, u64 size) +{ + static const char *const paths[] = { + "/reserved-memory/uat-ttbs", + "/reserved-memory/uat-pagetables", + "/reserved-memory/uat-handoff", + "/reserved-memory/uat-pagetables-l2", + }; + struct device_node *np; + struct resource res; + bool match; + + if (index >= ARRAY_SIZE(paths)) + return false; + np = of_find_node_by_path(paths[index]); + match = np && of_device_is_available(np) && + !of_property_read_bool(np, "reusable") && + !of_get_address(np, 1, NULL, NULL) && + !of_address_to_resource(np, 0, &res) && + res.start == start && resource_size(&res) == size; + of_node_put(np); + return match; +} + +/* + * Keep a single PMP RTKit owner. The maintained bridge serializes requests, + * waits for supplier readiness and acknowledgement, and latches lost replies. + * The GPU retains both its module and supplier dependency until reboot. + */ +int asahi_g15_pmp_prepare(struct device *dev) +{ + int ret; + + if (!asahi_g15_board() || !dev->of_node || + !of_device_is_compatible(dev->of_node, "apple,agx-t6030")) + return -ENODEV; + /* DISP ACK alone does not prove the native DRM component set is up. */ + /* The direct import waits for the display module to become LIVE; a + * symbol_get during its probe could defer without any post-LIVE retry. + */ + ret = apple_drm_t6030_link_device(dev); + if (ret) + return ret; + return apple_pmp_link_device(dev); +} + +int asahi_g15_pmp_get(struct device *dev) +{ + if (!asahi_g15_board() || !dev->of_node || + !of_device_is_compatible(dev->of_node, "apple,agx-t6030")) + return -ENODEV; + return apple_pmp_set_device_power(0x0f, 5, 1); + +} + +/* + * Give back the vote of asahi_g15_pmp_get() after a start that failed before + * the firmware was touched. The full M3 stack's J514S bridge has no release: + * its vote stays, as before. + */ +void asahi_g15_pmp_put(struct device *dev) +{ + int ret = apple_pmp_set_device_power(0x0f, 5, 0); + + if (ret) + dev_warn(dev, "G15: PMP AGX vote release failed: %d\n", ret); + +} + +/* SHA-256 of the firmware TEXT and the board templates. */ +void asahi_g15_sha256(const u8 *data, size_t len, u8 *out) +{ + sha256(data, len, out); +} + +/* Whether this is a J514S/J516S T6030 board. */ +bool asahi_g15_board(void) +{ + return of_machine_is_compatible("apple,t6030") && + (of_machine_is_compatible("apple,j514s") || + of_machine_is_compatible("apple,j516s")); +} + +/* Whether the machine carries this compatible (of_machine_is_compatible()). */ +bool asahi_g15_machine(const char *compatible) +{ + return of_machine_is_compatible(compatible) > 0; +} + +/* + * Keep the GFX domain powered for the whole (retained) session, like the + * firmware session itself; released only by a start that failed before the + * firmware was touched (asahi_g15_release_power()). + */ +void asahi_g15_hold_power(struct device *dev) +{ + pm_runtime_get_noresume(dev); + pm_runtime_set_active(dev); + pm_runtime_enable(dev); +} + +/* + * Give the hold of asahi_g15_hold_power() back: the start failed before + * anything firmware-visible was written, so the session is not retained. + * Only where the AGX vote is given back as well (asahi_g15_pmp_put()): the + * full M3 stack's J514S bridge keeps its vote, and with it the hold stays. + */ +void asahi_g15_release_power(struct device *dev) +{ + pm_runtime_put_noidle(dev); + pm_runtime_disable(dev); + pm_runtime_set_suspended(dev); + +} + +/* Pin this module until reboot. */ +void asahi_g15_module_get(void) +{ + __module_get(THIS_MODULE); +} + +/* + * The boot loader's phram "adt" export: the first /reserved-memory child + * compatible with "phram" and labelled "adt". + */ +int asahi_g15_adt_phram(u64 *start, u64 *size) +{ + struct device_node *rmem, *np; + struct resource res; + int ret = -ENODEV; + + rmem = of_find_node_by_path("/reserved-memory"); + for_each_child_of_node(rmem, np) { + const char *label; + + if (of_device_is_compatible(np, "phram") && + !of_property_read_string(np, "label", &label) && !strcmp(label, "adt") && + !of_address_to_resource(np, 0, &res)) { + of_node_put(np); + ret = 0; + break; + } + } + of_node_put(rmem); + if (ret) + return ret; + *start = res.start; + *size = resource_size(&res); + return 0; +} + +/* The range is disjoint from System RAM (ADT region admission). */ +bool asahi_g15_ram_disjoint(u64 start, u64 size) +{ + return region_intersects(start, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) == + REGION_DISJOINT; +} + +/* + * Whether DMA mappings of the device skip cache maintenance. The G15 firmware + * objects rely on the DMA mapping cleaning their pages to the point of + * coherency, so the device must not be DMA-coherent. + */ +bool asahi_g15_dma_coherent(struct device *dev) +{ + return dev_is_dma_coherent(dev); +} + +/* + * Every page must be valid, System RAM and still reserved from the allocator. + * REGION_INTERSECTS alone also accepts RAM mixed with undefined memory holes. + */ +bool asahi_g15_ram_within(u64 start, u64 size) +{ + u64 end, pa; + + if (!size || !IS_ALIGNED(start, PAGE_SIZE) || + !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) + return false; + for (pa = start; pa < end; pa += PAGE_SIZE) { + unsigned long pfn = PHYS_PFN(pa); + + if (!pfn_valid(pfn) || !page_is_ram(pfn) || + !PageReserved(pfn_to_page(pfn))) + return false; + } + return true; +} + +/* One classification for every adopted-UAT and firmware-region CPU mapping. */ +unsigned int asahi_g15_memory_mode(u64 start, u64 size) +{ + u64 end; + + if (!size || !IS_ALIGNED(start, PAGE_SIZE) || + !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) + return 0; + if (asahi_g15_ram_within(start, size)) + return MEMREMAP_WB; + if (asahi_g15_ram_disjoint(start, size)) + return MEMREMAP_WC; + return 0; +} + +/* The inherited RTKit buffer inside firmware DATA. */ +void __iomem *asahi_g15_ioremap_wc(u64 start, size_t size) +{ + return ioremap_wc(start, size); +} + +/* + * Called only by the final infallible DriverModule initializer, after both + * platform registrations have completed. driver_find() returns a borrowed + * pointer, not an owned reference. The pinned registration is still owned by + * DriverModule throughout this call; module exit cannot race its initialization. + * No put_driver() is appropriate. A failed attach must not fail module init: + * another device in this pass may already have started retained firmware. + */ +void asahi_g15_reprobe(void) +{ + const struct device_driver *drv; + int ret; + + drv = driver_find("asahi-g15", &platform_bus_type); + if (!drv) { + pr_err("asahi-g15: registered adapter not found for activation\n"); + return; + } + ret = driver_attach(drv); + if (ret) + pr_err("asahi-g15: activation attach failed: %d\n", ret); +} diff --git a/drivers/gpu/drm/asahi/g15/graph.rs b/drivers/gpu/drm/asahi/g15/graph.rs new file mode 100644 index 00000000000000..9a62f25f19a63b --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/graph.rs @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The persistent compute and render graphs. +//! +//! The compute graph holds 22 x 4 MiB compute pools, the freelist (every pool's pages), the pool +//! table, the manager, scheduling context, notifier, threshold, job list, queue info/state, ring, +//! queue scratch and the user and firmware stamps. The render graph holds the render queues, +//! scheduling context, notifier, threshold, job list, the empty legacy record and InitBM. The +//! compute slots and the render pass slots are [`super::slots`]; the render UMA/PB allocators +//! and their spare set are [`super::pools`], initialized from [`Firmware::init_graphs`]. +//! Classes per [`super::hw::tuning`]. Graph buffers with a client GVA are aliased into every +//! user VM ([`Request::client`]). +//! +//! The compute queue's Globals +0x9b0 = 0 (unchanged-work monitor off) is written with a waited +//! DEVCTL 0x13 before the queue is first exposed. + +use kernel::{ + device, + prelude::*, + sync::{aref::ARef, Arc}, +}; + +use super::channel::Channel; +use super::fw::graph::{job_list, manager, notifier, pools, qinfo, qinfo_row2, qstate, sched_ctx}; +use super::hw::{client, engine, pte, sizes, tuning}; +use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::Firmware; +use crate::driver::AsahiDrmDevice as AsahiDevice; + +/// Firmware class of firmware-maintained command objects. +pub(crate) const fn cmd_fw() -> Class { + if tuning::FW_CACHED { + Class::FwCached + } else { + Class::Fw + } +} + +/// The firmware + GPU twin of [`cmd_fw`]. +pub(crate) const fn cmd_shared() -> Class { + if tuning::FW_CACHED { + Class::SharedCached + } else { + Class::Shared + } +} + +/// Notifiers: firmware-only, cached as selected by `tuning::NOTIFIER_CACHED` (bit 0 compute, +/// bit 1 render). +pub(crate) const fn notifier_class(bit: u32) -> Class { + if tuning::NOTIFIER_CACHED & bit != 0 { + Class::FwCached + } else { + Class::Fw + } +} + +/// Allocator managers: their index-2 class or its AttrIndex 0 twin. +pub(crate) const fn manager_class(class: Class) -> Class { + if !tuning::MANAGER_CACHED { + return class; + } + match class { + Class::Shared => Class::SharedCached, + _ => Class::FwCached, + } +} + +/// Queue scratch: firmware-private cached, or the shared index-2 class. +pub(crate) const fn queue_scratch() -> Class { + if tuning::FW_CACHED { + Class::FwCached + } else { + Class::Shared + } +} + +/// A client alias: the GVA of the page holding the payload and the leaf word. +#[derive(Copy, Clone)] +pub(crate) struct Client { + pub(crate) page: u64, + pub(crate) leaf: u64, +} + +impl Client { + /// GPU-only NC RW. + pub(crate) const fn nc(page: u64) -> Option { + Some(Self { + page, + leaf: pte::LEAF_NC, + }) + } + + /// GPU-cached. + pub(crate) const fn cached(page: u64) -> Option { + Some(Self { + page, + leaf: pte::LEAF_CACHED, + }) + } +} + +/// Allocates a zeroed firmware object of `size` payload bytes at `offset` in its first page, +/// mapped in the firmware window with `class`, optionally aliased in every user VM and, with +/// `lower`, in the context-0 lower tree at the client page. +pub(crate) fn alloc( + objects: &mut Objects, + size: usize, + class: Class, + client: Option, + offset: usize, + lower: bool, +) -> Result> { + objects.alloc(Request { + size, + class, + placement: Placement::Anywhere, + offset, + client: client.map(|c| (c.page, c.leaf)), + lower: if lower { client.map(|c| c.page) } else { None }, + cpu: true, + }) +} + +/// The compute graph, without its slots. +pub(crate) struct ComputeGraph { + /// The empty legacy record: allocated for the firmware's layout, never written. + _legacy: Arc, + pub(crate) pools: KVec>, + pub(crate) freelist: Arc, + pub(crate) pool_table: Arc, + pub(crate) manager: Arc, + pub(crate) counter: Arc, + pub(crate) sched_ctx: Arc, + pub(crate) notifier: Arc, + pub(crate) threshold: Arc, + pub(crate) job_list: Arc, + pub(crate) qinfo: Arc, + pub(crate) qstate: Arc, + pub(crate) ring: Arc, + pub(crate) qscratch: Arc, + pub(crate) user_stamp: Arc, + pub(crate) fw_stamp: Arc, +} + +impl ComputeGraph { + /// Allocates the compute graph objects. + fn new(objects: &mut Objects) -> Result { + let (sh, fw) = (Class::Shared, Class::Fw); + let o = objects; + + let legacy = alloc(o, 0x4000, sh, None, 0, false)?; + let mut pools = KVec::with_capacity(sizes::POOLS, GFP_KERNEL)?; + for i in 0..sizes::POOLS as u64 { + let pool = alloc( + o, + sizes::POOL_SIZE as usize, + sh, + Client::nc(client::pool(i)), + 0, + false, + )?; + pools.push(pool, GFP_KERNEL)?; + } + Ok(Self { + _legacy: legacy, + pools, + freelist: alloc(o, 0x400000, sh, Client::nc(client::FREELIST), 0, false)?, + pool_table: alloc( + o, + 0x1000, + sh, + Client::nc(client::POOL_TABLE_PAGE), + client::POOL_TABLE_OFF as usize, + false, + )?, + manager: alloc(o, manager::SIZE, manager_class(sh), None, 0, false)?, + counter: alloc(o, 0x40, sh, None, 0, false)?, + sched_ctx: alloc(o, sched_ctx::SIZE, cmd_fw(), None, 0, false)?, + notifier: alloc(o, notifier::SIZE, notifier_class(1), None, 0, false)?, + threshold: alloc(o, 4, fw, None, 0, false)?, + job_list: alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?, + qinfo: alloc(o, qinfo::SIZE, cmd_fw(), None, 0, false)?, + qstate: alloc(o, qstate::SIZE, fw, None, 0, false)?, + ring: alloc(o, sizes::QUEUE_CAP as usize * 8, fw, None, 0, false)?, + qscratch: alloc(o, 0x40000, queue_scratch(), None, 0, false)?, + user_stamp: alloc(o, 4, sh, None, 0, false)?, + fw_stamp: alloc(o, 4, sh, None, 0, false)?, + }) + } + + /// Initial contents; the firmware owns them afterwards. The slots are scrubbed by + /// [`super::slots`]. + fn init(&self) -> Result { + let mut entry = 0u64; + + // Freelist: every 4 MiB pool in 0x1000 units. + for pool in self.pools.iter().take(pools::SEEDED_POOLS) { + let gva = pool.gva.ok_or(EINVAL)?; + let mut off = 0; + while off < sizes::POOL_SIZE { + self.freelist.w64(8 * entry as usize, gva + off)?; + entry += 1; + off += pools::SEED_BYTES; + } + } + for (k, pool) in self.pools.iter().enumerate() { + let gva = pool.gva.ok_or(EINVAL)?; + self.pool_table + .w64(pools::TABLE_STRIDE * k, gva | pools::TABLE_VALID)?; + } + let m = &self.manager; + m.w32(manager::ID, manager::COMPUTE_ID)?; + m.w32(manager::INDEX, manager::COMPUTE_INDEX)?; + m.w32(manager::ONE, 1)?; + m.w64(manager::FREELIST, self.freelist.gva.ok_or(EINVAL)?)?; + m.w32(manager::UNK_1C, manager::UNK_1C_VALUE)?; + m.w32(manager::SEEDS_A, pools::SEEDS)?; + m.w32(manager::SEEDS_B, pools::SEEDS)?; + m.w64(manager::POOL_TABLE, self.pool_table.gva.ok_or(EINVAL)?)?; + m.w32(manager::UNK_44, manager::UNK_44_VALUE)?; + m.w64(manager::COUNTER, self.counter.va)?; + self.counter.w32(0, 1)?; + + init_sched_ctx(&self.sched_ctx)?; + init_notifier(&self.notifier, &self.threshold)?; + self.job_list.w64(job_list::SELF, self.job_list.va)?; + self.threshold.w32(0, 1)?; + + let q = &self.qinfo; + q.w64(qinfo::STATE, self.qstate.va)?; + q.w64(qinfo::RING, self.ring.va)?; + q.w64(qinfo::JOB_LIST, self.job_list.va)?; + q.w64(qinfo::SCRATCH, self.qscratch.va)?; + q.w32(qinfo::UNK_2C, 0xffffffff)?; + q.w64(qinfo_row2::MASK, qinfo_row2::ROW0_MASK_VALUE)?; + q.w32(qinfo_row2::UNK_40, 1)?; + q.w32(qinfo_row2::UNK_48, 1)?; + if tuning::COMPUTE_QUEUE_CLASS == 2 { + // Row 2: 2, 2, ffff000000000000, 0, 0, 2. + q.w32(qinfo_row2::CLASS, 2)?; + q.w32(qinfo_row2::CLASS_B, 2)?; + q.w64(qinfo_row2::MASK, qinfo_row2::MASK_VALUE)?; + q.w32(qinfo_row2::UNK_40, 0)?; + q.w32(qinfo_row2::UNK_44, 0)?; + q.w32(qinfo_row2::UNK_48, 2)?; + } + q.w32(qinfo::UNK_4C, 0xffffffff)?; + q.w32(qinfo::UUID, engine::COMPUTE_UUID)?; + q.w64(qinfo::SCHED_CTX, self.sched_ctx.va)?; + q.w64(qinfo::UNK_AC, 4)?; + self.qstate.w32(qstate::CAP, sizes::QUEUE_CAP)?; + + self.user_stamp.w32(0, engine::COMPUTE_SEED)?; + self.fw_stamp.w32(0, 0) + } +} + +/// The render graph, without the pass slots, the clustering buffers and the render +/// allocators. +pub(crate) struct RenderGraph { + /// TA (0) and FS (1) queues. + pub(crate) qinfo: [Arc; 2], + pub(crate) qstate: [Arc; 2], + pub(crate) ring: [Arc; 2], + pub(crate) qscratch: [Arc; 2], + pub(crate) user_stamp: [Arc; 2], + pub(crate) fw_stamp: [Arc; 2], + pub(crate) sched_ctx: Arc, + pub(crate) notifier: Arc, + pub(crate) threshold: Arc, + pub(crate) job_list: Arc, + pub(crate) legacy_empty: Arc, + pub(crate) initbm: Arc, +} + +/// One render engine's queue objects, allocated together. +struct RenderQueue { + qinfo: Arc, + qstate: Arc, + ring: Arc, + qscratch: Arc, + user_stamp: Arc, + fw_stamp: Arc, +} + +impl RenderQueue { + fn new(o: &mut Objects) -> Result { + Ok(Self { + qinfo: alloc(o, qinfo::SIZE, cmd_fw(), None, 0, false)?, + qstate: alloc(o, qstate::SIZE, Class::Fw, None, 0, false)?, + ring: alloc(o, sizes::QUEUE_CAP as usize * 8, Class::Fw, None, 0, false)?, + qscratch: alloc(o, 0x40000, queue_scratch(), None, 0, false)?, + user_stamp: alloc(o, 4, Class::Shared, None, 0, false)?, + fw_stamp: alloc(o, 4, Class::Shared, None, 0, false)?, + }) + } +} + +impl RenderGraph { + /// Allocates the render graph objects. + fn new(o: &mut Objects) -> Result { + let [ta, fs] = [RenderQueue::new(o)?, RenderQueue::new(o)?]; + let sched_ctx = alloc(o, sched_ctx::SIZE, cmd_fw(), None, 0, false)?; + let notifier = alloc(o, notifier::SIZE, notifier_class(2), None, 0, false)?; + let threshold = alloc(o, 4, Class::Fw, None, 0, false)?; + let job_list = alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?; + let legacy_empty = alloc(o, 0x40, Class::Shared, None, 0, false)?; + let initbm = alloc(o, super::fw::work::initbm::SIZE, cmd_fw(), None, 0, false)?; + Ok(Self { + qinfo: [ta.qinfo, fs.qinfo], + qstate: [ta.qstate, fs.qstate], + ring: [ta.ring, fs.ring], + qscratch: [ta.qscratch, fs.qscratch], + user_stamp: [ta.user_stamp, fs.user_stamp], + fw_stamp: [ta.fw_stamp, fs.fw_stamp], + sched_ctx, + notifier, + threshold, + job_list, + legacy_empty, + initbm, + }) + } + + /// Initial contents; the render allocators are initialized separately. + fn init(&self) -> Result { + let uuid = [engine::TA_UUID, engine::FS_UUID]; + let seed = [engine::TA_SEED, engine::FS_SEED]; + + for e in 0..2 { + let q = &self.qinfo[e]; + q.w64(qinfo::STATE, self.qstate[e].va)?; + q.w64(qinfo::RING, self.ring[e].va)?; + q.w64(qinfo::JOB_LIST, self.job_list.va)?; + q.w64(qinfo::SCRATCH, self.qscratch[e].va)?; + q.w32(qinfo::UNK_2C, 0xffffffff)?; + if tuning::RENDER_QUEUE_CLASS == 2 { + // Recognized row 2: class/policy 2, mask, +0x40/+0x44 0. + q.w32(qinfo_row2::CLASS, 2)?; + q.w32(qinfo_row2::CLASS_B, 2)?; + q.w64(qinfo_row2::MASK, qinfo_row2::MASK_VALUE)?; + q.w32(qinfo_row2::UNK_48, 2)?; + } else { + q.w64(qinfo_row2::MASK, qinfo_row2::ROW0_MASK_VALUE)?; + q.w32(qinfo_row2::UNK_40, 1)?; + q.w32(qinfo_row2::UNK_48, 1)?; + } + q.w32(qinfo::UNK_4C, 0xffffffff)?; + q.w32(qinfo::UUID, uuid[e])?; + q.w64(qinfo::SCHED_CTX, self.sched_ctx.va)?; + q.w64(qinfo::UNK_AC, 4)?; + self.qstate[e].w32(qstate::CAP, sizes::QUEUE_CAP)?; + self.ring[e].fill(0, 0xcc, sizes::QUEUE_CAP as usize * 8)?; + self.user_stamp[e].w32(0, seed[e])?; + self.fw_stamp[e].w32(0, seed[e])?; + } + init_sched_ctx(&self.sched_ctx)?; + init_notifier(&self.notifier, &self.threshold)?; + self.job_list.w64(job_list::SELF, self.job_list.va)?; + self.threshold.w32(0, 2) + } +} + +/// Scheduling context initial contents, shared by both graphs. +fn init_sched_ctx(s: &FwObject) -> Result { + s.fill(0x00, 0xff, 2)?; + s.fill(0x05, 0x01, 1)?; + s.fill(0x1e, 0xff, 1)?; + s.fill(0x23, 0x02, 1) +} + +/// Notifier initial contents: the only host stores the notifier ever gets. +fn init_notifier(n: &FwObject, threshold: &FwObject) -> Result { + n.w64(notifier::THRESHOLD, threshold.va)?; + n.w32(notifier::UNK_10, notifier::UNK_10_VALUE)?; + n.fill(notifier::MASK, 0xff, 8) +} + +/// The compute and render graph objects. +pub(crate) struct Graphs { + /// The GPU device, for the engine's log messages. + pub(crate) dev: ARef, + pub(crate) compute: ComputeGraph, + pub(crate) render: RenderGraph, +} + +impl Graphs { + /// Allocates both graphs. + pub(crate) fn new(dev: &AsahiDevice, objects: &mut Objects) -> Result { + Ok(Self { + dev: dev.as_ref().as_ref().into(), + compute: ComputeGraph::new(objects)?, + render: RenderGraph::new(objects)?, + }) + } +} + +impl Firmware { + /// Initializes both graphs, the slots and the render allocators, then turns the compute + /// monitor off before the queues are first exposed. + pub(crate) fn init_graphs(&mut self) -> Result { + // TA/FS/compute channels must start empty. + for ch in [Channel::Ta, Channel::Fs, Channel::Compute] { + if self.channels.read(ch)? != 0 || self.channels.write_cell(ch)? != 0 { + return Err(Error::from_errno(-(kernel::bindings::EPROTO as i32))); + } + } + self.graph.compute.init()?; + self.slots.init()?; + super::engine::wmb(); + self.graph.render.init()?; + self.init_render_pools(false)?; + // New firmware and context-0 translations before any reference. + super::uat::tlbi_all(); + dev_info!( + self.graph.dev.as_ref(), + "G15: compute graph: work {:#x}/{:#x} pools {:#x} freelist {:#x} table {:#x}\n", + self.slots.scrub.compute[0].work.va, + self.slots.scrub.compute[0].work.gva.unwrap_or(0), + self.graph.compute.pools[0].gva.unwrap_or(0), + self.graph.compute.freelist.gva.unwrap_or(0), + self.graph.compute.pool_table.gva.unwrap_or(0) + ); + if tuning::COMPUTE_QUEUE_CLASS == 2 { + // Class-2 compute profile: the unchanged-work compute monitor (Globals +0x9b0) + // off before the queue's first exposure. + self.compute_monitor_off()?; + } + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/g15/hw.rs b/drivers/gpu/drm/asahi/g15/hw.rs new file mode 100644 index 00000000000000..d566a54953e072 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/hw.rs @@ -0,0 +1,590 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G15 hardware and firmware-ABI constants (layout values are shared by several modules; change +//! one only together with its users). The qualified T6030 values are the module-level +//! constants; what differs per SoC is a [`super::Config`] row ([`t6030`], [`t6031`]). The tuned +//! policy values are in [`tuning`]. + +use core::ops::Range; + +pub(crate) mod t6031; + +/// Identification register values of a qualified G15S. +pub(crate) struct HwId { + /// SGX identity word (`sgx + 0xd04000`). + pub(crate) version: u32, + /// SGX layout word (`sgx + 0xd04010`). + pub(crate) counts: u32, +} + +/// A qualified GPU firmware build, identified by its loaded TEXT. +pub(crate) struct FirmwareBuild { + pub(crate) name: &'static str, + /// Optional board restriction in addition to the SoC admission. + pub(crate) machine: Option<&'static kernel::str::CStr>, + pub(crate) text_size: u64, + pub(crate) data_size: u64, + /// Offset of the GKTS marker in TEXT; the 8 entropy bytes after it are zeroed before hashing. + pub(crate) marker: u32, + pub(crate) text_sha256: [u8; 32], +} + +/// Where a SoC's GPU regions, firmware segments and performance states come from, and how its +/// GPU is powered. +#[derive(Copy, Clone, PartialEq, Eq)] +pub(crate) enum Platform { + /// T6030: the boot loader's ADT export ([`super::adt`]), a GPU node synthesized by the PMP + /// handoff, and the PMP AGX vote through the J514S supplier. + AdtWithPmp, + /// The GPU node of the kernel device tree, filled by the boot loader (regions, firmware + /// segments and operating points); the GPU is powered by its power domain alone. + DeviceTree, +} + +/// The source of the board images (HardwareData, Globals, Power) of a SoC. +#[derive(Copy, Clone, PartialEq, Eq)] +pub(crate) enum Board { + /// The hash-checked T6030 templates ([`super::board`]). + Templates, + /// The three images built from the device tree ([`super::board::record`], + /// [`super::board::device_tree`]) and cross-checked against a firmware file holding the + /// machine's own ([`super::board::blob`], pinned by its SHA-256), which also supplies the + /// record's words the device tree does not carry ([`super::board::record::FROM_FILE`]); a + /// difference refuses admission, before any firmware is touched. + Blob { + name: &'static kernel::str::CStr, + sha256: [u8; 32], + }, + /// No board data: admission refuses the SoC before anything firmware-visible. + None, +} + +/// Per-SoC placement and size of the initdata objects that differ between G15 firmware +/// builds; everything else keeps the canonical [`va`] values. +pub(crate) struct Layout { + /// Root object version word. + pub(crate) root_magic: u64, + /// HardwareData VA, size, ASC-cached prefix (`None`: the whole object), and the offset of + /// the fourth HardwareDataB view (fault information). + pub(crate) hwdata_va: u64, + pub(crate) hwdata_size: usize, + pub(crate) hwdata_cached: Option, + pub(crate) hwdata_view: usize, + /// HardwareDataB IOMapping records. + pub(crate) iomaps: &'static [IoMap], + /// For a record built from the device tree ([`super::board::record`]): per IOMapping + /// record, in `iomaps` order, the mapped bytes, the element bytes and whether the firmware + /// may write the window; and the unmapped slots whose flag word is nevertheless 1. + pub(crate) record_slots: &'static [(u32, u32, bool)], + pub(crate) record_empty_writable: &'static [u8], +} + +/// Compute command register values that scale with the cluster count. +pub(crate) struct ComputeRegs { + /// Offset of the four saved-state pointers in the preemption buffer. + pub(crate) tail: u64, + /// UMA PTC (0xa599) and DUPM (0xd411). + pub(crate) ptc: u64, + pub(crate) dupm: u64, + /// The 0x1a0e9 word. + pub(crate) reg_1a0e9: u64, + /// Encode every command the way the first command of a fresh queue is encoded: zero + /// saved-state pointers and zero 0x12091/0x101d9. + pub(crate) fresh: bool, +} + +/// The T6030 configuration. +pub(crate) mod t6030 { + use super::super::Config; + use super::{ComputeRegs, FirmwareBuild, HwId, Layout}; + + /// The qualified graph: the canonical VAs and sizes of [`super::va`] and + /// [`super::super::fw::initdata`]. + pub(crate) const LAYOUT: Layout = Layout { + root_magic: super::super::fw::initdata::root::MAGIC, + hwdata_va: super::va::HWDATA, + hwdata_size: super::super::fw::initdata::hwdata::SIZE, + hwdata_cached: Some(super::super::fw::initdata::hwdata::CACHED), + hwdata_view: super::super::fw::initdata::hwdata::FAULT_INFO, + iomaps: &super::IOMAPS, + record_slots: &[], + record_empty_writable: &[], + }; + + /// The two-cluster compute register values. + pub(crate) const COMPUTE: ComputeRegs = ComputeRegs { + tail: 0x1480, + ptc: 0x13200400020, + dupm: 0x200000001, + reg_1a0e9: 8, + fresh: false, + }; + + pub(crate) const CONFIG: Config = Config { + name: "T6030 G15S", + chip_id: 0x6030, + gpu_variant: crate::hw::GpuVariant::S, + gpu_revision: 0x11, + uat_ias: 42, + uat_oas: 42, + num_clusters: 2, + num_cores_per_cluster: 10, + hw_ids: &[HwId { + version: 0x07031100, + counts: 0x00110209, + }], + firmware: &[ + FirmwareBuild { + name: "macOS 14.7-14.8.x stub firmware (iBoot-10151.140.19.700.2)", + machine: None, + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0x11, 0xe4, 0x9f, 0x75, 0x0b, 0x67, 0x1a, 0x2b, 0x13, 0xd0, 0x92, 0xdb, 0x1c, 0xbc, + 0xa3, 0xa8, 0x77, 0x55, 0x86, 0xd6, 0xb1, 0xe3, 0xaa, 0xe8, 0xa6, 0xa4, 0x64, 0xa7, + 0x80, 0x02, 0x93, 0xd5, + ], + }, + // The maintained J516S runtime already identifies this B0 image by + // UUID dbf37c40-ead5-3760-9441-995018782955 and uses the same + // 0x0c08e21e83800490 InitData ABI. Pin its complete measured TEXT + // digest here, rather than enabling the bring-up prefix override. + FirmwareBuild { + name: "J516S B0 RTKit-2419.140.12 (maintained 14.x handoff)", + machine: Some(kernel::c_str!("apple,j516s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0xda, 0x26, 0xec, 0xca, 0xb1, 0xf8, 0x59, 0x8d, + 0xa8, 0x0c, 0x85, 0x5e, 0xca, 0x91, 0x65, 0x20, + 0x40, 0x6d, 0x1d, 0x06, 0x70, 0xf1, 0xd4, 0x70, + 0xe7, 0x9b, 0xb9, 0xb0, 0x22, 0x09, 0xdb, 0x53, + ], + }, + ], + machine: kernel::c_str!("apple,t6030"), + platform: super::Platform::AdtWithPmp, + layout: &LAYOUT, + board: super::Board::Templates, + compute: COMPUTE, + }; +} + +/// User VA range reported as `vm_start..vm_end`. Not the full 42-bit range: the userspace VA +/// layout on G15S was qualified with this end. +pub(crate) const USER_RANGE: Range = 0x4000..0x2ffffff8000; + +/// Bits per cluster in the enabled-core mask (`sgx + 0xe01500`). +pub(crate) const CLUSTER_BITS: u32 = 10; + +/// UAT page size. +pub(crate) const PAGE: u64 = 0x4000; +/// Physical address bits of UAT leaves. +pub(crate) const PA_MASK: u64 = 0x3ffffffc000; + +/// Firmware upper half: root[0..1] are firmware-owned, root[2] is the host window. +pub(crate) const UPPER: u64 = 0xfffffc0000000000; +pub(crate) const HOST: u64 = 0xfffffc2000000000; +pub(crate) const HOST_SIZE: u64 = 0x1000000000; + +/// Firmware UAT leaf words. Shared-layer `Prot` values for them are built with +/// `mmu::Prot::from_pte` and must round-trip to these exact words. +pub(crate) mod pte { + /// Firmware-only shared RW data, AttrIndex 2 (inner non-cacheable for the ASC). + pub(crate) const FW: u64 = 0x00c000000000044b; + /// Firmware + GPU shared, AttrIndex 2. + pub(crate) const SHARED: u64 = 0x00e000000000040b; + /// The same two classes with AttrIndex 0 (inner+outer write-back for the ASC). + pub(crate) const FW_CACHED: u64 = 0x00c0000000000443; + pub(crate) const SHARED_CACHED: u64 = 0x00e0000000000403; + /// Firmware device RW. + pub(crate) const MMIO: u64 = 0x00c0000000000447; + /// Table descriptor bits. + pub(crate) const TABLE: u64 = 3; + /// Context-0 lower work alias: GPU RW NC, non-global. + pub(crate) const LOWER: u64 = 0x00c0000000000c8b; + /// Client (user VM) driver leaves: NC, cached, PB list. + pub(crate) const LEAF_NC: u64 = 0x00c0000000000c8b; + pub(crate) const LEAF_CACHED: u64 = 0x00c0000000000c83; + pub(crate) const LEAF_PB_LIST: u64 = 0x00e0000000000c03; +} + +/// PPL handoff magic. +pub(crate) const PPL_MAGIC: u64 = 0x4b1d000000000002; + +/// UAT handoff region sizes of this firmware ABI (TTBAT page, TTBAT tables (the firmware kernel +/// root), PPL handoff page, shared L2 page); the addresses come from the ADT. +pub(crate) const TTBS_SIZE: u64 = 0x4000; +pub(crate) const TABLES_SIZE: u64 = 0x40000; +pub(crate) const HANDOFF_SIZE: u64 = 0x4000; +pub(crate) const SHARED_L2_SIZE: u64 = 0x4000; + +/// Canonical initdata object VAs of the qualified build. +pub(crate) mod va { + pub(crate) const ROOT: u64 = 0xfffffc204062ff40; + pub(crate) const REGION_A: u64 = 0xfffffc2040670000; + pub(crate) const RUNTIME: u64 = 0xfffffc20406b7b4d; + pub(crate) const HWDATA: u64 = 0xfffffc20406fb5fc; + pub(crate) const PAIR: u64 = 0xfffffc2040747f00; + pub(crate) const SMALL: u64 = 0xfffffc204078bff0; + pub(crate) const C0: u64 = 0xfffffc2070003000; + pub(crate) const C1: u64 = 0xfffffc2070008000; + pub(crate) const C3: u64 = 0xfffffc2070010000; + pub(crate) const GLOBALS: u64 = 0xfffffc20407cc204; + pub(crate) const POWER: u64 = 0xfffffc204081370c; + pub(crate) const CONTROL: u64 = 0xfffffc20003bbc30; + pub(crate) const FLAGS: u64 = 0xfffffc2040857fc0; + pub(crate) const DEVCTL_STATE: u64 = 0xfffffc2040333fd0; + pub(crate) const DEVCTL_RING: u64 = 0xfffffc2000330800; + pub(crate) const EVENT_STATE: u64 = 0xfffffc2040377fd0; + pub(crate) const EVENT_RING: u64 = 0xfffffc20403b8800; + pub(crate) const LOG_STATE: u64 = 0xfffffc20403ffee0; + pub(crate) const LOG_RING: u64 = 0xfffffc2040443000; + pub(crate) const TRACE_STATE: u64 = 0xfffffc20404d7fd0; + pub(crate) const TRACE_RING: u64 = 0xfffffc2040519000; + pub(crate) const STATS_STATE: u64 = 0xfffffc2040563fd0; + pub(crate) const STATS_RING: u64 = 0xfffffc20405a4000; + pub(crate) const FWCTL_STATE: u64 = 0xfffffc20405ebfd0; + pub(crate) const FWCTL_RING: u64 = 0xfffffc2000376c00; + /// Firmware timestamp arena (64 MiB). + pub(crate) const TIMESTAMPS: u64 = 0xfffffc2ffc000000; + pub(crate) const TIMESTAMPS_SIZE: u64 = 0x4000000; + /// Firmware VA allocator window for backend objects. + pub(crate) const FW_ALLOC: core::ops::Range = 0xfffffc2d00000000..0xfffffc2e00000000; + + /// State block of submit channel `i` (12 channels). + pub(crate) const fn ch_state(i: u64) -> u64 { + 0xfffffc2040003fd0 + i * 0x44000 + } + /// Ring of submit channel `i`. + pub(crate) const fn ch_ring(i: u64) -> u64 { + 0xfffffc2000002800 + i * 0x44000 + } + + /// Scratch page of the boot-time PTE class self-check (host window; never published). + pub(crate) const SELF_CHECK: u64 = 0xfffffc2ff8000000; + /// Scratch page of the PTE self-check in the context-0 lower half (never published). + pub(crate) const SELF_CHECK_LOWER: u64 = 0x7ff0000000; +} + +/// Firmware channels and rings of the initdata graph. +pub(crate) mod rings { + /// Submit channels allocated (TA, FS and compute are used). + pub(crate) const CHANNELS: u64 = 12; + /// Bytes of a channel state block. + pub(crate) const STATE_SIZE: usize = 0x30; + /// Submit channel ring: 256 x 0x18. + pub(crate) const CHANNEL_RING_SIZE: usize = 0x1800; + /// Device-control and event rings: 256 x 0x38. + pub(crate) const DEVCTL_RING_SIZE: usize = 0x3800; + pub(crate) const EVENT_RING_SIZE: usize = 0x3800; + /// Six log sub-rings: their state blocks and their rings. + pub(crate) const LOG_RINGS: usize = 6; + pub(crate) const LOG_STATE_SIZE: usize = 0x120; + pub(crate) const LOG_RING_SIZE: usize = 0x51000; + pub(crate) const TRACE_RING_SIZE: usize = 0x7000; + pub(crate) const STATS_RING_SIZE: usize = 0x4000; + /// FwCtl ring: 256 x 0x18 (the record stride of this firmware). Never used by the host: no + /// firmware cache flush path exists. + pub(crate) const FWCTL_RING_SIZE: usize = 0x1800; + /// Device-control and event record sizes. + pub(crate) const DEVCTL_RECORD: usize = 0x38; + pub(crate) const EVENT_RECORD: usize = 0x38; + /// Submit channel record size. + pub(crate) const CHANNEL_RECORD: usize = 0x18; +} + +/// One HardwareDataB IOMapping record: firmware device alias of an MMIO range. +#[derive(Copy, Clone)] +pub(crate) struct IoMap { + pub(crate) slot: u8, + pub(crate) pa: u64, + pub(crate) map_bytes: u64, + pub(crate) va: u64, + /// Added to `va` in the HardwareData record. + pub(crate) delta: u64, +} + +/// HardwareDataB IOMapping records of the qualified build. +pub(crate) const IOMAPS: [IoMap; 15] = [ + IoMap { + slot: 0, + pa: 0x290d00000, + map_bytes: 0x144000, + va: 0xfffffc2068000000, + delta: 0, + }, + IoMap { + slot: 1, + pa: 0x20e100000, + map_bytes: 0x4000, + va: 0xfffffc2068148000, + delta: 0x1000, + }, + IoMap { + slot: 2, + pa: 0x351014000, + map_bytes: 0x4000, + va: 0xfffffc2068150000, + delta: 0, + }, + IoMap { + slot: 3, + pa: 0x290000000, + map_bytes: 0x20000, + va: 0xfffffc2068158000, + delta: 0, + }, + IoMap { + slot: 7, + pa: 0x3502bc000, + map_bytes: 0x4000, + va: 0xfffffc206817c000, + delta: 0, + }, + IoMap { + slot: 9, + pa: 0x290e08000, + map_bytes: 0x8000, + va: 0xfffffc2068184000, + delta: 0, + }, + IoMap { + slot: 11, + pa: 0x220000000, + map_bytes: 0x12c000, + va: 0xfffffc2068190000, + delta: 0, + }, + IoMap { + slot: 12, + pa: 0x35104c000, + map_bytes: 0x4000, + va: 0xfffffc20682c0000, + delta: 0, + }, + IoMap { + slot: 18, + pa: 0x3503d0000, + map_bytes: 0x4000, + va: 0xfffffc20682c8000, + delta: 0, + }, + IoMap { + slot: 19, + pa: 0x3503c0000, + map_bytes: 0x4000, + va: 0xfffffc20682d0000, + delta: 0, + }, + IoMap { + slot: 20, + pa: 0x3503d8000, + map_bytes: 0x4000, + va: 0xfffffc20682d8000, + delta: 0, + }, + IoMap { + slot: 23, + pa: 0x293000000, + map_bytes: 0x400000, + va: 0xfffffc20682e0000, + delta: 0, + }, + IoMap { + slot: 25, + pa: 0x30945c000, + map_bytes: 0x4000, + va: 0xfffffc20686e4000, + delta: 0, + }, + IoMap { + slot: 26, + pa: 0x350280000, + map_bytes: 0x8000, + va: 0xfffffc20686ec000, + delta: 0, + }, + IoMap { + slot: 29, + pa: 0x290e5c000, + map_bytes: 0x4000, + va: 0xfffffc20686f8000, + delta: 0, + }, +]; + +/// RTKit endpoints and messages. +pub(crate) mod ep { + /// Firmware endpoint: the initdata doorbell and ring-service requests. + pub(crate) const FIRMWARE: u8 = 0x20; + /// Doorbell endpoint: channel and device-control notifications. + pub(crate) const DOORBELL: u8 = 0x21; + /// Host message handing the firmware its initdata root. + pub(crate) const INITDATA: u64 = 0x0081 << 48; + /// Address bits of the initdata root carried by [`INITDATA`]. + pub(crate) const INITDATA_ADDR_MASK: u64 = 0xfffffffffff; + /// Firmware message requesting that the receive rings be drained. + pub(crate) const RING_SERVICE: u64 = 0x0042 << 48; +} + +/// Fixed per-VM client placement, identical in every VM, inside [`CLIENT_APERTURE`], plus the +/// pass slots and PB page list in the compact window. User binds into any of these fail. +pub(crate) mod client { + use core::ops::Range; + + /// Per-VM kernel objects (the hole the userspace VA layout leaves for the runtime graph). + pub(crate) const CLIENT_APERTURE: Range = 0x7000000000..0x7100000000; + /// Compact-pointer window that VDM stream bases must lie in. + pub(crate) const COMPACT_WINDOW: Range = 0x1000000000..0x9000000000; + + pub(crate) const fn pool(k: u64) -> u64 { + 0x7000000000 + k * 0x404000 + } + pub(crate) const FREELIST: u64 = 0x7005858000; + pub(crate) const POOL_TABLE_PAGE: u64 = 0x7005c5c000; + pub(crate) const POOL_TABLE_OFF: u64 = 0x3000; + pub(crate) const PREEMPT: u64 = 0x7005c64000; + pub(crate) const PREEMPT_STRIDE: u64 = 0x10000; + pub(crate) const WORK_PAGE: u64 = 0x7021000000; + pub(crate) const WORK_OFF: u64 = 0x3760; + pub(crate) const CWORK_STRIDE: u64 = 0x4000; + pub(crate) const FS_WORK_PAGE: u64 = 0x7020000000; + pub(crate) const FS_WORK_OFF: u64 = 0x3380; + pub(crate) const TA_WORK_PAGE: u64 = 0x7020010000; + pub(crate) const TA_WORK_OFF: u64 = 0x36c0; + pub(crate) const WORK_STRIDE: u64 = 0x20000; + pub(crate) const fn uma(engine: u64, k: u64) -> u64 { + 0x7010000000 + engine * 0x2450000 + k * 0x408000 + } + pub(crate) const fn uma_freelist(engine: u64) -> u64 { + 0x7012040000 + engine * 0x2450000 + } + pub(crate) const fn uma_table_page(engine: u64) -> u64 { + 0x7012448000 + engine * 0x2450000 + } + pub(crate) const AUX: u64 = 0x70148a0000; + pub(crate) const AUX_STRIDE: u64 = 0x98000; + pub(crate) const TPC: u64 = 0x7040000000; + pub(crate) const TPC_SIZE: u64 = 0x1000000; + pub(crate) const TILEMAP: u64 = 0x7042000000; + pub(crate) const TILEMAP_SIZE: u64 = 0x800000; + pub(crate) const TPC_SLOT_SIZE: u64 = 0x200000; + pub(crate) const TILEMAP_SLOT_SIZE: u64 = 0x100000; + pub(crate) const TPC_SLOT_STRIDE: u64 = 0x4000000; + pub(crate) const CT: u64 = 0x7080000000; + pub(crate) const CT_STRIDE: u64 = 0x1000000; + pub(crate) const CT_SIZE: u64 = 0x400000; + pub(crate) const PB_HEAP: u64 = 0x70c0000000; + pub(crate) const PB_HEAP_SIZE: u64 = 0x20000000; + pub(crate) const PB_BLOCK_LIST: u64 = 0x70f0000000; + /// Compact-window objects (32-bit compact pointers: `gva - 0x1000000000`). + pub(crate) const PRE0_PAGE: u64 = 0x1006080000; + pub(crate) const PRE1_PAGE: u64 = 0x1006098000; + pub(crate) const PRE2_PAGE: u64 = 0x10060b0000; + pub(crate) const HEAP_META_PAGE: u64 = 0x1006140000; + pub(crate) const SCENE_USER: u64 = 0x1006158000; + pub(crate) const FS_SCRATCH: u64 = 0x1006178000; + pub(crate) const PASS_STRIDE: u64 = 0x118000; + pub(crate) const PB_PAGE_LIST: u64 = 0x1074000000; + pub(crate) const PB_PAGE_LIST_SIZE: u64 = 0x28000; +} + +/// Sizes and counts of the engine's objects. +pub(crate) mod sizes { + pub(crate) const POOLS: usize = 22; + pub(crate) const POOL_SIZE: u64 = 0x400000; + pub(crate) const FREELIST_SEED: u32 = 8192; + pub(crate) const QUEUE_CAP: u32 = 0x500; + pub(crate) const COMPUTE_SLOTS: usize = 16; + pub(crate) const RENDER_SLOTS: usize = 16; + pub(crate) const CT_BUFS: usize = 2 * RENDER_SLOTS; + pub(crate) const CLUSTER_PB_PAGES: u32 = 0x3c; + pub(crate) const MAX_ATTACHMENTS: usize = 16; + pub(crate) const MAX_CLIENT: usize = 320; + pub(crate) const PB_PAGES: u32 = 16384; + pub(crate) const PB_BLOCKS: u32 = 4096; + pub(crate) const PB_LIST_RECORDS: u32 = 4096; + pub(crate) const PB_GROW_STEP: u32 = 10; + /// Flights (published prefixes) in flight at most; the second must be of the same VM. + pub(crate) const FLIGHTS: usize = 2; + /// Jobs per compute horizon, and scheduler credits per queue. + pub(crate) const HORIZON_JOBS: u32 = 16; + /// Unconsumed records per 256-entry channel ring a prefix may be posted behind. + pub(crate) const AHEAD_RECORDS: u32 = 64; + /// Policy bound on logical queues reported in QUEUE_LIMITS (not a firmware limit). + pub(crate) const MAX_QUEUES: u32 = 58; + /// TTBAT user slots: user VMs hold one each for their lifetime (ASIDs 1..63). + pub(crate) const MAX_VMS: u32 = 63; +} + +/// Firmware channels, doorbells, seeds and identifiers. +pub(crate) mod engine { + pub(crate) const DOORBELL: u64 = 0x0083000000000000; + pub(crate) const DEVCTL_DOORBELL: u64 = 0x0083000000000011; + pub(crate) const EVENT_SLOT: u32 = 2; + pub(crate) const COMPUTE_SEED: u32 = 0xc1000000; + pub(crate) const TA_SEED: u32 = 0x7a000000; + pub(crate) const FS_SEED: u32 = 0x3d000000; + pub(crate) const COMPUTE_UUID: u32 = 0xc10000; + pub(crate) const TA_UUID: u32 = 0x7a0000; + pub(crate) const FS_UUID: u32 = 0x3d0000; +} + +/// Tuned policy. Every value was chosen by measurement on hardware; only the ones in +/// `params.rs` are tunable. +pub(crate) mod tuning { + /// Firmware idle standby time, us, of a machine whose device tree does not provide one (the + /// T6030): with the template's 700 us the GPU powers down between works ~100 us apart. + pub(crate) const IDLE_STANDBY_US: u32 = 2500; + /// Command objects (work images, microsequences, barriers, queue info, scheduling contexts, + /// job lists, FW-only queue scratch) map ASC-cached (AttrIndex 0). + pub(crate) const FW_CACHED: bool = true; + /// The first HardwareData pages map ASC-cached. + pub(crate) const HWDATA_CACHED: bool = true; + /// Render notifier ASC-cached (bit 1), compute notifier not (bit 0). + pub(crate) const NOTIFIER_CACHED: u32 = 2; + /// UMA/PB managers, block_ctl and misc ASC-cached, with an uncached spare set. + pub(crate) const MANAGER_CACHED: bool = true; + /// Scheduling class of the render and compute queue-info rows (2: killable compute). + pub(crate) const RENDER_QUEUE_CLASS: u32 = 2; + pub(crate) const COMPUTE_QUEUE_CLASS: u32 = 2; + /// Intra-prefix FS->TA barrier type. + pub(crate) const RENDER_INTERNAL_HOLD: u32 = 0; + /// Bit 0: FS->compute type 1; bit 1: compute->TA type 1. Never both type 0. + pub(crate) const CROSS_ENGINE_HOLD: u32 = 1; + /// Compute-only jobs folded into one prefix. + pub(crate) const COMPUTE_HORIZON: u32 = 16; + /// Renders per prefix (half of the pass slots), with submit-ahead. + pub(crate) const PREFIX_RENDERS: u32 = 8; + pub(crate) const SUBMIT_AHEAD: bool = true; + /// Computes and renders in one prefix. + pub(crate) const MIXED_PREFIX: bool = true; + /// Two-cluster vertex clustering. + pub(crate) const VERTEX_CLUSTERING: bool = true; + /// Background zeroing of retired storage; also zero aux, heap and scene-user. + pub(crate) const CT_ASYNC: bool = true; + pub(crate) const PASS_FULL_RESET: bool = true; + /// Rotating compute-slot cursor. + pub(crate) const SLOT_ROTATE: bool = true; + /// Flights per VM. + pub(crate) const MAX_INFLIGHT: u32 = 2; + /// PB growth through event 7 / DEVCTL 7, initial and maximum blocks. + pub(crate) const PB_GROW: bool = true; + /// Initial PB blocks, and the most that may be posted: one below the mapped heap's block + /// count, so the block-list producer (modulo K = 4096) never returns to 0. + pub(crate) const PB_BLOCKS: u32 = 1024; + pub(crate) const PB_MAX_BLOCKS: u32 = super::sizes::PB_BLOCKS - 1; + /// At the host deadline, arm the firmware kill. + pub(crate) const HANG_PREEMPT: bool = true; + /// Compute start-sequence MMU fault mask (unmapped stores absorbed). + pub(crate) const COMPUTE_FAULT_MASK: u32 = 1; + /// Firmware idle decision: finite delay, not predictive. + pub(crate) const IDLE_PREDICTIVE: bool = false; + /// Handle EP 0x20 drain requests in the mailbox interrupt. + pub(crate) const EARLY_WAKE: bool = true; + /// Scheduler timeout per job, ms; the engine's deadlines own failure (always "no hang"). + pub(crate) const SCHED_TIMEOUT_MS: u32 = 3000; +} diff --git a/drivers/gpu/drm/asahi/g15/hw/t6031.rs b/drivers/gpu/drm/asahi/g15/hw/t6031.rs new file mode 100644 index 00000000000000..4af32f6068cd7a --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/hw/t6031.rs @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! T6031 (M3 Max, G15C) configuration, admitted on J516C only. +//! +//! One die, four clusters of ten core slots. The firmware is the same RTKit 2419 generation as +//! the T6030's and the initdata graph keeps the T6030 canonical VAs; what differs is the SoC +//! identity, the 40-bit enabled-core mask (two words), the source of the GPU regions (the +//! device tree node the boot loader fills, not an ADT export), the GPU power (its power domain; +//! there is no PMP vote), the initdata root version, a longer HardwareData record (0xb480 +//! bytes, its fourth view at +0xb400) placed aligned and ASC-cached, the IOMapping table (17 +//! slots at the T6031 register blocks) and the board images, built from the device tree and +//! checked against this machine's firmware file, which supplies the record's non-device-tree +//! words. Every +//! value was measured on a J516C: the SGX identification +//! registers, the loaded firmware segment, the device tree the boot loader hands over and the +//! initdata of that machine. + +use super::super::Config; +use super::{FirmwareBuild, HwId, IoMap, Layout}; + +/// SGX register window (the `sgx` resource), physical. +const SGX: u64 = 0x4_0800_0000; +/// The die 0 interrupt controller. +const AIC: u64 = 0x2_9240_0000; + +/// Base of the IOMapping firmware VAs and the gap left between consecutive mappings. +const IOMAP_BASE: u64 = 0xfffffc2068000000; +const IOMAP_GAP: u64 = 0x4000; +const PAGE: u64 = 0x4000; + +/// Mappings in slot order: slot, physical address, mapped bytes (rounded up to pages below), +/// element bytes, writable. Slots 0 (Fender, 0x144000), 1 (AIC timer page), 2 (AIC software +/// interrupts), 3 (RGX), 7, 9 (metrology sensors), 11 (memory cache, eight 0xd8000 +/// instances), 12 (AIC banked registers), 18-20 (telemetry dashboard), 21, 24, 25 (ANE), 26 +/// (PMS metrology), 28 and 29 (GPU clock generator at `sgx + 0xe1c000`). The record carries +/// each slot's physical address, sizes and access flag. +const SLOTS: [(u8, u64, u64, u64, bool); 17] = [ + (0, SGX + 0xd0_0000, 0x14_4000, 0x14_4000, true), + (1, 0x2_0e10_0000, 0x4000, 0x4000, false), + (2, AIC + 0x1_4000, 0x4000, 0x4000, true), + (3, SGX, 0x2_0000, 0x2_0000, true), + (7, 0x2_9044_4000, 0x4000, 0x4000, false), + (9, SGX + 0xe0_8000, 0x8000, 0x8000, true), + (11, 0x2_2000_0000, 8 * 0xd_8000, 0xd_8000, true), + (12, AIC + 0x4_c000, 0x4000, 0x4000, false), + (18, 0x2_903d_0000, 0x4000, 0x4000, true), + (19, 0x2_903c_0000, 0x4000, 0x4000, false), + (20, 0x2_903d_8000, 0x4000, 0x4000, true), + (21, SGX + 0xeb_4000, 0x4000, 0x4000, true), + (24, SGX + 0x100_0000, 0x8000, 0x8000, true), + (25, 0x3_c945_c000, 0x4000, 0x4000, true), + (26, 0x2_9040_0000, 0x8000, 0x8000, false), + (28, 0x2_a4dc_0000, 0x2_4000, 0x2_4000, false), + (29, SGX + 0xe1_c000, 0x4000, 0x4000, false), +]; + +/// The record's per-slot sizes and access flags, in [`SLOTS`] order. +const fn record_slots() -> [(u32, u32, bool); 17] { + let mut out = [(0, 0, false); 17]; + let mut i = 0; + while i < SLOTS.len() { + let (_, _, total, element, writable) = SLOTS[i]; + out[i] = (total as u32, element as u32, writable); + i += 1; + } + out +} +const RECORD_SLOTS: [(u32, u32, bool); 17] = record_slots(); + +/// Unmapped slots whose IOMapping flag word the J516C record holds as 1. +const RECORD_EMPTY_WRITABLE: [u8; 9] = [4, 6, 8, 10, 13, 14, 15, 16, 17]; + +/// Packs the slots' firmware VAs: consecutive from [`IOMAP_BASE`], each mapping followed by one +/// unmapped page. +const fn iomaps() -> [IoMap; 17] { + let mut out = [IoMap { + slot: 0, + pa: 0, + map_bytes: 0, + va: 0, + delta: 0, + }; 17]; + let mut va = IOMAP_BASE; + let mut i = 0; + while i < SLOTS.len() { + let (slot, pa, bytes, _, _) = SLOTS[i]; + let delta = pa & (PAGE - 1); + let map_bytes = (delta + bytes + PAGE - 1) & !(PAGE - 1); + out[i] = IoMap { + slot, + pa: pa & !(PAGE - 1), + map_bytes, + va, + delta, + }; + va += map_bytes + IOMAP_GAP; + i += 1; + } + out +} + +/// HardwareDataB IOMapping records of the J516C. +pub(crate) const IOMAPS: [IoMap; 17] = iomaps(); + +/// The J516C initdata layout: the T6030 graph with the root version this firmware's host +/// driver sends and the longer HardwareData record, placed 16-byte aligned (the firmware's MTR +/// alarm handler does a 64-bit atomic in HardwareDataA; at the T6030 placement the record is +/// 4-byte aligned, which faulted on T8122) and mapped ASC-cached as a whole. +pub(crate) const LAYOUT: Layout = Layout { + root_magic: 0x0c08e21e84820490, + hwdata_va: 0xfffffc20406fb580, + hwdata_size: 0xb480, + hwdata_cached: None, + hwdata_view: 0xb400, + iomaps: &IOMAPS, + record_slots: &RECORD_SLOTS, + record_empty_writable: &RECORD_EMPTY_WRITABLE, +}; + +/// The J516C board file (`asahi/t6031-j516c-board.bin`, built into the kernel): the hardware +/// record, Globals and the power block that this machine's firmware accepted, as the earlier +/// J516C driver uploaded them (its device-tree-built records with the per-board words of this +/// machine applied). Kept out of the tree; pinned by its SHA-256. The three images are built +/// from the device tree and must match the file's; the file supplies the record's words the +/// device tree does not carry (`board::record::FROM_FILE`). +const BOARD_SHA256: [u8; 32] = [ + 0x4e, 0x03, 0xf2, 0x9f, 0xa4, 0x47, 0xdc, 0xeb, 0xfd, 0x4d, 0x1c, 0x22, 0x5a, 0x64, 0x7b, + 0xfa, 0x31, 0xb3, 0x63, 0x45, 0x8f, 0x28, 0x33, 0x82, 0x3a, 0x5c, 0xa8, 0xa1, 0x0e, 0xdf, + 0xf3, 0xfc, +]; + +pub(crate) const CONFIG: Config = Config { + name: "T6031 G15C", + chip_id: 0x6031, + gpu_variant: crate::hw::GpuVariant::C, + gpu_revision: 0x12, + uat_ias: 42, + uat_oas: 42, + num_clusters: 4, + num_cores_per_cluster: 10, + hw_ids: &[HwId { + version: 0x07041100, + counts: 0x0021040a, + }], + // The stubs the boot chains of this J516C leave loaded (RTKit-2419.140.12): the macOS 14.7 + // chain's and the macOS 14.8 boot volume's. Same segment sizes and marker; the layout, board + // images and initdata below do not depend on which one is loaded. A further build can be + // admitted for one boot with `g15_accept_text_prefix`, which logs its digest. + firmware: &[ + FirmwareBuild { + name: "macOS 14.7 stub firmware (iBoot-10151.140.19.700.2), J516C", + machine: None, + text_size: 0x64000, + data_size: 0x140000, + marker: 0x5cf28, + text_sha256: [ + 0xc2, 0x6e, 0xc8, 0x9c, 0x11, 0x50, 0xeb, 0x65, 0x49, 0xcf, 0x60, 0x2e, 0x01, + 0x2d, 0x0c, 0x5f, 0x49, 0xeb, 0x75, 0x6e, 0x89, 0x6d, 0x6b, 0xb8, 0x34, 0x2c, + 0xb2, 0xc5, 0xd9, 0x8b, 0x33, 0x2c, + ], + }, + FirmwareBuild { + name: "macOS 14.8 stub firmware, J516C", + machine: None, + text_size: 0x64000, + data_size: 0x140000, + marker: 0x5cf28, + text_sha256: [ + 0x1b, 0xf2, 0xfd, 0x34, 0x76, 0xbe, 0xfe, 0x73, 0x6b, 0xc2, 0xc0, 0x70, 0xba, + 0xd4, 0x5f, 0x8b, 0xe3, 0x6b, 0x68, 0xcd, 0x11, 0xbc, 0xff, 0x16, 0xc9, 0x02, + 0x9d, 0x6b, 0xcd, 0xa0, 0x26, 0xcf, + ], + }, + ], + // The pinned board images and measured layout belong to the J516C, not + // every T6031 board (in particular, not the 14-inch J514C). + machine: kernel::c_str!("apple,j516c"), + platform: super::Platform::DeviceTree, + layout: &LAYOUT, + board: super::Board::Blob { + name: kernel::c_str!("asahi/t6031-j516c-board.bin"), + sha256: BOARD_SHA256, + }, + // Four clusters: the saved-state pointers at +0x2980 of the preemption buffer (0xd80 plus + // 0x700 per cluster), UMA PTC 0x6000400020, DUPM 0x3c000000140 (32 N | 96 N << 32 for + // N = 10 cores per cluster) and 0x1a0e9 = 0, with the saved-state pointers and the + // 0x12091/0x101d9 words zero in every command, as this machine's driver encodes a queue's + // first command. Read from 38 compute commands on a J516C; the two-cluster values fault + // the first job on this GPU. + compute: super::ComputeRegs { + tail: 0x2980, + ptc: 0x6000400020, + dupm: 0x3c000000140, + reg_1a0e9: 0, + fresh: true, + }, +}; diff --git a/drivers/gpu/drm/asahi/g15/identity.rs b/drivers/gpu/drm/asahi/g15/identity.rs new file mode 100644 index 00000000000000..2bf95c8ad98dbe --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/identity.rs @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Exact firmware and hardware identity. +//! +//! The firmware build is the SHA-256 of TEXT with the 8 entropy bytes after the single +//! `GKTS\x08\0\0\0` marker zeroed, plus the segment sizes, looked up in the SoC +//! configuration's `firmware` list; the hardware revision is checked against its `hw_ids` at +//! start ([`super::boot`]). An unknown build or revision is refused with its measured identity; +//! an unknown build's refusal also says what to report so that it can be pinned. The pure +//! lookup is in [`lookup`] (host-tested). +//! The canonical object VAs, the initdata graph, the board images and the work layouts all +//! belong to one build, so nothing is written before the build is identified. +//! +//! Bring-up escape hatch: `g15_accept_text_prefix=` admits an unpinned build whose digest +//! starts with those 8 bytes (the full digest and marker offset are logged, so that the build +//! can be pinned by the next kernel). + +use kernel::{bindings, device, fmt, prelude::*}; + +use super::boot::glue; +use super::hw::FirmwareBuild; + +mod lookup; +mod matching; + +use lookup::{Measured, Verdict}; + +/// Lowercase hex of a byte string, as `%*phN` prints it. +pub(crate) struct Hex<'a>(pub(crate) &'a [u8]); + +impl fmt::Display for Hex<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for b in self.0 { + write!(f, "{:02x}", b)?; + } + Ok(()) + } +} + +/// Copies `size` bytes at physical `phys`, a range outside the kernel's System RAM, into a +/// private copy through a temporary write-back mapping. +pub(crate) fn copy_physical(phys: u64, size: usize) -> Result> { + // SAFETY: memremap() of a boot-loader range creates a temporary mapping; it has no other + // side effects. + let map = unsafe { bindings::memremap(phys, size, bindings::MEMREMAP_WB as _) }; + if map.is_null() { + return Err(ENOMEM); + } + let copy = KVVec::from_elem(0u8, size, GFP_KERNEL).map(|mut copy| { + // SAFETY: `map` is a live mapping of `size` bytes and `copy` holds `size` bytes; the two do + // not overlap. + unsafe { core::ptr::copy_nonoverlapping(map as *const u8, copy.as_mut_ptr(), size) }; + copy + }); + // SAFETY: `map` came from memremap() above and is not used afterwards. + unsafe { bindings::memunmap(map) }; + Ok(copy?) +} + +impl From<&FirmwareBuild> for Measured { + fn from(build: &FirmwareBuild) -> Self { + Measured { + text_size: build.text_size, + data_size: build.data_size, + marker: build.marker, + sha256: build.text_sha256, + } + } +} + +/// Identifies the loaded firmware build: the pinned build, or `None` for a build admitted by +/// its digest prefix (`g15_accept_text_prefix`). +pub(crate) fn firmware( + dev: &device::Device, + adt: &super::adt::GpuAdt, + builds: &'static [FirmwareBuild], +) -> Result> { + let size = usize::try_from(adt.text.end - adt.text.start)?; + let data_size = adt.data.end - adt.data.start; + let mut copy = copy_physical(adt.text.start, size)?; + let at = lookup::marker(©).map_err(|found| { + dev_err!( + dev, + "GPU firmware TEXT has {} GKTS markers, need one\n", + found + ); + EINVAL + })?; + copy[at + 8..at + 16].fill(0); + let m = Measured { + text_size: size as u64, + data_size, + marker: u32::try_from(at)?, + sha256: glue::sha256(©), + }; + // A qualified build pins only on the machine it names. + let qualified = builds + .iter() + .map(|b| (Measured::from(b), b.machine.map_or(true, glue::machine))); + match lookup::verdict(&m, qualified, super::params::accept_text_prefix()) { + Verdict::Pinned(i) => { + let build = builds.get(i).ok_or(EINVAL)?; + dev_info!(dev, "GPU firmware build: {}\n", build.name); + return Ok(Some(build)); + } + Verdict::Admitted => { + dev_warn!( + dev, + "GPU firmware build admitted by g15_accept_text_prefix: TEXT {:#x} DATA {:#x} GKTS {:#x} sha256 {}\n", + size, + data_size, + at, + Hex(&m.sha256) + ); + return Ok(None); + } + Verdict::Refused => {} + } + dev_err!( + dev, + "unsupported GPU firmware build: TEXT {:#x} DATA {:#x} GKTS {:#x} sha256 {}; {}\n", + size, + data_size, + at, + Hex(&m.sha256), + lookup::REPORT_HINT + ); + for build in builds { + dev_err!(dev, "supported: {}\n", build.name); + } + Err(EINVAL) +} diff --git a/drivers/gpu/drm/asahi/g15/identity/lookup.rs b/drivers/gpu/drm/asahi/g15/identity/lookup.rs new file mode 100644 index 00000000000000..efb8bbcd08090f --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/identity/lookup.rs @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Pure firmware-build identification: the GKTS marker search, the lookup of a measured build in +//! the qualified list, the `g15_accept_text_prefix` escape and the refusal hint. +//! +//! A qualified build pins only through [`super::matching::exact`]: its sizes, marker and digest, +//! and the machine it names. +//! +//! Core-only (no `kernel` imports): this file is compiled by the host test harness as well. + +use super::matching; + +/// The GKTS marker: the 8 bytes after it are per-boot entropy. +pub(crate) const MARKER: [u8; 8] = [0x47, 0x4b, 0x54, 0x53, 0x08, 0, 0, 0]; + +/// Appended to the refusal of an unknown build: what a user reports so that it can be pinned. +pub(crate) const REPORT_HINT: &str = + "to have it supported, report this line and the macOS version of the boot chain that loaded it"; + +/// The identity of a loaded firmware build: segment sizes, marker offset and the TEXT digest with +/// the marker's entropy zeroed. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Measured { + pub(crate) text_size: u64, + pub(crate) data_size: u64, + pub(crate) marker: u32, + pub(crate) sha256: [u8; 32], +} + +/// The outcome of identifying a measured build. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Verdict { + /// The qualified build at this index. + Pinned(usize), + /// Not qualified, admitted for this boot because its digest prefix was named. + Admitted, + /// Not qualified and not admitted. + Refused, +} + +/// Offsets of the 8-byte-aligned GKTS markers in `text` that have their 8 entropy bytes in +/// range: `Ok(offset)` for exactly one, `Err(count)` otherwise. +pub(crate) fn marker(text: &[u8]) -> Result { + let mut at = 0usize; + let mut found = 0usize; + let mut off = 0usize; + while off + 16 <= text.len() { + if text[off..off + 8] == MARKER { + at = off; + found += 1; + } + off += 8; + } + if found == 1 { + Ok(at) + } else { + Err(found) + } +} + +/// The first 8 digest bytes, big-endian, as `g15_accept_text_prefix` names them. +pub(crate) fn prefix(sha256: &[u8; 32]) -> u64 { + let mut first = [0u8; 8]; + first.copy_from_slice(&sha256[..8]); + u64::from_be_bytes(first) +} + +/// Looks `m` up in `qualified`, each build with whether this machine is the one it names; an +/// unqualified build is admitted only when `accept_prefix` is nonzero and equals its digest +/// prefix. +pub(crate) fn verdict( + m: &Measured, + qualified: impl IntoIterator, + accept_prefix: u64, +) -> Verdict { + if let Some(i) = qualified.into_iter().position(|(q, machine)| { + matching::exact( + (q.text_size, q.data_size), + (m.text_size, m.data_size), + q.marker, + m.marker as usize, + &q.sha256, + &m.sha256, + machine, + ) + }) { + return Verdict::Pinned(i); + } + if accept_prefix != 0 && accept_prefix == prefix(&m.sha256) { + Verdict::Admitted + } else { + Verdict::Refused + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn build(n: u8) -> Measured { + let mut sha256 = [0u8; 32]; + sha256[0] = 0x1b; + sha256[7] = n; + sha256[31] = n; + Measured { + text_size: 0x64000, + data_size: 0x140000, + marker: 0x5cf28, + sha256, + } + } + + #[test] + fn finds_one_marker() { + let mut text = [0u8; 64]; + text[16..24].copy_from_slice(&MARKER); + assert_eq!(marker(&text), Ok(16)); + } + + #[test] + fn refuses_none_two_or_misaligned_markers() { + let mut text = [0u8; 64]; + assert_eq!(marker(&text), Err(0)); + text[12..20].copy_from_slice(&MARKER); + assert_eq!(marker(&text), Err(0)); + text = [0u8; 64]; + text[8..16].copy_from_slice(&MARKER); + text[32..40].copy_from_slice(&MARKER); + assert_eq!(marker(&text), Err(2)); + } + + #[test] + fn needs_the_entropy_bytes_in_range() { + let mut text = [0u8; 64]; + text[56..64].copy_from_slice(&MARKER); + assert_eq!(marker(&text), Err(0)); + } + + #[test] + fn prefix_is_the_first_eight_bytes_big_endian() { + let mut sha256 = [0u8; 32]; + sha256[..8].copy_from_slice(&[0x1b, 0xf2, 0xfd, 0x34, 0x76, 0xbe, 0xfe, 0x73]); + sha256[8] = 0xff; + assert_eq!(prefix(&sha256), 0x1bf2fd3476befe73); + } + + #[test] + fn pins_the_matching_build() { + assert_eq!( + verdict(&build(2), [(build(1), true), (build(2), true)], 0), + Verdict::Pinned(1) + ); + } + + #[test] + fn pinned_wins_over_the_prefix() { + let m = build(1); + assert_eq!(verdict(&m, [(m, true)], prefix(&m.sha256)), Verdict::Pinned(0)); + } + + #[test] + fn every_field_must_match() { + let q = build(1); + let mut m = q; + m.text_size += 0x1000; + assert_eq!(verdict(&m, [(q, true)], 0), Verdict::Refused); + m = q; + m.data_size += 0x1000; + assert_eq!(verdict(&m, [(q, true)], 0), Verdict::Refused); + m = q; + m.marker += 8; + assert_eq!(verdict(&m, [(q, true)], 0), Verdict::Refused); + m = q; + m.sha256[31] ^= 1; + assert_eq!(verdict(&m, [(q, true)], 0), Verdict::Refused); + } + + #[test] + fn another_machines_build_is_not_pinned() { + let m = build(1); + assert_eq!(verdict(&m, [(m, false)], 0), Verdict::Refused); + assert_eq!( + verdict(&m, [(m, false), (m, true)], 0), + Verdict::Pinned(1) + ); + // The digest-prefix escape still applies to it, as to any unqualified build. + assert_eq!( + verdict(&m, [(m, false)], prefix(&m.sha256)), + Verdict::Admitted + ); + } + + #[test] + fn admits_only_the_named_prefix() { + let m = build(3); + assert_eq!( + verdict(&m, [(build(1), true)], prefix(&m.sha256)), + Verdict::Admitted + ); + assert_eq!( + verdict(&m, [(build(1), true)], prefix(&build(4).sha256)), + Verdict::Refused + ); + } + + #[test] + fn zero_prefix_admits_nothing() { + let m = Measured { + sha256: [0u8; 32], + ..build(0) + }; + assert_eq!(verdict(&m, [(build(1), true)], 0), Verdict::Refused); + } + + #[test] + fn hint_says_what_to_report() { + assert!(REPORT_HINT.contains("report this line")); + assert!(REPORT_HINT.contains("macOS version")); + } +} diff --git a/drivers/gpu/drm/asahi/g15/identity/matching.rs b/drivers/gpu/drm/asahi/g15/identity/matching.rs new file mode 100644 index 00000000000000..23b24afd411593 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/identity/matching.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Exact firmware metadata admission, shared with the host regression checks. + +pub(crate) fn exact( + expected_sizes: (u64, u64), actual_sizes: (u64, u64), + expected_marker: u32, actual_marker: usize, + expected_digest: &[u8; 32], actual_digest: &[u8; 32], + machine_matches: bool, +) -> bool { + machine_matches && expected_sizes == actual_sizes && + expected_marker as usize == actual_marker && expected_digest == actual_digest +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn requires_board_full_digest_sizes_and_marker() { + let sizes = (0x5c000, 0x114000); + let hash = [0x5a; 32]; + assert!(exact(sizes, sizes, 0x58e88, 0x58e88, &hash, &hash, true)); + assert!(!exact(sizes, sizes, 0x58e88, 0x58e88, &hash, &hash, false)); + assert!(!exact(sizes, (sizes.0 + 1, sizes.1), 0x58e88, 0x58e88, &hash, &hash, true)); + assert!(!exact(sizes, (sizes.0, sizes.1 + 1), 0x58e88, 0x58e88, &hash, &hash, true)); + assert!(!exact(sizes, sizes, 0x58e88, 0x58e80, &hash, &hash, true)); + let mut same_prefix = hash; + same_prefix[31] ^= 1; + assert!(!exact(sizes, sizes, 0x58e88, 0x58e88, &hash, &same_prefix, true)); + } +} diff --git a/drivers/gpu/drm/asahi/g15/initdata.rs b/drivers/gpu/drm/asahi/g15/initdata.rs new file mode 100644 index 00000000000000..f3f5232e92a28f --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/initdata.rs @@ -0,0 +1,487 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The initdata graph (49 objects at canonical VAs) and its live words. +//! +//! The build allocates the objects, channels and IOMappings, writes the board images and the +//! root, runtime and control pointers, and patches HardwareData and Globals (TTBAT PA at +//! HardwareData +0xb44, IOMapping VAs, the timestamp arena at +0x28, the tuned idle policy, +//! Globals +0x980 = 100, HardwareDataA +0x4580 words). The object classes follow +//! [`super::hw::tuning`]: HardwareData pages 0-1 ASC-cached, the fault-information page and +//! everything else uncached; channel rings NEVER cached (caching them hangs the firmware). +//! +//! Live words used after READY: Globals (+0x1c/+0x24 kill divisors, +0x2c/+0x30/+0x7a8/ +//! +0x7c4/+0x9a0 idle policy, +0x9b0 compute monitor), Control (+0x40a0 pending, +0x4580 halt +//! count / PB epoch, +0x4590 halted, +0x45a0 resume), HardwareData +0x8900 fault information. +//! Globals changes are re-imported with DEVCTL 0x13. All objects here are firmware-only +//! (AttrIndex 2) unless noted; offsets are relative to each object's canonical VA. + +use kernel::{device, prelude::*, sync::Arc}; + +use super::adt::GpuAdt; +use super::board::{self, data}; +use super::boot::glue; +use super::channel::Channels; +use super::fw::initdata::{ + cbuf, control, flags, globals, hwdata, pair, power, region_a, root, runtime, small, +}; +use super::hw::{self, va}; +use super::identity::Hex; +use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::Config; + +/// The built initdata graph. +pub(crate) struct InitData { + /// Globals, Control and HardwareData: the live words of recovery, power and faults. + pub(crate) globals: Option>, + pub(crate) control: Option>, + pub(crate) hwdata: Option>, + /// Runtime (readiness) and Flags. + pub(crate) runtime: Option>, + pub(crate) flags: Option>, + /// C1 (firmware + GPU shared), written by the PB (re)initialization. + pub(crate) c1: Option>, + /// The rest of the graph, retained (root, region A, pair, small, C0, C1, C3, power). + others: KVec>, +} + +impl InitData { + pub(crate) fn new() -> Self { + Self { + globals: None, + control: None, + hwdata: None, + runtime: None, + flags: None, + c1: None, + others: KVec::new(), + } + } + + /// Control +0x4590: the firmware halted for recovery. + pub(crate) fn halted(&self) -> Result { + Ok(self.control.as_ref().ok_or(ENODEV)?.r32(control::HALTED)? == 1) + } + + /// The readiness words: Runtime +0x314 and Flags +4. + pub(crate) fn readiness(&self) -> Result<(u32, u32)> { + Ok(( + self.runtime.as_ref().ok_or(ENODEV)?.r32(runtime::READY)?, + self.flags.as_ref().ok_or(ENODEV)?.r32(flags::READY)?, + )) + } +} + +impl super::Firmware { + /// Writes the 16-byte C1 record into the initdata C1 object. + pub(crate) fn write_c1(&mut self, record: &[u8; 16]) -> Result { + self.init.c1.as_ref().ok_or(ENODEV)?.write(0, record) + } +} + +/// A canonical firmware-only object at `va`. +fn canonical(objects: &mut Objects, at: u64, size: usize, class: Class) -> Result> { + objects.alloc(Request { + size, + class, + placement: Placement::At(at), + offset: 0, + client: None, + lower: None, + cpu: true, + }) +} + +fn get32(b: &[u8], offset: usize) -> Result { + Ok(u32::from_le_bytes( + b.get(offset..offset + 4) + .ok_or(EINVAL)? + .try_into() + .map_err(|_| EINVAL)?, + )) +} + +fn put32(b: &mut [u8], offset: usize, value: u32) -> Result { + b.get_mut(offset..offset + 4) + .ok_or(EINVAL)? + .copy_from_slice(&value.to_le_bytes()); + Ok(()) +} + +fn put64(b: &mut [u8], offset: usize, value: u64) -> Result { + b.get_mut(offset..offset + 8) + .ok_or(EINVAL)? + .copy_from_slice(&value.to_le_bytes()); + Ok(()) +} + + +/// The T6030 board images: the verified templates with DVFS from the ADT. Returns the images +/// and the top DVFS frequency in kHz. +fn templates( + dev: &device::Device, + adt: &GpuAdt, +) -> Result<(KVVec, KVVec, KVVec, u32)> { + let mut hw_img = KVVec::from_elem(0u8, hwdata::SIZE, GFP_KERNEL)?; + let mut glob = KVVec::from_elem(0u8, globals::SIZE, GFP_KERNEL)?; + let mut pwr = KVVec::from_elem(0u8, power::SIZE, GFP_KERNEL)?; + if board::expand(&data::HARDWARE, &mut hw_img).is_err() + || board::expand(&data::GLOBALS, &mut glob).is_err() + || board::expand(&data::POWER, &mut pwr).is_err() + { + dev_err!(dev, "board data template hash mismatch\n"); + return Err(EINVAL); + } + if get32(&hw_img, hwdata::CHECK_A38)? != 1 + || get32(&hw_img, hwdata::DVFS_COUNT)? != board::DVFS_STATES as u32 - 1 + || get32(&glob, globals::UNK_980)? != 10 + || get32(&glob, globals::IDLE_STANDBY_US)? != 700 + || get32(&glob, globals::IDLE_MIN_CONF)? != 0x3f333333 + { + return Err(EINVAL); + } + let max_khz = board::from_adt(dev, adt, &mut hw_img)?; + let reference = glue::sha256(&hw_img) == data::HARDWARE.sha256; + dev_info!( + dev, + "board data: ADT performance states, {} MHz top{}\n", + max_khz / 1000, + if reference { + " (reference machine)" + } else { + " (differs from the reference machine)" + } + ); + if !reference { + dev_info!(dev, "board data sha256 {}\n", Hex(&glue::sha256(&hw_img))); + } + Ok((hw_img, glob, pwr, max_khz)) +} + +/// HardwareDataA word holding the system counter at initdata creation. +const HWDATA_A_INIT_TIMESTAMP: usize = 0x424c; + +/// Board images of a SoC with a firmware file. The hardware record ([`board::hardware_record`]), +/// Globals and Power ([`board::device_tree`]) are built from the device tree; the file, this +/// machine's own, supplies the record's words the device tree does not carry and is otherwise +/// a cross-check: admission ([`prepare_board`], before any firmware is touched) is refused at +/// the first differing word. Returns the images and the top operating-point frequency in kHz. +fn blob( + dev: &device::Device, + cfg: &Config, + adt: &GpuAdt, + name: &CStr, + sha256: &[u8; 32], +) -> Result<(KVVec, KVVec, KVVec, u32)> { + let layout = cfg.layout; + let images = board::blob::load( + dev, + name, + sha256, + [layout.hwdata_size, globals::SIZE, power::SIZE], + )?; + let hw_img = board::hardware_record(dev, cfg, adt, &images.hardware)?; + let (glob, pwr, max_power_mw) = board::device_tree(dev, &hw_img)?; + for (what, built, file) in [ + ("hardware record", &hw_img, &images.hardware), + ("Globals", &glob, &images.globals), + ("Power", &pwr, &images.power), + ] { + let diff = if what == "hardware record" { + board::record::cross_check(built, file) + } else { + board::words::first_difference(built, file) + }; + if let Some((at, b, f)) = diff { + dev_err!( + dev, + "board data: device-tree {} differs from {} at +{:#x}: built {:#x}, file {:#x}\n", + what, + name, + at, + b, + f + ); + return Err(EINVAL); + } + } + let max_mhz = adt.perf_mhz.iter().copied().max().unwrap_or(0); + dev_info!( + dev, + "board data: {} images from the device tree match {} ({} record words from the file, {} file words left zero), {} mW maximum power, {} MHz top operating point\n", + cfg.name, + name, + board::record::FROM_FILE.len(), + board::record::UNNEEDED.len(), + max_power_mw, + max_mhz + ); + let max_khz = max_mhz.checked_mul(1000).ok_or_else(|| { + dev_err!(dev, "board data: top operating point {} MHz does not fit in kHz\n", max_mhz); + EINVAL + })?; + Ok((hw_img, glob, pwr, max_khz)) +} + +/// Verified board bytes, prepared before any GPU firmware is started. +pub(crate) type BoardImages = (KVVec, KVVec, KVVec, u32); + +/// Check availability, digest, layout and machine-derived tables before firmware start. +/// Keep the verified bytes so a later firmware request cannot change the admitted data. +pub(crate) fn prepare_board( + dev: &device::Device, + cfg: &Config, + adt: &GpuAdt, +) -> Result { + match cfg.board { + hw::Board::Templates => templates(dev, adt), + hw::Board::Blob { name, sha256 } => blob(dev, cfg, adt, name, &sha256), + hw::Board::None => Err(ENODEV), + } +} + +/// Builds the initdata graph. Returns it with its channels and the top DVFS frequency in kHz. +/// Nothing is published here. +pub(crate) fn build( + dev: &device::Device, + cfg: &Config, + adt: &GpuAdt, + objects: &mut Objects, + board_images: BoardImages, +) -> Result<(InitData, Channels, u32)> { + let mut init = InitData::new(); + let fw = Class::Fw; + let layout = cfg.layout; + let hwdata_va = layout.hwdata_va; + + // Owned objects and channels. + let root_obj = canonical(objects, va::ROOT, root::SIZE, fw)?; + let region_a_obj = canonical(objects, va::REGION_A, region_a::SIZE, fw)?; + let runtime_obj = canonical(objects, va::RUNTIME, runtime::SIZE, fw)?; + // Activity records cached; fault info and HardwareDataA timestamps not (T6030), or the + // whole record cached (a layout without a cached prefix). + let cached = if hw::tuning::HWDATA_CACHED { + Class::FwCached + } else { + fw + }; + let hwdata_obj = match layout.hwdata_cached { + Some(prefix) => objects.alloc_split( + Request { + size: layout.hwdata_size, + class: fw, + placement: Placement::At(hwdata_va), + offset: 0, + client: None, + lower: None, + cpu: true, + }, + Some(((hwdata_va as usize & (hw::PAGE as usize - 1)) + prefix, cached)), + )?, + None => canonical(objects, hwdata_va, layout.hwdata_size, cached)?, + }; + let pair_obj = canonical(objects, va::PAIR, pair::SIZE, fw)?; + let small_obj = canonical(objects, va::SMALL, small::SIZE, fw)?; + let c0 = canonical(objects, va::C0, cbuf::C0_SIZE, Class::Shared)?; + let c1 = canonical(objects, va::C1, cbuf::C1_SIZE, Class::Shared)?; + let c3 = canonical(objects, va::C3, cbuf::C3_SIZE, Class::Shared)?; + let globals_obj = canonical(objects, va::GLOBALS, globals::SIZE, fw)?; + let power_obj = canonical(objects, va::POWER, power::SIZE, fw)?; + let control_obj = canonical(objects, va::CONTROL, control::SIZE, fw)?; + let flags_obj = canonical(objects, va::FLAGS, flags::SIZE, fw)?; + let channels = Channels::alloc(objects)?; + // Firmware Device RW aliases for the IOMapping table. + for map in layout.iomaps.iter() { + objects.map_mmio(map.va, map.pa, map.map_bytes)?; + } + + // Board images, verified, then the owned replacements. + let (mut hw_img, mut glob, pwr, max_khz) = board_images; + if matches!(cfg.board, hw::Board::Blob { .. }) { + // This timestamp belongs to initdata creation, not board-data preflight. + let now: u64; + // SAFETY: Reading the architectural counter has no side effects. + unsafe { + core::arch::asm!("mrs {}, cntpct_el0", out(reg) now, options(nomem, nostack, preserves_flags)) + }; + put64(&mut hw_img, hwdata::HWDATA_A + HWDATA_A_INIT_TIMESTAMP, now)?; + } + if hw_img.len() != layout.hwdata_size { + return Err(EINVAL); + } + put64(&mut hw_img, hwdata::TTBAT, adt.ttbs.start)?; + for map in layout.iomaps.iter() { + put64( + &mut hw_img, + hwdata::IOMAPS + hwdata::IOMAP_STRIDE * map.slot as usize + hwdata::IOMAP_VA, + map.va + map.delta, + )?; + } + put64(&mut hw_img, hwdata::TIMESTAMPS, va::TIMESTAMPS)?; + put32(&mut glob, globals::UNK_980, 100)?; + // The device tree's standby time (a machine with a firmware file; the templates' machine + // has none). + let dt_standby = match cfg.board { + hw::Board::Blob { .. } => { + let prop = board::words::PROPS[board::words::STANDBY_TIMER]; + match dev + .of_node() + .ok_or(ENODEV) + .and_then(|n| n.get_property::(prop)) + { + Ok(v) => Some(v), + Err(_) => { + dev_warn!( + dev, + "GPU node has no u32 {}, using the tuned idle standby\n", + prop + ); + None + } + } + } + _ => None, + }; + let (standby_us, standby_src, dt_rejected) = super::power::standby( + super::params::idle_standby_override_us(), + dt_standby, + hw::tuning::IDLE_STANDBY_US, + ); + if dt_rejected { + dev_warn!( + dev, + "apple,idleoff-standby-timer is outside 100..100000 us, ignored\n" + ); + } + dev_info!( + dev, + "idle standby {} us from {}\n", + standby_us, + standby_src.name() + ); + put32(&mut glob, globals::IDLE_STANDBY_US, standby_us)?; + put32( + &mut glob, + globals::IDLE_MIN_CONF, + super::power::permille_f32(super::params::idle_min_conf()), + )?; + put32( + &mut glob, + globals::IDLE_PREDICTIVE, + hw::tuning::IDLE_PREDICTIVE as u32, + )?; + // HardwareDataA at +0x4580: maintained S8 request (the templates' machine; a board image + // from a file carries its own machine's words). + if cfg.board == hw::Board::Templates { + for (offset, value) in [ + (0x2c, 8), + (0x30, 8), + (0x44, 800), + (0x7d8, 800), + (0x7e0, 800), + (0x81c, 800), + ] { + put32(&mut hw_img, hwdata::HWDATA_A + offset, value)?; + } + } + hwdata_obj.write(0, &hw_img)?; + globals_obj.write(0, &glob)?; + power_obj.write(0, &pwr)?; + + // Root. + let r = &root_obj; + r.w64(0x00, layout.root_magic)?; + r.w64(root::REGION_A, va::REGION_A)?; + r.w64(root::RUNTIME, va::RUNTIME)?; + r.w64(root::GLOBALS, va::GLOBALS)?; + r.w32(root::ENABLE, 1)?; + r.write(root::GEOMETRY, &[0x00, 0x40, 14, 3])?; + const SHIFTS: [u8; 3] = [36, 25, 14]; + const ENTRIES: [u16; 3] = [64, 2048, 2048]; + for i in 0..3 { + let at = root::LEVELS + root::LEVEL_STRIDE * i; + let e = ENTRIES[i].to_le_bytes(); + r.write(at, &[8, 14, 14, SHIFTS[i], e[0], e[1], 0x00, 0x40])?; + r.w64(at + 8, 1)?; + r.w64(at + 0x10, 0x3ffffffc000)?; + r.w64(at + 0x18, ((ENTRIES[i] - 1) as u64) << SHIFTS[i])?; + } + r.w64(root::FLAGS, va::FLAGS)?; + r.w64(root::CONTROL, va::CONTROL)?; + r.w64(root::POWER, va::POWER)?; + + // Runtime pointers. + let rt = &runtime_obj; + rt.w64(runtime::HWDATA, hwdata_va)?; + rt.w64(runtime::PAIR, va::PAIR)?; + rt.w64(runtime::PAIR2, va::PAIR)?; + for i in 0..13u64 { + let (state, ring) = if i < 12 { + (va::ch_state(i), va::ch_ring(i)) + } else { + (va::DEVCTL_STATE, va::DEVCTL_RING) + }; + let at = runtime::CHANNELS + runtime::CHANNEL_STRIDE * i as usize; + rt.w64(at, state)?; + rt.w64(at + 8, state + 0x10)?; + rt.w64(at + 0x10, state + 0x20)?; + rt.w64(at + 0x18, ring)?; + } + let rx = [ + (va::EVENT_STATE, va::EVENT_RING), + (va::LOG_STATE, va::LOG_RING), + (va::TRACE_STATE, va::TRACE_RING), + (va::STATS_STATE, va::STATS_RING), + ]; + for (i, (state, ring)) in rx.iter().enumerate() { + rt.w64(runtime::RX + runtime::RX_STRIDE * i, *state)?; + rt.w64(runtime::RX + 8 + runtime::RX_STRIDE * i, *ring)?; + } + rt.w64(runtime::SMALL, va::SMALL)?; + rt.w64( + runtime::TA_ACTIVITY, + hwdata_va + hwdata::TA_ACTIVITY as u64, + )?; + rt.w64( + runtime::FS_ACTIVITY, + hwdata_va + hwdata::FS_ACTIVITY as u64, + )?; + rt.w64( + runtime::COMPUTE_ACTIVITY, + hwdata_va + hwdata::COMPUTE_ACTIVITY as u64, + )?; + rt.w64(runtime::FAULT_INFO, hwdata_va + layout.hwdata_view as u64)?; + rt.w64(runtime::C0, va::C0)?; + rt.w64(runtime::C1, va::C1)?; + rt.w64(runtime::C1_2, va::C1)?; + rt.w64(runtime::C3, va::C3)?; + rt.w64(runtime::C3_2, va::C3)?; + rt.w32(runtime::UNK_2D0, 4)?; + rt.w32(runtime::UNK_3B0, 0xff)?; + rt.w64(runtime::HWDATA_A, hwdata_va + hwdata::HWDATA_A as u64)?; + + // Control and flags. + let c = &control_obj; + c.w32(control::ENABLE, 1)?; + c.w64(control::FWCTL_STATE, va::FWCTL_STATE)?; + c.w64(control::FWCTL_RING, va::FWCTL_RING)?; + c.w32(control::ENABLE2, 1)?; + + init.c1 = Some(c1); + for o in [ + root_obj, + region_a_obj, + pair_obj, + small_obj, + c0, + c3, + power_obj, + ] { + init.others.push(o, GFP_KERNEL)?; + } + init.globals = Some(globals_obj); + init.control = Some(control_obj); + init.hwdata = Some(hwdata_obj); + init.runtime = Some(runtime_obj); + init.flags = Some(flags_obj); + Ok((init, channels, max_khz)) +} diff --git a/drivers/gpu/drm/asahi/g15/job.rs b/drivers/gpu/drm/asahi/g15/job.rs new file mode 100644 index 00000000000000..a360b58987c815 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/job.rs @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Jobs: one per SUBMIT, scheduled by a per-queue DRM scheduler and executed by the engine. +//! +//! - One `drm_sched` scheduler and entity per logical queue ([`Scheduler`], credit limit +//! [`super::hw::sizes::HORIZON_JOBS`] = 16, one credit per job); every input sync is a +//! dependency of the whole job (PER_COMMAND_INPUT_SYNCS holds a fortiori). The host priority +//! lives in [`super::queue::QueueState::priority`] for the engine's pick: with one entity per +//! scheduler, the entity priority orders nothing. +//! - Timeout [`super::hw::tuning::SCHED_TIMEOUT_MS`], always "no hang": the engine's +//! progress-based deadlines own failure. +//! - A failed input refuses unpublished work and reports the error before its fence signals. +//! A foreign device-loss error does not become this VM's sticky hardware-admission failure. +//! - `run` hands the job to the engine ([`super::Firmware::enqueue`], then +//! [`super::Firmware::publish`]) under the device lock and returns the job's fence; FINISHED +//! fences stay in queue order ([`super::fence::Timeline`]). +//! - A failed job latches its VM error before its fence signals ([`Job::complete`]). +//! +//! # For the engine +//! +//! The engine owns an `Arc` from [`super::Firmware::enqueue`] on. It completes the job +//! exactly once with [`Job::complete`] (later calls are ignored), through [`Completions`] +//! collected under the device lock and [`complete_all`] after it is dropped. A job whose storage +//! the firmware may still reference stays in `Engine::retained` (failed jobs until reboot): its +//! [`mmu::VmJobGuard`] keeps the VM's mappings and its VM state keeps the VM's TTBAT slot until +//! the last `Arc` drops. + +use core::sync::atomic::{AtomicBool, Ordering}; +use kernel::{ + bindings, c_str, device, + dma_fence::{Fence, RawDmaFence}, + drm::sched, + prelude::*, + sync::Arc, +}; + +use super::{command::Command, fence::JobFence, hw, queue::QueueState, vm::VmState, Shared}; +use crate::mmu; + +/// A job as the engine sees it. +pub(crate) struct Job { + /// Submission ID (debugging). + pub(crate) id: u64, + /// The submitting queue (priority, service turn, horizon history). + pub(crate) queue: Arc, + /// The job's VM (TTBAT slot, status). + pub(crate) vm: Arc, + /// Validated commands, in submission order (at most 64). + pub(crate) commands: KVec, + /// The job's hardware fence. + pub(crate) fence: JobFence, + /// The engine's bookkeeping; `progress.signaled` makes [`Job::complete`] act once. + pub(crate) progress: super::engine::Progress, + /// The timestamp buffers the commands name (their arena VAs stay mapped while the job lives). + _timestamps: KVec>, + /// Retains the VM's mappings (deferred unmaps, deferred VM close) while the firmware may + /// access them. + _guard: mmu::VmJobGuard, + /// Pushed to the scheduler: from now on the job counts as submitted work of its VM. + accepted: AtomicBool, + /// Handed to the engine (or refused at `run`): the scheduler no longer cancels it. + started: AtomicBool, +} + +impl Job { + pub(crate) fn new( + id: u64, + queue: Arc, + vm: Arc, + commands: KVec, + fence: JobFence, + timestamps: KVec>, + guard: mmu::VmJobGuard, + ) -> Result> { + let progress = super::engine::Progress::new(commands.len()); + Ok(Arc::new( + Self { + id, + queue, + vm, + commands, + fence, + progress, + _timestamps: timestamps, + _guard: guard, + accepted: AtomicBool::new(false), + started: AtomicBool::new(false), + }, + GFP_KERNEL, + )?) + } + + /// Completes the job: latches the VM status on failure, then signals the fence (after every + /// earlier job of the queue). Called by the engine, without the device lock. Only the first + /// call has an effect. + /// + /// Any failure makes the VM's error sticky: later SUBMITs, QUEUE_CREATEs and mapping changes + /// of the VM are refused (EIO), and mapping changes stay blocked while the job lives (the + /// engine retains a job the firmware may still reference). + #[track_caller] + pub(crate) fn complete(&self, result: Result) { + self.finish(result, true); + } + + /// Completes the job; `engine`: the engine had it, so a failure quarantines its mappings. + /// ECANCELED (never-run work at queue teardown) is only reported, not sticky. + #[track_caller] + fn finish(&self, result: Result, engine: bool) { + if self.progress.signaled.swap(true, Ordering::AcqRel) { + return; + } + if let Err(error) = result { + if error == ECANCELED { + self.vm.status.report_failure(error); + } else { + if engine { + // Before the error fence becomes visible (G17's rule). + self._guard.quarantine(); + } + self.vm.status.record(error); + } + } + self.fence.signal(result); + } + + /// Reports an input failure without quarantining or poisoning a healthy consumer VM. + fn finish_dependency(&self, error: Error) { + if self.progress.signaled.swap(true, Ordering::AcqRel) { + return; + } + self.vm.status.report_failure(error); + self.fence.signal(Err(error)); + } + + /// Hands the job to the engine, or completes it before publication on GPU/input failure. + fn start(self: &Arc, shared: &Arc, inputs: &[Fence]) { + self.started.store(true, Ordering::Release); + if shared.crashed.load(Ordering::Acquire) { + self.finish(Err(EIO), false); + return; + } + // SAFETY: Each retained fence owns its pointer for this read. drm_sched has + // waited for every dependency; inspect errors even while this VM is healthy. + let failed = inputs + .iter() + .map(|fence| unsafe { bindings::dma_fence_get_status(fence.raw()) }) + .find(|&status| status < 0); + if let Some(status) = failed { + let error = Error::from_errno(status); + if self.vm.status.get() != 0 { + // Preserve the existing own-failed-VM completion semantics. + self.finish(Err(error), false); + } else { + self.finish_dependency(crate::g17::inherited_error(error)); + } + return; + } + // `Shared::submit`: enqueue, publish and rearm under the device lock, + // completions after it. + if let Err(error) = shared.submit(self.clone()) { + // An engine that refuses work is a device failure for the job's VM. + self.finish(Err(if error == ENODEV { EIO } else { error }), false); + } + } + + /// Cancels a job the scheduler never ran (queue teardown, or a failed submission). + fn cancel_unstarted(&self) { + if self.started.swap(true, Ordering::AcqRel) { + return; + } + if self.accepted.load(Ordering::Acquire) { + self.finish(Err(ECANCELED), false); + } else if !self.progress.signaled.swap(true, Ordering::AcqRel) { + // A refused submission's job: its fence orders nothing and was never published. + self.fence.signal(Err(ECANCELED)); + } + } +} + +/// Jobs retired or failed under the device lock, completed after it is dropped. +pub(crate) type Completions = KVec<(Arc, Result)>; + +/// Completes jobs in order. +#[track_caller] +pub(crate) fn complete_all(done: Completions) { + for (job, result) in done { + job.complete(result); + } +} + +/// The scheduler's view of a job. +struct SchedJob { + job: Arc, + shared: Arc, + /// The input fences, kept for the dependency-error check at `run`. + inputs: KVec, +} + +impl sched::JobImpl for SchedJob { + type TimeoutData = (); + + const MODULE: Option<&'static kernel::ThisModule> = Some(&crate::THIS_MODULE); + + fn timeout_data(&self) {} + + fn run(job: &mut Self) -> Result> { + let fence = job.job.fence.fence(); + job.job.start(&job.shared, &job.inputs); + Ok(Some(fence)) + } + + /// The engine's own deadlines own failure; late delivery is not a hang. + fn timed_out(_data: &mut (), _finished: bool) -> sched::Status { + sched::Status::NoHang + } + + fn cancel(job: &mut Self) { + job.job.cancel_unstarted(); + } +} + +impl Drop for SchedJob { + fn drop(&mut self) { + // Entity teardown frees jobs it never ran without calling `cancel`. + self.job.cancel_unstarted(); + } +} + +/// The scheduler and entity of one logical queue. +pub(crate) struct Scheduler { + // Dropped first: the entity flush waits until every queued job has run (QUEUE_DESTROY + // drains), and only then the scheduler is finalized. + entity: sched::Entity, + _scheduler: sched::Scheduler, +} + +impl Scheduler { + pub(crate) fn new(dev: &device::Device) -> Result { + let scheduler = sched::Scheduler::new( + dev, + 1, + hw::sizes::HORIZON_JOBS, + 0, + hw::tuning::SCHED_TIMEOUT_MS, + c_str!("asahi_g15"), + )?; + // With one run queue, only the kernel priority is valid. + let entity = sched::Entity::new(&scheduler, sched::Priority::Kernel)?; + Ok(Self { + entity, + _scheduler: scheduler, + }) + } + + /// Pushes a job that waits for `inputs`. On failure the job is cancelled (not counted as + /// submitted work of its VM) and the error is returned. + pub(crate) fn push( + &mut self, + job: Arc, + shared: Arc, + inputs: KVec, + ) -> Result { + let mut dependencies = KVec::with_capacity(inputs.len(), GFP_KERNEL)?; + for fence in inputs.iter() { + dependencies.push(fence.clone(), GFP_KERNEL)?; + } + let handle = job.clone(); + let mut pending = self.entity.new_job( + 1, + SchedJob { + job, + shared, + inputs, + }, + )?; + for fence in dependencies { + pending.add_dependency(fence)?; + } + let armed = pending.arm(); + handle.accepted.store(true, Ordering::Release); + armed.push(); + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs new file mode 100644 index 00000000000000..75d3ecc30ffe5a --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -0,0 +1,662 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G15 GPU support (T6030, M3 Pro: J514S, J516S; firmware RTKit 2419, the macOS 14.7-14.8 stub). +//! +//! G15 firmware is *classic*: one ring per engine (TA, FS, compute) and ordering expressed by +//! in-ring barrier records that wait on another queue's stamp, unlike the G17 kick-ring/QID +//! model. The boot loader leaves the firmware loaded; this driver identifies the exact build, +//! adopts the running PPL handoff, builds the 49-object initdata graph from this machine's ADT +//! and brings the firmware to READY. All logical queues and VMs share one persistent compute +//! graph and one render graph; the commands of a submission are encoded into compute and pass +//! slots and published as *prefixes* on the firmware's queues, then retired on their stamps. +//! Everything firmware-visible that a failed command may still reference is retained until +//! reboot. +//! +//! # Plugging into the shared driver +//! +//! - [`Driver`] is a separate platform driver. T6030 has a module alias; its probe must wait +//! for the native display and PMP supplier before booting firmware. T6031 retains explicit +//! module loading. It calls [`crate::driver::AsahiPlatformDriver::probe_g15`]. +//! - [`Gpu`] implements [`crate::gpu::Gpu`]: GET_PARAMS identity, VM creation (`new_vm`), +//! queues (`new_queue`, see [`queue`]) and timestamp buffers. +//! - User VMs are shared-layer [`mmu::Vm`]s on a [`mmu::Uat::new_adopted`] UAT with tracked +//! status ([`mmu::Vm::with_tracked_status`]); `file.rs` handles VM_BIND, GEM, syncobjs, +//! VM_STATUS(_MIRROR) and MADVISE. +//! +//! # Locking +//! +//! [`Shared::state`] is the device lock. It serializes all firmware-visible publication, the +//! device-control ring and every firmware-shared object, including the bounded waits for the +//! firmware that publication, recovery and the device controls need (up to 2 s). Fences are +//! signalled after dropping it ([`job::Completions`]). Lock order: `Shared::state` -> UAT shared +//! state -> VM exec lock -> GEM reservation. The RTKit receive callbacks run in interrupt +//! context and only set atomics and queue the poll work. +//! +//! # Module structure +//! +//! - Platform, firmware boot and UAT handoff: `boot`, `hw`, `adt`, `identity`, `regs`, `uat`, +//! `object`, `board`, `initdata`, `channel`, `event`, `fw/{mod,initdata,channels}`. +//! - Submission engine: `engine`, `encode`, `slots`, `graph`, `poll`, `fw/{work,graph}`. +//! - Recovery, parameter buffer and power: `recovery`, `pools`, `power`, `fw/buffer`. +//! - UAPI glue and VM integration: `queue`, `command`, `gate`, `job`, `fence`, `vm`, +//! `timestamp`, `params`, and the hooks in the shared driver (`file.rs`, `gem.rs`, `gpu.rs`, +//! `mmu.rs`, `pgtable.rs`). + +mod adt; +mod board; +mod boot; + +// One admission rule for the generation mappings and shared adopted UAT. +pub(crate) use boot::glue::memory_mode; +mod channel; +mod command; +mod encode; +mod engine; +mod event; +mod fence; +pub(crate) mod fw; +mod gate; +mod graph; +pub(crate) mod hw; +mod identity; +mod initdata; +mod job; +mod object; +mod params; +mod poll; +mod pools; +mod power; +mod queue; +mod recovery; +mod regs; +mod slots; +mod timestamp; +mod uat; +mod vm; +mod wire; + +use core::any::Any; +use core::ops::Range; +use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; + +use kernel::{ + c_str, + device::{self, Core}, + impl_has_delayed_work, new_delayed_work, new_mutex, of, platform, + prelude::*, + sync::{aref::ARef, Arc, Mutex}, + time::hrtimer::{ArcHrTimerHandle, HrTimer}, + uapi, + workqueue::{DelayedWork, WorkItem}, +}; + +use crate::driver::AsahiDrmDevice as AsahiDevice; +use crate::{alloc, gem, gpu, mmu}; + +/// Name of the G15 platform driver. + +/// GPU generation reported to userspace. +pub(crate) const GPU_GENERATION: u32 = 15; + +/// Static configuration of a SoC with a G15 GPU. +pub(crate) struct Config { + /// SoC and GPU name, for the log. + pub(crate) name: &'static str, + /// SoC identifier reported to userspace. + pub(crate) chip_id: u32, + /// GPU variant reported to userspace. + pub(crate) gpu_variant: crate::hw::GpuVariant, + /// GPU revision reported to userspace. + pub(crate) gpu_revision: u32, + /// Input address bits translated by each UAT root. + pub(crate) uat_ias: u32, + /// Output (physical) address bits of the UAT. + pub(crate) uat_oas: u32, + /// Clusters and cores per cluster. + pub(crate) num_clusters: u32, + pub(crate) num_cores_per_cluster: u32, + /// Qualified identification register values. + pub(crate) hw_ids: &'static [hw::HwId], + /// Qualified firmware builds. + pub(crate) firmware: &'static [hw::FirmwareBuild], + /// Machine compatible this SoC's boards carry. + pub(crate) machine: &'static CStr, + /// Where regions, segments and performance states come from, and how the GPU is powered. + pub(crate) platform: hw::Platform, + /// Initdata placement and sizes that differ between firmware builds. + pub(crate) layout: &'static hw::Layout, + /// Board images. + pub(crate) board: hw::Board, + /// Compute register values that scale with the cluster count. + pub(crate) compute: hw::ComputeRegs, +} + +/// Core slots of a SoC: the width of its enabled-core mask. +impl Config { + pub(crate) const fn core_slots(&self) -> u32 { + self.num_clusters * self.num_cores_per_cluster + } +} + +/// OF match table of the G15 platform driver. +const OF_TABLE: kernel::device_id::IdArray = + kernel::device_id::IdArray::new([ + ( + of::DeviceId::new(c_str!("apple,agx-t6030")), + &hw::t6030::CONFIG, + ), + ( + of::DeviceId::new(c_str!("apple,agx-t6031")), + &hw::t6031::CONFIG, + ), + ]); + +// T6030 probe admission requires the native display and PMP supplier before +// firmware starts. T6031 retains explicit loading until it has an equivalent +// display-order admission gate. +kernel::of_device_table!( + AUTOLOAD_OF_TABLE, + MODULE_OF_TABLE_G15, + (), + [(of::DeviceId::new(c_str!("apple,agx-t6030")), ())] +); + +/// The G15 platform adapter: the shared DRM registration probed through +/// [`crate::driver::AsahiPlatformDriver::probe_g15`]. +/// +/// `None` after a probe that failed once the firmware had been touched: the device stays bound +/// (unbinding would detach and power off the GFX domain under the running firmware), the +/// firmware session is retained until reboot and no DRM device exists. +#[pin_data] +pub(crate) struct Driver<'bound> { + _driver: Option>, +} + +impl platform::Driver for Driver<'_> { + type IdInfo = &'static Config; + type Data<'bound> = Driver<'bound>; + const OF_ID_TABLE: Option> = Some(&OF_TABLE); + + /// The firmware session cannot be stopped once started. + fn suppress_bind_attrs() -> bool { + true + } + + fn probe<'bound>( + pdev: &'bound platform::Device>, + info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit, Error> + 'bound { + // `Device::set_drvdata` allocates its KBox before running this initializer. + // Keep every firmware-visible action inside it: otherwise an allocation failure + // after probe_g15 started firmware would return an unbound device. + try_pin_init!(Driver { + _driver: { + if !MODULE_READY.load(Ordering::Acquire) { + return Err(EPROBE_DEFER); + } + let cfg = *info.ok_or(ENODEV)?; + dev_info!(pdev.as_ref(), "G15: probing ({})\n", cfg.name); + match crate::driver::AsahiPlatformDriver::probe_g15(pdev, cfg) { + Ok(driver) => Some(driver), + Err(error) if boot::glue::retained() => { + dev_err!( + pdev.as_ref(), + "G15: probe failed after the firmware start ({:?}); device kept bound, firmware retained until reboot\n", + error + ); + None + } + Err(error) => return Err(error), + } + }, + }) + } + +} + +/// Firmware starts only after every fallible module/driver registration has succeeded. +/// A deferred probe racing the final activation sees the Release/Acquire publication. +static MODULE_READY: AtomicBool = AtomicBool::new(false); + +/// Last, infallible module initializer: enable native probes and retry this adapter. +/// No fallible module initialization may follow this call. +pub(crate) fn activate() { + MODULE_READY.store(true, Ordering::Release); + // SAFETY: Both pinned platform registrations are fully initialized and remain owned + // by DriverModule. The C helper borrows their live driver pointer only for this call. + unsafe { boot::glue::asahi_g15_reprobe() }; +} + +/// Work item ID of the poll work. +const POLL_WORK: u64 = 0; + +/// Device state shared with the RTKit callbacks and the poll work. +#[pin_data] +pub(crate) struct Shared { + /// Reserved host logical queues, shared across every file and VM on this GPU. + pub(crate) logical_queues: AtomicU32, + pub(crate) dev: ARef, + /// Latched fail-stop: every VM fails with EIO until reboot. + pub(crate) crashed: AtomicBool, + /// Set by the firmware's EP 0x20 event message; consumed by the poll work. + pub(crate) evented: AtomicBool, + // --- RTKit callback state and a retained failed session. --- + /// The first latched error, as a negative errno. + pub(crate) error: AtomicI32, + /// The RTKit receive callbacks may queue the poll work. + pub(crate) started: AtomicBool, + /// Firmware DATA, where the only RTKit buffer accepted lies. + pub(crate) data: Range, + /// Physical address of the accepted RTKit buffer, 0 before. + pub(crate) rtkit_buffer: AtomicU64, + /// A firmware session whose start or backend start failed: retained, rings still drained. + pub(crate) orphaned: AtomicBool, + #[pin] + pub(crate) orphan: Mutex>>, + #[pin] + pub(crate) poll: DelayedWork, + // --- The completion/repoll hrtimer and the handle of its current expiry (dropping it + // cancels the expiry; see `Shared::rearm`). --- + #[pin] + pub(crate) resnap: HrTimer, + #[pin] + pub(crate) resnap_handle: Mutex>>, + /// The device lock. `None` before boot completes. + #[pin] + pub(crate) state: Mutex>>, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Shared { self.poll } +} + +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + if this.orphaned.load(Ordering::Acquire) { + this.drain_orphan(); + return; + } + this.run_poll(); + } +} + +impl Shared { + /// Queues the poll work immediately. Callable from any context. + pub(crate) fn kick(self: &Arc) { + self.evented.store(true, Ordering::Release); + // `mod_delayed_work(.., 0)` so that a kick also runs a poll whose 1-jiffy backup is + // pending (a plain enqueue is refused then). + self.poll_now(); + } + + /// Latches the fail-stop state. + pub(crate) fn fail_stop(&self, error: Error) { + let _ = + self.error + .compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire); + if !self.crashed.swap(true, Ordering::AcqRel) { + dev_err!( + self.dev.as_ref(), + "G15: fail-stop ({:?}); GPU unusable until reboot\n", + error + ); + } + } + + /// The latched error, if any. + pub(crate) fn check(&self) -> Result { + if !self.crashed.load(Ordering::Acquire) { + return Ok(()); + } + match self.error.load(Ordering::Acquire) { + 0 => Err(EIO), + e => Err(Error::from_errno(e)), + } + } + + /// Keeps a firmware session that did not complete until reboot; its receive rings stay + /// drained by the poll work. + pub(crate) fn orphan(&self, orphan: boot::Orphan) { + let mut slot = self.orphan.lock(); + match KBox::::new_uninit(GFP_KERNEL) { + Ok(storage) => { + *slot = Some(KBox::write(storage, orphan)); + self.orphaned.store(true, Ordering::Release); + } + Err(_) => { + // Allocation must not consume the live session: KBox::new would drop it + // on failure. Keep its mappings and backing even without ring draining. + core::mem::forget(orphan); + dev_err!( + self.dev.as_ref(), + "G15: cannot allocate failed-session storage; session leaked without ring draining\n" + ); + } + } + } + + /// Drains the receive rings of an orphaned session. + fn drain_orphan(&self) { + if let Some(orphan) = self.orphan.lock().as_deref_mut() { + let _ = orphan.drain(); + } + } +} + +/// Everything that exists while the firmware runs, under the device lock. +/// +/// Nothing in here is ever freed while the firmware can reach it: a G15 firmware session cannot +/// be stopped, so dropping this structure leaks the firmware-visible parts on purpose +/// ([`Gpu::retain`]). +pub(crate) struct Firmware { + /// The SoC configuration. + pub(crate) cfg: &'static Config, + /// RTKit, MMIO, regions, the adopted UAT and the host window. + pub(crate) session: boot::Session, + /// The initdata graph and its live words (Globals, Control, HardwareData, ...). + pub(crate) init: initdata::InitData, + /// Firmware objects: the firmware VA allocator and the retained objects. + pub(crate) objects: object::Objects, + /// Submit channels, the device-control ring and the receive rings. + pub(crate) channels: channel::Channels, + /// Decoded firmware events (stage counters, last error, growth requests). + pub(crate) events: event::Events, + /// The compute and render graphs. + pub(crate) graph: graph::Graphs, + /// Compute slots, pass slots and clustering buffers. + pub(crate) slots: slots::Slots, + /// Pending jobs, prefixes, horizons and flights. + pub(crate) engine: engine::Engine, + /// Halt/resume, kills, deadlines and fail-stop. + pub(crate) recovery: recovery::Recovery, + /// Render UMA/PB allocators, their spare set and parameter-buffer growth. + pub(crate) pools: pools::Pools, + /// Live VMs and their exclusive TTBAT slots, and the client aliases of every user VM. + pub(crate) vms: Arc, +} + +/// A G15 GPU. +pub(crate) struct Gpu { + cfg: &'static Config, + /// Identification read at boot. + pub(crate) id: regs::Identity, + /// Highest firmware performance state, kHz. + pub(crate) max_frequency_khz: u32, + ids: gpu::SequenceIDs, + pub(crate) shared: Arc, + /// The adopted UAT, for creating and binding user VMs without the device lock. + pub(crate) uat: Arc, +} + +impl Gpu { + /// Admits and boots a G15 GPU: identity checks, PMP AGX vote, RTKit, UAT handoff, initdata, + /// READY, then the compute and render graphs. On success the module is pinned: the + /// firmware session lasts until reboot. + pub(crate) fn new( + pdev: &platform::Device>, + dev: &AsahiDevice, + cfg: &'static Config, + ) -> Result> { + // Admission (probe-time checks), then the firmware start to READY. + let admitted = boot::admit(pdev, dev, cfg)?; + // Admission holds the GFX domain. A failure before the firmware is touched gives it + // back (a start that touched the firmware keeps it, retained until reboot). + let unretained = |error: Error| -> Error { + if !boot::glue::retained() { + boot::glue::release_power(dev.as_ref().as_ref()); + } + error + }; + let data = admitted.adt.data.clone(); + let shared = Arc::pin_init( + pin_init!(Shared { + logical_queues: AtomicU32::new(0), + dev: dev.as_ref().as_ref().into(), + crashed: AtomicBool::new(false), + evented: AtomicBool::new(false), + error: AtomicI32::new(0), + started: AtomicBool::new(false), + data, + rtkit_buffer: AtomicU64::new(0), + orphaned: AtomicBool::new(false), + orphan <- new_mutex!(None, "g15::Shared::orphan"), + poll <- new_delayed_work!("g15::Shared::poll"), + resnap <- HrTimer::new(), + resnap_handle <- new_mutex!(None, "g15::Shared::resnap_handle"), + state <- new_mutex!(None, "g15::Shared::state"), + }), + GFP_KERNEL, + ) + .map_err(unretained)?; + let booted = boot::start(admitted, dev, cfg, &shared).map_err(unretained)?; + let uat = booted.session.uat(); + let (id, max_frequency_khz) = (booted.id, booted.max_frequency_khz); + // The backend: graphs, slots, pools, engine, recovery and VM registry. + let firmware = Firmware::start_backend(dev, cfg, booted, &shared)?; + *shared.state.lock() = Some(firmware); + // The engine's statistics file (a debugfs failure does not fail the probe). + if let Err(error) = shared.start_engine() { + dev_warn!(dev.as_ref(), "G15: no asahi-g15 debugfs ({:?})\n", error); + } + let gpu = Arc::new( + Gpu { + cfg, + id, + max_frequency_khz, + ids: Default::default(), + shared, + uat, + }, + GFP_KERNEL, + )?; + gpu.retain(); + Ok(gpu) + } + + /// Keeps the firmware session and this module alive until reboot. + /// + /// Takes the module reference once. Nothing firmware-reachable is freed on any path: the + /// RTKit callbacks hold [`Shared`], which holds the [`Firmware`] (or the [`boot::Orphan`] of a + /// failed start) until reboot. + pub(crate) fn retain(&self) { + boot::glue::retain_module(); + } +} + +impl Firmware { + /// Builds the graphs and the engine after READY. On failure the firmware stays at READY, + /// retained as an orphan of `shared`. + fn start_backend( + dev: &AsahiDevice, + cfg: &'static Config, + booted: boot::Booted, + shared: &Arc, + ) -> Result> { + let boot::Booted { + session, + init, + mut objects, + channels, + events, + .. + } = booted; + dev_info!( + dev.as_ref(), + "G15: firmware at READY, starting the backend\n" + ); + let orphan = |session: boot::Session, + objects: object::Objects, + channels: channel::Channels, + init: initdata::InitData, + events: event::Events, + error: Error| + -> Error { + dev_err!( + dev.as_ref(), + "G15: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.orphan(boot::Orphan { + session, + _objects: objects, + channels: Some(channels), + _init: Some(init), + events, + }); + error + }; + let backend = (|| -> Result<_> { + let graph = graph::Graphs::new(dev, &mut objects)?; + let slots = slots::Slots::new(&mut objects)?; + let pools = pools::Pools::new(dev, &mut objects)?; + let vms = vm::Registry::new()?; + let slot = KBox::::new_uninit(GFP_KERNEL)?; + Ok((graph, slots, pools, vms, slot)) + })(); + let (graph, slots, pools, vms, slot) = match backend { + Ok(backend) => backend, + Err(e) => return Err(orphan(session, objects, channels, init, events, e)), + }; + let mut firmware = KBox::write( + slot, + Firmware { + cfg, + session, + init, + objects, + channels, + events, + graph, + slots, + engine: engine::Engine::new(), + recovery: recovery::Recovery::new(), + pools, + vms, + }, + ); + if let Err(e) = firmware.init_graphs() { + let Firmware { + session, + init, + objects, + channels, + events, + .. + } = KBox::into_inner(firmware); + return Err(orphan(session, objects, channels, init, events, e)); + } + Ok(firmware) + } +} + +impl gpu::Gpu for Gpu { + fn stats_snapshot(&self) -> Option> { + None + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn arc_as_any(self: Arc) -> Arc { + self as Arc + } + + fn manager(&self) -> Option<&dyn gpu::GpuManager> { + None + } + + fn init(&self) -> Result { + Ok(()) + } + + fn ids(&self) -> &gpu::SequenceIDs { + &self.ids + } + + fn is_crashed(&self) -> bool { + self.shared.crashed.load(Ordering::Acquire) + } + + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { + params::fill(self, params) + } + + fn feature_flags(&self) -> u64 { + params::feature_flags() + } + + fn supports_vm_status(&self) -> bool { + true + } + + fn queue_limits(&self) -> Option { + Some(params::queue_limits()) + } + + fn base_clock_hz(&self) -> u32 { + let frequency: u64; + // SAFETY: CNTFRQ_EL0 is a read-only register containing the architectural counter rate. + unsafe { core::arch::asm!("mrs {frequency}, CNTFRQ_EL0", frequency = out(reg) frequency) }; + frequency as u32 + } + + fn uat_geometry(&self) -> mmu::UatGeometry { + mmu::UatGeometry { + ias: self.cfg.uat_ias, + oas: self.cfg.uat_oas, + } + } + + fn user_range(&self) -> Range { + hw::USER_RANGE + } + + fn tracked_submission(&self) -> bool { + true + } + + fn soft_faults(&self) -> bool { + false + } + + fn prepare_new_objects(&self) -> bool { + true + } + + // VM_BIND operations per call at most. + fn bind_batch_limit(&self) -> Option { + Some(params::MAX_BINDS) + } + + fn vm_closed(&self) { + vm::closed(self) + } + + fn new_vm(&self, kernel_range: Range) -> Result { + vm::new_vm(self, kernel_range) + } + + fn new_queue( + &self, + vm: mmu::Vm, + _ualloc: Arc>, + _ualloc_priv: Arc>, + priority: u32, + usc_exec_base: u64, + ) -> Result> { + Ok(KBox::new( + queue::Queue::new(self, vm, priority, usc_exec_base)?, + GFP_KERNEL, + )?) + } + + fn map_timestamp_buffer( + &self, + bo: gem::ObjectRef, + range: Range, + ) -> Result { + timestamp::map(self, bo, range) + } +} diff --git a/drivers/gpu/drm/asahi/g15/object.rs b/drivers/gpu/drm/asahi/g15/object.rs new file mode 100644 index 00000000000000..227d8a8ac8e3b0 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/object.rs @@ -0,0 +1,529 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Firmware objects and their cache classes. +//! +//! Each object is a GEM kernel object (write-combined CPU mapping) mapped into the host window +//! at a fixed VA or in [`super::hw::va::FW_ALLOC`] (a bump allocator with an unmapped guard page +//! after each object), with these optional aliases of the same pages: +//! +//! - a context-0 lower alias (`Uat::kernel_lower_vm`, [`super::hw::pte::LOWER`]); +//! - a client alias at a fixed GVA in every user VM: recorded here ([`Objects::clients`]) and +//! installed by `vm.rs` as driver mappings when the VM is created. +//! +//! The backing is populated and DMA-mapped before any CPU view exists: on this non-DMA-coherent +//! device the DMA mapping cleans the freshly zeroed pages' cacheable alias to the point of +//! coherency, so no dirty line can later overwrite what the host writes through the +//! write-combined view. The firmware-side leaf word is chosen by [`Class`] and must be exact +//! ([`Objects::self_check`] proves the shared page-table code writes it). Host accesses +//! after publication use single, aligned volatile accesses (`r32`/`w32`/`w64`). Objects are +//! retained until reboot: nothing the firmware can reach is ever unmapped or freed. + +mod geometry; + +use core::ptr::NonNull; + +use kernel::io::Io; +use kernel::{drm::gem::BaseObject, prelude::*, sync::aref::ARef, sync::Arc}; + +use super::hw::{self, pte}; +use super::regs::wmb; +use super::uat; +use crate::driver::AsahiDrmDevice as AsahiDevice; +use crate::{gem, mmu}; + +/// Firmware-side cache class of an object (the leaf words of [`super::hw::pte`]). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Class { + /// Firmware-only, AttrIndex 2. + Fw, + /// Firmware-only, ASC-cached (AttrIndex 0). Never for rings or anything the host writes + /// after the firmware first touched it. + FwCached, + /// Firmware and GPU, AttrIndex 2. + Shared, + /// Firmware and GPU, ASC-cached. + SharedCached, + /// Firmware device mapping. + Mmio, +} + +impl Class { + /// The exact firmware leaf word of this class. + pub(crate) const fn pte(self) -> u64 { + match self { + Class::Fw => pte::FW, + Class::FwCached => pte::FW_CACHED, + Class::Shared => pte::SHARED, + Class::SharedCached => pte::SHARED_CACHED, + Class::Mmio => pte::MMIO, + } + } +} + +/// Where an object is placed in the host window. +pub(crate) enum Placement { + /// At this firmware VA (canonical initdata objects). The payload starts at this VA; the + /// object starts at its page. + At(u64), + /// Anywhere in the firmware allocator window, followed by an unmapped guard page. + Anywhere, +} + +/// A firmware object. +/// +/// # Invariants +/// +/// `cpu`, if set, points to a live write-combined kernel mapping of the whole backing (`bytes` +/// bytes), kept alive by `backing`. +pub(crate) struct FwObject { + /// Firmware (host-window) VA of byte 0 of the payload. + pub(crate) va: u64, + /// Client GVA of byte 0, if aliased into every user VM. + pub(crate) gva: Option, + /// Payload size. + pub(crate) size: usize, + /// Payload offset inside the first page. + offset: usize, + /// Mapped bytes: the payload rounded up to whole pages. + bytes: usize, + /// Client alias leaf word. + client_leaf: u64, + cpu: Option>, + /// Host-window and lower mappings; never dropped while the firmware runs. + _mappings: KVec, + /// Holds the pages for the device. + _sgt: HeldPages, + backing: gem::ObjectRef, +} + +// SAFETY: The object only refers to kernel memory shared with the firmware; every host access +// goes through raw pointers with volatile or byte-copy semantics, serialized by the device lock +// where the protocol needs it. +unsafe impl Send for FwObject {} +// SAFETY: See `Send`. +unsafe impl Sync for FwObject {} + +impl FwObject { + /// Pointer to payload byte `offset` for `len` bytes, bounded by the mapped pages. + fn ptr(&self, offset: usize, len: usize) -> Result<*mut u8> { + let cpu = self.cpu.ok_or(EINVAL)?; + let at = self.offset.checked_add(offset).ok_or(EINVAL)?; + if at.checked_add(len).ok_or(EINVAL)? > self.bytes { + return Err(EINVAL); + } + // SAFETY: By the type invariant `cpu` maps `bytes` bytes; `at + len` was checked. + Ok(unsafe { cpu.as_ptr().add(at) }) + } + + /// Copies bytes into the object before it is published, or into host-owned words. + pub(crate) fn write(&self, offset: usize, bytes: &[u8]) -> Result { + let p = self.ptr(offset, bytes.len())?; + // SAFETY: `p` is valid for `bytes.len()` bytes of the object's mapping, which no Rust + // reference aliases. + unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()) }; + Ok(()) + } + + /// Fills bytes. + pub(crate) fn fill(&self, offset: usize, value: u8, len: usize) -> Result { + let p = self.ptr(offset, len)?; + // SAFETY: As for `write`. + unsafe { core::ptr::write_bytes(p, value, len) }; + Ok(()) + } + + /// 32-bit store: a single aligned access, or bytes at an unaligned offset. + pub(crate) fn w32(&self, offset: usize, value: u32) -> Result { + let p = self.ptr(offset, 4)?; + if p as usize % 4 == 0 { + // SAFETY: `p` is valid and aligned for a u32. + unsafe { (p as *mut u32).write_volatile(value.to_le()) }; + Ok(()) + } else { + self.write(offset, &value.to_le_bytes()) + } + } + + /// 64-bit store: a single aligned access, or bytes at an unaligned offset. + pub(crate) fn w64(&self, offset: usize, value: u64) -> Result { + let p = self.ptr(offset, 8)?; + if p as usize % 8 == 0 { + // SAFETY: `p` is valid and aligned for a u64. + unsafe { (p as *mut u64).write_volatile(value.to_le()) }; + Ok(()) + } else { + self.write(offset, &value.to_le_bytes()) + } + } + + /// 32-bit load of a firmware- or GPU-written word: a single aligned access, or an unaligned + /// load (words of the unaligned canonical objects). + pub(crate) fn r32(&self, offset: usize) -> Result { + let p = self.ptr(offset, 4)?; + // SAFETY: `p` is valid for 4 bytes; Normal non-cacheable memory permits an unaligned + // load. + Ok(u32::from_le(unsafe { + if p as usize % 4 == 0 { + (p as *const u32).read_volatile() + } else { + (p as *const u32).read_unaligned() + } + })) + } + + /// Mapped bytes (the payload offset plus size, rounded up to pages). + pub(crate) fn bytes(&self) -> usize { + self.bytes + } + + /// The client alias: GVA of the first page and its leaf word. `vm.rs` maps [`Self::gem`] + /// there in every user VM. + pub(crate) fn client(&self) -> Option<(u64, u64)> { + self.gva + .map(|gva| (gva - self.offset as u64, self.client_leaf)) + } + + /// The backing GEM object, for aliases in other address spaces. + pub(crate) fn gem(&self) -> ARef { + self.backing.gem.clone() + } +} + +/// The pinned pages of a firmware-visible object, as [`gpu_backing`] returns them. +pub(crate) type HeldPages = ARef; + +// The host tests of the geometry use the hardware's page size and page-frame mask. +static_assert!(geometry::PAGE == hw::PAGE && geometry::PA_MASK == hw::PA_MASK); + +/// A zeroed GEM kernel object of exactly `bytes` (a nonzero number of whole pages, EINVAL +/// otherwise), populated and DMA-mapped. Its DMA segments must back exactly `bytes` with pages +/// the UAT can name ([`geometry::backing_ok`], EPERM otherwise). The DMA mapping cleans the +/// freshly zeroed pages' cacheable alias to the point of coherency, before any mapping of them +/// exists. +pub(crate) fn gpu_backing(dev: &AsahiDevice, bytes: usize) -> Result<(gem::ObjectRef, HeldPages)> { + if bytes == 0 || bytes as u64 & (hw::PAGE - 1) != 0 { + return Err(EINVAL); + } + let backing = gem::new_kernel_object_wc(dev, bytes)?; + if backing.gem.size() != bytes { + return Err(EINVAL); + } + // SAFETY: Backing is populated only while probing the bound G15 platform device, + // or through its retained session. Manual unbind is suppressed for this adapter. + let sgt = gem::held_sg_table(&backing.gem, unsafe { dev.as_ref().as_ref().as_bound() })?; + let segments = sgt + .iter() + .map(|range| (range.dma_address() as u64, range.dma_len() as u64)); + if !geometry::backing_ok(bytes as u64, hw::PAGE, hw::PA_MASK, segments) { + return Err(EPERM); + } + let held = backing.gem.clone(); + Ok((backing, held)) +} + +/// Allocation request. +pub(crate) struct Request { + pub(crate) size: usize, + pub(crate) class: Class, + pub(crate) placement: Placement, + /// Payload offset inside the first page (e.g. work images at +0x3760). Ignored + /// for [`Placement::At`], whose VA gives it. + pub(crate) offset: usize, + /// Client alias GVA of the page holding the payload, and its leaf word + /// ([`pte::LEAF_NC`], [`pte::LEAF_CACHED`] or [`pte::LEAF_PB_LIST`]). + pub(crate) client: Option<(u64, u64)>, + /// Context-0 lower alias GVA of the first page (the client alias page). + pub(crate) lower: Option, + /// GPU-only objects need no CPU mapping (zeroed at allocation). + pub(crate) cpu: bool, +} + +/// The firmware object allocator and the set of retained objects. +pub(crate) struct Objects { + dev: ARef, + uat: Arc, + /// The host window: shared L2 mirror and PPL handoff. + pub(crate) window: uat::Window, + /// Next free VA of the firmware allocator window. + fw_next: u64, + /// Every object, retained until reboot. + retained: KVec>, + /// Objects aliased into every user VM. + clients: KVec>, + /// Device aliases and self-check mappings, retained until reboot. + mappings: KVec, + /// Host-window pages backed by objects. + pages: usize, +} + +impl Objects { + pub(crate) fn new(dev: &AsahiDevice, uat: Arc, window: uat::Window) -> Self { + Self { + dev: dev.into(), + uat, + window, + fw_next: hw::va::FW_ALLOC.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + pages: 0, + } + } + + /// Objects aliased into every user VM, in allocation order. + pub(crate) fn clients(&self) -> &[Arc] { + &self.clients + } + + /// Host-window pages backed by firmware objects. + pub(crate) fn pages(&self) -> usize { + self.pages + } + + /// Mirrors host-window mappings made outside this allocator (timestamp buffers) into the + /// firmware's view before their addresses are used. + pub(crate) fn sync_window(&mut self, range: core::ops::Range) -> Result { + self.window.sync_range(&self.uat, range) + } + + /// Allocates and maps a zeroed firmware object. + pub(crate) fn alloc(&mut self, req: Request) -> Result> { + self.alloc_split(req, None) + } + + /// Like [`Self::alloc`], with the first `cached` mapped bytes (a whole number of pages) in + /// `class` and the rest in the request's class (HardwareData). + pub(super) fn alloc_split( + &mut self, + req: Request, + prefix: Option<(usize, Class)>, + ) -> Result> { + let page = hw::PAGE as usize; + let (page_va, offset) = match req.placement { + Placement::At(va) => (va & !(hw::PAGE - 1), (va & (hw::PAGE - 1)) as usize), + Placement::Anywhere => (self.fw_next, req.offset), + }; + if req.size == 0 || offset >= page { + return Err(EINVAL); + } + let bytes = offset + .checked_add(req.size) + .ok_or(EINVAL)? + .next_multiple_of(page); + if page_va < hw::HOST || page_va + bytes as u64 > hw::HOST + hw::HOST_SIZE { + return Err(EINVAL); + } + if let Placement::Anywhere = req.placement { + if page_va + bytes as u64 + hw::PAGE > hw::va::FW_ALLOC.end { + return Err(ENOSPC); + } + } + if let Some((gpage, _)) = req.client { + if gpage & (hw::PAGE - 1) != 0 || gpage + bytes as u64 > hw::USER_RANGE.end { + return Err(EINVAL); + } + if self.clients.len() == hw::sizes::MAX_CLIENT { + return Err(ENOSPC); + } + } + if let Some((cached, _)) = prefix { + if cached == 0 || cached % page != 0 || cached >= bytes { + return Err(EINVAL); + } + } + + // Populate and DMA-map first: this cleans the zeroed pages' cacheable alias to the + // point of coherency before any write-combined access. + let (mut backing, sgt) = gpu_backing(&self.dev, bytes)?; + let cpu = if req.cpu { + let vmap = backing.vmap()?; + for i in 0..bytes { + vmap.try_write8(0, i)?; + } + let ptr = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; + Some(ptr) + } else { + None + }; + + let mut mappings = KVec::new(); + let kernel_vm = self.uat.kernel_vm(); + let guard = matches!(req.placement, Placement::Anywhere); + match prefix { + None => { + mappings.push( + kernel_vm.map_at( + page_va, + bytes, + &backing.gem, + mmu::Prot::from_pte(req.class.pte()), + guard, + )?, + GFP_KERNEL, + )?; + } + Some((cached, class)) => { + mappings.push( + kernel_vm.map_in_range( + &backing.gem, + 0..cached, + hw::PAGE, + page_va..page_va + cached as u64, + mmu::Prot::from_pte(class.pte()), + false, + )?, + GFP_KERNEL, + )?; + let rest = page_va + cached as u64; + mappings.push( + kernel_vm.map_in_range( + &backing.gem, + cached..bytes, + hw::PAGE, + rest..page_va + bytes as u64, + mmu::Prot::from_pte(req.class.pte()), + guard, + )?, + GFP_KERNEL, + )?; + if mappings[0].iova() != page_va || mappings[1].iova() != rest { + return Err(EINVAL); + } + } + } + self.window + .sync_range(&self.uat, page_va..page_va + bytes as u64)?; + if let Placement::Anywhere = req.placement { + // Skip an unmapped guard page after the object. + self.fw_next += bytes as u64 + hw::PAGE; + } + if let Some(lower) = req.lower { + if lower & (hw::PAGE - 1) != 0 { + return Err(EINVAL); + } + mappings.push( + self.uat.kernel_lower_vm().map_at( + lower, + bytes, + &backing.gem, + mmu::Prot::from_pte(pte::LOWER), + false, + )?, + GFP_KERNEL, + )?; + uat::clean_lower(&self.uat)?; + } + wmb(); + + // INVARIANT: `cpu` came from the owned vmap that `backing` keeps for its lifetime. + let object = Arc::new( + FwObject { + va: page_va + offset as u64, + gva: req.client.map(|(gpage, _)| gpage + offset as u64), + size: req.size, + offset, + bytes, + client_leaf: req.client.map_or(pte::LEAF_NC, |(_, leaf)| leaf), + cpu, + _mappings: mappings, + _sgt: sgt, + backing, + }, + GFP_KERNEL, + )?; + self.pages += bytes / page; + self.retained.push(object.clone(), GFP_KERNEL)?; + if req.client.is_some() { + self.clients.push(object.clone(), GFP_KERNEL)?; + } + Ok(object) + } + + /// Maps a device range (an IOMapping record) for the firmware as [`Class::Mmio`]. + pub(crate) fn map_mmio(&mut self, va: u64, pa: u64, size: u64) -> Result { + let mapping = self.uat.kernel_vm().map_io( + self.dev.as_ref().as_ref(), + va, + usize::try_from(pa)?, + usize::try_from(size)?, + mmu::Prot::from_pte(Class::Mmio.pte()), + )?; + self.mappings.push(mapping, GFP_KERNEL)?; + self.window.sync_range(&self.uat, va..va + size) + } + + /// Boot-time check that the shared page-table code writes every firmware leaf word exactly: + /// each class word is mapped on a scratch page with `Prot::from_pte(word)`, the leaf is read + /// back from the tables and must equal `pa | word`. Host-window classes are checked in the + /// (global) host window, the lower and client classes in the (non-global) context-0 lower + /// tree, which user VMs share the leaf format with. Runs before anything firmware-visible is + /// written; the scratch mappings are retained (they are never published). A mismatch refuses + /// the boot. + pub(crate) fn self_check(&mut self) -> Result { + let window = [ + pte::FW, + pte::SHARED, + pte::FW_CACHED, + pte::SHARED_CACHED, + pte::MMIO, + ]; + let lower = [ + pte::LOWER, + pte::LEAF_NC, + pte::LEAF_CACHED, + pte::LEAF_PB_LIST, + ]; + let scratch = gem::new_kernel_object_wc(&self.dev, hw::PAGE as usize)?; + // SAFETY: The self-check runs during the bound platform probe. Its retained + // mappings and GEM owner keep the backing pinned after the check. + let sgt = gem::held_sg_table(&scratch.gem, unsafe { self.dev.as_ref().as_ref().as_bound() })?; + let pa = sgt.iter().next().ok_or(EINVAL)?.dma_address() as u64; + let checks = Iterator::chain( + window + .iter() + .enumerate() + .map(|(i, &w)| (true, hw::va::SELF_CHECK + i as u64 * hw::PAGE, w)), + lower + .iter() + .enumerate() + .map(|(i, &w)| (false, hw::va::SELF_CHECK_LOWER + i as u64 * hw::PAGE, w)), + ); + let mut count = 0; + for (host, va, word) in checks { + let (vm, root) = if host { + (self.uat.kernel_vm(), self.uat.kernel_window_root()) + } else { + (self.uat.kernel_lower_vm(), self.uat.kernel_lower_root()) + }; + let mapping = vm.map_at( + va, + hw::PAGE as usize, + &scratch.gem, + mmu::Prot::from_pte(word), + false, + )?; + self.mappings.push(mapping, GFP_KERNEL)?; + let leaf = uat::read_leaf(root, va)?; + if leaf != Some(pa | word) { + dev_err!( + self.dev.as_ref(), + "G15: UAT leaf self-check failed at {:#x}: want {:#x}, tables hold {:#x}\n", + va, + pa | word, + leaf.unwrap_or(0) + ); + return Err(super::boot::eproto()); + } + count += 1; + } + // The scratch page stays mapped: retain its backing with the mappings. + // SG backing is permanently pinned by held_sg_table; scratch remains retained. + core::mem::forget(scratch); + dev_info!( + self.dev.as_ref(), + "G15: UAT leaf self-check passed ({} classes)\n", + count + ); + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/g15/object/geometry.rs b/drivers/gpu/drm/asahi/g15/object/geometry.rs new file mode 100644 index 00000000000000..3dc47ca02f5345 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/object/geometry.rs @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The DMA geometry a firmware- or GPU-visible backing must have. +//! +//! Core-only (no `kernel` imports): this file is compiled by the host test harness as well. + +/// The page size and page-frame mask [`backing_ok`] is host-tested with (`hw::PAGE`, +/// `hw::PA_MASK`; `object.rs` asserts they are the same). +pub(crate) const PAGE: u64 = 0x4000; +pub(crate) const PA_MASK: u64 = 0x3ffffffc000; + +/// Whether the DMA segments `(address, length)` back exactly `bytes` with whole pages of `page` +/// bytes that the UAT can name: +/// +/// - `page` is a power of two and `bytes` a nonzero multiple of it; +/// - every segment is nonzero, starts and ends on a page boundary, does not start at 0 and its +/// last byte lies within `pa_mask` (the page-frame bits), with no overflow; +/// - the segments' lengths add up to `bytes`, no more and no less. +pub(crate) fn backing_ok( + bytes: u64, + page: u64, + pa_mask: u64, + segments: impl IntoIterator, +) -> bool { + if !page.is_power_of_two() || bytes == 0 || bytes & (page - 1) != 0 { + return false; + } + let mut covered = 0u64; + for (pa, len) in segments { + if pa == 0 || len == 0 || (pa | len) & (page - 1) != 0 { + return false; + } + let Some(last) = pa.checked_add(len - 1) else { + return false; + }; + if last & !(pa_mask | (page - 1)) != 0 { + return false; + } + match covered.checked_add(len) { + Some(sum) if sum <= bytes => covered = sum, + _ => return false, + } + } + covered == bytes +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ok(bytes: u64, segments: &[(u64, u64)]) -> bool { + backing_ok(bytes, PAGE, PA_MASK, segments.iter().copied()) + } + + #[test] + fn exact_coverage() { + assert!(ok(PAGE, &[(0x8_0000_0000, PAGE)])); + assert!(ok( + 3 * PAGE, + &[(0x8_0000_0000, PAGE), (0x9_0000_0000, 2 * PAGE)] + )); + // A short or an oversized scatterlist. + assert!(!ok(3 * PAGE, &[(0x8_0000_0000, 2 * PAGE)])); + assert!(!ok( + 2 * PAGE, + &[(0x8_0000_0000, 2 * PAGE), (0x9_0000_0000, PAGE)] + )); + assert!(!ok(PAGE, &[])); + } + + #[test] + fn sizes() { + assert!(!ok(0, &[])); + assert!(!ok(PAGE + 1, &[(0x8_0000_0000, PAGE)])); + assert!(!backing_ok(PAGE, 0, PA_MASK, [(0x8_0000_0000, PAGE)])); + assert!(!backing_ok( + 0x6000, + 0x3000, + PA_MASK, + [(0x8_0000_0000, 0x6000)] + )); + } + + #[test] + fn segments() { + // Address 0, a zero-length segment, unaligned starts and lengths. + assert!(!ok(PAGE, &[(0, PAGE)])); + assert!(!ok(PAGE, &[(0x8_0000_0000, 0), (0x9_0000_0000, PAGE)])); + assert!(!ok(PAGE, &[(0x8_0000_1000, PAGE)])); + assert!(!ok( + 2 * PAGE, + &[ + (0x8_0000_0000, PAGE + 0x1000), + (0x9_0000_0000, PAGE - 0x1000) + ] + )); + } + + #[test] + fn physical_bounds() { + // The last page the UAT names, and the one beyond it. + let top = PA_MASK & !(PAGE - 1); + assert!(ok(PAGE, &[(top, PAGE)])); + assert!(!ok(PAGE, &[(top + PAGE, PAGE)])); + assert!(!ok(2 * PAGE, &[(top, 2 * PAGE)])); + // The end overflows instead of wrapping. + assert!(!ok(2 * PAGE, &[(u64::MAX & !(PAGE - 1), 2 * PAGE)])); + // With every bit nameable: a segment ending at the last byte is fine, one page further + // overflows. + let len = u64::MAX & !(PAGE - 1); + assert!(backing_ok(len, PAGE, u64::MAX, [(PAGE, len)])); + assert!(!backing_ok(len, PAGE, u64::MAX, [(2 * PAGE, len)])); + } + + #[test] + fn coverage_does_not_overflow() { + // Two halves wrap the total to 0, and a third segment then makes it look exact. + let bytes = u64::MAX & !(PAGE - 1); + let half = 1u64 << 63; + assert!(!backing_ok( + bytes, + PAGE, + u64::MAX, + [(PAGE, half), (PAGE, half), (PAGE, bytes)] + )); + assert!(!backing_ok( + PAGE, + PAGE, + u64::MAX, + [(PAGE, half), (PAGE, half)] + )); + } +} diff --git a/drivers/gpu/drm/asahi/g15/params.rs b/drivers/gpu/drm/asahi/g15/params.rs new file mode 100644 index 00000000000000..6eabb033a0edf1 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/params.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Module parameters and the GET_PARAMS identity. +//! +//! With the shared `file.rs` additions (VM_STATUS and VM_STATUS_MIRROR from `supports_vm_status`, +//! INDEPENDENT_QUEUES from `queue_limits`, SOFT_FAULTS suppressed by `soft_faults`), the feature +//! word is exactly 0x3e (0xbe with `g15_early_tiling`). Never advertise SOFT_FAULTS, +//! FEW_PRIMITIVES or RENDER_RAY_QUERY on G15S. + +use kernel::prelude::*; + +use super::wire as uapi; + +use super::{hw, Gpu, GPU_GENERATION}; +use crate::module_parameters; + +/// Operations per VM_BIND batch at most: batches are atomic and may be large (sparse residency +/// updates); this bounds the kernel's staging allocation. +pub(crate) const MAX_BINDS: u32 = 1 << 20; + +/// Host deadline of a published prefix without progress, ms (at least 100). +pub(crate) fn deadline_ms() -> u32 { + (*module_parameters::g15_deadline_ms.value()).max(100) +} + +/// Compute no-progress budget before the kill, ms. +pub(crate) fn compute_deadline_ms() -> u32 { + (*module_parameters::g15_compute_deadline_ms.value()).max(100) +} + +/// Repoll while a ready prefix waits for record consumption, us. +pub(crate) fn repoll_us() -> u32 { + (*module_parameters::g15_repoll_us.value()).clamp(5, 100) +} + +/// Completion repoll interval, us. +pub(crate) fn resnap_us() -> u32 { + (*module_parameters::g15_resnap_us.value()).clamp(25, 1000) +} + +/// The explicit firmware idle standby time, us (0: not set). +pub(crate) fn idle_standby_override_us() -> u32 { + *module_parameters::g15_idle_standby_us.value() +} + +/// Firmware idle minimum confidence, permille. +pub(crate) fn idle_min_conf() -> u32 { + (*module_parameters::g15_idle_min_conf.value()).clamp(1, 1000) +} + +/// Whether firmware halts are answered with the handshake (else fail-stop). +pub(crate) fn recovery() -> bool { + *module_parameters::g15_recovery.value() != 0 +} + +/// Whether the CDM/VDM stream gates are on. +pub(crate) fn stream_gate() -> bool { + *module_parameters::g15_stream_gate.value() != 0 +} + +/// The 8-byte TEXT digest prefix of an unpinned firmware build to admit (0: none). +pub(crate) fn accept_text_prefix() -> u64 { + *module_parameters::g15_accept_text_prefix.value() +} + +/// The parameter for the PB growth maximum the firmware is given, in blocks, clamped to +/// 64..=4095. [`super::pools::Pools::soft_max`] raises it to at least the initial 1024 blocks; +/// the blocks above it, up to the 4095 posted at most, answer the synchronous requests of +/// partial renders. It is read-only after boot and does not change the 512 MiB heap. +pub(crate) fn pb_max_blocks() -> u32 { + (*module_parameters::g15_pb_max_blocks.value()).clamp(64, super::hw::tuning::PB_MAX_BLOCKS) +} + +/// Whether FRAGMENT_BARRIERS is advertised and mapped to early tiling. +pub(crate) fn early_tiling() -> bool { + *module_parameters::g15_early_tiling.value() != 0 +} + +/// Fills the generation part of GET_PARAMS group 0. +pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Result { + params.features |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS as u64 + | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS as u64; + if early_tiling() { + params.features |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS as u64; + } + params.gpu_generation = GPU_GENERATION; + params.gpu_variant = gpu.cfg.gpu_variant as u32; + params.gpu_revision = gpu.cfg.gpu_revision; + params.chip_id = gpu.cfg.chip_id; + params.num_dies = 1; + params.num_clusters_total = gpu.cfg.num_clusters; + params.num_cores_per_cluster = gpu.cfg.num_cores_per_cluster; + params.max_frequency_khz = gpu.max_frequency_khz; + params.usc_generation = 3; + params.gpu_hal_generation = uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_LEGACY; + params.max_attachments = hw::sizes::MAX_ATTACHMENTS as u32; + for (i, mask) in gpu + .id + .core_masks + .iter() + .enumerate() + .take(gpu.cfg.num_clusters as usize) + { + *(params.core_masks.get_mut(i).ok_or(EIO)?) = (*mask).into(); + } + Ok(()) +} + +/// QUEUE_LIMITS: a policy bound on logical queues (they own no firmware state) and the +/// number of prefixes in flight. +pub(crate) fn queue_limits() -> uapi::drm_asahi_queue_limits { + uapi::drm_asahi_queue_limits { + max_queues: hw::sizes::MAX_QUEUES, + max_in_flight_per_queue: hw::sizes::FLIGHTS as u32, + ..Default::default() + } +} + +/// Shared status/queue features in the native G15 ABI's assignments. +pub(crate) fn feature_flags() -> u64 { + uapi::SHARED_FEATURE_FLAGS +} diff --git a/drivers/gpu/drm/asahi/g15/poll.rs b/drivers/gpu/drm/asahi/g15/poll.rs new file mode 100644 index 00000000000000..751f19865436f8 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/poll.rs @@ -0,0 +1,733 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The poll work: drain, retire, growth, hang checks, publication; and the repoll timers. +//! +//! Order of one pass, under the device lock: drain the receive rings; retire flights (stamps, +//! queue DONE/READ, channel consumption, stage-event counts, idle bits, fault banks; renew the +//! progress deadline), with up to four trailing 5 us polls after an EP 0x20 event; answer PB +//! growth ([`Firmware::answer_growth`]); check hangs and recover ([`Firmware::check_hangs`], +//! which calls [`Firmware::progress`]); publish ([`Firmware::publish`]). Then drop the lock +//! and complete the retired jobs ([`super::job::complete_all`]). Wakeups: the EP 0x20 event +//! kick, then an hrtimer re-poll every `g15_resnap_us` (100) while anything is published, or +//! `g15_repoll_us` (15) while a ready prefix waits for record consumption, with a 1-jiffy +//! delayed-work backup. + +use core::sync::atomic::Ordering; + +use kernel::{ + bindings, c_str, debugfs, fmt, impl_has_hr_timer, + prelude::*, + sync::{Arc, ArcBorrow}, + time::{ + delay, + hrtimer::{ + HrTimerCallback, HrTimerCallbackContext, HrTimerPointer, HrTimerRestart, RelativeMode, + }, + Delta, Jiffies, Monotonic, + }, + workqueue::RawWorkItem, +}; + +use super::channel::Channel; +use super::engine::{complete, now_ns, rmb, Flight, Lap}; +use super::fw::graph::qstate; +use super::hw::sizes; +use super::job::{self, Completions, Job}; +use super::regs::EngineState; +use super::{params, Firmware, Shared, POLL_WORK}; +use crate::module_parameters; + +impl_has_hr_timer! { + impl HasHrTimer for Shared { + mode: RelativeMode, field: self.resnap + } +} + +impl HrTimerCallback for Shared { + type Pointer<'a> = Arc; + + /// Runs the poll now. + fn run(this: ArcBorrow<'_, Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart { + let this: Arc = this.into(); + this.poll_now(); + HrTimerRestart::NoRestart + } +} + +/// The `asahi-g15/stats` debugfs file contents. +fn stats_show(shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let state = shared.state.lock(); + match state.as_deref() { + Some(firmware) => firmware.write_stats(f), + None => Ok(()), + } +} + +/// The `asahi-g15/pstate` file contents. +fn pstate_show(shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let state = shared.state.lock(); + match state.as_deref() { + Some(firmware) => firmware.write_pstate(f), + None => Ok(()), + } +} + +impl Shared { + /// One poll pass (the poll work item). + pub(crate) fn run_poll(self: Arc) { + let mut done = Completions::new(); + { + let mut state = self.state.lock(); + if let Some(firmware) = state.as_deref_mut() { + if firmware.engine.shared.is_none() { + firmware.engine.shared = Some(self.clone()); + } + let evented = self.evented.swap(false, Ordering::AcqRel); + match firmware.poll(evented, &mut done) { + Ok(true) => self.rearm(firmware.engine.chan_wait), + Ok(false) => {} + Err(error) => self.fail_stop(error), + } + } + } + job::complete_all(done); + } + + /// Hands a job to the engine and publishes what can be published. Err: the job was not + /// accepted (the engine failed: EIO) and the caller fails it; once accepted, its fence is + /// signalled by the engine, also on failure. + pub(crate) fn submit(self: &Arc, job: Arc) -> Result { + let mut done = Completions::new(); + let accepted = { + let mut state = self.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + if firmware.engine.shared.is_none() { + firmware.engine.shared = Some(self.clone()); + } + let accepted = firmware.enqueue(job); + if accepted.is_ok() { + if let Err(error) = firmware.publish(&mut done) { + self.fail_stop(error); + } + if !firmware.engine.flights.is_empty() { + self.rearm(firmware.engine.chan_wait); + } + } + accepted + }; + job::complete_all(done); + accepted + } + + /// Queues the poll work now, or brings a pending one forward. Callable from any context. + pub(crate) fn poll_now(self: &Arc) { + self.mod_poll(0); + } + + /// Queues the poll on `system_highpri_wq` after `delay` jiffies, or moves an already + /// pending one to that expiry. + fn mod_poll(self: &Arc, delay: Jiffies) { + // SAFETY: The closure returns false only when `mod_delayed_work_on` found the work + // already pending (it then only modified its timer), so the queue keeps the reference + // it took when it was queued; otherwise the work is queued and owns this reference. + let _ = unsafe { + as RawWorkItem>::__enqueue(self.clone(), |work| { + let dwork = kernel::container_of!(work, bindings::delayed_work, work); + !bindings::mod_delayed_work_on( + bindings::wq_misc_consts_WORK_CPU_UNBOUND as kernel::ffi::c_int, + bindings::system_highpri_wq, + dwork, + delay, + ) + }) + }; + } + + /// Re-checks a published command soon: hrtimer, with a one-jiffy backup; sooner while a + /// ready prefix waits for a channel record's consumption. + pub(crate) fn rearm(self: &Arc, chan_wait: bool) { + let mut us = params::resnap_us(); + if chan_wait && *module_parameters::g15_repoll_us.value() != 0 { + us = params::repoll_us(); + } + { + let mut handle = self.resnap_handle.lock(); + // Dropping the previous handle cancels a still pending expiry before the timer + // is started again. + drop(handle.take()); + *handle = Some(self.clone().start(Delta::from_micros(us as i64))); + } + self.mod_poll(1); + } + + /// Starts what the engine needs besides the firmware state: the `asahi-g15/stats` and + /// `asahi-g15/pstate` files. + pub(crate) fn start_engine(self: &Arc) -> Result { + let dir = debugfs::Dir::new(c_str!("asahi-g15")); + let file = KBox::pin_init( + dir.read_callback_file(c_str!("stats"), self.clone(), &stats_show), + GFP_KERNEL, + )?; + let pstate = KBox::pin_init( + dir.read_callback_file(c_str!("pstate"), self.clone(), &pstate_show), + GFP_KERNEL, + )?; + let mut state = self.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + firmware.engine.shared = Some(self.clone()); + firmware.engine.debugfs = Some(file); + firmware.engine.debugfs_pstate = Some(pstate); + Ok(()) + } +} + +/// Stamp cell `obs` reached its own target, bounded by the newest published target `tail`. +pub(crate) fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { + obs != 0 && obs & 0xff == 0 && obs.wrapping_sub(own) <= tail.wrapping_sub(own) +} + +/// Cursor `c` of a ring of `m` entries passed end `h` of entries from `b`, within tail `t`. +pub(crate) fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { + let d = |x: u32| x.wrapping_add(m).wrapping_sub(b) % m; + let (dc, dh, dt) = (d(c), d(h), d(t)); + dh <= dc && dc <= dt +} + +impl Firmware { + /// One poll pass under the device lock. Returns whether to re-arm the poll timers. + pub(crate) fn poll(&mut self, evented: bool, done: &mut Completions) -> Result { + if self.recovery.failed().is_some() { + return Ok(false); + } + // With nothing published only an armed hang request whose prefix ended or a firmware + // error event needs this pass: one that arrived after its prefix's receipts is answered + // here (the firmware halted and waits for the resume) instead of being taken for a + // failure of the next prefix. Drain the receive rings before deciding, published or + // not, so the error count is current and idle log/trace/stats traffic is consumed. With + // prefixes published the retirement loop below drains first. + if self.engine.flights.is_empty() { + self.drain_rings()?; + if self.recovery_idle() { + return Ok(false); + } + } + let mut lap = Lap::start(); + let start = lap.on().then(now_ns); + self.retire(evented, done)?; + lap.lap(&mut self.engine.prof.retire_ns); + self.answer_growth()?; + self.check_hangs(done)?; + let published = self.publish(done); + let s = &mut self.engine.stats; + if self.engine.flights.is_empty() && s.idle_from_ns != 0 { + // Idle with nothing ready is not a gap: the clients are late. + s.starve_from_ns = s.idle_from_ns; + s.idle_from_ns = 0; + } + if let Some(start) = start { + self.engine.prof.polls += 1; + self.engine.prof.poll_ns += now_ns().wrapping_sub(start); + } + published?; + Ok(!self.engine.flights.is_empty() || self.recovery.needs_repoll() || self.engine.frozen) + } + + /// Drains the rings and retires finished flights, with up to four trailing 5 us polls + /// after an event. A receipt fault is left in `Recovery::receipt_fault` for the hang + /// checks. + pub(crate) fn retire(&mut self, evented: bool, done: &mut Completions) -> Result { + // After an event, a few short trailing polls catch the final receipts. + let mut tail = if evented { 4 } else { 0 }; + let mut ret; + + loop { + let mut lap = Lap::start(); + self.drain_rings()?; + lap.lap(&mut self.engine.prof.drain_ns); + ret = self.retired(); + while let Ok(true) = ret { + // An armed kill that ended it, or a doomed flight. + let outcome = self.retire_outcome(); + self.retire_oldest(outcome, done); + ret = self.retired(); + } + if ret.is_err() || tail == 0 || self.engine.flights.is_empty() { + break; + } + tail -= 1; + delay::udelay(Delta::from_micros(5)); + } + self.recovery.receipt_fault = ret.is_err(); + Ok(()) + } + + fn r32(o: &super::object::FwObject, offset: usize) -> Result { + o.r32(offset) + } + + /// Retirement of the oldest published prefix: Ok(true) retired, Ok(false) not yet, + /// Err(EIO) fault. The last published one needs every receipt exactly: final stamps, + /// DONE/READ at the tail heads, consumed pipes, new firing bits and idle engines. + pub(crate) fn retired(&self) -> Result { + let Some(f) = self.engine.oldest() else { + return Ok(false); + }; + rmb(); + if self.engine.flights.len() > 1 { + return self.flight_retired(f); + } + let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let ch = &self.channels; + // A render: both stamp pairs, both queues, both pipes. + if f.renders != 0 { + let pending = Self::r32(&r.user_stamp[0], 0)? != e.ta_target + || Self::r32(&r.fw_stamp[0], 0)? != e.ta_target + || Self::r32(&r.user_stamp[1], 0)? != e.fs_target + || Self::r32(&r.fw_stamp[1], 0)? != e.fs_target + || Self::r32(&r.qstate[0], qstate::DONE)? != e.ta_head + || Self::r32(&r.qstate[0], qstate::READ)? != e.ta_head + || Self::r32(&r.qstate[1], qstate::DONE)? != e.fs_head + || Self::r32(&r.qstate[1], qstate::READ)? != e.fs_head + || ch.read(Channel::Ta)? != ch.producer(Channel::Ta) + || ch.read(Channel::Fs)? != ch.producer(Channel::Fs); + if pending { + return Ok(false); + } + } + if f.computes != 0 { + let pending = Self::r32(&g.user_stamp, 0)? != e.target + || Self::r32(&g.fw_stamp, 0)? != e.target + || Self::r32(&g.qstate, qstate::DONE)? != e.head + || Self::r32(&g.qstate, qstate::READ)? != e.head + || ch.read(Channel::Compute)? != ch.producer(Channel::Compute) + || self.events.compute_events == e.events; + if pending { + return Ok(false); + } + } + // New firing bits: at least one per participating stage (1, 2 or 3). + let stages = if f.computes != 0 { 3 } else { 2 }; + if f.renders != 0 && self.events.stage_events.wrapping_sub(e.stage_seen) < stages { + return Ok(false); + } + let state = self.session.regs.engine_state()?; + if state.fault() != 0 { + self.log_fault(&state); + return Err(EIO); + } + Ok(state.busy == 0) + } + + /// The oldest published prefix while later ones may run: its own stamp targets reached + /// within the published interval, DONE past its saved ring ends, its channel records + /// consumed. Engine idle is not required; faults still are checked. + fn flight_retired(&self, f: &Flight) -> Result { + let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let ch = &self.channels; + let cap = sizes::QUEUE_CAP; + let rec_passed = |c: Channel, rec: u32| -> Result { + Ok(ring_passed( + ch.read(c)?, + (rec + 255) % 256, + rec, + ch.producer(c), + 256, + )) + }; + + if f.computes != 0 { + let pending = !stamp_reached(Self::r32(&g.user_stamp, 0)?, f.target, e.target) + || !stamp_reached(Self::r32(&g.fw_stamp, 0)?, f.target, e.target) + || !ring_passed( + Self::r32(&g.qstate, qstate::DONE)?, + f.c_start, + f.head, + e.head, + cap, + ) + || !rec_passed(Channel::Compute, f.rec[2])?; + if pending { + return Ok(false); + } + } + if f.renders != 0 { + let pending = !stamp_reached(Self::r32(&r.user_stamp[0], 0)?, f.ta_target, e.ta_target) + || !stamp_reached(Self::r32(&r.fw_stamp[0], 0)?, f.ta_target, e.ta_target) + || !stamp_reached(Self::r32(&r.user_stamp[1], 0)?, f.fs_target, e.fs_target) + || !stamp_reached(Self::r32(&r.fw_stamp[1], 0)?, f.fs_target, e.fs_target) + || !ring_passed( + Self::r32(&r.qstate[0], qstate::DONE)?, + f.ta_start, + f.ta_head, + e.ta_head, + cap, + ) + || !ring_passed( + Self::r32(&r.qstate[1], qstate::DONE)?, + f.fs_start, + f.fs_head, + e.fs_head, + cap, + ) + || !rec_passed(Channel::Ta, f.rec[0])? + || !rec_passed(Channel::Fs, f.rec[1])?; + if pending { + return Ok(false); + } + } + let state = self.session.regs.engine_state()?; + if state.fault() != 0 { + self.log_fault(&state); + return Err(EIO); + } + Ok(true) + } + + /// Logs the non-zero fault banks of `state`. + pub(crate) fn log_fault(&self, state: &EngineState) { + for bank in 0..2 { + let (f, va) = (state.status[bank], state.address[bank]); + if f == 0 { + continue; + } + let access = if (f >> 4) & 1 != 0 { "read" } else { "write" }; + let reason = if (f >> 1) & 7 != 0 { + "reason!=unmapped" + } else { + "unmapped" + }; + dev_info!( + self.graph.dev.as_ref(), + "G15: fault bank {}: status {:#x} va {:#x} ({} {} level {} unit {:#x} ctx {})\n", + bank, + f, + va, + access, + reason, + (f >> 7) & 3, + (f >> 9) & 0xff, + (f >> 17) & 0x3f + ); + } + } + + /// The oldest published prefix retired: its storage is released, its job completes when + /// this was its last published prefix and nothing of it is left to publish. A failed + /// (hang-killed, doomed, recovered) prefix fails its job, which drops its unpublished + /// commands. Recovery calls this for every published prefix after a recovered failure. + pub(crate) fn retire_oldest(&mut self, result: Result, done: &mut Completions) { + if self.engine.flights.is_empty() { + return; + } + let Ok(mut f) = self.engine.flights.remove(0) else { + return; + }; + if result.is_ok() { + self.stat_retire(&f); + } + self.slots.release(&mut f.claims); // after the stats read its timestamp cells + if f.rebuild { + f.rebuild = false; + self.engine.rebuild_live = false; + } + if self.engine.flights.is_empty() { + // Drained: a gap until the next publication. + self.engine.stats.idle_from_ns = now_ns(); + } + // The next prefix starts executing about now. + self.renew_deadlines(); + let job = f.job.clone(); + let p = &job.progress; + p.next.store(p.next() + f.count as u32, Ordering::Relaxed); + if let Err(error) = result { + complete(done, &job, Err(error)); + if p.is_pending() { + // Drop its unpublished commands. + p.pending.store(false, Ordering::Relaxed); + self.engine.pending.retain(|j| !Arc::ptr_eq(j, &job)); + p.count.store(p.sent(), Ordering::Relaxed); + } + } + if p.next() < p.sent() || p.sent() < p.count() { + return; // more of it published or still to publish + } + let s = &mut self.engine.stats; + if result.is_ok() { + s.jobs += 1; + s.job_cmds += p.count() as u64; + s.job_max = s.job_max.max(p.count() as u64); + } + complete(done, &job, Ok(())); + // The rest of a compute horizon, after the first job (fence order). + for j2 in f.group.iter() { + let p2 = &j2.progress; + p2.next.store(p2.count(), Ordering::Relaxed); + match result { + Err(error) => complete(done, j2, Err(error)), + Ok(()) => { + s.jobs += 1; + s.job_cmds += p2.count() as u64; + s.job_max = s.job_max.max(p2.count() as u64); + } + } + complete(done, j2, Ok(())); + } + } + + /// Progress of the oldest prefix: a FW stamp of an engine on which it still has unreached + /// work moved since the last poll (later prefixes' work on other engines does not count). + /// Renews the deadline; the first call for a prefix only records its position. + /// [`Self::check_hangs`] calls it after restoring an armed request, while no request is + /// armed. + pub(crate) fn progress(&mut self) { + let Some(f) = self.engine.oldest() else { + return; + }; + let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let (mut c, mut ta, mut fs) = (0, 0, 0); + + if f.computes != 0 { + c = g.fw_stamp.r32(0).unwrap_or(0); + if stamp_reached(c, f.target, e.target) { + c = 0; // its computes are done: later work does not count + } + } + if f.renders != 0 { + ta = r.fw_stamp[0].r32(0).unwrap_or(0); + fs = r.fw_stamp[1].r32(0).unwrap_or(0); + if stamp_reached(ta, f.ta_target, e.ta_target) { + ta = 0; + } + if stamp_reached(fs, f.fs_target, e.fs_target) { + fs = 0; + } + } + let moved = e.progress_flight == f.published_ns && [c, ta, fs] != e.progress; + let published = f.published_ns; + if moved { + self.renew_deadlines(); + } + self.engine.progress_flight = published; + self.engine.progress = [c, ta, fs]; + } + + /// A retired prefix: publication to retirement (including any wait behind its + /// predecessor), event times, internal stage times of its members. + fn stat_retire(&mut self, f: &Flight) { + let now = now_ns(); + let d = now.wrapping_sub(f.published_ns); + let kind = if f.computes != 0 && f.renders != 0 { + 2 + } else if f.renders != 0 { + 1 + } else { + 0 + }; + let (mut lo, mut hi) = (u64::MAX, 0u64); + let (mut first, mut last) = (u64::MAX, 0u64); + let scrub = self.slots.scrub.clone(); + let s = &mut self.engine.stats; + + // Add one stage interval read from internal timestamp cells (start, end). + let mut stage = |o: &super::object::FwObject, off: usize, sum: &mut u64| { + let rd = |x: usize| o.r32(x).unwrap_or(0) as u64; + let start = rd(off + 4) << 32 | rd(off); + let end = rd(off + 12) << 32 | rd(off + 8); + if start == 0 || end < start { + return; + } + *sum += end - start; + lo = lo.min(start); + hi = hi.max(end); + }; + for k in 0..f.renders as usize { + let p = &scrub.passes[f.claims.pass[k] as usize]; + stage(&p.its, 0, &mut s.ta_ticks); + stage(&p.its, 0x10, &mut s.fs_ticks); + } + for k in 0..(f.computes as usize).min(f.claims.slot_count as usize) { + let c = &scrub.compute[f.claims.slot[k] as usize]; + stage(&c.its, 0, &mut s.cdm_ticks); + } + if hi > lo { + s.span_ticks += hi - lo; + } + for b in 0..3 { + let t = self.events.event_ns[b]; + let skip = if b == 2 { + f.computes == 0 + } else { + f.renders == 0 + }; + if skip { + continue; + } + first = first.min(t); + last = last.max(t); + } + if first > f.published_ns && last <= now { + s.first_ns[kind] += first - f.published_ns; + s.last_ns[kind] += last - f.published_ns; + } + s.count[0] += f.computes as u64; + s.count[1] += f.renders as u64; + if kind == 2 { + s.count[2] += f.count as u64; + } + s.prefixes[kind] += 1; + s.busy_ns[kind] += d; + s.max_ns[kind] = s.max_ns[kind].max(d); + } + + /// Engine state report for failures and hang requests (without the initdata Runtime + /// readiness and Flags words). + pub(crate) fn report(&self, what: &str) { + let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let ch = &self.channels; + let rd = |o: &super::object::FwObject, off| o.r32(off).unwrap_or(0xdeadbeef); + let state = self.session.regs.engine_state().unwrap_or_default(); + let f = e.oldest(); + let ms = f.map_or(0, |f| now_ns().wrapping_sub(f.published_ns) / 1_000_000); + + dev_info!( + self.graph.dev.as_ref(), + "G15: {}: ctx={} prefixes={} n={} target={:#x} user={:#x} fw={:#x} done={} read={} write={} head={} ch={}/{} events={}/{} errors={} busy={} fault={:#x} {}ms\n", + what, + f.map_or(0, |f| f.job.vm.slot), + e.flights.len(), + e.ordinal, + e.target, + rd(&g.user_stamp, 0), + rd(&g.fw_stamp, 0), + rd(&g.qstate, qstate::DONE), + rd(&g.qstate, qstate::READ), + rd(&g.qstate, qstate::WRITE), + e.head, + ch.read(Channel::Compute).unwrap_or(0xdeadbeef), + ch.write_cell(Channel::Compute).unwrap_or(0xdeadbeef), + self.events.compute_events, + e.events, + self.events.errors, + state.busy, + state.fault(), + ms + ); + if f.is_some_and(|f| f.renders != 0) { + dev_info!( + self.graph.dev.as_ref(), + "G15: render: draw={} ta {:#x}/{:#x}/{:#x} done={} read={} write={} head={} ch0={}/{}; fs {:#x}/{:#x}/{:#x} done={} read={} write={} head={} ch1={}/{}; stage events={}/{}\n", + e.draw, + e.ta_target, + rd(&r.user_stamp[0], 0), + rd(&r.fw_stamp[0], 0), + rd(&r.qstate[0], qstate::DONE), + rd(&r.qstate[0], qstate::READ), + rd(&r.qstate[0], qstate::WRITE), + e.ta_head, + ch.read(Channel::Ta).unwrap_or(0xdeadbeef), + ch.write_cell(Channel::Ta).unwrap_or(0xdeadbeef), + e.fs_target, + rd(&r.user_stamp[1], 0), + rd(&r.fw_stamp[1], 0), + rd(&r.qstate[1], qstate::DONE), + rd(&r.qstate[1], qstate::READ), + rd(&r.qstate[1], qstate::WRITE), + e.fs_head, + ch.read(Channel::Fs).unwrap_or(0xdeadbeef), + ch.write_cell(Channel::Fs).unwrap_or(0xdeadbeef), + self.events.stage_events, + e.stage_seen + ); + } + } + + /// The `asahi-g15/stats` contents. Scripts parse the keys: keep them stable. + pub(crate) fn write_stats(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let s = &self.engine.stats; + let slots = &self.slots.stats; + let (recoveries, hang_kills) = self.recovery_counts(); + let us = |ns: u64| ns / 1000; + + for (e, name) in ["compute", "render", "mixed"].iter().enumerate() { + writeln!( + f, + "{}: count {} prefixes {} busy_us {} max_us {} first_us {} last_us {}", + name, + s.count[e], + s.prefixes[e], + us(s.busy_ns[e]), + us(s.max_ns[e]), + us(s.first_ns[e]), + us(s.last_ns[e]) + )?; + } + writeln!( + f, + "gaps {} gap_us {} yields {} overlaps {}", + s.gaps, + us(s.gap_ns), + s.yields, + s.overlaps + )?; + writeln!( + f, + "jobs {} job_cmds {} job_max {} early {} recoveries {} hang_kills {} clustered {}", + s.jobs, s.job_cmds, s.job_max, s.early, recoveries, hang_kills, s.clustered + )?; + writeln!( + f, + "ct_sync {} slot_sync {} starved_us {} prep_us {} grouped {} pass_sync {}", + slots.ct_sync, + slots.slot_sync, + us(s.starved_ns), + us(s.prep_ns), + s.grouped, + slots.pass_sync + )?; + writeln!(f, "type0: fs2c {} c2ta {}", s.fs2c0, s.c2ta0)?; + write!(f, "horizon:")?; + for n in s.hz.iter() { + write!(f, " {}", n)?; + } + writeln!( + f, + " stop {}/{}/{}/{} behind {} hold {}/{}/{} ahead {}", + s.hz_stop[0], + s.hz_stop[1], + s.hz_stop[2], + s.hz_stop[3], + s.hz_behind, + s.hold[0], + s.hold[1], + s.hold[2], + s.hz_ahead + )?; + self.pools.write_stats(f)?; + writeln!( + f, + "stage: ta_us {} fs_us {} cdm_us {} span_us {}", + s.ta_ticks / 24, + s.fs_ticks / 24, + s.cdm_ticks / 24, + s.span_ticks / 24 + )?; + // The phase timers of debug_flags bit 49, and the scrub flush waits. + let p = &self.engine.prof; + writeln!( + f, + "prof: prefixes {} select_us {} encode_us {} claim_us {} write_us {} post_us {} polls {} drain_us {} retire_us {} poll_us {} flushes {} flush_us {}", + p.prefixes, + us(p.select_ns), + us(p.encode_ns), + us(p.claim_ns), + us(p.write_ns), + us(p.post_ns), + p.polls, + us(p.drain_ns), + us(p.retire_ns), + us(p.poll_ns), + slots.flushes, + us(slots.flush_ns) + ) + } +} diff --git a/drivers/gpu/drm/asahi/g15/pools.rs b/drivers/gpu/drm/asahi/g15/pools.rs new file mode 100644 index 00000000000000..c635ed11c4a0c3 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/pools.rs @@ -0,0 +1,836 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Render UMA/PB allocators, their spare set and parameter-buffer growth. +//! +//! Record layouts: [`super::fw::buffer`]; the ledger and request checks: [`growth`] +//! (host-tested). +//! +//! - One 512 MiB PB heap at [`super::hw::client::PB_HEAP`] (4096 blocks of 128 KiB), backed on +//! demand: the initial blocks when the GPU starts, then chunks of at most +//! [`growth::CHUNK_BLOCKS`] (4 MiB) as growth needs them ([`Firmware::back_pb`]), never freed +//! or shrunk. The backing ([`PbChunk`]) is mapped only into user VMs, at the fixed client GVA, +//! each VM's before its prefixes are published ([`Firmware::map_pb`]); nothing names its pages +//! through the host window or context 0 (the records hold client GVAs only). Initial +//! [`super::hw::tuning::PB_BLOCKS`] (1024), at most [`super::hw::tuning::PB_MAX_BLOCKS`] +//! (4095) posted, so the producer never returns to 0; the firmware is given +//! [`Pools::soft_max`] (default 3072) as its growth maximum. Truthful K = 4096 in every +//! profile (PB reconstruction, also in recovery, synchronizes 8 * K bytes of the block list: +//! K = 0x26cd overran the 0x8000-byte list and crashed the second recovery). +//! - Growth: the event drain queues type-7 requests; [`Firmware::answer_growth`] answers each +//! one in the poll pass: type 7, PB slot 0, the context of a live published render prefix, +//! counter >= next expected, epoch == current halt count; write records `(G - 0x1000000000) +//! >> 15` at producer % K, barrier, block_ctl+4, barrier, then DEVCTL 7 with +4 = 1 echoing +//! slot, context, counter, position and epoch; +10 blocks per request. Above the firmware's +//! growth maximum the requests are answered as before, for the synchronous growth of partial +//! renders (Mesa's partial background/EOT programs). At the ledger's maximum the reply is +4 +//! = 0, a refusal, twice per initialization; later requests are left unanswered. A refusal +//! gives no pages and can leave the TA stalled; the poll pass returns, and the host deadline +//! and its recovery path apply, without a guarantee that they end the stall. Invalid requests +//! are logged and left unanswered, so the host deadline applies. Recovery drops pending +//! requests (epoch gate). +//! - Managers ASC-cached with an uncached spare set allocated with the graph; the first +//! recovered render abort swaps to the spare and never rewrites the cached set (the ASC may +//! still hold dirty lines of it); later aborts rewrite the spare in place. block_ctl stays +//! uncached when growth is on (a live host producer). +//! +//! The engine uses: [`Firmware::init_render_pools`] (render graph init: `false`; the priming +//! prefix after an abort: `true` when [`super::recovery::Recovery::reinit`] is set), the VAs +//! for its encoders ([`Pools::allocator_refs`]), [`Firmware::publish_pb`] after the render +//! threshold, and [`Pools::write_stats`] for the debugfs `pb:` line. + +mod growth; + +use core::fmt; +use core::sync::atomic::Ordering; +use kernel::{ + device, + prelude::*, + sync::{aref::ARef, Arc}, +}; + +use super::fw::buffer::{self, block_ctl, counter, misc, pb_manager, uma_manager, uma_pools}; +use super::fw::channels::DevCtl; +use super::fw::initdata::control; +use super::hw::{client, pte, sizes, tuning}; +use super::object::{self, Class, FwObject, HeldPages, Objects, Placement, Request}; +use super::vm::VmState; +use super::Firmware; +use crate::driver::AsahiDrmDevice as AsahiDevice; +use crate::{gem, mmu}; + +pub(crate) use growth::Ledger; + +static_assert!(buffer::MAX_BLOCKS == sizes::PB_BLOCKS); +static_assert!(buffer::MAX_PAGES == sizes::PB_PAGES); +static_assert!(buffer::BLOCK_LIST_RECORDS == sizes::PB_LIST_RECORDS); +static_assert!(buffer::GROW_STEP == sizes::PB_GROW_STEP); +static_assert!(buffer::MAX_BLOCKS as u64 * buffer::BLOCK_BYTES == client::PB_HEAP_SIZE); +static_assert!(buffer::PAGE_LIST_SIZE as u64 == client::PB_PAGE_LIST_SIZE); +static_assert!(uma_manager::SEEDS == sizes::FREELIST_SEED); +static_assert!(uma_pools::POOL_SIZE == sizes::POOL_SIZE); +// The ledger keeps the driver's PB sizes: neither is capped by [`growth::MAX_POSTED`]. +static_assert!(tuning::PB_MAX_BLOCKS <= growth::MAX_POSTED); +static_assert!(buffer::MIN_BLOCKS <= tuning::PB_BLOCKS); +static_assert!(tuning::PB_BLOCKS <= tuning::PB_MAX_BLOCKS); +// The PB alias is GPU-only (not cached and firmware-visible): dropping one is a plain unmap, +// with no firmware cache flush (`KernelMapping::drop`). +static_assert!(!mmu::Prot::from_pte(pte::LEAF_CACHED).is_cached_noncoherent()); + +/// Physical backing of PB blocks `[first, first + blocks)`: a zeroed GEM kernel object, pinned +/// and DMA-mapped ([`object::gpu_backing`]), aliased only into user VMs at the blocks' fixed +/// client GVA ([`Firmware::map_pb`]). Retained until reboot, like every firmware object; each +/// alias also holds the object. +struct PbChunk { + first: u32, + blocks: u32, + _pages: HeldPages, + backing: gem::ObjectRef, +} + +impl PbChunk { + fn new(dev: &AsahiDevice, first: u32, blocks: u32) -> Result { + if blocks == 0 || first.checked_add(blocks).ok_or(EINVAL)? > buffer::MAX_BLOCKS { + return Err(EINVAL); + } + let (backing, pages) = + object::gpu_backing(dev, blocks as usize * buffer::BLOCK_BYTES as usize)?; + Ok(Self { + first, + blocks, + _pages: pages, + backing, + }) + } + + /// The block after the chunk's last. + fn end(&self) -> u32 { + self.first + self.blocks + } + + /// Maps the whole chunk, exactly its object's size, at its fixed client GVA in `vm`. + fn map(&self, vm: &mmu::Vm) -> Result { + vm.map_at( + client::PB_HEAP + self.first as u64 * buffer::BLOCK_BYTES, + self.blocks as usize * buffer::BLOCK_BYTES as usize, + &self.backing.gem, + mmu::Prot::from_pte(pte::LEAF_CACHED), + false, + ) + } +} + +/// The allocator state a rebuild after an abort moves to the spare. +struct AllocatorSet { + /// TA (0) and FS (1) UMA managers and their counters. + uma_manager: [Arc; 2], + uma_counter: [Arc; 2], + block_ctl: Arc, + pb_counter: Arc, + misc: Arc, + scene_list: Arc, + pb_manager: Arc, +} + +/// One render engine's UMA pools: eight GPU-only 4 MiB pools, the freelist seeded with them and +/// the pool table. +struct UmaEngine { + pools: KVec>, + freelist: Arc, + pool_table: Arc, +} + +/// Firmware VAs of the render allocators in use (after a rebuild possibly the spare set), as +/// the TA/FS images, the scene and InitBM records name them. +#[derive(Copy, Clone, Default)] +pub(crate) struct AllocatorRefs { + /// UMA managers of TA (0) and FS (1). + pub(crate) uma_mgr: [u64; 2], + /// PB manager (InitBM +0x14, TA/FS work and sequences), scene list (scene +0x0/+0x8 at + /// `+ 4 * (draw % 48)`, TA work) and misc record (scene +0x40). + pub(crate) pb_mgr: u64, + pub(crate) scene_list: u64, + pub(crate) mgr_misc: u64, + /// Initial PB blocks of the current initialization (InitBM +0x10, TA register #33). + pub(crate) init_blocks: u32, +} + +/// PB growth statistics. +#[derive(Default)] +pub(crate) struct PbStats { + pub(crate) requests: u64, + pub(crate) grown: u64, + pub(crate) refused: u64, + pub(crate) bad: u64, +} + +/// Render allocator and PB state: the allocators, the PB ledger and the spare set. +pub(crate) struct Pools { + /// The GPU device, for logging (also used by recovery). + pub(crate) dev: ARef, + /// The DRM device, for the PB backing objects. + drm: ARef, + uma: [UmaEngine; 2], + /// The allocator set in use. + live: AllocatorSet, + /// The never-exposed uncached set the first rebuild moves to; afterwards the replaced + /// cached set, retained (only with `manager_cached`). + spare: Option, + /// The spare set has not been used yet. + spare_ready: bool, + pb_pages: Arc, + pb_blocks: Arc, + /// The PB backing, contiguous from block 0, in block order: the initial blocks, then the + /// growth chunks. Its capacity, reserved up front, is the most the ledger can need + /// ([`growth::max_chunks`]). + chunks: KVec, + /// The PB growth ledger since the last (re)initialization. + pub(crate) ledger: Ledger, + /// C1 names the current initial pages. + c1_written: bool, + /// The unanswered-at-the-maximum warning was given since the last initialization. + exhausted_logged: bool, + pub(crate) stats: PbStats, +} + +/// The ASC-cached twin of an allocator manager's class. +const fn manager_class(class: Class) -> Class { + if !tuning::MANAGER_CACHED { + return class; + } + match class { + Class::Shared => Class::SharedCached, + _ => Class::FwCached, + } +} + +/// Allocates a zeroed firmware object anywhere in the firmware window: `client` names the +/// fixed client page and leaf of its alias in every VM, `cpu` is false for GPU-only storage. +fn alloc( + objects: &mut Objects, + size: u64, + class: Class, + client: Option<(u64, u64)>, + offset: u64, + cpu: bool, +) -> Result> { + objects.alloc(Request { + size: size as usize, + class, + placement: Placement::Anywhere, + offset: offset as usize, + client, + lower: None, + cpu, + }) +} + +/// Writes `count` little-endian records of `W` bytes, record `i` at `offset + i * W`, in chunks. +fn write_records( + object: &FwObject, + offset: usize, + count: usize, + record: impl Fn(usize) -> [u8; W], +) -> Result { + const CHUNK: usize = 512; + let mut buf = [0u8; CHUNK]; + let per_chunk = CHUNK / W; + let mut i = 0; + while i < count { + let n = per_chunk.min(count - i); + for j in 0..n { + buf[j * W..(j + 1) * W].copy_from_slice(&record(i + j)); + } + object.write(offset + i * W, &buf[..n * W])?; + i += n; + } + Ok(()) +} + +/// A u64 record. +fn le64(value: u64) -> [u8; 8] { + value.to_le_bytes() +} + +impl UmaEngine { + /// Allocates engine `e`'s UMA pools, freelist and pool table, then its manager and counter, + /// in this order. + fn alloc(objects: &mut Objects, e: u64) -> Result<(Self, Arc, Arc)> { + let mut pools = KVec::with_capacity(uma_pools::POOLS, GFP_KERNEL)?; + for k in 0..uma_pools::POOLS as u64 { + pools.push( + alloc( + objects, + uma_pools::POOL_SIZE, + Class::Shared, + Some((client::uma(e, k), pte::LEAF_NC)), + 0, + false, + )?, + GFP_KERNEL, + )?; + } + let freelist = alloc( + objects, + uma_pools::FREELIST_SIZE as u64, + Class::Shared, + Some((client::uma_freelist(e), pte::LEAF_NC)), + 0, + true, + )?; + let pool_table = alloc( + objects, + uma_pools::POOL_TABLE_SIZE as u64, + Class::Shared, + Some((client::uma_table_page(e), pte::LEAF_NC)), + uma_pools::POOL_TABLE_OFFSET as u64, + true, + )?; + let manager = alloc( + objects, + uma_manager::SIZE as u64, + manager_class(Class::Shared), + None, + 0, + true, + )?; + let counter = alloc(objects, counter::SIZE as u64, Class::Shared, None, 0, true)?; + Ok(( + Self { + pools, + freelist, + pool_table, + }, + manager, + counter, + )) + } +} + +/// The client GVA of an object with a client alias. +fn gva(object: &FwObject) -> Result { + object.gva.ok_or(EINVAL) +} + +impl Pools { + /// Allocates the render allocator objects: per engine the UMA pools, freelist, pool table, + /// manager and counter; block control, PB counter, misc, scene list and PB manager; the + /// uncached spare set; the PB page list, block list and heap. Contents are written by + /// [`Firmware::init_render_pools`]. + pub(crate) fn new(dev: &AsahiDevice, objects: &mut Objects) -> Result { + let (uma0, manager0, counter0) = UmaEngine::alloc(objects, 0)?; + let (uma1, manager1, counter1) = UmaEngine::alloc(objects, 1)?; + let small = |objects: &mut Objects, size: usize, class| { + alloc(objects, size as u64, class, None, 0, true) + }; + // A live producer with growth: firmware index 2. + let block_ctl_class = if tuning::PB_GROW { + Class::Fw + } else { + manager_class(Class::Fw) + }; + let block_ctl = small(objects, block_ctl::SIZE, block_ctl_class)?; + let pb_counter = small(objects, counter::SIZE, Class::Fw)?; + let misc = small(objects, misc::SIZE, manager_class(Class::Fw))?; + let scene_list = small(objects, buffer::SCENE_LIST_SIZE, Class::Shared)?; + let pb_manager = small(objects, pb_manager::SIZE, manager_class(Class::Fw))?; + let live = AllocatorSet { + uma_manager: [manager0, manager1], + uma_counter: [counter0, counter1], + block_ctl, + pb_counter, + misc, + scene_list, + pb_manager, + }; + // The uncached spare set for the first rebuild after an abort (manager_cached). + let spare = if tuning::MANAGER_CACHED { + let m0 = small(objects, uma_manager::SIZE, Class::Shared)?; + let c0 = small(objects, counter::SIZE, Class::Shared)?; + let m1 = small(objects, uma_manager::SIZE, Class::Shared)?; + let c1 = small(objects, counter::SIZE, Class::Shared)?; + Some(AllocatorSet { + uma_manager: [m0, m1], + uma_counter: [c0, c1], + block_ctl: small(objects, block_ctl::SIZE, Class::Fw)?, + pb_counter: small(objects, counter::SIZE, Class::Fw)?, + misc: small(objects, misc::SIZE, Class::Fw)?, + scene_list: small(objects, buffer::SCENE_LIST_SIZE, Class::Shared)?, + pb_manager: small(objects, pb_manager::SIZE, Class::Fw)?, + }) + } else { + None + }; + let pb_pages = alloc( + objects, + buffer::PAGE_LIST_SIZE as u64, + Class::Shared, + Some((client::PB_PAGE_LIST, pte::LEAF_PB_LIST)), + 0, + true, + )?; + let pb_blocks = alloc( + objects, + buffer::BLOCK_LIST_SIZE as u64, + Class::Shared, + Some((client::PB_BLOCK_LIST, pte::LEAF_PB_LIST)), + 0, + true, + )?; + // Backing for the initial blocks; growth adds the rest. + let ledger = Ledger::new(tuning::PB_GROW, tuning::PB_BLOCKS, tuning::PB_MAX_BLOCKS); + let mut chunks = + KVec::with_capacity(growth::max_chunks(ledger.initial, ledger.max), GFP_KERNEL)?; + chunks.push(PbChunk::new(dev, 0, ledger.initial)?, GFP_KERNEL)?; + Ok(Self { + dev: dev.as_ref().as_ref().into(), + drm: dev.into(), + uma: [uma0, uma1], + live, + spare_ready: spare.is_some(), + spare, + pb_pages, + pb_blocks, + chunks, + ledger, + c1_written: false, + exhausted_logged: false, + stats: PbStats::default(), + }) + } + + /// First rebuild after an abort with cached managers: the cached set may still have dirty + /// lines in the ASC, so it is retained untouched and the graph moves to the never-exposed + /// uncached spare (and its own counters and scene list), which [`Self::init`] then + /// initializes. + fn take_spare(&mut self) { + if let Some(spare) = self.spare.as_mut() { + core::mem::swap(&mut self.live, spare); + } + self.spare_ready = false; + dev_info!( + self.dev, + "render allocators moved to a fresh uncached set; the cached set is retained\n" + ); + } + + /// Writes the initial allocator state: UMA pools, freelists and managers; the PB lists, + /// manager and counters. The firmware owns them once published; rewritten (zeroed first) + /// only after a recovered render abort, followed by a fresh InitBM. + fn init(&mut self) -> Result { + for e in 0..2 { + let uma = &self.uma[e]; + let manager = &self.live.uma_manager[e]; + let count = &self.live.uma_counter[e]; + manager.fill(0, 0, uma_manager::SIZE)?; + count.fill(0, 0, counter::SIZE)?; + // Freelist: the eight 4 MiB pools in 0x1000 units. + let per_pool = (uma_pools::POOL_SIZE / uma_pools::SEED_BYTES) as usize; + let mut bases = [0u64; uma_pools::POOLS]; + for (k, pool) in uma.pools.iter().enumerate() { + bases[k] = gva(pool)?; + } + write_records(&uma.freelist, 0, uma_pools::POOLS * per_pool, |i| { + le64(bases[i / per_pool] + (i % per_pool) as u64 * uma_pools::SEED_BYTES) + })?; + for (k, base) in bases.iter().enumerate() { + uma.pool_table + .w64(uma_pools::POOL_TABLE_STRIDE * k, uma_pools::row(*base))?; + } + manager.write( + 0, + &buffer::uma_manager_image( + e as u32 + 1, + e as u32, + gva(&uma.freelist)?, + gva(&uma.pool_table)?, + count.va, + ), + )?; + count.w32(0, 1)?; + } + + // PB: 16384 pages of 0x8000 in 4096 blocks of 0x20000; with growth the first initial + // blocks of them, at most 4095 posted, and page limits at the firmware's growth maximum. + // In every profile the block list declares its real 4096-record capacity. + self.ledger = Ledger::new(tuning::PB_GROW, tuning::PB_BLOCKS, tuning::PB_MAX_BLOCKS); + self.exhausted_logged = false; + if tuning::PB_GROW { + // C1 names the initial pages again. + self.c1_written = false; + } + let set = &self.live; + set.pb_manager.fill(0, 0, pb_manager::SIZE)?; + set.block_ctl.fill(0, 0, block_ctl::SIZE)?; + set.misc.fill(0, 0, misc::SIZE)?; + set.pb_counter.fill(0, 0, counter::SIZE)?; + set.scene_list.fill(0, 0, buffer::SCENE_LIST_SIZE)?; + if tuning::PB_GROW { + self.pb_pages.fill(0, 0, buffer::PAGE_LIST_SIZE)?; + self.pb_blocks.fill(0, 0, buffer::BLOCK_LIST_SIZE)?; + } + let heap = client::PB_HEAP; + let initial = self.ledger.initial; + if initial > self.backed() { + return Err(EINVAL); + } + write_records( + &self.pb_pages, + 0, + (buffer::PAGES_PER_BLOCK * initial) as usize, + |i| buffer::page_record(heap, i as u32).to_le_bytes(), + )?; + // The high word of every block record is zero (zero-filled, or only ever written 0). + write_records(&self.pb_blocks, 0, initial as usize, |i| { + le64(buffer::block_record(heap, i as u32) as u64) + })?; + set.pb_manager.write( + 0, + // The maximum the firmware sees is the asynchronous growth limit, below the mapped + // heap: the blocks above it answer the synchronous requests a partial render makes + // (the firmware cannot finish a scene at its maximum without them; refused, its TA + // stalls and no kill ends it: ticket malik-na/linux-aurora#69). + &buffer::pb_manager_image( + initial, + self.soft_max(), + gva(&self.pb_pages)?, + gva(&self.pb_blocks)?, + set.block_ctl.va, + set.pb_counter.va, + ), + )?; + set.block_ctl.write(0, &buffer::block_ctl_image(initial))?; + set.misc.w32(misc::ENABLE, 1)?; + set.pb_counter.w32(0, 1)?; + crate::mem::sync(); + Ok(()) + } + + /// The allocator addresses the render encoders name (the live set: after the first + /// rebuild, the spare). + pub(crate) fn allocator_refs(&self) -> AllocatorRefs { + let set = &self.live; + AllocatorRefs { + uma_mgr: [set.uma_manager[0].va, set.uma_manager[1].va], + pb_mgr: set.pb_manager.va, + scene_list: set.scene_list.va, + mgr_misc: set.misc.va, + init_blocks: self.ledger.initial, + } + } + + /// The firmware's growth maximum in blocks (`g15_pb_max_blocks`), at least the initial size + /// and at most the mapped heap. + pub(crate) fn soft_max(&self) -> u32 { + super::params::pb_max_blocks().clamp(self.ledger.initial, self.ledger.max) + } + + /// The blocks with backing, from block 0. + pub(crate) fn backed(&self) -> u32 { + self.chunks.last().map_or(0, PbChunk::end) + } + + /// The debugfs line `pb: blocks initial/posted/firmware-max/max backed blocks/chunks + /// requests grown refused bad`. + pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { + writeln!( + f, + "pb: blocks {}/{}/{}/{} backed {}/{} requests {} grown {} refused {} bad {}", + self.ledger.initial, + self.ledger.posted, + self.soft_max(), + self.ledger.max, + self.backed(), + self.chunks.len(), + self.stats.requests, + self.stats.grown, + self.stats.refused, + self.stats.bad + ) + } +} + +impl Firmware { + /// Maps the PB backing into `vm` up to its last chunk, before anything of a prefix of the + /// VM is published (the start of `publish_prefix_into`). Render work runs in one VM at a + /// time (`Engine::publish`), so the VM about to run is the only one through which the GPU + /// can reach a posted block next; a VM created or idle while the backing grew catches up + /// here, also a closed VM whose accepted jobs still run. + /// + /// Each chunk's alias joins the VM's driver mappings, held until the VM is torn down, and + /// the VM's count moves past the chunk only then. When that fails, the alias just made is + /// dropped again: nothing of the VM runs before its count covers the chunk, and the leaf is + /// GPU-only, so the drop is a plain unmap. The chunks mapped before stay counted. + /// + /// The one-VM rule is checked first: a flight of another VM, or a count past the chunks, + /// fails with EPROTO before anything is mapped. + pub(crate) fn map_pb(&mut self, vm: &VmState) -> Result { + let mut mapped = vm.pb_chunks.load(Ordering::Relaxed); + if mapped > self.pools.chunks.len() + || self + .engine + .flights + .iter() + .any(|f| !core::ptr::eq(&*f.job.vm, vm)) + { + dev_err!( + self.dev(), + "PB backing: ctx {} maps {} of {} chunks with {} flights of another VM\n", + vm.slot, + mapped, + self.pools.chunks.len(), + self.engine + .flights + .iter() + .filter(|f| !core::ptr::eq(&*f.job.vm, vm)) + .count() + ); + return Err(super::boot::eproto()); + } + while let Some(chunk) = self.pools.chunks.get(mapped) { + let mut aliases = KVec::with_capacity(1, GFP_KERNEL)?; + aliases.push(chunk.map(&vm.vm)?, GFP_KERNEL)?; + vm.vm.append_driver_mappings(aliases)?; + mapped += 1; + vm.pb_chunks.store(mapped, Ordering::Relaxed); + } + Ok(()) + } + + /// The VM whose render work runs: every flight's (`Engine::publish` puts a flight behind + /// another only for the same VM), and it must be the asking context's. EPROTO otherwise. + fn running_vm(&self, ctx: u32) -> Result> { + let flights = &self.engine.flights; + let vm = flights + .first() + .ok_or_else(super::boot::eproto)? + .job + .vm + .clone(); + if vm.slot != ctx || flights.iter().any(|f| !Arc::ptr_eq(&f.job.vm, &vm)) { + dev_err!( + self.dev(), + "PB growth: ctx {} is not the one VM in flight (ctx {}, {} flights)\n", + ctx, + vm.slot, + flights.len() + ); + return Err(super::boot::eproto()); + } + Ok(vm) + } + + /// Backs the PB up to block `end` in the VM that runs, the asking context `ctx`, before an + /// answer posts those blocks (nothing new when they are backed already): chunks of at most + /// [`growth::CHUNK_BLOCKS`] blocks are allocated ([`object::gpu_backing`]), mapped into that + /// VM and kept, one at a time. The VM first catches up ([`Self::map_pb`], which also checks + /// the one-VM rule), so its count equals the chunks. A chunk is kept + /// only once its alias in the VM is held, and the VM's count moves with it; when the alias + /// cannot be held, the alias and the chunk are dropped, neither ever reachable (the leaf is + /// GPU-only: a plain unmap). An error leaves the chunks backed so far for the next request, + /// and nothing is posted. The allocation sleeps (shmem pages with `__GFP_RETRY_MAYFAIL`) + /// while the firmware waits for the answer; how long is not bounded here. + fn back_pb(&mut self, end: u32, ctx: u32) -> Result { + let vm = self.running_vm(ctx)?; + self.map_pb(&vm)?; + while self.pools.backed() < end { + let (first, blocks) = + growth::next_chunk(self.pools.backed(), self.pools.ledger.max).ok_or(ENOSPC)?; + if self.pools.chunks.len() == self.pools.chunks.capacity() { + return Err(ENOSPC); + } + let chunk = PbChunk::new(&self.pools.drm, first, blocks)?; + let mut aliases = KVec::with_capacity(1, GFP_KERNEL)?; + aliases.push(chunk.map(&vm.vm)?, GFP_KERNEL)?; + vm.vm.append_driver_mappings(aliases)?; + // Within the capacity checked above. + self.pools + .chunks + .push_within_capacity(chunk) + .map_err(|_| EIO)?; + vm.pb_chunks + .store(self.pools.chunks.len(), Ordering::Relaxed); + } + Ok(()) + } + + /// (Re)initializes the render UMA managers, PB lists and PB manager. `rebuild`: the priming + /// prefix after a recovered abort: the first one moves to the uncached spare set, later + /// ones rewrite it in place. + pub(crate) fn init_render_pools(&mut self, rebuild: bool) -> Result { + if rebuild && self.pools.spare_ready { + self.pools.take_spare(); + } + self.pools.init() + } + + /// The PB counters of a publication with renders, after the render threshold: the PB + /// counter names the prefix's last draw, and C1 = {0x07400000, 4 * initial blocks} is + /// written once per (re)initialization. An error leaves the prefix unpublished. + pub(crate) fn publish_pb(&mut self, draw: u32) -> Result { + self.pools.live.pb_counter.w32(0, draw)?; + if !self.pools.c1_written { + self.write_c1(&buffer::c1_record(self.pools.ledger.initial))?; + self.pools.c1_written = true; + } + Ok(()) + } + + /// Answers the firmware's PB-growth requests, outside the event drain. + /// A request names PB slot 0, the context of a published render prefix and the next + /// request counter; anything else is logged and left unanswered (its TA then stays stalled + /// and the deadline applies). With growth up to ten more blocks of the mapped heap are + /// written to unposted block-list records, then the live block_ctl+4 producer advances and + /// DEVCTL 7 reports success; at the ledger's maximum the reply is the refusal (+4 = 0), + /// which gives the firmware no new pages, and after two refusals requests are left + /// unanswered. The firmware imports the blocks itself: P is never rewritten. Only the + /// requests queued before the pass are taken. A failed reply is logged; a request that + /// cannot be processed at all (a firmware object access failed) is logged and left + /// unanswered like an invalid one. Never fails: the poll pass continues. + pub(crate) fn answer_growth(&mut self) -> Result { + // Only the requests queued before this pass: a reply's wait drains the rings and may + // queue the next request, which the next pass answers (the device lock is released in + // between). + let queued = self.events.grow.len(); + for _ in 0..queued { + let Ok(request) = self.events.grow.remove(0) else { + break; + }; + self.pools.stats.requests += 1; + if let Err(e) = self.answer_request(&request) { + self.pools.stats.bad += 1; + dev_err!( + self.dev(), + "PB growth request {} ctx {} not answered: {}\n", + request[buffer::grow_request::COUNTER], + request[buffer::grow_request::CONTEXT], + e.to_errno() + ); + } + } + Ok(()) + } + + /// Processes one growth request. + fn answer_request(&mut self, request: &[u32; 14]) -> Result { + let ctl = self.init.control.clone().ok_or(ENODEV)?; + let epoch = + ctl.r32(control::HALT_COUNT)? as u64 | (ctl.r32(control::HALT_COUNT + 4)? as u64) << 32; + let ctx = request[buffer::grow_request::CONTEXT]; + let live = self + .engine + .flights + .iter() + .enumerate() + .any(|(i, f)| self.receipts(i).renders != 0 && f.job.vm.slot == ctx); + // At the maximum, after the refusals, the request is left unanswered: the poll pass + // returns, and the host deadline and its recovery path apply to a stalled TA. + if self.pools.ledger.exhausted() { + self.pools.stats.bad += 1; + if !self.pools.exhausted_logged { + self.pools.exhausted_logged = true; + dev_warn!( + self.dev(), + "PB growth request {} ctx {} left unanswered: {} refusals at the maximum ({} blocks); the host deadline applies\n", + request[buffer::grow_request::COUNTER], + ctx, + self.pools.ledger.refusals, + self.pools.ledger.max + ); + } + return Ok(()); + } + // A request from before a halt has no authority over the PB now. + if !self + .pools + .ledger + .admits(request, tuning::PB_GROW, live, epoch) + { + self.pools.stats.bad += 1; + dev_warn!( + self.dev(), + "PB growth request not answered: ctx {} slot {} counter {} (next {}) epoch {:#x} (now {:#x}) live {} pb_grow {}\n", + ctx, + request[buffer::grow_request::SLOT], + request[buffer::grow_request::COUNTER], + self.pools.ledger.next_request, + growth::request_epoch(request), + epoch, + live as u32, + tuning::PB_GROW as u32 + ); + return Ok(()); + } + // Every block the answer posts is backed in the VM that runs before anything of the + // answer is written; the one-VM rule is checked for every answer. If that fails, nothing + // is posted or answered (answer_growth logs it; the deadline applies), and the backing + // made so far stays for the next request. + let end = self.pools.ledger.posted + self.pools.ledger.next_count(); + self.back_pb(end, ctx)?; + let (first, n) = self.pools.ledger.accept(request); + let heap = client::PB_HEAP; + for b in first..first + n { + self.pools.pb_blocks.w64( + buffer::block_record_offset(b), + buffer::block_record(heap, b) as u64, + )?; + } + if n != 0 { + // Records before their producer. + crate::mem::sync(); + let producer = self.pools.ledger.post(n); + self.pools + .live + .block_ctl + .w32(block_ctl::PRODUCER, producer)?; + // Producer before the reply. + crate::mem::sync(); + self.pools.stats.grown += n as u64; + } else { + self.pools.stats.refused += 1; + } + let reply = DevCtl { + words: buffer::grow_reply_words(request, n != 0), + }; + let ret = self.devctl(&reply, true); + let ledger = self.pools.ledger; + let soft = self.pools.soft_max(); + // Every answer past the firmware's maximum is logged with its TA position: a scene + // that keeps asking at one position is a runaway, one that advances is large. + let past_soft = n != 0 && ledger.posted > soft; + let info = self.pools.ledger.log_answer(request, n, ret.is_err()) || past_soft; + let (counter, position) = ( + request[buffer::grow_request::COUNTER], + request[buffer::grow_request::POSITION], + ); + let ret = match ret { + Ok(()) => 0, + Err(e) => e.to_errno(), + }; + if info { + dev_info!( + self.dev(), + "PB growth request {} ctx {} position {}: +{} blocks ({} of {}), DEVCTL 7: {}\n", + counter, + ctx, + position, + n, + ledger.posted, + ledger.max, + ret + ); + } else { + dev_dbg!( + self.dev(), + "PB growth request {} ctx {} position {}: +{} blocks ({} of {}), DEVCTL 7: {}\n", + counter, + ctx, + position, + n, + ledger.posted, + ledger.max, + ret + ); + } + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/g15/pools/growth.rs b/drivers/gpu/drm/asahi/g15/pools/growth.rs new file mode 100644 index 00000000000000..20b298e641459d --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/pools/growth.rs @@ -0,0 +1,390 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The PB growth ledger and the growth-request checks. +//! +//! The firmware asks for more PB with an event of type 7 naming PB slot 0, the context of a +//! published render, its request counter (P+0x60 before its increment), the TA position and the +//! halt epoch; the host appends at most ten blocks of the mapped heap to the block list and +//! advances the block_ctl+4 producer (modulo K), then replies with DEVCTL 7. At the ledger's +//! maximum the reply refuses; after [`MAX_REFUSALS`] refusals since the last initialization, +//! later requests are left unanswered. That bounds the poll pass. It does not make the scene +//! finish: a refused or unanswered request can leave the TA stalled, and the host deadline and +//! its recovery path then apply, without a guarantee that they end the stall. A request from +//! before a halt (epoch) or not matching a published render prefix is left unanswered. +//! +//! Core-only (no `kernel` imports): this file is compiled by the host test harness as well. + +use crate::g15::fw::buffer::{grow_request, BLOCK_LIST_RECORDS, GROW_STEP, MAX_BLOCKS, MIN_BLOCKS}; + +/// The PB ledger since the last (re)initialization. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Ledger { + /// Initial blocks (the C1 pages, InitBM blocks and TA register #33 name them). + pub(crate) initial: u32, + /// The most blocks posted, at most [`MAX_POSTED`]. The PB manager's P+0x70/+0x74 hold + /// 4 * the firmware's growth maximum (`Pools::soft_max()`) in pages, which may be lower. + pub(crate) max: u32, + /// Blocks posted to the block list, cumulative (the block_ctl+4 producer is this modulo K). + pub(crate) posted: u32, + /// The next expected request counter. + pub(crate) next_request: u32, + /// A refusal at the maximum was logged since the last initialization. + pub(crate) refusal_logged: bool, + /// Refusals answered at the maximum since the last initialization. After + /// [`MAX_REFUSALS`] further requests are left unanswered: a firmware that keeps asking at + /// the maximum would otherwise be answered forever, under the device lock (ticket + /// malik-na/linux-aurora#69). Unanswered, the poll pass returns, and the host deadline and + /// its recovery path apply. + pub(crate) refusals: u32, +} + +/// Refusals answered at the maximum before requests are left to the deadline. +pub(crate) const MAX_REFUSALS: u32 = 2; + +/// Blocks of each PB backing chunk after the initial one (4 MiB): growth backs at most this +/// much at a time while the firmware waits for its answer. +pub(crate) const CHUNK_BLOCKS: u32 = 32; + +/// The backing chunk that follows `backed` blocks of a ledger with maximum `max`: its first block +/// and size, at most [`CHUNK_BLOCKS`] and never past `max`; none from `max` on. +pub(crate) const fn next_chunk(backed: u32, max: u32) -> Option<(u32, u32)> { + if backed >= max { + None + } else if max - backed < CHUNK_BLOCKS { + Some((backed, max - backed)) + } else { + Some((backed, CHUNK_BLOCKS)) + } +} + +/// The chunks that back a ledger with `initial` and `max` blocks at most: the initial one and +/// [`next_chunk`]'s from `initial` to `max`. +pub(crate) const fn max_chunks(initial: u32, max: u32) -> usize { + 1 + max.saturating_sub(initial).div_ceil(CHUNK_BLOCKS) as usize +} + +/// The most blocks a ledger posts: the mapped heap, and below K, so that the block_ctl+4 +/// producer (posted modulo K) is never 0, the value of an empty block list. +pub(crate) const MAX_POSTED: u32 = if MAX_BLOCKS < BLOCK_LIST_RECORDS { + MAX_BLOCKS +} else { + BLOCK_LIST_RECORDS - 1 +}; + +impl Ledger { + /// A fresh ledger. With growth, the initial size is clamped to 64..=[`MAX_POSTED`] blocks + /// and the maximum to initial..=[`MAX_POSTED`]; without, both are [`MAX_POSTED`]. + pub(crate) const fn new(grow: bool, blocks: u32, max_blocks: u32) -> Self { + let (initial, max) = if grow { + let nb = clamp(blocks, MIN_BLOCKS, MAX_POSTED); + (nb, clamp(max_blocks, nb, MAX_POSTED)) + } else { + (MAX_POSTED, MAX_POSTED) + }; + Self { + initial, + max, + posted: initial, + next_request: 0, + refusal_logged: false, + refusals: 0, + } + } + + /// The live block_ctl+4 producer. + pub(crate) const fn producer(&self) -> u32 { + self.posted % BLOCK_LIST_RECORDS + } + + /// Whether the refusals at the maximum are used up: further requests go unanswered. + pub(crate) const fn exhausted(&self) -> bool { + self.refusals >= MAX_REFUSALS + } + + /// Whether `request` may be answered: growth on, an event of type 7 for PB slot 0 from a + /// context with a published render prefix (`live`), a counter not below the next expected + /// one, the current halt epoch, and refusals at the maximum not used up. + pub(crate) fn admits(&self, request: &[u32; 14], grow: bool, live: bool, epoch: u64) -> bool { + !self.exhausted() + && grow + && request[grow_request::TYPE] == 7 + && request[grow_request::SLOT] == 0 + && live + && request[grow_request::COUNTER] >= self.next_request + && request_epoch(request) == epoch + } + + /// The blocks the next accepted request posts: at most [`GROW_STEP`], none at the maximum. + pub(crate) fn next_count(&self) -> u32 { + GROW_STEP.min(self.max - self.posted) + } + + /// Accepts an admitted request: the next expected counter follows it, and the returned + /// blocks `[first, first + count)` are to be written to the block list, `count` 0 meaning a + /// refusal at the maximum. + pub(crate) fn accept(&mut self, request: &[u32; 14]) -> (u32, u32) { + self.next_request = request[grow_request::COUNTER].wrapping_add(1); + let count = self.next_count(); + if count == 0 { + self.refusals += 1; + } + (self.posted, count) + } + + /// Records `count` blocks as posted after their records were written and returns the new + /// producer. + pub(crate) fn post(&mut self, count: u32) -> u32 { + self.posted += count; + self.producer() + } + + /// Whether the answer is logged at info level: a failed reply, the first two requests, or + /// the first refusal at the maximum since the initialization. Records the refusal. + pub(crate) fn log_answer( + &mut self, + request: &[u32; 14], + count: u32, + reply_failed: bool, + ) -> bool { + let info = reply_failed + || request[grow_request::COUNTER] < 2 + || (count == 0 && self.posted == self.max && !self.refusal_logged); + self.refusal_logged |= count == 0; + info + } +} + +/// The halt epoch a request names (u64 at words 5..6). +pub(crate) const fn request_epoch(request: &[u32; 14]) -> u64 { + request[grow_request::EPOCH] as u64 | (request[grow_request::EPOCH + 1] as u64) << 32 +} + +const fn clamp(v: u32, lo: u32, hi: u32) -> u32 { + if v < lo { + lo + } else if v > hi { + hi + } else { + v + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(ctx: u32, counter: u32, epoch: u64) -> [u32; 14] { + let mut q = [0u32; 14]; + q[0] = 7; + q[1] = ctx; + q[2] = 0; + q[3] = counter; + q[4] = 0x100; + q[5] = epoch as u32; + q[6] = (epoch >> 32) as u32; + q + } + + #[test] + fn clamps() { + let l = Ledger::new(true, 1024, 2048); + assert_eq!( + (l.initial, l.max, l.posted, l.next_request), + (1024, 2048, 1024, 0) + ); + assert_eq!(l.producer(), 1024); + assert_eq!(Ledger::new(true, 10, 20).initial, 64); + assert_eq!(Ledger::new(true, 10, 20).max, 64); + assert_eq!(Ledger::new(true, 5000, 100).initial, 4095); + assert_eq!(Ledger::new(true, 512, 1024).max, 1024); + assert_eq!(Ledger::new(true, 512, 100).max, 512); + let fixed = Ledger::new(false, 512, 1024); + assert_eq!((fixed.initial, fixed.max, fixed.posted), (4095, 4095, 4095)); + // The values the driver passes (tuning::PB_BLOCKS, tuning::PB_MAX_BLOCKS) are kept. + let l = Ledger::new(true, 1024, 4095); + assert_eq!( + (l.initial, l.max, l.posted, l.producer()), + (1024, 4095, 1024, 1024) + ); + } + + #[test] + fn producer_never_returns_to_zero() { + assert_eq!(MAX_POSTED, 4095); + assert!(MAX_POSTED <= MAX_BLOCKS && MAX_POSTED < BLOCK_LIST_RECORDS); + let values = [ + 0, + 1, + MIN_BLOCKS - 1, + MIN_BLOCKS, + MIN_BLOCKS + 1, + 1023, + 1024, + 1025, + 3071, + 3072, + 3073, + MAX_POSTED - 1, + MAX_POSTED, + MAX_BLOCKS, + MAX_BLOCKS + 1, + BLOCK_LIST_RECORDS, + 2 * BLOCK_LIST_RECORDS, + u32::MAX, + ]; + for grow in [true, false] { + for blocks in values { + for max_blocks in values { + let mut l = Ledger::new(grow, blocks, max_blocks); + assert!(MIN_BLOCKS <= l.initial && l.initial <= l.max && l.max <= MAX_POSTED); + assert_eq!(l.posted, l.initial); + assert!((1..=MAX_POSTED).contains(&l.producer())); + // Every producer of a growth to the maximum stays in 1..=4095. + let mut counter = 0; + loop { + let (first, n) = l.accept(&request(5, counter, 1)); + assert_eq!(first, l.posted); + if n == 0 { + break; + } + let producer = l.post(n); + assert!((1..=MAX_POSTED).contains(&producer)); + assert_eq!(producer, l.posted); + counter += 1; + } + assert_eq!(l.posted, l.max); + assert_eq!(l.refusals, 1); + } + } + } + } + + #[test] + fn admission() { + let l = Ledger::new(true, 1024, 2048); + let q = request(5, 0, 3); + assert!(l.admits(&q, true, true, 3)); + assert!(!l.admits(&q, false, true, 3)); + assert!(!l.admits(&q, true, false, 3)); + // Request of an earlier halt epoch (dropped at recovery, never answered). + assert!(!l.admits(&q, true, true, 4)); + let mut bad = q; + bad[0] = 6; + assert!(!l.admits(&bad, true, true, 3)); + let mut bad = q; + bad[2] = 1; + assert!(!l.admits(&bad, true, true, 3)); + // 64-bit epochs. + let q = request(5, 0, 0x1_0000_0002); + assert!(l.admits(&q, true, true, 0x1_0000_0002)); + assert!(!l.admits(&q, true, true, 2)); + } + + #[test] + fn growth_to_the_maximum() { + // 512 initial and 1024 maximum blocks. + let mut l = Ledger::new(true, 512, 1024); + let mut grown = 0; + let mut counter = 0; + loop { + let q = request(5, counter, 1); + assert!(l.admits(&q, true, true, 1)); + let (first, n) = l.accept(&q); + assert_eq!(first, 512 + grown); + if n == 0 { + break; + } + assert!(n <= 10); + assert_eq!(l.post(n), (512 + grown + n) % 4096); + grown += n; + counter += 1; + } + assert_eq!(l.posted, 1024); + assert_eq!(grown, 512); + // 51 requests of 10 blocks and one of 2. + assert_eq!(counter, 52); + // A stale (repeated) counter is refused, a later one accepted. + assert!(!l.admits(&request(5, counter - 1, 1), true, true, 1)); + assert!(l.admits(&request(5, counter + 3, 1), true, true, 1)); + // One refusal was answered above; one more is, then requests go unanswered. + assert_eq!(l.refusals, 1); + assert!(!l.exhausted()); + let q = request(5, counter + 3, 1); + assert_eq!(l.accept(&q), (1024, 0)); + assert!(l.exhausted()); + assert!(!l.admits(&request(5, counter + 4, 1), true, true, 1)); + // A fresh ledger starts over. + assert!(!Ledger::new(true, 512, 1024).exhausted()); + } + + /// Backing for every ledger the constructor makes, the driver's included: the chunks from + /// the initial one are contiguous, at most [`CHUNK_BLOCKS`] each, end at the maximum and + /// number at most [`max_chunks`]; growth with the backing made first never posts a block + /// past it. + #[test] + fn backing_chunks() { + assert_eq!(max_chunks(1024, 4095), 1 + 96); + assert_eq!(max_chunks(MIN_BLOCKS, MAX_POSTED), 1 + 126); + assert_eq!(max_chunks(MAX_POSTED, MAX_POSTED), 1); + assert_eq!(next_chunk(1024, 4095), Some((1024, 32))); + assert_eq!(next_chunk(4064, 4095), Some((4064, 31))); + assert_eq!(next_chunk(4095, 4095), None); + assert_eq!(next_chunk(4096, 4095), None); + let values = [ + 0, 1, MIN_BLOCKS, 65, 1023, 1024, 1025, 3072, 4094, MAX_POSTED, 5000, + ]; + for grow in [true, false] { + for blocks in values { + for max_blocks in values { + let mut l = Ledger::new(grow, blocks, max_blocks); + let (mut backed, mut chunks) = (l.initial, 1); + let mut counter = 0; + loop { + let end = l.posted + l.next_count(); + while backed < end { + let (first, n) = next_chunk(backed, l.max).unwrap(); + assert_eq!(first, backed); + assert!(n >= 1 && n <= CHUNK_BLOCKS); + backed += n; + chunks += 1; + } + let (first, n) = l.accept(&request(5, counter, 1)); + assert!(first + n <= backed); + if n == 0 { + break; + } + l.post(n); + counter += 1; + } + assert_eq!((l.posted, backed), (l.max, l.max)); + assert!(chunks <= max_chunks(l.initial, l.max)); + assert_eq!(next_chunk(backed, l.max), None); + } + } + } + } + + #[test] + fn producer_wraps_at_k() { + let mut l = Ledger::new(true, 2048, 2048); + assert_eq!(l.producer(), 2048); + l.posted = 4095; + assert_eq!(l.post(1), 0); + assert_eq!(l.post(10), 10); + } + + #[test] + fn logging() { + let mut l = Ledger::new(true, 64, 64); + // The first two requests are logged. + assert!(l.log_answer(&request(1, 0, 0), 10, false)); + assert!(l.log_answer(&request(1, 1, 0), 10, false)); + assert!(!l.log_answer(&request(1, 2, 0), 10, false)); + // A failed reply is logged. + assert!(l.log_answer(&request(1, 5, 0), 10, true)); + // The first refusal at the maximum is logged once. + assert!(l.log_answer(&request(1, 6, 0), 0, false)); + assert!(!l.log_answer(&request(1, 7, 0), 0, false)); + assert!(l.refusal_logged); + } +} diff --git a/drivers/gpu/drm/asahi/g15/power.rs b/drivers/gpu/drm/asahi/g15/power.rs new file mode 100644 index 00000000000000..58b6636fde383c --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/power.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The firmware idle policy. +//! +//! The words and their rationale are in [`idle`]. Initdata writes them into the Globals image +//! before the firmware first sees it: +//! +//! - +0x7a8 standby = `g15_idle_standby_us` when set (clamped 100..100000), else the GPU node's +//! `apple,idleoff-standby-timer`, else the tuned 2500 ([`idle::standby`]); +//! - +0x7c4 minimum confidence = `g15_idle_min_conf` (500 permille as f32); +//! - +0x30 predictive = 0 ([`super::hw::tuning::IDLE_PREDICTIVE`]): the finite delay, the GPU +//! powers down after the +0x9a0 delay (template 2, about 2 ms); +//! - +0x2c idle decision enabled (template 1, unchanged). +//! +//! DVFS is firmware-run on the ADT tables. The state it runs at is read back by +//! `asahi-g15/pstate` ([`pstate`], [`super::Firmware::write_pstate`]): the newest power-state +//! record of the stats ring, and HardwareDataA's state words. + +mod idle; +pub(crate) mod pstate; +pub(crate) use idle::{permille_f32, standby}; + +use kernel::{fmt, prelude::*}; + +use super::board; +use super::fw::initdata::{globals, hwdata}; +use super::hw::rings; +use super::Firmware; + +static_assert!(idle::ENABLE == globals::IDLE_ENABLE); +static_assert!(idle::PREDICTIVE == globals::IDLE_PREDICTIVE); +static_assert!(idle::STANDBY_US == globals::IDLE_STANDBY_US); +static_assert!(idle::MIN_CONF == globals::IDLE_MIN_CONF); +static_assert!(idle::DELAY == globals::IDLE_DELAY); + +static_assert!(pstate::STATES == board::DVFS_STATES); +static_assert!(pstate::STATS_RECORD * pstate::STATS_SLOTS as usize == rings::STATS_RING_SIZE); +static_assert!(pstate::STATS_SLOTS == super::fw::channels::RING_SLOTS); + +impl Firmware { + /// HardwareDataA's state words, as the firmware last wrote them. + fn pstate_words(&self) -> Result { + let hw = self.init.hwdata.as_ref().ok_or(ENODEV)?; + let word = |offset: usize| hw.r32(hwdata::HWDATA_A + offset); + Ok(pstate::HwWords { + actual: word(pstate::HWDATA_A_ACTUAL)?, + target: word(pstate::HWDATA_A_TARGET)?, + current: word(pstate::HWDATA_A_CURRENT)?, + freq_mhz: word(pstate::HWDATA_A_FREQ_MHZ)?, + }) + } + + /// The `asahi-g15/pstate` file ([`pstate::write`]): the stats ring's records so far, those + /// it holds unconsumed (read, not consumed), HardwareDataA's words and table A of the + /// device tree's operating points. Read-only: nothing firmware-visible is written. + pub(crate) fn write_pstate(&self, f: &mut impl fmt::Write) -> fmt::Result { + let Ok(hw) = self.pstate_words() else { + return Ok(()); + }; + let seen = self + .channels + .peek_stats() + .unwrap_or(self.channels.stats_seen); + let table = pstate::Table::from_mhz(board::table_a_mhz(&self.session.adt)); + pstate::write(f, &seen, &hw, &table) + } +} diff --git a/drivers/gpu/drm/asahi/g15/power/idle.rs b/drivers/gpu/drm/asahi/g15/power/idle.rs new file mode 100644 index 00000000000000..0db36fd859e504 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/power/idle.rs @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The firmware idle-policy words. +//! +//! Globals inputs of the firmware's idle decision: +//! +//! - +0x7a8 standby time, us (board template 700): the GPU stays up about this long after its +//! last work; tuned 2500 (with 700 us the GPU powers down between works ~100 us apart and +//! pays ~300 us at the next pickup). +//! - +0x7c4 minimum confidence of the predictive model, f32 (template 0x3f333333 = 0.7); tuned +//! 0.5. +//! - +0x30 predictive branch (template 1); 0 = the ordinary finite delay: the GPU powers down +//! once idle for the +0x9a0 delay (template 2, about 2 ms). The predictive branch makes 2-3 % +//! of works under sustained low-duty submission pay a ~300 us power-up. +//! - +0x2c enables the idle decision (template 1, unchanged). +//! +//! The standby time comes from [`standby`]: the explicit `g15_idle_standby_us` when set, else the +//! device tree's `apple,idleoff-standby-timer` where the machine has one, else the tuned value. +//! +//! Core-only (no `kernel` imports), so that it can be tested on the host. + +/// Globals offsets (mirrors of `fw::initdata::globals`). +pub(crate) const ENABLE: usize = 0x2c; +pub(crate) const PREDICTIVE: usize = 0x30; +pub(crate) const STANDBY_US: usize = 0x7a8; +pub(crate) const MIN_CONF: usize = 0x7c4; +pub(crate) const DELAY: usize = 0x9a0; + +/// Where the standby time came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum StandbySource { + /// The `g15_idle_standby_us` module parameter. + Parameter, + /// The GPU node's `apple,idleoff-standby-timer`. + DeviceTree, + /// The tuned value. + Tuning, +} + +impl StandbySource { + pub(crate) const fn name(self) -> &'static str { + match self { + Self::Parameter => "the module parameter", + Self::DeviceTree => "the device tree", + Self::Tuning => "the tuning", + } + } +} + +/// Bounds of an explicit or device-tree standby time, us. +pub(crate) const STANDBY_MIN_US: u32 = 100; +pub(crate) const STANDBY_MAX_US: u32 = 100000; + +/// Chooses the standby time, us: `param` (0: not set, else clamped to the bounds) wins, then +/// `dt` (the device-tree value, if the machine has one and it is within the bounds), else +/// `tuned`. Returns the value and its source; the flag tells a device-tree value outside the +/// bounds was ignored. +pub(crate) fn standby(param: u32, dt: Option, tuned: u32) -> (u32, StandbySource, bool) { + let rejected = matches!(dt, Some(v) if !(STANDBY_MIN_US..=STANDBY_MAX_US).contains(&v)); + if param != 0 { + return ( + param.clamp(STANDBY_MIN_US, STANDBY_MAX_US), + StandbySource::Parameter, + rejected, + ); + } + match dt { + Some(v) if !rejected => (v, StandbySource::DeviceTree, false), + _ => (tuned, StandbySource::Tuning, rejected), + } +} + +/// IEEE-754 single bits of `permille / 1000`, `permille` clamped to 1..=1000 (0 cannot be +/// expressed: it reads 0.001). +pub(crate) const fn permille_f32(permille: u32) -> u32 { + let p = if permille < 1 { + 1 + } else if permille > 1000 { + 1000 + } else { + permille + }; + // p/1000 * 2^k in [0.5, 1). + let mut k = 0u32; + while p * (1u32 << k) < 500 { + k += 1; + } + if p == 1000 { + return 0x3f800000; + } + // p/1000 = m/2^24 * 2^(1-k-1), m in [2^23, 2^24). + ((126 - k) << 23) | ((((p as u64) << (24 + k)) / 1000) as u32 - (1u32 << 23)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f32_bits(x: f32) -> u32 { + x.to_bits() + } + + #[test] + fn standby_choice() { + use StandbySource::*; + assert_eq!(standby(0, Some(1234), 2500), (1234, DeviceTree, false)); + assert_eq!(standby(0, None, 2500), (2500, Tuning, false)); + assert_eq!(standby(900, Some(1234), 2500), (900, Parameter, false)); + assert_eq!(standby(900, None, 2500), (900, Parameter, false)); + assert_eq!(standby(5, None, 2500), (100, Parameter, false)); + assert_eq!(standby(10_000_000, None, 2500), (100000, Parameter, false)); + assert_eq!(standby(0, Some(0), 2500), (2500, Tuning, true)); + assert_eq!(standby(0, Some(100001), 2500), (2500, Tuning, true)); + assert_eq!(standby(0, Some(100), 2500), (100, DeviceTree, false)); + assert_eq!(standby(0, Some(100000), 2500), (100000, DeviceTree, false)); + assert_eq!(standby(700, Some(0), 2500), (700, Parameter, true)); + } + + #[test] + fn permille() { + assert_eq!(permille_f32(500), 0x3f000000); + assert_eq!(permille_f32(700), 0x3f333333); + assert_eq!(permille_f32(1000), 0x3f800000); + assert_eq!(permille_f32(2000), 0x3f800000); + assert_eq!(permille_f32(0), permille_f32(1)); + assert_eq!(permille_f32(250), 0x3e800000); + // Within one ulp (truncation) of the nearest float everywhere. + for p in 1..=1000u32 { + let want = f32_bits(p as f32 / 1000.0); + let got = permille_f32(p); + assert!(want.abs_diff(got) <= 1, "{p}: {got:#x} vs {want:#x}"); + } + } +} diff --git a/drivers/gpu/drm/asahi/g15/power/pstate.rs b/drivers/gpu/drm/asahi/g15/power/pstate.rs new file mode 100644 index 00000000000000..411fe224138931 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/power/pstate.rs @@ -0,0 +1,376 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The GPU's current performance state, as the firmware reports it. +//! +//! Two places carry it: +//! +//! - The stats ring: 256 records of 0x40 bytes, a u32 tag at +0 and, in a power-state record +//! (tag 0x0b), the performance-state index at +0x20. +//! - HardwareDataA (hardware record +0x4580): actual (+0x2c), target (+0x30) and current +//! (+0x38) state indices and the frequency in MHz as an IEEE single (+0x58). +//! +//! An index counts the firmware's DVFS states, 0 (off) to 8; its frequency is the state's +//! table-A operating point ([`super::super::board`]), taken from the device tree. +//! +//! [`write`] prints the `asahi-g15/pstate` file. Its first line is what a sampler reads: +//! `pstate freq_khz source `, from the newest power-state record +//! seen, or HardwareDataA's current state when the stats ring has carried none. +//! +//! Core-only (no `kernel` imports), so that it can be tested on the host. + +use core::fmt; + +/// DVFS states of the firmware tables (= `board::DVFS_STATES`). +pub(crate) const STATES: usize = 9; + +/// HardwareDataA words. +pub(crate) const HWDATA_A_ACTUAL: usize = 0x2c; +pub(crate) const HWDATA_A_TARGET: usize = 0x30; +pub(crate) const HWDATA_A_CURRENT: usize = 0x38; +pub(crate) const HWDATA_A_FREQ_MHZ: usize = 0x58; + +/// Stats ring records. +pub(crate) const STATS_RECORD: usize = 0x40; +pub(crate) const STATS_SLOTS: u32 = 256; +pub(crate) const STATS_TAG: usize = 0x00; +pub(crate) const TAG_POWER_STATE: u32 = 0x0b; +pub(crate) const POWER_STATE_INDEX: usize = 0x20; + +/// Tags counted one by one; higher tags are counted together. +pub(crate) const TAGS: usize = 16; + +/// What the stats ring has carried. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct StatsSeen { + /// Records consumed. + pub(crate) records: u64, + /// Records per tag; the last slot counts every tag from `TAGS - 1` up. + pub(crate) tags: [u64; TAGS], + /// The index of the newest power-state record. + pub(crate) last: Option, +} + +impl StatsSeen { + /// Notes one record: its tag and the word at [`POWER_STATE_INDEX`]. + pub(crate) fn note(&mut self, tag: u32, index: u32) { + self.records = self.records.wrapping_add(1); + let slot = (tag as usize).min(TAGS - 1); + self.tags[slot] = self.tags[slot].wrapping_add(1); + if tag == TAG_POWER_STATE { + self.last = Some(index); + } + } +} + +/// The ring slots from the consumer `read` to the producer `write`, oldest first; `None` when +/// either index is out of the ring. +pub(crate) fn pending(read: u32, write: u32) -> Option> { + if read >= STATS_SLOTS || write >= STATS_SLOTS { + return None; + } + let count = (write + STATS_SLOTS - read) % STATS_SLOTS; + Some((0..count).map(move |i| (read + i) % STATS_SLOTS)) +} + +/// The HardwareDataA words. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct HwWords { + pub(crate) actual: u32, + pub(crate) target: u32, + pub(crate) current: u32, + /// IEEE single bits, MHz. + pub(crate) freq_mhz: u32, +} + +/// The table-A frequency of each firmware state, kHz. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Table { + pub(crate) khz: [u32; STATES], +} + +impl Table { + /// From the table-A operating points in MHz. + pub(crate) fn from_mhz(mhz: [u32; STATES]) -> Self { + Self { + khz: mhz.map(|m| m.saturating_mul(1000)), + } + } + + /// The frequency of state `index`, kHz; `None` past the table. + pub(crate) fn khz(&self, index: u32) -> Option { + self.khz.get(index as usize).copied() + } +} + +/// An IEEE single number of MHz in kHz, rounded to nearest; `None` for a negative number, an +/// infinity, a NaN or a value past `u32::MAX` kHz. +pub(crate) fn f32_mhz_to_khz(bits: u32) -> Option { + let exp = (bits >> 23) & 0xff; + let frac = bits & 0x7f_ffff; + if bits & 0x7fff_ffff == 0 { + return Some(0); + } + if bits >> 31 != 0 || exp == 0xff { + return None; + } + // value = m * 2^(e - 150); a subnormal has no implicit bit and e = 1. + let (m, e) = if exp == 0 { + (frac as u64, 1i32) + } else { + ((frac | 0x80_0000) as u64, exp as i32) + }; + let scaled = m * 1000; // < 2^34 + let shift = e - 150; + let khz = if shift >= 0 { + if shift > 31 { + return None; + } + scaled << shift + } else { + let s = (-shift) as u32; + if s >= 64 { + 0 + } else { + let q = scaled >> s; + let rem = scaled & ((1u64 << s) - 1); + let half = 1u64 << (s - 1); + // Ties to even. + if rem > half || (rem == half && q & 1 == 1) { + q + 1 + } else { + q + } + } + }; + u32::try_from(khz).ok() +} + +/// Where the reported state comes from. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Source { + Stats, + HwData, +} + +impl Source { + fn name(self) -> &'static str { + match self { + Source::Stats => "stats", + Source::HwData => "hwdata", + } + } +} + +/// The reported state: the newest power-state record, else HardwareDataA's current state. +pub(crate) fn current(seen: &StatsSeen, hw: &HwWords) -> (u32, Source) { + match seen.last { + Some(index) => (index, Source::Stats), + None => (hw.current, Source::HwData), + } +} + +/// A frequency for the file: kHz, or `unknown`. +struct Khz(Option); + +impl fmt::Display for Khz { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + Some(khz) => write!(f, "{}", khz), + None => f.write_str("unknown"), + } + } +} + +/// The `asahi-g15/pstate` file: +/// +/// ```text +/// pstate freq_khz source +/// stats: records power_states last tags : ... +/// hwdata: actual target current freq_mhz_f32 freq_khz +/// table_khz: x 9 +/// ``` +pub(crate) fn write( + f: &mut impl fmt::Write, + seen: &StatsSeen, + hw: &HwWords, + table: &Table, +) -> fmt::Result { + let (index, source) = current(seen, hw); + writeln!( + f, + "pstate {} freq_khz {} source {}", + index, + Khz(table.khz(index)), + source.name() + )?; + write!( + f, + "stats: records {} power_states {} last ", + seen.records, seen.tags[TAG_POWER_STATE as usize] + )?; + match seen.last { + Some(last) => write!(f, "{}", last)?, + None => f.write_str("none")?, + } + f.write_str(" tags")?; + for (tag, n) in seen.tags.iter().enumerate() { + if *n != 0 { + write!(f, " {}:{}", tag, n)?; + } + } + writeln!(f)?; + writeln!( + f, + "hwdata: actual {} target {} current {} freq_mhz_f32 {:#010x} freq_khz {}", + hw.actual, + hw.target, + hw.current, + hw.freq_mhz, + Khz(f32_mhz_to_khz(hw.freq_mhz)) + )?; + f.write_str("table_khz:")?; + for khz in table.khz { + write!(f, " {}", khz)?; + } + writeln!(f) +} + +#[cfg(test)] +mod tests { + use super::*; + + // A made-up table, not any machine's. + fn table() -> Table { + Table::from_mhz([0, 100, 200, 300, 400, 500, 600, 700, 800]) + } + + #[test] + fn table_is_khz_and_bounded() { + let t = table(); + assert_eq!(t.khz(0), Some(0)); + assert_eq!(t.khz(8), Some(800_000)); + assert_eq!(t.khz(9), None); + assert_eq!(t.khz(u32::MAX), None); + } + + #[test] + fn notes_tags_and_the_newest_power_state() { + let mut s = StatsSeen::default(); + assert_eq!(s.last, None); + s.note(4, 7); + assert_eq!(s.last, None); + s.note(TAG_POWER_STATE, 3); + s.note(TAG_POWER_STATE, 8); + s.note(9, 1); + s.note(200, 0); + assert_eq!(s.records, 5); + assert_eq!(s.last, Some(8)); + assert_eq!(s.tags[4], 1); + assert_eq!(s.tags[TAG_POWER_STATE as usize], 2); + assert_eq!(s.tags[9], 1); + assert_eq!(s.tags[TAGS - 1], 1); + } + + #[test] + fn pending_walks_from_read_to_write_with_wrap() { + let v: Vec = pending(3, 3).unwrap().collect(); + assert!(v.is_empty()); + let v: Vec = pending(3, 6).unwrap().collect(); + assert_eq!(v, [3, 4, 5]); + let v: Vec = pending(254, 1).unwrap().collect(); + assert_eq!(v, [254, 255, 0]); + assert!(pending(256, 0).is_none()); + assert!(pending(0, 256).is_none()); + } + + #[test] + fn f32_mhz_in_khz() { + let k = |x: f32| f32_mhz_to_khz(x.to_bits()); + assert_eq!(k(0.0), Some(0)); + assert_eq!(f32_mhz_to_khz(0x8000_0000), Some(0)); // -0 + assert_eq!(k(1.0), Some(1000)); + assert_eq!(k(800.0), Some(800_000)); + assert_eq!(k(1234.5), Some(1_234_500)); + assert_eq!(k(0.0015), Some(2)); // 1.5 kHz, nearest of the single + assert_eq!(k(0.0004), Some(0)); + assert_eq!(k(4_000_000.0), Some(4_000_000_000)); + assert_eq!(k(5_000_000.0), None); // past u32 kHz + assert_eq!(k(-1.0), None); + assert_eq!(k(f32::INFINITY), None); + assert_eq!(k(f32::NAN), None); + assert_eq!(f32_mhz_to_khz(1), Some(0)); // smallest subnormal + // Exact halves (an odd mantissa x 2^-4 MHz is n + 0.5 kHz) round to even. + for m in [0x80_0001u32, 0x80_0003, 0x80_0005, 0xff_ffff] { + let bits = (146 << 23) | (m & 0x7f_ffff); + let want = (m as f64 * 62.5).round_ties_even() as u32; + assert_eq!(f32_mhz_to_khz(bits), Some(want), "{m:#x}"); + } + // Against the host's arithmetic over a sweep. + for i in 0..20_000u32 { + let x = i as f32 * 0.37; + let want = (x as f64 * 1000.0).round_ties_even() as u32; + assert_eq!(k(x), Some(want), "{x}"); + } + } + + #[test] + fn current_prefers_the_stats_ring() { + let hw = HwWords { + current: 5, + ..Default::default() + }; + let mut s = StatsSeen::default(); + assert_eq!(current(&s, &hw), (5, Source::HwData)); + s.note(TAG_POWER_STATE, 8); + assert_eq!(current(&s, &hw), (8, Source::Stats)); + s.note(TAG_POWER_STATE, 0); + assert_eq!(current(&s, &hw), (0, Source::Stats)); + } + + #[test] + fn file_from_the_stats_ring() { + let mut s = StatsSeen::default(); + s.note(4, 0); + s.note(TAG_POWER_STATE, 8); + let hw = HwWords { + actual: 8, + target: 8, + current: 6, + freq_mhz: 800.0f32.to_bits(), + }; + let mut out = String::new(); + write(&mut out, &s, &hw, &table()).unwrap(); + assert_eq!( + out, + "pstate 8 freq_khz 800000 source stats\n\ + stats: records 2 power_states 1 last 8 tags 4:1 11:1\n\ + hwdata: actual 8 target 8 current 6 freq_mhz_f32 0x44480000 freq_khz 800000\n\ + table_khz: 0 100000 200000 300000 400000 500000 600000 700000 800000\n" + ); + } + + #[test] + fn file_from_hwdata_and_an_index_past_the_table() { + let hw = HwWords { + actual: 1, + target: 2, + current: 12, + freq_mhz: f32::NAN.to_bits(), + }; + let mut out = String::new(); + write(&mut out, &StatsSeen::default(), &hw, &table()).unwrap(); + let mut lines = out.lines(); + assert_eq!( + lines.next(), + Some("pstate 12 freq_khz unknown source hwdata") + ); + assert_eq!( + lines.next(), + Some("stats: records 0 power_states 0 last none tags") + ); + assert_eq!( + lines.next(), + Some("hwdata: actual 1 target 2 current 12 freq_mhz_f32 0x7fc00000 freq_khz unknown") + ); + } +} diff --git a/drivers/gpu/drm/asahi/g15/queue.rs b/drivers/gpu/drm/asahi/g15/queue.rs new file mode 100644 index 00000000000000..cc87f1ccbe084d --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/queue.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Logical queues: `crate::queue::Queue` for G15. +//! +//! Logical queues own no firmware state: they are independent scheduling entities over the one +//! shared graph, executed in one total order across queues and VMs. A device-wide host credit +//! bounds live logical queues to the advertised MAX_QUEUES; it reserves no hardware graph or +//! execution context. The native ABI hardware-reservation wording remains a compatibility limit. +//! QUEUE_CREATE validates +//! `usc_exec_base` (4 GiB aligned, the window inside the user range) and refuses a failed VM or +//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. Ray-query scratch layouts are +//! refused by the shared default `reserve_render_scs` (RENDER_RAY_QUERY is never advertised). +//! +//! QUEUE_DESTROY (dropping the queue) drains: the scheduler entity is torn down first, which +//! waits (killable) until every accepted job has been handed to the engine; the engine then runs +//! them to completion and their fences signal in order. A closing process waits at most a second +//! for jobs still waiting for inputs and cancels them (ECANCELED, in fence order). +//! +//! SUBMIT checks, in order: the stream's structure and the sync count (EINVAL), the VM's state +//! (a failed VM refuses with EIO), the timestamp handles, the EXACT_PRIOR ordinals against the +//! commands accepted on this queue before the ioctl, a job reference on the VM, then every +//! command's spans and stream gates ([`super::command`]). The accepted job is pushed to the +//! queue's scheduler and its fence published in every output sync; a refused SUBMIT publishes a +//! signalled error fence instead. + +use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use kernel::{dma_fence::Fence, prelude::*, sync::Arc, uapi, xarray}; + +use super::{ + command::{self, USC_WINDOW}, + fence::{Syncs, Timeline}, + hw, + job::{Job, Scheduler}, + params, + vm::{self, VmState}, + Gpu, Shared, +}; +use crate::{file, mmu}; + +/// Per-queue state the engine reads. +pub(crate) struct QueueState { + /// Host priority: `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it (MEDIUM 2, + /// LOW 3; `file.rs` refuses HIGH and REALTIME). Smaller is served first. + pub(crate) priority: u32, + /// USC executable window base. + pub(crate) usc_base: u64, + /// Engine service turn of this queue (least recently served first). + pub(crate) turn: AtomicU64, + /// Owned-job counts at the queue's last 32 arrivals (compute horizon ahead), recorded by the + /// engine when a job arrives. + pub(crate) owned: [AtomicU32; 32], + pub(crate) owned_index: AtomicU32, +} + +/// One device-wide logical-queue credit, released after the queue scheduler drains. +struct QueueCredit { + shared: Arc, +} + +impl QueueCredit { + fn acquire(shared: &Arc) -> Result { + shared + .logical_queues + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| { + (count < hw::sizes::MAX_QUEUES).then(|| count + 1) + }) + .map_err(|_| ENOMEM)?; + Ok(Self { + shared: shared.clone(), + }) + } +} + +impl Drop for QueueCredit { + fn drop(&mut self) { + let previous = self.shared.logical_queues.fetch_sub(1, Ordering::AcqRel); + debug_assert!(previous != 0); + } +} + +/// A G15 logical queue. +pub(crate) struct Queue { + // Dropped first: QUEUE_DESTROY drains the scheduler before anything else goes. + scheduler: Scheduler, + pub(crate) state: Arc, + /// Commands accepted per engine (render, compute) since creation, for EXACT_PRIOR. + pub(crate) accepted: [u64; 2], + vm: Arc, + shared: Arc, + timeline: Arc, + // Last field: all preceding fields (especially scheduler) drop before capacity returns. + _credit: QueueCredit, +} + +impl Drop for Queue { + fn drop(&mut self) { + // The registry's references to closed VMs (this queue's VM among them, if its handle is + // gone) go now; this VM's state lives on until the scheduler below has drained. + self.vm.prune_registry(); + } +} + +impl Queue { + /// Creates a logical queue. `priority` is `DRM_ASAHI_PRIORITY_REALTIME - priority`, as + /// `file.rs` passes it. + pub(crate) fn new(gpu: &Gpu, vm: mmu::Vm, priority: u32, usc_exec_base: u64) -> Result { + if priority > uapi::drm_asahi_priority_DRM_ASAHI_PRIORITY_REALTIME { + return Err(EINVAL); + } + let range = hw::USER_RANGE; + if usc_exec_base & (USC_WINDOW - 1) != 0 + || usc_exec_base < range.start + || usc_exec_base + .checked_add(USC_WINDOW) + .is_none_or(|end| end > range.end) + { + return Err(EINVAL); + } + if gpu.shared.crashed.load(Ordering::Acquire) { + return Err(EIO); + } + let vm_state = vm::lookup(gpu, &vm)?; + if vm_state.status.get() != 0 { + return Err(EIO); + } + let credit = QueueCredit::acquire(&gpu.shared)?; + let timeline = Timeline::new()?; + let scheduler = Scheduler::new(&gpu.shared.dev)?; + let state = Arc::new( + QueueState { + priority, + usc_base: usc_exec_base, + turn: AtomicU64::new(0), + owned: [const { AtomicU32::new(0) }; 32], + owned_index: AtomicU32::new(0), + }, + GFP_KERNEL, + )?; + Ok(Self { + scheduler, + state, + accepted: [0; 2], + vm: vm_state, + shared: gpu.shared.clone(), + timeline, + _credit: credit, + }) + } + + /// Validates a SUBMIT and pushes its job; returns the job's fence. + fn submit_job( + &mut self, + id: u64, + syncs: &Syncs, + sync_count: usize, + bytes: &[u8], + objects: Pin<&xarray::XArray>>, + ) -> Result { + if sync_count > command::MAX_SYNCS { + return Err(EINVAL); + } + command::check_stream(bytes, params::early_tiling())?; + if self.shared.crashed.load(Ordering::Acquire) { + return Err(EIO); + } + if self.vm.status.get() != 0 { + return Err(EIO); + } + let prepared = command::prepare(bytes, self.accepted, objects)?; + // The job reference first, so that the mappings checked below stay retained. + let guard = self.vm.vm.retain_first_job()?; + let submission = prepared.validate(&command::Context { + vm: &self.vm.vm, + usc_base: self.state.usc_base, + })?; + let mut inputs = KVec::with_capacity(syncs.inputs().len(), GFP_KERNEL)?; + for sync in syncs.inputs() { + if let Some(fence) = &sync.fence { + inputs.push(fence.clone(), GFP_KERNEL)?; + } + } + let fence = self.timeline.next()?; + let job = Job::new( + id, + self.state.clone(), + self.vm.clone(), + submission.commands, + fence, + submission.timestamps, + guard, + )?; + let published = job.fence.fence(); + self.scheduler.push(job, self.shared.clone(), inputs)?; + // Accepted: the whole SUBMIT counts for later EXACT_PRIOR ordinals. + self.accepted[command::RENDER] += submission.counts[command::RENDER]; + self.accepted[command::COMPUTE] += submission.counts[command::COMPUTE]; + Ok(published) + } +} + +impl crate::queue::Queue for Queue { + fn submit( + &mut self, + _reg_data: &crate::driver::AsahiRegData<'_>, + id: u64, + syncs: KVec, + in_sync_count: usize, + cmdbuf_raw: &[u8], + objects: Pin<&xarray::XArray>>, + ) -> Result { + let sync_count = syncs.len(); + let syncs = Syncs::new(syncs, in_sync_count); + match self.submit_job(id, &syncs, sync_count, cmdbuf_raw, objects) { + Ok(fence) => { + syncs.accept(&fence); + Ok(()) + } + Err(error) => { + // A refused submission leaves the VM usable unless the device is lost. + self.vm.status.record_if_device_loss(error); + syncs.refuse(&self.timeline, error); + Err(error) + } + } + } +} diff --git a/drivers/gpu/drm/asahi/g15/recovery.rs b/drivers/gpu/drm/asahi/g15/recovery.rs new file mode 100644 index 00000000000000..0827385e92c5fa --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/recovery.rs @@ -0,0 +1,688 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Hang detection, kills, the halt/resume handshake and fail-stop. +//! +//! The pure parts are in [`logic`] (host-tested); [`seams`] adapts the engine, register and VM +//! state they decide on. +//! +//! - Host deadline `g15_deadline_ms` (5000) from the oldest prefix's start or last progress +//! (a firmware stamp moving on an engine where that prefix still has work), renewed at every +//! retirement. At expiry with `HANG_PREEMPT`: arm the kill for the oldest prefix (compute +//! divisor +0x1c while its computes are unfinished, else fragment +0x24). +//! - Compute deadline `g15_compute_deadline_ms` (1000: a compute may run for up to 1 s): the +//! oldest prefix's first unfinished compute has its predecessors done, its FS wait reached, +//! its record consumed and the work ring READ past it, with no progress: class 2 -> kill; +//! class 0 -> fail-stop. Measured from the started compute: the total order never blames a +//! job for another VM's older work. +//! - Kill: Globals divisor = 1, DEVCTL 0x13 posted without waiting; publication frozen; 2 s +//! budget: (a) the prefix retires -> ETIMEDOUT, VM lost, later same-VM prefixes EIO; render +//! allocators re-initialized only for a fragment kill; waited disarm before publishing +//! anything; (b) an error event -> handshake, then disarm; (c) timeout -> fail-stop. +//! - Handshake on an error event or receipt fault: drop pending growth requests; wait up to +//! 200 x ~1-1.5 ms for Control+0x4590 = 1 while draining; write halted = 0, barrier, +//! resume = 1; wait <= 500 ms for the firmware to clear resume; wait <= 1000 polls for a full +//! drain, answering up to 4 further halts the same way. Then fail every published prefix +//! (EIO on fault, ETIMEDOUT on timeout) and latch the VM error; if any had renders, set +//! fs_resync and reinit so the next first TA waits on the FS stamp actually reached and an +//! exclusive priming prefix rebuilds the render allocators. A firmware error with nothing +//! published is answered and blames nobody. +//! - Fail-stop (latched until reboot, every VM EIO, published owners retained): publication +//! error after a queue WRITE advanced; recovery off, RTKit crash, no halt, resume not +//! consumed, not drained, more than 4 further halts, failed disarm; deadline without event +//! and no effective kill; class-0 compute hang; unanswerable TA stall. +//! +//! # The poll pass (poll.rs) +//! +//! 1. Failed ([`Recovery::failed`]): nothing. +//! 2. Nothing published and [`Firmware::recovery_idle`]: nothing, no repoll. +//! 3. Drain and retire. For each retired oldest prefix, [`Firmware::retire_outcome`] gives its +//! result (the kill outcome (a), or EIO for a doomed prefix); a receipt fault sets +//! [`Recovery::receipt_fault`]. +//! 4. [`Firmware::answer_growth`] (pools.rs). +//! 5. [`Firmware::check_hangs`]: waited disarm after an ended kill, progress, compute hang, +//! host deadline, recovery or fail-stop. `Err` = fail-stop done (flights failed, VMs failed, +//! pending drained): return it so `Shared::fail_stop` latches. +//! 6. Publish (frozen while [`Recovery::armed`]); repoll while anything is published or armed. + +pub(crate) mod logic; +mod seams; + +use kernel::{ + bindings, device, + prelude::*, + sync::Arc, + time::{ClockSource, Monotonic}, +}; + +use logic::{Failure, HangAction, HangInputs}; + +use super::fw::channels::{devctl, DevCtl, RING_SLOTS}; +use super::fw::initdata::{control, globals}; +use super::hw::{sizes, tuning}; +use super::job::{Completions, Job}; +use super::{params, Firmware}; + +static_assert!(logic::COMPUTE_KILL == globals::COMPUTE_KILL); +static_assert!(logic::FRAGMENT_KILL == globals::FRAGMENT_KILL); +static_assert!(logic::COMPUTE_MONITOR == globals::COMPUTE_MONITOR); +static_assert!(logic::QUEUE_CAP == sizes::QUEUE_CAP); +static_assert!(logic::CHANNEL_SLOTS == RING_SLOTS); +static_assert!(logic::TA == super::channel::Channel::Ta as usize); +static_assert!(logic::FS == super::channel::Channel::Fs as usize); +static_assert!(logic::COMPUTE == super::channel::Channel::Compute as usize); + +/// Monotonic time, ns. +pub(crate) fn now_ns() -> u64 { + ::ktime_get() as u64 +} + +/// One recovery poll interval, 1-1.5 ms. +fn poll_sleep() { + // SAFETY: Sleeping is allowed here: the poll work and the scheduler's run path hold only + // the device mutex. + unsafe { bindings::usleep_range_state(1000, 1500, bindings::TASK_UNINTERRUPTIBLE) }; +} + +/// Orders firmware-visible stores and loads: a full `dsb sy`, at least as strong as `wmb()`, +/// `mb()` and `smp_rmb()`. +fn barrier() { + crate::mem::sync(); +} + +/// A result as logged: 0 or a negative errno. +fn errno(result: &Result) -> i32 { + match result { + Ok(()) => 0, + Err(error) => error.to_errno(), + } +} + +/// Queues `job`'s completion once. Without memory for the entry the job stays referenced +/// forever and never completes (logged). +pub(crate) fn push_completion(done: &mut Completions, job: &Arc, result: Result) { + if done.iter().any(|(queued, _)| Arc::ptr_eq(queued, job)) { + return; + } + if done.push((job.clone(), result), GFP_KERNEL).is_err() { + pr_err!( + "G15: no memory to complete job {}; it is retained\n", + job.id + ); + core::mem::forget(job.clone()); + } +} + +/// Hang and recovery state. +pub(crate) struct Recovery { + /// Host deadline and compute no-progress deadline, monotonic ns; [`logic::EXPIRED`] (0) + /// has passed; renewed by [`Firmware::renew_deadlines`]. + pub(crate) deadline_ns: u64, + pub(crate) compute_deadline_ns: u64, + /// An armed kill: the Globals divisor offset (0x1c compute, 0x24 fragment) and when it was + /// armed. Publication is frozen while it is set (`Engine::frozen` mirrors it). + pub(crate) armed: Option<(usize, u64)>, + /// The prefix the kill was armed for retired: the disarm is pending. + pub(crate) kill_ended: bool, + /// After a recovered render abort: the next first TA waits on the FS stamp reached, and an + /// exclusive priming prefix rebuilds the render allocators. The engine clears both when + /// it publishes renders. + pub(crate) fs_resync: bool, + pub(crate) reinit: bool, + /// Firmware error events already answered. + pub(crate) errors_seen: u32, + /// The retirement check of this poll pass saw a fault; set by the poll pass, consumed by + /// [`Firmware::check_hangs`]. + pub(crate) receipt_fault: bool, + /// The latched backend failure: nothing is accepted or published again. + pub(crate) failed: Option, + /// Statistics (debugfs keys `recoveries`, `hang_kills`). + pub(crate) recoveries: u64, + pub(crate) hang_kills: u64, +} + +impl Recovery { + pub(crate) fn new() -> Self { + Self { + deadline_ns: logic::EXPIRED, + compute_deadline_ns: logic::EXPIRED, + armed: None, + kill_ended: false, + fs_resync: false, + reinit: false, + errors_seen: 0, + receipt_fault: false, + failed: None, + recoveries: 0, + hang_kills: 0, + } + } + + /// The latched backend failure, if any. + pub(crate) fn failed(&self) -> Option { + self.failed + } + + /// The poll must run again soon besides any published prefix: a kill is armed. + pub(crate) fn needs_repoll(&self) -> bool { + self.armed.is_some() + } +} + +impl Firmware { + /// The GPU device, for logging. + pub(crate) fn dev(&self) -> &device::Device { + &self.pools.dev + } + + /// Renews the host and compute deadlines from now: at the publication of a prefix with + /// nothing in flight, at every retirement, and on progress. + pub(crate) fn renew_deadlines(&mut self) { + let (deadline, compute) = logic::renew( + now_ns(), + params::deadline_ms(), + params::compute_deadline_ms(), + ); + self.recovery.deadline_ns = deadline; + self.recovery.compute_deadline_ns = compute; + } + + /// Firmware error events arrived that recovery has not answered. + fn new_errors(&self) -> bool { + self.events.errors != self.recovery.errors_seen + } + + /// Nothing for the poll pass to do when nothing is published: no kill armed (whose prefix + /// ended) and no firmware error event to answer (the pass is skipped without a repoll). + pub(crate) fn recovery_idle(&self) -> bool { + self.recovery.armed.is_none() && !self.new_errors() + } + + /// `(recoveries, hang_kills)` for `asahi-g15/stats`. + pub(crate) fn recovery_counts(&self) -> (u64, u64) { + (self.recovery.recoveries, self.recovery.hang_kills) + } + + /// The result of the oldest published prefix, which just retired. + /// Retired after an armed request (the first such retirement): the firmware ended it. + /// Its job fails with ETIMEDOUT and its client's VM is lost, like a hang reset; later + /// prefixes (same VM) may have been ended by the request too before it is restored: they + /// fail with EIO. A compute request ends compute work only: the prefix's renders completed + /// with their own receipts and the render allocators stay; only a fragment kill of a + /// prefix with renders re-initializes them. Otherwise a doomed prefix fails with EIO. + pub(crate) fn retire_outcome(&mut self) -> Result { + let doomed = self.engine.flights.first().is_some_and(|f| f.doomed); + let offset = match self.recovery.armed { + Some((offset, _)) if !self.recovery.kill_ended => offset, + _ => return if doomed { Err(EIO) } else { Ok(()) }, + }; + self.recovery.kill_ended = true; + self.recovery.hang_kills += 1; + if self.receipts(0).renders != 0 && offset == logic::FRAGMENT_KILL { + // Aborted scene: PB state untrusted. + self.recovery.reinit = true; + } + for flight in self.engine.flights.iter_mut().skip(1) { + flight.doomed = true; + } + let ctx = self.engine.flights.first().map_or(0, |f| f.job.vm.slot); + let kind = if offset == logic::FRAGMENT_KILL { + "fragment" + } else { + "compute" + }; + dev_warn!( + self.dev(), + "hung submission of ctx {} ended by the firmware's {} request\n", + ctx, + kind + ); + Err(ETIMEDOUT) + } + + /// The hang and recovery branches of the poll pass, after retirement and growth. `Err` + /// means the backend fail-stopped here: published prefixes failed and retained, every VM + /// failed, pending jobs failed; the caller latches [`crate::g15::Shared::fail_stop`] and + /// publishes nothing. + pub(crate) fn check_hangs(&mut self, done: &mut Completions) -> Result { + if let Some(error) = self.recovery.failed { + return Err(error); + } + let fault = core::mem::take(&mut self.recovery.receipt_fault); + // The request's prefix ended: restore the divisor (and wait for its import) before + // anything is published, unless a firmware error arrived meanwhile: the firmware may + // have halted, and the recovery below answers it first, then restores the divisor. + if self.recovery.kill_ended + && !fault + && self.transport_error().is_none() + && !self.new_errors() + && self.preempt_disarm().is_err() + { + // Not restored: fail below. + self.recovery.deadline_ns = logic::EXPIRED; + } + let flight = !self.engine.flights.is_empty(); + if flight && self.recovery.armed.is_none() { + self.progress(); + } + let now = now_ns(); + let inputs = HangInputs { + flight, + armed: self.recovery.armed.is_some(), + fault, + transport: self.transport_error().is_some(), + new_errors: self.new_errors(), + compute_deadline_expired: logic::expired(now, self.recovery.compute_deadline_ns), + deadline_expired: logic::expired(now, self.recovery.deadline_ns), + class: tuning::COMPUTE_QUEUE_CLASS, + recovery: params::recovery(), + hang_preempt: tuning::HANG_PREEMPT, + }; + let decision = logic::decide(&inputs, || self.compute_hang_now()); + if decision.compute_hang { + self.report("compute hang"); + } + let ctx = self.engine.flights.first().map_or(0, |f| f.job.vm.slot); + if decision.class0_hang { + dev_warn!( + self.dev(), + "class-0 compute hang of ctx {} (not preemptible): failing\n", + ctx + ); + // Take the fail-stop branch. + self.recovery.deadline_ns = logic::EXPIRED; + } + match decision.action { + HangAction::Idle | HangAction::Wait => Ok(()), + HangAction::ArmCompute => { + // The started compute made no progress for its budget, with no firmware + // event: ask the firmware to end it; publication stays frozen. + dev_warn!( + self.dev(), + "compute of ctx {} made no progress for {} ms: asking the firmware to end it\n", + ctx, + params::compute_deadline_ms() + ); + let _ = self.kill_arm(logic::COMPUTE_KILL); + Ok(()) + } + HangAction::ArmDeadline => { + // Host deadline, no firmware event: let the firmware kill it. + self.report("hung, requesting preemption"); + let offset = self.kill_offset_now(); + let _ = self.kill_arm(offset); + Ok(()) + } + HangAction::Fail { recover } => self.fail_or_recover(recover, fault, done), + } + } + + /// The failure branch: a firmware error event or a receipt fault with a live transport + /// waits for the firmware's own halt and answers it; every published prefix fails with it. + /// A hang in the render-only allocator rebuild prefix recovers like any render hang and + /// re-primes. An armed request is restored after the resume, before + /// anything is published; if it cannot be, the GPU stops. Anything else fail-stops. + fn fail_or_recover(&mut self, recover: bool, fault: bool, done: &mut Completions) -> Result { + let flight = !self.engine.flights.is_empty(); + let ctx = self.engine.flights.first().map_or(0, |f| f.job.vm.slot); + self.report(if flight { + "prefix FAILED" + } else { + "firmware error with no prefix published" + }); + let render = (0..self.engine.flights.len()).any(|i| self.receipts(i).renders != 0); + if recover { + let (error, mut recovered) = self.recover(); + if recovered && self.preempt_disarm().is_err() { + recovered = false; + } + if recovered { + self.recovery.errors_seen = self.events.errors; + self.recovery.recoveries += 1; + if render { + self.recovery.fs_resync = true; + self.recovery.reinit = true; + } + dev_warn!( + self.dev(), + "recovered: ctx {} submission failed with {}\n", + ctx, + error.to_errno() + ); + // The failing client's VM is lost; other clients continue. + while !self.engine.flights.is_empty() { + self.retire_oldest(Err(error), done); + } + return Ok(()); + } + } + let error = if fault { + EIO + } else { + self.transport_error().unwrap_or(ETIMEDOUT) + }; + self.fail_stop(error, done); + Err(error) + } + + /// Stops the backend until reboot: restores an armed divisor if possible, latches the + /// failure, fails and retains every published prefix, fails every live VM with EIO and + /// fails the pending jobs (retaining those partly published). The caller returns the error + /// so that [`crate::g15::Shared::fail_stop`] latches the device; a job the caller holds + /// outside `engine.pending` (the job whose publication failed) is the caller's to fail and + /// retain. + pub(crate) fn fail_stop(&mut self, error: Error, done: &mut Completions) { + let _ = self.preempt_disarm(); + if self.recovery.failed.is_none() { + self.recovery.failed = Some(error); + } + // Published and uncertain: never release their owners. + self.fail_flights(error, done); + // No recovery: every VM is lost, also those with no failed job. + self.fail_all_vms(EIO); + let pending = core::mem::take(&mut self.engine.pending); + for job in pending.iter() { + push_completion(done, job, Err(EIO)); + // A partly published job already ran commands: its owners stay retained. + if self.job_partly_published(job) { + self.retain(job); + } + } + } + + /// Fails every published prefix: their jobs fail (each once) and, with every owner the + /// firmware may still reference, are retained. The prefixes' storage is never released: + /// the flights are leaked. + pub(crate) fn fail_flights(&mut self, error: Error, done: &mut Completions) { + let flights = core::mem::take(&mut self.engine.flights); + for flight in flights.iter() { + for job in Iterator::chain(core::iter::once(&flight.job), flight.group.iter()) { + push_completion(done, job, Err(error)); + self.retain(job); + } + } + core::mem::forget(flights); + } + + /// Keeps `job` until reboot: its owners (VM mappings, storage) stay alive because the + /// firmware may still reference them. + pub(crate) fn retain(&mut self, job: &Arc) { + if self + .engine + .retained + .iter() + .any(|kept| Arc::ptr_eq(kept, job)) + { + return; + } + if self.engine.retained.push(job.clone(), GFP_KERNEL).is_err() { + core::mem::forget(job.clone()); + } + } + + /// The started-compute hang test on the oldest prefix. + fn compute_hang_now(&self) -> bool { + if self.engine.flights.is_empty() { + return false; + } + match self.observe() { + Ok(observed) => logic::compute_hang(&self.receipts(0), &self.tail(), &observed), + Err(_) => false, + } + } + + /// The divisor the host deadline arms for the oldest prefix. + fn kill_offset_now(&self) -> usize { + let observed = self.observe().unwrap_or_default(); + logic::kill_offset(&self.receipts(0), &self.tail(), &observed) + } + + /// Firmware DONE/READ reached the newest published ends, channels consumed, engines idle. + fn drained(&mut self) -> bool { + let tail = self.tail(); + match self.observe() { + Ok(observed) if logic::queues_drained(&tail, &observed) => { + matches!(self.engine_state(), Ok(state) if !state.busy) + } + _ => false, + } + } + + fn globals_w32(&self, offset: usize, value: u32) -> Result { + self.init.globals.as_ref().ok_or(ENODEV)?.w32(offset, value) + } + + fn control_r32(&self, offset: usize) -> Result { + self.init.control.as_ref().ok_or(ENODEV)?.r32(offset) + } + + fn control_w32(&self, offset: usize, value: u32) -> Result { + self.init.control.as_ref().ok_or(ENODEV)?.w32(offset, value) + } + + /// Writes a Globals divisor and waits for its import. + pub(crate) fn preempt_set(&mut self, offset: usize, divisor: u32) -> Result { + let ret = self.globals_w32(offset, divisor).and_then(|()| { + barrier(); + self.devctl(&DevCtl::op(devctl::IMPORT_GLOBALS), true) + }); + dev_info!( + self.dev(), + "preemption divisor Globals+{:#x}={}: {}\n", + offset, + divisor, + errno(&ret) + ); + ret + } + + /// The class-2 compute profile: the unchanged-work compute monitor off (Globals +0x9b0 = 0, + /// waited import) before the compute queue's first exposure (the periodic request +0x1c is + /// 0 in the image). Called once by the backend start after the graphs are initialized. + pub(crate) fn compute_monitor_off(&mut self) -> Result { + if tuning::COMPUTE_QUEUE_CLASS == 2 { + self.preempt_set(logic::COMPUTE_MONITOR, 0) + } else { + Ok(()) + } + } + + /// Arms the hang request: divisor 1 at Globals `offset`, DEVCTL 0x13 posted without + /// waiting (the firmware may halt before it consumes it), publication frozen until the + /// outcome, whose budget is 2 s (none if the post failed). + fn kill_arm(&mut self, offset: usize) -> Result { + let ret = self.globals_w32(offset, 1).and_then(|()| { + barrier(); + self.devctl(&DevCtl::op(devctl::IMPORT_GLOBALS), false) + }); + let now = now_ns(); + self.recovery.armed = Some((offset, now)); + self.recovery.kill_ended = false; + self.engine.frozen = true; + self.recovery.deadline_ns = logic::kill_deadline(now, ret.is_ok()); + dev_info!( + self.dev(), + "hang request Globals+{:#x}=1: {}\n", + offset, + errno(&ret) + ); + ret + } + + /// Restores the armed divisor to 0 and waits for the import before anything is published + /// again (an earlier arming record is consumed first). On failure the request stays armed + /// and publication frozen. + fn preempt_disarm(&mut self) -> Result { + let Some((offset, _)) = self.recovery.armed else { + return Ok(()); + }; + self.preempt_set(offset, 0)?; + self.recovery.armed = None; + self.recovery.kill_ended = false; + self.engine.frozen = false; + Ok(()) + } + + /// Logs the recovery handshake state: Control halt count, halted, resume and flag; + /// HardwareData fault information; up to 16 pending records. + fn recover_snapshot(&self, phase: &str) { + let ctl = |offset| self.control_r32(offset).unwrap_or(0); + let fault_info = |offset| { + self.init + .hwdata + .as_ref() + .and_then(|hw| hw.r32(self.cfg.layout.hwdata_view + offset).ok()) + .unwrap_or(0) + }; + dev_info!( + self.dev(), + "recovery {}: halt_count={:#x} halted={} resume={} flag={:#x} faultinfo status={} do_not_halt={} did_not_halt={} total={}\n", + phase, + ctl(control::HALT_COUNT), + ctl(control::HALTED), + ctl(control::RESUME), + ctl(control::FLAG), + fault_info(0), + fault_info(4), + fault_info(8), + fault_info(0x18) + ); + let mut shown = 0; + for i in 0..128 { + if shown == 16 { + break; + } + let info = ctl(control::PENDING + 8 * i); + if info & 1 == 0 { + continue; + } + shown += 1; + dev_info!( + self.dev(), + " pending[{}]: info {:#x} slot {} wait {:#x}\n", + i, + info, + (info >> 4) & 0x7f, + ctl(control::PENDING + 8 * i + 4) + ); + } + } + + /// Acknowledges a firmware halt: halted = 0, then resume = 1, ordered; nothing else. Then + /// waits up to 500 polls for the firmware to clear resume. Returns whether it did, and + /// the polls waited. + fn acknowledge_halt(&mut self) -> Result<(bool, u32)> { + self.control_w32(control::HALTED, 0)?; + barrier(); + self.control_w32(control::RESUME, 1)?; + barrier(); + let mut t = 0; + while t < logic::RESUME_POLLS && self.control_r32(control::RESUME)? != 0 { + poll_sleep(); + t += 1; + } + Ok((self.control_r32(control::RESUME)? == 0, t)) + } + + /// The firmware recovery handshake, with a published prefix active (or a firmware error + /// with nothing published) and a firmware error event seen (or a receipt fault). Returns + /// the error for the failed prefixes and whether the firmware halted, consumed the host's + /// resume and drained; otherwise the caller fail-stops (no halt, transport failure, or a + /// queue the firmware did not drain). + fn recover(&mut self) -> (Error, bool) { + // Growth requests of the failed epoch are never answered. + self.events.grow.clear(); + barrier(); + let fault = self.engine_state().map_or(0, |state| state.fault); + let last = self.events.last_error; + let error = match logic::failure(fault, last.map(|e| e.kind)) { + Failure::Fault => EIO, + Failure::Timeout => ETIMEDOUT, + }; + let (kind, slot, raw) = last.map_or((0, -1, [0; 14]), |e| (e.kind, e.slot, e.raw)); + let what = if error == EIO { "fault" } else { "timeout" }; + dev_warn!( + self.dev(), + "GPU {}: event type {} slot {} raw {:08x?}; recovering\n", + what, + kind, + slot, + raw + ); + self.recover_snapshot("error"); + let recovered = match self.handshake() { + Ok(recovered) => recovered, + Err(e) => { + dev_err!( + self.dev(), + "recovery: firmware state unavailable: {}\n", + e.to_errno() + ); + false + } + }; + (error, recovered) + } + + /// The halt, resume and drain steps of [`Self::recover`]. + fn handshake(&mut self) -> Result { + // The event precedes the halt publication: wait for the real halt. + let mut t = 0; + while t < logic::HALT_POLLS && self.control_r32(control::HALTED)? != 1 { + let _ = self.drain_rings(); + poll_sleep(); + t += 1; + } + if self.control_r32(control::HALTED)? != 1 || self.transport_error().is_some() { + dev_err!(self.dev(), "recovery: firmware did not halt ({} ms)\n", t); + return Ok(false); + } + self.recover_snapshot("halted"); + let (resumed, t) = self.acknowledge_halt()?; + if !resumed || self.transport_error().is_some() { + dev_err!(self.dev(), "recovery: resume not consumed ({} ms)\n", t); + return Ok(false); + } + // The firmware clears resume before finishing: wait for the queues to drain. Work of + // the failed prefixes that runs after the resume can fail in turn (a compute that + // waited on the aborted FS hitting a firmware compute timeout): its own halt is + // answered the same way, a bounded number of times, and the drain continues. + let mut halts = 0; + let mut t = 0; + while t < logic::DRAIN_POLLS && !self.drained() { + let _ = self.drain_rings(); + if self.control_r32(control::HALTED)? == 1 + && self.transport_error().is_none() + && halts < logic::FURTHER_HALTS + { + halts += 1; + self.recover_snapshot("halted again"); + if !self.acknowledge_halt()?.0 { + dev_err!( + self.dev(), + "recovery: resume after a further halt not consumed\n" + ); + return Ok(false); + } + // Restart the drain wait, counting this poll. + t = 1; + continue; + } + poll_sleep(); + t += 1; + } + self.recover_snapshot("resumed"); + self.report("recovery"); + if !self.drained() + || self.control_r32(control::HALTED)? != 0 + || self.transport_error().is_some() + { + dev_err!( + self.dev(), + "recovery: failed prefix not drained ({} ms)\n", + t + ); + return Ok(false); + } + Ok(true) + } +} diff --git a/drivers/gpu/drm/asahi/g15/recovery/logic.rs b/drivers/gpu/drm/asahi/g15/recovery/logic.rs new file mode 100644 index 00000000000000..6d36d1d6550d5a --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/recovery/logic.rs @@ -0,0 +1,599 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Pure hang-detection and recovery decisions. +//! +//! The arithmetic and branch structure of the poll pass, free of locks, objects and clocks so +//! host tests can exercise them: receipt comparisons, the started-compute hang test, the kill +//! divisor choice and the queue-drain test of the recovery handshake, the deadlines and the +//! hang branches. Times are monotonic nanoseconds; a deadline `d` has passed when `now > d`. +//! +//! Core-only (no `kernel` imports): this file is compiled by the host test harness as well. + +/// Entries of a firmware work ring (= `hw::sizes::QUEUE_CAP`). +pub(crate) const QUEUE_CAP: u32 = 0x500; +/// Records of a submit channel ring (= `fw::channels::RING_SLOTS`). +pub(crate) const CHANNEL_SLOTS: u32 = 256; +/// Channel indices. +pub(crate) const TA: usize = 0; +pub(crate) const FS: usize = 1; +pub(crate) const COMPUTE: usize = 2; + +/// Globals divisors of the firmware's periodic context-store request: +/// compute (+0x1c, ends a running class-2 compute) and fragment (+0x24). Mirrors +/// `fw::initdata::globals::{COMPUTE_KILL, FRAGMENT_KILL}`. +pub(crate) const COMPUTE_KILL: usize = 0x1c; +pub(crate) const FRAGMENT_KILL: usize = 0x24; +/// Globals unchanged-work compute monitor (`fw::initdata::globals::COMPUTE_MONITOR`). +pub(crate) const COMPUTE_MONITOR: usize = 0x9b0; + +/// Outcome budget of an armed kill: the prefix retires or an error event arrives within it. +pub(crate) const KILL_BUDGET_MS: u64 = 2000; +/// Recovery handshake bounds: polls for the firmware's halt, polls for the resume to be +/// consumed, polls for the drain, and further halts answered during the drain. +/// Every poll sleeps 1-1.5 ms. +pub(crate) const HALT_POLLS: u32 = 200; +pub(crate) const RESUME_POLLS: u32 = 500; +pub(crate) const DRAIN_POLLS: u32 = 1000; +pub(crate) const FURTHER_HALTS: u32 = 4; + +/// Stamp cell `obs` reached the own target `own`, bounded by the newest published target +/// `tail`. Stamps are seeded so that a written stamp is never 0 and has a zero low byte. +pub(crate) const fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { + obs != 0 && obs & 0xff == 0 && obs.wrapping_sub(own) <= tail.wrapping_sub(own) +} + +/// Cursor `c` of a ring of `m` entries passed the end `h` of entries starting at `b`, within +/// the tail `t`. +/// +/// `c` is a firmware-written cursor: the u32 arithmetic wraps (a garbage cursor must not trip +/// `CONFIG_RUST_OVERFLOW_CHECKS`). +pub(crate) const fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { + let dc = c.wrapping_add(m).wrapping_sub(b) % m; + let dh = h.wrapping_add(m).wrapping_sub(b) % m; + let dt = t.wrapping_add(m).wrapping_sub(b) % m; + dh <= dc && dc <= dt +} + +/// The receipts of one published prefix, filled at publication. +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)] +pub(crate) struct Receipts { + /// Compute and render members of the prefix. + pub(crate) computes: u32, + pub(crate) renders: u32, + /// Compute: final FW stamp target, work-ring end after the prefix and before it. + pub(crate) target: u32, + pub(crate) head: u32, + pub(crate) c_start: u32, + /// Render: final TA/FS stamp targets, ring ends after and before the prefix. + pub(crate) ta_target: u32, + pub(crate) fs_target: u32, + pub(crate) ta_head: u32, + pub(crate) fs_head: u32, + pub(crate) ta_start: u32, + pub(crate) fs_start: u32, + /// Host channel producers (TA, FS, compute) after the prefix's records. + pub(crate) rec: [u32; 3], + /// Compute member j's FW stamp target, and the FS target it waits on directly (0: none). + pub(crate) cstamp: [u32; 16], + pub(crate) cwait: [u32; 16], +} + +/// The newest published receipts. +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)] +pub(crate) struct Tail { + pub(crate) target: u32, + pub(crate) head: u32, + pub(crate) ta_target: u32, + pub(crate) fs_target: u32, + pub(crate) ta_head: u32, + pub(crate) fs_head: u32, + pub(crate) producer: [u32; 3], +} + +/// Firmware-written words read in one observation (single aligned loads of uncached cells). +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)] +pub(crate) struct Observed { + /// FW stamps: compute (the compute graph's `fw_stamp`), TA and FS (the render graph's + /// `fw_stamp[0..1]`). + pub(crate) compute_stamp: u32, + pub(crate) ta_stamp: u32, + pub(crate) fs_stamp: u32, + /// Work-ring DONE (qstate +0) and READ (qstate +0x30) of the compute, TA and FS queues. + pub(crate) compute_done: u32, + pub(crate) compute_read: u32, + pub(crate) ta_done: u32, + pub(crate) ta_read: u32, + pub(crate) fs_done: u32, + pub(crate) fs_read: u32, + /// Channel consumers (the read cell of the TA, FS and compute channel state blocks). + pub(crate) consumer: [u32; 3], +} + +/// Engine receipts from the SGX status window: busy is bit 0 of C020 | C120; fault is the D8C0 +/// status of fault banks 0 and 1. +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)] +pub(crate) struct EngineState { + pub(crate) busy: bool, + pub(crate) fault: u64, +} + +/// The oldest prefix `f`'s first unfinished compute has started and makes no progress: its +/// predecessors in the prefix are done (earlier compute members by the reached FW stamp, a +/// render it waits on directly by the FS stamp), the firmware consumed the prefix's compute +/// record and its work-ring READ passed the prefix's entries (the private start timestamp is +/// written only at completion). Later members, renders waiting on it included, may be +/// unfinished. +pub(crate) fn compute_hang(f: &Receipts, t: &Tail, o: &Observed) -> bool { + let fw = o.compute_stamp; + if f.computes == 0 || stamp_reached(fw, f.target, t.target) { + return false; // no compute, or its computes are done + } + let computes = (f.computes as usize).min(f.cstamp.len()); + let mut j = 0; + while j < computes && stamp_reached(fw, f.cstamp[j], t.target) { + j += 1; + } + if j == computes { + return false; + } + if f.cwait[j] != 0 && !stamp_reached(o.fs_stamp, f.cwait[j], t.fs_target) { + return false; // still waiting on a render of the prefix + } + if o.consumer[COMPUTE] != f.rec[COMPUTE] { + return false; // its record not consumed yet + } + ring_passed(o.compute_read, f.c_start, f.head, t.head, QUEUE_CAP) +} + +/// The divisor the host deadline arms: the compute request while the oldest prefix's computes +/// are not done, else the fragment request for a prefix with renders. +pub(crate) fn kill_offset(f: &Receipts, t: &Tail, o: &Observed) -> usize { + if f.computes != 0 && !stamp_reached(o.compute_stamp, f.target, t.target) { + COMPUTE_KILL + } else if f.renders != 0 { + FRAGMENT_KILL + } else { + COMPUTE_KILL + } +} + +/// Firmware DONE/READ reached the newest published ends of every queue and every channel +/// record was consumed (the caller adds the engine-idle test). +pub(crate) fn queues_drained(t: &Tail, o: &Observed) -> bool { + o.ta_done == t.ta_head + && o.ta_read == t.ta_head + && o.fs_done == t.fs_head + && o.fs_read == t.fs_head + && o.consumer[TA] == t.producer[TA] + && o.consumer[FS] == t.producer[FS] + && o.compute_done == t.head + && o.compute_read == t.head + && o.consumer[COMPUTE] == t.producer[COMPUTE] +} + +/// What a firmware error means for the failed prefixes. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Failure { + /// A GPU fault (EIO). + Fault, + /// A firmware timeout (ETIMEDOUT). + Timeout, +} + +/// Classifies a recovery: a pending fault status or a type-0 event is a fault. `event_type` is +/// the last error event's type; with none seen, type 0 applies. +pub(crate) fn failure(fault: u64, event_type: Option) -> Failure { + if fault != 0 || event_type.unwrap_or(0) == 0 { + Failure::Fault + } else { + Failure::Timeout + } +} + +const NSEC_PER_MSEC: u64 = 1_000_000; + +/// Host and compute deadlines `deadline_ms`/`compute_deadline_ms` from `now` (both budgets +/// are at least 100 ms). +pub(crate) fn renew(now: u64, deadline_ms: u32, compute_deadline_ms: u32) -> (u64, u64) { + ( + now + deadline_ms.max(100) as u64 * NSEC_PER_MSEC, + now + compute_deadline_ms.max(100) as u64 * NSEC_PER_MSEC, + ) +} + +/// Host deadline after arming a kill: the outcome budget, or at once (`EXPIRED`) when the +/// request could not be posted. +pub(crate) fn kill_deadline(now: u64, posted: bool) -> u64 { + if posted { + now + KILL_BUDGET_MS * NSEC_PER_MSEC + } else { + EXPIRED + } +} + +/// A deadline that has passed. Monotonic ns since boot never wrap, so 0 is in the past for +/// every later check. +pub(crate) const EXPIRED: u64 = 0; + +/// `time_after(now, deadline)`. +pub(crate) const fn expired(now: u64, deadline: u64) -> bool { + now > deadline +} + +/// The state the hang branches of the poll pass decide on. +#[derive(Copy, Clone, Default, Debug)] +pub(crate) struct HangInputs { + /// A prefix is published. + pub(crate) flight: bool, + /// A kill request is armed. + pub(crate) armed: bool, + /// The retirement check saw a fault. + pub(crate) fault: bool, + /// The RTKit transport failed. + pub(crate) transport: bool, + /// Firmware error events not yet answered. + pub(crate) new_errors: bool, + /// The compute no-progress and host deadlines passed. + pub(crate) compute_deadline_expired: bool, + pub(crate) deadline_expired: bool, + /// The compute queue's scheduling class (2: killable), recovery and hang preemption + /// enabled. + pub(crate) class: u32, + pub(crate) recovery: bool, + pub(crate) hang_preempt: bool, +} + +/// What the hang branches do. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum HangAction { + /// Nothing published or armed and no error: go straight to publication. + Idle, + /// Nothing to do in this pass; poll again. + Wait, + /// The oldest prefix's started compute made no progress for its budget, class 2: arm the + /// compute request (+0x1c); publication stays frozen. + ArmCompute, + /// The host deadline passed with no event: arm the request [`kill_offset`] chooses. + ArmDeadline, + /// Failure: answer the firmware halt first when `recover`, else fail-stop. + Fail { recover: bool }, +} + +/// The decision of the hang branches. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Decision { + pub(crate) action: HangAction, + /// The started-compute hang test matched (reported as "compute hang"). + pub(crate) compute_hang: bool, + /// ... on the class-0 queue, which cannot be ended: the host deadline is expired so the + /// failure branch fail-stops now. The caller persists the expired deadline. + pub(crate) class0_hang: bool, +} + +/// The hang branches of the poll pass, after the waited disarm and the progress update. +/// `compute_hang` evaluates [`compute_hang`] for the oldest prefix; it is called only once its +/// deadline passed (and again for a class-0 queue at the host deadline), never on the fast +/// path. +pub(crate) fn decide(i: &HangInputs, mut compute_hang: impl FnMut() -> bool) -> Decision { + let mut d = Decision { + action: HangAction::Wait, + compute_hang: false, + class0_hang: false, + }; + let quiet = !i.fault && !i.transport && !i.new_errors; + if !i.flight && !i.armed && quiet { + d.action = HangAction::Idle; + return d; + } + let mut deadline_expired = i.deadline_expired; + if i.flight && quiet && !i.armed && i.compute_deadline_expired && compute_hang() { + d.compute_hang = true; + if i.class != 0 && i.recovery { + d.action = HangAction::ArmCompute; + return d; + } + d.class0_hang = true; + deadline_expired = true; + } + if i.flight + && quiet + && deadline_expired + && !i.armed + && (i.class != 0 || !compute_hang()) + && i.hang_preempt + && i.recovery + { + d.action = HangAction::ArmDeadline; + } else if !quiet || ((i.flight || i.armed) && deadline_expired) { + d.action = HangAction::Fail { + recover: i.recovery && !i.transport && (i.new_errors || i.fault), + }; + } + d +} + +#[cfg(test)] +mod tests { + use super::*; + + const C0: u32 = 0xc1000000; + + fn stamp(n: u32) -> u32 { + C0 + (n << 8) + } + + #[test] + fn stamps() { + assert!(!stamp_reached(0, stamp(1), stamp(3))); + assert!(!stamp_reached(stamp(1) + 1, stamp(1), stamp(3))); + assert!(stamp_reached(stamp(1), stamp(1), stamp(3))); + assert!(stamp_reached(stamp(3), stamp(1), stamp(3))); + assert!(!stamp_reached(stamp(0), stamp(1), stamp(3))); + assert!(!stamp_reached(stamp(4), stamp(1), stamp(3))); + // Across the u32 wrap. + let own = 0xffffff00u32; + assert!(stamp_reached(0x00000100, own, 0x00000200)); + assert!(!stamp_reached(0xfffffe00, own, 0x00000200)); + } + + #[test] + fn rings() { + // Entries 10..14 of a 0x500 ring, tail at 20. + assert!(!ring_passed(12, 10, 14, 20, QUEUE_CAP)); + assert!(ring_passed(14, 10, 14, 20, QUEUE_CAP)); + assert!(ring_passed(20, 10, 14, 20, QUEUE_CAP)); + assert!(!ring_passed(21, 10, 14, 20, QUEUE_CAP)); + // Wrapped. + assert!(ring_passed(2, 0x4fe, 1, 5, QUEUE_CAP)); + assert!(!ring_passed(0x4ff, 0x4fe, 1, 5, QUEUE_CAP)); + // A channel record: consumed when the cursor passed rec - 1 .. rec. + let rec = 7; + assert!(!ring_passed(6, (rec + 255) % 256, rec, 9, CHANNEL_SLOTS)); + assert!(ring_passed(7, (rec + 255) % 256, rec, 9, CHANNEL_SLOTS)); + assert!(ring_passed(0, 255, 0, 3, CHANNEL_SLOTS)); + } + + /// A compute-only prefix of three computes, stamps 1..3, ring entries 10..13 (with the + /// compute->compute barriers), compute record producer 5. + fn prefix() -> (Receipts, Tail, Observed) { + let mut f = Receipts { + computes: 3, + target: stamp(3), + head: 15, + c_start: 10, + rec: [0, 0, 5], + ..Default::default() + }; + f.cstamp[..3].copy_from_slice(&[stamp(1), stamp(2), stamp(3)]); + let t = Tail { + target: stamp(3), + head: 15, + producer: [0, 0, 5], + ..Default::default() + }; + let o = Observed { + compute_stamp: stamp(0), + compute_read: 15, + consumer: [0, 0, 5], + ..Default::default() + }; + (f, t, o) + } + + #[test] + fn compute_hangs() { + let (mut f, t, mut o) = prefix(); + // Started (record consumed, READ past the prefix), first compute unfinished. + assert!(compute_hang(&f, &t, &o)); + // Second compute running after the first finished. + o.compute_stamp = stamp(1); + assert!(compute_hang(&f, &t, &o)); + // All done: no hang. + o.compute_stamp = stamp(3); + assert!(!compute_hang(&f, &t, &o)); + o.compute_stamp = stamp(1); + // Record not consumed yet. + o.consumer[COMPUTE] = 4; + assert!(!compute_hang(&f, &t, &o)); + o.consumer[COMPUTE] = 5; + // READ not past the prefix's entries. + o.compute_read = 12; + assert!(!compute_hang(&f, &t, &o)); + o.compute_read = 15; + // The running compute waits on an FS of the prefix that has not completed. + f.cwait[1] = 0x3d000300; + o.fs_stamp = 0x3d000200; + let mut t2 = t; + t2.fs_target = 0x3d000400; + assert!(!compute_hang(&f, &t2, &o)); + o.fs_stamp = 0x3d000300; + assert!(compute_hang(&f, &t2, &o)); + // No compute in the prefix. + f.computes = 0; + assert!(!compute_hang(&f, &t, &o)); + } + + #[test] + fn kill_offsets() { + let (mut f, t, mut o) = prefix(); + assert_eq!(kill_offset(&f, &t, &o), COMPUTE_KILL); + o.compute_stamp = stamp(3); + f.renders = 1; + assert_eq!(kill_offset(&f, &t, &o), FRAGMENT_KILL); + f.renders = 0; + assert_eq!(kill_offset(&f, &t, &o), COMPUTE_KILL); + f.computes = 0; + f.renders = 2; + assert_eq!(kill_offset(&f, &t, &o), FRAGMENT_KILL); + } + + #[test] + fn drained() { + let t = Tail { + head: 15, + ta_head: 7, + fs_head: 9, + producer: [3, 4, 5], + ..Default::default() + }; + let mut o = Observed { + compute_done: 15, + compute_read: 15, + ta_done: 7, + ta_read: 7, + fs_done: 9, + fs_read: 9, + consumer: [3, 4, 5], + ..Default::default() + }; + assert!(queues_drained(&t, &o)); + o.fs_read = 8; + assert!(!queues_drained(&t, &o)); + o.fs_read = 9; + o.consumer[COMPUTE] = 4; + assert!(!queues_drained(&t, &o)); + } + + #[test] + fn failures_and_deadlines() { + assert_eq!(failure(0, Some(4)), Failure::Timeout); + assert_eq!(failure(1, Some(4)), Failure::Fault); + assert_eq!(failure(0, Some(0)), Failure::Fault); + assert_eq!(failure(0, None), Failure::Fault); + assert_eq!( + renew(1000, 5000, 1000), + (1000 + 5_000_000_000, 1000 + 1_000_000_000) + ); + assert_eq!(renew(0, 10, 0), (100_000_000, 100_000_000)); + assert_eq!(kill_deadline(7, true), 7 + 2_000_000_000); + assert!(expired(1, kill_deadline(7, false))); + assert!(!expired(5, 5)); + assert!(expired(6, 5)); + } + + fn base() -> HangInputs { + HangInputs { + flight: true, + class: 2, + recovery: true, + hang_preempt: true, + ..Default::default() + } + } + + #[test] + fn decisions() { + let never = || -> bool { panic!("compute_hang evaluated on the fast path") }; + // Idle: nothing published, nothing armed, no error. + let i = HangInputs { + flight: false, + ..base() + }; + assert_eq!(decide(&i, never).action, HangAction::Idle); + // Published, within the deadlines: wait (no compute-hang evaluation). + assert_eq!(decide(&base(), never).action, HangAction::Wait); + // Compute deadline passed but no started compute hangs: wait. + let i = HangInputs { + compute_deadline_expired: true, + ..base() + }; + assert_eq!(decide(&i, || false).action, HangAction::Wait); + // ... with a hang on class 2: arm the compute request. + let d = decide(&i, || true); + assert_eq!(d.action, HangAction::ArmCompute); + assert!(d.compute_hang && !d.class0_hang); + // ... with recovery off: no request; the host deadline is expired, the failure + // branch fail-stops (no event, so no handshake). + let i0 = HangInputs { + recovery: false, + ..i + }; + let d = decide(&i0, || true); + assert_eq!(d.action, HangAction::Fail { recover: false }); + assert!(d.class0_hang); + // ... on class 0: fail-stop at once. + let i0 = HangInputs { class: 0, ..i }; + let d = decide(&i0, || true); + assert_eq!(d.action, HangAction::Fail { recover: false }); + assert!(d.compute_hang && d.class0_hang); + // Host deadline with no event: arm the request. + let i = HangInputs { + deadline_expired: true, + ..base() + }; + assert_eq!(decide(&i, never).action, HangAction::ArmDeadline); + // ... without hang preemption: fail-stop. + let i2 = HangInputs { + hang_preempt: false, + ..i + }; + assert_eq!( + decide(&i2, never).action, + HangAction::Fail { recover: false } + ); + // ... class 0 with a compute hang: no request (it cannot end it). + let i2 = HangInputs { class: 0, ..i }; + assert_eq!( + decide(&i2, || true).action, + HangAction::Fail { recover: false } + ); + assert_eq!(decide(&i2, || false).action, HangAction::ArmDeadline); + // Armed, budget running: wait; budget over: fail-stop. + let i = HangInputs { + armed: true, + ..base() + }; + assert_eq!(decide(&i, never).action, HangAction::Wait); + let i = HangInputs { + armed: true, + deadline_expired: true, + ..base() + }; + assert_eq!( + decide(&i, never).action, + HangAction::Fail { recover: false } + ); + // Armed with nothing published (the ended prefix retired, disarm pending): wait. + let i = HangInputs { + flight: false, + armed: true, + ..base() + }; + assert_eq!(decide(&i, never).action, HangAction::Wait); + // An error event: handshake, also with nothing published. + for flight in [true, false] { + let i = HangInputs { + flight, + new_errors: true, + ..base() + }; + assert_eq!(decide(&i, never).action, HangAction::Fail { recover: true }); + } + // A receipt fault: handshake. + let i = HangInputs { + fault: true, + ..base() + }; + assert_eq!(decide(&i, never).action, HangAction::Fail { recover: true }); + // Transport failure: fail-stop, never a handshake. + let i = HangInputs { + transport: true, + new_errors: true, + ..base() + }; + assert_eq!( + decide(&i, never).action, + HangAction::Fail { recover: false } + ); + // Recovery off: an error fail-stops. + let i = HangInputs { + new_errors: true, + recovery: false, + ..base() + }; + assert_eq!( + decide(&i, never).action, + HangAction::Fail { recover: false } + ); + } +} diff --git a/drivers/gpu/drm/asahi/g15/recovery/seams.rs b/drivers/gpu/drm/asahi/g15/recovery/seams.rs new file mode 100644 index 00000000000000..eb66a14e496ab2 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/recovery/seams.rs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The register, engine, channel and VM state recovery reads, as [`super::logic`]'s types, and +//! failing every VM. +//! +//! The other operations recovery, PB growth and the idle policy use are +//! `Firmware::{transport_error, drain_rings, devctl}` (channel.rs), `write_c1` (initdata.rs), +//! `Firmware::{progress, retire_oldest, report}` (poll.rs) and `job_partly_published` +//! (engine.rs). + +use kernel::prelude::*; + +use super::logic::{EngineState, Observed, Receipts, Tail}; +use crate::g15::channel::Channel; +use crate::g15::fw::graph::qstate; +use crate::g15::Firmware; + +impl Firmware { + // --- MMIO --- + + /// Engine busy and fault status (`Regs::engine_state`): busy = bit 0 of C020 | C120, fault + /// = D8C0 of fault banks 0 and 1 with the bank selector D800 saved and restored. Every + /// nonzero bank is logged with its decoded status (`log_fault`). + pub(crate) fn engine_state(&mut self) -> Result { + let state = self.session.regs.engine_state()?; + if state.fault() != 0 { + self.log_fault(&state); + } + Ok(EngineState { + busy: state.busy & 1 != 0, + fault: state.fault(), + }) + } + + // --- Engine --- + + /// Receipts of the published prefix `index` (0 = oldest): the `engine::Flight` fields + /// filled at publication. + pub(crate) fn receipts(&self, index: usize) -> Receipts { + let Some(f) = self.engine.flights.get(index) else { + return Receipts::default(); + }; + Receipts { + computes: f.computes, + renders: f.renders, + target: f.target, + head: f.head, + c_start: f.c_start, + ta_target: f.ta_target, + fs_target: f.fs_target, + ta_head: f.ta_head, + fs_head: f.fs_head, + ta_start: f.ta_start, + fs_start: f.fs_start, + rec: f.rec, + cstamp: f.cstamp, + cwait: f.cwait, + } + } + + /// The newest published receipts: the `engine::Engine` fields and the channel producers. + pub(crate) fn tail(&self) -> Tail { + let e = &self.engine; + Tail { + target: e.target, + head: e.head, + ta_target: e.ta_target, + fs_target: e.fs_target, + ta_head: e.ta_head, + fs_head: e.fs_head, + producer: [ + self.channels.producer(Channel::Ta), + self.channels.producer(Channel::Fs), + self.channels.producer(Channel::Compute), + ], + } + } + + /// One observation of the firmware-written receipt words: the compute/TA/FS FW stamps, the + /// compute/TA/FS work-ring DONE and READ cursors and the three submit channels' consumers. + pub(crate) fn observe(&self) -> Result { + let (g, r, ch) = (&self.graph.compute, &self.graph.render, &self.channels); + Ok(Observed { + compute_stamp: g.fw_stamp.r32(0)?, + ta_stamp: r.fw_stamp[0].r32(0)?, + fs_stamp: r.fw_stamp[1].r32(0)?, + compute_done: g.qstate.r32(qstate::DONE)?, + compute_read: g.qstate.r32(qstate::READ)?, + ta_done: r.qstate[0].r32(qstate::DONE)?, + ta_read: r.qstate[0].r32(qstate::READ)?, + fs_done: r.qstate[1].r32(qstate::DONE)?, + fs_read: r.qstate[1].r32(qstate::READ)?, + consumer: [ + ch.read(Channel::Ta)?, + ch.read(Channel::Fs)?, + ch.read(Channel::Compute)?, + ], + }) + } + + // --- VMs --- + + /// Latches `error` on every live VM (`Registry::fail_all`). + pub(crate) fn fail_all_vms(&mut self, error: Error) { + self.vms.fail_all(error) + } +} diff --git a/drivers/gpu/drm/asahi/g15/regs.rs b/drivers/gpu/drm/asahi/g15/regs.rs new file mode 100644 index 00000000000000..d5435e9f1c7eaa --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/regs.rs @@ -0,0 +1,308 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G15 MMIO: SGX identification, power, core and status windows, and ASC control. +//! +//! Windows inside `sgx` (accessed through the shared [`crate::regs::Resources`] runtime-offset +//! accessors): id `+0xd04000` (`+0` version, `+0x10` counts), open `+0xd14000` (write +//! 0x70001), core `+0xe00000` (`+0x1500` core mask, `+0x1000` pstate), status `+0xc000` +//! (`+0x20`/`+0x120` busy, `+0x1800` bank select, `+0x18c0` fault status, `+0x18c8` fault +//! address >> 6). ASC `+0x44` bit 4 is RUN (mapped from `asc` here; the shared layer does not +//! map it). No blind reads of unpowered blocks: read only after the AGX vote. +//! +//! The status window needs 64-bit stores (the fault bank select), which the shared accessors do +//! not offer, so it is mapped here, as is `asc`. This module also holds the [`Mapping`] type the +//! UAT regions use and the memory barriers. + +use kernel::{ + bindings, c_str, + device::Core, + io::{Io, Mmio, MmioRaw, Region}, + platform, + prelude::*, +}; + + + +/// Write memory barrier (`wmb()`): `dsb st`. +#[inline(always)] +pub(crate) fn wmb() { + // SAFETY: A barrier has no memory-safety requirements. + unsafe { core::arch::asm!("dsb st", options(nostack, preserves_flags)) }; +} + +/// Read memory barrier (`rmb()`): `dsb ld`. +#[inline(always)] +pub(crate) fn rmb() { + // SAFETY: A barrier has no memory-safety requirements. + unsafe { core::arch::asm!("dsb ld", options(nostack, preserves_flags)) }; +} + +/// Full memory barrier (`mb()`): `dsb sy`. +#[inline(always)] +pub(crate) fn mb() { + // SAFETY: A barrier has no memory-safety requirements. + unsafe { core::arch::asm!("dsb sy", options(nostack, preserves_flags)) }; +} + +/// How a [`Mapping`] was created. +#[derive(Copy, Clone, PartialEq, Eq)] +enum Kind { + /// `ioremap`/`ioremap_np`: device memory (registers). + Device, + /// `memremap(MEMREMAP_WC)`: normal non-cacheable memory. + WriteCombined, + /// `memremap(MEMREMAP_WB)`: System RAM through the kernel's own mapping. + WriteBack, +} + +/// A CPU mapping of a physical range that is not System RAM, accessed with the `readl`/`writel` +/// family (the accessors of [`Mmio`], with their barriers). +/// +/// # Invariants +/// +/// `raw` describes a live mapping of `raw.maxsize()` bytes created as `kind` says, which is +/// unmapped only on drop. +pub(crate) struct Mapping { + raw: MmioRaw>, + phys: u64, + kind: Kind, +} + +// SAFETY: The mapping is plain memory or registers; all accesses are single volatile accesses +// through `Mmio`, and callers serialize the protocols built on them. +unsafe impl Send for Mapping {} +// SAFETY: See `Send`. +unsafe impl Sync for Mapping {} + +impl Mapping { + /// Maps device registers (non-posted if `nonposted`). + pub(crate) fn device(phys: u64, size: usize, nonposted: bool) -> Result { + if size == 0 { + return Err(EINVAL); + } + // SAFETY: Mapping a physical range has no Rust-visible side effects; the range belongs to + // this device's `reg` resources. + let addr = unsafe { + if nonposted { + bindings::ioremap_np(phys, size) + } else { + bindings::ioremap(phys, size) + } + }; + if addr.is_null() { + return Err(ENOMEM); + } + Ok(Self { + raw: MmioRaw::new_region(addr as usize, size)?, + phys, + kind: Kind::Device, + }) + } + + /// Maps memory that is not System RAM write-combined. + pub(crate) fn write_combined(phys: u64, size: usize) -> Result { + if size == 0 { + return Err(EINVAL); + } + // SAFETY: memremap() of a range outside System RAM creates a new mapping; the range is + // an ADT-described GPU region that the caller admitted. + let addr = unsafe { bindings::memremap(phys, size, bindings::MEMREMAP_WC as _) }; + if addr.is_null() { + return Err(ENOMEM); + } + Ok(Self { + raw: MmioRaw::new_region(addr as usize, size)?, + phys, + kind: Kind::WriteCombined, + }) + } + + /// Maps a boot-loader region the firmware shares with the host: write-combined when it is + /// a carveout outside System RAM (the T6030 regions), through the kernel's cacheable + /// mapping when it is a reserved-memory region inside System RAM (the T6031 regions, which + /// the earlier driver of that SoC used the same way). + pub(crate) fn region(phys: u64, size: usize) -> Result { + if size == 0 { + return Err(EINVAL); + } + let mode = super::boot::glue::memory_mode(phys, size as u64)?; + if mode == bindings::MEMREMAP_WC as u32 { + return Self::write_combined(phys, size); + } + // SAFETY: memremap() of System RAM with MEMREMAP_WB returns its existing mapping; the + // range is a reserved-memory region of the GPU node that nothing else uses. + let addr = unsafe { bindings::memremap(phys, size, bindings::MEMREMAP_WB as _) }; + if addr.is_null() { + return Err(ENOMEM); + } + Ok(Self { + raw: MmioRaw::new_region(addr as usize, size)?, + phys, + kind: Kind::WriteBack, + }) + } + + /// The `readl`/`writel` accessors of this mapping. + pub(crate) fn io(&self) -> Mmio<'_, Region<0>> { + // SAFETY: By the type invariant `raw` describes a live mapping of `maxsize` bytes. + unsafe { Mmio::from_raw(self.raw) } + } + + /// Physical address of byte 0. + pub(crate) fn phys(&self) -> u64 { + self.phys + } +} + +impl Drop for Mapping { + fn drop(&mut self) { + // SAFETY: By the type invariant the mapping is live and was created as `kind` says. + unsafe { + match self.kind { + Kind::Device => bindings::iounmap(self.raw.addr() as *mut _), + Kind::WriteCombined | Kind::WriteBack => { + bindings::memunmap(self.raw.addr() as *mut _) + } + } + } + } +} + +/// Most clusters of a supported SoC. +pub(crate) const MAX_CLUSTERS: usize = 4; + +/// Identification read at start. +#[derive(Copy, Clone, Default)] +pub(crate) struct Identity { + pub(crate) version: u32, + pub(crate) counts: u32, + /// Raw enabled-core mask (`+0xe01500`, and `+0xe01504` above 32 core slots) and its + /// per-cluster split ([`super::hw::CLUSTER_BITS`] each, cluster 0 lowest), one entry per + /// cluster of the SoC. + pub(crate) cores: u64, + pub(crate) core_masks: [u32; MAX_CLUSTERS], +} + +/// Engine receipts: busy bit and the two fault banks. +#[derive(Copy, Clone, Default)] +pub(crate) struct EngineState { + /// Bit 0 of `+0xc020 | +0xc120`. + pub(crate) busy: u64, + /// `+0xd8c0` under fault-bank selectors 0 and 1. + pub(crate) status: [u64; 2], + /// `+0xd8c8 << 6` under fault-bank selectors 0 and 1. + pub(crate) address: [u64; 2], +} + +impl EngineState { + /// Fault status of both banks, OR-ed together. + pub(crate) fn fault(&self) -> u64 { + self.status[0] | self.status[1] + } +} + +/// G15 register access. +pub(crate) struct Regs { + /// The shared SGX mapping. + sgx: Mapping, + /// ASC control (`asc`, 0x4000). + asc: Mapping, + /// SGX status window (`sgx + 0xc000`, 0x4000). + status: Mapping, +} + +impl Regs { + /// Maps the ASC control page and the SGX status window. + pub(crate) fn new(pdev: &platform::Device>) -> Result { + let window = |name: &CStr, offset: u64| -> Result { + let r = pdev.resource_by_name(name).ok_or(EINVAL)?; + let nonposted = r + .flags() + .contains(kernel::io::resource::Flags::IORESOURCE_MEM_NONPOSTED); + if offset + WINDOW as u64 > r.size() { + return Err(EINVAL); + } + Mapping::device(r.start() + offset, WINDOW, nonposted) + }; + Ok(Self { + asc: window(c_str!("asc"), 0)?, + status: window(c_str!("sgx"), SGX_STATUS as u64)?, + sgx: { + let r = pdev.resource_by_name(c_str!("sgx")).ok_or(EINVAL)?; + let size = usize::try_from(r.size())?; + Mapping::device(r.start(), size, r.flags().contains(kernel::io::resource::Flags::IORESOURCE_MEM_NONPOSTED))? + }, + }) + } + + /// Reads the identification words and the enabled-core mask (once the GPU is powered). A + /// SoC with more than 32 core slots carries the mask in two words. + pub(crate) fn identity(&self, cfg: &super::Config) -> Result { + let version = self.sgx.io().try_read32(SGX_ID)?; + let counts = self.sgx.io().try_read32(SGX_ID + 0x10)?; + let mut cores = u64::from(self.sgx.io().try_read32(SGX_CORE + 0x1500)?); + if cfg.core_slots() > 32 { + cores |= u64::from(self.sgx.io().try_read32(SGX_CORE + 0x1504)?) << 32; + } + let bits = super::hw::CLUSTER_BITS; + let mask = (1u64 << bits) - 1; + let mut core_masks = [0u32; MAX_CLUSTERS]; + for (cluster, slot) in core_masks + .iter_mut() + .enumerate() + .take((cfg.num_clusters as usize).min(MAX_CLUSTERS)) + { + *slot = ((cores >> (cluster as u32 * bits)) & mask) as u32; + } + Ok(Identity { + version, + counts, + cores, + core_masks, + }) + } + + /// Opens the SGX for the firmware. + pub(crate) fn open(&self) -> Result { + self.sgx.io().try_write32(0x70001, SGX_OPEN) + } + + /// ASC control word (`asc + 0x44`). + pub(crate) fn asc_control(&self) -> Result { + self.asc.io().try_read32(ASC_CONTROL) + } + + /// Writes the ASC control word (`asc + 0x44`). + pub(crate) fn set_asc_control(&self, value: u32) -> Result { + self.asc.io().try_write32(value, ASC_CONTROL) + } + + /// Engine receipts, under the device lock: busy is bit 0 of `C020 | C120`; the fault status + /// is `D8C0` under fault-bank selectors 0 and 1 (`D800`), with the saved selector restored. + /// 64-bit accesses. + pub(crate) fn engine_state(&self) -> Result { + let r = self.status.io(); + let mut state = EngineState { + busy: (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1, + ..Default::default() + }; + let sel = r.try_read64(0x1800)?; + for bank in 0..2 { + r.try_write64(bank as u64, 0x1800)?; + state.status[bank] = r.try_read64(0x18c0)?; + state.address[bank] = r.try_read64(0x18c8)? << 6; + } + r.try_write64(sel, 0x1800)?; + Ok(state) + } +} + +/// Size of each MMIO window mapped here. +const WINDOW: usize = 0x4000; + +pub(crate) const SGX_ID: usize = 0xd04000; +pub(crate) const SGX_OPEN: usize = 0xd14000; +pub(crate) const SGX_CORE: usize = 0xe00000; +pub(crate) const SGX_STATUS: usize = 0xc000; +pub(crate) const ASC_CONTROL: usize = 0x44; +pub(crate) const ASC_RUN: u32 = 1 << 4; diff --git a/drivers/gpu/drm/asahi/g15/slots.rs b/drivers/gpu/drm/asahi/g15/slots.rs new file mode 100644 index 00000000000000..aae6d8804ee7f9 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/slots.rs @@ -0,0 +1,880 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Compute slots, render pass slots and clustering buffers, and their background scrub. +//! +//! States CLEAN/USED/DIRTY/CLEARING/STALE. A retired slot becomes DIRTY and is reset on a +//! dedicated unbound, reclaim-safe workqueue (work images, sequences, TA/FS scratch, stamps, +//! dirty TPC/tilemap spans, aux/heap/scene-user, the 3 preemption areas); a claim resets +//! synchronously only if the slot is not CLEAN. Slot 0 keeps the maximum TPC/tilemap; a 17th +//! TPC slot would collide with the clustering arena. +//! +//! The slot objects never change after allocation and live in [`Scrub`], shared by the engine +//! (under the device lock) and the scrub work (which never takes the device lock); the states +//! and the dirty spans are under the scrub spinlock. A claim may flush the scrub work under the +//! device lock: the scrub work runs on its own `WQ_UNBOUND | WQ_MEM_RECLAIM` queue because +//! flushing a system-queue work from the reclaim-safe scheduler work WARNs. + +use kernel::{ + bindings, c_str, impl_has_work, new_spinlock, new_work, + prelude::*, + sync::{Arc, SpinLock}, + workqueue::{self, HasWork, Work, WorkItem}, +}; + +use super::encode::{Geometry, PassRefs}; +use super::engine::wmb; +use super::fw::work::{barrier, compute, fs, ta}; +use super::graph::{alloc, cmd_fw, cmd_shared, Client}; +use super::hw::{client, sizes, tuning}; +use super::object::{Class, FwObject, Objects}; + +/// Reset state of a slot's mutable storage. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum SlotState { + /// All zero (scrubbed) and free. + Clean, + /// Held by a prefix being prepared or published. + Used, + /// Retired, waiting for the scrub. + Dirty, + /// Being scrubbed by the scrub work. + Clearing, + /// Retired without slot rotation: scrubbed at its next claim. + Stale, +} + +/// One compute command slot. +pub(crate) struct ComputeSlot { + pub(crate) its: Arc, + /// Part of the slot's firmware layout; the host does not use it. + _uts: Arc, + pub(crate) preempt: Arc, + pub(crate) work: Arc, + pub(crate) tail: Arc, + pub(crate) seq: Arc, + pub(crate) scratch: KVec>, + /// Mixed prefix: the wait on the previous render's FS or the previous compute. + pub(crate) barrier: Arc, +} + +/// A compute slot's objects before its barrier exists (the barriers are allocated after the +/// render graph). +struct ComputeParts { + its: Arc, + uts: Arc, + preempt: Arc, + work: Arc, + tail: Arc, + seq: Arc, + scratch: KVec>, +} + +impl ComputeParts { + /// Allocates compute slot `k`'s objects. + fn new(o: &mut Objects, k: u64) -> Result { + let sh = Class::Shared; + let its = alloc(o, 16, sh, None, 0, false)?; + let uts = alloc(o, 16, Class::Fw, None, 0, false)?; + let preempt = alloc( + o, + 0x10000, + sh, + Client::nc(client::PREEMPT + k * client::PREEMPT_STRIDE), + 0, + false, + )?; + let work = alloc( + o, + compute::WORK_SIZE, + cmd_shared(), + Client::nc(client::WORK_PAGE + k * client::CWORK_STRIDE), + client::WORK_OFF as usize, + true, + )?; + let tail = alloc(o, 0x10000, sh, None, 0, false)?; + let seq = alloc(o, compute::SEQ_OBJECT, cmd_fw(), None, 0, false)?; + let mut scratch = KVec::with_capacity(5, GFP_KERNEL)?; + for _ in 0..5 { + scratch.push(alloc(o, 0x10000, sh, None, 0, false)?, GFP_KERNEL)?; + } + Ok(Self { + its, + uts, + preempt, + work, + tail, + seq, + scratch, + }) + } + + fn with_barrier(self, barrier: Arc) -> ComputeSlot { + ComputeSlot { + its: self.its, + _uts: self.uts, + preempt: self.preempt, + work: self.work, + tail: self.tail, + seq: self.seq, + scratch: self.scratch, + barrier, + } + } +} + +impl ComputeSlot { + /// Per-use reset of a retired slot's runtime storage: timestamp cells, tail and sequence + /// scratch zeroed, preemption poisoned with 0xcc. + fn scrub(&self) -> Result { + self.its.fill(0, 0, 16)?; + self.tail.fill(0, 0, 0x10000)?; + for s in self.scratch.iter() { + s.fill(0, 0, 0x10000)?; + } + self.preempt.fill(0, 0xcc, 0x10000) + } +} + +/// One render pass slot. +pub(crate) struct PassSlot { + pub(crate) aux: Arc, + pub(crate) pre: KVec>, + pub(crate) tpc: Arc, + pub(crate) tilemap: Arc, + pub(crate) heap: Arc, + pub(crate) scene_user: Arc, + pub(crate) fs_scratch: Arc, + pub(crate) fs_work: Arc, + pub(crate) ta_work: Arc, + pub(crate) ta_seq: Arc, + pub(crate) fs_seq: Arc, + pub(crate) ta_scratch: Arc, + pub(crate) scene: Arc, + pub(crate) its: Arc, + /// Part of the slot's firmware layout; the host does not use it. + _uts: Arc, + pub(crate) own_barrier: Arc, + pub(crate) prev_barrier: Arc, + pub(crate) fs_dep: Arc, +} + +impl PassSlot { + /// Allocates pass slot `i`'s objects, with their client leaf classes. + fn new(o: &mut Objects, i: u64, pre_records: u32) -> Result { + let sh = Class::Shared; + let (ps, ws) = (i * client::PASS_STRIDE, i * client::WORK_STRIDE); + let tpc = if i != 0 { + client::TPC_SLOT_SIZE + } else { + client::TPC_SIZE + }; + let tilemap = if i != 0 { + client::TILEMAP_SLOT_SIZE + } else { + client::TILEMAP_SIZE + }; + let r = pre_records as usize; + + let aux = alloc( + o, + 0x20000, + sh, + Client::nc(client::AUX + i * client::AUX_STRIDE), + 0, + false, + )?; + let mut pre = KVec::with_capacity(3, GFP_KERNEL)?; + pre.push( + alloc( + o, + r * 0x540, + sh, + Client::cached(client::PRE0_PAGE + ps), + 0x3580, + false, + )?, + GFP_KERNEL, + )?; + pre.push( + alloc( + o, + r * 0x280, + sh, + Client::cached(client::PRE1_PAGE + ps), + 0x3b00, + false, + )?, + GFP_KERNEL, + )?; + pre.push( + alloc( + o, + r * 0x40, + sh, + Client::cached(client::PRE2_PAGE + ps), + 0x3f80, + false, + )?, + GFP_KERNEL, + )?; + let tpc = alloc( + o, + tpc as usize, + sh, + Client::cached(client::TPC + i * client::TPC_SLOT_STRIDE), + 0, + false, + )?; + let tilemap = alloc( + o, + tilemap as usize, + sh, + Client::cached(client::TILEMAP + i * client::TPC_SLOT_STRIDE), + 0, + false, + )?; + let heap = alloc( + o, + 0x1000, + sh, + Client::cached(client::HEAP_META_PAGE + ps), + 0x3000, + false, + )?; + let scene_user = alloc( + o, + 0x10000, + sh, + Client::cached(client::SCENE_USER + ps), + 0, + false, + )?; + let fs_scratch = alloc( + o, + 0x10000, + sh, + Client::cached(client::FS_SCRATCH + ps), + 0, + false, + )?; + let fs_work = alloc( + o, + fs::WORK_SIZE, + cmd_shared(), + Client::nc(client::FS_WORK_PAGE + ws), + client::FS_WORK_OFF as usize, + true, + )?; + let ta_work = alloc( + o, + ta::WORK_SIZE, + cmd_shared(), + Client::nc(client::TA_WORK_PAGE + ws), + client::TA_WORK_OFF as usize, + true, + )?; + Ok(Self { + aux, + pre, + tpc, + tilemap, + heap, + scene_user, + fs_scratch, + fs_work, + ta_work, + ta_seq: alloc(o, ta::SEQ_OBJECT, cmd_fw(), None, 0, false)?, + fs_seq: alloc(o, fs::SEQ_OBJECT, cmd_fw(), None, 0, false)?, + ta_scratch: alloc(o, 0x10000, sh, None, 0, false)?, + scene: alloc(o, super::fw::work::scene::SIZE, sh, None, 0, false)?, + // Internal TA start/end, FS start/end; legacy user cells likewise. + its: alloc(o, 32, sh, None, 0, false)?, + _uts: alloc(o, 32, Class::Fw, None, 0, false)?, + own_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + prev_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + fs_dep: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + }) + } + + /// Per-use reset of a pass slot's storage: work images, microsequences, scratch, stage + /// stamps, the TPC/tilemap spans its last use wrote, auxiliary, heap metadata and + /// scene-user (`PASS_FULL_RESET`) and the preemption save areas. The slot is neither + /// published nor claimed; the dirty spans are passed in. + fn scrub(&self, pre_records: u32, tpc_dirty: u64, tilemap_dirty: u64) -> Result { + let r = pre_records as usize; + + self.ta_work.fill(0, 0, ta::WORK_SIZE)?; + self.fs_work.fill(0, 0, fs::WORK_SIZE)?; + self.ta_seq.fill(0, 0, ta::SEQ_OBJECT)?; + self.fs_seq.fill(0, 0, fs::SEQ_OBJECT)?; + self.ta_scratch.fill(0, 0, 0x10000)?; + self.fs_scratch.fill(0, 0, 0x10000)?; + self.its.fill(0, 0, 32)?; + self.tpc.fill(0, 0, tpc_dirty as usize)?; + self.tilemap.fill(0, 0, tilemap_dirty as usize)?; + if tuning::PASS_FULL_RESET { + self.aux.fill(0, 0, 0x20000)?; + self.heap.fill(0, 0, 0x1000)?; + self.scene_user.fill(0, 0, 0x10000)?; + } + // Preemption save areas start zeroed on every use. + self.pre[0].fill(0, 0, r * 0x540)?; + self.pre[1].fill(0, 0, r * 0x280)?; + self.pre[2].fill(0, 0, r * 0x40) + } + + /// The addresses the render encoders name. + pub(crate) fn refs(&self) -> PassRefs { + PassRefs { + ta_work: self.ta_work.va, + ta_work_gva: self.ta_work.gva.unwrap_or(0), + fs_work: self.fs_work.va, + fs_work_gva: self.fs_work.gva.unwrap_or(0), + ta_seq: self.ta_seq.va, + fs_seq: self.fs_seq.va, + scene: self.scene.va, + tpc_gva: self.tpc.gva.unwrap_or(0), + tilemap_gva: self.tilemap.gva.unwrap_or(0), + heap_gva: self.heap.gva.unwrap_or(0), + scene_user_gva: self.scene_user.gva.unwrap_or(0), + pre_gva: [ + self.pre[0].gva.unwrap_or(0), + self.pre[1].gva.unwrap_or(0), + self.pre[2].gva.unwrap_or(0), + ], + fs_scratch_gva: self.fs_scratch.gva.unwrap_or(0), + aux_gva: self.aux.gva.unwrap_or(0), + its: self.its.va, + ta_scratch: self.ta_scratch.va, + } + } +} + +/// Reset states and dirty spans, under the scrub spinlock. +struct States { + compute: [SlotState; sizes::COMPUTE_SLOTS], + pass: [SlotState; sizes::RENDER_SLOTS], + /// The TPC/tilemap spans a pass slot's last use may have written. + tpc_dirty: [u64; sizes::RENDER_SLOTS], + tilemap_dirty: [u64; sizes::RENDER_SLOTS], + ct: [SlotState; sizes::CT_BUFS], + /// The span a clustering buffer's pass may have written. + ct_dirty: [u64; sizes::CT_BUFS], +} + +/// An owned `WQ_UNBOUND | WQ_MEM_RECLAIM` workqueue with one active work (allocated ordered, +/// which is the same for its single work item). +struct ClearQueue(*mut bindings::workqueue_struct); + +// SAFETY: The workqueue API is thread-safe; this only holds the pointer. +unsafe impl Send for ClearQueue {} +// SAFETY: The workqueue API is thread-safe; this only holds the pointer. +unsafe impl Sync for ClearQueue {} + +impl ClearQueue { + fn new() -> Result { + // SAFETY: The name is a valid NUL-terminated string the C side copies. + let ptr = unsafe { + bindings::alloc_ordered_workqueue( + c_str!("asahi-g15-clear").as_char_ptr(), + bindings::wq_flags_WQ_MEM_RECLAIM, + ) + }; + if ptr.is_null() { + return Err(ENOMEM); + } + Ok(Self(ptr)) + } + + fn queue(&self) -> &workqueue::Queue { + // SAFETY: The pointer is a live workqueue until `self` is dropped. + unsafe { workqueue::Queue::from_raw(self.0) } + } +} + +impl Drop for ClearQueue { + fn drop(&mut self) { + // SAFETY: The pointer came from `alloc_ordered_workqueue` and is not used afterwards; + // `destroy_workqueue` drains it first. + unsafe { bindings::destroy_workqueue(self.0) }; + } +} + +/// The slot objects and the background scrub. +#[pin_data] +pub(crate) struct Scrub { + pub(crate) compute: KVec, + pub(crate) passes: KVec, + /// Clustering buffers: a GPU-cached client view of 64 tilemap segments and four metadata + /// regions, after the ordinary TPC/tilemap slots. + pub(crate) cts: KVec>, + /// Preemption records per buffer: 2, 3 with clustering. + pub(crate) pre_records: u32, + #[pin] + states: SpinLock, + #[pin] + work: Work, + queue: ClearQueue, +} + +impl_has_work! { + impl HasWork for Scrub { self.work } +} + +impl WorkItem for Scrub { + type Pointer = Arc; + + fn run(this: Arc) { + this.clear_all(); + } +} + +impl Scrub { + /// Resets every DIRTY pass slot, compute slot and clustering buffer, outside the device + /// lock. + fn clear_all(&self) { + loop { + let taken = { + let mut st = self.states.lock(); + let k = st.pass.iter().position(|s| *s == SlotState::Dirty); + k.map(|k| { + st.pass[k] = SlotState::Clearing; + let dirty = (st.tpc_dirty[k], st.tilemap_dirty[k]); + st.tpc_dirty[k] = 0; + st.tilemap_dirty[k] = 0; + (k, dirty) + }) + }; + let Some((k, (tpc, tilemap))) = taken else { + break; + }; + let _ = self.passes[k].scrub(self.pre_records, tpc, tilemap); + wmb(); // reset before the slot can be claimed + self.states.lock().pass[k] = SlotState::Clean; + } + loop { + let taken = { + let mut st = self.states.lock(); + let k = st.compute.iter().position(|s| *s == SlotState::Dirty); + if let Some(k) = k { + st.compute[k] = SlotState::Clearing; + } + k + }; + let Some(k) = taken else { + break; + }; + let _ = self.compute[k].scrub(); + wmb(); // scrubbed before the slot can be claimed + self.states.lock().compute[k] = SlotState::Clean; + } + loop { + let taken = { + let mut st = self.states.lock(); + let k = st.ct.iter().position(|s| *s == SlotState::Dirty); + k.map(|k| { + st.ct[k] = SlotState::Clearing; + (k, st.ct_dirty[k]) + }) + }; + let Some((k, dirty)) = taken else { + return; + }; + let _ = self.cts[k].fill(0, 0, dirty as usize); + wmb(); // zeroes complete before the buffer can be claimed + let mut st = self.states.lock(); + st.ct_dirty[k] = 0; + st.ct[k] = SlotState::Clean; + } + } + + /// Waits for the scrub work. + fn flush(self: &Arc) { + // SAFETY: `self` is a live `Arc`, so its `work` field is a valid, initialized + // `work_struct` for the duration of the call. + unsafe { + let work = >::raw_get_work(Arc::as_ptr(self).cast_mut()); + bindings::flush_work(Work::raw_get(work)); + } + } + + /// Queues the scrub work on its own queue. + fn kick(self: &Arc) { + // Already queued if this fails, which is just as good. + let _ = self.queue.queue().enqueue(self.clone()); + } +} + +/// The storage claims of a prefix: compute slots, pass slots and clustering buffers. +#[derive(Copy, Clone)] +pub(crate) struct Claims { + /// Compute slot of compute member j. + pub(crate) slot: [u32; sizes::COMPUTE_SLOTS], + pub(crate) slot_count: u32, + /// Pass slot of render member j, and the set of them. + pub(crate) pass: [u32; sizes::RENDER_SLOTS], + pub(crate) pass_mask: u32, + /// Clustering buffers claimed. + pub(crate) ct: [u32; sizes::RENDER_SLOTS], + pub(crate) ct_count: u32, + /// The compute slots rotate (`tuning::SLOT_ROTATE` at the first member). + pub(crate) rotating: bool, +} + +impl Claims { + pub(crate) const fn new() -> Self { + Self { + slot: [0; sizes::COMPUTE_SLOTS], + slot_count: 0, + pass: [0; sizes::RENDER_SLOTS], + pass_mask: 0, + ct: [0; sizes::RENDER_SLOTS], + ct_count: 0, + rotating: false, + } + } +} + +/// Slot accounting statistics (`asahi-g15/stats`). +#[derive(Copy, Clone, Default)] +pub(crate) struct SlotStats { + /// Clustering buffers zeroed at claim, pass slots reset at claim, compute slots scrubbed + /// at claim. + pub(crate) ct_sync: u64, + pub(crate) pass_sync: u64, + pub(crate) slot_sync: u64, + /// Claims that waited for the scrub work, and how long (timed only with debug_flags bit 49). + pub(crate) flushes: u64, + pub(crate) flush_ns: u64, +} + +/// Slot and storage state. +pub(crate) struct Slots { + pub(crate) scrub: Arc, + /// Next compute slot to try. + pub(crate) cursor: u32, + /// Pass slots held by published or prepared prefixes. + pub(crate) pass_busy: u32, + /// Next small pass slot (1..slots-1) to try. + pub(crate) pass_cursor: u32, + pub(crate) stats: SlotStats, +} + +impl Slots { + /// Waits for the scrub work, counted. + fn flush_scrub(&mut self, scrub: &Arc) { + let mut lap = super::engine::Lap::start(); + scrub.flush(); + self.stats.flushes += 1; + lap.lap(&mut self.stats.flush_ns); + } + + /// Allocates the compute slots, the pass slots, the compute slots' barriers, the clustering + /// buffers and the scrub workqueue. + pub(crate) fn new(objects: &mut Objects) -> Result { + // Clustered tiling needs three records in each preemption buffer (two per-cluster plus + // an aggregate), each buffer then spanning two pages from the same payload offset. + let pre_records = if tuning::VERTEX_CLUSTERING { 3 } else { 2 }; + let mut compute = KVec::with_capacity(sizes::COMPUTE_SLOTS, GFP_KERNEL)?; + let mut passes = KVec::with_capacity(sizes::RENDER_SLOTS, GFP_KERNEL)?; + let mut cts = KVec::with_capacity(sizes::CT_BUFS, GFP_KERNEL)?; + + // Allocation order: the compute slots, the pass slots, then the compute slots' barriers + // and the clustering buffers. + let mut parts = KVec::with_capacity(sizes::COMPUTE_SLOTS, GFP_KERNEL)?; + for k in 0..sizes::COMPUTE_SLOTS as u64 { + parts.push(ComputeParts::new(objects, k)?, GFP_KERNEL)?; + } + for i in 0..sizes::RENDER_SLOTS as u64 { + passes.push(PassSlot::new(objects, i, pre_records)?, GFP_KERNEL)?; + } + for part in parts.drain_all() { + let barrier = alloc(objects, barrier::SIZE, cmd_fw(), None, 0, false)?; + compute.push(part.with_barrier(barrier), GFP_KERNEL)?; + } + // Clustering storage: GPU-cached client view and shared upper alias. + if pre_records == 3 { + for k in 0..sizes::CT_BUFS as u64 { + let ct = alloc( + objects, + client::CT_SIZE as usize, + Class::Shared, + Client::cached(client::CT + k * client::CT_STRIDE), + 0, + false, + )?; + cts.push(ct, GFP_KERNEL)?; + } + } + let scrub = Arc::pin_init( + try_pin_init!(Scrub { + compute, + passes, + cts, + pre_records, + states <- new_spinlock!( + States { + compute: [SlotState::Clean; sizes::COMPUTE_SLOTS], + pass: [SlotState::Clean; sizes::RENDER_SLOTS], + tpc_dirty: [0; sizes::RENDER_SLOTS], + tilemap_dirty: [0; sizes::RENDER_SLOTS], + ct: [SlotState::Clean; sizes::CT_BUFS], + ct_dirty: [0; sizes::CT_BUFS], + }, + "g15::Scrub::states" + ), + work <- new_work!("g15::Scrub::work"), + queue: ClearQueue::new()?, + }), + GFP_KERNEL, + )?; + Ok(Self { + scrub, + cursor: 0, + pass_busy: 0, + pass_cursor: 0, + stats: SlotStats::default(), + }) + } + + /// Scrubs every compute slot and marks it CLEAN. Pass slots and clustering buffers start as + /// fresh zero pages. + pub(crate) fn init(&self) -> Result { + for s in self.scrub.compute.iter() { + s.scrub()?; + } + let mut st = self.scrub.states.lock(); + st.compute = [SlotState::Clean; sizes::COMPUTE_SLOTS]; + Ok(()) + } + + /// Compute slots a new prefix can still claim: not held by a published one. + pub(crate) fn free_compute(&self) -> u32 { + let st = self.scrub.states.lock(); + st.compute.iter().filter(|s| **s != SlotState::Used).count() as u32 + } + + /// A scrubbed compute slot for compute member `j` of the prefix being prepared: the first + /// clean slot from the cursor, which follows the previous prefix's slots, so they can be + /// scrubbed while this one runs; with none clean, a retired slot is scrubbed here. Slots + /// of published prefixes are never taken. Without rotation member j takes slot j when it + /// is free. None: all held. + pub(crate) fn claim_compute(&mut self, f: &mut Claims, j: u32) -> Result> { + let scrub = self.scrub.clone(); + let slots = sizes::COMPUTE_SLOTS; + let mut found = None; + let mut sync = false; + + if j == 0 { + f.rotating = tuning::SLOT_ROTATE; + } + if !f.rotating && (j as usize) < slots { + let k = j as usize; + let mut st = scrub.states.lock(); + while st.compute[k] == SlotState::Clearing { + drop(st); + self.flush_scrub(&scrub); + st = scrub.states.lock(); + } + if st.compute[k] != SlotState::Used { + sync = st.compute[k] != SlotState::Clean; + st.compute[k] = SlotState::Used; + found = Some(k); + } + } + for _attempt in 0..2 { + if found.is_some() { + break; + } + let mut clearing = false; + { + let mut st = scrub.states.lock(); + for i in 0..slots { + let k = (self.cursor as usize + i) % slots; + if st.compute[k] == SlotState::Clean { + found = Some(k); + break; + } + } + if found.is_none() { + for i in 0..slots { + let k = (self.cursor as usize + i) % slots; + let s = st.compute[k]; + if found.is_none() && (s == SlotState::Dirty || s == SlotState::Stale) { + found = Some(k); + } + clearing |= s == SlotState::Clearing; + } + } + if let Some(k) = found { + sync = st.compute[k] != SlotState::Clean; + st.compute[k] = SlotState::Used; + } + } + if found.is_none() && !clearing { + break; // all held by published prefixes + } + if found.is_none() { + self.flush_scrub(&scrub); // the rest are being scrubbed + } + } + let Some(k) = found else { + return Ok(None); + }; + if sync { + scrub.compute[k].scrub()?; + self.stats.slot_sync += 1; + } + self.cursor = ((k + 1) % slots) as u32; + f.slot[f.slot_count as usize] = k as u32; + f.slot_count += 1; + Ok(Some(k)) + } + + /// A pass slot for a render of the given geometry, not held and not already picked: the + /// next small slot after the previous prefix's, else slot 0 (which holds any admitted + /// geometry); None if none is free. + pub(crate) fn pick_pass(&self, geo: &Geometry, picked: u32) -> Option { + let busy = self.pass_busy | picked; + let slots = sizes::RENDER_SLOTS as u32; + let passes = &self.scrub.passes; + let fits = |k: usize| { + geo.tpc_bytes <= passes[k].tpc.size as u64 + && geo.tilemap_bytes <= passes[k].tilemap.size as u64 + }; + + if slots > 1 { + for j in 0..slots - 1 { + let k = 1 + (self.pass_cursor + j) % (slots - 1); + if busy & (1 << k) == 0 && fits(k as usize) { + return Some(k as usize); + } + } + } + if busy & 1 == 0 && fits(0) { + return Some(0); + } + None + } + + /// Claims pass slot `k` for a render of the prefix being prepared: reset now unless the + /// background reset already did. + pub(crate) fn claim_pass(&mut self, k: usize) -> Result { + let scrub = self.scrub.clone(); + let (sync, tpc, tilemap) = { + let mut st = scrub.states.lock(); + while st.pass[k] == SlotState::Clearing { + drop(st); + self.flush_scrub(&scrub); + st = scrub.states.lock(); + } + let sync = st.pass[k] != SlotState::Clean; + let dirty = (st.tpc_dirty[k], st.tilemap_dirty[k]); + if sync { + st.tpc_dirty[k] = 0; + st.tilemap_dirty[k] = 0; + } + st.pass[k] = SlotState::Used; + (sync, dirty.0, dirty.1) + }; + if sync { + scrub.passes[k].scrub(scrub.pre_records, tpc, tilemap)?; + self.stats.pass_sync += 1; + } + Ok(()) + } + + /// Records the TPC/tilemap spans a claimed pass slot's render may write. + pub(crate) fn set_pass_dirty(&mut self, k: usize, tpc: u64, tilemap: u64) { + let mut st = self.scrub.states.lock(); + st.tpc_dirty[k] = tpc; + st.tilemap_dirty[k] = tilemap; + } + + /// A zeroed clustering buffer of at least `bytes` for a pass of the prefix being + /// prepared, or None: none provisioned or too small. + pub(crate) fn claim_ct(&mut self, f: &mut Claims, bytes: u64) -> Result> { + let scrub = self.scrub.clone(); + let mut found = None; + let mut clear = 0; + + if scrub.cts.is_empty() || bytes > scrub.cts[0].size as u64 { + return Ok(None); + } + for _attempt in 0..2 { + { + let mut st = scrub.states.lock(); + found = st.ct.iter().position(|s| *s == SlotState::Clean); + // None clean: take a retired one and zero it here. + if found.is_none() { + found = st.ct.iter().position(|s| *s == SlotState::Dirty); + } + if let Some(k) = found { + clear = if st.ct[k] == SlotState::Dirty { + st.ct_dirty[k] + } else { + 0 + }; + st.ct[k] = SlotState::Used; + } + } + if found.is_some() { + break; + } + self.flush_scrub(&scrub); // the rest are being cleared + } + let Some(k) = found else { + return Ok(None); + }; + if clear != 0 { + scrub.cts[k].fill(0, 0, clear as usize)?; + self.stats.ct_sync += 1; + } + scrub.states.lock().ct_dirty[k] = bytes; + f.ct[f.ct_count as usize] = k as u32; + f.ct_count += 1; + Ok(Some(k)) + } + + /// The storage of a retired (or never published) prefix: compute slots and clustering + /// buffers are reset in the background while later prefixes run; its pass slots become + /// free again. + pub(crate) fn release(&mut self, f: &mut Claims) { + let mut mask = f.pass_mask; + + self.pass_busy &= !f.pass_mask; + f.pass_mask = 0; + if f.ct_count == 0 && f.slot_count == 0 && mask == 0 { + return; + } + { + let mut st = self.scrub.states.lock(); + let mut k = 0; + while mask != 0 { + // Only a slot this prefix used is dirty; one it claimed but never wrote (a + // publication that failed before its records) keeps its state. + if mask & 1 != 0 && st.pass[k] == SlotState::Used { + st.pass[k] = SlotState::Dirty; + } + k += 1; + mask >>= 1; + } + for c in &f.ct[..f.ct_count as usize] { + st.ct[*c as usize] = SlotState::Dirty; + } + // Without rotation the next claim of a slot scrubs it (STALE). + for s in &f.slot[..f.slot_count as usize] { + st.compute[*s as usize] = if f.rotating { + SlotState::Dirty + } else { + SlotState::Stale + }; + } + } + f.ct_count = 0; + f.slot_count = 0; + if tuning::CT_ASYNC { + self.scrub.kick(); + } + } +} diff --git a/drivers/gpu/drm/asahi/g15/timestamp.rs b/drivers/gpu/drm/asahi/g15/timestamp.rs new file mode 100644 index 00000000000000..5a11f5550c0590 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/timestamp.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The firmware timestamp arena. +//! +//! GEM_BIND_OBJECT with USAGE_TIMESTAMPS maps the BO range into the 64 MiB arena at +//! [`super::hw::va::TIMESTAMPS`] in the host window with the firmware/GPU shared class +//! ([`super::hw::pte::SHARED`]); the firmware writes nanoseconds directly from the start/end +//! microsequence records (four distinct values for a render). The arena is a range of the +//! adopted UAT's `kernel_vm`, so the mapping is a shared-layer `mmu::KernelMapping`, placed in +//! the arena by the shared VA allocator (ENOSPC when full). Its leaves are cleaned to the point +//! of coherency by the shared page-table code; a page table it adds reaches the firmware's view +//! through the host-window sync ([`super::object::Objects::sync_window`]) before the VA is +//! returned. +//! +//! A job retains the mappings it names, and failed jobs are retained until +//! reboot, so an arena alias the firmware may still write is never unmapped. Unmapping clears +//! leaves only: the tables stay linked. + +use core::ops::Range; +use core::sync::atomic::Ordering; +use kernel::prelude::*; + +use super::{hw, Gpu}; +use crate::{gem, mmu}; + +/// The arena in the host window. +const ARENA: Range = hw::va::TIMESTAMPS..hw::va::TIMESTAMPS + hw::va::TIMESTAMPS_SIZE; + +/// Maps a timestamp buffer into the arena (`gpu::Gpu::map_timestamp_buffer`). +pub(crate) fn map( + gpu: &Gpu, + mut bo: gem::ObjectRef, + range: Range, +) -> Result { + if gpu.shared.crashed.load(Ordering::Acquire) { + return Err(EIO); + } + let size = range.end.checked_sub(range.start).ok_or(EINVAL)?; + if size == 0 || (range.start | size) & mmu::UAT_PGMSK != 0 || range.end > bo.size() { + return Err(EINVAL); + } + let mapping = bo.map_range_into_range( + gpu.uat.kernel_vm(), + range, + ARENA, + mmu::UAT_PGSZ as u64, + mmu::Prot::from_pte(hw::pte::SHARED), + false, + )?; + // The firmware walks the host window through its own second-level table. + let synced = gpu + .shared + .state + .lock() + .as_deref_mut() + .ok_or(ENODEV) + .and_then(|firmware| firmware.objects.sync_window(mapping.iova_range())); + // On failure the mapping is dropped (unmapped) without the device lock. + synced?; + Ok(mapping) +} diff --git a/drivers/gpu/drm/asahi/g15/uat.rs b/drivers/gpu/drm/asahi/g15/uat.rs new file mode 100644 index 00000000000000..854ff34e729a37 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/uat.rs @@ -0,0 +1,405 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The adopted UAT: PPL handoff, TTBAT context 0, the host window and TLB maintenance. +//! +//! The firmware's kernel root (the TABLES region, ADT `gpu-region`) and the shared L2 page are +//! not System RAM, so the shared page-table code cannot walk them. The design: +//! +//! 1. Map handoff, TTBAT, kernel root page and shared L2 (write-combined carveouts, or the +//! kernel's mapping of reserved System RAM, [`Mapping::region`]). PPL exchange: write the +//! AP magic, `cur_slot = 0xffffffff`, zero the 65 flush entries and `+0x640`, then poll the +//! firmware magic (1 s). +//! 2. `mmu::Uat::new_adopted` with `kernel_root = TABLES`: user VMs and the kernel lower VM get +//! driver-owned RAM roots; `kernel_vm` manages the host window under a RAM shadow root. +//! 3. Under the PPL lock: zero root entries 2..63 of the firmware kernel root and all of the +//! shared L2, TLBI all, root[2] = shared L2 | 3, zero TTBAT 2..127, TTBAT context 0 = +//! (kernel lower root | 1, TABLES | 1). Root entries 0..1 belong to the firmware. +//! 4. [`Window::sync_range`]: after any mapping in `kernel_vm`, copy the shadow root's window L2 +//! entries (they name RAM L3 tables) into the shared L2, before the firmware uses the new +//! addresses. Tables are never freed on unmap. +//! +//! Point of coherency: the tables are RAM pages the shared code writes through the cacheable +//! linear map, and the UAT walker does not snoop the CPU caches, so every table the firmware can +//! walk is cleaned to the point of coherency before it becomes reachable, and changed leaves are +//! cleaned before the new addresses are published: [`Window::sync_range`] for the host window, +//! [`clean_lower`] for the context-0 lower tree. (The cleaning in `pgtable.rs` makes these +//! redundant but harmless.) +//! +//! User VMs are bound to exclusive TTBAT slots for their lifetime through `mmu::Uat::bind` +//! (`vm.rs`); the shared layer writes TTBAT `(root | 1 | slot << 48, TABLES | 1 | +//! slot << 48)` under the PPL lock and invalidates the slot's ASID. + +use core::ops::Range; +use core::sync::atomic::Ordering; + +use kernel::{ + bindings, device, + io::Io, + prelude::*, + sync::Arc, + time::{delay::fsleep, Delta, Instant, Monotonic}, +}; + +use super::hw; +use super::regs::{mb, rmb, wmb, Mapping}; +use crate::driver::AsahiDrmDevice as AsahiDevice; +use crate::{mmu, pgtable}; + +/// Entries of a UAT table page. +const ENTRIES: usize = 2048; +/// Entries of the top-level table used with a 42-bit input range. +const ROOT_ENTRIES: usize = 64; +/// Input address mask of a 42-bit UAT. +const IAS_MASK: u64 = (1 << 42) - 1; +/// Valid table/leaf descriptor bits. +const VALID: u64 = 3; +/// Root entry of the host window (2). +const WINDOW_INDEX: usize = ((hw::HOST & IAS_MASK) >> 36) as usize; + +/// Root, L2 and L3 indices of `va`. +const fn indices(va: u64) -> [usize; 3] { + let va = va & IAS_MASK; + [ + ((va >> 36) & 63) as usize, + ((va >> 25) & 2047) as usize, + ((va >> 14) & 2047) as usize, + ] +} + +/// Creates the adopted UAT over the ADT regions (step 2 above). +pub(crate) fn adopt( + dev: &AsahiDevice, + cfg: &'static super::Config, + adt: &super::adt::GpuAdt, +) -> Result> { + let geometry = mmu::UatGeometry { + ias: cfg.uat_ias, + oas: cfg.uat_oas, + }; + let regions = mmu::AdoptedRegions { + handoff: adt.handoff.clone(), + ttbs: adt.ttbs.clone(), + kernel_root: adt.tables.start, + }; + Ok(Arc::new( + mmu::Uat::new_adopted(dev, geometry, ®ions)?, + GFP_KERNEL, + )?) +} + +/// Runs `f` on the entries of the RAM table page at `pa`. +fn with_table( + pa: u64, + count: usize, + f: impl FnOnce(&[core::sync::atomic::AtomicU64]) -> R, +) -> Result { + // SAFETY: Every table walked here is a page the shared page-table code allocated in RAM + // (`Page::alloc_page`) and never frees while the firmware runs (tables are not freed on + // unmap, and these VMs are retained until reboot). + unsafe { pgtable::with_root_entries(pa, count, f) } +} + +/// Cleans `len` bytes of the RAM table page at `pa`, from entry `first`, to the point of +/// coherency. +fn clean_entries(pa: u64, first: usize, count: usize) -> Result { + if first + count > ENTRIES { + return Err(EINVAL); + } + with_table(pa, ENTRIES, |entries| { + let start = entries[first..].as_ptr() as usize; + // SAFETY: `start..start + count * 8` lies inside the borrowed table page; cleaning a + // cacheable range has no other effect. + unsafe { + bindings::dcache_clean_poc(start as _, (start + count * 8) as _); + } + }) +} + +/// Cleans a whole RAM table page to the point of coherency. +fn clean_page(pa: u64) -> Result { + clean_entries(pa, 0, ENTRIES) +} + +/// Reads entry `index` of the RAM table page at `pa`. +fn entry(pa: u64, index: usize) -> Result { + with_table(pa, index + 1, |entries| { + entries[index].load(Ordering::Acquire) + }) +} + +/// Reads the leaf word that translates `va` under the RAM root `root`, or `None` if a level is +/// missing. +pub(crate) fn read_leaf(root: u64, va: u64) -> Result> { + let [i0, i1, i2] = indices(va); + let l1 = entry(root, i0)?; + if l1 & VALID != VALID { + return Ok(None); + } + let l2 = entry(l1 & hw::PA_MASK, i1)?; + if l2 & VALID != VALID { + return Ok(None); + } + Ok(Some(entry(l2 & hw::PA_MASK, i2)?)) +} + +/// Cleans every table of the context-0 lower tree (the kernel lower VM) to the point of +/// coherency: its root, then each second-level and leaf table. Called before TTBAT context 0 +/// names the root and after every lower mapping. +pub(crate) fn clean_lower(uat: &mmu::Uat) -> Result { + let root = uat.kernel_lower_root(); + let mut tables = KVec::new(); + for i in 0..ROOT_ENTRIES { + let e = entry(root, i)?; + if e & VALID == VALID { + tables.push(e & hw::PA_MASK, GFP_KERNEL)?; + } + } + let mut leaves = KVec::new(); + for &l2 in tables.iter() { + with_table(l2, ENTRIES, |entries| -> Result { + for e in entries { + let e = e.load(Ordering::Acquire); + if e & VALID == VALID { + leaves.push(e & hw::PA_MASK, GFP_KERNEL)?; + } + } + Ok(()) + })??; + } + // Leaves first, then the tables naming them, then the root. + for &pa in Iterator::chain(leaves.iter(), tables.iter()) { + clean_page(pa)?; + } + clean_page(root)?; + mb(); + Ok(()) +} + +/// Invalidates every TLB entry of the GPU UAT (`TLBI VMALLE1OS`). +pub(crate) fn tlbi_all() { + crate::mem::sync(); + crate::mem::tlbi_all(); + crate::mem::sync(); +} + +/// The firmware's view of the host window (root entry 2 -> shared L2) and the PPL handoff. +pub(crate) struct Window { + /// PPL handoff page. + handoff: Mapping, + /// TTBAT page. + ttbs: Mapping, + /// First page of the firmware kernel root tables. + root: Mapping, + /// The shared L2 page. + shared_l2: Mapping, + /// The shared L2 entries last written, and a snapshot buffer of the shadow L2. + image: KVec, + snapshot: KVec, +} + +impl Window { + /// Maps the UAT handoff regions ([`Mapping::region`]). + pub(crate) fn new(adt: &super::adt::GpuAdt) -> Result { + Ok(Self { + handoff: Mapping::region(adt.handoff.start, hw::HANDOFF_SIZE as usize)?, + ttbs: Mapping::region(adt.ttbs.start, hw::TTBS_SIZE as usize)?, + root: Mapping::region(adt.tables.start, hw::PAGE as usize)?, + shared_l2: Mapping::region(adt.shared_l2.start, hw::SHARED_L2_SIZE as usize)?, + image: KVec::from_elem(0u64, ENTRIES, GFP_KERNEL)?, + snapshot: KVec::from_elem(0u64, ENTRIES, GFP_KERNEL)?, + }) + } + + /// Cold-start check: all 128 TTBAT words are zero. + pub(crate) fn ttbat_is_clear(&self) -> Result { + let t = self.ttbs.io(); + for i in 0..128 { + if t.try_read64(i * 8)? != 0 { + return Ok(false); + } + } + Ok(true) + } + + /// Takes the PPL lock: AP interest, then wait while the firmware holds it, yielding the turn + /// when the firmware asks for it; 100 ms. + pub(crate) fn ppl_lock(&self) -> Result { + let h = self.handoff.io(); + let start = Instant::::now(); + let expired = || start.elapsed() > Delta::from_millis(100); + h.try_write8(1, 0x10)?; + wmb(); + while h.try_read8(0x11)? != 0 { + if h.try_read32(0x14)? != 0 { + h.try_write8(0, 0x10)?; + wmb(); + while h.try_read32(0x14)? != 0 { + if expired() { + return Err(ETIMEDOUT); + } + } + h.try_write8(1, 0x10)?; + wmb(); + } + if expired() { + h.try_write8(0, 0x10)?; + return Err(ETIMEDOUT); + } + core::hint::spin_loop(); + } + rmb(); + Ok(()) + } + + /// Releases the PPL lock. + pub(crate) fn ppl_unlock(&self) -> Result { + let h = self.handoff.io(); + wmb(); + h.try_write32(1, 0x14)?; + h.try_write8(0, 0x10)?; + wmb(); + Ok(()) + } + + /// The PPL exchange and the exclusive startup epoch: host window and TTBAT context 0 (step 3 + /// above). + pub(crate) fn bootstrap(&mut self, dev: &device::Device, uat: &mmu::Uat) -> Result { + let h = self.handoff.io(); + // AP side of the PPL exchange; never overwrite firmware interest/magic. + h.try_write64(hw::PPL_MAGIC, 0x00)?; + h.try_write32(0xffffffff, 0x18)?; + for i in 0..=64 { + for w in 0..3 { + h.try_write64(0, 0x20 + 24 * i + 8 * w)?; + } + } + h.try_write64(0, 0x640)?; + wmb(); + // Wait up to 1 s for the firmware magic. + let start = Instant::::now(); + loop { + let magic = h.try_read64(0x08)?; + if magic == hw::PPL_MAGIC { + break; + } + if start.elapsed() > Delta::from_millis(1000) { + let magic = h.try_read64(0x08)?; + if magic == hw::PPL_MAGIC { + break; + } + dev_err!(dev, "PPL firmware magic missing: {:#x}\n", magic); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_micros(250)); + } + // The context-0 lower root is the kernel lower VM's RAM root, cleaned before TTBAT names + // it. + let lower = uat.kernel_lower_root(); + clean_lower(uat)?; + self.ppl_lock()?; + let result = self.epoch(lower); + self.ppl_unlock()?; + result?; + self.image.fill(0); + let r = self.root.io(); + dev_info!( + dev, + "MMU: initialized, root[0..2]={:#x} {:#x} {:#x}\n", + r.try_read64(0)?, + r.try_read64(8)?, + r.try_read64(16)? + ); + Ok(()) + } + + /// The writes of the startup epoch, under the PPL lock. + fn epoch(&self, lower: u64) -> Result { + let root = self.root.io(); + let l2 = self.shared_l2.io(); + let ttbs = self.ttbs.io(); + // Exclusive startup epoch: host entries 2.. of the upper root go first. + for i in 2..ROOT_ENTRIES { + root.try_write64(0, i * 8)?; + } + for i in 0..ENTRIES { + l2.try_write64(0, i * 8)?; + } + tlbi_all(); + root.try_write64(self.shared_l2.phys() | hw::pte::TABLE, WINDOW_INDEX * 8)?; + // TTBAT context0: owned lower root, upper root = pagetables base. + for i in 2..128 { + ttbs.try_write64(0, i * 8)?; + } + ttbs.try_write64(lower | 1, 0)?; + ttbs.try_write64(self.root.phys() | 1, 8)?; + Ok(()) + } + + /// The RAM L2 table of the shadow window, if anything is mapped in the window. + fn shadow_l2(uat: &mmu::Uat) -> Result> { + let e = entry(uat.kernel_window_root(), WINDOW_INDEX)?; + Ok((e & VALID == VALID).then_some(e & hw::PA_MASK)) + } + + /// Copies the shadow window's L2 entries into the shared L2 and cleans the leaves of `range` + /// to the point of coherency, in leaf tables the firmware can already reach. New leaf tables + /// are always cleaned whole before they are linked. + pub(crate) fn sync_range(&mut self, uat: &mmu::Uat, range: Range) -> Result { + if range.start < hw::HOST || range.end > hw::HOST + hw::HOST_SIZE || range.is_empty() { + return Err(EINVAL); + } + self.sync_inner(uat, Some(range)) + } + + fn sync_inner(&mut self, uat: &mmu::Uat, range: Option>) -> Result { + let Some(l2) = Self::shadow_l2(uat)? else { + return Ok(()); + }; + let snapshot = &mut self.snapshot; + with_table(l2, ENTRIES, |entries| { + for (out, e) in snapshot.iter_mut().zip(entries) { + *out = e.load(Ordering::Acquire); + } + })?; + let shared = self.shared_l2.io(); + for i in 0..ENTRIES { + let e = self.snapshot[i]; + if e & VALID != VALID { + if self.image[i] != 0 { + // Tables are never freed, so a linked entry cannot disappear. + return Err(EIO); + } + continue; + } + let l3 = e & hw::PA_MASK; + if self.image[i] != e { + // A new leaf table: complete it in memory before the firmware can walk into it. + clean_page(l3)?; + mb(); + shared.try_write64(e, i * 8)?; + self.image[i] = e; + continue; + } + match &range { + None => clean_page(l3)?, + Some(r) => { + let base = hw::HOST + ((i as u64) << 25); + let start = r.start.max(base); + let end = r.end.min(base + (1 << 25)); + if start < end { + let first = ((start - base) >> 14) as usize; + let last = ((end - 1 - base) >> 14) as usize; + clean_entries(l3, first, last - first + 1)?; + } + } + } + } + mb(); + Ok(()) + } + + /// Leaf tables linked into the shared L2. + pub(crate) fn l3_count(&self) -> usize { + self.image.iter().filter(|&&e| e != 0).count() + } +} diff --git a/drivers/gpu/drm/asahi/g15/vm.rs b/drivers/gpu/drm/asahi/g15/vm.rs new file mode 100644 index 00000000000000..41cc7e438a6d65 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/vm.rs @@ -0,0 +1,335 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! User VMs on G15. +//! +//! A user VM is a shared-layer [`mmu::Vm`] created by the adopted UAT, with tracked status +//! ([`mmu::Vm::with_tracked_status`]: VM_STATUS, mirror, job guards, deferred close; no residency +//! reclaim). At creation: +//! +//! - install the client aliases of the firmware objects marked for every user VM +//! ([`object::Objects::clients`]) as driver mappings at their fixed GVAs, and reserve +//! [`super::hw::client::CLIENT_APERTURE`], the pass-slot range and the PB page list +//! (`vm.install_driver_mappings`): user binds there fail (EINVAL). The aperture holds the +//! whole PB range, whose backing is mapped later, before the VM's first prefix is published +//! (`Firmware::map_pb`, counted in [`VmState::pb_chunks`]); +//! - bind it to an exclusive TTBAT slot ([`mmu::Uat::bind`]) for as long as its [`VmState`] +//! lives; at most [`super::hw::sizes::MAX_VMS`] such VMs (ENOSPC beyond, checked before +//! binding so the slot allocator never blocks). +//! +//! The [`VmState`] of a VM is shared by the [`Registry`] (while the client's VM handle exists), +//! the VM's queues and its jobs. It cannot be owned by the [`mmu::Vm`] itself: the slot binding +//! holds a `Vm` reference. The registry drops its reference once the shared lifetime reports the +//! client's handle closed ([`mmu::Vm::is_closed`]), at the next VM creation; the slot returns when +//! the last queue or job of the VM is gone (failed jobs are retained until reboot, and their +//! VM's slot with them). +//! +//! User page tables are cleaned to the point of coherency by the shared `pgtable.rs` (enabled by +//! the adopted UAT); user objects are prepared at creation (`gpu::Gpu::prepare_new_objects`). +//! User leaves use the shared GPU-shared protections (AttrIndex 2) for NC and WRITEBACK objects +//! alike. + +use core::ops::Range; +use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; +use kernel::{ + drm::gem::BaseObject, + new_mutex, + prelude::*, + sync::{aref::ARef, Arc, Mutex}, +}; + +use super::{hw, object, Gpu}; +use crate::{debug::*, g17::status::VmStatus, gem, mmu, module_parameters}; + +const DEBUG_CLASS: DebugFlags = DebugFlags::Mmu; + +/// Descriptor bits the shared page-table code adds to every user leaf: valid page, non-global. +const USER_LEAF_BITS: u64 = 0x803; + +/// A firmware object aliased at a fixed GVA in every user VM. +struct ClientAlias { + /// The object (a GEM kernel object); its first `size` bytes are mapped. + gem: ARef, + /// Page-aligned client GVA of the object's first page. + gva: u64, + /// Mapped size, whole pages. + size: usize, + /// The exact client leaf word ([`hw::pte::LEAF_NC`], [`hw::pte::LEAF_CACHED`] or + /// [`hw::pte::LEAF_PB_LIST`]). + leaf: u64, +} + +impl ClientAlias { + /// The client aliases of the firmware object allocator, validated: whole pages of the + /// object, inside a range reserved for the kernel, and a leaf word that round-trips exactly + /// through the shared page-table code. + fn collect(objects: &object::Objects) -> Result> { + let clients = objects.clients(); + let mut aliases = KVec::with_capacity(clients.len(), GFP_KERNEL)?; + for object in clients { + let Some((gva, leaf)) = object.client() else { + continue; + }; + let alias = ClientAlias { + gem: object.gem(), + gva, + size: object.bytes(), + leaf, + }; + alias.check()?; + aliases.push(alias, GFP_KERNEL)?; + } + Ok(aliases) + } + + fn check(&self) -> Result { + let end = self.gva.checked_add(self.size as u64).ok_or(EINVAL)?; + let leaf = mmu::Prot::from_pte(self.leaf).leaf_bits() | USER_LEAF_BITS; + if self.size == 0 + || (self.gva | self.size as u64) & mmu::UAT_PGMSK as u64 != 0 + || self.size > self.gem.size() + || leaf != self.leaf + || !reserved_ranges() + .iter() + .any(|range| range.start <= self.gva && end <= range.end) + { + pr_err!( + "G15: refusing client alias {:#x}+{:#x} leaf {:#x}\n", + self.gva, + self.size, + self.leaf + ); + return Err(EINVAL); + } + Ok(()) + } +} + +/// G15 state of one user VM, shared by the registry, its queues and its jobs. +pub(crate) struct VmState { + /// The `mmu::Vm` identifier (`Gpu::ids.vm`). + pub(crate) id: u64, + /// The VM's TTBAT slot (ASID), for the work images' context. + pub(crate) slot: u32, + /// The sticky status (shared with `file.rs`). + pub(crate) status: Arc, + /// The VM: span checks, stream reads and job guards. + pub(crate) vm: mmu::Vm, + /// The exclusive slot binding, released before the live count drops. + bind: Option, + registry: Arc, + /// PB backing chunks mapped into the VM, from the first (`Firmware::map_pb`); changed only + /// under the device lock. + pub(crate) pb_chunks: AtomicUsize, +} + +impl VmState { + /// Drops the registry's references to closed VMs (the queues call this when destroyed). + pub(crate) fn prune_registry(&self) { + self.registry.prune(); + } +} + +impl Drop for VmState { + fn drop(&mut self) { + mod_pr_debug!("G15: VM {} releases context {}\n", self.id, self.slot); + drop(self.bind.take()); + self.registry.live.fetch_sub(1, Ordering::AcqRel); + } +} + +/// Live-VM accounting and the VMs whose client handle is open. +#[pin_data] +pub(crate) struct Registry { + /// VMs whose client handle may still be open, oldest first. + #[pin] + vms: Mutex>>, + /// Live [`VmState`]s (each holds a TTBAT slot) plus reservations being created. + live: AtomicU32, +} + +/// A reserved place among the live VMs, released unless a [`VmState`] takes it over. +struct Reservation<'a>(Option<&'a Registry>); + +impl Reservation<'_> { + fn into_state(mut self) { + self.0 = None; + } +} + +impl Drop for Reservation<'_> { + fn drop(&mut self) { + if let Some(registry) = self.0 { + registry.live.fetch_sub(1, Ordering::AcqRel); + } + } +} + +impl Registry { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + vms <- new_mutex!(KVec::new(), "g15::Registry::vms"), + live: AtomicU32::new(0), + }), + GFP_KERNEL, + ) + } + + /// Reserves a place for a new VM after dropping the registry's references to closed VMs. + fn reserve(&self) -> Result> { + self.prune(); + // The shared slot allocator hands out a single slot with robust isolation. + let limit = if *module_parameters::robust_isolation.value() != 0 { + 1 + } else { + hw::sizes::MAX_VMS + }; + self.live + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |live| { + (live < limit).then_some(live + 1) + }) + .map_err(|_| ENOSPC)?; + Ok(Reservation(Some(self))) + } + + /// Drops the registry's references to VMs whose client handle is closed. Called on VM close + /// ([`closed`]), on queue destruction and before a new VM is created: a closed VM's page + /// tables, bound objects and TTBAT slot go as soon as its last queue or job is gone. + fn prune(&self) { + let mut closed = KVec::new(); + { + let mut vms = self.vms.lock(); + let mut index = 0; + while index < vms.len() { + if vms[index].vm.is_closed() && closed.push(vms[index].clone(), GFP_KERNEL).is_ok() + { + // Cannot fail: `index` is in range. + let _ = vms.remove(index); + } else { + index += 1; + } + } + } + // VM teardown may take GPUVM and reservation locks: not under the registry lock. + drop(closed); + } + + /// The driver mappings and reserved ranges of a new VM. + fn driver_mappings( + vm: &mmu::Vm, + aliases: KVec, + ) -> Result<(KVec, KVec>)> { + let mut mappings = KVec::with_capacity(aliases.len(), GFP_KERNEL)?; + for alias in aliases { + mappings.push( + vm.map_at( + alias.gva, + alias.size, + &alias.gem, + mmu::Prot::from_pte(alias.leaf), + false, + )?, + GFP_KERNEL, + )?; + } + let ranges = reserved_ranges(); + let mut reserved = KVec::with_capacity(ranges.len(), GFP_KERNEL)?; + for range in ranges { + reserved.push(range, GFP_KERNEL)?; + } + Ok((mappings, reserved)) + } + + /// The state of a VM whose client handle is open. + pub(crate) fn find(&self, vm: &mmu::Vm) -> Result> { + let id = vm.id(); + self.vms + .lock() + .iter() + .find(|state| state.id == id) + .cloned() + .ok_or(ENOENT) + } + + /// Latches `error` on every VM whose client handle is open. The fail-stop path calls it under + /// the device lock. + pub(crate) fn fail_all(&self, error: Error) { + for state in self.vms.lock().iter() { + state.status.record(error); + } + } +} + +/// User VA ranges that belong to the kernel in every VM: the client aperture, the render pass +/// slots and the PB page list (the last two need 32-bit compact pointers). Every client alias +/// lies inside one of them ([`ClientAlias::check`]). +pub(crate) fn reserved_ranges() -> [Range; 3] { + use hw::client::*; + [ + CLIENT_APERTURE, + PRE0_PAGE..PRE0_PAGE + hw::sizes::RENDER_SLOTS as u64 * PASS_STRIDE, + PB_PAGE_LIST..PB_PAGE_LIST + PB_PAGE_LIST_SIZE, + ] +} + +/// Creates a user VM (`gpu::Gpu::new_vm`). +pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range) -> Result { + if gpu.shared.crashed.load(Ordering::Acquire) { + return Err(EIO); + } + // Snapshot the registry and the client aliases; map them without the device lock. + let (registry, aliases) = { + let state = gpu.shared.state.lock(); + let firmware = state.as_ref().ok_or(ENODEV)?; + ( + firmware.vms.clone(), + ClientAlias::collect(&firmware.objects)?, + ) + }; + let reservation = registry.reserve()?; + let id = gpu.ids.vm.next(); + let vm = gpu.uat.new_vm(id, kernel_range)?.with_tracked_status()?; + let status = vm.status().ok_or(EINVAL)?.clone(); + let (mappings, reserved) = Registry::driver_mappings(&vm, aliases)?; + vm.install_driver_mappings(mappings, reserved)?; + // The context names the root only now: everything above is already visible to the walker. + let bind = gpu.uat.bind(&vm)?; + let slot = bind.slot(); + // From here on the state (even one that fails to allocate) gives the place back. + reservation.into_state(); + let state = Arc::new( + VmState { + id, + slot, + status, + vm: vm.clone(), + bind: Some(bind), + registry: registry.clone(), + pb_chunks: AtomicUsize::new(0), + }, + GFP_KERNEL, + )?; + registry.vms.lock().push(state, GFP_KERNEL)?; + mod_pr_debug!("G15: VM {} context {}\n", id, slot); + Ok(vm) +} + +/// A client's VM handle is gone (`gpu::Gpu::vm_closed`): drop the registry's references to +/// closed VMs now, outside the device lock, instead of at the next VM creation. +pub(crate) fn closed(gpu: &Gpu) { + let registry = gpu + .shared + .state + .lock() + .as_ref() + .map(|firmware| firmware.vms.clone()); + if let Some(registry) = registry { + registry.prune(); + } +} + +/// The state of a VM for a new queue. +pub(crate) fn lookup(gpu: &Gpu, vm: &mmu::Vm) -> Result> { + let registry = gpu.shared.state.lock().as_ref().ok_or(ENODEV)?.vms.clone(); + registry.find(vm) +} diff --git a/drivers/gpu/drm/asahi/g15/wire.rs b/drivers/gpu/drm/asahi/g15/wire.rs new file mode 100644 index 00000000000000..6fbb360e11a610 --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/wire.rs @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Private G15 wire for Mesa 751 / public SF `asahi_m3_drm.h`. +//! +//! G15 modules that decode commands or advertise features do +//! `use crate::g15::wire as uapi`. Normal and G17 code keep `kernel::uapi`. +//! This module is not installed UAPI and is not a bindgen input. +//! `include/uapi/drm/asahi_drm.h` stays the canonical header: render 448 bytes +//! with `prior_vdm` at 320, compute 200 bytes with `scs_layout` at 128. +//! +//! Native feature numbers, matching that Mesa header. Canonical bits 10..15 +//! are a different assignment; Mesa rejects any of them (`0xfc00`). +//! +//! | bit | native name | canonical name at the same bit | +//! | 0 | SOFT_FAULTS | SOFT_FAULTS | +//! | 1 | VM_STATUS | VM_STATUS | +//! | 2 | INDEPENDENT_QUEUES | INDEPENDENT_QUEUES | +//! | 3 | PER_COMMAND_INPUT_SYNCS | SCHEDULED_QUEUES | +//! | 4 | VM_STATUS_MIRROR | RENDER_TIMESTAMP_COPIES | +//! | 5 | EXACT_PRIOR_BARRIERS | COMPUTE_TIMESTAMP_COPIES | +//! | 6 | FEW_PRIMITIVES | FRAGMENT_DEPENDENCY | +//! | 7 | FRAGMENT_BARRIERS | FRAGMENT_DEPENDENCY_COMPUTE | +//! | 8 | RENDER_RAY_QUERY | COMPUTE_WIDE_VISIBILITY | + +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] + +use core::mem::{offset_of, size_of}; + +use kernel::uapi; + +use crate::util::AnyBitPattern; + +/// Canonical bits 10..15. A G15 feature word with any of these set is the +/// maintained assignment, which Mesa 751 refuses for chip 0x6030 and 0x6031. +pub(crate) const LEGACY_FEATURE_MASK: u64 = 0xfc00; + +// Bindgen names, so `use crate::g15::wire as uapi` still matches params.rs. +// Scoped to these nine items; the rest of the module stays under the lint. +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_SOFT_FAULTS: u64 = 1 << 0; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS: u64 = 1 << 1; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES: u64 = 1 << 2; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS: u64 = 1 << 3; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS_MIRROR: u64 = 1 << 4; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS: u64 = 1 << 5; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES: u64 = 1 << 6; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS: u64 = 1 << 7; +#[allow(non_upper_case_globals)] +pub(crate) const drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_RAY_QUERY: u64 = 1 << 8; + +/// What `Gpu::feature_flags` returns for G15. This replaces the shared default +/// (canonical VM_STATUS | VM_STATUS_MIRROR | INDEPENDENT_QUEUES | optional +/// SOFT_FAULTS). Mirror is native bit 4. Soft faults, few-primitives and ray +/// query are not advertised. Command bits 3, 5 and 7 stay in `params::fill` +/// via this module's names, so this constant does not include them. +pub(crate) const SHARED_FEATURE_FLAGS: u64 = drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS + | drm_asahi_feature_DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES + | drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS_MIRROR; + +/// Command-feature bits `params::fill` ORs. Bit 7 only while early tiling is on. +pub(crate) const fn command_feature_flags(early_tiling: bool) -> u64 { + let mut flags = drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS + | drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS; + if early_tiling { + flags |= drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS; + } + flags +} + +/// Full G15 GET_PARAMS word: `0x3e`, or `0xbe` with early tiling. +pub(crate) const fn feature_word(early_tiling: bool) -> u64 { + SHARED_FEATURE_FLAGS | command_feature_flags(early_tiling) +} + +/// Ioctl types and constants whose layout and values match the canonical header. +/// Render flags used by G15 are the same numbers on both headers (1<<0, 1<<1, +/// 1<<2, 1<<4, 1<<18, 1<<20). Feature constants are not reexported. +pub(crate) use uapi::{ + drm_asahi_attachment, drm_asahi_bg_eot, drm_asahi_cmd_header, drm_asahi_cmd_type_DRM_ASAHI_CMD_COMPUTE, + drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER, drm_asahi_cmd_type_DRM_ASAHI_SET_COMPUTE_ATTACHMENTS, + drm_asahi_cmd_type_DRM_ASAHI_SET_FRAGMENT_ATTACHMENTS, + drm_asahi_cmd_type_DRM_ASAHI_SET_VERTEX_ATTACHMENTS, drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_LEGACY, + drm_asahi_helper_program, drm_asahi_params_global, drm_asahi_queue_limits, + drm_asahi_render_flags_DRM_ASAHI_RENDER_DBIAS_IS_INT, + drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS, + drm_asahi_render_flags_DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING, + drm_asahi_render_flags_DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES, + drm_asahi_render_flags_DRM_ASAHI_RENDER_RSRC_SPEC_HI, + drm_asahi_render_flags_DRM_ASAHI_RENDER_VERTEX_SCRATCH, drm_asahi_timestamp, + drm_asahi_timestamps, drm_asahi_zls_buffer, DRM_ASAHI_BARRIER_NONE, +}; + +/// Native render command. 384 bytes. The first 256 match the canonical prefix +/// through `bg_partial_rsrc_spec_hi` (offset 252). `prior_vdm` is at 256 and +/// `prior_cdm` at 264. `ray_query` is at 272 and is not advertised: a nonzero +/// byte from there on is rejected by `command::check_stream`. A 256-byte packet +/// zero-fills the priors; a 272-byte packet zero-fills `ray_query`. +#[repr(C)] +#[derive(Copy, Clone, Default)] +pub(crate) struct drm_asahi_cmd_render { + pub flags: u32, + pub isp_zls_pixels: u32, + pub vdm_ctrl_stream_base: u64, + pub vertex_helper: drm_asahi_helper_program, + pub fragment_helper: drm_asahi_helper_program, + pub isp_scissor_base: u64, + pub isp_dbias_base: u64, + pub isp_oclqry_base: u64, + pub depth: drm_asahi_zls_buffer, + pub stencil: drm_asahi_zls_buffer, + pub zls_ctrl: u64, + pub ppp_multisamplectl: u64, + pub sampler_heap: u64, + pub ppp_ctrl: u32, + pub width_px: u16, + pub height_px: u16, + pub layers: u16, + pub sampler_count: u16, + pub utile_width_px: u8, + pub utile_height_px: u8, + pub samples: u8, + pub sample_size_B: u8, + pub isp_merge_upper_x: u32, + pub isp_merge_upper_y: u32, + pub bg: drm_asahi_bg_eot, + pub eot: drm_asahi_bg_eot, + pub partial_bg: drm_asahi_bg_eot, + pub partial_eot: drm_asahi_bg_eot, + pub isp_bgobjdepth: u32, + pub isp_bgobjvals: u32, + pub ts_vtx: drm_asahi_timestamps, + pub ts_frag: drm_asahi_timestamps, + pub bg_eot_rsrc_spec_hi: u32, + pub bg_eot_partial_rsrc_spec_hi: u32, + pub bg_rsrc_spec_hi: u32, + pub bg_partial_rsrc_spec_hi: u32, + pub prior_vdm: u64, + pub prior_cdm: u64, + pub ray_query: [uapi::drm_asahi_render_ray_query_stage; 2], +} + +/// Native compute command. 136 bytes. The 64-byte prefix ends at `ts`. +/// `scs_layout` is at 64, `prior_vdm` at 72, `prior_cdm` at 80. G15 rejects a +/// nonzero `scs_layout` and the intersection tail; those fields still sit at +/// the native offsets so a 136-byte packet is not read as canonical scratch. +#[repr(C)] +#[derive(Copy, Clone, Default)] +pub(crate) struct drm_asahi_cmd_compute { + pub flags: u32, + pub sampler_count: u32, + pub cdm_ctrl_stream_base: u64, + pub cdm_ctrl_stream_end: u64, + pub sampler_heap: u64, + pub helper: drm_asahi_helper_program, + pub ts: drm_asahi_timestamps, + pub scs_layout: u64, + pub prior_vdm: u64, + pub prior_cdm: u64, + pub cdm_auxiliary_allocation: u32, + pub reserved: u32, + pub intersection_pool: u64, + pub intersection_pool_bytes: u64, + pub intersection_first: u32, + pub intersection_count: u32, + pub intersection_default_program: u64, + pub intersection_default_control: u64, +} + +// SAFETY: Every field is an integer or a `repr(C)` UAPI struct of integers. +// `command::payload` zero-fills a short record and rejects a nonzero tail. +unsafe impl AnyBitPattern for drm_asahi_cmd_render {} +// SAFETY: Same as `drm_asahi_cmd_render`. +unsafe impl AnyBitPattern for drm_asahi_cmd_compute {} + +const _: () = { + assert!(size_of::() == 448); + assert!(offset_of!(uapi::drm_asahi_cmd_render, prior_vdm) == 320); + assert!(size_of::() == 200); + assert!(offset_of!(uapi::drm_asahi_cmd_compute, scs_layout) == 128); + + assert!(size_of::() == 384); + assert!(offset_of!(drm_asahi_cmd_render, bg_partial_rsrc_spec_hi) == 252); + assert!(offset_of!(drm_asahi_cmd_render, prior_vdm) == 256); + assert!(offset_of!(drm_asahi_cmd_render, prior_cdm) == 264); + assert!(offset_of!(drm_asahi_cmd_render, ray_query) == 272); + + assert!(size_of::() == 136); + assert!(offset_of!(drm_asahi_cmd_compute, scs_layout) == 64); + assert!(offset_of!(drm_asahi_cmd_compute, prior_vdm) == 72); + assert!(offset_of!(drm_asahi_cmd_compute, prior_cdm) == 80); + assert!(offset_of!(drm_asahi_cmd_compute, cdm_auxiliary_allocation) == 88); + assert!(offset_of!(drm_asahi_cmd_compute, intersection_default_control) == 128); + + assert!(SHARED_FEATURE_FLAGS == 0x16); + assert!(command_feature_flags(false) == 0x28); + assert!(feature_word(false) == 0x3e); + assert!(feature_word(true) == 0xbe); + assert!(feature_word(true) & LEGACY_FEATURE_MASK == 0); + assert!(drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_RAY_QUERY == 1 << 8); + assert!(drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES == 1 << 6); + assert!(drm_asahi_feature_DRM_ASAHI_FEATURE_SOFT_FAULTS == 1); +}; diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 6ca0398abd2e27..9da90d2b0843ab 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -24,6 +24,8 @@ pub(crate) use command::Attachments; mod completion; pub(crate) mod context; mod dependency; +#[cfg(CONFIG_DRM_ASAHI_G15)] +pub(crate) use dependency::inherited_error; mod event; mod feed; mod fence; diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index 2266d18e9c85f2..3bcf8a9692dcca 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -385,3 +385,57 @@ pub(crate) fn madvise(gem: &Object, dontneed: bool) -> Result { } Ok(u32::from(gem.madvise(i32::from(dontneed)))) } + +/// Populates and pins a new user object through its DMA mapping, before any CPU view exists. +/// +/// On a device that is not DMA-coherent, the DMA mapping cleans the cacheable kernel alias of the +/// freshly zeroed pages to the point of coherency, so that no dirty line can later overwrite data +/// written through a write-combined view. The pin keeps reclaim from creating a new cacheable +/// alias. Only used when the GPU asks for it ([`crate::gpu::Gpu::prepare_new_objects`]). +/// +/// The DMA mapping only cleans if the device is not marked DMA-coherent (G15's synthesized node +/// has no `dma-coherent`). Should it ever be marked so, the pages are cleaned here instead. +#[cfg(CONFIG_DRM_ASAHI_G15)] +pub(crate) fn prepare_new_object(gem: &Object) -> Result { + // SAFETY: G15 objects belong to the retained bound platform device; user object + // creation occurs only after registration and before a file can outlive its device. + let dev: &kernel::device::Device = gem.dev().as_ref().as_ref(); + let sgt = held_sg_table(gem, unsafe { dev.as_bound() })?; + // SAFETY: The device outlives its GEM objects; the flag is fixed when the device is probed. + if !unsafe { asahi_g15_dma_coherent(dev.as_raw().cast()) } { + return Ok(()); + } + static WARNED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + dev_warn!( + dev, + "GPU marked DMA-coherent: cleaning new objects to the point of coherency explicitly\n" + ); + } + let page_size = kernel::page::PAGE_SIZE; + for segment in sgt.iter() { + // Without an IOMMU in front of the GPU, its DMA addresses are physical addresses. + let start = segment.dma_address() as kernel::addr::PhysicalAddr; + let len = segment.dma_len() as usize; + let mut offset = 0; + while offset < len { + let phys = start + offset as kernel::addr::PhysicalAddr; + // SAFETY: The pinned SG table keeps these shmem pages allocated. + let page = unsafe { kernel::page::Page::borrow_phys(&phys) }.ok_or(EIO)?; + page.with_pointer_into_page(0, page_size, |p| { + crate::pgtable::clean_poc(p, page_size); + Ok(()) + })?; + offset += page_size; + } + } + crate::pgtable::poc_barrier(); + Ok(()) +} + + +#[cfg(CONFIG_DRM_ASAHI_G15)] +extern "C" { fn asahi_g15_dma_coherent(dev: *mut core::ffi::c_void) -> bool; } + +#[cfg(not(CONFIG_DRM_ASAHI_G15))] +pub(crate) fn prepare_new_object(_gem: &Object) -> Result { Err(EINVAL) } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index ed54c350d7dbc2..90bb25451019e7 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -11,6 +11,7 @@ //! are unified, so that the top level of the driver itself (in `driver`) does not have to concern //! itself with version dependence. +use crate::module_parameters; use core::any::Any; use core::ops::Range; use core::slice; @@ -292,6 +293,21 @@ pub(crate) trait Gpu: Send + Sync { fn queue_limits(&self) -> Option { None } + /// Shared GET_PARAMS additions, using this backend's feature-number assignments. + fn feature_flags(&self) -> u64 { + let mut flags = 0; + if self.supports_vm_status() { + flags |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 + | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS_MIRROR as u64; + } + if self.queue_limits().is_some() { + flags |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES as u64; + } + if self.soft_faults() && *module_parameters::fault_control.value() == 0xb { + flags |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SOFT_FAULTS as u64; + } + flags + } /// Temporary capacity hint and validity in milliseconds for subsequent syncobj waits. fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { None @@ -300,6 +316,28 @@ pub(crate) trait Gpu: Send + Sync { fn base_clock_hz(&self) -> u32; /// Return the GPU address space geometry. fn uat_geometry(&self) -> mmu::UatGeometry; + /// Backend-specific user address aperture; other GPUs keep their geometry's range. + fn user_range(&self) -> Range { + self.uat_geometry().user_usable_range() + } + /// Use tracked command publication and sticky VM status on this backend. + fn tracked_submission(&self) -> bool { + false + } + /// Whether faults may be reported as recoverable to userspace. + fn soft_faults(&self) -> bool { + true + } + /// Populate and clean fresh object backing before any WC CPU mapping. + fn prepare_new_objects(&self) -> bool { + false + } + /// Optional backend-specific upper bound for a VM_BIND batch. + fn bind_batch_limit(&self) -> Option { + None + } + /// A userspace VM handle was closed; release backend-only registry references. + fn vm_closed(&self) {} /// Create a new `Vm` with the given range reserved for kernel-managed objects. fn new_vm(&self, kernel_range: Range) -> Result; /// Create a new user command queue. diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 4ea797d398a8b1..e868e30baca4c9 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -1475,6 +1475,8 @@ unsafe impl Send for UatShared {} #[pin_data] struct UatInner { firmware: UatFirmware, + #[cfg(CONFIG_DRM_ASAHI_G15)] + clean_poc: bool, #[pin] shared: Mutex, #[pin] @@ -1661,6 +1663,15 @@ impl Vm { UatPageTable::new(geometry.ias, geometry.oas)? }; + #[cfg(CONFIG_DRM_ASAHI_G15)] + let page_table = { + let mut page_table = page_table; + if uat_inner.clean_poc { + page_table.enable_clean_poc()?; + } + page_table + }; + let (va_range, gpuvm_range) = if is_kernel { (geometry.kernel_range(), kernel_range.clone()) } else { @@ -1737,6 +1748,63 @@ impl Vm { Ok(self) } + /// Attach a status and job lifetime tracking before sharing a newly created user VM with + /// queues, without the G17 canonical context views, shared-object footprints and idle + /// residency reclaim of [`Self::with_status`]. Used by G15, whose user objects stay pinned. + #[cfg(CONFIG_DRM_ASAHI_G15)] + pub(crate) fn with_tracked_status(mut self) -> Result { + self.status = Some(Arc::pin_init(crate::g17::status::VmStatus::new(), GFP_KERNEL)?); + self.lifetime = Some(lifetime::VmLifetime::new()?); + Ok(self) + } + + /// The identifier this VM was created with (G15 keeps per-VM state keyed by it). + #[cfg(CONFIG_DRM_ASAHI_G15)] + pub(crate) fn id(&self) -> u64 { + self.id + } + + /// Copies `buf.len()` bytes of GPU-readable memory at `va` of this VM into `buf`, for admission + /// checks of streams the GPU will execute (G15 stream gates). + /// + /// Every page must be mapped GPU-readable and be RAM; otherwise EFAULT. The lines are cleaned + /// and invalidated to the point of coherency first (never only invalidated: CPU-written lines + /// may be dirty), so the copy sees what the GPU or a write-combined CPU view stored. The + /// mappings cannot change during the copy (GPUVM exec lock). + #[cfg(CONFIG_DRM_ASAHI_G15)] + pub(crate) fn read_user(&self, va: u64, buf: &mut [u8]) -> Result { + let mut inner = lock_vm(&self.gpuvm, None, false)?; + let mut done = 0usize; + while done < buf.len() { + let address = va.checked_add(done as u64).ok_or(EFAULT)?; + let page = address & !(UAT_PGMSK as u64); + let within = (address - page) as usize; + let count = (buf.len() - done).min(UAT_PGSZ - within); + if page < inner.va_range.start || page >= inner.va_range.end { + return Err(EFAULT); + } + let leaf = inner.page_table.leaf_entry(page).map_err(|_| EFAULT)?; + if !Prot::from_pte(leaf).allows_gpu(true, false) { + return Err(EFAULT); + } + let phys = inner.page_table.translate_iova(page).map_err(|_| EFAULT)?; + // SAFETY: `phys` is checked to be a RAM page; it stays mapped (and its backing pinned) + // while the exec lock is held, and is only read here. + let ram = unsafe { kernel::page::Page::borrow_phys(&phys) }.ok_or(EFAULT)?; + let target = &mut buf[done..done + count]; + ram.with_pointer_into_page(within, count, |p| { + pgtable::clean_invalidate_poc(p, count); + pgtable::poc_barrier(); + // SAFETY: with_pointer_into_page() checked that `count` bytes at `p` are inside the + // page, and `target` holds exactly `count` bytes. + unsafe { core::ptr::copy_nonoverlapping(p, target.as_mut_ptr(), count) }; + Ok(()) + })?; + done += count; + } + Ok(()) + } + /// Status shared by every queue using this VM, if enabled by its GPU. pub(crate) fn status(&self) -> Option<&Arc> { self.status.as_ref() @@ -2348,7 +2416,149 @@ impl Drop for VmInner { } } +/// Physical regions of a UAT whose handoff the generation has already established itself +/// ([`Uat::new_adopted`]). None of them needs to be in the kernel linear map. +#[cfg(CONFIG_DRM_ASAHI_G15)] +pub(crate) struct AdoptedRegions { + /// The handoff region (PPL magic, lock and flush requests). + pub(crate) handoff: Range, + /// The TTBAT. + pub(crate) ttbs: Range, + /// The firmware kernel (upper) root, which every user context names as its upper half. + pub(crate) kernel_root: PhysicalAddr, +} + impl Uat { + #[cfg(CONFIG_DRM_ASAHI_G15)] + /// Map a region given by its physical range, write-combined. + fn map_physical(range: &Range, min_size: usize) -> Result { + let size: usize = (range.end.checked_sub(range.start).ok_or(EINVAL)?).try_into()?; + if size < min_size || (range.start | range.end) & (UAT_PGMSK as PhysicalAddr) != 0 { + return Err(EINVAL); + } + // SAFETY: All-zero is a valid `struct resource` (no name, parent or children). + let mut raw: kernel::bindings::resource = unsafe { core::mem::zeroed() }; + raw.start = range.start; + raw.end = range.end - 1; + raw.flags = kernel::bindings::IORESOURCE_MEM as _; + // SAFETY: `Resource` is a transparent wrapper around `Opaque`, and + // `raw` describes a valid memory range. + let res: io::resource::Resource = + unsafe { core::mem::transmute(kernel::types::Opaque::new(raw)) }; + // A carveout outside System RAM is mapped write-combined; a reserved-memory region + // inside System RAM (mapped by the kernel) through the kernel's own mapping, as + // `map_region` does for the other generations. + let mode = crate::g15::memory_mode(range.start, size as u64)?; + let ram = mode == kernel::bindings::MEMREMAP_WB as u32; + let flags = if ram { + io::mem::MemFlag::WB + } else { + io::mem::MemFlag::WC + }; + // SAFETY: The UAT regions are only accessed through this mapping by the CPU; the GPU + // reaches them through its own translation. + let map = unsafe { io::mem::Mem::try_new(res, flags.into()) }?; + Ok(UatRegion { + base: range.start, + map, + }) + } + + #[cfg(CONFIG_DRM_ASAHI_G15)] + /// Creates a `Uat` for a handoff that the caller establishes itself (G15). + /// + /// This only maps the handoff and the TTBAT (write-combined); neither is written here. The + /// caller performs the PPL magic exchange and installs TTBAT context 0 before any user `Vm` is + /// bound, naming [`Self::kernel_lower_vm`] as its lower half and `regions.kernel_root` as its + /// upper half. Bound user `Vm`s also name `regions.kernel_root` as their upper half. + /// + /// The firmware kernel root is not in the kernel linear map, so the driver cannot walk it. + /// [`Self::kernel_vm`] instead manages the driver window (the kernel range) below a + /// driver-owned shadow root that no context names: the caller links the window's second-level + /// entries ([`Self::kernel_window_root`]) into the firmware's own table for that window after + /// mapping and before the firmware uses the new addresses. Page tables are never freed on + /// unmap, so linked entries stay valid. + pub(crate) fn new_adopted( + dev: &driver::AsahiDrmDevice, + geometry: UatGeometry, + regions: &AdoptedRegions, + ) -> Result { + let handoff_rgn = Self::map_physical(®ions.handoff, HANDOFF_SIZE)?; + let ttbs_rgn = Self::map_physical(®ions.ttbs, SLOTS_SIZE)?; + + // SAFETY: The Handoff struct layout matches the firmware's view of memory at this + // address, and the region is at least large enough per the check above. + let handoff = unsafe { &(handoff_rgn.map.ptr() as *mut Handoff).as_ref().unwrap() }; + + let inner = Arc::pin_init( + try_pin_init!(UatInner { + firmware: UatFirmware::Handoff, + // The G15 UAT walker does not snoop the CPU caches. + clean_poc: true, + handoff_flush <- pin_init::pin_init_array_from_fn(|i| { + new_mutex!(HandoffFlush(&handoff.flush[i]), "handoff_flush") + }), + shared <- new_mutex!( + UatShared { + kernel_ttb1: regions.kernel_root, + execution_contexts: !EXECUTION_CONTEXT_MASK, + context_generations: [0; UAT_NUM_CTX], + secondary_ttb1: None, + map_kernel_to_user: true, + handoff_rgn, + ttbs_rgn, + }, + "uat_shared" + ), + }), + GFP_KERNEL, + )?; + + // The shadow root is retained for the lifetime of the driver window it describes. + let shadow = kernel::page::Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; + let shadow_root = kernel::page::Page::into_phys(shadow); + + let kernel_lower_vm = + Vm::new(dev.into(), inner.clone(), geometry.user_range(), geometry, None, 1)?; + let kernel_vm = Vm::new( + dev.into(), + inner.clone(), + geometry.kernel_range(), + geometry, + Some(shadow_root), + 0, + )?; + + Ok(Self { + dev: dev.into(), + geometry, + kernel_vm, + kernel_lower_vm, + inner, + slots: slotalloc::SlotAllocator::new( + UAT_USER_CTX as u32, + (), + |_inner, _slot| Some(SlotInner()), + c_str!("Uat::SlotAllocator"), + static_lock_class!(), + static_lock_class!(), + )?, + }) + } + + #[cfg(CONFIG_DRM_ASAHI_G15)] + /// Root of the kernel lower `Vm`, for TTBAT context 0 of an adopted handoff. + pub(crate) fn kernel_lower_root(&self) -> PhysicalAddr { + self.kernel_lower_vm.ttb() + } + + #[cfg(CONFIG_DRM_ASAHI_G15)] + /// Root whose driver-window entry names the second-level table of [`Self::kernel_vm`]'s + /// driver window. With [`Self::new_adopted`] this is the shadow root that no context names. + pub(crate) fn kernel_window_root(&self) -> PhysicalAddr { + self.kernel_vm.ttb() + } + /// Map a bootloader-preallocated memory region fn map_region( dev: &device::Device, @@ -2688,6 +2898,8 @@ impl Uat { Arc::pin_init( try_pin_init!(UatInner { firmware, + #[cfg(CONFIG_DRM_ASAHI_G15)] + clean_poc: false, handoff_flush <- pin_init::pin_init_array_from_fn(|i| { new_mutex!(HandoffFlush(&handoff.flush[i]), "handoff_flush") }), diff --git a/drivers/gpu/drm/asahi/mmu/lifetime.rs b/drivers/gpu/drm/asahi/mmu/lifetime.rs index 98006b9459c98b..4b881d6f1ebfd5 100644 --- a/drivers/gpu/drm/asahi/mmu/lifetime.rs +++ b/drivers/gpu/drm/asahi/mmu/lifetime.rs @@ -333,6 +333,12 @@ impl Vm { drop(previous); } + /// Whether userspace has permanently closed this VM's map admission. + #[cfg(CONFIG_DRM_ASAHI_G15)] + pub(crate) fn is_closed(&self) -> bool { + self.lifetime.as_ref().is_some_and(|lifetime| lifetime.state.lock().closed) + } + /// Tests mappings and reservations which userspace must never replace. pub(crate) fn driver_range_overlaps(&self, range: Range) -> bool { let Some(lifetime) = self.lifetime.as_ref() else { diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index af5fdbb5dc27b1..1655c1183438bf 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -53,6 +53,75 @@ const UAT_LEVELS: usize = 3; /// Number of address bits below the index of a top-level page table entry. pub(crate) const UAT_TOP_LEVEL_SHIFT: usize = UAT_PGBIT + (UAT_LEVELS - 1) * UAT_LVBIT; +/// Size of the smallest CPU data cache line (`CTR_EL0.DminLine`). +#[inline(always)] +fn dcache_line_size() -> usize { + let ctr: u64; + // SAFETY: CTR_EL0 is readable at EL1 and reading it has no side effects. + unsafe { + core::arch::asm!( + "mrs {ctr}, ctr_el0", + ctr = out(reg) ctr, + options(nomem, nostack, preserves_flags) + ) + }; + 4 << ((ctr >> 16) & 0xf) +} + +/// Cleans the CPU data cache lines covering `len` bytes at `ptr` to the point of coherency, for an +/// agent that does not snoop the CPU caches. [`poc_barrier`] completes the maintenance. +pub(crate) fn clean_poc(ptr: *const u8, len: usize) { + if len == 0 { + return; + } + let line = dcache_line_size(); + let end = ptr as usize + len; + let mut addr = ptr as usize & !(line - 1); + while addr < end { + // SAFETY: Cleaning a cache line of a mapped kernel address writes dirty data back without + // changing memory contents. The asm is a compiler barrier, so earlier stores are emitted + // first, and the architecture orders them with the clean of the same line. + unsafe { + core::arch::asm!( + "dc cvac, {addr}", + addr = in(reg) addr, + options(nostack, preserves_flags) + ) + }; + addr += line; + } +} + +/// Cleans and invalidates the CPU data cache lines covering `len` bytes at `ptr` to the point of +/// coherency, so that later CPU reads observe what a non-snooping agent wrote. Lines the CPU wrote +/// are written back first. [`poc_barrier`] completes the maintenance. +#[cfg(CONFIG_DRM_ASAHI_G15)] +pub(crate) fn clean_invalidate_poc(ptr: *const u8, len: usize) { + if len == 0 { + return; + } + let line = dcache_line_size(); + let end = ptr as usize + len; + let mut addr = ptr as usize & !(line - 1); + while addr < end { + // SAFETY: Clean+invalidate of a mapped kernel address never discards dirty data. + unsafe { + core::arch::asm!( + "dc civac, {addr}", + addr = in(reg) addr, + options(nostack, preserves_flags) + ) + }; + addr += line; + } +} + +/// Completes earlier point-of-coherency maintenance for the outer shareable domain (`dsb osh`). +pub(crate) fn poc_barrier() { + // SAFETY: Barriers are always safe. + unsafe { core::arch::asm!("dsb osh", options(nostack, preserves_flags)) }; +} + /// Runs `f` on the first `count` top-level entries of the root page table at `ttb`. /// /// # Safety @@ -184,6 +253,11 @@ impl Prot { Self { memattr, ..*self } } + #[cfg(CONFIG_DRM_ASAHI_G15)] + pub(crate) const fn leaf_bits(&self) -> u64 { + self.as_pte() + } + const fn as_pte(&self) -> u64 { (self.ap as u64) << UAT_AP_SHIFT | (self.high_bits as u64) << UAT_HIGH_BITS_SHIFT @@ -229,6 +303,10 @@ pub(crate) struct UatPageTable { va_range: Range, ias_mask: u64, oas_mask: u64, + /// Clean new tables and changed entries to the point of coherency, for a UAT walker that does + /// not snoop the CPU caches ([`Self::enable_clean_poc`]). + #[cfg(CONFIG_DRM_ASAHI_G15)] + clean_poc: bool, } impl UatPageTable { @@ -243,9 +321,43 @@ impl UatPageTable { va_range: 0..(1u64 << ias), ias_mask: (1u64 << ias) - 1, oas_mask: (1u64 << oas) - 1, + #[cfg(CONFIG_DRM_ASAHI_G15)] + clean_poc: false, }) } + /// Makes every later change of this page table visible to a UAT walker that does not snoop the + /// CPU caches (G15), and cleans the root, which was zeroed through the cacheable linear map. + /// + /// From now on, a new table page is cleaned before its parent descriptor names it, a changed + /// table or leaf descriptor is cleaned after the store, and every mutating walk ends with a + /// `dsb osh`. Call it before anything is mapped and before any context names the root. + #[cfg(CONFIG_DRM_ASAHI_G15)] + pub(crate) fn enable_clean_poc(&mut self) -> Result { + self.clean_poc = true; + // SAFETY: The root is a RAM page owned or borrowed by this page table for its lifetime. + let root = unsafe { Page::borrow_phys(&self.ttb) }.ok_or(EIO)?; + root.with_pointer_into_page(0, UAT_PGSZ, |p| { + clean_poc(p, UAT_PGSZ); + Ok(()) + })?; + poc_barrier(); + Ok(()) + } + + /// Whether changes are cleaned to the point of coherency (always false without G15 support). + #[inline(always)] + fn cleans_poc(&self) -> bool { + #[cfg(CONFIG_DRM_ASAHI_G15)] + { + self.clean_poc + } + #[cfg(not(CONFIG_DRM_ASAHI_G15))] + { + false + } + } + /// Borrow a root; track individual child ownership only when other agents /// can install tables below it. Handoff roots have driver-owned children. pub(crate) fn new_with_ttb( @@ -284,6 +396,8 @@ impl UatPageTable { va_range, ias_mask: (1u64 << ias) - 1, oas_mask: (1u64 << oas) - 1, + #[cfg(CONFIG_DRM_ASAHI_G15)] + clean_poc: false, }) } @@ -291,16 +405,48 @@ impl UatPageTable { self.ttb } - fn with_pages( + /// Walks the leaves of `iova_range` without changing them. + fn with_pages(&mut self, iova_range: Range, alloc: bool, free: bool, cb: F) -> Result + where + F: FnMut(u64, &[Pte]) -> Result, + { + self.walk(iova_range, alloc, free, false, cb) + } + + /// Walks the leaves of `iova_range`, which `cb` may change (`mutate`). + /// + /// With point-of-coherency cleaning enabled, the changed leaves are cleaned after `cb`, and a + /// walk that may have changed any descriptor ends with a barrier, also on failure. + fn walk( + &mut self, + iova_range: Range, + alloc: bool, + free: bool, + mutate: bool, + cb: F, + ) -> Result + where + F: FnMut(u64, &[Pte]) -> Result, + { + let result = self.walk_inner(iova_range, alloc, free, mutate, cb); + if self.cleans_poc() && (alloc || free || mutate) { + poc_barrier(); + } + result + } + + fn walk_inner( &mut self, iova_range: Range, alloc: bool, free: bool, + mutate: bool, mut cb: F, ) -> Result where F: FnMut(u64, &[Pte]) -> Result, { + let clean = self.cleans_poc(); mod_pr_debug!( "UATPageTable::with_pages: {:#x?} alloc={} free={}\n", iova_range, @@ -382,6 +528,14 @@ impl UatPageTable { if upte_val == 0 && alloc { let pt_page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; mod_pr_debug!("UATPageTable::with_pages: alloc PT at {:#x}\n", pt_page.phys()); + if clean { + // A non-snooping walker must never follow a parent to a + // table whose zeroes are still in the CPU caches. + pt_page.with_pointer_into_page(0, UAT_PGSZ, |p| { + clean_poc(p, UAT_PGSZ); + Ok(()) + })?; + } if let Some(tables) = self.driver_tables.as_mut() { tables.push(pt_page.phys(), GFP_KERNEL)?; } @@ -393,6 +547,9 @@ impl UatPageTable { // already-visible parent against earlier clears. crate::mem::sync(); upte.store(upte_val, Ordering::Relaxed); + if clean { + clean_poc(uptep.cast(), PTE_SIZE); + } } if upte_val & PTE_TYPE_BITS == PTE_TYPE_LEAF_TABLE { Ok(Some(upte_val & self.oas_mask & (!UAT_PGMSK as u64))) @@ -448,8 +605,12 @@ impl UatPageTable { // SAFETY: We know this is a valid pointer to PTEs and the range is valid and // checked by with_pointer_into_page(). let ptes = unsafe { core::slice::from_raw_parts(ptep, count) }; - cb(iova, ptes)?; - Ok(()) + let result = cb(iova, ptes); + if clean && mutate { + // Also after a partial change: the callback may have stored some leaves. + clean_poc(p, count * PTE_SIZE); + } + result })?; let block = 1 << (UAT_PGBIT + UAT_LVBIT); @@ -505,6 +666,9 @@ impl UatPageTable { return Err(EIO); } pte.store(0, Ordering::Release); + if self.cleans_poc() { + clean_poc(p, PTE_SIZE); + } Ok(()) })?; } @@ -625,7 +789,7 @@ impl UatPageTable { let pte_bits = self.pte_bits(); - self.with_pages(iova_range, true, false, |iova, ptes| { + self.walk(iova_range, true, false, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { let ptev = pte.load(Ordering::Relaxed); if ptev != 0 { @@ -650,7 +814,7 @@ impl UatPageTable { iova_range, prot ); - self.with_pages(iova_range, true, false, |iova, ptes| { + self.walk(iova_range, true, false, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { let ptev = pte.load(Ordering::Relaxed); if ptev & PTE_TYPE_BITS != PTE_TYPE_LEAF_TABLE { @@ -669,7 +833,7 @@ impl UatPageTable { pub(crate) fn unmap_pages(&mut self, iova_range: Range) -> Result { mod_pr_debug!("UATPageTable::unmap_pages: {:#x?}\n", iova_range); - self.with_pages(iova_range, false, false, |iova, ptes| { + self.walk(iova_range, false, false, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { if pte.load(Ordering::Relaxed) & PTE_TYPE_LEAF_TABLE == 0 { pr_err!( @@ -686,7 +850,7 @@ impl UatPageTable { /// Discards an aligned map operation that failed before acquiring a GPUVA owner. /// Missing tables and leaves are expected; existing table storage stays allocated. pub(crate) fn discard_partial_map(&mut self, iova_range: Range) -> Result { - self.with_pages(iova_range, false, false, |_, ptes| { + self.walk(iova_range, false, false, true, |_, ptes| { for pte in ptes { pte.store(0, Ordering::Relaxed); } diff --git a/drivers/gpu/drm/aspeed/aspeed_gfx_drv.c b/drivers/gpu/drm/aspeed/aspeed_gfx_drv.c index d4577663a1f0ef..aa36b79d0f6c42 100644 --- a/drivers/gpu/drm/aspeed/aspeed_gfx_drv.c +++ b/drivers/gpu/drm/aspeed/aspeed_gfx_drv.c @@ -189,13 +189,12 @@ static int aspeed_gfx_load(struct drm_device *drm) } reset_control_deassert(priv->rst); - priv->clk = devm_clk_get(drm->dev, NULL); + priv->clk = devm_clk_get_enabled(drm->dev, NULL); if (IS_ERR(priv->clk)) { dev_err(&pdev->dev, - "missing or invalid clk device tree entry"); + "failed to get and enable clock\n"); return PTR_ERR(priv->clk); } - clk_prepare_enable(priv->clk); /* Sanitize control registers */ writel(0, priv->base + CRT_CTRL1); diff --git a/drivers/gpu/drm/bridge/th1520-dw-hdmi.c b/drivers/gpu/drm/bridge/th1520-dw-hdmi.c index cbea8b14cd4b0f..2fa7f2d46b3dcd 100644 --- a/drivers/gpu/drm/bridge/th1520-dw-hdmi.c +++ b/drivers/gpu/drm/bridge/th1520-dw-hdmi.c @@ -135,8 +135,8 @@ static int th1520_dw_hdmi_probe(struct platform_device *pdev) plat_data->priv_data = hdmi; hdmi->dw_hdmi = dw_hdmi_probe(pdev, plat_data); - if (IS_ERR(hdmi)) - return PTR_ERR(hdmi); + if (IS_ERR(hdmi->dw_hdmi)) + return PTR_ERR(hdmi->dw_hdmi); platform_set_drvdata(pdev, hdmi); @@ -145,9 +145,9 @@ static int th1520_dw_hdmi_probe(struct platform_device *pdev) static void th1520_dw_hdmi_remove(struct platform_device *pdev) { - struct dw_hdmi *hdmi = platform_get_drvdata(pdev); + struct th1520_hdmi *hdmi = platform_get_drvdata(pdev); - dw_hdmi_remove(hdmi); + dw_hdmi_remove(hdmi->dw_hdmi); } static const struct of_device_id th1520_dw_hdmi_of_table[] = { diff --git a/drivers/gpu/drm/display/drm_dp_helper.c b/drivers/gpu/drm/display/drm_dp_helper.c index e623ccb4c1d8ab..488fd123a01adb 100644 --- a/drivers/gpu/drm/display/drm_dp_helper.c +++ b/drivers/gpu/drm/display/drm_dp_helper.c @@ -4634,7 +4634,9 @@ static int dp_aux_backlight_update_status(struct backlight_device *bd) if (!backlight_is_blank(bd)) { if (!bl->enabled) { - drm_edp_backlight_enable(bl->aux, &bl->info, brightness); + ret = drm_edp_backlight_enable(bl->aux, &bl->info, brightness); + if (ret) + return ret; bl->enabled = true; return 0; } diff --git a/drivers/gpu/drm/drm_bridge.c b/drivers/gpu/drm/drm_bridge.c index 687b36eea0c703..9124cbe1ff8895 100644 --- a/drivers/gpu/drm/drm_bridge.c +++ b/drivers/gpu/drm/drm_bridge.c @@ -414,8 +414,10 @@ void drm_bridge_add(struct drm_bridge *bridge) * in bridge_lingering_list. Remove it or bridge_lingering_list will be * corrupted when adding this bridge to bridge_list below. */ + mutex_lock(&bridge_lock); if (!list_empty(&bridge->list)) list_del_init(&bridge->list); + mutex_unlock(&bridge_lock); mutex_init(&bridge->hpd_mutex); @@ -556,8 +558,10 @@ int drm_bridge_attach(struct drm_encoder *encoder, struct drm_bridge *bridge, if (!bridge->container) DRM_WARN("DRM bridge corrupted or not allocated by devm_drm_bridge_alloc()\n"); - if (list_empty(&bridge->list)) - DRM_WARN("Missing drm_bridge_add() before attach\n"); + scoped_guard(mutex, &bridge_lock) { + if (list_empty(&bridge->list)) + DRM_WARN("Missing drm_bridge_add() before attach\n"); + } drm_bridge_get(bridge); diff --git a/drivers/gpu/drm/drm_fb_helper.c b/drivers/gpu/drm/drm_fb_helper.c index 80ca785bdb262f..3dfa64dc310969 100644 --- a/drivers/gpu/drm/drm_fb_helper.c +++ b/drivers/gpu/drm/drm_fb_helper.c @@ -1724,10 +1724,10 @@ __drm_fb_helper_initial_config_and_unlock(struct drm_fb_helper *fb_helper) ret = drm_fb_helper_single_fb_probe(fb_helper); if (ret < 0) { - if (ret == -EAGAIN) { - fb_helper->deferred_setup = true; + /* modesets are probed but fb_helper->fb isn't; defer restore too */ + fb_helper->deferred_setup = true; + if (ret == -EAGAIN) ret = 0; - } mutex_unlock(&fb_helper->lock); goto err_drm_fb_helper_release_info; diff --git a/drivers/gpu/drm/gud/gud_pipe.c b/drivers/gpu/drm/gud/gud_pipe.c index aa7792966287bf..5aa5ac2f37274a 100644 --- a/drivers/gpu/drm/gud/gud_pipe.c +++ b/drivers/gpu/drm/gud/gud_pipe.c @@ -507,6 +507,7 @@ int gud_plane_atomic_check(struct drm_plane *plane, for_each_new_connector_in_state(state, connector, connector_state, i) { if (connector_state->crtc) break; + connector_state = NULL; } /* diff --git a/drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c b/drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c index 1f303d4eaa4d4f..d5aadced7da0cf 100644 --- a/drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c +++ b/drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c @@ -1766,6 +1766,7 @@ static int eb_reinit_userptr(struct i915_execbuffer *eb) static noinline int eb_relocate_parse_slow(struct i915_execbuffer *eb) { + const unsigned int count = eb->buffer_count; bool have_copy = false; struct eb_vma *ev; int err = 0; @@ -1868,7 +1869,6 @@ static noinline int eb_relocate_parse_slow(struct i915_execbuffer *eb) out: if (have_copy) { - const unsigned int count = eb->buffer_count; unsigned int i; for (i = 0; i < count; i++) { diff --git a/drivers/gpu/drm/i915/gt/intel_rps.c b/drivers/gpu/drm/i915/gt/intel_rps.c index a33b19c04737a7..0f9b4f1dd3cb6d 100644 --- a/drivers/gpu/drm/i915/gt/intel_rps.c +++ b/drivers/gpu/drm/i915/gt/intel_rps.c @@ -1904,7 +1904,8 @@ static void rps_work(struct work_struct *work) out: spin_lock_irq(gt->irq_lock); - gen6_gt_pm_unmask_irq(gt, rps->pm_events); + if (intel_rps_is_active(rps)) + gen6_gt_pm_unmask_irq(gt, rps->pm_events); spin_unlock_irq(gt->irq_lock); } diff --git a/drivers/gpu/drm/imagination/pvr_mmu.c b/drivers/gpu/drm/imagination/pvr_mmu.c index 62eae7fcd5a26a..67e73d7d5d0e97 100644 --- a/drivers/gpu/drm/imagination/pvr_mmu.c +++ b/drivers/gpu/drm/imagination/pvr_mmu.c @@ -2337,7 +2337,7 @@ void pvr_mmu_op_context_destroy(struct pvr_mmu_op_context *op_ctx) * @ctx: MMU context associated with owning VM context. * @sgt: Scatter gather table containing pages pinned for use by this context. * @device_addr: Virtual device address at the start of the requested mapping. - * @sgt_offset: Start offset of the requested device-virtual memory mapping. + * @sgt_offset: Offset into @sgt of the start of the requested mapping. * @size: Size in bytes of the requested device-virtual memory mapping. For an * unmapping, this should be zero so that no page tables are allocated. * @@ -2350,7 +2350,6 @@ struct pvr_mmu_op_context * pvr_mmu_op_context_create(struct pvr_mmu_context *ctx, struct sg_table *sgt, u64 device_addr, u64 sgt_offset, u64 size) { - u64 start_addr = device_addr + sgt_offset; int err; struct pvr_mmu_op_context *op_ctx = kzalloc_obj(*op_ctx); @@ -2365,18 +2364,18 @@ pvr_mmu_op_context_create(struct pvr_mmu_context *ctx, struct sg_table *sgt, if (size) { /* - * The number of page table objects we need to prealloc is - * indicated by the mapping size, start address and the sizes - * of the areas mapped per PT or PD. The range calculation is - * identical to that for the index into a table for a device - * address, so we reuse those functions here. + * The page tables needed are set by the device-virtual range + * being mapped: one level 1 table per 1GiB region and one + * level 0 table per 2MiB region the range touches. Tables that + * already exist are not consumed, so this is an upper bound. */ - const u32 l1_start_idx = pvr_page_table_l2_idx(start_addr); - const u32 l1_end_idx = pvr_page_table_l2_idx(start_addr + size); - const u32 l1_count = l1_end_idx - l1_start_idx + 1; - const u32 l0_start_idx = pvr_page_table_l1_idx(start_addr); - const u32 l0_end_idx = pvr_page_table_l1_idx(start_addr + size); - const u32 l0_count = l0_end_idx - l0_start_idx + 1; + const u64 last_addr = device_addr + size - 1; + const u64 l1_count = + (last_addr >> ROGUE_MMUCTRL_VADDR_PC_INDEX_SHIFT) - + (device_addr >> ROGUE_MMUCTRL_VADDR_PC_INDEX_SHIFT) + 1; + const u64 l0_count = + (last_addr >> ROGUE_MMUCTRL_VADDR_PD_INDEX_SHIFT) - + (device_addr >> ROGUE_MMUCTRL_VADDR_PD_INDEX_SHIFT) + 1; /* * Alloc and push page table entries until we have enough of diff --git a/drivers/gpu/drm/imagination/pvr_vm.c b/drivers/gpu/drm/imagination/pvr_vm.c index 55cc999f3708b6..cbdd15ed74fdbb 100644 --- a/drivers/gpu/drm/imagination/pvr_vm.c +++ b/drivers/gpu/drm/imagination/pvr_vm.c @@ -418,6 +418,8 @@ pvr_vm_gpuva_unmap(struct drm_gpuva_op *op, void *op_ctx) static int pvr_vm_gpuva_remap(struct drm_gpuva_op *op, void *op_ctx) { + /* The split parts belong to the object of the mapping being split. */ + struct drm_gpuvm_bo *vm_bo = op->remap.unmap->va->vm_bo; struct pvr_vm_bind_op *ctx = op_ctx; u64 va_start = 0, va_range = 0; int err; @@ -433,14 +435,12 @@ pvr_vm_gpuva_remap(struct drm_gpuva_op *op, void *op_ctx) drm_gpuva_remap(&ctx->prev_va->base, &ctx->next_va->base, &op->remap); if (op->remap.prev) { - pvr_gem_object_get(gem_to_pvr_gem(ctx->prev_va->base.gem.obj)); - drm_gpuva_link(&ctx->prev_va->base, ctx->gpuvm_bo); + drm_gpuva_link(&ctx->prev_va->base, vm_bo); ctx->prev_va = NULL; } if (op->remap.next) { - pvr_gem_object_get(gem_to_pvr_gem(ctx->next_va->base.gem.obj)); - drm_gpuva_link(&ctx->next_va->base, ctx->gpuvm_bo); + drm_gpuva_link(&ctx->next_va->base, vm_bo); ctx->next_va = NULL; } diff --git a/drivers/gpu/drm/panthor/panthor_sched.c b/drivers/gpu/drm/panthor/panthor_sched.c index 369ee06434bbdd..765b895619e8be 100644 --- a/drivers/gpu/drm/panthor/panthor_sched.c +++ b/drivers/gpu/drm/panthor/panthor_sched.c @@ -3675,6 +3675,9 @@ int panthor_group_create(struct panthor_file *pfile, hweight64(group_args->tiler_core_mask) < group_args->max_tiler_cores) return -EINVAL; + if (group_args->queues.count > sched->cs_slot_count) + return -EINVAL; + group = kzalloc_obj(*group); if (!group) return -ENOMEM; diff --git a/drivers/gpu/drm/vc4/vc4_bo.c b/drivers/gpu/drm/vc4/vc4_bo.c index 49ea2ed0996b4c..7b8b3364000fce 100644 --- a/drivers/gpu/drm/vc4/vc4_bo.c +++ b/drivers/gpu/drm/vc4/vc4_bo.c @@ -204,7 +204,7 @@ static struct list_head *vc4_get_cache_list_for_size(struct drm_device *dev, struct list_head *new_list; uint32_t i; - new_list = kmalloc_objs(struct list_head, new_size); + new_list = kvmalloc_objs(struct list_head, new_size); if (!new_list) return NULL; @@ -224,7 +224,7 @@ static struct list_head *vc4_get_cache_list_for_size(struct drm_device *dev, for (i = vc4->bo_cache.size_list_size; i < new_size; i++) INIT_LIST_HEAD(&new_list[i]); - kfree(vc4->bo_cache.size_list); + kvfree(vc4->bo_cache.size_list); vc4->bo_cache.size_list = new_list; vc4->bo_cache.size_list_size = new_size; } @@ -1052,6 +1052,7 @@ static void vc4_bo_cache_destroy(struct drm_device *dev, void *unused) cancel_work_sync(&vc4->bo_cache.time_work); vc4_bo_cache_purge(dev); + kvfree(vc4->bo_cache.size_list); for (i = 0; i < vc4->num_labels; i++) { if (vc4->bo_labels[i].num_allocated) { diff --git a/drivers/gpu/drm/vc4/vc4_drv.c b/drivers/gpu/drm/vc4/vc4_drv.c index 8e4c665ca159d9..284a971e28b315 100644 --- a/drivers/gpu/drm/vc4/vc4_drv.c +++ b/drivers/gpu/drm/vc4/vc4_drv.c @@ -360,8 +360,11 @@ static int vc4_drm_bind(struct device *dev) } ret = aperture_remove_all_conflicting_devices(driver->name); - if (ret) + if (ret) { + if (firmware) + rpi_firmware_put(firmware); goto err; + } if (firmware) { ret = rpi_firmware_property(firmware, diff --git a/drivers/gpu/drm/vc4/vc4_drv.h b/drivers/gpu/drm/vc4/vc4_drv.h index 0f5958c1e6b601..b0e82c2dc1bae7 100644 --- a/drivers/gpu/drm/vc4/vc4_drv.h +++ b/drivers/gpu/drm/vc4/vc4_drv.h @@ -1051,7 +1051,7 @@ void vc4_plane_async_set_fb(struct drm_plane *plane, /* vc4_v3d.c */ extern struct platform_driver vc4_v3d_driver; extern const struct of_device_id vc4_v3d_dt_match[]; -int vc4_v3d_get_bin_slot(struct vc4_dev *vc4); +int vc4_v3d_get_bin_slot(struct vc4_dev *vc4, long timeout); int vc4_v3d_bin_bo_get(struct vc4_dev *vc4, bool *used); void vc4_v3d_bin_bo_put(struct vc4_dev *vc4); int vc4_v3d_pm_get(struct vc4_dev *vc4); diff --git a/drivers/gpu/drm/vc4/vc4_gem.c b/drivers/gpu/drm/vc4/vc4_gem.c index e231c906709c1b..6ee4bd77d4331a 100644 --- a/drivers/gpu/drm/vc4/vc4_gem.c +++ b/drivers/gpu/drm/vc4/vc4_gem.c @@ -877,11 +877,17 @@ vc4_complete_exec(struct drm_device *dev, struct vc4_exec_info *exec) drm_gem_object_put(&bo->base.base); } - /* Free up the allocation of any bin slots we used. */ + /* Free up the allocation of any bin slots we used. Jobs that ran to + * completion had their slots released in vc4_irq_finish_render_job(). + * Only jobs that never completed still have slots to be released here. + */ spin_lock_irqsave(&vc4->job_lock, irqflags); vc4->bin_alloc_used &= ~exec->bin_slots; spin_unlock_irqrestore(&vc4->job_lock, irqflags); + /* Let anyone waiting on the binner pool retry. */ + wake_up_all(&vc4->job_wait_queue); + /* Release the reference on the binner BO if needed. */ if (exec->bin_bo_used) vc4_v3d_bin_bo_put(vc4); diff --git a/drivers/gpu/drm/vc4/vc4_irq.c b/drivers/gpu/drm/vc4/vc4_irq.c index 7877d493d80e62..dc10d3a4d90f20 100644 --- a/drivers/gpu/drm/vc4/vc4_irq.c +++ b/drivers/gpu/drm/vc4/vc4_irq.c @@ -74,7 +74,7 @@ vc4_overflow_mem_work(struct work_struct *work) bo = vc4->bin_bo; - bin_bo_slot = vc4_v3d_get_bin_slot(vc4); + bin_bo_slot = vc4_v3d_get_bin_slot(vc4, msecs_to_jiffies(500)); if (bin_bo_slot < 0) { drm_err(&vc4->base, "Couldn't allocate binner overflow mem\n"); goto complete; @@ -165,6 +165,10 @@ vc4_irq_finish_render_job(struct drm_device *dev) trace_vc4_rcl_end_irq(dev, exec->seqno); vc4->finished_seqno++; + + vc4->bin_alloc_used &= ~exec->bin_slots; + exec->bin_slots = 0; + list_move_tail(&exec->head, &vc4->job_done_list); nextbin = vc4_first_bin_job(vc4); @@ -276,7 +280,7 @@ vc4_irq_disable(struct drm_device *dev) V3D_WRITE(V3D_INTCTL, V3D_DRIVER_IRQS); /* Finish any interrupt handler still in flight. */ - synchronize_irq(vc4->irq); + disable_irq(vc4->irq); cancel_work_sync(&vc4->overflow_mem_work); } @@ -284,7 +288,6 @@ vc4_irq_disable(struct drm_device *dev) int vc4_irq_install(struct drm_device *dev, int irq) { struct vc4_dev *vc4 = to_vc4_dev(dev); - int ret; if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) return -ENODEV; @@ -298,19 +301,8 @@ int vc4_irq_install(struct drm_device *dev, int irq) init_waitqueue_head(&vc4->job_wait_queue); INIT_WORK(&vc4->overflow_mem_work, vc4_overflow_mem_work); - /* Clear any pending interrupts someone might have left around - * for us. - */ - V3D_WRITE(V3D_INTCTL, V3D_DRIVER_IRQS); - - ret = devm_request_irq(dev->dev, irq, vc4_irq, 0, - dev_name(dev->dev), dev); - if (ret) - return ret; - - vc4_irq_enable(dev); - - return 0; + return devm_request_irq(dev->dev, irq, vc4_irq, IRQF_NO_AUTOEN, + dev_name(dev->dev), dev); } void vc4_irq_uninstall(struct drm_device *dev) diff --git a/drivers/gpu/drm/vc4/vc4_v3d.c b/drivers/gpu/drm/vc4/vc4_v3d.c index f32410420d3e4d..6844e8f3948cf8 100644 --- a/drivers/gpu/drm/vc4/vc4_v3d.c +++ b/drivers/gpu/drm/vc4/vc4_v3d.c @@ -9,6 +9,7 @@ #include #include #include +#include #include @@ -172,46 +173,42 @@ static void vc4_v3d_init_hw(struct drm_device *dev) V3D_WRITE(V3D_VPMBASE, 0); } -int vc4_v3d_get_bin_slot(struct vc4_dev *vc4) +static int bin_slot_try_alloc(struct vc4_dev *vc4) { - struct drm_device *dev = &vc4->base; - unsigned long irqflags; int slot; - uint64_t seqno = 0; - struct vc4_exec_info *exec; - if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) - return -ENODEV; + guard(spinlock_irqsave)(&vc4->job_lock); -try_again: - spin_lock_irqsave(&vc4->job_lock, irqflags); slot = ffs(~vc4->bin_alloc_used); if (slot != 0) { /* Switch from ffs() bit index to a 0-based index. */ slot--; vc4->bin_alloc_used |= BIT(slot); - spin_unlock_irqrestore(&vc4->job_lock, irqflags); - return slot; + } else { + slot = -ENOMEM; } - /* Couldn't find an open slot. Wait for render to complete - * and try again. - */ - exec = vc4_last_render_job(vc4); - if (exec) - seqno = exec->seqno; - spin_unlock_irqrestore(&vc4->job_lock, irqflags); + return slot; +} - if (seqno) { - int ret = vc4_wait_for_seqno(dev, seqno, ~0ull, true); +int vc4_v3d_get_bin_slot(struct vc4_dev *vc4, long timeout) +{ + int slot; + long ret; - if (ret == 0) - goto try_again; + if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) + return -ENODEV; + /* If the pool is full, wait for a job to release its slots. */ + ret = wait_event_interruptible_timeout(vc4->job_wait_queue, + (slot = bin_slot_try_alloc(vc4)) >= 0, + timeout); + if (ret < 0) return ret; - } + if (ret == 0) + return -ENOMEM; - return -ENOMEM; + return slot; } /* @@ -396,6 +393,7 @@ static int vc4_v3d_runtime_resume(struct device *dev) vc4_v3d_init_hw(&vc4->base); vc4_irq_enable(&vc4->base); + enable_irq(vc4->irq); return 0; } @@ -452,6 +450,12 @@ static int vc4_v3d_bind(struct device *dev, struct device *master, void *data) return ret; vc4->irq = ret; + ret = vc4_irq_install(drm, vc4->irq); + if (ret) { + drm_err(drm, "Failed to install IRQ handler\n"); + return ret; + } + ret = devm_pm_runtime_enable(dev); if (ret) return ret; @@ -473,12 +477,6 @@ static int vc4_v3d_bind(struct device *dev, struct device *master, void *data) V3D_WRITE(V3D_BPOA, 0); V3D_WRITE(V3D_BPOS, 0); - ret = vc4_irq_install(drm, vc4->irq); - if (ret) { - drm_err(drm, "Failed to install IRQ handler\n"); - goto err_put_runtime_pm; - } - pm_runtime_use_autosuspend(dev); pm_runtime_set_autosuspend_delay(dev, 40); /* a little over 2 frames. */ pm_runtime_put_autosuspend(dev); @@ -497,8 +495,15 @@ static void vc4_v3d_unbind(struct device *dev, struct device *master, struct drm_device *drm = data; struct vc4_dev *vc4 = to_vc4_dev(drm); + /* A straggler vc4_reset() re-enables the interrupt. */ + timer_shutdown_sync(&vc4->hangcheck.timer); + cancel_work_sync(&vc4->hangcheck.reset_work); + vc4_irq_uninstall(drm); + /* Flush rather than cancel, so queued completions release their jobs. */ + flush_work(&vc4->job_done_work); + /* Disable the binner's overflow memory address, so the next * driver probe (if any) doesn't try to reuse our old * allocation. diff --git a/drivers/gpu/drm/vc4/vc4_validate.c b/drivers/gpu/drm/vc4/vc4_validate.c index d2a65c968b1f90..565227657b43b4 100644 --- a/drivers/gpu/drm/vc4/vc4_validate.c +++ b/drivers/gpu/drm/vc4/vc4_validate.c @@ -402,7 +402,7 @@ validate_tile_binning_config(VALIDATE_ARGS) return -EINVAL; } - bin_slot = vc4_v3d_get_bin_slot(vc4); + bin_slot = vc4_v3d_get_bin_slot(vc4, MAX_SCHEDULE_TIMEOUT); if (bin_slot < 0) { if (bin_slot != -EINTR && bin_slot != -ERESTARTSYS) { drm_err(dev, "Failed to allocate binner memory: %d\n", diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c index d1e7df50019030..5a69606a0593bc 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c @@ -324,6 +324,7 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf, unsigned long kmap_num; SVGA3dCopyBox *box; u32 box_count; + u64 src_extent; void *virtual; bool is_iomem; struct vmw_dma_cmd { @@ -335,6 +336,8 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf, vmw_surface_get_desc(VMW_CURSOR_SNOOP_FORMAT); const u32 image_pitch = VMW_CURSOR_SNOOP_WIDTH * desc->pitchBytesPerBlock; + BUILD_BUG_ON(sizeof(*srf->snooper.image) != desc->pitchBytesPerBlock); + cmd = container_of(header, struct vmw_dma_cmd, header); /* No snooper installed, nothing to copy */ @@ -372,8 +375,19 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf, return; } + if (box->w == 0 || box->h == 0) + return; + + src_extent = (u64)(box->h - 1) * cmd->dma.guest.pitch + + (u64)box->w * desc->pitchBytesPerBlock; + if (src_extent > bo->base.size) { + DRM_ERROR("Cursor snoop source of %llu bytes exceeds the %zu byte buffer\n", + src_extent, bo->base.size); + return; + } + kmap_offset = cmd->dma.guest.ptr.offset >> PAGE_SHIFT; - kmap_num = (VMW_CURSOR_SNOOP_HEIGHT * image_pitch) >> PAGE_SHIFT; + kmap_num = PFN_UP(src_extent); ret = ttm_bo_reserve(bo, true, false, NULL); if (unlikely(ret != 0)) { @@ -387,14 +401,16 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf, virtual = ttm_kmap_obj_virtual(&map, &is_iomem); - if (box->w == VMW_CURSOR_SNOOP_WIDTH && cmd->dma.guest.pitch == image_pitch) { + if (box->w == VMW_CURSOR_SNOOP_WIDTH && + box->h == VMW_CURSOR_SNOOP_HEIGHT && + cmd->dma.guest.pitch == image_pitch) { memcpy(srf->snooper.image, virtual, VMW_CURSOR_SNOOP_HEIGHT * image_pitch); } else { - /* Image is unsigned pointer. */ + /* The destination stride is in pixels. */ for (i = 0; i < box->h; i++) - memcpy(srf->snooper.image + i * image_pitch, - virtual + i * cmd->dma.guest.pitch, + memcpy(srf->snooper.image + i * VMW_CURSOR_SNOOP_WIDTH, + virtual + (size_t)i * cmd->dma.guest.pitch, box->w * desc->pitchBytesPerBlock); } srf->snooper.id++; diff --git a/drivers/gpu/drm/xe/display/xe_fb_pin.c b/drivers/gpu/drm/xe/display/xe_fb_pin.c index 73469ea5f333d3..f1dbdc802df81a 100644 --- a/drivers/gpu/drm/xe/display/xe_fb_pin.c +++ b/drivers/gpu/drm/xe/display/xe_fb_pin.c @@ -356,7 +356,7 @@ static struct i915_vma *__xe_pin_fb_vma(struct drm_gem_object *obj, bool is_dpt, drm_exec_retry_on_contention(&exec); xe_validation_retry_on_oom(&ctx, &ret); if (!ret) - ttm_bo_pin(&bo->ttm); + xe_bo_pin_account(bo); } if (ret) goto err; @@ -373,7 +373,7 @@ static struct i915_vma *__xe_pin_fb_vma(struct drm_gem_object *obj, bool is_dpt, err_unpin: ttm_bo_reserve(&bo->ttm, false, false, NULL); - ttm_bo_unpin(&bo->ttm); + xe_bo_unpin_account(bo); ttm_bo_unreserve(&bo->ttm); err: kfree(vma); @@ -393,7 +393,7 @@ static void __xe_unpin_fb_vma(struct i915_vma *vma) xe_ggtt_node_remove(vma->node, false); ttm_bo_reserve(&vma->bo->ttm, false, false, NULL); - ttm_bo_unpin(&vma->bo->ttm); + xe_bo_unpin_account(vma->bo); ttm_bo_unreserve(&vma->bo->ttm); kfree(vma); } diff --git a/drivers/gpu/drm/xe/xe_bo.c b/drivers/gpu/drm/xe/xe_bo.c index 2c60e99249f932..f4c5151d61c7ce 100644 --- a/drivers/gpu/drm/xe/xe_bo.c +++ b/drivers/gpu/drm/xe/xe_bo.c @@ -443,6 +443,100 @@ static void xe_ttm_tt_account_subtract(struct xe_device *xe, struct ttm_tt *tt) xe_shrinker_mod_pages(xe->mem.shrinker, -(long)tt->num_pages, 0); } +static bool xe_ttm_bo_is_imported(struct ttm_buffer_object *tbo) +{ + dma_resv_assert_held(tbo->base.resv); + + return tbo->ttm && + (tbo->ttm->page_flags & (TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_EXTERNAL_MAPPABLE)) == + TTM_TT_FLAG_EXTERNAL; +} + +/* + * Account @bo's pages as pinned for the shrinker. Removes @bo's pages + * from the shrinker's shrinkable / purgeable counts on the transition + * from unpinned to pinned. Must be called with @bo's dma-resv held, + * after &ttm_buffer_object.pin_count has been incremented by + * ttm_bo_pin(). Safe to call unconditionally regardless of which pin + * path (kernel, external, framebuffer, backup object, ...) is pinning + * @bo, since it only acts on the true 0->1 pin_count transition. + * + * Imported bos (xe_ttm_bo_is_imported()) are excluded: for those, + * xe_ttm_tt_populate() never actually populates the tt or calls + * xe_ttm_tt_account_add(), but TTM core's ttm_tt_populate() still + * unconditionally marks the tt as populated on driver-hook success. + * Relying on ttm_tt_is_populated() for these would subtract pages that + * were never added, underflowing the shrinker's counts. + */ +static void xe_bo_account_pin(struct xe_bo *bo) +{ + struct xe_device *xe = xe_bo_device(bo); + + if (bo->ttm.pin_count == 1 && bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm) && + !xe_ttm_bo_is_imported(&bo->ttm)) + xe_ttm_tt_account_subtract(xe, bo->ttm.ttm); +} + +/* + * Counterpart to xe_bo_account_pin(). Must be called with @bo's dma-resv + * held, before &ttm_buffer_object.pin_count is decremented by + * ttm_bo_unpin(), so that the check against the true 1->0 transition sees + * the pin count that is about to be released. See xe_bo_account_pin() for + * why imported bos are excluded. + * + * On the true last unpin, also removes @bo from whichever pinned-bo list + * (external or kernel_bo_present) it may currently be linked on, since a + * bo's final unpin can happen through a pin path (e.g. framebuffer, + * backup object) that has no notion of, or ownership over, that list. + * This is safe and list-agnostic: list_del_init() only needs the node + * itself, not knowledge of which list it is threaded through, and is a + * no-op if @bo is not linked. + */ +static void xe_bo_account_unpin(struct xe_bo *bo) +{ + struct xe_device *xe = xe_bo_device(bo); + bool last_unpin = bo->ttm.pin_count == 1; + + if (last_unpin && !list_empty(&bo->pinned_link)) { + spin_lock(&xe->pinned.lock); + list_del_init(&bo->pinned_link); + spin_unlock(&xe->pinned.lock); + } + + if (last_unpin && bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm) && + !xe_ttm_bo_is_imported(&bo->ttm)) + xe_ttm_tt_account_add(xe, bo->ttm.ttm); +} + +/** + * xe_bo_pin_account() - Pin a bo and account its pages for the shrinker + * @bo: The buffer object to pin. + * + * Pins @bo via ttm_bo_pin() and updates the shrinker's shrinkable / + * purgeable page accounting to match. Must be called with @bo's dma-resv + * held. Safe to call regardless of which pin path (kernel, external, + * framebuffer, backup object, ...) is pinning @bo. + */ +void xe_bo_pin_account(struct xe_bo *bo) +{ + ttm_bo_pin(&bo->ttm); + xe_bo_account_pin(bo); +} + +/** + * xe_bo_unpin_account() - Unpin a bo and account its pages for the shrinker + * @bo: The buffer object to unpin. + * + * Counterpart to xe_bo_pin_account(). Updates the shrinker's shrinkable / + * purgeable page accounting to match, then unpins @bo via ttm_bo_unpin(). + * Must be called with @bo's dma-resv held. + */ +void xe_bo_unpin_account(struct xe_bo *bo) +{ + xe_bo_account_unpin(bo); + ttm_bo_unpin(&bo->ttm); +} + static void update_global_total_pages(struct ttm_device *ttm_dev, long num_pages) { @@ -1377,7 +1471,8 @@ int xe_bo_notifier_prepare_pinned(struct xe_bo *bo) } backup->parent_obj = xe_bo_get(bo); /* Released by bo_destroy */ - ttm_bo_pin(&backup->ttm); + /* Note: XE_BO_FLAG_SYSTEM resolves to XE_PL_TT so already populated. */ + xe_bo_pin_account(backup); bo->backup_obj = backup; } @@ -1397,7 +1492,7 @@ int xe_bo_notifier_unprepare_pinned(struct xe_bo *bo) { xe_bo_lock(bo, false); if (bo->backup_obj) { - ttm_bo_unpin(&bo->backup_obj->ttm); + xe_bo_unpin_account(bo->backup_obj); xe_bo_put(bo->backup_obj); bo->backup_obj = NULL; } @@ -1608,7 +1703,7 @@ int xe_bo_restore_pinned(struct xe_bo *bo) xe_bo_vunmap(backup); if (!bo->backup_obj) { if (xe_bo_is_pinned(backup)) - ttm_bo_unpin(&backup->ttm); + xe_bo_unpin_account(backup); xe_bo_put(backup); } out_unlock_bo: @@ -2000,15 +2095,6 @@ static vm_fault_t xe_err_to_fault_t(int err) return VM_FAULT_SIGBUS; } -static bool xe_ttm_bo_is_imported(struct ttm_buffer_object *tbo) -{ - dma_resv_assert_held(tbo->base.resv); - - return tbo->ttm && - (tbo->ttm->page_flags & (TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_EXTERNAL_MAPPABLE)) == - TTM_TT_FLAG_EXTERNAL; -} - static vm_fault_t xe_bo_cpu_fault_fastpath(struct vm_fault *vmf, struct xe_device *xe, struct xe_bo *bo, bool needs_rpm) { @@ -2975,12 +3061,13 @@ uint64_t vram_region_gpu_offset(struct ttm_resource *res) int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec) { struct xe_device *xe = xe_bo_device(bo); + bool first_pin = !xe_bo_is_pinned(bo); int err; xe_assert(xe, !bo->vm); xe_assert(xe, xe_bo_is_user(bo)); - if (!xe_bo_is_pinned(bo)) { + if (first_pin) { if (!in_place) { err = xe_bo_validate(bo, NULL, false, exec); if (err) @@ -2992,9 +3079,7 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec) spin_unlock(&xe->pinned.lock); } - ttm_bo_pin(&bo->ttm); - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm)) - xe_ttm_tt_account_subtract(xe, bo->ttm.ttm); + xe_bo_pin_account(bo); /* * FIXME: If we always use the reserve / unreserve functions for locking @@ -3050,9 +3135,7 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec) spin_unlock(&xe->pinned.lock); } - ttm_bo_pin(&bo->ttm); - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm)) - xe_ttm_tt_account_subtract(xe, bo->ttm.ttm); + xe_bo_pin_account(bo); /* * FIXME: If we always use the reserve / unreserve functions for locking @@ -3081,14 +3164,7 @@ void xe_bo_unpin_external(struct xe_bo *bo) xe_assert(xe, xe_bo_is_pinned(bo)); xe_assert(xe, xe_bo_is_user(bo)); - spin_lock(&xe->pinned.lock); - if (bo->ttm.pin_count == 1 && !list_empty(&bo->pinned_link)) - list_del_init(&bo->pinned_link); - spin_unlock(&xe->pinned.lock); - - ttm_bo_unpin(&bo->ttm); - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm)) - xe_ttm_tt_account_add(xe, bo->ttm.ttm); + xe_bo_unpin_account(bo); /* * FIXME: If we always use the reserve / unreserve functions for locking @@ -3106,21 +3182,16 @@ void xe_bo_unpin(struct xe_bo *bo) xe_assert(xe, xe_bo_is_pinned(bo)); if (mem_type_is_vram(place->mem_type) || bo->flags & XE_BO_FLAG_GGTT) { - spin_lock(&xe->pinned.lock); xe_assert(xe, !list_empty(&bo->pinned_link)); - list_del_init(&bo->pinned_link); - spin_unlock(&xe->pinned.lock); if (bo->backup_obj) { if (xe_bo_is_pinned(bo->backup_obj)) - ttm_bo_unpin(&bo->backup_obj->ttm); + xe_bo_unpin_account(bo->backup_obj); xe_bo_put(bo->backup_obj); bo->backup_obj = NULL; } } - ttm_bo_unpin(&bo->ttm); - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm)) - xe_ttm_tt_account_add(xe, bo->ttm.ttm); + xe_bo_unpin_account(bo); } /** diff --git a/drivers/gpu/drm/xe/xe_bo.h b/drivers/gpu/drm/xe/xe_bo.h index a9e5e1bb8e4f7d..f9c8c73a1e69ca 100644 --- a/drivers/gpu/drm/xe/xe_bo.h +++ b/drivers/gpu/drm/xe/xe_bo.h @@ -228,6 +228,8 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec); int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec); void xe_bo_unpin_external(struct xe_bo *bo); void xe_bo_unpin(struct xe_bo *bo); +void xe_bo_pin_account(struct xe_bo *bo); +void xe_bo_unpin_account(struct xe_bo *bo); int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict, struct drm_exec *exec); diff --git a/drivers/gpu/drm/xe/xe_i2c.c b/drivers/gpu/drm/xe/xe_i2c.c index b376a9167cc1c8..3127fb89d965fa 100644 --- a/drivers/gpu/drm/xe/xe_i2c.c +++ b/drivers/gpu/drm/xe/xe_i2c.c @@ -330,12 +330,15 @@ static void xe_i2c_remove(void *data) xe_i2c_irq_reset(xe); xe_amc_exit(i2c); + /* Stop the notifier from arming the client work before teardown. */ + bus_unregister_notifier(&i2c_bus_type, &i2c->bus_notifier); + cancel_work_sync(&i2c->work); + for (i = 0; i < XE_I2C_MAX_CLIENTS; i++) { i2c_unregister_device(i2c->client[i]); i2c->client[i] = NULL; } - bus_unregister_notifier(&i2c_bus_type, &i2c->bus_notifier); xe_i2c_unregister_adapter(i2c); xe->i2c = NULL; } diff --git a/drivers/gpu/drm/xe/xe_lrc.c b/drivers/gpu/drm/xe/xe_lrc.c index 9f8217ff1904ca..224e64bccaebc6 100644 --- a/drivers/gpu/drm/xe/xe_lrc.c +++ b/drivers/gpu/drm/xe/xe_lrc.c @@ -1099,8 +1099,7 @@ static void xe_lrc_finish(struct xe_lrc *lrc) #define CONTEXT_ACTIVE XE_LRC_CTX_TIMESTAMP_ACTIVE static ssize_t setup_utilization_wa(struct xe_lrc *lrc, struct xe_hw_engine *hwe, - u32 *batch, - size_t max_len) + u32 *batch, size_t max_len, bool indirect) { u32 *cmd = batch; @@ -1131,19 +1130,25 @@ static ssize_t setup_utilization_wa(struct xe_lrc *lrc, } static ssize_t setup_timestamp_wa(struct xe_lrc *lrc, struct xe_hw_engine *hwe, - u32 *batch, size_t max_len) + u32 *batch, size_t max_len, bool indirect) { const u32 ts_addr = __xe_lrc_ctx_timestamp_ggtt_addr(lrc); u32 *cmd = batch; - if (!XE_GT_WA(lrc->gt, 16010904313) || - !(hwe->class == XE_ENGINE_CLASS_RENDER || - hwe->class == XE_ENGINE_CLASS_COMPUTE || - hwe->class == XE_ENGINE_CLASS_COPY || + if (!XE_GT_WA(lrc->gt, 16010904313)) + return 0; + + if (!indirect && + !(hwe->class == XE_ENGINE_CLASS_COPY || hwe->class == XE_ENGINE_CLASS_VIDEO_DECODE || hwe->class == XE_ENGINE_CLASS_VIDEO_ENHANCE)) return 0; + if (indirect && + !(hwe->class == XE_ENGINE_CLASS_RENDER || + hwe->class == XE_ENGINE_CLASS_COMPUTE)) + return 0; + if (xe_gt_WARN_ON(lrc->gt, max_len < 12)) return -ENOSPC; @@ -1169,7 +1174,8 @@ static ssize_t setup_timestamp_wa(struct xe_lrc *lrc, struct xe_hw_engine *hwe, static ssize_t setup_configfs_post_ctx_restore_bb(struct xe_lrc *lrc, struct xe_hw_engine *hwe, - u32 *batch, size_t max_len) + u32 *batch, size_t max_len, + bool indirect) { struct xe_device *xe = gt_to_xe(lrc->gt); const u32 *user_batch; @@ -1198,7 +1204,8 @@ static ssize_t setup_configfs_post_ctx_restore_bb(struct xe_lrc *lrc, static ssize_t setup_configfs_mid_ctx_restore_bb(struct xe_lrc *lrc, struct xe_hw_engine *hwe, - u32 *batch, size_t max_len) + u32 *batch, size_t max_len, + bool indirect) { struct xe_device *xe = gt_to_xe(lrc->gt); const u32 *user_batch; @@ -1227,7 +1234,8 @@ static ssize_t setup_configfs_mid_ctx_restore_bb(struct xe_lrc *lrc, static ssize_t setup_invalidate_state_cache_wa(struct xe_lrc *lrc, struct xe_hw_engine *hwe, - u32 *batch, size_t max_len) + u32 *batch, size_t max_len, + bool indirect) { u32 *cmd = batch; @@ -1247,7 +1255,8 @@ static ssize_t setup_invalidate_state_cache_wa(struct xe_lrc *lrc, static ssize_t setup_invalidate_auxccs_wa(struct xe_lrc *lrc, struct xe_hw_engine *hwe, - u32 *batch, size_t max_len) + u32 *batch, size_t max_len, + bool indirect) { struct xe_gt *gt = lrc->gt; u32 *(*emit)(struct xe_gt *gt, u32 *cmd) = @@ -1264,7 +1273,7 @@ static ssize_t setup_invalidate_auxccs_wa(struct xe_lrc *lrc, struct bo_setup { ssize_t (*setup)(struct xe_lrc *lrc, struct xe_hw_engine *hwe, - u32 *batch, size_t max_size); + u32 *batch, size_t max_size, bool indirect); }; struct bo_setup_state { @@ -1273,6 +1282,7 @@ struct bo_setup_state { struct xe_hw_engine *hwe; size_t max_size; size_t reserve_dw; + bool indirect; unsigned int offset; const struct bo_setup *funcs; unsigned int num_funcs; @@ -1298,7 +1308,8 @@ static int setup_bo(struct bo_setup_state *state) for (size_t i = 0; i < state->num_funcs; i++) { ssize_t len = state->funcs[i].setup(state->lrc, state->hwe, - state->ptr, remain); + state->ptr, remain, + state->indirect); remain -= len; @@ -1404,6 +1415,7 @@ setup_indirect_ctx(struct xe_lrc *lrc, struct xe_hw_engine *hwe) struct bo_setup_state state = { .lrc = lrc, .hwe = hwe, + .indirect = true, .max_size = (63 * 64) /* max 63 cachelines */, .buffer = NULL, .offset = __xe_lrc_indirect_ctx_offset(lrc), diff --git a/drivers/gpu/drm/xe/xe_mmio.c b/drivers/gpu/drm/xe/xe_mmio.c index 78adb303b66303..6907c1127d3266 100644 --- a/drivers/gpu/drm/xe/xe_mmio.c +++ b/drivers/gpu/drm/xe/xe_mmio.c @@ -288,6 +288,7 @@ u64 xe_mmio_read64_2x32(struct xe_mmio *mmio, struct xe_reg reg) return (u64)udw << 32 | ldw; } +#define __XE_MMIO_WAIT_MAX_BACKOFF_100MS (100 * USEC_PER_MSEC) static int __xe_mmio_wait32(struct xe_mmio *mmio, struct xe_reg reg, u32 mask, u32 val, u32 timeout_us, u32 *out_val, bool atomic, bool expect_match) { @@ -318,10 +319,10 @@ static int __xe_mmio_wait32(struct xe_mmio *mmio, struct xe_reg reg, u32 mask, u wait = ktime_us_delta(end, cur); if (atomic) - udelay(wait); + udelay(min_t(s64, wait, (MAX_UDELAY_MS * 1000))); else usleep_range(wait, wait << 1); - wait <<= 1; + wait = min_t(s64, wait << 1, __XE_MMIO_WAIT_MAX_BACKOFF_100MS); } if (ret != 0) { diff --git a/drivers/gpu/drm/xe/xe_sysctrl_mailbox.c b/drivers/gpu/drm/xe/xe_sysctrl_mailbox.c index 72baf1aa4b3ad6..a0179e62abaaf0 100644 --- a/drivers/gpu/drm/xe/xe_sysctrl_mailbox.c +++ b/drivers/gpu/drm/xe/xe_sysctrl_mailbox.c @@ -19,20 +19,20 @@ #include "xe_sysctrl_mailbox_types.h" struct xe_sysctrl_mailbox_msg_hdr { - __le32 data; -} __packed; + u32 data; +}; #define XE_SYSCTRL_HDR_GROUP_ID(hdr) \ - FIELD_GET(SYSCTRL_HDR_GROUP_ID_MASK, le32_to_cpu((hdr)->data)) + FIELD_GET(SYSCTRL_HDR_GROUP_ID_MASK, (hdr)->data) #define XE_SYSCTRL_HDR_COMMAND(hdr) \ - FIELD_GET(SYSCTRL_HDR_COMMAND_MASK, le32_to_cpu((hdr)->data)) + FIELD_GET(SYSCTRL_HDR_COMMAND_MASK, (hdr)->data) #define XE_SYSCTRL_HDR_IS_RESPONSE(hdr) \ - FIELD_GET(SYSCTRL_HDR_IS_RESPONSE, le32_to_cpu((hdr)->data)) + FIELD_GET(SYSCTRL_HDR_IS_RESPONSE, (hdr)->data) #define XE_SYSCTRL_HDR_RESULT(hdr) \ - FIELD_GET(SYSCTRL_HDR_RESULT_MASK, le32_to_cpu((hdr)->data)) + FIELD_GET(SYSCTRL_HDR_RESULT_MASK, (hdr)->data) static bool sysctrl_wait_bit_clear(struct xe_sysctrl *sc, u32 bit_mask, unsigned int timeout_ms) @@ -126,8 +126,8 @@ static int sysctrl_prepare_command(struct xe_device *xe, return -ENOMEM; hdr = (struct xe_sysctrl_mailbox_msg_hdr *)buffer; - hdr->data = cpu_to_le32(FIELD_PREP(SYSCTRL_HDR_GROUP_ID_MASK, group_id) | - FIELD_PREP(SYSCTRL_HDR_COMMAND_MASK, command)); + hdr->data = FIELD_PREP(SYSCTRL_HDR_GROUP_ID_MASK, group_id) | + FIELD_PREP(SYSCTRL_HDR_COMMAND_MASK, command); if (data_in && data_in_len) memcpy(buffer + sizeof(*hdr), data_in, data_in_len); diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid.c b/drivers/hid/dockchannel-hid/dockchannel-hid.c index bb19561562ab79..e47de457f7f04f 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid.c @@ -1267,6 +1267,7 @@ static int dockchannel_hid_probe(struct platform_device *pdev) struct device *dev = &pdev->dev; struct dockchannel_hid *dchid; struct device_node *child, *helper; + struct fwnode_handle *stm; struct platform_device *helper_pdev; struct property *prop; int ret; @@ -1281,6 +1282,9 @@ static int dockchannel_hid_probe(struct platform_device *pdev) } dchid->dev = dev; + stm = device_get_named_child_node(dev, "stm"); + dchid->id_ready = !stm || !fwnode_device_is_available(stm); + fwnode_handle_put(stm); /* * The STM interface reports the machine's vendor and product IDs, @@ -1394,8 +1398,7 @@ static int dockchannel_hid_probe(struct platform_device *pdev) if (ret) dev_warn(dev, "Failed to set up wakeup: %d\n", ret); - dchid->new_iface_wq = alloc_workqueue("dchid-new", - WQ_UNBOUND | WQ_MEM_RECLAIM, 0); + dchid->new_iface_wq = alloc_ordered_workqueue("dchid-new", 0); if (!dchid->new_iface_wq) return -ENOMEM; diff --git a/drivers/hid/hid-steam.c b/drivers/hid/hid-steam.c index 80d2eabc930eca..84c90091d45fcd 100644 --- a/drivers/hid/hid-steam.c +++ b/drivers/hid/hid-steam.c @@ -327,12 +327,14 @@ struct steam_device { spinlock_t lock; struct hid_device *hdev, *client_hdev; struct mutex report_mutex; + struct mutex registration_mutex; unsigned long client_opened; struct input_dev __rcu *input; struct input_dev __rcu *sensors; unsigned long quirks; struct work_struct work_connect; bool connected; + bool registered; char serial_no[STEAM_SERIAL_LEN + 1]; struct power_supply_desc battery_desc; struct power_supply __rcu *battery; @@ -346,7 +348,6 @@ struct steam_device { u16 rumble_right; unsigned int sensor_timestamp_us; unsigned int sensor_update_rate_us; - struct work_struct unregister_work; }; static int steam_recv_report(struct steam_device *steam, @@ -510,7 +511,6 @@ static int steam_get_serial(struct steam_device *steam) u8 cmd[] = {ID_GET_STRING_ATTRIBUTE, sizeof(steam->serial_no), ATTRIB_STR_UNIT_SERIAL}; u8 reply[3 + STEAM_SERIAL_LEN + 1]; - guard(mutex)(&steam->report_mutex); ret = steam_send_report(steam, cmd, sizeof(cmd)); if (ret < 0) return ret; @@ -537,7 +537,6 @@ static int steam_get_attributes(struct steam_device *steam) int i; struct steam_controller_attribute *attr; - guard(mutex)(&steam->report_mutex); ret = steam_send_report(steam, cmd, sizeof(cmd)); if (ret < 0) return ret; @@ -599,9 +598,7 @@ static inline int steam_haptic_pulse(struct steam_device *steam, u8 pad, report[8] = count >> 8; report[9] = gain; - mutex_lock(&steam->report_mutex); ret = steam_send_report(steam, report, sizeof(report)); - mutex_unlock(&steam->report_mutex); return ret; } @@ -621,9 +618,7 @@ static inline int steam_haptic_rumble(struct steam_device *steam, report[9] = left_gain; report[10] = right_gain; - mutex_lock(&steam->report_mutex); ret = steam_send_report(steam, report, sizeof(report)); - mutex_unlock(&steam->report_mutex); return ret; } @@ -631,8 +626,11 @@ static void steam_haptic_rumble_cb(struct work_struct *work) { struct steam_device *steam = container_of(work, struct steam_device, rumble_work); + + mutex_lock(&steam->report_mutex); steam_haptic_rumble(steam, 0, steam->rumble_left, steam->rumble_right, 2, 0); + mutex_unlock(&steam->report_mutex); } #ifdef CONFIG_STEAM_FF @@ -653,7 +651,6 @@ static void steam_set_lizard_mode(struct steam_device *steam, bool enable) if (steam->gamepad_mode) enable = false; - mutex_lock(&steam->report_mutex); if (enable) { /* enable esc, enter, cursors */ steam_send_report_byte(steam, ID_SET_DEFAULT_DIGITAL_MAPPINGS); @@ -678,14 +675,13 @@ static void steam_set_lizard_mode(struct steam_device *steam, bool enable) 0); } } - mutex_unlock(&steam->report_mutex); } static int steam_input_open(struct input_dev *dev) { struct steam_device *steam = input_get_drvdata(dev); unsigned long flags; - bool set_lizard_mode; + bool client_opened; /* * Disabling lizard mode automatically is only done on the Steam @@ -694,9 +690,10 @@ static int steam_input_open(struct input_dev *dev) */ if (!(steam->quirks & STEAM_QUIRK_DECK)) { spin_lock_irqsave(&steam->lock, flags); - set_lizard_mode = !steam->client_opened && lizard_mode; + client_opened = steam->client_opened; spin_unlock_irqrestore(&steam->lock, flags); - if (set_lizard_mode) + guard(mutex)(&steam->report_mutex); + if (!client_opened && lizard_mode) steam_set_lizard_mode(steam, false); } @@ -707,13 +704,14 @@ static void steam_input_close(struct input_dev *dev) { struct steam_device *steam = input_get_drvdata(dev); unsigned long flags; - bool set_lizard_mode; + bool client_opened; if (!(steam->quirks & STEAM_QUIRK_DECK)) { spin_lock_irqsave(&steam->lock, flags); - set_lizard_mode = !steam->client_opened && lizard_mode; + client_opened = steam->client_opened; spin_unlock_irqrestore(&steam->lock, flags); - if (set_lizard_mode) + guard(mutex)(&steam->report_mutex); + if (!client_opened && lizard_mode) steam_set_lizard_mode(steam, true); } } @@ -721,14 +719,11 @@ static void steam_input_close(struct input_dev *dev) static int steam_sensor_open(struct input_dev *dev) { struct steam_device *steam = input_get_drvdata(dev); - unsigned long flags; - bool client_opened; - spin_lock_irqsave(&steam->lock, flags); - client_opened = steam->client_opened; - spin_unlock_irqrestore(&steam->lock, flags); - if (client_opened) - return 0; + scoped_guard(spinlock_irqsave, &steam->lock) { + if (steam->client_opened) + return 0; + } guard(mutex)(&steam->report_mutex); steam_write_settings(steam, SETTING_IMU_MODE, @@ -741,14 +736,11 @@ static int steam_sensor_open(struct input_dev *dev) static void steam_sensor_close(struct input_dev *dev) { struct steam_device *steam = input_get_drvdata(dev); - unsigned long flags; - bool client_opened; - spin_lock_irqsave(&steam->lock, flags); - client_opened = steam->client_opened; - spin_unlock_irqrestore(&steam->lock, flags); - if (client_opened) - return; + scoped_guard(spinlock_irqsave, &steam->lock) { + if (steam->client_opened) + return; + } guard(mutex)(&steam->report_mutex); steam_write_settings(steam, SETTING_IMU_MODE, 0, 0); @@ -823,6 +815,7 @@ static int steam_battery_register(struct steam_device *steam) &steam->battery_desc, &battery_cfg); if (IS_ERR(battery)) { ret = PTR_ERR(battery); + devm_kfree(&steam->hdev->dev, steam->battery_desc.name); hid_err(steam->hdev, "%s:power_supply_register failed with error %d\n", __func__, ret); @@ -1082,103 +1075,117 @@ static void steam_battery_unregister(struct steam_device *steam) RCU_INIT_POINTER(steam->battery, NULL); synchronize_rcu(); power_supply_unregister(battery); + devm_kfree(&steam->hdev->dev, steam->battery_desc.name); } static int steam_register(struct steam_device *steam) { int ret; - unsigned long client_opened; - unsigned long flags; + mutex_lock(&steam->registration_mutex); /* * This function can be called several times in a row with the * wireless adaptor, without steam_unregister() between them, because * another client send a get_connection_status command, for example. * The battery and serial number are set just once per device. */ - if (!steam->serial_no[0]) { - /* - * Unlikely, but getting the serial could fail, and it is not so - * important, so make up a serial number and go on. - */ - if (steam_get_serial(steam) < 0) - strscpy(steam->serial_no, "XXXXXXXXXX", - sizeof(steam->serial_no)); + if (steam->registered) { + mutex_unlock(&steam->registration_mutex); + return 0; + } - ret = steam_get_attributes(steam); - if (ret < 0) - hid_err(steam->hdev, - "%s:steam_get_attributes failed with error %d\n", - __func__, ret); + mutex_lock(&steam->report_mutex); + /* + * Unlikely, but getting the serial could fail, and it is not so + * important, so make up a serial number and go on. + */ + if (steam_get_serial(steam) < 0 || !steam->serial_no[0]) + strscpy(steam->serial_no, "XXXXXXXXXX", + sizeof(steam->serial_no)); - hid_info(steam->hdev, "Steam Controller '%s' connected", - steam->serial_no); + ret = steam_get_attributes(steam); + if (ret < 0) + hid_err(steam->hdev, + "%s:steam_get_attributes failed with error %d\n", + __func__, ret); - /* ignore battery errors, we can live without it */ - if (steam->quirks & STEAM_QUIRK_WIRELESS) - steam_battery_register(steam); + hid_info(steam->hdev, "Steam Controller '%s' connected", + steam->serial_no); - mutex_lock(&steam_devices_lock); - if (list_empty(&steam->list)) - list_add(&steam->list, &steam_devices); - mutex_unlock(&steam_devices_lock); - } + steam_set_lizard_mode(steam, lizard_mode); + mutex_unlock(&steam->report_mutex); - spin_lock_irqsave(&steam->lock, flags); - client_opened = steam->client_opened; - spin_unlock_irqrestore(&steam->lock, flags); + /* ignore battery errors, we can live without it */ + if (steam->quirks & STEAM_QUIRK_WIRELESS) + steam_battery_register(steam); - if (!client_opened) { - steam_set_lizard_mode(steam, lizard_mode); - ret = steam_input_register(steam); - if (ret != 0) - goto steam_register_input_fail; - ret = steam_sensors_register(steam); - if (ret != 0) - goto steam_register_sensors_fail; - } + ret = steam_input_register(steam); + if (ret != 0) + goto steam_register_input_fail; + ret = steam_sensors_register(steam); + if (ret != 0) + goto steam_register_sensors_fail; + + steam->registered = true; + mutex_unlock(&steam->registration_mutex); + mutex_lock(&steam_devices_lock); + if (list_empty(&steam->list)) + list_add(&steam->list, &steam_devices); + mutex_unlock(&steam_devices_lock); return 0; steam_register_sensors_fail: steam_input_unregister(steam); steam_register_input_fail: + steam_battery_unregister(steam); + mutex_unlock(&steam->registration_mutex); + cancel_work_sync(&steam->rumble_work); + cancel_delayed_work_sync(&steam->mode_switch); return ret; } static void steam_unregister(struct steam_device *steam) { + if (!steam->registered) + return; + + hid_info(steam->hdev, "Steam Controller '%s' disconnected", + steam->serial_no); + mutex_lock(&steam->registration_mutex); + steam->registered = false; steam_battery_unregister(steam); steam_sensors_unregister(steam); steam_input_unregister(steam); - if (steam->serial_no[0]) { - hid_info(steam->hdev, "Steam Controller '%s' disconnected", - steam->serial_no); - mutex_lock(&steam_devices_lock); - list_del_init(&steam->list); - mutex_unlock(&steam_devices_lock); - steam->serial_no[0] = 0; - } + mutex_unlock(&steam->registration_mutex); + cancel_work_sync(&steam->rumble_work); + cancel_delayed_work_sync(&steam->mode_switch); + mutex_lock(&steam_devices_lock); + list_del_init(&steam->list); + mutex_unlock(&steam_devices_lock); + steam->serial_no[0] = 0; } static void steam_work_connect_cb(struct work_struct *work) { struct steam_device *steam = container_of(work, struct steam_device, work_connect); + unsigned long flags; bool connected; + bool opened; int ret; spin_lock_irqsave(&steam->lock, flags); + opened = steam->client_opened; connected = steam->connected; spin_unlock_irqrestore(&steam->lock, flags); - if (connected) { + if (connected && !opened) { ret = steam_register(steam); - if (ret) { + if (ret) hid_err(steam->hdev, "%s:steam_register failed with error %d\n", __func__, ret); - } } else { steam_unregister(steam); } @@ -1190,54 +1197,32 @@ static void steam_mode_switch_cb(struct work_struct *work) struct steam_device, mode_switch); unsigned long flags; bool client_opened; + bool gamepad_mode; + if (!lizard_mode) return; + spin_lock_irqsave(&steam->lock, flags); steam->gamepad_mode = !steam->gamepad_mode; - hid_dbg(steam->hdev, "%s: switching gamepad mode to %i\n", __func__, steam->gamepad_mode); - if (steam->gamepad_mode) + gamepad_mode = steam->gamepad_mode; + client_opened = steam->client_opened; + spin_unlock_irqrestore(&steam->lock, flags); + + guard(mutex)(&steam->report_mutex); + hid_dbg(steam->hdev, "%s: switching gamepad mode to %i\n", __func__, gamepad_mode); + if (gamepad_mode) steam_set_lizard_mode(steam, false); - else { - spin_lock_irqsave(&steam->lock, flags); - client_opened = steam->client_opened; - spin_unlock_irqrestore(&steam->lock, flags); - if (!client_opened) - steam_set_lizard_mode(steam, lizard_mode); - } + else if (!client_opened) + steam_set_lizard_mode(steam, lizard_mode); steam_haptic_pulse(steam, STEAM_PAD_RIGHT, 0x190, 0, 1, 0); - if (steam->gamepad_mode) { + if (gamepad_mode) { steam_haptic_pulse(steam, STEAM_PAD_LEFT, 0x14D, 0x14D, 0x2D, 0); } else { steam_haptic_pulse(steam, STEAM_PAD_LEFT, 0x1F4, 0x1F4, 0x1E, 0); } } -static void steam_work_unregister_cb(struct work_struct *work) -{ - struct steam_device *steam = container_of(work, struct steam_device, - unregister_work); - unsigned long flags; - bool connected; - bool opened; - - spin_lock_irqsave(&steam->lock, flags); - opened = steam->client_opened; - connected = steam->connected; - spin_unlock_irqrestore(&steam->lock, flags); - - if (connected) { - if (opened) { - steam_sensors_unregister(steam); - steam_input_unregister(steam); - } else { - steam_set_lizard_mode(steam, lizard_mode); - steam_input_register(steam); - steam_sensors_register(steam); - } - } -} - static bool steam_is_valve_interface(struct hid_device *hdev) { struct hid_report_enum *rep_enum; @@ -1283,7 +1268,7 @@ static int steam_client_ll_open(struct hid_device *hdev) steam->client_opened++; spin_unlock_irqrestore(&steam->lock, flags); - schedule_work(&steam->unregister_work); + schedule_work(&steam->work_connect); return 0; } @@ -1298,7 +1283,7 @@ static void steam_client_ll_close(struct hid_device *hdev) steam->client_opened--; spin_unlock_irqrestore(&steam->lock, flags); - schedule_work(&steam->unregister_work); + schedule_work(&steam->work_connect); } static int steam_client_ll_raw_request(struct hid_device *hdev, @@ -1384,6 +1369,7 @@ static int steam_probe(struct hid_device *hdev, hid_set_drvdata(hdev, steam); spin_lock_init(&steam->lock); mutex_init(&steam->report_mutex); + mutex_init(&steam->registration_mutex); steam->quirks = id->driver_data; INIT_WORK(&steam->work_connect, steam_work_connect_cb); INIT_DELAYED_WORK(&steam->mode_switch, steam_mode_switch_cb); @@ -1394,7 +1380,6 @@ static int steam_probe(struct hid_device *hdev, steam->sensor_update_rate_us = 4000; else steam->sensor_update_rate_us = 9000; - INIT_WORK(&steam->unregister_work, steam_work_unregister_cb); /* * With the real steam controller interface, do not connect hidraw. @@ -1455,7 +1440,6 @@ static int steam_probe(struct hid_device *hdev, cancel_work_sync(&steam->work_connect); cancel_delayed_work_sync(&steam->mode_switch); cancel_work_sync(&steam->rumble_work); - cancel_work_sync(&steam->unregister_work); return ret; } @@ -1463,36 +1447,32 @@ static int steam_probe(struct hid_device *hdev, static void steam_remove(struct hid_device *hdev) { struct steam_device *steam = hid_get_drvdata(hdev); + unsigned long flags; if (!steam || hdev->group == HID_GROUP_STEAM) { hid_hw_stop(hdev); return; } + hid_hw_close(hdev); hid_destroy_device(steam->client_hdev); - cancel_delayed_work_sync(&steam->mode_switch); - cancel_work_sync(&steam->work_connect); - cancel_work_sync(&steam->rumble_work); - cancel_work_sync(&steam->unregister_work); - steam->client_hdev = NULL; + spin_lock_irqsave(&steam->lock, flags); steam->client_opened = 0; + spin_unlock_irqrestore(&steam->lock, flags); + cancel_work_sync(&steam->work_connect); if (steam->quirks & STEAM_QUIRK_WIRELESS) { hid_info(hdev, "Steam wireless receiver disconnected"); } - hid_hw_close(hdev); - hid_hw_stop(hdev); steam_unregister(steam); + hid_hw_stop(hdev); } static void steam_do_connect_event(struct steam_device *steam, bool connected) { - unsigned long flags; bool changed; - spin_lock_irqsave(&steam->lock, flags); changed = steam->connected != connected; steam->connected = connected; - spin_unlock_irqrestore(&steam->lock, flags); if (changed && schedule_work(&steam->work_connect) == 0) dbg_hid("%s: connected=%d event already queued\n", @@ -1921,8 +1901,6 @@ static void steam_do_deck_sensors_event(struct steam_device *steam, static void steam_do_battery_event(struct steam_device *steam, struct power_supply *battery, u8 *data) { - unsigned long flags; - s16 volts = steam_le16(data + 12); u8 batt = data[14]; @@ -1930,10 +1908,8 @@ static void steam_do_battery_event(struct steam_device *steam, rcu_read_lock(); battery = rcu_dereference(steam->battery); if (likely(battery)) { - spin_lock_irqsave(&steam->lock, flags); steam->voltage = volts; steam->battery_charge = batt; - spin_unlock_irqrestore(&steam->lock, flags); power_supply_changed(battery); } rcu_read_unlock(); @@ -1951,6 +1927,7 @@ static int steam_raw_event(struct hid_device *hdev, if (!steam) return 0; + guard(spinlock_irqsave)(&steam->lock); if (steam->client_opened) hid_input_report(steam->client_hdev, HID_FEATURE_REPORT, data, size, 0); @@ -2038,6 +2015,8 @@ static int steam_param_set_lizard_mode(const char *val, { struct steam_device *steam; int ret; + bool client_opened; + unsigned long flags; ret = param_set_bool(val, kp); if (ret) @@ -2045,8 +2024,13 @@ static int steam_param_set_lizard_mode(const char *val, mutex_lock(&steam_devices_lock); list_for_each_entry(steam, &steam_devices, list) { - if (!steam->client_opened) + spin_lock_irqsave(&steam->lock, flags); + client_opened = steam->client_opened; + spin_unlock_irqrestore(&steam->lock, flags); + if (!client_opened) { + guard(mutex)(&steam->report_mutex); steam_set_lizard_mode(steam, lizard_mode); + } } mutex_unlock(&steam_devices_lock); return 0; diff --git a/drivers/input/joystick/xpad.c b/drivers/input/joystick/xpad.c index 6406ceab988ade..810e52782ae891 100644 --- a/drivers/input/joystick/xpad.c +++ b/drivers/input/joystick/xpad.c @@ -302,6 +302,8 @@ static const struct xpad_device { { 0x17ef, 0x6182, "Lenovo Legion Controller for Windows", 0, XTYPE_XBOX360 }, { 0x1949, 0x041a, "Amazon Game Controller", 0, XTYPE_XBOX360 }, { 0x1a86, 0xe310, "Legion Go S", 0, XTYPE_XBOX360 }, + { 0x1b1c, 0x2b1f, "Corsair Novablade Pro (Wired)", 0, XTYPE_XBOX360 }, + { 0x1b1c, 0x2b2b, "Corsair Novablade Pro (2.4 GHz Receiver)", 0, XTYPE_XBOX360 }, { 0x1bad, 0x0002, "Harmonix Rock Band Guitar", 0, XTYPE_XBOX360 }, { 0x1bad, 0x0003, "Harmonix Rock Band Drumkit", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 }, { 0x1bad, 0x0130, "Ion Drum Rocker", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 }, @@ -379,6 +381,7 @@ static const struct xpad_device { { 0x2993, 0x2001, "TECNO Pocket Go", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x2000, "8BitDo Pro 2 Wired Controller fox Xbox", 0, XTYPE_XBOXONE }, { 0x2dc8, 0x200f, "8BitDo Ultimate 3-mode Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, + { 0x2dc8, 0x201e, "8BitDo Pro 2 Wired Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x3106, "8BitDo Ultimate Wireless / Pro 2 Wired Controller", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x3109, "8BitDo Ultimate Wireless Bluetooth", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x310a, "8BitDo Ultimate 2C Wireless Controller", 0, XTYPE_XBOX360 }, @@ -545,6 +548,7 @@ static const struct usb_device_id xpad_table[] = { XPAD_XBOX360_VENDOR(0x17ef), /* Lenovo */ XPAD_XBOX360_VENDOR(0x1949), /* Amazon controllers */ XPAD_XBOX360_VENDOR(0x1a86), /* Nanjing Qinheng Microelectronics (WCH) */ + XPAD_XBOX360_VENDOR(0x1b1c), /* Corsair controllers */ XPAD_XBOX360_VENDOR(0x1bad), /* Harmonix Rock Band guitar and drums */ XPAD_XBOX360_VENDOR(0x1ee9), /* ZOTAC Technology Limited */ XPAD_XBOX360_VENDOR(0x20bc), /* BETOP wireless dongles */ diff --git a/drivers/input/misc/ati_remote2.c b/drivers/input/misc/ati_remote2.c index 8db2dca84975ca..3e0f874e9b16fc 100644 --- a/drivers/input/misc/ati_remote2.c +++ b/drivers/input/misc/ati_remote2.c @@ -672,8 +672,7 @@ static ssize_t ati_remote2_show_channel_mask(struct device *dev, struct device_attribute *attr, char *buf) { - struct usb_device *udev = to_usb_device(dev); - struct usb_interface *intf = usb_ifnum_to_if(udev, 0); + struct usb_interface *intf = to_usb_interface(dev); struct ati_remote2 *ar2 = usb_get_intfdata(intf); return sprintf(buf, "0x%04x\n", ar2->channel_mask); @@ -683,8 +682,7 @@ static ssize_t ati_remote2_store_channel_mask(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct usb_device *udev = to_usb_device(dev); - struct usb_interface *intf = usb_ifnum_to_if(udev, 0); + struct usb_interface *intf = to_usb_interface(dev); struct ati_remote2 *ar2 = usb_get_intfdata(intf); unsigned int mask; int r; @@ -720,8 +718,7 @@ static ssize_t ati_remote2_show_mode_mask(struct device *dev, struct device_attribute *attr, char *buf) { - struct usb_device *udev = to_usb_device(dev); - struct usb_interface *intf = usb_ifnum_to_if(udev, 0); + struct usb_interface *intf = to_usb_interface(dev); struct ati_remote2 *ar2 = usb_get_intfdata(intf); return sprintf(buf, "0x%02x\n", ar2->mode_mask); @@ -731,8 +728,7 @@ static ssize_t ati_remote2_store_mode_mask(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct usb_device *udev = to_usb_device(dev); - struct usb_interface *intf = usb_ifnum_to_if(udev, 0); + struct usb_interface *intf = to_usb_interface(dev); struct ati_remote2 *ar2 = usb_get_intfdata(intf); unsigned int mask; int err; diff --git a/drivers/iommu/dma-iommu.c b/drivers/iommu/dma-iommu.c index c624d36cd106ad..d71802242992f7 100644 --- a/drivers/iommu/dma-iommu.c +++ b/drivers/iommu/dma-iommu.c @@ -1233,9 +1233,9 @@ dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size, * If both the physical buffer start address and size are page aligned, * we don't need to use a bounce page. */ - if (dev_use_swiotlb(dev, size, dir) && + if (!(attrs & DMA_ATTR_MMIO) && dev_use_swiotlb(dev, size, dir) && iova_unaligned(iovad, phys, size)) { - if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT)) + if (attrs & DMA_ATTR_REQUIRE_COHERENT) return DMA_MAPPING_ERROR; phys = iommu_dma_map_swiotlb(dev, phys, size, dir, attrs); diff --git a/drivers/md/dm-crypt.c b/drivers/md/dm-crypt.c index 608b617fb817ff..ee36789a7f0d8a 100644 --- a/drivers/md/dm-crypt.c +++ b/drivers/md/dm-crypt.c @@ -2895,8 +2895,13 @@ static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key } } - if (*ivmode && !strcmp(*ivmode, "lmk")) + if (*ivmode && !strcmp(*ivmode, "lmk")) { + if (crypt_integrity_aead(cc)) { + ti->error = "AEAD transforms not supported for LMK"; + return -EINVAL; + } cc->tfms_count = 64; + } if (*ivmode && !strcmp(*ivmode, "essiv")) { if (!*ivopts) { diff --git a/drivers/md/dm-integrity.c b/drivers/md/dm-integrity.c index 86fc35e76a0f7a..4bda7b5dba1a64 100644 --- a/drivers/md/dm-integrity.c +++ b/drivers/md/dm-integrity.c @@ -2721,7 +2721,7 @@ static void dm_integrity_inline_recheck(struct work_struct *w) outgoing_data = dio->integrity_payload + PAGE_SIZE; while (dio->bio_details.bi_iter.bi_size) { - char digest[HASH_MAX_DIGESTSIZE]; + char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)]; int r; struct bio_integrity_payload *bip; struct bio_vec bv; @@ -2788,7 +2788,7 @@ static inline bool dm_integrity_check(struct dm_integrity_c *ic, struct dm_integ unsigned pos = 0; while (dio->bio_details.bi_iter.bi_size) { - char digest[HASH_MAX_DIGESTSIZE]; + char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)]; struct bio_vec bv = bio_iter_iovec(bio, dio->bio_details.bi_iter); char *mem = integrity_kmap(ic, bv.bv_page); integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, mem, bv.bv_offset, digest); diff --git a/drivers/md/dm-ioctl.c b/drivers/md/dm-ioctl.c index 61af2a437a0508..d3430825acad10 100644 --- a/drivers/md/dm-ioctl.c +++ b/drivers/md/dm-ioctl.c @@ -658,10 +658,16 @@ static void *get_result_buffer(struct dm_ioctl *param, size_t param_size, { param->data_start = align_ptr(param + 1) - (void *) param; - if (param->data_start < param_size) + if (param->data_start < param_size) { *len = param_size - param->data_start; - else + } else { + /* + * The buffer can be as small as offsetof(*param, data), which + * is less than sizeof(*param), so don't run off the end of it. + */ *len = 0; + param->data_start = param_size; + } return ((void *) param) + param->data_start; } @@ -1289,6 +1295,7 @@ static int do_resume(struct dm_ioctl *param) /* Do we need to load a new map ? */ if (new_map) { sector_t old_size, new_size; + blk_mode_t new_map_mode; dm_ima_context_table_op(md, ima_context, DM_IMA_TABLE_SAVE); /* Suspend if it isn't already suspended */ @@ -1321,6 +1328,7 @@ static int do_resume(struct dm_ioctl *param) } } + new_map_mode = dm_table_get_mode(new_map); old_size = dm_get_size(md); old_map = dm_swap_table(md, new_map); if (IS_ERR(old_map)) { @@ -1336,7 +1344,7 @@ static int do_resume(struct dm_ioctl *param) if (old_size && new_size && old_size != new_size) need_resize_uevent = true; - if (dm_table_get_mode(new_map) & BLK_OPEN_WRITE) + if (new_map_mode & BLK_OPEN_WRITE) set_disk_ro(dm_disk(md), 0); else set_disk_ro(dm_disk(md), 1); diff --git a/drivers/md/dm-snap.c b/drivers/md/dm-snap.c index 1489fda9d24a09..02e3cc4730267a 100644 --- a/drivers/md/dm-snap.c +++ b/drivers/md/dm-snap.c @@ -1294,6 +1294,20 @@ static int snapshot_ctr(struct dm_target *ti, unsigned int argc, char **argv) goto bad_store; } + /* + * snapshot-merge requires the optional prepare_merge/commit_merge + * callbacks; the transient exception store does not implement them. + * The handover path checks this in __validate_exception_handover(), + * but a directly constructed snapshot-merge never goes through it. + */ + if (dm_target_is_snapshot_merge(ti) && + (!s->store->type->prepare_merge || + !s->store->type->commit_merge)) { + ti->error = "Snapshot exception store does not support snapshot-merge."; + r = -EINVAL; + goto bad_hash_tables; + } + argv += args_used; argc -= args_used; diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 270ffb69965960..986855879c7bf7 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -23,6 +23,8 @@ #include "avd-inst.h" #include "avd-regs.h" +#define AVD_CODEC_INFO_MAX_SIZE 0x40 + static void calc_tile_meta(u32 w, u32 h, u32 bpb, u32 tile_dim, u32 meta_hdr_bytes, u32 *tile, u32 *meta) { @@ -833,6 +835,7 @@ static int avd_probe(struct platform_device *pdev) { struct avd_dev *avd; const struct of_device_id *match; + const char *codec_info = NULL; int ret, irq; avd = devm_kzalloc(&pdev->dev, sizeof(*avd), GFP_KERNEL); @@ -877,6 +880,30 @@ static int avd_probe(struct platform_device *pdev) return ret; } + /* Determine firmware and HW variant capabilities */ + if (avd->fw->size >= AVD_CODEC_INFO_MAX_SIZE) + codec_info = avd->fw->data + avd->fw->size - AVD_CODEC_INFO_MAX_SIZE; + if (codec_info && strncmp(codec_info, "CODECS:", 7) == 0) { + unsigned int caps = 0; + unsigned int variant_caps = avd->variant->capabilities; + + if (strnstr(codec_info, "av1", AVD_CODEC_INFO_MAX_SIZE)) + caps |= variant_caps & AVD_CAPABILITY_AV1; + if (strnstr(codec_info, "h264", AVD_CODEC_INFO_MAX_SIZE)) + caps |= variant_caps & AVD_CAPABILITY_H264; + if (strnstr(codec_info, "h265", AVD_CODEC_INFO_MAX_SIZE)) + caps |= variant_caps & AVD_CAPABILITY_HEVC; + if (strnstr(codec_info, "vp9", AVD_CODEC_INFO_MAX_SIZE)) + caps |= variant_caps & AVD_CAPABILITY_VP9; + + dev_info(avd->dev, "Firmware codecs: %.27s\n", codec_info + 7); + + avd->capabilities = caps; + } else { + /* Backward compatibility to old firmware, do not upstream. */ + avd->capabilities = avd->variant->capabilities; + } + ret = dma_set_mask_and_coherent(avd->dev, DMA_BIT_MASK((avd->variant->quirks & AVD_QUIRK_LSR) ? 38 : 64)); diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 9ab137883478a7..4622e920554864 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -457,7 +457,7 @@ static const struct avd_coded_fmt_desc avd_coded_fmts[] = { static bool avd_is_capable(struct avd_ctx *ctx, unsigned int capability) { - return (ctx->dev->variant->capabilities & capability) == capability; + return (ctx->dev->capabilities & capability) == capability; } static const struct avd_coded_fmt_desc * diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 09a607b6a57a23..fd77a0163e8c51 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -232,6 +232,7 @@ struct avd_dev { struct reset_control *rstc; const struct avd_variant *variant; + unsigned int capabilities; }; struct avd_segment { diff --git a/drivers/memstick/core/memstick.c b/drivers/memstick/core/memstick.c index e03989c4e99ea1..0d15f48ef51d4f 100644 --- a/drivers/memstick/core/memstick.c +++ b/drivers/memstick/core/memstick.c @@ -370,9 +370,7 @@ int memstick_set_rw_addr(struct memstick_dev *card) { card->next_request = h_memstick_set_rw_addr; memstick_new_req(card->host); - if (!wait_for_completion_timeout(&card->mrq_complete, - msecs_to_jiffies(500))) - card->current_mrq.error = -ETIMEDOUT; + wait_for_completion(&card->mrq_complete); return card->current_mrq.error; } @@ -405,9 +403,7 @@ static struct memstick_dev *memstick_alloc_card(struct memstick_host *host) card->next_request = h_memstick_read_dev_id; memstick_new_req(host); - if (!wait_for_completion_timeout(&card->mrq_complete, - msecs_to_jiffies(500))) - card->current_mrq.error = -ETIMEDOUT; + wait_for_completion(&card->mrq_complete); if (card->current_mrq.error) goto err_out; diff --git a/drivers/memstick/host/rtsx_usb_ms.c b/drivers/memstick/host/rtsx_usb_ms.c index beadc389f15f39..d5b3a96fc609a1 100644 --- a/drivers/memstick/host/rtsx_usb_ms.c +++ b/drivers/memstick/host/rtsx_usb_ms.c @@ -27,7 +27,6 @@ struct rtsx_usb_ms { struct memstick_host *msh; struct memstick_request *req; - struct mutex host_mutex; struct work_struct handle_req; struct delayed_work poll_card; @@ -514,6 +513,13 @@ static void rtsx_usb_ms_handle_req(struct work_struct *work) struct memstick_host *msh = host->msh; int rc; + /* Fail requests after eject so their waiters are released. */ + if (host->eject) { + while (!memstick_next_req(msh, &host->req)) + host->req->error = -ENOMEDIUM; + return; + } + if (!host->req) { pm_runtime_get_sync(ms_dev(host)); do { @@ -547,8 +553,7 @@ static void rtsx_usb_ms_request(struct memstick_host *msh) dev_dbg(ms_dev(host), "--> %s\n", __func__); - if (!host->eject) - schedule_work(&host->handle_req); + schedule_work(&host->handle_req); } static int rtsx_usb_ms_set_param(struct memstick_host *msh, @@ -781,7 +786,6 @@ static int rtsx_usb_ms_drv_probe(struct platform_device *pdev) host->power_mode = MEMSTICK_POWER_OFF; platform_set_drvdata(pdev, host); - mutex_init(&host->host_mutex); INIT_WORK(&host->handle_req, rtsx_usb_ms_handle_req); INIT_DELAYED_WORK(&host->poll_card, rtsx_usb_ms_poll_card); @@ -812,27 +816,12 @@ static void rtsx_usb_ms_drv_remove(struct platform_device *pdev) { struct rtsx_usb_ms *host = platform_get_drvdata(pdev); struct memstick_host *msh = host->msh; - int err; host->eject = true; msh->removing = true; - cancel_work_sync(&host->handle_req); + flush_work(&host->handle_req); cancel_delayed_work_sync(&host->poll_card); - mutex_lock(&host->host_mutex); - if (host->req) { - dev_dbg(ms_dev(host), - "%s: Controller removed during transfer\n", - dev_name(&msh->dev)); - host->req->error = -ENOMEDIUM; - do { - err = memstick_next_req(msh, &host->req); - if (!err) - host->req->error = -ENOMEDIUM; - } while (!err); - } - mutex_unlock(&host->host_mutex); - /* Balance possible unbalanced usage count * e.g. unconditional module removal */ @@ -841,6 +830,8 @@ static void rtsx_usb_ms_drv_remove(struct platform_device *pdev) pm_runtime_disable(ms_dev(host)); memstick_remove_host(msh); + /* No card, no new requests; wait for the last failed one to finish. */ + cancel_work_sync(&host->handle_req); dev_dbg(ms_dev(host), ": Realtek USB Memstick controller has been removed\n"); memstick_free_host(msh); diff --git a/drivers/mfd/Kconfig b/drivers/mfd/Kconfig index 4d7a7f0fe1ea53..9fd738df5db7be 100644 --- a/drivers/mfd/Kconfig +++ b/drivers/mfd/Kconfig @@ -351,7 +351,8 @@ config MFD_MACSMC_KUNIT_TEST Build tests for SMC key/value readers, request limits and metadata decoding. Static stubs replace mailbox commands and SRAM access, allowing malformed replies and output buffer limits to be checked - without a running SMC. + without a running SMC. Client driver tests can also replace + apple_smc_read() and apple_smc_write() with a model of their keys. config MFD_MADERA tristate "Cirrus Logic Madera codecs" diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index 55d52c684d38b8..fb9e1d7fa0ba7d 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -190,6 +190,9 @@ static int apple_smc_rw_locked(struct apple_smc *smc, smc_key key, int apple_smc_read(struct apple_smc *smc, smc_key key, void *buf, size_t size) { + if (IS_ENABLED(CONFIG_MFD_MACSMC_KUNIT_TEST)) + KUNIT_STATIC_STUB_REDIRECT(apple_smc_read, smc, key, buf, size); + guard(mutex)(&smc->mutex); return apple_smc_rw_locked(smc, key, NULL, 0, buf, size); @@ -198,6 +201,9 @@ EXPORT_SYMBOL(apple_smc_read); int apple_smc_write(struct apple_smc *smc, smc_key key, const void *buf, size_t size) { + if (IS_ENABLED(CONFIG_MFD_MACSMC_KUNIT_TEST)) + KUNIT_STATIC_STUB_REDIRECT(apple_smc_write, smc, key, buf, size); + guard(mutex)(&smc->mutex); return apple_smc_rw_locked(smc, key, buf, size, NULL, 0); diff --git a/drivers/mmc/host/cavium-octeon.c b/drivers/mmc/host/cavium-octeon.c index 8a0daddd9200ea..1c219cf35a8e4b 100644 --- a/drivers/mmc/host/cavium-octeon.c +++ b/drivers/mmc/host/cavium-octeon.c @@ -301,9 +301,12 @@ static void octeon_mmc_remove(struct platform_device *pdev) u64 dma_cfg; int i; - for (i = 0; i < CAVIUM_MAX_MMC; i++) + for (i = 0; i < CAVIUM_MAX_MMC; i++) { if (host->slot[i]) cvm_mmc_of_slot_remove(host->slot[i]); + if (host->slot_pdev[i]) + of_platform_device_destroy(&host->slot_pdev[i]->dev, NULL); + } dma_cfg = readq(host->dma_base + MIO_EMM_DMA_CFG(host)); dma_cfg &= ~MIO_EMM_DMA_CFG_EN; diff --git a/drivers/mmc/host/cavium-thunderx.c b/drivers/mmc/host/cavium-thunderx.c index 84ff6d82ae3c0a..2635ac94ec5da3 100644 --- a/drivers/mmc/host/cavium-thunderx.c +++ b/drivers/mmc/host/cavium-thunderx.c @@ -173,9 +173,12 @@ static void thunder_mmc_remove(struct pci_dev *pdev) u64 dma_cfg; int i; - for (i = 0; i < CAVIUM_MAX_MMC; i++) + for (i = 0; i < CAVIUM_MAX_MMC; i++) { if (host->slot[i]) cvm_mmc_of_slot_remove(host->slot[i]); + if (host->slot_pdev[i]) + of_platform_device_destroy(&host->slot_pdev[i]->dev, NULL); + } dma_cfg = readq(host->dma_base + MIO_EMM_DMA_CFG(host)); dma_cfg &= ~MIO_EMM_DMA_CFG_EN; diff --git a/drivers/mmc/host/mtk-sd.c b/drivers/mmc/host/mtk-sd.c index b2680cc054bda2..d70e37eb1cb59c 100644 --- a/drivers/mmc/host/mtk-sd.c +++ b/drivers/mmc/host/mtk-sd.c @@ -3216,6 +3216,7 @@ static void msdc_drv_remove(struct platform_device *pdev) platform_set_drvdata(pdev, NULL); mmc_remove_host(mmc); + cancel_delayed_work_sync(&host->req_timeout); msdc_deinit_hw(host); msdc_gate_clock(host); diff --git a/drivers/mmc/host/sdhci-sprd.c b/drivers/mmc/host/sdhci-sprd.c index 3584a2b314a9f9..0c8f389fe58471 100644 --- a/drivers/mmc/host/sdhci-sprd.c +++ b/drivers/mmc/host/sdhci-sprd.c @@ -890,6 +890,10 @@ static void sdhci_sprd_remove(struct platform_device *pdev) struct sdhci_host *host = platform_get_drvdata(pdev); struct sdhci_sprd_host *sprd_host = TO_SPRD_HOST(host); + pm_runtime_get_sync(&pdev->dev); + pm_runtime_disable(&pdev->dev); + pm_runtime_put_noidle(&pdev->dev); + sdhci_remove_host(host, 0); clk_disable_unprepare(sprd_host->clk_sdio); diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 7645ce3a29ad96..189b3a43e4e2a2 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -80,15 +80,6 @@ static struct in6_addr mld2_all_node = MLD2_ALL_NODE_INIT; static struct mld2_grec mldv2_zero_grec; #endif -static struct amt_skb_cb *amt_skb_cb(struct sk_buff *skb) -{ - BUILD_BUG_ON(sizeof(struct amt_skb_cb) + sizeof(struct tc_skb_cb) > - sizeof_field(struct sk_buff, cb)); - - return (struct amt_skb_cb *)((void *)skb->cb + - sizeof(struct tc_skb_cb)); -} - static void __amt_source_gc_work(void) { struct amt_source_node *snode; @@ -789,6 +780,11 @@ static void amt_send_request(struct amt_dev *amt, bool v6) rcu_read_unlock(); } +static bool amt_send_membership_query(struct amt_dev *amt, + struct sk_buff *skb, + struct amt_tunnel_list *tunnel, + bool v6); + static void amt_send_igmp_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) { @@ -798,8 +794,11 @@ static void amt_send_igmp_gq(struct amt_dev *amt, if (!skb) return; - amt_skb_cb(skb)->tunnel = tunnel; - dev_queue_xmit(skb); + skb_pull(skb, sizeof(struct ethhdr)); + if (amt_send_membership_query(amt, skb, tunnel, false)) { + amt->dev->stats.tx_dropped++; + kfree_skb(skb); + } } #if IS_ENABLED(CONFIG_IPV6) @@ -883,8 +882,11 @@ static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) if (!skb) return; - amt_skb_cb(skb)->tunnel = tunnel; - dev_queue_xmit(skb); + skb_pull(skb, sizeof(struct ethhdr)); + if (amt_send_membership_query(amt, skb, tunnel, true)) { + amt->dev->stats.tx_dropped++; + kfree_skb(skb); + } } #else static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) @@ -1183,7 +1185,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) #endif bool report = false; struct igmphdr *ih; - bool query = false; struct iphdr *iph; bool data = false; bool v6 = false; @@ -1201,9 +1202,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) case IGMP_HOST_MEMBERSHIP_REPORT: report = true; break; - case IGMP_HOST_MEMBERSHIP_QUERY: - query = true; - break; default: goto free; } @@ -1225,9 +1223,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) case ICMPV6_MLD2_REPORT: report = true; break; - case ICMPV6_MGM_QUERY: - query = true; - break; default: goto free; } @@ -1258,19 +1253,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) goto free; goto unlock; } else if (amt->mode == AMT_MODE_RELAY) { - if (query) { - tunnel = amt_skb_cb(skb)->tunnel; - if (!tunnel) { - WARN_ON(1); - goto free; - } - - /* Do not forward unexpected query */ - if (amt_send_membership_query(amt, skb, tunnel, v6)) - goto free; - goto unlock; - } - if (!data) goto free; list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) { diff --git a/drivers/net/bareudp.c b/drivers/net/bareudp.c index 5ef841c8552697..2bfad8653be6af 100644 --- a/drivers/net/bareudp.c +++ b/drivers/net/bareudp.c @@ -355,7 +355,7 @@ static int bareudp_xmit_skb(struct sk_buff *skb, struct net_device *dev, if (err) goto free_dst; - skb_set_inner_protocol(skb, bareudp->ethertype); + skb_set_inner_protocol(skb, skb->protocol); udp_tunnel_xmit_skb(rt, sk, skb, saddr, info->key.u.ipv4.dst, tos, ttl, df, sport, bareudp->port, !net_eq(bareudp->net, dev_net(bareudp->dev)), @@ -423,6 +423,7 @@ static int bareudp6_xmit_skb(struct sk_buff *skb, struct net_device *dev, if (err) goto free_dst; + skb_set_inner_protocol(skb, skb->protocol); daddr = info->key.u.ipv6.dst; udp_tunnel6_xmit_skb(dst, sk, skb, dev, &saddr, &daddr, prio, ttl, diff --git a/drivers/net/bonding/bond_main.c b/drivers/net/bonding/bond_main.c index 34c5bbbed9aeea..507d655eca21e3 100644 --- a/drivers/net/bonding/bond_main.c +++ b/drivers/net/bonding/bond_main.c @@ -5738,12 +5738,12 @@ static int bond_xdp_set(struct net_device *dev, struct bpf_prog *prog, bpf_prog_inc(prog); } - if (prog) { + if (prog && !old_prog) static_branch_inc(&bpf_master_redirect_enabled_key); - } else if (old_prog) { - bpf_prog_put(old_prog); + else if (!prog && old_prog) static_branch_dec(&bpf_master_redirect_enabled_key); - } + if (old_prog) + bpf_prog_put(old_prog); return 0; diff --git a/drivers/net/can/dev/skb.c b/drivers/net/can/dev/skb.c index 95fcdc1026f808..14edec5afb57e4 100644 --- a/drivers/net/can/dev/skb.c +++ b/drivers/net/can/dev/skb.c @@ -210,6 +210,10 @@ static void init_can_skb(struct sk_buff *skb) { skb->pkt_type = PACKET_BROADCAST; skb->ip_summed = CHECKSUM_UNNECESSARY; + + skb_reset_mac_header(skb); + skb_reset_network_header(skb); + skb_reset_transport_header(skb); } struct sk_buff *alloc_can_skb(struct net_device *dev, struct can_frame **cf) diff --git a/drivers/net/can/usb/f81604.c b/drivers/net/can/usb/f81604.c index f12318268e46be..4c147b9d6d690a 100644 --- a/drivers/net/can/usb/f81604.c +++ b/drivers/net/can/usb/f81604.c @@ -169,7 +169,7 @@ struct f81604_int_data { u8 rxerr; u8 txerr; u8 val; -} __packed __aligned(4); +} __packed; struct f81604_sff { __be16 id; diff --git a/drivers/net/can/vxcan.c b/drivers/net/can/vxcan.c index e882250180ef65..f365deafaf5422 100644 --- a/drivers/net/can/vxcan.c +++ b/drivers/net/can/vxcan.c @@ -78,6 +78,9 @@ static netdev_tx_t vxcan_xmit(struct sk_buff *oskb, struct net_device *dev) /* reset CAN GW hop counter */ csx->can_gw_hops = 0; + /* start with new CAN skb UID in the other namespace */ + csx->can_skb_uid = 0; + skb->pkt_type = PACKET_BROADCAST; skb->dev = peer; skb->ip_summed = CHECKSUM_UNNECESSARY; diff --git a/drivers/net/dsa/microchip/ksz_common.h b/drivers/net/dsa/microchip/ksz_common.h index b4a5673ba365cb..8f6ac13b5b1821 100644 --- a/drivers/net/dsa/microchip/ksz_common.h +++ b/drivers/net/dsa/microchip/ksz_common.h @@ -778,7 +778,7 @@ static inline bool ksz_is_sgmii_port(struct ksz_device *dev, int port) #define KSZ88_FAMILY_ID 0x88 #define KSZ8895_FAMILY_ID 0x95 -#define KSZ8_PORT_STATUS_0 0x08 +#define KSZ8_PORT_STATUS_0 0x18 #define KSZ8_PORT_FIBER_MODE BIT(7) #define SW_CHIP_ID_M GENMASK(7, 4) diff --git a/drivers/net/ethernet/airoha/airoha_eth.c b/drivers/net/ethernet/airoha/airoha_eth.c index 2fc8c91f210c64..d4faf4503487e3 100644 --- a/drivers/net/ethernet/airoha/airoha_eth.c +++ b/drivers/net/ethernet/airoha/airoha_eth.c @@ -2716,14 +2716,34 @@ static int airoha_qdma_set_trtcm_param(struct airoha_qdma *qdma, int channel, FIELD_PREP(TRTCM_METER_GROUP_MASK, group) | FIELD_PREP(TRTCM_PARAM_INDEX_MASK, idx) | FIELD_PREP(TRTCM_PARAM_RATE_TYPE_MASK, mode); + int i; - airoha_qdma_wr(qdma, REG_TRTCM_DATA_LOW(addr), val); - airoha_qdma_wr(qdma, REG_TRTCM_CFG_PARAM(addr), config); + /* + * HW might be in the middle of bucket handling and might + * require an additional try to actually apply the new TRTCM + * config. + */ + for (i = 0; i < TRTCM_CONFIG_RETRY_MAX; i++) { + u32 data = 0; - return read_poll_timeout(airoha_qdma_rr, val, - val & TRTCM_PARAM_RW_DONE_MASK, - USEC_PER_MSEC, 10 * USEC_PER_MSEC, true, - qdma, REG_TRTCM_CFG_PARAM(addr)); + airoha_qdma_wr(qdma, REG_TRTCM_DATA_LOW(addr), val); + airoha_qdma_wr(qdma, REG_TRTCM_CFG_PARAM(addr), config); + + if (read_poll_timeout(airoha_qdma_rr, data, + data & TRTCM_PARAM_RW_DONE_MASK, + USEC_PER_MSEC, 10 * USEC_PER_MSEC, + true, qdma, REG_TRTCM_CFG_PARAM(addr))) + continue; + + if (airoha_qdma_get_trtcm_param(qdma, channel, addr, param, + mode, &data, NULL)) + continue; + + if (data == val) + return 0; + } + + return -EBUSY; } static int airoha_qdma_set_trtcm_config(struct airoha_qdma *qdma, int channel, diff --git a/drivers/net/ethernet/airoha/airoha_eth.h b/drivers/net/ethernet/airoha/airoha_eth.h index 70f16189b25827..dc0c29001f8103 100644 --- a/drivers/net/ethernet/airoha/airoha_eth.h +++ b/drivers/net/ethernet/airoha/airoha_eth.h @@ -171,6 +171,8 @@ enum trtcm_param { #define TRTCM_TOKEN_RATE_MASK GENMASK(23, 6) #define TRTCM_TOKEN_RATE_FRACTION_MASK GENMASK(5, 0) +#define TRTCM_CONFIG_RETRY_MAX 2 + enum airoha_dma_map_type { AIROHA_DMA_UNMAPPED, AIROHA_DMA_MAP_SINGLE, diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index ced998399efc33..78583cee3414f0 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -486,7 +486,7 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev) struct netdev_queue *txq; int i; dma_addr_t mapping; - unsigned int length, pad = 0; + unsigned int length; u32 len, free_size, vlan_tag_flags, cfa_action, flags; struct bnxt_ptp_cfg *ptp = bp->ptp_cfg; struct pci_dev *pdev = bp->pdev; @@ -536,6 +536,16 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev) return rc < 0 ? NETDEV_TX_BUSY : NETDEV_TX_OK; } + /* Pad after the SW USO branch: bnxt_sw_udp_gso_xmit() would + * otherwise account the padding as UDP payload. + * Must be done before skb_shinfo(skb)->nr_frags is sampled, + * because skb_put_padto() might linearize the skb. + */ + if (skb_put_padto(skb, BNXT_MIN_PKT_SIZE)) { + /* SKB already freed. */ + goto tx_kick_pending; + } + free_size = bnxt_tx_avail(bp, txr); if (unlikely(free_size < skb_shinfo(skb)->nr_frags + 2)) { /* We must have raced with NAPI cleanup */ @@ -672,14 +682,6 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev) } normal_tx: - if (length < BNXT_MIN_PKT_SIZE) { - pad = BNXT_MIN_PKT_SIZE - length; - if (skb_pad(skb, pad)) - /* SKB already freed. */ - goto tx_kick_pending; - length = BNXT_MIN_PKT_SIZE; - } - mapping = dma_map_single(&pdev->dev, skb->data, len, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(&pdev->dev, mapping))) @@ -759,10 +761,7 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev) txbd->tx_bd_len_flags_type = cpu_to_le32(flags); } - flags &= ~TX_BD_LEN; - txbd->tx_bd_len_flags_type = - cpu_to_le32(((len + pad) << TX_BD_LEN_SHIFT) | flags | - TX_BD_FLAGS_PACKET_END); + txbd->tx_bd_len_flags_type |= cpu_to_le32(TX_BD_FLAGS_PACKET_END); netdev_tx_sent_queue(txq, skb->len); @@ -15506,7 +15505,7 @@ static void bnxt_fw_reset_task(struct work_struct *work) if (test_and_clear_bit(BNXT_STATE_FW_ACTIVATE_RESET, &bp->state) && !test_bit(BNXT_STATE_FW_ACTIVATE, &bp->state)) bnxt_dl_remote_reload(bp); - if (pci_enable_device(bp->pdev)) { + if (!pci_is_enabled(bp->pdev) && pci_enable_device(bp->pdev)) { netdev_err(bp->dev, "Cannot re-enable PCI device\n"); rc = -ENODEV; goto fw_reset_abort; @@ -17067,6 +17066,51 @@ void bnxt_print_device_info(struct bnxt *bp) pcie_print_link_status(bp->pdev); } +static void bnxt_clear_bars(struct pci_dev *pdev) +{ + int off; + + for (off = PCI_BASE_ADDRESS_0; off <= PCI_BASE_ADDRESS_5; off += 4) + pci_write_config_dword(pdev, off, 0); +} + +/* Clear any pending DMA transactions from crash kernel while loading driver in + * capture kernel. + */ +static int bnxt_kdump_reset(struct pci_dev *pdev) +{ + int rc, i; + u16 cmd; + + pci_read_config_word(pdev, PCI_COMMAND, &cmd); + cmd &= ~(PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY); + pci_write_config_word(pdev, PCI_COMMAND, cmd); + + if (pci_save_state(pdev)) + dev_warn(&pdev->dev, "Failed to save PCI state, PCI restore may be incomplete\n"); + + rc = pcie_flr(pdev); + if (rc) + dev_warn(&pdev->dev, "pcie_flr() failed (rc: %d), trying to continue\n", + rc); + + /* In case device is not returning CRS, wait 5 seconds longer */ + for (i = 0; i < 50; i++) { + pci_read_config_word(pdev, PCI_COMMAND, &cmd); + if (!PCI_POSSIBLE_ERROR(cmd)) + break; + msleep(100); + } + if (PCI_POSSIBLE_ERROR(cmd)) { + dev_err(&pdev->dev, "PCI config space inaccessible after FLR, aborting\n"); + return -ENODEV; + } + + bnxt_clear_bars(pdev); + pci_restore_state(pdev); + return 0; +} + static int bnxt_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct bnxt_hw_resc *hw_resc; @@ -17082,12 +17126,10 @@ static int bnxt_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) return -ENODEV; } - /* Clear any pending DMA transactions from crash kernel - * while loading driver in capture kernel. - */ if (is_kdump_kernel()) { - pci_clear_master(pdev); - pcie_flr(pdev); + rc = bnxt_kdump_reset(pdev); + if (rc) + return rc; } max_irqs = bnxt_get_max_irq(pdev); @@ -17515,10 +17557,8 @@ static pci_ers_result_t bnxt_io_error_detected(struct pci_dev *pdev, * so we disable bus master to prevent any potential bad DMAs before * freeing kernel memory. */ - if (state == pci_channel_io_frozen) { - set_bit(BNXT_STATE_PCI_CHANNEL_IO_FROZEN, &bp->state); + if (state == pci_channel_io_frozen) bnxt_fw_fatal_close(bp); - } if (netif_running(netdev)) __bnxt_close_nic(bp, true, true); @@ -17548,69 +17588,80 @@ static pci_ers_result_t bnxt_io_slot_reset(struct pci_dev *pdev) struct bnxt *bp = netdev_priv(netdev); int retry = 0; int err = 0; - int off; + u16 cmd; netdev_info(bp->dev, "PCI Slot Reset\n"); - if (test_bit(BNXT_STATE_PCI_CHANNEL_IO_FROZEN, &bp->state)) { - /* After DPC, the chip should return CRS when the vendor ID - * config register is read until it is ready. On all chips, - * this is not happening reliably so add a 5-second delay as a - * workaround. - */ - msleep(5000); - } + /* After a PCIe hot reset, the chip should return CRS when the + * vendor ID config register is read until it is ready. On all + * chips, this is not happening reliably so add a 5-second delay + * as a workaround. + */ + msleep(5000); netdev_lock(netdev); - if (pci_enable_device(pdev)) { + pci_read_config_word(pdev, PCI_COMMAND, &cmd); + if (PCI_POSSIBLE_ERROR(cmd)) { dev_err(&pdev->dev, - "Cannot re-enable PCI device after reset.\n"); - } else { - pci_set_master(pdev); - /* Upon fatal error, our device internal logic that latches to - * BAR value is getting reset and will restore only upon - * rewriting the BARs. - * - * As pci_restore_state() does not re-write the BARs if the - * value is same as saved value earlier, driver needs to - * write the BARs to 0 to force restore, in case of fatal error. - */ - if (test_and_clear_bit(BNXT_STATE_PCI_CHANNEL_IO_FROZEN, - &bp->state)) { - for (off = PCI_BASE_ADDRESS_0; - off <= PCI_BASE_ADDRESS_5; off += 4) - pci_write_config_dword(bp->pdev, off, 0); - } - pci_restore_state(pdev); + "PCI config space inaccessible after reset\n"); + goto reset_exit; + } - bnxt_inv_fw_health_reg(bp); - bnxt_try_map_fw_health_reg(bp); + /* Upon PCIe error, our device internal logic that latches to + * BAR value is getting reset and will restore only upon + * rewriting the BARs. + * + * As pci_restore_state() does not re-write the BARs if the + * value is same as saved value earlier, driver needs to + * write the BARs to 0 to force restore. + */ + pci_clear_master(pdev); + pci_read_config_word(pdev, PCI_COMMAND, &cmd); + cmd &= ~PCI_COMMAND_MEMORY; + pci_write_config_word(pdev, PCI_COMMAND, cmd); - /* In some PCIe AER scenarios, firmware may take up to - * 10 seconds to become ready in the worst case. - */ - do { - err = bnxt_try_recover_fw(bp); - if (!err) - break; - retry++; - } while (retry < BNXT_FW_SLOT_RESET_RETRY); + bnxt_clear_bars(pdev); + pci_restore_state(pdev); - if (err) { - dev_err(&pdev->dev, "Firmware not ready\n"); - goto reset_exit; + if (!pci_is_enabled(pdev) && pci_enable_device(pdev)) { + dev_err(&pdev->dev, + "Cannot re-enable PCI device after reset.\n"); + pci_read_config_word(pdev, PCI_COMMAND, &cmd); + if (!PCI_POSSIBLE_ERROR(cmd)) { + cmd &= ~(PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY); + pci_write_config_word(pdev, PCI_COMMAND, cmd); } + goto reset_exit; + } + pci_set_master(pdev); - err = bnxt_hwrm_func_reset(bp); + bnxt_inv_fw_health_reg(bp); + bnxt_try_map_fw_health_reg(bp); + + /* In some PCIe AER scenarios, firmware may take up to + * 10 seconds to become ready in the worst case. + */ + do { + err = bnxt_try_recover_fw(bp); if (!err) - result = PCI_ERS_RESULT_RECOVERED; + break; + retry++; + } while (retry < BNXT_FW_SLOT_RESET_RETRY); - /* IRQ will be initialized later in bnxt_io_resume */ - bnxt_ulp_irq_stop(bp); - bnxt_clear_int_mode(bp); + if (err) { + dev_err(&pdev->dev, "Firmware not ready\n"); + goto reset_exit; } + err = bnxt_hwrm_func_reset(bp); + if (!err) + result = PCI_ERS_RESULT_RECOVERED; + + /* IRQ will be initialized later in bnxt_io_resume */ + bnxt_ulp_irq_stop(bp); + bnxt_clear_int_mode(bp); + reset_exit: clear_bit(BNXT_STATE_IN_FW_RESET, &bp->state); bnxt_clear_reservations(bp, true); diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.h b/drivers/net/ethernet/broadcom/bnxt/bnxt.h index 4dbcd08ef7c32f..a939f4ed10079a 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.h +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.h @@ -2470,7 +2470,6 @@ struct bnxt { #define BNXT_STATE_ABORT_ERR 5 #define BNXT_STATE_FW_FATAL_COND 6 #define BNXT_STATE_DRV_REGISTERED 7 -#define BNXT_STATE_PCI_CHANNEL_IO_FROZEN 8 #define BNXT_STATE_NAPI_DISABLED 9 #define BNXT_STATE_FW_ACTIVATE 11 #define BNXT_STATE_RECOVER 12 diff --git a/drivers/net/ethernet/broadcom/genet/bcmgenet_wol.c b/drivers/net/ethernet/broadcom/genet/bcmgenet_wol.c index 96d5d4f7f51fe8..984432952963ad 100644 --- a/drivers/net/ethernet/broadcom/genet/bcmgenet_wol.c +++ b/drivers/net/ethernet/broadcom/genet/bcmgenet_wol.c @@ -253,6 +253,17 @@ int bcmgenet_wol_power_up_cfg(struct bcmgenet_priv *priv, reg = bcmgenet_umac_readl(priv, UMAC_CMD); reg &= ~CMD_CRC_FWD; bcmgenet_umac_writel(priv, reg, UMAC_CMD); + + /* + * Mirror wol_power_down_cfg(). If only UMAC_RX + * is enabled, then we must place the UMAC back + * into SW_RESET. + */ + reg = bcmgenet_umac_readl(priv, UMAC_CMD); + if ((reg & CMD_RX_EN) && !(reg & CMD_TX_EN)) { + reg |= CMD_SW_RESET; + bcmgenet_umac_writel(priv, reg, UMAC_CMD); + } spin_unlock_bh(&priv->reg_lock); /* Resume link status tracking */ diff --git a/drivers/net/ethernet/chelsio/inline_crypto/ch_ktls/chcr_ktls.c b/drivers/net/ethernet/chelsio/inline_crypto/ch_ktls/chcr_ktls.c index f5acd4be1e69dc..dbec95b4977736 100644 --- a/drivers/net/ethernet/chelsio/inline_crypto/ch_ktls/chcr_ktls.c +++ b/drivers/net/ethernet/chelsio/inline_crypto/ch_ktls/chcr_ktls.c @@ -389,7 +389,7 @@ static void chcr_ktls_dev_del(struct net_device *netdev, cxgb4_remove_tid(&tx_info->adap->tids, tx_info->tx_chan, tx_info->tid, tx_info->ip_family); - xa_erase(&u_ctx->tid_list, tx_info->tid); + xa_erase_bh(&u_ctx->tid_list, tx_info->tid); } port_stats = &tx_info->adap->ch_ktls_stats.ktls_port[tx_info->port_id]; @@ -577,7 +577,7 @@ static int chcr_ktls_dev_add(struct net_device *netdev, struct sock *sk, cxgb4_remove_tid(&tx_info->adap->tids, tx_info->tx_chan, tx_info->tid, tx_info->ip_family); - xa_erase(&u_ctx->tid_list, tx_info->tid); + xa_erase_bh(&u_ctx->tid_list, tx_info->tid); put_module: /* release module refcount */ diff --git a/drivers/net/ethernet/google/gve/gve_main.c b/drivers/net/ethernet/google/gve/gve_main.c index e4d78ae52dafec..0dd04ee30c9a5e 100644 --- a/drivers/net/ethernet/google/gve/gve_main.c +++ b/drivers/net/ethernet/google/gve/gve_main.c @@ -1708,17 +1708,17 @@ static int gve_xsk_pool_disable(struct net_device *dev, } napi_rx = &priv->ntfy_blocks[priv->rx[qid].ntfy_id].napi; - napi_disable(napi_rx); /* make sure current rx poll is done */ + napi_disable_locked(napi_rx); /* make sure current rx poll is done */ tx_qid = gve_xdp_tx_queue_id(priv, qid); napi_tx = &priv->ntfy_blocks[priv->tx[tx_qid].ntfy_id].napi; - napi_disable(napi_tx); /* make sure current tx poll is done */ + napi_disable_locked(napi_tx); /* make sure current tx poll is done */ gve_unreg_xsk_pool(priv, qid); smp_mb(); /* Make sure it is visible to the workers on datapath */ - napi_enable(napi_rx); - napi_enable(napi_tx); + napi_enable_locked(napi_rx); + napi_enable_locked(napi_tx); if (gve_is_gqi(priv)) { if (gve_rx_work_pending(&priv->rx[qid])) napi_schedule(napi_rx); diff --git a/drivers/net/ethernet/google/gve/gve_rx_dqo.c b/drivers/net/ethernet/google/gve/gve_rx_dqo.c index 0ece2f6fdffb40..2e6d6abbddfc12 100644 --- a/drivers/net/ethernet/google/gve/gve_rx_dqo.c +++ b/drivers/net/ethernet/google/gve/gve_rx_dqo.c @@ -113,6 +113,12 @@ static void gve_rx_reset_ring_dqo(struct gve_priv *priv, int idx) gve_free_to_page_pool(rx, bs, false); else gve_free_qpl_page_dqo(bs); + + if (gve_buf_state_is_allocated(rx, bs) && + bs->xsk_buff) { + xsk_buff_free(bs->xsk_buff); + bs->xsk_buff = NULL; + } } } @@ -839,7 +845,12 @@ static int gve_rx_dqo(struct napi_struct *napi, struct gve_rx_ring *rx, } if (unlikely(compl_desc->rx_error)) { - gve_free_buffer(rx, buf_state); + if (buf_state->xsk_buff) { + xsk_buff_free(buf_state->xsk_buff); + gve_free_buf_state(rx, buf_state); + } else { + gve_free_buffer(rx, buf_state); + } return -EINVAL; } diff --git a/drivers/net/ethernet/ibm/ibmveth.c b/drivers/net/ethernet/ibm/ibmveth.c index 73e051d26b9d88..abebdb1fc26289 100644 --- a/drivers/net/ethernet/ibm/ibmveth.c +++ b/drivers/net/ethernet/ibm/ibmveth.c @@ -553,10 +553,15 @@ static int ibmveth_rxq_harvest_buffer(struct ibmveth_adapter *adapter, static void ibmveth_free_tx_ltb(struct ibmveth_adapter *adapter, int idx) { + void *ptr = adapter->tx_ltb_ptr[idx]; + + if (!ptr) + return; + + adapter->tx_ltb_ptr[idx] = NULL; dma_unmap_single(&adapter->vdev->dev, adapter->tx_ltb_dma[idx], adapter->tx_ltb_size, DMA_TO_DEVICE); - kfree(adapter->tx_ltb_ptr[idx]); - adapter->tx_ltb_ptr[idx] = NULL; + kfree(ptr); } static int ibmveth_allocate_tx_ltb(struct ibmveth_adapter *adapter, int idx) @@ -667,7 +672,7 @@ static int ibmveth_open(struct net_device *netdev) for (i = 0; i < netdev->real_num_tx_queues; i++) { if (ibmveth_allocate_tx_ltb(adapter, i)) - goto out_free_tx_ltb; + goto out_unmap_filter_list; } adapter->rx_queue.index = 0; @@ -718,10 +723,6 @@ static int ibmveth_open(struct net_device *netdev) if (rc != 0) { netdev_err(netdev, "unable to request irq 0x%x, rc %d\n", netdev->irq, rc); - do { - lpar_rc = h_free_logical_lan(adapter->vdev->unit_address); - } while (H_IS_LONG_BUSY(lpar_rc) || (lpar_rc == H_BUSY)); - goto out_free_buffer_pools; } @@ -737,6 +738,9 @@ static int ibmveth_open(struct net_device *netdev) return 0; out_free_buffer_pools: + do { + lpar_rc = h_free_logical_lan(adapter->vdev->unit_address); + } while (H_IS_LONG_BUSY(lpar_rc) || (lpar_rc == H_BUSY)); while (--i >= 0) { if (adapter->rx_buff_pool[i].active) ibmveth_free_buffer_pool(adapter, @@ -746,10 +750,8 @@ static int ibmveth_open(struct net_device *netdev) dma_unmap_single(dev, adapter->filter_list_dma, 4096, DMA_BIDIRECTIONAL); -out_free_tx_ltb: - while (--i >= 0) { + for (i = netdev->real_num_tx_queues - 1; i >= 0; i--) ibmveth_free_tx_ltb(adapter, i); - } out_unmap_buffer_list: dma_unmap_single(dev, adapter->buffer_list_dma, 4096, diff --git a/drivers/net/ethernet/intel/e1000e/netdev.c b/drivers/net/ethernet/intel/e1000e/netdev.c index 844f31ab37ad44..c282f65199e49e 100644 --- a/drivers/net/ethernet/intel/e1000e/netdev.c +++ b/drivers/net/ethernet/intel/e1000e/netdev.c @@ -67,6 +67,13 @@ static const struct dmi_system_id disable_k1_list[] = { DMI_MATCH(DMI_PRODUCT_NAME, "Dell Pro 16 Plus PB16250"), }, }, + { + .ident = "Lenovo ThinkPad P14s Gen 5", + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad P14s Gen 5"), + }, + }, {} }; diff --git a/drivers/net/ethernet/intel/iavf/iavf.h b/drivers/net/ethernet/intel/iavf/iavf.h index 050f8241ef5e6b..5fcbfa0ca8553c 100644 --- a/drivers/net/ethernet/intel/iavf/iavf.h +++ b/drivers/net/ethernet/intel/iavf/iavf.h @@ -259,7 +259,6 @@ struct iavf_adapter { struct work_struct adminq_task; struct work_struct finish_config; wait_queue_head_t down_waitqueue; - wait_queue_head_t vc_waitqueue; struct iavf_q_vector *q_vectors; struct list_head vlan_filter_list; int num_vlan_filters; @@ -588,8 +587,9 @@ void iavf_configure_queues(struct iavf_adapter *adapter); void iavf_enable_queues(struct iavf_adapter *adapter); void iavf_disable_queues(struct iavf_adapter *adapter); void iavf_map_queues(struct iavf_adapter *adapter); -void iavf_add_ether_addrs(struct iavf_adapter *adapter); +int iavf_add_ether_addrs(struct iavf_adapter *adapter); void iavf_del_ether_addrs(struct iavf_adapter *adapter); +void iavf_mac_add_reject(struct iavf_adapter *adapter); void iavf_add_vlans(struct iavf_adapter *adapter); void iavf_del_vlans(struct iavf_adapter *adapter); void iavf_set_promiscuous(struct iavf_adapter *adapter); @@ -606,6 +606,13 @@ void iavf_disable_vlan_stripping(struct iavf_adapter *adapter); void iavf_virtchnl_completion(struct iavf_adapter *adapter, enum virtchnl_ops v_opcode, enum iavf_status v_retval, u8 *msg, u16 msglen); +int iavf_poll_virtchnl_response(struct iavf_adapter *adapter, + struct iavf_arq_event_info *event, + bool (*condition)(struct iavf_adapter *adapter, + const void *data, + enum virtchnl_ops v_op), + const void *cond_data, + unsigned int timeout_ms); int iavf_config_rss(struct iavf_adapter *adapter); void iavf_cfg_queues_bw(struct iavf_adapter *adapter); void iavf_cfg_queues_quanta_size(struct iavf_adapter *adapter); diff --git a/drivers/net/ethernet/intel/iavf/iavf_main.c b/drivers/net/ethernet/intel/iavf/iavf_main.c index 29b8403a066bc8..2f8a80a1133626 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_main.c +++ b/drivers/net/ethernet/intel/iavf/iavf_main.c @@ -1029,6 +1029,60 @@ static bool iavf_is_mac_set_handled(struct net_device *netdev, return ret; } +/** + * iavf_mac_change_done - Check if MAC change completed + * @adapter: board private structure + * @data: MAC address being checked (as const void *) + * @v_op: virtchnl opcode from processed message + * + * Callback for iavf_poll_virtchnl_response() to check if MAC change completed. + * + * Return: true if MAC change completed, false otherwise + */ +static bool iavf_mac_change_done(struct iavf_adapter *adapter, + const void *data, enum virtchnl_ops v_op) +{ + const u8 *addr = data; + + return iavf_is_mac_set_handled(adapter->netdev, addr); +} + +/** + * iavf_set_mac_sync - Synchronously change MAC address + * @adapter: board private structure + * @addr: MAC address to set + * + * Send MAC change request to PF and poll admin queue for response. + * Caller must hold netdev_lock. This can sleep for up to 2.5 seconds. + * Event buffer is allocated before sending to avoid state mismatch if + * allocation fails after message is sent to PF. + * + * Return: 0 on success, negative on failure + */ +static int iavf_set_mac_sync(struct iavf_adapter *adapter, const u8 *addr) +{ + struct iavf_arq_event_info event; + int ret; + + netdev_assert_locked(adapter->netdev); + + event.buf_len = IAVF_MAX_AQ_BUF_SIZE; + event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL); + if (!event.msg_buf) + return -ENOMEM; + + ret = iavf_add_ether_addrs(adapter); + if (ret) + goto out; + + ret = iavf_poll_virtchnl_response(adapter, &event, + iavf_mac_change_done, addr, 2500); + +out: + kfree(event.msg_buf); + return ret; +} + /** * iavf_set_mac - NDO callback to set port MAC address * @netdev: network interface device structure @@ -1046,25 +1100,23 @@ static int iavf_set_mac(struct net_device *netdev, void *p) return -EADDRNOTAVAIL; ret = iavf_replace_primary_mac(adapter, addr->sa_data); - if (ret) return ret; - ret = wait_event_interruptible_timeout(adapter->vc_waitqueue, - iavf_is_mac_set_handled(netdev, addr->sa_data), - msecs_to_jiffies(2500)); - - /* If ret < 0 then it means wait was interrupted. - * If ret == 0 then it means we got a timeout. - * else it means we got response for set MAC from PF, - * check if netdev MAC was updated to requested MAC, - * if yes then set MAC succeeded otherwise it failed return -EACCES - */ - if (ret < 0) + ret = iavf_set_mac_sync(adapter, addr->sa_data); + if (ret) { + /* Rollback only if send failed (message never reached PF). + * Don't rollback on timeout (-EAGAIN) because the message was + * sent and PF will eventually respond. When the response arrives, + * iavf_virtchnl_completion() will handle rollback (on PF error) + * or acceptance (on PF success) automatically. + */ + if (ret != -EAGAIN) { + iavf_mac_add_reject(adapter); + ether_addr_copy(adapter->hw.mac.addr, netdev->dev_addr); + } return ret; - - if (!ret) - return -EAGAIN; + } if (!ether_addr_equal(netdev->dev_addr, addr->sa_data)) return -EACCES; @@ -5394,9 +5446,6 @@ static int iavf_probe(struct pci_dev *pdev, const struct pci_device_id *ent) /* Setup the wait queue for indicating transition to down status */ init_waitqueue_head(&adapter->down_waitqueue); - /* Setup the wait queue for indicating virtchannel events */ - init_waitqueue_head(&adapter->vc_waitqueue); - INIT_LIST_HEAD(&adapter->ptp.aq_cmds); init_waitqueue_head(&adapter->ptp.phc_time_waitqueue); mutex_init(&adapter->ptp.aq_cmd_lock); diff --git a/drivers/net/ethernet/intel/iavf/iavf_virtchnl.c b/drivers/net/ethernet/intel/iavf/iavf_virtchnl.c index ec234cc8bd9db0..e6b7e8f82c7c1f 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_virtchnl.c +++ b/drivers/net/ethernet/intel/iavf/iavf_virtchnl.c @@ -2,6 +2,7 @@ /* Copyright(c) 2013 - 2018 Intel Corporation. */ #include +#include #include "iavf.h" #include "iavf_ptp.h" @@ -555,20 +556,23 @@ iavf_set_mac_addr_type(struct virtchnl_ether_addr *virtchnl_ether_addr, * @adapter: adapter structure * * Request that the PF add one or more addresses to our filters. - **/ -void iavf_add_ether_addrs(struct iavf_adapter *adapter) + * + * Return: 0 on success, negative on failure + */ +int iavf_add_ether_addrs(struct iavf_adapter *adapter) { struct virtchnl_ether_addr_list *veal; struct iavf_mac_filter *f; int i = 0, count = 0; bool more = false; size_t len; + int ret; if (adapter->current_op != VIRTCHNL_OP_UNKNOWN) { /* bail because we already have a command pending */ dev_err(&adapter->pdev->dev, "Cannot add filters, command %d pending\n", adapter->current_op); - return; + return -EBUSY; } spin_lock_bh(&adapter->mac_vlan_list_lock); @@ -580,7 +584,7 @@ void iavf_add_ether_addrs(struct iavf_adapter *adapter) if (!count) { adapter->aq_required &= ~IAVF_FLAG_AQ_ADD_MAC_FILTER; spin_unlock_bh(&adapter->mac_vlan_list_lock); - return; + return 0; } adapter->current_op = VIRTCHNL_OP_ADD_ETH_ADDR; @@ -594,8 +598,9 @@ void iavf_add_ether_addrs(struct iavf_adapter *adapter) veal = kzalloc(len, GFP_ATOMIC); if (!veal) { + adapter->current_op = VIRTCHNL_OP_UNKNOWN; spin_unlock_bh(&adapter->mac_vlan_list_lock); - return; + return -ENOMEM; } veal->vsi_id = adapter->vsi_res->vsi_id; @@ -615,8 +620,15 @@ void iavf_add_ether_addrs(struct iavf_adapter *adapter) spin_unlock_bh(&adapter->mac_vlan_list_lock); - iavf_send_pf_msg(adapter, VIRTCHNL_OP_ADD_ETH_ADDR, (u8 *)veal, len); + ret = iavf_send_pf_msg(adapter, VIRTCHNL_OP_ADD_ETH_ADDR, (u8 *)veal, len); kfree(veal); + if (ret) { + dev_err(&adapter->pdev->dev, + "Unable to send ADD_ETH_ADDR message to PF, error %d\n", ret); + adapter->current_op = VIRTCHNL_OP_UNKNOWN; + } + + return ret; } /** @@ -712,8 +724,8 @@ static void iavf_mac_add_ok(struct iavf_adapter *adapter) * @adapter: adapter structure * * Remove filters from list based on PF response. - **/ -static void iavf_mac_add_reject(struct iavf_adapter *adapter) + */ +void iavf_mac_add_reject(struct iavf_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct iavf_mac_filter *f, *ftmp; @@ -2364,7 +2376,6 @@ void iavf_virtchnl_completion(struct iavf_adapter *adapter, iavf_mac_add_reject(adapter); /* restore administratively set MAC address */ ether_addr_copy(adapter->hw.mac.addr, netdev->dev_addr); - wake_up(&adapter->vc_waitqueue); break; case VIRTCHNL_OP_DEL_ETH_ADDR: dev_err(&adapter->pdev->dev, "Failed to delete MAC filter, error %s\n", @@ -2555,7 +2566,6 @@ void iavf_virtchnl_completion(struct iavf_adapter *adapter, eth_hw_addr_set(netdev, adapter->hw.mac.addr); netif_addr_unlock_bh(netdev); } - wake_up(&adapter->vc_waitqueue); break; case VIRTCHNL_OP_GET_STATS: { struct iavf_eth_stats *stats = @@ -2950,3 +2960,72 @@ void iavf_virtchnl_completion(struct iavf_adapter *adapter, } /* switch v_opcode */ adapter->current_op = VIRTCHNL_OP_UNKNOWN; } + +/** + * iavf_poll_virtchnl_response - Poll admin queue for virtchnl response + * @adapter: adapter structure + * @event: pre-allocated event buffer to use for polling + * @condition: callback to check if desired response received + * @cond_data: context data passed to condition callback + * @timeout_ms: maximum time to wait in milliseconds + * + * Polls the admin queue and processes all incoming virtchnl messages. + * After processing each valid message, calls the condition callback to check + * if the expected response has been received. The callback receives the opcode + * of the processed message to identify which response was received. Continues + * polling until the callback returns true or timeout expires. + * + * Caller must allocate event buffer before sending any messages to PF to avoid + * state mismatch if allocation fails after message is sent. + * + * Caller must hold netdev_lock. This can sleep for up to timeout_ms while + * polling hardware. + * + * Return: 0 on success (condition met), -EAGAIN on timeout, or error code + */ +int iavf_poll_virtchnl_response(struct iavf_adapter *adapter, + struct iavf_arq_event_info *event, + bool (*condition)(struct iavf_adapter *adapter, + const void *data, + enum virtchnl_ops v_op), + const void *cond_data, + unsigned int timeout_ms) +{ + struct iavf_hw *hw = &adapter->hw; + enum virtchnl_ops received_op; + unsigned long timeout; + int ret = -EAGAIN; + u16 pending = 0; + u32 v_retval; + + netdev_assert_locked(adapter->netdev); + + timeout = jiffies + msecs_to_jiffies(timeout_ms); + do { + if (!pending) + usleep_range(50, 75); + + if (iavf_clean_arq_element(hw, event, &pending) == IAVF_SUCCESS) { + received_op = (enum virtchnl_ops)le32_to_cpu(event->desc.cookie_high); + if (received_op != VIRTCHNL_OP_UNKNOWN) { + v_retval = le32_to_cpu(event->desc.cookie_low); + + iavf_virtchnl_completion(adapter, received_op, + (enum iavf_status)v_retval, + event->msg_buf, event->msg_len); + + if (condition(adapter, cond_data, received_op)) { + ret = 0; + break; + } + } + + memset(event->msg_buf, 0, IAVF_MAX_AQ_BUF_SIZE); + + if (pending) + continue; + } + } while (time_before(jiffies, timeout)); + + return ret; +} diff --git a/drivers/net/ethernet/intel/ice/devlink/port.c b/drivers/net/ethernet/intel/ice/devlink/port.c index 2a2e56777f9f75..3ede2464900272 100644 --- a/drivers/net/ethernet/intel/ice/devlink/port.c +++ b/drivers/net/ethernet/intel/ice/devlink/port.c @@ -590,8 +590,8 @@ static void ice_dealloc_dynamic_port(struct ice_dynamic_port *dyn_port) xa_erase(&pf->sf_nums, devlink_port->attrs.pci_sf.sf); ice_eswitch_detach_sf(pf, dyn_port); - ice_vsi_free(dyn_port->vsi); xa_erase(&pf->dyn_ports, dyn_port->vsi->idx); + ice_vsi_free(dyn_port->vsi); kfree(dyn_port); } diff --git a/drivers/net/ethernet/intel/ice/ice_eswitch.c b/drivers/net/ethernet/intel/ice/ice_eswitch.c index b069e6c514fb12..6e7bba4738989b 100644 --- a/drivers/net/ethernet/intel/ice/ice_eswitch.c +++ b/drivers/net/ethernet/intel/ice/ice_eswitch.c @@ -95,7 +95,7 @@ ice_eswitch_release_repr(struct ice_pf *pf, struct ice_repr *repr) return; ice_vsi_update_security(vsi, ice_vsi_ctx_set_antispoof); - metadata_dst_free(repr->dst); + dst_release(&repr->dst->dst); repr->dst = NULL; ice_fltr_add_mac_and_broadcast(vsi, repr->parent_mac, ICE_FWD_TO_VSI); diff --git a/drivers/net/ethernet/intel/ice/ice_txrx.c b/drivers/net/ethernet/intel/ice/ice_txrx.c index c04c5856dad6e2..4e26ace793ec6d 100644 --- a/drivers/net/ethernet/intel/ice/ice_txrx.c +++ b/drivers/net/ethernet/intel/ice/ice_txrx.c @@ -1561,10 +1561,10 @@ ice_tx_map(struct ice_tx_ring *tx_ring, struct ice_tx_buf *first, } } tstamp_ring->next_to_use = j; - writel_relaxed(j, tstamp_ring->tail); + writel(j, tstamp_ring->tail); } else { ring_kick: - writel_relaxed(i, tx_ring->tail); + writel(i, tx_ring->tail); } return; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en/xsk/rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en/xsk/rx.c index 4f984f6a2cb95e..55ec6387ab28d3 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en/xsk/rx.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en/xsk/rx.c @@ -3,6 +3,7 @@ #include "rx.h" #include "en/xdp.h" +#include #include #include @@ -156,6 +157,7 @@ int mlx5e_xsk_alloc_rx_mpwqe(struct mlx5e_rq *rq, u16 ix) xsk_buff_free(xsk_buffs[batch]); err: + bitmap_fill(wi->skip_release_bitmap, rq->mpwqe.pages_per_wqe); rq->stats->buff_alloc_err++; return -ENOMEM; } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c index 6fc6605d20549b..c75b064b04166a 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c @@ -410,8 +410,11 @@ static inline void mlx5e_free_rx_wqe(struct mlx5e_rq *rq, static void mlx5e_xsk_free_rx_wqe(struct mlx5e_wqe_frag_info *wi) { - if (!(wi->flags & BIT(MLX5E_WQE_FRAG_SKIP_RELEASE))) - xsk_buff_free(*wi->xskp); + if (wi->flags & BIT(MLX5E_WQE_FRAG_SKIP_RELEASE)) + return; + + xsk_buff_free(*wi->xskp); + wi->flags |= BIT(MLX5E_WQE_FRAG_SKIP_RELEASE); } static void mlx5e_dealloc_rx_wqe(struct mlx5e_rq *rq, u16 ix) @@ -905,10 +908,12 @@ int mlx5e_poll_ico_cq(struct mlx5e_cq *cq) } while (!last_wqe); } while ((++i < MLX5E_TX_CQ_POLL_BUDGET) && (cqe = mlx5_cqwq_get_cqe(&cq->wq))); - sq->cc = sqcc; - mlx5_cqwq_update_db_record(&cq->wq); + /* ensure cq space is freed before enabling more cqes */ + dma_wmb(); + + sq->cc = sqcc; return i; } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/esw/adj_vport.c b/drivers/net/ethernet/mellanox/mlx5/core/esw/adj_vport.c index 7950b82d8b8aec..3624c680a861a5 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/esw/adj_vport.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/esw/adj_vport.c @@ -11,26 +11,6 @@ int mlx5_esw_adj_vport_modify(struct mlx5_core_dev *dev, u16 vport, lockdep_assert_held(&dev->priv.eswitch->state_lock); - if (MLX5_CAP_ESW(dev, esw_vport_state_max_tx_speed)) { - u8 op_mod = MLX5_VPORT_STATE_OP_MOD_ESW_VPORT; - struct mlx5_vport *esw_vport; - u32 speed = 0; - int err; - - err = mlx5_query_vport_max_tx_speed(dev, op_mod, vport, - true, &speed, NULL); - if (err) { - esw_vport = mlx5_eswitch_get_vport(dev->priv.eswitch, - vport); - speed = IS_ERR(esw_vport) ? 0 : - esw_vport->agg_max_tx_speed; - mlx5_core_dbg(dev, - "Failed to query vport %d max tx speed, err=%d, using cached %u\n", - vport, err, speed); - } - MLX5_SET(modify_vport_state_in, in, max_tx_speed, speed); - } - MLX5_SET(modify_vport_state_in, in, opcode, MLX5_CMD_OP_MODIFY_VPORT_STATE); MLX5_SET(modify_vport_state_in, in, op_mod, diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c index 3b34bec559e089..4e173b08cb37af 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c @@ -1432,30 +1432,40 @@ static bool mlx5_lag_should_disable_lag(struct mlx5_lag *ldev, bool do_bond) } #ifdef CONFIG_MLX5_ESWITCH -static int -mlx5_lag_sum_devices_speed(struct mlx5_lag *ldev, u32 *sum_speed, - int (*get_speed)(struct mlx5_core_dev *, u32 *)) +static int mlx5_lag_get_devices_oper_speed(struct mlx5_lag *ldev, + u32 *sum_speed) { - struct mlx5_core_dev *pf_mdev; - struct lag_func *pf; int pf_idx; - u32 speed; - int ret; *sum_speed = 0; mlx5_ldev_for_each(pf_idx, 0, ldev) { + u8 opmod = MLX5_VPORT_STATE_OP_MOD_VNIC_VPORT; + struct mlx5_core_dev *pf_mdev; + struct lag_func *pf; + u32 speed; + u8 state; + int ret; + pf = mlx5_lag_pf(ldev, pf_idx); if (!pf) continue; pf_mdev = pf->dev; if (!pf_mdev) continue; + ret = mlx5_query_vport_max_tx_speed(pf_mdev, opmod, 0, 0, + &speed, &state); + if (ret) { + mlx5_core_dbg(pf_mdev, "State query failed (err=%d)\n", + ret); + return ret; + } + if (state != VPORT_STATE_UP) + continue; - ret = get_speed(pf_mdev, &speed); + ret = mlx5_port_oper_linkspeed(pf_mdev, &speed); if (ret) { mlx5_core_dbg(pf_mdev, - "Failed to get device speed using %ps. Device %s speed is not available (err=%d)\n", - get_speed, dev_name(pf_mdev->device), + "Failed to get oper speed (err=%d)\n", ret); return ret; } @@ -1466,17 +1476,42 @@ mlx5_lag_sum_devices_speed(struct mlx5_lag *ldev, u32 *sum_speed, return 0; } -static int mlx5_lag_sum_devices_max_speed(struct mlx5_lag *ldev, u32 *max_speed) +static int mlx5_lag_get_devices_max_speed(struct mlx5_lag *ldev, u32 *max_speed) { - return mlx5_lag_sum_devices_speed(ldev, max_speed, - mlx5_port_max_linkspeed); -} + bool take_max; + int pf_idx; -static int mlx5_lag_sum_devices_oper_speed(struct mlx5_lag *ldev, - u32 *oper_speed) -{ - return mlx5_lag_sum_devices_speed(ldev, oper_speed, - mlx5_port_oper_linkspeed); + take_max = ldev->tracker.tx_type == NETDEV_LAG_TX_TYPE_ACTIVEBACKUP; + if (ldev->mode == MLX5_LAG_MODE_MPESW) + take_max = false; + + *max_speed = 0; + mlx5_ldev_for_each(pf_idx, 0, ldev) { + struct mlx5_core_dev *pf_mdev; + struct lag_func *pf; + u32 speed; + int ret; + + pf = mlx5_lag_pf(ldev, pf_idx); + if (!pf) + continue; + pf_mdev = pf->dev; + if (!pf_mdev) + continue; + + ret = mlx5_port_max_linkspeed(pf_mdev, &speed); + if (ret) { + mlx5_core_dbg(pf_mdev, + "Failed to get max speed (err=%d)\n", + ret); + return ret; + } + + *max_speed = take_max ? + max(*max_speed, speed) : *max_speed + speed; + } + + return 0; } static void mlx5_lag_modify_device_vports_speed(struct mlx5_core_dev *mdev, @@ -1525,7 +1560,7 @@ void mlx5_lag_set_vports_agg_speed(struct mlx5_lag *ldev) int pf_idx; if (ldev->mode == MLX5_LAG_MODE_MPESW) { - if (mlx5_lag_sum_devices_oper_speed(ldev, &speed)) + if (mlx5_lag_get_devices_oper_speed(ldev, &speed)) return; } else { speed = ldev->tracker.bond_speed_mbps; @@ -1533,8 +1568,8 @@ void mlx5_lag_set_vports_agg_speed(struct mlx5_lag *ldev) return; } - /* If speed is not set, use the sum of max speeds of all PFs */ - if (!speed && mlx5_lag_sum_devices_max_speed(ldev, &speed)) + /* If speed is not set, fall back to the max achievable speed */ + if (!speed && mlx5_lag_get_devices_max_speed(ldev, &speed)) return; speed = speed / MLX5_MAX_TX_SPEED_UNIT; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/vport.c b/drivers/net/ethernet/mellanox/mlx5/core/vport.c index 8aa94ec87a0e3c..edac2d694e0f04 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/vport.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/vport.c @@ -93,30 +93,6 @@ int mlx5_modify_vport_admin_state(struct mlx5_core_dev *mdev, u8 opmod, lockdep_assert_held(&mdev->priv.eswitch->state_lock); #endif - if (MLX5_CAP_ESW(mdev, esw_vport_state_max_tx_speed) && - opmod == MLX5_VPORT_STATE_OP_MOD_ESW_VPORT && - vport != MLX5_VPORT_UPLINK) { - u32 speed = 0; - int err; - - err = mlx5_query_vport_max_tx_speed(mdev, opmod, vport, - other_vport, &speed, NULL); - if (err) { -#ifdef CONFIG_MLX5_ESWITCH - struct mlx5_vport *esw_vport; - - esw_vport = mlx5_eswitch_get_vport(mdev->priv.eswitch, - vport); - speed = IS_ERR(esw_vport) ? 0 : - esw_vport->agg_max_tx_speed; -#endif - mlx5_core_dbg(mdev, - "Failed to query vport %d max tx speed, err=%d, using cached %u\n", - vport, err, speed); - } - MLX5_SET(modify_vport_state_in, in, max_tx_speed, speed); - } - MLX5_SET(modify_vport_state_in, in, opcode, MLX5_CMD_OP_MODIFY_VPORT_STATE); MLX5_SET(modify_vport_state_in, in, op_mod, opmod); diff --git a/drivers/net/ethernet/mellanox/mlxsw/spectrum.h b/drivers/net/ethernet/mellanox/mlxsw/spectrum.h index b03ff9e044f9e2..10af08ce72efaf 100644 --- a/drivers/net/ethernet/mellanox/mlxsw/spectrum.h +++ b/drivers/net/ethernet/mellanox/mlxsw/spectrum.h @@ -989,6 +989,8 @@ void mlxsw_sp_acl_ruleset_prio_get(struct mlxsw_sp_acl_ruleset *ruleset, struct mlxsw_sp_acl_rule_info * mlxsw_sp_acl_rulei_create(struct mlxsw_sp_acl *acl, struct mlxsw_afa_block *afa_block); +void mlxsw_sp_acl_rulei_free(struct mlxsw_sp *mlxsw_sp, + const struct mlxsw_sp_acl_rule_info *rulei); void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp, struct mlxsw_sp_acl_rule_info *rulei); int mlxsw_sp_acl_rulei_commit(struct mlxsw_sp_acl_rule_info *rulei); diff --git a/drivers/net/ethernet/mellanox/mlxsw/spectrum_acl.c b/drivers/net/ethernet/mellanox/mlxsw/spectrum_acl.c index cb232accb296aa..f7be4f3a151842 100644 --- a/drivers/net/ethernet/mellanox/mlxsw/spectrum_acl.c +++ b/drivers/net/ethernet/mellanox/mlxsw/spectrum_acl.c @@ -340,8 +340,8 @@ mlxsw_sp_acl_rulei_create(struct mlxsw_sp_acl *acl, return ERR_PTR(err); } -void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp, - struct mlxsw_sp_acl_rule_info *rulei) +void mlxsw_sp_acl_rulei_free(struct mlxsw_sp *mlxsw_sp, + const struct mlxsw_sp_acl_rule_info *rulei) { if (rulei->action_created) mlxsw_afa_block_destroy(rulei->act_block); @@ -351,6 +351,12 @@ void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp, if (rulei->dst_port_range_reg_valid) mlxsw_sp_port_range_reg_put(mlxsw_sp, rulei->dst_port_range_reg_index); +} + +void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp, + struct mlxsw_sp_acl_rule_info *rulei) +{ + mlxsw_sp_acl_rulei_free(mlxsw_sp, rulei); kfree(rulei); } diff --git a/drivers/net/ethernet/mellanox/mlxsw/spectrum_flower.c b/drivers/net/ethernet/mellanox/mlxsw/spectrum_flower.c index 353fd9ca89a68a..5e4632cb792d56 100644 --- a/drivers/net/ethernet/mellanox/mlxsw/spectrum_flower.c +++ b/drivers/net/ethernet/mellanox/mlxsw/spectrum_flower.c @@ -862,14 +862,19 @@ int mlxsw_sp_flower_tmplt_create(struct mlxsw_sp *mlxsw_sp, memset(&rulei, 0, sizeof(rulei)); err = mlxsw_sp_flower_parse(mlxsw_sp, block, &rulei, f); if (err) - return err; + goto out; + ruleset = mlxsw_sp_acl_ruleset_get(mlxsw_sp, block, f->common.chain_index, MLXSW_SP_ACL_PROFILE_FLOWER, &rulei.values.elusage); + err = PTR_ERR_OR_ZERO(ruleset); + +out: + mlxsw_sp_acl_rulei_free(mlxsw_sp, &rulei); /* keep the reference to the ruleset */ - return PTR_ERR_OR_ZERO(ruleset); + return err; } void mlxsw_sp_flower_tmplt_destroy(struct mlxsw_sp *mlxsw_sp, diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c b/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c index 5953e04ef14e6f..2826e48af1033e 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c @@ -622,18 +622,9 @@ int sparx5_ptp_init(struct sparx5 *sparx5) sparx5->ptp = 1; } - if (!sparx5->ptp) - return 0; - - for (i = 0; i < SPARX5_PHC_COUNT; ++i) { - err = sparx5_ptp_phc_init(sparx5, i, &sparx5_ptp_clock_info); - if (err) - return err; - } - - spin_lock_init(&sparx5->ptp_clock_lock); - spin_lock_init(&sparx5->ptp_ts_id_lock); - mutex_init(&sparx5->ptp_lock); + /* The base, non-PTP-capable lan969x variants need the + * first TOD counter running to forward frames. + */ /* Disable master counters */ spx5_wr(PTP_PTP_DOM_CFG_PTP_ENA_SET(0), sparx5, PTP_PTP_DOM_CFG); @@ -657,6 +648,19 @@ int sparx5_ptp_init(struct sparx5 *sparx5) /* Enable master counters */ spx5_wr(PTP_PTP_DOM_CFG_PTP_ENA_SET(0x7), sparx5, PTP_PTP_DOM_CFG); + if (!sparx5->ptp) + return 0; + + for (i = 0; i < SPARX5_PHC_COUNT; ++i) { + err = sparx5_ptp_phc_init(sparx5, i, &sparx5_ptp_clock_info); + if (err) + return err; + } + + spin_lock_init(&sparx5->ptp_clock_lock); + spin_lock_init(&sparx5->ptp_ts_id_lock); + mutex_init(&sparx5->ptp_lock); + for (i = 0; i < sparx5->data->consts->n_ports; i++) { port = sparx5->ports[i]; if (!port) diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_tc_matchall.c b/drivers/net/ethernet/microchip/sparx5/sparx5_tc_matchall.c index 702257979462d4..146d7f28e8f3dd 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_tc_matchall.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_tc_matchall.c @@ -160,6 +160,7 @@ static int sparx5_tc_matchall_destroy(struct net_device *ndev, } list_del(&entry->list); + kfree(entry); return err; } diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 010fef79ec01e2..0da3da7d0d1b80 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -6222,6 +6222,13 @@ static netdev_features_t stmmac_fix_features(struct net_device *dev, if (priv->plat->bugged_jumbo && (dev->mtu > ETH_DATA_LEN)) features &= ~NETIF_F_CSUM_MASK; + if (priv->plat->core_type == DWMAC_CORE_XGMAC) { + if (features & NETIF_F_HW_VLAN_CTAG_RX) + features |= NETIF_F_HW_VLAN_STAG_RX; + else + features &= ~NETIF_F_HW_VLAN_STAG_RX; + } + return features; } @@ -8016,14 +8023,18 @@ static int __stmmac_dvr_probe(struct device *device, ndev->watchdog_timeo = msecs_to_jiffies(watchdog); #ifdef STMMAC_VLAN_TAG_USED /* Both mac100 and gmac support receive VLAN tag detection */ - ndev->features |= NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_STAG_RX; + ndev->features |= NETIF_F_HW_VLAN_CTAG_RX; + if (priv->plat->core_type == DWMAC_CORE_XGMAC) + ndev->features |= NETIF_F_HW_VLAN_STAG_RX; + if (dwmac_is_xmac(priv->plat->core_type)) { ndev->hw_features |= NETIF_F_HW_VLAN_CTAG_RX; priv->hw->hw_vlan_en = true; } if (priv->dma_cap.vlhash) { ndev->features |= NETIF_F_HW_VLAN_CTAG_FILTER; - ndev->features |= NETIF_F_HW_VLAN_STAG_FILTER; + if (priv->plat->core_type == DWMAC_CORE_XGMAC) + ndev->features |= NETIF_F_HW_VLAN_STAG_FILTER; } if (priv->dma_cap.vlins) ndev->features |= NETIF_F_HW_VLAN_CTAG_TX; diff --git a/drivers/net/ethernet/xilinx/xilinx_axienet.h b/drivers/net/ethernet/xilinx/xilinx_axienet.h index fcd3aaef27fc32..c63d99686d0bac 100644 --- a/drivers/net/ethernet/xilinx/xilinx_axienet.h +++ b/drivers/net/ethernet/xilinx/xilinx_axienet.h @@ -523,8 +523,9 @@ struct skbuf_dma_descriptor { * @stats_work: Work for reading the hardware statistics counters often enough * to catch overflows. * @dma_err_task: Work structure to process Axi DMA errors - * @stopping: Set when @dma_err_task shouldn't do anything because we are - * about to stop the device. + * @stopping: Set when we are about to stop the device: makes @dma_err_task + * a no-op (legacy DMA path) and fences RX descriptor + * resubmission in axienet_dma_rx_cb() (dmaengine path). * @tx_irq: Axidma TX IRQ number * @rx_irq: Axidma RX IRQ number * @eth_irq: Ethernet core IRQ number @@ -545,6 +546,7 @@ struct skbuf_dma_descriptor { * @tx_ring_tail: TX skb ring buffer tail index. * @rx_ring_head: RX skb ring buffer head index. * @rx_ring_tail: RX skb ring buffer tail index. + * @rx_submit_lock: Protects RX ring resubmission vs teardown in dmaengine path. */ struct axienet_local { struct net_device *ndev; @@ -626,6 +628,7 @@ struct axienet_local { int tx_ring_tail; int rx_ring_head; int rx_ring_tail; + spinlock_t rx_submit_lock; }; /** diff --git a/drivers/net/ethernet/xilinx/xilinx_axienet_main.c b/drivers/net/ethernet/xilinx/xilinx_axienet_main.c index fcf517069d161a..1ae4fd65e5ec51 100644 --- a/drivers/net/ethernet/xilinx/xilinx_axienet_main.c +++ b/drivers/net/ethernet/xilinx/xilinx_axienet_main.c @@ -881,6 +881,7 @@ static void axienet_dma_tx_cb(void *data, const struct dmaengine_result *result) u64_stats_update_end(&lp->tx_stat_sync); dma_unmap_sg(lp->dev, skbuf_dma->sgl, skbuf_dma->sg_len, DMA_TO_DEVICE); dev_consume_skb_any(skbuf_dma->skb); + skbuf_dma->skb = NULL; netif_txq_completed_wake(txq, 1, len, CIRC_SPACE(lp->tx_ring_head, lp->tx_ring_tail, TX_BD_NUM_MAX), 2); @@ -1171,6 +1172,7 @@ static void axienet_dma_rx_cb(void *data, const struct dmaengine_result *result) &meta_max_len); dma_unmap_single(lp->dev, skbuf_dma->dma_address, lp->max_frm_size, DMA_FROM_DEVICE); + skbuf_dma->skb = NULL; if (IS_ERR(app_metadata)) { if (net_ratelimit()) @@ -1193,10 +1195,17 @@ static void axienet_dma_rx_cb(void *data, const struct dmaengine_result *result) u64_stats_update_end(&lp->rx_stat_sync); rx_submit: + spin_lock(&lp->rx_submit_lock); + if (lp->stopping) { + spin_unlock(&lp->rx_submit_lock); + return; + } + for (i = 0; i < CIRC_SPACE(lp->rx_ring_head, lp->rx_ring_tail, RX_BUF_NUM_DEFAULT); i++) axienet_rx_submit_desc(lp->ndev); dma_async_issue_pending(lp->rx_chan); + spin_unlock(&lp->rx_submit_lock); } /** @@ -1541,6 +1550,7 @@ static int axienet_init_dmaengine(struct net_device *ndev) lp->tx_ring_head = 0; lp->rx_ring_tail = 0; lp->rx_ring_head = 0; + lp->stopping = false; lp->tx_skb_ring = kzalloc_objs(*lp->tx_skb_ring, TX_BD_NUM_MAX); if (!lp->tx_skb_ring) { ret = -ENOMEM; @@ -1752,20 +1762,42 @@ static int axienet_stop(struct net_device *ndev) free_irq(lp->rx_irq, ndev); axienet_dma_bd_release(ndev); } else { + struct skbuf_dma_descriptor *skbuf_dma; + + spin_lock_bh(&lp->rx_submit_lock); + lp->stopping = true; + spin_unlock_bh(&lp->rx_submit_lock); + dmaengine_terminate_sync(lp->tx_chan); - dmaengine_synchronize(lp->tx_chan); dmaengine_terminate_sync(lp->rx_chan); - dmaengine_synchronize(lp->rx_chan); - - for (i = 0; i < TX_BD_NUM_MAX; i++) - kfree(lp->tx_skb_ring[i]); - kfree(lp->tx_skb_ring); - for (i = 0; i < RX_BUF_NUM_DEFAULT; i++) - kfree(lp->rx_skb_ring[i]); - kfree(lp->rx_skb_ring); dma_release_channel(lp->rx_chan); dma_release_channel(lp->tx_chan); + + /* Unmap and free any buffer the terminate did not reclaim, so it + * is not leaked; a non-NULL skb marks such a slot. + */ + for (i = 0; i < TX_BD_NUM_MAX; i++) { + skbuf_dma = lp->tx_skb_ring[i]; + if (skbuf_dma && skbuf_dma->skb) { + dma_unmap_sg(lp->dev, skbuf_dma->sgl, + skbuf_dma->sg_len, DMA_TO_DEVICE); + dev_kfree_skb_any(skbuf_dma->skb); + } + kfree(skbuf_dma); + } + kfree(lp->tx_skb_ring); + + for (i = 0; i < RX_BUF_NUM_DEFAULT; i++) { + skbuf_dma = lp->rx_skb_ring[i]; + if (skbuf_dma && skbuf_dma->skb) { + dma_unmap_single(lp->dev, skbuf_dma->dma_address, + lp->max_frm_size, DMA_FROM_DEVICE); + dev_kfree_skb_any(skbuf_dma->skb); + } + kfree(skbuf_dma); + } + kfree(lp->rx_skb_ring); } netdev_reset_queue(ndev); @@ -3062,6 +3094,7 @@ static int axienet_probe(struct platform_device *pdev) spin_lock_init(&lp->rx_cr_lock); spin_lock_init(&lp->tx_cr_lock); + spin_lock_init(&lp->rx_submit_lock); INIT_WORK(&lp->rx_dim.work, axienet_rx_dim_work); lp->rx_dim_enabled = true; lp->rx_dim.profile_ix = 1; diff --git a/drivers/net/pfcp.c b/drivers/net/pfcp.c index 8bbaf167db7593..08557c03818093 100644 --- a/drivers/net/pfcp.c +++ b/drivers/net/pfcp.c @@ -64,6 +64,13 @@ static int pfcp_encap_recv(struct sock *sk, struct sk_buff *skb) goto drop; unparsed = pfcp_hdr(skb); + if (unparsed->flags & PFCP_SEID_FLAG) { + if (unlikely(!pskb_may_pull(skb, PFCP_HLEN + + offsetofend(struct pfcphdr_session, + seid)))) + goto drop; + unparsed = pfcp_hdr(skb); + } ip_tunnel_flags_zero(flags); tun_dst = udp_tun_rx_dst(skb, sk->sk_family, flags, 0, diff --git a/drivers/net/team/team_core.c b/drivers/net/team/team_core.c index feaa75fbf8fc25..3bf7c80f1d8e56 100644 --- a/drivers/net/team/team_core.c +++ b/drivers/net/team/team_core.c @@ -820,7 +820,8 @@ static struct list_head *__team_get_qom_list(struct team *team, u16 queue_id) /* * note: already called with rcu_read_lock */ -static bool team_queue_override_transmit(struct team *team, struct sk_buff *skb) +static bool team_queue_override_transmit(struct team *team, struct sk_buff *skb, + bool *tx_success) { struct list_head *qom_list; struct team_port *port; @@ -828,11 +829,11 @@ static bool team_queue_override_transmit(struct team *team, struct sk_buff *skb) if (!team->queue_override_enabled || !skb->queue_mapping) return false; qom_list = __team_get_qom_list(team, skb->queue_mapping); - list_for_each_entry_rcu(port, qom_list, qom_list) { - if (!team_dev_queue_xmit(team, port, skb)) - return true; - } - return false; + port = list_first_or_null_rcu(qom_list, struct team_port, qom_list); + if (!port) + return false; + *tx_success = !team_dev_queue_xmit(team, port, skb); + return true; } static void __team_queue_override_port_del(struct team *team, @@ -1864,8 +1865,7 @@ static netdev_tx_t team_xmit(struct sk_buff *skb, struct net_device *dev) bool tx_success; unsigned int len = skb->len; - tx_success = team_queue_override_transmit(team, skb); - if (!tx_success) + if (!team_queue_override_transmit(team, skb, &tx_success)) tx_success = READ_ONCE(team->ops.transmit)(team, skb); if (tx_success) { struct team_pcpu_stats *pcpu_stats; diff --git a/drivers/net/team/team_mode_broadcast.c b/drivers/net/team/team_mode_broadcast.c index 61d7d79f0c3638..69dc25a5847a17 100644 --- a/drivers/net/team/team_mode_broadcast.c +++ b/drivers/net/team/team_mode_broadcast.c @@ -37,6 +37,8 @@ static bool bc_transmit(struct team *team, struct sk_buff *skb) ret = !team_dev_queue_xmit(team, last, skb); if (!sum_ret) sum_ret = ret; + } else { + dev_kfree_skb_any(skb); } return sum_ret; } diff --git a/drivers/net/tun.c b/drivers/net/tun.c index 5bbe3123979e00..dcd39815205a9a 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -1818,12 +1818,7 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, } } - if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr)) { - atomic_long_inc(&tun->rx_frame_errors); - err = -EINVAL; - goto free_skb; - } - + skb->dev = tun->dev; switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: if (tun->flags & IFF_NO_PI) { @@ -1848,9 +1843,8 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, } } - skb_reset_mac_header(skb); + skb_reset_network_header(skb); skb->protocol = pi.proto; - skb->dev = tun->dev; break; case IFF_TAP: if (!pskb_may_pull(skb, ETH_HLEN)) { @@ -1858,10 +1852,19 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, drop_reason = SKB_DROP_REASON_HDR_TRUNC; goto drop; } - skb->protocol = eth_type_trans(skb, tun->dev); + skb_set_network_header(skb, ETH_HLEN); break; } + if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr)) { + atomic_long_inc(&tun->rx_frame_errors); + err = -EINVAL; + goto free_skb; + } + + if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) + skb->protocol = eth_type_trans(skb, tun->dev); + /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_zcopy_init(skb, msg_control); @@ -2469,6 +2472,8 @@ static int tun_xdp_one(struct tun_struct *tun, features = tun_vnet_hdr_guest_features(READ_ONCE(tun->vnet_hdr_sz)); tnl_hdr = (struct virtio_net_hdr_v1_hash_tunnel *)gso; + skb->dev = tun->dev; + skb_set_network_header(skb, ETH_HLEN); if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, tnl_hdr)) { atomic_long_inc(&tun->rx_frame_errors); kfree_skb(skb); diff --git a/drivers/net/usb/ax88179_178a.c b/drivers/net/usb/ax88179_178a.c index 81d8412ce8e2fa..cba1dc95d35942 100644 --- a/drivers/net/usb/ax88179_178a.c +++ b/drivers/net/usb/ax88179_178a.c @@ -1457,11 +1457,11 @@ static int ax88179_rx_fixup(struct usbnet *dev, struct sk_buff *skb) return 1; } - ax_skb = netdev_alloc_skb_ip_align(dev->net, pkt_len); + ax_skb = netdev_alloc_skb_ip_align(dev->net, pkt_len - 2); if (!ax_skb) return 0; - skb_put(ax_skb, pkt_len); - memcpy(ax_skb->data, skb->data + 2, pkt_len); + skb_put(ax_skb, pkt_len - 2); + memcpy(ax_skb->data, skb->data + 2, pkt_len - 2); ax88179_rx_checksum(ax_skb, pkt_hdr); usbnet_skb_return(dev, ax_skb); diff --git a/drivers/net/veth.c b/drivers/net/veth.c index 2780b2dd073d1c..4f145c5f686ef0 100644 --- a/drivers/net/veth.c +++ b/drivers/net/veth.c @@ -1414,6 +1414,7 @@ static int veth_open(struct net_device *dev) } veth_set_xdp_features(dev); + veth_set_xdp_features(peer); return 0; } diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index bf82ef9874abb4..daab43ac92ce42 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -2515,6 +2515,8 @@ static void virtnet_receive_done(struct virtnet_info *vi, struct receive_queue * goto frame_err; } + skb->dev = dev; + skb_set_network_header(skb, ETH_HLEN); if (virtio_net_hdr_tnl_to_skb(skb, &hdr->tnl_hdr, vi->rx_tnl, vi->rx_tnl_csum, virtio_is_little_endian(vi->vdev))) { diff --git a/drivers/net/wireguard/noise.c b/drivers/net/wireguard/noise.c index 9c0a09bf6c9562..ec2513d6dfab35 100644 --- a/drivers/net/wireguard/noise.c +++ b/drivers/net/wireguard/noise.c @@ -784,10 +784,11 @@ wg_noise_handshake_consume_response(struct message_handshake_response *src, /* Success! Copy everything to peer */ down_write(&handshake->lock); - /* It's important to check that the state is still the same, while we - * have an exclusive lock. + /* Check that the state is the same and that this is still the + * initiation we started with, while we have an exclusive lock. */ - if (handshake->state != state) { + if (handshake->state != state || + crypto_memneq(handshake->ephemeral_private, ephemeral_private, NOISE_PUBLIC_KEY_LEN)) { up_write(&handshake->lock); goto fail; } diff --git a/drivers/net/wireguard/queueing.h b/drivers/net/wireguard/queueing.h index 79b6d70de236bc..663b19b7839533 100644 --- a/drivers/net/wireguard/queueing.h +++ b/drivers/net/wireguard/queueing.h @@ -78,12 +78,14 @@ static inline void wg_reset_packet(struct sk_buff *skb, bool encapsulating) u8 l4_hash = skb->l4_hash; u8 sw_hash = skb->sw_hash; u32 hash = skb->hash; + u8 tstamp_type = skb->tstamp_type; skb_scrub_packet(skb, true); memset(&skb->headers, 0, sizeof(skb->headers)); if (encapsulating) { skb->l4_hash = l4_hash; skb->sw_hash = sw_hash; skb->hash = hash; + skb->tstamp_type = tstamp_type; } skb->queue_mapping = 0; skb->nohdr = 0; diff --git a/drivers/net/wireless/ath/ath12k/core.c b/drivers/net/wireless/ath/ath12k/core.c index 5cdf4973d986af..992602965fb494 100644 --- a/drivers/net/wireless/ath/ath12k/core.c +++ b/drivers/net/wireless/ath/ath12k/core.c @@ -1770,29 +1770,6 @@ int ath12k_core_pre_init(struct ath12k_base *ab) return 0; } -static int ath12k_core_panic_handler(struct notifier_block *nb, - unsigned long action, void *data) -{ - struct ath12k_base *ab = container_of(nb, struct ath12k_base, - panic_nb); - - return ath12k_hif_panic_handler(ab); -} - -static int ath12k_core_panic_notifier_register(struct ath12k_base *ab) -{ - ab->panic_nb.notifier_call = ath12k_core_panic_handler; - - return atomic_notifier_chain_register(&panic_notifier_list, - &ab->panic_nb); -} - -static void ath12k_core_panic_notifier_unregister(struct ath12k_base *ab) -{ - atomic_notifier_chain_unregister(&panic_notifier_list, - &ab->panic_nb); -} - static inline bool ath12k_core_hw_group_create_ready(struct ath12k_hw_group *ag) { @@ -2208,18 +2185,13 @@ int ath12k_core_init(struct ath12k_base *ab) struct ath12k_hw_group *ag; int ret; - ret = ath12k_core_panic_notifier_register(ab); - if (ret) - ath12k_warn(ab, "failed to register panic handler: %d\n", ret); - mutex_lock(&ath12k_hw_group_mutex); ag = ath12k_core_hw_group_assign(ab); if (!ag) { mutex_unlock(&ath12k_hw_group_mutex); ath12k_warn(ab, "unable to get hw group\n"); - ret = -ENODEV; - goto err_unregister_notifier; + return -ENODEV; } mutex_unlock(&ath12k_hw_group_mutex); @@ -2244,8 +2216,6 @@ int ath12k_core_init(struct ath12k_base *ab) err_unassign_hw_group: ath12k_core_hw_group_unassign(ab); -err_unregister_notifier: - ath12k_core_panic_notifier_unregister(ab); return ret; } @@ -2254,7 +2224,6 @@ void ath12k_core_deinit(struct ath12k_base *ab) { ath12k_core_hw_group_destroy(ab->ag); ath12k_core_hw_group_unassign(ab); - ath12k_core_panic_notifier_unregister(ab); } void ath12k_core_free(struct ath12k_base *ab) diff --git a/drivers/net/wireless/ath/ath12k/core.h b/drivers/net/wireless/ath/ath12k/core.h index f28d2e90b67b29..708479df4b89e8 100644 --- a/drivers/net/wireless/ath/ath12k/core.h +++ b/drivers/net/wireless/ath/ath12k/core.h @@ -15,7 +15,6 @@ #include #include #include -#include #include #include #include @@ -1146,8 +1145,6 @@ struct ath12k_base { #endif /* CONFIG_ACPI */ - struct notifier_block panic_nb; - struct ath12k_hw_group *ag; struct ath12k_wsi_info wsi_info; enum ath12k_firmware_mode fw_mode; diff --git a/drivers/net/wireless/ath/ath12k/hif.h b/drivers/net/wireless/ath/ath12k/hif.h index 4de8667690e915..aecdb0c5f2858d 100644 --- a/drivers/net/wireless/ath/ath12k/hif.h +++ b/drivers/net/wireless/ath/ath12k/hif.h @@ -30,7 +30,6 @@ struct ath12k_hif_ops { void (*ce_irq_enable)(struct ath12k_base *ab); void (*ce_irq_disable)(struct ath12k_base *ab); void (*get_ce_msi_idx)(struct ath12k_base *ab, u32 ce_id, u32 *msi_idx); - int (*panic_handler)(struct ath12k_base *ab); void (*coredump_download)(struct ath12k_base *ab); }; @@ -149,14 +148,6 @@ static inline void ath12k_hif_power_down(struct ath12k_base *ab, bool is_suspend ab->hif.ops->power_down(ab, is_suspend); } -static inline int ath12k_hif_panic_handler(struct ath12k_base *ab) -{ - if (!ab->hif.ops->panic_handler) - return NOTIFY_DONE; - - return ab->hif.ops->panic_handler(ab); -} - static inline void ath12k_hif_coredump_download(struct ath12k_base *ab) { if (ab->hif.ops->coredump_download) diff --git a/drivers/net/wireless/ath/ath12k/pci.c b/drivers/net/wireless/ath/ath12k/pci.c index fee4129ea4055b..a41544665080a8 100644 --- a/drivers/net/wireless/ath/ath12k/pci.c +++ b/drivers/net/wireless/ath/ath12k/pci.c @@ -1473,13 +1473,6 @@ void ath12k_pci_power_down(struct ath12k_base *ab, bool is_suspend) ath12k_pci_sw_reset(ab_pci->ab, false); } -static int ath12k_pci_panic_handler(struct ath12k_base *ab) -{ - ath12k_pci_sw_reset(ab, false); - - return NOTIFY_OK; -} - static const struct ath12k_hif_ops ath12k_pci_hif_ops = { .start = ath12k_pci_start, .stop = ath12k_pci_stop, @@ -1497,7 +1490,6 @@ static const struct ath12k_hif_ops ath12k_pci_hif_ops = { .ce_irq_enable = ath12k_pci_hif_ce_irq_enable, .ce_irq_disable = ath12k_pci_hif_ce_irq_disable, .get_ce_msi_idx = ath12k_pci_get_ce_msi_idx, - .panic_handler = ath12k_pci_panic_handler, #ifdef CONFIG_ATH12K_COREDUMP .coredump_download = ath12k_pci_coredump_download, #endif diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/core.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/core.c index cc660583f7cb48..891439493a5c0d 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/core.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/core.c @@ -1634,8 +1634,31 @@ void brcmf_detach(struct device *dev) brcmf_cfg80211_awdl_stop(drvr->config); /* make sure primary interface removed last */ for (i = BRCMF_MAX_IFS - 1; i > -1; i--) { - if (drvr->iflist[i]) - brcmf_remove_interface(drvr->iflist[i], false); + struct brcmf_if *ifp = drvr->iflist[i]; + + if (!ifp) + continue; + + if (ifp->ndev) { + brcmf_remove_interface(ifp, false); + continue; + } + + /* The P2P device interface has no netdev. Its removal can + * race with NL80211_CMD_DEL_INTERFACE issued by a user space + * process that is exiting (e.g. wpa_supplicant), which ends + * in brcmf_p2p_del_vif() under RTNL and the wiphy mutex. If + * both paths remove the interface, the wdev is unregistered + * twice and the vif is used after being freed. Take the same + * locks and re-read iflist, so only one path removes it. + */ + rtnl_lock(); + wiphy_lock(drvr->wiphy); + ifp = drvr->iflist[i]; + if (ifp) + brcmf_remove_interface(ifp, true); + wiphy_unlock(drvr->wiphy); + rtnl_unlock(); } brcmf_proto_detach(drvr); diff --git a/drivers/net/wireless/marvell/libertas/tx.c b/drivers/net/wireless/marvell/libertas/tx.c index 13d08022e41415..27304a98787d6a 100644 --- a/drivers/net/wireless/marvell/libertas/tx.c +++ b/drivers/net/wireless/marvell/libertas/tx.c @@ -117,13 +117,6 @@ netdev_tx_t lbs_hard_start_xmit(struct sk_buff *skb, struct net_device *dev) if (priv->wdev->iftype == NL80211_IFTYPE_MONITOR) { struct tx_radiotap_hdr *rtap_hdr = (void *)skb->data; - if (skb->len < sizeof(*rtap_hdr) + 4 + ETH_ALEN) { - lbs_deb_tx("tx err: short monitor frame %u\n", skb->len); - dev->stats.tx_dropped++; - dev->stats.tx_errors++; - goto free; - } - /* set txpd fields from the radiotap header */ txpd->tx_control = cpu_to_le32(convert_radiotap_rate_to_mv(rtap_hdr->rate)); diff --git a/drivers/net/wireless/mediatek/mt76/mt76.h b/drivers/net/wireless/mediatek/mt76/mt76.h index 476578e2fbf0c5..9188a27e78652c 100644 --- a/drivers/net/wireless/mediatek/mt76/mt76.h +++ b/drivers/net/wireless/mediatek/mt76/mt76.h @@ -539,6 +539,7 @@ struct mt76_hw_cap { #define MT_DRV_HW_MGMT_TXQ BIT(4) #define MT_DRV_AMSDU_OFFLOAD BIT(5) #define MT_DRV_IGNORE_TXS_FAILED BIT(6) +#define MT_DRV_HW_PS_BUFFERING BIT(7) struct mt76_driver_ops { u32 drv_flags; @@ -1424,6 +1425,13 @@ mtxq_to_txq(struct mt76_txq *mtxq) return container_of(ptr, struct ieee80211_txq, drv_priv); } +/* peer-wide state uses the wcid of the primary link */ +static inline struct mt76_wcid * +mt76_wcid_primary(struct mt76_wcid *wcid) +{ + return wcid->def_wcid ? wcid->def_wcid : wcid; +} + static inline struct ieee80211_sta * wcid_to_sta(struct mt76_wcid *wcid) { @@ -1541,6 +1549,8 @@ void mt76_release_buffered_frames(struct ieee80211_hw *hw, u16 tids, int nframes, enum ieee80211_frame_release_type reason, bool more_data); +void mt76_sta_ps_transition(struct mt76_dev *dev, struct mt76_wcid *wcid, + bool ps); bool mt76_has_tx_pending(struct mt76_phy *phy); int mt76_update_channel(struct mt76_phy *phy); void mt76_update_survey(struct mt76_phy *phy); diff --git a/drivers/net/wireless/mediatek/mt76/mt7603/init.c b/drivers/net/wireless/mediatek/mt76/mt7603/init.c index 10f2ec70c792b8..218ec406d2a878 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7603/init.c +++ b/drivers/net/wireless/mediatek/mt76/mt7603/init.c @@ -230,6 +230,7 @@ mt7603_mac_init(struct mt7603_dev *dev) eth_broadcast_addr(bc_addr); mt7603_wtbl_init(dev, MT7603_WTBL_RESERVED, -1, bc_addr); + mt76_wcid_init(&dev->global_sta.wcid, 0); dev->global_sta.wcid.idx = MT7603_WTBL_RESERVED; rcu_assign_pointer(dev->mt76.wcid[MT7603_WTBL_RESERVED], &dev->global_sta.wcid); diff --git a/drivers/net/wireless/mediatek/mt76/mt76_connac_mcu.h b/drivers/net/wireless/mediatek/mt76/mt76_connac_mcu.h index a9a4a87ae0a76b..fe03bc70e63a4e 100644 --- a/drivers/net/wireless/mediatek/mt76/mt76_connac_mcu.h +++ b/drivers/net/wireless/mediatek/mt76/mt76_connac_mcu.h @@ -1068,6 +1068,7 @@ enum { MCU_UNI_EVENT_IE_COUNTDOWN = 0x09, MCU_UNI_EVENT_COREDUMP = 0x0a, MCU_UNI_EVENT_BSS_BEACON_LOSS = 0x0c, + MCU_UNI_EVENT_PS_SYNC = 0x0d, MCU_UNI_EVENT_SCAN_DONE = 0x0e, MCU_UNI_EVENT_RDD_REPORT = 0x11, MCU_UNI_EVENT_ROC = 0x27, diff --git a/drivers/net/wireless/mediatek/mt76/mt7915/init.c b/drivers/net/wireless/mediatek/mt76/mt7915/init.c index 2ab38f9e525810..e768f4f72ed8e7 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7915/init.c +++ b/drivers/net/wireless/mediatek/mt76/mt7915/init.c @@ -1208,6 +1208,12 @@ static void mt7915_unregister_ext_phy(struct mt7915_dev *dev) static void mt7915_stop_hardware(struct mt7915_dev *dev) { + int i; + + mt76_for_each_q_rx(&dev->mt76, i) { + if (!mt76_queue_is_wed_rro(&dev->mt76.q_rx[i])) + napi_disable(&dev->mt76.napi[i]); + } mt7915_mcu_exit(dev); mt76_connac2_tx_token_put(&dev->mt76); mt7915_dma_cleanup(dev); diff --git a/drivers/net/wireless/mediatek/mt76/mt7915/main.c b/drivers/net/wireless/mediatek/mt76/mt7915/main.c index 4783e5f52d2293..1830398ff719f0 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7915/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7915/main.c @@ -805,6 +805,7 @@ __mt7915_drop_sta(void *ptr, u8 *mac, struct ieee80211_vif *vif) msta = (struct mt7915_sta *)sta->drv_priv; mt7915_mcu_add_sta(data->dev, vif, sta, CONN_STATE_DISCONNECT, false); + msta->wcid.tx_info &= ~MT_WCID_TX_INFO_SET; msta->wcid.sta_disabled = 1; msta->wcid.sta = 0; } @@ -871,6 +872,7 @@ int mt7915_mac_sta_event(struct mt76_dev *mdev, struct ieee80211_vif *vif, mutex_unlock(&dev->mt76.mutex); mt7915_mcu_add_sta(dev, vif, sta, CONN_STATE_DISCONNECT, false); + msta->wcid.tx_info &= ~MT_WCID_TX_INFO_SET; msta->wcid.sta_disabled = 1; msta->wcid.sta = 0; return 0; diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/mac.c b/drivers/net/wireless/mediatek/mt76/mt7925/mac.c index b52b6783306042..8603915ddc2eff 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/mac.c @@ -781,7 +781,8 @@ mt7925_mac_write_txwi(struct mt76_dev *dev, __le32 *txwi, val = FIELD_PREP(MT_TXD1_WLAN_IDX, wcid->idx) | FIELD_PREP(MT_TXD1_OWN_MAC, omac_idx); - if (band_idx) + /* 0xff means BAND_AUTO to the firmware, and TGID cannot encode it */ + if (band_idx && band_idx != 0xff) val |= FIELD_PREP(MT_TXD1_TGID, band_idx); txwi[1] = cpu_to_le32(val); diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/main.c b/drivers/net/wireless/mediatek/mt76/mt7925/main.c index 9f080da13341b3..e6e5c26307a11d 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/main.c @@ -2220,6 +2220,18 @@ mt7925_change_vif_links(struct ieee80211_hw *hw, struct ieee80211_vif *vif, mvif->valid_links = new_links; + /* Restore the legacy BSS after disabling MLO */ + if (old_links && !new_links) { + mt792x_mac_link_bss_remove(dev, &mvif->bss_conf, + &mvif->sta.deflink); + err = mt7925_mac_link_bss_add(dev, &vif->bss_conf, + &mvif->sta.deflink); + if (err < 0) { + mt792x_mutex_release(dev); + return err; + } + } + mt792x_mutex_release(dev); return 0; diff --git a/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.c b/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.c index 946dd7956e4a0d..ce5d5909d838dd 100644 --- a/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.c +++ b/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.c @@ -108,68 +108,98 @@ mt792x_asar_acpi_read_mtcl(struct mt792x_dev *dev, u8 **table, u8 *version) return ret; } +/* A table's layout is decided by the version byte in MTCL, but some firmware + * labels a version 2 table as version 1. Accept whichever layout the table + * actually has: for every accepted entry count the two do not overlap, since + * one is 6 + 5n bytes and the other 7 + 7n. + */ +static bool +mt792x_asar_fits(u8 *table, int len, int prelen, int sarlen, int nr_off, + int min, int max) +{ + int tblcnt; + + if (len < prelen || (len - prelen) % sarlen) + return false; + + tblcnt = (len - prelen) / sarlen; + if (tblcnt < min || tblcnt > max) + return false; + + return tblcnt == table[nr_off]; +} + /* MTDS : Dynamic SAR Power Table */ static int -mt792x_asar_acpi_read_mtds(struct mt792x_dev *dev, u8 **table, u8 version) +mt792x_asar_acpi_read_mtds(struct mt792x_dev *dev, u8 **table, u8 version, + u8 *used) { - int len, ret, sarlen, prelen, tblcnt; - bool enable; + int len, ret; + u8 *t; ret = mt792x_acpi_read(dev, MT792x_ACPI_MTDS, table, &len); if (ret) return ret; + t = *table; + /* Table content validation */ - switch (version) { - case 1: - enable = ((struct mt792x_asar_dyn *)*table)->enable; - sarlen = sizeof(struct mt792x_asar_dyn_limit); - prelen = sizeof(struct mt792x_asar_dyn); - break; - case 2: - enable = ((struct mt792x_asar_dyn_v2 *)*table)->enable; - sarlen = sizeof(struct mt792x_asar_dyn_limit_v2); - prelen = sizeof(struct mt792x_asar_dyn_v2); - break; - default: + if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_dyn), + sizeof(struct mt792x_asar_dyn_limit), + offsetof(struct mt792x_asar_dyn, nr_tbl), + MT792x_ASAR_MIN_DYN, MT792x_ASAR_MAX_DYN)) + *used = 1; + else if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_dyn_v2), + sizeof(struct mt792x_asar_dyn_limit_v2), + offsetof(struct mt792x_asar_dyn_v2, nr_tbl), + MT792x_ASAR_MIN_DYN, MT792x_ASAR_MAX_DYN)) + *used = 2; + else return -EINVAL; - } - tblcnt = (len - prelen) / sarlen; - if (!enable || - tblcnt > MT792x_ASAR_MAX_DYN || tblcnt < MT792x_ASAR_MIN_DYN) + if (!t[offsetof(struct mt792x_asar_dyn, enable)]) return -EINVAL; + if (version && *used != version) + dev_info(dev->mt76.dev, + "MTDS is v%u, MTCL says v%u; using v%u\n", + *used, version, *used); + return 0; } /* MTGS : Geo SAR Power Table */ static int -mt792x_asar_acpi_read_mtgs(struct mt792x_dev *dev, u8 **table, u8 version) +mt792x_asar_acpi_read_mtgs(struct mt792x_dev *dev, u8 **table, u8 version, + u8 *used) { - int len, ret, sarlen, prelen, tblcnt; + int len, ret; + u8 *t; ret = mt792x_acpi_read(dev, MT792x_ACPI_MTGS, table, &len); if (ret) return ret; + t = *table; + /* Table content validation */ - switch (version) { - case 1: - sarlen = sizeof(struct mt792x_asar_geo_limit); - prelen = sizeof(struct mt792x_asar_geo); - break; - case 2: - sarlen = sizeof(struct mt792x_asar_geo_limit_v2); - prelen = sizeof(struct mt792x_asar_geo_v2); - break; - default: + if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_geo), + sizeof(struct mt792x_asar_geo_limit), + offsetof(struct mt792x_asar_geo, nr_tbl), + MT792x_ASAR_MIN_GEO, MT792x_ASAR_MAX_GEO)) + *used = 1; + else if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_geo_v2), + sizeof(struct mt792x_asar_geo_limit_v2), + offsetof(struct mt792x_asar_geo_v2, nr_tbl), + MT792x_ASAR_MIN_GEO, MT792x_ASAR_MAX_GEO)) + *used = 2; + else return -EINVAL; - } - tblcnt = (len - prelen) / sarlen; - if (tblcnt > MT792x_ASAR_MAX_GEO || tblcnt < MT792x_ASAR_MIN_GEO) - return -EINVAL; + if (version && *used != version) + dev_info(dev->mt76.dev, + "MTGS is v%u, MTCL says v%u; using v%u\n", + *used, version, *used); return 0; } @@ -205,14 +235,16 @@ int mt792x_init_acpi_sar(struct mt792x_dev *dev) asar->countrylist = NULL; } - ret = mt792x_asar_acpi_read_mtds(dev, (u8 **)&asar->dyn, asar->ver); + ret = mt792x_asar_acpi_read_mtds(dev, (u8 **)&asar->dyn, asar->ver, + &asar->dyn_ver); if (ret) { devm_kfree(dev->mt76.dev, asar->dyn); asar->dyn = NULL; } /* MTGS is optional */ - ret = mt792x_asar_acpi_read_mtgs(dev, (u8 **)&asar->geo, asar->ver); + ret = mt792x_asar_acpi_read_mtgs(dev, (u8 **)&asar->geo, asar->ver, + &asar->geo_ver); if (ret) { devm_kfree(dev->mt76.dev, asar->geo); asar->geo = NULL; @@ -254,7 +286,7 @@ mt792x_asar_get_geo_pwr(struct mt792x_phy *phy, break; } - if (asar->ver == 1) { + if (asar->geo_ver == 1) { band_pwr = &asar->geo->tbl[idx].band[0]; max = ARRAY_SIZE(asar->geo->tbl[idx].band); } else { @@ -279,10 +311,18 @@ mt792x_asar_get_geo_pwr(struct mt792x_phy *phy, if (idx >= max) return dyn_power; - geo_power = (band_pwr + idx)->pwr; - dyn_power += (band_pwr + idx)->offset; + band_pwr += idx; + + /* Some OEM tables carry 0xff here; narrowed to s8 that is -1 and + * wins the min() below. Take it as no limit. + */ + if (band_pwr->pwr == 0xff) + return dyn_power; + + geo_power = band_pwr->pwr; - return min(geo_power, dyn_power); + return min_t(int, geo_power, + min_t(int, dyn_power + band_pwr->offset, 127)); } static s8 @@ -297,7 +337,7 @@ mt792x_asar_range_pwr(struct mt792x_phy *phy, if (!capa) return 127; - if (asar->ver == 1) { + if (asar->dyn_ver == 1) { limit = &asar->dyn->tbl[0].frp[0]; max = ARRAY_SIZE(asar->dyn->tbl[0].frp); } else { @@ -315,7 +355,9 @@ mt792x_asar_range_pwr(struct mt792x_phy *phy, else band = NL80211_BAND_2GHZ; - return mt792x_asar_get_geo_pwr(phy, band, limit[idx]); + /* 0xff: no dynamic limit, see mt792x_asar_get_geo_pwr() */ + return mt792x_asar_get_geo_pwr(phy, band, + limit[idx] == 0xff ? 127 : limit[idx]); } int mt792x_init_acpi_sar_power(struct mt792x_phy *phy, bool set_default) diff --git a/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.h b/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.h index 47403307383158..1d42f24b05f668 100644 --- a/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.h +++ b/drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.h @@ -105,6 +105,8 @@ struct mt792x_asar_fg { struct mt792x_acpi_sar { u8 ver; + u8 dyn_ver; + u8 geo_ver; union { struct mt792x_asar_dyn *dyn; struct mt792x_asar_dyn_v2 *dyn_v2; diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/init.c b/drivers/net/wireless/mediatek/mt76/mt7996/init.c index fa74aba4269037..95fb30404b8579 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/init.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/init.c @@ -536,6 +536,7 @@ mt7996_init_wiphy(struct ieee80211_hw *hw, struct mtk_wed_device *wed) ieee80211_hw_set(hw, NO_VIRTUAL_MONITOR); ieee80211_hw_set(hw, SUPPORTS_MULTI_BSSID); ieee80211_hw_set(hw, CHANCTX_STA_CSA); + ieee80211_hw_set(hw, CONNECTION_MONITOR); hw->max_tx_fragments = 4; wiphy->txq_memory_limit = 32 << 20; /* 32 MiB */ @@ -1237,7 +1238,7 @@ static int mt7996_variant_fem_init(struct mt7996_dev *dev) adie_ver = u32_get_bits(regval, MT_ADIE_VERSION_MASK); idx = MT7976C_EFUSE_OFFSET % MT7996_EEPROM_BLOCK_SIZE; is_7976c = adie_ver == 0x8a10 || adie_ver == 0x8b00 || - adie_ver == 0x8c10 || buf[idx] == 0xc; + adie_ver == 0x8c10 || (!ret && buf[idx] == 0xc); adie_id = u32_get_bits(regval, MT_ADIE_CHIP_ID_MASK); if (adie_id == 0x7975 || adie_id == 0x7979 || diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/main.c b/drivers/net/wireless/mediatek/mt76/mt7996/main.c index c6140412ed3227..ae006f29091fff 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/main.c @@ -310,7 +310,14 @@ int mt7996_vif_link_add(struct mt76_phy *mphy, struct ieee80211_vif *vif, if (vif->type == NL80211_IFTYPE_AP) return mt7996_mcu_mld_link_oper(dev, link_conf, link, true); - return 0; + + /* update the link address */ + ret = mt7996_mcu_add_dev_info(phy, vif, link_conf, mlink, true); + if (ret) + return ret; + + return mt7996_mcu_add_bss_info(phy, vif, link_conf, mlink, + msta_link, true); } mlink->idx = __ffs64(~dev->mt76.vif_mask); @@ -1422,6 +1429,7 @@ mt7996_mac_sta_event(struct mt7996_dev *dev, struct ieee80211_vif *vif, else if (sta->mlo && links == BIT(link_id)) /* last link */ mt7996_mcu_teardown_mld_sta(dev, link, msta_link); + msta_link->wcid.tx_info &= ~MT_WCID_TX_INFO_SET; msta_link->wcid.sta_disabled = 1; msta_link->wcid.sta = 0; links = links & ~BIT(link_id); diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h b/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h index c673e986ecb52a..288b923750c0da 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h +++ b/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h @@ -284,6 +284,9 @@ struct mt7996_mcu_wed_rro_ba_delete_event { __le16 len; __le16 session_id; + __le16 wlan_id; + u8 tid; + u8 __rsv1; u8 __rsv2[2]; } __packed; diff --git a/drivers/net/wireless/mediatek/mt76/tx.c b/drivers/net/wireless/mediatek/mt76/tx.c index b03be0eb471282..65703dbb185c98 100644 --- a/drivers/net/wireless/mediatek/mt76/tx.c +++ b/drivers/net/wireless/mediatek/mt76/tx.c @@ -234,6 +234,8 @@ mt76_tx_check_non_aql(struct mt76_dev *dev, struct mt76_wcid *wcid, if (!wcid || info->tx_time_est) return; + wcid = mt76_wcid_primary(wcid); + pending = atomic_dec_return(&wcid->non_aql_packets); if (pending < 0) atomic_cmpxchg(&wcid->non_aql_packets, pending, 0); @@ -267,6 +269,21 @@ void __mt76_tx_complete_skb(struct mt76_dev *dev, u16 wcid_idx, struct sk_buff * wcid = __mt76_wcid_ptr(dev, wcid_idx); mt76_tx_check_non_aql(dev, wcid, skb); + if (wcid && (dev->drv->drv_flags & MT_DRV_HW_PS_BUFFERING) && + test_bit(MT_WCID_FLAG_PS, &wcid->flags)) { + struct ieee80211_sta *sta = wcid_to_sta(wcid); + + if (sta) { + struct ieee80211_hw *hw = mt76_phy_hw(dev, wcid->phy_idx); + int i; + + for (i = 0; i < ARRAY_SIZE(sta->txq); i++) + if (sta->txq[i]) + ieee80211_schedule_txq(hw, sta->txq[i]); + mt76_worker_schedule(&dev->tx_worker); + } + } + #ifdef CONFIG_NL80211_TESTMODE if (mt76_is_testmode_skb(dev, skb, &hw)) { struct mt76_phy *phy = hw->priv; @@ -329,7 +346,8 @@ __mt76_tx_queue_skb(struct mt76_phy *phy, int qid, struct sk_buff *skb, if (!non_aql) return idx; - pending = atomic_inc_return(&wcid->non_aql_packets); + /* the hardware can report the completion on a different link */ + pending = atomic_inc_return(&mt76_wcid_primary(wcid)->non_aql_packets); if (stop && pending >= MT_MAX_NON_AQL_PKT) *stop = true; @@ -476,10 +494,15 @@ mt76_txq_send_burst(struct mt76_phy *phy, struct mt76_queue *q, bool stop = false; int idx; - if (test_bit(MT_WCID_FLAG_PS, &wcid->flags)) - return 0; + if (test_bit(MT_WCID_FLAG_PS, &wcid->flags)) { + if (!(dev->drv->drv_flags & MT_DRV_HW_PS_BUFFERING)) + return 0; + if (ieee80211_txq_aql_pending(phy->hw, txq)) + return 0; + } - if (atomic_read(&wcid->non_aql_packets) >= MT_MAX_NON_AQL_PKT) + if (atomic_read(&mt76_wcid_primary(wcid)->non_aql_packets) >= + MT_MAX_NON_AQL_PKT) return 0; skb = mt76_txq_dequeue(phy, mtxq); @@ -497,6 +520,9 @@ mt76_txq_send_burst(struct mt76_phy *phy, struct mt76_queue *q, if (idx < 0) return idx; + if (test_bit(MT_WCID_FLAG_PS, &wcid->flags)) + goto out; + do { if (test_bit(MT76_RESET, &phy->state) || phy->offchannel) break; @@ -522,6 +548,7 @@ mt76_txq_send_burst(struct mt76_phy *phy, struct mt76_queue *q, n_frames++; } while (1); +out: spin_lock(&q->lock); dev->queue_ops->kick(dev, q); spin_unlock(&q->lock); @@ -548,10 +575,7 @@ mt76_txq_schedule_list(struct mt76_phy *phy, enum mt76_txq_id qid) mtxq = (struct mt76_txq *)txq->drv_priv; wcid = __mt76_wcid_ptr(dev, mtxq->wcid); - if (!wcid || test_bit(MT_WCID_FLAG_PS, &wcid->flags)) - continue; - - if (atomic_read(&wcid->non_aql_packets) >= MT_MAX_NON_AQL_PKT) + if (!wcid) continue; phy = mt76_dev_phy(dev, wcid->phy_idx); @@ -559,6 +583,25 @@ mt76_txq_schedule_list(struct mt76_phy *phy, enum mt76_txq_id qid) continue; q = phy->q_tx[qid]; + + if (test_bit(MT_WCID_FLAG_PS, &wcid->flags)) { + if (!(dev->drv->drv_flags & MT_DRV_HW_PS_BUFFERING)) + continue; + + if (!mt76_txq_stopped(q)) + n_frames = mt76_txq_send_burst(phy, q, mtxq, wcid); + + ieee80211_return_txq(phy->hw, txq, false); + + if (unlikely(n_frames < 0)) + return n_frames; + ret += n_frames; + continue; + } + + if (atomic_read(&mt76_wcid_primary(wcid)->non_aql_packets) >= + MT_MAX_NON_AQL_PKT) + continue; if (dev->queue_ops->tx_cleanup && q->queued + 2 * MT_TXQ_FREE_THR >= q->ndesc) { dev->queue_ops->tx_cleanup(dev, q, false); @@ -629,7 +672,8 @@ mt76_txq_schedule_pending_wcid(struct mt76_phy *phy, struct mt76_wcid *wcid, if ((dev->drv->drv_flags & MT_DRV_HW_MGMT_TXQ) && !(info->flags & IEEE80211_TX_CTL_HW_80211_ENCAP) && !ieee80211_is_data_present(hdr->frame_control) && - (!ieee80211_is_bufferable_mmpdu(skb) || + (!(wcid->tx_info & MT_WCID_TX_INFO_SET) || + !ieee80211_is_bufferable_mmpdu(skb) || ieee80211_is_deauth(hdr->frame_control) || ieee80211_is_disassoc(hdr->frame_control) || head == &wcid->tx_offchannel)) @@ -765,6 +809,33 @@ void mt76_stop_tx_queues(struct mt76_phy *phy, struct ieee80211_sta *sta, } EXPORT_SYMBOL_GPL(mt76_stop_tx_queues); +void mt76_sta_ps_transition(struct mt76_dev *dev, struct mt76_wcid *wcid, + bool ps) +{ + struct ieee80211_sta *sta; + struct ieee80211_hw *hw; + int i; + + if (ps) { + set_bit(MT_WCID_FLAG_PS, &wcid->flags); + mt76_worker_schedule(&dev->tx_worker); + return; + } + + clear_bit(MT_WCID_FLAG_PS, &wcid->flags); + + sta = wcid_to_sta(wcid); + if (!sta) + return; + + hw = mt76_phy_hw(dev, wcid->phy_idx); + for (i = 0; i < ARRAY_SIZE(sta->txq); i++) + if (sta->txq[i]) + ieee80211_schedule_txq(hw, sta->txq[i]); + mt76_worker_schedule(&dev->tx_worker); +} +EXPORT_SYMBOL_GPL(mt76_sta_ps_transition); + void mt76_wake_tx_queue(struct ieee80211_hw *hw, struct ieee80211_txq *txq) { struct mt76_phy *phy = hw->priv; diff --git a/drivers/net/xen-netfront.c b/drivers/net/xen-netfront.c index d269457e839ea9..fdcb91042f2906 100644 --- a/drivers/net/xen-netfront.c +++ b/drivers/net/xen-netfront.c @@ -1346,8 +1346,10 @@ static int xennet_poll(struct napi_struct *napi, int budget) skb->data_len = rx->status; skb->len += rx->status; - if (unlikely(xennet_fill_frags(queue, skb, &tmpq))) + if (unlikely(xennet_fill_frags(queue, skb, &tmpq))) { + __skb_queue_head(&tmpq, skb); goto err; + } if (rx->flags & XEN_NETRXF_csum_blank) skb->ip_summed = CHECKSUM_PARTIAL; diff --git a/drivers/nvme/target/core.c b/drivers/nvme/target/core.c index 2aa9ded7d55148..0b1f800c6cc8fd 100644 --- a/drivers/nvme/target/core.c +++ b/drivers/nvme/target/core.c @@ -1310,7 +1310,7 @@ static int nvmet_req_alloc_p2pmem_sgls(struct pci_dev *p2p_dev, return 0; out_free_sg: - pci_p2pmem_free_sgl(req->p2p_dev, req->sg); + pci_p2pmem_free_sgl(p2p_dev, req->sg); out_err: return -ENOMEM; } diff --git a/drivers/nvme/target/pr.c b/drivers/nvme/target/pr.c index ad07f55e7f173f..acb44df15fc7ea 100644 --- a/drivers/nvme/target/pr.c +++ b/drivers/nvme/target/pr.c @@ -51,6 +51,8 @@ u16 nvmet_set_feat_resv_notif_mask(struct nvmet_req *req, u32 mask) if (nsid != U32_MAX) { status = nvmet_req_find_ns(req); + if (status == (NVME_SC_INVALID_NS | NVME_STATUS_DNR)) + return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR; if (status) return status; if (!req->ns->pr.enable) @@ -75,6 +77,8 @@ u16 nvmet_get_feat_resv_notif_mask(struct nvmet_req *req) u16 status; status = nvmet_req_find_ns(req); + if (status == (NVME_SC_INVALID_NS | NVME_STATUS_DNR)) + return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR; if (status) return status; diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index eb0dbb9037babd..9067059f0675df 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -991,7 +991,43 @@ static void atcphy_test_usb2_init_after_safe(struct kunit *test) KUNIT_EXPECT_EQ(test, atcphy->mode, APPLE_ATCPHY_MODE_OFF); } +static void atcphy_test_t8103_usb3_machine_scope(struct kunit *test) +{ + static const struct { + const char *compatible; + bool enabled; + } cases[] = { + { "apple,t8103", true }, + { "apple,t6000", false }, + { "apple,t6001", false }, + { "apple,t6002", false }, + { "apple,t8112", false }, + { "apple,t6020", false }, + { "apple,t6021", false }, + { "apple,t6022", false }, + { "apple,t8122", false }, + { "apple,t6030", false }, + { "apple,t6031", false }, + { "apple,t6034", false }, + { "apple,t8140", false }, + { "apple,t8142", false }, + }; + struct property compatible = { .name = "compatible" }; + struct device_node root = { .properties = &compatible }; + + for (size_t i = 0; i < ARRAY_SIZE(cases); i++) { + compatible.value = (void *)cases[i].compatible; + compatible.length = strlen(cases[i].compatible) + 1; + /* M2 and Pro/Max PHYs select this same fallback hardware row. */ + KUNIT_EXPECT_EQ(test, atcphy_has_t8103_usb3_workaround(&atcphy_hw_t8103, &root), + cases[i].enabled); + KUNIT_EXPECT_FALSE(test, + atcphy_has_t8103_usb3_workaround(&atcphy_hw_t8122, &root)); + } +} + static struct kunit_case atcphy_mux_test_cases[] = { + KUNIT_CASE(atcphy_test_t8103_usb3_machine_scope), KUNIT_CASE(atcphy_test_target_mode), KUNIT_CASE(atcphy_test_target_mode_fixed_hub), KUNIT_CASE(atcphy_test_noop_same_mode), diff --git a/drivers/phy/apple/atc-tunnel-test.c b/drivers/phy/apple/atc-tunnel-test.c index e5decf7480a686..15f10557073328 100644 --- a/drivers/phy/apple/atc-tunnel-test.c +++ b/drivers/phy/apple/atc-tunnel-test.c @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause #include +#include #include "atc-tunnel.h" @@ -90,7 +91,21 @@ static void atc_tunnel_wiring_gate(struct kunit *test) cases[i].expected); } +static void atc_tunnel_t6030_clock_sources(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(0, 0), 0); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(2, 0), 0); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(0, 1), 1); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(2, 1), 1); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(1, 0), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(4, 0), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(0, 2), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(~0U, 0), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, apple_dp_tunnel_t6030_pclk(0, ~0U), -EOPNOTSUPP); +} + static struct kunit_case atc_tunnel_cases[] = { + KUNIT_CASE(atc_tunnel_t6030_clock_sources), KUNIT_CASE(atc_tunnel_soc_qualification), KUNIT_CASE(atc_tunnel_core_qualification), KUNIT_CASE(atc_tunnel_wiring_gate), diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 51e2e9d18e5ed8..4ce4ad5062504f 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -722,13 +722,17 @@ struct atcphy_hw { * @tunnel_rate: DP link rate code the t8103 tunnel pixel clock is set up for * @tunnel_users: DP IN adapters (BIT(dpin)) whose tunnel pixel clock runs; on * t8103 and t600x both share the one clock - * @tunnel_dpin_rate: DP link rate code each T602X DP IN adapter's clock runs at + * @tunnel_dpin_rate: DP link rate code each T602X/T6030 DP IN clock runs at + * @tunnel_source: T6030 display source owning each DP IN clock * @dp_t8122: DisplayPort state of a T8122 generation PHY * @dp_t8122.aux: The AUX channel block is powered * @dp_t8122.pll: The AUSPLL runs for the DisplayPort main link * @dp_t8122.pairs: Lane pairs (bit mask) whose DisplayPort transmitters run * @dp_t8122.rate: Main link rate in Mb/s per lane, 0 while stopped * @pipe_state: Backend the PIPE mux ("pipehandler") is routed to + * @t8103_dummy_pending: A live T8103-generation handoff still needs its unlock ACK + * @t8103_usb3_retry: USB3 routing owed after a deferred role or parked lane change + * @t8103_usb3_workaround: Base M1 admission for the USB3 handoff workaround * @pd_nb: Power domain notifier, registered with restore_after_pd_off * @pd_was_off: The power domain was switched off since the state was last * brought back; set from the notifier, cleared under @lock @@ -794,6 +798,9 @@ struct apple_atcphy { int dp_link_rate; bool swap_lanes; enum atcphy_pipehandler_state pipe_state; + bool t8103_dummy_pending; + bool t8103_usb3_retry; + bool t8103_usb3_workaround; struct notifier_block pd_nb; bool pd_was_off; @@ -806,6 +813,7 @@ struct apple_atcphy { u8 tunnel_rate; u8 tunnel_users; u8 tunnel_dpin_rate[2]; + unsigned int tunnel_source[2]; /* T6030 source owning each DP IN clock */ struct { bool aux; @@ -1192,6 +1200,22 @@ static int atcphy_pipehandler_lock(struct apple_atcphy *atcphy) return ret; } +/* Retry only a live legacy PIPE: USB4 and stopped parking cannot clock the ACK. */ +static int atcphy_pipehandler_lock_live(struct apple_atcphy *atcphy) +{ + unsigned int attempts = atcphy->t8103_usb3_workaround ? 10 : 1; + int ret; + + for (unsigned int attempt = 0; attempt < attempts; attempt++) { + ret = atcphy_pipehandler_lock(atcphy); + if (!ret) + return 0; + if (attempt + 1 < attempts) + usleep_range(5000, 10000); + } + return ret; +} + static int atcphy_pipehandler_unlock(struct apple_atcphy *atcphy) { int ret; @@ -1621,14 +1645,18 @@ static int atcphy_configure_pipehandler_dummy(struct apple_atcphy *atcphy, bool static int atcphy_configure_pipehandler(struct apple_atcphy *atcphy, bool host) { enum atcphy_pipehandler_state state = atcphy_modes[atcphy->mode].pipehandler_state; + bool host_bist = host && !atcphy->t8103_usb3_workaround; int ret = -EINVAL; lockdep_assert_held(&atcphy->lock); + if (atcphy->t8103_dummy_pending) + return -EBUSY; switch (state) { case ATCPHY_PIPEHANDLER_STATE_USB3: atcphy->pipe_pending = true; - ret = atcphy_configure_pipehandler_usb3(atcphy, host); + /* Legacy host BIST can hide the first xHCI link-detection scan. */ + ret = atcphy_configure_pipehandler_usb3(atcphy, host_bist); break; case ATCPHY_PIPEHANDLER_STATE_USB4: ret = atcphy_configure_pipehandler_usb4(atcphy); @@ -1640,11 +1668,73 @@ static int atcphy_configure_pipehandler(struct apple_atcphy *atcphy, bool host) if (!ret) { atcphy->pipe_state = state; atcphy->pipe_pending = false; + if (state == ATCPHY_PIPEHANDLER_STATE_USB3) + atcphy->t8103_usb3_retry = false; } return ret; } +/* + * Park a live T8103 USB3 backend before a Type-C lane change. Unlike legacy + * shutdown, an unacknowledged handoff must not let the lane change continue. + */ +static int atcphy_park_live_t8103_pipehandler(struct apple_atcphy *atcphy) +{ + const u32 override_mask = PIPEHANDLER_OVERRIDE_RXVALID | + PIPEHANDLER_OVERRIDE_RXDETECT; + const u32 value_mask = PIPEHANDLER_OVERRIDE_VAL_RXDETECT0 | + PIPEHANDLER_OVERRIDE_VAL_RXDETECT1; + void __iomem *pipe = atcphy->regs.pipehandler; + u32 overrides, values; + int ret; + + lockdep_assert_held(&atcphy->lock); + if (!atcphy->t8103_usb3_workaround) + return -EOPNOTSUPP; + + if (!atcphy->t8103_dummy_pending) { + if (atcphy->pipe_state == ATCPHY_PIPEHANDLER_STATE_DUMMY) + return 0; + if (atcphy->pipe_state != ATCPHY_PIPEHANDLER_STATE_USB3) + return -EBUSY; + ret = atcphy_pipehandler_check(atcphy); + if (ret) + return ret; + overrides = readl(pipe + PIPEHANDLER_OVERRIDE); + values = readl(pipe + PIPEHANDLER_OVERRIDE_VALUES); + clear32(pipe + PIPEHANDLER_OVERRIDE_VALUES, value_mask); + set32(pipe + PIPEHANDLER_OVERRIDE, override_mask); + + ret = atcphy_pipehandler_lock_live(atcphy); + if (ret) { + /* The mux did not move: restore only the fields we touched. */ + mask32(pipe + PIPEHANDLER_OVERRIDE_VALUES, value_mask, + values & value_mask); + mask32(pipe + PIPEHANDLER_OVERRIDE, override_mask, + overrides & override_mask); + return ret; + } + atcphy_pipehandler_set_mux(atcphy, PIPEHANDLER_MUX_CTRL_DATA_DUMMY, + PIPEHANDLER_MUX_CTRL_CLK_DUMMY); + /* The physical mux moved even if completion now fails. */ + atcphy->pipe_state = ATCPHY_PIPEHANDLER_STATE_DUMMY; + atcphy->t8103_dummy_pending = true; + atcphy->t8103_usb3_retry = true; + } + + /* Retry completion without requesting another lock on the dummy clock. */ + ret = atcphy_pipehandler_unlock(atcphy); + if (ret) + return ret; + mask32(pipe + PIPEHANDLER_NONSELECTED_OVERRIDE, + PIPEHANDLER_NATIVE_POWER_DOWN, FIELD_PREP(PIPEHANDLER_NATIVE_POWER_DOWN, 2)); + set32(pipe + PIPEHANDLER_NONSELECTED_OVERRIDE, PIPEHANDLER_NATIVE_RESET); + atcphy->t8103_dummy_pending = false; + atcphy->pipe_pending = false; + return 0; +} + /* Route the PIPE back to the dummy backend unless it is there already */ static int atcphy_park_pipehandler(struct apple_atcphy *atcphy, bool stopped) { @@ -1656,6 +1746,10 @@ static int atcphy_park_pipehandler(struct apple_atcphy *atcphy, bool stopped) dev_dbg(atcphy->dev, "PIPE park: mode=%u pipe=%u host=%u dirty=%u owned=%u idle=%u\n", atcphy->mode, atcphy->pipe_state, atcphy->host_active, atcphy->mode_dirty, atcphy->dp_owned_pmas, atcphy->dp_idle_pmas); + if (atcphy->t8103_dummy_pending || + (!stopped && atcphy->t8103_usb3_workaround && + atcphy->pipe_state == ATCPHY_PIPEHANDLER_STATE_USB3)) + return atcphy_park_live_t8103_pipehandler(atcphy); if (atcphy->pipe_state == ATCPHY_PIPEHANDLER_STATE_DUMMY && !atcphy->pipe_pending) return 0; @@ -1677,6 +1771,8 @@ static void atcphy_setup_pipehandler(struct apple_atcphy *atcphy) PIPEHANDLER_MUX_CTRL_CLK_DUMMY); atcphy->pipe_state = ATCPHY_PIPEHANDLER_STATE_DUMMY; atcphy->pipe_pending = false; + atcphy->t8103_dummy_pending = false; + atcphy->t8103_usb3_retry = false; if (atcphy_needs_dummy_phy(atcphy)) atcphy_enable_dummy_phy(atcphy); } @@ -2534,10 +2630,40 @@ static int atc_t8122_tunnel_stop(struct apple_atcphy *atcphy) } atcphy->tunnel_clock_on = false; atcphy->tunnel_rate = 0; + atcphy->tunnel_users = 0; + atcphy->tunnel_dpin_rate[0] = 0; + atcphy->tunnel_dpin_rate[1] = 0; return 0; } -static int atc_t8122_tunnel_start(struct apple_atcphy *atcphy, u8 rate) +static void atc_t8122_tunnel_pclk(struct apple_atcphy *atcphy, + unsigned int pclk, u32 selector) +{ + u32 enable = pclk ? DPTX_PCLK2_ENABLE : DPTX_PCLK1_ENABLE; + u32 select = pclk ? DPTX_PCLK2_SELECT : DPTX_PCLK1_SELECT; + u32 value = pclk ? FIELD_PREP(DPTX_PCLK2_SELECT, selector) : + FIELD_PREP(DPTX_PCLK1_SELECT, selector); + + lockdep_assert_held(&atcphy->lock); + /* PCLK1 is also DPIN1's prerequisite: retuning DPIN0 must not gate it. */ + if (!pclk && (atcphy->tunnel_users & BIT(1))) + value |= DPTX_PCLK1_ENABLE; + core_mask32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, + enable | select, value); + /* Enable the prerequisite before the second stream's pixel clock. */ + if (pclk) { + if (!(atcphy->tunnel_users & BIT(0))) + core_mask32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, + DPTX_PCLK1_SELECT, + FIELD_PREP(DPTX_PCLK1_SELECT, selector)); + core_set32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, + DPTX_PCLK1_ENABLE); + } + core_set32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, enable); +} + +static int atc_t8122_tunnel_start(struct apple_atcphy *atcphy, + unsigned int pclk, u8 rate) { u32 selector, value, saved_tx; int ret, cleanup; @@ -2563,13 +2689,7 @@ static int atc_t8122_tunnel_start(struct apple_atcphy *atcphy, u8 rate) /* A failed shutdown retains ownership, but is not a running clock. */ if (!atcphy->tunnel_rate) return -EBUSY; - if (atcphy->tunnel_rate == rate) - return 0; - core_mask32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, - DPTX_PCLK1_ENABLE | DPTX_PCLK1_SELECT, - FIELD_PREP(DPTX_PCLK1_SELECT, selector)); - core_set32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, - DPTX_PCLK1_ENABLE); + atc_t8122_tunnel_pclk(atcphy, pclk, selector); atcphy->tunnel_rate = rate; return 0; } @@ -2582,7 +2702,8 @@ static int atc_t8122_tunnel_start(struct apple_atcphy *atcphy, u8 rate) /* Inactive slots use selector zero; all gates stay off during PLL setup. */ core_mask32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, GENMASK(15, 4), - FIELD_PREP(DPTX_PCLK1_SELECT, selector)); + FIELD_PREP(DPTX_PCLK1_SELECT, selector) | + (pclk ? FIELD_PREP(DPTX_PCLK2_SELECT, selector) : 0)); core_set32(atcphy, ACIOPHY_CFG0, ACIOPHY_CFG0_COMMON_SMALL); core_set32(atcphy, ACIOPHY_CFG0, ACIOPHY_CFG0_COMMON_SMALL_OV); udelay(1); @@ -2624,7 +2745,7 @@ static int atc_t8122_tunnel_start(struct apple_atcphy *atcphy, u8 rate) goto fail; core_set32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, DPTXPHY_PMA_LANE_RESET_N | DPTXPHY_PMA_LANE_RESET_N_OV); - core_set32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, DPTX_PCLK1_ENABLE); + atc_t8122_tunnel_pclk(atcphy, pclk, selector); atcphy->tunnel_rate = rate; return 0; @@ -3098,7 +3219,7 @@ static int atc_tunnel_set_t602x(struct apple_atcphy *atcphy, unsigned int dpin, return 0; } -/* T6030 (M3 Pro): T8122-generation PHYs, only the DP IN0 route so far. */ +/* T6030 (M3 Pro) uses T8122-generation PHYs for both DP IN clock outputs. */ static bool apple_atc_tunnel_is_t6030(struct apple_atcphy *atcphy) { return of_machine_is_compatible("apple,t6030") && @@ -3331,6 +3452,8 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) KUNIT_STATIC_STUB_REDIRECT(atcphy_configure, atcphy, mode); lockdep_assert_held(&atcphy->lock); + if (atcphy->t8103_dummy_pending) + return -EBUSY; if (atcphy->pipe_pending) return -EBUSY; if (atcphy->usb_off_pending && mode != APPLE_ATCPHY_MODE_OFF) @@ -3636,6 +3759,7 @@ static int atcphy_usb3_power_off(struct phy *phy) ret = atcphy_park_pipehandler(atcphy, true); if (ret) return ret; + atcphy->t8103_usb3_retry = false; /* * dwc3 can tear its host down while a DisplayPort alt mode link is up, * e.g. when a monitor's built-in hub re-enumerates after a hot-plug. @@ -3661,6 +3785,12 @@ static int atcphy_usb3_route(struct apple_atcphy *atcphy, bool host) int ret; lockdep_assert_held(&atcphy->lock); + if (atcphy->t8103_dummy_pending) { + ret = atcphy_park_live_t8103_pipehandler(atcphy); + if (ret) + return ret; + } + /* * We may get multiple calls to set_mode (for host mode e.g. at least one from the dwc3 glue @@ -3671,6 +3801,19 @@ static int atcphy_usb3_route(struct apple_atcphy *atcphy, bool host) /* A failed lane/domain transition must be restored before routing PIPE. */ if (atcphy->mode_dirty) return -EBUSY; + /* dwc3 can select its role before the debounced Type-C mux update. */ + if (atcphy->t8103_usb3_workaround && + atcphy->mode == APPLE_ATCPHY_MODE_OFF) { + /* Keep the valid role's route owed across a late mux update or failure. */ + atcphy->t8103_usb3_retry = true; + if (atcphy->typec_mode != APPLE_ATCPHY_MODE_USB3) + return 0; + if (atcphy->dp_only || !atcphy->ss_tunables) + return -EOPNOTSUPP; + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_USB3); + if (ret) + return ret; + } if (atcphy->pipe_pending) { ret = atcphy_park_pipehandler(atcphy, false); if (ret) @@ -3849,6 +3992,62 @@ static bool apple_atc_tunnel_is_t8103_style(void) of_machine_is_compatible("apple,t8112") || apple_atc_tunnel_is_t600x(); } +int apple_atc_dp_tunnel_rate_source(struct phy *phy, unsigned int source, + unsigned int dpin, u8 rate) +{ + struct apple_atcphy *atcphy; + int pclk, ret; + + if (!phy || phy->ops != &apple_atc_dp_phy_ops || dpin > 1) + return -EINVAL; + atcphy = phy_get_drvdata(phy); + pclk = apple_dp_tunnel_t6030_pclk(source, dpin); + if (!apple_atc_tunnel_is_t6030(atcphy) || pclk < 0) + return -EOPNOTSUPP; + guard(mutex)(&atcphy->lock); + atcphy_restore_after_pd_off(atcphy); + /* A stale source must not retune or stop another source's clock. */ + if ((atcphy->tunnel_users & BIT(dpin)) && + atcphy->tunnel_source[dpin] != source) + return -ESTALE; + if (!rate) { + if (!(atcphy->tunnel_users & BIT(dpin))) + return 0; + if (!(atcphy->tunnel_users & ~BIT(dpin))) + return atc_t8122_tunnel_stop(atcphy); + /* Release only this stream; the other stream keeps its PLL and gates. */ + if (pclk) + core_clear32(atcphy, ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0, + DPTX_PCLK2_ENABLE); + atcphy->tunnel_users &= ~BIT(dpin); + atcphy->tunnel_dpin_rate[dpin] = 0; + return 0; + } + if (atcphy->mode != APPLE_ATCPHY_MODE_USB4 && + atcphy->mode != APPLE_ATCPHY_MODE_TBT) + return -EBUSY; + if (atcphy->tunnel_clock_on && !atcphy->tunnel_rate) + return -EBUSY; + /* Keep this owner if a failed start cannot shut the PLL down. */ + if ((atcphy->tunnel_users & BIT(1 - dpin)) && + atcphy->tunnel_source[1 - dpin] == source) + return -EBUSY; + if ((atcphy->tunnel_users & BIT(dpin)) && + atcphy->tunnel_dpin_rate[dpin] == rate && atcphy->tunnel_rate) + return 0; + atcphy->tunnel_source[dpin] = source; + ret = atc_t8122_tunnel_start(atcphy, pclk, rate); + if (!ret || (atcphy->tunnel_clock_on && !atcphy->tunnel_rate)) { + atcphy->tunnel_users |= BIT(dpin); + atcphy->tunnel_dpin_rate[dpin] = ret ? 0 : rate; + } + dev_dbg(atcphy->dev, "DP tunnel source %u rate 0x%x: %d (TX_DP_CTRL0=%08x PCLK_STAT=%08x)\n", + source, rate, ret, + readl(atcphy->regs.core + ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0), + readl(atcphy->regs.core + T8122_DP_PCLK_STATUS)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_atc_dp_tunnel_rate_source); int apple_atc_dp_tunnel_rate(struct phy *phy, unsigned int dpin, u8 rate) { @@ -3859,23 +4058,8 @@ int apple_atc_dp_tunnel_rate(struct phy *phy, unsigned int dpin, u8 rate) return -EINVAL; atcphy = phy_get_drvdata(phy); /* Keep each supported SoC on its qualified clock sequence. */ - if (apple_atc_tunnel_is_t6030(atcphy)) { - if (dpin) - return -EOPNOTSUPP; - guard(mutex)(&atcphy->lock); - atcphy_restore_after_pd_off(atcphy); - if (!rate) - return atc_t8122_tunnel_stop(atcphy); - if (atcphy->mode != APPLE_ATCPHY_MODE_USB4 && - atcphy->mode != APPLE_ATCPHY_MODE_TBT) - return -EBUSY; - ret = atc_t8122_tunnel_start(atcphy, rate); - dev_dbg(atcphy->dev, "DP tunnel clock rate 0x%x: %d (TX_DP_CTRL0=%08x PCLK_STAT=%08x)\n", - rate, ret, - readl(atcphy->regs.core + ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0), - readl(atcphy->regs.core + T8122_DP_PCLK_STATUS)); - return ret; - } + if (apple_atc_tunnel_is_t6030(atcphy)) + return apple_atc_dp_tunnel_rate_source(phy, 0, dpin, rate); if (!apple_atc_tunnel_is_t8103_style()) { bool valid_core = apple_atc_t602x_core_valid(atcphy->np, atcphy->res.core->start, resource_size(atcphy->res.core)); @@ -4013,6 +4197,7 @@ static int atcphy_dwc3_reset_assert(struct reset_controller_dev *rcdev, unsigned if (ret) return ret; + atcphy->t8103_usb3_retry = false; _atcphy_dwc3_reset_assert(atcphy); atcphy_usb2_power_off(atcphy); @@ -4025,6 +4210,12 @@ static int atcphy_dwc3_reset_deassert(struct reset_controller_dev *rcdev, unsign guard(mutex)(&atcphy->lock); atcphy_restore_after_pd_off(atcphy); + if (atcphy->t8103_dummy_pending) { + int ret = atcphy_park_live_t8103_pipehandler(atcphy); + + if (ret) + return ret; + } clear32(atcphy->regs.pipehandler + PIPEHANDLER_AON_GEN, PIPEHANDLER_AON_GEN_DWC3_FORCE_CLAMP_EN); @@ -4467,7 +4658,8 @@ static enum atcphy_mode atcphy_typec_target_mode(struct apple_atcphy *atcphy, */ static bool atcphy_mux_in_mode(const struct apple_atcphy *atcphy, enum atcphy_mode target_mode) { - if (atcphy->mode != target_mode || atcphy->mode_dirty) + if (atcphy->mode != target_mode || atcphy->mode_dirty || + atcphy->t8103_dummy_pending || atcphy->t8103_usb3_retry) return false; return !(atcphy->fixed_usb2 && atcphy->host_active && @@ -4528,8 +4720,20 @@ static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode targe int ret; lockdep_assert_held(&atcphy->lock); + if (atcphy->t8103_dummy_pending) { + ret = atcphy_park_live_t8103_pipehandler(atcphy); + if (ret) + return ret; + } + if (atcphy->mode == target_mode && !atcphy->mode_dirty) { atcphy->typec_mode = target_mode; + /* A canceled lane change owes the old USB3 backend its reconnect. */ + if (atcphy->t8103_usb3_retry) { + if (atcphy_modes[target_mode].pipehandler_state == ATCPHY_PIPEHANDLER_STATE_USB3) + return atcphy_configure_pipehandler(atcphy, false); + atcphy->t8103_usb3_retry = false; + } /* Retry a failed PIPE setup without disturbing the configured lanes. */ if (atcphy->fixed_usb2 && atcphy->host_active && (atcphy->pipe_state != atcphy_modes[target_mode].pipehandler_state || @@ -4578,6 +4782,8 @@ static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode targe if (atcphy->host_active && atcphy->pipe_state != pipe_state) ret = atcphy_configure_pipehandler(atcphy, true); + if (!ret && pipe_state != ATCPHY_PIPEHANDLER_STATE_USB3) + atcphy->t8103_usb3_retry = false; return ret; } @@ -4594,8 +4800,28 @@ static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode targe * complain loudly. We can still try to switch modes and hope for the best though, * in the worst case the hardware will fall back to USB2-only. */ - WARN_ON_ONCE(atcphy->pipe_state != ATCPHY_PIPEHANDLER_STATE_DUMMY); - return atcphy_configure(atcphy, target_mode); + if (atcphy->t8103_usb3_workaround) { + if (atcphy->pipe_state == ATCPHY_PIPEHANDLER_STATE_USB3 && + atcphy_modes[target_mode].pipehandler_state == ATCPHY_PIPEHANDLER_STATE_DUMMY) { + ret = atcphy_park_live_t8103_pipehandler(atcphy); + if (ret) + return ret; + } + WARN_ON_ONCE(atcphy->pipe_state != ATCPHY_PIPEHANDLER_STATE_DUMMY && + atcphy_modes[target_mode].pipehandler_state == + ATCPHY_PIPEHANDLER_STATE_DUMMY); + } else { + WARN_ON_ONCE(atcphy->pipe_state != ATCPHY_PIPEHANDLER_STATE_DUMMY); + } + ret = atcphy_configure(atcphy, target_mode); + if (ret) + return ret; + if (atcphy->t8103_usb3_retry) { + if (atcphy_modes[target_mode].pipehandler_state == ATCPHY_PIPEHANDLER_STATE_USB3) + return atcphy_configure_pipehandler(atcphy, false); + atcphy->t8103_usb3_retry = false; + } + return 0; } /* @@ -5137,6 +5363,14 @@ static void atcphy_probe_pd_notifier(struct apple_atcphy *atcphy) ret); } +/* The T8103 PHY compatible is also a fallback on unqualified M1/M2 variants. */ +static bool atcphy_has_t8103_usb3_workaround(const struct atcphy_hw *hw, + const struct device_node *root) +{ + return hw->gen == ATCPHY_GENERATION_T8103 && + of_device_is_compatible(root, "apple,t8103"); +} + static int atcphy_probe(struct platform_device *pdev) { struct apple_atcphy *atcphy; @@ -5150,6 +5384,7 @@ static int atcphy_probe(struct platform_device *pdev) atcphy->hw = of_device_get_match_data(&pdev->dev); if (!atcphy->hw) return -EINVAL; + atcphy->t8103_usb3_workaround = atcphy_has_t8103_usb3_workaround(atcphy->hw, of_root); atcphy->dev = dev; atcphy->np = dev->of_node; diff --git a/drivers/pmdomain/apple/Kconfig b/drivers/pmdomain/apple/Kconfig index b2f9b5113782f4..5f0a9d95c196c2 100644 --- a/drivers/pmdomain/apple/Kconfig +++ b/drivers/pmdomain/apple/Kconfig @@ -14,6 +14,17 @@ config APPLE_PMGR_PWRSTATE controls for SoC devices. This driver manages them through the generic power domain framework, and also provides reset support. +config APPLE_PMGR_PWRSTATE_KUNIT_TEST + bool "KUnit tests for the Apple PMGR power state driver" if !KUNIT_ALL_TESTS + depends on APPLE_PMGR_PWRSTATE && KUNIT=y + default KUNIT_ALL_TESTS + help + Check that a domain marked apple,no-auto-pm never gets automatic + power management when it is powered on or when a failed power-off + is undone, and that other domains still do. The tests run the + driver's power callbacks against an emulated power state register + and need no Apple hardware. + config APPLE_PMP_REPORT bool "Apple PMP report control" depends on OF @@ -26,7 +37,8 @@ config APPLE_PMP_REPORT report region it shares with the system, and the PMP's report of its own state. - On T8122 (M3) and T6031 (M3 Max) Macs whose boot loader hands the + On T8122 (M3), T6031 (M3 Max), and opted-in T6030 (M3 Pro) Macs + whose boot loader hands the internal display over (see APPLE_T6030_DISPLAY_GATE), iBoot leaves the PMP halted, and this driver starts it when the display driver first asks for it. Once its nodes are enabled the PMP may run until diff --git a/drivers/pmdomain/apple/pmgr-pwrstate-test.c b/drivers/pmdomain/apple/pmgr-pwrstate-test.c new file mode 100644 index 00000000000000..64eceb75ede6b3 --- /dev/null +++ b/drivers/pmdomain/apple/pmgr-pwrstate-test.c @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by pmgr-pwrstate.c: apple,no-auto-pm on the power-on and + * power-off paths. The power state register is emulated: its actual state + * follows the target written, unless the test holds it where it is. + */ +#include +#include + +struct pmgr_ps_test_reg { + u32 val; + bool stuck; /* the actual state no longer follows the target */ + unsigned int auto_writes; /* writes that enabled automatic PM */ +}; + +static int pmgr_ps_test_read(void *ctx, unsigned int reg, unsigned int *val) +{ + struct pmgr_ps_test_reg *r = ctx; + + *val = r->val; + return 0; +} + +static int pmgr_ps_test_write(void *ctx, unsigned int reg, unsigned int val) +{ + struct pmgr_ps_test_reg *r = ctx; + u32 actual = r->stuck ? FIELD_GET(APPLE_PMGR_PS_ACTUAL, r->val) : + FIELD_GET(APPLE_PMGR_PS_TARGET, val); + + if (val & APPLE_PMGR_AUTO_ENABLE) + r->auto_writes++; + r->val = (val & ~APPLE_PMGR_PS_ACTUAL) | FIELD_PREP(APPLE_PMGR_PS_ACTUAL, actual); + return 0; +} + +static const struct regmap_config pmgr_ps_test_regmap = { + .reg_bits = 32, + .val_bits = 32, + .reg_stride = 4, + .reg_read = pmgr_ps_test_read, + .reg_write = pmgr_ps_test_write, + .fast_io = true, +}; + +/* A domain in power state @pstate, actual and target, on a device of its own */ +static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, + bool no_auto_pm, struct pmgr_ps_test_reg **reg) +{ + static const char *const names[] = { "apple-pmgr-ps-auto", "apple-pmgr-ps-no-auto" }; + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + struct device *dev; + + r = kunit_kzalloc(test, sizeof(*r), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, r); + r->val = FIELD_PREP(APPLE_PMGR_PS_TARGET, pstate) | + FIELD_PREP(APPLE_PMGR_PS_ACTUAL, pstate); + dev = kunit_device_register(test, names[no_auto_pm]); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + ps = kunit_kzalloc(test, sizeof(*ps), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ps); + ps->dev = dev; + ps->genpd.name = "test"; + ps->no_auto_pm = no_auto_pm; + ps->regmap = devm_regmap_init(dev, NULL, r, &pmgr_ps_test_regmap); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ps->regmap); + *reg = r; + return ps; +} + +/* Powering on enables automatic PM, unless the domain is apple,no-auto-pm. */ +static void pmgr_ps_power_on_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + bool no_auto_pm; + + for (no_auto_pm = false; ; no_auto_pm = true) { + ps = pmgr_ps_test_domain(test, APPLE_PMGR_PS_PWRGATE, no_auto_pm, &r); + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_power_on(&ps->genpd), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), + APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_ACTUAL, r->val), + APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_EQ_MSG(test, !!(r->val & APPLE_PMGR_AUTO_ENABLE), !no_auto_pm, + "no_auto_pm %d", no_auto_pm); + KUNIT_EXPECT_EQ_MSG(test, r->auto_writes, no_auto_pm ? 0U : 1U, + "no_auto_pm %d", no_auto_pm); + if (no_auto_pm) + break; + } +} + +/* + * A power-off that does not complete is undone: the domain is requested on + * again, with automatic PM only when the domain allows it. + */ +static void pmgr_ps_power_off_undo_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + bool no_auto_pm; + + for (no_auto_pm = false; ; no_auto_pm = true) { + ps = pmgr_ps_test_domain(test, APPLE_PMGR_PS_ACTIVE, no_auto_pm, &r); + r->stuck = true; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_power_off(&ps->genpd), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), + APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_EQ_MSG(test, !!(r->val & APPLE_PMGR_AUTO_ENABLE), !no_auto_pm, + "no_auto_pm %d", no_auto_pm); + KUNIT_EXPECT_EQ_MSG(test, r->auto_writes, no_auto_pm ? 0U : 1U, + "no_auto_pm %d", no_auto_pm); + if (no_auto_pm) + break; + } +} + +/* A power-on that does not complete never enabled automatic PM on such a domain. */ +static void pmgr_ps_power_on_fails_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + + ps = pmgr_ps_test_domain(test, APPLE_PMGR_PS_PWRGATE, true, &r); + r->stuck = true; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_power_on(&ps->genpd), -ETIMEDOUT); + /* Undone: requested off again */ + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_PWRGATE); + KUNIT_EXPECT_EQ(test, r->auto_writes, 0U); +} + +static struct kunit_case pmgr_ps_test_cases[] = { + KUNIT_CASE(pmgr_ps_power_on_test), + KUNIT_CASE(pmgr_ps_power_off_undo_test), + KUNIT_CASE(pmgr_ps_power_on_fails_test), + {} +}; + +static struct kunit_suite pmgr_ps_test_suite = { + .name = "apple-pmgr-pwrstate", + .test_cases = pmgr_ps_test_cases, +}; + +kunit_test_suite(pmgr_ps_test_suite); diff --git a/drivers/pmdomain/apple/pmgr-pwrstate.c b/drivers/pmdomain/apple/pmgr-pwrstate.c index d0b75e0b4b6711..808f45a2b66067 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate.c @@ -50,6 +50,8 @@ struct apple_pmgr_ps { bool externally_clocked; bool system_sleep; bool firmware_owned; + /* Never enable automatic power management (apple,no-auto-pm). */ + bool no_auto_pm; }; #define genpd_to_apple_pmgr_ps(_genpd) container_of(_genpd, struct apple_pmgr_ps, genpd) @@ -167,7 +169,7 @@ static int apple_pmgr_ps_power_on(struct generic_pm_domain *genpd) if (ps->firmware_owned) return 0; - ret = apple_pmgr_ps_set(genpd, APPLE_PMGR_PS_ACTIVE, true); + ret = apple_pmgr_ps_set(genpd, APPLE_PMGR_PS_ACTIVE, !ps->no_auto_pm); if (ret && !ps->system_sleep) apple_pmgr_ps_set(genpd, APPLE_PMGR_PS_PWRGATE, false); @@ -176,14 +178,15 @@ static int apple_pmgr_ps_power_on(struct generic_pm_domain *genpd) static int apple_pmgr_ps_power_off(struct generic_pm_domain *genpd) { + struct apple_pmgr_ps *ps = genpd_to_apple_pmgr_ps(genpd); int ret; - if (genpd_to_apple_pmgr_ps(genpd)->firmware_owned) + if (ps->firmware_owned) return 0; ret = apple_pmgr_ps_set(genpd, APPLE_PMGR_PS_PWRGATE, false); if (ret) - apple_pmgr_ps_set(genpd, APPLE_PMGR_PS_ACTIVE, true); + apple_pmgr_ps_set(genpd, APPLE_PMGR_PS_ACTIVE, !ps->no_auto_pm); return ret; } @@ -360,6 +363,12 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) if (of_property_read_bool(node, "apple,externally-clocked")) ps->externally_clocked = true; + /* + * A coprocessor CPU domain whose firmware Linux starts cold must not be + * gated automatically behind its back: keep it at the requested state. + */ + ps->no_auto_pm = of_property_read_bool(node, "apple,no-auto-pm"); + active = apple_pmgr_ps_is_active(ps); if (ps->firmware_owned) { /* Consumers (the boot framebuffer) need it; never try to turn it on. */ @@ -383,16 +392,16 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) * even if it does not get there in time. */ active = apple_pmgr_ps_set(&ps->genpd, APPLE_PMGR_PS_ACTIVE, - true) == 0; + !ps->no_auto_pm) == 0; } } else if (active) { ps->genpd.flags |= GENPD_FLAG_DEFER_OFF | GENPD_FLAG_ACTIVE_WAKEUP; } - /* Turn on auto-PM if the domain is already on */ + /* Turn on auto-PM if the domain is already on, unless it must stay off */ if (active && !ps->firmware_owned) regmap_update_bits(regmap, ps->offset, APPLE_PMGR_FLAGS | APPLE_PMGR_AUTO_ENABLE, - APPLE_PMGR_AUTO_ENABLE); + ps->no_auto_pm ? 0 : APPLE_PMGR_AUTO_ENABLE); ret = pm_genpd_init(&ps->genpd, NULL, !active); if (ret < 0) { @@ -475,3 +484,7 @@ MODULE_AUTHOR("Hector Martin "); MODULE_DESCRIPTION("PMGR power state driver for Apple SoCs"); module_platform_driver(apple_pmgr_ps_driver); + +#if IS_ENABLED(CONFIG_APPLE_PMGR_PWRSTATE_KUNIT_TEST) +#include "pmgr-pwrstate-test.c" +#endif diff --git a/drivers/pmdomain/apple/pmp-report-start-test.c b/drivers/pmdomain/apple/pmp-report-start-test.c index aeb9e28f53b9e0..36cf2c87eb128a 100644 --- a/drivers/pmdomain/apple/pmp-report-start-test.c +++ b/drivers/pmdomain/apple/pmp-report-start-test.c @@ -343,7 +343,50 @@ static void pmp_start_entry_teardown_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_pmp_report_entry_power_on(&ent->genpd), -ENODEV); } +/* T6030's real overlay: DISP (7), deferred external requests (8/9), + * and storage (16), which has no acknowledgement. Only DISP gates startup. + */ +static struct pst *pst_t6030(struct kunit *test) +{ + struct pst *t = pst_new(test); + + t->st.seed = BIT_ULL(7) | BIT_ULL(8) | BIT_ULL(9) | BIT_ULL(16); + t->st.ack = BIT_ULL(7) | BIT_ULL(8) | BIT_ULL(9); + t->st.startup_ack = BIT_ULL(7); + t->pmp.ack = BIT_ULL(7); + pst_write(t, pst_offsets.tgt_read, t->st.seed); + return t; +} + +static void pmp_start_t6030_deferred_external_test(struct kunit *test) +{ + struct pst *t = pst_t6030(test); + + KUNIT_ASSERT_EQ(test, pst_wait(t, 7, 5000), 0); + KUNIT_EXPECT_EQ(test, t->pmp.enables, 1U); + KUNIT_EXPECT_EQ(test, pst_wait(t, 8, 1), -EIO); + KUNIT_EXPECT_EQ(test, pst_wait(t, 9, 1), -EIO); + KUNIT_EXPECT_EQ(test, pst_wait(t, 16, 1), -EINVAL); + pst_write(t, pst_offsets.actual, BIT_ULL(7) | BIT_ULL(8)); + KUNIT_EXPECT_EQ(test, pst_wait(t, 8, 1), 0); + KUNIT_EXPECT_EQ(test, t->pmp.enables, 1U); + pst_drain(t); +} + +/* An external consumer must not bypass the internal startup admission. */ +static void pmp_start_t6030_external_first_test(struct kunit *test) +{ + struct pst *t = pst_t6030(test); + + t->pmp.ack = BIT_ULL(8); + KUNIT_EXPECT_EQ(test, pst_wait(t, 8, 5000), -EIO); + KUNIT_EXPECT_EQ(test, pst_wait(t, 7, 1), -EIO); + pst_drain(t); +} + static struct kunit_case pmp_start_cases[] = { + KUNIT_CASE(pmp_start_t6030_deferred_external_test), + KUNIT_CASE(pmp_start_t6030_external_first_test), KUNIT_CASE(pmp_start_ok_test), KUNIT_CASE(pmp_start_check_fails_test), KUNIT_CASE(pmp_start_busy_ptd_test), diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index beedc4d96eb7f9..b07bb9081d6c57 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -79,6 +79,8 @@ struct apple_pmp_report { struct apple_pmp_start *start; }; +static const struct apple_pmp_report_offsets apple_pmp_offsets_t6030; + /* Bound report regions, protected by RCU until managed teardown drains readers. */ static LIST_HEAD(apple_pmp_reports); static DEFINE_MUTEX(apple_pmp_reports_lock); @@ -175,6 +177,61 @@ static void apple_pmp_report_release(void *data) debugfs_remove(rep->debugfs); } +/* The unique, enabled and acknowledged T6030 display request (DISP, reg 7). */ +static struct device_node *apple_pmp_report_t6030_entry(struct device_node *report) +{ + struct device_node *child, *entry = NULL; + u32 reg; + + for_each_child_of_node(report, child) { + if (of_property_read_u32(child, "reg", ®) || reg != 7) + continue; + if (entry || of_property_count_u32_elems(child, "reg") != 1 || + !of_device_is_available(child) || + !of_device_is_compatible(child, "apple,t6000-pmp-v2-report-entry") || + of_property_read_bool(child, "apple,no-ack")) { + of_node_put(child); + of_node_put(entry); + return NULL; + } + entry = of_node_get(child); + } + return entry; +} + +/* The existing display domain seeds DISP; require its READY and ACK before AGX. */ +static int apple_pmp_report_wait_t6030_14(struct device *supplier, unsigned int timeout_ms) +{ + struct device_node *np, *report = NULL, *pmp, *entry; + int ret; + + if (!IS_ENABLED(CONFIG_APPLE_T6030_GPU_PMP_LINK) || + !of_machine_is_compatible("apple,t6030") || + !of_device_is_compatible(supplier->of_node, "apple,t6030-pmp-v2")) + return -ENODEV; + for_each_compatible_node(np, NULL, "apple,t6030-pmp-v2-report") { + if (report) { + of_node_put(np); + of_node_put(report); + return -ENODEV; + } + report = of_node_get(np); + } + if (!report || !of_device_is_available(report) || + of_property_count_u32_elems(report, "apple,pmp") != 1) { + of_node_put(report); + return -ENODEV; + } + pmp = of_parse_phandle(report, "apple,pmp", 0); + entry = apple_pmp_report_t6030_entry(report); + ret = pmp == supplier->of_node && entry ? + apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)) : -ENODEV; + of_node_put(entry); + of_node_put(pmp); + of_node_put(report); + return ret; +} + /* The native 25G83 PMP starts through its supplier topology, after requests * are seeded. Its report is pinned against removal while readiness is read. */ @@ -186,6 +243,9 @@ int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int t u64 status; int ret; + /* A declared report always takes the existing native25 path below. */ + if (!np && !of_property_present(supplier->of_node, "apple,pmp-report")) + return apple_pmp_report_wait_t6030_14(supplier, timeout_ms); if (!np || !of_device_is_compatible(np, "apple,j613-25g83-pmp-report")) { of_node_put(np); return -ENODEV; @@ -212,7 +272,7 @@ int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int t EXPORT_SYMBOL_GPL(apple_pmp_report_wait_supplier_ready); /* - * Starting a halted PMP (T8122, T6031) + * Starting a halted PMP (T8122, T6031, opted-in T6030) * * On these SoCs iBoot leaves the PMP loaded but halted, and the DCP firmware * of the 14.x system needs it running. A display gate that admits the boot @@ -1064,6 +1124,12 @@ static const struct apple_pmp_report_offsets apple_pmp_offsets_t6030 = { .tgt_write = 0x108c0, .actual = 0x11c0, .status = 0x10, + /* Native G15 explicitly opts into the gate's halted-PMP handoff. */ + .starts_pmp = IS_ENABLED(CONFIG_APPLE_T6030_GPU_PMP_LINK), + .name = "T6030", + .fallback = "apple_t6030_display.enable=0", + .pwrstate = "apple,t6030-pmgr-pwrstate", + .devices_ordered = true, }; static const struct apple_pmp_report_offsets apple_pmp_offsets_t8112 = { diff --git a/drivers/pmdomain/imx/imx8m-blk-ctrl.c b/drivers/pmdomain/imx/imx8m-blk-ctrl.c index 99d100e1d923f5..62c4f829605c64 100644 --- a/drivers/pmdomain/imx/imx8m-blk-ctrl.c +++ b/drivers/pmdomain/imx/imx8m-blk-ctrl.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -34,6 +35,12 @@ struct imx8m_blk_ctrl { struct regmap *regmap; struct imx8m_blk_ctrl_domain *domains; struct genpd_onecell_data onecell_data; + /* + * Serializes the blk-ctrl reset/clock sequence across sibling domains; + * their transitions interact through the shared VPUMIX bus domain, + * VPU_NOC and the not-ack-verified ADB400 handshake (ERR050531). + */ + struct mutex power_lock; }; struct imx8m_blk_ctrl_domain_data { @@ -98,6 +105,8 @@ static int imx8m_blk_ctrl_power_on(struct generic_pm_domain *genpd) struct imx8m_blk_ctrl *bc = domain->bc; int ret; + guard(mutex)(&bc->power_lock); + /* make sure bus domain is awake */ ret = pm_runtime_get_sync(bc->bus_power_dev); if (ret < 0) { @@ -164,6 +173,8 @@ static int imx8m_blk_ctrl_power_off(struct generic_pm_domain *genpd) const struct imx8m_blk_ctrl_domain_data *data = domain->data; struct imx8m_blk_ctrl *bc = domain->bc; + guard(mutex)(&bc->power_lock); + /* put devices into reset and disable clocks */ if (data->mipi_phy_rst_mask) regmap_clear_bits(bc->regmap, BLK_MIPI_RESET_DIV, data->mipi_phy_rst_mask); @@ -202,6 +213,10 @@ static int imx8m_blk_ctrl_probe(struct platform_device *pdev) bc->dev = dev; + ret = devm_mutex_init(dev, &bc->power_lock); + if (ret) + return ret; + bc_data = of_device_get_match_data(dev); base = devm_platform_ioremap_resource(pdev, 0); diff --git a/drivers/pmdomain/rockchip/pm-domains.c b/drivers/pmdomain/rockchip/pm-domains.c index 490bbb1d1d8e8f..b57581b367a90b 100644 --- a/drivers/pmdomain/rockchip/pm-domains.c +++ b/drivers/pmdomain/rockchip/pm-domains.c @@ -745,7 +745,19 @@ static int rockchip_pd_attach_dev(struct generic_pm_domain *genpd, } i = 0; - while ((clk = of_clk_get(dev->of_node, i++)) && !IS_ERR(clk)) { + while (1) { + clk = of_clk_get(dev->of_node, i++); + if (IS_ERR(clk)) { + error = PTR_ERR(clk); + if (error == -ENOENT) + break; + + dev_err(dev, "failed to get clock %d: %d\n", i - 1, + error); + pm_clk_destroy(dev); + return error; + } + dev_dbg(dev, "adding clock '%pC' to list of PM clocks\n", clk); error = pm_clk_add_clk(dev, clk); if (error) { @@ -828,7 +840,7 @@ static int rockchip_pm_add_one_domain(struct rockchip_pmu *pmu, dev_err(pmu->dev, "%pOFn: failed to get clk at index %d: %d\n", node, i, error); - return error; + goto err_put_clocks; } } @@ -1004,7 +1016,9 @@ static int rockchip_pm_add_subdomain(struct rockchip_pmu *pmu, parent_domain->name, child_domain->name); } - rockchip_pm_add_subdomain(pmu, np); + error = rockchip_pm_add_subdomain(pmu, np); + if (error) + return error; } return 0; diff --git a/drivers/power/sequencing/pwrseq-pcie-m2.c b/drivers/power/sequencing/pwrseq-pcie-m2.c index ddfe6ca824945e..c59c487c43e306 100644 --- a/drivers/power/sequencing/pwrseq-pcie-m2.c +++ b/drivers/power/sequencing/pwrseq-pcie-m2.c @@ -562,6 +562,7 @@ static int pwrseq_pcie_m2_probe(struct platform_device *pdev) mutex_destroy(&ctx->list_lock); err_free_regulators: regulator_bulk_free(ctx->num_vregs, ctx->regs); + kfree(ctx->regs); return ret; } @@ -575,6 +576,7 @@ static void pwrseq_pcie_m2_remove(struct platform_device *pdev) mutex_destroy(&ctx->list_lock); regulator_bulk_free(ctx->num_vregs, ctx->regs); + kfree(ctx->regs); } static const struct of_device_id pwrseq_pcie_m2_of_match[] = { diff --git a/drivers/power/supply/Kconfig b/drivers/power/supply/Kconfig index c535296dd5e804..ae3121a55ec553 100644 --- a/drivers/power/supply/Kconfig +++ b/drivers/power/supply/Kconfig @@ -1189,11 +1189,14 @@ config MACSMC_POWER config MACSMC_POWER_KUNIT_TEST bool "KUnit tests for Apple SMC battery replies" if !KUNIT_ALL_TESTS depends on MACSMC_POWER && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST default KUNIT_ALL_TESTS help - Build tests for malformed fixed-width battery replies. The tests - exercise zero-length and short CHTE replies and check that the - charge-behaviour reader rejects them. Static stubs replace SMC - reads, so the tests need no Apple hardware. + Build tests for malformed fixed-width battery replies and for the + charge settings. The tests exercise zero-length and short CHTE + replies, the charge thresholds and behaviours against a model of + their SMC keys, failures of each key access, and two concurrent + writers. Static stubs replace SMC reads and writes, so the tests + need no Apple hardware. endif # POWER_SUPPLY diff --git a/drivers/power/supply/macsmc-power-test.c b/drivers/power/supply/macsmc-power-test.c index 78f7f1b877beb4..3ddb58970771c6 100644 --- a/drivers/power/supply/macsmc-power-test.c +++ b/drivers/power/supply/macsmc-power-test.c @@ -1,6 +1,13 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -/* Included by macsmc-power.c; the charge-behaviour reader is stubbed. */ +/* + * Included by macsmc-power.c. The first suite stubs the CHTE reader; the + * charge suite replaces apple_smc_read() and apple_smc_write() with a model + * of the charge keys that can fail any one access. + */ #include +#include +#include +#include struct macsmc_power_test_context { struct macsmc_power power; @@ -24,6 +31,7 @@ static int macsmc_power_test_init(struct kunit *test) ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; + mutex_init(&ctx->power.charge_lock); ctx->power.has_chte = true; test->priv = ctx; kunit_activate_static_stub(test, macsmc_power_read_chte, @@ -55,4 +63,625 @@ static struct kunit_suite macsmc_power_test_suite = { .test_cases = macsmc_power_test_cases, }; -kunit_test_suite(macsmc_power_test_suite); +/* Charge settings against a model of the SMC's charge keys. */ + +#define CHARGE_TEST_MAX_OPS 32 + +struct macsmc_charge_op { + smc_key key; + bool write; + u32 value; +}; + +struct charge_test_writer; + +struct macsmc_charge_test { + struct kunit *test; + struct apple_smc smc; + struct macsmc_power power; + struct power_supply psy; + + /* The keys' values */ + u16 chls; + u8 ch0i; + u8 ch0c; + u32 chte; + + /* Fail the access to fail_key (a write if fail_write) with fail_err */ + smc_key fail_key; + bool fail_write; + int fail_err; + + /* Every access, in order */ + struct macsmc_charge_op ops[CHARGE_TEST_MAX_OPS]; + unsigned int nops; + + /* Charge-key accesses must hold charge_lock (set by the tests) */ + bool expect_locked; + + /* Runs once from within the next CHLS read, after the value is taken */ + void (*on_chls_read)(struct macsmc_charge_test *t); + + /* The concurrent writer of the serialization test */ + struct charge_test_writer *writer; + bool writer_early; + /* The test's own task; the writer records its findings for it to report */ + struct task_struct *task; + atomic_t writer_unlocked; +}; + +static bool charge_test_key_is_charge_setting(smc_key key) +{ + return key == SMC_KEY(CHLS) || key == SMC_KEY(CH0I) || + key == SMC_KEY(CH0C) || key == SMC_KEY(CHTE); +} + +static void charge_test_log(struct macsmc_charge_test *t, smc_key key, bool write, + u32 value) +{ + bool unlocked = t->expect_locked && charge_test_key_is_charge_setting(key) && + !mutex_is_locked(&t->power.charge_lock); + + /* KUnit reports only from the test's task; the writer leaves it a count. */ + if (current != t->task) { + if (unlocked) + atomic_inc(&t->writer_unlocked); + return; + } + KUNIT_EXPECT_FALSE_MSG(t->test, unlocked, "charge key %08x accessed without charge_lock", + key); + if (t->nops >= CHARGE_TEST_MAX_OPS) { + KUNIT_FAIL(t->test, "more than %d charge key accesses", CHARGE_TEST_MAX_OPS); + return; + } + t->ops[t->nops++] = (struct macsmc_charge_op){ key, write, value }; +} + +static int charge_test_read(struct apple_smc *smc, smc_key key, void *buf, size_t size) +{ + struct macsmc_charge_test *t = container_of(smc, struct macsmc_charge_test, smc); + void (*hook)(struct macsmc_charge_test *t) = NULL; + u32 value; + + if (key == SMC_KEY(CHLS) && size == sizeof(u16)) { + value = t->chls; + hook = t->on_chls_read; + t->on_chls_read = NULL; + } else if (key == SMC_KEY(CH0I) && size == sizeof(u8)) { + value = t->ch0i; + } else if (key == SMC_KEY(CH0C) && size == sizeof(u8)) { + value = t->ch0c; + } else if (key == SMC_KEY(CHTE) && size == sizeof(u32)) { + value = t->chte; + } else { + KUNIT_FAIL(t->test, "unexpected read of %08x, %zu bytes", key, size); + return -EINVAL; + } + + charge_test_log(t, key, false, value); + if (t->fail_key == key && !t->fail_write) + return t->fail_err; + /* Little-endian, like the SMC's own replies */ + memcpy(buf, &value, size); + /* Another writer gets its turn after this read has taken the value */ + if (hook) + hook(t); + return size; +} + +static int charge_test_write(struct apple_smc *smc, smc_key key, const void *buf, + size_t size) +{ + struct macsmc_charge_test *t = container_of(smc, struct macsmc_charge_test, smc); + u32 value = 0; + + memcpy(&value, buf, min(size, sizeof(value))); + charge_test_log(t, key, true, value); + if (t->fail_key == key && t->fail_write) + return t->fail_err; + + if (key == SMC_KEY(CHLS) && size == sizeof(u16)) + t->chls = value; + else if (key == SMC_KEY(CH0I) && size == sizeof(u8)) + t->ch0i = value; + else if (key == SMC_KEY(CH0C) && size == sizeof(u8)) + t->ch0c = value; + else if (key == SMC_KEY(CHTE) && size == sizeof(u32)) + t->chte = value; + else + KUNIT_FAIL(t->test, "unexpected write of %08x, %zu bytes", key, size); + /* An SMC write reply may echo the request length; it is not an error. */ + return size; +} + +static int macsmc_charge_test_init(struct kunit *test) +{ + struct macsmc_charge_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + if (!t) + return -ENOMEM; + t->test = test; + t->task = current; + atomic_set(&t->writer_unlocked, 0); + t->power.smc = &t->smc; + mutex_init(&t->power.charge_lock); + t->psy.drv_data = &t->power; + t->expect_locked = true; + test->priv = t; + kunit_activate_static_stub(test, apple_smc_read, charge_test_read); + kunit_activate_static_stub(test, apple_smc_write, charge_test_write); + return 0; +} + +static int charge_test_set(struct macsmc_charge_test *t, enum power_supply_property psp, + int value) +{ + union power_supply_propval val = { .intval = value }; + + return macsmc_battery_set_property(&t->psy, psp, &val); +} + +static int charge_test_get(struct macsmc_charge_test *t, enum power_supply_property psp, + int *value) +{ + union power_supply_propval val = {}; + int ret = macsmc_battery_get_property(&t->psy, psp, &val); + + *value = val.intval; + return ret; +} + +static unsigned int charge_test_writes(struct macsmc_charge_test *t) +{ + unsigned int i, n = 0; + + for (i = 0; i < t->nops; i++) + n += t->ops[i].write; + return n; +} + +static void charge_test_expect_op(struct kunit *test, struct macsmc_charge_test *t, + unsigned int i, smc_key key, bool write, u32 value) +{ + if (i >= t->nops) { + KUNIT_FAIL(test, "access %u missing, only %u", i, t->nops); + return; + } + KUNIT_EXPECT_EQ_MSG(test, t->ops[i].key, key, "access %u", i); + KUNIT_EXPECT_EQ_MSG(test, t->ops[i].write, write, "access %u", i); + if (write) + KUNIT_EXPECT_EQ_MSG(test, t->ops[i].value, value, "access %u", i); +} + +/* The behaviours a battery offers follow from its keys alone. */ +static void macsmc_charge_behaviours_test(struct kunit *test) +{ + struct macsmc_charge_test *t = test->priv; + struct macsmc_power *p = &t->power; + unsigned int combo; + + for (combo = 0; combo < 32; combo++) { + unsigned int got; + + p->has_ch0i = combo & BIT(0); + p->has_ch0c = combo & BIT(1); + p->has_chte = combo & BIT(2); + p->has_chls = combo & BIT(3); + p->has_chwa = combo & BIT(4); + got = macsmc_battery_charge_behaviours(p); + + KUNIT_EXPECT_EQ_MSG(test, !!(got & BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO)), + p->has_ch0i || p->has_ch0c || p->has_chte || p->has_chls, + "combo %u", combo); + KUNIT_EXPECT_EQ_MSG(test, + !!(got & BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_FORCE_DISCHARGE)), + p->has_ch0i, "combo %u", combo); + KUNIT_EXPECT_EQ_MSG(test, + !!(got & BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE)), + p->has_chte || p->has_ch0c, "combo %u", combo); + KUNIT_EXPECT_EQ_MSG(test, + !!(got & BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE)), + p->has_chls, "combo %u", combo); + KUNIT_EXPECT_EQ_MSG(test, + got & BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE_AWAKE), + 0U, "combo %u", combo); + } + + /* CHWA alone offers no behaviour, as before; CHLS alone offers both autos */ + p->has_ch0i = false; + p->has_ch0c = false; + p->has_chte = false; + p->has_chls = false; + p->has_chwa = true; + KUNIT_EXPECT_EQ(test, macsmc_battery_charge_behaviours(p), 0U); + p->has_chwa = false; + p->has_chls = true; + KUNIT_EXPECT_EQ(test, macsmc_battery_charge_behaviours(p), + (unsigned int)(BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO) | + BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE))); + KUNIT_EXPECT_EQ(test, t->nops, 0U); +} + +/* The end threshold keeps the force-discharge bit only while there is a limit. */ +static void macsmc_charge_end_threshold_test(struct kunit *test) +{ + static const struct { + u16 before; + int threshold; + u16 after; + } cases[] = { + { 0x0000, 80, 0x0050 }, + { 0x0150, 70, 0x0146 }, /* auto-discharge stays */ + { 0x0150, 99, 0x0163 }, + { 0x0000, 5, 0x000a }, /* below the minimum: the minimum */ + { 0x0150, 0, 0x010a }, + { 0x0000, -1, 0x000a }, + { 0x0350, 60, 0x013c }, /* other high bits are not kept */ + { 0x0150, 100, 0x0000 }, /* no limit ends auto-discharge */ + { 0x0050, 100, 0x0000 }, + { 0x0150, 150, 0x0000 }, + }; + struct macsmc_charge_test *t = test->priv; + unsigned int i; + + t->power.has_chls = true; + for (i = 0; i < ARRAY_SIZE(cases); i++) { + int ret; + + t->chls = cases[i].before; + t->nops = 0; + ret = charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD, + cases[i].threshold); + KUNIT_EXPECT_EQ_MSG(test, ret, 0, "case %u", i); + KUNIT_EXPECT_EQ_MSG(test, t->chls, cases[i].after, "case %u", i); + KUNIT_EXPECT_EQ_MSG(test, t->nops, 2U, "case %u", i); + charge_test_expect_op(test, t, 0, SMC_KEY(CHLS), false, 0); + charge_test_expect_op(test, t, 1, SMC_KEY(CHLS), true, cases[i].after); + } +} + +/* A failed CHLS read changes nothing; a failed write is reported. */ +static void macsmc_charge_end_threshold_fault_test(struct kunit *test) +{ + struct macsmc_charge_test *t = test->priv; + + t->power.has_chls = true; + t->chls = 0x0150; + t->fail_key = SMC_KEY(CHLS); + t->fail_err = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD, + 60), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, charge_test_writes(t), 0U); + KUNIT_EXPECT_EQ(test, t->chls, 0x0150); + + t->nops = 0; + t->fail_write = true; + t->fail_err = -EIO; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD, + 60), -EIO); + KUNIT_EXPECT_EQ(test, t->chls, 0x0150); +} + +/* auto-discharge clears the inhibitors, then sets the bit next to the limit. */ +static void macsmc_charge_auto_discharge_test(struct kunit *test) +{ + struct macsmc_charge_test *t = test->priv; + int value; + + t->power.has_ch0i = true; + t->power.has_chte = true; + t->power.has_chls = true; + t->chls = 0x0050; + t->ch0i = 1; + t->chte = 1; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE), 0); + KUNIT_EXPECT_EQ(test, t->nops, 4U); + charge_test_expect_op(test, t, 0, SMC_KEY(CHLS), false, 0); + charge_test_expect_op(test, t, 1, SMC_KEY(CH0I), true, 0); + charge_test_expect_op(test, t, 2, SMC_KEY(CHTE), true, 0); + charge_test_expect_op(test, t, 3, SMC_KEY(CHLS), true, 0x0150); + KUNIT_EXPECT_EQ(test, charge_test_get(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, &value), 0); + KUNIT_EXPECT_EQ(test, value, POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE); + + /* The threshold reads past the bit */ + t->expect_locked = false; + KUNIT_EXPECT_EQ(test, charge_test_get(t, POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD, + &value), 0); + KUNIT_EXPECT_EQ(test, value, 80); + KUNIT_EXPECT_EQ(test, charge_test_get(t, POWER_SUPPLY_PROP_CHARGE_CONTROL_START_THRESHOLD, + &value), 0); + KUNIT_EXPECT_EQ(test, value, 75); + t->expect_locked = true; + + /* auto clears it again and keeps the limit */ + t->nops = 0; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO), 0); + KUNIT_EXPECT_EQ(test, t->chls, 0x0050); + KUNIT_EXPECT_EQ(test, charge_test_get(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, &value), 0); + KUNIT_EXPECT_EQ(test, value, POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO); +} + +/* Without a limit there is nothing to discharge to: refused, nothing written. */ +static void macsmc_charge_auto_discharge_no_limit_test(struct kunit *test) +{ + static const u16 no_limit[] = { 0x0000, 0x0009, 0x0064, 0x00ff, 0x0100 }; + struct macsmc_charge_test *t = test->priv; + unsigned int i; + + t->power.has_ch0i = true; + t->power.has_chte = true; + t->power.has_chls = true; + for (i = 0; i < ARRAY_SIZE(no_limit); i++) { + t->chls = no_limit[i]; + t->ch0i = 1; + t->nops = 0; + KUNIT_EXPECT_EQ_MSG(test, + charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE), + -EINVAL, "chls %04x", no_limit[i]); + KUNIT_EXPECT_EQ_MSG(test, charge_test_writes(t), 0U, "chls %04x", no_limit[i]); + KUNIT_EXPECT_EQ(test, t->ch0i, 1); + KUNIT_EXPECT_EQ(test, t->chls, no_limit[i]); + } + + /* The lowest and highest limits are limits */ + t->chls = 0x000a; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE), 0); + KUNIT_EXPECT_EQ(test, t->chls, 0x010a); + t->chls = 0x0063; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE), 0); + KUNIT_EXPECT_EQ(test, t->chls, 0x0163); + + /* auto is always allowed, and clears a bit left without a limit */ + t->chls = 0x0100; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO), 0); + KUNIT_EXPECT_EQ(test, t->chls, 0x0000); +} + +/* Without CHLS, auto-discharge is not offered and touches no key. */ +static void macsmc_charge_auto_discharge_unsupported_test(struct kunit *test) +{ + struct macsmc_charge_test *t = test->priv; + + t->power.has_ch0i = true; + t->power.has_chte = true; + t->power.has_chwa = true; + t->ch0i = 1; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, t->nops, 0U); + KUNIT_EXPECT_EQ(test, t->ch0i, 1); +} + +/* An unreadable CHLS leaves every inhibitor as it was. */ +static void macsmc_charge_auto_chls_read_fault_test(struct kunit *test) +{ + static const int modes[] = { + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE, + }; + struct macsmc_charge_test *t = test->priv; + unsigned int i; + + t->power.has_ch0i = true; + t->power.has_chte = true; + t->power.has_chls = true; + t->fail_key = SMC_KEY(CHLS); + t->fail_err = -ETIMEDOUT; + for (i = 0; i < ARRAY_SIZE(modes); i++) { + t->chls = 0x0150; + t->ch0i = 1; + t->chte = 1; + t->nops = 0; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + modes[i]), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, charge_test_writes(t), 0U); + KUNIT_EXPECT_EQ(test, t->ch0i, 1); + KUNIT_EXPECT_EQ(test, t->chte, 1U); + KUNIT_EXPECT_EQ(test, t->chls, 0x0150); + } +} + +/* + * A failure partway through is reported and stops there. The keys are + * separate SMC writes, so the ones already written stay written. + */ +static void macsmc_charge_auto_partial_failure_test(struct kunit *test) +{ + struct macsmc_charge_test *t = test->priv; + + t->power.has_ch0i = true; + t->power.has_chte = true; + t->power.has_chls = true; + t->chls = 0x0050; + t->ch0i = 1; + t->chte = 1; + t->fail_key = SMC_KEY(CHTE); + t->fail_write = true; + t->fail_err = -EIO; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE), -EIO); + KUNIT_EXPECT_EQ(test, t->ch0i, 0); + KUNIT_EXPECT_EQ(test, t->chte, 1U); + KUNIT_EXPECT_EQ(test, t->chls, 0x0050); + KUNIT_EXPECT_EQ(test, t->nops, 3U); + + t->nops = 0; + t->fail_key = SMC_KEY(CHLS); + t->chte = 1; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE), -EIO); + KUNIT_EXPECT_EQ(test, t->chte, 0U); + KUNIT_EXPECT_EQ(test, t->chls, 0x0050); +} + +/* Reported behaviour: CH0I, then the inhibitors, then CHLS; failures propagate. */ +static void macsmc_charge_get_precedence_test(struct kunit *test) +{ + struct macsmc_charge_test *t = test->priv; + + t->power.has_ch0i = true; + t->power.has_ch0c = true; + t->power.has_chls = true; + t->chls = 0x0150; + t->ch0i = 1; + t->ch0c = 1; + KUNIT_EXPECT_EQ(test, macsmc_battery_get_charge_behaviour(&t->power), + POWER_SUPPLY_CHARGE_BEHAVIOUR_FORCE_DISCHARGE); + t->ch0i = 0; + KUNIT_EXPECT_EQ(test, macsmc_battery_get_charge_behaviour(&t->power), + POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE); + t->ch0c = 0; + KUNIT_EXPECT_EQ(test, macsmc_battery_get_charge_behaviour(&t->power), + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE); + t->chls = 0x0050; + KUNIT_EXPECT_EQ(test, macsmc_battery_get_charge_behaviour(&t->power), + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO); + /* The bit without a limit, as an earlier kernel could leave it, reads as auto */ + t->nops = 0; + t->chls = 0x0100; + KUNIT_EXPECT_EQ(test, macsmc_battery_get_charge_behaviour(&t->power), + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO); + t->chls = 0x0164; + KUNIT_EXPECT_EQ(test, macsmc_battery_get_charge_behaviour(&t->power), + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO); + t->fail_key = SMC_KEY(CHLS); + t->fail_err = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_battery_get_charge_behaviour(&t->power), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, charge_test_writes(t), 0U); +} + +/* + * Two writers to CHLS at once: the end threshold's read-modify-write and the + * behaviour's. The behaviour's writer starts while the threshold's has read + * CHLS but not yet written it. Serialized, it waits, and both settings + * survive; without the lock its bit would be lost. + */ +struct charge_test_writer { + struct macsmc_charge_test *t; + struct completion done; + int ret; +}; + +static int charge_test_writer_fn(void *data) +{ + struct charge_test_writer *w = data; + + current->kunit_test = w->t->test; + w->ret = charge_test_set(w->t, POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE); + current->kunit_test = NULL; + complete(&w->done); + return 0; +} + +static void charge_test_start_writer(struct macsmc_charge_test *t) +{ + struct charge_test_writer *w = t->writer; + struct task_struct *task; + + task = kthread_run(charge_test_writer_fn, w, "macsmc-charge-test"); + if (IS_ERR(task)) { + KUNIT_FAIL(t->test, "no writer thread: %ld", PTR_ERR(task)); + w->ret = PTR_ERR(task); + complete(&w->done); + return; + } + /* Serialized, the writer cannot finish while this setter runs */ + t->writer_early = wait_for_completion_timeout(&w->done, msecs_to_jiffies(200)); +} + +static void macsmc_charge_serialized_test(struct kunit *test) +{ + struct macsmc_charge_test *t = test->priv; + struct charge_test_writer *w; + + w = kunit_kzalloc(test, sizeof(*w), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, w); + w->t = t; + init_completion(&w->done); + t->writer = w; + + t->power.has_chls = true; + t->chls = 0x0050; + t->on_chls_read = charge_test_start_writer; + KUNIT_EXPECT_EQ(test, charge_test_set(t, POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD, + 60), 0); + /* + * Always wait for the writer, which uses this test's memory: a writer that never + * finishes is left to the KUnit timeout. + */ + wait_for_completion(&w->done); + KUNIT_EXPECT_FALSE(test, t->writer_early); + KUNIT_EXPECT_EQ(test, atomic_read(&t->writer_unlocked), 0); + KUNIT_EXPECT_EQ(test, w->ret, 0); + /* Both the new limit and auto-discharge */ + KUNIT_EXPECT_EQ(test, t->chls, 0x013c); +} + +/* Probe clears force-discharge left without a limit, and only that. */ +static void macsmc_charge_clear_stray_discharge_test(struct kunit *test) +{ + static const struct { + u16 before, after; + unsigned int writes; + } cases[] = { + { 0x0100, 0x0000, 1 }, + { 0x0164, 0x0064, 1 }, + { 0x0105, 0x0005, 1 }, + { 0x0150, 0x0150, 0 }, /* auto-discharge with a limit stays */ + { 0x0050, 0x0050, 0 }, + { 0x0000, 0x0000, 0 }, + }; + struct macsmc_charge_test *t = test->priv; + unsigned int i; + + t->power.has_chls = true; + for (i = 0; i < ARRAY_SIZE(cases); i++) { + t->chls = cases[i].before; + t->nops = 0; + KUNIT_EXPECT_EQ_MSG(test, macsmc_battery_clear_stray_discharge(&t->power), 0, + "case %u", i); + KUNIT_EXPECT_EQ_MSG(test, t->chls, cases[i].after, "case %u", i); + KUNIT_EXPECT_EQ_MSG(test, charge_test_writes(t), cases[i].writes, "case %u", i); + } + + t->chls = 0x0100; + t->fail_key = SMC_KEY(CHLS); + t->fail_err = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_battery_clear_stray_discharge(&t->power), -ETIMEDOUT); + t->fail_write = true; + t->fail_err = -EIO; + KUNIT_EXPECT_EQ(test, macsmc_battery_clear_stray_discharge(&t->power), -EIO); + KUNIT_EXPECT_EQ(test, t->chls, 0x0100); +} + +static struct kunit_case macsmc_charge_test_cases[] = { + KUNIT_CASE(macsmc_charge_behaviours_test), + KUNIT_CASE(macsmc_charge_end_threshold_test), + KUNIT_CASE(macsmc_charge_end_threshold_fault_test), + KUNIT_CASE(macsmc_charge_auto_discharge_test), + KUNIT_CASE(macsmc_charge_auto_discharge_no_limit_test), + KUNIT_CASE(macsmc_charge_auto_discharge_unsupported_test), + KUNIT_CASE(macsmc_charge_auto_chls_read_fault_test), + KUNIT_CASE(macsmc_charge_auto_partial_failure_test), + KUNIT_CASE(macsmc_charge_get_precedence_test), + KUNIT_CASE(macsmc_charge_serialized_test), + KUNIT_CASE(macsmc_charge_clear_stray_discharge_test), + {} +}; + +static struct kunit_suite macsmc_charge_test_suite = { + .name = "macsmc-power-charge", + .init = macsmc_charge_test_init, + .test_cases = macsmc_charge_test_cases, +}; + +kunit_test_suites(&macsmc_power_test_suite, &macsmc_charge_test_suite); diff --git a/drivers/power/supply/macsmc-power.c b/drivers/power/supply/macsmc-power.c index be101284147582..aec59fe13483c4 100644 --- a/drivers/power/supply/macsmc-power.c +++ b/drivers/power/supply/macsmc-power.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -72,6 +73,12 @@ struct macsmc_power { struct device *dev; struct apple_smc *smc; + /* + * Serializes the charge settings: the CHLS threshold and behaviour + * setters each read, modify and write bits of the same key. + */ + struct mutex charge_lock; + struct power_supply_desc ac_desc; struct power_supply_desc batt_desc; @@ -326,11 +333,42 @@ static int macsmc_power_read_chte(struct macsmc_power *power, u8 *buf) return apple_smc_read(power->smc, SMC_KEY(CHTE), buf, 4); } +/* + * Whether a CHLS value holds a charge limit, as the threshold getter reads + * it. Force discharge is only ever written together with a limit: without + * one there is nothing to discharge to. + */ +static bool macsmc_chls_has_limit(u16 chls) +{ + u8 limit = chls & 0xff; + + return limit >= CHLS_MIN_END_THRESHOLD && limit < 100; +} + +static unsigned int macsmc_battery_charge_behaviours(struct macsmc_power *power) +{ + unsigned int behaviours = 0; + + if (power->has_ch0i || power->has_ch0c || power->has_chte || power->has_chls) + behaviours |= BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO); + if (power->has_ch0i) + behaviours |= BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_FORCE_DISCHARGE); + if (power->has_chte || power->has_ch0c) + behaviours |= BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE); + if (power->has_chls) + behaviours |= BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE); + + return behaviours; +} + static int macsmc_battery_get_charge_behaviour(struct macsmc_power *power) { int ret; u8 val8; u8 chte_buf[4]; + u16 vu16; + + guard(mutex)(&power->charge_lock); if (power->has_ch0i) { ret = apple_smc_read_u8(power->smc, SMC_KEY(CH0I), &val8); @@ -359,31 +397,73 @@ static int macsmc_battery_get_charge_behaviour(struct macsmc_power *power) return POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE; } + if (power->has_chls) { + ret = apple_smc_read_u16(power->smc, SMC_KEY(CHLS), &vu16); + if (ret) + return ret; + /* The bit without a limit discharges to nothing: report auto */ + if ((vu16 & CHLS_FORCE_DISCHARGE) && macsmc_chls_has_limit(vu16)) + return POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE; + } + return POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO; } static int macsmc_battery_set_charge_behaviour(struct macsmc_power *power, int val) { + u16 vu16 = 0; int ret; + lockdep_assert_held(&power->charge_lock); + switch (val) { + case POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE: + if (!power->has_chls) + return -EOPNOTSUPP; + fallthrough; case POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO: - /* Reset all inhibitors to a known-good 'auto' state */ + /* + * Read the shared limit before changing any inhibitor, so that a + * refusal leaves every setting as it was. + */ + if (power->has_chls) { + ret = apple_smc_read_u16(power->smc, SMC_KEY(CHLS), &vu16); + if (ret) + return ret; + if (val == POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE && + !macsmc_chls_has_limit(vu16)) + return -EINVAL; + } + + /* + * Reset all inhibitors to a known-good 'auto' state. A write + * reply carries the SMC's response size, which may echo the + * request length: only a negative value is a failure. + */ if (power->has_ch0i) { ret = apple_smc_write_u8(power->smc, SMC_KEY(CH0I), 0); - if (ret) + if (ret < 0) return ret; } if (power->has_chte) { ret = apple_smc_write_u32(power->smc, SMC_KEY(CHTE), 0); - if (ret) + if (ret < 0) return ret; } else if (power->has_ch0c) { ret = apple_smc_write_u8(power->smc, SMC_KEY(CH0C), 0); - if (ret) + if (ret < 0) return ret; } + + /* Set or clear force-discharge to the CHLS charge limit */ + if (power->has_chls) { + if (val == POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE) + vu16 |= CHLS_FORCE_DISCHARGE; + else + vu16 &= ~CHLS_FORCE_DISCHARGE; + return apple_smc_write_u16(power->smc, SMC_KEY(CHLS), vu16); + } return 0; case POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE: @@ -640,11 +720,11 @@ static int macsmc_battery_get_property(struct power_supply *psy, return ret; } -static int macsmc_battery_set_property(struct power_supply *psy, - enum power_supply_property psp, - const union power_supply_propval *val) +static int macsmc_battery_set_charge_property(struct macsmc_power *power, + enum power_supply_property psp, + const union power_supply_propval *val) { - struct macsmc_power *power = power_supply_get_drvdata(psy); + lockdep_assert_held(&power->charge_lock); switch (psp) { case POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR: @@ -658,12 +738,20 @@ static int macsmc_battery_set_property(struct power_supply *psy, return 0; case POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD: if (power->has_chls) { - u16 kval = 0; - /* TODO: Make CHLS_FORCE_DISCHARGE configurable */ + u16 kval; + int ret; + + /* Preserve the force-discharge (auto-discharge) charge_behaviour */ + ret = apple_smc_read_u16(power->smc, SMC_KEY(CHLS), &kval); + if (ret) + return ret; + kval &= CHLS_FORCE_DISCHARGE; if (val->intval < CHLS_MIN_END_THRESHOLD) - kval = CHLS_FORCE_DISCHARGE | CHLS_MIN_END_THRESHOLD; + kval |= CHLS_MIN_END_THRESHOLD; else if (val->intval < 100) - kval = CHLS_FORCE_DISCHARGE | (val->intval & 0xff); + kval |= val->intval & 0xff; + else + kval = 0; /* No limit: auto-discharge ends with it */ return apple_smc_write_u16(power->smc, SMC_KEY(CHLS), kval); } else if (power->has_chwa) { return apple_smc_write_flag(power->smc, SMC_KEY(CHWA), @@ -676,6 +764,38 @@ static int macsmc_battery_set_property(struct power_supply *psy, } } +static int macsmc_battery_set_property(struct power_supply *psy, + enum power_supply_property psp, + const union power_supply_propval *val) +{ + struct macsmc_power *power = power_supply_get_drvdata(psy); + int ret; + + guard(mutex)(&power->charge_lock); + ret = macsmc_battery_set_charge_property(power, psp, val); + /* A write's reply size is not an error, and nothing for sysfs to see */ + return ret < 0 ? ret : 0; +} + +/* + * An earlier kernel could leave force-discharge set in CHLS without a charge limit, which this + * driver never asks of the SMC. Clear the bit once at probe; the limit byte is kept. + */ +static int macsmc_battery_clear_stray_discharge(struct macsmc_power *power) +{ + u16 chls; + int ret; + + guard(mutex)(&power->charge_lock); + ret = apple_smc_read_u16(power->smc, SMC_KEY(CHLS), &chls); + if (ret) + return ret; + if (!(chls & CHLS_FORCE_DISCHARGE) || macsmc_chls_has_limit(chls)) + return 0; + ret = apple_smc_write_u16(power->smc, SMC_KEY(CHLS), chls & ~CHLS_FORCE_DISCHARGE); + return ret < 0 ? ret : 0; +} + static int macsmc_battery_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { @@ -875,6 +995,9 @@ static int macsmc_power_probe(struct platform_device *pdev) power->dev = dev; power->smc = smc; + ret = devm_mutex_init(dev, &power->charge_lock); + if (ret) + return ret; dev_set_drvdata(dev, power); INIT_WORK(&power->critical_work, macsmc_power_critical_work); @@ -988,28 +1111,24 @@ static int macsmc_power_probe(struct platform_device *pdev) apple_smc_write_u8(smc, SMC_KEY(CH0K), 0); apple_smc_write_u8(smc, SMC_KEY(CH0B), 0); - /* Configure charge behaviour if supported */ - if (power->has_ch0i || power->has_ch0c || power->has_chte) { - props[nprops++] = POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR; - - power->batt_desc.charge_behaviours = - BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO); - - if (power->has_ch0i) - power->batt_desc.charge_behaviours |= - BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_FORCE_DISCHARGE); - - if (power->has_chte || power->has_ch0c) - power->batt_desc.charge_behaviours |= - BIT(POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE); - } - /* Detect charge limit method (CHWA vs CHLS) */ if (apple_smc_read_flag(power->smc, SMC_KEY(CHWA), &flag) == 0) power->has_chwa = true; else if (apple_smc_read_u16(power->smc, SMC_KEY(CHLS), &vu16) >= 0) power->has_chls = true; + if (power->has_chls && macsmc_battery_clear_stray_discharge(power)) + dev_warn(dev, "Failed to clear force-discharge without a charge limit\n"); + + /* + * CHLS carries auto-discharge, so a CHLS-only Mac can select auto + * to leave it as well. + */ + power->batt_desc.charge_behaviours = + macsmc_battery_charge_behaviours(power); + if (power->batt_desc.charge_behaviours) + props[nprops++] = POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR; + if (power->has_chwa || power->has_chls) { props[nprops++] = POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD; props[nprops++] = POWER_SUPPLY_PROP_CHARGE_CONTROL_START_THRESHOLD; diff --git a/drivers/power/supply/power_supply_sysfs.c b/drivers/power/supply/power_supply_sysfs.c index f30a7b9ccd5e93..d22541f4a4ecf6 100644 --- a/drivers/power/supply/power_supply_sysfs.c +++ b/drivers/power/supply/power_supply_sysfs.c @@ -146,6 +146,7 @@ static const char * const POWER_SUPPLY_CHARGE_BEHAVIOUR_TEXT[] = { [POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE] = "inhibit-charge", [POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE_AWAKE] = "inhibit-charge-awake", [POWER_SUPPLY_CHARGE_BEHAVIOUR_FORCE_DISCHARGE] = "force-discharge", + [POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE] = "auto-discharge", }; static struct power_supply_attr power_supply_attrs[] __ro_after_init = { diff --git a/drivers/ptp/ptp_ocp.c b/drivers/ptp/ptp_ocp.c index 3d26ec1f7b9ec2..a8cba2f64b98ae 100644 --- a/drivers/ptp/ptp_ocp.c +++ b/drivers/ptp/ptp_ocp.c @@ -1825,7 +1825,7 @@ ptp_ocp_watchdog(struct timer_list *t) static void ptp_ocp_estimate_pci_timing(struct ptp_ocp *bp) { - ktime_t start, end, delay = U64_MAX; + ktime_t start, end, delay = KTIME_MAX; u32 ctrl; int i; diff --git a/drivers/regulator/ltc3676.c b/drivers/regulator/ltc3676.c index 768cdce0d4ecfb..1ec218951829d2 100644 --- a/drivers/regulator/ltc3676.c +++ b/drivers/regulator/ltc3676.c @@ -232,7 +232,7 @@ static const struct regulator_desc ltc3676_regulators[LTC3676_NUM_REGULATORS] = LTC3676_FIXED_REG(LDO4, ldo4, LDOB, 2), }; -static bool ltc3676_readable_writeable_reg(struct device *dev, unsigned int reg) +static bool ltc3676_writeable_reg(struct device *dev, unsigned int reg) { switch (reg) { case LTC3676_BUCK1 ... LTC3676_IRQSTAT: @@ -243,6 +243,15 @@ static bool ltc3676_readable_writeable_reg(struct device *dev, unsigned int reg) return false; } +static bool ltc3676_readable_reg(struct device *dev, unsigned int reg) +{ + switch (reg) { + case LTC3676_BUCK1 ... LTC3676_IRQSTAT: + return true; + } + return false; +} + static bool ltc3676_volatile_reg(struct device *dev, unsigned int reg) { switch (reg) { @@ -255,8 +264,8 @@ static bool ltc3676_volatile_reg(struct device *dev, unsigned int reg) static const struct regmap_config ltc3676_regmap_config = { .reg_bits = 8, .val_bits = 8, - .writeable_reg = ltc3676_readable_writeable_reg, - .readable_reg = ltc3676_readable_writeable_reg, + .writeable_reg = ltc3676_writeable_reg, + .readable_reg = ltc3676_readable_reg, .volatile_reg = ltc3676_volatile_reg, .max_register = LTC3676_CLIRQ, .use_single_read = true, diff --git a/drivers/regulator/of_regulator.c b/drivers/regulator/of_regulator.c index c0cc6cc0afd8bf..785b7a11dfc660 100644 --- a/drivers/regulator/of_regulator.c +++ b/drivers/regulator/of_regulator.c @@ -935,15 +935,15 @@ static int is_supply_name(const char *name) int of_regulator_bulk_get_all(struct device *dev, struct device_node *np, struct regulator_bulk_data **consumers) { - int num_consumers = 0; + int num_consumers = 0, names_len = 0; struct regulator *tmp; struct regulator_bulk_data *_consumers = NULL; struct property *prop; + char *names; int i, n = 0, ret; - char name[64]; /* - * first pass: get numbers of xxx-supply + * first pass: get numbers of xxx-supply and the room their names take * second pass: fill consumers */ restart: @@ -953,16 +953,19 @@ int of_regulator_bulk_get_all(struct device *dev, struct device_node *np, continue; if (!_consumers) { num_consumers++; + names_len += i + 1; continue; } else { - memcpy(name, prop->name, i); - name[i] = '\0'; - tmp = regulator_get(dev, name); + memcpy(names, prop->name, i); + names[i] = '\0'; + tmp = regulator_get(dev, names); if (IS_ERR(tmp)) { ret = PTR_ERR(tmp); goto error; } + _consumers[n].supply = names; _consumers[n].consumer = tmp; + names += i + 1; n++; continue; } @@ -973,9 +976,16 @@ int of_regulator_bulk_get_all(struct device *dev, struct device_node *np, } if (num_consumers == 0) return 0; - _consumers = kmalloc_objs(struct regulator_bulk_data, num_consumers); + /* + * The supply names are kept in the same allocation as the array, so + * that they share its lifetime and the caller has nothing extra to + * free. + */ + _consumers = kzalloc(size_add(size_mul(num_consumers, sizeof(*_consumers)), + names_len), GFP_KERNEL); if (!_consumers) return -ENOMEM; + names = (char *)(_consumers + num_consumers); goto restart; error: diff --git a/drivers/regulator/tps6594-regulator.c b/drivers/regulator/tps6594-regulator.c index 31a5218d551059..503b89a2f5f810 100644 --- a/drivers/regulator/tps6594-regulator.c +++ b/drivers/regulator/tps6594-regulator.c @@ -241,21 +241,21 @@ static const struct regulator_desc tps65224_buck_regs[] = { TPS65224_MASK_BUCKS_VSET, TPS6594_REG_BUCKX_CTRL(1), TPS6594_BIT_BUCK_EN, 0, 0, tps65224_bucks_2_3_4_ranges, - 4, 0, 0, NULL, 0, 0), + ARRAY_SIZE(tps65224_bucks_2_3_4_ranges), 0, 0, NULL, 0, 0), TPS6594_REGULATOR("BUCK3", "buck3", TPS6594_BUCK_3, REGULATOR_VOLTAGE, tps6594_bucks_ops, TPS65224_MASK_BUCKS_VSET, TPS6594_REG_BUCKX_VOUT_1(2), TPS65224_MASK_BUCKS_VSET, TPS6594_REG_BUCKX_CTRL(2), TPS6594_BIT_BUCK_EN, 0, 0, tps65224_bucks_2_3_4_ranges, - 4, 0, 0, NULL, 0, 0), + ARRAY_SIZE(tps65224_bucks_2_3_4_ranges), 0, 0, NULL, 0, 0), TPS6594_REGULATOR("BUCK4", "buck4", TPS6594_BUCK_4, REGULATOR_VOLTAGE, tps6594_bucks_ops, TPS65224_MASK_BUCKS_VSET, TPS6594_REG_BUCKX_VOUT_1(3), TPS65224_MASK_BUCKS_VSET, TPS6594_REG_BUCKX_CTRL(3), TPS6594_BIT_BUCK_EN, 0, 0, tps65224_bucks_2_3_4_ranges, - 4, 0, 0, NULL, 0, 0), + ARRAY_SIZE(tps65224_bucks_2_3_4_ranges), 0, 0, NULL, 0, 0), }; static const struct tps6594_regulator_irq_type tps6594_buck1_irq_types[] = { diff --git a/drivers/scsi/ch.c b/drivers/scsi/ch.c index 4010fdbf813cc7..c36539c83ed1a4 100644 --- a/drivers/scsi/ch.c +++ b/drivers/scsi/ch.c @@ -112,7 +112,6 @@ typedef struct { int minor; char name[8]; struct scsi_device *device; - struct scsi_device **dt; /* ptrs to data transfer elements */ u_int firsts[CH_TYPES]; u_int counts[CH_TYPES]; u_int voltags; @@ -363,15 +362,10 @@ ch_readconfig(scsi_changer *ch) vendor_labels[i]); } - /* look up the devices of the data transfer elements */ - ch->dt = kzalloc_objs(*ch->dt, ch->counts[CHET_DT]); - - if (!ch->dt) { - kfree(buffer); - return -ENOMEM; - } - + /* report the devices of the data transfer elements */ for (elem = 0; elem < ch->counts[CHET_DT]; elem++) { + struct scsi_device *sdev; + id = -1; lun = 0; if (elem < CH_DT_MAX && -1 != dt_id[elem]) { @@ -387,10 +381,8 @@ ch_readconfig(scsi_changer *ch) VPRINTK(KERN_INFO, "dt 0x%x: ",elem+ch->firsts[CHET_DT]); if (data[6] & 0x80) { VPRINTK(KERN_CONT, "not this SCSI bus\n"); - ch->dt[elem] = NULL; } else if (0 == (data[6] & 0x30)) { VPRINTK(KERN_CONT, "ID/LUN unknown\n"); - ch->dt[elem] = NULL; } else { id = ch->device->id; lun = 0; @@ -400,18 +392,16 @@ ch_readconfig(scsi_changer *ch) } if (-1 != id) { VPRINTK(KERN_CONT, "ID %i, LUN %i, ",id,lun); - ch->dt[elem] = - scsi_device_lookup(ch->device->host, - ch->device->channel, - id,lun); - if (!ch->dt[elem]) { + sdev = scsi_device_lookup(ch->device->host, + ch->device->channel, + id, lun); + if (!sdev) { /* should not happen */ VPRINTK(KERN_CONT, "Huh? device not found!\n"); } else { VPRINTK(KERN_CONT, "name: %8.8s %16.16s %4.4s\n", - ch->dt[elem]->vendor, - ch->dt[elem]->model, - ch->dt[elem]->rev); + sdev->vendor, sdev->model, sdev->rev); + scsi_device_put(sdev); } } } @@ -575,7 +565,6 @@ static void ch_destroy(struct kref *ref) scsi_changer *ch = container_of(ref, scsi_changer, ref); ch->device = NULL; - kfree(ch->dt); kfree(ch); } diff --git a/drivers/scsi/qedi/qedi_main.c b/drivers/scsi/qedi/qedi_main.c index 227ff7bd1bdc9b..f394fcbb97e7ee 100644 --- a/drivers/scsi/qedi/qedi_main.c +++ b/drivers/scsi/qedi/qedi_main.c @@ -2652,8 +2652,6 @@ static int __qedi_probe(struct pci_dev *pdev, int mode) snprintf(host_buf, sizeof(host_buf), "host_%d", qedi->shost->host_no); qedi_ops->common->set_name(qedi->cdev, host_buf); - qedi_ops->register_ops(qedi->cdev, &qedi_cb_ops, qedi); - memset(¶ms, 0, sizeof(params)); params.mtu = DEF_PATH_MTU + IPV6_HDR_LEN + TCP_HDR_LEN; qedi->ll2_mtu = DEF_PATH_MTU; @@ -2670,6 +2668,7 @@ static int __qedi_probe(struct pci_dev *pdev, int mode) spin_lock_init(&qedi->task_idx_lock); mutex_init(&qedi->stats_lock); } + qedi_ops->register_ops(qedi->cdev, &qedi_cb_ops, qedi); qedi_ops->ll2->register_cb_ops(qedi->cdev, &qedi_ll2_cb_ops, qedi); qedi_ops->ll2->start(qedi->cdev, ¶ms); diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 0295ceac3c3fa2..af85f95e1a2014 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -234,6 +234,15 @@ config APPLE_T6030_DISPLAY_GATE Say 'y' if you want the native display on M3 Pro MacBook Pros. +config APPLE_T6030_GPU_PMP_LINK + bool + depends on APPLE_T6030_DISPLAY_GATE + default n + help + Link an opted-in T6030 GPU to the PMP admitted by the display gate. + GPU power commands wait for that supplier's acknowledged display + request through the existing PMP report startup and removal rules. + config APPLE_DISPLAY_GATE_KUNIT_TEST bool "KUnit tests for the Apple display gate" if !KUNIT_ALL_TESTS depends on KUNIT=y && APPLE_T6030_DISPLAY_GATE diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 0c3d680185685d..0425bf2cdaa6ed 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -52,6 +52,7 @@ long sep_store_read(void *handle, long long off, void *buf, size_t len); long sep_store_write(void *handle, long long off, const void *buf, size_t len); int sep_store_sync(void *handle); +int sep_store_sync_parent(void *handle); /* -- sha_shim.c --------------------------------------------------------- */ diff --git a/drivers/soc/apple/shim.rs b/drivers/soc/apple/shim.rs index 7e7f489e594818..8e30c3f54b8177 100644 --- a/drivers/soc/apple/shim.rs +++ b/drivers/soc/apple/shim.rs @@ -16,6 +16,7 @@ extern "C" { fn sep_store_read(handle: *mut c_void, off: i64, buf: *mut c_void, len: usize) -> c_long; fn sep_store_write(handle: *mut c_void, off: i64, buf: *const c_void, len: usize) -> c_long; fn sep_store_sync(handle: *mut c_void) -> c_int; + fn sep_store_sync_parent(handle: *mut c_void) -> c_int; fn sep_random_bytes(buf: *mut c_void, len: usize) -> c_int; } @@ -184,6 +185,13 @@ impl StoreFile { // SAFETY: `handle` is live per the type invariant. kernel::error::to_result(unsafe { sep_store_sync(self.handle) }) } + + /// Flushes the directory entry of this file, which [`StoreFile::sync`] + /// alone does not make durable for a newly created file. + pub(crate) fn sync_parent(&self) -> Result<()> { + // SAFETY: `handle` is live per the type invariant. + kernel::error::to_result(unsafe { sep_store_sync_parent(self.handle) }) + } } impl Drop for StoreFile { diff --git a/drivers/soc/apple/store_shim.c b/drivers/soc/apple/store_shim.c index 4c89f92eb5f13b..0eabe7305b0497 100644 --- a/drivers/soc/apple/store_shim.c +++ b/drivers/soc/apple/store_shim.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -142,3 +143,35 @@ int sep_store_sync(void *handle) { return vfs_fsync((struct file *)handle, 0); } + +/* + * Flushes the directory that holds an open store file. fsync() of the file + * itself is not guaranteed to make its name in that directory durable, so a + * file created this boot could be missing after a crash. Opened under kernel + * credentials, as the file was. + */ +int sep_store_sync_parent(void *handle) +{ + struct file *f = handle; + struct cred *kern; + struct file *dir; + struct path parent; + int ret; + + kern = prepare_kernel_cred(&init_task); + if (!kern) + return -ENOMEM; + + /* The file holds its mount; the parent dentry is pinned until dput(). */ + parent.mnt = f->f_path.mnt; + parent.dentry = dget_parent(f->f_path.dentry); + dir = dentry_open(&parent, O_RDONLY | O_DIRECTORY, kern); + dput(parent.dentry); + put_cred(kern); + if (IS_ERR(dir)) + return PTR_ERR(dir); + + ret = vfs_fsync(dir, 0); + fput(dir); + return ret; +} diff --git a/drivers/soc/apple/t6030-display-gate.c b/drivers/soc/apple/t6030-display-gate.c index 82c69f53cfcae5..2f73104b05c8cc 100644 --- a/drivers/soc/apple/t6030-display-gate.c +++ b/drivers/soc/apple/t6030-display-gate.c @@ -811,18 +811,27 @@ static int __init gate_pmp_copy_values(struct of_changeset *cs, struct device_no return n; } -static int __init gate_t8122_gpu_pmp_link(struct of_changeset *cs, struct device_node *pmp) +static int __init gate_gpu_pmp_link(struct of_changeset *cs, struct device_node *pmp) { struct device_node *gpu, *linked; + bool t6030 = IS_ENABLED(CONFIG_APPLE_T6030_GPU_PMP_LINK) && gate_soc == &gate_t6030; int ret = 0; - if (gate_soc != &gate_t8122) + if (gate_soc != &gate_t8122 && !t6030) return 0; - gpu = of_find_compatible_node(NULL, NULL, "apple,agx-t8122"); + gpu = t6030 ? gate_find_one("apple,agx-t6030") : + of_find_compatible_node(NULL, NULL, "apple,agx-t8122"); if (!gpu || !of_device_is_available(gpu)) goto out; + /* Do not replace a malformed or unresolved pre-existing GPU supplier. */ + if (t6030 && of_property_present(gpu, "apple,pmp") && + of_property_count_u32_elems(gpu, "apple,pmp") != 1) { + ret = -EINVAL; + goto out; + } linked = of_parse_phandle(gpu, "apple,pmp", 0); - if (!pmp || !pmp->phandle || (linked && linked != pmp)) + if (!pmp || !pmp->phandle || (linked && linked != pmp) || + (t6030 && of_property_present(gpu, "apple,pmp") && !linked)) ret = -EINVAL; else if (!linked) ret = of_changeset_add_prop_u32(cs, gpu, "apple,pmp", pmp->phandle); @@ -868,7 +877,7 @@ static int __init gate_reuse_apply(struct device_node **ps) ret = gate_add_bool(&gate_pmp_cs, r->ans, "apple,no-ack"); /* The current14 T8122 GPU needs an inner AGX vote from this Mac's PMP. */ if (!ret) - ret = gate_t8122_gpu_pmp_link(&gate_pmp_cs, r->pmp); + ret = gate_gpu_pmp_link(&gate_pmp_cs, r->pmp); /* The display domains' floor, applied by the PMGR driver when it probes. */ for (i = PMP_PS_DISP_SYS; i <= PMP_PS_DISP_CPU && !ret; i++) ret = gate_set_u32(&gate_pmp_cs, ps[i], "apple,min-state", PMGR_PS_ACTIVE); @@ -941,9 +950,9 @@ static int __init gate_pmp_apply(struct device_node *dcp, struct device_node **p if (!ret) ret = of_changeset_add_prop_u32(&gate_pmp_cs, dcp, "apple,pmp-report", disp->phandle); - /* The current14 T8122 GPU needs an inner AGX vote from this Mac's PMP. */ + /* T8122 and an opted-in T6030 GPU need this Mac's PMP AGX vote. */ if (!ret) - ret = gate_t8122_gpu_pmp_link(&gate_pmp_cs, pmp); + ret = gate_gpu_pmp_link(&gate_pmp_cs, pmp); /* The DART and mailbox interrupt parent lives in the base tree. */ if (!ret) ret = of_changeset_add_prop_u32(&gate_pmp_cs, dart, "interrupt-parent", diff --git a/drivers/soc/apple/xart_guard.rs b/drivers/soc/apple/xart_guard.rs index db6a6bbc5654eb..661253c5b01461 100644 --- a/drivers/soc/apple/xart_guard.rs +++ b/drivers/soc/apple/xart_guard.rs @@ -27,9 +27,12 @@ //! a guard that blocks matching from one that has refused nothing yet. //! //! The list entry is made durable before the enclave's write reaches the -//! gigalocker. A crash between the two leaves an entry for a record that was -//! never written, which is harmless. It can never leave a Linux record that -//! the next boot treats as another OS's. +//! gigalocker, and the list's own directory entry is flushed before anything +//! is adopted; the key is listed in memory only once its entry is written and +//! flushed. A crash between the two durable points leaves an entry for a +//! record that was never written, which is harmless, and a failed adoption is +//! retried in the same slot rather than skipped. It can never leave a Linux +//! record that the next boot treats as another OS's. use crate::shim::StoreFile; use crate::xart_store::{crc32_ieee, Key}; @@ -167,6 +170,8 @@ pub(crate) trait ListFile { fn read_exact(&self, off: u64, buf: &mut [u8]) -> Result<()>; fn write_all(&self, off: u64, buf: &[u8]) -> Result<()>; fn sync(&self) -> Result<()>; + /// Makes the file's directory entry durable. + fn sync_parent(&self) -> Result<()>; } impl ListFile for StoreFile { @@ -185,6 +190,10 @@ impl ListFile for StoreFile { fn sync(&self) -> Result<()> { StoreFile::sync(self) } + + fn sync_parent(&self) -> Result<()> { + StoreFile::sync_parent(self) + } } pub(crate) struct Guard { @@ -223,6 +232,11 @@ impl Guard { existed: existing, refused: 0, }; + // A list created this boot (or by a crashed one) is only safe to adopt + // into once its name is durable: fsync() of the file alone does not + // guarantee that. If the directory cannot be flushed, the file is + // dropped and nothing is adopted, as without a list. + let file = file.and_then(|file| file.sync_parent().map(|()| file)); match file { Ok(file) => { if let Err(e) = guard.load(&file) { @@ -302,10 +316,18 @@ impl Guard { if usize::try_from(self.end).map_or(true, |end| end / ENTRY_SIZE >= MAX_ENTRIES) { return Err(ENOSPC); } + // Reserve room for the in-memory key before writing, so an entry made + // durable is always listed in memory as well: no allocation can fail + // after a record is written. + self.owned.reserve(1, GFP_KERNEL)?; file.write_all(self.end, &encode(key))?; file.sync()?; + // Only now that the entry is written and flushed: list it (into the + // reserved slot, which cannot fail) and then advance the end. A failed + // write or flush above leaves the end unchanged, so the next adoption + // overwrites this slot, which holds no record the enclave kept. + self.owned.push_within_capacity(*key).map_err(|_| ENOMEM)?; self.end += ENTRY_SIZE as u64; - self.owned.push(*key, GFP_KERNEL)?; Ok(()) } @@ -346,7 +368,7 @@ impl Guard { #[kernel::macros::kunit_tests(apple_sep_xart_guard)] mod tests { use super::*; - use core::cell::RefCell; + use core::cell::{Cell, RefCell}; fn session(byte: u8) -> Key { Key::new(4, [byte; 16]) @@ -442,8 +464,34 @@ mod tests { assert_eq!(decode(&encode(&key)[..31]), None); } - /// A list file in memory, kept across the guards of successive boots. - struct MemFile<'a>(&'a RefCell>); + /// Failures a [`MemFile`] reports, switchable while a guard holds it. + #[derive(Default)] + struct Faults { + /// The write fails and changes nothing. + write: Cell, + /// The write lands, but the flush after it fails. + sync: Cell, + /// The directory entry cannot be flushed. + parent: Cell, + } + + /// A list file in memory, kept across the guards of successive boots, with + /// optional injected faults. + struct MemFile<'a>(&'a RefCell>, Option<&'a Faults>); + + fn mem(bytes: &RefCell>) -> MemFile<'_> { + MemFile(bytes, None) + } + + fn faulty<'a>(bytes: &'a RefCell>, faults: &'a Faults) -> MemFile<'a> { + MemFile(bytes, Some(faults)) + } + + impl MemFile<'_> { + fn fails(&self, fault: impl Fn(&Faults) -> &Cell) -> bool { + self.1.is_some_and(|faults| fault(faults).get()) + } + } impl ListFile for MemFile<'_> { fn size(&self) -> Result { @@ -459,6 +507,9 @@ mod tests { } fn write_all(&self, off: u64, buf: &[u8]) -> Result<()> { + if self.fails(|f| &f.write) { + return Err(EIO); + } let mut bytes = self.0.borrow_mut(); let off = usize::try_from(off).map_err(|_| EINVAL)?; let end = off.checked_add(buf.len()).ok_or(EINVAL)?; @@ -470,6 +521,16 @@ mod tests { } fn sync(&self) -> Result<()> { + if self.fails(|f| &f.sync) { + return Err(EIO); + } + Ok(()) + } + + fn sync_parent(&self) -> Result<()> { + if self.fails(|f| &f.parent) { + return Err(EIO); + } Ok(()) } } @@ -496,7 +557,7 @@ mod tests { fn a_guard_refuses_another_os_record() -> Result<()> { let bytes = RefCell::new(KVec::new()); let foreign = session(1); - let mut guard = Guard::with_file(1, keys(&[foreign])?, Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, keys(&[foreign])?, Ok(mem(&bytes))); assert_eq!(guard.effective_level(), 1); assert!(guard.list_loaded()); assert_eq!(guard.check(&foreign, true), Err(EPERM)); @@ -512,7 +573,7 @@ mod tests { let mut list = KVec::new(); list.extend_from_slice(&encode(&own), GFP_KERNEL)?; let bytes = RefCell::new(list); - let mut guard = Guard::with_file(1, keys(&[own])?, Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, keys(&[own])?, Ok(mem(&bytes))); assert_eq!(guard.check(&own, true), Ok(())); assert_eq!(guard.check(&own, false), Ok(())); // An entry that is already listed is not written again. @@ -527,13 +588,13 @@ mod tests { let created = session(3); // First boot: the enclave creates a record, which is listed first. - let mut guard = Guard::with_file(1, keys(&[foreign])?, Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, keys(&[foreign])?, Ok(mem(&bytes))); assert_eq!(guard.check(&created, true), Ok(())); assert_eq!(listed(&bytes).as_slice(), &[Some(created)]); drop(guard); // Next boot: both records predate the guard; only Linux's is writable. - let mut guard = Guard::with_file(1, keys(&[foreign, created])?, Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, keys(&[foreign, created])?, Ok(mem(&bytes))); assert_eq!(guard.check(&created, true), Ok(())); assert_eq!(guard.check(&created, false), Ok(())); assert_eq!(guard.check(&foreign, true), Err(EPERM)); @@ -551,7 +612,7 @@ mod tests { list.extend_from_slice(&encode(&second)[..10], GFP_KERNEL)?; let bytes = RefCell::new(list); - let mut guard = Guard::with_file(1, keys(&[first])?, Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, keys(&[first])?, Ok(mem(&bytes))); assert_eq!(guard.check(&first, true), Ok(())); assert_eq!(guard.check(&second, true), Ok(())); assert_eq!(listed(&bytes).as_slice(), &[Some(first), Some(second)]); @@ -580,14 +641,14 @@ mod tests { all.push(numbered(i), GFP_KERNEL)?; } let bytes = RefCell::new(list_of(&all)?); - let mut guard = Guard::with_file(1, KVec::new(), Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, KVec::new(), Ok(mem(&bytes))); assert!(guard.file.is_some()); assert_eq!(guard.check(&numbered(MAX_ENTRIES), true), Err(ENOSPC)); assert_eq!(bytes.borrow().len(), MAX_ENTRIES * ENTRY_SIZE); drop(guard); // Reopened: still within what load() accepts, and Linux's records // are still Linux's. - let mut guard = Guard::with_file(1, keys(&[numbered(7)])?, Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, keys(&[numbered(7)])?, Ok(mem(&bytes))); assert!(guard.file.is_some()); assert_eq!(guard.check(&numbered(7), true), Ok(())); Ok(()) @@ -603,13 +664,13 @@ mod tests { all.push(numbered(i % distinct), GFP_KERNEL)?; } let bytes = RefCell::new(list_of(&all)?); - let mut guard = Guard::with_file(1, KVec::new(), Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, KVec::new(), Ok(mem(&bytes))); assert_eq!(guard.owned.len(), distinct); // Appending would make a list the next boot refuses. assert_eq!(guard.check(&numbered(MAX_ENTRIES), true), Err(ENOSPC)); assert_eq!(bytes.borrow().len(), MAX_ENTRIES * ENTRY_SIZE); drop(guard); - let guard = Guard::with_file(1, KVec::new(), Ok(MemFile(&bytes))); + let guard = Guard::with_file(1, KVec::new(), Ok(mem(&bytes))); assert!(guard.file.is_some()); Ok(()) } @@ -624,13 +685,13 @@ mod tests { list.extend_from_slice(&encode(&numbered(MAX_ENTRIES))[..10], GFP_KERNEL)?; let bytes = RefCell::new(list); - let mut guard = Guard::with_file(1, KVec::new(), Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, KVec::new(), Ok(mem(&bytes))); // The torn tail is overwritten by the one entry that still fits. assert_eq!(guard.check(&numbered(MAX_ENTRIES), true), Ok(())); assert_eq!(bytes.borrow().len(), MAX_ENTRIES * ENTRY_SIZE); assert_eq!(guard.check(&numbered(MAX_ENTRIES + 1), true), Err(ENOSPC)); drop(guard); - let mut guard = Guard::with_file(1, KVec::new(), Ok(MemFile(&bytes))); + let mut guard = Guard::with_file(1, KVec::new(), Ok(mem(&bytes))); assert!(guard.file.is_some()); assert_eq!(guard.check(&numbered(MAX_ENTRIES), true), Ok(())); Ok(()) @@ -649,6 +710,66 @@ mod tests { Ok(()) } + #[test] + fn a_failed_write_lists_nothing() -> Result<()> { + let bytes = RefCell::new(KVec::new()); + let faults = Faults::default(); + let created = session(3); + let mut guard = Guard::with_file(1, KVec::new(), Ok(faulty(&bytes, &faults))); + faults.write.set(true); + // The write fails: nothing is listed and the end did not advance. + assert_eq!(guard.check(&created, true), Err(EIO)); + assert_eq!(bytes.borrow().len(), 0); + faults.write.set(false); + // The same slot takes the record once the write lands. + assert_eq!(guard.check(&created, true), Ok(())); + assert_eq!(listed(&bytes).as_slice(), &[Some(created)]); + Ok(()) + } + + #[test] + fn a_failed_flush_is_retried_in_the_same_slot() -> Result<()> { + let bytes = RefCell::new(KVec::new()); + let faults = Faults::default(); + let refused = session(3); + let created = session(4); + let mut guard = Guard::with_file(1, KVec::new(), Ok(faulty(&bytes, &faults))); + faults.sync.set(true); + // The write lands but the flush fails: the record is not listed, so it + // is not writable on a retry either. + assert_eq!(guard.check(&refused, true), Err(EIO)); + assert_eq!(guard.check(&refused, true), Err(EIO)); + faults.sync.set(false); + // The next adoption reuses the same slot the unflushed write took, so + // the list holds no duplicate. + assert_eq!(guard.check(&created, true), Ok(())); + assert_eq!(guard.check(&refused, true), Ok(())); + assert_eq!(listed(&bytes).as_slice(), &[Some(created), Some(refused)]); + drop(guard); + + // The next boot reads exactly those two, in order. + let mut guard = Guard::with_file(1, keys(&[created, refused])?, Ok(mem(&bytes))); + assert_eq!(guard.check(&created, true), Ok(())); + assert_eq!(guard.check(&refused, true), Ok(())); + Ok(()) + } + + #[test] + fn without_a_durable_directory_entry_nothing_is_adopted() -> Result<()> { + let own = session(2); + let bytes = RefCell::new(list_of(&[own])?); + let faults = Faults::default(); + faults.parent.set(true); + let mut guard = Guard::with_file(1, keys(&[own])?, Ok(faulty(&bytes, &faults))); + // The directory flush fails, so the file is dropped: as without a + // list, every existing record is protected and nothing is listed. + assert!(!guard.list_loaded()); + assert_eq!(guard.check(&own, true), Err(EPERM)); + assert!(guard.check(&session(3), true).is_err()); + assert_eq!(bytes.borrow().len(), ENTRY_SIZE); + Ok(()) + } + #[test] fn the_default_follows_the_platform() { use crate::profile; diff --git a/drivers/spi/spi-nxp-fspi.c b/drivers/spi/spi-nxp-fspi.c index 4425132432ec87..e0c88e9f81833b 100644 --- a/drivers/spi/spi-nxp-fspi.c +++ b/drivers/spi/spi-nxp-fspi.c @@ -898,10 +898,10 @@ static int nxp_fspi_select_mem(struct nxp_fspi *f, struct spi_device *spi, dev_dbg(f->dev, "Target device [CS:%x] selected\n", spi_get_chipselect(spi, 0)); /* - * Per the FlexSPI reference manual (initialization sequence), MCR0 and - * the DLL control registers should be configured while the module is in - * stop mode (MCR0[MDIS] = 1). Enter stop mode before reconfiguring the - * RX sample clock source and the DLL, then exit stop mode afterwards. + * Per the FlexSPI reference manual (initialization sequence), MCR0 + * should be configured while the module is in stop mode (MCR0[MDIS] = 1). + * Enter stop mode before reconfiguring the RX sample clock source, then + * exit stop mode afterwards. */ reg = fspi_readl(f, f->iobase + FSPI_MCR0); fspi_writel(f, reg | FSPI_MCR0_MDIS, f->iobase + FSPI_MCR0); @@ -936,6 +936,16 @@ static int nxp_fspi_select_mem(struct nxp_fspi *f, struct spi_device *spi, if (ret) return ret; + /* + * Exit stop mode before running the DLL calibration. The DLL + * reference clock is derived from the module clock domain, which is + * gated while MCR0[MDIS] = 1. Calibrating the DLL in stop mode leaves + * the STS2 lock bits stuck at 0 (the DLL never runs), so clear MDIS + * first and let the module and reference clock run. + */ + reg = fspi_readl(f, f->iobase + FSPI_MCR0); + fspi_writel(f, reg & ~FSPI_MCR0_MDIS, f->iobase + FSPI_MCR0); + /* * If clock rate > 100MHz, then switch from DLL override mode to * DLL calibration mode. @@ -945,10 +955,6 @@ static int nxp_fspi_select_mem(struct nxp_fspi *f, struct spi_device *spi, else nxp_fspi_dll_override(f); - /* Exit stop mode now that MCR0 and the DLL have been reconfigured. */ - reg = fspi_readl(f, f->iobase + FSPI_MCR0); - fspi_writel(f, reg & ~FSPI_MCR0_MDIS, f->iobase + FSPI_MCR0); - f->pre_op_rate = op->max_freq; f->selected = spi_get_chipselect(spi, 0); diff --git a/drivers/spi/spi-sg2044-nor.c b/drivers/spi/spi-sg2044-nor.c index f3bcb8a1b92bb1..bc9a8ee9bce448 100644 --- a/drivers/spi/spi-sg2044-nor.c +++ b/drivers/spi/spi-sg2044-nor.c @@ -307,15 +307,15 @@ static ssize_t sg2044_spifmc_tran_cmd(struct sg2044_spifmc *spifmc, return 0; } -static void sg2044_spifmc_trans(struct sg2044_spifmc *spifmc, - const struct spi_mem_op *op) +static int sg2044_spifmc_trans(struct sg2044_spifmc *spifmc, + const struct spi_mem_op *op) { if (op->data.dir == SPI_MEM_DATA_IN) - sg2044_spifmc_read(spifmc, op); + return sg2044_spifmc_read(spifmc, op); else if (op->data.dir == SPI_MEM_DATA_OUT) - sg2044_spifmc_write(spifmc, op); + return sg2044_spifmc_write(spifmc, op); else - sg2044_spifmc_tran_cmd(spifmc, op); + return sg2044_spifmc_tran_cmd(spifmc, op); } static ssize_t sg2044_spifmc_trans_reg(struct sg2044_spifmc *spifmc, @@ -385,29 +385,64 @@ static ssize_t sg2044_spifmc_trans_reg(struct sg2044_spifmc *spifmc, return 0; } +static int sg2044_spifmc_set_speed(struct sg2044_spifmc *spifmc, + unsigned int speed_hz) +{ + unsigned long rate = clk_get_rate(spifmc->clk); + u64 div; + u32 reg; + + if (!rate) + return -EINVAL; + + /* SCK = HCLK / (2 * (SckDiv + 1)); round down the resulting SCK. */ + div = speed_hz ? DIV_ROUND_UP_ULL(rate, 2ULL * speed_hz) : 1; + if (div > SPIFMC_CTRL_SCK_DIV_MASK + 1) + return -EINVAL; + + reg = readl(spifmc->io_base + SPIFMC_CTRL); + reg &= ~SPIFMC_CTRL_SCK_DIV_MASK; + reg |= div - 1; + writel(reg, spifmc->io_base + SPIFMC_CTRL); + + return 0; +} + static int sg2044_spifmc_exec_op(struct spi_mem *mem, const struct spi_mem_op *op) { struct sg2044_spifmc *spifmc; + int ret; spifmc = spi_controller_get_devdata(mem->spi->controller); mutex_lock(&spifmc->lock); + ret = sg2044_spifmc_set_speed(spifmc, op->max_freq ? + min(op->max_freq, mem->spi->max_speed_hz) : + mem->spi->max_speed_hz); + if (ret) + goto out_unlock; + if (op->addr.nbytes == 0) - sg2044_spifmc_trans_reg(spifmc, op); + ret = sg2044_spifmc_trans_reg(spifmc, op); else - sg2044_spifmc_trans(spifmc, op); + ret = sg2044_spifmc_trans(spifmc, op); +out_unlock: mutex_unlock(&spifmc->lock); - return 0; + return ret; } static const struct spi_controller_mem_ops sg2044_spifmc_mem_ops = { .exec_op = sg2044_spifmc_exec_op, }; +static const struct spi_controller_mem_caps sg2044_spifmc_mem_caps = { + .per_op_freq = true, +}; + static void sg2044_spifmc_init(struct sg2044_spifmc *spifmc) { u32 tran_csr; @@ -447,6 +482,10 @@ static int sg2044_spifmc_probe(struct platform_device *pdev) if (IS_ERR(spifmc->clk)) return dev_err_probe(dev, PTR_ERR(spifmc->clk), "Cannot get and enable AHB clock\n"); + ctrl->max_speed_hz = clk_get_rate(spifmc->clk) / 2; + if (!ctrl->max_speed_hz) + return dev_err_probe(dev, -EINVAL, "Invalid AHB clock rate\n"); + spifmc->dev = &pdev->dev; spifmc->ctrl = ctrl; @@ -458,6 +497,7 @@ static int sg2044_spifmc_probe(struct platform_device *pdev) ctrl->bits_per_word_mask = SPI_BPW_MASK(8); ctrl->auto_runtime_pm = false; ctrl->mem_ops = &sg2044_spifmc_mem_ops; + ctrl->mem_caps = &sg2044_spifmc_mem_caps; ctrl->mode_bits = SPI_RX_DUAL | SPI_TX_DUAL | SPI_RX_QUAD | SPI_TX_QUAD; ret = devm_mutex_init(dev, &spifmc->lock); diff --git a/drivers/tee/optee/ffa_abi.c b/drivers/tee/optee/ffa_abi.c index 633715b98625cd..d027fe7ce86fd7 100644 --- a/drivers/tee/optee/ffa_abi.c +++ b/drivers/tee/optee/ffa_abi.c @@ -198,7 +198,8 @@ static int to_msg_param_ffa_mem(struct optee_msg_param *mp, if (shm) { u64 shm_offs = p->u.memref.shm_offs; - mp->u.fmem.internal_offs = shm->offset; + mp->u.fmem.internal_offs = tee_shm_get_page_offset(shm) & + (FFA_PAGE_SIZE - 1); mp->u.fmem.offs_low = shm_offs; mp->u.fmem.offs_high = shm_offs >> 32; @@ -284,14 +285,26 @@ static int optee_ffa_shm_register(struct tee_context *ctx, struct tee_shm *shm, .nattrs = 1, }; struct sg_table sgt; + size_t ffa_offs; int rc; + if (!num_pages) + return -EINVAL; + rc = optee_check_mem_type(start, num_pages); if (rc) return rc; - rc = sg_alloc_table_from_pages(&sgt, pages, num_pages, 0, - num_pages * PAGE_SIZE, GFP_KERNEL); + /* + * Start the FF-A descriptor at the 4 KiB page containing the shared + * buffer, skipping unused leading 4 KiB pages when PAGE_SIZE is + * larger. Same approach as optee_fill_pages_list() in the SMC ABI. + * This leaves only the offset into that 4 KiB page for internal_offs. + */ + ffa_offs = round_down(tee_shm_get_page_offset(shm), FFA_PAGE_SIZE); + rc = sg_alloc_table_from_pages(&sgt, pages, num_pages, ffa_offs, + num_pages * PAGE_SIZE - ffa_offs, + GFP_KERNEL); if (rc) return rc; args.sg = sgt.sgl; @@ -458,7 +471,8 @@ static void handle_ffa_rpc_func_cmd_shm_alloc(struct tee_context *ctx, .attr = OPTEE_MSG_ATTR_TYPE_FMEM_OUTPUT, .u.fmem.size = tee_shm_get_size(shm), .u.fmem.global_id = shm->sec_world_id, - .u.fmem.internal_offs = shm->offset, + .u.fmem.internal_offs = tee_shm_get_page_offset(shm) & + (FFA_PAGE_SIZE - 1), }; arg->ret = TEEC_SUCCESS; @@ -1123,14 +1137,6 @@ static int optee_ffa_probe(struct ffa_device *ffa_dev) optee_set_dev_group(optee); - rc = tee_device_register(optee->teedev); - if (rc) - goto err_unreg_supp_teedev; - - rc = tee_device_register(optee->supp_teedev); - if (rc) - goto err_unreg_supp_teedev; - rc = rhashtable_init(&optee->ffa.global_ids, &shm_rhash_params); if (rc) goto err_unreg_supp_teedev; @@ -1159,6 +1165,14 @@ static int optee_ffa_probe(struct ffa_device *ffa_dev) if (optee_ffa_protmem_pool_init(optee, sec_caps)) pr_info("Protected memory service not available\n"); + rc = tee_device_register(optee->teedev); + if (rc) + goto err_unregister_devices; + + rc = tee_device_register(optee->supp_teedev); + if (rc) + goto err_unregister_devices; + rc = optee_enumerate_devices(PTA_CMD_GET_DEVICES); if (rc) goto err_unregister_devices; diff --git a/drivers/tee/optee/optee_msg.h b/drivers/tee/optee/optee_msg.h index 7d9b12e71c0354..6c3043f8da33c6 100644 --- a/drivers/tee/optee/optee_msg.h +++ b/drivers/tee/optee/optee_msg.h @@ -136,8 +136,8 @@ struct optee_msg_param_rmem { * struct optee_msg_param_fmem - FF-A memory reference parameter * @offs_low: lower bits of offset into shared memory reference * @offs_high: higher bits of offset into shared memory reference - * @internal_offs: internal offset into the first page of shared memory - * reference + * @internal_offs: offset into the first 4 KiB page of the FF-A shared + * memory region * @size: size of the buffer * @global_id: global identifier of the shared memory */ diff --git a/drivers/tee/optee/smc_abi.c b/drivers/tee/optee/smc_abi.c index b8a2bdac3208f9..51624443359bfb 100644 --- a/drivers/tee/optee/smc_abi.c +++ b/drivers/tee/optee/smc_abi.c @@ -1849,14 +1849,6 @@ static int optee_probe(struct platform_device *pdev) optee_set_dev_group(optee); - rc = tee_device_register(optee->teedev); - if (rc) - goto err_unreg_supp_teedev; - - rc = tee_device_register(optee->supp_teedev); - if (rc) - goto err_unreg_supp_teedev; - optee_cq_init(&optee->call_queue, thread_count); optee_supp_init(&optee->supp); optee->smc.memremaped_shm = memremaped_shm; @@ -1916,6 +1908,14 @@ static int optee_probe(struct platform_device *pdev) if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM) pr_info("dynamic shared memory is enabled\n"); + rc = tee_device_register(optee->teedev); + if (rc) + goto err_disable_shm_cache; + + rc = tee_device_register(optee->supp_teedev); + if (rc) + goto err_disable_shm_cache; + rc = optee_enumerate_devices(PTA_CMD_GET_DEVICES); if (rc) goto err_disable_shm_cache; @@ -1942,7 +1942,6 @@ static int optee_probe(struct platform_device *pdev) optee_shm_arg_cache_uninit(optee); optee_supp_uninit(&optee->supp); mutex_destroy(&optee->call_queue.mutex); -err_unreg_supp_teedev: tee_device_unregister(optee->supp_teedev); err_unreg_teedev: tee_device_unregister(optee->teedev); diff --git a/drivers/tee/tee_shm.c b/drivers/tee/tee_shm.c index 6742b3579c86d6..daa4af1e089e59 100644 --- a/drivers/tee/tee_shm.c +++ b/drivers/tee/tee_shm.c @@ -343,6 +343,10 @@ int tee_dyn_shm_alloc_helper(struct tee_shm *shm, size_t size, size_t align, unsigned int i; int rc = 0; + /* get_order(0) is undefined and exceeds MAX_PAGE_ORDER. */ + if (!nr_pages) + return -EINVAL; + /* * Ignore alignment since this is already going to be page aligned * and there's no need for any larger alignment. diff --git a/drivers/thunderbolt/apple-dpin-state.c b/drivers/thunderbolt/apple-dpin-state.c index b07d65ad531a7c..18817e784822c0 100644 --- a/drivers/thunderbolt/apple-dpin-state.c +++ b/drivers/thunderbolt/apple-dpin-state.c @@ -28,6 +28,8 @@ const struct apple_dpin_policy apple_dpin_m2 = { const struct apple_dpin_policy apple_dpin_m3 = { .flow = APPLE_DPIN_CHANGED, + .capacity_retry = true, + .defer_new_bringup = true, .host_policy = TB_HOST_DP_NOTIFY, }; diff --git a/drivers/thunderbolt/apple-dpin-test.c b/drivers/thunderbolt/apple-dpin-test.c index 46f23b72fb0e04..c22da168bd8bc9 100644 --- a/drivers/thunderbolt/apple-dpin-test.c +++ b/drivers/thunderbolt/apple-dpin-test.c @@ -192,7 +192,7 @@ static void run_trace(struct kunit *test, const struct apple_dpin_policy *profil } } -static void apple_dpin_m1_capacity_trace(struct kunit *test) +static void apple_dpin_capacity_trace(struct kunit *test) { const struct dpin_trace trace[] = { { APPLE_DPIN_UP, false, 0, APPLE_DPIN_QUEUE, APPLE_DPIN_ACTIVATING }, @@ -217,6 +217,7 @@ static void apple_dpin_m1_capacity_trace(struct kunit *test) }; run_trace(test, &apple_dpin_m1, trace, ARRAY_SIZE(trace)); + run_trace(test, &apple_dpin_m3, trace, ARRAY_SIZE(trace)); } static void apple_dpin_t602x_rearm_trace(struct kunit *test) @@ -388,10 +389,11 @@ static void apple_dpin_all_policy_fields(struct kunit *test) TB_HOST_DP_HPD_ON_ACTIVATE | TB_HOST_DP_ACTIVE_BEFORE_DPRX | TB_HOST_DP_KEEP_DPRX_TIMEOUT | TB_HOST_DP_ADAPTER_QUIRKS | TB_HOST_DP_INITIAL_BW_GRANT }, - { APPLE_DPIN_CHANGED, false, false, false, false, TB_HOST_DP_NOTIFY }, + { APPLE_DPIN_CHANGED, true, false, false, true, TB_HOST_DP_NOTIFY }, }; unsigned int i, queue, display; + KUNIT_ASSERT_EQ(test, ARRAY_SIZE(actual), ARRAY_SIZE(expected)); for (i = 0; i < ARRAY_SIZE(actual); i++) { KUNIT_EXPECT_EQ(test, actual[i]->flow, expected[i].flow); KUNIT_EXPECT_EQ(test, actual[i]->capacity_retry, expected[i].capacity_retry); @@ -529,7 +531,7 @@ static void apple_dpin_sleep_handed_and_policy_scope(struct kunit *test) struct apple_dpin_state s = { .alive = true, .handed = true, .phase = APPLE_DPIN_HANDED }; const struct apple_dpin_policy * const unaffected[] = { - &apple_dpin_m2, &apple_dpin_m3, + &apple_dpin_m2, }; unsigned int i, actions; @@ -602,7 +604,8 @@ static void apple_dpin_sleep_dprx_retention(struct kunit *test) KUNIT_EXPECT_FALSE(test, apple_dpin_awaits_display(&s, &apple_dpin_m1)); s.handed = false; KUNIT_EXPECT_FALSE(test, apple_dpin_awaits_display(&s, &apple_dpin_m2)); - KUNIT_EXPECT_FALSE(test, apple_dpin_awaits_display(&s, &apple_dpin_m3)); + apple_dpin_step(&s, &apple_dpin_m3, APPLE_DPIN_UP, false, 0); + KUNIT_EXPECT_TRUE(test, apple_dpin_awaits_display(&s, &apple_dpin_m3)); } static void apple_dpin_sleep_complete_before_work(struct kunit *test) @@ -1086,7 +1089,75 @@ static void apple_dpin_provider_unavailable(struct kunit *test) KUNIT_EXPECT_EQ(test, fake.references, 0U); } +static void apple_dpin_m3_capacity_suspend(struct kunit *test) +{ + struct apple_dpin_state s = {}; + struct apple_dpin_tokens tokens = {}; + const struct apple_dpin_policy *p = &apple_dpin_m3; + + apple_dpin_step(&s, p, APPLE_DPIN_UP, false, 0); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_WORK, false, 0), + APPLE_DPIN_ATTACH); + apple_dpin_step(&s, p, APPLE_DPIN_ADMITTED, true, 0); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_RESULT, true, -EBUSY), + APPLE_DPIN_FIRST_WAIT | APPLE_DPIN_ARM_RETRY); + KUNIT_EXPECT_TRUE(test, apple_dpin_awaits_display(&s, p)); + apple_dpin_step(&s, p, APPLE_DPIN_PAUSE, true, 0); + KUNIT_EXPECT_TRUE(test, apple_dpin_admission_blocked(&s, p, false)); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_RETRY, true, 0), 0U); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_WORK, true, 0), 0U); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_RESUME, true, 0), + APPLE_DPIN_ARM_RETRY); + KUNIT_EXPECT_FALSE(test, apple_dpin_admission_blocked(&s, p, false)); + apple_dpin_step(&s, p, APPLE_DPIN_RETRY, true, 0); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_WORK, true, 0), + APPLE_DPIN_ATTACH); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_RESULT, true, 0), + APPLE_DPIN_RECOVERED | APPLE_DPIN_LOG_CONNECTED | APPLE_DPIN_AGAIN); + KUNIT_EXPECT_FALSE(test, apple_dpin_awaits_display(&s, p)); + /* A handed callback remains valid while new admission is paused. */ + apple_dpin_token_request(&tokens, 1, true); + apple_dpin_token_admit(&tokens, 1); + apple_dpin_token_complete(&tokens, 1); + apple_dpin_step(&s, p, APPLE_DPIN_PAUSE, true, 0); + KUNIT_EXPECT_TRUE(test, apple_dpin_token_access(&tokens, 1)); + KUNIT_EXPECT_FALSE(test, apple_dpin_awaits_display(&s, p)); + /* A replacement request revokes the old token during the same gate. */ + apple_dpin_token_request(&tokens, 2, true); + KUNIT_EXPECT_FALSE(test, apple_dpin_token_access(&tokens, 1)); + KUNIT_EXPECT_FALSE(test, apple_dpin_token_complete(&tokens, 1)); + apple_dpin_step(&s, p, APPLE_DPIN_DOWN, true, 0); + apple_dpin_step(&s, p, APPLE_DPIN_WORK, true, 0); + apple_dpin_step(&s, p, APPLE_DPIN_DROPPED, false, 0); + apple_dpin_step(&s, p, APPLE_DPIN_UP, false, 0); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_WORK, false, 0), 0U); + KUNIT_EXPECT_TRUE(test, apple_dpin_awaits_display(&s, p)); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_RESUME, false, 0), + APPLE_DPIN_QUEUE); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_WORK, false, 0), + APPLE_DPIN_ATTACH); + apple_dpin_token_admit(&tokens, 2); + KUNIT_EXPECT_TRUE(test, apple_dpin_token_access(&tokens, 2)); + /* Removal drains the request, then resets a gate with no complete(). */ + apple_dpin_step(&s, p, APPLE_DPIN_PAUSE, true, 0); + apple_dpin_step(&s, p, APPLE_DPIN_DOWN, true, 0); + apple_dpin_step(&s, p, APPLE_DPIN_WORK, true, 0); + apple_dpin_step(&s, p, APPLE_DPIN_DROPPED, false, 0); + apple_dpin_token_revoke(&tokens, 2); + apple_dpin_step(&s, p, APPLE_DPIN_END_PM_GATE, false, 0); + KUNIT_EXPECT_FALSE(test, s.paused); + KUNIT_EXPECT_FALSE(test, apple_dpin_token_access(&tokens, 2)); + apple_dpin_step(&s, p, APPLE_DPIN_UP, false, 0); + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_WORK, false, 0), + APPLE_DPIN_ATTACH); + /* An unsupported DP IN ends the wait instead of retaining DPRX forever. */ + KUNIT_EXPECT_EQ(test, apple_dpin_step(&s, p, APPLE_DPIN_RESULT, true, -EOPNOTSUPP), + APPLE_DPIN_CANCEL_RETRY | APPLE_DPIN_WARN); + KUNIT_EXPECT_FALSE(test, apple_dpin_awaits_display(&s, p)); +} + static struct kunit_case apple_dpin_cases[] = { + KUNIT_CASE(apple_dpin_m3_capacity_suspend), KUNIT_CASE(apple_dpin_provider_handed_lifetime), KUNIT_CASE(apple_dpin_provider_failed_retry), KUNIT_CASE(apple_dpin_provider_unavailable), @@ -1111,7 +1182,7 @@ static struct kunit_case apple_dpin_cases[] = { KUNIT_CASE(apple_dpin_sleep_handed_and_policy_scope), KUNIT_CASE(apple_dpin_sleep_complete_races_deferral), KUNIT_CASE(apple_dpin_exhaustive_equivalence), - KUNIT_CASE(apple_dpin_m1_capacity_trace), + KUNIT_CASE(apple_dpin_capacity_trace), KUNIT_CASE(apple_dpin_t602x_rearm_trace), KUNIT_CASE(apple_dpin_preserve_paused_event), KUNIT_CASE(apple_dpin_preserve_coalesced_replace), diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 6c7b38e3bf4223..c6625c5cbb5d3f 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -733,7 +733,7 @@ static void apple_dpin_retry_fn(struct work_struct *work) /* * Only where both the display allocator and the connection manager can hold - * a tunnel for a pipeline (M1-family hosts, see + * a tunnel for a pipeline (capacity-retry hosts, see * apple_nhi_dp_tunnel_awaits_display()) does a refused tunnel wait for one. */ static void apple_dpin_work_fn(struct work_struct *work) @@ -2218,8 +2218,8 @@ static void apple_nhi_remove(struct platform_device *pdev) * seconds. Not while devices suspend and resume: stop asking before any of * them suspends, let an attempt in flight finish (a wait for appledrm to * load gives way, see apple_dpin_connect()), and ask again once all of them - * have resumed. The tunnel keeps waiting meanwhile. New M1-family handoffs are - * deferred until complete, including after an aborted suspend. Established + * have resumed. The tunnel keeps waiting meanwhile. Suspend-gated handoffs + * are deferred until complete, including after an aborted suspend. Established * handed callbacks and synchronous tunnel teardown remain permitted. */ static void apple_dpin_pause_retries(struct apple_cio *acio) diff --git a/drivers/thunderbolt/tb.c b/drivers/thunderbolt/tb.c index b4e6e231b603ab..5a8233150bb626 100644 --- a/drivers/thunderbolt/tb.c +++ b/drivers/thunderbolt/tb.c @@ -62,6 +62,8 @@ MODULE_PARM_DESC(asym_threshold, * after cfg has been paused. * @remove_work: Work used to remove any unplugged routers after * runtime resume + * @dp_tunnel_work: Re-pair DP resources after retired DPRX work releases its paths + * @dp_tunnel_pending: A pairing request not yet serviced, retained across sleep * @groups: Bandwidth groups used in this domain. */ struct tb_cm { @@ -70,6 +72,8 @@ struct tb_cm { bool hotplug_active; bool stopping; struct delayed_work remove_work; + struct work_struct dp_tunnel_work; + bool dp_tunnel_pending; struct tb_bandwidth_group groups[MAX_GROUPS]; }; @@ -2260,6 +2264,57 @@ static void tb_switch_exit_redrive(struct tb_switch *sw) } } +/* + * A failed DPRX callback can retire the list's tunnel reference while its + * worker still owns the paths. Pairing here, on the same ordered domain + * queue, waits until that worker returns and drops its reference, releasing + * the old fixed HopIDs. Keep only the domain, never an unplugged port. + */ +static void tb_dp_tunnel_work(struct work_struct *work) +{ + struct tb_cm *tcm = container_of(work, struct tb_cm, dp_tunnel_work); + struct tb *tb = tcm_to_tb(tcm); + int ret; + + /* Domain removal drains this queue before unregistering the domain. */ + if (!READ_ONCE(tcm->hotplug_active)) + goto put_domain; + + /* Runtime resume can acquire the domain lock, so do it first. */ + ret = pm_runtime_resume_and_get(&tb->dev); + if (ret < 0) + goto put_domain; + + mutex_lock(&tb->lock); + if (tcm->hotplug_active && tb->root_switch) { + tcm->dp_tunnel_pending = false; + tb_tunnel_dp(tb); + } + mutex_unlock(&tb->lock); + + pm_runtime_mark_last_busy(&tb->dev); + pm_runtime_put_autosuspend(&tb->dev); +put_domain: + tb_domain_put(tb); +} + +static void tb_queue_dp_tunnels(struct tb *tb) +{ + struct tb_cm *tcm = tb_priv(tb); + + lockdep_assert_held(&tb->lock); + if (!tcm->hotplug_active) + return; + + /* An inactive worker leaves this set for thaw or resume. */ + tcm->dp_tunnel_pending = true; + + /* One reference for each queued execution; coalescing adds none. */ + tb_domain_get(tb); + if (!queue_work(tb->wq, &tcm->dp_tunnel_work)) + tb_domain_put(tb); +} + static void tb_dp_resource_unavailable(struct tb *tb, struct tb_port *port, const char *reason) { @@ -2288,7 +2343,7 @@ static void tb_dp_resource_unavailable(struct tb *tb, struct tb_port *port, * to create another tunnel. */ tb_recalc_estimated_bandwidth(tb); - tb_tunnel_dp(tb); + tb_queue_dp_tunnels(tb); } static void tb_dp_resource_available(struct tb *tb, struct tb_port *port) @@ -3064,6 +3119,7 @@ static void tb_stop(struct tb *tb) tb_switch_remove(tb->root_switch); tb->root_switch = NULL; tcm->hotplug_active = false; /* signal tb_handle_hotplug to quit */ + tcm->dp_tunnel_pending = false; } static void tb_deinit(struct tb *tb) @@ -3330,6 +3386,8 @@ static int tb_resume_noirq(struct tb *tb) tb_switch_enter_redrive(tb->root_switch); /* Allow tb_handle_hotplug to progress events */ tcm->hotplug_active = true; + if (tcm->dp_tunnel_pending) + tb_queue_dp_tunnels(tb); tb_dbg(tb, "resume finished\n"); return 0; @@ -3348,6 +3406,8 @@ static int tb_thaw_noirq(struct tb *tb) struct tb_cm *tcm = tb_priv(tb); tcm->hotplug_active = true; + if (tcm->dp_tunnel_pending) + tb_queue_dp_tunnels(tb); return 0; } @@ -3390,6 +3450,8 @@ static void tb_restore_dp_resources(struct tb_switch *sw) static void tb_complete(struct tb *tb) { + struct tb_cm *tcm = tb_priv(tb); + /* * Unregister unplugged XDomains and if there is a case where * another domain is swapped in place of unplugged XDomain we @@ -3404,11 +3466,16 @@ static void tb_complete(struct tb *tb) * Routers kept awake through system sleep send no plug events for * the DP resources released at suspend, so pair them up again here. */ + guard(mutex)(&tb->lock); if (tb->nhi->quirks & QUIRK_NO_SYSTEM_SLEEP) { - guard(mutex)(&tb->lock); tb_restore_dp_resources(tb->root_switch); + tcm->dp_tunnel_pending = false; tb_tunnel_dp(tb); } + + /* A noirq replay may have failed while runtime PM was disabled. */ + if (tcm->dp_tunnel_pending) + tb_queue_dp_tunnels(tb); } static int tb_runtime_suspend(struct tb *tb) @@ -3463,6 +3530,8 @@ static int tb_runtime_resume(struct tb *tb) tb_tunnel_activate(tunnel); tb_switch_enter_redrive(tb->root_switch); tcm->hotplug_active = true; + if (tcm->dp_tunnel_pending) + tb_queue_dp_tunnels(tb); mutex_unlock(&tb->lock); /* @@ -3581,6 +3650,7 @@ struct tb *tb_probe(struct tb_nhi *nhi) INIT_LIST_HEAD(&tcm->tunnel_list); INIT_LIST_HEAD(&tcm->dp_resources); INIT_DELAYED_WORK(&tcm->remove_work, tb_remove_work); + INIT_WORK(&tcm->dp_tunnel_work, tb_dp_tunnel_work); tb_init_bandwidth_groups(tcm); tb_dbg(tb, "using software connection manager\n"); diff --git a/drivers/ufs/core/ufs-mcq.c b/drivers/ufs/core/ufs-mcq.c index 13b60a2d06db6a..967b51ca57a0e6 100644 --- a/drivers/ufs/core/ufs-mcq.c +++ b/drivers/ufs/core/ufs-mcq.c @@ -306,20 +306,24 @@ static int ufshcd_mcq_get_tag(struct ufs_hba *hba, struct cq_entry *cqe) return div_u64(addr, ufshcd_get_ucd_size(hba)); } +static void ufshcd_mcq_compl_cqe(struct ufs_hba *hba, struct cq_entry *cqe) +{ + int tag = ufshcd_mcq_get_tag(hba, cqe); + + ufshcd_compl_one_cqe(hba, tag, cqe); + /* After processing the CQE, mark it as an empty (invalid) entry. */ + cqe->command_desc_base_addr = 0; +} + static void ufshcd_mcq_process_cqe(struct ufs_hba *hba, struct ufs_hw_queue *hwq) { struct cq_entry *cqe = ufshcd_mcq_cur_cqe(hwq); - if (cqe->command_desc_base_addr) { - int tag = ufshcd_mcq_get_tag(hba, cqe); - - ufshcd_compl_one_cqe(hba, tag, cqe); - /* After processed the cqe, mark it empty (invalid) entry */ - cqe->command_desc_base_addr = 0; - } else { + if (cqe->command_desc_base_addr) + ufshcd_mcq_compl_cqe(hba, cqe); + else dev_err(hba->dev, "Abnormal CQ entry!\n"); - } } /* @@ -327,7 +331,7 @@ static void ufshcd_mcq_process_cqe(struct ufs_hba *hba, * controller disabled (HCE = 0). Reading host controller registers, e.g. the * CQ tail pointer (CQTPy), may not be safe with the host controller disabled. * Hence, iterate over all completion queue entries. This won't result in - * double completions because ufshcd_mcq_process_cqe() clears a CQE after it + * double completions because ufshcd_mcq_compl_cqe() clears a CQE after it * has been processed. */ void ufshcd_mcq_compl_all_cqes_lock(struct ufs_hba *hba, @@ -338,13 +342,13 @@ void ufshcd_mcq_compl_all_cqes_lock(struct ufs_hba *hba, spin_lock_irqsave(&hwq->cq_lock, flags); while (entries > 0) { - ufshcd_mcq_process_cqe(hba, hwq); + struct cq_entry *cqe = ufshcd_mcq_cur_cqe(hwq); + + if (cqe->command_desc_base_addr) + ufshcd_mcq_compl_cqe(hba, cqe); ufshcd_mcq_inc_cq_head_slot(hwq); entries--; } - - ufshcd_mcq_update_cq_tail_slot(hwq); - hwq->cq_head_slot = hwq->cq_tail_slot; spin_unlock_irqrestore(&hwq->cq_lock, flags); } diff --git a/drivers/ufs/core/ufshcd.c b/drivers/ufs/core/ufshcd.c index bc33da89af2679..0a9366f21483fe 100644 --- a/drivers/ufs/core/ufshcd.c +++ b/drivers/ufs/core/ufshcd.c @@ -5975,8 +5975,6 @@ static bool ufshcd_mcq_force_compl_one(struct request *rq, void *priv) if (blk_mq_is_reserved_rq(rq) || !hwq) return true; - ufshcd_mcq_compl_all_cqes_lock(hba, hwq); - /* * For those cmds of which the cqes are not present in the cq, complete * them explicitly. @@ -5992,19 +5990,6 @@ static bool ufshcd_mcq_force_compl_one(struct request *rq, void *priv) return true; } -static bool ufshcd_mcq_compl_one(struct request *rq, void *priv) -{ - struct scsi_device *sdev = rq->q->queuedata; - struct Scsi_Host *shost = sdev->host; - struct ufs_hba *hba = shost_priv(shost); - struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq); - - if (!blk_mq_is_reserved_rq(rq) && hwq) - ufshcd_mcq_poll_cqe_lock(hba, hwq); - - return true; -} - /** * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is * invoked from the error handler context or ufshcd_host_reset_and_restore() @@ -6019,10 +6004,18 @@ static bool ufshcd_mcq_compl_one(struct request *rq, void *priv) static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba, bool force_compl) { - blk_mq_tagset_busy_iter(&hba->host->tag_set, - force_compl ? ufshcd_mcq_force_compl_one : - ufshcd_mcq_compl_one, - NULL); + int i; + + for (i = 0; i < hba->nr_hw_queues; i++) { + if (force_compl) + ufshcd_mcq_compl_all_cqes_lock(hba, &hba->uhq[i]); + else + ufshcd_mcq_poll_cqe_lock(hba, &hba->uhq[i]); + } + + if (force_compl) + blk_mq_tagset_busy_iter(&hba->host->tag_set, + ufshcd_mcq_force_compl_one, NULL); } /** @@ -9491,6 +9484,7 @@ static void ufshcd_async_scan(void *data, async_cookie_t cookie) ret = ufshcd_add_lus(hba); out: + ufshcd_release(hba); pm_runtime_put_sync(hba->dev); if (ret) @@ -11213,6 +11207,9 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) ufshcd_init_clk_gating(hba); + /* Released by ufshcd_async_scan(), or by out_release on failure. */ + ufshcd_hold(hba); + ufshcd_init_clk_scaling(hba); /* @@ -11233,7 +11230,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba); if (err) { dev_err(hba->dev, "request irq failed\n"); - goto out_disable; + goto out_release; } else { hba->is_irq_enabled = true; } @@ -11249,7 +11246,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) dev_err(hba->dev, "Host controller enable failed\n"); ufshcd_print_evt_hist(hba); ufshcd_print_host_state(hba); - goto out_disable; + goto out_release; } INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, ufshcd_rpm_dev_flush_recheck_work); @@ -11263,7 +11260,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) err = ufshcd_add_scsi_host(hba); if (err) - goto out_disable; + goto out_release; /* Hold auto suspend until async scan completes */ pm_runtime_get_sync(dev); @@ -11283,7 +11280,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) err = ufshcd_link_startup(hba); if (err) - goto out_disable; + goto out_release; if (hba->mcq_enabled) ufshcd_config_mcq(hba); @@ -11300,23 +11297,23 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) /* Verify device initialization by sending NOP OUT UPIU */ err = ufshcd_verify_dev_init(hba); if (err) - goto out_disable; + goto out_release; /* Initiate UFS initialization, and waiting until completion */ err = ufshcd_complete_dev_init(hba); if (err) - goto out_disable; + goto out_release; err = ufshcd_device_params_init(hba); if (err) - goto out_disable; + goto out_release; err = ufshcd_post_device_init(hba); initialized: ufshcd_process_probe_result(hba, probe_start, err); if (err) - goto out_disable; + goto out_release; ufs_sysfs_add_nodes(hba->dev); hba->dme_qos_sysfs_handle = sysfs_get_dirent(hba->dev->kobj.sd, @@ -11327,6 +11324,8 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) ufshcd_pm_qos_init(hba); return 0; +out_release: + ufshcd_release(hba); out_disable: hba->is_irq_enabled = false; ufshcd_hba_exit(hba); diff --git a/drivers/ufs/host/ufs-mediatek.c b/drivers/ufs/host/ufs-mediatek.c index 3991a51263a6d5..a2defbe3b7483c 100644 --- a/drivers/ufs/host/ufs-mediatek.c +++ b/drivers/ufs/host/ufs-mediatek.c @@ -509,6 +509,7 @@ static int ufs_mtk_mphy_power_on(struct ufs_hba *hba, bool on) struct ufs_mtk_host *host = ufshcd_get_variant(hba); struct phy *mphy = host->mphy; struct arm_smccc_res res; + int err; int ret = 0; if (!mphy || !(on ^ host->mphy_powered_on)) @@ -523,7 +524,18 @@ static int ufs_mtk_mphy_power_on(struct ufs_hba *hba, bool on) usleep_range(200, 210); ufs_mtk_va09_pwr_ctrl(res, 1); } - phy_power_on(mphy); + ret = phy_power_on(mphy); + if (ret) { + if (ufs_mtk_is_va09_supported(hba)) { + ufs_mtk_va09_pwr_ctrl(res, 0); + err = regulator_disable(host->reg_va09); + if (err) + dev_err(hba->dev, + "failed to unwind va09: %d\n", err); + } + dev_err(hba->dev, "failed to enable mphy: %d\n", ret); + return ret; + } } else { phy_power_off(mphy); if (ufs_mtk_is_va09_supported(hba)) { @@ -1295,7 +1307,9 @@ static int ufs_mtk_init(struct ufs_hba *hba) * * Enable phy clocks specifically here. */ - ufs_mtk_mphy_power_on(hba, true); + err = ufs_mtk_mphy_power_on(hba, true); + if (err) + goto out_variant_clear; if (ufs_mtk_is_rtff_mtcmos(hba)) { /* First Restore here, to avoid backup unexpected value */ diff --git a/drivers/usb/typec/mux.c b/drivers/usb/typec/mux.c index 3b72317e338ef6..1df58b4f9012ef 100644 --- a/drivers/usb/typec/mux.c +++ b/drivers/usb/typec/mux.c @@ -83,7 +83,7 @@ static void *typec_switch_match(const struct fwnode_handle *fwnode, */ struct typec_switch *fwnode_typec_switch_get(struct fwnode_handle *fwnode) { - struct typec_switch_dev *sw_devs[TYPEC_MUX_MAX_DEVS]; + struct typec_switch_dev *sw_devs[TYPEC_MUX_MAX_DEVS] = {}; struct typec_switch *sw; int count; int err; @@ -433,7 +433,7 @@ static void *typec_mux_match(const struct fwnode_handle *fwnode, */ struct typec_mux *fwnode_typec_mux_get(struct fwnode_handle *fwnode) { - struct typec_mux_dev *mux_devs[TYPEC_MUX_MAX_DEVS]; + struct typec_mux_dev *mux_devs[TYPEC_MUX_MAX_DEVS] = {}; struct typec_mux *mux; int count; int err; diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index 7fe0a63d690a35..579b82e27b5acb 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -9622,7 +9622,6 @@ int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode, struct completion sync_reads; unsigned long i = 0; struct btrfs_bio *bbio; - int ret; /* * Fast path for synchronous reads which completes in this call, io_uring @@ -9669,10 +9668,10 @@ int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode, if (uring_ctx) { if (refcount_dec_and_test(&priv->pending_refs)) { - ret = blk_status_to_errno(READ_ONCE(priv->status)); - btrfs_uring_read_extent_endio(uring_ctx, ret); + int error = blk_status_to_errno(READ_ONCE(priv->status)); + + btrfs_uring_read_extent_endio(uring_ctx, error); kfree(priv); - return ret; } return -EIOCBQUEUED; diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c index a537036303a476..833052306964b1 100644 --- a/fs/btrfs/ioctl.c +++ b/fs/btrfs/ioctl.c @@ -4559,7 +4559,7 @@ static void btrfs_uring_read_finished(struct io_tw_req tw_req, io_tw_token_t tw) size_t page_offset; ssize_t ret; - /* The inode lock has already been acquired in btrfs_uring_read_extent. */ + /* The inode lock has already been acquired in btrfs_encoded_read(). */ btrfs_lockdep_inode_acquire(inode, i_rwsem); if (priv->err) { @@ -4625,7 +4625,6 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter, struct iovec *iov, struct io_uring_cmd *cmd) { struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp)); - struct extent_io_tree *io_tree = &inode->io_tree; struct page **pages = NULL; struct btrfs_uring_priv *priv = NULL; unsigned long nr_pages; @@ -4681,8 +4680,6 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter, return -EIOCBQUEUED; out_fail: - btrfs_unlock_extent(io_tree, start, lockend, &cached_state); - btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED); kfree(priv); for (int i = 0; i < nr_pages; i++) { if (pages[i]) @@ -4795,7 +4792,7 @@ static int btrfs_uring_encoded_read(struct io_uring_cmd *cmd, unsigned int issue ret = btrfs_encoded_read(&kiocb, &data->iter, &data->args, &cached_state, &disk_bytenr, &disk_io_size); if (ret == -EAGAIN) - goto out_acct; + goto out_free; if (ret < 0 && ret != -EIOCBQUEUED) goto out_free; @@ -4823,8 +4820,10 @@ static int btrfs_uring_encoded_read(struct io_uring_cmd *cmd, unsigned int issue cached_state, disk_bytenr, disk_io_size, count, data->args.compression, data->iov, cmd); - - goto out_acct; + if (ret == -EIOCBQUEUED) + goto out_acct; + btrfs_unlock_extent(io_tree, start, lockend, &cached_state); + btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED); } out_free: @@ -4835,8 +4834,10 @@ static int btrfs_uring_encoded_read(struct io_uring_cmd *cmd, unsigned int issue add_rchar(current, ret); inc_syscr(current); - if (ret != -EIOCBQUEUED && ret != -EAGAIN) + if (ret != -EIOCBQUEUED) { kfree(data); + bc->data = NULL; + } return ret; } @@ -4865,6 +4866,11 @@ static int btrfs_uring_encoded_write(struct io_uring_cmd *cmd, unsigned int issu goto out_acct; } + if (issue_flags & IO_URING_F_NONBLOCK) { + ret = -EAGAIN; + goto out_acct; + } + if (!data) { data = kzalloc_obj(*data, GFP_NOFS); if (!data) { @@ -4933,11 +4939,6 @@ static int btrfs_uring_encoded_write(struct io_uring_cmd *cmd, unsigned int issu } } - if (issue_flags & IO_URING_F_NONBLOCK) { - ret = -EAGAIN; - goto out_acct; - } - pos = data->args.offset; ret = rw_verify_area(WRITE, file, &pos, data->args.len); if (ret < 0) @@ -4963,8 +4964,8 @@ static int btrfs_uring_encoded_write(struct io_uring_cmd *cmd, unsigned int issu add_wchar(current, ret); inc_syscw(current); - if (ret != -EAGAIN) - kfree(data); + kfree(data); + bc->data = NULL; return ret; } diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c index 3b3f04521369d7..9db8f8b6d3d544 100644 --- a/fs/btrfs/scrub.c +++ b/fs/btrfs/scrub.c @@ -550,8 +550,10 @@ static int scrub_print_warning_inode(u64 inum, u64 offset, u64 num_bytes, } ret = paths_from_inode(inum, ipath); - if (ret < 0) + if (ret < 0) { + btrfs_put_root(local_root); goto err; + } /* * we deliberately ignore the bit ipath might have been too small to diff --git a/fs/btrfs/xattr.c b/fs/btrfs/xattr.c index ab55d10bd71fdb..cb001a211f5575 100644 --- a/fs/btrfs/xattr.c +++ b/fs/btrfs/xattr.c @@ -161,6 +161,7 @@ int btrfs_setxattr(struct btrfs_trans_handle *trans, struct inode *inode, const u16 old_data_len = btrfs_dir_data_len(leaf, di); const u32 item_size = btrfs_item_size(leaf, slot); const u32 data_size = sizeof(*di) + name_len + size; + unsigned long name_ptr; unsigned long data_ptr; char *ptr; @@ -189,8 +190,16 @@ int btrfs_setxattr(struct btrfs_trans_handle *trans, struct inode *inode, ptr = btrfs_item_ptr(leaf, slot, char); ptr += btrfs_item_size(leaf, slot) - data_size; di = (struct btrfs_dir_item *)ptr; + memzero_extent_buffer(leaf, (unsigned long)ptr + + offsetof(struct btrfs_dir_item, location), + sizeof(struct btrfs_disk_key)); + btrfs_set_dir_flags(leaf, di, BTRFS_FT_XATTR); + btrfs_set_dir_transid(leaf, di, trans->transid); + btrfs_set_dir_name_len(leaf, di, name_len); btrfs_set_dir_data_len(leaf, di, size); + name_ptr = (unsigned long)(di + 1); data_ptr = ((unsigned long)(di + 1)) + name_len; + write_extent_buffer(leaf, name, name_ptr, name_len); write_extent_buffer(leaf, value, data_ptr, size); } else { /* @@ -320,10 +329,8 @@ ssize_t btrfs_listxattr(struct dentry *dentry, char *buffer, size_t size) if (!size) goto next; - if (!buffer || (name_len + 1) > size_left) { - iter_ret = -ERANGE; - break; - } + if (!buffer || (name_len + 1) > size_left) + return -ERANGE; read_extent_buffer(leaf, buffer, name_ptr, name_len); buffer[name_len] = '\0'; diff --git a/fs/dcache.c b/fs/dcache.c index 073c2ce2d44486..d6fbb4fa7dbc50 100644 --- a/fs/dcache.c +++ b/fs/dcache.c @@ -1583,6 +1583,8 @@ EXPORT_SYMBOL(path_has_submounts); * * Only one of d_invalidate() and d_set_mounted() must succeed. For * this reason take rename_lock and d_lock on dentry and ancestors. + * Likewise for dont_mount() which marks a dentry that is being removed + * under d_lock. */ int d_set_mounted(struct dentry *dentry) { @@ -1599,7 +1601,7 @@ int d_set_mounted(struct dentry *dentry) spin_unlock(&p->d_lock); } spin_lock(&dentry->d_lock); - if (!d_unlinked(dentry)) { + if (!d_unlinked(dentry) && !cant_mount(dentry)) { ret = -EBUSY; if (!d_mountpoint(dentry)) { dentry->d_flags |= DCACHE_MOUNTED; diff --git a/fs/fcntl.c b/fs/fcntl.c index c158f082f1da4f..9b71bc9d71d159 100644 --- a/fs/fcntl.c +++ b/fs/fcntl.c @@ -372,6 +372,9 @@ static long fcntl_set_rw_hint(struct file *file, unsigned long arg) u64 __user *argp = (u64 __user *)arg; u64 hint; + /* nothing is ever written to it */ + if (IS_IMMUTABLE(inode)) + return -EPERM; if (!inode_owner_or_capable(file_mnt_idmap(file), inode)) return -EPERM; diff --git a/fs/fs_context.c b/fs/fs_context.c index 23ad66cd94e1f9..a50584df97bea7 100644 --- a/fs/fs_context.c +++ b/fs/fs_context.c @@ -315,6 +315,10 @@ struct fs_context *fs_context_for_reconfigure(struct dentry *dentry, unsigned int sb_flags, unsigned int sb_flags_mask) { + /* kernel-internal superblocks are nobody's to reconfigure */ + if (dentry->d_sb->s_flags & SB_NOUSER) + return ERR_PTR(-EINVAL); + return alloc_fs_context(dentry->d_sb->s_type, dentry, sb_flags, sb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE); } diff --git a/fs/inode.c b/fs/inode.c index c6b08e8c5f6277..efa801f3eb1106 100644 --- a/fs/inode.c +++ b/fs/inode.c @@ -763,21 +763,18 @@ void clear_inode(struct inode *inode) fsverity_cleanup_inode(inode); /* - * We have to cycle the i_pages lock here because reclaim can be in the - * process of removing the last page (in __filemap_remove_folio()) - * and we must not free the mapping under it. + * We have to cycle the i_pages lock here because reclaim + * can be in the process of removing the last page (in + * __filemap_remove_folio()) and we must not free the mapping + * under it. We also remove nodes which are empty; these + * can occur in two different ways. The first is that radix + * tree expansion can fail partway and the second is that THP + * collapse_file() can allocate some temporary nodes and not + * clean them up. */ - xa_lock_irq(&inode->i_data.i_pages); + xa_destroy(&inode->i_data.i_pages); + BUG_ON(inode->i_data.nrpages); - /* - * Almost always, mapping_empty(&inode->i_data) here; but there are - * two known and long-standing ways in which nodes may get left behind - * (when deep radix-tree node allocation failed partway; or when THP - * collapse_file() failed). Until those two known cases are cleaned up, - * or a cleanup function is called here, do not BUG_ON(!mapping_empty), - * nor even WARN_ON(!mapping_empty). - */ - xa_unlock_irq(&inode->i_data.i_pages); BUG_ON(!(inode_state_read_once(inode) & I_FREEING)); BUG_ON(inode_state_read_once(inode) & I_CLEAR); BUG_ON(!list_empty(&inode->i_wb_list)); diff --git a/fs/mount.h b/fs/mount.h index 94fcc306d21e7d..2223fb141499fe 100644 --- a/fs/mount.h +++ b/fs/mount.h @@ -33,7 +33,8 @@ struct mnt_namespace { } __randomize_layout; struct mnt_pcp { - int mnt_count; + unsigned int mnt_gets; + unsigned int mnt_puts; int mnt_writers; }; @@ -233,6 +234,9 @@ static inline struct mnt_namespace *to_mnt_ns(struct ns_common *ns) #ifdef CONFIG_FSNOTIFY static inline void mnt_notify_add(struct mount *m) { + /* queued already under this namespace_sem hold */ + if (!list_empty(&m->to_notify)) + return; /* Optimize the case where there are no watches */ if ((m->mnt_ns && m->mnt_ns->n_fsnotify_marks) || (m->prev_ns && m->prev_ns->n_fsnotify_marks)) diff --git a/fs/namei.c b/fs/namei.c index 19ce43c9a6e662..27e0637bfdda2a 100644 --- a/fs/namei.c +++ b/fs/namei.c @@ -2086,6 +2086,33 @@ static noinline const char *pick_link(struct nameidata *nd, struct path *link, return NULL; } +/* + * Be careful in case the dentry is unlinked or renamed. Any mounts + * stacked on top of it are going away. We need to make sure that we + * don't reveal the underyling dentry during refwalk. In rcuwalk we + * catch this via d_seq and another lookup for the name. Give the same + * guarantee in refwalk. + */ +static bool unlink_may_reveal(struct nameidata *nd, int flags, + struct path *path, struct dentry *dentry) +{ + /* ".." and LOOKUP_DOWN may land on an unhashed directory */ + if (flags & WALK_NOFOLLOW) + return false; + if (nd->flags & LOOKUP_REVAL) + return false; + /* We crossed onto a mount and the name led us here while it still existed */ + if (path->mnt != nd->path.mnt) + return false; + /* only a name on its way out is flagged */ + if (likely(!cant_mount(dentry))) + return false; + if (!d_unlinked(dentry)) + return false; + dput(no_free_ptr(path->dentry)); + return true; +} + /* * Do we need to follow links? We _really_ want to be able * to do this check without having to look at inode->i_op, @@ -2115,6 +2142,8 @@ static noinline const char *step_into_slowpath(struct nameidata *nd, int flags, if (unlikely(!inode)) return ERR_PTR(-ENOENT); } else { + if (unlikely(unlink_may_reveal(nd, flags, &path, dentry))) + return ERR_PTR(-ESTALE); dput(nd->path.dentry); if (nd->path.mnt != path.mnt) mntput(nd->path.mnt); diff --git a/fs/namespace.c b/fs/namespace.c index 3d5cd5bf3b0537..ec93bdac9e7894 100644 --- a/fs/namespace.c +++ b/fs/namespace.c @@ -130,7 +130,6 @@ static void mnt_ns_release(struct mnt_namespace *ns) { /* keep alive for {list,stat}mount() */ if (ns && refcount_dec_and_test(&ns->passive)) { - fsnotify_mntns_delete(ns); put_user_ns(ns->user_ns); kfree(ns); } @@ -249,16 +248,24 @@ void mnt_release_group_id(struct mount *mnt) mnt->mnt_group_id = 0; } -/* - * vfsmount lock must be held for read - */ -static inline void mnt_add_count(struct mount *mnt, int n) +static inline void mnt_inc_count(struct mount *mnt) { #ifdef CONFIG_SMP - this_cpu_add(mnt->mnt_pcp->mnt_count, n); + this_cpu_inc(mnt->mnt_pcp->mnt_gets); #else preempt_disable(); - mnt->mnt_count += n; + mnt->mnt_count++; + preempt_enable(); +#endif +} + +static inline void mnt_dec_count(struct mount *mnt) +{ +#ifdef CONFIG_SMP + this_cpu_inc(mnt->mnt_pcp->mnt_puts); +#else + preempt_disable(); + mnt->mnt_count--; preempt_enable(); #endif } @@ -269,14 +276,17 @@ static inline void mnt_add_count(struct mount *mnt, int n) int mnt_get_count(struct mount *mnt) { #ifdef CONFIG_SMP - int count = 0; + unsigned int gets = 0, puts = 0; int cpu; - for_each_possible_cpu(cpu) { - count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count; - } + /* puts first, so a put counted here has its get counted below */ + for_each_possible_cpu(cpu) + puts += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_puts; + smp_mb(); /* pairs with the smp_wmb() in mntput_no_expire() */ + for_each_possible_cpu(cpu) + gets += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_gets; - return count; + return gets - puts; #else return mnt->mnt_count; #endif @@ -305,7 +315,7 @@ static struct mount *alloc_vfsmnt(const char *name) if (!mnt->mnt_pcp) goto out_free_devname; - this_cpu_add(mnt->mnt_pcp->mnt_count, 1); + this_cpu_inc(mnt->mnt_pcp->mnt_gets); #else mnt->mnt_count = 1; mnt->mnt_writers = 0; @@ -322,6 +332,9 @@ static struct mount *alloc_vfsmnt(const char *name) INIT_HLIST_NODE(&mnt->mnt_mp_list); INIT_HLIST_HEAD(&mnt->mnt_stuck_children); INIT_HLIST_NODE(&mnt->mnt_ns_visible); +#ifdef CONFIG_FSNOTIFY + INIT_LIST_HEAD(&mnt->to_notify); +#endif RB_CLEAR_NODE(&mnt->mnt_node); mnt->mnt.mnt_idmap = &nop_mnt_idmap; } @@ -746,13 +759,13 @@ int __legitimize_mnt(struct vfsmount *bastard, unsigned seq) if (bastard == NULL) return 0; mnt = real_mount(bastard); - mnt_add_count(mnt, 1); - smp_mb(); // see mntput_no_expire() and do_umount() + mnt_inc_count(mnt); + smp_mb(); /* see mntput_no_expire_slowpath() and do_umount() */ if (likely(!read_seqretry(&mount_lock, seq))) return 0; lock_mount_hash(); if (unlikely(bastard->mnt_flags & (MNT_SYNC_UMOUNT | MNT_DOOMED))) { - mnt_add_count(mnt, -1); + mnt_dec_count(mnt); unlock_mount_hash(); return 1; } @@ -1058,7 +1071,10 @@ static void attach_mnt(struct mount *mnt, struct mount *parent, void mnt_change_mountpoint(struct mount *parent, struct mountpoint *mp, struct mount *mnt) { struct mountpoint *old_mp = mnt->mnt_mp; + struct mount *old_parent = mnt->mnt_parent; + if (old_parent->overmount == mnt) + old_parent->overmount = NULL; list_del_init(&mnt->mnt_child); hlist_del_init(&mnt->mnt_mp_list); hlist_del_init_rcu(&mnt->mnt_hash); @@ -1254,6 +1270,7 @@ static struct mount *clone_mnt(struct mount *old, struct dentry *root, mnt->mnt.mnt_flags = READ_ONCE(old->mnt.mnt_flags) & ~MNT_INTERNAL_FLAGS; + mnt->mnt_t_flags = old->mnt_t_flags & T_UNBINDABLE; if (flag & (CL_SLAVE | CL_PRIVATE)) mnt->mnt_group_id = 0; /* not a peer of original */ @@ -1347,7 +1364,7 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt) * mount_lock, we'll see their refcount increment here. */ smp_mb(); - mnt_add_count(mnt, -1); + mnt_dec_count(mnt); count = mnt_get_count(mnt); if (count != 0) { WARN_ON(count < 0); @@ -1404,7 +1421,8 @@ static void mntput_no_expire(struct mount *mnt) * non-NULL under rcu_read_lock(), the reference * we are dropping is not the final one. */ - mnt_add_count(mnt, -1); + smp_wmb(); /* pairs with the smp_mb() in mnt_get_count() */ + mnt_dec_count(mnt); rcu_read_unlock(); return; } @@ -1426,7 +1444,7 @@ EXPORT_SYMBOL(mntput); struct vfsmount *mntget(struct vfsmount *mnt) { if (mnt) - mnt_add_count(real_mount(mnt), 1); + mnt_inc_count(real_mount(mnt)); return mnt; } EXPORT_SYMBOL(mntget); @@ -1783,6 +1801,8 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how) /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { + /* A mount is unmounted once. */ + VFS_WARN_ON_ONCE(p->mnt.mnt_flags & MNT_UMOUNT); p->mnt.mnt_flags |= MNT_UMOUNT; if (mnt_ns_attached(p)) move_from_ns(p); @@ -1976,6 +1996,9 @@ static int do_umount(struct mount *mnt, int flags) * detach_mounts allows lazily unmounting those mounts instead of * leaking them. * + * The dentry is unhashed before the mounts go so that no lookup finds + * what they covered. The caller removes it for good afterwards. + * * The caller may hold dentry->d_inode->i_rwsem. */ void __detach_mounts(struct dentry *dentry) @@ -1989,6 +2012,8 @@ void __detach_mounts(struct dentry *dentry) if (!lookup_mountpoint(dentry, &mp)) return; + /* the name goes first, what covered it goes second */ + d_drop(dentry); event++; while (mp.node.next) { mnt = hlist_entry(mp.node.next, struct mount, mnt_mp_list); @@ -2345,6 +2370,18 @@ bool has_locked_children(struct mount *mnt, struct dentry *dentry) return __has_locked_children(mnt, dentry); } +/* locks: namespace_shared && pinned(mnt) || mount_locked_reader */ +static bool __has_children(struct mount *mnt, struct dentry *dentry) +{ + struct mount *child; + + list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) { + if (is_subdir(child->mnt_mountpoint, dentry)) + return true; + } + return false; +} + /* * Check that there aren't references to earlier/same mount namespaces in the * specified subtree. Such references can act as pins for mount namespaces @@ -2564,11 +2601,11 @@ enum mnt_tree_flags_t { static int attach_recursive_mnt(struct mount *source_mnt, const struct pinned_mountpoint *dest) { - struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns; struct mount *dest_mnt = dest->parent; struct mountpoint *dest_mp = dest->mp; HLIST_HEAD(tree_list); struct mnt_namespace *ns = dest_mnt->mnt_ns; + struct user_namespace *user_ns = ns->user_ns; struct pinned_mountpoint root = {}; struct mountpoint *shorter = NULL; struct mount *child, *p; @@ -2577,13 +2614,31 @@ static int attach_recursive_mnt(struct mount *source_mnt, int err = 0; bool moving = mnt_has_parent(source_mnt); + /* + * A caller in an unprivileged mount namespaces may trigger an + * automount and propagate locked mounts into privileged mount + * namespaces. Take ownership from the target mount namespace. + * It's equivalent for everything but the automount case. + * + * Detached trees in anonymous mount namespaces by be handed + * over via SCM_RIGHTS or inherited in other ways on purpose + * the attaching task's mount namespace is authoritative, not + * the creator of the detached tree. + */ + if (is_anon_ns(ns)) + user_ns = current->nsproxy->mnt_ns->user_ns; + else + user_ns = ns->user_ns; + /* * Preallocate a mountpoint in case the new mounts need to be * mounted beneath mounts on the same mountpoint. */ - for (top = source_mnt; unlikely(top->overmount); top = top->overmount) { + for (top = source_mnt; ; top = top->overmount) { if (!shorter && is_mnt_ns_file(top->mnt.mnt_root)) shorter = top->mnt_mp; + if (likely(!top->overmount)) + break; } err = get_mountpoint(top->mnt.mnt_root, &root); if (err) @@ -2654,15 +2709,17 @@ static int attach_recursive_mnt(struct mount *source_mnt, /* * If @q was locked it was meant to hide * whatever was under it. Let @child take over - * that job and lock it, then we can unlock @q. - * That'll allow another namespace to shed @q - * and reveal @child. Clearly, that mounter - * consented to this by not severing the mount - * relationship. Otherwise, what's the point. + * that job and lock it. If @child is the mount + * the caller placed we can then unlock @q: + * nothing another namespace does removes it + * again. A propagated copy goes away when the + * mounter of the original unmounts it, so @q + * keeps its lock. */ if (IS_MNT_LOCKED(q)) { child->mnt.mnt_flags |= MNT_LOCKED; - q->mnt.mnt_flags &= ~MNT_LOCKED; + if (child == source_mnt) + q->mnt.mnt_flags &= ~MNT_LOCKED; } mnt_change_mountpoint(r, mp, q); } @@ -2986,6 +3043,13 @@ static struct mount *__do_loopback(const struct path *old_path, if (!may_copy_tree(old_path)) return ERR_PTR(-EINVAL); + /* a pseudo dentry is freed without an RCU delay, no walk may find it */ + if (old_path->dentry->d_flags & DCACHE_NORCU) + return ERR_PTR(-EINVAL); + + if (recurse && !old->mnt_ns) + return ERR_PTR(-EINVAL); + if (!recurse && __has_locked_children(old, old_path->dentry)) return ERR_PTR(-EINVAL); @@ -3025,7 +3089,11 @@ static int do_loopback(const struct path *path, const char *old_name, if (IS_ERR(mnt)) return PTR_ERR(mnt); - err = graft_tree(mnt, &mp); + /* the copy may carry mount namespace files from below the source */ + if (recurse && !check_for_nsfs_mounts(mnt)) + err = -EINVAL; + else + err = graft_tree(mnt, &mp); if (err) { lock_mount_hash(); umount_tree(mnt, UMOUNT_SYNC); @@ -3107,12 +3175,18 @@ static struct mnt_namespace *create_new_namespace(struct path *path, struct mount *mnt; unsigned int copy_flags = 0; bool locked = false, recurse = flags & MOUNT_COPY_RECURSIVE; + bool foreign = user_ns != ns->user_ns; if (unlikely(!d_can_lookup(path->dentry))) return ERR_PTR(-ENOTDIR); - if (user_ns != ns->user_ns) - copy_flags |= CL_SLAVE; + /* + * Without privileges over the mount namespace the copy is made from + * nothing mounted below @path may be left out. It would reveal what + * it covers. That's what unshare() gives such a caller as well. + */ + if (foreign) + copy_flags |= CL_SLAVE | CL_COPY_UNBINDABLE; new_ns = alloc_mnt_ns(user_ns, false); if (IS_ERR(new_ns)) @@ -3146,10 +3220,14 @@ static struct mnt_namespace *create_new_namespace(struct path *path, /* * We don't emulate unshare()ing a mount namespace. We stick to * the restrictions of creating detached bind-mounts. It has a - * lot saner and simpler semantics. + * lot saner and simpler semantics. A caller without privileges + * over the mount namespace can't leave out any child though. */ if (flags & MOUNT_COPY_NEW) mnt = clone_mnt(real_mount(path->mnt), path->dentry, copy_flags); + else if (foreign && !recurse && + __has_children(real_mount(path->mnt), path->dentry)) + mnt = ERR_PTR(-EINVAL); else mnt = __do_loopback(path, recurse, copy_flags); scoped_guard(mount_writer) { @@ -3166,7 +3244,7 @@ static struct mnt_namespace *create_new_namespace(struct path *path, * of the real rootfs we created. */ attach_mnt(mnt, new_ns_root, mp.mp); - if (user_ns != ns->user_ns) + if (foreign) lock_mnt_tree(new_ns_root); } @@ -3464,7 +3542,7 @@ static int do_set_group(const struct path *from_path, const struct path *to_path return -EINVAL; /* Setting sharing groups is only allowed on private mounts */ - if (IS_MNT_SHARED(to) || IS_MNT_SLAVE(to)) + if (IS_MNT_SHARED(to) || IS_MNT_SLAVE(to) || IS_MNT_UNBINDABLE(to)) return -EINVAL; /* From should not be private */ @@ -3736,7 +3814,7 @@ static int do_add_mount(struct mount *newmnt, const struct pinned_mountpoint *mp if (!(mnt_flags & MNT_SHRINKABLE)) return -EINVAL; /* ... and for those we'd better have mountpoint still alive */ - if (!parent->mnt_ns) + if (!is_mounted(&parent->mnt)) return -EINVAL; } @@ -3946,6 +4024,8 @@ void mark_mounts_for_expiry(struct list_head *mounts) list_for_each_entry_safe(mnt, next, mounts, mnt_expire) { if (!is_mounted(&mnt->mnt)) continue; + /* lock_mnt_tree() leaves expirable mounts alone */ + VFS_WARN_ON_ONCE(IS_MNT_LOCKED(mnt)); if (!xchg(&mnt->mnt_expiry_mark, 1) || propagate_mount_busy(mnt, 1)) continue; @@ -3953,6 +4033,11 @@ void mark_mounts_for_expiry(struct list_head *mounts) } while (!list_empty(&graveyard)) { mnt = list_first_entry(&graveyard, struct mount, mnt_expire); + /* an earlier umount_tree() may have moved a busy mount here */ + if (propagate_mount_busy(mnt, 1)) { + list_move(&mnt->mnt_expire, mounts); + continue; + } touch_mnt_namespace(mnt->mnt_ns); umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC); } @@ -3960,17 +4045,38 @@ void mark_mounts_for_expiry(struct list_head *mounts) EXPORT_SYMBOL_GPL(mark_mounts_for_expiry); +/* + * Unmount @mnt if it's a shrinkable mount without children that nobody uses. + * + * mount_lock must be held for write + */ +static bool shrink_submount(struct mount *mnt) +{ + /* not the kernel's to remove either */ + if (IS_MNT_LOCKED(mnt) || propagate_mount_busy(mnt, 1)) + return false; + touch_mnt_namespace(mnt->mnt_ns); + umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC); + return true; +} + /* * Ripoff of 'select_parent()' * - * search the list of submounts for a given mountpoint, and move any - * shrinkable submounts to the 'graveyard' list. + * unmount the shrinkable submounts of @parent that aren't busy, children + * before their parent, and say whether anything went + * + * The cursor into the children of @this_parent survives the umount of a + * child mount without child mounts. The mounts that get umounted together with + * it are located under receiving mounts of @this_parent and never under + * @this_parent itself. The one exception is @this_parent getting unmounted + * then the walk starts over. */ -static int select_submounts(struct mount *parent, struct list_head *graveyard) +static bool __shrink_submounts(struct mount *parent) { struct mount *this_parent = parent; struct list_head *next; - int found = 0; + bool shrunk = false; repeat: next = this_parent->mnt_mounts.next; @@ -3989,42 +4095,45 @@ static int select_submounts(struct mount *parent, struct list_head *graveyard) this_parent = mnt; goto repeat; } - - if (!propagate_mount_busy(mnt, 1)) { - list_move_tail(&mnt->mnt_expire, graveyard); - found++; - } + if (!shrink_submount(mnt)) + continue; + shrunk = true; + if (unlikely(this_parent->mnt.mnt_flags & MNT_UMOUNT)) + return true; } /* * All done at this level ... ascend and resume the search */ if (this_parent != parent) { - next = this_parent->mnt_child.next; - this_parent = this_parent->mnt_parent; + struct mount *mnt = this_parent; + + next = mnt->mnt_child.next; + this_parent = mnt->mnt_parent; + /* its children are gone, maybe it can go as well */ + if (shrink_submount(mnt)) { + shrunk = true; + if (unlikely(this_parent->mnt.mnt_flags & MNT_UMOUNT)) + return true; + } goto resume; } - return found; + return shrunk; } /* - * process a list of expirable mountpoints with the intent of discarding any - * submounts of a specific parent mountpoint + * unmount the shrinkable submounts of @mnt that aren't busy + * + * The busy check and the umount of a mount are adjacent. An umount can + * still empty or move a mount in a part of the tree that was walked + * already, so walk again until nothing goes. * * mount_lock must be held for write */ static void shrink_submounts(struct mount *mnt) { - LIST_HEAD(graveyard); - struct mount *m; - - /* extract submounts of 'mountpoint' from the expiration list */ - while (select_submounts(mnt, &graveyard)) { - while (!list_empty(&graveyard)) { - m = list_first_entry(&graveyard, struct mount, - mnt_expire); - touch_mnt_namespace(m->mnt_ns); - umount_tree(m, UMOUNT_PROPAGATE|UMOUNT_SYNC); - } + for (;;) { + if (!__shrink_submounts(mnt)) + break; } } @@ -4189,6 +4298,8 @@ static void free_mnt_ns(struct mnt_namespace *ns) if (!is_anon_ns(ns)) ns_common_free(ns); dec_mnt_namespaces(ns->ucounts); + /* the last active reference is gone, no mark can show up anymore */ + fsnotify_mntns_delete(ns); mnt_ns_tree_remove(ns); } @@ -4690,14 +4801,15 @@ int path_pivot_root(struct path *new, struct path *old) new_mnt = real_mount(new->mnt); root_mnt = real_mount(root.mnt); + /* only a mounted mount has a parent that namespace_sem pins */ + if (!check_mnt(root_mnt) || !check_mnt(new_mnt)) + return -EINVAL; ex_parent = new_mnt->mnt_parent; root_parent = root_mnt->mnt_parent; if (IS_MNT_SHARED(old_mnt) || IS_MNT_SHARED(ex_parent) || IS_MNT_SHARED(root_parent)) return -EINVAL; - if (!check_mnt(root_mnt) || !check_mnt(new_mnt)) - return -EINVAL; if (new_mnt->mnt.mnt_flags & MNT_LOCKED) return -EINVAL; if (d_unlinked(new->dentry)) @@ -4948,6 +5060,11 @@ static int do_mount_setattr(const struct path *path, struct mount_kattr *kattr) * propagation. */ namespace_lock(); + /* invent_group_ids() walks the tree, only walk a mounted one */ + if (!anon_ns_root(mnt) && !check_mnt(mnt)) { + namespace_unlock(); + return -EINVAL; + } if (kattr->propagation == MS_SHARED) { err = invent_group_ids(mnt, kattr->kflags & MOUNT_KATTR_RECURSE); if (err) { @@ -4960,6 +5077,7 @@ static int do_mount_setattr(const struct path *path, struct mount_kattr *kattr) err = -EINVAL; lock_mount_hash(); + /* Checked under namespace_sem already if the propagation changes. */ if (!anon_ns_root(mnt) && !check_mnt(mnt)) goto out; @@ -5312,15 +5430,25 @@ static void statmount_sb_basic(struct kstatmount *s) s->sm.sb_flags = sb->s_flags & (SB_RDONLY|SB_SYNCHRONOUS|SB_DIRSYNC|SB_LAZYTIME); } +static void statmount_mnt_parent(struct kstatmount *s, const struct mount *m) +{ + s->sm.mnt_parent_id = m->mnt_parent->mnt_id_unique; + s->sm.mnt_parent_id_old = m->mnt_parent->mnt_id; +} + static void statmount_mnt_basic(struct kstatmount *s) { struct mount *m = real_mount(s->mnt); s->sm.mask |= STATMOUNT_MNT_BASIC; s->sm.mnt_id = m->mnt_id_unique; - s->sm.mnt_parent_id = m->mnt_parent->mnt_id_unique; s->sm.mnt_id_old = m->mnt_id; - s->sm.mnt_parent_id_old = m->mnt_parent->mnt_id; + /* An unmounted mount is cut loose from its parent under mount_lock alone. */ + if (likely(is_mounted(s->mnt))) + statmount_mnt_parent(s, m); + else + scoped_guard(mount_locked_reader) + statmount_mnt_parent(s, m); s->sm.mnt_attr = mnt_to_attr_flags(&m->mnt); s->sm.mnt_propagation = mnt_to_propagation_flags(m); s->sm.mnt_peer_group = m->mnt_group_id; diff --git a/fs/nullfs.c b/fs/nullfs.c index fdbd3e5d3d71f5..20d3aa627a47de 100644 --- a/fs/nullfs.c +++ b/fs/nullfs.c @@ -30,8 +30,8 @@ static int nullfs_fs_fill_super(struct super_block *s, struct fs_context *fc) make_empty_dir_inode(inode); simple_inode_init_ts(inode); inode->i_ino = 1; - /* ... and immutable. */ - inode->i_flags |= S_IMMUTABLE; + /* ... and immutable, reading it leaves no trace either. */ + inode->i_flags |= S_IMMUTABLE | S_NOATIME; s->s_root = d_make_root(inode); if (!s->s_root) diff --git a/fs/pnode.c b/fs/pnode.c index 5d91c3e58d2a35..2cd667958efe1b 100644 --- a/fs/pnode.c +++ b/fs/pnode.c @@ -410,19 +410,99 @@ bool propagation_would_overmount(const struct mount *from, return false; } +/* Does @m receive propagation from @parent? */ +static bool receives_from(struct mount *m, struct mount *parent) +{ + if (m == parent) + return false; + for (; m; m = m->mnt_master) + if (m == parent || peers(m, parent)) + return true; + return false; +} + +/* + * Does @m receive propagation from the victim's parent as well? If so, then + * the mount at the victim's mountpoint inside of @m is a umount candidate as + * well. So it's the next candidate in the chain. Otherwise the chain ends at + * @m. + */ +static struct mount *next_candidate(struct mount *m, struct mount *victim) +{ + if (!receives_from(m, victim->mnt_parent)) + return NULL; + return __lookup_mnt(&m->mnt, victim->mnt_mountpoint); +} + +/* + * Would propagate_umount() pull out a mount of the chain of candidates that + * starts at @c, and does that mount have references beyond its own? + * + * This mirrors how trim_one(), trim_ancestors() and handle_locked() handle a + * synchronous umount: + * + * - single victim + * - without children + * - with MNT_LOCKED already cleared on every candidate by propagate_mount_unlock() + * + * A copy of the victim gets unmounted when each of its children is + * the next candidate in the chain or its overmount, unless the next + * unmount candidate is not its overmount and some unmount candidate further + * down has a child outside the chain. Keep this in sync with + * Documentation/filesystems/propagate_umount.txt. + */ +static bool chain_busy(struct mount *c, struct mount *victim) +{ + struct mount *m, *n, *next, *deepest = NULL; + bool above; + + /* the deepest candidate with a child outside the chain */ + for (m = c; m; m = next) { + next = next_candidate(m, victim); + list_for_each_entry(n, &m->mnt_mounts, mnt_child) { + if (n != next && n != victim) { + deepest = m; + break; + } + } + } + + above = deepest != NULL; /* @deepest is at or below @m */ + for (m = c; m; m = next) { + bool goes = true; + + next = next_candidate(m, victim); + list_for_each_entry(n, &m->mnt_mounts, mnt_child) { + if (n != next && n != m->overmount && n != victim) { + goes = false; + break; + } + } + if (goes && next && next != m->overmount && above && m != deepest) + goes = false; + if (m == deepest) + above = false; + if (goes && do_refcount_check(m, 1)) + return true; + } + return false; +} + /* * check if the mount 'mnt' can be unmounted successfully. * @mnt: the mount to be checked for unmount * NOTE: unmounting 'mnt' would naturally propagate to all * other mounts its parent propagates to. - * Check if any of these mounts that **do not have submounts** - * have more references than 'refcnt'. If so return busy. + * Check if any of the mounts that propagate_umount() would pull out + * along with it have more references than their own. If so return busy. * * vfsmount lock must be held for write */ int propagate_mount_busy(struct mount *mnt, int refcnt) { struct mount *parent = mnt->mnt_parent; + struct dentry *mp = mnt->mnt_mountpoint; + struct mount *m; /* * quickly check if the current mount can be unmounted. @@ -435,24 +515,16 @@ int propagate_mount_busy(struct mount *mnt, int refcnt) if (mnt == parent) return 0; - for (struct mount *m = propagation_next(parent, parent); m; - m = propagation_next(m, parent)) { - struct list_head *head; - struct mount *child = __lookup_mnt(&m->mnt, mnt->mnt_mountpoint); + /* the candidates are the mounts at @mp below the receivers */ + for (m = propagation_next(parent, parent); m; + m = propagation_next(m, parent)) { + struct mount *c = __lookup_mnt(&m->mnt, mp); - if (!child) + /* each chain once, from its top: skip receivers that are candidates */ + if (!c || (mnt_has_parent(m) && m->mnt_mountpoint == mp && + receives_from(m->mnt_parent, parent))) continue; - - head = &child->mnt_mounts; - if (!list_empty(head)) { - /* - * a mount that covers child completely wouldn't prevent - * it being pulled out; any other would. - */ - if (!list_is_singular(head) || !child->overmount) - continue; - } - if (do_refcount_check(child, 1)) + if (chain_busy(c, mnt)) return 1; } return 0; diff --git a/fs/verity/fsverity_private.h b/fs/verity/fsverity_private.h index 881d46f25e087c..6f85f63861aaa1 100644 --- a/fs/verity/fsverity_private.h +++ b/fs/verity/fsverity_private.h @@ -11,6 +11,7 @@ #define pr_fmt(fmt) "fs-verity: " fmt #include +#include #include /* @@ -76,7 +77,19 @@ struct merkle_tree_params { struct fsverity_info { struct rhash_head rhash_head; struct merkle_tree_params tree_params; - u8 root_hash[FS_VERITY_MAX_DIGEST_SIZE]; + union { + u8 root_hash[FS_VERITY_MAX_DIGEST_SIZE]; + + /* + * Used for final freeing of the struct, in which case root_hash + * is no longer needed. Specifically, the only fields needed + * besides the rcu_head are those needed by fsverity_free_info() + * itself, and those that can be accessed by fsverity_get_info() + * (rhash_head and inode) during the RCU-protected rhashtable + * chain search trying to find another inode's fsverity_info. + */ + struct rcu_head rcu_head; + }; u8 file_digest[FS_VERITY_MAX_DIGEST_SIZE]; struct inode *inode; unsigned long *hash_block_verified; diff --git a/fs/verity/open.c b/fs/verity/open.c index d0c56a7faa3bb1..52c8cd0149216e 100644 --- a/fs/verity/open.c +++ b/fs/verity/open.c @@ -399,11 +399,22 @@ void fsverity_free_info(struct fsverity_info *vi) kmem_cache_free(fsverity_info_cachep, vi); } +static void fsverity_free_info_rcu(struct rcu_head *head) +{ + fsverity_free_info(container_of(head, struct fsverity_info, rcu_head)); +} + void fsverity_remove_info(struct fsverity_info *vi) { rhashtable_remove_fast(&fsverity_info_hash, &vi->rhash_head, fsverity_info_hash_params); - fsverity_free_info(vi); + /* + * The freeing must be RCU-delayed because __fsverity_get_info() for a + * *different* inode's fsverity_info in the same rhashtable hash chain + * can still be accessing *this* fsverity_info's rhash_head and inode + * fields as part of the RCU-protected hash chain search. + */ + call_rcu(&vi->rcu_head, fsverity_free_info_rcu); } void fsverity_cleanup_inode(struct inode *inode) diff --git a/fs/xfs/libxfs/xfs_exchmaps.c b/fs/xfs/libxfs/xfs_exchmaps.c index 49eda8d0994dee..37595f579b635a 100644 --- a/fs/xfs/libxfs/xfs_exchmaps.c +++ b/fs/xfs/libxfs/xfs_exchmaps.c @@ -49,7 +49,7 @@ struct xfs_exchmaps_adjacent { .right2 = { .br_startblock = HOLESTARTBLOCK }, \ } -/* Information to reset reflink flag / CoW fork state after an exchange. */ +/* Information to reset CoW fork state after an exchange. */ /* * If the reflink flag is set on either inode, make sure it has an incore CoW @@ -127,9 +127,7 @@ xmi_has_more_exchange_work(const struct xfs_exchmaps_intent *xmi) static inline bool xmi_has_postop_work(const struct xfs_exchmaps_intent *xmi) { - return xmi->xmi_flags & (XFS_EXCHMAPS_CLEAR_INO1_REFLINK | - XFS_EXCHMAPS_CLEAR_INO2_REFLINK | - __XFS_EXCHMAPS_INO2_SHORTFORM); + return xmi->xmi_flags & __XFS_EXCHMAPS_INO2_SHORTFORM; } /* Check all mappings to make sure we can actually exchange them. */ @@ -525,18 +523,6 @@ xfs_exchmaps_link_to_sf( return error; } -/* Clear the reflink flag after an exchange. */ -static inline void -xfs_exchmaps_clear_reflink( - struct xfs_trans *tp, - struct xfs_inode *ip) -{ - trace_xfs_reflink_unset_inode_flag(ip); - - ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK; - xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); -} - /* Finish whatever work might come after an exchange operation. */ static int xfs_exchmaps_do_postop_work( @@ -557,16 +543,6 @@ xfs_exchmaps_do_postop_work( return error; } - if (xmi->xmi_flags & XFS_EXCHMAPS_CLEAR_INO1_REFLINK) { - xfs_exchmaps_clear_reflink(tp, xmi->xmi_ip1); - xmi->xmi_flags &= ~XFS_EXCHMAPS_CLEAR_INO1_REFLINK; - } - - if (xmi->xmi_flags & XFS_EXCHMAPS_CLEAR_INO2_REFLINK) { - xfs_exchmaps_clear_reflink(tp, xmi->xmi_ip2); - xmi->xmi_flags &= ~XFS_EXCHMAPS_CLEAR_INO2_REFLINK; - } - return 0; } @@ -948,56 +924,14 @@ xfs_exchmaps_intent_destroy_cache(void) } /* - * Decide if we will exchange the reflink flags between the two files after the - * exchange. The only time we want to do this is if we're exchanging all - * mappings under EOF and the inode reflink flags have different states. + * Allocate and initialize a new incore intent item from a request. */ -static inline bool -xmi_can_exchange_reflink_flags( - const struct xfs_exchmaps_req *req, - unsigned int reflink_state) -{ - struct xfs_mount *mp = req->ip1->i_mount; - - /* - * The INO1_WRITTEN optimization can skip exchanging hole and - * unwritten mappings, which means we cannot guarantee that all - * shared extents actually moved to the other file. Clearing the - * reflink flag of an inode that still holds shared extents breaks - * the CoW write path, so refuse to exchange the flags in that case. - */ - if (req->flags & XFS_EXCHMAPS_INO1_WRITTEN) - return false; - - /* - * The INO1_WRITTEN optimization can skip exchanging hole and - * unwritten mappings, which means we cannot guarantee that all - * shared extents actually moved to the other file. Clearing the - * reflink flag of an inode that still holds shared extents breaks - * the CoW write path, so refuse to exchange the flags in that case. - */ - if (req->flags & XFS_EXCHMAPS_INO1_WRITTEN) - return false; - - if (hweight32(reflink_state) != 1) - return false; - if (req->startoff1 != 0 || req->startoff2 != 0) - return false; - if (req->blockcount != XFS_B_TO_FSB(mp, req->ip1->i_disk_size)) - return false; - if (req->blockcount != XFS_B_TO_FSB(mp, req->ip2->i_disk_size)) - return false; - return true; -} - - -/* Allocate and initialize a new incore intent item from a request. */ struct xfs_exchmaps_intent * xfs_exchmaps_init_intent( const struct xfs_exchmaps_req *req) { struct xfs_exchmaps_intent *xmi; - unsigned int rs = 0; + struct xfs_mount *mp = req->ip1->i_mount; xmi = kmem_cache_zalloc(xfs_exchmaps_intent_cache, GFP_NOFS | __GFP_NOFAIL); @@ -1015,27 +949,18 @@ xfs_exchmaps_init_intent( return xmi; } - if (req->flags & XFS_EXCHMAPS_SET_SIZES) { - xmi->xmi_flags |= XFS_EXCHMAPS_SET_SIZES; - xmi->xmi_isize1 = req->ip2->i_disk_size; - xmi->xmi_isize2 = req->ip1->i_disk_size; - } - - /* Record the state of each inode's reflink flag before the op. */ - if (xfs_is_reflink_inode(req->ip1)) - rs |= 1; - if (xfs_is_reflink_inode(req->ip2)) - rs |= 2; - /* - * Figure out if we're clearing the reflink flags (which effectively - * exchanges them) after the operation. + * If the caller wanted, set each file's size to that file's exchange + * offset + length exchanged from the other file because the ranges in + * each file might be different lengths. */ - if (xmi_can_exchange_reflink_flags(req, rs)) { - if (rs & 1) - xmi->xmi_flags |= XFS_EXCHMAPS_CLEAR_INO1_REFLINK; - if (rs & 2) - xmi->xmi_flags |= XFS_EXCHMAPS_CLEAR_INO2_REFLINK; + if (req->flags & XFS_EXCHMAPS_SET_SIZES) { + loff_t off1 = XFS_FSB_TO_B(mp, xmi->xmi_startoff1); + loff_t off2 = XFS_FSB_TO_B(mp, xmi->xmi_startoff2); + + xmi->xmi_flags |= XFS_EXCHMAPS_SET_SIZES; + xmi->xmi_isize1 = off1 + (req->ip2->i_disk_size - off2); + xmi->xmi_isize2 = off2 + (req->ip1->i_disk_size - off1); } if (S_ISDIR(VFS_I(xmi->xmi_ip2)->i_mode) || diff --git a/fs/xfs/libxfs/xfs_log_format.h b/fs/xfs/libxfs/xfs_log_format.h index a4e1b3eb425cda..6e620380d5dc86 100644 --- a/fs/xfs/libxfs/xfs_log_format.h +++ b/fs/xfs/libxfs/xfs_log_format.h @@ -927,10 +927,8 @@ struct xfs_xmi_log_format { */ #define XFS_EXCHMAPS_INO1_WRITTEN (1ULL << 2) -/* Clear the reflink flag from inode1 after the operation. */ +/* No longer set, but older intents may carry them; keep them valid. */ #define XFS_EXCHMAPS_CLEAR_INO1_REFLINK (1ULL << 3) - -/* Clear the reflink flag from inode2 after the operation. */ #define XFS_EXCHMAPS_CLEAR_INO2_REFLINK (1ULL << 4) #define XFS_EXCHMAPS_LOGGED_FLAGS (XFS_EXCHMAPS_ATTR_FORK | \ diff --git a/fs/xfs/xfs_bmap_util.c b/fs/xfs/xfs_bmap_util.c index c88b9ade7389dd..2ea6507678050a 100644 --- a/fs/xfs/xfs_bmap_util.c +++ b/fs/xfs/xfs_bmap_util.c @@ -1514,7 +1514,6 @@ xfs_swap_extents( struct xfs_bstat *sbp = &sxp->sx_stat; int src_log_flags, target_log_flags; int error = 0; - uint64_t f; int resblks = 0; unsigned int flags = 0; struct timespec64 ctime, mtime; @@ -1670,14 +1669,12 @@ xfs_swap_extents( if (error) goto out_trans_cancel; - /* Do we have to swap reflink flags? */ - if ((ip->i_diflags2 & XFS_DIFLAG2_REFLINK) ^ - (tip->i_diflags2 & XFS_DIFLAG2_REFLINK)) { - f = ip->i_diflags2 & XFS_DIFLAG2_REFLINK; - ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK; - ip->i_diflags2 |= tip->i_diflags2 & XFS_DIFLAG2_REFLINK; - tip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK; - tip->i_diflags2 |= f & XFS_DIFLAG2_REFLINK; + /* Either inode may now own shared blocks; flag both, with CoW forks. */ + if ((ip->i_diflags2 | tip->i_diflags2) & XFS_DIFLAG2_REFLINK) { + ip->i_diflags2 |= XFS_DIFLAG2_REFLINK; + tip->i_diflags2 |= XFS_DIFLAG2_REFLINK; + xfs_ifork_init_cow(ip); + xfs_ifork_init_cow(tip); } /* Swap the cow forks. */ diff --git a/fs/xfs/xfs_exchrange.c b/fs/xfs/xfs_exchrange.c index fafb4e3f065c75..935b561dfd3c5c 100644 --- a/fs/xfs/xfs_exchrange.c +++ b/fs/xfs/xfs_exchrange.c @@ -290,17 +290,20 @@ xfs_exchrange_mappings( goto out_unlock; /* - * If the caller wanted us to exchange the contents of two complete - * files of unequal length, exchange the incore sizes now. This should - * be safe because we flushed both files' page caches, exchanged all - * the mappings, and updated the ondisk sizes. + * If the caller wanted, set each file's size to that file's exchange + * offset + length exchanged from the other file because the ranges in + * each file might be different lengths. This should be safe because + * we flushed both files' page caches, exchanged all the mappings, and + * updated the ondisk sizes. */ if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF) { - loff_t temp; + loff_t old_ip1_size = i_size_read(VFS_I(ip1)); + loff_t old_ip2_size = i_size_read(VFS_I(ip2)); - temp = i_size_read(VFS_I(ip2)); - i_size_write(VFS_I(ip2), i_size_read(VFS_I(ip1))); - i_size_write(VFS_I(ip1), temp); + i_size_write(VFS_I(ip2), fxr->file2_offset + + (old_ip1_size - fxr->file1_offset)); + i_size_write(VFS_I(ip1), fxr->file1_offset + + (old_ip2_size - fxr->file2_offset)); } out_unlock: @@ -445,6 +448,30 @@ xfs_exchange_range_checks( return blen == fxr->length ? 0 : -EINVAL; } +/* Flush all relevant dirty pagecache near the range to be exchanged. */ +static inline int +xfs_exchange_range_flush( + struct xfs_inode *ip, + const struct xfs_exchrange *fxr, + loff_t offset) +{ + /* + * If TO_EOF is set, the ondisk file size update logic depends on the + * ondisk file size matching the incore file size. Flush everything. + */ + if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF) + return filemap_write_and_wait(VFS_I(ip)->i_mapping); + + /* + * Because we're updating the ondisk mappings, flush all dirty data + * between the ondisk size and the exchange offset to reduce the chance + * of zeroed file contents in that gap after a crash. + */ + return filemap_write_and_wait_range(VFS_I(ip)->i_mapping, + min(offset, ip->i_disk_size), + offset + fxr->length - 1); +} + /* * Check that the two inodes are eligible for range exchanges, the ranges make * sense, and then flush all dirty data. Caller must ensure that the inodes @@ -470,15 +497,11 @@ xfs_exchange_range_prep( if (!same_inode) inode_dio_wait(inode2); - error = filemap_write_and_wait_range(inode1->i_mapping, - fxr->file1_offset, - fxr->file1_offset + fxr->length - 1); + error = xfs_exchange_range_flush(XFS_I(inode1), fxr, fxr->file1_offset); if (error) return error; - error = filemap_write_and_wait_range(inode2->i_mapping, - fxr->file2_offset, - fxr->file2_offset + fxr->length - 1); + error = xfs_exchange_range_flush(XFS_I(inode2), fxr, fxr->file2_offset); if (error) return error; diff --git a/include/linux/can/core.h b/include/linux/can/core.h index 3287232e3cad92..2de74c2b78b6c1 100644 --- a/include/linux/can/core.h +++ b/include/linux/can/core.h @@ -17,6 +17,7 @@ #include #include #include +#include #define DNAME(dev) ((dev) ? (dev)->name : "any") @@ -58,7 +59,7 @@ extern void can_rx_unregister(struct net *net, struct net_device *dev, void *data); extern int can_send(struct sk_buff *skb, int loop); -void can_set_skb_uid(struct sk_buff *skb); +void can_set_skb_uid(struct can_skb_ext *csx); void can_sock_destruct(struct sock *sk); #endif /* !_CAN_CORE_H */ diff --git a/include/linux/can/skb.h b/include/linux/can/skb.h index a70a0296707115..5d27843862fca4 100644 --- a/include/linux/can/skb.h +++ b/include/linux/can/skb.h @@ -43,8 +43,10 @@ static inline struct can_skb_ext *can_skb_ext_add(struct sk_buff *skb) struct can_skb_ext *csx = skb_ext_add(skb, SKB_EXT_CAN); /* skb_ext_add() returns uninitialized space */ - if (csx) + if (csx) { csx->can_gw_hops = 0; + csx->can_skb_uid = 0; + } return csx; } diff --git a/include/linux/io_uring_types.h b/include/linux/io_uring_types.h index c7a7a7a6889f8d..f83da0af60d1dd 100644 --- a/include/linux/io_uring_types.h +++ b/include/linux/io_uring_types.h @@ -316,6 +316,8 @@ enum { IO_RING_F_DRAIN_DISABLED = BIT(10), IO_RING_F_COMPAT = BIT(11), IO_RING_F_IOWQ_LIMITS_SET = BIT(12), + /* restrictions were inherited from the task that created the ring */ + IO_RING_F_RESTRICT_INHERITED = BIT(13), }; struct iou_ctx {}; diff --git a/include/linux/mount.h b/include/linux/mount.h index acfe7ef86a1b3f..b16ba5d456057a 100644 --- a/include/linux/mount.h +++ b/include/linux/mount.h @@ -52,7 +52,7 @@ enum mount_flags { MNT_ATIME_MASK = MNT_NOATIME | MNT_NODIRATIME | MNT_RELATIME, MNT_INTERNAL_FLAGS = MNT_INTERNAL | MNT_DOOMED | - MNT_SYNC_UMOUNT | MNT_LOCKED + MNT_SYNC_UMOUNT | MNT_LOCKED | MNT_UMOUNT }; struct vfsmount { diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h index 5a67648721c7d9..dc2447f5f09240 100644 --- a/include/linux/nsproxy.h +++ b/include/linux/nsproxy.h @@ -100,6 +100,7 @@ void exit_cred_namespaces(struct task_struct *tsk); void switch_task_namespaces(struct task_struct *tsk, struct nsproxy *new); int exec_task_namespaces(void); void deactivate_nsproxy(struct nsproxy *ns); +void nsproxy_free(struct nsproxy *ns); int unshare_nsproxy_namespaces(unsigned long, struct nsproxy **, struct cred *, struct fs_struct *); int __init nsproxy_cache_init(void); diff --git a/include/linux/nvme.h b/include/linux/nvme.h index 041f30931a908a..03ddd2c6d7fa7a 100644 --- a/include/linux/nvme.h +++ b/include/linux/nvme.h @@ -1266,8 +1266,8 @@ enum { NVME_ZRASF_ZONE_STATE_IMP_OPEN = 0x02, NVME_ZRASF_ZONE_STATE_EXP_OPEN = 0x03, NVME_ZRASF_ZONE_STATE_CLOSED = 0x04, - NVME_ZRASF_ZONE_STATE_READONLY = 0x05, - NVME_ZRASF_ZONE_STATE_FULL = 0x06, + NVME_ZRASF_ZONE_STATE_FULL = 0x05, + NVME_ZRASF_ZONE_STATE_READONLY = 0x06, NVME_ZRASF_ZONE_STATE_OFFLINE = 0x07, NVME_REPORT_ZONE_PARTIAL = 1, }; diff --git a/include/linux/power_supply.h b/include/linux/power_supply.h index 7a5e4c3242a01d..82215a75385010 100644 --- a/include/linux/power_supply.h +++ b/include/linux/power_supply.h @@ -221,6 +221,7 @@ enum power_supply_charge_behaviour { POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE, POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE_AWAKE, POWER_SUPPLY_CHARGE_BEHAVIOUR_FORCE_DISCHARGE, + POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO_DISCHARGE, }; enum power_supply_notifier_events { diff --git a/include/linux/sched/ext.h b/include/linux/sched/ext.h index 87e353f7e0112e..67a97429d8a6ce 100644 --- a/include/linux/sched/ext.h +++ b/include/linux/sched/ext.h @@ -198,6 +198,7 @@ struct sched_ext_entity { s32 sticky_cpu; s32 holding_cpu; s32 selected_cpu; + u32 ops_qseq; /* protected by rq lock */ struct task_struct *kf_tasks[2]; /* see SCX_CALL_OP_TASK() */ struct list_head runnable_node; /* rq->scx.runnable_list */ diff --git a/include/linux/soc/apple/display.h b/include/linux/soc/apple/display.h new file mode 100644 index 00000000000000..8978d95d40484f --- /dev/null +++ b/include/linux/soc/apple/display.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _LINUX_SOC_APPLE_DISPLAY_H_ +#define _LINUX_SOC_APPLE_DISPLAY_H_ + +struct device; + +/* Initial native display admission, before starting retained G15 firmware. */ +int apple_drm_t6030_link_device(struct device *consumer); + +#endif diff --git a/include/linux/soc/apple/dp-tunnel.h b/include/linux/soc/apple/dp-tunnel.h index 7bd546080f25be..540d48fe8e0dcb 100644 --- a/include/linux/soc/apple/dp-tunnel.h +++ b/include/linux/soc/apple/dp-tunnel.h @@ -44,6 +44,16 @@ int apple_dcp_tb_dp_tunnel(struct device_node *connector_np, unsigned int dpin, */ int apple_atc_dp_tunnel_rate(struct phy *phy, unsigned int dpin, u8 rate); +/* T6030's external DPTX port 0 sources feed DP IN0/1 through PCLK1/2. */ +static inline int apple_dp_tunnel_t6030_pclk(unsigned int source, unsigned int dpin) +{ + return dpin < 2 && (source == 0 || source == 2) ? (int)dpin : -EOPNOTSUPP; +} + +/* T6030: keep the source owning the pixel clock across rate changes and stop. */ +int apple_atc_dp_tunnel_rate_source(struct phy *phy, unsigned int source, + unsigned int dpin, u8 rate); + /* * ATC PHY: wake the DP clock path of a PHY in Thunderbolt/USB4 mode ahead of * apple_atc_dp_tunnel_rate(), before DCP is told about the display. @@ -94,6 +104,40 @@ static inline bool apple_dp_tunnel_mux_matches(struct device_node *dcp, return matches; } +/* T6030 boot trees without DPIN names use the same three-output crossbar. + * Explicit DPIN/USB4 names remain authoritative, including invalid wiring. */ +static inline bool apple_dp_tunnel_t6030_legacy_mux(struct device_node *dcp, + unsigned int port) +{ + struct of_phandle_args base; + char name[24]; + u32 source; + bool matches; + int index, i; + + if (!of_machine_is_compatible("apple,t6030") || port >= 4 || + of_property_read_u32_index(dcp, "apple,typec-mux-indices", port, &source) || + apple_dp_tunnel_t6030_pclk(source, 0) < 0) + return false; + for (i = 0; i < 2; i++) { + snprintf(name, sizeof(name), "typec%u-dpin%u", port, i); + if (of_property_match_string(dcp, "mux-control-names", name) >= 0) + return false; + } + snprintf(name, sizeof(name), "typec%u-usb4", port); + if (of_property_match_string(dcp, "mux-control-names", name) >= 0) + return false; + snprintf(name, sizeof(name), "typec%u", port); + index = of_property_match_string(dcp, "mux-control-names", name); + if (index < 0 || of_parse_phandle_with_args(dcp, "mux-controls", + "#mux-control-cells", index, &base)) + return false; + matches = base.args_count == 1 && base.args[0] == 0 && + of_device_is_compatible(base.np, "apple,t6020-display-crossbar"); + of_node_put(base.np); + return matches; +} + static inline bool apple_dp_tunnel_route_wired(struct device_node *route, unsigned int endpoints) { @@ -122,16 +166,18 @@ static inline bool apple_dp_tunnel_route_wired(struct device_node *route, } if (!named[0] && !named[1]) { snprintf(name, sizeof(name), "typec%u-usb4", index); - legacy = apple_dp_tunnel_mux_matches(dcp, name, base.np, 1); + legacy = apple_dp_tunnel_mux_matches(dcp, name, base.np, 1) || + apple_dp_tunnel_t6030_legacy_mux(dcp, index); } of_node_put(base.np); return wired && apple_dp_tunnel_wiring_dual(endpoints, named[0], named[1], legacy); } /* - * Physical DT wiring only: no DCP registration, firmware, status or board list. + * DT wiring only: no DCP registration, firmware or display status. * Two candidates alone (e.g. j314) are single-stream. Named DPIN0/1 controls, * or old-DTB typecN-usb4 cell 1, must share the DP-alt crossbar (cell 0). + * T6030 old trees may omit DPIN names on their three-output T602X crossbar. * Consumers qualify their SoC flow separately and never select these muxes. */ static inline bool apple_dp_tunnel_dual_stream(struct device_node *connector_np) diff --git a/include/linux/virtio_net.h b/include/linux/virtio_net.h index c381b916c1b54a..d6466f96cdd00c 100644 --- a/include/linux/virtio_net.h +++ b/include/linux/virtio_net.h @@ -111,48 +111,38 @@ static inline int __virtio_net_hdr_to_skb(struct sk_buff *skb, p_off = nh_min_len + thlen; if (!pskb_may_pull(skb, p_off)) return -EINVAL; - } else { + } else if (gso_type) { /* gso packets without NEEDS_CSUM do not set transport_offset. * probe and drop if does not match one of the above types. */ - if (gso_type && skb->network_header) { - struct flow_keys_basic keys; - - if (!skb->protocol) { - __be16 protocol = dev_parse_header_protocol(skb); - - if (!protocol) - virtio_net_hdr_set_proto(skb, hdr); - else if (!virtio_net_hdr_match_proto(protocol, - hdr_gso_type)) - return -EINVAL; - else - skb->protocol = protocol; - } + struct flow_keys_basic keys; + + if (!skb->protocol) { + skb->protocol = dev_parse_header_protocol(skb); + if (!skb->protocol) + virtio_net_hdr_set_proto(skb, hdr); + } retry: - if (!skb_flow_dissect_flow_keys_basic(NULL, skb, &keys, - NULL, 0, 0, 0, - 0)) { - /* UFO does not specify ipv4 or 6: try both */ - if (gso_type & SKB_GSO_UDP && - skb->protocol == htons(ETH_P_IP)) { - skb->protocol = htons(ETH_P_IPV6); - goto retry; - } - return -EINVAL; + if (!skb_flow_dissect_flow_keys_basic(NULL, skb, &keys, + NULL, 0, 0, 0, + 0)) { + /* UFO does not specify ipv4 or 6: try both */ + if (gso_type & SKB_GSO_UDP && + skb->protocol == htons(ETH_P_IP)) { + skb->protocol = htons(ETH_P_IPV6); + goto retry; } + return -EINVAL; + } - p_off = keys.control.thoff + thlen; - if (!pskb_may_pull(skb, p_off) || - keys.basic.ip_proto != ip_proto) - return -EINVAL; + p_off = keys.control.thoff + thlen; + if (!pskb_may_pull(skb, p_off) || + keys.basic.ip_proto != ip_proto || + !virtio_net_hdr_match_proto(keys.basic.n_proto, + hdr_gso_type)) + return -EINVAL; - skb_set_transport_header(skb, keys.control.thoff); - } else if (gso_type) { - p_off = nh_min_len + thlen; - if (!pskb_may_pull(skb, p_off)) - return -EINVAL; - } + skb_set_transport_header(skb, keys.control.thoff); } if (hdr_gso_type != VIRTIO_NET_HDR_GSO_NONE) { diff --git a/include/net/amt.h b/include/net/amt.h index a0255491f5b05e..2846dde0cadce3 100644 --- a/include/net/amt.h +++ b/include/net/amt.h @@ -231,10 +231,6 @@ struct amt_relay_headers { }; } __packed; -struct amt_skb_cb { - struct amt_tunnel_list *tunnel; -}; - struct amt_tunnel_list { struct list_head list; /* Protect All resources under an amt_tunne_list */ diff --git a/include/net/bluetooth/rfcomm.h b/include/net/bluetooth/rfcomm.h index 102c278e35844c..9dc5fd4cb8c815 100644 --- a/include/net/bluetooth/rfcomm.h +++ b/include/net/bluetooth/rfcomm.h @@ -207,6 +207,7 @@ struct rfcomm_dlc { #define RFCOMM_AUTH_REJECT 7 #define RFCOMM_DEFER_SETUP 8 #define RFCOMM_ENC_DROP 9 +#define RFCOMM_CLOSED 10 /* Scheduling flags and events */ #define RFCOMM_SCHED_WAKEUP 31 diff --git a/include/net/can.h b/include/net/can.h index 6db9e826f0e05f..2b8af2598732c0 100644 --- a/include/net/can.h +++ b/include/net/can.h @@ -17,12 +17,14 @@ * @can_framelen: cached echo CAN frame length for bql * @can_gw_hops: can-gw CAN frame time-to-live counter * @can_ext_flags: CAN skb extensions flags + * @can_skb_uid: CAN skb UID for raw_rcv and isotp echo handling */ struct can_skb_ext { int can_iif; u16 can_framelen; u8 can_gw_hops; u8 can_ext_flags; + u32 can_skb_uid; }; #endif /* _NET_CAN_H */ diff --git a/include/net/cfg80211.h b/include/net/cfg80211.h index f5abf1db7558bc..7354ba079363a5 100644 --- a/include/net/cfg80211.h +++ b/include/net/cfg80211.h @@ -3722,6 +3722,7 @@ enum wiphy_params_flags { /* The per TXQ device queue limit in airtime */ #define IEEE80211_DEFAULT_AQL_TXQ_LIMIT_L 5000 #define IEEE80211_DEFAULT_AQL_TXQ_LIMIT_H 12000 +#define IEEE80211_DEFAULT_AQL_TXQ_LIMIT_MC 50000 /* The per interface airtime threshold to switch to lower queue limit */ #define IEEE80211_AQL_THRESHOLD 24000 diff --git a/include/net/ip.h b/include/net/ip.h index 6f602df72ee621..d07c2c5730240b 100644 --- a/include/net/ip.h +++ b/include/net/ip.h @@ -74,6 +74,13 @@ static inline unsigned int ip_hdrlen(const struct sk_buff *skb) return ip_hdr(skb)->ihl * 4; } +static inline int ip_check_csum_start(const struct sk_buff *skb) +{ + if (unlikely(skb->csum_start < skb->network_header + ip_hdrlen(skb))) + return -EINVAL; + return 0; +} + struct ipcm_cookie { struct sockcm_cookie sockc; __be32 addr; diff --git a/include/net/mac80211.h b/include/net/mac80211.h index 36055d40172a18..7b610dfee28670 100644 --- a/include/net/mac80211.h +++ b/include/net/mac80211.h @@ -1317,6 +1317,7 @@ ieee80211_rate_get_vht_nss(const struct ieee80211_tx_rate *rate) * @status_data: internal data for TX status handling, assigned privately, * see also &enum ieee80211_status_data for the internal documentation * @status_data_idr: indicates status data is IDR allocated ID for ack frame + * @tx_time_mc: TX time estimate is for a multicast frame, used internally * @tx_time_est: TX time estimate in units of 4us, used internally * @control: union part for control data * @control.rates: TX rates array to try @@ -1354,8 +1355,8 @@ struct ieee80211_tx_info { status_data_idr:1, status_data:13, hw_queue:4, + tx_time_mc:1, tx_time_est:10; - /* 1 free bit */ union { struct { @@ -6876,6 +6877,17 @@ void ieee80211_sta_register_airtime(struct ieee80211_sta *pubsta, u8 tid, bool ieee80211_txq_airtime_check(struct ieee80211_hw *hw, struct ieee80211_txq *txq); +/** + * ieee80211_txq_aql_pending - get pending AQL airtime for a txq + * + * @hw: pointer obtained from ieee80211_alloc_hw() + * @txq: pointer obtained from station or virtual interface + * + * Return: pending airtime (in usec) for the given txq. + */ +u32 ieee80211_txq_aql_pending(struct ieee80211_hw *hw, + struct ieee80211_txq *txq); + /** * ieee80211_iter_keys - iterate keys programmed into the device * @hw: pointer obtained from ieee80211_alloc_hw() diff --git a/include/net/strparser.h b/include/net/strparser.h index 0ed73e364faa29..881b7ae3449864 100644 --- a/include/net/strparser.h +++ b/include/net/strparser.h @@ -91,11 +91,11 @@ static inline struct strp_msg *strp_msg(struct sk_buff *skb) struct strparser { struct sock *sk; - u32 stopped : 1; - u32 paused : 1; - u32 aborted : 1; - u32 interrupted : 1; - u32 unrecov_intr : 1; + u8 stopped; + u8 paused; + u8 aborted; + u8 interrupted; + u8 unrecov_intr; struct sk_buff **skb_nextp; struct sk_buff *skb_head; diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index c5404fbe3f7efb..3d8c8a50fd3128 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -2077,8 +2077,9 @@ int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr) static void io_rings_free(struct io_ring_ctx *ctx) { - io_free_region(ctx->user, &ctx->sq_region); - io_free_region(ctx->user, &ctx->ring_region); + /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */ + io_free_region(NULL, &ctx->sq_region); + io_free_region(NULL, &ctx->ring_region); ctx->rings = NULL; RCU_INIT_POINTER(ctx->rings_rcu, NULL); ctx->sq_sqes = NULL; @@ -2742,7 +2743,8 @@ static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx, rd.user_addr = p->cq_off.user_addr; rd.flags |= IORING_MEM_REGION_TYPE_USER; } - ret = io_create_region(ctx, &ctx->ring_region, &rd, IORING_OFF_CQ_RING); + /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */ + ret = io_create_region(NULL, &ctx->ring_region, &rd, IORING_OFF_CQ_RING); if (ret) return ret; ctx->rings = rings = io_region_get_ptr(&ctx->ring_region); @@ -2756,7 +2758,7 @@ static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx, rd.user_addr = p->sq_off.user_addr; rd.flags |= IORING_MEM_REGION_TYPE_USER; } - ret = io_create_region(ctx, &ctx->sq_region, &rd, IORING_OFF_SQES); + ret = io_create_region(NULL, &ctx->sq_region, &rd, IORING_OFF_SQES); if (ret) { io_rings_free(ctx); return ret; @@ -2967,7 +2969,8 @@ static void io_ctx_restriction_clone(struct io_ring_ctx *ctx, if (dst->op_registered) ctx->int_flags |= IO_RING_F_OP_RESTRICTED; if (dst->reg_registered) - ctx->int_flags |= IO_RING_F_REG_RESTRICTED; + ctx->int_flags |= IO_RING_F_REG_RESTRICTED | + IO_RING_F_RESTRICT_INHERITED; } static __cold int io_uring_create(struct io_ctx_config *config) diff --git a/io_uring/kbuf.c b/io_uring/kbuf.c index 1cf5be62bb6563..5065a3eff80946 100644 --- a/io_uring/kbuf.c +++ b/io_uring/kbuf.c @@ -458,7 +458,7 @@ static int io_remove_buffers_legacy(struct io_ring_ctx *ctx, static void io_put_bl(struct io_ring_ctx *ctx, struct io_buffer_list *bl) { if (bl->flags & IOBL_BUF_RING) - io_free_region(ctx->user, &bl->region); + io_free_region(NULL, &bl->region); else io_remove_buffers_legacy(ctx, bl, -1U); @@ -675,7 +675,7 @@ int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg) rd.user_addr = reg.ring_addr; rd.flags |= IORING_MEM_REGION_TYPE_USER; } - ret = io_create_region(ctx, &bl->region, &rd, mmap_offset); + ret = io_create_region(NULL, &bl->region, &rd, mmap_offset); if (ret) goto fail; br = io_region_get_ptr(&bl->region); @@ -708,7 +708,7 @@ int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg) if (!ret) return 0; fail: - io_free_region(ctx->user, &bl->region); + io_free_region(NULL, &bl->region); kfree(bl); return ret; } diff --git a/io_uring/memmap.c b/io_uring/memmap.c index 653715e940ba09..7e83c48ad8d960 100644 --- a/io_uring/memmap.c +++ b/io_uring/memmap.c @@ -16,8 +16,10 @@ #include "zcrx.h" static bool io_mem_alloc_compound(struct page **pages, int nr_pages, - size_t size, gfp_t gfp) + size_t size, gfp_t gfp, + struct user_struct *user) { + unsigned long nr_compound, extra; struct page *page; int i, order; @@ -27,9 +29,22 @@ static bool io_mem_alloc_compound(struct page **pages, int nr_pages, else if (order) gfp |= __GFP_COMP; + /* + * get_order() rounds a non power of two size up, so the allocation + * can hold more pages than the region exposes. Account those too, + * and leave the compound allocation alone if they do not fit. + */ + nr_compound = 1UL << order; + extra = nr_compound - nr_pages; + if (extra && user && __io_account_mem(user, extra)) + return false; + page = alloc_pages(gfp, order); - if (!page) + if (!page) { + if (extra && user) + __io_unaccount_mem(user, extra); return false; + } for (i = 0; i < nr_pages; i++) pages[i] = page + i; @@ -105,8 +120,15 @@ void io_free_region(struct user_struct *user, struct io_mapped_region *mr) } if ((mr->flags & IO_REGION_F_VMAP) && mr->ptr) vunmap(mr->ptr); - if (mr->nr_pages && user) - __io_unaccount_mem(user, mr->nr_pages); + if (mr->nr_pages && user) { + unsigned long nr_accounted = mr->nr_pages; + + /* a compound region was accounted for the whole allocation */ + if (mr->flags & IO_REGION_F_SINGLE_REF) + nr_accounted = 1UL << get_order(io_region_size(mr)); + + __io_unaccount_mem(user, nr_accounted); + } memset(mr, 0, sizeof(*mr)); } @@ -151,7 +173,8 @@ static int io_region_pin_pages(struct io_mapped_region *mr, static int io_region_allocate_pages(struct io_mapped_region *mr, struct io_uring_region_desc *reg, - unsigned long mmap_offset) + unsigned long mmap_offset, + struct user_struct *user) { gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN; size_t size = io_region_size(mr); @@ -162,7 +185,7 @@ static int io_region_allocate_pages(struct io_mapped_region *mr, if (!pages) return -ENOMEM; - if (io_mem_alloc_compound(pages, mr->nr_pages, size, gfp)) { + if (io_mem_alloc_compound(pages, mr->nr_pages, size, gfp, user)) { mr->flags |= IO_REGION_F_SINGLE_REF; goto done; } @@ -181,7 +204,7 @@ static int io_region_allocate_pages(struct io_mapped_region *mr, return 0; } -int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr, +int io_create_region(struct user_struct *user, struct io_mapped_region *mr, struct io_uring_region_desc *reg, unsigned long mmap_offset) { @@ -207,8 +230,8 @@ int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr, return -EOVERFLOW; nr_pages = reg->size >> PAGE_SHIFT; - if (ctx->user) { - ret = __io_account_mem(ctx->user, nr_pages); + if (user) { + ret = __io_account_mem(user, nr_pages); if (ret) return ret; } @@ -217,7 +240,7 @@ int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr, if (reg->flags & IORING_MEM_REGION_TYPE_USER) ret = io_region_pin_pages(mr, reg); else - ret = io_region_allocate_pages(mr, reg, mmap_offset); + ret = io_region_allocate_pages(mr, reg, mmap_offset, user); if (ret) goto out_free; @@ -226,7 +249,7 @@ int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr, goto out_free; return 0; out_free: - io_free_region(ctx->user, mr); + io_free_region(user, mr); return ret; } diff --git a/io_uring/memmap.h b/io_uring/memmap.h index f4cfbb6b9a1f46..0714bb5a9616ef 100644 --- a/io_uring/memmap.h +++ b/io_uring/memmap.h @@ -18,7 +18,7 @@ unsigned long io_uring_get_unmapped_area(struct file *file, unsigned long addr, int io_uring_mmap(struct file *file, struct vm_area_struct *vma); void io_free_region(struct user_struct *user, struct io_mapped_region *mr); -int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr, +int io_create_region(struct user_struct *user, struct io_mapped_region *mr, struct io_uring_region_desc *reg, unsigned long mmap_offset); diff --git a/io_uring/net.c b/io_uring/net.c index e6847fb084abcb..37fc7baa55b277 100644 --- a/io_uring/net.c +++ b/io_uring/net.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -1772,7 +1773,8 @@ void io_connect_bpf_populate(struct io_uring_bpf_ctx *bctx, struct io_kiocb *req case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ss; - if (conn->addr_len < (int)sizeof(*sin6)) + /* The IPv6 stack accepts SIN6_LEN_RFC2133; port and addr are in it. */ + if (conn->addr_len < SIN6_LEN_RFC2133) break; bctx->connect.port = sin6->sin6_port; memcpy(bctx->connect.v6_addr, &sin6->sin6_addr, diff --git a/io_uring/register.c b/io_uring/register.c index 02bc103bcc9d54..dab3eb4258dffe 100644 --- a/io_uring/register.c +++ b/io_uring/register.c @@ -480,8 +480,9 @@ struct io_ring_ctx_rings { static void io_register_free_rings(struct io_ring_ctx *ctx, struct io_ring_ctx_rings *r) { - io_free_region(ctx->user, &r->sq_region); - io_free_region(ctx->user, &r->ring_region); + /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */ + io_free_region(NULL, &r->sq_region); + io_free_region(NULL, &r->ring_region); } #define swap_old(ctx, o, n, field) \ @@ -529,7 +530,7 @@ static int io_register_resize_rings(struct io_ring_ctx *ctx, void __user *arg) rd.user_addr = p->cq_off.user_addr; rd.flags |= IORING_MEM_REGION_TYPE_USER; } - ret = io_create_region(ctx, &n.ring_region, &rd, IORING_OFF_CQ_RING); + ret = io_create_region(NULL, &n.ring_region, &rd, IORING_OFF_CQ_RING); if (ret) return ret; @@ -559,7 +560,7 @@ static int io_register_resize_rings(struct io_ring_ctx *ctx, void __user *arg) rd.user_addr = p->sq_off.user_addr; rd.flags |= IORING_MEM_REGION_TYPE_USER; } - ret = io_create_region(ctx, &n.sq_region, &rd, IORING_OFF_SQES); + ret = io_create_region(NULL, &n.sq_region, &rd, IORING_OFF_SQES); if (ret) { io_register_free_rings(ctx, &n); return ret; @@ -730,7 +731,8 @@ static int io_register_mem_region(struct io_ring_ctx *ctx, void __user *uarg) !(ctx->flags & IORING_SETUP_R_DISABLED)) return -EINVAL; - ret = io_create_region(ctx, ®ion, &rd, IORING_MAP_OFF_PARAM_REGION); + ret = io_create_region(ctx->user, ®ion, &rd, + IORING_MAP_OFF_PARAM_REGION); if (ret) return ret; if (copy_to_user(rd_uptr, &rd, sizeof(rd))) { @@ -764,7 +766,14 @@ static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode, if (ctx->submitter_task && ctx->submitter_task != current) return -EEXIST; - if ((ctx->int_flags & IO_RING_F_REG_RESTRICTED) && !(ctx->flags & IORING_SETUP_R_DISABLED)) { + /* + * A disabled ring is exempt from its own register restrictions, so + * that the creator can set them up and then enable the ring. That + * does not apply to restrictions inherited from the task. + */ + if ((ctx->int_flags & IO_RING_F_REG_RESTRICTED) && + (!(ctx->flags & IORING_SETUP_R_DISABLED) || + (ctx->int_flags & IO_RING_F_RESTRICT_INHERITED))) { opcode = array_index_nospec(opcode, IORING_REGISTER_LAST); if (!test_bit(opcode, ctx->restrictions.register_op)) return -EACCES; diff --git a/io_uring/zcrx.c b/io_uring/zcrx.c index 1b6832f6e10fa2..0a9e8a58b99a14 100644 --- a/io_uring/zcrx.c +++ b/io_uring/zcrx.c @@ -398,7 +398,7 @@ static int io_allocate_rbuf_ring(struct io_ring_ctx *ctx, mmap_offset = IORING_MAP_OFF_ZCRX_REGION; mmap_offset += (u64)id << IORING_OFF_ZCRX_SHIFT; - ret = io_create_region(ctx, &ifq->rq_region, rd, mmap_offset); + ret = io_create_region(ctx->user, &ifq->rq_region, rd, mmap_offset); if (ret < 0) return ret; diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c index c43f15c9917c1a..501f12de533f42 100644 --- a/kernel/cgroup/cpuset.c +++ b/kernel/cgroup/cpuset.c @@ -151,6 +151,12 @@ static cpumask_var_t isolated_cpus; /* CSCB */ */ static bool update_housekeeping; /* RWCS */ +/* + * Set if "cpuset_v2_mode" mount option is used + * Cached at bind time and not lock protected; accessed via {READ,WRITE}_ONCE + */ +static bool cpuset_v2_mode; + /* * Copy of isolated_cpus to be passed to housekeeping_update() */ @@ -403,8 +409,7 @@ static inline bool cpuset_v2(void) */ static inline bool is_in_v2_mode(void) { - return cpuset_v2() || - (cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE); + return cpuset_v2() || READ_ONCE(cpuset_v2_mode); } /** @@ -478,10 +483,26 @@ static void guarantee_active_cpus(struct task_struct *tsk, rcu_read_lock(); cs = task_cs(tsk); - while (!cpumask_intersects(cs->effective_cpus, pmask)) + while (!cpumask_intersects(cs->effective_cpus, pmask)) { cs = parent_cs(cs); - + if (unlikely(!cs)) { + /* + * The top cpuset doesn't have any active cpu as a + * consequence of a race between its caller and the cpu + * hotplug operation where cpu_active_mask is updated + * asynchronously before cpuset_handle_hotplug() is + * being called to adjust the effective_cpus of the + * affected cpusets. But we know the top cpuset's + * effective_cpus is on its way to be identical to + * cpu_active_mask minus the exclusive CPUs dedicated + * to other valid cpuset partitions. Just pass back + * the filtered cpu_active_mask in this case. + */ + goto out_unlock; + } + } cpumask_and(pmask, pmask, cs->effective_cpus); +out_unlock: rcu_read_unlock(); } @@ -3586,6 +3607,8 @@ static void cpuset_bind(struct cgroup_subsys_state *root_css) mutex_lock(&cpuset_mutex); spin_lock_irq(&callback_lock); + WRITE_ONCE(cpuset_v2_mode, + !!(cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE)); if (is_in_v2_mode()) { cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask); cpumask_copy(top_cpuset.effective_xcpus, cpu_possible_mask); @@ -3902,15 +3925,16 @@ static void cpuset_handle_hotplug(void) static cpumask_t new_cpus; static nodemask_t new_mems; bool cpus_updated, mems_updated; - bool on_dfl = is_in_v2_mode(); + bool on_dfl; struct tmpmasks tmp, *ptmp = NULL; - if (on_dfl && !alloc_tmpmasks(&tmp)) - ptmp = &tmp; - lockdep_assert_cpus_held(); mutex_lock(&cpuset_mutex); + on_dfl = is_in_v2_mode(); + if (on_dfl && !alloc_tmpmasks(&tmp)) + ptmp = &tmp; + /* fetch the available cpus/mems and find out which changed how */ cpumask_copy(&new_cpus, cpu_active_mask); new_mems = node_states[N_MEMORY]; diff --git a/kernel/dma/swiotlb.c b/kernel/dma/swiotlb.c index bd539313375336..08ded023328f69 100644 --- a/kernel/dma/swiotlb.c +++ b/kernel/dma/swiotlb.c @@ -1680,10 +1680,10 @@ phys_addr_t default_swiotlb_base(void) phys_addr_t default_swiotlb_limit(void) { #ifdef CONFIG_SWIOTLB_DYNAMIC - return io_tlb_default_mem.phys_limit; -#else - return io_tlb_default_mem.defpool.end - 1; + if (io_tlb_default_mem.can_grow) + return io_tlb_default_mem.phys_limit; #endif + return io_tlb_default_mem.defpool.end - 1; } #ifdef CONFIG_DEBUG_FS diff --git a/kernel/fork.c b/kernel/fork.c index f9fd9c9188639a..f26f22e67643bb 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -3360,8 +3360,9 @@ int ksys_unshare(unsigned long unshare_flags) perf_event_namespaces(current); bad_unshare_cleanup_nsproxy: + /* never installed, so no active references to drop */ if (new_nsproxy) - put_nsproxy(new_nsproxy); + nsproxy_free(new_nsproxy); bad_unshare_cleanup_cred: if (new_cred) put_cred(new_cred); diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c index d9d3d5973bf523..3fb1595a4a5934 100644 --- a/kernel/nsproxy.c +++ b/kernel/nsproxy.c @@ -61,7 +61,7 @@ static inline struct nsproxy *create_nsproxy(void) return nsproxy; } -static inline void nsproxy_free(struct nsproxy *ns) +void nsproxy_free(struct nsproxy *ns) { put_mnt_ns(ns->mnt_ns); put_uts_ns(ns->uts_ns); diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index cd7cbd1c99a263..a9f33e2b17aceb 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -1953,8 +1953,14 @@ static void do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags, if (unlikely(!SCX_HAS_OP(sch, enqueue))) goto global; - /* DSQ bypass didn't trigger, enqueue on the BPF scheduler */ - qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT; + /* + * DSQ bypass didn't trigger, enqueue on the BPF scheduler. Wrap the + * per-task qseq counter where the QSEQ field wraps and skip 0, which is + * what scx_bpf_dsq_insert() records for a task in NONE or DISPATCHING. + */ + p->scx.ops_qseq = ((p->scx.ops_qseq + 1) & + (SCX_OPSS_QSEQ_MASK >> SCX_OPSS_QSEQ_SHIFT)) ?: 1; + qseq = (unsigned long)p->scx.ops_qseq << SCX_OPSS_QSEQ_SHIFT; WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE); atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq); @@ -2044,6 +2050,13 @@ static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int core_enq_ int sticky_cpu = p->scx.sticky_cpu; u64 enq_flags = core_enq_flags | rq->scx.extra_enq_flags; + /* + * An SCX-internal migration ends on arrival. Clear sticky_cpu so @p can + * leave custody when inserted into the destination DSQ. + */ + if (sticky_cpu >= 0) + p->scx.sticky_cpu = -1; + /* * SCX_RQ_IN_WAKEUP promises a task_woken_scx() call once this enqueue * returns. Only the core's wakeup path delivers one. The flags stashed @@ -2082,9 +2095,6 @@ static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int core_enq_ dl_server_start(&rq->ext_server); do_enqueue_task(rq, p, enq_flags, sticky_cpu); - - if (sticky_cpu >= 0) - p->scx.sticky_cpu = -1; out: rq->scx.flags &= ~SCX_RQ_IN_WAKEUP; @@ -6690,10 +6700,9 @@ static void scx_dump_cpu(struct scx_sched *sch, struct seq_buf *s, seq_buf_init(&ns, buf, avail); dump_newline(&ns); - dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu ksync=%lu", + dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ksync=%lu", cpu, rq->scx.nr_running, rq->scx.flags, - rq->scx.cpu_released, rq->scx.ops_qseq, - rq->scx.kick_sync); + rq->scx.cpu_released, rq->scx.kick_sync); dump_line(&ns, " curr=%s[%d] class=%ps", rq->curr->comm, rq->curr->pid, rq->curr->sched_class); diff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h index b295991b9f10c5..3cd223c6d7639a 100644 --- a/kernel/sched/ext/internal.h +++ b/kernel/sched/ext/internal.h @@ -1508,6 +1508,11 @@ enum scx_ops_state { * dequeue/requeue, the dispatcher can tell whether it still has a claim * on the task being dispatched. * + * QSEQ is generated from the per-task p->scx.ops_qseq counter so that + * it doesn't repeat across QUEUED instances of the same task even if + * the task moves between rqs. 0 is never used as a valid QSEQ since + * NONE and DISPATCHING map to this value. + * * As some 32bit archs can't do 64bit store_release/load_acquire, * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on * 32bit machines. The dispatch race window QSEQ protects is very narrow diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index f76e6f7f4a0147..a6c6f8165eecc8 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -795,7 +795,6 @@ struct scx_rq { struct scx_dispatch_q local_dsq; struct list_head runnable_list; /* runnable tasks on this rq */ struct list_head ddsp_deferred_locals; /* deferred ddsps from enq */ - unsigned long ops_qseq; u64 extra_enq_flags; /* see move_task_to_local_dsq() */ u32 nr_running; u32 cpuperf_target; /* [0, SCHED_CAPACITY_SCALE] */ diff --git a/kernel/workqueue.c b/kernel/workqueue.c index 53608ac01fab1b..cb7055aee3afc7 100644 --- a/kernel/workqueue.c +++ b/kernel/workqueue.c @@ -2244,7 +2244,7 @@ static bool is_chained_work(struct workqueue_struct *wq) * Return %true iff I'm a worker executing a work item on @wq. If * I'm @worker, it's safe to dereference it without locking. */ - return worker && worker->current_pwq->wq == wq; + return worker && worker->current_pwq && worker->current_pwq->wq == wq; } /* diff --git a/lib/dim/dim.c b/lib/dim/dim.c index 97c3d084ebf023..7f3eebae73cb92 100644 --- a/lib/dim/dim.c +++ b/lib/dim/dim.c @@ -69,11 +69,15 @@ bool dim_calc_stats(const struct dim_sample *start, if (!delta_us) return false; - curr_stats->ppms = DIV_ROUND_UP(npkts * USEC_PER_MSEC, delta_us); - curr_stats->bpms = DIV_ROUND_UP(nbytes * USEC_PER_MSEC, delta_us); + /* u32 * USEC_PER_MSEC overflows a 32-bit long */ + curr_stats->ppms = DIV_ROUND_UP_ULL((u64)npkts * USEC_PER_MSEC, + delta_us); + curr_stats->bpms = DIV_ROUND_UP_ULL((u64)nbytes * USEC_PER_MSEC, + delta_us); curr_stats->epms = DIV_ROUND_UP(DIM_NEVENTS * USEC_PER_MSEC, delta_us); - curr_stats->cpms = DIV_ROUND_UP(ncomps * USEC_PER_MSEC, delta_us); + curr_stats->cpms = DIV_ROUND_UP_ULL((u64)ncomps * USEC_PER_MSEC, + delta_us); if (curr_stats->epms != 0) curr_stats->cpe_ratio = DIV_ROUND_DOWN_ULL( curr_stats->cpms * 100, curr_stats->epms); diff --git a/mm/mremap.c b/mm/mremap.c index 8e3d0e4b107d00..15dc2e38cb4e0c 100644 --- a/mm/mremap.c +++ b/mm/mremap.c @@ -1035,6 +1035,7 @@ static void vrm_stat_account(struct vma_remap_struct *vrm, } static bool __check_map_count_against_split(struct mm_struct *mm, + bool pre_split, bool before_unmaps) { const int sys_map_count = get_sysctl_max_map_count(); @@ -1086,26 +1087,42 @@ static bool __check_map_count_against_split(struct mm_struct *mm, * Therefore we must check to ensure we have headroom of 2 additional * VMAs. */ - return map_count + 2 <= sys_map_count; + map_count += 2; + + /* If pre-split, the -1 observed above doesn't apply. */ + if (pre_split) + map_count++; + + return map_count <= sys_map_count; +} + +static bool needs_pre_split(struct vma_remap_struct *vrm) +{ + /* + * An MREMAP_DONTUNMAP of a mlock()'d VMA needs to unlock the + * source VMA, so split in this case. + */ + return (vrm->flags & MREMAP_DONTUNMAP) && + vma_test(vrm->vma, VMA_LOCKED_BIT); } /* Do we violate the map count limit if we split VMAs when moving the VMA? */ -static bool check_map_count_against_split(void) +static bool check_map_count_against_split(struct vma_remap_struct *vrm) { return __check_map_count_against_split(current->mm, - /*before_unmaps=*/false); + needs_pre_split(vrm), /*before_unmaps=*/false); } /* Do we violate the map count limit if we split VMAs prior to early unmaps? */ -static bool check_map_count_against_split_early(void) +static bool check_map_count_against_split_early(struct vma_remap_struct *vrm) { return __check_map_count_against_split(current->mm, - /*before_unmaps=*/true); + vrm->flags & MREMAP_DONTUNMAP, /*before_unmaps=*/true); } /* - * Perform checks before attempting to write a VMA prior to it being - * moved. + * Perform checks and preparation before attempting to write a VMA prior to it + * being moved. */ static unsigned long prep_move_vma(struct vma_remap_struct *vrm) { @@ -1114,19 +1131,17 @@ static unsigned long prep_move_vma(struct vma_remap_struct *vrm) unsigned long old_addr = vrm->addr; unsigned long old_len = vrm->old_len; vm_flags_t dummy = vma->vm_flags; + const bool split_before = vma->vm_start != old_addr; + const bool split_after = vma->vm_end != old_addr + old_len; - /* - * We'd prefer to avoid failure later on in do_munmap: we copy a VMA, - * which may not merge, then (if MREMAP_DONTUNMAP is not set) unmap the - * source, which may split, causing a net increase of 2 mappings. - */ - if (!check_map_count_against_split()) + /* Avoid failure later on. */ + if (!check_map_count_against_split(vrm)) return -ENOMEM; if (vma->vm_ops && vma->vm_ops->may_split) { - if (vma->vm_start != old_addr) + if (split_before) err = vma->vm_ops->may_split(vma, old_addr); - if (!err && vma->vm_end != old_addr + old_len) + if (!err && split_after) err = vma->vm_ops->may_split(vma, old_addr + old_len); if (err) return err; @@ -1144,6 +1159,21 @@ static unsigned long prep_move_vma(struct vma_remap_struct *vrm) if (err) return err; + /* + * To account mlock()'d pages correctly in the MREMAP_DONTUNMAP + * case perform any split ahead of time for an mlock()'d VMA. + */ + if (needs_pre_split(vrm)) { + VMA_ITERATOR(vmi, vma->vm_mm, old_addr); + + if (split_before) + err = split_vma(&vmi, vma, old_addr, 1); + if (!err && split_after) + err = split_vma(&vmi, vma, old_addr + old_len, 0); + vrm->vmi_needs_invalidate = true; + return err; + } + return 0; } @@ -1269,7 +1299,8 @@ static int copy_vma_and_data(struct vma_remap_struct *vrm, PAGETABLE_MOVE(pmc, NULL, NULL, vrm->addr, vrm->new_addr, vrm->old_len); new_vma = copy_vma(&vma, vrm->new_addr, vrm->new_len, pos, - &pmc.need_rmap_locks); + &pmc.need_rmap_locks, + vrm->flags & MREMAP_DONTUNMAP); if (!new_vma) { vrm_uncharge(vrm); *new_vma_ptr = NULL; @@ -1329,6 +1360,9 @@ static void dontunmap_complete(struct vma_remap_struct *vrm, unsigned long old_start = vma->vm_start; unsigned long old_end = vma->vm_end; + /* Self-merge is disallowed. */ + VM_WARN_ON_ONCE(new_vma == vma); + /* We always clear VM_LOCKED[ONFAULT] on the old VMA. */ vm_flags_clear(vma, VM_LOCKED_MASK); @@ -1336,8 +1370,11 @@ static void dontunmap_complete(struct vma_remap_struct *vrm, * anon_vma links of the old vma is no longer needed after its page * table has been moved. */ - if (new_vma != vma && start == old_start && end == old_end) { - const pgoff_t pgoff_unfaulted = vma->vm_start >> PAGE_SHIFT; + if (start == old_start && end == old_end) { + const struct vm_page_offset pos_unfaulted = { + .index = vma->vm_start >> PAGE_SHIFT, + .offset = vma->vm_start & ~PAGE_MASK, + }; unlink_anon_vmas(vma); /* @@ -1346,7 +1383,7 @@ static void dontunmap_complete(struct vma_remap_struct *vrm, * vma->vm_start >> PAGE_SHIFT. */ if (vma_is_anonymous(vma) && !vma->vm_file) - vma->vm_pgoff = pgoff_unfaulted; + vma_set_page_offset(vma, pos_unfaulted); } } @@ -1997,7 +2034,7 @@ static unsigned long do_mremap(struct vma_remap_struct *vrm) return -EINTR; vrm->mmap_locked = true; - if (!check_map_count_against_split_early()) { + if (!check_map_count_against_split_early(vrm)) { mmap_write_unlock(mm); return -ENOMEM; } diff --git a/mm/pgtable-generic.c b/mm/pgtable-generic.c index 7a9eef9b4f5b7e..70f1cd37f007b7 100644 --- a/mm/pgtable-generic.c +++ b/mm/pgtable-generic.c @@ -455,12 +455,30 @@ static void kernel_pgtable_work_func(struct work_struct *work) __pagetable_free(pt); } +static void schedule_kernel_pgtable_free(void) +{ + schedule_work(&kernel_pgtable_work.work); +} + void pagetable_free_kernel(struct ptdesc *pt) { spin_lock(&kernel_pgtable_work.lock); list_add(&pt->pt_list, &kernel_pgtable_work.list); spin_unlock(&kernel_pgtable_work.lock); - schedule_work(&kernel_pgtable_work.work); + /* + * The workqueue may not exist yet while the system is booting. + * kernel_pgtable_drain_early() schedules the work once it does. + */ + if (system_state != SYSTEM_BOOTING) + schedule_kernel_pgtable_free(); +} + +static int __init kernel_pgtable_drain_early(void) +{ + /* Free the kernel page tables queued while booting. */ + schedule_kernel_pgtable_free(); + return 0; } +core_initcall(kernel_pgtable_drain_early); #endif diff --git a/mm/vma.c b/mm/vma.c index 941d9ec9f4b765..8646a0a8d91a98 100644 --- a/mm/vma.c +++ b/mm/vma.c @@ -599,8 +599,8 @@ __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, * Split a vma into two pieces at address 'addr', a new vma is allocated * either for the first part or the tail. */ -static int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, - unsigned long addr, int new_below) +int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, + unsigned long addr, int new_below) { if (vma->vm_mm->map_count >= get_sysctl_max_map_count()) return -ENOMEM; @@ -1877,7 +1877,7 @@ static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma) */ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap, unsigned long addr, unsigned long len, struct vm_page_offset pos, - bool *need_rmap_locks) + bool *need_rmap_locks, bool keep_source) { struct vm_area_struct *vma = *vmap; unsigned long vma_start = vma->vm_start; @@ -1913,6 +1913,21 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap, vmg_set_page_offset(&vmg, pos); vmg.next = vma_iter_next_rewind(&vmi, NULL); + + /* + * If the original VMA is kept (MREMAP_DONTUNMAP), the source and + * destination VMA must be treated distinctly. + * + * A merge violates this, so in this case disallow a self-merge. + */ + if (!faulted_in_anon_vma && keep_source) { + if (vmg.prev == vma) + vmg.prev = NULL; + if (vmg.next == vma) + vmg.next = NULL; + faulted_in_anon_vma = true; + } + new_vma = vma_merge_copied_range(&vmg); if (new_vma) { diff --git a/mm/vma.h b/mm/vma.h index 3d9c8ee4be05d1..9f9dac01dde4b1 100644 --- a/mm/vma.h +++ b/mm/vma.h @@ -481,7 +481,7 @@ void unlink_file_vma_batch_add(struct unlink_vma_file_batch *vb, struct vm_area_struct *copy_vma(struct vm_area_struct **vmap, unsigned long addr, unsigned long len, struct vm_page_offset pos, - bool *need_rmap_locks); + bool *need_rmap_locks, bool keep_source); struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma); @@ -502,6 +502,11 @@ int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma, unsigned long unmapped_area(struct vm_unmapped_area_info *info); unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info); +#ifdef CONFIG_MMU +int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, + unsigned long addr, int new_below); +#endif + static inline bool vma_wants_manual_pte_write_upgrade(struct vm_area_struct *vma) { /* diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index aea017ee5b0a36..b19e68844e1a98 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -4113,9 +4113,11 @@ static int hci_send_cmd_sync(struct hci_dev *hdev, struct sk_buff *skb) bt_dev_dbg(hdev, "skb %p", skb); + hci_dev_lock(hdev); kfree_skb(hdev->sent_cmd); hdev->sent_cmd = skb_clone(skb, GFP_KERNEL); + hci_dev_unlock(hdev); if (!hdev->sent_cmd) { skb_queue_head(&hdev->cmd_q, skb); queue_work(hdev->workqueue, &hdev->cmd_work); @@ -4136,8 +4138,10 @@ static int hci_send_cmd_sync(struct hci_dev *hdev, struct sk_buff *skb) if (READ_ONCE(hdev->req_status) == HCI_REQ_PEND && !hci_dev_test_and_set_flag(hdev, HCI_CMD_PENDING)) { + hci_dev_lock(hdev); kfree_skb(hdev->req_skb); hdev->req_skb = skb_get(hdev->sent_cmd); + hci_dev_unlock(hdev); } return err; diff --git a/net/bluetooth/hci_sock.c b/net/bluetooth/hci_sock.c index 6d56c77741e194..81068b585764e8 100644 --- a/net/bluetooth/hci_sock.c +++ b/net/bluetooth/hci_sock.c @@ -1223,8 +1223,10 @@ static int hci_sock_bind(struct socket *sock, struct sockaddr_unsized *addr, */ hdev = hci_pi(sk)->hdev; if (hdev && hci_dev_test_flag(hdev, HCI_UNREGISTER)) { + write_lock(&hci_sk_list.lock); hci_pi(sk)->hdev = NULL; sk->sk_state = BT_OPEN; + write_unlock(&hci_sk_list.lock); hci_dev_put(hdev); } hdev = NULL; diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 9f4852e2dc7bc6..d54556ecdbe92e 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -32,8 +32,10 @@ static void hci_cmd_sync_complete(struct hci_dev *hdev, u8 result, u16 opcode, WRITE_ONCE(hdev->req_status, HCI_REQ_DONE); /* Free the request command so it is not used as response */ + hci_dev_lock(hdev); kfree_skb(hdev->req_skb); hdev->req_skb = NULL; + hci_dev_unlock(hdev); if (skb) { struct sock *sk = hci_skb_sk(skb); @@ -3060,15 +3062,21 @@ static int hci_le_set_ext_scan_param_sync(struct hci_dev *hdev, u8 type, */ if (hci_dev_test_flag(hdev, HCI_PA_SYNC)) { struct hci_cp_le_add_to_accept_list *sent; + bdaddr_t bdaddr; + hci_dev_lock(hdev); sent = hci_sent_cmd_data(hdev, HCI_OP_LE_ADD_TO_ACCEPT_LIST); + if (sent) + bacpy(&bdaddr, &sent->bdaddr); + hci_dev_unlock(hdev); + if (sent) { struct hci_conn *conn; rcu_read_lock(); conn = hci_conn_hash_lookup_ba(hdev, PA_LINK, - &sent->bdaddr); + &bdaddr); if (conn) { struct bt_iso_qos *qos = &conn->iso_qos; diff --git a/net/bluetooth/iso.c b/net/bluetooth/iso.c index 7657c2a0abbf7c..d6ac5b1f49bc13 100644 --- a/net/bluetooth/iso.c +++ b/net/bluetooth/iso.c @@ -61,6 +61,7 @@ enum { BT_SK_BIG_SYNC, BT_SK_PA_SYNC, BT_SK_KILLED, + BT_SK_CONNECTING, }; struct iso_pinfo { @@ -350,6 +351,9 @@ static int __iso_chan_add(struct iso_conn *conn, struct sock *sk, return -EBUSY; } + if (iso_pi(sk)->conn) + return -EISCONN; + if (!conn->hcon) { BT_ERR("conn->hcon missing"); return -EIO; @@ -410,6 +414,11 @@ static int iso_connect_bis(struct sock *sk) hci_dev_lock(hdev); lock_sock(sk); + if (iso_pi(sk)->conn) { + err = -EISCONN; + goto unlock; + } + if (!bis_capable(hdev)) { err = -EOPNOTSUPP; goto unlock; @@ -562,6 +571,13 @@ static int iso_connect_cis(struct sock *sk) lockdep_assert_held(&hcon->hdev->lock); + /* The socket lock keeps the current attachment and its hcon stable. */ + if (iso_pi(sk)->conn && iso_pi(sk)->conn->hcon != hcon) { + hci_conn_drop(hcon); + err = -EISCONN; + goto unlock; + } + conn = iso_conn_add(hcon); if (!conn) { hci_conn_drop(hcon); @@ -1269,17 +1285,26 @@ static int iso_sock_connect(struct socket *sock, struct sockaddr_unsized *addr, addr->sa_family != AF_BLUETOOTH) return -EINVAL; - if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) - return -EBADFD; + lock_sock(sk); - if (sk->sk_type != SOCK_SEQPACKET) - return -EINVAL; + if ((sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) || + test_bit(BT_SK_CONNECTING, &iso_pi(sk)->flags)) { + err = -EBADFD; + goto done; + } + + if (sk->sk_type != SOCK_SEQPACKET) { + err = -EINVAL; + goto done; + } /* Check if the address type is of LE type */ - if (!bdaddr_type_is_le(sa->iso_bdaddr_type)) - return -EINVAL; + if (!bdaddr_type_is_le(sa->iso_bdaddr_type)) { + err = -EINVAL; + goto done; + } - lock_sock(sk); + set_bit(BT_SK_CONNECTING, &iso_pi(sk)->flags); bacpy(&iso_pi(sk)->dst, &sa->iso_bdaddr); iso_pi(sk)->dst_type = sa->iso_bdaddr_type; @@ -1291,16 +1316,18 @@ static int iso_sock_connect(struct socket *sock, struct sockaddr_unsized *addr, else err = iso_connect_bis(sk); - if (err) - return err; - lock_sock(sk); + clear_bit(BT_SK_CONNECTING, &iso_pi(sk)->flags); + if (err) + goto done; + if (!test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); } +done: release_sock(sk); return err; } @@ -1340,6 +1367,11 @@ static int iso_listen_bis(struct sock *sk) hci_dev_lock(hdev); lock_sock(sk); + if (sk->sk_state != BT_BOUND || iso_pi(sk)->conn) { + err = -EBADFD; + goto unlock; + } + /* Fail if user set invalid QoS */ if (iso_pi(sk)->qos_user_set && !check_bcast_qos(&iso_pi(sk)->qos)) { iso_pi(sk)->qos = default_qos; diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index 2a177cd17a9efb..7928d9e45f98ab 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -1489,7 +1489,7 @@ static void cmd_complete_rsp(struct mgmt_pending_cmd *cmd, void *data) return; } - cmd_status_rsp(cmd, data); + cmd_status_rsp(cmd, &match->mgmt_status); } static int generic_cmd_complete(struct mgmt_pending_cmd *cmd, u8 status) diff --git a/net/bluetooth/rfcomm/core.c b/net/bluetooth/rfcomm/core.c index 3f757198051a21..7a7791fe56b0e9 100644 --- a/net/bluetooth/rfcomm/core.c +++ b/net/bluetooth/rfcomm/core.c @@ -62,10 +62,9 @@ static void rfcomm_make_uih(struct sk_buff *skb, u8 addr); static void rfcomm_process_connect(struct rfcomm_session *s); -static struct rfcomm_session *rfcomm_session_create(bdaddr_t *src, - bdaddr_t *dst, - u8 sec_level, - int *err); +static struct socket *rfcomm_session_connect(bdaddr_t *src, bdaddr_t *dst, + u8 sec_level, int *err); +static struct rfcomm_session *rfcomm_session_add(struct socket *sock, int state); static struct rfcomm_session *rfcomm_session_get(bdaddr_t *src, bdaddr_t *dst); static struct rfcomm_session *rfcomm_session_del(struct rfcomm_session *s); @@ -365,28 +364,17 @@ static int rfcomm_check_channel(u8 channel) return channel < 1 || channel > 30; } -static int __rfcomm_dlc_open(struct rfcomm_dlc *d, bdaddr_t *src, bdaddr_t *dst, u8 channel) +static int __rfcomm_dlc_open(struct rfcomm_dlc *d, struct rfcomm_session *s, + u8 channel) { - struct rfcomm_session *s; - int err = 0; u8 dlci; - BT_DBG("dlc %p state %ld %pMR -> %pMR channel %d", - d, d->state, src, dst, channel); - - if (rfcomm_check_channel(channel)) - return -EINVAL; + BT_DBG("dlc %p state %ld session %p channel %d", + d, d->state, s, channel); if (d->state != BT_OPEN && d->state != BT_CLOSED) return 0; - s = rfcomm_session_get(src, dst); - if (!s) { - s = rfcomm_session_create(src, dst, d->sec_level, &err); - if (!s) - return err; - } - dlci = __dlci(__session_dir(s), channel); /* Check if DLCI already exists */ @@ -421,14 +409,84 @@ static int __rfcomm_dlc_open(struct rfcomm_dlc *d, bdaddr_t *src, bdaddr_t *dst, int rfcomm_dlc_open(struct rfcomm_dlc *d, bdaddr_t *src, bdaddr_t *dst, u8 channel) { - int r; + struct rfcomm_session *s; + struct socket *sock; + int err; + + BT_DBG("dlc %p state %ld %pMR -> %pMR channel %d", + d, d->state, src, dst, channel); + + if (rfcomm_check_channel(channel)) + return -EINVAL; rfcomm_lock(); - r = __rfcomm_dlc_open(d, src, dst, channel); + clear_bit(RFCOMM_CLOSED, &d->flags); + /* Do not page the remote device for a DLC that cannot be opened + * anyway. __rfcomm_dlc_open() looks at the state again once the + * lock has been re-acquired below. + */ + if (d->state != BT_OPEN && d->state != BT_CLOSED) { + rfcomm_unlock(); + return 0; + } + + s = rfcomm_session_get(src, dst); + if (s) { + err = __rfcomm_dlc_open(d, s, channel); + rfcomm_unlock(); + return err; + } rfcomm_unlock(); - return r; + + /* There is no session for this pair yet. kernel_connect() ends up in + * l2cap_chan_connect(), which takes hdev->lock, and the HCI event + * path takes rfcomm_mutex while holding hdev->lock, so the socket has + * to be connected with rfcomm_mutex released. + */ + sock = rfcomm_session_connect(src, dst, d->sec_level, &err); + if (!sock) + return err; + + rfcomm_lock(); + + /* The DLC may have been closed while the socket was connecting. It + * was not on a session, so rfcomm_dlc_close() could only mark it; + * attaching it now would leave it with no owner. + */ + if (test_bit(RFCOMM_CLOSED, &d->flags)) { + rfcomm_unlock(); + sock_release(sock); + return -ECONNRESET; + } + + /* Another opener may have added a session for the same pair in the + * meantime; that one is used and this socket is dropped. + */ + s = rfcomm_session_get(src, dst); + if (!s) { + s = rfcomm_session_add(sock, BT_BOUND); + if (s) { + s->initiator = 1; + sock = NULL; + } + } + + err = s ? __rfcomm_dlc_open(d, s, channel) : -ENOMEM; + + rfcomm_unlock(); + + if (sock) + sock_release(sock); + + /* Over an existing ACL link the connection can complete before the + * session reaches the list, and that wakeup is then lost, so let + * krfcommd look at the socket state now. + */ + rfcomm_schedule(); + + return err; } static void __rfcomm_dlc_disconn(struct rfcomm_dlc *d) @@ -508,8 +566,14 @@ int rfcomm_dlc_close(struct rfcomm_dlc *d, int err) rfcomm_lock(); s = d->session; - if (!s) + if (!s) { + /* Not on a session yet: rfcomm_dlc_open() may be connecting a + * socket for it with rfcomm_mutex released. Leave a mark so + * that it does not attach the DLC once it holds the lock again. + */ + set_bit(RFCOMM_CLOSED, &d->flags); goto no_session; + } /* after waiting on the mutex check the session still exists * then check the dlc still exists @@ -757,12 +821,12 @@ static struct rfcomm_session *rfcomm_session_close(struct rfcomm_session *s, return rfcomm_session_del(s); } -static struct rfcomm_session *rfcomm_session_create(bdaddr_t *src, - bdaddr_t *dst, - u8 sec_level, - int *err) +/* Creates the L2CAP socket a new session will run on and starts connecting + * it. Must be called with rfcomm_mutex released. + */ +static struct socket *rfcomm_session_connect(bdaddr_t *src, bdaddr_t *dst, + u8 sec_level, int *err) { - struct rfcomm_session *s = NULL; struct sockaddr_l2 addr; struct socket *sock; struct sock *sk; @@ -792,24 +856,16 @@ static struct rfcomm_session *rfcomm_session_create(bdaddr_t *src, l2cap_pi(sk)->chan->mode = L2CAP_MODE_ERTM; release_sock(sk); - s = rfcomm_session_add(sock, BT_BOUND); - if (!s) { - *err = -ENOMEM; - goto failed; - } - - s->initiator = 1; - bacpy(&addr.l2_bdaddr, dst); addr.l2_family = AF_BLUETOOTH; addr.l2_psm = cpu_to_le16(L2CAP_PSM_RFCOMM); addr.l2_cid = 0; addr.l2_bdaddr_type = BDADDR_BREDR; *err = kernel_connect(sock, (struct sockaddr_unsized *)&addr, sizeof(addr), O_NONBLOCK); - if (*err == 0 || *err == -EINPROGRESS) - return s; + if (*err && *err != -EINPROGRESS) + goto failed; - return rfcomm_session_del(s); + return sock; failed: sock_release(sock); diff --git a/net/bluetooth/rfcomm/sock.c b/net/bluetooth/rfcomm/sock.c index d2855f9b3abc3a..0a6ba8ca230f0c 100644 --- a/net/bluetooth/rfcomm/sock.c +++ b/net/bluetooth/rfcomm/sock.c @@ -48,8 +48,11 @@ static void rfcomm_sock_kill(struct sock *sk); static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb) { struct sock *sk = d->owner; - if (!sk) + + if (!sk) { + kfree_skb(skb); return; + } atomic_add(skb->len, &sk->sk_rmem_alloc); skb_queue_tail(&sk->sk_receive_queue, skb); diff --git a/net/bluetooth/rfcomm/tty.c b/net/bluetooth/rfcomm/tty.c index dc3cdf614defe2..198c7dd1a95b42 100644 --- a/net/bluetooth/rfcomm/tty.c +++ b/net/bluetooth/rfcomm/tty.c @@ -128,7 +128,7 @@ static void rfcomm_dev_shutdown(struct tty_port *port) { struct rfcomm_dev *dev = container_of(port, struct rfcomm_dev, port); - if (dev->tty_dev->parent) + if (dev->tty_dev && dev->tty_dev->parent) device_move(dev->tty_dev, NULL, DPM_ORDER_DEV_LAST); /* close the dlc */ diff --git a/net/bluetooth/sco.c b/net/bluetooth/sco.c index 3d4362a09df4cd..f4a20d7b5f9cb9 100644 --- a/net/bluetooth/sco.c +++ b/net/bluetooth/sco.c @@ -84,12 +84,14 @@ static void sco_conn_free(struct kref *ref) if (conn->sk) sco_pi(conn->sk)->conn = NULL; - if (conn->hcon) { - conn->hcon->sco_data = NULL; - hci_conn_drop(conn->hcon); - } + /* hcon->sco_data is cleared and the association's reference on the + * sco_conn is dropped in sco_conn_del() under hdev->lock, and the + * hci_conn is now owned by the socket (held in __sco_chan_add() and + * dropped in sco_chan_del()/sco_sock_destruct()), so there is nothing + * left to release towards hcon here. + */ - /* Ensure no more work items will run since hci_conn has been dropped */ + /* Ensure no more work items will run before the connection is freed */ disable_delayed_work_sync(&conn->timeout_work); kfree(conn); @@ -188,25 +190,19 @@ static void sco_sock_clear_timer(struct sock *sk) } /* ---- SCO connections ---- */ -/* Consumes a reference on @hcon, which the returned sco_conn owns until it is - * freed. On failure (NULL return) the reference is left for the caller to drop. +/* Returns a new reference the caller must drop with sco_conn_put(). The + * hcon->sco_data association holds its own reference on the sco_conn for the + * connection's lifetime; it is dropped in sco_conn_del() under hdev->lock. + * @hcon is not consumed: the hci_conn reference is taken and owned by the + * socket in __sco_chan_add(). */ static struct sco_conn *sco_conn_add(struct hci_conn *hcon) { struct sco_conn *conn = hcon->sco_data; conn = sco_conn_hold_unless_zero(conn); - if (conn) { - if (!conn->hcon) { - sco_conn_lock(conn); - conn->hcon = hcon; - sco_conn_unlock(conn); - } else { - /* conn already owns a reference on hcon */ - hci_conn_drop(hcon); - } + if (conn) return conn; - } conn = kzalloc_obj(struct sco_conn); if (!conn) @@ -227,7 +223,10 @@ static struct sco_conn *sco_conn_add(struct hci_conn *hcon) BT_DBG("hcon %p conn %p", hcon, conn); - return conn; + /* kref_init() above set the association reference owned by + * hcon->sco_data; hand the caller its own reference. + */ + return sco_conn_hold(conn); } /* Delete channel. @@ -242,6 +241,19 @@ static void sco_chan_del(struct sock *sk, int err) BT_DBG("sk %p, conn %p, err %d", sk, conn, err); if (conn) { + struct hci_conn *hcon; + + sco_conn_lock(conn); + hcon = conn->hcon; + sco_conn_unlock(conn); + + /* Drop the socket's hci_conn reference BEFORE clearing + * conn->sk, so sco_conn_del() on another CPU cannot free + * the hci_conn while we still hold a pointer to it. + */ + if (hcon) + hci_conn_drop(hcon); + sco_conn_lock(conn); conn->sk = NULL; sco_conn_unlock(conn); @@ -266,6 +278,13 @@ static void sco_conn_del(struct hci_conn *hcon, int err) BT_DBG("hcon %p conn %p, err %d", hcon, conn, err); + /* Detach from the hci_conn and drop the association's reference. + * The caller holds hdev->lock, which serialises this against the + * read of hcon->sco_data in sco_recv_scodata(). + */ + hcon->sco_data = NULL; + sco_conn_put(conn); + sco_conn_lock(conn); sk = sco_sock_hold(conn); sco_conn_unlock(conn); @@ -290,6 +309,11 @@ static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, sco_pi(sk)->conn = sco_conn_hold(conn); conn->sk = sk; + /* The socket owns an hci_conn reference for as long as it stays + * attached; it is dropped in sco_chan_del()/sco_sock_destruct(). + */ + hci_conn_hold(conn->hcon); + if (parent) bt_accept_enqueue(parent, sk, true); } @@ -371,6 +395,7 @@ static int sco_connect(struct sock *sk) if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) { release_sock(sk); sco_conn_put(conn); + hci_conn_drop(hcon); err = -EBADFD; goto unlock; } @@ -379,9 +404,13 @@ static int sco_connect(struct sock *sk) sco_conn_put(conn); if (err) { release_sock(sk); + hci_conn_drop(hcon); goto unlock; } + /* __sco_chan_add() took its own hci_conn reference; drop ours. */ + hci_conn_drop(hcon); + /* Update source addr of the socket */ bacpy(&sco_pi(sk)->src, &hcon->src); @@ -495,9 +524,25 @@ static struct sock *sco_get_sock_listen(bdaddr_t *src) static void sco_sock_destruct(struct sock *sk) { + struct sco_conn *conn = sco_pi(sk)->conn; + BT_DBG("sk %p", sk); - sco_conn_put(sco_pi(sk)->conn); + /* If the channel was not already torn down via sco_chan_del(), drop + * the socket's own references here. + */ + if (conn) { + struct hci_conn *hcon; + + sco_conn_lock(conn); + hcon = conn->hcon; + sco_conn_unlock(conn); + + if (hcon) + hci_conn_drop(hcon); + sco_pi(sk)->conn = NULL; + sco_conn_put(conn); + } skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); @@ -1511,12 +1556,10 @@ static void sco_connect_cfm(struct hci_conn *hcon, __u8 status) if (!status) { struct sco_conn *conn; - conn = sco_conn_add(hci_conn_hold(hcon)); + conn = sco_conn_add(hcon); if (conn) { sco_conn_ready(conn); sco_conn_put(conn); - } else { - hci_conn_drop(hcon); } } else sco_conn_del(hcon, bt_to_errno(status)); diff --git a/net/bridge/br_multicast.c b/net/bridge/br_multicast.c index 2191d35d9fa07a..79b6fe54a7cbe6 100644 --- a/net/bridge/br_multicast.c +++ b/net/bridge/br_multicast.c @@ -81,6 +81,10 @@ __br_multicast_add_group(struct net_bridge_mcast *brmctx, bool blocked); static void br_multicast_find_del_pg(struct net_bridge *br, struct net_bridge_port_group *pg); +static void __br_multicast_del_pg(struct net_bridge_mdb_entry *mp, + struct net_bridge_port_group *pg, + struct net_bridge_port_group __rcu **pp, + bool sg_del_exclude_ports); static void __br_multicast_stop(struct net_bridge_mcast *brmctx); static int br_mc_disabled_update(struct net_device *dev, bool value, @@ -458,7 +462,7 @@ static void br_multicast_sg_del_exclude_ports(struct net_bridge_mdb_entry *sgmp) for (pp = &sgmp->ports; (p = mlock_dereference(*pp, sgmp->br)) != NULL;) { if (!(p->flags & MDB_PG_FLAGS_PERMANENT)) - br_multicast_del_pg(sgmp, p, pp); + __br_multicast_del_pg(sgmp, p, pp, false); else pp = &p->next; } @@ -799,9 +803,10 @@ static void br_multicast_destroy_port_group(struct net_bridge_mcast_gc *gc) kfree_rcu(pg, rcu); } -void br_multicast_del_pg(struct net_bridge_mdb_entry *mp, - struct net_bridge_port_group *pg, - struct net_bridge_port_group __rcu **pp) +static void __br_multicast_del_pg(struct net_bridge_mdb_entry *mp, + struct net_bridge_port_group *pg, + struct net_bridge_port_group __rcu **pp, + bool sg_del_exclude_ports) { struct net_bridge *br = pg->key.port->br; struct net_bridge_group_src *ent; @@ -816,7 +821,8 @@ void br_multicast_del_pg(struct net_bridge_mdb_entry *mp, if (!br_multicast_is_star_g(&mp->addr)) { rhashtable_remove_fast(&br->sg_port_tbl, &pg->rhnode, br_sg_port_rht_params); - br_multicast_sg_del_exclude_ports(mp); + if (sg_del_exclude_ports) + br_multicast_sg_del_exclude_ports(mp); } else { br_multicast_star_g_handle_mode(pg, MCAST_INCLUDE); } @@ -828,6 +834,13 @@ void br_multicast_del_pg(struct net_bridge_mdb_entry *mp, mod_timer(&mp->timer, jiffies); } +void br_multicast_del_pg(struct net_bridge_mdb_entry *mp, + struct net_bridge_port_group *pg, + struct net_bridge_port_group __rcu **pp) +{ + __br_multicast_del_pg(mp, pg, pp, true); +} + static void br_multicast_find_del_pg(struct net_bridge *br, struct net_bridge_port_group *pg) { diff --git a/net/bridge/netfilter/nf_conntrack_bridge.c b/net/bridge/netfilter/nf_conntrack_bridge.c index 7ecb8a26bfa3a7..b5444335b86f2b 100644 --- a/net/bridge/netfilter/nf_conntrack_bridge.c +++ b/net/bridge/netfilter/nf_conntrack_bridge.c @@ -39,9 +39,13 @@ static int nf_br_ip_fragment(struct net *net, struct sock *sk, int err = 0; /* for offloaded checksums cleanup checksum before fragmentation */ - if (skb->ip_summed == CHECKSUM_PARTIAL && - (err = skb_checksum_help(skb))) - goto blackhole; + if (skb->ip_summed == CHECKSUM_PARTIAL) { + err = ip_check_csum_start(skb); + if (!err) + err = skb_checksum_help(skb); + if (err) + goto blackhole; + } iph = ip_hdr(skb); diff --git a/net/can/af_can.c b/net/can/af_can.c index 7bc86b176b4de3..34fe3b28d576f3 100644 --- a/net/can/af_can.c +++ b/net/can/af_can.c @@ -641,13 +641,10 @@ static int can_rcv_filter(struct can_dev_rcv_lists *dev_rcv_lists, struct sk_buf return matches; } -void can_set_skb_uid(struct sk_buff *skb) +void can_set_skb_uid(struct can_skb_ext *csx) { - /* create non-zero unique skb identifier together with *skb */ - while (!(skb->hash)) - skb->hash = atomic_inc_return(&skbcounter); - - skb->sw_hash = 1; + while (!(csx->can_skb_uid)) + csx->can_skb_uid = atomic_inc_return(&skbcounter); } EXPORT_SYMBOL(can_set_skb_uid); @@ -662,8 +659,6 @@ static void can_receive(struct sk_buff *skb, struct net_device *dev) atomic_long_inc(&pkg_stats->rx_frames); atomic_long_inc(&pkg_stats->rx_frames_delta); - can_set_skb_uid(skb); - rcu_read_lock(); /* deliver the packet to sockets listening on all devices */ @@ -687,8 +682,10 @@ static void can_receive(struct sk_buff *skb, struct net_device *dev) static int can_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { + struct can_skb_ext *csx = can_skb_ext_find(skb); + if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) || - !can_skb_ext_find(skb) || !can_is_can_skb(skb))) { + !csx || !can_is_can_skb(skb))) { pr_warn_once("PF_CAN: dropped non conform CAN skbuff: dev type %d, len %d\n", dev->type, skb->len); @@ -696,6 +693,14 @@ static int can_rcv(struct sk_buff *skb, struct net_device *dev, return NET_RX_DROP; } + /* create unshared CAN skb_extension for netem/mirred skb clones */ + csx = skb_ext_add(skb, SKB_EXT_CAN); + if (unlikely(!csx)) { + kfree_skb_reason(skb, SKB_DROP_REASON_NOMEM); + return NET_RX_DROP; + } + + can_set_skb_uid(csx); can_receive(skb, dev); return NET_RX_SUCCESS; } @@ -703,8 +708,10 @@ static int can_rcv(struct sk_buff *skb, struct net_device *dev, static int canfd_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { + struct can_skb_ext *csx = can_skb_ext_find(skb); + if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) || - !can_skb_ext_find(skb) || !can_is_canfd_skb(skb))) { + !csx || !can_is_canfd_skb(skb))) { pr_warn_once("PF_CAN: dropped non conform CAN FD skbuff: dev type %d, len %d\n", dev->type, skb->len); @@ -712,6 +719,14 @@ static int canfd_rcv(struct sk_buff *skb, struct net_device *dev, return NET_RX_DROP; } + /* create unshared CAN skb_extension for netem/mirred skb clones */ + csx = skb_ext_add(skb, SKB_EXT_CAN); + if (unlikely(!csx)) { + kfree_skb_reason(skb, SKB_DROP_REASON_NOMEM); + return NET_RX_DROP; + } + + can_set_skb_uid(csx); can_receive(skb, dev); return NET_RX_SUCCESS; } @@ -719,8 +734,10 @@ static int canfd_rcv(struct sk_buff *skb, struct net_device *dev, static int canxl_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { + struct can_skb_ext *csx = can_skb_ext_find(skb); + if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) || - !can_skb_ext_find(skb) || !can_is_canxl_skb(skb))) { + !csx || !can_is_canxl_skb(skb))) { pr_warn_once("PF_CAN: dropped non conform CAN XL skbuff: dev type %d, len %d\n", dev->type, skb->len); @@ -728,6 +745,14 @@ static int canxl_rcv(struct sk_buff *skb, struct net_device *dev, return NET_RX_DROP; } + /* create unshared CAN skb_extension for netem/mirred skb clones */ + csx = skb_ext_add(skb, SKB_EXT_CAN); + if (unlikely(!csx)) { + kfree_skb_reason(skb, SKB_DROP_REASON_NOMEM); + return NET_RX_DROP; + } + + can_set_skb_uid(csx); can_receive(skb, dev); return NET_RX_SUCCESS; } diff --git a/net/can/gw.c b/net/can/gw.c index 0ec99f68aa452d..5793cb2420ed3c 100644 --- a/net/can/gw.c +++ b/net/can/gw.c @@ -527,6 +527,9 @@ static void can_can_gw_rcv(struct sk_buff *skb, void *data) /* put the incremented hop counter in the cloned skb */ ncsx->can_gw_hops = csx->can_gw_hops + 1; + /* force a new CAN UID generation for the routed frame */ + ncsx->can_skb_uid = 0; + /* first processing of this CAN frame -> adjust to private hop limit */ if (gwj->limit_hops && ncsx->can_gw_hops == 1) ncsx->can_gw_hops = max_hops - gwj->limit_hops + 1; diff --git a/net/can/isotp.c b/net/can/isotp.c index 155530aedce2e3..f5dc9d04bd6862 100644 --- a/net/can/isotp.c +++ b/net/can/isotp.c @@ -891,7 +891,7 @@ static void isotp_send_cframe(struct isotp_sock *so) csx->can_iif = dev->ifindex; /* set uid in tx skb to identify CF echo frames */ - can_set_skb_uid(skb); + can_set_skb_uid(csx); cf = (struct canfd_frame *)skb->data; skb_put_zero(skb, so->ll.mtu); @@ -917,7 +917,7 @@ static void isotp_send_cframe(struct isotp_sock *so) pr_notice_once("can-isotp: cfecho is %08X != 0\n", old_cfecho); /* set consecutive frame echo tag */ - WRITE_ONCE(so->cfecho, skb->hash); + WRITE_ONCE(so->cfecho, csx->can_skb_uid); /* send frame with local echo enabled */ can_send_ret = can_send(skb, 1); @@ -969,18 +969,22 @@ static void isotp_rcv_echo(struct sk_buff *skb, void *data) { struct sock *sk = (struct sock *)data; struct isotp_sock *so = isotp_sk(sk); + struct can_skb_ext *csx = can_skb_ext_find(skb); /* only handle my own local echo CF/SF skb's (no FF!) */ if (skb->sk != sk) return; + if (WARN_ON_ONCE(!csx)) + return; + /* unlike isotp_rcv_fc()/isotp_rcv_cf(), not already under so->rx_lock * (no isotp_rcv() caller here), so take it ourselves */ spin_lock(&so->rx_lock); /* so->cfecho may since belong to a new transfer; recheck under lock */ - if (READ_ONCE(so->cfecho) != skb->hash) + if (READ_ONCE(so->cfecho) != csx->can_skb_uid) goto out_unlock; /* cancel local echo timeout */ @@ -1222,7 +1226,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) csx->can_iif = dev->ifindex; /* set uid in tx skb to identify CF echo frames */ - can_set_skb_uid(skb); + can_set_skb_uid(csx); so->tx.len = size; so->tx.idx = 0; @@ -1261,7 +1265,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) cf->data[ae] |= size; /* set CF echo tag for isotp_rcv_echo() (SF-mode) */ - WRITE_ONCE(so->cfecho, skb->hash); + WRITE_ONCE(so->cfecho, csx->can_skb_uid); } else { /* send first frame */ @@ -1278,7 +1282,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) so->txfc.bs = 0; /* set CF echo tag for isotp_rcv_echo() (CF-mode) */ - WRITE_ONCE(so->cfecho, skb->hash); + WRITE_ONCE(so->cfecho, csx->can_skb_uid); } else { /* standard flow control check */ new_state = ISOTP_WAIT_FIRST_FC; diff --git a/net/can/raw.c b/net/can/raw.c index 82d9c0499c95fa..0acd4f6c6dd672 100644 --- a/net/can/raw.c +++ b/net/can/raw.c @@ -77,7 +77,7 @@ MODULE_ALIAS("can-proto-1"); struct uniqframe { const struct sk_buff *skb; - u32 hash; + u32 can_skb_uid; unsigned int join_rx_count; }; @@ -133,12 +133,16 @@ static void raw_rcv(struct sk_buff *oskb, void *data) enum skb_drop_reason reason; struct sockaddr_can *addr; struct sk_buff *skb; + struct can_skb_ext *csx = can_skb_ext_find(oskb); unsigned int *pflags; /* check the received tx sock reference */ if (!ro->recv_own_msgs && oskb->sk == sk) return; + if (WARN_ON_ONCE(!csx)) + return; + /* make sure to not pass oversized frames to the socket */ if (!ro->fd_frames && can_is_canfd_skb(oskb)) return; @@ -165,7 +169,7 @@ static void raw_rcv(struct sk_buff *oskb, void *data) /* eliminate multiple filter matches for the same skb */ if (this_cpu_ptr(ro->uniq)->skb == oskb && - this_cpu_ptr(ro->uniq)->hash == oskb->hash) { + this_cpu_ptr(ro->uniq)->can_skb_uid == csx->can_skb_uid) { if (!ro->join_filters) return; @@ -175,7 +179,7 @@ static void raw_rcv(struct sk_buff *oskb, void *data) return; } else { this_cpu_ptr(ro->uniq)->skb = oskb; - this_cpu_ptr(ro->uniq)->hash = oskb->hash; + this_cpu_ptr(ro->uniq)->can_skb_uid = csx->can_skb_uid; this_cpu_ptr(ro->uniq)->join_rx_count = 1; /* drop first frame to check all enabled filters? */ if (ro->join_filters && ro->count > 1) diff --git a/net/core/dev.c b/net/core/dev.c index 6f75d1d1af32ce..1a06976e195630 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -10356,13 +10356,15 @@ EXPORT_SYMBOL_GPL(dev_xdp_prog_count); u8 dev_xdp_sb_prog_count(struct net_device *dev) { + struct bpf_prog *prog; u8 count = 0; int i; - for (i = 0; i < __MAX_XDP_MODE; i++) - if (dev->xdp_state[i].prog && - !dev->xdp_state[i].prog->aux->xdp_has_frags) + for (i = 0; i < __MAX_XDP_MODE; i++) { + prog = dev_xdp_prog(dev, i); + if (prog && !prog->aux->xdp_has_frags) count++; + } return count; } @@ -10742,11 +10744,12 @@ static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog, bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode); err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL, xdp_link->flags, new_prog); + if (!err) + old_prog = xchg(&link->prog, new_prog); netdev_unlock_ops(xdp_link->dev); if (err) goto out_unlock; - old_prog = xchg(&link->prog, new_prog); bpf_prog_put(old_prog); out_unlock: diff --git a/net/core/flow_dissector.c b/net/core/flow_dissector.c index 8aa4f9b4df8101..1be6c739e3c718 100644 --- a/net/core/flow_dissector.c +++ b/net/core/flow_dissector.c @@ -1023,6 +1023,8 @@ u32 bpf_flow_dissect(struct bpf_prog *prog, struct bpf_flow_dissector *ctx, result = bpf_prog_run_pin_on_cpu(prog, ctx); + /* bpf_flow_keys offsets are u16: do not let @hlen be truncated. */ + hlen = min_t(int, hlen, U16_MAX); flow_keys->nhoff = clamp_t(u16, flow_keys->nhoff, nhoff, hlen); flow_keys->thoff = clamp_t(u16, flow_keys->thoff, flow_keys->nhoff, hlen); @@ -1071,6 +1073,7 @@ bool __skb_flow_dissect(const struct net *net, int mpls_lse = 0; int num_hdrs = 0; u8 ip_proto = 0; + u32 thoff; bool ret; if (!data) { @@ -1692,7 +1695,13 @@ bool __skb_flow_dissect(const struct net *net, ret = true; out: - key_control->thoff = min_t(u16, nhoff, skb ? skb->len : hlen); + thoff = min_t(u32, nhoff, skb ? skb->len : hlen); + if (unlikely(thoff > U16_MAX)) { + /* Cannot be represented in key_control->thoff. */ + thoff = U16_MAX; + ret = false; + } + key_control->thoff = thoff; key_basic->n_proto = proto; key_basic->ip_proto = ip_proto; diff --git a/net/core/skbuff.c b/net/core/skbuff.c index a5e46d1007070e..0aa0f1a377e0ef 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -3639,8 +3639,12 @@ __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset, pos = copy; } - if (!skb_frags_readable(skb)) + if (!skb_frags_readable(skb)) { + /* Don't hand the caller a buffer with stale bytes in it. */ + if (len > 0) + memset(to, 0, len); return 0; + } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; diff --git a/net/devlink/core.c b/net/devlink/core.c index fe9f6a0a67d5b3..42c16940e4c438 100644 --- a/net/devlink/core.c +++ b/net/devlink/core.c @@ -96,13 +96,19 @@ static void devlink_rel_nested_in_notify_work(struct work_struct *work) return; reschedule_work: - schedule_delayed_work(&rel->nested_in.notify_work, 1); + /* The work may have been queued again meanwhile, which took its own + * reference. Drop ours in that case. + */ + if (!schedule_delayed_work(&rel->nested_in.notify_work, 1)) + __devlink_rel_put(rel); } static void devlink_rel_nested_in_notify_work_schedule(struct devlink_rel *rel) { __devlink_rel_get(rel); - schedule_delayed_work(&rel->nested_in.notify_work, 0); + /* The pending work holds a reference already, drop the new one. */ + if (!schedule_delayed_work(&rel->nested_in.notify_work, 0)) + __devlink_rel_put(rel); } static struct devlink_rel *devlink_rel_alloc(void) diff --git a/net/ipv4/cipso_ipv4.c b/net/ipv4/cipso_ipv4.c index a05aa075de1a5b..1aacbbeffbc647 100644 --- a/net/ipv4/cipso_ipv4.c +++ b/net/ipv4/cipso_ipv4.c @@ -2287,6 +2287,14 @@ int cipso_v4_skbuff_delattr(struct sk_buff *skb) new_hdr_len - new_hdr_len_actual); opt->optlen -= hdr_len_delta; + if (opt->srr > opt->cipso) + opt->srr -= cipso_len; + if (opt->rr > opt->cipso) + opt->rr -= cipso_len; + if (opt->ts > opt->cipso) + opt->ts -= cipso_len; + if (opt->router_alert > opt->cipso) + opt->router_alert -= cipso_len; opt->cipso = 0; opt->is_changed = 1; if (hdr_len_delta != 0) { diff --git a/net/ipv4/fib_semantics.c b/net/ipv4/fib_semantics.c index 0c25f6dfb8a6f9..92cfc838e5d3b4 100644 --- a/net/ipv4/fib_semantics.c +++ b/net/ipv4/fib_semantics.c @@ -542,6 +542,9 @@ size_t fib_nlmsg_size(struct fib_info *fi) struct fib_nh_common *nhc = fib_info_nhc(fi, i); size_t nhsize; + if (!nhc) + break; + nhsize = fib_nexthop_nlmsg_size(nhc, nhs != 1); if (nhs != 1) diff --git a/net/ipv4/fib_trie.c b/net/ipv4/fib_trie.c index 6badad29593b71..58be0752b0350f 100644 --- a/net/ipv4/fib_trie.c +++ b/net/ipv4/fib_trie.c @@ -1079,8 +1079,6 @@ void fib_alias_hw_flags_set(struct net *net, const struct fib_rt_info *fri) err = fib_dump_info(skb, 0, 0, RTM_NEWROUTE, fri, 0); if (err < 0) { - /* -EMSGSIZE implies BUG in fib_nlmsg_size() */ - WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } diff --git a/net/ipv4/ip_output.c b/net/ipv4/ip_output.c index a24cc8ee11d3ea..eaa6fabda347e9 100644 --- a/net/ipv4/ip_output.c +++ b/net/ipv4/ip_output.c @@ -771,9 +771,13 @@ int ip_do_fragment(struct net *net, struct sock *sk, struct sk_buff *skb, int err = 0; /* for offloaded checksums cleanup checksum before fragmentation */ - if (skb->ip_summed == CHECKSUM_PARTIAL && - (err = skb_checksum_help(skb))) - goto fail; + if (skb->ip_summed == CHECKSUM_PARTIAL) { + err = ip_check_csum_start(skb); + if (!err) + err = skb_checksum_help(skb); + if (err) + goto fail; + } /* * Point into the IP datagram header. diff --git a/net/ipv4/route.c b/net/ipv4/route.c index f07231447883f3..196ca7e8acff01 100644 --- a/net/ipv4/route.c +++ b/net/ipv4/route.c @@ -1080,6 +1080,8 @@ static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu) for (nhsel = 0; nhsel < fib_info_num_path(res.fi); nhsel++) { nhc = fib_info_nhc(res.fi, nhsel); + if (!nhc) + break; update_or_create_fnhe(nhc, fl4->daddr, 0, mtu, lock, jiffies + net->ipv4.ip_rt_mtu_expires); } @@ -3163,6 +3165,9 @@ int fib_dump_info_fnhe(struct sk_buff *skb, struct netlink_callback *cb, struct fnhe_hash_bucket *bucket; int err; + if (!nhc) + break; + if (nhc->nhc_flags & RTNH_F_DEAD) continue; diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index ce0a111f9eb732..19663713ef92af 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -1908,6 +1908,8 @@ static bool can_map_frag(const skb_frag_t *frag) if (skb_frag_size(frag) != PAGE_SIZE || skb_frag_off(frag)) return false; + if (skb_frag_is_net_iov(frag)) + return false; page = skb_frag_page(frag); diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index 59afce196079a8..a50dccfbf4205f 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -908,6 +908,15 @@ static struct sock *__udp4_lib_err_encap(struct net *net, return sk; } +static void udp_err_update_exception(struct net *net, struct sk_buff *skb, + int type, int code, u32 info) +{ + if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED) + ipv4_update_pmtu(skb, net, info, 0, IPPROTO_UDP); + else if (type == ICMP_REDIRECT) + ipv4_redirect(skb, net, 0, IPPROTO_UDP); +} + /* * This routine is called by the ICMP module when it gets some * sort of error condition. If err < 0 then the socket should @@ -931,6 +940,8 @@ int udp_err(struct sk_buff *skb, u32 info) int harderr; int err; + udp_err_update_exception(net, skb, type, code, info); + uh = (struct udphdr *)(skb->data + (iph->ihl << 2)); sk = __udp4_lib_lookup(net, iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex, diff --git a/net/ipv6/ip6_gre.c b/net/ipv6/ip6_gre.c index e6913a7f688117..6d7c547232a2d7 100644 --- a/net/ipv6/ip6_gre.c +++ b/net/ipv6/ip6_gre.c @@ -923,7 +923,6 @@ static netdev_tx_t ip6erspan_tunnel_xmit(struct sk_buff *skb, { struct ip_tunnel_info *tun_info = NULL; struct ip6_tnl *t = netdev_priv(dev); - struct dst_entry *dst = skb_dst(skb); IP_TUNNEL_DECLARE_FLAGS(flags) = { }; bool truncate = false; int encap_limit = -1; @@ -1059,12 +1058,6 @@ static netdev_tx_t ip6erspan_tunnel_xmit(struct sk_buff *skb, gre_build_header(skb, 8, flags, proto, 0, htonl(atomic_fetch_inc(&t->o_seqno))); - /* TooBig packet may have updated dst->dev's mtu */ - if (!t->parms.collect_md && dst) { - mtu = READ_ONCE(dst_dev(dst)->mtu); - if (dst_mtu(dst) > mtu) - dst->ops->update_pmtu(dst, NULL, skb, mtu, false); - } err = ip6_tnl_xmit(skb, dev, dsfield, &fl6, encap_limit, &mtu, NEXTHDR_GRE); if (err != 0) { diff --git a/net/ipv6/route.c b/net/ipv6/route.c index 8fddcc631fcb62..5d80a025c3e6d1 100644 --- a/net/ipv6/route.c +++ b/net/ipv6/route.c @@ -3261,7 +3261,7 @@ void ip6_redirect_no_header(struct sk_buff *skb, struct net *net, int oif) void ip6_sk_redirect(struct sk_buff *skb, struct sock *sk) { - ip6_redirect(skb, sock_net(sk), sk->sk_bound_dev_if, + ip6_redirect(skb, sock_net(sk), skb->dev->ifindex, READ_ONCE(sk->sk_mark), sk_uid(sk)); } @@ -6474,8 +6474,6 @@ void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i, err = rt6_fill_node(net, skb, f6i, NULL, NULL, NULL, 0, RTM_NEWROUTE, 0, 0, 0); if (err < 0) { - /* -EMSGSIZE implies BUG in rt6_nlmsg_size() */ - WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } diff --git a/net/ipv6/udp.c b/net/ipv6/udp.c index 15e032194eccc3..b73cf02ac1b6e6 100644 --- a/net/ipv6/udp.c +++ b/net/ipv6/udp.c @@ -690,6 +690,17 @@ static struct sock *__udp6_lib_err_encap(struct net *net, return sk; } +static void udpv6_err_update_exception(struct net *net, struct sk_buff *skb, + u8 type, __be32 info) +{ + if (type == ICMPV6_PKT_TOOBIG) + ip6_update_pmtu(skb, net, info, skb->dev->ifindex, 0, + sock_net_uid(net, NULL)); + else if (type == NDISC_REDIRECT) + ip6_redirect(skb, net, skb->dev->ifindex, 0, + sock_net_uid(net, NULL)); +} + static int udpv6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, u8 type, u8 code, int offset, __be32 info) { @@ -703,6 +714,8 @@ static int udpv6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, int harderr; int err; + udpv6_err_update_exception(net, skb, type, info); + daddr = seg6_get_daddr(skb, opt) ? : &hdr->daddr; saddr = &hdr->saddr; sk = __udp6_lib_lookup(net, daddr, uh->dest, saddr, uh->source, diff --git a/net/mac80211/debugfs.c b/net/mac80211/debugfs.c index f36cc25903050f..3a671225c12777 100644 --- a/net/mac80211/debugfs.c +++ b/net/mac80211/debugfs.c @@ -210,11 +210,13 @@ static ssize_t aql_pending_read(struct file *file, "VI %u us\n" "BE %u us\n" "BK %u us\n" + "MC %u us\n" "total %u us\n", atomic_read(&local->aql_ac_pending_airtime[IEEE80211_AC_VO]), atomic_read(&local->aql_ac_pending_airtime[IEEE80211_AC_VI]), atomic_read(&local->aql_ac_pending_airtime[IEEE80211_AC_BE]), atomic_read(&local->aql_ac_pending_airtime[IEEE80211_AC_BK]), + atomic_read(&local->aql_mc_pending_airtime), atomic_read(&local->aql_total_pending_airtime)); return simple_read_from_buffer(user_buf, count, ppos, buf, len); @@ -239,7 +241,8 @@ static ssize_t aql_txq_limit_read(struct file *file, "VO %u %u\n" "VI %u %u\n" "BE %u %u\n" - "BK %u %u\n", + "BK %u %u\n" + "MC %u\n", local->aql_txq_limit_low[IEEE80211_AC_VO], local->aql_txq_limit_high[IEEE80211_AC_VO], local->aql_txq_limit_low[IEEE80211_AC_VI], @@ -247,7 +250,8 @@ static ssize_t aql_txq_limit_read(struct file *file, local->aql_txq_limit_low[IEEE80211_AC_BE], local->aql_txq_limit_high[IEEE80211_AC_BE], local->aql_txq_limit_low[IEEE80211_AC_BK], - local->aql_txq_limit_high[IEEE80211_AC_BK]); + local->aql_txq_limit_high[IEEE80211_AC_BK], + local->aql_txq_limit_mc); return simple_read_from_buffer(user_buf, count, ppos, buf, len); } @@ -273,6 +277,11 @@ static ssize_t aql_txq_limit_write(struct file *file, else buf[count] = '\0'; + if (sscanf(buf, "mcast %u", &q_limit_low) == 1) { + local->aql_txq_limit_mc = q_limit_low; + return count; + } + if (sscanf(buf, "%u %u %u", &ac, &q_limit_low, &q_limit_high) != 3) return -EINVAL; diff --git a/net/mac80211/ieee80211_i.h b/net/mac80211/ieee80211_i.h index 011ec7fbb71185..2854dcc86b21b3 100644 --- a/net/mac80211/ieee80211_i.h +++ b/net/mac80211/ieee80211_i.h @@ -1464,10 +1464,12 @@ struct ieee80211_local { spinlock_t handle_wake_tx_queue_lock; u16 airtime_flags; + u32 aql_txq_limit_mc; u32 aql_txq_limit_low[IEEE80211_NUM_ACS]; u32 aql_txq_limit_high[IEEE80211_NUM_ACS]; u32 aql_threshold; atomic_t aql_total_pending_airtime; + atomic_t aql_mc_pending_airtime; atomic_t aql_ac_pending_airtime[IEEE80211_NUM_ACS]; const struct ieee80211_ops *ops; diff --git a/net/mac80211/main.c b/net/mac80211/main.c index 8edfef2b57f80f..d5ef44f2b3f2dd 100644 --- a/net/mac80211/main.c +++ b/net/mac80211/main.c @@ -988,6 +988,7 @@ struct ieee80211_hw *ieee80211_alloc_hw_nm(size_t priv_data_len, spin_lock_init(&local->rx_path_lock); spin_lock_init(&local->queue_stop_reason_lock); + local->aql_txq_limit_mc = IEEE80211_DEFAULT_AQL_TXQ_LIMIT_MC; for (i = 0; i < IEEE80211_NUM_ACS; i++) { INIT_LIST_HEAD(&local->active_txqs[i]); spin_lock_init(&local->active_txq_lock[i]); diff --git a/net/mac80211/sta_info.c b/net/mac80211/sta_info.c index 01d70f71c43ec2..ce7a3f839ce2eb 100644 --- a/net/mac80211/sta_info.c +++ b/net/mac80211/sta_info.c @@ -2493,13 +2493,28 @@ EXPORT_SYMBOL(ieee80211_sta_recalc_aggregates); void ieee80211_sta_update_pending_airtime(struct ieee80211_local *local, struct sta_info *sta, u8 ac, - u16 tx_airtime, bool tx_completed) + u16 tx_airtime, bool tx_completed, + bool mcast) { int tx_pending; if (!wiphy_ext_feature_isset(local->hw.wiphy, NL80211_EXT_FEATURE_AQL)) return; + if (mcast) { + if (!tx_completed) { + atomic_add(tx_airtime, &local->aql_mc_pending_airtime); + return; + } + + tx_pending = atomic_sub_return(tx_airtime, + &local->aql_mc_pending_airtime); + if (tx_pending < 0) + atomic_cmpxchg(&local->aql_mc_pending_airtime, + tx_pending, 0); + return; + } + if (!tx_completed) { if (sta) atomic_add(tx_airtime, diff --git a/net/mac80211/sta_info.h b/net/mac80211/sta_info.h index 5da3142d8516ef..ee0d32877c5b47 100644 --- a/net/mac80211/sta_info.h +++ b/net/mac80211/sta_info.h @@ -147,7 +147,8 @@ struct airtime_info { void ieee80211_sta_update_pending_airtime(struct ieee80211_local *local, struct sta_info *sta, u8 ac, - u16 tx_airtime, bool tx_completed); + u16 tx_airtime, bool tx_completed, + bool mcast); struct sta_info; diff --git a/net/mac80211/status.c b/net/mac80211/status.c index e10e5bcc279b6a..a9da9fe87cf157 100644 --- a/net/mac80211/status.c +++ b/net/mac80211/status.c @@ -774,7 +774,7 @@ static void ieee80211_report_used_skb(struct ieee80211_local *local, ieee80211_sta_update_pending_airtime(local, sta, skb_get_queue_mapping(skb), tx_time_est, - true); + true, info->tx_time_mc); rcu_read_unlock(); } @@ -1255,10 +1255,11 @@ void ieee80211_tx_status_ext(struct ieee80211_hw *hw, /* Do this here to avoid the expensive lookup of the sta * in ieee80211_report_used_skb(). */ + bool mcast = IEEE80211_SKB_CB(skb)->tx_time_mc; ieee80211_sta_update_pending_airtime(local, sta, skb_get_queue_mapping(skb), tx_time_est, - true); + true, mcast); ieee80211_info_set_tx_time_est(IEEE80211_SKB_CB(skb), 0); } diff --git a/net/mac80211/tx.c b/net/mac80211/tx.c index 65c5a6519b8953..3e5b1c05f4a3e1 100644 --- a/net/mac80211/tx.c +++ b/net/mac80211/tx.c @@ -4083,20 +4083,20 @@ struct sk_buff *ieee80211_tx_dequeue(struct ieee80211_hw *hw, encap_out: info->control.vif = vif; - if (tx.sta && - wiphy_ext_feature_isset(local->hw.wiphy, NL80211_EXT_FEATURE_AQL)) { - bool ampdu = txq->ac != IEEE80211_AC_VO; + if (wiphy_ext_feature_isset(local->hw.wiphy, NL80211_EXT_FEATURE_AQL)) { + bool ampdu = txq->sta && txq->ac != IEEE80211_AC_VO; u32 airtime; airtime = ieee80211_calc_expected_tx_airtime(hw, vif, txq->sta, skb->len, ampdu); - if (airtime) { - airtime = ieee80211_info_set_tx_time_est(info, airtime); - ieee80211_sta_update_pending_airtime(local, tx.sta, - txq->ac, - airtime, - false); - } + if (!airtime) + return skb; + + airtime = ieee80211_info_set_tx_time_est(info, airtime); + info->tx_time_mc = !tx.sta; + ieee80211_sta_update_pending_airtime(local, tx.sta, txq->ac, + airtime, false, + info->tx_time_mc); } return skb; @@ -4148,6 +4148,7 @@ struct ieee80211_txq *ieee80211_next_txq(struct ieee80211_hw *hw, u8 ac) struct ieee80211_txq *ret = NULL; struct txq_info *txqi = NULL, *head = NULL; bool found_eligible_txq = false; + bool aql_check; spin_lock_bh(&local->active_txq_lock[ac]); @@ -4171,26 +4172,28 @@ struct ieee80211_txq *ieee80211_next_txq(struct ieee80211_hw *hw, u8 ac) if (!head) head = txqi; + aql_check = ieee80211_txq_airtime_check(hw, &txqi->txq); + if (aql_check) + found_eligible_txq = true; + if (txqi->txq.sta) { struct sta_info *sta = container_of(txqi->txq.sta, struct sta_info, sta); - bool aql_check = ieee80211_txq_airtime_check(hw, &txqi->txq); - s32 deficit = ieee80211_sta_deficit(sta, txqi->txq.ac); - if (aql_check) - found_eligible_txq = true; - - if (deficit < 0) + if (ieee80211_sta_deficit(sta, txqi->txq.ac) < 0) { sta->airtime[txqi->txq.ac].deficit += sta->airtime_weight; - if (deficit < 0 || !aql_check) { - list_move_tail(&txqi->schedule_order, - &local->active_txqs[txqi->txq.ac]); - goto begin; + aql_check = false; } } + if (!aql_check) { + list_move_tail(&txqi->schedule_order, + &local->active_txqs[txqi->txq.ac]); + goto begin; + } + if (txqi->schedule_round == local->schedule_round[ac]) goto out; @@ -4257,7 +4260,8 @@ bool ieee80211_txq_airtime_check(struct ieee80211_hw *hw, return true; if (!txq->sta) - return true; + return atomic_read(&local->aql_mc_pending_airtime) < + local->aql_txq_limit_mc; if (unlikely(txq->tid == IEEE80211_NUM_TIDS)) return true; @@ -4277,6 +4281,24 @@ bool ieee80211_txq_airtime_check(struct ieee80211_hw *hw, } EXPORT_SYMBOL(ieee80211_txq_airtime_check); +u32 ieee80211_txq_aql_pending(struct ieee80211_hw *hw, + struct ieee80211_txq *txq) +{ + struct ieee80211_local *local = hw_to_local(hw); + struct sta_info *sta; + + if (unlikely(txq->tid == IEEE80211_NUM_TIDS)) + return 0; + + if (!txq->sta) + return atomic_read(&local->aql_mc_pending_airtime); + + sta = container_of(txq->sta, struct sta_info, sta); + + return atomic_read(&sta->airtime[txq->ac].aql_tx_pending); +} +EXPORT_SYMBOL(ieee80211_txq_aql_pending); + static bool ieee80211_txq_schedule_airtime_check(struct ieee80211_local *local, u8 ac) { @@ -4306,15 +4328,15 @@ bool ieee80211_txq_may_transmit(struct ieee80211_hw *hw, spin_lock_bh(&local->active_txq_lock[ac]); - if (!txqi->txq.sta) - goto out; - if (list_empty(&txqi->schedule_order)) goto out; if (!ieee80211_txq_schedule_airtime_check(local, ac)) goto out; + if (!txqi->txq.sta) + goto out; + list_for_each_entry_safe(iter, tmp, &local->active_txqs[ac], schedule_order) { if (iter == txqi) diff --git a/net/netfilter/nfnetlink_queue.c b/net/netfilter/nfnetlink_queue.c index ec5e7716df8b5d..8a5240a9be222d 100644 --- a/net/netfilter/nfnetlink_queue.c +++ b/net/netfilter/nfnetlink_queue.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -667,6 +668,12 @@ static int nfqnl_put_bridge(struct nf_queue_entry *entry, struct sk_buff *skb) static int nf_queue_checksum_help(struct sk_buff *entskb) { + if (entskb->protocol == htons(ETH_P_IP)) { + if (!pskb_network_may_pull(entskb, sizeof(struct iphdr)) || + ip_check_csum_start(entskb)) + return -EINVAL; + } + if (skb_csum_is_sctp(entskb)) return skb_crc32c_csum_help(entskb); diff --git a/net/netfilter/xt_CHECKSUM.c b/net/netfilter/xt_CHECKSUM.c index 9d99f5a3d1764b..1fb0f8118404d6 100644 --- a/net/netfilter/xt_CHECKSUM.c +++ b/net/netfilter/xt_CHECKSUM.c @@ -15,6 +15,7 @@ #include #include +#include MODULE_LICENSE("GPL"); MODULE_AUTHOR("Michael S. Tsirkin "); @@ -25,8 +26,11 @@ MODULE_ALIAS("ip6t_CHECKSUM"); static unsigned int checksum_tg(struct sk_buff *skb, const struct xt_action_param *par) { - if (skb->ip_summed == CHECKSUM_PARTIAL && !skb_is_gso(skb)) + if (skb->ip_summed == CHECKSUM_PARTIAL && !skb_is_gso(skb)) { + if (xt_family(par) == NFPROTO_IPV4 && ip_check_csum_start(skb)) + return NF_DROP; skb_checksum_help(skb); + } return XT_CONTINUE; } diff --git a/net/openvswitch/actions.c b/net/openvswitch/actions.c index dc5ff859f11451..27152bca8a8ce7 100644 --- a/net/openvswitch/actions.c +++ b/net/openvswitch/actions.c @@ -358,7 +358,12 @@ static void set_ip_addr(struct sk_buff *skb, struct iphdr *nh, static void update_ipv6_checksum(struct sk_buff *skb, u8 l4_proto, __be32 addr[4], const __be32 new_addr[4]) { - int transport_len = skb->len - skb_transport_offset(skb); + int transport_len; + + if (l4_proto == NEXTHDR_FRAGMENT) + return; + + transport_len = skb->len - skb_transport_offset(skb); if (l4_proto == NEXTHDR_TCP) { if (likely(transport_len >= sizeof(struct tcphdr))) diff --git a/net/openvswitch/datapath.c b/net/openvswitch/datapath.c index b601e4859de920..21bc56e796277e 100644 --- a/net/openvswitch/datapath.c +++ b/net/openvswitch/datapath.c @@ -1529,6 +1529,12 @@ static int ovs_flow_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb) return -ENODEV; } + /* + * Not needed for safety. Stops every spin_unlock_bh() in + * ovs_flow_stats_get() from running the softirq backlog. + */ + local_bh_disable(); + ti = rcu_dereference(dp->table.ti); for (;;) { struct sw_flow *flow; @@ -1549,6 +1555,8 @@ static int ovs_flow_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb) cb->args[0] = bucket; cb->args[1] = obj; } + + local_bh_enable(); rcu_read_unlock(); return skb->len; } diff --git a/net/packet/af_packet.c b/net/packet/af_packet.c index 8865c1a4266796..52ae3d875e971b 100644 --- a/net/packet/af_packet.c +++ b/net/packet/af_packet.c @@ -1911,7 +1911,8 @@ static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev, spkt = &PACKET_SKB_CB(skb)->sa.pkt; - skb_push(skb, skb->data - skb_mac_header(skb)); + if (dev_has_header(dev)) + skb_push(skb, skb->data - skb_mac_header(skb)); /* * The SOCK_PACKET socket receives _all_ frames. @@ -1942,8 +1943,7 @@ static void packet_parse_headers(struct sk_buff *skb, struct socket *sock) /* On TX skb->data is the L2 header; anchor it for all socket types. */ skb_reset_mac_header(skb); - if ((!skb->protocol || skb->protocol == htons(ETH_P_ALL)) && - sock->type == SOCK_RAW) + if (!skb->protocol && sock->type == SOCK_RAW) skb->protocol = dev_parse_header_protocol(skb); skb_probe_transport_header(skb); @@ -2613,7 +2613,8 @@ static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb, struct page *page; int err; - skb->protocol = proto; + if (proto != htons(ETH_P_ALL)) + skb->protocol = proto; skb->dev = dev; skb->priority = sockc->priority; skb->mark = sockc->mark; @@ -2677,8 +2678,6 @@ static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb, if (unlikely(!skb->len)) return -EINVAL; - packet_parse_headers(skb, sock); - return tp_len; } @@ -2918,9 +2917,13 @@ static int tpacket_snd(struct packet_sock *po, struct msghdr *msg) tp_len = -EINVAL; goto tpacket_error; } - virtio_net_hdr_set_proto(skb, &vnet_hdr); } + packet_parse_headers(skb, po->sk.sk_socket); + + if (has_vnet_hdr) + virtio_net_hdr_set_proto(skb, &vnet_hdr); + uarg = kmalloc(sizeof(*uarg), GFP_KERNEL); if (unlikely(!uarg)) { if (likely(len_sum > 0)) @@ -3121,7 +3124,8 @@ static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) goto out_free; } - skb->protocol = proto; + if (proto != htons(ETH_P_ALL)) + skb->protocol = proto; skb->dev = dev; skb->priority = sockc.priority; skb->mark = sockc.mark; @@ -3130,16 +3134,18 @@ static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) if (unlikely(extra_len == 4)) skb->no_fcs = 1; - packet_parse_headers(skb, sock); - if (vnet_hdr_sz) { err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le()); if (err) goto out_free; len += vnet_hdr_sz; - virtio_net_hdr_set_proto(skb, &vnet_hdr); } + packet_parse_headers(skb, sock); + + if (vnet_hdr_sz) + virtio_net_hdr_set_proto(skb, &vnet_hdr); + err = packet_xmit(po, skb); if (unlikely(err != 0)) { diff --git a/net/sched/cls_route.c b/net/sched/cls_route.c index 0f211f030fd9a7..dca812a7526981 100644 --- a/net/sched/cls_route.c +++ b/net/sched/cls_route.c @@ -434,6 +434,12 @@ static int route4_set_parms(struct net *net, struct tcf_proto *tp, if (handle && (!fold || nhandle == (handle & ~0x7F00))) nhandle |= handle & 0x7F00; + if (fold && !tb[TCA_ROUTE4_TO] && !tb[TCA_ROUTE4_FROM] && + !tb[TCA_ROUTE4_IIF] && nhandle != fold->handle) { + NL_SET_ERR_MSG(extack, "Routing attributes required"); + return -EINVAL; + } + if (handle && !fold && nhandle != handle) { NL_SET_ERR_MSG_FMT(extack, "Handle mismatch constructed: %x (expected: %x)", diff --git a/net/sched/em_text.c b/net/sched/em_text.c index 4132f8c3c5fc95..bc45edb8c03bff 100644 --- a/net/sched/em_text.c +++ b/net/sched/em_text.c @@ -58,6 +58,9 @@ static int em_text_change(struct net *net, void *data, int len, if (len < sizeof(*conf) || len < (sizeof(*conf) + conf->pattern_len)) return -EINVAL; + if (!memchr(conf->algo, '\0', sizeof(conf->algo))) + return -EINVAL; + if (conf->from_layer > conf->to_layer) return -EINVAL; diff --git a/net/sctp/socket.c b/net/sctp/socket.c index 4652fd90d9a6c4..e35692dd8d303b 100644 --- a/net/sctp/socket.c +++ b/net/sctp/socket.c @@ -7569,11 +7569,7 @@ static int sctp_getsockopt_pr_streamstatus(struct sock *sk, int len, /* Not allocated yet, means all stats are 0 */ params.sprstat_abandoned_unsent = 0; params.sprstat_abandoned_sent = 0; - retval = 0; - goto out; - } - - if (policy == SCTP_PR_SCTP_ALL) { + } else if (policy == SCTP_PR_SCTP_ALL) { params.sprstat_abandoned_unsent = 0; params.sprstat_abandoned_sent = 0; for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) { diff --git a/net/smc/af_smc.c b/net/smc/af_smc.c index e9f93b3ab435bb..8b3ee70f8433f4 100644 --- a/net/smc/af_smc.c +++ b/net/smc/af_smc.c @@ -2784,6 +2784,7 @@ int smc_getname(struct socket *sock, struct sockaddr *addr, int peer) { struct smc_sock *smc; + int rc = -EBADF; if (peer && (sock->sk->sk_state != SMC_ACTIVE) && (sock->sk->sk_state != SMC_APPCLOSEWAIT1)) @@ -2791,7 +2792,11 @@ int smc_getname(struct socket *sock, struct sockaddr *addr, smc = smc_sk(sock->sk); - return smc->clcsock->ops->getname(smc->clcsock, addr, peer); + mutex_lock(&smc->clcsock_release_lock); + if (smc->clcsock) + rc = smc->clcsock->ops->getname(smc->clcsock, addr, peer); + mutex_unlock(&smc->clcsock_release_lock); + return rc; } int smc_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) diff --git a/net/strparser/strparser.c b/net/strparser/strparser.c index a23f4b4dfc6733..d5b17d099a0e78 100644 --- a/net/strparser/strparser.c +++ b/net/strparser/strparser.c @@ -505,12 +505,16 @@ void strp_unpause(struct strparser *strp) EXPORT_SYMBOL_GPL(strp_unpause); /* strp must already be stopped so that strp_recv will no longer be called. - * Note that strp_done is not called with the lower socket held. + * Note that strp_done must not be called with the lower socket held. */ void strp_done(struct strparser *strp) { WARN_ON(!strp->stopped); + lock_sock(strp->sk); + /* sync with pending strp_recv */ + release_sock(strp->sk); + cancel_delayed_work_sync(&strp->msg_timer_work); cancel_work_sync(&strp->work); diff --git a/net/tipc/node.c b/net/tipc/node.c index 683a136e53efcf..5a7487dab31dae 100644 --- a/net/tipc/node.c +++ b/net/tipc/node.c @@ -2419,8 +2419,11 @@ static struct tipc_node *tipc_node_find_by_name(struct net *net, } } tipc_node_read_unlock(n); - if (found_node) + if (found_node) { + if (!kref_get_unless_zero(&found_node->kref)) + found_node = NULL; break; + } } rcu_read_unlock(); @@ -2505,6 +2508,7 @@ int tipc_nl_node_set_link(struct sk_buff *skb, struct genl_info *info) tipc_node_read_unlock(node); tipc_bearer_xmit(net, bearer_id, &xmitq, &node->links[bearer_id].maddr, NULL); + tipc_node_put(node); return res; } @@ -2556,12 +2560,14 @@ int tipc_nl_node_get_link(struct sk_buff *skb, struct genl_info *info) link = node->links[bearer_id].link; if (!link) { tipc_node_read_unlock(node); + tipc_node_put(node); err = -EINVAL; goto err_free; } err = __tipc_nl_add_link(net, &msg, link, 0); tipc_node_read_unlock(node); + tipc_node_put(node); if (err) goto err_free; } @@ -2632,11 +2638,13 @@ int tipc_nl_node_reset_link_stats(struct sk_buff *skb, struct genl_info *info) if (!link) { spin_unlock_bh(&le->lock); tipc_node_read_unlock(node); + tipc_node_put(node); return -EINVAL; } tipc_link_reset_stats(link); spin_unlock_bh(&le->lock); tipc_node_read_unlock(node); + tipc_node_put(node); return 0; } diff --git a/net/tipc/topsrv.c b/net/tipc/topsrv.c index af530c9ed8402c..82e9f44e2fe46e 100644 --- a/net/tipc/topsrv.c +++ b/net/tipc/topsrv.c @@ -55,7 +55,7 @@ /** * struct tipc_topsrv - TIPC server structure * @conn_idr: identifier set of connection - * @idr_lock: protect the connection identifier set + * @idr_lock: protect the connection identifier set and listener * @idr_in_use: amount of allocated identifier entry * @net: network namespace instance * @awork: accept work item @@ -218,6 +218,10 @@ static struct tipc_conn *tipc_conn_lookup(struct tipc_topsrv *s, int conid) struct tipc_conn *con; spin_lock_bh(&s->idr_lock); + if (!s->listener) { + spin_unlock_bh(&s->idr_lock); + return NULL; + } con = idr_find(&s->conn_idr, conid); if (!connected(con) || !kref_get_unless_zero(&con->kref)) con = NULL; @@ -301,10 +305,20 @@ static void tipc_conn_send_to_sock(struct tipc_conn *con) static void tipc_conn_send_work(struct work_struct *work) { struct tipc_conn *con = container_of(work, struct tipc_conn, swork); + struct tipc_topsrv *srv; + + srv = con->server; + spin_lock_bh(&srv->idr_lock); + if (!srv->listener) { + spin_unlock_bh(&srv->idr_lock); + goto out; + } + spin_unlock_bh(&srv->idr_lock); if (connected(con)) tipc_conn_send_to_sock(con); +out: conn_put(con); } @@ -334,8 +348,14 @@ void tipc_topsrv_queue_evt(struct net *net, int conid, list_add_tail(&e->list, &con->outqueue); spin_unlock_bh(&con->outqueue_lock); - if (queue_work(srv->send_wq, &con->swork)) - return; + spin_lock_bh(&srv->idr_lock); + if (srv->listener) { + if (queue_work(srv->send_wq, &con->swork)) { + spin_unlock_bh(&srv->idr_lock); + return; + } + } + spin_unlock_bh(&srv->idr_lock); err: conn_put(con); } @@ -346,14 +366,20 @@ void tipc_topsrv_queue_evt(struct net *net, int conid, */ static void tipc_conn_write_space(struct sock *sk) { + struct tipc_topsrv *srv; struct tipc_conn *con; read_lock_bh(&sk->sk_callback_lock); con = sk->sk_user_data; if (connected(con)) { - conn_get(con); - if (!queue_work(con->server->send_wq, &con->swork)) - conn_put(con); + srv = con->server; + spin_lock_bh(&srv->idr_lock); + if (srv->listener) { + conn_get(con); + if (!queue_work(srv->send_wq, &con->swork)) + conn_put(con); + } + spin_unlock_bh(&srv->idr_lock); } read_unlock_bh(&sk->sk_callback_lock); } @@ -418,8 +444,17 @@ static int tipc_conn_rcv_from_sock(struct tipc_conn *con) static void tipc_conn_recv_work(struct work_struct *work) { struct tipc_conn *con = container_of(work, struct tipc_conn, rwork); + struct tipc_topsrv *srv; int count = 0; + srv = con->server; + spin_lock_bh(&srv->idr_lock); + if (!srv->listener) { + spin_unlock_bh(&srv->idr_lock); + goto out; + } + spin_unlock_bh(&srv->idr_lock); + while (connected(con)) { if (tipc_conn_rcv_from_sock(con)) break; @@ -430,6 +465,7 @@ static void tipc_conn_recv_work(struct work_struct *work) count = 0; } } +out: conn_put(con); } @@ -438,6 +474,7 @@ static void tipc_conn_recv_work(struct work_struct *work) */ static void tipc_conn_data_ready(struct sock *sk) { + struct tipc_topsrv *srv; struct tipc_conn *con; trace_sk_data_ready(sk); @@ -445,9 +482,14 @@ static void tipc_conn_data_ready(struct sock *sk) read_lock_bh(&sk->sk_callback_lock); con = sk->sk_user_data; if (connected(con)) { - conn_get(con); - if (!queue_work(con->server->rcv_wq, &con->rwork)) - conn_put(con); + srv = con->server; + spin_lock_bh(&srv->idr_lock); + if (srv->listener) { + conn_get(con); + if (!queue_work(srv->rcv_wq, &con->rwork)) + conn_put(con); + } + spin_unlock_bh(&srv->idr_lock); } read_unlock_bh(&sk->sk_callback_lock); } @@ -503,8 +545,12 @@ static void tipc_topsrv_listener_data_ready(struct sock *sk) read_lock_bh(&sk->sk_callback_lock); srv = sk->sk_user_data; - if (srv) - queue_work(srv->rcv_wq, &srv->awork); + if (srv) { + spin_lock_bh(&srv->idr_lock); + if (srv->listener) + queue_work(srv->rcv_wq, &srv->awork); + spin_unlock_bh(&srv->idr_lock); + } read_unlock_bh(&sk->sk_callback_lock); } @@ -700,23 +746,27 @@ static void tipc_topsrv_stop(struct net *net) struct tipc_conn *con; int id; + spin_lock_bh(&srv->idr_lock); + srv->listener = NULL; + spin_unlock_bh(&srv->idr_lock); + tipc_topsrv_work_stop(srv); + spin_lock_bh(&srv->idr_lock); for (id = 0; srv->idr_in_use; id++) { con = idr_find(&srv->conn_idr, id); if (con) { - conn_get(con); spin_unlock_bh(&srv->idr_lock); tipc_conn_close(con); - conn_put(con); spin_lock_bh(&srv->idr_lock); + continue; } + spin_unlock_bh(&srv->idr_lock); + spin_lock_bh(&srv->idr_lock); } __module_get(lsock->ops->owner); __module_get(lsock->sk->sk_prot_creator->owner); - srv->listener = NULL; spin_unlock_bh(&srv->idr_lock); - tipc_topsrv_work_stop(srv); sock_release(lsock); idr_destroy(&srv->conn_idr); kfree(srv); diff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c index 4a1dfde8414f44..f271a095996c9f 100644 --- a/net/vmw_vsock/af_vsock.c +++ b/net/vmw_vsock/af_vsock.c @@ -1021,6 +1021,8 @@ static void vsock_sk_destruct(struct sock *sk) { struct vsock_sock *vsk = vsock_sk(sk); + /* Socket buffers may remain in the queue in VMCI datagram mode */ + __skb_queue_purge(&sk->sk_receive_queue); /* Flush MSG_ZEROCOPY leftovers. */ __skb_queue_purge(&sk->sk_error_queue); diff --git a/net/vmw_vsock/virtio_transport_common.c b/net/vmw_vsock/virtio_transport_common.c index 8becad81279c86..1f3fd0895f7c63 100644 --- a/net/vmw_vsock/virtio_transport_common.c +++ b/net/vmw_vsock/virtio_transport_common.c @@ -1916,6 +1916,7 @@ int virtio_transport_read_skb(struct vsock_sock *vsk, skb_read_actor_t recv_acto struct sock *sk = sk_vsock(vsk); struct virtio_vsock_hdr *hdr; struct sk_buff *skb; + u32 bytes_read; u32 pkt_len; int off = 0; int err; @@ -1935,7 +1936,8 @@ int virtio_transport_read_skb(struct vsock_sock *vsk, skb_read_actor_t recv_acto vvs->msg_count--; pkt_len = le32_to_cpu(hdr->len); - virtio_transport_dec_rx_pkt(vvs, pkt_len, pkt_len); + bytes_read = skb->len - VIRTIO_VSOCK_SKB_CB(skb)->offset; + virtio_transport_dec_rx_pkt(vvs, bytes_read, pkt_len); spin_unlock_bh(&vvs->rx_lock); virtio_transport_send_credit_update(vsk); diff --git a/net/xfrm/xfrm_output.c b/net/xfrm/xfrm_output.c index e305ba32e356b7..f1f612cd7b438d 100644 --- a/net/xfrm/xfrm_output.c +++ b/net/xfrm/xfrm_output.c @@ -823,16 +823,22 @@ int xfrm_output(struct sock *sk, struct sk_buff *skb) } if (skb->ip_summed == CHECKSUM_PARTIAL) { - err = skb_checksum_help(skb); - if (err) { - XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTERROR); - kfree_skb(skb); - return err; + if (skb->protocol == htons(ETH_P_IP)) { + err = ip_check_csum_start(skb); + if (err) + goto error; } + err = skb_checksum_help(skb); + if (err) + goto error; } out: return xfrm_output2(net, sk, skb); +error: + XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTERROR); + kfree_skb(skb); + return err; } EXPORT_SYMBOL_GPL(xfrm_output); diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index d41555a4b31d23..10ccce3c305fc5 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -79,6 +79,7 @@ unsafe impl driver::RegistrationOps for Adapter { (*pdrv.get()).remove = Some(Self::remove_callback); (*pdrv.get()).driver.of_match_table = of_table; (*pdrv.get()).driver.acpi_match_table = acpi_table; + (*pdrv.get()).driver.suppress_bind_attrs = T::suppress_bind_attrs(); } // SAFETY: `pdrv` is guaranteed to be a valid `DriverType`. @@ -224,6 +225,12 @@ pub trait Driver { /// The table of ACPI device ids supported by the driver. const ACPI_ID_TABLE: Option> = None; + /// Suppress manual bind/unbind for hardware without a safe teardown path. + /// Evaluated before registration, including before a deferred probe. + fn suppress_bind_attrs() -> bool { + false + } + /// Platform driver probe. /// /// Called when a new platform device is added or discovered. diff --git a/security/keys/key.c b/security/keys/key.c index b34a64d81d47ab..a438c4508595d9 100644 --- a/security/keys/key.c +++ b/security/keys/key.c @@ -840,9 +840,6 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, key_check(keyring); - if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION)) - restrict_link = keyring->restrict_link; - key_ref = ERR_PTR(-ENOTDIR); if (keyring->type != &key_type_keyring) goto error_put_type; @@ -880,6 +877,9 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, goto error_link_end; } + if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION)) + restrict_link = keyring->restrict_link; + if (restrict_link && restrict_link->check) { ret = restrict_link->check(keyring, index_key.type, &prep.payload, restrict_link->key); diff --git a/security/keys/persistent.c b/security/keys/persistent.c index 97af230aa4b22b..bdab9953932613 100644 --- a/security/keys/persistent.c +++ b/security/keys/persistent.c @@ -33,25 +33,31 @@ static int key_create_persistent_register(struct user_namespace *ns) } /* - * Create the persistent keyring for the specified user. + * Get or create the persistent keyring for the specified user. * * Called with the namespace's sem locked for writing. + * + * Returns a boolean indicating whether the keyring already existed, + * or a negative error. On success, *persistent_ref holds a reference + * to the keyring. */ -static key_ref_t key_create_persistent(struct user_namespace *ns, kuid_t uid, - struct keyring_index_key *index_key) +static int key_get_or_create_persistent(struct user_namespace *ns, kuid_t uid, + struct keyring_index_key *index_key, + key_ref_t *persistent_ref) { struct key *persistent; - key_ref_t reg_ref, persistent_ref; + key_ref_t reg_ref; if (!ns->persistent_keyring_register) { - long err = key_create_persistent_register(ns); + int err = key_create_persistent_register(ns); + if (err < 0) - return ERR_PTR(err); + return err; } else { reg_ref = make_key_ref(ns->persistent_keyring_register, true); - persistent_ref = find_key_to_update(reg_ref, index_key); - if (persistent_ref) - return persistent_ref; + *persistent_ref = find_key_to_update(reg_ref, index_key); + if (*persistent_ref) + return 1; } persistent = keyring_alloc(index_key->description, @@ -61,9 +67,10 @@ static key_ref_t key_create_persistent(struct user_namespace *ns, kuid_t uid, KEY_ALLOC_NOT_IN_QUOTA, NULL, ns->persistent_keyring_register); if (IS_ERR(persistent)) - return ERR_CAST(persistent); + return PTR_ERR(persistent); - return make_key_ref(persistent, true); + *persistent_ref = make_key_ref(persistent, true); + return 0; } /* @@ -78,6 +85,7 @@ static long key_get_persistent(struct user_namespace *ns, kuid_t uid, key_ref_t reg_ref, persistent_ref; char buf[32]; long ret; + bool created = false; /* Look in the register if it exists */ memset(&index_key, 0, sizeof(index_key)); @@ -100,23 +108,24 @@ static long key_get_persistent(struct user_namespace *ns, kuid_t uid, * also need to create the register. */ down_write(&ns->keyring_sem); - persistent_ref = key_create_persistent(ns, uid, &index_key); + ret = key_get_or_create_persistent(ns, uid, &index_key, + &persistent_ref); up_write(&ns->keyring_sem); - if (!IS_ERR(persistent_ref)) - goto found; - - return PTR_ERR(persistent_ref); + if (ret < 0) + return ret; + created = ret == 0; found: + persistent = key_ref_to_ptr(persistent_ref); ret = key_task_permission(persistent_ref, current_cred(), KEY_NEED_LINK); - if (ret == 0) { - persistent = key_ref_to_ptr(persistent_ref); + if (ret == 0) ret = key_link(key_ref_to_ptr(dest_ref), persistent); - if (ret == 0) { - key_set_timeout(persistent, persistent_keyring_expiry); - ret = persistent->serial; - } - } + + if (ret == 0 || created) + key_set_timeout(persistent, persistent_keyring_expiry); + + if (ret == 0) + ret = persistent->serial; key_ref_put(persistent_ref); return ret; diff --git a/security/selinux/avc.c b/security/selinux/avc.c index 221c41978dc509..436b9af7b92c1d 100644 --- a/security/selinux/avc.c +++ b/security/selinux/avc.c @@ -579,7 +579,7 @@ static int avc_latest_notif_update(u32 seqno, int is_insert) } } else { if (seqno > selinux_avc.avc_cache.latest_notif) - selinux_avc.avc_cache.latest_notif = seqno; + WRITE_ONCE(selinux_avc.avc_cache.latest_notif, seqno); } spin_unlock_irqrestore(¬if_lock, flag); @@ -1207,5 +1207,6 @@ int avc_has_perm(u32 ssid, u32 tsid, u16 tclass, u32 avc_policy_seqno(void) { - return selinux_avc.avc_cache.latest_notif; + /* Writers hold notif_lock; readers only sample the sequence number. */ + return READ_ONCE(selinux_avc.avc_cache.latest_notif); } diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c index 5832131f29c47d..cf7297072ec03f 100644 --- a/security/selinux/hooks.c +++ b/security/selinux/hooks.c @@ -688,8 +688,12 @@ static int selinux_set_mnt_opts(struct super_block *sb, * will be used for both mounts) */ if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA) - && !opts) + && !opts) { + if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && + sbsec->behavior == SECURITY_FS_USE_NATIVE) + *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS; goto out; + } root_isec = backing_inode_security_novalidate(root); @@ -733,6 +737,9 @@ static int selinux_set_mnt_opts(struct super_block *sb, /* previously mounted with options, but not on this attempt? */ if ((sbsec->flags & SE_MNTMASK) && !opts) goto out_double_mount; + if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && + sbsec->behavior == SECURITY_FS_USE_NATIVE) + *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS; rc = 0; goto out; } diff --git a/sound/hda/codecs/side-codecs/tas2781_hda.c b/sound/hda/codecs/side-codecs/tas2781_hda.c index b22f93424c6211..e0da299df780c2 100644 --- a/sound/hda/codecs/side-codecs/tas2781_hda.c +++ b/sound/hda/codecs/side-codecs/tas2781_hda.c @@ -139,9 +139,21 @@ static void tas2781_apply_calib(struct tasdevice_priv *p) */ crc = crc32(~0, data, 84) ^ ~0; if (crc != tmp_val[21]) { - cali_data->total_sz = 0; - dev_err(p->dev, "%s: V1 CRC error\n", __func__); - return; + /* + * Some Lenovo BIOSes (e.g. Legion Pro 7 16IRX9H, + * SSID 17aa:38cd) store valid V1 calibration data + * but leave TimeStamp and CRC zeroed. + */ + if (!tmp_val[20] && !tmp_val[21] && + tmp_val[0] && tmp_val[1]) { + dev_warn(p->dev, + "%s: V1 data without CRC, accepting\n", + __func__); + } else { + cali_data->total_sz = 0; + dev_err(p->dev, "%s: V1 CRC error\n", __func__); + return; + } } for (j = p->ndev - 1; j >= 0; j--) { diff --git a/sound/pci/ctxfi/ctdaio.c b/sound/pci/ctxfi/ctdaio.c index 69aacd06716cef..59ed96fb938a23 100644 --- a/sound/pci/ctxfi/ctdaio.c +++ b/sound/pci/ctxfi/ctdaio.c @@ -221,14 +221,18 @@ static int dao_set_right_input(struct dao *dao, struct rsc *input) static int dao_clear_input(struct dao *dao, unsigned int start, unsigned int end) { + struct imapper *entry; unsigned int i; - if (!dao->imappers[start]) + entry = dao->imappers[start]; + if (!entry) return 0; + for (i = start; i < end; i++) { dao->mgr->imap_delete(dao->mgr, dao->imappers[i]); dao->imappers[i] = NULL; } + kfree(entry); return 0; } diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index 79858fc9480651..7eaf15a27b7b91 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -759,6 +759,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_BOARD_NAME, "Herbag_MDU"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "MDC"), + DMI_MATCH(DMI_BOARD_NAME, "Herbag2_MDU"), + } + }, { .driver_data = &acp6x_card, .matches = { diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index e4d139108d7204..fbd8b94453bfe9 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -990,6 +990,21 @@ config SND_SOC_CS42L42_SDW help Enable support for Cirrus Logic CS42L42 codec with Soundwire control +config SND_SOC_CS42L42_TEST + bool "KUnit test for Cirrus Logic cs42l42 driver" if !KUNIT_ALL_TESTS + depends on SND_SOC_CS42L42_CORE=y && SND_SOC=y && KUNIT=y + default KUNIT_ALL_TESTS + help + This builds KUnit tests for the clock switching that the + Cirrus Logic cs42l42 codec driver does when a stream is + muted or unmuted, including PCM resume refusal and prepare recovery. + These tests use built-in ALSA/ASoC entry points. + + For more information on KUnit and unit tests in general, + please refer to the KUnit documentation in + Documentation/dev-tools/kunit/. + If in doubt, say "N". + config SND_SOC_CS42L43 tristate "Cirrus Logic CS42L43 CODEC" depends on MFD_CS42L43 @@ -1037,6 +1052,21 @@ config SND_SOC_CS42L84 select REGMAP select REGMAP_I2C +config SND_SOC_CS42L84_TEST + bool "KUnit test for Cirrus Logic cs42l84 driver" if !KUNIT_ALL_TESTS + depends on SND_SOC_CS42L84 && (KUNIT=y || KUNIT=SND_SOC_CS42L84) + default KUNIT_ALL_TESTS + help + This builds KUnit tests for the clock switching that the + Cirrus Logic cs42l84 codec driver does when a stream is + muted or unmuted. The tests are built into the cs42l84 + driver and run when it is loaded. + + For more information on KUnit and unit tests in general, + please refer to the KUnit documentation in + Documentation/dev-tools/kunit/. + If in doubt, say "N". + config SND_SOC_CS4234 tristate "Cirrus Logic CS4234 CODEC" depends on I2C diff --git a/sound/soc/codecs/Makefile b/sound/soc/codecs/Makefile index aa0396e5b575b6..1ed18ec77cd15c 100644 --- a/sound/soc/codecs/Makefile +++ b/sound/soc/codecs/Makefile @@ -86,6 +86,7 @@ snd-soc-cs40l50-y := cs40l50-codec.o snd-soc-cs42l42-y := cs42l42.o snd-soc-cs42l42-i2c-y := cs42l42-i2c.o snd-soc-cs42l42-sdw-y := cs42l42-sdw.o +snd-soc-cs42l42-test-y := cs42l42-test.o snd-soc-cs42l43-y := cs42l43.o cs42l43-jack.o snd-soc-cs42l43-sdw-y := cs42l43-sdw.o snd-soc-cs42l51-y := cs42l51.o @@ -527,6 +528,7 @@ obj-$(CONFIG_SND_SOC_CS40L50) += snd-soc-cs40l50.o obj-$(CONFIG_SND_SOC_CS42L42_CORE) += snd-soc-cs42l42.o obj-$(CONFIG_SND_SOC_CS42L42) += snd-soc-cs42l42-i2c.o obj-$(CONFIG_SND_SOC_CS42L42_SDW) += snd-soc-cs42l42-sdw.o +obj-$(CONFIG_SND_SOC_CS42L42_TEST) += snd-soc-cs42l42-test.o obj-$(CONFIG_SND_SOC_CS42L43) += snd-soc-cs42l43.o obj-$(CONFIG_SND_SOC_CS42L43_SDW) += snd-soc-cs42l43-sdw.o obj-$(CONFIG_SND_SOC_CS42L51) += snd-soc-cs42l51.o diff --git a/sound/soc/codecs/adau1372.c b/sound/soc/codecs/adau1372.c index cc174ec3a1f825..c3d3be898ba6cc 100644 --- a/sound/soc/codecs/adau1372.c +++ b/sound/soc/codecs/adau1372.c @@ -798,7 +798,7 @@ static int adau1372_set_power(struct adau1372 *adau1372, bool enable) if (ret) return ret; if (adau1372->pd_gpio) - gpiod_set_value(adau1372->pd_gpio, 0); + gpiod_set_value_cansleep(adau1372->pd_gpio, 0); if (adau1372->switch_mode) adau1372->switch_mode(adau1372->dev); @@ -818,8 +818,7 @@ static int adau1372_set_power(struct adau1372 *adau1372, bool enable) ADAU1372_CLK_CTRL_PLL_EN, 0); regcache_cache_only(adau1372->regmap, true); - if (adau1372->pd_gpio) - gpiod_set_value(adau1372->pd_gpio, 1); + gpiod_set_value_cansleep(adau1372->pd_gpio, 1); clk_disable_unprepare(adau1372->mclk); return ret; } @@ -836,7 +835,7 @@ static int adau1372_set_power(struct adau1372 *adau1372, bool enable) * map. No need to do any register writes to manually * turn things off. */ - gpiod_set_value(adau1372->pd_gpio, 1); + gpiod_set_value_cansleep(adau1372->pd_gpio, 1); regcache_mark_dirty(adau1372->regmap); } else { regmap_update_bits(adau1372->regmap, ADAU1372_REG_CLK_CTRL, @@ -1003,6 +1002,17 @@ int adau1372_probe(struct device *dev, struct regmap *regmap, regmap_write(regmap, ADAU1372_REG_OP_STAGE_MUTE, 0x0); + /* + * Set sane default values for the Output ASRC and DAC input muxes, + * since the power-on reset defaults are invalid "Reserved" states. + */ + regmap_write(regmap, ADAU1372_REG_ASRCO_SOURCE_0_1, + 0x54); /* Decimator0, Decimator1 */ + regmap_write(regmap, ADAU1372_REG_ASRCO_SOURCE_2_3, + 0x76); /* Decimator2, Decimator3 */ + regmap_write(regmap, ADAU1372_REG_DAC_SOURCE, + 0xdc); /* Input ASRC0, Input ASRC1 */ + regmap_write(regmap, 0x7, 0x01); /* CLOCK OUT */ return devm_snd_soc_register_component(dev, &adau1372_driver, &adau1372_dai_driver, 1); diff --git a/sound/soc/codecs/cs42l42-sdw.c b/sound/soc/codecs/cs42l42-sdw.c index ad1256910a180a..d0621c56581d26 100644 --- a/sound/soc/codecs/cs42l42-sdw.c +++ b/sound/soc/codecs/cs42l42-sdw.c @@ -98,6 +98,7 @@ static int cs42l42_sdw_dai_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct cs42l42_private *cs42l42 = snd_soc_component_get_drvdata(dai->component); + int ret; dev_dbg(dai->dev, "dai_prepare: sclk=%u rate=%u\n", cs42l42->sclk, cs42l42->sample_rate); @@ -110,7 +111,11 @@ static int cs42l42_sdw_dai_prepare(struct snd_pcm_substream *substream, * an unsupported SWIRE_CLK and sample_rate combination. */ - return cs42l42_pll_config(dai->component, cs42l42->sclk, cs42l42->sample_rate); + ret = cs42l42_pll_config(dai->component, cs42l42->sclk, cs42l42->sample_rate); + if (ret) + return ret; + + return cs42l42_dai_prepare(substream, dai); } static int cs42l42_sdw_dai_hw_free(struct snd_pcm_substream *substream, diff --git a/sound/soc/codecs/cs42l42-test.c b/sound/soc/codecs/cs42l42-test.c new file mode 100644 index 00000000000000..4ce8219c29336d --- /dev/null +++ b/sound/soc/codecs/cs42l42-test.c @@ -0,0 +1,886 @@ +// SPDX-License-Identifier: GPL-2.0-only +// +// KUnit tests for the clock switching in cs42l42_mute_stream(). +// +// The codec runs from its internal oscillator while no stream is active. +// Unmuting the first stream moves it onto SCLK, through the PLL if the +// selected clock configuration needs one. Once the codec has left the +// oscillator it needs a working clock to answer on I2C, so these tests +// check when that switch happens and when it must not happen. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cs42l42.h" + +#define CS42L42_TEST_MAX_WRITES 64 + +#define CS42L42_TEST_HP_MUTE_MASK (CS42L42_HP_ANA_AMUTE_MASK | \ + CS42L42_HP_ANA_BMUTE_MASK) + +/* PLL_LOCK_STATUS bit polled by cs42l42_mute_stream() */ +#define CS42L42_TEST_PLL_LOCKED BIT(0) + +struct cs42l42_test_write { + unsigned int reg; + unsigned int val; +}; + +struct cs42l42_test_priv { + struct kunit *test; + + struct cs42l42_private cs42l42; + struct snd_soc_component component; + struct snd_soc_dai dai; + struct snd_soc_card soc_card; + struct snd_card card; + + /* Register contents seen by the driver */ + u8 *regs; + + /* Every register write made by the driver, in order */ + struct cs42l42_test_write writes[CS42L42_TEST_MAX_WRITES]; + unsigned int num_writes; + + unsigned int num_lock_reads; + bool pll_locks; +}; + +struct cs42l42_test_clk_param { + unsigned int sclk; + unsigned int rate; + bool pll_divout_step; +}; + +struct cs42l42_test_power_param { + unsigned int state; + const char *name; +}; + +/* Clock configurations that run the codec from the PLL */ +static const struct cs42l42_test_clk_param cs42l42_test_pll_clks[] = { + { .sclk = 1536000, .rate = 48000, .pll_divout_step = true }, + { .sclk = 3072000, .rate = 48000, .pll_divout_step = false }, +}; + +static const struct cs42l42_test_power_param cs42l42_test_low_power[] = { + { .state = SNDRV_CTL_POWER_D1, .name = "D1" }, + { .state = SNDRV_CTL_POWER_D2, .name = "D2" }, + { .state = SNDRV_CTL_POWER_D3hot, .name = "D3hot" }, + { .state = SNDRV_CTL_POWER_D3cold, .name = "D3cold" }, +}; + +static int cs42l42_test_reg_read(void *context, unsigned int reg, unsigned int *val) +{ + struct cs42l42_test_priv *priv = context; + + if (reg > CS42L42_MAX_REGISTER) + return -EINVAL; + + if (reg == CS42L42_PLL_LOCK_STATUS) { + priv->num_lock_reads++; + *val = priv->pll_locks ? CS42L42_TEST_PLL_LOCKED : 0; + return 0; + } + + *val = priv->regs[reg]; + + return 0; +} + +static int cs42l42_test_reg_write(void *context, unsigned int reg, unsigned int val) +{ + struct cs42l42_test_priv *priv = context; + + if (reg > CS42L42_MAX_REGISTER) + return -EINVAL; + + if (priv->num_writes < ARRAY_SIZE(priv->writes)) { + priv->writes[priv->num_writes].reg = reg; + priv->writes[priv->num_writes].val = val; + priv->num_writes++; + } else { + KUNIT_FAIL(priv->test, "write log full at reg %#x", reg); + } + + priv->regs[reg] = val; + + return 0; +} + +static const struct regmap_config cs42l42_test_regmap_config = { + .reg_bits = 16, + .val_bits = 8, + .max_register = CS42L42_MAX_REGISTER, + .reg_read = cs42l42_test_reg_read, + .reg_write = cs42l42_test_reg_write, + .cache_type = REGCACHE_NONE, +}; + +static void cs42l42_test_clear_log(struct cs42l42_test_priv *priv) +{ + priv->num_writes = 0; + priv->num_lock_reads = 0; +} + +/* Index of the first write to @reg at or after index @from, or -1 */ +static int cs42l42_test_find_write(struct cs42l42_test_priv *priv, + unsigned int reg, int from) +{ + unsigned int i; + + for (i = max(from, 0); i < priv->num_writes; i++) { + if (priv->writes[i].reg == reg) + return i; + } + + return -1; +} + +/* Index of the last write to @reg, or -1 */ +static int cs42l42_test_last_write(struct cs42l42_test_priv *priv, unsigned int reg) +{ + unsigned int i; + + for (i = priv->num_writes; i > 0; i--) { + if (priv->writes[i - 1].reg == reg) + return i - 1; + } + + return -1; +} + +static unsigned int cs42l42_test_count_writes(struct cs42l42_test_priv *priv, + unsigned int reg) +{ + unsigned int i, n = 0; + + for (i = 0; i < priv->num_writes; i++) { + if (priv->writes[i].reg == reg) + n++; + } + + return n; +} + +/* Select the clock configuration the way hw_params does */ +static void cs42l42_test_set_clk(struct kunit *test, unsigned int sclk, + unsigned int rate) +{ + struct cs42l42_test_priv *priv = test->priv; + + KUNIT_ASSERT_EQ(test, cs42l42_pll_config(&priv->component, sclk, rate), 0); + cs42l42_test_clear_log(priv); +} + +static void cs42l42_test_set_power(struct cs42l42_test_priv *priv, unsigned int state) +{ + snd_power_change_state(priv->soc_card.snd_card, state); +} + +/* + * Check that the writes logged since the last clear are a complete switch + * from the oscillator to SCLK through the PLL, with the headphone unmuted + * last. The PLL output divider is only rewritten if it still holds the + * startup value from cs42l42_pll_config(), so @check_divout must be false + * when an earlier unmute has already set the final value. + */ +static void cs42l42_test_expect_switch_to_pll(struct kunit *test, + const struct cs42l42_test_clk_param *param, + bool check_divout) +{ + struct cs42l42_test_priv *priv = test->priv; + int pll_start, divout, mclk_sel, sclk, hp; + + pll_start = cs42l42_test_find_write(priv, CS42L42_PLL_CTL1, 0); + KUNIT_ASSERT_GE(test, pll_start, 0); + KUNIT_EXPECT_TRUE(test, priv->writes[pll_start].val & CS42L42_PLL_START_MASK); + + divout = cs42l42_test_find_write(priv, CS42L42_PLL_CTL3, pll_start); + if (check_divout && param->pll_divout_step) + KUNIT_EXPECT_GT(test, divout, pll_start); + else if (check_divout) + KUNIT_EXPECT_LT(test, divout, 0); + + /* The PLL output must only be selected once the PLL has locked */ + KUNIT_EXPECT_GT(test, priv->num_lock_reads, 0); + mclk_sel = cs42l42_test_find_write(priv, CS42L42_MCLK_SRC_SEL, pll_start); + KUNIT_ASSERT_GT(test, mclk_sel, pll_start); + KUNIT_EXPECT_EQ(test, priv->writes[mclk_sel].val & CS42L42_MCLK_SRC_SEL_MASK, + CS42L42_MCLK_SRC_SEL_MASK); + + sclk = cs42l42_test_find_write(priv, CS42L42_OSC_SWITCH, mclk_sel); + KUNIT_ASSERT_GT(test, sclk, mclk_sel); + KUNIT_EXPECT_EQ(test, priv->writes[sclk].val, CS42L42_SCLK_PRESENT_MASK); + + hp = cs42l42_test_find_write(priv, CS42L42_HP_CTL, sclk); + KUNIT_ASSERT_GT(test, hp, sclk); + KUNIT_EXPECT_EQ(test, priv->writes[hp].val & CS42L42_TEST_HP_MUTE_MASK, 0); +} + +/* + * ASoC resume sets the card to D2, unmutes the playback DAIs that were + * active at suspend and only then sets D0. That early unmute must not move + * the codec off the oscillator: the stream is still suspended and SCLK may + * not be running yet. + */ +static void cs42l42_test_unmute_below_d0_does_nothing(struct kunit *test) +{ + const struct cs42l42_test_power_param *param = test->param_value; + const struct cs42l42_test_clk_param *clk = &cs42l42_test_pll_clks[0]; + struct cs42l42_test_priv *priv = test->priv; + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "card power state needs CONFIG_PM"); + + /* A PLL configuration whose PLL would lock if it were started */ + cs42l42_test_set_clk(test, clk->sclk, clk->rate); + cs42l42_test_set_power(priv, param->state); + + KUNIT_EXPECT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); + KUNIT_EXPECT_EQ(test, priv->num_lock_reads, 0); + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_HP_CTL] & CS42L42_TEST_HP_MUTE_MASK, + CS42L42_TEST_HP_MUTE_MASK); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_OSC_SWITCH], 0); +} + +/* + * Use real ALSA RESUME/PREPARE ioctls and the ASoC trigger installed by + * soc_new_pcm(). Only the host DAI and prepare callback are synthetic: the + * host prepare supplies a working clock before calling the codec unmute. + */ +struct cs42l42_test_pcm { + struct snd_soc_pcm_runtime rtd; + struct snd_soc_dai_link link; + struct snd_soc_dai_link_ch_map map; + struct snd_soc_dai cpu; + struct snd_soc_dai_driver cpu_driver; + struct snd_soc_dai *dais[2]; + struct snd_pcm_runtime runtime; + struct snd_pcm_mmap_status status; + struct snd_pcm_mmap_control control; + struct snd_pcm_runtime capture_runtime; + struct snd_pcm_mmap_status capture_status; + struct snd_pcm_group linked_group; + struct snd_pcm_file pcm_file; + struct file file; + struct cs42l42_test_priv *priv; + unsigned int resumes; + unsigned int suspends; + unsigned int prepares; +}; + +static int cs42l42_test_cpu_trigger(struct snd_pcm_substream *substream, + int cmd, struct snd_soc_dai *dai) +{ + struct cs42l42_test_pcm *pcm = container_of(snd_soc_substream_to_rtd(substream), + struct cs42l42_test_pcm, rtd); + + if (cmd == SNDRV_PCM_TRIGGER_RESUME) + pcm->resumes++; + else if (cmd == SNDRV_PCM_TRIGGER_SUSPEND) + pcm->suspends++; + return 0; +} + +static const struct snd_soc_dai_ops cs42l42_test_cpu_ops = { + .trigger = cs42l42_test_cpu_trigger, +}; + +static int cs42l42_test_pcm_prepare(struct snd_pcm_substream *substream) +{ + struct cs42l42_test_pcm *pcm = container_of(snd_soc_substream_to_rtd(substream), + struct cs42l42_test_pcm, rtd); + int ret; + + pcm->prepares++; + pcm->priv->pll_locks = true; + ret = snd_soc_pcm_dai_prepare(substream); + if (ret) + return ret; + return cs42l42_mute_stream(&pcm->priv->dai, 0, substream->stream); +} + +static int cs42l42_test_pcm_ioctl(struct snd_pcm_substream *substream, + unsigned int cmd, void *arg) +{ + return cmd == SNDRV_PCM_IOCTL1_RESET ? 0 : -EINVAL; +} + +static void cs42l42_test_pcm_free(void *data) +{ + struct cs42l42_test_pcm *pcm = data; + int stream; + + if (pcm->rtd.pcm) { + for_each_pcm_streams(stream) { + struct snd_pcm_substream *substream; + + substream = pcm->rtd.pcm->streams[stream].substream; + if (!substream) + continue; + substream->runtime = NULL; + if (snd_pcm_stream_linked(substream)) { + list_move(&substream->link_list, &substream->self_group.substreams); + substream->group = &substream->self_group; + } + } + } + snd_card_free(pcm->rtd.card->snd_card); +} + +static struct cs42l42_test_pcm *cs42l42_test_pcm_init(struct kunit *test) +{ + struct cs42l42_test_priv *priv = test->priv; + struct cs42l42_test_pcm *pcm; + struct snd_pcm_substream *substream; + struct snd_card *card; + + pcm = kunit_kzalloc(test, sizeof(*pcm), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, pcm); + KUNIT_ASSERT_EQ(test, snd_card_new(priv->component.dev, -1, NULL, + THIS_MODULE, 0, &card), 0); + priv->soc_card.snd_card = card; + priv->soc_card.dev = priv->component.dev; + pcm->priv = priv; + pcm->rtd.dev = priv->component.dev; + pcm->rtd.card = &priv->soc_card; + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cs42l42_test_pcm_free, pcm), 0); + pcm->rtd.dai_link = &pcm->link; + pcm->rtd.dais = pcm->dais; + pcm->link.name = "cs42l42-resume-test"; + pcm->link.stream_name = pcm->link.name; + pcm->link.num_cpus = 1; + pcm->link.num_codecs = 1; + pcm->link.ch_maps = &pcm->map; + pcm->cpu_driver = cs42l42_dai; + pcm->cpu_driver.ops = &cs42l42_test_cpu_ops; + pcm->cpu.driver = &pcm->cpu_driver; + pcm->cpu.name = "clock-provider"; + pcm->cpu.dev = priv->component.dev; + pcm->cpu.component = &priv->component; + pcm->dais[0] = &pcm->cpu; + pcm->dais[1] = &priv->dai; + KUNIT_ASSERT_EQ(test, soc_new_pcm(&pcm->rtd), 0); + pcm->rtd.ops.prepare = cs42l42_test_pcm_prepare; + pcm->rtd.ops.ioctl = cs42l42_test_pcm_ioctl; + substream = pcm->rtd.pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream; + substream->private_data = &pcm->rtd; + substream->runtime = &pcm->runtime; + pcm->runtime.status = &pcm->status; + pcm->runtime.control = &pcm->control; + pcm->runtime.info = SNDRV_PCM_INFO_RESUME; + pcm->runtime.suspended_state = SNDRV_PCM_STATE_RUNNING; + pcm->runtime.period_size = 128; + mutex_init(&pcm->runtime.buffer_mutex); + init_waitqueue_head(&pcm->runtime.sleep); + init_waitqueue_head(&pcm->runtime.tsleep); + pcm->pcm_file.substream = substream; + pcm->file.private_data = &pcm->pcm_file; + return pcm; +} + +static long cs42l42_test_pcm_command(struct cs42l42_test_pcm *pcm, unsigned int cmd) +{ + return snd_pcm_f_ops[SNDRV_PCM_STREAM_PLAYBACK].unlocked_ioctl(&pcm->file, cmd, 0); +} + +static void cs42l42_test_resume_requires_prepare(struct kunit *test) +{ + const struct cs42l42_test_clk_param *clk = &cs42l42_test_pll_clks[0]; + struct cs42l42_test_priv *priv = test->priv; + struct cs42l42_test_pcm *pcm; + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "card power state needs CONFIG_PM"); + pcm = cs42l42_test_pcm_init(test); + KUNIT_ASSERT_NOT_NULL(test, pcm); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D0); + cs42l42_test_set_clk(test, clk->sclk, clk->rate); + __snd_pcm_set_state(&pcm->runtime, SNDRV_PCM_STATE_SETUP); + KUNIT_ASSERT_EQ(test, cs42l42_test_pcm_command(pcm, SNDRV_PCM_IOCTL_PREPARE), 0); + KUNIT_EXPECT_FALSE(test, pcm->runtime.info & SNDRV_PCM_INFO_RESUME); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D3hot); + KUNIT_ASSERT_EQ(test, cs42l42_mute_stream(&priv->dai, 1, SNDRV_PCM_STREAM_PLAYBACK), 0); + __snd_pcm_set_state(&pcm->runtime, SNDRV_PCM_STATE_SUSPENDED); + cs42l42_test_clear_log(priv); + priv->pll_locks = false; + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D2); + KUNIT_ASSERT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D0); + + /* ALSA rejects before the real ASoC trigger can start any DAI. */ + KUNIT_EXPECT_EQ(test, cs42l42_test_pcm_command(pcm, SNDRV_PCM_IOCTL_RESUME), -ENOSYS); + KUNIT_EXPECT_EQ(test, pcm->resumes, 0); + KUNIT_EXPECT_EQ(test, pcm->suspends, 0); + KUNIT_EXPECT_EQ(test, pcm->runtime.state, SNDRV_PCM_STATE_SUSPENDED); + KUNIT_EXPECT_EQ(test, pcm->prepares, 1); + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); + + /* ALSA's documented -ENOSYS recovery is PREPARE, not a D0 callback. */ + KUNIT_ASSERT_EQ(test, cs42l42_test_pcm_command(pcm, SNDRV_PCM_IOCTL_PREPARE), 0); + KUNIT_EXPECT_EQ(test, pcm->prepares, 2); + KUNIT_EXPECT_EQ(test, pcm->runtime.state, SNDRV_PCM_STATE_PREPARED); + cs42l42_test_expect_switch_to_pll(test, clk, false); + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); +} + +static void cs42l42_test_linked_resume_preflight(struct kunit *test) +{ + struct cs42l42_test_priv *priv = test->priv; + struct cs42l42_test_pcm *pcm; + struct snd_pcm_substream *playback, *capture; + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "card power state needs CONFIG_PM"); + pcm = cs42l42_test_pcm_init(test); + KUNIT_ASSERT_NOT_NULL(test, pcm); + playback = pcm->pcm_file.substream; + capture = pcm->rtd.pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream; + capture->private_data = &pcm->rtd; + capture->runtime = &pcm->capture_runtime; + pcm->capture_runtime.info = SNDRV_PCM_INFO_RESUME; + pcm->capture_runtime.status = &pcm->capture_status; + pcm->capture_runtime.suspended_state = SNDRV_PCM_STATE_RUNNING; + __snd_pcm_set_state(&pcm->capture_runtime, SNDRV_PCM_STATE_SUSPENDED); + __snd_pcm_set_state(&pcm->runtime, SNDRV_PCM_STATE_SUSPENDED); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D0); + KUNIT_ASSERT_EQ(test, snd_soc_pcm_dai_prepare(playback), 0); + + /* Same group layout as linked ALSA streams, with capture visited first. */ + spin_lock_init(&pcm->linked_group.lock); + mutex_init(&pcm->linked_group.mutex); + INIT_LIST_HEAD(&pcm->linked_group.substreams); + refcount_set(&pcm->linked_group.refs, 2); + list_move_tail(&capture->link_list, &pcm->linked_group.substreams); + list_move_tail(&playback->link_list, &pcm->linked_group.substreams); + capture->group = &pcm->linked_group; + playback->group = &pcm->linked_group; + + KUNIT_EXPECT_EQ(test, cs42l42_test_pcm_command(pcm, SNDRV_PCM_IOCTL_RESUME), -ENOSYS); + KUNIT_EXPECT_EQ(test, pcm->resumes, 0); + KUNIT_EXPECT_EQ(test, pcm->suspends, 0); + KUNIT_EXPECT_EQ(test, pcm->runtime.state, SNDRV_PCM_STATE_SUSPENDED); + KUNIT_EXPECT_EQ(test, pcm->capture_runtime.state, SNDRV_PCM_STATE_SUSPENDED); + KUNIT_EXPECT_TRUE(test, pcm->capture_runtime.info & SNDRV_PCM_INFO_RESUME); + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); +} + +static void cs42l42_test_capture_resume_remains_supported(struct kunit *test) +{ + struct cs42l42_test_priv *priv = test->priv; + struct cs42l42_test_pcm *pcm; + struct snd_pcm_substream *capture; + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "card power state needs CONFIG_PM"); + pcm = cs42l42_test_pcm_init(test); + KUNIT_ASSERT_NOT_NULL(test, pcm); + capture = pcm->rtd.pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream; + capture->private_data = &pcm->rtd; + capture->runtime = &pcm->capture_runtime; + pcm->capture_runtime.info = SNDRV_PCM_INFO_RESUME; + pcm->capture_runtime.status = &pcm->capture_status; + pcm->capture_runtime.suspended_state = SNDRV_PCM_STATE_RUNNING; + __snd_pcm_set_state(&pcm->capture_runtime, SNDRV_PCM_STATE_SUSPENDED); + pcm->pcm_file.substream = capture; + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D0); + KUNIT_ASSERT_EQ(test, snd_soc_pcm_dai_prepare(capture), 0); + KUNIT_EXPECT_EQ(test, cs42l42_test_pcm_command(pcm, SNDRV_PCM_IOCTL_RESUME), 0); + KUNIT_EXPECT_EQ(test, pcm->resumes, 1); + KUNIT_EXPECT_EQ(test, pcm->suspends, 0); + KUNIT_EXPECT_EQ(test, pcm->capture_runtime.state, SNDRV_PCM_STATE_RUNNING); + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); +} + +static void cs42l42_test_prepare_resume_capability_is_per_stream(struct kunit *test) +{ + struct cs42l42_test_priv *priv = test->priv; + struct snd_pcm_runtime runtime = { + .info = SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_MMAP, + }; + struct snd_pcm_substream substream = { + .stream = SNDRV_PCM_STREAM_CAPTURE, + .runtime = &runtime, + }; + + KUNIT_ASSERT_EQ(test, snd_soc_dai_prepare(&priv->dai, &substream), 0); + KUNIT_EXPECT_EQ(test, runtime.info, + SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_MMAP); + substream.stream = SNDRV_PCM_STREAM_PLAYBACK; + KUNIT_ASSERT_EQ(test, snd_soc_dai_prepare(&priv->dai, &substream), 0); + KUNIT_EXPECT_EQ(test, runtime.info, SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_MMAP); + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); +} + +struct cs42l42_test_admission_param { + const char *name; + const char *root; + size_t root_len; + const char *codec; + size_t codec_len; + bool soundwire; + bool expected; +}; + +#define CS42L42_TEST_M1_ROOT(board) "apple," board "\0apple,t8103\0apple,arm-platform" +#define CS42L42_TEST_ADMISSION(label, machine, device, sdw, admitted) \ + { label, machine, sizeof(machine), device, sizeof(device), sdw, admitted } + +static const struct cs42l42_test_admission_param cs42l42_test_admissions[] = { + CS42L42_TEST_ADMISSION("J274 CS42L83", CS42L42_TEST_M1_ROOT("j274"), + "cirrus,cs42l83", false, true), + CS42L42_TEST_ADMISSION("J293 CS42L83", CS42L42_TEST_M1_ROOT("j293"), + "cirrus,cs42l83", false, true), + CS42L42_TEST_ADMISSION("J313 CS42L83", CS42L42_TEST_M1_ROOT("j313"), + "cirrus,cs42l83", false, true), + CS42L42_TEST_ADMISSION("J456 CS42L83", CS42L42_TEST_M1_ROOT("j456"), + "cirrus,cs42l83", false, true), + CS42L42_TEST_ADMISSION("J457 CS42L83", CS42L42_TEST_M1_ROOT("j457"), + "cirrus,cs42l83", false, true), + CS42L42_TEST_ADMISSION("base-M1 CS42L42", "apple,t8103", + "cirrus,cs42l42", false, true), + CS42L42_TEST_ADMISSION("J700 CS42L83", "apple,j700\0apple,t8140", + "cirrus,cs42l83", false, false), + CS42L42_TEST_ADMISSION("M1 Pro", "apple,j314s\0apple,t6000", + "cirrus,cs42l83", false, false), + CS42L42_TEST_ADMISSION("M2 Air", "apple,j413\0apple,t8112", + "cirrus,cs42l83", false, false), + CS42L42_TEST_ADMISSION("other codec", "apple,t8103", + "cirrus,cs42l84", false, false), + CS42L42_TEST_ADMISSION("absent codec OF node", "apple,t8103", + NULL, false, false), + CS42L42_TEST_ADMISSION("ACPI/non-OF host", NULL, + "cirrus,cs42l42", false, false), + CS42L42_TEST_ADMISSION("CS42L42 SoundWire", "apple,t8103", + "cirrus,cs42l42", true, false), + CS42L42_TEST_ADMISSION("CS42L83 SoundWire", "apple,t8103", + "cirrus,cs42l83", true, false), + CS42L42_TEST_ADMISSION("generic shared-BE host", "test,shared-be", + "cirrus,cs42l42", false, false), + CS42L42_TEST_ADMISSION("root lookalike", "apple,t8103-other", + "cirrus,cs42l83", false, false), +}; + +static void cs42l42_test_resume_admission(struct kunit *test) +{ + const struct cs42l42_test_admission_param *param = test->param_value; + struct property root_prop = { + .name = "compatible", .value = (void *)param->root, .length = param->root_len, + }; + struct property codec_prop = { + .name = "compatible", .value = (void *)param->codec, .length = param->codec_len, + }; + struct device_node root = { .full_name = "/", .properties = &root_prop }; + struct device_node codec = { .full_name = "/codec", .properties = &codec_prop }; + bool required; + + if (!IS_ENABLED(CONFIG_OF)) + kunit_skip(test, "admission matching needs CONFIG_OF"); + required = cs42l42_resume_workaround_required(param->root ? &root : NULL, + param->codec ? &codec : NULL, + param->soundwire); + KUNIT_EXPECT_EQ(test, required, param->expected); +} + +/* Excluded hosts keep their sole D2 unmute and transparent PCM resume. */ +static void cs42l42_test_unadmitted_resume_without_prepare(struct kunit *test) +{ + struct cs42l42_test_priv *priv = test->priv; + struct cs42l42_test_pcm *pcm; + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "card power state needs CONFIG_PM"); + priv->cs42l42.resume_reprepare = false; + pcm = cs42l42_test_pcm_init(test); + KUNIT_ASSERT_NOT_NULL(test, pcm); + cs42l42_test_set_clk(test, 3072000, 48000); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D0); + __snd_pcm_set_state(&pcm->runtime, SNDRV_PCM_STATE_SETUP); + KUNIT_ASSERT_EQ(test, cs42l42_test_pcm_command(pcm, SNDRV_PCM_IOCTL_PREPARE), 0); + KUNIT_EXPECT_TRUE(test, pcm->runtime.info & SNDRV_PCM_INFO_RESUME); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D3hot); + KUNIT_ASSERT_EQ(test, cs42l42_mute_stream(&priv->dai, 1, SNDRV_PCM_STREAM_PLAYBACK), 0); + __snd_pcm_set_state(&pcm->runtime, SNDRV_PCM_STATE_SUSPENDED); + cs42l42_test_clear_log(priv); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D2); + KUNIT_ASSERT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + cs42l42_test_expect_switch_to_pll(test, &cs42l42_test_pll_clks[1], false); + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D0); + cs42l42_test_clear_log(priv); + KUNIT_EXPECT_EQ(test, cs42l42_test_pcm_command(pcm, SNDRV_PCM_IOCTL_RESUME), 0); + KUNIT_EXPECT_EQ(test, pcm->runtime.state, SNDRV_PCM_STATE_RUNNING); + KUNIT_EXPECT_EQ(test, pcm->prepares, 1); + KUNIT_EXPECT_EQ(test, pcm->resumes, 1); + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_HP_CTL] & CS42L42_TEST_HP_MUTE_MASK, 0); + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); +} + +static void cs42l42_test_unadmitted_prepare_preserves_capabilities(struct kunit *test) +{ + struct cs42l42_test_priv *priv = test->priv; + struct snd_pcm_runtime runtime = { + .info = SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_MMAP, + }; + struct snd_pcm_substream substream = { + .stream = SNDRV_PCM_STREAM_PLAYBACK, .runtime = &runtime, + }; + + priv->cs42l42.resume_reprepare = false; + KUNIT_ASSERT_EQ(test, snd_soc_dai_prepare(&priv->dai, &substream), 0); + KUNIT_EXPECT_EQ(test, runtime.info, + SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_MMAP); + KUNIT_EXPECT_EQ(test, priv->num_writes, 0); +} + +/* At D0 with a locked PLL the codec moves onto the PLL output and SCLK */ +static void cs42l42_test_unmute_pll_locked(struct kunit *test) +{ + const struct cs42l42_test_clk_param *param = test->param_value; + struct cs42l42_test_priv *priv = test->priv; + + cs42l42_test_set_clk(test, param->sclk, param->rate); + + KUNIT_EXPECT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + cs42l42_test_expect_switch_to_pll(test, param, true); + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_HP_CTL] & CS42L42_TEST_HP_MUTE_MASK, 0); +} + +/* + * If the PLL does not lock the codec must stay on the oscillator with the + * PLL stopped and the headphone muted, and the error must be returned. + */ +static void cs42l42_test_unmute_pll_lock_timeout(struct kunit *test) +{ + const struct cs42l42_test_clk_param *param = test->param_value; + struct cs42l42_test_priv *priv = test->priv; + int pll_stop; + + cs42l42_test_set_clk(test, param->sclk, param->rate); + priv->pll_locks = false; + + KUNIT_EXPECT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), + -ETIMEDOUT); + KUNIT_EXPECT_GT(test, priv->num_lock_reads, 0); + + /* The PLL was started, then stopped again */ + pll_stop = cs42l42_test_last_write(priv, CS42L42_PLL_CTL1); + KUNIT_ASSERT_GE(test, pll_stop, 0); + KUNIT_EXPECT_EQ(test, priv->writes[pll_stop].val & CS42L42_PLL_START_MASK, 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_PLL_CTL1] & CS42L42_PLL_START_MASK, 0); + + /* Still on the oscillator */ + KUNIT_EXPECT_EQ(test, cs42l42_test_count_writes(priv, CS42L42_MCLK_SRC_SEL), 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_MCLK_SRC_SEL] & CS42L42_MCLK_SRC_SEL_MASK, 0); + KUNIT_EXPECT_EQ(test, cs42l42_test_count_writes(priv, CS42L42_OSC_SWITCH), 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_OSC_SWITCH], 0); + + /* Headphone still muted, stream not counted as running */ + KUNIT_EXPECT_EQ(test, cs42l42_test_count_writes(priv, CS42L42_HP_CTL), 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L42_HP_CTL] & CS42L42_TEST_HP_MUTE_MASK, + CS42L42_TEST_HP_MUTE_MASK); + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, 0); +} + +/* + * A failed unmute leaves stream_use clear, so the next unmute retries the + * whole switch instead of assuming the codec is already on SCLK. + */ +static void cs42l42_test_unmute_after_pll_lock_timeout(struct kunit *test) +{ + const struct cs42l42_test_clk_param *param = test->param_value; + struct cs42l42_test_priv *priv = test->priv; + + cs42l42_test_set_clk(test, param->sclk, param->rate); + + priv->pll_locks = false; + KUNIT_EXPECT_LT(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + cs42l42_test_clear_log(priv); + priv->pll_locks = true; + KUNIT_EXPECT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + cs42l42_test_expect_switch_to_pll(test, param, false); + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); +} + +/* Muting the last stream goes back to the oscillator, then stops the PLL */ +static void cs42l42_test_mute_returns_to_osc(struct kunit *test) +{ + const struct cs42l42_test_clk_param *param = test->param_value; + struct cs42l42_test_priv *priv = test->priv; + int hp, osc, mclk_sel, pll_stop; + + cs42l42_test_set_clk(test, param->sclk, param->rate); + KUNIT_ASSERT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + cs42l42_test_clear_log(priv); + + KUNIT_EXPECT_EQ(test, cs42l42_mute_stream(&priv->dai, 1, SNDRV_PCM_STREAM_PLAYBACK), 0); + + hp = cs42l42_test_find_write(priv, CS42L42_HP_CTL, 0); + KUNIT_ASSERT_GE(test, hp, 0); + KUNIT_EXPECT_EQ(test, priv->writes[hp].val & CS42L42_TEST_HP_MUTE_MASK, + CS42L42_TEST_HP_MUTE_MASK); + + osc = cs42l42_test_find_write(priv, CS42L42_OSC_SWITCH, hp); + KUNIT_ASSERT_GT(test, osc, hp); + KUNIT_EXPECT_EQ(test, priv->writes[osc].val, 0); + + mclk_sel = cs42l42_test_find_write(priv, CS42L42_MCLK_SRC_SEL, osc); + KUNIT_ASSERT_GT(test, mclk_sel, osc); + KUNIT_EXPECT_EQ(test, priv->writes[mclk_sel].val & CS42L42_MCLK_SRC_SEL_MASK, 0); + + pll_stop = cs42l42_test_find_write(priv, CS42L42_PLL_CTL1, mclk_sel); + KUNIT_ASSERT_GT(test, pll_stop, mclk_sel); + KUNIT_EXPECT_EQ(test, priv->writes[pll_stop].val & CS42L42_PLL_START_MASK, 0); + + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, 0); +} + +/* Without the PLL the codec goes straight onto SCLK, no lock poll */ +static void cs42l42_test_unmute_no_pll(struct kunit *test) +{ + struct cs42l42_test_priv *priv = test->priv; + int sclk, hp; + + /* SCLK is used directly as MCLK */ + cs42l42_test_set_clk(test, 12288000, 48000); + priv->pll_locks = false; + + KUNIT_EXPECT_EQ(test, cs42l42_mute_stream(&priv->dai, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + KUNIT_EXPECT_EQ(test, priv->num_lock_reads, 0); + KUNIT_EXPECT_EQ(test, cs42l42_test_count_writes(priv, CS42L42_PLL_CTL1), 0); + KUNIT_EXPECT_EQ(test, cs42l42_test_count_writes(priv, CS42L42_MCLK_SRC_SEL), 0); + + sclk = cs42l42_test_find_write(priv, CS42L42_OSC_SWITCH, 0); + KUNIT_ASSERT_GE(test, sclk, 0); + KUNIT_EXPECT_EQ(test, priv->writes[sclk].val, CS42L42_SCLK_PRESENT_MASK); + + hp = cs42l42_test_find_write(priv, CS42L42_HP_CTL, sclk); + KUNIT_ASSERT_GT(test, hp, sclk); + KUNIT_EXPECT_EQ(test, priv->writes[hp].val & CS42L42_TEST_HP_MUTE_MASK, 0); + + KUNIT_EXPECT_EQ(test, priv->cs42l42.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); +} + +static int cs42l42_test_case_init(struct kunit *test) +{ + struct cs42l42_test_priv *priv; + struct regmap *regmap; + struct device *dev; + + priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv); + priv->test = test; + test->priv = priv; + + priv->regs = kunit_kzalloc(test, CS42L42_MAX_REGISTER + 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv->regs); + + dev = kunit_device_register(test, "cs42l42_test_drv"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + regmap = devm_regmap_init(dev, NULL, priv, &cs42l42_test_regmap_config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, regmap); + + /* Construct the minimal set of driver structs */ + priv->cs42l42.dev = dev; + priv->cs42l42.regmap = regmap; + /* Existing clock-safety cases model the admitted base-M1 I2C path. */ + priv->cs42l42.resume_reprepare = true; + + priv->component.dev = dev; + priv->component.card = &priv->soc_card; + snd_soc_component_init_regmap(&priv->component, regmap); + snd_soc_component_set_drvdata(&priv->component, &priv->cs42l42); + + priv->dai.component = &priv->component; + priv->dai.dev = dev; + priv->dai.name = cs42l42_dai.name; + priv->dai.driver = &cs42l42_dai; + + priv->soc_card.snd_card = &priv->card; +#ifdef CONFIG_PM + init_waitqueue_head(&priv->card.power_sleep); + snd_refcount_init(&priv->card.power_ref); +#endif + cs42l42_test_set_power(priv, SNDRV_CTL_POWER_D0); + + /* Idle codec: on the oscillator, PLL stopped, headphone muted */ + priv->regs[CS42L42_HP_CTL] = CS42L42_TEST_HP_MUTE_MASK; + priv->pll_locks = true; + + return 0; +} + +static void cs42l42_test_clk_desc(const struct cs42l42_test_clk_param *param, char *desc) +{ + snprintf(desc, KUNIT_PARAM_DESC_SIZE, "SCLK %u Hz, %u Hz", param->sclk, param->rate); +} + +static void cs42l42_test_power_desc(const struct cs42l42_test_power_param *param, char *desc) +{ + snprintf(desc, KUNIT_PARAM_DESC_SIZE, "%s", param->name); +} + +static void cs42l42_test_admission_desc(const struct cs42l42_test_admission_param *param, + char *desc) +{ + snprintf(desc, KUNIT_PARAM_DESC_SIZE, "%s", param->name); +} + +KUNIT_ARRAY_PARAM(cs42l42_test_admissions, cs42l42_test_admissions, cs42l42_test_admission_desc); +KUNIT_ARRAY_PARAM(cs42l42_test_pll_clks, cs42l42_test_pll_clks, cs42l42_test_clk_desc); +KUNIT_ARRAY_PARAM(cs42l42_test_low_power, cs42l42_test_low_power, cs42l42_test_power_desc); + +static struct kunit_case cs42l42_test_cases[] = { + KUNIT_CASE_PARAM(cs42l42_test_resume_admission, cs42l42_test_admissions_gen_params), + KUNIT_CASE(cs42l42_test_unadmitted_resume_without_prepare), + KUNIT_CASE(cs42l42_test_unadmitted_prepare_preserves_capabilities), + KUNIT_CASE_PARAM(cs42l42_test_unmute_below_d0_does_nothing, + cs42l42_test_low_power_gen_params), + KUNIT_CASE(cs42l42_test_resume_requires_prepare), + KUNIT_CASE(cs42l42_test_linked_resume_preflight), + KUNIT_CASE(cs42l42_test_capture_resume_remains_supported), + KUNIT_CASE(cs42l42_test_prepare_resume_capability_is_per_stream), + KUNIT_CASE_PARAM(cs42l42_test_unmute_pll_locked, cs42l42_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l42_test_unmute_pll_lock_timeout, cs42l42_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l42_test_unmute_after_pll_lock_timeout, + cs42l42_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l42_test_mute_returns_to_osc, cs42l42_test_pll_clks_gen_params), + KUNIT_CASE(cs42l42_test_unmute_no_pll), + { } /* terminator */ +}; + +static struct kunit_suite cs42l42_test_suite = { + .name = "snd-soc-cs42l42-test", + .init = cs42l42_test_case_init, + .test_cases = cs42l42_test_cases, +}; + +kunit_test_suite(cs42l42_test_suite); + +MODULE_IMPORT_NS("SND_SOC_CS42L42_CORE"); +MODULE_DESCRIPTION("KUnit test for Cirrus Logic cs42l42 codec driver"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/cs42l42.c b/sound/soc/codecs/cs42l42.c index 08ab73ef965609..9a742905dd3af8 100644 --- a/sound/soc/codecs/cs42l42.c +++ b/sound/soc/codecs/cs42l42.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -1110,6 +1111,18 @@ int cs42l42_mute_stream(struct snd_soc_dai *dai, int mute, int stream) CS42L42_PLL_START_MASK, 0); } } else { + /* + * On the admitted base-M1 I2C path, ASoC resume unmutes + * playback while the card is still below D0. The PCM is + * suspended then and the host may not be driving SCLK yet, + * so moving the codec onto it would take the I2C bus down. + * Stay on the oscillator; playback prepare disables PCM RESUME + * so userspace must prepare and send another unmute at D0. + */ + if (cs42l42->resume_reprepare && + snd_power_get_state(component->card->snd_card) != SNDRV_CTL_POWER_D0) + return 0; + if (!cs42l42->stream_use) { /* SCLK must be running before codec unmute. * @@ -1139,8 +1152,17 @@ int cs42l42_mute_stream(struct snd_soc_dai *dai, int mute, int stream) (regval & 1), CS42L42_PLL_LOCK_POLL_US, CS42L42_PLL_LOCK_TIMEOUT_US); - if (ret < 0) + if (ret < 0) { + /* + * Without a locked PLL the codec has no clock + * once it leaves the oscillator, and then the + * I2C bus stops working. Stay on the oscillator. + */ dev_warn(component->dev, "PLL failed to lock: %d\n", ret); + snd_soc_component_update_bits(component, CS42L42_PLL_CTL1, + CS42L42_PLL_START_MASK, 0); + return ret; + } /* PLL must be running to drive glitchless switch logic */ snd_soc_component_update_bits(component, @@ -1168,6 +1190,23 @@ int cs42l42_mute_stream(struct snd_soc_dai *dai, int mute, int stream) } EXPORT_SYMBOL_NS_GPL(cs42l42_mute_stream, "SND_SOC_CS42L42_CORE"); +int cs42l42_dai_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) +{ + struct cs42l42_private *cs42l42 = snd_soc_component_get_drvdata(dai->component); + + /* + * Only the admitted base-M1 I2C workaround drops the D2 unmute and + * needs another prepare. Its macaudio topology permits one FE per BE, + * whose runtime is shared. This is not a generic shared-BE workaround: + * generic and SoundWire users retain their existing resume capability. + */ + if (cs42l42->resume_reprepare && substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + substream->runtime->info &= ~SNDRV_PCM_INFO_RESUME; + + return 0; +} +EXPORT_SYMBOL_NS_GPL(cs42l42_dai_prepare, "SND_SOC_CS42L42_CORE"); + #define CS42L42_FORMATS (SNDRV_PCM_FMTBIT_S16_LE |\ SNDRV_PCM_FMTBIT_S24_LE |\ SNDRV_PCM_FMTBIT_S32_LE) @@ -1179,6 +1218,7 @@ static const struct snd_soc_dai_ops cs42l42_ops = { .set_sysclk = cs42l42_set_sysclk, .set_bclk_ratio = cs42l42_set_bclk_ratio, .mute_stream = cs42l42_mute_stream, + .prepare = cs42l42_dai_prepare, }; struct snd_soc_dai_driver cs42l42_dai = { @@ -2659,12 +2699,29 @@ static int __maybe_unused cs42l42_i2c_resume(struct device *dev) return 0; } +/* No new policy for unqualified hosts, ACPI codecs or SoundWire devices. */ +bool cs42l42_resume_workaround_required(const struct device_node *root, + const struct device_node *codec, bool soundwire) +{ + if (soundwire || !root || !codec) + return false; + + return of_device_is_compatible(root, "apple,t8103") && + (of_device_is_compatible(codec, "cirrus,cs42l42") || + of_device_is_compatible(codec, "cirrus,cs42l83")); +} + int cs42l42_common_probe(struct cs42l42_private *cs42l42, const struct snd_soc_component_driver *component_drv, struct snd_soc_dai_driver *dai) { + struct device_node *root = of_find_node_by_path("/"); + bool reprepare = cs42l42_resume_workaround_required(root, cs42l42->dev->of_node, + !!cs42l42->sdw_peripheral); int ret, i; + cs42l42->resume_reprepare = reprepare; + of_node_put(root); dev_set_drvdata(cs42l42->dev, cs42l42); mutex_init(&cs42l42->irq_lock); diff --git a/sound/soc/codecs/cs42l42.h b/sound/soc/codecs/cs42l42.h index 7a9f2a5be5ef89..dd5a456fa62737 100644 --- a/sound/soc/codecs/cs42l42.h +++ b/sound/soc/codecs/cs42l42.h @@ -69,6 +69,8 @@ struct cs42l42_private { bool remote_active; unsigned int remote_saved[CS42L83_REMOTE_NUM_SAVED_REGS]; bool hp_adc_up_pending; + /* Set once at probe for the base-M1 I2C resume workaround. */ + bool resume_reprepare; bool suspended; bool sdw_waiting_first_unattach; bool init_done; @@ -86,6 +88,9 @@ int cs42l42_pll_config(struct snd_soc_component *component, unsigned int clk, unsigned int sample_rate); void cs42l42_src_config(struct snd_soc_component *component, unsigned int sample_rate); int cs42l42_mute_stream(struct snd_soc_dai *dai, int mute, int stream); +int cs42l42_dai_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai); +bool cs42l42_resume_workaround_required(const struct device_node *root, + const struct device_node *codec, bool soundwire); irqreturn_t cs42l42_irq_thread(int irq, void *data); int cs42l42_suspend(struct device *dev); int cs42l42_resume(struct device *dev); diff --git a/sound/soc/codecs/cs42l84-test.c b/sound/soc/codecs/cs42l84-test.c new file mode 100644 index 00000000000000..4d4952a33c8485 --- /dev/null +++ b/sound/soc/codecs/cs42l84-test.c @@ -0,0 +1,520 @@ +// SPDX-License-Identifier: GPL-2.0-only +// +// KUnit tests for the clock switching in cs42l84_mute_stream(). +// +// This file is included at the end of cs42l84.c when +// CONFIG_SND_SOC_CS42L84_TEST is enabled, so the tests can reach the +// driver's static DAI ops and PLL configuration. +// +// The codec runs from its internal oscillator (RCO) while no stream is +// active. Unmuting the first stream moves it onto BCLK, through the PLL +// if the BCLK rate needs one. Once the codec has left the oscillator it +// needs a working clock to answer on I2C, so these tests check when that +// switch happens and when it must not happen. + +#include +#include + +#define CS42L84_TEST_MAX_WRITES 64 +#define CS42L84_TEST_NUM_REGS 0x7400 + +#define CS42L84_TEST_CCM_CTL1(src, freq) \ + (FIELD_PREP_CONST(CS42L84_CCM_CTL1_MCLK_SRC, (src)) | \ + FIELD_PREP_CONST(CS42L84_CCM_CTL1_MCLK_FREQ, (freq))) + +struct cs42l84_test_write { + unsigned int reg; + unsigned int val; +}; + +struct cs42l84_test_priv { + struct kunit *test; + + struct cs42l84_private cs42l84; + struct snd_soc_component component; + struct snd_soc_dai dai; + struct snd_soc_card soc_card; + struct snd_card card; + + /* Register contents seen by the driver */ + u8 *regs; + + /* Every register write made by the driver, in order */ + struct cs42l84_test_write writes[CS42L84_TEST_MAX_WRITES]; + unsigned int num_writes; + + unsigned int num_lock_reads; + unsigned int lock_status; +}; + +struct cs42l84_test_clk_param { + unsigned int bclk; + unsigned int rate; + unsigned int ccm_ctl1; +}; + +/* BCLK rates that run the codec from the PLL */ +static const struct cs42l84_test_clk_param cs42l84_test_pll_clks[] = { + { + .bclk = 3072000, .rate = 48000, + .ccm_ctl1 = CS42L84_TEST_CCM_CTL1(CS42L84_CCM_CTL1_MCLK_SRC_PLL, + CS42L84_CCM_CTL1_MCLK_F_12_288KHZ), + }, + { + .bclk = 2822400, .rate = 44100, + .ccm_ctl1 = CS42L84_TEST_CCM_CTL1(CS42L84_CCM_CTL1_MCLK_SRC_PLL, + CS42L84_CCM_CTL1_MCLK_F_12_288KHZ), + }, +}; + +/* BCLK rates that are used directly as MCLK */ +static const struct cs42l84_test_clk_param cs42l84_test_bclk_clks[] = { + { + .bclk = 12288000, .rate = 48000, + .ccm_ctl1 = CS42L84_TEST_CCM_CTL1(CS42L84_CCM_CTL1_MCLK_SRC_BCLK, + CS42L84_CCM_CTL1_MCLK_F_12_288KHZ), + }, + { + .bclk = 11289600, .rate = 44100, + .ccm_ctl1 = CS42L84_TEST_CCM_CTL1(CS42L84_CCM_CTL1_MCLK_SRC_BCLK, + CS42L84_CCM_CTL1_MCLK_F_12_288KHZ), + }, +}; + +static int cs42l84_test_reg_read(void *context, unsigned int reg, unsigned int *val) +{ + struct cs42l84_test_priv *priv = context; + + if (reg >= CS42L84_TEST_NUM_REGS) + return -EINVAL; + + if (reg == CS42L84_PLL_LOCK_STATUS) { + priv->num_lock_reads++; + *val = priv->lock_status; + return 0; + } + + *val = priv->regs[reg]; + + return 0; +} + +static int cs42l84_test_reg_write(void *context, unsigned int reg, unsigned int val) +{ + struct cs42l84_test_priv *priv = context; + + if (reg >= CS42L84_TEST_NUM_REGS) + return -EINVAL; + + if (priv->num_writes < ARRAY_SIZE(priv->writes)) { + priv->writes[priv->num_writes].reg = reg; + priv->writes[priv->num_writes].val = val; + priv->num_writes++; + } else { + KUNIT_FAIL(priv->test, "write log full at reg %#x", reg); + } + + priv->regs[reg] = val; + + return 0; +} + +static const struct regmap_config cs42l84_test_regmap_config = { + .reg_bits = 16, + .val_bits = 8, + .max_register = CS42L84_TEST_NUM_REGS - 1, + .reg_read = cs42l84_test_reg_read, + .reg_write = cs42l84_test_reg_write, + .cache_type = REGCACHE_NONE, +}; + +static void cs42l84_test_clear_log(struct cs42l84_test_priv *priv) +{ + priv->num_writes = 0; + priv->num_lock_reads = 0; +} + +/* Index of the first write to @reg at or after index @from, or -1 */ +static int cs42l84_test_find_write(struct cs42l84_test_priv *priv, + unsigned int reg, int from) +{ + unsigned int i; + + for (i = max(from, 0); i < priv->num_writes; i++) { + if (priv->writes[i].reg == reg) + return i; + } + + return -1; +} + +/* Index of the last write to @reg, or -1 */ +static int cs42l84_test_last_write(struct cs42l84_test_priv *priv, unsigned int reg) +{ + unsigned int i; + + for (i = priv->num_writes; i > 0; i--) { + if (priv->writes[i - 1].reg == reg) + return i - 1; + } + + return -1; +} + +static unsigned int cs42l84_test_count_writes(struct cs42l84_test_priv *priv, + unsigned int reg) +{ + unsigned int i, n = 0; + + for (i = 0; i < priv->num_writes; i++) { + if (priv->writes[i].reg == reg) + n++; + } + + return n; +} + +/* Select the clock configuration the way the machine driver and hw_params do */ +static void cs42l84_test_set_clk(struct kunit *test, const struct cs42l84_test_clk_param *clk) +{ + struct cs42l84_test_priv *priv = test->priv; + + KUNIT_ASSERT_EQ(test, snd_soc_dai_set_sysclk(&priv->dai, 0, clk->bclk, + SND_SOC_CLOCK_IN), 0); + priv->cs42l84.srate = clk->rate; + KUNIT_ASSERT_EQ(test, cs42l84_pll_config(&priv->component), 0); + cs42l84_test_clear_log(priv); +} + +static void cs42l84_test_set_power(struct cs42l84_test_priv *priv, unsigned int state) +{ + snd_power_change_state(&priv->card, state); +} + +/* Mute or unmute through the DAI ops, as the ASoC core does */ +static int cs42l84_test_mute(struct cs42l84_test_priv *priv, int mute, int stream) +{ + return snd_soc_dai_digital_mute(&priv->dai, mute, stream); +} + +/* + * Check that the writes logged since the last clear are a complete switch + * from the oscillator to the PLL output, with the DAC unmuted last. + */ +static void cs42l84_test_expect_switch_to_pll(struct kunit *test, + const struct cs42l84_test_clk_param *clk) +{ + struct cs42l84_test_priv *priv = test->priv; + int refclk, pll_start, ccm, dac; + + refclk = cs42l84_test_find_write(priv, CS42L84_CCM_CTL4, 0); + KUNIT_ASSERT_GE(test, refclk, 0); + KUNIT_EXPECT_TRUE(test, priv->writes[refclk].val & CS42L84_CCM_CTL4_REFCLK_EN); + + pll_start = cs42l84_test_find_write(priv, CS42L84_PLL_CTL1, refclk); + KUNIT_ASSERT_GT(test, pll_start, refclk); + KUNIT_EXPECT_TRUE(test, priv->writes[pll_start].val & CS42L84_PLL_CTL1_EN); + + /* The PLL output must only be selected once the PLL has locked */ + KUNIT_EXPECT_GT(test, priv->num_lock_reads, 0); + ccm = cs42l84_test_find_write(priv, CS42L84_CCM_CTL1, pll_start); + KUNIT_ASSERT_GT(test, ccm, pll_start); + KUNIT_EXPECT_EQ(test, priv->writes[ccm].val, clk->ccm_ctl1); + + dac = cs42l84_test_find_write(priv, CS42L84_DAC_CTL1, ccm); + KUNIT_ASSERT_GT(test, dac, ccm); + KUNIT_EXPECT_TRUE(test, priv->writes[dac].val & CS42L84_DAC_CTL1_UNMUTE); +} + +/* + * Follow the codec callbacks from a running stream through card suspend and + * resume. ASoC sends the only resume unmute at D2, then publishes D0. A PCM + * with SNDRV_PCM_INFO_RESUME can trigger without another prepare/unmute. + * A successful PLL lock represents clocks being available, independently of + * card power state; the direct-BCLK case retains the host's clock contract. + */ +static void cs42l84_test_resume_without_prepare(struct kunit *test) +{ + const struct cs42l84_test_clk_param *clk = test->param_value; + struct cs42l84_test_priv *priv = test->priv; + unsigned int writes; + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "card power state needs CONFIG_PM"); + + cs42l84_test_set_clk(test, clk); + KUNIT_ASSERT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + cs42l84_test_set_power(priv, SNDRV_CTL_POWER_D3hot); + KUNIT_ASSERT_EQ(test, cs42l84_test_mute(priv, 1, SNDRV_PCM_STREAM_PLAYBACK), 0); + KUNIT_ASSERT_EQ(test, priv->cs42l84.stream_use, 0); + KUNIT_ASSERT_EQ(test, priv->regs[CS42L84_CCM_CTL1], CS42L84_CCM_CTL1_RCO); + cs42l84_test_clear_log(priv); + + cs42l84_test_set_power(priv, SNDRV_CTL_POWER_D2); + KUNIT_ASSERT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L84_CCM_CTL1], clk->ccm_ctl1); + KUNIT_EXPECT_TRUE(test, priv->regs[CS42L84_DAC_CTL1] & CS42L84_DAC_CTL1_UNMUTE); + KUNIT_EXPECT_EQ(test, priv->cs42l84.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); + writes = priv->num_writes; + KUNIT_EXPECT_GT(test, writes, 0); + + /* D0 is a notification, not a second codec callback or clock proof. */ + cs42l84_test_set_power(priv, SNDRV_CTL_POWER_D0); + KUNIT_EXPECT_EQ(test, priv->num_writes, writes); + KUNIT_EXPECT_TRUE(test, priv->regs[CS42L84_DAC_CTL1] & CS42L84_DAC_CTL1_UNMUTE); +} + +static void cs42l84_test_resume_without_prepare_bclk(struct kunit *test) +{ + cs42l84_test_resume_without_prepare(test); +} + +/* At D0 with a locked PLL the codec moves onto the PLL output */ +static void cs42l84_test_unmute_pll_locked(struct kunit *test) +{ + const struct cs42l84_test_clk_param *clk = test->param_value; + struct cs42l84_test_priv *priv = test->priv; + + cs42l84_test_set_clk(test, clk); + + KUNIT_EXPECT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + cs42l84_test_expect_switch_to_pll(test, clk); + KUNIT_EXPECT_EQ(test, priv->cs42l84.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L84_CCM_CTL1], clk->ccm_ctl1); + KUNIT_EXPECT_TRUE(test, priv->regs[CS42L84_DAC_CTL1] & CS42L84_DAC_CTL1_UNMUTE); +} + +/* + * The PLL lock error bit is only reported: once the lock bit is set the + * codec still moves onto the PLL output. + */ +static void cs42l84_test_unmute_pll_lock_error_bit(struct kunit *test) +{ + const struct cs42l84_test_clk_param *clk = &cs42l84_test_pll_clks[0]; + struct cs42l84_test_priv *priv = test->priv; + + cs42l84_test_set_clk(test, clk); + priv->lock_status = CS42L84_PLL_LOCK_STATUS_LOCKED | CS42L84_PLL_LOCK_STATUS_ERROR; + + KUNIT_EXPECT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + cs42l84_test_expect_switch_to_pll(test, clk); + KUNIT_EXPECT_EQ(test, priv->cs42l84.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); +} + +/* + * If the PLL does not lock the codec must stay on the oscillator with the + * PLL and its reference clock stopped again and the DAC muted, and the + * error must be returned. + */ +static void cs42l84_test_unmute_pll_lock_timeout(struct kunit *test) +{ + const struct cs42l84_test_clk_param *clk = test->param_value; + struct cs42l84_test_priv *priv = test->priv; + int pll_stop, refclk_stop; + + cs42l84_test_set_clk(test, clk); + priv->lock_status = 0; + + KUNIT_EXPECT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), + -ETIMEDOUT); + KUNIT_EXPECT_GT(test, priv->num_lock_reads, 0); + + /* Still on the oscillator */ + KUNIT_EXPECT_EQ(test, cs42l84_test_count_writes(priv, CS42L84_CCM_CTL1), 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L84_CCM_CTL1], CS42L84_CCM_CTL1_RCO); + + /* The PLL was started and stopped again, then its reference clock */ + pll_stop = cs42l84_test_last_write(priv, CS42L84_PLL_CTL1); + KUNIT_ASSERT_GE(test, pll_stop, 0); + KUNIT_EXPECT_EQ(test, priv->writes[pll_stop].val & CS42L84_PLL_CTL1_EN, 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L84_PLL_CTL1] & CS42L84_PLL_CTL1_EN, 0); + + refclk_stop = cs42l84_test_last_write(priv, CS42L84_CCM_CTL4); + KUNIT_ASSERT_GT(test, refclk_stop, pll_stop); + KUNIT_EXPECT_EQ(test, priv->writes[refclk_stop].val & CS42L84_CCM_CTL4_REFCLK_EN, 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L84_CCM_CTL4] & CS42L84_CCM_CTL4_REFCLK_EN, 0); + + /* DAC still muted, stream not counted as running */ + KUNIT_EXPECT_EQ(test, cs42l84_test_count_writes(priv, CS42L84_DAC_CTL1), 0); + KUNIT_EXPECT_EQ(test, priv->regs[CS42L84_DAC_CTL1] & CS42L84_DAC_CTL1_UNMUTE, 0); + KUNIT_EXPECT_EQ(test, priv->cs42l84.stream_use, 0); +} + +/* No PLL lock at D2 must not be mistaken for a usable clock at resume. */ +static void cs42l84_test_resume_without_pll_lock(struct kunit *test) +{ + struct cs42l84_test_priv *priv = test->priv; + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "card power state needs CONFIG_PM"); + + cs42l84_test_set_power(priv, SNDRV_CTL_POWER_D2); + cs42l84_test_unmute_pll_lock_timeout(test); +} + +/* + * A failed unmute leaves stream_use clear, so the next unmute retries the + * whole switch instead of assuming the codec is already on the PLL. + */ +static void cs42l84_test_unmute_after_pll_lock_timeout(struct kunit *test) +{ + const struct cs42l84_test_clk_param *clk = test->param_value; + struct cs42l84_test_priv *priv = test->priv; + + cs42l84_test_set_clk(test, clk); + + priv->lock_status = 0; + KUNIT_EXPECT_LT(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + cs42l84_test_clear_log(priv); + priv->lock_status = CS42L84_PLL_LOCK_STATUS_LOCKED; + KUNIT_EXPECT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + cs42l84_test_expect_switch_to_pll(test, clk); + KUNIT_EXPECT_EQ(test, priv->cs42l84.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); +} + +/* + * Muting the last stream goes back to the oscillator before stopping the + * PLL and then its reference clock. + */ +static void cs42l84_test_mute_returns_to_rco(struct kunit *test) +{ + const struct cs42l84_test_clk_param *clk = test->param_value; + struct cs42l84_test_priv *priv = test->priv; + int dac, ccm, pll_stop, refclk_stop; + + cs42l84_test_set_clk(test, clk); + KUNIT_ASSERT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + cs42l84_test_clear_log(priv); + + KUNIT_EXPECT_EQ(test, cs42l84_test_mute(priv, 1, SNDRV_PCM_STREAM_PLAYBACK), 0); + + dac = cs42l84_test_find_write(priv, CS42L84_DAC_CTL1, 0); + KUNIT_ASSERT_GE(test, dac, 0); + KUNIT_EXPECT_EQ(test, priv->writes[dac].val & CS42L84_DAC_CTL1_UNMUTE, 0); + + ccm = cs42l84_test_find_write(priv, CS42L84_CCM_CTL1, dac); + KUNIT_ASSERT_GT(test, ccm, dac); + KUNIT_EXPECT_EQ(test, priv->writes[ccm].val, CS42L84_CCM_CTL1_RCO); + + pll_stop = cs42l84_test_find_write(priv, CS42L84_PLL_CTL1, ccm); + KUNIT_ASSERT_GT(test, pll_stop, ccm); + KUNIT_EXPECT_EQ(test, priv->writes[pll_stop].val & CS42L84_PLL_CTL1_EN, 0); + + refclk_stop = cs42l84_test_find_write(priv, CS42L84_CCM_CTL4, pll_stop); + KUNIT_ASSERT_GT(test, refclk_stop, pll_stop); + KUNIT_EXPECT_EQ(test, priv->writes[refclk_stop].val & CS42L84_CCM_CTL4_REFCLK_EN, 0); + + KUNIT_EXPECT_EQ(test, priv->cs42l84.stream_use, 0); +} + +/* Without the PLL the codec goes straight onto BCLK, no lock poll */ +static void cs42l84_test_unmute_bclk(struct kunit *test) +{ + const struct cs42l84_test_clk_param *clk = test->param_value; + struct cs42l84_test_priv *priv = test->priv; + int refclk, ccm, dac; + + cs42l84_test_set_clk(test, clk); + priv->lock_status = 0; + + KUNIT_EXPECT_EQ(test, cs42l84_test_mute(priv, 0, SNDRV_PCM_STREAM_PLAYBACK), 0); + + KUNIT_EXPECT_EQ(test, priv->num_lock_reads, 0); + KUNIT_EXPECT_EQ(test, cs42l84_test_count_writes(priv, CS42L84_PLL_CTL1), 0); + + refclk = cs42l84_test_find_write(priv, CS42L84_CCM_CTL4, 0); + KUNIT_ASSERT_GE(test, refclk, 0); + KUNIT_EXPECT_TRUE(test, priv->writes[refclk].val & CS42L84_CCM_CTL4_REFCLK_EN); + + ccm = cs42l84_test_find_write(priv, CS42L84_CCM_CTL1, refclk); + KUNIT_ASSERT_GT(test, ccm, refclk); + KUNIT_EXPECT_EQ(test, priv->writes[ccm].val, clk->ccm_ctl1); + + dac = cs42l84_test_find_write(priv, CS42L84_DAC_CTL1, ccm); + KUNIT_ASSERT_GT(test, dac, ccm); + KUNIT_EXPECT_TRUE(test, priv->writes[dac].val & CS42L84_DAC_CTL1_UNMUTE); + + KUNIT_EXPECT_EQ(test, priv->cs42l84.stream_use, BIT(SNDRV_PCM_STREAM_PLAYBACK)); +} + +static int cs42l84_test_case_init(struct kunit *test) +{ + struct cs42l84_test_priv *priv; + struct regmap *regmap; + struct device *dev; + + priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv); + priv->test = test; + test->priv = priv; + + priv->regs = kunit_kzalloc(test, CS42L84_TEST_NUM_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv->regs); + + dev = kunit_device_register(test, "cs42l84_test_drv"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + regmap = devm_regmap_init(dev, NULL, priv, &cs42l84_test_regmap_config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, regmap); + + /* Construct the minimal set of driver structs */ + priv->cs42l84.dev = dev; + priv->cs42l84.regmap = regmap; + + priv->component.dev = dev; + priv->component.card = &priv->soc_card; + snd_soc_component_init_regmap(&priv->component, regmap); + snd_soc_component_set_drvdata(&priv->component, &priv->cs42l84); + + priv->dai.dev = dev; + priv->dai.name = cs42l84_dai.name; + priv->dai.driver = &cs42l84_dai; + priv->dai.component = &priv->component; + + priv->soc_card.snd_card = &priv->card; +#ifdef CONFIG_PM + init_waitqueue_head(&priv->card.power_sleep); + snd_refcount_init(&priv->card.power_ref); +#endif + cs42l84_test_set_power(priv, SNDRV_CTL_POWER_D0); + + /* Idle codec: on the oscillator, PLL and REFCLK off, DAC muted */ + priv->regs[CS42L84_CCM_CTL1] = CS42L84_CCM_CTL1_RCO; + priv->lock_status = CS42L84_PLL_LOCK_STATUS_LOCKED; + + return 0; +} + +static void cs42l84_test_clk_desc(const struct cs42l84_test_clk_param *param, char *desc) +{ + snprintf(desc, KUNIT_PARAM_DESC_SIZE, "BCLK %u Hz, %u Hz", param->bclk, param->rate); +} + +KUNIT_ARRAY_PARAM(cs42l84_test_pll_clks, cs42l84_test_pll_clks, cs42l84_test_clk_desc); +KUNIT_ARRAY_PARAM(cs42l84_test_bclk_clks, cs42l84_test_bclk_clks, cs42l84_test_clk_desc); + +static struct kunit_case cs42l84_test_cases[] = { + KUNIT_CASE_PARAM(cs42l84_test_resume_without_prepare, cs42l84_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l84_test_resume_without_prepare_bclk, cs42l84_test_bclk_clks_gen_params), + KUNIT_CASE_PARAM(cs42l84_test_unmute_pll_locked, cs42l84_test_pll_clks_gen_params), + KUNIT_CASE(cs42l84_test_unmute_pll_lock_error_bit), + KUNIT_CASE_PARAM(cs42l84_test_unmute_pll_lock_timeout, cs42l84_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l84_test_resume_without_pll_lock, cs42l84_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l84_test_unmute_after_pll_lock_timeout, + cs42l84_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l84_test_mute_returns_to_rco, cs42l84_test_pll_clks_gen_params), + KUNIT_CASE_PARAM(cs42l84_test_unmute_bclk, cs42l84_test_bclk_clks_gen_params), + { } /* terminator */ +}; + +static struct kunit_suite cs42l84_test_suite = { + .name = "snd-soc-cs42l84-test", + .init = cs42l84_test_case_init, + .test_cases = cs42l84_test_cases, +}; + +kunit_test_suite(cs42l84_test_suite); diff --git a/sound/soc/codecs/cs42l84.c b/sound/soc/codecs/cs42l84.c index 48d8e95a53405a..b8c85c5b96f081 100644 --- a/sound/soc/codecs/cs42l84.c +++ b/sound/soc/codecs/cs42l84.c @@ -608,6 +608,12 @@ static int cs42l84_mute_stream(struct snd_soc_dai *dai, int mute, int stream) CS42L84_CCM_CTL4_REFCLK_EN, 0); } } else { + /* + * ASoC also unmutes here at D2 during card resume. A PCM + * advertising RESUME can restart without another prepare, so + * do not discard that unmute based on the card power state. + * The PLL path below still requires lock before switching. + */ if (!cs42l84->stream_use) { /* SCLK must be running before codec unmute. * @@ -636,8 +642,24 @@ static int cs42l84_mute_stream(struct snd_soc_dai *dai, int mute, int stream) (regval & CS42L84_PLL_LOCK_STATUS_LOCKED), CS42L84_PLL_LOCK_POLL_US, CS42L84_PLL_LOCK_TIMEOUT_US); - if (ret < 0) + if (ret < 0) { + /* + * Without a locked PLL the codec has no clock + * once it leaves the oscillator, and then the + * I2C bus stops working. Stay on the oscillator + * and undo what was enabled above, in the same + * order as the mute path. + */ dev_warn(component->dev, "PLL failed to lock: %d\n", ret); + snd_soc_component_update_bits(component, + CS42L84_PLL_CTL1, + CS42L84_PLL_CTL1_EN, 0); + snd_soc_component_update_bits(component, + CS42L84_CCM_CTL4, + CS42L84_CCM_CTL4_REFCLK_EN, + 0); + return ret; + } if (regval & CS42L84_PLL_LOCK_STATUS_ERROR) dev_warn(component->dev, "PLL lock error\n"); @@ -1224,3 +1246,7 @@ MODULE_AUTHOR("Martin PoviÅ¡er "); MODULE_AUTHOR("Hector Martin "); MODULE_AUTHOR("James Calligeros "); MODULE_LICENSE("GPL"); + +#if IS_ENABLED(CONFIG_SND_SOC_CS42L84_TEST) +#include "cs42l84-test.c" +#endif diff --git a/sound/soc/samsung/i2s.c b/sound/soc/samsung/i2s.c index f80e8d49815652..525126ecb0c302 100644 --- a/sound/soc/samsung/i2s.c +++ b/sound/soc/samsung/i2s.c @@ -1518,9 +1518,16 @@ static int samsung_i2s_probe(struct platform_device *pdev) goto err_disable_pm; priv->op_clk = clk_get_parent(priv->clk_table[CLK_I2S_RCLK_SRC]); + ret = clk_prepare_enable(priv->op_clk); + if (ret < 0) { + priv->op_clk = NULL; + goto err_unregister_clk; + } return 0; +err_unregister_clk: + i2s_unregister_clock_provider(priv); err_disable_pm: pm_runtime_disable(&pdev->dev); err_del_sec: @@ -1543,6 +1550,7 @@ static void samsung_i2s_remove(struct platform_device *pdev) i2s_unregister_clock_provider(priv); i2s_delete_secondary_device(priv); + clk_disable_unprepare(priv->op_clk); clk_disable_unprepare(priv->clk); pm_runtime_put_noidle(&pdev->dev); diff --git a/sound/soc/sdw_utils/soc_sdw_utils.c b/sound/soc/sdw_utils/soc_sdw_utils.c index 5266720e58b3ce..a47f34afd1d19c 100644 --- a/sound/soc/sdw_utils/soc_sdw_utils.c +++ b/sound/soc/sdw_utils/soc_sdw_utils.c @@ -797,7 +797,7 @@ struct asoc_sdw_codec_info codec_info_list[] = { }, { .direction = {false, true}, - .dai_name = "cs35l56-sdw1c", + .dai_name = "cs35l56-ot25", .dai_type = SOC_SDW_DAI_TYPE_AMP, .dailink = {SOC_SDW_UNUSED_DAI_ID, SOC_SDW_AMP_IN_DAI_ID}, .rtd_init = asoc_sdw_cs_spk_feedback_rtd_init, @@ -826,7 +826,36 @@ struct asoc_sdw_codec_info codec_info_list[] = { }, { .direction = {false, true}, - .dai_name = "cs35l56-sdw1c", + .dai_name = "cs35l56-ot25", + .dai_type = SOC_SDW_DAI_TYPE_AMP, + .dailink = {SOC_SDW_UNUSED_DAI_ID, SOC_SDW_AMP_IN_DAI_ID}, + .rtd_init = asoc_sdw_cs_spk_feedback_rtd_init, + }, + }, + .dai_num = 2, + }, + { + .vendor_id = 0x01fa, + .part_id = 0x3562, + .name_prefix = "AMP", + .is_amp = true, + .dais = { + { + .direction = {true, false}, + .dai_name = "cs35l56-sdw1", + .component_name = "cs35l56", + .dai_type = SOC_SDW_DAI_TYPE_AMP, + .dailink = {SOC_SDW_AMP_OUT_DAI_ID, SOC_SDW_UNUSED_DAI_ID}, + .init = asoc_sdw_cs_amp_init, + .rtd_init = asoc_sdw_cs_spk_rtd_init, + .controls = generic_spk_controls, + .num_controls = ARRAY_SIZE(generic_spk_controls), + .widgets = generic_spk_widgets, + .num_widgets = ARRAY_SIZE(generic_spk_widgets), + }, + { + .direction = {false, true}, + .dai_name = "cs35l56-ot25", .dai_type = SOC_SDW_DAI_TYPE_AMP, .dailink = {SOC_SDW_UNUSED_DAI_ID, SOC_SDW_AMP_IN_DAI_ID}, .rtd_init = asoc_sdw_cs_spk_feedback_rtd_init, @@ -855,7 +884,7 @@ struct asoc_sdw_codec_info codec_info_list[] = { }, { .direction = {false, true}, - .dai_name = "cs35l56-sdw1c", + .dai_name = "cs35l56-ot25", .dai_type = SOC_SDW_DAI_TYPE_AMP, .dailink = {SOC_SDW_UNUSED_DAI_ID, SOC_SDW_AMP_IN_DAI_ID}, .rtd_init = asoc_sdw_cs_spk_feedback_rtd_init, diff --git a/tools/asahi/atc-usb3-tests.py b/tools/asahi/atc-usb3-tests.py new file mode 100644 index 00000000000000..5e45e11c3c46d6 --- /dev/null +++ b/tools/asahi/atc-usb3-tests.py @@ -0,0 +1,880 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +"""Host regression tests for the ATCPHY USB3 handoff. + +Compile the actual driver functions, defines, enums and mode table. MMIO polling +models a single completed timeout/success per invocation; no timing, electrical +behavior, firmware, real BIST sequence or kernel mutex behavior is simulated. +The actual admission helper restricts the workaround to base M1 machines; +T600x/T8112/T602x still match the T8103 PHY fallback but keep their previous +single-poll/BIST/role behavior. OF compatible lookup is a modeled boundary. +The DT-to-driver match contract is checked from the actual sources. +Hardware qualification remains necessary. +Run --mutations for sensitivity checks. +""" + +import argparse +import json +import hashlib +import os +from pathlib import Path +import re +import subprocess +import tempfile + + +def block(source, marker): + if marker.startswith("static"): + # Skip a forward declaration; the next opening brace after a prototype + # belongs to an unrelated function. + match = re.search(re.escape(marker) + r"[^;{]*\{", source) + if match is None: + raise ValueError("function definition not found: " + marker) + start = match.start() + else: + start = source.index(marker) + opening = source.index("{", start) + depth = 1 + pos = opening + 1 + while depth: + if source[pos] == "{": + depth += 1 + elif source[pos] == "}": + depth -= 1 + pos += 1 + return source[start:pos] + (";" if source[pos:pos + 1] == ";" else "") + + +PRELUDE = r''' +#include +#include +#include +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define BIT(n) (1U << (n)) +#define GENMASK(h,l) ((UINT32_MAX >> (31-(h))) & (UINT32_MAX << (l))) +#define dev_warn(...) ((void)0) +#define dev_err(...) ((void)0) +#define dev_dbg(...) ((void)0) +#define lockdep_assert_held(...) ((void)0) +#define guard(which) (void) +#define IS_ENABLED(x) 0 +#define KUNIT_STATIC_STUB_REDIRECT(...) ((void)0) +#define __iomem +#define FIELD_PREP(mask,value) (((u32)(value) << __builtin_ctz(mask)) & (mask)) +#define FIELD_GET(mask,value) (((value) & (mask)) >> __builtin_ctz(mask)) +#define fallthrough __attribute__((fallthrough)) +#define WARN_ON_ONCE(cond) do { if (cond) warnings++; } while (0) +#define container_of(ptr,type,member) ((type *)((char *)(ptr) - offsetof(type,member))) +''' + +STUBS = r''' +struct atcphy_hw { enum atcphy_generation gen; + bool has_t8140_dp, dp_t8122, has_usb4, park_pipe_unlocked, park_dummy_phy; }; +struct device_node { const char *const *compatible; unsigned int count; }; +static bool of_device_is_compatible(const struct device_node *root, const char *compatible) { + if (!root) return false; + for (unsigned int i = 0; i < root->count; i++) + if (!strcasecmp(root->compatible[i], compatible)) return true; + return false; +} +/* ACTUAL_ADMISSION */ +struct reset_controller_dev { int unused; }; +struct apple_atcphy { + struct atcphy_hw *hw; + struct { unsigned char *pipehandler, *core; } regs; + void *dev; + int lock; + struct reset_controller_dev rcdev; + enum atcphy_mode mode; + enum atcphy_pipehandler_state pipe_state; + enum atcphy_mode typec_mode; + bool pipe_pending, t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround, mode_dirty, usb_off_pending; + bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, t8140_dp_tunables, dp_tunables; +}; +struct phy { struct apple_atcphy *data; }; +struct typec_mux_dev { struct apple_atcphy *data; }; +struct typec_altmode { unsigned svid; }; +struct typec_mux_state { unsigned long mode; struct typec_altmode *alt; void *data; }; +struct enter_usb_data { u32 eudo; }; +enum phy_mode { PHY_MODE_USB_HOST, PHY_MODE_USB_DEVICE, PHY_MODE_INVALID }; +static unsigned char memory[0x18000] __attribute__((aligned(4))); +static struct atcphy_hw hw; +static struct apple_atcphy p; +static struct phy phy; +static unsigned polls, sleeps, sets, clears, muxes, bist_old, bist_new; +static unsigned configure_calls, restore_calls, unlocks, warnings; +static unsigned dummy_muxes, pending_seen_at_unlock; +static unsigned usb2_power_off_calls; +static unsigned ack_on; +static int check_ret, bist_ret, unlock_ret, configure_ret; +static bool concurrent_override_change; +static u32 readl(const void *ptr) { u32 v; memcpy(&v, ptr, sizeof(v)); return v; } +static void writel(u32 val, void *ptr) { memcpy(ptr, &val, sizeof(val)); } +static void set32(void *ptr, u32 mask) { + if (ptr == memory + PIPEHANDLER_LOCK_REQ) sets++; + writel(readl(ptr) | mask, ptr); +} +static void clear32(void *ptr, u32 mask) { + if (ptr == memory + PIPEHANDLER_LOCK_REQ) clears++; + writel(readl(ptr) & ~mask, ptr); +} +static void mask32(void *ptr, u32 mask, u32 value) { + writel((readl(ptr) & ~mask) | value, ptr); +} +static u32 poll_value(void *ptr) { + assert(ptr == memory + PIPEHANDLER_LOCK_ACK); + polls++; + if (concurrent_override_change) { + set32(memory + PIPEHANDLER_OVERRIDE, BIT(9)); + set32(memory + PIPEHANDLER_OVERRIDE_VALUES, BIT(9)); + } + return ack_on && polls >= ack_on ? PIPEHANDLER_LOCK_EN : 0; +} +#define readl_poll_timeout(addr,val,cond,delay,timeout) \ + ({ assert((delay) == 10 && (timeout) == 1000); \ + (val) = poll_value(addr); (cond) ? 0 : -ETIMEDOUT; }) +static void usleep_range(unsigned lo, unsigned hi) { + assert(lo == 5000 && hi == 10000); sleeps++; +} +static int atcphy_pipehandler_check(struct apple_atcphy *a) { (void)a; return check_ret; } +static int atcphy_pipehandler_unlock(struct apple_atcphy *a) { + unlocks++; + if (a->pipe_state == ATCPHY_PIPEHANDLER_STATE_DUMMY && a->t8103_dummy_pending) + pending_seen_at_unlock++; + clear32(a->regs.pipehandler + PIPEHANDLER_LOCK_REQ, PIPEHANDLER_LOCK_EN); + return unlock_ret; +} +static int atcphy_configure_pipehandler_usb3_host_t8103(struct apple_atcphy *a) { + (void)a; bist_old++; return bist_ret; +} +static int atcphy_configure_pipehandler_usb3_host_t8122(struct apple_atcphy *a) { + (void)a; bist_new++; return bist_ret; +} +static void atcphy_pipehandler_set_mux(struct apple_atcphy *a, u32 data, u32 clk) { + (void)a; + assert((data == PIPEHANDLER_MUX_CTRL_DATA_USB3 && clk == PIPEHANDLER_MUX_CTRL_CLK_USB3) || + (data == PIPEHANDLER_MUX_CTRL_DATA_DUMMY && clk == PIPEHANDLER_MUX_CTRL_CLK_DUMMY) || + (data == PIPEHANDLER_MUX_CTRL_DATA_USB4 && clk == PIPEHANDLER_MUX_CTRL_CLK_USB4)); + if (data == PIPEHANDLER_MUX_CTRL_DATA_DUMMY) dummy_muxes++; + muxes++; +} +static struct apple_atcphy *phy_get_drvdata(struct phy *f) { return f->data; } +static struct apple_atcphy *typec_mux_get_drvdata(struct typec_mux_dev *m) { return m->data; } +static void atcphy_restore_after_pd_off(struct apple_atcphy *a) { (void)a; restore_calls++; } +static int atcphy_usb2_power_off(struct apple_atcphy *a) { + (void)a; usb2_power_off_calls++; return 0; +} +static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) { + /* ACTUAL_CONFIGURE_ENTRY */ + struct apple_atcphy *a = atcphy; + configure_calls++; + assert(!a->t8103_dummy_pending); + if (!configure_ret) { a->mode = mode; a->mode_dirty = false; } + else a->mode_dirty = true; + return configure_ret; +} +static void reset(enum atcphy_generation generation, bool t8140) { + memset(memory, 0, sizeof(memory)); + hw = (struct atcphy_hw){ .gen = generation, .has_t8140_dp = t8140 }; + p = (struct apple_atcphy){ .hw = &hw, .regs = {memory, memory}, + .mode = APPLE_ATCPHY_MODE_OFF, .typec_mode = APPLE_ATCPHY_MODE_USB3, + .ss_tunables = true }; + const char *const compatibles[] = {generation == ATCPHY_GENERATION_T8103 ? "apple,t8103" : "apple,t8122"}; + const struct device_node root = {compatibles, 1}; + p.t8103_usb3_workaround = atcphy_has_t8103_usb3_workaround(&hw, &root); + phy.data = &p; + polls = sleeps = sets = clears = muxes = bist_old = bist_new = 0; + configure_calls = restore_calls = unlocks = warnings = 0; + dummy_muxes = pending_seen_at_unlock = 0; + usb2_power_off_calls = 0; + ack_on = 1; + check_ret = bist_ret = unlock_ret = configure_ret = 0; + concurrent_override_change = false; +} +static void reset_machine(enum atcphy_generation generation, const char *machine) { + reset(generation, false); + const char *const compatibles[] = {"apple,synthetic-board", machine}; + const struct device_node root = {compatibles, 2}; + p.t8103_usb3_workaround = atcphy_has_t8103_usb3_workaround(&hw, &root); +} +''' + +TESTS = r''' +static unsigned tests; +#define TEST(name) do { name(); tests++; } while (0) +static void live_retry_last(void) { + reset(ATCPHY_GENERATION_T8103,false); ack_on=10; + writel(BIT(7),memory+PIPEHANDLER_LOCK_REQ); + assert(!atcphy_pipehandler_lock_live(&p)); + assert(polls==10 && sleeps==9 && sets==10 && clears==9); + assert(readl(memory+PIPEHANDLER_LOCK_REQ)==(BIT(7)|PIPEHANDLER_LOCK_EN)); +} +static void live_retry_exhausted(void) { + reset(ATCPHY_GENERATION_T8103,false); ack_on=0; + assert(atcphy_pipehandler_lock_live(&p)==-ETIMEDOUT); + assert(polls==10 && sleeps==9 && sets==10 && clears==10); +} +static void request_is_not_ack(void) { + reset(ATCPHY_GENERATION_T8103,false); ack_on=2; + writel(PIPEHANDLER_LOCK_EN,memory+PIPEHANDLER_LOCK_REQ); + assert(!atcphy_pipehandler_lock_live(&p)); + assert(polls==2 && sleeps==1 && sets==1 && clears==1); +} +static void requested_ack_no_writes(void) { + reset(ATCPHY_GENERATION_T8103,false); + writel(PIPEHANDLER_LOCK_EN,memory+PIPEHANDLER_LOCK_REQ); + assert(!atcphy_pipehandler_lock_live(&p)); assert(polls==1 && !sets && !clears && !sleeps); +} +static void later_ack_semantics_unchanged(void) { + for(unsigned neo=0;neo<2;neo++) { + reset(ATCPHY_GENERATION_T8122,neo); ack_on=0; + writel(PIPEHANDLER_LOCK_EN,memory+PIPEHANDLER_LOCK_REQ); + assert(atcphy_pipehandler_lock_live(&p)==-ETIMEDOUT); + assert(polls==1 && !sleeps && !sets && clears==1); + } +} +static void usb4_and_dead_parking_single_poll(void) { + reset(ATCPHY_GENERATION_T8103,false); ack_on=0; + assert(!atcphy_configure_pipehandler_usb4(&p)); assert(polls==1 && !sleeps); + reset(ATCPHY_GENERATION_T8103,false); ack_on=0; + p.pipe_state=ATCPHY_PIPEHANDLER_STATE_USB4; + assert(!atcphy_park_pipehandler(&p,true)); assert(polls==1 && !sleeps); +} +static void early_host_and_device(void) { + for(unsigned host=0;host<2;host++) { + reset(ATCPHY_GENERATION_T8103,false); + assert(!atcphy_usb3_set_mode(&phy,host?PHY_MODE_USB_HOST:PHY_MODE_USB_DEVICE,0)); + assert(p.mode==APPLE_ATCPHY_MODE_USB3 && p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3); + assert(configure_calls==1 && muxes==1 && !polls && !bist_old && !bist_new); + assert(p.host_active==host && !p.pipe_pending); + assert(!atcphy_usb3_set_mode(&phy,host?PHY_MODE_USB_HOST:PHY_MODE_USB_DEVICE,0)); + assert(configure_calls==1 && muxes==1); + } +} +static void early_admission_and_failure(void) { + reset(ATCPHY_GENERATION_T8103,false);p.ss_tunables=false; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-EOPNOTSUPP);assert(!configure_calls&&!muxes); + reset(ATCPHY_GENERATION_T8103,false);p.dp_only=true; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-EOPNOTSUPP);assert(!configure_calls&&!muxes); + reset(ATCPHY_GENERATION_T8103,false);configure_ret=-EIO; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-EIO);assert(configure_calls==1&&!muxes); +} +static void later_off_and_bist_unchanged(void) { + for(unsigned neo=0;neo<2;neo++) { + reset(ATCPHY_GENERATION_T8122,neo); + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0));assert(p.mode==APPLE_ATCPHY_MODE_OFF&&!configure_calls&&!muxes); + p.mode=APPLE_ATCPHY_MODE_USB3; + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0));assert(bist_new==1&&!bist_old&&polls==1); + } +} +static void success_only_all_generations(void) { + for(unsigned gen=0;gen<2;gen++)for(unsigned mode=0;mode<2;mode++) { + reset(gen?ATCPHY_GENERATION_T8122:ATCPHY_GENERATION_T8103,false); + p.mode=mode?APPLE_ATCPHY_MODE_USB4:APPLE_ATCPHY_MODE_USB3;check_ret=-EIO; + assert(atcphy_configure_pipehandler(&p,true)==-EIO); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY&&!muxes); + check_ret=0;assert(!atcphy_configure_pipehandler(&p,true)); + assert(p.pipe_state==atcphy_modes[p.mode].pipehandler_state&&!p.pipe_pending); + } +} +static void setup_legacy_usb3(void) { + reset(ATCPHY_GENERATION_T8103,false);p.mode=APPLE_ATCPHY_MODE_USB3;p.pipe_state=ATCPHY_PIPEHANDLER_STATE_USB3; +} +static void live_lock_failure_restores_masks(void) { + setup_legacy_usb3();ack_on=0;concurrent_override_change=true; + writel(BIT(7),memory+PIPEHANDLER_OVERRIDE); + writel(BIT(7)|PIPEHANDLER_OVERRIDE_VAL_RXDETECT0,memory+PIPEHANDLER_OVERRIDE_VALUES); + assert(atcphy_park_live_t8103_pipehandler(&p)==-ETIMEDOUT); + assert(polls==10&&sleeps==9&&!muxes&&!unlocks); + assert(readl(memory+PIPEHANDLER_OVERRIDE)==(BIT(7)|BIT(9))); + assert(readl(memory+PIPEHANDLER_OVERRIDE_VALUES)==(BIT(7)|BIT(9)|PIPEHANDLER_OVERRIDE_VAL_RXDETECT0)); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3&&!p.t8103_dummy_pending&&!p.t8103_usb3_retry&&!p.mode_dirty); +} +static void live_park_then_pending_completion(void) { + setup_legacy_usb3();unlock_ret=-ETIMEDOUT; + assert(atcphy_park_live_t8103_pipehandler(&p)==-ETIMEDOUT); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY&&p.t8103_dummy_pending&&p.t8103_usb3_retry); + assert(muxes==1&&polls==1&&pending_seen_at_unlock==1); + unsigned savedpolls=polls; + assert(atcphy_park_pipehandler(&p,true)==-ETIMEDOUT);assert(polls==savedpolls&&muxes==1&&unlocks==2); + unlock_ret=0;assert(!atcphy_park_pipehandler(&p,true)); + assert(!p.t8103_dummy_pending&&p.t8103_usb3_retry&&unlocks==3&&polls==savedpolls); + assert(readl(memory+PIPEHANDLER_NONSELECTED_OVERRIDE)&PIPEHANDLER_NATIVE_RESET); +} +static void legacy_live_dispatch_and_generation(void) { + setup_legacy_usb3();ack_on=0; + assert(atcphy_park_pipehandler(&p,false)==-ETIMEDOUT);assert(polls==10&&!muxes); + reset(ATCPHY_GENERATION_T8122,true);p.fixed_usb2=true;p.host_active=true;p.pipe_pending=true;p.pipe_state=ATCPHY_PIPEHANDLER_STATE_USB3;ack_on=0; + assert(atcphy_park_pipehandler(&p,false)==-ETIMEDOUT);assert(polls==1&&!sleeps&&!muxes&&p.mode_dirty); + assert(atcphy_park_live_t8103_pipehandler(&p)==-EOPNOTSUPP); +} +static void pending_blocks_lane_and_backend(void) { + setup_legacy_usb3();p.t8103_dummy_pending=true; + assert(atcphy_configure(&p,APPLE_ATCPHY_MODE_DP)==-EBUSY);assert(!configure_calls); + assert(atcphy_configure_pipehandler(&p,true)==-EBUSY);assert(!muxes); +} +static void canceled_lane_change_reconnects(void) { + setup_legacy_usb3();unlock_ret=-ETIMEDOUT; + assert(atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_DP)==-ETIMEDOUT); + assert(p.mode==APPLE_ATCPHY_MODE_USB3&&p.t8103_dummy_pending&&p.t8103_usb3_retry&&!configure_calls); + assert(!atcphy_mux_in_mode(&p,APPLE_ATCPHY_MODE_USB3));assert(!atcphy_mux_is_noop(&p,APPLE_ATCPHY_MODE_USB3)); + unlock_ret=0;assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3&&!p.t8103_dummy_pending&&!p.t8103_usb3_retry); + assert(polls==1&&dummy_muxes==1&&muxes==2&&!configure_calls&&!bist_old&&!bist_new); +} +static void role_finishes_pending(void) { + setup_legacy_usb3();unlock_ret=-ETIMEDOUT;assert(atcphy_park_live_t8103_pipehandler(&p)==-ETIMEDOUT); + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-ETIMEDOUT);assert(muxes==1); + unlock_ret=0;assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3&&!p.t8103_usb3_retry&&!p.t8103_dummy_pending&&muxes==2); +} +static void target_failure_preserves_reconnect(void) { + setup_legacy_usb3();configure_ret=-EIO; + assert(atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_DP)==-EIO); + assert(p.t8103_usb3_retry&&!p.t8103_dummy_pending&&p.mode_dirty); + configure_ret=0;assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3&&!p.t8103_usb3_retry&&!p.mode_dirty); +} +static void nonusb_commit_clears_retry(void) { + setup_legacy_usb3();assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_DP)); + assert(p.mode==APPLE_ATCPHY_MODE_DP&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY&&!p.t8103_usb3_retry&&!p.t8103_dummy_pending); +} +static void dp_assignment_d_retains_usb3(void) { + setup_legacy_usb3();assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3_DP)); + assert(p.mode==APPLE_ATCPHY_MODE_USB3_DP&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3&&!polls&&!muxes&&!warnings); +} +static void modern_safe_refusal_retained(void) { + setup_legacy_usb3();assert(atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_OFF)==-EBUSY);assert(!polls&&!muxes&&!configure_calls); +} +static void fixed_hub_host_dispatch(void) { + for(unsigned gen=0;gen<2;gen++) { + reset(gen?ATCPHY_GENERATION_T8122:ATCPHY_GENERATION_T8103,false);p.fixed_usb2=true;p.host_active=true; + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.mode==APPLE_ATCPHY_MODE_USB3&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3); + assert(bist_new==gen&&!bist_old&&configure_calls==1&&muxes==1); + } +} +static void reset_release_retries_before_writes(void) { + setup_legacy_usb3();unlock_ret=-ETIMEDOUT;assert(atcphy_park_live_t8103_pipehandler(&p)==-ETIMEDOUT); + u32 aon=BIT(14)|PIPEHANDLER_AON_GEN_DWC3_FORCE_CLAMP_EN;writel(aon,memory+PIPEHANDLER_AON_GEN); + assert(atcphy_dwc3_reset_deassert(&p.rcdev,0)==-ETIMEDOUT);assert(readl(memory+PIPEHANDLER_AON_GEN)==aon); + unlock_ret=0;assert(!atcphy_dwc3_reset_deassert(&p.rcdev,0));assert(!p.t8103_dummy_pending&&p.t8103_usb3_retry); + assert(readl(memory+PIPEHANDLER_AON_GEN)==((aon&~PIPEHANDLER_AON_GEN_DWC3_FORCE_CLAMP_EN)|PIPEHANDLER_AON_GEN_DWC3_RESET_N)); + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0));assert(!p.t8103_usb3_retry&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3); +} +static void reset_assert_failure_and_stop(void) { + setup_legacy_usb3();unlock_ret=-ETIMEDOUT;assert(atcphy_park_live_t8103_pipehandler(&p)==-ETIMEDOUT); + u32 aon=BIT(14)|PIPEHANDLER_AON_GEN_DWC3_RESET_N;writel(aon,memory+PIPEHANDLER_AON_GEN); + assert(atcphy_dwc3_reset_assert(&p.rcdev,0)==-ETIMEDOUT);assert(readl(memory+PIPEHANDLER_AON_GEN)==aon&&!usb2_power_off_calls); + unlock_ret=0;assert(!atcphy_dwc3_reset_assert(&p.rcdev,0));assert(!p.t8103_dummy_pending&&!p.t8103_usb3_retry&&usb2_power_off_calls==1); +} +static void power_off_preserves_dp_and_finishes_pending(void) { + setup_legacy_usb3();unlock_ret=-ETIMEDOUT;assert(atcphy_park_live_t8103_pipehandler(&p)==-ETIMEDOUT);p.mode=APPLE_ATCPHY_MODE_USB3_DP; + assert(atcphy_usb3_power_off(&phy)==-ETIMEDOUT);assert(!configure_calls); + unlock_ret=0;assert(!atcphy_usb3_power_off(&phy));assert(p.mode==APPLE_ATCPHY_MODE_USB3_DP&&!configure_calls&&!p.t8103_usb3_retry&&!p.t8103_dummy_pending); +} +static void setup_known_reset_clears_obligations(void) { + setup_legacy_usb3();p.t8103_dummy_pending=p.t8103_usb3_retry=true;p.pipe_pending=true; + atcphy_setup_pipehandler(&p);assert(!p.t8103_dummy_pending&&!p.t8103_usb3_retry&&!p.pipe_pending&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY); +} +static void target_mode_table_and_dirty(void) { + reset(ATCPHY_GENERATION_T8103,false);struct typec_mux_state state={.mode=TYPEC_DP_STATE_D};struct typec_altmode alt={.svid=USB_TYPEC_DP_SID};state.alt=&alt; + assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_USB3_DP);state.mode=TYPEC_DP_STATE_C; + assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_DP); + p.mode=APPLE_ATCPHY_MODE_USB3;p.mode_dirty=true;assert(atcphy_usb3_route(&p,true)==-EBUSY);assert(!muxes&&!configure_calls); + p.mode_dirty=false;p.usb_off_pending=true;assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-EBUSY); +} +static void live_park_finishes_generic_pending(void) { + setup_legacy_usb3(); p.pipe_pending=true; + assert(!atcphy_park_pipehandler(&p,false)); + assert(!p.pipe_pending && !p.t8103_dummy_pending && p.t8103_usb3_retry); + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_DP)); + assert(p.mode==APPLE_ATCPHY_MODE_DP&&!p.t8103_usb3_retry); +} +static void fixed_hub_nonusb3_commit_discharges_retry(void) { + setup_legacy_usb3();p.fixed_usb2=true;p.host_active=true; + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_DP)); + assert(!p.t8103_usb3_retry&&!p.t8103_dummy_pending&&!p.pipe_pending); + assert(atcphy_mux_in_mode(&p,APPLE_ATCPHY_MODE_DP)); + assert(atcphy_mux_is_noop(&p,APPLE_ATCPHY_MODE_DP)); +} +static void actual_dt_fallback_generation_scope(void) { + for(unsigned i=0;iusb_off_pending") + stubs = STUBS.replace("/* ACTUAL_CONFIGURE_ENTRY */", configure[guard_start:guard_end]) + stubs = stubs.replace("/* ACTUAL_ADMISSION */", + block(source, "static bool atcphy_has_t8103_usb3_workaround(")) + scope_c += "static const char *const scope_machines[] = {" + ",".join( + json.dumps(row["machine_compatible"]) for row in scope) + "};\n" + return PRELUDE + defines + "\n" + "\n".join(usb_defines) + "\n" + types + "\n" + table + stubs + functions + scope_c + TESTS + + +MUTATIONS = {'no-live-retry': ('atcphy_pipehandler_lock_live', '? 10 : 1;', '? 1 : 1;'), + 'retry-later-generations': ('atcphy_pipehandler_lock_live', '? 10 : 1;', '? 10 : 10;'), + 'sleep-after-last': ('atcphy_pipehandler_lock_live', 'if (attempt + 1 < attempts)', 'if (true)'), + 'missing-ack-check': ('atcphy_pipehandler_lock', + 'if (requested & PIPEHANDLER_LOCK_EN) {', + 'if (requested & PIPEHANDLER_LOCK_EN) return 0;\n' + '\tif (requested & PIPEHANDLER_LOCK_EN) {'), + 'usb4-live-retry': ('atcphy_configure_pipehandler_usb4', + 'atcphy_pipehandler_lock(atcphy)', + 'atcphy_pipehandler_lock_live(atcphy)'), + 'dead-park-live-retry': ('atcphy_configure_pipehandler_dummy', + 'atcphy_pipehandler_lock(atcphy)', + 'atcphy_pipehandler_lock_live(atcphy)'), + 'early-missing-tunables': ('atcphy_usb3_route', + 'if (atcphy->dp_only || !atcphy->ss_tunables)', + 'if (atcphy->dp_only)'), + 'early-missing-dp-only': ('atcphy_usb3_route', + 'if (atcphy->dp_only || !atcphy->ss_tunables)', + 'if (!atcphy->ss_tunables)'), + 'early-all-generations': ('atcphy_usb3_route', + 'atcphy->t8103_usb3_workaround &&', + 'true &&'), + 'early-ignores-typec-request': ('atcphy_usb3_route', + 'atcphy->typec_mode != APPLE_ATCPHY_MODE_USB3', + 'false'), + 'early-role-not-remembered': ('atcphy_usb3_route', + 'atcphy->t8103_usb3_retry = true;', + '(void)0;'), + 'early-configure-error-loses-obligation': ('atcphy_usb3_route', + 'atcphy->t8103_usb3_retry = true;', + 'if (atcphy->typec_mode != APPLE_ATCPHY_MODE_USB3) atcphy->t8103_usb3_retry = true;'), + 'same-mode-nonusb3-keeps-role-obligation': ('atcphy_mux_switch', + '\t\t\tatcphy->t8103_usb3_retry = false;\n\t\t}\n\t\t/* Retry a failed PIPE setup', + '\t\t\t(void)0;\n\t\t}\n\t\t/* Retry a failed PIPE setup'), + 'admission-ignores-machine': ('bool atcphy_has_t8103_usb3_workaround', + 'of_device_is_compatible(root, "apple,t8103")', + 'true'), + 'admission-ignores-generation': ('bool atcphy_has_t8103_usb3_workaround', + 'hw->gen == ATCPHY_GENERATION_T8103 &&', + 'true &&'), + 'bist-restored-t8103': ('atcphy_configure_pipehandler', + 'host && !atcphy->t8103_usb3_workaround', + 'host'), + 'bist-skipped-later': ('atcphy_configure_pipehandler', + 'host && !atcphy->t8103_usb3_workaround', + 'false'), + 'bist-skipped-fallback-machines': ('atcphy_configure_pipehandler', + 'host && !atcphy->t8103_usb3_workaround', + 'host && atcphy->hw->gen != ATCPHY_GENERATION_T8103'), + 'failed-state-published': ('atcphy_configure_pipehandler', 'if (!ret) {', 'if (true) {'), + 'live-generation-gate-removed': ('atcphy_park_live_t8103_pipehandler', + 'if (!atcphy->t8103_usb3_workaround)', + 'if (false)'), + 'live-park-dispatch-all-fallbacks': ('atcphy_park_pipehandler', + '!stopped && atcphy->t8103_usb3_workaround &&', + '!stopped && atcphy->hw->gen == ATCPHY_GENERATION_T8103 &&'), + 'mux-live-park-all-fallbacks': ('atcphy_mux_switch', + 'if (atcphy->t8103_usb3_workaround)', + 'if (atcphy->hw->gen == ATCPHY_GENERATION_T8103)'), + 'no-values-restore': ('atcphy_park_live_t8103_pipehandler', + 'mask32(pipe + PIPEHANDLER_OVERRIDE_VALUES, value_mask,\n' + '\t\t\t values & value_mask);', + '(void)values;'), + 'no-overrides-restore': ('atcphy_park_live_t8103_pipehandler', + 'mask32(pipe + PIPEHANDLER_OVERRIDE, override_mask,\n' + '\t\t\t overrides & override_mask);', + '(void)overrides;'), + 'clobber-unrelated-overrides': ('atcphy_park_live_t8103_pipehandler', + 'mask32(pipe + PIPEHANDLER_OVERRIDE, override_mask,\n' + '\t\t\t overrides & override_mask);', + 'writel(overrides, pipe + PIPEHANDLER_OVERRIDE);'), + 'no-physical-mux-state': ('atcphy_park_live_t8103_pipehandler', + 'atcphy->pipe_state = ATCPHY_PIPEHANDLER_STATE_DUMMY;', + '(void)0;'), + 'no-pending-after-move': ('atcphy_park_live_t8103_pipehandler', + 'atcphy->t8103_dummy_pending = true;', + '(void)0;'), + 'relock-pending': ('atcphy_park_live_t8103_pipehandler', + 'if (!atcphy->t8103_dummy_pending)', + 'if (true)'), + 'no-reconnect-obligation': ('atcphy_park_live_t8103_pipehandler', + 'atcphy->t8103_usb3_retry = true;', + '(void)0;'), + 'pending-cleared-before-ack': ('atcphy_park_live_t8103_pipehandler', + 'ret = atcphy_pipehandler_unlock(atcphy);', + 'atcphy->t8103_dummy_pending = false;\n' + '\tret = atcphy_pipehandler_unlock(atcphy);'), + 'park-bypasses-pending': ('atcphy_park_pipehandler', + 'if (atcphy->t8103_dummy_pending ||', + 'if (false ||'), + 'lanes-ignore-pending': ('atcphy_configure', 'if (atcphy->t8103_dummy_pending)', 'if (false)'), + 'backend-ignores-pending': ('atcphy_configure_pipehandler', + 'if (atcphy->t8103_dummy_pending)', + 'if (false)'), + 'role-ignores-pending': ('atcphy_usb3_route', 'if (atcphy->t8103_dummy_pending)', 'if (false)'), + 'mux-ignores-pending': ('atcphy_mux_switch', 'if (atcphy->t8103_dummy_pending)', 'if (false)'), + 'canceled-not-reconnected': ('atcphy_mux_switch', + 'if (atcphy_modes[target_mode].pipehandler_state == ATCPHY_PIPEHANDLER_STATE_USB3)\n\t\t\t\treturn atcphy_configure_pipehandler', + 'if (false)\n\t\t\t\treturn atcphy_configure_pipehandler'), + 'retry-cleared-at-unlock': ('atcphy_park_live_t8103_pipehandler', + 'atcphy->t8103_dummy_pending = false;', + 'atcphy->t8103_dummy_pending = false; atcphy->t8103_usb3_retry = ' + 'false;'), + 'retry-not-cleared-after-usb3': ('atcphy_configure_pipehandler', + 'atcphy->t8103_usb3_retry = false;', + '(void)0;'), + 'retry-not-cleared-after-nonusb3': ('atcphy_mux_switch', + 'return atcphy_configure_pipehandler(atcphy, false);\n' + '\t\tatcphy->t8103_usb3_retry = false;', + 'return atcphy_configure_pipehandler(atcphy, false);\n' + '\t\t(void)0;'), + 'usb3-dp-wrongly-parked': ('atcphy_mux_switch', + 'atcphy_modes[target_mode].pipehandler_state == ' + 'ATCPHY_PIPEHANDLER_STATE_DUMMY) {', + 'true) {'), + 'reset-release-ignores-pending': ('atcphy_dwc3_reset_deassert', + 'if (atcphy->t8103_dummy_pending)', + 'if (false)'), + 'reset-release-permanent-ebusy': ('atcphy_dwc3_reset_deassert', + 'if (atcphy->t8103_dummy_pending) {', + 'if (atcphy->t8103_dummy_pending) return -EBUSY;\n' + '\tif (atcphy->t8103_dummy_pending) {'), + 'reset-release-writes-early': ('atcphy_dwc3_reset_deassert', + 'if (atcphy->t8103_dummy_pending) {', + 'clear32(atcphy->regs.pipehandler + PIPEHANDLER_AON_GEN, ' + 'PIPEHANDLER_AON_GEN_DWC3_FORCE_CLAMP_EN);\n' + '\tif (atcphy->t8103_dummy_pending) {'), + 'reset-no-retry-clear': ('atcphy_dwc3_reset_assert', + 'atcphy->t8103_usb3_retry = false;', + '(void)0;'), + 'poweroff-no-retry-clear': ('atcphy_usb3_power_off', + 'atcphy->t8103_usb3_retry = false;', + '(void)0;'), + 'known-reset-no-retry-clear': ('void atcphy_setup_pipehandler', + 'atcphy->t8103_usb3_retry = false;', + '(void)0;'), + 'live-completion-leaves-generic-pending': ('atcphy_park_live_t8103_pipehandler', + 'atcphy->pipe_pending = false;', + '(void)0;'), + 'fixedhub-nonusb3-keeps-retry': ('atcphy_mux_switch', + 'if (!ret && pipe_state != ATCPHY_PIPEHANDLER_STATE_USB3)\n' + '\t\t\tatcphy->t8103_usb3_retry = false;', + '(void)0;'), + 'outer-noop-ignores-new-obligations': ('bool atcphy_mux_in_mode', + 'atcphy->t8103_dummy_pending || atcphy->t8103_usb3_retry', + 'false')} + + +def run(code, cc, directory, name): + cfile = directory / (name + ".c") + binary = directory / name + cfile.write_text(code) + build = subprocess.run([cc, "-std=gnu11", "-O1", "-g", "-fsanitize=address,undefined", + "-fno-omit-frame-pointer", "-Wall", "-Wextra", + "-Wno-unused-parameter", "-Wno-unused-function", + str(cfile), "-o", str(binary)], text=True, capture_output=True) + if build.returncode: + raise RuntimeError("compile failed for " + name + ":\n" + build.stderr) + env = dict(os.environ, ASAN_OPTIONS="detect_leaks=1:abort_on_error=1") + return subprocess.run([str(binary)], text=True, capture_output=True, env=env) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, + default=Path(__file__).resolve().parents[2] / "drivers/phy/apple/atc.c") + parser.add_argument("--cc", default="clang") + parser.add_argument("--mutations", action="store_true") + parser.add_argument("--out", type=Path, help="retain generated C, binaries and receipt") + args = parser.parse_args() + code = harness(args.source.read_text()) + results = {} + context = tempfile.TemporaryDirectory(prefix="atc-usb3-tests-") if args.out is None else None + directory = Path(context.name) if context else args.out + directory.mkdir(parents=True, exist_ok=True) + result = run(code, args.cc, directory, "actual") + (directory / "actual.stdout").write_text(result.stdout) + (directory / "actual.stderr").write_text(result.stderr) + if result.returncode: + raise SystemExit(result.stderr or result.stdout) + print(result.stdout, end="") + if args.mutations: + for name, mutation in MUTATIONS.items(): + function, before, after = mutation + declaration = function if " " in function else "int " + function + old_scope = block(code, "static " + declaration + "(") + if old_scope.count(before) != 1: + raise RuntimeError(name + ": expected one mutation site") + changed = old_scope.replace(before, after, 1) + mutated = code.replace(old_scope, changed, 1) + result = run(mutated, args.cc, directory, name) + (directory / (name+".stdout")).write_text(result.stdout) + (directory / (name+".stderr")).write_text(result.stderr) + if result.returncode == 0: + raise RuntimeError("mutation survived: " + name) + if "Assertion" not in result.stderr and "runtime error:" not in result.stderr: + raise RuntimeError("mutant failed without an assertion or sanitizer diagnostic: " + name) + results[name] = {"class": "KILLED", "returncode": result.returncode} + print(json.dumps({"mutations": results}, sort_keys=True)) + after = run(code, args.cc, directory, "restored-control") + (directory/"restored-control.stdout").write_text(after.stdout) + (directory/"restored-control.stderr").write_text(after.stderr) + if after.returncode: + raise RuntimeError("post-mutation control failed: " + after.stderr) + receipt = {"source_sha256": hashlib.sha256(args.source.read_bytes()).hexdigest(), + "harness_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "generated_sha256": hashlib.sha256(code.encode()).hexdigest(), + "generation_scope": generation_scope(args.source.read_text(),Path(__file__).resolve().parents[2]), + "control_stdout": (directory/"actual.stdout").read_text(), + "after_control_stdout": after.stdout, + "mutations": results, + "scope": "actual extracted driver bodies; MMIO, polling, BIST, lane configuration and power restoration boundary models"} + (directory/"receipt.json").write_text(json.dumps(receipt, indent=2)+"\n") + if context: context.cleanup() + + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/avd-codec-tail-tests.py b/tools/asahi/avd-codec-tail-tests.py new file mode 100755 index 00000000000000..31616efc2651c4 --- /dev/null +++ b/tools/asahi/avd-codec-tail-tests.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Exercise the actual AVD capability-tail block under ASan/UBSan. + +Firmware loading, MMIO and device logging are not exercised. The firmware and +variant structures, kernel BIT helper and bounded strnstr are host stand-ins. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +SOURCE = "drivers/media/platform/apple/avd/avd-drv.c" +HEADER = "drivers/media/platform/apple/avd/avd.h" + + +def read(path, ref): + if ref: + return subprocess.check_output( + ["git", "-C", str(ROOT), "show", f"{ref}:{path}"], text=True + ) + return (ROOT / path).read_text() + + +def build_source(body, defines): + return r''' +#include +#include +#include +#define BIT(n) (1u << (n)) +#define dev_info(...) ((void)0) +''' + defines + r''' +struct firmware { const unsigned char *data; size_t size; }; +struct variant { unsigned int capabilities; }; +struct avd_dev { + struct firmware *fw; + const struct variant *variant; + unsigned int capabilities; +}; +static char *strnstr(const char *s, const char *needle, size_t n) +{ + size_t len = strlen(needle); + for (size_t i = 0; i + len <= n && s[i]; i++) + if (!memcmp(s + i, needle, len)) + return (char *)s + i; + return NULL; +} +static unsigned int probe_tail(struct avd_dev *avd) +{ + const char *codec_info = NULL; +''' + body + r''' + return avd->capabilities; +} +int main(int argc, char **argv) +{ + if (argc != 5) + return 2; + size_t size = strtoul(argv[1], NULL, 0); + unsigned char *data = calloc(size ? size : 1, 1); + if (!data) + return 2; + struct firmware fw = {data, size}; + struct variant variant = {strtoul(argv[3], NULL, 0)}; + struct avd_dev avd = {&fw, &variant, 0}; + size_t len = strlen(argv[2]); + if (size >= AVD_CODEC_INFO_MAX_SIZE && len <= AVD_CODEC_INFO_MAX_SIZE) + memcpy(data + size - AVD_CODEC_INFO_MAX_SIZE, argv[2], len); + unsigned int actual = probe_tail(&avd); + unsigned int expected = strtoul(argv[4], NULL, 0); + printf("size=%zu variant=%u capabilities=%u expected=%u\n", + size, variant.capabilities, actual, expected); + free(data); + return actual == expected ? 0 : 1; +} +''' + + +def run_variant(out, name, body, defines, cases): + dest = out / name + dest.mkdir() + source = dest / "actual-tail.c" + source.write_text(build_source(body, defines)) + cmd = shlex.split(os.environ.get("CC", "cc")) + [ + # Match scripts/Makefile.warn for the existing firmware u8*/char* use. + "-std=gnu11", "-g", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-pointer-sign", + "-fsanitize=address,undefined", "-fno-omit-frame-pointer", + str(source), "-o", str(dest / "actual-tail"), + ] + build = subprocess.run(cmd, capture_output=True, text=True) + (dest / "build.log").write_text(build.stdout + build.stderr) + rows = [] + if build.returncode == 0: + for index, (size, tail, mask, expected) in enumerate(cases): + result = subprocess.run( + [str(dest / "actual-tail"), str(size), tail, str(mask), str(expected)], + capture_output=True, text=True, + ) + (dest / f"case-{index:02d}.log").write_text(result.stdout + result.stderr) + rows.append({"size": size, "tail": tail, "variant": mask, + "expected": expected, "returncode": result.returncode, + "sanitizer_diagnostic": bool(re.search( + r"AddressSanitizer|runtime error:", result.stderr))}) + return {"name": name, "build_command": cmd, + "build_returncode": build.returncode, "cases": rows, + "failed_cases": sum(x["returncode"] != 0 or x["sanitizer_diagnostic"] + for x in rows)} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--ref", help="extract production code from this Git ref") + parser.add_argument("--output", type=Path, required=True, + help="new evidence directory (must not already exist)") + parser.add_argument("--mutations", action="store_true") + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + source, header = read(SOURCE, args.ref), read(HEADER, args.ref) + start = source.index("\t/* Determine firmware and HW variant capabilities */") + end = source.index("\n\tret = dma_set_mask_and_coherent", start) + body = source[start:end] + wanted = ["AVD_CODEC_INFO_MAX_SIZE", "AVD_CAPABILITY_AV1", "AVD_CAPABILITY_H264", + "AVD_CAPABILITY_HEVC", "AVD_CAPABILITY_VP9"] + defines = "" + for macro in wanted: + matches = re.findall(r"^#define\s+" + macro + r"\s+[^\n]+$", + source + "\n" + header, re.M) + if len(matches) != 1: + raise ValueError(f"expected exactly one definition of {macro}") + defines += matches[0] + "\n" + # Codec bits are read from the header above; the expected masks below track + # the current public ABI (HEVC/H264/VP9/AV1 = bits 0/1/2/3). + all_codecs = "CODECS:av1 h264 h265 vp9" + cases = [(n, "legacy firmware", 15, 15) for n in (0, 1, 7, 63, 64, 128)] + cases += [(n, all_codecs, 15, 15) for n in (64, 128)] + cases += [(64, "CODECS:" + codec, 15, bit) + for codec, bit in (("av1", 8), ("h264", 2), ("h265", 1), ("vp9", 4))] + cases += [(128, all_codecs, 3, 3), (128, all_codecs, 0, 0), + (64, "CODECS:vvc", 15, 0), (64, "CODECS:", 15, 0), + (64, "CODECS:" + "x" * 57, 15, 0), + (64, "CODECSx:av1", 5, 5), (128, "legacy", 0, 0), + (128, "legacy", 5, 5)] + variants = [("control-before", body)] + if args.mutations: + anchor = "\tif (avd->fw->size >= AVD_CODEC_INFO_MAX_SIZE)\n" + if body.count(anchor) != 1: + raise ValueError("size-guard mutation did not match exactly once") + variants += [("no-size-guard", body.replace(anchor, "")), + ("no-variant-intersection", body.replace( + "\t\tunsigned int variant_caps = avd->variant->capabilities;\n", "" + ).replace("caps |= variant_caps & ", "caps |= ")), + ("no-legacy-fallback", body.replace( + "avd->capabilities = avd->variant->capabilities;", + "avd->capabilities = 0;"))] + variants.append(("control-after", body)) + results = [run_variant(args.output, name, text, defines, cases) + for name, text in variants] + ok = True + for result in results: + is_control = result["name"].startswith("control-") + valid = result["build_returncode"] == 0 and len(result["cases"]) == len(cases) + valid &= (result["failed_cases"] == 0) if is_control else (result["failed_cases"] > 0) + result["verdict"] = ("PASS" if is_control else "KILLED") if valid else "FAIL" + ok &= valid + compiler = subprocess.check_output( + shlex.split(os.environ.get("CC", "cc")) + ["--version"], text=True + ).splitlines()[0] + receipt = {"ref": args.ref, "compiler": compiler, + "source_sha256": hashlib.sha256(source.encode()).hexdigest(), + "body_sha256": hashlib.sha256(body.encode()).hexdigest(), + "defines_sha256": hashlib.sha256(defines.encode()).hexdigest(), + "cases_per_variant": len(cases), "results": results, "passed": ok} + (args.output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps({"passed": ok, "cases": len(cases), + "variants": [{k: x[k] for k in ("name", "failed_cases", "verdict")} + for x in results]})) + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/asahi/dcp14-panel-tests.py b/tools/asahi/dcp14-panel-tests.py index 3d0d98a8875669..0abcd1e89d3f93 100755 --- a/tools/asahi/dcp14-panel-tests.py +++ b/tools/asahi/dcp14-panel-tests.py @@ -114,10 +114,32 @@ height=2234;assert(dcp_v14_geometry(&m)==0&&m.panel_height==2234); height=2160;notch=0;assert(dcp_v14_geometry(&m)==-EINVAL); notch=74;width=3024;stride=width*4;height=1890;assert(dcp_v14_geometry(&m)==-EINVAL); - machine="apple,j514c";assert(IS_ERR(iomfb_v14_7_board(&dev))); + /* J514C is now admitted explicitly; its dimensions come from simplefb. */ + machine="apple,j514c"; + const struct dcp_v14_board *c14=iomfb_v14_7_board(&dev); + assert(!IS_ERR(c14)&&c14==&dcp_v14_board_j514c&&c14!=c); + assert(!strcmp(c14->name,"J514C")&&!strcmp(c14->debugfs,"dcp-j514c")); + assert(!strcmp(c14->firmware_uuid,"F493F03E-CC40-3D89-9A08-5F259BA2B246")); + assert(!strcmp(c14->handoff,"apple,t6031-handoff")&&c14->promotion&&c14->log_bringup); + assert(!c14->panel_width&&!c14->panel_height&&!c14->ctm_set&&!c14->ctm_get); + image_uuid=c14->firmware_uuid;assert(probe_gate(&dev,c14)==0); + image_uuid="90F849E1-B422-367E-B389-50246F8DEC47";assert(probe_gate(&dev,c14)==-ENODEV); + image_uuid=NULL;assert(probe_gate(&dev,c14)==-ENODEV); + image_uuid=c14->firmware_uuid;marker_value=0;assert(probe_gate(&dev,c14)==-ENODEV); + marker_value=2;assert(probe_gate(&dev,c14)==-ENODEV);marker_value=1; + struct apple_dcp_v14 m14={.dev=&dev,.board=c14}; + width=3024;height=1890;stride=width*4;notch=74; + assert(dcp_v14_geometry(&m14)==0&&m14.panel_width==3024&&m14.panel_height==1964); + assert(m14.notch_rows==74); + stride++;assert(dcp_v14_geometry(&m14)==-EINVAL);stride--; + notch=MAX_NOTCH_HEIGHT+1;assert(dcp_v14_geometry(&m14)==-EINVAL);notch=74; + width=0;stride=0;assert(dcp_v14_geometry(&m14)==-EINVAL); + dcp.compatible="apple,t8122-dcp";assert(IS_ERR(iomfb_v14_7_board(&dev))); + dcp.compatible="apple,t6031-dcp";machine="apple,j514s";assert(IS_ERR(iomfb_v14_7_board(&dev))); + machine="apple,j613";assert(IS_ERR(iomfb_v14_7_board(&dev))); machine="apple,j516m";assert(IS_ERR(iomfb_v14_7_board(&dev))); dcp.compatible="apple,t6030-dcp";machine="apple,j516s";assert(iomfb_v14_7_board(&dev)==&dcp_v14_board_t6030); - puts("current J615/J613/T6030/J516C admission + hidden/full notch, wrong geometry controls: PASS"); + puts("current J615/J613/T6030/J516C/J514C admission + hidden/full notch, wrong geometry controls: PASS"); #endif } ''' diff --git a/tools/asahi/g15-input-error-tests.py b/tools/asahi/g15-input-error-tests.py new file mode 100644 index 00000000000000..47971fccfa7106 --- /dev/null +++ b/tools/asahi/g15-input-error-tests.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Actual G15 job dependency completion and G17 status/policy bodies on host services. + +DMA fence lookup, engine submission, queue-fence ordering and kernel mutexes are +models. No kernel scheduling, GPU access or firmware execution is exercised. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[2] + + +def extract(text, marker): + start = text.index(marker) + opening = text.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return text[start:end] + + +PRELUDE = r''' +#![allow(dead_code)] +use std::sync::{Arc,Mutex as StdMutex,MutexGuard,atomic::{AtomicBool,AtomicI32,AtomicU32,Ordering}}; +#[derive(Copy,Clone,Debug,PartialEq,Eq)] struct Error(i32); +impl Error { fn from_errno(n:i32)->Self {assert!(n<0);Self(n)} fn to_errno(self)->i32{self.0} } +type Result = std::result::Result; +const EIO:Error=Error(-5);const ENODEV:Error=Error(-19);const ETIMEDOUT:Error=Error(-110); +const ECANCELED:Error=Error(-125);const EINVAL:Error=Error(-22);const ENOMEM:Error=Error(-12); +macro_rules! pr_warn { ($($arg:tt)*)=>{{ let _=format_args!($($arg)*); }} } +struct Mutex(StdMutex);impl Mutex{fn lock(&self)->MutexGuard<'_,T>{self.0.lock().unwrap()}} +struct Mirror{word:*mut i32} +struct VmStatus{error:AtomicI32,reported_error:AtomicI32,mirror:Mutex>} +impl VmStatus { + fn new(word:*mut i32)->Self{Self{error:AtomicI32::new(0),reported_error:AtomicI32::new(0),mirror:Mutex(StdMutex::new(Some(Mirror{word})))}} +__STATUS__ +} +mod g17 {use super::*;__POLICY__} +mod bindings {pub unsafe fn dma_fence_get_status(p:*const i32)->i32{unsafe{*p}}} +struct Fence(i32);impl Fence{fn raw(&self)->*const i32{&self.0}} +struct Vm{status:VmStatus} +struct Progress{signaled:AtomicBool} +struct Guard{quarantines:AtomicU32}impl Guard{fn quarantine(&self){self.quarantines.fetch_add(1,Ordering::SeqCst);}} +struct JobFence{vm:Arc,signals:AtomicU32,result:AtomicI32,saw_sticky:AtomicI32,saw_report:AtomicI32,saw_mirror:AtomicI32} +impl JobFence{ + fn signal(&self,result:Result){ + self.saw_sticky.store(self.vm.status.get(),Ordering::SeqCst); + self.saw_report.store(self.vm.status.reported_error(),Ordering::SeqCst); + let mirror=self.vm.status.mirror.lock(); + self.saw_mirror.store(unsafe{AtomicI32::from_ptr(mirror.as_ref().unwrap().word)}.load(Ordering::SeqCst),Ordering::SeqCst); + self.result.store(result.err().map_or(0,|e|e.to_errno()),Ordering::SeqCst); + self.signals.fetch_add(1,Ordering::SeqCst); + } +} +struct Shared{crashed:AtomicBool,submits:AtomicU32,submit_result:Result} +impl Shared{fn submit(&self,_:Arc)->Result{self.submits.fetch_add(1,Ordering::SeqCst);self.submit_result}} +struct Job{started:AtomicBool,vm:Arc,progress:Progress,_guard:Guard,fence:JobFence} +impl Job {__JOB__} +fn make_job(own:Option)->(Arc,Box){ + let mut mirror=Box::new(AtomicI32::new(0));let vm=Arc::new(Vm{status:VmStatus::new((&mut *mirror as *mut AtomicI32).cast())}); + if let Some(error)=own{vm.status.record(error);} + let job=Arc::new(Job{started:AtomicBool::new(false),vm:vm.clone(),progress:Progress{signaled:AtomicBool::new(false)},_guard:Guard{quarantines:AtomicU32::new(0)},fence:JobFence{vm,signals:AtomicU32::new(0),result:AtomicI32::new(0),saw_sticky:AtomicI32::new(0),saw_report:AtomicI32::new(0),saw_mirror:AtomicI32::new(0)}}); + (job,mirror) +} +fn shared(crashed:bool,result:Result)->Arc{Arc::new(Shared{crashed:AtomicBool::new(crashed),submits:AtomicU32::new(0),submit_result:result})} +fn n(n:&AtomicI32)->i32{n.load(Ordering::SeqCst)} +fn main(){ + let (unrelated,other_mirror)=make_job(None); + for input in [ECANCELED,EIO,ENODEV,ETIMEDOUT,EINVAL,ENOMEM]{ + let (job,mirror)=make_job(None);let device=shared(false,Ok(())); + job.start(&device,&[Fence(1),Fence(input.to_errno()),Fence(-1)]); + let expected=g17::inherited_error(input).to_errno(); + assert_eq!(device.submits.load(Ordering::SeqCst),0,"errored input must never submit"); + assert_eq!(job.fence.signals.load(Ordering::SeqCst),1,"dependency completion must signal once"); + assert_eq!(n(&job.fence.result),expected,"inherited error mapping"); + assert_eq!(n(&job.fence.saw_report),expected,"report must precede fence signal"); + assert_eq!(n(&job.fence.saw_mirror),expected,"mirror must precede fence signal"); + assert_eq!(n(&job.fence.saw_sticky),0,"healthy dependency consumer admission stays open"); + assert_eq!(job.vm.status.get(),0,"healthy dependency consumer admission stays open"); + assert_eq!(mirror.load(Ordering::SeqCst),expected); + assert_eq!(job._guard.quarantines.load(Ordering::SeqCst),0,"unpublished job must not quarantine"); + job.finish_dependency(EIO);job.complete(Err(EIO)); + assert_eq!(job.fence.signals.load(Ordering::SeqCst),1,"dependency completion must signal once"); + assert_eq!(job.vm.status.get(),0,"duplicate completion must not poison VM"); + // A later job on the same VM is admitted despite the reported client error. + let later=Arc::new(Job{started:AtomicBool::new(false),vm:job.vm.clone(),progress:Progress{signaled:AtomicBool::new(false)},_guard:Guard{quarantines:AtomicU32::new(0)},fence:JobFence{vm:job.vm.clone(),signals:AtomicU32::new(0),result:AtomicI32::new(0),saw_sticky:AtomicI32::new(0),saw_report:AtomicI32::new(0),saw_mirror:AtomicI32::new(0)}}); + later.start(&device,&[Fence(1)]);assert_eq!(device.submits.load(Ordering::SeqCst),1,"successful dependencies after report must submit"); + } + for own in [EIO,EINVAL]{for input in [ECANCELED,EIO,ENODEV,ETIMEDOUT,EINVAL]{ + let(job,_mirror)=make_job(Some(own));let device=shared(false,Ok(()));job.start(&device,&[Fence(input.to_errno())]); + assert_eq!(device.submits.load(Ordering::SeqCst),0);assert_eq!(n(&job.fence.result),input.to_errno(),"own-failed VM must retain original dependency errno"); + assert_eq!(job.vm.status.get(),own.to_errno(),"own-failed VM sticky error must remain"); + assert_eq!(n(&job.fence.saw_report),own.to_errno());assert_eq!(n(&job.fence.saw_mirror),own.to_errno()); + assert_eq!(job._guard.quarantines.load(Ordering::SeqCst),0); + }} + for inputs in [vec![],vec![Fence(1)],vec![Fence(1),Fence(1)]]{ + let(job,_mirror)=make_job(None);let device=shared(false,Ok(()));job.start(&device,&inputs); + assert_eq!(device.submits.load(Ordering::SeqCst),1,"successful dependencies must submit");assert_eq!(job.fence.signals.load(Ordering::SeqCst),0);assert_eq!(job.vm.status.get(),0); + } + // Preserve device-crash and submit-refusal sticky semantics. + for (crashed,result) in [(true,Ok(())),(false,Err(ENODEV)),(false,Err(EINVAL))]{ + let(job,_mirror)=make_job(None);let device=shared(crashed,result);job.start(&device,&[Fence(1)]); + let expected=if crashed||result==Err(ENODEV){EIO}else{EINVAL};assert_eq!(job.vm.status.get(),expected.to_errno());assert_eq!(n(&job.fence.saw_mirror),expected.to_errno()); + } + // An engine-owned fault still quarantines before completion. + let(job,_mirror)=make_job(None);job.complete(Err(EIO));assert_eq!(job._guard.quarantines.load(Ordering::SeqCst),1);assert_eq!(job.vm.status.get(),EIO.to_errno()); + assert_eq!(unrelated.vm.status.get(),0,"unrelated VM untouched");assert_eq!(unrelated.vm.status.reported_error(),0);assert_eq!(other_mirror.load(Ordering::SeqCst),0);assert_eq!(unrelated.fence.signals.load(Ordering::SeqCst),0); + println!("PASS: actual Job::start/completion and VmStatus/policy: healthy/failed VMs, mirror ordering, one-shot completion, successful input, device faults and isolation"); +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mutations", action="store_true") + parser.add_argument("--ref", help="Read job.rs at a public git revision for a removed-fix control") + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=True) + job_path = "drivers/gpu/drm/asahi/g15/job.rs" + job = (subprocess.check_output(["git", "show", args.ref + ":" + job_path], cwd=ROOT, text=True) + if args.ref else (ROOT / job_path).read_text()) + current = (ROOT / job_path).read_text() + status = (ROOT / "drivers/gpu/drm/asahi/g17/status.rs").read_text() + policy = (ROOT / "drivers/gpu/drm/asahi/g17/dependency.rs").read_text() + methods = [extract(job, " pub(crate) fn complete("), extract(job, " fn finish("), + extract(job, " fn start(self: &Arc")] + # The old control needs the current helper for the duplicate-completion test; + # it still runs its actual unmodified start, which reproduces the lost input error. + methods.append(extract(job if "fn finish_dependency(" in job else current, " fn finish_dependency(")) + bodies = "\n".join(methods) + code = PRELUDE.replace("__JOB__", bodies).replace("__STATUS__", "\n".join( + extract(status, marker) for marker in [" pub(crate) fn get(", " pub(crate) fn record(", + " pub(crate) fn reported_error(", " pub(crate) fn report_failure("])).replace( + "__POLICY__", extract(policy, "pub(crate) fn inherited_error(")) + variants = {"control": code} + expected = {} + if args.mutations: + changes = { + "healthy-errors-submit": ("if let Some(status) = failed {", "if let Some(status) = failed.filter(|_| self.vm.status.get() != 0) {", "errored input must never submit"), + "foreign-device-error-unmapped": ("crate::g17::inherited_error(error)", "error", "inherited error mapping"), + "dependency-records-sticky": ("self.finish_dependency(crate::g17::inherited_error(error));", "self.finish(Err(crate::g17::inherited_error(error)), false);", "healthy dependency consumer admission stays open"), + "report-after-signal": ("self.vm.status.report_failure(error);\n self.fence.signal(Err(error));", "self.fence.signal(Err(error));\n self.vm.status.report_failure(error);", "report must precede fence signal"), + "dependency-quarantines": (" fn finish_dependency(&self, error: Error) {", " fn finish_dependency(&self, error: Error) {\n self._guard.quarantine();", "unpublished job must not quarantine"), + "own-error-remapped": ("self.finish(Err(error), false);\n } else", "self.finish(Err(crate::g17::inherited_error(error)), false);\n } else", "own-failed VM must retain original dependency errno"), + "success-refused": ("if let Some(status) = failed {", "if let Some(status) = failed.or(Some(-125)) {", "successful dependencies after report must submit"), + "dependency-completes-twice": (" fn finish_dependency(&self, error: Error) {\n if self.progress.signaled.swap(true, Ordering::AcqRel) {\n return;\n }", " fn finish_dependency(&self, error: Error) {", "dependency completion must signal once"), + "mirror-not-published": ("unsafe { AtomicI32::from_ptr(mirror.word) }.store(error, Ordering::SeqCst);", "let _ = mirror;", "mirror must precede fence signal"), + } + for name, (old, new, message) in changes.items(): + if code.count(old) != 1: + raise RuntimeError(f"{name}: unique mutation anchor count {code.count(old)}") + variants[name] = code.replace(old, new) + expected[name] = message + variants["control-after"] = code + receipt = {"scope": __doc__, "ref": args.ref, "sources": {name: hashlib.sha256(text.encode()).hexdigest() + for name, text in [(job_path, job), ("g17/status.rs", status), ("g17/dependency.rs", policy)]}, "variants": {}} + for name, source in variants.items(): + path = args.output / (name + ".rs"); path.write_text(source) + binary = args.output / name + built = subprocess.run([os.environ.get("RUSTC", "rustc"), "--edition=2021", str(path), "-o", str(binary)], capture_output=True, text=True) + (args.output / (name + ".build.log")).write_text(built.stdout + built.stderr) + if built.returncode: + raise RuntimeError(f"{name}: NOBUILD, not a runtime kill: {built.stderr}") + ran = subprocess.run([str(binary.resolve())], capture_output=True, text=True, timeout=30) + receipt["variants"][name] = {"exit": ran.returncode, "stdout": ran.stdout, "stderr": ran.stderr, + "intended_failure": name in expected and expected[name] in ran.stderr} + if name.startswith("control") and not args.ref and ran.returncode: + raise RuntimeError(ran.stdout + ran.stderr) + if name in expected and (ran.returncode == 0 or expected[name] not in ran.stderr): + raise RuntimeError(f"{name}: did not die at intended runtime assertion: {ran.stderr}") + (args.output / "result.json").write_text(json.dumps(receipt, indent=2) + "\n") + if args.ref: + for name in ["control", "control-after"]: + result = receipt["variants"][name] + if result["exit"] == 0 or "errored input must never submit" not in result["stderr"]: + raise RuntimeError("removed-fix control did not reproduce the intended lost-input failure") + print(json.dumps(receipt, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/g15-maintained-handoff-tests.py b/tools/asahi/g15-maintained-handoff-tests.py new file mode 100644 index 00000000000000..4dd2961d3a8ace --- /dev/null +++ b/tools/asahi/g15-maintained-handoff-tests.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Actual native G15 ADT parser/admission and RTKit constructor on public synthetic inputs. + +Uses the production ADT byte parser, performance parser, region admission, +T6030 firmware rows and RTKit constructor. Resource/owner lookup and RTKit init +are models. It does not read firmware, a device or private machine data. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +G15 = ROOT / 'drivers/gpu/drm/asahi/g15' + + +def item(s, marker): + a = s.index(marker); i = s.index('{', a) + 1; depth = 1 + while depth: + depth += (s[i] == '{') - (s[i] == '}'); i += 1 + return s[a:i] + + +PREFIX = r''' +#![allow(dead_code, unused_variables)] +use std::{cell::Cell, ffi::{c_void, CStr}, ops::Range, sync::Arc}; +type Result = std::result::Result; +const EINVAL: i32 = -22; +macro_rules! dev_err { ($($x:tt)*) => {{}}; } +#[macro_export] macro_rules! c_str { ($s:literal) => { match CStr::from_bytes_with_nul(concat!($s, "\0").as_bytes()) { Ok(s) => s, Err(_) => panic!("bad C string") } }; } +extern crate self as kernel; +pub mod str { pub use std::ffi::CStr; } +mod device { pub struct Device; impl Device { pub fn as_raw(&self) -> *mut c_void { 1usize as *mut c_void } } use std::ffi::c_void; } +const PERF_STATES: usize = 14; +const CLUSTERS: usize = 4; +const REGION_NAMES: [&str; 6] = ["ttbs", "tables", "handoff", "shared-l2", "text", "data"]; +const BASE: [u64; 6] = [0x100000000, 0x100100000, 0x100200000, 0x100300000, 0x200000000, 0x20005c000]; +const SIZES: [u64; 6] = [0x4000, 0x40000, 0x4000, 0x4000, 0x5c000, 0x114000]; +thread_local! { + static OWNERS: Cell = const { Cell::new(15) }; + static OWNER_CALLS: Cell = const { Cell::new(0) }; + static RAM_OK: Cell = const { Cell::new(true) }; + static TEXT_RAM: Cell = const { Cell::new(false) }; + static INIT_ERROR: Cell = const { Cell::new(0) }; + static COOKIE: Cell<*const Shared> = const { Cell::new(core::ptr::null()) }; +} +mod glue { + use super::*; + pub fn reserved_uat(index: u32, start: u64, size: u64) -> bool { + OWNER_CALLS.set(OWNER_CALLS.get() + 1); + index < 4 && BASE[index as usize] == start && SIZES[index as usize] == size + && OWNERS.get() & (1 << index) != 0 + } + pub fn ram_disjoint(start: u64, _size: u64) -> bool { + start >= BASE[4] && !TEXT_RAM.get() + } + pub fn ram_within(start: u64, _size: u64) -> bool { start < BASE[4] && RAM_OK.get() } +} +#[derive(Clone)] +struct Node { name: &'static str, props: Vec<(&'static str, Vec)>, kids: Vec } +impl Node { + fn encode(&self) -> Vec { + let mut out = Vec::new(); + let mut props = self.props.clone(); + props.push(("name", [self.name.as_bytes(), &[0]].concat())); + out.extend_from_slice(&(props.len() as u32).to_le_bytes()); + out.extend_from_slice(&(self.kids.len() as u32).to_le_bytes()); + for (name, data) in props { + let mut n = [0u8; 32]; n[..name.len()].copy_from_slice(name.as_bytes()); + out.extend_from_slice(&n); out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out.extend_from_slice(&data); while out.len() % 4 != 0 { out.push(0); } + } + for child in &self.kids { out.extend_from_slice(&child.encode()); } + out + } +} +fn fixture(kind: u8) -> Vec { + let mut sgx = Node { name: "sgx", props: vec![("compatible", b"gpu,t6030\0".to_vec())], kids: vec![] }; + for (i, (b, s)) in [("gpu-region-base", "gpu-region-size"), ("gfx-shared-region-base", "gfx-shared-region-size"), ("gfx-handoff-base", "gfx-handoff-size"), ("gfx-shared-l2-region-base", "gfx-shared-l2-region-size")].iter().enumerate() { + sgx.props.push((b, BASE[i].to_le_bytes().to_vec())); sgx.props.push((s, SIZES[i].to_le_bytes().to_vec())); + } + for (name, value) in [("perf-state-count", 14u32), ("gpu-num-perf-states", 13), ("perf-state-table-count", 1), ("gpu-power-sample-period", 8), ("gpu-pwr-sample-period-aic-clks", 200000)] { sgx.props.push((name, value.to_le_bytes().to_vec())); } + for (name, mv) in [("perf-states", 600u32), ("perf-states-sram", 700)] { + let mut table = vec![]; + for i in 0..14u32 { table.extend_from_slice(&(i * 100000000).to_le_bytes()); table.extend_from_slice(&mv.to_le_bytes()); } + sgx.props.push((name, table)); + } + let mut segments = vec![]; + for i in 0..2 { + segments.extend_from_slice(&BASE[4+i].to_le_bytes()); + segments.extend_from_slice(&(hw::UPPER + if i == 0 { 0 } else { SIZES[4] } + if kind == 3 { 0x4000 } else { 0 }).to_le_bytes()); + segments.extend_from_slice(&BASE[4+i].to_le_bytes()); + segments.extend_from_slice(&(SIZES[4+i] as u32).to_le_bytes()); + segments.extend_from_slice(&(if i == 0 { 1u32 } else { 0 }).to_le_bytes()); + } + let mut nub_segments = segments.clone(); if kind == 2 { nub_segments[0] ^= 1; } + let nub = Node { name: "iop-gfx-nub", props: vec![("segment-ranges", nub_segments), ("pre-loaded", (if kind == 1 { 0u32 } else { 1 }).to_le_bytes().to_vec())], kids: vec![] }; + let asc = Node { name: "gfx-asc", props: vec![("segment-ranges", segments), ("segment-names", b"__TEXT;__DATA\0".to_vec())], kids: vec![nub] }; + let chosen = Node { name: "chosen", props: vec![("dram-base", (if kind == 4 { u64::MAX } else { 0x100000000u64 }).to_le_bytes().to_vec()), ("dram-size", 0x200000000u64.to_le_bytes().to_vec())], kids: vec![] }; + Node { name: "root", props: vec![], kids: vec![Node { name: "arm-io", props: vec![], kids: vec![sgx, asc] }, chosen] }.encode() +} +struct Shared; +struct Rtkit { rtk: *mut c_void } +static RTKIT_OPS: u8 = 0; +fn from_err_ptr(p: *mut c_void) -> Result<*mut c_void> { if (p as isize) < 0 { Err(p as isize as i32) } else { Ok(p) } } +mod bindings { + use super::*; + pub unsafe fn apple_rtkit_init(_dev: *mut c_void, cookie: *mut c_void, name: *const core::ffi::c_char, index: u32, _ops: *const u8) -> *mut c_void { + assert!(name.is_null(), "maintained DT mailbox must be selected by index"); + assert_eq!(index, 0); + COOKIE.set(cookie.cast()); + let e = INIT_ERROR.get(); if e == 0 { 1usize as *mut c_void } else { e as isize as *mut c_void } + } +} +''' + +CASES = r''' +fn main() { + let bytes = fixture(0); let adt = Adt { data: &bytes }; let dev = device::Device; + OWNERS.set(15); OWNER_CALLS.set(0); RAM_OK.set(true); TEXT_RAM.set(false); + let parsed = parse(&dev, &adt).expect("maintained reserved-RAM ADT admission"); + assert_eq!(OWNER_CALLS.get(), 4, "all four owner reservations must be checked"); assert_eq!(parsed.ttbs, BASE[0]..BASE[0]+SIZES[0]); + assert_eq!(parsed.perf_mhz[13], 1300); assert_eq!(parsed.cluster_mv[13][0], 600); + for missing in 0..4 { + OWNERS.set(15 & !(1 << missing)); OWNER_CALLS.set(0); + assert!(parse(&dev, &adt).is_err(), "every maintained UAT owner is mandatory"); + assert_eq!(OWNER_CALLS.get(), missing + 1); + } + OWNERS.set(15); RAM_OK.set(false); assert!(parse(&dev, &adt).is_err()); RAM_OK.set(true); + TEXT_RAM.set(true); assert!(parse(&dev, &adt).is_err()); TEXT_RAM.set(false); + for kind in 1..=4 { + OWNER_CALLS.set(0); let bytes = fixture(kind); + assert!(parse(&dev, &Adt { data: &bytes }).is_err()); assert_eq!(OWNER_CALLS.get(), 0); + } + assert_eq!(BUILDS.len(), 2, "maintained B0 firmware row must not require an absent profile symbol"); + assert_eq!(BUILDS[1].machine.unwrap().to_bytes(), b"apple,j516s"); + assert_eq!((BUILDS[1].text_size, BUILDS[1].data_size, BUILDS[1].marker), (0x5c000, 0x114000, 0x58e88)); + assert_eq!(BUILDS[1].text_sha256, [0xda,0x26,0xec,0xca,0xb1,0xf8,0x59,0x8d,0xa8,0x0c,0x85,0x5e,0xca,0x91,0x65,0x20,0x40,0x6d,0x1d,0x06,0x70,0xf1,0xd4,0x70,0xe7,0x9b,0xb9,0xb0,0x22,0x09,0xdb,0x53]); + for error in [0, -517, -12] { + INIT_ERROR.set(error); let shared = Arc::new(Shared); let result = Rtkit::new(&dev, &shared); + assert_eq!(result.is_ok(), error == 0); + assert_eq!(Arc::strong_count(&shared), if error == 0 { 2 } else { 1 }); + if error == 0 { unsafe { drop(Arc::from_raw(COOKIE.get())); } } + } + println!("PASS actual ADT/owner/performance parser, B0 identity row, unnamed RTKit mailbox and cookie lifetime"); +} +''' + + +def main(): + p = argparse.ArgumentParser(description=__doc__); p.add_argument('--output', type=Path); p.add_argument('--mutations', action='store_true'); a=p.parse_args() + out=(a.output or Path(tempfile.mkdtemp(prefix='g15-maintained-handoff-'))).resolve(); out.mkdir(parents=True, exist_ok=True) + adt=(G15/'adt.rs').read_text(); boot=(G15/'boot.rs').read_text(); hw=(G15/'hw.rs').read_text() + helpers='\n'.join(item(adt,m) for m in ["pub(crate) struct GpuAdt", "struct Adt<'a>", 'fn le32(', 'fn le64(', 'fn strncmp_eq(', "impl Adt<'_>", 'fn collect_perf(', 'fn parse(', 'fn admit_regions(']) + constants='\n'.join(re.search(r'pub\(crate\) const '+n+r':[^;]+;', hw).group(0) for n in ['PAGE','PA_MASK','TTBS_SIZE','TABLES_SIZE','HANDOFF_SIZE','SHARED_L2_SIZE','UPPER']) + start=hw.index(' firmware: &['); start=hw.index('[',start); end=start+1; depth=1 + while depth: depth+=(hw[end]=='[')-(hw[end]==']'); end+=1 + firmware='static BUILDS: &[FirmwareBuild] = &'+hw[start:end]+';\n'+item(hw,'pub(crate) struct FirmwareBuild') + constructor=item(boot,' fn new(dev: &device::Device, shared: &Arc)') + source=PREFIX+'\nmod hw {\n'+constants+'\n}\n'+helpers+'\n'+firmware+'\nimpl Rtkit {\n'+constructor+'\n}\n'+CASES + variants={'actual':source} + if a.mutations: + variants['skip-owner-check']=source.replace('if !glue::reserved_uat(i as u32, r.start, r.end - r.start) {','if false {') + variants['skip-fourth-owner']=source.replace('region[..4].iter().enumerate()', 'region[..3].iter().enumerate()') + variants['drop-reserved-ram']=source.replace('Some(dram_base..dram_base + dram_size), true)?;', 'Some(dram_base..dram_base + dram_size), false)?;') + variants['require-obsolete-b0-profile']=source.replace(' FirmwareBuild {\n name: "J516S B0', ' #[cfg(CONFIG_SILICONFOREST_NATIVE_GPU)]\n FirmwareBuild {\n name: "J516S B0') + variants['named-mailbox']=source.replace('cookie, core::ptr::null(), 0, &RTKIT_OPS', 'cookie, c"mbox".as_ptr(), 0, &RTKIT_OPS') + receipt={'scope':__doc__,'sources':{p:hashlib.sha256(t.encode()).hexdigest() for p,t in [('adt.rs',adt),('boot.rs',boot),('hw.rs',hw)]},'variants':{}} + for name,text in variants.items(): + if name!='actual' and text==source: raise SystemExit('NOT_APPLIED '+name) + src=out/(name+'.rs');src.write_text(text); binary=out/name + subprocess.run([os.environ.get('HOSTRUSTC','rustc'),'--edition=2021',str(src),'-o',str(binary)],check=True) + r=subprocess.run([str(binary)],capture_output=True,text=True) + receipt['variants'][name]={'exit':r.returncode,'stdout':r.stdout,'stderr':r.stderr} + if name=='actual' and r.returncode: raise SystemExit(r.stderr) + if name!='actual' and not r.returncode: raise SystemExit('SURVIVED '+name) + if name!='actual': + expected={'skip-owner-check':'all four owner reservations must be checked','skip-fourth-owner':'all four owner reservations must be checked','drop-reserved-ram':'maintained reserved-RAM ADT admission','require-obsolete-b0-profile':'maintained B0 firmware row must not require an absent profile symbol','named-mailbox':'maintained DT mailbox must be selected by index'}[name] + receipt['variants'][name]['intended_failure']=expected in r.stderr + if expected not in r.stderr: raise SystemExit('INVALID unrelated failure '+name+'\n'+r.stderr) + (out/'result.json').write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps(receipt,indent=2)) +if __name__=='__main__': main() diff --git a/tools/asahi/g15-pb-growth-tests.py b/tools/asahi/g15-pb-growth-tests.py new file mode 100644 index 00000000000000..7cdedc9f0cc951 --- /dev/null +++ b/tools/asahi/g15-pb-growth-tests.py @@ -0,0 +1,1573 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G15 PB growth answer and its on-demand backing, actual bodies, against a model. + +The harness extracts from drivers/gpu/drm/asahi/g15/pools.rs Firmware::answer_growth(), +answer_request(), map_pb(), running_vm() and back_pb(), Pools::soft_max() and backed(), +PbChunk and Pools::new's PB backing statements; pb_max_blocks() from params.rs; the PB sizes, +tuning and PB leaf word from hw.rs; Prot::from_pte() and is_cached_noncoherent() from +pgtable.rs; and the parameter's default from asahi_core.rs. It includes pools/growth.rs, +fw/buffer.rs and fw/channels.rs whole. The bodies run against a model of the firmware objects, +the GEM backing allocation, the shared layer's map_at() and append_driver_mappings(), and the +DEVCTL wait, which logs every allocation, alias map, append, unmap, free, block record, +barrier, producer store, reply and log line in order. Allocation, alias map and append +failures can be injected. Source checks: publish_prefix_into() starts with the PB catch-up, +and pools.rs asserts the PB leaf GPU-only at compile time. + +What it shows: +- a poll pass answers only the requests queued when it starts, in order; one the reply's wait + queues goes to the next pass. A request that cannot be processed does not end the pass; +- from the driver's initial size to its maximum, every block record is written once at its + offset, each producer store follows its records and a barrier, each reply follows its producer + store and a barrier, and every producer is in 1..=4095, ending at 4095; +- at the maximum two refusals are answered; further requests get no reply, count as bad and + warn once until the ledger is made again, as init() does; +- the soft maximum is the parameter clamped to 64..=4095 and then to the ledger's + initial..=max; growth answers above it are logged at info level, and the one that reaches it + exactly is not; +- invalid requests (type, slot, stale counter, epoch, no live render) get no reply, and requests + rejected so allocate nothing; +- the backing: the initial blocks only when the GPU starts; chunks of at most 4 MiB, allocated + and held by the running VM before any record or producer names their blocks, never past the + maximum, at most growth::max_chunks(); a failed allocation, alias map or append posts and + answers nothing, leaves the request counter and the VM's count alone and drops what is not + held, and the next request is answered; a failed reply keeps everything; +- a VM's count always equals the aliases it holds, contiguous from the heap's start; a VM that + runs after another grew the backing maps it first (at publication, and again before it grows); + a partial catch-up counts only held aliases; +- the one-VM rule: a catch-up with a flight of another VM, or a count past the chunks, and a + grant with flights of two VMs, are refused (EPROTO) before anything is mapped or posted; +- the ledger reset of Pools::init() re-posts from the backing without allocating; +- the PB leaf decodes as GPU-only, not cached-noncoherent: dropping an alias is a plain unmap; +- Ledger::new() is Ledger::new() as of dba2a110de00 (the carried upstream constructor), capped at + 4095, over every growth and fixed input in 0..=4200 and at the u32 extremes. The driver's + values are unchanged. + +Not shown: kernel, firmware or GPU execution, timing, or what the firmware does with a reply, a +refusal or an unanswered request. The model's VMs have no open/closed state: that a closed VM +whose jobs still run keeps its aliases comes from the VM lifetime source (Job and VmJobGuard +hold the VM), not from these tests. The ledger reset is not a recovery. The shared layer's +mapping and its rollback are modelled, not run. Running only running_vm()'s or only map_pb()'s +one-VM check on a grant is not distinguishable: each covers it. + +With --mutations, each mutation below must fail its intended test with the expected message, and +the control (a driver maximum of the whole 4096-block heap) must pass, held by the ledger's cap. +A run that hangs (60 s) counts as no test failed. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import resource +import subprocess + +ROOT = Path(__file__).resolve().parents[2] +G15 = "drivers/gpu/drm/asahi/g15" +POOLS = f"{G15}/pools.rs" +GROWTH = f"{G15}/pools/growth.rs" +BUFFER = f"{G15}/fw/buffer.rs" +CHANNELS = f"{G15}/fw/channels.rs" +INITDATA = f"{G15}/fw/initdata.rs" +PARAMS = f"{G15}/params.rs" +HW = f"{G15}/hw.rs" +CORE = "drivers/gpu/drm/asahi/asahi_core.rs" +ENGINE = f"{G15}/engine.rs" +PGTABLE = "drivers/gpu/drm/asahi/pgtable.rs" +OLD_REF = "dba2a110de00743eeecd41edf23e54ede4491d5e" + +# Ledger::new() at OLD_REF, the tip of the four PR363 carries (upstream 027bd7623f37), verbatim: +# the constructor before the cap below K. +OLD_LEDGER_NEW = ''' pub(crate) const fn new(grow: bool, blocks: u32, max_blocks: u32) -> Self { + let (initial, max) = if grow { + let nb = clamp(blocks, MIN_BLOCKS, MAX_BLOCKS); + (nb, clamp(max_blocks, nb, MAX_BLOCKS)) + } else { + (MAX_BLOCKS, MAX_BLOCKS) + }; + Self { + initial, + max, + posted: initial, + next_request: 0, + refusal_logged: false, + refusals: 0, + } + }''' + +# Pools::new's PB backing, run verbatim by the model. +POOLS_NEW_BACKING = (' // Backing for the initial blocks; growth adds the rest.\n', ' chunks.push(') +# The compile-time proof that a PB alias drop is a plain unmap. +PB_LEAF_ASSERT = 'static_assert!(!mmu::Prot::from_pte(pte::LEAF_CACHED).is_cached_noncoherent());' + +# The two statements of Pools::init() that start a new ledger. +LEDGER_RESET = ['self.ledger = Ledger::new(tuning::PB_GROW, tuning::PB_BLOCKS, tuning::PB_MAX_BLOCKS);', + 'self.exhausted_logged = false;'] + +MUTATIONS = { + # Answer until the queue is empty, including requests queued by the replies' waits. + 'drain-until-empty': (POOLS, 'for _ in 0..queued {', 'while !self.events.grow.is_empty() {'), + # Leave the last request queued before the pass for later. + 'skip-last-queued': (POOLS, 'for _ in 0..queued {', 'for _ in 0..queued.saturating_sub(1) {'), + # End the pass at a request that cannot be processed. + 'return-after-request-error': (POOLS, ' self.pools.stats.bad += 1;\n dev_err!(', + ' self.pools.stats.bad += 1;\n return Ok(());\n' + ' dev_err!('), + # Answer three refusals at the maximum. + 'three-refusals': (GROWTH, 'pub(crate) const MAX_REFUSALS: u32 = 2;', 'pub(crate) const MAX_REFUSALS: u32 = 3;'), + # Answer refusals for ever. + 'never-exhausted': (GROWTH, 'self.refusals >= MAX_REFUSALS', 'false && self.refusals >= MAX_REFUSALS'), + # Warn for every unanswered request. + 'warn-every-time': (POOLS, 'if !self.pools.exhausted_logged {', 'if true {'), + # Store the producer without the barrier after the block records. + 'no-record-barrier': (POOLS, ' // Records before their producer.\n crate::mem::sync();\n', + ' // Records before their producer.\n'), + # Reply without the barrier after the producer store. + 'no-reply-barrier': (POOLS, ' // Producer before the reply.\n crate::mem::sync();\n', + ' // Producer before the reply.\n'), + # Log the answer that reaches the soft maximum exactly. + 'soft-boundary-inclusive': (POOLS, 'let past_soft = n != 0 && ledger.posted > soft;', + 'let past_soft = n != 0 && ledger.posted >= soft;'), + # Give the firmware the parameter without the ledger's bounds. + 'soft-max-unclamped': (POOLS, 'super::params::pb_max_blocks().clamp(self.ledger.initial, self.ledger.max)', + 'super::params::pb_max_blocks()'), + # Ledger::new() without the cap below K. + 'uncapped-ledger': (GROWTH, 'let nb = clamp(blocks, MIN_BLOCKS, MAX_POSTED);\n' + ' (nb, clamp(max_blocks, nb, MAX_POSTED))\n' + ' } else {\n (MAX_POSTED, MAX_POSTED)', + 'let nb = clamp(blocks, MIN_BLOCKS, MAX_BLOCKS);\n' + ' (nb, clamp(max_blocks, nb, MAX_BLOCKS))\n' + ' } else {\n (MAX_BLOCKS, MAX_BLOCKS)'), + # Post blocks without backing them first. + 'grant-without-backing': (POOLS, ' self.back_pb(end, ctx)?;\n let (first, n) = self.pools.ledger.accept(request);', + ' let (first, n) = self.pools.ledger.accept(request);'), + # Back the blocks only after the request is accepted. + 'back-after-accept': (POOLS, ' self.back_pb(end, ctx)?;\n let (first, n) = self.pools.ledger.accept(request);', + ' let (first, n) = self.pools.ledger.accept(request);\n self.back_pb(end, ctx)?;'), + # Count a catch-up alias before the VM holds it. + 'catch-up-cursor-before-append': (POOLS, ' vm.vm.append_driver_mappings(aliases)?;\n mapped += 1;\n' + ' vm.pb_chunks.store(mapped, Ordering::Relaxed);', + ' mapped += 1;\n vm.pb_chunks.store(mapped, Ordering::Relaxed);\n' + ' vm.vm.append_driver_mappings(aliases)?;'), + # Count a growth chunk's alias before the VM holds it. + 'growth-cursor-before-append': (POOLS, ' vm.vm.append_driver_mappings(aliases)?;\n // Within the capacity checked above.', + ' vm.pb_chunks.store(self.pools.chunks.len() + 1, Ordering::Relaxed);\n' + ' vm.vm.append_driver_mappings(aliases)?;\n // Within the capacity checked above.'), + # Keep a chunk whose alias the VM never held. + 'keep-unappended-chunk': (POOLS, ' vm.vm.append_driver_mappings(aliases)?;\n // Within the capacity checked above.\n' + ' self.pools\n .chunks\n .push_within_capacity(chunk)\n' + ' .map_err(|_| EIO)?;', + ' // Within the capacity checked above.\n self.pools\n .chunks\n' + ' .push_within_capacity(chunk)\n .map_err(|_| EIO)?;\n' + ' vm.vm.append_driver_mappings(aliases)?;'), + # Grow without catching the running VM up first. + 'no-growth-catch-up': (POOLS, ' let vm = self.running_vm(ctx)?;\n self.map_pb(&vm)?;\n', + ' let vm = self.running_vm(ctx)?;\n'), + # Catch up without the one-VM check. + 'no-activation-guard': (POOLS, '.any(|f| !core::ptr::eq(&*f.job.vm, vm))', '.any(|_| false)'), + # Neither the catch-up's nor the grant's one-VM check (each alone covers a grant). + 'no-same-vm-checks': [(POOLS, '.any(|f| !core::ptr::eq(&*f.job.vm, vm))', '.any(|_| false)'), + (POOLS, 'if vm.slot != ctx || flights.iter().any(|f| !Arc::ptr_eq(&f.job.vm, &vm)) {', + 'if vm.slot != ctx {')], + # Back the whole heap when the GPU starts. + 'initial-backs-whole-heap': (POOLS, 'chunks.push(PbChunk::new(dev, 0, ledger.initial)?, GFP_KERNEL)?;', + 'chunks.push(PbChunk::new(dev, 0, buffer::MAX_BLOCKS)?, GFP_KERNEL)?;'), + # Growth chunks of 8 MiB. + 'chunks-above-4mib': (GROWTH, 'pub(crate) const CHUNK_BLOCKS: u32 = 32;', 'pub(crate) const CHUNK_BLOCKS: u32 = 64;'), + # A firmware-visible cached PB leaf (its drop would ask the firmware to flush). + 'pb-leaf-fw-visible': (HW, 'pub(crate) const LEAF_CACHED: u64 = 0x00c0000000000c83;', + 'pub(crate) const LEAF_CACHED: u64 = 0x00c0000000000c03;'), +} + +# The test each mutation must fail, and a piece of its failure message. +INTENDED = { + 'drain-until-empty': ('queued_snapshot_keeps_order', 'unbounded answering in one poll pass'), + 'skip-last-queued': ('queued_snapshot_keeps_order', 'replies in the first pass'), + 'return-after-request-error': ('unprocessed_request_does_not_end_the_pass', 'requests taken in the pass'), + 'three-refusals': ('default_growth_to_exhaustion', 'want Some(Log("warn"'), + 'never-exhausted': ('default_growth_to_exhaustion', 'growth did not end'), + 'warn-every-time': ('default_growth_to_exhaustion', 'later request after exhaustion'), + 'no-record-barrier': ('default_growth_to_exhaustion', 'got Some(Producer(1034)), want Some(Sync)'), + 'no-reply-barrier': ('default_growth_to_exhaustion', + 'got Some(Reply([7, 1, 0, 5, 0, 256, 3, 1, 0, 0, 0, 0, 0, 0])), want Some(Sync)'), + 'soft-boundary-inclusive': ('soft_max_boundaries', 'got Some(Log("info", "")), want Some(Log("dbg", ""))'), + 'soft-max-unclamped': ('soft_max_bounds', 'soft_max, param 0'), + 'uncapped-ledger': ('constructor_is_the_old_one_capped', 'new(true, '), + 'grant-without-backing': ('growth_backs_before_posting', 'record of block'), + 'back-after-accept': ('allocation_failure_posts_nothing', 'ledger after a backing failure'), + 'catch-up-cursor-before-append': ('partial_catch_up_counts_only_held_aliases', 'count after a failed append'), + 'growth-cursor-before-append': ('append_failure_posts_nothing', 'count differs from held aliases'), + 'keep-unappended-chunk': ('append_failure_posts_nothing', 'chunks after a backing failure'), + 'no-growth-catch-up': ('growth_catches_the_running_vm_up_first', 'running VM not caught up'), + 'no-activation-guard': ('catch_up_refuses_flights_of_another_vm', 'catch-up with a flight of another VM'), + 'no-same-vm-checks': ('grant_refuses_flights_of_two_vms', 'grant with flights of two VMs'), + 'initial-backs-whole-heap': ('startup_backs_the_initial_blocks', 'startup allocation'), + 'chunks-above-4mib': ('growth_backs_before_posting', 'a growth chunk above 4 MiB'), + 'pb-leaf-fw-visible': ('pb_leaf_is_gpu_only', 'PB leaf not GPU-only'), +} +assert set(INTENDED) == set(MUTATIONS) + +# Changes that must pass: the ledger's cap holds a driver maximum of the whole heap. +CONTROLS = { + 'tuning-whole-heap': (HW, 'pub(crate) const PB_MAX_BLOCKS: u32 = super::sizes::PB_BLOCKS - 1;', + 'pub(crate) const PB_MAX_BLOCKS: u32 = super::sizes::PB_BLOCKS;'), +} + + +def item(text, start): + a = text.index(start) + b = text.index("{", a) + 1 + depth = 1 + while depth: + depth += (text[b] == "{") - (text[b] == "}") + b += 1 + return text[a:b] + + +def consts(text, names): + out = [] + for name in names: + m = re.search(rf'pub\(crate\) const {name}: (\w+) = ([^;]+);', text) + if not m: + raise SystemExit(f'{name} not found') + out.append(f'pub const {name}: {m.group(1)} = {m.group(2)};') + return '\n'.join(out) + + +PREFIX = r''' +#![allow(dead_code, unused_imports, unused_macros, unused_variables, unreachable_code, non_upper_case_globals)] +extern crate self as kernel; +use std::cell::{Cell, RefCell}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(i32); +impl Error { + pub fn to_errno(&self) -> i32 { + self.0 + } +} +pub type Result = core::result::Result; +pub const EINVAL: Error = Error(-22); +pub const ENODEV: Error = Error(-19); +pub const EIO: Error = Error(-5); +pub const ENOMEM: Error = Error(-12); +pub const ENOSPC: Error = Error(-28); +pub const EBUSY: Error = Error(-16); +pub const EPROTO: Error = Error(-71); +pub mod prelude { + pub use crate::{static_assert, Error, Result, EBUSY, EINVAL, EIO, ENODEV, ENOMEM, ENOSPC, KVec, GFP_KERNEL}; +} +pub type ARef = std::sync::Arc; +#[derive(Copy, Clone)] +pub struct Flags; +pub const GFP_KERNEL: Flags = Flags; +/// A kernel vector: pushes past the reserved capacity fail only through push_within_capacity. +pub struct KVec(pub Vec); +impl KVec { + pub fn with_capacity(n: usize, _: Flags) -> Result { + Ok(KVec(Vec::with_capacity(n))) + } + pub fn push(&mut self, value: T, _: Flags) -> Result { + self.0.push(value); + Ok(()) + } + pub fn push_within_capacity(&mut self, value: T) -> core::result::Result<(), T> { + if self.0.len() == self.0.capacity() { + return Err(value); + } + self.0.push(value); + Ok(()) + } + pub fn capacity(&self) -> usize { + self.0.capacity() + } + pub fn len(&self) -> usize { + self.0.len() + } + pub fn get(&self, i: usize) -> Option<&T> { + self.0.get(i) + } + pub fn last(&self) -> Option<&T> { + self.0.last() + } +} +#[macro_export] +macro_rules! static_assert { + ($e:expr) => { + const _: () = assert!($e); + }; +} + +/// One firmware-visible access, barrier or log line, in program order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Ev { + Record(usize, u64), + Sync, + Producer(u32), + Reply([u32; 14]), + Log(&'static str, String), + /// Backing object `id` of this many bytes allocated, or freed (its last reference gone). + Alloc(u32, usize), + Free(u32), + /// A PB alias of object `id` at GVA in the VM with this context, made, held by the VM + /// (appended to its driver mappings), or unmapped. + Map(u32, u64, usize, u32), + Append(u32, u64), + Unmap(u32, u64), +} +thread_local! { + pub static LOG: RefCell> = RefCell::new(Vec::new()); + pub static PARAM: Cell = Cell::new(PARAM_DEFAULT); + /// Failures to inject: the next this many allocations, alias maps, appends fail. + pub static FAIL_ALLOC: Cell = Cell::new(0); + pub static FAIL_MAP: Cell = Cell::new(0); + pub static MAP_OK_BEFORE_FAIL: Cell = Cell::new(0); + pub static FAIL_APPEND: Cell = Cell::new(0); + pub static NEXT_ID: Cell = Cell::new(1); +} +/// Takes one injected failure of `which`. +pub fn fail(which: &'static std::thread::LocalKey>) -> bool { + which.with(|c| { + let n = c.get(); + if n != 0 { + c.set(n - 1); + } + n != 0 + }) +} +pub fn ev(e: Ev) { + LOG.with(|l| l.borrow_mut().push(e)); +} +pub fn take() -> Vec { + LOG.with(|l| std::mem::take(&mut *l.borrow_mut())) +} +macro_rules! dev_log { + ($lvl:expr, $dev:expr, $($arg:tt)*) => {{ + let _ = $dev; + crate::ev(crate::Ev::Log($lvl, format!($($arg)*))); + }}; +} +macro_rules! dev_err { ($($t:tt)*) => { dev_log!("err", $($t)*) }; } +macro_rules! dev_warn { ($($t:tt)*) => { dev_log!("warn", $($t)*) }; } +macro_rules! dev_info { ($($t:tt)*) => { dev_log!("info", $($t)*) }; } +macro_rules! dev_dbg { ($($t:tt)*) => { dev_log!("dbg", $($t)*) }; } + +pub mod mem { + pub fn sync() { + crate::ev(crate::Ev::Sync); + } +} + +/// A boot parameter: read-only after load. +pub mod module_parameters { + pub struct Param; + impl Param { + pub fn value(&self) -> &'static u32 { + Box::leak(Box::new(crate::PARAM.with(|p| p.get()))) + } + } + pub static g15_pb_max_blocks: Param = Param; +} + +pub mod driver { + pub struct AsahiDevice; +} + +/// GEM kernel objects: freed when the last reference (chunk or alias) goes. +pub mod gem { + pub struct Object { + pub id: u32, + pub size: usize, + } + impl Drop for Object { + fn drop(&mut self) { + crate::ev(crate::Ev::Free(self.id)); + } + } + pub struct ObjectRef { + pub gem: crate::ARef, + } +} + +/// The shared layer's VM: kernel aliases at fixed addresses, held by the VM once appended. +pub mod mmu { + use crate::prelude::*; + pub struct Prot(pub u64); + impl Prot { + pub const fn from_pte(pte: u64) -> Self { + Prot(pte) + } + } + pub struct KernelMapping { + pub slot: u32, + pub gva: u64, + pub size: usize, + pub prot: u64, + pub gem: crate::ARef, + } + impl Drop for KernelMapping { + fn drop(&mut self) { + crate::ev(crate::Ev::Unmap(self.slot, self.gva)); + } + } + pub struct Vm { + pub slot: u32, + pub held: std::cell::RefCell>, + } + impl Vm { + pub fn new(slot: u32) -> Self { + Vm { slot, held: Default::default() } + } + pub fn map_at( + &self, + addr: u64, + size: usize, + gem: &crate::ARef, + prot: Prot, + guard: bool, + ) -> Result { + assert!(!guard); + // The shared layer maps whatever size it is given: the whole object, exactly. + assert_eq!(size, gem.size, "alias size differs from its object"); + let skip = crate::MAP_OK_BEFORE_FAIL.with(|c| { + let n = c.get(); + c.set(n.saturating_sub(1)); + n != 0 + }); + if !skip && crate::fail(&crate::FAIL_MAP) { + return Err(ENOMEM); + } + // Leaves already in use: EBUSY (prepare_map). + let end = addr + size as u64; + if self.held.borrow().iter().any(|m| m.gva < end && addr < m.gva + m.size as u64) { + return Err(EBUSY); + } + crate::ev(crate::Ev::Map(self.slot, addr, size, gem.id)); + Ok(KernelMapping { slot: self.slot, gva: addr, size, prot: prot.0, gem: gem.clone() }) + } + pub fn append_driver_mappings(&self, mappings: KVec) -> Result { + if crate::fail(&crate::FAIL_APPEND) { + return Err(ENOMEM); // the mappings drop here + } + for m in mappings.0 { + crate::ev(crate::Ev::Append(self.slot, m.gva)); + self.held.borrow_mut().push(m); + } + Ok(()) + } + } +} +''' + +MODEL = r''' + pub struct Ctl { + pub epoch: u64, + } + impl Ctl { + pub fn r32(&self, offset: usize) -> Result { + if offset == control::HALT_COUNT { + Ok(self.epoch as u32) + } else if offset == control::HALT_COUNT + 4 { + Ok((self.epoch >> 32) as u32) + } else { + panic!("unexpected control read {offset:#x}") + } + } + } + pub struct Init { + pub control: Option>, + } + pub struct VmState { + pub slot: u32, + pub vm: mmu::Vm, + pub pb_chunks: AtomicUsize, + } + impl VmState { + pub fn new(slot: u32) -> Arc { + Arc::new(VmState { slot, vm: mmu::Vm::new(slot), pb_chunks: AtomicUsize::new(0) }) + } + } + pub struct Job { + pub vm: Arc, + } + pub struct Flight { + pub job: Job, + } + pub struct Engine { + pub flights: Vec, + } + pub struct Receipts { + pub renders: u32, + } + /// A firmware object: the block list, block_ctl or the heap. + pub struct FwObject { + pub gva: Option, + pub size: usize, + /// Writes that fail from now on. + pub failures: Cell, + } + impl FwObject { + pub fn w64(&self, offset: usize, value: u64) -> Result { + assert!(offset % 8 == 0 && offset + 8 <= self.size, "record write at {offset:#x}"); + if self.failures.get() != 0 { + self.failures.set(self.failures.get() - 1); + return Err(EIO); + } + crate::ev(crate::Ev::Record(offset, value)); + Ok(()) + } + pub fn w32(&self, offset: usize, value: u32) -> Result { + assert_eq!(offset, block_ctl::PRODUCER); + assert!(offset + 4 <= self.size); + crate::ev(crate::Ev::Producer(value)); + Ok(()) + } + } + fn gva(object: &FwObject) -> Result { + object.gva.ok_or(EINVAL) + } + #[derive(Default)] + pub struct PbStats { + pub requests: u64, + pub grown: u64, + pub refused: u64, + pub bad: u64, + } + pub struct Live { + pub block_ctl: FwObject, + } + pub struct Pools { + pub ledger: Ledger, + pub exhausted_logged: bool, + pub stats: PbStats, + pub pb_blocks: FwObject, + pub live: Live, + pub drm: ARef, + pub chunks: KVec, + } + impl Pools { + pub fn chunk_count(&self) -> usize { + self.chunks.len() + } + pub fn chunk_capacity(&self) -> usize { + self.chunks.capacity() + } + } + pub struct Queue(pub std::collections::VecDeque<[u32; 14]>); + impl Queue { + pub fn len(&self) -> usize { + self.0.len() + } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn remove(&mut self, i: usize) -> core::result::Result<[u32; 14], ()> { + assert_eq!(i, 0); + self.0.pop_front().ok_or(()) + } + } + pub struct Events { + pub grow: Queue, + } + /// The firmware side: its requests, and whether the next one arrives during a reply. + pub struct FwModel { + pub ctx: u32, + pub epoch: u64, + pub next_counter: u32, + pub ask_after_reply: bool, + pub reply_fails: bool, + pub replies_this_pass: u32, + } + impl FwModel { + pub fn request(&mut self) -> [u32; 14] { + let mut q = [0u32; 14]; + q[buffer::grow_request::TYPE] = 7; + q[buffer::grow_request::CONTEXT] = self.ctx; + q[buffer::grow_request::SLOT] = 0; + q[buffer::grow_request::COUNTER] = self.next_counter; + q[buffer::grow_request::POSITION] = 0x100 + self.next_counter; + q[buffer::grow_request::EPOCH] = self.epoch as u32; + q[buffer::grow_request::EPOCH + 1] = (self.epoch >> 32) as u32; + self.next_counter += 1; + q + } + } + pub struct Firmware { + pub events: Events, + pub pools: Pools, + pub init: Init, + pub engine: Engine, + pub renders: Vec, + pub fw: FwModel, + } + pub const HEAP: u64 = super::hw::client::PB_HEAP; + impl Firmware { + /// The VM with context 5 runs: one flight, its PB backing mapped (map_pb, as at the + /// start of its prefix's publication). + pub fn new() -> Self { + let vm = VmState::new(5); + let mut f = Self::without_flights(); + f.engine.flights.push(Flight { job: Job { vm: vm.clone() } }); + f.map_pb(&vm).unwrap(); + crate::take(); + f + } + /// Pools::new's PB backing: the initial chunk, room for every chunk the ledger needs. + pub fn without_flights() -> Self { + let drm = ARef::new(AsahiDevice); + let (ledger, chunks) = pools_new_backing(&drm).unwrap(); + Firmware { + events: Events { grow: Queue(Default::default()) }, + pools: Pools { + ledger, + exhausted_logged: false, + stats: PbStats::default(), + drm, + chunks, + pb_blocks: FwObject { + gva: Some(super::hw::client::PB_BLOCK_LIST), + size: buffer::BLOCK_LIST_SIZE, + failures: Cell::new(0), + }, + live: Live { + block_ctl: FwObject { gva: None, size: block_ctl::SIZE, failures: Cell::new(0) }, + }, + }, + init: Init { control: Some(std::sync::Arc::new(Ctl { epoch: 0x1_0000_0003 })) }, + engine: Engine { flights: Vec::new() }, + renders: vec![1], + fw: FwModel { + ctx: 5, + epoch: 0x1_0000_0003, + next_counter: 0, + ask_after_reply: false, + reply_fails: false, + replies_this_pass: 0, + }, + } + } + pub fn dev(&self) -> &() { + &() + } + pub fn receipts(&self, i: usize) -> Receipts { + Receipts { renders: self.renders[i] } + } + pub fn devctl(&mut self, reply: &DevCtl, wait: bool) -> Result { + assert!(wait); + crate::ev(crate::Ev::Reply(reply.words)); + self.fw.replies_this_pass += 1; + assert!(self.fw.replies_this_pass <= 64, "unbounded answering in one poll pass"); + // The reply's wait drains the rings: the firmware's next request may queue now. + if self.fw.ask_after_reply { + let q = self.fw.request(); + self.events.grow.0.push_back(q); + } + if self.fw.reply_fails { + Err(EIO) + } else { + Ok(()) + } + } + pub fn queue(&mut self) { + let q = self.fw.request(); + self.events.grow.0.push_back(q); + } + /// One poll pass. + pub fn pass(&mut self) { + self.fw.replies_this_pass = 0; + assert_eq!(self.answer_growth(), Ok(())); + } + /// What Pools::init() does to the ledger. + pub fn reset_ledger(&mut self) { + let p = &mut self.pools; + p.RESET + } + } +''' + +TESTS = r''' +#[cfg(test)] +mod pb_growth_tests { + use crate::g15::firmware::{Firmware, VmState, Flight, Job, HEAP}; + use crate::g15::hw::{client, pte}; + use crate::g15::fw::buffer::{BLOCK_BYTES, MAX_BLOCKS}; + use crate::g15::pools::growth::{max_chunks, CHUNK_BLOCKS}; + use crate::g15::pgtable::Prot; + use crate::{EPROTO, FAIL_ALLOC, FAIL_APPEND, FAIL_MAP}; + use core::sync::atomic::Ordering; + use std::sync::Arc; + use crate::g15::fw::buffer::{self, grow_reply, BLOCK_LIST_RECORDS, GROW_STEP}; + use crate::g15::fw::channels::devctl; + use crate::g15::hw::tuning; + use crate::g15::pools::growth::Ledger; + use crate::g15::{params, OldLedger}; + use crate::{take, Ev, ENOMEM, PARAM, PARAM_DEFAULT}; + + const CAP: u32 = BLOCK_LIST_RECORDS - 1; + /// Refusals answered at the maximum, as the commit states them. + const REFUSALS: u32 = 2; + + fn clamp(v: u32, lo: u32, hi: u32) -> u32 { + v.max(lo).min(hi) + } + + fn soft(param: u32, initial: u32, max: u32) -> u32 { + clamp(clamp(param, 64, tuning::PB_MAX_BLOCKS), initial, max) + } + + /// Event logs compared with a short message at the first difference. + fn same(got: &[Ev], want: &[Ev]) { + if let Some(i) = (0..got.len().max(want.len())).find(|&i| got.get(i) != want.get(i)) { + panic!("event {i} of {}/{}: got {:?}, want {:?}", got.len(), want.len(), got.get(i), want.get(i)); + } + } + + fn level(e: &Ev) -> Option<&'static str> { + match e { + Ev::Log(l, _) => Some(l), + _ => None, + } + } + + /// The accesses, replies and log levels a ledger at `posted` gives for the firmware's + /// requests from counter 0 on, if it keeps asking after every reply: growth to the maximum, + /// MAX_REFUSALS refusals, then one unanswered request. + fn expected(initial: u32, max: u32, soft_max: u32) -> (Vec, u32, u32) { + let mut out = Vec::new(); + let (mut posted, mut refusals, mut logged_refusal) = (initial, 0, false); + let mut counter = 0; + loop { + assert!(counter < 10_000, "the expected trace does not end"); + if refusals >= REFUSALS { + out.push(Ev::Log("warn", String::new())); + break; + } + let n = GROW_STEP.min(max - posted); + for b in posted..posted + n { + out.push(Ev::Record(8 * b as usize, buffer::block_record(HEAP, b) as u64)); + } + if n != 0 { + out.push(Ev::Sync); + out.push(Ev::Producer(posted + n)); + out.push(Ev::Sync); + } + let mut r = [0u32; 14]; + r[grow_reply::OPCODE] = devctl::GROW_REPLY; + r[grow_reply::GREW] = (n != 0) as u32; + r[grow_reply::CONTEXT] = 5; + r[grow_reply::COUNTER] = counter; + r[grow_reply::POSITION] = 0x100 + counter; + r[grow_reply::EPOCH] = 3; + r[grow_reply::EPOCH + 1] = 1; + out.push(Ev::Reply(r)); + posted += n; + let first_refusal = n == 0 && !logged_refusal; + if n == 0 { + refusals += 1; + logged_refusal = true; + } + let info = counter < 2 || (n != 0 && posted > soft_max) || first_refusal; + out.push(Ev::Log(if info { "info" } else { "dbg" }, String::new())); + counter += 1; + } + (out, posted, counter + 1) + } + + fn levels_only(evs: Vec) -> Vec { + evs.into_iter() + .filter(|e| !is_backing(e)) + .map(|e| match e { + Ev::Log(l, _) => Ev::Log(l, String::new()), + e => e, + }) + .collect() + } + + /// Growth to the maximum with the firmware asking after every reply, one pass at a time. + fn run_to_exhaustion(param: u32) { + PARAM.with(|p| p.set(param)); + let mut f = Firmware::new(); + let (initial, max) = (f.pools.ledger.initial, f.pools.ledger.max); + assert_eq!(f.pools.soft_max(), soft(param, initial, max)); + f.fw.ask_after_reply = true; + f.queue(); + take(); + let mut passes = 0; + while !f.events.grow.is_empty() { + let queued = f.events.grow.len(); + let before = f.pools.stats.requests; + f.pass(); + passes += 1; + // Exactly the requests queued before the pass were taken. + assert_eq!(f.pools.stats.requests - before, queued as u64); + assert!(passes <= 1000, "growth did not end"); + } + let log = take(); + let (want, posted, requests) = expected(initial, max, soft(param, initial, max)); + same(&levels_only(log.clone()), &want); + assert_eq!(passes, requests); + assert_eq!(f.pools.ledger.posted, posted); + assert_eq!(posted, max); + // Every producer store: increasing, in 1..=4095, the last one the maximum. + let producers: Vec = log + .iter() + .filter_map(|e| if let Ev::Producer(p) = e { Some(*p) } else { None }) + .collect(); + assert!(producers.windows(2).all(|w| w[0] < w[1])); + assert!(producers.iter().all(|p| (1..=CAP).contains(p))); + assert_eq!(*producers.last().unwrap(), max); + // Every block above the initial ones was written once, below the list's end. + let records: Vec = log + .iter() + .filter_map(|e| if let Ev::Record(o, _) = e { Some(*o) } else { None }) + .collect(); + assert_eq!(records.len() as u32, max - initial); + assert!(records.iter().all(|o| o + 8 <= buffer::BLOCK_LIST_SIZE)); + let s = &f.pools.stats; + assert_eq!((s.grown, s.refused, s.bad), ((max - initial) as u64, REFUSALS as u64, 1)); + let warn: Vec<&String> = log + .iter() + .filter_map(|e| if let Ev::Log("warn", m) = e { Some(m) } else { None }) + .collect(); + assert_eq!(warn.len(), 1); + assert!(warn[0].contains(&format!("left unanswered: {REFUSALS} refusals at the maximum ({max} blocks)"))); + // A later request: no reply, counted, no second warning. + f.queue(); + f.pass(); + let log = take(); + assert!(log.is_empty(), "later request after exhaustion: {log:?}"); + assert_eq!(f.pools.stats.bad, 2); + // A new ledger, as Pools::init() makes, answers again. + f.reset_ledger(); + f.queue(); + f.pass(); + let log = take(); + assert_eq!(log.iter().filter(|e| matches!(e, Ev::Producer(_))).count(), 1); + assert!(log.contains(&Ev::Producer(initial + GROW_STEP.min(max - initial)))); + } + + #[test] + fn driver_values() { + let l = Ledger::new(tuning::PB_GROW, tuning::PB_BLOCKS, tuning::PB_MAX_BLOCKS); + assert!(tuning::PB_GROW); + assert_eq!((l.initial, l.max, l.posted), (1024, 4095, 1024)); + assert_eq!(PARAM_DEFAULT, 3072); + PARAM.with(|p| p.set(PARAM_DEFAULT)); + assert_eq!(params::pb_max_blocks(), 3072); + assert_eq!(Firmware::new().pools.soft_max(), 3072); + } + + #[test] + fn soft_max_bounds() { + let f = Firmware::new(); + for param in [0, 1, 63, 64, 65, 1023, 1024, 1025, 3071, 3072, 3073, 4094, 4095, 4096, 8192, u32::MAX] { + PARAM.with(|p| p.set(param)); + assert_eq!(params::pb_max_blocks(), clamp(param, 64, tuning::PB_MAX_BLOCKS), "pb_max_blocks, param {param}"); + // Below the initial 1024 the firmware still gets 1024. + assert_eq!(f.pools.soft_max(), clamp(param, 1024, CAP), "soft_max, param {param}"); + } + } + + #[test] + fn default_growth_to_exhaustion() { + run_to_exhaustion(PARAM_DEFAULT); + } + + #[test] + fn soft_max_boundaries() { + // 3074 is reached exactly (1024 + 205 * 10): that answer is not past it. + for param in [0, 1024, 3072, 3074, 3075, 4094, 4095, u32::MAX] { + run_to_exhaustion(param); + } + } + + #[test] + fn queued_snapshot_keeps_order() { + let mut f = Firmware::new(); + f.fw.ask_after_reply = true; + f.queue(); + f.queue(); + take(); + f.pass(); + let log = take(); + let replies: Vec = log + .iter() + .filter_map(|e| if let Ev::Reply(r) = e { Some(r[grow_reply::COUNTER]) } else { None }) + .collect(); + assert_eq!(replies, vec![0, 1], "replies in the first pass"); + // Compare both requests' complete record/barrier/producer/reply/log sequences, + // not just their reply order. Each request finishes before the next one's records. + let (want, _, _) = expected(f.pools.ledger.initial, f.pools.ledger.max, f.pools.soft_max()); + let end = want.iter().position(|e| matches!(e, Ev::Reply(r) if r[grow_reply::COUNTER] == 1)) + .expect("second expected reply") + 2; // Include its log too. + same(&levels_only(log), &want[..end]); + let queued: Vec = f.events.grow.0.iter().map(|q| q[buffer::grow_request::COUNTER]).collect(); + assert_eq!(queued, vec![2, 3]); + assert_eq!(f.pools.stats.requests, 2); + f.pass(); + assert_eq!(f.pools.stats.requests, 4); + assert_eq!(f.events.grow.len(), 2); + } + + #[test] + fn empty_queue_does_nothing() { + let mut f = Firmware::new(); + take(); + f.pass(); + assert!(take().is_empty()); + assert_eq!(f.pools.stats.requests, 0); + } + + #[test] + fn unprocessed_request_does_not_end_the_pass() { + let mut f = Firmware::new(); + f.queue(); + f.queue(); + f.pools.pb_blocks.failures.set(1); + take(); + f.pass(); + let log = take(); + // The second request was answered in the same pass, from the same posted count. + assert_eq!(f.pools.stats.requests, 2, "requests taken in the pass"); + assert_eq!(f.pools.stats.bad, 1); + assert!(log.iter().any(|e| matches!(e, Ev::Log("err", m) if m.contains("not answered: -5")))); + assert!(log.contains(&Ev::Producer(1024 + GROW_STEP))); + assert!(f.events.grow.is_empty()); + } + + #[test] + fn failed_reply_is_logged_and_counted_as_grown() { + let mut f = Firmware::new(); + f.fw.reply_fails = true; + f.queue(); + f.queue(); + f.queue(); + take(); + f.pass(); + let log = take(); + assert_eq!(f.pools.ledger.posted, 1024 + 3 * GROW_STEP); + assert_eq!((f.pools.stats.grown, f.pools.stats.bad), (3 * GROW_STEP as u64, 0)); + // Each failed reply is logged at info level. + let info = log.iter().filter(|e| matches!(e, Ev::Log("info", m) if m.contains("DEVCTL 7: -5"))).count(); + assert_eq!(info, 3); + } + + #[test] + fn invalid_requests_get_no_reply() { + let mut f = Firmware::new(); + let good = f.fw.request(); + let mut cases = Vec::new(); + let mut q = good; + q[buffer::grow_request::TYPE] = 6; + cases.push(q); + let mut q = good; + q[buffer::grow_request::SLOT] = 1; + cases.push(q); + let mut q = good; + q[buffer::grow_request::EPOCH] = 2; + cases.push(q); + let mut q = good; + q[buffer::grow_request::CONTEXT] = 6; + cases.push(q); + for q in cases { + f.events.grow.0.push_back(q); + } + take(); + f.pass(); + let log = take(); + assert!(log.iter().all(|e| matches!(e, Ev::Log("warn", _))), "{log:?}"); + assert_eq!(log.len(), 4); + assert_eq!(f.pools.stats.bad, 4); + assert_eq!(f.pools.ledger, Ledger::new(tuning::PB_GROW, tuning::PB_BLOCKS, tuning::PB_MAX_BLOCKS)); + // No render published: not live. + f.renders[0] = 0; + f.events.grow.0.push_back(good); + f.pass(); + assert!(!take().iter().any(|e| matches!(e, Ev::Reply(_)))); + // A stale counter after an answer. + f.renders[0] = 1; + f.events.grow.0.push_back(good); + f.pass(); + assert!(take().iter().any(|e| matches!(e, Ev::Reply(_)))); + f.events.grow.0.push_back(good); + f.pass(); + assert!(!take().iter().any(|e| matches!(e, Ev::Reply(_)))); + assert_eq!(f.pools.stats.bad, 6); + } + + fn is_backing(e: &Ev) -> bool { + matches!(e, Ev::Alloc(..) | Ev::Free(_) | Ev::Map(..) | Ev::Append(..) | Ev::Unmap(..)) + } + + /// A VM's PB aliases: its count, and the aliases it holds, from block 0 in order. + fn assert_cursor(vm: &VmState, chunks: usize) { + let held = vm.vm.held.borrow(); + assert_eq!(vm.pb_chunks.load(Ordering::Relaxed), held.len(), "count differs from held aliases"); + assert!(held.len() <= chunks); + let mut gva = client::PB_HEAP; + for m in held.iter() { + assert_eq!(m.gva, gva, "aliases not contiguous from the heap's start"); + assert_eq!(m.prot, pte::LEAF_CACHED); + gva += m.size as u64; + } + } + + /// In the order of `log`: no block record and no producer past the blocks the VM with + /// context `slot` holds aliases for at that point. + fn assert_posted_backed(log: &[Ev], slot: u32, start: u64) { + let mut mapped = start; + for e in log { + match e { + Ev::Append(s, gva) if *s == slot => { + assert_eq!(*gva, client::PB_HEAP + mapped * BLOCK_BYTES, "append out of order"); + } + Ev::Map(s, gva, size, _) if *s == slot && *gva == client::PB_HEAP + mapped * BLOCK_BYTES => { + // Counted at its append. + let _ = size; + } + _ => {} + } + if let Ev::Append(s, gva) = e { + if *s == slot { + let size = log + .iter() + .find_map(|m| match m { + Ev::Map(ms, mg, size, _) if ms == s && mg == gva => Some(*size as u64), + _ => None, + }) + .unwrap(); + mapped += size / BLOCK_BYTES; + } + } + if let Ev::Record(off, _) = e { + assert!((*off as u64 / 8) < mapped, "record of block {} with {} mapped", off / 8, mapped); + } + if let Ev::Producer(p) = e { + assert!(*p as u64 <= mapped, "producer {} with {} mapped", p, mapped); + } + } + } + + fn count(log: &[Ev], f: impl Fn(&Ev) -> bool) -> usize { + log.iter().filter(|e| f(e)).count() + } + + /// The firmware asks until the ledger reaches `target` posted blocks, one request a pass. + fn grow_to(f: &mut Firmware, target: u32) { + for _ in 0..1000 { + if f.pools.ledger.posted >= target { + return; + } + f.queue(); + f.pass(); + } + panic!("growth stopped at {} blocks", f.pools.ledger.posted); + } + + #[test] + fn startup_backs_the_initial_blocks() { + let mut f = Firmware::without_flights(); + let log = take(); + let (initial, max) = (f.pools.ledger.initial, f.pools.ledger.max); + assert_eq!(log, vec![Ev::Alloc(1, initial as usize * BLOCK_BYTES as usize)], "startup allocation"); + assert_eq!((f.pools.backed(), f.pools.chunk_count()), (initial, 1)); + assert_eq!(f.pools.chunk_capacity(), max_chunks(initial, max)); + assert_eq!(max_chunks(initial, max), 97); + // The first prefix of a VM maps the backing, nothing else. + let vm = VmState::new(7); + f.engine.flights.push(Flight { job: Job { vm: vm.clone() } }); + f.map_pb(&vm).unwrap(); + let size = initial as usize * BLOCK_BYTES as usize; + assert_eq!(take(), vec![Ev::Map(7, client::PB_HEAP, size, 1), Ev::Append(7, client::PB_HEAP)]); + assert_cursor(&vm, 1); + // Mapping again maps nothing. + f.map_pb(&vm).unwrap(); + assert!(take().is_empty()); + } + + #[test] + fn pb_leaf_is_gpu_only() { + let prot = Prot::from_pte(pte::LEAF_CACHED); + assert!(prot.ap_is_gpu() && !prot.is_cached_noncoherent(), "PB leaf not GPU-only"); + } + + #[test] + fn growth_backs_before_posting() { + PARAM.with(|p| p.set(PARAM_DEFAULT)); + let mut f = Firmware::new(); + f.fw.ask_after_reply = true; + f.queue(); + take(); + let mut passes = 0; + while !f.events.grow.is_empty() { + f.pass(); + passes += 1; + assert!(passes <= 1000, "growth did not end"); + } + let log = take(); + let (initial, max) = (f.pools.ledger.initial, f.pools.ledger.max); + assert_posted_backed(&log, 5, initial as u64); + // Chunks of at most 32 blocks, allocated only as needed: up to the maximum, no further. + let allocs: Vec = log + .iter() + .filter_map(|e| if let Ev::Alloc(_, b) = e { Some(*b) } else { None }) + .collect(); + assert_eq!(allocs.len() + 1, max_chunks(initial, max)); + assert!(allocs.iter().all(|b| *b <= 4 << 20), "a growth chunk above 4 MiB"); + assert_eq!(CHUNK_BLOCKS as u64 * BLOCK_BYTES, 4 << 20); + assert_eq!(f.pools.backed(), max); + assert_eq!(count(&log, |e| matches!(e, Ev::Free(_) | Ev::Unmap(..))), 0); + assert_cursor(&f.engine.flights[0].job.vm, f.pools.chunk_count()); + } + + /// A failure while backing posts nothing and answers nothing; the request counter and the + /// VM's count stay; the next request is answered. + fn failure_posts_nothing(which: &'static std::thread::LocalKey>) -> Vec { + let mut f = Firmware::new(); + which.with(|c| c.set(1)); + f.queue(); + f.pass(); + let log = take(); + assert_eq!(count(&log, |e| matches!(e, Ev::Record(..) | Ev::Producer(_) | Ev::Reply(_) | Ev::Sync)), 0, + "posted after a backing failure: {log:?}"); + assert_eq!((f.pools.ledger.posted, f.pools.ledger.next_request), (1024, 0), "ledger after a backing failure"); + assert_eq!((f.pools.stats.bad, f.pools.chunk_count()), (1, 1), "chunks after a backing failure"); + assert_cursor(&f.engine.flights[0].job.vm, 1); + assert!(log.iter().any(|e| matches!(e, Ev::Log("err", m) if m.contains("not answered: -12")))); + f.queue(); + f.pass(); + let retry = take(); + assert!(retry.contains(&Ev::Producer(1034))); + assert_eq!(f.pools.chunk_count(), 2); + assert_cursor(&f.engine.flights[0].job.vm, 2); + log + } + + #[test] + fn allocation_failure_posts_nothing() { + let log = failure_posts_nothing(&FAIL_ALLOC); + assert_eq!(count(&log, is_backing), 0); + } + + #[test] + fn map_failure_posts_nothing() { + let log = failure_posts_nothing(&FAIL_MAP); + let backing: Vec<&Ev> = log.iter().filter(|e| is_backing(e)).collect(); + assert!(matches!(backing[..], [Ev::Alloc(2, _), Ev::Free(2)]), "{backing:?}"); + } + + #[test] + fn append_failure_posts_nothing() { + let log = failure_posts_nothing(&FAIL_APPEND); + let backing: Vec<&Ev> = log.iter().filter(|e| is_backing(e)).collect(); + assert!( + matches!(backing[..], [Ev::Alloc(2, _), Ev::Map(5, _, _, 2), Ev::Unmap(5, _), Ev::Free(2)]), + "{backing:?}" + ); + } + + #[test] + fn transport_failure_keeps_everything() { + let mut f = Firmware::new(); + f.fw.reply_fails = true; + f.queue(); + f.pass(); + let log = take(); + assert!(log.contains(&Ev::Producer(1034))); + assert_eq!((f.pools.ledger.posted, f.pools.chunk_count()), (1034, 2)); + assert_cursor(&f.engine.flights[0].job.vm, 2); + assert_eq!(count(&log, |e| matches!(e, Ev::Free(_) | Ev::Unmap(..))), 0); + } + + #[test] + fn other_vms_catch_up_before_they_run() { + let mut f = Firmware::new(); + let a = f.engine.flights[0].job.vm.clone(); + grow_to(&mut f, 1100); + take(); + assert_eq!(f.pools.chunk_count(), 4); + // A's work retires; a new VM runs next: it maps every chunk first. + f.engine.flights.clear(); + let b = VmState::new(6); + f.engine.flights.push(Flight { job: Job { vm: b.clone() } }); + f.fw.ctx = 6; + f.map_pb(&b).unwrap(); + let log = take(); + assert_eq!(count(&log, |e| matches!(e, Ev::Append(6, _))), 4); + assert_eq!(count(&log, |e| matches!(e, Ev::Alloc(..))), 0); + assert_cursor(&b, 4); + // B grows the backing; A, behind, catches up when it runs again. + grow_to(&mut f, 1200); + let log = take(); + assert_posted_backed(&log, 6, 1120); + assert_eq!(count(&log, |e| matches!(e, Ev::Map(5, ..))), 0); + f.engine.flights.clear(); + f.engine.flights.push(Flight { job: Job { vm: a.clone() } }); + f.map_pb(&a).unwrap(); + assert_cursor(&a, f.pools.chunk_count()); + assert_eq!(a.pb_chunks.load(Ordering::Relaxed), f.pools.chunk_count()); + } + + #[test] + fn growth_catches_the_running_vm_up_first() { + let mut f = Firmware::new(); + let a = f.engine.flights[0].job.vm.clone(); + // B grows the backing while A is idle. + f.engine.flights.clear(); + let b = VmState::new(6); + f.engine.flights.push(Flight { job: Job { vm: b.clone() } }); + f.map_pb(&b).unwrap(); + f.fw.ctx = 6; + grow_to(&mut f, 1100); + // A runs again; its growth request maps what it lacks before backing more. + f.engine.flights.clear(); + f.engine.flights.push(Flight { job: Job { vm: a.clone() } }); + f.fw.ctx = 5; + take(); + grow_to(&mut f, 1130); + let log = take(); + assert_eq!(a.vm.held.borrow().len(), f.pools.chunk_count(), "running VM not caught up"); + assert_cursor(&a, f.pools.chunk_count()); + assert_posted_backed(&log, 5, 1024); + } + + #[test] + fn partial_catch_up_counts_only_held_aliases() { + let mut f = Firmware::new(); + grow_to(&mut f, 1100); + f.engine.flights.clear(); + let b = VmState::new(6); + f.engine.flights.push(Flight { job: Job { vm: b.clone() } }); + take(); + // The third alias cannot be made: two held. + FAIL_MAP.with(|c| c.set(0)); + crate::MAP_OK_BEFORE_FAIL.with(|c| c.set(2)); + FAIL_MAP.with(|c| c.set(1)); + assert_eq!(f.map_pb(&b), Err(ENOMEM)); + assert_cursor(&b, 4); + assert_eq!(b.pb_chunks.load(Ordering::Relaxed), 2); + // The third alias is made but cannot be held: dropped, still two. + FAIL_APPEND.with(|c| c.set(1)); + assert_eq!(f.map_pb(&b), Err(ENOMEM)); + assert_eq!(b.pb_chunks.load(Ordering::Relaxed), 2, "count after a failed append"); + assert!(take().iter().any(|e| matches!(e, Ev::Unmap(6, _)))); + assert_cursor(&b, 4); + f.map_pb(&b).unwrap(); + assert_eq!(b.pb_chunks.load(Ordering::Relaxed), 4); + assert_cursor(&b, 4); + } + + /// The ledger reset of Pools::init(), not a full recovery. + #[test] + fn ledger_reset_reuses_the_backing() { + let mut f = Firmware::new(); + grow_to(&mut f, 1300); + let chunks = f.pools.chunk_count(); + take(); + f.reset_ledger(); + assert_eq!(f.pools.ledger.posted, 1024); + grow_to(&mut f, 1300); + let log = take(); + assert_eq!(count(&log, |e| matches!(e, Ev::Alloc(..) | Ev::Map(..))), 0); + assert_eq!(f.pools.chunk_count(), chunks); + assert_posted_backed(&log, 5, f.pools.backed() as u64); + } + + #[test] + fn rejected_requests_allocate_nothing() { + let mut f = Firmware::new(); + let mut q = f.fw.request(); + q[buffer::grow_request::EPOCH] = 2; // a halt epoch that has passed + f.events.grow.0.push_back(q); + f.pass(); + let log = take(); + assert_eq!(count(&log, is_backing), 0); + assert_eq!(f.pools.stats.bad, 1); + } + + #[test] + fn catch_up_refuses_flights_of_another_vm() { + let mut f = Firmware::new(); + let a = f.engine.flights[0].job.vm.clone(); + let b = VmState::new(6); + f.engine.flights.push(Flight { job: Job { vm: b.clone() } }); + assert_eq!(f.map_pb(&b), Err(EPROTO), "catch-up with a flight of another VM"); + assert_eq!(b.pb_chunks.load(Ordering::Relaxed), 0); + assert_eq!(count(&take(), is_backing), 0); + // A count past the chunks. + f.engine.flights.pop(); + a.pb_chunks.store(f.pools.chunk_count() + 1, Ordering::Relaxed); + assert_eq!(f.map_pb(&a), Err(EPROTO), "catch-up with a count past the chunks"); + } + + #[test] + fn grant_refuses_flights_of_two_vms() { + let mut f = Firmware::new(); + let b = VmState::new(6); + f.engine.flights.push(Flight { job: Job { vm: b.clone() } }); + f.renders.push(1); + f.queue(); + f.pass(); + let log = take(); + assert_eq!( + count(&log, |e| is_backing(e) || matches!(e, Ev::Reply(_) | Ev::Producer(_) | Ev::Record(..))), + 0, + "grant with flights of two VMs" + ); + assert!(log.iter().any(|e| matches!(e, Ev::Log("err", m) if m.contains("not answered: -71")))); + } + + #[test] + fn constructor_is_the_old_one_capped() { + let mut values: Vec = (0..=4200).collect(); + values.extend([8191, 8192, u32::MAX - 1, u32::MAX]); + let mut changed = 0u64; + let mut cases = 0u64; + for grow in [true, false] { + for &blocks in &values { + for &max_blocks in &values { + let old = OldLedger::new(grow, blocks, max_blocks); + let new = Ledger::new(grow, blocks, max_blocks); + cases += 1; + assert_eq!( + (new.initial, new.max, new.posted), + (old.initial.min(CAP), old.max.min(CAP), old.posted.min(CAP)), + "new({grow}, {blocks}, {max_blocks})" + ); + assert!((1..=CAP).contains(&(new.posted % BLOCK_LIST_RECORDS))); + if old.max <= CAP { + assert_eq!((new.initial, new.max), (old.initial, old.max)); + } else { + changed += 1; + } + } + } + } + // Only inputs the old constructor took to the whole 4096-block heap changed. + assert!(changed > 0 && changed < cases); + // The driver's values are below the cap, so its ledger is the old one. + let d = (tuning::PB_GROW, tuning::PB_BLOCKS, tuning::PB_MAX_BLOCKS); + let (old, new) = (OldLedger::new(d.0, d.1, d.2), Ledger::new(d.0, d.1, d.2)); + if d.2 <= CAP { + assert_eq!((old.initial, old.max, old.posted), (new.initial, new.max, new.posted)); + } + println!("constructor cases {cases}, changed {changed}"); + } +} +''' + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--ref', help='Read the tested bodies at this git revision') + p.add_argument('--mutation', choices=sorted(MUTATIONS) + sorted(CONTROLS)) + p.add_argument('--mutations', action='store_true', + help='Also require every mutation to fail and every control to pass') + a = p.parse_args() + import tempfile + out = (a.output or Path(tempfile.mkdtemp(prefix='g15-pb-growth-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + + def read(path, ref=None): + ref = ref or a.ref + return (subprocess.check_output(['git', 'show', f'{ref}:{path}'], cwd=ROOT, text=True, + stderr=subprocess.DEVNULL) + if ref else (ROOT / path).read_text()) + + # The embedded reference is the commit's own text, when the commit is here. + try: + old_git = item(read(GROWTH.replace("drivers/gpu/drm/asahi/", "drivers/gpu/drm/asahi-m3/"), OLD_REF), ' pub(crate) const fn new(') + except (subprocess.CalledProcessError, ValueError): + old_git = None + if old_git is not None and old_git != OLD_LEDGER_NEW: + raise SystemExit('embedded Ledger::new() differs from ' + OLD_REF) + + def run(mutation): + paths = (POOLS, GROWTH, BUFFER, CHANNELS, INITDATA, PARAMS, HW, CORE, ENGINE, PGTABLE) + src = {path: read(path) for path in paths} + if mutation: + spec = {**MUTATIONS, **CONTROLS}[mutation] + for path, old, new in (spec if isinstance(spec, list) else [spec]): + if src[path].count(old) != 1: + raise SystemExit(f'mutation {mutation}: anchor not found once') + src[path] = src[path].replace(old, new) + pools, hw = src[POOLS], src[HW] + bodies = [item(pools, s) for s in (' pub(crate) fn answer_growth(&mut self) -> Result {', + ' fn answer_request(&mut self, request: &[u32; 14]) -> Result {', + ' pub(crate) fn map_pb(&mut self, vm: &VmState) -> Result {', + ' fn running_vm(&self, ctx: u32) -> Result> {', + ' fn back_pb(&mut self, end: u32, ctx: u32) -> Result {')] + soft_max = item(pools, ' pub(crate) fn soft_max(&self) -> u32 {') + backed = item(pools, ' pub(crate) fn backed(&self) -> u32 {') + chunk = item(pools, 'struct PbChunk {') + '\n' + item(pools, 'impl PbChunk {') + start = pools.index(POOLS_NEW_BACKING[0]) + end = pools.index('\n', pools.index(POOLS_NEW_BACKING[1], start)) + 1 + pools_new_backing = pools[start:end] + if pools.count(PB_LEAF_ASSERT) != 1: + raise SystemExit('pools.rs does not assert the PB leaf GPU-only') + # Every prefix maps the PB into its VM before anything else. + prefix_into = item(src[ENGINE], ' fn publish_prefix_into(&mut self, job: &Arc, f: &mut Flight) -> Result {') + statements = [l.strip() for l in prefix_into.splitlines()[1:] if l.strip() and not l.strip().startswith('//')] + if not statements[0].startswith('self.map_pb(&job.vm)'): + raise SystemExit('publish_prefix_into does not start with the PB catch-up') + pgtable = src[PGTABLE] + pg_consts = '\n'.join(re.search(rf'^const {n}: \w+ = [^;]+;', pgtable, re.M).group(0) + for n in ('UAT_AP_SHIFT', 'UAT_AP_BITS', 'UAT_HIGH_BITS_SHIFT', 'UAT_MEMATTR_SHIFT', + 'UAT_MEMATTR_BITS', 'MEMATTR_CACHED', 'AP_GPU')) + prot = (item(pgtable, 'pub(crate) struct Prot {') + '\nimpl Prot {\n' + + item(pgtable, ' pub(crate) const fn from_pte(pte: u64) -> Self {') + '\n' + + item(pgtable, ' pub(crate) const fn is_cached_noncoherent(&self) -> bool {') + + '\n pub fn ap_is_gpu(&self) -> bool { self.ap == AP_GPU }\n}\n') + init = item(pools, ' fn init(&mut self) -> Result {') + for line in LEDGER_RESET: + if init.count(line) != 1: + raise SystemExit('Pools::init() does not hold: ' + line) + reset = '\n'.join('p.' + line[len('self.'):] for line in LEDGER_RESET) + pb_max_blocks = item(src[PARAMS], 'pub(crate) fn pb_max_blocks() -> u32 {') + m = re.search(r'g15_pb_max_blocks: u32 \{\s*default: (\d+),', src[CORE]) + if not m: + raise SystemExit('g15_pb_max_blocks default not found') + param_default = int(m.group(1)) + sizes = consts(item(hw, 'pub(crate) mod sizes {'), ['PB_BLOCKS']) + tuning = consts(item(hw, 'pub(crate) mod tuning {'), ['PB_GROW', 'PB_BLOCKS', 'PB_MAX_BLOCKS']) + client = consts(item(hw, 'pub(crate) mod client {'), ['PB_HEAP', 'PB_BLOCK_LIST']) + pte = consts(item(hw, 'pub(crate) mod pte {'), ['LEAF_CACHED']) + control = consts(item(src[INITDATA], 'pub(crate) mod control {'), ['HALT_COUNT']) + growth = src[GROWTH] + clamp_fn = item(growth, 'const fn clamp(v: u32, lo: u32, hi: u32) -> u32 {') + tested = (''.join(bodies) + soft_max + backed + chunk + pools_new_backing + pb_max_blocks + growth + + src[BUFFER] + sizes + tuning + pte + prot) + dir = out / (mutation or 'actual') + dir.mkdir(exist_ok=True) + for path in (GROWTH, BUFFER, CHANNELS): + (dir / Path(path).name).write_text(src[path]) + code = (PREFIX + f'pub const PARAM_DEFAULT: u32 = {param_default};\n' + + 'pub mod g15 {\n' + ' pub mod fw {\n' + f' #[path = "{dir / "channels.rs"}"] pub mod channels;\n' + f' #[path = "{dir / "buffer.rs"}"] pub mod buffer;\n' + ' pub mod initdata { pub mod control {\n' + control + '\n} }\n' + ' }\n' + f' pub mod pools {{ #[path = "{dir / "growth.rs"}"] pub mod growth; }}\n' + ' pub mod hw {\n' + ' pub mod sizes {\n' + sizes + '\n}\n' + ' pub mod tuning {\n' + tuning + '\n}\n' + ' pub mod client {\n' + client + '\n}\n' + ' pub mod pte {\n' + pte + '\n}\n' + ' }\n' + ' pub mod pgtable {\n' + pg_consts + '\n' + prot + '\n }\n' + ' pub mod boot {\n pub fn eproto() -> crate::Error { crate::EPROTO }\n }\n' + ' /// The checked backing allocation, failing where a test injects it.\n' + ' pub mod object {\n' + ' use crate::prelude::*;\n' + ' pub struct HeldPages;\n' + ' pub fn gpu_backing(_: &crate::driver::AsahiDevice, bytes: usize)\n' + ' -> Result<(crate::gem::ObjectRef, HeldPages)> {\n' + ' if crate::fail(&crate::FAIL_ALLOC) { return Err(ENOMEM); }\n' + ' let id = crate::NEXT_ID.with(|n| { let id = n.get(); n.set(id + 1); id });\n' + ' crate::ev(crate::Ev::Alloc(id, bytes));\n' + ' Ok((crate::gem::ObjectRef { gem: crate::ARef::new(crate::gem::Object { id, size: bytes }) }, HeldPages))\n' + ' }\n' + ' }\n' + ' pub mod params {\n use crate::module_parameters;\n' + pb_max_blocks + '\n }\n' + ' /// Ledger::new() at ' + OLD_REF[:12] + '.\n' + ' pub struct OldLedger { pub initial: u32, pub max: u32, pub posted: u32, pub next_request: u32,\n' + ' pub refusal_logged: bool, pub refusals: u32 }\n' + ' use crate::g15::fw::buffer::{MAX_BLOCKS, MIN_BLOCKS};\n' + ' impl OldLedger {\n' + OLD_LEDGER_NEW + '\n }\n' + clamp_fn + '\n' + ' pub mod firmware {\n' + ' use crate::prelude::*;\n' + ' use std::cell::Cell;\n' + ' use super::fw::buffer::{self, block_ctl};\n' + ' use super::fw::channels::DevCtl;\n' + ' use super::fw::initdata::control;\n' + ' use super::hw::{client, pte, tuning};\n' + ' use super::pools::growth::{self, Ledger};\n' + ' use super::object::{self, HeldPages};\n' + ' use crate::driver::AsahiDevice;\n' + ' use crate::{gem, mmu, ARef};\n' + ' use core::sync::atomic::{AtomicUsize, Ordering};\n' + ' use std::sync::Arc;\n' + + MODEL.replace('p.RESET', reset).replace('POOLS_NEW_BACKING', '') + + chunk + '\n' + ' /// Pools::new\'s PB backing, verbatim.\n' + ' pub fn pools_new_backing(dev: &AsahiDevice) -> Result<(Ledger, KVec)> {\n' + + pools_new_backing + ' Ok((ledger, chunks))\n }\n' + ' impl Pools {\n' + soft_max + '\n' + backed + '\n }\n' + ' impl Firmware {\n' + '\n'.join(bodies) + '\n }\n' + ' }\n' + '}\n' + TESTS) + path = dir / 'growth-answer.rs' + path.write_text(code) + binary = dir / 'growth-answer' + build = subprocess.run(['rustup', 'run', '1.93.1', 'rustc', '--edition=2021', '--test', '-O', + '-C', 'overflow-checks=on', str(path), '-o', str(binary)], + capture_output=True, text=True) + if build.returncode != 0: + raise SystemExit(f'{mutation or "actual"}: build failed\n{build.stderr[-3000:]}') + + def no_core(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + try: + r = subprocess.run([str(binary), '--show-output', 'pb_growth_tests::'], capture_output=True, + text=True, preexec_fn=no_core, timeout=60) + except subprocess.TimeoutExpired: + # A hang is not a test failure: no test is reported failed, so no mutation counts. + return {'mutation': mutation, 'exit': 'timeout', 'summary': [], 'failed': [], 'output': {}, + 'stderr': 'timed out after 60 s'} + summary = [line for line in r.stdout.splitlines() if line.startswith('test result:')] + failed = sorted(line.split()[1].removeprefix('pb_growth_tests::') for line in r.stdout.splitlines() + if line.startswith('test ') and line.endswith('FAILED')) + # Each test's captured output: the panic message of a failure, the counts of a success. + output = {m.group(1).removeprefix('pb_growth_tests::'): m.group(2).strip() + for m in re.finditer(r'---- (\S+) stdout ----\n(.*?)(?=\n---- |\n(?:failures|successes):\n|\Z)', + r.stdout, re.S)} + source_hashes = {path: hashlib.sha256(src[path].encode()).hexdigest() for path in paths} + source_inputs = json.dumps(source_hashes, sort_keys=True, separators=(',', ':')).encode() + return {'mutation': mutation, 'tested_sha256': hashlib.sha256(tested.encode()).hexdigest(), + 'source_sha256': source_hashes, + 'source_inputs_sha256': hashlib.sha256(source_inputs).hexdigest(), + 'exit': r.returncode, 'summary': summary, 'failed': failed, 'output': output, + 'stderr': r.stderr[-2000:]} + + result = run(a.mutation) + receipt = {'ref': a.ref, 'old_ref': OLD_REF, 'old_reference_checked_against_git': old_git is not None, + **result, + 'scope': 'Actual answer_growth/answer_request/soft_max/pb_max_blocks, pools/growth.rs, ' + 'fw/buffer.rs and fw/channels.rs over a model of the firmware objects with an ' + 'ordered access log, and Ledger::new against its body at ' + f'{OLD_REF[:12]}. Not kernel, firmware or GPU execution, timing, or recovery.'} + if a.mutations and not a.mutation: + receipt['mutations'] = {} + for m in sorted(MUTATIONS): + res = run(m) + test, message = INTENDED[m] + got = res['output'].get(test, '') + receipt['mutations'][m] = {'exit': res['exit'], 'failed': res['failed'], 'intended_test': test, + 'intended_failure': test in res['failed'] and message in got, + 'message': '\n'.join(l for l in got.splitlines() + if not l.startswith('note:'))[-600:]} + receipt['controls'] = {} + for m in sorted(CONTROLS): + res = run(m) + receipt['controls'][m] = {'exit': res['exit'], 'failed': res['failed'], 'summary': res['summary']} + (out / 'result.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps({k: v for k, v in receipt.items() if k not in ('output', 'stderr')}, indent=2)) + # The actual bodies and the controls must pass; a single requested mutation must fail. + expect_fail = a.mutation in MUTATIONS + if (receipt['exit'] != 0) != expect_fail: + raise SystemExit(1) + if expect_fail: + test, message = INTENDED[a.mutation] + if test not in receipt['failed'] or message not in receipt['output'].get(test, ''): + raise SystemExit('the mutation timed out or failed elsewhere than intended') + if a.mutations and any(v['exit'] == 0 or not v['intended_failure'] + for v in receipt.get('mutations', {}).values()): + raise SystemExit('a mutation survived or failed elsewhere than intended') + if a.mutations and any(v['exit'] != 0 for v in receipt.get('controls', {}).values()): + raise SystemExit('a control failed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py new file mode 100644 index 00000000000000..9acd1f012413ad --- /dev/null +++ b/tools/asahi/g15-probe-init-tests.py @@ -0,0 +1,402 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise the actual G15 probe with the vendored pin-init crate and proc macro. + +Builds the actual vendored host proc macro without a kernel build or downloaded +crates. An existing kernel-build macro may optionally be supplied for comparison. +The G15 probe, platform callback's dispatch block, Device::set_drvdata and +try_pin_init macro are extracted from production. GPU startup and the allocator +are fault-injection models. KBox's actual source is checked to allocate before +write_pin_init; the host uses the same vendored write_pin_init implementation. +This checks allocation/init/binding order, not a GPU or a kernel probe on hardware. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +OLD_REF = "564f61b8189e" +PROBE_PATH = "drivers/gpu/drm/asahi/g15/mod.rs" +# Verbatim inherited eager probe before the lazy initializer fix. +OLD_PROBE = r''' fn probe<'bound>( + pdev: &'bound platform::Device>, + info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit, Error> + 'bound { + let cfg = *info.ok_or(ENODEV)?; + dev_info!(pdev.as_ref(), "G15: probing ({})\n", cfg.name); + match crate::driver::AsahiPlatformDriver::probe_g15(pdev, cfg) { + Ok(driver) => Ok(Driver { _driver: Some(driver) }), + Err(error) if boot::glue::retained() => { + dev_err!( + pdev.as_ref(), + "G15: probe failed after the firmware start ({:?}); device kept bound, firmware retained until reboot\n", + error + ); + Ok(Driver { _driver: None }) + } + Err(error) => Err(error), + } + }''' + + +def item(text, marker): + start = text.index(marker) + at = text.index("{", start) + depth = 1 + end = at + 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return text[start:end] + + +PREFIX = r''' +#![allow(dead_code, unused_variables)] +extern crate self as kernel; +use std::{cell::Cell, marker::PhantomData, pin::Pin, sync::atomic::{AtomicBool, Ordering}}; +use pin_init::{pin_data, PinInit, InPlaceWrite}; +pub mod error { pub type Error = i32; } +use error::Error; +type Result = std::result::Result; +const ENODEV: i32 = -19; +const EPROBE_DEFER: i32 = -517; +const GFP_KERNEL: u32 = 0; +macro_rules! dev_info { ($($x:tt)*) => {{}}; } +macro_rules! dev_err { ($($x:tt)*) => {{}}; } +thread_local! { + static FAIL_ALLOC: Cell = const { Cell::new(false) }; + static ALLOCS: Cell = const { Cell::new(0) }; + static PROBES: Cell = const { Cell::new(0) }; + static TOUCH: Cell = const { Cell::new(false) }; + static RETAINED: Cell = const { Cell::new(false) }; + static FAIL_REGISTRATION: Cell = const { Cell::new(0) }; + static COMPLETED_REGISTRATION: Cell = const { Cell::new(0) }; + static ACTIVATED: Cell = const { Cell::new(false) }; + static ATTACH_ERROR: Cell = const { Cell::new(false) }; + static PROBE_ERROR: Cell = const { Cell::new(0) }; +} +struct Core<'a>(PhantomData<&'a ()>); +struct Device { data: Cell<*mut core::ffi::c_void> } +impl Device { + fn as_raw(&self) -> *mut Device { self as *const Device as *mut Device } + // SET_DRVDATA +} +mod bindings { + pub unsafe fn dev_set_drvdata(dev: *mut crate::Device, data: *mut core::ffi::c_void) { + unsafe { (*dev).data.set(data); } + } +} +struct Owned(Pin>); +impl Owned { + fn into_foreign(self) -> *mut T { + // Test ownership transfer mirrors the kernel's retained pinned KBox. + unsafe { Box::into_raw(Pin::into_inner_unchecked(self.0)) } + } +} +struct KBox; +impl KBox { + fn pin_init(init: impl PinInit, _flags: u32) -> Result> { + ALLOCS.with(|v| v.set(v.get() + 1)); + if FAIL_ALLOC.with(Cell::get) { return Err(-12); } + // Kernel KBox::try_pin_init has this same ordering. Allocation is the only + // mocked operation here; write_pin_init is the actual vendored implementation. + let slot = Box::::new_uninit(); + Ok(Owned(slot.write_pin_init(init)?)) + } +} +mod platform { + use super::*; + pub struct Device { pub base: super::Device, pub ctx: PhantomData } + // The fixture runs serially on one thread; this only permits a static probe target. + unsafe impl Sync for Device {} + pub struct Adapter(pub PhantomData); + impl AsRef for Device { + fn as_ref(&self) -> &super::Device { &self.base } + } + pub trait Driver { + type IdInfo; + type Data<'bound>; + fn probe<'bound>( + pdev: &'bound Device>, + info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit, Error> + 'bound; + } +} +struct Config { name: &'static str } +pub struct ThisModule; +pub trait ModuleMetadata { const NAME: &'static std::ffi::CStr; } +pub trait InPlaceModule: Sized { + fn init(module: &'static ThisModule) -> impl PinInit; +} +mod cleanup { + pub struct QueueOwner; + impl QueueOwner { pub fn new() -> crate::Result { Ok(Self) } } +} +mod driver { + use super::*; + #[pin_data] + pub struct Registration { stage: u8, marker: PhantomData } + impl Registration { + pub fn new(name: &'static std::ffi::CStr, _module: &'static ThisModule) -> impl PinInit { + try_pin_init!(Self { + stage: { + let stage = if name.to_bytes() == b"asahi-g15" { 1 } else { 2 }; + // Model driver_attach and a late driver_add_groups failure. A deferred + // worker can also retry G15 while the other registration is in progress. + let _ = callback::>(&PDEV, Some(&&CFG)); + if FAIL_REGISTRATION.get() == stage { return Err(-5); } + COMPLETED_REGISTRATION.set(stage); + stage + }, + marker: PhantomData, + }) + } + } + pub struct AsahiPlatformDriverData<'bound> { value: u8, bound: PhantomData<&'bound ()> } + pub struct AsahiPlatformDriver; + impl AsahiPlatformDriver { + pub fn probe_g15<'bound>( + _pdev: &'bound platform::Device>, _cfg: &'static Config, + ) -> Result> { + PROBES.with(|v| v.set(v.get() + 1)); + RETAINED.with(|v| v.set(TOUCH.with(Cell::get))); + match PROBE_ERROR.with(Cell::get) { + 0 => Ok(AsahiPlatformDriverData { value: 1, bound: PhantomData }), + e => Err(e), + } + } + } +} +mod boot { pub mod glue { + pub fn retained() -> bool { crate::RETAINED.with(core::cell::Cell::get) } + pub unsafe fn asahi_g15_reprobe() { crate::activation_reprobe(); } +}} +''' + +SUFFIX = r''' +fn callback<'bound, T: platform::Driver>( + pdev: &'bound platform::Device>, + info: Option<&'bound T::IdInfo>, +) -> Result { + // CALLBACK +} +fn reset(fail_alloc: bool, touch: bool, error: i32) { + MODULE_READY.store(true, Ordering::Release); + FAIL_ALLOC.set(fail_alloc); TOUCH.set(touch); PROBE_ERROR.set(error); + RETAINED.set(false); ALLOCS.set(0); PROBES.set(0); +} +static CFG: Config = Config { name: "test" }; +static PDEV: platform::Device> = platform::Device { + base: Device { data: Cell::new(core::ptr::null_mut()) }, ctx: PhantomData, +}; +fn activation_reprobe() { + assert_eq!(COMPLETED_REGISTRATION.get(), 2, "activation before all registrations completed"); + ACTIVATED.set(true); + let _ = callback::>(&PDEV, Some(&&CFG)); + // An attach pass may fail after another device starts. Its error is logged, not returned + // to module initialization. The actual helper's void signature is checked separately. + if ATTACH_ERROR.get() { println!("attach failure after probe was not propagated"); } +} +fn module_cases() { + static MODULE: ThisModule = ThisModule; + for failure in [1, 2, 0] { + reset(false, true, 0); + PDEV.base.data.set(core::ptr::null_mut()); + MODULE_READY.store(false, Ordering::Release); + COMPLETED_REGISTRATION.set(0); FAIL_REGISTRATION.set(failure); + ACTIVATED.set(false); ATTACH_ERROR.set(failure == 0); + let init = ::init(&MODULE); + assert_eq!(PROBES.get(), 0, "module initializer eagerly started firmware"); + let result = KBox::pin_init(init, GFP_KERNEL); + if failure != 0 { + assert!(result.is_err(), "late registration failure must fail module init"); + assert_eq!(PROBES.get(), 0, "late registration failure started firmware"); + assert!(!MODULE_READY.load(Ordering::Acquire)); + assert!(!ACTIVATED.get()); + } else { + assert!(result.is_ok(), "attach failure must not unwind a live session"); + assert_eq!(PROBES.get(), 1); + assert!(MODULE_READY.load(Ordering::Acquire)); + assert!(ACTIVATED.get()); + assert!(!PDEV.base.data.get().is_null()); + unsafe { drop(Box::from_raw(PDEV.base.data.get().cast::>())); } + } + println!("module-registration-{failure}: PASS"); + } +} +fn main() { + let cfg = &CFG; + for (name, allocation_fails, touched, error, expected, bound, calls) in [ + ("allocation-before-start", true, true, 0, Err(-12), false, 0), + ("allocation-before-retained-failure", true, true, -5, Err(-12), false, 0), + ("pre-start-failure", false, false, -19, Err(-19), false, 1), + ("retained-start-failure-binds", false, true, -5, Ok(0), true, 1), + ("retained-registration-failure-binds", false, true, -12, Ok(0), true, 1), + ("successful-registration-binds", false, true, 0, Ok(0), true, 1), + ] { + reset(allocation_fails, touched, error); + let pdev = platform::Device { base: Device { data: Cell::new(core::ptr::null_mut()) }, ctx: PhantomData }; + let result = callback::>(&pdev, Some(&cfg)); + assert_eq!(result, expected, "{name}: callback result"); + assert_eq!(PROBES.get(), calls, "{name}: firmware probe before drvdata allocation"); + assert_eq!(ALLOCS.get(), 1, "{name}: driver-data allocations"); + assert_eq!(!pdev.base.data.get().is_null(), bound, "{name}: bound data"); + if bound { + // Fake kernel teardown after asserting installation. Production suppresses manual unbind. + let data = unsafe { Box::from_raw(pdev.base.data.get().cast::>()) }; + assert_eq!(data._driver.is_some(), error == 0, "{name}: retained failure state"); + } + println!("{name}: PASS"); + } + module_cases(); +} +''' + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--kernel-build", type=Path, help="Use this existing host proc macro instead of compiling vendored host dependencies") + p.add_argument("--output", type=Path) + p.add_argument("--mutations", action="store_true") + p.add_argument("--rustc", default=os.environ.get("HOSTRUSTC", "rustc")) + a = p.parse_args() + out = (a.output or Path(tempfile.mkdtemp(prefix="g15-probe-init-"))).resolve() + out.mkdir(parents=True, exist_ok=True) + if a.kernel_build is None: + a.kernel_build = out / "host-deps" + dependencies = a.kernel_build / "rust" + dependencies.mkdir(parents=True, exist_ok=True) + crates = [ + ("proc_macro2", "rust/proc-macro2/lib.rs", "2021", [], + ['feature="proc-macro"', "wrap_proc_macro", "proc_macro_span_file", "proc_macro_span_location"]), + ("quote", "rust/quote/lib.rs", "2018", ["proc_macro2"], ['feature="proc-macro"']), + ("syn", "rust/syn/lib.rs", "2021", ["proc_macro2", "quote"], + ['feature="' + feature + '"' for feature in ["clone-impls", "derive", "full", "parsing", "printing", "proc-macro", "visit", "visit-mut"]]), + ("pin_init_internal", "rust/pin-init/internal/src/lib.rs", "2021", ["proc_macro2", "quote", "syn"], + ["kernel", "USE_RUSTC_FEATURES"]), + ] + commands = [] + for name, path, edition, external, cfgs in crates: + macro_crate = name == "pin_init_internal" + output = dependencies / ("lib" + name + (".so" if macro_crate else ".rlib")) + command = [a.rustc, "--edition=" + edition, "--crate-name=" + name, + "--crate-type=" + ("proc-macro" if macro_crate else "rlib"), + "--cap-lints=allow", str(ROOT / path), "-L", "dependency=" + str(dependencies), "-o", str(output)] + if macro_crate: + command += ["--extern", "proc_macro"] + for dependency in external: + command += ["--extern", dependency + "=" + str(dependencies / ("lib" + dependency + ".rlib"))] + for cfg in cfgs: + command += ["--cfg", cfg] + commands.append(command) + built = subprocess.run(command, capture_output=True, text=True) + (out / (name + "-build.log")).write_text(built.stdout + built.stderr) + if built.returncode: + raise RuntimeError("vendored host dependency failed: " + name + "\n" + built.stderr) + (out / "host-dependency-commands.json").write_text(json.dumps(commands, indent=2) + "\n") + sources = {name: (ROOT / name).read_text() for name in [PROBE_PATH, "rust/kernel/platform.rs", "rust/kernel/device.rs", "rust/kernel/init.rs", "rust/kernel/alloc/kbox.rs", "drivers/gpu/drm/asahi/asahi_core.rs", "drivers/gpu/drm/asahi/g15/glue.c"]} + probe = item(sources[PROBE_PATH], " fn probe<'bound>(") + driver = item(sources[PROBE_PATH], "#[pin_data]\npub(crate) struct Driver<'bound>").replace("pub(crate) ", "") + macro = item(sources["rust/kernel/init.rs"], "macro_rules! try_pin_init") + set_data = item(sources["rust/kernel/device.rs"], " pub fn set_drvdata") + callback = sources["rust/kernel/platform.rs"] + callback = callback[callback.index(" let data = T::probe(pdev, info);"):] + callback = callback[:callback.index(" Ok(0)") + len(" Ok(0)")] + ready = "static MODULE_READY: AtomicBool = AtomicBool::new(false);" + assert ready in sources[PROBE_PATH] + activate = item(sources[PROBE_PATH], "pub(crate) fn activate()") + core = sources["drivers/gpu/drm/asahi/asahi_core.rs"] + module_struct = item(core, "#[pin_data]\nstruct DriverModule") + module_init = item(core, " fn init(module:") + module_code = module_struct + "\nimpl InPlaceModule for DriverModule {\n" + module_init + "\n}\nimpl ModuleMetadata for DriverModule { const NAME: &'static std::ffi::CStr = c\"asahi\"; }\n" + kbox = item(sources["rust/kernel/alloc/kbox.rs"], " fn try_pin_init(") + assert "Box::<_, A>::new_uninit(flags)?.write_pin_init(init)" in kbox + reprobe = item(sources["drivers/gpu/drm/asahi/g15/glue.c"], "void asahi_g15_reprobe(void)\n{") + c_prefix = r''' +#include +#include +#include +struct device_driver { int unused; }; +static struct device_driver driver; +static int platform_bus_type; +static bool present; +static int attach_result, finds, attaches, logs, started; +#define pr_err(...) ((void)++logs) +static const struct device_driver *driver_find(const char *name, const int *bus) { + (void)name; assert(bus == &platform_bus_type); finds++; + return present ? &driver : 0; +} +static int driver_attach(const struct device_driver *drv) { + assert(drv == &driver); attaches++; started++; return attach_result; +} +''' + c_suffix = r''' +int main(void) { + for (int test = 0; test < 3; test++) { + present = test != 0; attach_result = test == 2 ? -ENOMEM : 0; + finds = attaches = logs = started = 0; + asahi_g15_reprobe(); + assert(finds == 1); + assert(attaches == (test != 0)); + assert(started == (test != 0)); + assert(logs == (test == 0 || test == 2)); + } +} +''' + c_source = out / "actual-activation.c" + c_source.write_text(c_prefix + reprobe + c_suffix) + c_binary = out / "actual-activation" + subprocess.run([os.environ.get("HOSTCC", "cc"), "-std=c11", "-Wall", "-Wextra", "-Werror", str(c_source), "-o", str(c_binary)], check=True) + subprocess.run([str(c_binary)], check=True) + library = out / "libpin_init.rlib" + subprocess.run([a.rustc, "--edition=2021", "--crate-type=rlib", "--crate-name=pin_init", "--cfg", 'feature="std"', str(ROOT / "rust/pin-init/src/lib.rs"), "--extern", f"pin_init_internal={a.kernel_build / 'rust/libpin_init_internal.so'}", "-L", f"dependency={a.kernel_build / 'rust'}", "-o", str(library)], check=True) + receipt = {"rustc": subprocess.check_output([a.rustc, "--version"], text=True).strip(), "pin_init_source_sha256": {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() for p in (ROOT / "rust/pin-init").rglob("*.rs")}, "proc_macro_sha256": hashlib.sha256((a.kernel_build / "rust/libpin_init_internal.so").read_bytes()).hexdigest(), "source_sha256": {n: hashlib.sha256(s.encode()).hexdigest() for n, s in sources.items()}, "cases": 9, "actual_C_activation_cases": 3, "mutants": {}, "scope": __doc__} + variants = {"actual": (probe, module_code)} + if a.mutations: + try: + old = subprocess.check_output(["git", "show", f"{OLD_REF}:{PROBE_PATH}"], cwd=ROOT, text=True, stderr=subprocess.DEVNULL) + assert item(old, " fn probe<'bound>(") == OLD_PROBE + receipt["old_reference_checked_against_git"] = True + except subprocess.CalledProcessError: + receipt["old_reference_checked_against_git"] = False + variants["eager-probe-before-allocation"] = (OLD_PROBE, module_code) + needle = " None\n" + assert probe.count(needle) == 1 + variants["retained-error-unbinds"] = (probe.replace(needle, " return Err(error);\n"), module_code) + gate = " if !MODULE_READY.load(Ordering::Acquire) {\n return Err(EPROBE_DEFER);\n }\n" + assert probe.count(gate) == 1 + variants["no-registration-readiness-gate"] = (probe.replace(gate, ""), module_code) + late = " #[cfg(CONFIG_DRM_ASAHI_G15)]\n _g15_ready: g15::activate(),\n" + assert module_code.count(late) == 1 + early = module_code.replace(late, "").replace(" _driver <-", late + " _driver <-", 1) + variants["activation-before-last-registration"] = (probe, early) + for name, (method, module_variant) in variants.items(): + # Macro definitions precede the fake registration, just as kernel prelude exports them. + source = macro + "\n" + PREFIX.replace("#![allow(dead_code, unused_variables)]\n", "").replace(" // SET_DRVDATA", set_data) + "\n" + ready + "\n" + driver + "\nimpl platform::Driver for Driver<'_> {\n type IdInfo = &'static Config;\n type Data<'bound> = Driver<'bound>;\n" + method + "\n}\nmod g15 { use super::*; pub type Driver<'a> = super::Driver<'a>; " + activate + "\n}\ntype G15Registration = driver::Registration>>;\n" + module_variant + "\n" + SUFFIX.replace(" // CALLBACK", callback) + source = "#![allow(dead_code, unused_variables, private_bounds, private_interfaces)]\n" + source + src = out / (name + ".rs"); src.write_text(source) + binary = out / name + subprocess.run([a.rustc, "--edition=2021", "--cfg", "CONFIG_DRM_ASAHI_G15", str(src), "--extern", f"pin_init={library}", "-L", f"dependency={a.kernel_build / 'rust'}", "-o", str(binary)], check=True) + r = subprocess.run([str(binary)], capture_output=True, text=True) + receipt["mutants" if name != "actual" else "control"] = receipt.get("mutants" if name != "actual" else "control", {}) + result = {"exit": r.returncode, "stdout": r.stdout, "stderr": r.stderr} + if name == "actual": + receipt["control"] = result + if r.returncode: raise SystemExit(r.stderr) + if r.stdout.count(": PASS\n") != 9: raise SystemExit("control did not run every case") + else: + receipt["mutants"][name] = result + if r.returncode == 0: raise SystemExit("SURVIVED: " + name) + intended = {"eager-probe-before-allocation": "allocation-before-start: firmware probe before drvdata allocation", "retained-error-unbinds": "retained-start-failure-binds: callback result", "no-registration-readiness-gate": "late registration failure started firmware", "activation-before-last-registration": "activation before all registrations completed"}[name] + result["intended_failure"] = intended in r.stderr + if not result["intended_failure"]: raise SystemExit("INVALID unrelated failure: " + name + "\n" + r.stderr) + (out / "result.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps(receipt, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/g15-queue-credit-tests.py b/tools/asahi/g15-queue-credit-tests.py new file mode 100644 index 00000000000000..2c8d7f64fb3f33 --- /dev/null +++ b/tools/asahi/g15-queue-credit-tests.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run actual native logical-queue credit/new/drop bodies on host services. + +Scheduler/VM/allocation services are models. This tests host capacity and Rust +field-drop ordering, not hardware execution-state reservation or DRM scheduling. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[2] + + +def extract(text, marker): + start = text.index(marker); opening = text.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return text[start:end] + + +CODE = r''' +#![allow(dead_code)] +use std::{sync::{Arc as StdArc,Mutex,Barrier,OnceLock,atomic::{AtomicBool,AtomicI32,AtomicU32,AtomicU64,Ordering}},ops::Deref,cell::Cell}; +#[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); +type Result = std::result::Result; +const EIO:Error=Error(-5);const EINVAL:Error=Error(-22);const ENOMEM:Error=Error(-12);const GFP_KERNEL:()=(); +thread_local!{static FAIL:Cell=const{Cell::new(0)};static RACE_FIRST:Cell=const{Cell::new(false)};} +static RACE_GATE:OnceLock=OnceLock::new(); +trait RacyCounter{fn racy_reserve(&self)->std::result::Result;} +impl RacyCounter for StdArc{fn racy_reserve(&self)->std::result::Result{ + let count=self.load(Ordering::Acquire); + RACE_FIRST.with(|flag|if flag.replace(false){RACE_GATE.get_or_init(||Barrier::new(16)).wait();}); + if countbool{FAIL.with(|f|f.get()==n)} +struct Arc(StdArc);impl Clone for Arc{fn clone(&self)->Self{Self(self.0.clone())}} +impl Deref for Arc{type Target=T;fn deref(&self)->&T{&self.0}} +impl Arc{fn wrap(v:T)->Self{Self(StdArc::new(v))}fn new(v:T,_:())->Result{if failure(4){Err(ENOMEM)}else{Ok(Self::wrap(v))}}} +struct KBox(Box);implKBox{fn new(v:T,_:())->Result{if failure(5){Err(ENOMEM)}else{Ok(Self(Box::new(v)))}}} +struct Trace{counter:StdArc,drains:Mutex>,prunes:AtomicU32} +struct Device{trace:StdArc} +struct Shared{logical_queues:StdArc,crashed:AtomicBool,dev:Device} +struct Status(AtomicI32);impl Status{fn get(&self)->i32{self.0.load(Ordering::SeqCst)}} +struct VmState{status:Status,trace:StdArc}impl VmState{fn prune_registry(&self){self.trace.prunes.fetch_add(1,Ordering::SeqCst);}} +mod mmu{use super::*;pub struct Vm{pub state:Arc}} +mod vm{use super::*;pub fn lookup(_:&Gpu,vm:&mmu::Vm)->Result>{if failure(1){Err(ENOMEM)}else{Ok(vm.state.clone())}}} +mod hw{pub const USER_RANGE:std::ops::Range=0x100000000..0x2000000000;pub mod sizes{__LIMIT__}} +mod uapi{pub const drm_asahi_priority_DRM_ASAHI_PRIORITY_REALTIME:u32=3;} +const USC_WINDOW:u64=0x100000000; +struct Gpu{shared:Arc} +struct Scheduler{trace:StdArc} +impl Scheduler{fn new(dev:&Device)->Result{if failure(3){Err(ENOMEM)}else{Ok(Self{trace:dev.trace.clone()})}}} +impl Drop for Scheduler{fn drop(&mut self){let n=self.trace.counter.load(Ordering::SeqCst);assert!(n>0,"scheduler must drain before credit release");self.trace.drains.lock().unwrap().push(n);}} +struct Timeline;impl Timeline{fn new()->Result>{if failure(2){Err(ENOMEM)}else{Ok(Arc::wrap(Self))}}} +__STATE__ +__CREDIT__ +__CREDIT_IMPL__ +__CREDIT_DROP__ +__QUEUE__ +__QUEUE_DROP__ +impl Queue{__NEW__} +fn setup()->Gpu{ + let counter=StdArc::new(AtomicU32::new(0));let trace=StdArc::new(Trace{counter:counter.clone(),drains:Mutex::new(Vec::new()),prunes:AtomicU32::new(0)}); + Gpu{shared:Arc::wrap(Shared{logical_queues:counter,crashed:AtomicBool::new(false),dev:Device{trace}})} +} +fn vm(gpu:&Gpu,status:i32)->mmu::Vm{mmu::Vm{state:Arc::wrap(VmState{status:Status(AtomicI32::new(status)),trace:gpu.shared.dev.trace.clone()})}} +fn new(gpu:&Gpu,status:i32,priority:u32,base:u64)->Result>{KBox::new(Queue::new(gpu,vm(gpu,status),priority,base)?,GFP_KERNEL)} +fn count(gpu:&Gpu)->u32{gpu.shared.logical_queues.load(Ordering::SeqCst)} +fn main(){ + // One device shared across different VM objects/files: exactly58 live queues. + let gpu=setup();let mut queues=Vec::new();for _ in 0..hw::sizes::MAX_QUEUES{queues.push(new(&gpu,0,2,0x100000000).expect("live logical queue below cap"));} + assert_eq!(count(&gpu),58,"reported logical capacity must be reserved"); + assert!(matches!(new(&gpu,0,2,0x100000000),Err(ENOMEM)),"59th device queue must refuse"); + assert_eq!(count(&gpu),58);drop(queues); + assert_eq!(count(&gpu),0,"release returns all logical credits"); + assert_eq!(*gpu.shared.dev.trace.drains.lock().unwrap(),(1..=58).rev().collect::>(),"every scheduler drains before its capacity returns"); + assert!(new(&gpu,0,2,0x100000000).is_ok(),"capacity reusable after drain"); + assert_eq!(count(&gpu),0); + // Failure at lookup/timeline/scheduler/state/outerKBox must never leak a credit. + for point in 1..=5{ + let gpu=setup();FAIL.with(|f|f.set(point));assert!(new(&gpu,0,2,0x100000000).is_err());FAIL.with(|f|f.set(0)); + assert_eq!(count(&gpu),0,"allocation failure must return logical credit"); + let drains=gpu.shared.dev.trace.drains.lock().unwrap().clone(); + assert_eq!(drains,if point>=4{vec![1]}else{vec![]},"allocation rollback drains before credit release"); + let retry=new(&gpu,0,2,0x100000000).expect("allocation failure must leave reusable capacity");assert_eq!(count(&gpu),1);drop(retry);assert_eq!(count(&gpu),0); + } + // Existing GPU/VM/range refusals do not consume capacity. + for (status,priority,base) in [(-5,2,0x100000000),(0,4,0x100000000),(0,2,1),(0,2,0x2000000000)]{ + let gpu=setup();assert!(new(&gpu,status,priority,base).is_err());assert_eq!(count(&gpu),0); + } + let gpu=setup();gpu.shared.crashed.store(true,Ordering::SeqCst);assert!(new(&gpu,0,2,0x100000000).is_err());assert_eq!(count(&gpu),0); + // CAS contention:128 acquisitions across16threads, held until all have attempted. + let gpu=setup();let ready=StdArc::new(Barrier::new(17));let release=StdArc::new(Barrier::new(17));let successes=StdArc::new(AtomicU32::new(0));let mut threads=Vec::new(); + for _ in 0..16{let shared=gpu.shared.clone();let ready=ready.clone();let release=release.clone();let successes=successes.clone();threads.push(std::thread::spawn(move||{ + RACE_FIRST.with(|flag|flag.set(true));let mut held=Vec::new();for _ in 0..8{if let Ok(credit)=QueueCredit::acquire(&shared){successes.fetch_add(1,Ordering::SeqCst);held.push(credit);}} + ready.wait();release.wait();drop(held); + }));} + ready.wait();assert_eq!(successes.load(Ordering::SeqCst),58,"concurrent reservations respect shared cap");assert_eq!(count(&gpu),58,"concurrent reservations respect shared cap");release.wait();for t in threads{t.join().unwrap();}assert_eq!(count(&gpu),0,"concurrent releases return capacity"); + // An already-corrupt/saturated counter must not wrap into an admitted credit. + gpu.shared.logical_queues.store(u32::MAX,Ordering::SeqCst);assert!(matches!(QueueCredit::acquire(&gpu.shared),Err(ENOMEM)));assert_eq!(count(&gpu),u32::MAX); + println!("PASS actual Queue::new/field order/credit:58/59,5 allocation failures,admission negatives,16-thread CAS and saturation"); +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mutations", action="store_true") + args = parser.parse_args(); args.output.mkdir(parents=True, exist_ok=True) + queue = (ROOT / "drivers/gpu/drm/asahi/g15/queue.rs").read_text() + hardware = (ROOT / "drivers/gpu/drm/asahi/g15/hw.rs").read_text() + limit = next(line.strip() for line in hardware.splitlines() if "const MAX_QUEUES:" in line) + replacements = {"__LIMIT__": limit, "__STATE__": extract(queue, "pub(crate) struct QueueState {"), + "__CREDIT__": extract(queue, "struct QueueCredit {"), "__CREDIT_IMPL__": extract(queue, "impl QueueCredit {"), + "__CREDIT_DROP__": extract(queue, "impl Drop for QueueCredit {"), "__QUEUE__": extract(queue, "pub(crate) struct Queue {"), + "__QUEUE_DROP__": extract(queue, "impl Drop for Queue {"), "__NEW__": extract(queue, " pub(crate) fn new(gpu: &Gpu,")} + code = CODE + for old, new in replacements.items(): code = code.replace(old, new) + variants = {"control": code}; expected = {} + if args.mutations: + changes = { + "cap-not-enforced": ("count < hw::sizes::MAX_QUEUES", "count < u32::MAX", "59th device queue must refuse"), + "counter-not-reserved": ("then(|| count + 1)", "then(|| count)", "reported logical capacity must be reserved"), + "credit-not-released": ("let previous = self.shared.logical_queues.fetch_sub(1, Ordering::AcqRel);\n debug_assert!(previous != 0);", "let _ = &self.shared;", "release returns all logical credits"), + "release-before-drain": ("pub(crate) struct Queue {\n", "pub(crate) struct Queue {\n _credit: QueueCredit,\n", "scheduler must drain before credit release"), + "nonatomic-reservation": (".fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| {\n (count < hw::sizes::MAX_QUEUES).then(|| count + 1)\n })", ".racy_reserve()", "concurrent reservations respect shared cap"), + "advertised-cap-off-by-one": ("count < hw::sizes::MAX_QUEUES", "count <= hw::sizes::MAX_QUEUES", "59th device queue must refuse"), + } + for name, (old, new, message) in changes.items(): + if code.count(old) != 1: raise RuntimeError(f"{name}: mutation anchor count {code.count(old)}") + variant = code.replace(old, new) + if name == "release-before-drain": + old_tail = " // Last field: all preceding fields (especially scheduler) drop before capacity returns.\n _credit: QueueCredit,\n" + if variant.count(old_tail) != 1: raise RuntimeError("missing tail credit") + variant = variant.replace(old_tail, "") + variants[name] = variant; expected[name] = message + variants["control-after"] = code + receipt = {"scope": __doc__, "sources": {"queue.rs": hashlib.sha256(queue.encode()).hexdigest(), + "hw.rs": hashlib.sha256(hardware.encode()).hexdigest()}, "variants": {}} + for name, source in variants.items(): + path=args.output/(name+".rs");path.write_text(source);binary=args.output/name + built=subprocess.run([os.environ.get("RUSTC","rustc"),"--edition=2021",str(path),"-o",str(binary)],capture_output=True,text=True) + (args.output/(name+".build.log")).write_text(built.stdout+built.stderr) + if built.returncode: raise RuntimeError(f"{name}: NOBUILD, not a runtime kill: {built.stderr}") + ran=subprocess.run([str(binary.resolve())],capture_output=True,text=True,timeout=30) + receipt["variants"][name]={"exit":ran.returncode,"stdout":ran.stdout,"stderr":ran.stderr,"intended_failure":name in expected and expected[name] in ran.stderr} + if name.startswith("control") and ran.returncode:raise RuntimeError(ran.stdout+ran.stderr) + if name in expected and (ran.returncode==0 or expected[name] not in ran.stderr):raise RuntimeError(f"{name}: wrong runtime failure: {ran.stderr}") + (args.output/"result.json").write_text(json.dumps(receipt,indent=2)+"\n");print(json.dumps(receipt,indent=2)) + + +if __name__ == "__main__": main() diff --git a/tools/asahi/g15-retention-tests.py b/tools/asahi/g15-retention-tests.py new file mode 100644 index 00000000000000..4812a32b0b1e3e --- /dev/null +++ b/tools/asahi/g15-retention-tests.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run actual G15 retention/backend/boot-completion bodies with drop-count fault injection. + +Allocators, firmware objects and hardware operations are host models. Production +ownership transfers and error handling are extracted unchanged. No firmware or +device is accessed. Mutants must build and fail an intended runtime assertion. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +G15 = ROOT / "drivers/gpu/drm/asahi/g15" +CONTROL_REF = "31da169251bd34d5810a0874563d9a019b85bf56" + + +def item(text, marker): + start = text.index(marker) + end = text.index("{", start) + 1 + depth = 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return text[start:end] + + +PREFIX = r''' +#![allow(dead_code, unused_variables)] +use std::{cell::{Cell, RefCell, RefMut}, mem::MaybeUninit, ops::{Deref, DerefMut}, + sync::{Arc, atomic::{AtomicBool, Ordering}}}; +type Error = i32; +type Result = std::result::Result; +const GFP_KERNEL: u32 = 0; +const EINVAL: Error = -22; +macro_rules! dev_info { ($($args:tt)*) => {{}}; } +macro_rules! dev_err { ($($args:tt)*) => {{}}; } +thread_local! { + static FAIL: Cell = const { Cell::new(0) }; + static OWNER_DROPS: Cell = const { Cell::new(0) }; + static BUFFER_DROPS: Cell = const { Cell::new(0) }; +} +fn step(site: u32) -> Result { + if FAIL.get() & (1 << site) != 0 { Err(-100 - site as i32) } else { Ok(()) } +} +struct Owner; +impl Drop for Owner { fn drop(&mut self) { OWNER_DROPS.set(OWNER_DROPS.get() + 1); } } +struct Buffer; +impl Drop for Buffer { fn drop(&mut self) { BUFFER_DROPS.set(BUFFER_DROPS.get() + 1); } } +struct Mutex(RefCell); +impl Mutex { + fn new(value: T) -> Self { Self(RefCell::new(value)) } + fn lock(&self) -> RefMut<'_, T> { self.0.borrow_mut() } +} +struct KBox(Box); +impl KBox { + fn new_uninit(_flags: u32) -> Result>> { + step(if std::any::type_name::().ends_with("Orphan") { 7 } else { 5 })?; + Ok(KBox(Box::new_uninit())) + } + // KBOX_NEW + fn into_inner(value: Self) -> T { *value.0 } +} +impl KBox> { + fn write(storage: Self, value: T) -> KBox { KBox(Box::write(storage.0, value)) } +} +impl Deref for KBox { type Target = T; fn deref(&self) -> &T { &self.0 } } +impl DerefMut for KBox { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } +struct AsahiDevice; +impl AsahiDevice { fn as_ref(&self) -> &Self { self } } +struct Config; +static CONFIG: Config = Config; +mod mmu { pub struct Uat; } +mod regs { + pub struct Identity; + pub struct Regs; + pub const ASC_RUN: u32 = 1; + impl Regs { pub fn set_asc_control(&self, _: u32) -> super::Result { super::step(11) } } +} +mod object { + use super::*; + pub struct Objects { _owner: Owner, retained: Vec> } + impl Objects { + pub fn new() -> Self { Self { _owner: Owner, retained: vec![] } } + pub fn buffer(&mut self) -> Arc { + let buffer = Arc::new(Buffer); self.retained.push(buffer.clone()); buffer + } + } +} +mod initdata { pub struct InitData(pub super::Owner); } +mod channel { pub struct Channels(pub super::Owner); } +mod event { + pub struct Events(pub super::Owner); + impl Events { + pub fn new() -> Self { Self(super::Owner) } + pub fn reserve(&mut self) -> super::Result { super::step(12) } + } +} +mod graph { + use super::*; + pub struct Graphs(Arc); + impl Graphs { + pub fn new(_: &AsahiDevice, objects: &mut object::Objects) -> Result { + let buffer = objects.buffer(); step(1)?; Ok(Self(buffer)) + } + } +} +mod slots { + use super::*; + pub struct Slots(Arc); + impl Slots { + pub fn new(objects: &mut object::Objects) -> Result { + let buffer = objects.buffer(); step(2)?; Ok(Self(buffer)) + } + } +} +mod pools { + use super::*; + pub struct Pools(Arc); + impl Pools { + pub fn new(_: &AsahiDevice, objects: &mut object::Objects) -> Result { + let buffer = objects.buffer(); step(3)?; Ok(Self(buffer)) + } + } +} +mod vm { + use super::*; + pub struct Registry; + impl Registry { pub fn new() -> Result> { step(4)?; Ok(Arc::new(Self)) } } +} +mod engine { pub struct Engine; impl Engine { pub fn new() -> Self { Self } } } +mod recovery { pub struct Recovery; impl Recovery { pub fn new() -> Self { Self } } } +struct Shared { + dev: AsahiDevice, + orphan: Mutex>>, + orphaned: AtomicBool, +} +impl Shared { + fn new() -> Arc { + Arc::new(Self { dev: AsahiDevice, orphan: Mutex::new(None), orphaned: AtomicBool::new(false) }) + } + // ORPHAN +} +// FIRMWARE +impl Firmware { + fn init_graphs(&mut self) -> Result { step(6) } + // BACKEND +} +mod boot { + use super::*; + use super::{object::Objects, initdata::InitData, channel::Channels, event::Events}; + pub struct Session { _owner: Owner, uat: Arc, regs: regs::Regs } + impl Session { + pub fn new() -> Self { Self { _owner: Owner, uat: Arc::new(mmu::Uat), regs: regs::Regs } } + // UAT + } + // BOOTED + // ORPHAN_STRUCT + fn run(_: &mut Session, _: &Config, _: &mut Objects, _: &mut Events, + built: &mut Option<(InitData, Channels, u32)>, _: ()) -> Result { + step(8)?; + *built = Some((InitData(Owner), Channels(Owner), 1234)); + step(9) + } + pub fn start(shared: &Arc) -> Result { + let mut session = Session::new(); + let mut objects = Objects::new(); + let d = AsahiDevice; + let cfg = &CONFIG; + let control = 0; + let id = regs::Identity; + let board_images = (); + // START_TAIL +} +fn booted() -> boot::Booted { + boot::Booted { session: boot::Session::new(), init: initdata::InitData(Owner), + objects: object::Objects::new(), channels: channel::Channels(Owner), + events: event::Events::new(), id: regs::Identity, max_frequency_khz: 1234 } +} +fn orphan() -> boot::Orphan { + let boot::Booted { session, init, objects, channels, events, .. } = booted(); + boot::Orphan { session, _objects: objects, channels: Some(channels), _init: Some(init), events } +} +fn reset(fail: u32) { FAIL.set(fail); OWNER_DROPS.set(0); BUFFER_DROPS.set(0); } +fn retained(label: &str) { + assert_eq!(OWNER_DROPS.get(), 0, "{label}: live session owner dropped"); + assert_eq!(BUFFER_DROPS.get(), 0, "{label}: firmware buffer dropped"); +} +fn main() { + for oom in [false, true] { + reset(if oom { 1 << 7 } else { 0 }); + let shared = Shared::new(); shared.orphan(orphan()); + retained("orphan allocation"); + assert_eq!(shared.orphaned.load(Ordering::Acquire), !oom); + assert_eq!(shared.orphan.lock().is_some(), !oom); + std::mem::forget(shared); + } + for site in 1..=6 { + for orphan_oom in [false, true] { + reset((1 << site) | if orphan_oom { 1 << 7 } else { 0 }); + let shared = Shared::new(); + let result = Firmware::start_backend(&AsahiDevice, &CONFIG, booted(), &shared); + assert!(matches!(result, Err(e) if e == -100 - site as i32), "backend error changed"); + retained("backend failure"); + assert_eq!(shared.orphan.lock().is_some(), !orphan_oom); + std::mem::forget(shared); + } + } + for site in [8, 9, 11, 12] { + for orphan_oom in [false, true] { + reset((1 << site) | if orphan_oom { 1 << 7 } else { 0 }); + let shared = Shared::new(); let result = boot::start(&shared); + let expected = -100 - site as i32; + assert!(matches!(result, Err(e) if e == expected), "boot error changed"); + retained("boot completion"); + assert_eq!(shared.orphan.lock().is_some(), !orphan_oom); + std::mem::forget(shared); + } + } + reset(0); + let shared = Shared::new(); + let booted = boot::start(&shared).expect("normal boot"); + assert_eq!(booted.max_frequency_khz, 1234); + let uat: Arc = booted.session.uat(); + let firmware = Firmware::start_backend(&AsahiDevice, &CONFIG, booted, &shared).expect("normal backend"); + assert!(Arc::ptr_eq(&uat, &firmware.session.uat())); + assert!(!shared.orphaned.load(Ordering::Acquire)); + retained("normal success"); + std::mem::forget((shared, firmware)); + println!("PASS 23 retention cases: orphan OOM, six backend failure sites, four boot-completion sites and normal success"); + println!("normal success owner_drops={} buffer_drops={}", OWNER_DROPS.get(), BUFFER_DROPS.get()); +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path) + parser.add_argument("--mutations", action="store_true") + args = parser.parse_args() + out = (args.output or Path(tempfile.mkdtemp(prefix="g15-retention-"))).resolve() + out.mkdir(parents=True, exist_ok=True) + mod = (G15 / "mod.rs").read_text() + boot = (G15 / "boot.rs").read_text() + kbox = (ROOT / "rust/kernel/alloc/kbox.rs").read_text() + orphan = item(mod, " pub(crate) fn orphan(") + backend = item(mod, " fn start_backend(") + start = item(boot, "pub(crate) fn start(") + tail = start[start.index(" let mut events = Events::new();"):] + source = PREFIX.replace(" // ORPHAN\n", orphan + "\n") + allocator_new = item(kbox, " pub fn new(x: T, flags: Flags)") + allocator_new = allocator_new.replace("pub fn new(x: T, flags: Flags) -> Result", + "fn new(x: T, flags: u32) -> Result") + source = source.replace(" // KBOX_NEW", allocator_new.replace("Box::write", "KBox::write")) + source = source.replace("// FIRMWARE", item(mod, "pub(crate) struct Firmware")) + source = source.replace(" // BACKEND", backend) + source = source.replace(" // UAT", item(boot, " pub(crate) fn uat(")) + source = source.replace(" // BOOTED", item(boot, "pub(crate) struct Booted")) + source = source.replace(" // ORPHAN_STRUCT", item(boot, "pub(crate) struct Orphan")) + source = source.replace(" // START_TAIL", tail) + variants = {"actual": source} + if args.mutations: + old = subprocess.check_output( + ["git", "show", CONTROL_REF + ":drivers/gpu/drm/asahi/g15/mod.rs"], + cwd=ROOT, text=True) + variants["consume-orphan-before-allocation"] = source.replace(orphan, item(old, " pub(crate) fn orphan(")) + variants["unguarded-registry-allocation"] = source.replace(backend, item(old, " fn start_backend(")) + receipt = {"scope": __doc__, "sources": { + name: hashlib.sha256(text.encode()).hexdigest() + for name, text in [("mod.rs", mod), ("boot.rs", boot), ("kbox.rs", kbox)]}, + "rustc": subprocess.check_output([os.environ.get("HOSTRUSTC", "rustc"), "--version"], text=True).strip(), + "cases": 23, "public_old_source_control": CONTROL_REF, "variants": {}} + for name, text in variants.items(): + if name != "actual" and text == source: + raise RuntimeError("NOT_APPLIED " + name) + path = out / (name + ".rs") + path.write_text(text) + binary = out / name + subprocess.run([os.environ.get("HOSTRUSTC", "rustc"), "--edition=2021", + str(path), "-o", str(binary)], check=True) + result = subprocess.run([str(binary)], capture_output=True, text=True) + receipt["variants"][name] = {"exit": result.returncode, "stdout": result.stdout, + "stderr": result.stderr} + if name == "actual": + if result.returncode: + raise RuntimeError(result.stderr) + else: + expected = {"consume-orphan-before-allocation": "orphan allocation: live session owner dropped", + "unguarded-registry-allocation": "backend failure: live session owner dropped"}[name] + if result.returncode == 0 or expected not in result.stderr or "left: 5" not in result.stderr: + raise RuntimeError("INVALID mutant outcome " + name + "\n" + result.stderr) + receipt["variants"][name]["intended_owner_drops"] = 5 + after = subprocess.run([str(out / "actual")], capture_output=True, text=True, check=True) + receipt["actual_after_mutants"] = {"exit": after.returncode, "stdout": after.stdout, "stderr": after.stderr} + receipt["fixed_invariants"] = {"live_session_owner_drops": 0, "firmware_buffer_drops": 0, + "checked_cases": 23} + (out / "result.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps(receipt, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/g15-stats-drain-tests.py b/tools/asahi/g15-stats-drain-tests.py new file mode 100644 index 00000000000000..2bd9cc2cacd0be --- /dev/null +++ b/tools/asahi/g15-stats-drain-tests.py @@ -0,0 +1,459 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G15 receive-ring drain's actual bodies, before and after the stats ring is noted. + +The harness extracts Channels::drain_one(), note_stats(), peek_stats() and drain_rings() from +drivers/gpu/drm/asahi/g15/channel.rs, and power/pstate.rs whole. It runs them against a +model of the firmware objects that logs every load, store and barrier in order. The reference is +drain_rings() as of 9f09c85f8d3b, before the stats ring was noted. It is embedded below, because +a shallow checkout lacks that commit, and checked against git when the commit is present. + +What it shows, for the stats ring and the event, log and trace rings drained beside it: +- every (consumer, producer) pair, both inside and outside the 256-slot ring, gives the same + stores the firmware sees (offsets, values, order, write barriers) and the same final state; +- the producer is loaded before the consumer, as before. Inside the ring the consumer is loaded + again before the store; outside the ring both are loaded again by the earlier drain_one(); +- with a producer that moves between loads, the consumer store is the earlier drain's for the + producer loaded by the same code; +- the noted records: the pending slots in ring order (wrap, empty, full), the tag at +0 and the + word at +0x20, read after a read barrier, the newest power-state record winning; +- a full barrier after the last record load and before the consumer store that frees the slots; +- peek_stats() stores nothing. + +Not shown: kernel, firmware or GPU execution, nor timing. The noting drain loads up to 510 more +record words, so it takes longer than the earlier drain. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import resource +import subprocess + +ROOT = Path(__file__).resolve().parents[2] +G15 = "drivers/gpu/drm/asahi/g15" +CHANNEL = f"{G15}/channel.rs" +PSTATE = f"{G15}/power/pstate.rs" +HW = f"{G15}/hw.rs" +FW_CHANNELS = f"{G15}/fw/channels.rs" +OLD_REF = "9f09c85f8d3bae8512712686f5a91067fc4eb3de" + +# drain_rings() at OLD_REF (the stats ring consumed unread), verbatim. +OLD_DRAIN_RINGS = ''' pub(crate) fn drain_rings(&self, dev: &kernel::device::Device, events: &mut Events) -> Result { + events.drain(dev, &self.event)?; + for i in 0..rings::LOG_RINGS { + Self::drain_one(&self.log, i * 0x30)?; + } + Self::drain_one(&self.trace, 0)?; + Self::drain_one(&self.stats, 0) + }''' + +MUTATIONS = { + # Store the consumer even when it already equals the producer. + 'unconditional-consume': (CHANNEL, 'if self.stats.read()? != producer {', 'if true {'), + # Leave the stats ring unconsumed when an index is out of the ring. + 'skip-fallback': (CHANNEL, ' Self::drain_one(&self.stats, 0)\n }', ' Ok(())\n }'), + # Store a producer loaded after the records were noted. + 'resample-producer': (CHANNEL, 'self.stats.state.w32(STATE_READ, producer)?', + 'self.stats.state.w32(STATE_READ, self.stats.state.r32(STATE_WRITE)?)?'), + # Store the consumer without the full barrier after the record loads. + 'no-release-barrier': (CHANNEL, ' mb();\n self.stats.state.w32(STATE_READ, producer)?;', + ' self.stats.state.w32(STATE_READ, producer)?;'), + # Read the records without the read barrier. + 'no-read-barrier': (CHANNEL, ' rmb();\n for slot in slots {', ' for slot in slots {'), + # Walk the slots without the wrap. + 'no-wrap': (PSTATE, '(read + i) % STATS_SLOTS', 'read + i'), + # Keep the oldest power-state record instead of the newest. + 'oldest-power-state': (PSTATE, 'if tag == TAG_POWER_STATE {', 'if tag == TAG_POWER_STATE && self.last.is_none() {'), +} + + +def item(text, start): + a = text.index(start) + b = text.index("{", a) + 1 + depth = 1 + while depth: + depth += (text[b] == "{") - (text[b] == "}") + b += 1 + return text[a:b] + + +def const(text, name): + m = re.search(rf'pub\(crate\) const {name}: (\w+) = ([^;]+);', text) + if not m: + raise SystemExit(f'{name} not found') + return f'pub const {name}: {m.group(1)} = {m.group(2)};' + + +PREFIX = r''' +#![allow(dead_code, unused_imports)] +use std::{cell::RefCell, sync::Arc}; +type Result = std::result::Result; +const EINVAL: i32 = -22; +mod kernel { pub mod device { pub struct Device; } } +mod power { + #[path = "PSTATE_PATH"] + pub mod pstate; +} +use power::pstate::{self, StatsSeen}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Ev { Load(u8, usize, u32), Store(u8, usize, u32), Rmb, Mb, Wmb, Events } +thread_local! { static LOG: RefCell> = RefCell::new(Vec::new()); } +fn log(e: Ev) { LOG.with(|l| l.borrow_mut().push(e)); } +fn take_log() -> Vec { LOG.with(|l| std::mem::take(&mut *l.borrow_mut())) } +fn wmb() { log(Ev::Wmb); } +fn rmb() { log(Ev::Rmb); } +fn mb() { log(Ev::Mb); } + +/// A firmware object: little-endian bytes, bounds-checked like FwObject's ptr(). A word the +/// firmware writes (a producer) is given as successive values, one per load; the last repeats. +struct FwObject { id: u8, mem: RefCell>, fw: RefCell)>> } +impl FwObject { + fn new(id: u8, size: usize) -> Arc { + Arc::new(Self { id, mem: RefCell::new(vec![0; size]), fw: RefCell::new(Vec::new()) }) + } + fn set(&self, at: usize, v: u32) { self.mem.borrow_mut()[at..at + 4].copy_from_slice(&v.to_le_bytes()); } + fn firmware(&self, at: usize, values: &[u32]) { self.fw.borrow_mut().push((at, values.to_vec())); } + fn r32(&self, offset: usize) -> Result { + if offset.checked_add(4).map_or(true, |e| e > self.mem.borrow().len()) { return Err(EINVAL); } + let mut fw = self.fw.borrow_mut(); + if let Some((_, vals)) = fw.iter_mut().find(|(at, _)| *at == offset) { + let v = if vals.len() > 1 { vals.remove(0) } else { vals[0] }; + drop(fw); + self.set(offset, v); + } else { drop(fw); } + let m = self.mem.borrow(); + let v = u32::from_le_bytes(m[offset..offset + 4].try_into().unwrap()); + log(Ev::Load(self.id, offset, v)); + Ok(v) + } + fn w32(&self, offset: usize, value: u32) -> Result { + if offset.checked_add(4).map_or(true, |e| e > self.mem.borrow().len()) { return Err(EINVAL); } + self.set(offset, value); + log(Ev::Store(self.id, offset, value)); + Ok(()) + } +} + +pub(crate) struct Ring { pub(crate) state: Arc, pub(crate) ring: Arc } +impl Ring { +RING_READ +} + +struct Events; +impl Events { + fn drain(&mut self, _dev: &kernel::device::Device, _ring: &Ring) -> Result { log(Ev::Events); Ok(()) } +} +''' + +MAIN = r''' +// Object ids in the access log. +const EVENT: u8 = 1; const LOG_ID: u8 = 2; const TRACE: u8 = 3; const STATS: u8 = 4; const STATS_RECORDS: u8 = 5; + +struct World { event: Ring, log: Ring, trace: Ring, stats: Ring } + +/// The rings: log and trace with fixed indices, some behind; the stats ring at `read` with the +/// producer's successive loads `producers`; record s carries tag `tag(s)` and word `index(s)`. +fn world(read: u32, producers: &[u32], records: usize, recs: &dyn Fn(usize) -> (u32, u32)) -> World { + let ring = |id: u8, ring_id: u8, state: usize, size: usize| Ring { state: FwObject::new(id, state), ring: FwObject::new(ring_id, size) }; + let w = World { + event: ring(EVENT, 11, rings::STATE_SIZE, 0x40), + log: ring(LOG_ID, 12, rings::LOG_STATE_SIZE, 0x40), + trace: ring(TRACE, 13, rings::STATE_SIZE, 0x40), + stats: ring(STATS, STATS_RECORDS, rings::STATE_SIZE, records), + }; + for i in 0..rings::LOG_RINGS { + w.log.state.set(i * 0x30 + STATE_READ, (i * 7) as u32); + w.log.state.set(i * 0x30 + STATE_WRITE, if i % 2 == 0 { (i * 7) as u32 } else { (i * 7 + 3) as u32 }); + } + w.trace.state.set(STATE_READ, 40); + w.trace.state.set(STATE_WRITE, 41); + w.stats.state.set(STATE_READ, read); + w.stats.state.firmware(STATE_WRITE, producers); + for s in 0..records / pstate::STATS_RECORD { + let (tag, index) = recs(s); + w.stats.ring.set(s * pstate::STATS_RECORD + pstate::STATS_TAG, tag); + w.stats.ring.set(s * pstate::STATS_RECORD + pstate::POWER_STATE_INDEX, index); + w.stats.ring.set(s * pstate::STATS_RECORD + 4, 0xdead_0000 | s as u32); + } + w +} +fn old(w: &World) -> OldChannels { OldChannels { event: w.event.clone(), log: w.log.clone(), trace: w.trace.clone(), stats: w.stats.clone() } } +fn new(w: &World) -> Channels { Channels { event: w.event.clone(), log: w.log.clone(), trace: w.trace.clone(), stats: w.stats.clone(), stats_seen: StatsSeen::default() } } +impl Clone for Ring { fn clone(&self) -> Self { Ring { state: self.state.clone(), ring: self.ring.clone() } } } + +/// What the firmware sees: stores and write barriers, in order. +fn visible(log: &[Ev]) -> Vec { log.iter().copied().filter(|e| matches!(e, Ev::Store(..) | Ev::Wmb)).collect() } +fn state(w: &World) -> Vec> { [&w.event, &w.log, &w.trace, &w.stats].iter().map(|r| r.state.mem.borrow().clone()).collect() } +fn stats_index_loads(log: &[Ev]) -> Vec<(usize, u32)> { log.iter().filter_map(|e| match e { Ev::Load(STATS, at, v) => Some((*at, *v)), _ => None }).collect() } +fn record_loads(log: &[Ev]) -> Vec { log.iter().filter_map(|e| match e { Ev::Load(STATS_RECORDS, at, _) => Some(*at), _ => None }).collect() } + +fn pattern(s: usize) -> (u32, u32) { ((s % 20) as u32, (s as u32) ^ 0x5a) } + +/// The expected notes of slots `read..write` (with wrap) under `recs`. +fn expect(read: u32, write: u32, recs: &dyn Fn(usize) -> (u32, u32)) -> (StatsSeen, Vec) { + let mut seen = StatsSeen::default(); + let mut loads = Vec::new(); + let mut s = read; + while s != write { + let (tag, index) = recs(s as usize); + seen.records += 1; + seen.tags[(tag as usize).min(pstate::TAGS - 1)] += 1; + if tag == pstate::TAG_POWER_STATE { seen.last = Some(index); } + loads.push(s as usize * pstate::STATS_RECORD + pstate::STATS_TAG); + loads.push(s as usize * pstate::STATS_RECORD + pstate::POWER_STATE_INDEX); + s = (s + 1) % 256; + } + (seen, loads) +} + +fn main() { + let dev = kernel::device::Device; + let size = rings::STATS_RING_SIZE; + // The record reads stay inside the ring object; the kernel holds the same with static_assert. + assert_eq!(pstate::STATS_RECORD * pstate::STATS_SLOTS as usize, rings::STATS_RING_SIZE); + assert!(pstate::STATS_TAG + 4 <= pstate::STATS_RECORD && pstate::POWER_STATE_INDEX + 4 <= pstate::STATS_RECORD); + assert_eq!(pstate::STATS_SLOTS, RING_SLOTS); + + // 1. Every consumer/producer pair, inside and outside the ring, with a steady producer. + let mut idx: Vec = (0..256).collect(); + idx.extend([256, 257, 0x1000, 0x7fff_ffff, u32::MAX]); + let mut pairs = 0u64; + for &r in &idx { for &p in &idx { + let wo = world(r, &[p], size, &pattern); + let mut ev = Events; + take_log(); + old(&wo).drain_rings(&dev, &mut ev).unwrap(); + let lo = take_log(); + let wn = world(r, &[p], size, &pattern); + let mut ch = new(&wn); + ch.drain_rings(&dev, &mut ev).unwrap(); + let ln = take_log(); + assert_eq!(visible(&lo), visible(&ln), "stores for read {r:#x} producer {p:#x}"); + assert_eq!(state(&wo), state(&wn), "state for read {r:#x} producer {p:#x}"); + let (io, inew) = (stats_index_loads(&lo), stats_index_loads(&ln)); + assert_eq!(io, [(STATE_WRITE, p), (STATE_READ, r)]); + assert_eq!(inew[..2], io[..], "producer before consumer"); + if r < 256 && p < 256 { + let (seen, loads) = expect(r, p, &pattern); + assert_eq!(inew, [(STATE_WRITE, p), (STATE_READ, r), (STATE_READ, r)], "consumer loaded again before the store"); + assert_eq!(record_loads(&ln), loads, "records {r}..{p}"); + assert_eq!(ch.stats_seen, seen); + let rmb = ln.iter().position(|e| *e == Ev::Rmb).expect("read barrier"); + let second = ln.iter().position(|e| *e == Ev::Load(STATS, STATE_READ, r)).unwrap(); + assert!(second < rmb, "barrier after the indices"); + if let Some(first) = ln.iter().position(|e| matches!(e, Ev::Load(STATS_RECORDS, ..))) { + assert!(rmb < first, "barrier before the records"); + } + let last_record = ln.iter().rposition(|e| matches!(e, Ev::Load(STATS_RECORDS, ..))).unwrap_or(rmb); + let reread = ln.iter().rposition(|e| *e == Ev::Load(STATS, STATE_READ, r)).unwrap(); + assert!(last_record < reread, "consumer loaded again after the records"); + // The record loads complete before the store hands their slots back. + let mbs: Vec = ln.iter().enumerate().filter(|(_, e)| **e == Ev::Mb).map(|(i, _)| i).collect(); + match ln.iter().position(|e| matches!(e, Ev::Store(STATS, ..))) { + Some(store) => { + assert_eq!(mbs.len(), 1, "one full barrier before the consumer store"); + assert!(last_record < mbs[0] && mbs[0] < store, "full barrier after the records, before the store"); + assert_eq!(ln.get(store + 1), Some(&Ev::Wmb)); + } + None => assert!(mbs.is_empty()), + } + } else { + assert_eq!(inew, [(STATE_WRITE, p), (STATE_READ, r), (STATE_WRITE, p), (STATE_READ, r)], "outside the ring: the earlier drain_one"); + assert!(record_loads(&ln).is_empty() && !ln.contains(&Ev::Rmb) && !ln.contains(&Ev::Mb)); + assert_eq!(ch.stats_seen, StatsSeen::default()); + } + // peek_stats() on the same ring stores nothing and notes what the drain would. + let wp = world(r, &[p], size, &pattern); + let cp = new(&wp); + take_log(); + let peeked = cp.peek_stats().unwrap(); + let lp = take_log(); + assert!(visible(&lp).is_empty(), "peek stores"); + assert_eq!(peeked, ch.stats_seen); + pairs += 1; + }} + + // 2. A producer that moves between loads. + // Inside the ring: one producer load per drain, the same as the earlier drain's. + for (r, ps) in [(10u32, vec![20u32, 30]), (250, vec![3, 9]), (5, vec![5, 6])] { + let wo = world(r, &ps, size, &pattern); + let wn = world(r, &ps, size, &pattern); + let (o, mut n) = (old(&wo), new(&wn)); + let mut ev = Events; + take_log(); o.drain_rings(&dev, &mut ev).unwrap(); o.drain_rings(&dev, &mut ev).unwrap(); let lo = take_log(); + n.drain_rings(&dev, &mut ev).unwrap(); let first = take_log(); + n.drain_rings(&dev, &mut ev).unwrap(); let second = take_log(); + let both: Vec = first.iter().chain(second.iter()).copied().collect(); + assert_eq!(visible(&lo), visible(&both), "moving producer {ps:?}"); + let (s1, l1) = expect(r, ps[0], &pattern); + assert_eq!(record_loads(&first), l1); + let (_, l2) = expect(ps[0], ps[1], &pattern); + assert_eq!(record_loads(&second), l2, "each record noted once"); + assert_eq!(n.stats_seen.records, s1.records + l2.len() as u64 / 2); + } + // Outside the ring: the earlier drain_one() loads the producer again and stores that load. + for (r, ps) in [(10u32, vec![300u32, 40]), (300, vec![40, 41]), (10, vec![u32::MAX, 10])] { + let wn = world(r, &ps, size, &pattern); + let mut n = new(&wn); + let mut ev = Events; + take_log(); n.drain_rings(&dev, &mut ev).unwrap(); let ln = take_log(); + // The earlier drain with the producer the fallback loads. + let wo = world(r, &ps[1..], size, &pattern); + old(&wo).drain_rings(&dev, &mut ev).unwrap(); let lo = take_log(); + assert_eq!(visible(&ln), visible(&lo), "fallback store for {ps:?}"); + assert_eq!(stats_index_loads(&ln), [(STATE_WRITE, ps[0]), (STATE_READ, r), (STATE_WRITE, ps[1]), (STATE_READ, r)]); + assert_eq!(n.stats_seen, StatsSeen::default()); + } + + // 3. Wrap, empty and full, with the parsing. + let recs = |s: usize| match s { + 254 => (pstate::TAG_POWER_STATE, 3), + 2 => (pstate::TAG_POWER_STATE, 7), + 0 => (4, 99), + 1 => (200, 98), + _ => (9, 97), + }; + let wn = world(250, &[5], size, &recs); + let mut n = new(&wn); let mut ev = Events; + n.drain_rings(&dev, &mut ev).unwrap(); take_log(); + assert_eq!(n.stats_seen.records, 11); + assert_eq!(n.stats_seen.last, Some(7), "the newest power-state record, across the wrap"); + assert_eq!(n.stats_seen.tags[pstate::TAG_POWER_STATE as usize], 2); + assert_eq!(n.stats_seen.tags[4], 1); + assert_eq!(n.stats_seen.tags[pstate::TAGS - 1], 1); + assert_eq!(n.stats_seen.tags[9], 7); + assert_eq!(wn.stats.state.mem.borrow()[0..4], 5u32.to_le_bytes()); + for (r, p, count) in [(0u32, 0u32, 0u64), (128, 128, 0), (255, 255, 0), (10, 9, 255), (0, 255, 255), (255, 254, 255), (255, 0, 1)] { + let wn = world(r, &[p], size, &pattern); + let mut n = new(&wn); + n.drain_rings(&dev, &mut ev).unwrap(); + let l = take_log(); + assert_eq!(n.stats_seen.records, count, "{r}..{p}"); + assert_eq!(l.iter().filter(|e| matches!(e, Ev::Store(STATS, ..))).count(), (count != 0) as usize); + } + // Notes accumulate across drains. + let wn = world(0, &[100, 200, 200], size, &pattern); + let mut n = new(&wn); + for _ in 0..3 { n.drain_rings(&dev, &mut ev).unwrap(); } + take_log(); + assert_eq!(n.stats_seen, expect(0, 200, &pattern).0); + + // 4. A record that cannot be loaded (not reachable in the kernel: see the size checks above). + // The drain then fails before its store and keeps its notes. + let wn = world(250, &[5], 0x3000, &pattern); + let mut n = new(&wn); + take_log(); + assert_eq!(n.drain_rings(&dev, &mut ev), Err(EINVAL)); + let l = take_log(); + assert!(visible(&l).iter().all(|e| !matches!(e, Ev::Store(STATS, ..)))); + assert_eq!(n.stats_seen, StatsSeen::default()); + + // 5. The HardwareDataA frequency single against the host's arithmetic. + let mut singles = 0u32; + for sign in [0u32, 1] { for exp in 0u32..=255 { + for frac in [0u32, 1, 2, 0x3ff, 0x40_0000, 0x40_0001, 0x55_5555, 0x7f_fffe, 0x7f_ffff] { + let bits = sign << 31 | exp << 23 | frac; + let f = f32::from_bits(bits); + let want = if f == 0.0 { Some(0) } else if !f.is_finite() || f < 0.0 { None } else { + let r = (f as f64 * 1000.0).round_ties_even(); + if r > u32::MAX as f64 { None } else { Some(r as u32) } + }; + assert_eq!(pstate::f32_mhz_to_khz(bits), want, "{bits:#010x}"); + singles += 1; + } + }} + + println!("PASS actual G15 drain bodies: {pairs} consumer/producer pairs, moving producers, wrap/empty/full parsing, peek, record fault, {singles} singles"); +} +''' + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--ref', help='Read the tested bodies at this git revision') + p.add_argument('--mutation', choices=sorted(MUTATIONS)) + p.add_argument('--mutations', action='store_true', help='Also require every mutation to fail') + a = p.parse_args() + import tempfile + out = (a.output or Path(tempfile.mkdtemp(prefix='g15-stats-drain-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + + def read(path, ref=None): + ref = ref or a.ref + return (subprocess.check_output(['git', 'show', f'{ref}:{path}'], cwd=ROOT, text=True, + stderr=subprocess.DEVNULL) + if ref else (ROOT / path).read_text()) + + # The embedded reference is the commit's own text, when the commit is here. + try: + old_git = item(read(CHANNEL.replace("drivers/gpu/drm/asahi/", "drivers/gpu/drm/asahi-m3/"), OLD_REF), ' pub(crate) fn drain_rings(') + except (subprocess.CalledProcessError, ValueError): + old_git = None + if old_git is not None and old_git != OLD_DRAIN_RINGS: + raise SystemExit('embedded drain_rings() differs from ' + OLD_REF) + + def run(mutation): + src = {CHANNEL: read(CHANNEL), PSTATE: read(PSTATE)} + if mutation: + path, old, new = MUTATIONS[mutation] + if src[path].count(old) != 1: + raise SystemExit(f'mutation {mutation}: anchor not found once') + src[path] = src[path].replace(old, new) + channel, hw, fw = src[CHANNEL], read(HW), read(FW_CHANNELS) + drain_one = item(channel, ' fn drain_one(ring: &Ring, offset: usize) -> Result {') + bodies = [item(channel, s) for s in ( + ' fn note_stats(ring: &Ring, seen: &mut StatsSeen) -> Result> {', + ' pub(crate) fn peek_stats(&self) -> Result {', + ' pub(crate) fn drain_rings(')] + ring_read = item(channel, ' pub(crate) fn read(&self) -> Result {') + consts = '\n'.join(const(fw, n) for n in ('STATE_READ', 'STATE_WRITE', 'RING_SLOTS')) + consts += '\nmod rings {\n' + '\n'.join( + const(hw, n) for n in ('STATE_SIZE', 'LOG_RINGS', 'LOG_STATE_SIZE', 'STATS_RING_SIZE')) + '\n}\n' + tested = drain_one + ''.join(bodies) + ring_read + src[PSTATE] + dir = out / (mutation or 'actual') + dir.mkdir(exist_ok=True) + (dir / 'pstate.rs').write_text(src[PSTATE]) + code = (PREFIX.replace('PSTATE_PATH', str(dir / 'pstate.rs')).replace('RING_READ', ring_read) + consts + + 'struct OldChannels { event: Ring, log: Ring, trace: Ring, stats: Ring }\n' + 'impl OldChannels {\n' + drain_one + '\n' + OLD_DRAIN_RINGS + '\n}\n' + 'struct Channels { event: Ring, log: Ring, trace: Ring, stats: Ring, stats_seen: StatsSeen }\n' + 'impl Channels {\n' + drain_one + '\n' + '\n'.join(bodies) + '\n}\n' + MAIN) + path = dir / 'drain.rs' + path.write_text(code) + binary = dir / 'drain' + subprocess.run(['rustup', 'run', '1.93.1', 'rustc', '--edition=2021', '-O', '-C', 'overflow-checks=on', + '-C', 'panic=abort', str(path), '-o', str(binary)], check=True) + + def no_core(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + r = subprocess.run([str(binary)], capture_output=True, text=True, preexec_fn=no_core, timeout=300) + return {'mutation': mutation, 'tested_sha256': hashlib.sha256(tested.encode()).hexdigest(), + 'exit': r.returncode, 'stdout': r.stdout, 'stderr': r.stderr[-2000:]} + + result = run(a.mutation) + receipt = {'ref': a.ref, 'old_ref': OLD_REF, 'old_reference_checked_against_git': old_git is not None, + **result, + 'scope': 'Actual drain_one/note_stats/peek_stats/drain_rings and power/pstate.rs against ' + f'drain_rings at {OLD_REF[:12]}, over a model of the firmware objects with an ' + 'ordered access log. Not kernel, firmware or GPU execution, and not timing: the ' + 'noting drain loads more words and takes longer.'} + if a.mutations and not a.mutation: + receipt['mutations'] = {} + for m in sorted(MUTATIONS): + res = run(m) + receipt['mutations'][m] = {'exit': res['exit'], 'stderr': res['stderr'][-400:]} + (out / 'result.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps({k: v for k, v in receipt.items() if k != 'stderr'}, indent=2)) + # The actual bodies must pass; a single requested mutation must fail. + if (receipt['exit'] != 0) != bool(a.mutation): + raise SystemExit(1) + if a.mutations and any(v['exit'] == 0 for v in receipt.get('mutations', {}).values()): + raise SystemExit('a mutation survived') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g15-zero-words-tests.py b/tools/asahi/g15-zero-words-tests.py new file mode 100644 index 00000000000000..5b728e95fc03e2 --- /dev/null +++ b/tools/asahi/g15-zero-words-tests.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Test the actual J516C record builder's narrow zero-word exemption. + +Uses synthetic public data and temporary host copies of production Rust modules. +No GPU, firmware file, private fixture, kernel build or hardware access. The +golden T6030 inputs below are from SiliconForest 9f09c85f8d3b, except the full +hw.rs file refreshed at 709f0f08316a for the reviewed shared PB allocator changes. +Its T6030 configuration module is independently pinned to the original bytes. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +G15 = "drivers/gpu/drm/asahi/g15" +GOLDEN_FILES = { + "board/data.rs": "7c5ff1077ca3296cbfc9e7144294162b6dea78a3774c38eeed4b0f59a14d7a5c", + "board/template.rs": "286872f5474a67534f214e83e659253299f85143f3dc59035fa80894022e2549", + "hw.rs": "e4619590e670ed88d2a9bb76b03853081c615d3d0ad1c6a68321ce8e615ef8a0", + "power/idle.rs": "4928ecf7699b3ca85ff5143eb6e996efd40d47321e29a238a02c8873bc9f102c", +} +GOLDEN_FUNCTIONS = { + ("hw.rs", "pub(crate) mod t6030 {"): "0079ae08fbe0e51cbf14e48711981a81048d1a1d3fc5495ab8d5c376283a760c", + ("initdata.rs", "fn templates("): "c3115c9926d3d7d93317cb8510e93b04f30b0c256811d7137568e822dd93b8ee", + ("initdata.rs", "pub(crate) fn prepare_board("): "c59f968f125397efc63f75a49d3a8543c15c1fd4d50362f15683563398e64bc6", + ("board.rs", "pub(crate) fn from_adt("): "cecd0b28db5bd94d3b75c1bbb5f35204e8bf0699f74e5b3d08228c59025f6ac2", +} + + +def function(source, marker): + start = source.index(marker) + depth = 0 + for end in range(source.index("{", start), len(source)): + depth += (source[end] == "{") - (source[end] == "}") + if depth == 0: + return source[start:end + 1] + raise ValueError("unterminated function: " + marker) + + +CASES = r''' +#[cfg(test)] +mod zero_words_regressions { + use super::*; + + // Frozen pre-5131caff FROM_FILE offsets from SiliconForest 9f09c85f8d3b. + // This list is deliberately independent of both new lists. + const OLD: [usize; 74] = [ + 224,232,244,248,252,256,260,264,268,728,732,736,740,744,748, + 992,1000,1012,1016,1024,1036,1496,1500,1504,1508,1512,1516, + 4192,4196,4200,4204,4208,4212,4216,12504,12528,19492,20012, + 20016,23056,23060,27176,27180,45528,45532,45536,45540,45544, + 45548,45552,45556,45560,45564,45568,45572,45576,45580,45584, + 45588,45592,45596,45748,45836,45840,45844,45848,45900,45904, + 45908,45912,45932,45940,45948,45956, + ]; + + fn synthetic() -> (Vec, Vec, [Opp; 1], [u32; PROPS.len()]) { + let mut file = vec![0u8; SIZE]; + for (n, &at) in OLD.iter().enumerate() { + put32(&mut file, at, 0x13570000 | (n as u32 + 1)).unwrap(); + } + put32(&mut file, MAX_POWER, 54321).unwrap(); + for (n, key) in [b"RT0g", b"RT1g", b"RT2g", b"RT3g", b"RT0r", b"RT0f"].iter().enumerate() { + put32(&mut file, SENSOR_ROWS + 12*n, u32::from_le_bytes(**key)).unwrap(); + } + // Public, synthetic OPPs: state0 off; eight voltage groups, five paired. + let mut main = vec![Opp {mhz:0, mv:[125;4], cells:4, mw:0}]; + for (mv, freqs) in [ + (600, &[300u32][..]), (650, &[500][..]), (700, &[700][..]), + (750, &[800,900][..]), (800, &[950,1000][..]), + (850, &[1050,1100][..]), (900, &[1150,1200][..]), + (950, &[1250,1300][..]), + ] { + for &mhz in freqs { + main.push(Opp {mhz, mv:[mv;4], cells:4, mw:mhz*40}); + } + } + let cs = [Opp {mhz:24, mv:[635,0,0,0], cells:1, mw:0}]; + let mut props = [1u32; PROPS.len()]; + props[PERIOD_MS] = 8; + props[AVG_TC_MS] = 32; + props[PPM_TC_MS] = 32; + props[MIN_SRAM_UV] = 815000; + props[CSAFR_MIN_SRAM_UV] = 815000; + for at in [AVG_KI,AVG_KP,FD_KI,FD_KP,PERF_KI,PERF_KI2,PERF_KP, + PERF_KP2,PPM_KI,PPM_KP,PWR_KI,PWR_KP,SE_KI,SE_KI1,SE_KP,SE_KP1] { + props[at] = 0x3f800000; // finite normal 1.0, not a calibration claim + } + (file, main, cs, props) + } + + fn inputs<'a>(main: &'a [Opp], cs: &'a [Opp], props: [u32; PROPS.len()]) -> Inputs<'a> { + Inputs {props, zones:&[], main, cs, afr:cs, slots:&[], empty_writable:&[], + ttbat:0x100000, usc_base:0x1000000000, user_end:0x2000000000, + timestamps:0xfffffc2ffc000000, max_power_mw:54321} + } + + #[test] + fn old74_is_exact_disjoint_partition() { + assert_eq!(FROM_FILE.len(), 32); + assert_eq!(UNNEEDED.len(), 42); + let mut union = FROM_FILE.to_vec(); + union.extend_from_slice(&UNNEEDED); + union.sort_unstable(); + assert!(union.windows(2).all(|w| w[0] < w[1]), "duplicate or overlapping offsets"); + assert!(union.iter().all(|&at| at % 4 == 0 && at + 4 <= SIZE)); + let mut old = OLD.to_vec(); old.sort_unstable(); + assert_eq!(union, old, "the exemption must not grow beyond old74"); + } + + #[test] + fn actual_from_file_copies_only_retained32() { + let (file, _, _, _) = synthetic(); + let mut out = vec![0u8; SIZE]; + from_file(&mut out, &file).unwrap(); + for at in (0..SIZE).step_by(4) { + let expected = if FROM_FILE.contains(&at) {get32(&file, at).unwrap()} else {0}; + assert_eq!(get32(&out, at).unwrap(), expected, "copy offset +{at:#x}"); + } + } + + #[test] + fn actual_builder_leaves42_zero_and_preserves32() { + let (file, main, cs, props) = synthetic(); + let mut out = vec![0u8; SIZE]; + from_file(&mut out, &file).unwrap(); + build(&mut out, &inputs(&main, &cs, props)).unwrap(); + for &at in UNNEEDED.iter() { + assert_ne!(get32(&file, at).unwrap(), 0, "fixture must exercise a real difference"); + assert_eq!(get32(&out, at).unwrap(), 0, "built offset +{at:#x}"); + } + for &at in FROM_FILE.iter() { + assert_eq!(get32(&out, at).unwrap(), get32(&file, at).unwrap(), "retained +{at:#x}"); + } + // Model a matching board file with nonzero legacy values only at the42. + let mut matching = out.clone(); + for &at in UNNEEDED.iter() { + put32(&mut matching, at, get32(&file, at).unwrap()).unwrap(); + } + assert_eq!(cross_check(&out, &matching), None); + } + + #[test] + fn actual_cross_check_exempts_only_zero_at_exact42() { + let mut built = vec![0u8; SIZE]; + let mut file = vec![0u8; SIZE]; + for at in (0..SIZE).step_by(4) { + put32(&mut file, at, 0x12345678).unwrap(); + let expected = if UNNEEDED.contains(&at) {None} else {Some((at,0,0x12345678))}; + assert_eq!(cross_check(&built, &file), expected, "file mismatch +{at:#x}"); + // No exemption for a nonzero built mismatch, even at the42. + put32(&mut built, at, 1).unwrap(); + assert_eq!(cross_check(&built, &file), Some((at,1,0x12345678)), "built mismatch +{at:#x}"); + put32(&mut built, at, 0).unwrap(); + put32(&mut file, at, 0).unwrap(); + } + } +} +''' + + +MUTANTS = { + "broad-cross-check-exemption": ("cross_check", "UNNEEDED.contains(&at)", "true"), + "nonzero-built-exempted": ("cross_check", "b == 0 && UNNEEDED.contains(&at)", "UNNEEDED.contains(&at)"), + "legacy-copy-reintroduced": ("from_file", "FROM_FILE.iter()", "FROM_FILE.iter().chain(UNNEEDED.iter())"), +} + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-root", type=Path, default=Path(__file__).resolve().parents[2]) + parser.add_argument("--rustc", default=os.environ.get("HOSTRUSTC", "rustc")) + parser.add_argument("--mutations", action="store_true") + parser.add_argument("--evidence", type=Path) + args = parser.parse_args() + root = args.source_root.resolve() + sources = {name: (root / G15 / "board" / name).read_bytes() + for name in ("record.rs", "words.rs", "template.rs", "data.rs")} + golden = {} + for name, expected in GOLDEN_FILES.items(): + actual = sha((root / G15 / name).read_bytes()) + if actual != expected: + raise SystemExit("T6030 golden file changed: " + name) + golden[name] = actual + for (name, marker), expected in GOLDEN_FUNCTIONS.items(): + actual = sha(function((root / G15 / name).read_text(), marker).encode()) + if actual != expected: + raise SystemExit("T6030 golden path changed: " + marker) + golden[name + ":" + marker] = actual + + if args.evidence: + args.evidence.mkdir(parents=False, exist_ok=False) + receipt = {"sources": {name: sha(data) for name, data in sources.items()}, + "t6030_golden_inputs": golden, "mutants": {}, + "harness_sha256": sha(Path(__file__).read_bytes()), + "compiler": subprocess.check_output([args.rustc, "--version"], text=True).strip()} + with tempfile.TemporaryDirectory(prefix="g15-zero-words-") as temp: + temp = Path(temp) + for name, data in sources.items(): + (temp / name).write_bytes(data) + original = sources["record.rs"].decode() + wrapper = "mod board {\n" + for name in ("template", "data", "words", "record"): + wrapper += f'#[path = "{temp / name}.rs"] pub(crate) mod {name};\n' + if name == "template": + wrapper += "pub(crate) use template::{Line, Template};\n" + wrapper += "}\n" + (temp / "host.rs").write_text(wrapper) + + def run(name, record): + (temp / "record.rs").write_text(record + CASES) + binary = temp / name + command = [args.rustc, "--edition=2021", "--test", "-O", "-C", "overflow-checks=on", + str(temp / "host.rs"), "-o", str(binary)] + compiled = subprocess.run(command, capture_output=True, text=True) + if args.evidence: + (args.evidence / (name + "-compile.log")).write_text(compiled.stdout + compiled.stderr) + if compiled.returncode: + raise RuntimeError(name + " did not compile:\n" + compiled.stderr) + tested = subprocess.run([str(binary)], capture_output=True, text=True) + if args.evidence: + (args.evidence / (name + "-test.log")).write_text(tested.stdout + tested.stderr) + return tested + + actual = run("actual", original) + if actual.returncode: + raise SystemExit(actual.stdout + actual.stderr) + receipt["test_summary"] = next(line for line in actual.stdout.splitlines() + if line.startswith("test result:")) + if args.mutations: + for name, (func, before, after) in MUTANTS.items(): + scope = function(original, "pub(crate) fn " + func + "(") + if scope.count(before) != 1: + raise RuntimeError("mutation site changed: " + name) + changed = original.replace(scope, scope.replace(before, after, 1), 1) + mutant = run(name, changed) + if not mutant.returncode: + raise RuntimeError("mutant survived: " + name) + regression = ("actual_from_file_copies_only_retained32" if func == "from_file" + else "actual_cross_check_exempts_only_zero_at_exact42") + if regression + " ... FAILED" not in mutant.stdout: + raise RuntimeError("new regression did not catch mutant: " + name) + receipt["mutants"][name] = "caught at runtime" + receipt["source_files_unchanged"] = all( + (root / G15 / "board" / name).read_bytes() == data for name, data in sources.items()) + if not receipt["source_files_unchanged"]: + raise SystemExit("source changed during validation; rerun on a frozen candidate") + receipt["limits"] = "Host synthetic record data only; two private hardware-fixture tests remain ignored." + if args.evidence: + for name, data in sources.items(): + (args.evidence / name).write_bytes(data) + (args.evidence / "synthetic-tests.rs").write_text(CASES) + (args.evidence / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps(receipt, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/t6030-clock-tests.py b/tools/asahi/t6030-clock-tests.py new file mode 100644 index 00000000000000..0b75c3ade6f5d6 --- /dev/null +++ b/tools/asahi/t6030-clock-tests.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Execute T6030 DCP callbacks and PHY clock functions on modeled registers.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import resource +import subprocess +ROOT = Path(__file__).resolve().parents[2] +FUNCTIONS = { + 'include/linux/soc/apple/dp-tunnel.h': ['apple_dp_tunnel_t6030_pclk'], + 'drivers/gpu/drm/apple/dcp-fabric-core.h': ['dcp_fabric_t6030_pclk'], + 'drivers/gpu/drm/apple/dcp-fabric-session.h': ['dcp_fabric_callback_valid'], + 'drivers/phy/apple/atc.c': [ + 'apple_atc_tunnel_is_t6030', 'atc_t8122_tunnel_apb', 'atc_t8122_tunnel_stop', + 'atc_t8122_tunnel_pclk', 'atc_t8122_tunnel_start', + 'apple_atc_dp_tunnel_rate_source'], + 'drivers/gpu/drm/apple/dcp-fabric.c': [ + 'dcp_route_clock_rate', 'dcp_tunnel_set_rate'], +} +CASES = ['dual-start', 'reverse-start', 'stop-second', 'same-rate', + 'stale-owner', 'same-source', 'retune-one', 'busy-mode', 'busy-pll', + 'invalid-source', 'invalid-rate', 'wrong-generation', 'failed-cleanup', 'failed-final-stop'] +CASES += ['fail-start-' + str(i) for i in range(4)] + +def function(source, name): + match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:int|void|bool)\s+' + name + + r'\([^;]*?\)\n\{', source, re.M | re.S) + if not match: + raise ValueError('Missing production function: ' + name) + pos = source.index('{', match.start()) + 1 + level = 1 + while level: + level += (source[pos] == '{') - (source[pos] == '}') + pos += 1 + return source[match.start():pos] + '\n' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--callback-ref') + parser.add_argument('--pclk-function', type=Path) + args = parser.parse_args() + bodies = {name: function((ROOT / path).read_text(), name) + for path, names in FUNCTIONS.items() for name in names} + if args.callback_ref: + original = subprocess.check_output( + ['git', 'show', args.callback_ref + ':drivers/gpu/drm/apple/dcp-fabric.c'], + cwd=ROOT, text=True) + bodies['dcp_tunnel_set_rate'] = function(original, 'dcp_tunnel_set_rate') + if args.pclk_function: + bodies['atc_t8122_tunnel_pclk'] = args.pclk_function.read_text() + lines = iter((ROOT / 'drivers/phy/apple/atc.c').read_text().splitlines(keepends=True)) + defines = [] + for line in lines: + if line.startswith('#define'): + definition = line + while line.rstrip().endswith('\\'): + line = next(lines) + definition += line + defines.append(definition) + code = (ROOT / 'tools/asahi/t6030-clock/fixture.c').read_text().replace( + '/* REGISTER_DEFINES */', ''.join(defines) + re.search( + r'enum atcphy_generation \{.*?\n\};', + (ROOT / 'drivers/phy/apple/atc.c').read_text(), re.S).group()).replace( + '/* PRODUCTION_FUNCTIONS */', '\n'.join(bodies.values())) + args.out.mkdir(parents=True, exist_ok=True) + source = args.out / 'production.c' + source.write_text(code) + binary = args.out / 'production' + subprocess.run(['cc', '-std=gnu11', '-g', '-Wall', '-Wextra', '-Werror', + '-fsanitize=address,undefined', '-fno-omit-frame-pointer', + '-Wno-unused-parameter', str(source), '-o', str(binary)], check=True) + def no_core(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + results = [] + for case in CASES: + run = subprocess.run([str(binary), case], capture_output=True, + text=True, preexec_fn=no_core) + results.append({'case': case, 'exit': run.returncode, + 'stdout': run.stdout, 'stderr': run.stderr}) + receipt = {'production_bodies': {name: hashlib.sha256(body.encode()).hexdigest() + for name, body in bodies.items()}, + 'translation_sha256': hashlib.sha256(code.encode()).hexdigest(), + 'hardware_access': False, 'original_callback_ref': args.callback_ref, + 'pclk_function_override': str(args.pclk_function) if args.pclk_function else None, + 'results': results} + (args.out / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps(results, indent=2)) + if any(row['exit'] for row in results): + raise SystemExit(1) +if __name__ == '__main__': + main() diff --git a/tools/asahi/t6030-clock/fixture.c b/tools/asahi/t6030-clock/fixture.c new file mode 100644 index 00000000000000..0a465d503ce030 --- /dev/null +++ b/tools/asahi/t6030-clock/fixture.c @@ -0,0 +1,318 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; +typedef uint32_t u32; +typedef uint64_t u64; +#define BIT(n) (1U << (n)) +#define GENMASK(h, l) ((~0U >> (31 - (h))) & (~0U << (l))) +#define FIELD_PREP(mask, v) (((u32)(v) << __builtin_ctz(mask)) & (mask)) +#define JOIN_(a, b) a##b +#define JOIN(a, b) JOIN_(a, b) +#define guard(x) __attribute__((unused)) void *JOIN(guard_, __LINE__) = +#define lockdep_assert_held(x) ((void)0) +#define dev_dbg(...) ((void)0) +#define dev_warn(...) ((void)0) +#define dev_err(...) ((void)0) +#define EXPORT_SYMBOL_GPL(x) +#define APPLE_ATCPHY_MODE_USB4 1 +#define APPLE_ATCPHY_MODE_TBT 2 +#define symbol_get(fn) (&fn) +#define symbol_put(fn) ((void)0) +/* REGISTER_DEFINES */ +struct atcphy_hw { + enum atcphy_generation gen; +}; +struct apple_atcphy { + const struct atcphy_hw *hw; + int lock, mode, dp_link_rate; + void *dev; + struct { + u8 *core; + } regs; + bool tunnel_clock_on; + u8 tunnel_rate, tunnel_users, tunnel_dpin_rate[2]; + unsigned tunnel_source[2]; +}; +struct phy { + const void *ops; + struct apple_atcphy *data; +}; +struct apple_dcp; +struct apple_dcp_typec_route { + struct apple_dcp *dcp; + unsigned mux_index, tunnel_dpin; + u64 tunnel_generation; + bool xbar_up; + void *active_xbar; +}; +struct apple_dcp { + int tb_lock; + void *dev; + bool dptx_tunnel, tb_clock_ok; + unsigned dptx_dfp_port; + u64 tb_generation; + struct apple_dcp_typec_route *active_typec_route; + struct { + bool active, xbar_up, clock_ok; + u64 generation; + void *xbar; + } split; +}; +static int apple_atc_dp_phy_ops; +static unsigned writes, polls, apb_requests, stop_requests, crossbar_stops; +static uint64_t faults; +static u8 *registers; +static struct apple_atcphy *running_phy; +static struct apple_atcphy *phy_get_drvdata(struct phy *p) +{ + return p->data; +} +static bool of_machine_is_compatible(const char *s) +{ + return !strcmp(s, "apple,t6030"); +} +static void atcphy_restore_after_pd_off(struct apple_atcphy *p) +{ +} +static void udelay(unsigned us) +{ +} +static u32 readl(const void *p) +{ + u32 v; + memcpy(&v, p, 4); + return v; +} +static void writel(u32 v, void *p) +{ + if ((u8 *)p == registers + ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0) { + assert(!(v & DPTX_PCLK2_ENABLE) || (v & DPTX_PCLK1_ENABLE)); + if (running_phy && (running_phy->tunnel_users & BIT(1)) && + running_phy->tunnel_rate) + assert(v & DPTX_PCLK1_ENABLE); + } + writes++; + memcpy(p, &v, 4); +} +static void core_clear32(struct apple_atcphy *p, unsigned off, u32 mask) +{ + writel(readl(p->regs.core + off) & ~mask, p->regs.core + off); +} +static void core_set32(struct apple_atcphy *p, unsigned off, u32 mask) +{ + writel(readl(p->regs.core + off) | mask, p->regs.core + off); +} +static void core_mask32(struct apple_atcphy *p, unsigned off, u32 mask, u32 v) +{ + writel((readl(p->regs.core + off) & ~mask) | (v & mask), + p->regs.core + off); +} +static int apple_atc_dp_tunnel_rate(struct phy *p, unsigned dpin, u8 rate) +{ + abort(); +} +static int dcp_dpxbar_link(void *xbar, bool up) +{ + assert(!up); + crossbar_stops++; + return 0; +} +static int model_poll(void *address, u32 *value) +{ + unsigned i = polls++, off = (u8 *)address - registers; + if (faults & (UINT64_C(1) << i)) + return -ETIMEDOUT; + if (off == AUS_COMMON_DIG_RCAL1) + *value = AUS_COMMON_DIG_RCAL1_ALL_CODES_DONE; + else if (off == AUSPLL_APB_CMD_OVERRIDE) { + u32 cmd = readl(address); + if (cmd & BIT(0)) { + *value = cmd | BIT(1); + apb_requests++; + } else { + *value = cmd & ~BIT(1); + if ((cmd & 0x10000018) == 0x10000018) { + u32 zero = 0; + memcpy(registers + T8122_DP_PCLK_STATUS, &zero, + 4); + stop_requests++; + } + } + } else { + assert(off == T8122_DP_PCLK_STATUS); + *value = readl(address); + } + if (off == AUSPLL_APB_CMD_OVERRIDE && (*value & BIT(0))) { + u32 lock = ACIOPHY_AUSPLL_LOCK; + memcpy(registers + T8122_DP_PCLK_STATUS, &lock, 4); + } + memcpy(address, value, 4); + return 0; +} +#define readl_poll_timeout(address, value, condition, interval, timeout) \ + ({ \ + int err = model_poll((address), &(value)); \ + assert(err || (condition)); \ + err; \ + }) +/* PRODUCTION_FUNCTIONS */ +static int clock_call(struct phy *phy, unsigned source, unsigned dpin, u8 rate) +{ + struct apple_dcp d = { .dptx_tunnel = true, + .dptx_dfp_port = dpin + 1, + .tb_generation = 7 }; + struct apple_dcp_typec_route r = { .dcp = &d, + .mux_index = source, + .tunnel_dpin = dpin, + .tunnel_generation = 7 }; + d.active_typec_route = &r; + int ret = dcp_tunnel_set_rate(&d, phy, 0, rate); + assert(d.tb_clock_ok == (!ret && rate)); + return ret; +} +static u32 tx(void) +{ + return readl(registers + ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0); +} +int main(int argc, char **argv) +{ + assert(argc == 2); + const char *name = argv[1]; + for (unsigned source = 0; source < 5; source++) + for (unsigned dpin = 0; dpin < 4; dpin++) + assert(dcp_fabric_t6030_pclk(source, dpin) == + apple_dp_tunnel_t6030_pclk(source, dpin)); + u8 regs[0x10000] = { 0 }; + registers = regs; + struct atcphy_hw hw = { .gen = ATCPHY_GENERATION_T8122 }; + struct apple_atcphy d = { .hw = &hw, + .regs.core = regs, + .mode = APPLE_ATCPHY_MODE_USB4 }; + running_phy = &d; + struct phy phy = { .ops = &apple_atc_dp_phy_ops, .data = &d }; + if (!strcmp(name, "wrong-generation")) { + hw.gen = ATCPHY_GENERATION_T8103; + assert(clock_call(&phy, 0, 0, 0x14) == -EOPNOTSUPP && !writes); + return 0; + } + if (!strncmp(name, "fail-start-", 11)) { + unsigned n = strtoul(name + 11, NULL, 10); + faults = UINT64_C(1) << n; + assert(clock_call(&phy, 0, 0, 0x14) == -ETIMEDOUT); + assert(!d.tunnel_clock_on && !d.tunnel_users && !d.tunnel_rate); + assert(!(tx() & T8122_PCLK_ENABLES)); + return 0; + } + if (!strcmp(name, "busy-mode")) { + d.mode = 0; + assert(clock_call(&phy, 0, 0, 0x14) == -EBUSY && !writes); + return 0; + } + if (!strcmp(name, "busy-pll")) { + writel(T8122_AUSPLL_PCLK_DRIVER, regs + AUSPLL_CLKOUT_MASTER); + unsigned saved = writes; + assert(clock_call(&phy, 0, 0, 0x14) == -EBUSY && + writes == saved); + return 0; + } + if (!strcmp(name, "invalid-source")) { + assert(clock_call(&phy, 1, 0, 0x14) == -EOPNOTSUPP && !writes); + return 0; + } + if (!strcmp(name, "invalid-rate")) { + assert(clock_call(&phy, 0, 0, 0x12) == -EINVAL && !writes); + return 0; + } + if (!strcmp(name, "failed-cleanup")) { + faults = BIT(1) | BIT(2); + assert(clock_call(&phy, 0, 0, 0x14) == -ETIMEDOUT); + assert(d.tunnel_clock_on && !d.tunnel_rate && + d.tunnel_users == 1); + unsigned saved = writes; + assert(clock_call(&phy, 2, 1, 0x14) == -EBUSY && + writes == saved); + faults = 0; + assert(!clock_call(&phy, 0, 0, 0)); + assert(!d.tunnel_clock_on && !d.tunnel_users); + return 0; + } + unsigned first = !strcmp(name, "reverse-start") ? 1 : 0, + second = 1 - first; + assert(!clock_call(&phy, 2 * first, first, 0x14)); + assert(d.tunnel_users == BIT(first) && d.tunnel_clock_on); + assert(tx() & DPTX_PCLK1_ENABLE); + if (first) + assert(tx() & DPTX_PCLK2_ENABLE); + unsigned saved_poll = polls, saved_apb = apb_requests; + assert(!clock_call(&phy, 2 * second, second, 0x1e)); + assert(d.tunnel_users == 3 && polls == saved_poll && + apb_requests == saved_apb); + assert((tx() & (DPTX_PCLK1_ENABLE | DPTX_PCLK2_ENABLE)) == + (DPTX_PCLK1_ENABLE | DPTX_PCLK2_ENABLE)); + assert((tx() & DPTX_PCLK1_SELECT) == + FIELD_PREP(DPTX_PCLK1_SELECT, first ? 0 : 1)); + assert((tx() & DPTX_PCLK2_SELECT) == + FIELD_PREP(DPTX_PCLK2_SELECT, first ? 1 : 0)); + if (!strcmp(name, "same-rate")) { + unsigned saved = writes; + assert(!clock_call(&phy, 0, 0, d.tunnel_dpin_rate[0]) && + writes == saved); + } + if (!strcmp(name, "stale-owner")) { + unsigned saved = writes; + assert(clock_call(&phy, 2, 0, 0x06) == -ESTALE && + writes == saved); + assert(clock_call(&phy, 2, 0, 0) == -ESTALE && writes == saved); + } + if (!strcmp(name, "same-source")) { + assert(!clock_call(&phy, 2, 1, 0)); + unsigned saved = writes; + assert(clock_call(&phy, 0, 1, 0x14) == -EBUSY && + writes == saved); + assert(!clock_call(&phy, 2, 1, 0x1e)); + } + if (!strcmp(name, "retune-one")) { + u32 other = tx() & DPTX_PCLK2_SELECT; + assert(!clock_call(&phy, 0, 0, 0x06)); + assert((tx() & DPTX_PCLK1_SELECT) == + FIELD_PREP(DPTX_PCLK1_SELECT, 4)); + assert((tx() & DPTX_PCLK2_SELECT) == other && + polls == saved_poll); + } + unsigned released = !strcmp(name, "stop-second") ? 1 : 0, + remaining = 1 - released; + assert(!clock_call(&phy, 2 * released, released, 0)); + assert(d.tunnel_clock_on && d.tunnel_users == BIT(remaining) && + !stop_requests); + assert(tx() & DPTX_PCLK1_ENABLE); + assert(!!(tx() & DPTX_PCLK2_ENABLE) == !!remaining); + unsigned saved = writes; + assert(!clock_call(&phy, 2 * released, released, 0) && writes == saved); + if (!strcmp(name, "failed-final-stop")) { + faults = UINT64_C(1) << polls; + assert(clock_call(&phy, 2 * remaining, remaining, 0) == + -ETIMEDOUT); + assert(d.tunnel_clock_on && !d.tunnel_rate && + d.tunnel_users == BIT(remaining)); + saved = writes; + assert(clock_call(&phy, 2 * released, released, 0x14) == + -EBUSY && + writes == saved); + faults = 0; + } + assert(!clock_call(&phy, 2 * remaining, remaining, 0)); + assert(!d.tunnel_clock_on && !d.tunnel_users && !d.tunnel_rate && + !(tx() & T8122_PCLK_ENABLES)); + saved = writes; + assert(!clock_call(&phy, 2 * remaining, remaining, 0) && + writes == saved); + printf("PASS %s writes=%u polls=%u: two callbacks, independent selectors, shared PLL, stop ownership\n", + name, writes, polls); + return 0; +} diff --git a/tools/asahi/t6030-display-admission-tests.c b/tools/asahi/t6030-display-admission-tests.c new file mode 100644 index 00000000000000..e2c75eddb5ea53 --- /dev/null +++ b/tools/asahi/t6030-display-admission-tests.c @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-only +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define EPROBE_DEFER 517 +#define DL_FLAG_AUTOREMOVE_CONSUMER 1 +#define EXPORT_SYMBOL_GPL(x) +struct device_node { + const char *compatible; +}; +struct device { + struct device_node *of_node; + atomic_int refs; +}; +struct device_link { + int unused; +}; +static pthread_mutex_t apple_t6030_display_lock = PTHREAD_MUTEX_INITIALIZER; +static struct device *apple_t6030_display; +static struct device_node display_node = { "apple,t6030-display-subsystem" }, + gpu_node = { "apple,agx-t6030" }, + other_node = { "apple,t6031-display-subsystem" }; +static struct device display, duplicate, gpu; +static const char *machine = "apple,t6030"; +static int pmp_calls, link_calls, pmp_result; +static bool link_ok = true; +static atomic_bool pause_link, link_entered, release_link, withdrew; +struct lock_guard { + pthread_mutex_t *lock; + bool once; +}; +static _Thread_local bool locked; +static struct lock_guard lock_take(pthread_mutex_t *lock) +{ + assert(!locked); + assert(!pthread_mutex_lock(lock)); + locked = true; + return (struct lock_guard){ lock, true }; +} +static void lock_drop(struct lock_guard *g) +{ + assert(locked); + locked = false; + assert(!pthread_mutex_unlock(g->lock)); +} +#define guard(kind) \ + struct lock_guard local_guard \ + __attribute__((cleanup(lock_drop))) = lock_take +#define scoped_guard(kind, lock) \ + for (struct lock_guard scoped \ + __attribute__((cleanup(lock_drop))) = lock_take(lock); \ + scoped.once; scoped.once = false) +static bool of_device_is_compatible(const struct device_node *n, + const char *name) +{ + return n && !strcmp(n->compatible, name); +} +static bool of_machine_is_compatible(const char *name) +{ + return !strcmp(machine, name); +} +static bool asahi_g15_board(void) +{ + return of_machine_is_compatible("apple,t6030"); +} +static struct device *get_device(struct device *dev) +{ + assert(locked); + atomic_fetch_add(&dev->refs, 1); + return dev; +} +static void put_device(struct device *dev) +{ + assert(!locked); + if (dev) + assert(atomic_fetch_sub(&dev->refs, 1) > 1); +} +static struct device_link host_link; +static struct device_link *device_link_add(struct device *consumer, + struct device *supplier, int flags) +{ + assert(locked && consumer == &gpu && supplier == &display && + atomic_load(&display.refs) == 2); + assert(flags == DL_FLAG_AUTOREMOVE_CONSUMER); + link_calls++; + if (atomic_load(&pause_link)) { + atomic_store(&link_entered, true); + while (!atomic_load(&release_link)) + sched_yield(); + } + return link_ok ? &host_link : NULL; +} +static int apple_pmp_link_device(struct device *dev) +{ + assert(!locked && dev == &gpu && link_calls > 0); + pmp_calls++; + return pmp_result; +} +#include "production.h" +static void reset(void) +{ + assert(!apple_t6030_display && !locked); + display = (struct device){ .of_node = &display_node, .refs = 1 }; + duplicate = (struct device){ .of_node = &display_node, .refs = 1 }; + gpu = (struct device){ .of_node = &gpu_node, .refs = 1 }; + pmp_calls = link_calls = pmp_result = 0; + link_ok = true; + machine = "apple,t6030"; + atomic_store(&pause_link, false); + atomic_store(&link_entered, false); + atomic_store(&release_link, false); + atomic_store(&withdrew, false); +} +static void *admit_thread(void *unused) +{ + (void)unused; + assert(asahi_g15_pmp_prepare(&gpu) == 0); + return NULL; +} +static void *withdraw_thread(void *unused) +{ + (void)unused; + apple_t6030_display_withdraw(&display); + atomic_store(&withdrew, true); + return NULL; +} +int main(void) +{ + unsigned int cases = 0; + (void)get_device; + (void)put_device; + reset(); + assert(asahi_g15_pmp_prepare(&gpu) == -EPROBE_DEFER && !pmp_calls); + cases++; + /* Component platform bind alone never calls this publication. Retry succeeds only afterward. */ + assert(apple_t6030_display_publish(&display) == 0 && + atomic_load(&display.refs) == 2); + cases++; + assert(asahi_g15_pmp_prepare(&gpu) == 0 && pmp_calls == 1); + cases++; + assert(apple_t6030_display_publish(&display) == 0 && + atomic_load(&display.refs) == 2); + cases++; + assert(apple_t6030_display_publish(&duplicate) == -EBUSY && + apple_t6030_display == &display); + cases++; + apple_t6030_display_withdraw(&duplicate); + assert(apple_t6030_display == &display && + atomic_load(&display.refs) == 2); + cases++; + link_ok = false; + assert(asahi_g15_pmp_prepare(&gpu) == -EINVAL && pmp_calls == 1); + cases++; + link_ok = true; + pmp_result = -EPROBE_DEFER; + assert(asahi_g15_pmp_prepare(&gpu) == -EPROBE_DEFER && pmp_calls == 2); + cases++; + machine = "apple,t6031"; + assert(apple_drm_t6030_link_device(&gpu) == -ENODEV); + cases++; + machine = "apple,t6030"; + gpu.of_node = &other_node; + assert(apple_drm_t6030_link_device(&gpu) == -ENODEV); + cases++; + gpu.of_node = &gpu_node; + apple_t6030_display_withdraw(&display); + assert(atomic_load(&display.refs) == 1 && !apple_t6030_display); + cases++; + assert(asahi_g15_pmp_prepare(&gpu) == -EPROBE_DEFER && pmp_calls == 2); + cases++; + display.of_node = &other_node; + assert(apple_t6030_display_publish(&display) == 0 && + !apple_t6030_display && atomic_load(&display.refs) == 1); + cases++; + reset(); + assert(!apple_t6030_display_publish(&display)); + atomic_store(&pause_link, true); + pthread_t admit, withdraw; + assert(!pthread_create(&admit, NULL, admit_thread, NULL)); + while (!atomic_load(&link_entered)) + sched_yield(); + assert(!pthread_create(&withdraw, NULL, withdraw_thread, NULL)); + usleep(10000); + assert(!atomic_load(&withdrew) && atomic_load(&display.refs) == 2); + atomic_store(&release_link, true); + assert(!pthread_join(admit, NULL) && !pthread_join(withdraw, NULL)); + assert(atomic_load(&withdrew) && atomic_load(&display.refs) == 1 && + !apple_t6030_display); + cases++; + printf("PASS: %u actual display publisher/admission controls, including concurrent link/withdraw\n", + cases); + return 0; +} diff --git a/tools/asahi/t6030-display-admission-tests.py b/tools/asahi/t6030-display-admission-tests.py new file mode 100644 index 00000000000000..a1da987377f182 --- /dev/null +++ b/tools/asahi/t6030-display-admission-tests.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Actual T6030 display publisher and G15 admission, with pthread boundaries. + +Tests initial admission and pointer lifetime, not safe shutdown of retained G15 +firmware after forced display unbind. Full DRM publication placement is checked +as source ordering separately from executable host boundary controls. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shlex +import subprocess +from importlib.machinery import SourceFileLoader +ROOT = Path(__file__).resolve().parents[2] +extract = SourceFileLoader('supplier_test', str(ROOT / 'tools/asahi/t6030-pmp-supplier-tests.py')).load_module() + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--output', required=True, type=Path) + p.add_argument('--mutations', action='store_true') + args = p.parse_args(); args.output.mkdir(parents=True, exist_ok=False) + drv = (ROOT / 'drivers/gpu/drm/apple/apple_drv.c').read_text() + glue = (ROOT / 'drivers/gpu/drm/asahi/g15/glue.c').read_text() + init = extract.function(drv, 'static int apple_drm_init(') + uninit = extract.function(drv, 'static void apple_drm_uninit(') + assert init.index('ret = drm_dev_register(') < init.index('drm_client_setup_with_fourcc(') < init.index('ret = apple_t6030_display_publish(') + assert uninit.index('apple_t6030_display_withdraw(') < uninit.index('apple_drm_quiesce_connectors(') < uninit.index('drm_dev_unplug(') + assert 'drm_dev_unregister(&apple->drm);\n\t\tgoto err_unbind;' in init + code = '\n'.join([extract.function(drv, 'static int apple_t6030_display_publish('), + extract.function(drv, 'static void apple_t6030_display_withdraw('), + extract.function(drv, 'int apple_drm_t6030_link_device('), + extract.function(glue, 'int asahi_g15_pmp_prepare(struct device *dev)\n')]) + variants = [('control', code)] + if args.mutations: + for name, old, new in [ + ('no-ready-gate', 'if (!apple_t6030_display)', 'if (false)'), + ('no-display-get', 'apple_t6030_display = get_device(dev);', 'apple_t6030_display = dev;'), + ('no-display-put', 'put_device(old);', '(void)old;'), + ('replace-live-provider', 'return apple_t6030_display == dev ? 0 : -EBUSY;', 'apple_t6030_display = dev;'), + ('ignore-display-error', 'if (ret)\n\t\treturn ret;', 'if (false)\n\t\treturn ret;'), + ('wrong-gpu', '!of_device_is_compatible(consumer->of_node, "apple,agx-t6030")', 'false'), + ('withdraw-wrong-provider', 'if (apple_t6030_display == dev)', 'if (((void)dev, true))'), + ]: + assert code.count(old) == 1, (name, code.count(old)) + variants.append((name, code.replace(old, new))) + compiler = shlex.split(os.environ.get('CC', 'clang')) + command = compiler + ['-std=gnu11', '-g', '-O1', '-Wall', '-Wextra', '-Werror', + '-fsanitize=address,undefined', '-fno-omit-frame-pointer', '-pthread', + '-I', str(args.output), str(ROOT / 'tools/asahi/t6030-display-admission-tests.c'), '-o', str(args.output / 'admission')] + results = [] + for name, source in variants: + (args.output / 'production.h').write_text(source) + built = subprocess.run(command, capture_output=True, text=True) + ran = subprocess.run([str(args.output / 'admission')], capture_output=True, text=True) if not built.returncode else None + (args.output / (name + '.log')).write_text(built.stdout + built.stderr + (ran.stdout + ran.stderr if ran else '')) + results.append({'name': name, 'build_rc': built.returncode, 'run_rc': ran.returncode if ran else None}) + (args.output / 'production.h').write_text(code) + good = all(x['build_rc'] == 0 and (x['run_rc'] == 0 if x['name'] == 'control' else x['run_rc'] != 0) for x in results) + (args.output / 'receipt.json').write_text(json.dumps({'passed': good, 'source_sha256': hashlib.sha256(code.encode()).hexdigest(), + 'publication_order_verified': True, 'forced_supplier_unbind_safety_claimed': False, 'command': command, 'results': results}, indent=2) + '\n') + print(json.dumps({'passed': good, 'results': results})) + return not good +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/t6030-display-linkage-tests.py b/tools/asahi/t6030-display-linkage-tests.py new file mode 100644 index 00000000000000..7ff606c41817d4 --- /dev/null +++ b/tools/asahi/t6030-display-linkage-tests.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual G15 Kconfig stanza through the kernel's conf in 18 combinations. + +The test uses a minimal Kconfig containing the actual production G15 stanza and +its dependency/select names, so unrelated architecture/compiler options do not +hide invalid provider/consumer linkage. It writes only the supplied output dir. +""" +import argparse +import hashlib +import itertools +import json +import os +from pathlib import Path +import re +import subprocess +ROOT = Path(__file__).resolve().parents[2] + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--output', required=True, type=Path) + p.add_argument('--conf', required=True, type=Path, help='built scripts/kconfig/conf') + args = p.parse_args(); args.output.mkdir(parents=True, exist_ok=False) + source = (ROOT / 'drivers/gpu/drm/asahi/Kconfig').read_text() + stanza = source.split('config DRM_ASAHI_G15\n', 1)[1].split('\nconfig ', 1)[0] + stanza = 'config DRM_ASAHI_G15\n' + stanza + assert 'depends on DRM_APPLE=y || (DRM_APPLE=m && DRM_ASAHI=m)' in stanza + kconfig = '''mainmenu "T6030 display linkage controls" +config MODULES + bool "Modules" + modules + default y +config DRM_APPLE + tristate "Display" +config DRM_ASAHI + tristate "GPU" +config APPLE_T6030_GPU_PMP_LINK + bool +config CRYPTO_LIB_SHA256 + bool +''' + stanza + source_path = args.output.resolve() / 'Kconfig' + source_path.write_text(kconfig) + results = [] + for gpu, display, request in itertools.product(('n', 'm', 'y'), ('n', 'm', 'y'), ('n', 'y')): + case = args.output / f'asahi-{gpu}-display-{display}-g15-{request}' + case.mkdir() + config = case.resolve() / 'config' + config.write_text(f'CONFIG_MODULES=y\nCONFIG_DRM_ASAHI={gpu}\nCONFIG_DRM_APPLE={display}\nCONFIG_DRM_ASAHI_G15={request}\n') + env = os.environ | {'KCONFIG_CONFIG': str(config)} + result = subprocess.run([str(args.conf.resolve()), '--olddefconfig', str(source_path)], + env=env, cwd=case, capture_output=True, text=True) + (case / 'conf.log').write_text(result.stdout + result.stderr) + actual = dict(re.findall(r'^CONFIG_(\w+)=(\w+)$', config.read_text(), re.M)) + expected = 'y' if request == 'y' and gpu != 'n' and (display == 'y' or display == 'm' and gpu == 'm') else 'n' + got = actual.get('DRM_ASAHI_G15', 'n') + good = result.returncode == 0 and got == expected and actual.get('DRM_ASAHI', 'n') == gpu and actual.get('DRM_APPLE', 'n') == display + results.append({'gpu': gpu, 'display': display, 'g15_requested': request, + 'g15_expected': expected, 'g15_actual': got, 'conf_rc': result.returncode, 'pass': good}) + glue = (ROOT / 'drivers/gpu/drm/asahi/g15/glue.c').read_text() + start = glue.index('int asahi_g15_pmp_prepare(struct device *dev)\n') + body = glue[start:glue.index('\nint asahi_g15_pmp_get(', start)] + assert 'ret = apple_drm_t6030_link_device(dev);' in body + assert 'symbol_get(' not in body + # The provider does not import any of Asahi's glue symbols. Full modpost + # and the actual .modinfo dependency are separately required build gates. + provider = '\n'.join(f.read_text() for f in (ROOT / 'drivers/gpu/drm/apple').glob('*.c')) + assert not re.search(r'\basahi_g15_\w+\s*\(', provider) + good = all(row['pass'] for row in results) + (args.output / 'receipt.json').write_text(json.dumps({'passed': good, + 'stanza_sha256': hashlib.sha256(stanza.encode()).hexdigest(), + 'direct_import_checked': True, 'modpost_or_hardware_claimed': False, 'results': results}, indent=2) + '\n') + print(json.dumps({'passed': good, 'configurations': len(results), 'accepted_g15_linkages': [[r['gpu'], r['display']] for r in results if r['g15_actual'] == 'y']})) + return not good +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/t6030-pmp-graph-tests.c b/tools/asahi/t6030-pmp-graph-tests.c new file mode 100644 index 00000000000000..37fdc54a057d98 --- /dev/null +++ b/tools/asahi/t6030-pmp-graph-tests.c @@ -0,0 +1,803 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Typed host boundaries for the actual T6030 PMP probe/start/consumer graph. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +typedef uint64_t u64; +typedef uint32_t u32; +typedef uint16_t u16; +typedef uint8_t u8; +#define BIT_ULL(n) (1ULL << (n)) +#define __ffs64(v) __builtin_ctzll(v) +#define BIT(n) (1U << (n)) +#define IS_ENABLED(x) (x) +#define CONFIG_APPLE_T6030_GPU_PMP_LINK 1 +#define PMP_REPORT_READY 1 +#define GFP_KERNEL 0 +#define GENPD_FLAG_ACTIVE_WAKEUP 1 +#define MAX_PHANDLE_ARGS 4 +#define EPROBE_DEFER 517 +#define SZ_4K 4096 +#define __iomem +#define __force +#define container_of(p, t, m) ((t *)((char *)(p) - offsetof(t, m))) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define EXPORT_SYMBOL_GPL(x) +#define IS_ERR(p) false +#define PTR_ERR(p) (-ENOMEM) +static void host_log(const char *format, ...) +{ + (void)format; +} +#define dev_err(dev, ...) ((void)(dev), host_log(__VA_ARGS__)) +#define dev_info dev_err +#define dev_warn dev_err +#define dev_err_probe(dev, err, ...) ((void)(dev), (err)) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +struct device_node { + const char *name, *compatible; + bool available, always_on, no_ack, deferred, uuid, soc_record; + u32 reg; + int refs; + struct device_node *parent, *child, *sibling, *pmp; +}; +struct device { + struct device_node *of_node; + struct device *parent; + void *data; +}; +struct platform_device { + struct device dev; +}; +struct generic_pm_domain { + char *name; + int flags; + int (*power_on)(struct generic_pm_domain *), + (*power_off)(struct generic_pm_domain *); +}; +struct apple_pmp_report_offsets { + u32 tgt_read, tgt_write, actual, status, fast_die, fast_die_lanes; + bool starts_pmp; + const char *name, *fallback, *pwrstate; + bool devices_ordered; +}; +struct list_head { + struct list_head *next, *prev; +}; +#define INIT_LIST_HEAD(h) ((h)->next = (h), (h)->prev = (h)) +static void list_add_tail(struct list_head *n, struct list_head *h) +{ + n->prev = h->prev; + n->next = h; + h->prev->next = n; + h->prev = n; +} +static void list_del(struct list_head *n) +{ + n->prev->next = n->next; + n->next->prev = n->prev; + INIT_LIST_HEAD(n); +} +#define list_add_tail_rcu list_add_tail +#define list_for_each_entry(p, h, m) \ + for (struct list_head *cursor = (h)->next; \ + cursor != (h) && \ + ((p) = container_of(cursor, __typeof__(*(p)), m), 1); \ + cursor = cursor->next) +#define list_for_each_entry_rcu list_for_each_entry +struct apple_pmp_start; +struct apple_pmp_report { + struct device *dev; + const struct apple_pmp_report_offsets *offsets; + void *base; + int lock; + struct list_head list; + void *debugfs; + struct apple_pmp_start *start; +}; +struct completion { + bool done; +}; +struct work_struct { + void (*func)(struct work_struct *); + bool pending; +}; +typedef struct { + u8 b[16]; +} uuid_t; +struct apple_pmp_start_ops { + int (*check)(struct apple_pmp_start *, uuid_t *); + int (*enable)(struct apple_pmp_start *); + bool (*bound)(struct apple_pmp_start *); +}; +struct apple_pmp_start_timing { + unsigned int bind, quiet, ready, ack; +}; +struct apple_pmp_start { + struct apple_pmp_report *rep; + struct list_head list; + struct device_node *pmp; + u64 seed, ack, startup_ack, record_seed; + const struct apple_pmp_start_ops *ops; + const struct apple_pmp_start_timing *timing; + struct work_struct work; + bool queued, enabled; + struct completion started; + int result; + bool stopping; + unsigned int waiters; + struct completion waiters_done; +}; +struct apple_pmp_report_entry { + struct generic_pm_domain genpd; + struct device_node *node, *report_node; + u32 id; + bool no_ack, removed; +}; +#define genpd_to_apple_pmp_report_entry(p) \ + container_of(p, struct apple_pmp_report_entry, genpd) +struct of_phandle_iterator { + struct device_node *node; +}; +struct of_phandle_args { + struct device_node *np; + int args_count, args[MAX_PHANDLE_ARGS]; +}; +#define of_for_each_phandle(it, ret, node, ...) for ((ret) = 0; false;) +static int of_phandle_iterator_args(struct of_phandle_iterator *it, int *a, + int max) +{ + (void)it; + (void)a; + (void)max; + return 0; +} +static int of_genpd_add_subdomain(struct of_phandle_args *p, + struct of_phandle_args *c) +{ + (void)p; + (void)c; + return 0; +} +static int pm_genpd_init(struct generic_pm_domain *pd, void *gov, bool off) +{ + (void)pd; + (void)gov; + (void)off; + return 0; +} +static int pm_genpd_remove(struct generic_pm_domain *pd) +{ + (void)pd; + return 0; +} +static void pm_genpd_remove_device(struct device *d) +{ + (void)d; +} +static int of_genpd_add_provider_simple(struct device_node *n, + struct generic_pm_domain *pd) +{ + (void)n; + (void)pd; + return 0; +} +static void of_genpd_del_provider(struct device_node *n) +{ + (void)n; +} +static int apple_pmp_start_mutex, apple_pmp_reports_lock; +struct lock_guard { + int *lock; + bool once; +}; +static struct lock_guard lock_take(int *l) +{ + assert(!*l); + *l = 1; + return (struct lock_guard){ l, true }; +} +static void lock_drop(struct lock_guard *l) +{ + assert(*l->lock); + *l->lock = 0; +} +#define guard(kind) \ + struct lock_guard local_guard \ + __attribute__((cleanup(lock_drop))) = lock_take +#define scoped_guard(kind, lock) \ + for (struct lock_guard scoped \ + __attribute__((cleanup(lock_drop))) = lock_take(lock); \ + scoped.once; scoped.once = false) +static void mutex_lock(int *l) +{ + assert(!*l); + *l = 1; +} +static void mutex_unlock(int *l) +{ + assert(*l); + *l = 0; +} +#define spin_lock_init(l) (*(l) = 0) +#define spin_lock_irqsave(l, f) ((f) = 0, mutex_lock(l)) +#define spin_unlock_irqrestore(l, f) ((void)(f), mutex_unlock(l)) +static void rcu_read_lock(void) +{ +} +static void rcu_read_unlock(void) +{ +} +static struct list_head apple_pmp_starts, apple_pmp_reports; +static struct device_node report_node, pmp_node, entries[4]; +static struct platform_device report_dev, entry_devs[4]; +static u64 regs[0x14000 / 8]; +static u8 ranges[64], devices[17 * 0x7c]; +static struct work_struct *pending; +static unsigned long jiffies; +static unsigned int ack_polls; +#define msecs_to_jiffies(v) (v) +#define time_before(a, b) ((long)((a) - (b)) < 0) +#define time_after(a, b) time_before(b, a) +static void msleep(unsigned int n) +{ + jiffies += n ? n : 1; +} +static void init_completion(struct completion *c) +{ + c->done = false; +} +static void complete_all(struct completion *c) +{ + c->done = true; +} +#define complete complete_all +#define INIT_WORK(w, f) ((w)->func = (f), (w)->pending = false) +#define system_unbound_wq NULL +static bool queue_work(void *q, struct work_struct *w) +{ + assert(!q && !pending); + pending = w; + w->pending = true; + return true; +} +static unsigned long wait_for_completion_timeout(struct completion *c, + unsigned long n) +{ + assert(!apple_pmp_start_mutex); + if (pending) { + struct work_struct *w = pending; + pending = NULL; + w->pending = false; + w->func(w); + } + jiffies++; + return c->done ? n : 0; +} +static void wait_for_completion(struct completion *c) +{ + assert(c->done); +} +static void cancel_work_sync(struct work_struct *w) +{ + if (pending == w) + pending = NULL; + w->pending = false; +} +static u64 readq(const void *a) +{ + return *(const u64 *)a; +} +static void writeq(u64 v, void *a) +{ + assert(a == (char *)regs + 0x108c0); + *(u64 *)a = v; + regs[0x1180 / 8] = v; +} +#define readq_poll_timeout(address, value, condition, delay, timeout) \ + ({ \ + int r = -ETIMEDOUT; \ + ack_polls++; \ + for (int i = 0; i < 4; i++) { \ + (value) = readq(address); \ + if (condition) { \ + r = 0; \ + break; \ + } \ + } \ + (void)(delay); \ + (void)(timeout); \ + r; \ + }) +#define readq_poll_timeout_atomic readq_poll_timeout +static u32 get_unaligned_le32(const void *p) +{ + u32 v; + memcpy(&v, p, 4); + return v; +} +static void put32(u8 *p, u32 v) +{ + memcpy(p, &v, 4); +} +static struct device_node *of_node_get(struct device_node *n) +{ + if (n) + n->refs++; + return n; +} +static void of_node_put(struct device_node *n) +{ + if (n) { + assert(n->refs > 0); + n->refs--; + } +} +static bool of_device_is_available(const struct device_node *n) +{ + return n && n->available; +} +static bool of_device_is_compatible(const struct device_node *n, const char *s) +{ + return n && n->compatible && !strcmp(n->compatible, s); +} +static bool of_machine_is_compatible(const char *s) +{ + return !strcmp(s, "apple,t6030"); +} +static bool of_property_read_bool(const struct device_node *n, const char *p) +{ + if (!strcmp(p, "apple,always-on")) + return n->always_on; + if (!strcmp(p, "apple,no-ack")) + return n->no_ack; + if (!strcmp(p, "apple,defer-startup-ack")) + return n->deferred; + if (!strcmp(p, "apple,soc-device-record")) + return n->soc_record; + return false; +} +static bool of_property_present(const struct device_node *n, const char *p) +{ + if (!strcmp(p, "apple,tunable-uuid")) + return n->uuid; + if (!strcmp(p, "apple,pmp")) + return !!n->pmp; + return false; +} +static int of_property_read_u32(const struct device_node *n, const char *p, + u32 *v) +{ + assert(!strcmp(p, "reg")); + *v = n->reg; + return 0; +} +static int of_property_count_u32_elems(const struct device_node *n, + const char *p) +{ + if (!strcmp(p, "reg")) + return 1; + assert(!strcmp(p, "apple,pmp")); + return n->pmp ? 1 : -EINVAL; +} +static int of_property_read_string(const struct device_node *n, const char *p, + const char **v) +{ + assert(!strcmp(p, "label")); + *v = n->name; + return 0; +} +static const void *of_get_property(const struct device_node *n, const char *p, + int *len) +{ + assert(n == &pmp_node); + if (!strcmp(p, "apple,tunable-ptd-range")) { + *len = sizeof(ranges); + return ranges; + } + assert(!strcmp(p, "apple,tunable-soc-device")); + *len = sizeof(devices); + return devices; +} +static struct device_node *of_parse_phandle(const struct device_node *n, + const char *p, int i) +{ + assert(!i); + if (!strcmp(p, "apple,pmp")) + return of_node_get(n->pmp); + assert(!strcmp(p, "apple,pmp-report")); + return NULL; +} +static struct device_node *of_get_parent(struct device_node *n) +{ + return of_node_get(n->parent); +} +static struct device_node *next_child(struct device_node *p, + struct device_node *old, bool available) +{ + struct device_node *n = old ? old->sibling : p->child; + of_node_put(old); + while (n && available && !n->available) + n = n->sibling; + return of_node_get(n); +} +#define for_each_child_of_node(p, n) \ + for ((n) = next_child(p, NULL, false); (n); \ + (n) = next_child(p, n, false)) +#define for_each_available_child_of_node(p, n) \ + for ((n) = next_child(p, NULL, true); (n); (n) = next_child(p, n, true)) +static struct device_node *find_report(struct device_node *old, const char *c) +{ + of_node_put(old); + return !old && of_device_is_compatible(&report_node, c) ? + of_node_get(&report_node) : + NULL; +} +#define for_each_compatible_node(n, t, c) \ + for ((n) = find_report(NULL, c); (n); (n) = find_report(n, c)) +static void *dev_get_drvdata(struct device *d) +{ + return d->data; +} +static void platform_set_drvdata(struct platform_device *p, void *v) +{ + p->dev.data = v; +} +static void *platform_get_drvdata(struct platform_device *p) +{ + return p->dev.data; +} +static bool device_is_bound(struct device *d) +{ + (void)d; + return false; +} +static bool device_trylock(struct device *d) +{ + (void)d; + return false; +} +static void device_unlock(struct device *d) +{ + (void)d; +} +static void put_device(struct device *d) +{ + (void)d; +} +static struct platform_device *of_find_device_by_node(struct device_node *n) +{ + (void)n; + return NULL; +} +struct action { + void (*f)(void *); + void *p; +}; +static struct action actions[8]; +static unsigned int action_count; +static void *allocations[8]; +static unsigned int allocation_count; +static void *devm_kzalloc(struct device *d, size_t n, int g) +{ + (void)d; + (void)g; + void *v = calloc(1, n); + assert(v); + allocations[allocation_count++] = v; + return v; +} +#define kzalloc_obj(v) calloc(1, sizeof(v)) +#define kfree free +static char *kstrdup(const char *s, int g) +{ + (void)g; + return strdup(s); +} +static int devm_add_action_or_reset(struct device *d, void (*f)(void *), + void *p) +{ + (void)d; + assert(action_count < 8); + actions[action_count++] = (struct action){ f, p }; + return 0; +} +static void *devm_platform_ioremap_resource(struct platform_device *p, int i) +{ + assert(p == &report_dev && !i); + return regs; +} +static const struct apple_pmp_report_offsets * +of_device_get_match_data(struct device *d); +static void apple_pmp_report_release(void *p) +{ + struct apple_pmp_report *r = p; + list_del(&r->list); +} +static void *apple_pmp_report_debugfs; +static int apple_pmp_report_status_fops; +static const char *dev_name(struct device *d) +{ + (void)d; + return "host-report"; +} +static void *debugfs_create_file(const char *n, int mode, void *dir, void *data, + void *ops) +{ + (void)n; + (void)mode; + (void)dir; + (void)data; + (void)ops; + return NULL; +} +static int of_platform_populate(struct device_node *n, void *a, void *b, + struct device *d); +static int check_error, enable_error; +static bool hw_binds, hw_ready; +static u64 hw_ack; +static unsigned int enables, commands; +static int hw_check(struct apple_pmp_start *s, uuid_t *u) +{ + (void)s; + memset(u, 0, sizeof(*u)); + return check_error; +} +static int hw_enable(struct apple_pmp_start *s) +{ + assert(!pmp_node.available); + enables++; + if (!enable_error) + pmp_node.available = true; + (void)s; + return enable_error; +} +static bool hw_bound(struct apple_pmp_start *s) +{ + if (!hw_binds) + return false; + regs[s->rep->offsets->status / 8] = hw_ready ? 1 : 0; + regs[s->rep->offsets->actual / 8] = hw_ack; + return true; +} +static const struct apple_pmp_start_ops apple_pmp_start_hw_ops = { hw_check, + hw_enable, + hw_bound }; +static const struct apple_pmp_start_timing apple_pmp_start_timing = { 2, 0, 2, + 2 }; +#include "production.h" +static const struct apple_pmp_report_offsets * +of_device_get_match_data(struct device *d) +{ + assert(d == &report_dev.dev); + return &apple_pmp_offsets_t6030; +} +static int of_platform_populate(struct device_node *n, void *a, void *b, + struct device *d) +{ + assert(n == &report_node && !a && !b && d == &report_dev.dev); + /* Actual child probe seeds each request while PMP status is still halted. */ + for (unsigned int i = 0; i < 4; i++) { + int r = apple_pmp_report_entry_probe(&entry_devs[i]); + if (r) + return r; + } + return 0; +} +struct overlay_entry { + u32 reg; + bool always_on, no_ack, deferred; +}; +#include "overlay.h" +static void cleanup(void) +{ + for (unsigned int i = 0; i < 4; i++) { + struct apple_pmp_report_entry *e = entry_devs[i].dev.data; + if (e) + apple_pmp_report_entry_free(e); + entry_devs[i].dev.data = NULL; + } + while (action_count) { + struct action a = actions[--action_count]; + a.f(a.p); + } + for (unsigned int i = 0; i < allocation_count; i++) + free(allocations[i]); + allocation_count = 0; + assert(!report_node.refs && !pmp_node.refs); + for (unsigned int i = 0; i < 4; i++) + assert(!entries[i].refs); + assert(!apple_pmp_start_mutex && !apple_pmp_reports_lock && !pending); +} +static struct apple_pmp_report *setup(void) +{ + INIT_LIST_HEAD(&apple_pmp_starts); + INIT_LIST_HEAD(&apple_pmp_reports); + memset(regs, 0, sizeof(regs)); + memset(ranges, 0, sizeof(ranges)); + memset(devices, 0, sizeof(devices)); + report_node = + (struct device_node){ .name = "report", + .compatible = "apple,t6030-pmp-v2-report", + .available = true, + .child = &entries[0], + .pmp = &pmp_node }; + pmp_node = (struct device_node){ .name = "PMP", + .compatible = "apple,t6000-pmp-v2", + .uuid = true }; + for (unsigned int i = 0; i < 4; i++) { + const struct overlay_entry *o = &overlay_entries[i]; + entries[i] = (struct device_node){ + .name = "entry", + .compatible = "apple,t6000-pmp-v2-report-entry", + .available = true, + .reg = o->reg, + .always_on = o->always_on, + .no_ack = o->no_ack, + .deferred = o->deferred, + .parent = &report_node, + .sibling = i < 3 ? &entries[i + 1] : NULL + }; + entry_devs[i] = (struct platform_device){ + .dev = { .of_node = &entries[i], + .parent = &report_dev.dev } + }; + } + report_dev = + (struct platform_device){ .dev = { .of_node = &report_node } }; + put32(ranges, 10); + put32(ranges + 4, 0x118); + put32(ranges + 8, 4); + put32(ranges + 32, 11); + put32(ranges + 36, 0x11c); + put32(ranges + 40, 4); + for (unsigned int i = 0; i < 17; i++) { + put32(devices + i * 0x7c, i + 1); + if (i >= 7 && i <= 9) + put32(devices + i * 0x7c + 8, 2); + } + ack_polls = 0; + check_error = enable_error = 0; + hw_binds = hw_ready = true; + hw_ack = BIT_ULL(7); + enables = commands = 0; + return NULL; +} +static int g15_vote(void) +{ + struct device supplier = { .of_node = &pmp_node }; + /* Scoped supplier has its first, more specific compatible as on the real DT. */ + pmp_node.compatible = "apple,t6030-pmp-v2"; + int ret = apple_pmp_report_wait_supplier_ready(&supplier, 5000); + if (!ret) + commands++; + return ret; +} +int main(void) +{ + unsigned int cases = 0; + (void)apple_pmp_start_init; + (void)apple_pmp_report_wait_t6030_14; + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + struct apple_pmp_report *r = report_dev.dev.data; + /* The old passive descriptor fails the real DCP entry waiter here. */ + if (!r->start) + assert(apple_pmp_report_wait_ready(&entries[0], 30000) == 0); + assert(r->start); + assert(r->start->seed == + (BIT_ULL(7) | BIT_ULL(8) | BIT_ULL(9) | BIT_ULL(16))); + assert(r->start->ack == (BIT_ULL(7) | BIT_ULL(8) | BIT_ULL(9)) && + r->start->startup_ack == BIT_ULL(7)); + assert(!pmp_node.available && regs[0x10 / 8] == 0 && enables == 0); + assert(regs[0x1180 / 8] == r->start->seed); + assert(((struct apple_pmp_report_entry *)entry_devs[3].dev.data) + ->no_ack); + assert(apple_pmp_report_wait_ready(&entries[0], 30000) == 0 && + enables == 1 && pmp_node.available); + assert(g15_vote() == 0 && commands == 1 && enables == 1); + cases++; + assert(apple_pmp_report_wait_ready(&entries[1], 3000) == -EIO); + cases++; + regs[0x11c0 / 8] |= BIT_ULL(8); + assert(apple_pmp_report_wait_ready(&entries[1], 3000) == 0); + cases++; + assert(apple_pmp_report_wait_ready(&entries[3], 3000) == -EINVAL); + cases++; + unsigned int polls = ack_polls; + struct apple_pmp_report_entry *storage = entry_devs[3].dev.data; + assert(apple_pmp_report_entry_power_on(&storage->genpd) == 0 && + ack_polls == polls); + cases++; + regs[0x11c0 / 8] &= ~BIT_ULL(7); + assert(g15_vote() == -EIO && commands == 1); + cases++; + cleanup(); + /* Missing display acknowledgement cannot release G15, even if bound+READY. */ + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + hw_ack = BIT_ULL(8); + assert(apple_pmp_report_wait_ready(&entries[1], 3000) == -EIO); + cases++; + assert(g15_vote() == -EIO && commands == 0 && enables == 1); + cases++; + cleanup(); + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + hw_ready = false; + assert(g15_vote() == -ETIMEDOUT && commands == 0); + cases++; + cleanup(); + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + hw_binds = false; + assert(g15_vote() == -ETIMEDOUT && commands == 0); + cases++; + cleanup(); + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + check_error = -EIO; + assert(g15_vote() == -EIO && !enables && !pmp_node.available); + cases++; + cleanup(); + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + enable_error = -EINVAL; + assert(g15_vote() == -EINVAL && enables == 1 && !pmp_node.available); + cases++; + cleanup(); + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + regs[0x1180 / 8] = 0; + assert(g15_vote() == -EBUSY && !enables); + cases++; + cleanup(); + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + regs[0x10 / 8] = 1; + assert(g15_vote() == -EBUSY && !enables); + cases++; + cleanup(); + /* No valid handoff means no startup owner; a bound report isn't enough. */ + setup(); + pmp_node.uuid = false; + assert(apple_pmp_report_probe(&report_dev) == 0); + assert(!((struct apple_pmp_report *)report_dev.dev.data)->start); + assert(g15_vote() == -ENODEV && !enables); + cases++; + cleanup(); + /* A drained managed owner is unavailable even while the report stays bound. */ + setup(); + assert(apple_pmp_report_probe(&report_dev) == 0); + r = report_dev.dev.data; + assert(action_count == 2 && actions[1].p == r->start); + action_count--; + apple_pmp_start_drain(r->start); + assert(g15_vote() == -ENODEV && commands == 0 && !enables); + cases++; + cleanup(); + /* Actual describe rejects malformed handoff layouts before any enable. */ + setup(); + put32(ranges + 4, 0x100); + assert(apple_pmp_report_probe(&report_dev) == 0); + assert(g15_vote() == -EINVAL && commands == 0 && !enables); + cases++; + cleanup(); + setup(); + put32(devices + 16 * 0x7c + 8, 2); + assert(apple_pmp_report_probe(&report_dev) == 0); + assert(g15_vote() == -EINVAL && commands == 0 && !enables); + cases++; + cleanup(); + printf("PASS: %u actual overlay/probe/entry/DCP7/managed-start/supplier graph cases\n", + cases); + return 0; +} diff --git a/tools/asahi/t6030-pmp-graph-tests.py b/tools/asahi/t6030-pmp-graph-tests.py new file mode 100644 index 00000000000000..dcef7dcc4c2504 --- /dev/null +++ b/tools/asahi/t6030-pmp-graph-tests.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Execute the actual report probe -> entry seed -> DCP -> PMP -> G15 graph. + +The actual overlay supplies the report entries. OF storage, allocation, MMIO, +workqueue execution and the PMP hardware operations are typed host boundaries. +The production probe, descriptor validation, startup, waiter and supplier/command +bodies are extracted verbatim. This is not a firmware or hardware test. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import subprocess +from importlib.machinery import SourceFileLoader +ROOT = Path(__file__).resolve().parents[2] +extract = SourceFileLoader('supplier_test', str(ROOT / 'tools/asahi/t6030-pmp-supplier-tests.py')).load_module() + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--ref', help='read report source at a Git ref (negative control)') + p.add_argument('--mutations', action='store_true') + p.add_argument('--output', required=True, type=Path) + args = p.parse_args(); args.output.mkdir(parents=True, exist_ok=False) + source = subprocess.check_output(['git', '-C', str(ROOT), 'show', args.ref + ':' + extract.REPORT], text=True) if args.ref else (ROOT / extract.REPORT).read_text() + overlay = (ROOT / 'drivers/soc/apple/t6030-pmp.dtso').read_text() + entries = [] + for node in re.findall(r'report@[0-9a-f]+\s*\{(.*?)\n\s*\};', overlay, re.S): + reg = int(re.search(r'reg = <(0x[0-9a-f]+|[0-9]+)>', node)[1], 0) + entries.append((reg, 'apple,always-on;' in node, 'apple,no-ack;' in node, 'apple,defer-startup-ack;' in node)) + assert len(entries) == 4 + entry_data = ',\n'.join('{%d, %d, %d, %d}' % e for e in entries) + names = ['static int apple_pmp_report_bit(', 'static int apple_pmp_start_check_layout(', + 'static int apple_pmp_start_describe(', 'static void apple_pmp_start_finish(', + 'static bool apple_pmp_start_stopping(', 'static void apple_pmp_start_work(', + 'static void apple_pmp_start_drain(', 'static int apple_pmp_start_init(', + 'static int apple_pmp_start_wait(', 'int apple_pmp_report_wait_ready(', + 'static int apple_pmp_report_set_state(', 'static int apple_pmp_report_entry_set_state(', + 'static int apple_pmp_report_entry_power_on(', 'static int apple_pmp_report_entry_power_off(', + 'static void apple_pmp_report_entry_free(', 'static int apple_pmp_report_entry_probe(', + 'static int apple_pmp_report_probe(', 'static struct device_node *apple_pmp_report_t6030_entry(', + 'static int apple_pmp_report_wait_t6030_14(', 'int apple_pmp_report_wait_supplier_ready('] + if 'static int apple_pmp_report_wait_t6030_bound(' in source: + names.insert(names.index('static struct device_node *apple_pmp_report_t6030_entry('), 'static int apple_pmp_report_wait_t6030_bound(') + offsets = re.search(r'static const struct apple_pmp_report_offsets apple_pmp_offsets_t6030 = \{.*?\n\};', source, re.S)[0] + functions = '\n'.join(extract.function(source, n) for n in names) + validation = re.sub(r'^#include .*\n', '', (ROOT / 'drivers/pmdomain/apple/pmp-report-validation.h').read_text(), flags=re.M) + code = offsets + '\n' + validation + '\n' + functions + # The actual overlay must still describe a halted supplier and disabled DMA/mailbox. + assert overlay.count('status = \"disabled\";') >= 3 + (args.output / 'production.h').write_text(code) + (args.output / 'overlay.h').write_text('static const struct overlay_entry overlay_entries[] = {\n' + entry_data + '\n};\n') + compiler = shlex.split(os.environ.get('CC', 'clang')) + command = compiler + ['-std=gnu11', '-g', '-O1', '-Wall', '-Wextra', '-Werror', + '-fsanitize=address,undefined', '-fno-omit-frame-pointer', + '-I', str(args.output), str(ROOT / 'tools/asahi/t6030-pmp-graph-tests.c'), + '-o', str(args.output / 'graph')] + result = subprocess.run(command, capture_output=True, text=True) + (args.output / 'build.log').write_text(result.stdout + result.stderr) + if result.returncode: + print(result.stderr); return 1 + result = subprocess.run([str(args.output / 'graph')], capture_output=True, text=True) + (args.output / 'run.log').write_text(result.stdout + result.stderr) + print(result.stdout + result.stderr) + mutations = [] + if args.mutations: + controls = [ + ('no-managed-owner', '.starts_pmp = IS_ENABLED(CONFIG_APPLE_T6030_GPU_PMP_LINK)', '.starts_pmp = false'), + ('no-managed-probe', 'ret = apple_pmp_start_init(rep);', 'ret = 0; (void)apple_pmp_start_init;'), + ('no-child-seeding', 'apple_pmp_report_entry_set_state(&ent->genpd, true);', '(void)0;'), + ('no-storage-policy', 'ent->no_ack = of_property_read_bool(node, "apple,no-ack");', 'ent->no_ack = false;'), + ('external-startup-ack', '!of_property_read_bool(child, "apple,defer-startup-ack")', 'true'), + ('ignore-seeded-state', 'status || request != st->seed', 'status'), + ('ignore-halted-state', 'status || request != st->seed', 'request != st->seed'), + ('ignore-safety-check', 'ret = st->ops->check(st, &image);', 'ret = 0; (void)image;'), + ('ignore-startup-ack', '(ack & st->startup_ack) != st->startup_ack', 'false'), + ('ignore-entry-ack', 'status == PMP_REPORT_READY && (ack & BIT_ULL(id))', '((void)ack, status == PMP_REPORT_READY)'), + ('storage-ack-layout', 'st->ack & ~st->record_seed,', 'st->seed & ~st->record_seed,'), + ('skip-supplier-wait', 'apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms))', '((void)timeout_ms, 0)'), + ] + for name, old, new in controls: + assert code.count(old) == 1, (name, code.count(old)) + (args.output / 'production.h').write_text(code.replace(old, new)) + built = subprocess.run(command, capture_output=True, text=True) + # A mutant must compile; compilation failure is not regression evidence. + ran = subprocess.run([str(args.output / 'graph')], capture_output=True, text=True) if not built.returncode else None + (args.output / (name + '.log')).write_text(built.stdout + built.stderr + (ran.stdout + ran.stderr if ran else '')) + mutations.append({'name': name, 'build_rc': built.returncode, 'run_rc': ran.returncode if ran else None}) + (args.output / 'production.h').write_text(code) + assert all(m['build_rc'] == 0 and m['run_rc'] != 0 for m in mutations), mutations + (args.output / 'receipt.json').write_text(json.dumps({'source_ref': args.ref, 'source_sha256': hashlib.sha256(code.encode()).hexdigest(), + 'overlay_sha256': hashlib.sha256(overlay.encode()).hexdigest(), 'overlay_entries': entries, + 'command': command, 'returncode': result.returncode, 'mutations': mutations}, indent=2) + '\n') + return bool(result.returncode) +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/t6030-pmp-supplier-tests.c b/tools/asahi/t6030-pmp-supplier-tests.c new file mode 100644 index 00000000000000..b581f3863a2323 --- /dev/null +++ b/tools/asahi/t6030-pmp-supplier-tests.c @@ -0,0 +1,690 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Host boundaries for the extracted T6030 PMP selection and power bridge. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#define __init +#define IS_ENABLED(x) (x) +#define EPROBE_DEFER 517 +#define PMP_REPORT_READY 1 +#define DL_FLAG_AUTOREMOVE_CONSUMER 1 +#define BIT_ULL(n) (1ULL << (n)) +typedef uint64_t u64; +typedef uint32_t u32; +typedef uint16_t u16; +typedef uint8_t u8; +struct device_node { + const char *compatible; + bool available, has_reg, has_pmp, has_report, no_ack; + int reg_cells, pmp_cells, report_cells, refs; + u32 reg, phandle; + struct device_node *pmp, *report, *child, *sibling, *parent; +}; +struct device { + struct device_node *of_node; + int refs; + bool bound; +}; +struct platform_device { + struct device dev; +}; +struct device_link { + int unused; +}; +struct of_changeset { + int unused; +}; +struct gate_soc { + int id; +}; +struct apple_pmp_report_offsets { + unsigned int status, actual, tgt_read, tgt_write; + bool starts_pmp, devices_ordered; + const char *name, *fallback, *pwrstate; +}; +struct apple_pmp_report { + void *base; + const struct apple_pmp_report_offsets *offsets; + struct device *dev; + void *start; + struct apple_pmp_report *next; +}; +struct completion { + bool done; +}; +struct apple_pmp_start { + struct apple_pmp_report *rep; + struct apple_pmp_start *next; + bool stopping; + unsigned int waiters; + bool queued; + int result, work; + u64 ack; + struct completion started, waiters_done; +}; +struct host_list { + void *first; +}; +static struct host_list apple_pmp_starts, apple_pmp_reports; +static int apple_pmp_start_mutex; +#define list_for_each_entry(it, head, member) \ + for ((it) = (head)->first; (it); (it) = (it)->next) +#define list_for_each_entry_rcu(it, head, member) \ + list_for_each_entry(it, head, member) +static int rcu_depth; +static void rcu_read_lock(void) +{ + assert(!rcu_depth++); +} +static void rcu_read_unlock(void) +{ + assert(rcu_depth-- == 1); +} +static int apple_pmp_report_bit(struct apple_pmp_start *st, + struct device_node *entry, u32 *id, + bool *record) +{ + (void)st; + *id = entry->reg; + *record = false; + return 0; +} +static struct apple_pmp_start managed_start; +static int ready_result, start_calls; +#define msecs_to_jiffies(n) (n) +#define system_unbound_wq NULL +static bool wait_for_completion_timeout(struct completion *c, + unsigned long timeout) +{ + assert(timeout > 0); + return c->done; +} +static void complete(struct completion *c) +{ + c->done = true; +} +static void queue_work(void *wq, int *work); +static const struct gate_soc gate_t6030 = { 6030 }, gate_t8122 = { 8122 }, + other_soc = { 0 }; +static const struct gate_soc *gate_soc; +static struct device_node supplier_node, other_node, gpu, extra_gpu; +static struct device_node report14, extra_report, report25, entry7, entry17; +static struct device_node *nodes[9]; +static struct device supplier, consumer; +static struct platform_device native_report, passive_report; +static struct device_link link; +static struct apple_pmp_report_offsets native_offsets; +static u64 status_word; +static struct apple_pmp_report native_rep, passive_rep; +static u64 passive_words[0x14000 / sizeof(u64)]; +static bool passive_present, passive_lockable, passive_data; + +static const char *machine; +static const void *pmp_data; +static struct device *pmp_device; +static int pmp_lock, ready_calls, add_calls, add_result; +static int poll_calls, device_locked, power_calls, power_result, link_calls; +static int find_calls, lockable, present_device, link_ok; +static int case_count; + +static struct device_node *of_node_get(struct device_node *node) +{ + if (node) + node->refs++; + return node; +} +static void of_node_put(struct device_node *node) +{ + if (node) { + assert(node->refs > 0); + node->refs--; + } +} +static bool of_device_is_compatible(const struct device_node *node, + const char *name) +{ + return node && node->compatible && !strcmp(node->compatible, name); +} +static bool of_device_is_available(const struct device_node *node) +{ + return node && node->available; +} +static bool of_machine_is_compatible(const char *name) +{ + return !strcmp(machine, name); +} +static struct device_node *of_find_compatible_node(struct device_node *from, + const char *type, + const char *compat) +{ + size_t i = 0; + + assert(!type); + find_calls++; + if (from) { + for (; i < sizeof(nodes) / sizeof(nodes[0]); i++) + if (nodes[i] == from) { + i++; + break; + } + of_node_put(from); + } + for (; i < sizeof(nodes) / sizeof(nodes[0]); i++) + if (of_device_is_compatible(nodes[i], compat)) + return of_node_get(nodes[i]); + return NULL; +} +#define for_each_compatible_node(np, type, compat) \ + for ((np) = of_find_compatible_node(NULL, type, compat); (np); \ + (np) = of_find_compatible_node(np, type, compat)) +static struct device_node *of_get_next_child(struct device_node *parent, + struct device_node *old) +{ + struct device_node *next = old ? old->sibling : parent->child; + + of_node_put(old); + return of_node_get(next); +} +#define for_each_child_of_node(parent, child) \ + for ((child) = of_get_next_child(parent, NULL); (child); \ + (child) = of_get_next_child(parent, child)) +static bool of_property_present(const struct device_node *node, + const char *prop) +{ + if (!strcmp(prop, "apple,pmp")) + return node->has_pmp; + assert(!strcmp(prop, "apple,pmp-report")); + return node->has_report; +} +static bool of_property_read_bool(const struct device_node *node, + const char *prop) +{ + assert(!strcmp(prop, "apple,no-ack")); + return node->no_ack; +} +static int of_property_count_u32_elems(const struct device_node *node, + const char *prop) +{ + if (!strcmp(prop, "reg")) + return node->has_reg ? node->reg_cells : -EINVAL; + assert(!strcmp(prop, "apple,pmp")); + return node->has_pmp ? node->pmp_cells : -EINVAL; +} +static int of_property_read_u32(const struct device_node *node, + const char *prop, u32 *value) +{ + assert(!strcmp(prop, "reg")); + if (!node->has_reg || node->reg_cells < 1) + return -EINVAL; + *value = node->reg; + return 0; +} +static struct device_node *of_parse_phandle(struct device_node *node, + const char *prop, int index) +{ + assert(!index); + if (!strcmp(prop, "apple,pmp")) + return node->has_pmp && node->pmp_cells >= 1 ? + of_node_get(node->pmp) : + NULL; + assert(!strcmp(prop, "apple,pmp-report")); + return node->has_report && node->report_cells >= 1 ? + of_node_get(node->report) : + NULL; +} +static int of_changeset_add_prop_u32(struct of_changeset *cs, + struct device_node *node, const char *prop, + u32 value) +{ + assert(cs && node == &gpu && !strcmp(prop, "apple,pmp")); + assert(value == supplier_node.phandle); + add_calls++; + return add_result; +} +static struct device_node *of_get_parent(struct device_node *node) +{ + return of_node_get(node->parent); +} +static struct platform_device *of_find_device_by_node(struct device_node *node) +{ + struct platform_device *pdev; + + assert(node == &report25 || node == &report14); + if (node == &report25) { + if (!present_device) + return NULL; + pdev = &native_report; + } else { + if (!passive_present) + return NULL; + pdev = &passive_report; + } + pdev->dev.refs++; + return pdev; +} +static bool device_trylock(struct device *dev) +{ + assert(!device_locked); + assert(dev == &native_report.dev || dev == &passive_report.dev); + if (dev == &native_report.dev ? !lockable : !passive_lockable) + return false; + device_locked = dev == &native_report.dev ? 1 : 2; + return true; +} +static void device_unlock(struct device *dev) +{ + assert(device_locked == (dev == &native_report.dev ? 1 : 2)); + device_locked = 0; +} +static bool device_is_bound(const struct device *dev) +{ + return dev->bound; +} +static struct apple_pmp_report * +platform_get_drvdata(struct platform_device *pdev) +{ + assert(device_locked == (pdev == &native_report ? 1 : 2)); + return pdev == &native_report ? &native_rep : + passive_data ? &passive_rep : + NULL; +} +static u64 readq(const void *address) +{ + if (!device_locked) { + assert(apple_pmp_start_mutex && managed_start.waiters); + } else { + assert(device_locked == 1 && native_report.dev.refs > 0); + } + return *(const u64 *)address; +} +#define readq_poll_timeout(address, value, condition, delay, timeout) \ + ({ \ + int poll_ret = -ETIMEDOUT; \ + assert(device_locked && (delay) == 1000 && \ + (timeout) == 5000000); \ + if (device_locked == 2) \ + ready_calls++; \ + else \ + poll_calls++; \ + for (int poll_i = 0; poll_i < 4; poll_i++) { \ + (value) = readq(address); \ + if (condition) { \ + poll_ret = 0; \ + break; \ + } \ + } \ + poll_ret; \ + }) +static struct device *get_device(struct device *dev) +{ + dev->refs++; + return dev; +} +static void put_device(struct device *dev) +{ + assert(dev->refs > 0); + dev->refs--; +} +static struct device_link * +device_link_add(struct device *con, struct device *sup, unsigned int flags) +{ + assert(con == &consumer && sup == &supplier && sup->refs > 0); + assert(flags == DL_FLAG_AUTOREMOVE_CONSUMER && !pmp_lock); + link_calls++; + return link_ok ? &link : NULL; +} +struct lock_guard { + int *lock; + bool once; +}; +static struct lock_guard lock_take(int *lock) +{ + assert(!*lock); + *lock = 1; + return (struct lock_guard){ lock, true }; +} +static void lock_drop(struct lock_guard *guard) +{ + assert(*guard->lock == 1); + *guard->lock = 0; +} +#define guard(kind) \ + struct lock_guard local_guard \ + __attribute__((cleanup(lock_drop))) = lock_take +#define scoped_guard(kind, lock) \ + for (struct lock_guard scoped \ + __attribute__((cleanup(lock_drop))) = lock_take(lock); \ + scoped.once; scoped.once = false) +static int apple_pmp_send_power_command(const void *data, u8 command, u16 id, + u32 enabled) +{ + assert(data == pmp_data && command == 0x0f && id == 5 && enabled == 1); + assert(pmp_lock == 1 && (start_calls == 1 || poll_calls == 1)); + power_calls++; + return power_result; +} +static void queue_work(void *wq, int *work) +{ + assert(!wq && work == &managed_start.work && apple_pmp_start_mutex); + /* Firmware boundary: no READY is fabricated by the readiness reader. */ + start_calls++; + managed_start.result = ready_result; + managed_start.started.done = true; +} +#include "t6030-pmp-production.h" + +static void balanced(void) +{ + for (size_t i = 0; i < sizeof(nodes) / sizeof(nodes[0]); i++) + assert(!nodes[i]->refs); + assert(!managed_start.waiters); + assert(!supplier.refs && !consumer.refs && !native_report.dev.refs && + !passive_report.dev.refs); + assert(!apple_pmp_start_mutex && !rcu_depth); + assert(!pmp_lock && !device_locked); +} +static void reset(void) +{ + balanced(); + supplier_node = + (struct device_node){ .compatible = "apple,t6030-pmp-v2", + .phandle = 10 }; + other_node = (struct device_node){ .compatible = "apple,t6030-pmp-v2", + .phandle = 11 }; + gpu = (struct device_node){ .compatible = "apple,agx-t6030", + .available = true }; + extra_gpu = (struct device_node){ 0 }; + report14 = + (struct device_node){ .compatible = "apple,t6030-pmp-v2-report", + .available = true, + .has_pmp = true, + .pmp_cells = 1, + .pmp = &supplier_node, + .child = &entry17 }; + extra_report = (struct device_node){ 0 }; + report25 = (struct device_node){ + .compatible = "apple,j613-25g83-pmp-report", .available = true + }; + entry7 = + (struct device_node){ .compatible = + "apple,t6000-pmp-v2-report-entry", + .available = true, + .has_reg = true, + .reg_cells = 1, + .reg = 7, + .parent = &report14 }; + entry17 = + (struct device_node){ .compatible = + "apple,t6000-pmp-v2-report-entry", + .available = true, + .has_reg = true, + .reg_cells = 1, + .reg = 17, + .sibling = &entry7, + .parent = &report14 }; + supplier = (struct device){ .of_node = &supplier_node, .bound = true }; + consumer = (struct device){ .of_node = &gpu }; + native_report = (struct platform_device){ .dev = { .of_node = &report25, + .bound = true } }; + native_rep = (struct apple_pmp_report){ .base = &status_word, + .offsets = &native_offsets, + .dev = &native_report.dev }; + passive_report = (struct platform_device){ + .dev = { .of_node = &report14, .bound = true } + }; + passive_rep = + (struct apple_pmp_report){ .base = passive_words, + .offsets = &apple_pmp_offsets_t6030, + .dev = &passive_report.dev }; + memset(passive_words, 0, sizeof(passive_words)); + passive_words[apple_pmp_offsets_t6030.status / 8] = PMP_REPORT_READY; + passive_words[apple_pmp_offsets_t6030.actual / 8] = BIT_ULL(7); + passive_present = passive_lockable = passive_data = true; + managed_start = (struct apple_pmp_start){ .rep = &passive_rep, + .ack = BIT_ULL(7) }; + passive_rep.start = &managed_start; + apple_pmp_starts.first = + CONFIG_APPLE_T6030_GPU_PMP_LINK ? &managed_start : NULL; + ready_result = start_calls = 0; + apple_pmp_reports.first = &passive_rep; + machine = "apple,t6030"; + gate_soc = &gate_t6030; + pmp_device = &supplier; + pmp_data = (void *)1; + ready_calls = add_calls = add_result = poll_calls = 0; + power_calls = power_result = link_calls = find_calls = 0; + lockable = present_device = link_ok = 1; + status_word = PMP_REPORT_READY; +} +static int power(void) +{ + return apple_pmp_set_device_power(0x0f, 5, 1); +} +#define RUN(change, result, ready, sent) \ + do { \ + reset(); \ + change; \ + assert(power() == (result)); \ + assert(ready_calls == (ready) && power_calls == (sent)); \ + balanced(); \ + case_count++; \ + } while (0) +int main(void) +{ + struct device_node *initial[] = { + &supplier_node, &other_node, &gpu, &extra_gpu, &report14, + &extra_report, &report25, &entry7, &entry17 + }; + memcpy(nodes, initial, sizeof(nodes)); + /* Keep host boundary functions available when a mutant removes a call. */ + (void)apple_pmp_report_wait_ready; + (void)complete; + (void)of_machine_is_compatible; + (void)of_property_read_bool; + (void)of_property_present; + (void)gate_find_one; + (void)apple_pmp_report_t6030_entry; + (void)apple_pmp_report_wait_t6030_14; + reset(); + assert(apple_pmp_offsets_t6030.starts_pmp == + !!CONFIG_APPLE_T6030_GPU_PMP_LINK); +#if CONFIG_APPLE_T6030_GPU_PMP_LINK + assert(apple_pmp_report_wait_ready(&entry7, 10000) == 0 && + start_calls == 1); + balanced(); + case_count++; + RUN((void)0, 0, 0, 1); + RUN(report14.child = &entry7; entry7.sibling = &entry17; + entry17.sibling = NULL, 0, 0, 1); + RUN(apple_pmp_starts.first = NULL, -ENODEV, 0, 0); + RUN(apple_pmp_starts.first = NULL; + apple_pmp_reports.first = NULL, -EPROBE_DEFER, 0, 0); + RUN(managed_start.stopping = true, -ENODEV, 0, 0); + RUN(ready_result = -ETIMEDOUT, -ETIMEDOUT, 0, 0); + RUN(ready_result = -EINVAL, -EINVAL, 0, 0); + RUN(passive_words[apple_pmp_offsets_t6030.status / 8] = 0, -EIO, 0, 0); + RUN(passive_words[apple_pmp_offsets_t6030.status / 8] = 3, -EIO, 0, 0); + RUN(passive_words[apple_pmp_offsets_t6030.actual / 8] = 0, -EIO, 0, 0); + RUN(passive_words[apple_pmp_offsets_t6030.actual / 8] = BIT_ULL(8), + -EIO, 0, 0); + RUN(passive_words[apple_pmp_offsets_t6030.actual / 8] |= BIT_ULL(9), 0, + 0, 1); + RUN(power_result = -EIO, -EIO, 0, 1); + RUN(machine = "apple,t8122", -ENODEV, 0, 0); + RUN(machine = "apple,t6031", -ENODEV, 0, 0); + RUN(machine = "apple,t8140", -ENODEV, 0, 0); + RUN(supplier_node.compatible = "apple,t8122-pmp-v2", -ENODEV, 0, 0); + RUN(report14.compatible = NULL, -ENODEV, 0, 0); + RUN(extra_report = report14, -ENODEV, 0, 0); + RUN(extra_report = report14; + extra_report.available = false, -ENODEV, 0, 0); + RUN(report14.available = false, -ENODEV, 0, 0); + RUN(report14.has_pmp = false, -ENODEV, 0, 0); + RUN(report14.pmp_cells = 0, -ENODEV, 0, 0); + RUN(report14.pmp_cells = 2, -ENODEV, 0, 0); + RUN(report14.pmp = NULL, -ENODEV, 0, 0); + RUN(report14.pmp = &other_node, -ENODEV, 0, 0); + RUN(entry17.sibling = NULL, -ENODEV, 0, 0); + RUN(entry7.has_reg = false, -ENODEV, 0, 0); + RUN(entry7.reg_cells = 0, -ENODEV, 0, 0); + RUN(entry7.reg_cells = 2, -ENODEV, 0, 0); + RUN(entry7.reg = 8, -ENODEV, 0, 0); + RUN(entry7.available = false, -ENODEV, 0, 0); + RUN(entry7.compatible = "apple,other", -ENODEV, 0, 0); + RUN(entry7.no_ack = true, -ENODEV, 0, 0); + RUN(entry17.reg = 7, -ENODEV, 0, 0); + RUN(entry17.reg = 7; entry17.available = false, -ENODEV, 0, 0); +#else + RUN((void)0, -ENODEV, 0, 0); + assert(!find_calls); +#endif + /* T8122 current14 remains unsupported by this supplier API. */ + RUN(machine = "apple,t8122"; + supplier_node.compatible = "apple,t8122-pmp-v2", -ENODEV, 0, 0); + /* A declared report, including malformed/unresolved data, never falls back. */ + RUN(supplier_node.has_report = true; + supplier_node.report_cells = 0, -ENODEV, 0, 0); + RUN(supplier_node.has_report = true; + supplier_node.report_cells = 1, -ENODEV, 0, 0); + RUN(supplier_node.has_report = true; supplier_node.report_cells = 1; + supplier_node.report = &report14, -ENODEV, 0, 0); + /* Native25 dispatch is untouched, even on another machine/config. */ + RUN(supplier_node.has_report = true; supplier_node.report_cells = 1; + supplier_node.report = &report25; machine = "apple,t8122", 0, 0, 1); + assert(poll_calls == 1); + /* Preserve the existing native25 first-phandle behaviour as well. */ + RUN(supplier_node.has_report = true; supplier_node.report_cells = 2; + supplier_node.report = &report25, 0, 0, 1); + RUN(supplier_node.has_report = true; supplier_node.report_cells = 1; + supplier_node.report = &report25; + present_device = 0, -EPROBE_DEFER, 0, 0); + RUN(supplier_node.has_report = true; supplier_node.report_cells = 1; + supplier_node.report = &report25; + lockable = 0, -EPROBE_DEFER, 0, 0); + RUN(supplier_node.has_report = true; supplier_node.report_cells = 1; + supplier_node.report = &report25; + native_report.dev.bound = false, -EPROBE_DEFER, 0, 0); + RUN(supplier_node.has_report = true; supplier_node.report_cells = 1; + supplier_node.report = &report25; + status_word = 0, -ETIMEDOUT, 0, 0); + RUN(pmp_data = NULL, -ENODEV, 0, 0); + /* GPU phandle changes are scoped, preserve existing good links, and fail closed. */ + for (int soc = 0; soc < 3; soc++) { + struct of_changeset cs; + reset(); + gate_soc = soc == 0 ? &gate_t8122 : + soc == 1 ? &gate_t6030 : + &other_soc; + gpu.compatible = soc == 0 ? "apple,agx-t8122" : + "apple,agx-t6030"; + int active = soc == 0 || + (soc == 1 && CONFIG_APPLE_T6030_GPU_PMP_LINK); + assert(gate_gpu_pmp_link(&cs, &supplier_node) == 0 && + add_calls == active); + balanced(); + case_count++; + add_calls = 0; + gpu.has_pmp = true; + gpu.pmp_cells = 1; + gpu.pmp = &supplier_node; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == 0 && + !add_calls); + balanced(); + case_count++; + gpu.pmp = &other_node; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == + (active ? -EINVAL : 0)); + balanced(); + case_count++; + } + reset(); + struct of_changeset cs; +#if CONFIG_APPLE_T6030_GPU_PMP_LINK + gpu.has_pmp = true; + gpu.pmp_cells = 2; + gpu.pmp = &supplier_node; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == -EINVAL && !add_calls); + balanced(); + case_count++; + reset(); + gpu.has_pmp = true; + gpu.pmp_cells = 1; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == -EINVAL && !add_calls); + balanced(); + case_count++; + reset(); + extra_gpu = gpu; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == 0 && !add_calls); + balanced(); + case_count++; + reset(); + supplier_node.phandle = 0; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == -EINVAL && !add_calls); + balanced(); + case_count++; + reset(); + assert(gate_gpu_pmp_link(&cs, NULL) == -EINVAL && !add_calls); + balanced(); + case_count++; + reset(); + add_result = -ENOMEM; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == -ENOMEM && + add_calls == 1); + balanced(); + case_count++; + reset(); + gpu.available = false; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == 0 && !add_calls); + balanced(); + case_count++; + reset(); + gpu.compatible = NULL; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == 0 && !add_calls); + balanced(); + case_count++; +#else + assert(gate_gpu_pmp_link(&cs, &supplier_node) == 0 && !find_calls); + balanced(); + case_count++; +#endif + /* Existing T8122 linking keeps its original first-phandle semantics. */ + reset(); + gate_soc = &gate_t8122; + gpu.compatible = "apple,agx-t8122"; + gpu.has_pmp = true; + gpu.pmp_cells = 2; + gpu.pmp = &supplier_node; + assert(gate_gpu_pmp_link(&cs, &supplier_node) == 0 && !add_calls); + balanced(); + case_count++; + /* Actual existing consumer link uses the exact supplier and balances refs. */ + reset(); + gpu.has_pmp = true; + gpu.pmp_cells = 1; + gpu.pmp = &supplier_node; + assert(apple_pmp_link_device(&consumer) == 0 && link_calls == 1); + balanced(); + case_count++; + gpu.pmp = &other_node; + assert(apple_pmp_link_device(&consumer) == -EPROBE_DEFER && + link_calls == 1); + balanced(); + case_count++; + gpu.pmp = &supplier_node; + supplier.bound = false; + assert(apple_pmp_link_device(&consumer) == -EPROBE_DEFER); + balanced(); + case_count++; + supplier.bound = true; + link_ok = 0; + assert(apple_pmp_link_device(&consumer) == -EINVAL); + balanced(); + case_count++; + printf("PASS: %d T6030 PMP cases, config=%d; reference, lock and command boundaries checked\n", + case_count, CONFIG_APPLE_T6030_GPU_PMP_LINK); + return 0; +} diff --git a/tools/asahi/t6030-pmp-supplier-tests.py b/tools/asahi/t6030-pmp-supplier-tests.py new file mode 100755 index 00000000000000..3379b2911f4804 --- /dev/null +++ b/tools/asahi/t6030-pmp-supplier-tests.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Host controls for default-off T6030 GPU/PMP selection and error propagation. + +Actual selection, dispatch, device-link and serialized power functions are +extracted. OF enumeration/property storage, device binding, MMIO polling, +and locks are controlled host boundaries. The T6030 managed entry wait +and start wait are extracted too; the firmware/workqueue boundary is controlled. +This models ownership/error handling, not real teardown concurrency or DMA. +""" +import argparse +import hashlib +import json +import os +import re +from pathlib import Path +import resource +import shlex +import signal +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] +GATE = "drivers/soc/apple/t6030-display-gate.c" +REPORT = "drivers/pmdomain/apple/pmp-report.c" +EXPORT = "drivers/soc/apple/pmp-export.c" + + +def function(source, signature): + start = source.index(signature) + end = source.index("{", start) + 1 + depth = 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + "\n" + + +def digest(text): + return hashlib.sha256(text.encode()).hexdigest() + + +def no_core(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + + +def run(out, name, code, compiler, configs=(0, 1)): + dest = out / name + dest.mkdir() + (dest / "t6030-pmp-production.h").write_text(code) + results = [] + for config in configs: + binary = dest / f"config-{config}" + command = compiler + ["-std=gnu11", "-g", "-O1", "-Wall", "-Wextra", "-Werror", + "-fsanitize=address,undefined", "-fno-omit-frame-pointer", + f"-DCONFIG_APPLE_T6030_GPU_PMP_LINK={config}", + "-I", str(dest), + str(ROOT / "tools/asahi/t6030-pmp-supplier-tests.c"), + "-o", str(binary)] + built = subprocess.run(command, capture_output=True, text=True) + (dest / f"config-{config}-build.log").write_text(built.stdout + built.stderr) + ran = None + if built.returncode == 0: + ran = subprocess.run([str(binary)], capture_output=True, text=True, + preexec_fn=no_core) + (dest / f"config-{config}-run.log").write_text(ran.stdout + ran.stderr) + results.append({"config": config, "command": command, + "build_rc": built.returncode, "run_rc": ran.returncode if ran else None, + "sanitizer_diagnostic": bool(ran and ( + "AddressSanitizer" in ran.stderr or "runtime error:" in ran.stderr)), + "stdout": ran.stdout if ran else ""}) + return {"name": name, "results": results} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path, + help="new directory for generated sources, logs and receipt") + parser.add_argument("--mutations", action="store_true") + parser.add_argument("--baseline-ref", help="also verify unchanged entry-ready/start consumers") + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + gate, report, export = [(ROOT / path).read_text() for path in (GATE, REPORT, EXPORT)] + kconfig = (ROOT / "drivers/soc/apple/Kconfig").read_text() + section = kconfig.split("config APPLE_T6030_GPU_PMP_LINK\n", 1)[1].split("\nconfig ", 1)[0] + assert '\n\tbool\n' in "\n" + section and "\n\tdefault n\n" in section + assert "depends on APPLE_T6030_DISPLAY_GATE" in section + parts = [function(gate, "static struct device_node *__init gate_find_one("), + function(gate, "static int __init gate_gpu_pmp_link("), + function(report, "static struct device_node *apple_pmp_report_t6030_entry("), + function(report, "static int apple_pmp_report_wait_t6030_14("), + function(report, "int apple_pmp_report_wait_supplier_ready("), + function(export, "int apple_pmp_link_device("), + function(export, "int apple_pmp_set_device_power(")] + offsets = re.search(r'static const struct apple_pmp_report_offsets apple_pmp_offsets_t6030 = \{.*?\n\};', report, re.S) + assert offsets + code = offsets.group() + "\n" + function(report, "static int apple_pmp_start_wait(") + "\n" + function(report, "int apple_pmp_report_wait_ready(") + "\n" + "\n".join(parts) + # Existing managed-start consumers must remain byte-identical. + consumers = ["int apple_pmp_report_wait_ready(", "static int apple_pmp_start_wait("] + consumer_hashes = {name: digest(function(report, name)) for name in consumers} + baseline_checked = False + baseline_code = None + if args.baseline_ref: + baseline = subprocess.check_output(["git", "-C", str(ROOT), "show", + f"{args.baseline_ref}:{REPORT}"], text=True) + for name in consumers: + assert function(report, name) == function(baseline, name), name + baseline_gate = subprocess.check_output(["git", "-C", str(ROOT), "show", + f"{args.baseline_ref}:{GATE}"], text=True) + old_gate = function(baseline_gate, "static int __init gate_t8122_gpu_pmp_link(") + old_gate = old_gate.replace("gate_t8122_gpu_pmp_link", "gate_gpu_pmp_link") + old_dispatch = function(baseline, "int apple_pmp_report_wait_supplier_ready(") + baseline_code = code.replace(parts[1], old_gate).replace(function(report, "int apple_pmp_report_wait_supplier_ready("), old_dispatch) + baseline_checked = True + compiler = shlex.split(os.environ.get("CC", "cc")) + version = subprocess.check_output(compiler + ["--version"], text=True).splitlines()[0] + variants = [("control-before", code)] + if args.mutations: + mutations = [ + ("config-scope", "if (!IS_ENABLED(CONFIG_APPLE_T6030_GPU_PMP_LINK) ||", "if (false ||"), + ("machine-scope", '!of_machine_is_compatible("apple,t6030") ||', "false ||"), + ("supplier-compat", '!of_device_is_compatible(supplier->of_node, "apple,t6030-pmp-v2"))', "false)"), + ("duplicate-report", "\t\tif (report) {", "\t\tif (false) {"), + ("disabled-report", "!of_device_is_available(report) ||", "false ||"), + ("report-phandle-shape", 'of_property_count_u32_elems(report, "apple,pmp") != 1', "false"), + ("supplier-identity", "pmp == supplier->of_node && entry ?", "entry ?"), + ("entry-shape", 'of_property_count_u32_elems(child, "reg") != 1', "false"), + ("duplicate-entry", "if (entry ||", "if (false ||"), + ("disabled-entry", "!of_device_is_available(child) ||", "false ||"), + ("entry-compat", '!of_device_is_compatible(child, "apple,t6000-pmp-v2-report-entry") ||', "false ||"), + ("entry-no-ack", 'of_property_read_bool(child, "apple,no-ack"))', "false)"), + ("declared-report-fallback", '!np && !of_property_present(supplier->of_node, "apple,pmp-report")', "!np"), + ("readiness-error", "apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)) : -ENODEV;", + "(apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)), 0) : -ENODEV;"), + ("managed-owner", '.starts_pmp = IS_ENABLED(CONFIG_APPLE_T6030_GPU_PMP_LINK)', '.starts_pmp = false'), + ("managed-ack", 'status == PMP_REPORT_READY && (ack & BIT_ULL(id))', '((void)ack, status == PMP_REPORT_READY)'), + ("managed-ready", 'status == PMP_REPORT_READY && (ack & BIT_ULL(id))', '((void)status, (ack & BIT_ULL(id)))'), + ("entry-reference", "\tof_node_put(entry);\n\tof_node_put(pmp);", "\tof_node_put(pmp);"), + ("gate-config", "IS_ENABLED(CONFIG_APPLE_T6030_GPU_PMP_LINK) && gate_soc == &gate_t6030", "gate_soc == &gate_t6030"), + ("gate-phandle-shape", 'of_property_count_u32_elems(gpu, "apple,pmp") != 1', "false"), + ("serialized-command", "\tguard(mutex)(&pmp_lock);", "\t(void)&pmp_lock;"), + ] + for name, old, new in mutations: + assert code.count(old) == 1, (name, code.count(old)) + variants.append((name, code.replace(old, new))) + variants.append(("control-after", code)) + results = [run(args.output, name, source, compiler) for name, source in variants] + if baseline_code: + results.append(run(args.output, "control-prior-config-off", baseline_code, compiler, (0,))) + valid = True + for item in results: + control = item["name"].startswith("control-") + built = all(x["build_rc"] == 0 for x in item["results"]) + good = all(x["run_rc"] == 0 and not x["sanitizer_diagnostic"] for x in item["results"]) + killed = any(x["run_rc"] == -signal.SIGABRT or x["sanitizer_diagnostic"] for x in item["results"]) + item["verdict"] = ("PASS" if good else "INVALID") if control else ( + "NOBUILD" if not built else "KILLED" if killed else "SURVIVED") + valid &= item["verdict"] == ("PASS" if control else "KILLED") + receipt = {"passed": valid, "compiler": version, "production_sha256": digest(code), + "fixture_sha256": hashlib.sha256((ROOT / "tools/asahi/t6030-pmp-supplier-tests.c").read_bytes()).hexdigest(), + "entry_ready_consumers_unchanged_checked": baseline_checked, + "consumer_hashes": consumer_hashes, "results": results} + (args.output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps({"passed": valid, "variants": [{"name": x["name"], "verdict": x["verdict"]} + for x in results]})) + return 0 if valid else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/asahi/t6030-wiring-tests.py b/tools/asahi/t6030-wiring-tests.py new file mode 100644 index 00000000000000..3a158d20699c59 --- /dev/null +++ b/tools/asahi/t6030-wiring-tests.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise the shared DP wiring admission and DCP mux lookup on modeled DT nodes.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import resource +import subprocess +ROOT = Path(__file__).resolve().parents[2] +FUNCTIONS = { + 'include/linux/soc/apple/dp-tunnel.h': [ + 'apple_dp_tunnel_t6030_pclk', 'apple_dp_tunnel_wiring_dual', + 'apple_dp_tunnel_mux_matches', 'apple_dp_tunnel_t6030_legacy_mux', + 'apple_dp_tunnel_route_wired', 'apple_dp_tunnel_dual_stream'], + 'drivers/gpu/drm/apple/dcp-fabric-core.c': ['dcp_fabric_wiring'], + 'drivers/gpu/drm/apple/dcp-fabric.c': ['dcp_typec_route_endpoints', 'dcp_typec_route_wiring'], +} +CASES = ['tb-source0', 'tb-source2', 'dcp-source0', 'dcp-source2', + 'other-soc', 'odd-source', 'unknown-source', 'missing-source', + 'single-endpoint', 'wrong-provider', 'missing-primary', 'parse-failure', + 'primary-cell1', 'primary-two-args', 'named', 'named-other-soc', + 'named-wrong-cell', 'named-other-provider', 'partial-named', + 'usb4', 'usb4-other-soc', 'bad-usb4'] + +def function(source, name): + match = re.search(r'^[^\n;{}]*\b' + name + r'\([^;]*?\)\n\{', source, re.M | re.S) + if not match: + raise ValueError(name) + pos = source.index('{', match.start()) + 1 + depth = 1 + while depth: + depth += (source[pos] == '{') - (source[pos] == '}') + pos += 1 + return source[match.start():pos] + '\n' + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--old-ref') + parser.add_argument('--old-classifier', choices=['tb', 'dcp']) + args = parser.parse_args() + bodies = {} + for path, names in FUNCTIONS.items(): + source = (ROOT / path).read_text() + for name in names: + body = function(source, name) + old_name = {'tb': 'apple_dp_tunnel_route_wired', 'dcp': 'dcp_typec_route_wiring'}.get(args.old_classifier) + if args.old_ref and name == old_name: + body = function(subprocess.check_output(['git', 'show', args.old_ref + ':' + path], cwd=ROOT, text=True), name) + bodies[name] = body + enum = re.search(r'enum dcp_fabric_wiring \{.*?\n\};', + (ROOT / 'drivers/gpu/drm/apple/dcp-fabric-core.h').read_text(), re.S).group() + fixture = (ROOT / 'tools/asahi/t6030-wiring/fixture.c').read_text() + code = fixture.replace('/* PRODUCTION_FUNCTIONS */', enum + '\n' + '\n'.join(bodies.values())) + args.out.mkdir(parents=True, exist_ok=True) + source, binary = args.out / 'production.c', args.out / 'production' + source.write_text(code) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Wextra', '-Werror', '-fsanitize=address,undefined', '-fno-omit-frame-pointer', '-Wno-unused-function', str(source), '-o', str(binary)], check=True) + def no_core(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + results = [] + for case in CASES: + run = subprocess.run([str(binary), case], capture_output=True, text=True, preexec_fn=no_core) + results.append({'case': case, 'exit': run.returncode, 'stderr': run.stderr}) + receipt = {'production_bodies': {n: hashlib.sha256(b.encode()).hexdigest() for n, b in bodies.items()}, + 'old_ref': args.old_ref, 'old_classifier': args.old_classifier, + 'hardware_access': False, 'results': results} + (args.out / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps(results, indent=2)) + if any(r['exit'] for r in results): + raise SystemExit(1) +if __name__ == '__main__': + main() diff --git a/tools/asahi/t6030-wiring/fixture.c b/tools/asahi/t6030-wiring/fixture.c new file mode 100644 index 00000000000000..01629ab2c2eb34 --- /dev/null +++ b/tools/asahi/t6030-wiring/fixture.c @@ -0,0 +1,299 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#include +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define BIT(n) (1u << (n)) +struct mux_chip; +struct mux_control { + struct mux_chip *chip; + unsigned int index; +}; +struct mux_chip { + unsigned int controllers; + struct mux_control mux[3]; +}; +struct device_node { + const char *name, *compatible; + struct device_node *parent, *child, *next, *remote; + unsigned int refs, reg, source, names_count; + bool missing_source, bad_parse; + const char *names[4]; + struct device_node *providers[4]; + unsigned int cells[4], nargs[4]; + struct mux_chip *chip; +}; +struct of_phandle_args { + struct device_node *np; + unsigned int args_count, args[2]; +}; +static bool t6030 = true; +static struct device_node *get(struct device_node *n) +{ + if (n) + n->refs++; + return n; +} +static void of_node_put(struct device_node *n) +{ + if (n) { + assert(n->refs); + n->refs--; + } +} +static void device_node_free(struct device_node **n) +{ + of_node_put(*n); +} +#define __free(name) __attribute__((cleanup(name##_free))) +static struct device_node *of_get_parent(struct device_node *n) +{ + return get(n ? n->parent : NULL); +} +static bool of_node_name_eq(struct device_node *n, const char *s) +{ + return n && !strcmp(n->name, s); +} +static bool of_machine_is_compatible(const char *s) +{ + return t6030 && !strcmp(s, "apple,t6030"); +} +static bool of_device_is_compatible(struct device_node *n, const char *s) +{ + return n && n->compatible && !strcmp(n->compatible, s); +} +static int of_property_match_string(struct device_node *n, const char *prop, + const char *name) +{ + assert(!strcmp(prop, "mux-control-names")); + for (unsigned int i = 0; n && i < n->names_count; i++) + if (!strcmp(n->names[i], name)) + return i; + return -ENODATA; +} +static int of_property_read_u32_index(struct device_node *n, const char *prop, + unsigned int i, u32 *value) +{ + assert(!strcmp(prop, "apple,typec-mux-indices")); + if (!n || n->missing_source || i >= 3) + return -EINVAL; + *value = n->source; + return 0; +} +static int of_property_read_u32(struct device_node *n, const char *prop, + u32 *value) +{ + assert(!strcmp(prop, "reg")); + if (!n) + return -EINVAL; + *value = n->reg; + return 0; +} +static int of_parse_phandle_with_args(struct device_node *n, const char *prop, + const char *cells, int index, + struct of_phandle_args *args) +{ + assert(!strcmp(prop, "mux-controls") && + !strcmp(cells, "#mux-control-cells")); + if (!n || n->bad_parse || index < 0 || + (unsigned)index >= n->names_count) + return -EINVAL; + args->np = get(n->providers[index]); + args->args_count = n->nargs[index]; + args->args[0] = n->cells[index]; + return 0; +} +static struct device_node *of_graph_get_port_by_id(struct device_node *n, + unsigned int id) +{ + for (struct device_node *p = n ? n->child : NULL; p; p = p->next) + if (p->reg == id) + return get(p); + return NULL; +} +static struct device_node *next_child(struct device_node *parent, + struct device_node *prev) +{ + struct device_node *next = prev ? prev->next : + parent ? parent->child : + NULL; + of_node_put(prev); + return get(next); +} +#define for_each_child_of_node_scoped(parent, node) \ + for (struct device_node * node __free(device_node) = \ + next_child(parent, NULL); \ + node; node = next_child(parent, node)) +#define for_each_of_graph_port_endpoint(parent, node) \ + for_each_child_of_node_scoped(parent, node) +static struct device_node * +of_graph_get_remote_port_parent(struct device_node *n) +{ + return get(n ? n->remote : NULL); +} +struct device { + struct device_node *of_node; +}; +struct apple_dcp { + struct device *dev; +}; +struct apple_dcp_typec_route { + struct apple_dcp *dcp; + struct mux_control *xbar, *dpin[2]; + bool dual_stream; +}; +#define IS_ERR(p) ((uintptr_t)(p) >= (uintptr_t)-4095) +#define PTR_ERR(p) ((int)(intptr_t)(p)) +#define dev_warn_once(dev, ...) ((void)(dev)) +static struct mux_control *devm_mux_control_get(struct device *dev, + const char *name) +{ + int i = of_property_match_string(dev->of_node, "mux-control-names", + name); + if (i < 0 || dev->of_node->nargs[i] != 1 || + !dev->of_node->providers[i]->chip || + dev->of_node->cells[i] >= + dev->of_node->providers[i]->chip->controllers) + return (void *)(intptr_t)-EINVAL; + return &dev->of_node->providers[i]->chip->mux[dev->of_node->cells[i]]; +} +/* PRODUCTION_FUNCTIONS */ +int main(int argc, char **argv) +{ + assert(argc == 2); + struct mux_chip chip = { .controllers = 3 }, + other_chip = { .controllers = 3 }; + for (unsigned int i = 0; i < 3; i++) { + chip.mux[i].chip = &chip; + chip.mux[i].index = i; + other_chip.mux[i].chip = &other_chip; + other_chip.mux[i].index = i; + } + struct device_node provider = { + .compatible = "apple,t6020-display-crossbar", .chip = &chip + }; + struct device_node other = { .compatible = + "apple,t6020-display-crossbar", + .chip = &other_chip }; + struct device_node dcp = { .name = "dcpext", + .names_count = 1, + .names = { "typec0" }, + .providers = { &provider, &provider, + &provider }, + .cells = { 0, 1, 2 }, + .nargs = { 1, 1, 1 } }; + struct device_node routes = { .name = "typec-routes", .parent = &dcp }; + struct device_node route_np = { .parent = &routes }; + struct device_node endpoint[2] = { { .remote = &route_np }, + { .remote = &route_np } }; + endpoint[0].next = &endpoint[1]; + struct device_node port = { .reg = 3, .child = &endpoint[0] }; + struct device_node connector = { .child = &port }; + struct device dev = { .of_node = &dcp }; + struct apple_dcp engine = { .dev = &dev }; + struct apple_dcp_typec_route route = { .dcp = &engine, + .xbar = &chip.mux[0] }; + bool expected = true; + int expected_dcp = 0; + const char *test = argv[1]; + if (strstr(test, "source2")) + dcp.source = 2; + if (!strcmp(test, "other-soc")) { + t6030 = false; + expected = false; + } + if (!strcmp(test, "odd-source")) { + dcp.source = 1; + expected = false; + } + if (!strcmp(test, "unknown-source")) { + dcp.source = 4; + expected = false; + } + if (!strcmp(test, "missing-source")) { + dcp.missing_source = true; + expected = false; + } + if (!strcmp(test, "single-endpoint")) { + endpoint[0].next = NULL; + expected = false; + } + if (!strcmp(test, "wrong-provider")) { + provider.compatible = "apple,t8103-display-crossbar"; + expected = false; + } + if (!strcmp(test, "missing-primary")) { + dcp.names_count = 0; + expected = false; + } + if (!strcmp(test, "parse-failure")) { + dcp.bad_parse = true; + expected = false; + } + if (!strcmp(test, "primary-cell1")) { + dcp.cells[0] = 1; + expected = false; + } + if (!strcmp(test, "primary-two-args")) { + dcp.nargs[0] = 2; + expected = false; + } + if (!strcmp(test, "named") || !strcmp(test, "named-other-soc") || + !strcmp(test, "named-wrong-cell") || + !strcmp(test, "named-other-provider") || + !strcmp(test, "partial-named")) { + dcp.names_count = 3; + dcp.names[1] = "typec0-dpin0"; + dcp.names[2] = "typec0-dpin1"; + if (!strcmp(test, "named-other-soc")) + t6030 = false; + if (!strcmp(test, "named-wrong-cell")) { + dcp.cells[2] = 1; + expected = false; + expected_dcp = -EINVAL; + } + if (!strcmp(test, "named-other-provider")) { + dcp.providers[2] = &other; + expected = false; + expected_dcp = -EINVAL; + } + if (!strcmp(test, "partial-named")) { + dcp.names_count = 2; + expected = false; + expected_dcp = -EINVAL; + } + } + if (!strcmp(test, "usb4") || !strcmp(test, "usb4-other-soc") || + !strcmp(test, "bad-usb4")) { + dcp.names_count = 2; + dcp.names[1] = "typec0-usb4"; + if (!strcmp(test, "usb4-other-soc")) + t6030 = false; + if (!strcmp(test, "bad-usb4")) { + dcp.cells[1] = 0; + expected = false; + expected_dcp = -EINVAL; + } + } + if (strncmp(test, "dcp-", 4)) + assert(apple_dp_tunnel_dual_stream(&connector) == expected); + if (strncmp(test, "tb-", 3)) { + int ret = dcp_typec_route_wiring(&route, &connector, 0); + assert(ret == expected_dcp); + if (!ret) { + assert(route.dual_stream == expected); + if (expected) { + assert(route.dpin[0] == &chip.mux[1]); + assert(route.dpin[1] == &chip.mux[2]); + } + } + } + assert(!provider.refs && !other.refs && !dcp.refs && !routes.refs && + !route_np.refs && !port.refs && !endpoint[0].refs && + !endpoint[1].refs); + printf("PASS %s\n", test); + return 0; +} diff --git a/tools/asahi/tb-dp-repair-tests.py b/tools/asahi/tb-dp-repair-tests.py new file mode 100644 index 00000000000000..7e59e8739181f8 --- /dev/null +++ b/tools/asahi/tb-dp-repair-tests.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Exercise real DP retirement/repair bodies with modeled paths, PM and a queue. + +This checks ordering and reference balance, not kernel structure layout, hardware, +real runtime-PM locking or a complete Thunderbolt workqueue implementation. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def function(text, name): + match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:int|void|bool)\s+' + + name + r'\([^;]*?\)\n\{', text, re.M | re.S) + if not match: + raise ValueError('Missing actual function: ' + name) + pos = text.index('{', match.start()) + 1 + depth = 1 + while depth: + depth += (text[pos] == '{') - (text[pos] == '}') + pos += 1 + return text[match.start():pos] + '\n' + + +HEADER = r''' +#include +#include +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"CHECK line %d: %s\n",__LINE__,#x); exit(77); } } while (0) +struct list_head {int unused;}; +struct device {int unused;}; +struct tb_switch {struct device dev;}; +struct tb_port {struct tb_switch *sw;bool is_dpin;struct list_head list;}; +struct work_struct {void(*fn)(struct work_struct*);bool pending;}; +struct tb_nhi {unsigned long quirks;}; +#define BIT(n) (1UL<<(n)) +#define QUIRK_NO_SYSTEM_SLEEP BIT(5) +struct tb {int lock;struct device dev;void*wq;struct tb_switch*root_switch;struct tb_nhi*nhi;}; +struct tb_cm {bool hotplug_active;struct work_struct dp_tunnel_work;bool dp_tunnel_pending;}; +struct domain {struct tb tb;struct tb_cm cm;}; +_Static_assert(offsetof(struct domain,cm)==sizeof(struct tb),"mock private storage adjacency"); +#define INIT_WORK(w,handler) ((w)->fn=(handler)) +struct kref {int count;}; +struct tb_path {bool reserved;}; +enum {TB_TUNNEL_DP,TB_TUNNEL_USB3}; +struct tb_tunnel {struct kref kref;struct tb*tb;struct tb_port*src_port,*dst_port;int npaths;void(*destroy)(struct tb_tunnel*);struct list_head list;int type;bool dprx_started,dprx_canceled;void(*callback)(struct tb_tunnel*);struct tb_path*paths[3];}; +static int tb_tunnel_lock,occupied,alloc_calls,alloc_failures,alloc_successes,freed; +static int domain_refs,pm_refs,pm_calls,pm_error,stop_during_pm,requeue_once,lock_depth; +static int restore_calls,scan_calls,unplugged_xdomains; +static struct tb_tunnel *current; +static struct domain domain; +#define container_of(p,t,m) ((t*)((char*)(p)-offsetof(t,m))) +#define READ_ONCE(x) (x) +#define fallthrough __attribute__((fallthrough)) +#define tb_port_dbg(...) ((void)0) +#define tb_tunnel_dbg(...) ((void)0) +#define tb_tunnel_warn(...) ((void)0) +static struct tb_cm*tb_priv(struct tb*t){return (struct tb_cm*)((char*)t+sizeof(*t));} +static struct tb*tcm_to_tb(struct tb_cm*c){return (struct tb*)((char*)c-sizeof(struct tb));} +static void mutex_lock(int*x){if(x==&domain.tb.lock){CHECK(!lock_depth);lock_depth++;}} +static void mutex_unlock(int*x){if(x==&domain.tb.lock){CHECK(lock_depth==1);lock_depth--;}} +#define lockdep_assert_held(x) CHECK((x)==&domain.tb.lock && lock_depth==1) +/* guard()/scoped_guard() as in : the lock is dropped when the scope ends. */ +static int*guard_mutex_lock(int*x){mutex_lock(x);return x;} +static void guard_mutex_unlock(int**x){if(*x)mutex_unlock(*x);} +#define GUARD_CAT2(a,b) a##b +#define GUARD_CAT(a,b) GUARD_CAT2(a,b) +#define guard(type) int*GUARD_CAT(guard_,__COUNTER__) __attribute__((unused,cleanup(guard_##type##_unlock)))=guard_##type##_lock +#define scoped_guard(type,x) \ + for(int*scope __attribute__((cleanup(guard_##type##_unlock)))=guard_##type##_lock(x),*scope_done=NULL; \ + !scope_done;scope_done=scope) +static int tb_domain_unregister_unplugged_xdomains(struct tb*t){return unplugged_xdomains;} +static void tb_scan_switch(struct tb_switch*s){CHECK(lock_depth==1 && s);scan_calls++;} +static void tb_restore_dp_resources(struct tb_switch*s){CHECK(lock_depth==1 && s);restore_calls++;} +static void kref_get(struct kref*k){CHECK(k->count>0);k->count++;} +static void kref_put(struct kref*k,void(*destroy)(struct kref*)){CHECK(k->count>0);if(!--k->count)destroy(k);} +static void tb_path_free(struct tb_path*p){if(p->reserved)occupied--;freed++;free(p);} +#define kfree(x) free(x) +static void list_del(struct list_head*l){current=NULL;} +static void list_del_init(struct list_head*l){} +static bool tb_port_is_dpin(struct tb_port*p){return p->is_dpin;} +static void tb_dp_tunnel_notify(struct tb_tunnel*t,bool active){} +static void tb_tunnel_deactivate(struct tb_tunnel*t){} +static void tb_detach_bandwidth_group(struct tb_port*p){} +static void tb_switch_dealloc_dp_resource(struct tb_switch*s,struct tb_port*p){} +static void tb_configure_sym(struct tb*t,struct tb_port*i,struct tb_port*o,bool active){} +static void pm_runtime_mark_last_busy(struct device*d){} +static void pm_runtime_put_autosuspend(struct device*d){if(d==&domain.tb.dev){CHECK(pm_refs==1);pm_refs--;}} +static int pm_runtime_resume_and_get(struct device*d){ + CHECK(!lock_depth);pm_calls++; + if(pm_error)return pm_error; + pm_refs++; + if(stop_during_pm)domain.cm.hotplug_active=false; + return 0; +} +static void tb_reclaim_usb3_bandwidth(struct tb*t,struct tb_port*i,struct tb_port*o){} +static bool tb_tunnel_is_active(struct tb_tunnel*t){return false;} +static int tb_tunnel_consumed_bandwidth(struct tb_tunnel*t,int*up,int*down){return 0;} +static void tb_configure_asym(struct tb*t,struct tb_port*i,struct tb_port*o,int up,int down){} +static void tb_increase_tmu_accuracy(struct tb_tunnel*t){} +static struct tb_tunnel*tb_find_tunnel(struct tb*t,int type,struct tb_port*in,struct tb_port*out){return current;} +static void tb_enter_redrive(struct tb_port*p){} +static void tb_recalc_estimated_bandwidth(struct tb*t){} +static struct tb*tb_domain_get(struct tb*t){CHECK(domain_refs>=1);domain_refs++;return t;} +static void tb_domain_put(struct tb*t){CHECK(domain_refs>1);domain_refs--;} +static bool queue_work(void*wq,struct work_struct*w){if(w->pending)return false;w->pending=true;return true;} +static void tb_queue_dp_tunnels(struct tb*tb); +static void tb_tunnel_dp(struct tb*t){ + CHECK(lock_depth==1 && domain.cm.hotplug_active && t->root_switch); + alloc_calls++;if(occupied)alloc_failures++;else alloc_successes++; + if(requeue_once){requeue_once=0;tb_queue_dp_tunnels(t);} +} +''' + +FOOTER = r''' +static struct tb_tunnel*new_tunnel(struct tb*tb,struct tb_port*in,struct tb_port*out){ + struct tb_tunnel*t=calloc(1,sizeof(*t));CHECK(t);t->tb=tb;t->src_port=in;t->dst_port=out;t->type=TB_TUNNEL_DP;t->kref.count=1;t->npaths=1; + t->paths[0]=calloc(1,sizeof(struct tb_path));CHECK(t->paths[0]);t->paths[0]->reserved=true;occupied++;t->callback=tb_dp_tunnel_active;current=t;return t; +} +static void flush_queue(void){ + unsigned n=0; + while(domain.cm.dp_tunnel_work.pending){ + CHECK(++n<8);CHECK(domain.cm.dp_tunnel_work.fn);domain.cm.dp_tunnel_work.pending=false; + domain.cm.dp_tunnel_work.fn(&domain.cm.dp_tunnel_work); + } + CHECK(!lock_depth && !pm_refs && domain_refs==1); + if(alloc_successes)CHECK(!domain.cm.dp_tunnel_pending); +} +static void queue_repair(unsigned count){ + mutex_lock(&domain.tb.lock); + for(unsigned i=0;idprx_canceled=true;tb_tunnel_get(t);tb_domain_get(&domain.tb); + worker_tail(&domain.tb,t); + CHECK(!domain.cm.dp_tunnel_work.pending && !alloc_calls && occupied==1 && !freed && domain_refs==1); + mutex_lock(&domain.tb.lock);tb_deactivate_and_free_tunnel(t);mutex_unlock(&domain.tb.lock); + CHECK(!occupied && freed==1 && !lock_depth); + }else if(!strcmp(c,"coalesce")){ + queue_repair(20);CHECK(domain_refs==2);flush_queue();CHECK(alloc_calls==1); + }else if(!strcmp(c,"stop-before-queue")){ + domain.cm.hotplug_active=false;queue_repair(1);CHECK(!domain.cm.dp_tunnel_work.pending && domain_refs==1);flush_queue();CHECK(!alloc_calls && !pm_calls); + }else if(!strcmp(c,"stop-after-queue")){ + queue_repair(1);domain.cm.hotplug_active=false;domain.tb.root_switch=NULL;flush_queue();CHECK(!alloc_calls && !pm_calls); + }else if(!strcmp(c,"stop-during-pm")){ + queue_repair(1);stop_during_pm=1;flush_queue();CHECK(!alloc_calls && pm_calls==1); + }else if(!strcmp(c,"no-root")){ + queue_repair(1);domain.tb.root_switch=NULL;flush_queue();CHECK(!alloc_calls && pm_calls==1); + }else if(!strcmp(c,"pm-failure")){ + queue_repair(1);pm_error=-5;flush_queue();CHECK(!alloc_calls && pm_calls==1); + }else if(!strcmp(c,"requeue-running")){ + queue_repair(1);requeue_once=1;flush_queue();CHECK(alloc_calls==2 && alloc_successes==2); + }else if(!strcmp(c,"freeze-thaw-repair")){ + queue_repair(1);mutex_lock(&domain.tb.lock);CHECK(!tb_freeze_noirq(&domain.tb));mutex_unlock(&domain.tb.lock); + flush_queue();CHECK(!alloc_calls && !pm_calls && domain.cm.dp_tunnel_pending); + mutex_lock(&domain.tb.lock);CHECK(!tb_thaw_noirq(&domain.tb));mutex_unlock(&domain.tb.lock); + CHECK(domain.cm.dp_tunnel_work.pending && domain_refs==2);flush_queue();CHECK(alloc_successes==1); + }else if(!strcmp(c,"pm-failure-retry")){ + queue_repair(1);pm_error=-5;flush_queue();CHECK(!alloc_calls && domain.cm.dp_tunnel_pending); + pm_error=0;mutex_lock(&domain.tb.lock);CHECK(!tb_thaw_noirq(&domain.tb));mutex_unlock(&domain.tb.lock); + flush_queue();CHECK(alloc_successes==1 && pm_calls==2); + }else if(!strcmp(c,"ordinary-retirement")){ + new_tunnel(&domain.tb,&in,&out);mutex_lock(&domain.tb.lock); + tb_dp_resource_unavailable(&domain.tb,&in,"ordinary detach");mutex_unlock(&domain.tb.lock); + CHECK(!occupied && freed==1 && !alloc_calls);flush_queue();CHECK(alloc_successes==1); + }else if(!strcmp(c,"noirq-pm-error-complete-replay")){ + /* Generic host: completion replays the request the noirq pass could not serve. */ + freeze_then_thaw_with_pm_disabled(); + tb_complete(&domain.tb); + CHECK(!lock_depth && !restore_calls && !scan_calls && domain.cm.dp_tunnel_work.pending && domain_refs==2); + flush_queue();CHECK(alloc_calls==1 && alloc_successes==1 && pm_calls==2 && !domain.cm.dp_tunnel_pending); + }else if(!strcmp(c,"apple-complete-acknowledges")){ + /* QUIRK_NO_SYSTEM_SLEEP pairs directly; that serves the request, so nothing is queued again. */ + nhi.quirks=QUIRK_NO_SYSTEM_SLEEP; + freeze_then_thaw_with_pm_disabled(); + tb_complete(&domain.tb); + CHECK(!lock_depth && restore_calls==1 && alloc_calls==1 && !domain.cm.dp_tunnel_pending); + CHECK(!domain.cm.dp_tunnel_work.pending && domain_refs==1); + flush_queue();CHECK(alloc_calls==1 && pm_calls==1); + }else if(!strcmp(c,"complete-no-request")){ + tb_complete(&domain.tb); + CHECK(!lock_depth && !domain.cm.dp_tunnel_work.pending && !alloc_calls && !restore_calls && domain_refs==1); + flush_queue();CHECK(!alloc_calls && !pm_calls); + }else if(!strcmp(c,"complete-xdomain-rescan-replay")){ + /* The rescan's scoped lock is dropped before the pairing lock is taken. */ + unplugged_xdomains=1; + freeze_then_thaw_with_pm_disabled(); + tb_complete(&domain.tb); + CHECK(!lock_depth && scan_calls==1 && domain.cm.dp_tunnel_work.pending); + flush_queue();CHECK(alloc_successes==1 && !domain.cm.dp_tunnel_pending); + }else return 78; + printf("PASS %s\n",c);return 0; +} +''' + +CASES = ['callback-release-before-repair', 'canceled-callback-does-not-repair', 'coalesce', 'stop-before-queue', + 'stop-after-queue', 'stop-during-pm', 'no-root', 'pm-failure', + 'requeue-running', 'ordinary-retirement', 'freeze-thaw-repair', + 'pm-failure-retry', 'noirq-pm-error-complete-replay', + 'apple-complete-acknowledges', 'complete-no-request', + 'complete-xdomain-rescan-replay'] +# The cases a tb_complete() without the replay and the acknowledgement must fail. +COMPLETE_CASES = {'noirq-pm-error-complete-replay', 'apple-complete-acknowledges', + 'complete-xdomain-rescan-replay'} +MUTANTS = { + 'missing-canceled-callback-guard': ('if (tunnel->dprx_canceled)', 'if (false)'), + 'inline-repair': ('\ttb_recalc_estimated_bandwidth(tb);\n\ttb_queue_dp_tunnels(tb);', + '\ttb_recalc_estimated_bandwidth(tb);\n\ttb_tunnel_dp(tb);'), + 'missing-queue-reference': ('\ttb_domain_get(tb);', '\t/* removed get */'), + 'coalescing-leaks-reference': ('\tif (!queue_work(tb->wq, &tcm->dp_tunnel_work))\n\t\ttb_domain_put(tb);', + '\tqueue_work(tb->wq, &tcm->dp_tunnel_work);'), + 'missing-stop-guard': ('\tif (!READ_ONCE(tcm->hotplug_active))', '\tif (false)'), + 'missing-post-resume-guard': ('\tif (tcm->hotplug_active && tb->root_switch)', '\tif (tb->root_switch)'), + 'missing-root-guard': ('\tif (tcm->hotplug_active && tb->root_switch)', '\tif (tcm->hotplug_active)'), + 'missing-pm-error-guard': ('\tif (ret < 0)', '\tif (false)'), + 'missing-pm-put': ('\tpm_runtime_put_autosuspend(&tb->dev);', '\t/* removed PM put */'), + 'missing-probe-init': ('INIT_WORK(&tcm->dp_tunnel_work, tb_dp_tunnel_work);', + '/* removed probe initialization */'), + 'missing-pending-request': ('\ttcm->dp_tunnel_pending = true;', '\t/* lost request */'), + 'pending-never-consumed': ('if (tcm->hotplug_active && tb->root_switch) {\n\t\ttcm->dp_tunnel_pending = false;', + 'if (tcm->hotplug_active && tb->root_switch) {\n\t\t/* pending forever */'), + 'missing-thaw-requeue': ('\ttcm->hotplug_active = true;\n\tif (tcm->dp_tunnel_pending)\n\t\ttb_queue_dp_tunnels(tb);', + '\ttcm->hotplug_active = true;\n\t/* lost thaw request */'), + 'missing-complete-replay': ('was disabled. */\n\tif (tcm->dp_tunnel_pending)\n\t\ttb_queue_dp_tunnels(tb);', + 'was disabled. */\n\t/* lost completion replay */'), + 'missing-apple-ack': ('\t\ttb_restore_dp_resources(tb->root_switch);\n\t\ttcm->dp_tunnel_pending = false;', + '\t\ttb_restore_dp_resources(tb->root_switch);\n\t\t/* request not acknowledged */'), + 'unconditional-complete-replay': ('was disabled. */\n\tif (tcm->dp_tunnel_pending)\n\t\ttb_queue_dp_tunnels(tb);', + 'was disabled. */\n\ttb_queue_dp_tunnels(tb);'), +} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--mutations', action='store_true') + parser.add_argument('--output', type=Path) + parser.add_argument('--complete-ref', help='negative control: take only tb_complete() from ' + 'this commit; exactly the completion cases must fail') + args = parser.parse_args() + tb = (ROOT / 'drivers/thunderbolt/tb.c').read_text() + tunnel = (ROOT / 'drivers/thunderbolt/tunnel.c').read_text() + names = ['tb_tunnel_get', 'tb_tunnel_destroy', 'tb_tunnel_put'] + parts = {n: function(tunnel, n) for n in names} + for name in ['tb_deactivate_and_free_tunnel', 'tb_dp_tunnel_work', + 'tb_queue_dp_tunnels', 'tb_dp_resource_unavailable', 'tb_dp_tunnel_active', + 'tb_freeze_noirq', 'tb_thaw_noirq', 'tb_complete']: + parts[name] = function(tb, name) + if args.complete_ref: + old = subprocess.check_output(['git', 'show', args.complete_ref + ':drivers/thunderbolt/tb.c'], + cwd=ROOT, text=True) + parts['tb_complete'] = function(old, 'tb_complete') + worker = function(tunnel, 'tb_dp_dprx_work') + marker = '\ttunnel->callback(tunnel);' + if worker.count(marker) != 1: + raise ValueError('DPRX completion tail changed; review extraction') + tail = worker[worker.index(marker):].rstrip()[:-1] + if tail.strip() != 'tunnel->callback(tunnel);\n\ttb_tunnel_put(tunnel);\n\ttb_domain_put(tb);': + raise ValueError('DPRX reference-release order changed; review extraction') + production = '\n'.join(parts.values()) + probe = (ROOT / 'drivers/thunderbolt/tb.c').read_text() + probe = probe[probe.index('struct tb *tb_probe(struct tb_nhi *nhi)'):] + initializers = re.findall(r'INIT_WORK\(&tcm->\w+,\s*\w+\);', probe) + production += '\nstatic void init_fixture(struct tb_cm*tcm){\n' + '\n'.join(initializers) + '\n}\n' + results = {} + with tempfile.TemporaryDirectory(prefix='tb-dp-repair-') as tmp: + out = args.output or Path(tmp) + out.mkdir(parents=True, exist_ok=True) + variants = {'real': production} + if args.mutations and not args.complete_ref: + for name, (old, new) in MUTANTS.items(): + if production.count(old) != 1: + raise ValueError('Mutation site changed: ' + name) + variants[name] = production.replace(old, new, 1) + for name, body in variants.items(): + unit = out / (name + '.c') + unit.write_text(HEADER + '#include \n' + body + + '\nstatic void worker_tail(struct tb*tb,struct tb_tunnel*tunnel){\n' + + tail + '\n}\n' + FOOTER) + executable = out / name + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-Wno-unused-but-set-variable', '-g', + '-fsanitize=address,undefined', str(unit), '-o', str(executable)], + check=True) + runs = [] + for case in CASES: + run = subprocess.run([str(executable), case], capture_output=True, text=True) + runs.append({'case': case, 'rc': run.returncode, + 'stdout': run.stdout, 'stderr': run.stderr}) + failures = [r for r in runs if r['rc'] != 0] + if args.complete_ref: + failed = {r['case'] for r in failures} + if failed != COMPLETE_CASES or any(r['rc'] != 77 for r in failures): + raise RuntimeError('Control did not fail exactly the completion cases: ' + + json.dumps(sorted(failed))) + elif name == 'real' and failures: + raise RuntimeError(json.dumps(failures)) + if name != 'real' and not any(r['rc'] == 77 for r in failures): + raise RuntimeError('Mutant not caught by a valid runtime assertion: ' + name) + results[name] = runs + receipt = {'scope': __doc__, 'production_bodies': { + n: hashlib.sha256(body.encode()).hexdigest() for n, body in parts.items()}, + 'worker_tail_sha256': hashlib.sha256(tail.encode()).hexdigest(), + 'probe_initializers': initializers, + 'complete_ref': args.complete_ref, + 'results': results} + (out / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps({'cases': len(CASES), 'passed': True, + 'complete_ref': args.complete_ref, + 'control_failed': sorted(COMPLETE_CASES) if args.complete_ref else [], + 'mutants_caught': len(variants) - 1, 'output': str(out)})) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/tiled-split-tests.py b/tools/asahi/tiled-split-tests.py new file mode 100644 index 00000000000000..ecb6cbe311f3c4 --- /dev/null +++ b/tools/asahi/tiled-split-tests.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise the production DPIN1 dispatch and tiled-display split admission. + +The production bodies are compiled with ASan/UBSan against a host fixture +that stubs only what lies below them. With --mutations, each mutant changes +the extracted bodies in memory (never the source) and must make at least one +case fail. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import resource +import subprocess + +ROOT = Path(__file__).resolve().parents[2] +FUNCTIONS = { + 'drivers/gpu/drm/apple/dcp-fabric-session.h': ['dcp_fabric_binding_request'], + 'drivers/gpu/drm/apple/dcp-fabric-core.c': ['dcp_fabric_tunnel_slot'], + 'drivers/gpu/drm/apple/dcp-fabric.c': [ + 'dcp_typec_port_untileable', 'dcp_tb_split_locked', 'dcp_tb_dispatch_request'], +} +CASES = ['t6030-dpin1-alone', 't6030-dpin1-alone-before-services', + 't6030-dpin1-with-external-owner', 't6030-dpin1-then-dpin0', + 't6030-dpin0-then-dpin1', 't6030-split-off', 't6030-inactive-dpin1', + 'internal-dpin1-alone-waits', 'internal-not-ready-waits', + 'mixed-routes-wait', 'no-routes-wait', 'internal-tile-hint-pending', + 'internal-tiled-join', 'internal-owner-without-port1', + 'split-retired-teardown-first', 'split-existing-release', + 'split-existing-active'] +# (name, old, new): valid C that changes the admission. +MUTATIONS = [ + ('gate-removed', 'if (dcp_typec_port_untileable(port))', + 'if (false && dcp_typec_port_untileable(port))'), + ('gate-before-split-handling', + 'lockdep_assert_held(&dcp_typec_fabric_lock);\n\t/* A retired provider', + 'lockdep_assert_held(&dcp_typec_fabric_lock);\n\tif (dcp_typec_port_untileable(port))\n' + '\t\treturn -EOPNOTSUPP;\n\t/* A retired provider'), + ('readiness-judged', 'if (!route->dcp->external)\n\t\t\treturn false;', + 'if (!route->dcp->external && route->dcp->dptxport[1].enabled)\n\t\t\treturn false;'), + ('empty-untileable', 'return !list_empty(&port->routes);', 'return true;'), + ('any-external-untileable', 'if (!route->dcp->external)\n\t\t\treturn false;', + 'if (route->dcp->external)\n\t\t\treturn true;'), + ('gate-always', 'if (dcp_typec_port_untileable(port))', + 'if (true || dcp_typec_port_untileable(port))'), +] + + +def function(source, name): + # A definition line: not a comment line that mentions the name. + match = re.search(r'^(?![ \t]*(?:\*|/\*|//))[^\n;{}]*\b' + name + r'\([^;]*?\)\n\{', + source, re.M | re.S) + if not match: + raise ValueError(name) + pos = source.index('{', match.start()) + 1 + depth = 1 + while depth: + depth += (source[pos] == '{') - (source[pos] == '}') + pos += 1 + return source[match.start():pos] + '\n' + + +def build(out, bodies, tag): + fixture = (ROOT / 'tools/asahi/tiled-split/fixture.c').read_text() + code = fixture.replace('/* PRODUCTION_FUNCTIONS */', '\n'.join(bodies.values())) + source, binary = out / f'{tag}.c', out / tag + source.write_text(code) + subprocess.run(['cc', '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-function', '-Wno-unused-parameter', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(source), '-o', str(binary)], check=True) + return binary + + +def run(binary): + def no_core(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + results = [] + for case in CASES: + r = subprocess.run([str(binary), case], capture_output=True, text=True, + preexec_fn=no_core) + results.append({'case': case, 'exit': r.returncode, 'stderr': r.stderr.strip()[-300:]}) + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--mutations', action='store_true') + parser.add_argument('--old-ref', help='take the dispatch and split bodies from this ' + 'commit instead (a negative control: expected to fail)') + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + bodies = {} + for path, names in FUNCTIONS.items(): + source = (ROOT / path).read_text() + for name in names: + bodies[name] = function(source, name) + if args.old_ref and name in ('dcp_tb_split_locked', 'dcp_tb_dispatch_request'): + old = subprocess.check_output(['git', 'show', f'{args.old_ref}:{path}'], + cwd=ROOT, text=True) + bodies[name] = function(old, name) + results = run(build(args.out, bodies, 'production')) + failed = [r for r in results if r['exit']] + mutants = [] + if args.mutations: + for name, old, new in MUTATIONS: + text = '\n'.join(bodies.values()) + if text.count(old) != 1: + raise SystemExit(f'mutation {name}: {text.count(old)} matches') + mutated = {k: v.replace(old, new) for k, v in bodies.items()} + mres = run(build(args.out, mutated, 'mutant-' + name)) + caught = [r['case'] for r in mres if r['exit']] + mutants.append({'mutant': name, 'caught_by': caught, 'killed': bool(caught)}) + receipt = {'production_bodies': {n: hashlib.sha256(b.encode()).hexdigest() for n, b in bodies.items()}, + 'old_ref': args.old_ref, 'hardware_access': False, + 'results': results, 'mutants': mutants} + (args.out / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(f'{len(results) - len(failed)}/{len(results)} cases pass') + for r in failed: + print('FAIL', r['case'], r['stderr']) + for m in mutants: + print('KILLED' if m['killed'] else 'SURVIVED', m['mutant'], m['caught_by'][:4]) + if failed or any(not m['killed'] for m in mutants): + raise SystemExit(1) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/tiled-split/fixture.c b/tools/asahi/tiled-split/fixture.c new file mode 100644 index 00000000000000..dd21b5b876ba1e --- /dev/null +++ b/tools/asahi/tiled-split/fixture.c @@ -0,0 +1,459 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Host fixture for the Thunderbolt DPIN1 dispatch and tiled-display split + * admission. The production bodies of dcp_tb_dispatch_request(), + * dcp_tb_split_locked(), dcp_typec_port_untileable(), + * dcp_fabric_tunnel_slot() and dcp_fabric_binding_request() are pasted in; + * only what lies below them (join, connect, teardown, release, attach, + * rebalance) is stubbed, and every stub call is recorded. + */ +#include +#include +#include +#include +#include +#include +#include + +typedef uint64_t u64; +typedef uint32_t u32; +typedef uint8_t u8; + +#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) +#define READ_ONCE(x) (x) +#define smp_load_acquire(p) (*(p)) +#define lockdep_assert_held(l) ((void)(l)) +#define scoped_guard(type, lock) for (int _sg = 1; _sg; _sg = 0) +#define time_before(a, b) ((long)((a) - (b)) < 0) +#define dev_warn(dev, ...) fprintf(stderr, __VA_ARGS__) +#define EXPORT_SYMBOL_GPL(x) + +struct list_head { struct list_head *next, *prev; }; +#define LIST_HEAD_INIT(n) { &(n), &(n) } +static void INIT_LIST_HEAD(struct list_head *l) { l->next = l->prev = l; } +static bool list_empty(const struct list_head *l) { return l->next == l; } +static void list_add_tail(struct list_head *n, struct list_head *h) +{ + n->prev = h->prev; n->next = h; h->prev->next = n; h->prev = n; +} +#define list_for_each_entry(pos, head, member) \ + for (pos = container_of((head)->next, __typeof__(*pos), member); \ + &pos->member != (head); \ + pos = container_of(pos->member.next, __typeof__(*pos), member)) + +struct mutex { int unused; }; +struct device { int unused; }; +struct mux_chip; +struct mux_control { struct mux_chip *chip; }; +struct mux_chip { struct mux_control mux[3]; unsigned int controllers; }; + +struct dptx_port { bool enabled, connected, tile_hint; }; +struct apple_dcp { + struct device *dev; + bool external; + struct dptx_port dptxport[2]; + struct mutex tb_lock; + bool tb_retiring; + int (*tb_dpin_set_active)(void *, bool); + void *tb_dpin_ctx; + struct { + bool active, ready; + u64 generation; + int (*set_active)(void *, bool); + void *binding; + } split; +}; + +struct dcp_fabric_route { + struct dcp_fabric_route *next; + void *pipeline; + bool tunnel; + unsigned int dpin; + u8 tunnel_clock_blocked; +}; +struct dcp_fabric_port { + unsigned long key; + struct dcp_fabric_port *next; + struct dcp_fabric_route *routes; + struct dcp_fabric_route *owner[2]; + struct dcp_fabric_route *preferred; + u32 candidate_crtcs[2]; + bool wanted, hpd; + void *plan; +}; +struct apple_dcp_typec_route { + struct apple_dcp *dcp; + struct list_head port_link; + struct dcp_fabric_route core; + bool tunnel; + unsigned int tunnel_dpin; + u64 tunnel_generation; + struct mux_control *dpin[2]; + struct mux_control *xbar; +}; +struct apple_dcp_typec_port { + struct dcp_fabric_port core; + struct list_head routes; + struct apple_dcp_typec_route *owner, *secondary_owner; + struct apple_dcp *split_dcp; + unsigned long tile_hint_deadline; +}; +struct dcp_tb_attach_context { + unsigned int dpin; + bool active; + u64 generation; + int (*set_active)(void *, bool); + void *binding; + struct apple_dcp_typec_port *port; + struct apple_dcp_typec_route **slot; + bool planned; +}; +struct dcp_fabric_attach_ops { int unused; }; + +static bool tiled_split = true; +static unsigned long jiffies = 1000; +static int dcp_typec_fabric_lock; +static const struct dcp_fabric_attach_ops dcp_tb_attach_ops; + +/* --- recorded stubs --- */ +static struct { + unsigned int teardown, join, connect, release, attach, rebalance; + unsigned int attach_dpin[4]; + int teardown_ret, connect_ret; + struct apple_dcp *attach_dcp[2]; +} st; + +static int dcp_tb_split_teardown_locked(struct apple_dcp_typec_port *port, bool force) +{ + (void)force; + st.teardown++; + if (port->split_dcp) { + port->split_dcp->split.active = false; + port->split_dcp->split.generation = 0; + port->split_dcp = NULL; + } + return st.teardown_ret; +} + +static int dcp_tb_split_join_locked(struct apple_dcp_typec_port *port, + struct apple_dcp_typec_route *route, + struct mux_control *xbar, u64 generation, + int (*set_active)(void *, bool), void *binding) +{ + (void)xbar; + st.join++; + port->split_dcp = route->dcp; + route->dcp->split.active = true; + route->dcp->split.generation = generation; + route->dcp->split.set_active = set_active; + route->dcp->split.binding = binding; + return 0; +} + +static int dcp_dptx_connect(struct apple_dcp *dcp, unsigned int port) +{ + (void)dcp; (void)port; + st.connect++; + return st.connect_ret; +} + +static int dcp_tb_release_locked(struct apple_dcp_typec_port *port, unsigned int dpin) +{ + st.release++; + if (dpin) + port->secondary_owner = NULL; + else + port->owner = NULL; + return 0; +} + +static struct apple_dcp_typec_route attach_route[2]; + +static int dcp_fabric_run_attach(const struct dcp_fabric_attach_ops *ops, + struct dcp_tb_attach_context *ctx) +{ + struct apple_dcp_typec_route *r = &attach_route[ctx->dpin]; + + (void)ops; + st.attach_dpin[st.attach++] = ctx->dpin; + r->dcp = st.attach_dcp[ctx->dpin]; + r->tunnel = true; + r->tunnel_dpin = ctx->dpin; + r->tunnel_generation = ctx->generation; + *ctx->slot = r; + return 0; +} + +static struct apple_dcp_typec_route * +dcp_typec_rebalance_locked(struct apple_dcp_typec_port *arriving, unsigned int dpin) +{ + (void)arriving; (void)dpin; + st.rebalance++; + return NULL; +} + +/* PRODUCTION_FUNCTIONS */ + +/* --- topology --- */ +static struct apple_dcp dcp_a, dcp_b; +static struct apple_dcp_typec_route route_a, route_b; +static struct apple_dcp_typec_port port; +static struct mux_chip chip; + +static int set_active(void *binding, bool active) { (void)binding; (void)active; return 0; } + +enum kind { NONE, ALL_EXTERNAL, ALL_INTERNAL, MIXED }; + +static void topology(enum kind kind, bool port1_ready) +{ + memset(&st, 0, sizeof(st)); + memset(&dcp_a, 0, sizeof(dcp_a)); + memset(&dcp_b, 0, sizeof(dcp_b)); + memset(&route_a, 0, sizeof(route_a)); + memset(&route_b, 0, sizeof(route_b)); + memset(&port, 0, sizeof(port)); + memset(attach_route, 0, sizeof(attach_route)); + INIT_LIST_HEAD(&port.routes); + chip.controllers = 3; + for (int i = 0; i < 3; i++) + chip.mux[i].chip = &chip; + dcp_a.external = kind == ALL_EXTERNAL || kind == MIXED; + dcp_b.external = kind == ALL_EXTERNAL; + dcp_a.dptxport[1].enabled = dcp_b.dptxport[1].enabled = port1_ready; + route_a.dcp = &dcp_a; + route_b.dcp = &dcp_b; + route_a.xbar = route_b.xbar = &chip.mux[0]; + if (kind != NONE) { + list_add_tail(&route_a.port_link, &port.routes); + list_add_tail(&route_b.port_link, &port.routes); + } + st.attach_dcp[0] = &dcp_a; + st.attach_dcp[1] = &dcp_b; + tiled_split = true; + jiffies = 1000; + port.tile_hint_deadline = 3000; +} + +/* The dpin0 tunnel route already on the port, on @dcp. */ +static void owner_on(struct apple_dcp *dcp) +{ + attach_route[0].dcp = dcp; + attach_route[0].tunnel = true; + attach_route[0].tunnel_dpin = 0; + attach_route[0].tunnel_generation = 5; + attach_route[0].xbar = &chip.mux[0]; + port.owner = &attach_route[0]; +} + +static int request(unsigned int dpin, bool active, u64 generation) +{ + struct dcp_tb_attach_context ctx = { + .dpin = dpin, .active = active, .generation = generation, + .set_active = set_active, .binding = &port, + }; + + return dcp_tb_dispatch_request(&ctx, &port.core); +} + +static int split(bool active, u64 generation) +{ + struct dcp_tb_attach_context ctx = { + .dpin = 1, .active = active, .generation = generation, + .set_active = set_active, .binding = &port, + }; + + return dcp_tb_split_locked(&port, &ctx); +} + +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "%s:%d: %s\n", __func__, __LINE__, #c); exit(1); } } while (0) + +/* T6030: every route an external processor. */ +static void t6030_dpin1_alone(void) +{ + topology(ALL_EXTERNAL, true); + CHECK(split(true, 9) == -EOPNOTSUPP); + CHECK(request(1, true, 9) == 0); + CHECK(st.attach == 1 && st.attach_dpin[0] == 1 && port.secondary_owner); + CHECK(!st.join && !st.connect && !st.teardown); +} + +static void t6030_dpin1_alone_before_services(void) +{ + /* No port 1 service yet: the identity decides, not readiness. */ + topology(ALL_EXTERNAL, false); + CHECK(request(1, true, 9) == 0); + CHECK(st.attach == 1 && !st.join); +} + +static void t6030_dpin1_with_external_owner(void) +{ + topology(ALL_EXTERNAL, true); + owner_on(&dcp_a); + dcp_a.dptxport[0].tile_hint = true; + CHECK(split(true, 9) == -EOPNOTSUPP); + CHECK(request(1, true, 9) == 0); + CHECK(st.attach == 1 && st.attach_dpin[0] == 1 && !st.join); +} + +static void t6030_dpin1_then_dpin0(void) +{ + topology(ALL_EXTERNAL, true); + CHECK(request(1, true, 9) == 0); + CHECK(request(0, true, 10) == 0); + CHECK(st.attach == 2 && st.attach_dpin[0] == 1 && st.attach_dpin[1] == 0); + CHECK(port.owner && port.secondary_owner && !st.join); +} + +static void t6030_dpin0_then_dpin1(void) +{ + topology(ALL_EXTERNAL, true); + CHECK(request(0, true, 10) == 0); + CHECK(request(1, true, 9) == 0); + CHECK(st.attach == 2 && st.attach_dpin[0] == 0 && st.attach_dpin[1] == 1); + CHECK(port.owner && port.secondary_owner && !st.join); +} + +static void t6030_split_off(void) +{ + topology(ALL_EXTERNAL, true); + tiled_split = false; + CHECK(request(1, true, 9) == 0); + CHECK(st.attach == 1 && !st.join); +} + +static void t6030_inactive_dpin1(void) +{ + topology(ALL_EXTERNAL, true); + CHECK(split(false, 9) == -EOPNOTSUPP); + CHECK(request(1, false, 9) == -ESTALE); + CHECK(!st.attach && !st.teardown && !st.release); +} + +/* M1/M2: pipelines that can host a tile keep the dpin0 wait. */ +static void internal_dpin1_alone_waits(void) +{ + topology(ALL_INTERNAL, true); + CHECK(request(1, true, 9) == -ENODEV); + CHECK(!st.attach && !st.join); +} + +static void internal_not_ready_waits(void) +{ + /* Port 1 not announced yet is no reason to give the tile up. */ + topology(ALL_INTERNAL, false); + CHECK(request(1, true, 9) == -ENODEV); + CHECK(!st.attach); +} + +static void mixed_routes_wait(void) +{ + topology(MIXED, true); + CHECK(request(1, true, 9) == -ENODEV); + CHECK(!st.attach); +} + +static void no_routes_wait(void) +{ + topology(NONE, true); + CHECK(request(1, true, 9) == -ENODEV); + CHECK(!st.attach); +} + +static void internal_tile_hint_pending(void) +{ + topology(ALL_INTERNAL, true); + owner_on(&dcp_a); + CHECK(request(1, true, 9) == -ENODEV); + CHECK(!st.attach && !st.join); + jiffies = 4000; + CHECK(request(1, true, 9) == 0); + CHECK(st.attach == 1 && !st.join); +} + +static void internal_tiled_join(void) +{ + topology(ALL_INTERNAL, true); + owner_on(&dcp_a); + dcp_a.dptxport[0].tile_hint = true; + CHECK(request(1, true, 9) == 0); + CHECK(st.join == 1 && st.connect == 1 && !st.attach); + CHECK(port.split_dcp == &dcp_a && dcp_a.split.ready); +} + +static void internal_owner_without_port1(void) +{ + topology(ALL_INTERNAL, true); + owner_on(&dcp_a); + dcp_a.dptxport[1].enabled = false; + dcp_a.dptxport[0].tile_hint = true; + CHECK(request(1, true, 9) == 0); + CHECK(st.attach == 1 && !st.join); +} + +/* An existing split is handled before anything else, on any port. */ +static void split_retired_teardown_first(void) +{ + topology(ALL_EXTERNAL, true); + port.split_dcp = &dcp_a; + dcp_a.split.active = true; + dcp_a.split.generation = 0; + CHECK(request(1, true, 9) == 0); + CHECK(st.teardown == 1 && !port.split_dcp && st.attach == 1); +} + +static void split_existing_release(void) +{ + topology(ALL_EXTERNAL, true); + port.split_dcp = &dcp_a; + dcp_a.split.active = true; + dcp_a.split.generation = 7; + dcp_a.split.set_active = set_active; + dcp_a.split.binding = &port; + CHECK(request(1, false, 7) == 0); + CHECK(st.teardown == 1 && !port.split_dcp && !st.attach); +} + +static void split_existing_active(void) +{ + topology(ALL_EXTERNAL, true); + port.split_dcp = &dcp_a; + dcp_a.split.active = true; + dcp_a.split.generation = 7; + dcp_a.split.set_active = set_active; + dcp_a.split.binding = &port; + CHECK(request(1, true, 7) == -EAGAIN); + dcp_a.split.ready = true; + CHECK(request(1, true, 7) == 0); + CHECK(!st.teardown && !st.attach && port.split_dcp == &dcp_a); +} + +static const struct { const char *name; void (*fn)(void); } cases[] = { + { "t6030-dpin1-alone", t6030_dpin1_alone }, + { "t6030-dpin1-alone-before-services", t6030_dpin1_alone_before_services }, + { "t6030-dpin1-with-external-owner", t6030_dpin1_with_external_owner }, + { "t6030-dpin1-then-dpin0", t6030_dpin1_then_dpin0 }, + { "t6030-dpin0-then-dpin1", t6030_dpin0_then_dpin1 }, + { "t6030-split-off", t6030_split_off }, + { "t6030-inactive-dpin1", t6030_inactive_dpin1 }, + { "internal-dpin1-alone-waits", internal_dpin1_alone_waits }, + { "internal-not-ready-waits", internal_not_ready_waits }, + { "mixed-routes-wait", mixed_routes_wait }, + { "no-routes-wait", no_routes_wait }, + { "internal-tile-hint-pending", internal_tile_hint_pending }, + { "internal-tiled-join", internal_tiled_join }, + { "internal-owner-without-port1", internal_owner_without_port1 }, + { "split-retired-teardown-first", split_retired_teardown_first }, + { "split-existing-release", split_existing_release }, + { "split-existing-active", split_existing_active }, +}; + +int main(int argc, char **argv) +{ + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) + if (argc > 1 && !strcmp(argv[1], cases[i].name)) { + cases[i].fn(); + return 0; + } + fprintf(stderr, "unknown case\n"); + return 2; +} diff --git a/tools/asahi/tunnel-route-tests.py b/tools/asahi/tunnel-route-tests.py index 05d0cbc018802c..5be05c91c156f6 100644 --- a/tools/asahi/tunnel-route-tests.py +++ b/tools/asahi/tunnel-route-tests.py @@ -11,6 +11,7 @@ ROOT = Path(__file__).resolve().parents[2] FUNCTIONS = { + 'include/linux/soc/apple/dp-tunnel.h': ['apple_dp_tunnel_t6030_pclk'], 'drivers/gpu/drm/apple/dcp-fabric-core.c': ['dcp_fabric_tunnel_clock_blocked'], 'drivers/gpu/drm/apple/dcp-fabric.c': [ 'dcp_fabric_snapshot_port', 'dcp_typec_tunnel_ctl'], diff --git a/tools/asahi/tunnel-route/fixture.c b/tools/asahi/tunnel-route/fixture.c index da8e6c70a212ce..dd63853c3bd369 100644 --- a/tools/asahi/tunnel-route/fixture.c +++ b/tools/asahi/tunnel-route/fixture.c @@ -8,87 +8,126 @@ typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +#define READ_ONCE(x) (x) #define BIT(n) (1U << (n)) #define lockdep_assert_held(x) ((void)0) #define list_for_each_entry(r, head, link) \ - for ((r) = *(head); (r); (r) = (r)->next) + for ((r) = *(head); (r); (r) = (r)->next) /* CORE_HEADER */ struct mux_chip; -struct mux_control { struct mux_chip *chip; }; -struct mux_chip { struct mux_control mux[3]; unsigned int controllers; }; -struct apple_connector { u32 candidate_crtcs; }; -struct apple_crtc { struct { unsigned int index; } base; }; +struct mux_control { + struct mux_chip *chip; +}; +struct mux_chip { + struct mux_control mux[3]; + unsigned int controllers; +}; +struct apple_connector { + u32 candidate_crtcs; +}; +struct apple_crtc { + struct { + unsigned int index; + } base; +}; struct apple_dcp { - struct dcp_fabric_pipeline fabric; - struct apple_crtc *crtc; - bool tb_retiring, external; - void *fixed_phy, *active_typec_route; + struct dcp_fabric_pipeline fabric; + struct apple_crtc *crtc; + bool tb_retiring, external, clamshell, clamshell_free; + void *fixed_phy, *active_typec_route; }; struct apple_dcp_typec_route { - struct apple_dcp_typec_route *next; - struct apple_dcp *dcp; - struct dcp_fabric_route core; - bool tunnel; - unsigned int tunnel_dpin, mux_index; - struct mux_control *xbar, *dpin[2]; + struct apple_dcp_typec_route *next; + struct apple_dcp *dcp; + struct dcp_fabric_route core; + bool tunnel; + unsigned int tunnel_dpin, mux_index; + struct mux_control *xbar, *dpin[2]; }; struct apple_dcp_typec_port { - struct dcp_fabric_port core; - struct dcp_fabric_plan plan; - struct apple_dcp_typec_route *routes, *owner, *secondary_owner, *preferred_route; - struct apple_connector *connector, *secondary_connector; - bool dp_wanted, dp_hpd; + struct dcp_fabric_port core; + struct dcp_fabric_plan plan; + struct apple_dcp_typec_route *routes, *owner, *secondary_owner, + *preferred_route; + struct apple_connector *connector, *secondary_connector; + bool dp_wanted, dp_hpd; }; static bool t6030; static bool of_machine_is_compatible(const char *compatible) { - assert(!strcmp(compatible, "apple,t6030")); - return t6030; + assert(!strcmp(compatible, "apple,t6030")); + return t6030; } #define drm_crtc_index(crtc) ((crtc)->index) -static bool dcp_typec_route_busy(struct apple_dcp_typec_route *r) { return false; } -static bool dcp_typec_tunnel_held(struct apple_dcp *d) { return false; } -static bool dcp_typec_safe_held(struct apple_dcp *d) { return false; } +static bool dcp_typec_route_busy(struct apple_dcp_typec_route *r) +{ + return false; +} +static bool dcp_typec_tunnel_held(struct apple_dcp *d) +{ + return false; +} +static bool dcp_typec_safe_held(struct apple_dcp *d) +{ + return false; +} static enum dcp_fabric_presence_state dcp_hdmi_presence(struct apple_dcp *d) { - return DCP_FABRIC_ABSENT; + return DCP_FABRIC_ABSENT; +} +static bool dcpext_scanout_terminal(struct apple_dcp *d) +{ + return false; +} +static bool dcp_tb_services_ready(struct apple_dcp *d) +{ + return true; } -static bool dcpext_scanout_terminal(struct apple_dcp *d) { return false; } -static bool dcp_tb_services_ready(struct apple_dcp *d) { return true; } /* PRODUCTION_FUNCTIONS */ int main(void) { - struct mux_chip chip = { .controllers = 3 }; - struct apple_crtc crtc = { .base.index = 1 }; - struct apple_dcp dcp = { .crtc = &crtc }; - struct apple_dcp_typec_route source0 = { .dcp = &dcp, .xbar = &chip.mux[0] }; - struct apple_dcp_typec_route source2 = { - .dcp = &dcp, .xbar = &chip.mux[0], .mux_index = 2, - }; - struct apple_dcp_typec_port port = { .routes = &source0 }; - source0.next = &source2; - for (unsigned int i = 0; i < 3; i++) chip.mux[i].chip = &chip; - for (unsigned int soc = 0; soc < 2; soc++) { - t6030 = soc; - for (unsigned int named = 0; named < 2; named++) { - source0.dpin[0] = source2.dpin[0] = named ? &chip.mux[1] : NULL; - source0.dpin[1] = source2.dpin[1] = named ? &chip.mux[2] : NULL; - dcp_fabric_snapshot_port(&port, true); - assert(port.core.routes == &source0.core); - assert(source0.core.next == &source2.core); - assert(!source2.core.next); - assert(source0.core.tunnel_clock_blocked == (soc ? BIT(1) : 0)); - assert(source2.core.tunnel_clock_blocked == (soc ? BIT(1) : 0)); - assert(dcp_typec_tunnel_ctl(&source0, 0) == &chip.mux[1]); - assert(dcp_typec_tunnel_ctl(&source0, 1) == (soc ? NULL : &chip.mux[2])); - assert(dcp_typec_tunnel_ctl(&source2, 0) == &chip.mux[1]); - assert(dcp_typec_tunnel_ctl(&source2, 1) == (soc ? NULL : &chip.mux[2])); - assert(!dcp_typec_tunnel_ctl(&source0, 2)); - /* Late migration checks the real route, even with a stale snapshot. */ - source2.core.tunnel_clock_blocked = 0; - assert(dcp_typec_tunnel_ctl(&source2, 0) == &chip.mux[1]); - } - } - puts("PASS: DCP snapshot, named/legacy controls, invalid DP IN, stale snapshot"); - return 0; + struct mux_chip chip = { .controllers = 3 }; + struct apple_crtc crtc = { .base.index = 1 }; + struct apple_dcp dcp = { .crtc = &crtc }; + struct apple_dcp_typec_route source0 = { .dcp = &dcp, + .xbar = &chip.mux[0] }; + struct apple_dcp_typec_route source2 = { + .dcp = &dcp, + .xbar = &chip.mux[0], + .mux_index = 2, + }; + struct apple_dcp_typec_port port = { .routes = &source0 }; + source0.next = &source2; + for (unsigned int i = 0; i < 3; i++) + chip.mux[i].chip = &chip; + for (unsigned int soc = 0; soc < 2; soc++) { + t6030 = soc; + for (unsigned int named = 0; named < 2; named++) { + source0.dpin[0] = source2.dpin[0] = + named ? &chip.mux[1] : NULL; + source0.dpin[1] = source2.dpin[1] = + named ? &chip.mux[2] : NULL; + dcp_fabric_snapshot_port(&port, true); + assert(port.core.routes == &source0.core); + assert(source0.core.next == &source2.core); + assert(!source2.core.next); + assert(source0.core.tunnel_clock_blocked == 0); + assert(source2.core.tunnel_clock_blocked == 0); + assert(dcp_typec_tunnel_ctl(&source0, 0) == + &chip.mux[1]); + assert(dcp_typec_tunnel_ctl(&source0, 1) == + &chip.mux[2]); + assert(dcp_typec_tunnel_ctl(&source2, 0) == + &chip.mux[1]); + assert(dcp_typec_tunnel_ctl(&source2, 1) == + &chip.mux[2]); + assert(!dcp_typec_tunnel_ctl(&source0, 2)); + /* Late migration checks the real route, even with a stale snapshot. */ + source2.core.tunnel_clock_blocked = 0; + assert(dcp_typec_tunnel_ctl(&source2, 0) == + &chip.mux[1]); + } + } + puts("PASS: DCP snapshot, named/legacy controls, invalid DP IN, stale snapshot"); + return 0; } diff --git a/tools/aurora-ci/aurora.kunitconfig b/tools/aurora-ci/aurora.kunitconfig index babcfcd6312ecc..13805653b4b2d2 100644 --- a/tools/aurora-ci/aurora.kunitconfig +++ b/tools/aurora-ci/aurora.kunitconfig @@ -2,7 +2,7 @@ # omacom/linux-aurora (integration/aurora). # # Run with tools/testing/kunit/kunit.py run --arch=arm64 (QEMU virt, -cpu max) -# and --make_options LLVM=... . At 1b4997bbab62 this builds one kernel with +# and --make_options LLVM=... . Historical result at 1b4997bbab62: # 98 suites / 1399 cases (expected: 3 skips, 0 failures). # Needs a Rust toolchain: the SEP, AOP, T8140 audio and Asahi GPU code is Rust. # The kernel uses 16K pages and 48-bit VA, as the shipped kernel does: @@ -169,6 +169,14 @@ CONFIG_DMADEVICES=y CONFIG_DMA_ENGINE=y CONFIG_SND_SOC_APPLE_T8140_AOP_AUDIO=y +# Cirrus jack codecs: clock switching and playback resume/prepare recovery +# I2C is enabled above; build the codecs in with their real KUnit suites. +CONFIG_SND_SOC_CS42L42=y +CONFIG_SND_SOC_CS42L42_CORE=y +CONFIG_SND_SOC_CS42L42_TEST=y +CONFIG_SND_SOC_CS42L84=y +CONFIG_SND_SOC_CS42L84_TEST=y + # Wireless and Bluetooth: brcmfmac scan timeout, MT7932 (J700) CONFIG_NET=y CONFIG_NETDEVICES=y diff --git a/tools/aurora-ci/check-commits.py b/tools/aurora-ci/check-commits.py index 16ad3712a96fd3..83c8864ffce83c 100755 --- a/tools/aurora-ci/check-commits.py +++ b/tools/aurora-ci/check-commits.py @@ -36,20 +36,35 @@ DEPTHS = (64, 256, 1024, 4096) -def git(repo, *args, check=True): - return subprocess.run(["git", "-C", str(repo), *args], check=check, text=True, +def git(repo, *args, check=True, text=True): + return subprocess.run(["git", "-C", str(repo), *args], check=check, text=text, stdout=subprocess.PIPE, stderr=subprocess.PIPE) +def range_history_complete(repo, base, head): + if git(repo, "merge-base", base, head, check=False).returncode != 0: + return False + shallow = Path(git(repo, "rev-parse", "--path-format=absolute", + "--git-path", "shallow").stdout.strip()) + if not shallow.exists(): + return True + # A recent merge can expose base while an older topic parent is still + # shallow. Such a boundary looks like a root commit to format-patch. + boundaries = set(shallow.read_text().split()) + added = set(git(repo, "rev-list", f"{base}..{head}").stdout.split()) + return boundaries.isdisjoint(added) + + def ensure_history(repo, remote, base, head): """Fetch base and head, deepening until they share history. - Returns False if they still do not meet at the deepest fetch.""" + Also require every commit added by the range to have its parents. + Returns False if either condition remains unmet at the deepest fetch.""" for depth in DEPTHS: - if git(repo, "merge-base", base, head, check=False).returncode == 0: + if range_history_complete(repo, base, head): return True git(repo, "fetch", "--quiet", "--no-tags", f"--depth={depth}", remote, base, head) - return git(repo, "merge-base", base, head, check=False).returncode == 0 + return range_history_complete(repo, base, head) def commits_in(repo, base, head): @@ -64,13 +79,15 @@ def describe(repo, sha): def run_checkpatch(repo, sha): """checkpatch.pl findings for one commit, as dicts.""" - patch = git(repo, "format-patch", "-1", "--stdout", sha).stdout + # A patch may contain non-UTF-8 source text. Preserve its bytes for perl; + # only diagnostic output is decoded for the report. + patch = git(repo, "format-patch", "-1", "--stdout", sha, text=False).stdout result = subprocess.run( ["perl", "scripts/checkpatch.pl", "--terse", "--showfile", "--show-types", "--no-summary", - "--color=never", "-"], cwd=repo, input=patch, text=True, + "--color=never", "-"], cwd=repo, input=patch, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) findings = [] - for line in result.stdout.splitlines(): + for line in result.stdout.decode("utf-8", errors="replace").splitlines(): match = CHECKPATCH_LINE.match(line.strip()) if match: findings.append(match.groupdict()) @@ -91,8 +108,9 @@ def check(repo, remote, base, head, max_commits, checkpatch=True): "mode": "full", "notes": []} if not ensure_history(repo, remote, base, head): report["mode"] = "unrelated" - report["notes"].append(f"{base[:12]} and {head[:12]} share no history within " - f"{DEPTHS[-1]} commits; commit checks skipped") + report["notes"].append(f"Complete added history for {base[:12]}..{head[:12]} " + f"was not established within {DEPTHS[-1]} commits; " + "commit checks skipped") return report shas = commits_in(repo, base, head) @@ -154,7 +172,10 @@ def main(argv=None): report = check(args.repo, args.remote, args.base, args.head, args.max_commits, checkpatch=not args.no_checkpatch) except subprocess.CalledProcessError as error: - print(f"::error title=Commit checks::{' '.join(error.cmd)} failed: {escape(error.stderr or '')}", + stderr = error.stderr or "" + if isinstance(stderr, bytes): + stderr = stderr.decode("utf-8", errors="replace") + print(f"::error title=Commit checks::{' '.join(error.cmd)} failed: {escape(stderr)}", file=sys.stderr) return 1 if args.report: diff --git a/tools/aurora-ci/host-tests.json b/tools/aurora-ci/host-tests.json index 321f6cf163de53..d286dde870e537 100644 --- a/tools/aurora-ci/host-tests.json +++ b/tools/aurora-ci/host-tests.json @@ -31,7 +31,8 @@ "tools/aurora-*", "tools/testing/apple", "tools/testing/selftests/drivers/apple", - "tools/testing/selftests/drivers/gpu/apple-*" + "tools/testing/selftests/drivers/gpu/apple-*", + "tools/testing/selftests/drivers/gpu/asahi-g15" ], "suites": [ { @@ -53,6 +54,17 @@ ], "known_failure": "its mocks predate the current apple-dart.c (no u32, fw_mirror/fw_handoff, apple_dart_fw_invalidate; apple_dart_hw_sync_locked takes three arguments now)" }, + { + "name": "tools/asahi/avd-codec-tail-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/avd-codec-tail-tests.py", + "--mutations", + "--output", + "{output}" + ] + }, { "name": "tools/asahi/avd-av1-tail-tests.py", "group": "tools", @@ -1934,6 +1946,17 @@ "tools/testing/selftests/drivers/gpu/apple-afkv2/test-admission.py" ] }, + { + "name": "tools/testing/selftests/drivers/gpu/apple-dcp/plane-layout.py", + "group": "tools", + "argv": [ + "python3", + "tools/testing/selftests/drivers/gpu/apple-dcp/plane-layout.py", + "--mutations", + "--output", + "{output}" + ] + }, { "name": "tools/testing/selftests/drivers/gpu/apple-dcp/run.sh", "group": "tools", @@ -1961,10 +1984,240 @@ "tools/testing/selftests/drivers/net/mt7932_e2e_test.py", "-v" ] + }, + { + "name": "tools/asahi/tb-dp-repair-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/tb-dp-repair-tests.py", + "--mutations", + "--output", + "{output}" + ] + }, + { + "name": "tools/asahi/t6030-clock-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/t6030-clock-tests.py", + "--out", + "{output}" + ] + }, + { + "name": "tools/asahi/t6030-wiring-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/t6030-wiring-tests.py", + "--out", + "{output}" + ] + }, + { + "name": "tools/asahi/tiled-split-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/tiled-split-tests.py", + "--mutations", + "--out", + "{output}" + ] + }, + { + "name": "tools/asahi/t6030-pmp-supplier-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/t6030-pmp-supplier-tests.py", + "--mutations", + "--output", + "{output}" + ] + }, + { + "name": "tools/asahi/atc-usb3-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/atc-usb3-tests.py", + "--mutations", + "--out", + "{output}" + ] + }, + { + "name": "tools/asahi/g15-input-error-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/g15-input-error-tests.py", + "--mutations", + "--output", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual production-body host control plus runtime mutants; kernel services modeled, no private hardware fixtures." + }, + { + "name": "tools/asahi/g15-queue-credit-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/g15-queue-credit-tests.py", + "--mutations", + "--output", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual production-body host control plus runtime mutants; kernel services modeled, no private hardware fixtures." + }, + { + "name": "tools/asahi/g15-probe-init-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/g15-probe-init-tests.py", + "--mutations", + "--output", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual production-body host control plus runtime mutants; kernel services modeled, no private hardware fixtures." + }, + { + "name": "tools/asahi/g15-retention-tests.py", + "group": "tools", + "commits": [ + "31da169251bd34d5810a0874563d9a019b85bf56" + ], + "argv": [ + "python3", + "tools/asahi/g15-retention-tests.py", + "--mutations", + "--output", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual G15 and KBox ownership bodies with drop-count allocation failures; old-source P1 controls must fail at runtime. Public synthetic inputs only." + }, + { + "name": "tools/asahi/g15-maintained-handoff-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/g15-maintained-handoff-tests.py", + "--mutations", + "--output", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual production-body host control plus runtime mutants; kernel services modeled, no private hardware fixtures." + }, + { + "name": "tools/asahi/g15-zero-words-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/g15-zero-words-tests.py", + "--mutations", + "--evidence", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual production-body host control plus runtime mutants; kernel services modeled, no private hardware fixtures." + }, + { + "name": "tools/asahi/g15-pb-growth-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/g15-pb-growth-tests.py", + "--mutations", + "--output", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual production-body host control plus runtime mutants; kernel services modeled, no private hardware fixtures." + }, + { + "name": "tools/asahi/g15-stats-drain-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/g15-stats-drain-tests.py", + "--mutations", + "--output", + "{output}" + ], + "rust": "1.93.1", + "note": "Actual production-body host control plus runtime mutants; kernel services modeled, no private hardware fixtures." + }, + { + "name": "tools/testing/selftests/drivers/gpu/asahi-g15/run.py", + "group": "tools", + "argv": [ + "python3", + "tools/testing/selftests/drivers/gpu/asahi-g15/run.py" + ], + "rust": "1.93.1", + "note": "Public synthetic Rust/C host cases; two unavailable private-hardware fixture cases remain explicitly ignored." + }, + { + "name": "tools/asahi/t6030-pmp-graph-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/t6030-pmp-graph-tests.py", + "--mutations", + "--output", + "{output}" + ], + "note": "Actual production-body host boundaries and runtime mutants; no firmware or hardware qualification." + }, + { + "name": "tools/asahi/t6030-display-admission-tests.py", + "group": "tools", + "argv": [ + "python3", + "tools/asahi/t6030-display-admission-tests.py", + "--mutations", + "--output", + "{output}" + ], + "note": "Actual production-body host boundaries and runtime mutants; no firmware or hardware qualification." + }, + { + "name": "tools/asahi/t6030-display-linkage-tests.py", + "group": "tools", + "setup": [ + [ + "make", + "-s", + "O={output}-conf", + "allnoconfig" + ] + ], + "argv": [ + "python3", + "tools/asahi/t6030-display-linkage-tests.py", + "--conf", + "{output}-conf/scripts/kconfig/conf", + "--output", + "{output}" + ], + "note": "Build only the host Kconfig tool in an isolated output directory; check all built-in/module dependency combinations." } ], "helpers": { - "tools/testing/selftests/drivers/gpu/apple-dcp/run.py": "the implementation behind tools/testing/selftests/drivers/gpu/apple-dcp/run.sh, which is listed" + "tools/testing/selftests/drivers/gpu/apple-dcp/run.py": "the implementation behind tools/testing/selftests/drivers/gpu/apple-dcp/run.sh, which is listed", + "tools/testing/selftests/drivers/gpu/asahi-g15/uat-owner.c": "compiled and executed by the registered asahi-g15/run.py actual reservation-owner fixture", + "tools/testing/selftests/drivers/gpu/asahi-g15/pmp-bridge.c": "compiled and executed by the registered asahi-g15/run.py maintained PMP fixture", + "tools/asahi/t6030-pmp-graph-tests.c": "compiled and executed by the corresponding registered Python actual-body host suite", + "tools/asahi/t6030-display-admission-tests.c": "compiled and executed by the corresponding registered Python actual-body host suite" }, "excluded": { "tools/aurora-sep/tests/coordinator/runtime-check.sh": "Needs /dev/sep-bio, a running kernel booted with trusted.source=applesep, the hw_random sysfs interface and fprintd. Coordinator payload for an approved device.", diff --git a/tools/aurora-ci/kunit-expected.json b/tools/aurora-ci/kunit-expected.json index 2821a087374e4f..9c7520e8be6c48 100644 --- a/tools/aurora-ci/kunit-expected.json +++ b/tools/aurora-ci/kunit-expected.json @@ -19,13 +19,5 @@ "reason": "By design when built in: the case skips while system_state < SYSTEM_RUNNING, because built-in KUnit runs before mark_readonly(). It only runs when trusted_source_kunit is loaded as a module after boot, which kunit.py run does not do (security/keys/trusted-keys/tests/trusted_source_kunit.c)." } }, - "warnings": { - "apple-display-parser.parser_attribute_deferred": [ - { - "site": "kernel/workqueue.c:__queue_work", - "count": 1, - "reason": "WARN_ON(!list_empty(&work->entry)): dcp_attributes_replace() schedules dcp->connector->hotplug_wq, but the test allocates the connector with kunit_kzalloc() and never calls INIT_WORK() on it, so the work is refused. The test still passes." - } - ] - } + "warnings": {} } diff --git a/tools/aurora-ci/tests/test_check_commits.py b/tools/aurora-ci/tests/test_check_commits.py index baf9b9b4829f72..ff5a5970f6cace 100644 --- a/tools/aurora-ci/tests/test_check_commits.py +++ b/tools/aurora-ci/tests/test_check_commits.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 import json +import subprocess from support import TempDirTestCase, commit_file, git, load @@ -32,6 +33,51 @@ def test_signed_series_passes_from_a_shallow_clone(self): self.assertEqual(report["failures"], []) self.assertEqual(report["uapi"], []) + def test_non_utf8_patch_reaches_checkpatch_unchanged(self): + source = self.origin / "fixture.c" + source.write_bytes(b"/* legacy byte: \xc0 */\n") + git(self.origin, "add", "fixture.c") + git(self.origin, "commit", "--quiet", "-m", "legacy source" + SIGNED) + head = git(self.origin, "rev-parse", "HEAD") + scripts = self.origin / "scripts" + scripts.mkdir() + (scripts / "checkpatch.pl").write_text( + 'use strict; use warnings;\n' + 'binmode STDIN; binmode STDOUT;\n' + 'local $/; my $patch = ;\n' + 'open my $out, ">:raw", "seen.patch" or die $!;\n' + 'print {$out} $patch; close $out or die $!;\n' + 'print "fixture.c:1: WARNING:NON_UTF8: legacy byte \\xc0\\n";\n' + ) + expected = subprocess.check_output( + ["git", "-C", str(self.origin), "format-patch", "-1", "--stdout", head]) + self.assertIn(b"\xc0", expected) + report = checks.check(self.origin, "origin", self.base, head, + max_commits=100) + self.assertEqual((self.origin / "seen.patch").read_bytes(), expected) + self.assertEqual(report["failures"], []) + finding, = report["commits"][0]["checkpatch"] + self.assertEqual(finding["type"], "NON_UTF8") + self.assertEqual(finding["message"], "legacy byte \ufffd") + + def test_shallow_merge_fetches_the_whole_added_branch(self): + git(self.origin, "checkout", "--quiet", "-b", "topic") + for i in range(70): + commit_file(self.origin, "drivers/a.c", f"{i}\n", + f"topic {i}" + SIGNED) + topic = git(self.origin, "rev-parse", "HEAD") + git(self.origin, "checkout", "--quiet", "main") + base = commit_file(self.origin, "README", "main update\n", + "main update" + SIGNED) + git(self.origin, "merge", "--quiet", "--no-ff", "-m", "Merge topic", topic) + head = git(self.origin, "rev-parse", "HEAD") + clone = self.shallow_clone(head) + report = checks.check(clone, "origin", base, head, + max_commits=100, checkpatch=False) + self.assertEqual([c["subject"] for c in report["commits"]], + [f"topic {i}" for i in range(70)]) + self.assertEqual(report["failures"], []) + def test_unsigned_commit_fails(self): unsigned = commit_file(self.origin, "drivers/a.c", "a\n", "drivers: add a\n\nNo trailer here.") head = commit_file(self.origin, "drivers/b.c", "b\n", "drivers: add b" + SIGNED) diff --git a/tools/aurora-sep/tests/test_m3_max.py b/tools/aurora-sep/tests/test_m3_max.py index 3bb279c2a24b3e..7dc7cd998279f2 100644 --- a/tools/aurora-sep/tests/test_m3_max.py +++ b/tools/aurora-sep/tests/test_m3_max.py @@ -163,7 +163,11 @@ if [[ -n ${FAKE_HOT:-} ]]; then sed -i 's/ Tp0a flt 4 80 45000$/ Tp0a flt 4 80 101000/' "$keys"; fi if mkdir "$FAKE/first-load" 2>/dev/null; then if [[ -n ${FAKE_KILL_SAMPLER:-} ]]; then pkill -KILL -f -- "$keys"; fi - if [[ -n ${FAKE_KEYS_HANG:-} ]]; then rm -f "$keys"; mkfifo "$keys"; fi + if [[ -n ${FAKE_KEYS_HANG:-} ]]; then + # Publish the blocked reader atomically: an unlink/create gap can instead + # make the sampler report a missing key list, which is a different test. + mkfifo "$keys.hang" && mv -f "$keys.hang" "$keys" + fi if [[ -n ${FAKE_KEYS_GONE:-} ]]; then rm -f "$keys"; fi fi exec sleep 60 diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/Makefile b/tools/testing/selftests/drivers/gpu/apple-dcp/Makefile index 619da7189c114b..3966be6ec2174e 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/Makefile +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/Makefile @@ -1,4 +1,4 @@ # SPDX-License-Identifier: GPL-2.0-only OR MIT -TEST_PROGS := run.sh +TEST_PROGS := run.sh plane-layout.py TEST_FILES := run.py common.py edid.py recovery.py rate.py phy.py lifecycle.py pm.py idle.py boot.py quiesce.py transaction.py accounting.py dwc3 README include ../../../lib.mk diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/README b/tools/testing/selftests/drivers/gpu/apple-dcp/README index 0c413f8af667aa..1dbec8e9d2faf2 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/README +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/README @@ -103,3 +103,16 @@ no port down and checks that none comes up. A failed USB3 power-off or reset leaves dwc3 out of host mode, and a fixed-hub host whose PIPE cannot be routed still starts. Each fixture detects these from the source, so the expectations for sources without the handover remain. + +The standalone plane-layout.py test executes the production atomic check and +update, the DRM block-format descriptors, and the surface structs with synthetic +GEM sizes. It checks RGB8/RGB10/FP16 and semiplanar YUV layouts, tile padding, +metadata, offsets, GEM boundaries, arithmetic overflow and invisible planes. +Packed P030/P230 remain supported for LINEAR; INTERCHANGE is refused and omitted +from per-format modifier advertisement until its packed tile layout is known. +DRM's three-pixel block descriptor establishes linear storage, not how those +blocks cross the interchange tile and compression-subtile boundaries. +Run `./plane-layout.py --mutations --ref --output ` +to retain the compiled before/after controls, baseline reproducer and runtime +mutation results. A compile failure never counts as a mutation kill. DRM +clipping, GEM/DMA allocation and firmware execution are outside this host test. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py index 91ccd2a84123df..4097d7db7d86ae 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py @@ -93,6 +93,12 @@ def run_unit(name, unit, output, cases=((),), includes=(), extra=()): ATC_SPLIT = ('atcphy_pipe_live', 'atcphy_usb3_route') +# The retryable T8103-generation USB3 handoff: the bounded live lock and the +# park of a live legacy PIPE, which the extracted PIPE, mux, reset and route +# functions call. Older sources have neither; atc_function() then yields ''. +ATC_T8103_LIVE = ('atcphy_pipehandler_lock_live', 'atcphy_park_live_t8103_pipehandler') + + def atc_function(source, name): """The actual ATC function @name, or nothing for a source that does not have it. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/cases.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/cases.c index dafb4d6822bee9..b210e7ff4e7194 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/cases.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/cases.c @@ -76,6 +76,8 @@ static void initial(struct fixture *f, unsigned int gen, bool fixed, bool pm) }; hardware.configure_post_tunable = post_tunable[gen]; f->atc = (struct apple_atcphy){ + /* Generation zero models an admitted base M1. */ + .t8103_usb3_workaround = gen == 0, .hw = &hardware, .regs.core = (unsigned char *)core_regs, .regs.lpdptx = (unsigned char *)core_regs, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c index 8b318ef8c2346b..10d238b9220a49 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c @@ -20,6 +20,7 @@ struct apple_atcphy { u32 dp_usb_context[2][27]; bool pipe_pending, usb_off_pending, usb_off_drained; bool usb3_port_off, park_owed; + bool t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround; enum atcphy_mode mode, typec_mode; enum atcphy_pipehandler_state pipe_state; }; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index dfd6d61bcf74fd..1cee66408389df 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -76,6 +76,8 @@ def function(file,signature): static void schedule_work(unsigned int *p) { (*p)++; } struct work_struct { bool pending; }; static bool queue_work(void *wq,struct work_struct *w) { assert(wq);bool fresh=!w->pending;w->pending=true;return fresh; } +/* Only the 14.7 external role queues the AV client close; these providers never do. */ +static bool __attribute__((unused)) cancel_work_sync(struct work_struct *w) { bool queued=w->pending;assert(!queued);return queued; } struct apple_dcp;struct apple_dcp_afkep;struct apple_epic_service; void afk_service_retry(struct apple_dcp_afkep *ep); struct apple_epic_service_ops { char name[32];bool reusable,optional;void (*init)(struct apple_epic_service *,const char *,const char *,s64);int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*teardown)(struct apple_epic_service *); }; @@ -92,14 +94,16 @@ def function(file,signature): struct apple_dcp { void *dev;int fw_compat;struct apple_dcp_afkep *dcpavservep;struct apple_connector *connector; bool external_physically_absent,hpd_mutex,quiescing,typec_cable_connected;u64 typec_generation;unsigned int nr_modes; - struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead; - struct { bool lock,enabled;u64 epoch;int enable_completion;struct apple_epic_service *service,*opened; } dcpavserv; + struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead,external_native; + struct { bool lock,enabled;u64 epoch;int enable_completion;struct apple_epic_service *service,*opened; + u64 opened_epoch,close_gen,terminated_epoch,close_epoch;bool opening;struct work_struct close_wq; } dcpavserv; }; -'''+internal_inline(root,'dcp_fw_is_14_7')+r'''struct epic_cmd { u32 retcode;u64 rxbuf,txbuf;u32 rxlen,txlen; }; +'''+internal_inline(root,'dcp_fw_is_14_7')+internal_inline(root,'dcp_is_v14_7_external')+r'''struct epic_cmd { u32 retcode;u64 rxbuf,txbuf;u32 rxlen,txlen; }; static unsigned int dma_frees,opens; static int open_error,open_action; void dpavservep_detach(struct apple_dcp *dcp); +static void afk_recv_handle_teardown(struct apple_dcp_afkep *ep, u32 channel); static void inject_owner(struct apple_dcp_afkep *ep,u32 pending_channel); static void dma_free_coherent(void *dev,size_t size,void *p,dma_addr_t address) { (void)dev;assert(size && (uintptr_t)p==address);free(p);dma_frees++; } @@ -582,6 +586,7 @@ def function(file, signature): #define dev_dbg(...) ((void)0) #define dev_info(...) ((void)0) #define dev_err(...) ((void)0) +#define dev_warn(...) ((void)0) #define trace_dcpavserv_init(...) ((void)0) #define DRM_CONNECTOR_REGISTERED 1 #define to_platform_device(x) (x) @@ -610,16 +615,17 @@ def function(file, signature): struct apple_epic_service { struct apple_dcp_afkep *ep; unsigned int users; bool enabled,torndown; struct { u64 generation,epoch; } admission; void *cookie; unsigned int channel; }; struct apple_dcp { struct apple_dcp_afkep *dcpavservep, *dptxep, *avep, *systemep, *ibootep, *dptx_controller_ep; - struct { bool lock, enabled; u64 epoch; int enable_completion; struct apple_epic_service *service, *opened; } dcpavserv; + struct { bool lock, enabled; u64 epoch; int enable_completion; struct apple_epic_service *service, *opened; + u64 opened_epoch, close_gen, terminated_epoch; bool opening; } dcpavserv; struct apple_connector *connector; unsigned int nr_modes; - struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead; + struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead,external_native; bool external_physically_absent,hpd_mutex, typec_cable_connected, quiescing; u64 typec_generation; int fw_compat; void *dev; }; struct drm_edid { int identity; }; -static unsigned int reads, allocations, legacy_reads, receives; +'''+internal_inline(root,'dcp_is_v14_7_external')+r'''static unsigned int reads, allocations, legacy_reads, receives; static unsigned int event; static struct apple_dcp_afkep *received_ep; static struct apple_epic_service *afk_service_get(struct apple_epic_service *s) @@ -643,6 +649,10 @@ def function(file, signature): { legacy_reads++; return dcpavserv_read_edid_inline(s); } static int __attribute__((unused)) afk_service_call(struct apple_epic_service *s,unsigned short group,unsigned command,const void *data,size_t data_len,size_t data_pad,void *output,size_t output_len,size_t output_pad) { (void)s;(void)group;(void)command;(void)data;(void)data_len;(void)data_pad;(void)output;(void)output_len;(void)output_pad;assert(!"14.7 open-before-EDID on H17P");return -ENODEV; } +/* Only the 14.7 external role opens the AV client and validates every EDID block. */ +static int __attribute__((unused)) dcpavserv_v14_open(struct apple_dcp *d,struct apple_epic_service *s,u64 epoch,u64 gen) +{ (void)d;(void)s;(void)epoch;(void)gen;assert(!"14.7 AV client open on H17P");return -ENODEV; } +static bool __attribute__((unused)) drm_edid_valid(const struct drm_edid *e) { (void)e;assert(!"14.7 EDID validation on H17P");return false; } static void iomfb_recv_msg(struct apple_dcp *d, u64 message) { (void)d; (void)message; } static void afk_receive_message(struct apple_dcp_afkep *ep, u64 message) { (void)message; received_ep=ep; receives++; } @@ -824,7 +834,7 @@ def function(text, signature): struct test_mode_ticket { u64 generation; bool associated; }; struct apple_dcp { bool quiescing; int fw_compat; void *dev; - struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead; + struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead,external_native; struct { struct mutex lock; u64 epoch; bool enabled; void *service; } dcpavserv; struct test_mode_ticket dummy_ticket; struct { u64 connection_sequence; } rate_proof; @@ -1021,7 +1031,7 @@ def startup(root): }; struct apple_dcp { void *dev; - struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead; + struct { int iomfb_method_profile; bool fw_14_7_endpoints; } hw; bool ext_dead,external_native; struct { unsigned enable_completion; bool enabled; } dcpavserv; struct apple_dcp_afkep *dcpavservep; }; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index 682635f56ca1ab..d8270fb0a89c4a 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1001,14 +1001,16 @@ def fn(n, name): decls.append(files['atc'][start:end]) names = { - 'atc': ('atcphy_pipehandler_lock', 'atcphy_pipehandler_unlock', + 'atc': ('atcphy_pipehandler_lock', 'atcphy_pipehandler_lock_live', + 'atcphy_pipehandler_unlock', 'atcphy_pipehandler_check', 'atcphy_pipehandler_set_mux', 'atcphy_clear_nonselected_phy_reset', 'atcphy_configure_pipehandler_usb3_host_t8103', 'atcphy_configure_pipehandler_usb3_host_t8122', 'atcphy_configure_pipehandler_usb3', 'atcphy_configure_pipehandler_usb4', 'atcphy_enable_dummy_phy', 'atcphy_pipe_live', 'atcphy_needs_dummy_phy', 'atcphy_configure_pipehandler_dummy', - 'atcphy_configure_pipehandler', 'atcphy_park_pipehandler', + 'atcphy_configure_pipehandler', 'atcphy_park_live_t8103_pipehandler', + 'atcphy_park_pipehandler', 'atcphy_get_mode_config', 'atcphy_dp_configure', 'j700_field_update', 'j700_aux_disable', 'atcphy_disable_dp_aux', 'atcphy_power_off', 'atcphy_power_on', *ATC_POST_TUNABLE, 'atcphy_configure', 'atcphy_restore_after_pd_off', @@ -1371,11 +1373,18 @@ def function(source, marker): struct platform_device { struct device dev; bool bound, registered; }; /* The native T6030 14.7 backend is never selected in these scenarios. */ enum dcp_firmware_version { DCP_FIRMWARE_UNKNOWN, DCP_FIRMWARE_V_14_7, DCP_FIRMWARE_V_14_7_TEMPLATE, DCP_FIRMWARE_V_26_6 }; +struct work_struct { int unused; }; struct apple_dcp { bool external_prepared, quiescing, crashed, external_native, ext_dead; enum dcp_firmware_version fw_compat; struct { int iomfb_method_profile; } hw; + struct work_struct external_audio_work; }; +/* This readiness fixture has no AV owner or native audio initializer. */ +static void av_audiosrv_quiesce(struct apple_dcp *d) +{ assert(!d->external_native); } +static void disable_work_sync(struct work_struct *work) +{ (void)work; assert(!"native audio work in a J700 readiness scenario"); } static void __attribute__((unused)) iomfb_v14_7_remove(struct apple_dcp *d) { (void)d; assert(!"14.7 backend on a non-14.7 DCP"); } /* Nor the J613 26.6 backend. */ diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py index 25b0dbeff1d2a0..18bc3c78c96c05 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py @@ -4,7 +4,7 @@ from pathlib import Path import re from common import (block, source_defines, atc_mux_without_pm, ATC_POST_TUNABLE, - atc_function, ATC_SPLIT) + atc_function, ATC_SPLIT, ATC_T8103_LIVE) def parking(root): @@ -15,7 +15,7 @@ def parking(root): def function(source, name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) - if name in ATC_SPLIT: + if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(source, re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -45,6 +45,7 @@ def function(source, name): u32 dp_usb_context[2][27]; bool pipe_pending, usb_off_pending, usb_off_drained; bool usb3_port_off, park_owed; + bool t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround; bool dp_only, pd_was_off, tunnel_clock_on; unsigned int tunnel_rate, tunnel_users; struct { bool aux, pll; unsigned int pairs, rate; } dp_t8122; @@ -150,14 +151,16 @@ def function(source, name): parts.append(block(t8122, match.start()).replace('static inline ', 'static inline __attribute__((unused)) ', 1)) for name in ('atcphy_dp_aux_on_t8122', 'atcphy_dp_stop_t8122'): parts.append(function(atc, name)) - for name in ('atcphy_pipehandler_lock', 'atcphy_pipehandler_unlock', 'atcphy_pipehandler_check', + for name in ('atcphy_pipehandler_lock', 'atcphy_pipehandler_lock_live', + 'atcphy_pipehandler_unlock', 'atcphy_pipehandler_check', 'atcphy_pipehandler_set_mux', 'atcphy_clear_nonselected_phy_reset', 'atcphy_configure_pipehandler_usb3_host_t8122', 'atcphy_configure_pipehandler_usb3_host_t8103', 'atcphy_configure_pipehandler_usb3', 'atcphy_configure_pipehandler_usb4', 'atcphy_enable_dummy_phy', 'atcphy_pipe_live', 'atcphy_needs_dummy_phy', 'atcphy_configure_pipehandler_dummy', - 'atcphy_configure_pipehandler', 'atcphy_park_pipehandler', + 'atcphy_configure_pipehandler', 'atcphy_park_live_t8103_pipehandler', + 'atcphy_park_pipehandler', 'atcphy_usb2_power_off', '_atcphy_dwc3_reset_assert', 'atcphy_dwc3_reset_assert'): parts.append(function(atc, name)) for name in ('core_read32', 'atcphy_get_mode_config', 'j700_field_update', 'j700_pma_idle'): @@ -249,6 +252,7 @@ def function(source, name): pipe_regs[PIPEHANDLER_AON_GEN / 4] = PIPEHANDLER_AON_GEN_DWC3_RESET_N; usb2_regs[USB2PHY_USBCTL / 4] = USB2PHY_USBCTL_RUN; *p = (struct apple_atcphy) { + .t8103_usb3_workaround = hw.gen == ATCPHY_GENERATION_T8103, .hw = &hw, .regs.core = (unsigned char *)registers, .regs.lpdptx = (unsigned char *)registers, .regs.pipehandler = (unsigned char *)pipe_regs, @@ -985,6 +989,11 @@ def adverse(root): # continued PLL clock macro exercised by the legacy rate helper here. ns = parking(root) production = ns['production'] + '\n' + ns['function'](ns['atc'], 'atcphy_usb2_init') + # An admitted base-M1 host start may skip the native BIST, and the lock it holds. + dispatch = ns['function'](ns['atc'], 'atcphy_configure_pipehandler') + production = ('#define T8103_HOST_BIST ' + str(int('ATCPHY_GENERATION_T8103' not in dispatch and + 't8103_usb3_workaround' not in dispatch)) + + '\n' + production) production = production.replace('bool pipe_pending, usb_off_pending, usb_off_drained;', 'bool pipe_pending, usb_off_pending, usb_off_drained, tunnel_saved;', 1) production += '\n' + ns['block'](ns['atc'], 'enum atcphy_lane {') + ';' @@ -1048,6 +1057,81 @@ def adverse(root): } puts("PASS: every T8103/T8122 BIST poll propagates first error through full cleanup"); } +#if !T8103_HOST_BIST +static bool bist_polled(unsigned int from) +{ + for (unsigned int i=from; i=1 && !strcmp(poll_caller[0],"atcphy_pipehandler_unlock")); + if (starts) { + /* The fixed-hub host starts anyway; its park repeats the release. */ + assert(ret==0); + if (unlock) { + assert(polls==2 && only_released(0) && p->pipe_pending && mux_writes==0); + } else { + assert(polls==3 && !strcmp(poll_caller[1],"atcphy_pipehandler_lock") && + !strcmp(poll_caller[2],"atcphy_pipehandler_unlock")); + assert(!p->pipe_pending && mux_writes==3); + } + } else { + assert(ret==(unlock ? -ETIMEDOUT : -EIO) && polls==1); + assert(p->pipe_pending && mux_writes==0); + } + assert(p->pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY && !p->mode_dirty && writes==before); + + /* A lock that stays held fails the next start at the same release. */ + hold_unlock_ack=false; + memset(poll_errors,0,sizeof(poll_errors)); + pipe_regs[PIPEHANDLER_LOCK_ACK/4]=PIPEHANDLER_LOCK_EN; + stuck_ack=true; + unsigned int first=polls, moved=mux_writes; + ret=atcphy_usb3_set_mode(phy,PHY_MODE_USB_HOST,0); + assert(ret==(starts ? 0 : -ETIMEDOUT) && polls>first && only_released(first)); + assert(mux_writes==moved && p->pipe_pending); + assert(p->pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY && !p->mode_dirty); + + /* The lanes were never touched: the callback rebuilds nothing. */ + stuck_ack=false; + ret=mux ? select_mode(p,APPLE_ATCPHY_MODE_USB3) : atcphy_usb2_init(phy); + assert(ret==0 && writes==before && !p->mode_dirty); + assert(atcphy_usb3_set_mode(phy,PHY_MODE_USB_HOST,0)==0); + assert(p->pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3 && !p->pipe_pending); + assert(!p->mode_dirty && writes==before); + assert(!(pipe_regs[PIPEHANDLER_LOCK_REQ/4] & PIPEHANDLER_LOCK_EN) && !bist_polled(0)); +} +#endif static void retry_callbacks(bool mux) { for (unsigned int gen=0; gen<4; gen++) @@ -1056,6 +1140,12 @@ def adverse(root): struct apple_atcphy p; legacy_setup(&p,gen,fixed); struct phy phy={&p}; +#if !T8103_HOST_BIST + if (gen==0) { + t8103_release_fault(&p,&phy,fixed,unlock,mux); + continue; + } +#endif if (unlock) hold_unlock_ack=true; else poll_errors[2]=-EIO; #if FIXED_HOST_STARTS @@ -1147,8 +1237,17 @@ def adverse(root): struct apple_atcphy p; legacy_setup(&p,gen,false); struct phy phy={&p}; + const char *fault="atcphy_pipehandler_lock"; +#if !T8103_HOST_BIST + /* T8103 host start takes no lock: fail the release of a stale one instead. */ + if (gen==0) { + pipe_regs[PIPEHANDLER_LOCK_ACK/4]=PIPEHANDLER_LOCK_EN; + fault="atcphy_pipehandler_unlock"; + } +#endif stuck_ack=true; assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-ETIMEDOUT); + assert(polls==1 && !strcmp(poll_caller[0],fault)); assert(p.pipe_pending && !p.mode_dirty); unsigned int w=writes,r=mmio_reads; int ret=atcphy_configure(&p,APPLE_ATCPHY_MODE_USB3); @@ -1212,8 +1311,17 @@ def adverse(root): struct apple_atcphy p; legacy_setup(&p,gen,false); struct phy phy={&p}; + const char *fault="atcphy_pipehandler_lock"; +#if !T8103_HOST_BIST + /* T8103 host start takes no lock: fail the release of a stale one instead. */ + if (gen==0) { + pipe_regs[PIPEHANDLER_LOCK_ACK/4]=PIPEHANDLER_LOCK_EN; + fault="atcphy_pipehandler_unlock"; + } +#endif stuck_ack=true; assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-ETIMEDOUT); + assert(polls==1 && !strcmp(poll_caller[0],fault)); assert(p.pipe_pending && !p.mode_dirty); p.dp_link_rate=ATCPHY_DP_LINK_RATE_HBR3; unsigned int w=writes,r=mmio_reads; @@ -1789,7 +1897,7 @@ def block(marker): def function(name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) - if name in ATC_SPLIT: + if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -1814,6 +1922,7 @@ def function(name): u32 dp_usb_context[2][27]; bool pipe_pending, usb_off_pending, usb_off_drained; bool usb3_port_off, park_owed; + bool t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround; bool swap_lanes; enum atcphy_mode mode, typec_mode; enum atcphy_pipehandler_state pipe_state; @@ -1824,6 +1933,7 @@ def function(name): parts.append(r''' static u32 pipe_regs[0x1000 / 4], core_regs[0x30000 / 4]; static unsigned int polls, fail_poll, mux_writes, lane_calls; +static const char *last_poll; static bool stuck_ack; static u32 readl(void *address) { return *(u32 *)address; } static void mask32(void *address, u32 mask, u32 value) @@ -1843,7 +1953,7 @@ def function(name): static void core_clear32(struct apple_atcphy *p, u32 o, u32 v) { core_mask32(p, o, v, 0); } #define readl_poll_timeout_atomic readl_poll_timeout #define readl_poll_timeout(address, value, condition, interval, timeout) \ - ({ (value) = readl(address); polls++; \ + ({ (value) = readl(address); polls++; last_poll = __func__; \ polls == fail_poll || !(condition) ? -ETIMEDOUT : 0; }) /* Lane configuration is outside this test: count calls and commit its result. */ /* Observation is read-only and separately tested; retain production caller control flow. */ @@ -1865,17 +1975,23 @@ def function(name): p->mode = mode; p->mode_dirty = false; return 0; } ''') - for name in ('atcphy_pipehandler_lock', 'atcphy_pipehandler_unlock', 'atcphy_pipehandler_check', + for name in ('atcphy_pipehandler_lock', 'atcphy_pipehandler_lock_live', + 'atcphy_pipehandler_unlock', 'atcphy_pipehandler_check', 'atcphy_pipehandler_set_mux', 'atcphy_clear_nonselected_phy_reset', 'atcphy_configure_pipehandler_usb3_host_t8122', 'atcphy_configure_pipehandler_usb3_host_t8103', 'atcphy_configure_pipehandler_usb3', 'atcphy_configure_pipehandler_usb4', 'atcphy_enable_dummy_phy', 'atcphy_pipe_live', 'atcphy_needs_dummy_phy', 'atcphy_configure_pipehandler_dummy', - 'atcphy_configure_pipehandler', 'atcphy_park_pipehandler', + 'atcphy_configure_pipehandler', 'atcphy_park_live_t8103_pipehandler', + 'atcphy_park_pipehandler', 'atcphy_usb3_route', 'atcphy_usb3_set_mode', 'atcphy_mux_set'): parts.append(function(name)) production = '\n'.join(parts) + # An admitted base-M1 host start may skip the native BIST, and the lock it holds. + production = ('#define T8103_HOST_BIST ' + str(int('ATCPHY_GENERATION_T8103' not in + function('atcphy_configure_pipehandler') and 't8103_usb3_workaround' not in + function('atcphy_configure_pipehandler'))) + '\n' + production) prefix = r''' #include #include @@ -1903,6 +2019,7 @@ def function(name): #define fallthrough __attribute__((fallthrough)) #define usleep_range(...) ((void)0) #define udelay(n) ((void)(n)) +#define __iomem enum { TYPEC_STATE_SAFE, TYPEC_STATE_USB, TYPEC_MODE_USB4, TYPEC_DP_STATE_C, TYPEC_DP_STATE_D, TYPEC_DP_STATE_E }; enum { USB_TYPEC_TBT_SID = 0x8087, USB_TYPEC_DP_SID = 0xff01 }; @@ -1930,6 +2047,7 @@ def function(name): memset(core_regs, 0, sizeof(core_regs)); core_regs[ACIOPHY_TOP_PHY_STAT / 4] = ACIOPHY_TOP_PHY_STAT_LN0_UNK0; *p = (struct apple_atcphy) { + .t8103_usb3_workaround = hw.gen == ATCPHY_GENERATION_T8103, .hw = &hw, .regs.core = (unsigned char *)core_regs, .regs.pipehandler = (unsigned char *)pipe_regs, .mode = mode, .typec_mode = mode, .pipe_state = backend, @@ -1992,8 +2110,17 @@ def function(name): hw.gen = gen ? ATCPHY_GENERATION_T8122 : ATCPHY_GENERATION_T8103; initial(&p, APPLE_ATCPHY_MODE_USB3, ATCPHY_PIPEHANDLER_STATE_DUMMY); struct phy phy = { &p }; + const char *fault = "atcphy_pipehandler_lock"; +#if !T8103_HOST_BIST + /* T8103 host start takes no lock: fail the release of a stale one instead. */ + if (!gen) { + pipe_regs[PIPEHANDLER_LOCK_ACK / 4] = PIPEHANDLER_LOCK_EN; + fault = "atcphy_pipehandler_unlock"; + } +#endif stuck_ack = true; assert(atcphy_usb3_set_mode(&phy, PHY_MODE_USB_HOST, 0) == -ETIMEDOUT); + assert(polls == 1 && !strcmp(last_poll, fault)); assert(p.pipe_state == ATCPHY_PIPEHANDLER_STATE_DUMMY && mux_writes == 0); assert(!(pipe_regs[PIPEHANDLER_LOCK_REQ / 4] & PIPEHANDLER_LOCK_EN)); stuck_ack = false; @@ -2003,7 +2130,11 @@ def function(name): assert(atcphy_usb3_set_mode(&phy, PHY_MODE_USB_HOST, 0) == 0); assert(polls == before && mux_writes == 6); } +#if T8103_HOST_BIST puts("PASS: both USB3 host BIST generations retain fatal lock ACK and retry"); +#else + puts("PASS: T8122 host lock and T8103 stale-lock release faults stay fatal; both retry once acknowledged"); +#endif } static void mux_retry(void) { @@ -2150,7 +2281,7 @@ def unwind(root): def function(source, name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) - if name in ATC_SPLIT: + if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(source, re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -2180,6 +2311,7 @@ def function(source, name): u32 dp_usb_context[2][27]; bool pipe_pending, usb_off_pending, usb_off_drained; bool usb3_port_off, park_owed; + bool t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround; enum atcphy_mode mode, typec_mode; enum atcphy_pipehandler_state pipe_state; }; @@ -2245,6 +2377,9 @@ def function(source, name): static int atcphy_park_pipehandler(struct apple_atcphy *p, bool keep_dp) { (void)keep_dp; p->pipe_state = ATCPHY_PIPEHANDLER_STATE_DUMMY; return 0; } +/* The T8140 profile never owes a T8103-generation live PIPE park. */ +static int __attribute__((unused)) atcphy_park_live_t8103_pipehandler(struct apple_atcphy *p) +{ (void)p; assert(!"T8103 live PIPE park"); return -EINVAL; } /* Observation is read-only and separately tested; retain production caller control flow. */ static int atcphy_configure_pipehandler(struct apple_atcphy *p, bool host) { (void)host; p->pipe_state = atcphy_modes[p->mode].pipehandler_state; return 0; } @@ -2311,6 +2446,7 @@ def function(source, name): memset(registers, 0, sizeof(registers)); registers[AUS_COMMON_DIG_RCAL1 / 4] = AUS_COMMON_DIG_RCAL1_ALL_CODES_DONE; *p = (struct apple_atcphy) { + .t8103_usb3_workaround = hw.gen == ATCPHY_GENERATION_T8103, .hw = &hw, .regs.core = (unsigned char *)registers, .regs.lpdptx = (unsigned char *)registers, .fixed_usb2 = fixed, .swap_lanes = swapped, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/plane-layout.py b/tools/testing/selftests/drivers/gpu/apple-dcp/plane-layout.py new file mode 100755 index 00000000000000..e7b12e5bdbb59f --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/plane-layout.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the real Apple plane check/update with synthetic framebuffer objects. + +The format descriptors, block helpers, surface structs and plane functions are +extracted from public kernel sources. GEM objects contain sizes, not DMA memory; +DRM atomic/clipping and device logging are stand-ins. This tests layout admission +and emitted geometry, not firmware packing, GPU rendering or DMA execution. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import subprocess +import tempfile + +from common import block + +FORMATS = ('XRGB8888', 'XRGB2101010', 'ABGR16161616F', 'NV12', 'NV16', + 'NV24', 'P010', 'P210', 'P030', 'P230') + + +def read(root, name, ref=None): + if ref: + return subprocess.check_output(['git', '-C', str(root), 'show', ref + ':' + name], text=True) + path = root / name + if path.exists(): + return path.read_text() + return subprocess.check_output(['git', '-C', str(root), 'show', 'HEAD:' + name], text=True) + + +def unit(root, ref=None, mutation=None, callback_ref=None): + plane = read(root, 'drivers/gpu/drm/apple/plane.c', ref) + if callback_ref: + old = read(root, 'drivers/gpu/drm/apple/plane.c', callback_ref) + marker = 'static bool apple_plane_format_mod_supported(' + plane = plane.replace(block(plane, marker), block(old, marker), 1) + if mutation: + before, after = MUTATIONS[mutation] + pattern = r'\s+'.join(re.escape(word) for word in before.split()) + plane, count = re.subn(pattern, lambda match: after, plane) + if count != 1: + raise RuntimeError(mutation + ': NOT_APPLIED') + fourcc = read(root, 'drivers/gpu/drm/drm_fourcc.c', ref) + header = read(root, 'include/drm/drm_fourcc.h', ref) + uapi = read(root, 'include/uapi/drm/drm_fourcc.h', ref) + surface = read(root, 'drivers/gpu/drm/apple/iomfb_plane.h', ref) + plane_header = read(root, 'drivers/gpu/drm/apple/plane.h', ref) + plane_core = read(root, 'drivers/gpu/drm/drm_plane.c', ref) + dma_header = read(root, 'include/drm/drm_fb_dma_helper.h', ref) + prefix = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; +#define U16_MAX UINT16_MAX +#define U32_MAX UINT32_MAX +#define BIT(n) (1UL << (n)) +#define __packed __attribute__((packed)) +#define check_mul_overflow(a,b,c) __builtin_mul_overflow((a),(b),(c)) +#define check_add_overflow(a,b,c) __builtin_add_overflow((a),(b),(c)) +#define DIV_ROUND_UP(n,d) (((n)+(d)-1)/(d)) +#define DIV_ROUND_UP_ULL(n,d) (((u64)(n)+(d)-1)/(d)) +#define ALIGN(n,a) (((n)+(a)-1)&~((a)-1)) +#define roundup_pow_of_two(n) ((n) == 1 ? 1UL : 1UL << (64-__builtin_clzl((unsigned long)(n)-1))) +#define fourcc_code(a,b,c,d) ((u32)(a)|((u32)(b)<<8)|((u32)(c)<<16)|((u32)(d)<<24)) +#define DRM_FORMAT_MAX_PLANES 4 +#define DRM_FORMAT_MOD_INVALID UINT64_MAX +#define DRM_FORMAT_MOD_LINEAR 0 +#define DRM_FORMAT_MOD_APPLE_INTERCHANGE 3 +#define pr_warn(...) ((void)0) +#define dev_err_once(...) ((void)0) +#define dev_err_ratelimited(...) ((void)0) +#define IS_ERR(p) false +#define PTR_ERR(p) (-EINVAL) +static int warnings; +#define WARN_ON_ONCE(x) ({ bool _x = !!(x); warnings += _x; _x; }) +#define container_of(p,t,m) ((t *)((char *)(p)-offsetof(t,m))) +''' + prefix += '\n'.join(line for line in uapi.splitlines() + if re.match(r'#define DRM_FORMAT_\w+\s+fourcc_code\(', line)) + '\n' + prefix += block(header, 'struct drm_format_info {') + ';\n' + prefix += '\n'.join(block(fourcc, name) for name in ( + 'unsigned int drm_format_info_block_width(', + 'unsigned int drm_format_info_block_height(', + 'unsigned int drm_format_info_bpp(')) + '\n' + prefix += '\n'.join('static inline ' + block(header, name) for name in ( + 'int drm_format_info_plane_width(', 'int drm_format_info_plane_height(')) + '\n' + for name in FORMATS: + row = re.search(r'\{\s*\.format\s*=\s*DRM_FORMAT_' + name + r'\s*,', fourcc) + prefix += 'static const struct drm_format_info fmt_' + name + ' = ' + block(fourcc, row.start()) + ';\n' + prefix += 'static inline const struct drm_format_info *drm_format_info(u32 format) {\n' + for name in FORMATS: + prefix += 'if (format == DRM_FORMAT_' + name + ') return &fmt_' + name + ';\n' + prefix += 'return NULL; }\n' + prefix += '\n'.join(line for line in surface.splitlines() if not line.startswith('#include')) + prefix += r''' +struct drm_gem_object { size_t size; }; +struct drm_gem_dma_object { struct drm_gem_object base; u64 dma_addr; }; +struct drm_framebuffer { const struct drm_format_info *format; u32 width,height,pitches[4],offsets[4];u64 modifier;struct drm_gem_object *obj[4]; }; +struct drm_rect { int x1,y1,x2,y2; }; +enum drm_color_range { DRM_COLOR_YCBCR_LIMITED_RANGE, DRM_COLOR_YCBCR_FULL_RANGE }; +enum drm_color_encoding { DRM_COLOR_YCBCR_BT601, DRM_COLOR_YCBCR_BT709, DRM_COLOR_YCBCR_BT2020 }; +struct drm_crtc_state { struct { int hdisplay,vdisplay; } mode; }; +struct drm_plane_state { void *crtc; bool visible; struct drm_framebuffer *fb; struct drm_rect src,dst; enum drm_color_range color_range; enum drm_color_encoding color_encoding; }; +struct drm_plane; +struct drm_plane_funcs { bool (*format_mod_supported)(struct drm_plane *,u32,u64); }; +struct drm_plane { struct { u32 id; } base;struct drm_plane_state *state;u32 *format_types;unsigned int format_count;u64 *modifiers;unsigned int modifier_count;const struct drm_plane_funcs *funcs; }; +struct drm_atomic_commit { struct { void *dev; } *dev; }; +''' + prefix += block(plane_header, 'struct apple_plane_state {') + ';\n' + prefix += r''' +#define to_apple_plane_state(p) container_of(p,struct apple_plane_state,base) +static struct drm_crtc_state crtc_state = { .mode = { 3840,2160 } }; +static struct drm_plane_state *drm_atomic_get_new_plane_state(struct drm_atomic_commit *c,struct drm_plane *p) { return p->state; } +static struct drm_crtc_state *drm_atomic_get_crtc_state(struct drm_atomic_commit *c,void *crtc) { return &crtc_state; } +static int drm_atomic_helper_check_plane_state(struct drm_plane_state *s,struct drm_crtc_state *c,int min,int max,bool pos,bool disable) { return 0; } +static int drm_rect_width(const struct drm_rect *r) { return r->x2-r->x1; } +static int drm_rect_height(const struct drm_rect *r) { return r->y2-r->y1; } +static void drm_rect_fp_to_int(struct drm_rect *dst,const struct drm_rect *src) { *dst = (struct drm_rect){src->x1>>16,src->y1>>16,src->x2>>16,src->y2>>16}; } +#define APPLE_GPU_CACHELINE 16 +#define FRAC_16_16(mult,div) (((mult)<<16)/(div)) +''' + prototype = dma_header[dma_header.index('struct drm_gem_dma_object *drm_fb_dma_get_gem_obj('):].split(';', 1)[0] + prefix += prototype + ' { return (void *)fb->obj[plane]; }\n' + prefix += block(plane_core, 'bool drm_plane_has_format(') + '\n' + if 'struct apple_plane_layout {' in plane: + prefix += block(plane, 'struct apple_plane_layout {') + ';\n' + prefix += '#define HAS_MOD_CALLBACK 1\n' + prefix += block(plane, 'static int apple_plane_ix_bpp(') + '\n' + prefix += block(plane, 'static bool apple_plane_format_mod_supported(') + '\n' + prefix += block(plane, 'static int apple_get_ix_layout(') + '\n' + prefix += block(plane, 'static int apple_plane_get_fb_layout(') + '\n' + else: + prefix += '#define HAS_MOD_CALLBACK 0\n' + # The baseline uses a struct-returning helper. Keep it unmodified so + # --ref can reproduce the check/update mismatch rather than a model. + start = plane.index('static struct dcp_image_layout\napple_get_ix_layout') + prefix += block(plane, start) + '\n' + for name in ('static int apple_plane_atomic_check(', + 'static struct dcp_rect drm_to_dcp_rect(', + 'static struct dcp_rect drm_to_dcp_rect_fp(', + 'static u32 drm_format_to_dcp(', + 'static enum dcp_xfer_func get_xfer_func(', + 'static enum dcp_colorspace get_colorspace(', + 'static void apple_plane_atomic_update('): + prefix += block(plane, name) + '\n' + return prefix + MAIN + + +MAIN = r''' +static struct drm_gem_dma_object gem = { .base.size = SIZE_MAX, .dma_addr = 0x100000000 }; +static struct drm_gem_dma_object other = { .base.size = SIZE_MAX }; +static struct drm_framebuffer fb; +static struct apple_plane_state state; +static struct drm_plane plane = { .base.id = 1, .state = &state.base }; +static struct drm_atomic_commit commit; +static u64 all_modifiers[]={DRM_FORMAT_MOD_APPLE_INTERCHANGE,DRM_FORMAT_MOD_LINEAR}; +static u64 linear_modifier[]={DRM_FORMAT_MOD_LINEAR}; +static u32 advertised_format; +static const struct drm_plane_funcs plane_funcs={ +#if HAS_MOD_CALLBACK + .format_mod_supported=apple_plane_format_mod_supported, +#endif +}; +static void init(const struct drm_format_info *fmt,u32 w,u32 h,u64 modifier) { + assert(drm_format_info(fmt->format)); + memset(&fb,0,sizeof(fb));memset(&state,0,sizeof(state));warnings=0; + advertised_format=fmt->format; + plane.format_types=&advertised_format;plane.format_count=1; + plane.modifiers=all_modifiers;plane.modifier_count=2;plane.funcs=&plane_funcs; + fb.format=fmt;fb.width=w;fb.height=h;fb.modifier=modifier; + gem.base.size=SIZE_MAX; + state.base=(struct drm_plane_state){.crtc=&crtc_state,.fb=&fb,.visible=true,.dst={0,0,64,64}}; + u64 next=128; + for(u32 i=0;inum_planes;i++) { + u32 pw=drm_format_info_plane_width(fmt,w,i),ph=drm_format_info_plane_height(fmt,h,i); + u32 bw=drm_format_info_block_width(fmt,i),bh=drm_format_info_block_height(fmt,i); + fb.pitches[i]=ALIGN(DIV_ROUND_UP_ULL(pw, bw)*fmt->char_per_block[i],64); + fb.offsets[i]=next;fb.obj[i]=&gem.base; + if(modifier==DRM_FORMAT_MOD_LINEAR) next+=(u64)ph*fb.pitches[i]+64; + else { + u32 tw=fmt->is_yuv&&!i?32:16,th=tw; + u64 data=DIV_ROUND_UP_ULL(pw,tw)*DIV_ROUND_UP_ULL(ph,th)*tw*th*fmt->char_per_block[i]/(bw*bh); + u64 meta=DIV_ROUND_UP_ULL(roundup_pow_of_two(pw),tw)*DIV_ROUND_UP_ULL(roundup_pow_of_two(ph),th)*(tw==32?32:8); + next+=ALIGN(data,16)+ALIGN(meta,16)+64; + } + } + gem.base.size=next; +} +static int check(void) { return apple_plane_atomic_check(&plane,&commit); } +static void update(void) { apple_plane_atomic_update(&plane,&commit);assert(!warnings); } +static void reference_layout(void) { + const struct drm_format_info *f=fb.format;u64 total=0; + for(u32 i=0;inum_planes;i++) { + const struct dcp_plane_info *p=&state.surf.planes[i]; + u32 w=i?DIV_ROUND_UP(fb.width,f->hsub):fb.width,h=i?DIV_ROUND_UP(fb.height,f->vsub):fb.height; + u32 bw=drm_format_info_block_width(f,i),bh=drm_format_info_block_height(f,i); + assert(p->width==w&&p->height==h&&p->offset==fb.offsets[i]-fb.offsets[0]); + u64 size; + if(fb.modifier==DRM_FORMAT_MOD_LINEAR) { + size=(u64)h*fb.pitches[i];assert(p->stride==fb.pitches[i]); + assert(p->tile_w==bw&&p->tile_h==bh&&p->tile_size==bw*bh); + } else { + u32 tw=f->is_yuv&&!i?32:16,th=tw; + u64 wt=DIV_ROUND_UP_ULL(w,tw),ht=DIV_ROUND_UP_ULL(h,th),tile=(u64)tw*th*f->char_per_block[i]/(bw*bh); + u64 data=ALIGN(wt*ht*tile,16); + u64 meta=ALIGN(DIV_ROUND_UP_ULL(roundup_pow_of_two(w),tw)*DIV_ROUND_UP_ULL(roundup_pow_of_two(h),th)*(tw==32?32:8),16); + size=data+meta; + assert(p->tile_w==tw&&p->tile_h==th&&p->tile_size==tile&&p->stride==wt*tile); + const struct dcp_compression_info *c=&state.surf.compression_info[i]; + assert(c->metadata_offset==p->offset+data&&c->data_offset==p->offset); + assert(c->row_stride==p->stride&&c->tiles_w==wt&&c->tiles_h==ht&&c->tile_bytes==tile); + } + assert(p->size==size);assert((u64)fb.offsets[i]+size<=gem.base.size);total+=size; + } + assert(state.surf.buf_size==total&&state.iova==gem.dma_addr+fb.offsets[0]); +} +int main(int argc,char **argv) { + assert(argc==2);const char *test=argv[1]; + if(!strcmp(test,"matrix")) { + const struct drm_format_info *formats[]={&fmt_XRGB8888,&fmt_XRGB2101010,&fmt_ABGR16161616F,&fmt_NV12,&fmt_NV16,&fmt_NV24,&fmt_P010,&fmt_P210,&fmt_P030,&fmt_P230}; + u32 dims[][2]={{1,1},{15,17},{16,16},{17,15},{31,33},{32,32},{33,31},{127,129},{128,128},{129,127},{1920,1080},{2560,1600},{3840,2160}}; + unsigned admitted=0,refused=0; + for(unsigned f=0;fformat,fb.modifier)==(linear||!(f==8||f==9))); +#endif + if(!linear&&(f==8||f==9)) { assert(check()==-EINVAL);refused++;continue; } + assert(check()==0);update();reference_layout();admitted++; + } + printf("PASS matrix %u admitted / %u fractional interchange refused\n",admitted,refused);return 0; + } + if(!strcmp(test,"reproduce")) { + init(&fmt_P030,33,33,DRM_FORMAT_MOD_APPLE_INTERCHANGE);fb.offsets[0]=0;fb.offsets[1]=2112;gem.base.size=4096; + int ret=check();printf("check=%d ",ret); + if(!ret) { update();printf("plane0-size=%u plane1-size=%u GEM=%zu\n",state.surf.planes[0].size,state.surf.planes[1].size,gem.base.size); } + else puts("fractional interchange refused");return 0; + } + if(!strcmp(test,"format-advertisement")) { + init(&fmt_P030,33,33,DRM_FORMAT_MOD_LINEAR); + assert(!drm_plane_has_format(&plane,0,DRM_FORMAT_MOD_LINEAR)); + assert(!drm_plane_has_format(&plane,DRM_FORMAT_P030,0x42)); + assert(drm_plane_has_format(&plane,DRM_FORMAT_P030,DRM_FORMAT_MOD_LINEAR)); + assert(!drm_plane_has_format(&plane,DRM_FORMAT_P030,DRM_FORMAT_MOD_APPLE_INTERCHANGE)); + puts("PASS format/modifier advertisement through real DRM framework");return 0; + } + if(!strcmp(test,"linear-only-framework")) { + init(&fmt_XRGB8888,64,64,DRM_FORMAT_MOD_LINEAR); + plane.modifiers=linear_modifier;plane.modifier_count=1; + assert(drm_plane_has_format(&plane,DRM_FORMAT_XRGB8888,DRM_FORMAT_MOD_LINEAR)); + assert(!drm_plane_has_format(&plane,DRM_FORMAT_XRGB8888,DRM_FORMAT_MOD_APPLE_INTERCHANGE)); + plane.modifier_count=0; +#if HAS_MOD_CALLBACK + assert(!drm_plane_has_format(&plane,DRM_FORMAT_XRGB8888,DRM_FORMAT_MOD_LINEAR)); +#endif + puts("PASS linear-only plane cannot gain Interchange through callback");return 0; + } + init(&fmt_XRGB8888,33,33,DRM_FORMAT_MOD_APPLE_INTERCHANGE); + if(!strcmp(test,"gem-short")) { + assert(check()==0);update();gem.base.size=fb.offsets[0]+state.surf.planes[0].size-1; + } else if(!strcmp(test,"gem-exact")) { + assert(check()==0);update();gem.base.size=fb.offsets[0]+state.surf.planes[0].size; + assert(check()==0);update();reference_layout();puts("PASS exact GEM boundary");return 0; + } else if(!strcmp(test,"offset-wrap")) { fb.offsets[0]=U32_MAX-15;gem.base.size=U32_MAX; + } else if(!strcmp(test,"relative-wrap")) { + init(&fmt_NV12,64,64,DRM_FORMAT_MOD_LINEAR);fb.offsets[0]=0;fb.offsets[1]=U32_MAX-15;gem.base.size=(u64)U32_MAX*2; + } else if(!strcmp(test,"backwards-offset")) { + init(&fmt_NV12,64,64,DRM_FORMAT_MOD_LINEAR);fb.offsets[1]=fb.offsets[0]-1; + } else if(!strcmp(test,"different-object")) { init(&fmt_NV12,64,64,DRM_FORMAT_MOD_LINEAR);fb.obj[1]=&other.base; + } else if(!strcmp(test,"missing-object")) { init(&fmt_NV12,64,64,DRM_FORMAT_MOD_LINEAR);fb.obj[1]=NULL; + } else if(!strcmp(test,"later-plane-short")) { + init(&fmt_NV12,64,64,DRM_FORMAT_MOD_LINEAR);fb.offsets[1]=16384;gem.base.size=16384+32*64-1; + } else if(!strcmp(test,"data-overflow")) { fb.width=65536;fb.height=65536;gem.base.size=SIZE_MAX; + } else if(!strcmp(test,"stride-overflow")) { fb.width=0x40000000;fb.height=1;gem.base.size=SIZE_MAX; + } else if(!strcmp(test,"meta-sum-overflow")) { fb.width=32752;fb.height=32768;gem.base.size=SIZE_MAX; + } else if(!strcmp(test,"linear-overflow")) { init(&fmt_XRGB8888,64,64,DRM_FORMAT_MOD_LINEAR);fb.pitches[0]=0x10000000;gem.base.size=SIZE_MAX; + } else if(!strcmp(test,"aggregate-overflow")) { + init(&fmt_P010,64,1,DRM_FORMAT_MOD_LINEAR);fb.offsets[0]=fb.offsets[1]=0;fb.pitches[0]=fb.pitches[1]=0x80000000;gem.base.size=SIZE_MAX; + } else if(!strcmp(test,"linear-short")) { + init(&fmt_XRGB8888,33,33,DRM_FORMAT_MOD_LINEAR);gem.base.size=fb.offsets[0]+fb.height*fb.pitches[0]-1; + } else if(!strcmp(test,"nonvisible-fractional")) { init(&fmt_P230,33,33,DRM_FORMAT_MOD_APPLE_INTERCHANGE);state.base.visible=false; + } else if(!strcmp(test,"nonvisible-valid")) { + state.base.visible=false;assert(check()==0);update();reference_layout();puts("PASS nonvisible valid geometry");return 0; + } else if(!strcmp(test,"invisible-disable")) { + state.base.crtc=NULL;state.base.fb=NULL;assert(check()==0);update();assert(!state.surf.buf_size);puts("PASS disabled plane");return 0; + } else { fprintf(stderr,"unknown case %s\n",test);return 2; } + assert(check()==-EINVAL);printf("PASS refusal %s\n",test);return 0; +} +''' + +CASES = ('matrix', 'format-advertisement', 'linear-only-framework', 'gem-short', 'gem-exact', 'offset-wrap', 'relative-wrap', + 'backwards-offset', 'different-object', 'missing-object', 'later-plane-short', + 'data-overflow', 'stride-overflow', 'meta-sum-overflow', 'linear-overflow', + 'aggregate-overflow', 'linear-short', 'nonvisible-fractional', + 'nonvisible-valid', 'invisible-disable') +MUTATIONS = { + 'callback-ignores-plane-modifiers': ('if (i == plane->modifier_count)', 'if (i == plane->modifier_count && false)'), + 'fractional-allowed': ('bits % block_pixels)', 'false)'), + 'callback-advertises-fractional': ('if (apple_plane_ix_bpp(fmt, i, &bpp))', 'if (apple_plane_ix_bpp(fmt, i, &bpp) && false)'), + 'gem-bound-removed': ('(u64)fb->offsets[i] + p->size > obj->base.size ||', 'false ||'), + 'stride-overflow-ignored': ('check_mul_overflow(layout->width_tiles, layout->tile_bytes,\n\t\t\t &out->stride)', '(out->stride = layout->width_tiles * layout->tile_bytes, false)'), + 'relative-overflow-ignored': ('check_add_overflow(p->offset, p->size, &end)', '(end = p->offset + p->size, (void)end, false)'), + 'aggregate-overflow-ignored': ('check_add_overflow(*buf_size, p->size, buf_size)', '(*buf_size += p->size, false)'), + 'data-overflow-ignored': ('check_mul_overflow(out->stride, layout->height_tiles, &bytes)', '(bytes = out->stride * layout->height_tiles, false)'), + 'meta-sum-overflow-ignored': ('check_add_overflow(layout->meta_offset, layout->meta_size,\n\t\t\t &out->size)', '(out->size = layout->meta_offset + layout->meta_size, false)'), + 'linear-overflow-ignored': ('check_mul_overflow(p->height, fb->pitches[i], &p->size)', '(p->size = p->height * fb->pitches[i], false)'), +} + + +def run(label, text, output): + path = output / label + path.mkdir(parents=True, exist_ok=True) + source = path / 'host.c' + source.write_text(text) + command = shlex.split(os.environ.get('HOSTCC', 'clang')) + [ + '-std=gnu23', '-Wall', '-Werror', '-O1', '-g', '-fsanitize=address,undefined', + '-fno-omit-frame-pointer', str(source), '-o', str(path / 'host')] + (path / 'command.json').write_text(json.dumps(command) + '\n') + built = subprocess.run(command, text=True, capture_output=True, timeout=120) + (path / 'build.log').write_text(built.stdout + built.stderr) + result = {'class': 'NOBUILD' if built.returncode else 'RAN', 'source_sha256': hashlib.sha256(text.encode()).hexdigest(), 'cases': {}} + if built.returncode: + return result + for case in (*CASES, 'reproduce'): + ran = subprocess.run([str(path / 'host'), case], text=True, capture_output=True, timeout=30) + (path / (case + '.log')).write_text(ran.stdout + ran.stderr) + result['cases'][case] = ran.returncode + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, default=Path(__file__).resolve().parents[6]) + parser.add_argument('--output', type=Path, default=None) + parser.add_argument('--ref', help='also reproduce admission on this old public source revision') + parser.add_argument('--mutations', action='store_true') + parser.add_argument('--callback-ref', help='also test this old callback on the fixed helper and real DRM framework') + args = parser.parse_args() + root = args.source.resolve() + output = args.output or Path(tempfile.mkdtemp(prefix='apple-plane-layout-')) + output.mkdir(parents=True, exist_ok=True) + report = {'control': run('control', unit(root), output)} + valid = report['control']['class'] == 'RAN' and not any(report['control']['cases'].values()) + if args.ref: + report['baseline'] = run('baseline', unit(root, args.ref), output) + valid &= report['baseline']['class'] == 'RAN' and any(report['baseline']['cases'].values()) + if args.callback_ref: + report['old_callback'] = run('old-callback', unit(root, callback_ref=args.callback_ref), output) + valid &= report['old_callback']['class'] == 'RAN' and report['old_callback']['cases'].get('linear-only-framework', 0) != 0 + if args.mutations: + report['mutants'] = {} + for name in MUTATIONS: + result = run(name, unit(root, mutation=name), output) + result['class'] = 'KILLED' if result['class'] == 'RAN' and any(result['cases'].values()) else result['class'] + report['mutants'][name] = result + valid &= result['class'] == 'KILLED' + report['after_control'] = run('after-control', unit(root), output) + valid &= report['after_control']['class'] == 'RAN' and not any(report['after_control']['cases'].values()) + report['valid'] = bool(valid) + (output / 'receipt.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps({'valid': bool(valid), 'output': str(output), 'control': report['control']['class'], + 'baseline': report.get('baseline', {}).get('class'), + 'mutants': {k: v['class'] for k, v in report.get('mutants', {}).items()}})) + return 0 if valid else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py b/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py index 697d9c02370c8d..1b88670daf92f7 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py @@ -133,12 +133,15 @@ def make_unit(source, parent=False, reference=None): APPLE_ATCPHY_MODE_USB3, APPLE_ATCPHY_MODE_USB3_DP, APPLE_ATCPHY_MODE_DP, APPLE_ATCPHY_MODE_TBT, APPLE_ATCPHY_MODE_USB4 }; enum atcphy_pipehandler_state { ATCPHY_PIPEHANDLER_STATE_DUMMY, ATCPHY_PIPEHANDLER_STATE_USB3 }; +GENERATION_ENUM +struct atcphy_hw { GENERATION_FIELD bool has_usb4,has_t8140_dp,dp_t8122; }; struct apple_atcphy { void *dev; int lock; - const struct { bool has_usb4,has_t8140_dp,dp_t8122; } *hw; + const struct atcphy_hw *hw; struct { void *usb2phy; } regs; bool fixed_usb2,host_active,mode_dirty,pipe_pending,usb_off_pending,ss_tunables,dp_tunables; bool usb3_port_off,park_owed,dp_only,pd_was_off; + bool t8103_dummy_pending,t8103_usb3_retry,t8103_usb3_workaround; enum atcphy_mode mode,typec_mode; enum atcphy_pipehandler_state pipe_state; }; @@ -153,6 +156,9 @@ def make_unit(source, parent=False, reference=None): static void atcphy_restore_after_pd_off(struct apple_atcphy *p) { assert(!p->pd_was_off); } static int atcphy_park_pipehandler(struct apple_atcphy *p, bool keep_dp) { (void)keep_dp;p->pipe_state=ATCPHY_PIPEHANDLER_STATE_DUMMY;return 0; } static int atcphy_configure_pipehandler(struct apple_atcphy *p,bool on) { (void)p;(void)on;assert(false);return -EINVAL; } +/* Role exit parks the ordinary PIPE first; a live legacy park is never owed here. */ +static int __attribute__((unused)) atcphy_park_live_t8103_pipehandler(struct apple_atcphy *p) { (void)p;assert(false);return -EINVAL; } +static struct atcphy_hw ordinary_hw GENERATION_INIT; static int atcphy_configure(struct apple_atcphy *p,enum atcphy_mode mode) { configure_calls++;lane_requests+=mode!=APPLE_ATCPHY_MODE_OFF;p->mode=mode;p->mode_dirty=false;return 0; } static void set32(void *p,unsigned v) { (void)p;(void)v;assert(false); } static void atcphy_usb2_power_on(struct apple_atcphy *p) { (void)p;assert(false); } @@ -161,7 +167,7 @@ def make_unit(source, parent=False, reference=None): 'static int atcphy_usb2_init(')) + r''' static int ordinary_power_off(void) { return atcphy_usb3_power_off(&usb_phy); } static void ordinary_initial(void) { - ordinary_phy=(struct apple_atcphy){.mode=APPLE_ATCPHY_MODE_USB3,.typec_mode=APPLE_ATCPHY_MODE_USB3,.pipe_state=ATCPHY_PIPEHANDLER_STATE_USB3}; + ordinary_phy=(struct apple_atcphy){.hw=&ordinary_hw,.mode=APPLE_ATCPHY_MODE_USB3,.typec_mode=APPLE_ATCPHY_MODE_USB3,.pipe_state=ATCPHY_PIPEHANDLER_STATE_USB3}; phy_warns=configure_calls=lane_requests=0; } static int ordinary_safe(void) { @@ -177,6 +183,12 @@ def make_unit(source, parent=False, reference=None): assert(ordinary_phy.typec_mode==APPLE_ATCPHY_MODE_OFF&&lane_requests==before); } ''' + # The ordinary port is the T8122 profile unless a case selects the T8103 + # generation, whose live legacy PIPE park the mux switch now consults. + generation='enum atcphy_generation {' in atc + ordinary_phy=ordinary_phy.replace('GENERATION_ENUM\n',block(atc,'enum atcphy_generation {')+';\n' if generation else '',1) + ordinary_phy=ordinary_phy.replace('GENERATION_FIELD ','enum atcphy_generation gen; ' if generation else '',1) + ordinary_phy=ordinary_phy.replace(' GENERATION_INIT',' ={.gen=ATCPHY_GENERATION_T8122}' if generation else '',1) if split[-1]: # An ordinary port takes no SuperSpeed port down, so none may come up. ordinary_phy=ordinary_phy.replace(' int ret=atcphy_mux_set_locked(&ordinary_phy,APPLE_ATCPHY_MODE_OFF);', diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index b69a0bd01a4bd9..5ac596625d9acc 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -48,6 +48,8 @@ def wire(value, out): metadata = block(metadata, 'struct dcp_display_metadata {') + ';\n' header = (base / 'parser.h').read_text() header = header[header.index('struct apple_dcp;'):header.index('int parse(')] + # Header helpers stay header-like: unused here, as in any includer. + header = header.replace('static inline ', 'static inline __attribute__((unused)) ') edid_header = (root / 'include/drm/drm_edid.h').read_text() edid_header = edid_header[edid_header.index('#define EDID_LENGTH'):edid_header.index('/* EDID matching */')] builder = (base / 'dcp-display-metadata.c').read_text() @@ -559,13 +561,13 @@ def publication(root): state = state.replace('struct apple_epic_service { struct apple_epic *ep; void *cookie; bool enabled; };', '''struct apple_epic_service { struct apple_epic *ep; void *cookie; bool enabled,torndown; unsigned users,channel; struct { u64 generation,epoch; } admission; };''') - state = state.replace('struct { bool lock, enabled; void *service; u64 epoch; } dcpavserv;', 'struct { bool lock, enabled; void *service, *opened; u64 epoch; int enable_completion; } dcpavserv;') + state = state.replace('struct { bool lock, enabled; void *service; u64 epoch; } dcpavserv;', 'struct { bool lock, enabled; void *service, *opened; u64 epoch,opened_epoch; int enable_completion; struct work_struct close_wq; } dcpavserv;') # Catalogue/EDID ownership: modes are admitted per attachment under modes_lock. state = state.replace(' struct work_struct hotplug_wq, bl_sync_wq;\n};', ' struct work_struct hotplug_wq, bl_sync_wq;\n bool edid_live; unsigned hotplug_reasons;\n};', 1) state = state.replace('u64 typec_generation; unsigned int nr_modes;', '''u64 typec_generation; unsigned int nr_modes; struct apple_epic *dcpavservep; int fw_compat,width_mm,height_mm,fixed_connector_type; unsigned notch_height; - bool modes_lock,modes_admitted,modes_provisional,placeholder_retried; int external_held; + bool modes_lock,modes_admitted,modes_provisional,placeholder_retried,external_native; int external_held; u64 modes_generation,dimensions_generation; struct work_struct dimensions_wq; struct { int width_mm,height_mm; } panel; struct { size_t length,received; void *data; bool contiguous,payload_complete; u64 modes_generation; @@ -606,6 +608,10 @@ def publication(root): static struct apple_epic_service *afk_service_get(struct apple_epic_service *s) { if(!s->enabled) return NULL; s->users++; return s; } static void afk_service_put(struct apple_epic_service *s) { assert(s->users); s->users--; } static void afk_service_retire(struct apple_epic_service *s) { assert(!*hpd_lock); s->enabled=false; s->torndown=true; } +/* These H17P scenarios never queue the native 14.7 Close worker. */ +static bool cancel_work_sync(struct work_struct *w) { assert(!w->scheduled); return false; } +/* Native audio is out of scope: reject entry instead of silently queueing it. */ +static void dcp_external_audio_start(struct apple_dcp *d) { assert(!d->external_native); } static void dpavservep_detach(struct apple_dcp *d); static struct apple_dcp *probing; static struct drm_edid transport_edid; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py b/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py index 5fa3a4900ce180..0a26ac0e584f13 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py @@ -408,6 +408,13 @@ def run(name,text,cases): static const struct drm_edid *dcpavserv_read_edid_legacy(struct apple_epic_service *service) { return dcpavserv_read_edid_inline(service); } /* The 14.7 open-before-EDID handshake is for T6030 external processors only. */ static int __attribute__((unused)) afk_service_call(struct apple_epic_service *s,u16 group,u32 command,const void *data,size_t data_len,size_t data_pad,void *output,size_t output_len,size_t output_pad) { (void)s;(void)group;(void)command;(void)data;(void)data_len;(void)data_pad;(void)output;(void)output_len;(void)output_pad;assert(!"14.7 open-before-EDID on H17P");return -ENODEV; } + /* Only the 14.7 external role opens the AV client and validates every EDID block. */ + #ifndef ECANCELED + #define ECANCELED 125 + #endif + static int __attribute__((unused)) dcpavserv_v14_open(struct apple_dcp *d,struct apple_epic_service *s,u64 epoch,u64 gen) + { (void)d;(void)s;(void)epoch;(void)gen;assert(!"14.7 AV client open on H17P");return -ENODEV; } + static bool __attribute__((unused)) drm_edid_valid(const struct drm_edid *e) { (void)e;assert(!"14.7 EDID validation on H17P");return false; } ''' dpav=(root/'drivers/gpu/drm/apple/epic/dpavservep.c').read_text() for signature in ['bool dcpavserv_edid_current(', 'bool dcpavserv_edid_service_current(', 'const struct drm_edid *dcpavserv_copy_edid(']: diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py b/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py index 4fac9d05bb746d..1c1cc0327353cd 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py @@ -102,10 +102,17 @@ def check(name, unit, cases=((),), negative=False, flags=()): actual=actual[:pos]+extra+actual[pos:] # The fabric core split: availability is the real dcp_fabric_available() over # the real ownership (SAFE lease included) and HDMI presence of the pipeline. + # T6030 dock support keys availability and HDMI settling on the ordered + # dual-stream policy, the real dcp_fabric_ordered_dual_stream() of the wiring. available=''.join(block(dcp,marker)+'\n' for marker in ( 'static bool dcp_typec_safe_held(struct apple_dcp *dcp)\n{', 'bool dcp_typec_dual_stream(void)\n{', + 'bool dcp_typec_ordered_dual_stream(void)\n{', 'static bool dcp_hdmi_settle_enabled(struct apple_dcp *dcp)\n{', 'static enum dcp_fabric_presence_state dcp_hdmi_presence(struct apple_dcp *dcp)\n{') if marker in dcp) + if 'bool dcp_typec_ordered_dual_stream(void)\n{' in dcp: + # These scenarios are an M1/M2 Type-C port, never the native T6030 machine. + available='''static bool of_machine_is_compatible(const char *compat) { assert(!strcmp(compat,"apple,t6030"));return false; } + '''+available # Route-follow: the fixed output, or a failed T6030 external processor, keeps the route busy. available+=apple_function(ROOT,'dcp_typec_route_busy') if available: diff --git a/tools/testing/selftests/drivers/gpu/asahi-g15/pmp-bridge.c b/tools/testing/selftests/drivers/gpu/asahi-g15/pmp-bridge.c new file mode 100644 index 00000000000000..b27a8e6347b603 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-g15/pmp-bridge.c @@ -0,0 +1,81 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* Compile the production consumer glue against the maintained PMP owner. */ +#include +#include +#include +#include + +struct device { void *of_node; }; +static bool board = true, compatible = true; +static int links, votes, link_result, vote_result; +static int display_calls, display_result; +static bool display_admitted; +static bool asahi_g15_board(void) { return board; } +static bool of_device_is_compatible(void *node, const char *name) +{ + (void)node; + (void)name; + return compatible; +} +static int apple_drm_t6030_link_device(struct device *dev) +{ + assert(dev->of_node); + display_calls++; + display_admitted = display_result == 0; + return display_result; +} +static int apple_pmp_link_device(struct device *dev) +{ + assert(dev->of_node); + assert(display_admitted); + display_admitted = false; + links++; + return link_result; +} +static int apple_pmp_set_device_power(unsigned char command, unsigned short device, + unsigned int enabled) +{ + assert(command == 0x0f && device == 5 && enabled == 1); + votes++; + return vote_result; +} +#include "pmp-production.h" + +int main(void) +{ + struct device dev = { .of_node = &dev }; + + board = false; + assert(asahi_g15_pmp_prepare(&dev) == -ENODEV); + assert(asahi_g15_pmp_get(&dev) == -ENODEV); + board = true; + compatible = false; + assert(asahi_g15_pmp_prepare(&dev) == -ENODEV); + assert(asahi_g15_pmp_get(&dev) == -ENODEV); + compatible = true; + dev.of_node = NULL; + assert(asahi_g15_pmp_prepare(&dev) == -ENODEV); + assert(asahi_g15_pmp_get(&dev) == -ENODEV); + assert(display_calls == 0 && links == 0 && votes == 0); + dev.of_node = &dev; + display_result = -517; + assert(asahi_g15_pmp_prepare(&dev) == -517); + assert(links == 0 && votes == 0); + display_result = -EINVAL; + assert(asahi_g15_pmp_prepare(&dev) == -EINVAL); + assert(links == 0 && votes == 0); + display_result = 0; + link_result = -517; /* EPROBE_DEFER */ + assert(asahi_g15_pmp_prepare(&dev) == -517); + assert(votes == 0); + link_result = 0; + assert(asahi_g15_pmp_prepare(&dev) == 0); + vote_result = -ETIMEDOUT; + assert(asahi_g15_pmp_get(&dev) == -ETIMEDOUT); + vote_result = -EIO; + assert(asahi_g15_pmp_get(&dev) == -EIO); + vote_result = 0; + assert(asahi_g15_pmp_get(&dev) == 0); + assert(display_calls == 4 && links == 2 && votes == 3); + puts("production PMP bridge: board rejection, display-before-PMP admission, defer, ACK errors and exact AGX vote: PASS"); +} diff --git a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py new file mode 100644 index 00000000000000..35c96a7f36176c --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host checks of production G15 admission and pure recovery/buffer logic. + +No GPU access or kernel build. Kernel services are mocked; this cannot establish +that a GPU boots, that cache maintenance works, or that the driver compiles. +""" +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[6] +G15 = ROOT / "drivers/gpu/drm/asahi/g15" + +MEMORY_PREFIX = r''' +#include +#include +#include +typedef uint64_t u64; +#define PAGE_SIZE 0x4000UL +#define PAGE_SHIFT 14 +#define IS_ALIGNED(x, a) (!((x) & ((a) - 1))) +#define PHYS_PFN(x) ((unsigned long)((x) >> PAGE_SHIFT)) +#define check_add_overflow(a, b, out) __builtin_add_overflow(a, b, out) +#define IORESOURCE_SYSTEM_RAM 1 +#define IORES_DESC_NONE 0 +#define REGION_INTERSECTS 1 +#define REGION_DISJOINT 0 +#define MEMREMAP_WB 1 +#define MEMREMAP_WC 4 +struct page { bool valid, ram, reserved; }; +static struct page pages[8]; +static bool pfn_valid(unsigned long pfn) { return pfn < 8 && pages[pfn].valid; } +static bool page_is_ram(unsigned long pfn) { return pfn < 8 && pages[pfn].ram; } +static struct page *pfn_to_page(unsigned long pfn) { return &pages[pfn]; } +#define PageReserved(p) ((p)->reserved) +/* Model the documented API: RAM plus undefined holes is INTERSECTS. */ +static int region_intersects(u64 start, u64 size, int flags, int desc) +{ + unsigned long first = PHYS_PFN(start); + (void)flags; (void)desc; + if (!size || start + size < start) + return REGION_DISJOINT; + for (unsigned long p = first; p < 8 && p <= PHYS_PFN(start + size - 1); p++) + if (pages[p].ram) + return REGION_INTERSECTS; + return REGION_DISJOINT; +} +''' + +MEMORY_CASES = r''' +static int failures; +static void check(const char *name, u64 start, u64 size, bool expected) +{ + bool actual = asahi_g15_ram_within(start, size); + printf("%s: %s\n", name, actual == expected ? "PASS" : "FAIL"); + failures += actual != expected; +} +static void mode(const char *name, u64 start, u64 size, unsigned int expected) +{ + unsigned int actual = asahi_g15_memory_mode(start, size); + printf("%s: %s\n", name, actual == expected ? "PASS" : "FAIL"); + failures += actual != expected; +} +int main(void) +{ + for (int i = 0; i < 8; i++) + pages[i] = (struct page){true, true, true}; + check("reserved RAM", PAGE_SIZE, 3 * PAGE_SIZE, true); + mode("reserved mapping is WB", PAGE_SIZE, 3 * PAGE_SIZE, MEMREMAP_WB); + mode("non-RAM mapping is WC", 8 * PAGE_SIZE, PAGE_SIZE, MEMREMAP_WC); + mode("mapping rejects empty range", PAGE_SIZE, 0, 0); + mode("mapping rejects unaligned address", PAGE_SIZE + 1, PAGE_SIZE, 0); + mode("mapping rejects unaligned size", PAGE_SIZE, PAGE_SIZE - 1, 0); + mode("mapping rejects overflow", UINT64_MAX & ~(PAGE_SIZE - 1), PAGE_SIZE, 0); + check("last complete page", 7 * PAGE_SIZE, PAGE_SIZE, true); + check("empty range", PAGE_SIZE, 0, false); + check("unaligned address", PAGE_SIZE + 1, PAGE_SIZE, false); + check("unaligned size", PAGE_SIZE, PAGE_SIZE - 1, false); + check("overflow", UINT64_MAX & ~(PAGE_SIZE - 1), PAGE_SIZE, false); + pages[2].ram = false; + check("RAM plus undefined hole", PAGE_SIZE, 3 * PAGE_SIZE, false); + mode("mapping rejects RAM plus hole", PAGE_SIZE, 3 * PAGE_SIZE, 0); + pages[2].ram = true; + pages[2].reserved = false; + check("allocator-owned page", PAGE_SIZE, 3 * PAGE_SIZE, false); + mode("mapping rejects allocator page", PAGE_SIZE, 3 * PAGE_SIZE, 0); + pages[2].reserved = true; + pages[2].valid = false; + check("invalid PFN", PAGE_SIZE, 3 * PAGE_SIZE, false); + mode("mapping rejects invalid PFN", PAGE_SIZE, 3 * PAGE_SIZE, 0); + return failures ? 1 : 0; +} +''' + +RUST_PREFIX = r''' +#![allow(dead_code)] +extern crate self as kernel; +pub mod prelude { + pub type Error = i32; + pub type Result = std::result::Result; + pub const EINVAL: Error = -22; + pub const EFAULT: Error = -14; + pub use crate::{pr_warn, static_assert}; +} +#[macro_export] +macro_rules! pr_warn { ($($arg:tt)*) => { let _ = format_args!($($arg)*); } } +#[macro_export] +macro_rules! static_assert { ($e:expr) => { const _: () = assert!($e); } } +pub mod mmu { + use crate::prelude::*; + pub const UAT_PGSZ: usize = 0x4000; + pub const UAT_PGMSK: usize = UAT_PGSZ - 1; + pub struct Vm(pub Vec); + impl Vm { + pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { + let start = usize::try_from(va).map_err(|_| EFAULT)?; + let end = start.checked_add(out.len()).ok_or(EFAULT)?; + out.copy_from_slice(self.0.get(start..end).ok_or(EFAULT)?); + Ok(()) + } + } +} +mod command { + use crate::{mmu, prelude::*}; + pub const USC_WINDOW: u64 = 1 << 32; + pub fn cover(vm: &mmu::Vm, start: u64, end: u64, _: bool, _: bool) -> Result { + let mut bytes = vec![0; usize::try_from(end - start).map_err(|_| EINVAL)?]; + vm.read_user(start, &mut bytes) + } +} +mod params { pub fn stream_gate() -> bool { true } } +''' + +GATE_CASES = r''' +#[cfg(test)] +mod gate_regressions { + use crate::{gate, mmu, prelude::*}; + fn vm(words: &[u32]) -> mmu::Vm { + let mut bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + bytes.resize(bytes.len() + 256, 0); + mmu::Vm(bytes) + } + #[test] + fn terminator_and_known_barrier() { + assert_eq!(gate::cdm(&vm(&[0x40000000]), 0, 0), Ok(())); + assert_eq!(gate::cdm(&vm(&[0x60000160, 0x40000000]), 0, 0), Ok(())); + } + #[test] + fn cyclic_links_are_rejected() { + assert_eq!(gate::cdm(&vm(&[0x20000000, 0]), 0, 0), Err(EINVAL)); + } + #[test] + fn record_budget_requires_a_terminator() { + assert_eq!(gate::cdm(&vm(&vec![0x60000160; 8192]), 0, 0), Err(EINVAL)); + } + #[test] + fn final_record_may_terminate() { + let mut words = vec![0x60000160; 8192]; + words[8191] = 0x40000000; + assert_eq!(gate::cdm(&vm(&words), 0, 0), Ok(())); + } + #[test] + fn malformed_and_unreadable_streams_are_rejected() { + assert_eq!(gate::cdm(&vm(&[0xffffffff]), 0, 0), Err(EINVAL)); + assert_eq!(gate::cdm(&vm(&[0x20000000, 2]), 0, 0), Err(EINVAL)); + assert_eq!(gate::cdm(&mmu::Vm(vec![]), 0, 0), Err(EFAULT)); + } +} +''' + + +def main(): + with tempfile.TemporaryDirectory(prefix="asahi-g15-host-") as temp: + temp = Path(temp) + glue = (G15 / "glue.c").read_text() + functions = [] + for signature in ["bool asahi_g15_ram_disjoint", "bool asahi_g15_ram_within", + "unsigned int asahi_g15_memory_mode"]: + marker = signature + "(u64 start, u64 size)\n{" + start = glue.index(marker) + end = glue.index("\n}", start) + 2 + functions.append(glue[start:end]) + c_source = temp / "memory.c" + c_source.write_text(MEMORY_PREFIX + "\n".join(functions) + MEMORY_CASES) + subprocess.run([os.environ.get("HOSTCC", "cc"), "-std=gnu11", "-Wall", "-Wextra", + "-Werror", "-Wno-unused-function", str(c_source), + "-o", str(temp / "memory")], check=True) + memory = subprocess.run([str(temp / "memory")]).returncode + + start = glue.index("bool asahi_g15_reserved_uat(u32 index, u64 start, u64 size)\n{") + end = glue.index("\n}", start) + 2 + (temp / "uat-production.h").write_text(glue[start:end]) + subprocess.run([os.environ.get("HOSTCC", "cc"), "-std=c11", "-Wall", "-Wextra", + "-Werror", "-I", str(temp), + str(Path(__file__).with_name("uat-owner.c")), + "-o", str(temp / "uat-owner")], check=True) + subprocess.run([str(temp / "uat-owner")], check=True) + + pmp = [] + for name in ["prepare", "get"]: + start = glue.index("int asahi_g15_pmp_" + name + "(struct device *dev)\n{") + end = glue.index("\n}", start) + 2 + pmp.append(glue[start:end]) + (temp / "pmp-production.h").write_text("\n".join(pmp)) + # This module has one maintained PMP bridge, not SF's old alternate stack. + # Supplier-readiness behavior is covered with the maintained PMP implementation's + # own tests; this fixture verifies the consumer's gate, defer, ACK and vote contract. + output = temp / "pmp-maintained" + subprocess.run([os.environ.get("HOSTCC", "cc"), "-std=c11", "-Wall", "-Wextra", + "-Werror", "-Wno-unused-function", "-I", str(temp), + str(Path(__file__).with_name("pmp-bridge.c")), "-o", str(output)], check=True) + subprocess.run([str(output)], check=True) + + # Native wire layout is a private per-backend facade. Its independent host test + # checks that canonical normal/G17 UAPI remains unchanged; there is no global + # Rust bindgen header selector in this integration. + harness = RUST_PREFIX + f'\n#[path = "{G15 / "gate.rs"}"] mod gate;\n' + harness += f'#[path = "{G15 / "recovery/logic.rs"}"] mod recovery;\n' + harness += f'#[path = "{G15 / "power/idle.rs"}"] mod idle;\n' + harness += f'#[path = "{G15 / "power/pstate.rs"}"] mod pstate;\n' + harness += ("mod firmware_identity {\n" + + f'#[path = "{G15 / "identity/matching.rs"}"] pub mod matching;\n' + + f'#[path = "{G15 / "identity/lookup.rs"}"] pub mod lookup;\n' + "}\n") + # The T6031 board-data builders (the J516C fixture cases stay ignored: they need + # off-tree machine data). + harness += ("mod board {\n" + + f'#[path = "{G15 / "board/template.rs"}"] pub mod template;\n' + + "pub(crate) use template::{Line, Template};\n" + + f'#[path = "{G15 / "board/data.rs"}"] pub mod data;\n' + + f'#[path = "{G15 / "board/words.rs"}"] pub mod words;\n' + + f'#[path = "{G15 / "board/record.rs"}"] pub mod record;\n' + "}\n") + harness += ("mod g15 { pub mod fw {\n" + + f'#[path = "{G15 / "fw/channels.rs"}"] pub mod channels;\n' + + f'#[path = "{G15 / "fw/buffer.rs"}"] pub mod buffer;\n' + + "} pub mod object {\n" + + f'#[path = "{G15 / "object/geometry.rs"}"] pub mod geometry;\n' + + "} pub mod pools {\n" + + f'#[path = "{G15 / "pools/growth.rs"}"] pub mod growth;\n' + "}}\n") + rust_source = temp / "host.rs" + rust_source.write_text(harness + GATE_CASES) + subprocess.run([os.environ.get("HOSTRUSTC", "rustc"), "--edition=2021", "--test", + str(rust_source), "-o", str(temp / "host")], check=True) + rust = subprocess.run([str(temp / "host")]).returncode + return int(bool(memory or rust)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/testing/selftests/drivers/gpu/asahi-g15/uat-owner.c b/tools/testing/selftests/drivers/gpu/asahi-g15/uat-owner.c new file mode 100644 index 00000000000000..9909ac31e3a417 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-g15/uat-owner.c @@ -0,0 +1,85 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#include +#include +#include +#include +#include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +typedef uint32_t u32; +typedef uint64_t u64; +struct device_node { + bool available, reusable, extra, bad_reg; +}; +struct resource { + u64 start, end; +}; +static struct device_node node = { .available = true }; +static bool missing; +static u64 start = 0x100000, size = 0x4000; +static int refs; +static struct device_node *of_find_node_by_path(const char *path) +{ + assert(!strncmp(path, "/reserved-memory/uat-", 21)); + if (missing) + return NULL; + refs++; + return &node; +} +static bool of_device_is_available(struct device_node *np) +{ + return np->available; +} +static bool of_property_read_bool(struct device_node *np, const char *name) +{ + assert(!strcmp(name, "reusable")); + return np->reusable; +} +static const void *of_get_address(struct device_node *np, int index, void *a, + void *b) +{ + assert(index == 1 && !a && !b); + return np->extra ? np : NULL; +} +static int of_address_to_resource(struct device_node *np, int index, + struct resource *res) +{ + assert(index == 0); + res->start = start; + res->end = start + size - 1; + return np->bad_reg ? -1 : 0; +} +static u64 resource_size(struct resource *res) +{ + return res->end - res->start + 1; +} +static void of_node_put(struct device_node *np) +{ + if (np) + refs--; +} +#include "uat-production.h" + +int main(void) +{ + for (u32 i = 0; i < 4; ++i) + assert(asahi_g15_reserved_uat(i, start, size)); + assert(!asahi_g15_reserved_uat(4, start, size)); + assert(!asahi_g15_reserved_uat(0, start + 0x4000, size)); + assert(!asahi_g15_reserved_uat(0, start, size + 0x4000)); + missing = true; + assert(!asahi_g15_reserved_uat(0, start, size)); + missing = false; + node.available = false; + assert(!asahi_g15_reserved_uat(0, start, size)); + node.available = true; + node.reusable = true; + assert(!asahi_g15_reserved_uat(0, start, size)); + node.reusable = false; + node.extra = true; + assert(!asahi_g15_reserved_uat(0, start, size)); + node.extra = false; + node.bad_reg = true; + assert(!asahi_g15_reserved_uat(0, start, size)); + assert(refs == 0); + puts("production UAT owner: exact ranges, unavailable/reusable/malformed/extra reservations: PASS"); +} diff --git a/tools/testing/selftests/mm/hugetlb-mmap.c b/tools/testing/selftests/mm/hugetlb-mmap.c index 0f2aad1b7dbd6f..2edbc992e6bcf0 100644 --- a/tools/testing/selftests/mm/hugetlb-mmap.c +++ b/tools/testing/selftests/mm/hugetlb-mmap.c @@ -122,7 +122,7 @@ int main(int argc, char **argv) hugepage_size = default_huge_page_size(); if (!hugepage_size) ksft_exit_skip("Could not detect default hugetlb page size."); - ksft_print_msg("Default size hugepages (%lu kB)\n", hugepage_size >> 10); + ksft_print_msg("Default size hugepages (%zu kB)\n", hugepage_size >> 10); } /* munmap will fail if the length is not page aligned */ @@ -131,7 +131,7 @@ int main(int argc, char **argv) hugetlb_set_nr_pages(hugepage_size, nr); if (hugetlb_free_pages(hugepage_size) < nr) - ksft_exit_skip("Not enough %lu Kb pages\n", hugepage_size >> 10); + ksft_exit_skip("Not enough %zu Kb pages\n", hugepage_size >> 10); ksft_set_plan(2); ksft_print_msg("Mapping %lu Mbytes\n", (unsigned long)length >> 20); diff --git a/tools/testing/vma/tests/vma.c b/tools/testing/vma/tests/vma.c index 38a7cc6702f237..04afec6a07e903 100644 --- a/tools/testing/vma/tests/vma.c +++ b/tools/testing/vma/tests/vma.c @@ -38,7 +38,7 @@ static bool test_copy_vma(void) /* Move backwards and do not merge. */ vma = alloc_and_link_vma(&mm, 0x3000, 0x5000, 3, vma_flags); - vma_new = copy_vma(&vma, 0, 0x2000, (struct vm_page_offset) { 0, 0 }, &need_locks); + vma_new = copy_vma(&vma, 0, 0x2000, (struct vm_page_offset) { 0, 0 }, &need_locks, false); ASSERT_NE(vma_new, vma); ASSERT_EQ(vma_new->vm_start, 0); ASSERT_EQ(vma_new->vm_end, 0x2000); @@ -51,7 +51,7 @@ static bool test_copy_vma(void) vma = alloc_and_link_vma(&mm, 0, 0x2000, 0, vma_flags); vma_next = alloc_and_link_vma(&mm, 0x6000, 0x8000, 6, vma_flags); - vma_new = copy_vma(&vma, 0x4000, 0x2000, (struct vm_page_offset) { 4, 0 }, &need_locks); + vma_new = copy_vma(&vma, 0x4000, 0x2000, (struct vm_page_offset) { 4, 0 }, &need_locks, false); vma_assert_attached(vma_new); ASSERT_EQ(vma_new, vma_next);