diff --git a/Documentation/ABI/testing/sysfs-driver-apple-sep b/Documentation/ABI/testing/sysfs-driver-apple-sep index 56be9de08998b..9073e230f884c 100644 --- a/Documentation/ABI/testing/sysfs-driver-apple-sep +++ b/Documentation/ABI/testing/sysfs-driver-apple-sep @@ -623,7 +623,13 @@ Description: while Touch ID captures and entropy requests are held, and "awake" otherwise. sleeps counts completed prepare/post pairs since probe, aborted suspends included. The enclave's - power domains stay on across sleep, so every other attribute + power domains stay on across sleep, except in a T6000 deep + sleep: there the enclave is asked to sleep at the sleep's + commit, gates its own power island and is resumed through + its SEPROM once the tasks run again. If it does not answer + that request, does not gate its island or does not come + back after the wake, the driver stops using it and refuses + every later deep sleep until a reboot. Every other attribute keeps its value over a suspend; a reader checking that the enclave still answers after a resume reads the hwrng. diff --git a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml index 7b0906ff0febf..98ca25e2c6391 100644 --- a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml +++ b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml @@ -44,12 +44,7 @@ properties: reg: minItems: 2 - items: - - description: NVMe controller registers, including the NVMMU - registers on SoCs without a separate NVMMU region - - description: ANS2 co-processor control registers - - description: NVMMU registers, a separate region since T8132 (and - on T604x) + maxItems: 4 reg-names: oneOf: @@ -62,6 +57,14 @@ properties: - const: nvme - const: nvmmu - const: ans + - description: T6000. The NVMe controller and ANS2 co-processor + registers, then ANS's AXI2AF block and its storage-lane block + (ADT ans reg[4] and reg[5]). + items: + - const: nvme + - const: ans + - const: axi2af + - const: storage-lane resets: maxItems: 1 @@ -112,6 +115,29 @@ properties: adopts that RTKit session without renegotiating it. Shared firmware buffers must remain reserved and protected by the SART. + apple,tunable-axi2af: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: + The ADT's afc-aiu-ans-dual-tunables for the axi2af block, as [offset, + mask, value] entries. A deep sleep resets the block; the driver puts + them back before ANS2 starts again. + items: + items: + - description: register offset + - description: mask of the bits to clear + - description: bits to set + + apple,tunable-storage-lane: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: + The ADT's storage-lane-common-tunables for the storage-lane block, as + [offset, mask, value] entries, put back as apple,tunable-axi2af is. + items: + items: + - description: register offset + - description: mask of the bits to clear + - description: bits to set + apple,sleep-wake-delay-ms: description: T6050. After a deep sleep, the time from the storage power being back @@ -184,13 +210,35 @@ allOf: minItems: 3 reg-names: minItems: 3 - else: + + - if: + properties: + compatible: + not: + contains: + enum: + - apple,t6000-nvme-ans2 + - apple,t6041-nvme-ans2 + - apple,t6050-nvme-ans2 + - apple,t8132-nvme-ans2 + - apple,t8140-nvme-ans2 + then: properties: reg: maxItems: 2 reg-names: maxItems: 2 + - if: + properties: + compatible: + contains: + const: apple,t6000-nvme-ans2 + else: + properties: + apple,tunable-axi2af: false + apple,tunable-storage-lane: false + - if: properties: compatible: diff --git a/Documentation/devicetree/bindings/power/apple,t8140-pmp-report.yaml b/Documentation/devicetree/bindings/power/apple,t8140-pmp-report.yaml index 9e0847cb04b0a..2186802c66215 100644 --- a/Documentation/devicetree/bindings/power/apple,t8140-pmp-report.yaml +++ b/Documentation/devicetree/bindings/power/apple,t8140-pmp-report.yaml @@ -258,6 +258,15 @@ patternProperties: switched with interrupts disabled. Setting the state takes a spinlock and polls the acknowledgment atomically. + apple,sleep-wakeup-path: + type: boolean + description: + The consumer of this entry can keep its firmware running through a + system sleep and is then on the wakeup path. The OS keeps the entry, + and the power states it is a child of, on through system sleep while + its consumer is on the wakeup path, as apple,sleep-wakeup-path does + for a PMGR power state. + required: - compatible - reg diff --git a/Documentation/devicetree/bindings/soc/apple/apple,pmp.yaml b/Documentation/devicetree/bindings/soc/apple/apple,pmp.yaml index 33c9d95e38243..4b2bfa130404c 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,pmp.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,pmp.yaml @@ -48,9 +48,15 @@ properties: rather than claim every view as an exclusive resource. reg-names: + minItems: 2 items: - const: pmp - const: asc + - const: iorvbar + description: + The coprocessor's reset vector, which iBoot points at the firmware SRAM + and locks. A sleep that cuts its power resets it; the OS puts it back + before the firmware starts again. mboxes: maxItems: 1 @@ -179,7 +185,7 @@ allOf: else: properties: reg: - maxItems: 2 + maxItems: 3 power-domains: maxItems: 1 interrupts: false diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml index ad24b561a8d5b..003c2cd1a61ad 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml @@ -19,6 +19,7 @@ description: | properties: compatible: enum: + - apple,t6000-sleep - apple,t8103-sleep - apple,t8112-sleep - apple,t8122-sleep @@ -101,6 +102,78 @@ properties: The DCP and the external DCPs, which must be off before a commit, in that order. + apple,pmgr-misc: + $ref: /schemas/types.yaml#/definitions/phandle + description: | + The PMGR misc node (apple,t6000-pmgr-misc), whose "dcs-ps" and "fabric-ps" + words the sleep sets: the memory clock's and the fabric's performance state. + + apple,sio: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The SIO coprocessor. Its CPU (its first reg), its mailbox (mboxes) and + its DARTs (iommus) are stopped in the late steps while its CPU power word + (power-domains) is on. + + apple,sleep-late-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + items: + items: + - description: a PMGR power-state node + - description: the word written to it + description: + T6000. The PMGR power-state words the late steps write right before the + S2R timer, in that order, each with the value written; a node may appear + more than once. Restored on wake. + + apple,tunable-gfx-fabric: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: Offset in the gfx-fabric reg. + - description: Bits to replace, always the whole word. + const: 0xffffffff + - description: Their value. + description: + The setup of the GPU's fabric port, applied in this order before its + power goes for a deep sleep, each word written as listed. + + apple,tunable-disp0-fabric: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: Offset in the disp0-fabric reg. + - description: Bits to replace, always the whole word. + const: 0xffffffff + - description: Their value. + description: + The setup of the internal display block's fabric port, applied in this order before its + power goes for a deep sleep, each word written as listed. + + apple,tunable-dispext0-fabric: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: Offset in the dispext0-fabric reg. + - description: Bits to replace, always the whole word. + const: 0xffffffff + - description: Their value. + description: + The setup of the first external display block's fabric port, applied in this order before its + power goes for a deep sleep, each word written as listed. + + apple,tunable-dispext1-fabric: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: Offset in the dispext1-fabric reg. + - description: Bits to replace, always the whole word. + const: 0xffffffff + - description: Their value. + description: + The setup of the second external display block's fabric port, applied in this order before its + power goes for a deep sleep, each word written as listed. + apple,nco: $ref: /schemas/types.yaml#/definitions/phandle description: @@ -125,6 +198,47 @@ required: - apple,display-coprocessors allOf: + - if: + properties: + compatible: + contains: + const: apple,t6000-sleep + then: + required: + - apple,wake-enable + - apple,pmgr-misc + - apple,sio + - apple,sleep-late-domains + - apple,nco + - apple,tunable-gfx-fabric + - apple,tunable-disp0-fabric + - apple,tunable-dispext0-fabric + - apple,tunable-dispext1-fabric + properties: + reg: + minItems: 13 + maxItems: 13 + reg-names: + items: + - const: wake + - const: ps + - const: ps-east + - const: cpu-start + - const: wdt + - const: commit + - const: spmi-irq + - const: ptd + - const: clk-gen + - const: gfx-fabric + - const: disp0-fabric + - const: dispext0-fabric + - const: dispext1-fabric + else: + properties: + apple,tunable-gfx-fabric: false + apple,tunable-disp0-fabric: false + apple,tunable-dispext0-fabric: false + apple,tunable-dispext1-fabric: false - if: properties: compatible: diff --git a/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml b/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml index 08ecfa211ad65..354e8a25a7633 100644 --- a/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml +++ b/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml @@ -62,6 +62,15 @@ properties: Tell the controller the system's power state (SSPS) around a firmware-driven suspend, S3 before it and S0 after. + apple,sleep-ssps-rules: + type: boolean + description: + Talk to the controller under the sleep's rules. A controller that does + not take S3 refuses the sleep. One that does not take S0 after it is + set up again (system power state and interrupt mask) by the driver's + controller setup recovery, and the failure is reported. A command found + done on a read made past its limit counts as done. + firmware-name: description: | Should contain the name of the default patch binary @@ -106,6 +115,7 @@ allOf: then: properties: apple,sleep-ssps: false + apple,sleep-ssps-rules: false additionalProperties: false diff --git a/arch/arm64/boot/dts/apple/t6000-j314s.dts b/arch/arm64/boot/dts/apple/t6000-j314s.dts index 763a99dba58b0..4446fc246c1a5 100644 --- a/arch/arm64/boot/dts/apple/t6000-j314s.dts +++ b/arch/arm64/boot/dts/apple/t6000-j314s.dts @@ -39,6 +39,44 @@ status = "okay"; }; +/* + * The SMC's sleep keys and wake record: pmVC is written 0x100 between slpw and slpa, as macOS + * does; the wake reasons are the ADT's smc-pmu event_name-bitN. + */ +&smc { + apple,sleep-pmvc = <0x100>; + apple,wake-reasons = <0 8 9 10 11 12 14 40 41 42 43 44 45 48>; + apple,wake-reason-names = "pwrbtn", "lid", "charger", "codec", "wifibt", + "trackpadkeyboard", "sdconn", "acattach", "acdetach", + "USB-C_plug", "USB2_plug", "USB2_wake", "aupo", "rtc"; +}; + +/* + * The port controllers' system power state: S3 before a firmware-driven sleep, S0 after it. + * Left in S0, a controller keeps raising events after its bus is down, and the SMC wakes the + * machine at once with acdetach. Under the sleep's rules a controller that does not take S3 + * refuses the sleep, and one that does not take S0 again is set up again by the driver. + */ +&hpm0 { + apple,sleep-ssps; + apple,sleep-ssps-rules; +}; + +&hpm1 { + apple,sleep-ssps; + apple,sleep-ssps-rules; +}; + +&hpm2 { + apple,sleep-ssps; + apple,sleep-ssps-rules; +}; + +&hpm5 { + apple,sleep-ssps; + apple,sleep-ssps-rules; +}; + /* * From the J314s platform device tree (/arm-io/spi2/mesa): the power line * is gpio0 pin 196 (function-mesa_pwr, active high) and the data-ready line @@ -91,3 +129,7 @@ &apciec3_piodma { status = "disabled"; }; + +&sleep { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6000.dtsi b/arch/arm64/boot/dts/apple/t6000.dtsi index 07ae672a27c96..0f77a5718e1af 100644 --- a/arch/arm64/boot/dts/apple/t6000.dtsi +++ b/arch/arm64/boot/dts/apple/t6000.dtsi @@ -34,6 +34,395 @@ <0x2 0x10e70000 0x0 0x90000>, <0x2 0x11e70000 0x0 0x90000>, <0x2 0x12e70000 0x0 0x90000>; + /* + * A deep sleep cuts the PMP's power: its reset vector (reg[1] of the + * ADT's pmp node) and its whole firmware SRAM are put back before it + * starts again. + */ + reg = <0x2 0x8e700000 0x0 0x100000>, + <0x2 0x8ec00000 0x0 0x4000>, + <0x2 0x8e850000 0x0 0x8>; + reg-names = "pmp", "asc", "iorvbar"; + apple,sram-keep = <0x0 0x100000>; +}; + +/* + * The PMP's DART filters every access of the PMP (ADT dart-pmp reg[1]). A deep + * sleep clears it: the DART driver keeps what the loader programmed and writes + * it back after the sleep, before the PMP starts again. + */ +&pmp_dart { + reg = <0x2 0x8e300000 0x0 0x4000>, + <0x2 0x8e304000 0x0 0x4000>; + reg-names = "dart", "dapf"; +}; + +/* + * The camera coprocessor's first DART has an address filter (ADT dart-isp0 + * reg[5]) that the loader programs. A deep sleep clears it: the DART driver + * keeps what the loader programmed and writes it back on resume. + */ +&isp_dart0 { + reg = <0x3 0x860e8000 0x0 0x4000>, + <0x3 0x860ec000 0x0 0x4000>; + reg-names = "dart", "dapf"; +}; + +/* + * ANS's AXI2AF and storage-lane blocks (ADT ans reg[4] and reg[5]) with the ADT's + * afc-aiu-ans-dual-tunables and storage-lane-common-tunables. A deep sleep resets + * both, and the NVMe driver puts the tunables back before ANS starts again. + */ +&nvme { + reg = <0x3 0x93cc0000 0x0 0x40000>, <0x3 0x8f400000 0x0 0x4000>, + <0x3 0x91000000 0x0 0x18000>, <0x3 0x93b90000 0x0 0xc000>; + reg-names = "nvme", "ans", "axi2af", "storage-lane"; + apple,tunable-axi2af = <0x000 0x00000003 0x00000001>, + <0x010 0x0fff0000 0x000d0000>, <0x014 0x0000003f 0x00000001>, + <0x018 0x0000003f 0x00000001>, <0x01c 0x0000003f 0x00000003>, + <0x020 0x0000003f 0x00000003>, <0x024 0x0000003f 0x00000003>, + <0x028 0x0000003f 0x00000003>, <0x02c 0x0000003f 0x00000003>, + <0x030 0x0000003f 0x00000003>, <0x034 0x0000003f 0x00000003>, + <0x400 0x400103ff 0x40010001>, <0x600 0x01ffffff 0x01ffffff>; + apple,tunable-storage-lane = <0x4100 0x00080000 0x0>, + <0x4104 0x00001000 0x0>; +}; + +&{/soc} { + sleep: sleep-controller@292004000 { + compatible = "apple,t6000-sleep"; + reg = <0x2 0x92004000 0x0 0x40>, + <0x2 0x8e080000 0x0 0x50000>, + <0x2 0x8e580000 0x0 0x1000>, + <0x2 0x8e0d4000 0x0 0x18>, + <0x2 0x922b0000 0x0 0x30>, + <0x2 0x925c4000 0x0 0x4>, + <0x2 0x920a1320 0x0 0x44>, + <0x2 0x8e3c0000 0x0 0x19000>, + <0x2 0x8e038000 0x0 0x200>, + <0x4 0x05000000 0x0 0xc000>, + <0x3 0x8c000000 0x0 0xc000>, + <0x2 0x8a000000 0x0 0xc000>, + <0x2 0x8d000000 0x0 0xc000>; + reg-names = "wake", "ps", "ps-east", "cpu-start", "wdt", "commit", + "spmi-irq", "ptd", "clk-gen", "gfx-fabric", + "disp0-fabric", "dispext0-fabric", "dispext1-fabric"; + apple,pmgr-misc = <&pmgr_misc>; + apple,sio = <&sio>; + /* + * The PMGR words of the late steps before the S2R timer, in macOS's order, + * each with the value macOS writes (our traces of macOS on J314s). + */ + apple,sleep-late-domains = + <&ps_afnc2_lw1 0x1f0000ff>, <&ps_sio 0x1f0000ff>, + <&ps_atc0_usb 0x300>, <&ps_atc2_usb 0x300>, + <&ps_atc1_usb 0x300>, <&ps_atc0_usb_aon 0x300>, + <&ps_atc2_usb_aon 0x300>, <&ps_atc1_usb_aon 0x300>, + <&ps_atc3_usb_aon 0x300>, <&ps_atc0_pcie 0x300>, + <&ps_atc1_pcie 0x300>, <&ps_atc2_pcie 0x300>, + <&ps_atc3_pcie 0x300>, <&ps_atc0_common 0x300>, + <&ps_atc2_common 0x300>, <&ps_atc3_common 0x300>, + <&ps_uart2 0x200>, <&ps_uart3 0x200>, + <&ps_uart4 0x200>, <&ps_uart6 0x200>, + <&ps_uart7 0x200>, <&ps_msg 0x200>, + <&ps_afnc1_lw2 0x1000030f>, <&ps_afnc2_lw1 0x1000030f>, + <&ps_afnc3_lw0 0x1000030f>, <&ps_apcie_gp_sys 0x1000030f>, + <&ps_pcie0_ref 0x1400024f>, <&ps_pcie1_ref 0x1400024f>, + <&ps_apcie_st_sys 0x1f0003ff>, <&ps_apcie_st1_sys 0x1f0003ff>, + <&ps_apcie_st 0xff>, <&ps_gpio 0xff>, + <&ps_pmgr_soc_ocla 0xff>, <&ps_sio_cpu 0xf0002ff>, + <&ps_fpwm0 0x2ff>, <&ps_spi_p 0xff>, + <&ps_sio_spmi0 0x1f0000ff>, <&ps_sio_spmi1 0x1f0000ff>, + <&ps_sio_spmi2 0x1f0000ff>, <&ps_uart_n 0xff>, + <&ps_uart1 0xff>, <&ps_audio_p 0x2ff>, + <&ps_aes 0x3ff>, <&ps_ans2 0x1f0003ff>, + <&ps_sio_cpu 0xf00000f>, <&ps_pcie0_ref 0x0>, + <&ps_apcie_gp_sys 0x0>; + /* + * The sources macOS leaves on: AOP.GPIO.IRQ4/6, AOP.OutboxNotEmpty, + * AOP.CPUWakeupAP, NUB.WakeupAP, NUB.GPIO.IRQ2, NUB.APWatchdog, + * NUB.APWakeupTime, NUB.SPMISw0/1/3IRQ, SMC.CPUWakeupAP, + * SMC.OutboxNotEmpty, ATC0-3.CIOWakeup, ATC0-3.USBWakeup. + */ + apple,wake-enable = <12 14 26 27 40 43 49 50 51 52 54 85 90 + 126 127 128 129 130 131 132 133>; + apple,display-coprocessors = <&dcp>; + apple,nco = <&nco>; + + /* + * The setup of the GPU's and the display blocks' fabric ports, as macOS + * writes it in this order when it powers each block up (own hypervisor + * trace, macOS 13.7.8 on a J314s). Linux leaves the blocks at their reset + * values; the sleep entry applies these, then the fabric handshake, before + * the block's power goes. Full masks: each word is written as traced. + */ + apple,tunable-gfx-fabric = + <0x714 0xffffffff 0x2000000>, + <0x718 0xffffffff 0x400080>, + <0x71c 0xffffffff 0x400080>, + <0x720 0xffffffff 0x400080>, + <0x724 0xffffffff 0x400080>, + <0x728 0xffffffff 0x400080>, + <0x72c 0xffffffff 0x400080>, + <0x730 0xffffffff 0x400080>, + <0x734 0xffffffff 0x400080>, + <0x0 0xffffffff 0x11>, + <0x10 0xffffffff 0xd0000>, + <0x14 0xffffffff 0x1>, + <0x18 0xffffffff 0x1>, + <0x1c 0xffffffff 0x3>, + <0x20 0xffffffff 0x3>, + <0x24 0xffffffff 0x3>, + <0x28 0xffffffff 0x3>, + <0x2c 0xffffffff 0x3>, + <0x400 0xffffffff 0x40a10001>, + <0x600 0xffffffff 0x1ffffff>, + <0x800 0xffffffff 0x101>, + <0x410 0xffffffff 0x1100>, + <0x420 0xffffffff 0x1100>, + <0x430 0xffffffff 0x1100>, + <0x8000 0xffffffff 0x9>, + <0x820 0xffffffff 0x80>, + <0x8008 0xffffffff 0x7>, + <0x8014 0xffffffff 0x1>, + <0x8018 0xffffffff 0x1>, + <0x748 0xffffffff 0x1>, + <0x8208 0xffffffff 0x2>, + <0x8280 0xffffffff 0x20>, + <0x8288 0xffffffff 0x3>, + <0x828c 0xffffffff 0xc>, + <0x8290 0xffffffff 0x18>, + <0x8294 0xffffffff 0x30>, + <0x8298 0xffffffff 0x78>, + <0x829c 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x7>, + <0x82bc 0xffffffff 0x1>, + <0x82c0 0xffffffff 0x7>, + <0x7a8 0xffffffff 0x1>, + <0x820c 0xffffffff 0x5>, + <0x8284 0xffffffff 0x20>, + <0x82a0 0xffffffff 0x3>, + <0x82a4 0xffffffff 0xc>, + <0x82a8 0xffffffff 0x18>, + <0x82ac 0xffffffff 0x30>, + <0x82b0 0xffffffff 0x78>, + <0x82b4 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x7>, + <0x82bc 0xffffffff 0x2>, + <0x82c0 0xffffffff 0x7>, + <0x8210 0xffffffff 0x0>, + <0x8408 0xffffffff 0xd>, + <0x8418 0xffffffff 0x3>, + <0x841c 0xffffffff 0x0>, + <0x8420 0xffffffff 0xffffffff>, + <0x8424 0xffffffff 0x0>, + <0x8428 0xffffffff 0xfff>, + <0x82b8 0xffffffff 0x7>, + <0x82bc 0xffffffff 0x4>, + <0x82c0 0xffffffff 0x7>; + apple,tunable-disp0-fabric = + <0x0 0xffffffff 0x11>, + <0x10 0xffffffff 0x610000>, + <0x14 0xffffffff 0x8>, + <0x18 0xffffffff 0x8>, + <0x1c 0xffffffff 0x18>, + <0x20 0xffffffff 0x18>, + <0x24 0xffffffff 0x1>, + <0x28 0xffffffff 0x1>, + <0x2c 0xffffffff 0x18>, + <0x30 0xffffffff 0x18>, + <0x34 0xffffffff 0x18>, + <0x400 0xffffffff 0x40a10001>, + <0x600 0xffffffff 0xaab>, + <0x700 0xffffffff 0x1ffffff>, + <0x8a8 0xffffffff 0x2000005>, + <0x8ac 0xffffffff 0x14d004e>, + <0x8b0 0xffffffff 0x14d004e>, + <0x8b4 0xffffffff 0x14d004e>, + <0x8b8 0xffffffff 0x14d004e>, + <0x8bc 0xffffffff 0x14d004e>, + <0x8c0 0xffffffff 0x14d004e>, + <0x8c4 0xffffffff 0x14d004e>, + <0x8c8 0xffffffff 0x14d004e>, + <0x410 0xffffffff 0x1100>, + <0x420 0xffffffff 0x1100>, + <0x430 0xffffffff 0x1100>, + <0x8000 0xffffffff 0x9>, + <0xa20 0xffffffff 0x2>, + <0x8008 0xffffffff 0x7>, + <0x8014 0xffffffff 0x1>, + <0x8018 0xffffffff 0x1>, + <0x920 0xffffffff 0x3fff0001>, + <0x8208 0xffffffff 0x8>, + <0x8280 0xffffffff 0x20>, + <0x8288 0xffffffff 0x3>, + <0x828c 0xffffffff 0xc>, + <0x8290 0xffffffff 0x18>, + <0x8294 0xffffffff 0x30>, + <0x8298 0xffffffff 0x78>, + <0x829c 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x1>, + <0x82bc 0xffffffff 0x1>, + <0x82c0 0xffffffff 0x1>, + <0x860 0xffffffff 0x1>, + <0x820c 0xffffffff 0x5>, + <0x8284 0xffffffff 0x20>, + <0x82a0 0xffffffff 0x3>, + <0x82a4 0xffffffff 0xc>, + <0x82a8 0xffffffff 0x18>, + <0x82ac 0xffffffff 0x30>, + <0x82b0 0xffffffff 0x78>, + <0x82b4 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x3>, + <0x82bc 0xffffffff 0x2>, + <0x82c0 0xffffffff 0x3>, + <0x8210 0xffffffff 0x0>, + <0x8408 0xffffffff 0x3>, + <0x8418 0xffffffff 0x3>, + <0x841c 0xffffffff 0x0>, + <0x8420 0xffffffff 0xffffffff>, + <0x8424 0xffffffff 0x0>, + <0x8428 0xffffffff 0xfff>, + <0x82b8 0xffffffff 0x7>, + <0x82bc 0xffffffff 0x4>, + <0x82c0 0xffffffff 0x7>; + apple,tunable-dispext0-fabric = + <0x0 0xffffffff 0x11>, + <0x10 0xffffffff 0x6d0000>, + <0x14 0xffffffff 0x9>, + <0x18 0xffffffff 0x9>, + <0x1c 0xffffffff 0x1b>, + <0x20 0xffffffff 0x1b>, + <0x24 0xffffffff 0x1>, + <0x28 0xffffffff 0x1>, + <0x2c 0xffffffff 0x1b>, + <0x30 0xffffffff 0x1b>, + <0x34 0xffffffff 0x1b>, + <0x400 0xffffffff 0x40a10001>, + <0x600 0xffffffff 0xaab>, + <0x700 0xffffffff 0x1ffffff>, + <0x8a8 0xffffffff 0x2000005>, + <0x8ac 0xffffffff 0x14d004e>, + <0x8b0 0xffffffff 0x14d004e>, + <0x8b4 0xffffffff 0x14d004e>, + <0x8b8 0xffffffff 0x14d004e>, + <0x8bc 0xffffffff 0x14d004e>, + <0x8c0 0xffffffff 0x14d004e>, + <0x8c4 0xffffffff 0x14d004e>, + <0x8c8 0xffffffff 0x14d004e>, + <0x410 0xffffffff 0x1100>, + <0x420 0xffffffff 0x1100>, + <0x430 0xffffffff 0x1100>, + <0x8000 0xffffffff 0x9>, + <0xa20 0xffffffff 0x2>, + <0x8008 0xffffffff 0x7>, + <0x8014 0xffffffff 0x1>, + <0x8018 0xffffffff 0x1>, + <0x860 0xffffffff 0x1>, + <0x8208 0xffffffff 0x4>, + <0x8280 0xffffffff 0x20>, + <0x8288 0xffffffff 0x3>, + <0x828c 0xffffffff 0xc>, + <0x8290 0xffffffff 0x18>, + <0x8294 0xffffffff 0x30>, + <0x8298 0xffffffff 0x78>, + <0x829c 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x1>, + <0x82bc 0xffffffff 0x1>, + <0x82c0 0xffffffff 0x1>, + <0x800 0xffffffff 0x1>, + <0x820c 0xffffffff 0x3>, + <0x8284 0xffffffff 0x20>, + <0x82a0 0xffffffff 0x3>, + <0x82a4 0xffffffff 0xc>, + <0x82a8 0xffffffff 0x18>, + <0x82ac 0xffffffff 0x30>, + <0x82b0 0xffffffff 0x78>, + <0x82b4 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x3>, + <0x82bc 0xffffffff 0x2>, + <0x82c0 0xffffffff 0x3>, + <0x8210 0xffffffff 0x0>, + <0x8408 0xffffffff 0x3>, + <0x8418 0xffffffff 0x3>, + <0x841c 0xffffffff 0x0>, + <0x8420 0xffffffff 0xffffffff>, + <0x8424 0xffffffff 0x0>, + <0x8428 0xffffffff 0xfff>, + <0x82b8 0xffffffff 0x7>, + <0x82bc 0xffffffff 0x4>, + <0x82c0 0xffffffff 0x7>; + apple,tunable-dispext1-fabric = + <0x0 0xffffffff 0x11>, + <0x10 0xffffffff 0x6d0000>, + <0x14 0xffffffff 0x9>, + <0x18 0xffffffff 0x9>, + <0x1c 0xffffffff 0x1b>, + <0x20 0xffffffff 0x1b>, + <0x24 0xffffffff 0x1>, + <0x28 0xffffffff 0x1>, + <0x2c 0xffffffff 0x1b>, + <0x30 0xffffffff 0x1b>, + <0x34 0xffffffff 0x1b>, + <0x400 0xffffffff 0x40a10001>, + <0x600 0xffffffff 0xaab>, + <0x700 0xffffffff 0x1ffffff>, + <0x8a8 0xffffffff 0x2000005>, + <0x8ac 0xffffffff 0x14d004e>, + <0x8b0 0xffffffff 0x14d004e>, + <0x8b4 0xffffffff 0x14d004e>, + <0x8b8 0xffffffff 0x14d004e>, + <0x8bc 0xffffffff 0x14d004e>, + <0x8c0 0xffffffff 0x14d004e>, + <0x8c4 0xffffffff 0x14d004e>, + <0x8c8 0xffffffff 0x14d004e>, + <0x410 0xffffffff 0x1100>, + <0x420 0xffffffff 0x1100>, + <0x430 0xffffffff 0x1100>, + <0x8000 0xffffffff 0x9>, + <0xa20 0xffffffff 0x2>, + <0x8008 0xffffffff 0x7>, + <0x8014 0xffffffff 0x1>, + <0x8018 0xffffffff 0x1>, + <0x860 0xffffffff 0x1>, + <0x8208 0xffffffff 0x4>, + <0x8280 0xffffffff 0x20>, + <0x8288 0xffffffff 0x3>, + <0x828c 0xffffffff 0xc>, + <0x8290 0xffffffff 0x18>, + <0x8294 0xffffffff 0x30>, + <0x8298 0xffffffff 0x78>, + <0x829c 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x1>, + <0x82bc 0xffffffff 0x1>, + <0x82c0 0xffffffff 0x1>, + <0x800 0xffffffff 0x1>, + <0x820c 0xffffffff 0x3>, + <0x8284 0xffffffff 0x20>, + <0x82a0 0xffffffff 0x3>, + <0x82a4 0xffffffff 0xc>, + <0x82a8 0xffffffff 0x18>, + <0x82ac 0xffffffff 0x30>, + <0x82b0 0xffffffff 0x78>, + <0x82b4 0xffffffff 0xf0>, + <0x82b8 0xffffffff 0x3>, + <0x82bc 0xffffffff 0x2>, + <0x82c0 0xffffffff 0x3>, + <0x8210 0xffffffff 0x0>, + <0x8408 0xffffffff 0x3>, + <0x8418 0xffffffff 0x3>, + <0x841c 0xffffffff 0x0>, + <0x8420 0xffffffff 0xffffffff>, + <0x8424 0xffffffff 0x0>, + <0x8428 0xffffffff 0xfff>, + <0x82b8 0xffffffff 0x7>, + <0x82bc 0xffffffff 0x4>, + <0x82c0 0xffffffff 0x7>; + /* The ADT's no-restore-gpio-pins of gpio0 */ + apple,pinctrl = <&pinctrl_ap>; + apple,pinctrl-skip-pins = <114 115 119>; + status = "disabled"; + }; }; &gpu { @@ -85,6 +474,16 @@ reg-names = "report", "ane-dvfs"; }; +/* + * The external DCPs' firmware runs through s2idle and a sleep given up, and the DCP puts + * itself on the wakeup path for it. With APPLE_USE_PMP this entry is dcpext1's power domain: + * keep it, and the dispext1 power states under it, on then. dispext0's and disp0's entries + * have that from apple,always-on. + */ +&pmp_report_dispext1 { + apple,sleep-wakeup-path; +}; + #ifdef APPLE_USE_PMP /* * The video encoder, AVD, the JPEG codecs, the scaler and the ProRes codec diff --git a/drivers/base/power/wakeup.c b/drivers/base/power/wakeup.c index e1f6438379631..7355021801559 100644 --- a/drivers/base/power/wakeup.c +++ b/drivers/base/power/wakeup.c @@ -35,6 +35,9 @@ static DEFINE_RAW_SPINLOCK(wakeup_irq_lock); /* If greater than 0 and the system is suspending, terminate the suspend. */ static atomic_t pm_abort_suspend __read_mostly; +/* The transition in progress can no longer be aborted, see pm_wakeup_hold() */ +static bool pm_wakeup_held __read_mostly; + /* * Combined counters of registered wakeup events and wakeup events in progress. * They need to be modified together atomically, so it's better to use one @@ -873,6 +876,9 @@ bool pm_wakeup_pending(void) unsigned long flags; bool ret = false; + if (READ_ONCE(pm_wakeup_held)) + return false; + raw_spin_lock_irqsave(&events_lock, flags); if (events_check_enabled) { unsigned int cnt, inpr; @@ -904,6 +910,20 @@ void pm_system_cancel_wakeup(void) atomic_dec_if_positive(&pm_abort_suspend); } +/** + * pm_wakeup_hold - Keep wakeup events from aborting the transition in progress. + * @hold: Whether to hold them. + * + * For a platform whose suspend cannot be turned around from some point on. + * While held, pm_wakeup_pending() returns false. The events are still + * registered, so the platform sees them once it lets go and can then make + * the sleep a short one. + */ +void pm_wakeup_hold(bool hold) +{ + WRITE_ONCE(pm_wakeup_held, hold); +} + void pm_wakeup_clear(unsigned int irq_number) { raw_spin_lock_irq(&wakeup_irq_lock); diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 81a7ee1da1224..b58858a0a08e2 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -225,6 +225,11 @@ struct sio_hw_data { bool commit_early; /* Acknowledge OSLog counters so pending logs do not stall AP idle. */ bool oslog_echo; + /* + * Idled late with its context and buffers kept, and restarted from there once + * the sleep has cut its power: see sio_park_kept(). + */ + bool park_kept; /* DMA arrays owned by the driver, if not protocol 9's */ const struct sio_dma_arrays *arrays; int (*check_boot_tables)(struct device *dev); @@ -232,6 +237,13 @@ struct sio_hw_data { int (*send_dt_params)(struct sio_data *sio); }; +/* The firmware of a park_kept SIO across a deep sleep */ +enum sio_fw_state { + SIO_FW_RUNNING, /* zero, as after probe */ + SIO_FW_PARKED, /* idle and stopped for the sleep: nothing is sent */ + SIO_FW_LOST, /* did not go idle or start again: left alone until a reboot */ +}; + struct sio_data { const struct sio_hw_data *hw; void __iomem *base; @@ -252,6 +264,7 @@ struct sio_data { * sio_synchronize() is bounded (sio_pm_prepare()). */ bool sleeping; + enum sio_fw_state fw_state; bool firmware_only; /* Protocol 10 firmware given the earlier boot tables: no DMA, which would crash it */ bool tables_mismatch; @@ -729,6 +742,16 @@ static const struct sio_hw_data sio_hw_generic = { .cfg_word4 = 0x800, }; +/* + * T6000 (M1 Pro): parked late for a deep sleep, as macOS does, and restarted with its + * context once the sleep has cut its power. + */ +static const struct sio_hw_data sio_hw_t6000 = { + .fifo_threshold = 0x800, + .cfg_word4 = 0x800, + .park_kept = true, +}; + static const struct sio_hw_data sio_hw_t6030 = { .stop_at_commit = true, .commit_no_cpu_down = true, @@ -815,6 +838,7 @@ static const struct of_device_id sio_of_match[] = { */ { .compatible = "apple,t8122-sio", .data = &sio_hw_t8140 }, { .compatible = "apple,t6030-sio", .data = &sio_hw_t6030 }, + { .compatible = "apple,t6000-sio", .data = &sio_hw_t6000 }, { .compatible = "apple,sio", .data = &sio_hw_generic }, { } }; @@ -1399,11 +1423,11 @@ static bool sio_fill_in_old_locked(struct sio_chan *siochan) FIELD_PREP(SIOMSG_TYPE, MSG_ISSUE) | FIELD_PREP(SIOMSG_DATA, sio_coproc_desc_slot(sio, d)), sio_handle_issue_ack, (void *)(uintptr_t)tx->vd.tx.cookie); - if (ret < 0) + if (ret >= 0) + siochan->pending++; + else if (ret != -ESHUTDOWN) dev_err_ratelimited(sio->dev, "can't issue on chan %d ninflight %d: %d\n", siochan->no, tx->ninflight, ret); - else - siochan->pending++; return true; } @@ -1425,8 +1449,9 @@ static bool sio_fill_in_ring_locked(struct sio_chan *siochan) FIELD_PREP(SIOMSG_DATA, sio_coproc_desc_slot(sio, d)), sio_handle_issue_ack, NULL); if (ret < 0) { - dev_err_ratelimited(sio->dev, "can't issue on chan %d ninflight %d: %d\n", - siochan->no, siochan->nissued, ret); + if (ret != -ESHUTDOWN) + dev_err_ratelimited(sio->dev, "can't issue on chan %d ninflight %d: %d\n", + siochan->no, siochan->nissued, ret); return false; } /* The ack takes the channel lock, held here. */ @@ -2399,6 +2424,10 @@ static int _sio_send_siomsg(struct sio_data *sio, u64 msg, bool atomic, unsigned long generation; int tag, ret; + /* Not to a firmware parked for a deep sleep, or one that did not start again */ + if (READ_ONCE(sio->fw_state) != SIO_FW_RUNNING) + return -ESHUTDOWN; + tag = sio_alloc_tag(sio, msg, atomic, ack_callback, cookie, &generation); if (tag < 0) return tag; @@ -2859,9 +2888,13 @@ static int sio_commit_stop(void *data) return ret; } +/* + * A park_kept SIO is idled by its own late suspend for a deep sleep and needs a live + * firmware there: it stays runtime-active, as one stopped at the commit does. + */ static bool sio_can_runtime_suspend(const struct sio_data *sio) { - return !sio->hw->commit_stop && !sio->hw->stop_at_commit; + return !sio->hw->commit_stop && !sio->hw->stop_at_commit && !sio->hw->park_kept; } static int sio_probe(struct platform_device *pdev) @@ -3255,6 +3288,92 @@ static __maybe_unused int sio_resume(struct device *dev) return 0; } +/* + * A deep sleep of a SoC whose SIO is parked late with its context kept. Not a dry run, which + * cuts no power: there the SIO stays as for s2idle, as a parked one would stay stopped. + */ +static __maybe_unused bool sio_park_kept(struct sio_data *sio) +{ + return sio->hw->park_kept && pm_suspend_target_state == PM_SUSPEND_MEM && + pm_suspend_via_firmware() && !apple_sleep_dry_run(); +} + +/* + * The deep sleep cuts the SIO's power. As macOS does before it, tell the firmware + * that the AP goes idle, idle it and stop its CPU, with its buffers and its state + * left where they are: after the power cut it carries on from there. In the late + * phase, once every device has suspended, as a stopped firmware only starts again + * after a power cut. + */ +static __maybe_unused int sio_park_kept_suspend_late(struct device *dev) +{ + struct sio_data *sio = dev_get_drvdata(dev); + int ret; + + /* Still stopped from a sleep whose restart failed, or left alone */ + if (sio->fw_state != SIO_FW_RUNNING) + return 0; + + ret = apple_rtkit_ap_power_timeout(sio->rtk, false, 2000); + if (!ret) + ret = apple_rtkit_idle_iop(sio->rtk); + if (ret) { + dev_err(dev, "the firmware did not go idle (%d), no DisplayPort sound until a reboot\n", + ret); + WRITE_ONCE(sio->fw_state, SIO_FW_LOST); + return 0; + } + apple_rtkit_detach_keep(sio->rtk); + writel(readl(sio->base + REG_CPU_CONTROL) & ~CPU_CONTROL_RUN, sio->base + REG_CPU_CONTROL); + WRITE_ONCE(sio->fw_state, SIO_FW_PARKED); + + return 0; +} + +static __maybe_unused int sio_park_kept_resume(struct device *dev) +{ + struct sio_data *sio = dev_get_drvdata(dev); + int ret; + + /* This sleep's suspend_late did not park it (it gave up, or the firmware is lost) */ + if (sio->fw_state != SIO_FW_PARKED) + return 0; + + /* + * Given up on the way down, the power was not cut, and a stopped firmware only + * starts again from reset: pulse the engine reset, as the runtime resume does, + * then start it as after the power cut. + */ + if (!pm_resume_via_firmware()) { + ret = apple_sleep_engine_reset(dev); + if (ret) { + dev_err(dev, "sleep given up and the firmware not reset (%d): no DisplayPort sound until the next sleep\n", + ret); + return 0; + } + dev_info(dev, "sleep given up: firmware reset, starting it again\n"); + } + + ret = apple_rtkit_reinit_keep(sio->rtk); + if (!ret) { + writel(CPU_CONTROL_RUN, sio->base + REG_CPU_CONTROL); + ret = apple_rtkit_wake_keep_ap(sio->rtk); + } + if (!ret) + ret = apple_rtkit_restart_started_eps(sio->rtk); + if (!ret) + ret = apple_rtkit_ap_power_timeout(sio->rtk, true, 2000); + if (ret) { + dev_err(dev, "the firmware did not start again (%d), no DisplayPort sound until a reboot\n", + ret); + WRITE_ONCE(sio->fw_state, SIO_FW_LOST); + return 0; + } + WRITE_ONCE(sio->fw_state, SIO_FW_RUNNING); + + return 0; +} + /* One stopped at the sleep commit stays up through system suspend. */ static __maybe_unused int sio_system_suspend(struct device *dev) { @@ -3267,6 +3386,14 @@ static __maybe_unused int sio_system_resume(struct device *dev) { struct sio_data *sio = dev_get_drvdata(dev); + /* + * As this sleep's late suspend went: sio_park_kept() holds for the whole suspend + * cycle. A firmware still parked by an earlier deep sleep whose restart failed stays + * stopped through an s2idle or a dry run, sends nothing (-ESHUTDOWN) and starts again + * after the next power cut. + */ + if (sio_park_kept(sio)) + return sio_park_kept_resume(dev); return sio_can_runtime_suspend(sio) ? pm_runtime_force_resume(dev) : 0; } @@ -3277,6 +3404,10 @@ static __maybe_unused int sio_suspend_late(struct device *dev) if (!pm_suspend_via_firmware() || sio->asleep || sio->rpm_stopped) return 0; + if (sio_park_kept(sio)) + return sio_park_kept_suspend_late(dev); + if (sio->hw->park_kept) + return 0; for (i = 0; i < sio->nchannels; i++) { if (sio_chan_busy(&sio->channels[i])) { diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 52a59dc0eee57..badc6d7de8484 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -2199,7 +2199,15 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, for (ch_idx = 0; ch_idx < ep->num_channels; ch_idx++) { struct apple_epic_service *old = &ep->services[ch_idx]; - if (old != service && afk_service_supersede(old, ops, channel)) { + if (old == service) + continue; + if (afk_service_held(old, ops)) { + dev_info(ep->dcp->dev, + "AFK[ep:%02x]: %s on channel %u: channel %u is still open, left to its owner\n", + ep->endpoint, service_name, channel, old->channel); + continue; + } + if (afk_service_supersede(old, ops, channel)) { dev_info(ep->dcp->dev, "AFK[ep:%02x]: %s on channel %u supersedes channel %u\n", ep->endpoint, service_name, channel, old->channel); diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index 7e17d5188c218..60151ccaed626 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -126,6 +126,13 @@ struct apple_epic_service_ops { /* Compact EPIC: do not send compact start (0x12) on announcement. */ bool defer_start; + /* + * A singleton instance its owner still holds open in the firmware, + * which keeps such an instance after announcing its successor until + * the owner closes it: the successor leaves it to the owner, which + * closes and retires it. Called from the receive path. + */ + bool (*held)(struct apple_epic_service *service); /* * Optional admission, before OPEN/publication. Must not retain service * on failure; teardown must accept a failed/partial preparation. @@ -290,6 +297,21 @@ static inline bool afk_service_supersede(struct apple_epic_service *service, return superseded; } +/* Whether @service, a live instance of @ops, is still held open by its owner. */ +static inline bool afk_service_held(struct apple_epic_service *service, + const struct apple_epic_service_ops *ops) +{ + unsigned long flags; + bool live; + + if (!ops->singleton || !ops->held) + return false; + spin_lock_irqsave(&service->lock, flags); + live = service->ops == ops && service->enabled && !service->torndown; + spin_unlock_irqrestore(&service->lock, flags); + return live && ops->held(service); +} + static inline bool afk_service_matches(struct apple_epic_service *service, u32 channel) { diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index c979b6b83ec9a..eeb2cbbd21131 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -107,6 +107,11 @@ struct audiosrv_data { struct rw_semaphore srv_rwsem; /* Workqueue for starting the audio service */ struct work_struct start_av_service_wq; + /* + * An instance replaced while it was open, with its owner pin + * (plug_lock): the start work closes it (av_audiosrv_held()). + */ + struct apple_epic_service *replaced; #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; @@ -182,6 +187,26 @@ static void av_interface_teardown(struct apple_epic_service *service) mutex_unlock(&asrv->plug_lock); } +/* + * The firmware keeps an audio instance its client has opened, and the + * display's link with it, until the client closes it, also once it has + * announced the instance's successor (a display that drops and comes back + * before the host turned it off). Its successor does not retire such an + * instance: av_audiosrv_init() has it closed first. + */ +static bool av_audiosrv_held(struct apple_epic_service *service) +{ + struct audiosrv_data *asrv = service->ep->dcp->audiosrv; + bool held; + + if (!asrv) + return false; + guard(mutex)(&asrv->plug_lock); + scoped_guard(rwsem_read, &asrv->srv_rwsem) + held = asrv->is_open && asrv->srv == service; + return held; +} + static void av_audiosrv_init(struct apple_epic_service *service, const char *name, const char *class, s64 unit) { @@ -208,6 +233,15 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) wake_up_all(&asrv->gen_wq); #endif + if (old && old != service && asrv->is_open) { + if (!asrv->replaced && queue_start) { + /* The start work closes it before it opens @service. */ + asrv->replaced = old; + old = NULL; + } else { + afk_service_retire_channel(old, old->channel); + } + } if (old) afk_service_put(old); @@ -1132,6 +1166,7 @@ static const struct apple_epic_service_ops avep_ops[] = { .name = "DCPAVAudioInterface", .reusable = true, .singleton = true, + .held = av_audiosrv_held, .init = av_audiosrv_init, .report = av_audiosrv_report, .teardown = av_audiosrv_teardown, @@ -1443,12 +1478,41 @@ static void av_work_service_terminate(struct work_struct *work) } #endif +/* Close the instance replaced while it was open, then retire it. */ +static void av_audiosrv_close_replaced(struct audiosrv_data *asrv) +{ + struct apple_epic_service *old; + struct device *dev; + u32 channel; + int ret; + + scoped_guard(mutex, &asrv->plug_lock) { + old = asrv->replaced; + asrv->replaced = NULL; + } + if (!old) + return; + dev = old->ep->dcp->dev; + channel = old->channel; + ret = afk_service_call(old, 0, asrv->cmds.close, NULL, 0, 16, NULL, 0, 16); + if (ret == -ENODEV) + dev_dbg(dev, "replaced audio service on channel %u already gone\n", channel); + else if (ret) + dev_err(dev, "error closing the replaced audio service on channel %u: %d\n", + channel, ret); + else + dev_info(dev, "closed the replaced audio service on channel %u\n", channel); + afk_service_retire_channel(old, channel); + afk_service_put(old); +} + static void av_work_service_start(struct work_struct *work) { struct audiosrv_data *audiosrv_data; struct apple_dcp *dcp; audiosrv_data = container_of(work, struct audiosrv_data, start_av_service_wq); + av_audiosrv_close_replaced(audiosrv_data); scoped_guard(rwsem_read, &audiosrv_data->srv_rwsem) { if (!audiosrv_data->srv || @@ -1494,6 +1558,7 @@ static void av_audiosrv_flush_owner(struct audiosrv_data *asrv) /* Drain the captured owner, without following a later dcp publication. */ static bool av_audiosrv_drain_owner(struct audiosrv_data *asrv) { + struct apple_epic_service *old; bool first_stop; if (!asrv || !asrv->works_live) @@ -1520,6 +1585,15 @@ static bool av_audiosrv_drain_owner(struct audiosrv_data *asrv) } else { av_audiosrv_flush_owner(asrv); } + /* A replaced instance whose start work never ran keeps no pin. */ + scoped_guard(mutex, &asrv->plug_lock) { + old = asrv->replaced; + asrv->replaced = NULL; + } + if (old) { + afk_service_retire_channel(old, old->channel); + afk_service_put(old); + } return true; } diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index 58105cc3ac6c9..a3da98777a46e 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -1384,6 +1384,34 @@ void dcp_hdmi_suspend(struct apple_dcp *dcp) dcp_hdmi_release_unplugged_locked(dcp, NULL); } +/* + * hw.s2r_park: an HDMI display whose link is up as its firmware is parked for a deep sleep. + * The sleep cuts the PHY and the display block under the parked firmware, and with the link + * still up there the SoC resets. Release the link while the firmware runs, as for a T6030 + * native output, and power the converter down, as macOS keeps it in sleep. + * dcp_platform_resume() sets the output up again and connects the display, also after a + * sleep given up. A display that is gone is left to dcp_hdmi_suspend(). Returns 1 if the + * link was released, 0 if none was up, or the error that kept it up. + */ +int dcp_hdmi_sleep_release(struct apple_dcp *dcp) +{ + int ret; + + guard(mutex)(&dcp_typec_fabric_lock); + + if (dcp->active_typec_route || !READ_ONCE(dcp->dptxport[0].connected) || + !dcp->hdmi_hpd || gpiod_get_value_cansleep(dcp->hdmi_hpd) == 0) + return 0; + + ret = dcp_hdmi_link_release(dcp); + if (ret) + return ret; + if (dcp->dp2hdmi_pwren) + gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 0); + dev_dbg(dcp->dev, "HDMI: link released and converter off for the deep sleep\n"); + return 1; +} + /* * Release a fixed HDMI link unplugged while its HPD IRQ was masked. Hold * the fabric lock from the ownership check through the presence update so @@ -2311,14 +2339,14 @@ static int dcp_typec_route_apply(struct typec_mux_dev *mux, } /* - * Desktop 26.x has one Type-C pipeline: only a port with a sink (HPD) - * takes it. A dock or cable in DP alt mode without a display behind it - * would otherwise hold it against the port that has one. + * Only a port with a sink (HPD) takes a pipeline. A dock or cable in DP + * alt mode without a display behind it would otherwise hold one against + * a port that has a display, for as long as it stays plugged in. The + * port controller reports HPD as a new status when a display appears, + * and the port is routed then. What a port that owns a pipeline does on + * an HPD drop is unchanged. */ - if (!port->owner && !hpd && - (route->dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp_t6041_ext_v27(route->dcp) || - dcp_t8142_ext(route->dcp))) { + if (!port->owner && !hpd) { port->applied_valid = true; return 0; } @@ -2333,7 +2361,7 @@ static int dcp_typec_route_apply(struct typec_mux_dev *mux, best = dcp_typec_free_route(port); /* Every pipeline is driving another port's display. */ if (!best) - return hpd ? dcp_typec_port_busy(port, route->dcp) : -ENOSPC; + return dcp_typec_port_busy(port, route->dcp); ret = dcp_typec_route_activate(best, best->xbar); if (ret) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index b471e87d8f15f..cd5e436870f1a 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -433,6 +433,12 @@ struct apple_dcp_hw_data { bool s2r_ext; /* An external display processor (a dcpext block), not the internal display's */ bool external_processor; + /* + * With 13.5 firmware: a deep sleep, which cuts the display block's power, parks a + * running firmware (A500, IDLE, CPU stopped, RTKit buffers kept) in + * the late suspend and restarts it warm, see dcp_s2r_park(). + */ + bool s2r_park; /* The firmware crashes on any mode but the 120 Hz boot timing, see dcp_mode_settable(). */ bool only_120hz_modes; /* A firmware 27 sleep in progress, and how it ended */ @@ -1085,6 +1091,24 @@ struct apple_dcp { /* Messages from the coprocessor are held in the mailbox for sleep. */ bool rx_held; + /* hw.s2r_park: the suspend got as far as the park, which waits for the late suspend */ + bool s2r_park_due; + /* hw.s2r_park: the PHYs were left to genpd for the sleep, see dcp_platform_resume() */ + bool s2r_phys_unheld; + /* hw.s2r_park: an HDMI display released for the sleep, see dcp_hdmi_sleep_release() */ + bool s2r_hdmi_released; + /* hw.s2r_park: connects that display again after the wake or a refused release */ + struct work_struct s2r_hdmi_link_work; + /* hw.s2r_park, a Type-C output: its Type-C work stopped at PM_SUSPEND_PREPARE */ + bool s2r_typec_off; + /* hw.s2r_park: parked for the sleep (IDLE, CPU stopped), restarted by resume */ + bool s2r_parked; + /* hw.s2r_park: the park set the AP to IDLE, the restart sets it ON again */ + bool s2r_ap_idle; + /* The park released the mailbox hold: resume unpauses the presentation */ + bool s2r_unheld; + /* The last poweron timed out ("connector will be broken"): no firmware sleep */ + bool poweron_timed_out; /* A firmware-driven suspend stops the firmware, see dcp_s2r_suspend(). */ struct apple_dcp_afkep *sleep_v27_ep[0x20]; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 69494314b7614..822225881ca2a 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5618,6 +5618,22 @@ static void dcp_fixed_hdmi_reconnect(struct apple_dcp *dcp, bool poweroff_unplug } } +/* + * hw.s2r_park: the HDMI display released for a deep sleep (dcp_hdmi_sleep_release()), or one + * whose release was refused. Its HPD stayed high, so no edge connects it. As main's + * dcp_s2r_restart_done() does for an s2r_ext DCP, but from a work, as the T6040 link work runs + * after its wake: the connect of a converter output waits out the link configuration this + * firmware does not send for it (dcp_dptx_connect_raw()), which the resume must not wait for. + * A display unplugged meanwhile is reported gone instead. + */ +static void dcp_s2r_hdmi_link_work(struct work_struct *work) +{ + struct apple_dcp *dcp = container_of(work, struct apple_dcp, s2r_hdmi_link_work); + + dev_dbg(dcp->dev, "HDMI: connecting the display released for the sleep\n"); + dcp_fixed_hdmi_reconnect(dcp, false); +} + static int dcp_enable_dp2hdmi_hpd(struct apple_dcp *dcp) { if (dcp_is_typec_output(dcp)) { @@ -9281,6 +9297,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) INIT_WORK(&dcp->s2r_prewarm_work, dcp_s2r_prewarm_work); INIT_WORK(&dcp->t6040_link_work, dcp_t6040_link_work); INIT_DELAYED_WORK(&dcp->t6040_plug_wq, dcp_t6040_plug_work); + INIT_WORK(&dcp->s2r_hdmi_link_work, dcp_s2r_hdmi_link_work); INIT_DELAYED_WORK(&dcp->s2r_prewarm_off_wq, dcp_s2r_prewarm_off_work); mutex_init(&dcp->s2r_prewarm_lock); INIT_WORK(&dcp->bl_register_wq, dcp_work_register_backlight); @@ -9862,6 +9879,7 @@ static void dcp_platform_remove(struct platform_device *pdev) if (dcp) { cancel_work_sync(&dcp->s2r_prewarm_work); cancel_work_sync(&dcp->t6040_link_work); + cancel_work_sync(&dcp->s2r_hdmi_link_work); cancel_delayed_work_sync(&dcp->t6040_plug_wq); cancel_delayed_work_sync(&dcp->s2r_prewarm_off_wq); if (system_state == SYSTEM_RUNNING && dcp->sleep_host_stop && @@ -10141,13 +10159,133 @@ static const char *dcp_external_sleep_vetoed(struct apple_dcp *dcp) return NULL; } -/* dpm_prepare completes for every device before any dpm_suspend callback. - * Veto early so Thunderbolt cannot tear down a working tunnel first. The - * same HPD lock serializes this gate against explicit firmware startup. +/* + * hw.s2r_park (T6000's DCPs, 13.5 firmware): a deep sleep cuts the display blocks' power, the + * external ones' too, and a firmware still running then does not start again. So it is parked + * after every device's suspend, as macOS does it: A500 puts the IOMFB link to sleep, the AP + * goes IDLE where it did, then the IOP, and the CPU stops with the RTKit buffers kept. Not in + * a dry run, which cuts no power. */ +static bool dcp_s2r_park_selected(struct apple_dcp *dcp) +{ + return IS_ENABLED(CONFIG_APPLE_SOC_SLEEP) && dcp->hw.s2r_park && !dcp->external && + dcp->fw_compat == DCP_FIRMWARE_V_13_5 && apple_sleep_commit_stops_coprocs() && + !apple_sleep_dry_run(); +} + +/* The IDLE acknowledgment comes through the mailbox that dcp_hold_for_sleep() held. */ +static void dcp_s2r_park_unhold(struct apple_dcp *dcp) +{ + if (!dcp->rx_held) + return; + apple_rtkit_resume_rx(dcp->rtk); + dcp->rx_held = false; + dcp->s2r_unheld = true; +} + +/* 0 once parked, or with no running firmware to park; else why it is still running */ +static int dcp_s2r_park(struct apple_dcp *dcp) +{ + void __iomem *control = dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL; + u32 ctrl; + int ret; + + if (dcp->hw.adopt_live_session || IS_ERR_OR_NULL(dcp->rtk) || !dcp->coproc_reg || + READ_ONCE(dcp->crashed) || !apple_rtkit_is_running(dcp->rtk)) + return 0; + + dcp_s2r_park_unhold(dcp); + ret = iomfb_s2r_link_sleep_v13_3(dcp); + dev_dbg(dcp->dev, "s2r: link sleep (A500): %d\n", ret); + if (!ret) + ret = apple_rtkit_ap_power_timeout(dcp->rtk, false, 2000); + dcp->s2r_ap_idle = !ret; + ret = apple_rtkit_idle_iop(dcp->rtk); + if (ret) { + dev_warn(dcp->dev, "s2r: IOP IDLE failed: %d, not parked\n", ret); + /* + * Not parked, so dcp_s2r_unpark() does nothing: the AP goes back ON here, which + * also makes A500's link active again. Before RX is held again: the answer comes + * through the mailbox. + */ + if (dcp->s2r_ap_idle) { + int err = apple_rtkit_ap_power_timeout(dcp->rtk, true, 2000); + + if (err) + dev_err(dcp->dev, "s2r: AP not back ON after a failed park: %d\n", err); + dcp->s2r_ap_idle = false; + } + if (dcp->s2r_unheld) { + apple_rtkit_hold_rx(dcp->rtk); + dcp->rx_held = true; + dcp->s2r_unheld = false; + } + return ret; + } + apple_rtkit_detach_keep(dcp->rtk); + ctrl = readl_relaxed(control); + writel_relaxed(ctrl & ~APPLE_DCP_COPROC_CPU_CONTROL_RUN, control); + dcp->s2r_parked = true; + dcp->sleep_fw_runs = false; + apple_sleep_display_quiesced(dcp->dev, true); + dev_dbg(dcp->dev, "s2r: parked, cpu control %#x\n", ctrl); + return 0; +} + +/* + * The parked firmware restarts warm, from what IDLE saved: the CPU runs again with the RTKit + * buffers kept, INIT and the endpoint map, the started endpoints started again and the AP ON + * if the park set it IDLE. That needs its display block to have lost its power: a deep sleep + * did that, and after one given up the sleep driver powers the block down and up first. The + * panel comes back with the display's resume (poweron). + */ +static void dcp_s2r_unpark(struct apple_dcp *dcp) +{ + void __iomem *control = dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL; + struct device_node *ps; + u32 ctrl; + int ret; + + dcp->s2r_park_due = false; + if (!dcp->s2r_parked) + return; + dcp->s2r_parked = false; + apple_sleep_display_quiesced(dcp->dev, false); + if (!pm_resume_via_firmware()) { + ps = of_parse_phandle(dcp->dev->of_node, "resets", 0); + if (!apple_sleep_refusal_cycled(ps)) + dev_warn(dcp->dev, "s2r: sleep given up and the display block not power-cycled: the restart may fail\n"); + of_node_put(ps); + } + + ctrl = readl_relaxed(control); + ret = apple_rtkit_reinit_keep(dcp->rtk); + if (!ret) { + writel_relaxed(ctrl | APPLE_DCP_COPROC_CPU_CONTROL_RUN, control); + ret = apple_rtkit_wake_keep_ap(dcp->rtk); + } + if (!ret) + ret = apple_rtkit_restart_started_eps(dcp->rtk); + if (!ret && dcp->s2r_ap_idle) + ret = apple_rtkit_ap_power_timeout(dcp->rtk, true, 2000); + dcp->s2r_ap_idle = false; + if (ret) + dev_err(dcp->dev, "s2r: restart failed: %d (cpu control was %#x)\n", ret, ctrl); + else + dev_dbg(dcp->dev, "s2r: restarted (cpu control was %#x)\n", ctrl); + if (dcp->s2r_unheld) { + dcp->s2r_unheld = false; + iomfb_pause_presentation(dcp, false); + } +} + static bool dcp_v27_sleep_selected(struct apple_dcp *dcp); static void dcp_v27_sleep_invalidate(struct apple_dcp *dcp); +/* dpm_prepare completes for every device before any dpm_suspend callback. + * Veto early so Thunderbolt cannot tear down a working tunnel first. The + * same HPD lock serializes this gate against explicit firmware startup. + */ static int dcp_platform_prepare(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); @@ -10198,6 +10336,14 @@ static int dcp_platform_prepare(struct device *dev) } return 0; } + /* + * A firmware that did not power its display on is stuck: parked for a deep sleep it + * would not answer, and the sleep resets the SoC. Refused here, where the sleep is known. + */ + if (dcp_s2r_park_selected(dcp) && READ_ONCE(dcp->poweron_timed_out)) { + dev_err(dev, "display firmware did not power on, refusing deep sleep\n"); + return -EBUSY; + } if (!dcp->external) return 0; mutex_lock(&dcp->hpd_mutex); @@ -10222,6 +10368,12 @@ static void dcp_platform_complete(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); + /* The sleep failed before this device suspended (dcp_s2r_pm_notify()). */ + if (dcp->s2r_typec_off) { + dcp->s2r_typec_off = false; + dcp_enable_typec_work(dcp); + } + /* The iBoot interface's display stays powered across system sleep. */ if (dcp_is_iboot(dcp) || READ_ONCE(dcp->sleep_cold_stopped)) return; @@ -12725,6 +12877,23 @@ static int dcp_s2r_pm_notify(struct notifier_block *nb, unsigned long action, vo dcp_v27_dark_replug_owed(dcp); if (dcp_ext_idle_capable(dcp)) dcp_ext_idle_kick(dcp); + /* The sleep failed before this device suspended */ + if (dcp->s2r_typec_off) { + dcp->s2r_typec_off = false; + dcp_enable_typec_work(dcp); + } + } + /* + * hw.s2r_park, a Type-C output: for a deep sleep its Type-C work stops before the sleep + * starts, so that it does not run while the USB controllers take the Type-C PHYs down in + * their own suspend, which has no set order against this device's. PM_SUSPEND_PREPARE + * has no target state yet: a deep sleep is "mem" when s2idle is not the default. + */ + if (action == PM_SUSPEND_PREPARE && dcp->hw.s2r_park && dcp_is_typec_output(dcp) && + !pm_suspend_default_s2idle() && !dcp_takeover_was_aborted(dcp) && + !dcp->s2r_typec_off) { + dcp_disable_typec_work(dcp, false); + dcp->s2r_typec_off = true; } /* * A J714s external display processor that has crashed cannot take its sleep calls, and @@ -12752,7 +12921,7 @@ static int dcp_s2r_pm_register(struct apple_dcp *dcp) { int ret; - if (!dcp_s2r_ext_capable(dcp) && !dcp_j714s_ext(dcp->dev)) + if (!dcp_s2r_ext_capable(dcp) && !dcp_j714s_ext(dcp->dev) && !dcp->hw.s2r_park) return 0; dcp->s2r_pm_nb.notifier_call = dcp_s2r_pm_notify; ret = register_pm_notifier(&dcp->s2r_pm_nb); @@ -13218,6 +13387,7 @@ static int dcp_platform_suspend(struct device *dev) struct apple_dcp *dcp = dev_get_drvdata(dev); dcp->sleep_fw_runs = false; + dcp->s2r_park_due = false; /* * The display subsystem's suspend already stopped this DCP and lowered its power words: * its registers sit behind a powered-off block, and a read there stalls the CPU. @@ -13423,7 +13593,11 @@ static int dcp_platform_suspend(struct device *dev) * connected, and resume powers the CRTC back up through dcp_poweron() * as after DPMS off. */ - dcp_disable_typec_work(dcp, false); + /* Stopped already for a deep sleep, see dcp_s2r_pm_notify() */ + if (dcp->s2r_typec_off) + dcp->s2r_typec_off = false; + else + 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); @@ -13432,13 +13606,38 @@ static int dcp_platform_suspend(struct device *dev) av_service_disconnect(dcp); if (dcp->hdmi_hpd_irq) { + int ret = 0; + + /* A display still being connected after the last wake first. */ + flush_work(&dcp->s2r_hdmi_link_work); disable_irq(dcp->hdmi_hpd_irq); /* - * The firmware runs through this sleep, so the HDMI output - * keeps its link as through DPMS off (see dcp_poweroff()), and - * resume lights it again through dcp_poweron(). Only a display - * that is gone is reported and released here. Releasing one - * that stays attached reports it unplugged, and nothing + * hw.s2r_park: a firmware parked for a deep sleep drives no link, + * so an attached display is released and its converter powered + * down (dcp_hdmi_sleep_release()); resume connects it again. A + * link that cannot be released refuses the sleep here, before + * anything is parked or powered down. The firmware may have + * dropped the display on the way (dcp_hdmi_link_release()): it is + * connected again as after a wake, and kept as it is otherwise. + */ + if (dcp_s2r_park_selected(dcp)) + ret = dcp_hdmi_sleep_release(dcp); + if (ret < 0) { + dev_err(dev, "HDMI link not released (%d), refusing deep sleep\n", ret); + enable_irq(dcp->hdmi_hpd_irq); + if (dcp->avep) + av_service_connect(dcp); + dcp_enable_typec_work(dcp); + queue_work(system_dfl_wq, &dcp->s2r_hdmi_link_work); + return -EBUSY; + } + dcp->s2r_hdmi_released = ret > 0; + /* + * Otherwise the firmware runs through this sleep, so the HDMI + * output keeps its link as through DPMS off (see dcp_poweroff()), + * and resume lights it again through dcp_poweron(). Only a + * display that is gone is reported and released here. Releasing + * one that stays attached reports it unplugged, and nothing * connects it again after the wake: its HPD stays high, so no * edge comes, and a CRTC userspace turned off for the unplug * never runs dcp_poweron(). A T6030 native output's resume sets @@ -13454,10 +13653,47 @@ static int dcp_platform_suspend(struct device *dev) */ dcp->sleep_fw_runs = true; device_set_wakeup_path(dev); - dcp_sleep_hold_phys(dcp); + /* + * A firmware parked for the sleep drives no PHY, so the PHY's power domain is left to + * genpd: off before the commit, on again after its parents at the wake. Held on, it + * would keep its state while the commit lowers those parents under it. The crossbar of + * a Type-C display's route shares that domain and wakes with its output lost, while the + * mux core still holds the selection: take the output down while it has power, and + * resume selects it again before the link connects, as for an s2r_ext DCP. + */ + dcp->s2r_park_due = dcp_s2r_park_selected(dcp); + dcp->s2r_phys_unheld = dcp->s2r_park_due; + if (!dcp->s2r_park_due) + dcp_sleep_hold_phys(dcp); + else + dcp_typec_route_park(dcp); /* Last: the steps above still talk to the coprocessor. */ dcp_hold_for_sleep(dcp); - dcp_commit_stop_arm(dcp); + /* hw.s2r_park: parked in the late suspend and restarted warm, never stopped cold. */ + if (!dcp->hw.s2r_park) + dcp_commit_stop_arm(dcp); + + return 0; +} + +/* + * hw.s2r_park: a parked firmware only starts again once its block lost power. So it is parked + * after every device's suspend: when one of those refuses the sleep, nothing has stopped it. + * A firmware that could not be parked refuses the sleep: the sleep driver checks only the + * internal DCP's CPU before the commit, and the display blocks go down under a running one. + */ +static int dcp_platform_suspend_late(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + int ret = 0; + + if (dcp->s2r_park_due) + ret = dcp_s2r_park(dcp); + dcp->s2r_park_due = false; + if (ret) { + dev_err(dev, "display firmware not parked (%d), refusing deep sleep\n", ret); + return -EBUSY; + } return 0; } @@ -13468,6 +13704,33 @@ void dcp_hdmi_disconnect(struct apple_dcp *dcp) dcp_dptx_disconnect(dcp, 0); } +/* + * As dcp_hdmi_disconnect(), but reported gone only once the firmware has released the link. + * In a release the firmware reports the display unplugged and sets the PHY rate to 0 + * (SET_LINK_RATE) before it answers: a call that timed out after both has released the link, + * and only its answer is late (AFK frees it then). A release that timed out is still asked + * for and goes on in the firmware, so the port takes a connect again either way. + * Returns 0 once released. + */ +int dcp_hdmi_link_release(struct apple_dcp *dcp) +{ + struct dptx_port *port = &dcp->dptxport[0]; + u32 unplugs = dcp_typec_fw_unplugs(dcp); + int ret = dcp_dptx_disconnect(dcp, 0); + + if (ret == -ETIMEDOUT) { + scoped_guard(mutex, &dcp->hpd_mutex) + port->connected = false; + if (dcp_typec_fw_unplugs(dcp) != unplugs && !READ_ONCE(port->link_rate)) { + dev_info(dcp->dev, "HDMI: link down before the release was answered\n"); + ret = 0; + } + } + if (!ret) + disconnected_hpd_event(dcp->connector); + return ret; +} + static int dcp_platform_resume(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); @@ -13516,6 +13779,10 @@ static int dcp_platform_resume(struct device *dev) if (READ_ONCE(dcp->ext_dead)) return 0; + /* A released display's converter first: it starts up while the firmware restarts. */ + if (dcp->s2r_hdmi_released && dcp->dp2hdmi_pwren) + gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 1); + dcp_s2r_unpark(dcp); dcp->link_recovery_tries = 0; if (dcp_is_ext26(dcp)) { if (!(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & APPLE_DCP_COPROC_CPU_CONTROL_RUN) || @@ -13533,12 +13800,27 @@ static int dcp_platform_resume(struct device *dev) dcp_release_after_sleep(dcp); iomfb_v14_7_backlight_resume(dcp); /* Its crossbar output, parked by the suspend, before the link connects again. */ - if (dcp_is_external_h17p(dcp)) + if (dcp_is_external_h17p(dcp) || dcp->s2r_phys_unheld) dcp_typec_route_unpark(dcp); dcp_enable_typec_work(dcp); /* The HDMI output's PHY and crossbar may have lost their setup in sleep. */ if (dcp->external_native) dcp_fabric_hdmi_reinit(dcp, "after system sleep"); + /* + * hw.s2r_park: the PHYs were not held, so a deep sleep took the fixed HDMI output's PHY + * and crossbar down with their power domain, and the crossbar driver keeps no state + * across it. Set them up again, a display attached or not, as main does after a deep + * sleep for an s2r_ext DCP. Also after a sleep given up: there it only repeats the + * setup. + */ + else if (dcp->s2r_phys_unheld) + dcp_fabric_hdmi_reinit(dcp, "after deep sleep"); + dcp->s2r_phys_unheld = false; + /* The display released for the sleep, on the output just set up; not in the resume. */ + if (dcp->s2r_hdmi_released) { + dcp->s2r_hdmi_released = false; + queue_work(system_dfl_wq, &dcp->s2r_hdmi_link_work); + } /* Before the HPD IRQ comes back: an edge from now on is replayed. */ if (dcp->hdmi_hpd_irq) dcp_hdmi_unplugged_in_sleep(dcp); @@ -13572,6 +13854,7 @@ static const struct dev_pm_ops dcp_platform_pm_ops = { .prepare = pm_sleep_ptr(dcp_platform_prepare), .complete = pm_sleep_ptr(dcp_platform_complete), .suspend = pm_sleep_ptr(dcp_platform_suspend), + .suspend_late = pm_sleep_ptr(dcp_platform_suspend_late), .resume = pm_sleep_ptr(dcp_platform_resume), .freeze = pm_sleep_ptr(dcp_platform_freeze), .thaw = pm_sleep_ptr(dcp_platform_resume), @@ -13691,6 +13974,22 @@ static const struct apple_dcp_hw_data apple_dcp_hw_dcp = { .num_dptx_ports = 0, }; +/* T6000's internal DCP: parked for a deep sleep, see dcp_s2r_park() */ +static const struct apple_dcp_hw_data apple_dcp_hw_t6000 = { + .num_dptx_ports = 0, + .s2r_park = true, +}; + +/* + * T6000's external DCPs: the generic apple,dcpext entry they matched before, and a running + * firmware parked for a deep sleep as the internal one's + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t6000_dcpext = { + .external_processor = true, + .num_dptx_ports = 2, + .s2r_park = true, +}; + static const struct apple_dcp_hw_data apple_dcp_hw_t6030 = { .iboot_handoff = "apple,t6030-handoff", .num_dptx_ports = 1, @@ -13851,6 +14150,8 @@ static const struct of_device_id of_match[] = { { .compatible = "apple,t6050-dcpext", .data = &apple_dcp_hw_t6050_dcpext }, { .compatible = "apple,t6020-dcp", .data = &apple_dcp_hw_t6020, }, { .compatible = "apple,t6020-dcpext", .data = &apple_dcp_hw_t6020_dcpext, }, + { .compatible = "apple,t6000-dcp", .data = &apple_dcp_hw_t6000, }, + { .compatible = "apple,t6000-dcpext", .data = &apple_dcp_hw_t6000_dcpext, }, { .compatible = "apple,t8103-dcp", .data = &apple_dcp_hw_t8103, }, { .compatible = "apple,t8103-dcpext", .data = &apple_dcp_hw_t8103_dcpext, }, { .compatible = "apple,t8112-dcp", .data = &apple_dcp_hw_t8112, }, diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index c68f55fb41835..cad9c4aa7ec1a 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -213,8 +213,10 @@ bool apple_t8122_25g83_board(void); void dcp_typec_hybrid_first_dt(void); void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp); void dcp_hdmi_suspend(struct apple_dcp *dcp); +int dcp_hdmi_sleep_release(struct apple_dcp *dcp); void dcp_hdmi_unplugged_in_sleep(struct apple_dcp *dcp); void dcp_hdmi_disconnect(struct apple_dcp *dcp); +int dcp_hdmi_link_release(struct apple_dcp *dcp); void dcp_fabric_hybrid_kick(struct apple_dcp *dcp, unsigned int delay_ms); void dcp_hdmi_yield_link(struct apple_dcp *dcp); void dcp_link_recovery_schedule(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 36dca5e1e1463..443b5dedaa83b 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -2682,6 +2682,48 @@ static void dcp_on_set_parameter(struct apple_dcp *dcp, void *out, void *cookie) } #endif +#if DCP_FW_VER == DCP_FW_VERSION(13, 3, 0) +DCP_THUNK_IN(dcp_s2r_link_sleep_call, dcpep_unnamed_500, u32); + +static void dcp_s2r_link_sleep_done(struct apple_dcp *dcp, void *out, void *cookie) +{ + struct dcp_wait_cookie *wait = cookie; + + complete(&wait->done); + kref_put(&wait->refcount, release_wait_cookie); +} + +/* + * The display firmware's power manager call A500 on 13.x firmware: drains the AP link and + * marks it inactive, so that the firmware acknowledges an AP power IDLE; AP power ON after the + * wake activates the link again. Its argument is a teardown (which also unregisters the AP + * power callbacks), not wanted for a sleep. + */ +int DCP_FW_NAME(iomfb_s2r_link_sleep)(struct apple_dcp *dcp) +{ + struct dcp_wait_cookie *cookie; + unsigned long left; + u32 teardown = 0; + + if (!dcp_methods[dcpep_unnamed_500].tag[0]) + return -EOPNOTSUPP; + cookie = kzalloc_obj(*cookie); + if (!cookie) + return -ENOMEM; + init_completion(&cookie->done); + kref_init(&cookie->refcount); + /* increase refcount to ensure the receiver has a reference */ + kref_get(&cookie->refcount); + + dcp_s2r_link_sleep_call(dcp, false, &teardown, dcp_s2r_link_sleep_done, cookie); + + left = wait_for_completion_timeout(&cookie->done, msecs_to_jiffies(2000)); + kref_put(&cookie->refcount, release_wait_cookie); + + return left ? 0 : -ETIMEDOUT; +} +#endif + void DCP_FW_NAME(iomfb_poweron)(struct apple_dcp *dcp) { struct dcp_wait_cookie *cookie; @@ -2755,6 +2797,9 @@ void DCP_FW_NAME(iomfb_poweron)(struct apple_dcp *dcp) dcp_backlight_desktop_power(dcp, true); #endif + /* Until a poweron completes again, a firmware sleep is refused (dcp_platform_prepare()). */ + if (ret >= 0) + WRITE_ONCE(dcp->poweron_timed_out, ret == 0); if (ret == 0) { dev_warn(dcp->dev, "wait for power timed out, connector will be broken\n"); } else if (ret > 0) { diff --git a/drivers/gpu/drm/apple/iomfb_template.h b/drivers/gpu/drm/apple/iomfb_template.h index 2cd64bffc3863..2363c689e46a9 100644 --- a/drivers/gpu/drm/apple/iomfb_template.h +++ b/drivers/gpu/drm/apple/iomfb_template.h @@ -398,6 +398,9 @@ void DCP_FW_NAME(iomfb_shutdown)(struct apple_dcp *dcp); int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp); int DCP_FW_NAME(iomfb_system_power)(struct apple_dcp *dcp, bool on); #endif +#if DCP_FW_VER == DCP_FW_VERSION(13, 3, 0) +int DCP_FW_NAME(iomfb_s2r_link_sleep)(struct apple_dcp *dcp); +#endif #if DCP_FW_H17(DCP_FW_VER) int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp); int DCP_FW_NAME(iomfb_s2r_power)(struct apple_dcp *dcp, bool on, bool named_calls, bool oob); diff --git a/drivers/gpu/drm/apple/iomfb_v13_3.c b/drivers/gpu/drm/apple/iomfb_v13_3.c index 3521abccf038e..15c16517f5df4 100644 --- a/drivers/gpu/drm/apple/iomfb_v13_3.c +++ b/drivers/gpu/drm/apple/iomfb_v13_3.c @@ -39,6 +39,7 @@ static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { IOMFB_METHOD("A466", dcpep_flush_supports_power), IOMFB_METHOD("A467", iomfbep_abort_swaps_dcp), IOMFB_METHOD("A472", dcpep_set_power_state), + IOMFB_METHOD("A500", dcpep_unnamed_500), }; #define DCP_FW v13_3 diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index ddaa10e627c47..971ff1d61110e 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -50,6 +50,9 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { _reg: drm::Registration<'bound, AsahiDrmDriver>, /// The G17 GPU, whose coprocessors must be stopped when the driver is unbound. g17: Option>, + /// A GPU whose firmware is stopped at the commit of a sleep that cuts the SoC's power, as its + /// hardware data says ([`hw::HwConfig::fw_park_for_sleep`]). + legacy: Option>, #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) g16: Option>, m3: Option, @@ -288,12 +291,77 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i } match data.g17.as_ref() { Some(gpu) => kernel::error::from_result(|| gpu.sleep_prepare().map(|_| 0)), + // Stopped at the sleep's commit: see `sleep_park_at_prepare`. + None if data.legacy.is_some() => 0, None => EBUSY.to_errno(), } } +/// For a sleep that cuts the SoC's power, has the firmware of a GPU whose hardware data asks for +/// it stopped at the sleep's commit, past its last refusal, registered from the sleep's .prepare. +/// The firmware runs until then, and its power domain stays on through the noirq phase, so a +/// sleep given up before the commit leaves it running. +/// +/// # Safety +/// +/// `dev` must be the GPU device registered with `asahi_sleep_fw_park_at_prepare`. +unsafe extern "C" fn sleep_park_at_prepare(dev: *mut bindings::device) { + // SAFETY: Reads a global flag word. + if !unsafe { bindings::pm_suspend_via_firmware() } { + return; + } + // SAFETY: Registered in probe, unregistered with the binding: `dev` is bound, and no sleep + // runs while a probe does, so its probe has completed. + if unsafe { bindings::dev_get_drvdata(dev) }.is_null() { + return; + } + // SAFETY: As above. + let data = unsafe { sleep_data(dev) }; + if let Some(mgr) = data.legacy.as_ref().and_then(|gpu| gpu.manager()) { + // Without a stop registered, the GPU's suspend_noirq gives the sleep up. + let _ = mgr.sleep_park(dev); + } +} + +/// Starts a firmware stopped at the commit [`sleep_park_at_prepare`] armed again, from the sleep's +/// .finish, which follows every .prepare, given up or not: after the PMP's restart and the AOP's +/// wake notice, and before the SMC is told of the wake. After a sleep given up before its commit +/// the firmware is still running, and only the stop is unregistered. +/// +/// # Safety +/// +/// `dev` must be the GPU device registered with `asahi_sleep_fw_park_at_prepare`. +unsafe extern "C" fn sleep_unpark_at_finish(dev: *mut bindings::device) { + // SAFETY: Registered in probe, unregistered with the binding: `dev` is bound, and no sleep + // runs while a probe does, so its probe has completed. + if unsafe { bindings::dev_get_drvdata(dev) }.is_null() { + return; + } + // SAFETY: As above. + let data = unsafe { sleep_data(dev) }; + if let Some(mgr) = data.legacy.as_ref().and_then(|gpu| gpu.manager()) { + mgr.sleep_unpark(dev); + } +} + +/// The same as [`sleep_unpark_at_finish`], which already ran for every sleep that armed the +/// stop: then it finds nothing to do. +unsafe extern "C" fn sleep_resume(dev: *mut bindings::device) -> core::ffi::c_int { + // SAFETY: Called by the PM core. + let data = unsafe { sleep_data(dev) }; + if let Some(mgr) = data.legacy.as_ref().and_then(|gpu| gpu.manager()) { + mgr.sleep_unpark(dev); + } + 0 +} + extern "C" { fn asahi_sleep_pd_init(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_sleep_fw_park_at_prepare( + dev: *mut core::ffi::c_void, + park: Option, + unpark: Option, + ) -> core::ffi::c_int; fn asahi_sleep_pd_suspend_noirq(dev: *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_sleep_pd_suspend_noirq_hold( dev: *mut core::ffi::c_void, @@ -368,6 +436,7 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_prepare), complete: Some(sleep_complete), + resume: Some(sleep_resume), suspend_noirq: Some(sleep_suspend_noirq_driver), resume_noirq: Some(sleep_resume_noirq), // SAFETY: All-zero is the absence of every other callback. @@ -527,6 +596,17 @@ impl platform::Driver for AsahiPlatformDriver { } }; gpu.init()?; + let legacy = cfg.fw_park_for_sleep.then(|| gpu.clone()); + if legacy.is_some() { + // SAFETY: `pdev` is being probed, and `sleep_pd_init` gave it the state this takes. + kernel::error::to_result(unsafe { + asahi_sleep_fw_park_at_prepare( + pdev.as_ref().as_raw().cast(), + Some(sleep_park_at_prepare), + Some(sleep_unpark_at_finish), + ) + })?; + } let stats = gpu.stats_snapshot(); let debug_stats = gpu.raw_stats_snapshot(); @@ -558,6 +638,7 @@ impl platform::Driver for AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -603,6 +684,7 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, m3: None, @@ -639,6 +721,7 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -683,6 +766,7 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, m3: Some(backend), #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -766,6 +850,7 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: Some(gpu), + legacy: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -815,6 +900,7 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -857,6 +943,7 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -915,6 +1002,7 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 8da8a428ad72a..00c128b1260e9 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -610,6 +610,13 @@ pub(crate) trait GpuManager: Send + Sync { /// Release the queue structures of invalidated contexts after firmware reports that all data /// masters are powered off. fn fw_power_off(&self); + /// Have the firmware stopped at the commit of a sleep that cuts the SoC's power, from the + /// sleep's .prepare: see [`hw::HwConfig::fw_park_for_sleep`]. `dev` is the GPU's platform + /// device. + fn sleep_park(&self, dev: *mut kernel::bindings::device) -> Result; + /// Start the firmware stopped at the commit again, from the sleep's .finish; + /// the GPU's resume calls it again and finds nothing to do. + fn sleep_unpark(&self, dev: *mut kernel::bindings::device); } /// Private generic trait for functions that don't need to escape this module. @@ -1681,6 +1688,10 @@ impl GpuManager::ver { extern "C" { fn asahi_min_cpu_capacity() -> u32; + fn asahi_sleep_fw_park(dev: *mut core::ffi::c_void, rtk: *mut core::ffi::c_void) + -> core::ffi::c_int; + fn asahi_sleep_fw_unpark(dev: *mut core::ffi::c_void, rtk: *mut core::ffi::c_void) + -> core::ffi::c_int; } #[versions(AGX)] @@ -2221,6 +2232,24 @@ impl GpuManager for GpuManager::ver { } } + fn sleep_park(&self, dev: *mut kernel::bindings::device) -> Result { + let mut guard = self.rtkit.lock(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + // SAFETY: `dev` is the bound GPU platform device and `rtk` its live RTKit, set once at + // probe and kept for the binding, so it outlives the sleep's commit, which uses it with + // every other CPU stopped and interrupts off. + kernel::error::to_result(unsafe { asahi_sleep_fw_park(dev.cast(), rtk.as_raw().cast()) }) + } + + fn sleep_unpark(&self, dev: *mut kernel::bindings::device) { + let mut guard = self.rtkit.lock(); + if let Some(rtk) = guard.as_mut().as_pin_mut() { + // SAFETY: As in `sleep_park`. The helper logs its own failure: the firmware then + // stays stopped until the next sleep that cuts the power. + unsafe { asahi_sleep_fw_unpark(dev.cast(), rtk.as_raw().cast()) }; + } + } + fn fw_power_off(&self) { let mut released = KVec::new(); core::mem::swap(&mut *self.powered_contexts.lock(), &mut released); diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index aee820abaef56..d38e1145a71cf 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -342,6 +342,9 @@ pub(crate) struct HwConfig { /// What firmware 27.2 needs, on the SoCs the driver starts it on. #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) v27_2: Option, + /// For a sleep that cuts the SoC's power, the firmware is stopped at the sleep's commit and + /// started again at its .finish, its RTKit kept: T6000 (G13S). + pub(crate) fw_park_for_sleep: bool, } /// Dynamic (fetched from hardware/DT) configuration. diff --git a/drivers/gpu/drm/asahi/hw/t600x.rs b/drivers/gpu/drm/asahi/hw/t600x.rs index 702474e47b1d7..32f147f6bdd49 100644 --- a/drivers/gpu/drm/asahi/hw/t600x.rs +++ b/drivers/gpu/drm/asahi/hw/t600x.rs @@ -134,6 +134,7 @@ pub(crate) const HWCONFIG_T6002: super::HwConfig = HwConfig { sram_size: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] v27_2: None, + fw_park_for_sleep: false, }; pub(crate) const HWCONFIG_T6001: super::HwConfig = HwConfig { @@ -160,5 +161,6 @@ pub(crate) const HWCONFIG_T6000: super::HwConfig = HwConfig { fast_sensor_mask_alt: [0x9090, 0], fast_die0_sensor_present: 0x03, io_mappings: &iomaps(4, false), + fw_park_for_sleep: true, ..HWCONFIG_T6001 }; diff --git a/drivers/gpu/drm/asahi/hw/t602x.rs b/drivers/gpu/drm/asahi/hw/t602x.rs index 9047e8c609846..069737a4f4af8 100644 --- a/drivers/gpu/drm/asahi/hw/t602x.rs +++ b/drivers/gpu/drm/asahi/hw/t602x.rs @@ -147,6 +147,7 @@ pub(crate) const HWCONFIG_T6022: super::HwConfig = HwConfig { sram_size: Some(0x20000), #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] v27_2: None, + fw_park_for_sleep: false, }; pub(crate) const HWCONFIG_T6021: super::HwConfig = HwConfig { diff --git a/drivers/gpu/drm/asahi/hw/t8103.rs b/drivers/gpu/drm/asahi/hw/t8103.rs index 62771231e57c0..a4e93cff2291d 100644 --- a/drivers/gpu/drm/asahi/hw/t8103.rs +++ b/drivers/gpu/drm/asahi/hw/t8103.rs @@ -96,6 +96,7 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { writable: WRITABLE_V27_2, active_mccs: None, }), + fw_park_for_sleep: false, }; #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] diff --git a/drivers/gpu/drm/asahi/hw/t8112.rs b/drivers/gpu/drm/asahi/hw/t8112.rs index 0f99285abc4f6..a32c40dc032af 100644 --- a/drivers/gpu/drm/asahi/hw/t8112.rs +++ b/drivers/gpu/drm/asahi/hw/t8112.rs @@ -109,6 +109,7 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { writable: WRITABLE_V27_2, active_mccs: None, }), + fw_park_for_sleep: false, }; #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] diff --git a/drivers/gpu/drm/asahi/sleep_pd.c b/drivers/gpu/drm/asahi/sleep_pd.c index 059269f84c847..966f77ea74954 100644 --- a/drivers/gpu/drm/asahi/sleep_pd.c +++ b/drivers/gpu/drm/asahi/sleep_pd.c @@ -14,23 +14,54 @@ * Register a temporary GENPD_NOTIFY_PRE_OFF veto notifier on the GPU device's * own genpd for the noirq sleep window, matching pcie-apple's consumer-side * hold without changing any other power domain. + * + * Also stop the GPU firmware for a deep sleep, on the GPUs whose driver has no + * firmware sleep of its own (T6000), at the sleep's commit, and start it again from the + * sleep's .finish: see asahi_sleep_fw_park_at_prepare(). */ #include #include #include #include +#include #include #include +#include #include +#include +#include #include #include #include "sleep_pd.h" +/* The ASC's CPU control word, and its status word after it. */ +#define ASAHI_ASC_CPU_CONTROL 0x44 +#define ASAHI_ASC_CPU_SIZE 8 +#define ASAHI_ASC_CPU_RUN BIT(4) +/* The AP's ON after the endpoints are started again, as for the display coprocessors */ +#define ASAHI_FW_AP_ON_MS 2000 + struct asahi_sleep_pd { struct notifier_block nb; bool active; + void __iomem *cpu_control; + /* Its stop registered for this sleep's commit, with the RTKit it stops */ + struct apple_rtkit *rtk; + bool armed; + /* The commit ran that stop, and what the firmware answered to its idle */ + bool commit_ran; + int commit_ret; + /* It did not start again: only the next deep sleep's power cut brings it back. */ + bool stopped; + /* Parks it from the sleep's .prepare: see asahi_sleep_fw_park_at_prepare() */ + struct notifier_block prepare_nb; + struct device *dev; + void (*park)(struct device *dev); + /* And starts it again from the sleep's .finish */ + struct notifier_block finish_nb; + void (*unpark)(struct device *dev); }; /* IRQ-safe domains invoke power notifiers in atomic context. */ @@ -46,10 +77,20 @@ static void asahi_sleep_pd_release(struct device *dev, void *res) { struct asahi_sleep_pd *hold = res; + if (hold->park) { + apple_sleep_prepare_notifier_unregister(&hold->prepare_nb); + apple_sleep_finish_notifier_unregister(&hold->finish_nb); + } + if (hold->armed) { + apple_sleep_coproc_unregister(dev); + hold->armed = false; + } if (hold->active) { dev_pm_genpd_remove_notifier(dev); hold->active = false; } + if (hold->cpu_control) + iounmap(hold->cpu_control); } int asahi_sleep_pd_init(struct device *dev) @@ -70,6 +111,16 @@ int asahi_sleep_pd_suspend_noirq_hold(struct device *dev, bool hold_firmware) struct asahi_sleep_pd *hold; int ret; + hold = devres_find(dev, asahi_sleep_pd_release, NULL, NULL); + /* + * A GPU whose firmware the sleep's commit stops: it runs until then, so its domain must + * not lose power before. Without a stop registered, the sleep must not go on. + */ + if (pm_suspend_via_firmware() && hold && hold->park) { + if (!hold->armed) + return -EBUSY; + hold_firmware = true; + } if (pm_suspend_via_firmware() && !hold_firmware) return 0; @@ -96,7 +147,6 @@ int asahi_sleep_pd_suspend_noirq_hold(struct device *dev, bool hold_firmware) if (!dev_pm_genpd_is_on(dev)) return 0; - hold = devres_find(dev, asahi_sleep_pd_release, NULL, NULL); if (WARN_ON_ONCE(!hold)) return -EBUSY; @@ -120,6 +170,218 @@ int asahi_sleep_pd_suspend_noirq(struct device *dev) return asahi_sleep_pd_suspend_noirq_hold(dev, false); } +static struct asahi_sleep_pd *asahi_sleep_pd_get(struct device *dev) +{ + return devres_find(dev, asahi_sleep_pd_release, NULL, NULL); +} + +static void __iomem *asahi_sleep_cpu_control(struct device *dev, struct asahi_sleep_pd *hold) +{ + struct resource *res; + + if (hold->cpu_control) + return hold->cpu_control; + res = platform_get_resource_byname(to_platform_device(dev), IORESOURCE_MEM, "asc"); + if (!res || resource_size(res) < ASAHI_ASC_CPU_CONTROL + ASAHI_ASC_CPU_SIZE) + return NULL; + /* As the bus asks: a posted access to the ASC ends in an SError on these SoCs */ + if (res->flags & IORESOURCE_MEM_NONPOSTED) + hold->cpu_control = ioremap_np(res->start + ASAHI_ASC_CPU_CONTROL, + ASAHI_ASC_CPU_SIZE); + else + hold->cpu_control = ioremap(res->start + ASAHI_ASC_CPU_CONTROL, ASAHI_ASC_CPU_SIZE); + return hold->cpu_control; +} + +/* + * The sleep's commit, past its last refusal: interrupts off, the other CPUs stopped, nothing + * else running. AP idle and IOP idle over the polled mailbox, as at a park, then receiving off + * and RUN cleared. The mailbox is detached at .finish, after the wake, as nothing here may + * sleep. One that did not start again after an earlier sleep has nothing to be told and is + * stopped as it is. A failed idle can't refuse the sleep any more: the firmware is stopped all + * the same and is not started again after the wake. + */ +static int asahi_sleep_fw_commit_stop(void *data) +{ + struct asahi_sleep_pd *hold = data; + unsigned int us = 0; + int ret = 0; + + hold->commit_ran = true; + if (!hold->stopped) { + apple_rtkit_polled_begin(hold->rtk); + ret = apple_rtkit_polled_ap_idle(hold->rtk, &us); + if (!ret) + ret = apple_rtkit_polled_iop_idle(hold->rtk, &us); + apple_rtkit_polled_end(hold->rtk); + } + apple_rtkit_mailbox_recv_off(hold->rtk); + writel_relaxed(readl_relaxed(hold->cpu_control) & ~ASAHI_ASC_CPU_RUN, hold->cpu_control); + hold->commit_ret = ret; + return ret; +} + +/** + * asahi_sleep_fw_park() - Have the GPU firmware stopped at the deep sleep's commit + * @dev: the GPU + * @rtk: its RTKit + * + * From the sleep's .prepare. The firmware keeps running, and its power domain stays on through + * the noirq phase. Its stop is registered with the sleep driver as one that runs first at the + * commit, after the last refusal (apple_sleep_coproc_register_first()), and the GPU's port goes + * down only after it. So a sleep given up anywhere before the commit, in a dry run too, leaves + * the firmware running and has nothing to start again. + * + * Return: 0, or the error with which nothing is registered: the GPU's suspend_noirq then gives + * the sleep up, before its domain could lose power under the running firmware. + */ +int asahi_sleep_fw_park(struct device *dev, struct apple_rtkit *rtk) +{ + struct asahi_sleep_pd *hold = asahi_sleep_pd_get(dev); + int ret; + + if (!hold) + return -ENODEV; + if (hold->armed) + return 0; + if (!asahi_sleep_cpu_control(dev, hold)) + return -ENODEV; + hold->rtk = rtk; + hold->commit_ran = false; + hold->commit_ret = 0; + ret = apple_sleep_coproc_register_first(dev, asahi_sleep_fw_commit_stop, hold); + if (ret) { + dev_err(dev, "GPU firmware can't be stopped at the sleep's commit: %d\n", ret); + return ret; + } + apple_sleep_coproc_set_ready(dev, true); + hold->armed = true; + return 0; +} + +static int asahi_sleep_prepare_notify(struct notifier_block *nb, unsigned long action, void *data) +{ + struct asahi_sleep_pd *hold = container_of(nb, struct asahi_sleep_pd, prepare_nb); + + hold->park(hold->dev); + return NOTIFY_OK; +} + +static int asahi_sleep_finish_notify(struct notifier_block *nb, unsigned long action, void *data) +{ + struct asahi_sleep_pd *hold = container_of(nb, struct asahi_sleep_pd, finish_nb); + + hold->unpark(hold->dev); + return NOTIFY_OK; +} + +/** + * asahi_sleep_fw_park_at_prepare() - Have the GPU firmware stopped at the sleep's commit + * @dev: the GPU, being probed + * @park: registers the stop at the sleep's .prepare, through asahi_sleep_fw_park() with its + * RTKit + * @unpark: starts it again, or leaves it running, through asahi_sleep_fw_unpark() with its RTKit + * + * The sleep's .finish, which follows every .prepare, given up or not, starts a firmware stopped + * at the commit again: after the PMP's restart and the AOP's wake notice, before the SMC is told + * of the wake. Unregistered with the GPU's binding. + * + * Return: 0 or a negative error. + */ +int asahi_sleep_fw_park_at_prepare(struct device *dev, void (*park)(struct device *dev), + void (*unpark)(struct device *dev)) +{ + struct asahi_sleep_pd *hold = asahi_sleep_pd_get(dev); + int ret; + + if (!hold) + return -ENODEV; + if (hold->park) + return 0; + hold->dev = dev; + hold->prepare_nb.notifier_call = asahi_sleep_prepare_notify; + hold->finish_nb.notifier_call = asahi_sleep_finish_notify; + hold->park = park; + hold->unpark = unpark; + ret = apple_sleep_finish_notifier_register(&hold->finish_nb); + if (!ret) { + ret = apple_sleep_prepare_notifier_register(&hold->prepare_nb); + if (ret) + apple_sleep_finish_notifier_unregister(&hold->finish_nb); + } + if (ret) + hold->park = NULL; + return ret; +} + +/* + * After the power cut, with the CPU still stopped: the mailbox and handshake afresh with the + * buffers kept, RUN, the IOP's INIT and endpoint map, every endpoint started again, then the + * AP's ON. + */ +static int asahi_sleep_fw_restart(struct apple_rtkit *rtk, void __iomem *ctl) +{ + u32 control = readl_relaxed(ctl); + int ret; + + ret = apple_rtkit_reinit_keep(rtk); + if (ret) + return ret; + writel_relaxed(control | ASAHI_ASC_CPU_RUN, ctl); + ret = apple_rtkit_wake_keep_ap(rtk); + if (ret) + return ret; + ret = apple_rtkit_restart_started_eps(rtk); + if (ret) + return ret; + return apple_rtkit_ap_power_timeout(rtk, true, ASAHI_FW_AP_ON_MS); +} + +/** + * asahi_sleep_fw_unpark() - Start the GPU firmware stopped at the sleep's commit again + * @dev: the GPU + * @rtk: its RTKit + * + * From the sleep's .finish, which follows every sleep that reached its .prepare, given up or + * not, and before the SMC is told of the wake. The stop is unregistered. A sleep given up before + * its commit never ran it: the firmware is running, and nothing is done. After the commit only a + * real sleep comes back here (else the machine restarts): the mailbox is detached and the + * firmware started again with its buffers kept. The GPU's .resume calls it again, and then finds + * nothing to do. + * + * Return: 0, or the error with which the firmware stays stopped. + */ +int asahi_sleep_fw_unpark(struct device *dev, struct apple_rtkit *rtk) +{ + struct asahi_sleep_pd *hold = asahi_sleep_pd_get(dev); + int ret; + + if (!hold || !hold->armed) + return 0; + hold->armed = false; + apple_sleep_coproc_unregister(dev); + if (!hold->commit_ran) { + dev_info(dev, "sleep ended before its commit: GPU firmware left running\n"); + return 0; + } + hold->commit_ran = false; + apple_rtkit_detach_keep(rtk); + if (hold->commit_ret) { + dev_err(dev, "GPU firmware did not idle at the sleep's commit: %d; the next deep sleep starts it\n", + hold->commit_ret); + hold->stopped = true; + return hold->commit_ret; + } + ret = asahi_sleep_fw_restart(rtk, hold->cpu_control); + hold->stopped = ret; + if (ret) + dev_err(dev, "GPU firmware did not start again: %d; the next deep sleep starts it\n", + ret); + else + dev_info(dev, "GPU firmware stopped at the sleep's commit and started again\n"); + return ret; +} + int asahi_sleep_pd_resume_noirq(struct device *dev) { struct asahi_sleep_pd *hold; diff --git a/drivers/gpu/drm/asahi/sleep_pd.h b/drivers/gpu/drm/asahi/sleep_pd.h index f9ce7f989d069..fdd22ff12ac50 100644 --- a/drivers/gpu/drm/asahi/sleep_pd.h +++ b/drivers/gpu/drm/asahi/sleep_pd.h @@ -5,11 +5,16 @@ #include +struct apple_rtkit; struct device; int asahi_sleep_pd_init(struct device *dev); int asahi_sleep_pd_suspend_noirq(struct device *dev); int asahi_sleep_pd_suspend_noirq_hold(struct device *dev, bool hold_firmware); int asahi_sleep_pd_resume_noirq(struct device *dev); +int asahi_sleep_fw_park(struct device *dev, struct apple_rtkit *rtk); +int asahi_sleep_fw_park_at_prepare(struct device *dev, void (*park)(struct device *dev), + void (*unpark)(struct device *dev)); +int asahi_sleep_fw_unpark(struct device *dev, struct apple_rtkit *rtk); #endif diff --git a/drivers/hid/spi-hid/spi-hid-apple-core.c b/drivers/hid/spi-hid/spi-hid-apple-core.c index 3f369b99f28c4..b9f76a92f253d 100644 --- a/drivers/hid/spi-hid/spi-hid-apple-core.c +++ b/drivers/hid/spi-hid/spi-hid-apple-core.c @@ -26,8 +26,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -140,6 +142,8 @@ struct spihid_apple { atomic_t power; bool irq_wake_enabled; + /* No wake source in a firmware-driven sleep: the T6000's, where the SMC wakes for it */ + bool fw_sleep_off; }; /** @@ -1261,6 +1265,7 @@ int spihid_apple_core_probe(struct spi_device *spi, struct spihid_apple_ops *ops if (err) dev_warn(dev, "cannot enable wakeup: %d\n", err); } + spihid->fw_sleep_off = apple_t6000_sleep_described(); /* request device information */ dev_dbg(dev, "request device info"); @@ -1332,6 +1337,14 @@ static int spihid_apple_core_suspend(struct device *dev) { int ret; struct spihid_apple *spihid = spi_get_drvdata(to_spi_device(dev)); + /* + * The T6000 firmware-driven sleep cuts the SoC's power. Keys and the trackpad wake the + * machine through the SMC there, and an armed interrupt would turn every other wake + * into a full one. So the controller is powered off and booted again on resume, as + * for a device that is no wakeup source. + */ + bool wake = device_may_wakeup(dev) && + !(spihid->fw_sleep_off && pm_suspend_via_firmware()); if (spihid->tp.hid) { ret = hid_driver_suspend(spihid->tp.hid, PMSG_SUSPEND); @@ -1365,7 +1378,7 @@ static int spihid_apple_core_suspend(struct device *dev) * system. Its state is kept, so resume does not reboot it. */ spihid->irq_wake_enabled = false; - if (device_may_wakeup(dev)) { + if (wake) { ret = spihid->ops->enable_irq_wake(spihid->ops); if (!ret) { spihid->irq_wake_enabled = true; diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 20e82332ade01..d0d43f7cffea6 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -605,6 +605,14 @@ struct apple_dart { u32 save_tcr[DART_MAX_STREAMS]; u32 save_ttbr[DART_MAX_STREAMS][DART_MAX_TTBR]; + /* + * A locked DART that the T6000 firmware-driven sleep resets: its lock word and stream + * enables, saved with the streams, and whether they were. + */ + bool locked_sleep; + bool locked_saved; + u32 save_config; + u32 save_enable[BITS_TO_U32(DART_MAX_STREAMS)]; u64 *locked_ttbr[DART_MAX_STREAMS][DART_MAX_TTBR]; /* Values published by this driver into initially vacant root slots. */ @@ -6614,7 +6622,8 @@ static int apple_dart_probe(struct platform_device *pdev) ret = apple_dart_dapf_parse(pdev, dart); if (ret) return ret; - if (!dart->dapf_count && dart->hw->type == DART_T8020 && + if (!dart->dapf_count && + (dart->hw->type == DART_T8020 || dart->hw->type == DART_T6000) && platform_get_resource_byname(pdev, IORESOURCE_MEM, "dapf")) { /* Read back once the DART is powered, below. */ dart->dapf = devm_platform_ioremap_resource_byname(pdev, "dapf"); @@ -7008,6 +7017,7 @@ static int apple_dart_probe(struct platform_device *pdev) dart->fw_handoff = apple_dart_fw_handoff_enabled(dart); /* Only a locked DART takes the range invalidates apple_dart_t8110_tlb_wait() waits out. */ dart->display_scanout = dart->locked && apple_dart_display_scanout(dev->of_node); + dart->locked_sleep = dart->locked && apple_t6000_sleep_described(); /* * Preserve our retained-root path when no reserved-table handoff exists. * T6050's boot loader leaves every display DART locked on four-level @@ -7673,13 +7683,22 @@ static void apple_dart_sleep_write_kept(struct apple_dart *dart, list->pairs[2 * i]); } +/* + * The TLB command engine's busy flag. The T8020 layout (T8020 and T6000, such as the T6000 + * SEP's DART) has it in STREAM_COMMAND; its register at the T8110 TLB_CMD offset is REMAP. + */ static void apple_dart_sleep_wait_tlb(struct apple_dart *dart) { + u32 reg = DART_T8110_TLB_CMD, busy = DART_T8110_TLB_CMD_BUSY; + u32 timeout = DART_T8110_FLUSH_BUSY_TIMEOUT; u32 status; - if (readl_poll_timeout_atomic(dart->regs + DART_T8110_TLB_CMD, status, - !(status & DART_T8110_TLB_CMD_BUSY), 1, - DART_T8110_FLUSH_BUSY_TIMEOUT)) + if (dart->hw->type != DART_T8110) { + reg = DART_T8020_STREAM_COMMAND; + busy = DART_T8020_STREAM_COMMAND_BUSY; + timeout = DART_STREAM_COMMAND_BUSY_TIMEOUT; + } + if (readl_poll_timeout_atomic(dart->regs + reg, status, !(status & busy), 1, timeout)) dev_err(dart->dev, "TLB command still busy around a sleep: %#x\n", status); } @@ -7894,10 +7913,25 @@ static __maybe_unused int apple_dart_suspend(struct device *dev) if (dart->power_retained || dart->retained_mtp) return 0; - /* Locked DARTs can't be restored so skip saving their registers. */ - if (dart->locked) + /* + * Locked DARTs can't be restored so skip saving their registers, unless the T6000 sleep + * resets them: the firmware's page tables stay in memory. A runtime suspend saves them + * too, as it may be the last one before the sleep. Resume writes them back only when the + * DART really lost its state. + */ + if (dart->locked && !dart->locked_sleep) return 0; + if (dart->locked) { + unsigned int idx; + + dart->save_config = apple_dart_readl(dart, dart->hw->lock); + for (idx = 0; idx < BITS_TO_U32(dart->num_streams); idx++) + dart->save_enable[idx] = + apple_dart_readl(dart, dart->hw->enable_streams + 4 * idx); + dart->locked_saved = true; + } + apple_dart_save_state(dart); return 0; } @@ -8276,9 +8310,28 @@ static __maybe_unused int apple_dart_resume(struct device *dev) return 0; /* Locked DARTs can't be restored, and they should not need it */ - if (dart->locked) + if (dart->locked && (!dart->locked_saved || apple_dart_state_retained(dart))) return 0; + /* + * The T6000 sleep reset it: put back what the boot loader set up, then the lock, then + * drop whatever the TLBs picked up meanwhile. + */ + if (dart->locked) { + for (sid = 0; sid < dart->num_streams; sid++) { + for (idx = 0; idx < dart->hw->ttbr_count; idx++) + apple_dart_writel(dart, dart->save_ttbr[sid][idx], + DART_TTBR(dart, sid, idx)); + apple_dart_writel(dart, dart->save_tcr[sid], DART_TCR(dart, sid)); + } + for (idx = 0; idx < BITS_TO_U32(dart->num_streams); idx++) + apple_dart_writel(dart, dart->save_enable[idx], + dart->hw->enable_streams + 4 * idx); + apple_dart_writel(dart, dart->save_config, dart->hw->lock); + apple_dart_invalidate_each_stream(dart); + return 0; + } + /* * Not for a DART restored at every power-up, as macOS's SPTM does (its * t8110dart powerup): T8140's ISP DART keeps Linux's values through a wake diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index ef8c31817b9ac..1491ca61cd9d7 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -282,6 +282,8 @@ struct aic_info { bool fw_suspend; /* If set, fw_suspend holds only where this says the sleep is described */ bool (*fw_suspend_described)(void); + /* The wake-armed lines stay unmasked from the syscore suspend to the last WFI */ + bool fw_suspend_wake_open; }; static const struct aic_info aic1_info __initconst = { @@ -349,6 +351,22 @@ static const struct aic_info aic3_info __initconst = { .local_fast_ipi = true, }; +/* + * T6000 (M1 Pro): its AICv2 loses its configuration in the firmware-driven sleep, which is + * set up where the device tree describes it; T6001 and T6002 share the compatible. Lines + * armed for wake stay unmasked to the end, so that a wake event that comes in during the + * entry still shows as pending. + */ +static const struct aic_info aic2_t6000_info __initconst = { + .version = 2, + .irq_cfg = AIC2_IRQ_CFG, + .fast_ipi = true, + .local_fast_ipi = true, + .fw_suspend = true, + .fw_suspend_described = apple_t6000_sleep_described, + .fw_suspend_wake_open = true, +}; + /* * The M5 Pro's sleep: the last steps mask every interrupt and acknowledge events by hand. The * save and restore are set up on the boards whose device tree describes a T6050 sleep; @@ -437,6 +455,10 @@ static const struct of_device_id aic_info_match[] = { .compatible = "apple,t8015-aic", .data = &aic1_fipi_info, }, + { + .compatible = "apple,t6000-aic", + .data = &aic2_t6000_info, + }, { .compatible = "apple,aic", .data = &aic1_info, @@ -537,6 +559,35 @@ void aic_sleep_mask_all(void) ic->sleep_cpu_ids[i] = aic_ic_read(ic, AIC_CPU_BLOCK(i)); } +/* Unmask the lines the IRQ core has armed for wake and not masked, from its books. */ +static void aic_sleep_open_wake_lines(struct aic_irq_chip *ic) +{ + u32 off = 0; + int die, i; + + for (die = 0; die < ic->nr_die; die++, off += ic->info.die_stride) { + for (i = 0; i < ic->nr_irq; i++) { + unsigned int virq = irq_find_mapping(ic->hw_domain, AIC_IRQ_HWIRQ(die, i)); + struct irq_data *d = virq ? irq_get_irq_data(virq) : NULL; + + if (d && irqd_is_wakeup_set(d) && !irqd_irq_masked(d)) + aic_ic_write(ic, ic->info.mask_clr + off + MASK_REG(i), + MASK_BIT(i)); + } + } +} + +/* + * As aic_sleep_mask_all(), for a sleep that leaves the lines armed for wake open to the last + * WFI: a wake event during the entry then ends that WFI instead of waiting in a masked line. + * aic_sleep_restore() puts back the masks as they were before. + */ +void aic_sleep_mask_all_but_wake(void) +{ + aic_sleep_mask_all(); + aic_sleep_open_wake_lines(aic_irqc); +} + void aic_sleep_restore(void) { struct aic_irq_chip *ic = aic_irqc; @@ -1329,6 +1380,8 @@ static int aic_syscore_suspend(void *data) aic_ic_write(ic, ic->info.mask_set + off + i * 4, U32_MAX); off += ic->info.die_stride; } + if (ic->info.fw_suspend_wake_open) + aic_sleep_open_wake_lines(ic); aic_sleep.saved = true; return 0; diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index 25daa975c1fbe..0b87f03d4defa 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -774,6 +774,11 @@ static int apple_smc_probe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8103-smc") || of_device_is_compatible(dev->of_node, "apple,t8112-smc")) smc->saved_enabled = true; + /* T6000 is told in the same place as T8103, after the other coprocessors stopped. */ + smc->sleep_t6000 = apple_t6000_sleep_described() && + of_device_is_compatible(dev->of_node, "apple,t6000-smc"); + if (smc->sleep_t6000) + smc->saved_enabled = true; smc->sram_base = devm_platform_get_and_ioremap_resource(pdev, 1, &smc->sram); if (IS_ERR(smc->sram_base)) return dev_err_probe(dev, PTR_ERR(smc->sram_base), "Failed to map SRAM region"); @@ -1173,6 +1178,20 @@ static int apple_smc_wake_reason_names(const struct apple_smc *smc, u64 record, return len; } +static void apple_smc_wake_ap_on(struct apple_smc *smc) +{ + /* T6000: an idle AP gets every key refused, so AP ON gets three tries. */ + unsigned int tries = smc->sleep_t6000 ? 3 : 1; + int ret; + + do { + ret = apple_smc_ap_power(smc, true); + } while (ret && --tries); + if (ret) + dev_err(smc->dev, "SMC did not take the wake notice: %d\n", ret); + apple_smc_set_ap_notified(smc, false); +} + /* * Returns the first error reading the wake record; *mbsw: whether MBSW was read. With @later, a * failed read logs nothing; the noirq resume logs the record if it reads one. @@ -1184,12 +1203,9 @@ static int apple_smc_notice_on(struct apple_smc *smc, bool *mbsw, bool later) u32 event = 0; int ret, error = 0; - if (!smc->saved_wake) { - ret = apple_smc_ap_power(smc, true); - if (ret) - dev_err(smc->dev, "SMC did not take the wake notice: %d\n", ret); - apple_smc_set_ap_notified(smc, false); - } + /* T6000: AP ON went out at the noirq resume already */ + if (!smc->saved_wake && !smc->wake_at_finish) + apple_smc_wake_ap_on(smc); ret = apple_smc_read_u32(smc, SMC_KEY(MBSE), &event); if (ret) { @@ -1579,6 +1595,7 @@ static int apple_smc_sleep_saved_begin(void *data) smc->saved_scope = true; smc->saved_committed = false; smc->saved_pmvc_sent = false; + smc->gen1_keys_sent = false; /* Drain only a bounded prefix before reserving any ID. An old reply * cannot satisfy a fresh command or a stale AP completion a new post. */ @@ -1688,6 +1705,21 @@ static int apple_smc_j813_saved_end(void *data) return apple_smc_sleep_saved_release(data, false); } +/* + * T6000, at the platform finish: the wake record and waka, and what follows them, once the PMP, + * the AOP and the other coprocessors are back, as the sequence that runs on the hardware has + * them. AP ON went out at the noirq resume, before any key. + */ +static void apple_smc_j813_saved_finish(void *data) +{ + struct apple_smc *smc = data; + + if (!smc->wake_at_finish) + return; + apple_smc_sleep_wake(smc, false); + smc->wake_at_finish = false; +} + /* Readiness is a returning operation BEFORE SEP/ANS/PMP stop. A drained * notification remains retained and can cancel only on this side of the boundary. */ @@ -1829,6 +1861,39 @@ static const struct apple_sleep_smc_saved_ops apple_smc_saved_ops = { * resume, except on gen 1, whose are drained once the AP's power-down is * answered. */ +/* Gen 1: pmVC (where the SMC has one), then WKTP, as macOS writes them before slpa. */ +static int apple_smc_sleep_gen1_keys(struct apple_smc *smc) +{ + u8 wktp = 2; + int ret; + + if (smc->sleep_pmvc_set) { + ret = apple_smc_saved_write_u32(smc, SMC_KEY(pmVC), smc->sleep_pmvc); + if (ret) + return ret; + } + return apple_smc_saved_write(smc, SMC_KEY(WKTP), &wktp, sizeof(wktp)); +} + +/* The same, where the sleep driver asks for them while a failure still refuses the sleep */ +static int apple_smc_sleep_keys(void *data) +{ + struct apple_smc *smc = data; + int ret; + + lockdep_assert_held(&smc->mutex); + if (!irqs_disabled() || !smc->saved_scope || !smc->sleep_warned || + smc->saved_committed || smc->ap_notified || !apple_sleep_smc_gen1_keys()) + return -EINVAL; + ret = apple_smc_sleep_gen1_keys(smc); + if (ret) { + dev_err(smc->dev, "SMC sleep keys failed: %d\n", ret); + return ret; + } + smc->gen1_keys_sent = true; + return 0; +} + static int apple_smc_sleep_after_peers(void *data, u64 *sent, u64 *ack) { struct apple_smc *smc = data; @@ -1841,25 +1906,29 @@ static int apple_smc_sleep_after_peers(void *data, u64 *sent, u64 *ack) return -EINVAL; smc->saved_committed = true; - /* Gen 1 (T8103): WKTP between slpw and slpa; this SMC has no pmVC. */ - if (apple_sleep_smc_gen1_keys()) { - u8 wktp = 2; - - ret = apple_smc_saved_write(smc, SMC_KEY(WKTP), &wktp, sizeof(wktp)); + /* + * Gen 1 (T8103): WKTP between slpw and slpa; this SMC has no pmVC. T6000's has: with + * apple,sleep-pmvc, pmVC goes first, then WKTP, as macOS writes them there. + */ + if (apple_sleep_smc_gen1_keys() && !smc->gen1_keys_sent) { + ret = apple_smc_sleep_gen1_keys(smc); if (ret) goto out; } ret = apple_smc_saved_write_u32(smc, SMC_KEY(MBSE), SMC_KEY(slpa)); if (ret) goto out; - mdelay(SMC_SLEEP_ARM_MS); + /* T6000: the AP idle notice right behind slpa's answer, with no gap after it either. */ + if (!smc->sleep_t6000) + mdelay(SMC_SLEEP_ARM_MS); smc->ap_notified = true; ret = apple_rtkit_m5_saved_ap_power(smc->rtk, false, sent, ack); if (!ret) { /* Gen 1: what the SMC posted with its answer, out of the mailbox first */ if (apple_sleep_smc_gen1_keys()) apple_smc_saved_drain(smc); - mdelay(apple_sleep_smc_settle_ms() ?: SMC_SLEEP_IDLE_MS); + if (!smc->sleep_t6000) + mdelay(apple_sleep_smc_settle_ms() ?: SMC_SLEEP_IDLE_MS); } out: smc->saved_notice_error = ret; @@ -1868,8 +1937,10 @@ static int apple_smc_sleep_after_peers(void *data, u64 *sent, u64 *ack) static const struct apple_sleep_smc_saved_ops apple_smc_j813_saved_ops = { .begin = apple_smc_sleep_saved_begin, + .keys = apple_smc_sleep_keys, .late_notice = apple_smc_sleep_after_peers, .end = apple_smc_j813_saved_end, + .finish = apple_smc_j813_saved_finish, }; static int apple_smc_prepare_policy(struct apple_smc *smc) @@ -1958,10 +2029,25 @@ static int apple_smc_sleep_prepare(struct apple_smc *smc) smc->sleep_policy = NULL; return ret; } - if (apple_sleep_debug_link_up()) + if (apple_sleep_debug_link_up()) { smc->sleep_warn_late = true; - else + } else if (smc->sleep_t6000) { + int ret = apple_smc_write_u32(smc, SMC_KEY(MBSE), SMC_KEY(slpw)); + + if (ret) { + /* + * No sleep without the warning. A write that timed out may still have + * reached the SMC, and .complete is not called after a failed .prepare. + */ + dev_err(smc->dev, "Failed to issue MBSE = slpw: %d\n", ret); + if (ret == -ETIMEDOUT) + apple_smc_write_mbse(smc, SMC_KEY(waka)); + return ret; + } + smc->sleep_warned = true; + } else { apple_smc_sleep_warn(smc); + } if (apple_sleep_smc_defer_notice()) return apple_sleep_smc_register_saved(smc->dev, &apple_smc_j813_saved_ops, smc); @@ -2007,6 +2093,11 @@ static void apple_smc_complete(struct device *dev) struct apple_smc *smc = dev_get_drvdata(dev); apple_sleep_smc_unregister(dev); + /* T6000: a platform finish that did not take the wake record leaves it here */ + if (smc->wake_at_finish) { + apple_smc_sleep_wake(smc, false); + smc->wake_at_finish = false; + } /* A full wake ends the run of dark ones. */ if (!pm_dark_wake()) smc->dark_wakes = smc->radio_dark_wakes = 0; @@ -2156,7 +2247,13 @@ static int apple_smc_resume_noirq(struct device *dev) } if (smc->ap_notified) { apple_smc_set_polled(smc, true); - apple_smc_sleep_wake(smc, false); + if (smc->sleep_t6000) { + /* AP ON before any key; the record at the platform finish */ + apple_smc_wake_ap_on(smc); + smc->wake_at_finish = true; + } else { + apple_smc_sleep_wake(smc, false); + } apple_smc_set_polled(smc, false); } diff --git a/drivers/mmc/host/sdhci-pci-gli.c b/drivers/mmc/host/sdhci-pci-gli.c index 300bfe010e69b..82ebc55abaed7 100644 --- a/drivers/mmc/host/sdhci-pci-gli.c +++ b/drivers/mmc/host/sdhci-pci-gli.c @@ -1930,6 +1930,9 @@ static int sdhci_pci_gli_resume(struct sdhci_pci_chip *chip) static int gl9755_resume(struct sdhci_pci_chip *chip) { struct sdhci_pci_slot *slot = chip->slots[0]; + struct sdhci_host *host = slot->host; + u32 val; + int ret; /* * A sleep that takes the reader's power resets its vendor configuration, @@ -1937,9 +1940,24 @@ static int gl9755_resume(struct sdhci_pci_chip *chip) * at probe before the host resumes. */ gl9755_hw_setting(slot); - gl9755_vendor_init(slot->host); + gl9755_vendor_init(host); + + ret = sdhci_pci_gli_resume(chip); + if (ret) + return ret; + + /* + * After such a power cut the chip reports an empty slot, with the + * card state stable, for most of a second. The detect the core runs + * right after resume would take the card that sat in the slot for + * removed. Wait for that card to show up again. + */ + if (host->mmc->card) + read_poll_timeout(sdhci_readl, val, val & SDHCI_CARD_PRESENT, + 10000, 1500000, false, host, + SDHCI_PRESENT_STATE); - return sdhci_pci_gli_resume(chip); + return 0; } static int gl9763e_resume(struct sdhci_pci_chip *chip) diff --git a/drivers/nvme/host/Kconfig b/drivers/nvme/host/Kconfig index 971ae44868e60..ac67af8ec4df9 100644 --- a/drivers/nvme/host/Kconfig +++ b/drivers/nvme/host/Kconfig @@ -127,6 +127,7 @@ config NVME_APPLE depends on OF && BLOCK depends on APPLE_RTKIT && APPLE_SART depends on ARCH_APPLE || COMPILE_TEST + select APPLE_TUNABLE select BLK_INLINE_ENCRYPTION select NVME_CORE help diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index f79c0b647af12..fe80fbb591476 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -225,6 +226,17 @@ struct apple_nvme_iod { unsigned int tcb_stale_stops; }; +/* + * Blocks outside ANS that a firmware sleep resets and whose ADT tunables its + * firmware needs: DT reg name and tunable property of each. + */ +static const char * const apple_nvme_sleep_blocks[][2] = { + { "axi2af", "apple,tunable-axi2af" }, + { "storage-lane", "apple,tunable-storage-lane" }, +}; + +#define APPLE_NVME_TUNABLE_BLOCKS ARRAY_SIZE(apple_nvme_sleep_blocks) + struct apple_nvme_hw { const struct apple_nvme_m5_policy *m5_sleep; bool has_lsq_nvmmu; @@ -293,6 +305,13 @@ struct apple_nvme { bool fw_sleep_idled; /* The SART power word as it was before that sleep */ u32 sart_power; + /* The blocks of apple_nvme_sleep_blocks, where the DT describes all of them */ + bool sleep_restore; + void __iomem *sleep_tunable_regs[APPLE_NVME_TUNABLE_BLOCKS]; + struct apple_tunable *sleep_tunables[APPLE_NVME_TUNABLE_BLOCKS]; + /* ... and the SART power word of the first good start, read at its end */ + u32 sart_power_boot; + bool sleep_boot_saved; bool sleep_failed; /* Run bit set after a sleep, and not yet reported on. */ bool sleep_restarting; @@ -2163,6 +2182,51 @@ static void apple_nvme_stop_crashed_session(struct apple_nvme *anv) anv->ctrl.ctrl_config = 0; } +/* Only the fields that differ: a block the sleep did not reset is left as it is. */ +static void apple_nvme_sleep_tunables(struct apple_nvme *anv) +{ + unsigned int i; + + for (i = 0; i < APPLE_NVME_TUNABLE_BLOCKS; i++) + apple_tunable_apply(anv->sleep_tunable_regs[i], anv->sleep_tunables[i]); +} + +/* + * ANS's AXI2AF and storage-lane blocks (ADT ans reg[4] and reg[5]) are set up with + * the ADT's tunables at cold boot. A firmware sleep resets them, and ANS's firmware + * crashes after its endpoint discovery without them. A controller whose DT gives + * both blocks with their tunables has them put back after such a sleep; one without + * them is left as before. + */ +static int apple_nvme_map_sleep_tunables(struct apple_nvme *anv, + struct platform_device *pdev) +{ + struct device_node *np = anv->dev->of_node; + unsigned int i; + + for (i = 0; i < APPLE_NVME_TUNABLE_BLOCKS; i++) + if (!of_property_present(np, apple_nvme_sleep_blocks[i][1])) + return 0; + + for (i = 0; i < APPLE_NVME_TUNABLE_BLOCKS; i++) { + struct resource *res; + + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, + apple_nvme_sleep_blocks[i][0]); + if (!res) + return -EINVAL; + anv->sleep_tunables[i] = + devm_apple_tunable_parse(anv->dev, np, apple_nvme_sleep_blocks[i][1], res); + if (IS_ERR(anv->sleep_tunables[i])) + return PTR_ERR(anv->sleep_tunables[i]); + anv->sleep_tunable_regs[i] = devm_ioremap_resource(anv->dev, res); + if (IS_ERR(anv->sleep_tunable_regs[i])) + return PTR_ERR(anv->sleep_tunable_regs[i]); + } + anv->sleep_restore = true; + return 0; +} + static bool apple_nvme_sleep_wait_on(struct apple_nvme *anv); static void apple_nvme_reset_work_impl(struct work_struct *work) @@ -2362,8 +2426,19 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) * entries before starting ANS (no-op on cold boot when replay_valid is false). */ if (fw_sleep) { - if (readl(anv->mmio_nvme + APPLE_ANS_SART_POWER) != anv->sart_power) - writel(anv->sart_power, anv->mmio_nvme + APPLE_ANS_SART_POWER); + /* + * Where the DT gives them: the power cut also reset ANS's AXI2AF and + * storage-lane blocks, and its firmware crashes right after its endpoint + * discovery without their tunables. Put them back with the SART's power + * word as the first good start had it. + */ + u32 sart_power = anv->sleep_boot_saved ? + anv->sart_power_boot : anv->sart_power; + + if (readl(anv->mmio_nvme + APPLE_ANS_SART_POWER) != sart_power) + writel(sart_power, anv->mmio_nvme + APPLE_ANS_SART_POWER); + if (anv->sleep_boot_saved) + apple_nvme_sleep_tunables(anv); /* Only after a sleep that didn't happen: the wake wrote them already. */ if (anv->sart) apple_sart_restore_early(anv->sart); @@ -2655,6 +2730,11 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) nvme_start_ctrl(&anv->ctrl); dev_dbg(anv->dev, "ANS boot and NVMe init completed."); + /* What a deep sleep takes from ANS is what its first good start had. */ + if (anv->sleep_restore && !anv->sleep_boot_saved) { + anv->sart_power_boot = readl(anv->mmio_nvme + APPLE_ANS_SART_POWER); + anv->sleep_boot_saved = true; + } return; out_remove_sq: @@ -3123,6 +3203,12 @@ static struct apple_nvme *apple_nvme_alloc(struct platform_device *pdev) anv->mmio_nvmmu = anv->mmio_nvme; } + ret = apple_nvme_map_sleep_tunables(anv, pdev); + if (ret) { + dev_err_probe(dev, ret, "bad sleep tunables\n"); + goto out_detach_genpd; + } + ret = apple_nvme_read_handoff(anv); if (ret) { dev_err_probe(dev, ret, "Invalid live firmware handoff\n"); diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 88f464309cf27..a5bd9754341c6 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -323,6 +323,16 @@ struct hw_info { */ bool s2r_noirq; bool host_resumes_dart; + /* + * ... and waits 100 ms after PERST# there too, as probe does, before the + * PHY's ready bit is polled. + */ + bool s2r_perst_wait; + /* + * ... and a port that cannot be set up again there takes the host's functions with + * it: they are marked disconnected and the DARTs behind the host quiesced. + */ + bool s2r_lost_gone; }; static const struct hw_info t8103_hw = { @@ -336,6 +346,25 @@ static const struct hw_info t8103_hw = { .max_rid2sid = 64, }; +/* + * T6000 (M1 Pro): the T8103 layout. After a deep sleep the internal ports (Wi-Fi and + * Bluetooth, SD reader) come back in the noirq resume, before anything below them is + * touched, with probe's wait after PERST#. + */ +static const struct hw_info t6000_hw = { + .phy_lane_ctl = PHY_LANE_CTL, + .port_msiaddr = PORT_MSIADDR, + .port_msiaddr_hi = 0, + .port_refclk = PORT_REFCLK, + .port_perst = PORT_PERST, + .port_rid2sid = PORT_RID2SID, + .port_msimap = 0, + .max_rid2sid = 64, + .s2r_noirq = true, + .s2r_perst_wait = true, + .s2r_lost_gone = true, +}; + static const struct hw_info t602x_hw = { .phy_lane_ctl = 0, .port_msiaddr = PORT_T602X_MSIADDR, @@ -734,6 +763,8 @@ struct apple_pcie { atomic_t hib_l1ss_pending_cnt; bool hib_l1ss_closing; bool hib_saved; + /* A cold port's set-up failed in this noirq bring-up (hw->s2r_lost_gone) */ + bool hib_lost; struct completion event; struct irq_fwspec fwspec; struct irq_domain *msi_domain; @@ -6729,6 +6760,12 @@ static int apple_pcie_probe(struct platform_device *pdev) hw = of_device_get_match_data(dev); if (!hw) return -ENODEV; + /* + * The T6000 data is the T8103 data plus the deep sleep's steps. Where that sleep is + * not described (T6001 and T6002 share the compatible), keep the T8103 path. + */ + if (hw == &t6000_hw && !apple_t6000_sleep_described()) + hw = &t8103_hw; /* * A tunneled PCIe-C port has no host GPIO for PERST#: the tunnel @@ -10032,8 +10069,10 @@ static int apple_pcie_hib_port_up(struct apple_pcie *pcie, struct apple_pcie_por int ret; ret = apple_pcie_setup_link(pcie, port, port->np); - if (ret) + if (ret) { + pcie->hib_lost = true; return ret; + } ret = apple_pcie_hib_port_start(pcie, port); if (ret) return ret; @@ -10056,6 +10095,42 @@ static void apple_pcie_hib_port_failed(struct apple_pcie *pcie, struct apple_pci port->hib_cold = false; } +/* ... because its set-up failed, rather than its link not training in time. */ +static void apple_pcie_hib_port_lost(struct apple_pcie *pcie, struct apple_pcie_port *port, + int ret) +{ + apple_pcie_hib_port_failed(pcie, port, ret); + pcie->hib_lost = true; +} + +/* Stop every DART the iommu-map of this host points at from touching hardware. */ +static void apple_pcie_quiesce_mapped_darts(struct apple_pcie *pcie) +{ + struct device_node *np = pcie->dev->of_node; + int n, i; + + n = of_property_count_u32_elems(np, "iommu-map"); + for (i = 0; n > 0 && i + 3 < n;) { + struct platform_device *pdev; + struct device_node *dart; + u32 phandle, cells = 1; + + if (of_property_read_u32_index(np, "iommu-map", i + 1, &phandle)) + break; + dart = of_find_node_by_phandle(phandle); + if (!dart) + break; + of_property_read_u32(dart, "#iommu-cells", &cells); + pdev = of_find_device_by_node(dart); + if (pdev) { + apple_dart_quiesce_commands(&pdev->dev); + put_device(&pdev->dev); + } + of_node_put(dart); + i += 3 + cells; + } +} + /* * apple_pcie_setup_link()'s bring-up of the cold ports taken in phases, so that the * power-on, PERST# and post-training waits run once for all of them rather than once @@ -10081,7 +10156,7 @@ static void apple_pcie_hib_ports_phased(struct apple_pcie *pcie) if (!ret) ret = apple_pcie_setup_refclk(pcie, port); if (ret < 0) - apple_pcie_hib_port_failed(pcie, port, ret); + apple_pcie_hib_port_lost(pcie, port, ret); } /* Tpvperl of at least 100 ms when powering up, Tperst-clk of 100 us otherwise */ if (powered) @@ -10090,9 +10165,9 @@ static void apple_pcie_hib_ports_phased(struct apple_pcie *pcie) usleep_range(100, 200); /* - * No wait after PERST#: these root ports go beyond 5 GT/s, so configuration requests - * wait for 100 ms after training instead (PCIe r5.0, 6.6.1), below. The PHY's ready bit - * has no interrupt. + * No wait after PERST# unless s2r_perst_wait: these root ports go beyond 5 GT/s, so + * configuration requests wait for 100 ms after training instead (PCIe r5.0, 6.6.1), + * below. The PHY's ready bit has no interrupt. */ list_for_each_entry(port, &pcie->ports, entry) { if (!port->hib_cold) @@ -10100,8 +10175,11 @@ static void apple_pcie_hib_ports_phased(struct apple_pcie *pcie) rmw_set(PORT_PERST_OFF, port->base + pcie->hw->port_perst); ret = gpiod_set_value_cansleep(port->perst_gpio, 0); if (ret) - apple_pcie_hib_port_failed(pcie, port, ret); + apple_pcie_hib_port_lost(pcie, port, ret); } + /* 100 ms after PERST# (PCIe r5.0, 6.6.1), once for all of them */ + if (pcie->hw->s2r_perst_wait) + msleep(100); list_for_each_entry(port, &pcie->ports, entry) { if (!port->hib_cold) @@ -10109,7 +10187,7 @@ static void apple_pcie_hib_ports_phased(struct apple_pcie *pcie) ret = readl_relaxed_poll_timeout(port->base + PORT_STATUS, stat, stat & PORT_STATUS_READY, 100, 250000); if (ret < 0) { - apple_pcie_hib_port_failed(pcie, port, ret); + apple_pcie_hib_port_lost(pcie, port, ret); continue; } reinit_completion(&port->hib_link); @@ -10167,6 +10245,7 @@ static void apple_pcie_hib_ports_up_noirq(struct apple_pcie *pcie) struct apple_pcie_port *port; int ret; + pcie->hib_lost = false; if (apple_pcie_hib_phased_ok(pcie)) { apple_pcie_hib_ports_phased(pcie); } else { @@ -10187,6 +10266,17 @@ static void apple_pcie_hib_ports_up_noirq(struct apple_pcie *pcie) port->hib_cold = false; } apple_pcie_hib_free_fns(pcie); + /* + * Nothing below this host may touch it then: its functions are cut off as after + * a surprise removal and its DARTs stop taking commands, rather than Wi-Fi or + * the SD reader resuming against a dead link. + */ + if (pcie->hw->s2r_lost_gone && pcie->hib_lost) { + dev_warn(pcie->dev, + "S2R: a port did not come back, the host's functions stay down\n"); + apple_pcie_tunnel_hierarchy_gone(pcie->dev); + apple_pcie_quiesce_mapped_darts(pcie); + } } /* The normal phase, after the SMC (the PWREN GPIOs are its) and before the functions. */ @@ -10521,6 +10611,7 @@ static const struct of_device_id apple_pcie_of_match[] = { { .compatible = "apple,t6020-pcie", .data = &t602x_hw }, { .compatible = "apple,t8140-pcie", .data = &t8140_hw }, { .compatible = "apple,t6050-pcie", .data = &t6050_hw }, + { .compatible = "apple,t6000-pcie", .data = &t6000_hw }, { .compatible = "apple,pcie", .data = &t8103_hw }, { } }; diff --git a/drivers/pinctrl/pinctrl-apple-gpio.c b/drivers/pinctrl/pinctrl-apple-gpio.c index 6494d024e9d54..94e86629fbcf0 100644 --- a/drivers/pinctrl/pinctrl-apple-gpio.c +++ b/drivers/pinctrl/pinctrl-apple-gpio.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -56,6 +57,11 @@ struct apple_gpio_pinctrl { unsigned long *saved_valid; /* Pins this driver has written. Others belong to someone else. */ unsigned long *touched; + /* The pins' words across a deep sleep that cuts this block's power */ + u32 *sleep_cfg; + unsigned long *sleep_skip; + u32 sleep_input_enable; + bool sleep_saved; struct apple_gpio_irq_group irqgrps[]; }; @@ -83,6 +89,12 @@ struct apple_gpio_pinctrl { #define REG_GPIOx_LOCK BIT(21) #define REG_GPIOx_DRIVE_STRENGTH1 GENMASK(23, 22) #define REG_IRQ(g, x) (0x800 + 0x40 * (g) + 4 * ((x) >> 5)) +/* + * Input receivers of the whole block. The boot firmware sets this, and it reads + * 0 once the block has lost power. While it is clear every input reads low, so + * a level-low IRQ fires forever although nothing drives the line. + */ +#define REG_INPUT_ENABLE 0xc48 static const struct regmap_config regmap_config = { .reg_bits = 32, @@ -421,6 +433,27 @@ static const struct irq_chip apple_gpio_irqchip = { GPIOCHIP_IRQ_RESOURCE_HELPERS, }; +/* + * The same for a block whose pins are saved for a deep sleep. Every pin shares + * the group IRQs, which stay open, so the pins that are not wake sources are + * masked as the sleep starts instead of at their first interrupt. The save then + * holds the modes the IRQ core unmasks again, through the regmap, on resume, and + * no pin is masked after it. Wake sources a driver disabled are enabled for the + * sleep. + */ +static const struct irq_chip apple_gpio_irqchip_sleep = { + .name = "Apple-GPIO", + .irq_startup = apple_gpio_irq_startup, + .irq_ack = apple_gpio_irq_ack, + .irq_mask_ack = apple_gpio_irq_mask_ack, + .irq_mask = apple_gpio_irq_mask, + .irq_unmask = apple_gpio_irq_unmask, + .irq_set_type = apple_gpio_irq_set_type, + .flags = IRQCHIP_IMMUTABLE | IRQCHIP_SKIP_SET_WAKE | + IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_ENABLE_WAKEUP_ON_SUSPEND, + GPIOCHIP_IRQ_RESOURCE_HELPERS, +}; + /* Probe & register */ struct apple_gpio_hw { @@ -430,6 +463,11 @@ struct apple_gpio_hw { * only within the valid GPIO registers minus gpio-reserved-ranges. */ bool no_regcache; + /* + * The block a sleep controller names as the one whose pins a deep sleep + * resets keeps them itself: saved and put back by this driver. + */ + bool sleep_save; }; /* T8140 (A18 Pro) and T8132 (M4) both have faulting slots in this block. */ @@ -437,6 +475,10 @@ static const struct apple_gpio_hw apple_gpio_uncached_hw = { .no_regcache = true, }; +static const struct apple_gpio_hw apple_gpio_t6000_hw = { + .sleep_save = true, +}; + static int apple_gpio_regmap_access(struct device *dev, unsigned int npins, struct regmap_config *config) { @@ -486,6 +528,70 @@ static int apple_gpio_regmap_access(struct device *dev, unsigned int npins, return 0; } +/* + * Only a block whose power domain can go down loses its pins in a deep sleep: + * on T6000 that is the AP block. The NUB block sits in an always-on domain, and + * the SMC and AOP blocks have no domain at all. + */ +static bool apple_gpio_domain_can_power_down(struct device *dev) +{ + struct device_node *pd; + bool ret; + + pd = of_parse_phandle(dev->of_node, "power-domains", 0); + if (!pd) + return false; + + ret = !of_property_read_bool(pd, "apple,always-on"); + of_node_put(pd); + + return ret; +} + +/* + * A T6000 deep sleep cuts the AP block's power with the SoC, and the block comes + * back with every pin reset. The sleep controller names that block + * ("apple,pinctrl") and the pins to leave alone ("apple,pinctrl-skip-pins", the + * ADT's no-restore-gpio-pins, which macOS does not put back either). + */ +static int apple_gpio_sleep_init(struct apple_gpio_pinctrl *pctl, unsigned int npins) +{ + struct device *dev = pctl->dev; + struct device_node *np, *pins; + u32 pin; + int i, n; + + if (!apple_gpio_domain_can_power_down(dev)) + return 0; + + for_each_node_with_property(np, "apple,pinctrl") { + if (!of_device_is_available(np)) + continue; + pins = of_parse_phandle(np, "apple,pinctrl", 0); + of_node_put(pins); + if (pins == dev->of_node) + break; + } + if (!np) + return 0; + + pctl->sleep_cfg = devm_kcalloc(dev, npins, sizeof(*pctl->sleep_cfg), GFP_KERNEL); + pctl->sleep_skip = devm_bitmap_zalloc(dev, npins, GFP_KERNEL); + if (!pctl->sleep_cfg || !pctl->sleep_skip) { + of_node_put(np); + return -ENOMEM; + } + + n = of_property_count_u32_elems(np, "apple,pinctrl-skip-pins"); + for (i = 0; i < n; i++) + if (!of_property_read_u32_index(np, "apple,pinctrl-skip-pins", i, &pin) && + pin < npins) + set_bit(pin, pctl->sleep_skip); + of_node_put(np); + + return 0; +} + static int apple_gpio_register(struct apple_gpio_pinctrl *pctl) { struct gpio_irq_chip *girq = &pctl->gpio_chip.irq; @@ -507,7 +613,10 @@ static int apple_gpio_register(struct apple_gpio_pinctrl *pctl) if (girq->num_parents) { int i; - gpio_irq_chip_set_chip(girq, &apple_gpio_irqchip); + if (pctl->sleep_cfg) + gpio_irq_chip_set_chip(girq, &apple_gpio_irqchip_sleep); + else + gpio_irq_chip_set_chip(girq, &apple_gpio_irqchip); girq->parent_handler = apple_gpio_irq_handler; girq->parents = kmalloc_array(girq->num_parents, @@ -639,6 +748,12 @@ static int apple_gpio_pinctrl_probe(struct platform_device *pdev) return -ENOMEM; } + if (hw && hw->sleep_save) { + res = apple_gpio_sleep_init(pctl, npins); + if (res) + return res; + } + for (i = 0; i < npins; i++) { pins[i].number = i; pins[i].name = devm_kasprintf(&pdev->dev, GFP_KERNEL, "PIN%u", i); @@ -685,12 +800,114 @@ static const struct of_device_id apple_gpio_pinctrl_of_match[] = { { .compatible = "apple,t8132-pinctrl", .data = &apple_gpio_uncached_hw }, { .compatible = "apple,t6050-pinctrl", .data = &apple_gpio_uncached_hw }, { .compatible = "apple,t6030-pinctrl", .data = &apple_gpio_uncached_hw }, + { .compatible = "apple,t6000-pinctrl", .data = &apple_gpio_t6000_hw }, { .compatible = "apple,t8103-pinctrl", }, { .compatible = "apple,pinctrl", }, { } }; MODULE_DEVICE_TABLE(of, apple_gpio_pinctrl_of_match); +/* Deep sleep */ + +/* + * The bits that tell whether a pin kept its configuration. DATA only counts + * on a GPIO output; on any other pin it follows the pad. + */ +static u32 apple_gpio_sleep_mask(u32 cfg) +{ + if (!FIELD_GET(REG_GPIOx_PERIPH, cfg) && + FIELD_GET(REG_GPIOx_MODE, cfg) == REG_GPIOx_OUT) + return ~0U; + + return ~(u32)REG_GPIOx_DATA; +} + +/* + * The block keeps its power through every system sleep until the sleep itself + * cuts it: the sleep's last steps need the GPIO domain on. + * + * A deep sleep (a firmware-driven suspend to RAM) takes the domain down with the + * SoC. Every pin is saved here, after its consumers' noirq suspend and after + * suspend_device_irqs() masked the pins that are not wake sources, so the saved + * IRQ modes are the ones the IRQ core unmasks again on resume. s2idle stays as + * it was. + */ +static void apple_gpio_sleep_save(struct apple_gpio_pinctrl *pctl) +{ + unsigned int pin; + + if (!pctl->sleep_cfg) + return; + + device_set_awake_path(pctl->dev); + if (pm_suspend_target_state != PM_SUSPEND_MEM || !pm_suspend_via_firmware()) + return; + + for (pin = 0; pin < pctl->pinctrl_desc.npins; pin++) + pctl->sleep_cfg[pin] = readl_relaxed(pctl->base + REG_GPIO(pin)); + pctl->sleep_input_enable = readl_relaxed(pctl->base + REG_INPUT_ENABLE); + pctl->sleep_saved = true; +} + +/* + * By now the sleep's .wake has the domain on again, and no consumer has resumed. + * Only pins that changed are written, so this does nothing when the block kept + * its state. The writes go through the regmap so its cache follows: a + * regcache_sync() would skip every register that equals the cached value. The + * pins the sleep controller lists are left alone, and so are the IRQ status + * registers: a bit latched there is for the IRQ handler to see. + */ +static void apple_gpio_sleep_restore(struct apple_gpio_pinctrl *pctl) +{ + struct device *dev = pctl->dev; + unsigned int pin, first = 0, lost = 0, stuck = 0; + u32 cfg, saved, first_cfg = 0; + + if (!pctl->sleep_saved) + return; + pctl->sleep_saved = false; + + /* First, so the pins below come back with their real input levels */ + cfg = readl_relaxed(pctl->base + REG_INPUT_ENABLE); + if (cfg != pctl->sleep_input_enable) { + writel_relaxed(pctl->sleep_input_enable, pctl->base + REG_INPUT_ENABLE); + dev_dbg(dev, "restored the input enable after a deep sleep (was 0x%x)\n", cfg); + } + + for (pin = 0; pin < pctl->pinctrl_desc.npins; pin++) { + if (test_bit(pin, pctl->sleep_skip)) + continue; + + saved = pctl->sleep_cfg[pin]; + cfg = readl_relaxed(pctl->base + REG_GPIO(pin)); + if (!((cfg ^ saved) & apple_gpio_sleep_mask(saved))) + continue; + + if (!lost++) { + first = pin; + first_cfg = cfg; + } + + if (regmap_write(pctl->map, REG_GPIO(pin), saved)) { + stuck++; + continue; + } + + cfg = readl_relaxed(pctl->base + REG_GPIO(pin)); + if ((cfg ^ saved) & apple_gpio_sleep_mask(saved)) + stuck++; + } + + if (!lost) + dev_dbg(dev, "pins kept their configuration through a deep sleep\n"); + else + dev_dbg(dev, "restored %u pins after a deep sleep (pin %u was 0x%08x, saved 0x%08x)\n", + lost, first, first_cfg, pctl->sleep_cfg[first]); + + if (stuck) + dev_warn(dev, "%u pins did not take their saved configuration\n", stuck); +} + /* * A firmware-driven suspend powers this block off, and neither the pin core nor * a consumer sets a pin up again. Slots that fault aren't readable in the regmap, @@ -701,6 +918,7 @@ static int apple_gpio_pinctrl_suspend_noirq(struct device *dev) struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); unsigned int i; + apple_gpio_sleep_save(pctl); if (!pctl->saved || pm_suspend_target_state != PM_SUSPEND_MEM || !pm_suspend_via_firmware()) return 0; @@ -722,6 +940,7 @@ static int apple_gpio_pinctrl_resume_noirq(struct device *dev) struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); unsigned int i, val, restored = 0; + apple_gpio_sleep_restore(pctl); if (!pctl->saved || !pm_resume_via_firmware()) return 0; diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index c790606badd8a..7347057950742 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -143,6 +143,9 @@ struct apple_pmp_report { bool defer; /* The request word when a system sleep stopped the PMP. */ u64 sleep_request; + /* T600x: the DVFS entries apple_pmp_report_sleep_tail() idled, to put back at the wake. */ + u64 tail_dvfs[4]; + bool tail_done; /* The last SOC-DEV-DVFS word written to each entry, 0 if none. */ u64 *dvfs_shadow; unsigned int polls; @@ -625,21 +628,76 @@ void apple_pmp_report_sleep(struct device *pmp, bool at_commit) } EXPORT_SYMBOL_GPL(apple_pmp_report_sleep); +/* + * T600x: the CPU and fabric DVFS entries (SOC-DEV-DVFS 0x108-0x10a and 0x10c), read at 16 bytes + * a record and written through the update aperture, the idle value of each and the report's + * sleep word, as the PMP's sleep action leaves them. + */ +static const u16 apple_pmp_t600x_sleep_dvfs[] = { 0x108, 0x109, 0x10a, 0x10c }; +#define PMP_T600X_DVFS_READ(id) (0x10 * (id)) +#define PMP_T600X_DVFS_IDLE BIT_ULL(61) +#define PMP_T600X_SLEEP_WORD 0x18328 + +static void apple_pmp_t600x_dvfs_idle(struct apple_pmp_report *rep, unsigned int n) +{ + unsigned int i; + + for (i = 0; i < n; i++) + writeq(PMP_T600X_DVFS_IDLE, + rep->base + rep->offsets->update + 8 * apple_pmp_t600x_sleep_dvfs[i]); +} + /** - * apple_pmp_report_wake() - hand the PMP every request after a system sleep - * @pmp: the PMP device, running again - * @lost_power: the sleep reached the hardware, so the report may have lost its - * contents: bits no entry owns come from the word kept at the sleep + * apple_pmp_report_sleep_tail() - a T600x PMP's last requests before a sleep stops it + * @pmp: the PMP device, still running * - * The power requests go first and the performance requests after them, the - * order an entry uses when it powers on. + * Interrupts off, right before the PMP is idled at the sleep's commit, as macOS's sleep + * action does it: every request withdrawn, the CPU and fabric DVFS entries set to idle + * (twice, and the first three once more after the sleep word) and the sleep word to 1. + * The withdrawn requests come back from the word kept by apple_pmp_report_sleep(), the + * DVFS entries from what they read here. */ -void apple_pmp_report_wake(struct device *pmp, bool lost_power) +void apple_pmp_report_sleep_tail(struct device *pmp) +{ + const unsigned int n = ARRAY_SIZE(apple_pmp_t600x_sleep_dvfs); + struct apple_pmp_report *rep; + unsigned long flags; + unsigned int i; + u64 val; + + rcu_read_lock(); + list_for_each_entry_rcu(rep, &apple_pmp_reports, list) { + if (rep->offsets != &apple_pmp_offsets_t600x || !apple_pmp_report_of(rep, pmp)) + continue; + spin_lock_irqsave(&rep->lock, flags); + writeq(0, rep->base + rep->offsets->tgt_write); + spin_unlock_irqrestore(&rep->lock, flags); + /* macOS waits for the low half alone: the high one may stay acknowledged. */ + if (readq_poll_timeout_atomic(rep->base + rep->offsets->actual, val, + !lower_32_bits(val), 1000, 200000)) + dev_warn(rep->dev, "PMP still acknowledges %#llx at the sleep\n", val); + for (i = 0; i < n; i++) { + u32 reg = PMP_T600X_DVFS_READ(apple_pmp_t600x_sleep_dvfs[i]); + + rep->tail_dvfs[i] = readq(rep->base + reg); + } + apple_pmp_t600x_dvfs_idle(rep, n); + apple_pmp_t600x_dvfs_idle(rep, n); + writel(1, rep->base + PMP_T600X_SLEEP_WORD); + apple_pmp_t600x_dvfs_idle(rep, n - 1); + rep->tail_done = true; + } + rcu_read_unlock(); +} +EXPORT_SYMBOL_GPL(apple_pmp_report_sleep_tail); + +static void apple_pmp_report_requests_back(struct device *pmp, bool lost_power, bool started) { struct apple_pmp_report *rep; unsigned long flags; unsigned int i; u64 val, want; + bool tail; mutex_lock(&apple_pmp_reports_lock); list_for_each_entry(rep, &apple_pmp_reports, list) { @@ -651,6 +709,12 @@ void apple_pmp_report_wake(struct device *pmp, bool lost_power) val = lost_power ? rep->sleep_request : readq(rep->base + offs->tgt_read); writeq(apple_pmp_request_word(val, rep->known, rep->shadow), rep->base + offs->tgt_write); + /* Left at idle, the PMP keeps the fabric clocks at their idle source. */ + tail = rep->tail_done && started; + for (i = 0; tail && i < ARRAY_SIZE(apple_pmp_t600x_sleep_dvfs); i++) + writeq(rep->tail_dvfs[i], + rep->base + offs->update + 8 * apple_pmp_t600x_sleep_dvfs[i]); + rep->tail_done = false; for (i = 0; rep->dvfs_shadow && i < offs->dvfs_count; i++) if (rep->dvfs_shadow[i]) writeq(rep->dvfs_shadow[i], @@ -658,6 +722,9 @@ void apple_pmp_report_wake(struct device *pmp, bool lost_power) want = rep->shadow & ~rep->no_ack; WRITE_ONCE(rep->defer, false); spin_unlock_irqrestore(&rep->lock, flags); + /* A PMP that did not start again moves no clock and acknowledges nothing. */ + if (!started) + continue; if (want && readq_poll_timeout(rep->base + offs->actual, val, (val & want) == want, 1000, 1000000)) @@ -667,8 +734,36 @@ void apple_pmp_report_wake(struct device *pmp, bool lost_power) mutex_unlock(&apple_pmp_reports_lock); } + +/** + * apple_pmp_report_wake() - hand the PMP every request after a system sleep + * @pmp: the PMP device, running again + * @lost_power: the sleep reached the hardware, so the report may have lost its + * contents: bits no entry owns come from the word kept at the sleep + * + * The power requests go first and the performance requests after them, the + * order an entry uses when it powers on. + */ +void apple_pmp_report_wake(struct device *pmp, bool lost_power) +{ + apple_pmp_report_requests_back(pmp, lost_power, true); +} EXPORT_SYMBOL_GPL(apple_pmp_report_wake); +/** + * apple_pmp_report_wake_unstarted() - the requests back for a T600x PMP that did not start again + * @pmp: the PMP device, its firmware not running after the sleep's power cut + * + * The request words go back as apple_pmp_report_wake() writes them, so its next start finds + * them. The DVFS entries the sleep's tail left at idle stay so, with no wait for the clocks + * and none for an acknowledge: no firmware answers. + */ +void apple_pmp_report_wake_unstarted(struct device *pmp) +{ + apple_pmp_report_requests_back(pmp, true, false); +} +EXPORT_SYMBOL_GPL(apple_pmp_report_wake_unstarted); + /* The unique, enabled and acknowledged T6030 display request (DISP, reg 7). */ static struct device_node *apple_pmp_report_t6030_entry(struct device_node *report) { @@ -3257,6 +3352,55 @@ int apple_pmp_report_set_request(const struct device_node *report_np, unsigned i } EXPORT_SYMBOL_GPL(apple_pmp_report_set_request); +/** + * apple_pmp_report_sleep_request() - set or clear a request bit for a sleep, interrupts off + * @report_np: the report's node + * @id: the request bit + * @enable: set it, or clear it + * @timeout_us: how long to wait for the acknowledge to follow + * @was: if not NULL, whether the bit was requested before + * + * For a sleep profile, at its own steps with interrupts off: the bit is written whoever owns + * it, the T600x AGX vote's bit 9 included, under the report's lock. The books (@shadow) are + * left alone, so the owners' requests are what the report hands the PMP again after the + * sleep; the profile itself puts back a bit it cleared when a sleep is given up. The + * acknowledge is polled in 10 us steps whatever the report says of the PMP: one that does not + * answer within @timeout_us fails, and the sleep is not entered over it. + * + * Return: 0, -ENODEV with no report bound to @report_np, -EINVAL for an @id over 63, + * -ETIMEDOUT when the bit was written and the acknowledge did not follow. + */ +int apple_pmp_report_sleep_request(const struct device_node *report_np, unsigned int id, + bool enable, unsigned int timeout_us, bool *was) +{ + struct apple_pmp_report *rep; + unsigned long flags; + int ret = -ENODEV; + u64 bit, val; + + if (id > 63) + return -EINVAL; + bit = BIT_ULL(id); + rcu_read_lock(); + list_for_each_entry_rcu(rep, &apple_pmp_reports, list) { + if (rep->dev->of_node != report_np) + continue; + spin_lock_irqsave(&rep->lock, flags); + val = readq(rep->base + rep->offsets->tgt_read); + if (was) + *was = val & bit; + writeq(enable ? val | bit : val & ~bit, rep->base + rep->offsets->tgt_write); + spin_unlock_irqrestore(&rep->lock, flags); + ret = readq_poll_timeout_atomic(rep->base + rep->offsets->actual, val, + !!(val & bit) == enable, 10, timeout_us); + break; + } + rcu_read_unlock(); + + return ret; +} +EXPORT_SYMBOL_GPL(apple_pmp_report_sleep_request); + static int apple_pmp_report_entry_set_state(struct generic_pm_domain *genpd, bool enable) { struct apple_pmp_report_entry *ent = genpd_to_apple_pmp_report_entry(genpd); @@ -3718,6 +3862,14 @@ static int apple_pmp_report_entry_probe(struct platform_device *pdev) ent->sleep_release = false; } } + /* + * A consumer whose firmware keeps running through a system sleep puts itself on the + * wakeup path, as a PMGR state's consumer does for apple,sleep-wakeup-path. Keep the + * entry on with it then, and with the entry its parent power states: powered off in the + * noirq phase, they would take the firmware's power while it runs. + */ + if (of_property_read_bool(node, "apple,sleep-wakeup-path")) + ent->genpd.flags |= GENPD_FLAG_ACTIVE_WAKEUP; ent->genpd.power_on = apple_pmp_report_entry_power_on; ent->genpd.power_off = apple_pmp_report_entry_power_off; diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 3099c44a084d1..5dde2faec02d6 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -82,6 +82,7 @@ use kernel::{ }, types::{ ForeignOwnable, + Opaque, ScopeGuard, // }, workqueue::{ @@ -1372,6 +1373,15 @@ struct AopData { sleep_stopped: Atomic, /// The firmware was told the AP is going to sleep. ap_idle: Atomic, + /// [`AOP_S2R_UNANSWERED`]: the sleep's stops go out at the platform's .prepare, through + /// this notifier, instead of in suspend_late. + #[cfg_attr(not(CONFIG_APPLE_SOC_SLEEP), allow(dead_code))] + prepare_nb: SleepNotifier, + /// And are undone at the platform's .finish, through this one, instead of at resume. + #[cfg_attr(not(CONFIG_APPLE_SOC_SLEEP), allow(dead_code))] + finish_nb: SleepNotifier, + /// [`Self::prepare_nb`] and [`Self::finish_nb`] are registered. + stop_at_prepare: Atomic, #[pin] hid_listeners: Mutex>, #[pin] @@ -1572,6 +1582,9 @@ impl AopData { crashed: Atomic::new(false), sleep_stopped: Atomic::new(0), ap_idle: Atomic::new(false), + prepare_nb: SleepNotifier(Opaque::zeroed()), + finish_nb: SleepNotifier(Opaque::zeroed()), + stop_at_prepare: Atomic::new(false), hid_listeners <- new_mutex!(KVec::new()), report_listeners <- new_mutex!(KVec::new()), source_ring <- new_mutex!(None), @@ -1818,6 +1831,138 @@ impl AopData { .ok_or(ETIMEDOUT) } + /// Sends `msg` to the first [`AOP_S2R_UNANSWERED_EPS`] endpoints in `eps` (by index), + /// without waiting for answers. Returns those it went out to, and of those the started + /// ones, whose answers [`Self::sleep_wait_answers`] can wait for. + fn sleep_send_unanswered(&self, eps: u32, msg: u64) -> (u32, u32) { + let mut running = 0u32; + for index in 0..AOP_S2R_UNANSWERED_EPS { + if eps & (1 << index) != 0 && self.endpoints[index as usize].lock().started { + running |= 1 << index; + } + } + let mut guard = self.rtkit.lock(); + let Some(mut rtk) = guard.as_mut().as_pin_mut() else { + return (0, 0); + }; + let mut sent = 0; + for index in 0..AOP_S2R_UNANSWERED_EPS { + if eps & (1 << index) == 0 { + continue; + } + let endpoint = AFK_ENDPOINT_START + index; + // An answer left from an earlier message must not count for this one. + self.ep_sleep[index as usize].reset(); + match rtk.as_mut().send_message(endpoint, msg) { + Ok(()) => sent |= 1 << index, + Err(e) => dev_dbg!( + self.dev, + "Endpoint {:#04x}: {:#x} not sent ({:?})\n", + endpoint, + msg, + e + ), + } + } + (sent, sent & running) + } + + /// Waits for the answers of the endpoints in `eps` (by index), with one deadline for + /// them all, as the shutdown does, so a firmware that stopped answering costs one + /// [`AFK_SLEEP_TIMEOUT_MS`]. Returns those that did not answer. + fn sleep_wait_answers(&self, eps: u32) -> u32 { + let mut left = msecs_to_jiffies(AFK_SLEEP_TIMEOUT_MS); + let mut missing = 0u32; + for index in 0..AOP_S2R_UNANSWERED_EPS { + if eps & (1 << index) == 0 { + continue; + } + let (answer, rest) = self.ep_sleep[index as usize].wait_jiffies(left); + left = rest; + if answer.is_none() { + missing |= 1 << index; + } + } + missing + } + + /// [`AOP_S2R_UNANSWERED`]: the stops, the started endpoints' answers and the idle notice; + /// nothing refuses. + fn sleep_enter_unanswered(&self) { + let all = (1u32 << AOP_S2R_UNANSWERED_EPS) - 1; + let (sent, started) = self.sleep_send_unanswered(all, AFK_MSG_SLEEP); + self.sleep_stopped.store(sent, Relaxed); + let missing = self.sleep_wait_answers(started); + if missing != 0 { + dev_warn!( + self.dev, + "Endpoints did not answer their stop within {} ms (mask {:#x}, bit 0 = endpoint {:#04x}), sleeping anyway\n", + AFK_SLEEP_TIMEOUT_MS, + missing, + AFK_ENDPOINT_START + ); + } + match self.ap_power(false) { + Ok(()) => self.ap_idle.store(true, Relaxed), + Err(e) => dev_warn!( + self.dev, + "Sleep notice not answered ({:?}), sleeping anyway\n", + e + ), + } + } + + /// [`AOP_S2R_UNANSWERED`]: the stops and the idle notice go out at the sleep's .prepare, + /// right after the GPU firmware's stop, as the T6000's sleep has them: from there on + /// nothing gives the sleep up for a wakeup event. The wake notice and the starts go out at + /// the sleep's .finish, which follows every .prepare, given up or not: after the PMP's + /// restart, right before the GPU firmware's, and before the SMC is told of the wake. + /// Without the sleep core they stay in suspend_late and resume. + fn stop_at_prepare_register(&self) { + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + { + let finish = self.finish_nb.0.get(); + let prepare = self.prepare_nb.0.get(); + // SAFETY: `finish` and `prepare` live as long as `self`, whose removal unregisters + // them first; they aren't registered yet, so nothing else reads them. + let ret = unsafe { + (*finish).notifier_call = Some(aop_finish_notify); + // Before the GPU's, which has the default priority 0. + (*finish).priority = 1; + (*prepare).notifier_call = Some(aop_prepare_notify); + // After the GPU's, which has the default priority 0. + (*prepare).priority = -1; + let ret = apple_sleep_finish_notifier_register(finish); + if ret != 0 { + ret + } else { + let ret = apple_sleep_prepare_notifier_register(prepare); + if ret != 0 { + apple_sleep_finish_notifier_unregister(finish); + } + ret + } + }; + if ret == 0 { + self.stop_at_prepare.store(true, Release); + } else { + dev_warn!(self.dev, "Sleep stops stay in suspend_late ({})\n", ret); + } + } + } + + fn stop_at_prepare_unregister(&self) { + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + if self.stop_at_prepare.xchg(false, Acquire) { + // SAFETY: registered by `stop_at_prepare_register()`; each returns once no call of + // it runs. + unsafe { + apple_sleep_prepare_notifier_unregister(self.prepare_nb.0.get()); + apple_sleep_finish_notifier_unregister(self.finish_nb.0.get()); + } + } + } + /// Tells the firmware about the AP's power state. Waits with the RTKit lock /// dropped, as the answer shares a worker with messages that take it. fn ap_power(&self, on: bool) -> Result<()> { @@ -1851,6 +1996,11 @@ impl AopData { dev_err!(self.dev, "Wake notice not answered ({:?})", e); } } + if self.s2r_notice & AOP_S2R_UNANSWERED != 0 { + let _ = self.sleep_send_unanswered(stopped, AFK_MSG_START); + self.sleeping.store(false, Release); + return; + } let order = AfkOrder::new(&self.wake_endpoints); for endpoint in order { let Some(index) = afk_endpoint_index(endpoint) else { @@ -1887,8 +2037,12 @@ impl AopData { drop(turn.lock()); } - let mut result = Ok(()); let notice = self.s2r_notice; + if notice & AOP_S2R_UNANSWERED != 0 { + self.sleep_enter_unanswered(); + return Ok(()); + } + let mut result = Ok(()); // An empty order is every endpoint: without the stops, the loop doesn't run. let stops = AfkOrder::new(&self.sleep_endpoints) .take_while(|_| notice & AOP_S2R_ENDPOINTS != 0); @@ -2506,6 +2660,7 @@ impl AOP for AopData { return; } } + self.stop_at_prepare_unregister(); // No registration is queued after this point, so once the queue is // empty the list of children is complete. self.registration_queue.drain(); @@ -3094,6 +3249,15 @@ struct AopHwConfig { const AOP_S2R_ENDPOINTS: u8 = 1 << 0; /// [`AopHwConfig::s2r_notice`]: the AP's idle and on notices around a sleep. const AOP_S2R_AP_IDLE: u8 = 1 << 1; +/// [`AopHwConfig::s2r_notice`], with both of the above, as macOS does on T6000: every AFK +/// endpoint from 0x20 to 0x2b is stopped, started or not, all at once. The AP's idle notice +/// follows once the started ones have answered their stop, or [`AFK_SLEEP_TIMEOUT_MS`] after +/// the stops for all of them together; the others are not waited for. Neither can refuse the +/// sleep. The on notice only follows an answered idle notice; the endpoints that took the stop +/// start again either way. +const AOP_S2R_UNANSWERED: u8 = 1 << 2; +/// The endpoints [`AOP_S2R_UNANSWERED`] stops, from [`AFK_ENDPOINT_START`]. +const AOP_S2R_UNANSWERED_EPS: u8 = 12; impl AopHwConfig { /// The configuration to start the block with, given whether the @@ -3178,7 +3342,7 @@ const HW_CFG_T6000: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, - s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE | AOP_S2R_UNANSWERED, }; const HW_CFG_T6020: AopHwConfig = AopHwConfig { ec0p: 0x0100_00000000, @@ -3360,16 +3524,76 @@ unsafe extern "C" fn aop_suspend_late(dev: *mut bindings::device) -> c_int { return 0; } // SAFETY: by this function's contract. - match unsafe { aop_from_dev(dev) }.sleep_enter() { + let data = unsafe { aop_from_dev(dev) }; + // Stopped at the sleep's .prepare already. + if data.stop_at_prepare.load(Acquire) { + return 0; + } + match data.sleep_enter() { Ok(()) => 0, Err(e) => e.to_errno(), } } +/// A notifier block of [`AopData::stop_at_prepare_register()`]. +#[repr(transparent)] +struct SleepNotifier(Opaque); + +// SAFETY: written only before its registration; then only the notifier chain uses it, under the +// chain's own lock. +unsafe impl Send for SleepNotifier {} +// SAFETY: as above. +unsafe impl Sync for SleepNotifier {} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +extern "C" { + fn apple_sleep_prepare_notifier_register(nb: *mut bindings::notifier_block) -> c_int; + fn apple_sleep_prepare_notifier_unregister(nb: *mut bindings::notifier_block); + fn apple_sleep_finish_notifier_register(nb: *mut bindings::notifier_block) -> c_int; + fn apple_sleep_finish_notifier_unregister(nb: *mut bindings::notifier_block); +} + +/// # Safety +/// +/// Called by the sleep's .prepare chain with the `prepare_nb` of a registered [`AopData`]. +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +unsafe extern "C" fn aop_prepare_notify( + nb: *mut bindings::notifier_block, + _action: c_ulong, + _data: *mut c_void, +) -> c_int { + // SAFETY: `nb` is the `prepare_nb` of a live `AopData`: its removal unregisters it before + // anything of it goes. + let data = unsafe { &*kernel::container_of!(nb.cast::(), AopData, prepare_nb) }; + // As at suspend_late: for this firmware nothing refuses. + if let Err(e) = data.sleep_enter() { + dev_warn!(data.dev, "Sleep stops failed ({:?})\n", e); + } + bindings::NOTIFY_OK as c_int +} + +/// # Safety +/// +/// Called by the sleep's .finish chain with the `finish_nb` of a registered [`AopData`]. +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +unsafe extern "C" fn aop_finish_notify( + nb: *mut bindings::notifier_block, + _action: c_ulong, + _data: *mut c_void, +) -> c_int { + // SAFETY: `nb` is the `finish_nb` of a live `AopData`: its removal unregisters it before + // anything of it goes. + let data = unsafe { &*kernel::container_of!(nb.cast::(), AopData, finish_nb) }; + // What the .prepare chain stopped; the resume after it then finds nothing to undo. + data.sleep_undo(); + bindings::NOTIFY_OK as c_int +} + /// # Safety /// /// Called by the PM core with a bound AOP device. unsafe extern "C" fn aop_resume(dev: *mut bindings::device) -> c_int { + // Nothing left to undo where the sleep's .finish chain already did it. // SAFETY: by this function's contract. unsafe { aop_from_dev(dev) }.sleep_undo(); 0 @@ -3517,6 +3741,9 @@ impl platform::Driver for AopDriver { } return Err(e); } + if cfg.s2r_notice & AOP_S2R_UNANSWERED != 0 { + data.stop_at_prepare_register(); + } probe_guard.dismiss(); let data = data as Arc; Ok(Self(data)) diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index 295a0ea4308ab..0eb68623db8b3 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -1100,6 +1100,23 @@ void apple_mbox_set_recv_enabled(struct apple_mbox *mbox, bool enabled) } EXPORT_SYMBOL_GPL(apple_mbox_set_recv_enabled); +/* + * Bit 0 of the send control word, the inbox enable (the ADT's inbox-ctrl-enable-mask). A + * client whose firmware lost its power with the mailbox sets it before the firmware starts + * again, as macOS does when it starts the processor. Written only if it reads otherwise. + */ +void apple_mbox_set_send_enabled(struct apple_mbox *mbox, bool enabled) +{ + u32 val = readl(mbox->regs + mbox->hw->a2i_control); + + if (!!(val & APPLE_ASC_MBOX_CONTROL_RECV_ENABLE) == enabled) + return; + val = enabled ? val | APPLE_ASC_MBOX_CONTROL_RECV_ENABLE : + val & ~APPLE_ASC_MBOX_CONTROL_RECV_ENABLE; + writel(val, mbox->regs + mbox->hw->a2i_control); +} +EXPORT_SYMBOL_GPL(apple_mbox_set_send_enabled); + int apple_mbox_ans_idle_status(struct apple_mbox *mbox, u32 *status) { if (!of_device_is_compatible(mbox->dev->of_node, "apple,t6050-asc-mailbox")) diff --git a/drivers/soc/apple/pm.rs b/drivers/soc/apple/pm.rs index d479bf866ae4c..3a5780bcc01c4 100644 --- a/drivers/soc/apple/pm.rs +++ b/drivers/soc/apple/pm.rs @@ -48,8 +48,17 @@ extern "C" { msg1: u32, reply: u64, mask: u64, + answer_ms: u32, + flags: u32, ) -> c_int; fn sep_pm_commit_finish(dev: *mut c_void) -> c_int; + fn sep_pm_power_on(dev: *mut c_void) -> c_int; + fn sep_pm_power_release(dev: *mut c_void); + fn sep_pm_dart_gate(dev: *mut c_void) -> c_int; + fn sep_pm_dart_ungate(dev: *mut c_void) -> c_int; + fn sep_pm_dart_island_save(dev: *mut c_void) -> c_int; + fn sep_pm_dart_island_restore(dev: *mut c_void) -> c_int; + fn sep_pm_inbox_on(mbox: *mut c_void); pub(crate) static sep_pm_ops: kernel::bindings::dev_pm_ops; } @@ -90,15 +99,52 @@ impl SleepGate { } } +/// `SEP_PM_GATE_ACTUAL` in `pm_shim.c`. +const COMMIT_GATE_ACTUAL: u32 = 1 << 0; +/// `SEP_PM_ANSWER_RESULT` in `pm_shim.c`. +const COMMIT_ANSWER_RESULT: u32 = 1 << 1; +/// `SEP_PM_SOFT_FAIL` in `pm_shim.c`. +const COMMIT_SOFT_FAIL: u32 = 1 << 2; +/// `SEP_PM_PS_NONPOSTED` in `pm_shim.c`. +const COMMIT_PS_NONPOSTED: u32 = 1 << 3; + +/// Outcome of a staged sleep request at device resume. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CommitFinish { + /// No request was staged for this suspend. + Unstaged, + /// Staged, but SLEEP was never sent (or the enclave refused it and stayed awake). + Unsent, + /// SLEEP was sent and the enclave gated its domain. + Sent, + /// SLEEP was sent, then timed out or did not gate (`SEP_PM_SOFT_FAIL`); enclave is lost. + Failed, +} + /// Stages `request` for the irreversible commit, with RX held until physical wake. /// Unsupported providers/transports refuse here; device suspend never sends SLEEP. +/// `sleep` says how long its answer may take and when the enclave is down after it. pub(crate) fn leave_for_commit( dev: &kernel::device::Device, mbox: *mut kernel::bindings::apple_mbox, request: kernel::soc::apple::mailbox::Message, reply: u64, mask: u64, + sleep: &crate::profile::SleepProfile, ) -> Result<()> { + let mut flags = 0; + if sleep.gate_actual { + flags |= COMMIT_GATE_ACTUAL; + } + if sleep.answer_result { + flags |= COMMIT_ANSWER_RESULT; + } + if sleep.commit_soft_fail { + flags |= COMMIT_SOFT_FAIL; + } + if sleep.ps_nonposted { + flags |= COMMIT_PS_NONPOSTED; + } // SAFETY: `dev` is the bound SEP device and `mbox` its mailbox, which outlives the sleep: // `commit_finish` takes the request back at the resume. let rc = unsafe { @@ -109,6 +155,8 @@ pub(crate) fn leave_for_commit( request.msg1, reply, mask, + sleep.answer_ms, + flags, ) }; if rc == 0 { @@ -119,14 +167,18 @@ pub(crate) fn leave_for_commit( } /// Finishes a staged request. A sent request requires a real firmware return; -/// the C boundary terminates an impossible sent-without-sleep unwind. `None` if unstaged. -pub(crate) fn commit_finish(dev: &kernel::device::Device) -> Option { +/// the C boundary terminates an impossible sent-without-sleep unwind. +pub(crate) fn commit_finish(dev: &kernel::device::Device) -> CommitFinish { // SAFETY: `dev` is the bound SEP device. let rc = unsafe { sep_pm_commit_finish(dev.as_raw().cast()) }; - if rc < 0 { - None + if rc == ENOENT.to_errno() { + CommitFinish::Unstaged + } else if rc < 0 { + CommitFinish::Failed + } else if rc == 0 { + CommitFinish::Unsent } else { - Some(rc > 0) + CommitFinish::Sent } } @@ -171,6 +223,70 @@ pub(crate) fn clear_dev_disable(dev: &kernel::device::Device) -> Result<()> { Ok(()) } +/// Powers the enclave's domain on after a deep sleep: its minimum state raised, DEV_DISABLE +/// cleared. The minimum stays raised until [`power_release`], also on failure. +pub(crate) fn power_on(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is the bound SEP device. + let rc = unsafe { sep_pm_power_on(dev.as_raw().cast()) }; + if rc != 0 { + return Err(Error::from_errno(rc)); + } + Ok(()) +} + +/// Drops the minimum state [`power_on`] raised. +pub(crate) fn power_release(dev: &kernel::device::Device) { + // SAFETY: `dev` is the bound SEP device. + unsafe { sep_pm_power_release(dev.as_raw().cast()) }; +} + +/// Enables the enclave's inbox after a deep sleep, if it reads off. +pub(crate) fn inbox_on(mbox: *mut kernel::bindings::apple_mbox) { + // SAFETY: `mbox` is the enclave's live mailbox. + unsafe { sep_pm_inbox_on(mbox.cast()) }; +} + +/// Keeps the DART driver off the enclave's DART after a wake that failed. +pub(crate) fn dart_gate(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is the bound SEP device. + let rc = unsafe { sep_pm_dart_gate(dev.as_raw().cast()) }; + if rc != 0 { + return Err(Error::from_errno(rc)); + } + Ok(()) +} + +/// Allows DART commands again without resetting the DART, after an unsent abort. +pub(crate) fn dart_ungate(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is the bound SEP device. + let rc = unsafe { sep_pm_dart_ungate(dev.as_raw().cast()) }; + if rc != 0 { + return Err(Error::from_errno(rc)); + } + Ok(()) +} + +/// Saves the enclave's DART before the request, where it goes down with the enclave's island. +pub(crate) fn dart_island_save(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is the bound SEP device. + let rc = unsafe { sep_pm_dart_island_save(dev.as_raw().cast()) }; + if rc != 0 { + return Err(Error::from_errno(rc)); + } + Ok(()) +} + +/// Allows the DART's commands again, then resets it and puts back what +/// [`dart_island_save`] saved. +pub(crate) fn dart_island_restore(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is the bound SEP device. + let rc = unsafe { sep_pm_dart_island_restore(dev.as_raw().cast()) }; + if rc != 0 { + return Err(Error::from_errno(rc)); + } + Ok(()) +} + /// Attaches every power domain of a multi-domain SEP node and keeps them on /// across system sleep; see `pm_shim.c`. Must run before the enclave is first /// spoken to. @@ -232,6 +348,10 @@ unsafe extern "C" fn pm_event(entering: bool) { // `unregister` only after `sep_pm_unregister` has waited out any running // notifier call, so it is live for this borrow. let sep = unsafe { as ForeignOwnable>::borrow(ptr) }; + // Before the holds go: requests held for the sleep go to an enclave that is back. + if !entering && sep.sleep_exit_after_thaw() { + SepData::queue_stac_online(sep.into()); + } sleep_event(&*sep, entering); } diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index a7d965603a5ae..9a6931a81e3fc 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -36,6 +36,8 @@ /* The state word of a PMGR power domain, as pmgr-pwrstate has it. */ #define SEP_PS_DEV_DISABLE BIT(10) #define SEP_PS_ACTUAL GENMASK(7, 4) +#define SEP_PS_FLAGS (BIT(8) | BIT(9)) +#define SEP_PS_MIN GENMASK(19, 16) /* * After its sleep request, the enclave has gone down: DEV_DISABLE where its firmware sets @@ -48,6 +50,25 @@ static bool sep_ps_down(u32 state) (!apple_sleep_sep_dev_disable() && !FIELD_GET(SEP_PS_ACTUAL, state)); } +/* + * Only the answer ends the wait for it, and after it the domain counts as down only once its + * actual state reads 0: what macOS waits for on T6000. Without the flag, DEV_DISABLE ends + * either wait. + */ +#define SEP_PM_GATE_ACTUAL BIT(0) +/* + * A nonzero reply result means the enclave refused and stayed awake: refuse the sleep + * cleanly, without panicking. + */ +#define SEP_PM_ANSWER_RESULT BIT(1) +/* + * A post-send timeout or no-gate refuses the sleep instead of panicking, leaving the + * enclave's receive disabled and held so resume marks it lost (EAGAIN). + */ +#define SEP_PM_SOFT_FAIL BIT(2) +/* The power-state word is mapped non-posted where the bus says so. */ +#define SEP_PM_PS_NONPOSTED BIT(3) + /* One-shot precommit test: no SLEEP request or commit coprocessor stop. */ static bool sleep_refuse_before_send; module_param(sleep_refuse_before_send, bool, 0644); @@ -225,9 +246,11 @@ static struct sep_pm_commit { void __iomem *ps; struct apple_mbox_msg request; u64 reply, reply_mask; + unsigned int answer_max_us; + u32 flags; void (*rx)(struct apple_mbox *mbox, struct apple_mbox_msg msg, void *cookie); void *cookie; - bool registered, sent, answered, gate_valid; + bool registered, sent, failed, answered, gate_valid; u8 reply_result; unsigned int answer_us; int gate_ret; @@ -275,6 +298,7 @@ static int sep_pm_commit_stop(void *data) int ret = 0; c->sent = false; + c->failed = false; c->answered = false; c->answer_us = 0; c->reply_result = 0xff; @@ -313,8 +337,9 @@ static int sep_pm_commit_stop(void *data) if (ret) goto out; c->sent = true; - while (!c->answered && !((c->state = readl(c->ps)) & SEP_PS_DEV_DISABLE) && - c->answer_us < SEP_PM_TIMEOUT_US) { + while (!c->answered && c->answer_us < c->answer_max_us && + ((c->flags & SEP_PM_GATE_ACTUAL) || + !((c->state = readl(c->ps)) & SEP_PS_DEV_DISABLE))) { ret = apple_mbox_poll_one(c->mbox); if (ret < 0) break; @@ -333,24 +358,57 @@ static int sep_pm_commit_stop(void *data) } /* Preserve the failure reason without another hardware query. */ if (ret >= 0 && !c->answered) - ret = c->state & SEP_PS_DEV_DISABLE ? -EHOSTDOWN : -ETIMEDOUT; - if (c->answered && c->reply_result) + ret = !(c->flags & SEP_PM_GATE_ACTUAL) && (c->state & SEP_PS_DEV_DISABLE) ? + -EHOSTDOWN : -ETIMEDOUT; + if (c->answered && c->reply_result) { + if (c->flags & SEP_PM_ANSWER_RESULT) { + dev_err(c->dev, + "sleep refused: the enclave refused its sleep request (result %#04x)\n", + c->reply_result); + c->sent = false; + if (prepared) + apple_dart_sleep_restore(c->dart); + return -EIO; + } ret = -EREMOTEIO; - /* Native cmsgSLEEP errors/abort/timeout are fatal, never cancellation. */ - if (ret < 0) + } + /* Native cmsgSLEEP errors/abort/timeout are fatal unless the profile allows soft fail. */ + if (ret < 0) { + if (c->flags & SEP_PM_SOFT_FAIL) { + apple_mbox_set_recv_enabled(c->mbox, false); + c->failed = true; + dev_err(c->dev, + "sleep refused: SEP SLEEP failed after send (ret %d reply_valid %d result %#x state %#x)\n", + ret, c->answered, c->reply_result, c->state); + return ret; + } panic("SEP SLEEP failed after send: ret %d reply_valid %d result %#x state %#x", ret, c->answered, c->reply_result, c->state); + } /* * Native success-only receive close. No mailbox access follows it. The * held RX IRQ adapts native workloop exclusion; access-until-close is * the native contract, not proved atomic by the preceding PMGR sample. */ apple_mbox_set_recv_enabled(c->mbox, false); - c->gate_ret = readl_poll_timeout_atomic(c->ps, c->state, sep_ps_down(c->state), - SEP_PM_POLL_US, SEP_PM_TIMEOUT_US); + if (c->flags & SEP_PM_GATE_ACTUAL) + c->gate_ret = readl_poll_timeout_atomic(c->ps, c->state, + !FIELD_GET(SEP_PS_ACTUAL, c->state), + SEP_PM_POLL_US, SEP_PM_TIMEOUT_US); + else + c->gate_ret = readl_poll_timeout_atomic(c->ps, c->state, sep_ps_down(c->state), + SEP_PM_POLL_US, SEP_PM_TIMEOUT_US); c->gate_valid = true; - if (c->gate_ret) + if (c->gate_ret) { + if (c->flags & SEP_PM_SOFT_FAIL) { + c->failed = true; + dev_err(c->dev, + "sleep refused: SEP did not power-gate after send (%d, state %#x)\n", + c->gate_ret, c->state); + return c->gate_ret; + } panic("SEP SLEEP did not gate after send: %d state %#x", c->gate_ret, c->state); + } return 0; } @@ -358,9 +416,11 @@ static int sep_pm_commit_stop(void *data) /* * From .suspend, with the enclave drained and its receive interrupt held: leaves the * request in @msg0 and @msg1 to the irreversible commit. Its answer is the message - * whose @mask bits read @reply. Unsupported paths must refuse without sending. + * whose @mask bits read @reply, waited for up to @answer_ms; @flags are SEP_PM_*. + * Unsupported paths must refuse without sending. */ -int sep_pm_commit_prepare(void *ptr, void *mbox, u64 msg0, u32 msg1, u64 reply, u64 mask) +int sep_pm_commit_prepare(void *ptr, void *mbox, u64 msg0, u32 msg1, u64 reply, u64 mask, + unsigned int answer_ms, u32 flags) { struct sep_pm_commit *c = &sep_pm_commit; struct device *dev = ptr; @@ -395,7 +455,14 @@ int sep_pm_commit_prepare(void *ptr, void *mbox, u64 msg0, u32 msg1, u64 reply, ret = -ENODEV; goto err; } - c->ps = ioremap(res.start + offset, 4); + /* + * Where the profile asks for it and the bus is non-posted (T6000, where a posted read + * of the PMGR was seen to end in an SError); every other SoC keeps the posted mapping. + */ + if ((flags & SEP_PM_PS_NONPOSTED) && (res.flags & IORESOURCE_MEM_NONPOSTED)) + c->ps = ioremap_np(res.start + offset, 4); + else + c->ps = ioremap(res.start + offset, 4); if (!c->ps) { ret = -ENOMEM; goto err; @@ -406,7 +473,10 @@ int sep_pm_commit_prepare(void *ptr, void *mbox, u64 msg0, u32 msg1, u64 reply, c->request.msg1 = msg1; c->reply = reply; c->reply_mask = mask; + c->answer_max_us = answer_ms * USEC_PER_MSEC; + c->flags = flags; c->sent = false; + c->failed = false; /* Resume may follow a pre-tell abort: observations belong to this attempt. */ c->answered = false; c->answer_us = 0; @@ -431,27 +501,31 @@ int sep_pm_commit_prepare(void *ptr, void *mbox, u64 msg0, u32 msg1, u64 reply, return ret; } -/* After the sleep, refused or not: 1 if the request went out, 0 if not, <0 if none was left. */ +/* + * After the sleep, refused or not: 1 if the request went out and gated, 0 if unsent or + * cleanly refused by the enclave, -EIO if a post-send soft failure left the enclave lost, + * -ENOENT if none was left. + */ int sep_pm_commit_finish(void *ptr) { struct sep_pm_commit *c = &sep_pm_commit; if (!c->registered || c->dev != ptr) return -ENOENT; - if (c->sent && !pm_resume_via_firmware()) + if (c->sent && !c->failed && !pm_resume_via_firmware()) panic("SEP SLEEP was sent without a physical sleep/wake"); apple_sleep_enclave_unregister(c->dev); c->registered = false; dev_dbg(c->dev, - "sleep commit finished: sent=%d reply_valid=%d result=%#x answer_us=%u gate_valid=%d gate_ret=%d state=%#x\n", - c->sent, c->answered, c->reply_result, c->answer_us, + "sleep commit finished: sent=%d failed=%d reply_valid=%d result=%#x answer_us=%u gate_valid=%d gate_ret=%d state=%#x\n", + c->sent, c->failed, c->answered, c->reply_result, c->answer_us, c->gate_valid, c->gate_ret, c->state); iounmap(c->ps); c->ps = NULL; put_device(c->dart); c->dart = NULL; - return c->sent; + return c->failed ? -EIO : c->sent; } /* @@ -519,6 +593,144 @@ const struct dev_pm_ops sep_pm_ops = { .suspend_noirq = pm_sleep_ptr(sep_pm_suspend_noirq), }; +/* + * macOS's wake raises the minimum state of the enclave's power state to on and + * waits up to 8 ms for the domain; the target is left as it is. A deep sleep also leaves + * DEV_DISABLE set, which is cleared as a reset deassert does, before anything reads the + * mailbox or the DART. The status bits 8 and 9 are written as 0, which leaves them as they + * are. The minimum stays raised until sep_pm_power_release(). + */ +int sep_pm_power_on(void *ptr) +{ + struct device *dev = ptr; + struct regmap *map; + u32 off, val = 0, raised; + int ret; + + ret = sep_pm_domain(dev, &map, &off); + if (ret) + return ret; + + regmap_update_bits(map, off, SEP_PS_FLAGS | SEP_PS_MIN, SEP_PS_MIN); + ret = regmap_read_poll_timeout(map, off, val, + FIELD_GET(SEP_PS_ACTUAL, val) == 0xf, 100, 20000); + raised = val; + if (ret && (val & SEP_PS_DEV_DISABLE)) { + regmap_update_bits(map, off, SEP_PS_FLAGS | SEP_PS_DEV_DISABLE, 0); + ret = regmap_read_poll_timeout(map, off, val, + FIELD_GET(SEP_PS_ACTUAL, val) == 0xf, 100, 20000); + } + if (!ret && (val & SEP_PS_DEV_DISABLE)) { + regmap_update_bits(map, off, SEP_PS_FLAGS | SEP_PS_DEV_DISABLE, 0); + regmap_read(map, off, &val); + } + if (!ret && (FIELD_GET(SEP_PS_ACTUAL, val) != 0xf || (val & SEP_PS_DEV_DISABLE))) + ret = -EIO; + if (ret) { + /* The word with the minimum raised, and the last one read: which bits stayed */ + dev_warn(dev, "the enclave's domain did not come on: state %#x, then %#x (%d)\n", + raised, val, ret); + sep_pm_power_release(ptr); + } + + return ret; +} + +void sep_pm_power_release(void *ptr) +{ + struct device *dev = ptr; + struct regmap *map; + u32 off; + + if (sep_pm_domain(dev, &map, &off)) + return; + regmap_update_bits(map, off, SEP_PS_FLAGS | SEP_PS_MIN, 0); +} + +/* The enclave's inbox after a deep sleep, enabled as macOS does if it reads off. */ +void sep_pm_inbox_on(void *mbox) +{ + apple_mbox_set_send_enabled(mbox, true); +} + +/* + * Keeps the DART driver off a DART whose domain the enclave left off, as macOS takes the + * mapper inactive: after a wake that failed to start the enclave again. + */ +int sep_pm_dart_gate(void *ptr) +{ + struct device *dart = sep_pm_dart(ptr); + int ret; + + if (!dart) + return -ENODEV; + ret = apple_dart_quiesce_commands(dart); + put_device(dart); + + return ret; +} + +/* + * Allows DART commands again without resetting the block, when a staged sleep was refused + * before the enclave was told and its island kept its power. + */ +int sep_pm_dart_ungate(void *ptr) +{ + struct device *dart = sep_pm_dart(ptr); + int ret; + + if (!dart) + return -ENODEV; + ret = apple_dart_resume_commands(dart); + put_device(dart); + + return ret; +} + +/* + * T6000: the enclave's DART is in the enclave's own power island and loses its registers with + * it. They are saved before the request, and the DART's commands + * are gated once the enclave has answered (sep_pm_dart_gate()), as macOS takes the mapper + * inactive: then no TLB command reaches a block without power, and the DART's own callbacks + * leave it alone. Before the enclave resumes, the commands are allowed again and the DART is + * reset and its translations put back, as after a sleep that cut its power. + */ +static bool sep_pm_island_saved; + +int sep_pm_dart_island_save(void *ptr) +{ + struct device *dart = sep_pm_dart(ptr); + int ret; + + /* Only this sleep's save may be written back: an earlier one's translations are stale. */ + WRITE_ONCE(sep_pm_island_saved, false); + if (!dart) + return -ENODEV; + ret = apple_dart_state_save(dart); + if (!ret) + WRITE_ONCE(sep_pm_island_saved, true); + put_device(dart); + + return ret; +} + +int sep_pm_dart_island_restore(void *ptr) +{ + struct device *dart = sep_pm_dart(ptr); + int ret = -EINVAL; + + if (!dart) + return -ENODEV; + if (READ_ONCE(sep_pm_island_saved)) { + ret = apple_dart_resume_commands(dart); + if (!ret) + ret = apple_dart_state_restore(dart); + } + put_device(dart); + + return ret; +} + int sep_pm_register(void *ptr, void (*event)(bool entering), int (*sleep)(void), void (*wake)(void), bool (*told)(void)) { diff --git a/drivers/soc/apple/pmp-export.c b/drivers/soc/apple/pmp-export.c index 87c5144392ebc..54695941c8daa 100644 --- a/drivers/soc/apple/pmp-export.c +++ b/drivers/soc/apple/pmp-export.c @@ -1,10 +1,16 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include #include #include +#include #include +#include #include #include #include +#include +#include #include #include #include @@ -22,6 +28,262 @@ static struct device *pmp_device; /* The firmware is stopped for a system sleep. */ static bool pmp_asleep; +/* + * The reset vector (DT reg "iorvbar"), where one is described: iBoot points it at the + * firmware SRAM and locks it, and a sleep that cuts the PMP's power resets it. + */ +#define PMP_IORVBAR_LOCK BIT_ULL(0) +static void __iomem *pmp_iorvbar; +static u64 pmp_iorvbar_boot; + +static void apple_pmp_iorvbar_init(struct device *dev) +{ + int idx = of_property_match_string(dev->of_node, "reg-names", "iorvbar"); + + pmp_iorvbar = idx >= 0 ? of_iomap(dev->of_node, idx) : NULL; + if (pmp_iorvbar) + pmp_iorvbar_boot = readq(pmp_iorvbar); +} + +/* Before the firmware starts again: what iBoot left, unless it is still there, locked. */ +static void apple_pmp_iorvbar_restore(struct device *dev) +{ + u64 now; + + if (!pmp_iorvbar) + return; + now = readq(pmp_iorvbar); + if (now & PMP_IORVBAR_LOCK) + return; + writeq(pmp_iorvbar_boot, pmp_iorvbar); + dev_dbg(dev, "reset vector %#llx after the sleep, %#llx written back\n", now, + pmp_iorvbar_boot); +} + +/* + * T6000 power-cycles its PMP for a deep sleep, as macOS does: at the stop, once its + * CPU is idle, its own power state and then its SRAM's go to 0, the SRAM copied in between; + * at the start both come back up, the SRAM first, and the firmware boots from its reset vector + * and sets itself up again. The memory clock is the PMP's while it has power: the sleep's + * quiesce steps it down only once the PMP's power state reads 0. Its DART goes down and comes + * back with it, as macOS saves and restores it around the power cut: its interrupt off and + * its state saved once the CPU stopped, written back before the CPU runs again. + */ +#define PMP_PS_TARGET GENMASK(3, 0) +#define PMP_PS_ACTUAL GENMASK(7, 4) +#define PMP_PS_WAS_GATED GENMASK(9, 8) /* write one to clear */ +#define PMP_PS_DEV_DISABLE BIT(10) +#define PMP_PS_BUSY BIT(11) +#define PMP_PS_AUTO_MIN GENMASK(19, 16) +#define PMP_PS_AUTO_ENABLE BIT(28) +#define PMP_PS_BIT30 BIT(30) +#define PMP_PS_ACTIVE 0xf +/* 0x2ee00 ticks of 24 MHz */ +#define PMP_PS_TIMEOUT_US 8000 + +/* In the ASC, after the CPU control word */ +#define PMP_ASC_CPU_STATUS 4 +#define PMP_ASC_CPU_STATUS_IDLE GENMASK(1, 0) +#define PMP_ASC_CPU_RUN BIT(4) + +struct apple_pmp_ps { + void __iomem *reg; + u32 saved; +}; + +/* What the commit's stop left: the start after the sleep follows it. */ +enum apple_pmp_pc_state { + PMP_PC_NONE, + /* Its idle was refused: the firmware runs on. */ + PMP_PC_RUNNING, + /* Idled, its CPU never idle: not powered down, and it cannot boot again. */ + PMP_PC_IDLED, + /* Idled, stopped, both power states at 0. */ + PMP_PC_DOWN, +}; + +static struct { + struct apple_pmp_ps pmp, sram; + enum apple_pmp_pc_state state; + /* The PMP's DART (its iommus) and that DART's interrupt */ + struct device *dart; + int dart_irq; +} pmp_pc; + +static bool apple_pmp_pc_described(void) +{ + return pmp_pc.pmp.reg && pmp_pc.sram.reg && pmp_pc.dart; +} + +/* + * The DART's own runtime PM callbacks, called directly: its runtime PM state is the system + * sleep's by now, and the stop runs with interrupts off. + */ +static int apple_pmp_dart(bool up) +{ + const struct dev_pm_ops *pm = pmp_pc.dart->driver ? pmp_pc.dart->driver->pm : NULL; + int ret = -ENODEV; + + if (!up) { + /* One CPU, interrupts off: no handler of it can be running */ + disable_irq_nosync(pmp_pc.dart_irq); + if (pm && pm->runtime_suspend) + ret = pm->runtime_suspend(pmp_pc.dart); + return ret; + } + if (pm && pm->runtime_resume) + ret = pm->runtime_resume(pmp_pc.dart); + enable_irq(pmp_pc.dart_irq); + return ret; +} + +static void apple_pmp_dart_init(struct device *dev) +{ + struct device_node *np = of_parse_phandle(dev->of_node, "iommus", 0); + struct platform_device *pdev = np ? of_find_device_by_node(np) : NULL; + int irq; + + of_node_put(np); + if (!pdev) + return; + irq = platform_get_irq(pdev, 0); + if (irq < 0) { + put_device(&pdev->dev); + return; + } + pmp_pc.dart = &pdev->dev; + pmp_pc.dart_irq = irq; +} + +static void __iomem *apple_pmp_ps_map(struct device_node *ps_np) +{ + struct device_node *parent = of_get_parent(ps_np); + struct resource res; + void __iomem *reg = NULL; + u32 off; + + if (parent && !of_address_to_resource(parent, 0, &res) && + !of_property_read_u32(ps_np, "reg", &off)) + reg = ioremap_np(res.start + off, 4); + of_node_put(parent); + return reg; +} + +/* The PMP's power state (its power domain) and, next to it, the one labelled pms_sram. */ +static void apple_pmp_pc_init(struct device *dev) +{ + struct device_node *ps_np, *parent, *child; + const char *label; + + /* A PMP whose reset vector and SRAM the DT says survive its power cut */ + if (of_property_match_string(dev->of_node, "reg-names", "iorvbar") < 0 || + !of_property_present(dev->of_node, "apple,sram-keep")) + return; + ps_np = of_parse_phandle(dev->of_node, "power-domains", 0); + if (!ps_np) + return; + pmp_pc.pmp.reg = apple_pmp_ps_map(ps_np); + parent = of_get_parent(ps_np); + of_node_put(ps_np); + for_each_child_of_node(parent, child) { + if (!of_property_read_string(child, "label", &label) && + !strcmp(label, "pms_sram")) { + pmp_pc.sram.reg = apple_pmp_ps_map(child); + of_node_put(child); + break; + } + } + of_node_put(parent); + if (pmp_pc.pmp.reg && pmp_pc.sram.reg) + apple_pmp_dart_init(dev); + if (apple_pmp_pc_described()) + return; + if (pmp_pc.pmp.reg) + iounmap(pmp_pc.pmp.reg); + if (pmp_pc.sram.reg) + iounmap(pmp_pc.sram.reg); + memset(&pmp_pc, 0, sizeof(pmp_pc)); +} + +static void apple_pmp_pc_exit(void) +{ + if (pmp_pc.pmp.reg) + iounmap(pmp_pc.pmp.reg); + if (pmp_pc.sram.reg) + iounmap(pmp_pc.sram.reg); + if (pmp_pc.dart) + put_device(pmp_pc.dart); + memset(&pmp_pc, 0, sizeof(pmp_pc)); +} + +static int apple_pmp_ps_wait(struct apple_pmp_ps *ps, u32 mask, u32 val) +{ + u32 v; + + return readl_poll_timeout_atomic(ps->reg, v, (v & mask) == val, 1, PMP_PS_TIMEOUT_US); +} + +/* The PMGR waits out BUSY after each write of a lower target, as macOS does. */ +static int apple_pmp_ps_write(struct apple_pmp_ps *ps, u32 val) +{ + writel(val, ps->reg); + if (FIELD_GET(PMP_PS_TARGET, val) == PMP_PS_ACTIVE) + return 0; + return apple_pmp_ps_wait(ps, PMP_PS_BUSY, 0); +} + +/* The lowest state the PMGR may take the domain to by itself */ +static void apple_pmp_ps_set_auto_min(struct apple_pmp_ps *ps, u32 level) +{ + u32 r = readl(ps->reg); + + apple_pmp_ps_write(ps, (r & ~(PMP_PS_AUTO_MIN | PMP_PS_WAS_GATED)) | + FIELD_PREP(PMP_PS_AUTO_MIN, level)); +} + +/* A domain's target state: auto PM is left only from the active state */ +static int apple_pmp_ps_set_level(struct apple_pmp_ps *ps, u32 level, bool auto_enable) +{ + u32 r = readl(ps->reg), w; + int ret; + + if (FIELD_GET(PMP_PS_TARGET, r) == level && !!(r & PMP_PS_AUTO_ENABLE) == auto_enable && + !(r & (PMP_PS_BIT30 | PMP_PS_DEV_DISABLE))) + return 0; + if (r & PMP_PS_AUTO_ENABLE) { + if (FIELD_GET(PMP_PS_TARGET, r) != PMP_PS_ACTIVE) + return -EINVAL; + w = r & ~(PMP_PS_AUTO_ENABLE | PMP_PS_WAS_GATED); + apple_pmp_ps_write(ps, w); + apple_pmp_ps_wait(ps, PMP_PS_ACTUAL, FIELD_PREP(PMP_PS_ACTUAL, PMP_PS_ACTIVE)); + } else { + w = r & ~PMP_PS_WAS_GATED; + } + w = (w & ~PMP_PS_TARGET) | level; + apple_pmp_ps_write(ps, level == PMP_PS_ACTIVE ? w : w | PMP_PS_WAS_GATED); + ret = apple_pmp_ps_wait(ps, PMP_PS_ACTUAL, FIELD_PREP(PMP_PS_ACTUAL, level)); + if (auto_enable) { + w |= PMP_PS_AUTO_ENABLE; + apple_pmp_ps_write(ps, w); + } + if (w & PMP_PS_BIT30) { + w &= ~PMP_PS_BIT30; + apple_pmp_ps_write(ps, w); + } + if (w & PMP_PS_DEV_DISABLE) { + w &= ~PMP_PS_DEV_DISABLE; + apple_pmp_ps_write(ps, w); + } + return ret; +} + +/* As the PMGR powers a device up: its auto-min level, then active */ +static int apple_pmp_ps_power_up(struct apple_pmp_ps *ps) +{ + apple_pmp_ps_set_auto_min(ps, FIELD_GET(PMP_PS_AUTO_MIN, ps->saved)); + return apple_pmp_ps_set_level(ps, PMP_PS_ACTIVE, ps->saved & PMP_PS_AUTO_ENABLE); +} + int apple_pmp_register(struct device *dev, const void *data) { int ret = 0; @@ -32,6 +294,8 @@ int apple_pmp_register(struct device *dev, const void *data) else { pmp_data = data; pmp_device = dev; + apple_pmp_iorvbar_init(dev); + apple_pmp_pc_init(dev); } return ret; } @@ -42,6 +306,10 @@ void apple_pmp_unregister(const void *data) if (pmp_data == data) { pmp_data = NULL; pmp_device = NULL; + if (pmp_iorvbar) + iounmap(pmp_iorvbar); + pmp_iorvbar = NULL; + apple_pmp_pc_exit(); } } @@ -198,6 +466,46 @@ EXPORT_SYMBOL_GPL(apple_pmp_t6030_gpu_ready); static struct apple_pmp_commit_stop pmp_commit; static bool pmp_commit_registered, pmp_commit_used, pmp_rx_held; +/* + * T6000, interrupts off: AP and IOP idle, the outbox off, the CPU idle and stopped, its DART + * down, then its power state to 0, the SRAM copied with the SRAM still powered, and the SRAM's + * power state to 0. A CPU that never goes idle is not powered down: without the power cut it + * cannot start again, and macOS panics there. + */ +static int apple_pmp_t6000_stop(struct apple_pmp_commit_stop *c) +{ + void __iomem *status = c->control + PMP_ASC_CPU_STATUS; + unsigned int us; + size_t i; + u32 st; + int ret; + + apple_rtkit_polled_begin(c->rtk); + ret = apple_rtkit_polled_ap_idle(c->rtk, &us); + if (!ret) + ret = apple_rtkit_polled_iop_idle(c->rtk, &us); + apple_rtkit_polled_end(c->rtk); + if (ret) { + pmp_pc.state = PMP_PC_RUNNING; + return ret; + } + pmp_pc.state = PMP_PC_IDLED; + apple_rtkit_mailbox_recv_off(c->rtk); + ret = readl_poll_timeout_atomic(status, st, st & PMP_ASC_CPU_STATUS_IDLE, 1000, 10000); + if (ret) + return ret; + writel(readl(c->control) & ~PMP_ASC_CPU_RUN, c->control); + apple_pmp_dart(false); + pmp_pc.pmp.saved = readl(pmp_pc.pmp.reg); + pmp_pc.sram.saved = readl(pmp_pc.sram.reg); + pmp_pc.state = PMP_PC_DOWN; + apple_pmp_ps_set_level(&pmp_pc.pmp, 0, false); + for (i = 0; c->sram && i < c->count; i++) + c->words[i] = readl_relaxed(c->sram + 4 * i); + apple_pmp_ps_set_level(&pmp_pc.sram, 0, false); + return 0; +} + /* Interrupts off, one CPU: what apple_pmp_sleep() does, through pointers taken before. */ static int apple_pmp_commit_stop_fn(void *unused) { @@ -206,6 +514,10 @@ static int apple_pmp_commit_stop_fn(void *unused) size_t i; int ret; + /* A T600x PMP's last requests: withdrawn, DVFS at idle (pmp-report.c) */ + apple_pmp_report_sleep_tail(pmp_device); + if (apple_pmp_pc_described()) + return apple_pmp_t6000_stop(c); ret = apple_rtkit_sleep_idle_polled(c->rtk, c->control, &us); apple_rtkit_mailbox_recv_off(c->rtk); if (!c->control) @@ -256,6 +568,16 @@ static bool apple_pmp_commit_available(struct device *dev) if (pmp_commit_registered) return true; + /* + * A T6000 PMP's own stop clears its RUN bit and takes its power away: the sleep driver + * gets no ASC, which it would otherwise stop after it, unpowered. + */ + if (apple_pmp_pc_described()) { + if (apple_sleep_coproc_register(dev, NULL, false, apple_pmp_commit_stop_fn, NULL)) + return false; + pmp_commit_registered = true; + return true; + } /* * On T6030 macOS never reads ASC CPU_STATUS or clears CPU_CONTROL_RUN * at the PMP's commit stop (t29-mac-t331cap-8B9ClHbz, HV recs 1397438..1397459); @@ -367,6 +689,47 @@ static int apple_pmp_suspend_late(struct device *dev) return 0; } +/* + * T6000, after every sleep its stop ran in, given up or not: a PMP that was powered down starts + * cold, its SRAM's power and image first, then its own power, its DART, its reset vector and + * the boot. One whose CPU never went idle cannot boot again; one whose idle was refused runs on. + */ +static int apple_pmp_t6000_start(struct device *dev) +{ + enum apple_pmp_pc_state state = pmp_pc.state; + int ret; + + pmp_pc.state = PMP_PC_NONE; + if (state == PMP_PC_RUNNING) + return 0; + if (state == PMP_PC_IDLED) { + apple_rtkit_set_recv_enabled(pmp_commit.rtk, true); + return -EIO; + } + /* Nothing is written into a domain that did not come up */ + ret = apple_pmp_ps_power_up(&pmp_pc.sram); + if (!ret) + ret = apple_pmp_sram_restore(pmp_data); + if (!ret) + ret = apple_pmp_ps_power_up(&pmp_pc.pmp); + if (ret) { + /* The DART stays down; only its interrupt comes back, as it went */ + enable_irq(pmp_pc.dart_irq); + return ret; + } + apple_pmp_dart(true); + apple_pmp_iorvbar_restore(dev); + if (ret) + return ret; + /* A fresh RTKit state before RUN, so the HELLO cannot be lost */ + ret = apple_pmp_reinit(pmp_data); + if (ret) + return ret; + apple_rtkit_set_recv_enabled(pmp_commit.rtk, true); + writel(readl(pmp_commit.control) | PMP_ASC_CPU_RUN, pmp_commit.control); + return apple_pmp_boot(pmp_data); +} + static int apple_pmp_resume_early(struct device *dev) { int ret; @@ -396,6 +759,17 @@ static int apple_pmp_resume_early(struct device *dev) return 0; } } + if (pmp_pc.state != PMP_PC_NONE) { + pmp_asleep = false; + ret = apple_pmp_t6000_start(dev); + if (ret) { + dev_err(dev, "firmware did not come back from sleep: %d\n", ret); + apple_pmp_report_wake_unstarted(dev); + } else { + apple_pmp_report_wake(dev, true); + } + return 0; + } /* A stopped firmware doesn't restart with its power kept: the next real sleep does. */ if (!pm_resume_via_firmware()) { if (pmp_rx_held) { @@ -407,6 +781,7 @@ static int apple_pmp_resume_early(struct device *dev) } pmp_asleep = false; pmp_rx_held = false; + apple_pmp_iorvbar_restore(dev); ret = apple_pmp_wake(pmp_data); if (ret) dev_err(dev, "firmware did not come back from sleep: %d\n", ret); diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index da82fcd9857be..513ba3ce134d8 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -116,6 +116,9 @@ const OPTIONAL_BOOTARGS: [(&[u8; 4], &CStr); 5] = [ struct PmpAllocation { addr: u64, alloc: Coherent<[u8]>, + /// Given before the firmware's last restart from its reset vector. It stays allocated and + /// mapped, as the firmware may still point there, but no longer counts in the budget. + held_over: bool, } struct IovaTableEntry { @@ -147,6 +150,13 @@ struct PmpState { ioreg_ids: KVec, /// Held from a system sleep's start until its end. sram: Option, + /// The firmware was started again after a system sleep took its power. + restarted: bool, + /// After such a restart it asked for its IOVA table again: it sets itself up from the + /// start, its buffer included. + setup_again: bool, + /// ... and its first REGISTER_IOREG from then on begins a new list. + ioreg_new_list: bool, } impl PmpState { @@ -159,6 +169,9 @@ impl PmpState { ioreg_entries: KVec::with_capacity(340, GFP_KERNEL)?, ioreg_ids: KVec::with_capacity(340, GFP_KERNEL)?, sram: None, + restarted: false, + setup_again: false, + ioreg_new_list: false, }) } fn find_alloc(&self, addr: u64) -> Option { @@ -302,7 +315,15 @@ impl PmpData { } fn get_iova_table(&self) -> Result { let mut state = self.state.lock(); - if state.iova_table.is_some() { + if let Some(table) = &state.iova_table { + // A firmware restarted from its kept SRAM can set itself up again: the PIO + // ranges are still mapped from the first time. + if state.restarted { + let msg = (OPC_GET_IOVA_TABLE | OPC_ACK_MASK) << OPC_SHIFT | table.dma_address(); + state.setup_again = true; + state.ioreg_new_list = true; + return Ok(msg); + } dev_err!(self.dev, "Asked for iova table with existing buffer"); return Err(EIO); } @@ -375,6 +396,7 @@ impl PmpData { PmpAllocation { addr: addr, alloc: iomem, + held_over: false, }, GFP_KERNEL, ) { @@ -387,7 +409,9 @@ impl PmpData { let mut state = self.state.lock(); if let Some(idx) = state.find_alloc(addr) { let freed = state.allocs.swap_remove(idx); - state.alloc_budget.release(freed.alloc.size() as u64); + if !freed.held_over { + state.alloc_budget.release(freed.alloc.size() as u64); + } } else { dev_err!( self.dev, @@ -401,7 +425,7 @@ impl PmpData { } fn set_buf(&self, addr: u64) -> Result { let mut state = self.state.lock(); - if state.value_buf.is_some() { + if state.value_buf.is_some() && !state.setup_again { dev_err!(self.dev, "Setting a buffer when one exists"); return Err(EIO); } @@ -422,6 +446,11 @@ impl PmpData { } fn register_ioreg(&self, addr: u64) -> Result { let mut state = self.state.lock(); + if state.ioreg_new_list { + state.ioreg_new_list = false; + state.ioreg_entries.clear(); + state.ioreg_ids.clear(); + } if !pmp_alloc::ioreg_fits(state.ioreg_entries.len()) { dev_err!( self.dev, @@ -676,6 +705,44 @@ impl PmpData { // and `control` is inside the ASC mapping held by `self`. to_result(unsafe { bindings::apple_rtkit_sleep_return(rtk, control) }) } + /// T6000, after a power cycle and with the CPU stopped: RTKit afresh, its buffers freed, as + /// for a firmware that boots from its reset vector. That firmware sets itself up again: its + /// IOVA table and buffer are asked for once more, and its registers make a new list. It + /// runs from the SRAM kept over the sleep and may still point into what it was given + /// before, so that stays allocated and mapped and is never handed out again; every new + /// request gets a new buffer. The budget counts from the restart, so the same setup fits + /// again after every sleep. + fn reinit(&self) -> Result { + let rtk = self.rtkit_handle()?; + // SAFETY: the handle stays valid until unbind, which can't run during a system sleep. + to_result(unsafe { bindings::apple_rtkit_reinit(rtk) })?; + let mut state = self.state.lock(); + state.restarted = true; + state.setup_again = true; + state.ioreg_new_list = true; + for a in state.allocs.iter_mut() { + a.held_over = true; + } + state.alloc_budget = AllocBudget::new(); + Ok(()) + } + /// ... and once its CPU runs: the boot, then the PMP endpoint. A restarted firmware + /// acknowledges IOP power by itself; it is asked for it if it does not. + fn boot(&self) -> Result { + let rtk = self.rtkit_handle()?; + // SAFETY: as in reinit(). + let ret = match to_result(unsafe { bindings::apple_rtkit_boot(rtk) }) { + Err(e) if e == ETIME => { + dev_warn!(self.dev, "no IOP power ack after restart, sending INIT\n"); + // SAFETY: as above. + to_result(unsafe { bindings::apple_rtkit_wake(rtk) }) + } + ret => ret, + }; + ret?; + // SAFETY: as above. + to_result(unsafe { bindings::apple_rtkit_start_ep(rtk, PMP_ENDPOINT) }) + } /// CONFIRM_IOREG's value for an UPDATE_IOREG: the length of the entry the firmware names by /// its own index, as registered. macOS 27.2 answers so on the M4 Mac mini (J773g), 8 for each /// of the four entries that image updates. An index that names no registered entry, which @@ -932,6 +999,55 @@ pub unsafe extern "C" fn apple_pmp_wake(data: *const core::ffi::c_void) -> i32 { } } +/// Writes the SRAM kept over a sleep back, with the firmware stopped. +/// +/// # Safety +/// `data` must point to the live PmpData registered by PmpDriver. +#[export] +pub unsafe extern "C" fn apple_pmp_sram_restore(data: *const core::ffi::c_void) -> i32 { + // SAFETY: The C bridge serializes calls against unregister in Drop. + let data = unsafe { &*data.cast::() }; + match data.sram_restore() { + Ok(()) => 0, + Err(error) => error.to_errno(), + } +} + +/// RTKit afresh for a firmware that starts from its reset vector after a power cycle. +/// +/// # Safety +/// `data` must point to the live PmpData registered by PmpDriver. +#[export] +pub unsafe extern "C" fn apple_pmp_reinit(data: *const core::ffi::c_void) -> i32 { + // SAFETY: The C bridge serializes calls against unregister in Drop. + let data = unsafe { &*data.cast::() }; + match data.reinit() { + Ok(()) => 0, + Err(error) => { + data.fail_display(error); + error.to_errno() + } + } +} + +/// Boots that firmware once its CPU runs, and starts the PMP endpoint. A firmware that doesn't +/// come back disables further power commands. +/// +/// # Safety +/// `data` must point to the live PmpData registered by PmpDriver. +#[export] +pub unsafe extern "C" fn apple_pmp_boot(data: *const core::ffi::c_void) -> i32 { + // SAFETY: The C bridge serializes calls against unregister in Drop. + let data = unsafe { &*data.cast::() }; + match data.boot() { + Ok(()) => 0, + Err(error) => { + data.fail_display(error); + error.to_errno() + } + } +} + struct NoBuffer; impl rtkit::Buffer for NoBuffer { fn iova(&self) -> Result { diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index 4c026d1bbea91..3f288468cf967 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -157,6 +157,66 @@ const DART_T8112: DartWindow = DartWindow { range: [0x0, 0x4000, 0x0, 0xffff_0000], }; +/// How the enclave goes to sleep for a deep sleep, and how it comes back. +#[derive(Clone, Copy)] +pub(crate) struct SleepProfile { + /// How long the enclave gets to answer its sleep request. + pub(crate) answer_ms: u32, + /// Only the answer ends the wait for it, and after it the domain is down once its actual + /// state reads 0; otherwise DEV_DISABLE ends either wait. + pub(crate) gate_actual: bool, + /// After the power cut the SEPROM resumes sepOS from RAM: the domain is powered on with + /// its minimum state raised, and the enclave is asked through its boot endpoint (TZ0, + /// then op 8, answered by 0x6c). Otherwise a doorbell wakes it. + pub(crate) seprom_resume: bool, + /// The answer's result says whether the enclave took the request: any but 0 refuses the + /// sleep at once, with the enclave still awake. Otherwise any answer is taken. + pub(crate) answer_result: bool, + /// The enclave's DART goes down with the enclave's own power island: saved before the + /// request, its commands gated from then on, and before the enclave + /// resumes, reset and its translations put back as a DART that lost its power. Otherwise + /// the DART's apple,sleep-restore list does it. + pub(crate) dart_island: bool, + /// The enclave comes back once the tasks run again (`PM_POST_SUSPEND`), + /// so that a SEPROM that doesn't answer holds up only the enclave's users, not the resume; + /// otherwise in the device's resume. + pub(crate) wake_after_thaw: bool, + /// On the commit-staged path, a post-send timeout or no-gate refuses the sleep and marks the + /// enclave lost (`EAGAIN`) instead of panicking. + pub(crate) commit_soft_fail: bool, + /// The commit reads the power-state word through a non-posted mapping where the PMGR's + /// bus asks for one; otherwise through a posted one. + pub(crate) ps_nonposted: bool, +} + +/// Every SoC but T6000. +const SLEEP_DEFAULT: SleepProfile = SleepProfile { + answer_ms: crate::proto::SLEEP_TIMEOUT_MS, + gate_actual: false, + seprom_resume: false, + answer_result: false, + dart_island: false, + wake_after_thaw: false, + commit_soft_fail: false, + ps_nonposted: false, +}; + +/// T6000 deep sleep: the request is staged at device suspend and sent in `.enter` at the +/// commit boundary, after every returnable refusal, because a T6000 enclave that gated its +/// own island will not power back on without a SoC power cut (`ps_sep` stays at actual 0). +/// Waits 15 s for the answer and matches it by its tag, polls actual state to 0 after it, +/// and resumes sepOS through the SEPROM after the wake. +const SLEEP_T6000: SleepProfile = SleepProfile { + answer_ms: 15000, + gate_actual: true, + seprom_resume: true, + answer_result: true, + dart_island: true, + wake_after_thaw: true, + commit_soft_fail: true, + ps_nonposted: true, +}; + pub(crate) struct PlatformProfile { pub(crate) name: &'static str, /// Capacity of the boot shared-memory window. The layout is still checked @@ -188,6 +248,8 @@ pub(crate) struct PlatformProfile { /// The `xart_guard` level when the parameter is left at its default (see /// [`crate::xart_guard`]). pub(crate) xart_guard: u8, + /// The enclave's deep sleep (see [`SleepProfile`]). + pub(crate) sleep: SleepProfile, } pub(crate) const T8103: PlatformProfile = PlatformProfile { @@ -226,6 +288,7 @@ pub(crate) const T8103: PlatformProfile = PlatformProfile { // Off: Touch ID setup on a cold-boot SEP rewrites a session record that // predates Linux, so the guard would only block it. xart_guard: 0, + sleep: SLEEP_DEFAULT, }; /// M1 Pro (J316s). The M1 family cold-boots its SEP like T8103, so the boot @@ -267,6 +330,7 @@ pub(crate) const T6000: PlatformProfile = PlatformProfile { // As T8103. On J316s, creating the identity keybag also rewrites a // session record that predates Linux. xart_guard: 0, + sleep: SLEEP_T6000, }; pub(crate) const T6020: PlatformProfile = PlatformProfile { @@ -300,6 +364,7 @@ pub(crate) const T6020: PlatformProfile = PlatformProfile { nonce_session: false, // A warm-attach enclave shared with macOS, as on T8112. xart_guard: 1, + sleep: SLEEP_DEFAULT, }; /// M2 Pro/Max on system firmware before 26.3. Their enclave refuses the @@ -356,6 +421,7 @@ pub(crate) const T8140: PlatformProfile = PlatformProfile { // Linux records from before the guard's list exist here, and Linux has // left the macOS records unchanged on this platform. xart_guard: 0, + sleep: SLEEP_DEFAULT, }; /// MacBook Air M2 (J413, J415). iBoot leaves the SEP running and the Mesa @@ -401,6 +467,7 @@ pub(crate) const T8112: PlatformProfile = PlatformProfile { nonce_session: false, // Guarded from its first Linux boot (2026-10-16): no record refused. xart_guard: 1, + sleep: SLEEP_DEFAULT, }; /// MacBook Air M3 (J613, J615). The J613 and J615 ADTs (26.6.2, 25G83) are diff --git a/drivers/soc/apple/proto.rs b/drivers/soc/apple/proto.rs index 1bdea86a4c51e..f0a787591407a 100644 --- a/drivers/soc/apple/proto.rs +++ b/drivers/soc/apple/proto.rs @@ -29,6 +29,10 @@ pub(crate) const MSG_SET_SHMEM: u64 = 0x18; pub(crate) const MSG_BOOT_TZ0_ACK1: u64 = 0x69; pub(crate) const MSG_BOOT_TZ0_ACK2: u64 = 0xd2; pub(crate) const MSG_BOOT_IMG4_ACK: u64 = 0x6a; +// The enclave's boot without firmware: op 8 in place of the IMG4 tells the SEPROM to +// resume the sepOS still in RAM; it answers 0x6c ("SEP resumed from RAM"). +pub(crate) const MSG_BOOT_RESUME: u64 = 0x8; +pub(crate) const MSG_BOOT_RESUMED: u64 = 0x6c; // 4 KiB units even though CPU pages are 16 KiB pub(crate) const IOVA_SHIFT: u32 = 12; @@ -87,6 +91,10 @@ pub(crate) fn shmem_registration(iova: u64, size: usize) -> Result { } pub(crate) const CONTROL_REPLY_TYPE: u8 = 0x01; +/// Control messages (tag 0) with which a resumed enclave reports its OS running again. +pub(crate) const CONTROL_OS_ACTIVE: u8 = 0x0d; +/// The same report, in the other form the enclave sends it. +pub(crate) const CONTROL_OS_ACTIVE_2: u8 = 0x15; pub(crate) const TAG_ENTROPY: u8 = 0xE7; diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index 8697450b4281a..e0791cb5df8dc 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2724,7 +2724,12 @@ EXPORT_SYMBOL_GPL(apple_rtkit_port_restart); * Everything of a firmware session but the mailbox hardware and, with * @keep_buffers, the shared buffers and the syslog geometry. */ -static void apple_rtkit_reset_session(struct apple_rtkit *rtk, bool keep_buffers) +/* + * @keep_started: the firmware resumes from its saved context, so the endpoints it + * had started stay started and what it announced once is not announced again. + */ +static void apple_rtkit_reset_session(struct apple_rtkit *rtk, bool keep_buffers, + bool keep_started) { unsigned long flags; @@ -2755,11 +2760,14 @@ static void apple_rtkit_reset_session(struct apple_rtkit *rtk, bool keep_buffers bitmap_zero(rtk->endpoints, APPLE_RTKIT_MAX_ENDPOINTS); set_bit(APPLE_RTKIT_EP_MGMT, rtk->endpoints); - bitmap_zero(rtk->started, APPLE_RTKIT_MAX_ENDPOINTS); - set_bit(APPLE_RTKIT_EP_MGMT, rtk->started); + if (!keep_started) { + bitmap_zero(rtk->started, APPLE_RTKIT_MAX_ENDPOINTS); + set_bit(APPLE_RTKIT_EP_MGMT, rtk->started); + } reinit_completion(&rtk->epmap_completion); - reinit_completion(&rtk->coreanalytics_completion); + if (!keep_started) + reinit_completion(&rtk->coreanalytics_completion); reinit_completion(&rtk->iop_pwr_ack_completion); reinit_completion(&rtk->ap_pwr_ack_completion); @@ -2780,7 +2788,7 @@ int apple_rtkit_reinit(struct apple_rtkit *rtk) { int ret; - apple_rtkit_reset_session(rtk, false); + apple_rtkit_reset_session(rtk, false, false); ret = apple_mbox_start(rtk->mbox); if (ret) { apple_rtkit_detach_rx(rtk); @@ -2794,7 +2802,7 @@ int apple_rtkit_reinit_retaining_buffers(struct apple_rtkit *rtk) { int ret; - apple_rtkit_reset_session(rtk, true); + apple_rtkit_reset_session(rtk, true, false); ret = apple_mbox_start(rtk->mbox); if (ret) { apple_rtkit_detach_rx(rtk); @@ -2804,6 +2812,34 @@ int apple_rtkit_reinit_retaining_buffers(struct apple_rtkit *rtk) } EXPORT_SYMBOL_GPL(apple_rtkit_reinit_retaining_buffers); +/* + * Like apple_rtkit_reinit(), for a co-processor that was idled with its buffers + * kept and lost its power: the firmware resumes from its saved context, so the + * shared buffers it was given stay mapped. Only the mailbox and the power + * handshake restart; the endpoint map is taken again as at a boot. + */ +int apple_rtkit_reinit_keep(struct apple_rtkit *rtk) +{ + int ret; + + apple_rtkit_reset_session(rtk, true, true); + ret = apple_mbox_start(rtk->mbox); + if (ret) { + apple_rtkit_detach_rx(rtk); + flush_workqueue(rtk->wq); + } + return ret; +} +EXPORT_SYMBOL_GPL(apple_rtkit_reinit_keep); + +/* Stop receiving before an idled co-processor loses its power; its buffers stay put. */ +void apple_rtkit_detach_keep(struct apple_rtkit *rtk) +{ + apple_rtkit_detach_rx(rtk); + flush_workqueue(rtk->wq); +} +EXPORT_SYMBOL_GPL(apple_rtkit_detach_keep); + static int apple_rtkit_set_ap_power_state(struct apple_rtkit *rtk, unsigned int state) { @@ -3141,13 +3177,50 @@ int apple_rtkit_ap_power_noirq(struct apple_rtkit *rtk, bool on) } EXPORT_SYMBOL_GPL(apple_rtkit_ap_power_noirq); +/* The AP power state alone, IDLE or ON, waiting @ms for the acknowledgment. */ +int apple_rtkit_ap_power_timeout(struct apple_rtkit *rtk, bool on, unsigned int ms) +{ + unsigned int state = on ? APPLE_RTKIT_PWR_STATE_ON : APPLE_RTKIT_PWR_STATE_IDLE; + int ret; + + reinit_completion(&rtk->ap_pwr_ack_completion); + ret = apple_rtkit_management_send(rtk, APPLE_RTKIT_MGMT_SET_AP_PWR_STATE, + FIELD_PREP(APPLE_RTKIT_MGMT_PWR_STATE, state)); + if (ret) + return ret; + if (!wait_for_completion_timeout(&rtk->ap_pwr_ack_completion, msecs_to_jiffies(ms))) { + dev_warn(rtk->dev, "RTKit: AP power %#x not acknowledged within %u ms, state %#x\n", + state, ms, rtk->ap_power_state); + return -ETIME; + } + return 0; +} +EXPORT_SYMBOL_GPL(apple_rtkit_ap_power_timeout); + +/* + * The IOP power state IDLE alone, as macOS sends it after the AP's to a + * co-processor it is about to stop with its context kept. + */ +int apple_rtkit_idle_iop(struct apple_rtkit *rtk) +{ + int ret; + + ret = apple_rtkit_set_iop_power_state(rtk, APPLE_RTKIT_PWR_STATE_IDLE); + if (ret) + return ret; + + rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_IDLE; + return 0; +} +EXPORT_SYMBOL_GPL(apple_rtkit_idle_iop); + /* Power is back, the CPU is stopped, and poweroff() discarded the old session. */ int apple_rtkit_cold_restart(struct apple_rtkit *rtk, int (*start)(void *), void *ctx) { int ret; /* A fresh boot: no warm or port-only restart may answer its endpoint map. */ - apple_rtkit_reset_session(rtk, false); + apple_rtkit_reset_session(rtk, false, false); rtk->warm_restart = false; rtk->port_only = false; rtk->warm_last_mask = U32_MAX; @@ -3292,6 +3365,69 @@ int apple_rtkit_wake_early_ap(struct apple_rtkit *rtk) } EXPORT_SYMBOL_GPL(apple_rtkit_wake_early_ap); +/* + * Wake after apple_rtkit_reinit_keep(): INIT, then the endpoint map and the IOP + * acknowledgment, but no AP power message yet. The app endpoints are started + * again first (apple_rtkit_restart_started_eps()), and the AP state is set + * after them with apple_rtkit_ap_power_timeout(). + */ +int apple_rtkit_wake_keep_ap(struct apple_rtkit *rtk) +{ + u64 msg; + int ret; + + if (apple_rtkit_is_running(rtk)) + return -EINVAL; + + reinit_completion(&rtk->iop_pwr_ack_completion); + msg = FIELD_PREP(APPLE_RTKIT_MGMT_PWR_STATE, APPLE_RTKIT_PWR_STATE_INIT); + ret = apple_rtkit_management_send(rtk, APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE, msg); + if (ret) + return ret; + + ret = apple_rtkit_wait(rtk, &rtk->epmap_completion); + if (ret) { + dev_err(rtk->dev, "RTKit: endpoint discovery failed: %d\n", ret); + return ret; + } + if (rtk->boot_result) + return rtk->boot_result; + + ret = apple_rtkit_wait(rtk, &rtk->iop_pwr_ack_completion); + if (ret) { + dev_err(rtk->dev, "RTKit: IOP power acknowledgment failed: %d\n", ret); + return ret; + } + if (rtk->crashed) + return -EIO; + + /* The app endpoints may be started again; the AP message follows them. */ + rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_ON; + return 0; +} +EXPORT_SYMBOL_GPL(apple_rtkit_wake_keep_ap); + +/* Start again, in ascending order, every app endpoint that was started before the idle. */ +int apple_rtkit_restart_started_eps(struct apple_rtkit *rtk) +{ + DECLARE_BITMAP(eps, APPLE_RTKIT_MAX_ENDPOINTS); + unsigned int ep; + int ret; + + bitmap_copy(eps, rtk->started, APPLE_RTKIT_MAX_ENDPOINTS); + ep = APPLE_RTKIT_APP_ENDPOINT_START; + for_each_set_bit_from(ep, eps, APPLE_RTKIT_MAX_ENDPOINTS) { + ret = apple_rtkit_start_ep(rtk, ep); + if (ret) { + dev_err(rtk->dev, "RTKit: restarting endpoint 0x%02x failed: %d\n", + ep, ret); + return ret; + } + } + return 0; +} +EXPORT_SYMBOL_GPL(apple_rtkit_restart_started_eps); + static int apple_rtkit_sleep_idle(struct apple_rtkit *rtk, void __iomem *cpu_control) { u32 status; @@ -3455,6 +3591,13 @@ int apple_rtkit_polled_ap_idle(struct apple_rtkit *rtk, unsigned int *us) } EXPORT_SYMBOL_GPL(apple_rtkit_polled_ap_idle); +int apple_rtkit_polled_iop_idle(struct apple_rtkit *rtk, unsigned int *us) +{ + return apple_rtkit_polled_state(rtk, APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE, + &rtk->iop_power_state, us); +} +EXPORT_SYMBOL_GPL(apple_rtkit_polled_iop_idle); + int apple_rtkit_sleep_idle_polled(struct apple_rtkit *rtk, void __iomem *cpu_control, unsigned int *us) { diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index a812a88bc73f6..69e4d4d99090f 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -744,9 +744,13 @@ struct SepData { sleep_rx_held: Atomic, /// Told at device suspend (no sleep core commit, T6041) rather than staged for the commit. sleep_at_suspend: Atomic, + /// A commit-staged real wake deferred to `PM_POST_SUSPEND` (`wake_after_thaw`). + sleep_wake_pending: Atomic, /// The enclave didn't answer a sleep request or a wake this boot: no deep sleep until a /// reboot, as a commit over a running enclave resets the SoC. sleep_unanswered: Atomic, + /// Where the SEPROM resume after a deep sleep is (`RESUME_*`). + resume_state: Atomic, #[pin] ool_xarm: Mutex>, @@ -1320,7 +1324,9 @@ impl SepData { sleep_gate: Atomic::new(pm::SleepGate::Open as u32), sleep_rx_held: Atomic::new(false), sleep_at_suspend: Atomic::new(false), + sleep_wake_pending: Atomic::new(false), sleep_unanswered: Atomic::new(false), + resume_state: Atomic::new(Self::RESUME_IDLE), ool_xarm <- new_mutex!(Some(ool_xarm)), ool_sbio <- new_mutex!(Some(ool_sbio)), ool_sks <- new_mutex!(Some(ool_sks)), @@ -1486,6 +1492,10 @@ impl SepData { /// Handle a message from the boot endpoint during the cold-boot handshake. fn on_boot(&self, msg: Message) { let ty = (msg.msg0 >> proto::MSG_TYPE_SHIFT) & 0xff; + if self.resume_state.load(Relaxed) != Self::RESUME_IDLE { + self.on_boot_resume(msg, ty); + return; + } match ty { proto::MSG_BOOT_TZ0_ACK1 => { dev_info_ratelimited!(self.dev, "boot: first TZ0 acknowledgement\n"); @@ -1649,6 +1659,11 @@ impl SepData { if !pm::platform_commit() { return self.sleep_enter_at_suspend(); } + // A dark wake's next round comes before the tasks run again: wake the enclave from the + // previous real sleep before staging the next one. + if self.profile.sleep.wake_after_thaw && self.sleep_wake_pending.xchg(false, Relaxed) { + self.sleep_wake_committed(); + } match self.sleep_gate() { // A failed earlier wake is not repaired by another precommit attempt. pm::SleepGate::Lost => return Err(EIO), @@ -1688,12 +1703,36 @@ impl SepData { return Err(EBUSY); } + if self.profile.sleep.dart_island { + if let Err(e) = pm::dart_island_save(&self.dev) { + dev_err_ratelimited!( + self.dev, + "sleep refused: its DART could not be saved ({:?})\n", + e + ); + self.set_sleep_gate(pm::SleepGate::Open); + return Err(e); + } + if let Err(e) = pm::dart_gate(&self.dev) { + dev_err_ratelimited!( + self.dev, + "sleep refused: its DART could not be gated ({:?})\n", + e + ); + self.set_sleep_gate(pm::SleepGate::Open); + return Err(e); + } + } + if let Err(e) = self.sleep_leave_for_commit() { dev_err_ratelimited!( self.dev, "sleep refused: irreversible request could not be staged ({:?})\n", e ); + if self.profile.sleep.dart_island { + let _ = pm::dart_ungate(&self.dev); + } self.set_sleep_gate(pm::SleepGate::Open); return Err(e); } @@ -1892,13 +1931,16 @@ impl SepData { /// Stage without sending; the platform's commit owns SLEEP with IRQs off. fn sleep_leave_for_commit(&self) -> Result<()> { let request = proto::encode_control(&proto::op_sleep(), proto::TAG_SLEEP); + let sleep = &self.profile.sleep; + let mask = proto::SLEEP_REPLY_MASK; match self.mbox.lock().as_ref() { Some(mbox) => pm::leave_for_commit( &self.dev, mbox.as_raw(), request, - proto::SLEEP_REPLY, - proto::SLEEP_REPLY_MASK, + proto::SLEEP_REPLY & mask, + mask, + sleep, ), None => Err(ENODEV), }?; @@ -1945,11 +1987,27 @@ impl SepData { if self.sleep_at_suspend.load(Relaxed) { return self.sleep_exit_at_suspend(); } - // Staged only: an unsent refusal releases RX without a restart. + // Staged only: an unsent refusal releases RX and ungates an island DART without a restart. match pm::commit_finish(&self.dev) { - Some(true) => self.set_sleep_gate(pm::SleepGate::Told), - Some(false) => self.sleep_release_rx(), - None => {} + pm::CommitFinish::Sent => self.set_sleep_gate(pm::SleepGate::Told), + pm::CommitFinish::Unsent => { + self.sleep_release_rx(); + if self.profile.sleep.dart_island { + if let Err(e) = pm::dart_ungate(&self.dev) { + dev_err_ratelimited!(self.dev, "could not ungate the DART ({:?})\n", e); + } + } + } + pm::CommitFinish::Failed => { + dev_err_ratelimited!( + self.dev, + "the enclave sleep request did not finish; it stays unused until a reboot\n" + ); + self.sleep_hold_rx(); + self.set_sleep_gate(pm::SleepGate::Lost); + return false; + } + pm::CommitFinish::Unstaged => {} } let gate = self.sleep_gate(); if gate == pm::SleepGate::Draining { @@ -1970,8 +2028,16 @@ impl SepData { self.set_sleep_gate(pm::SleepGate::Lost); return false; } - let answered = self.sleep_kick(); - match answered { + if self.profile.sleep.wake_after_thaw { + self.sleep_wake_pending.store(true, Relaxed); + return false; + } + self.sleep_wake_committed() + } + + /// Wakes an enclave after a real sleep whose request was sent at the commit. + fn sleep_wake_committed(&self) -> bool { + match self.sleep_wake() { Ok(()) => { self.set_sleep_gate(pm::SleepGate::Open); // One line per sleep it was told of: nothing else says it came back. @@ -1991,6 +2057,160 @@ impl SepData { } } + /// The wake of an enclave deferred to `PM_POST_SUSPEND` once the tasks run again, + /// where the profile says so (T6000). Returns whether the enclave came back from a + /// sleep it was told of. + pub(crate) fn sleep_exit_after_thaw(&self) -> bool { + if !self.profile.sleep.wake_after_thaw { + return false; + } + self.sleep_wake_pending.xchg(false, Relaxed) && self.sleep_wake_committed() + } + + /// Starts the enclave after a real sleep, as the SoC's [`profile::SleepProfile`] says. + fn sleep_wake(&self) -> Result<()> { + if self.profile.sleep.seprom_resume { + self.sleep_resume() + } else { + self.sleep_kick() + } + } + + const RESUME_IDLE: u32 = 0; + const RESUME_TZ0: u32 = 1; + const RESUME_SENT: u32 = 2; + const RESUME_DONE: u32 = 3; + const RESUME_FAILED: u32 = 4; + + /// How long the SEPROM gets to resume sepOS, in 10 ms steps. + const RESUME_POLLS: u32 = 1000; + + /// The enclave's wake from a deep sleep as macOS takes it (T6000). The domain is powered + /// on as macOS's wake does it and the DART restored, then the SEPROM resumes + /// sepOS from RAM: TZ0, and once the ROM reports its status, op 8 in place of the IMG4, + /// answered by 0x6c. On failure the enclave is left as asleep and its DART gated. + fn sleep_resume(&self) -> Result<()> { + self.sleep_power_on()?; + self.sleep_resume_powered() + } + + /// The domain on, as macOS's wake does. On failure nothing else was touched. + fn sleep_power_on(&self) -> Result<()> { + if self.shutting_down.load(Relaxed) { + return Err(ENODEV); + } + pm::power_on(&self.dev) + } + + /// The rest of the resume, with the domain on; its minimum state is dropped after. + fn sleep_resume_powered(&self) -> Result<()> { + let ret = self.sleep_resume_handshake(); + self.resume_state.store(Self::RESUME_IDLE, Relaxed); + if ret.is_err() { + if let Some(mbox) = self.mbox.lock().as_ref() { + mbox.set_recv_enabled(false); + } + self.sleep_hold_rx(); + if let Err(e) = pm::dart_gate(&self.dev) { + dev_err_ratelimited!(self.dev, "could not gate the DART again ({:?})\n", e); + } + } + pm::power_release(&self.dev); + ret + } + + /// The enclave's DART back before the enclave runs again. Where it lost its island, the wake + /// ends on an error. + fn sleep_dart_back(&self) -> Result<()> { + if !self.profile.sleep.dart_island { + pm::dart_restore(&self.dev); + return Ok(()); + } + pm::dart_island_restore(&self.dev).inspect_err(|e| { + dev_err_ratelimited!(self.dev, "could not restore the DART ({:?})\n", e); + }) + } + + fn sleep_resume_handshake(&self) -> Result<()> { + self.sleep_dart_back()?; + self.resume_state.store(Self::RESUME_TZ0, Relaxed); + // As macOS starts the enclave: the inbox, the outbox, then the receive interrupt. + match self.mbox.lock().as_ref() { + Some(mbox) => { + pm::inbox_on(mbox.as_raw()); + mbox.set_recv_enabled(true); + } + None => return Err(ENODEV), + } + self.sleep_release_rx(); + // sepOS stays silent until the boot endpoint rings, and the ROM answers TZ0 within + // milliseconds: ring at once, as macOS's boot of the enclave does. + match self.mbox.lock().as_ref() { + Some(mbox) => { + let msg = Message { + msg0: u64::from(proto::EP_BOOT) + | (proto::MSG_BOOT_TZ0 << proto::MSG_TYPE_SHIFT), + msg1: 0, + }; + Self::ring(mbox, msg)?; + } + None => return Err(ENODEV), + } + for _ in 0..Self::RESUME_POLLS { + match self.resume_state.load(Relaxed) { + Self::RESUME_DONE => return Ok(()), + Self::RESUME_FAILED => return Err(EIO), + _ => kernel::time::delay::fsleep(kernel::time::Delta::from_millis(10)), + } + } + dev_err_ratelimited!( + self.dev, + "no answer from the SEPROM within 10 s (state {})\n", + self.resume_state.load(Relaxed) + ); + Err(ETIMEDOUT) + } + + /// A boot-endpoint message during [`Self::sleep_resume`], read as + /// macOS reads it: 0x69 accepts TZ0, 0xd2 carries the ROM status in + /// its data, 0x6c reports sepOS resumed from RAM. + fn on_boot_resume(&self, msg: Message, ty: u64) { + match ty { + proto::MSG_BOOT_TZ0_ACK1 => {} + proto::MSG_BOOT_TZ0_ACK2 => { + if self + .resume_state + .cmpxchg(Self::RESUME_TZ0, Self::RESUME_SENT, Relaxed) + .is_err() + { + return; + } + let resume = Message { + msg0: u64::from(proto::EP_BOOT) + | (proto::MSG_BOOT_RESUME << proto::MSG_TYPE_SHIFT), + msg1: 0, + }; + let sent = match self.mbox.lock().as_ref() { + Some(mbox) => Self::ring(mbox, resume), + None => Err(ENODEV), + }; + if let Err(e) = sent { + dev_err_ratelimited!(self.dev, "could not send the resume ({:?})\n", e); + self.resume_state.store(Self::RESUME_FAILED, Relaxed); + } + } + proto::MSG_BOOT_RESUMED => self.resume_state.store(Self::RESUME_DONE, Relaxed), + _ => { + dev_warn_ratelimited!( + self.dev, + "resume: boot message type {:#x} (msg0 {:#018x})\n", + ty, + msg.msg0 + ); + } + } + } + /// Starts a gated enclave and waits for the messages that say it's up. fn sleep_kick(&self) -> Result<()> { pm::clear_dev_disable(&self.dev)?; @@ -3470,6 +3690,16 @@ impl SepData { fn dispatch(&self, msg: Message) { let f = proto::decode(&msg); + // The resumed enclave reports its OS running: the resume is over. While a resume + // runs nothing else waits for these, so they end here. + if f.ep == proto::EP_CONTROL + && f.tag == 0 + && (f.ty == proto::CONTROL_OS_ACTIVE || f.ty == proto::CONTROL_OS_ACTIVE_2) + && self.resume_state.load(Relaxed) != Self::RESUME_IDLE + { + self.resume_state.store(Self::RESUME_DONE, Relaxed); + return; + } match f.ep { proto::EP_DISCOVER => self.on_discovery(msg, f), diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 20ab55c32ef94..6c3910a637a6e 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -35,8 +35,16 @@ int sep_pm_clear_dev_disable(void *dev); void sep_pm_dart_restore(void *dev); int sep_pm_dart_prepare(void *dev); bool sep_pm_platform_commit(void); -int sep_pm_commit_prepare(void *dev, void *mbox, u64 msg0, u32 msg1, u64 reply, u64 mask); +int sep_pm_commit_prepare(void *dev, void *mbox, u64 msg0, u32 msg1, u64 reply, u64 mask, + unsigned int answer_ms, u32 flags); int sep_pm_commit_finish(void *dev); +int sep_pm_power_on(void *dev); +void sep_pm_power_release(void *dev); +int sep_pm_dart_gate(void *dev); +int sep_pm_dart_ungate(void *dev); +int sep_pm_dart_island_save(void *dev); +int sep_pm_dart_island_restore(void *dev); +void sep_pm_inbox_on(void *mbox); extern const struct dev_pm_ops sep_pm_ops; /* -- hwrng_shim.c ------------------------------------------------------- */ diff --git a/drivers/soc/apple/sleep-t6000-display.inc b/drivers/soc/apple/sleep-t6000-display.inc new file mode 100644 index 0000000000000..debeb4e895235 --- /dev/null +++ b/drivers/soc/apple/sleep-t6000-display.inc @@ -0,0 +1,551 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * T6000 (M1 Pro): the display blocks and the GPU's fabric port taken down for a deep sleep, + * while the PMP still runs. Included by the T6000 profile, which calls t6000_display_map() from + * its .map_regs, t6000_sleep_display_off() as its .display_off, t6000_sleep_display_undo() when + * an entry that ran .display_off is given up before the SoC went down, and + * t6000_sleep_gpu_port_off() as its .first_stopped, past the last refusal. + * + * Their drivers have stopped the display coprocessors that ran (IDLE, CPU stopped) by then. + * Each block is first dropped from the PMP's device requests and acknowledged, then its power + * states are lowered. Before a power state goes, the fabric block behind it gets its setup + * and the fabric handshake. The setup is the device tree's apple,tunable--fabric list + * for the block's -fabric reg, each word written whole in the list's order, as macOS + * writes it when it powers the block up. Linux leaves the blocks at reset values, so there + * is nothing of the boot loader's to save and write back instead. A display block still up + * after its waits refuses the sleep, before SEP and the SMC are told. + * + * All three blocks go down on every sleep, a display attached or not: disp0 (the internal + * display) and the external ones, dispext0 and dispext1. The PMGR's sleep engine waits after + * the commit for what dispext0's fabric handshake sets (0x2922c0044 bit 2, hv trace). + */ + +/* Power state words, in the PMGR blocks at 0x28e080000 and 0x28e580000 (east) */ +#define T6000_DISP_PS_PMGR 0x28e080000ULL +#define T6000_DISP_PS_EAST 0x28e580000ULL +#define T6000_DISP_PS_LEN 0x1000 +#define T6000_GFX_PS 0x3c0 /* east */ +#define T6000_AFR_PS 0x28e0801e8ULL +/* The AFR cluster's word (cluster 5) of the PMGR cluster power states */ +#define T6000_AFR_CLUSTER_PS (0x28e098000ULL + 4 * 5) +#define T6000_AFR_CLUSTER_TARGET GENMASK(3, 0) +#define T6000_AFR_CLUSTER_UP BIT(5) +#define T6000_AFR_CLUSTER_BUSY BIT(4) +#define T6000_AFR_GATE 0x28e5e4000ULL +#define T6000_AFR_GATE_EN BIT(0) +#define T6000_FABRIC_HS_8014 0x8014 +#define T6000_FABRIC_HS_82BC 0x82bc + +/* + * A power-state word as these steps write it, field by field: auto-enable, the auto state, the + * minimum state, the two latched flags (written back to clear them), the actual state as read + * back (read-only), and the target. States: on, clock-gated, power-gated. + */ +#define T6000_PS_MIN GENMASK(19, 16) +#define T6000_PS_ON 0xf +#define T6000_PS_CLKGATE 0x4 +#define T6000_PS_OFF 0x0 +#define T6000_PSW(en, autostate, min, flags, actual, target) \ + (((en) ? PS_AUTO_ENABLE : 0) | FIELD_PREP_CONST(PS_AUTO_STATE, autostate) | \ + FIELD_PREP_CONST(T6000_PS_MIN, min) | FIELD_PREP_CONST(PS_FLAGS, flags) | \ + FIELD_PREP_CONST(PS_ACTUAL, actual) | FIELD_PREP_CONST(PS_TARGET, target)) + +/* PMP device requests (bits of SOC-DEV-PS-REQ): the GPU's; the displays' are below */ +#define T6000_PMP_AGX_ID 9 +#define T6000_PMP_ACK_US 200000 + +/* + * The display blocks, numbered as the stuck bits count them: block b's CPU word is bit 2 * b, + * its front end's bit 2 * b + 1, its PMP request bit 8 + b. + */ +enum { T6000_DISPEXT0, T6000_DISP0, T6000_DISPEXT1, T6000_DISP_BLOCKS }; +#define T6000_DISP_ALL GENMASK(T6000_DISP_BLOCKS - 1, 0) + +static const struct t6000_disp_block { + const char *name; + u64 cpu0, fe; + /* Its fabric block's reg-name, and its setup's apple,tunable- */ + const char *fabric; + /* Its PMP device request */ + unsigned int pmp_id; +} t6000_disp_blocks[T6000_DISP_BLOCKS] = { + [T6000_DISPEXT0] = { "dispext0", 0x28e080280, 0x28e080258, "dispext0-fabric", 13 }, + [T6000_DISP0] = { "disp0", 0x28e580350, 0x28e580328, "disp0-fabric", 12 }, + [T6000_DISPEXT1] = { "dispext1", 0x28e0802a8, 0x28e080260, "dispext1-fabric", 14 }, +}; + +/* macOS's order, disp0, dispext0, dispext1: its requests step 0x7000, 0x6000, 0x4000, 0 */ +static const u8 t6000_disp_order[] = { T6000_DISP0, T6000_DISPEXT0, T6000_DISPEXT1 }; + +/* macOS's AFR power state writes after GFX goes down, in order */ +static const u32 t6000_gfx_afr_down[] = { + T6000_PSW(0, T6000_PS_CLKGATE, T6000_PS_CLKGATE, 0, T6000_PS_CLKGATE, T6000_PS_ON), + T6000_PSW(0, T6000_PS_ON, T6000_PS_CLKGATE, 3, T6000_PS_ON, T6000_PS_ON), + T6000_PSW(1, T6000_PS_ON, T6000_PS_CLKGATE, 0, T6000_PS_ON, T6000_PS_ON), + T6000_PSW(1, T6000_PS_CLKGATE, T6000_PS_ON, 2, T6000_PS_CLKGATE, T6000_PS_ON), + T6000_PSW(0, T6000_PS_ON, T6000_PS_ON, 2, T6000_PS_ON, T6000_PS_ON), + T6000_PSW(0, T6000_PS_CLKGATE, T6000_PS_CLKGATE, 3, T6000_PS_CLKGATE, T6000_PS_OFF), +}; + +static struct t6000_display { + void __iomem *pmgr_ps; + void __iomem *east_ps; + void __iomem *afr_ps; + void __iomem *afr_cluster; + void __iomem *afr_gate; + void __iomem *gfx_blk; + void __iomem *disp_blk[T6000_DISP_BLOCKS]; + /* Their setups, from the device tree */ + struct apple_tunable *gfx_setup; + struct apple_tunable *disp_setup[T6000_DISP_BLOCKS]; + /* The PMP report and each display block's entry in it */ + struct device_node *pmp_report; + struct device_node *pmp_entry[T6000_DISP_BLOCKS]; + + /* + * What the last lowering changed, for t6000_sleep_display_undo(): the PMP requests it + * dropped that were up. The AFR cluster word as it was is the profile's + * t6000_sleep.afr_cl_pre: its quiesce restore after a wake uses it too. + */ + u64 ptd_dropped; + bool undo_due; + /* The blocks whose entry is dropped here, not by the PMP's own suspend */ + unsigned long owned; + /* The blocks that went down in this attempt: a sleep given up then raises them again */ + unsigned long cycled; + /* The blocks whose display coprocessor its driver has parked, until it starts it again */ + unsigned long parked; + /* + * GFX and AFR as the commit found them, before the GPU's port went down, for the wake: + * genpd keeps both on across a sleep whose commit stops the GPU's firmware. + */ + u32 gfx_commit, afr_commit; + bool gpu_port_down; + + /* For the report */ + u32 gfx_stuck, disp_stuck; + u32 gfx_seen[4], disp_read[2 * T6000_DISP_BLOCKS]; +} t6000_display; + +static void __iomem *t6000_display_ioremap(struct apple_sleep *s, phys_addr_t pa, size_t len) +{ + void __iomem *base = ioremap_np(pa, len); + + if (base && devm_add_action_or_reset(s->dev, apple_sleep_iounmap, (void __force *)base)) + return NULL; + return base; +} + +/* + * A fabric block, the sleep node's reg @name, and its setup, apple,tunable-@name: bounded by + * that reg. Without either the profile does not probe, as no block is written without its + * setup. + */ +static void __iomem *t6000_fabric_map(struct apple_sleep *s, const char *name, + struct apple_tunable **setup) +{ + struct resource *res; + char prop[40]; + size_t i; + + res = platform_get_resource_byname(to_platform_device(s->dev), IORESOURCE_MEM, name); + if (!res) { + dev_err(s->dev, "T6000: no %s reg\n", name); + return NULL; + } + snprintf(prop, sizeof(prop), "apple,tunable-%s", name); + *setup = devm_apple_tunable_parse(s->dev, s->dev->of_node, prop, res); + if (IS_ERR(*setup)) { + dev_err(s->dev, "T6000: %s: %pe\n", prop, *setup); + *setup = NULL; + return NULL; + } + for (i = 0; i < (*setup)->sz; i++) { + if ((*setup)->values[i].mask != U32_MAX) { + dev_err(s->dev, "T6000: %s: entry %zu is not a whole word\n", prop, i); + *setup = NULL; + return NULL; + } + } + return t6000_display_ioremap(s, res->start, resource_size(res)); +} + +/* + * A fabric block's setup, in the list's order, each word written as listed. Nothing in the + * block is read: it is at reset, and a read there is not part of the sequence that is known + * to work while the block powers down. apple_tunable_apply() would read each word first and + * skip the ones that already hold the value, among them the stage words written again. + */ +static void t6000_fabric_setup(void __iomem *blk, const struct apple_tunable *setup) +{ + size_t i; + + for (i = 0; i < setup->sz; i++) + writel(setup->values[i].value, blk + setup->values[i].offset); +} + +static int t6000_display_map(struct apple_sleep *s) +{ + struct t6000_display *d = &t6000_display; + struct device_node *np; + unsigned int b; + u32 id; + + /* Inside the sleep node's "ps" and "ps-east", mapped by the profile already */ + d->pmgr_ps = s->ps + (T6000_DISP_PS_PMGR - T6000_PS_BASE); + d->east_ps = t6000_sleep.ps_east + (T6000_DISP_PS_EAST - T6000_PS_EAST_BASE); + d->afr_ps = s->ps + (T6000_AFR_PS - T6000_PS_BASE); + d->afr_cluster = s->ps + (T6000_AFR_CLUSTER_PS - T6000_PS_BASE); + d->afr_gate = t6000_display_ioremap(s, T6000_AFR_GATE, 4); + d->gfx_blk = t6000_fabric_map(s, "gfx-fabric", &d->gfx_setup); + if (!d->gfx_blk) + return -ENODEV; + for (b = 0; b < T6000_DISP_BLOCKS; b++) { + d->disp_blk[b] = t6000_fabric_map(s, t6000_disp_blocks[b].fabric, + &d->disp_setup[b]); + if (!d->disp_blk[b]) + return -ENODEV; + } + if (!d->pmgr_ps || !d->east_ps) + return -ENOMEM; + + /* Kept for good, as the report is */ + d->pmp_report = of_find_compatible_node(NULL, NULL, "apple,t6000-pmp-v2-report"); + for_each_child_of_node(d->pmp_report, np) { + if (of_property_read_u32(np, "reg", &id)) + continue; + for (b = 0; b < T6000_DISP_BLOCKS; b++) + if (id == t6000_disp_blocks[b].pmp_id && !d->pmp_entry[b]) + d->pmp_entry[b] = of_node_get(np); + } + for (b = 0; b < T6000_DISP_BLOCKS; b++) + if (!d->pmp_entry[b]) + dev_warn(s->dev, + "T6000: no PMP report entry for %s, not held for the commit\n", + t6000_disp_blocks[b].name); + + return 0; +} + +/* A display block's power word, or NULL */ +static void __iomem *t6000_disp_ps(struct t6000_display *d, u64 pa) +{ + if (pa >= T6000_DISP_PS_PMGR && pa < T6000_DISP_PS_PMGR + T6000_DISP_PS_LEN) + return d->pmgr_ps ? d->pmgr_ps + (pa - T6000_DISP_PS_PMGR) : NULL; + if (pa >= T6000_DISP_PS_EAST && pa < T6000_DISP_PS_EAST + T6000_DISP_PS_LEN) + return d->east_ps ? d->east_ps + (pa - T6000_DISP_PS_EAST) : NULL; + return NULL; +} + +/* The display block whose CPU power word is @pd (a PMGR power-state node), or -1 */ +static int t6000_disp_block_of(struct device_node *pd) +{ + struct device_node *parent = of_get_parent(pd); + struct resource res; + unsigned int b; + int found = -1; + u32 off; + + if (parent && !of_address_to_resource(parent, 0, &res) && + !of_property_read_u32(pd, "reg", &off)) + for (b = 0; b < T6000_DISP_BLOCKS; b++) + if (res.start + off == t6000_disp_blocks[b].cpu0) + found = b; + of_node_put(parent); + return found; +} + +/* + * The GPU's fabric port as macOS leaves it for the sleep: the AFR cluster, AFR and GFX up, the + * PMP's GFX request raised so that GFX stays up, the fabric block set up, the request dropped + * again, the fabric handshake, then GFX and AFR down. Linux otherwise reaches the sleep with + * GFX at 0xf000b00. Nothing here refuses the sleep: what got stuck is only reported. + */ +static void t6000_sleep_gfx_down(struct apple_sleep *s) +{ + struct t6000_display *d = &t6000_display; + void __iomem *gfx = d->east_ps + T6000_GFX_PS; + bool was = false; + unsigned int j; + int ret; + u32 v; + + d->gfx_stuck = 0; + t6000_sleep.afr_cl_valid = false; + if (!d->gfx_blk || !d->afr_ps || !d->pmp_report) + return; + d->gfx_seen[0] = readl(gfx); + d->gfx_seen[1] = readl(d->afr_ps); + /* The AFR cluster up first: 0xf, it reads back 0x2f once up, then 0x2f */ + if (d->afr_cluster) { + t6000_sleep.afr_cl_pre = readl(d->afr_cluster); + t6000_sleep.afr_cl_valid = true; + writel(FIELD_PREP(T6000_AFR_CLUSTER_TARGET, T6000_PS_ON), d->afr_cluster); + if (readl_poll_timeout_atomic(d->afr_cluster, v, v & T6000_AFR_CLUSTER_UP, 1, 50000)) + d->gfx_stuck |= BIT(6); + writel(T6000_AFR_CLUSTER_UP | FIELD_PREP(T6000_AFR_CLUSTER_TARGET, T6000_PS_ON), + d->afr_cluster); + } + if (d->afr_gate) + writel(T6000_AFR_GATE_EN, d->afr_gate); + /* AFR on, with clock gating as its floor, then auto */ + writel(T6000_PSW(0, T6000_PS_ON, T6000_PS_CLKGATE, 0, 0, T6000_PS_OFF), d->afr_ps); + writel(T6000_PSW(0, T6000_PS_ON, T6000_PS_CLKGATE, 0, 0, T6000_PS_ON), d->afr_ps); + writel(T6000_PSW(1, T6000_PS_ON, T6000_PS_CLKGATE, 0, 0, T6000_PS_ON), d->afr_ps); + if (readl_poll_timeout_atomic(d->afr_ps, v, FIELD_GET(PS_ACTUAL, v), 1, 50000)) + d->gfx_stuck |= BIT(0); + /* GFX on, then auto */ + writel(T6000_PSW(0, T6000_PS_ON, 0, 0, 0, T6000_PS_OFF), gfx); + writel(T6000_PSW(0, T6000_PS_ON, 0, 0, 0, T6000_PS_ON), gfx); + writel(T6000_PSW(1, T6000_PS_ON, 0, 0, 0, T6000_PS_ON), gfx); + /* GFX reaches 4, and the PMP drops it again unless its request is up: raise that first. */ + ret = apple_pmp_report_sleep_request(d->pmp_report, T6000_PMP_AGX_ID, true, + T6000_PMP_ACK_US, &was); + if (was) + d->ptd_dropped |= BIT_ULL(T6000_PMP_AGX_ID); + if (ret) + d->gfx_stuck |= BIT(2); + /* The fabric block is in the GFX domain: never write it unpowered. */ + if (readl_poll_timeout_atomic(gfx, v, FIELD_GET(PS_ACTUAL, v), 1, 50000)) { + d->gfx_stuck |= BIT(1); + } else { + t6000_fabric_setup(d->gfx_blk, d->gfx_setup); + } + if (apple_pmp_report_sleep_request(d->pmp_report, T6000_PMP_AGX_ID, false, + T6000_PMP_ACK_US, NULL)) + d->gfx_stuck |= BIT(3); + if (!(d->gfx_stuck & BIT(1)) && FIELD_GET(PS_ACTUAL, readl(gfx))) { + writel(1, d->gfx_blk + T6000_FABRIC_HS_8014); + writel(1, d->gfx_blk + T6000_FABRIC_HS_82BC); + writel(2, d->gfx_blk + T6000_FABRIC_HS_82BC); + writel(4, d->gfx_blk + T6000_FABRIC_HS_82BC); + } else { + d->gfx_stuck |= BIT(7); + } + /* GFX off: auto off, then power-gated with the latched flags cleared */ + writel(T6000_PSW(0, T6000_PS_ON, 0, 0, T6000_PS_ON, T6000_PS_ON), gfx); + writel(T6000_PSW(0, T6000_PS_ON, 0, 3, T6000_PS_ON, T6000_PS_OFF), gfx); + if (readl_poll_timeout_atomic(gfx, v, !FIELD_GET(PS_ACTUAL, v), 1, 10000)) + d->gfx_stuck |= BIT(4); + d->gfx_seen[2] = v; + for (j = 0; j < ARRAY_SIZE(t6000_gfx_afr_down); j++) + writel(t6000_gfx_afr_down[j], d->afr_ps); + if (readl_poll_timeout_atomic(d->afr_ps, v, !FIELD_GET(PS_ACTUAL, v), 1, 10000)) + d->gfx_stuck |= BIT(5); + d->gfx_seen[3] = v; + if (d->afr_gate) + writel(0, d->afr_gate); + if (d->afr_cluster) + writel(FIELD_PREP(T6000_AFR_CLUSTER_TARGET, T6000_PS_OFF), d->afr_cluster); + dev_dbg(s->dev, "T6000: GFX down: stuck %#x, gfx %#x -> %#x, afr %#x -> %#x\n", + d->gfx_stuck, d->gfx_seen[0], d->gfx_seen[2], d->gfx_seen[1], d->gfx_seen[3]); +} + +/* + * The display blocks in @blocks, in macOS's order (hv trace, macOS 13.7.8 sleep entry). Per + * block: the fabric block's setup, the PMP's request for the + * block dropped and acknowledged within 200 ms, as macOS waits, the CPU's power state, the + * fabric handshake (+0x8014 = 1, +0x82bc = 1, 2, 4), then the front end's power state. The + * fabric block only answers while the front end has power: a write to it otherwise is an + * SError. The request word only: the report's books keep the block on, as the PMP's wake + * rewrites them. + */ +static void t6000_sleep_disp_down(struct apple_sleep *s, unsigned long blocks) +{ + struct t6000_display *d = &t6000_display; + unsigned int k, b; + u32 v; + + d->ptd_dropped = 0; + d->cycled |= blocks; + d->disp_stuck = 0; + for (k = 0; k < ARRAY_SIZE(t6000_disp_order); k++) { + const struct t6000_disp_block *db; + void __iomem *cpu0, *fe, *blk; + + b = t6000_disp_order[k]; + if (!(blocks & BIT(b))) + continue; + db = &t6000_disp_blocks[b]; + cpu0 = t6000_disp_ps(d, db->cpu0); + fe = t6000_disp_ps(d, db->fe); + if (!cpu0 || !fe) + continue; + + blk = d->disp_blk[b]; + if (blk && !FIELD_GET(PS_ACTUAL, readl(fe))) + blk = NULL; + if (blk) + t6000_fabric_setup(blk, d->disp_setup[b]); + if (d->pmp_report) { + bool was = false; + + if (apple_pmp_report_sleep_request(d->pmp_report, db->pmp_id, false, + T6000_PMP_ACK_US, &was)) + d->disp_stuck |= BIT(8 + b); + if (was) + d->ptd_dropped |= BIT_ULL(db->pmp_id); + } + /* The CPU off: auto off, then power-gated with the latched flags cleared */ + writel(T6000_PSW(0, T6000_PS_ON, T6000_PS_CLKGATE, 0, T6000_PS_ON, T6000_PS_ON), + cpu0); + writel(T6000_PSW(0, T6000_PS_ON, T6000_PS_CLKGATE, 3, T6000_PS_ON, T6000_PS_OFF), + cpu0); + if (readl_poll_timeout_atomic(cpu0, v, !FIELD_GET(PS_ACTUAL, v), 1, 10000)) + d->disp_stuck |= BIT(2 * b); + d->disp_read[2 * b] = readl(cpu0); + + blk = d->disp_blk[b]; + if (blk && !FIELD_GET(PS_ACTUAL, readl(fe))) + blk = NULL; + if (blk) { + writel(1, blk + T6000_FABRIC_HS_8014); + writel(1, blk + T6000_FABRIC_HS_82BC); + writel(2, blk + T6000_FABRIC_HS_82BC); + writel(4, blk + T6000_FABRIC_HS_82BC); + } + /* The front end power-gated, the latched flags cleared */ + writel(T6000_PSW(0, 0, 0, 3, T6000_PS_ON, T6000_PS_OFF), fe); + if (readl_poll_timeout_atomic(fe, v, !FIELD_GET(PS_ACTUAL, v), 1, 10000)) + d->disp_stuck |= BIT(2 * b + 1); + d->disp_read[2 * b + 1] = readl(fe); + } + dev_dbg(s->dev, "T6000: displays down: stuck %#x, ps %#x %#x %#x %#x %#x %#x\n", + d->disp_stuck, d->disp_read[0], d->disp_read[1], d->disp_read[2], d->disp_read[3], + d->disp_read[4], d->disp_read[5]); +} + +/* + * Every display block, before the SMC is told. A display block that stays up refuses the sleep: + * the SoC must never go down around it. The GPU's port is not among them: it goes down only + * past the last refusal, see t6000_sleep_gpu_port_off(). + */ +static int t6000_sleep_display_off(struct apple_sleep *s) +{ + struct t6000_display *d = &t6000_display; + unsigned int b; + + if (!d->pmgr_ps || !d->east_ps) + return -ENODEV; + d->undo_due = true; + t6000_sleep_disp_down(s, T6000_DISP_ALL); + if (d->disp_stuck) { + for (b = 0; b < T6000_DISP_BLOCKS - 1; b++) + if (d->disp_stuck & (BIT(2 * b) | BIT(2 * b + 1) | BIT(8 + b))) + break; + dev_err(s->dev, "%s did not power down (%#x), not sleeping\n", + t6000_disp_blocks[b].name, d->disp_stuck); + return -EBUSY; + } + + return 0; +} + +/* + * The GPU's fabric port, right after the commit's first pass of coprocessor stops, in which the + * GPU's driver stopped its firmware (apple_sleep_coproc_register_first()). macOS takes it down + * before the display blocks; here it waits for the GPU's stop, which comes only once nothing can + * refuse the sleep any more, so a sleep given up before that leaves the GPU running and its port + * as its driver had it. Still before the PMP's stop and the SoC's last words. + */ +static void t6000_sleep_gpu_port_off(struct apple_sleep *s) +{ + struct t6000_display *d = &t6000_display; + + if (!d->east_ps || !d->afr_ps) + return; + d->gfx_commit = readl(d->east_ps + T6000_GFX_PS); + d->afr_commit = readl(d->afr_ps); + d->gpu_port_down = true; + t6000_sleep_gfx_down(s); +} + +/* + * After a sleep whose commit took the GPU's port down: AFR, then GFX, back as the commit found + * them, before any device resumes and before the GPU's driver starts its firmware again. genpd + * counted both on across the sleep and writes neither again; with them on, the media blocks + * under AFR come back through genpd as before. + */ +static void t6000_sleep_gpu_port_back(struct apple_sleep *s) +{ + struct t6000_display *d = &t6000_display; + void __iomem *gfx = d->east_ps + T6000_GFX_PS; + int ret; + + if (!d->gpu_port_down) + return; + d->gpu_port_down = false; + ret = sleep_ps_restore(d->afr_ps, d->afr_commit); + if (!ret) + ret = sleep_ps_restore(gfx, d->gfx_commit); + if (ret) + dev_warn(s->dev, "T6000: GPU port not back after the sleep: gfx %#x (was %#x), afr %#x (was %#x)\n", + readl(gfx), d->gfx_commit, readl(d->afr_ps), d->afr_commit); + else + dev_dbg(s->dev, "T6000: GPU port back: gfx %#x, afr %#x\n", readl(gfx), + readl(d->afr_ps)); +} + +/* + * An entry given up after t6000_sleep_display_off() and before the SoC went down. A running + * PMP keeps a block down until its request is up again; a stopped one gets its requests back + * when it starts. The AFR cluster word goes back to what it was. Raising the power states the + * entry lowered is left to the profile's restore of every power state, after this. + */ +static void t6000_sleep_display_undo(struct apple_sleep *s) +{ + struct t6000_display *d = &t6000_display; + unsigned long dropped = d->ptd_dropped; + u64 failed = 0; + unsigned int id; + u32 v; + + if (!d->undo_due) + return; + d->undo_due = false; + d->ptd_dropped = 0; + for_each_set_bit(id, &dropped, BITS_PER_LONG) + if (apple_pmp_report_sleep_request(d->pmp_report, id, true, T6000_PMP_ACK_US, NULL)) + failed |= BIT_ULL(id); + if (failed) + dev_warn(s->dev, "T6000: PMP did not take device requests %#llx back\n", failed); + if (d->afr_cluster && t6000_sleep.afr_cl_valid) { + if ((readl(d->afr_cluster) ^ t6000_sleep.afr_cl_pre) & T6000_AFR_CLUSTER_TARGET) + writel(t6000_sleep.afr_cl_pre, d->afr_cluster); + readl_poll_timeout_atomic(d->afr_cluster, v, !(v & T6000_AFR_CLUSTER_BUSY), 1, + 10000); + t6000_sleep.afr_cl_valid = false; + } + dev_info(s->dev, "sleep given up, powering the displays back up\n"); +} + +/* + * The display blocks' requests are dropped by t6000_sleep_disp_down(), in .enter: the PMP's + * own suspend_late must leave them, or a block's request drops while its coprocessor still + * runs. From the profile's .begin to its .finish; a failure leaves none held. + */ +static int t6000_display_own(struct apple_sleep *s, bool own) +{ + struct t6000_display *d = &t6000_display; + unsigned int b; + int ret; + + for (b = 0; b < T6000_DISP_BLOCKS; b++) { + if (!d->pmp_entry[b] || test_bit(b, &d->owned) == own) + continue; + ret = apple_pmp_report_entry_commit_owned(d->pmp_entry[b], own); + if (ret) { + dev_err(s->dev, + "T6000: %s's PMP report entry not held for the commit: %d\n", + t6000_disp_blocks[b].name, ret); + if (own) + t6000_display_own(s, false); + return ret; + } + if (own) + __set_bit(b, &d->owned); + else + __clear_bit(b, &d->owned); + } + return 0; +} diff --git a/drivers/soc/apple/sleep-t6000.h b/drivers/soc/apple/sleep-t6000.h new file mode 100644 index 0000000000000..6c21e80e4a534 --- /dev/null +++ b/drivers/soc/apple/sleep-t6000.h @@ -0,0 +1,2113 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * T6000 (M1 Pro, J314s: two E cores and two P clusters of three). Included by sleep.c. + * + * The sequence is macOS 13's (its PMGR's sleep entry and exit, and the kernel's last + * steps before the sleep): the boot core quiesces the memory controller, the error and counter + * blocks, the internal PCIe block's handshake, the CPU complexes, the memory clock and the AFR + * fabric, takes every cluster's target to 0 and parks the SoC clocks on the reference clock. + * Only then are the parked cores stopped, the late power-state image written, and the S2R + * timer started. Every core then writes back its L1 and takes a WFI without retention. + * + * Register map: the PMGR power-state blocks, CPU start, wake, watchdog, S2R timer, NUB SPMI + * vector enables and PMP telemetry are the sleep node's reg, the NCO its apple,nco; the CPU + * complexes, memory controllers and the other blocks the sequence touches once are fixed for + * the SoC and mapped here, as on T8103. None of them is claimed: their own drivers map them too. + */ + +/* In "ps" (ADT /arm-io/pmgr reg[0], 0x28e080000) */ +#define T6000_PS_AFR 0x1e8 +#define T6000_PS_PMP 0x2d8 +#define T6000_CLUSTER_PS 0x18000 + +#define T6000_PS_BASE 0x28e080000ULL +#define T6000_PS_EAST_BASE 0x28e580000ULL +#define T6000_PS_SIZE 0x1000 + +/* + * The PMGR's cluster words, one per ADT soc-clusters entry: target in [3:0], bit 4 set while + * it changes. The three CPU clusters go down with their cores. + */ +#define T6000_CLUSTERS 9 +#define T6000_CLUSTER_EACC 0 +#define T6000_CLUSTER_PACC0 1 +#define T6000_CLUSTER_PACC1 2 +#define T6000_CLUSTER_ANE0 3 +#define T6000_CLUSTER_AFR 5 +#define T6000_CLUSTER_DISPLAY 6 +#define T6000_CLUSTER_AVEMSR 8 +#define T6000_CLUSTERS_CPU (BIT(T6000_CLUSTER_EACC) | BIT(T6000_CLUSTER_PACC0) | \ + BIT(T6000_CLUSTER_PACC1)) +#define T6000_CLUSTERS_VALID (T6000_CLUSTERS_CPU | BIT(T6000_CLUSTER_ANE0) | \ + BIT(T6000_CLUSTER_AFR) | BIT(T6000_CLUSTER_DISPLAY) | \ + BIT(T6000_CLUSTER_AVEMSR)) +#define T6000_CLUSTER_TARGET GENMASK(3, 0) +#define T6000_CLUSTER_BUSY BIT(4) + +/* The CPU complexes' ACC blocks (64-bit registers): ECPU, PCPU0, PCPU1 */ +#define T6000_ACC_BASE 0x210e20000ULL +#define T6000_ACC_STRIDE 0x1000000ULL +#define T6000_ACCS 3 +#define T6000_ACC_SIZE 0x29000 +#define T6000_ACC_DVFS 0x00020 +#define T6000_ACC_DVFS_APSC_OFF BIT_ULL(22) +#define T6000_ACC_DVFS_BUSY BIT_ULL(7) +#define T6000_ACC_DVFS_RELOCK 0x100101ULL +#define T6000_ACC_DVFS_APSC_MACOS 0x40000500101ULL +#define T6000_ACC_LLC_THRTL 0x20240 +#define T6000_ACC_AMX_THRTL 0x20250 +#define T6000_ACC_THRTL_EN BIT_ULL(63) +#define T6000_ACC_PERF 0x00660 +#define T6000_ACC_PERF_EN 0x15ULL +#define T6000_ACC_ENERGY 0x28080 +#define T6000_ACC_ENERGY_EN (BIT_ULL(63) | BIT_ULL(61)) +#define T6000_ACC_PPT_THRTL 0x28400 + +enum { T6000_ACCR_PERF, T6000_ACCR_ENERGY, T6000_ACCR_AMX, T6000_ACCR_LLC, T6000_ACCR_PPT, + T6000_ACCR_DVFS, T6000_ACCR_N }; + +static const u32 t6000_acc_regs[T6000_ACCR_N] = { + [T6000_ACCR_PERF] = T6000_ACC_PERF, + [T6000_ACCR_ENERGY] = T6000_ACC_ENERGY, + [T6000_ACCR_AMX] = T6000_ACC_AMX_THRTL, + [T6000_ACCR_LLC] = T6000_ACC_LLC_THRTL, + [T6000_ACCR_PPT] = T6000_ACC_PPT_THRTL, + [T6000_ACCR_DVFS] = T6000_ACC_DVFS, +}; + +/* + * In "clk-gen" (ClkGenSOC): five muxes from here onto the reference clock, in macOS's order + * (0x160 stays for the late steps) + */ +#define T6000_CLKGEN_QUIESCE 0x15c +#define T6000_CLKGEN_MUXES 5 +#define T6000_CLKGEN_ON BIT(31) +#define T6000_CLKGEN_BUSY BIT(30) +#define T6000_CLKGEN_SEL GENMASK(27, 24) +static const u8 t6000_clkgen_mux_off[T6000_CLKGEN_MUXES] = { 0x08, 0x10, 0x0c, 0x00, 0x14 }; + +/* PLL 0, left in off mode 3 as macOS's setPLLOffMode() leaves it */ +#define T6000_PLL0 0x28e224000ULL +#define T6000_PLL_ON BIT(0) +#define T6000_PLL_OFF_OK BIT(1) +#define T6000_PLL_OFF_MODE GENMASK(5, 3) +#define T6000_PLL_BUSY BIT(31) + +/* + * The memory clock's and the fabric's performance-state words: pmgr_misc's "dcs-ps" and + * "fabric-ps" (apple,t6000-pmgr-misc). Fields as drivers/soc/apple/apple-pmgr-misc.c has them. + */ +#define T6000_DCS_PS_TARGET GENMASK(3, 0) +#define T6000_DCS_PS_ACTUAL GENMASK(7, 4) +#define T6000_DCS_PS_BUSY BIT(31) + +/* + * The memory controllers: each AMCC drained (+0x1c00 = 0 under the +0x10000c lock, +0x1c04 + * polled to 0), and each DCS's +0x10 with bit 12 on as XNU sets it at boot. + */ +#define T6000_AMCCS 4 +#define T6000_AMCC_BASE 0x200000000ULL +#define T6000_AMCC_STRIDE 0x1000000ULL +#define T6000_AMCC_MAP 0x160000 +#define T6000_AMCC_DRAIN_CTL 0x1c00 +#define T6000_AMCC_DRAIN_CNT 0x1c04 +#define T6000_AMCC_LOCK 0x10000c +#define T6000_DCS_PER_AMCC 4 +#define T6000_DCS_OFF(k) (0x200000ULL * ((k) + 1)) +#define T6000_DCS_CTL 0x10 +#define T6000_DCS_CTL_IBOOT 0x70a0100 +#define T6000_DCS_CTL_MACOS 0x70a1100 + +/* The internal PCIe block's quiesce handshake: 0x8014 = 1, then 0x82bc = 1, 2, 4 */ +#define T6000_APCIE_Q_8014 0x58c008014ULL +#define T6000_APCIE_Q_82BC 0x58c0082bcULL + +/* In "ptd" (PMP telemetry): the word macOS sets to 4 right after slpw */ +#define T6000_PTD_SLEEP 0x18328 + +/* In "spmi-irq": the NUB SPMI vector enables, the clear words 0x40 above */ +#define T6000_SPMI_WORDS 7 +#define T6000_SPMI_CLEAR 0x40 +/* Vector 2: the PMU RTC's alarm, on before the S2R timer as macOS has it */ +#define T6000_SPMI_VEC_RTC BIT(2) + +/* + * The NCO block (apple,nco): its five channels clock the MCA clusters. Every enable bit + * stays on across the sleep, and the sleep resets each channel's rate registers. + */ +#define T6000_NCO_CHANS 5 +#define T6000_NCO_STRIDE 0x4000 +#define T6000_NCO_REG_CTRL 0x00 +#define T6000_NCO_REG_DIV 0x04 +#define T6000_NCO_REG_INC1 0x08 +#define T6000_NCO_REG_INC2 0x0c +#define T6000_NCO_REG_ACCINIT 0x10 +#define T6000_NCO_CTRL_EN BIT(31) + +/* The NUB PMGR's power words: they keep their state through the sleep */ +#define T6000_NUB_PS 0x292280000ULL + +/* WD1 from the late steps to the wake: it keeps counting through the sleep */ +#define T6000_WDT_GO_SECS 120 +/* WD1 from the wake to .end: counted again from 0, for the device resume */ +#define T6000_WDT_WAKE_SECS 170U + +/* The wake's power-domain walk: passes, 10 ms apart, while some are still off */ +#define T6000_PSALL_PASSES 30 +#define T6000_PSALL_MAX 256 +#define T6000_PSALL_BASES 8 + +/* SIQ_CFG (SYS_APL_SIQ_CFG_EL1): whether the AIC delivers IRQs to this core */ +#define T6000_SIQ_CFG_ROUTE GENMASK_ULL(1, 0) +#define T6000_SIQ_CFG_ROUTE_NONE 3 + +/* Each core's power-down overrides */ +#define T6000_CYC_OVRD sys_reg(3, 5, 15, 5, 0) +#define T6000_CYC_DISABLE_WFI_RET BIT_ULL(0) +#define T6000_CYC_FIQ_MODE GENMASK_ULL(21, 20) +#define T6000_CYC_IRQ_MODE GENMASK_ULL(23, 22) +#define T6000_CYC_WFI_MODE GENMASK_ULL(25, 24) +#define T6000_ACC_OVRD sys_reg(3, 5, 15, 6, 0) +#define T6000_ACC_PWR_DN_SRM GENMASK_ULL(14, 13) +#define T6000_ACC_DIS_L2_FLUSH GENMASK_ULL(16, 15) +#define T6000_ACC_TRAIN_DOWN_LINK GENMASK_ULL(18, 17) +#define T6000_ACC_POWER_DOWN_CPM GENMASK_ULL(26, 25) +#define T6000_ACC_DISABLE_PIO_ON_WFI BIT_ULL(32) +#define T6000_ACC_DEEP_SLEEP BIT_ULL(34) + +/* + * The head of macOS's PMGR sleep entry, in its order: the error-handler enables, the + * performance counters, then the SoC voltage monitors. Each written 0, and put back in reverse + * at the wake. + */ +static const u64 t6000_zero_pa[] = { + 0x282000a00, 0x304000a00, 0x383000a00, 0x402000a00, + 0x28e0ad000, 0x28e0f8000, 0x28e0f9000, 0x28e0fa000, 0x28e0fb000, 0x28e0fc000, + 0x28e0fd000, 0x28e070000, 0x28e5d8000, + 0x28e5e0000, 0x28e5e4000, 0x28e0c8200, 0x28e0c8400, 0x28e0c8600, 0x28e0c8000, +}; + +/* + * The late steps, right before the S2R timer, exactly as macOS takes them (our hv traces of + * macOS on J314s): every word gets the value macOS writes, in its order, with its waits, and + * nothing is polled but SIO's CPU word. The PMGR words and their values are the sleep node's + * apple,sleep-late-domains, in its order; these steps say where the other words fall between + * them. Each of those is a named block's: "clk-gen", pmgr_misc's "fabric-ps", SIO's CPU, + * mailbox and DARTs (apple,sio), and one word in the NUB not described yet. + */ +enum t6000_late_op { + T6000_LATE_PS, /* the next arg words of apple,sleep-late-domains */ + T6000_LATE_WAIT, /* arg microseconds */ + T6000_LATE_CLKGEN, /* "clk-gen" + arg */ + T6000_LATE_NUB, /* T6000_LATE_NUB_PA */ + T6000_LATE_FABRIC, /* pmgr_misc's "fabric-ps" */ + T6000_LATE_SIO, /* SIO's word arg, written only while SIO's CPU word is on */ +}; + +enum { + T6000_LATE_SIO_ASC, /* its CPU's control word */ + T6000_LATE_SIO_MBOX, /* its mailbox's I2A control */ + T6000_LATE_SIO_DART0, /* each DART's stream enables */ + T6000_LATE_SIO_DART1, + T6000_LATE_SIO_N, +}; + +static const struct { + u8 op; + u16 arg; + u32 val; +} t6000_late_steps[] = { + { T6000_LATE_PS, 2 }, { T6000_LATE_WAIT, 2000 }, + { T6000_LATE_PS, 42 }, { T6000_LATE_CLKGEN, 0x104, 0x80100000 }, + { T6000_LATE_CLKGEN, 0x108, 0x80100000 }, { T6000_LATE_CLKGEN, 0x10c, 0x80100000 }, + { T6000_LATE_CLKGEN, 0x114, 0x8a100100 }, { T6000_LATE_CLKGEN, 0x120, 0x85100100 }, + { T6000_LATE_CLKGEN, 0x124, 0x85100100 }, { T6000_LATE_CLKGEN, 0x128, 0x87100100 }, + { T6000_LATE_CLKGEN, 0x12c, 0x87100100 }, { T6000_LATE_CLKGEN, 0x130, 0x87100100 }, + { T6000_LATE_CLKGEN, 0x134, 0x87100100 }, { T6000_LATE_CLKGEN, 0x138, 0x87100100 }, + { T6000_LATE_CLKGEN, 0x13c, 0x87100100 }, { T6000_LATE_CLKGEN, 0x148, 0x80100100 }, + { T6000_LATE_CLKGEN, 0x14c, 0x85100100 }, { T6000_LATE_CLKGEN, 0x160, 0x85100100 }, + { T6000_LATE_CLKGEN, 0x180, 0x87100000 }, { T6000_LATE_CLKGEN, 0x184, 0x87100000 }, + { T6000_LATE_CLKGEN, 0x188, 0x87100000 }, { T6000_LATE_CLKGEN, 0x18c, 0x87100100 }, + { T6000_LATE_NUB, 0, 0x80100010 }, { T6000_LATE_FABRIC, 0, 0x333 }, + { T6000_LATE_WAIT, 2000 }, { T6000_LATE_PS, 1 }, + { T6000_LATE_SIO, T6000_LATE_SIO_ASC, 0x0 }, { T6000_LATE_SIO, T6000_LATE_SIO_MBOX, 0x0 }, + { T6000_LATE_SIO, T6000_LATE_SIO_DART0, 0x0 }, { T6000_LATE_SIO, T6000_LATE_SIO_DART1, 0x0 }, + { T6000_LATE_PS, 2 }, { T6000_LATE_CLKGEN, 0x098, 0x00000000 }, + { T6000_LATE_CLKGEN, 0x09c, 0x00000000 }, { T6000_LATE_CLKGEN, 0x0a0, 0x00000000 }, + { T6000_LATE_CLKGEN, 0x0a4, 0x00000000 }, { T6000_LATE_WAIT, 100 } +}; + +/* After the late steps, before the S2R timer */ +#define T6000_LATE_MS 200 +/* The NUB word macOS writes with the late steps; no node describes it yet */ +#define T6000_LATE_NUB_PA 0x292240000ULL + +#define T6000_LATE_MAX 96 + +/* SIO (apple,sio): its mailbox's I2A control, its DARTs' stream enables */ +#define T6000_MBOX_I2A_CONTROL 0x114 +#define T6000_DART_STREAMS_ENABLE 0xfc + +static struct t6000_sleep { + void __iomem *ps_east, *spmi_irq, *nco, *ptd; + void __iomem *cluster_ps, *afr_ps, *pmp_ps; + void __iomem *dcs, *fabric_ps, *pll, *clkgen_blk, *clkgen, *apcie_8014, *apcie_82bc; + void __iomem *acc[T6000_ACCS]; + void __iomem *amcc[T6000_AMCCS], *dcs_blk[T6000_AMCCS][T6000_DCS_PER_AMCC]; + void __iomem *zero[ARRAY_SIZE(t6000_zero_pa)]; + /* SIO's CPU, mailbox and DARTs, and its CPU's power word */ + void __iomem *sio_asc, *sio_mbox, *sio_dart[2], *sio_cpu_ps; + /* The late steps' NUB word */ + void __iomem *late_nub; + /* The PMP, whose stop lets the commit take the memory clock down */ + struct device_node *pmp_np; + /* The boot core, which takes its WFI last */ + + /* This attempt */ + bool committed, quiesce, pmp_idled; + u32 socq_done; + + /* The cluster words the quiesce wrote, as it found them */ + u32 cluster_written, cluster_saved[T6000_CLUSTERS]; + /* + * The AFR cluster word as it was before the GPU's lowering took it to 0 (written by + * sleep-t6000-display.inc): a quiesce restore of 0 leaves it busy and the next sleep + * stalls. Put back once: by the display's undo after a sleep given up, else by the + * quiesce restore. + */ + u32 afr_cl_pre; + bool afr_cl_valid; + + u64 acc_saved[T6000_ACCS][T6000_ACCR_N]; + u64 relock_saved[2]; + u32 mux_saved[T6000_CLKGEN_MUXES], mux_n; + u32 pll_saved, dcs_saved, afr_saved; + u32 zero_saved[ARRAY_SIZE(t6000_zero_pa)]; + u32 apcie_saved[2]; + u32 mcc_done; + + /* The SPMI vector enables as their irqchip had them */ + u32 spmi_saved[T6000_SPMI_WORDS]; + bool spmi_written; + + /* The NCO channels whose enable bit prepare_regs set */ + u8 nco_forced; + /* Each NCO channel's control, divider and increments as prepare_regs found them */ + u32 nco_saved[T6000_NCO_CHANS][4]; + + /* The PTD sleep word before .prepare set it to 4 */ + u32 ptd_sleep_saved; + bool ptd_noticed; + + /* The late steps' words, in the order they are written, as Linux had them at .begin */ + struct t6000_late_word { + void __iomem *reg; + u8 op; + u32 val, saved; + } late[T6000_LATE_MAX]; + unsigned int late_n; + bool late_applied; + + /* The display blocks are down for this sleep and come back with a given-up one */ + bool disp_undo_due; + + /* Every PMGR power word with a node, as before the sleep, walked back up at the wake */ + struct { + struct device_node *np; + void __iomem *reg; + const char *name; + u64 pa; + u32 saved; + } psall[T6000_PSALL_MAX]; + unsigned int psall_n, psall_pass, psall_stuck; + bool psall_armed; + struct { + resource_size_t start; + void __iomem *base; + } psall_base[T6000_PSALL_BASES]; + unsigned int psall_nbase; + + /* The memory controllers' power words at the first sleep's S2R timer */ + u32 go_base[T6000_PSALL_MAX]; + bool go_base_taken; + /* DCS words that did not settle within the bound, this sleep (for the wake's report) */ + u8 go_timeouts; +} t6000_sleep; + +#define T6000_SOCQ_COUNTERS BIT(0) +#define T6000_SOCQ_THROTTLERS BIT(1) +#define T6000_SOCQ_APSC BIT(2) +#define T6000_SOCQ_CLKGEN BIT(3) +#define T6000_SOCQ_PLL BIT(4) +#define T6000_SOCQ_DCS BIT(5) +#define T6000_SOCQ_AFR BIT(6) +#define T6000_SOCQ_ZEROS BIT(7) +#define T6000_SOCQ_APCIE BIT(8) +#define T6000_SOCQ_RELOCK BIT(9) +#define T6000_SOCQ_MCC BIT(10) +#define T6000_MCC_DCS_LP BIT(2) + +#include "sleep-t6000-display.inc" + +/* Mapped for good, non-posted, or NULL */ +static void __iomem *t6000_ioremap(struct apple_sleep *s, phys_addr_t pa, size_t len) +{ + void __iomem *base = ioremap_np(pa, len); + + if (base && devm_add_action_or_reset(s->dev, apple_sleep_iounmap, (void __force *)base)) + return NULL; + return base; +} + +static void __iomem *t6000_ps(u64 pa) +{ + struct apple_sleep *s = apple_sleep; + + if (pa >= T6000_PS_BASE && pa < T6000_PS_BASE + T6000_PS_SIZE) + return s->ps + (pa - T6000_PS_BASE); + if (pa >= T6000_PS_EAST_BASE && pa < T6000_PS_EAST_BASE + T6000_PS_SIZE) + return t6000_sleep.ps_east + (pa - T6000_PS_EAST_BASE); + return NULL; +} + +/* E cores 0.0.n, P cores 0.1.n and 0.2.n: MPIDR's affinity 1 is the cluster */ +static bool t6000_sleep_cpu_valid(u64 mpidr) +{ + unsigned int cluster = MPIDR_AFFINITY_LEVEL(mpidr, 1); + + return !(mpidr & ~MPIDR_HWID_BITMASK) && !MPIDR_AFFINITY_LEVEL(mpidr, 3) && + MPIDR_AFFINITY_LEVEL(mpidr, 2) == !!cluster && cluster < 3; +} + +/* + * Each core's power-down overrides as Linux has them, back after a refusal, and its SIQ_CFG + * from before it went offline. @held: it answered a sleep's hold and has not been restored + * since. @siq_saved: @siq holds what the core had before it went offline, and is not back + * yet; any value is one, 0 included (route field 0 is a route). + */ +struct t6000_cpu_control { + u64 cyc, acc, siq; + bool saved, held, siq_saved; +}; + +static DEFINE_PER_CPU(struct t6000_cpu_control, t6000_cpu_control); + +/* + * As XNU does for a core going offline: the AIC stops delivering IRQs to it while it can + * still take them. AICv2 can't steer an IRQ, so one delivered after the core masked them + * would stay pending there: its device never sees it handled, and the core keeps aborting + * its power down at the sleep's commit. Runs on that core, interrupts on. + */ +static int t6000_cpu_down_prep(unsigned int cpu) +{ + struct t6000_cpu_control *c = this_cpu_ptr(&t6000_cpu_control); + u64 siq = read_sysreg_s(SYS_APL_SIQ_CFG_EL1); + + c->siq = siq; + c->siq_saved = true; + write_sysreg_s(siq | FIELD_PREP(T6000_SIQ_CFG_ROUTE, T6000_SIQ_CFG_ROUTE_NONE), + SYS_APL_SIQ_CFG_EL1); + isb(); + + return 0; +} + +/* Back online, after an offline that was rolled back or through a reset after a wake */ +static void t6000_cpu_siq_restore(struct t6000_cpu_control *c) +{ + if (!c->siq_saved) + return; + if (FIELD_GET(T6000_SIQ_CFG_ROUTE, read_sysreg_s(SYS_APL_SIQ_CFG_EL1)) == + T6000_SIQ_CFG_ROUTE_NONE) { + write_sysreg_s(c->siq, SYS_APL_SIQ_CFG_EL1); + isb(); + } + c->siq_saved = false; +} + +static int t6000_cpu_online(unsigned int cpu) +{ + t6000_cpu_siq_restore(this_cpu_ptr(&t6000_cpu_control)); + + return 0; +} + +static void t6000_cpuhp_remove(void *data) +{ + cpuhp_remove_state_nocalls((enum cpuhp_state)(uintptr_t)data); +} + +static int t6000_sleep_cpu_prepare(u64 mpidr) +{ + struct t6000_cpu_control *c = this_cpu_ptr(&t6000_cpu_control); + + if (!is_kernel_in_hyp_mode()) + return -EOPNOTSUPP; + c->held = true; + if (!c->saved) { + c->cyc = read_sysreg_s(T6000_CYC_OVRD); + c->acc = read_sysreg_s(T6000_ACC_OVRD); + c->saved = true; + } + return 0; +} + +/* + * Called by a held core that a refused sleep sends back to the park, and by every core that + * comes online through the spin table, before any CPU hotplug callback of its own runs: the + * AIC's reads the route there. A core still parked keeps the route at none until then. + */ +static void t6000_sleep_cpu_restore(u64 mpidr) +{ + struct t6000_cpu_control *c = this_cpu_ptr(&t6000_cpu_control); + bool parked = c->held && !pm_resume_via_firmware(); + + c->held = false; + if (!parked) + t6000_cpu_siq_restore(c); + if (!c->saved) + return; + write_sysreg_s(c->acc, T6000_ACC_OVRD); + write_sysreg_s(c->cyc, T6000_CYC_OVRD); + isb(); + c->saved = false; +} + +/* + * void t6000_cpu_off(u64 cyc_ovrd, u64 acc_ovrd): a core's last instructions, as XNU takes + * them. The data cache off and L1 written back and invalidated by set and way (the L2 and the + * memory cache are the hardware's), the timers off, ACC_OVRD then CYC_OVRD written, then WFI + * until the power goes. Uses no stack once the cache is off. Never returns. + * + * int t6000_cpu_sleep(u64 cyc_ovrd, u64 acc_ovrd): the same for the boot core, the last one. + * A pending fast IPI is acknowledged before each WFI, as on T8103. Another interrupt already + * pending keeps the core from powering down and its WFI returns at once: the data cache goes + * back on and it returns -EBUSY rather than wait there for the watchdog. + */ +asm(" .pushsection .text, \"ax\"\n" +" .type t6000_cpu_off, %function\n" +"t6000_cpu_off:\n" +" mov x11, #0\n" +" b 0f\n" +" .size t6000_cpu_off, . - t6000_cpu_off\n" +" .type t6000_cpu_sleep, %function\n" +"t6000_cpu_sleep:\n" +" mov x11, #1\n" +"0: msr daifset, #0xf\n" +" mrs x3, sctlr_el1\n" +" bic x3, x3, #(1 << 2)\n" +" msr sctlr_el1, x3\n" +" isb\n" +" msr csselr_el1, xzr\n" +" isb\n" +" mrs x3, ccsidr_el1\n" +" and x4, x3, #7\n" +" add x4, x4, #4\n" +" ubfx x5, x3, #3, #10\n" +" ubfx x6, x3, #13, #15\n" +" clz w7, w5\n" +"1: mov x8, x6\n" +"2: lsl x9, x5, x7\n" +" lsl x10, x8, x4\n" +" orr x9, x9, x10\n" +" dc cisw, x9\n" +" subs x8, x8, #1\n" +" b.ge 2b\n" +" subs x5, x5, #1\n" +" b.ge 1b\n" +" dsb sy\n" +" isb\n" +/* A pending timer, even a masked one, keeps the core from powering down */ +" msr cntp_ctl_el0, xzr\n" +" msr cntv_ctl_el0, xzr\n" +" mrs x3, CurrentEL\n" +" cmp x3, #(2 << 2)\n" +" b.ne 3f\n" +" msr s3_5_c14_c2_1, xzr\n" /* CNTP_CTL_EL02 */ +" msr s3_5_c14_c3_1, xzr\n" /* CNTV_CTL_EL02 */ +"3: msr s3_5_c15_c6_0, x1\n" /* ACC_OVRD */ +" msr s3_5_c15_c5_0, x0\n" /* CYC_OVRD */ +" isb\n" +" mov x9, #1\n" +"4: msr s3_5_c15_c1_1, x9\n" /* IPI_SR: a fast IPI ends WFI */ +" dsb sy\n" +" isb\n" +" wfi\n" +" cbnz x11, 5f\n" +" b 4b\n" +"5: mrs x3, sctlr_el1\n" +" orr x3, x3, #(1 << 2)\n" +" msr sctlr_el1, x3\n" +" isb\n" +" mov x0, #-16\n" /* -EBUSY */ +" ret\n" +" .size t6000_cpu_sleep, . - t6000_cpu_sleep\n" +" .popsection\n" +); +void t6000_cpu_off(u64 cyc_ovrd, u64 acc_ovrd); +int t6000_cpu_sleep(u64 cyc_ovrd, u64 acc_ovrd); + +/* macOS's enableCluster(false): the target to 0; a CPU cluster goes down with its cores */ +static void t6000_cluster_write(struct t6000_sleep *t, unsigned int i) +{ + void __iomem *reg = t->cluster_ps + 4 * i; + u32 val; + + t->cluster_saved[i] = readl(reg); + writel(t->cluster_saved[i] & ~T6000_CLUSTER_TARGET, reg); + t->cluster_written |= BIT(i); + if (!(T6000_CLUSTERS_CPU & BIT(i))) + readl_poll_timeout_atomic(reg, val, !(val & T6000_CLUSTER_BUSY), 1, 10000); +} + +/* The boot core's own cluster, if the quiesce left it */ +static void t6000_cluster_eacc(struct t6000_sleep *t) +{ + if (!t->quiesce || (t->cluster_written & BIT(T6000_CLUSTER_EACC))) + return; + t6000_cluster_write(t, T6000_CLUSTER_EACC); +} + +/* + * On every core before its last WFI: no retention, woken by a reset; IRQ and FIQ modes 0 so + * a wake interrupt still reaches the core. + */ +static void t6000_deep_ovrd(u64 *cyc, u64 *acc) +{ + *cyc &= ~(T6000_CYC_WFI_MODE | T6000_CYC_IRQ_MODE | T6000_CYC_FIQ_MODE); + *cyc |= FIELD_PREP(T6000_CYC_WFI_MODE, 3) | T6000_CYC_DISABLE_WFI_RET; + *acc &= ~(T6000_ACC_PWR_DN_SRM | T6000_ACC_DIS_L2_FLUSH | T6000_ACC_TRAIN_DOWN_LINK | + T6000_ACC_POWER_DOWN_CPM); + *acc |= FIELD_PREP(T6000_ACC_PWR_DN_SRM, 3) | FIELD_PREP(T6000_ACC_DIS_L2_FLUSH, 2) | + FIELD_PREP(T6000_ACC_TRAIN_DOWN_LINK, 3) | FIELD_PREP(T6000_ACC_POWER_DOWN_CPM, 3) | + T6000_ACC_DISABLE_PIO_ON_WFI | T6000_ACC_DEEP_SLEEP; +} + +/* A stopped core's last WFI; the boot core's is t6000_sleep_boot_sleep() */ +static void t6000_deep_wfi_arm(void) +{ + u64 cyc = read_sysreg_s(T6000_CYC_OVRD), acc = read_sysreg_s(T6000_ACC_OVRD); + + t6000_deep_ovrd(&cyc, &acc); + t6000_cpu_off(cyc, acc); + unreachable(); +} + +static void t6000_quiesce_restore(struct t6000_sleep *t); +static void t6000_spmi_restore(struct t6000_sleep *t); + +/* + * The boot core, the last one, first gives its own cluster's target a last chance, as macOS + * does after it releases the others. Back only if an interrupt already pending ended its WFI: + * the sleep is given up, and the quiesce and the RTC alarm's vector go back first. + */ +static int t6000_sleep_boot_sleep(void) +{ + struct t6000_sleep *t = &t6000_sleep; + u64 cyc = read_sysreg_s(T6000_CYC_OVRD), acc = read_sysreg_s(T6000_ACC_OVRD); + int ret; + + t6000_cluster_eacc(t); + t6000_deep_ovrd(&cyc, &acc); + ret = t6000_cpu_sleep(cyc, acc); + t6000_quiesce_restore(t); + t6000_spmi_restore(t); + return ret; +} + +/* PMGR registers only, and none that iBoot armed or that must never be touched */ +static bool t6000_restore_pa_ok(u64 pa) +{ + if (pa < 0x28e000000ULL || pa >= 0x293000000ULL) + return false; + if ((pa >= 0x28e200000ULL && pa < 0x28e208000ULL) || + (pa >= 0x28e941000ULL && pa < 0x28e942000ULL) || + (pa >= 0x28e59c000ULL && pa < 0x28e59d000ULL) || + (pa >= 0x28e099000ULL && pa < 0x28e099078ULL) || + (pa >= 0x292000200ULL && pa < 0x292000204ULL) || + (pa >= 0x2922b0000ULL && pa < 0x2922b0100ULL) || + (pa >= 0x2922c0000ULL && pa < 0x2922c0314ULL) || + (pa >= 0x2922dc21cULL && pa < 0x2922dc22cULL) || + (pa >= 0x2925c0000ULL && pa < 0x2925d4000ULL) || + (pa >= 0x292f00000ULL && pa < 0x292f70000ULL)) + return false; + return true; +} + +static void __iomem *t6000_psall_map(struct apple_sleep *s, struct device_node *parent, + resource_size_t *start) +{ + struct t6000_sleep *t = &t6000_sleep; + struct resource res; + unsigned int b; + + if (of_address_to_resource(parent, 0, &res)) + return NULL; + *start = res.start; + for (b = 0; b < t->psall_nbase; b++) + if (t->psall_base[b].start == res.start) + return t->psall_base[b].base; + if (t->psall_nbase == T6000_PSALL_BASES) + return NULL; + t->psall_base[b].start = res.start; + t->psall_base[b].base = t6000_ioremap(s, res.start, resource_size(&res)); + if (t->psall_base[b].base) + t->psall_nbase++; + return t->psall_base[b].base; +} + +/* Every PMGR power word with a node, but SEP's, AFC's and AFI's */ +static int t6000_psall_init(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + struct device_node *np, *parent; + resource_size_t start; + void __iomem *base; + const char *label; + u32 off; + + for_each_compatible_node(np, NULL, "apple,pmgr-pwrstate") { + if (t->psall_n == T6000_PSALL_MAX) { + of_node_put(np); + break; + } + label = NULL; + of_property_read_string(np, "label", &label); + if (!label || !strcmp(label, "sep") || !strcmp(label, "afc") || + !strcmp(label, "afi")) + continue; + if (of_property_read_u32(np, "reg", &off)) + continue; + parent = of_get_parent(np); + base = parent ? t6000_psall_map(s, parent, &start) : NULL; + of_node_put(parent); + if (!base || !t6000_restore_pa_ok(start + off)) + continue; + of_node_get(np); + if (devm_add_action_or_reset(s->dev, apple_sleep_put_node, np)) { + of_node_put(np); + return -ENOMEM; + } + t->psall[t->psall_n].np = np; + t->psall[t->psall_n].reg = base + off; + t->psall[t->psall_n].name = label; + t->psall[t->psall_n].pa = start + off; + t->psall_n++; + } + return 0; +} + +/* Another node's reg, by index, mapped as the sleep node's own: shared, not claimed */ +static void __iomem *t6000_map_node(struct apple_sleep *s, struct device_node *np, int index) +{ + struct resource res; + + if (index < 0 || of_address_to_resource(np, index, &res)) + return NULL; + return t6000_ioremap(s, res.start, resource_size(&res)); +} + +static void __iomem *t6000_map_named(struct apple_sleep *s, struct device_node *np, + const char *name) +{ + return t6000_map_node(s, np, of_property_match_string(np, "reg-names", name)); +} + +/* apple,pmgr-misc: the memory clock's and the fabric's performance-state words */ +static int t6000_pmgr_misc_map(struct apple_sleep *s, struct t6000_sleep *t) +{ + struct device_node *misc = of_parse_phandle(s->dev->of_node, "apple,pmgr-misc", 0); + + if (misc) { + t->dcs = t6000_map_named(s, misc, "dcs-ps"); + t->fabric_ps = t6000_map_named(s, misc, "fabric-ps"); + of_node_put(misc); + } + if (!t->dcs || !t->fabric_ps) + return dev_err_probe(s->dev, -EINVAL, + "apple,pmgr-misc: dcs-ps and fabric-ps must both be mapped\n"); + return 0; +} + +static int t6000_psall_find(struct t6000_sleep *t, struct device_node *np); + +/* A power-state node's word, from the walk of every PMGR word (t6000_psall_init()) */ +static void __iomem *t6000_ps_reg(struct t6000_sleep *t, struct device_node *np) +{ + int i = np ? t6000_psall_find(t, np) : -1; + + return i < 0 ? NULL : t->psall[i].reg; +} + +static int t6000_late_add(struct apple_sleep *s, struct t6000_sleep *t, void __iomem *reg, + u8 op, u32 val) +{ + if (t->late_n == T6000_LATE_MAX) + return dev_err_probe(s->dev, -E2BIG, "more than %u late-step words\n", + T6000_LATE_MAX); + t->late[t->late_n].reg = reg; + t->late[t->late_n].op = op; + t->late[t->late_n].val = val; + t->late_n++; + return 0; +} + +/* apple,sio: SIO's CPU (its reg), mailbox, two DARTs and CPU power word, by its node */ +static int t6000_sio_map(struct apple_sleep *s, struct t6000_sleep *t) +{ + struct device_node *sio = of_parse_phandle(s->dev->of_node, "apple,sio", 0), *np; + struct of_phandle_args args; + unsigned int i; + + if (!sio) + return dev_err_probe(s->dev, -EINVAL, "apple,sio is missing\n"); + t->sio_asc = t6000_map_node(s, sio, 0); + np = of_parse_phandle(sio, "mboxes", 0); + if (np) { + t->sio_mbox = t6000_map_node(s, np, 0); + of_node_put(np); + } + for (i = 0; i < ARRAY_SIZE(t->sio_dart); i++) { + if (of_parse_phandle_with_args(sio, "iommus", "#iommu-cells", i, &args)) + break; + t->sio_dart[i] = t6000_map_node(s, args.np, 0); + of_node_put(args.np); + } + np = of_parse_phandle(sio, "power-domains", 0); + t->sio_cpu_ps = t6000_ps_reg(t, np); + of_node_put(np); + of_node_put(sio); + if (!t->sio_asc || !t->sio_mbox || !t->sio_dart[0] || !t->sio_dart[1] || !t->sio_cpu_ps) + return dev_err_probe(s->dev, -EINVAL, + "apple,sio: CPU, mailbox, DARTs or power word not mapped\n"); + return 0; +} + +/* The next n entries of apple,sleep-late-domains: a PMGR power word and the value it gets */ +static int t6000_late_add_ps(struct apple_sleep *s, struct t6000_sleep *t, + struct of_phandle_iterator *it, unsigned int n) +{ + void __iomem *reg; + u32 val; + int ret; + + while (n--) { + ret = of_phandle_iterator_next(it); + if (ret) + return dev_err_probe(s->dev, -EINVAL, + "apple,sleep-late-domains: fewer entries than the steps\n"); + reg = t6000_ps_reg(t, it->node); + if (!reg || of_phandle_iterator_args(it, &val, 1) != 1) + ret = dev_err_probe(s->dev, -EINVAL, + "apple,sleep-late-domains: %pOF is not a PMGR power word\n", + it->node); + else + ret = t6000_late_add(s, t, reg, T6000_LATE_PS, val); + if (ret) { + of_node_put(it->node); + it->node = NULL; + return ret; + } + } + return 0; +} + +/* + * The late steps from the sleep node: t6000_late_steps[] with each PMGR step's words taken in + * order from apple,sleep-late-domains, which must have exactly as many. A missing block or a + * phandle that is not a PMGR power word fails the probe. + */ +static int t6000_late_init(struct apple_sleep *s, struct t6000_sleep *t) +{ + void __iomem *sio_reg[T6000_LATE_SIO_N]; + struct of_phandle_iterator it; + void __iomem *reg; + unsigned int i; + int ret; + + ret = t6000_sio_map(s, t); + if (ret) + return ret; + sio_reg[T6000_LATE_SIO_ASC] = t->sio_asc + ASC_CPU_CONTROL; + sio_reg[T6000_LATE_SIO_MBOX] = t->sio_mbox + T6000_MBOX_I2A_CONTROL; + sio_reg[T6000_LATE_SIO_DART0] = t->sio_dart[0] + T6000_DART_STREAMS_ENABLE; + sio_reg[T6000_LATE_SIO_DART1] = t->sio_dart[1] + T6000_DART_STREAMS_ENABLE; + t->late_nub = t6000_ioremap(s, T6000_LATE_NUB_PA, 4); + if (!t->late_nub) + return dev_err_probe(s->dev, -ENOMEM, "the late steps' NUB word not mapped\n"); + + ret = of_phandle_iterator_init(&it, s->dev->of_node, "apple,sleep-late-domains", NULL, 1); + if (ret) + return dev_err_probe(s->dev, ret, "apple,sleep-late-domains is missing\n"); + for (i = 0; i < ARRAY_SIZE(t6000_late_steps); i++) { + u8 op = t6000_late_steps[i].op; + u16 arg = t6000_late_steps[i].arg; + u32 val = t6000_late_steps[i].val; + + switch (op) { + case T6000_LATE_PS: + ret = t6000_late_add_ps(s, t, &it, arg); + break; + case T6000_LATE_WAIT: + ret = t6000_late_add(s, t, NULL, op, arg); + break; + default: + reg = op == T6000_LATE_CLKGEN ? t->clkgen_blk + arg : + op == T6000_LATE_NUB ? t->late_nub : + op == T6000_LATE_FABRIC ? t->fabric_ps : sio_reg[arg]; + ret = t6000_late_add(s, t, reg, op, val); + break; + } + if (ret) { + of_node_put(it.node); + return ret; + } + } + if (of_phandle_iterator_next(&it) != -ENOENT) { + of_node_put(it.node); + return dev_err_probe(s->dev, -EINVAL, + "apple,sleep-late-domains: more entries than the steps\n"); + } + return 0; +} + +/* The NCO block of the sleep node's apple,nco: mapped, not requested, as its driver has it. */ +static void __iomem *t6000_map_nco(struct apple_sleep *s) +{ + struct device_node *np = of_parse_phandle(s->dev->of_node, "apple,nco", 0); + struct resource res; + void __iomem *base; + int ret; + + if (!np) + return IOMEM_ERR_PTR(-ENODEV); + ret = of_address_to_resource(np, 0, &res); + of_node_put(np); + if (ret || resource_size(&res) < T6000_NCO_CHANS * T6000_NCO_STRIDE) + return IOMEM_ERR_PTR(-EINVAL); + base = ioremap_np(res.start, resource_size(&res)); + if (!base || devm_add_action_or_reset(s->dev, apple_sleep_iounmap, (void __force *)base)) + return IOMEM_ERR_PTR(-ENOMEM); + return base; +} + +static int t6000_sleep_map_regs(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + unsigned int i, a; + int ret; + + s->ps = apple_sleep_map(s->dev, "ps"); + t->ps_east = apple_sleep_map(s->dev, "ps-east"); + s->cpu_start = apple_sleep_map(s->dev, "cpu-start"); + s->wake = apple_sleep_map(s->dev, "wake"); + s->wdt = apple_sleep_map(s->dev, "wdt"); + s->commit = apple_sleep_map(s->dev, "commit"); + t->spmi_irq = apple_sleep_map(s->dev, "spmi-irq"); + t->nco = t6000_map_nco(s); + t->ptd = apple_sleep_map(s->dev, "ptd"); + if (IS_ERR(s->ps) || IS_ERR(t->ps_east) || IS_ERR(s->cpu_start) || IS_ERR(s->wake) || + IS_ERR(s->wdt) || IS_ERR(s->commit) || IS_ERR(t->spmi_irq) || IS_ERR(t->nco) || + IS_ERR(t->ptd)) + return dev_err_probe(s->dev, -EINVAL, + "ps, ps-east, cpu-start, wake, wdt, commit, spmi-irq, ptd and apple,nco must all be mapped\n"); + t->cluster_ps = s->ps + T6000_CLUSTER_PS; + t->afr_ps = s->ps + T6000_PS_AFR; + t->pmp_ps = s->ps + T6000_PS_PMP; + s->cluster = t->cluster_ps; + + /* The blocks the quiesce writes once: none in the sleep node's reg */ + for (i = 0; i < T6000_ACCS; i++) { + t->acc[i] = t6000_ioremap(s, T6000_ACC_BASE + i * T6000_ACC_STRIDE, + T6000_ACC_SIZE); + if (!t->acc[i]) + return dev_err_probe(s->dev, -ENOMEM, "ACC blocks not mapped\n"); + } + for (a = 0; a < T6000_AMCCS; a++) { + t->amcc[a] = t6000_ioremap(s, T6000_AMCC_BASE + a * T6000_AMCC_STRIDE, + T6000_AMCC_MAP); + for (i = 0; i < T6000_DCS_PER_AMCC; i++) + t->dcs_blk[a][i] = t6000_ioremap(s, T6000_AMCC_BASE + + a * T6000_AMCC_STRIDE + + T6000_DCS_OFF(i), 0x1000); + } + for (i = 0; i < ARRAY_SIZE(t6000_zero_pa); i++) + t->zero[i] = t6000_ioremap(s, t6000_zero_pa[i], 4); + t->clkgen_blk = apple_sleep_map(s->dev, "clk-gen"); + if (IS_ERR(t->clkgen_blk)) + return dev_err_probe(s->dev, PTR_ERR(t->clkgen_blk), "clk-gen must be mapped\n"); + t->clkgen = t->clkgen_blk + T6000_CLKGEN_QUIESCE; + t->pll = t6000_ioremap(s, T6000_PLL0, 4); + ret = t6000_pmgr_misc_map(s, t); + if (ret) + return ret; + t->apcie_8014 = t6000_ioremap(s, T6000_APCIE_Q_8014, 4); + t->apcie_82bc = t6000_ioremap(s, T6000_APCIE_Q_82BC, 4); + + ret = t6000_psall_init(s); + if (ret) + return ret; + ret = t6000_late_init(s, t); + if (ret) + return ret; + + t->pmp_np = of_find_compatible_node(NULL, NULL, "apple,t6000-pmp-v2"); + if (t->pmp_np && devm_add_action_or_reset(s->dev, apple_sleep_put_node, t->pmp_np)) + return -ENOMEM; + + ret = apple_sleep_read_wake_sources(s); + if (ret) + return ret; + + /* + * Every core that goes offline, for a sleep or not, has its IRQs routed away first. Only + * at EL2, where SIQ_CFG is the kernel's to write and the sleep can run at all. + */ + if (is_kernel_in_hyp_mode()) { + ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "soc/apple-sleep-t6000:siq", + t6000_cpu_online, t6000_cpu_down_prep); + if (ret < 0) + return ret; + ret = devm_add_action_or_reset(s->dev, t6000_cpuhp_remove, + (void *)(uintptr_t)ret); + if (ret) + return ret; + } + + return t6000_display_map(s); +} + +/* Awake, at .begin: what Linux has in every word the late steps write */ +static void t6000_late_save(struct t6000_sleep *t) +{ + unsigned int i; + + t->late_applied = false; + for (i = 0; i < t->late_n; i++) + if (t->late[i].op != T6000_LATE_WAIT && t->late[i].op != T6000_LATE_SIO) + t->late[i].saved = readl(t->late[i].reg); +} + +static void t6000_psall_save(struct t6000_sleep *t) +{ + unsigned int i; + + t->psall_armed = false; + for (i = 0; i < t->psall_n; i++) + t->psall[i].saved = readl(t->psall[i].reg); +} + +/* + * Two of .enter's refusals (apple_sleep_refuse()) are known before anything is stopped, and + * are made here too, before the AOP is stopped at .prepare and the display coprocessors and + * the SIO are parked in suspend_late, which a refusal after them has to undo. + * The enclave's driver bound (apple_sleep_gate_failed(); its sleep request is registered only + * when that driver suspends, so that half stays with .enter), and a driver bound to the + * internal display coprocessor. + */ +static int t6000_sleep_refuse_early(struct apple_sleep *s) +{ + struct platform_device *pdev; + bool bound = false; + unsigned int i; + + apple_sleep_gate_prepare(s); + for (i = 0; i < s->gate_count; i++) { + if (s->gate[i].sep && !s->gate[i].bound) { + dev_err(s->dev, "refused: SEP has no prepared irreversible sleep request\n"); + return -EBUSY; + } + } + if (!s->soc->ndisp) + return 0; + pdev = s->display[0].np ? of_find_device_by_node(s->display[0].np) : NULL; + if (pdev) { + bound = device_is_bound(&pdev->dev); + put_device(&pdev->dev); + } + if (!bound) { + dev_err(s->dev, "refused: no driver bound to the display coprocessor\n"); + return -EBUSY; + } + return 0; +} + +static int t6000_sleep_begin(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + int ret; + + ret = t6000_sleep_refuse_early(s); + if (ret) + return ret; + + t->committed = false; + t->quiesce = false; + t->pmp_idled = false; + t->socq_done = 0; + t->mcc_done = 0; + t->mux_n = 0; + t->cluster_written = 0; + t->disp_undo_due = false; + t->afr_cl_valid = false; + t6000_display.cycled = 0; + t6000_display.gpu_port_down = false; + t6000_late_save(t); + t6000_psall_save(t); + return t6000_display_own(s, true); +} + +/* Right after the SMC's slpw, as macOS does: the PMP told too, long before its own last word */ +static void t6000_sleep_smc_warned(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + if (t->ptd_noticed) + return; + t->ptd_sleep_saved = readl(t->ptd + T6000_PTD_SLEEP); + writel(4, t->ptd + T6000_PTD_SLEEP); + t->ptd_noticed = true; +} + +/* At .prepare, every device suspended: the PMP told here if a debug link held slpw back */ +static void t6000_sleep_prepare(struct apple_sleep *s) +{ + t6000_sleep_smc_warned(s); +} + +/* An interrupt raised since they were masked would end the last WFI right away. */ +static int t6000_isr_check(struct apple_sleep *s) +{ + if (read_sysreg(isr_el1) & (PSR_I_BIT | PSR_F_BIT)) { + dev_err(s->dev, "refused: an interrupt is pending\n"); + return -EBUSY; + } + return 0; +} + +/* The SoC's first refusals in .enter: nothing has been written yet. */ +static int t6000_sleep_check(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + t->psall_armed = t->psall_n; + return t6000_isr_check(s); +} + +/* + * The last refusals. SEP's sleep and its power gate are its driver's, at the commit: the gate + * entry (t6000_gate_coprocs) refuses a sleep without them. + */ +static int t6000_sleep_final_check(struct apple_sleep *s) +{ + return t6000_isr_check(s); +} + +/* + * From the display blocks' lowering on, a sleep that is given up puts them back, as one that + * fails halfway does; a real one wakes them. + */ +static int t6000_display_off(struct apple_sleep *s) +{ + t6000_sleep.disp_undo_due = true; + return t6000_sleep_display_off(s); +} + +/* The NCO channels' enable bits restored where prepare_regs set them */ +static void t6000_nco_restore(struct t6000_sleep *t) +{ + unsigned int i; + + for (i = 0; i < T6000_NCO_CHANS; i++) { + void __iomem *reg = t->nco + i * T6000_NCO_STRIDE; + + if (t->nco_forced & BIT(i)) + writel(readl(reg) & ~T6000_NCO_CTRL_EN, reg); + } + t->nco_forced = 0; +} + +/* + * A deep sleep resets the NCO channels' rate registers, and the clock driver, which keeps the + * rate it set, does not program them again: an audio channel would run many times too fast. + * Put back what prepare_regs read, as the T8122 profile does, each channel running until + * t6000_nco_restore() stops the ones prepare_regs started. + */ +static void t6000_nco_put_back(struct t6000_sleep *t) +{ + unsigned int i; + + for (i = 0; i < T6000_NCO_CHANS; i++) { + void __iomem *ch = t->nco + i * T6000_NCO_STRIDE; + u32 ctrl = t->nco_saved[i][0]; + + writel(ctrl & ~T6000_NCO_CTRL_EN, ch + T6000_NCO_REG_CTRL); + writel(t->nco_saved[i][1], ch + T6000_NCO_REG_DIV); + writel(t->nco_saved[i][2], ch + T6000_NCO_REG_INC1); + writel(t->nco_saved[i][3], ch + T6000_NCO_REG_INC2); + writel(BIT(31), ch + T6000_NCO_REG_ACCINIT); + writel(ctrl | T6000_NCO_CTRL_EN, ch + T6000_NCO_REG_CTRL); + } +} + +/* + * After the enclave's stop and the wake mask, before the other coprocessors stop: each NCO + * channel's rate kept for the wake, and, as a channel of the NCO that clocks an MCA cluster + * and was disabled keeps the PMGR from power-gating the SIO island, every channel's enable + * bit on until the wake. + */ +static void t6000_sleep_prepare_regs(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + unsigned int i; + u32 v; + + t->nco_forced = 0; + for (i = 0; i < T6000_NCO_CHANS; i++) { + void __iomem *ch = t->nco + i * T6000_NCO_STRIDE; + + v = readl(ch + T6000_NCO_REG_CTRL); + t->nco_saved[i][0] = v; + t->nco_saved[i][1] = readl(ch + T6000_NCO_REG_DIV); + t->nco_saved[i][2] = readl(ch + T6000_NCO_REG_INC1); + t->nco_saved[i][3] = readl(ch + T6000_NCO_REG_INC2); + if (!(v & T6000_NCO_CTRL_EN)) { + writel(v | T6000_NCO_CTRL_EN, ch + T6000_NCO_REG_CTRL); + t->nco_forced |= BIT(i); + } + } +} + +static void t6000_sleep_undo_regs(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + t6000_nco_restore(t); +} + +/* The memory controllers first: each DCS's low-power bit as XNU sets it, each AMCC drained */ +static void t6000_quiesce_mcc(struct t6000_sleep *t) +{ + unsigned int a, i; + u32 val; + + for (a = 0; a < T6000_AMCCS; a++) + if (!t->amcc[a]) + return; + + for (a = 0; a < T6000_AMCCS; a++) + for (i = 0; i < T6000_DCS_PER_AMCC; i++) + if (t->dcs_blk[a][i]) + writel(T6000_DCS_CTL_MACOS, t->dcs_blk[a][i] + T6000_DCS_CTL); + t->mcc_done |= T6000_MCC_DCS_LP; + + for (a = 0; a < T6000_AMCCS; a++) + writel(1, t->amcc[a] + T6000_AMCC_LOCK); + for (a = 0; a < T6000_AMCCS; a++) + writel(0, t->amcc[a] + T6000_AMCC_DRAIN_CTL); + for (a = 0; a < T6000_AMCCS; a++) + writel(0, t->amcc[a] + T6000_AMCC_LOCK); + for (a = 0; a < T6000_AMCCS; a++) + readl_poll_timeout_atomic(t->amcc[a] + T6000_AMCC_DRAIN_CNT, val, !val, 1, 20000); + t->socq_done |= T6000_SOCQ_MCC; +} + +/* The same bits off in one register of each CPU complex */ +static void t6000_acc_clear(struct t6000_sleep *t, int r, u64 bits) +{ + unsigned int i; + + for (i = 0; i < T6000_ACCS; i++) { + void __iomem *reg = t->acc[i] + t6000_acc_regs[r]; + + t->acc_saved[i][r] = readq(reg); + writeq(t->acc_saved[i][r] & ~bits, reg); + } +} + +/* quiesceACC: counters, throttlers, the PLL relock of ACC0 and ACC1, then the APSC value */ +static void t6000_quiesce_acc(struct t6000_sleep *t) +{ + unsigned int i, n; + u64 val; + + t6000_acc_clear(t, T6000_ACCR_PERF, T6000_ACC_PERF_EN); + t6000_acc_clear(t, T6000_ACCR_ENERGY, T6000_ACC_ENERGY_EN); + t->socq_done |= T6000_SOCQ_COUNTERS; + + t6000_acc_clear(t, T6000_ACCR_AMX, T6000_ACC_THRTL_EN); + t6000_acc_clear(t, T6000_ACCR_LLC, T6000_ACC_THRTL_EN); + t6000_acc_clear(t, T6000_ACCR_PPT, T6000_ACC_THRTL_EN); + t->socq_done |= T6000_SOCQ_THROTTLERS; + + for (i = 0; i < 2; i++) { + void __iomem *reg = t->acc[i] + T6000_ACC_DVFS; + + t->relock_saved[i] = readq(reg); + writeq(T6000_ACC_DVFS_RELOCK, reg); + readq_poll_timeout_atomic(reg, val, !(val & T6000_ACC_DVFS_BUSY), 1, 8000); + } + t->socq_done |= T6000_SOCQ_RELOCK; + + /* Twice, as macOS writes it */ + for (i = 0; i < T6000_ACCS; i++) { + void __iomem *reg = t->acc[i] + T6000_ACC_DVFS; + + t->acc_saved[i][T6000_ACCR_DVFS] = readq(reg); + for (n = 0; n < 2; n++) { + writeq(T6000_ACC_DVFS_APSC_MACOS, reg); + readq_poll_timeout_atomic(reg, val, !(val & T6000_ACC_DVFS_BUSY), 1, 8000); + } + } + t->socq_done |= T6000_SOCQ_APSC; +} + +static bool t6000_dcs_set(struct t6000_sleep *t, u32 ps) +{ + u32 val = readl(t->dcs); + + writel((val & ~T6000_DCS_PS_TARGET) | FIELD_PREP(T6000_DCS_PS_TARGET, ps), t->dcs); + return !readl_poll_timeout_atomic(t->dcs, val, !(val & T6000_DCS_PS_BUSY), 1, 8000); +} + +/* A stopped PMP: it owns the memory clock while it runs. */ +static bool t6000_pmp_stopped(struct t6000_sleep *t) +{ + int i; + + for (i = 0; t->pmp_np && i < SLEEP_COPROCS; i++) + if (apple_sleep_coprocs[i].dev && apple_sleep_coprocs[i].dev->of_node == t->pmp_np) + return apple_sleep_coprocs[i].stopped; + return false; +} + +/* quiescePerfState, then the start of the T6000 tail: memory clock 7 then 5, AFR's word 0 */ +static void t6000_quiesce_dcs_afr(struct t6000_sleep *t) +{ + u32 val; + + t->pmp_idled = t6000_pmp_stopped(t); + if (t->pmp_idled && !FIELD_GET(PS_ACTUAL, readl(t->pmp_ps))) { + t->dcs_saved = readl(t->dcs); + t->socq_done |= T6000_SOCQ_DCS; + t6000_dcs_set(t, 7); + t6000_dcs_set(t, 5); + } + + t->afr_saved = readl(t->afr_ps); + t->socq_done |= T6000_SOCQ_AFR; + writel(0, t->afr_ps); + readl_poll_timeout_atomic(t->afr_ps, val, !(val & PS_ACTUAL), 1, 8000); +} + +/* The blocks in a cluster, which have to be off before it goes down */ +static bool t6000_cluster_gate(unsigned int cluster) +{ + static const u64 ane0[] = { 0x28e080268, 0x28e0802c8, 0 }; + static const u64 afr[] = { 0x28e0801e8, 0x28e5803c0, 0x28e080268, 0x28e080270, + 0x28e580390, 0x28e580398, 0x28e5803b0, 0 }; + /* disp0, dispext0 and dispext1 */ + static const u64 display[] = { 0x28e580350, 0x28e080280, 0x28e0802a8, 0 }; + static const u64 avemsr[] = { 0x28e080270, 0x28e580398, 0x28e5803b0, 0 }; + const u64 *ps; + + switch (cluster) { + case T6000_CLUSTER_ANE0: + ps = ane0; + break; + case T6000_CLUSTER_AFR: + ps = afr; + break; + case T6000_CLUSTER_DISPLAY: + ps = display; + break; + case T6000_CLUSTER_AVEMSR: + ps = avemsr; + break; + default: + return true; + } + + for (; *ps; ps++) { + void __iomem *reg = t6000_ps(*ps); + + if (!reg || FIELD_GET(PS_ACTUAL, readl(reg))) + return false; + } + return true; +} + +/* The SoC clocks onto the reference clock, then PLL 0 off, twice as macOS does */ +static void t6000_quiesce_clocks(struct t6000_sleep *t) +{ + unsigned int i, n; + u32 val; + + for (i = 0; i < T6000_CLKGEN_MUXES; i++) { + void __iomem *reg = t->clkgen + t6000_clkgen_mux_off[i]; + + t->mux_saved[i] = readl(reg); + writel((t->mux_saved[i] & ~T6000_CLKGEN_SEL) | T6000_CLKGEN_ON, reg); + t->mux_n = i + 1; + if (readl_poll_timeout_atomic(reg, val, !(val & T6000_CLKGEN_BUSY), 1, 8000)) + return; + } + t->socq_done |= T6000_SOCQ_CLKGEN; + + t->pll_saved = readl(t->pll); + t->socq_done |= T6000_SOCQ_PLL; + for (n = 0; n < 2; n++) { + writel((readl(t->pll) & ~T6000_PLL_OFF_MODE) | FIELD_PREP(T6000_PLL_OFF_MODE, 3), + t->pll); + writel(readl(t->pll) | T6000_PLL_OFF_OK, t->pll); + writel(readl(t->pll) & ~T6000_PLL_ON, t->pll); + if (readl_poll_timeout_atomic(t->pll, val, !(val & T6000_PLL_BUSY), 1, 8000)) + break; + } +} + +/* The PMGR's sleep entry, on the boot core alone while the parked cores still wait */ +static void t6000_quiesce(struct t6000_sleep *t) +{ + unsigned int i; + + t->quiesce = true; + t6000_quiesce_mcc(t); + + for (i = 0; i < ARRAY_SIZE(t6000_zero_pa); i++) { + if (!t->zero[i]) + continue; + t->zero_saved[i] = readl(t->zero[i]); + writel(0, t->zero[i]); + } + t->socq_done |= T6000_SOCQ_ZEROS; + /* + * No power-word reads here: reading the PCIe block's three words this late left the SoC + * stuck before the sleep. + */ + if (t->apcie_8014 && t->apcie_82bc) { + t->apcie_saved[0] = readl(t->apcie_8014); + t->apcie_saved[1] = readl(t->apcie_82bc); + writel(1, t->apcie_8014); + writel(1, t->apcie_82bc); + writel(2, t->apcie_82bc); + writel(4, t->apcie_82bc); + t->socq_done |= T6000_SOCQ_APCIE; + } + t6000_quiesce_acc(t); + t6000_quiesce_dcs_afr(t); + + for (i = 0; i < T6000_CLUSTERS; i++) { + if (!(T6000_CLUSTERS_VALID & BIT(i)) || !t6000_cluster_gate(i)) + continue; + t6000_cluster_write(t, i); + } + + t6000_quiesce_clocks(t); +} + +/* + * The wake engines wait for each DCS power word to drop to 0 on the way back, and one that + * goes to sleep in another state holds them until the watchdog. The first sleep keeps the + * words at the S2R timer as the baseline; later ones put a changed one back. + */ +static u32 t6000_go_mask(u32 a, u32 b) +{ + u32 m = PS_TARGET | PS_ACTUAL | BIT(10) | GENMASK(19, 16) | PS_AUTO_ENABLE; + + if (a & b & PS_AUTO_ENABLE) + m &= ~PS_ACTUAL; + return m; +} + +/* + * A DCS word just written has settled once its actual state is its target: the status the + * fixed 100 us stood in for, bounded as every other power-word wait in the sleep. One the + * PMGR manages (AUTO_ENABLE) is the PMGR's to move, and its actual state is outside the + * baseline's compare (t6000_go_mask()): nothing to wait for. + */ +static int t6000_go_settle(void __iomem *reg) +{ + u32 v = readl(reg); + + if (v & PS_AUTO_ENABLE) + return 0; + return readl_poll_timeout_atomic(reg, v, FIELD_GET(PS_ACTUAL, v) == FIELD_GET(PS_TARGET, v), + 1, PS_OFF_TIMEOUT_US); +} + +static void t6000_go_check(struct t6000_sleep *t) +{ + unsigned int i; + u32 v, base, d; + + t->go_timeouts = 0; + for (i = 0; i < t->psall_n; i++) { + void __iomem *reg = t->psall[i].reg; + + if (strncmp(t->psall[i].name, "dcs_", 4)) + continue; + v = readl(reg); + if (!t->go_base_taken) { + /* A floor there on the first sleep must not end up in the baseline. */ + if (v & GENMASK(19, 16)) { + writel(v & ~(GENMASK(19, 16) | BIT(31) | BIT(9) | BIT(8)), reg); + if (t6000_go_settle(reg)) + t->go_timeouts++; + v = readl(reg); + } + t->go_base[i] = v; + continue; + } + base = t->go_base[i]; + d = (v ^ base) & t6000_go_mask(v, base); + if (!d || (base & GENMASK(19, 16))) + continue; + writel((v & ~(PS_TARGET | PS_AUTO_ENABLE | GENMASK(19, 16) | BIT(31) | BIT(9) | + BIT(8))) | + (base & (PS_TARGET | PS_AUTO_ENABLE | GENMASK(19, 16))), reg); + if (t6000_go_settle(reg)) + t->go_timeouts++; + } + if (t->psall_n) + t->go_base_taken = true; +} + +/* The late steps, every word, unconditionally, with their waits; then 200 ms */ +static void t6000_late_write(struct t6000_sleep *t) +{ + unsigned int i, us; + + t->late_applied = t->late_n != 0; + for (i = 0; i < t->late_n; i++) { + const struct t6000_late_word *w = &t->late[i]; + + if (w->op == T6000_LATE_WAIT) { + udelay(w->val); + continue; + } + if (w->op == T6000_LATE_SIO) { + /* SIO's word needs a moment after its target is raised */ + for (us = 0; us < 2000 && + FIELD_GET(PS_ACTUAL, readl(t->sio_cpu_ps)) != 0xf; us++) + udelay(1); + if (FIELD_GET(PS_ACTUAL, readl(t->sio_cpu_ps)) != 0xf) + continue; + } + writel(w->val, w->reg); + } + dsb(sy); + mdelay(T6000_LATE_MS); +} + +/* The PMU RTC alarm's vector on, unless its driver has it on already */ +static void t6000_spmi_arm(struct t6000_sleep *t) +{ + unsigned int i; + + for (i = 0; i < T6000_SPMI_WORDS; i++) + t->spmi_saved[i] = readl(t->spmi_irq + 4 * i); + t->spmi_written = true; + if (t->spmi_saved[0] & T6000_SPMI_VEC_RTC) + return; + writel(T6000_SPMI_VEC_RTC, t->spmi_irq + T6000_SPMI_CLEAR); + writel(t->spmi_saved[0] | T6000_SPMI_VEC_RTC, t->spmi_irq); + dsb(sy); +} + +/* + * The enables back as the irqchip had them. A latched alarm stays for the irqchip if it has + * the vector on, and is cleared if only the sleep turned it on. + */ +static void t6000_spmi_restore(struct t6000_sleep *t) +{ + unsigned int i; + + if (!t->spmi_written) + return; + t->spmi_written = false; + for (i = 0; i < T6000_SPMI_WORDS; i++) + writel(t->spmi_saved[i], t->spmi_irq + 4 * i); + if (!(t->spmi_saved[0] & T6000_SPMI_VEC_RTC)) + writel(T6000_SPMI_VEC_RTC, t->spmi_irq + T6000_SPMI_CLEAR); + dsb(sy); +} + +/* + * The commit, from the quiesced SoC (t6000_sleep_commit_quiesce()) to the mailbox, in macOS's + * order: the memory controllers' words checked, the parked cores stopped and the boot + * cluster's target, WD1, the late image, the RTC alarm's vector and WD1 again. The shared + * commit then arms the mailbox and starts the S2R timer. Nothing printed, nothing can fail. + */ +static void t6000_sleep_commit_regs(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + t6000_go_check(t); + + /* PE_cpu_machine_quiesce: the PMGR has to know each core is down for the sleep */ + s->cpus_stop_ret = spin_table_stop_parked(); + t6000_cluster_eacc(t); + dsb(sy); + + /* A fabric hang in the late steps below still ends in a reset */ + apple_sleep_set_wd2(s, T6000_WDT_GO_SECS); + dsb(sy); + t6000_late_write(t); + t6000_spmi_arm(t); + /* From here to the wake: it keeps counting through the sleep */ + apple_sleep_set_wd2(s, T6000_WDT_GO_SECS); + dsb(sy); +} + +/* The PMGR's wake: AFR's word first, then the memory clock 7 and back to what the PMP had */ +static void t6000_dcs_afr_restore(struct t6000_sleep *t) +{ + u32 val; + + if (t->socq_done & T6000_SOCQ_AFR) { + writel(t->afr_saved, t->afr_ps); + readl_poll_timeout_atomic(t->afr_ps, val, + FIELD_GET(PS_ACTUAL, val) == FIELD_GET(PS_TARGET, val), + 1, 8000); + } + if (t->socq_done & T6000_SOCQ_DCS) { + t6000_dcs_set(t, 7); + t6000_dcs_set(t, FIELD_GET(T6000_DCS_PS_TARGET, t->dcs_saved)); + } +} + +/* PLL 0 back on and locked before any mux goes back to it */ +static void t6000_clocks_restore(struct t6000_sleep *t) +{ + u32 val = 0; + int i; + + if (t->socq_done & T6000_SOCQ_PLL) { + writel(readl(t->pll) | T6000_PLL_ON, t->pll); + readl_poll_timeout_atomic(t->pll, val, !(val & T6000_PLL_BUSY), 1, 8000); + writel(t->pll_saved, t->pll); + readl_poll_timeout_atomic(t->pll, val, !(val & T6000_PLL_BUSY), 1, 8000); + /* Better slow on the reference clock than on a PLL that never locked */ + if (val & T6000_PLL_BUSY) + return; + } + + for (i = t->mux_n - 1; i >= 0; i--) { + void __iomem *reg = t->clkgen + t6000_clkgen_mux_off[i]; + + writel(t->mux_saved[i], reg); + readl_poll_timeout_atomic(reg, val, !(val & T6000_CLKGEN_BUSY), 1, 8000); + } +} + +/* Once the CPU complexes have power again */ +static void t6000_acc_restore(struct t6000_sleep *t) +{ + u32 regs = 0; + unsigned int i; + int r; + u64 val; + + if (t->socq_done & T6000_SOCQ_COUNTERS) + regs |= BIT(T6000_ACCR_PERF) | BIT(T6000_ACCR_ENERGY); + if (t->socq_done & T6000_SOCQ_THROTTLERS) + regs |= BIT(T6000_ACCR_AMX) | BIT(T6000_ACCR_LLC) | BIT(T6000_ACCR_PPT); + if (t->socq_done & T6000_SOCQ_APSC) + regs |= BIT(T6000_ACCR_DVFS); + + for (i = 0; i < T6000_ACCS; i++) { + for (r = T6000_ACCR_N - 1; r >= 0; r--) { + void __iomem *reg = t->acc[i] + t6000_acc_regs[r]; + + if (!(regs & BIT(r))) + continue; + /* Only the APSC bit: cpufreq owns the rest of the DVFS word */ + if (r == T6000_ACCR_DVFS) { + val = readq(reg) & ~T6000_ACC_DVFS_APSC_OFF; + writeq(val | (t->acc_saved[i][r] & T6000_ACC_DVFS_APSC_OFF), reg); + readq_poll_timeout_atomic(reg, val, !(val & T6000_ACC_DVFS_BUSY), + 1, 8000); + } else { + writeq(t->acc_saved[i][r], reg); + } + } + } +} + +/* The PCIe block's three words: a write to it with any of them off never completes */ +static bool t6000_apcie_on(void) +{ + static const u64 apcie_ps[] = { 0x28e080138ULL, 0x28e080150ULL, 0x28e080320ULL }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(apcie_ps); i++) + if (FIELD_GET(PS_ACTUAL, readl(t6000_ps(apcie_ps[i]))) != 0xf) + return false; + return true; +} + +/* The PMGR's wake, before any parked core comes back */ +static void t6000_quiesce_restore(struct t6000_sleep *t) +{ + unsigned int done = t->socq_done, a, i; + u32 val, now; + + if (t->mcc_done & T6000_MCC_DCS_LP) + for (a = 0; a < T6000_AMCCS; a++) + for (i = 0; i < T6000_DCS_PER_AMCC; i++) + if (t->dcs_blk[a][i]) + writel(T6000_DCS_CTL_IBOOT, + t->dcs_blk[a][i] + T6000_DCS_CTL); + t6000_clocks_restore(t); + + for (i = 0; i < T6000_CLUSTERS; i++) { + void __iomem *reg = t->cluster_ps + 4 * i; + + if (!(t->cluster_written & BIT(i))) + continue; + now = readl(reg); + if (i == T6000_CLUSTER_AFR && t->afr_cl_valid && + !(t->cluster_saved[i] & T6000_CLUSTER_TARGET)) { + /* The GPU's lowering took it to 0 first: back to what it was before that */ + if ((now ^ t->afr_cl_pre) & T6000_CLUSTER_TARGET) + writel(t->afr_cl_pre, reg); + } else { + writel(t->cluster_saved[i], reg); + } + readl_poll_timeout_atomic(reg, val, !(val & T6000_CLUSTER_BUSY), 1, 10000); + } + + t6000_dcs_afr_restore(t); + t6000_acc_restore(t); + + for (i = 2; (done & T6000_SOCQ_RELOCK) && i-- > 0;) { + void __iomem *reg = t->acc[i] + T6000_ACC_DVFS; + u64 v; + + writeq(t->relock_saved[i], reg); + readq_poll_timeout_atomic(reg, v, !(v & T6000_ACC_DVFS_BUSY), 1, 8000); + } + /* After a real sleep the block comes back powered off and reset: nothing to restore */ + if ((done & T6000_SOCQ_APCIE) && t6000_apcie_on()) { + writel(t->apcie_saved[1], t->apcie_82bc); + writel(t->apcie_saved[0], t->apcie_8014); + } + + /* The voltage monitors first, then the counters, then the error handlers */ + for (i = ARRAY_SIZE(t6000_zero_pa); (done & T6000_SOCQ_ZEROS) && i-- > 0;) + if (t->zero[i]) + writel(t->zero_saved[i], t->zero[i]); + t->socq_done = 0; + t->mcc_done = 0; + t->mux_n = 0; + t->cluster_written = 0; + t->afr_cl_valid = false; +} + +/* + * The commit's first step: the PMGR's sleep entry, from the stopped coprocessors, then the + * interrupt check once more. One raised since .enter's checks would end the last WFI at once, + * with the parked cores not yet stopped: give up there, the quiesce put back first. Nothing + * printed. + */ +static int t6000_sleep_commit_quiesce(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + t->committed = true; + t6000_quiesce(t); + if (read_sysreg(isr_el1) & (PSR_I_BIT | PSR_F_BIT)) { + t6000_quiesce_restore(t); + /* Given up: as before the commit, until .enter restarts the machine */ + t->committed = false; + return -EBUSY; + } + return 0; +} + +/* Back on the boot core, the AIC restored, before any other core starts */ +static void t6000_sleep_wake(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + /* + * Only when the commit armed it: counted again from 0 with the wake's time, so a slow + * device resume has it and a hung one still ends in a reset. The control word stays as + * it is; .end puts user space's back. + */ + if (readl(s->wdt + WDT_WD1_CTL) & WDT_WD1_RESET_EN) { + writel(0, s->wdt + WDT_WD1_COUNT); + writel(T6000_WDT_WAKE_SECS * WDT_TICKS_PER_S, s->wdt + WDT_WD1_BITE); + } + + /* A real sleep woke the display blocks: nothing to undo at .wake */ + t->disp_undo_due = false; + t6000_quiesce_restore(t); + t6000_spmi_restore(t); + t6000_nco_put_back(t); + t6000_nco_restore(t); +} + +/* + * After a sleep, before any device resumes: the late steps' words back as Linux had them. + * Walked backwards, so parents come back before children, each word once. + */ +static void t6000_late_put_back(struct apple_sleep *s, struct t6000_sleep *t) +{ + unsigned int i, j; + u32 v, now; + + if (!t->late_applied) + return; + t->late_applied = false; + if (t->go_timeouts) + dev_warn(s->dev, "T6000: %u DCS words missed their bound\n", t->go_timeouts); + for (i = t->late_n; i-- > 0;) { + const struct t6000_late_word *w = &t->late[i]; + bool again = false; + + if (w->op == T6000_LATE_WAIT || w->op == T6000_LATE_SIO) + continue; + for (j = i + 1; j < t->late_n; j++) + if (t->late[j].reg == w->reg) + again = true; + if (again) + continue; + v = w->saved; + if (w->op != T6000_LATE_PS) { + writel(v, w->reg); + continue; + } + /* One Linux had on comes back through the walk below, parents first. */ + if (FIELD_GET(PS_ACTUAL, v)) + continue; + /* The was-gated bits are write-one-to-clear, the actual state read only */ + writel(v & ~(PS_FLAGS | PS_ACTUAL), w->reg); + if (readl_poll_timeout_atomic(w->reg, now, FIELD_GET(PS_ACTUAL, now) == + FIELD_GET(PS_TARGET, v), 10, 100000)) + dev_warn(s->dev, "T6000: late-step word %u not back at %lu: %#x\n", i, + FIELD_GET(PS_TARGET, v), now); + } +} + +static int t6000_psall_find(struct t6000_sleep *t, struct device_node *np) +{ + unsigned int i; + + for (i = 0; i < t->psall_n; i++) + if (t->psall[i].np == np) + return i; + return -1; +} + +/* One saved power word back on, its parents first */ +static void t6000_psall_on(struct apple_sleep *s, struct t6000_sleep *t, unsigned int i, + unsigned int depth, unsigned long *seen) +{ + struct of_phandle_iterator it; + void __iomem *reg = t->psall[i].reg; + u32 saved = t->psall[i].saved, cur; + unsigned int us; + int err, j; + + if (test_and_set_bit(i, seen) || depth > 8) + return; + /* + * The NUB PMGR keeps its state through the sleep. Its domains are auto-PM: a saved + * actual state only says a transfer was running, and raising one would cost it + * AUTO_ENABLE for the rest of the boot. + */ + if (t->psall[i].pa >= T6000_NUB_PS) + return; + /* Linux had it off: genpd's to bring up */ + if (!FIELD_GET(PS_ACTUAL, saved)) + return; + of_for_each_phandle(&it, err, t->psall[i].np, "power-domains", "#power-domain-cells", 0) { + j = t6000_psall_find(t, it.node); + if (j >= 0) + t6000_psall_on(s, t, j, depth + 1, seen); + } + cur = readl(reg); + /* The minimum state (the DCP CPUs') is lost with the power: back first */ + if ((cur ^ saved) & GENMASK(19, 16)) { + writel((cur & ~(BIT(12) | BIT(11) | BIT(10) | BIT(9) | BIT(8) | GENMASK(19, 16))) | + (saved & GENMASK(19, 16)), reg); + cur = readl(reg); + } + if (FIELD_GET(PS_TARGET, cur) == FIELD_GET(PS_TARGET, saved) && + FIELD_GET(PS_ACTUAL, cur) >= FIELD_GET(PS_ACTUAL, saved)) + return; + cur &= ~(BIT(12) | BIT(11) | BIT(10) | BIT(9) | BIT(8) | BIT(28) | PS_TARGET | + GENMASK(27, 24)); + cur |= saved & GENMASK(27, 24); + if (t->psall_pass && !FIELD_GET(PS_ACTUAL, readl(reg))) { + writel(cur & ~PS_ACTUAL, reg); + udelay(100); + } + writel(cur | (saved & PS_TARGET), reg); + for (us = 0; us < 2000 && FIELD_GET(PS_ACTUAL, readl(reg)) < FIELD_GET(PS_ACTUAL, saved); + us++) + udelay(10); + cur = readl(reg) & ~(BIT(12) | BIT(11) | BIT(10) | BIT(9) | BIT(8) | PS_ACTUAL); + /* + * After the first pass, a word still off comes up without AUTO_ENABLE: with it the PMGR + * keeps an idle fabric domain off even when a DART behind it is accessed. + */ + if ((saved & BIT(28)) && !t->psall_pass) + writel(cur | BIT(28), reg); + cur = readl(reg); + if ((cur & BIT(31)) && !(saved & BIT(31)) && FIELD_GET(PS_ACTUAL, cur)) { + writel(cur & ~(BIT(31) | BIT(11) | BIT(9) | BIT(8) | PS_ACTUAL), reg); + udelay(1); + cur = readl(reg); + } + if (FIELD_GET(PS_ACTUAL, cur) < FIELD_GET(PS_ACTUAL, saved)) { + t->psall_stuck++; + if (t->psall_pass == T6000_PSALL_PASSES - 1) + dev_warn(s->dev, "T6000: %s stays off (%#x, was %#x)\n", t->psall[i].name, + cur, saved); + } +} + +/* + * Every PMGR domain that was on before the sleep back on, parents first, before any device + * resumes (never SEP, AFC or AFI): up to 30 passes 10 ms apart while some are still off, as a + * fabric parent can take longer than one poll. + */ +static void t6000_psall_restore(struct apple_sleep *s, struct t6000_sleep *t) +{ + DECLARE_BITMAP(seen, T6000_PSALL_MAX); + unsigned int i, pass; + + if (!t->psall_armed) + return; + t->psall_armed = false; + for (pass = 0; pass < T6000_PSALL_PASSES; pass++) { + if (pass) + mdelay(10); + t->psall_pass = pass; + t->psall_stuck = 0; + bitmap_zero(seen, T6000_PSALL_MAX); + for (i = 0; i < t->psall_n; i++) + t6000_psall_on(s, t, i, 0, seen); + if (!t->psall_stuck) + break; + } +} + +/* + * Display blocks whose coprocessor its driver parked, and that no .display_off took down, down + * and up: the lowering without the GPU's port, the PMP requests back, then the blocks' CPU and + * front-end words raised to what they were at .begin, block by block. + */ +static void t6000_sleep_display_cycle(struct apple_sleep *s, unsigned long blocks) +{ + struct t6000_display *d = &t6000_display; + struct t6000_sleep *t = &t6000_sleep; + DECLARE_BITMAP(seen, T6000_PSALL_MAX); + unsigned int b, i; + + t6000_sleep_disp_down(s, blocks); + d->undo_due = true; + t6000_sleep_display_undo(s); + t->psall_pass = 0; + bitmap_zero(seen, T6000_PSALL_MAX); + for_each_set_bit(b, &blocks, T6000_DISP_BLOCKS) { + const struct t6000_disp_block *db = &t6000_disp_blocks[b]; + + for (i = 0; i < t->psall_n; i++) + if (t->psall[i].pa == db->cpu0) + t6000_psall_on(s, t, i, 0, seen); + for (i = 0; i < t->psall_n; i++) + if (t->psall[i].pa == db->fe) + t6000_psall_on(s, t, i, 0, seen); + } +} + +/* + * A sleep given up after a display coprocessor was parked and before .display_off took its + * block down: the parked firmware starts again only once its block lost power. Done here, at + * .wake, ahead of resume_noirq, which writes the blocks' DARTs back: a block cycled after that + * loses them again under the restarting firmware. + */ +static void t6000_sleep_restart_displays(struct apple_sleep *s) +{ + struct t6000_display *d = &t6000_display; + unsigned long blocks = d->parked & ~d->cycled; + + if (t6000_sleep.committed || !blocks || !d->pmgr_ps || !d->east_ps) + return; + t6000_sleep_display_cycle(s, blocks); +} + +/* + * At .wake (and again at .end, when each step has already run): the late steps put back, the + * display blocks back after a sleep that was given up, then every domain that was on, the GPU's + * port as the commit found it, then the blocks of the parked display coprocessors that the entry + * did not take down. + */ +static void t6000_sleep_finish(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + t6000_late_put_back(s, t); + if (t->disp_undo_due) { + t->disp_undo_due = false; + t6000_sleep_display_undo(s); + } + t6000_psall_restore(s, t); + t6000_sleep_gpu_port_back(s); + t6000_sleep_restart_displays(s); + t6000_display_own(s, false); +} + +/* The display coprocessor of a block parked, or started again, by its driver */ +static void t6000_sleep_display_parked(struct apple_sleep *s, struct device *dev, bool parked) +{ + struct device_node *pd = of_parse_phandle(dev->of_node, "resets", 0); + int b = pd ? t6000_disp_block_of(pd) : -1; + + of_node_put(pd); + if (b < 0) + return; + if (parked) + set_bit(b, &t6000_display.parked); + else + clear_bit(b, &t6000_display.parked); +} + +/* + * A display coprocessor's driver parks its firmware for a sleep that commits, and a parked + * firmware starts again only once its display block lost its power. Asked by that driver's + * resume after a sleep that was given up: if .display_off or .wake took the block down, it is + * up again. If not (the sleep was given up in suspend_late or suspend_noirq, where .wake does + * not run), the block goes down and up now. + */ +static bool t6000_sleep_refusal_cycled(struct apple_sleep *s, struct device_node *pd) +{ + struct t6000_display *d = &t6000_display; + struct t6000_sleep *t = &t6000_sleep; + const struct t6000_disp_block *db; + int b; + + if (!pd || t->committed || !d->pmgr_ps || !d->east_ps) + return false; + b = t6000_disp_block_of(pd); + if (b < 0) + return false; + if (test_bit(b, &d->cycled)) + return true; + + db = &t6000_disp_blocks[b]; + t6000_sleep_display_cycle(s, BIT(b)); + + return !(d->disp_stuck & BIT(2 * b)) && + FIELD_GET(PS_ACTUAL, readl(t6000_disp_ps(d, db->cpu0))); +} + +/* At .end: the PTD sleep word back */ +static void t6000_sleep_end(struct apple_sleep *s) +{ + struct t6000_sleep *t = &t6000_sleep; + + if (!t->ptd_noticed) + return; + writel(t->ptd_sleep_saved, t->ptd + T6000_PTD_SLEEP); + t->ptd_noticed = false; +} + +static const struct apple_sleep_wake_name t6000_wake_names[] = { + { 12, "AOP.GPIO.IRQ4" }, { 14, "AOP.GPIO.IRQ6" }, + { 26, "AOP.OutboxNotEmpty" }, { 27, "AOP.CPUWakeupAP" }, + { 40, "NUB.WakeupAP" }, { 43, "NUB.GPIO.IRQ2" }, + { 49, "NUB.APWatchdog" }, { 50, "NUB.APWakeupTime" }, + { 51, "NUB.SPMISw0IRQ" }, { 52, "NUB.SPMISw1IRQ" }, { 54, "NUB.SPMISw3IRQ" }, + { 85, "SMC.CPUWakeupAP" }, { 90, "SMC.OutboxNotEmpty" }, + { 126, "ATC0.CIOWakeup" }, { 127, "ATC1.CIOWakeup" }, + { 128, "ATC2.CIOWakeup" }, { 129, "ATC3.CIOWakeup" }, + { 130, "ATC0.USBWakeup" }, { 131, "ATC1.USBWakeup" }, + { 132, "ATC2.USBWakeup" }, { 133, "ATC3.USBWakeup" }, +}; + +/* The enclave's driver must be bound and have staged its sleep request for the commit */ +static const struct apple_sleep_gate_coproc t6000_gate_coprocs[] = { + { "/soc/sep@396400000" }, +}; + +static const struct apple_sleep_ops t6000_sleep_ops = { + .deep_wfi_arm = t6000_deep_wfi_arm, + .boot_sleep = t6000_sleep_boot_sleep, + .resume = cpu_resume, + /* Wake-armed lines stay open for the last WFI, as the AIC's syscore suspend left them */ + .aic_mask_all = aic_sleep_mask_all_but_wake, + .aic_ack = aic_sleep_ack, + .aic_restore = aic_sleep_restore, + .map_regs = t6000_sleep_map_regs, + .begin = t6000_sleep_begin, + .prepare = t6000_sleep_prepare, + .smc_warned = t6000_sleep_smc_warned, + .check = t6000_sleep_check, + .final_check = t6000_sleep_final_check, + .display_off = t6000_display_off, + .first_stopped = t6000_sleep_gpu_port_off, + .prepare_regs = t6000_sleep_prepare_regs, + .undo_regs = t6000_sleep_undo_regs, + .commit_quiesce = t6000_sleep_commit_quiesce, + .commit_regs = t6000_sleep_commit_regs, + .wake = t6000_sleep_wake, + .finish = t6000_sleep_finish, + .end = t6000_sleep_end, + .refusal_cycled = t6000_sleep_refusal_cycled, + .display_parked = t6000_sleep_display_parked, + .cpu_prepare = t6000_sleep_cpu_prepare, + .cpu_restore = t6000_sleep_cpu_restore, +}; + +static const struct apple_sleep_soc t6000_sleep_soc = { + .ops = &t6000_sleep_ops, + /* + * Deep sleep offered only with apple_sleep.deep=1, a commit only with + * untested_commit=1, until J314s rows on the default command line exist + */ + .untested = true, + .no_pmu_notes = true, + .early_context = true, + .commit_stops_cpus = true, + /* Its driver parks the DCP only for a sleep that commits: a dry run leaves it running. */ + .display_no_restart = true, + .wdt_wd1 = true, + .smc_gen1_keys = true, + .smc_keys_refuse = true, + /* slpa and the SMC's AP 0x201 before the PMP's stop, as macOS has them */ + .smc_before_peers = true, + /* + * The display coprocessors and the SIO park in suspend_late; the enclave and the GPU + * firmware stop only at the commit, past the last refusal. + */ + .wakeup_hold = true, + .boot_mpidr = 0x0, + .cpu_count = 8, + /* + * MPIDR affinity 1 is the cluster: E 0.0.n, P0 0.1.n, P1 0.2.n. Start bits 4 * cluster + + * core; a binned cluster keeps its cores' numbers, so 4 bounds the core, not the count. + */ + .cpu_cluster_affinity = 1, + .cpu_clusters = 3, + .cpu_cores_per_cluster = 4, + .cpu_start_stride = 4, + .cpu_valid = t6000_sleep_cpu_valid, + .cluster_cpu = { T6000_CLUSTER_EACC * 4, T6000_CLUSTER_PACC0 * 4, + T6000_CLUSTER_PACC1 * 4 }, + .ncluster_cpu = 3, + .ndisp = 1, + .gate_coprocs = t6000_gate_coprocs, + .ngate_coprocs = ARRAY_SIZE(t6000_gate_coprocs), + /* The PMGR's AP wake block: 7 mask words, then 7 status words */ + .wake_mask = 0x08, + .wake_status = 0x24, + .wake_words = 7, + .wake_last_word = 0x00001fff, + .wake_names = t6000_wake_names, + .nwake_names = ARRAY_SIZE(t6000_wake_names), +}; diff --git a/drivers/soc/apple/sleep-t6050.h b/drivers/soc/apple/sleep-t6050.h index 623da36c05a13..570d86b12f65e 100644 --- a/drivers/soc/apple/sleep-t6050.h +++ b/drivers/soc/apple/sleep-t6050.h @@ -3573,6 +3573,8 @@ bool apple_sleep_refusal_cycled(struct device_node *pd) unsigned int i; int word; + if (s && s->soc->ops->refusal_cycled) + return s->soc->ops->refusal_cycled(s, pd); if (!r || !r->refusal_cycled || !pd) return false; word = sleep_region_domain_offset(s, pd); diff --git a/drivers/soc/apple/sleep-test.c b/drivers/soc/apple/sleep-test.c index b86da75784b20..dddf0de50f13b 100644 --- a/drivers/soc/apple/sleep-test.c +++ b/drivers/soc/apple/sleep-test.c @@ -18,6 +18,7 @@ static const char *const apple_sleep_test_profiles[] = { "apple,t8122-sleep", "apple,t6030-sleep", "apple,t6020-sleep", + "apple,t6000-sleep", }; /* diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index e6eaa106f88a1..089ea6744ee9b 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -72,6 +72,7 @@ #include #include #include +#include #include #include #include @@ -577,6 +578,12 @@ struct apple_sleep_extra_off { struct apple_sleep_ops { /* What makes a core's last WFI end in a reset, after its timers are masked */ void (*deep_wfi_arm)(void); + /* + * Optional: the boot core's last WFI, in place of deep_wfi_arm's, for a SoC whose commit + * gives up when an interrupt already pending ends it. Returns only then, with the data + * cache back on; .enter then restarts the machine. + */ + int (*boot_sleep)(void); /* Once the other cores stop: the I/O domains the commit lowers itself, ANS's last */ void (*lower_io)(struct apple_sleep *s); /* @@ -591,6 +598,14 @@ struct apple_sleep_ops { * mailbox. No protocol/lifecycle duplication here. */ void (*commit_regs)(struct apple_sleep *s); + /* + * Optional, right before commit_regs, for a SoC with commit_stops_cpus and early_context: + * the SoC's quiesce, after which it can still give up, as macOS checks for a raised + * interrupt once more there. Nonzero: it has put its quiesce back; the parked cores are + * released and the entry returns the error, its peers already stopped, and .enter + * restarts the machine. + */ + int (*commit_quiesce)(struct apple_sleep *s); /* Where the wake enters the kernel with the MMU off: cpu_resume, or a stub ending there */ void (*resume)(void); /* Optional, once the mailbox is armed: the last step before the commit word */ @@ -624,6 +639,22 @@ struct apple_sleep_ops { void (*wfi_again)(struct apple_sleep *s); /* Optional: power domain kept across sleep by the SoC provider */ bool (*domain_kept)(struct apple_sleep *s, int off); + /* Optional: at .prepare, every device suspended and the SMC told the sleep is coming */ + void (*prepare)(struct apple_sleep *s); + /* Optional: right after the SMC's sleep warning (slpw), from the SMC's own .prepare */ + void (*smc_warned)(struct apple_sleep *s); + /* Optional: at .end, last, once the watchdog is back as user space had it */ + void (*end)(struct apple_sleep *s); + /* + * Optional, for apple_sleep_refusal_cycled(): whether @pd's word was switched off and on + * since a refused entry began, which the SoC may do on the asking driver's behalf. + */ + bool (*refusal_cycled)(struct apple_sleep *s, struct device_node *pd); + /* + * Optional: a display coprocessor's driver parked its firmware for the sleep (@parked), + * or started it again, as it tells apple_sleep_display_quiesced(). + */ + void (*display_parked)(struct apple_sleep *s, struct device *dev, bool parked); /* Pure bounded planning only; no register read/write or entry authorization. */ int (*plan_complex_request)(u32 observed, u32 *request); @@ -634,6 +665,12 @@ struct apple_sleep_ops { int (*display_stop)(struct apple_sleep *s); /* After the always-on GPU stop, right before SEP's sleep request. */ void (*before_enclave)(struct apple_sleep *s); + /* + * Optional, for a SoC with early_context and no display_stop: right after the first + * pass of coprocessor stops, past the last refusal. A port that a coprocessor's own + * stop leaves up goes down here. It can't refuse. + */ + void (*first_stopped)(struct apple_sleep *s); /* After cpu_suspend saved context, before any stopped core loses power. */ void (*commit_begin)(struct apple_sleep *s); int (*check)(struct apple_sleep *s); @@ -887,6 +924,19 @@ struct apple_sleep_soc { unsigned int smc_settle_ms; /* SEP's word: DEV_DISABLE, and not an actual state of 0, says that it is down */ bool sep_dev_disable; + /* ... before the point of no return, where a failed write still refuses the sleep */ + bool smc_keys_refuse; + /* + * Gen 1: the SMC hears slpa after SEP's stop but before the other coprocessors', the PMP + * among them, as macOS orders them, instead of after every one of them. + */ + bool smc_before_peers; + /* + * A coprocessor stopped at .prepare comes back only through the power cut, so from there + * on a wakeup event is held for after the sleep (pm_wakeup_hold()) and the wake is a full + * one, instead of a refusal that would leave it stopped. + */ + bool wakeup_hold; /* Live coprocessors with DRAM buffers require WAKE_SLP_DDR across sleep. */ bool coproc_slp_ddr; /* @@ -1123,6 +1173,10 @@ struct apple_sleep { } smc; /* This sleep's wake came from the SMC's sources alone. */ bool smc_woke_alone; + /* Wakeup events are held (wakeup_hold) from .prepare until the entry returns. */ + bool wakeups_held; + /* The commit gave up after the SMC had slpa: only a restart leads back. */ + bool no_return; /* A power word the DRAM-kept wake polls stayed latched: this sleep went deep. */ bool deep_once; /* Each latched word the commit cleared, as it found it */ @@ -1306,6 +1360,36 @@ void apple_sleep_usb_asleep_notifier_unregister(struct notifier_block *nb) } EXPORT_SYMBOL_GPL(apple_sleep_usb_asleep_notifier_unregister); +/* See apple_sleep_prepare() */ +static BLOCKING_NOTIFIER_HEAD(sleep_prepare_chain); + +int apple_sleep_prepare_notifier_register(struct notifier_block *nb) +{ + return blocking_notifier_chain_register(&sleep_prepare_chain, nb); +} +EXPORT_SYMBOL_GPL(apple_sleep_prepare_notifier_register); + +void apple_sleep_prepare_notifier_unregister(struct notifier_block *nb) +{ + blocking_notifier_chain_unregister(&sleep_prepare_chain, nb); +} +EXPORT_SYMBOL_GPL(apple_sleep_prepare_notifier_unregister); + +/* See apple_sleep_late_scope_finish() */ +static BLOCKING_NOTIFIER_HEAD(sleep_finish_chain); + +int apple_sleep_finish_notifier_register(struct notifier_block *nb) +{ + return blocking_notifier_chain_register(&sleep_finish_chain, nb); +} +EXPORT_SYMBOL_GPL(apple_sleep_finish_notifier_register); + +void apple_sleep_finish_notifier_unregister(struct notifier_block *nb) +{ + blocking_notifier_chain_unregister(&sleep_finish_chain, nb); +} +EXPORT_SYMBOL_GPL(apple_sleep_finish_notifier_unregister); + static unsigned long sleep_usb_wake_ports; void apple_sleep_usb_set_wake_ports(unsigned long ports) @@ -1993,7 +2077,7 @@ static int apple_sleep_enclave_stop(struct apple_sleep *s) return 0; ret = apple_sleep_enclave.stop(apple_sleep_enclave.data); if (ret) - dev_err(s->dev, "refused before SEP SLEEP was sent: %d\n", ret); + dev_err(s->dev, "refused at SEP sleep step: %d\n", ret); return ret; } @@ -2222,6 +2306,9 @@ int apple_sleep_smc_register_saved(struct device *dev, s->smc.saved_ops = ops; s->smc.late_notice = ops->late_notice; s->smc.data = data; + /* A gen-1 SMC registers right after slpw, unless a debug link holds slpw back. */ + if (s->soc->ops->smc_warned && !apple_sleep_debug_link_up()) + s->soc->ops->smc_warned(s); return 0; } EXPORT_SYMBOL_GPL(apple_sleep_smc_register_saved); @@ -2364,7 +2451,11 @@ void apple_sleep_display_quiesced(struct device *dev, bool quiesced) struct apple_sleep *s = apple_sleep; unsigned int i; - if (!s || !s->soc->regions) + if (!s) + return; + if (s->soc->ops->display_parked) + s->soc->ops->display_parked(s, dev, quiesced); + if (!s->soc->regions) return; for (i = 0; i < s->soc->ndisp; i++) if (s->display[i].np == dev->of_node) @@ -3436,7 +3527,10 @@ static bool sleep_ps_domain(struct apple_sleep *s, struct device_node *pd, u32 * return ours; } -/* Map a PMGR power-state word directly when apple_sleep is not bound on this board. */ +/* + * Map a PMGR power-state word directly: when apple_sleep is not bound on this board, or + * the domain is in another PMGR block than the one mapped here as "ps". + */ static void __iomem *sleep_map_pmgr_domain(struct device_node *pd, void __iomem **map) { struct device_node *parent; @@ -3501,11 +3595,10 @@ int apple_sleep_engine_reset(struct device *dev) void __iomem *map = NULL; void __iomem *reg; - if (s) { - if (!sleep_ps_domain(s, it.node, &val)) - continue; + if (s && sleep_ps_domain(s, it.node, &val)) { reg = sleep_power_reg(s, val); } else { + /* No sleep engine here, or a domain outside its block (T6000 SIO: east) */ reg = sleep_map_pmgr_domain(it.node, &map); if (!reg) continue; @@ -6235,6 +6328,23 @@ static void __noreturn sleep_boot_wfi(struct apple_sleep *s) } } +/* + * On a SoC with boot_sleep: the same, but an interrupt already pending that ends the WFI gives + * the sleep up, its peers told and stopped and the other cores down. The entry then returns as + * an uncommitted one. + */ +static int sleep_boot_sleep(struct apple_sleep *s) +{ + int ret; + + /* As sleep_deep_wfi_arm(): a timer left running ends the WFI. */ + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntp_ctl_el0); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntv_ctl_el0); + ret = s->soc->ops->boot_sleep(); + s->entry_committed = false; + return ret; +} + /* XNU polls these off just before its complex words. The sleep goes on whatever they read. */ static void apple_sleep_wait_still_on(struct apple_sleep *s) { @@ -6289,6 +6399,20 @@ static int apple_sleep_commit(unsigned long unused) if (early) udelay(SLEEP_EARLY_WFI_SETTLE_US); + if (s->soc->ops->commit_quiesce) { + int ret = s->soc->ops->commit_quiesce(s); + + /* + * Given up with its parked cores still held (the SoC stops them in commit_regs): + * they go back as at a refusal, and the entry returns as an uncommitted one. Its + * peers were told and stopped: .enter restarts the machine. + */ + if (ret) { + s->entry_committed = false; + spin_table_unhold_parked(); + return ret; + } + } if (s->soc->ops->commit_regs) { /* A SoC whose irreversible steps share nothing with the ones below. */ s->soc->ops->commit_regs(s); @@ -6332,6 +6456,8 @@ static int apple_sleep_commit(unsigned long unused) mdelay(s->soc->boot_wfi_delay_ms); if (s->soc->ops->last_mile == t8142_last_mile && READ_ONCE(sleep_post_commit_ms)) t8142_post_commit_probe(s, READ_ONCE(sleep_post_commit_ms)); + if (s->soc->ops->boot_sleep) + return sleep_boot_sleep(s); sleep_boot_wfi(s); } @@ -6763,6 +6889,14 @@ static int apple_sleep_smc_pmvc(struct apple_sleep *s) return s->smc.saved_ops->pmvc(s->smc.data); } +/* Gen 1, where the SoC asks: the SMC's keys before slpa, while a failure still refuses. */ +static int apple_sleep_smc_keys(struct apple_sleep *s) +{ + if (!s->smc.dev || !s->smc.held || !s->smc.saved_ops || !s->smc.saved_ops->keys) + return -ENODEV; + return s->smc.saved_ops->keys(s->smc.data); +} + static int apple_sleep_smc_commit_notice(struct apple_sleep *s) { if (!s->smc.dev || !s->smc.held || !s->smc.saved_ops || @@ -6905,11 +7039,15 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) if (ret) panic("Apple SEP refused after the always-on GPU stop: %d", ret); } else if (!ret) { - if (s->soc->ops->before_enclave) { + /* A failed key write is logged by the SMC's driver and refuses before SEP. */ + if (s->soc->smc_keys_refuse && apple_sleep_smc_defer_notice()) + ret = apple_sleep_smc_keys(s); + if (!ret && s->soc->ops->before_enclave) { s->regs_staged = true; s->soc->ops->before_enclave(s); } - ret = apple_sleep_enclave_stop(s); + if (!ret) + ret = apple_sleep_enclave_stop(s); } if (ret) { dev_dbg(s->dev, "refused before any commit coprocessor stop: %d\n", ret); @@ -6920,8 +7058,11 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) /* SEP success belongs to irreversible commitment, never cancellation. */ s->entry_committed = true; /* No returning error path below this point. */ - if (!s->soc->ops->display_stop) + if (!s->soc->ops->display_stop) { apple_sleep_coprocs_stop(s, true); + if (s->soc->ops->first_stopped) + s->soc->ops->first_stopped(s); + } /* Its driver's stop ran just above; past the last refusal, a failure goes on. */ if (late_display) { ret = s->soc->ops->display_off(s); @@ -6935,12 +7076,18 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) } s->soc->ops->prepare_regs(s); s->regs_staged = true; + if (s->soc->smc_before_peers && !s->soc->ops->commit_notice && + apple_sleep_smc_defer_notice()) { + ret = apple_sleep_smc_late_notice(s); + if (ret) + panic("Apple SMC sleep notice failed before peer stop: %d", ret); + } apple_sleep_coprocs_stop(s, false); if (s->soc->ops->commit_notice) { ret = s->soc->ops->commit_notice(s); if (ret) panic("Apple committed SMC notice failed after peer stop: %d", ret); - } else if (apple_sleep_smc_defer_notice()) { + } else if (apple_sleep_smc_defer_notice() && !s->soc->smc_before_peers) { /* Gen 1: the SMC hears last, after SEP and the other coprocessors stopped. */ ret = apple_sleep_smc_late_notice(s); if (ret) @@ -6955,6 +7102,8 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) return 0; } +static void apple_sleep_check_no_return(struct apple_sleep *s); + static int apple_sleep_enter_saved(unsigned long unused) { struct apple_sleep *s = apple_sleep; @@ -6974,17 +7123,49 @@ static int apple_sleep_enter_saved(unsigned long unused) if (ret) return ret; /* cpu_suspend has already saved boot context. Commit never returns. */ - return apple_sleep_commit(0); + ret = apple_sleep_commit(0); + /* Unless it gave up, after slpa: see apple_sleep_check_no_return() */ + s->no_return = true; + return ret; +} + +/* + * Wakeup events count again. One that came meanwhile stays pending, and the PM core then + * makes the wake a full one (pm_consume_dark_wake()), whatever the SMC calls it. + */ +static void apple_sleep_wakeups_release(struct apple_sleep *s) +{ + if (!s || !s->wakeups_held) + return; + + s->wakeups_held = false; + pm_wakeup_hold(false); + if (pm_wakeup_pending()) + dev_info(s->dev, "full wake: a wakeup event on the way down\n"); } /* A SoC with early_context: the whole entry runs inside cpu_suspend(), on the saved context. */ static int apple_sleep_enter_early(struct apple_sleep *s) { + u64 resumes = READ_ONCE(s->mbox->resumes); int ret; s->entry_committed = false; s->cntkctl = read_sysreg(cntkctl_el1); ret = cpu_suspend(0, apple_sleep_enter_saved); + /* Back through aura's resume, or it counted one meanwhile: the SoC was down after all */ + if (!ret) { + s->no_return = false; + } else if (s->no_return) { + dcache_inval_poc((unsigned long)s->mbox, (unsigned long)(s->mbox + 1)); + if (READ_ONCE(s->mbox->resumes) != resumes) + s->no_return = false; + } + /* + * Otherwise restart here, still on this core alone with IRQs off: nothing may run on the + * blocks the entry already stopped, as IRQ handlers and the other cores' start would. + */ + apple_sleep_check_no_return(s); if (ret && s->entry_committed) panic("Apple committed sleep returned without physical wake: %d", ret); if (!ret) { @@ -6995,6 +7176,8 @@ static int apple_sleep_enter_early(struct apple_sleep *s) if (s->entry_prepared) apple_sleep_enter_cleanup(s); s->soc->ops->cpu_restore(s->mbox->boot_mpidr); + /* Back up, or never down */ + apple_sleep_wakeups_release(s); return ret; } @@ -7397,6 +7580,7 @@ static int apple_sleep_begin(suspend_state_t state) } apple_sleep->dry_run = apple_sleep->untested && !READ_ONCE(sleep_untested_commit); + apple_sleep->no_return = false; if (apple_sleep->soc->ops->begin) { ret = apple_sleep->soc->ops->begin(apple_sleep); @@ -7432,6 +7616,7 @@ static int apple_sleep_begin(suspend_state_t state) static void apple_sleep_end(void) { + apple_sleep_wakeups_release(apple_sleep); WRITE_ONCE(sleep_deep_requested, false); sleep_ans_late_release(true); sleep_v27_scope_end(); @@ -7457,6 +7642,8 @@ static void apple_sleep_end(void) } else if (pm_suspend_via_firmware() && !apple_sleep->soc->no_wd2) { apple_sleep_wdt_end(apple_sleep->wdt); } + if (pm_suspend_via_firmware() && apple_sleep->soc->ops->end) + apple_sleep->soc->ops->end(apple_sleep); } /* @@ -7739,11 +7926,33 @@ static int apple_sleep_late_scope_begin(void) static void apple_sleep_late_scope_finish(void) { + struct apple_sleep *s = apple_sleep; + + apple_sleep_wakeups_release(s); /* .finish also runs when noirq suspend fails before platform .wake. */ apple_sleep_smc_scope_end(); sleep_v27_scope_end(); + /* + * What the .prepare chain stopped starts again here, after every early resume (the PMP's + * restart and its requests among them) and before the SMC hears of the wake, on every path + * that ran .prepare: a refused sleep and a dry run too. + */ + if (pm_suspend_via_firmware()) + blocking_notifier_call_chain(&sleep_finish_chain, 0, NULL); /* After device early resume, which consumed the ANS receipt. */ sleep_ans_late_release(false); + /* Registered until the SMC's .complete: its wake commands, the coprocessors back */ + scoped_guard(mutex, &apple_sleep_smc_lock) { + if (s && s->smc.saved_ops && s->smc.saved_ops->finish) { + s->smc.saved_ops->finish(s->smc.data); + /* + * The SMC named the wake only now, after the PM core's own pass right after + * the noirq resume: consume its IRQ here, or the wake can never stay dark. + * Anything else pending still makes it a full one. + */ + pm_consume_dark_wake(); + } + } } static int apple_sleep_prepare(void) @@ -7782,6 +7991,23 @@ static int apple_sleep_prepare(void) } } apple_sleep_gate_prepare(s); + if (s->soc->ops->prepare && pm_suspend_via_firmware()) + s->soc->ops->prepare(s); + /* + * A coprocessor stopped from here on, by the chain below or in its late suspend, may not + * start again without the power cut: a wakeup event from here on is kept for after the + * sleep. Not in a dry run, which stops none of them. + */ + if (s->soc->wakeup_hold && pm_suspend_via_firmware() && !apple_sleep_dry(s)) { + s->wakeups_held = true; + pm_wakeup_hold(true); + } + /* + * Last, after every device's suspend and before any late one: a coprocessor that stops + * here, or registers its stop for the commit. + */ + if (pm_suspend_via_firmware()) + blocking_notifier_call_chain(&sleep_prepare_chain, 0, NULL); return 0; } @@ -7817,12 +8043,35 @@ static bool apple_sleep_smc_woke_alone(struct apple_sleep *s) return any; } +/* + * A sleep given up in the commit leaves the SMC, which has slpa, and the stopped PMP waiting + * for a power cut that never comes. The NVMe, the PCIe ports and the other cores do not come + * back from that, so restart while the disk is still in order rather than run on without one. + */ +static void apple_sleep_check_no_return(struct apple_sleep *s) +{ + if (!s->no_return) + return; + + dev_emerg(s->dev, "deep sleep was given up after the point of no return, restarting\n"); + /* In case the restart needs the SMC */ + if (s->wdt) { + writel(0, s->wdt + WDT_WD1_CTL); + writel(0, s->wdt + WDT_WD1_COUNT); + writel(5 * WDT_TICKS_PER_S, s->wdt + WDT_WD1_BITE); + writel(WDT_WD1_RESET_EN, s->wdt + WDT_WD1_CTL); + } + emergency_restart(); +} + static void apple_sleep_report(void) { struct apple_sleep *s = apple_sleep; const struct apple_sleep_wake_name *names = s->soc->wake_names; int i; + /* Given up in the commit: .enter restarts before this, which is only a second net */ + apple_sleep_check_no_return(s); /* Back in Linux, before any device resumes: a reset after this is in the resume. */ sleep_note(s, 0x7e); if (s->soc->ops->finish) @@ -8433,6 +8682,9 @@ static void apple_sleep_map_pins(struct apple_sleep *s) if (!of_device_is_available(np) || of_property_read_u32(np, "apple,npins", &npins) || !npins || npins > 512) goto out; + /* T6000's pin controller driver keeps its pins across the sleep itself. */ + if (of_device_is_compatible(np, "apple,t6000-pinctrl")) + goto out; /* Without the pins to leave alone none is saved: reading some of them faults. */ if (s->soc->regions && !of_property_present(s->dev->of_node, "apple,pinctrl-skip-pins")) goto out; @@ -10830,6 +11082,7 @@ static const struct apple_sleep_soc t8142_sleep_soc = { #include "sleep-t8112.h" #include "sleep-t6030.h" #include "sleep-t6020.h" +#include "sleep-t6000.h" /* * Qualified profiles expose system sleep. Inventory-only profiles match for a @@ -10848,6 +11101,7 @@ static const struct of_device_id apple_sleep_of_match[] = { { .compatible = "apple,t8122-sleep", .data = &t8122_sleep_soc }, { .compatible = "apple,t6030-sleep", .data = &t6030_sleep_soc }, { .compatible = "apple,t6020-sleep", .data = &t6020_sleep_soc }, + { .compatible = "apple,t6000-sleep", .data = &t6000_sleep_soc }, { } }; diff --git a/include/linux/irqchip/irq-apple-aic.h b/include/linux/irqchip/irq-apple-aic.h index 3c3781322a52b..1577bb11012fc 100644 --- a/include/linux/irqchip/irq-apple-aic.h +++ b/include/linux/irqchip/irq-apple-aic.h @@ -6,10 +6,12 @@ #ifdef CONFIG_APPLE_AIC void aic_sleep_mask_all(void); +void aic_sleep_mask_all_but_wake(void); void aic_sleep_restore(void); u32 aic_sleep_ack(void); #else static inline void aic_sleep_mask_all(void) { } +static inline void aic_sleep_mask_all_but_wake(void) { } static inline void aic_sleep_restore(void) { } static inline u32 aic_sleep_ack(void) { return 0; } #endif diff --git a/include/linux/mfd/macsmc.h b/include/linux/mfd/macsmc.h index a6d07b2a7b6bc..76bb42b0a4b88 100644 --- a/include/linux/mfd/macsmc.h +++ b/include/linux/mfd/macsmc.h @@ -155,6 +155,15 @@ struct apple_smc { /* apple,sleep-pmvc: when set, the pmVC value written at the sleep commit. */ bool sleep_pmvc_set; u32 sleep_pmvc; + /* Gen 1: pmVC and WKTP went out ahead of slpa, at the last step that can refuse. */ + bool gen1_keys_sent; + /* + * T6000 with its firmware-driven sleep described: a failed slpw refuses the sleep, slpa + * and the AP idle notice follow each other without gaps, and AP ON is tried three times. + */ + bool sleep_t6000; + /* T6000: AP ON went out at the noirq resume, the wake record waits for .finish */ + bool wake_at_finish; /* To be told at the noirq suspend, after the debug link's cut. */ bool sleep_warn_late; /* In a noirq phase: replies are polled for. */ diff --git a/include/linux/soc/apple/mailbox.h b/include/linux/soc/apple/mailbox.h index b0b1083faef03..4c836d18ccceb 100644 --- a/include/linux/soc/apple/mailbox.h +++ b/include/linux/soc/apple/mailbox.h @@ -127,6 +127,7 @@ int apple_mbox_recv_nowait(struct apple_mbox *mbox, struct apple_mbox_msg *msg); /* Bit 0 of the receive control word, for firmware that powers itself down. */ void apple_mbox_set_recv_enabled(struct apple_mbox *mbox, bool enabled); u32 apple_mbox_read_status(struct apple_mbox *mbox); +void apple_mbox_set_send_enabled(struct apple_mbox *mbox, bool enabled); /* * Leave received messages in the hardware FIFO, without an interrupt, until * apple_mbox_release_rx(). For consumers that must not wake the system. diff --git a/include/linux/soc/apple/pmp-report.h b/include/linux/soc/apple/pmp-report.h index d76d580cf3944..7fc16f6b048a8 100644 --- a/include/linux/soc/apple/pmp-report.h +++ b/include/linux/soc/apple/pmp-report.h @@ -29,7 +29,9 @@ int apple_pmp_report_check_t6030_ack(const struct device_node *entry); int apple_pmp_report_fast_die_effort(const struct device_node *np, unsigned int lane, u8 *effort); void apple_pmp_report_sleep(struct device *pmp, bool at_commit); +void apple_pmp_report_sleep_tail(struct device *pmp); void apple_pmp_report_wake(struct device *pmp, bool lost_power); +void apple_pmp_report_wake_unstarted(struct device *pmp); int apple_pmp_report_entry_request(const struct device_node *entry, bool enable); int apple_pmp_report_entry_commit_owned(const struct device_node *entry, bool owned); int apple_pmp_report_entry_withdraw_polled(const struct device_node *entry); @@ -39,6 +41,15 @@ int apple_pmp_report_entry_withdraw_polled(const struct device_node *entry); */ int apple_pmp_report_set_request(const struct device_node *report_np, unsigned int id, bool enable, bool no_ack); +/* + * For a sleep profile's entry, interrupts off: set or clear request bit @id whatever owns it + * (the T600x AGX vote's bit 9 too), under the report's lock, then poll the acknowledge word + * (10 us steps, at most @timeout_us). @was (may be NULL) gets whether the + * bit was set before. Return 0, -ENODEV (no report bound to @report_np), -EINVAL (@id > 63), + * -ETIMEDOUT (written, not acknowledged). + */ +int apple_pmp_report_sleep_request(const struct device_node *report_np, unsigned int id, + bool enable, unsigned int timeout_us, bool *was); /* * T6001: the GPU driver reports each operation in flight. With the pmp_report.agx_vote parameter set, the AGX request (PS-REQ bit 9) is * set while any operation runs and cleared agx_vote_idle_ms after the last one ends. Parameter off: no effect. Both may be called from @@ -70,10 +81,18 @@ static inline void apple_pmp_report_sleep(struct device *pmp, bool at_commit) { } +static inline void apple_pmp_report_sleep_tail(struct device *pmp) +{ +} + static inline void apple_pmp_report_wake(struct device *pmp, bool lost_power) { } +static inline void apple_pmp_report_wake_unstarted(struct device *pmp) +{ +} + static inline int apple_pmp_report_ane_available(const struct device_node *np) { return -EOPNOTSUPP; @@ -147,6 +166,13 @@ static inline int apple_pmp_report_set_request(const struct device_node *report_ return -ENODEV; } +static inline int apple_pmp_report_sleep_request(const struct device_node *report_np, + unsigned int id, bool enable, + unsigned int timeout_us, bool *was) +{ + return -ENODEV; +} + static inline void apple_pmp_floor_gpu_activity(bool busy) { } diff --git a/include/linux/soc/apple/pmp.h b/include/linux/soc/apple/pmp.h index f860b67ad78d7..1bbc8c3e86aaf 100644 --- a/include/linux/soc/apple/pmp.h +++ b/include/linux/soc/apple/pmp.h @@ -40,6 +40,13 @@ int apple_pmp_send_power_command(const void *data, u8 command, extern const struct dev_pm_ops apple_pmp_pm_ops; int apple_pmp_sleep(const void *data); int apple_pmp_wake(const void *data); +/* + * After a power cycle, with the CPU stopped: its SRAM back, then RTKit afresh (its CPU is + * started between the two), then the boot and the PMP endpoint. + */ +int apple_pmp_sram_restore(const void *data); +int apple_pmp_reinit(const void *data); +int apple_pmp_boot(const void *data); /* * What the sleep's last step needs to idle and stop the PMP with interrupts off: its RTKit and diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 47e646644b429..4a52e682d8b2c 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -240,6 +240,17 @@ int apple_rtkit_reinit(struct apple_rtkit *rtk); */ int apple_rtkit_reinit_retaining_buffers(struct apple_rtkit *rtk); +/* + * A co-processor idled with its context and buffers kept, whose power was then + * cut: apple_rtkit_reinit() without freeing anything. Call it with the CPU + * stopped; then start the CPU, apple_rtkit_wake_keep_ap(), + * apple_rtkit_restart_started_eps() and apple_rtkit_ap_power_timeout(on). + */ +int apple_rtkit_reinit_keep(struct apple_rtkit *rtk); + +/* Stop receiving from an idled co-processor before its power goes, buffers kept. */ +void apple_rtkit_detach_keep(struct apple_rtkit *rtk); + /* * Set how long each handshake step (power state and endpoint map replies) * waits for the co-processor, for one that is known to answer slowly. Call @@ -291,6 +302,14 @@ int apple_rtkit_boot_or_wake(struct apple_rtkit *rtk, unsigned int self_ack_ms); /* Wake helpers which require AP readiness before their IOP power acknowledgment. */ int apple_rtkit_wake_early_ap(struct apple_rtkit *rtk); +/* + * After apple_rtkit_reinit_keep() and the CPU started: INIT, endpoint map and + * IOP acknowledgment, with no AP message. Then apple_rtkit_restart_started_eps() + * starts the app endpoints the client had started, and the AP state follows. + */ +int apple_rtkit_wake_keep_ap(struct apple_rtkit *rtk); +int apple_rtkit_restart_started_eps(struct apple_rtkit *rtk); + /* * Wake a co-processor stopped after apple_rtkit_idle() with its firmware, * endpoints and buffers kept: restore the mailbox, resume RX, call @start to @@ -383,6 +402,12 @@ int apple_rtkit_ap_power(struct apple_rtkit *rtk, bool on); /* The same, for a noirq phase: device interrupts are off, so it polls. */ int apple_rtkit_ap_power_noirq(struct apple_rtkit *rtk, bool on); +/* The AP power state alone, waiting @ms for its acknowledgment (not the handshake timeout). */ +int apple_rtkit_ap_power_timeout(struct apple_rtkit *rtk, bool on, unsigned int ms); + +/* The IOP power state IDLE alone, after the AP's, for a co-processor stopped with its context. */ +int apple_rtkit_idle_iop(struct apple_rtkit *rtk); + /* The M5 Pro's AP-only saved-context lane. begin/end run in process context, * with the consumer device locked throughout. Exclude every other RTKit user. * begin synchronizes RX and refuses while accepted jobs are still active; @@ -478,6 +503,8 @@ void apple_rtkit_polled_begin(struct apple_rtkit *rtk); void apple_rtkit_polled_end(struct apple_rtkit *rtk); int apple_rtkit_polled_exchange(struct apple_rtkit *rtk, u8 ep, u64 msg, u64 mask, u64 want); int apple_rtkit_polled_ap_idle(struct apple_rtkit *rtk, unsigned int *us); +/* Then the IOP's IDLE, after the AP's: @us adds the time it took */ +int apple_rtkit_polled_iop_idle(struct apple_rtkit *rtk, unsigned int *us); /* * Send a message to the given endpoint. diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index 39ab320931c91..5e0d94208a772 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -55,6 +55,21 @@ static inline bool apple_sleep_smc_policy_described(void) return false; } +/* + * A machine whose device tree describes the T6000 firmware-driven sleep: its sleep node is + * enabled. T6001 and T6002 share T6000's block compatibles, and their trees have no such node. + */ +static inline bool apple_t6000_sleep_described(void) +{ + struct device_node *np; + bool ret; + + np = of_find_compatible_node(NULL, NULL, "apple,t6000-sleep"); + ret = np && of_device_is_available(np); + of_node_put(np); + return ret; +} + /* The SMC's sleep messages: the pmVC value and the spacings between them, used as floors */ struct apple_sleep_smc_policy { u32 pmvc; @@ -78,6 +93,11 @@ struct apple_sleep_smc_saved_ops { * the SMC's first wake commands (its wake record, waka). */ void (*woken)(void *data); + /* + * Optional, at the platform .finish, after every device's early resume (the coprocessors + * back): the SMC's wake commands a SoC sends there rather than at the noirq resume. + */ + void (*finish)(void *data); /* Optional, after the irreversible stops: pmVC alone, before late_notice (which then skips it). */ int (*pmvc)(void *data); /* @@ -86,6 +106,12 @@ struct apple_sleep_smc_saved_ops { * be taken there too. */ void (*until_before_slpa)(void *data, u32 us); + /* + * Optional, gen 1, for a SoC that asks: the keys macOS writes between slpw and slpa + * (pmVC, WKTP), as the entry's last step that can still refuse. late_notice then + * skips them. + */ + int (*keys)(void *data); }; #if IS_ENABLED(CONFIG_APPLE_SOC_SLEEP) @@ -213,6 +239,23 @@ struct notifier_block; int apple_sleep_usb_asleep_notifier_register(struct notifier_block *nb); void apple_sleep_usb_asleep_notifier_unregister(struct notifier_block *nb); +/* + * Called at .prepare of a sleep that cuts the SoC's power, once every device's suspend has run and + * before any late suspend: for a coprocessor whose firmware must be stopped before the noirq phase, + * which powers its domain off with its mailbox, and as late as that allows. + */ +int apple_sleep_prepare_notifier_register(struct notifier_block *nb); +void apple_sleep_prepare_notifier_unregister(struct notifier_block *nb); + +/* + * Called at .finish of every sleep whose .prepare called the chain above, given up or not, after + * every device's early resume and before the SMC is told of the wake: for such a coprocessor to + * start again. Only on a SoC whose entry runs inside cpu_suspend(); elsewhere it is not called, + * and the coprocessor's own resume has to start it. + */ +int apple_sleep_finish_notifier_register(struct notifier_block *nb); +void apple_sleep_finish_notifier_unregister(struct notifier_block *nb); + /* * The USB host is up, as macOS's USB_SLP_DDR vote has it: from the host's start to its stop, * awake and asleep. It sets bit 0 of the wake block's word 0 for every sleep in between. @@ -510,6 +553,24 @@ static inline void apple_sleep_usb_asleep_notifier_unregister(struct notifier_bl { } +static inline int apple_sleep_prepare_notifier_register(struct notifier_block *nb) +{ + return 0; +} + +static inline void apple_sleep_prepare_notifier_unregister(struct notifier_block *nb) +{ +} + +static inline int apple_sleep_finish_notifier_register(struct notifier_block *nb) +{ + return 0; +} + +static inline void apple_sleep_finish_notifier_unregister(struct notifier_block *nb) +{ +} + static inline void apple_sleep_usb_slp_ddr(bool up) { } diff --git a/include/linux/suspend.h b/include/linux/suspend.h index 2fcb352878229..9ac34a49f2288 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -514,6 +514,7 @@ static inline bool pm_suspended_storage(void) extern bool pm_wakeup_pending(void); extern void pm_system_wakeup(void); extern void pm_system_cancel_wakeup(void); +extern void pm_wakeup_hold(bool hold); extern void pm_wakeup_clear(unsigned int irq_number); void pm_wakeup_consume_irq(unsigned int irq_number); extern void pm_system_irq_wakeup(unsigned int irq_number); @@ -554,6 +555,7 @@ static inline void ksys_sync_helper(void) {} static inline bool pm_suspended_storage(void) { return false; } static inline bool pm_wakeup_pending(void) { return false; } static inline void pm_system_wakeup(void) {} +static inline void pm_wakeup_hold(bool hold) {} static inline void pm_wakeup_clear(bool reset) {} static inline void pm_wakeup_consume_irq(unsigned int irq_number) {} static inline void pm_system_irq_wakeup(unsigned int irq_number) {}