diff --git a/Documentation/arch/arm64/ctxr-execmem.rst b/Documentation/arch/arm64/ctxr-execmem.rst index 4eb104ef0c2c4..14a5eeb844ba5 100644 --- a/Documentation/arch/arm64/ctxr-execmem.rst +++ b/Documentation/arch/arm64/ctxr-execmem.rst @@ -150,8 +150,11 @@ kexec and crash kernels with a warning when a window is active. Hibernate - Resume runs from a ``trans_pgd`` page outside the window. This is unchanged - and untested under a window. + A boot CPU that a system sleep restarted at its reset vector is confined + like the secondaries, so the code that writes the image back and jumps to + the restored kernel runs from a nosave page of the kernel image, inside the + window, instead of an ordinary page. The image's kernel must have run at the + same physical address; a restore of an image from elsewhere is refused. Verifying confinement ===================== diff --git a/Documentation/devicetree/bindings/chosen/aura,hibernate.yaml b/Documentation/devicetree/bindings/chosen/aura,hibernate.yaml new file mode 100644 index 0000000000000..8c8e9390b1e60 --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/aura,hibernate.yaml @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/aura,hibernate.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Memory layout a boot object keeps the same on every boot + +maintainers: + - František Balázsy + +description: | + A hibernation image puts every saved page back into the frame it was taken + from, so the boot that resumes an image has to give the kernel the same RAM, + and keep the same ranges from it, as the boot that wrote the image. On Apple + silicon the boot firmware loads the boot object at an address that changes + from boot to boot, and what the boot object keeps alive after the hand-off + moves with it. A boot object that instead keeps everything from the start of + RAM up to a fixed end from the kernel, at the same addresses on every boot, + says so with aura,hibernate-layout. Without it the kernel neither hibernates + nor resumes. + + The boot firmware still places some firmware segments anew on every boot, + inside that range, and a kernel restored from an image holds the device tree + of the boot that wrote the image. The boot object therefore puts the device + tree of every boot at one address inside the range, given in + aura,hibernate-dt. The image does not contain that memory, so the restored + kernel reads there what the resuming boot placed. + + The properties are named after aura, the boot loader that defined them and + whose released versions publish them. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + aura,hibernate-layout: + $ref: /schemas/types.yaml#/definitions/uint64-array + description: + The range of RAM that is kept from the kernel and laid out the same on + every boot. + items: + - description: Physical address of the start of RAM. + - description: Physical address of the end of the range, exclusive. + + aura,hibernate-dt: + $ref: /schemas/types.yaml#/definitions/uint64 + description: + Physical address, inside the range of aura,hibernate-layout, of the + device tree the kernel is started with. The kernel reads at most 2 MiB + there. + +dependencies: + aura,hibernate-dt: [ 'aura,hibernate-layout' ] + +additionalProperties: true +... diff --git a/Documentation/devicetree/bindings/chosen/aurora,s2r-mailbox.yaml b/Documentation/devicetree/bindings/chosen/aurora,s2r-mailbox.yaml new file mode 100644 index 0000000000000..64412bf791251 --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/aurora,s2r-mailbox.yaml @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/aurora,s2r-mailbox.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Suspend-to-RAM mailbox of the boot object + +maintainers: + - Diljit Singh + +description: | + On Apple silicon the boot object stays resident across a suspend-to-RAM and + owns the handshake that wakes the system. It tells the kernel where its + mailbox is in /chosen/aurora,s2r-mailbox: the kernel hands the wake there and + the boot object reads it on resume. The same object parks the "spin-table" + CPUs, so a kernel given this mailbox gets the spin-table CPU enable method. + The mailbox moves with the boot object on every boot, so a kernel restored + from a hibernation image reads this boot's address here, not the one the + image was written with. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + aurora,s2r-mailbox: + $ref: /schemas/types.yaml#/definitions/uint64 + description: + Physical address of the boot object's suspend-to-RAM mailbox. The kernel + checks a magic there before it uses the mailbox. + +additionalProperties: true +... diff --git a/Documentation/devicetree/bindings/soc/apple/apple,sep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,sep.yaml index 2f092e2674fb0..0335b8d2af7e1 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,sep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,sep.yaml @@ -59,6 +59,15 @@ properties: description: The SEP firmware carveout, added by the bootloader. + apple,sep-boot-timeout-ms: + description: + How long, in milliseconds, the enclave may take to finish booting its + firmware before the operating system gives up and leaves it unused. It + bounds both the first boot and a re-boot after a hibernation resume. + Depends on the SoC and the signed firmware; when absent the driver uses + a built-in default. + default: 5000 + iboot-manifest: $ref: /schemas/types.yaml#/definitions/uint8-array description: diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t6041-aop.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t6041-aop.yaml index 6b57b39dacda5..126f0b69ad04d 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t6041-aop.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t6041-aop.yaml @@ -23,6 +23,7 @@ description: properties: compatible: enum: + - apple,t6040-aop - apple,t6041-aop - apple,t8132-aop diff --git a/Documentation/devicetree/bindings/vendor-prefixes.yaml b/Documentation/devicetree/bindings/vendor-prefixes.yaml index 7e8a847ea70ab..c3dd6459893ba 100644 --- a/Documentation/devicetree/bindings/vendor-prefixes.yaml +++ b/Documentation/devicetree/bindings/vendor-prefixes.yaml @@ -207,6 +207,8 @@ patternProperties: description: Atmel Corporation "^auo,.*": description: AU Optronics Corporation + "^aura,.*": + description: aura boot loader for Apple silicon "^aurora,.*": description: Aurora Silicon "^auvidea,.*": diff --git a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml index f65a37d504791..01d40cba81ff0 100644 --- a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml +++ b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml @@ -55,12 +55,17 @@ properties: items: - description: Watchdog timer registers - description: Simple-reconfig routing register + - description: + SMC AP deadline register. Where present, the SMC resets the AP + once its uptime passes the programmed deadline; this replaces the + WD2 route through the simple-reconfig register. reg-names: minItems: 1 items: - const: wdt - const: reconfig + - const: deadline clocks: maxItems: 1 diff --git a/MAINTAINERS b/MAINTAINERS index 2813a0e47141c..1bdc578322aab 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2104,7 +2104,9 @@ F: include/linux/mt7932.h F: include/linux/soc/apple/pmp-report.h F: Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-quiesced.yaml F: Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml +F: Documentation/devicetree/bindings/chosen/aura,hibernate.yaml F: Documentation/devicetree/bindings/chosen/aurora,ctxr-exec-window.yaml +F: Documentation/devicetree/bindings/chosen/aurora,s2r-mailbox.yaml F: Documentation/devicetree/bindings/display/apple,dcp.yaml F: Documentation/devicetree/bindings/display/apple,display-subsystem.yaml F: Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml @@ -2148,14 +2150,18 @@ F: drivers/pci/controller/pcie-apple-t8140-bootstrap* F: drivers/phy/apple/atc-j700-dp.h F: drivers/rtc/rtc-apple-pmu.c F: drivers/soc/apple/aop.rs +F: drivers/soc/apple/aura-hibernate.c F: drivers/soc/apple/mcc.c +F: drivers/soc/apple/rtkit-hib-handoff.c F: drivers/soc/apple/sleep*.c F: drivers/tty/serial/apple_dockchannel* +F: include/linux/soc/apple/aura-hibernate.h F: include/linux/soc/apple/pci-apple-piodma.h F: include/linux/soc/apple/sleep.h F: rust/kernel/iio/common/aop_sensors.rs F: rust/kernel/soc/apple/aop.rs F: sound/soc/apple/aop_t8140.rs +F: tools/asahi/hibernate-signature-tests.py F: tools/asahi/mt7932* F: tools/testing/apple/ F: tools/testing/kunit/configs/apple_firmware.config diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig index fc0dc2a678bf7..a185b60b67875 100644 --- a/arch/arm64/Kconfig +++ b/arch/arm64/Kconfig @@ -2706,6 +2706,10 @@ config ARCH_HIBERNATION_HEADER def_bool y depends on HIBERNATION +config ARCH_HIBERNATION_CLEAN_IMAGE + def_bool y + depends on HIBERNATION + config ARCH_SUSPEND_POSSIBLE def_bool y diff --git a/arch/arm64/boot/dts/apple/t6040.dtsi b/arch/arm64/boot/dts/apple/t6040.dtsi index 3d0e019b55f82..c7da15e1cb0f8 100644 --- a/arch/arm64/boot/dts/apple/t6040.dtsi +++ b/arch/arm64/boot/dts/apple/t6040.dtsi @@ -466,6 +466,7 @@ }; &aop { + compatible = "apple,t6040-aop"; /* The calibration properties come from the bootloader. */ aop_accel: accel { compatible = "apple,t6041-aop-accel", "apple,aop-accel"; diff --git a/arch/arm64/boot/dts/apple/t604x.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi index f1ac746a96461..f27ba6d372a55 100644 --- a/arch/arm64/boot/dts/apple/t604x.dtsi +++ b/arch/arm64/boot/dts/apple/t604x.dtsi @@ -1132,7 +1132,10 @@ */ wdt: watchdog@50836c000 { compatible = "apple,t6041-wdt", "apple,t8103-wdt"; - reg = <0x5 0x0836c000 0x0 0x4000>; + reg = <0x5 0x0836c000 0x0 0x4000>, + <0x5 0x0833002c 0x0 0x4>, + <0x5 0x08330008 0x0 0x4>; + reg-names = "wdt", "reconfig", "deadline"; clocks = <&clkref>; interrupt-parent = <&aic>; interrupts = ; diff --git a/arch/arm64/include/asm/cpu_ops.h b/arch/arm64/include/asm/cpu_ops.h index 0de73a0c7cefd..2cbf1c031463d 100644 --- a/arch/arm64/include/asm/cpu_ops.h +++ b/arch/arm64/include/asm/cpu_ops.h @@ -72,6 +72,14 @@ struct cpumask; #ifdef CONFIG_HOTPLUG_CPU int spin_table_set_power_ops(const struct spin_table_power_ops *ops); +#ifdef CONFIG_HIBERNATION +extern char spin_table_hibernate_pen[]; +extern const struct cpu_operations smp_rvbar_spin_table_ops; +int spin_table_hibernate_pen_begin(phys_addr_t image_ttbr1, int primary); +void spin_table_hibernate_pen_end(bool frozen); +void spin_table_hibernate_restored(void); +bool spin_table_hibernate_cpus_stuck(void); +#endif int spin_table_hold_parked(void); void spin_table_unhold_parked(void); int spin_table_stop_parked(void); @@ -117,6 +125,21 @@ static inline bool spin_table_cpus_stuck(void) } #endif +#if !defined(CONFIG_HOTPLUG_CPU) || !defined(CONFIG_HIBERNATION) +static inline int spin_table_hibernate_pen_begin(phys_addr_t image_ttbr1, int primary) +{ + return 0; +} + +static inline void spin_table_hibernate_pen_end(bool frozen) {} +static inline void spin_table_hibernate_restored(void) {} + +static inline bool spin_table_hibernate_cpus_stuck(void) +{ + return false; +} +#endif + int __init init_cpu_ops(int cpu); extern const struct cpu_operations *get_cpu_ops(int cpu); diff --git a/arch/arm64/include/asm/suspend.h b/arch/arm64/include/asm/suspend.h index e9ce68d50ba45..f453f11af781e 100644 --- a/arch/arm64/include/asm/suspend.h +++ b/arch/arm64/include/asm/suspend.h @@ -48,6 +48,38 @@ int swsusp_arch_resume(void); int arch_hibernation_header_save(void *addr, unsigned int max_size); int arch_hibernation_header_restore(void *addr); +/** + * struct arm64_hibernate_layout - What a platform adds to the boot layout check. + * @ex: Ranges that this boot keeps out of the image and that the layout check + * leaves out of the memory it compares, in ascending order. + * @nex: Number of valid entries in @ex. + * @have_base: Whether CPU release addresses are compared as offsets from @base. + * @base: Base address for the release addresses, if @have_base. + */ +struct arm64_hibernate_layout { + u64 ex[2][2]; + int nex; + bool have_base; + u64 base; +}; + +/** + * struct arm64_hibernate_platform - Platform hooks of arm64 hibernation. + * @pfn_nosave: Whether the platform keeps page frame @pfn out of the image. + * @layout: Mix the platform's boot facts into the layout cookie in @h with + * arm64_hibernate_layout_mix(), fill @lay, and return the new hash. The + * cookie is stored with an image and compared before it is restored: the + * boot that resumes an image must give the kernel the layout of the boot + * that wrote it. + */ +struct arm64_hibernate_platform { + bool (*pfn_nosave)(unsigned long pfn); + u64 (*layout)(u64 h, struct arm64_hibernate_layout *lay); +}; + +void arm64_hibernate_set_platform(const struct arm64_hibernate_platform *platform); +u64 arm64_hibernate_layout_mix(u64 h, const void *p, size_t len); + /* Used to resume on the CPU we hibernated on */ int hibernate_resume_nonboot_cpu_disable(void); diff --git a/arch/arm64/kernel/Makefile b/arch/arm64/kernel/Makefile index cac465111055b..263d682d48620 100644 --- a/arch/arm64/kernel/Makefile +++ b/arch/arm64/kernel/Makefile @@ -65,6 +65,9 @@ obj-$(CONFIG_ARM64_ACPI_PARKING_PROTOCOL) += acpi_parking_protocol.o obj-$(CONFIG_PARAVIRT) += paravirt.o obj-$(CONFIG_RANDOMIZE_BASE) += kaslr.o obj-$(CONFIG_HIBERNATION) += hibernate.o hibernate-asm.o +ifdef CONFIG_HOTPLUG_CPU +obj-$(CONFIG_HIBERNATION) += smp_spin_table_pen.o +endif obj-$(CONFIG_ELF_CORE) += elfcore.o obj-$(CONFIG_KEXEC_CORE) += machine_kexec.o relocate_kernel.o \ cpu-reset.o diff --git a/arch/arm64/kernel/hibernate-asm.S b/arch/arm64/kernel/hibernate-asm.S index 2baefe7a82d36..89fc1db49f618 100644 --- a/arch/arm64/kernel/hibernate-asm.S +++ b/arch/arm64/kernel/hibernate-asm.S @@ -67,19 +67,24 @@ SYM_CODE_START(swsusp_arch_suspend_exit) copy_page x0, x1, x2, x3, x4, x5, x6, x7, x8, x9 add x1, x10, #PAGE_SIZE - /* Clean the copied page to PoU - based on caches_clean_inval_pou() */ + /* + * Clean the copied page to PoC, not only PoU: non-coherent DMA + * masters (the coprocessors of some SoCs) read the restored pages + * from DRAM. Clean+invalidate to PoC also covers what + * caches_clean_inval_pou() did for the I-side. + */ raw_dcache_line_size x2, x3 sub x3, x2, #1 bic x4, x10, x3 2: /* clean D line / unified line */ -alternative_insn "dc cvau, x4", "dc civac, x4", ARM64_WORKAROUND_CLEAN_CACHE + dc civac, x4 add x4, x4, x2 cmp x4, x1 b.lo 2b ldr x19, [x19, #HIBERN_PBE_NEXT] cbnz x19, 1b - dsb ish /* wait for PoU cleaning to finish */ + dsb ish /* wait for PoC cleaning to finish */ /* switch to the restored kernels page tables */ break_before_make_ttbr_switch x25, x21, x6, x8 diff --git a/arch/arm64/kernel/hibernate.c b/arch/arm64/kernel/hibernate.c index 9398c8d0ecb03..a90318ee0ab3c 100644 --- a/arch/arm64/kernel/hibernate.c +++ b/arch/arm64/kernel/hibernate.c @@ -11,9 +11,13 @@ */ #define pr_fmt(x) "hibernate: " x #include +#include #include +#include +#include #include #include +#include #include #include @@ -81,6 +85,9 @@ static struct arch_hibernate_hdr { phys_addr_t __hyp_stub_vectors; u64 sleep_cpu_mpidr; + + /* What the boot loader decided for the boot that wrote the image. */ + u64 boot_layout; } resume_hdr; static inline void arch_hdr_invariants(struct arch_hibernate_hdr_invariants *i) @@ -89,13 +96,137 @@ static inline void arch_hdr_invariants(struct arch_hibernate_hdr_invariants *i) memcpy(i->uts_version, init_utsname()->version, sizeof(i->uts_version)); } +/** + * arm64_hibernate_layout_mix - Mix bytes into the boot layout cookie. + * @h: Hash so far. + * @p: Bytes to mix. + * @len: Number of bytes. + * + * FNV-1a, for the callback of a platform to mix its boot facts into the cookie + * in the same way as the rest of the layout. + */ +u64 arm64_hibernate_layout_mix(u64 h, const void *p, size_t len) +{ + const u8 *b = p; + + while (len--) { + h ^= *b++; + h *= 0x100000001b3ULL; /* FNV-1a */ + } + return h; +} + +/* + * Mix one memory span less the parts in @ex, ranges that this boot keeps out of + * the image. The boot loader's no-map allocations inside aura's fixed layout (the DCP + * oslogs, ANS firmware) move with the boot object and split memblock's regions + * differently on every boot; what lies there never holds an image page. + */ +static u64 hibernate_mix_span(u64 h, u64 b, u64 e, u32 flags, const u64 (*ex)[2], int nex) +{ + u64 size; + + if (b >= e) + return h; + if (nex && e > ex[0][0] && b < ex[0][1]) { + h = hibernate_mix_span(h, b, ex[0][0], flags, ex + 1, nex - 1); + return hibernate_mix_span(h, ex[0][1], e, flags, ex + 1, nex - 1); + } + if (nex) + return hibernate_mix_span(h, b, e, flags, ex + 1, nex - 1); + size = e - b; + h = arm64_hibernate_layout_mix(h, &b, sizeof(b)); + h = arm64_hibernate_layout_mix(h, &size, sizeof(size)); + return arm64_hibernate_layout_mix(h, &flags, sizeof(flags)); +} + +static const struct arm64_hibernate_platform *hibernate_platform __ro_after_init; + +/** + * arm64_hibernate_set_platform - Register the platform's hibernation hooks. + * @platform: Hooks of the platform; they must stay valid. + * + * Only one platform can register, at boot. + */ +void __init arm64_hibernate_set_platform(const struct arm64_hibernate_platform *platform) +{ + if (WARN_ON_ONCE(hibernate_platform)) + return; + hibernate_platform = platform; +} + +static bool hibernate_platform_pfn_nosave(unsigned long pfn) +{ + return hibernate_platform && hibernate_platform->pfn_nosave && + hibernate_platform->pfn_nosave(pfn); +} + +/* + * The image restores every page to the frame it came from, so the boot that + * resumes it must give the kernel what the boot that wrote it did: the same + * RAM, the same CPUs started the same way, and whatever fixed layout the + * platform's boot loader gives the kernel, which the platform's hook adds. A + * boot loader decides them on every boot; the kernel build check above cannot + * see them. + */ +static u64 hibernate_boot_layout(void) +{ + struct arm64_hibernate_layout lay = {}; + u64 h = 0xcbf29ce484222325ULL, rel, hwid; + struct memblock_region *r; + struct device_node *np; + u8 kept; + + if (hibernate_platform && hibernate_platform->layout) + h = hibernate_platform->layout(h, &lay); + + for_each_of_cpu_node(np) { + if (of_property_read_u64(np, "cpu-release-addr", &rel)) + continue; + hwid = of_get_cpu_hwid(np, 0); + kept = hibernate_platform_pfn_nosave(PHYS_PFN(rel)); + if (lay.have_base) + rel -= lay.base; + h = arm64_hibernate_layout_mix(h, &hwid, sizeof(hwid)); + h = arm64_hibernate_layout_mix(h, &rel, sizeof(rel)); + h = arm64_hibernate_layout_mix(h, &kept, sizeof(kept)); + } + + for_each_mem_region(r) + h = hibernate_mix_span(h, r->base, r->base + r->size, r->flags, lay.ex, lay.nex); + return h; +} + +/* + * Most image pages are loaded straight into their original frames through the + * cacheable linear map. Non-coherent DMA masters (on Apple SoCs: the GPU page + * table walker, DCP, every RTKit co-processor, the NVMe queues) read DRAM, and + * a later eviction of a dirty line would overwrite what a device wrote since. + * Clean and invalidate the page to the PoC before the jump. + * + * A frame that is not in the boot kernel's linear map (for example the linear + * alias of the kernel image, which faults when touched) had nothing loaded + * through the linear map: such frames are restored by the restore_pblist copy, + * which cleans each copied page itself. + */ +int arch_hibernate_clean_image_page(unsigned long pfn) +{ + unsigned long va; + + if (!kernel_page_present(pfn_to_page(pfn))) + return 0; + va = (unsigned long)page_address(pfn_to_page(pfn)); + dcache_clean_inval_poc(va, va + PAGE_SIZE); + return 1; +} + int pfn_is_nosave(unsigned long pfn) { unsigned long nosave_begin_pfn = sym_to_pfn(&__nosave_begin); unsigned long nosave_end_pfn = sym_to_pfn(&__nosave_end - 1); return ((pfn >= nosave_begin_pfn) && (pfn <= nosave_end_pfn)) || - crash_is_nosave(pfn); + crash_is_nosave(pfn) || hibernate_platform_pfn_nosave(pfn); } void notrace save_processor_state(void) @@ -129,8 +260,9 @@ int arch_hibernation_header_save(void *addr, unsigned int max_size) return -ENODEV; } hdr->sleep_cpu_mpidr = cpu_logical_map(sleep_cpu); - pr_info("Hibernating on CPU %d [mpidr:0x%llx]\n", sleep_cpu, - hdr->sleep_cpu_mpidr); + hdr->boot_layout = hibernate_boot_layout(); + pr_info("Hibernating on CPU %d [mpidr:0x%llx], boot layout %016llx\n", sleep_cpu, + hdr->sleep_cpu_mpidr, hdr->boot_layout); return 0; } @@ -138,6 +270,7 @@ EXPORT_SYMBOL(arch_hibernation_header_save); int arch_hibernation_header_restore(void *addr) { + u64 layout; int ret; struct arch_hibernate_hdr_invariants invariants; struct arch_hibernate_hdr *hdr = addr; @@ -147,6 +280,12 @@ int arch_hibernation_header_restore(void *addr) pr_crit("Hibernate image not generated by this kernel!\n"); return -EINVAL; } + layout = hibernate_boot_layout(); + if (hdr->boot_layout != layout) { + pr_crit("Hibernate image written under another boot layout (%016llx, this boot %016llx): not restored\n", + hdr->boot_layout, layout); + return -EINVAL; + } sleep_cpu = get_logical_index(hdr->sleep_cpu_mpidr); pr_info("Hibernated on CPU %d [mpidr:0x%llx]\n", sleep_cpu, @@ -186,6 +325,17 @@ static void *hibernate_page_alloc(void *arg) * Length is provided as we probably only want 4K of data, even on a 64K * page system. */ +/* + * A core confined to an execute window (Documentation/arch/arm64/ctxr-execmem.rst) + * fetches only from inside it. The boot CPU starts unconfined, but once a system + * sleep has restarted it at its reset vector it is confined like the secondaries, + * and a page from get_safe_page() can be anywhere in RAM. The kernel image is + * inside the window, so while one is active the exit code runs from this page of + * the image instead. It is nosave: the image doesn't hold it and the restore + * doesn't write it, as long as the image's kernel ran at this physical address. + */ +static u8 hibernate_exit_page[PAGE_SIZE] __nosavedata __aligned(PAGE_SIZE); + static int create_safe_exec_page(void *src_start, size_t length, phys_addr_t *phys_dst_addr) { @@ -194,13 +344,23 @@ static int create_safe_exec_page(void *src_start, size_t length, .trans_alloc_arg = (__force void *)GFP_ATOMIC, }; - void *page = (void *)get_safe_page(GFP_ATOMIC); phys_addr_t trans_ttbr0; unsigned long t0sz; + void *page; int rc; - if (!page) - return -ENOMEM; + if (execmem_confine_active()) { + if (length > sizeof(hibernate_exit_page) || + resume_hdr.ttbr1_el1 != __pa_symbol(swapper_pg_dir)) { + pr_err("the image's kernel ran at another physical address: no page for the exit code inside the execute window\n"); + return -EINVAL; + } + page = hibernate_exit_page; + } else { + page = (void *)get_safe_page(GFP_ATOMIC); + if (!page) + return -ENOMEM; + } memcpy(page, src_start, length); caches_clean_inval_pou((unsigned long)page, (unsigned long)page + length); @@ -337,7 +497,7 @@ int swsusp_arch_suspend(void) unsigned long flags; struct sleep_stack_data state; - if (cpus_are_stuck_in_kernel() || spin_table_cpus_stuck()) { + if (cpus_are_stuck_in_kernel() || spin_table_hibernate_cpus_stuck()) { pr_err("Can't hibernate: no mechanism to offline secondary CPUs.\n"); return -EBUSY; } @@ -386,6 +546,9 @@ int swsusp_arch_suspend(void) sleep_cpu = -EINVAL; __cpu_suspend_exit(); + /* The boot kernel's secondaries are in its pen, not where the image parked them. */ + spin_table_hibernate_restored(); + /* * Just in case the boot kernel did turn the SSBD * mitigation off behind our back, let's set the state @@ -489,10 +652,19 @@ int __nocfi swsusp_arch_resume(void) int hibernate_resume_nonboot_cpu_disable(void) { + int ret; + if (sleep_cpu < 0) { pr_err("Failing to resume from hibernate on an unknown CPU.\n"); return -ENODEV; } - return freeze_secondary_cpus(sleep_cpu); + /* Parking spin-table CPUs wait outside the image while it is restored. */ + ret = spin_table_hibernate_pen_begin(resume_hdr.ttbr1_el1, sleep_cpu); + if (ret) + return ret; + ret = freeze_secondary_cpus(sleep_cpu); + spin_table_hibernate_pen_end(!ret); + + return ret; } diff --git a/arch/arm64/kernel/smp.c b/arch/arm64/kernel/smp.c index f383d15a104cf..3017e2ed637cd 100644 --- a/arch/arm64/kernel/smp.c +++ b/arch/arm64/kernel/smp.c @@ -1363,14 +1363,29 @@ bool smp_crash_stop_failed(void) } #endif +/* + * The CPUs that have to leave the kernel are the others. A boot CPU whose node + * carries no enable-method (Apple boot objects describe only the secondaries' + * spin table) has no operations of its own: then every other possible CPU must + * have a way out. + */ static bool have_cpu_die(void) { #ifdef CONFIG_HOTPLUG_CPU - int any_cpu = raw_smp_processor_id(); - const struct cpu_operations *ops = get_cpu_ops(any_cpu); + int this_cpu = raw_smp_processor_id(), cpu; + const struct cpu_operations *ops = get_cpu_ops(this_cpu); - if (ops && ops->cpu_die) - return true; + if (ops) + return ops->cpu_die; + + for_each_possible_cpu(cpu) { + if (cpu == this_cpu) + continue; + ops = get_cpu_ops(cpu); + if (!ops || !ops->cpu_die) + return false; + } + return num_possible_cpus() > 1; #endif return false; } diff --git a/arch/arm64/kernel/smp_spin_table.c b/arch/arm64/kernel/smp_spin_table.c index 0d0f200e3de6a..509bcf12ea875 100644 --- a/arch/arm64/kernel/smp_spin_table.c +++ b/arch/arm64/kernel/smp_spin_table.c @@ -5,10 +5,12 @@ * Copyright (C) 2013 ARM Ltd. */ +#include #include #include #include #include +#include #include #include @@ -151,8 +153,10 @@ const struct cpu_operations smp_spin_table_ops = { * masked. From there it goes back through secondary_holding_pen, or, when the * platform suspends the system, it stops and takes its last WFI after the commit. * It is then started again at its reset vector. Stopping and starting a CPU is - * SoC-specific, so a platform driver provides it. Until one has, CPU hotplug - * fails cleanly, as on plain spin-table. + * SoC-specific, so a platform driver provides it (spin_table_set_power_ops()); + * until one has, a suspend that needs the parked CPUs stopped is refused. + * Parking and leaving the park need only cpu_soft_restart(): without + * KEXEC_CORE, CPU hotplug fails cleanly, as on plain spin-table. * * A CPU left awake at the commit can hang the machine, and the commit can't be * undone. So each parked CPU first answers a hold, while the suspend can still @@ -174,6 +178,196 @@ static struct cpumask spin_table_cpus_early; #define SPIN_TABLE_WAIT_US 100000 +#if defined(CONFIG_HIBERNATION) && defined(CONFIG_KEXEC_CORE) +/* + * Resuming from hibernation, the boot kernel takes its secondaries offline and + * then overwrites every page the image saved, the park and its cpumasks + * included. A CPU parked there would run on in memory that changes under it, + * and its translation tables with it. On that path a CPU leaving the kernel + * waits instead in a pen the image doesn't contain: the code and a slot per + * CPU in .data..nosave, run with the MMU off. arm64 resumes only an image of + * the kernel build that is running; with the boot kernel loaded at the image + * kernel's physical address (checked when the resume starts) the pen is at the + * same place in both, and the restored kernel reads what the boot kernel left + * there. It starts each CPU from the pen through secondary_holding_pen, as at + * boot. Nothing is powered off, so this needs no platform power ops. + */ +#define SPIN_TABLE_PEN_MAGIC 0x314e455034535053ULL /* "SPS4PEN1" */ +#define SPIN_TABLE_PEN_HERE 0x45524548ULL /* "HERE", from the pen */ + +struct spin_table_pen_slot { + u64 release; /* where the CPU goes; 0 holds it */ + u64 here; /* the CPU reached the pen */ + u64 mpidr; +} __aligned(ARCH_DMA_MINALIGN); + +static struct { + u64 magic; + u64 self; /* this record's address in the kernel that wrote it */ + unsigned long penned[BITS_TO_LONGS(NR_CPUS)]; + struct spin_table_pen_slot slot[NR_CPUS]; +} spin_table_pen __nosavedata __aligned(ARCH_DMA_MINALIGN); + +static struct cpumask spin_table_cpus_penned; +static bool spin_table_pen_requested; + +static void spin_table_pen_clean(void *start, size_t size) +{ + dcache_clean_inval_poc((unsigned long)start, (unsigned long)start + size); +} + +/* + * Resuming from hibernation, before the boot kernel takes its secondaries offline. + * The restored kernel finds the pen only where it is in its own image, which holds + * when the boot kernel is loaded at the image kernel's physical address. arm64 can + * restore from a boot kernel placed elsewhere (@image_ttbr1, the image's + * swapper_pg_dir, is used for the jump), but there the pen's frames are image + * frames: the restore would overwrite them while the penned CPUs run from them with + * the MMU off. Refuse the resume then, as long as a CPU other than @primary (the + * one that stays online) would need the pen. + */ +int spin_table_hibernate_pen_begin(phys_addr_t image_ttbr1, int primary) +{ + phys_addr_t here = __pa_symbol(swapper_pg_dir); + int cpu; + + /* No record of an earlier, abandoned resume may reach the restored kernel. */ + spin_table_pen.magic = 0; + spin_table_pen_clean(&spin_table_pen, sizeof(spin_table_pen.magic)); + + if (image_ttbr1 != here) { + for_each_online_cpu(cpu) { + if (cpu == primary || get_cpu_ops(cpu) != &smp_rvbar_spin_table_ops) + continue; + pr_err("hibernation: the image's kernel ran at another physical address (swapper_pg_dir %pa, here %pa): spin-table CPUs cannot wait in this kernel's pen, resume refused\n", + &image_ttbr1, &here); + return -EINVAL; + } + return 0; + } + WRITE_ONCE(spin_table_pen_requested, true); + return 0; +} + +/* + * After they went offline. With all of them frozen, the restored kernel finds the + * record; otherwise the resume is abandoned and they go back online from the pen. + */ +void spin_table_hibernate_pen_end(bool frozen) +{ + unsigned int cpu; + + WRITE_ONCE(spin_table_pen_requested, false); + if (!frozen || cpumask_empty(&spin_table_cpus_penned)) + return; + + memset(spin_table_pen.penned, 0, sizeof(spin_table_pen.penned)); + for_each_cpu(cpu, &spin_table_cpus_penned) + __set_bit(cpu, spin_table_pen.penned); + spin_table_pen.self = __pa_symbol(&spin_table_pen); + spin_table_pen.magic = SPIN_TABLE_PEN_MAGIC; + spin_table_pen_clean(&spin_table_pen, offsetof(typeof(spin_table_pen), slot)); + pr_debug("hibernation: %u CPUs wait outside the image\n", + cpumask_weight(&spin_table_cpus_penned)); +} + +/* + * In the restored kernel, right after the image took over: the CPUs the image parked + * before its snapshot are in the boot kernel's pen now. + */ +void spin_table_hibernate_restored(void) +{ + unsigned int cpu, found = 0; + + if (spin_table_pen.magic != SPIN_TABLE_PEN_MAGIC) + return; + spin_table_pen.magic = 0; + spin_table_pen_clean(&spin_table_pen, sizeof(spin_table_pen.magic)); + if (spin_table_pen.self != __pa_symbol(&spin_table_pen)) { + pr_err("hibernation: the boot kernel's CPU pen was at %#llx, not here: its CPUs stay offline\n", + spin_table_pen.self); + return; + } + + cpumask_clear(&spin_table_cpus_penned); + for_each_present_cpu(cpu) { + if (!test_bit(cpu, spin_table_pen.penned)) + continue; + if (spin_table_pen.slot[cpu].mpidr != cpu_logical_map(cpu)) { + pr_err("hibernation: CPU%u: the pen holds MPIDR %#llx, not %#llx\n", cpu, + spin_table_pen.slot[cpu].mpidr, cpu_logical_map(cpu)); + continue; + } + cpumask_clear_cpu(cpu, &spin_table_cpus_parked); + cpumask_clear_cpu(cpu, &spin_table_cpus_held); + cpumask_clear_cpu(cpu, &spin_table_cpus_unpark); + cpumask_clear_cpu(cpu, &spin_table_cpus_off); + cpumask_set_cpu(cpu, &spin_table_cpus_penned); + found++; + } + pr_debug("hibernation: %u CPUs start from the boot kernel's pen\n", found); +} + +/* Leaves the kernel for the pen; the boot CPU waits for it to arrive (cpu_kill). */ +static void __noreturn smp_rvbar_spin_table_pen(unsigned int cpu, u64 mpidr) +{ + struct spin_table_pen_slot *slot = &spin_table_pen.slot[cpu]; + typeof(cpu_soft_restart) *restart; + + slot->release = 0; + slot->here = 0; + slot->mpidr = mpidr; + spin_table_pen_clean(slot, sizeof(*slot)); + cpumask_set_cpu(cpu, &spin_table_cpus_penned); + + cpu_install_idmap(); + restart = (void *)__pa_symbol(cpu_soft_restart); + restart(0, __pa_symbol(spin_table_hibernate_pen), __pa_symbol(slot), 0, 0); + unreachable(); +} + +static bool spin_table_pen_arrived(unsigned int cpu) +{ + struct spin_table_pen_slot *slot = &spin_table_pen.slot[cpu]; + + /* Written with the MMU off: drop any copy of the line before reading. */ + dcache_inval_poc((unsigned long)slot, (unsigned long)(slot + 1)); + return READ_ONCE(slot->here) == SPIN_TABLE_PEN_HERE; +} + +/* Starts a CPU waiting in the pen; it goes on to secondary_holding_pen. */ +static void spin_table_pen_release(unsigned int cpu) +{ + struct spin_table_pen_slot *slot = &spin_table_pen.slot[cpu]; + + WRITE_ONCE(slot->release, __pa_symbol(secondary_holding_pen)); + spin_table_pen_clean(slot, sizeof(*slot)); +} +#else +static const bool spin_table_pen_requested; +static struct cpumask spin_table_cpus_penned; + +static void smp_rvbar_spin_table_pen(unsigned int cpu, u64 mpidr) +{ +} + +static bool spin_table_pen_arrived(unsigned int cpu) +{ + return false; +} + +static void spin_table_pen_release(unsigned int cpu) +{ +} + +#ifdef CONFIG_HIBERNATION +/* Without cpu_soft_restart() a CPU cannot leave the kernel: nothing to keep. */ +int spin_table_hibernate_pen_begin(phys_addr_t image_ttbr1, int primary) { return 0; } +void spin_table_hibernate_pen_end(bool frozen) {} +void spin_table_hibernate_restored(void) {} +#endif +#endif + int spin_table_set_power_ops(const struct spin_table_power_ops *ops) { return cmpxchg(&spin_table_power, NULL, ops) ? -EBUSY : 0; @@ -222,6 +416,9 @@ int spin_table_hold_parked(void) int us, ret; unsigned int cpu; + if (!READ_ONCE(spin_table_power)) + return -EOPNOTSUPP; + /* No CPU restarted from here to the wake may pass the pen without its own bring-up. */ write_pen_release(INVALID_HWID); @@ -354,7 +551,9 @@ static int smp_rvbar_spin_table_cpu_boot(unsigned int cpu) /* The CPU may run straight into the pen: release it before it starts. */ write_pen_release(mpidr); - if (cpumask_test_cpu(cpu, &spin_table_cpus_off)) { + if (cpumask_test_and_clear_cpu(cpu, &spin_table_cpus_penned)) { + spin_table_pen_release(cpu); + } else if (cpumask_test_cpu(cpu, &spin_table_cpus_off)) { /* * Still off until it runs smp_rvbar_spin_table_postboot(): a start that times out * leaves it here, so another online attempt pulses it again. @@ -379,10 +578,11 @@ static bool smp_rvbar_spin_table_cpu_can_disable(unsigned int cpu) static int smp_rvbar_spin_table_cpu_disable(unsigned int cpu) { - if (!IS_ENABLED(CONFIG_KEXEC_CORE)) - return -EOPNOTSUPP; - - return READ_ONCE(spin_table_power) ? 0 : -EOPNOTSUPP; + /* + * A parked CPU comes back through cpu_soft_restart(). Only stopping it for a + * suspend needs the platform's power ops (spin_table_hold_parked()). + */ + return IS_ENABLED(CONFIG_KEXEC_CORE) ? 0 : -EOPNOTSUPP; } #ifdef CONFIG_KEXEC_CORE @@ -441,11 +641,14 @@ static void smp_rvbar_spin_table_cpu_die(unsigned int cpu) u64 mpidr = cpu_logical_map(cpu); /* The early-boot and crash paths get here without hotplug support. */ - if (!READ_ONCE(spin_table_power) || !IS_ENABLED(CONFIG_KEXEC_CORE)) { + if (!IS_ENABLED(CONFIG_KEXEC_CORE)) { while (1) wfe(); } + if (READ_ONCE(spin_table_pen_requested)) + smp_rvbar_spin_table_pen(cpu, mpidr); + cpumask_set_cpu(cpu, &spin_table_cpus_parked); while (!cpumask_test_cpu(cpu, &spin_table_cpus_unpark)) { @@ -464,12 +667,11 @@ static int smp_rvbar_spin_table_cpu_kill(unsigned int cpu) { int us; - if (!READ_ONCE(spin_table_power)) - return 0; - for (us = 0; us < SPIN_TABLE_WAIT_US; us += 10) { if (cpumask_test_cpu(cpu, &spin_table_cpus_parked)) return 0; + if (cpumask_test_cpu(cpu, &spin_table_cpus_penned) && spin_table_pen_arrived(cpu)) + return 0; udelay(10); } @@ -516,4 +718,17 @@ bool spin_table_cpus_stuck(void) return true; return false; } + +#ifdef CONFIG_HIBERNATION +/* + * For a hibernation that only holds without the pen. With it the kernel that + * resumes an image takes its offlined CPUs out of the memory the restore + * overwrites before it starts (spin_table_hibernate_pen_begin()), and the + * restored kernel starts them from there. + */ +bool spin_table_hibernate_cpus_stuck(void) +{ + return !IS_ENABLED(CONFIG_KEXEC_CORE) && spin_table_cpus_stuck(); +} +#endif #endif /* CONFIG_HOTPLUG_CPU */ diff --git a/arch/arm64/kernel/smp_spin_table_pen.S b/arch/arm64/kernel/smp_spin_table_pen.S new file mode 100644 index 0000000000000..4610bc09ad002 --- /dev/null +++ b/arch/arm64/kernel/smp_spin_table_pen.S @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * Where a parking spin-table CPU waits while the kernel resuming from + * hibernation overwrites memory with the image (smp_spin_table.c). + */ + +#include +#include + +/* + * x0: the CPU's struct spin_table_pen_slot: the entry address at offset 0, + * written by the kernel that starts the CPU again, and the arrival word at 8, + * written here. + * + * Entered from cpu_soft_restart() with the MMU and caches off and interrupts + * masked, so nothing here depends on the kernel's page tables or on cache + * maintenance by this CPU. The code and the slots are in .data..nosave: the + * image never contains them, so the restore leaves both as the boot kernel + * wrote them, at the same physical address in the restored kernel. + */ + .pushsection ".data..nosave", "aw" + .balign 64 +SYM_CODE_START(spin_table_hibernate_pen) + movz x1, #0x4548 + movk x1, #0x4552, lsl #16 // "HERE" + str x1, [x0, #8] + dsb sy +1: ldr x1, [x0] + cbnz x1, 2f + wfe + b 1b +2: br x1 +SYM_CODE_END(spin_table_hibernate_pen) + .popsection diff --git a/arch/arm64/kvm/arch_timer.c b/arch/arm64/kvm/arch_timer.c index 6ac3321f4c575..0773f1c1209e8 100644 --- a/arch/arm64/kvm/arch_timer.c +++ b/arch/arm64/kvm/arch_timer.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -1436,6 +1437,58 @@ static void kvm_timer_handle_errata(void) } } +/* + * A guest's counters are the physical counter minus an offset that is fixed + * when the VM is made. The physical counter can start again in a sleep: it + * always does across a resume from disk, which is a cold boot. The guest's + * counters then fall back by what the counter lost, and the guest's clock + * stands still until the counter has caught up, which takes as long as the + * host had been up. Move the offsets by the same amount instead: the + * guest's counters go on from the value they had when the system went down, + * as for a VM that was stopped that long. A counter that keeps running + * through the sleep is left alone, and the guest sees the sleep as time that + * passed. + * + * Syscore: one CPU, interrupts off, every task frozen, so no vCPU is loaded + * and nothing changes vm_list. + */ +static u64 kvm_timer_sleep_cnt; + +static int kvm_timer_syscore_suspend(void *data) +{ + kvm_timer_sleep_cnt = kvm_phys_timer_read(); + return 0; +} + +static void kvm_timer_syscore_resume(void *data) +{ + u64 now = kvm_phys_timer_read(); + unsigned int vms = 0; + struct kvm *kvm; + u64 lost; + + if (now >= kvm_timer_sleep_cnt) + return; + lost = kvm_timer_sleep_cnt - now; + list_for_each_entry(kvm, &vm_list, vm_list) { + kvm->arch.timer_data.voffset -= lost; + kvm->arch.timer_data.poffset -= lost; + vms++; + } + if (vms) + kvm_info("the counter started again in the sleep (%llu -> %llu): the counters of %u VM(s) kept\n", + kvm_timer_sleep_cnt, now, vms); +} + +static const struct syscore_ops kvm_timer_syscore_ops = { + .suspend = kvm_timer_syscore_suspend, + .resume = kvm_timer_syscore_resume, +}; + +static struct syscore kvm_timer_syscore = { + .ops = &kvm_timer_syscore_ops, +}; + int __init kvm_timer_hyp_init(bool has_gic) { struct arch_timer_kvm_info *info; @@ -1505,6 +1558,7 @@ int __init kvm_timer_hyp_init(bool has_gic) } kvm_timer_handle_errata(); + register_syscore(&kvm_timer_syscore); return 0; out_free_ptimer_irq: diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 09c7659ba37e2..d1b7b96d36942 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -1905,6 +1905,7 @@ static int ane_fw_pm_event(struct notifier_block *nb, unsigned long event, void */ if (!retained) return NOTIFY_DONE; + event = ane_fw_cold_sleep_event(event, ane_fw_sleep_warm(b)); if (event == PM_POST_SUSPEND) { ane_fw_sleep_resume(b); WRITE_ONCE(b->in_sleep, false); @@ -1949,7 +1950,7 @@ static int ane_fw_pm_event(struct notifier_block *nb, unsigned long event, void dev_warn_once(&b->pdev->dev, ANE_FW_SLEEP_REFUSED); return NOTIFY_BAD; } - /* Hibernation and restore stay refused. */ + /* With a warm sleep, hibernation and restore stay refused. */ if (ane_fw_sleep_refused_cycle(event, retained, true)) { if (event == PM_SUSPEND_PREPARE) ane_fw_sleep_unblock(b); diff --git a/drivers/accel/ane/ane_fw_cold_test.c b/drivers/accel/ane/ane_fw_cold_test.c index 8aa8b3949dfcd..e83a1342840ce 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -305,6 +305,20 @@ static void ane_cold_sleep_test(struct kunit *test) /* The device callback backstop: refuse with running firmware only. */ KUNIT_EXPECT_EQ(test, ane_fw_sleep_backstop(true), -EBUSY); KUNIT_EXPECT_EQ(test, ane_fw_sleep_backstop(false), 0); + + /* Cold-cycling maps hibernation and restore to suspend/post-suspend; warm sleep does not. */ + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(PM_HIBERNATION_PREPARE, false), + PM_SUSPEND_PREPARE); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(PM_RESTORE_PREPARE, false), + PM_SUSPEND_PREPARE); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(PM_POST_HIBERNATION, false), + PM_POST_SUSPEND); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(PM_POST_RESTORE, false), + PM_POST_SUSPEND); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(PM_HIBERNATION_PREPARE, true), + PM_HIBERNATION_PREPARE); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(PM_RESTORE_PREPARE, true), + PM_RESTORE_PREPARE); } /* diff --git a/drivers/accel/ane/ane_fw_sleep.h b/drivers/accel/ane/ane_fw_sleep.h index 1d93692e59ba3..c61eaf2b90563 100644 --- a/drivers/accel/ane/ane_fw_sleep.h +++ b/drivers/accel/ane/ane_fw_sleep.h @@ -46,4 +46,27 @@ static inline int ane_fw_sleep_backstop(bool retained) return retained ? -EBUSY : 0; } +/* + * The cold cycle powers the engine off and boots the firmware again from the + * preload, so nothing of the old firmware has to survive the transition. That + * holds for an image as well: hibernation and restore take the suspend path. + * A warm sleep keeps firmware state across it that an image cannot carry, so + * there they stay refused. + */ +static inline unsigned long ane_fw_cold_sleep_event(unsigned long event, bool sleep_warm) +{ + if (sleep_warm) + return event; + switch (event) { + case PM_HIBERNATION_PREPARE: + case PM_RESTORE_PREPARE: + return PM_SUSPEND_PREPARE; + case PM_POST_HIBERNATION: + case PM_POST_RESTORE: + return PM_POST_SUSPEND; + default: + return event; + } +} + #endif /* __ANE_FW_SLEEP_H__ */ diff --git a/drivers/accel/ane/ane_h16_backend.c b/drivers/accel/ane/ane_h16_backend.c index d7b81b2248253..7f1a76fc8b829 100644 --- a/drivers/accel/ane/ane_h16_backend.c +++ b/drivers/accel/ane/ane_h16_backend.c @@ -1165,6 +1165,29 @@ static void ane_h16_sleep_unblock(struct ane_h16_device *h) wake_up_all(&h->session.wake); } +/* + * The cold cycle powers the engine off and boots the firmware again from the + * preload, so nothing of the old firmware has to survive the transition. That + * holds for an image as well: hibernation and restore take the suspend path. + * A warm sleep keeps firmware state across it that an image cannot carry, so + * there they stay refused. + */ +static unsigned long ane_h16_sleep_event(const struct ane_h16_device *h, unsigned long event) +{ + if (h->boot.soc->sleep_warm) + return event; + switch (event) { + case PM_HIBERNATION_PREPARE: + case PM_RESTORE_PREPARE: + return PM_SUSPEND_PREPARE; + case PM_POST_HIBERNATION: + case PM_POST_RESTORE: + return PM_POST_SUSPEND; + default: + return event; + } +} + static int ane_h16_pm_event(struct notifier_block *nb, unsigned long event, void *unused) { struct ane_h16_device *h = container_of(nb, struct ane_h16_device, pm_notifier); @@ -1183,6 +1206,7 @@ static int ane_h16_pm_event(struct notifier_block *nb, unsigned long event, void dev_warn_once(h->dev, ANE_FW_SLEEP_REFUSED); return ane_fw_sleep_event(event, pinned); } + event = ane_h16_sleep_event(h, event); if (event == PM_POST_SUSPEND) { ane_h16_sleep_resume(h); ane_h16_sleep_unblock(h); @@ -1221,7 +1245,7 @@ static int ane_h16_pm_event(struct notifier_block *nb, unsigned long event, void dev_warn_once(h->dev, ANE_FW_SLEEP_REFUSED); return NOTIFY_BAD; } - /* Hibernation and restore stay refused. */ + /* With a warm sleep, hibernation and restore stay refused. */ if (ane_fw_sleep_refused_cycle(event, pinned, true)) { dev_warn_once(h->dev, ANE_FW_SLEEP_REFUSED); return NOTIFY_BAD; diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index dfa21895e9bf2..49ce3f108a463 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -3000,7 +3000,7 @@ static void bcm4377_reset_work(struct work_struct *work) */ ret = device_reprobe(&rw->pdev->dev); if (ret == -EPROBE_DEFER) - dev_info(&rw->pdev->dev, "reprobe after command timeout deferred\n"); + dev_info(&rw->pdev->dev, "reprobe deferred until the resume completes\n"); else if (ret) dev_err(&rw->pdev->dev, "reprobe after command timeout failed: %d\n", ret); @@ -3015,7 +3015,7 @@ static void bcm4377_reset_work(struct work_struct *work) * same way, by rebinding the driver. */ static void bcm4377_queue_rebind(struct bcm4377_data *bcm4377, - const char *why) + const char *why, bool failure) { struct hci_dev *hdev = bcm4377->hdev; struct bcm4377_reset_work *rw; @@ -3035,7 +3035,11 @@ static void bcm4377_queue_rebind(struct bcm4377_data *bcm4377, if (!rw) return; - bt_dev_err(hdev, "%s, rebinding the driver", why); + /* A restore from hibernation is no error: it always starts the controller over. */ + if (failure) + bt_dev_err(hdev, "%s, rebinding the driver", why); + else + bt_dev_info(hdev, "%s, rebinding the driver", why); rw->pdev = pci_dev_get(bcm4377->pdev); queue_work(bcm4377_reset_wq, &rw->work); } @@ -3062,7 +3066,7 @@ static void bcm4377_hci_reset(struct hci_dev *hdev) bt_dev_warn(hdev, "command timed out while the firmware boots after the sleep; not rebinding"); return; } - bcm4377_queue_rebind(bcm4377, "controller not responding"); + bcm4377_queue_rebind(bcm4377, "controller not responding", true); } /* @@ -3094,7 +3098,7 @@ static void bcm4377_reset_done(struct pci_dev *pdev) irq = pci_irq_vector(pdev, 0); if (irq > 0) enable_irq(irq); - bcm4377_queue_rebind(bcm4377, "function reset"); + bcm4377_queue_rebind(bcm4377, "function reset", true); } static const struct pci_error_handlers bcm4377_err_handler = { @@ -3389,7 +3393,7 @@ static int bcm4377_recover_power_lost(struct bcm4377_data *bcm4377, bool pci_loc bt_dev_err(hdev, "firmware not back after the sleep: %d", ret); /* A timeout during this boot did not rebind (bcm4377_hci_reset()). */ if (!pci_locked) - bcm4377_queue_rebind(bcm4377, "firmware not back after the sleep"); + bcm4377_queue_rebind(bcm4377, "firmware not back after the sleep", true); return ret; } bt_dev_info(hdev, "firmware booted again after the sleep"); @@ -3407,7 +3411,7 @@ static void bcm4377_power_lost_work(struct work_struct *work) bcm4377_recover_power_lost(bcm4377, false); } -static int bcm4377_suspend(struct device *dev) +static int __bcm4377_suspend(struct device *dev, bool wake) { struct pci_dev *pdev = to_pci_dev(dev); struct bcm4377_data *bcm4377 = pci_get_drvdata(pdev); @@ -3450,7 +3454,7 @@ static int bcm4377_suspend(struct device *dev) return ret; } - if (device_may_wakeup(dev)) { + if (wake && device_may_wakeup(dev)) { ret = enable_irq_wake(pdev->irq); if (ret) { int resume_ret; @@ -3488,6 +3492,51 @@ static int bcm4377_suspend(struct device *dev) return ret; } +static int bcm4377_suspend(struct device *dev) +{ + return __bcm4377_suspend(dev, true); +} + +/* + * Hibernation: nothing wakes the system from an image freeze, and a + * controller left running for a wakeup keeps writing to host memory while + * the image is created or, in the kernel that loads one, while the image is + * restored over that memory. Quiesce the firmware without a wake source. + */ +static int bcm4377_freeze(struct device *dev) +{ + return __bcm4377_suspend(dev, false); +} + +/* + * Restore from hibernation. The rings in the image date from its freeze, + * but the controller went on: it ran on through the image write + * (test_resume), or the kernel that loaded the image set it up again. The + * resume commands would only time out; rebind, and probe sets it up from + * scratch, as after a power loss. + */ +static int bcm4377_restore(struct device *dev) +{ + struct bcm4377_data *bcm4377 = pci_get_drvdata(to_pci_dev(dev)); + int ret; + + ret = apple_radio_sleep_endpoint_resume(dev); + if (ret) + return ret; + + if (bcm4377->wake_armed) { + disable_irq_wake(bcm4377->pdev->irq); + bcm4377->wake_armed = false; + } + bcm4377->quiesced = false; + bcm4377->resume_powered = false; + /* The firmware's rings are not the image's: reset at the close. */ + bcm4377->needs_reset = true; + WRITE_ONCE(bcm4377->setup_retry_blocked, false); + bcm4377_queue_rebind(bcm4377, "restored from hibernation", false); + return 0; +} + static bool bcm4377_mmio_ready(struct pci_dev *pdev) { u16 cmd = 0; @@ -3622,7 +3671,7 @@ static int bcm4377_resume(struct device *dev) ret = bcm4377_prepare_sleep_boot(bcm4377); if (ret) { dev_err(dev, "cannot prepare Bluetooth boot ROM after sleep: %d\n", ret); - bcm4377_queue_rebind(bcm4377, "post-sleep boot ROM unavailable"); + bcm4377_queue_rebind(bcm4377, "post-sleep boot ROM unavailable", true); return ret; } bcm4377->rom_ready = true; @@ -3768,7 +3817,12 @@ static int bcm4377_resume_noirq(struct device *dev) } static const struct dev_pm_ops bcm4377_ops = { - SYSTEM_SLEEP_PM_OPS(bcm4377_suspend, bcm4377_resume) + .suspend = pm_sleep_ptr(bcm4377_suspend), + .resume = pm_sleep_ptr(bcm4377_resume), + .freeze = pm_sleep_ptr(bcm4377_freeze), + .thaw = pm_sleep_ptr(bcm4377_resume), + .poweroff = pm_sleep_ptr(bcm4377_freeze), + .restore = pm_sleep_ptr(bcm4377_restore), .resume_noirq = bcm4377_resume_noirq, }; diff --git a/drivers/clk/clk-apple-nco.c b/drivers/clk/clk-apple-nco.c index 68fe4b0987b2d..eb2f23bc8bc86 100644 --- a/drivers/clk/clk-apple-nco.c +++ b/drivers/clk/clk-apple-nco.c @@ -84,6 +84,7 @@ struct applnco_channel { struct applnco_regs saved; /* over a system sleep */ bool suspended; + struct applnco_regs hib_saved; /* over a hibernation */ }; #define to_applnco_channel(_hw) container_of(_hw, struct applnco_channel, hw) @@ -340,8 +341,53 @@ static int applnco_resume_early(struct device *dev) return 0; } +/* + * A cold boot resets the channels before a hibernation image is restored, + * while MCA and ASoC resume expecting an enabled channel to keep its divider + * and increments. Save them once the clock users are frozen and write them + * back when the restore went through a boot. + */ +static int applnco_freeze_noirq(struct device *dev) +{ + struct clk_hw_onecell_data *onecell_data = dev_get_drvdata(dev); + unsigned long flags; + unsigned int i; + + for (i = 0; i < onecell_data->num; i++) { + struct applnco_channel *chan = to_applnco_channel(onecell_data->hws[i]); + + spin_lock_irqsave(&chan->lock, flags); + applnco_read_regs(chan, &chan->hib_saved); + spin_unlock_irqrestore(&chan->lock, flags); + } + + return 0; +} + +static int applnco_restore_noirq(struct device *dev) +{ + struct clk_hw_onecell_data *onecell_data = dev_get_drvdata(dev); + unsigned long flags; + unsigned int i; + + if (!pm_hibernate_restored_cold()) + return 0; + + for (i = 0; i < onecell_data->num; i++) { + struct applnco_channel *chan = to_applnco_channel(onecell_data->hws[i]); + + spin_lock_irqsave(&chan->lock, flags); + applnco_write_regs(chan, &chan->hib_saved); + spin_unlock_irqrestore(&chan->lock, flags); + } + + return 0; +} + static const struct dev_pm_ops applnco_pm_ops = { LATE_SYSTEM_SLEEP_PM_OPS(applnco_suspend_late, applnco_resume_early) + .freeze_noirq = applnco_freeze_noirq, + .restore_noirq = applnco_restore_noirq, }; static int applnco_probe(struct platform_device *pdev) diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index 3c6f2abf49b02..7c658fd785d0f 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -1777,10 +1777,11 @@ static int apple_soc_cpufreq_suspend(struct cpufreq_policy *policy) } /* - * A firmware-driven sleep powers the cluster down, and it comes back in a performance state - * of the hardware's choosing, not the one asked for at suspend. Take what it reads as the - * expected state again, before the governor starts, rather than stopping every request as if - * someone else owned it. + * A firmware-driven sleep or cold hibernation restore powers the cluster down, + * and it comes back in a performance state of the hardware's choosing, not the + * one asked for at suspend. Take what it reads as the expected state again, + * before the governor starts, rather than stopping every request as if someone + * else owned it. */ static int apple_soc_cpufreq_resume(struct cpufreq_policy *policy) { @@ -1788,7 +1789,17 @@ static int apple_soc_cpufreq_resume(struct cpufreq_policy *policy) unsigned long flags; u64 reg; - if (!priv->info->verify_transition || !pm_resume_via_firmware()) + if (pm_hibernate_is_restored() && priv->fast_die) { + struct apple_fast_die *fd = priv->fast_die; + + spin_lock_irqsave(&fd->lock, flags); + fd->start = jiffies; + fd->warned = false; + spin_unlock_irqrestore(&fd->lock, flags); + } + + if (!priv->info->verify_transition || + (!pm_resume_via_firmware() && !pm_hibernate_restored_cold())) return 0; raw_spin_lock_irqsave(&priv->lock, flags); @@ -1962,6 +1973,14 @@ static void apple_fast_die_sample(struct apple_fast_die *fd) fd->waiting = false; } else { limit = fd->fallback; + /* + * The PMP stopped after it had run (a resume from disk restarts it): + * the wait, and its warning, start over from now. + */ + if (!fd->waiting && fd->report) { + fd->start = jiffies; + fd->warned = false; + } fd->waiting = true; if (!fd->warned && time_after(jiffies, fd->start + APPLE_FAST_DIE_WARN_S * HZ)) { diff --git a/drivers/dma/apple-admac.c b/drivers/dma/apple-admac.c index 9117fa81d72ef..17759a0f34586 100644 --- a/drivers/dma/apple-admac.c +++ b/drivers/dma/apple-admac.c @@ -1632,15 +1632,11 @@ static int admac_runtime_resume(struct device *dev) * client still holds (genpd gates the domain at noirq), and its client won't * configure it again: only a new hw_params does that. */ -static int __maybe_unused admac_resume_early(struct device *dev) +static void admac_mark_lost(struct admac_data *ad) { - struct admac_data *ad = dev_get_drvdata(dev); unsigned long flags; int i; - if (!pm_suspend_via_firmware()) - return 0; - mutex_lock(&ad->cache_alloc_lock); ad->ctl_programmed = false; mutex_unlock(&ad->cache_alloc_lock); @@ -1650,13 +1646,39 @@ static int __maybe_unused admac_resume_early(struct device *dev) ad->channels[i].lost = true; spin_unlock_irqrestore(&ad->channels[i].lock, flags); } +} +static int admac_resume_early(struct device *dev) +{ + struct admac_data *ad = dev_get_drvdata(dev); + + if (!pm_suspend_via_firmware()) + return 0; + + admac_mark_lost(ad); return 0; } +#ifdef CONFIG_HIBERNATION +static int admac_restore_early(struct device *dev) +{ + struct admac_data *ad = dev_get_drvdata(dev); + + if (pm_hibernate_restored_cold()) + admac_mark_lost(ad); + return 0; +} +#endif + /* Allocated channels must stay powered, including paused cyclic transfers. */ static const struct dev_pm_ops admac_pm_ops = { - LATE_SYSTEM_SLEEP_PM_OPS(NULL, admac_resume_early) + .resume_early = pm_sleep_ptr(admac_resume_early), + .thaw_early = pm_sleep_ptr(admac_resume_early), +#ifdef CONFIG_HIBERNATION + .restore_early = admac_restore_early, +#else + .restore_early = pm_sleep_ptr(admac_resume_early), +#endif RUNTIME_PM_OPS(admac_runtime_suspend, admac_runtime_resume, NULL) }; diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 424a8abb3c4dd..7db92f67d679b 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -3433,10 +3433,139 @@ static __maybe_unused int sio_resume_early(struct device *dev) return 0; } +/* + * After a hibernation restore the boot loader has staged the firmware anew and left it halted: + * boot it as probe does, on this kernel's buffers. The channels are idle: user space was frozen. + */ +static int sio_restart_after_restore(struct sio_data *sio) +{ + size_t size = SIO_SHMEM_SIZE; + int err; + + err = apple_rtkit_reinit(sio->rtk); + if (err) + return err; + writel(CPU_CONTROL_RUN, sio->base + REG_CPU_CONTROL); + err = apple_rtkit_boot(sio->rtk); + if (err) + return err; + if (sio->firmware_only) + return 0; + + err = apple_rtkit_start_ep(sio->rtk, EP_SIO); + if (err) + return err; + err = sio_call(sio, FIELD_PREP(SIOMSG_TYPE, MSG_START)); + if (err < 1) + return err ?: -ENXIO; + err = sio_send_dt_params(sio); + if (err < 0) + return err; + + if (sio->arrays) + size = (size_t)sio->arrays->segments * sio->arrays->segment_size; + memset(sio->shmem, 0, size); + bitmap_zero(sio->desc_allocated, SIO_NO_DESC_SLOTS); + if (sio->arrays) { + memset(sio->responses, 0, + (size_t)sio->arrays->responses * sio->arrays->response_size); + return sio_send_v9_shmem(sio, sio_set_param); + } + err = sio_set_param(sio, 1, sio->shmem_iova >> 12); + if (err) + return err; + return sio_set_param(sio, 2, SIO_SHMEM_SIZE); +} + +/* + * Hibernation: nothing may be in flight when the image is taken, so a busy channel refuses it. + * On the hibernating kernel the firmware is left as runtime PM has it, and .thaw returns it the + * same way: the hibernation goes on in this kernel once the image is taken, written or not. + * + * A firmware that a kernel has started does not take a second boot before the next reboot: it + * answers the handshake and then refuses its parameters. A kernel that loads an image and has + * started the firmware idles it before the jump, so that it stops writing into memory the image + * overwrites, and leaves its run bit set, which tells the restored kernel that it cannot boot it. + */ +static __maybe_unused int sio_hib_freeze(struct device *dev) +{ + struct sio_data *sio = dev_get_drvdata(dev); + int i, ret; + + if (sio->hw->commit_stop) + return sio_system_suspend(dev); + for (i = 0; i < sio->nchannels; i++) { + if (sio_chan_busy(&sio->channels[i])) { + dev_err(dev, "channel %d is busy, refusing the hibernation\n", i); + return -EBUSY; + } + } + if (!pm_hibernate_is_loading()) + return sio_system_suspend(dev); + + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + ret = apple_rtkit_idle(sio->rtk); + if (ret) { + pm_runtime_put_noidle(dev); + dev_err(dev, "firmware did not idle before the image: %d\n", ret); + return ret; + } + apple_rtkit_mailbox_off(sio->rtk); + pm_runtime_put_noidle(dev); + + return 0; +} + +/* + * On the restored kernel: the firmware boots again on this kernel's buffers, once. The image holds + * the mailbox and runtime PM state of the firmware that ran when it was taken: the mailbox goes + * off and runtime PM's stop is forgotten, so that the runtime resume doesn't start the firmware + * first. With the run bit set, the kernel that loaded the image started the firmware: it cannot + * boot again, and the SIO stays off until the next boot. + */ +static __maybe_unused int sio_restore(struct device *dev) +{ + struct sio_data *sio = dev_get_drvdata(dev); + int ret; + + WRITE_ONCE(sio->rpm_stopped, false); + WRITE_ONCE(sio->rtk_unavailable, false); + ret = sio_system_resume(dev); + if (ret) + return ret; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + apple_rtkit_mailbox_off(sio->rtk); + if (readl(sio->base + REG_CPU_CONTROL) & CPU_CONTROL_RUN) { + WRITE_ONCE(sio->rtk_unavailable, true); + pm_runtime_put(dev); + dev_warn(dev, "firmware started by the boot that loaded the image: off until the next boot\n"); + return 0; + } + ret = sio_restart_after_restore(sio); + pm_runtime_put(dev); + if (ret) { + WRITE_ONCE(sio->rtk_unavailable, true); + dev_err(dev, "firmware not booted again after the hibernation: %d\n", ret); + return 0; + } + dev_info(dev, "firmware booted again after the hibernation restore\n"); + + return 0; +} + static const struct dev_pm_ops sio_pm_ops = { .prepare = pm_sleep_ptr(sio_pm_prepare), .complete = pm_sleep_ptr(sio_pm_complete), - SYSTEM_SLEEP_PM_OPS(sio_system_suspend, sio_system_resume) + .suspend = pm_sleep_ptr(sio_system_suspend), + .resume = pm_sleep_ptr(sio_system_resume), + .freeze = pm_sleep_ptr(sio_hib_freeze), + .thaw = pm_sleep_ptr(sio_system_resume), + .poweroff = pm_sleep_ptr(sio_hib_freeze), + .restore = pm_sleep_ptr(sio_restore), LATE_SYSTEM_SLEEP_PM_OPS(sio_suspend_late, sio_resume_early) RUNTIME_PM_OPS(sio_suspend, sio_resume, NULL) }; diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 8be3305b6e645..d1b0f5c3e66cd 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -97,6 +97,7 @@ struct apple_drm_private { struct list_head pm_node; /* The notifier's output restore, run outside apple_drm_pm_lock. */ struct work_struct pm_resume_work; + bool hib_thaw_skipped; }; static struct apple_drm_private *to_apple_drm(struct drm_device *drm) @@ -2668,6 +2669,7 @@ static int apple_drm_init_dcp(struct device *dev) bool ready[MAX_COPROCESSORS] = {}; struct device_node *np; u64 timeout; + unsigned int ready_ms; int i, ret, num_dcp = 0; int pass; @@ -2759,14 +2761,20 @@ static int apple_drm_init_dcp(struct device *dev) } /* - * Starting DPTX might take some time. The T6041 panel runs its - * client-open, main-display and power chain inside the start: give it - * as long as that takes. + * Starting DPTX might take some time. A processor whose match data names + * a longer ready wait is given that long (the T6041 panel runs its + * client-open, main-display and power chain inside the start). */ - timeout = get_jiffies_64() + msecs_to_jiffies(3000); - for (i = 0; i < num_dcp; i++) - if (of_device_is_compatible(dcp[i]->dev.of_node, "apple,t6041-dcp")) - timeout = get_jiffies_64() + msecs_to_jiffies(10000); + ready_ms = 3000; + for (i = 0; i < num_dcp; i++) { + struct apple_dcp *adcp = platform_get_drvdata(dcp[i]); + unsigned int ms = adcp && adcp->hw.ready_timeout_ms ? + adcp->hw.ready_timeout_ms : 3000; + + if (ms > ready_ms) + ready_ms = ms; + } + timeout = get_jiffies_64() + msecs_to_jiffies(ready_ms); for (i = 0; i < num_dcp; ++i) { u64 jiffies = get_jiffies_64(); @@ -3116,6 +3124,14 @@ static int apple_platform_probe(struct platform_device *pdev) struct component_match *match = NULL; int num_dcp, ret; + /* + * Do not bind the display subsystem in a restore kernel while a + * resume-from-disk attempt is still outstanding. See + * pm_hibernate_resume_pending(). + */ + if (pm_hibernate_resume_pending()) + return -EPROBE_DEFER; + /* add DCP components, handle less than 1 as probe error */ num_dcp = add_dcp_components(mdev, &match); if (num_dcp < 1) @@ -3176,18 +3192,19 @@ static bool apple_drm_firmware_stopped(struct apple_drm_private *apple) static void apple_drm_resume_outputs(struct apple_drm_private *apple); -static int apple_platform_suspend(struct device *dev) +/* @stop: the display firmware stopped, as for a real sleep (dcp_t6041_s2r_all()). */ +static int apple_drm_sleep(struct device *dev, bool stop) { struct apple_drm_private *apple = dev_get_drvdata(dev); /* Still suspended from before a dark wake. */ if (apple && apple->dark_held) { - if (pm_suspend_via_firmware()) + if (stop) return dcp_t6041_s2r_all(false); return 0; } - if (pm_suspend_via_firmware()) { + if (stop) { int ret = dcp_t6041_s2r_all(false); if (ret) @@ -3206,7 +3223,7 @@ static int apple_platform_suspend(struct device *dev) } } - if (!pm_suspend_via_firmware()) { + if (!stop) { int ret = dcp_t6041_s2idle(false); if (ret) { @@ -3219,6 +3236,11 @@ static int apple_platform_suspend(struct device *dev) return 0; } +static int apple_platform_suspend(struct device *dev) +{ + return apple_drm_sleep(dev, pm_suspend_via_firmware()); +} + /* * The DCP of an external display sends the hotplug event for its CRTC * itself, once the modes of the new link are in; see dcp_hold_resume_event(). @@ -3285,6 +3307,61 @@ static int apple_platform_resume(struct device *dev) return 0; } +#ifdef CONFIG_HIBERNATION +/* + * Hibernation (Documentation/driver-api/pm/devices.rst): the display firmware is stopped at + * .freeze as for a real sleep, so the image holds it stopped by Linux, and stays stopped + * through the image write: .thaw brings it back only if the hibernation failed, or if the + * machine suspends instead of powering off, and PM_POST_HIBERNATION does once this kernel + * goes on after anything else (as amdgpu's .thaw). .restore so starts from the state of the + * image: a restore by the kernel that wrote it, or after a failed power-off, takes the sleep's + * return; one through a boot finds firmware the boot loader started anew. + */ +static int apple_platform_freeze(struct device *dev) +{ + struct apple_drm_private *apple = dev_get_drvdata(dev); + + if (apple && apple->hib_thaw_skipped) + return 0; + return apple_drm_sleep(dev, true); +} + +static int apple_platform_poweroff(struct device *dev) +{ + struct apple_drm_private *apple = dev_get_drvdata(dev); + + /* Still suspended from .freeze after .thaw kept outputs off for image write. */ + if (apple && apple->hib_thaw_skipped) + return 0; + return apple_drm_sleep(dev, true); +} + +static int apple_platform_thaw(struct device *dev) +{ + struct apple_drm_private *apple = dev_get_drvdata(dev); + + if (!pm_hibernate_is_recovering() && !pm_hibernation_mode_is_suspend()) { + if (apple) + apple->hib_thaw_skipped = true; + return 0; + } + return apple_platform_resume(dev); +} + +static int apple_platform_restore(struct device *dev) +{ + struct apple_drm_private *apple = dev_get_drvdata(dev); + + if (apple) + apple->hib_thaw_skipped = false; + dcp_t6041_hib_restore(); + if (!apple || apple->aborted || apple->s2r_skipped) + return 0; + apple_drm_resume_outputs(apple); + return 0; +} +#endif + /* The suspend after a dark wake failed before it suspended this device. */ static void apple_platform_complete(struct device *dev) { @@ -3303,6 +3380,13 @@ static void apple_drm_pm_resume_work(struct work_struct *work) struct apple_drm_private *apple = container_of(work, struct apple_drm_private, pm_resume_work); +#ifdef CONFIG_HIBERNATION + /* The image was not entered, or was written and the power-off did not come. */ + if (apple->hib_thaw_skipped) { + apple->hib_thaw_skipped = false; + apple_platform_resume(apple->drm.dev); + } +#endif if (apple->dark_held) { dev_warn(apple->drm.dev, "dark wake over without a resume: outputs back now\n"); apple_drm_resume_outputs(apple); @@ -3321,12 +3405,12 @@ static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, /* The T8132 external outputs' sleep handling (a no-op without them). */ ret = t8132_ext_drm_pm_event(action); - if (action != PM_POST_SUSPEND) + if (action != PM_POST_SUSPEND && action != PM_POST_HIBERNATION) return ret; mutex_lock(&apple_drm_pm_lock); list_for_each_entry(apple, &apple_drm_pm_list, pm_node) - if (apple->dark_held) + if (apple->dark_held || apple->hib_thaw_skipped) queue_work(apple_drm_pm_wq, &apple->pm_resume_work); mutex_unlock(&apple_drm_pm_lock); @@ -3336,6 +3420,12 @@ static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, static const struct dev_pm_ops apple_platform_pm_ops = { .suspend = apple_platform_suspend, .resume = apple_platform_resume, +#ifdef CONFIG_HIBERNATION + .freeze = apple_platform_freeze, + .thaw = apple_platform_thaw, + .poweroff = apple_platform_poweroff, + .restore = apple_platform_restore, +#endif .complete = apple_platform_complete, }; #else diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index cf8e8f7af171e..635844e75c895 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -341,8 +341,8 @@ struct dcp_t6041_power { bool child_valid; u32 boot_ps[3]; bool boot_ps_valid; - /* apple,t6040-display-power: the external DCPs are restarted after the wake */ - bool t6040; + /* From display-power match data: the external DCPs are restarted after the wake */ + bool relink_ext; }; /* @@ -491,6 +491,12 @@ struct apple_dcp_hw_data { * D572 turns it off first, and the stop's power-down resets it (T8103). */ bool s2r_disp_dart_with_dcp; + /* + * How long apple_drm_start waits for this processor to become ready after + * start (0: 3 s). The T6041 panel runs its client-open, main-display and + * power chain inside the start, so its wait has to cover that. + */ + unsigned int ready_timeout_ms; /* * Keep the external processor out of runtime idle power-off * (dcp_ext_idle_capable()) while hot-plug wake from idle-off is @@ -786,21 +792,21 @@ struct apple_dcp { /* T6041 S2R: this external DCP's firmware stop ran in a sleep of this boot */ bool t6041_ext_seen; /* T6040 S2R: this external DCP's link set up again once its firmware is back */ - struct work_struct t6040_link_work; + struct work_struct ext_link_work; /* * T6040 S2R: an external display's link work is through once the firmware reports the * display plugged again; this bounds the wait for that. */ - struct delayed_work t6040_plug_wq; + struct delayed_work ext_plug_wq; /* T6040 S2R: the link work waits for the firmware's plug of the display. */ - bool t6040_plug_wait; + bool ext_plug_wait; /* * T6040 S2R: from this external DCP's stop until its link work is through, the DRM - * entry points leave its firmware alone (see dcp_t6040_ext_link_down()). + * entry points leave its firmware alone (see dcp_ext_link_down()). */ - bool t6040_relinking; + bool ext_relinking; /* T6040 S2R: the fixed HDMI output's DP PHY was given back for the sleep. */ - bool t6040_fixed_phy_off; + bool fixed_phy_off; /* * A T6030 external processor in the main DRM device: the kernel starts * its firmware on first use, its modes come from the attached display. @@ -1594,6 +1600,17 @@ struct apple_dcp { struct delayed_work link_recovery_wq; unsigned int link_recovery_tries; unsigned int link_recovery_snap; + /* + * Kernel retrains of an active CRTC from the hotplug worker in the + * current window (dcp_hotplug_retrain_allowed()): a sink that answers + * every retrain with IRQ_HPD would otherwise loop forever. + */ + unsigned long hotplug_retrain_since; + unsigned long hotplug_disconnect_at; + unsigned int hotplug_retrains; + bool hotplug_retrain_stopped; + /* One retrain at the end of a stopped window, see dcp_hotplug(). */ + struct delayed_work hotplug_retrain_retry_wq; atomic_t modesets_done; unsigned long hdmi_edge_jiffies; bool hdmi_edge_seen; @@ -1617,6 +1634,36 @@ struct apple_dcp { unsigned int tb_hpd_count; ktime_t tb_irq_hpd_last; + /* + * Resume from disk (desktop 26.x panel and dcpext), see + * dcp_platform_restore(): + * the IOMFB shared-memory iova, given again to the restarted firmware; + * the restore phase; RTKit receive held since freeze; the + * PM_POST_HIBERNATION notifier and the work that restarts the firmware. + */ + dma_addr_t shmem_iova; + int hib_phase; + bool hib_rx_held; + bool hib_poweroff_entered; + bool hib_nb_registered; + /* + * External processors (dcpext): link work and the HDMI HPD interrupt + * stopped, the link and DP PHYs released, from hibernation prepare + * until PM_POST_HIBERNATION replays the link; this + * processor still counted in the restart's firmware-start and + * idle-pipe barriers (see dcp_hib_ext_restore()). + */ + bool hib_typec_disabled; + bool hib_irq_disabled; + /* The fixed (HDMI) DP PHY given back at prepare, see dcp.c. */ + bool hib_fixed_phy_off; + /* Link work stopped and the link released at hibernation prepare. */ + bool hib_link_released; + bool hib_ext_start_pending; + bool hib_ext_idle_pending; + struct notifier_block hib_nb; + struct work_struct hib_restore_work; + /* Kept last: the template instances share the layout above. */ struct dcp_desktop_state *desktop; /* Internal panel identity; NULL without an internal panel. */ @@ -1642,6 +1689,44 @@ bool dcp_retain_live_session_commit(struct apple_dcp *dcp, struct dcp_session_ref *session); int dcp_retain_live_session(struct apple_dcp *dcp); +/* + * Resume-from-disk restart of the desktop 26.x panel's firmware. + * QUIESCED: the old session is dropped on the host side, nothing goes to the + * firmware; RESTARTING: the restart work talks to the new firmware, the DRM + * entry points still do not; FAILED: as QUIESCED, until the reboot. + */ +enum dcp_hib_phase { + DCP_HIB_NONE = 0, + DCP_HIB_QUIESCED, + DCP_HIB_RESTARTING, + DCP_HIB_FAILED, +}; + +/* The DRM and backlight entry points leave the firmware alone. */ +static inline bool dcp_hib_gated(const struct apple_dcp *dcp) +{ + return IS_ENABLED(CONFIG_HIBERNATION) && + READ_ONCE(dcp->hib_phase) != DCP_HIB_NONE; +} + +/* No message goes to or comes from the firmware at all. */ +static inline bool dcp_hib_tx_gated(const struct apple_dcp *dcp) +{ + int phase = READ_ONCE(dcp->hib_phase); + + return IS_ENABLED(CONFIG_HIBERNATION) && + (phase == DCP_HIB_QUIESCED || phase == DCP_HIB_FAILED); +} + +/* The restart of the last resume from disk has not finished yet. */ +static inline bool dcp_hib_busy(const struct apple_dcp *dcp) +{ + int phase = READ_ONCE(dcp->hib_phase); + + return IS_ENABLED(CONFIG_HIBERNATION) && + (phase == DCP_HIB_QUIESCED || phase == DCP_HIB_RESTARTING); +} + /* T8132 firmware uses its own wire codec, with the common DRM/KMS owner. */ /* The display's own timings: the catalogue less the notch-free twins. */ static inline unsigned int dcp_nr_timings(const struct apple_dcp *dcp) @@ -1748,6 +1833,7 @@ bool dcp_external_hotplug(struct apple_dcp *dcp, bool connected); void dcp_announce_arm(struct apple_dcp *dcp); void dcp_announce_work(struct work_struct *work); void dcp_external_crtc_released(struct apple_dcp *dcp); +bool dcp_external_has_sink(struct apple_dcp *dcp); void dcp_external_link_fault(struct apple_dcp *dcp); irqreturn_t dcp_desktop_dp2hdmi_hpd(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index f0a1c3af9589a..9de262d9b55c8 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +48,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +56,7 @@ #include #include +#include #include #include #include @@ -63,6 +66,7 @@ #include #include #include +#include #include #include #include @@ -2066,6 +2070,13 @@ void dcp_swap_watchdog_complete(struct apple_dcp *dcp) dcp_takeover_adopt_proven(dcp); } +/* A sink is attached: a Type-C route is claimed, or HDMI HPD is high. */ +bool dcp_external_has_sink(struct apple_dcp *dcp) +{ + return READ_ONCE(dcp->active_typec_route) || + (dcp->hdmi_hpd && gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0); +} + /* * The firmware reports that the DisplayPort sink stopped answering, or that * the link did not start. On the external H17P display, the mode set @@ -2090,6 +2101,9 @@ static void dcp_recv_msg(void *cookie, u8 endpoint, u64 message) if (READ_ONCE(dcp->quiescing)) return; + /* Resume from disk: the host session is being rebuilt, see dcp.c. */ + if (dcp_hib_tx_gated(dcp)) + return; trace_dcp_recv_msg(dcp, endpoint, message); @@ -2546,6 +2560,9 @@ int dcp_send_message_ret(struct apple_dcp *dcp, u8 endpoint, u64 message) if (READ_ONCE(dcp->quiescing) || (dcp_is_ext26(dcp) && READ_ONCE(dcp->ext26_blocked))) return -ESHUTDOWN; + /* Resume from disk: nothing reaches a firmware session not yet rebuilt. */ + if (dcp_hib_tx_gated(dcp)) + return -ESHUTDOWN; #if IS_ENABLED(CONFIG_DRM_APPLE_KUNIT_TEST) if (dcp->test_send) return dcp->test_send(dcp, endpoint, message); @@ -3646,8 +3663,9 @@ static int dcp_desktop_dptx_connect(struct apple_dcp *dcp, u32 port) /* Without a sink the link is configured once one arrives. */ left = wait_for_completion_timeout(&dptx->linkcfg_completion, DPTX_CONNECT_TIMEOUT); - if (!left) - dev_dbg(dcp->dev, "DPTX port %u: no link configuration yet\n", port); + dev_info(dcp->dev, "DPTX port %u: link configuration %s after %u ms\n", + port, left ? "ready" : "not ready", + jiffies_to_msecs(DPTX_CONNECT_TIMEOUT - left)); usleep_range(5, 10); @@ -4154,6 +4172,17 @@ static void dcp_link_recovery_work(struct work_struct *work) dcp_dptx_connect_oob(pdev, 0); } +/* The end of a stopped retrain window (dcp_hotplug_retrain_allowed()). */ +static void dcp_hotplug_retrain_retry_work(struct work_struct *work) +{ + struct apple_dcp *dcp = container_of(to_delayed_work(work), struct apple_dcp, + hotplug_retrain_retry_wq); + struct apple_connector *connector = READ_ONCE(dcp->connector); + + if (connector && READ_ONCE(connector->connected)) + schedule_work(&connector->hotplug_wq); +} + static void dcp_typec_reconnect_work(struct work_struct *work) { struct apple_dcp *dcp = @@ -5276,6 +5305,44 @@ static int dcp_desktop_start_ext_ep(struct apple_dcp *dcp, u32 map, u32 endpoint return 0; } +/* + * The link step of an external processor's start: a Type-C route powers the + * PHY and selects the crossbar when it is claimed; until then there is no + * link to bring up. + * + * The HDMI output's connect waits up to DPTX_CONNECT_TIMEOUT for a link + * configuration, which without a sink never comes: with HPD low, leave the + * connect to dcp_enable_dp2hdmi_hpd() once the processor is up and to the HPD + * interrupt, so the start does not hold the display driver back by that wait. + */ +static void dcp_start_desktop_ext_link(struct apple_dcp *dcp) +{ + int ret; + + if (!dptx_service_available(&dcp->dptxport[0]) || + !(dcp->fixed_phy || dcp->active_typec_route)) + return; + if (!dcp->active_typec_route && dcp->hdmi_hpd && + !gpiod_get_value_cansleep(dcp->hdmi_hpd)) { + dev_dbg(dcp->dev, "no HDMI sink at startup: no DPTX link yet\n"); + return; + } + ret = dcp_dptx_connect(dcp, 0); + if (ret) + dev_info(dcp->dev, "no DPTX link at startup: %d\n", ret); +} + +/* + * Resume from disk: the restart work connects the link itself, once this + * processor's DRM entry points are open again and the other external + * processors run (see dcp_hib_ext_restore()). + */ +static bool dcp_hib_link_deferred(struct apple_dcp *dcp) +{ + return IS_ENABLED(CONFIG_HIBERNATION) && + READ_ONCE(dcp->hib_phase) == DCP_HIB_RESTARTING; +} + static int dcp_start_desktop_external(struct apple_dcp *dcp, u32 map) { struct dcp_desktop_state *d = dcp->desktop; @@ -5366,27 +5433,8 @@ static int dcp_start_desktop_external(struct apple_dcp *dcp, u32 map) if (ret) return ret; - /* - * A Type-C route powers the PHY and selects the crossbar when it is - * claimed; until then there is no link to bring up. - * - * The HDMI output's connect waits up to DPTX_CONNECT_TIMEOUT for a link - * configuration, which without a sink never comes: with HPD low, leave - * the connect to dcp_enable_dp2hdmi_hpd() once the processor is up and - * to the HPD interrupt, so the start does not hold the display driver - * back by that wait. - */ - if (!dptx_ret && dptx_service_available(&dcp->dptxport[0]) && - (dcp->fixed_phy || dcp->active_typec_route)) { - if (!dcp->active_typec_route && dcp->hdmi_hpd && - !gpiod_get_value_cansleep(dcp->hdmi_hpd)) { - dev_dbg(dcp->dev, "no HDMI sink at startup: no DPTX link yet\n"); - return 0; - } - ret = dcp_dptx_connect(dcp, 0); - if (ret) - dev_info(dcp->dev, "no DPTX link at startup: %d\n", ret); - } + if (!dptx_ret && !dcp_hib_link_deferred(dcp)) + dcp_start_desktop_ext_link(dcp); return 0; } @@ -6070,8 +6118,8 @@ static bool dcp_t6041_dpms_capable(struct apple_dcp *dcp); static bool dcp_dpms_power_off(struct apple_dcp *dcp); static bool dcp_dpms_power_on(struct apple_dcp *dcp); static void dcp_s2r_prewarm_work(struct work_struct *work); -static void dcp_t6040_link_work(struct work_struct *work); -static void dcp_t6040_plug_work(struct work_struct *work); +static void dcp_ext_link_work(struct work_struct *work); +static void dcp_ext_plug_work(struct work_struct *work); static void dcp_s2r_prewarm_off_work(struct work_struct *work); static bool dcp_uses_soft_dpms(struct apple_dcp *dcp) @@ -6146,8 +6194,12 @@ void dcp_poweron(struct platform_device *pdev) unsigned long remaining; int ret; - /* T6040 S2R: powered once the link is back (dcp_t6040_ext_link_down()). */ - if (READ_ONCE(dcp->t6040_relinking)) + /* + * Powered later: on T6040 S2R once the link is back + * (dcp_ext_link_down()), after a resume from disk by the + * firmware restart (dcp_hib_recommit()). + */ + if (READ_ONCE(dcp->ext_relinking) || dcp_hib_gated(dcp)) return; /* The link comes back below: an HDMI unplug held meanwhile is over. */ @@ -6469,8 +6521,12 @@ void dcp_poweroff(struct platform_device *pdev) bool display_gone = false; int ret; - /* T6040 S2R: this pipe is off until its link work is through. */ - if (READ_ONCE(dcp->t6040_relinking)) + /* + * Nothing to power off: on T6040 S2R this pipe is off until its link + * work is through, after a resume from disk there is no firmware + * session yet. + */ + if (READ_ONCE(dcp->ext_relinking) || dcp_hib_gated(dcp)) return; if (iomfb_is_m4(dcp)) { @@ -7762,6 +7818,7 @@ VISIBLE_IF_KUNIT void dcp_disable_typec_work(struct apple_dcp *dcp, bool release dcp->tb_event_route = NULL; dcp->tb_event_generation = 0; } + disable_delayed_work_sync(&dcp->hotplug_retrain_retry_wq); disable_delayed_work_sync(&dcp->hybrid_wq); } @@ -7778,6 +7835,7 @@ VISIBLE_IF_KUNIT void dcp_enable_typec_work(struct apple_dcp *dcp) enable_delayed_work(&dcp->hdmi_recheck_wq); enable_delayed_work(&dcp->link_recovery_wq); enable_work(&dcp->tb_event_work); + enable_delayed_work(&dcp->hotplug_retrain_retry_wq); enable_delayed_work(&dcp->hybrid_wq); dcp_hdmi_enable(dcp); scoped_guard(mutex, &dcp->hpd_mutex) @@ -8146,6 +8204,16 @@ static int dcp_ext26_start_resident(struct apple_dcp *dcp) return ret; } +/* Runs the coprocessor CPU; returns CPU_CONTROL as it was before. */ +static u32 dcp_coproc_assert_run(struct apple_dcp *dcp) +{ + u32 cpu_ctrl = readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); + + writel_relaxed(cpu_ctrl | APPLE_DCP_COPROC_CPU_CONTROL_RUN, + dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); + return cpu_ctrl; +} + /* * The notch rows are a fact of the panel; whether they are drawn on is the * boot loader's choice first, then the user's, at run time (see dcp-notch.h). @@ -8425,12 +8493,8 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat goto session_ready; } - if (!dcp->hw.adopt_live_session) { - cpu_ctrl = - readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); - writel_relaxed(cpu_ctrl | APPLE_DCP_COPROC_CPU_CONTROL_RUN, - dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); - } + if (!dcp->hw.adopt_live_session) + cpu_ctrl = dcp_coproc_assert_run(dcp); /* * Check a handed-over session before anything is retained for it: a @@ -8895,12 +8959,21 @@ static int dcp_native_routes_error(struct apple_dcp *dcp, int err) return 0; } +/* The fixed PHY probe powered, captured when its release was registered. */ +struct dcp_desktop_phy_hold { + struct apple_dcp *dcp; + struct phy *phy; +}; + static void dcp_desktop_phy_off(void *data) { - struct phy *phy = data; + struct dcp_desktop_phy_hold *hold = data; - phy_power_off(phy); - phy_exit(phy); + /* Given back for hibernation and not powered again, see dcp.c. */ + if (hold->dcp->hib_fixed_phy_off) + return; + phy_power_off(hold->phy); + phy_exit(hold->phy); } /* @@ -8912,12 +8985,18 @@ static void dcp_desktop_phy_off(void *data) */ static int dcp_desktop_probe_routes(struct apple_dcp *dcp) { + struct dcp_desktop_phy_hold *hold; struct device *dev = dcp->dev; int ret; if (!dcp_desktop_external(dcp) || !dcp->phy) return 0; + hold = devm_kmalloc(dev, sizeof(*hold), GFP_KERNEL); + if (!hold) + return -ENOMEM; + hold->dcp = dcp; + hold->phy = dcp->phy; ret = phy_init(dcp->phy); if (ret) return dev_err_probe(dev, ret, "Failed to initialize dp-phy\n"); @@ -8926,7 +9005,7 @@ static int dcp_desktop_probe_routes(struct apple_dcp *dcp) phy_exit(dcp->phy); return dev_err_probe(dev, ret, "Failed to power on dp-phy\n"); } - ret = devm_add_action_or_reset(dev, dcp_desktop_phy_off, dcp->phy); + ret = devm_add_action_or_reset(dev, dcp_desktop_phy_off, hold); if (ret) return ret; msleep(25); @@ -8972,6 +9051,10 @@ static void dcp_t8132_ext_routes(struct apple_dcp *dcp) } static int dcp_s2r_pm_register(struct apple_dcp *dcp); +#ifdef CONFIG_HIBERNATION +static void dcp_hib_restore_work(struct work_struct *work); +static int dcp_hib_register(struct apple_dcp *dcp); +#endif /* A DCP node with apple,sleep-host-stop: the SoC's sleep needs the display stopped from here. */ static bool dcp_sleep_host_stop; @@ -9205,7 +9288,7 @@ static int dcp_t6041_parse_chain(struct device *dev, struct dcp_t6041_power *pwr chain->domains[i] = reg; } - if ((chain->is_main || pwr->t6040) && count > 3) { + if ((chain->is_main || pwr->relink_ext) && count > 3) { chain->child_saved = devm_kcalloc(dev, count - 3, sizeof(*chain->child_saved), GFP_KERNEL); if (!chain->child_saved) @@ -9215,6 +9298,28 @@ static int dcp_t6041_parse_chain(struct device *dev, struct dcp_t6041_power *pwr return 0; } +/* + * Per-compatible data for apple,display-power. Another SoC only adds a table + * entry; the general mapping code stays generic. + */ +struct dcp_display_power_data { + /* The sleep takes the external links down and back, and restarts them. */ + bool relink_ext; +}; + +static const struct dcp_display_power_data dcp_display_power_t6041 = { +}; + +static const struct dcp_display_power_data dcp_display_power_t6040 = { + .relink_ext = true, +}; + +static const struct of_device_id dcp_display_power_of_match[] = { + { .compatible = "apple,t6040-display-power", .data = &dcp_display_power_t6040 }, + { .compatible = "apple,t6041-display-power", .data = &dcp_display_power_t6041 }, + { } +}; + static int dcp_t6041_map_power(struct apple_dcp *dcp) { struct device *dev = dcp->dev; @@ -9237,13 +9342,17 @@ static int dcp_t6041_map_power(struct apple_dcp *dcp) }; unsigned int nchains = 0, idx = 0, main_count = 0, i, j; int ret; + const struct of_device_id *id; + const struct dcp_display_power_data *pdata; if (!np) return -ENODEV; - if (!of_device_is_compatible(np, "apple,t6041-display-power")) + id = of_match_node(dcp_display_power_of_match, np); + if (!id) return -EINVAL; - /* T6040's external DCPs are restarted after the wake, from their chains. */ - pwr->t6040 = of_device_is_compatible(np, "apple,t6040-display-power"); + /* Per-compatible data: another SoC only adds a table entry. */ + pdata = id->data; + pwr->relink_ext = pdata && pdata->relink_ext; for (i = 0; i < ARRAY_SIZE(regs); i++) { void __iomem *base = dcp_t6041_map_reg(dev, np, regs[i].name, @@ -9726,6 +9835,8 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) INIT_DELAYED_WORK(&dcp->link_recovery_wq, dcp_link_recovery_work); mutex_init(&dcp->tb_event_lock); INIT_WORK(&dcp->tb_event_work, dcp_tb_event_work); + INIT_DELAYED_WORK(&dcp->hotplug_retrain_retry_wq, + dcp_hotplug_retrain_retry_work); INIT_DELAYED_WORK(&dcp->placeholder_edid_wq, dcp_placeholder_edid_work); INIT_DELAYED_WORK(&dcp->typec_relink_wq, dcp_typec_relink_work); @@ -9735,10 +9846,23 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) INIT_DELAYED_WORK(&dcp->bl_fallback_wq, dcp_work_backlight_fallback); /* System sleep and shutdown cancel these even if no bind succeeded. */ INIT_WORK(&dcp->vblank_wq, dcp_delayed_vblank); +#ifdef CONFIG_HIBERNATION + INIT_WORK(&dcp->hib_restore_work, dcp_hib_restore_work); + /* + * From probe: the notifier flushes a restart before the next sleep, + * replays a link given back for a hibernation that failed, and is in + * the image for the restore. + */ + if (fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) { + ret = dcp_hib_register(dcp); + if (ret) + return dev_err_probe(dev, ret, "no PM notifier\n"); + } +#endif INIT_DELAYED_WORK(&dcp->swap_watchdog_wq, dcp_swap_watchdog); 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->ext_link_work, dcp_ext_link_work); + INIT_DELAYED_WORK(&dcp->ext_plug_wq, dcp_ext_plug_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); @@ -9752,6 +9876,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) disable_delayed_work(&dcp->announce_wq); disable_delayed_work(&dcp->link_recovery_wq); disable_work(&dcp->tb_event_work); + disable_delayed_work(&dcp->hotplug_retrain_retry_wq); dcp->announce.stopped = true; /* * A native external pipe's bind enables these; firmware callbacks may @@ -10249,6 +10374,15 @@ static int dcp_platform_probe(struct platform_device *pdev) void *group; int ret; + /* + * The restore kernel must not start DCP firmware before the image is + * loaded: freezing a just-bound DCP around the jump leaves the + * coprocessor running against overwritten Linux state. Defer until + * software_resume() has either jumped or given up. + */ + if (pm_hibernate_resume_pending()) + return -EPROBE_DEFER; + if (hw->firmware_compat == DCP_FIRMWARE_IBOOT) { /* The port controllers wait for the USB-C display switches. */ t8152_typec_register(dev); @@ -10320,8 +10454,8 @@ 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_delayed_work_sync(&dcp->t6040_plug_wq); + cancel_work_sync(&dcp->ext_link_work); + cancel_delayed_work_sync(&dcp->ext_plug_wq); cancel_delayed_work_sync(&dcp->s2r_prewarm_off_wq); dcp_hdmi_off_hold_stop(dcp); if (system_state == SYSTEM_RUNNING && dcp->sleep_host_stop && @@ -10377,6 +10511,28 @@ static void dcp_platform_remove(struct platform_device *pdev) } /* A refused takeover left the DCP running untouched, see apple_drv.c. */ +#ifdef CONFIG_HIBERNATION +/* + * From PM_HIBERNATION_PREPARE to PM_POST_HIBERNATION, whatever + * /sys/power/disk says (shutdown, platform, reboot, suspend): see + * dcp_hib_global_notify(). Set in the image as well. + */ +static bool dcp_hib_in_progress; + +static bool dcp_hibernating(void) +{ + return READ_ONCE(dcp_hib_in_progress); +} + +static int dcp_hib_prepare(struct apple_dcp *dcp); +static bool dcp_t6041_hib_capable(void); +#else +static bool dcp_hibernating(void) +{ + return false; +} +#endif + static bool dcp_takeover_was_aborted(struct apple_dcp *dcp) { return dcp && dcp->desktop && READ_ONCE(dcp->desktop->takeover_aborted); @@ -10404,6 +10560,22 @@ VISIBLE_IF_KUNIT void dcp_platform_shutdown(struct platform_device *pdev) dcp_ext_idle_close(dcp, false); + /* + * The S4 power-off after the image is on disk: the compositor is + * frozen, and the DRM/component teardown below waits on it. The next + * boot restarts the firmware anyway, so only stop host submissions, + * as for a live session that has no stop sequence. + */ + if (dcp && dcp_hibernating()) { + pr_emerg("dcp: hibernation power-off, skipping teardown\n"); + iomfb_queue_stop(dcp); + cancel_delayed_work_sync(&dcp->bl_fallback_wq); + dcp_backlight_stop(dcp); + cancel_work_sync(&dcp->bl_register_wq); + cancel_work_sync(&dcp->bl_update_wq); + return; + } + if (dcp && iomfb_is_m4(dcp)) { dcp_comp_unbind(&pdev->dev, NULL, NULL); return; @@ -10615,6 +10787,14 @@ static int dcp_platform_prepare(struct device *dev) bool deep_v27 = dcp && pm_suspend_via_firmware() && dcp_v27_sleep_selected(dcp); int ret; +#ifdef CONFIG_HIBERNATION + if (dcp_hibernating()) { + ret = dcp_hib_prepare(dcp); + if (ret) + return ret; + } +#endif + /* TEST: the 27.2 idle-only session has no display to refuse the sleep for. */ if (dcp->ext272) return 0; @@ -14205,6 +14385,11 @@ static int dcp_platform_suspend(struct device *dev) dev_warn(dev, "native26 refuses non-s2idle target %d\n", pm_suspend_target_state); return -EBUSY; } + /* PM_SUSPEND_PREPARE flushed it; a restart still running is refused. */ + if (dcp_hib_busy(dcp)) { + dev_warn(dev, "suspend refused: firmware restart after resume from disk still running\n"); + return -EBUSY; + } iomfb_v14_7_backlight_suspend(dcp); /* Serialize PM against explicit bring-up, including queued startup work. @@ -14455,145 +14640,1306 @@ static int dcp_platform_resume(struct device *dev) } /* - * Hibernation: the T8132 power-down keeps the retained session, which a - * hibernation image cannot carry across the boot that restores it. + * The longest an external display's link work waits for the firmware to report the display + * plugged after the restart. On the J616s that came 1.0 s after the link request for a Type-C + * display and 6.1 s after it for a TV behind the HDMI port's converter (6.9 s at boot). */ -static int dcp_platform_freeze(struct device *dev) -{ - if (iomfb_is_m4(dev_get_drvdata(dev))) - return -EBUSY; - return dcp_platform_suspend(dev); -} +#define DCP_S2R_PLUG_MS 10000 -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), - .resume = pm_sleep_ptr(dcp_platform_resume), - .freeze = pm_sleep_ptr(dcp_platform_freeze), - .thaw = pm_sleep_ptr(dcp_platform_resume), - .poweroff = pm_sleep_ptr(dcp_platform_freeze), - .restore = pm_sleep_ptr(dcp_platform_resume), -}; +#ifdef CONFIG_HIBERNATION +/* + * Hibernation. + * + * The image is written with the display left as it is: the firmware's own + * power sequence is not run (it may crash the DCP), so the panel keeps + * showing the last frame until the machine powers off. + * + * A resume from disk is a cold boot: the boot loader restarts the DCP + * firmware and lights the panel with its boot framebuffer, and the boot + * kernel (which does not load this driver) jumps into the image. For the + * desktop 26.x panel (T6041, not adopted: probe itself runs the coprocessor + * and does the RTKit handshake) the restored driver rebuilds the firmware + * session in place, the way probe built it: + * + * freeze: hold RTKit receive, so the image holds it held: what the new + * firmware sends before .restore (the AIC masks come back at + * syscore resume and the mailbox IRQ is IRQF_NO_SUSPEND) stays in + * the mailbox FIFO instead of reaching the old RTKit session. + * restore: drop the old session on the host side (dcp_hib_quiesce()): + * mode invalid, endpoints quiesced, IOMFB channels, firmware + * mappings, retained framebuffers and pending flips released. + * From here the DRM entry points leave the firmware alone and a + * flip completes without a swap (dcp_hib_gated()). + * PM_POST_HIBERNATION (after the PMP is rebuilt), in a work item: + * CPU_CONTROL.RUN, apple_rtkit_reinit(), receive released, then + * dcp_start_desktop() as at probe (RTKit wake/HELLO/EPMAP, system + * and IOMFB endpoints, panel endpoints, set_shmem with the same + * arena), the IOMFB start sequence, pipe power on and a modeset + * commit of the current DRM state, which also swaps the frame. + * + * Every devm allocation, the DMA arena, the iommu mappings, clocks and + * registers are reused; no probe primitive runs again. The old endpoint + * objects are quiesced and stay allocated until unbind (a bounded leak per + * resume) because their services may still be referenced. Any failing step + * falls back to the previous behaviour: IOMFB traffic stopped, display left + * to the boot loader, until the reboot. + * + * The T6041 external processors (dcpext: HDMI on dcpext0, the Type-C + * routes on all of them, the dual-pipe peer of a display wider than one + * pipe) are restarted the same way, and then their display link is set up + * again through the paths a display plugged at runtime takes: + * + * prepare (dcp_hib_prepare(), only for hibernation: dcp_hib_in_progress + * is set by a PM_HIBERNATION_PREPARE notifier), with every DCP's + * receive still live: the link work (dcp_disable_typec_work(), + * as for s2idle) and the HDMI HPD interrupt are stopped, a merged + * dual pipe is stopped as a pair, and the display link and the + * DP PHYs are given back as at a runtime unplug + * (dcp_hib_release_ext_link()): the T6040 PHY has no PM ops and + * the cold boot resets it, so the image must record it off. + * freeze: as above. The link stays given back through thaw and the + * image write; if this kernel goes on (the hibernation failed, + * or disk=suspend woke), PM_POST_HIBERNATION replays it, as + * below, once every DCP is thawed. + * restore_early, before any .restore (the Type-C port controllers' + * .restore may report their mode again, the crossbar rewrites + * its routes in its own): the old session is dropped on the + * host side as above, its DMA (firmware mappings, framebuffers) + * only in .restore, after the DARTs restored theirs; and also + * its DPTX port services, IBOOT, DPAVSERV and the HDR + * service, the mode list, the dual-pipe pairing and the + * HDR/rate state of the link. A display that is shown is + * reported gone (disconnected_hpd_event(), as an unplug), so + * that its return is a hotplug to which the compositor answers + * with a full modeset; a Type-C display under DPMS off stays + * connected, as at runtime, and its wake connects it. The Type-C + * route itself (crossbar selection, cable, generation) is kept. + * PM_POST_HIBERNATION, in the restart work: the firmware restart as + * above, with the start's DPTX connect held back + * (dcp_hib_link_deferred()), then the DRM entry points open + * (phase NONE). A processor without a display then connects + * what its probe connects (the fixed HDMI output, sinkless); + * one with a display waits until every external processor's + * firmware runs and every idle one has done that, so that a + * display wider than one pipe finds its peer (the firmware asks + * for one during link training, dcp_peer_hints_26_6()), and + * then connects: the fixed PHY powered as at probe, the start's + * link step (its connect powers the route's PHY afresh, + * dcp_typec_phy_on()), dcp_enable_dp2hdmi_hpd() + * as dcp_wait_ready() does at probe (Type-C connect, HDMI HPD, + * HPD interrupt on) and the link work enabled again (the + * reconnect retries). The firmware's hotplug then reports the + * display, the hotplug worker sets the link status BAD and + * resets an active CRTC, and userspace gets the event. + * + * Failure before the link step leaves the processor dead (ext_dead), as a + * failed probe does: USB on its ports goes on. A failing link is left to + * the runtime reconnect and relink machinery. + */ +#define DCP_HIB_READY_TIMEOUT msecs_to_jiffies(10000) -static const struct apple_dcp_hw_data apple_dcp_hw_t6020 = { - .num_dptx_ports = 1, - .t6020_tunnel_flow = true, - .s2r = true, - .s2r_untested = true, - .s2r_no_secure_port = true, - .map_reg_dart = true, - .s2r_disp_dart_with_dcp = true, - .s2r_layout = &dcp_s2r_t6020, -}; +static bool dcp_hib_can_restart(struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && dcp->desktop && + !dcp->external && + !dcp->hw.adopt_live_session && !READ_ONCE(dcp->retain_dma) && + !IS_ERR_OR_NULL(dcp->rtk) && dcp->coproc_reg && dcp->shmem; +} -static const struct apple_dcp_hw_data apple_dcp_hw_t6020_dcpext = { - .external_processor = true, - .num_dptx_ports = 2, - .t6020_tunnel_flow = true, - .s2r_ext = true, - .s2r_untested = true, - .s2r_no_secure_port = true, - .map_reg_dart = true, - .s2r_disp_dart_with_dcp = true, - .s2r_layout = &dcp_s2r_t6020_ext[0], -}; +/* + * External processors still starting their firmware, and idle ones (no + * display) still connecting their link, in this restore. + */ +static atomic_t dcp_hib_ext_starting = ATOMIC_INIT(0); +static atomic_t dcp_hib_ext_idle = ATOMIC_INIT(0); +static DECLARE_WAIT_QUEUE_HEAD(dcp_hib_ext_wq); -static const struct apple_dcp_hw_data apple_dcp_hw_t8112 = { - .num_dptx_ports = 2, - .s2r = true, - .s2r_no_secure_port = true, - .map_reg_dart = true, - .s2r_disp_dart_with_dcp = true, - .s2r_layout = &dcp_s2r_t8112, -}; +static void dcp_hib_ext_put(struct apple_dcp *dcp, bool start, bool idle) +{ + bool wake = false; -static const struct apple_dcp_hw_data apple_dcp_hw_t8112_dcpext = { - .num_dptx_ports = 2, - .s2r_ext = true, - .s2r_no_secure_port = true, - .map_reg_dart = true, - .s2r_disp_dart_with_dcp = true, - .s2r_layout = &dcp_s2r_t8112_ext, -}; + if (start && dcp->hib_ext_start_pending) { + dcp->hib_ext_start_pending = false; + atomic_dec(&dcp_hib_ext_starting); + wake = true; + } + if (idle && dcp->hib_ext_idle_pending) { + dcp->hib_ext_idle_pending = false; + atomic_dec(&dcp_hib_ext_idle); + wake = true; + } + if (wake) + wake_up_all(&dcp_hib_ext_wq); +} -/* The internal T8140 endpoint uses the H17P method profile. */ -static const struct resource t8140_firmware_clock = - DEFINE_RES_MEM(0x302800000, 0xbc000); +static bool dcp_hib_ext_settled(void) +{ + return !atomic_read(&dcp_hib_ext_starting) && + !atomic_read(&dcp_hib_ext_idle); +} -static const struct apple_dcp_hw_data apple_dcp_hw_t8140 = { - .num_dptx_ports = 0, - .adopt_live_session = true, - .firmware_compat = DCP_FIRMWARE_H17P, - .firmware_clock = &t8140_firmware_clock, - .firmware_display_windows = 5, - .firmware_scratch = 0x20000, - .firmware_request = 0x68000, - .s2r = true, - .s2r_layout = &dcp_s2r_t8140, -}; +static void dcp_hib_log_coproc(struct apple_dcp *dcp, const char *when) +{ + u32 ctl = readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); + u32 sts = readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS); -/* Separate from the established internal-panel H17P profile. */ -static const struct apple_dcp_hw_data apple_dcp_hw_t8140_external = { - .external_processor = true, - .num_dptx_ports = 1, - .iomfb_method_profile = DCP_IOMFB_METHODS_H17P_EXTERNAL, - .adopt_live_session = false, - .firmware_compat = DCP_FIRMWARE_H17P, - .firmware_clock = &t8140_firmware_clock, - .firmware_display_windows = 4, - /* Native PMGR BWR agent 2 and boost agent 3 for DISPEXT0. */ - .firmware_scratch = 0x28000, - .firmware_request = 0x70000, - .s2r_ext = true, -}; + dev_dbg(dcp->dev, + "hibernation restore: %s: CPU_CONTROL %#x (RUN %d) CPU_STATUS %#x\n", + when, ctl, !!(ctl & APPLE_DCP_COPROC_CPU_CONTROL_RUN), sts); +} /* - * M5 (T8142) runs H17-generation DCP firmware with the H17G method numbering - * and is left running by the bootloader. + * The descriptors the old firmware allocated or mapped: nothing uses them + * any more, and the new firmware asks for its own. As release_mem_desc. */ -static const struct apple_dcp_hw_data apple_dcp_hw_t8142 = { - .num_dptx_ports = 0, - .iomfb_method_profile = DCP_IOMFB_METHODS_H17G, - .adopt_live_session = true, - .firmware_compat = DCP_FIRMWARE_H17P, - /* Firmware 27.0's sleep calls (iomfb_v27.c), unless appledrm.s2r_untested=0 */ - .s2r = true, - .s2r_untested = true, - .s2r_no_secure_port = true, - .s2r_layout = &dcp_s2r_t8142, -}; +static void dcp_hib_release_memdescs(struct apple_dcp *dcp) +{ + unsigned int id = 1, n = 0; -/* T8103's DCP: the firmware stop around DPMS off and system sleep, with its own power words */ -static const struct apple_dcp_hw_data apple_dcp_hw_t8103 = { - .num_dptx_ports = 0, - .s2r = true, - .s2r_no_secure_port = true, - .s2r_layout = &dcp_s2r_t8103, - .map_reg_dart = true, - .s2r_disp_dart_with_dcp = true, -}; + /* Bit 0 is reserved at bind: descriptor IDs start at 1. */ + for_each_set_bit_from(id, dcp->memdesc_map, DCP_MAX_MAPPINGS) { + struct dcp_mem_descriptor *memdesc = &dcp->memdesc[id]; + size_t size = ALIGN(memdesc->size, SZ_16K); -/* T8103's external DCP: maps register windows through its DART and stops/restarts across S2R */ -static const struct apple_dcp_hw_data apple_dcp_hw_t8103_dcpext = { - .num_dptx_ports = 2, - .s2r_ext = true, - .s2r_no_secure_port = true, - .s2r_layout = &dcp_s2r_t8103_ext, - .map_reg_dart = true, - .s2r_disp_dart_with_dcp = true, -}; + if (memdesc->piodma_mapped) { + if (!dcp->iommu_dom || + iommu_unmap(dcp->iommu_dom, memdesc->dva, size) != size) { + /* Keep pages the display could still read. */ + dev_warn(dcp->dev, + "hibernation restore: buffer %u stays mapped for piodma\n", + id); + continue; + } + memdesc->piodma_mapped = false; + } + clear_bit(id, dcp->memdesc_map); + if (memdesc->buf) { + sg_free_table(&memdesc->map); + dma_free_coherent(dcp->dev, size, memdesc->buf, memdesc->dva); + memdesc->buf = NULL; + memset(&memdesc->map, 0, sizeof(memdesc->map)); + } else if (memdesc->size) { + dma_unmap_resource(dcp->dev, memdesc->dva, memdesc->size, + DMA_BIDIRECTIONAL, 0); + memdesc->reg = 0; + } + memdesc->dva = 0; + memdesc->size = 0; + n++; + } + dev_dbg(dcp->dev, "hibernation restore: released %u firmware mappings\n", n); +} -static const struct apple_dcp_hw_data apple_dcp_hw_dcp = { - .num_dptx_ports = 0, -}; +/* Host side of the old firmware session; called with userspace frozen. */ +static void dcp_hib_quiesce(struct apple_dcp *dcp) +{ + struct dcp_desktop_state *d = dcp->desktop; + int i; -static const struct apple_dcp_hw_data apple_dcp_hw_t6030 = { - .iboot_handoff = "apple,t6030-handoff", - .num_dptx_ports = 1, - .afk_name_fallback = true, - /* Firmware 27.2's sleep: only with the DT's sleep arguments and display power words */ - .v27_early_stop = true, + WRITE_ONCE(dcp->hib_phase, DCP_HIB_QUIESCED); + WRITE_ONCE(dcp->active, false); + dcp_mode_invalidate(&dcp->mode_state); + + cancel_delayed_work_sync(&dcp->swap_watchdog_wq); + dcp_backlight_stop(dcp); + if (dcp->secure_rtk) { + dcp_secure_poll_stop(dcp); + dcp->secure_answered = false; + } + + /* Endpoint objects stay allocated: their services may be referenced. */ + afk_quiesce(dcp->systemep); + dcp->systemep = NULL; + for (i = 0; i < ARRAY_SIZE(d->graph); i++) { + struct apple_dcp_afkep *ep = READ_ONCE(d->graph[i]); + + if (ep) { + afk_quiesce(ep); + WRITE_ONCE(d->graph[i], NULL); + } + } + d->graph_started = 0; + d->graph_skipped = 0; + d->dpavctrl_av_controller[0] = NULL; + d->dpavctrl_av_controller[1] = NULL; + d->dpavctrl_late_service = NULL; + + /* Calls in flight on the old session are never answered. */ + memset(&dcp->ch_cmd, 0, sizeof(dcp->ch_cmd)); + memset(&dcp->ch_oobcmd, 0, sizeof(dcp->ch_oobcmd)); + memset(&dcp->ch_cb, 0, sizeof(dcp->ch_cb)); + memset(&dcp->ch_oobcb, 0, sizeof(dcp->ch_oobcb)); + memset(&dcp->ch_async, 0, sizeof(dcp->ch_async)); + memset(&dcp->ch_oobasync, 0, sizeof(dcp->ch_oobasync)); + kfree(dcp->chunks.data); + memset(&dcp->chunks, 0, sizeof(dcp->chunks)); + + /* Start over as from probe: clear the surfaces on the first swap. */ + dcp->surfaces_cleared = false; + dcp->have_swap_complete = false; + dcp->last_swap_id = 0; + d->mode_live = false; + d->modeset_active = false; + d->modeset_callback_error = false; + d->trial_powered = false; + d->trial_modeset_ok = false; + d->poweron_result = 0; + d->present_pending = false; + d->vrr_min_sent = 0; +} + +/* + * The old session's DMA: the firmware mappings and the framebuffers its + * swaps held. In .restore, not before: the DARTs restore their state in the + * normal phase (pm_runtime_force_resume()), and these unmap through them. + */ +static void dcp_hib_release_dma(struct apple_dcp *dcp) +{ + dcp_hib_release_memdescs(dcp); + /* Swaps of the old session never complete: drop what they held. */ + dcp_release_all_retained_framebuffers(dcp); + + /* A flip the old session took before the image completes now. */ + if (READ_ONCE(dcp->crtc)) + schedule_work(&dcp->vblank_wq); +} + +/* + * External processor at freeze (and, if freeze did not, at restore): no link + * work and no HDMI HPD edge may reach the old session, nor, after the + * restore, the new one before it runs. As dcp_platform_suspend() stops them + * for s2idle, without its firmware calls. + */ +static void dcp_hib_stop_ext_link_work(struct apple_dcp *dcp) +{ + if (!dcp->hib_typec_disabled) { + dcp_disable_typec_work(dcp, false); + dcp->hib_typec_disabled = true; + } + cancel_delayed_work_sync(&dcp->swap_watchdog_wq); + if (dcp->hdmi_hpd_irq && !dcp->hib_irq_disabled) { + disable_irq(dcp->hdmi_hpd_irq); + dcp->hib_irq_disabled = true; + } +} + +/* + * External processor at hibernation prepare (dcp_hib_prepare()), after the + * link work is stopped, while every DCP's RTKit receive is still live: + * release the display link and give back the DP PHYs, so that the image + * records them off. The T6040 PHY (apple,t6040-atcphy) + * has no PM ops: the S4 cold boot resets it while its driver state, the PHY + * core's init/power counts and phy_powered come back from the image as on, + * and a later phy_power_on() would not set it up again. + * + * The link goes as at a runtime unplug of the sink (the HDMI + * dcp_desktop_dptx_disconnect_oob(), which s2idle also runs for HDMI): + * a shown display is reported gone, a merged dual pipe stopped as a pair + * first (dcp_peer_stop_26_6(), as the pipe power-off does: a single-pipe + * teardown of a merged pair loops the firmware), the AV service + * disconnected, HPD dropped, the display released. The peer pipe of a + * pair has its owner stop the pair before its own link goes, whichever of + * the two prepares first. + * Unlike a cable unplug the Type-C route, its crossbar selection and the + * cable flag stay. A Type-C display under DPMS off has no link (its CRTC + * disable released it) and stays connected, as at runtime. Then the + * route's PHY is given back as a route deactivation does, and the fixed + * (HDMI) PHY, which probe powered for the life of the device, likewise. + * The next connect powers the route's PHY again (dcp_typec_phy_on()), + * dcp_hib_ext_relink() the fixed one. + */ +static void dcp_hib_release_ext_link(struct apple_dcp *dcp) +{ + struct platform_device *pdev = to_platform_device(dcp->dev); + struct apple_connector *con = READ_ONCE(dcp->connector); + bool typec = dcp_is_typec_output(dcp), shown, route_phy; + struct apple_dcp *owner; + int ret = 0; + + if (!dcp->fixed_phy && !READ_ONCE(dcp->active_typec_route)) + return; + + shown = con && READ_ONCE(con->connected) && READ_ONCE(con->dcp) == pdev && + !(typec && READ_ONCE(dcp->typec_crtc_off)); + if (shown) + disconnected_hpd_event(con); + /* A crashed session answers nothing: only the PHYs are given back. */ + if (READ_ONCE(dcp->crashed)) + goto phys; + scoped_guard(mutex, &dcp_peer_lock) + owner = dcp->peer_owner; + if (owner) + ret = dcp_peer_stop_26_6(owner); + if (ret >= 0) + ret = dcp_peer_stop_26_6(dcp); + if (ret < 0) + dev_warn(dcp->dev, "hibernation: dual-pipe pair not stopped: %d\n", ret); + else if (ret > 0) + dev_dbg(dcp->dev, "hibernation: dual-pipe pair stopped\n"); + ret = 0; + if (dcp->avep) + av_service_disconnect(dcp); + scoped_guard(mutex, &dcp->hpd_mutex) { + if (dptx_service_available(&dcp->dptxport[0]) && + dcp->dptxport[0].connected) + ret = dptxport_set_hpd(dcp->dptxport[0].service, false); + } + if (ret) + dev_warn(dcp->dev, "hibernation: DPTX HPD not dropped: %d\n", ret); + ret = dcp_dptx_disconnect(dcp, 0); + if (ret) + dev_warn(dcp->dev, "hibernation: display link not released: %d\n", ret); + if (!dcp->main_display) + dcp->desktop->ext_pipe_off = true; + if (typec) + reinit_completion(&dcp->typec_iomfb_hpd_ready); + +phys: + route_phy = dcp_typec_phy_release(dcp); + if (dcp->fixed_phy && !dcp->hib_fixed_phy_off) { + phy_power_off(dcp->fixed_phy); + phy_exit(dcp->fixed_phy); + dcp->hib_fixed_phy_off = true; + } + dev_dbg(dcp->dev, + "hibernation: display link released (display %s), DP PHY off: route %d, fixed %d\n", + shown ? "reported gone" : + (con && READ_ONCE(con->connected)) ? "kept (DPMS off)" : "none", + route_phy, dcp->hib_fixed_phy_off); +} + +/* The fixed PHY back on, as probe powers it (dcp_desktop_probe_routes()). */ +static void dcp_hib_fixed_phy_on(struct apple_dcp *dcp) +{ + int ret; + + if (!dcp->hib_fixed_phy_off) + return; + ret = phy_init(dcp->fixed_phy); + if (!ret) { + ret = phy_power_on(dcp->fixed_phy); + if (ret) + phy_exit(dcp->fixed_phy); + } + if (ret) { + /* + * Stays off: the device action at unbind must not power off a + * PHY that is not on. The HDMI output has no link then. + */ + dev_err(dcp->dev, "hibernation: fixed DP PHY not powered again: %d\n", + ret); + return; + } + dcp->hib_fixed_phy_off = false; + msleep(25); +} + +/* + * The dual-pipe pairing (dcp-peer-v26_6.inc) belongs to the two firmware + * sessions: both restart, and the next link training of the wide display + * reserves its peer again. peer_unbinding is the component's, kept. + */ +static void dcp_hib_peer_reset(struct apple_dcp *dcp) +{ + struct apple_dcp *peer, *owner; + + guard(mutex)(&dcp_peer_lock); + peer = dcp->peer_reserved; + owner = dcp->peer_owner; + if (peer || owner) + dev_dbg(dcp->dev, "hibernation restore: dual-pipe pairing with %s dropped\n", + dev_name((peer ?: owner)->dev)); + if (peer) { + peer->peer_owner = NULL; + memset(&peer->peer_tiling, 0, sizeof(peer->peer_tiling)); + peer->peer_complete_logged = false; + } + if (owner) { + owner->peer_reserved = NULL; + owner->peer_active = false; + memset(&owner->peer_tiling, 0, sizeof(owner->peer_tiling)); + } + dcp->peer_reserved = NULL; + dcp->peer_owner = NULL; + memset(&dcp->peer_tiling, 0, sizeof(dcp->peer_tiling)); + dcp->peer_active = false; + dcp->peer_failed = false; + dcp->peer_complete_logged = false; + WRITE_ONCE(dcp->peer_starved, false); +} + +/* + * The external processor's part of the old session, after dcp_hib_quiesce(): + * the endpoints its start brought up beside the panel's, the DPTX ports + * (so that the new firmware's port services bind: dptx_service_bind() + * refuses a port that still has one), the HDR service, the mode list (as + * at probe, so that the IOMFB start does not report the display connected + * from it), and the display, reported gone. + */ +static void dcp_hib_quiesce_ext(struct apple_dcp *dcp) +{ + struct platform_device *pdev = to_platform_device(dcp->dev); + struct apple_connector *con = READ_ONCE(dcp->connector); + struct dcp_desktop_state *d = dcp->desktop; + unsigned long flags; + bool shown; + int i; + + dcp_hib_stop_ext_link_work(dcp); + + /* + * Shown: report it gone now, as an unplug. A Type-C display whose + * CRTC is off (DPMS) stays connected, as it does at runtime: the wake + * connects its link (dcp_poweron()). + */ + shown = con && READ_ONCE(con->connected) && READ_ONCE(con->dcp) == pdev && + !(dcp_is_typec_output(dcp) && READ_ONCE(dcp->typec_crtc_off)); + if (shown) + disconnected_hpd_event(con); + + afk_quiesce(dcp->dptxep); + dcp->dptxep = NULL; + afk_quiesce(dcp->ibootep); + dcp->ibootep = NULL; + afk_quiesce(dcp->avep); + dcp->avep = NULL; + if (dcp->dcpavservep) { + afk_quiesce(dcp->dcpavservep); + dpavservep_detach(dcp); + dcp->dcpavservep = NULL; + } + + scoped_guard(mutex, &dcp->hpd_mutex) { + for (i = 0; i < ARRAY_SIZE(dcp->dptxport); i++) { + struct dptx_port *port = &dcp->dptxport[i]; + + /* Pairs with dptx_service_available(): no reader uses the old service. */ + smp_store_release(&port->enabled, false); + WRITE_ONCE(port->connected, false); + WRITE_ONCE(port->closed, false); + WRITE_ONCE(port->tile_hint, false); + port->service = NULL; + reinit_completion(&port->enable_completion); + reinit_completion(&port->linkcfg_completion); + } + WRITE_ONCE(dcp->typec_poweron_hpd, false); + } + reinit_completion(&dcp->typec_iomfb_hpd_ready); + dcp_180hz_invalidate(dcp); + + if (dcp->avep) + av_service_disconnect(dcp); + dcp_hdr_metadata_forget(dcp); + + /* No modes until the new firmware describes the display. */ + scoped_guard(mutex, &dcp->modes_lock) { + dcp->modes_generation++; + dcp->modes_admitted = false; + dcp->modes_provisional = false; + /* The replaced array is retained, as for dcp_modes_replace(). */ + spin_lock_irqsave(&dcp->metadata.lock, flags); + dcp->modes = NULL; + dcp->nr_modes = 0; + spin_unlock_irqrestore(&dcp->metadata.lock, flags); + } + + /* The new firmware has the pipe off, as after an unplug. */ + d->ext_pipe_off = true; + dcp_hib_peer_reset(dcp); + + dev_dbg(dcp->dev, + "hibernation restore: external session dropped: route %s, cable %d, display %s\n", + READ_ONCE(dcp->active_typec_route) ? "Type-C" : + dcp->fixed_phy ? "fixed" : "none", + READ_ONCE(dcp->typec_cable_connected), + shown ? "reported gone" : + (con && READ_ONCE(con->connected)) ? "kept (DPMS off)" : "none"); +} + +/* Commits that started before the locks were taken finish first. */ +static void dcp_hib_wait_commits(struct drm_crtc *crtc) +{ + struct drm_crtc_commit *commit; + + spin_lock(&crtc->commit_lock); + commit = list_first_entry_or_null(&crtc->commit_list, + struct drm_crtc_commit, commit_entry); + if (commit) + drm_crtc_commit_get(commit); + spin_unlock(&crtc->commit_lock); + if (!commit) + return; + if (!wait_for_completion_timeout(&commit->cleanup_done, 10 * HZ)) + dev_warn(crtc->dev->dev, + "hibernation restore: earlier commit did not finish\n"); + drm_crtc_commit_put(commit); +} + +/* + * Power the pipe on and commit the current state of the CRTC with a mode + * set and its planes: the firmware gets the mode and the frame, and the + * compositor's next flip goes to the new session. A CRTC switched off by + * soft DPMS gets the pipe back with the backlight off; its enable sets the + * mode. + */ +static int dcp_hib_recommit(struct apple_dcp *dcp) +{ + struct apple_crtc *acrtc = READ_ONCE(dcp->crtc); + struct drm_modeset_acquire_ctx ctx; + struct drm_atomic_commit *state; + struct drm_crtc_state *cs; + struct drm_crtc *crtc; + bool powered = false; + int ret; + + if (!acrtc) { + /* No DRM pipeline: nothing to set, the firmware is up. */ + WRITE_ONCE(dcp->hib_phase, DCP_HIB_NONE); + return 0; + } + crtc = &acrtc->base; + + DRM_MODESET_LOCK_ALL_BEGIN(crtc->dev, ctx, 0, ret); + dcp_hib_wait_commits(crtc); + + if (!crtc->state->active) { + if (!dcp_uses_soft_dpms(dcp)) { + /* dcp_poweron() powers the pipe on the enable. */ + WRITE_ONCE(dcp->hib_phase, DCP_HIB_NONE); + goto unlock; + } + if (!powered) { + iomfb_poweron_v26_6_desktop(dcp); + powered = true; + } + if (READ_ONCE(dcp->crashed) || dcp->desktop->poweron_result) { + ret = -EIO; + goto unlock; + } + WRITE_ONCE(dcp->hib_phase, DCP_HIB_NONE); + ret = dcp_backlight_dpms(dcp, false); + if (ret) + dev_warn(dcp->dev, + "hibernation restore: backlight blank unavailable: %d\n", + ret); + ret = 0; + dev_dbg(dcp->dev, + "hibernation restore: CRTC off, pipe powered, mode set on enable\n"); + goto unlock; + } + + if (!powered) { + iomfb_poweron_v26_6_desktop(dcp); + powered = true; + } + if (READ_ONCE(dcp->crashed) || dcp->desktop->poweron_result) { + ret = -EIO; + goto unlock; + } + + state = drm_atomic_commit_alloc(crtc->dev); + if (!state) { + ret = -ENOMEM; + goto unlock; + } + state->acquire_ctx = &ctx; + cs = drm_atomic_get_crtc_state(state, crtc); + if (IS_ERR(cs)) { + ret = PTR_ERR(cs); + goto put; + } + /* The same mode, set again on a firmware that has none. */ + cs->mode_changed = true; + ret = drm_atomic_add_affected_connectors(state, crtc); + if (!ret) + ret = drm_atomic_add_affected_planes(state, crtc); + if (ret) + goto put; + + WRITE_ONCE(dcp->hib_phase, DCP_HIB_NONE); + ret = drm_atomic_commit(state); + if (!ret) + dev_dbg(dcp->dev, + "hibernation restore: mode " DRM_MODE_FMT " committed, valid %d\n", + DRM_MODE_ARG(&cs->mode), + READ_ONCE(dcp->mode_state.valid)); + else if (ret != -EDEADLK) + WRITE_ONCE(dcp->hib_phase, DCP_HIB_RESTARTING); +put: + drm_atomic_commit_put(state); +unlock: + if (ret == -EDEADLK) + WRITE_ONCE(dcp->hib_phase, DCP_HIB_RESTARTING); + DRM_MODESET_LOCK_ALL_END(crtc->dev, ctx, ret); + return ret; +} + +static void dcp_hib_give_up(struct apple_dcp *dcp, const char *step, int ret) +{ + dev_err(dcp->dev, + "hibernation restore: firmware restart failed at %s (%d). Display left to the boot loader, IOMFB traffic stopped\n", + step, ret); + WRITE_ONCE(dcp->hib_phase, DCP_HIB_FAILED); + WRITE_ONCE(dcp->ext_dead, true); + if (READ_ONCE(dcp->crtc)) + schedule_work(&dcp->vblank_wq); + /* A display processor waiting for this one goes on without it. */ + dcp_hib_ext_put(dcp, true, true); +} + +/* A display is attached: a Type-C route is claimed, or HDMI HPD is high. */ +static bool dcp_hib_ext_has_display(struct apple_dcp *dcp) +{ + return READ_ONCE(dcp->active_typec_route) || + (dcp->hdmi_hpd && gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0); +} + +/* + * The link set up again as at probe and after s2idle, see the overview + * above. The HPD interrupt that dcp_enable_dp2hdmi_hpd() enables was + * disabled at freeze, or at restore. + */ +static void dcp_fixed_phy_up(struct apple_dcp *dcp); +static bool dcp_fixed_hdmi(struct apple_dcp *dcp); + +static void dcp_hib_ext_relink(struct apple_dcp *dcp) +{ + bool plug; + + dcp->hib_link_released = false; + /* + * Taken down at .freeze by the T6040 sleep's stop (dcp_ext_link_down()): the + * fixed HDMI output's DP PHY and converter rail are off, and the output is held + * relinking, which keeps every power-on away. Come back as after that sleep + * (dcp_ext_link_work()): the PHY and the converter up before the link, and the + * output released once the firmware reports the display plugged, or never does. + */ + if (READ_ONCE(dcp->ext_relinking)) { + if (dcp->fixed_phy_off) + dcp_fixed_phy_up(dcp); + plug = dcp_is_typec_output(dcp) && READ_ONCE(dcp->typec_cable_connected); + if (!plug && dcp_fixed_hdmi(dcp) && !READ_ONCE(dcp->hdmi_yielded) && + gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0) + plug = true; + WRITE_ONCE(dcp->ext_plug_wait, plug); + if (dcp->hib_typec_disabled) { + dcp->hib_typec_disabled = false; + dcp_enable_typec_work(dcp); + } + dcp_start_desktop_ext_link(dcp); + if (dcp->hdmi_hpd_irq && !dcp->hib_irq_disabled) + disable_irq(dcp->hdmi_hpd_irq); + dcp->hib_irq_disabled = false; + dcp_enable_dp2hdmi_hpd(dcp); + if (plug) + mod_delayed_work(system_dfl_wq, &dcp->ext_plug_wq, + msecs_to_jiffies(DCP_S2R_PLUG_MS)); + else + WRITE_ONCE(dcp->ext_relinking, false); + return; + } + /* + * The HDMI converter is powered through SMC GPIOs, which the cold boot + * of a resume from disk turned off behind the restored kernel's back: + * without them its HPD stays low and no plug is ever seen. Power it as + * probe did, and let the rails settle before the link (as the T6030 + * output set-up does). + */ + if (dcp->hdmi_pwren || dcp->dp2hdmi_pwren) { + if (dcp->hdmi_pwren) + gpiod_set_value_cansleep(dcp->hdmi_pwren, 1); + if (dcp->dp2hdmi_pwren) + gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 1); + msleep(100); + dev_dbg(dcp->dev, "hibernation: HDMI converter powered again\n"); + } + dcp_hib_fixed_phy_on(dcp); + if (dcp->hib_typec_disabled) { + dcp->hib_typec_disabled = false; + dcp_enable_typec_work(dcp); + } + dcp_start_desktop_ext_link(dcp); + if (dcp->hdmi_hpd_irq && !dcp->hib_irq_disabled) + disable_irq(dcp->hdmi_hpd_irq); + dcp->hib_irq_disabled = false; + dcp_enable_dp2hdmi_hpd(dcp); +} + +/* + * The link connected again in the order the dual-pipe pairing needs: a + * processor without a display at once, one with a display once every + * external processor's firmware runs and every idle one is done (see the + * overview above). After the restart in the restored kernel, or, in the + * kernel that hibernated, after a hibernation that failed or a disk=suspend + * wake (PM_POST_HIBERNATION: every DCP is thawed, userspace runs). + */ +static void dcp_hib_ext_link_up(struct apple_dcp *dcp, const char *when) +{ + bool display; + + /* + * The HDMI port's converter, off since the T6040 sleep's stop at .freeze, shows its + * sink on HPD only once powered: power it before asking whether a display is there. + */ + if (READ_ONCE(dcp->ext_relinking) && dcp->fixed_phy_off) + dcp_fixed_phy_up(dcp); + display = dcp_hib_ext_has_display(dcp); + + dcp_hib_ext_put(dcp, true, display); + { + ktime_t link_start = ktime_get(); + + if (display && + !wait_event_timeout(dcp_hib_ext_wq, dcp_hib_ext_settled(), + DCP_HIB_READY_TIMEOUT)) + dev_warn(dcp->dev, + "hibernation %s: other display processors not up after 10 s (%d starting, %d idle), connecting anyway\n", + when, atomic_read(&dcp_hib_ext_starting), + atomic_read(&dcp_hib_ext_idle)); + + dcp_hib_ext_relink(dcp); + dcp_hib_ext_put(dcp, false, true); + dev_info(dcp->dev, + "hibernation %s: external link replayed in %lld ms (display %d)\n", + when, ktime_ms_delta(ktime_get(), link_start), display); + } +} + +/* + * After dcp_start_desktop(): dcp_wait_ready() without its link step, the + * DRM entry points opened, then the link (dcp_hib_ext_link_up()). + */ +static void dcp_hib_ext_restore(struct apple_dcp *dcp) +{ + unsigned long left; + + left = wait_for_completion_timeout(&dcp->start_done, DCP_HIB_READY_TIMEOUT); + if (!left || READ_ONCE(dcp->crashed) || !READ_ONCE(dcp->active)) { + dcp_hib_give_up(dcp, "iomfb-ready", left ? -ENODEV : -ETIMEDOUT); + return; + } + dev_dbg(dcp->dev, + "hibernation restore: external firmware session up, endpoints %#010x, DPTX ports %d/%d\n", + dcp->desktop->graph_started, + dptx_service_available(&dcp->dptxport[0]), + dptx_service_available(&dcp->dptxport[1])); + + WRITE_ONCE(dcp->hib_phase, DCP_HIB_NONE); + dcp_hib_ext_link_up(dcp, "restore"); +} + +/* + * The DARTs of a DCP across a hibernation. The restoring boot's loader locks + * them again with fresh firmware roots and drives the display through them + * until this DCP starts its firmware again; their registers are not this + * kernel's to touch before that, and a display DART only needs programming + * at its display's power-up anyway. So their .restore is deferred at .freeze + * (apple_dart_display_unpowered()) and run where the firmware restarts + * (dcp_hib_restore_work()); a DCP whose display stays with the loader leaves + * them so. .thaw, the kernel that hibernated going on, only clears the mark. + */ +static void dcp_hib_darts(struct apple_dcp *dcp, bool defer) +{ + struct device_node *piodma; + struct device *darts[2]; + int i, ret; + + piodma = of_get_child_by_name(dcp->dev->of_node, "piodma"); + darts[0] = piodma ? dcp_s2r_find_dart(piodma) : NULL; + of_node_put(piodma); + darts[1] = dcp_s2r_find_dart(dcp->dev->of_node); + + for (i = 0; i < ARRAY_SIZE(darts); i++) { + if (!darts[i]) + continue; + if (defer) { + apple_dart_display_unpowered(darts[i]); + } else { + ret = apple_dart_display_restore(darts[i]); + if (ret) + dev_warn(dcp->dev, + "hibernation: restore of %s failed: %d\n", + dev_name(darts[i]), ret); + } + put_device(darts[i]); + } +} + +static void dcp_hib_restore_work(struct work_struct *work) +{ + struct apple_dcp *dcp = container_of(work, struct apple_dcp, + hib_restore_work); + struct platform_device *pdev = to_platform_device(dcp->dev); + u32 cpu_ctrl; + int ret; + + /* The kernel that hibernated: the hibernation failed, or disk=suspend woke. */ + if (READ_ONCE(dcp->hib_phase) == DCP_HIB_NONE && dcp->hib_link_released && + !READ_ONCE(dcp->ext_dead)) { + dcp_hib_ext_link_up(dcp, "aborted"); + return; + } + if (READ_ONCE(dcp->hib_phase) != DCP_HIB_QUIESCED) { + dcp_hib_ext_put(dcp, true, true); + return; + } + + dcp_hib_log_coproc(dcp, "firmware restart"); + /* Before the firmware's first DMA: the .restore deferred at .freeze. */ + dcp_hib_darts(dcp, false); + cpu_ctrl = dcp_coproc_assert_run(dcp); + if (!(cpu_ctrl & APPLE_DCP_COPROC_CPU_CONTROL_RUN)) + dcp_hib_log_coproc(dcp, "CPU was halted, RUN asserted"); + + WRITE_ONCE(dcp->hib_phase, DCP_HIB_RESTARTING); + WRITE_ONCE(dcp->crashed, false); + ret = apple_rtkit_reinit(dcp->rtk); + /* Balances the hold at freeze; the new session reads the queued HELLO. */ + if (dcp->hib_rx_held) { + dcp->hib_rx_held = false; + apple_rtkit_resume_rx(dcp->rtk); + } + if (ret) { + dcp_hib_give_up(dcp, "rtkit-reinit", ret); + return; + } + + /* The firmware-facing start of probe (RTKit wake through set_shmem). */ + init_completion(&dcp->start_done); + ret = dcp_start_desktop(dcp); + if (ret) { + dcp_hib_give_up(dcp, "start", ret); + return; + } + if (dcp_desktop_external(dcp)) { + dcp_hib_ext_restore(dcp); + return; + } + ret = dcp_wait_ready(pdev, DCP_HIB_READY_TIMEOUT); + if (ret) { + dcp_hib_give_up(dcp, "iomfb-ready", ret); + return; + } + dev_dbg(dcp->dev, + "hibernation restore: firmware session up, endpoints %#010x, main display %d\n", + dcp->desktop->graph_started, dcp->main_display); + + ret = dcp_hib_recommit(dcp); + if (ret) { + dcp_hib_give_up(dcp, "modeset", ret); + return; + } + dev_dbg(dcp->dev, "hibernation restore: display restored\n"); +} + +/* + * The firmware restart waits for PM_POST_HIBERNATION: the PMP is rebuilt by + * its own notifier (priority 10, pmp-export.c), and this one runs after it. + * PM_POST_RESTORE: a restore through the snapshot device. In the kernel + * that hibernated, PM_POST_HIBERNATION comes only after a failure or a + * disk=suspend wake: the link given back at prepare is replayed then. + * Before the next system sleep the restart work has finished. + */ +static int dcp_hib_pm_notify(struct notifier_block *nb, unsigned long action, + void *unused) +{ + struct apple_dcp *dcp = container_of(nb, struct apple_dcp, hib_nb); + + switch (action) { + case PM_HIBERNATION_PREPARE: + case PM_SUSPEND_PREPARE: + flush_work(&dcp->hib_restore_work); + break; + case PM_POST_HIBERNATION: + case PM_POST_RESTORE: + if (READ_ONCE(dcp->hib_phase) == DCP_HIB_QUIESCED || + (READ_ONCE(dcp->hib_phase) == DCP_HIB_NONE && + dcp->hib_link_released)) + queue_work(system_long_wq, &dcp->hib_restore_work); + break; + } + return NOTIFY_DONE; +} + +/* + * Hibernation prepare (dpm_prepare(), before any freeze callback and before + * the kernel threads freeze; every DCP's mailbox is live): an external + * processor stops its link work and gives back its link and DP PHYs. The + * PM_HIBERNATION_PREPARE notifier set dcp_hib_in_progress; s2idle never + * gets here. The second prepare, for the power-off, finds it done. + */ +static int dcp_hib_prepare(struct apple_dcp *dcp) +{ + if (!dcp || dcp_takeover_was_aborted(dcp) || READ_ONCE(dcp->ext_dead)) + return 0; + if (dcp_hib_busy(dcp)) { + dev_warn(dcp->dev, + "refusing hibernation: firmware restart after the last resume still running\n"); + return -EBUSY; + } + /* Taken down at .freeze with the sleep's stop instead (apple_platform_freeze()). */ + if (dcp_t6041_hib_capable()) + return 0; + if (!dcp_hib_can_restart(dcp) || !dcp_desktop_external(dcp)) + return 0; + dcp_hib_stop_ext_link_work(dcp); + if (!dcp->hib_link_released) { + dcp_hib_release_ext_link(dcp); + dcp->hib_link_released = true; + } + /* Its relink is waited for by the processors with a display. */ + if (!dcp->hib_ext_idle_pending) { + dcp->hib_ext_idle_pending = true; + atomic_inc(&dcp_hib_ext_idle); + } + return 0; +} + +static void dcp_hib_release(void *data) +{ + struct apple_dcp *dcp = data; + + unregister_pm_notifier(&dcp->hib_nb); + cancel_work_sync(&dcp->hib_restore_work); + dcp_hib_ext_put(dcp, true, true); +} + +static int dcp_hib_register(struct apple_dcp *dcp) +{ + int ret; + + if (dcp->hib_nb_registered) + return 0; + dcp->hib_nb.notifier_call = dcp_hib_pm_notify; + dcp->hib_nb.priority = -5; /* after PMP (10), before the GPU drain (-10) */ + ret = register_pm_notifier(&dcp->hib_nb); + if (ret) + return ret; + ret = devm_add_action_or_reset(dcp->dev, dcp_hib_release, dcp); + if (ret) + return ret; + dcp->hib_nb_registered = true; + return 0; +} + +/* + * The old firmware session dropped on the host side for the restart after + * PM_POST_HIBERNATION (dcp_hib_restore_work()); @release_dma once the DARTs + * have restored their state. + */ +static int dcp_hib_drop_session(struct apple_dcp *dcp, bool release_dma) +{ + int ret = dcp_hib_register(dcp); + + if (ret) { + dev_err(dcp->dev, "hibernation restore: no PM notifier (%d)\n", ret); + return ret; + } + dcp_hib_quiesce(dcp); + if (dcp_desktop_external(dcp)) { + dcp_hib_quiesce_ext(dcp); + dcp->hib_ext_start_pending = true; + atomic_inc(&dcp_hib_ext_starting); + /* Counted at prepare, in the image, unless prepare did not run. */ + if (!dcp->hib_ext_idle_pending) { + dcp->hib_ext_idle_pending = true; + atomic_inc(&dcp_hib_ext_idle); + } + } + if (release_dma) + dcp_hib_release_dma(dcp); + dev_dbg(dcp->dev, + "hibernation restore: old firmware session dropped; restart after PM_POST_HIBERNATION\n"); + return 0; +} + +static int dcp_platform_freeze(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + + /* The T8132 power-down keeps a retained session that no image can carry. */ + if (iomfb_is_m4(dcp)) + return -EBUSY; + if (dcp_takeover_was_aborted(dcp) || READ_ONCE(dcp->ext_dead)) + return 0; + if (dcp->external) { + int ret = dcp_platform_suspend(dev); + + /* + * The boot loader relocks these DARTs for the restore boot. + * Mark them so .restore defers reimport until this DCP's + * power-up (dcp_hib_darts() / apple_dart_display_restore()). + */ + dcp_hib_darts(dcp, true); + return ret; + } + /* PM_HIBERNATION_PREPARE flushed it; a restart still running is refused. */ + if (dcp_hib_busy(dcp)) + return -EBUSY; + /* Done at prepare (dcp_hib_prepare()); a no-op then. */ + if (dcp_hib_can_restart(dcp) && dcp_desktop_external(dcp)) + dcp_hib_stop_ext_link_work(dcp); + if (dcp_hib_can_restart(dcp) && !READ_ONCE(dcp->crashed) && + !dcp->hib_rx_held) { + apple_rtkit_hold_rx(dcp->rtk); + apple_rtkit_flush_rx(dcp->rtk); + dcp->hib_rx_held = true; + } else if (!dcp_hib_can_restart(dcp) && dcp->hw.adopt_live_session) { + dcp_hold_for_sleep(dcp); + if (dcp->rx_held) + apple_rtkit_flush_rx(dcp->rtk); + } + dcp_hib_darts(dcp, true); + return 0; +} + +/* + * After the image is written. Remembered so that a .restore in this same + * kernel (the power-off failed) is told apart from one in the restored + * kernel, whose image was taken before this ran. + */ +static int dcp_platform_poweroff(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + + dcp->hib_poweroff_entered = true; + return dcp_platform_freeze(dev); +} + +static int dcp_platform_thaw(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + + dcp->hib_poweroff_entered = false; + /* The image is written, or hibernation failed: the firmware ran on. */ + dcp_hib_darts(dcp, false); + if (dcp->hib_rx_held) { + dcp->hib_rx_held = false; + apple_rtkit_resume_rx(dcp->rtk); + } + dcp_release_after_sleep(dcp); + if (dcp_takeover_was_aborted(dcp) || READ_ONCE(dcp->ext_dead)) + return 0; + /* + * An external processor's link stays given back while the image is + * written: PM_POST_HIBERNATION replays it if this kernel goes on. + */ + if (dcp->external) + return dcp_platform_resume(dev); + return 0; +} + +/* + * External processors drop their old session before any .restore: the + * Type-C port controllers' .restore may report their mode again + * (dcp_typec_route_set()), and every firmware call from there must fail + * at once on the quiesced endpoints rather than wait on a session that is + * gone. The panel keeps its .restore (dcp_platform_restore()). + */ +static int dcp_platform_restore_early(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + + /* The power-off failed, or an in-place test_resume kept firmware live: .restore thaws. */ + if (!dcp || dcp->hib_poweroff_entered || !pm_hibernate_restored_cold()) + return 0; + if (dcp_takeover_was_aborted(dcp) || READ_ONCE(dcp->ext_dead) || + !dcp_desktop_external(dcp) || !dcp_hib_can_restart(dcp) || + READ_ONCE(dcp->hib_phase) != DCP_HIB_NONE) + return 0; + + dcp_hib_log_coproc(dcp, "entry"); + if (!dcp->hib_rx_held) + dev_warn(dev, + "hibernation restore: RTKit receive was not held in the image\n"); + /* Host side only: the DMA of the old session goes in .restore. */ + dcp_hib_drop_session(dcp, false); + return 0; +} + +static int dcp_platform_restore(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + + /* The power-off failed: the firmware ran on, as after a thaw. */ + if (dcp->hib_poweroff_entered) { + dcp->hib_poweroff_entered = false; + dev_warn(dev, "hibernation power-off failed: firmware session kept\n"); + return dcp_platform_thaw(dev); + } + + if (dcp_takeover_was_aborted(dcp) || READ_ONCE(dcp->ext_dead)) + return 0; + /* Dropped at restore_early (dcp_platform_restore_early()); its DMA now. */ + if (dcp_desktop_external(dcp) && + READ_ONCE(dcp->hib_phase) == DCP_HIB_QUIESCED) { + dcp_hib_release_dma(dcp); + return 0; + } + + /* In-place test_resume without a cold boot: the firmware never restarted. */ + if (!pm_hibernate_restored_cold() && !dcp_hib_can_restart(dcp)) + return dcp_platform_thaw(dev); + + if (dcp_hib_can_restart(dcp) && !dcp_desktop_external(dcp)) { + dcp_hib_log_coproc(dcp, "entry"); + if (!dcp->hib_rx_held) + dev_warn(dev, + "hibernation restore: RTKit receive was not held in the image\n"); + if (!dcp_hib_drop_session(dcp, true)) + return 0; + } + + if (READ_ONCE(dcp->retain_dma) || dcp->hw.adopt_live_session) + dev_err(dev, + "hibernation restore: the DCP firmware was restarted by the boot loader; its session was pinned for this boot and cannot be re-adopted without a reboot. Display left to the boot loader, IOMFB traffic stopped\n"); + else + dev_err(dev, + "hibernation restore: the DCP firmware was restarted by the boot loader and in-place re-adoption is not implemented for this processor. Display left to the boot loader, IOMFB traffic stopped\n"); + + WRITE_ONCE(dcp->crashed, true); + WRITE_ONCE(dcp->ext_dead, true); + return 0; +} +#endif + +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), + .resume = pm_sleep_ptr(dcp_platform_resume), +#ifdef CONFIG_HIBERNATION + .freeze = dcp_platform_freeze, + .thaw = dcp_platform_thaw, + .poweroff = dcp_platform_poweroff, + .restore_early = dcp_platform_restore_early, + .restore = dcp_platform_restore, +#else + .freeze = pm_sleep_ptr(dcp_platform_suspend), + .thaw = pm_sleep_ptr(dcp_platform_resume), + .poweroff = pm_sleep_ptr(dcp_platform_suspend), + .restore = pm_sleep_ptr(dcp_platform_resume), +#endif +}; + +static const struct apple_dcp_hw_data apple_dcp_hw_t6020 = { + .num_dptx_ports = 1, + .t6020_tunnel_flow = true, + .s2r = true, + .s2r_untested = true, + .s2r_no_secure_port = true, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, + .s2r_layout = &dcp_s2r_t6020, +}; + +static const struct apple_dcp_hw_data apple_dcp_hw_t6020_dcpext = { + .external_processor = true, + .num_dptx_ports = 2, + .t6020_tunnel_flow = true, + .s2r_ext = true, + .s2r_untested = true, + .s2r_no_secure_port = true, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, + .s2r_layout = &dcp_s2r_t6020_ext[0], +}; + +static const struct apple_dcp_hw_data apple_dcp_hw_t8112 = { + .num_dptx_ports = 2, + .s2r = true, + .s2r_no_secure_port = true, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, + .s2r_layout = &dcp_s2r_t8112, +}; + +static const struct apple_dcp_hw_data apple_dcp_hw_t8112_dcpext = { + .num_dptx_ports = 2, + .s2r_ext = true, + .s2r_no_secure_port = true, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, + .s2r_layout = &dcp_s2r_t8112_ext, +}; + +/* The internal T8140 endpoint uses the H17P method profile. */ +static const struct resource t8140_firmware_clock = + DEFINE_RES_MEM(0x302800000, 0xbc000); + +static const struct apple_dcp_hw_data apple_dcp_hw_t8140 = { + .num_dptx_ports = 0, + .adopt_live_session = true, + .firmware_compat = DCP_FIRMWARE_H17P, + .firmware_clock = &t8140_firmware_clock, + .firmware_display_windows = 5, + .firmware_scratch = 0x20000, + .firmware_request = 0x68000, + .s2r = true, + .s2r_layout = &dcp_s2r_t8140, +}; + +/* Separate from the established internal-panel H17P profile. */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8140_external = { + .external_processor = true, + .num_dptx_ports = 1, + .iomfb_method_profile = DCP_IOMFB_METHODS_H17P_EXTERNAL, + .adopt_live_session = false, + .firmware_compat = DCP_FIRMWARE_H17P, + .firmware_clock = &t8140_firmware_clock, + .firmware_display_windows = 4, + /* Native PMGR BWR agent 2 and boost agent 3 for DISPEXT0. */ + .firmware_scratch = 0x28000, + .firmware_request = 0x70000, + .s2r_ext = true, +}; + +/* + * M5 (T8142) runs H17-generation DCP firmware with the H17G method numbering + * and is left running by the bootloader. + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8142 = { + .num_dptx_ports = 0, + .iomfb_method_profile = DCP_IOMFB_METHODS_H17G, + .adopt_live_session = true, + .firmware_compat = DCP_FIRMWARE_H17P, + /* Firmware 27.0's sleep calls (iomfb_v27.c), unless appledrm.s2r_untested=0 */ + .s2r = true, + .s2r_untested = true, + .s2r_no_secure_port = true, + .s2r_layout = &dcp_s2r_t8142, +}; + +/* T8103's DCP: the firmware stop around DPMS off and system sleep, with its own power words */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8103 = { + .num_dptx_ports = 0, + .s2r = true, + .s2r_no_secure_port = true, + .s2r_layout = &dcp_s2r_t8103, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, +}; + +/* T8103's external DCP: maps register windows through its DART and stops/restarts across S2R */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8103_dcpext = { + .num_dptx_ports = 2, + .s2r_ext = true, + .s2r_no_secure_port = true, + .s2r_layout = &dcp_s2r_t8103_ext, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, +}; + +static const struct apple_dcp_hw_data apple_dcp_hw_dcp = { + .num_dptx_ports = 0, +}; + +static const struct apple_dcp_hw_data apple_dcp_hw_t6030 = { + .iboot_handoff = "apple,t6030-handoff", + .num_dptx_ports = 1, + .afk_name_fallback = true, + /* Firmware 27.2's sleep: only with the DT's sleep arguments and display power words */ + .v27_early_stop = true, .s2r_layout = &dcp_s2r_t6030, /* Firmware 27: the boot timing only, as on T6050, see dcp_mode_settable(). */ .only_120hz_modes = true, @@ -14665,6 +16011,7 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext = { static const struct apple_dcp_hw_data apple_dcp_hw_t6041 = { .iboot_handoff = "apple,t6041-handoff", .num_dptx_ports = 2, + .ready_timeout_ms = 10000, .afk_name_fallback = true, }; @@ -14805,7 +16152,7 @@ static struct platform_driver apple_platform_driver = { /* * T6041 suspend-to-RAM: each display firmware is stopped from Linux before the sleep, from the * display subsystem's own suspend, and the internal one is restarted warm after the wake. On - * T6040 the external ones are restarted too (dcp_t6040_ext_start_one()). + * T6040 the external ones are restarted too (dcp_ext_start_one()). */ static int dcp_stop_poller(void *data) { @@ -14823,28 +16170,22 @@ static int dcp_t6041_recommit_planes(struct apple_dcp *dcp); * T6040: the most to wait for the firmware's D572(0) after the power-off. Its internal DCP * doesn't always send it, and its external ones' streams go off here as well. */ -#define DCP_T6040_D572_MS 100 -/* - * The longest an external display's link work waits for the firmware to report the display - * plugged after the restart. On the J616s that came 1.0 s after the link request for a Type-C - * display and 6.1 s after it for a TV behind the HDMI port's converter (6.9 s at boot). - */ -#define DCP_S2R_PLUG_MS 10000 +#define DCP_EXT_D572_MS 100 /* * T6040 (apple,t6040-display-power): its sleep takes the external links down and back, its - * external DCPs being restarted after the wake as the internal one (dcp_t6040_ext_start_one()). + * external DCPs being restarted after the wake as the internal one (dcp_ext_start_one()). * On T6041 they are shut down and stay off. */ -bool dcp_t6040_relinks(void) +bool dcp_ext_relinks(void) { struct apple_dcp *host = READ_ONCE(dcp_t6041_host); - return host && host->t6041_power.t6040; + return host && host->t6041_power.relink_ext; } /* The fixed HDMI output of a T6040 external DCP, not lent to a Type-C display. */ -static bool dcp_t6040_fixed_hdmi(struct apple_dcp *dcp) +static bool dcp_fixed_hdmi(struct apple_dcp *dcp) { return dcp_desktop_external(dcp) && dcp->fixed_phy && dcp->hdmi_hpd && !dcp->active_typec_route; @@ -14858,9 +16199,9 @@ static bool dcp_t6040_fixed_hdmi(struct apple_dcp *dcp) * alone; the firmware's hotplug once the link is back has the CRTC state that DRM kept active * applied again (dcp_hotplug()). */ -static void dcp_t6040_ext_link_down(struct apple_dcp *dcp) +static void dcp_ext_link_down(struct apple_dcp *dcp) { - WRITE_ONCE(dcp->t6040_relinking, true); + WRITE_ONCE(dcp->ext_relinking, true); dcp_disable_typec_work(dcp, false); if (dcp->avep) av_service_disconnect(dcp); @@ -14873,7 +16214,7 @@ static void dcp_t6040_ext_link_down(struct apple_dcp *dcp) if (dcp->hdmi_hpd_irq && dcp->active_typec_route) return; /* The fixed HDMI output: HPD dropped first, as at an unplug of the sink. */ - if (dcp_t6040_fixed_hdmi(dcp)) { + if (dcp_fixed_hdmi(dcp)) { int ret = 0; scoped_guard(mutex, &dcp->hpd_mutex) { @@ -14899,10 +16240,10 @@ static void dcp_t6040_ext_link_down(struct apple_dcp *dcp) */ if (dcp_is_typec_output(dcp) && dcp_typec_phy_release(dcp)) dev_dbg(dcp->dev, "Type-C DP PHY off for the sleep\n"); - if (dcp_t6040_fixed_hdmi(dcp) && !dcp->t6040_fixed_phy_off) { + if (dcp_fixed_hdmi(dcp) && !dcp->fixed_phy_off) { phy_power_off(dcp->fixed_phy); phy_exit(dcp->fixed_phy); - dcp->t6040_fixed_phy_off = true; + dcp->fixed_phy_off = true; if (dcp->dp2hdmi_pwren) gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 0); } @@ -14918,24 +16259,24 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi /* The display DART's streams turned off here, not by a D572(0). */ bool streams_off = false; bool idle_attempted = false; - bool t6040 = dcp_t6040_relinks(); + bool relink_ext = dcp_ext_relinks(); bool relink; u32 ctrl, status; int ret; /* T6040: a link still being set up after the last wake finishes first. */ - if (dcp && t6040) { - flush_work(&dcp->t6040_link_work); - /* The stop takes the link down again (dcp_t6040_ext_link_down()). */ - cancel_delayed_work_sync(&dcp->t6040_plug_wq); - WRITE_ONCE(dcp->t6040_plug_wait, false); + if (dcp && relink_ext) { + flush_work(&dcp->ext_link_work); + /* The stop takes the link down again (dcp_ext_link_down()). */ + cancel_delayed_work_sync(&dcp->ext_plug_wq); + WRITE_ONCE(dcp->ext_plug_wait, false); } /* dcp->external is only set on T6030. */ if (!dcp || IS_ERR_OR_NULL(dcp->rtk) || dcp->sleep_host_stop == external) return 0; dev = dcp->dev; /* T6040's external DCPs come back after the wake: stopped as the internal one. */ - relink = external && t6040; + relink = external && relink_ext; /* * An external DCP stopped for an earlier sleep stays down, with its domains forced off by * the power word step: reading its registers again hung the second sleep of a boot (11 Nov). @@ -14974,14 +16315,14 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi dcp_s2r_put_darts(dcp); return ret; } - if (t6040) { + if (relink_ext) { /* The firmware may send its D572(0) as early as during the drain. */ reinit_completion(&dcp->s2r_dart_done); WRITE_ONCE(dcp->s2r_active, true); } dcp_drain_for_sleep_opts(dcp, !dpms); if (relink) - dcp_t6040_ext_link_down(dcp); + dcp_ext_link_down(dcp); cancel_delayed_work_sync(&dcp->swap_watchdog_wq); iomfb_pause_presentation(dcp, true); iomfb_queue_settle(dcp, msecs_to_jiffies(500)); @@ -15015,7 +16356,7 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi * out. T6040 bounds its D572 wait and turns the streams off without it, so it * keeps its own path. */ - if (!t6040 && READ_ONCE(dcp->pipe_off)) { + if (!relink_ext && READ_ONCE(dcp->pipe_off)) { dev_info(dev, "display already off: no second power-off\n"); if (dcp->s2r_disp_dart) { streams_off = true; @@ -15026,11 +16367,11 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi goto err_unwind; } } else { - unsigned long d572 = msecs_to_jiffies(t6040 ? DCP_T6040_D572_MS : + unsigned long d572 = msecs_to_jiffies(relink_ext ? DCP_EXT_D572_MS : DCP_S2R_D572_TIMEOUT_MS); WRITE_ONCE(dcp->s2r_dart_err, 0); - if (!t6040) { + if (!relink_ext) { reinit_completion(&dcp->s2r_dart_done); WRITE_ONCE(dcp->s2r_active, true); } @@ -15045,7 +16386,7 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi _dcp_poweroff(dcp, false); } powered_off = true; - if (t6040) { + if (relink_ext) { if (iomfb_wait_channels_idle(dcp, 200)) dev_warn(dev, "display calls still in flight after the power-off\n"); @@ -15059,13 +16400,13 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi } if (!wait_for_completion_timeout(&dcp->s2r_dart_done, d572)) { dcp_s2r_dart_end(dcp); - if (!t6040) { + if (!relink_ext) { dev_err(dev, "no D572 after the power-off\n"); ret = -ETIMEDOUT; goto err_unwind; } dev_dbg(dev, "no D572(0) %u ms after the power-off\n", - DCP_T6040_D572_MS); + DCP_EXT_D572_MS); } dcp_s2r_dart_end(dcp); ret = READ_ONCE(dcp->s2r_dart_err); @@ -15078,14 +16419,14 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi * turns off only the layout's streams; an external DCP's are flushed as * well, as that DCP goes dark below. */ - if (t6040 && dcp->s2r_disp_dart) { + if (relink_ext && dcp->s2r_disp_dart) { apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, false, relink); streams_off = true; } } /* T6040: nothing may be in flight through them once their blocks go off. */ - if (t6040 && dcp->s2r_disp_dart) { + if (relink_ext && dcp->s2r_disp_dart) { ret = apple_dart_display_streams_idle(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS); if (ret) { @@ -15240,7 +16581,7 @@ static int dcp_t6041_stop_dev(struct apple_dcp *dcp, bool external, bool recommi if (relink) { dcp->t6041_ext_seen = false; /* Its link was taken down above: up again as after a wake. */ - queue_work(system_dfl_wq, &dcp->t6040_link_work); + queue_work(system_dfl_wq, &dcp->ext_link_work); } if (!external && powered_off) { if (dcp_t6041_display_poweron(dcp) || @@ -15626,7 +16967,29 @@ static int dcp_t6041_boot_ps_io(struct apple_dcp *dcp, bool restore) return 0; } -static int dcp_t6041_start_internal_hw(struct apple_dcp *dcp) +/* + * Through a boot (hibernation .restore, dcp_t6041_hib_restore()): the boot loader started the + * firmware anew, so it takes the new handshake after PM_POST_HIBERNATION instead of the + * sleep's warm return. + */ +static void dcp_t6041_hib_handshake(struct apple_dcp *dcp) +{ + WRITE_ONCE(dcp->s2r_fw_down, false); + iomfb_pause_presentation(dcp, false); +#ifdef CONFIG_HIBERNATION + if (dcp_hib_can_restart(dcp) && !dcp_hib_drop_session(dcp, true)) + return; +#endif + dev_err(dcp->dev, "hibernation restore: firmware started by the boot loader cannot be restarted: output stays off\n"); + WRITE_ONCE(dcp->crashed, true); + WRITE_ONCE(dcp->ext_dead, true); +} + +/* + * The internal display back up: the domains and DARTs as after a sleep, then the firmware's warm + * return, or (@cold, through a boot) the new handshake. + */ +static int dcp_t6041_start_internal_hw(struct apple_dcp *dcp, bool cold) { struct device *dev = dcp->dev; struct dcp_t6041_power *pwr; @@ -15636,7 +16999,7 @@ static int dcp_t6041_start_internal_hw(struct apple_dcp *dcp) u32 v, cur, to = 0; int ret, ps_ret; - KUNIT_STATIC_STUB_REDIRECT(dcp_t6041_start_internal_hw, dcp); + KUNIT_STATIC_STUB_REDIRECT(dcp_t6041_start_internal_hw, dcp, cold); if (!dcp || IS_ERR_OR_NULL(dcp->rtk) || !dcp->sleep_host_stop) return 0; pwr = &dcp->t6041_power; @@ -15704,6 +17067,10 @@ static int dcp_t6041_start_internal_hw(struct apple_dcp *dcp) dev_warn(dev, "display child domains not on after the sleep: %#x\n", to); dcp_s2r_find_darts(dcp); + if (dcp->s2r_disp_dart) + apple_dart_display_restore(dcp->s2r_disp_dart); + if (dcp->s2r_dcp_dart) + apple_dart_display_restore(dcp->s2r_dcp_dart); ret = 0; if (dcp->s2r_disp_dart) { apple_dart_display_keep(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, false); @@ -15724,6 +17091,11 @@ static int dcp_t6041_start_internal_hw(struct apple_dcp *dcp) WRITE_ONCE(dcp->crashed, false); WRITE_ONCE(dcp->ext_dead, false); + if (cold) { + WRITE_ONCE(dcp_t6041_internal_down, false); + dcp_t6041_hib_handshake(dcp); + return 0; + } ret = apple_rtkit_power_cycled_return(dcp->rtk, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); if (ret) { @@ -15753,7 +17125,7 @@ static int dcp_t6041_start_internal_hw(struct apple_dcp *dcp) return ret ?: ps_ret; } -static int dcp_t6041_internal_start_locked(struct apple_dcp *host) +static int dcp_t6041_internal_start_how(struct apple_dcp *host, bool cold) { int ret; @@ -15764,12 +17136,17 @@ static int dcp_t6041_internal_start_locked(struct apple_dcp *host) return 0; } - ret = dcp_t6041_start_internal_hw(host); + ret = dcp_t6041_start_internal_hw(host, cold); if (!ret || !READ_ONCE(dcp_t6041_internal_down)) host->dpms_powered_off = false; return ret; } +static int dcp_t6041_internal_start_locked(struct apple_dcp *host) +{ + return dcp_t6041_internal_start_how(host, false); +} + static bool dcp_t6041_internal_capable(struct apple_dcp *dcp) { return dcp && dcp->sleep_host_stop && @@ -15836,8 +17213,10 @@ static int dcp_t6041_internal_stop_locked(struct apple_dcp *host, bool dpms) return 0; } +/* @data: whether through a boot (bool *), as for dcp_t6041_start(). */ static int dcp_t6041_start_one(struct device *dev, void *data) { + bool cold = data && *(bool *)data; struct apple_dcp *dcp = dev_get_drvdata(dev); int ret, commit_ret = 0; @@ -15845,14 +17224,17 @@ static int dcp_t6041_start_one(struct device *dev, void *data) return 0; scoped_guard(mutex, &dcp->s2r_prewarm_lock) { - if (dcp->dpms_powered_off && !READ_ONCE(dcp->crashed)) { + /* Through a boot the firmware is new: it takes the handshake even with DPMS off. */ + if (dcp->dpms_powered_off && !cold && !READ_ONCE(dcp->crashed)) { dcp_t6041_s2idle_down = false; dev_info(dev, "T6041 S2R: panel off by DPMS before sleep, staying off\n"); return 0; } - ret = dcp_t6041_internal_start_locked(dcp); + ret = dcp_t6041_internal_start_how(dcp, cold); } + if (cold) + return ret; if (!ret) { commit_ret = dcp_t6041_recommit_planes(dcp); if (commit_ret) @@ -15931,7 +17313,7 @@ static int dcp_t6041_ext_darts_dark(void) } /* A power word to manual target on, as dcp_t6041_start_one() writes them; true once on. */ -static bool dcp_t6040_word_up(void __iomem *w) +static bool dcp_ext_word_up(void __iomem *w) { u32 v = readl(w) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)), cur; @@ -15942,8 +17324,7 @@ static bool dcp_t6040_word_up(void __iomem *w) } /* T6040: the chain of an external DCP, by its label: apple,dcp-endpoint 1 is ext0. */ -static struct dcp_t6041_chain *dcp_t6040_ext_chain(struct apple_dcp *host, - struct apple_dcp *dcp) +static struct dcp_t6041_chain *dcp_ext_chain(struct apple_dcp *host, struct apple_dcp *dcp) { struct dcp_t6041_power *pwr = &host->t6041_power; char name[16]; @@ -15965,10 +17346,11 @@ static struct dcp_t6041_chain *dcp_t6040_ext_chain(struct apple_dcp *host, * the idled firmware restarted, then its link set up again as after any system sleep. A display * on it comes back through its hotplug. One that does not come back stays stopped, as before. */ -static int dcp_t6040_ext_start_one(struct device *dev, void *data) +static int dcp_ext_start_one(struct device *dev, void *data) { + bool cold = data && *(bool *)data; struct apple_dcp *dcp = dev_get_drvdata(dev); - struct apple_dcp *host = data; + struct apple_dcp *host = READ_ONCE(dcp_t6041_host); struct dcp_t6041_chain *chain; struct device_node *piodma; unsigned int i; @@ -15978,18 +17360,18 @@ static int dcp_t6040_ext_start_one(struct device *dev, void *data) if (!dcp || dcp == host || IS_ERR_OR_NULL(dcp->rtk) || !dcp->t6041_ext_seen || !READ_ONCE(dcp->s2r_fw_down)) return 0; - chain = dcp_t6040_ext_chain(host, dcp); + chain = dcp_ext_chain(host, dcp); if (!chain) return 0; - if (!dcp_t6040_word_up(chain->domains[0])) + if (!dcp_ext_word_up(chain->domains[0])) to |= BIT(0); writel(0, chain->pg_a); writel(1, chain->pg_b); - if (!dcp_t6040_word_up(chain->domains[1])) + if (!dcp_ext_word_up(chain->domains[1])) to |= BIT(1); writel(readl(chain->gapf) & ~BIT(4), chain->gapf); - if (!dcp_t6040_word_up(chain->domains[2])) + if (!dcp_ext_word_up(chain->domains[2])) to |= BIT(2); for (i = 3; i < chain->num_domains && chain->child_valid; i++) { void __iomem *cw = chain->domains[i]; @@ -16014,6 +17396,10 @@ static int dcp_t6040_ext_start_one(struct device *dev, void *data) of_node_put(piodma); dcp_t6041_dart_dark(dev->of_node, false); dcp_s2r_find_darts(dcp); + if (dcp->s2r_disp_dart) + apple_dart_display_restore(dcp->s2r_disp_dart); + if (dcp->s2r_dcp_dart) + apple_dart_display_restore(dcp->s2r_dcp_dart); if (dcp->s2r_disp_dart) apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, true, false); if (dcp->s2r_dcp_dart) @@ -16022,13 +17408,18 @@ static int dcp_t6040_ext_start_one(struct device *dev, void *data) WRITE_ONCE(dcp->crashed, false); WRITE_ONCE(dcp->ext_dead, false); + if (cold) { + dcp->t6041_ext_seen = false; + dcp_t6041_hib_handshake(dcp); + return 0; + } ret = apple_rtkit_power_cycled_return(dcp->rtk, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); if (ret) { dev_err(dev, "the firmware's warm restart after the sleep failed: %d\n", ret); WRITE_ONCE(dcp->crashed, true); WRITE_ONCE(dcp->ext_dead, true); - WRITE_ONCE(dcp->t6040_relinking, false); + WRITE_ONCE(dcp->ext_relinking, false); return 0; } WRITE_ONCE(dcp->s2r_fw_down, false); @@ -16039,19 +17430,19 @@ static int dcp_t6040_ext_start_one(struct device *dev, void *data) dcp->desktop->ext_pipe_off = true; iomfb_pause_presentation(dcp, false); /* Its link takes a second or more: not in the resume. */ - queue_work(system_dfl_wq, &dcp->t6040_link_work); + queue_work(system_dfl_wq, &dcp->ext_link_work); return 0; } /* The most the converter's rails take to come up: probe's wait for them before the link. */ -#define DCP_T6040_RAILS_MS 100 +#define DCP_EXT_RAILS_MS 100 /* - * The fixed HDMI output given back before the sleep (dcp_t6040_ext_link_down()): the converter's + * The fixed HDMI output given back before the sleep (dcp_ext_link_down()): the converter's * rail on, its DP PHY set up from the start as probe does, then the converter up before the link - * is requested: a sink behind it raises HPD once it is powered (dcp_t6040_link_work()). + * is requested: a sink behind it raises HPD once it is powered (dcp_ext_link_work()). */ -static void dcp_t6040_fixed_phy_up(struct apple_dcp *dcp) +static void dcp_fixed_phy_up(struct apple_dcp *dcp) { ktime_t t = ktime_get(); int ret, hpd; @@ -16070,25 +17461,25 @@ static void dcp_t6040_fixed_phy_up(struct apple_dcp *dcp) /* * The PHY stays off (the unbind action must not power off a PHY that is not on), * and so does the converter's rail. The +5 V rail stays on as the sleep left it - * (dcp_t6040_ext_link_down()): without it HPD stays low. + * (dcp_ext_link_down()): without it HPD stays low. */ dev_err(dcp->dev, "HDMI: DP PHY not powered again after the sleep: %d\n", ret); if (dcp->dp2hdmi_pwren) gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 0); return; } - dcp->t6040_fixed_phy_off = false; + dcp->fixed_phy_off = false; /* * Without an HPD line nothing reports the converter up: the same wait as probe's after * the rails. */ if (!dcp->hdmi_hpd) { - msleep(DCP_T6040_RAILS_MS); + msleep(DCP_EXT_RAILS_MS); return; } /* A sink raises HPD once the converter is up; without one the whole wait. */ ret = read_poll_timeout(gpiod_get_value_cansleep, hpd, hpd, 1000, - DCP_T6040_RAILS_MS * USEC_PER_MSEC, false, dcp->hdmi_hpd); + DCP_EXT_RAILS_MS * USEC_PER_MSEC, false, dcp->hdmi_hpd); if (hpd < 0) dev_warn(dcp->dev, "HDMI: HPD not readable after the sleep: %d\n", hpd); else if (!ret) @@ -16102,9 +17493,9 @@ static void dcp_t6040_fixed_phy_up(struct apple_dcp *dcp) * firmware start at bind (dcp_wait_ready()): a Type-C cable or the HDMI port's HPD connects it * again, and the HPD interrupt is on again. The next sleep's stop waits for this. */ -static void dcp_t6040_link_work(struct work_struct *work) +static void dcp_ext_link_work(struct work_struct *work) { - struct apple_dcp *dcp = container_of(work, struct apple_dcp, t6040_link_work); + struct apple_dcp *dcp = container_of(work, struct apple_dcp, ext_link_work); bool plug; int ret; @@ -16118,25 +17509,25 @@ static void dcp_t6040_link_work(struct work_struct *work) * that the plug cannot come first. */ plug = dcp_is_typec_output(dcp) && READ_ONCE(dcp->typec_cable_connected); - WRITE_ONCE(dcp->t6040_plug_wait, plug); + WRITE_ONCE(dcp->ext_plug_wait, plug); dcp_enable_typec_work(dcp); - if (dcp->t6040_fixed_phy_off) - dcp_t6040_fixed_phy_up(dcp); + if (dcp->fixed_phy_off) + dcp_fixed_phy_up(dcp); /* The HDMI port: a sink behind the converter, which its HPD shows once powered. */ - if (!plug && dcp_t6040_fixed_hdmi(dcp) && !READ_ONCE(dcp->hdmi_yielded) && + if (!plug && dcp_fixed_hdmi(dcp) && !READ_ONCE(dcp->hdmi_yielded) && gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0) { plug = true; - WRITE_ONCE(dcp->t6040_plug_wait, true); + WRITE_ONCE(dcp->ext_plug_wait, true); } dcp_enable_dp2hdmi_hpd(dcp); if (dcp->avep) av_service_connect(dcp); - if (plug && READ_ONCE(dcp->t6040_plug_wait)) { - mod_delayed_work(system_dfl_wq, &dcp->t6040_plug_wq, + if (plug && READ_ONCE(dcp->ext_plug_wait)) { + mod_delayed_work(system_dfl_wq, &dcp->ext_plug_wq, msecs_to_jiffies(DCP_S2R_PLUG_MS)); return; } - WRITE_ONCE(dcp->t6040_relinking, false); + WRITE_ONCE(dcp->ext_relinking, false); } /* @@ -16144,13 +17535,13 @@ static void dcp_t6040_link_work(struct work_struct *work) * within DCP_S2R_PLUG_MS: either way the link work is through, and the hotplug worker applies * the CRTC state that DRM kept active, or the compositor learns that the display is gone. */ -void dcp_t6040_plug_done(struct apple_dcp *dcp, bool plug) +void dcp_ext_plug_done(struct apple_dcp *dcp, bool plug) { - if (!xchg(&dcp->t6040_plug_wait, false)) + if (!xchg(&dcp->ext_plug_wait, false)) return; if (!plug) dev_info(dcp->dev, "display not reported back after the sleep\n"); - WRITE_ONCE(dcp->t6040_relinking, false); + WRITE_ONCE(dcp->ext_relinking, false); /* * The hotplug the plug itself queues may run first and skip this output while it is * relinking, and an unchanged connector queues none: queue one now. @@ -16159,16 +17550,39 @@ void dcp_t6040_plug_done(struct apple_dcp *dcp, bool plug) dcp_queue_hotplug(dcp->connector); } -static void dcp_t6040_plug_work(struct work_struct *work) +static void dcp_ext_plug_work(struct work_struct *work) { struct apple_dcp *dcp = container_of(to_delayed_work(work), struct apple_dcp, - t6040_plug_wq); + ext_plug_wq); - dcp_t6040_plug_done(dcp, false); + dcp_ext_plug_done(dcp, false); } enum dcp_t6041_step { DCP_S2R_FW_STOP, DCP_S2R_WORDS_DOWN, DCP_S2R_START }; +/* + * The display back up after dcp_t6041_s2r_all(false): the domains and DARTs as after a sleep, + * then the firmware's warm return, or (@cold, through a boot) the new handshake. + */ +static int dcp_t6041_start(bool cold) +{ + struct apple_dcp *host = READ_ONCE(dcp_t6041_host); + int ret; + + if (!host) + return -ENODEV; + if (!READ_ONCE(dcp_t6041_down)) + return 0; + WRITE_ONCE(dcp_t6041_down, false); + dcp_t6041_words = false; + ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &cold, + dcp_t6041_start_one); + if (!ret && host->t6041_power.relink_ext) + ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &cold, + dcp_ext_start_one); + return ret; +} + /* Each step once per sleep. */ static int dcp_t6041_s2r_step(enum dcp_t6041_step step) { @@ -16180,19 +17594,8 @@ static int dcp_t6041_s2r_step(enum dcp_t6041_step step) if (!host) return -ENODEV; - if (step == DCP_S2R_START) { - if (!READ_ONCE(dcp_t6041_down)) - return 0; - WRITE_ONCE(dcp_t6041_down, false); - dcp_t6041_words = false; - ret = driver_for_each_device(&apple_platform_driver.driver, NULL, NULL, - dcp_t6041_start_one); - /* T6040: the external DCPs once the internal display runs again. */ - if (!ret && host->t6041_power.t6040) - ret = driver_for_each_device(&apple_platform_driver.driver, NULL, host, - dcp_t6040_ext_start_one); - return ret; - } + if (step == DCP_S2R_START) + return dcp_t6041_start(false); if (step == DCP_S2R_WORDS_DOWN) { if (dcp_t6041_words || !READ_ONCE(dcp_t6041_down)) return 0; @@ -16286,6 +17689,27 @@ int dcp_t6041_s2r_all(bool start) return 0; } +#ifdef CONFIG_HIBERNATION +/* A display complex that hibernation takes down with the sleep's stop (from the DT). */ +static bool dcp_t6041_hib_capable(void) +{ + return READ_ONCE(dcp_sleep_host_stop); +} + +/* + * Hibernation .restore of a display complex that .freeze took down (dcp_t6041_s2r_all()): + * from the loading kernel, whose .freeze stopped it the same way, the sleep's warm return; + * through a boot (pm_hibernate_restored_cold() not 0), the new handshake. + */ +void dcp_t6041_hib_restore(void) +{ + if (pm_hibernate_restored_cold()) + dcp_t6041_start(true); + else + dcp_t6041_s2r_all(true); +} +#endif + /* * T6041 suspend-to-idle: stop only the internal DCP and lower DISP0's power * words, leaving external DCPs untouched on their normal s2idle suspend path. @@ -16326,15 +17750,49 @@ int dcp_t6041_s2idle(bool start) return ret; } +#ifdef CONFIG_HIBERNATION +/* Ahead of the per-DCP notifiers (priority -5). */ +static int dcp_hib_global_notify(struct notifier_block *nb, unsigned long action, + void *unused) +{ + switch (action) { + case PM_HIBERNATION_PREPARE: + WRITE_ONCE(dcp_hib_in_progress, true); + break; + case PM_POST_HIBERNATION: + case PM_POST_RESTORE: + WRITE_ONCE(dcp_hib_in_progress, false); + break; + } + return NOTIFY_DONE; +} + +static struct notifier_block dcp_hib_global_nb = { + .notifier_call = dcp_hib_global_notify, + .priority = 10, +}; +#endif + int __init dcp_register(void) { int ret = dcp_panel_led_register(); if (ret) return ret; +#ifdef CONFIG_HIBERNATION + ret = register_pm_notifier(&dcp_hib_global_nb); + if (ret) { + dcp_panel_led_unregister(); + return ret; + } +#endif ret = platform_driver_register(&apple_platform_driver); - if (ret) + if (ret) { +#ifdef CONFIG_HIBERNATION + unregister_pm_notifier(&dcp_hib_global_nb); +#endif dcp_panel_led_unregister(); + } return ret; } @@ -16343,6 +17801,10 @@ void dcp_unregister(void) platform_driver_unregister(&apple_platform_driver); dcp_panel_led_unregister(); t8152_typec_unregister(); + +#ifdef CONFIG_HIBERNATION + unregister_pm_notifier(&dcp_hib_global_nb); +#endif } #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index dc13799b2dd41..b32221d3bf9c8 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -183,8 +183,9 @@ void dcp_fabric_pm_unregister(void); bool dcp_hold_resume_event(struct platform_device *pdev); bool dcp_s2r_firmware_stopped(struct platform_device *pdev); int dcp_t6041_s2r_all(bool start); +bool dcp_ext_relinks(void); +void dcp_t6041_hib_restore(void); int dcp_t6041_s2idle(bool start); -bool dcp_t6040_relinks(void); int iomfb_start_rtkit(struct apple_dcp *dcp); void iomfb_ext26_start(struct apple_dcp *dcp); @@ -221,7 +222,7 @@ void dcp_hdmi_disconnect(struct apple_dcp *dcp); void dcp_fabric_hybrid_kick(struct apple_dcp *dcp, unsigned int delay_ms); void dcp_hdmi_yield_link(struct apple_dcp *dcp); void dcp_link_recovery_schedule(struct apple_dcp *dcp); -void dcp_t6040_plug_done(struct apple_dcp *dcp, bool plug); +void dcp_ext_plug_done(struct apple_dcp *dcp, bool plug); /* Desktop 26.6 dual-pipe peer (dcp-peer-v26_6.inc, included from dcp.c) */ struct dptx_port; diff --git a/drivers/gpu/drm/apple/dcp_backlight.c b/drivers/gpu/drm/apple/dcp_backlight.c index f77cf22d9788e..bb8f55c5d7c6f 100644 --- a/drivers/gpu/drm/apple/dcp_backlight.c +++ b/drivers/gpu/drm/apple/dcp_backlight.c @@ -360,6 +360,9 @@ static void dcp_backlight_kick(struct apple_dcp *dcp) { void (*kick)(struct apple_dcp *dcp) = READ_ONCE(dcp->backlight.kick); + /* Resume from disk: the level stays pending until the new session. */ + if (dcp_hib_gated(dcp)) + return; if (kick) kick(dcp); } diff --git a/drivers/gpu/drm/apple/dcp_external_announce_test.c b/drivers/gpu/drm/apple/dcp_external_announce_test.c index 9c9b8421d0b46..2a566c7d07b49 100644 --- a/drivers/gpu/drm/apple/dcp_external_announce_test.c +++ b/drivers/gpu/drm/apple/dcp_external_announce_test.c @@ -114,6 +114,7 @@ static struct announce_test *announce_test_init(struct kunit *test) INIT_DELAYED_WORK(&dcp->hdmi_settle_wq, announce_test_noop); INIT_DELAYED_WORK(&dcp->hdmi_recheck_wq, announce_test_noop); INIT_DELAYED_WORK(&dcp->link_recovery_wq, announce_test_noop); + INIT_DELAYED_WORK(&dcp->hotplug_retrain_retry_wq, announce_test_noop); INIT_DELAYED_WORK(&dcp->hybrid_wq, announce_test_noop); INIT_DELAYED_WORK(&dcp->bl_fallback_wq, announce_test_noop); INIT_DELAYED_WORK(&dcp->backlight.fade_work, announce_test_noop); diff --git a/drivers/gpu/drm/apple/dcp_t6041_wake_test.c b/drivers/gpu/drm/apple/dcp_t6041_wake_test.c index 81be65c4c31df..ee5f625ac5f88 100644 --- a/drivers/gpu/drm/apple/dcp_t6041_wake_test.c +++ b/drivers/gpu/drm/apple/dcp_t6041_wake_test.c @@ -124,7 +124,7 @@ struct dcp_t6041_start_hw_stub_ctx { static struct dcp_t6041_start_hw_stub_ctx *dcp_t6041_start_hw_stub_cur; -static int dcp_t6041_start_internal_hw_stub(struct apple_dcp *dcp) +static int dcp_t6041_start_internal_hw_stub(struct apple_dcp *dcp, bool cold) { struct dcp_t6041_start_hw_stub_ctx *ctx = dcp_t6041_start_hw_stub_cur; @@ -198,9 +198,9 @@ static void dcp_t6041_dpms_policy(struct kunit *test) host->v27_methods = methods; KUNIT_EXPECT_TRUE(test, dcp_t6041_dpms_capable(host)); /* T6040 (M4 Pro) has the same display-power block: capable too. */ - host->t6041_power.t6040 = true; + host->t6041_power.relink_ext = true; KUNIT_EXPECT_TRUE(test, dcp_t6041_dpms_capable(host)); - host->t6041_power.t6040 = false; + host->t6041_power.relink_ext = false; KUNIT_EXPECT_TRUE(test, dcp_dpms_power_cycles(host)); #ifdef CONFIG_SUSPEND @@ -402,7 +402,7 @@ static int dcp_t6041_desktop_stop_stub(struct apple_dcp *host, bool dpms) return ctx->stop_ret; } -static int dcp_t6041_desktop_start_stub(struct apple_dcp *host) +static int dcp_t6041_desktop_start_stub(struct apple_dcp *host, bool cold) { struct dcp_t6041_desktop_dpms_ctx *ctx = dcp_t6041_desktop_dpms_cur; @@ -470,7 +470,7 @@ static void dcp_t6041_v26_6_desktop_dpms(struct kunit *test) host->connector_type = DRM_MODE_CONNECTOR_eDP; host->sleep_host_stop = true; host->t6041_power.main_chain = &main_chain; - host->t6041_power.t6040 = true; + host->t6041_power.relink_ext = true; WRITE_ONCE(dcp_sleep_host_stop, true); WRITE_ONCE(dcp_t6041_host, host); @@ -497,9 +497,9 @@ static void dcp_t6041_v26_6_desktop_dpms(struct kunit *test) /* 26.6 desktop internal panel uses classic DPMS, not soft DPMS. */ KUNIT_EXPECT_FALSE(test, dcp_uses_soft_dpms(host)); KUNIT_EXPECT_TRUE(test, dcp_t6041_dpms_capable(host)); - host->t6041_power.t6040 = false; + host->t6041_power.relink_ext = false; KUNIT_EXPECT_TRUE(test, dcp_t6041_dpms_capable(host)); - host->t6041_power.t6040 = true; + host->t6041_power.relink_ext = true; /* Runtime DPMS off stops host/firmware in one pass without fallback _dcp_poweroff(). */ dcp_poweroff(&pdev); diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index e2b5a6366ff6a..21ef1d042d751 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -1041,10 +1041,17 @@ static int dptxport_call(struct apple_epic_service *service, u32 idx, case DPTX_APCALL_DEVICE_BUSY_TIMEOUT: case DPTX_APCALL_DEVICE_NOT_STARTED: dcp_external_link_fault(service->ep->dcp); - dev_warn(service->ep->dcp->dev, - "DPTXPort: firmware reports link fault %u on target %u:%u\n", - idx, service->ep->dcp->dptx_die, - service->ep->dcp->dptx_phy); + /* Without a sink the firmware's probing of the port fails by design. */ + if (dcp_external_has_sink(service->ep->dcp)) + dev_warn(service->ep->dcp->dev, + "DPTXPort: firmware reports link fault %u on target %u:%u\n", + idx, service->ep->dcp->dptx_die, + service->ep->dcp->dptx_phy); + else + dev_dbg(service->ep->dcp->dev, + "DPTXPort: link fault %u on target %u:%u without a sink\n", + idx, service->ep->dcp->dptx_die, + service->ep->dcp->dptx_phy); memcpy(reply, data, min(reply_size, data_size)); return 0; case DPTX_APCALL_SET_TILED_DISPLAY_HINTS: { diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index b9fd196aa5d97..8d7003f651c17 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -5,10 +5,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -21,6 +23,7 @@ #include #include #include +#include #include #include @@ -2475,7 +2478,7 @@ static int dcp_retrain_active_crtc(struct apple_connector *connector, (READ_ONCE(dcp->mode_state.valid) || !dcp_has_mode(dcp, &crtc->state->mode))) { ret = 0; - } else if (dcp_t6040_relinks() && crtc && crtc->state && crtc->state->active && + } else if (dcp_ext_relinks() && crtc && crtc->state && crtc->state->active && !dcp_mode_settable(dcp, &crtc->state->mode) && !dcp_typec_follows_crtc(dcp)) { /* @@ -2921,6 +2924,74 @@ void dcp_route_failure_notify(struct apple_connector *connector) schedule_work(&connector->hotplug_wq); } +/* + * A sink that drops its link and raises IRQ_HPD after every training (seen + * with a dual-pipe monitor after a modeset from the kernel console during a + * hibernation entry) turns each hotplug into a retrain and each + * retrain into a hotplug, every 0.4-1.2 s, until the Type-C controller gives + * up on the cable. The worker retrains at most DCP_HOTPLUG_RETRAIN_MAX times + * in a DCP_HOTPLUG_RETRAIN_WINDOW that starts with its first retrain and is + * not extended by refused requests, so a storm is bounded to that rate and + * never stops the retrains for good. Past the limit the link status stays + * BAD (userspace still gets every hotplug event and may set a mode); when the + * window ends, one more retrain is tried if the sink is still connected. + * + * A disconnect lasting DCP_HOTPLUG_REPLUG_GAP or longer is a real replug and + * starts a fresh window. A completed modeset does not: in the storm every + * compositor modeset completed before the sink dropped the link again. + */ +#define DCP_HOTPLUG_RETRAIN_MAX 5 +#define DCP_HOTPLUG_RETRAIN_WINDOW (30 * HZ) +#define DCP_HOTPLUG_REPLUG_GAP (3 * HZ) + +static void dcp_hotplug_retrain_reset(struct apple_dcp *dcp, const char *why) +{ + if (dcp->hotplug_retrain_stopped) + dev_dbg(dcp->dev, "hotplug: link retrains resumed (%s)\n", why); + dcp->hotplug_retrain_stopped = false; + dcp->hotplug_retrains = 0; +} + +/* Called from the connector's hotplug work only, which serializes it. */ +static void dcp_hotplug_retrain_note(struct apple_dcp *dcp, bool connected) +{ + unsigned long now = jiffies; + + if (!connected) { + if (!dcp->hotplug_disconnect_at) + dcp->hotplug_disconnect_at = now ?: 1; + return; + } + if (dcp->hotplug_disconnect_at && + time_after_eq(now, dcp->hotplug_disconnect_at + DCP_HOTPLUG_REPLUG_GAP)) + dcp_hotplug_retrain_reset(dcp, "replug"); + dcp->hotplug_disconnect_at = 0; +} + +static bool dcp_hotplug_retrain_allowed(struct apple_dcp *dcp) +{ + unsigned long now = jiffies; + + if (dcp->hotplug_retrains && + time_after_eq(now, dcp->hotplug_retrain_since + DCP_HOTPLUG_RETRAIN_WINDOW)) + dcp_hotplug_retrain_reset(dcp, "window over"); + if (dcp->hotplug_retrain_stopped) + return false; + if (!dcp->hotplug_retrains) + dcp->hotplug_retrain_since = now; + if (++dcp->hotplug_retrains > DCP_HOTPLUG_RETRAIN_MAX) { + dcp->hotplug_retrain_stopped = true; + dev_warn(dcp->dev, + "hotplug: %u link retrains within %u s, the sink keeps dropping the link; next kernel retrain when the window ends\n", + DCP_HOTPLUG_RETRAIN_MAX, + jiffies_to_msecs(DCP_HOTPLUG_RETRAIN_WINDOW) / 1000); + mod_delayed_work(system_freezable_wq, &dcp->hotplug_retrain_retry_wq, + dcp->hotplug_retrain_since + DCP_HOTPLUG_RETRAIN_WINDOW - now); + return false; + } + return true; +} + void dcp_hotplug(struct work_struct *work) { struct apple_connector *connector; @@ -2962,7 +3033,7 @@ void dcp_hotplug(struct work_struct *work) * mode list: the plug that follows reads that list, so a link recovery * pending for the old one would only take the new link down. */ - if (!READ_ONCE(connector->connected) && dcp_t6040_relinks()) + if (!READ_ONCE(connector->connected) && dcp_ext_relinks()) cancel_delayed_work(&dcp->link_recovery_wq); scoped_guard(mutex, &connector->base.dev->mode_config.mutex) { @@ -2971,6 +3042,7 @@ void dcp_hotplug(struct work_struct *work) if (!READ_ONCE(connector->connected)) dcp_clear_connector_edid(connector); } + dcp_hotplug_retrain_note(dcp, READ_ONCE(connector->connected)); gated = dcp_announce_gated(dcp, connector); if (gated) { @@ -3018,7 +3090,7 @@ void dcp_hotplug(struct work_struct *work) !READ_ONCE(dcp->typec_enable_pending) && !READ_ONCE(dcp->mode_state.changing) && /* T6040 S2R: applied again once the link work is through. */ - !READ_ONCE(dcp->t6040_relinking) && + !READ_ONCE(dcp->ext_relinking) && (!dcp_uses_t6020_tunnel_flow(dcp) || dcp->tunnel_power_cycles < DCP_TUNNEL_POWER_CYCLES)) { bool power_cycle = dcp_uses_t6020_tunnel_flow(dcp); @@ -3040,7 +3112,8 @@ void dcp_hotplug(struct work_struct *work) * link. Re-apply the active CRTC state once the DPTX link-config * callback has completed. */ - ret = dcp_retrain_active_crtc(connector, dcp, power_cycle); + ret = dcp_hotplug_retrain_allowed(dcp) ? + dcp_retrain_active_crtc(connector, dcp, power_cycle) : 0; if (ret == -ENOENT) { dev_dbg(dcp->dev, "active CRTC mode not listed yet, retrain deferred\n"); dcp_link_recovery_schedule(dcp); @@ -5040,9 +5113,13 @@ int dcp_crtc_atomic_modeset(struct drm_crtc *crtc, * leaves the pipe off ("Modeset done, but pipe not enabled") and * fails. dcp_poweron() and the flips leave the firmware alone until * then too; the hotplug worker sets the mode of the CRTC that is - * still active once the link work is through (dcp_t6040_plug_done()). + * still active once the link work is through (dcp_ext_plug_done()). */ - if (READ_ONCE(dcp->t6040_relinking)) + if (READ_ONCE(dcp->ext_relinking)) + return 0; + + /* Resume from disk: the restart sets the mode (see dcp_hib_recommit()). */ + if (dcp_hib_gated(dcp)) return 0; /* Disconnect cannot pass the admission check before these RPCs finish. */ @@ -6162,7 +6239,17 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) } /* T6040 S2R: no swap until the external link work is through. */ - if (READ_ONCE(dcp->t6040_relinking)) { + if (READ_ONCE(dcp->ext_relinking)) { + schedule_work(&dcp->vblank_wq); + return; + } + + /* + * Resume from disk: the firmware session the flip would go to is gone + * and the new one is not up yet (or never came up). Complete the + * flip without a swap; the restart re-commits the mode and the frame. + */ + if (dcp_hib_gated(dcp)) { schedule_work(&dcp->vblank_wq); return; } @@ -6340,6 +6427,34 @@ void iomfb_ext26_start(struct apple_dcp *dcp) iomfb_queue_advance(dcp); } +/* + * Resume from disk: the image restore wrote the arena's pages through the + * cacheable linear map and cleaned them only to the PoU + * (arch/arm64/kernel/hibernate-asm.S). The DCP is not DMA-coherent (no + * dma-coherent in its node), its arena is mapped non-cacheable, and a dirty + * line of the linear alias could be written back over what the host writes + * through that mapping, or hold what the firmware should read. Clean the + * linear alias to the PoC before the arena is cleared and handed over. + */ +static void iomfb_hib_clean_shmem(struct apple_dcp *dcp) +{ + size_t off; + + if (dev_is_dma_coherent(dcp->dev)) + return; + for (off = 0; off < DCP_SHMEM_SIZE; off += PAGE_SIZE) { + void *va = dcp->shmem + off; + struct page *page = is_vmalloc_addr(va) ? vmalloc_to_page(va) : + virt_to_page(va); + unsigned long lin; + + if (!page) + continue; + lin = (unsigned long)page_address(page); + dcache_clean_poc(lin, lin + PAGE_SIZE); + } +} + int iomfb_start_rtkit(struct apple_dcp *dcp) { dma_addr_t shmem_iova; @@ -6387,10 +6502,27 @@ int iomfb_start_rtkit(struct apple_dcp *dcp) return ret; } + /* + * Firmware restarted in place after a resume from disk: the arena and + * its mapping are in the restored image, only the firmware's binding + * is gone. Give it the same arena, cleared as a new one would be. + */ + if (IS_ENABLED(CONFIG_HIBERNATION) && dcp->shmem && + READ_ONCE(dcp->hib_phase) == DCP_HIB_RESTARTING) { + iomfb_hib_clean_shmem(dcp); + memset(dcp->shmem, 0, DCP_SHMEM_SIZE); + /* The firmware reads the arena only after set_shmem. */ + wmb(); + dcp_send_message(dcp, IOMFB_ENDPOINT, + dcpep_set_shmem(dcp->shmem_iova)); + return 0; + } + dcp->shmem = dma_alloc_coherent(dcp->dev, DCP_SHMEM_SIZE, &shmem_iova, GFP_KERNEL); if (!dcp->shmem) return -ENOMEM; + dcp->shmem_iova = shmem_iova; dcp_send_message(dcp, IOMFB_ENDPOINT, dcpep_set_shmem(shmem_iova)); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 8690305ea2adb..93bad63aa1d65 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -1314,6 +1314,13 @@ static bool dcpep_map_piodma(struct apple_dcp *dcp, .dva = memdesc->dva, }; #elif DCP_FW_DESKTOP_26(DCP_FW_VER) + /* + * Tracked as on H17P: a buffer released, or a session dropped after a + * resume from disk, must not leave its piodma translation behind, or + * the next mapping at the same address fails with -EEXIST. + */ + memdesc->piodma_mapped = true; + /* the desktop 26.x reply echoes the buffer index too */ *resp = (struct DCP_FW_NAME(dcp_map_buf_resp)) { .buffer = req->buffer, @@ -1366,7 +1373,7 @@ static bool dcpep_unmap_piodma(struct apple_dcp *dcp, if (!test_bit(request->buffer, dcp->memdesc_map) || !memdesc->buf || !dcp->iommu_dom) goto not_mapped; -#if DCP_FW_H17(DCP_FW_VER) +#if DCP_FW_H17(DCP_FW_VER) || DCP_FW_DESKTOP_26(DCP_FW_VER) if (!memdesc->piodma_mapped) goto not_mapped; #endif @@ -1503,8 +1510,9 @@ static u8 dcpep_cb_release_mem_desc(struct apple_dcp *dcp, u32 *mem_desc_id) * the allocator. The firmware is expected to unmap piodma first, but * if it releases a descriptor without doing so we would hand the pages * back while the DART still resolves them -- the display engine would - * then read whoever owns them next. Only the H17P map_piodma handler - * sets piodma_mapped, so older firmware is unaffected. + * then read whoever owns them next. The H17P and desktop 26.x + * map_piodma handlers set piodma_mapped, so older firmware is + * unaffected. */ if (memdesc->piodma_mapped) { dev_warn(dcp->dev, @@ -3399,16 +3407,16 @@ static void dcpep_cb_hotplug(struct apple_dcp *dcp, u64 *connected) /* * T6040 S2R: the unplug an external output reports when its link and pipe go down for * the sleep. The display is still there, and the link work after the wake brings it - * back (see dcp_t6040_ext_link_down()). + * back (see dcp_ext_link_down()). */ - if (!(*connected) && READ_ONCE(dcp->t6040_relinking)) { + if (!(*connected) && READ_ONCE(dcp->ext_relinking)) { dcp_mode_invalidate(&dcp->mode_state); schedule_work(&dcp->vblank_wq); return; } /* T6040 S2R: the display is back, which the link work waits for. */ - if (*connected && READ_ONCE(dcp->t6040_plug_wait)) - dcp_t6040_plug_done(dcp, true); + if (*connected && READ_ONCE(dcp->ext_plug_wait)) + dcp_ext_plug_done(dcp, true); /* DCP lost a sink which is still attached, see dcp_typec_relink() */ if (!(*connected) && dcp_typec_relink(dcp)) { dcp_mode_invalidate(&dcp->mode_state); diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b30f0750dd93c..1400f885c7c7e 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -30,6 +30,7 @@ mod g16; mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; +mod boot_memory; mod gpu; #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod g14_v27_2; @@ -112,6 +113,8 @@ impl kernel::InPlaceModule for DriverModule { // SAFETY: Module init runs once, before either adapter is registered below. unsafe { binding::init() }; // SAFETY: Module init runs once, before either adapter is registered below. + unsafe { boot_memory::init() }; + // SAFETY: Module init runs once, before either adapter is registered below. unsafe { queue_share::init() }; // SAFETY: Module init runs once, before either adapter is registered below. unsafe { mmu::residency_init() }; diff --git a/drivers/gpu/drm/asahi/boot_memory.rs b/drivers/gpu/drm/asahi/boot_memory.rs new file mode 100644 index 0000000000000..0d28b1603acc3 --- /dev/null +++ b/drivers/gpu/drm/asahi/boot_memory.rs @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The GPU firmware's reserved memory as the boot loader handed it over. +//! +//! The firmware's memory regions (the device's `memory-region` list: its data segment and the +//! tables it and the boot loader build) are set up by the boot loader once per boot. A firmware +//! that ran and was stopped, by an unbind or for a hibernation, leaves its data segment and its +//! tables behind, and booting it again from them faults. The first probe of a device in a boot +//! keeps a copy of every region the firmware may write, before anything touches them, and every +//! later probe of that device puts the copy back first, so each boot of the firmware starts +//! from memory as it was handed over. +//! +//! The text segment (`fw-text`) is not kept: the boot loader keeps it from being written, so it +//! never changes. + +use core::ptr; + +use kernel::{ + device, + io::mem::{Mem, MemFlag}, + prelude::*, + str::CStr, // +}; + +kernel::sync::global_lock! { + // SAFETY: Module initialization initializes this lock before registering adapters. + unsafe(uninit) static HANDED_OVER: Mutex> = KVec::new(); +} + +/// # Safety +/// +/// Called exactly once per module instance, before any device probes. +pub(crate) unsafe fn init() { + // SAFETY: The module initializer establishes the single-call ordering above. + unsafe { HANDED_OVER.init() }; +} + +/// Called by a probe before anything writes the firmware's memory: keeps it as handed over on +/// the device's first probe, and puts it back on every later one. +pub(crate) fn prepare(dev: &device::Device) -> Result { + let key = dev.as_raw() as usize; + let mut handed_over = HANDED_OVER.lock(); + if let Some((_, carried)) = handed_over.iter_mut().find(|(k, _)| *k == key) { + // A restored image finds the memory a later boot handed over. + carried.save(); + return Ok(()); + } + let mut carried = Carried::new(dev)?; + carried.save(); + handed_over.push((key, carried), GFP_KERNEL)?; + Ok(()) +} + +/// After the firmware stopped and its processors were reset: the memory goes back to how the +/// boot loader handed it over, so the next start boots the firmware afresh. +pub(crate) fn put_back(dev: &device::Device) { + let key = dev.as_raw() as usize; + let handed_over = HANDED_OVER.lock(); + if let Some((_, carried)) = handed_over.iter().find(|(k, _)| *k == key) { + let pages = carried.put_back(); + dev_dbg!(dev, "GPU firmware memory as handed over: {} pages put back\n", pages); + } +} + +use crate::pgtable::{clean_invalidate_poc, clean_poc, poc_barrier}; + +/// The granule pages are compared and written back in. +const PAGE: usize = 1 << 14; + +/// The region the boot loader keeps from being written. +const READ_ONLY: &[u8] = b"fw-text"; + +/// One reserved region and its copy. +struct Region { + mem: Mem, + copy: KVVec, +} + +/// Every writable reserved region of a GPU, with its copy. +struct Carried { + regions: KVec, +} + +// SAFETY: The mappings are plain write-back memory owned by this object, and every access is +// made under `HANDED_OVER`'s lock, with the firmware stopped. +unsafe impl Send for Carried {} +// SAFETY: As above. +unsafe impl Sync for Carried {} + +/// Writes the `PAGE`-sized chunks of `saved` that differ from `live` into `live`, and returns +/// how many did. +fn put_back_pages(saved: &[u8], live: &mut [u8]) -> usize { + let mut changed = 0; + for (from, to) in saved.chunks(PAGE).zip(live.chunks_mut(PAGE)) { + if from != &*to { + changed += 1; + to.copy_from_slice(from); + } + } + changed +} + +impl Carried { + /// Maps every region named in `dev`'s `memory-region-names` but the text, and allocates its + /// copy. Nothing is copied yet. + fn new(dev: &device::Device) -> Result { + let node = dev.of_node().ok_or(ENODEV)?; + let names: KVec = node.get_property(c"memory-region-names")?; + let mut regions = KVec::new(); + for name in names.split_inclusive(|byte| *byte == 0) { + let name = CStr::from_bytes_with_nul(name).map_err(|_| EINVAL)?; + if name.is_empty() || name.to_bytes() == READ_ONLY { + continue; + } + let res = node.reserved_mem_region_to_resource_byname(name)?; + // SAFETY: A region the boot loader reserved (no-map) for the GPU firmware; it stays + // reserved until reboot. The mapping is only used for CPU copies, never for DMA. + let mem = unsafe { Mem::try_new(res, MemFlag::WB.into())? }; + let copy = KVVec::from_elem(0u8, mem.size(), GFP_KERNEL)?; + regions.push(Region { mem, copy }, GFP_KERNEL)?; + } + if regions.is_empty() { + return Err(ENOENT); + } + Ok(Self { regions }) + } + + /// Copies every region. Nothing has written them since the boot loader, which doesn't go + /// through the CPU's caches, so they are read from memory. + fn save(&mut self) { + for region in self.regions.iter_mut() { + let size = region.mem.size(); + clean_invalidate_poc(region.mem.ptr(), size); + poc_barrier(); + // SAFETY: The mapping and the copy are both `size` bytes and don't overlap. + unsafe { ptr::copy_nonoverlapping(region.mem.ptr(), region.copy.as_mut_ptr(), size) }; + } + } + + /// Writes every region back as it was handed over, with the firmware stopped, and cleans it + /// to the point of coherency for the firmware. Returns how many pages differed. + fn put_back(&self) -> usize { + let mut written = 0; + for region in self.regions.iter() { + let size = region.mem.size(); + clean_invalidate_poc(region.mem.ptr(), size); + poc_barrier(); + // SAFETY: The mapping is `size` bytes of reserved memory that nothing else touches + // with the firmware stopped. + let live = unsafe { core::slice::from_raw_parts_mut(region.mem.ptr(), size) }; + let n = put_back_pages(®ion.copy, live); + written += n; + clean_poc(region.mem.ptr(), size); + } + poc_barrier(); + written + } +} + +#[kernel::macros::kunit_tests(asahi_boot_memory)] +mod tests { + use super::*; + + fn pages(fill: &[u8]) -> KVec { + let mut v = KVec::new(); + for byte in fill { + for _ in 0..PAGE { + v.push(*byte, GFP_KERNEL).unwrap(); + } + } + v + } + + #[test] + fn only_changed_pages_are_written() { + let saved = pages(&[1, 2, 3]); + let mut live = pages(&[1, 9, 3]); + assert_eq!(put_back_pages(&saved, &mut live), 1); + assert!(saved[..] == live[..]); + assert_eq!(put_back_pages(&saved, &mut live), 0); + } + + #[test] + fn a_zeroed_region_is_written_whole() { + let saved = pages(&[1, 2]); + let mut live = pages(&[0, 0]); + assert_eq!(put_back_pages(&saved, &mut live), 2); + assert!(saved[..] == live[..]); + } + + #[test] + fn a_partial_last_page_is_compared() { + let mut saved = pages(&[4]); + saved.push(5, GFP_KERNEL).unwrap(); + let mut live = pages(&[4]); + live.push(6, GFP_KERNEL).unwrap(); + assert_eq!(put_back_pages(&saved, &mut live), 1); + assert_eq!(live[PAGE], 5); + } +} diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 912f6df85d821..666eb4bc1480e 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -33,6 +33,7 @@ use crate::{ hw, regs, // }; +use crate::gpu::HibRestoreContain; use kernel::macros::vtable; @@ -383,11 +384,77 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { } } +/// Hibernation restore, on the restored kernel only. The firmware captured in the image is gone +/// (a fresh warm boot reset the ASC), so hand each present GPU backend a chance to mark itself +/// lost before its runtime touches the dead coprocessor. Dispatch is generation-agnostic through +/// [`gpu::HibRestoreContain`]; a generation that has not opted in no-ops. Suspend resume and a +/// hibernating kernel's own thaw never reach here, so no gating on the sleep kind is needed. +unsafe extern "C" fn sleep_restore_noirq(dev: *mut bindings::device) -> core::ffi::c_int { + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { for_each_backend(dev, |gpu| gpu.hib_restore_contain()) }; + 0 +} + +/// Runs `f` on every present GPU backend, through the generation-agnostic +/// [`gpu::HibRestoreContain`] hooks. +/// +/// # Safety +/// +/// `dev` must be a device this driver is bound to, as for a PM core callback. +unsafe fn for_each_backend(dev: *mut bindings::device, mut f: impl FnMut(&dyn HibRestoreContain)) { + // SAFETY: The caller's obligation. + let data = unsafe { sleep_data(dev) }; + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + if let Some(backend) = data.g14_v27_2.as_ref() { + f(&**backend); + } + #[cfg(CONFIG_DRM_ASAHI_G16)] + if let Some(gpu) = data.g16.as_ref() { + f(&**gpu); + } + if let Some(gpu) = data.g17.as_ref() { + f(&**gpu); + } +} + +/// Hibernation freeze, after `.prepare`: a backend that boots its firmware again on restore stops +/// it here. A refusal fails the hibernation. +unsafe extern "C" fn sleep_freeze(dev: *mut bindings::device) -> core::ffi::c_int { + let mut result = Ok(()); + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { + for_each_backend(dev, |gpu| { + if result.is_ok() { + result = gpu.hib_freeze(); + } + }) + }; + result.map_or_else(|error| error.to_errno(), |_| 0) +} + +/// The last device step before the image is taken. +unsafe extern "C" fn sleep_freeze_noirq(dev: *mut bindings::device) -> core::ffi::c_int { + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { for_each_backend(dev, |gpu| gpu.hib_freeze_late()) }; + 0 +} + +/// The image is written or the hibernation failed: the firmware's memory is intact. +unsafe extern "C" fn sleep_thaw(dev: *mut bindings::device) -> core::ffi::c_int { + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { for_each_backend(dev, |gpu| gpu.hib_thaw()) }; + 0 +} + static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_prepare), complete: Some(sleep_complete), suspend_noirq: Some(sleep_suspend_noirq_driver), resume_noirq: Some(sleep_resume_noirq), + freeze: Some(sleep_freeze), + freeze_noirq: Some(sleep_freeze_noirq), + thaw: Some(sleep_thaw), + restore_noirq: Some(sleep_restore_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); @@ -764,6 +831,8 @@ impl AsahiPlatformDriver { ) -> Result> { // SAFETY: The GPU performs DMA through a UAT whose output width is part of the SoC config. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; + // Before anything writes the firmware's memory: a probe after an unbind boots it again. + crate::boot_memory::prepare(pdev.as_ref())?; let resources = regs::Resources::new(pdev)?; let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; // SAFETY: Every adapter calls close_binding in unbind before devres; diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index edc511b26052e..8f2cb09cefa1d 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -551,13 +551,68 @@ fn admit_bind( /// queues is given back once the queue itself is gone. pub(crate) struct TableQueue { queue: KBox, + /// What the queue was created with, to build it again on the same VM + /// ([`queue::Queue::needs_rebuild`]). + created: QueueArgs, /// Reusable staging buffer for `SUBMIT` command buffers, avoiding per-submit heap /// allocations and keeping large command buffers off the kernel stack. cmdbuf: KVVec, _share: Option, } +/// The arguments of `QUEUE_CREATE` that a rebuilt queue is given again. +struct QueueArgs { + vm: crate::mmu::Vm, + ualloc: Arc>, + ualloc_priv: Arc>, + priority: u32, + usc_exec_base: u64, + render_scs_layout: [u64; 2], + compute_timeout_ms: u32, + async_submit: bool, +} + +impl QueueArgs { + fn build( + &self, + reg_data: &driver::AsahiRegData<'_>, + usage: Arc, + ) -> Result> { + let mut queue = reg_data.gpu.new_queue( + self.vm.clone(), + self.ualloc.clone(), + self.ualloc_priv.clone(), + self.priority, + self.usc_exec_base, + usage, + )?; + queue.reserve_render_scs(self.render_scs_layout)?; + if self.compute_timeout_ms != 0 { + queue.set_compute_timeout(self.compute_timeout_ms)?; + } + if self.async_submit { + queue.set_async_submit()?; + } + Ok(queue) + } +} + impl TableQueue { + /// Builds the queue again on its VM where the firmware kept the VM but not the queue. + fn rebuild_if_needed( + &mut self, + reg_data: &driver::AsahiRegData<'_>, + usage: Arc, + ) -> Result { + if !self.queue.needs_rebuild() { + return Ok(()); + } + let queue = self.created.build(reg_data, usage)?; + // The earlier queue goes here, with nothing in flight: the firmware that held it is gone. + drop(core::mem::replace(&mut self.queue, queue)); + Ok(()) + } + /// Maximum command-buffer capacity retained on a queue between submissions. const REUSE_CMDBUF_CAP: usize = 4096; @@ -2011,12 +2066,13 @@ impl File { let _ = file_vm; core::mem::drop(guard); + // TODO: Plumb deeper the enum + let priority = uapi::drm_asahi_priority_DRM_ASAHI_PRIORITY_REALTIME - data.priority; let mut queue = reg_data.gpu.new_queue( - vm, - ualloc, - ualloc_priv, - // TODO: Plumb deeper the enum - uapi::drm_asahi_priority_DRM_ASAHI_PRIORITY_REALTIME - data.priority, + vm.clone(), + ualloc.clone(), + ualloc_priv.clone(), + priority, data.usc_exec_base, file.inner().usage.clone(), )?; @@ -2025,14 +2081,27 @@ impl File { if data.compute_timeout_ms != 0 { data.compute_timeout_ms = queue.set_compute_timeout(data.compute_timeout_ms)?; } - if data.flags & uapi::drm_asahi_queue_create_flags_DRM_ASAHI_QUEUE_CREATE_ASYNC_SUBMIT != 0 { + let async_submit = + data.flags & uapi::drm_asahi_queue_create_flags_DRM_ASAHI_QUEUE_CREATE_ASYNC_SUBMIT != 0; + if async_submit { queue.set_async_submit()?; } + let created = QueueArgs { + vm, + ualloc, + ualloc_priv, + priority, + usc_exec_base: data.usc_exec_base, + render_scs_layout: data.render_scs_layout, + compute_timeout_ms: data.compute_timeout_ms, + async_submit, + }; data.queue_id = resv.index().try_into()?; resv.fill(Arc::pin_init( new_mutex!(TableQueue { queue, + created, cmdbuf: KVVec::new(), _share: share, }), @@ -2179,6 +2248,10 @@ impl File { let objects = file.inner().objects(); let mut guard = queue.lock(); + if let Err(e) = guard.rebuild_if_needed(reg_data, file.inner().usage.clone()) { + guard.return_cmdbuf(cmdbuf); + return Err(e); + } let ret = guard.queue.submit( reg_data, id, diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 65bf2e05aeecf..5319a562ecc03 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -2828,6 +2828,10 @@ pub(crate) struct Backend { preempt_bytes: usize, } +/// g14 (27.2) has not opted into hibernation-restore containment; it keeps +/// its current behaviour via the no-op default. +impl crate::gpu::HibRestoreContain for Backend {} + impl Backend { /// Takes over the running firmware after the boot job. #[allow(clippy::too_many_arguments)] diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 1b81177e6854c..f0c913937b631 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -497,6 +497,10 @@ impl Gpu { } } +/// g16 has not opted into hibernation-restore containment; it keeps its +/// current behaviour via the no-op default. +impl crate::gpu::HibRestoreContain for Gpu {} + /// # Safety /// /// `dev` must be a device this driver is bound to, as for a PM core callback. diff --git a/drivers/gpu/drm/asahi/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index fcb5344944ce9..b9484c63e0f19 100644 --- a/drivers/gpu/drm/asahi/g17/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/buffer.rs @@ -77,6 +77,22 @@ impl BufferIds { self.next_token = token + 1; token } + /// All identities free and the returned stack rebuilt, as in [`Self::new`]. + /// `next_token` is left alone so a token is never reused while a late + /// drop could still name it. + pub(crate) fn reset_to_probe(&mut self) { + for (index, entry) in self.entries.iter_mut().enumerate() { + *entry = BufferId { + references: 0, + owner: false, + token: 0, + bound: None, + }; + self.returned[index] = (BUFFER_IDS - index - 1) as u8; + } + self.returned_count = BUFFER_IDS; + } + pub(crate) fn allocate_render(&mut self) -> Result<(u8, u64)> { let id = if self.returned_count != 0 { self.returned_count -= 1; @@ -391,7 +407,15 @@ fn alias_in( prot: mmu::Prot, guard: usize, ) -> Result { + let need = source + .end + .checked_sub(source.start) + .and_then(|n| n.checked_add(guard)) + .ok_or(EOVERFLOW)? as u64; for range in ranges.iter().cloned() { + if range.end.saturating_sub(range.start) < need { + continue; + } match object.map_range(vm, source.clone(), range, align, prot, guard) { Ok(mapping) => return Ok(mapping), Err(error) if error == ENOSPC => {} @@ -967,6 +991,11 @@ impl Manager { pub(crate) fn mark_initialized(&mut self) { self.initialized = true; } + + /// The firmware booted cold and holds no manager: the next tiling pass initializes it again. + pub(crate) fn forget_firmware(&mut self) { + self.initialized = false; + } pub(crate) fn buffer_id(&self) -> u8 { self.buffer_id } diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 0ab365a54a989..b310126f05529 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -558,6 +558,29 @@ impl Context { pub(crate) fn status(&self) -> &Arc { &self.status } + + /// The firmware this context's VM was created for is gone + /// ([`crate::mmu::Vm::outlived_firmware`]). Its client is told, once, that the + /// device was lost, as after a restart. + pub(crate) fn outlived_firmware(&self) -> bool { + let outlived = self.vm().outlived_firmware(); + if !outlived && self.execution.outlived_firmware() { + // The VM is kept and the queue is built again before it runs anything + // ([`Self::needs_rebuild`]); nothing of this context runs any more. + return true; + } + if outlived && self.status.get() == 0 { + self.status.record(EIO); + } + outlived + } + /// The firmware booted afresh and kept this context's VM: the queue goes on with a new + /// context on the same VM ([`crate::queue::Queue::needs_rebuild`]). + pub(crate) fn needs_rebuild(&self) -> bool { + self.status.get() == 0 + && !self.vm().outlived_firmware() + && self.execution.outlived_firmware() + } pub(crate) fn id(&self) -> u32 { self.execution.id() } diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index e68551713e831..3c9f55903a18c 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -106,10 +106,14 @@ impl RenderIds { Err(_) => {} } } - let claim = state.leases.claim(cell.owner, |_| false).map_err(|error| match error { - render_ids::Error::Busy | render_ids::Error::PendingRelease => ENOSPC, - render_ids::Error::Overflow => EOVERFLOW, - _ => EIO, + let claim = state.leases.claim(cell.owner, |_| false).map_err(|error| { + let err = match error { + render_ids::Error::Busy | render_ids::Error::PendingRelease => ENOSPC, + render_ids::Error::Overflow => EOVERFLOW, + _ => EIO, + }; + + err })?; let index = usize::from(claim.lease.slot - render_ids::FIRST); state.cells[index] = Some(cell.clone()); @@ -1526,6 +1530,23 @@ impl RenderIds { self.used[0].load(Ordering::Acquire).count_ones() + (self.used[1].load(Ordering::Acquire) & !(1u64 << 63)).count_ones() } + + /// The firmware is stopped and every pair that named a lease is gone. + /// Leftover cells re-claim on the next pin; stale pins fail with StaleLease. + pub(crate) fn reset_to_probe(&self) { + let mut state = self.state.lock(); + let cells = core::mem::replace( + &mut state.cells, + [const { None }; render_ids::COUNT], + ); + state.leases = render_ids::State::new(); + self.used[0].store(0, Ordering::Release); + self.used[1].store(1u64 << 63, Ordering::Release); + drop(state); + drop(cells); + self.available.notify(); + } + } #[kunit_tests(asahi_g17_render_id_capacity)] diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 499359d3d4559..c8cbe9b6e3d00 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -217,6 +217,66 @@ pub(super) struct InitData { render_pages: Option, render_runs: Option, render_blocks: core::ops::Range, + reuse: Reuse, +} + +/// What an earlier build mapped, for a rebuild to fill again in the same order: a firmware +/// booted again on the same session finds every object at the address it had, and every alias +/// a client address space holds of one stays valid. Both lists are kept last-first. +struct Reuse { + active: bool, + objects: KVec, + aliases: KVec, +} + +impl Reuse { + const fn new() -> Self { + Self { active: false, objects: KVec::new(), aliases: KVec::new() } + } + + /// The next object of the earlier build, emptied, if this build reuses one. It has to be + /// the one this step asks for. + fn object( + &mut self, + matches: impl FnOnce(&KernelObject) -> bool, + ) -> Result> { + self.object_as(matches, false) + } + + /// [`Self::object`], keeping its contents when `keep`: firmware-owned counters the host's + /// queues go on from. + fn object_as( + &mut self, + matches: impl FnOnce(&KernelObject) -> bool, + keep: bool, + ) -> Result> { + if !self.active { + return Ok(None); + } + let mut object = self.objects.pop().ok_or(EINVAL)?; + if !matches(&object) { + return Err(EINVAL); + } + if !keep { + object.bytes_mut().fill(0); + } + Ok(Some(object)) + } + + /// The next alias of the earlier build, if this build reuses one. + fn alias( + &mut self, + matches: impl FnOnce(&mmu::KernelMapping) -> bool, + ) -> Result> { + if !self.active { + return Ok(None); + } + let alias = self.aliases.pop().ok_or(EINVAL)?; + if !matches(&alias) { + return Err(EINVAL); + } + Ok(Some(alias)) + } } /// Placement inputs shared by the build steps. @@ -229,9 +289,29 @@ struct BuildEnv<'a> { dynamic: Range, /// GPU clusters, as the GPU reports them. clusters: u32, + reuse: core::cell::RefCell, } impl BuildEnv<'_> { + /// [`Self::fixed`] for a page of firmware-owned counters: a rebuild keeps what the earlier + /// firmware wrote there. The host's queues go on from those values (their stamps cover what + /// they published), and a firmware booted again seeds each queue from them. + fn fixed_kept( + &self, + offset: u64, + size: usize, + prot: mmu::Prot, + cpu: CpuMap, + ) -> Result { + let va = self.base + offset; + if let Some(object) = + self.reuse.borrow_mut().object_as(|o| o.gpu_va() == va && o.size() == size, true)? + { + return Ok(object); + } + self.fixed(offset, size, prot, cpu) + } + /// An object at a fixed offset of the kernel window. fn fixed( &self, @@ -240,10 +320,16 @@ impl BuildEnv<'_> { prot: mmu::Prot, cpu: CpuMap, ) -> Result { + let va = self.base + offset; + if let Some(object) = + self.reuse.borrow_mut().object(|o| o.gpu_va() == va && o.size() == size)? + { + return Ok(object); + } KernelObject::new( self.dev, self.vm, - Placement::At(self.base + offset), + Placement::At(va), size, prot, cpu, @@ -258,6 +344,11 @@ impl BuildEnv<'_> { prot: mmu::Prot, cpu: CpuMap, ) -> Result { + if let Some(object) = self.reuse.borrow_mut().object(|o| { + self.dynamic.contains(&o.gpu_va()) && o.size() == size + })? { + return Ok(object); + } KernelObject::new( self.dev, self.vm, @@ -267,6 +358,34 @@ impl BuildEnv<'_> { cpu, ) } + + /// Backing whose mappings the build installs as aliases. + fn backing(&self, size: usize, cpu: CpuMap) -> Result { + if let Some(object) = + self.reuse.borrow_mut().object(|o| o.gpu_va() == 0 && o.size() == size)? + { + return Ok(object); + } + KernelObject::backing(self.dev, size, cpu) + } + + /// An object at a fixed address of the kernel's lower address space. + fn lower_at(&self, va: u64, size: usize, prot: mmu::Prot, cpu: CpuMap) -> Result { + if let Some(object) = + self.reuse.borrow_mut().object(|o| o.gpu_va() == va && o.size() == size)? + { + return Ok(object); + } + KernelObject::new(self.dev, self.lower, Placement::At(va), size, prot, cpu) + } + + /// The earlier build's alias at `va`, if this build reuses one. + fn reused_alias( + &self, + matches: impl FnOnce(&mmu::KernelMapping) -> bool, + ) -> Result> { + self.reuse.borrow_mut().alias(matches) + } } /// Object indices the firmware-object initialization needs from the table step. @@ -327,9 +446,28 @@ impl InitData { render_pages: None, render_runs: None, render_blocks: 0..0, + reuse: Reuse::new(), } } + /// Empties the graph for [`Self::build`] to fill again on the same objects and aliases, for + /// firmware booted again on this session. The compute backing and scheduler stay, and the + /// rebuild publishes them again. + pub(super) fn prepare_rebuild(&mut self) { + let mut next = Self::new(); + let mut objects = core::mem::replace(&mut self.objects, KVec::new()); + let mut aliases = core::mem::replace(&mut self.aliases, KVec::new()); + objects.reverse(); + aliases.reverse(); + next.reuse = Reuse { active: true, objects, aliases }; + next.compute_shared = self.compute_shared.take(); + next.compute_scheduler = self.compute_scheduler.take(); + *self = next; + } + + /// Addresses the rebuild keeps and later publishes again. Other kernel-window + /// objects can be cleared before a firmware cold boot. + pub(super) fn pm_metrics_va(&self) -> u64 { self.pm_metrics_va } @@ -386,6 +524,96 @@ impl InitData { ]) } + /// After the firmware boots afresh, every QID's completion stamps move one sequence step + /// (`1 << 8`) past anything the earlier firmware wrote, as the firmware's own restart does. + /// Work-ring cursors, ring slots and the firmware recovery word in kept + /// cluster/bundle objects, set back to the values a fresh probe leaves + /// after allocation (zeros) so a cold boot does not sample pre-image + /// producers or a leftover recovery flag. Outer-credit accounting is + /// dropped; `build` installs a new one. + pub(super) fn reset_publication_to_probe(&mut self) -> Result { + use super::fw::{channels, queue::DataMaster, queue::Policy}; + if self.objects.is_empty() || self.cluster >= self.objects.len() + || self.bundle >= self.objects.len() + { + return Ok(()); + } + if let Some(word) = self + .object(self.cluster) + .ok() + .and_then(|object| object.word(self.recovery_state_offset()).ok()) + { + word.store(0, Ordering::Relaxed); + } + for role in [Role::Primary, Role::Secondary] { + for priority in 0..Policy::PRIORITIES { + for engine in [DataMaster::Compute, DataMaster::Tiling, DataMaster::Fragment] { + let Some(channel) = channels::work_ring_index(priority, engine) else { + continue; + }; + let base = self.state_offset(role) + abi::work_state_offset(channel); + if let Ok(state) = self.object(self.cluster) { + for offset in [ + abi::ChannelState::CONSUMER, + abi::ChannelState::UNK_10, + abi::ChannelState::PRODUCER, + ] { + if let Ok(word) = state.word(base + offset) { + word.store(0, Ordering::Relaxed); + } + } + } + } + } + } + for priority in 0..Policy::PRIORITIES { + for engine in [DataMaster::Compute, DataMaster::Tiling, DataMaster::Fragment] { + let Some(channel) = channels::work_ring_index(priority, engine) else { + continue; + }; + let offset = self.work_ring_offset(channel); + let bytes = channels::WORK_RING_SLOTS as usize + * core::mem::size_of::(); + if let Ok(bundle) = self.object_mut(self.bundle) { + let memory = bundle.bytes_mut(); + if offset.checked_add(bytes).is_some_and(|end| end <= memory.len()) { + memory[offset..offset + bytes].fill(0); + } + } + } + } + self.outer_credits = None; + Ok(()) + } + + pub(super) fn reseed_stamps(&mut self) -> Result { + for index in self.stamps { + { + let page = self.object(index)?; + for qid in 0..=usize::from(super::fw::kick::QID_MAX) { + // Single 32-bit accesses: the page isn't cacheable, + // so no atomic read-modify-write. + let word = page.word(qid * core::mem::size_of::())?; + word.store( + word.load(Ordering::Relaxed).wrapping_add(1 << 8), + Ordering::Relaxed, + ); + } + } + // These pages also hold firmware-owned descriptor state that a + // fresh boot finds clear. Keep only the stamp words, as the + // firmware's own restart does, and clear the rest. + let stamp_bytes = + (usize::from(super::fw::kick::QID_MAX) + 1) * core::mem::size_of::(); + let bytes = self.object_mut(index)?.bytes_mut(); + if bytes.len() > stamp_bytes { + bytes[stamp_bytes..].fill(0); + } + } + fence(Ordering::SeqCst); + Ok(()) + } + /// The caller reads both engine lanes before its acquire fence. Page A is the completed /// GPU-maintenance witness; page B stays under firmware ownership. pub(super) fn stamp(&self, qid: u8) -> Result<&AtomicU32> { @@ -525,6 +753,28 @@ impl InitData { if self.compute_shared.is_some() { return Ok(()); } + self.publish_compute_shared()?; + self.compute_shared = Some(shared); + Ok(()) + } + + /// After a rebuild: the compute backing and scheduler kept from before, published again. + fn republish_compute(&mut self) -> Result { + if self.compute_shared.is_some() { + self.publish_compute_shared()?; + } + if let Some(scheduler) = self.compute_scheduler.as_mut() { + scheduler.object.bytes_mut().fill(0); + scheduler.object.initialize::(0, |state| { + state.init(); + Ok(()) + })?; + fence(Ordering::SeqCst); + } + Ok(()) + } + + fn publish_compute_shared(&mut self) -> Result { let boot_control = self.boot_control.ok_or(ENODEV)?; let boot_state = self.boot_state.ok_or(ENODEV)?; let state_va = self.object(boot_state)?.gpu_va(); @@ -541,7 +791,6 @@ impl InitData { self.object_mut(boot_control)?.write(0, control)?; self.object_mut(boot_state)?.bytes_mut().fill(0); fence(Ordering::SeqCst); - self.compute_shared = Some(shared); Ok(()) } @@ -1099,6 +1348,8 @@ impl InitData { self.objects.get(index).ok_or(EINVAL) } + + fn object_mut(&mut self, index: usize) -> Result<&mut KernelObject> { self.objects.get_mut(index).ok_or(EINVAL) } @@ -1115,6 +1366,23 @@ impl InitData { Ok(()) } + /// [`Self::alias`] for a build step, which takes the earlier build's alias on a rebuild. + fn alias_in_build( + &mut self, + env: &BuildEnv<'_>, + index: usize, + vm: &mmu::Vm, + va: u64, + prot: mmu::Prot, + ) -> Result { + let alias = match env.reused_alias(|a| a.iova() == va)? { + Some(alias) => alias, + None => self.object_mut(index)?.map_alias(vm, va, prot)?, + }; + self.aliases.push(alias, GFP_KERNEL)?; + Ok(()) + } + /// Constructs the graph after the firmware has published the high-root entries. #[expect( clippy::too_many_arguments, @@ -1143,19 +1411,42 @@ impl InitData { base: range.start, dynamic: t8140::dynamic::upper(range.clone()), clusters, + reuse: core::cell::RefCell::new(core::mem::replace(&mut self.reuse, Reuse::new())), }; + let rebuild = env.reuse.borrow().active; + self.build_graph(&env, dev, cfg, metrics, active_cores, variant)?; + let left = env.reuse.into_inner(); + if !left.objects.is_empty() || !left.aliases.is_empty() { + return Err(EINVAL); + } + if rebuild { + self.republish_compute()?; + } + Ok(()) + } + + fn build_graph( + &mut self, + env: &BuildEnv<'_>, + dev: &AsahiDrmDevice, + cfg: &Config, + metrics: &KernelObject, + active_cores: u32, + variant: &super::fw::Variant, + ) -> Result { + let clusters = env.clusters; if variant.graph == super::fw::variant::InitGraph::V25G83 { - return self.build_25g83(&env, cfg, metrics, active_cores, variant); + return self.build_25g83(env, cfg, metrics, active_cores, variant); } (self.active_effort, self.coarse_base_opp) = active_effort(&Self::opps(dev, cfg.opps, clusters)?, cfg.perf()?)?; - self.map_register_windows(&env, cfg.windows)?; - let tables = self.build_descriptor_tables(&env, abi::private::SIZE)?; - self.build_render_free_lists(&env)?; - let first_block = self.build_render_pool(&env)?; - self.build_compute_pools(&env, first_block)?; - let bundle = self.build_bundle(&env, cfg, metrics)?; - self.initialize_firmware_objects(&env, cfg, &tables, &bundle) + self.map_register_windows(env, cfg.windows)?; + let tables = self.build_descriptor_tables(env, abi::private::SIZE)?; + self.build_render_free_lists(env)?; + let first_block = self.build_render_pool(env)?; + self.build_compute_pools(env, first_block)?; + let bundle = self.build_bundle(env, cfg, metrics)?; + self.initialize_firmware_objects(env, cfg, &tables, &bundle) } fn map_register_windows( @@ -1166,6 +1457,10 @@ impl InitData { for window in windows { for instance in 0..window.instances { let (phys, va, size) = window.mapping(instance).ok_or(EINVAL)?; + if let Some(alias) = env.reused_alias(|a| a.iova() == va)? { + self.aliases.push(alias, GFP_KERNEL)?; + continue; + } self.aliases.push( env.vm.map_io( env.dev.as_ref().as_ref(), @@ -1209,15 +1504,15 @@ impl InitData { })?; self.pb = pb; self.page_pool = page_pool; - self.alias(pb, env.lower, low::PB_DESCRIPTORS, GS)?; - self.alias(page_pool, env.lower, low::PAGE_POOL_DESCRIPTORS, GS)?; + self.alias_in_build(env, pb, env.lower, low::PB_DESCRIPTORS, GS)?; + self.alias_in_build(env, page_pool, env.lower, low::PAGE_POOL_DESCRIPTORS, GS)?; let index = self.add(env.fixed(high::INDEX, INDEX_SIZE, GFS, WB)?)?; self.object_mut(index)? .initialize::(0, |table| { table.init(); Ok(()) })?; - self.alias(index, env.lower, low::INDEX, GFS)?; + self.alias_in_build(env, index, env.lower, low::INDEX, GFS)?; let fwctl = self.add(env.fixed(high::FWCTL, abi::FWCTL_SIZE, FS, WB)?)?; Ok(DescriptorTables { pb, @@ -1268,8 +1563,10 @@ impl InitData { self.boot_state = Some(state); } } - self.stamps[0] = self.add(env.fixed(high::DESCRIPTOR_PAGE_A, mmu::UAT_PGSZ, FS, WC)?)?; - self.stamps[1] = self.add(env.fixed(high::DESCRIPTOR_PAGE_B, mmu::UAT_PGSZ, FP, WC)?)?; + self.stamps[0] = self.add(env.fixed_kept( + high::DESCRIPTOR_PAGE_A, mmu::UAT_PGSZ, FS, WC)?)?; + self.stamps[1] = self.add(env.fixed_kept( + high::DESCRIPTOR_PAGE_B, mmu::UAT_PGSZ, FP, WC)?)?; self.add(env.fixed(high::TA_CONTEXT, CONTEXT_SIZE, FS, WC)?)?; self.add(env.fixed(high::FRAGMENT_CONTEXT, CONTEXT_SIZE, FS, WC)?)?; Ok(()) @@ -1280,11 +1577,7 @@ impl InitData { fn build_render_pool(&mut self, env: &BuildEnv<'_>) -> Result { use mmu::PROT_GPU_SHARED_RW as GS; use CpuMap::WriteBack as WB; - let pages = self.add(KernelObject::backing( - env.dev, - low::RENDER_PAGE_LIST_SIZE, - WB, - )?)?; + let pages = self.add(env.backing(low::RENDER_PAGE_LIST_SIZE, WB)?)?; self.object_mut(pages)? .initialize::<[u64; low::RENDER_PAGE_LIST_SIZE / 8]>(0, |list| { abi::fill_page_list( @@ -1292,26 +1585,19 @@ impl InitData { (0..low::RENDER_BLOCKS_INITIAL as usize).map(low::render_block), ) })?; - let runs = self.add(KernelObject::backing( - env.dev, - low::RENDER_RUN_LIST_SIZE, - WB, - )?)?; + let runs = self.add(env.backing(low::RENDER_RUN_LIST_SIZE, WB)?)?; let first_block = self.objects.len(); for _ in 0..low::RENDER_BLOCKS_ALLOCATED { - self.add(KernelObject::backing( - env.dev, - abi::FREE_LIST_BLOCK_SIZE, - WB, - )?)?; + self.add(env.backing(abi::FREE_LIST_BLOCK_SIZE, WB)?)?; } self.render_pages = Some(pages); self.render_runs = Some(runs); self.render_blocks = first_block..self.objects.len(); - self.alias(pages, env.render, low::RENDER_PAGE_LIST, GS)?; - self.alias(runs, env.render, low::RENDER_RUN_LIST, GS)?; + self.alias_in_build(env, pages, env.render, low::RENDER_PAGE_LIST, GS)?; + self.alias_in_build(env, runs, env.render, low::RENDER_RUN_LIST, GS)?; for block in 0..low::RENDER_BLOCKS_MAPPED { - self.alias( + self.alias_in_build( + env, first_block + block, env.render, low::render_block(block), @@ -1342,17 +1628,11 @@ impl InitData { state_va: env.base + high::COMPUTE_FREE_LIST_STATE, }), )?; - let compute_state = self.add(KernelObject::backing(env.dev, mmu::UAT_PGSZ, WB)?)?; + let compute_state = self.add(env.backing(mmu::UAT_PGSZ, WB)?)?; self.object_mut(compute_state)? .write(0, abi::FreeListState::COMPUTE)?; - let compute_runs = self.add(KernelObject::new( - env.dev, - env.lower, - Placement::At(low::COMPUTE_RUN_LIST), - mmu::UAT_PGSZ, - GFS, - WC, - )?)?; + let compute_runs = + self.add(env.lower_at(low::COMPUTE_RUN_LIST, mmu::UAT_PGSZ, GFS, WC)?)?; self.object_mut(compute_runs)? .initialize::<[abi::FreeListRunSlot; mmu::UAT_PGSZ / 0x40]>(0, |list| { abi::fill_run_list(list, low::COMPUTE_FREE_LIST_BLOCKS) @@ -1411,7 +1691,7 @@ impl InitData { let offset = high::BUNDLE + abi::bundle::COMPLETION_RINGS[slot] as u64; let ring = self.add(env.fixed(offset, abi::COMPLETION_RING_SIZE, FP, WB)?)?; self.completion_rings[slot] = Some(ring); - self.alias(ring, env.lower, low::COMPLETION_RINGS[slot], GS)?; + self.alias_in_build(env, ring, env.lower, low::COMPLETION_RINGS[slot], GS)?; *completion_ring = abi::CompletionRing { low_va: low::COMPLETION_RINGS[slot], high_va: env.base + offset, @@ -1420,8 +1700,15 @@ impl InitData { let qos = self.add(env.dynamic(abi::QOS_SIZE, mmu::UAT_PGSZ as u64, FS, WC)?)?; self.qos = qos; fence(Ordering::SeqCst); - let metrics_alias = - metrics.alias_in(env.vm, env.dynamic.clone(), cfg.pm_metrics()?.size as u64, GFS)?; + let metrics_alias = match env.reused_alias(|a| env.dynamic.contains(&a.iova()))? { + Some(alias) => alias, + None => metrics.alias_in( + env.vm, + env.dynamic.clone(), + cfg.pm_metrics()?.size as u64, + GFS, + )?, + }; self.metrics_fw_va = metrics_alias.iova(); self.aliases.push(metrics_alias, GFP_KERNEL)?; fence(Ordering::SeqCst); diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 7f365425f5d78..9bf88b4ed3afb 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -93,22 +93,38 @@ pub(crate) struct QueueIds { leased: usize, /// First QID the host may use ([`crate::g17::fw::Variant::qid_floor`]). floor: usize, + /// Floor at probe; restored by [`Self::reset_to_probe`]. + probe_floor: usize, } impl QueueIds { pub(crate) fn new(floor: usize) -> impl Init { + let probe_floor = floor; kernel::try_init!(Self { entries <- pin_init::init_array_from_fn(|_| None), initial_render: [None; 2], leased: 0, // The reserve must keep render capacity above the floor. - floor: if floor < FULL_RENDER_RESERVE { floor } else { return Err(EINVAL) }, + floor: if probe_floor < FULL_RENDER_RESERVE { probe_floor } else { return Err(EINVAL) }, + probe_floor, }) } /// Keep the initial render reservations until another engine needs their /// capacity. No graph receives these tokens, so an unpublished reservation /// can be replaced without changing an installed physical channel. + /// Release every identity, then take the same bootstrap reservations as + /// [`QueueIds::new`] followed by [`Self::reserve_initial_render`]. + pub(crate) fn reset_to_probe(&mut self) -> Result { + for slot in self.entries.iter_mut() { + *slot = None; + } + self.initial_render = [None; 2]; + self.leased = 0; + self.floor = self.probe_floor; + self.reserve_initial_render() + } + pub(crate) fn reserve_initial_render(&mut self) -> Result { if self.leased != 0 { return Err(EINVAL); @@ -302,6 +318,27 @@ impl QueueIds { _ => Err(EINVAL), } } + + /// Frees a physical identity, published or not, so a cold firmware boot can + /// allocate the slot again for a new queue. Idempotent if the slot is already empty. + pub(crate) fn release(&mut self, id: Id) -> Result { + let index = usize::from(id.qid); + let slot = self.entries.get_mut(index).ok_or(EINVAL)?; + match slot { + Some(entry) if entry.id == id => { + *slot = None; + self.leased = self.leased.saturating_sub(1); + for token in &mut self.initial_render { + if token.is_some_and(|token| token == id) { + *token = None; + } + } + Ok(()) + } + None => Ok(()), + _ => Err(EINVAL), + } + } } #[kunit_tests(asahi_g17_qid_accounting)] @@ -562,6 +599,21 @@ impl RenderRings { core::mem::forget(rejected); } } + + /// Local-only release after `retire_for_cold_boot`: drop every stocked + /// kick ring so its lower alias, range and backing are freed. The firmware + /// is already stopped, so no teardown command is sent. Written rings + /// otherwise stay mapped in the kernel-lower window for the life of the + /// device, and a new `Queue::render` hits EBUSY on the occupied alias. + pub(crate) fn release_for_cold_boot(&self) { + let mut stock = self.stock.lock(); + let retired = core::mem::replace(&mut stock.retired, KVec::new()); + stock.created = 0; + drop(stock); + // Firmware is already stopped: unmap + TLBI (via KernelMapping::drop) + // before the drm_mm node is freed. + drop(retired); + } } /// Storage lent to one render ring; returned to the stock when the ring drops. @@ -677,16 +729,19 @@ impl Queue { .prepare_alias(client, address, CLIENT_KICK_PROT, false); // On failure, or if `client` still had a view of the pages, the storage returns to // the stock and a fresh ring is built. - if let Ok(Some(alias)) = alias { - return Ok(( - Self { - backing: Backing::Render(ring), - id, - timestamp: KickTimestamp::FIRST, - previous: None, - }, - Some(alias), - )); + match alias { + Ok(Some(alias)) => { + return Ok(( + Self { + backing: Backing::Render(ring), + id, + timestamp: KickTimestamp::FIRST, + previous: None, + }, + Some(alias), + )); + } + Ok(None) | Err(_) => {} } } let (vm, status) = (client.id(), client.status().cloned()); @@ -701,23 +756,28 @@ impl Queue { )?; let mut range = alloc.uat.kernel_lower_dynamic_range(); let (low, client) = loop { - let low = high.alias_in( - alloc.uat.kernel_lower_vm(), - range.clone(), - mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_SHARED_RW, - )?; + let low = high + .alias_in( + alloc.uat.kernel_lower_vm(), + range.clone(), + mmu::UAT_PGSZ as u64, + mmu::PROT_GPU_SHARED_RW, + )?; let end = low .iova() .checked_add(KICK_RING_SIZE as u64) - .ok_or(EOVERFLOW)?; + .ok_or_else(|| { + EOVERFLOW + })?; match high.map_alias(client, low.iova(), CLIENT_KICK_PROT) { Ok(client) => break (low, client), Err(error) if error == ENOSPC && end < range.end => { drop(low); range.start = end; } - Err(error) => return Err(error), + Err(error) => { + return Err(error); + } } }; let storage = RenderStorage { low, high, vm, status }; diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 1466bb6c99db9..a8167ab56a47d 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -256,6 +256,10 @@ pub(crate) struct Config { /// The firmware's warm restart across a system sleep is known for this SoC. Otherwise the /// driver refuses a sleep that powers the SoC down. pub(crate) sleep_restart: bool, + /// A cold firmware boot on a restored hibernation image keeps the clients: their VMs carry + /// over, and each queue is built again on its VM before its next submission. Otherwise + /// every pre-image client sees a lost device. + pub(crate) hib_keep_clients: bool, /// The SoC's values of region C; `None` where the firmware graph has its own (M5). pub(crate) region_c: Option<&'static fw::initdata::RegionCConfig>, pub(crate) chip: Option<&'static fw::initdata::v25g83::Chip>, @@ -842,6 +846,9 @@ struct Firmware { init: initdata::InitData, _render_global: mmu::Vm, _pm_metrics: Arc, + /// Translation memory a hibernation image needs to boot the firmware again: + /// `Some` from `.freeze` until `.thaw` or `.restore` ([`sleep`]). + hib: Option, uat: Arc, } @@ -873,6 +880,28 @@ impl Drop for Firmware { } impl Firmware { + /// Parks every running instance before its CPU stops: the AP side goes + /// quiesced and the firmware to sleep, each acknowledged. An instance that + /// does not answer in time only gets a warning: its CPU stops anyway. + fn park(&mut self) { + let dev = self.primary.state.shared.dev.clone(); + for role in [Role::Secondary, Role::Primary] { + let coprocessor = match role { + Role::Primary => &mut self.primary, + Role::Secondary => match self.secondary.as_mut() { + Some(secondary) => secondary, + None => continue, + }, + }; + if !coprocessor.running { + continue; + } + if let Err(error) = coprocessor.rtkit.with(|rtkit| rtkit.shutdown()) { + dev_warn!(dev.as_ref(), "GPU firmware {:?} did not park: {:?}\n", role, error); + } + } + } + /// The firmware's fixed timestamp window, on the older firmware graph; `None` on M5's graph. fn timestamp_window(&self) -> Option> { (!self.uat.is_m5()).then_some(hw::t8140::dynamic::TIMESTAMP_WINDOW) @@ -1747,6 +1776,8 @@ static BELOW_FULL_COUNT: AtomicU32 = AtomicU32::new(0); pub(crate) unsafe fn init() { // SAFETY: Single-call module initialization invariant upheld by caller. unsafe { EFFORT_TARGETS.init() }; + // SAFETY: As above. + unsafe { sleep::init() }; } fn register_effort_target(shared: &Arc) { @@ -1863,6 +1894,21 @@ impl Shared { self.queue_event_records(); } + /// After a hibernation cold boot: the freeze path cancelled the poll, idle + /// and housekeeping timers and the rescan hrtimer. Re-arm them the way a + /// fresh probe does after `queue_events`. + fn rearm_after_cold_boot(self: &Arc) { + self.housekeeping_ns.store(0, Ordering::Release); + self.cancel_rescan(); + self.queue_events(); + self.queue_poll(); + self.queue_housekeeping(1_000_000); + // wait_render_busy blocks on this same Availability. Advance it after + // the cold boot so a sample taken against the pre-image generation does + // not wait for a wakeup that belongs to the old epoch. + self.renders.notify(); + } + /// Queues the event worker for firmware records alone: completions, or records that arrived /// during a pass. The pass skips the housekeeping that nothing needs (see /// `runtime_event_turn`). Callable from any context. @@ -2126,6 +2172,8 @@ impl Gpu { cfg: &'static Config, regs: regs::G17Resources, ) -> Result> { + // A probe after an unbind finds the domain off. + sleep::power_for_probe(pdev.as_ref())?; let id = regs.get_g17_id()?; let active_cores: u32 = id.core_masks.iter().map(|mask| mask.count_ones()).sum(); let (variant, build_cfg) = @@ -2723,6 +2771,7 @@ impl Gpu { init: initdata::InitData::new(), _render_global: render_global, _pm_metrics: session_metrics, + hib: None, uat, }), GFP_KERNEL, @@ -2931,6 +2980,7 @@ impl Gpu { init: initdata::InitData::new(), _render_global: render_global, _pm_metrics: Arc::new(pm_metrics, GFP_KERNEL)?, + hib: None, uat, }), GFP_KERNEL, diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index fe6230f1c8891..f3f0eefc83f47 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -249,6 +249,12 @@ impl Drop for OuterClaim<'_> { } impl Port { + /// Moves the memory-demand provider out, for the port that replaces this one. + pub(super) fn take_demand(&self) -> super::power::Demand { + self.demand.set_active(false); + self.demand.take() + } + pub(super) fn new( demand: super::power::Demand, feed: Arc, diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index f28545fc8f4c9..c7aeb66b2d325 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -1255,7 +1255,7 @@ unsafe extern "C" { /// DT-selected memory-demand provider. Its independent allocation outlives a /// detached provider; a device link orders supplier removal and suspend. -pub(super) struct Demand(*mut core::ffi::c_void); +pub(super) struct Demand(core::sync::atomic::AtomicPtr); // SAFETY: the provider's leaf spinlock serializes all access; no GPU callback. unsafe impl Send for Demand {} @@ -1270,40 +1270,57 @@ impl Demand { if ret < 0 { Err(kernel::error::Error::from_errno(ret)) } else { - Ok(Self(out)) + Ok(Self(core::sync::atomic::AtomicPtr::new(out))) } } + /// Moves the provider reference out, leaving this one without a provider. Taking a new + /// reference isn't possible while devices resume: it adds a device link. + pub(super) fn take(&self) -> Self { + Self(core::sync::atomic::AtomicPtr::new( + self.0.swap(core::ptr::null_mut(), core::sync::atomic::Ordering::AcqRel), + )) + } + + fn ptr(&self) -> *mut core::ffi::c_void { + self.0.load(core::sync::atomic::Ordering::Acquire) + } + pub(super) fn has_provider(&self) -> bool { - !self.0.is_null() + !self.ptr().is_null() } pub(super) fn set_active(&self, active: bool) { // SAFETY: the retained reference is live; NULL denotes no DT provider. - unsafe { asahi_clpc_gpu_set_active(self.0, active) }; + unsafe { asahi_clpc_gpu_set_active(self.ptr().cast(), active) }; } pub(super) fn set_busy(&self, permille: u32) { // SAFETY: the retained reference is live; NULL denotes no DT provider. - unsafe { asahi_clpc_gpu_set_busy(self.0, permille.min(1000) as core::ffi::c_uint) }; + unsafe { + asahi_clpc_gpu_set_busy( + self.ptr().cast(), + permille.min(1000) as core::ffi::c_uint, + ) + }; } pub(super) fn clear_busy(&self) { // SAFETY: the retained reference is live; NULL denotes no DT provider. - unsafe { asahi_clpc_gpu_clear_busy(self.0) }; + unsafe { asahi_clpc_gpu_clear_busy(self.ptr()) }; } /// The power in mW the low-power profile allows the GPU's own budget, 0 for no limit /// (and without a provider). pub(super) fn power_cap_mw(&self) -> u32 { // SAFETY: the retained reference is live; NULL denotes no DT provider. - unsafe { asahi_clpc_gpu_power_cap(self.0) } + unsafe { asahi_clpc_gpu_power_cap(self.ptr()) } } } impl Drop for Demand { fn drop(&mut self) { // SAFETY: releases exactly the reference returned by get, clearing demand first. - unsafe { asahi_clpc_gpu_put(self.0) }; + unsafe { asahi_clpc_gpu_put(self.ptr().cast()) }; } } diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index f593da530fd67..579f2f6121c02 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -15,7 +15,7 @@ use crate::g17::{ job::{Order, Packet}, }; use crate::{hw::t8140::queues as cfg, mmu::MAX_EXECUTION_CONTEXTS}; -use core::sync::atomic::{AtomicU32, Ordering}; +use core::sync::atomic::{AtomicU64, Ordering}; use kernel::{ new_condvar, new_mutex, prelude::*, @@ -1183,7 +1183,7 @@ pub(crate) struct Pool { state: Mutex, #[pin] released: CondVar, - queues: AtomicU32, + queues: AtomicU64, /// Logical queues admitted at most: each must be able to hold a render pair. max_queues: u32, /// Logical-queue creation waiting for a returned slot. @@ -1220,7 +1220,7 @@ impl Pool { pin_init!(Self { state <- new_mutex!(State::with_depth(render_depth), "G17 render admission"), released <- new_condvar!("G17 render pair release"), - queues: AtomicU32::new(0), + queues: AtomicU64::new(0), max_queues, waiters, renders, @@ -1246,7 +1246,64 @@ impl Pool { } /// Logical queues currently counted, including one being created. pub(crate) fn queues(&self) -> u32 { - self.queues.load(Ordering::Acquire) + Self::queue_count(self.queues.load(Ordering::Acquire)) + } + + fn queue_generation(packed: u64) -> u32 { + (packed >> 32) as u32 + } + + fn queue_count(packed: u64) -> u32 { + packed as u32 + } + + fn pack_queues(generation: u32, count: u32) -> u64 { + (u64::from(generation) << 32) | u64::from(count) + } + + /// Bump the logical-queue generation and zero the live count. Pre-restore + /// [`QueueSlot`] guards keep their old generation and neither inflate + /// demand nor subtract from the new counter when they drop. + pub(crate) fn reset_queue_slots_after_cold_boot(&self) { + loop { + let packed = self.queues.load(Ordering::Acquire); + let next = Self::pack_queues(Self::queue_generation(packed).wrapping_add(1), 0); + if self + .queues + .compare_exchange(packed, next, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + return; + } + } + } + + /// Subtract one live queue if `generation` is still current. A retired + /// slot (generation already bumped) is a no-op, including when the count + /// of a later generation is already non-zero. + fn release_queue_count(&self, generation: u32) { + loop { + let packed = self.queues.load(Ordering::Acquire); + if Self::queue_generation(packed) != generation { + return; + } + let count = Self::queue_count(packed); + if count == 0 { + return; + } + if self + .queues + .compare_exchange( + packed, + Self::pack_queues(generation, count - 1), + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() + { + return; + } + } } /// Whether one more logical queue fits, without reserving it. Creators /// check before reserving, so a refusal never returns (and notifies) a slot. @@ -1258,7 +1315,7 @@ impl Pool { /// pairs. pub(crate) fn render_demand(&self, extra_queues: usize) -> usize { let state = self.state.lock(); - let open = self.queues.load(Ordering::Acquire) as usize; + let open = self.queues() as usize; state.pair_demand(open).saturating_add(extra_queues) } /// Whether admitting one more logical queue requires reclaiming a warmed @@ -1271,7 +1328,7 @@ impl Pool { ) -> bool { let state = self.state.lock(); let cap = render_capacity.min(cfg::RENDER_SLOTS - 1); - let open = self.queues.load(Ordering::Acquire) as usize; + let open = self.queues() as usize; let total = state.total_pair_demand(open).saturating_add(1); total > cap && total.saturating_sub(state.reclaimable_siblings_in(reclaimable)) > cap } @@ -1299,9 +1356,10 @@ impl Pool { let mut state = self.state.lock(); state.render_capacity = render_capacity; let cap = render_capacity.min(cfg::RENDER_SLOTS - 1); - let mut count = self.queues.load(Ordering::Acquire); + let mut packed = self.queues.load(Ordering::Acquire); let mut reclaimed = false; loop { + let count = Self::queue_count(packed); if count >= self.max_queues { drop(state); if reclaimed { @@ -1328,19 +1386,20 @@ impl Pool { )); } match self.queues.compare_exchange( - count, - count + 1, + packed, + Self::pack_queues(Self::queue_generation(packed), count + 1), Ordering::AcqRel, Ordering::Acquire, ) { Ok(_) => { + let generation = Self::queue_generation(packed); drop(state); if reclaimed { self.returned(); } - return Ok(QueueSlot { pool: self.clone() }); + return Ok(QueueSlot { pool: self.clone(), generation }); } - Err(current) => count = current, + Err(current) => packed = current, } } } @@ -1353,7 +1412,7 @@ impl Pool { reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>, ) -> Result { let mut state = self.state.lock(); - let open = self.queues.load(Ordering::Acquire) as usize; + let open = self.queues() as usize; let demand = state.pair_demand(open); let (value, room, capacity) = reserve(demand)?; let capacity_grew = capacity > state.render_capacity; @@ -1439,7 +1498,7 @@ impl Pool { } else { state.plan(owner, request, ticket) }; - let open_queues = self.queues.load(Ordering::Acquire) as usize; + let open_queues = self.queues() as usize; if let Some(slot) = state.pick_for(owner, pairs, open_queues, plan) { state.forget_waiter(ticket.take()); let record = @@ -1498,7 +1557,7 @@ impl Pool { return Ok(None); } let plan = state.plan(owner, request, None); - let open_queues = self.queues.load(Ordering::Acquire) as usize; + let open_queues = self.queues() as usize; let Some(slot) = state.pick_for(owner, pairs, open_queues, plan) else { return Ok(None); }; @@ -1520,7 +1579,7 @@ impl Pool { return false; } let plan = state.plan(owner, request, None); - let open_queues = self.queues.load(Ordering::Acquire) as usize; + let open_queues = self.queues() as usize; state.can_pick_render_for(owner, pairs, open_queues, plan) } pub(crate) fn warmable_sibling( @@ -1529,7 +1588,7 @@ impl Pool { publishing: u8, ) -> Option { let mut state = self.state.lock(); - let open_queues = self.queues.load(Ordering::Acquire) as usize; + let open_queues = self.queues() as usize; let candidate = state.warmable_sibling(owner, publishing)?; if !state.can_lease_slot(owner, usize::from(candidate), open_queues) { return None; @@ -1654,6 +1713,28 @@ impl Pool { } } + /// Bring occupancy back to a fresh probe: every pre-restore tenure is over + /// because the firmware is already stopped and the registry has vacated + /// the pairs. Marks those owners released, drops leftover lease accounting, + /// then reuses [`Self::release_retained_owners_after_processor_stop`]. + pub(crate) fn reset_occupancy_after_cold_boot(&self) { + { + let mut state = self.state.lock(); + for slot in 1..cfg::RENDER_SLOTS { + if state.owners[slot] != 0 { + state.released |= 1u64 << slot; + } + } + state.active = 0; + state.refs = [0; cfg::RENDER_SLOTS]; + state.killed_at = [0; cfg::RENDER_SLOTS]; + state.drained = 0; + state.footprints = KVec::new(); + } + self.release_retained_owners_after_processor_stop(); + self.reset_queue_slots_after_cold_boot(); + } + /// Under the device mutex, each time the runtime puts a pair back: `held` while no other /// owner can bind the pair in `slot` (`render_hold` in the runtime). Set before that pass's /// retirements drop their leases, and before a closing owner's slots are released, so the @@ -1842,19 +1923,23 @@ mod accounting_tests { leases.push(pool.reserve_queue().unwrap(), GFP_KERNEL).unwrap(); } assert!(matches!(pool.reserve_queue(), Err(ENOSPC))); - assert_eq!(pool.queues.load(Ordering::Acquire), MAX_EXECUTION_CONTEXTS); + assert_eq!(pool.queues(), MAX_EXECUTION_CONTEXTS); drop(leases.pop()); let replacement = pool.reserve_queue().unwrap(); drop(leases); - assert_eq!(pool.queues.load(Ordering::Acquire), 1); + assert_eq!(pool.queues(), 1); drop(replacement); - assert_eq!(pool.queues.load(Ordering::Acquire), 0); + assert_eq!(pool.queues(), 0); } } /// Counted once per userspace logical queue, independently of installed graphs. pub(crate) struct QueueSlot { pool: Arc, + /// [`Pool`] generation at reservation. A later cold-boot reset bumps the + /// generation, so this slot no longer counts toward demand and drop is a + /// no-op on the post-reset counter. + generation: u32, } impl QueueSlot { /// The device's admission pool, which lives as long as the firmware session. @@ -1867,17 +1952,20 @@ impl QueueSlot { /// itself. /// /// [`Availability::notify_own`]: crate::g17::availability::Availability::notify_own + #[allow(dead_code)] // Invoked from the kunit tests in this file. pub(crate) fn cancel(self, observed: u64) -> u64 { let this = core::mem::ManuallyDrop::new(self); - // SAFETY: `this` is never used or dropped again, so the pool reference moves out once. + // SAFETY: `this` is never used or dropped again, so the pool reference + // and generation move out once. let pool = unsafe { core::ptr::read(&this.pool) }; - pool.queues.fetch_sub(1, Ordering::AcqRel); + let generation = this.generation; + pool.release_queue_count(generation); pool.waiters.as_ref().map_or(observed, |waiters| waiters.notify_own(observed)) } } impl Drop for QueueSlot { fn drop(&mut self) { - self.pool.queues.fetch_sub(1, Ordering::AcqRel); + self.pool.release_queue_count(self.generation); if let Some(waiters) = &self.pool.waiters { waiters.notify(); } @@ -2190,7 +2278,7 @@ impl Pool { impl Pool { pub(crate) fn write_capacity(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { - writeln!(f, "logical_queues used={} total={}", self.queues.load(Ordering::Acquire), self.max_queues)?; + writeln!(f, "logical_queues used={} total={}", self.queues(), self.max_queues)?; let state = self.state.lock(); writeln!(f, "render_slots used={} total={} retained={} active={} quarantined={} kill_held={} held={}", state.used().count_ones(), State::MASK.count_ones(), state.retained().count_ones(), @@ -2330,7 +2418,7 @@ mod fault_capacity_tests { assert_eq!(state.active, 0); assert_eq!(state.quarantined, 0); assert_eq!(state.owners.iter().enumerate().filter(|(slot, id)| **id != 0 && state.released & (1u64 << slot) == 0).count(), 0); - assert_eq!(pool.queues.load(Ordering::Acquire), 0); + assert_eq!(pool.queues(), 0); } } diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 1662cbb5d4733..c054e854f2a41 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -734,6 +734,8 @@ pub(crate) struct Queue { /// A channel error of this queue waits for the firmware to consume its acknowledgement: the /// queue keeps its owner and backing until then. channel_error: bool, + /// The firmware this queue was installed on is gone. + outlived: bool, /// Prepared packets of the bound owner about to publish (see [`Self::claim`]). claims: u32, last_published: u64, @@ -755,6 +757,25 @@ pub(crate) struct Queue { } impl Queue { + /// The firmware booted cold: this pre-restore queue is dead. It must not + /// message the fresh firmware or be handed to a new client. + pub(crate) fn retire_for_cold_boot(&mut self) { + self.outlived = true; + self.forget_firmware(); + } + + + /// The firmware booted cold and knows nothing of this queue: its next command + /// installs it again, as the first one did. + pub(crate) fn forget_firmware(&mut self) { + self.installed = false; + self.ordinal = 0; + self.outer_started = 0; + self.published_config = None; + self.config_cache = None; + self.m5_install = None; + } + /// The caller reserves a QID first, cancels it on construction failure, and retains every /// successfully installed queue until processor stop. Shared VM apertures precede this call. pub(crate) fn new( @@ -856,6 +877,7 @@ impl Queue { submitted: 0, fault_stamp: None, channel_error: false, + outlived: false, claims: 0, last_published: 0, last_end: 0, diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 9681fe4aee416..e874939c33589 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -616,6 +616,10 @@ impl Queue { } impl crate::queue::Queue for Queue { + fn needs_rebuild(&self) -> bool { + self.context.needs_rebuild() + } + fn set_compute_timeout(&mut self, requested_ms: u32) -> Result { // The compute scheduler takes the allowance when the first compute command creates it. if self.compute.is_some() { @@ -678,7 +682,7 @@ impl crate::queue::Queue for Queue { if !self.backend.supports_submission() { return Err(ENOTSUPP); } - if self.context.status().get() != 0 { + if self.context.outlived_firmware() || self.context.status().get() != 0 { return Err(EIO); } self.prepare_submission(bytes, objects, &mut scratch)?; diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 3bf479b408bd3..26ceb6a648870 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -275,6 +275,8 @@ pub(crate) struct Pair { /// A channel error of one of this pair's queues waits for the firmware to consume its /// acknowledgement: the pair keeps its owner and graph until then. channel_error: bool, + /// The firmware this pair was installed on is gone. + outlived: bool, kick_aliases: Option<[Option; 2]>, /// The read-only views of the two kick rings in the VM of the pair's contexts, installed with /// its first graph in that VM. They belong to the pair's time in that VM, not to the VM: they @@ -497,11 +499,48 @@ impl Pair { drain_failures: 0, drain_retry_at: 0, channel_error: false, + outlived: false, })) } pub(crate) fn qids(&self) -> [u8; 2] { self.kicks.each_ref().map(|kick| kick.id().qid()) } + + pub(crate) fn kick_ids(&self) -> [crate::g17::kick::Id; 2] { + self.kicks.each_ref().map(crate::g17::kick::Queue::id) + } + + /// The firmware booted cold: these pre-restore queues are dead. + /// Alias mappings and kick-ring views are released locally; the firmware + /// is already stopped, so no teardown command is sent. The rings themselves + /// return to the stock on drop and are drained by + /// [`crate::g17::kick::RenderRings::release_for_cold_boot`]. + pub(crate) fn retire_for_cold_boot(&mut self) { + self.outlived = true; + self.forget_firmware(); + self.kick_aliases = None; + self.client_kicks = [None, None]; + self.pending_aliases = None; + } + + /// The firmware booted cold and knows nothing of these queues: the next command + /// installs both again, from the host's cursors. + pub(crate) fn forget_firmware(&mut self) { + self.registered = None; + self.installed = [false; 2]; + self.graph_started = false; + self.context_update = true; + self.identity_update = true; + self.configs = [None; 2]; + self.memory.manager.forget_firmware(); + self.outer_started = 0; + self.executed = 0; + self.executed_generation = None; + self.switch = None; + self.published_completions = None; + self.configured_context = None; + self.configured_qos = None; + } /// The queue record the firmware runs physical queue `qid` of this pair from. pub(crate) fn queue_record_va(&self, qid: u8) -> Option { self.qids().contains(&qid).then(|| { diff --git a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs index e41d8855108ac..6f652fe969139 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs @@ -45,6 +45,8 @@ pub(crate) struct ParkedPair { vm: u64, /// That VM's status, which tells when its client closed it ([`Self::take_closed_views`]). status: Option>, + /// The firmware this pair was installed on is gone. + outlived: bool, } /// All new graph ownership stays separate from the installed kick storage until commit. @@ -148,6 +150,7 @@ impl Pair { executed: self.executed, vm, status, + outlived: self.outlived, }; let retired = RetiredBinding { _client_kicks: retired_kicks, @@ -169,6 +172,28 @@ fn closed(status: Option<&Arc>) -> bool { } impl ParkedPair { + + pub(crate) fn kick_ids(&self) -> [crate::g17::kick::Id; 2] { + self.ids + } + + pub(crate) fn retire_for_cold_boot(&mut self) { + self.outlived = true; + self.forget_firmware(); + // Local release: drop client aliases first, then the rings so their + // storage is in the stock before the post-retire drain unmaps it. + self.client_kicks = [None, None]; + drop(self.kicks.take()); + } + + /// The firmware booted cold: the queues install again with the pair's next command. + pub(crate) fn forget_firmware(&mut self) { + self.registered = None; + self.installed = [false; 2]; + self.outer_started = 0; + self.executed = 0; + } + /// Removes the previous VM's views of both kick rings and clears the rings when the pair /// goes to a context of another VM than the one that last ran on it, so neither owner can /// read the entries the other's commands leave there. The pair is parked, so the firmware @@ -381,6 +406,7 @@ impl ParkedPair { drain_failures: 0, drain_retry_at: 0, channel_error: false, + outlived: self.outlived, })) } } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index c5ab57c847d5f..150c3a558c3c9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -4406,7 +4406,11 @@ impl Backend { let check = || { if packet.cancel_requested() { return Err(ECANCELED); } self.admission_open()?; - if packet.completion.status().get() != 0 { return Err(EIO); } + if packet.context.outlived_firmware() + || packet.completion.status().get() != 0 + { + return Err(EIO); + } Ok(()) }; let admission = Admission::new(deadline, &check); @@ -4653,7 +4657,7 @@ impl super::Firmware { /// Both processors are stopped and their owner detached before this call. /// Error fences release their command mappings without the device mutex /// or an allocation-dependent collector. - fn finish_stopped_queues(&mut self) { + pub(in crate::g17) fn finish_stopped_queues(&mut self) { self.stop_render(); for mut queue in self .queues @@ -4736,6 +4740,11 @@ impl super::Shared { let firmware = { let mut state = self.state.lock(); if let Some(firmware) = (*state).as_deref_mut() { + // A firmware told to stop parks itself first: its CPUs then stop with nothing + // in flight, and the next probe boots it again from the memory it was handed. + if !self.crashed.load(Ordering::Acquire) { + firmware.park(); + } if let Some(secondary) = firmware.secondary.as_mut() { secondary.stop(); } @@ -4758,6 +4767,7 @@ impl super::Shared { firmware.finish_stopped_queues(); // RTKit destruction still dereferences the mailbox provider. drop(firmware); + self.power_off_after_stop(); } } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 308429e4e2382..34bb38ed53565 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -1445,9 +1445,87 @@ impl crate::g17::Firmware { } } } + } impl Registry { + pub(in crate::g17) fn retire_for_cold_boot(&mut self) { + for slot in 0..self.render.entries.len() { + let Some(mut entry) = self.render.entries[slot].take() else { + continue; + }; + if let Some(mut pair) = entry.pair.take() { + let ids = pair.kick_ids(); + let buffer = pair.buffer_id(); + pair.retire_for_cold_boot(); + for id in ids { + let _ = self.qids.release(id); + } + let _ = self.buffers.unreserve_owner(buffer); + drop(pair); + } + if let Some(mut parked) = entry.parked.take() { + let ids = parked.kick_ids(); + parked.retire_for_cold_boot(); + for id in ids { + let _ = self.qids.release(id); + } + drop(parked); + } + for id in entry.reservation.ids { + let _ = self.qids.release(id); + } + if entry.reservation.buffer.0 != 0 { + let _ = self.buffers.unreserve_owner(entry.reservation.buffer.0); + } + drop(entry); + } + let kept = core::mem::replace(&mut self.render.kept_pairs, KVec::new()); + for mut parked in kept { + let ids = parked.kick_ids(); + parked.retire_for_cold_boot(); + for id in ids { + let _ = self.qids.release(id); + } + drop(parked); + } + let _kept_graphs = core::mem::replace(&mut self.render.kept_graphs, KVec::new()); + let _retired = core::mem::replace(&mut self.render.retired, KVec::new()); + self.render.pools.abandon_for_cold_boot(); + self.render.grow.abandon_for_cold_boot(); + for slot in 0..self.compute.len() { + let Some(mut entry) = self.compute[slot].take() else { + continue; + }; + let id = entry.reservation.id; + if let Some(mut queue) = entry.queue.take() { + queue.retire_for_cold_boot(); + drop(queue); + } + let _ = self.qids.release(id); + drop(entry); + } + if let Err(error) = self.qids.reset_to_probe() { + pr_err!("Failed to reset GPU queue IDs for a firmware reboot: {:?}\n", error); + } + self.buffers.reset_to_probe(); + self.render.next_pm_generation = 1; + self.admission.reset_occupancy_after_cold_boot(); + self.teardown.abandon_for_cold_boot(); + self.observations.clear(); + self.completion_cursor = 0; + for word in self.completion_seen.iter_mut() { + *word = 0; + } + self.compute_building = false; + self.compute_scheduler_building = false; + self.replay_outer_wait = None; + self.replay_consumer_wait = None; + self.sync_render_holds(); + self.note_build_room(); + } + + pub(in crate::g17) fn render_oldest_spared(&self, qid: u8) -> Option { self.render .entries diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs b/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs index ac7504aadd73f..c66dfb9cb37a2 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs @@ -34,6 +34,15 @@ pub(super) struct Grow { ack_attempts: u16, } impl Grow { + + pub(super) fn abandon_for_cold_boot(&mut self) { + self.requests.clear(); + self.active = None; + self.reply = None; + self.release_attempts = 0; + self.acks.clear(); + self.ack_attempts = 0; + } pub(super) fn new() -> Result { Ok(Self { requests: KVec::with_capacity(2 * EVENT_SLOTS as usize, GFP_KERNEL)?, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs b/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs index cad2591784932..283a2060418c9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs @@ -39,6 +39,13 @@ pub(super) struct Preparation { } impl Pools { + + /// The firmware is stopped and every pair that named a lease is gone. + pub(super) fn abandon_for_cold_boot(&mut self) { + for lease in self.leases.iter_mut() { + *lease = None; + } + } pub(super) fn new() -> Result { let mut leases = KVec::with_capacity(POOLS, GFP_KERNEL)?; for _ in 0..POOLS { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index b64fe33b78af6..7f9c59dbb0248 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -488,7 +488,10 @@ impl super::super::Backend { if let Some(error) = error { return Err(error); } - if !self.context.is_current() || self.context.status().get() != 0 { + if !self.context.is_current() + || self.context.outlived_firmware() + || self.context.status().get() != 0 + { return Err(EFAULT); } if firmware.queues.render.reserved(reservation)?.closed { @@ -573,7 +576,10 @@ impl super::super::Backend { if let Some(error) = error { return Err(error); } - if !self.context.is_current() || self.context.status().get() != 0 { + if !self.context.is_current() + || self.context.outlived_firmware() + || self.context.status().get() != 0 + { return Err(EFAULT); } let entry = firmware.queues.render.entry(slot)?; @@ -703,7 +709,10 @@ impl super::super::Backend { if let Some(error) = error { return Err(error); } - if !self.context.is_current() || self.context.status().get() != 0 { + if !self.context.is_current() + || self.context.outlived_firmware() + || self.context.status().get() != 0 + { return Err(EFAULT); } let entry = firmware.queues.render.entry(slot)?; @@ -794,7 +803,10 @@ impl super::super::Backend { if firmware.queues.render.entry(slot)?.closed { return Err(ECANCELED); } - if !self.context.is_current() || self.context.status().get() != 0 { + if !self.context.is_current() + || self.context.outlived_firmware() + || self.context.status().get() != 0 + { return Err(EFAULT); } // From this point every error leaves the complete graph retained for diff --git a/drivers/gpu/drm/asahi/g17/sleep.c b/drivers/gpu/drm/asahi/g17/sleep.c index 6b8c03bea798b..e45c09a7355e1 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.c +++ b/drivers/gpu/drm/asahi/g17/sleep.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -310,6 +311,52 @@ static u32 asahi_g17_ps_on(struct device *dev, u32 val, u32 saved) return val | (saved & PS_AUTO) | FIELD_PREP(PS_TARGET, PS_ACTIVE); } +/* The domain's word, and whether the domain is on. */ +int asahi_g17_power_word(struct device *dev, u32 *val, bool *active) +{ + struct regmap *regmap; + u32 offset; + int ret; + + ret = asahi_g17_ps(dev, ®map, &offset); + if (ret) + return ret; + ret = regmap_read(regmap, offset, val); + if (ret) + return ret; + *active = FIELD_GET(PS_ACTUAL, *val) == PS_ACTIVE; + return 0; +} + +/* + * Reset the coprocessor behind the GPU's mailbox. Its processors stopped, but a + * stopped processor resumes where it stopped: only a reset makes the next start + * boot the firmware from its vector. A mailbox without a reset has none to give. + */ +int asahi_g17_asc_reset(struct device *dev) +{ + struct reset_control *reset; + struct device_node *np; + int ret; + + np = of_parse_phandle(dev->of_node, "mboxes", 0); + if (!np) + return -ENODEV; + reset = of_reset_control_get_optional_exclusive(np, NULL); + if (IS_ERR(reset)) { + of_node_put(np); + return PTR_ERR(reset); + } + if (!reset) { + of_node_put(np); + return -EOPNOTSUPP; + } + ret = reset_control_reset(reset); + reset_control_put(reset); + of_node_put(np); + return ret; +} + /* The target on, and wait for it. */ int asahi_g17_power_raise(struct device *dev, u32 saved) { diff --git a/drivers/gpu/drm/asahi/g17/sleep.h b/drivers/gpu/drm/asahi/g17/sleep.h index 9fb8ed38b2858..1531bc07bffae 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.h +++ b/drivers/gpu/drm/asahi/g17/sleep.h @@ -26,6 +26,8 @@ bool asahi_g17_commit_required(void); bool asahi_g17_commit_stops_firmware(void); int asahi_g17_power_auto_off(struct device *dev, u32 *saved); int asahi_g17_power_lower(struct device *dev); +int asahi_g17_asc_reset(struct device *dev); +int asahi_g17_power_word(struct device *dev, u32 *val, bool *active); int asahi_g17_power_raise(struct device *dev, u32 saved); int asahi_g17_power_auto_on(struct device *dev, u32 saved); int asahi_g16_register_pm_notify(struct device *dev, diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index a5d5aac489468..e9c3619222a22 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -20,10 +20,12 @@ //! own would leave the firmware stopped after any later refusal, until the next real sleep. use super::{Firmware, Role, Shared}; +use crate::mmu; use core::sync::atomic::Ordering; use kernel::{ - bindings, + bindings, device, prelude::*, + pr_warn_once, sync::Arc, time::{delay::fsleep, Delta}, workqueue::{DelayedWork, Work}, @@ -40,6 +42,12 @@ unsafe extern "C" { fn asahi_g17_pmp_request(dev: *mut core::ffi::c_void, enable: bool) -> core::ffi::c_int; fn asahi_g17_power_auto_off(dev: *mut core::ffi::c_void, saved: *mut u32) -> core::ffi::c_int; fn asahi_g17_power_lower(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_g17_power_word( + dev: *mut core::ffi::c_void, + val: *mut u32, + active: *mut bool, + ) -> core::ffi::c_int; + fn asahi_g17_asc_reset(dev: *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_g17_power_raise(dev: *mut core::ffi::c_void, saved: u32) -> core::ffi::c_int; fn asahi_g17_power_auto_on(dev: *mut core::ffi::c_void, saved: u32) -> core::ffi::c_int; fn asahi_g17_commit_prepare( @@ -54,6 +62,72 @@ unsafe extern "C" { fn asahi_g17_commit_stops_firmware() -> bool; } +kernel::sync::global_lock! { + // SAFETY: Module initialization initializes this lock before registering adapters. + unsafe(uninit) static HANDED_OVER_POWER: Mutex> = KVec::new(); +} + +/// # Safety +/// +/// Called exactly once per module instance, before any device probes. +pub(super) unsafe fn init() { + // SAFETY: The module initializer establishes the single-call ordering above. + unsafe { HANDED_OVER_POWER.init() }; +} + +/// Before a probe boots the firmware. The device's first probe keeps the domain's word as the +/// boot loader left it; a later one finds the domain as the last unbind left it, off, and +/// brings it back with that word, as a wake does. +pub(super) fn power_for_probe(dev: &device::Device) -> Result { + let raw = dev.as_raw().cast(); + let (mut word, mut active) = (0, false); + // SAFETY: `dev` is the live GPU device and both pointers are writable. + kernel::error::to_result(unsafe { asahi_g17_power_word(raw, &mut word, &mut active) })?; + let key = dev.as_raw() as usize; + let saved = { + let mut handed_over = HANDED_OVER_POWER.lock(); + match handed_over.iter().find(|(k, _)| *k == key) { + Some((_, saved)) => *saved, + None => { + handed_over.push((key, word), GFP_KERNEL)?; + return Ok(()); + } + } + }; + if active { + return Ok(()); + } + dev_dbg!(dev, "GPU domain off before the boot: {:#x}\n", word); + // SAFETY: `dev` is the live GPU device. + kernel::error::to_result(unsafe { asahi_g17_power_raise(raw, saved) })?; + // SAFETY: As above. + kernel::error::to_result(unsafe { asahi_g17_power_auto_on(raw, saved) })?; + // SAFETY: As above. + let request = kernel::error::to_result(unsafe { asahi_g17_pmp_request(raw, true) }); + if let Err(error) = request { + dev_warn!(dev, "PMP request for the GPU, true: {:?}\n", error); + } + Ok(()) +} + +impl Shared { + /// After an unbind stopped the firmware and dropped its session: the domain goes off, so + /// the next boot of the firmware starts from reset. + pub(super) fn power_off_after_stop(&self) { + // SAFETY: `dev` is the live GPU device. + let reset = unsafe { asahi_g17_asc_reset(self.dev.as_raw().cast()) }; + if reset != 0 && reset != -(bindings::EOPNOTSUPP as i32) { + dev_warn!(self.dev.as_ref(), "GPU coprocessor reset: {}\n", reset); + } + if reset == 0 { + crate::boot_memory::put_back(self.dev.as_ref()); + } + self.pmp_request(false); + let _ = self.power_auto_off(); + let _ = self.power_lower(); + } +} + /// What `.complete` does after a sleep whose stop was left to the commit. #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum AfterCommit { @@ -621,6 +695,12 @@ impl super::Gpu { if !self.shared.sleeping() { return; } + // A restored image boots the firmware once every device resumed: the power and + // performance controllers it asks for are only back then. + if self.shared.hib_carried() { + self.shared.hib_restore(self.cfg); + return; + } // SAFETY: Reads a global flag word. let real = unsafe { bindings::pm_resume_via_firmware() }; if let Some(stopped) = self.shared.sleep_commit_finish() { @@ -646,6 +726,417 @@ impl super::Gpu { } } +impl Firmware { + /// On the restored kernel, before the cold boot: the boot that loaded the image left the + /// firmware halted, while the image holds the books of the firmware that ran when it was + /// taken. Each mailbox goes off and each CPU is marked stopped, without a register write + /// to the CPU. + fn hib_forget_running(&mut self) { + for role in [Role::Secondary, Role::Primary] { + let Ok(coprocessor) = self.coprocessor(role) else { + continue; + }; + // SAFETY: Nothing runs on this instance; a cold boot follows. + coprocessor + .rtkit + .with(|rtkit| unsafe { bindings::apple_rtkit_mailbox_off(rtkit.as_raw()) }); + coprocessor.stopped_at_commit(); + } + } + + /// Boots the firmware cold on this session's objects, on a restored image. The boot that + /// restored it handed the firmware's memory over afresh, so it gets everything a probe gives + /// it: the host's translation memory as the image left it, new initialization data and a new + /// port. Pre-image queues are not carried over. Where the SoC keeps the clients + /// (`hib_keep_clients`), their VMs are, and each queue is built again on its VM before its + /// next submission; elsewhere post-restore clients allocate both fresh. + fn hib_cold_boot(&mut self, cfg: &'static super::Config, tables: &mmu::ReservedCopy) -> Result { + let shared = self.primary.state.shared.clone(); + let dev = shared.dev.clone(); + let at = |step: &'static str| { + let dev = dev.clone(); + move |e: &Error| dev_err!(dev.as_ref(), "GPU cold boot failed at {}: {:?}\n", step, e) + }; + let drm = (*shared.drm.lock()).clone().ok_or(ENODEV)?; + let t0 = super::now_ns(); + + // Everything that can fail without the hardware first. + let rings = super::channel::Rings::new( + shared.variant.graph, + shared.variant.telemetry_protocol, + shared.max_pstate, + ).inspect_err(at("rings"))?; + let port = super::port::Port::new( + self.port.take_demand(), + shared.feed.clone(), + ).inspect_err(at("port"))?; + self.uat.restore_reserved(tables).inspect_err(at("tables"))?; + let tables_ns = super::now_ns().saturating_sub(t0); + + + // Work-ring cursors and outer-credit accounting in objects the rebuild + // will keep must match a fresh probe before the firmware starts, or it + // samples pre-image producers/consumers against a boot that starts at 0. + self.init.reset_publication_to_probe().inspect_err(at("reset publication"))?; + self.recovery = super::recovery::State::new(); + self.hold = super::power::Hold::new(); + self.registration_power_release_pending = false; + // Nothing the firmware held before the image is in flight any more. + self.finish_stopped_queues(); + // Pre-restore queues must not talk to the fresh firmware: their kick-ring + // VAs would be written into table[qid]+8 by QueueConfig (command 0xf). + // Vacate slots and free QIDs so post-restore clients allocate them fresh. + self.queues.retire_for_cold_boot(); + // Dropping the retired pairs only returns their rings to the stock, where + // written rings stay mapped in the kernel-lower window. Release that + // storage locally (no firmware teardown command) so a new Queue::render + // does not hit EBUSY on the occupied aliases. + self.render_rings.release_for_cold_boot(); + let retire_ns = super::now_ns().saturating_sub(t0); + + if cfg.hib_keep_clients { + // The clients' VMs are host memory the image held: they carry over. Their + // contexts and queues do not; each queue is built again on its VM before + // its next submission. + self.uat.outlive_client_contexts(); + } else { + // As a firmware restart does, pre-image clients are not carried over: + // each sees a lost device and starts again, on new VMs. + self.uat.outlive_client_vms(); + } + // Physical render-ID claims from the pre-image session are not a + // firmware release the new boot can honour. Wipe the namespace so a + // new client can pin. + self.render_ids.reset_to_probe(); + shared.renders.notify(); + + shared.forget_port(); + // The earlier port and rings go once the firmware runs again: before its boot, the + // translation tables they are mapped through aren't all in place. + let _earlier = ( + core::mem::replace(&mut self.port, port), + core::mem::replace(&mut self.rings, rings), + ); + self.init.prepare_rebuild(); + + // The firmware samples the kernel lower-root and the context table when + // it starts. Clear the outlived clients' TTB slots, clean the table and + // the handoff, and flush the GPU TLB before that boot, so it does not + // snapshot a stale or empty slot. + self.uat.reset_outlived_contexts(); + let contexts_ns = super::now_ns().saturating_sub(t0); + + self.direct_idle = super::power::DirectIdle::new(); + // The firmware starts at its own effort, as at probe. + self.effort = super::power::Effort::new(); + shared.set_full_effort_published(false); + for role in [Role::Secondary, Role::Primary] { + if let Ok(coprocessor) = self.coprocessor(role) { + coprocessor.rtkit.with(|rtkit| rtkit.reinit()).inspect_err(at("rtkit reinit"))?; + } + } + + // Do not wipe inventoried kernel-window objects here: a blanket + // zero would clear pool backing, metrics, PB headers and other + // objects that are still reused. Only the targeted firmware-visible + // resets belong here: retire, publication cursors, and stamps. + let rtkit_ns = super::now_ns().saturating_sub(t0); + self.raise().inspect_err(at("raise"))?; + self.bridge(true).inspect_err(at("bridge"))?; + self.auto_on().inspect_err(at("auto on"))?; + self.request(true); + self.gating(true).inspect_err(at("gating"))?; + self.primary.boot().inspect_err(at("boot"))?; + + if let Some(secondary) = self.secondary.as_mut() { + secondary.boot()?; + } + self.uat.invalidate_reserved_tables(); + let merged = self.uat.merge_reserved(tables).inspect_err(at("merge"))?; + // After the firmware starts it builds its kernel-window tables in the + // reserved no-map l2-pagetables region (translation memory the image does + // not hold). The rebuilt entries already match the freeze copy, so merge + // reports nothing as restored, and live leaves sit in VA holes whose + // drm_mm nodes were already freed. Unmap those leaves and TLBI before + // init.build allocates new objects. + self.uat.kernel_dynamic_holes(true).inspect_err(at("holes after merge"))?; + dev_info!( + shared.dev.as_ref(), + "GPU tables after the cold boot: {:?}, application contexts were cleared before the firmware started\n", + merged + ); + let root_entries = match cfg.adopt_root_entries { + true => Some(self.uat.adopt_firmware_root_entries().inspect_err(at("adopt"))?), + false => None, + }; + self.init.build( + &drm, + cfg, + &self.uat, + &self._render_global, + &self._pm_metrics, + shared.clusters, + shared.active_cores, + shared.variant, + ).inspect_err(at("build"))?; + if let Some(root_entries) = root_entries { + self.uat.confirm_firmware_root_entries(root_entries).inspect_err(at("confirm"))?; + } + self.init.reseed_stamps().inspect_err(at("stamps"))?; + + let mailbox: *const super::Mailbox = &*self.primary.rtkit; + self.port.attach( + self.init.port_views(mailbox)?, + self.bridge.regs.clone(), + shared.variant.registration, + ).inspect_err(at("attach"))?; + + self.uat.mirror_secondary_root().inspect_err(at("mirror"))?; + if cfg.fabric_bridge { + self.bridge.regs.enable_g17_gating()?; + } + let ack = shared.variant.init_ack; + self.primary.init(self.init.root_va(Role::Primary)?, ack).inspect_err(at("init"))?; + let boot_ns = super::now_ns().saturating_sub(t0); + + if ack == super::fw::variant::InitAck::Status { + super::Gpu::wait_for_init_accepted( + &drm, + &self.init, + &self.primary, + ).inspect_err(at("accepted"))?; + } + let accepted_ns = super::now_ns().saturating_sub(t0); + if let Some(secondary) = self.secondary.as_mut() { + secondary.init(self.init.root_va(Role::Secondary)?, ack)?; + } + self.power_on_done().inspect_err(at("power on done"))?; + + if shared.variant.opening_record { + super::Gpu::wait_for_opening( + &drm, + &self.init, + &self.primary, + self.secondary.as_ref(), + ).inspect_err(at("opening"))?; + } + let opening_ns = super::now_ns().saturating_sub(t0); + self.uat.activate_render_context(&self._render_global).inspect_err(at("render context"))?; + + shared + .port + .store(Arc::as_ptr(&self.port).cast_mut(), Ordering::Release); + + // Validation only: after init.build, holes should already be clean. + let (cleared, first) = self + .uat + .kernel_dynamic_holes(true) + .inspect_err(at("holes after init"))?; + if cleared != 0 { + pr_warn_once!( + "asahi: untracked kernel-dynamic leaves remained after init data was rebuilt ({} at {:?})\n", + cleared, + first + ); + } + dev_info!( + shared.dev.as_ref(), + "GPU cold-boot steps: tables {} us, retire {} us, contexts {} us, rtkit {} us, firmware up {} us, init accepted {} us, opening {} us\n", + tables_ns / 1000, + retire_ns.saturating_sub(tables_ns) / 1000, + contexts_ns.saturating_sub(retire_ns) / 1000, + rtkit_ns.saturating_sub(contexts_ns) / 1000, + boot_ns.saturating_sub(rtkit_ns) / 1000, + accepted_ns.saturating_sub(boot_ns) / 1000, + opening_ns.saturating_sub(accepted_ns) / 1000 + ); + Ok(()) + } +} + +impl Shared { + /// Whether the image carries what the firmware needs to boot again (from `.freeze` on). + fn hib_carried(&self) -> bool { + (*self.state.lock()) + .as_deref() + .is_some_and(|firmware| firmware.hib.is_some()) + } + + /// Closes publication and waits for quiet; `tables` is filled at the last step before the + /// image. The firmware stays running, idle: once a kernel started it, it doesn't start again + /// before a reboot, and every hibernation goes on in this kernel after the image is taken. + /// A refusal changes nothing; a device already lost has nothing to carry and doesn't refuse. + fn hib_freeze(self: &Arc, tables: mmu::ReservedCopy) -> Result { + if self.sleeping() { + return Err(EBUSY); + } + let deadline = super::now_ns().saturating_add(DRAIN_NS); + self.sleep_gate.store(true, Ordering::Release); + self.preparations.close(); + let result = self + .preparations + .wait_drained_until(deadline) + .map_err(|_| EBUSY) + .and_then(|_| self.wait_quiet(deadline)) + .and_then(|_| { + self.sleeping.store(true, Ordering::Release); + self.join_event_workers(); + let mut state = self.state.lock(); + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if !firmware.sleep_quiet(super::now_ns())? { + return Err(EBUSY); + } + firmware.hib = Some(tables); + Ok(()) + }); + match result { + Ok(()) => Ok(()), + Err(error) => { + let lost = error == ENODEV || self.crashed.load(Ordering::Acquire); + self.sleep_cancel(false); + if lost { + return Ok(()); + } + Err(error) + } + } + } + + /// The last step before the image: nothing maps, binds or runs on the GPU any more. + fn hib_freeze_late(&self) { + let mut state = self.state.lock(); + if let Some(firmware) = (*state).as_deref_mut() { + if let Some(mut tables) = firmware.hib.take() { + firmware.uat.save_reserved(&mut tables); + firmware.hib = Some(tables); + } + } + } + + /// The image is taken, written or not: the firmware never stopped, so publication reopens. + fn hib_thaw(self: &Arc) { + let carried = match (*self.state.lock()).as_deref_mut() { + Some(firmware) => firmware.hib.take().is_some(), + None => false, + }; + if carried && self.sleeping() { + self.sleep_cancel(false); + } + } + + /// On the restored kernel: boots the firmware cold and reopens publication. Any failure + /// loses the device. + fn hib_restore(self: &Arc, cfg: &'static super::Config) { + if !self.sleeping() { + return; + } + let started = super::now_ns(); + let result = match (*self.state.lock()).as_deref_mut() { + Some(firmware) if !self.crashed.load(Ordering::Acquire) => match firmware.hib.take() { + Some(tables) => { + firmware.hib_forget_running(); + firmware.hib_cold_boot(cfg, &tables).inspect_err(|_| { + // Leave nothing running for a device that is lost. The domain stays as + // it is: the PMP runs, and reads the GPU's registers. + if let Some(secondary) = firmware.secondary.as_mut() { + secondary.stop(); + } + firmware.primary.stop(); + }) + } + None => Err(ENODATA), + }, + _ => Err(ENODEV), + }; + self.sleeping.store(false, Ordering::Release); + self.sleep_gate.store(false, Ordering::Release); + match result { + Ok(()) => { + dev_info!( + self.dev.as_ref(), + "GPU firmware booted again after the hibernation in {} us\n", + super::now_ns().saturating_sub(started) / 1000 + ); + if !self.preparations.reopen() { + dev_err!( + self.dev.as_ref(), + "GPU publication did not reopen after the firmware reboot\n" + ); + } + self.rearm_after_cold_boot(); + } + Err(error) => { + dev_err!( + self.dev.as_ref(), + "GPU firmware did not boot again after the hibernation: {:?}\n", + error + ); + self.lose_device_quietly(); + } + } + } +} + +impl super::Gpu { + /// Whether the firmware boots again after a hibernation restore: on a chip whose firmware + /// restarts after a sleep, where the stop isn't left to the sleep's last steps. + fn hib_boots_again(&self) -> bool { + // SAFETY: Reads the sleep driver's state: true where the commit stops the firmware. + self.cfg.sleep_restart + && !self.cfg.profile.is_m5() + && !unsafe { asahi_g17_commit_stops_firmware() } + } +} + +impl crate::gpu::HibRestoreContain for super::Gpu { + /// Mark the device lost before the runtime touches the firmware the resuming kernel's image + /// describes, unless the image carries what boots it again. The boot loader reset the ASC, + /// so that firmware is gone; a failed GPU restore then leaves the GPU unusable until reboot + /// while the system stays alive -- never a mailbox poke, a warm restart or a page-table + /// teardown against stale firmware state. Only a hibernation restore reaches here (a + /// suspend resume and a hibernating kernel's own thaw do not). + fn hib_restore_contain(&self) { + if !self.shared.hib_carried() { + self.shared.lose_device_quietly(); + } + } + + fn hib_freeze(&self) -> Result { + if !self.hib_boots_again() { + return Ok(()); + } + // Everything that can fail to allocate does so before the firmware stops. + let tables = match (*self.shared.state.lock()).as_deref() { + Some(firmware) => firmware.uat.reserved_copy(), + None => return Ok(()), + }; + let tables = match tables { + Ok(tables) => tables, + Err(error) => { + dev_warn!( + self.shared.dev.as_ref(), + "GPU firmware will not boot again after the hibernation: {:?}\n", + error + ); + return Ok(()); + } + }; + let result = self.shared.hib_freeze(tables); + if let Err(error) = result { + dev_warn!(self.shared.dev.as_ref(), "GPU refused hibernation: {:?}\n", error); + } + result + } + + fn hib_freeze_late(&self) { + self.shared.hib_freeze_late(); + } + + fn hib_thaw(&self) { + self.shared.hib_thaw(); + } +} + #[kernel::macros::kunit_tests(asahi_g17_sleep)] mod tests { use super::*; diff --git a/drivers/gpu/drm/asahi/g17/teardown.rs b/drivers/gpu/drm/asahi/g17/teardown.rs index d41800b4caead..1b31b4ddf2ef9 100644 --- a/drivers/gpu/drm/asahi/g17/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/teardown.rs @@ -112,6 +112,12 @@ impl Pending { self.entries.len() } + /// Drop every pending scheduler-release without talking to firmware: the + /// coprocessors are already stopped and a cold boot must not replay them. + pub(crate) fn abandon_for_cold_boot(&mut self) { + self.entries.clear(); + } + pub(crate) fn is_empty(&self) -> bool { self.entries.is_empty() } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 1aca336f48a17..74698cb3a141d 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -701,6 +701,40 @@ pub(crate) trait GpuManager: Send + Sync { fn fw_power_off(&self); } +/// Hibernation-restore containment, independent of GPU generation. +/// +/// A resume from a hibernation image comes up on a fresh warm boot with the +/// coprocessor reset, so the firmware state captured in the image is gone. +/// Before a backend's runtime touches that dead firmware, the PM core's +/// hibernation `.restore_noirq` gives each present GPU backend a chance to +/// mark itself lost: a failed GPU restore then leaves the GPU unusable until +/// reboot while the system stays alive -- never a mailbox poke, a warm +/// restart or a page-table teardown against stale firmware state. +/// +/// The default is a no-op, so a generation that has not opted in keeps its +/// current behaviour. A generation opts in by overriding this hook to mark +/// its device lost. +/// +/// A generation that can boot its firmware again on the restored kernel's +/// objects also overrides the other hooks: `.freeze` stops the firmware for +/// the image, `.freeze_noirq` copies the memory the image needs to boot it +/// again, and `.thaw` restarts it with its memory intact. On the restored +/// kernel it boots the firmware cold once every device resumed, so that +/// clients keep their contexts. Its containment then only +/// applies to an image that carries no such copy. +pub(crate) trait HibRestoreContain { + fn hib_restore_contain(&self) {} + /// `.freeze`: stop the firmware for the image. An error refuses the + /// hibernation. + fn hib_freeze(&self) -> Result { + Ok(()) + } + /// `.freeze_noirq`: the last step before the image is taken. + fn hib_freeze_late(&self) {} + /// `.thaw`: the image is written or the hibernation failed. + fn hib_thaw(&self) {} +} + /// Private generic trait for functions that don't need to escape this module. trait GpuManagerPriv { /// Decrement the pending submission counter. diff --git a/drivers/gpu/drm/asahi/hw/t6040.rs b/drivers/gpu/drm/asahi/hw/t6040.rs index d2bbfc91febcc..97e261a1d84cc 100644 --- a/drivers/gpu/drm/asahi/hw/t6040.rs +++ b/drivers/gpu/drm/asahi/hw/t6040.rs @@ -60,6 +60,7 @@ pub(crate) const CONFIG: Config = Config { adopt_root_entries: false, fabric_bridge: false, sleep_restart: true, + hib_keep_clients: true, // The firmware's per-slot recovery keys are not known for this build; recovery relies on // the firmware's own blame. recovery_slot_keys: None, diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index 04d74bed0b500..7a3c05941ab71 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -51,6 +51,7 @@ pub(super) const BASE: Config = Config { adopt_root_entries: false, fabric_bridge: false, sleep_restart: false, + hib_keep_clients: false, recovery_slot_keys: None, gpu_generation: GpuGen::G16, max_mesh_workgroups: 0, @@ -256,6 +257,7 @@ const CONFIG_25G83: Config = Config { firmware: fw::variant::Firmware::Identified(&[BUILD_25G83]), // The GPU is restarted after a real sleep, as on the 32-core part. sleep_restart: true, + hib_keep_clients: false, ..BASE }; diff --git a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs index 64bd7bd5f14ee..545cc84b3ff20 100644 --- a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs +++ b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs @@ -51,6 +51,7 @@ pub(super) const CONFIG: Config = Config { }, // The GPU is restarted after a real sleep, as on T8140. sleep_restart: true, + hib_keep_clients: false, ..t6041::BASE }; diff --git a/drivers/gpu/drm/asahi/hw/t6050.rs b/drivers/gpu/drm/asahi/hw/t6050.rs index d9b76770a5244..f9ef2165ed9e3 100644 --- a/drivers/gpu/drm/asahi/hw/t6050.rs +++ b/drivers/gpu/drm/asahi/hw/t6050.rs @@ -47,6 +47,7 @@ pub(crate) const CONFIG: Config = Config { adopt_root_entries: true, fabric_bridge: false, sleep_restart: false, + hib_keep_clients: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, max_mesh_workgroups: 0, @@ -180,6 +181,7 @@ pub(crate) const CONFIG_MAX: Config = Config { adopt_root_entries: true, fabric_bridge: false, sleep_restart: false, + hib_keep_clients: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, max_mesh_workgroups: 0, @@ -323,6 +325,7 @@ pub(crate) const CONFIG_ULTRA: Config = Config { adopt_root_entries: true, fabric_bridge: false, sleep_restart: false, + hib_keep_clients: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, max_mesh_workgroups: 0, diff --git a/drivers/gpu/drm/asahi/hw/t8140.rs b/drivers/gpu/drm/asahi/hw/t8140.rs index 75f495e59066a..6528f10c6e498 100644 --- a/drivers/gpu/drm/asahi/hw/t8140.rs +++ b/drivers/gpu/drm/asahi/hw/t8140.rs @@ -59,6 +59,7 @@ pub(crate) const CONFIG: Config = Config { adopt_root_entries: true, fabric_bridge: true, sleep_restart: true, + hib_keep_clients: false, firmware: crate::g17::fw::variant::Firmware::Fixed(&crate::g17::fw::variant::V26A428), // The layouts the A18 Pro has always run with. core_layout: crate::g17::CoreLayout { diff --git a/drivers/gpu/drm/asahi/hw/t8142.rs b/drivers/gpu/drm/asahi/hw/t8142.rs index 6195d65895ca8..84674d633ee1b 100644 --- a/drivers/gpu/drm/asahi/hw/t8142.rs +++ b/drivers/gpu/drm/asahi/hw/t8142.rs @@ -45,6 +45,7 @@ pub(crate) const PROBE: Config = Config { adopt_root_entries: true, fabric_bridge: false, sleep_restart: false, + hib_keep_clients: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, max_mesh_workgroups: 0, @@ -87,6 +88,7 @@ const BASE: Config = Config { // TEST: the sleep's commit stops the firmware and a real wake restarts it warm, as on // T8140. Not yet run through a real sleep on the J813. sleep_restart: true, + hib_keep_clients: false, ..PROBE }; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index c188ea77ec620..5f8296481bba8 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -376,6 +376,33 @@ struct Handoff { const HANDOFF_SIZE: usize = size_of::(); +/// The no-map regions holding page tables, in [`pgtable::ReservedTables`] order. The first holds +/// the roots the firmware builds while it boots; the second is the table beneath the kernel +/// window, whose entries name the host's own tables. +const RESERVED_TABLES: [&CStr; 2] = [c"pagetables", c"l2-pagetables"]; + +/// The reserved table the host maps the kernel window's objects beneath. +const KERNEL_WINDOW_TABLE: usize = 1; + +/// A copy of the translation memory a hibernation image does not hold: the context table and +/// the reserved tables. Allocated before the firmware stops, filled at the last step before the +/// image ([`Uat::save_reserved`]). +pub(crate) struct ReservedCopy { + ttbs: KVVec, + tables: KVec>, +} + +/// Entries of one reserved table after a cold boot, compared with the copy. +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct ReservedMerge { + /// Entries the firmware wrote where the copy has none. + pub(crate) added: u32, + /// Entries of the copy the boot did not keep, written back. + pub(crate) restored: u32, + /// Entries the boot set to another value than the copy. + pub(crate) conflicts: u32, +} + /// One VM slot in the TTBAT #[repr(C)] struct SlotTTBS { @@ -1382,6 +1409,8 @@ pub(crate) struct Vm { /// The UAT this VM was created on, the same one [`VmInner`] holds. Kept here so that /// [`Vm::mark_binding_published`] reaches it without the VM reservation. uat_inner: Arc, + /// [`UatInner::client_epoch`] when this VM was created. + firmware_epoch: u32, } no_debug!(Vm); @@ -1408,11 +1437,19 @@ struct ExecutionRoot { inner: Arc, id: u8, generation: u8, + /// [`UatInner::firmware_epoch`] when this root was published. A later + /// rebuild of the firmware has already cleared the slot. + epoch: u32, low: u64, high: u64, } impl ExecutionContext { + /// The firmware was booted afresh after this context was published: its slot was cleared + /// before that boot and may have a new owner. + pub(crate) fn outlived_firmware(&self) -> bool { + self.root.inner.firmware_epoch.load(Ordering::Acquire) != self.root.epoch + } pub(crate) fn id(&self) -> u32 { self.root.id.into() } @@ -1473,8 +1510,16 @@ impl ExecutionRoot { return; } let id = usize::from(self.id); + // The firmware was rebuilt after this root was published: the context + // table was already cleared. Do not touch a slot a new client may own. + if self.inner.firmware_epoch.load(Ordering::Acquire) != self.epoch { + return; + } let release = { let inner = self.inner.lock(); + if self.inner.firmware_epoch.load(Ordering::Acquire) != self.epoch { + return; + } inner.handoff_lock(); let roots = &inner.ttbs()[id]; let low = roots.ttb0.load(Ordering::Acquire); @@ -2122,7 +2167,8 @@ impl Drop for KernelMapping { } }; let _mutation = owner.mapping_mutation(); - if owner.page_table.unmap_pages(self.iova_range()).is_err() { + let unmap_err = owner.page_table.unmap_pages(self.iova_range()).err(); + if unmap_err.is_some() { if self.0.uat_inner.m4_adopted { self.0.uat_inner.failed.store(true, Ordering::Release); dev_err!( @@ -2138,6 +2184,10 @@ impl Drop for KernelMapping { self.size() ); } + // Invariant: never free a drm_mm node while its leaves are still live. + // A leftover leaf on a hole is a silent prepare_map EBUSY. If unmap + // could not clear them, keep the VA reserved (no firmware command). + let live = owner.page_table.first_live_leaf(self.iova_range()).ok().flatten(); drop(upper_handoff); @@ -2159,11 +2209,16 @@ impl Drop for KernelMapping { owner.tlbi_contexts_naming_root(self.iova(), self.size()); drop(_mutation); drop(owner); + // A live leaf remains after unmap: keep the drm_mm node. + if live.is_some() { + return; + } if let Some(private) = self.0.private.as_ref() { private.fetch_sub(self.0.mapped_size as u64, Ordering::Relaxed); } // SAFETY: Every normal path reaches this exactly once, after all GPUVM locks have - // been released. Uncertain M4 paths return earlier, retaining the node and its pins. + // been released. Uncertain M4 paths, and a live leaf after unmap, return earlier + // and retain the node and its pins. unsafe { ManuallyDrop::drop(&mut self.0) }; } } @@ -2297,6 +2352,13 @@ struct UatInner { m4_adopted: bool, /// An uncertain mapping/root is retained; future M4 allocation and publication fail. failed: AtomicBool, + /// Moves on when the firmware boots afresh knowing none of the clients' address spaces: + /// the VMs created before then run nothing any more ([`Vm::outlived_firmware`]). + firmware_epoch: AtomicU32, + /// Moves on when the clients' address spaces are lost to a firmware boot. A boot that keeps + /// them moves only [`Self::firmware_epoch`]: their VMs stay, their contexts are published + /// again ([`ExecutionContext::outlived_firmware`]). + client_epoch: AtomicU32, /// Clean page tables to the point of coherency for a walker that does not snoop the CPU /// caches: [`Uat::new_adopted`], and [`UatQuirks::clean_tables`] otherwise. clean_poc: bool, @@ -2621,6 +2683,7 @@ impl Vm { let dummy_obj = gem::new_kernel_object(&dev, UAT_PGSZ)?; let is_kernel = ttb.is_some(); let narrow_pool_window = uat_inner.quirks.narrow_pool_window; + let firmware_epoch = uat_inner.client_epoch.load(Ordering::Acquire); let page_table = if let Some(ttb) = ttb { UatPageTable::new_with_ttb( @@ -2720,6 +2783,7 @@ impl Vm { private_bytes: Arc::new(AtomicU64::new(0), GFP_KERNEL)?, narrow_pool_window, uat_inner, + firmware_epoch, }) } @@ -3917,6 +3981,8 @@ impl Uat { firmware: UatFirmware::Handoff, m4_adopted: !map_kernel_to_user, failed: AtomicBool::new(false), + firmware_epoch: AtomicU32::new(0), + client_epoch: AtomicU32::new(0), // The G15 UAT walker does not snoop the CPU caches. clean_poc: true, reserved: None, @@ -4317,6 +4383,7 @@ impl Uat { inner: self.inner.clone(), id: id as u8, generation, + epoch: self.inner.firmware_epoch.load(Ordering::Acquire), low, high, }, @@ -4379,6 +4446,47 @@ impl Uat { } } + /// After a cold-boot restore: zero kernel-dynamic leaves that drm_mm does not + /// own. Freeze keeps those PTEs so the image is consistent; thaw never writes + /// the reserved copy back, but `restore_reserved` / `merge_reserved` can leave + /// a live leaf on a VA the allocator will later hand out, which `prepare_map` + /// then refuses with a silent EBUSY. There is no separate boolean unseal on + /// this path (`sleep_gate` / `preparations` already reopen in `hib_restore`). + /// Walks kernel-dynamic holes. When `clear`, unmaps untracked leaves and + /// issues a TLBI. After a reserved-table cold boot the firmware may rewrite + /// those leaves from its pre-image view; dropping a `KernelMapping` before + /// the boot is not enough. Never frees a drm_mm node here (holes only). + pub(crate) fn kernel_dynamic_holes(&self, clear: bool) -> Result<(u32, Option<(u64, u64)>)> { + let range = self.kernel_dynamic_range(); + let mut inner = lock_vm(&self.kernel_vm.gpuvm, None, false)?; + let mut covered = KVec::new(); + let mut cursor = range.start; + while cursor < range.end { + match inner.mm.first_overlap(cursor..range.end) { + Ok(Some(owned)) => { + let next = owned.end.max(cursor.saturating_add(1)); + covered.push(owned, GFP_KERNEL)?; + cursor = next; + } + Ok(None) => break, + Err(error) if error == EINVAL => break, + Err(error) => return Err(error), + } + } + let result = inner + .page_table + .clear_untracked_leaves(range, &covered, clear); + drop(inner); + let (cleared, first) = result?; + if clear && cleared != 0 { + mem::sync(); + mem::tlbi_all(); + mem::sync(); + } + Ok((cleared, first)) + } + + /// Canonical lower objects are aliased into every owning client VM. /// Sparse VA reservation has no physical-memory cost. pub(crate) fn kernel_lower_dynamic_range(&self) -> Range { @@ -4491,6 +4599,197 @@ impl Uat { Ok(()) } + /// Allocates the copy of the translation memory a hibernation image does not hold. + pub(crate) fn reserved_copy(&self) -> Result { + let mut tables = KVec::new(); + if let Some(reserved) = self.inner.reserved.as_deref() { + for map in reserved.regions() { + tables.push(KVVec::from_elem(0u8, map.size(), GFP_KERNEL)?, GFP_KERNEL)?; + } + } + Ok(ReservedCopy { + ttbs: KVVec::from_elem(0u8, SLOTS_SIZE, GFP_KERNEL)?, + tables, + }) + } + + /// Copies the context table and the reserved tables, with the firmware stopped and nothing + /// mapped or bound any more. + pub(crate) fn save_reserved(&self, copy: &mut ReservedCopy) { + let inner = self.inner.lock(); + let ttbs = inner.ttbs().as_ptr().cast::(); + pgtable::clean_invalidate_poc(ttbs, SLOTS_SIZE); + pgtable::poc_barrier(); + // SAFETY: Both are `SLOTS_SIZE` bytes and don't overlap. + unsafe { core::ptr::copy_nonoverlapping(ttbs, copy.ttbs.as_mut_ptr(), SLOTS_SIZE) }; + if let Some(reserved) = self.inner.reserved.as_deref() { + for (map, buf) in reserved.regions().zip(copy.tables.iter_mut()) { + let size = map.size().min(buf.len()); + pgtable::clean_invalidate_poc(map.ptr(), size); + pgtable::poc_barrier(); + // SAFETY: Both are at least `size` bytes and don't overlap. + unsafe { core::ptr::copy_nonoverlapping(map.ptr(), buf.as_mut_ptr(), size) }; + } + } + } + + /// The firmware boots afresh and keeps none of the clients' address spaces: every VM + /// created until now is lost to its client ([`Vm::outlived_firmware`]). + pub(crate) fn outlive_client_vms(&self) { + self.inner.client_epoch.fetch_add(1, Ordering::AcqRel); + self.inner.firmware_epoch.fetch_add(1, Ordering::AcqRel); + } + + /// The firmware boots afresh and keeps the clients' address spaces: their VMs stay, but + /// every context published until now names a slot the new boot does not know, and is + /// published again through a new queue ([`ExecutionContext::outlived_firmware`]). + pub(crate) fn outlive_client_contexts(&self) { + self.inner.firmware_epoch.fetch_add(1, Ordering::AcqRel); + } + + /// Before a cold boot on a restored image: the handoff starts afresh, the context table and + /// the kernel window's table go back as the image left them, and contexts 0 and 1 name the + /// kernel roots again, as [`Uat::new`] leaves them for a boot. The roots stay as this boot + /// handed them over: the firmware builds them while booting. + pub(crate) fn restore_reserved(&self, copy: &ReservedCopy) -> Result { + let ttb0 = self.kernel_lower_vm.ttb(); + let ttb1 = self.kernel_vm.ttb(); + let inner = self.inner.lock(); + inner + .handoff() + .init( + self.inner.firmware, + self.inner.quirks.handoff_slot, + self.inner.quirks.handoff_unk2, + )?; + let clean = self.inner.quirks.clean_tables; + if clean { + pgtable::clean_poc(core::ptr::from_ref(inner.handoff()).cast::(), HANDOFF_SIZE); + pgtable::poc_barrier(); + } + inner.handoff_lock(); + let ttbs = inner.ttbs(); + let saved = copy.ttbs.as_ptr().cast::(); + for (index, ctx) in ttbs.iter().enumerate() { + // SAFETY: The copy holds `UAT_NUM_CTX` pairs of words. + let (low, high) = unsafe { + (saved.add(2 * index).read_unaligned(), saved.add(2 * index + 1).read_unaligned()) + }; + ctx.ttb0.store(low, Ordering::Relaxed); + ctx.ttb1.store(high, Ordering::Relaxed); + } + ttbs[0].ttb0.store(ttb0 | TTBR_VALID, Ordering::SeqCst); + ttbs[0].ttb1.store(ttb1 | TTBR_VALID, Ordering::SeqCst); + if matches!(self.inner.firmware, UatFirmware::PublishedRoots { .. }) { + let alias = &ttbs[KERNEL_ALIAS_CTX]; + alias.ttb0.store(tagged_root(ttb0, KERNEL_ALIAS_CTX), Ordering::SeqCst); + alias.ttb1.store(tagged_root(ttb1, KERNEL_ALIAS_CTX), Ordering::SeqCst); + } + if clean { + pgtable::clean_poc(ttbs.as_ptr().cast::(), SLOTS_SIZE); + pgtable::poc_barrier(); + } + inner.handoff_unlock(); + core::mem::drop(inner); + if let Some(reserved) = self.inner.reserved.as_deref() { + if let (Some(map), Some(buf)) = + (reserved.regions().nth(KERNEL_WINDOW_TABLE), copy.tables.get(KERNEL_WINDOW_TABLE)) + { + let size = map.size().min(buf.len()); + // SAFETY: The firmware is stopped; both are at least `size` bytes and do not + // overlap. + unsafe { pgtable::copy_and_clean_poc(map.ptr(), buf.as_ptr(), size) }; + pgtable::poc_barrier(); + pr_info!("asahi: restored kernel-window tables ({} bytes)\n", size); + } + } + mem::sync(); + mem::tlbi_all(); + mem::sync(); + Ok(()) + } + + /// After the cold boot built the firmware's tables: compares each reserved table with the + /// copy, and writes back the kernel window's entries the boot did not keep. An entry the + /// boot set to another value there is a conflict and fails the restore. + pub(crate) fn merge_reserved(&self, copy: &ReservedCopy) -> Result<[ReservedMerge; 2]> { + let mut result = [ReservedMerge::default(); 2]; + let Some(reserved) = self.inner.reserved.as_deref() else { + return Ok(result); + }; + for (index, (map, buf)) in reserved.regions().zip(copy.tables.iter()).enumerate() { + let count = map.size().min(buf.len()) / size_of::(); + let window = index == KERNEL_WINDOW_TABLE; + let merge = &mut result[index.min(1)]; + for entry in 0..count { + // SAFETY: In bounds of both; table entries are only accessed as atomics. + let (live, saved) = unsafe { + ( + &*map.ptr().cast::().add(entry), + buf.as_ptr().cast::().add(entry).read_unaligned(), + ) + }; + let now = live.load(Ordering::Relaxed); + if now == saved { + continue; + } + if saved == 0 { + merge.added += 1; + } else if now == 0 { + merge.restored += 1; + if window { + live.store(saved, Ordering::Relaxed); + } + } else { + merge.conflicts += 1; + } + } + if window { + pgtable::clean_poc(map.ptr(), count * size_of::()); + pgtable::poc_barrier(); + } + } + mem::sync(); + mem::tlbi_all(); + mem::sync(); + if result[KERNEL_WINDOW_TABLE].conflicts != 0 { + return Err(EIO); + } + Ok(result) + } + + + /// After the clients' address spaces were declared lost: drop their context-table + /// slots, write the table and the handoff back to the point of coherency, and + /// invalidate the GPU TLB, so a new client's walk does not see a stale or uncached + /// TTB. + pub(crate) fn reset_outlived_contexts(&self) { + let inner = self.inner.lock(); + inner.handoff_lock(); + let ttbs = inner.ttbs(); + for index in 0..UAT_NUM_CTX { + if EXECUTION_CONTEXT_MASK & (1u64 << index) == 0 { + continue; + } + ttbs[index].ttb0.store(0, Ordering::Release); + ttbs[index].ttb1.store(0, Ordering::Release); + } + if inner.quirks.clean_tables || inner.clean_poc { + pgtable::clean_poc(ttbs.as_ptr().cast::(), SLOTS_SIZE); + pgtable::clean_poc(core::ptr::from_ref(inner.handoff()).cast::(), HANDOFF_SIZE); + pgtable::poc_barrier(); + } + inner.handoff_unlock(); + core::mem::drop(inner); + let mut inner = self.inner.lock(); + inner.execution_contexts &= !EXECUTION_CONTEXT_MASK; + core::mem::drop(inner); + mem::sync(); + mem::tlbi_all(); + mem::sync(); + } + + /// Discards the CPU's cached lines of the no-map table regions after the firmware built its /// root there during boot (`UatQuirks::reserved_tables`; see `ReservedTables::invalidate`). pub(crate) fn invalidate_reserved_tables(&self) { @@ -4548,6 +4847,8 @@ impl Uat { firmware, m4_adopted: false, failed: AtomicBool::new(false), + firmware_epoch: AtomicU32::new(0), + client_epoch: AtomicU32::new(0), clean_poc: quirks.clean_tables, quirks, reserved, @@ -4602,7 +4903,7 @@ impl Uat { let of_node = dev.as_ref().as_ref().of_node().ok_or(EINVAL)?; let reserved = if quirks.reserved_tables { let mut tables = pgtable::ReservedTables::new(); - for name in [c"pagetables", c"l2-pagetables"] { + for name in RESERVED_TABLES { let res = of_node.reserved_mem_region_to_resource_byname(name)?; // SAFETY: The boot loader reserved these regions (no-map) for the firmware's // page tables; they stay reserved until reboot. @@ -4742,6 +5043,12 @@ impl Drop for Uat { } impl Vm { + /// The firmware this VM was created for is gone: firmware booted afresh knows none of the + /// address spaces from before it, so nothing of this VM runs any more. + pub(crate) fn outlived_firmware(&self) -> bool { + self.uat_inner.client_epoch.load(Ordering::Acquire) != self.firmware_epoch + } + /// Diagnostic reservation occupancy (including guards), not a placement promise. /// Removal can progress between queries; allocations are excluded by the VM lock. pub(crate) fn capacity(&self, range: Range) -> Result<(u64, u64)> { diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index c56079f6f8035..389b63319a671 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -106,6 +106,33 @@ pub(crate) fn clean_poc(ptr: *const u8, len: usize) { } } +/// Copies `len` bytes and cleans each destination cache line in one walk, so a non-snooping +/// walker sees the new contents without a second pass over the range. +pub(crate) unsafe fn copy_and_clean_poc(dst: *mut u8, src: *const u8, len: usize) { + if len == 0 { + return; + } + let line = dcache_line_size(); + let end = dst as usize + len; + let mut off = 0usize; + // Copy a line (or the leading/trailing fragment), then clean that line. + while (dst as usize + off) < end { + let addr = (dst as usize + off) & !(line - 1); + let next = core::cmp::min(addr + line, end); + let chunk = next - (dst as usize + off); + // SAFETY: `off + chunk` stays in `len`; src/dst do not overlap. + unsafe { + core::ptr::copy_nonoverlapping(src.add(off), dst.add(off), chunk); + core::arch::asm!( + "dc cvac, {addr}", + addr = in(reg) addr, + options(nostack, preserves_flags) + ); + } + off += chunk; + } +} + /// Cleans and invalidates the CPU data cache lines covering `len` bytes at `ptr` to the point of /// coherency, so that later CPU reads observe what a non-snooping agent wrote. Lines the CPU wrote /// are written back first. [`poc_barrier`] completes the maintenance. @@ -187,6 +214,11 @@ impl ReservedTables { None } + /// The regions, in the order they were added. + pub(crate) fn regions(&self) -> impl Iterator { + self.regions.iter() + } + /// Whether `phys` is a page of one of the regions. pub(crate) fn contains(&self, phys: PhysicalAddr) -> bool { self.lookup(phys).is_some() @@ -1086,6 +1118,84 @@ impl UatPageTable { self.with_pages(range, missing, false, |_, _| Ok(())) } + /// Walk IOVAs are masked by [`Self::ias_mask`]. Reassemble the canonical VA + /// so a comparison with a full drm_mm range is meaningful (0x2003124000 vs + /// 0xfffffc2003124000). + fn canonical_iova(ias_mask: u64, range: &Range, masked: u64) -> u64 { + (range.start & !ias_mask) | (masked & ias_mask) + } + + /// Zero live leaves in `range` that do not fall inside any `tracked` VA interval. + /// After a hibernation restore, firmware-rebuilt reserved tables can leave + /// PTEs in VA ranges whose drm_mm nodes were already freed. Those leaves + /// make the next map fail with EBUSY. + pub(crate) fn clear_untracked_leaves( + &mut self, + range: Range, + tracked: &[Range], + clear: bool, + ) -> Result<(u32, Option<(u64, u64)>)> { + if range.is_empty() { + return Ok((0, None)); + } + if (range.start | range.end) & UAT_PGMSK as u64 != 0 { + return Err(EINVAL); + } + let mut cleared = 0u32; + let mut first = None; + let ias_mask = self.ias_mask; + self.walk(range.clone(), Missing::Skip, false, clear, |iova, ptes| { + for (idx, pte) in ptes.iter().enumerate() { + let addr = Self::canonical_iova(ias_mask, &range, iova + (idx * UAT_PGSZ) as u64); + if addr < range.start || addr >= range.end { + continue; + } + let val = pte.load(Ordering::Relaxed); + if val == 0 { + continue; + } + let owned = tracked.iter().any(|r| addr >= r.start && addr < r.end); + if owned { + continue; + } + if clear { + pte.store(0, Ordering::Relaxed); + } + if first.is_none() { + first = Some((addr, val)); + } + cleared = cleared.saturating_add(1); + } + Ok(()) + })?; + Ok((cleared, first)) + } + + /// First live leaf in `range`, as (canonical IOVA, PTE). Used to refuse + /// freeing a drm_mm node while its leaves are still set. + pub(crate) fn first_live_leaf(&mut self, range: Range) -> Result> { + if range.is_empty() { + return Ok(None); + } + if (range.start | range.end) & UAT_PGMSK as u64 != 0 { + return Err(EINVAL); + } + let mut found = None; + let ias_mask = self.ias_mask; + self.walk(range.clone(), Missing::Skip, false, false, |iova, ptes| { + if found.is_some() { + return Ok(()); + } + if let Some(idx) = ptes.iter().position(|pte| pte.load(Ordering::Relaxed) != 0) { + let addr = Self::canonical_iova(ias_mask, &range, iova + (idx * UAT_PGSZ) as u64); + let val = ptes[idx].load(Ordering::Relaxed); + found = Some((addr, val)); + } + Ok(()) + })?; + Ok(found) + } + fn pte_bits(&self) -> u64 { if self.ttb_owned { // Owned page tables are userspace, so non-global diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 2343f312a4674..9809cde74c1b2 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -189,6 +189,13 @@ pub(crate) trait Queue: Send + Sync { Err(EINVAL) } + /// The firmware booted afresh and kept this queue's VM, but nothing of the queue itself: + /// the file builds it again, with the arguments it was created with, before its next + /// submission. + fn needs_rebuild(&self) -> bool { + false + } + fn reserve_render_scs(&mut self, layouts: [u64; 2]) -> Result { if layouts != [0; 2] { return Err(EINVAL); diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid.c b/drivers/hid/dockchannel-hid/dockchannel-hid.c index 98b4a13341098..afccce35bd47f 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid.c @@ -259,6 +259,12 @@ struct dockchannel_hid { void *ring; dma_addr_t ring_dma; u32 ring_read; + /* + * Set by a restore from disk: until a ring frame has been read, the + * firmware may carry on from the ring position of the boot kernel's + * session instead of the image's. + */ + bool ring_resync; bool id_ready; struct dchid_stm_id device_id; char serial[64]; @@ -2042,11 +2048,39 @@ static int dchid_drain_ring_buf(struct dockchannel_hid *dchid, void *ring, /* All frame reads must complete before the producer can reuse it. */ mb(); WRITE_ONCE(indices[1], consumer); + WRITE_ONCE(dchid->ring_resync, false); cond_resched(); } return 0; } +/* + * The boot kernel of a resume from disk hands the running firmware to the + * image, but the ring indices in memory are the image's, while the firmware + * goes on writing from where the boot kernel's session left off. The first + * ring that does not add up after a restore is therefore skipped: everything + * up to the producer the firmware published last is dropped, and receiving + * goes on from there. + */ +static bool dchid_ring_resync(struct dockchannel_hid *dchid) +{ + const u32 capacity = dchid->ring_size - DCHID_RING_HEADER_SIZE; + u32 *indices = dchid->ring; + u32 producer = READ_ONCE(indices[0]); + + if (!READ_ONCE(dchid->ring_resync) || producer >= capacity || + !IS_ALIGNED(producer, 4)) + return false; + dev_dbg(dchid->dev, "receive ring resynchronised after a restore (consumer %#x read %#x producer %#x)\n", + READ_ONCE(indices[1]), dchid->ring_read, producer); + WRITE_ONCE(dchid->ring_resync, false); + dchid->ring_read = producer; + /* As in dchid_drain_ring(): order the reads before handing space back. */ + mb(); + WRITE_ONCE(indices[1], producer); + return true; +} + static int dchid_drain_ring(struct dockchannel_hid *dchid) { return dchid_drain_ring_buf(dchid, dchid->ring, dchid->ring_size, @@ -2270,8 +2304,16 @@ static void dchid_handle_packet(void *cookie, size_t avail) if (READ_ONCE(dchid->stopping)) return; + if (pm_hibernate_is_restored() && avail < sizeof(hdr)) { + dev_dbg(dchid->dev, "short receive wake (%zu bytes) after restore; re-arming\n", + avail); + goto done; + } + if (dockchannel_recv(dchid->dc, &hdr, sizeof(hdr)) != sizeof(hdr)) { dev_err(dchid->dev, "Read failed (header)\n"); + if (pm_hibernate_is_restored()) + goto done; return; } if (hdr.hdr_len != sizeof(hdr)) { @@ -2285,6 +2327,8 @@ static void dchid_handle_packet(void *cookie, size_t avail) if (dchid_dispatch(dchid, &hdr, dchid->pkt_buf, true)) { ret = dchid_drain_ring(dchid); + if (ret < 0 && dchid_ring_resync(dchid)) + ret = dchid_drain_ring(dchid); if (ret < 0) dev_err(dchid->dev, "Receive ring failed: %d\n", ret); } @@ -2699,8 +2743,24 @@ static int dockchannel_hid_resume(struct device *dev) return ret; } -static DEFINE_SIMPLE_DEV_PM_OPS(dockchannel_hid_pm_ops, dockchannel_hid_suspend, - dockchannel_hid_resume); +/* After a restore from disk, also resynchronise the receive ring. */ +static int dockchannel_hid_restore(struct device *dev) +{ + struct dockchannel_hid *dchid = dev_get_drvdata(dev); + + if (dchid->use_rx_ring) + WRITE_ONCE(dchid->ring_resync, true); + return dockchannel_hid_resume(dev); +} + +static const struct dev_pm_ops dockchannel_hid_pm_ops = { + .suspend = pm_sleep_ptr(dockchannel_hid_suspend), + .resume = pm_sleep_ptr(dockchannel_hid_resume), + .freeze = pm_sleep_ptr(dockchannel_hid_suspend), + .thaw = pm_sleep_ptr(dockchannel_hid_resume), + .poweroff = pm_sleep_ptr(dockchannel_hid_suspend), + .restore = pm_sleep_ptr(dockchannel_hid_restore), +}; static const struct of_device_id dockchannel_hid_of_match[] = { { .compatible = "apple,dockchannel-hid" }, diff --git a/drivers/i2c/busses/i2c-pasemi-platform.c b/drivers/i2c/busses/i2c-pasemi-platform.c index 827873107301c..4ed9cd197a18c 100644 --- a/drivers/i2c/busses/i2c-pasemi-platform.c +++ b/drivers/i2c/busses/i2c-pasemi-platform.c @@ -51,9 +51,12 @@ static int pasemi_platform_i2c_runtime_resume(struct device *dev) return 0; } -static DEFINE_RUNTIME_DEV_PM_OPS(pasemi_platform_i2c_pm_ops, - pasemi_platform_i2c_runtime_suspend, - pasemi_platform_i2c_runtime_resume, NULL); +static const struct dev_pm_ops pasemi_platform_i2c_pm_ops = { + LATE_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, + pm_runtime_force_resume) + RUNTIME_PM_OPS(pasemi_platform_i2c_runtime_suspend, + pasemi_platform_i2c_runtime_resume, NULL) +}; static void pasemi_platform_i2c_disable_pm(void *arg) { diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index b647a19ae8867..97b7d944940e3 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -386,7 +386,7 @@ static void apple_dart_test_locked_handoff(struct kunit *test) cfg.apple_dart_cfg.ttbr[0] = ours; /* Legacy firmware mappings are rebuilt by the IOMMU core at handoff. */ - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false), 0); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false, false), 0); KUNIT_EXPECT_MEMEQ(test, live, ours, sizeof(live)); KUNIT_EXPECT_MEMEQ(test, owned, ours, sizeof(owned)); apple_dart_retire_root(live, owned, ARRAY_SIZE(live)); @@ -397,7 +397,7 @@ static void apple_dart_test_locked_handoff(struct kunit *test) dart->hw = &apple_dart_hw_t8110; dart->version = 0x0200; live[0] = 0x1001; - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false), 0); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false, false), 0); KUNIT_EXPECT_MEMEQ(test, live, ours, sizeof(live)); } @@ -424,11 +424,11 @@ static void apple_dart_test_sync_unknown_roots(struct kunit *test) cfg.apple_dart_cfg.ttbr[0] = ours; /* An early TLB sync skips the stream and leaves the root alone... */ - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, true), 0); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, true, false), 0); KUNIT_EXPECT_EQ(test, live[0], 0x1001ULL); KUNIT_EXPECT_EQ(test, live[1], 0ULL); /* ...but publishing at attach still requires both. */ - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false), -EIO); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false, false), -EIO); KUNIT_EXPECT_EQ(test, live[1], 0ULL); } @@ -455,13 +455,13 @@ static void apple_dart_test_firmware_roots(struct kunit *test) cfg.apple_dart_cfg.n_ttbrs = 1; cfg.apple_dart_cfg.ttbr[0] = ours; - KUNIT_ASSERT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false), 0); + KUNIT_ASSERT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false, false), 0); KUNIT_EXPECT_EQ(test, live[0], 0x1001ULL); KUNIT_EXPECT_EQ(test, live[1], 0x2001ULL); ours[0] = 0x3001; - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false, false), -EBUSY); dart->version = 0x0203; - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(&cfg, &stream, false, false), -EBUSY); KUNIT_EXPECT_EQ(test, live[0], 0x1001ULL); /* Teardown must preserve a root which firmware has since replaced. */ live[1] = 0x4001; @@ -526,7 +526,7 @@ static void apple_dart_test_unmap_flush_after_publish_failure(struct kunit *test writel(sentinel, other->regs + DART_T8110_TLB_CMD); stream.dart = locked; __set_bit(0, stream.sidmap); - KUNIT_ASSERT_EQ(test, apple_dart_hw_sync_locked(&iop->cfg, &stream, true), + KUNIT_ASSERT_EQ(test, apple_dart_hw_sync_locked(&iop->cfg, &stream, true, false), -EBUSY); /* The pages are freed after this: both DARTs must drop them. */ @@ -540,6 +540,59 @@ static void apple_dart_test_unmap_flush_after_publish_failure(struct kunit *test pm_runtime_disable(other->dev); } +/* + * A display DART whose hibernation .restore waits for its display's power-up: + * its registers aren't touched, while the domain's other DARTs still flush. + */ +static void apple_dart_test_restore_deferred(struct kunit *test) +{ + struct iommu_iotlb_gather gather = { .start = 0, .end = SZ_16K - 1 }; + struct apple_dart_domain *domain; + struct apple_dart *pending, *other; + struct io_pgtable *iop; + u64 ours[] = { 0x3001, 0, 0, 0 }; + u32 sentinel = 0x40; + + if (!IS_ENABLED(CONFIG_HIBERNATION)) + kunit_skip(test, "needs CONFIG_HIBERNATION"); + pending = apple_dart_test_t8110(test, "apple-dart-restore-pending"); + pending->pgsize = SZ_16K; + pending->restore_pending = true; + other = apple_dart_test_t8110(test, "apple-dart-restore-other"); + other->pgsize = SZ_16K; + + iop = kunit_kzalloc(test, sizeof(*iop), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, iop); + iop->cfg.apple_dart_cfg.n_ttbrs = 1; + iop->cfg.apple_dart_cfg.ttbr[0] = ours; + domain = kunit_kzalloc(test, sizeof(*domain), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, domain); + domain->pgtbl_ops = &iop->ops; + domain->stream_maps[0].dart = pending; + atomic_long_set(&domain->stream_maps[0].sidmap[0], 1); + domain->stream_maps[1].dart = other; + atomic_long_set(&domain->stream_maps[1].sidmap[0], 1); + + writel(sentinel, pending->regs + DART_T8110_TLB_CMD); + writel(sentinel, other->regs + DART_T8110_TLB_CMD); + apple_dart_iotlb_sync(&domain->domain, &gather); + KUNIT_EXPECT_EQ(test, readl(pending->regs + DART_T8110_TLB_CMD), sentinel); + KUNIT_EXPECT_NE(test, readl(other->regs + DART_T8110_TLB_CMD), sentinel); + + /* A map that would need the loader's live roots fails without a read. */ + pending->fw_mirror = true; + KUNIT_EXPECT_EQ(test, apple_dart_check_fw_map(domain, 0, 0x80000000ULL, + SZ_16K, IOMMU_READ), + -EBUSY); + KUNIT_EXPECT_EQ(test, readl(pending->regs + DART_T8110_TLB_CMD), sentinel); + + KUNIT_EXPECT_EQ(test, atomic_read(&pending->dev->power.usage_count), 0); + KUNIT_EXPECT_EQ(test, atomic_read(&other->dev->power.usage_count), 0); + pending->restore_pending = false; + pm_runtime_disable(pending->dev); + pm_runtime_disable(other->dev); +} + static void apple_dart_test_gated_commands(struct kunit *test) { struct apple_dart_stream_map stream = {}; @@ -2313,7 +2366,7 @@ static void apple_dart_test_four_level_live_import(struct kunit *test) /* The attach publishes nothing into the slot firmware holds. */ stream.dart = four.dart; __set_bit(23, stream.sidmap); - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(cfg, &stream, false), 0); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(cfg, &stream, false, false), 0); KUNIT_EXPECT_EQ(test, four.root[16], slot); /* A Linux copy of the same page in that slot is refused, the slot kept. */ @@ -2321,7 +2374,7 @@ static void apple_dart_test_four_level_live_import(struct kunit *test) apple_dart_test_four_pa, SZ_16K, 1, IOMMU_READ | IOMMU_WRITE, GFP_KERNEL, &mapped); KUNIT_ASSERT_EQ(test, ret, 0); - KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(cfg, &stream, false), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_dart_hw_sync_locked(cfg, &stream, false, false), -EBUSY); KUNIT_EXPECT_EQ(test, four.root[16], slot); apple_dart_test_four_teardown(&four, domain); @@ -2615,6 +2668,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_display_keep), KUNIT_CASE(apple_dart_test_v27_cycle_errors), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), + KUNIT_CASE(apple_dart_test_restore_deferred), KUNIT_CASE(apple_dart_test_gated_commands), KUNIT_CASE(apple_dart_test_resume_commands_failure), KUNIT_CASE(apple_dart_test_tunnel_restore), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 94f03a40a7f13..84636f6443fab 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -414,6 +414,12 @@ struct apple_dart { bool display_tlb_stale; unsigned int display_writers; unsigned int display_dark_writers; + /* + * Its block was powered down by its display consumer (the DCP's power word step), which + * raises it again: a hibernation .restore defers to apple_dart_display_restore(). + */ + bool display_unpowered; + bool restore_pending; DECLARE_BITMAP(display_tcr_four, DART_MAX_STREAMS); /* T8020: its enabled streams and translations, saved at the display's power-down */ u32 display_enable; @@ -628,6 +634,14 @@ struct apple_dart { * The first error of each stream is logged. */ int locked_retire_err[DART_MAX_STREAMS]; + /* Physical address of each mapped locked root, as read from its TTBR. */ + phys_addr_t locked_phys[DART_MAX_STREAMS][DART_MAX_TTBR]; + /* + * Page-table configuration last published into each locked stream's + * roots, for the re-import after a resume from disk (the boot loader + * installs fresh firmware roots). Cleared when the stream's roots retire. + */ + struct io_pgtable_cfg *locked_cfg[DART_MAX_STREAMS]; }; #define APPLE_DART_WRITER_COUNTED 1 @@ -1137,6 +1151,37 @@ static bool apple_dart_display_scanout(struct device_node *np) return false; } +#ifdef CONFIG_HIBERNATION +/* + * Locked DARTs whose consumer is a coprocessor the boot loader restarts + * (the display pipe, or the PMP): reimport at that consumer's power-up, + * not in the DART's own .restore, so the loader's roots are no longer live. + */ +static bool apple_dart_hib_defer_reimport(struct device_node *np) +{ + struct of_phandle_args args; + int i; + + if (apple_dart_display_scanout(np)) + return true; + + for_each_compatible_node_scoped(pmp, NULL, "apple,t6000-pmp-v2") { + if (!of_device_is_available(pmp)) + continue; + for (i = 0; !of_parse_phandle_with_args(pmp, "iommus", + "#iommu-cells", i, + &args); i++) { + bool match = args.np == np; + + of_node_put(args.np); + if (match) + return true; + } + } + return false; +} +#endif + /* A 16K table page, aligned and inside the output address space. */ static bool apple_dart_fw_table_page(const struct apple_dart *dart, phys_addr_t phys, phys_addr_t *end) @@ -1290,7 +1335,7 @@ static bool apple_dart_fw_slot_mirrors(const struct apple_dart *dart, static int apple_dart_publish_root(const struct apple_dart *dart, u64 *live, u64 *owned, const u64 *ours, struct apple_dart_fw_root *fw, - size_t entries) + size_t entries, bool adopt) { size_t i; @@ -1300,6 +1345,13 @@ static int apple_dart_publish_root(const struct apple_dart *dart, if (!next && !previous) continue; + /* + * Hibernation adopt: owned was forgotten and the boot loader + * filled a new root. A vacant slot is not already published, + * and the pre-image tables need not mirror the loader's slots. + */ + if (adopt) + continue; if (READ_ONCE(live[i]) == previous) continue; if (previous || !apple_dart_fw_slot_owned(fw, live, i)) @@ -1313,7 +1365,24 @@ static int apple_dart_publish_root(const struct apple_dart *dart, for (i = 0; i < entries; i++) { u64 next = READ_ONCE(ours[i]); u64 previous = READ_ONCE(owned[i]); + u64 live_now = READ_ONCE(live[i]); + if (adopt && next) { + if (apple_dart_fw_slot_owned(fw, live, i) && + apple_dart_fw_slot_mirrors(dart, fw, next, i, entries)) { + fw->accepted[i] = next; + continue; + } + /* Take the slot: the boot loader's session is over. */ + if (cmpxchg(&live[i], live_now, next) != live_now) + return -EBUSY; + WRITE_ONCE(owned[i], next); + if (fw && fw->entry) + WRITE_ONCE(fw->entry[i], 0); + if (fw && fw->accepted) + WRITE_ONCE(fw->accepted[i], 0); + continue; + } if (next == previous) continue; if (!previous && apple_dart_fw_slot_owned(fw, live, i)) { @@ -1598,6 +1667,7 @@ apple_dart_hw_map_locked_ttbr(struct apple_dart_stream_map *stream_map, u8 idx) dart->locked_owned[sid][idx] = owned; dart->locked_ttbr[sid][idx] = l1_tbl; dart->locked_fw[sid][idx] = fw; + dart->locked_phys[sid][idx] = phys; if (!idx) dart->locked_fw_tree[sid] = tree; spin_unlock_irqrestore(&dart->lock, flags); @@ -1646,6 +1716,8 @@ apple_dart_hw_unmap_locked_ttbr(struct apple_dart_stream_map *stream_map, u8 idx fw = dart->locked_fw[sid][idx]; dart->locked_fw[sid][idx] = NULL; dart->locked_ttbr[sid][idx] = NULL; + dart->locked_phys[sid][idx] = 0; + dart->locked_cfg[sid] = NULL; if (!idx) { tree = dart->locked_fw_tree[sid]; dart->locked_fw_tree[sid] = NULL; @@ -1685,7 +1757,7 @@ static int apple_dart_retire_error(struct apple_dart_stream_map *stream_map) static int apple_dart_hw_sync_locked(struct io_pgtable_cfg *cfg, struct apple_dart_stream_map *stream_map, - bool defer_unknown) + bool defer_unknown, bool adopt) { struct apple_dart *dart = stream_map->dart; unsigned long flags; @@ -1745,10 +1817,13 @@ apple_dart_hw_sync_locked(struct io_pgtable_cfg *cfg, } ret = apple_dart_publish_root(dart, live, owned, ours, dart->locked_fw[sid][idx], - dart->pgsize / sizeof(*live)); + dart->pgsize / sizeof(*live), + adopt); if (ret) goto out; } + if (dart->locked_ttbr[sid][0]) + dart->locked_cfg[sid] = cfg; } out: spin_unlock_irqrestore(&dart->lock, flags); @@ -2967,11 +3042,27 @@ static int __apple_dart_dcp_domain_flush(struct apple_dart_domain *domain); * hold the stream's lock, which the power-up takes; apple_dart_host_lock()). * A power-up that completed meanwhile confirmed the power in the same step. */ +/* + * A hibernation .restore deferred to its display's power-up + * (apple_dart_restore()): the restoring boot's loader locked the DART again + * with roots of its own, which hold none of this kernel's tables, and its + * block may not answer. Until apple_dart_display_restore() nothing reads or + * writes its registers: a flush has nothing of ours to drop, and a map that + * would need its live roots fails instead. + */ +static bool apple_dart_restore_deferred(struct apple_dart *dart) +{ + return IS_ENABLED(CONFIG_HIBERNATION) && READ_ONCE(dart->restore_pending); +} + static int apple_dart_dcp_domain_flush(struct apple_dart_domain *domain) { struct apple_dart *dart = domain->dcp->dart; int ret; + /* See apple_dart_restore_deferred(): no register of it is touched. */ + if (apple_dart_restore_deferred(dart)) + return 0; if (!apple_dart_pm_get(dart)) { if (READ_ONCE(dart->host_off)) return 0; @@ -3037,6 +3128,8 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, stream.sidmap[j] = atomic_long_read(&map->sidmap[j]); if (bitmap_empty(stream.sidmap, stream.dart->num_streams)) continue; + if (apple_dart_restore_deferred(stream.dart)) + continue; /* * Its display is powered off: publish to memory only. With its streams off * nothing walks the tables, and the TLB is invalidated before they're on. @@ -3052,7 +3145,7 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, spin_unlock_irqrestore(&stream.dart->managed_lock, flags); if (dark) { ret = stream.dart->locked ? - apple_dart_hw_sync_locked(cfg, &stream, true) : 0; + apple_dart_hw_sync_locked(cfg, &stream, true, false) : 0; spin_lock_irqsave(&stream.dart->managed_lock, flags); stream.dart->display_dark_writers--; spin_unlock_irqrestore(&stream.dart->managed_lock, flags); @@ -3065,7 +3158,7 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, /* Closed for its owner's power cycle: likewise, the owner flushes it. */ if (gate == APPLE_DART_WRITER_CLOSED) { ret = stream.dart->locked ? - apple_dart_hw_sync_locked(cfg, &stream, true) : 0; + apple_dart_hw_sync_locked(cfg, &stream, true, false) : 0; apple_dart_sleep_writer_put(stream.dart, gate); spin_lock_irqsave(&stream.dart->managed_lock, flags); stream.dart->display_writers--; @@ -3085,7 +3178,7 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, continue; } ret = stream.dart->locked ? - apple_dart_hw_sync_locked(cfg, &stream, true) : 0; + apple_dart_hw_sync_locked(cfg, &stream, true, false) : 0; if (ret) { dev_err_ratelimited(stream.dart->dev, "failed to publish host page-table entries: %d\n", ret); @@ -3195,6 +3288,9 @@ static int apple_dart_check_fw_map(struct apple_dart_domain *domain, u64 dva, if (!dart->fw_handoff && !dart->fw_mirror) continue; + /* Its live roots are the loader's until the deferred restore. */ + if (apple_dart_restore_deferred(dart)) + return -EBUSY; spin_lock_irqsave(&dart->lock, flags); for (off = 0; off < size; off += dart->pgsize) { u64 addr = dva + off; @@ -3676,7 +3772,7 @@ apple_dart_setup_translation_locked(struct apple_dart_domain *domain, if (ret) goto unmap; } - ret = apple_dart_hw_sync_locked(cfg, stream_map, false); + ret = apple_dart_hw_sync_locked(cfg, stream_map, false, false); if (!ret) ret = stream_map->dart->hw->invalidate_tlb(stream_map); if (!ret) @@ -8749,8 +8845,210 @@ static __maybe_unused int apple_dart_sys_resume_noirq(struct device *dev) return pm_suspend_via_firmware() ? apple_dart_resume_noirq(dev) : 0; } +#ifdef CONFIG_HIBERNATION +/* + * After a resume from disk through a boot, the boot loader has locked every + * locked DART again with fresh firmware-owned roots, while the restored kernel + * still describes the roots of the image (their mapping, their firmware + * snapshot and the slots it had published): every publication then fails + * (-EBUSY), and with it every DMA mapping through the DART (the PMP and every + * DCP fail their buffer requests with -ENOMEM). .restore re-reads the live + * roots whichever kernel loaded the image, re-imports them the way attach maps + * them, and publishes the stream's page tables into them again, as attach + * does. A root at the address the image describes is re-read too: the boot + * loader places its roots the same way on every boot, and fills them afresh, + * without the slots the image published. Firmware-owned memory is never + * written: the old roots' published slots are forgotten, not retired. + */ +static int apple_dart_reimport_locked(struct apple_dart *dart) +{ + DECLARE_BITMAP(redo, DART_MAX_STREAMS) = {}; + unsigned int sid, idx; + int ret = 0, done = 0; + + /* + * Two passes, as attach does: every stream's live roots are re-read and + * snapshotted before any of them is republished, so that a root shared + * by several streams is snapshotted before Linux slots enter it. + */ + for (sid = 0; sid < dart->num_streams; sid++) { + bool any = false; + + for (idx = 0; idx < dart->hw->ttbr_count; idx++) { + u64 *live = dart->locked_ttbr[sid][idx]; + u64 *owned = dart->locked_owned[sid][idx]; + struct apple_dart_fw_tree *tree = NULL, *old_tree = NULL; + struct apple_dart_fw_root *fw, *old_fw; + unsigned long flags; + phys_addr_t phys; + u64 *l1; + u32 ttbr; + + if (!live || !owned) + continue; + ttbr = apple_dart_readl(dart, DART_TTBR(dart, sid, idx)); + if (!(ttbr & dart->hw->ttbr_valid)) { + dev_err(dart->dev, "hibernation restore: stream %u ttbr[%u] not valid\n", + sid, idx); + ret = ret ?: -EIO; + continue; + } + ttbr &= ~dart->hw->ttbr_valid; + if (dart->hw->ttbr_addr_field_shift) + ttbr >>= dart->hw->ttbr_addr_field_shift; + phys = ((phys_addr_t)ttbr) << dart->hw->ttbr_shift; + if (dart->fw_handoff && !apple_dart_fw_table_ram(dart, phys)) { + ret = ret ?: -EINVAL; + continue; + } + l1 = devm_memremap(dart->dev, phys, dart->pgsize, MEMREMAP_WB); + if (IS_ERR(l1)) { + ret = ret ?: PTR_ERR(l1); + continue; + } + fw = apple_dart_snapshot_fw_root(dart, sid, l1); + if (IS_ERR(fw)) { + devm_memunmap(dart->dev, l1); + ret = ret ?: PTR_ERR(fw); + continue; + } + if (!idx) + tree = apple_dart_snapshot_fw_tree(dart, sid, l1); + spin_lock_irqsave(&dart->lock, flags); + old_fw = dart->locked_fw[sid][idx]; + memset(owned, 0, dart->pgsize); + dart->locked_ttbr[sid][idx] = l1; + dart->locked_phys[sid][idx] = phys; + dart->locked_fw[sid][idx] = fw; + if (!idx) { + old_tree = dart->locked_fw_tree[sid]; + dart->locked_fw_tree[sid] = tree; + } + spin_unlock_irqrestore(&dart->lock, flags); + apple_dart_free_fw_root(dart, old_fw); + apple_dart_free_fw_tree(dart, old_tree); + devm_memunmap(dart->dev, live); + any = true; + } + if (any) + __set_bit(sid, redo); + } + + for_each_set_bit(sid, redo, dart->num_streams) { + struct apple_dart_stream_map stream = { .dart = dart }; + struct io_pgtable_cfg *cfg = READ_ONCE(dart->locked_cfg[sid]); + int err; + + if (!cfg) + continue; + __set_bit(sid, stream.sidmap); + err = apple_dart_hw_sync_locked(cfg, &stream, false, true); + if (!err) + err = dart->hw->invalidate_tlb(&stream); + if (err) { + dev_err(dart->dev, "hibernation restore: stream %u not republished: %d\n", + sid, err); + ret = ret ?: err; + continue; + } + done++; + } + dev_dbg(dart->dev, "hibernation restore: %d locked streams re-imported (%d)\n", + done, ret); + return ret; +} + +static int apple_dart_restore(struct device *dev) +{ + struct apple_dart *dart = dev_get_drvdata(dev); + int ret; + + /* + * No register of a block its consumer took down can be read before it + * is up. Locked display and PMP DARTs also defer: the boot loader + * still owns those roots until the consumer's power-up. A reimport + * here races with that and fails with -EBUSY. + */ + if (READ_ONCE(dart->display_unpowered) || + (dart->locked && apple_dart_hib_defer_reimport(dev->of_node))) { + WRITE_ONCE(dart->restore_pending, true); + dev_info(dev, "hibernation restore deferred until the consumer is up\n"); + return 0; + } + ret = apple_dart_system_resume(dev); + if (ret || !dart->locked) + return ret; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + /* Logged per stream; a failed stream must not fail the whole restore. */ + apple_dart_reimport_locked(dart); + pm_runtime_put(dev); + return 0; +} +#endif + +/* The display consumer powers the DART's block down: see apple_dart_restore(). */ +void apple_dart_display_unpowered(struct device *dev) +{ + struct apple_dart *dart = dev_get_drvdata(dev); + + if (dart) + WRITE_ONCE(dart->display_unpowered, true); +} +EXPORT_SYMBOL_GPL(apple_dart_display_unpowered); + +/* + * The display consumer powered the DART's block up again: a .restore deferred by + * apple_dart_restore() runs now, the resume and the re-import of the locked roots. + */ +int apple_dart_display_restore(struct device *dev) +{ + struct apple_dart *dart = dev_get_drvdata(dev); + int ret = 0; + + if (!dart) + return -ENODEV; + WRITE_ONCE(dart->display_unpowered, false); +#ifdef CONFIG_HIBERNATION + if (!dart->restore_pending) + return 0; + WRITE_ONCE(dart->restore_pending, false); + { + ktime_t adopt_start = ktime_get(); + + ret = apple_dart_system_resume(dev); + if (ret || !dart->locked) { + if (ret) + dev_err(dev, "deferred hibernation restore failed: %d\n", ret); + return ret; + } + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + ret = apple_dart_reimport_locked(dart); + pm_runtime_put(dev); + if (ret) + WRITE_ONCE(dart->restore_pending, true); + dev_info(dev, "hibernation restore at consumer power-up: %d in %lld us\n", + ret, ktime_to_us(ktime_sub(ktime_get(), adopt_start))); + } +#endif + return ret; +} +EXPORT_SYMBOL_GPL(apple_dart_display_restore); + static const struct dev_pm_ops apple_dart_pm_ops = { - SYSTEM_SLEEP_PM_OPS(apple_dart_system_suspend, apple_dart_system_resume) + .suspend = pm_sleep_ptr(apple_dart_system_suspend), + .resume = pm_sleep_ptr(apple_dart_system_resume), + .freeze = pm_sleep_ptr(apple_dart_system_suspend), + .thaw = pm_sleep_ptr(apple_dart_system_resume), + .poweroff = pm_sleep_ptr(apple_dart_system_suspend), +#ifdef CONFIG_HIBERNATION + .restore = apple_dart_restore, +#else + .restore = pm_sleep_ptr(apple_dart_system_resume), +#endif NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_dart_sys_suspend_noirq, apple_dart_sys_resume_noirq) RUNTIME_PM_OPS(apple_dart_suspend, apple_dart_resume, NULL) }; diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index ef8c31817b9ac..7b922ccba6871 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -1300,6 +1300,11 @@ static void build_fiq_affinity(struct aic_irq_chip *ic, struct device_node *aff) * mask everything before the commit, so that no line can end the final WFI, and * put it all back after. Linux never writes IRQ_CFG or these global registers * outside of config's enable bit, so they hold what the bootloader set. + * + * A hibernation image is restored after a reboot, with the masks and the IRQ + * configuration as the kernel that loaded the image left them: a line that + * kernel had no driver for stays masked. The image keeps what it saved when + * it was made, and puts it back the same way. */ static struct { u32 config; @@ -1307,6 +1312,7 @@ static struct { u32 cluster_prio; u32 *irq_cfg; bool saved; + bool hibernation; } aic_sleep; static int aic_syscore_suspend(void *data) @@ -1314,7 +1320,7 @@ static int aic_syscore_suspend(void *data) struct aic_irq_chip *ic = aic_irqc; u32 die, i, off = 0; - if (!pm_suspend_via_firmware()) + if (!pm_suspend_via_firmware() && !aic_sleep.hibernation) return 0; aic_sleep.config = aic_ic_read(ic, AIC2_CONFIG); @@ -1363,8 +1369,12 @@ static void aic_syscore_resume(void *data) return; aic_sleep.saved = false; - /* Otherwise the suspend was refused, and the controller stayed powered. */ - if (pm_resume_via_firmware()) { + /* + * After a firmware-driven suspend or a cold hibernation restore, put back + * the global controller registers and the boot CPU's FIQ mask state. + * Otherwise the suspend was refused and the controller stayed powered. + */ + if (pm_resume_via_firmware() || pm_hibernate_restored_cold()) { aic_ic_write(ic, AIC2_TIMEOUT, aic_sleep.timeout); aic_ic_write(ic, AIC2_CLUSTER_PRIO, aic_sleep.cluster_prio); aic_ic_write(ic, AIC2_CONFIG, aic_sleep.config); @@ -1394,6 +1404,19 @@ static void aic_syscore_resume(void *data) } } +static int aic_pm_notify(struct notifier_block *nb, unsigned long action, void *data) +{ + if (action == PM_HIBERNATION_PREPARE) + WRITE_ONCE(aic_sleep.hibernation, true); + else if (action == PM_POST_HIBERNATION) + WRITE_ONCE(aic_sleep.hibernation, false); + return NOTIFY_DONE; +} + +static struct notifier_block aic_pm_nb = { + .notifier_call = aic_pm_notify, +}; + static const struct syscore_ops aic_syscore_ops = { .suspend = aic_syscore_suspend, .resume = aic_syscore_resume, @@ -1414,6 +1437,7 @@ static void __init aic_sleep_init(struct aic_irq_chip *irqc) return; register_syscore(&aic_syscore); + register_pm_notifier(&aic_pm_nb); } #else static void __init aic_sleep_init(struct aic_irq_chip *irqc) diff --git a/drivers/media/platform/apple/isp/Kconfig b/drivers/media/platform/apple/isp/Kconfig index 48f9b401861b8..2cef6c54a0732 100644 --- a/drivers/media/platform/apple/isp/Kconfig +++ b/drivers/media/platform/apple/isp/Kconfig @@ -6,6 +6,7 @@ config VIDEO_APPLE_ISP select VIDEOBUF2_V4L2 select VIDEOBUF2_DMA_SG select APPLE_PMP_REPORT + select CRC32 if HIBERNATION depends on ARCH_APPLE || COMPILE_TEST depends on OF_ADDRESS depends on PM diff --git a/drivers/media/platform/apple/isp/isp-drv.c b/drivers/media/platform/apple/isp/isp-drv.c index 83ea8a00d121a..5215081662ebd 100644 --- a/drivers/media/platform/apple/isp/isp-drv.c +++ b/drivers/media/platform/apple/isp/isp-drv.c @@ -5,6 +5,7 @@ * Copyright (C) 2023 The Asahi Linux Contributors */ +#include #include #include #include @@ -1700,29 +1701,55 @@ static __maybe_unused int apple_isp_runtime_resume(struct device *dev) return 0; } +#ifdef CONFIG_HIBERNATION +/* The CRC32 of the firmware text segment, the "text" memory-region. */ +static int apple_isp_fw_text_crc(struct apple_isp *isp, u32 *crc) +{ + struct resource res; + void *mem; + int err; + + err = of_reserved_mem_region_to_resource_byname(isp->dev->of_node, "text", &res); + if (err) + return err; + mem = memremap(res.start, resource_size(&res), MEMREMAP_WB); + if (!mem) + return -ENOMEM; + *crc = crc32_le(~0, mem, resource_size(&res)); + memunmap(mem); + return 0; +} +#endif + /* - * Stop resident firmware. For a system sleep it starts again on resume where - * it can; otherwise, or for hibernation, the camera is gone until the next - * boot. + * Stop resident firmware. Firmware that starts again (hw->fw_restart) does so + * on resume, after a hibernation too if the boot that resumes the image has + * loaded the same text (apple_isp_restore()); its data segment and heap come + * from the copies kept at probe. Other resident firmware is gone until the + * next boot. */ static void apple_isp_stop_resident(struct apple_isp *isp, bool sleep) { - bool restart = sleep && isp->hw->fw_restart; + bool restart = isp->hw->fw_restart; if (!isp->hw->resident_fw) return; +#ifdef CONFIG_HIBERNATION + if (restart && !sleep) + isp->fw_text_crc_valid = !apple_isp_fw_text_crc(isp, &isp->fw_text_crc); +#endif mutex_lock(&isp->video_lock); if (isp->fw_state == ISP_FW_RUNNING) { if (restart) - dev_dbg(isp->dev, "stopping the firmware for system sleep\n"); + dev_dbg(isp->dev, "stopping the firmware for %s\n", + sleep ? "system sleep" : "hibernation"); else dev_warn(isp->dev, "stopping the firmware for %s, the camera is unavailable until the next boot\n", sleep ? "system sleep" : "hibernation"); isp->fw_sleep_stopped = restart; } apple_isp_firmware_halt(isp); - /* Hibernation resumes in another boot, where that memory isn't ours. */ if (!restart) isp->fw_state = ISP_FW_DEAD; mutex_unlock(&isp->video_lock); @@ -1777,8 +1804,8 @@ static __maybe_unused int apple_isp_freeze(struct device *dev) /* * Hibernation hands the system from one kernel to another, and * firmware left running would go on using the memory of the kernel - * that started it. Stop it cleanly instead; if it ran, the camera is - * then unavailable until the next system boot. + * that started it. Stop it cleanly instead; see apple_isp_restore() + * for whether it starts again. */ apple_isp_stop_resident(isp, false); @@ -1804,13 +1831,39 @@ static __maybe_unused int apple_isp_resume(struct device *dev) return 0; } +/* + * The image was resumed by another boot. Firmware that starts again finds its + * text where this kernel has it, as long as that boot's loader put the same + * text there: otherwise it stays down until the next boot. + */ +static __maybe_unused int apple_isp_restore(struct device *dev) +{ + struct apple_isp *isp = dev_get_drvdata(dev); + bool kept = false; +#ifdef CONFIG_HIBERNATION + u32 crc; + + kept = isp->fw_text_crc_valid && !apple_isp_fw_text_crc(isp, &crc) && + crc == isp->fw_text_crc; +#endif + if (isp->hw->fw_restart && !kept) { + mutex_lock(&isp->video_lock); + if (isp->fw_state != ISP_FW_DEAD) + dev_warn(dev, "firmware text not the same after the resume from disk, the camera is unavailable until the next boot\n"); + isp->fw_sleep_stopped = false; + isp->fw_state = ISP_FW_DEAD; + mutex_unlock(&isp->video_lock); + } + return apple_isp_resume(dev); +} + static const struct dev_pm_ops apple_isp_pm_ops = { .suspend = pm_sleep_ptr(apple_isp_suspend), .resume = pm_sleep_ptr(apple_isp_resume), .freeze = pm_sleep_ptr(apple_isp_freeze), .thaw = pm_sleep_ptr(apple_isp_resume), .poweroff = pm_sleep_ptr(apple_isp_freeze), - .restore = pm_sleep_ptr(apple_isp_resume), + .restore = pm_sleep_ptr(apple_isp_restore), RUNTIME_PM_OPS(apple_isp_runtime_suspend, apple_isp_runtime_resume, NULL) }; diff --git a/drivers/media/platform/apple/isp/isp-drv.h b/drivers/media/platform/apple/isp/isp-drv.h index 4ddc028373772..af77e48d7c743 100644 --- a/drivers/media/platform/apple/isp/isp-drv.h +++ b/drivers/media/platform/apple/isp/isp-drv.h @@ -494,6 +494,13 @@ struct apple_isp { void *fw_heap; void *fw_heap_copy; size_t fw_heap_size; + /* + * With hw->fw_restart, across a hibernation: the CRC32 of the firmware + * text segment at the freeze. The boot that resumes the image must have + * loaded the same text again for the firmware to start (apple_isp_restore()). + */ + u32 fw_text_crc; + bool fw_text_crc_valid; /* hw, as this device runs it (see apple_isp_select_hw()) */ struct apple_isp_hw hw_local; struct isp_surf *log_surf; diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index caf8561eabb84..388785d18a5af 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -742,6 +742,48 @@ static void apple_smc_sleep_pmvc_report(struct apple_smc *smc) static atomic64_t apple_smc_bind_gen; +/* The SMC endpoint started and initialised after the RTKit wake: probe, hibernation restore. */ +static int apple_smc_start(struct apple_smc *smc) +{ + int ret; + + ret = apple_rtkit_start_ep(smc->rtk, SMC_ENDPOINT); + if (ret) + return dev_err_probe(smc->dev, ret, "Failed to start SMC endpoint"); + + reinit_completion(&smc->init_done); + ret = apple_rtkit_send_message(smc->rtk, SMC_ENDPOINT, + FIELD_PREP(SMC_MSG, SMC_MSG_INITIALIZE), NULL, false); + if (ret) + return dev_err_probe(smc->dev, ret, "Failed to send init message"); + + if (wait_for_completion_timeout(&smc->init_done, msecs_to_jiffies(SMC_TIMEOUT_MS)) == 0) { + dev_err(smc->dev, "Timed out initializing SMC"); + return -ETIMEDOUT; + } + + if (smc->boot_stage != APPLE_SMC_INITIALIZED) { + dev_err(smc->dev, "SMC failed to boot successfully, boot stage=%d\n", + smc->boot_stage); + return -EIO; + } + return 0; +} + +static int apple_smc_read_key_count(struct apple_smc *smc) +{ + __be32 count; + int ret; + + ret = apple_smc_read(smc, SMC_KEY(#KEY), &count, sizeof(count)); + if (ret >= 0 && ret != sizeof(count)) + ret = -EIO; + if (ret < 0) + return dev_err_probe(smc->dev, ret, "Failed to get key count"); + smc->key_count = be32_to_cpu(count); + return 0; +} + static bool apple_smc_saved_late_notice(const struct device_node *np) { const char *compat; @@ -767,7 +809,6 @@ static int apple_smc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct apple_smc *smc; - __be32 count = 0; bool t6050; int ret; @@ -815,35 +856,15 @@ static int apple_smc_probe(struct platform_device *pdev) if (ret) return ret; - ret = apple_rtkit_start_ep(smc->rtk, SMC_ENDPOINT); + ret = apple_smc_start(smc); if (ret) - return dev_err_probe(dev, ret, "Failed to start SMC endpoint"); - - ret = apple_rtkit_send_message(smc->rtk, SMC_ENDPOINT, - FIELD_PREP(SMC_MSG, SMC_MSG_INITIALIZE), NULL, false); - if (ret) - return dev_err_probe(dev, ret, "Failed to send init message"); - - if (wait_for_completion_timeout(&smc->init_done, msecs_to_jiffies(SMC_TIMEOUT_MS)) == 0) { - dev_err(dev, "Timed out initializing SMC"); - return -ETIMEDOUT; - } - - if (smc->boot_stage != APPLE_SMC_INITIALIZED) { - dev_err(dev, "SMC failed to boot successfully, boot stage=%d\n", smc->boot_stage); - return -EIO; - } + return ret; dev_set_drvdata(&pdev->dev, smc); - ret = apple_smc_read(smc, SMC_KEY(#KEY), &count, sizeof(count)); - if (ret >= 0 && ret != sizeof(count)) { - count = 0; - ret = -EIO; - } - if (ret < 0) - return dev_err_probe(smc->dev, ret, "Failed to get key count"); - smc->key_count = be32_to_cpu(count); + ret = apple_smc_read_key_count(smc); + if (ret) + return ret; if (smc->sleep_pmvc_set) apple_smc_sleep_pmvc_report(smc); @@ -2194,10 +2215,95 @@ static int apple_smc_resume_noirq(struct device *dev) return 0; } +#ifdef CONFIG_HIBERNATION +/* + * Hibernation. The image is written with the SMC left running: the driver keeps no state that + * has to survive in it, and thermal and power management go on while it is written. The kernel + * that loads an image binds this driver like any boot and holds a live session; the firmware + * would never answer the restored kernel's new start (IOP power INIT) with a HELLO from there. + * So that kernel's .freeze, right before the jump, quiesces it, the state the teardown leaves + * it in and from which a wake starts a new session, and .restore always starts one: the same + * state whether the loading kernel is the one that wrote the image (test_resume) or one started + * by a boot. + */ +static bool apple_smc_handed_over; + +static int apple_smc_freeze(struct device *dev) +{ + struct apple_smc *smc = dev_get_drvdata(dev); + int ret; + + if (!pm_hibernate_is_loading() || !smc || !apple_rtkit_is_running(smc->rtk)) + return 0; + + apple_smc_write_flag(smc, SMC_KEY(NTAP), false); + ret = apple_rtkit_quiesce(smc->rtk); + if (ret) { + /* + * Failing here would abandon the image, whose signature is already gone, and leave + * this kernel without a session: enter the image anyway, its restore tries a new + * session. + */ + dev_err(dev, "could not quiesce the SMC for the image: %d\n", ret); + return 0; + } + apple_smc_handed_over = true; + dev_dbg(dev, "SMC quiesced for the restored kernel\n"); + return 0; +} + +static int apple_smc_restore(struct device *dev) +{ + struct apple_smc *smc = dev_get_drvdata(dev); + int ret; + + /* + * The RTKit bookkeeping restored from the image still marks the session running, in which + * state a wake is refused: back to the state probe starts from first. + */ + ret = apple_rtkit_reinit(smc->rtk); + if (ret) + return dev_err_probe(dev, ret, "Failed to reinit RTKit on restore"); + + smc->boot_stage = APPLE_SMC_BOOTING; + ret = apple_rtkit_wake(smc->rtk); + if (ret) + return dev_err_probe(dev, ret, "Failed to wake up SMC on restore"); + + ret = apple_smc_start(smc); + if (ret) + return ret; + + /* A new firmware instance: nothing says its key table is the same. */ + ret = apple_smc_read_key_count(smc); + if (ret) + return ret; + + /* The notifier chain and the sub-devices on it are in the image; only the flag is not. */ + apple_smc_write_flag(smc, SMC_KEY(NTAP), true); + return 0; +} + +/* The hand-over above, but the image could not be entered: a new session the same way. */ +static int apple_smc_thaw(struct device *dev) +{ + if (!apple_smc_handed_over) + return 0; + apple_smc_handed_over = false; + return apple_smc_restore(dev); +} +#endif + static const struct dev_pm_ops apple_smc_pm_ops = { .prepare = pm_sleep_ptr(apple_smc_prepare), .suspend = pm_sleep_ptr(apple_smc_suspend), .complete = pm_sleep_ptr(apple_smc_complete), +#ifdef CONFIG_HIBERNATION + .freeze = apple_smc_freeze, + .thaw = apple_smc_thaw, + .poweroff = apple_smc_freeze, + .restore = apple_smc_restore, +#endif NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_smc_suspend_noirq, apple_smc_resume_noirq) }; diff --git a/drivers/net/usb/r8152.c b/drivers/net/usb/r8152.c index f61686433031c..550b65a066293 100644 --- a/drivers/net/usb/r8152.c +++ b/drivers/net/usb/r8152.c @@ -2355,7 +2355,7 @@ static void intr_callback(struct urb *urb) resubmit: res = usb_submit_urb(urb, GFP_ATOMIC); - if (res == -ENODEV) { + if (res == -ENODEV || res == -ESHUTDOWN) { rtl_set_unplug(tp); netif_device_detach(tp->netdev); } else if (res) { @@ -3183,7 +3183,7 @@ static void tx_bottom(struct r8152 *tp) if (!res) continue; - if (res == -ENODEV) { + if (res == -ENODEV || res == -ESHUTDOWN) { rtl_set_unplug(tp); netif_device_detach(netdev); } else { @@ -3257,7 +3257,13 @@ int r8152_submit_rx(struct r8152 *tp, struct rx_agg *agg, gfp_t mem_flags) (usb_complete_t)read_bulk_callback, agg); ret = usb_submit_urb(agg->urb, mem_flags); - if (ret == -ENODEV) { + if (ret == -ENODEV || ret == -ESHUTDOWN) { + /* + * The host controller is gone (its driver is being removed or + * stopped under a bound interface): no resubmission can succeed, + * and rescheduling NAPI for each failure spins until the + * disconnect finally arrives. + */ rtl_set_unplug(tp); netif_device_detach(tp->netdev); } else if (ret) { diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 08f76a450caaf..c879d9219353f 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -3798,6 +3798,41 @@ static int brcmf_pcie_pm_leave_D3(struct device *dev) } +/* + * The firmware session at restore does not describe the rings in the image: + * it was started by the kernel that loaded the image, or continued across + * the image write in test_resume. The loading kernel quiesced it in D3. + * Tear down the saved host state without resetting a chip in that state, + * then probe it again, as in the resume path after a power loss. + */ +static int brcmf_pcie_pm_restore(struct device *dev) +{ + struct brcmf_bus *bus = dev_get_drvdata(dev); + struct brcmf_pciedev_info *devinfo = bus->bus_priv.pcie->devinfo; + struct pci_dev *pdev = devinfo->pdev; + int err; + + err = apple_radio_sleep_endpoint_resume(dev); + if (err) + return err; + + if (apple_radio_sleep_owned(dev)) { + /* Lost firmware/rings violate retention; reset/reprobe is not recovery. */ + apple_radio_sleep_endpoint_resumed(dev, -EUCLEAN); + return -EUCLEAN; + } + + devinfo->state = BRCMFMAC_PCIE_STATE_DOWN; + brcmf_chip_detach(devinfo->ci); + devinfo->ci = NULL; + brcmf_pcie_remove(pdev); + err = brcmf_pcie_probe(pdev, NULL); + if (err) + __brcmf_err(NULL, __func__, "probe after restore failed, err=%d\n", err); + + return err; +} + /* * On BCM4378 (Apple M1 / T8103), allowing the PCIe link into ASPM L1 across * s2idle causes a hard SoC reset while the radio transitions through MPC with @@ -3851,7 +3886,7 @@ static const struct dev_pm_ops brcmf_pciedrvr_pm = { .resume = brcmf_pcie_pm_leave_D3, .freeze = brcmf_pcie_pm_enter_D3, .thaw = brcmf_pcie_pm_leave_D3, - .restore = brcmf_pcie_pm_leave_D3, + .restore = brcmf_pcie_pm_restore, }; diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 2b713b6e971fc..aab9317aac6e3 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -51,6 +51,7 @@ #include "nvme.h" #include "apple-m5-policy.h" #include +#include #define APPLE_ANS_BOOT_TIMEOUT USEC_PER_SEC #define APPLE_ANS_SLEEP_SHN_TIMEOUT USEC_PER_SEC @@ -262,6 +263,8 @@ struct apple_nvme_hw { bool secure_reg_layout; /* Also send the NVMe shutdown notification (CC.SHN) on removal. */ bool shutdown_notify; + /* A reset with the controller enabled wedges ANS: disable it at a panic. */ + bool panic_quiesce; u32 max_queue_depth; unsigned long quirks; }; @@ -315,6 +318,8 @@ struct apple_nvme { */ bool shmem_defer; struct list_head kept_shmem; + /* Disables the controller at a panic, as the final shutdown does (panic_quiesce). */ + struct notifier_block panic_nb; unsigned long recovery_flags; void __iomem *mmio_coproc; @@ -3166,6 +3171,9 @@ static void apple_nvme_free_rtkit(void *data) if (apple_nvme_m5_retained(anv)) return; guard(mutex)(&anv->disable_lock); + /* A failed hibernation restore leaves no session behind. */ + if (!anv->rtk) + return; if (anv->hw->needs_ioq_registers) apple_rtkit_free_retaining_buffers(anv->rtk); else @@ -3502,6 +3510,39 @@ static void apple_nvme_keep_link_powered(struct apple_nvme *anv); #include "apple-m5-sleep.h" +/* + * A reset with the controller still enabled leaves ANS in a state the next boot stage + * can't start again (no HELLO, warm or cold, until a power cycle). At a panic, do what + * the final shutdown does before the platform reset: shutdown notification, then + * controller disable, ANS left running. Polled: the other CPUs are stopped, interrupts + * are off and nothing may sleep. + */ +static int apple_nvme_panic_notify(struct notifier_block *nb, unsigned long action, void *data) +{ + struct apple_nvme *anv = container_of(nb, struct apple_nvme, panic_nb); + void __iomem *regs = anv->mmio_nvme; + u32 cc = readl(regs + NVME_REG_CC); + int i; + + if (!(cc & NVME_CC_ENABLE) || + !(readl(anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL) & + APPLE_ANS_COPROC_CPU_CONTROL_RUN)) + return NOTIFY_DONE; + writel((cc & ~NVME_CC_SHN_MASK) | NVME_CC_SHN_NORMAL, regs + NVME_REG_CC); + for (i = 0; i < 2000; i++) { + if ((readl(regs + NVME_REG_CSTS) & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT) + break; + udelay(500); + } + writel(readl(regs + NVME_REG_CC) & ~NVME_CC_ENABLE, regs + NVME_REG_CC); + for (i = 0; i < 2000 && (readl(regs + NVME_REG_CSTS) & NVME_CSTS_RDY); i++) + udelay(500); + dev_emerg(anv->dev, "controller disabled at panic (CSTS %#x)\n", + readl(regs + NVME_REG_CSTS)); + + return NOTIFY_DONE; +} + static int apple_nvme_probe(struct platform_device *pdev) { struct apple_nvme *anv; @@ -3548,6 +3589,12 @@ static int apple_nvme_probe(struct platform_device *pdev) apple_nvme_set_reset_ready(anv, true); nvme_reset_ctrl(&anv->ctrl); async_schedule(apple_nvme_async_probe, anv); + if (anv->hw->panic_quiesce) { + anv->panic_nb.notifier_call = apple_nvme_panic_notify; + /* After the other notifiers: the controller may hold their writes. */ + anv->panic_nb.priority = INT_MIN; + atomic_notifier_chain_register(&panic_notifier_list, &anv->panic_nb); + } return 0; @@ -3563,6 +3610,8 @@ static void apple_nvme_remove(struct platform_device *pdev) { struct apple_nvme *anv = platform_get_drvdata(pdev); + if (anv->panic_nb.notifier_call) + atomic_notifier_chain_unregister(&panic_notifier_list, &anv->panic_nb); if (anv->m5.registered) apple_sleep_coproc_unregister(anv->dev); if (apple_nvme_m5_fenced(anv)) { @@ -4075,8 +4124,125 @@ static int apple_nvme_suspend(struct device *dev) return ret; } +/* + * Hibernation restore on post-M4 through a boot. The machine cold-booted since .freeze: + * the boot firmware restarted ANS, the boot stages kept it running, and the + * resume kernel adopted that session to read the image (its own queues, and + * its .freeze cleared CC.EN before jumping here). anv->rtk therefore + * describes a firmware instance that no longer exists, and the live session + * on the mailbox has never been adopted by this kernel. Unlike + * apple_nvme_can_adopt_rtkit(), accept a disabled controller: it was just + * disabled below, and RUN + BOOT_STATUS_OK + !CFS are what survive. + */ +static bool apple_nvme_can_adopt_restored_rtkit(struct apple_nvme *anv) +{ + u32 csts; + + if (!(readl(anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL) & + APPLE_ANS_COPROC_CPU_CONTROL_RUN) || + readl(anv->mmio_nvme + APPLE_ANS_BOOT_STATUS) != APPLE_ANS_BOOT_STATUS_OK) + return false; + csts = readl(anv->mmio_nvme + NVME_REG_CSTS); + if (csts & NVME_CSTS_CFS) + return false; + return !(readl(anv->mmio_nvme + NVME_REG_CC) & NVME_CC_ENABLE) && + !(csts & NVME_CSTS_RDY); +} + +static int apple_nvme_restore_post_m4(struct apple_nvme *anv) +{ + struct apple_rtkit *rtk; + int ret; + + guard(mutex)(&anv->disable_lock); + if (READ_ONCE(anv->quarantined)) + return -EIO; + dev_dbg(anv->dev, + "hibernation restore: CPU_CONTROL=%#x BOOT_STATUS=%#x CC=%#x CSTS=%#x\n", + readl(anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL), + readl(anv->mmio_nvme + APPLE_ANS_BOOT_STATUS), + readl(anv->mmio_nvme + NVME_REG_CC), + readl(anv->mmio_nvme + NVME_REG_CSTS)); + + /* + * Stop the controller first: until CC.EN is clear the firmware may + * still fetch from the resume kernel's queues, whose memory is now + * this kernel's. This is the owned-session reset path. + */ + ret = apple_nvme_disable_locked(anv, false); + if (ret) + return ret; + + /* + * Our firmware instance ended with the power-off. No shutdown + * handshake: the new instance would receive it. Shared buffers are + * retained as in apple_nvme_free_rtkit(). + */ + apple_nvme_set_reset_ready(anv, false); + apple_rtkit_free_retaining_buffers(anv->rtk); + anv->rtk = NULL; + anv->owns_rtkit = false; + + if (!apple_nvme_can_adopt_restored_rtkit(anv)) { + dev_err(anv->dev, "hibernation restore: no adoptable ANS session\n"); + apple_nvme_quarantine(anv, -EIO); + return -EIO; + } + + /* Publish admission before the initializer enables mailbox RX. */ + anv->inherited_rtkit = true; + rtk = apple_rtkit_init_adopted(anv->dev, anv, NULL, 0, + &apple_nvme_rtkit_ops); + if (IS_ERR(rtk)) { + ret = PTR_ERR(rtk); + dev_err(anv->dev, "hibernation restore: RTKit init failed: %d\n", ret); + apple_nvme_quarantine(anv, ret); + return ret; + } + anv->rtk = rtk; + ret = apple_rtkit_adopt_running(rtk); + if (ret) { + dev_err(anv->dev, "hibernation restore: RTKit adoption failed: %d\n", ret); + apple_nvme_quarantine(anv, ret); + return ret; + } + /* Owned: reset_work takes the live-session path, as after s2idle. */ + anv->owns_rtkit = true; + apple_nvme_set_reset_ready(anv, true); + dev_info(anv->dev, + "hibernation restore: adopted the boot loader's ANS session\n"); + return 0; +} + +static int apple_nvme_restore(struct device *dev) +{ + struct apple_nvme *anv = dev_get_drvdata(dev); + int ret; + + /* + * From the loading kernel (test_resume) the controller is as its + * .freeze left it, disabled with the session kept: a resume. + */ + if (anv->hw->needs_ioq_registers && pm_hibernate_restored_cold()) { + ret = apple_nvme_restore_post_m4(anv); + if (ret) + return ret; + } + return apple_nvme_resume(dev); +} + +/* + * freeze and poweroff disable the controller and keep the session, like + * suspend; thaw (image not written) is a resume. Only restore differs. The + * early resume restarts ANS only after a firmware-driven suspend idled it. + */ static const struct dev_pm_ops apple_nvme_pm_ops = { - SYSTEM_SLEEP_PM_OPS(apple_nvme_suspend, apple_nvme_resume) + .suspend = pm_sleep_ptr(apple_nvme_suspend), + .resume = pm_sleep_ptr(apple_nvme_resume), + .freeze = pm_sleep_ptr(apple_nvme_suspend), + .thaw = pm_sleep_ptr(apple_nvme_resume), + .poweroff = pm_sleep_ptr(apple_nvme_suspend), + .restore = pm_sleep_ptr(apple_nvme_restore), LATE_SYSTEM_SLEEP_PM_OPS(NULL, apple_nvme_resume_early) }; @@ -4158,6 +4324,7 @@ static const struct apple_nvme_hw apple_nvme_t6040_hw = { .sleep_traced = true, .sleep_flush_max_nsid = 1, .sleep_shn = NVME_CC_SHN_MASK, + .panic_quiesce = true, .quirks = NVME_QUIRK_NO_APST, }; diff --git a/drivers/pci/controller/pcie-apple-msi.c b/drivers/pci/controller/pcie-apple-msi.c index 02809d9e26c7a..f4f6c94963864 100644 --- a/drivers/pci/controller/pcie-apple-msi.c +++ b/drivers/pci/controller/pcie-apple-msi.c @@ -140,8 +140,25 @@ static int apple_msi_resume_noirq(struct device *dev) return 0; } +#ifdef CONFIG_HIBERNATION +/* + * After a cold hibernation restore the bootloader has re-trained the port + * without programming the MSI doorbell or map, so reprogram them before + * PCI devices resume and before any port cycle snapshots the tables. + */ +static int apple_msi_restore_noirq(struct device *dev) +{ + if (pm_hibernate_restored_cold()) + apple_msi_hw_init(dev_get_drvdata(dev)); + return 0; +} +#endif + static const struct dev_pm_ops apple_msi_pm_ops = { .resume_noirq = apple_msi_resume_noirq, +#ifdef CONFIG_HIBERNATION + .restore_noirq = apple_msi_restore_noirq, +#endif }; static int apple_msi_probe(struct platform_device *pdev) diff --git a/drivers/phy/apple/t6040-usb2.c b/drivers/phy/apple/t6040-usb2.c index 370dfc42ced0a..aee6cf43fe325 100644 --- a/drivers/phy/apple/t6040-usb2.c +++ b/drivers/phy/apple/t6040-usb2.c @@ -4048,7 +4048,7 @@ static int t6040_phy_count(struct phy *phy) } /* - * Resume from disk is a cold boot: the PHY, its coprocessor and the + * Resume from disk through a boot: the PHY, its coprocessor and the * pipehandler come back reset, while this driver's state comes from the * image. Before the image its consumers gave it back: the sleep hook * unbinds dwc3 (USB2/USB3 phys powered off, controller reset asserted), @@ -4074,6 +4074,15 @@ static int t6040_usb2_restore_early(struct device *dev) if (!tphy) return 0; guard(mutex)(&tphy->lock); + /* + * The kernel that wrote the image loaded it again (test_resume): the PHY + * kept its power and its state, and the hardware matches this driver's, + * as after a sleep that the firmware did not take the SoC through. + */ + if (!pm_hibernate_restored_cold()) { + WRITE_ONCE(tphy->sleep_back, tphy->sleep_down); + return 0; + } if (tphy->powered || tphy->usb3_on || tphy->dwc3_running || t6040_phy_count(tphy->dp)) dev_warn(dev, @@ -4120,7 +4129,8 @@ static int t6040_usb2_restore(struct device *dev) if (!tphy || IS_ERR_OR_NULL(tphy->rtk)) return 0; guard(mutex)(&tphy->lock); - if (!apple_rtkit_is_running(tphy->rtk)) + /* Without a boot behind the restore the session is still the one this kernel runs. */ + if (!pm_hibernate_restored_cold() || !apple_rtkit_is_running(tphy->rtk)) return 0; ret = apple_rtkit_reinit(tphy->rtk); dev_info(dev, "restore: USB3 coprocessor RTKit reset: %d\n", ret); diff --git a/drivers/pinctrl/pinctrl-apple-gpio.c b/drivers/pinctrl/pinctrl-apple-gpio.c index 6494d024e9d54..09994c730b6e5 100644 --- a/drivers/pinctrl/pinctrl-apple-gpio.c +++ b/drivers/pinctrl/pinctrl-apple-gpio.c @@ -696,15 +696,10 @@ MODULE_DEVICE_TABLE(of, apple_gpio_pinctrl_of_match); * a consumer sets a pin up again. Slots that fault aren't readable in the regmap, * so they stay out of this. */ -static int apple_gpio_pinctrl_suspend_noirq(struct device *dev) +static void apple_gpio_pinctrl_save(struct apple_gpio_pinctrl *pctl) { - struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); unsigned int i; - if (!pctl->saved || pm_suspend_target_state != PM_SUSPEND_MEM || - !pm_suspend_via_firmware()) - return 0; - /* * Only the pins this driver configured. The others belong to the firmware or another * processor, and writing one back after the wake raises an SError. @@ -713,18 +708,12 @@ static int apple_gpio_pinctrl_suspend_noirq(struct device *dev) for_each_set_bit(i, pctl->touched, pctl->pinctrl_desc.npins) if (!regmap_read(pctl->map, REG_GPIO(i), &pctl->saved[i])) set_bit(i, pctl->saved_valid); - - return 0; } -static int apple_gpio_pinctrl_resume_noirq(struct device *dev) +static void apple_gpio_pinctrl_put_back(struct device *dev, struct apple_gpio_pinctrl *pctl) { - struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); unsigned int i, val, restored = 0; - if (!pctl->saved || !pm_resume_via_firmware()) - return 0; - for_each_set_bit(i, pctl->saved_valid, pctl->pinctrl_desc.npins) { if (!regmap_read(pctl->map, REG_GPIO(i), &val) && val == pctl->saved[i]) continue; @@ -734,13 +723,77 @@ static int apple_gpio_pinctrl_resume_noirq(struct device *dev) dev_dbg(dev, "resume: %u of %u configured pins put back\n", restored, bitmap_weight(pctl->saved_valid, pctl->pinctrl_desc.npins)); bitmap_zero(pctl->saved_valid, pctl->pinctrl_desc.npins); +} +static int apple_gpio_pinctrl_suspend_noirq(struct device *dev) +{ + struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); + + if (!pctl->saved || pm_suspend_target_state != PM_SUSPEND_MEM || + !pm_suspend_via_firmware()) + return 0; + + apple_gpio_pinctrl_save(pctl); return 0; } +static int apple_gpio_pinctrl_resume_noirq(struct device *dev) +{ + struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); + + if (!pctl->saved || !pm_resume_via_firmware()) + return 0; + + apple_gpio_pinctrl_put_back(dev, pctl); + return 0; +} + +/* + * A hibernation image is restored after a reboot, with the pins as the boot + * firmware and the kernel that loaded the image left them: the image's own + * setup goes back. Without a cache it is saved when the image is made, as for + * a firmware-driven suspend; a thaw finds the block as it was and leaves it. + */ +static int apple_gpio_pinctrl_freeze_noirq(struct device *dev) +{ + struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); + + if (pctl->saved) + apple_gpio_pinctrl_save(pctl); + return 0; +} + +static int apple_gpio_pinctrl_thaw_noirq(struct device *dev) +{ + struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); + + if (pctl->saved) + bitmap_zero(pctl->saved_valid, pctl->pinctrl_desc.npins); + return 0; +} + +static int apple_gpio_pinctrl_restore_noirq(struct device *dev) +{ + struct apple_gpio_pinctrl *pctl = dev_get_drvdata(dev); + + if (pctl->saved) { + apple_gpio_pinctrl_put_back(dev, pctl); + return 0; + } + /* + * The cache holds the image's setup and the pins differ from it: write + * back what this kernel changed from the block as it found it at probe. + */ + regcache_mark_dirty(pctl->map); + return regcache_sync(pctl->map); +} + static const struct dev_pm_ops apple_gpio_pinctrl_pm_ops = { - NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_gpio_pinctrl_suspend_noirq, - apple_gpio_pinctrl_resume_noirq) + .suspend_noirq = pm_sleep_ptr(apple_gpio_pinctrl_suspend_noirq), + .resume_noirq = pm_sleep_ptr(apple_gpio_pinctrl_resume_noirq), + .freeze_noirq = pm_sleep_ptr(apple_gpio_pinctrl_freeze_noirq), + .thaw_noirq = pm_sleep_ptr(apple_gpio_pinctrl_thaw_noirq), + .restore_noirq = pm_sleep_ptr(apple_gpio_pinctrl_restore_noirq), }; static struct platform_driver apple_gpio_pinctrl_driver = { diff --git a/drivers/pmdomain/apple/pmc.c b/drivers/pmdomain/apple/pmc.c index af41cc7f3b75c..ea3b176b1369f 100644 --- a/drivers/pmdomain/apple/pmc.c +++ b/drivers/pmdomain/apple/pmc.c @@ -2260,18 +2260,14 @@ static int apple_pmc_dvmr_resume_locked(struct apple_pmc *pmc) pmc->dvmr_active || pmc->dvmr_dirty); } -/* - * A system sleep that reached the hardware may have taken the enables and floors - * with it. Put back what the driver's books say: these are no-ops if they stayed. - */ -static int apple_pmc_resume_early(struct device *dev) +static int apple_pmc_restore_state(struct device *dev) { struct apple_pmc *pmc = dev_get_drvdata(dev); unsigned long flags; unsigned int rail; int ret = 0, err; - if (!pm_resume_via_firmware() || !pmc) + if (!pmc) return 0; raw_spin_lock_irqsave(&pmc->lock, flags); @@ -2302,8 +2298,38 @@ static int apple_pmc_resume_early(struct device *dev) return 0; } +/* + * A system sleep that reached the hardware may have taken the enables and floors + * with it. Put back what the driver's books say: these are no-ops if they stayed. + */ +static int apple_pmc_resume_early(struct device *dev) +{ + if (!pm_resume_via_firmware()) + return 0; + + return apple_pmc_restore_state(dev); +} + +#ifdef CONFIG_HIBERNATION +/* + * A kernel restored from a hibernation image runs after a boot that started + * from a reset PMC with every agent disabled on every rail. Always write the + * image's voter enables, floors, DCS vote, and interfaces back. + */ +static int apple_pmc_restore_early(struct device *dev) +{ + return apple_pmc_restore_state(dev); +} +#endif + static const struct dev_pm_ops apple_pmc_pm_ops = { - LATE_SYSTEM_SLEEP_PM_OPS(NULL, apple_pmc_resume_early) + .resume_early = pm_sleep_ptr(apple_pmc_resume_early), + .thaw_early = pm_sleep_ptr(apple_pmc_resume_early), +#ifdef CONFIG_HIBERNATION + .restore_early = apple_pmc_restore_early, +#else + .restore_early = pm_sleep_ptr(apple_pmc_resume_early), +#endif }; static const struct of_device_id apple_pmc_of_match[] = { diff --git a/drivers/pmdomain/apple/pmgr-pwrstate-test.c b/drivers/pmdomain/apple/pmgr-pwrstate-test.c index 8f053270be314..adc3747a8e953 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate-test.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate-test.c @@ -1699,6 +1699,47 @@ static void pmgr_ps_power_off_auto_two_step_test(struct kunit *test) KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->writes[0]), APPLE_PMGR_PS_PWRGATE); } +/* + * Hibernation restore: a domain the image has on but the loading boot left gated is + * brought up; one the image has off is not touched. A plain resume_noirq outside a + * firmware sleep leaves both alone. + */ +static void pmgr_ps_restore_noirq_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + + ps = pmgr_ps_test_named_domain(test, "apple-pmgr-ps-restore-on", + APPLE_PMGR_PS_PWRGATE, false, &r); + spin_lock_init(&ps->genpd.slock); + dev_set_drvdata(ps->dev, ps); + ps->genpd.status = GENPD_STATE_ON; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_resume_noirq(ps->dev), 0); + KUNIT_EXPECT_EQ(test, r->nwrites, 0U); + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_restore_noirq(ps->dev), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_ACTUAL, r->val), APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_AUTO_ENABLE); + + ps = pmgr_ps_test_named_domain(test, "apple-pmgr-ps-restore-off", + APPLE_PMGR_PS_ACTIVE, false, &r); + spin_lock_init(&ps->genpd.slock); + dev_set_drvdata(ps->dev, ps); + ps->genpd.status = GENPD_STATE_OFF; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_restore_noirq(ps->dev), 0); + KUNIT_EXPECT_EQ(test, r->nwrites, 0U); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_ACTIVE); + + ps = pmgr_ps_test_named_domain(test, "apple-pmgr-ps-restore-fw", + APPLE_PMGR_PS_PWRGATE, false, &r); + spin_lock_init(&ps->genpd.slock); + dev_set_drvdata(ps->dev, ps); + ps->genpd.status = GENPD_STATE_ON; + ps->firmware_owned = true; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_restore_noirq(ps->dev), 0); + KUNIT_EXPECT_EQ(test, r->nwrites, 0U); +} + /* * A failed power-on must never write APPLE_PMGR_AUTO_ENABLE, including when * system_sleep retains the ACTIVE target or when wait_parent fails on a @@ -1791,6 +1832,7 @@ static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_auto_enable_test), KUNIT_CASE(pmgr_ps_auto_enable_skip_test), KUNIT_CASE(pmgr_ps_auto_enable_fail_test), + KUNIT_CASE(pmgr_ps_restore_noirq_test), KUNIT_CASE(pmgr_ps_set_auto_pm_test), KUNIT_CASE(pmgr_ps_set_auto_pm_fail_test), KUNIT_CASE(pmgr_ps_set_auto_pm_latch_test), diff --git a/drivers/pmdomain/apple/pmgr-pwrstate.c b/drivers/pmdomain/apple/pmgr-pwrstate.c index e4667fb29dfc7..7b6c8dada0f43 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate.c @@ -724,16 +724,17 @@ static int apple_pmgr_ps_suspend_noirq(struct device *dev) * its own order. A domain someone else raised before the sleep, and still at that * target, stays theirs. */ -static int apple_pmgr_ps_resume_noirq(struct device *dev) +/* + * Put the hardware back to genpd's view of the domain. With @lower, a domain genpd + * has off is power-gated too; without it only one genpd has on is brought up. + */ +static void apple_pmgr_ps_resync(struct device *dev, bool lower) { struct apple_pmgr_ps *ps = dev_get_drvdata(dev); unsigned long flags; u32 reg; int ret; - if (!pm_resume_via_firmware() || ps->firmware_owned) - return 0; - /* * The wake resets each word's minimum state with the rest, and probe is the only * place that sets apple,min-state: put it back, whoever owns the domain now. With @@ -752,7 +753,7 @@ static int apple_pmgr_ps_resume_noirq(struct device *dev) if (ps->inherited_on || ps->auto_managed || ps->sleep_driver_owned || apple_sleep_domain_is_down(dev->of_node)) - return 0; + return; spin_lock_irqsave(&ps->genpd.slock, flags); ret = regmap_read(ps->regmap, ps->offset, ®); @@ -760,6 +761,9 @@ static int apple_pmgr_ps_resume_noirq(struct device *dev) if (ps->genpd.status == GENPD_STATE_OFF) { u32 target = FIELD_GET(APPLE_PMGR_PS_TARGET, reg); + if (!lower) + goto unlock; + /* * Lowering an AOP-raised audio domain here leaves the internal * microphone array's data path dark: the AOP never raises it again. @@ -777,9 +781,36 @@ static int apple_pmgr_ps_resume_noirq(struct device *dev) auto_enable); } } +unlock: spin_unlock_irqrestore(&ps->genpd.slock, flags); if (ret) dev_err(dev, "PS %s: resync after sleep failed: %d\n", ps->genpd.name, ret); +} + +static int apple_pmgr_ps_resume_noirq(struct device *dev) +{ + struct apple_pmgr_ps *ps = dev_get_drvdata(dev); + + if (!pm_resume_via_firmware() || ps->firmware_owned) + return 0; + apple_pmgr_ps_resync(dev, true); + + return 0; +} + +/* + * Hibernation restore. genpd powers a domain on only when the image has it off, but + * the boot that loaded the image may have gated one the image has on: one whose + * devices it didn't bind, at its restore quiesce. A register block in it stalls the + * bus at the first access. Domains are suppliers of their consumers, so this runs + * before any consumer's restore callbacks. Nothing is gated here. + */ +static int apple_pmgr_ps_restore_noirq(struct device *dev) +{ + struct apple_pmgr_ps *ps = dev_get_drvdata(dev); + + if (!ps->firmware_owned) + apple_pmgr_ps_resync(dev, false); return 0; } @@ -1895,7 +1926,12 @@ arch_initcall(apple_pmgr_ps_auto_init); static const struct dev_pm_ops apple_pmgr_ps_pm_ops = { LATE_SYSTEM_SLEEP_PM_OPS(apple_pmgr_ps_suspend_late, apple_pmgr_ps_resume_early) - NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_pmgr_ps_suspend_noirq, apple_pmgr_ps_resume_noirq) + .suspend_noirq = pm_sleep_ptr(apple_pmgr_ps_suspend_noirq), + .resume_noirq = pm_sleep_ptr(apple_pmgr_ps_resume_noirq), + .freeze_noirq = pm_sleep_ptr(apple_pmgr_ps_suspend_noirq), + .thaw_noirq = pm_sleep_ptr(apple_pmgr_ps_resume_noirq), + .poweroff_noirq = pm_sleep_ptr(apple_pmgr_ps_suspend_noirq), + .restore_noirq = pm_sleep_ptr(apple_pmgr_ps_restore_noirq), }; static struct platform_driver apple_pmgr_ps_driver = { diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index c362284e7b85d..5aee34817a909 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -3673,9 +3673,14 @@ static int apple_pmp_report_entry_resume_noirq(struct device *dev) return ret; } +/* + * Only system suspend (s2idle / S2R) withdraws release-for-sleep entries here: + * on cold hibernation restore the PMP is still halted during .restore_noirq and + * apple_pmp_pm_notify() replays all active report requests after PMP restarts. + */ static const struct dev_pm_ops apple_pmp_report_entry_pm_ops = { - NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_pmp_report_entry_suspend_noirq, - apple_pmp_report_entry_resume_noirq) + .suspend_noirq = pm_sleep_ptr(apple_pmp_report_entry_suspend_noirq), + .resume_noirq = pm_sleep_ptr(apple_pmp_report_entry_resume_noirq), }; static int apple_pmp_report_entry_power_on(struct generic_pm_domain *genpd) diff --git a/drivers/pmdomain/core.c b/drivers/pmdomain/core.c index 5163207a8b431..0ecd64226c62e 100644 --- a/drivers/pmdomain/core.c +++ b/drivers/pmdomain/core.c @@ -1661,7 +1661,7 @@ static int genpd_finish_resume(struct device *dev, return ret; } - return pm_generic_resume_noirq(dev); + return resume_noirq(dev); } /** diff --git a/drivers/power/reset/macsmc-reboot.c b/drivers/power/reset/macsmc-reboot.c index 3cf0bd7e5f608..72033e11b7c64 100644 --- a/drivers/power/reset/macsmc-reboot.c +++ b/drivers/power/reset/macsmc-reboot.c @@ -129,15 +129,30 @@ static int macsmc_prepare_atomic(struct sys_off_data *data) static int macsmc_power_off(struct sys_off_data *data) { struct macsmc_reboot *reboot = data->cb_data; + int ret, i; dev_info(reboot->dev, "Issuing power off (off1)\n"); - if (apple_smc_write_u32_atomic(reboot->smc, SMC_KEY(MBSE), SMC_KEY(off1)) < 0) { - dev_err(reboot->dev, "Failed to issue MBSE = off1 (power_off)\n"); - } else { + /* + * The next handler is PSCI SYSTEM_OFF. Under a monitor that has no + * power-off path it resets the machine instead, so a slow or refused + * off1 must not hand over to it after only 100 ms: retry a refused + * command and give an accepted one time to take effect. + */ + for (i = 0; i < 3; i++) { + ret = apple_smc_write_u32_atomic(reboot->smc, SMC_KEY(MBSE), SMC_KEY(off1)); + if (ret >= 0) + break; + dev_warn(reboot->dev, "MBSE = off1 refused (%d), attempt %d\n", ret, i + 1); mdelay(100); - WARN_ONCE(1, "Unable to power off system\n"); } + if (ret < 0) { + dev_err(reboot->dev, "Failed to issue MBSE = off1 (power_off)\n"); + return NOTIFY_OK; + } + for (i = 0; i < 50; i++) + mdelay(100); + WARN_ONCE(1, "Unable to power off system: off1 accepted, power still on after 5 s\n"); return NOTIFY_OK; } diff --git a/drivers/power/supply/macsmc-power.c b/drivers/power/supply/macsmc-power.c index 42264b1c57ba8..adcc1e0117b64 100644 --- a/drivers/power/supply/macsmc-power.c +++ b/drivers/power/supply/macsmc-power.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -138,6 +139,14 @@ struct macsmc_power { bool orderly_shutdown_triggered; struct delayed_work dbg_log_work; +#ifdef CONFIG_HIBERNATION + struct { + bool chls_valid; + u16 chls; + bool chwa_valid; + bool chwa; + } hib_saved; +#endif }; static int macsmc_log_power_set(const char *val, const struct kernel_param *kp); @@ -1577,7 +1586,63 @@ static void macsmc_power_complete(struct device *dev) power_supply_changed(power->ac); } +#ifdef CONFIG_HIBERNATION +static int macsmc_power_freeze(struct device *dev) +{ + struct macsmc_power *power = dev_get_drvdata(dev); + u16 chls; + bool chwa; + + guard(mutex)(&power->charge_lock); + power->hib_saved.chls_valid = false; + power->hib_saved.chwa_valid = false; + + if (power->has_chls && + apple_smc_read_u16(power->smc, SMC_KEY(CHLS), &chls) == 0) { + power->hib_saved.chls = chls; + power->hib_saved.chls_valid = true; + } else if (power->has_chwa && + apple_smc_read_flag(power->smc, SMC_KEY(CHWA), &chwa) == 0) { + power->hib_saved.chwa = chwa; + power->hib_saved.chwa_valid = true; + } + return 0; +} + +static int macsmc_power_restore(struct device *dev) +{ + struct macsmc_power *power = dev_get_drvdata(dev); + int ret; + + if (!pm_hibernate_restored_cold()) + return 0; + + guard(mutex)(&power->charge_lock); + if (power->hib_saved.chls_valid) { + ret = apple_smc_write_u16(power->smc, SMC_KEY(CHLS), + power->hib_saved.chls); + if (ret < 0) + dev_warn(dev, "hibernation restore: failed to restore CHLS (%#x): %d\n", + power->hib_saved.chls, ret); + power->hib_saved.chls_valid = false; + } else if (power->hib_saved.chwa_valid) { + ret = apple_smc_write_flag(power->smc, SMC_KEY(CHWA), + power->hib_saved.chwa); + if (ret < 0) + dev_warn(dev, "hibernation restore: failed to restore CHWA (%u): %d\n", + power->hib_saved.chwa, ret); + power->hib_saved.chwa_valid = false; + } + return 0; +} +#endif + static const struct dev_pm_ops macsmc_power_pm_ops = { +#ifdef CONFIG_HIBERNATION + .freeze = macsmc_power_freeze, + .poweroff = macsmc_power_freeze, + .restore = macsmc_power_restore, +#endif .complete = pm_sleep_ptr(macsmc_power_complete), }; diff --git a/drivers/pwm/pwm-apple.c b/drivers/pwm/pwm-apple.c index fd12a3d1bc42d..e3ebc54cccb16 100644 --- a/drivers/pwm/pwm-apple.c +++ b/drivers/pwm/pwm-apple.c @@ -172,7 +172,9 @@ static int apple_pwm_runtime_resume(struct device *dev) writel(fpwm->on_cycles, fpwm->base + APPLE_PWM_ON_CYCLES); writel(fpwm->off_cycles, fpwm->base + APPLE_PWM_OFF_CYCLES); - writel(fpwm->ctrl, fpwm->base + APPLE_PWM_CTRL); + writel(fpwm->ctrl | ((fpwm->ctrl & APPLE_PWM_CTRL_ENABLE) ? + APPLE_PWM_CTRL_UPDATE : 0), + fpwm->base + APPLE_PWM_CTRL); return 0; } @@ -190,6 +192,8 @@ static void apple_pwm_runtime_disable(void *data) } static const struct dev_pm_ops apple_pwm_pm_ops = { + LATE_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, + pm_runtime_force_resume) RUNTIME_PM_OPS(apple_pwm_runtime_suspend, apple_pwm_runtime_resume, NULL) }; diff --git a/drivers/rtc/rtc-apple-pmu.c b/drivers/rtc/rtc-apple-pmu.c index 2330086b3a09f..a298f2c2f06ac 100644 --- a/drivers/rtc/rtc-apple-pmu.c +++ b/drivers/rtc/rtc-apple-pmu.c @@ -489,9 +489,12 @@ static int apple_pmu_rtc_prepare(struct device *dev) /* * A firmware-driven suspend programs the wake sources itself, and the * alarm stays armed in the PMU, which stays powered. Only a sleep state - * without either has no way to bring the alarm back. + * without either has no way to bring the alarm back. Hibernation has no + * suspend target: the machine wakes from it by a cold boot, which needs + * nothing from the alarm. */ - if (pm_suspend_target_state != PM_SUSPEND_TO_IDLE && !pm_suspend_via_firmware()) + if (pm_suspend_target_state != PM_SUSPEND_ON && + pm_suspend_target_state != PM_SUSPEND_TO_IDLE && !pm_suspend_via_firmware()) return -EBUSY; return 0; } diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index d644e9689f3c0..613f02b2f58a9 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -515,6 +515,19 @@ config APPLE_CLPC Say 'y' or 'm' here if you have an Apple SoC. +config APPLE_AURA_HIBERNATE + def_bool y + depends on ARCH_APPLE && HIBERNATION && OF_EARLY_FLATTREE + help + Under aura, the boot loader and the firmware keep memory alive + below Linux's allocations, and on Apple M4 Pro boots the boot + firmware places it at a different address every time. With + aura's fixed layout (/chosen/aura,hibernate-layout) this keeps + every reserved range out of the hibernation image; without it, + hibernation and resume are refused instead of overwriting the + running boot loader. The refusal is part of the hibernation + support of these machines, so the option cannot be turned off. + config APPLE_DISPLAY_GATE bool "Apple internal display enable gate" depends on ARCH_APPLE || (COMPILE_TEST && KUNIT) diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index fca7327d06cdd..3ad0d59e2a419 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -27,7 +27,7 @@ apple-sleep-y = sleep.o sleep-perf-step.o obj-$(CONFIG_APPLE_SOC_SLEEP) += t6041-sleep.o obj-$(CONFIG_APPLE_RTKIT) += apple-rtkit.o -apple-rtkit-y = rtkit.o rtkit-crashlog.o +apple-rtkit-y = rtkit.o rtkit-crashlog.o rtkit-hib-handoff.o obj-$(CONFIG_APPLE_RTKIT_HELPER) += apple-rtkit-helper.o apple-rtkit-helper-y = rtkit-helper.o @@ -86,3 +86,4 @@ obj-$(CONFIG_APPLE_ADT_SYSFS) += adt-sysfs.o obj-$(CONFIG_APPLE_ADT_SYSFS_KUNIT_TEST) += adt-sysfs-test.o obj-$(CONFIG_APPLE_AURORA_BOOT_SECURITY) += aurora-boot-security.o +obj-$(CONFIG_APPLE_AURA_HIBERNATE) += aura-hibernate.o diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 72dc06604c6d6..ee3e66dd50bd7 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -11,7 +11,8 @@ use core::{ marker::Unpin, mem, ptr::{self, NonNull}, - slice, // + slice, + sync::atomic::{AtomicI32, AtomicU64, Ordering as CoreOrd}, // }; use kernel::{ @@ -797,6 +798,18 @@ impl AFKEndpoint { } Ok(()) } + /// A reply with no matching call after a hibernation restore is leftover + /// firmware completion for a request that is not in this kernel. Drop it + /// without a warning. Any other unmatched reply is still an error. + fn stale_reply_after_restore() -> Result<()> { + // SAFETY: only reads a flag the PM core keeps until the next snapshot. + if unsafe { bindings::pm_hibernate_is_restored() } { + Ok(()) + } else { + Err(ENOENT) + } + } + /// Counts a message the endpoint could not handle and logs it. The log /// is throttled to the powers of two of the count, so that a stream of /// such messages cannot flood it. @@ -860,10 +873,13 @@ impl AFKEndpoint { // while an abandoned one is outstanding, so at most one // slot is in use and the reply belongs to it. _ if client.epic_v4 => { - self.calls.iter().position(|c| c.is_some()).ok_or(ENOENT)? + match self.calls.iter().position(|c| c.is_some()) { + Some(slot) => slot, + None => return Self::stale_reply_after_restore(), + } } _ if tag == 0 || tag > self.calls.len() => return Err(EINVAL), - _ => return Err(ENOENT), + _ => return Self::stale_reply_after_restore(), }; let tag = slot + 1; let (future, ret) = match self.calls[slot].take() { @@ -871,15 +887,17 @@ impl AFKEndpoint { Some(CallSlot::Abandoned) => { // The late reply to a call that timed out; its slot // is free again. - dev_warn!( - client.dev, - "Late reply for tag {} on endpoint {}", - tag, - self.index - ); + if Self::stale_reply_after_restore().is_err() { + dev_warn!( + client.dev, + "Late reply for tag {} on endpoint {}", + tag, + self.index + ); + } return Ok(()); } - None => return Err(ENOENT), + None => return Self::stale_reply_after_restore(), }; let extra_data = ret.map(|mut ret| { let len = cmp::min(data.len() - 4, ret.len()); @@ -1277,6 +1295,27 @@ const RETIRED_DRIVER_OVERRIDE: &CStr = c_str!("apple-aop-retired"); /// before a reboot. static RETIRED: Atomic = Atomic::new(false); +/// Set by unbind when the ASC CPU run bit reads 0: the co-processor was +/// halted underneath this instance, as the boot loader stages it on every +/// boot, including the one that resumes a hibernation image. A halted CPU +/// neither answers nor DMAs, so the teardown sends nothing and frees +/// everything, and the next probe starts the staged firmware as at boot. +static HALTED_AT_UNBIND: Atomic = Atomic::new(false); + +/// Set by unbind with [`HALTED_AT_UNBIND`], cleared once the next probe set +/// the run bit: that probe starts firmware staged by a boot other than the one +/// this kernel was started on, so it maps that boot's firmware regions +/// ([`AopData::remap_fw_regions_cold`]). +static COLD_REPROBE: Atomic = Atomic::new(false); + +/// The firmware regions mapped in the default domain now (phys, IOVA, size): +/// -1 until the first probe takes them from the device tree; a cold probe +/// replaces them with those of the boot that resumed the image. +const FW_SET_MAX: usize = 8; +static FW_CUR_LEN: AtomicI32 = AtomicI32::new(-1); +static FW_CUR: [[AtomicU64; 3]; FW_SET_MAX] = + [const { [const { AtomicU64::new(0) }; 3] }; FW_SET_MAX]; + impl ChildDevice { /// Keeps the child from binding to any driver again; it stays registered. fn retire(&self) { @@ -1730,6 +1769,37 @@ impl AopData { Ok(()) } + /// Stops the endpoints and shuts the firmware down for good (until the + /// boot loader stages it again), without tearing the instance down: no + /// call starts after it, and the firmware writes nothing more. + fn quiesce_for_image(&self) { + if !self.cpu_started.load(Acquire) || self.crashed.load(Acquire) { + return; + } + self.transport_closing.store(true, Release); + // Any call in progress finishes first; new ones see the flag. + for turn in &self.call_turn { + drop(turn.lock()); + } + if let Err(e) = self.stop() { + dev_warn!(self.dev, "endpoints not stopped before the image ({:?})\n", e); + } + // Out of the lock: the shutdown drains the receive worker, which takes it. + let rtkit = self.rtkit.lock().take(); + if let Some(mut rtkit) = rtkit { + match Pin::new(&mut rtkit).shutdown() { + Ok(()) => dev_info!(self.dev, "firmware shut down before the image is restored\n"), + Err(e) => dev_warn!( + self.dev, + "firmware shutdown before the image unconfirmed ({:?})\n", + e + ), + } + self.rtkit.lock().as_mut().set(Some(rtkit)); + } + self.crashed.store(true, Release); + } + fn shutdown_complete(&self, endpoint: u8) { if let Some(index) = afk_endpoint_index(endpoint) { self.ep_shutdown[index].complete(()); @@ -2184,17 +2254,16 @@ impl AopData { ec0p: u64, allow_ed0p: bool, ) -> Result> { - // SAFETY: `dev` is a live device being probed. - let np = unsafe { (*dev.as_raw()).of_node }; - if np.is_null() { - return Err(ENODEV); - } - // SAFETY: `np` is the device's node, valid while it is bound. - let count = unsafe { bindings::of_reserved_mem_region_count(np) }; - if count <= 0 { - dev_err!(dev, "No firmware memory-region from the bootloader"); - return Err(ENOENT); - } + let set = Self::fw_set_load(dev)?; + let domain = Self::fw_domain(dev)?; + let external_data = Self::check_fw_set(dev, Some(domain), ec0p, allow_ed0p, &set)?; + Self::fw_set_store(&set)?; + Ok(external_data) + } + + /// The device's translated IOMMU domain, which the firmware segments are + /// mapped in. + fn fw_domain(dev: &device::Device) -> Result<*mut bindings::iommu_domain> { // SAFETY: `dev` is a live device being probed. let domain = unsafe { bindings::iommu_get_domain_for_dev(dev.as_raw()) }; let ty = if domain.is_null() { @@ -2207,13 +2276,80 @@ impl AopData { dev_err!(dev, "No translated IOMMU domain for the firmware"); return Err(ENODEV); } - let mut etext = false; - let mut etext_end = 0; - let mut external_data = None; + Ok(domain) + } + + /// The device's node and its number of firmware memory-regions. + fn fw_node(dev: &device::Device) -> Result<(*mut bindings::device_node, c_int)> { + // SAFETY: `dev` is a live device being probed. + let np = unsafe { (*dev.as_raw()).of_node }; + if np.is_null() { + return Err(ENODEV); + } + // SAFETY: `np` is the device's node, valid while it is bound. + let count = unsafe { bindings::of_reserved_mem_region_count(np) }; + if count <= 0 { + dev_err!(dev, "No firmware memory-region from the bootloader"); + return Err(ENOENT); + } + Ok((np, count)) + } + + /// The firmware regions the default domain maps now: the device tree's, + /// until a resume from disk replaced them with those of the boot that + /// resumed. + fn fw_set_load(dev: &device::Device) -> Result> { + let mut set = KVec::new(); + let len = FW_CUR_LEN.load(CoreOrd::Acquire); + if len >= 0 { + for r in FW_CUR.iter().take(len as usize) { + set.push( + ( + r[0].load(CoreOrd::Relaxed), + r[1].load(CoreOrd::Relaxed), + r[2].load(CoreOrd::Relaxed), + ), + GFP_KERNEL, + )?; + } + return Ok(set); + } + let (np, count) = Self::fw_node(dev)?; for idx in 0..count { - let (phys, iova, size) = Self::fw_region(np, idx).inspect_err(|e| { + let region = Self::fw_region(np, idx).inspect_err(|e| { dev_err!(dev, "Invalid firmware memory-region {} ({:?})", idx, e); })?; + set.push(region, GFP_KERNEL)?; + } + Ok(set) + } + + fn fw_set_store(set: &[(u64, u64, u64)]) -> Result<()> { + if set.len() > FW_SET_MAX { + return Err(E2BIG); + } + for (slot, r) in FW_CUR.iter().zip(set.iter()) { + slot[0].store(r.0, CoreOrd::Relaxed); + slot[1].store(r.1, CoreOrd::Relaxed); + slot[2].store(r.2, CoreOrd::Relaxed); + } + FW_CUR_LEN.store(set.len() as i32, CoreOrd::Release); + Ok(()) + } + + /// The layout rules of a set of firmware regions, and with `domain` + /// that every page is mapped where the set says. + fn check_fw_set( + dev: &device::Device, + domain: Option<*mut bindings::iommu_domain>, + ec0p: u64, + allow_ed0p: bool, + set: &[(u64, u64, u64)], + ) -> Result> { + let mut etext = false; + let mut etext_end = 0; + let mut external_data = None; + for (idx, &(phys, iova, size)) in set.iter().enumerate() { if phys % FW_REGION_PAGE != 0 || size == 0 || size % FW_REGION_PAGE != 0 @@ -2248,6 +2384,9 @@ impl AopData { return Err(EINVAL); } } + let Some(domain) = domain else { + continue; + }; let mut off = 0; while off < size { // SAFETY: `domain` is the device's domain, live while it is @@ -2277,13 +2416,159 @@ impl AopData { ); return Err(EINVAL); } - dev_info!( + if domain.is_some() { + dev_info!( + dev, + "Validated external data region at IOVA {:#x}, size {:#x}", + iova, + size + ); + } + } + Ok(external_data) + } + + /// The firmware segments after a resume from disk. The boot that resumed + /// the image staged the firmware anew and placed some of its DRAM + /// segments elsewhere than the boot this kernel was started on (the + /// `__OS_LOG` moves on every boot). Their places come from the device tree + /// of the running boot, which the boot loader leaves at a fixed address: + /// the previous set's mappings this boot does not have are removed, this + /// boot's are mapped (at the IOVA its device tree gives), checked as at + /// boot, and become the current set. Without that device tree the current + /// set is only checked, as before. + fn remap_fw_regions_cold( + dev: &device::Device, + ec0p: u64, + allow_ed0p: bool, + ) -> Result> { + let (np, _) = Self::fw_node(dev)?; + let prev = Self::fw_set_load(dev)?; + let domain = Self::fw_domain(dev)?; + let mut raw = [bindings::aura_fw_region { + phys: 0, + iova: 0, + size: 0, + }; FW_SET_MAX]; + let n = if cfg!(CONFIG_APPLE_AURA_HIBERNATE) { + // SAFETY: `np` is the device's node and `raw` has room for + // `FW_SET_MAX` entries. + unsafe { + bindings::aura_hibernate_boot_fw_regions(np, raw.as_mut_ptr(), FW_SET_MAX as u32) + } + } else { + -(bindings::ENODEV as c_int) + }; + if n == -(bindings::ENODEV as c_int) { + dev_warn!( dev, - "Validated external data region at IOVA {:#x}, size {:#x}", - iova, - size + "resume from disk: no device tree of this boot; checking the current firmware regions" ); + return Self::check_fw_regions(dev, ec0p, allow_ed0p); + } + if n < 0 { + dev_err!( + dev, + "This boot's firmware memory-regions are not available ({}); the firmware cannot be mapped", + n + ); + return Err(Error::from_errno(n)); + } + let mut boot = KVec::new(); + for r in &raw[..n as usize] { + boot.push((r.phys, r.iova, r.size), GFP_KERNEL)?; + } + // The layout first: nothing is mapped for a set that breaks it. + Self::check_fw_set(dev, None, ec0p, allow_ed0p, &boot)?; + // Mapped like the IOMMU core maps a direct region of this device. + // SAFETY: `np` is a valid node. + let coherent = unsafe { bindings::of_dma_is_coherent(np) }; + let mut prot = (bindings::IOMMU_READ | bindings::IOMMU_WRITE) as c_int; + if coherent { + prot |= bindings::IOMMU_CACHE as c_int; + } + // The previous set's regions that this boot moved: unmap only pages + // that still map the old physical range, never anything else at that + // IOVA. Repeating it after a partial failure is harmless. + for &(phys, iova, size) in prev.iter() { + if boot.iter().any(|r| *r == (phys, iova, size)) { + continue; + } + let mut off = 0; + while off < size { + // SAFETY: `domain` is the device's domain, live while it is + // bound. + let back = unsafe { bindings::iommu_iova_to_phys(domain, iova + off) }; + if back == phys + off { + // SAFETY: As above; the page was mapped for this region. + let done = unsafe { + bindings::iommu_unmap( + domain, + (iova + off) as usize, + FW_REGION_PAGE as usize, + ) + }; + if done != FW_REGION_PAGE as usize { + dev_err!(dev, "Could not unmap IOVA {:#x} of the old boot", iova + off); + return Err(EIO); + } + } + off += FW_REGION_PAGE; + } } + // This boot's regions: map what is missing, refuse what is taken. + let mut moved = 0; + for (idx, &(phys, iova, size)) in boot.iter().enumerate() { + let mut off = 0; + let mut mapped = 0; + while off < size { + // SAFETY: `domain` is the device's domain, live while it is + // bound. + let back = unsafe { bindings::iommu_iova_to_phys(domain, iova + off) }; + if back != phys + off { + if back != 0 { + dev_err!( + dev, + "IOVA {:#x} for this boot's firmware region {} is in use ({:#x})", + iova + off, + idx, + back + ); + return Err(EBUSY); + } + // SAFETY: As above; the IOVA page is free and the physical + // page is this boot's firmware segment, which Linux does + // not own (checked by the helper). + let err = unsafe { + bindings::iommu_map( + domain, + (iova + off) as usize, + phys + off, + FW_REGION_PAGE as usize, + prot, + bindings::GFP_KERNEL, + ) + }; + if err != 0 { + dev_err!(dev, "Could not map IOVA {:#x} ({})", iova + off, err); + return Err(Error::from_errno(err)); + } + mapped += 1; + } + off += FW_REGION_PAGE; + } + if mapped != 0 { + moved += 1; + } + } + let external_data = Self::check_fw_set(dev, Some(domain), ec0p, allow_ed0p, &boot)?; + Self::fw_set_store(&boot)?; + dev_info!( + dev, + "resume from disk: {} firmware regions of this boot mapped, {} of them moved\n", + boot.len(), + moved + ); Ok(external_data) } @@ -2511,6 +2796,16 @@ impl AOP for AopData { // No registration is queued after this point, so once the queue is // empty the list of children is complete. self.registration_queue.drain(); + let halted = HALTED_AT_UNBIND.xchg(false, Acquire) && self.cpu_started.load(Acquire); + if halted { + // Nobody answers: the children's unbind calls fail at once + // instead of each waiting for a reply. + self.transport_closing.store(true, Release); + dev_info!( + self.dev, + "co-processor halted underneath (resume from disk): releasing the old session without a shutdown\n" + ); + } // Unbind the children while the transport still works, so that their // unbind can talk to their services. Then drop any listener a child // left behind: no report may reach a driver that is going away. @@ -2521,8 +2816,10 @@ impl AOP for AopData { self.hid_listeners.lock().clear(); self.report_listeners.lock().clear(); self.transport_closing.store(true, Release); - if let Err(e) = self.stop() { - dev_err!(self.dev, "Failed to stop AOP {:?}", e); + if !halted { + if let Err(e) = self.stop() { + dev_err!(self.dev, "Failed to stop AOP {:?}", e); + } } // Take the handle out of the shared state before dropping it: the // drop waits for the RTKit receive worker, which takes the same lock. @@ -2530,7 +2827,7 @@ impl AOP for AopData { let rtkit = self.rtkit.lock().take(); let mut quiesced = true; if let Some(mut rtkit) = rtkit { - if self.quiesce_on_unbind && self.cpu_started.load(Acquire) { + if self.quiesce_on_unbind && self.cpu_started.load(Acquire) && !halted { // The co-processor DMAs into the shared buffers until it has // acknowledged the shutdown. If it does not, nothing it may // still write to can be freed. @@ -3227,11 +3524,20 @@ const HW_CFG_T6040: AopHwConfig = AopHwConfig { without_fw_regions: None, s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; +/// T6040 (J616s) AFK sleep and wake order: the same endpoint sequence T6041 +/// uses. T6040 already used that order under the shared t604x compatible +/// `apple,t6041-aop`. HW_CFG_T6040 itself stays empty so SoCs that copy it +/// do not inherit a T604x-only sequence. +const HW_CFG_T6040_AFK: AopHwConfig = AopHwConfig { + sleep_endpoints: &[0x2b, 0x2a, 0x24, 0x20, 0x27, 0x26, 0x28, 0x25, 0x21, 0x29, 0x23, 0x22], + wake_endpoints: &[0x22, 0x23, 0x29, 0x21, 0x25, 0x28, 0x26, 0x27, 0x20, 0x24, 0x2a, 0x2b], + ..HW_CFG_T6040 +}; /// T6041 (J616C): as T6040, with the AFK sleep and wake order macOS 26.6.2 uses on the J616C /// (trace, 8 Nov 2026: sleep to these endpoints in this order, then the AP idle notice). const HW_CFG_T6041: AopHwConfig = AopHwConfig { - sleep_endpoints: &[0x2b, 0x2a, 0x24, 0x20, 0x27, 0x26, 0x28, 0x25, 0x21, 0x29, 0x23, 0x22], - wake_endpoints: &[0x22, 0x23, 0x29, 0x21, 0x25, 0x28, 0x26, 0x27, 0x20, 0x24, 0x2a, 0x2b], + sleep_endpoints: HW_CFG_T6040_AFK.sleep_endpoints, + wake_endpoints: HW_CFG_T6040_AFK.wake_endpoints, ..HW_CFG_T6040 }; /// T8132 (J713): as T6040. The bootloader hands the AOP over the same way, with @@ -3384,9 +3690,91 @@ unsafe extern "C" fn aop_resume(dev: *mut bindings::device) -> c_int { 0 } +/// The kernel that loads a hibernation image started this co-processor for +/// its own boot, and its buffers are about to be overwritten by the image: +/// shut the firmware down first, so that it stops writing into them. It +/// cannot be started again before a reboot (it does not answer a new boot +/// handshake), which the restored kernel finds out from the run bit. +/// +/// # Safety +/// +/// Called by the PM core with a bound AOP device. +unsafe extern "C" fn aop_freeze(dev: *mut bindings::device) -> c_int { + // SAFETY: only reads a flag. + if !unsafe { bindings::apple_rtkit_hib_restoring() } { + return 0; + } + // SAFETY: by this function's contract. + unsafe { aop_from_dev(dev) }.quiesce_for_image(); + 0 +} + +/// A resume from disk is a cold boot: the boot loader staged the co-processor +/// anew and left it halted. The session this kernel holds is gone, but +/// nothing tells its clients: every call they make waits for a reply that +/// never comes, and the mailbox keeps the doorbells, which the firmware the +/// next probe starts would take as its own first messages. So the transport +/// closes here, before any client runs, and the device is probed again once +/// the tasks are thawed: the unbind finds the run bit clear and drops the old +/// session without a shutdown, the probe starts the firmware as at boot and +/// registers the services again, each of which sets itself up from scratch. +/// A co-processor that runs was started by the kernel that loaded the image, +/// for its own session: it stays off until a reboot. +/// +/// # Safety +/// +/// Called by the PM core with a bound AOP device. +unsafe extern "C" fn aop_restore(dev: *mut bindings::device) -> c_int { + // SAFETY: only reads a flag. + if !unsafe { bindings::pm_hibernate_is_restored() } { + return 0; + } + // SAFETY: by this function's contract. + let data = unsafe { aop_from_dev(dev) }; + if !data.cpu_started.load(Acquire) || data.removing.load(Acquire) { + return 0; + } + data.transport_closing.store(true, Release); + // SAFETY: the PM core runs this callback on a bound device, under its + // device lock. + let bound = unsafe { device::Device::::from_raw(dev) }; + let Ok(pdev) = <&platform::Device>::try_from(bound) else { + return 0; + }; + if !asc_cpu_halted(pdev) { + data.crashed.store(true, Release); + dev_warn!( + data.dev, + "resume from disk: the co-processor runs a session of the kernel that loaded the image; it stays off until a reboot\n" + ); + return 0; + } + let queued = if cfg!(CONFIG_APPLE_AURA_HIBERNATE) { + // SAFETY: `dev` is a live device; the helper holds a reference until + // its work ran. + to_result(unsafe { bindings::aura_hibernate_reprobe_after_thaw(dev) }) + } else { + Err(EOPNOTSUPP) + }; + match queued { + Ok(()) => dev_info!( + data.dev, + "resume from disk: co-processor halted (cold boot), restarting it once tasks are thawed\n" + ), + Err(e) => dev_warn!( + data.dev, + "resume from disk: co-processor halted (cold boot), calls refused; restart not queued ({:?})\n", + e + ), + } + 0 +} + static AOP_PM_OPS: bindings::dev_pm_ops = bindings::dev_pm_ops { suspend_late: Some(aop_suspend_late), resume: Some(aop_resume), + freeze: Some(aop_freeze), + restore: Some(aop_restore), // SAFETY: all-zero is a valid `dev_pm_ops`: no callbacks. ..unsafe { core::mem::zeroed() } }; @@ -3403,6 +3791,7 @@ kernel::of_device_table!( (of::DeviceId::new(c_str!("apple,t6031-aop")), &HW_CFG_T6030), (of::DeviceId::new(c_str!("apple,t6020-aop")), &HW_CFG_T6020), (of::DeviceId::new(c_str!("apple,t8140-aop")), &HW_CFG_T8140), + (of::DeviceId::new(c_str!("apple,t6040-aop")), &HW_CFG_T6040_AFK), (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6041), (of::DeviceId::new(c_str!("apple,t8132-aop")), &HW_CFG_T8132), (of::DeviceId::new(c_str!("apple,t6050-aop")), &HW_CFG_T6050), @@ -3452,7 +3841,20 @@ impl platform::Driver for AopDriver { // Before anything is written to the AOP: no mapping, no start. let allow_ed0p = cfg.patch_bootargs && AopData::bootargs_has_ed0p(&aop_mmio, cfg.bootargs_word_access)?; - AopData::check_fw_regions(pdev.as_ref(), cfg.ec0p, allow_ed0p)?.map(|(iova, _)| iova) + let regions = if COLD_REPROBE.load(Acquire) { + // Remapping is only safe while the firmware does not run. + if asc_mmio.read(ASC_CPU_CONTROL).cpu_run() != 0 { + dev_err!( + pdev.as_ref(), + "resume from disk: the co-processor runs, its firmware regions are left alone" + ); + return Err(EBUSY); + } + AopData::remap_fw_regions_cold(pdev.as_ref(), cfg.ec0p, allow_ed0p)? + } else { + AopData::check_fw_regions(pdev.as_ref(), cfg.ec0p, allow_ed0p)? + }; + regions.map(|(iova, _)| iova) } else { None }; @@ -3494,6 +3896,9 @@ impl platform::Driver for AopDriver { } asc_mmio.update(ASC_CPU_CONTROL, |r| r.with_const_cpu_run::<1>()); data.cpu_started.store(true, Release); + // The firmware runs from here on: a later unbind sees it running and + // the next probe is an ordinary one, whatever happens below. + COLD_REPROBE.store(false, Release); let started = if setup_port { // The RTKit handshake up to AP power on comes first, then the // setup port's own power state and endpoint buffers, and only @@ -3531,13 +3936,37 @@ impl platform::Driver for AopDriver { Ok(Self(data)) } - fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { + fn unbind(dev: &platform::Device>, this: Pin<&Self>) { + let data: *const dyn AOP = &*this.0; + // SAFETY: probe made this `Arc` from an `Arc`. + let data = unsafe { &*data.cast::() }; + // Run bit clear on a co-processor this instance started: the boot + // that resumed an image staged it anew. + let halted = data.cpu_started.load(Acquire) && asc_cpu_halted(dev); + HALTED_AT_UNBIND.store(halted, Release); + if halted { + COLD_REPROBE.store(true, Release); + } // The device is still bound here, which the DMA allocations the // teardown frees require. Drop only repeats it as a no-op. this.0.remove(); } } +/// Reads the ASC CPU run bit. Probe sets it; only the boot loader clears it +/// (the co-processor is staged halted at every boot, including the one that +/// resumes a hibernation image). A failure to read it counts as running, +/// which keeps the full shutdown. +fn asc_cpu_halted(pdev: &platform::Device) -> bool { + let Some(req) = pdev.io_request_by_index(1) else { + return false; + }; + let Ok(asc) = req.iomap_sized::() else { + return false; + }; + asc.as_view().relaxed().read(ASC_CPU_CONTROL).cpu_run() == 0 +} + impl Drop for AopDriver { fn drop(&mut self) { self.0.remove(); diff --git a/drivers/soc/apple/apple-cluster-pwrgate.c b/drivers/soc/apple/apple-cluster-pwrgate.c index 127f95a56f436..26a75621931f9 100644 --- a/drivers/soc/apple/apple-cluster-pwrgate.c +++ b/drivers/soc/apple/apple-cluster-pwrgate.c @@ -42,14 +42,43 @@ #include #include #include +#include #define CLUSTER_PWRGATE_EN BIT(31) +#define CLUSTER_PWRGATE_MAX 64 static const struct of_device_id apple_cluster_pwrgate_of_match[] __initconst = { { .compatible = "apple,cluster-pwrgate" }, { } }; +#ifdef CONFIG_PM_SLEEP +static void __iomem *apple_cluster_pwrgates[CLUSTER_PWRGATE_MAX]; +static unsigned int apple_cluster_pwrgate_count; + +/* + * After a cold hibernation restore the boot ROM starts CPU 0 with its power + * gate word clear again. Restore every gate before secondary CPUs online and + * before any subsequent suspend-to-RAM enters the sleep sequencer. + */ +static void apple_cluster_pwrgate_resume(void *data) +{ + unsigned int i; + + for (i = 0; i < apple_cluster_pwrgate_count; i++) + writel(readl(apple_cluster_pwrgates[i]) | CLUSTER_PWRGATE_EN, + apple_cluster_pwrgates[i]); +} + +static const struct syscore_ops apple_cluster_pwrgate_syscore_ops = { + .resume = apple_cluster_pwrgate_resume, +}; + +static struct syscore apple_cluster_pwrgate_syscore = { + .ops = &apple_cluster_pwrgate_syscore_ops, +}; +#endif + /* Before the secondaries start. A core picks the word up at its next WFI. */ static int __init apple_cluster_pwrgate_init(void) { @@ -69,10 +98,21 @@ static int __init apple_cluster_pwrgate_init(void) writel(was | CLUSTER_PWRGATE_EN, gate); pr_debug("%pOF: power gate %d %#x, now %#x\n", np, i, was, readl(gate)); +#ifdef CONFIG_PM_SLEEP + if (apple_cluster_pwrgate_count < CLUSTER_PWRGATE_MAX) { + apple_cluster_pwrgates[apple_cluster_pwrgate_count++] = gate; + continue; + } +#endif iounmap(gate); } } +#ifdef CONFIG_PM_SLEEP + if (apple_cluster_pwrgate_count) + register_syscore(&apple_cluster_pwrgate_syscore); +#endif + return 0; } early_initcall(apple_cluster_pwrgate_init); diff --git a/drivers/soc/apple/aura-hibernate.c b/drivers/soc/apple/aura-hibernate.c new file mode 100644 index 0000000000000..6e20eb89da5c8 --- /dev/null +++ b/drivers/soc/apple/aura-hibernate.c @@ -0,0 +1,571 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Hibernation on Apple Silicon under an aura boot object. + * + * A hibernation image restores every saved page to the frame it was taken from, and swsusp saves + * reserved pages as long as they are mapped. Under aura the memory below Linux's own allocations + * holds what the boot loader keeps alive across the hand-off: aura itself (resident at EL2), its + * heap with the firmware buffers it handed over, the device tree, the initramfs, and the ranges + * the boot firmware placed for the co-processors. Restoring old contents there would overwrite + * the running boot loader and the live firmware state of the resuming boot. + * + * aura marks a boot whose layout is the same on every boot with /chosen/aura,hibernate-layout + * (start, end of the range it keeps from Linux). On such a boot every /memreserve/ range and every + * non-reusable /reserved-memory range is registered as nosave, except the kernel image itself. + * Without the property, hibernation and resume are refused, since the reserved ranges move. + * + * The boot firmware still places some firmware segments anew on every boot (the AOP __OS_LOG), + * inside the range aura keeps from Linux. A kernel restored from an image knows the device tree of + * the boot it was started on, not of the boot that resumed it. aura therefore hands Linux its + * device tree at a fixed address inside that range (/chosen/aura,hibernate-dt): the image does not + * save it, so after a resume the kernel finds this boot's tree at the address it was started with, + * and aura_hibernate_boot_fw_regions() reads a device's firmware regions from it. + * + * aura itself moves with the boot object, and with it its S2R mailbox: a restored kernel reads the + * mailbox of the boot it runs on from that tree too (aura_hibernate_boot_chosen_u64()). + */ + +#define pr_fmt(fmt) "aura-hibernate: " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool aura_layout_fixed; +static u64 aura_layout[2]; +/* Where aura puts the device tree on every boot; 0 when it does not. */ +static phys_addr_t aura_boot_dt; +#define AURA_BOOT_DT_MAX SZ_2M + +/* + * Ranges kept out of the image, in page frames. Filled once at late_initcall, + * read through the arm64 hibernation platform hooks. A static table avoids + * register_nosave_region(), which allocates from memblock and is meant for + * setup_arch() time. + */ +#define AURA_NOSAVE_MAX 128 +static struct { unsigned long start, end; } aura_nosave[AURA_NOSAVE_MAX]; +static unsigned int aura_nosave_count; + +/* + * Apple silicon Macs run firmware on their coprocessors (storage, secure + * enclave, display, always-on processor, system controller, GPU and more). + * Restoring an image means a cold boot through the platform boot chain, which + * restarts that firmware, but most of the Linux drivers have no + * freeze/poweroff/restore path that rebuilds their mailbox, ring and DMA state + * from a cold start. The restored kernel would keep using stale state, so + * writing and restoring images stays disabled on these machines, except where + * the boot object gives the OS a fixed memory layout and the drivers rebuild + * their coprocessor state from the cold boot that restores the image (aura + * hib=1, see above). + */ +static bool aura_hibernate_blocked(void) +{ + return of_machine_is_compatible("apple,arm-platform") && !aura_layout_fixed; +} + +static bool aura_hibernate_pfn_nosave(unsigned long pfn) +{ + unsigned int i; + + for (i = 0; i < aura_nosave_count; i++) + if (pfn >= aura_nosave[i].start && pfn < aura_nosave[i].end) + return true; + return false; +} + +/* + * Whether no page of [start, end) can reach the image: each is in a range kept out of it, or in + * memory the kernel does not map (the boot loader's no-map carveouts and firmware ranges, which + * the kernel never saves), or in no memory at all. + */ +static bool aura_hibernate_range_nosave(u64 start, u64 end) +{ + unsigned long pfn = PFN_DOWN(start), last = PFN_UP(end), next, s, e; + struct memblock_region *r; + unsigned int i; + bool moved; + + while (pfn < last) { + moved = false; + for (i = 0; i < aura_nosave_count; i++) { + if (pfn >= aura_nosave[i].start && pfn < aura_nosave[i].end) { + pfn = aura_nosave[i].end; + moved = true; + } + } + if (moved) + continue; + /* Skip the unmapped memory or hole at @pfn; mapped memory is saved. */ + next = last; + for_each_mem_region(r) { + s = PFN_DOWN(r->base); + e = PFN_UP(r->base + r->size); + if (pfn >= s && pfn < e) { + if (!(r->flags & MEMBLOCK_NOMAP)) + return false; + next = e; + break; + } + if (s > pfn && s < next) + next = s; + } + pfn = next; + } + return true; +} + +/* + * The image restores every page to the frame it came from, so the boot that + * resumes it must give the kernel what the boot that wrote it did: on Apple + * machines at EL2 the same CTXR exec window (secondaries only execute inside + * it) and aura's fixed hibernation layout. They are added to the layout cookie + * of arm64 hibernation. + * + * aura's own image moves with the boot object, and its CPU release addresses + * and S2R mailbox with it, inside the range the layout keeps from Linux. The + * restored kernel uses neither address of the boot that wrote the image: its + * CPUs come back from the boot kernel's pen, a CPU started at its reset vector + * again finds the release target the boot kernel wrote (both kernels run at the + * window's fixed address), and the T6040 sleep driver takes this boot's mailbox + * from aura's tree after the restore. What has to match is the spin table's + * shape (the same CPUs, at the same offsets from the mailbox) and that this + * boot keeps all of it out of the image. + */ +static u64 aura_hibernate_layout(u64 h, struct arm64_hibernate_layout *lay) +{ + static const char * const chosen_props[] = { + "aura,hibernate-layout", "aura,hibernate-dt", + "aurora,ctxr-exec-window", + }; + u64 mbox = 0, layout[2], win[2]; + struct device_node *np; + const void *v; + u8 kept; + int i, len; + + np = of_find_node_by_path("/chosen"); + for (i = 0; np && i < ARRAY_SIZE(chosen_props); i++) { + v = of_get_property(np, chosen_props[i], &len); + if (!v) + continue; + h = arm64_hibernate_layout_mix(h, chosen_props[i], strlen(chosen_props[i])); + h = arm64_hibernate_layout_mix(h, v, len); + } + if (np && !of_property_read_u64(np, "aurora,s2r-mailbox", &mbox)) { + lay->have_base = true; + lay->base = mbox; + kept = aura_hibernate_pfn_nosave(PHYS_PFN(mbox)); + h = arm64_hibernate_layout_mix(h, "aurora,s2r-mailbox", + strlen("aurora,s2r-mailbox")); + h = arm64_hibernate_layout_mix(h, &kept, sizeof(kept)); + } + /* aura's layout less the OS window, only where all of it is kept out of the image */ + if (np && !of_property_read_u64_array(np, "aura,hibernate-layout", layout, 2) && + !of_property_read_u64_array(np, "aurora,ctxr-exec-window", win, 2) && + layout[0] <= win[0] && win[0] + win[1] <= layout[1]) { + lay->ex[lay->nex][0] = layout[0]; + lay->ex[lay->nex][1] = win[0]; + if (aura_hibernate_range_nosave(lay->ex[lay->nex][0], lay->ex[lay->nex][1])) + lay->nex++; + lay->ex[lay->nex][0] = win[0] + win[1]; + lay->ex[lay->nex][1] = layout[1]; + if (aura_hibernate_range_nosave(lay->ex[lay->nex][0], lay->ex[lay->nex][1])) + lay->nex++; + } + of_node_put(np); + return h; +} + +static const struct arm64_hibernate_platform aura_hibernate_platform = { + .pfn_nosave = aura_hibernate_pfn_nosave, + .layout = aura_hibernate_layout, +}; + +static void __init aura_nosave_add(unsigned long s, unsigned long e) +{ + if (s >= e) + return; + if (aura_nosave_count == AURA_NOSAVE_MAX) { + pr_warn("more than %d reserved ranges; hibernation stays disabled\n", + AURA_NOSAVE_MAX); + aura_nosave_count++; + return; + } + if (aura_nosave_count < AURA_NOSAVE_MAX) { + aura_nosave[aura_nosave_count].start = s; + aura_nosave[aura_nosave_count].end = e; + aura_nosave_count++; + } +} + +static void __init aura_nosave_range(u64 start, u64 end, unsigned long kstart, unsigned long kend, + const char *what) +{ + unsigned long s = PFN_DOWN(start), e = PFN_UP(end); + + if (s >= e) + return; + /* The kernel image is Linux's own and is saved; split the range around it. */ + if (s < kend && e > kstart) { + if (s < kstart) + aura_nosave_add(s, kstart); + if (e > kend) + aura_nosave_add(kend, e); + } else { + aura_nosave_add(s, e); + } + pr_debug("nosave %s [%#llx, %#llx)\n", what, start, end); +} + +/* + * Whether @fdt, mapped from @slot, is a tree aura wrote there: a valid header that fits the slot, + * and a /chosen naming this slot and the fixed layout @layout. + */ +static bool aura_slot_tree_valid(const void *fdt, phys_addr_t slot, const u64 layout[2]) +{ + const fdt64_t *v; + int node, len; + + if (fdt_check_header(fdt) || fdt_totalsize(fdt) > AURA_BOOT_DT_MAX) + return false; + node = fdt_path_offset(fdt, "/chosen"); + if (node < 0) + return false; + v = fdt_getprop(fdt, node, "aura,hibernate-dt", &len); + if (!v || len != sizeof(*v) || fdt64_ld(v) != slot) + return false; + v = fdt_getprop(fdt, node, "aura,hibernate-layout", &len); + return v && len == 2 * sizeof(*v) && fdt64_ld(&v[0]) == layout[0] && + fdt64_ld(&v[1]) == layout[1]; +} + +/* + * Reads the u64 property @name of /chosen from the device tree of the running boot, which after a + * resume from disk is not the one the kernel was started with. Returns 0, -ENODEV when aura does + * not hand the tree over at a fixed address, -EINVAL when the slot holds no tree for this layout, + * -ENOENT when the tree has no such property. + */ +int aura_hibernate_boot_chosen_u64(const char *name, u64 *val) +{ + const fdt64_t *v; + int node, len, ret; + void *fdt; + + if (!aura_boot_dt) + return -ENODEV; + fdt = memremap(aura_boot_dt, AURA_BOOT_DT_MAX, MEMREMAP_WB); + if (!fdt) + return -ENOMEM; + ret = -EINVAL; + if (!aura_slot_tree_valid(fdt, aura_boot_dt, aura_layout)) + goto out; + ret = -ENOENT; + node = fdt_path_offset(fdt, "/chosen"); + v = node < 0 ? NULL : fdt_getprop(fdt, node, name, &len); + if (!v || len != sizeof(*v)) + goto out; + *val = fdt64_ld(v); + ret = 0; +out: + memunmap(fdt); + return ret; +} +EXPORT_SYMBOL_GPL(aura_hibernate_boot_chosen_u64); + +static bool aura_fw_region_kept(u64 start, u64 size) +{ + u64 end = start + size, a; + + if (end < start) + return false; + /* + * Inside the range aura keeps from Linux below its device tree slot, where the boot + * firmware places the firmware: reserved, and not saved in the image. Not the slot or + * aura's heap above it. + */ + if (start >= aura_layout[0] && end <= aura_boot_dt) + return true; + /* Otherwise Linux must neither own nor map any of it (no-map or not RAM). */ + for (a = start & PAGE_MASK; a < end; a += PAGE_SIZE) + if (memblock_is_map_memory(a)) + return false; + return true; +} + +/* + * Reads the firmware memory-regions of @np (its memory-region phandles, each + * region's reg and the iommu-addresses entry naming @np) from the device tree + * of the running boot, which after a resume from disk is not the one the + * kernel was started with. Returns the number of regions, at most @max, or a + * negative errno: -ENODEV when aura does not hand the tree over at a fixed + * address. Only flat, untranslated layouts are accepted: @np's parent without + * dma-ranges, a /reserved-memory without a non-empty ranges. + */ +int aura_hibernate_boot_fw_regions(struct device_node *np, struct aura_fw_region *out, + unsigned int max) +{ + const fdt32_t *phandles, *p; + unsigned int n = 0; + int node, parent, len, ret, i; + u32 own; + char *path; + void *fdt; + + if (!aura_boot_dt || !np) + return -ENODEV; + fdt = memremap(aura_boot_dt, AURA_BOOT_DT_MAX, MEMREMAP_WB); + if (!fdt) + return -ENOMEM; + ret = -EINVAL; + /* The tree aura handed over on this boot, with the same fixed layout. */ + if (!aura_slot_tree_valid(fdt, aura_boot_dt, aura_layout)) + goto out; + + path = kasprintf(GFP_KERNEL, "%pOF", np); + if (!path) { + ret = -ENOMEM; + goto out; + } + node = fdt_path_offset(fdt, path); + kfree(path); + ret = -ENOENT; + if (node < 0) + goto out; + ret = -EINVAL; + own = fdt_get_phandle(fdt, node); + parent = fdt_parent_offset(fdt, node); + if (!own || parent < 0 || fdt_getprop(fdt, parent, "dma-ranges", NULL)) + goto out; + phandles = fdt_getprop(fdt, node, "memory-region", &len); + if (!phandles || len <= 0 || len % sizeof(*phandles)) + goto out; + + for (i = 0; i < len / (int)sizeof(*phandles); i++) { + int region, rparent, ac, sc, cells, pos, plen; + const fdt32_t *reg, *iommu; + u64 phys, size, iova = 0, length = 0; + bool found = false; + + region = fdt_node_offset_by_phandle(fdt, fdt32_to_cpu(phandles[i])); + if (region < 0) + goto out; + rparent = fdt_parent_offset(fdt, region); + if (rparent < 0) + goto out; + p = fdt_getprop(fdt, rparent, "ranges", &plen); + if (p && plen) + goto out; + ac = fdt_address_cells(fdt, rparent); + sc = fdt_size_cells(fdt, rparent); + reg = fdt_getprop(fdt, region, "reg", &plen); + if (ac < 1 || ac > 2 || sc < 1 || sc > 2 || !reg || + plen < (int)((ac + sc) * sizeof(*reg))) + goto out; + phys = fdt32_to_cpu(reg[0]); + if (ac == 2) + phys = phys << 32 | fdt32_to_cpu(reg[1]); + size = fdt32_to_cpu(reg[ac]); + if (sc == 2) + size = size << 32 | fdt32_to_cpu(reg[ac + 1]); + + /* Entries: owner phandle, then an address and a size in the owner's bus cells. */ + iommu = fdt_getprop(fdt, region, "iommu-addresses", &plen); + if (!iommu || plen <= 0 || plen % sizeof(*iommu)) + goto out; + cells = plen / sizeof(*iommu); + for (pos = 0; pos < cells;) { + u32 ph = fdt32_to_cpu(iommu[pos++]); + int owner = fdt_node_offset_by_phandle(fdt, ph), op, oac, osc; + + if (owner < 0) + goto out; + op = fdt_parent_offset(fdt, owner); + if (op < 0) + goto out; + oac = fdt_address_cells(fdt, op); + osc = fdt_size_cells(fdt, op); + if (oac < 1 || oac > 2 || osc < 1 || osc > 2 || oac + osc > cells - pos) + goto out; + if (ph == own) { + if (found) + goto out; + found = true; + iova = fdt32_to_cpu(iommu[pos]); + if (oac == 2) + iova = iova << 32 | fdt32_to_cpu(iommu[pos + 1]); + length = fdt32_to_cpu(iommu[pos + oac]); + if (osc == 2) + length = length << 32 | fdt32_to_cpu(iommu[pos + oac + 1]); + } + pos += oac + osc; + } + if (!found || length != size || !size) + goto out; + if (!aura_fw_region_kept(phys, size)) { + pr_warn("%pOF: this boot's firmware region [%#llx, +%#llx) is memory Linux owns\n", + np, phys, size); + ret = -EBUSY; + goto out; + } + if (n == max) { + ret = -E2BIG; + goto out; + } + out[n].phys = phys; + out[n].iova = iova; + out[n].size = size; + n++; + } + ret = n; +out: + memunmap(fdt); + return ret; +} +EXPORT_SYMBOL_GPL(aura_hibernate_boot_fw_regions); + +struct aura_hibernate_reprobe { + struct work_struct work; + struct device *dev; +}; + +static void aura_hibernate_reprobe_work(struct work_struct *work) +{ + struct aura_hibernate_reprobe *rp = container_of(work, struct aura_hibernate_reprobe, work); + int ret; + + ret = device_reprobe(rp->dev); + /* A failed probe is not reported by device_reprobe() itself. */ + if (ret || !READ_ONCE(rp->dev->driver)) + dev_err(rp->dev, "probe after the resume from disk failed: %d\n", ret); + put_device(rp->dev); + kfree(rp); +} + +/* + * Unbinds @dev and probes it again once the tasks are thawed, for a driver whose co-processor + * the boot that resumed the image left halted: its unbind and its probe know how to drop a + * session that died under it and start the firmware anew, as at boot, and a restore callback + * cannot run either. The work runs on the freezable workqueue, which the restore finds frozen, + * so it starts after every device's restore and its complete step, when probing is allowed + * again. Built in, so that a driver module going away meanwhile leaves nothing behind. + */ +int aura_hibernate_reprobe_after_thaw(struct device *dev) +{ + struct aura_hibernate_reprobe *rp; + + rp = kzalloc_obj(*rp); + if (!rp) + return -ENOMEM; + INIT_WORK(&rp->work, aura_hibernate_reprobe_work); + rp->dev = get_device(dev); + queue_work(system_freezable_wq, &rp->work); + return 0; +} +EXPORT_SYMBOL_GPL(aura_hibernate_reprobe_after_thaw); + +static int __init aura_hibernate_init(void) +{ + unsigned long kstart = PFN_DOWN(__pa_symbol(_text)), kend = PFN_UP(__pa_symbol(_end)); + struct device_node *chosen, *rmem, *child; + unsigned int count = 0; + const void *fdt = initial_boot_params; + u64 layout[2], dt_slot; + int i, n; + + if (!of_machine_is_compatible("apple,arm-platform")) + return 0; + + hibernation_set_platform_check(aura_hibernate_blocked, + "coprocessor firmware state is not restored from an image"); + arm64_hibernate_set_platform(&aura_hibernate_platform); + + /* Only a boot loader that keeps the layout fixed publishes it. */ + chosen = of_find_node_by_path("/chosen"); + if (!chosen || + of_property_read_u64_array(chosen, "aura,hibernate-layout", layout, 2)) { + of_node_put(chosen); + return 0; + } + /* + * The device tree slot. Trusted where this kernel's tree is, or, when a later stage (U-Boot + * and the EFI stub) handed the kernel its own copy of aura's tree, where the slot still + * holds aura's tree for this layout: those stages do not move the firmware segments, so + * aura's tree and the kernel's copy agree on them. + */ + if (!of_property_read_u64(chosen, "aura,hibernate-dt", &dt_slot)) { + bool in_layout = dt_slot >= layout[0] && dt_slot + AURA_BOOT_DT_MAX <= layout[1]; + void *slot_fdt; + + if (in_layout && dt_slot == __fdt_pointer) { + aura_boot_dt = dt_slot; + } else if (in_layout) { + slot_fdt = memremap(dt_slot, AURA_BOOT_DT_MAX, MEMREMAP_WB); + if (slot_fdt && aura_slot_tree_valid(slot_fdt, dt_slot, layout)) { + aura_boot_dt = dt_slot; + pr_info("device tree handed over at %pa; using aura's tree at %#llx\n", + &__fdt_pointer, dt_slot); + } else { + pr_warn("device tree at %pa, aura's slot %#llx holds no tree for this layout\n", + &__fdt_pointer, dt_slot); + } + if (slot_fdt) + memunmap(slot_fdt); + } else { + pr_warn("device tree slot %#llx outside the fixed layout\n", dt_slot); + } + } + of_node_put(chosen); + + if (fdt) { + n = fdt_num_mem_rsv(fdt); + for (i = 0; i < n; i++) { + u64 addr, size; + + if (fdt_get_mem_rsv(fdt, i, &addr, &size) || !size) + continue; + aura_nosave_range(addr, addr + size, kstart, kend, "memreserve"); + count++; + } + } + + rmem = of_find_node_by_path("/reserved-memory"); + for_each_available_child_of_node(rmem, child) { + struct resource r; + + if (of_property_read_bool(child, "reusable")) + continue; + if (of_address_to_resource(child, 0, &r)) + continue; + aura_nosave_range(r.start, r.end + 1, kstart, kend, "reserved-memory"); + count++; + } + of_node_put(rmem); + + if (aura_nosave_count > AURA_NOSAVE_MAX) { + aura_nosave_count = 0; + return 0; + } + aura_layout[0] = layout[0]; + aura_layout[1] = layout[1]; + aura_layout_fixed = true; + pr_info("fixed boot layout [%#llx, %#llx), %u reserved ranges kept out of the image%s\n", + layout[0], layout[1], count, + aura_boot_dt ? ", device tree at a fixed address" : ""); + return 0; +} +late_initcall(aura_hibernate_init); diff --git a/drivers/soc/apple/diag_shim.c b/drivers/soc/apple/diag_shim.c index 1f905fd2f5c65..ad6e7d75a7266 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -844,6 +844,10 @@ int sep_diag_register(struct device *dev, const char *profile, atomic_set(&sep_diag.trusted, SEP_DIAG_TRUSTED_UNKNOWN); /* So do the failure counts: they are documented as counts since probe. */ sep_diag_bind_counts_reset(&sep_diag.bind); + /* And the attach and bring-up times and the key store's state. */ + atomic64_set(&sep_diag.attach_ns, 0); + atomic64_set(&sep_diag.ready_ns, 0); + atomic_set(&sep_diag.keystore, SEP_DIAG_KEYSTORE_UNKNOWN); ret = devm_device_add_group(dev, &sep_diag_group); if (ret) diff --git a/drivers/soc/apple/dockchannel.c b/drivers/soc/apple/dockchannel.c index 2bbc5f21181f3..86ad0996e3bbb 100644 --- a/drivers/soc/apple/dockchannel.c +++ b/drivers/soc/apple/dockchannel.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -67,6 +68,10 @@ struct dockchannel { struct completion tx_comp; struct completion rx_comp; + /* Receive threshold last programmed, and below-threshold interrupts in a row. */ + u32 rx_thresh; + unsigned int rx_spurious; + void *cookie; void (*data_available)(void *cookie, size_t avail); }; @@ -80,6 +85,9 @@ struct dockchannel_common { void __iomem *irq_base; }; +/* Receive interrupts below the threshold in a row before they are handled anyway. */ +#define DOCKCHANNEL_RX_SPURIOUS_MAX 16 + /* * FIFO register accesses. They are functions so that the KUnit test can model * the FIFO behind them. @@ -161,10 +169,41 @@ static irqreturn_t dockchannel_tx_irq(int irq, void *data) return IRQ_HANDLED; } +/* + * An interrupt with less data than the threshold that was programmed means + * that the FIFO does not hold that threshold: after a resume from disk the + * configuration registers hold what the boot loader or the boot kernel left, + * while the restored interrupt state says that receive is armed. Program it + * again and keep waiting (the interrupt stays enabled), instead of waking a + * client to read data that is not there. Only a kernel restored from an image + * is in that position: any other takes every receive interrupt as it comes. + */ +static bool dockchannel_rx_spurious(struct dockchannel *dockchannel) +{ + u32 thresh = READ_ONCE(dockchannel->rx_thresh); + + if (!pm_hibernate_is_restored()) + return false; + if (dockchannel_readl(dockchannel->data_base + DATA_RX_COUNT) >= thresh) + goto real; + dockchannel_writel(thresh, dockchannel->config_base + CONFIG_RX_THRESH); + if (dockchannel_readl(dockchannel->data_base + DATA_RX_COUNT) >= thresh) + goto real; + if (++dockchannel->rx_spurious <= DOCKCHANNEL_RX_SPURIOUS_MAX) + return true; + dev_warn_once(dockchannel->dev, + "receive interrupt keeps firing below its threshold (%u)\n", thresh); +real: + dockchannel->rx_spurious = 0; + return false; +} + static irqreturn_t dockchannel_rx_irq(int irq, void *data) { struct dockchannel *dockchannel = data; + if (dockchannel_rx_spurious(dockchannel)) + return IRQ_HANDLED; dockchannel_disable_irq_nosync(dockchannel, irq, &dockchannel->rx_irq_enabled); @@ -256,6 +295,7 @@ int dockchannel_recv(struct dockchannel *dockchannel, void *buf, size_t count) if (avail == 0) { size_t threshold = min((size_t)(dockchannel->fifo_size / 2), left); + WRITE_ONCE(dockchannel->rx_thresh, threshold); dockchannel_writel(threshold, dockchannel->config_base + CONFIG_RX_THRESH); reinit_completion(&dockchannel->rx_comp); dockchannel_enable_irq(dockchannel, dockchannel->rx_irq, @@ -362,6 +402,7 @@ int dockchannel_await(struct dockchannel *dockchannel, } dockchannel->data_available = callback; dockchannel->cookie = cookie; + WRITE_ONCE(dockchannel->rx_thresh, threshold); WRITE_ONCE(dockchannel->awaiting, true); if (!dockchannel->rx_irq_enabled) { dockchannel->rx_irq_enabled = true; @@ -550,6 +591,33 @@ static void dockchannel_teardown(struct device *dev, writel_relaxed(~0, dcc->irq_base + IRQ_FLAG); } +/* + * After a resume from disk the interrupt mask register holds what the boot + * kernel left in it (nothing, if it never loaded this driver), while the + * restored interrupt descriptors still describe the image's state. Write the + * image's state back before the channel clients restore; an unmasked receive + * interrupt that the hardware has masked would never fire. + */ +static int dockchannel_restore_noirq(struct device *dev) +{ + struct dockchannel_common *dcc = dev_get_drvdata(dev); + u32 mask = 0; + int hwirq; + + for (hwirq = 0; hwirq < DOCKCHANNEL_MAX_IRQ; hwirq++) { + unsigned int virq = irq_find_mapping(dcc->domain, hwirq); + + if (virq && !irqd_irq_masked(irq_get_irq_data(virq))) + mask |= BIT(hwirq); + } + writel_relaxed(mask, dcc->irq_base + IRQ_MASK); + return 0; +} + +static const struct dev_pm_ops dockchannel_pm_ops = { + .restore_noirq = pm_sleep_ptr(dockchannel_restore_noirq), +}; + static int dockchannel_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -609,6 +677,7 @@ static struct platform_driver dockchannel_driver = { .driver = { .name = "dockchannel", .of_match_table = dockchannel_of_match, + .pm = pm_sleep_ptr(&dockchannel_pm_ops), }, .probe = dockchannel_probe, .remove = dockchannel_remove, diff --git a/drivers/soc/apple/dt.rs b/drivers/soc/apple/dt.rs index adebb7c189b0f..0b94a630411b1 100644 --- a/drivers/soc/apple/dt.rs +++ b/drivers/soc/apple/dt.rs @@ -289,10 +289,54 @@ pub(crate) fn enable_sep_and_dart(window: &crate::profile::DartWindow) -> Result Ok(()) } +/// The firmware boot timeout the enclave needs, in milliseconds, from +/// `apple,sep-boot-timeout-ms`. The time the host waits for the enclave to +/// finish a (re-)boot is a property of the SoC and its firmware, not a number +/// baked into the driver; absent, [`DEFAULT_BOOT_TIMEOUT_MS`] is used. +pub(crate) const DEFAULT_BOOT_TIMEOUT_MS: u32 = 5000; + +pub(crate) fn boot_timeout_ms(sep: &DtNode) -> u32 { + let mut got: u32 = 0; + // SAFETY: `sep.0` is a live node and `got` is a valid out-parameter sized + // for the single cell the array reader is asked for. + let rc = unsafe { + bindings::of_property_read_variable_u32_array( + sep.0, + c"apple,sep-boot-timeout-ms".as_char_ptr(), + &mut got, + 1, + 1, + ) + }; + if rc >= 0 && got != 0 { + got + } else { + DEFAULT_BOOT_TIMEOUT_MS + } +} + pub(crate) fn registration_already_sent(sep: &DtNode) -> bool { sep.has_property(REGISTERED_PROP) } +/// Drop the marker of an earlier registration, once the enclave it went to is +/// known to be gone (a hibernation image restored over a boot that started the +/// enclave again): the marker came back with the image's device tree. +pub(crate) fn clear_registration_sent(sep: &DtNode) -> Result<()> { + // SAFETY: `sep.0` is a live node and the name is NUL-terminated; a NULL + // length pointer is accepted. + let prop = unsafe { + bindings::of_find_property(sep.0, REGISTERED_PROP.as_char_ptr(), core::ptr::null_mut()) + }; + if prop.is_null() { + return Ok(()); + } + // SAFETY: `prop` is a property of the live node `sep.0`, just looked up; + // the core keeps a removed property on the node's dead list, so it is not + // freed under a reader. + to_result(unsafe { bindings::of_remove_property(sep.0, prop) }) +} + pub(crate) fn mark_registration_sent(sep: &DtNode, iova: u64) -> Result<()> { let cells = [(iova >> 32) as u32, iova as u32]; with_changeset(|cs| { diff --git a/drivers/soc/apple/hibe.rs b/drivers/soc/apple/hibe.rs index f37be523f2051..bdf24d0e6673d 100644 --- a/drivers/soc/apple/hibe.rs +++ b/drivers/soc/apple/hibe.rs @@ -75,7 +75,6 @@ impl Drop for Prepared { /// Splits a prepare reply at its fixed boundaries. `None` unless `bytes` is /// exactly one reply long: the layout has no length field to trust. -#[allow(dead_code)] pub(crate) fn split_prepare_reply(bytes: &[u8]) -> Option { if bytes.len() != PREPARE_REPLY_LEN { return None; @@ -93,6 +92,49 @@ pub(crate) fn split_prepare_reply(bytes: &[u8]) -> Option { }) } + +/// The endpoint's two exchanges, named by the opcode the enclave reads from +/// `ty` (byte 2 of `msg0`). A reply carries its status in the same field; +/// `0` is success. The prepare opcode is `0`, the resume opcode `1`. +pub(crate) const HIBE_OP_PREPARE: u8 = 0x00; +pub(crate) const HIBE_OP_RESUME: u8 = 0x01; +pub(crate) const HIBE_STATUS_OK: u8 = 0x00; + +/// One page each way, as the layout word advertises: the prepare reply is +/// read from the inbound buffer, the resume authorisation written to the +/// outbound one. Same size as the enclave's other per-endpoint buffers. +pub(crate) const HIBE_OOL_INBOUND: usize = 0x4000; +pub(crate) const HIBE_OOL_OUTBOUND: usize = 0x4000; +static_assert!(PREPARE_REPLY_LEN <= HIBE_OOL_INBOUND && RESUME_AUTH_LEN <= HIBE_OOL_OUTBOUND); + +/// Builds a request to the endpoint: the endpoint in `ep`, the opcode in +/// `ty`, nothing inline. The payload, when there is one, travels in the +/// outbound buffer and the reply in the inbound one. +const fn hibe_request(op: u8) -> Message { + Message { + msg0: (EP_HIBE as u64) | ((op as u64) << MSG_TYPE_SHIFT), + msg1: 0, + } +} + +/// Prepare (op0): asked before the image is committed; the reply fills the +/// inbound buffer with one [`PREPARE_REPLY_LEN`] reply. Carries no payload. +pub(crate) fn prepare_request() -> Message { + hibe_request(HIBE_OP_PREPARE) +} + +/// Resume (op1): asked on the cold boot that resumes the image, after the +/// [`RESUME_AUTH_LEN`] authorisation has been written to the outbound buffer. +pub(crate) fn resume_request() -> Message { + hibe_request(HIBE_OP_RESUME) +} + +/// A reply on the endpoint is for us only when it names the endpoint and its +/// status field is clear. +pub(crate) fn hibe_reply_ok(f: &Fields) -> bool { + f.ep == EP_HIBE && f.ty == HIBE_STATUS_OK +} + impl SepData { /// Records the discovery messages of the endpoint. pub(crate) fn hibe_discovered(&self, f: &Fields) { @@ -121,11 +163,28 @@ impl SepData { layout ); } + // Size the held buffers to the advertised one-page-each-way layout + // so a future prepare/resume can register them without re-sizing. + // Registering and sending happen only when a hibernation image is + // actually prepared, in the op0/op1 writer. + if offer != diag::Offer::Absent && layout == HIBE_LAYOUT { + let _ = self.size_ool(&self.ool_hibe, (HIBE_OOL_INBOUND, HIBE_OOL_OUTBOUND)); + } diag::hibe(offer); } - /// Nothing is asked of the service, so nothing it says is expected. + /// A reply is taken only while an exchange is waiting; anything else on + /// the endpoint is counted as unhandled. pub(crate) fn on_hibe(&self, msg: Message) { + let mut rx = self.hibe_rx.lock(); + if let Some(generation) = rx.current() { + if rx.answer(generation, msg.msg0) { + drop(rx); + self.hibe_wq.notify_all(); + return; + } + } + drop(rx); if diag::unhandled() <= UNHANDLED_LOG_LIMIT { dev_info_ratelimited!( self.dev, @@ -134,6 +193,151 @@ impl SepData { ); } } + + /// Whether the enclave offers the endpoint as the driver knows it. + fn hibe_offered(&self) -> bool { + self.endpoint_present(EP_HIBE) + && self.hibe_named.load(Relaxed) + && self.hibe_layout.load(Relaxed) == HIBE_LAYOUT + } + + /// Registers the endpoint's buffers, once per enclave boot. + fn hibe_register(&self) -> Result<()> { + if self.sep_unusable.load(Relaxed) { + return Err(ENODEV); + } + if !self.hibe_offered() { + return Err(ENODEV); + } + let registered = self.ool_hibe.lock().as_ref().map(|p| p.registered); + if registered == Some(true) { + return Ok(()); + } + self.size_ool(&self.ool_hibe, (HIBE_OOL_INBOUND, HIBE_OOL_OUTBOUND)) + .and_then(|()| self.register_ool(&self.ool_hibe)) + } + + /// Sends one request and waits for its reply word. `Ok(None)` when the + /// enclave did not answer within the device-tree boot timeout. + fn hibe_exchange(&self, request: Message) -> Result> { + self.hibe_rx.lock().begin(); + if let Err(e) = self.send(request) { + self.hibe_rx.lock().end(); + return Err(e); + } + let timeout_ms = crate::dt::sep_node() + .map_or(crate::dt::DEFAULT_BOOT_TIMEOUT_MS, |n| crate::dt::boot_timeout_ms(&n)); + let mut remaining = time::msecs_to_jiffies(timeout_ms); + let mut guard = self.hibe_rx.lock(); + loop { + if self.shutting_down.load(Relaxed) { + guard.end(); + return Err(ENODEV); + } + if let Some(word) = guard.take() { + return Ok(Some(word)); + } + if remaining == 0 { + guard.end(); + return Ok(None); + } + match self.hibe_wq.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => remaining = jiffies, + CondVarTimeoutResult::Signal { .. } => remaining = 0, + CondVarTimeoutResult::Timeout => remaining = 0, + } + } + } + + /// Prepare (op0): the enclave's wrapped image key, boot word and resume + /// authorisation for an image about to be committed. + // The in-flow production entry a hibernation image writer calls; no such + // writer is upstream yet, so it has no in-tree caller. + #[allow(dead_code)] + pub(crate) fn hibe_prepare(&self) -> Result<(u64, Prepared)> { + // The enclave powers its hibernation service up only when it is told + // the hibernation sleep-type; a prepare asked outside that flow is + // not serviced and wedges the endpoint. Drive it in-flow only. + if !self.hibernating.load(Relaxed) { + dev_warn_ratelimited!(self.dev, "hibe: prepare refused outside a hibernation flow\n"); + return Err(EAGAIN); + } + self.hibe_register()?; + self.ool_repoison(&self.ool_hibe, 0, PREPARE_REPLY_LEN); + let word = self.hibe_exchange(prepare_request())?.ok_or(ETIMEDOUT)?; + let f = decode(&Message { msg0: word, msg1: 0 }); + if !hibe_reply_ok(&f) { + dev_warn_ratelimited!(self.dev, "hibe: prepare refused (msg0 {:#018x})\n", word); + return Err(EIO); + } + if !self.ool_await_written(&self.ool_hibe, 0, PREPARE_REPLY_LEN) { + dev_warn_ratelimited!(self.dev, "hibe: prepare reply not written (msg0 {:#018x})\n", word); + return Err(EIO); + } + let mut bytes = self.ool_read(&self.ool_hibe, 0, PREPARE_REPLY_LEN)?; + let prepared = split_prepare_reply(&bytes).ok_or(EIO); + bytes.iter_mut().for_each(|b| *b = 0); + self.ool_repoison(&self.ool_hibe, 0, PREPARE_REPLY_LEN); + Ok((word, prepared?)) + } + + /// Resume (op1): hands the enclave back the authorisation it gave at + /// prepare. Success is a clear status in the reply word. + #[allow(dead_code)] + pub(crate) fn hibe_resume(&self, auth: &[u8; RESUME_AUTH_LEN]) -> Result { + self.hibe_register()?; + self.ool_write(&self.ool_hibe, 0, auth)?; + let word = self.hibe_exchange(resume_request()); + let _ = self.ool_write(&self.ool_hibe, 0, &[0u8; RESUME_AUTH_LEN]); + let word = word?.ok_or(ETIMEDOUT)?; + if !hibe_reply_ok(&decode(&Message { msg0: word, msg1: 0 })) { + dev_warn_ratelimited!(self.dev, "hibe: resume refused (msg0 {:#018x})\n", word); + return Err(EIO); + } + Ok(word) + } + +} + +/// The single exchange the endpoint can have in flight; the answer is the +/// reply word, its payload stays in the buffers. +pub(crate) struct Exchange { + waiting: bool, + generation: u64, + reply: Option, +} + +impl Exchange { + pub(crate) fn new() -> Exchange { + Exchange { waiting: false, generation: 0, reply: None } + } + pub(crate) fn begin(&mut self) -> u64 { + self.generation = self.generation.wrapping_add(1); + self.waiting = true; + self.reply = None; + self.generation + } + pub(crate) fn current(&self) -> Option { + if self.waiting { Some(self.generation) } else { None } + } + pub(crate) fn answer(&mut self, generation: u64, word: u64) -> bool { + if !self.waiting || generation != self.generation || self.reply.is_some() { + return false; + } + self.reply = Some(word); + true + } + pub(crate) fn take(&mut self) -> Option { + let r = self.reply.take(); + if r.is_some() { + self.waiting = false; + } + r + } + pub(crate) fn end(&mut self) { + self.waiting = false; + self.reply = None; + } } #[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] @@ -190,6 +394,39 @@ mod tests { assert!(split_prepare_reply(&long).is_none()); } + #[test] + fn the_request_words_carry_the_endpoint_and_opcode() { + // Prepare: endpoint in ep, opcode 0 in ty, nothing else. + let p = decode(&prepare_request()); + assert_eq!(p.ep, EP_HIBE); + assert_eq!(p.ty, HIBE_OP_PREPARE); + assert_eq!(prepare_request().msg0, EP_HIBE as u64); + assert_eq!(prepare_request().msg1, 0); + + // Resume: endpoint in ep, opcode 1 in ty. The opcode sits in byte 2 + // (0x1_0000 before the endpoint byte is added). + let r = decode(&resume_request()); + assert_eq!(r.ep, EP_HIBE); + assert_eq!(r.ty, HIBE_OP_RESUME); + assert_eq!(resume_request().msg0, (EP_HIBE as u64) | (1u64 << MSG_TYPE_SHIFT)); + assert_eq!(resume_request().msg0 & !0xff, 0x1_0000); + } + + #[test] + fn a_reply_is_ours_only_when_named_and_clear() { + let ok = decode(&Message { msg0: EP_HIBE as u64, msg1: 0 }); + assert!(hibe_reply_ok(&ok)); + // A non-zero status is an error, not for us to accept. + let err = decode(&Message { + msg0: (EP_HIBE as u64) | (1u64 << MSG_TYPE_SHIFT), + msg1: 0, + }); + assert!(!hibe_reply_ok(&err)); + // A reply naming another endpoint is not ours. + let other = decode(&Message { msg0: EP_SKS as u64, msg1: 0 }); + assert!(!hibe_reply_ok(&other)); + } + #[test] fn prepared_material_is_wiped() { let mut r = [0u8; PREPARE_REPLY_LEN]; diff --git a/drivers/soc/apple/mcc.c b/drivers/soc/apple/mcc.c index 7504e98367f74..d99ad9ce19447 100644 --- a/drivers/soc/apple/mcc.c +++ b/drivers/soc/apple/mcc.c @@ -820,8 +820,50 @@ static int apple_mcc_resume_noirq(struct device *dev) return ret; } +#ifdef CONFIG_HIBERNATION +static int apple_mcc_restore_noirq(struct device *dev) +{ + struct apple_mcc *mcc = dev_get_drvdata(dev); + int ret; + + if (!pm_hibernate_restored_cold()) + return 0; + + apple_mcc_boot_dma_lock(); + if (mcc->dcs_lp) { + apple_mcc_t8103_enable_lp(mcc, false); + apple_mcc_boot_dma_unlock(); + return 0; + } + if (!mcc->enabled) { + apple_mcc_boot_dma_unlock(); + return 0; + } + if (mcc->ways_off && mcc->ways && + FIELD_GET(MCC_CACHE_WAYS_ENABLED, + readl(mcc->planes[0] + MCC_CACHE_WAYS)) != mcc->ways) + apple_mcc_set_ways(mcc, mcc->ways); + ret = mcc->retained ? apple_mcc_enable_t8132(mcc) : apple_mcc_enable(mcc); + mcc->enabled = !ret; + if (ret) + dev_warn(dev, "system level cache allocation stays off after hibernation: %d\n", + ret); + apple_mcc_boot_dma_unlock(); + return 0; +} +#endif + static const struct dev_pm_ops apple_mcc_pm_ops = { - NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_mcc_suspend_noirq, apple_mcc_resume_noirq) + .suspend_noirq = pm_sleep_ptr(apple_mcc_suspend_noirq), + .resume_noirq = pm_sleep_ptr(apple_mcc_resume_noirq), + .freeze_noirq = pm_sleep_ptr(apple_mcc_suspend_noirq), + .thaw_noirq = pm_sleep_ptr(apple_mcc_resume_noirq), + .poweroff_noirq = pm_sleep_ptr(apple_mcc_suspend_noirq), +#ifdef CONFIG_HIBERNATION + .restore_noirq = apple_mcc_restore_noirq, +#else + .restore_noirq = pm_sleep_ptr(apple_mcc_resume_noirq), +#endif }; static const struct of_device_id apple_mcc_of_match[] = { diff --git a/drivers/soc/apple/pm.rs b/drivers/soc/apple/pm.rs index d479bf866ae4c..0580dfb306e0f 100644 --- a/drivers/soc/apple/pm.rs +++ b/drivers/soc/apple/pm.rs @@ -15,6 +15,7 @@ use core::sync::atomic::{AtomicPtr, Ordering}; +use kernel::error::to_result; use kernel::prelude::*; use kernel::sync::Arc; use kernel::types::ForeignOwnable; @@ -30,6 +31,7 @@ extern "C" { fn sep_pm_register( dev: *mut c_void, event: unsafe extern "C" fn(bool), + hib: unsafe extern "C" fn(c_int), sleep: unsafe extern "C" fn() -> c_int, wake: unsafe extern "C" fn(), told: unsafe extern "C" fn() -> bool, @@ -50,6 +52,7 @@ extern "C" { mask: u64, ) -> c_int; fn sep_pm_commit_finish(dev: *mut c_void) -> c_int; + fn sep_pm_rebind(dev: *mut c_void) -> c_int; pub(crate) static sep_pm_ops: kernel::bindings::dev_pm_ops; } @@ -278,6 +281,35 @@ unsafe extern "C" fn pm_told() -> bool { with_sep(false, |sep| sep.sleep_gate() == SleepGate::Told) } +/// # Safety +/// Called by `pm_shim.c` from the PM notifier chain, in process context. +/// `phase`: 0 entering hibernation, 1 leaving it, 2 leaving it on a resume +/// from a saved image (the enclave was re-booted by the boot loader). +unsafe extern "C" fn pm_hibernation(phase: c_int) { + let ptr = SEP.load(Ordering::Acquire); + if ptr.is_null() { + return; + } + // SAFETY: as in `pm_event`. + let sep = unsafe { as ForeignOwnable>::borrow(ptr) }; + match phase { + 0 => sep.hibe_flow_enter(), + 2 => { + sep.hibe_flow_leave(); + SepData::resume_after_hibernation(sep.into()); + } + _ => sep.hibe_flow_leave(), + } +} + +/// Bind the driver to the enclave's device again, from a thread of its own: +/// the unbind waits for this driver's work, and the caller may be the PM +/// notifier. +pub(crate) fn rebind(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is a live device; the shim takes its own reference. + to_result(unsafe { sep_pm_rebind(dev.as_raw().cast()) }) +} + pub(crate) fn register(sep: Arc) -> Result<()> { let dev: *mut c_void = sep.dev.as_raw().cast(); let ptr = sep.into_foreign(); @@ -298,7 +330,7 @@ pub(crate) fn register(sep: Arc) -> Result<()> { // SAFETY: the shim stores the callback and registers a notifier block // that lives for the module's lifetime. - let rc = unsafe { sep_pm_register(dev, pm_event, pm_sleep, pm_wake, pm_told) }; + let rc = unsafe { sep_pm_register(dev, pm_event, pm_hibernation, pm_sleep, pm_wake, pm_told) }; if rc != 0 { let raw = SEP.swap(core::ptr::null_mut(), Ordering::AcqRel); if !raw.is_null() { diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index a7d965603a5ae..36b9cf06bad5b 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -14,6 +14,8 @@ #include #include #include +#include +#include #include #include #include @@ -55,6 +57,11 @@ MODULE_PARM_DESC(sleep_refuse_before_send, "Test only: refuse the next prepared deep sleep before sending SEP SLEEP"); static void (*sep_pm_event)(bool entering); +/* Distinguishes hibernation from an ordinary suspend, and a resume from a + * saved image from one that was written or aborted. phase: 0 entering + * hibernation, 1 leaving it, 2 leaving it on a resume from an image. + */ +static void (*sep_pm_hib)(int phase); static int (*sep_pm_sleep)(void); static void (*sep_pm_wake)(void); static bool (*sep_pm_told)(void); @@ -69,15 +76,34 @@ static int sep_pm_notify(struct notifier_block *nb, unsigned long action, if (!event) return NOTIFY_DONE; + void (*hib)(int phase) = READ_ONCE(sep_pm_hib); + switch (action) { - case PM_SUSPEND_PREPARE: case PM_HIBERNATION_PREPARE: + sep_diag_sleep(true); + event(true); + if (hib) + hib(0); + return NOTIFY_OK; + case PM_SUSPEND_PREPARE: case PM_RESTORE_PREPARE: sep_diag_sleep(true); event(true); return NOTIFY_OK; - case PM_POST_SUSPEND: case PM_POST_HIBERNATION: + /* + * After a cold hibernation restore the enclave was started again by the boot: + * let go of the old session before the requests held over the sleep are released + * to it. An in-place test_resume keeps the live enclave session intact. + */ + if (hib && pm_hibernate_restored_cold()) + hib(2); + event(false); + sep_diag_sleep(false); + if (hib && !pm_hibernate_restored_cold()) + hib(1); + return NOTIFY_OK; + case PM_POST_SUSPEND: case PM_POST_RESTORE: event(false); sep_diag_sleep(false); @@ -519,18 +545,54 @@ const struct dev_pm_ops sep_pm_ops = { .suspend_noirq = pm_sleep_ptr(sep_pm_suspend_noirq), }; -int sep_pm_register(void *ptr, void (*event)(bool entering), int (*sleep)(void), +static int sep_pm_rebind_fn(void *data) +{ + struct device *dev = data; + int ret; + + ret = device_reprobe(dev); + if (ret) + dev_err(dev, "hibernation: the driver did not bind again: %d\n", ret); + put_device(dev); + module_put_and_kthread_exit(0); +} + +/* + * Unbind the driver from the enclave's device and bind it again, on a thread of its own: the + * unbind waits for the driver's work and unregisters this notifier, so neither may run it. + */ +int sep_pm_rebind(void *ptr) +{ + struct device *dev = ptr; + struct task_struct *t; + + if (!try_module_get(THIS_MODULE)) + return -ENODEV; + get_device(dev); + t = kthread_run(sep_pm_rebind_fn, dev, "sep-rebind"); + if (IS_ERR(t)) { + put_device(dev); + module_put(THIS_MODULE); + return PTR_ERR(t); + } + return 0; +} + +int sep_pm_register(void *ptr, void (*event)(bool entering), + void (*hib)(int phase), int (*sleep)(void), void (*wake)(void), bool (*told)(void)) { int ret; WRITE_ONCE(sep_pm_event, event); + WRITE_ONCE(sep_pm_hib, hib); WRITE_ONCE(sep_pm_sleep, sleep); WRITE_ONCE(sep_pm_wake, wake); WRITE_ONCE(sep_pm_told, told); ret = register_pm_notifier(&sep_pm_nb); if (ret) { WRITE_ONCE(sep_pm_event, NULL); + WRITE_ONCE(sep_pm_hib, NULL); WRITE_ONCE(sep_pm_sleep, NULL); WRITE_ONCE(sep_pm_wake, NULL); WRITE_ONCE(sep_pm_told, NULL); @@ -545,6 +607,7 @@ void sep_pm_unregister(void) { unregister_pm_notifier(&sep_pm_nb); WRITE_ONCE(sep_pm_event, NULL); + WRITE_ONCE(sep_pm_hib, NULL); WRITE_ONCE(sep_pm_sleep, NULL); WRITE_ONCE(sep_pm_wake, NULL); WRITE_ONCE(sep_pm_told, NULL); diff --git a/drivers/soc/apple/pmp-export.c b/drivers/soc/apple/pmp-export.c index 87c5144392ebc..f2726de386d7e 100644 --- a/drivers/soc/apple/pmp-export.c +++ b/drivers/soc/apple/pmp-export.c @@ -3,9 +3,13 @@ #include #include #include +#include #include #include +#include +#include #include +#include #include #include #include @@ -22,27 +26,109 @@ static struct device *pmp_device; /* The firmware is stopped for a system sleep. */ static bool pmp_asleep; -int apple_pmp_register(struct device *dev, const void *data) +/* + * After a hibernation restore the boot loader has cold-restarted the PMP + * (image resident in PMS_SRAM, ASC CPU halted) and nothing replays the + * probe-time bring-up, so the firmware stays down (the display gate and + * cpufreq both wait on a PMP that never reports running). The module cannot be + * reloaded (the power-vote bridge is retained until reboot), so rebuild the + * firmware session in place. + * + * The restored kernel resumes inside hibernate() with in_suspend == 0 and + * sends PM_POST_HIBERNATION, not PM_POST_RESTORE (that one only reaches the + * boot kernel when it fails to restore). PM_POST_HIBERNATION also ends an + * aborted hibernation, where the firmware never stopped: restore() reads the + * ASC CPU run bit and leaves a running firmware alone. + */ +static struct device *pmp_dart(struct device *pmp) { - int ret = 0; + struct device_node *np; + struct platform_device *pdev; + + if (!pmp || !pmp->of_node) + return NULL; + np = of_parse_phandle(pmp->of_node, "iommus", 0); + if (!np) + return NULL; + pdev = of_find_device_by_node(np); + of_node_put(np); + return pdev ? &pdev->dev : NULL; +} +static int apple_pmp_pm_notify(struct notifier_block *nb, unsigned long action, + void *unused) +{ + if (action == PM_HIBERNATION_PREPARE) { + /* The boot loader relocks this DART; reimport at POST_HIBERNATION. */ + scoped_guard(mutex, &pmp_lock) { + if (pmp_device) { + struct device *dart = pmp_dart(pmp_device); + + if (dart) { + apple_dart_display_unpowered(dart); + put_device(dart); + } + } + } + return NOTIFY_DONE; + } + if (action != PM_POST_HIBERNATION && action != PM_POST_RESTORE) + return NOTIFY_DONE; + /* Serialize against unregister in Drop, as the power-command path does. */ guard(mutex)(&pmp_lock); - if (pmp_data) - ret = -EBUSY; - else { + if (pmp_data) { + struct device *dart = pmp_dart(pmp_device); + + if (dart) { + int ret = apple_dart_display_restore(dart); + + if (ret && pmp_device) + dev_warn(pmp_device, + "hibernation: DART restore failed: %d\n", ret); + put_device(dart); + } + if (!apple_pmp_restore(pmp_data) && pm_hibernate_restored_cold()) + apple_pmp_report_wake(pmp_device, false); + } + return NOTIFY_DONE; +} + +static struct notifier_block apple_pmp_pm_nb = { + .notifier_call = apple_pmp_pm_notify, + /* Ahead of every consumer's restore at priority 0 or below (ANE, DCP, GPU). */ + .priority = 10, +}; + +int apple_pmp_register(struct device *dev, const void *data) +{ + scoped_guard(mutex, &pmp_lock) { + if (pmp_data) + return -EBUSY; pmp_data = data; pmp_device = dev; } - return ret; + /* + * Outside pmp_lock: the notifier chain's lock is taken around the + * callback, which takes pmp_lock, so nesting them here would invert the + * order. The callback re-checks pmp_data under the lock. + */ + register_pm_notifier(&apple_pmp_pm_nb); + return 0; } void apple_pmp_unregister(const void *data) { - guard(mutex)(&pmp_lock); - if (pmp_data == data) { - pmp_data = NULL; - pmp_device = NULL; + bool was_registered = false; + + scoped_guard(mutex, &pmp_lock) { + if (pmp_data == data) { + pmp_data = NULL; + pmp_device = NULL; + was_registered = true; + } } + if (was_registered) + unregister_pm_notifier(&apple_pmp_pm_nb); } int apple_pmp_link_device(struct device *consumer) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index 637ee5bd572fa..7b9e07483f416 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -9,7 +9,7 @@ //! Copyright (C) The Asahi Linux Contributors use core::mem; -use core::sync::atomic::{fence, AtomicI32, AtomicPtr, Ordering}; +use core::sync::atomic::{fence, AtomicBool, AtomicI32, AtomicPtr, Ordering}; mod pmp_alloc; mod pmp_bootargs; @@ -202,6 +202,12 @@ struct PmpData { self_ack_start: bool, /// See [`PmpHwConfig::confirm_ioreg_len`]. confirm_ioreg_len: bool, + /// Whether `apple,pio-ranges` have already been mapped into this device's IOMMU domain. + pio_mapped: AtomicBool, + /// See [`PmpHwConfig::check_bootargs_uuid`], for the hibernation restore's + /// boot-argument patching (the boot loader cold-restarts the PMP on a + /// resume from disk and nothing else replays the probe-time bring-up). + check_bootargs_uuid: bool, /// See [`PmpHwConfig::register_ack_index`]. register_ack_index: bool, /// See [`PmpHwConfig::commit_cpu_down`]. @@ -243,6 +249,8 @@ impl PmpData { sram_backup_data, self_ack_start: cfg.self_ack_start, confirm_ioreg_len: cfg.confirm_ioreg_len, + pio_mapped: AtomicBool::new(false), + check_bootargs_uuid: cfg.check_bootargs_uuid, register_ack_index: cfg.register_ack_index, commit_cpu_down: cfg.commit_cpu_down, } @@ -250,6 +258,87 @@ impl PmpData { GFP_KERNEL, ) } + + /// Build the SRAM boot-argument patch list from the device-tree node, as + /// `probe()` does. Re-derivable on a hibernation restore (the DT is static). + fn build_patches(&self) -> Result> { + let node = self.dev.fwnode().ok_or(EIO)?; + let dvid = node + .property_read(c"apple,dram-vendor-id") + .required_by(&self.dev)?; + let bdid = node.property_read(c"apple,board-id").required_by(&self.dev)?; + let mut patches = KVec::with_capacity(9, GFP_KERNEL)?; + patches.push((from_fourcc(b"BDID"), bdid), GFP_KERNEL)?; + patches.push((from_fourcc(b"DVID"), dvid), GFP_KERNEL)?; + for (tag, prop) in OPTIONAL_BOOTARGS.iter() { + if let Some(v) = node.property_read::(prop).optional() { + patches.push((from_fourcc(tag), v), GFP_KERNEL)?; + } + } + if let Some(v) = node.property_read::(c"apple,pmc-pmgr").optional() { + patches.push((from_fourcc(b"PMCV"), v & 1), GFP_KERNEL)?; + patches.push((from_fourcc(b"PMCB"), (v >> 3) & 1), GFP_KERNEL)?; + } + Ok(patches) + } + + /// Re-run the PMP bring-up after a hibernation restore. The boot loader + /// cold-restarts the PMP (image resident in PMS_SRAM, ASC CPU halted), and + /// nothing replays the probe-time sequence, so the firmware stays down: + /// "no PMP within 20000ms" / cpufreq "PMP not running after 30s". The + /// retained `PmpData` Arc, both `DevresIoMem` mappings and the C power-vote + /// bridge all stay; only the volatile session and firmware are rebuilt. + /// The decision between a halted (reinit + boot) and a live (adopt) firmware + /// follows the ASC CPU run bit, as the NVMe ANS restore does. + fn restore(&self) -> Result<()> { + // Reached from a PM notifier, not the bound probe context, so access the + // retained mappings revocably (the device is still bound during resume). + // try_access() holds an RCU read-side lock while its guard lives: keep each + // guard to the MMIO accesses, never across a mutex, an allocation or the + // sleeping RTKit handshake. + let cpu_running = { + let asc = self.asc_mmio.try_access().ok_or(ENODEV)?; + asc.as_view().relaxed().read(ASC_CPU_CONTROL).cpu_run() != 0 + }; + dev_dbg!(self.dev, "PMP restore: ASC CPU_RUN={}\n", cpu_running as u32); + { + let mut guard = self.rtkit.lock(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + if rtk.is_crashed() { + dev_err!(self.dev, "PMP restore: session crashed, unrecoverable\n"); + return Err(EIO); + } + if cpu_running { + // The firmware never stopped (an aborted hibernation, or a + // restore failure in the boot kernel): nothing to rebuild. + dev_dbg!(self.dev, "PMP restore: firmware still running, left as is\n"); + return Ok(()); + } + // Halted firmware: detach the stale session so a fresh HELLO/EPMAP + // boot is accepted, as the NVMe ANS restore reinits its session. + rtk.reinit()?; + } + // The runtime handshake on the PMP endpoint fails against the state + // left from before the hibernation, so clear it first. + *self.state.lock() = PmpState::new()?; + *self.power_command.lock() = Command::Idle; + // Re-patch the SRAM boot args (the cold-restarted firmware re-reads them). + let patches = self.build_patches()?; + { + let pmp = self.pmp_mmio.try_access().ok_or(ENODEV)?; + self.patch_bootargs(&pmp.as_view(), &patches, self.check_bootargs_uuid)?; + } + // Release the ASC CPU and drive the wake/boot handshake, as probe does. + { + let asc = self.asc_mmio.try_access().ok_or(ENODEV)?; + asc.as_view() + .relaxed() + .update(ASC_CPU_CONTROL, |r| r.with_const_cpu_run::<1>()); + } + self.start()?; + dev_dbg!(self.dev, "PMP restore: firmware and endpoint back\n"); + Ok(()) + } fn start(&self) -> Result<()> { let mut guard = self.rtkit.lock(); let mut rtk = guard.as_mut().as_pin_mut().unwrap(); @@ -320,21 +409,25 @@ impl PmpData { let bound_dev = unsafe { self.dev.as_bound() }; let mut table = CoherentBox::<[IovaTableEntry]>::zeroed_slice(bound_dev, 170, GFP_KERNEL)?; + let already_mapped = self.pio_mapped.load(Ordering::Acquire); let domain = unsafe { bindings::iommu_get_domain_for_dev(self.dev.as_raw()) }; + let prot = (bindings::IOMMU_READ | bindings::IOMMU_WRITE | bindings::IOMMU_MMIO) as i32; for i in 0..n_entries { let host_addr = ranges[i * 2]; let size = ranges[i * 2 + 1]; - unsafe { - let err = bindings::iommu_map( - domain, - pio_base as usize, - host_addr, - size as usize, - (bindings::IOMMU_READ | bindings::IOMMU_WRITE | bindings::IOMMU_MMIO) as i32, - bindings::GFP_KERNEL, - ); - if err != 0 { - return Err(Error::from_errno(err)); + if !already_mapped { + unsafe { + let err = bindings::iommu_map( + domain, + pio_base as usize, + host_addr, + size as usize, + prot, + bindings::GFP_KERNEL, + ); + if err != 0 { + return Err(Error::from_errno(err)); + } } } table[i] = IovaTableEntry { @@ -344,6 +437,9 @@ impl PmpData { }; pio_base += PIO_GRANULARITY; } + if !already_mapped { + self.pio_mapped.store(true, Ordering::Release); + } let table: Coherent<[IovaTableEntry]> = table.into(); let msg = (OPC_GET_IOVA_TABLE | OPC_ACK_MASK) << OPC_SHIFT | table.dma_address(); state.iova_table = Some(table); @@ -932,6 +1028,28 @@ pub unsafe extern "C" fn apple_pmp_wake(data: *const core::ffi::c_void) -> i32 { } } +/// Rebuild the PMP firmware session after a resume from disk (PM_POST_HIBERNATION). +/// The C power-vote bridge calls this with the retained `PmpData` pointer; the +/// bridge, the Arc and the MMIO mappings all stay — only the firmware session is +/// rebuilt. Returns 0 on success or a negative errno. A failure is logged and the +/// PMP stays down (cpufreq keeps its fallback clamp) rather than aborting resume. +/// +/// # Safety +/// `data` must be the live `PmpData` pointer the bridge was registered with, and +/// the caller must serialize against unregister in `Drop`. +#[export] +pub unsafe extern "C" fn apple_pmp_restore(data: *const core::ffi::c_void) -> i32 { + // SAFETY: the C bridge holds the retained foreign reference until reboot. + let data = unsafe { &*data.cast::() }; + match data.restore() { + Ok(()) => 0, + Err(e) => { + dev_err!(data.dev, "PMP restore failed: {:?}\n", e); + e.to_errno() + } + } +} + struct NoBuffer; impl rtkit::Buffer for NoBuffer { fn iova(&self) -> Result { diff --git a/drivers/soc/apple/proto.rs b/drivers/soc/apple/proto.rs index 1bdea86a4c51e..5b764ad4f840d 100644 --- a/drivers/soc/apple/proto.rs +++ b/drivers/soc/apple/proto.rs @@ -201,6 +201,23 @@ pub(crate) fn op_sleep() -> ControlOp { } } +/// Asks the enclave to save its state for a resume from a saved image and +/// gate its own power domain. The sleep-type (`param`) is the only difference +/// from [`op_sleep`]: a plain sleep keeps the enclave resident; a hibernation +/// tells it the host is about to write an image it will resume from a cold +/// boot, after which the enclave is re-booted rather than woken. +pub(crate) fn op_hibernate() -> ControlOp { + ControlOp { + ty: 0x0c, + param: 0x03, + data: 0, + expect_reply: true, + timeout_ms: SLEEP_TIMEOUT_MS, + reserved_tag: false, + name: c"HIBERNATE", + } +} + pub(crate) fn encode_control(op: &ControlOp, tag: u8) -> Message { Message { msg0: u64::from(EP_CONTROL) @@ -329,6 +346,15 @@ mod tests { assert_eq!(msg.msg1, 0); } + #[test] + fn hibernate_request_differs_only_in_the_sleep_type() { + // Same endpoint, tag and opcode as a plain sleep; only the sleep-type + // (param) rises from 2 to 3. + let msg = encode_control(&op_hibernate(), TAG_SLEEP); + assert_eq!(msg.msg0, 0x0000_0000_030c_0800); + assert_eq!(msg.msg1, 0); + } + #[test] fn its_answer_matches_the_trace() { let reply = Message { diff --git a/drivers/soc/apple/rtkit-helper.c b/drivers/soc/apple/rtkit-helper.c index 0466dc2e2463f..a11731cb74470 100644 --- a/drivers/soc/apple/rtkit-helper.c +++ b/drivers/soc/apple/rtkit-helper.c @@ -57,6 +57,12 @@ struct apple_rtkit_helper { bool idle_pending; /* Ends a sleep whose .prepare failed, which gets no .complete. */ struct notifier_block pm_nb; + /* Boot kernel of a resume from disk: RX held for the image. */ + bool rx_held; + /* This restore took over the session the boot kernel started. */ + bool readopted; + /* This restore found the co-processor of our own session halted. */ + bool halted_underneath; void __iomem *asc_base; @@ -72,6 +78,22 @@ bool apple_rtkit_helper_preserves_input(struct device *dev) } EXPORT_SYMBOL_GPL(apple_rtkit_helper_preserves_input); +bool apple_rtkit_helper_readopted(struct device *dev) +{ + struct apple_rtkit_helper *helper = dev_get_drvdata(dev); + + return helper && helper->readopted; +} +EXPORT_SYMBOL_GPL(apple_rtkit_helper_readopted); + +bool apple_rtkit_helper_halted_underneath(struct device *dev) +{ + struct apple_rtkit_helper *helper = dev_get_drvdata(dev); + + return helper && helper->halted_underneath; +} +EXPORT_SYMBOL_GPL(apple_rtkit_helper_halted_underneath); + static int apple_rtkit_helper_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) { struct apple_rtkit_helper *helper = cookie; @@ -128,9 +150,19 @@ static const struct apple_rtkit_ops apple_rtkit_helper_ops = { .shmem_destroy = apple_rtkit_helper_shmem_destroy, }; -static void apple_rtkit_helper_release(void *rtk) +/* Whether the coprocessor's CPU runs: halted, nothing answers on its mailbox. */ +static bool apple_rtkit_helper_cpu_running(struct apple_rtkit_helper *helper) { - apple_rtkit_free_retaining_buffers(rtk); + return readl_relaxed(helper->asc_base + APPLE_ASC_CPU_CONTROL) & + APPLE_ASC_CPU_CONTROL_RUN; +} + +static void apple_rtkit_helper_release(void *data) +{ + struct apple_rtkit_helper *helper = data; + + /* The current session object: a hibernation restore may have replaced it. */ + apple_rtkit_free_retaining_buffers(helper->rtk); } static void apple_rtkit_helper_release_slp_ddr(void *unused) @@ -161,8 +193,7 @@ static int apple_rtkit_helper_live(struct apple_rtkit_helper *helper) return -EINVAL; } - if (!(readl_relaxed(helper->asc_base + APPLE_ASC_CPU_CONTROL) & - APPLE_ASC_CPU_CONTROL_RUN)) { + if (!apple_rtkit_helper_cpu_running(helper)) { dev_warn(helper->dev, "RTKit handoff without a running CPU\n"); return -ENODEV; } @@ -286,6 +317,13 @@ static int apple_rtkit_helper_inherit_buffers( return count; } +/* + * Whether an adopted session refuses buffers its inventory does not list. With + * an inventory, and on T8132 and the J614s without one, no new allocation is + * safe: the firmware still uses what it negotiated with its first host. + * Producers that predate the inventory (T8140) keep mapping IOVAs inside the + * SRAM region. Probe and the restore after a hibernation adopt by this rule. + */ static int apple_rtkit_helper_pm_register(struct apple_rtkit_helper *helper); static int apple_rtkit_helper_probe(struct platform_device *pdev) @@ -372,11 +410,7 @@ static int apple_rtkit_helper_probe(struct platform_device *pdev) } if (live) { - /* - * Set before RX starts: with an inventory, or on T8132, no new - * buffer allocation is safe here. Producers that predate the - * inventory (T8140) keep mapping IOVAs inside the SRAM region. - */ + /* Set before RX starts, which may bring a buffer request. */ helper->adopted = true; helper->strict_buffers = count > 0 || apple_rtkit_helper_retained_mtp(dev->of_node); @@ -389,7 +423,7 @@ static int apple_rtkit_helper_probe(struct platform_device *pdev) apple_rtkit_set_oslog_echo(helper->rtk, true); ret = devm_add_action_or_reset(dev, apple_rtkit_helper_release, - helper->rtk); + helper); if (ret) return ret; ret = apple_rtkit_helper_pm_register(helper); @@ -440,6 +474,17 @@ static void apple_rtkit_helper_remove(struct platform_device *pdev) if (helper->adopted || helper->preserved) return; + /* + * After a resume from disk the boot loader left the coprocessor halted + * with fresh firmware loaded, while the restored host session still + * believes it runs: nothing would answer the quiesce. Drop the session + * without a handshake so that the next probe starts the CPU again. + */ + if (!apple_rtkit_helper_cpu_running(helper)) { + dev_dbg(&pdev->dev, "co-processor halted underneath (resume from disk): removed without quiesce\n"); + return; + } + if (apple_rtkit_is_running(helper->rtk)) apple_rtkit_quiesce(helper->rtk); @@ -630,12 +675,196 @@ static int __maybe_unused apple_rtkit_helper_resume(struct device *dev) return 0; } -static int __maybe_unused apple_rtkit_helper_freeze(struct device *dev) +/* + * What the boot kernel of a resume from disk leaves for the restored kernel + * about a session it started itself: the shared buffers the firmware holds. + */ +struct apple_rtkit_helper_hib { + u32 count; + u32 reserved; + struct apple_rtkit_buffer_desc buf[APPLE_RTKIT_BUF_COUNT]; +}; + +static_assert(sizeof(struct apple_rtkit_helper_hib) <= APPLE_RTKIT_HIB_HANDOFF_MAX); + +static void apple_rtkit_helper_hib_tag(struct device *dev, char *tag, size_t len) +{ + snprintf(tag, len, "rtkh:%s", dev_name(dev)); +} + +/* + * Hibernation of an adopted session. The image is written while the firmware + * keeps running; its buffers live in SRAM or in no-map reserved RAM, so they + * are not part of the image and the host side has nothing to quiesce. The + * restore re-adopts the instance the boot loader started for the resume boot, + * exactly as probe adopted the first one. + * + * A session this driver started itself is left running as well: the MTP + * firmware does not come back from QUIESCED (it does not answer the endpoint + * discovery of the next start). When this is the boot kernel of a resume from + * disk (it started MTP so that the disk passphrase can be typed), it hands + * the running firmware to the image: mailbox RX is held, so that what the + * firmware sends now stays queued for the restored kernel, the messages + * already received are handled, and the shared buffers are described for the + * restored kernel, which can only take the session over if its own buffers + * sit at the same IOVAs (the firmware keeps writing to the IOVAs it was + * given, and after the restore the DART translates them through the image's + * page tables). + */ +static int apple_rtkit_helper_freeze(struct device *dev) +{ + struct apple_rtkit_helper *helper = dev_get_drvdata(dev); + struct apple_rtkit_helper_hib rec = {}; + char tag[32]; + int n, ret; + + helper->readopted = false; + helper->halted_underneath = false; + if (helper->adopted || !apple_rtkit_hib_restoring()) + return 0; + if (!apple_rtkit_helper_cpu_running(helper) || + !apple_rtkit_is_running(helper->rtk)) + return 0; + + apple_rtkit_hold_rx(helper->rtk); + apple_rtkit_flush_rx(helper->rtk); + helper->rx_held = true; + + n = apple_rtkit_describe_buffers(helper->rtk, rec.buf, ARRAY_SIZE(rec.buf)); + if (n < 0) { + dev_warn(dev, "resume from disk: cannot describe the RTKit buffers: %d\n", n); + return 0; + } + rec.count = n; + apple_rtkit_helper_hib_tag(dev, tag, sizeof(tag)); + ret = apple_rtkit_hib_handoff_put(tag, &rec, sizeof(rec)); + if (ret) + dev_warn(dev, "resume from disk: no hand-off record for the image: %d\n", ret); + else + dev_dbg(dev, "resume from disk: RTKit session left running for the image (%d buffers)\n", + n); + return 0; +} + +static int apple_rtkit_helper_thaw(struct device *dev) +{ + struct apple_rtkit_helper *helper = dev_get_drvdata(dev); + char tag[32]; + + /* The jump into the image failed: this kernel keeps the session. */ + if (helper->rx_held) { + helper->rx_held = false; + apple_rtkit_helper_hib_tag(dev, tag, sizeof(tag)); + apple_rtkit_hib_handoff_drop(tag); + apple_rtkit_resume_rx(helper->rtk); + } + return 0; +} + +/* + * A session this driver started itself, after a resume from disk. Taken over + * in place when the boot kernel left it running and its buffers match ours; + * otherwise left as before (stale until the driver is reloaded). + */ +static int apple_rtkit_helper_restore_own(struct apple_rtkit_helper *helper) +{ + struct device *dev = helper->dev; + struct apple_rtkit_helper_hib rec = {}, own = {}; + char tag[32]; + int i, n, ret; + + apple_rtkit_helper_hib_tag(dev, tag, sizeof(tag)); + ret = apple_rtkit_hib_handoff_take(tag, &rec, sizeof(rec)); + if (ret < 0) { + if (apple_rtkit_helper_cpu_running(helper)) { + dev_warn(dev, "resume from disk: co-processor runs without a hand-off from the boot kernel (%d): not taken over\n", + ret); + } else { + helper->halted_underneath = true; + dev_dbg(dev, "resume from disk: self-started RTKit session left for a reload\n"); + } + return 0; + } + if (!apple_rtkit_helper_cpu_running(helper)) { + helper->halted_underneath = true; + dev_warn(dev, "resume from disk: hand-off present but the co-processor is halted: not taken over\n"); + return 0; + } + + n = apple_rtkit_describe_buffers(helper->rtk, own.buf, ARRAY_SIZE(own.buf)); + own.count = n < 0 ? 0 : n; + if (n < 0 || rec.count > ARRAY_SIZE(rec.buf) || own.count != rec.count || + memcmp(own.buf, rec.buf, rec.count * sizeof(rec.buf[0]))) { + dev_err(dev, "resume from disk: RTKit buffers of the boot kernel differ from the image's: not taken over\n"); + for (i = 0; i < min_t(u32, rec.count, ARRAY_SIZE(rec.buf)); i++) + dev_err(dev, " boot kind %u iova %#llx size %#llx\n", + rec.buf[i].kind, rec.buf[i].iova, rec.buf[i].size); + for (i = 0; i < own.count; i++) + dev_err(dev, " image kind %u iova %#llx size %#llx\n", + own.buf[i].kind, own.buf[i].iova, own.buf[i].size); + return 0; + } + + ret = apple_rtkit_readopt(helper->rtk); + if (ret) { + dev_err(dev, "resume from disk: RTKit session not taken over: %d\n", ret); + return 0; + } + helper->readopted = true; + dev_dbg(dev, "resume from disk: took over the RTKit session the boot kernel started (%d buffers at the same IOVAs)\n", + n); + return 0; +} + +static int apple_rtkit_helper_restore(struct device *dev) { struct apple_rtkit_helper *helper = dev_get_drvdata(dev); + struct apple_rtkit_inherited_buffer buffers[APPLE_RTKIT_HELPER_MAX_BUFFERS] = {}; + struct apple_rtkit *old, *rtk; + int count, live; - /* A hibernation image cannot recreate the firmware's live DMA ownership. */ - return helper->adopted ? -EBUSY : 0; + if (!helper->adopted) + return apple_rtkit_helper_restore_own(helper); + + /* + * The restored tree still carries the handoff the image's boot stage + * wrote. The resume boot's loader hands the same firmware over at the + * same SRAM and no-map addresses (the inventory comes from the firmware + * carveouts, not from the kernel allocator), so re-read it and check + * that a CPU is running behind it. + */ + live = apple_rtkit_helper_live(helper); + if (live < 0) { + dev_err(dev, "hibernation restore: invalid live RTKit handoff: %d\n", live); + return live; + } + if (!live) { + dev_err(dev, "hibernation restore: no live RTKit session to re-adopt\n"); + return -ENODEV; + } + count = apple_rtkit_helper_inherit_buffers(helper, buffers); + if (count < 0) { + dev_err(dev, "hibernation restore: invalid inherited RTKit buffers: %d\n", count); + return count; + } + + /* As at probe, before the new session's RX starts. */ + helper->strict_buffers = count > 0 || + apple_rtkit_helper_retained_mtp(dev->of_node); + rtk = apple_rtkit_init_adopted_with_buffers(dev, helper, NULL, 0, + &apple_rtkit_helper_ops, buffers, count); + if (IS_ERR(rtk)) { + dev_err(dev, "hibernation restore: failed to re-adopt RTKit: %pe\n", rtk); + return PTR_ERR(rtk); + } + + /* The old object described an instance that no longer exists. */ + old = helper->rtk; + helper->rtk = rtk; + apple_rtkit_free_retaining_buffers(old); + dev_dbg(dev, "re-adopted the running RTKit session after hibernation (%d retained buffers)\n", + count); + return 0; } static const struct dev_pm_ops apple_rtkit_helper_pm_ops = { @@ -646,6 +875,8 @@ static const struct dev_pm_ops apple_rtkit_helper_pm_ops = { .resume = pm_sleep_ptr(apple_rtkit_helper_resume), .freeze = pm_sleep_ptr(apple_rtkit_helper_freeze), .poweroff = pm_sleep_ptr(apple_rtkit_helper_freeze), + .thaw = pm_sleep_ptr(apple_rtkit_helper_thaw), + .restore = pm_sleep_ptr(apple_rtkit_helper_restore), }; static const struct of_device_id apple_rtkit_helper_of_match[] = { diff --git a/drivers/soc/apple/rtkit-hib-handoff.c b/drivers/soc/apple/rtkit-hib-handoff.c new file mode 100644 index 0000000000000..0700ab8488284 --- /dev/null +++ b/drivers/soc/apple/rtkit-hib-handoff.c @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple RTKit: hand a running co-processor session from the kernel that loads + * a hibernation image (the boot kernel) to the kernel restored from it. + * + * A co-processor that the boot kernel started keeps running across the jump + * into the image, but everything the boot kernel knew about it is overwritten + * by the image. The few facts the restored kernel needs to take the session + * over (where the firmware's shared buffers are, how far a receive ring got) + * are left in __nosavedata: the image never saves those pages, so after the + * restore they still hold what the boot kernel wrote, provided both kernels + * are the same build loaded at the same physical address. Each record carries + * its own physical address and a checksum, so a record from a kernel loaded + * elsewhere, or no record at all, reads as absent. + * + * The storage must be in the kernel image, so this only works with RTKit + * built in. A taken record is cleared. + */ + +#include +#include +#include +#include +#include + +#if IS_BUILTIN(CONFIG_APPLE_RTKIT) && IS_ENABLED(CONFIG_HIBERNATION) + +#define HANDOFF_MAGIC 0x52544b48 /* "RTKH" */ +#define HANDOFF_VERSION 1 +#define HANDOFF_SLOTS 4 +#define HANDOFF_TAG 32 + +struct apple_rtkit_hib_slot { + u32 magic; + u32 version; + u64 self_phys; + char tag[HANDOFF_TAG]; + u32 len; + u32 sum; + u8 data[APPLE_RTKIT_HIB_HANDOFF_MAX]; +}; + +static struct apple_rtkit_hib_slot handoff[HANDOFF_SLOTS] __nosavedata; +static DEFINE_SPINLOCK(handoff_lock); + +/* FNV-1a over everything but the checksum itself. */ +static u32 handoff_sum(const struct apple_rtkit_hib_slot *s) +{ + const u8 *p = (const u8 *)s; + size_t off = offsetof(struct apple_rtkit_hib_slot, sum); + u32 h = 0x811c9dc5; + size_t i; + + for (i = 0; i < sizeof(*s); i++) { + if (i >= off && i < off + sizeof(s->sum)) + continue; + h ^= p[i]; + h *= 0x01000193; + } + return h; +} + +static bool handoff_valid(const struct apple_rtkit_hib_slot *s) +{ + return s->magic == HANDOFF_MAGIC && s->version == HANDOFF_VERSION && + s->self_phys == __pa_symbol(s) && + s->len <= APPLE_RTKIT_HIB_HANDOFF_MAX && + s->tag[HANDOFF_TAG - 1] == '\0' && s->sum == handoff_sum(s); +} + +static struct apple_rtkit_hib_slot *handoff_find(const char *tag) +{ + int i; + + for (i = 0; i < HANDOFF_SLOTS; i++) + if (handoff_valid(&handoff[i]) && !strcmp(handoff[i].tag, tag)) + return &handoff[i]; + return NULL; +} + +bool apple_rtkit_hib_restoring(void) +{ + return pm_hibernate_is_loading(); +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_restoring); + +int apple_rtkit_hib_handoff_put(const char *tag, const void *data, size_t len) +{ + struct apple_rtkit_hib_slot *s; + unsigned long flags; + int i, ret = 0; + + if (len > APPLE_RTKIT_HIB_HANDOFF_MAX || strlen(tag) >= HANDOFF_TAG) + return -EINVAL; + + spin_lock_irqsave(&handoff_lock, flags); + s = handoff_find(tag); + for (i = 0; !s && i < HANDOFF_SLOTS; i++) + if (!handoff_valid(&handoff[i])) + s = &handoff[i]; + if (s) { + memset(s, 0, sizeof(*s)); + s->magic = HANDOFF_MAGIC; + s->version = HANDOFF_VERSION; + s->self_phys = __pa_symbol(s); + strscpy(s->tag, tag, sizeof(s->tag)); + s->len = len; + memcpy(s->data, data, len); + s->sum = handoff_sum(s); + } else { + ret = -ENOSPC; + } + spin_unlock_irqrestore(&handoff_lock, flags); + return ret; +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_handoff_put); + +int apple_rtkit_hib_handoff_take(const char *tag, void *data, size_t len) +{ + struct apple_rtkit_hib_slot *s; + unsigned long flags; + int ret; + + spin_lock_irqsave(&handoff_lock, flags); + s = handoff_find(tag); + if (!s) { + ret = -ENOENT; + } else if (s->len != len) { + ret = -EINVAL; + } else { + memcpy(data, s->data, len); + ret = len; + } + if (s) + memset(s, 0, sizeof(*s)); + spin_unlock_irqrestore(&handoff_lock, flags); + return ret; +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_handoff_take); + +void apple_rtkit_hib_handoff_drop(const char *tag) +{ + struct apple_rtkit_hib_slot *s; + unsigned long flags; + + spin_lock_irqsave(&handoff_lock, flags); + s = handoff_find(tag); + if (s) + memset(s, 0, sizeof(*s)); + spin_unlock_irqrestore(&handoff_lock, flags); +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_handoff_drop); + +#else + +bool apple_rtkit_hib_restoring(void) +{ + return false; +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_restoring); + +int apple_rtkit_hib_handoff_put(const char *tag, const void *data, size_t len) +{ + return -EOPNOTSUPP; +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_handoff_put); + +int apple_rtkit_hib_handoff_take(const char *tag, void *data, size_t len) +{ + return -ENOENT; +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_handoff_take); + +void apple_rtkit_hib_handoff_drop(const char *tag) +{ +} +EXPORT_SYMBOL_GPL(apple_rtkit_hib_handoff_drop); + +#endif diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index 5db404c7b370d..6e03fb3ae19f9 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2203,6 +2203,62 @@ bool apple_rtkit_v27_rx_drained(struct apple_rtkit *rtk) kfifo_is_empty(&rtk->m5_saved.deferred) && !READ_ONCE(rtk->oslog_owed); } EXPORT_SYMBOL_GPL(apple_rtkit_v27_rx_drained); +int apple_rtkit_describe_buffers(struct apple_rtkit *rtk, + struct apple_rtkit_buffer_desc *desc, + unsigned int max) +{ + const struct apple_rtkit_shmem *bufs[APPLE_RTKIT_BUF_COUNT] = { + [APPLE_RTKIT_BUF_IOREPORT] = &rtk->ioreport_buffer, + [APPLE_RTKIT_BUF_COREANALYTICS] = &rtk->coreanalytics_buffer, + [APPLE_RTKIT_BUF_CRASHLOG] = &rtk->crashlog_buffer, + [APPLE_RTKIT_BUF_OSLOG] = &rtk->oslog_buffer, + [APPLE_RTKIT_BUF_KDEBUG0] = &rtk->kdebug_buffer0, + [APPLE_RTKIT_BUF_KDEBUG1] = &rtk->kdebug_buffer1, + [APPLE_RTKIT_BUF_PMP_AUX] = &rtk->pmp_aux_buffer, + [APPLE_RTKIT_BUF_SYSLOG] = &rtk->syslog_buffer, + }; + unsigned int i, n = 0; + + for (i = 0; i < APPLE_RTKIT_BUF_COUNT; i++) { + if (!bufs[i]->size) + continue; + if (n == max) + return -ENOSPC; + desc[n].kind = i; + desc[n].is_mapped = bufs[i]->is_mapped; + desc[n].iova = bufs[i]->iova; + desc[n].size = bufs[i]->size; + n++; + } + return n; +} +EXPORT_SYMBOL_GPL(apple_rtkit_describe_buffers); + +int apple_rtkit_readopt(struct apple_rtkit *rtk) +{ + /* + * Only a session that was running when it was left can be taken over: + * its endpoint map, protocol version, syslog geometry and buffers then + * describe the same firmware build and the same IOVAs as the instance + * that runs now (the caller compared the buffers). + */ + if (READ_ONCE(rtk->shutting_down) || !apple_rtkit_is_running(rtk)) + return -EINVAL; + + apple_mbox_hold_rx(rtk->mbox); + /* Acknowledgments still queued belong to the instance that is gone. */ + cancel_work_sync(&rtk->sync_ack_work); + flush_workqueue(rtk->wq); + kfifo_reset(&rtk->sync_ack_fifo); + + reinit_completion(&rtk->iop_pwr_ack_completion); + reinit_completion(&rtk->ap_pwr_ack_completion); + + /* Messages the other kernel left queued in the mailbox arrive now. */ + apple_mbox_release_rx(rtk->mbox); + return 0; +} +EXPORT_SYMBOL_GPL(apple_rtkit_readopt); /* * A co-processor adopted from the bootloader has already sent its endpoint @@ -2942,6 +2998,8 @@ int apple_rtkit_reinit(struct apple_rtkit *rtk) apple_rtkit_reset_session(rtk, false); ret = apple_mbox_start(rtk->mbox); + if (!ret) + ret = apple_mbox_restore(rtk->mbox); if (ret) { apple_rtkit_detach_rx(rtk); flush_workqueue(rtk->wq); @@ -2956,6 +3014,8 @@ int apple_rtkit_reinit_retaining_buffers(struct apple_rtkit *rtk) apple_rtkit_reset_session(rtk, true); ret = apple_mbox_start(rtk->mbox); + if (!ret) + ret = apple_mbox_restore(rtk->mbox); if (ret) { apple_rtkit_detach_rx(rtk); flush_workqueue(rtk->wq); @@ -2987,8 +3047,9 @@ static int apple_rtkit_set_ap_power_state(struct apple_rtkit *rtk, return 0; } -static int apple_rtkit_set_iop_power_state(struct apple_rtkit *rtk, - unsigned int state) +/* Ask the IOP for a power state and wait for its acknowledgment; the caller judges the state. */ +static int apple_rtkit_send_iop_power_state(struct apple_rtkit *rtk, + unsigned int state) { u64 msg; int ret; @@ -3001,7 +3062,15 @@ static int apple_rtkit_set_iop_power_state(struct apple_rtkit *rtk, if (ret) return ret; - ret = apple_rtkit_wait(rtk, &rtk->iop_pwr_ack_completion); + return apple_rtkit_wait(rtk, &rtk->iop_pwr_ack_completion); +} + +static int apple_rtkit_set_iop_power_state(struct apple_rtkit *rtk, + unsigned int state) +{ + int ret; + + ret = apple_rtkit_send_iop_power_state(rtk, state); if (ret) return ret; @@ -3160,11 +3229,16 @@ int apple_rtkit_idle_with(struct apple_rtkit *rtk, void (*after_ap)(void *data), if (after_ap) after_ap(data); - ret = apple_rtkit_set_iop_power_state(rtk, APPLE_RTKIT_PWR_STATE_IDLE); + ret = apple_rtkit_send_iop_power_state(rtk, APPLE_RTKIT_PWR_STATE_IDLE); if (ret) { dev_err(rtk->dev, "RTKit: IOP idle not acknowledged: %d\n", ret); return ret; } + if (rtk->iop_power_state != APPLE_RTKIT_PWR_STATE_IDLE) { + dev_dbg(rtk->dev, "RTKit: IOP acknowledged %#x instead of idle\n", + rtk->iop_power_state); + return APPLE_RTKIT_IDLE_RETAINED; + } rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_IDLE; rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_IDLE; @@ -3699,6 +3773,40 @@ int apple_rtkit_sleep_idle_polled(struct apple_rtkit *rtk, void __iomem *cpu_con } EXPORT_SYMBOL_GPL(apple_rtkit_sleep_idle_polled); +/* + * For a co-processor that stays up: its client may still be owed a reply or an event on + * its own endpoints. Those go the usual way, to recv_message_early and, if it leaves + * them, to the receive work, which runs again after the wake. + */ +static void apple_rtkit_ap_polled_rx(struct apple_mbox *mbox, struct apple_mbox_msg msg, + void *cookie) +{ + if (msg.msg1 >= APPLE_RTKIT_APP_ENDPOINT_START) + apple_rtkit_rx(mbox, msg, cookie); + else + apple_rtkit_polled_rx(mbox, msg, cookie); +} + +int apple_rtkit_ap_idle_polled(struct apple_rtkit *rtk, unsigned int *us) +{ + unsigned long flags; + int ret; + + apple_rtkit_polled_begin(rtk); + + /* The client's own endpoints keep their usual path while the idle is polled for. */ + spin_lock_irqsave(&rtk->mbox->rx_lock, flags); + rtk->mbox->rx = apple_rtkit_ap_polled_rx; + spin_unlock_irqrestore(&rtk->mbox->rx_lock, flags); + + ret = apple_rtkit_polled_ap_idle(rtk, us); + + apple_rtkit_polled_end(rtk); + + return ret; +} +EXPORT_SYMBOL_GPL(apple_rtkit_ap_idle_polled); + void apple_rtkit_mailbox_recv_off(struct apple_rtkit *rtk) { apple_mbox_set_recv_enabled(rtk->mbox, false); diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 75ab9f95b1719..886563ba58845 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -916,6 +916,11 @@ struct SepData { // exchange, and what discovery said about it. #[pin] ool_pnon: Mutex>, + // The hibernation endpoint (see `hibe`): its one page each way, held + // for the op0/op1 writer. Allocated here, sized from discovery, and + // registered only when a hibernation image is prepared. + #[pin] + ool_hibe: Mutex>, #[pin] pnon_rx: Mutex, #[pin] @@ -936,6 +941,17 @@ struct SepData { pnon_signed: Atomic, #[pin] pnon_owner: Mutex>, + #[pin] + hibe_rx: Mutex, + #[pin] + hibe_wq: CondVar, + /// Set while the system is hibernating (between PM_HIBERNATION_PREPARE + /// and PM_POST_HIBERNATION): the enclave is told the hibernation + /// sleep-type, and a hibernation image prepare may be driven on `hibe`. + hibernating: Atomic, + /// Set if a re-boot of the enclave after a hibernation resume did not + /// finish in time: the enclave is left unused rather than hung. + sep_unusable: Atomic, // What discovery said about the endpoints the driver checks and sends // nothing to (see `sse`, `hibe`, `skdl`). @@ -1191,6 +1207,8 @@ impl SepData { )?; // Sized from the endpoint's layout before it is registered. let ool_pnon = Self::alloc_ool(dev, pnon::EP_PNON, pnon::OOL_SIZE_PNON, (0, 0))?; + // hibe: one enclave page each way; sized from its layout on discovery. + let ool_hibe = Self::alloc_ool(dev, hibe::EP_HIBE, hibe::HIBE_OOL_INBOUND, (0, 0))?; let dma_ring = dma::Coherent::::zeroed_slice(dev, DMA_RING_SIZE, GFP_KERNEL)?; let keystore_only = attach::requested(); @@ -1363,6 +1381,7 @@ impl SepData { hdcp_layout: Atomic::new(0), hdcp_quarantined: Atomic::new(false), ool_pnon <- new_mutex!(Some(ool_pnon)), + ool_hibe <- new_mutex!(Some(ool_hibe)), pnon_rx <- new_mutex!(pnon::Exchange::new()), pnon_wq <- new_condvar!("SepData::pnon_wq"), pnon_named: Atomic::new(false), @@ -1374,6 +1393,10 @@ impl SepData { pnon_txn: Atomic::new(false), pnon_signed: Atomic::new(false), pnon_owner <- new_mutex!(None), + hibe_rx <- new_mutex!(hibe::Exchange::new()), + hibe_wq <- new_condvar!("SepData::hibe_wq"), + hibernating: Atomic::new(false), + sep_unusable: Atomic::new(false), sse_named: Atomic::new(false), sse_layout: Atomic::new(0), hibe_named: Atomic::new(false), @@ -1628,6 +1651,84 @@ impl SepData { } } + /// The system has just resumed from a hibernation image. The boot that + /// restored it started the enclave again, so the session this instance + /// holds (its registration, buffers, endpoints and bring-up state) belongs + /// to an enclave that is gone. Nothing more goes to the enclave from it: + /// its requests are refused and their waiters woken, the registration + /// marker that came back with the image's device tree is dropped, and the + /// driver is bound again, which attaches and brings the running enclave up + /// as at boot. Runs in the PM notifier, before held requests are released, + /// and returns at once: the new bind runs on its own thread. + pub(crate) fn resume_after_hibernation(this: Arc) { + if this.shutting_down.xchg(true, Relaxed) { + return; + } + // The gone enclave held these; the unbind frees them instead of + // keeping them for it. + this.registered.store(false, Relaxed); + this.sbio_ready.store(false, Relaxed); + for slot in [ + &this.ool_xarm, + &this.ool_sbio, + &this.ool_sks, + &this.ool_scrd, + &this.ool_stac, + &this.ool_hdcp, + &this.ool_pnon, + &this.ool_hibe, + ] { + let mut guard = slot.lock(); + let pair: &mut Option = &mut guard; + if let Some(b) = pair.as_mut() { + b.registered = false; + } + } + { + let _guard = this.endpoints.lock(); + this.trusted_ready.notify_all(); + } + this.control_wq.notify_all(); + + let Some(sep_node) = dt::sep_node() else { + dev_err_ratelimited!( + this.dev, + "hibernation: the enclave node is gone; the enclave stays unused\n" + ); + return; + }; + if let Err(e) = dt::clear_registration_sent(&sep_node) { + dev_err_ratelimited!( + this.dev, + "hibernation: the registration marker stays ({:?}); the enclave stays unused\n", + e + ); + return; + } + if let Err(e) = pm::rebind(&this.dev) { + dev_err_ratelimited!( + this.dev, + "hibernation: the driver could not be bound again ({:?}); the enclave stays unused\n", + e + ); + return; + } + dev_info_ratelimited!( + this.dev, + "hibernation: the enclave was started again; binding the driver again\n" + ); + } + + /// The system is entering hibernation (PM_HIBERNATION_PREPARE). + pub(crate) fn hibe_flow_enter(&self) { + self.hibernating.store(true, Relaxed); + } + + /// Hibernation is over: written, aborted or resumed (PM_POST_HIBERNATION). + pub(crate) fn hibe_flow_leave(&self) { + self.hibernating.store(false, Relaxed); + } + fn send(&self, msg: Message) -> Result<()> { if self.shutting_down.load(Relaxed) { return Err(ENODEV); @@ -1818,7 +1919,14 @@ impl SepData { /// Asks the enclave to go to sleep (told at suspend). The request is sent past the gate. fn sleep_request(&self) -> Result<()> { - let op = proto::op_sleep(); + // A hibernation uses the hibernation sleep-type, so the enclave saves + // for a resume from a cold boot rather than staying resident. The + // reply correlates on the tag and reply type, not the sleep-type. + let op = if self.hibernating.load(Relaxed) { + proto::op_hibernate() + } else { + proto::op_sleep() + }; let tag = proto::TAG_SLEEP; let idx = self.control.lock().alloc_sleep()?; let msg = proto::encode_control(&op, tag); @@ -3661,6 +3769,7 @@ impl SepData { self.scrd_wq.notify_all(); self.stac_wq.notify_all(); self.pnon_wq.notify_all(); + self.hibe_wq.notify_all(); if let Some(mut handle) = self.rng.lock().take() { handle.unregister(); } @@ -3699,6 +3808,7 @@ impl SepData { &self.ool_stac, &self.ool_hdcp, &self.ool_pnon, + &self.ool_hibe, ] { if let Some(buffers) = slot.lock().take() { if buffers.registered { diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 3887ee5245bbb..167de85f3a9ff 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -26,7 +26,8 @@ void sep_cancel_delayed_work_sync(void *work); /* -- pm_shim.c ---------------------------------------------------------- */ -int sep_pm_register(void *dev, void (*event)(bool entering), int (*sleep)(void), +int sep_pm_register(void *dev, void (*event)(bool entering), + void (*hib)(int phase), int (*sleep)(void), void (*wake)(void), bool (*told)(void)); void sep_pm_unregister(void); int sep_pm_keep_domains(void *dev); @@ -37,6 +38,7 @@ int sep_pm_dart_prepare(void *dev); bool sep_pm_platform_commit(void); int sep_pm_commit_prepare(void *dev, void *mbox, u64 msg0, u32 msg1, u64 reply, u64 mask); int sep_pm_commit_finish(void *dev); +int sep_pm_rebind(void *dev); extern const struct dev_pm_ops sep_pm_ops; /* -- hwrng_shim.c ------------------------------------------------------- */ diff --git a/drivers/soc/apple/sleep-t6040.h b/drivers/soc/apple/sleep-t6040.h index cd80a1be3cd59..f4cb26637b278 100644 --- a/drivers/soc/apple/sleep-t6040.h +++ b/drivers/soc/apple/sleep-t6040.h @@ -2426,6 +2426,7 @@ static const struct apple_sleep_ops t6040_sleep_ops = { }; static const struct apple_sleep_soc t6040_sleep_soc = { + .ps_reg_name = "soc-east", .ps = { .ans = PS_ANS, .apcie_gp = PS_APCIE_GP, diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index c6da3c58321d4..10661496544a0 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -73,6 +73,7 @@ #include #include #include +#include #include #include #include @@ -858,6 +859,12 @@ struct apple_sleep_soc { struct apple_sleep_words quiesce; /* Blocks the SoC doesn't have, by reg-name, NULL-terminated: left unmapped. */ const char *const *regs_absent; + /* + * DT reg-names of the PMGR block whose power-controller nodes the engine reset + * looks up. NULL means "ps". A SoC that maps that block under another name sets + * this; another SoC only adds the name to its data. + */ + const char *ps_reg_name; /* The sleep's SPMI bus has gen 4's queue layout (T8142). */ bool spmi_gen4; /* @@ -1008,6 +1015,9 @@ struct apple_sleep { bool matched; void __iomem *dvfm[SLEEP_CLUSTERS]; struct aura_s2r_mailbox *mbox; + u64 mbox_pa; + /* After a resume from disk: no mailbox of this boot, so no deep sleep */ + bool mbox_lost; u32 wake_enable[WAKE_SOURCES_MAX]; int wake_enable_count; @@ -3562,10 +3572,11 @@ static int sleep_engine_reset_power(struct device *dev, void __iomem **ps_regs, return ret; } -/* A domain of the PMGR block mapped here as "ps", and its offset in it. */ +/* A domain of the PMGR block mapped here as "ps" (or soc->ps_reg_name), and its offset in it. */ static bool sleep_ps_domain(struct apple_sleep *s, struct device_node *pd, u32 *offset) { - int idx = of_property_match_string(s->dev->of_node, "reg-names", "ps"); + const char *name = s->soc->ps_reg_name ? s->soc->ps_reg_name : "ps"; + int idx = of_property_match_string(s->dev->of_node, "reg-names", name); struct device_node *parent = of_get_parent(pd); struct resource ps, res; bool ours; @@ -3683,6 +3694,7 @@ int apple_sleep_engine_reset(struct device *dev) idx = of_property_match_string(dev->of_node, "reg-names", "coproc"); if (idx < 0) idx = of_property_match_string(dev->of_node, "reg-names", "asc"); + /* A coprocessor with one unnamed register range: that range is its ASC. */ if (idx < 0 && !of_property_present(dev->of_node, "reg-names")) idx = 0; asc = idx >= 0 ? of_iomap(dev->of_node, idx) : NULL; @@ -7552,6 +7564,9 @@ static int apple_sleep_begin(suspend_state_t state) /* Before the PM core takes the other CPUs down: the wake's burst starts only these. */ cpumask_copy(&sleep_cpus_awake, cpu_online_mask); + if (apple_sleep->mbox_lost) + return -ENODEV; + ret = apple_sleep_profile_check(apple_sleep); if (ret) return ret; @@ -8732,6 +8747,7 @@ static int apple_sleep_map_mailbox(struct apple_sleep *s) s->mbox = devm_memremap(s->dev, pa, sizeof(*s->mbox), MEMREMAP_WB); if (IS_ERR(s->mbox)) return PTR_ERR(s->mbox); + s->mbox_pa = pa; /* aura wrote it with the MMU off, so nothing of it can be in a cache. */ if (s->mbox->magic != AURA_S2R_MAGIC) @@ -8746,6 +8762,62 @@ static int apple_sleep_map_mailbox(struct apple_sleep *s) return 0; } +/* + * aura's mailbox moves with the boot object, so after a resume from disk the + * one mapped at probe is the one of the boot that wrote the image, which no + * aura reads any more. Take this boot's from aura's tree. Without a valid one + * deep sleep stays off until the next boot: a wake through a mailbox aura does + * not read would run its boot flow again. + */ +static int apple_sleep_restore(struct device *dev) +{ + struct apple_sleep *s = dev_get_drvdata(dev); + struct aura_s2r_mailbox *mbox; + u64 pa; + int ret; + + if (!IS_ENABLED(CONFIG_APPLE_AURA_HIBERNATE)) + return 0; + + ret = aura_hibernate_boot_chosen_u64("aurora,s2r-mailbox", &pa); + if (ret) { + dev_err(dev, "no S2R mailbox of this boot (%d): deep sleep off\n", ret); + goto lost; + } + if (pa == s->mbox_pa && !s->mbox_lost) + return 0; + + mbox = devm_memremap(dev, pa, sizeof(*mbox), MEMREMAP_WB); + if (IS_ERR(mbox)) { + ret = PTR_ERR(mbox); + dev_err(dev, "S2R mailbox of this boot not mapped (%d): deep sleep off\n", ret); + goto lost; + } + /* The boot kernel may have read it through a cacheable mapping. */ + dcache_inval_poc((unsigned long)mbox, (unsigned long)(mbox + 1)); + if (mbox->magic != AURA_S2R_MAGIC || mbox->boot_mpidr != cpu_logical_map(0)) { + dev_err(dev, "S2R mailbox of this boot not valid (magic %llx, CPU %llx): deep sleep off\n", + mbox->magic, mbox->boot_mpidr); + devm_memunmap(dev, mbox); + goto lost; + } + + devm_memunmap(dev, s->mbox); + s->mbox = mbox; + s->mbox_pa = pa; + s->mbox_lost = false; + dev_dbg(dev, "S2R mailbox of this boot at %llx\n", pa); + return 0; + +lost: + s->mbox_lost = true; + return 0; +} + +static const struct dev_pm_ops apple_sleep_pm_ops = { + .restore = apple_sleep_restore, +}; + static struct apple_tunable *apple_sleep_apcie_tunable(struct apple_sleep *s, struct device_node *np, const char *name, const char *prop) @@ -11478,6 +11550,7 @@ static struct platform_driver apple_sleep_driver = { .name = "apple-sleep", .of_match_table = apple_sleep_of_match, .suppress_bind_attrs = true, + .pm = pm_sleep_ptr(&apple_sleep_pm_ops), }, .probe = apple_sleep_probe, }; diff --git a/drivers/spi/spi-apple.c b/drivers/spi/spi-apple.c index 61f328f00ff38..72ec2e9b2dc53 100644 --- a/drivers/spi/spi-apple.c +++ b/drivers/spi/spi-apple.c @@ -799,6 +799,8 @@ static int apple_spi_probe(struct platform_device *pdev) ctlr->use_gpio_descriptors = true; ctlr->auto_runtime_pm = true; + platform_set_drvdata(pdev, ctlr); + pm_runtime_set_active(&pdev->dev); ret = devm_pm_runtime_enable(&pdev->dev); if (ret < 0) @@ -811,6 +813,48 @@ static int apple_spi_probe(struct platform_device *pdev) return 0; } +static int apple_spi_runtime_resume(struct device *dev) +{ + struct spi_controller *ctlr = dev_get_drvdata(dev); + struct apple_spi *spi = spi_controller_get_devdata(ctlr); + + apple_spi_init(spi); + return 0; +} + +static int apple_spi_suspend(struct device *dev) +{ + struct spi_controller *ctlr = dev_get_drvdata(dev); + int ret; + + ret = spi_controller_suspend(ctlr); + if (ret) + return ret; + + ret = pm_runtime_force_suspend(dev); + if (ret) + spi_controller_resume(ctlr); + + return ret; +} + +static int apple_spi_resume(struct device *dev) +{ + struct spi_controller *ctlr = dev_get_drvdata(dev); + int ret; + + ret = pm_runtime_force_resume(dev); + if (ret) + return ret; + + return spi_controller_resume(ctlr); +} + +static const struct dev_pm_ops apple_spi_pm_ops = { + SYSTEM_SLEEP_PM_OPS(apple_spi_suspend, apple_spi_resume) + RUNTIME_PM_OPS(NULL, apple_spi_runtime_resume, NULL) +}; + static const struct of_device_id apple_spi_of_match[] = { { .compatible = "apple,t8103-spi", }, { .compatible = "apple,spi", }, @@ -823,6 +867,7 @@ static struct platform_driver apple_spi_driver = { .driver = { .name = "apple-spi", .of_match_table = apple_spi_of_match, + .pm = pm_ptr(&apple_spi_pm_ops), }, }; module_platform_driver(apple_spi_driver); diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index 46d6f70c763f2..83d5d67d6296b 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -762,8 +762,49 @@ static int apple_spmi_resume_noirq(struct device *dev) return 0; } -static DEFINE_NOIRQ_DEV_PM_OPS(apple_spmi_pm_ops, apple_spmi_suspend_noirq, - apple_spmi_resume_noirq); +/* + * A restored hibernation image finds the controller as the kernel that loaded + * the image left it: its mask bank is that kernel's, and replies it did not + * read may be queued. Put this kernel's enables back and drop the replies. + */ +static int apple_spmi_restore_noirq(struct device *dev) +{ + struct apple_spmi *spmi = dev_get_drvdata(dev); + u32 words[SPMI_MAX_PERIPHERAL_IRQS / 32]; + unsigned int stale = 0; + unsigned long flags; + size_t i; + + guard(mutex)(&spmi->fifo_lock); + while (!(readl(spmi->regs + spmi->hw->status) & spmi->hw->rx_empty) && stale < 64) { + readl(spmi->regs + spmi->hw->reply); + stale++; + } + if (stale) + dev_info(dev, "dropped %u stale reply words after the restore\n", stale); + if (!spmi->irqd) + return 0; + raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); + bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->num_irqs); + for (i = 0; i < spmi->num_irqs / 32; i++) + writel(words[i], spmi->regs + spmi->hw->irq_mask + i * 4); + if (spmi->notify_irq) { + apple_spmi_irq_ack_raw(spmi, spmi->num_irqs); + apple_spmi_irq_unmask_raw(spmi, spmi->num_irqs); + } + raw_spin_unlock_irqrestore(&spmi->irq_mask_lock, flags); + + return 0; +} + +static const struct dev_pm_ops apple_spmi_pm_ops = { + .suspend_noirq = pm_sleep_ptr(apple_spmi_suspend_noirq), + .resume_noirq = pm_sleep_ptr(apple_spmi_resume_noirq), + .freeze_noirq = pm_sleep_ptr(apple_spmi_suspend_noirq), + .thaw_noirq = pm_sleep_ptr(apple_spmi_resume_noirq), + .poweroff_noirq = pm_sleep_ptr(apple_spmi_suspend_noirq), + .restore_noirq = pm_sleep_ptr(apple_spmi_restore_noirq), +}; static int apple_spmi_probe(struct platform_device *pdev) { diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 8cef94ad69f9a..8fbdf58cd628c 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -3359,6 +3359,22 @@ static int apple_nhi_thaw_noirq(struct device *dev) return tb_domain_thaw_noirq(anhi->tb); } +#ifdef CONFIG_HIBERNATION +/* + * After a cold hibernation restore, the boot loader reset the CIO controller + * and router. Clear any s2idle-only keep-alive quirks left from an earlier + * suspend so tb_domain_resume_noirq() restarts the NHI rings from scratch. + */ +static int apple_nhi_restore_noirq(struct device *dev) +{ + struct apple_nhi *anhi = dev_get_drvdata(dev); + + if (pm_hibernate_restored_cold()) + anhi->nhi.quirks &= ~(QUIRK_NO_SYSTEM_SLEEP | QUIRK_KEEP_TUNNELS); + return apple_nhi_resume_noirq(dev); +} +#endif + static int apple_nhi_suspend(struct device *dev) { struct apple_nhi *anhi = dev_get_drvdata(dev); @@ -3394,7 +3410,11 @@ static const struct dev_pm_ops apple_nhi_pm_ops = { .resume_noirq = apple_nhi_resume_noirq, .freeze_noirq = apple_nhi_freeze_noirq, .thaw_noirq = apple_nhi_thaw_noirq, +#ifdef CONFIG_HIBERNATION + .restore_noirq = apple_nhi_restore_noirq, +#else .restore_noirq = apple_nhi_resume_noirq, +#endif .poweroff = apple_nhi_suspend, .poweroff_noirq = apple_nhi_suspend_noirq, .complete = apple_nhi_complete, diff --git a/drivers/usb/core/hub.c b/drivers/usb/core/hub.c index e980897eb9c07..b045964948106 100644 --- a/drivers/usb/core/hub.c +++ b/drivers/usb/core/hub.c @@ -3334,8 +3334,8 @@ static int hub_port_reset(struct usb_hub *hub, int port1, status = set_port_feature(hub->hdev, port1, (warm ? USB_PORT_FEAT_BH_PORT_RESET : USB_PORT_FEAT_RESET)); - if (status == -ENODEV) { - ; /* The hub is gone */ + if (status == -ENODEV || status == -ESHUTDOWN) { + ; /* The hub or its host controller is gone */ } else if (status) { dev_err(&port_dev->dev, "cannot %sreset (err = %d)\n", @@ -3354,6 +3354,7 @@ static int hub_port_reset(struct usb_hub *hub, int port1, * reset attempts to avoid warm reset loop. */ if (status == 0 || status == -ENOTCONN || status == -ENODEV || + status == -ESHUTDOWN || (status == -EBUSY && i == PORT_RESET_TRIES - 1)) { usb_clear_port_feature(hub->hdev, port1, USB_PORT_FEAT_C_RESET); @@ -5074,7 +5075,7 @@ static int hub_port_disable(struct usb_hub *hub, int port1, int set_state) } if (port_dev->child && set_state) usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED); - if (ret && ret != -ENODEV) + if (ret && ret != -ENODEV && ret != -ESHUTDOWN) dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret); return ret; } @@ -6705,7 +6706,8 @@ static int usb_reset_and_verify_device(struct usb_device *udev) * Other endpoints will be handled by re-enumeration. */ usb_ep0_reinit(udev); ret = hub_port_init(parent_hub, udev, port1, i, &descriptor); - if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV) + if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV || + ret == -ESHUTDOWN) break; } mutex_unlock(hcd->address0_mutex); diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index 7501b971b03bb..722f48d6bb88d 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -269,6 +269,8 @@ struct dwc3_apple { /* Desired syscore ownership, held off only while device prepare must run. */ bool sleep_syscore; bool sleep_deep; + /* A hibernation epoch: the host is stopped, never kept, see dwc3_apple_pm_notify() */ + bool sleep_hibernate; bool sleep_pm_online; bool sleep_role_pending; enum dwc3_apple_state sleep_role; @@ -2186,6 +2188,11 @@ static int dwc3_apple_sleep_prepare_work(struct dwc3_apple *appledwc) ret = dwc3_apple_sleep_start(appledwc); if (ret) return ret; + if (appledwc->sleep_hibernate) { + ret = dwc3_apple_sleep_stop(appledwc); + dwc3_apple_sleep_take_role(appledwc); + return ret; + } if (!appledwc->sleep_deep) { /* * Suspend-to-idle keeps a gadget controller started; taking a @@ -2343,6 +2350,34 @@ static void dwc3_apple_sleep_start_work(struct work_struct *work) dev_err(appledwc->dev, "USB host recovery failed: %d\n", ret); } +static int dwc3_apple_set_child_async(struct device *dev, void *data) +{ + bool enable = *(bool *)data; + + if (enable) + device_enable_async_suspend(dev); + else + device_disable_async_suspend(dev); + device_for_each_child(dev, data, dwc3_apple_set_child_async); + return 0; +} + +/* + * With async resume the restored tree's hub port resets can race the parent + * hub coming back, which showed up as a burst of -ESHUTDOWN port resets after + * a hibernation restore. Keep the USB tree ordered for that transition only; + * ordinary suspend keeps async resume so the host is not stuck behind the + * display. + */ +static void dwc3_apple_set_tree_async(struct dwc3_apple *appledwc, bool enable) +{ + if (enable) + device_enable_async_suspend(appledwc->dev); + else + device_disable_async_suspend(appledwc->dev); + device_for_each_child(appledwc->dev, &enable, dwc3_apple_set_child_async); +} + /* The blocking notifier chain must never join teardown, even indirectly through a lock. */ static int dwc3_apple_pm_notify(struct notifier_block *nb, unsigned long action, void *unused) { @@ -2350,7 +2385,10 @@ static int dwc3_apple_pm_notify(struct notifier_block *nb, unsigned long action, unsigned long flags; bool start = false; - if (action == PM_POST_SUSPEND) { + if (action == PM_POST_HIBERNATION) + dwc3_apple_set_tree_async(appledwc, true); + + if (action == PM_POST_SUSPEND || action == PM_POST_HIBERNATION) { spin_lock_irqsave(&appledwc->sleep_pm_lock, flags); if (appledwc->sleep_phase == DWC3_APPLE_SLEEP_PREPARING || appledwc->sleep_phase == DWC3_APPLE_SLEEP_PREPARED) { @@ -2371,7 +2409,8 @@ static int dwc3_apple_pm_notify(struct notifier_block *nb, unsigned long action, msecs_to_jiffies(DWC3_APPLE_SLEEP_START_MS) : 0); return NOTIFY_DONE; } - if (action != PM_SUSPEND_PREPARE || !READ_ONCE(appledwc->sleep_pm_online)) + if ((action != PM_SUSPEND_PREPARE && action != PM_HIBERNATION_PREPARE) || + !READ_ONCE(appledwc->sleep_pm_online)) return NOTIFY_DONE; if (!mutex_trylock(&appledwc->lock)) return notifier_from_errno(-EBUSY); @@ -2389,6 +2428,15 @@ static int dwc3_apple_pm_notify(struct notifier_block *nb, unsigned long action, appledwc->sleep_phase = DWC3_APPLE_SLEEP_PREPARING; /* A "freeze" is a suspend-to-idle with deep as the default too: the host stays. */ appledwc->sleep_deep = !pm_suspend_default_s2idle() && !pm_suspend_no_platform(); + /* + * A hibernation image is restored after a reboot, with the controller reset and set up + * by the kernel that loaded the image, if at all: no host is kept across it. It is + * stopped before the image, the way a cable disconnect does, and started again from + * scratch once the restored system runs, as after a deep sleep that lost it. + */ + appledwc->sleep_hibernate = action == PM_HIBERNATION_PREPARE; + if (appledwc->sleep_hibernate) + dwc3_apple_set_tree_async(appledwc, false); /* Every admitted epoch must reach device prepare, including a retained host. */ dev_pm_syscore_device(appledwc->dev, false); reinit_completion(&appledwc->sleep_stop_done); diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c index 3cc4227d27e09..669e939ac05e3 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c @@ -3417,6 +3417,7 @@ static void xhci_endpoint_reset(struct usb_hcd *hcd, struct xhci_virt_device *vdev; struct xhci_virt_ep *ep; struct xhci_input_control_ctx *ctrl_ctx; + struct xhci_slot_ctx *slot_ctx; struct xhci_command *stop_cmd, *cfg_cmd; unsigned int ep_index; unsigned long flags; @@ -3441,6 +3442,17 @@ static void xhci_endpoint_reset(struct usb_hcd *hcd, if (!vdev || vdev->udev != udev) return; + /* + * A slot that is only enabled, as after the xHC lost its state and + * a reset-resume allocated the slot again, has no ep0 context yet: + * an Evaluate Context fails with a Context State Error. Address + * Device sets ep0 up and the core resets ep0 again if needed. + */ + slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx); + if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) == + SLOT_STATE_DISABLED) + return; + xhci_check_ep0_maxpacket(xhci, vdev); /* Nothing else should be done here for ep0 during ep reset */ diff --git a/drivers/usb/typec/tipd/spmi.c b/drivers/usb/typec/tipd/spmi.c index cf331b9900d4a..5109cacb536c8 100644 --- a/drivers/usb/typec/tipd/spmi.c +++ b/drivers/usb/typec/tipd/spmi.c @@ -1791,10 +1791,40 @@ static void sn201202x_complete(struct device *dev) MODULE_DEVICE_TABLE(of, sn201202x_of_match); +#ifdef CONFIG_HIBERNATION +/* + * On a resume from disk across a cold boot, the resuming boot reset the port + * controller (clearing any liquid-detection mitigation) and the loading kernel + * put it to sleep at its freeze. Invalidate the cached mitigation state so + * complete() reads the detector afresh, then wake the controller as after a + * sleep. + */ +static int sn201202x_restore(struct device *dev) +{ + struct tps6598x *tps = dev_get_drvdata(dev); + + if (pm_hibernate_restored_cold()) { + scoped_guard(mutex, &tps->lock) + sn201202x_ldcm_invalidate(tps); + dev_dbg(dev, "resume from disk: waking port controller as after a sleep\n"); + } + return sn201202x_resume(dev); +} +#endif + static const struct dev_pm_ops sn201202x_pm_ops = { .prepare = pm_sleep_ptr(sn201202x_prepare), .complete = pm_sleep_ptr(sn201202x_complete), - SET_SYSTEM_SLEEP_PM_OPS(sn201202x_suspend, sn201202x_resume) + .suspend = pm_sleep_ptr(sn201202x_suspend), + .resume = pm_sleep_ptr(sn201202x_resume), + .freeze = pm_sleep_ptr(sn201202x_suspend), + .thaw = pm_sleep_ptr(sn201202x_resume), + .poweroff = pm_sleep_ptr(sn201202x_suspend), +#ifdef CONFIG_HIBERNATION + .restore = sn201202x_restore, +#else + .restore = pm_sleep_ptr(sn201202x_resume), +#endif SET_RUNTIME_PM_OPS(sn201202x_runtime_suspend, sn201202x_runtime_resume, NULL) }; diff --git a/drivers/watchdog/apple_wdt-test.c b/drivers/watchdog/apple_wdt-test.c index 2d07a2ab51de1..4902618aa6540 100644 --- a/drivers/watchdog/apple_wdt-test.c +++ b/drivers/watchdog/apple_wdt-test.c @@ -541,7 +541,8 @@ static void apple_wdt_test_sleep_handoff_mode(struct kunit *test, bool reconfig) apple_wdt_test_expect(ctx, APPLE_WDT_WD2_CTRL, APPLE_WDT_CTRL_IRQ_EN); KUNIT_EXPECT_EQ(test, *reconfig_reg, - (0x123400c3U & ~APPLE_WDT_RECONFIG_MASK) | + (0x123400c3U & ~APPLE_WDT_RECONFIG_LOW_MASK) | + APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2); } else { apple_wdt_test_expect(ctx, APPLE_WDT_WD1_CUR_TIME, 0); @@ -594,7 +595,8 @@ static void apple_wdt_test_wd2_reconfig_ops(struct kunit *test) apple_wdt_test_expect(ctx, APPLE_WDT_WD2_CTRL, APPLE_WDT_CTRL_IRQ_EN); apple_wdt_test_check(test); KUNIT_EXPECT_EQ(test, *reconfig_reg, - (0xa000003fU & ~APPLE_WDT_RECONFIG_MASK) | + (0xa000003fU & ~APPLE_WDT_RECONFIG_LOW_MASK) | + APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2); apple_wdt_test_set(ctx, APPLE_WDT_WD2_CUR_TIME, 15 * APPLE_WDT_TEST_RATE); diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index ab7da24f82385..3335ce2757137 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -12,27 +12,42 @@ #include #include #include +#include +#include #include #include #include #include #include +#include #include +#include #include /* * Apple Watchdog MMIO registers * * This HW block has three separate watchdogs. WD0 resets the machine to - * recovery mode and is not used by Linux. On legacy wdt-version 2 platforms - * WD1 triggers a normal machine reset via APPLE_WDT_CTRL_RESET_EN when - * CUR_TIME >= BITE_TIME. + * recovery mode and is not used by Linux. On legacy platforms without a + * reconfig register, WD1 triggers a normal machine reset via + * APPLE_WDT_CTRL_RESET_EN when CUR_TIME >= BITE_TIME. * - * On platforms that provide the optional "reconfig" routing register - * (simple-reconfig-wdog-support), WD1/WD2 hardware RESET_EN does not reset - * reliably; instead, setting bits 5:4 = 01 in the reconfig register routes - * WD2's bark interrupt (CUR_TIME >= BARK_TIME with APPLE_WDT_CTRL_IRQ_EN - * set and BITE_TIME = U32_MAX) to a clean cold reset. + * On SoCs with a "reconfig" routing register the runtime reset path depends + * on the generation: + * + * With an optional "deadline" register (t6041): the AP watchdog is the SMC + * deadline, an absolute time in seconds of the continuous timer. The SMC + * checks it once a second and resets the AP once its uptime passes + * deadline - 1. Writing 0 disarms it (the SMC and the sleep driver both + * zero it). The WD2 bark there only serves the sleep reconfig path, not + * the runtime cold-reset route. + * + * Without one (t6050 and later): WD2 bark (IRQ_EN, BITE unused) with + * reconfig bits 5:4 = 01 is the runtime route. + * + * The firmware owns the low 8 bits of the reconfig register: bit 0 = + * halt-on-expiration, bit 3 if !AWL, bit 4 only on the WD2 route. Linux + * never sets the halt bit. * * APPLE_WDT_WDx_CUR_TIME is a simple counter incremented for each tick of the * reference clock. It can also be overwritten to any value. @@ -58,27 +73,55 @@ #define APPLE_WDT_CTRL_IRQ_STATUS BIT(1) #define APPLE_WDT_CTRL_RESET_EN BIT(2) -/* Optional "reconfig" register: bits 5:4 = 01 routes WD2 bark to cold reset */ +/* + * Reconfig low-8-bit policy, as the firmware programs it. Bits 8+ are + * preserved, including bit 17 (SMC ignores the WD2 IRQ when it is set). + */ +#define APPLE_WDT_RECONFIG_LOW_MASK 0xff +#define APPLE_WDT_RECONFIG_HALT BIT(0) +#define APPLE_WDT_RECONFIG_NO_AWL BIT(3) #define APPLE_WDT_RECONFIG_MASK GENMASK(5, 4) #define APPLE_WDT_RECONFIG_WD2 BIT(4) -/* ~40 ms bark delay before simple-reconfig cold reset */ +/* ~40 ms bark delay before a WD2 simple-reconfig cold reset */ #define APPLE_WDT_REBOOT_DELAY_MS 40 #define APPLE_WDT_TIMEOUT_DEFAULT 30 +/* + * Default restore backstop. The SMC deadline is a 32-bit second stamp, so + * this is no longer capped by the ~178 s WD2 U32 wrap at 24 MHz; keep a + * one-hour ceiling so a missing ping cannot linger for days. + */ +#define APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT 150 +#define APPLE_WDT_DEADLINE_TIMEOUT_MAX 3600 struct apple_wdt { struct watchdog_device wdd; void __iomem *regs; void __iomem *reconfig; + void __iomem *deadline; /* optional SMC AP deadline */ unsigned long clk_rate; + bool hib_backstop; }; +static unsigned int hibernation_restore_timeout = + APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT; +module_param(hibernation_restore_timeout, uint, 0644); +MODULE_PARM_DESC(hibernation_restore_timeout, + "Hibernation-restore backstop timeout in seconds (0 = disable, default 150, capped at 3600 on the SMC deadline path)"); + +static struct apple_wdt *apple_wdt_instance; + static struct apple_wdt *to_apple_wdt(struct watchdog_device *wdd) { return container_of(wdd, struct apple_wdt, wdd); } +static bool apple_wdt_use_smc_deadline(const struct apple_wdt *wdt) +{ + return wdt->deadline; +} + static u32 apple_wdt_timeout_ticks(struct apple_wdt *wdt, unsigned int s) { u32 actual = min(s, wdt->wdd.max_hw_heartbeat_ms / 1000); @@ -86,25 +129,91 @@ static u32 apple_wdt_timeout_ticks(struct apple_wdt *wdt, unsigned int s) return wdt->clk_rate * actual; } -static void apple_wdt_enable_reconfig(struct apple_wdt *wdt) +static void apple_wdt_write_ap_config(struct apple_wdt *wdt, u32 lo) { u32 val = readl_relaxed(wdt->reconfig); - writel_relaxed((val & ~APPLE_WDT_RECONFIG_MASK) | APPLE_WDT_RECONFIG_WD2, + writel_relaxed((val & ~APPLE_WDT_RECONFIG_LOW_MASK) | (lo & APPLE_WDT_RECONFIG_LOW_MASK), wdt->reconfig); (void)readl(wdt->reconfig); } +static void apple_wdt_enable_reconfig(struct apple_wdt *wdt) +{ + /* + * WD2 route: replace the low 8 bits with !AWL | bit 4, preserving + * bits 8+. Do not RMW only bits 5:4, which can leave a leftover + * halt-on-expiration bit. + */ + apple_wdt_write_ap_config(wdt, APPLE_WDT_RECONFIG_NO_AWL | + APPLE_WDT_RECONFIG_WD2); +} + +static void apple_wdt_deadline_disarm(struct apple_wdt *wdt) +{ + if (!wdt->deadline) + return; + writel_relaxed(0, wdt->deadline); + (void)readl(wdt->deadline); +} + +/* + * The SMC compares deadline against its own uptime in seconds, which + * Firmware fills it from its continuous timebase. Linux + * ktime_get_boottime() starts at kernel timekeeping and would be late + * by the iBoot/m1n1 window, so a short deadline could already be in + * the past. CNTPCT is the shared 24 MHz AON timebase and is the best + * available stand-in; a few seconds of SMC-vs-CNTPCT skew is acceptable + * on a 150 s backstop. + */ +static u32 apple_wdt_smc_now_seconds(void) +{ + u32 rate = arch_timer_get_rate(); + + if (!rate) + return (u32)ktime_get_boottime_seconds(); + return (u32)div_u64(arch_timer_read_counter(), rate); +} + +static u32 apple_wdt_deadline_arm(struct apple_wdt *wdt, unsigned int timeout_s) +{ + u32 now, dl; + + /* Runtime v2 reset is the SMC deadline, not WD2 bark. */ + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL); + (void)readl(wdt->regs + APPLE_WDT_WD2_CTRL); + + if (wdt->reconfig) + apple_wdt_write_ap_config(wdt, APPLE_WDT_RECONFIG_NO_AWL); + + now = apple_wdt_smc_now_seconds(); + dl = now + timeout_s; + if (dl < now) + dl = U32_MAX; + /* 0 is the disarm sentinel used by the SMC and by sleep.c. */ + if (!dl) + dl = 1; + + writel_relaxed(dl, wdt->deadline); + (void)readl(wdt->deadline); + return dl; +} + static void apple_wdt_wd2_arm(struct apple_wdt *wdt, u32 bark_ticks) { /* * Disarm WD2, program safe BITE/CUR/BARK, and clear any latched * IRQ_STATUS before routing WD2 bark to cold reset and enabling IRQ_EN. + * Drain the disarm first: while IRQ_EN is set the block ignores a + * CUR_TIME update, and a sleep or hibernation restore re-programs an + * already-running counter (start and ping use the same sequence). * Read back WD2_CTRL to order the watchdog-block writes before touching * the separate AON reconfig mapping; apple_wdt_enable_reconfig() reads * back reconfig before the final IRQ_EN write. */ writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL); + (void)readl(wdt->regs + APPLE_WDT_WD2_CTRL); writel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME); writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME); writel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME); @@ -113,6 +222,7 @@ static void apple_wdt_wd2_arm(struct apple_wdt *wdt, u32 bark_ticks) (void)readl(wdt->regs + APPLE_WDT_WD2_CTRL); apple_wdt_enable_reconfig(wdt); writel_relaxed(APPLE_WDT_CTRL_IRQ_EN, wdt->regs + APPLE_WDT_WD2_CTRL); + (void)readl(wdt->regs + APPLE_WDT_WD2_CUR_TIME); } static bool apple_wdt_sleep_owned(struct device *dev) @@ -126,7 +236,16 @@ static void apple_wdt_start_hw(struct apple_wdt *wdt) { u32 ticks = apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout); - if (wdt->reconfig) { + /* + * Everyday systemd pings stay on WD1 next to an SMC deadline. The SMC + * deadline is only the hibernation/restart backstop; programming + * it from start() would also make a timebase mistake take the + * machine down on first /dev/watchdog0 open. + */ + if (wdt->hib_backstop && apple_wdt_use_smc_deadline(wdt)) + return; + + if (!apple_wdt_use_smc_deadline(wdt) && wdt->reconfig) { apple_wdt_wd2_arm(wdt, ticks); return; } @@ -156,6 +275,15 @@ static int apple_wdt_stop(struct watchdog_device *wdd) if (apple_wdt_sleep_owned(wdd->parent)) return 0; + if (apple_wdt_use_smc_deadline(wdt)) { + if (wdt->hib_backstop) + apple_wdt_deadline_disarm(wdt); + if (wdt->reconfig && !wdt->hib_backstop) + apple_wdt_write_ap_config(wdt, 0); + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + return 0; + } + writel_relaxed(0, wdt->regs + ctrl_off); return 0; @@ -169,8 +297,33 @@ static int apple_wdt_ping(struct watchdog_device *wdd) if (apple_wdt_sleep_owned(wdd->parent)) return 0; - cur_off = wdt->reconfig ? APPLE_WDT_WD2_CUR_TIME : APPLE_WDT_WD1_CUR_TIME; + if (wdt->hib_backstop && apple_wdt_use_smc_deadline(wdt)) + return 0; + + if (apple_wdt_use_smc_deadline(wdt)) { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); + (void)readl(wdt->regs + APPLE_WDT_WD1_CUR_TIME); + return 0; + } + + if (wdt->reconfig) { + u32 ctrl = readl(wdt->regs + APPLE_WDT_WD2_CTRL); + + if (ctrl & APPLE_WDT_CTRL_IRQ_EN) { + writel_relaxed(ctrl & ~APPLE_WDT_CTRL_IRQ_EN, + wdt->regs + APPLE_WDT_WD2_CTRL); + (void)readl(wdt->regs + APPLE_WDT_WD2_CTRL); + } + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME); + (void)readl(wdt->regs + APPLE_WDT_WD2_CUR_TIME); + if (ctrl & APPLE_WDT_CTRL_IRQ_EN) + writel_relaxed(ctrl, wdt->regs + APPLE_WDT_WD2_CTRL); + return 0; + } + + cur_off = APPLE_WDT_WD1_CUR_TIME; writel_relaxed(0, wdt->regs + cur_off); + (void)readl(wdt->regs + cur_off); return 0; } @@ -187,6 +340,17 @@ static int apple_wdt_set_timeout(struct watchdog_device *wdd, unsigned int s) if (apple_wdt_sleep_owned(wdd->parent)) return 0; + if (apple_wdt_use_smc_deadline(wdt)) { + if (wdt->hib_backstop) + return 0; + if (watchdog_active(wdd) || watchdog_hw_running(wdd)) { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); + writel_relaxed(apple_wdt_timeout_ticks(wdt, s), + wdt->regs + APPLE_WDT_WD1_BITE_TIME); + } + return 0; + } + ticks = apple_wdt_timeout_ticks(wdt, s); if (wdt->reconfig) { writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME); @@ -202,7 +366,28 @@ static int apple_wdt_set_timeout(struct watchdog_device *wdd, unsigned int s) static unsigned int apple_wdt_get_timeleft(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); - u32 ctrl, cur_time, reset_time; + u32 ctrl, cur_time, reset_time, now, dl; + + if (wdt->hib_backstop && apple_wdt_use_smc_deadline(wdt)) { + dl = readl_relaxed(wdt->deadline); + if (!dl) + return 0; + now = apple_wdt_smc_now_seconds(); + if (now >= dl) + return 0; + return dl - now; + } + + if (apple_wdt_use_smc_deadline(wdt)) { + ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); + if (!(ctrl & APPLE_WDT_CTRL_RESET_EN)) + return 0; + cur_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CUR_TIME); + reset_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_BITE_TIME); + if (cur_time >= reset_time) + return 0; + return (reset_time - cur_time) / wdt->clk_rate; + } /* * Without the reset armed the counter runs freely and wraps every @@ -239,6 +424,17 @@ static int apple_wdt_restart(struct watchdog_device *wdd, unsigned long mode, { struct apple_wdt *wdt = to_apple_wdt(wdd); + if (apple_wdt_use_smc_deadline(wdt)) { + /* + * A deadline of "now" trips the SMC poll (uptime > deadline-1) + * within about one second. + */ + apple_wdt_deadline_arm(wdt, 0); + (void)readl(wdt->deadline); + mdelay(2000); + return 0; + } + if (wdt->reconfig) { u32 ticks = max_t(u32, 1, div_u64((u64)wdt->clk_rate * APPLE_WDT_REBOOT_DELAY_MS, @@ -304,10 +500,102 @@ static void apple_wdt_sleep_unregister(void *data) apple_sleep_wdt_unregister(data); } +static int apple_wdt_map_deadline(struct device *dev, struct apple_wdt *wdt, + const struct resource *res) +{ + if (resource_size(res) < sizeof(u32)) + return -EINVAL; + wdt->deadline = devm_ioremap(dev, res->start, resource_size(res)); + if (!wdt->deadline) + return -ENOMEM; + dev_info(dev, "SMC AP deadline at %pR\n", res); + return 0; +} + +/* + * The hibernation backstop: the SMC AP deadline where the DT provides one, + * otherwise WD2 on the simple-reconfig cold-reset route, for + * hibernation_restore_timeout seconds. + */ +static int apple_wdt_hib_arm(void) +{ + struct apple_wdt *wdt = apple_wdt_instance; + unsigned int max_s, s; + u32 dl; + + if (!wdt) + return -ENODEV; + if (apple_wdt_use_smc_deadline(wdt)) { + s = hibernation_restore_timeout; + if (!s) + return 0; + if (s > APPLE_WDT_DEADLINE_TIMEOUT_MAX) + s = APPLE_WDT_DEADLINE_TIMEOUT_MAX; + dl = apple_wdt_deadline_arm(wdt, s); + wdt->hib_backstop = true; + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + pr_info("hibernation backstop: SMC AP deadline %u (cntpct %u, boottime %u, +%u s)\n", + dl, apple_wdt_smc_now_seconds(), + (u32)ktime_get_boottime_seconds(), s); + return 0; + } + if (!wdt->reconfig) { + pr_err("hibernation restore backstop needs simple-reconfig or an SMC AP deadline\n"); + return -ENODEV; + } + + s = hibernation_restore_timeout; + if (!s) + return 0; + + max_s = wdt->wdd.max_hw_heartbeat_ms / 1000; + if (s > max_s) + s = max_s; + if (!s) + return -EINVAL; + + apple_wdt_wd2_arm(wdt, apple_wdt_timeout_ticks(wdt, s)); + wdt->hib_backstop = true; + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + pr_info("hibernation backstop: WD2 simple-reconfig cold-reset in %u s\n", s); + return 0; +} + +static void apple_wdt_hib_disarm(void) +{ + struct apple_wdt *wdt = apple_wdt_instance; + + if (!wdt || !wdt->hib_backstop) + return; + + if (apple_wdt_use_smc_deadline(wdt)) + apple_wdt_deadline_disarm(wdt); + else + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL); + wdt->hib_backstop = false; + if (watchdog_active(&wdt->wdd)) + apple_wdt_start(&wdt->wdd); + else + clear_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + pr_info("hibernation backstop disarmed: the system kept running%s\n", + watchdog_active(&wdt->wdd) ? ", watchdog running" : ""); +} + +static const struct hibernation_backstop apple_wdt_hib_backstop = { + .arm = apple_wdt_hib_arm, + .disarm = apple_wdt_hib_disarm, +}; + +static void apple_wdt_hib_unregister(void *data) +{ + hibernation_set_backstop(NULL); + apple_wdt_instance = NULL; +} + static int apple_wdt_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; - struct resource *wdt_res, *reconfig_res; + struct resource *wdt_res, *reconfig_res, *deadline_res; struct apple_wdt *wdt; struct clk *clk; resource_size_t min_regs; @@ -332,6 +620,14 @@ static int apple_wdt_probe(struct platform_device *pdev) return -ENOMEM; } + /* The SMC deadline replaces the WD2 route; it needs a reconfig register. */ + deadline_res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "deadline"); + if (deadline_res && wdt->reconfig) { + ret = apple_wdt_map_deadline(dev, wdt, deadline_res); + if (ret) + return ret; + } + min_regs = (wdt->reconfig ? APPLE_WDT_WD2_CTRL : APPLE_WDT_WD1_CTRL) + sizeof(u32); if (resource_size(wdt_res) < min_regs) @@ -369,30 +665,69 @@ static int apple_wdt_probe(struct platform_device *pdev) return ret; if (wdt->reconfig) { - u32 wd1_ctrl, wd2_ctrl; + u32 wd1_ctrl, wd2_ctrl, deadline; bool armed; wd1_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); wd2_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD2_CTRL); - armed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) || - (wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN)); - - if (wd1_ctrl) - writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); - - if (armed && !is_kdump_kernel()) { - if (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) - dev_info(dev, "taking over legacy WD1 watchdog as WD2 simple-reconfig\n"); - if (wd2_ctrl & APPLE_WDT_CTRL_RESET_EN) - dev_info(dev, "taking over WD2 RESET_EN watchdog as WD2 simple-reconfig\n"); - set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); - apple_wdt_wd2_arm(wdt, - apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout)); + deadline = wdt->deadline ? readl_relaxed(wdt->deadline) : 0; + + if (apple_wdt_use_smc_deadline(wdt)) { + /* + * Leftover WD1/WD2 from firmware or an older kernel + * is not the v2 runtime route: stop it. Adopt a + * live SMC deadline (and only that) as the backstop. + */ + if (wd1_ctrl) + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + if (wd2_ctrl) { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL); + dev_info(dev, "stopped leftover WD2; v2 runtime reset is the SMC deadline\n"); + } + if (deadline && !is_kdump_kernel()) { + unsigned int s = hibernation_restore_timeout ? + hibernation_restore_timeout : + wdt->wdd.timeout; + + wdt->hib_backstop = true; + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + apple_wdt_deadline_arm(wdt, s); + dev_info(dev, + "adopting running SMC AP deadline 0x%x, refreshing to %u s\n", + deadline, s); + } else { + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + } } else { - if (wd2_ctrl) - writel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS, - wdt->regs + APPLE_WDT_WD2_CTRL); - apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + armed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) || + (wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN)); + + if (wd1_ctrl) + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + + if (armed && !is_kdump_kernel()) { + unsigned int s = wdt->wdd.timeout; + + if (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) + dev_info(dev, "taking over legacy WD1 watchdog as WD2 simple-reconfig\n"); + if (wd2_ctrl & APPLE_WDT_CTRL_RESET_EN) + dev_info(dev, "taking over WD2 RESET_EN watchdog as WD2 simple-reconfig\n"); + if (wd2_ctrl & APPLE_WDT_CTRL_IRQ_EN) { + if (hibernation_restore_timeout) + s = hibernation_restore_timeout; + wdt->hib_backstop = true; + dev_info(dev, + "adopting running WD2 backstop, refreshing to %u s\n", + s); + } + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + apple_wdt_wd2_arm(wdt, apple_wdt_timeout_ticks(wdt, s)); + } else { + if (wd2_ctrl) + writel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS, + wdt->regs + APPLE_WDT_WD2_CTRL); + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + } } } else { wdt_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); @@ -416,6 +751,12 @@ static int apple_wdt_probe(struct platform_device *pdev) watchdog_stop_on_unregister(&wdt->wdd); watchdog_set_restart_priority(&wdt->wdd, 128); + apple_wdt_instance = wdt; + hibernation_set_backstop(&apple_wdt_hib_backstop); + ret = devm_add_action_or_reset(dev, apple_wdt_hib_unregister, NULL); + if (ret) + return ret; + ret = devm_watchdog_register_device(dev, &wdt->wdd); if (ret) { if (is_kdump_kernel()) @@ -426,6 +767,20 @@ static int apple_wdt_probe(struct platform_device *pdev) return 0; } +static bool apple_wdt_hw_armed(struct apple_wdt *wdt) +{ + u32 ctrl; + + if (apple_wdt_use_smc_deadline(wdt)) + return readl_relaxed(wdt->deadline) != 0; + if (wdt->reconfig) { + ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD2_CTRL); + return !!(ctrl & APPLE_WDT_CTRL_IRQ_EN); + } + ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); + return !!(ctrl & APPLE_WDT_CTRL_RESET_EN); +} + static int apple_wdt_resume(struct device *dev) { struct apple_wdt *wdt = dev_get_drvdata(dev); @@ -453,7 +808,73 @@ static int apple_wdt_suspend(struct device *dev) return 0; } -static DEFINE_SIMPLE_DEV_PM_OPS(apple_wdt_pm_ops, apple_wdt_suspend, apple_wdt_resume); +/* Leave a hibernation backstop ticking through snapshot, write, and reboot. */ +static int apple_wdt_freeze(struct device *dev) +{ + struct apple_wdt *wdt = dev_get_drvdata(dev); + + if (wdt->hib_backstop) + return 0; + + return apple_wdt_suspend(dev); +} + +/* + * The image is back in memory and every device has been restored: the + * backstop armed on hibernation entry (and refreshed by the restore kernel) + * has done its job. Left armed it resets the machine at its original expiry, + * so a restored session would end a few minutes after it came back. Disarm + * or adopt it and hand the everyday watchdog back to systemd if active. + */ +static int apple_wdt_restore(struct device *dev) +{ + struct apple_wdt *wdt = dev_get_drvdata(dev); + + if (apple_wdt_sleep_owned(dev)) + return 0; + + if (apple_wdt_use_smc_deadline(wdt) && wdt->hib_backstop) { + writel_relaxed(0, wdt->deadline); + (void)readl(wdt->deadline); + wdt->hib_backstop = false; + if (watchdog_active(&wdt->wdd)) { + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + apple_wdt_start(&wdt->wdd); + } else { + clear_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + } + dev_info(dev, "hibernation restore complete: SMC AP deadline disarmed%s\n", + watchdog_active(&wdt->wdd) ? ", WD1 running" : ""); + return 0; + } + + /* + * The restore-kernel backstop keeps ticking across the image jump. + * Adopt it so a successful restore is not reset once the timeout elapses. + */ + if (apple_wdt_hw_armed(wdt)) { + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + if (!watchdog_active(&wdt->wdd)) { + apple_wdt_stop(&wdt->wdd); + wdt->hib_backstop = false; + clear_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + dev_info(dev, "adopted hibernation-restore backstop and stopped it\n"); + return 0; + } + dev_info(dev, "adopted hibernation-restore backstop; refreshing timeout\n"); + } + + return apple_wdt_resume(dev); +} + +static const struct dev_pm_ops apple_wdt_pm_ops = { + .suspend = pm_sleep_ptr(apple_wdt_suspend), + .resume = pm_sleep_ptr(apple_wdt_resume), + .freeze = pm_sleep_ptr(apple_wdt_freeze), + .thaw = pm_sleep_ptr(apple_wdt_resume), + .poweroff = pm_sleep_ptr(apple_wdt_freeze), + .restore = pm_sleep_ptr(apple_wdt_restore), +}; static const struct of_device_id apple_wdt_of_match[] = { { .compatible = "apple,t8103-wdt" }, diff --git a/include/linux/device/driver.h b/include/linux/device/driver.h index 768a1334c0a1d..82263ec63ceb1 100644 --- a/include/linux/device/driver.h +++ b/include/linux/device/driver.h @@ -247,6 +247,7 @@ driver_find_device_by_acpi_dev(const struct device_driver *drv, const void *adev void driver_deferred_probe_add(struct device *dev); int driver_deferred_probe_check_state(struct device *dev); +void driver_deferred_probe_trigger(void); void driver_init(void); /** diff --git a/include/linux/soc/apple/aura-hibernate.h b/include/linux/soc/apple/aura-hibernate.h new file mode 100644 index 0000000000000..729ced7b3c4cb --- /dev/null +++ b/include/linux/soc/apple/aura-hibernate.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __LINUX_SOC_APPLE_AURA_HIBERNATE_H +#define __LINUX_SOC_APPLE_AURA_HIBERNATE_H + +#include +#include + +struct device; +struct device_node; + +/* A firmware memory-region of a device as this boot's device tree gives it. */ +struct aura_fw_region { + u64 phys; + u64 iova; + u64 size; +}; + +/* + * Declared unconditionally so that Rust drivers can bind to them; without + * CONFIG_APPLE_AURA_HIBERNATE they must not call them. + */ +int aura_hibernate_boot_fw_regions(struct device_node *np, struct aura_fw_region *out, + unsigned int max); +int aura_hibernate_reprobe_after_thaw(struct device *dev); + +#ifdef CONFIG_APPLE_AURA_HIBERNATE +int aura_hibernate_boot_chosen_u64(const char *name, u64 *val); +#else +static inline int aura_hibernate_boot_chosen_u64(const char *name, u64 *val) { return -ENODEV; } +#endif + +#endif diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 52bbf1549b203..2c401a4719972 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -252,6 +252,8 @@ u32 apple_dart_enabled_streams(struct device *dev); int apple_dart_display_keep(struct device *dev, u32 streams, bool save); /* The display streams turned off read disabled and the DART has nothing in flight. */ int apple_dart_display_streams_idle(struct device *dev, u32 streams); +void apple_dart_display_unpowered(struct device *dev); +int apple_dart_display_restore(struct device *dev); /* A GAPF slice released before its coprocessor's CPU domain comes up after a wake. */ int apple_dart_gapf_ready(struct device *dev); /* A display DART whose domain goes off at runtime while others still map into it. */ @@ -295,6 +297,15 @@ static inline u32 apple_dart_enabled_streams(struct device *dev) return 0; } +static inline void apple_dart_display_unpowered(struct device *dev) +{ +} + +static inline int apple_dart_display_restore(struct device *dev) +{ + return 0; +} + static inline int apple_dart_display_keep(struct device *dev, u32 streams, bool save) { return -ENODEV; diff --git a/include/linux/soc/apple/pmp.h b/include/linux/soc/apple/pmp.h index f860b67ad78d7..6adeb193e1b78 100644 --- a/include/linux/soc/apple/pmp.h +++ b/include/linux/soc/apple/pmp.h @@ -55,4 +55,6 @@ struct apple_pmp_commit_stop { }; int apple_pmp_sleep_prepare(const void *data, struct apple_pmp_commit_stop *stop); +/* Rebuild the firmware session after a resume from disk (PM_POST_HIBERNATION). */ +int apple_pmp_restore(const void *data); #endif diff --git a/include/linux/soc/apple/rtkit-helper.h b/include/linux/soc/apple/rtkit-helper.h index 190caf432e098..4c712936e6c15 100644 --- a/include/linux/soc/apple/rtkit-helper.h +++ b/include/linux/soc/apple/rtkit-helper.h @@ -9,4 +9,20 @@ struct device; /* The caller holds a device link to the bound helper supplier. */ bool apple_rtkit_helper_preserves_input(struct device *dev); +/* + * After a resume from disk: the helper took over, in its .restore callback, + * the session that the boot kernel started and left running. Valid from the + * helper's .restore until its next .freeze. + */ +bool apple_rtkit_helper_readopted(struct device *dev); + +/* + * After a resume from disk: the session this helper had started itself was + * found with its co-processor halted (the boot loader stopped it and the boot + * kernel did not start it). Nothing answers until the helper is probed again, + * which starts the co-processor. Valid from the helper's .restore until its + * next .freeze. + */ +bool apple_rtkit_helper_halted_underneath(struct device *dev); + #endif diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 2624e7d25df28..c373a703c0066 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -319,6 +320,13 @@ int apple_rtkit_mbox_restore(struct apple_rtkit *rtk); */ int apple_rtkit_cold_restart(struct apple_rtkit *rtk, int (*start)(void *), void *ctx); +/* + * Returned by apple_rtkit_idle() and apple_rtkit_idle_with() when the AP side is idle + * and the IOP acknowledged a power state other than idle: it is asleep with its memory + * kept. No other error carries this value. + */ +#define APPLE_RTKIT_IDLE_RETAINED (-EALREADY) + /* * Put the co-processor into idle mode */ @@ -403,6 +411,16 @@ int apple_rtkit_m5_saved_send(struct apple_rtkit *rtk, u64 message); int apple_rtkit_m5_saved_ap_power(struct apple_rtkit *rtk, bool on, u64 *sent, u64 *ack); +/* + * The idle notice with interrupts off and one CPU up, where nothing can sleep and the + * receive work doesn't run: the mailbox is polled a bounded number of times, with no + * clock read, and the acknowledgment is taken in the poll. A message on one of the + * client's own endpoints still goes to recv_message_early; one it leaves waits for the + * receive work. @us is about how long the acknowledgment took. The wake's notice is + * apple_rtkit_ap_power() or apple_rtkit_ap_power_noirq(), as after any other. + */ +int apple_rtkit_ap_idle_polled(struct apple_rtkit *rtk, unsigned int *us); + /* * Stop a co-processor for a system sleep that may remove its power: idle, wait * for the status that shows it has finished, then clear the run bit. On an error @@ -583,6 +601,62 @@ struct apple_rtkit *devm_apple_rtkit_init_m5_saved(struct device *dev, void *coo */ void apple_rtkit_adopt_ep(struct apple_rtkit *rtk, u8 ep); +/* + * A shared buffer of a running session, as the co-processor addresses it. + * @kind is one of APPLE_RTKIT_BUF_*. + */ +#define APPLE_RTKIT_BUF_IOREPORT 0 +#define APPLE_RTKIT_BUF_COREANALYTICS 1 +#define APPLE_RTKIT_BUF_CRASHLOG 2 +#define APPLE_RTKIT_BUF_OSLOG 3 +#define APPLE_RTKIT_BUF_KDEBUG0 4 +#define APPLE_RTKIT_BUF_KDEBUG1 5 +#define APPLE_RTKIT_BUF_PMP_AUX 6 +#define APPLE_RTKIT_BUF_SYSLOG 7 +#define APPLE_RTKIT_BUF_COUNT 8 + +struct apple_rtkit_buffer_desc { + u32 kind; + u32 is_mapped; + u64 iova; + u64 size; +}; + +/* + * Describe the shared buffers the co-processor currently holds, in a fixed + * order. Returns the number of entries written, or -ENOSPC if @max is too + * small. + */ +int apple_rtkit_describe_buffers(struct apple_rtkit *rtk, + struct apple_rtkit_buffer_desc *desc, + unsigned int max); + +/* + * Take over, in place, a firmware instance that another kernel started and + * left running with its shared buffers at the IOVAs this session already + * holds (the caller must have checked that with apple_rtkit_describe_buffers() + * against the other kernel's description). Only host-side transient state is + * reset; no message is sent to the co-processor. + */ +int apple_rtkit_readopt(struct apple_rtkit *rtk); + +/* + * Resume from disk. The kernel that loads a hibernation image (the boot + * kernel) can leave a few bytes for the kernel restored from that image in + * memory that the image does not overwrite. Only available with RTKit + * built in; elsewhere put() fails and take() finds nothing. + * + * apple_rtkit_hib_restoring(): true in the boot kernel between + * PM_RESTORE_PREPARE and the jump into the image (or PM_POST_RESTORE), + * i.e. while its devices are quiesced for the image, not frozen for one. + */ +#define APPLE_RTKIT_HIB_HANDOFF_MAX 256 + +bool apple_rtkit_hib_restoring(void); +int apple_rtkit_hib_handoff_put(const char *tag, const void *data, size_t len); +int apple_rtkit_hib_handoff_take(const char *tag, void *data, size_t len); +void apple_rtkit_hib_handoff_drop(const char *tag); + /* * Return the size in bytes of the mapped IOReport shared buffer, or 0 if * none has been allocated for this session. diff --git a/include/linux/suspend.h b/include/linux/suspend.h index 49f8d3a6acc83..4e46a129a8965 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -450,6 +450,18 @@ struct platform_hibernation_ops { void (*recover)(void); }; +/** + * struct hibernation_backstop - Hardware timer that resets a hung hibernation. + * @arm: Start it. Called before the image is created, and on the loading + * kernel once its devices are quiesced, before the jump into the image. + * @disarm: Stop it: the hibernation ended with this kernel still running. + * After a restore, the platform stops it from its own restore path. + */ +struct hibernation_backstop { + int (*arm)(void); + void (*disarm)(void); +}; + #ifdef CONFIG_HIBERNATION /* kernel/power/snapshot.c */ extern void register_nosave_region(unsigned long b, unsigned long e); @@ -465,6 +477,9 @@ extern void hibernation_set_ops(const struct platform_hibernation_ops *ops); extern int hibernate(void); extern bool system_entering_hibernation(void); extern bool hibernation_available(void); +void hibernation_set_platform_check(bool (*blocked)(void), const char *reason); + +void hibernation_set_backstop(const struct hibernation_backstop *backstop); asmlinkage int swsusp_save(void); extern struct pbe *restore_pblist; int pfn_is_nosave(unsigned long pfn); @@ -474,6 +489,22 @@ int hibernate_resume_nonboot_cpu_disable(void); int arch_hibernation_header_save(void *addr, unsigned int max_size); int arch_hibernation_header_restore(void *addr); +#ifdef CONFIG_ARCH_HIBERNATION_CLEAN_IMAGE +/** + * arch_hibernate_clean_image_page - Make a loaded image page visible to devices. + * @pfn: Valid page frame of the image. + * + * Provided by an architecture that sets ARCH_HIBERNATION_CLEAN_IMAGE. + * Called for every image page loaded straight into its original frame, once + * its contents are complete and before it is protected, so that the + * architecture can clean the caches for devices that do not snoop them. + * + * Return: 1 when the page was cleaned, 0 when it was left alone because + * nothing was loaded into it through the linear map. + */ +int arch_hibernate_clean_image_page(unsigned long pfn); +#endif + #else /* CONFIG_HIBERNATION */ static inline void register_nosave_region(unsigned long b, unsigned long e) {} static inline int swsusp_page_is_forbidden(struct page *p) { return 0; } @@ -484,6 +515,7 @@ static inline void hibernation_set_ops(const struct platform_hibernation_ops *op static inline int hibernate(void) { return -ENOSYS; } static inline bool system_entering_hibernation(void) { return false; } static inline bool hibernation_available(void) { return false; } +static inline void hibernation_set_backstop(const struct hibernation_backstop *backstop) {} static inline int hibernate_quiet_exec(int (*func)(void *data), void *data) { return -ENOTSUPP; @@ -496,6 +528,18 @@ bool pm_hibernation_mode_is_suspend(void); static inline bool pm_hibernation_mode_is_suspend(void) { return false; } #endif +#ifdef CONFIG_HIBERNATION +bool pm_hibernate_is_restored(void); +bool pm_hibernate_is_loading(void); +bool pm_hibernate_resume_pending(void); +int pm_hibernate_restored_cold(void); +#else +static inline bool pm_hibernate_is_restored(void) { return false; } +static inline bool pm_hibernate_is_loading(void) { return false; } +static inline bool pm_hibernate_resume_pending(void) { return false; } +static inline int pm_hibernate_restored_cold(void) { return 0; } +#endif + int arch_resume_nosmt(void); #ifdef CONFIG_HIBERNATION_SNAPSHOT_DEV diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 890bf7b447f89..f72499ebac0b4 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -81,6 +81,146 @@ static const struct platform_hibernation_ops *hibernation_ops; static atomic_t hibernate_atomic = ATOMIC_INIT(1); +/* Set when swsusp_arch_suspend() returned in a kernel restored from an image. */ +static bool hibernate_restored; + +/** + * pm_hibernate_is_restored - Whether this kernel was just restored from an image. + * + * Devices get PMSG_RESTORE in the kernel restored from a hibernation image, + * whose hardware went through a boot, and PMSG_RECOVER in the kernel that + * hibernated when hibernation is aborted before the image is created (a device + * failed to freeze, a wakeup event). True from the restore until the next + * hibernation starts (hibernation_snapshot()); meant for code that runs after + * the restore, such as the PM_POST_HIBERNATION notifiers. + */ +bool pm_hibernate_is_restored(void) +{ + return READ_ONCE(hibernate_restored); +} +EXPORT_SYMBOL_GPL(pm_hibernate_is_restored); + +/* + * What the kernel that loads an image leaves for the kernel restored from it. + * It lives in the no-save section, which the image neither saves nor + * overwrites, so the restored kernel reads what the loading kernel wrote, as + * long as both are the same build loaded at the same physical address (which + * the image's header requires). The record carries its own physical address + * and a magic: a record from a kernel loaded elsewhere, or none, reads as + * absent. + */ +struct hibernate_load_record { + u32 magic; + u32 other_boot; + u64 self_phys; +}; + +#define HIBERNATE_LOAD_MAGIC 0x484c4452 /* "HLDR" */ + +static struct hibernate_load_record hibernate_load_record __nosavedata; + +/* Set while hibernate() loads the image it has just written (test_resume). */ +static bool hibernate_loading_own_image; + +/* Whether the restore came from another boot, see pm_hibernate_restored_cold(). */ +static int hibernate_restored_cold = -ENODATA; + +/** + * pm_hibernate_restored_cold - Whether this kernel was restored by another boot. + * + * Meaningful once pm_hibernate_is_restored() is true, under the same lifetime. + * The kernel that loads an image tells the kernel restored from it whether it + * is the kernel that wrote the image (a test_resume load: the machine did not + * boot) or one that was started to resume it (the boot loader and the + * firmware have been through a boot). Whether a particular device lost its + * state across that boot is for its driver to find out. + * + * Return: 1 if the image was loaded by another boot, 0 if this kernel loaded + * its own image or was not restored, -ENODATA if the record of the loading + * kernel is missing. + */ +int pm_hibernate_restored_cold(void) +{ + if (!READ_ONCE(hibernate_restored)) + return 0; + return READ_ONCE(hibernate_restored_cold); +} +EXPORT_SYMBOL_GPL(pm_hibernate_restored_cold); + +/* Set while this kernel loads a hibernation image, see pm_hibernate_is_loading(). */ +static bool hibernate_loading; + +/** + * pm_hibernate_is_loading - Whether this kernel is loading a hibernation image. + * + * True from the PM_RESTORE_PREPARE notification, which starts the loading of an + * image (from the resume path or through the snapshot device), until the + * PM_POST_RESTORE notification that ends it when the image was not restored + * (or the notification chain refused it), and while hibernate() loads the + * image it has just written (test_resume). The devices of the kernel that + * loads an image are quiesced for the jump into the image, not frozen for an + * image of their own; the flag lets drivers tell the two apart in their + * freeze callbacks. The kernel restored from an image reads false: the image + * holds the state of the kernel that created it. + */ +bool pm_hibernate_is_loading(void) +{ + return READ_ONCE(hibernate_loading); +} +EXPORT_SYMBOL_GPL(pm_hibernate_is_loading); + +/** + * hibernate_set_loading - Record that an image is being loaded or no longer is. + * @loading: New value of the flag read by pm_hibernate_is_loading(). + * + * Called from the PM notifier chain helpers around PM_RESTORE_PREPARE and + * PM_POST_RESTORE. + */ +void hibernate_set_loading(bool loading) +{ + WRITE_ONCE(hibernate_loading, loading); +} + +/* + * Set while resume= (or a later /sys/power/resume write) has armed a + * resume-from-disk attempt that has not yet given up. pm_hibernate_is_loading() + * is only true once an image has already been found, which is after a restore + * kernel may already have bound display firmware; this flag covers the earlier + * window so drivers can defer that bind. + */ +static bool hibernate_resume_pending; + +/** + * pm_hibernate_resume_pending - Whether a resume-from-disk attempt is outstanding. + * + * True from the resume= command-line parameter (or from a write to + * /sys/power/resume) until software_resume() has given up. On a successful + * restore this kernel does not continue. Drivers whose probe would start + * firmware or hardware that cannot safely be frozen around the restore jump + * should return -EPROBE_DEFER while this is true; software_resume() triggers + * deferred probing when it clears the flag after a failed attempt. The flag + * stays set if the resume device is not ready at late_initcall time, so a + * later initramfs retry still sees it. + */ +bool pm_hibernate_resume_pending(void) +{ + return READ_ONCE(hibernate_resume_pending); +} +EXPORT_SYMBOL_GPL(pm_hibernate_resume_pending); + +static void hibernate_set_resume_pending(void) +{ + WRITE_ONCE(hibernate_resume_pending, true); +} + +static void hibernate_clear_resume_pending(void) +{ + if (!READ_ONCE(hibernate_resume_pending)) + return; + WRITE_ONCE(hibernate_resume_pending, false); + driver_deferred_probe_trigger(); +} + #ifdef CONFIG_SUSPEND /** * pm_hibernation_mode_is_suspend - Check if hibernation has been set to suspend @@ -107,22 +247,74 @@ bool hibernation_in_progress(void) return !atomic_read(&hibernate_atomic); } -/* - * Apple silicon Macs run firmware on their coprocessors (storage, secure - * enclave, display, always-on processor, system controller, GPU and more). - * Restoring an image means a cold boot through the platform boot chain, which - * restarts that firmware, but most of the Linux drivers have no - * freeze/poweroff/restore path that rebuilds their mailbox, ring and DMA state - * from a cold start. The restored kernel would keep using stale state, so - * writing and restoring images stays disabled on these machines. +static bool (*hibernation_platform_blocked_fn)(void); +static const char *hibernation_platform_blocked_reason; + +/** + * hibernation_set_platform_check - Let platform code refuse hibernation. + * @blocked: Tells whether hibernation is refused on this platform at the time. + * @reason: Why it is refused, for the log. + * + * A platform whose drivers cannot yet restore their devices from an image + * registers a check that is true until the platform has what it needs. While + * it is true, writing and restoring images stays disabled + * (hibernation_available() is false) and @reason is logged at the end of the + * boot. Only one check can be registered. * * pm_test dry runs are allowed (see hibernate()): every pm_test level stops * before create_image() takes a snapshot, so no image is written or restored. * They exercise the freezer and the device freeze/thaw callbacks that a real * implementation needs. */ +void hibernation_set_platform_check(bool (*blocked)(void), const char *reason) +{ + if (WARN_ON_ONCE(hibernation_platform_blocked_fn)) + return; + hibernation_platform_blocked_reason = reason; + hibernation_platform_blocked_fn = blocked; +} + +static const struct hibernation_backstop *hibernation_backstop; + +/** + * hibernation_set_backstop - Register a hardware timer for hung hibernations. + * @backstop: The timer's operations, or NULL to remove them. + */ +void hibernation_set_backstop(const struct hibernation_backstop *backstop) +{ + WRITE_ONCE(hibernation_backstop, backstop); +} +EXPORT_SYMBOL_GPL(hibernation_set_backstop); + +static void hibernation_backstop_arm(const char *when) +{ + const struct hibernation_backstop *backstop = READ_ONCE(hibernation_backstop); + int error; + + if (!backstop) + return; + error = backstop->arm(); + if (error) + pr_err("%s backstop not armed (%d); continuing\n", when, error); +} + +static void hibernation_backstop_disarm(void) +{ + const struct hibernation_backstop *backstop = READ_ONCE(hibernation_backstop); + + if (backstop) + backstop->disarm(); +} + static bool hibernation_platform_blocked(void) { + if (hibernation_platform_blocked_fn) + return hibernation_platform_blocked_fn(); + /* + * Apple silicon Macs run firmware on their coprocessors, which a + * restore restarts; without platform code that says it is handled, + * images stay refused there. + */ return of_machine_is_compatible("apple,arm-platform"); } @@ -142,10 +334,12 @@ bool hibernation_available(void) static int __init hibernation_platform_report(void) { if (hibernation_platform_blocked()) - pr_info("disabled on this platform: coprocessor firmware state is not restored from an image\n"); + pr_info("disabled on this platform: %s\n", + hibernation_platform_blocked_reason ?: + "coprocessor firmware state is not restored from an image"); return 0; } -late_initcall(hibernation_platform_report); +late_initcall_sync(hibernation_platform_report); /** * hibernation_set_ops - Set the global hibernate operations. @@ -346,6 +540,25 @@ __weak int arch_resume_nosmt(void) return 0; } +/** + * hibernate_resume_event - Pick the event that resumes the devices frozen for an image. + * @error: Result of the image creation so far. + * + * Called once the image is created, restored or given up on. in_suspend is + * set only in the kernel that created the image, so a clear one means either + * that this kernel was restored from an image (devices get PMSG_RESTORE, + * their hardware went through a boot) or that the hibernation was aborted + * before the image existed (a device failed to freeze, a wakeup event, a + * pm_test level): the devices were only frozen, and the right event is + * PMSG_RECOVER, as after any other failed freeze. + */ +static pm_message_t hibernate_resume_event(int error) +{ + if (in_suspend) + return error ? PMSG_RECOVER : PMSG_THAW; + return pm_hibernate_is_restored() ? PMSG_RESTORE : PMSG_RECOVER; +} + /** * create_image - Create a hibernation image. * @platform_mode: Whether or not to use the platform driver. @@ -399,6 +612,13 @@ static int create_image(int platform_mode) if (!in_suspend) { events_check_enabled = false; clear_or_poison_free_pages(); + if (hibernate_load_record.magic == HIBERNATE_LOAD_MAGIC && + hibernate_load_record.self_phys == __pa_symbol(&hibernate_load_record)) + WRITE_ONCE(hibernate_restored_cold, !!hibernate_load_record.other_boot); + else + WRITE_ONCE(hibernate_restored_cold, -ENODATA); + hibernate_load_record.magic = 0; + WRITE_ONCE(hibernate_restored, true); } platform_leave(platform_mode); @@ -420,8 +640,7 @@ static int create_image(int platform_mode) Platform_finish: platform_finish(platform_mode); - dpm_resume_start(in_suspend ? - (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE); + dpm_resume_start(hibernate_resume_event(error)); return error; } @@ -438,6 +657,8 @@ int hibernation_snapshot(int platform_mode) int error; pm_suspend_clear_flags(); + WRITE_ONCE(hibernate_restored, false); + WRITE_ONCE(hibernate_restored_cold, -ENODATA); error = platform_begin(platform_mode); if (error) goto Close; @@ -485,8 +706,17 @@ int hibernation_snapshot(int platform_mode) if (error || !in_suspend) swsusp_free(); - msg = in_suspend ? (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE; - dpm_resume(msg); + msg = hibernate_resume_event(error); + if (!in_suspend) { + ktime_t devices_start = ktime_get(); + s64 devices_ms; + + dpm_resume(msg); + devices_ms = ktime_ms_delta(ktime_get(), devices_start); + pr_info("device restore took %lld ms\n", devices_ms); + } else { + dpm_resume(msg); + } if (error || !in_suspend) pm_restore_gfp_mask(); @@ -551,6 +781,9 @@ static int resume_target_kernel(bool platform_mode) save_processor_state(); error = restore_highmem(); if (!error) { + hibernate_load_record.other_boot = !hibernate_loading_own_image; + hibernate_load_record.self_phys = __pa_symbol(&hibernate_load_record); + hibernate_load_record.magic = HIBERNATE_LOAD_MAGIC; error = swsusp_arch_resume(); /* * The code below is only ever reached in case of a failure. @@ -558,6 +791,7 @@ static int resume_target_kernel(bool platform_mode) * swsusp_arch_suspend() was called. */ BUG_ON(!error); + hibernate_load_record.magic = 0; /* * This call to restore_highmem() reverts the changes made by * the previous one. @@ -606,6 +840,13 @@ int hibernation_restore(int platform_mode) console_suspend_all(); error = dpm_suspend_start(PMSG_QUIESCE); if (!error) { + /* + * Arm the backstop once the devices are quiesced (so no driver + * callback stops it) and the image is in memory. It runs on + * across the jump, so a hang in the restore then resets the + * machine within its bound. + */ + hibernation_backstop_arm("restore"); error = resume_target_kernel(platform_mode); /* * The above should either succeed and jump to the new kernel, @@ -615,6 +856,8 @@ int hibernation_restore(int platform_mode) BUG_ON(!error); } dpm_resume_end(PMSG_RECOVER); + /* The image was not restored: this kernel goes on booting. */ + hibernation_backstop_disarm(); console_resume_all(); pm_restore_console(); return error; @@ -773,7 +1016,25 @@ static int load_image_and_restore(void) goto Unlock; } - error = swsusp_read(&flags); + { + ktime_t read_start = ktime_get(); + + error = swsusp_read(&flags); + pr_info("image read in %lld ms (ret %d)\n", + ktime_ms_delta(ktime_get(), read_start), error); + } + if (!error) { + /* + * The image is in memory now. Clear its on-disk signature + * before the device restore, so that a restore which hangs + * (for example a co-processor that does not come back after + * the cold boot) cannot leave a valid image for the next boot + * to resume into the same hang. swsusp_close() releases the + * resume device, so do it while that is still open. + */ + if (swsusp_invalidate_sig()) + pr_warn("could not invalidate the image signature; a failed restore may repeat\n"); + } swsusp_close(); if (!error) error = hibernation_restore(flags & SF_PLATFORM_MODE); @@ -838,6 +1099,7 @@ int hibernate(void) } pr_info("hibernation entry\n"); + hibernation_backstop_arm("entry"); pm_prepare_console(); error = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION); if (error) @@ -895,14 +1157,23 @@ int hibernate(void) flags |= SF_COMPRESSION_ALG_LZO; } - pm_pr_dbg("Writing hibernation image.\n"); - error = swsusp_write(flags); + pr_info("writing hibernation image\n"); + { + ktime_t write_start = ktime_get(); + + error = swsusp_write(flags); + pr_info("image written in %lld ms (ret %d)\n", + ktime_ms_delta(ktime_get(), write_start), error); + } swsusp_free(); if (!error) { + pr_info("image written, powering down\n"); if (hibernation_mode == HIBERNATION_TEST_RESUME) snapshot_test = true; else power_down(); + } else { + pr_err("image write failed (%d)\n", error); } in_suspend = 0; pm_restore_gfp_mask(); @@ -917,8 +1188,31 @@ int hibernate(void) if (snapshot_test) { pm_pr_dbg("Checking hibernation image\n"); error = swsusp_check(false); - if (!error) + if (!error) { + /* + * The tasks are still frozen from the snapshot, so + * nothing has cleared a wakeup that a wake IRQ latched + * while the image was created and written. Clear it as + * freeze_processes() does on the resume path, or the + * QUIESCE of the devices fails with -EBUSY. + */ + pm_wakeup_clear(0); + /* + * This kernel loads the image now, as the resume path's + * PM_RESTORE_PREPARE would mark it, so drivers quiesce + * for the jump into it as they do there. + */ + hibernate_loading_own_image = true; + hibernate_set_loading(true); error = load_image_and_restore(); + hibernate_set_loading(false); + hibernate_loading_own_image = false; + } + /* + * Still here, so the image was not restored, and the swap + * pages that hold it are allocated in this kernel's swap map. + */ + swsusp_free_image_swap(); } thaw_processes(); @@ -932,6 +1226,12 @@ int hibernate(void) pm_restore_console(); hibernate_release(); Unlock: + /* + * Back in the running system: the image was not written or this is a + * test resume. After a real restore the watchdog's restore callback + * has already disarmed the backstop. + */ + hibernation_backstop_disarm(); unlock_system_sleep(sleep_flags); pr_info("hibernation exit\n"); @@ -1142,6 +1442,7 @@ static int software_resume(void) Unlock: mutex_unlock(&system_transition_mutex); pm_pr_dbg("Hibernation image not present or could not be loaded.\n"); + hibernate_clear_resume_pending(); return error; Close_Finish: swsusp_close(); @@ -1168,8 +1469,10 @@ static int __init software_resume_initcall(void) /* * If the user said "noresume".. bail out early. */ - if (noresume || !hibernation_available()) + if (noresume || !hibernation_available()) { + hibernate_clear_resume_pending(); return 0; + } if (!swsusp_resume_device) { int error = find_resume_device(); @@ -1364,6 +1667,7 @@ static ssize_t resume_store(struct kobject *kobj, struct kobj_attribute *attr, pm_pr_dbg("Configured hibernation resume from disk to %u\n", swsusp_resume_device); noresume = 0; + hibernate_set_resume_pending(); software_resume(); return n; } @@ -1465,6 +1769,7 @@ static int __init resume_setup(char *str) return 1; strscpy(resume_file, str); + hibernate_set_resume_pending(); return 1; } @@ -1485,11 +1790,13 @@ static int __init hibernate_setup(char *str) { if (!strncmp(str, "noresume", 8)) { noresume = 1; + hibernate_clear_resume_pending(); } else if (!strncmp(str, "nocompress", 10)) { nocompress = 1; } else if (!strncmp(str, "no", 2)) { noresume = 1; nohibernate = 1; + hibernate_clear_resume_pending(); } else if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX) && !strncmp(str, "protect_image", 13)) { enable_restore_image_protection(); @@ -1500,6 +1807,7 @@ static int __init hibernate_setup(char *str) static int __init noresume_setup(char *str) { noresume = 1; + hibernate_clear_resume_pending(); return 1; } @@ -1522,6 +1830,7 @@ static int __init nohibernate_setup(char *str) { noresume = 1; nohibernate = 1; + hibernate_clear_resume_pending(); return 1; } @@ -1537,10 +1846,15 @@ static const char * const comp_alg_enabled[] = { static int hibernate_compressor_param_set(const char *compressor, const struct kernel_param *kp) { + unsigned int sleep_flags; int index, ret; - if (!mutex_trylock(&system_transition_mutex)) - return -EBUSY; + /* + * Wait for a holder of the transition lock (another sleep transition, or + * a driver loading firmware under lock_system_sleep()) instead of + * failing with -EBUSY, as the other hibernation knobs in sysfs do. + */ + sleep_flags = lock_system_sleep(); index = sysfs_match_string(comp_alg_enabled, compressor); if (index >= 0) { @@ -1551,7 +1865,7 @@ static int hibernate_compressor_param_set(const char *compressor, ret = index; } - mutex_unlock(&system_transition_mutex); + unlock_system_sleep(sleep_flags); if (ret) pr_debug("Cannot set specified compressor %s\n", diff --git a/kernel/power/main.c b/kernel/power/main.c index 5429e9f19b655..ccced400c15c7 100644 --- a/kernel/power/main.c +++ b/kernel/power/main.c @@ -169,14 +169,25 @@ int pm_notifier_call_chain_robust(unsigned long val_up, unsigned long val_down) { int ret; + if (val_up == PM_RESTORE_PREPARE) + hibernate_set_loading(true); + ret = blocking_notifier_call_chain_robust(&pm_chain_head, val_up, val_down, NULL); + if (ret && val_up == PM_RESTORE_PREPARE) + hibernate_set_loading(false); + return notifier_to_errno(ret); } int pm_notifier_call_chain(unsigned long val) { - return blocking_notifier_call_chain(&pm_chain_head, val, NULL); + int ret = blocking_notifier_call_chain(&pm_chain_head, val, NULL); + + if (val == PM_POST_RESTORE) + hibernate_set_loading(false); + + return ret; } /* If set, devices may be suspended and resumed asynchronously. */ diff --git a/kernel/power/power.h b/kernel/power/power.h index 75b63843886ee..d9d3353900c5f 100644 --- a/kernel/power/power.h +++ b/kernel/power/power.h @@ -77,6 +77,7 @@ static inline void enable_restore_image_protection(void) {} #endif /* CONFIG_STRICT_KERNEL_RWX */ extern bool hibernation_in_progress(void); +void hibernate_set_loading(bool loading); #else /* !CONFIG_HIBERNATION */ @@ -84,6 +85,7 @@ static inline void hibernate_reserved_size_init(void) {} static inline void hibernate_image_size_init(void) {} static inline bool hibernation_in_progress(void) { return false; } +static inline void hibernate_set_loading(bool loading) {} #endif /* !CONFIG_HIBERNATION */ #define power_attr(_name) \ @@ -201,6 +203,8 @@ extern void swsusp_free(void); extern int swsusp_read(unsigned int *flags_p); extern int swsusp_write(unsigned int flags); void swsusp_close(void); +int swsusp_invalidate_sig(void); +void swsusp_free_image_swap(void); #ifdef CONFIG_SUSPEND extern int swsusp_unmark(void); #else diff --git a/kernel/power/snapshot.c b/kernel/power/snapshot.c index b209712cb2c3a..4a37d9fa79ff3 100644 --- a/kernel/power/snapshot.c +++ b/kernel/power/snapshot.c @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -2750,6 +2751,36 @@ static void *get_buffer(struct memory_bitmap *bm, struct chain_allocator *ca) return pbe->address; } +#ifdef CONFIG_ARCH_HIBERNATION_CLEAN_IMAGE +/* + * Most image pages are loaded straight into their original frames through + * the cacheable linear map (only conflicting pages go through restore_pblist, + * whose copy cleans them). Where devices read memory without snooping the CPU + * caches, a later eviction of a dirty line would overwrite what a device wrote + * since: let the architecture clean each such page once it is complete, while + * the loader still waits for the next one, rather than all of them in a pass + * after the load. + */ +static unsigned long nr_cleaned_pages; + +static void swsusp_clean_loaded_page(void *addr) +{ + unsigned long pfn = memory_bm_get_current(&orig_bm); + + if (addr == page_address(pfn_to_page(pfn))) + nr_cleaned_pages += arch_hibernate_clean_image_page(pfn); +} + +static void swsusp_clean_report(void) +{ + pr_debug("%lu image pages cleaned as they were loaded\n", nr_cleaned_pages); + nr_cleaned_pages = 0; +} +#else +static inline void swsusp_clean_loaded_page(void *addr) {} +static inline void swsusp_clean_report(void) {} +#endif + /** * snapshot_write_next - Get the address to store the next image page. * @handle: Snapshot handle structure to guide the writing. @@ -2824,6 +2855,7 @@ int snapshot_write_next(struct snapshot_handle *handle) } } else { copy_last_highmem_page(); + swsusp_clean_loaded_page(handle->buffer); error = hibernate_restore_protect_page(handle->buffer); if (error) return error; @@ -2854,6 +2886,7 @@ int snapshot_write_next(struct snapshot_handle *handle) */ int snapshot_write_finalize(struct snapshot_handle *handle) { + bool loaded; int error; /* @@ -2867,10 +2900,15 @@ int snapshot_write_finalize(struct snapshot_handle *handle) if (error) return error > 0 ? -ENODATA : error; } + loaded = handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages + nr_zero_pages; copy_last_highmem_page(); + /* while orig_bm still points at the last page: recycling overwrites it */ + if (loaded) + swsusp_clean_loaded_page(handle->buffer); error = hibernate_restore_protect_page(handle->buffer); /* Do that only if we have loaded the image entirely */ - if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages + nr_zero_pages) { + if (loaded) { + swsusp_clean_report(); memory_bm_recycle(&orig_bm); free_highmem_data(); } diff --git a/kernel/power/swap.c b/kernel/power/swap.c index c78f1593600bb..febb4dcf933e1 100644 --- a/kernel/power/swap.c +++ b/kernel/power/swap.c @@ -483,15 +483,41 @@ static int flush_swap_writer(struct swap_map_handle *handle) static int swap_writer_finish(struct swap_map_handle *handle, unsigned int flags, int error) { + bool marked = false; + int ret; + if (!error) { pr_info("S"); error = mark_swapfiles(handle, flags); + marked = true; pr_cont("|\n"); - flush_swap_writer(handle); + ret = flush_swap_writer(handle); + if (!error) + error = ret; + /* + * Make the image durable now: otherwise the device cache is + * flushed only by the device shutdown in the power-off that + * follows, and a platform whose power-off does not get that far + * loses the image. + */ + ret = blkdev_issue_flush(file_bdev(hib_resume_bdev_file)); + if (!error) + error = ret; } - if (error) - free_all_swap_pages(root_swap); + /* + * Once the header write was attempted, the signature may be on the + * disk even though the image is not complete or not durable. Release + * the image's swap pages only after the signature is durably gone: + * otherwise swap can reuse them while a later boot still resumes from + * them. If that fails, keep them reserved until the next boot. + */ + if (error) { + if (marked && swsusp_invalidate_sig()) + pr_err("image not saved and its signature could not be cleared; its swap pages stay reserved\n"); + else + free_all_swap_pages(root_swap); + } release_swap_writer(handle); swsusp_close(); @@ -1583,10 +1609,15 @@ int swsusp_check(bool exclusive) if (!memcmp(HIBERNATE_SIG, swsusp_header->sig, 10)) { memcpy(swsusp_header->sig, swsusp_header->orig_sig, 10); swsusp_header_flags = swsusp_header->flags; - /* Reset swap signature now */ - error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC, - swsusp_resume_block, - swsusp_header); + /* + * Reset swap signature now. FUA: a REQ_SYNC write + * can sit in a volatile device cache, and a hard + * power-off of a hung restore then loses it and the + * next boot resumes the same image again. + */ + error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_FUA, + swsusp_resume_block, + swsusp_header); } else { error = -EINVAL; } @@ -1625,6 +1656,72 @@ void swsusp_close(void) fput(hib_resume_bdev_file); } +/* + * Clear the on-disk image signature without freeing the swap pages. + * Called on the resume path right after the image is read into memory and + * before the device restore, so a restore that hangs (a co-processor that does + * not come back after a cold boot) cannot leave a valid image that the next + * boot resumes into the same hang. Unlike swsusp_unmark() this keeps the swap + * pages: the resuming kernel is about to jump into the restored image, and + * freeing swap here would desync the restored kernel's swap accounting. + * + * Needs the resume device open. Returns 0 only when the header durably carries + * no image signature, whether this call or an earlier one cleared it. + */ +int swsusp_invalidate_sig(void) +{ + int error; + + error = hib_submit_io_sync(REQ_OP_READ, swsusp_resume_block, swsusp_header); + if (error) + return error; + if (!memcmp(HIBERNATE_SIG, swsusp_header->sig, 10)) { + memcpy(swsusp_header->sig, swsusp_header->orig_sig, 10); + error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_FUA, + swsusp_resume_block, swsusp_header); + if (error) + return error; + } + /* + * An earlier reset (swsusp_check()'s) may still sit in the device's + * volatile cache, and a device may ignore FUA: flush either way. + */ + return blkdev_issue_flush(file_bdev(hib_resume_bdev_file)); +} + +/** + * swsusp_free_image_swap - Free the swap pages of an image that was not restored. + * + * The pages that hold an image written by this kernel are allocated in its own + * swap map. If this kernel goes on instead of the image (a test_resume restore + * that failed or never started), nothing frees them, and swapoff then waits + * for them forever. + * + * The signature that points at them may still be on the disk: the header read + * or the signature reset in swsusp_check() can fail. Free the pages only once + * the signature is durably gone, or a later boot resumes an image whose pages + * ordinary swap has reused. If it cannot be cleared, keep them reserved. + */ +void swsusp_free_image_swap(void) +{ + int error; + + hib_resume_bdev_file = bdev_file_open_by_dev(swsusp_resume_device, + BLK_OPEN_READ, NULL, NULL); + if (IS_ERR(hib_resume_bdev_file)) { + error = PTR_ERR(hib_resume_bdev_file); + } else { + error = swsusp_invalidate_sig(); + swsusp_close(); + } + if (error) { + pr_err("image signature could not be cleared (%d); its swap pages stay reserved\n", + error); + return; + } + free_all_swap_pages(root_swap); +} + /** * swsusp_unmark - Unmark swsusp signature in the resume device * diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index d15860f9f11c7..ea75281ce77d9 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -108,6 +108,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/suspend.c b/rust/helpers/suspend.c index 12e05f94de7c4..e1c580a9eb372 100644 --- a/rust/helpers/suspend.c +++ b/rust/helpers/suspend.c @@ -21,3 +21,10 @@ __rust_helper bool rust_helper_pm_suspend_no_platform(void) { return pm_suspend_no_platform(); } + +#ifndef CONFIG_HIBERNATION +__rust_helper bool rust_helper_pm_hibernate_is_restored(void) +{ + return pm_hibernate_is_restored(); +} +#endif diff --git a/rust/kernel/soc/apple/rtkit.rs b/rust/kernel/soc/apple/rtkit.rs index 22d0bf9bbcfc3..806c0a4a8edff 100644 --- a/rust/kernel/soc/apple/rtkit.rs +++ b/rust/kernel/soc/apple/rtkit.rs @@ -376,6 +376,15 @@ impl RtKit { to_result(unsafe { bindings::apple_rtkit_boot_or_wake(self.rtk, self_ack_ms) }) } + /// Re-initialises a stopped session so a fresh HELLO/EPMAP boot can be + /// accepted again (hibernation restore of a coprocessor the boot loader + /// cold-restarted): detaches RX, frees inherited buffers, zeroes the + /// endpoint bitmap, reinitialises the completions and restarts the mailbox. + pub fn reinit(self: Pin<&mut Self>) -> Result { + // SAFETY: `rtk` is valid per the type invariant. + to_result(unsafe { bindings::apple_rtkit_reinit(self.rtk) }) + } + /// Waits for the RTKit coprocessor to finish booting. pub fn boot(self: Pin<&mut Self>) -> Result { // SAFETY: `rtk` is valid per the type invariant. diff --git a/sound/soc/apple/mca.c b/sound/soc/apple/mca.c index 01a22f3f94cad..87ec950b814b4 100644 --- a/sound/soc/apple/mca.c +++ b/sound/soc/apple/mca.c @@ -1715,12 +1715,12 @@ static u8 mca_cluster_saved_kind(struct mca_cluster *cl) return 0; } -static int __maybe_unused apple_mca_suspend_late(struct device *dev) +static int apple_mca_save(struct device *dev) { struct mca_data *mca = dev_get_drvdata(dev); int i, j, n = 0; - if (!pm_suspend_via_firmware() || pm_runtime_status_suspended(dev)) + if (pm_runtime_status_suspended(dev)) return 0; for (i = 0; i < mca->nclusters; i++) { @@ -1748,12 +1748,12 @@ static int __maybe_unused apple_mca_suspend_late(struct device *dev) return 0; } -static int __maybe_unused apple_mca_resume_early(struct device *dev) +static int apple_mca_restore(struct device *dev) { struct mca_data *mca = dev_get_drvdata(dev); int i, j, n = 0; - if (!pm_resume_via_firmware() || pm_runtime_status_suspended(dev)) + if (pm_runtime_status_suspended(dev)) return 0; for (i = 0; i < mca->nclusters; i++) { @@ -1794,8 +1794,67 @@ static int __maybe_unused apple_mca_resume_early(struct device *dev) return 0; } +static void apple_mca_discard_saved(struct device *dev) +{ + struct mca_data *mca = dev_get_drvdata(dev); + int i; + + for (i = 0; i < mca->nclusters; i++) + mca->clusters[i].saved_kind = 0; +} + +static int __maybe_unused apple_mca_suspend_late(struct device *dev) +{ + if (!pm_suspend_via_firmware()) + return 0; + + return apple_mca_save(dev); +} + +static int __maybe_unused apple_mca_resume_early(struct device *dev) +{ + if (!pm_resume_via_firmware()) + return 0; + + return apple_mca_restore(dev); +} + +#ifdef CONFIG_HIBERNATION +static int apple_mca_freeze_late(struct device *dev) +{ + return apple_mca_save(dev); +} + +static int apple_mca_thaw_early(struct device *dev) +{ + apple_mca_discard_saved(dev); + return 0; +} + +static int apple_mca_restore_early(struct device *dev) +{ + if (!pm_hibernate_restored_cold()) { + apple_mca_discard_saved(dev); + return 0; + } + return apple_mca_restore(dev); +} +#endif + static const struct dev_pm_ops apple_mca_pm_ops = { - LATE_SYSTEM_SLEEP_PM_OPS(apple_mca_suspend_late, apple_mca_resume_early) + .suspend_late = pm_sleep_ptr(apple_mca_suspend_late), + .resume_early = pm_sleep_ptr(apple_mca_resume_early), +#ifdef CONFIG_HIBERNATION + .freeze_late = apple_mca_freeze_late, + .thaw_early = apple_mca_thaw_early, + .poweroff_late = apple_mca_freeze_late, + .restore_early = apple_mca_restore_early, +#else + .freeze_late = pm_sleep_ptr(apple_mca_suspend_late), + .thaw_early = pm_sleep_ptr(apple_mca_resume_early), + .poweroff_late = pm_sleep_ptr(apple_mca_suspend_late), + .restore_early = pm_sleep_ptr(apple_mca_resume_early), +#endif }; static struct platform_driver apple_mca_driver = { diff --git a/sound/soc/codecs/cs42l84.c b/sound/soc/codecs/cs42l84.c index 0b64d899be873..b95fead1e98db 100644 --- a/sound/soc/codecs/cs42l84.c +++ b/sound/soc/codecs/cs42l84.c @@ -1721,15 +1721,11 @@ static void cs42l84_sleep_quiesce(struct cs42l84_private *cs42l84, struct device * after the wake release it as the probe does and write everything back from * the cache. Other sleep states leave the codec alone. */ -static int cs42l84_suspend(struct device *dev) +static int cs42l84_power_down(struct device *dev) { struct i2c_client *i2c_client = to_i2c_client(dev); struct cs42l84_private *cs42l84 = i2c_get_clientdata(i2c_client); - if (!pm_suspend_via_firmware() && - pm_suspend_target_state != PM_SUSPEND_TO_IDLE) - return 0; - /* Still down from a resume that failed. */ if (cs42l84->sleep_reset) return 0; @@ -1750,6 +1746,15 @@ static int cs42l84_suspend(struct device *dev) return 0; } +static int cs42l84_suspend(struct device *dev) +{ + if (!pm_suspend_via_firmware() && + pm_suspend_target_state != PM_SUSPEND_TO_IDLE) + return 0; + + return cs42l84_power_down(dev); +} + static int cs42l84_resume(struct device *dev) { struct i2c_client *i2c_client = to_i2c_client(dev); @@ -1873,7 +1878,14 @@ static int cs42l84_resume(struct device *dev) return ret; } -static DEFINE_SIMPLE_DEV_PM_OPS(cs42l84_pm_ops, cs42l84_suspend, cs42l84_resume); +static const struct dev_pm_ops cs42l84_pm_ops = { + .suspend = pm_sleep_ptr(cs42l84_suspend), + .resume = pm_sleep_ptr(cs42l84_resume), + .freeze = pm_sleep_ptr(cs42l84_power_down), + .thaw = pm_sleep_ptr(cs42l84_resume), + .poweroff = pm_sleep_ptr(cs42l84_power_down), + .restore = pm_sleep_ptr(cs42l84_resume), +}; static const struct of_device_id cs42l84_of_match[] = { { .compatible = "cirrus,cs42l84", }, diff --git a/sound/soc/codecs/tas2764.c b/sound/soc/codecs/tas2764.c index de18e527c1987..a262903ba8d95 100644 --- a/sound/soc/codecs/tas2764.c +++ b/sound/soc/codecs/tas2764.c @@ -482,10 +482,13 @@ static int tas2764_codec_resume(struct snd_soc_component *component) * A firmware-driven (deep) sleep powers the SoC's pin controller off, * so the group's SDZ line drops while asleep and every amp comes back * from a power-on reset when the pin controller restores the line - * (its resume_noirq, before this). s2idle keeps the line and the - * amps' registers and stays on the path below. + * (its resume_noirq, before this). A restore from hibernation is the + * same: the rails were off, and pm_resume_via_firmware() is false. + * s2idle keeps the line and the amps' registers and stays on the path + * below, unless the amp itself shows a reset. */ - bool power_on = (tas2764->sdz_group || tas2764->sdz_gpio) && pm_resume_via_firmware(); + bool power_on = (tas2764->sdz_group || tas2764->sdz_gpio) && + (pm_resume_via_firmware() || pm_hibernate_restored_cold()); int ret; if (!tas2764->sdz_group) { diff --git a/tools/asahi/apple-dart-fw-tests.py b/tools/asahi/apple-dart-fw-tests.py index aaa5247fee767..dedb2423739ae 100644 --- a/tools/asahi/apple-dart-fw-tests.py +++ b/tools/asahi/apple-dart-fw-tests.py @@ -5,7 +5,7 @@ import argparse, hashlib, json, re, subprocess ROOT=Path(__file__).resolve().parents[2] NAMES=('apple_dart_fw_handoff_enabled','apple_dart_pte_to_paddr','apple_dart_fw_table_page','apple_dart_fw_table_ram','apple_dart_fw_table_pte','apple_dart_fw_table_decode','apple_dart_fw_tree_table','apple_dart_fw_slot_owned','apple_dart_fw_leaf_decode','apple_dart_fw_mapping_matches','apple_dart_fw_page_matches','apple_dart_fw_slot_mirrors','apple_dart_publish_root','apple_dart_retire_root','apple_dart_free_fw_root','apple_dart_snapshot_fw_root','apple_dart_free_fw_tree','apple_dart_fw_tree_phys','apple_dart_fw_slot_foreign','apple_dart_domain_uses_fw','apple_dart_check_fw_map','apple_dart_inherited_phys_prot','apple_dart_inherited_phys','apple_dart_fw_slot_range','apple_dart_get_fw_resv_regions','apple_dart_fw_invalidate','apple_dart_hw_unmap_locked_ttbr','apple_dart_retire_error','apple_dart_t8110_hw_invalidate_tlb','apple_dart_release_device','apple_dart_domain_free') -CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-dart1-format','handoff-unversioned','handoff-version-0201','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') +CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','adopt-foreign','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-dart1-format','handoff-unversioned','handoff-version-0201','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') def function(s,name): match=re.search(r'^static[^;{}]*\b'+re.escape(name)+r'\([^;{}]*\)\s*\{',s,re.M) if not match:return None diff --git a/tools/asahi/apple-dart-fw/fixture.c b/tools/asahi/apple-dart-fw/fixture.c index 7ccecc109ffb3..8630a404a94fa 100644 --- a/tools/asahi/apple-dart-fw/fixture.c +++ b/tools/asahi/apple-dart-fw/fixture.c @@ -63,6 +63,8 @@ struct apple_dart { u64 *locked_ttbr[2][4], *locked_owned[2][4]; struct apple_dart_fw_root *locked_fw[2][4]; struct apple_dart_fw_tree *locked_fw_tree[2]; + phys_addr_t locked_phys[2][4]; + struct io_pgtable_cfg *locked_cfg[2]; bool display_dark, display_tlb_stale; DECLARE_BITMAP(display_tcr_four, 64); int lock, locked_retire_err[2]; @@ -129,6 +131,8 @@ static void pm_runtime_put(struct device*d){pm_puts++;} static void free_io_pgtable_ops(void*ops){assert(ops);pgtable_frees++;} /* No borrowed display roots here; the DCP paths are covered elsewhere. */ static bool apple_dart_has_borrowed(struct apple_dart*d){return false;} +/* No hibernation restore is pending in these controls. */ +static bool apple_dart_restore_deferred(struct apple_dart*d){return false;} static int apple_dart_dcp_invalidate_tlb_gated(struct apple_dart_stream_map*m){abort();} /* No J713 sleep owns these DARTs: releasing their state is always allowed. */ static void apple_dart_sleep_release_failed(void) @@ -340,13 +344,14 @@ int main(int argc,char**argv){ assert(d.locked_retire_err[0]==(timeout?-ETIMEDOUT:0)); assert(pgtable_frees==!timeout&&errors_logged==timeout&&warnings_logged==timeout); } - else if(!strcmp(c,"mirror")){assert(!apple_dart_publish_root(&d,live,owned,ours,&fw,2));assert(live[0]==0x1401&&owned[0]==0);} - else if(!strcmp(c,"changed-leaf")){assert(!apple_dart_publish_root(&d,live,owned,ours,&fw,2));firmware_leaf[0]=leaf(0xc000);assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2)==-EBUSY);} - else if(!strcmp(c,"wrong-permission")){firmware_leaf[0]|=4;assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2)==-EBUSY);} - else if(!strcmp(c,"wrong-physical")){firmware_leaf[0]=leaf(0xc000);assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2)==-EBUSY);} - else if(!strcmp(c,"malformed-leaf")){firmware_leaf[0]|=BIT_ULL(60);assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2)==-EBUSY);} - else if(!strcmp(c,"vacant")){ours[0]=0;ours[1]=0x801;assert(!apple_dart_publish_root(&d,live,owned,ours,&fw,2));assert(live[0]==0x1401&&live[1]==0x801&&owned[1]==0x801);} - else if(!strcmp(c,"changed-owner")){live[0]=0x1801;assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2)==-EBUSY);assert(!owned[0]);} + else if(!strcmp(c,"mirror")){assert(!apple_dart_publish_root(&d,live,owned,ours,&fw,2,false));assert(live[0]==0x1401&&owned[0]==0);} + else if(!strcmp(c,"changed-leaf")){assert(!apple_dart_publish_root(&d,live,owned,ours,&fw,2,false));firmware_leaf[0]=leaf(0xc000);assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2,false)==-EBUSY);} + else if(!strcmp(c,"wrong-permission")){firmware_leaf[0]|=4;assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2,false)==-EBUSY);} + else if(!strcmp(c,"wrong-physical")){firmware_leaf[0]=leaf(0xc000);assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2,false)==-EBUSY);} + else if(!strcmp(c,"malformed-leaf")){firmware_leaf[0]|=BIT_ULL(60);assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2,false)==-EBUSY);} + else if(!strcmp(c,"vacant")){ours[0]=0;ours[1]=0x801;assert(!apple_dart_publish_root(&d,live,owned,ours,&fw,2,false));assert(live[0]==0x1401&&live[1]==0x801&&owned[1]==0x801);} + else if(!strcmp(c,"changed-owner")){live[0]=0x1801;assert(apple_dart_publish_root(&d,live,owned,ours,&fw,2,false)==-EBUSY);assert(!owned[0]);} + else if(!strcmp(c,"adopt-foreign")){live[0]=0x1801;assert(!apple_dart_publish_root(&d,live,owned,ours,&fw,2,true));assert(live[0]==ours[0]&&owned[0]==ours[0]);} else if(!strcmp(c,"retire")){owned[1]=0x801;live[1]=0xc01;apple_dart_retire_root(live,owned,2);assert(live[0]==0x1401&&live[1]==0xc01&&!owned[1]);} else if(!strcmp(c,"subtree-free-partial")){ /* A failed allocation leaves any of the four arrays missing: freeing must not touch them. */ diff --git a/tools/asahi/apple-dart-range-tests.py b/tools/asahi/apple-dart-range-tests.py index f8c5d0f07d217..d9eb4afbad617 100644 --- a/tools/asahi/apple-dart-range-tests.py +++ b/tools/asahi/apple-dart-range-tests.py @@ -58,9 +58,11 @@ def main(): static u64 seen_first, seen_last; static int pm_runtime_resume_and_get(void *dev) { if (power_error && !dev) return power_error; powered++; return 0; } static void pm_runtime_put(void *dev) { assert(powered>0); powered--; } -static int apple_dart_hw_sync_locked(struct io_pgtable_cfg *cfg, struct apple_dart_stream_map *stream, bool invalidate) { - assert(invalidate); syncs++; return sync_error; +static int apple_dart_hw_sync_locked(struct io_pgtable_cfg *cfg, struct apple_dart_stream_map *stream, bool invalidate, bool adopt) { + assert(invalidate && !adopt); syncs++; return sync_error; } +/* No hibernation restore is pending in these controls. */ +static bool apple_dart_restore_deferred(struct apple_dart *dart) { return false; } static int apple_dart_t8110_hw_tlb_command_range(struct apple_dart_stream_map *stream, int command, bool range, u64 first, u64 last) { assert(command==1 && range); ranges++; seen_first=first; seen_last=last; return range_error; diff --git a/tools/asahi/apple-wdt-tests.py b/tools/asahi/apple-wdt-tests.py index a1a4fa53cb7a7..5746e8a244b31 100755 --- a/tools/asahi/apple-wdt-tests.py +++ b/tools/asahi/apple-wdt-tests.py @@ -60,7 +60,13 @@ def show(ref, path): def extract_body(source): start = source.index('#define APPLE_WDT_WD0_CUR_TIME') - end = source.index('static DEFINE_SIMPLE_DEV_PM_OPS') + for marker in ('static const struct dev_pm_ops apple_wdt_pm_ops', + 'static DEFINE_SIMPLE_DEV_PM_OPS'): + if marker in source: + end = source.index(marker) + break + else: + raise ValueError('apple_wdt.c: no PM ops table') return source[start:end] @@ -103,6 +109,7 @@ def apply_mutation(body, t6050_helpers, mutation): return body.replace(needle, '\t/* omitted IRQ_STATUS clear */'), t6050_helpers if mutation == 'reconfig-before-bark': old = ('\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\t(void)readl(wdt->regs + APPLE_WDT_WD2_CTRL);\n' '\twritel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME);\n' '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME);\n' '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);\n' @@ -114,6 +121,7 @@ def apply_mutation(body, t6050_helpers, mutation): raise SystemExit(f'mutation {mutation}: target pattern not found') new = ('\tapple_wdt_enable_reconfig(wdt);\n' '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\t(void)readl(wdt->regs + APPLE_WDT_WD2_CTRL);\n' '\twritel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME);\n' '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME);\n' '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);\n' @@ -147,21 +155,19 @@ def apply_mutation(body, t6050_helpers, mutation): '\t}\n' + reg_block + '\treturn 0;') return mut, t6050_helpers if mutation == 'hwrunning-after-arm': - old = ('\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);\n' - '\t\t\tapple_wdt_wd2_arm(wdt,\n' - '\t\t\t\t\t apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout));') + old = ('\t\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);\n' + '\t\t\t\tapple_wdt_wd2_arm(wdt, apple_wdt_timeout_ticks(wdt, s));') if old not in body: raise SystemExit(f'mutation {mutation}: target pattern not found') - new = ('\t\t\tapple_wdt_wd2_arm(wdt,\n' - '\t\t\t\t\t apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout));\n' - '\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);') + new = ('\t\t\t\tapple_wdt_wd2_arm(wdt, apple_wdt_timeout_ticks(wdt, s));\n' + '\t\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);') return body.replace(old, new), t6050_helpers if mutation == 'no-wd1-adopt': - old = ('\t\tarmed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) ||\n' - '\t\t\t(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));') + old = ('\t\t\tarmed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) ||\n' + '\t\t\t\t(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));') if old not in body: raise SystemExit(f'mutation {mutation}: target pattern not found') - new = '\t\tarmed = !!(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));' + new = '\t\t\tarmed = !!(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));' return body.replace(old, new), t6050_helpers if mutation == 'no-t6050-wake-restore': old = ('\tif (s->aon_wdt_marked) {\n' @@ -226,6 +232,32 @@ def apply_mutation(body, t6050_helpers, mutation): return (*addr & (1UL << nr)) != 0; } +static inline void clear_bit(unsigned int nr, volatile unsigned long *addr) +{ + *addr &= ~(1UL << nr); +} + +#define module_param(name, type, perm) _Static_assert(1, #name) +#define MODULE_PARM_DESC(name, desc) _Static_assert(1, desc) + +/* The hibernation backstop's timebase; no control here enters a hibernation. */ +static u32 mock_timer_rate = 24000000; +static u64 mock_counter; +static long long mock_boottime; +static inline u32 arch_timer_get_rate(void) { return mock_timer_rate; } +static inline u64 arch_timer_read_counter(void) { return mock_counter; } +static inline long long ktime_get_boottime_seconds(void) { return mock_boottime; } + +struct hibernation_backstop { + int (*arm)(void); + void (*disarm)(void); +}; +static const struct hibernation_backstop *mock_backstop; +static inline void hibernation_set_backstop(const struct hibernation_backstop *b) +{ + mock_backstop = b; +} + static inline bool IS_ERR(const void *ptr) { return (uintptr_t)ptr >= (uintptr_t)-4095L; @@ -549,6 +581,8 @@ def apply_mutation(body, t6050_helpers, mutation): #define dev_warn(dev, fmt, ...) do { mock_warns++; } while (0) #define dev_info(dev, fmt, ...) do { mock_infos++; } while (0) +#define pr_info(fmt, ...) do { (void)sizeof(printf(fmt, ##__VA_ARGS__)); } while (0) +#define pr_err(fmt, ...) do { mock_warns++; } while (0) ''' T6050_PRELUDE = r''' @@ -744,9 +778,12 @@ def apply_mutation(body, t6050_helpers, mutation): assert(wdd->ops->get_timeleft(wdd) == 60u); assert(mmio_regs[0x2c / 4] == 0); teardown_pdev(&pdev); - assert(teardown_order_len == 2); + /* The watchdog, then the hibernation backstop, then the sleep handoff */ + assert(teardown_order_len == 3); assert(teardown_order[0] == DEVM_WDT); assert(teardown_order[1] == DEVM_ACTION); + assert(teardown_order[2] == DEVM_ACTION); + assert(mock_backstop == NULL); assert(mock_sleep_owner == NULL); /* @@ -792,8 +829,10 @@ def apply_mutation(body, t6050_helpers, mutation): /* 3. Simple-reconfig WD2: probe clears armed WD1 and safely takes over hazardous WD2 */ reset_hw(true, 24000000UL, false); mock_dt_timeout = 20; /* verify watchdog_init_timeout() runs before takeover */ + /* A running WD2 bark is adopted as the restore backstop; keep the DT timeout here. */ + hibernation_restore_timeout = 0; expect_hw_running_before_wd2_write = true; - reconfig_reg = 0x000000a5u; /* unrelated bits must be preserved */ + reconfig_reg = 0x000001a5u; /* bits 8+ must be preserved, the low byte is replaced */ mmio_regs[0x1c / 4] = BIT(2); /* legacy WD1 armed before probe */ mmio_regs[0x20 / 4] = 500u; /* hazardous: CUR >= BARK */ mmio_regs[0x24 / 4] = 1000u; /* stale short WD2_BITE */ @@ -803,10 +842,11 @@ def apply_mutation(body, t6050_helpers, mutation): expect_hw_running_before_wd2_write = false; wdd = registered_wdd; assert(mock_sleep_reg_res == &mock_wdt_res); - assert(mock_infos == 2); /* both legacy WD1 and WD2 RESET_EN takeover logged */ + assert(mock_infos == 3); /* WD1 and WD2 RESET_EN takeover, and the running WD2 adopted as the restore backstop */ assert(mmio_regs[0x1c / 4] == 0); /* WD1 cleared */ assert(watchdog_hw_running(wdd)); - assert(reconfig_reg == 0x00000095u); + assert(reconfig_reg == 0x00000118u); + hibernation_restore_timeout = APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT; assert(mmio_regs[0x24 / 4] == U32_MAX); assert(mmio_regs[0x2c / 4] == BIT(0)); assert(mmio_regs[0x28 / 4] == 20u * 24000000u); @@ -819,7 +859,7 @@ def apply_mutation(body, t6050_helpers, mutation): int i_cur = find_write(false, 0x20, 0, i_bite); int i_bark = find_write(false, 0x28, 20u * 24000000u, i_cur); int i_clr = find_write(false, 0x2c, BIT(1), i_bark); - int i_reconfig = find_write(true, 0x2c, 0x00000095u, i_clr); + int i_reconfig = find_write(true, 0x2c, 0x00000118u, i_clr); int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); @@ -853,7 +893,7 @@ def apply_mutation(body, t6050_helpers, mutation): reconfig_reg = 0; write_log_len = 0; assert(apple_wdt_resume(&pdev.dev) == 0); - assert(reconfig_reg == BIT(4)); + assert(reconfig_reg == (APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2)); assert(mmio_regs[0x24 / 4] == U32_MAX); assert(mmio_regs[0x28 / 4] == 15u * 24000000u); assert(mmio_regs[0x20 / 4] == 0); @@ -864,7 +904,7 @@ def apply_mutation(body, t6050_helpers, mutation): int i_cur = find_write(false, 0x20, 0, i_bite); int i_bark = find_write(false, 0x28, 15u * 24000000u, i_cur); int i_clr = find_write(false, 0x2c, BIT(1), i_bark); - int i_reconfig = find_write(true, 0x2c, BIT(4), i_clr); + int i_reconfig = find_write(true, 0x2c, APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2, i_clr); int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); @@ -894,7 +934,7 @@ def apply_mutation(body, t6050_helpers, mutation): mmio_regs[0x2c / 4] = 0; mock_sleep_restore(mock_sleep_data); mock_sleep_active = false; - assert(reconfig_reg == BIT(4)); + assert(reconfig_reg == (APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2)); assert(mmio_regs[0x24 / 4] == U32_MAX); assert(mmio_regs[0x28 / 4] == 15u * 24000000u); assert(mmio_regs[0x20 / 4] == 0); @@ -931,7 +971,7 @@ def apply_mutation(body, t6050_helpers, mutation): mdelay_total_ms = 0; write_log_len = 0; assert(wdd->ops->restart(wdd, 0, NULL) == 0); - assert(reconfig_reg == BIT(4)); + assert(reconfig_reg == (APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2)); assert(mmio_regs[0x24 / 4] == U32_MAX); assert(mmio_regs[0x28 / 4] == 24000000u * 40u / 1000u); assert(mmio_regs[0x2c / 4] == BIT(0)); @@ -943,16 +983,18 @@ def apply_mutation(body, t6050_helpers, mutation): int i_cur = find_write(false, 0x20, 0, i_bite); int i_bark = find_write(false, 0x28, 24000000u * 40u / 1000u, i_cur); int i_clr = find_write(false, 0x2c, BIT(1), i_bark); - int i_reconfig = find_write(true, 0x2c, BIT(4), i_clr); + int i_reconfig = find_write(true, 0x2c, APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2, i_clr); int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); } teardown_pdev(&pdev); - /* Verify devm unwinds watchdog before sleep handoff */ - assert(teardown_order_len == 2); + /* Verify devm unwinds watchdog, then the hibernation backstop, then the sleep handoff */ + assert(teardown_order_len == 3); assert(teardown_order[0] == DEVM_WDT); assert(teardown_order[1] == DEVM_ACTION); + assert(teardown_order[2] == DEVM_ACTION); + assert(mock_backstop == NULL); assert(mock_sleep_restore == NULL); /* 7b. Pre-probe legacy WD1 alone is adopted as WD2 simple-reconfig with HW_RUNNING */ @@ -965,7 +1007,7 @@ def apply_mutation(body, t6050_helpers, mutation): assert(mock_infos == 1); assert(mmio_regs[0x1c / 4] == 0); assert(watchdog_hw_running(wdd)); - assert(reconfig_reg == BIT(4)); + assert(reconfig_reg == (APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2)); assert(mmio_regs[0x24 / 4] == U32_MAX); assert(mmio_regs[0x28 / 4] == 30u * 24000000u); assert(mmio_regs[0x2c / 4] == BIT(0)); @@ -980,7 +1022,7 @@ def apply_mutation(body, t6050_helpers, mutation): wdd = registered_wdd; assert(mock_infos == 1); assert(watchdog_hw_running(wdd)); - assert(reconfig_reg == BIT(4)); + assert(reconfig_reg == (APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2)); assert(mmio_regs[0x2c / 4] == BIT(0)); teardown_pdev(&pdev); @@ -1010,7 +1052,7 @@ def apply_mutation(body, t6050_helpers, mutation): wdd = registered_wdd; assert(!watchdog_hw_running(wdd)); assert(mmio_regs[0x1c / 4] == 0); - assert(reconfig_reg == BIT(4)); + assert(reconfig_reg == (APPLE_WDT_RECONFIG_NO_AWL | APPLE_WDT_RECONFIG_WD2)); assert(mmio_regs[0x24 / 4] == U32_MAX); assert(mmio_regs[0x28 / 4] == (U32_MAX / 24000000u) * 24000000u); assert(mmio_regs[0x2c / 4] == BIT(0)); @@ -1099,6 +1141,13 @@ def main(): body, t6050_helpers = apply_mutation(body, t6050_helpers, args.mutation) t6050_part = T6050_PRELUDE + t6050_helpers + if args.old_ref: + # Older drivers have no restore backstop or low-byte policy; the controls still compile. + body += ('\n#ifndef APPLE_WDT_RECONFIG_NO_AWL\n#define APPLE_WDT_RECONFIG_NO_AWL BIT(3)\n' + '#define APPLE_WDT_RECONFIG_WD2 BIT(4)\n#endif\n') + if 'hibernation_restore_timeout' not in body: + body += ('static unsigned int hibernation_restore_timeout;\n' + '#define APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT 0\n') code = PREFIX + body + t6050_part + MAIN def run(out): diff --git a/tools/asahi/backlight-coldboot-tests.py b/tools/asahi/backlight-coldboot-tests.py index 47edbe6384b84..e690e8eac8abf 100755 --- a/tools/asahi/backlight-coldboot-tests.py +++ b/tools/asahi/backlight-coldboot-tests.py @@ -72,7 +72,7 @@ def function(source, name): struct desktop *desktop; struct { struct dcp_backlight_state state; int lock; } backlight; struct { bool update; u32 maximum; } brightness; - bool panel,m4,v14,external,typec,pipe_enabled_h17p,crashed,quiescing,t6040_relinking; + bool panel,m4,v14,external,typec,pipe_enabled_h17p,crashed,quiescing,ext_relinking; bool typec_crtc_off,typec_cable_connected,typec_follow_start,typec_poweron_hpd,hdmi_yielded; unsigned crtc_unplugs,typec_unplugs,typec_generation,typec_reconnect_tries,external_generation,external_crtc_generation; int external_lock,hpd_mutex,relink_lock,relink,typec_iomfb_hpd_ready; @@ -99,6 +99,7 @@ def function(source, name): /* These fixtures exercise the internal panel and the H17P external path. */ static bool dcp_is_ext26(struct apple_dcp *p) { (void)p;return false; } static bool dcp_is_retained_external(struct apple_dcp *p) { return dcp_is_external_h17p(p); } +static bool dcp_hib_gated(const struct apple_dcp *p) { (void)p;return false; } static void flush_work(struct work_struct *p) { (void)p;assert(!"unexpected native26 work flush"); } static bool dcp_is_typec_output(struct apple_dcp *p) { return p->typec; } static bool dcp_h17g_panel(struct apple_dcp *p) { return p->hw.iomfb_method_profile==DCP_IOMFB_METHODS_H17G; } @@ -192,7 +193,7 @@ def function(source, name): struct apple_dcp d=fresh(DCP_FIRMWARE_V_27_0);struct platform_device p={&d};d.m4=true; dcp_poweron(&p);assert(dpms_calls==1 && warnings==1 && !d.backlight.state.ready); /* A pipe whose link work after a sleep is still running stays off. */ - d=fresh(DCP_FIRMWARE_H17P);p.data=&d;d.t6040_relinking=true; + d=fresh(DCP_FIRMWARE_H17P);p.data=&d;d.ext_relinking=true; dcp_poweron(&p);assert(!d.pipe_enabled_h17p && !powers && !dpms_calls && !fallbacks); puts("coldboot/late-hint/fallback, ready restore, error, M4 and relinking callback paths PASS"); } diff --git a/tools/asahi/bcm4377-resume-tests.py b/tools/asahi/bcm4377-resume-tests.py index 4f2dad8b3ff75..6399bcc484478 100755 --- a/tools/asahi/bcm4377-resume-tests.py +++ b/tools/asahi/bcm4377-resume-tests.py @@ -12,7 +12,7 @@ def extract(s,n): while depth:depth+=(s[b]=='{')-(s[b]=='}');b+=1 return s[m.start():b]+'\n' s=(r/'drivers/bluetooth/hci_bcm4377.c').read_text();core=(r/'net/bluetooth/hci_sync.c').read_text();core_hci=(r/'net/bluetooth/hci_core.c').read_text() -names=['bcm4377_setup_retry_allowed','bcm4377_queue_setup_retry','bcm4377_setup_retry_work','bcm4377_resume_recovery_supported','bcm4377_resume_recovery_allowed','bcm4377_resume_recovery_invalidate','bcm4377_resume_recovery_sync','bcm4377_resume_recovery_destroy','bcm4377_resume_recovery_work','bcm4377_hci_timeout','bcm4377_resume_recovery_stop','bcm4377_hci_open','bcm4377_hci_close','bcm4377_hci_setup_once','bcm4377_hci_setup','bcm4377_clamp_acl_mtu','bcm4377_hci_post_init','bcm4377_hci_unregister_dev','bcm4377_sleep_finish','bcm4377_recover_power_lost','bcm4377_power_lost_work','bcm4377_suspend','bcm4377_mmio_ready','bcm4377_read_rom_ready','bcm4377_prepare_sleep_boot','bcm4377_check_sleep_rom','bcm4377_resume'] +names=['bcm4377_setup_retry_allowed','bcm4377_queue_setup_retry','bcm4377_setup_retry_work','bcm4377_resume_recovery_supported','bcm4377_resume_recovery_allowed','bcm4377_resume_recovery_invalidate','bcm4377_resume_recovery_sync','bcm4377_resume_recovery_destroy','bcm4377_resume_recovery_work','bcm4377_hci_timeout','bcm4377_resume_recovery_stop','bcm4377_hci_open','bcm4377_hci_close','bcm4377_hci_setup_once','bcm4377_hci_setup','bcm4377_clamp_acl_mtu','bcm4377_hci_post_init','bcm4377_hci_unregister_dev','bcm4377_sleep_finish','bcm4377_recover_power_lost','bcm4377_power_lost_work','__bcm4377_suspend','bcm4377_suspend','bcm4377_mmio_ready','bcm4377_read_rom_ready','bcm4377_prepare_sleep_boot','bcm4377_check_sleep_rom','bcm4377_resume'] bodies={n:extract(s,n) for n in names};shared=[] if a.old_ref: old=subprocess.check_output(['git','show',a.old_ref+':drivers/bluetooth/hci_bcm4377.c'],cwd=r,text=True) @@ -26,9 +26,9 @@ def extract(s,n): 'board':('bcm4377_resume_recovery_supported','of_machine_is_compatible("apple,j493")','true',13), 'rom-reset':('bcm4377_prepare_sleep_boot','ret = pci_reset_function_locked(pdev);','ret = 0;',47), 'rom-recheck':('bcm4377_prepare_sleep_boot','if (!ret && !ready)\n\t\tret = -EIO;','',50), - 'rom-rebind':('bcm4377_resume','bcm4377_queue_rebind(bcm4377, "post-sleep boot ROM unavailable");','',48), - 'flush-frozen-firmware':('bcm4377_suspend','if (cancel_work_sync(&bcm4377->power_lost_work)) {','flush_work(&bcm4377->power_lost_work);\n\tif (0) {',52), - 'fail-sleep-on-recovery-error':('bcm4377_suspend','dev_warn(dev, "recovery from the last sleep failed: %d\\n", ret);','return ret;',53), + 'rom-rebind':('bcm4377_resume','bcm4377_queue_rebind(bcm4377, "post-sleep boot ROM unavailable", true);','',48), + 'flush-frozen-firmware':('__bcm4377_suspend','if (cancel_work_sync(&bcm4377->power_lost_work)) {','flush_work(&bcm4377->power_lost_work);\n\tif (0) {',52), + 'fail-sleep-on-recovery-error':('__bcm4377_suspend','dev_warn(dev, "recovery from the last sleep failed: %d\\n", ret);','return ret;',53), 'unlocked-recovery-reset':('bcm4377_recover_power_lost','bcm4377->reset_with_pci_lock = pci_locked;','bcm4377->reset_with_pci_lock = false;',52), 'rom-irq-guard':('bcm4377_prepare_sleep_boot','if (!ret)\n\t\tWRITE_ONCE(bcm4377->irq_blocked, false);','',46), 'resume-mmio-guard':('bcm4377_resume','if (!bcm4377_mmio_ready(pdev)) {','if (false) {',55), diff --git a/tools/asahi/bcm4377-resume/fixture.h b/tools/asahi/bcm4377-resume/fixture.h index c1b6b3905303f..652834ca8133e 100644 --- a/tools/asahi/bcm4377-resume/fixture.h +++ b/tools/asahi/bcm4377-resume/fixture.h @@ -140,9 +140,9 @@ static bool hdev_is_powered(struct hci_dev *h) {return (h->flags&HCI_UP) && !(h- static bool firmware_resume; static bool pm_resume_via_firmware(void) { return firmware_resume; } -static void bcm4377_queue_rebind(struct bcm4377_data *b, const char *why) +static void bcm4377_queue_rebind(struct bcm4377_data *b, const char *why, bool failure) { - assert(b == active && why); + assert(b == active && why && failure); rebind_count++; } static bool of_machine_is_compatible(const char *s) {assert(!strcmp(s,"apple,j493"));return board_j493;} diff --git a/tools/asahi/dcpext26-retrain-tests.py b/tools/asahi/dcpext26-retrain-tests.py index b8b625e179889..ce9d1aaaaad63 100644 --- a/tools/asahi/dcpext26-retrain-tests.py +++ b/tools/asahi/dcpext26-retrain-tests.py @@ -13,7 +13,7 @@ body = s[a:b] if '--negative-control' in sys.argv: a = body.index('\t} else if (dcp_is_ext26(dcp) && crtc && crtc->state &&') - b = body.index('\t} else if (dcp_t6040_relinks() && crtc && crtc->state &&', a) + b = body.index('\t} else if (dcp_ext_relinks() && crtc && crtc->state &&', a) body = body[:a] + body[b:] pre = r''' @@ -46,7 +46,7 @@ #define DRM_MODESET_LOCK_ALL_END(dev, ctx, ret) } while (0) static bool dcp_is_ext26(struct apple_dcp *d) { return d->native; } static bool dcp_has_mode(struct apple_dcp *d, const struct mode *m) { return d->admitted && m->id == 1; } -static bool dcp_t6040_relinks(void) { return t604x; } +static bool dcp_ext_relinks(void) { return t604x; } static bool dcp_mode_settable(struct apple_dcp *d, const struct mode *m) { return !unlisted; } static bool dcp_typec_follows_crtc(struct apple_dcp *d) { return follows; } static bool dcp_crtc_lost_route(struct drm_crtc *c, struct apple_connector *p) { return lost; } diff --git a/tools/asahi/display26-tests.py b/tools/asahi/display26-tests.py index 2dcc3058a0cc0..eaecb6350811d 100644 --- a/tools/asahi/display26-tests.py +++ b/tools/asahi/display26-tests.py @@ -101,7 +101,19 @@ def main(): '#define LATE_SYSTEM_SLEEP_PM_OPS(s, r) .suspend_late = (s), .resume_early = (r),\n') write(tmp, 'linux/suspend.h', '#include \n' 'static inline bool pm_suspend_via_firmware(void) { return false; }\n' - 'static inline bool pm_resume_via_firmware(void) { return false; }\n') + 'static inline bool pm_resume_via_firmware(void) { return false; }\n' + 'static inline bool pm_hibernate_restored_cold(void) { return false; }\n' + '#define PM_HIBERNATION_PREPARE 1\n#define PM_POST_HIBERNATION 2\n#define PM_POST_RESTORE 6\n') + # The bridge restarts the PMP after a resume from disk; this harness only counts the notifier. + write(tmp, 'linux/notifier.h', '#pragma once\n#define NOTIFY_DONE 0\n' + 'struct notifier_block { int (*notifier_call)(struct notifier_block *, unsigned long, void *); int priority; };\n' + 'static int pm_notifiers;\n' + 'static inline int register_pm_notifier(struct notifier_block *nb) { pm_notifiers++; return 0; }\n' + 'static inline int unregister_pm_notifier(struct notifier_block *nb) { pm_notifiers--; return 0; }\n') + # The DART lookup of the resume-from-disk restart; never reached here. + write(tmp, 'linux/platform_device.h', '#pragma once\n#include "mock.h"\nstruct platform_device { struct device dev; };\n') + write(tmp, 'linux/of_platform.h', '#pragma once\n#include \n' + 'static inline struct platform_device *of_find_device_by_node(struct device_node *n) { assert(!"no resume from disk here"); return NULL; }\n') # The bridge's sleep-commit stop: MMIO, RTKit and the sleep driver, reached only in a suspend. write(tmp, 'linux/io.h', '#include "mock.h"\n' 'static inline u32 readl_relaxed(const volatile void __iomem *a) { assert(!"no system sleep here"); return 0; }\n' @@ -182,6 +194,9 @@ def main(): int apple_pmp_sleep(const void*data){assert(!"no system sleep here");return -EIO;} int apple_pmp_sleep_prepare(const void*data,struct apple_pmp_commit_stop*stop){assert(!"no system sleep here");return -EIO;} int apple_pmp_wake(const void*data){assert(!"no system sleep here");return -EIO;} +int apple_pmp_restore(const void*data){assert(!"no resume from disk here");return -EIO;} +void apple_dart_display_unpowered(struct device*d){assert(!"no resume from disk here");} +int apple_dart_display_restore(struct device*d){assert(!"no resume from disk here");return -EIO;} int main(void){ struct device_node n={1},wrong={2}; struct device supplier={&n,true,0},consumer={NULL,false,0}; int data; assert(apple_pmp_set_device_power(0xf,8,1)==-ENODEV); @@ -189,7 +204,7 @@ def main(): assert(apple_pmp_link_device(&consumer)==-EINVAL); phandle=&n;assert(apple_pmp_link_device(&consumer)==-EPROBE_DEFER); assert(apple_pmp_register(&supplier,&data)==0); - assert(apple_pmp_register(&supplier,&data)==-EBUSY); + assert(apple_pmp_register(&supplier,&data)==-EBUSY);assert(pm_notifiers==1); assert(apple_pmp_t602x_agx_vote(true)==-ENODEV);assert(calls==0); supplier.bound=false;assert(apple_pmp_link_device(&consumer)==-EPROBE_DEFER);supplier.bound=true; phandle=&wrong;assert(apple_pmp_link_device(&consumer)==-EPROBE_DEFER);phandle=&n; @@ -206,7 +221,7 @@ def main(): assert(apple_pmp_set_device_power(0xf,5,1)==0);assert(calls==3); assert(apple_pmp_set_device_power(0xe,5,0)==0);assert(calls==4); apple_pmp_unregister(&wrong);assert(pmp_data==&data); - apple_pmp_unregister(&data);assert(!pmp_data && !pmp_device); + apple_pmp_unregister(&data);assert(!pmp_data && !pmp_device);assert(pm_notifiers==0); assert(apple_pmp_set_device_power(0xf,8,1)==-ENODEV); puts("production PMP bridge supplier/ready/ack controls: PASS"); } diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py index 8325d47481703..108c019d0e109 100644 --- a/tools/asahi/g15-probe-init-tests.py +++ b/tools/asahi/g15-probe-init-tests.py @@ -158,6 +158,10 @@ def item(text, marker): mod binding { pub unsafe fn init() { crate::BINDING_READY.set(true); } } +// Boot-memory bookkeeping for a resume from disk; no control reads it. +mod boot_memory { + pub unsafe fn init() {} +} // The queue-share registry must also be ready before an adapter can probe. mod queue_share { pub unsafe fn init() { crate::QUEUE_SHARE_READY.set(true); } diff --git a/tools/asahi/g17-admission-deadline-tests.py b/tools/asahi/g17-admission-deadline-tests.py index f7c6dc5c4361e..b279053808720 100644 --- a/tools/asahi/g17-admission-deadline-tests.py +++ b/tools/asahi/g17-admission-deadline-tests.py @@ -71,6 +71,7 @@ def fixture(): struct Pool {state:Lock,released:CondVar,queues:AtomicU32} struct RenderLease {pool:Arc,slot:u8,record:Option} ''' + item(source, 'fn wait_slice_ms(') + '\nimpl Pool {\n' + item(source, 'pub(crate) fn acquire_render(') + r''' + fn queues(&self)->u32 {self.queues.load(Ordering::SeqCst)} } fn new_pool(conflict:bool,quarantined:u64)->Arc { Arc::new(Pool{state:Lock(Mutex::new(State{owners:[0,1],released:0,quarantined,spared:0,next_ticket:1,waiters:0,conflict,ready:false})),released:CondVar,queues:AtomicU32::new(1)}) diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 7bc14b610a848..ec24be2175fb7 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -171,6 +171,8 @@ def held_fixture(): 'fn release(', 'fn set_held(', 'fn retained(', 'fn used(', 'fn rehabilitate(', 'fn pair_drained(', 'fn reclaim_sibling(']) pool = '\n'.join(item(source, name) for name in [ + 'fn queue_generation(', 'fn queue_count(', 'fn pack_queues(', + 'fn release_queue_count(', 'pub(crate) fn try_reserve_queue_reclaiming(', 'pub(crate) fn set_held(', 'pub(crate) fn release_owner(', 'pub(crate) fn pair_drained(', 'pub(crate) fn note_build_room(', @@ -179,7 +181,7 @@ def held_fixture(): 'pub(crate) fn killed_pair_free(']) return r''' #![allow(dead_code, unused_macros)] -use std::sync::{Arc, Mutex, MutexGuard, atomic::{AtomicU32, AtomicUsize, Ordering::{self, SeqCst}}}; +use std::sync::{Arc, Mutex, MutexGuard, atomic::{AtomicU64, AtomicUsize, Ordering::{self, SeqCst}}}; type Result = std::result::Result; const ENOSPC: i32 = -28; const EIO: i32 = -5; @@ -200,10 +202,10 @@ def held_fixture(): } type KVec = Vec; struct InFlight; -struct QueueSlot { pool: Arc } +struct QueueSlot { pool: Arc, generation: u32 } impl Drop for QueueSlot { fn drop(&mut self) { - self.pool.queues.fetch_sub(1, Ordering::AcqRel); + self.pool.release_queue_count(self.generation); self.pool.notify_queue_waiters(); } } @@ -213,7 +215,7 @@ def held_fixture(): } struct Lock(Mutex); impl Lock { fn lock(&self) -> MutexGuard<'_, State> { self.0.lock().unwrap() } } -struct Pool { state: Lock, queues: AtomicU32, max_queues: u32, wakes: AtomicUsize, queue_wakes: AtomicUsize } +struct Pool { state: Lock, queues: AtomicU64, max_queues: u32, wakes: AtomicUsize, queue_wakes: AtomicUsize } impl Pool { fn returned(&self) { self.wakes.fetch_add(1, SeqCst); } fn notify_queue_waiters(&self) { self.queue_wakes.fetch_add(1, SeqCst); } @@ -237,7 +239,7 @@ def held_fixture(): fn pool(state: State) -> Arc { Arc::new(Pool { state: Lock(Mutex::new(state)), - queues: AtomicU32::new(0), + queues: AtomicU64::new(0), max_queues: (SLOTS - 1) as u32, wakes: AtomicUsize::new(0), queue_wakes: AtomicUsize::new(0), diff --git a/tools/asahi/g17-compute-deadline-tests.py b/tools/asahi/g17-compute-deadline-tests.py index 8fc49063f1f31..4a4ebdd19bbc5 100644 --- a/tools/asahi/g17-compute-deadline-tests.py +++ b/tools/asahi/g17-compute-deadline-tests.py @@ -96,7 +96,7 @@ def fixture(): struct Work;impl Work{fn acquire(&self,engine:g17::job::Engine)->Result{assert_eq!(engine,g17::job::Engine::Compute,"compute admission takes a compute work state");if MODE.load(Ordering::SeqCst)==4{Err(EBUSY)}else{Ok(1)}}} struct Completion;impl Completion{fn status(&self)->Status{Status}fn work_state(&self)->Result{Ok(Work)}} struct Order{wait_through:[Option;2]} -struct Packet{command:Validated,completion:Completion,order:Order} +struct Packet{command:Validated,completion:Completion,order:Order,context:Context} impl Packet{fn check_dependencies(&self)->Result{if SIGNALLED.load(Ordering::SeqCst){Err(PRODUCER_FAILED)}else{Ok(())}}fn cancel_requested(&self)->bool{now_ns()>=CANCEL.load(Ordering::SeqCst)}fn is_published(&self)->bool{false}} const PRODUCER_FAILED:i32=ECANCELED; #[derive(Default)]struct DeferredBatch{failed:usize} @@ -112,7 +112,7 @@ def fixture(): } struct Recovery;impl Recovery{fn pending(&self)->bool{MODE.load(Ordering::SeqCst)==1}} struct Init;impl Init{fn compute_vm_cached(&self,_:&())->bool{true}} -struct Context;impl Context{fn vm(&self)->&(){&()}} +struct Context;impl Context{fn vm(&self)->&(){&()} fn outlived_firmware(&self)->bool{false}} struct Memory;impl Memory{fn recovery_state(_:&Init)->Result{Ok(0)}} struct Queues; impl Queues{ @@ -180,7 +180,7 @@ def fixture(): } fn main(){ let b=backend(); - let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion,order:Order{wait_through:[None,None]}}); + let p=Arc::new(Packet{context:Context,command:Validated::Compute{scratch:Scratch},completion:Completion,order:Order{wait_through:[None,None]}}); for mode in 0..4 { MODE.store(mode,Ordering::SeqCst);NOW.store(0,Ordering::SeqCst);CALLS.store(0,Ordering::SeqCst);REPORTED.store(usize::MAX,Ordering::SeqCst); let r=b.compute_packet(&p,&mut DeferredBatch::default()); diff --git a/tools/asahi/g17-render-submit-fastpath-tests.py b/tools/asahi/g17-render-submit-fastpath-tests.py index 1936ac4076ae7..5b5f4ca7c4afa 100755 --- a/tools/asahi/g17-render-submit-fastpath-tests.py +++ b/tools/asahi/g17-render-submit-fastpath-tests.py @@ -150,6 +150,8 @@ def run_rust_fixture(admission: str, completion: str, deps: str, resources: str) 'fn retained(', ] ) + queues_fn = item(admission, 'pub(crate) fn queues(') + queue_count_fn = item(admission, 'fn queue_count(') try_acquire = item(admission, 'pub(crate) fn try_acquire_render(') release_owner = item(admission, 'pub(crate) fn release_owner(') @@ -175,7 +177,7 @@ def run_rust_fixture(admission: str, completion: str, deps: str, resources: str) #![allow(dead_code, unused_variables, unused_imports, unused_unsafe)] use std::sync::{ Arc, Mutex, MutexGuard, - atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}, + atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, }; type Result = std::result::Result; @@ -248,14 +250,14 @@ def run_rust_fixture(admission: str, completion: str, deps: str, resources: str) } struct Lock(Mutex); impl Lock { fn lock(&self) -> MutexGuard<'_, State> { self.0.lock().unwrap() } } -pub(crate) struct Pool { state: Lock, queues: AtomicU32 } +pub(crate) struct Pool { state: Lock, queues: AtomicU64 } impl Pool { fn new() -> Arc { - Arc::new(Self { state: Lock(Mutex::new(State::new())), queues: AtomicU32::new(1) }) + Arc::new(Self { state: Lock(Mutex::new(State::new())), queues: AtomicU64::new(1) }) } fn returned(&self) {} fn notify_queue_waiters(&self) {} -''' + try_acquire + '\n' + release_owner + r''' +''' + queues_fn + '\n' + queue_count_fn + '\n' + try_acquire + '\n' + release_owner + r''' } fn check_occupied(state: &State) { diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index ad217cca0c5c9..9db083fb59ea2 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -179,7 +179,7 @@ def item(s,start): #[derive(Clone,Copy)] struct Identity {id:Id,published:bool} '''+constants+'\n'+item(s,'const fn render_reserve(')+'\n'+item(s,'const fn queue_limit(')+'\n'+item(s,'pub(crate) struct QueueIds')+'\nimpl QueueIds {\n'+''.join(item(s,'pub(crate) fn '+name+'(')+'\n' for name in ['reserve_initial_render','reserve','reserve_for','publish','can_cancel_unpublished','cancel_unpublished'])+''.join(item(s, sig)+'\n' for sig in ['fn render_ids(', 'fn compute_room('])+'}\n' test=''' - fn fresh()->QueueIds {QueueIds {entries:[None;QID_COUNT],initial_render:[None;2],leased:0,floor:0}} + fn fresh()->QueueIds {QueueIds {entries:[None;QID_COUNT],initial_render:[None;2],leased:0,floor:0,probe_floor:0}} fn main(){ for floor in [0,32] { for render in [0,2,16,32,80,96,112,126].into_iter().filter(|render|*render<=QID_COUNT-floor) { diff --git a/tools/asahi/hibernate-signature-tests.py b/tools/asahi/hibernate-signature-tests.py new file mode 100755 index 0000000000000..4f3072d36e493 --- /dev/null +++ b/tools/asahi/hibernate-signature-tests.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the hibernation image signature and swap release paths against I/O faults. + +swap_writer_finish(), swsusp_invalidate_sig() and swsusp_free_image_swap() are +taken from kernel/power/swap.c and run against a resume device model with a +volatile cache, FUA writes, flushes and injected read, write and flush errors. +The invariant: the image's swap pages are released only when no valid image +signature is left on the device, durably or in its cache. +""" +from pathlib import Path +import argparse +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +SWAP = 'kernel/power/swap.c' +NAMES = ('swap_writer_finish', 'swsusp_invalidate_sig', 'swsusp_free_image_swap') + +MUTATIONS = { + # Release the writer's swap pages on any error, as before. + 'writer-free-always': ('if (marked && swsusp_invalidate_sig())', 'if (0)'), + # Ignore a failed write of the last swap map page. + 'writer-ignore-map-page': ('if (!error)\n\t\t\terror = ret;\n\t\t/*', '/*'), + # Free the test_resume image pages without clearing the signature. + 'free-unchecked': ('\tif (error) {\n\t\tpr_err("image signature could not', + '\tif (0) {\n\t\tpr_err("image signature could not'), + # Trust a signature reset that may still sit in the device cache. + 'no-flush': ('return blkdev_issue_flush(file_bdev(hib_resume_bdev_file));\n}', + 'return 0;\n}'), +} + + +def show(ref): + if ref: + return subprocess.run(['git', '-C', str(ROOT), 'show', f'{ref}:{SWAP}'], + check=True, capture_output=True, text=True).stdout + return (ROOT / SWAP).read_text() + + +def function(text, name): + match = re.search(r'^(?:static )?(?:int|void) ' + re.escape(name) + r'\(', text, re.M) + if not match: + raise SystemExit(f'{name} not found') + start = text.index('{', match.start()) + depth, end = 1, start + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[match.start():end] + '\n' + + +PREFIX = r''' +#include +#include +#include +#include +#include +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); abort(); } } while (0) +#include +#define HIBERNATE_SIG "S1SUSPEND" +#define ORIG "SWAPSPACE2" +#define REQ_OP_READ 0 +#define REQ_OP_WRITE 1 +#define REQ_SYNC 2 +#define REQ_FUA 4 +#define BLK_OPEN_READ 1 +#define pr_info(...) ((void)0) +#define pr_cont(...) ((void)0) +#define pr_err(...) ((void)0) +#define pr_warn(...) ((void)0) +#define IS_ERR(p) ((p) == NULL) +#define PTR_ERR(p) (-ENXIO) +struct file { int open; }; +struct block_device { int unused; }; +struct swsusp_header { char orig_sig[10]; char sig[10]; }; +struct swap_map_handle { int unused; }; +typedef unsigned long sector_t; +static struct swsusp_header header_page, *swsusp_header = &header_page; +static struct file bdev_file, *hib_resume_bdev_file; +static struct block_device bdev; +static int root_swap, swsusp_resume_device = 1, opens, closes; +static sector_t swsusp_resume_block; +/* Device model: what the media holds and what its volatile cache holds. */ +static char media[10], cache[10]; +static int read_err, write_err, flush_err, open_err, map_err, mark_err, mark_writes; +static int freed, released; +static bool valid(const char *s) { return !memcmp(s, HIBERNATE_SIG, 10); } +static void set(char *s, const char *v) { memcpy(s, v, 10); } +static struct block_device *file_bdev(struct file *f) { CHECK(f && f->open); return &bdev; } +static int hib_submit_io_sync(int op, sector_t block, void *page) +{ + struct swsusp_header *h = page; + CHECK(hib_resume_bdev_file && hib_resume_bdev_file->open); + if ((op & 1) == REQ_OP_READ) { + if (read_err) { read_err--; return -EIO; } + set(h->sig, cache); set(h->orig_sig, ORIG); + return 0; + } + if (write_err) { write_err--; return -EIO; } + set(cache, h->sig); + if (op & REQ_FUA) + set(media, h->sig); + return 0; +} +static int blkdev_issue_flush(struct block_device *b) +{ + if (flush_err) { flush_err--; return -EIO; } + set(media, cache); + return 0; +} +static struct file *bdev_file_open_by_dev(int dev, int mode, void *holder, void *ops) +{ + if (open_err) return NULL; + opens++; bdev_file.open = 1; return &bdev_file; +} +static void swsusp_close(void) { CHECK(bdev_file.open); bdev_file.open = 0; closes++; } +static void free_all_swap_pages(int swap) +{ + CHECK(!valid(media) && !valid(cache)); + freed++; +} +static void release_swap_writer(struct swap_map_handle *h) { released++; } +static int mark_swapfiles(struct swap_map_handle *h, unsigned int flags) +{ + mark_writes++; + if (mark_err == 1) return -EIO; /* header read failed, nothing written */ + set(cache, HIBERNATE_SIG); /* REQ_SYNC write, no FUA */ + return mark_err ? -EIO : 0; /* 2: written, completion error */ +} +static int flush_swap_writer(struct swap_map_handle *h) { return map_err ? -EIO : 0; } +int swsusp_invalidate_sig(void); +''' + +MAIN = r''' +static struct swap_map_handle handle; +static void reset(const char *sig) +{ + set(media, sig); set(cache, sig); + read_err = write_err = flush_err = open_err = map_err = mark_err = 0; + freed = released = opens = closes = mark_writes = 0; + hib_resume_bdev_file = NULL; +} +static int writer(int error) +{ + int ret; + hib_resume_bdev_file = bdev_file_open_by_dev(1, 0, NULL, NULL); + ret = swap_writer_finish(&handle, 0, error); + CHECK(released == 1 && !bdev_file.open); + return ret; +} +int main(void) +{ + /* Writer, success: the image stays, signed and durable. */ + reset(ORIG); + CHECK(writer(0) == 0 && !freed && valid(media)); + /* Writer, earlier error: nothing was marked, the pages go. */ + reset(ORIG); + CHECK(writer(-ENOSPC) == -ENOSPC && freed == 1 && !mark_writes); + /* Writer, device flush fails once: the signature is cleared, then the pages go. */ + reset(ORIG); flush_err = 1; + CHECK(writer(0) == -EIO && freed == 1 && !valid(media) && !valid(cache)); + /* Writer, flush and the signature clear both fail: the pages stay reserved. */ + reset(ORIG); flush_err = 100; + CHECK(writer(0) == -EIO && !freed); + reset(ORIG); flush_err = 1; write_err = 1; + CHECK(writer(0) == -EIO && !freed && valid(cache)); + reset(ORIG); flush_err = 1; read_err = 1; + CHECK(writer(0) == -EIO && !freed); + /* Writer, the last map page fails: no image, signature cleared, pages go. */ + reset(ORIG); map_err = 1; + CHECK(writer(0) == -EIO && freed == 1 && !valid(media) && !valid(cache)); + /* Writer, header write reports an error after landing: cleared before freeing. */ + reset(ORIG); mark_err = 2; + CHECK(writer(0) == -EIO && freed == 1 && !valid(cache)); + reset(ORIG); mark_err = 1; + CHECK(writer(0) == -EIO && freed == 1); + + /* test_resume: swsusp_check() could not read the header; the image is still signed. */ + reset(HIBERNATE_SIG); read_err = 100; + swsusp_free_image_swap(); + CHECK(!freed && valid(media) && opens == closes); + /* A later read works: the signature is cleared durably, then the pages go. */ + reset(HIBERNATE_SIG); + swsusp_free_image_swap(); + CHECK(freed == 1 && !valid(media) && !valid(cache) && opens == 1 && closes == 1); + /* swsusp_check() could not write the reset: still signed, the clear fails again. */ + reset(HIBERNATE_SIG); write_err = 100; + swsusp_free_image_swap(); + CHECK(!freed && valid(media)); + /* The reset is only in the device cache: it is flushed before freeing. */ + reset(HIBERNATE_SIG); set(cache, ORIG); + swsusp_free_image_swap(); + CHECK(freed == 1 && !valid(media)); + reset(HIBERNATE_SIG); set(cache, ORIG); flush_err = 100; + swsusp_free_image_swap(); + CHECK(!freed && valid(media)); + /* A failed restore after a good check: already cleared, the pages go. */ + reset(ORIG); + swsusp_free_image_swap(); + CHECK(freed == 1); + /* The resume device cannot be opened: keep the pages. */ + reset(HIBERNATE_SIG); open_err = 1; + swsusp_free_image_swap(); + CHECK(!freed); + puts("PASS hibernate signature: swap pages released only after the signature is durably gone"); + return 0; +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--old-ref', help='take kernel/power/swap.c from this revision') + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + + text = show(args.old_ref) + body = ''.join(function(text, n) for n in NAMES) + if args.mutation: + old, new = MUTATIONS[args.mutation] + if old not in body: + raise SystemExit(f'mutation {args.mutation} does not apply') + body = body.replace(old, new, 1) + + def run(out): + out.mkdir(parents=True, exist_ok=True) + cfile, exe = out / 'hibernate-signature.c', out / 'hibernate-signature' + cfile.write_text(PREFIX + body + MAIN) + subprocess.run([args.cc, '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-Wno-unused-variable', '-Wno-unused-but-set-variable', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(cfile), '-o', str(exe)], check=True) + res = subprocess.run([str(exe)], capture_output=True, text=True) + print(res.stdout + res.stderr, end='') + return res.returncode + + if args.out: + raise SystemExit(run(args.out)) + with tempfile.TemporaryDirectory() as tmp: + raise SystemExit(run(Path(tmp))) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/iomfb-startup-tests.py b/tools/asahi/iomfb-startup-tests.py index 47fea6c57581e..4905d45e84dae 100644 --- a/tools/asahi/iomfb-startup-tests.py +++ b/tools/asahi/iomfb-startup-tests.py @@ -13,6 +13,7 @@ #include #include #include +#include #include typedef uint64_t dma_addr_t; #define DCP_FIRMWARE_H17P 1 @@ -23,10 +24,14 @@ #define IOMFB_ENDPOINT 0x20 #define DCP_SHMEM_SIZE 1 #define GFP_KERNEL 0 +#define IS_ENABLED(x) 1 +#define READ_ONCE(x) (x) +#define wmb() ((void)0) +enum { DCP_HIB_NONE, DCP_HIB_RESTARTING }; struct apple_dcp { int fw_compat; struct {int iomfb_method_profile;} hw; struct {int lock; bool active, scanout, stopped;} iomfb; - void *rtk, *shmem, *dev; bool ext; }; -static int alloc_calls, iomfb_calls, fail_ep; + void *rtk, *shmem, *dev; bool ext; int hib_phase; dma_addr_t shmem_iova; }; +static int alloc_calls, iomfb_calls, fail_ep, dma_allocs, cleans; /* Firmware 27 lists the endpoints it uses; whether that list has the allocator. */ static bool alloc_advertised; static bool apple_rtkit_has_endpoint(void *r, int ep) {return ep!=REMOTE_ALLOC_ENDPOINT || alloc_advertised;} @@ -40,7 +45,9 @@ if(ep==REMOTE_ALLOC_ENDPOINT) alloc_calls++; else iomfb_calls++; return 0; } -static void *dma_alloc_coherent(void *d,int n,dma_addr_t *a,int flags) {*a=0; return (void *)1;} +static char arena[DCP_SHMEM_SIZE]; +static void *dma_alloc_coherent(void *d,int n,dma_addr_t *a,int flags) {*a=0x1000; dma_allocs++; return arena;} +static void iomfb_hib_clean_shmem(struct apple_dcp *d) {cleans++;} static int dcpep_set_shmem(dma_addr_t a) {return 0;} static void dcp_send_message(struct apple_dcp *d,int ep,int m) {} ''' @@ -57,6 +64,9 @@ /* The native26 map has no allocator: it must still start IOMFB. */ if(ext) { fail_ep=REMOTE_ALLOC_ENDPOINT;assert(!iomfb_start_rtkit(&d)); } if(alloc) { fail_ep=REMOTE_ALLOC_ENDPOINT;assert(iomfb_start_rtkit(&d)==-EINVAL); } + /* A firmware restarted after a resume from disk gets the restored arena back, cleared. */ + fail_ep=-1;dma_allocs=cleans=0;arena[0]=1;d.hib_phase=DCP_HIB_RESTARTING;d.shmem=arena;d.shmem_iova=0x1000; + assert(!iomfb_start_rtkit(&d));assert(!dma_allocs && cleans==1 && !arena[0] && d.shmem==arena); } return 0; } diff --git a/tools/asahi/pmu-rtc-tests.py b/tools/asahi/pmu-rtc-tests.py index 73a017a6ca997..0334f02b57d90 100644 --- a/tools/asahi/pmu-rtc-tests.py +++ b/tools/asahi/pmu-rtc-tests.py @@ -67,6 +67,7 @@ #define kfree free #define guard(x) (void) #define dev_err(...) ((void)0) +#define PM_SUSPEND_ON 0 #define PM_SUSPEND_TO_IDLE 1 #define RTC_IRQF 0x80 #define RTC_AF 0x20 @@ -538,6 +539,9 @@ firmware_suspend = true; assert(!apple_pmu_rtc_prepare(&dev)); firmware_suspend = false; + /* Hibernation has no suspend target: a cold boot wakes it. */ + pm_suspend_target_state = PM_SUSPEND_ON; + assert(!apple_pmu_rtc_prepare(&dev)); pm_suspend_target_state = PM_SUSPEND_TO_IDLE; } int main(void) { diff --git a/tools/asahi/rtkit-oslog-tests.py b/tools/asahi/rtkit-oslog-tests.py index d1dd8f8b919b5..512e276ba9d55 100644 --- a/tools/asahi/rtkit-oslog-tests.py +++ b/tools/asahi/rtkit-oslog-tests.py @@ -98,6 +98,7 @@ def function(source, name): { (void)r; ++freed; b->size=0; } #define kfree(p) ((void)(p)) static int apple_mbox_start(struct mailbox *m) { (void)m; return start_error; } +static int apple_mbox_restore(struct mailbox *m) { (void)m; return 0; } static int apple_rtkit_send_message(struct apple_rtkit *r, u8 ep, u64 msg, void *c, bool atomic) { (void)r; assert(ep==APPLE_RTKIT_EP_OSLOG && c==NULL && !atomic); ++sent; sent_message=msg; return send_error; } static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *r, diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index de7eed3a05907..8d8c3b05aa3a3 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -196,6 +196,11 @@ def mutations(flag, names, base, expect=KILL): 'no-status-clear', 'reconfig-before-bark', 'register-after-arm', 'hwrunning-after-arm', 'no-wd1-adopt', 'no-t6050-wake-restore'), out()), + # c80d78247f3d frees the image's swap pages while its signature may still be on the disk. + 'hibernate-signature-tests.py': [(out(), PASS), + (out() + ['--old-ref', 'c80d78247f3de9d7444bf903207d472f26585af4'], KILL)] + + mutations('--mutation', ('writer-free-always', 'writer-ignore-map-page', + 'free-unchecked', 'no-flush'), out()), 'apple-m4-pmu-tests.py': [([], PASS)] + mutations('--mutation', ('m1-layout', 'cycles-anywhere', 'expose-8-9', 'flags-in-event'), []), # 255761f1d55f leaves streams on a domain whose paging attach failed part way. diff --git a/tools/asahi/t8132-sleep-refuse-tests.c b/tools/asahi/t8132-sleep-refuse-tests.c index 43ab5b07cb905..1aa64d921f7ad 100644 --- a/tools/asahi/t8132-sleep-refuse-tests.c +++ b/tools/asahi/t8132-sleep-refuse-tests.c @@ -42,7 +42,7 @@ struct apple_sleep { const struct apple_sleep_soc *soc; struct device *dev; bool untested, dry_run, apcie_ports_unowned; - bool apcie_port_stopped, usb_down_ran, smc_woke_alone, wd1_saved; + bool apcie_port_stopped, usb_down_ran, smc_woke_alone, wd1_saved, mbox_lost; u32 wd1_saved_ctl, wd1_saved_bite; char *wdt; }; diff --git a/tools/aurora-sep/tests/test_diag_sensor.py b/tools/aurora-sep/tests/test_diag_sensor.py index 25fc78cee8b3b..313f06934adc8 100644 --- a/tools/aurora-sep/tests/test_diag_sensor.py +++ b/tools/aurora-sep/tests/test_diag_sensor.py @@ -59,6 +59,7 @@ #define atomic_xchg(v, i) __atomic_exchange_n(&(v)->counter, (i), __ATOMIC_SEQ_CST) typedef struct { int64_t counter; } atomic64_t; #define atomic64_read(v) __atomic_load_n(&(v)->counter, __ATOMIC_SEQ_CST) +#define atomic64_set(v, i) __atomic_store_n(&(v)->counter, (i), __ATOMIC_SEQ_CST) static inline int64_t atomic64_cmpxchg(atomic64_t *v, int64_t old, int64_t new_) { __atomic_compare_exchange_n(&v->counter, &old, new_, false, diff --git a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py index d77edbb801bbe..525b4decd66fb 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py @@ -312,8 +312,9 @@ def main(): { (void)d; (void)c; return finalize_result; } static int apple_dart_setup_translation_locked(struct apple_dart_domain *d, struct apple_dart_stream_map *m) { (void)d; (void)m; abort(); } -static int apple_dart_hw_sync_locked(struct io_pgtable_cfg *c, struct apple_dart_stream_map *m, bool b) -{ (void)c; (void)m; (void)b; abort(); } +static int apple_dart_hw_sync_locked(struct io_pgtable_cfg *c, struct apple_dart_stream_map *m, bool b, bool adopt) +{ (void)c; (void)m; (void)b; (void)adopt; abort(); } +static bool apple_dart_restore_deferred(struct apple_dart *d) { (void)d; return false; } static int apple_dart_fw_invalidate(struct apple_dart_stream_map *m, u64 a, u64 b) { (void)m; (void)a; (void)b; abort(); } static int apple_dart_dcp_domain_flush(struct apple_dart_domain *d) diff --git a/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py b/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py index b03fb73e3e312..3ec9b9a7ce495 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py @@ -54,6 +54,8 @@ def recovery_program(source): #define test_and_set_bit(bit,p) ({ unsigned long mask=1UL<<(bit); bool old=*(p)&mask; *(p)|=mask; old; }) #define xchg(ptr, value) ({ __typeof__(*(ptr)) old = *(ptr); *(ptr) = (value); old; }) static void bt_dev_err(struct hci_dev *h,const char *fmt,...) { assert(h && h->data->hdev==h && fmt);errors++; } +/* A restore from hibernation rebinds without an error. */ +static void bt_dev_info(struct hci_dev *h, const char *fmt, ...) { assert(h && h->data->hdev == h && fmt); } static void bt_dev_warn(struct hci_dev *h, const char *fmt, ...) { assert(h && h->data->hdev == h && fmt); diff --git a/tools/testing/selftests/drivers/apple/dwc3-sleep-gadget.py b/tools/testing/selftests/drivers/apple/dwc3-sleep-gadget.py index 35e0d9e5c3df0..170d051519037 100755 --- a/tools/testing/selftests/drivers/apple/dwc3-sleep-gadget.py +++ b/tools/testing/selftests/drivers/apple/dwc3-sleep-gadget.py @@ -107,7 +107,7 @@ def block(source, start): bool sleep_deep, core_active, core_exit_pending, reset_pending, shutting_down, sleep_dead; bool sleep_role_pending, sleep_stopped, sleep_tunnel, sleep_in_place, sleep_restart, fixed_hub; bool host_only, dt_dis_u3_susphy, sleep_ddr, sleep_phy_pending, sleep_phy_wait, ss_retry; - bool sleep_gadget_off, sleep_syscore; + bool sleep_gadget_off, sleep_syscore, sleep_hibernate; unsigned sleep_guid; struct work_struct sleep_tunnel_work, sleep_stop_work; struct delayed_work sleep_start_work, hub_check; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index bc3fc50f514ae..c3462cb3e49f0 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -446,6 +446,8 @@ def v27_panel_handoff(root): u8 firmware_dma_bits; /* Set in the T6030/T6031/T8122 profiles, not read by dcp_apply_dt_profile(). */ bool afk_name_fallback, v27_early_stop, v27_idle_cache, only_120hz_modes; + /* Read by the DRM start's ready wait, not by dcp_apply_dt_profile(). */ + unsigned int ready_timeout_ms; bool no_fw27_panel_pq; const struct dcp_s2r_layout *s2r_layout; }; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index f5a3fda65422e..664f2f8fbb2fb 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -737,7 +737,9 @@ def function(file, signature): struct apple_dcp_afkep *v27_early_svc_ep[0x20]; }; struct drm_edid { int identity; }; -'''+internal_inline(root,'dcp_is_v14_7_external')+r'''static unsigned int reads, allocations, legacy_reads, receives; +'''+internal_inline(root,'dcp_is_v14_7_external')+r'''/* No resume from disk in this control: the host session is never rebuilt. */ +static bool dcp_hib_tx_gated(const struct apple_dcp *d) { (void)d; return false; } +static unsigned int reads, allocations, legacy_reads, receives; static unsigned int event; static struct apple_dcp_afkep *received_ep; static struct apple_epic_service *hdr_bound; @@ -1020,6 +1022,8 @@ def function(text, signature): /* The T6030 firmware 27 service endpoints: none is started here. */ struct apple_dcp_afkep *v27_early_svc_ep[0x20]; }; +/* No resume from disk in this control: the host session is never rebuilt. */ +static bool dcp_hib_tx_gated(const struct apple_dcp *d) { (void)d; return false; } struct afk_receive_message_work { struct apple_dcp_afkep *ep; u64 message; struct work_struct work; }; struct apple_rtkit_ops { void (*recv_message)(void *,u8,u64); void (*recv_message_timed)(void *,u8,u64,u64); }; struct apple_rtkit { bool shutting_down, sync_syslog_ack, pmp_registry_v2; const struct apple_rtkit_ops *ops; void *cookie,*dev; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index 167aaa70acf25..ddbdff7762e16 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1031,7 +1031,7 @@ def poweroff_replug(root): struct apple_connector *connector; struct { bool active; } split; bool external_h17p, external_stop_deferred, soft_dpms, typec_output, usb4_output; - bool typec_cable_connected, typec_crtc_off, external_native, t6040_relinking; + bool typec_cable_connected, typec_crtc_off, external_native, ext_relinking; bool t6041_dpms, dpms_stop_ok; /* The fixed-HDMI standby hold; these Type-C cases never take it. */ bool hdmi_off_ready, hdmi_crtc_off; @@ -1049,6 +1049,8 @@ def poweroff_replug(root): { (void)d; (void)generation; return 0; } static void dcp_external_crtc_released(struct apple_dcp *d) { (void)d; } static bool dcp_uses_soft_dpms(struct apple_dcp *d) { return d->soft_dpms; } +/* No resume from disk in this control. */ +static bool dcp_hib_gated(const struct apple_dcp *d) { (void)d; return false; } static bool dcp_t6041_dpms_capable(struct apple_dcp *d) { return d->t6041_dpms; } /* The T8140 display power cycle has its own test on hardware; here it only has to be reached. */ static void iomfb_v27_idle_cache_cancel(struct apple_dcp *d) { (void)d; } @@ -1788,7 +1790,7 @@ def function(source, marker): struct apple_dcp { bool external_prepared, quiescing, crashed, external_native, ext_dead; enum dcp_firmware_version fw_compat; - struct { int iomfb_method_profile; } hw; + struct { int iomfb_method_profile; unsigned int ready_timeout_ms; } hw; struct work_struct external_audio_work; }; /* This readiness fixture has no AV owner or native audio initializer. */ diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index 651476232b445..de14b9b0e1671 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -1476,7 +1476,7 @@ def hotplug(root): struct work_struct external_stop_work,vblank_wq; bool external_physically_absent,main_display,typec_crtc_off,external_cable,external_error,external_power_attempted,external_stopped; bool external_hotplug_pending,external_hotplug_connected,typec_poweron_hpd; - bool t6040_relinking,t6040_plug_wait,hdmi_crtc_off; + bool ext_relinking,ext_plug_wait,hdmi_crtc_off; u64 external_stop_generation,external_rx_generation,external_crtc_generation; unsigned swap_watchdog_retrains;int typec_iomfb_hpd_ready,typec_display_ready;''') stubs = r''' @@ -1497,7 +1497,7 @@ def hotplug(root): #define queue_delayed_work(...) assert(!"HDMI standby hold in a Type-C scenario") #define cancel_delayed_work(...) assert(!"HDMI standby hold in a Type-C scenario") /* No T6040 sleep link work runs in this H17P scenario. */ -static void dcp_t6040_plug_done(struct apple_dcp *d,bool plug) { (void)d;(void)plug;assert(!"T6040 sleep link work in an H17P scenario"); } +static void dcp_ext_plug_done(struct apple_dcp *d,bool plug) { (void)d;(void)plug;assert(!"T6040 sleep link work in an H17P scenario"); } ''' dcp = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() template = (root / 'drivers/gpu/drm/apple/iomfb_template.c').read_text() diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index 12f800398c116..92bcbddc12645 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py @@ -55,7 +55,9 @@ def body(source,marker): fn uat_with(m4:bool,firmware:UatFirmware,clean_poc:bool,clean_tables:bool)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],clean_poc,quirks:Quirks{handoff_lock:true,clean_tables}})})} #[derive(Clone,Copy)]struct Prot{cached:bool}impl Prot{fn is_cached_noncoherent(&self)->bool{self.cached}} struct Mutation;impl Drop for Mutation{fn drop(&mut self){MUTATIONS.fetch_sub(1,Ordering::Relaxed);}} -struct MapTable{fail:bool}impl MapTable{fn unmap_pages(&mut self,_r:Range)->Result{LEAF_CLEARS.fetch_add(1,Ordering::Relaxed);if self.fail{Err(EIO)}else{Ok(())}}} +struct MapTable{fail:bool}impl MapTable{fn unmap_pages(&mut self,_r:Range)->Result{LEAF_CLEARS.fetch_add(1,Ordering::Relaxed);if self.fail{Err(EIO)}else{Ok(())}} +// A failed unmap leaves the range's leaves live. +fn first_live_leaf(&mut self,r:Range)->Result>{Ok(if self.fail{Some((r.start,r.end))}else{None})}} struct OwnerState{dev:(),is_kernel:bool,page_table:MapTable}impl OwnerState{fn mapping_mutation(&mut self)->Mutation{MUTATIONS.fetch_add(1,Ordering::Relaxed);Mutation}fn slot(&self)->Option{Some(0)}fn tlbi_range(&self,_a:u8,_v:u64,_s:usize){}fn tlbi_contexts_naming_root(&self,_v:u64,_s:usize){}} struct Owner(RefCell);impl Owner{fn lock_inner(&self)->std::cell::RefMut<'_,OwnerState>{self.0.borrow_mut()}} struct PinBo;struct KernelMappingInner{owner:Rc,uat_inner:Rc,prot:Prot,mapped_size:usize,_bo:Rc,private:Option>}