From 1db416f83f4cf537889db0b3cf44f564cd8992cd Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 13 Nov 2026 00:01:52 +0100 Subject: [PATCH 001/140] dt-bindings: chosen: document the aura hibernation layout The kernel hibernates on Apple silicon only where the boot object says, in /chosen, that it keeps the same memory layout on every boot, and it reads the device tree of the resuming boot at the address the boot object gives there. Neither property had a binding, and their prefix was not a registered one. Register the prefix and describe the two properties. The prefix is the name of the boot loader that defined them, as u-boot's is: its released versions publish the properties under this name, so a kernel that looked for another one would not hibernate with any of them. Signed-off-by: fbalazsy (cherry picked from commit c2119e142b1f4405ba2971c4d8cdd708638aed84) --- .../bindings/chosen/aura,hibernate.yaml | 64 +++++++++++++++++++ .../devicetree/bindings/vendor-prefixes.yaml | 2 + MAINTAINERS | 1 + 3 files changed, 67 insertions(+) create mode 100644 Documentation/devicetree/bindings/chosen/aura,hibernate.yaml 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/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/MAINTAINERS b/MAINTAINERS index 2cc9ae199bf9c..90bbceb9f76d1 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2094,6 +2094,7 @@ 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/display/apple,dcp.yaml F: Documentation/devicetree/bindings/display/apple,display-subsystem.yaml From 0cc237ddf2223bf8be975417dfb504b161a4513f Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:15 +0100 Subject: [PATCH 002/140] PM: hibernate: Make the image signature handling durable A REQ_SYNC write can sit in a volatile device cache, so the signature reset at resume and the end of the image are not on the medium when the write completes. A power loss after the restore then resumes the same image again, or the image is incomplete. Write the signature reset with FUA, flush the image in swap_writer_finish() and fail the hibernation (dropping the signature) when the flush fails. Once the image is in memory, clear the signature again before the devices are restored, so a restore that hangs cannot be resumed into a second time. Signed-off-by: fbalazsy (cherry picked from commit faaf017c06a653e9262b2ad1e4298ec62013672d) --- kernel/power/hibernate.c | 12 ++++++++ kernel/power/power.h | 1 + kernel/power/swap.c | 62 +++++++++++++++++++++++++++++++++++++--- 3 files changed, 71 insertions(+), 4 deletions(-) diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 890bf7b447f89..f1b0de2a09e8d 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -774,6 +774,18 @@ static int load_image_and_restore(void) } error = swsusp_read(&flags); + 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); diff --git a/kernel/power/power.h b/kernel/power/power.h index 75b63843886ee..6c269ce9410ec 100644 --- a/kernel/power/power.h +++ b/kernel/power/power.h @@ -201,6 +201,7 @@ 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); #ifdef CONFIG_SUSPEND extern int swsusp_unmark(void); #else diff --git a/kernel/power/swap.c b/kernel/power/swap.c index c78f1593600bb..28fd87f4f82d1 100644 --- a/kernel/power/swap.c +++ b/kernel/power/swap.c @@ -483,11 +483,27 @@ 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) { + int flush; + if (!error) { pr_info("S"); error = mark_swapfiles(handle, flags); pr_cont("|\n"); flush_swap_writer(handle); + /* + * 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. A failed flush leaves no durable image: drop + * the signature durably (unlike swsusp_unmark()) so that no + * later boot resumes from freed swap. + */ + flush = blkdev_issue_flush(file_bdev(hib_resume_bdev_file)); + if (!error && flush) { + if (swsusp_invalidate_sig()) + pr_err("image flush failed and the signature could not be dropped\n"); + error = flush; + } } if (error) @@ -1583,10 +1599,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 +1646,39 @@ 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. + */ +int swsusp_invalidate_sig(void) +{ + int error; + + error = hib_submit_io_sync(REQ_OP_READ, swsusp_resume_block, swsusp_header); + if (error) + return error; + /* + * swsusp_check() normally reset the signature already; that write may + * still be in the device's volatile cache, so rewrite the header with + * FUA either way and make the reset durable before the restore. + */ + if (!memcmp(HIBERNATE_SIG, swsusp_header->sig, 10)) + memcpy(swsusp_header->sig, swsusp_header->orig_sig, 10); + else if (memcmp(swsusp_header->sig, swsusp_header->orig_sig, 10)) + return -ENODEV; + error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_FUA, + swsusp_resume_block, swsusp_header); + /* A device that ignores FUA still honours an explicit cache flush. */ + if (!error) + error = blkdev_issue_flush(file_bdev(hib_resume_bdev_file)); + return error; +} + /** * swsusp_unmark - Unmark swsusp signature in the resume device * From 4161a74f26f6f9689ba6a5ae2ef061d0c79dd054 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:19 +0100 Subject: [PATCH 003/140] PM: hibernate: Tell drivers whether a restore went through a boot The devices of a kernel restored from an image get PMSG_RESTORE whether the image was loaded by another boot (the firmware and the boot loader reset the hardware) or by the kernel that wrote it (test_resume: the hardware kept its state). Drivers of devices that a boot resets need to tell the two apart. The kernel that loads an image leaves a record in the no-save section, which the image neither saves nor overwrites, and the restored kernel reads it: pm_hibernate_restored_cold() returns 1 after a load by another boot, 0 after a load of the own image. pm_hibernate_is_restored() says whether the kernel was restored at all, and pm_hibernate_is_loading() whether this kernel is loading an image, so freeze callbacks can tell a quiesce for the jump into an image from a freeze for an image of their own. A hibernation aborted before the image exists resumes the devices with PMSG_RECOVER. Signed-off-by: fbalazsy (cherry picked from commit 394d4a1ae34120d3ee57c362587551db63b48c16) --- include/linux/suspend.h | 10 +++ kernel/power/hibernate.c | 149 +++++++++++++++++++++++++++++++++++++-- kernel/power/main.c | 13 +++- kernel/power/power.h | 2 + 4 files changed, 169 insertions(+), 5 deletions(-) diff --git a/include/linux/suspend.h b/include/linux/suspend.h index 365437ce2cc02..baa20a855e101 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -453,6 +453,16 @@ 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); +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 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 f1b0de2a09e8d..a4ad05fae7948 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -81,6 +81,106 @@ 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); +} + #ifdef CONFIG_SUSPEND /** * pm_hibernation_mode_is_suspend - Check if hibernation has been set to suspend @@ -346,6 +446,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 +518,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 +546,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 +563,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,7 +612,7 @@ int hibernation_snapshot(int platform_mode) if (error || !in_suspend) swsusp_free(); - msg = in_suspend ? (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE; + msg = hibernate_resume_event(error); dpm_resume(msg); if (error || !in_suspend) @@ -551,6 +678,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 +688,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. @@ -929,8 +1060,18 @@ int hibernate(void) if (snapshot_test) { pm_pr_dbg("Checking hibernation image\n"); error = swsusp_check(false); - if (!error) + if (!error) { + /* + * 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; + } } thaw_processes(); 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 6c269ce9410ec..e43e77f9a999b 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) \ From f47a2e1b20362d354c59aa6b6af206b8e64096fb Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:20 +0100 Subject: [PATCH 004/140] PM: hibernate: Let platform code decide whether hibernation is refused Hibernation is refused on every Apple platform, because the drivers of their co-processors have no path to rebuild their state after the cold boot of a restore. Add hibernation_set_platform_check() so platform code can tell when that is handled for the running boot. Without a registered check Apple platforms keep refusing images as before. Signed-off-by: fbalazsy (cherry picked from commit 3891bc402830852c0dd8fd4ed213eb1521e6f310) --- include/linux/suspend.h | 1 + kernel/power/hibernate.c | 40 +++++++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/include/linux/suspend.h b/include/linux/suspend.h index baa20a855e101..4c61ffb302ade 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -422,6 +422,7 @@ 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); asmlinkage int swsusp_save(void); extern struct pbe *restore_pblist; int pfn_is_nosave(unsigned long pfn); diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index a4ad05fae7948..4e878e936588d 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -207,22 +207,42 @@ 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 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"); } @@ -242,7 +262,9 @@ 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); From 80c547abd30dc8d70cb0828dcae1689d630c6fba Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:17 +0100 Subject: [PATCH 005/140] PM: hibernate: Clean the loaded image to the PoC on arm64 Most image pages are loaded straight into their original frames through the cacheable linear map, not through the copy loop. Add an architecture hook, called for every valid image frame once the whole image is loaded and while the list of those frames is still intact, and implement it on arm64 by cleaning and invalidating the page to the PoC. Frames outside the boot kernel's linear map are left to the copy, which cleans them. Signed-off-by: fbalazsy (cherry picked from commit 7089f48daffe15ff2b9058c4e361ac04e33c4862) --- arch/arm64/Kconfig | 4 ++++ arch/arm64/kernel/hibernate.c | 24 ++++++++++++++++++++++++ include/linux/suspend.h | 17 +++++++++++++++++ kernel/power/snapshot.c | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+) diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig index 81f92a6fb50f7..224bba9710481 100644 --- a/arch/arm64/Kconfig +++ b/arch/arm64/Kconfig @@ -2689,6 +2689,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/kernel/hibernate.c b/arch/arm64/kernel/hibernate.c index 9398c8d0ecb03..c58e55db0dd81 100644 --- a/arch/arm64/kernel/hibernate.c +++ b/arch/arm64/kernel/hibernate.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -89,6 +90,29 @@ static inline void arch_hdr_invariants(struct arch_hibernate_hdr_invariants *i) memcpy(i->uts_version, init_utsname()->version, sizeof(i->uts_version)); } +/* + * 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); diff --git a/include/linux/suspend.h b/include/linux/suspend.h index 4c61ffb302ade..f76d9d4a24cdb 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -432,6 +432,23 @@ 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 once for every valid page frame of the image after the whole image + * has been loaded, while the list of those frames is still intact, 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 (the frame is restored + * from restore_pblist). + */ +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; } diff --git a/kernel/power/snapshot.c b/kernel/power/snapshot.c index b209712cb2c3a..b47b379f454be 100644 --- a/kernel/power/snapshot.c +++ b/kernel/power/snapshot.c @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -2750,6 +2751,37 @@ 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). + * 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 every image page before the jump. + */ +static void swsusp_clean_restored_image(void) +{ + unsigned long pfn, n = 0, skipped = 0; + + memory_bm_position_reset(&orig_bm); + for (pfn = memory_bm_next_pfn(&orig_bm); pfn != BM_END_OF_MAP; + pfn = memory_bm_next_pfn(&orig_bm)) { + if (!pfn_valid(pfn)) + continue; + if (!arch_hibernate_clean_image_page(pfn)) { + skipped++; + continue; + } + if (!(++n & 0xffff)) + cond_resched(); + } + pr_debug("%lu image pages cleaned, %lu left to the restore_pblist copy\n", + n, skipped); +} +#else +static inline void swsusp_clean_restored_image(void) {} +#endif + /** * snapshot_write_next - Get the address to store the next image page. * @handle: Snapshot handle structure to guide the writing. @@ -2871,6 +2903,8 @@ int snapshot_write_finalize(struct snapshot_handle *handle) 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) { + /* while orig_bm still lists the image: recycling overwrites it */ + swsusp_clean_restored_image(); memory_bm_recycle(&orig_bm); free_highmem_data(); } From d70454477379a31d347c9922861b3e919a1a084c Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:16 +0100 Subject: [PATCH 006/140] arm64: hibernate: Clean copied pages to the PoC swsusp_arch_suspend_exit() cleans every copied page to the PoU, which is enough for instruction fetch but not for DMA masters that do not snoop the CPU caches. A later eviction of a dirty line can then overwrite what such a device wrote since the restore. Clean to the PoC instead. Signed-off-by: fbalazsy (cherry picked from commit d98e6011a4dd72fe01f9ebe167947cee623656d9) --- arch/arm64/kernel/hibernate-asm.S | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) 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 From b894c796cf3d79b48e80fd3a09bcf0f6c3d3b427 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:21 +0100 Subject: [PATCH 007/140] arm64: hibernate: Add platform hooks for nosave ranges and the boot layout 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 any fixed layout of the boot loader. The kernel build check of the image header cannot see these. Let one platform register hooks: pfn_nosave() keeps ranges that the boot owns out of the image, and layout() mixes the platform's boot facts into a boot layout cookie that is stored in the image header next to the memory regions and the spin-table release addresses. A restore under another layout is refused. Signed-off-by: fbalazsy (cherry picked from commit 54d9b8e86f228cb7f47acccd640421d24cdb18b4) --- arch/arm64/include/asm/suspend.h | 32 +++++++++ arch/arm64/kernel/hibernate.c | 120 ++++++++++++++++++++++++++++++- 2 files changed, 149 insertions(+), 3 deletions(-) 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/hibernate.c b/arch/arm64/kernel/hibernate.c index c58e55db0dd81..dfc9a8e297370 100644 --- a/arch/arm64/kernel/hibernate.c +++ b/arch/arm64/kernel/hibernate.c @@ -12,6 +12,8 @@ #define pr_fmt(x) "hibernate: " x #include #include +#include +#include #include #include #include @@ -82,6 +84,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) @@ -90,6 +95,107 @@ 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. iBoot'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 @@ -119,7 +225,7 @@ int pfn_is_nosave(unsigned long pfn) 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) @@ -153,8 +259,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; } @@ -162,6 +269,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; @@ -171,6 +279,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, From 49f67dd2e8229147eb85503ddb51fcd42320c52e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:23 +0100 Subject: [PATCH 008/140] arm64: smp: spin-table: Park secondaries outside the image across hibernation Spin-table CPUs cannot be powered off; a parked CPU spins in kernel text that the boot kernel overwrites while it loads an image. Let them wait in a small pen outside the image instead, entered with the image's page tables, and have the restored kernel release them from it. A boot CPU whose node has no enable-method is treated as one that can leave the kernel. Signed-off-by: fbalazsy (cherry picked from commit b6838fb1954f0802b85e91c620cfa4946126f475) --- arch/arm64/include/asm/cpu_ops.h | 23 +++ arch/arm64/kernel/Makefile | 3 + arch/arm64/kernel/hibernate.c | 16 +- arch/arm64/kernel/smp.c | 23 ++- arch/arm64/kernel/smp_spin_table.c | 237 +++++++++++++++++++++++-- arch/arm64/kernel/smp_spin_table_pen.S | 34 ++++ 6 files changed, 319 insertions(+), 17 deletions(-) create mode 100644 arch/arm64/kernel/smp_spin_table_pen.S 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/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.c b/arch/arm64/kernel/hibernate.c index dfc9a8e297370..ce251b5b20d0d 100644 --- a/arch/arm64/kernel/hibernate.c +++ b/arch/arm64/kernel/hibernate.c @@ -475,7 +475,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; } @@ -524,6 +524,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 @@ -627,10 +630,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..124836466a49b 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_info("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_info("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 From 679355f782666a08e338aa67939e70b1e2498416 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:24 +0100 Subject: [PATCH 009/140] KVM: arm64: timer: Keep guest counters when the counter restarts in a sleep A guest's counters are the physical counter minus an offset fixed when the VM is made. The physical counter starts again across a resume from disk, which is a cold boot, so the guest's counters fall back and its clock stands still until the counter has caught up. Record the counter at syscore suspend and, if it went backwards at resume, move the offsets of every VM by what it lost, so the guest's counters continue as for a VM that was stopped that long. A counter that keeps running through the sleep is left alone. Signed-off-by: fbalazsy (cherry picked from commit ac2fa3d5078d02598ea1fc3ea60fed276d22caf0) --- arch/arm64/kvm/arch_timer.c | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) 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: From aea302f4543bab51bc9d80b4209c212b1e8261ec Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:25 +0100 Subject: [PATCH 010/140] soc: apple: rtkit: Hand running sessions over to a resumed kernel A co-processor that stays up across a resume from disk keeps the shared buffers of its session, which the restored kernel has to adopt. Add apple_rtkit_describe_buffers() and a small hand-over area in the no-save section in which the boot kernel leaves, per tagged session, what the restored kernel needs to take it over. Also let the polled power-state exchange used with interrupts off put the co-processor to idle for clients that stay up, and add apple_rtkit_reinit() to the Rust bindings. Signed-off-by: fbalazsy (cherry picked from commit f986895ffe00951af5c2d6f7294d22969962a60d) --- drivers/soc/apple/Makefile | 2 +- drivers/soc/apple/rtkit-hib-handoff.c | 179 ++++++++++++++++++++++++++ drivers/soc/apple/rtkit.c | 112 +++++++++++++++- include/linux/soc/apple/rtkit.h | 74 +++++++++++ rust/kernel/soc/apple/rtkit.rs | 9 ++ 5 files changed, 371 insertions(+), 5 deletions(-) create mode 100644 drivers/soc/apple/rtkit-hib-handoff.c diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 216234e3aba5d..86cffdfba1442 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -24,7 +24,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 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 be89050bcef44..fcb96227c4bec 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2164,6 +2164,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 @@ -2792,8 +2848,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; @@ -2806,7 +2863,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; @@ -2965,11 +3030,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; @@ -3504,6 +3574,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/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index e384fe1a1b108..18c2e2a57ed91 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -317,6 +318,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 */ @@ -400,6 +408,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 @@ -562,4 +580,60 @@ 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); + #endif /* _LINUX_APPLE_RTKIT_H_ */ 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. From 9a0adc692df7e9c33266a6302ab7f1421afbb6eb Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:27 +0100 Subject: [PATCH 011/140] soc: apple: rtkit-helper: Re-adopt a session after a resume from disk The boot kernel of a resume from disk holds RX of an adopted session and hands it over with its buffers; the restored kernel adopts it again in .restore. A self-started session is left for a reload, and a co-processor that the boot left halted is released without a handshake. Add .thaw and .restore callbacks and apple_rtkit_helper_readopted(). Signed-off-by: fbalazsy (cherry picked from commit c8d3761732c362da23a7aad950282a91310c6099) --- drivers/soc/apple/rtkit-helper.c | 257 +++++++++++++++++++++++-- include/linux/soc/apple/rtkit-helper.h | 16 ++ 2 files changed, 260 insertions(+), 13 deletions(-) diff --git a/drivers/soc/apple/rtkit-helper.c b/drivers/soc/apple/rtkit-helper.c index 2d0871dc5af5e..90a32b7d94bcf 100644 --- a/drivers/soc/apple/rtkit-helper.c +++ b/drivers/soc/apple/rtkit-helper.c @@ -54,6 +54,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; @@ -69,6 +75,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; @@ -125,9 +147,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); } /* @@ -153,8 +185,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; } @@ -264,6 +295,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) @@ -349,11 +387,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); @@ -364,7 +398,7 @@ static int apple_rtkit_helper_probe(struct platform_device *pdev) "Failed to adopt RTKit\n"); 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); @@ -405,6 +439,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_info(&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); @@ -595,12 +640,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_info(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 = { @@ -611,6 +840,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/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 From 59b1dd69b43f2ed71f749ac8337afaf4bca3af49 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:46:28 +0100 Subject: [PATCH 012/140] soc: apple: Allow hibernation under aura's fixed boot layout aura publishes /chosen/aura,hibernate-layout on a boot whose memory layout below Linux is the same on every boot, and copies the device tree of each boot to the slot named by /chosen/aura,hibernate-dt. On such a boot, keep every /memreserve/ and non-reusable /reserved-memory range except the kernel image out of the image, add the layout and the boot facts of /chosen to the boot layout cookie, and let hibernation through. Without the property hibernation and resume stay refused on Apple platforms. Also provide this boot's /chosen values and a deferred re-probe for drivers whose co-processor the resuming boot left halted. Signed-off-by: fbalazsy (cherry picked from commit 74acceec0380c7970b698d51c026083a1a6892bd) --- drivers/soc/apple/Kconfig | 13 + drivers/soc/apple/Makefile | 1 + drivers/soc/apple/aura-hibernate.c | 551 +++++++++++++++++++++++ include/linux/soc/apple/aura-hibernate.h | 32 ++ rust/bindings/bindings_helper.h | 1 + 5 files changed, 598 insertions(+) create mode 100644 drivers/soc/apple/aura-hibernate.c create mode 100644 include/linux/soc/apple/aura-hibernate.h diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 978833308016d..18181790c0cea 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -469,6 +469,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 && OF_DYNAMIC && OF_OVERLAY diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 86cffdfba1442..abf24e0edb0c8 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -78,3 +78,4 @@ apple-regview-y := regview.o obj-$(CONFIG_APPLE_REGVIEW_KUNIT_TEST) += regview-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/aura-hibernate.c b/drivers/soc/apple/aura-hibernate.c new file mode 100644 index 0000000000000..81aa997925ff1 --- /dev/null +++ b/drivers/soc/apple/aura-hibernate.c @@ -0,0 +1,551 @@ +// 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 the ranges kept out of the image cover all of [start, end). */ +static bool aura_hibernate_range_nosave(u64 start, u64 end) +{ + unsigned long pfn = PFN_DOWN(start), last = PFN_UP(end); + 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) + return false; + } + 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); +} + +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; +} + +/* + * 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 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); + +/* + * 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); + +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/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/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 01e0e6cfbced8..3da0006a9c8ea 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -114,6 +114,7 @@ #include #include #include +#include #include #include #include From c0b8c6dfb8c3d16d97c431d3e6cd5e43cc8681d1 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 02:52:36 +0100 Subject: [PATCH 013/140] soc: apple: pmp: rebuild the firmware session after a resume from disk After a resume from disk through a boot the boot loader has cold-restarted the PMP (its image resident in SRAM, the co-processor halted) and nothing replays the probe-time bring-up, so the firmware stays down: the display gate and cpufreq wait for a PMP that never reports running. The module cannot be reloaded, since the power-vote bridge is retained until reboot. Rebuild the session in place on PM_POST_HIBERNATION, the event the restored kernel sends (PM_POST_RESTORE only reaches the loading kernel when it fails to restore), from a notifier registered ahead of every consumer's restore notifier (ANE, DCP, GPU). The decision follows the co-processor's run bit, the state the loading kernel or the boot left: a running firmware (restored by the kernel that wrote the image, or an aborted hibernation) is left alone; a halted one gets its RTKit session reinitialised, its SRAM boot arguments patched again and the boot handshake driven as at probe. The notifier is registered outside pmp_lock, since the notifier chain lock is taken around the callback, which takes pmp_lock. The revocable MMIO guards are held only around the register accesses: they hold an RCU read-side lock, which must not be kept across the sleeping RTKit handshake. Signed-off-by: fbalazsy (cherry picked from commit 0833903b217b9e4082de02ab3b08f7642a37ca5c) --- drivers/soc/apple/pmp-export.c | 62 ++++++++++++++++--- drivers/soc/apple/pmp.rs | 108 +++++++++++++++++++++++++++++++++ include/linux/soc/apple/pmp.h | 2 + 3 files changed, 162 insertions(+), 10 deletions(-) diff --git a/drivers/soc/apple/pmp-export.c b/drivers/soc/apple/pmp-export.c index 79e1a70e515ad..b7ed02455f167 100644 --- a/drivers/soc/apple/pmp-export.c +++ b/drivers/soc/apple/pmp-export.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -20,27 +21,68 @@ 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 int apple_pmp_pm_notify(struct notifier_block *nb, unsigned long action, + void *unused) { - int ret = 0; - + 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 { + apple_pmp_restore(pmp_data); + 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 00795a75a035e..98fd1b686d258 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -202,6 +202,10 @@ struct PmpData { self_ack_start: bool, /// See [`PmpHwConfig::confirm_ioreg_len`]. confirm_ioreg_len: bool, + /// 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, } impl PmpData { @@ -239,11 +243,93 @@ impl PmpData { sram_backup_data, self_ack_start: cfg.self_ack_start, confirm_ioreg_len: cfg.confirm_ioreg_len, + check_bootargs_uuid: cfg.check_bootargs_uuid, } ), 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_info!(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_info!(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_info!(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(); @@ -918,6 +1004,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/include/linux/soc/apple/pmp.h b/include/linux/soc/apple/pmp.h index 8663ca195febe..59e9c05ff1e68 100644 --- a/include/linux/soc/apple/pmp.h +++ b/include/linux/soc/apple/pmp.h @@ -49,4 +49,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 From 72408f697d0928369de264ef422f57f7b558b33b Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 02:42:37 +0100 Subject: [PATCH 014/140] iommu: apple-dart: re-import locked firmware roots after a resume from disk A resume from disk through a boot finds every locked DART locked again by the boot loader 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 with -EBUSY, and with it every DMA mapping through the DART; on the M4 Pro the PMP and every DCP failed their buffer requests with -ENOMEM. Remember the physical address of each mapped locked root and the page table configuration last published into each locked stream. In .restore, read the live roots back: a root that moved is re-imported the way attach maps it, in two passes as attach does (every stream's roots are re-read and snapshotted before any of them is republished, so a root shared by several streams is snapshotted before Linux slots enter it), then the stream's page tables are published into it again. A root that did not move, as when the kernel that wrote the image loads it, is the one the image describes and is kept. Firmware-owned memory is never written: the old roots' published slots are forgotten, not retired. A failed stream is logged and does not fail the whole restore. Signed-off-by: fbalazsy (cherry picked from commit b7fa3a14970cdf9ea04580f3fee7b316a5ae060b) --- drivers/iommu/apple-dart.c | 212 ++++++++++++++++++++++++++++++++- include/linux/soc/apple/dart.h | 11 ++ 2 files changed, 222 insertions(+), 1 deletion(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 32226743df54f..c087ed4e5729d 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; @@ -624,6 +630,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 @@ -1594,6 +1608,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); @@ -1642,6 +1657,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; @@ -1745,6 +1762,8 @@ apple_dart_hw_sync_locked(struct io_pgtable_cfg *cfg, if (ret) goto out; } + if (dart->locked_ttbr[sid][0]) + dart->locked_cfg[sid] = cfg; } out: spin_unlock_irqrestore(&dart->lock, flags); @@ -8327,8 +8346,199 @@ 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 that did not move (the kernel that wrote the image loaded + * it) is still the one the image describes and is kept. 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; + } + /* Not replaced (the loading kernel wrote the image): as described. */ + if (phys == dart->locked_phys[sid][idx]) + 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); + 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_info(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 display consumer took down can be read before it is up. */ + if (READ_ONCE(dart->display_unpowered)) { + dart->restore_pending = true; + dev_info(dev, "hibernation restore deferred to its display's power-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; + dart->restore_pending = false; + ret = apple_dart_system_resume(dev); + if (ret || !dart->locked) { + dev_info(dev, "deferred hibernation restore at its display's power-up: %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); + dev_info(dev, "deferred hibernation restore at its display's power-up: %d\n", ret); +#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/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 4abc1753e447e..ec9944be138aa 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -229,6 +229,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. */ @@ -268,6 +270,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; From 7da17e53e43102cad565ea1a9c852ab8429d0be5 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 02:40:25 +0100 Subject: [PATCH 015/140] mfd: macsmc: start a new SMC session after a resume from disk After a resume from disk the RTKit session the restored driver describes is not the one the SMC is in, and every SMC command times out (battery, keyboard and trackpad preflight, power-off). The kernel that loads the image binds this driver like any boot and holds a live session when it jumps into the image; the restored kernel then asks the firmware to start and waits for a HELLO that a firmware already in a session never sends. Following Documentation/driver-api/pm/devices.rst, leave the restored kernel a defined state: - the loading kernel (pm_hibernate_is_loading()) quiesces the SMC in .freeze, the state the normal teardown leaves it in, from which a wake starts a new session. A failed quiesce still enters the image, whose signature is already gone; its restore tries a new session; - .restore reinitialises the RTKit transport, replays probe's bring-up handshake, re-reads the key count and re-arms the notification flag, the same whether the loading kernel wrote the image or was booted; - .thaw after a hand-over that could not enter the image starts a new session the same way. Probe's handshake and key count read move into helpers both use. Signed-off-by: fbalazsy (cherry picked from commit 216072f9ea16a402e593290eaff44fab5e15def0) --- drivers/mfd/macsmc.c | 158 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 132 insertions(+), 26 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index eec9a03ad0a74..2c9b91856e8d1 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -719,12 +719,53 @@ 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 int apple_smc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; const struct apple_smc_wake_reason *dt_reasons; struct apple_smc *smc; - __be32 count = 0; bool t6050; int ret; @@ -775,35 +816,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); @@ -2075,10 +2096,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_info(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) }; From 2e0637bf79340f1e37df3ad10e35f19401401cd7 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 3 Nov 2026 12:19:47 +0100 Subject: [PATCH 016/140] power: reset: macsmc-reboot: give an accepted power-off time to take effect The next power-off handler is PSCI SYSTEM_OFF. Under a boot monitor without a power-off path it resets the machine instead, so a slow or refused off1 must not fall through after only 100 ms: the image written for hibernation would be resumed at once, or the machine would reboot instead of powering off. Retry a refused off1 up to three times, and give an accepted one five seconds before warning and falling through. Signed-off-by: fbalazsy (cherry picked from commit 6ea1f046c02b09a3b33654131e0b86d81ac558fe) --- drivers/power/reset/macsmc-reboot.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) 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; } From dfdcdea8ba71e4c043ec4677c62cf9ded72cd258 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 20 Nov 2026 23:39:45 +0100 Subject: [PATCH 017/140] rtc: apple-pmu: let hibernation through the prepare step The prepare callback refuses every transition that is neither suspend-to-idle nor a firmware-driven suspend, because only those keep a way to bring the alarm back. Hibernation runs the same callback for its freeze, but with no suspend target set, so it is refused as well: on the M4 Pro (J616s) a hibernation pm_test run stops at this device ("apple_pmu_rtc_prepare returns -16") before any device is frozen. A hibernated machine comes back through a cold boot, which needs nothing from the alarm. Refuse only a suspend state that cannot keep the alarm, and let a transition without a suspend target through. Signed-off-by: fbalazsy (cherry picked from commit 0c1fbf57b16498eba20853d9845f86764e26be6c) --- drivers/rtc/rtc-apple-pmu.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/rtc/rtc-apple-pmu.c b/drivers/rtc/rtc-apple-pmu.c index 2388c2eafd722..8b30f66f33ee3 100644 --- a/drivers/rtc/rtc-apple-pmu.c +++ b/drivers/rtc/rtc-apple-pmu.c @@ -451,9 +451,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; } From 79242961358b613864d86278af4b798960edceb2 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 3 Nov 2026 12:19:47 +0100 Subject: [PATCH 018/140] cpufreq: apple-soc: restart the fast die-temperature wait when the PMP stops A resume from disk restarts the PMP after it had run. The fast die-temperature wait then reported the PMP as late, measured from the first boot. Start the wait, and its warning, over when the PMP stops. Signed-off-by: fbalazsy (cherry picked from commit 0148e6b5bccc787b54925c254a632523ae77346a) --- drivers/cpufreq/apple-soc-cpufreq.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index beb06e86090a6..6a06fc97d62cb 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -1066,6 +1066,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)) { From b4be361489b78dd6febc16bc3f63d0ddb8b0a72a Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 02:38:43 +0100 Subject: [PATCH 019/140] nvme-apple: support hibernation on post-M4 ANS On post-M4 ANS a resume from disk through a boot is a cold boot: the boot firmware restarted ANS, the boot stages kept it running, and the loading kernel adopted that session to read the image. In the restored kernel anv->rtk describes a firmware instance that no longer exists, and the live session on the mailbox has never been adopted by this kernel. Give the driver explicit hibernation callbacks: freeze and poweroff disable the controller and keep the session like suspend, thaw resumes. A .restore through a boot (pm_hibernate_restored_cold()) stops the controller first (until CC.EN is clear the firmware may fetch from the loading kernel's queues), releases the stale session without a shutdown handshake (the new instance would receive it), checks that a running, booted, enabled-off controller is there and adopts it, as probe adopts the boot loader's session, before the usual resume. A failure quarantines the controller. A .restore from the kernel that wrote the image finds the controller as its .freeze left it and resumes. Signed-off-by: fbalazsy (cherry picked from commit 594d6724b6b56b6f505d07d0ede00c16958e9748) --- drivers/nvme/host/apple.c | 122 +++++++++++++++++++++++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 8b52468c7f929..560e5876e44b8 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -2996,6 +2996,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 @@ -3854,8 +3857,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) }; From 5c7a72fc139d8ac8762903a28afecbdebec473b6 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 20 Nov 2026 23:25:45 +0100 Subject: [PATCH 020/140] accel/ane: H16: cycle the engine across hibernation as across suspend An H16 engine whose firmware has been started refuses hibernation and restore from its PM notifier, even on a platform that sleeps it cold. On the M4 Pro (J616s) that refusal is the first thing that stops a hibernation pm_test run, before the freezer level is reached. The cold cycle leaves nothing of the old firmware behind: the engine is powered off with nothing in flight, and after the transition the firmware boots again from the preload and every open program is replayed. Across suspend this already runs on the J616s ("powered down for system sleep", then "resume ok: cold" after every wake). An image needs no more than that, so on a platform without a warm sleep map PM_HIBERNATION_PREPARE and PM_RESTORE_PREPARE to the suspend prepare step and PM_POST_HIBERNATION and PM_POST_RESTORE to the wake step. A platform that sleeps the engine warm keeps firmware state across the transition that an image cannot carry; there both stay refused. Signed-off-by: fbalazsy (cherry picked from commit 78dac9674b848efcfa20c8ceb9ccc814f8dce699) --- drivers/accel/ane/ane_h16_backend.c | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/drivers/accel/ane/ane_h16_backend.c b/drivers/accel/ane/ane_h16_backend.c index 105ce4dbcbbb6..6de8a2b602482 100644 --- a/drivers/accel/ane/ane_h16_backend.c +++ b/drivers/accel/ane/ane_h16_backend.c @@ -1009,6 +1009,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); @@ -1027,6 +1050,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); @@ -1065,7 +1089,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; From 16259241ecf362dce0486712f4daf3c4013ee29e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 01:23:04 +0100 Subject: [PATCH 021/140] drm: apple: Suspend the DRM state for hibernation too The DCPs freeze and thaw through their system sleep callbacks, but the DRM device had only .suspend and .resume. A hibernation freeze therefore stopped the display firmware under an active mode configuration: the HDMI link of the external DCP went down in .freeze, the CRTC was never committed again on .thaw, and the HDMI output stayed disconnected until the next suspend and resume. Use the system sleep callbacks for the hibernation phases as well, so the DRM state is saved before the DCPs stop and committed again after they restart, as for suspend to RAM. Signed-off-by: fbalazsy (cherry picked from commit 1d4dbc57674294975badf3e29417bfd8d41aa1b1) --- drivers/gpu/drm/apple/apple_drv.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 281d6e11ec6f6..9660c36ba72ce 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -2994,6 +2994,10 @@ 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, + .freeze = apple_platform_suspend, + .thaw = apple_platform_resume, + .poweroff = apple_platform_suspend, + .restore = apple_platform_resume, .complete = apple_platform_complete, }; #else From 902b79ebe6585c683e2aa0d29ba6e0be2f2ac09d Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 3 Nov 2026 12:19:48 +0100 Subject: [PATCH 022/140] drm: apple: track piodma mappings on desktop 26.x firmware too Only the H17P handler marked a buffer mapped for piodma. On desktop 26.x the mark was never set, so neither a release nor the session drop after a resume from disk took the translation down, and the second resume from disk in one boot failed every piodma mapping with -EEXIST: no picture on the internal panel. Mark it there too, and refuse an unmap of a buffer that is not mapped, as on H17P, instead of reaching the page table. Signed-off-by: fbalazsy (cherry picked from commit dbbd96e4f5645ee755b82bb6dbd7337b38da4526) --- drivers/gpu/drm/apple/iomfb_template.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index c5ca1cb1f1408..283e5e24495e0 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -1220,6 +1220,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, @@ -1272,7 +1279,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 @@ -1409,8 +1416,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, From 42e77680f8bd5091d15b4ac17ac297ea49bae3a6 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 3 Nov 2026 12:19:49 +0100 Subject: [PATCH 023/140] drm: apple: dptxep: report link faults as warnings only with a sink attached Without a sink the firmware's probing of a DP port fails by design, which logged a warning on every external processor start, including each restart after a resume from disk. Log those at debug level and keep the warning when a sink is attached. Signed-off-by: fbalazsy (cherry picked from commit 4e27f7d05838d0d767daa4cc09aba58b3652d7c5) --- drivers/gpu/drm/apple/dcp-internal.h | 1 + drivers/gpu/drm/apple/dcp.c | 7 +++++++ drivers/gpu/drm/apple/dptxep.c | 15 +++++++++++---- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index fed8da33424ee..e67c2bbb7cfd2 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1490,6 +1490,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 c886a9bcde7b0..9133d8f656f1d 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1918,6 +1918,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 diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index 513514cd2cfb1..85c896bb23d01 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -1016,10 +1016,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: { From c2efa60e9ac011c6578c88249f70bbba98ae8ffd Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 3 Nov 2026 12:19:48 +0100 Subject: [PATCH 024/140] drm/apple: dcp: restart the display firmware in place after a resume from disk A resume from disk is a cold boot: the boot loader restarts the DCP firmware and lights the panel with its boot framebuffer, while the restored driver still holds the session of the previous firmware instance. Until now the driver had no hibernation callbacks, and the display was lost until a reboot. Rebuild the session in place, the way probe builds it, for the desktop 26.x internal DCP and for the T6041 external display processors: - prepare (hibernation only): stop the link work and the HDMI HPD interrupt, stop a merged dual pipe as a pair, and give the external display link and the DP PHYs back as at a runtime unplug, since the cold boot resets the PHY and the image must record it off; - freeze: hold RTKit receive, so whatever the new firmware sends before .restore stays in the mailbox instead of reaching the old session; - restore_early/restore: drop the old session on the host side (mode invalid, endpoints quiesced, IOMFB channels, firmware mappings, retained framebuffers and pending flips released; DMA only after the DARTs are restored). From here the DRM entry points leave the firmware alone and a flip completes without a swap; a shown external display is reported gone so that its return is a hotplug; - PM_POST_HIBERNATION, after the PMP is rebuilt and before the GPU drain, in a work item: run the co-processor, reinitialise RTKit and start the firmware as probe does, power the pipe on and commit the current DRM state. External processors with a display wait until every external processor runs, so a display wider than one pipe finds its peer, and then connect their link through the runtime hotplug path; the HDMI converter is powered again when the link comes back. Every devm allocation, the DMA arena (cleaned to the PoC before the restart), the IOMMU mappings, clocks and registers are reused; no probe primitive runs again. The old endpoint objects 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 teardown at the hibernation power-off is skipped, since the firmware's own power sequence may crash the DCP; the panel keeps the last frame until the machine powers off. If the hibernation fails, PM_POST_HIBERNATION replays the external links once every DCP is thawed. Signed-off-by: fbalazsy (cherry picked from commit 0dfc337436ae1ef73d441e9b08f7124e9814019d) --- drivers/gpu/drm/apple/dcp-internal.h | 68 ++ drivers/gpu/drm/apple/dcp.c | 1263 ++++++++++++++++++++++++- drivers/gpu/drm/apple/dcp_backlight.c | 3 + drivers/gpu/drm/apple/iomfb.c | 62 ++ 4 files changed, 1365 insertions(+), 31 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index e67c2bbb7cfd2..e0147af210775 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1381,6 +1381,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. */ @@ -1401,6 +1431,44 @@ void dcp_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr); /* Keep a session that cannot be stopped, its DMA and this driver until reboot. */ int dcp_retain_live_session(struct apple_dcp *dcp); +/* + * 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) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 9133d8f656f1d..9f574f3e62d76 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -43,12 +43,14 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -58,6 +60,7 @@ #include #include #include +#include #include #include #include @@ -1949,6 +1952,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); @@ -2377,6 +2383,9 @@ void dcp_send_message(struct apple_dcp *dcp, u8 endpoint, u64 message) if (READ_ONCE(dcp->quiescing) || (dcp_is_ext26(dcp) && READ_ONCE(dcp->ext26_blocked))) return; + /* Resume from disk: nothing reaches a firmware session not yet rebuilt. */ + if (dcp_hib_tx_gated(dcp)) + return; trace_dcp_send_msg(dcp, endpoint, message); /* * The adopted T6030 14.7 and native26 (ext26) sessions share this @@ -4843,6 +4852,34 @@ 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 fixed HDMI output connects without a sink. + */ +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; + 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; @@ -4933,16 +4970,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. - */ - if (!dptx_ret && dptx_service_available(&dcp->dptxport[0]) && - (dcp->fixed_phy || dcp->active_typec_route)) { - 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; } @@ -5563,8 +5592,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_t6040_ext_link_down()), after a resume from disk by the + * firmware restart (dcp_hib_recommit()). + */ + if (READ_ONCE(dcp->t6040_relinking) || dcp_hib_gated(dcp)) return; /* The takeover trial powered it on before the eviction. */ @@ -5766,8 +5799,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->t6040_relinking) || dcp_hib_gated(dcp)) return; if (iomfb_is_m4(dcp)) { @@ -7357,6 +7394,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; +} + static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *data) { struct device_node *panel_np; @@ -7622,12 +7669,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 @@ -8026,12 +8069,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); } /* @@ -8043,12 +8095,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"); @@ -8057,7 +8115,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); @@ -8103,6 +8161,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; @@ -8806,6 +8868,19 @@ 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); @@ -9422,6 +9497,27 @@ 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); +#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); @@ -9445,6 +9541,22 @@ VISIBLE_IF_KUNIT void dcp_platform_shutdown(struct platform_device *pdev) if (dcp && dcp_is_iboot(dcp)) return; + /* + * 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; @@ -9621,6 +9733,15 @@ static int dcp_platform_prepare(struct device *dev) struct apple_dcp *dcp = dev_get_drvdata(dev); const char *why; +#ifdef CONFIG_HIBERNATION + if (dcp_hibernating()) { + int ret = dcp_hib_prepare(dcp); + + if (ret) + return ret; + } +#endif + if (pm_suspend_via_firmware() && dcp_v27_sleep_selected(dcp)) { dcp_v27_sleep_invalidate(dcp); return 0; @@ -11499,6 +11620,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. @@ -11678,26 +11804,1062 @@ static int dcp_platform_resume(struct device *dev) return 0; } +#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 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; +} + +/* + * 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 void dcp_hib_ext_put(struct apple_dcp *dcp, bool start, bool idle) +{ + bool wake = false; + + 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); +} + +static bool dcp_hib_ext_settled(void) +{ + return !atomic_read(&dcp_hib_ext_starting) && + !atomic_read(&dcp_hib_ext_idle); +} + +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); + + dev_info(dcp->dev, + "hibernation restore: %s: CPU_CONTROL %#x (RUN %d) CPU_STATUS %#x\n", + when, ctl, !!(ctl & APPLE_DCP_COPROC_CPU_CONTROL_RUN), sts); +} + +/* + * 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 void dcp_hib_release_memdescs(struct apple_dcp *dcp) +{ + unsigned int id = 1, n = 0; + + /* 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); + + 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); +} + +/* 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; + + 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); + + /* 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_info(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_info(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_info(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_info(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_info(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_info(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_hib_ext_relink(struct apple_dcp *dcp) +{ + dcp->hib_link_released = false; + /* + * 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_info(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 = dcp_hib_ext_has_display(dcp); + + dcp_hib_ext_put(dcp, true, display); + 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: display %d, route %s, cable %d, DPTX port 0 connected %d\n", + when, display, + READ_ONCE(dcp->active_typec_route) ? "Type-C" : + dcp->fixed_phy ? "fixed" : "none", + READ_ONCE(dcp->typec_cable_connected), + READ_ONCE(dcp->dptxport[0].connected)); +} + +/* + * 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_info(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"); +} + +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"); + 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_info(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_info(dcp->dev, "hibernation restore: display restored\n"); +} + /* - * Hibernation: the T8132 power-down keeps the retained session, which a - * hibernation image cannot carry across the boot that restores it. + * 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; + } + 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; +} + static int dcp_platform_freeze(struct device *dev) { - if (iomfb_is_m4(dev_get_drvdata(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; - return dcp_platform_suspend(dev); + if (dcp_takeover_was_aborted(dcp) || READ_ONCE(dcp->ext_dead)) + return 0; + if (dcp->external) + return dcp_platform_suspend(dev); + /* 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; + } + 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); + + /* The image is written, or hibernation failed: the firmware ran on. */ + if (dcp->hib_rx_held) { + dcp->hib_rx_held = false; + apple_rtkit_resume_rx(dcp->rtk); + } + 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); + int ret; + + /* The power-off failed: .restore thaws. */ + if (!dcp || dcp->hib_poweroff_entered) + 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"); + ret = dcp_hib_register(dcp); + if (ret) { + /* .restore refuses, as for a processor it cannot restart. */ + dev_err(dev, "hibernation restore: no PM notifier (%d)\n", ret); + return 0; + } + /* Host side only: the DMA of the old session goes in .restore. */ + dcp_hib_quiesce(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); + } + dev_info(dev, + "hibernation restore: old firmware session dropped; restart after PM_POST_HIBERNATION\n"); + return 0; +} + +static int dcp_platform_restore(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + int ret; + + /* The power-off failed: the firmware ran on, as after a thaw. */ + if (dcp->hib_poweroff_entered) { + dcp->hib_poweroff_entered = false; + dev_info(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; + } + + 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"); + ret = dcp_hib_register(dcp); + if (!ret) { + dcp_hib_quiesce(dcp); + dcp_hib_release_dma(dcp); + dev_info(dev, + "hibernation restore: old firmware session dropped; restart after PM_POST_HIBERNATION\n"); + return 0; + } + dev_err(dev, "hibernation restore: no PM notifier (%d)\n", ret); + } + + 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->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), - .freeze = pm_sleep_ptr(dcp_platform_freeze), +#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_freeze), + .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 = { @@ -13246,15 +14408,54 @@ int dcp_t6041_s2r_all(bool start) return 0; } +#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) { - return platform_driver_register(&apple_platform_driver); + int ret; + +#ifdef CONFIG_HIBERNATION + ret = register_pm_notifier(&dcp_hib_global_nb); + if (ret) + return ret; +#endif + ret = platform_driver_register(&apple_platform_driver); +#ifdef CONFIG_HIBERNATION + if (ret) + unregister_pm_notifier(&dcp_hib_global_nb); +#endif + return ret; } void dcp_unregister(void) { platform_driver_unregister(&apple_platform_driver); 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_backlight.c b/drivers/gpu/drm/apple/dcp_backlight.c index b10ebd990dc31..276ea6434beb4 100644 --- a/drivers/gpu/drm/apple/dcp_backlight.c +++ b/drivers/gpu/drm/apple/dcp_backlight.c @@ -347,6 +347,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/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 77cd2db4a47e1..5749e9e084255 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 @@ -3947,6 +3950,10 @@ int dcp_crtc_atomic_modeset(struct drm_crtc *crtc, if (READ_ONCE(dcp->t6040_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. */ guard(mutex)(&dcp->external_lock); if (dcp_is_retained_external(dcp) && @@ -4808,6 +4815,16 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) 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; + } + dcp_desktop_ext_repower(dcp, crtc, commit); if (dcp->fw_compat == DCP_FIRMWARE_V_14_7) { iomfb_v14_7_flush(dcp, crtc, commit); @@ -4981,6 +4998,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; @@ -5028,10 +5073,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)); From 06973cb663116faaa0b8644e494e01062d9051b6 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 3 Nov 2026 12:19:49 +0100 Subject: [PATCH 025/140] drm/apple: bound kernel retrains of an active CRTC after hotplug 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. Retrain at most DCP_HOTPLUG_RETRAIN_MAX times in a DCP_HOTPLUG_RETRAIN_WINDOW that starts with the first retrain and is not extended by refused requests; at the end of the window one more retrain is tried. A real replug resets the bound. Past the limit the link status stays as it is and userspace still gets the hotplug events. Signed-off-by: fbalazsy (cherry picked from commit 18364022e1063e5a0262ba969682631e64a69890) --- drivers/gpu/drm/apple/dcp-internal.h | 11 +++ drivers/gpu/drm/apple/dcp.c | 16 +++++ .../drm/apple/dcp_external_announce_test.c | 1 + drivers/gpu/drm/apple/iomfb.c | 72 ++++++++++++++++++- 4 files changed, 99 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index e0147af210775..060da34b25142 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1358,6 +1358,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; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 9f574f3e62d76..868a4f65ec871 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -3940,6 +3940,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 = @@ -7023,6 +7034,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); } @@ -7038,6 +7050,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) @@ -8860,6 +8873,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); @@ -8897,6 +8912,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 diff --git a/drivers/gpu/drm/apple/dcp_external_announce_test.c b/drivers/gpu/drm/apple/dcp_external_announce_test.c index f07b3777cc751..38944eb138d76 100644 --- a/drivers/gpu/drm/apple/dcp_external_announce_test.c +++ b/drivers/gpu/drm/apple/dcp_external_announce_test.c @@ -113,6 +113,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/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 5749e9e084255..405f345d2aa7d 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -1986,6 +1986,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_info(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; @@ -2036,6 +2104,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) { @@ -2105,7 +2174,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); From 8fdc256e043cba54d89fff9e016a3449a6671ea1 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 02:37:38 +0100 Subject: [PATCH 026/140] drm/apple: take the T604x displays down for hibernation as for a sleep Hibernation restored the display firmware with a new handshake only, which assumes the boot loader started it anew. A restore by the kernel that wrote the image (test_resume) finds the firmware still in the session it ran on after the image was taken, and the handshake times out on every DCP: RTKit: endpoint discovery failed: -62 hibernation restore: firmware restart failed at start (-62) Per Documentation/driver-api/pm/devices.rst, .restore has to cope with whatever state the loading kernel left. Stop the display firmware at .freeze with the stop the suspend-to-RAM path already uses on the T604x display complex (dcp_t6041_s2r_all(), selected by the apple,display-power node), so the image holds it stopped by Linux, and keep it stopped through the image write, as amdgpu's .thaw does: .thaw brings it back only when the hibernation failed (pm_hibernate_is_recovering()) or the machine suspends instead (pm_hibernation_mode_is_suspend()), and PM_POST_HIBERNATION does when this kernel goes on after anything else. The firmware then is in exactly the state the image describes: - a .restore by the kernel that wrote the image (test_resume), or after a failed power-off, takes the sleep's warm return; - a .restore through a boot (pm_hibernate_restored_cold()) powers the domains and DARTs the same way, then gives the firmware the boot loader started the new handshake after PM_POST_HIBERNATION. A thaw that restarted the firmware for the image write left it in a newer session than the image: the restored kernel's warm return then crashed all three DCPs with ASSERT afk_messenger_common.c:67. The link release at hibernation prepare is not needed then, as the stop takes the external links down itself. Factor the host-side session drop into dcp_hib_drop_session() for both restore paths. Signed-off-by: fbalazsy (cherry picked from commit 223277a45052583915196bb76ee05730fc0426cb) --- drivers/gpu/drm/apple/apple_drv.c | 73 ++++++++++++-- drivers/gpu/drm/apple/dcp.c | 158 ++++++++++++++++++++++-------- drivers/gpu/drm/apple/dcp.h | 1 + 3 files changed, 183 insertions(+), 49 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 9660c36ba72ce..770212cab05af 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -92,6 +92,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) @@ -2853,7 +2854,8 @@ static bool apple_drm_firmware_stopped(struct apple_drm_private *apple) return stopped; } -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); @@ -2861,7 +2863,7 @@ static int apple_platform_suspend(struct device *dev) if (apple && apple->dark_held) return 0; - if (pm_suspend_via_firmware()) { + if (stop) { int ret = dcp_t6041_s2r_all(false); if (ret) @@ -2883,6 +2885,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(). @@ -2943,6 +2950,47 @@ 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) +{ + 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) { @@ -2961,6 +3009,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); @@ -2979,12 +3034,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); @@ -2994,10 +3049,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, - .freeze = apple_platform_suspend, - .thaw = apple_platform_resume, - .poweroff = apple_platform_suspend, - .restore = apple_platform_resume, +#ifdef CONFIG_HIBERNATION + .freeze = apple_platform_freeze, + .thaw = apple_platform_thaw, + .poweroff = apple_platform_freeze, + .restore = apple_platform_restore, +#endif .complete = apple_platform_complete, }; #else diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 868a4f65ec871..ce0ab5b07532d 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9527,6 +9527,7 @@ static bool dcp_hibernating(void) } static int dcp_hib_prepare(struct apple_dcp *dcp); +static bool dcp_t6041_hib_capable(void); #else static bool dcp_hibernating(void) { @@ -12664,6 +12665,9 @@ static int dcp_hib_prepare(struct apple_dcp *dcp) "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); @@ -12706,6 +12710,37 @@ static int dcp_hib_register(struct apple_dcp *dcp) 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_info(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); @@ -12775,7 +12810,6 @@ static int dcp_platform_thaw(struct device *dev) static int dcp_platform_restore_early(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); - int ret; /* The power-off failed: .restore thaws. */ if (!dcp || dcp->hib_poweroff_entered) @@ -12789,31 +12823,14 @@ static int dcp_platform_restore_early(struct device *dev) if (!dcp->hib_rx_held) dev_warn(dev, "hibernation restore: RTKit receive was not held in the image\n"); - ret = dcp_hib_register(dcp); - if (ret) { - /* .restore refuses, as for a processor it cannot restart. */ - dev_err(dev, "hibernation restore: no PM notifier (%d)\n", ret); - return 0; - } /* Host side only: the DMA of the old session goes in .restore. */ - dcp_hib_quiesce(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); - } - dev_info(dev, - "hibernation restore: old firmware session dropped; restart after PM_POST_HIBERNATION\n"); + dcp_hib_drop_session(dcp, false); return 0; } static int dcp_platform_restore(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); - int ret; /* The power-off failed: the firmware ran on, as after a thaw. */ if (dcp->hib_poweroff_entered) { @@ -12836,15 +12853,8 @@ static int dcp_platform_restore(struct device *dev) if (!dcp->hib_rx_held) dev_warn(dev, "hibernation restore: RTKit receive was not held in the image\n"); - ret = dcp_hib_register(dcp); - if (!ret) { - dcp_hib_quiesce(dcp); - dcp_hib_release_dma(dcp); - dev_info(dev, - "hibernation restore: old firmware session dropped; restart after PM_POST_HIBERNATION\n"); + if (!dcp_hib_drop_session(dcp, true)) return 0; - } - dev_err(dev, "hibernation restore: no PM notifier (%d)\n", ret); } if (READ_ONCE(dcp->retain_dma) || dcp->hw.adopt_live_session) @@ -13901,8 +13911,27 @@ static int dcp_t6041_boot_ps_io(struct apple_dcp *dcp, bool restore) return 0; } +/* + * 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); +} + static int dcp_t6041_start_one(struct device *dev, void *data) { + bool cold = data && *(bool *)data; struct apple_dcp *dcp = dev_get_drvdata(dev); struct dcp_t6041_power *pwr; const struct dcp_t6041_chain *main; @@ -13997,6 +14026,10 @@ static int dcp_t6041_start_one(struct device *dev, void *data) WRITE_ONCE(dcp->crashed, false); WRITE_ONCE(dcp->ext_dead, false); + if (cold) { + 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) { @@ -14133,8 +14166,9 @@ static struct dcp_t6041_chain *dcp_t6040_ext_chain(struct apple_dcp *host, */ static int dcp_t6040_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; @@ -14180,6 +14214,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) @@ -14188,6 +14226,11 @@ 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) { @@ -14336,6 +14379,29 @@ static void dcp_t6040_plug_work(struct work_struct *work) enum dcp_t6041_step { DCP_S2R_FW_STOP, DCP_S2R_WORDS_DOWN, DCP_S2R_START }; /* Each step once per sleep. */ +/* + * 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 (!dcp_t6041_down) + return 0; + 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.t6040) + ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &cold, + dcp_t6040_ext_start_one); + return ret; +} + static int dcp_t6041_s2r_step(enum dcp_t6041_step step) { struct apple_dcp *host = READ_ONCE(dcp_t6041_host); @@ -14346,19 +14412,8 @@ static int dcp_t6041_s2r_step(enum dcp_t6041_step step) if (!host) return -ENODEV; - if (step == DCP_S2R_START) { - if (!dcp_t6041_down) - return 0; - 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 || !dcp_t6041_down) return 0; @@ -14424,6 +14479,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 + #ifdef CONFIG_HIBERNATION /* Ahead of the per-DCP notifiers (priority -5). */ static int dcp_hib_global_notify(struct notifier_block *nb, unsigned long action, diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 230f3e433d5e8..f4f948eba5726 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -177,6 +177,7 @@ 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_t6040_relinks(void); +void dcp_t6041_hib_restore(void); int iomfb_start_rtkit(struct apple_dcp *dcp); void iomfb_ext26_start(struct apple_dcp *dcp); From a682f9f79195b7e4c508b1d6371d135d230fdc31 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 21 Nov 2026 12:19:40 +0100 Subject: [PATCH 027/140] phy: apple: t6040: keep the PHY state in a restore without a boot A test_resume load restores the image in the kernel that wrote it: the SoC was not powered down and the PHY, its coprocessor and the DP and USB sides its consumers kept are as the image records them. Resetting that state, as after a resume through a boot, made the DP side of a Type-C display look down while the display controller still held it, and the next mode set of that display failed. Only reset the state, and the coprocessor's RTKit session, when pm_hibernate_restored_cold() says the restore went through a boot (or cannot tell), as a resume from a sleep does only after the firmware took the SoC down (pm_resume_via_firmware()). Signed-off-by: fbalazsy (cherry picked from commit 27864609a7ae38e1b2372544d252ab33842443f2) --- drivers/phy/apple/t6040-usb2.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) 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); From 71afd9c6105516811a1c27fa6c00989ec4d1fa18 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 01:03:00 +0100 Subject: [PATCH 028/140] PM: hibernate: Clear a latched wakeup before the test_resume restore In the test_resume mode, hibernate() loads the image it has just written and restores it while the tasks are still frozen from the snapshot. The resume path clears the wakeup state in freeze_processes() before it quiesces the devices, but this path does not, so a wakeup that a wake IRQ latched during the image creation or write (a Bluetooth controller with wakeup allowed does this in the thaw) is still pending when dpm_suspend() runs for PMSG_QUIESCE. The quiesce then fails with -EBUSY before any device is called, without a message naming a device, and the restore is abandoned with "Failed to load image, recovering". Clear the wakeup state before the image is loaded, as the resume path does. Signed-off-by: fbalazsy (cherry picked from commit 88b362586ad6db5df66c2c90bfc087a53e9d7b48) --- kernel/power/hibernate.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 4e878e936588d..1fd3fa78c478b 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -1083,6 +1083,14 @@ int hibernate(void) pm_pr_dbg("Checking hibernation image\n"); error = swsusp_check(false); 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 From 34e4080155215255cbcf139fe916a297ea667dd4 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 07:37:38 +0100 Subject: [PATCH 029/140] PM: hibernate: Free the image's swap pages when a test_resume restore fails In the test_resume mode the kernel that wrote the image loads it back and jumps into it. The swap pages that hold the image are allocated in this kernel's swap map; the restored kernel's map predates them, so a restore that succeeds needs nothing freed. A restore that fails ("Failed to load image, recovering") leaves this kernel running with those pages still allocated and no owner for them, and nothing frees them: a later swapoff of that swap area never finishes, which stops the shutdown at "Deactivating swap" until a watchdog resets the machine. Free them when hibernate() comes back from the test restore. Signed-off-by: fbalazsy (cherry picked from commit ca6cc4cce79922006f973db4d072d38b68595b44) --- kernel/power/hibernate.c | 5 +++++ kernel/power/power.h | 1 + kernel/power/swap.c | 12 ++++++++++++ 3 files changed, 18 insertions(+) diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 1fd3fa78c478b..531792242e117 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -1102,6 +1102,11 @@ int hibernate(void) 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(); diff --git a/kernel/power/power.h b/kernel/power/power.h index e43e77f9a999b..d9d3353900c5f 100644 --- a/kernel/power/power.h +++ b/kernel/power/power.h @@ -204,6 +204,7 @@ 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/swap.c b/kernel/power/swap.c index 28fd87f4f82d1..6dbe843590190 100644 --- a/kernel/power/swap.c +++ b/kernel/power/swap.c @@ -1679,6 +1679,18 @@ int swsusp_invalidate_sig(void) return error; } +/** + * 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), nothing frees them, and swapoff then waits for them forever. + */ +void swsusp_free_image_swap(void) +{ + free_all_swap_pages(root_swap); +} + /** * swsusp_unmark - Unmark swsusp signature in the resume device * From 10ac8bac0be5e207d99296f3ac891070681ac81e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 08:06:59 +0100 Subject: [PATCH 030/140] wifi: brcmfmac: pcie: probe the chip again in a restore from hibernation The rings and the bus state in a hibernation image date from its freeze, but the firmware does not stay with them: in a test_resume it runs on through the image write, and after a boot the kernel that loads the image may have probed the chip and started its own firmware session. Either way the kernel that loads the image quiesces it with the D3 hand-shake of the freeze callback. The restore callback was the resume one, which finds the interrupt mask set and resumes the firmware in place on rings that no longer match. The firmware then stops answering a few seconds later ("firmware died (no response to control requests)"), and the chip reset that follows takes the machine down: a watchdog reset of a chip whose firmware waits in its D3 state does not complete. Give the restore its own callback that takes the path the resume already takes after a power loss: detach from the chip without touching it, so that brcmf_pcie_remove() does not reset it, free the host state and probe again. The probe brings the chip up from whatever state it was left in. Signed-off-by: fbalazsy (cherry picked from commit def5653e7dfcf853f4d8dd6c922beb5576af0795) --- .../broadcom/brcm80211/brcmfmac/pcie.c | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index ac9acda72b6a0..e94faaa0d0733 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -3675,12 +3675,47 @@ 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; +} + static const struct dev_pm_ops brcmf_pciedrvr_pm = { .suspend = brcmf_pcie_pm_enter_D3, .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, }; From 3e1f4e7cb64caa79740650920d38b5a64eaa68ef Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 08:07:00 +0100 Subject: [PATCH 031/140] Bluetooth: hci_bcm4377: Quiesce for hibernation and rebind on restore The system sleep callbacks served hibernation too. The freeze armed the wake IRQ and left the firmware running, as for a suspend with wakeup allowed: the controller kept writing to host memory while the image was created and, in the kernel that loads an image, while the image is restored over that memory, and its interrupt during the thaw latched a system wakeup. The restore resumed the firmware in place on rings from the image's freeze, while the controller had run on (test_resume) or had been set up by the kernel that loaded the image; the resume commands timed out ("command 0x0c01 tx timeout") before the driver rebound. Freeze and power off without a wake source, and rebind on restore as after a power loss. Signed-off-by: fbalazsy (cherry picked from commit e39587ea4e61c2ad65863eaa5de850bb38d69a85) --- drivers/bluetooth/hci_bcm4377.c | 56 +++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 3 deletions(-) diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 41e0da1442ecd..9dc78d8d7a0f9 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -3216,7 +3216,7 @@ static void bcm4377_power_lost_work(struct work_struct *work) bt_dev_err(hdev, "resume after the sleep failed: %d", ret); } -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); @@ -3247,7 +3247,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; @@ -3285,6 +3285,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", true); + return 0; +} + static int bcm4377_resume(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); @@ -3375,7 +3420,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, }; From 2ae0ad9e4e8c22e34adead5aac5c983bf097d5e4 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 13:02:43 +0100 Subject: [PATCH 032/140] arm64: hibernate: Run the exit code inside the CTXR execute window While an execute window is active, a CPU that is confined to it can only fetch instructions from inside the window. The boot CPU starts unconfined, but a system sleep restarts it at its reset vector, and from then on it is confined like the secondaries. swsusp_arch_resume() copies the exit code to a page from get_safe_page(), which can be anywhere in RAM. After a suspend-to-RAM, the jump to that page stops the CPU before the restored kernel runs, and the watchdog resets the machine. The kernel image lies inside the window. While one is active, copy the exit code to a page-aligned nosave page of the image. The image doesn't contain that page, so restoring the image does not overwrite it, as long as the image's kernel ran at the same physical address. Refuse the restore otherwise. Without a window nothing changes. Signed-off-by: fbalazsy (cherry picked from commit ec55d694815b97ac5de118fb5e1998b9f03fdd21) --- Documentation/arch/arm64/ctxr-execmem.rst | 7 ++++-- arch/arm64/kernel/hibernate.c | 28 ++++++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) 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/arch/arm64/kernel/hibernate.c b/arch/arm64/kernel/hibernate.c index ce251b5b20d0d..59ec0caf5b346 100644 --- a/arch/arm64/kernel/hibernate.c +++ b/arch/arm64/kernel/hibernate.c @@ -11,6 +11,7 @@ */ #define pr_fmt(x) "hibernate: " x #include +#include #include #include #include @@ -324,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) { @@ -332,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); From 2ef49434c9b020a3965fc12868d302861753fb36 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 13:39:17 +0100 Subject: [PATCH 033/140] usb: xhci: Skip the ep0 max packet check on a slot that is only enabled When the xHC loses its state, as on restore from hibernation, xhci_resume() resets it and frees every virtual device. A reset-resume then gives the device a new slot from hub_hc_release_resources(), with only an Enable Slot command, and usb_reset_and_verify_device() calls usb_ep0_reinit() before the port reset and Address Device. For a full-speed device xhci_endpoint_reset() compares ep0's max packet size in the usb_device, which still holds the value read before, with the one in the output context, which is still zero, and issues an Evaluate Context. A slot in the Enabled state can't evaluate a context, so the command fails with a Context State Error: usb 1-1: WARN: invalid context state for evaluate context command. Skip the check while the slot is only enabled. Address Device sets up ep0, and the core resets ep0 again if the descriptor reports another size. Signed-off-by: fbalazsy (cherry picked from commit f3484001777d68d3312bf63a117c2ef047e5bcf8) --- drivers/usb/host/xhci.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) 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 */ From 2a5c3253bda254a51c9853ba8e7eabad789cc8a3 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 16:43:17 +0100 Subject: [PATCH 034/140] arm64: smp: spin-table: Log the hibernation pen at debug level The CPU counts for the pen are printed on every hibernation and every restore. They tell nothing unless something goes wrong, so use pr_debug(). Signed-off-by: fbalazsy (cherry picked from commit e7cd4cbf456160d577e146932ac2c83640a7762a) --- arch/arm64/kernel/smp_spin_table.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/arm64/kernel/smp_spin_table.c b/arch/arm64/kernel/smp_spin_table.c index 124836466a49b..509bcf12ea875 100644 --- a/arch/arm64/kernel/smp_spin_table.c +++ b/arch/arm64/kernel/smp_spin_table.c @@ -267,8 +267,8 @@ void spin_table_hibernate_pen_end(bool frozen) 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_info("hibernation: %u CPUs wait outside the image\n", - cpumask_weight(&spin_table_cpus_penned)); + pr_debug("hibernation: %u CPUs wait outside the image\n", + cpumask_weight(&spin_table_cpus_penned)); } /* @@ -305,7 +305,7 @@ void spin_table_hibernate_restored(void) cpumask_set_cpu(cpu, &spin_table_cpus_penned); found++; } - pr_info("hibernation: %u CPUs start from the boot kernel's pen\n", 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). */ From 885c83275a326d6e5ac0d0a686286d97469c3c82 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 16:43:17 +0100 Subject: [PATCH 035/140] drm/apple: dcp: Log the hibernation steps at debug level Each hibernation and restore printed a dozen informational lines per display controller. Keep them as dev_dbg() for debugging, and print a failed power-off, after which the firmware session is kept, as a warning. Signed-off-by: fbalazsy (cherry picked from commit 7dc5c4b5bf2879555dec9622984621d4c7804ffe) --- drivers/gpu/drm/apple/dcp.c | 88 +++++++++++++++++------------------ drivers/gpu/drm/apple/iomfb.c | 2 +- 2 files changed, 45 insertions(+), 45 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index ce0ab5b07532d..dfd414042e199 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -11958,9 +11958,9 @@ 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); - dev_info(dcp->dev, - "hibernation restore: %s: CPU_CONTROL %#x (RUN %d) CPU_STATUS %#x\n", - when, ctl, !!(ctl & APPLE_DCP_COPROC_CPU_CONTROL_RUN), sts); + 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); } /* @@ -12146,7 +12146,7 @@ static void dcp_hib_release_ext_link(struct apple_dcp *dcp) if (ret < 0) dev_warn(dcp->dev, "hibernation: dual-pipe pair not stopped: %d\n", ret); else if (ret > 0) - dev_info(dcp->dev, "hibernation: dual-pipe pair stopped\n"); + dev_dbg(dcp->dev, "hibernation: dual-pipe pair stopped\n"); ret = 0; if (dcp->avep) av_service_disconnect(dcp); @@ -12172,11 +12172,11 @@ static void dcp_hib_release_ext_link(struct apple_dcp *dcp) phy_exit(dcp->fixed_phy); dcp->hib_fixed_phy_off = true; } - dev_info(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); + 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()). */ @@ -12218,8 +12218,8 @@ static void dcp_hib_peer_reset(struct apple_dcp *dcp) peer = dcp->peer_reserved; owner = dcp->peer_owner; if (peer || owner) - dev_info(dcp->dev, "hibernation restore: dual-pipe pairing with %s dropped\n", - dev_name((peer ?: owner)->dev)); + 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)); @@ -12318,13 +12318,13 @@ static void dcp_hib_quiesce_ext(struct apple_dcp *dcp) d->ext_pipe_off = true; dcp_hib_peer_reset(dcp); - dev_info(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"); + 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. */ @@ -12394,8 +12394,8 @@ static int dcp_hib_recommit(struct apple_dcp *dcp) "hibernation restore: backlight blank unavailable: %d\n", ret); ret = 0; - dev_info(dcp->dev, - "hibernation restore: CRTC off, pipe powered, mode set on enable\n"); + dev_dbg(dcp->dev, + "hibernation restore: CRTC off, pipe powered, mode set on enable\n"); goto unlock; } @@ -12430,10 +12430,10 @@ static int dcp_hib_recommit(struct apple_dcp *dcp) WRITE_ONCE(dcp->hib_phase, DCP_HIB_NONE); ret = drm_atomic_commit(state); if (!ret) - dev_info(dcp->dev, - "hibernation restore: mode " DRM_MODE_FMT " committed, valid %d\n", - DRM_MODE_ARG(&cs->mode), - READ_ONCE(dcp->mode_state.valid)); + 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: @@ -12486,7 +12486,7 @@ static void dcp_hib_ext_relink(struct apple_dcp *dcp) if (dcp->dp2hdmi_pwren) gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 1); msleep(100); - dev_info(dcp->dev, "hibernation: HDMI converter powered again\n"); + dev_dbg(dcp->dev, "hibernation: HDMI converter powered again\n"); } dcp_hib_fixed_phy_on(dcp); if (dcp->hib_typec_disabled) { @@ -12523,13 +12523,13 @@ static void dcp_hib_ext_link_up(struct apple_dcp *dcp, const char *when) dcp_hib_ext_relink(dcp); dcp_hib_ext_put(dcp, false, true); - dev_info(dcp->dev, - "hibernation %s: external link replayed: display %d, route %s, cable %d, DPTX port 0 connected %d\n", - when, display, - READ_ONCE(dcp->active_typec_route) ? "Type-C" : - dcp->fixed_phy ? "fixed" : "none", - READ_ONCE(dcp->typec_cable_connected), - READ_ONCE(dcp->dptxport[0].connected)); + dev_dbg(dcp->dev, + "hibernation %s: external link replayed: display %d, route %s, cable %d, DPTX port 0 connected %d\n", + when, display, + READ_ONCE(dcp->active_typec_route) ? "Type-C" : + dcp->fixed_phy ? "fixed" : "none", + READ_ONCE(dcp->typec_cable_connected), + READ_ONCE(dcp->dptxport[0].connected)); } /* @@ -12545,11 +12545,11 @@ static void dcp_hib_ext_restore(struct apple_dcp *dcp) dcp_hib_give_up(dcp, "iomfb-ready", left ? -ENODEV : -ETIMEDOUT); return; } - dev_info(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])); + 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"); @@ -12608,16 +12608,16 @@ static void dcp_hib_restore_work(struct work_struct *work) dcp_hib_give_up(dcp, "iomfb-ready", ret); return; } - dev_info(dcp->dev, - "hibernation restore: firmware session up, endpoints %#010x, main display %d\n", - dcp->desktop->graph_started, dcp->main_display); + 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_info(dcp->dev, "hibernation restore: display restored\n"); + dev_dbg(dcp->dev, "hibernation restore: display restored\n"); } /* @@ -12736,8 +12736,8 @@ static int dcp_hib_drop_session(struct apple_dcp *dcp, bool release_dma) } if (release_dma) dcp_hib_release_dma(dcp); - dev_info(dcp->dev, - "hibernation restore: old firmware session dropped; restart after PM_POST_HIBERNATION\n"); + dev_dbg(dcp->dev, + "hibernation restore: old firmware session dropped; restart after PM_POST_HIBERNATION\n"); return 0; } @@ -12835,7 +12835,7 @@ static int dcp_platform_restore(struct device *dev) /* The power-off failed: the firmware ran on, as after a thaw. */ if (dcp->hib_poweroff_entered) { dcp->hib_poweroff_entered = false; - dev_info(dev, "hibernation power-off failed: firmware session kept\n"); + dev_warn(dev, "hibernation power-off failed: firmware session kept\n"); return dcp_platform_thaw(dev); } diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 405f345d2aa7d..a7bad6d16f17a 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -2009,7 +2009,7 @@ void dcp_route_failure_notify(struct apple_connector *connector) static void dcp_hotplug_retrain_reset(struct apple_dcp *dcp, const char *why) { if (dcp->hotplug_retrain_stopped) - dev_info(dcp->dev, "hotplug: link retrains resumed (%s)\n", why); + dev_dbg(dcp->dev, "hotplug: link retrains resumed (%s)\n", why); dcp->hotplug_retrain_stopped = false; dcp->hotplug_retrains = 0; } From 09ec99c196d209d02de1bc553a4a8b35f2595416 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 16:43:17 +0100 Subject: [PATCH 036/140] iommu: apple-dart: Log the hibernation restore at debug level The re-import of the locked streams logs each failed stream as an error already. Print the summary and the deferral at debug level, and report a failed deferred restore as an error. Signed-off-by: fbalazsy (cherry picked from commit 4d6ce80b97da81f8cac74536e7d035af8f33c36e) --- drivers/iommu/apple-dart.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index c087ed4e5729d..d9546806306e1 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -8457,8 +8457,8 @@ static int apple_dart_reimport_locked(struct apple_dart *dart) } done++; } - dev_info(dart->dev, "hibernation restore: %d locked streams re-imported (%d)\n", - done, ret); + dev_dbg(dart->dev, "hibernation restore: %d locked streams re-imported (%d)\n", + done, ret); return ret; } @@ -8470,7 +8470,7 @@ static int apple_dart_restore(struct device *dev) /* No register of a block its display consumer took down can be read before it is up. */ if (READ_ONCE(dart->display_unpowered)) { dart->restore_pending = true; - dev_info(dev, "hibernation restore deferred to its display's power-up\n"); + dev_dbg(dev, "hibernation restore deferred to its display's power-up\n"); return 0; } ret = apple_dart_system_resume(dev); @@ -8514,7 +8514,8 @@ int apple_dart_display_restore(struct device *dev) dart->restore_pending = false; ret = apple_dart_system_resume(dev); if (ret || !dart->locked) { - dev_info(dev, "deferred hibernation restore at its display's power-up: %d\n", ret); + if (ret) + dev_err(dev, "deferred hibernation restore failed: %d\n", ret); return ret; } ret = pm_runtime_resume_and_get(dev); @@ -8522,7 +8523,7 @@ int apple_dart_display_restore(struct device *dev) return ret; ret = apple_dart_reimport_locked(dart); pm_runtime_put(dev); - dev_info(dev, "deferred hibernation restore at its display's power-up: %d\n", ret); + dev_dbg(dev, "deferred hibernation restore at its display's power-up: %d\n", ret); #endif return ret; } From 1c31733b4d30babc05406054bb91136314ad2d5b Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 16:43:17 +0100 Subject: [PATCH 037/140] mfd: macsmc: Log the hand-over for the restored kernel at debug level The SMC quiesce before the image is entered is the normal path. A failure is reported as an error already. Signed-off-by: fbalazsy (cherry picked from commit 646b918e6691c0261f44f1242cf103f22e68b1f0) --- drivers/mfd/macsmc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index 2c9b91856e8d1..d91743c4ed71a 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -2129,7 +2129,7 @@ static int apple_smc_freeze(struct device *dev) return 0; } apple_smc_handed_over = true; - dev_info(dev, "SMC quiesced for the restored kernel\n"); + dev_dbg(dev, "SMC quiesced for the restored kernel\n"); return 0; } From 0c0ffbe127b96ef966cf88bb352ced28a6f60160 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 16:43:18 +0100 Subject: [PATCH 038/140] soc: apple: Log the co-processor restore steps at debug level The PMP and RTKit helper restore paths printed their normal progress as informational messages on every resume from disk. Errors and warnings stay as they are. Signed-off-by: fbalazsy (cherry picked from commit c2a7b9582c5f6a1b0a440240ba2b73d68d9527b1) --- drivers/soc/apple/pmp.rs | 6 +++--- drivers/soc/apple/rtkit-helper.c | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index 98fd1b686d258..fda4928d9e3d9 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -291,7 +291,7 @@ impl PmpData { let asc = self.asc_mmio.try_access().ok_or(ENODEV)?; asc.as_view().relaxed().read(ASC_CPU_CONTROL).cpu_run() != 0 }; - dev_info!(self.dev, "PMP restore: ASC CPU_RUN={}\n", cpu_running as u32); + 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)?; @@ -302,7 +302,7 @@ impl PmpData { if cpu_running { // The firmware never stopped (an aborted hibernation, or a // restore failure in the boot kernel): nothing to rebuild. - dev_info!(self.dev, "PMP restore: firmware still running, left as is\n"); + 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 @@ -327,7 +327,7 @@ impl PmpData { .update(ASC_CPU_CONTROL, |r| r.with_const_cpu_run::<1>()); } self.start()?; - dev_info!(self.dev, "PMP restore: firmware and endpoint back\n"); + dev_dbg!(self.dev, "PMP restore: firmware and endpoint back\n"); Ok(()) } fn start(&self) -> Result<()> { diff --git a/drivers/soc/apple/rtkit-helper.c b/drivers/soc/apple/rtkit-helper.c index 90a32b7d94bcf..ea0d51b356a44 100644 --- a/drivers/soc/apple/rtkit-helper.c +++ b/drivers/soc/apple/rtkit-helper.c @@ -446,7 +446,7 @@ static void apple_rtkit_helper_remove(struct platform_device *pdev) * without a handshake so that the next probe starts the CPU again. */ if (!apple_rtkit_helper_cpu_running(helper)) { - dev_info(&pdev->dev, "co-processor halted underneath (resume from disk): removed without quiesce\n"); + dev_dbg(&pdev->dev, "co-processor halted underneath (resume from disk): removed without quiesce\n"); return; } @@ -746,7 +746,7 @@ static int apple_rtkit_helper_restore_own(struct apple_rtkit_helper *helper) ret); } else { helper->halted_underneath = true; - dev_info(dev, "resume from disk: self-started RTKit session left for a reload\n"); + dev_dbg(dev, "resume from disk: self-started RTKit session left for a reload\n"); } return 0; } From 901794ef29b5dc4dddbcd69ae9de732255d28795 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 16:43:18 +0100 Subject: [PATCH 039/140] MAINTAINERS: Add the aura hibernation files List the aura hibernation layout driver, its header and the RTKit hand-off helper with the other Aurora platform files. Signed-off-by: fbalazsy (cherry picked from commit c9695f6218262d5a1b8a2bce8b2793c75b90c4de) --- MAINTAINERS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 90bbceb9f76d1..091b180a28dee 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2137,9 +2137,12 @@ 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 From 6aecea1ac6451a7acf36ccea6ee65ffbe33681b5 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 17:08:32 +0100 Subject: [PATCH 040/140] media: apple: isp: Start restartable firmware again after hibernation Firmware that starts again (hw->fw_restart) runs its text from the memory the boot loader loaded it into, and gets its data segment and heap back from the copies kept at probe. It is restarted after a sleep that powers the SoC down, but a hibernation marks it dead, so the camera stays unavailable after a thaw or a restore until the next boot. Stop it for the freeze as for such a sleep. A thaw finds the memory as it was. A restore comes from another boot, so take a CRC32 of the text segment at the freeze and restart the firmware only if that boot has loaded the same text at the same place. Otherwise the firmware stays down until the next boot, as before. Firmware that cannot start again is handled as before. Signed-off-by: fbalazsy (cherry picked from commit 870c1fc71f55055826c081148caaf606cb03010f) --- drivers/media/platform/apple/isp/Kconfig | 1 + drivers/media/platform/apple/isp/isp-drv.c | 71 +++++++++++++++++++--- drivers/media/platform/apple/isp/isp-drv.h | 7 +++ 3 files changed, 70 insertions(+), 9 deletions(-) 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 302e59f65acd5..793da7ab79b38 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 @@ -1659,29 +1660,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); @@ -1736,8 +1763,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); @@ -1763,13 +1790,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 b3dccaf9a7508..ab59c48ed905b 100644 --- a/drivers/media/platform/apple/isp/isp-drv.h +++ b/drivers/media/platform/apple/isp/isp-drv.h @@ -467,6 +467,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; From eb0aa1db40664d69db9765cf27291e0ffe5d4d09 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 17:33:43 +0100 Subject: [PATCH 041/140] soc: apple: aura-hibernate: Drop the helpers no driver uses Nothing calls aura_hibernate_boot_fw_regions() or aura_hibernate_reprobe_after_thaw(), and no Rust code uses the header. Drop both, with the declarations kept for Rust bindings and the bindings include. Signed-off-by: fbalazsy (cherry picked from commit 7e07d3811ede2ae4f54e6698c46dbe285649a884) --- drivers/soc/apple/aura-hibernate.c | 197 +---------------------- include/linux/soc/apple/aura-hibernate.h | 18 --- rust/bindings/bindings_helper.h | 1 - 3 files changed, 1 insertion(+), 215 deletions(-) diff --git a/drivers/soc/apple/aura-hibernate.c b/drivers/soc/apple/aura-hibernate.c index 81aa997925ff1..cc88dc2cff06e 100644 --- a/drivers/soc/apple/aura-hibernate.c +++ b/drivers/soc/apple/aura-hibernate.c @@ -18,8 +18,7 @@ * 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. + * save it, so after a resume the kernel finds this boot's tree at the address it was started with. * * 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()). @@ -31,14 +30,11 @@ #include #include #include -#include -#include #include #include #include #include #include -#include #include #include #include @@ -212,26 +208,6 @@ static void __init aura_nosave_range(u64 start, u64 end, unsigned long kstart, u pr_debug("nosave %s [%#llx, %#llx)\n", what, start, end); } -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; -} - /* * 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. @@ -254,137 +230,6 @@ static bool aura_slot_tree_valid(const void *fdt, phys_addr_t slot, const u64 la fdt64_ld(&v[1]) == layout[1]; } -/* - * 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); - /* * 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 @@ -418,46 +263,6 @@ int aura_hibernate_boot_chosen_u64(const char *name, u64 *val) } EXPORT_SYMBOL_GPL(aura_hibernate_boot_chosen_u64); -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)); diff --git a/include/linux/soc/apple/aura-hibernate.h b/include/linux/soc/apple/aura-hibernate.h index 729ced7b3c4cb..23a7b1f6eb972 100644 --- a/include/linux/soc/apple/aura-hibernate.h +++ b/include/linux/soc/apple/aura-hibernate.h @@ -5,24 +5,6 @@ #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 diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 3da0006a9c8ea..01e0e6cfbced8 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -114,7 +114,6 @@ #include #include #include -#include #include #include #include From cf9b0e4834338ddb849290a05de498208de15c96 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 17:33:50 +0100 Subject: [PATCH 042/140] soc: apple: sleep: Take this boot's S2R mailbox after a resume from disk aura's S2R mailbox moves with the boot object on every boot, so after a resume from disk the mailbox mapped at probe belongs to the boot that wrote the image and no aura reads it. A deep sleep through it would hand the wake to an address the running aura never looks at. On restore, read this boot's mailbox from aura's device tree, check its magic and boot CPU as at probe, and switch to it. Without a valid one, refuse deep sleep until the next boot. Signed-off-by: fbalazsy (cherry picked from commit 4d6eb856a57224c9ffeb92ebbc5f7ebdfe22b87e) --- drivers/soc/apple/sleep.c | 64 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 611fe3de6e1e9..259b853724875 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -73,6 +73,7 @@ #include #include #include +#include #include #include #include @@ -942,6 +943,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; @@ -6904,6 +6908,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; @@ -7697,6 +7704,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) @@ -7711,6 +7719,61 @@ 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) + 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; + 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) @@ -10186,6 +10249,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, }; From 4b957d697764c58222fee59265f9f44e83366c8e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 18:16:05 +0100 Subject: [PATCH 043/140] PM: hibernate: Clean each image page to the PoC as it is loaded The loaded image was cleaned to the PoC in one pass over every image frame after the load: 0.54 s on a single CPU for an 8.5 GB image on a J616s, with nothing else to do meanwhile. Clean each page that is loaded straight into its original frame as soon as its contents are complete, where it is protected, while the loader waits for the next one to be read and decompressed. A page that goes through restore_pblist is still cleaned by the copy. Signed-off-by: fbalazsy (cherry picked from commit 42abb79b145b094d2bb4fa78bb73bc7b70e1e3b8) --- include/linux/suspend.h | 9 ++++--- kernel/power/snapshot.c | 52 ++++++++++++++++++++++------------------- 2 files changed, 32 insertions(+), 29 deletions(-) diff --git a/include/linux/suspend.h b/include/linux/suspend.h index f76d9d4a24cdb..85ad46cb1b79d 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -438,13 +438,12 @@ int arch_hibernation_header_restore(void *addr); * @pfn: Valid page frame of the image. * * Provided by an architecture that sets ARCH_HIBERNATION_CLEAN_IMAGE. - * Called once for every valid page frame of the image after the whole image - * has been loaded, while the list of those frames is still intact, so that - * the architecture can clean the caches for devices that do not snoop them. + * 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 (the frame is restored - * from restore_pblist). + * nothing was loaded into it through the linear map. */ int arch_hibernate_clean_image_page(unsigned long pfn); #endif diff --git a/kernel/power/snapshot.c b/kernel/power/snapshot.c index b47b379f454be..4a37d9fa79ff3 100644 --- a/kernel/power/snapshot.c +++ b/kernel/power/snapshot.c @@ -2754,32 +2754,31 @@ static void *get_buffer(struct memory_bitmap *bm, struct chain_allocator *ca) #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). - * 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 every image page before the jump. + * 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 void swsusp_clean_restored_image(void) +static unsigned long nr_cleaned_pages; + +static void swsusp_clean_loaded_page(void *addr) { - unsigned long pfn, n = 0, skipped = 0; + unsigned long pfn = memory_bm_get_current(&orig_bm); - memory_bm_position_reset(&orig_bm); - for (pfn = memory_bm_next_pfn(&orig_bm); pfn != BM_END_OF_MAP; - pfn = memory_bm_next_pfn(&orig_bm)) { - if (!pfn_valid(pfn)) - continue; - if (!arch_hibernate_clean_image_page(pfn)) { - skipped++; - continue; - } - if (!(++n & 0xffff)) - cond_resched(); - } - pr_debug("%lu image pages cleaned, %lu left to the restore_pblist copy\n", - n, skipped); + 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_restored_image(void) {} +static inline void swsusp_clean_loaded_page(void *addr) {} +static inline void swsusp_clean_report(void) {} #endif /** @@ -2856,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; @@ -2886,6 +2886,7 @@ int snapshot_write_next(struct snapshot_handle *handle) */ int snapshot_write_finalize(struct snapshot_handle *handle) { + bool loaded; int error; /* @@ -2899,12 +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) { - /* while orig_bm still lists the image: recycling overwrites it */ - swsusp_clean_restored_image(); + if (loaded) { + swsusp_clean_report(); memory_bm_recycle(&orig_bm); free_highmem_data(); } From 51027bf114c0376a602e619f4f6fea806ca2cc5e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Mon, 23 Nov 2026 20:42:33 +0100 Subject: [PATCH 044/140] arm64: hibernate: Call the boot loader by its role in a comment No functional change. Signed-off-by: fbalazsy (cherry picked from commit 526763a0fe5772a6daf204e9c1e19182b4fdb09e) --- arch/arm64/kernel/hibernate.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/kernel/hibernate.c b/arch/arm64/kernel/hibernate.c index 59ec0caf5b346..a90318ee0ab3c 100644 --- a/arch/arm64/kernel/hibernate.c +++ b/arch/arm64/kernel/hibernate.c @@ -118,7 +118,7 @@ u64 arm64_hibernate_layout_mix(u64 h, const void *p, size_t len) /* * Mix one memory span less the parts in @ex, ranges that this boot keeps out of - * the image. iBoot's no-map allocations inside aura's fixed layout (the DCP + * 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. */ From 445cd15bae5c5c18b90b4fe9eb6fcb4820a1bfb4 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 28 Nov 2026 09:45:40 +0100 Subject: [PATCH 045/140] selftests: asahi: Follow the hibernation changes in the host tests The host tests extract production code into single-threaded harnesses. The hibernation series added calls and fields those harnesses did not provide, so eight of them stopped compiling: - apple-dcp provider-admission, ordered-rx and stale-crtc-poweroff, and backlight-coldboot: dcp_hib_gated() and dcp_hib_tx_gated(). None of these controls resumes from disk, so both gates stay open. - iomfb-startup: the in-place firmware restart after a resume from disk hands the restored arena back. Model its fields and add a case that checks the arena is cleaned, cleared and reused, not allocated again. - bcm4377-resume: bcm4377_suspend() now wraps __bcm4377_suspend(), shared with the freeze callback. Extract the shared body too. - apple-dart-fw: the locked roots now record their physical address and page table configuration. - display26: the PMP bridge registers a PM notifier for the restore. Mock the notifier and check it is registered and dropped with the bridge. - pmu-rtc: hibernation has no suspend target (PM_SUSPEND_ON). Define it and check that the alarm does not refuse it. No driver change. Signed-off-by: fbalazsy (cherry picked from commit f43d634033dbabbb455ae5f0a220437c45c69cdb) --- tools/asahi/apple-dart-fw/fixture.c | 2 ++ tools/asahi/backlight-coldboot-tests.py | 1 + tools/asahi/bcm4377-resume-tests.py | 2 +- tools/asahi/display26-tests.py | 14 +++++++++++--- tools/asahi/iomfb-startup-tests.py | 16 +++++++++++++--- tools/asahi/pmu-rtc-tests.py | 4 ++++ .../selftests/drivers/gpu/apple-dcp/edid.py | 6 +++++- .../selftests/drivers/gpu/apple-dcp/lifecycle.py | 2 ++ 8 files changed, 39 insertions(+), 8 deletions(-) diff --git a/tools/asahi/apple-dart-fw/fixture.c b/tools/asahi/apple-dart-fw/fixture.c index 7ccecc109ffb3..df0327f757ede 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]; diff --git a/tools/asahi/backlight-coldboot-tests.py b/tools/asahi/backlight-coldboot-tests.py index ead647251b3cf..5284351d27144 100755 --- a/tools/asahi/backlight-coldboot-tests.py +++ b/tools/asahi/backlight-coldboot-tests.py @@ -98,6 +98,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; } diff --git a/tools/asahi/bcm4377-resume-tests.py b/tools/asahi/bcm4377-resume-tests.py index e415dc0a76350..bd221581f967c 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_suspend','bcm4377_resume'] +names=['bcm4377_setup_retry_allowed','bcm4377_queue_setup_retry','bcm4377_setup_retry_work','bcm4377_resume_recovery_supported','bcm4377_resume_recovery_allowed','bcm4377_resume_recovery_invalidate','bcm4377_resume_recovery_sync','bcm4377_resume_recovery_destroy','bcm4377_resume_recovery_work','bcm4377_hci_timeout','bcm4377_resume_recovery_stop','bcm4377_hci_open','bcm4377_hci_close','bcm4377_hci_setup_once','bcm4377_hci_setup','bcm4377_clamp_acl_mtu','bcm4377_hci_post_init','bcm4377_hci_unregister_dev','bcm4377_sleep_finish','__bcm4377_suspend','bcm4377_suspend','bcm4377_resume'] bodies={n:extract(s,n) for n in names};shared=[] if a.old_ref: old=subprocess.check_output(['git','show',a.old_ref+':drivers/bluetooth/hci_bcm4377.c'],cwd=r,text=True) diff --git a/tools/asahi/display26-tests.py b/tools/asahi/display26-tests.py index c030aaaf9bcc6..880e0e9b1121d 100644 --- a/tools/asahi/display26-tests.py +++ b/tools/asahi/display26-tests.py @@ -97,7 +97,14 @@ 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' + '#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 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' @@ -170,13 +177,14 @@ 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;} 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); 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); 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; link_fail=true;assert(apple_pmp_link_device(&consumer)==-EINVAL);assert(supplier.refs==0);link_fail=false; @@ -192,7 +200,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/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 b378c1c61b350..7157cf45eb324 100644 --- a/tools/asahi/pmu-rtc-tests.py +++ b/tools/asahi/pmu-rtc-tests.py @@ -58,6 +58,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 @@ -337,6 +338,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/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index d2ca8a50eb36a..693c62d491a4a 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -721,7 +721,9 @@ def function(file, signature): struct apple_dcp_afkep *sleep_v27_ep[0x20], *panelav[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; @@ -995,6 +997,8 @@ def function(text, signature): bool v27_j714s, v27_sleep_transport, sleep_v27_unhandled; struct apple_dcp_afkep *sleep_v27_ep[0x20], *panelav[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 b91d8a5812f72..10fa7701723f2 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -869,6 +869,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; } /* The T8140 display power cycle has its own test on hardware; here it only has to be reached. */ static void dcp_dpms_power_off(struct apple_dcp *d) { (void)d; } static bool __attribute__((unused)) dcp_has_panel(struct apple_dcp *d) { return !d->typec_output; } From 1df3f535a7f391179cf67ace4fd38e411b9c504f Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sun, 29 Nov 2026 01:01:01 +0100 Subject: [PATCH 046/140] soc: apple: aura-hibernate: Count unmapped memory as kept out of the image The image is refused unless the ranges kept out of it cover the whole fixed layout outside the image window. Most of that layout is no-map memory (the boot loader's carveouts and firmware ranges), which the kernel never maps and never saves, plus a few reserved islands that move from boot to boot. Requiring explicit nosave ranges for all of it failed the check, so the ranges that should have been excluded were not, and the moving islands went into the layout hash: the resuming boot then rejected an image written under the same boot layout. Treat memory the kernel does not map, and holes between memory regions, as kept out when checking coverage. Mapped memory outside the kept-out ranges still fails the check. Signed-off-by: fbalazsy (cherry picked from commit 98715692199be4765668188c7b4d89dc6010167d) --- drivers/soc/apple/aura-hibernate.c | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/aura-hibernate.c b/drivers/soc/apple/aura-hibernate.c index cc88dc2cff06e..2d872d0a4a394 100644 --- a/drivers/soc/apple/aura-hibernate.c +++ b/drivers/soc/apple/aura-hibernate.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -84,10 +85,15 @@ static bool aura_hibernate_pfn_nosave(unsigned long pfn) return false; } -/* Whether the ranges kept out of the image cover all of [start, end). */ +/* + * 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); + unsigned long pfn = PFN_DOWN(start), last = PFN_UP(end), next, s, e; + struct memblock_region *r; unsigned int i; bool moved; @@ -99,8 +105,23 @@ static bool aura_hibernate_range_nosave(u64 start, u64 end) moved = true; } } - if (!moved) - return false; + 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; } From ae48ee4950b6404daeb330a7a07cd6c412e519b8 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sun, 29 Nov 2026 01:01:01 +0100 Subject: [PATCH 047/140] Bluetooth: hci_bcm4377: Log the rebind after a hibernation restore as info A restore from hibernation always restarts the controller by rebinding the driver, since the firmware's rings are not the image's. That is the expected path, not an error: log it at info level, and keep the error level for a controller that stopped responding or a function reset. Also say why a reprobe was deferred. Signed-off-by: fbalazsy (cherry picked from commit eb5e3c337c2bfbad0e25e1ab0f18a19bc9e031b1) --- drivers/bluetooth/hci_bcm4377.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 9dc78d8d7a0f9..578481c9c255f 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -2850,7 +2850,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); @@ -2865,7 +2865,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; @@ -2887,7 +2887,11 @@ static void bcm4377_queue_rebind(struct bcm4377_data *bcm4377, 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); INIT_WORK(&rw->work, bcm4377_reset_work); queue_work(bcm4377_reset_wq, &rw->work); @@ -2900,7 +2904,7 @@ static void bcm4377_hci_reset(struct hci_dev *hdev) /* A timeout while still setting up would only loop probe failures. */ if (hci_dev_test_flag(hdev, HCI_SETUP)) return; - bcm4377_queue_rebind(bcm4377, "controller not responding"); + bcm4377_queue_rebind(bcm4377, "controller not responding", true); } /* @@ -2932,7 +2936,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 = { @@ -3326,7 +3330,7 @@ static int bcm4377_restore(struct device *dev) /* 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", true); + bcm4377_queue_rebind(bcm4377, "restored from hibernation", false); return 0; } From 494754def0c1771ee8dfb358db5ec8a4d0678046 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sun, 29 Nov 2026 01:01:01 +0100 Subject: [PATCH 048/140] PM: hibernate: Report the platform block after all late initcalls The report asks the platform whether it handles a restore, and the platform code that answers registers from a late initcall itself. Run the report from late_initcall_sync so it sees the final answer instead of logging hibernation as disabled on a platform that enables it. Signed-off-by: fbalazsy (cherry picked from commit b98cf42edad23f815cf5ec35f404cc1b41b58ded) --- kernel/power/hibernate.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 531792242e117..faaab5c6d1fea 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -267,7 +267,7 @@ static int __init hibernation_platform_report(void) "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. From 00a87c53ce933f7b1e056e3e8702379a364683fc Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sun, 29 Nov 2026 14:01:55 +0100 Subject: [PATCH 049/140] dt-bindings: chosen: document aurora,s2r-mailbox The boot object's suspend-to-RAM mailbox is handed to the kernel in /chosen/aurora,s2r-mailbox and is read on both the sleep and the resume-from-disk paths, but the property had no schema. Add one next to the other /chosen aurora properties, and list it in MAINTAINERS. Signed-off-by: fbalazsy --- .../bindings/chosen/aurora,s2r-mailbox.yaml | 40 +++++++++++++++++++ MAINTAINERS | 1 + 2 files changed, 41 insertions(+) create mode 100644 Documentation/devicetree/bindings/chosen/aurora,s2r-mailbox.yaml 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/MAINTAINERS b/MAINTAINERS index 091b180a28dee..db65f525414d3 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2096,6 +2096,7 @@ 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 From d30a10c1f7d2aae50a71b1bde690150fb86dc656 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 00:50:20 +0100 Subject: [PATCH 050/140] iommu/apple-dart: keep off a deferred display DART across a hibernation restore A DART whose consumer is a display block is taken down for hibernation by that consumer, and apple_dart_restore() defers its restore while the block is still unpowered: it sets restore_pending and leaves the registers alone until apple_dart_display_restore() runs at the consumer's power-up. On the restoring boot the loader has locked the DART again with roots of its own, which hold none of this kernel's tables, and the block may not answer yet. Honour that deferral in the paths that would otherwise reach the block while it is pending: the DCP domain flush and the TLB range flush publish to memory only (nothing walks the tables with the streams off), and a firmware-map check that needs the live roots returns -EBUSY. restore_pending is now read outside the restore callback, so access it with READ_ONCE()/WRITE_ONCE(). Signed-off-by: fbalazsy --- drivers/iommu/apple-dart-test.c | 54 +++++++++++++++++++++++++++++++++ drivers/iommu/apple-dart.c | 25 +++++++++++++-- 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index a0c23f34dcbb7..b8496999e1db7 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -481,6 +481,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 = {}; @@ -1817,6 +1870,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_fw_mirror_prot), KUNIT_CASE(apple_dart_test_display_keep), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), + KUNIT_CASE(apple_dart_test_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 d9546806306e1..a4ce0394a0277 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -2979,11 +2979,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; @@ -3049,6 +3065,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. @@ -3207,6 +3225,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; @@ -8469,7 +8490,7 @@ static int apple_dart_restore(struct device *dev) /* No register of a block its display consumer took down can be read before it is up. */ if (READ_ONCE(dart->display_unpowered)) { - dart->restore_pending = true; + WRITE_ONCE(dart->restore_pending, true); dev_dbg(dev, "hibernation restore deferred to its display's power-up\n"); return 0; } @@ -8511,7 +8532,7 @@ int apple_dart_display_restore(struct device *dev) #ifdef CONFIG_HIBERNATION if (!dart->restore_pending) return 0; - dart->restore_pending = false; + WRITE_ONCE(dart->restore_pending, false); ret = apple_dart_system_resume(dev); if (ret || !dart->locked) { if (ret) From bece695fefd00abb0ef360069a5cf6f76e32147d Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 00:50:20 +0100 Subject: [PATCH 051/140] drm/apple: defer a DCP's DART restore to its firmware restart across hibernation The DARTs behind a DCP (its own and its piodma child's) are driven by the restoring boot's loader with fresh firmware roots until this DCP starts its firmware again; their registers are not this kernel's to touch before that, and the platform firmware programs a display DART only at its display's power-up. Mark them unpowered at .freeze so apple_dart_restore() defers them, and run the deferred restore from dcp_hib_restore_work() just before the firmware's first DMA. A DCP whose display stays with the loader leaves them deferred. On .thaw -- the kernel that hibernated carrying on, its firmware never having stopped -- only clear the mark. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp.c | 41 +++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index dfd414042e199..8b5b16ee947bf 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -12555,6 +12555,43 @@ static void dcp_hib_ext_restore(struct apple_dcp *dcp) 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, @@ -12575,6 +12612,8 @@ static void dcp_hib_restore_work(struct work_struct *work) } 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"); @@ -12764,6 +12803,7 @@ static int dcp_platform_freeze(struct device *dev) apple_rtkit_flush_rx(dcp->rtk); dcp->hib_rx_held = true; } + dcp_hib_darts(dcp, true); return 0; } @@ -12785,6 +12825,7 @@ static int dcp_platform_thaw(struct device *dev) struct apple_dcp *dcp = dev_get_drvdata(dev); /* 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); From 012030799a5c04d2f4ff301c64e319b64cc8437f Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 00:50:20 +0100 Subject: [PATCH 052/140] pmdomain: apple: resync power domains on a hibernation restore At a restore genpd powers a domain on only when the image recorded it off. But the boot that loaded the image may itself have left a domain gated that the image has on: one whose devices that boot did not bind, gated at its restore-time quiesce. A register block in such a domain stalls the bus on the first access after the restore. Factor the resume_noirq resync into apple_pmgr_ps_resync() and add a restore_noirq that calls it in the power-on direction only. It never gates a domain and skips firmware-owned ones; domains are suppliers of their consumers, so it runs before any consumer's restore callback. The suspend-to-RAM path is unchanged: the pm_ops are now spelled out per event, with freeze/thaw/poweroff reusing the suspend/resume handlers and restore taking the new one. Signed-off-by: fbalazsy --- drivers/pmdomain/apple/pmgr-pwrstate-test.c | 42 ++++++++++++++++++ drivers/pmdomain/apple/pmgr-pwrstate.c | 48 ++++++++++++++++++--- 2 files changed, 84 insertions(+), 6 deletions(-) diff --git a/drivers/pmdomain/apple/pmgr-pwrstate-test.c b/drivers/pmdomain/apple/pmgr-pwrstate-test.c index e7449c1dbee8a..a6f3b35e9a792 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate-test.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate-test.c @@ -826,6 +826,47 @@ static void pmgr_ps_auto_enable_fail_test(struct kunit *test) KUNIT_EXPECT_EQ(test, r->auto_writes, 0U); } +/* + * 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); +} + static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_power_on_test), KUNIT_CASE(pmgr_ps_power_off_undo_test), @@ -853,6 +894,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), {} }; diff --git a/drivers/pmdomain/apple/pmgr-pwrstate.c b/drivers/pmdomain/apple/pmgr-pwrstate.c index 1b7295fbe243c..469646061b213 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate.c @@ -635,16 +635,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 @@ -663,7 +664,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, ®); @@ -671,6 +672,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. @@ -688,9 +692,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; } @@ -1551,7 +1582,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 = { From a59ddfa1bb421af68a92b0db103108bc210e4041 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 01:18:54 +0100 Subject: [PATCH 053/140] iommu/apple-dart: test: take the T8132 fw-mirror DART off the stack apple_dart_test_t8132_fw_mirror_selection() put a whole struct apple_dart on the stack. With its per-stream arrays (locked_ttbr, locked_owned, locked_fw and the rest, each [DART_MAX_STREAMS][DART_MAX_TTBR]) the object is tens of kilobytes, and zero-initialising it overflowed the KUnit test thread's stack and panicked the run under the 16K-page config, taking the rest of the suite with it. Allocate it with kunit_kzalloc() (freed with the test) instead; the test is otherwise unchanged. Fixes: ef48113b7930 ("iommu: apple-dart: give any fw_mirror DART's firmware segments their leaves' protection") Signed-off-by: fbalazsy --- drivers/iommu/apple-dart-test.c | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index b8496999e1db7..32601048d6140 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1660,20 +1660,23 @@ static u64 *apple_dart_test_reserved_table(struct kunit *test) */ static void apple_dart_test_t8132_fw_mirror_selection(struct kunit *test) { - struct apple_dart dart = { .locked = true }; + struct apple_dart *dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); - KUNIT_EXPECT_TRUE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->locked = true; + + KUNIT_EXPECT_TRUE(test, apple_dart_selects_fw_mirror(dart, NULL, true)); /* A locked T8132 DART no display processor names: the PMP's. */ - KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, false)); - - dart.locked = false; - KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); - dart.locked = true; - dart.fw_handoff = true; - KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); - dart.fw_handoff = false; - dart.preserve_display = true; - KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(dart, NULL, false)); + + dart->locked = false; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(dart, NULL, true)); + dart->locked = true; + dart->fw_handoff = true; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(dart, NULL, true)); + dart->fw_handoff = false; + dart->preserve_display = true; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(dart, NULL, true)); } /* From 81b16c9882b6ad8c64de5edf2c764dca6c609494 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 01:32:46 +0100 Subject: [PATCH 054/140] apple-sep/hibe: type the op0/op1 request words The hibe endpoint's two request opcodes and reply status are fixed by the protocol: prepare carries opcode 0 in the ty field, resume opcode 1, and a reply reports its status in the same field (0 = success). Add the request builders, the one-page-each-way buffer sizes, and a reply check, with KUnit covering the encoded words against those values. No writer is wired yet and nothing is sent. Signed-off-by: fbalazsy --- drivers/soc/apple/hibe.rs | 83 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/drivers/soc/apple/hibe.rs b/drivers/soc/apple/hibe.rs index b016143927954..275b75e45cb8b 100644 --- a/drivers/soc/apple/hibe.rs +++ b/drivers/soc/apple/hibe.rs @@ -49,6 +49,7 @@ static_assert!(PREPARE_REPLY_LEN <= 0x4000 && RESUME_AUTH_LEN <= 0x4000); /// What the service gives a hibernation writer before the image is committed. /// Kept by the writer until the resume, then cleared. #[allow(dead_code)] +#[allow(dead_code)] pub(crate) struct Prepared { pub(crate) wrapped_image_key: [u8; WRAPPED_KEY_LEN], pub(crate) boot_word: u32, @@ -75,6 +76,54 @@ 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. Recovered from the enclave's own hibernation client, not +/// guessed: 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. +#[allow(dead_code)] +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. +#[allow(dead_code)] +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. +#[allow(dead_code)] +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. +#[allow(dead_code)] +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) { @@ -171,4 +220,38 @@ mod tests { long[..PREPARE_REPLY_LEN].copy_from_slice(&r); 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, + // matching the enclave client's inline word (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)); + } } From b71a1bdd2c774d349228a4cf706afc6fad2dc97f Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 01:32:47 +0100 Subject: [PATCH 055/140] apple-sep/hibe: hold an OolPair for the hibernation endpoint Mirror the pnon endpoint's out-of-line buffer handling for EP 0x14: add a pinned ool_hibe Mutex>, allocate one enclave page each way in probe (sized from HIBE_LAYOUT on discovery, in hibe_attach), so a future prepare(op0)/resume(op1) can register and drive the buffers without re-sizing on the PM path. No send is wired yet; the op0/op1 request word and the SEP re-boot-on-resume recovery path follow in the next changes. Signed-off-by: fbalazsy --- drivers/soc/apple/hibe.rs | 7 +++++++ drivers/soc/apple/sep.rs | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/drivers/soc/apple/hibe.rs b/drivers/soc/apple/hibe.rs index 275b75e45cb8b..d64251fbadb0a 100644 --- a/drivers/soc/apple/hibe.rs +++ b/drivers/soc/apple/hibe.rs @@ -152,6 +152,13 @@ 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); } diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 9b076c62714cc..348de02257678 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -856,6 +856,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] @@ -1118,6 +1123,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(); @@ -1288,6 +1295,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), From 9fa5d554f509e3fcff35f0cf007734a48cd9d554 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 01:45:24 +0100 Subject: [PATCH 056/140] dt-bindings: soc: apple: document apple,sep-boot-timeout-ms Add an optional apple,sep-boot-timeout-ms property: the time the host waits for the enclave to finish (re-)booting its firmware is a property of the SoC and its signed firmware, not a constant in the driver. It bounds both the first boot and the re-boot after a hibernation resume; absent, the driver's built-in default is used. Signed-off-by: fbalazsy --- .../devicetree/bindings/soc/apple/apple,sep.yaml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,sep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,sep.yaml index 1a20d2ce27eb5..ec140c9008011 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: From bd56b8270b998453ed14f1270c2a461cec770918 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 01:45:24 +0100 Subject: [PATCH 057/140] apple-sep: hibernation sleep-type and a DT-described boot timeout Add the control-endpoint hibernation sleep-type (op_hibernate): it differs from a plain sleep only in the sleep-type field, telling the enclave 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. Add a reader for the apple,sep-boot-timeout-ms device-tree property; the time the host waits for the enclave to finish (re-)booting is read from it, falling back to a built-in default when the property is absent. KUnit covers the sleep-type encoding. Signed-off-by: fbalazsy --- drivers/soc/apple/dt.rs | 26 ++++++++++++++++++++++++++ drivers/soc/apple/proto.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/drivers/soc/apple/dt.rs b/drivers/soc/apple/dt.rs index 02f68e36ea0ec..2fc24b90b89a6 100644 --- a/drivers/soc/apple/dt.rs +++ b/drivers/soc/apple/dt.rs @@ -280,6 +280,32 @@ 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) } 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 { From 5958764485eaa30ed943f33f684605e9cc61b0b9 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 01:45:24 +0100 Subject: [PATCH 058/140] apple-sep/hibe: op0/op1 exchange and the prepare/resume requests Add the hibernation endpoint's request/reply exchange on EP 0x14, mirroring the single-exchange, work-queued pattern the boot-policy endpoint uses: a per-endpoint Exchange (reply word correlated by generation), register the one-page-each-way OOL buffers on first use, write the outbound payload, send the request word and wait for the reply word bounded by the device-tree boot timeout with a clean fallback, then read and zero the inbound reply. hibe_prepare() performs exchange A (wrapped image key + boot word + resume authorisation, 132-byte fixed layout) and hibe_resume() exchange B (hands the 64-byte authorisation back). Both clear buffers on the way out and never log the opaque blobs. No writer is wired yet; the production path drives prepare/resume only within the hibernation sequence added next. Signed-off-by: fbalazsy --- drivers/soc/apple/hibe.rs | 151 ++++++++++++++++++++++++++++++++++++-- drivers/soc/apple/sep.rs | 8 ++ 2 files changed, 152 insertions(+), 7 deletions(-) diff --git a/drivers/soc/apple/hibe.rs b/drivers/soc/apple/hibe.rs index d64251fbadb0a..ed08430bddd86 100644 --- a/drivers/soc/apple/hibe.rs +++ b/drivers/soc/apple/hibe.rs @@ -49,7 +49,6 @@ static_assert!(PREPARE_REPLY_LEN <= 0x4000 && RESUME_AUTH_LEN <= 0x4000); /// What the service gives a hibernation writer before the image is committed. /// Kept by the writer until the resume, then cleared. #[allow(dead_code)] -#[allow(dead_code)] pub(crate) struct Prepared { pub(crate) wrapped_image_key: [u8; WRAPPED_KEY_LEN], pub(crate) boot_word: u32, @@ -58,7 +57,6 @@ pub(crate) struct 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; @@ -95,7 +93,6 @@ static_assert!(PREPARE_REPLY_LEN <= HIBE_OOL_INBOUND && RESUME_AUTH_LEN <= HIBE_ /// 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. -#[allow(dead_code)] const fn hibe_request(op: u8) -> Message { Message { msg0: (EP_HIBE as u64) | ((op as u64) << MSG_TYPE_SHIFT), @@ -105,21 +102,18 @@ const fn hibe_request(op: u8) -> Message { /// Prepare (op0): asked before the image is committed; the reply fills the /// inbound buffer with one [`PREPARE_REPLY_LEN`] reply. Carries no payload. -#[allow(dead_code)] 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. -#[allow(dead_code)] 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. -#[allow(dead_code)] pub(crate) fn hibe_reply_ok(f: &Fields) -> bool { f.ep == EP_HIBE && f.ty == HIBE_STATUS_OK } @@ -162,8 +156,18 @@ impl SepData { 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, @@ -172,6 +176,139 @@ 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.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. + #[allow(dead_code)] + pub(crate) fn hibe_prepare(&self) -> Result<(u64, Prepared)> { + 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!(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!(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!(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)] diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 348de02257678..4035705afe337 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -868,6 +868,10 @@ struct SepData { pnon_named: Atomic, pnon_layout: Atomic, pnon_done: Atomic, + #[pin] + hibe_rx: Mutex, + #[pin] + hibe_wq: CondVar, // What discovery said about the endpoints the driver checks and sends // nothing to (see `sse`, `hibe`, `skdl`). @@ -1301,6 +1305,8 @@ impl SepData { pnon_named: Atomic::new(false), pnon_layout: Atomic::new(0), pnon_done: Atomic::new(false), + hibe_rx <- new_mutex!(hibe::Exchange::new()), + hibe_wq <- new_condvar!("SepData::hibe_wq"), sse_named: Atomic::new(false), sse_layout: Atomic::new(0), hibe_named: Atomic::new(false), @@ -3528,6 +3534,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(); } @@ -3566,6 +3573,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 { From 28862acdf66bc6b74db068314ac07ce72c4b4189 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 01:42:23 +0100 Subject: [PATCH 059/140] soc: apple-sep: re-boot the enclave across a hibernation resume A resume from a hibernation image comes up on a fresh boot: the boot loader has re-booted the enclave for the resuming kernel, so the enclave session captured in the saved image is gone. Its shared-memory handoff and firmware mapping describe a session the running enclave knows nothing about, and reusing them leaves the endpoint silent. Hook the hibernation lifecycle through the PM notifier so the driver can tell the two halves apart from an ordinary suspend: - Entering hibernation (PM_HIBERNATION_PREPARE) raises a flag so the control endpoint is told the hibernation sleep-type rather than the suspend sleep-type, and so a hibernation-image prepare on the hibe endpoint is permitted. The enclave powers its hibernation service up only once it has been told that sleep-type; a prepare asked outside that window is not serviced and wedges the endpoint, so hibe_prepare is gated to the window and refused with -EAGAIN outside it. - Leaving hibernation (PM_POST_HIBERNATION) clears the flag, and when the system resumed from an image (pm_hibernate_is_restored()) re-boots the enclave the way the first probe did: tear the stale handoff down, re-acquire the enclave node from this boot's device tree, hand the firmware and shared memory over again and let discovery run. The wait blocks on the enclave's readiness signal, bounded by the device-tree boot timeout; if the enclave does not come back the endpoint is marked unusable rather than left hung, and further registration is refused with -ENODEV. No addresses are hard-coded; the timeout comes from the binding added in the preceding change. Signed-off-by: fbalazsy --- drivers/soc/apple/hibe.rs | 12 +++++ drivers/soc/apple/pm.rs | 24 ++++++++- drivers/soc/apple/pm_shim.c | 27 ++++++++-- drivers/soc/apple/sep.rs | 104 +++++++++++++++++++++++++++++++++++- drivers/soc/apple/shim.h | 3 +- 5 files changed, 164 insertions(+), 6 deletions(-) diff --git a/drivers/soc/apple/hibe.rs b/drivers/soc/apple/hibe.rs index ed08430bddd86..b03c0881907b7 100644 --- a/drivers/soc/apple/hibe.rs +++ b/drivers/soc/apple/hibe.rs @@ -186,6 +186,9 @@ impl SepData { /// 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); } @@ -231,8 +234,17 @@ impl SepData { /// 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!(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)?; diff --git a/drivers/soc/apple/pm.rs b/drivers/soc/apple/pm.rs index d479bf866ae4c..765c61a44cf94 100644 --- a/drivers/soc/apple/pm.rs +++ b/drivers/soc/apple/pm.rs @@ -30,6 +30,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, @@ -278,6 +279,27 @@ 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_reboot_after_hibernation(sep.into()); + } + _ => sep.hibe_flow_leave(), + } +} + pub(crate) fn register(sep: Arc) -> Result<()> { let dev: *mut c_void = sep.dev.as_raw().cast(); let ptr = sep.into_foreign(); @@ -298,7 +320,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 221634f03a3db..be87b3b09e320 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -53,6 +53,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); @@ -67,15 +72,27 @@ 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: + event(false); + sep_diag_sleep(false); + if (hib) + hib(pm_hibernate_is_restored() ? 2 : 1); + return NOTIFY_OK; + case PM_POST_SUSPEND: case PM_POST_RESTORE: event(false); sep_diag_sleep(false); @@ -517,18 +534,21 @@ 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), +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); @@ -543,6 +563,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/sep.rs b/drivers/soc/apple/sep.rs index 4035705afe337..0fa99fc1cbda9 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -612,6 +612,11 @@ impl EndpointTable { } } + /// Forget every discovered endpoint, before the enclave is re-booted. + fn clear(&mut self) { + self.eps.clear(); + } + fn slot(&mut self, id: u8) -> Result { if let Some(i) = self.eps.iter().position(|e| e.id == id) { return Ok(i); @@ -872,6 +877,13 @@ struct SepData { 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`). @@ -1307,6 +1319,8 @@ impl SepData { pnon_done: Atomic::new(false), 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), @@ -1561,6 +1575,87 @@ impl SepData { } } + /// The system has just resumed from a hibernation image. On these + /// machines the boot loader re-boots the enclave for the resuming boot, + /// so the saved image's enclave session is dead: its shared-memory + /// handoff and firmware mapping mean nothing to the running enclave. + /// Re-boot it as the first probe did: tear the stale handoff down, hand + /// the firmware and shared memory over again and let discovery run, + /// bounded by the device tree boot timeout, leaving the enclave unused + /// rather than hung if it does not come back. This mirrors the enclave + /// manager re-booting the coprocessor on a resume. + pub(crate) fn resume_reboot_after_hibernation(this: Arc) { + if this.shutting_down.load(Relaxed) { + return; + } + dev_info!(this.dev, "hibe: re-booting the enclave after a hibernation resume\n"); + // The running enclave owns none of the saved handoff. + this.registered.store(false, Relaxed); + this.release_firmware_mapping(); + this.endpoints.lock().clear(); + this.phase.store(PHASE_ATTACH, Relaxed); + this.sep_unusable.store(false, Relaxed); + // This boot's device tree is the one handed to the resume, so its + // one-shot registration marker is clear and the handoff can repeat. + let Some(sep_node) = dt::sep_node() else { + this.sep_unusable.store(true, Relaxed); + dev_err!(this.dev, "hibe: resume re-boot abandoned: the enclave node is gone\n"); + return; + }; + if let Err(e) = this.attach(&sep_node) { + this.sep_unusable.store(true, Relaxed); + dev_err!( + this.dev, + "hibe: resume re-boot could not hand over firmware and memory ({:?})\n", + e + ); + return; + } + if this.registered.load(Relaxed) { + Self::arm_settle(&this); + } + // Wait, bounded, for discovery to finish, as the first boot does, + // blocking on the readiness the enclave signals rather than polling. + let timeout_ms = dt::boot_timeout_ms(&sep_node); + let mut remaining = time::msecs_to_jiffies(timeout_ms); + let mut guard = this.endpoints.lock(); + while this.phase.load(Relaxed) != PHASE_READY { + if this.shutting_down.load(Relaxed) { + return; + } + if remaining == 0 { + drop(guard); + this.sep_unusable.store(true, Relaxed); + dev_err!( + this.dev, + "hibe: the enclave did not finish re-booting within {} ms; left unused\n", + timeout_ms + ); + return; + } + match this.trusted_ready.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => remaining = jiffies, + CondVarTimeoutResult::Signal { .. } => remaining = 0, + CondVarTimeoutResult::Timeout => remaining = 0, + } + } + drop(guard); + dev_info!(this.dev, "hibe: the enclave re-booted and is ready again\n"); + // A hibernation writer would now hand the enclave back the resume + // authorisation from prepare (op1). Linux writes no image yet, so + // there is none to return; that call belongs here. + } + + /// 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); @@ -1751,7 +1846,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); diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 992f51bd19e09..ab32446bb4ad2 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); From 8be180d931c92291a06cec2f114c2015b14679b2 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 02:02:08 +0100 Subject: [PATCH 060/140] drm/asahi: contain the GPU across a hibernation restore A resume from a hibernation image comes up on a fresh warm boot: the boot loader has reset the GPU coprocessor, so the firmware state the image describes is gone. Letting a backend's runtime touch that dead firmware -- a mailbox poke, a warm restart, a page-table teardown -- risks hanging the resume path. Add a generation-agnostic HibRestoreContain trait in the common GPU layer with a no-op default, dispatched from a new PM-core .restore_noirq callback over every present backend. The restore callback runs only on a hibernation resume (a suspend resume and a hibernating kernel's own thaw never reach it), so it needs no gating on the sleep kind. A generation opts in by overriding the hook to mark its device lost; one that does not keeps its current behaviour through the default. g17 opts in, marking the device lost before its runtime touches the stale firmware, so a failed GPU restore leaves the GPU unusable until reboot while the system stays alive. g16 and g14 (27.2) keep their current behaviour via the no-op default and are built unchanged. Built for all GPU generations (g16, g17, g14_v27_2, g15) as a cross-generation regression; g17 hardware was used to prove the restore path at runtime. Signed-off-by: fbalazsy --- drivers/gpu/drm/asahi/driver.rs | 23 +++++++++++++++++++++++ drivers/gpu/drm/asahi/g14_v27_2.rs | 4 ++++ drivers/gpu/drm/asahi/g16/sleep.rs | 4 ++++ drivers/gpu/drm/asahi/g17/sleep.rs | 14 ++++++++++++++ drivers/gpu/drm/asahi/gpu.rs | 17 +++++++++++++++++ 5 files changed, 62 insertions(+) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 4ca274e2be406..5b692ea51f190 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; @@ -330,11 +331,33 @@ 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. + let data = unsafe { sleep_data(dev) }; + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + if let Some(backend) = data.g14_v27_2.as_ref() { + backend.hib_restore_contain(); + } + if let Some(gpu) = data.g16.as_ref() { + gpu.hib_restore_contain(); + } + if let Some(gpu) = data.g17.as_ref() { + gpu.hib_restore_contain(); + } + 0 +} + static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_prepare), complete: Some(sleep_complete), suspend_noirq: Some(sleep_suspend_noirq), resume_noirq: Some(sleep_resume_noirq), + restore_noirq: Some(sleep_restore_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 6961bbc9471f6..ca28dd16cd0ff 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -2013,6 +2013,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 b51556822b075..24bd8d0b87de8 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -320,6 +320,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/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index 17a21a88223a3..ec031bfa03f3b 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -645,6 +645,20 @@ impl super::Gpu { } } +impl crate::gpu::HibRestoreContain for super::Gpu { + /// Mark the device lost before the runtime touches the firmware the + /// resuming kernel's image describes. This is a fresh warm boot and 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) { + self.shared.lose_device_quietly(); + } +} + #[kernel::macros::kunit_tests(asahi_g17_sleep)] mod tests { use super::*; diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index e91fc1bfef3dd..d9401f447961e 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -608,6 +608,23 @@ 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. +pub(crate) trait HibRestoreContain { + fn hib_restore_contain(&self) {} +} + /// Private generic trait for functions that don't need to escape this module. trait GpuManagerPriv { /// Decrement the pending submission counter. From 8df0d1394097fb2618b9350149f183bd3c6363b1 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 10:49:38 +0100 Subject: [PATCH 061/140] pmdomain: core: Run the thaw and restore noirq callbacks of genpd devices genpd_finish_resume() is handed the callback of the phase it completes, but calls it only for a device on an active wakeup path. Every other device gets pm_generic_resume_noirq(), whatever the phase. A driver's .thaw_noirq and .restore_noirq then never run for a device in a generic PM domain, and a device whose hibernation image was just restored is resumed as from a system suspend instead. Call the callback that was passed in, as the wakeup path already does. Fixes: d9cc34fe0aae ("PM: domains: Consolidate genpd_restore_noirq() and genpd_resume_noirq()") Signed-off-by: fbalazsy --- drivers/pmdomain/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/pmdomain/core.c b/drivers/pmdomain/core.c index a721a936357d0..e4465b190d3c3 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); } /** From db09d8139001fd949a05436413b3b560895487aa Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 10:49:40 +0100 Subject: [PATCH 062/140] spmi: apple: Restore the interrupt enables after a hibernation restore A restored hibernation image finds the controller as the kernel that loaded the image left it. Its mask bank holds that kernel's enables, not the ones in this kernel's cache, and that kernel may have left replies in the queue. The resume path rewrites the mask bank and drains the queue only after a firmware-driven sleep, so after a restore a peripheral's interrupt can stay masked: a USB-C port controller then completes its register selections, but its driver never hears of it and times out. Add a restore_noirq callback that drops the stale replies, writes the mask bank back from the cache and, where the controller signals its replies by interrupt, re-arms that vector. Signed-off-by: fbalazsy --- drivers/spmi/spmi-apple-controller.c | 45 ++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index 1182e2e2daae3..6b5be3092546e 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -713,8 +713,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) { From df7c969af3c2cbad1162c5fa7a32675f2bad3b7d Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 10:49:40 +0100 Subject: [PATCH 063/140] usb: dwc3: apple: Stop the host across a hibernation A hibernation image is restored after a reboot. The kernel that loads the image has reset the controller and its PHYs, and may have set them up for itself, so the core the image describes is gone: xHCI's restore then fails to halt the controller ("Host halt failed, -110") and the port's USB devices are lost until the cable is replugged. Treat a hibernation like a deep sleep in which the host cannot be kept: from PM_HIBERNATION_PREPARE stop the host the way a cable disconnect does, and from PM_POST_HIBERNATION start it again from scratch, as the existing sleep epoch does for PM_SUSPEND_PREPARE and PM_POST_SUSPEND. The image is then written with no host on the port, and the restored system enumerates the port's devices afresh. A hibernation that fails before the image is written starts the host again the same way. Signed-off-by: fbalazsy --- drivers/usb/dwc3/dwc3-apple.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index 1d19945b1af9d..3d953192c739e 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -264,6 +264,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; @@ -2055,6 +2057,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) return 0; in_place = appledwc->fixed_hub && appledwc->state == DWC3_APPLE_HOST; @@ -2159,7 +2166,7 @@ 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_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) { @@ -2180,7 +2187,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); @@ -2198,6 +2206,13 @@ 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; /* Every admitted epoch must reach device prepare, including a retained host. */ dev_pm_syscore_device(appledwc->dev, false); reinit_completion(&appledwc->sleep_stop_done); From f0d3a89716e3fc375db96a780d59ee24183cf91b Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 11:44:35 +0100 Subject: [PATCH 064/140] pinctrl: apple: Put the pins back after a hibernation restore A restored hibernation image finds the pins as the boot firmware and the kernel that loaded the image left them. The pin setup is put back only after a firmware-driven suspend, so after a restore an output this kernel drives can sit at another level: the shared shutdown line of the speaker amplifiers stays low, and every amplifier NACKs its first I2C access after the restore. Add freeze, thaw and restore noirq callbacks. Without a register cache the configured pins are saved when the image is made and written back at restore, as for a firmware-driven suspend; a thaw drops the saved copy. With the cache, restore marks it dirty and syncs it, so every pin this kernel changed from the state it found at probe is written again. Signed-off-by: fbalazsy --- drivers/pinctrl/pinctrl-apple-gpio.c | 83 +++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/drivers/pinctrl/pinctrl-apple-gpio.c b/drivers/pinctrl/pinctrl-apple-gpio.c index 7089aac3bbe2e..33c124b5e3362 100644 --- a/drivers/pinctrl/pinctrl-apple-gpio.c +++ b/drivers/pinctrl/pinctrl-apple-gpio.c @@ -695,15 +695,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. @@ -712,18 +707,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; @@ -733,13 +722,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 = { From d19f2732a784f6c67ac11ae8907f8d1bd32a943c Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 11:44:35 +0100 Subject: [PATCH 065/140] irqchip/apple-aic: Keep the interrupt setup across a hibernation A restored hibernation image finds the controller as the kernel that loaded the image left it: a line that kernel had no driver for stays masked, and its IRQ configuration is that kernel's. The masks and the configuration are saved and written back only around a firmware-driven suspend, so after a restore the co-processor mailboxes whose drivers the loading kernel lacked never interrupt again: their RTKit restarts time out in endpoint discovery (-ETIME), and the DCPs and the PMP stay down. Track a hibernation from PM_HIBERNATION_PREPARE to PM_POST_HIBERNATION and take the existing syscore path for it too: the state is saved when the image is made and the masks are rebuilt from the IRQ core's books when it resumes, after a restore and after the image is written alike. Signed-off-by: fbalazsy --- drivers/irqchip/irq-apple-aic.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index a13eb5c1fcb2c..71b4af12a9cf1 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -1259,6 +1259,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; @@ -1266,6 +1271,7 @@ static struct { u32 cluster_prio; u32 *irq_cfg; bool saved; + bool hibernation; } aic_sleep; static int aic_syscore_suspend(void *data) @@ -1273,7 +1279,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); @@ -1353,6 +1359,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, @@ -1373,6 +1392,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) From be53318b76880fb486a20bf52429ec47b3043dbd Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 11:44:35 +0100 Subject: [PATCH 066/140] iommu: apple-dart: Re-import every locked root after a hibernation restore After a restore through a boot, the boot loader has locked the display DARTs again with fresh roots. A root found at the address the image describes was kept as described, on the assumption that the kernel that wrote the image had loaded it. The boot loader places its roots the same way on every boot, though, and fills them afresh without the slots the image published: every publication into such a root then fails (-EBUSY), and with it every DMA mapping through the DART, so the DCPs fail their RTKit buffer requests (-ENOMEM) and the displays stay down. Re-read and re-import a root whatever its address. Signed-off-by: fbalazsy --- drivers/iommu/apple-dart.c | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index a4ce0394a0277..59a80c7e0deda 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -8377,10 +8377,10 @@ static __maybe_unused int apple_dart_sys_resume_noirq(struct device *dev) * 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 that did not move (the kernel that wrote the image loaded - * it) is still the one the image describes and is kept. Firmware-owned - * memory is never written: the old roots' published slots are forgotten, not - * retired. + * 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) { @@ -8423,9 +8423,6 @@ static int apple_dart_reimport_locked(struct apple_dart *dart) ret = ret ?: -EINVAL; continue; } - /* Not replaced (the loading kernel wrote the image): as described. */ - if (phys == dart->locked_phys[sid][idx]) - continue; l1 = devm_memremap(dart->dev, phys, dart->pgsize, MEMREMAP_WB); if (IS_ERR(l1)) { ret = ret ?: PTR_ERR(l1); From 3570cba8850eccbb3fec0881202605fe064b2f29 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 12:22:27 +0100 Subject: [PATCH 067/140] drm/apple: dcp: Bring the T6040 external outputs back after a hibernation On T6040 the sleep's stop at .freeze takes the external links down: the fixed HDMI output's DP PHY and its converter rail are powered off, and each external output is held as relinking until the link work after the wake brings it back. A hibernation restore does not run that link work. Its relink powered the converter GPIOs alone, so the PHY stayed off, and nothing ever released the relinking state, so every later power-on of the output was skipped: the HDMI output saw its sink only late, came up without a display, and its link reported faults; the Type-C output's pipe stayed disabled. When the output is relinking, power the PHY and the converter before asking whether a display is attached, so that the HDMI sink is waited for like a Type-C one, and finish as the link work after a sleep does: release the output once the firmware reports the display plugged, or after the same timeout, or at once with no display attached. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp.c | 59 ++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 8b5b16ee947bf..f92f816d715c2 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -12470,9 +12470,52 @@ static bool dcp_hib_ext_has_display(struct apple_dcp *dcp) * above. The HPD interrupt that dcp_enable_dp2hdmi_hpd() enables was * disabled at freeze, or at restore. */ +/* + * 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 + +static void dcp_t6040_fixed_phy_up(struct apple_dcp *dcp); +static bool dcp_t6040_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_t6040_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_t6040_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->t6040_relinking)) { + if (dcp->t6040_fixed_phy_off) + dcp_t6040_fixed_phy_up(dcp); + plug = dcp_is_typec_output(dcp) && READ_ONCE(dcp->typec_cable_connected); + if (!plug && dcp_t6040_fixed_hdmi(dcp) && !READ_ONCE(dcp->hdmi_yielded) && + gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0) + plug = true; + WRITE_ONCE(dcp->t6040_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->t6040_plug_wq, + msecs_to_jiffies(DCP_S2R_PLUG_MS)); + else + WRITE_ONCE(dcp->t6040_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: @@ -12510,7 +12553,15 @@ static void dcp_hib_ext_relink(struct apple_dcp *dcp) */ static void dcp_hib_ext_link_up(struct apple_dcp *dcp, const char *when) { - bool display = dcp_hib_ext_has_display(dcp); + 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->t6040_relinking) && dcp->t6040_fixed_phy_off) + dcp_t6040_fixed_phy_up(dcp); + display = dcp_hib_ext_has_display(dcp); dcp_hib_ext_put(dcp, true, display); if (display && @@ -13205,12 +13256,6 @@ static int dcp_t6041_recommit(struct apple_dcp *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 /* * T6040 (apple,t6040-display-power): its sleep takes the external links down and back, its From a9e2f463a4c511cdc4934518e2b02352fcbd6c02 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 12:54:20 +0100 Subject: [PATCH 068/140] soc: apple-sep: Start the diag attach and ready times again at each bind The attach and bring-up times are taken once, when still unset, and reported against the time of the probe. A second bind keeps the first bind's times, which then fall before its probe and read as 0 ms, and it keeps the first bind's key store state, which reads as open before this bind's bring-up has ended. Clear them when the diag group registers, as the failure counts already are. Signed-off-by: fbalazsy --- drivers/soc/apple/diag_shim.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/soc/apple/diag_shim.c b/drivers/soc/apple/diag_shim.c index 0fe57d0f4e33b..3b17d2d00c34c 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -837,6 +837,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) From f4c13031cd71190366d6e3a44069c60fe2e61464 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 12:54:21 +0100 Subject: [PATCH 069/140] soc: apple-sep: Bind the driver again after a hibernation restore The boot that restores a hibernation image starts the enclave again, and it waits for a new shared-memory registration. The restored driver instance instead holds the session of the enclave that wrote the image: its registration marker, which came back with the image's device tree, so the re-registration was refused (-EBUSY); its out-of-line buffer registrations and bring-up state, so even an accepted registration left the key store closed and the control endpoint without answers; and the entropy requests held over the sleep, which went out as soon as the notifier released them, before the enclave had been registered. On PM_POST_HIBERNATION after a restore, before the held requests are released, refuse every request of the old instance and wake its waiters, drop the stale registration marker, and bind the driver again on a thread of its own, so that the enclave is attached and brought up as at boot. Neither the notifier nor the rest of the restore waits for the new bind. The buffers the old enclave held are freed at the unbind, since no enclave holds them any more. Signed-off-by: fbalazsy --- drivers/soc/apple/dt.rs | 18 ++++++ drivers/soc/apple/pm.rs | 12 +++- drivers/soc/apple/pm_shim.c | 45 +++++++++++++- drivers/soc/apple/sep.rs | 114 +++++++++++++++++------------------- drivers/soc/apple/shim.h | 1 + 5 files changed, 126 insertions(+), 64 deletions(-) diff --git a/drivers/soc/apple/dt.rs b/drivers/soc/apple/dt.rs index 2fc24b90b89a6..fd40ce0ea4f3a 100644 --- a/drivers/soc/apple/dt.rs +++ b/drivers/soc/apple/dt.rs @@ -310,6 +310,24 @@ 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/pm.rs b/drivers/soc/apple/pm.rs index 765c61a44cf94..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; @@ -51,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; } @@ -294,12 +296,20 @@ unsafe extern "C" fn pm_hibernation(phase: c_int) { 0 => sep.hibe_flow_enter(), 2 => { sep.hibe_flow_leave(); - SepData::resume_reboot_after_hibernation(sep.into()); + 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(); diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index be87b3b09e320..c34f833cda94c 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 @@ -87,10 +89,16 @@ static int sep_pm_notify(struct notifier_block *nb, unsigned long action, event(true); return NOTIFY_OK; case PM_POST_HIBERNATION: + /* + * After a restored image 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. + */ + if (hib && pm_hibernate_is_restored()) + hib(2); event(false); sep_diag_sleep(false); - if (hib) - hib(pm_hibernate_is_restored() ? 2 : 1); + if (hib && !pm_hibernate_is_restored()) + hib(1); return NOTIFY_OK; case PM_POST_SUSPEND: case PM_POST_RESTORE: @@ -534,6 +542,39 @@ const struct dev_pm_ops sep_pm_ops = { .suspend_noirq = pm_sleep_ptr(sep_pm_suspend_noirq), }; +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)) diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 0fa99fc1cbda9..2afa27c1ff7ae 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -612,11 +612,6 @@ impl EndpointTable { } } - /// Forget every discovered endpoint, before the enclave is re-booted. - fn clear(&mut self) { - self.eps.clear(); - } - fn slot(&mut self, id: u8) -> Result { if let Some(i) = self.eps.iter().position(|e| e.id == id) { return Ok(i); @@ -1575,75 +1570,72 @@ impl SepData { } } - /// The system has just resumed from a hibernation image. On these - /// machines the boot loader re-boots the enclave for the resuming boot, - /// so the saved image's enclave session is dead: its shared-memory - /// handoff and firmware mapping mean nothing to the running enclave. - /// Re-boot it as the first probe did: tear the stale handoff down, hand - /// the firmware and shared memory over again and let discovery run, - /// bounded by the device tree boot timeout, leaving the enclave unused - /// rather than hung if it does not come back. This mirrors the enclave - /// manager re-booting the coprocessor on a resume. - pub(crate) fn resume_reboot_after_hibernation(this: Arc) { - if this.shutting_down.load(Relaxed) { + /// 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; } - dev_info!(this.dev, "hibe: re-booting the enclave after a hibernation resume\n"); - // The running enclave owns none of the saved handoff. + // The gone enclave held these; the unbind frees them instead of + // keeping them for it. this.registered.store(false, Relaxed); - this.release_firmware_mapping(); - this.endpoints.lock().clear(); - this.phase.store(PHASE_ATTACH, Relaxed); - this.sep_unusable.store(false, Relaxed); - // This boot's device tree is the one handed to the resume, so its - // one-shot registration marker is clear and the handoff can repeat. + 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 { - this.sep_unusable.store(true, Relaxed); - dev_err!(this.dev, "hibe: resume re-boot abandoned: the enclave node is gone\n"); + dev_err!( + this.dev, + "hibernation: the enclave node is gone; the enclave stays unused\n" + ); return; }; - if let Err(e) = this.attach(&sep_node) { - this.sep_unusable.store(true, Relaxed); + if let Err(e) = dt::clear_registration_sent(&sep_node) { dev_err!( this.dev, - "hibe: resume re-boot could not hand over firmware and memory ({:?})\n", + "hibernation: the registration marker stays ({:?}); the enclave stays unused\n", e ); return; } - if this.registered.load(Relaxed) { - Self::arm_settle(&this); - } - // Wait, bounded, for discovery to finish, as the first boot does, - // blocking on the readiness the enclave signals rather than polling. - let timeout_ms = dt::boot_timeout_ms(&sep_node); - let mut remaining = time::msecs_to_jiffies(timeout_ms); - let mut guard = this.endpoints.lock(); - while this.phase.load(Relaxed) != PHASE_READY { - if this.shutting_down.load(Relaxed) { - return; - } - if remaining == 0 { - drop(guard); - this.sep_unusable.store(true, Relaxed); - dev_err!( - this.dev, - "hibe: the enclave did not finish re-booting within {} ms; left unused\n", - timeout_ms - ); - return; - } - match this.trusted_ready.wait_timeout(&mut guard, remaining) { - CondVarTimeoutResult::Woken { jiffies } => remaining = jiffies, - CondVarTimeoutResult::Signal { .. } => remaining = 0, - CondVarTimeoutResult::Timeout => remaining = 0, - } + if let Err(e) = pm::rebind(&this.dev) { + dev_err!( + this.dev, + "hibernation: the driver could not be bound again ({:?}); the enclave stays unused\n", + e + ); + return; } - drop(guard); - dev_info!(this.dev, "hibe: the enclave re-booted and is ready again\n"); - // A hibernation writer would now hand the enclave back the resume - // authorisation from prepare (op1). Linux writes no image yet, so - // there is none to return; that call belongs here. + dev_info!( + this.dev, + "hibernation: the enclave was started again; binding the driver again\n" + ); } /// The system is entering hibernation (PM_HIBERNATION_PREPARE). diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index ab32446bb4ad2..0f9b7e24401dc 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -38,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 ------------------------------------------------------- */ From c19904ea9cc213a0356c7e3efda5e77b6c4becd5 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 17:12:24 +0100 Subject: [PATCH 070/140] nvme: apple: Disable the T6040 controller at a panic When a T6040 is reset while its NVMe controller is still enabled, the next boot stage cannot start ANS again: it answers neither a warm nor a cold start (no HELLO, CPU status 0x40) until the machine is power cycled. A clean shutdown never gets there, because it sends the shutdown notification and disables the controller before the reset, leaving ANS running. A panic reboot, or a watchdog reset after a panic that waits for it, resets with the controller enabled. On these controllers, register a panic notifier that does what the shutdown does: send the shutdown notification, wait for it to complete, clear CC.EN and wait for RDY to drop. Everything is polled with a bound, since the other CPUs are stopped and nothing may sleep. It runs last among the panic notifiers, so the others can still write through the controller. Signed-off-by: fbalazsy --- drivers/nvme/host/apple.c | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 560e5876e44b8..45e6ded67b4d2 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 @@ -256,6 +257,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; }; @@ -308,6 +311,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; @@ -3326,6 +3331,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; @@ -3372,6 +3410,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; @@ -3387,6 +3431,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)) { @@ -4067,6 +4113,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, }; From 2d63a0c346f3624ed356a7147ebab5f5ced4f8a5 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 17:07:33 +0100 Subject: [PATCH 071/140] soc: apple: sleep: Find the T6040 power controllers for an engine reset apple_sleep_engine_reset() resets a coprocessor through the power controllers its node lists, and takes only those in the PMGR block the sleep node maps as "ps". The T6040 sleep maps its registers itself and names that block "soc-east", so no controller was found and every engine reset failed with -ENODEV: after a hibernation restore SIO could not be reset and its firmware kept running with the loading kernel's buffers. Keep the resource of the block a SoC's own register mapping uses for its power words, and look the controllers up in it as well. Only the engine reset uses it: apple_sleep_domain_set() and its record of the domains a driver took down still apply to "ps" alone. Signed-off-by: fbalazsy --- drivers/soc/apple/sleep-t6040.h | 4 ++++ drivers/soc/apple/sleep.c | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/drivers/soc/apple/sleep-t6040.h b/drivers/soc/apple/sleep-t6040.h index cd80a1be3cd59..5682a3df32a3d 100644 --- a/drivers/soc/apple/sleep-t6040.h +++ b/drivers/soc/apple/sleep-t6040.h @@ -2159,6 +2159,10 @@ static int t6040_sleep_map_regs(struct apple_sleep *c) s->mbox = c->mbox; c->ps = s->soc_east; + /* The PMGR block whose power controllers the engine reset looks up. */ + widx = of_property_match_string(dev->of_node, "reg-names", "soc-east"); + if (widx < 0 || of_address_to_resource(dev->of_node, widx, &c->ps_window)) + memset(&c->ps_window, 0, sizeof(c->ps_window)); c->wdt = s->wdt; c->cpu_start = s->cpu_start; c->commit = s->mastermini + MASTERMINI_S2R_TIMER; diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 259b853724875..3e44d3f9eb6ef 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -887,6 +887,12 @@ struct apple_sleep { bool usb_down_ran; /* The PMGR block "ps" maps, for the power controllers' nodes. */ struct resource ps_res; + /* + * The same block where a SoC's own map_regs maps it under another name: only the + * engine reset looks its power controllers up there, apple_sleep_domain_set() and its + * driver-down words keep to ps_res. + */ + struct resource ps_window; /* Its words a driver took down with apple_sleep_domain_set() and hasn't raised. */ unsigned long *driver_down; void __iomem *clk_mux; @@ -3144,6 +3150,11 @@ static bool sleep_ps_domain(struct apple_sleep *s, struct device_node *pd, u32 * ours = idx >= 0 && parent && !of_address_to_resource(s->dev->of_node, idx, &ps) && !of_address_to_resource(parent, 0, &res) && res.start == ps.start && !of_property_read_u32(pd, "reg", offset); + if (!ours && parent && resource_size(&s->ps_window)) + ours = !of_address_to_resource(parent, 0, &res) && + res.start == s->ps_window.start && + !of_property_read_u32(pd, "reg", offset) && !(*offset % 4) && + *offset + 4 <= resource_size(&s->ps_window); of_node_put(parent); return ours; From cce49c0b88452aa05ded8ac4fa49ea0e10ca0d45 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 17:07:34 +0100 Subject: [PATCH 072/140] dmaengine: apple-sio: Stop and boot the firmware across a hibernation The boot that loads a hibernation image starts SIO and hands its firmware the buffers and parameters of that boot. The restored kernel then sent requests against its own buffers to a firmware that had never been given them, and every transfer (audio, SPI) timed out. Stop the firmware at .freeze and .poweroff so nothing it writes lands after the snapshot, and refuse the hibernation if a channel is busy or the stop fails. After the usual resume, .thaw and .restore reset the engine and boot the firmware again as probe does, then hand it this kernel's device tree parameters and shared memory. The channels are idle at that point, since user space is frozen. A failed restart is reported and leaves the rest of the restore going. Signed-off-by: fbalazsy --- drivers/dma/apple-sio.c | 128 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 127 insertions(+), 1 deletion(-) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index b6f5286904459..5f8ed38bba59c 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -181,6 +181,8 @@ struct sio_hw_data { }; struct sio_data { + /* Stopped for a hibernation image: booted again at thaw or restore. */ + bool hib_stopped; const struct sio_hw_data *hw; void __iomem *base; struct dma_device dma; @@ -2389,8 +2391,132 @@ static __maybe_unused int sio_resume_early(struct device *dev) return 0; } +/* + * After a hibernation restore the firmware runs as the boot that loaded the image started it, + * with that kernel's buffers and parameters. Reset the engine and boot the firmware again 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_sleep_engine_reset(sio->dev); + if (err) { + dev_err(sio->dev, "engine reset after the hibernation: %d\n", err); + return 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: the firmware stops before the image is taken, so that nothing it writes lands + * after the snapshot, and again before the power goes off. A busy channel or a refused stop + * refuses the hibernation, the firmware still running. + */ +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 || sio->hib_stopped) + 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; + } + } + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + ret = apple_rtkit_sleep_stop(sio->rtk, sio->base + REG_CPU_CONTROL); + pm_runtime_put_noidle(dev); + if (ret) { + dev_err(dev, "firmware did not stop for the hibernation: %d\n", ret); + return ret; + } + sio->hib_stopped = true; + + return sio_system_suspend(dev); +} + +/* After the image is written, a failed hibernation or a restore: the firmware boots again. */ +static __maybe_unused int sio_hib_start(struct device *dev, bool restore) +{ + struct sio_data *sio = dev_get_drvdata(dev); + int ret; + + ret = sio_system_resume(dev); + if (ret) + return ret; + if (!sio->hib_stopped && !restore) + return 0; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + ret = sio_restart_after_restore(sio); + pm_runtime_put(dev); + if (ret) { + dev_err(dev, "firmware not booted again after the hibernation: %d\n", ret); + return 0; + } + sio->hib_stopped = false; + dev_info(dev, "firmware booted again after the hibernation%s\n", + restore ? " restore" : ""); + + return 0; +} + +static __maybe_unused int sio_hib_thaw(struct device *dev) +{ + return sio_hib_start(dev, false); +} + +static __maybe_unused int sio_restore(struct device *dev) +{ + return sio_hib_start(dev, true); +} + static const struct dev_pm_ops sio_pm_ops = { - 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_hib_thaw), + .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) }; From 4b3bf67480b280dd1e49c7df601f5adc1708db58 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 19:50:35 +0100 Subject: [PATCH 073/140] watchdog: apple: Drain a WD2 disarm before re-programming CUR_TIME On T6040, WD2 ignores a CUR_TIME write while IRQ_EN is set, and a posted disarm is not enough for the next write to be accepted. A hibernation restore, and a ping of an already-running watchdog, then left the counter running from probe, so a timeout armed at start expired at the original boot time rather than after the restore. Drop IRQ_EN and read the control register back before writing CUR_TIME in the arm and ping paths, then restore the enable. The same drain is used after a CUR_TIME write so the programmed value is in the block before the function returns. Signed-off-by: fbalazsy --- drivers/watchdog/apple_wdt.c | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index f523cf3d1d8c8..6d11daeb34470 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -103,7 +103,14 @@ static void apple_wdt_wd2_arm(struct apple_wdt *wdt, u32 bark_ticks) * the separate AON reconfig mapping; apple_wdt_enable_reconfig() reads * back reconfig before the final IRQ_EN write. */ + /* + * Disarm first and drain that write: while IRQ_EN is set the block + * ignores a CUR_TIME update, and a posted disarm is not enough. + * A sleep or hibernation restore has to re-program an already-running + * counter; the same sequence is used at start and at ping. + */ 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); @@ -112,6 +119,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 int apple_wdt_start(struct watchdog_device *wdd) @@ -148,8 +156,24 @@ static int apple_wdt_ping(struct watchdog_device *wdd) if (wdt->reconfig && apple_sleep_wdt_active(wdd->parent)) return 0; - cur_off = wdt->reconfig ? APPLE_WDT_WD2_CUR_TIME : APPLE_WDT_WD1_CUR_TIME; + 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; } From 03b7a6bd78a561cf17a2579e5c2ad91ed740cc3d Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 21:31:46 +0100 Subject: [PATCH 074/140] soc: apple: sleep: Look up the engine-reset power block from SoC data apple_sleep_engine_reset() finds a coprocessor's power controllers in the PMGR block the sleep node maps as "ps". Some SoCs map that same block under another name and keep their own mapping, so the lookup had a second window filled by the T6040 map with a hard-coded "soc-east". Name the block in the SoC's match data (ps_reg_name, default "ps") and look it up there. Another SoC only adds the name to its data. Signed-off-by: fbalazsy --- drivers/soc/apple/sleep-t6040.h | 5 +---- drivers/soc/apple/sleep.c | 22 +++++++++------------- 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/drivers/soc/apple/sleep-t6040.h b/drivers/soc/apple/sleep-t6040.h index 5682a3df32a3d..f4cb26637b278 100644 --- a/drivers/soc/apple/sleep-t6040.h +++ b/drivers/soc/apple/sleep-t6040.h @@ -2159,10 +2159,6 @@ static int t6040_sleep_map_regs(struct apple_sleep *c) s->mbox = c->mbox; c->ps = s->soc_east; - /* The PMGR block whose power controllers the engine reset looks up. */ - widx = of_property_match_string(dev->of_node, "reg-names", "soc-east"); - if (widx < 0 || of_address_to_resource(dev->of_node, widx, &c->ps_window)) - memset(&c->ps_window, 0, sizeof(c->ps_window)); c->wdt = s->wdt; c->cpu_start = s->cpu_start; c->commit = s->mastermini + MASTERMINI_S2R_TIMER; @@ -2430,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 3e44d3f9eb6ef..a98efb206e1d3 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -818,6 +818,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; /* @@ -887,12 +893,6 @@ struct apple_sleep { bool usb_down_ran; /* The PMGR block "ps" maps, for the power controllers' nodes. */ struct resource ps_res; - /* - * The same block where a SoC's own map_regs maps it under another name: only the - * engine reset looks its power controllers up there, apple_sleep_domain_set() and its - * driver-down words keep to ps_res. - */ - struct resource ps_window; /* Its words a driver took down with apple_sleep_domain_set() and hasn't raised. */ unsigned long *driver_down; void __iomem *clk_mux; @@ -3139,10 +3139,11 @@ static int sleep_engine_reset_wait(struct apple_sleep *s, u32 offset, u32 actual 10, PS_OFF_TIMEOUT_US); } -/* 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; @@ -3150,11 +3151,6 @@ static bool sleep_ps_domain(struct apple_sleep *s, struct device_node *pd, u32 * ours = idx >= 0 && parent && !of_address_to_resource(s->dev->of_node, idx, &ps) && !of_address_to_resource(parent, 0, &res) && res.start == ps.start && !of_property_read_u32(pd, "reg", offset); - if (!ours && parent && resource_size(&s->ps_window)) - ours = !of_address_to_resource(parent, 0, &res) && - res.start == s->ps_window.start && - !of_property_read_u32(pd, "reg", offset) && !(*offset % 4) && - *offset + 4 <= resource_size(&s->ps_window); of_node_put(parent); return ours; From 6667e6d232cb23224c9f7e8f5ac10d715c690e4d Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 21:31:47 +0100 Subject: [PATCH 075/140] drm/apple: dcp: Drive external-link restart from display-power match data Whether the sleep takes the external links down and back, and whether the external DCPs are restarted after the wake, was selected in the general mapping code with of_device_is_compatible() for apple,t6040-display-power. Put a relink_ext flag in per-compatible data and look the node up in an of_device_id table, the way the sleep driver selects SoC data. Another SoC only adds a table entry. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp-internal.h | 4 +-- drivers/gpu/drm/apple/dcp.c | 38 +++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 060da34b25142..ac046901c6961 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -301,8 +301,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; }; /* diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index f92f816d715c2..8f280e145e4e2 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -8399,7 +8399,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) @@ -8409,6 +8409,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; @@ -8431,13 +8453,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, @@ -13266,7 +13292,7 @@ bool dcp_t6040_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. */ @@ -14482,7 +14508,7 @@ static int dcp_t6041_start(bool cold) dcp_t6041_words = false; ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &cold, dcp_t6041_start_one); - if (!ret && host->t6041_power.t6040) + if (!ret && host->t6041_power.relink_ext) ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &cold, dcp_t6040_ext_start_one); return ret; From b2e962e1260aa3f0b9503978b51eccfc17d6fa5c Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 21:40:36 +0100 Subject: [PATCH 076/140] drm/apple: dcp: Give the hibernation relink path generic names The general IOMFB and hibernation paths referred to the external-link restart with T6040-named fields and helpers (t6040_relinking, dcp_t6040_relinks() and so on), even though the behaviour is already selected by display-power match data (relink_ext). Rename those fields and functions so another SoC only adds its match-data flag. Update the selftests that stub or string-match the same names. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp-internal.h | 12 +- drivers/gpu/drm/apple/dcp.c | 169 +++++++++--------- drivers/gpu/drm/apple/dcp.h | 4 +- drivers/gpu/drm/apple/iomfb.c | 12 +- drivers/gpu/drm/apple/iomfb_template.c | 8 +- tools/asahi/backlight-coldboot-tests.py | 4 +- tools/asahi/dcpext26-retrain-tests.py | 4 +- .../drivers/gpu/apple-dcp/lifecycle.py | 2 +- .../selftests/drivers/gpu/apple-dcp/rate.py | 4 +- 9 files changed, 109 insertions(+), 110 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index ac046901c6961..5baa6e2bed760 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -689,21 +689,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. diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 8f280e145e4e2..5962818229621 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5561,8 +5561,8 @@ static bool dcp_h17g_panel(struct apple_dcp *dcp) static void dcp_dpms_power_off(struct apple_dcp *dcp); static void 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) @@ -5605,10 +5605,10 @@ void dcp_poweron(struct platform_device *pdev) /* * Powered later: on T6040 S2R once the link is back - * (dcp_t6040_ext_link_down()), after a resume from disk by the + * (dcp_ext_link_down()), after a resume from disk by the * firmware restart (dcp_hib_recommit()). */ - if (READ_ONCE(dcp->t6040_relinking) || dcp_hib_gated(dcp)) + if (READ_ONCE(dcp->ext_relinking) || dcp_hib_gated(dcp)) return; /* The takeover trial powered it on before the eviction. */ @@ -5815,7 +5815,7 @@ void dcp_poweroff(struct platform_device *pdev) * work is through, after a resume from disk there is no firmware * session yet. */ - if (READ_ONCE(dcp->t6040_relinking) || dcp_hib_gated(dcp)) + if (READ_ONCE(dcp->ext_relinking) || dcp_hib_gated(dcp)) return; if (iomfb_is_m4(dcp)) { @@ -8924,8 +8924,8 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) #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); @@ -9499,8 +9499,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); } /* Registration pins callback/provider lifetimes until same-task scope end. */ @@ -12503,8 +12503,8 @@ static bool dcp_hib_ext_has_display(struct apple_dcp *dcp) */ #define DCP_S2R_PLUG_MS 10000 -static void dcp_t6040_fixed_phy_up(struct apple_dcp *dcp); -static bool dcp_t6040_fixed_hdmi(struct apple_dcp *dcp); +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) { @@ -12512,20 +12512,20 @@ static void dcp_hib_ext_relink(struct apple_dcp *dcp) dcp->hib_link_released = false; /* - * Taken down at .freeze by the T6040 sleep's stop (dcp_t6040_ext_link_down()): the + * 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_t6040_link_work()): the PHY and the converter up before the link, and the + * (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->t6040_relinking)) { - if (dcp->t6040_fixed_phy_off) - dcp_t6040_fixed_phy_up(dcp); + 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_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, plug); + WRITE_ONCE(dcp->ext_plug_wait, plug); if (dcp->hib_typec_disabled) { dcp->hib_typec_disabled = false; dcp_enable_typec_work(dcp); @@ -12536,10 +12536,10 @@ static void dcp_hib_ext_relink(struct apple_dcp *dcp) dcp->hib_irq_disabled = false; dcp_enable_dp2hdmi_hpd(dcp); if (plug) - mod_delayed_work(system_dfl_wq, &dcp->t6040_plug_wq, + mod_delayed_work(system_dfl_wq, &dcp->ext_plug_wq, msecs_to_jiffies(DCP_S2R_PLUG_MS)); else - WRITE_ONCE(dcp->t6040_relinking, false); + WRITE_ONCE(dcp->ext_relinking, false); return; } /* @@ -12585,8 +12585,8 @@ static void dcp_hib_ext_link_up(struct apple_dcp *dcp, const char *when) * 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->t6040_relinking) && dcp->t6040_fixed_phy_off) - dcp_t6040_fixed_phy_up(dcp); + 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); @@ -13264,7 +13264,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) { @@ -13281,14 +13281,14 @@ static int dcp_t6041_recommit(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 +#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); @@ -13296,7 +13296,7 @@ bool dcp_t6040_relinks(void) } /* 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; @@ -13310,9 +13310,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); @@ -13325,7 +13325,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) { @@ -13351,10 +13351,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); } @@ -13370,23 +13370,23 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) /* 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; /* 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). @@ -13425,14 +13425,14 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) 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(dcp); 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)); @@ -13466,7 +13466,7 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) * 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; @@ -13477,17 +13477,17 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) 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); } _dcp_poweroff(dcp); 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"); @@ -13501,13 +13501,13 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) } 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); @@ -13520,14 +13520,14 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) * 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) { @@ -13669,7 +13669,7 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) 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_recommit(dcp)) @@ -14242,7 +14242,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; @@ -14253,8 +14253,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]; @@ -14276,7 +14275,7 @@ 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); @@ -14290,18 +14289,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]; @@ -14349,7 +14348,7 @@ static int dcp_t6040_ext_start_one(struct device *dev, void *data) 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); @@ -14360,19 +14359,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; @@ -14391,25 +14390,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) @@ -14423,9 +14422,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; @@ -14439,25 +14438,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); } /* @@ -14465,13 +14464,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. @@ -14480,12 +14479,12 @@ 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 }; @@ -14510,7 +14509,7 @@ static int dcp_t6041_start(bool cold) dcp_t6041_start_one); if (!ret && host->t6041_power.relink_ext) ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &cold, - dcp_t6040_ext_start_one); + dcp_ext_start_one); return ret; } diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index f4f948eba5726..0890f0d205cdd 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -176,7 +176,7 @@ int dcp_dptx_disconnect_oob(struct platform_device *pdev, u32 port); bool dcp_hold_resume_event(struct platform_device *pdev); bool dcp_s2r_firmware_stopped(struct platform_device *pdev); int dcp_t6041_s2r_all(bool start); -bool dcp_t6040_relinks(void); +bool dcp_ext_relinks(void); void dcp_t6041_hib_restore(void); int iomfb_start_rtkit(struct apple_dcp *dcp); @@ -213,7 +213,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/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index a7bad6d16f17a..b7171df3da305 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -1591,7 +1591,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)) { /* @@ -2095,7 +2095,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) { @@ -2152,7 +2152,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); @@ -4015,9 +4015,9 @@ 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()). */ @@ -4880,7 +4880,7 @@ 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; } diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 283e5e24495e0..fc0a581c915f2 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -3257,16 +3257,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/tools/asahi/backlight-coldboot-tests.py b/tools/asahi/backlight-coldboot-tests.py index 5284351d27144..692bf50780241 100755 --- a/tools/asahi/backlight-coldboot-tests.py +++ b/tools/asahi/backlight-coldboot-tests.py @@ -71,7 +71,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; @@ -186,7 +186,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/dcpext26-retrain-tests.py b/tools/asahi/dcpext26-retrain-tests.py index f4e8e784c2e81..c5e7fe6529d64 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/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index 10fa7701723f2..93f278ad02f2c 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -856,7 +856,7 @@ def poweroff_replug(root): struct apple_connector *connector; struct { bool active; } split; bool external_h17p, external_stop_deferred, soft_dpms, typec_output; - bool typec_cable_connected, typec_crtc_off, external_native, t6040_relinking; + bool typec_cable_connected, typec_crtc_off, external_native, ext_relinking; u64 external_crtc_generation, typec_unplugs, crtc_unplugs; }; struct platform_device { struct apple_dcp *data; }; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index 65dd73488a27e..a8e2a7bea3b16 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -1440,7 +1440,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; + bool ext_relinking,ext_plug_wait; u64 external_stop_generation,external_rx_generation,external_crtc_generation; unsigned swap_watchdog_retrains;int typec_iomfb_hpd_ready,typec_display_ready;''') stubs = r''' @@ -1452,7 +1452,7 @@ def hotplug(root): static void dcp_handle_hotplug_actions(struct apple_dcp *d,unsigned action) { (void)d;(void)action; } static bool dcp_typec_relink(struct apple_dcp *d) { (void)d;return false; } /* 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() From be10c35d726b0e77a8844679a74832df0c8ed285 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Tue, 1 Dec 2026 21:40:36 +0100 Subject: [PATCH 077/140] drm/apple: dcp: Take the start ready-wait from match data The general start path waited 10 s when the node was apple,t6041-dcp. The T6041 panel runs its client-open, main-display and power chain inside the start, so the wait has to cover that. Put the timeout in the DCP's match data (ready_timeout_ms; 0 means the 3 s default) and take the longest of the processors being started. Another SoC only sets the field. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/apple_drv.c | 21 ++++++++++++++------- drivers/gpu/drm/apple/dcp-internal.h | 6 ++++++ drivers/gpu/drm/apple/dcp.c | 1 + 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 770212cab05af..775abaa07d092 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -2361,6 +2361,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; for_each_matching_node(np, apple_dcp_id_tbl) { @@ -2439,14 +2440,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(); diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 5baa6e2bed760..d0af72fbb6134 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -434,6 +434,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; }; enum dcp_test_point { diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 5962818229621..3bf9ebf332a4e 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -13137,6 +13137,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, }; static const struct apple_dcp_hw_data apple_dcp_hw_t6041_dcpext = { From ccc1fb8c32e5531877ce0b914cf007bb100699c8 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 04:45:37 +0100 Subject: [PATCH 078/140] drm/asahi: Reboot G17 firmware after a hibernation restore On a chip whose firmware already restarts after a system sleep, keep enough state in the image to boot the firmware again after a restore: the reserved translation tables (the image does not hold that memory), the bootloader-handover regions named in the device tree, and the initialization objects the driver can reuse. At freeze, snapshot those tables and stop the firmware. On restore the boot loader has reset the coprocessor, so pre-image queues, client VMs and kick rings must not be handed to the new firmware. Retire them locally, bump the firmware epoch so leftover clients see a lost device, rebuild init data, and start the firmware as a probe would. An ASC reset on driver teardown puts the handover regions back so the next boot starts from the same contents the boot loader left. Queue admission packs a generation with the live count so a leftover QueueSlot from before the image cannot underflow the new count. Signed-off-by: fbalazsy --- drivers/gpu/drm/asahi/asahi_core.rs | 3 + drivers/gpu/drm/asahi/boot_memory.rs | 200 ++++++++ drivers/gpu/drm/asahi/driver.rs | 51 +- drivers/gpu/drm/asahi/g17/buffer.rs | 21 + drivers/gpu/drm/asahi/g17/context.rs | 11 + drivers/gpu/drm/asahi/g17/freelist.rs | 29 +- drivers/gpu/drm/asahi/g17/initdata.rs | 379 +++++++++++++-- drivers/gpu/drm/asahi/g17/kick.rs | 109 ++++- drivers/gpu/drm/asahi/g17/mod.rs | 46 ++ drivers/gpu/drm/asahi/g17/port.rs | 6 + drivers/gpu/drm/asahi/g17/power.rs | 29 +- drivers/gpu/drm/asahi/g17/queue/admission.rs | 136 +++++- drivers/gpu/drm/asahi/g17/queue/compute.rs | 22 + drivers/gpu/drm/asahi/g17/queue/mod.rs | 2 +- drivers/gpu/drm/asahi/g17/queue/render.rs | 39 ++ .../gpu/drm/asahi/g17/queue/render/parked.rs | 26 + drivers/gpu/drm/asahi/g17/runtime.rs | 14 +- drivers/gpu/drm/asahi/g17/runtime/render.rs | 78 +++ .../gpu/drm/asahi/g17/runtime/render/grow.rs | 9 + .../gpu/drm/asahi/g17/runtime/render/pools.rs | 7 + .../drm/asahi/g17/runtime/render/prepare.rs | 20 +- drivers/gpu/drm/asahi/g17/sleep.c | 47 ++ drivers/gpu/drm/asahi/g17/sleep.h | 2 + drivers/gpu/drm/asahi/g17/sleep.rs | 457 +++++++++++++++++- drivers/gpu/drm/asahi/g17/teardown.rs | 6 + drivers/gpu/drm/asahi/gpu.rs | 17 + drivers/gpu/drm/asahi/mmu.rs | 269 ++++++++++- 27 files changed, 1908 insertions(+), 127 deletions(-) create mode 100644 drivers/gpu/drm/asahi/boot_memory.rs diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b236766ef8697..813c5e2812344 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; @@ -110,6 +111,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 { g17::exec_share::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 5b692ea51f190..3657864fc7860 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -338,17 +338,57 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { /// 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() { - backend.hib_restore_contain(); + f(&**backend); } if let Some(gpu) = data.g16.as_ref() { - gpu.hib_restore_contain(); + f(&**gpu); } if let Some(gpu) = data.g17.as_ref() { - gpu.hib_restore_contain(); + 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 } @@ -357,6 +397,9 @@ static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { complete: Some(sleep_complete), suspend_noirq: Some(sleep_suspend_noirq), 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() } @@ -706,6 +749,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/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index 0d9bdd33ba1ed..806933b77576f 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; @@ -882,6 +898,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 1ceff7bd982c0..6ea11ceef1c5d 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -450,6 +450,17 @@ 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.status.get() == 0 { + self.status.record(EIO); + } + outlived + } 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 017f6d03b2013..e59a24e3224e4 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -91,10 +91,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()); @@ -1477,6 +1481,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 56d654e7712f6..67b6ae404be3f 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -229,6 +229,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. @@ -241,9 +301,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, @@ -252,10 +332,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, @@ -270,6 +356,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, @@ -279,6 +370,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. @@ -338,9 +457,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 } @@ -397,6 +535,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> { @@ -536,6 +764,30 @@ impl InitData { if self.compute_shared.is_some() { return Ok(()); } + self.publish_compute_shared(&mut 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 let Some(mut shared) = self.compute_shared.take() { + let result = self.publish_compute_shared(&mut shared); + self.compute_shared = Some(shared); + result?; + } + 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, shared: &mut ComputeShared) -> 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(); @@ -566,7 +818,6 @@ impl InitData { Ok(()) })?; fence(Ordering::SeqCst); - self.compute_shared = Some(shared); Ok(()) } @@ -1149,6 +1400,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) } @@ -1165,6 +1418,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, @@ -1193,18 +1463,41 @@ 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 = 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( @@ -1215,6 +1508,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(), @@ -1258,15 +1555,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, @@ -1322,8 +1619,10 @@ impl InitData { self.boot_state = Some(state); } } - self.stamps[0] = self.add(env.fixed(high::DESCRIPTOR_PAGE_A, mmu::UAT_PGSZ, GFS, WC)?)?; - self.stamps[1] = self.add(env.fixed(high::DESCRIPTOR_PAGE_B, mmu::UAT_PGSZ, GFP, WC)?)?; + self.stamps[0] = self.add(env.fixed_kept( + high::DESCRIPTOR_PAGE_A, mmu::UAT_PGSZ, GFS, WC)?)?; + self.stamps[1] = self.add(env.fixed_kept( + high::DESCRIPTOR_PAGE_B, mmu::UAT_PGSZ, GFP, WC)?)?; self.add(env.fixed(high::TA_CONTEXT, CONTEXT_SIZE, FS, WC)?)?; self.add(env.fixed(high::FRAGMENT_CONTEXT, CONTEXT_SIZE, FS, WC)?)?; Ok(()) @@ -1334,11 +1633,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( @@ -1346,26 +1641,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), @@ -1392,17 +1680,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) @@ -1461,7 +1743,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, @@ -1470,8 +1752,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 43e1115f221f0..580740ab0c41b 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,22 @@ 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(error) => { + let _ = error; + } } } let (vm, status) = (client.id(), client.status().cloned()); @@ -703,26 +761,37 @@ impl Queue { mmu::UAT_PGSZ as u64, firmware_prot, CpuMap::WriteCombined, - )?; + ) + .map_err(|error| { + error + })?; 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, + ) + .map_err(|error| { + error + })?; 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 37c6e84473b0f..4abb68b0cfcc7 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -830,6 +830,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, } @@ -861,6 +864,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) @@ -1649,6 +1674,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) { @@ -1765,6 +1792,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. @@ -2022,6 +2064,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 calibration = if cfg.chip_id == crate::hw::t6040::CHIP_ID { Some(calibration::Calibration::read(dev).inspect_err(|_| { dev_err!( @@ -2587,6 +2631,7 @@ impl Gpu { init: initdata::InitData::new(), _render_global: render_global, _pm_metrics: session_metrics, + hib: None, uat, }), GFP_KERNEL, @@ -2794,6 +2839,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 00fa2cdf0294b..c51c4629a2c86 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -205,6 +205,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 c4e1125a6dbd9..87fe1ba833e42 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -994,7 +994,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 {} @@ -1009,28 +1009,45 @@ 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, + ) + }; } } 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 2cdad54f1706b..a3bcc82c144d5 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::*, @@ -924,7 +924,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. @@ -950,7 +950,7 @@ impl Pool { pin_init!(Self { state <- new_mutex!(State::new(), "G17 render admission"), released <- new_condvar!("G17 render pair release"), - queues: AtomicU32::new(0), + queues: AtomicU64::new(0), max_queues, waiters, renders, @@ -967,7 +967,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. @@ -979,7 +1036,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 @@ -992,7 +1049,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 } @@ -1020,9 +1077,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 { @@ -1049,19 +1107,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, } } } @@ -1074,7 +1133,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 grew = (room && !state.build_room) || capacity > state.render_capacity; @@ -1156,7 +1215,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 = @@ -1211,7 +1270,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); }; @@ -1233,7 +1292,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( @@ -1242,7 +1301,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; @@ -1340,6 +1399,28 @@ impl Pool { self.returned(); } + /// 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 @@ -1521,19 +1602,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. @@ -1546,17 +1631,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(); } @@ -1767,7 +1855,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(), @@ -1877,7 +1965,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 919741fdf9faf..08038c662e084 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -723,6 +723,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, @@ -744,6 +746,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( @@ -843,6 +864,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 4df522c98daf9..6d38cd96820c7 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -586,7 +586,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 5d63169e007a9..d4a1cdb2712ff 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -208,6 +208,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 @@ -423,11 +425,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 349cbe1a60add..c74e957afdac2 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. @@ -146,6 +148,7 @@ impl Pair { executed: self.executed, vm, status, + outlived: self.outlived, }; let retired = RetiredBinding { _client_kicks: retired_kicks, @@ -167,6 +170,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 @@ -370,6 +395,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 b79ee66cfa63b..70c7deb0237d0 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -3959,7 +3959,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); @@ -4185,7 +4189,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 @@ -4268,6 +4272,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(); } @@ -4290,6 +4299,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 08545e3097cdf..0c65f416880e3 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -1334,9 +1334,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 c096970ded545..9ac9dc900497a 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 c3a66941cfbae..eafa4feeb8ec1 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs @@ -33,6 +33,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 1c57ed12adcef..85c426337b9f8 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -491,7 +491,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 { @@ -576,7 +579,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)?; @@ -706,7 +712,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)?; @@ -796,7 +805,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 e62315b1eb2b5..4fc1418c62f5e 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.c +++ b/drivers/gpu/drm/asahi/g17/sleep.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -308,6 +309,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 a8a304fd86144..a471db16380ae 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.h +++ b/drivers/gpu/drm/asahi/g17/sleep.h @@ -20,6 +20,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); #endif diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index ec031bfa03f3b..654c1b0473e3c 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -20,9 +20,10 @@ //! 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::*, sync::Arc, time::{delay::fsleep, Delta}, @@ -40,6 +41,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 +61,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 { @@ -620,6 +693,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() { @@ -645,17 +724,375 @@ impl super::Gpu { } } +impl Firmware { + /// Stops the firmware for a hibernation image, from a process context: each instance is told + /// to idle and its acknowledgments are waited for, its mailbox goes off and its CPU stops, + /// then the domain is lowered as for a sleep. Told to idle, the firmware can't carry on, so + /// the stop goes on whatever an instance answers. + fn hib_stop(&mut self) { + let shared = self.primary.state.shared.clone(); + for role in [Role::Secondary, Role::Primary] { + let Ok(coprocessor) = self.coprocessor(role) else { + continue; + }; + // An instance asleep with its memory kept answers EALREADY: as good as idle here. + match coprocessor.rtkit.with(|rtkit| rtkit.idle()) { + Ok(()) | Err(EALREADY) => {} + Err(error) => { + dev_warn!(shared.dev.as_ref(), "GPU firmware {:?} idle: {:?}\n", role, error) + } + } + // SAFETY: The instance was told to idle; a restart or a cold boot follows. + coprocessor + .rtkit + .with(|rtkit| unsafe { bindings::apple_rtkit_mailbox_off(rtkit.as_raw()) }); + coprocessor.stop(); + } + // The domain stays up with its request: the PMP still runs until the image is written, + // and reads the GPU's registers while it does. + } + + /// 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 and client VMs are not carried over; post-restore clients allocate + /// them 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)?; + + // 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"))?; + + + // 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(); + + // 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(); + + self.seen_submissions = 0; + // 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. + 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"))?; + 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"))?; + + if ack == super::fw::variant::InitAck::Status { + super::Gpu::wait_for_init_accepted( + &drm, + &self.init, + &self.primary, + ).inspect_err(at("accepted"))?; + } + 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"))?; + } + 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); + + 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, waits for quiet and stops the firmware; `tables` is filled at the last + /// step before the image. 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_stop(); + 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 written or the hibernation failed: the firmware's memory is as it left it. + 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() { + let _ = self.sleep_up(); + } + } + + /// 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_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. This is a fresh warm boot and 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). + /// 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) { - self.shared.lose_device_quietly(); + 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(); } } diff --git a/drivers/gpu/drm/asahi/g17/teardown.rs b/drivers/gpu/drm/asahi/g17/teardown.rs index 84e36aaaeadc6..c7a96980398c9 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 d9401f447961e..ab54c390ff47d 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -621,8 +621,25 @@ pub(crate) trait GpuManager: Send + Sync { /// 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. diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index ae4a95da16b87..a03b8defee748 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -365,6 +365,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 { @@ -1240,9 +1267,13 @@ impl VmInner { let _mutation = self.mapping_mutation(); // Allocate detached RAM tables before excluding the firmware. The shadow L2 is not // the reserved shared-L2; only final leaf stores below already linked L3s are live. - self.page_table.prepare_map(node.start()..end)?; + self.page_table.prepare_map(node.start()..end).map_err(|error| { + error + })?; let uat_inner = self.uat_inner.clone(); - let handoff = uat_inner.lock_m4_upper(self.is_kernel)?; + let handoff = uat_inner.lock_m4_upper(self.is_kernel).map_err(|error| { + error + })?; // Refuse a range holding another mapping's leaves before writing anything: the // discard below clears the whole range. if let Err(error) = self.page_table.ensure_unmapped(node.start()..end) { @@ -1362,6 +1393,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::firmware_epoch`] when this VM was created. + firmware_epoch: u32, } no_debug!(Vm); @@ -1388,6 +1421,9 @@ 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, } @@ -1453,8 +1489,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); @@ -2102,7 +2146,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!( @@ -2118,6 +2163,9 @@ 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). drop(upper_handoff); @@ -2143,7 +2191,8 @@ impl Drop for KernelMapping { 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) }; } } @@ -2277,6 +2326,9 @@ 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, /// 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, @@ -2601,6 +2653,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.firmware_epoch.load(Ordering::Acquire); let page_table = if let Some(ttb) = ttb { UatPageTable::new_with_ttb( @@ -2701,6 +2754,7 @@ impl Vm { private_bytes: Arc::new(AtomicU64::new(0), GFP_KERNEL)?, narrow_pool_window, uat_inner, + firmware_epoch, }) } @@ -2997,12 +3051,18 @@ impl Vm { return Err(EINVAL); } let reserved_size = size.checked_add(guard_size).ok_or(EOVERFLOW)?; - let _residency = self.enter_residency()?; + let _residency = self.enter_residency().map_err(|error| { + error + })?; // End the bound-device lease before entering firmware/GPUVM waits. let (_bind_lease, vm_bo) = { - let binding = self.device_binding.enter()?; + let binding = self.device_binding.enter().map_err(|error| { + error + })?; let dev = binding.device(); - let lease = crate::gem::held_sg_table(gem, dev)?.into_lease(); + let lease = crate::gem::held_sg_table(gem, dev).map_err(|error| { + error + })?.into_lease(); let bo = self.gpuvm.obtain( gem, pin_init!(VmBoData { @@ -3753,6 +3813,7 @@ impl Uat { firmware: UatFirmware::Handoff, m4_adopted: !map_kernel_to_user, failed: AtomicBool::new(false), + firmware_epoch: AtomicU32::new(0), // The G15 UAT walker does not snoop the CPU caches. clean_poc: true, reserved: None, @@ -4153,6 +4214,7 @@ impl Uat { inner: self.inner.clone(), id: id as u8, generation, + epoch: self.inner.firmware_epoch.load(Ordering::Acquire), low, high, }, @@ -4215,6 +4277,8 @@ impl Uat { } } + + /// 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 { @@ -4327,6 +4391,188 @@ 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.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. + unsafe { core::ptr::copy_nonoverlapping(buf.as_ptr(), map.ptr(), size) }; + pgtable::clean_poc(map.ptr(), size); + pgtable::poc_barrier(); + } + } + 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) { @@ -4384,6 +4630,7 @@ impl Uat { firmware, m4_adopted: false, failed: AtomicBool::new(false), + firmware_epoch: AtomicU32::new(0), clean_poc: quirks.clean_tables, quirks, reserved, @@ -4438,7 +4685,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. @@ -4578,6 +4825,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.firmware_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)> { From fdd44fda8bdc474f39faed3270827ad08204e9ae Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 04:45:38 +0100 Subject: [PATCH 079/140] drm/asahi: Clear untracked kernel-dynamic PTEs after reserved-table merge After a hibernation restore, pre-image kernel mappings are unmapped before the firmware is started again. That unmap succeeds. The firmware then builds its kernel-window tables in the reserved no-map l2-pagetables region (translation memory the hibernation image does not hold), which puts the previous PTEs back into VA ranges whose drm_mm nodes were already freed. merge_reserved does not catch this: the rebuilt entries already match the copy taken at freeze, so nothing is reported as restored. A later map into those holes fails with EBUSY. After the reserved tables are merged, walk the kernel-dynamic range and unmap any leaf that is not covered by a drm_mm node, then TLBI, before init data is rebuilt. Never free a drm_mm node while its leaves are still live. Reconstruct the canonical IOVA when walking IAS-masked addresses so a comparison with a full drm_mm range is meaningful. A walk after init is a cheap check: warn once and clear if anything remains. Skip compact-window ranges that cannot hold the requested mapping. Signed-off-by: fbalazsy --- drivers/gpu/drm/asahi/g17/buffer.rs | 8 +++ drivers/gpu/drm/asahi/g17/sleep.rs | 20 +++++++ drivers/gpu/drm/asahi/mmu.rs | 44 +++++++++++++++ drivers/gpu/drm/asahi/pgtable.rs | 83 +++++++++++++++++++++++++++++ 4 files changed, 155 insertions(+) diff --git a/drivers/gpu/drm/asahi/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index 806933b77576f..98353b404f936 100644 --- a/drivers/gpu/drm/asahi/g17/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/buffer.rs @@ -382,7 +382,15 @@ pub(crate) fn compact_alias( 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 cfg::compact_ranges() { + 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 => {} diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index 654c1b0473e3c..082f389be6443 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -25,6 +25,7 @@ use core::sync::atomic::Ordering; use kernel::{ bindings, device, prelude::*, + pr_warn_once, sync::Arc, time::{delay::fsleep, Delta}, workqueue::{DelayedWork, Work}, @@ -848,6 +849,13 @@ impl Firmware { } 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", @@ -912,6 +920,18 @@ impl Firmware { .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 + ); + } Ok(()) } } diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index a03b8defee748..32caaede0075f 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -2166,6 +2166,7 @@ impl Drop for KernelMapping { // 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); @@ -2187,6 +2188,10 @@ 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); } @@ -4277,6 +4282,45 @@ 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. diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index 381ad1acc7164..56ae8cd8d1c4d 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -187,6 +187,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() @@ -1045,6 +1050,84 @@ impl UatPageTable { self.alloc_pages(range) } + /// 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(), false, 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(), false, 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 From e285d57d2199efeaa3217936eb559d676cdbb41e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 06:25:40 +0100 Subject: [PATCH 080/140] soc: apple: sleep: Map an unnamed coprocessor register range for engine reset apple_sleep_engine_reset looks up the ASC by the "coproc" or "asc" reg-name. A coprocessor whose node has a single register range and no reg-names then returns -ENODEV, and its firmware is not restarted after a hibernation restore. If the node has no reg-names, use register index 0. Signed-off-by: fbalazsy --- drivers/soc/apple/sleep.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index a98efb206e1d3..702d4d87b79c1 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -3198,6 +3198,9 @@ 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; if (!asc) return -ENODEV; From f45d7dfdc2a1d0136220683044f3104516d1cc19 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 16:49:03 +0100 Subject: [PATCH 081/140] watchdog: apple: arm WD2 simple-reconfig as a hibernation-restore backstop The firmware DT on some platforms (T6041, T8142) describes the watchdog block but not the simple-reconfig routing register, so apple_wdt_start() falls back to WD1 RESET_EN, which does not reset reliably. When the DT has no "reconfig" resource, map it from per-compatible match data (the same AON_WDT_SLEEP / wdt-aux + 0x2c register the sleep driver already documents for that SoC). A DT resource still wins when present. Arm WD2 once the hibernation image is loaded and devices have been quiesced, just before the image jump, so a hang in restore_noirq cold-resets within a bound below the ~178 s hardware wrap (default 120 s). After a successful restore, adopt or stop a still-running WD2 so the backstop cannot fire on a healthy path. Write /var/log/hibernate-restore.crumb (fallback /boot/...) when an image is found, because pstore/ramoops has no reserved-memory in the firmware DT and a later default-kernel boot would otherwise leave no evidence of the restore attempt. --- drivers/watchdog/apple_wdt.c | 107 +++++++++++++++++++++++++++++ include/linux/soc/apple/watchdog.h | 23 +++++++ kernel/power/hibernate.c | 54 +++++++++++++++ 3 files changed, 184 insertions(+) create mode 100644 include/linux/soc/apple/watchdog.h diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 6d11daeb34470..595e5748cca44 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -16,7 +16,9 @@ #include #include #include +#include #include +#include #include /* @@ -65,6 +67,8 @@ #define APPLE_WDT_REBOOT_DELAY_MS 40 #define APPLE_WDT_TIMEOUT_DEFAULT 30 +/* Default restore backstop: under the ~178 s U32 wrap at 24 MHz. */ +#define APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT 120 struct apple_wdt { struct watchdog_device wdd; @@ -73,6 +77,35 @@ struct apple_wdt { unsigned long clk_rate; }; +/* + * Simple-reconfig physical address, used only when the DT has no named + * "reconfig" resource. Addresses are the AON_WDT_SLEEP / wdt-aux + 0x2c + * register already documented by the sleep driver for that SoC. + */ +struct apple_wdt_match { + u64 reconfig_pa; +}; + +static const struct apple_wdt_match apple_wdt_t6041 = { + .reconfig_pa = 0x50833002c, +}; + +static const struct apple_wdt_match apple_wdt_t6050 = { + .reconfig_pa = 0x28833002c, +}; + +static const struct apple_wdt_match apple_wdt_t8142 = { + .reconfig_pa = 0x3882b802c, +}; + +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 WD2 backstop timeout in seconds (0 = disable, default 120, capped by max_hw_heartbeat_ms)"); + +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); @@ -321,6 +354,19 @@ static int apple_wdt_probe(struct platform_device *pdev) resource_size(reconfig_res)); if (!wdt->reconfig) return -ENOMEM; + } else { + const struct apple_wdt_match *match; + + match = of_device_get_match_data(dev); + if (match && match->reconfig_pa) { + wdt->reconfig = devm_ioremap(dev, match->reconfig_pa, + sizeof(u32)); + if (!wdt->reconfig) + return -ENOMEM; + dev_info(dev, + "simple-reconfig at %#llx (SoC match data)\n", + (unsigned long long)match->reconfig_pa); + } } clk = devm_clk_get_enabled(dev, NULL); @@ -402,9 +448,52 @@ 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; + return devm_watchdog_register_device(dev, &wdt->wdd); } +int apple_wdt_arm_hibernation_restore(unsigned int timeout_s) +{ + struct apple_wdt *wdt = apple_wdt_instance; + unsigned int max_s, s; + + if (!wdt) + return -ENODEV; + if (!wdt->reconfig) { + pr_err("hibernation restore backstop needs simple-reconfig\n"); + return -ENODEV; + } + + s = timeout_s ? timeout_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)); + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + pr_info("hibernation restore: WD2 simple-reconfig cold-reset in %u s\n", s); + return 0; +} +EXPORT_SYMBOL_GPL(apple_wdt_arm_hibernation_restore); + +static bool apple_wdt_hw_armed(struct apple_wdt *wdt) +{ + u32 ctrl; + + 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); @@ -412,6 +501,21 @@ static int apple_wdt_resume(struct device *dev) if (wdt->reconfig && apple_sleep_wdt_active(dev)) 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); + clear_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + dev_info(dev, "adopted hibernation-restore WD2 and stopped it\n"); + return 0; + } + dev_info(dev, "adopted hibernation-restore WD2; refreshing timeout\n"); + } + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) apple_wdt_start(&wdt->wdd); @@ -434,6 +538,9 @@ static int apple_wdt_suspend(struct device *dev) static DEFINE_SIMPLE_DEV_PM_OPS(apple_wdt_pm_ops, apple_wdt_suspend, apple_wdt_resume); static const struct of_device_id apple_wdt_of_match[] = { + { .compatible = "apple,t6041-wdt", .data = &apple_wdt_t6041 }, + { .compatible = "apple,t6050-wdt", .data = &apple_wdt_t6050 }, + { .compatible = "apple,t8142-wdt", .data = &apple_wdt_t8142 }, { .compatible = "apple,t8103-wdt" }, { .compatible = "apple,wdt" }, {}, diff --git a/include/linux/soc/apple/watchdog.h b/include/linux/soc/apple/watchdog.h new file mode 100644 index 0000000000000..cc55d37b17180 --- /dev/null +++ b/include/linux/soc/apple/watchdog.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _LINUX_SOC_APPLE_WATCHDOG_H_ +#define _LINUX_SOC_APPLE_WATCHDOG_H_ + +#include +#include + +/* + * Arm WD2 on the simple-reconfig cold-reset route as a hibernation-restore + * backstop. @timeout_s of 0 uses the driver's default (capped below the + * ~178 s U32 wrap). Returns 0 if armed or disabled, or a negative errno + * if the hardware cannot be programmed. + */ +#if IS_REACHABLE(CONFIG_APPLE_WATCHDOG) +int apple_wdt_arm_hibernation_restore(unsigned int timeout_s); +#else +static inline int apple_wdt_arm_hibernation_restore(unsigned int timeout_s) +{ + return -ENODEV; +} +#endif + +#endif /* _LINUX_SOC_APPLE_WATCHDOG_H_ */ diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index faaab5c6d1fea..9abcaabd00a33 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -33,7 +33,9 @@ #include #include #include +#include #include +#include #include #include "power.h" @@ -759,6 +761,17 @@ int hibernation_restore(int platform_mode) console_suspend_all(); error = dpm_suspend_start(PMSG_QUIESCE); if (!error) { + /* + * Arm WD2 after the restore-kernel has quiesced devices (so the + * driver's suspend callback cannot stop it) and after the image is + * already in memory. The counter survives the jump; a hang in + * restore_noirq then cold-resets within the programmed bound. + */ + int wdt_err = apple_wdt_arm_hibernation_restore(0); + + if (wdt_err) + pr_err("WD2 restore backstop failed (%d); continuing\n", + wdt_err); error = resume_target_kernel(platform_mode); /* * The above should either succeed and jump to the new kernel, @@ -912,6 +925,45 @@ static void power_down(void) pr_err("Swap will be unusable! Try swapon -a.\n"); } +/* + * Persistent breadcrumb for a restore that hangs after the image is found. + * pstore/ramoops is compiled in on some platforms but has no reserved-memory + * in the firmware DT, so a file on the root fs is what a later default-kernel + * boot can still read. Written before filesystems_freeze(). + */ +static void hibernation_write_crumb(const char *what) +{ + static const char * const paths[] = { + "/var/log/hibernate-restore.crumb", + "/boot/hibernate-restore.crumb", + }; + char buf[256]; + int i, n; + + n = snprintf(buf, sizeof(buf), "%llu %s\n", + (unsigned long long)ktime_get_real_seconds(), what); + if (n <= 0) + return; + + for (i = 0; i < ARRAY_SIZE(paths); i++) { + struct file *f; + loff_t pos = 0; + ssize_t w; + + f = filp_open(paths[i], O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + if (IS_ERR(f)) + continue; + w = kernel_write(f, buf, n, &pos); + vfs_fsync(f, 0); + filp_close(f, NULL); + if (w == n) { + pr_info("wrote restore crumb to %s\n", paths[i]); + return; + } + } + pr_warn("could not write a restore crumb\n"); +} + static int load_image_and_restore(void) { int error; @@ -1296,6 +1348,8 @@ static int software_resume(void) } pr_info("resume from hibernation\n"); + hibernation_write_crumb( + "image found; will load, then arm WD2 backstop before jump"); pm_prepare_console(); error = pm_notifier_call_chain_robust(PM_RESTORE_PREPARE, PM_POST_RESTORE); if (error) From 1b91d0ecba595c6630caadef181492c6665185fe Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 17:38:19 +0100 Subject: [PATCH 082/140] watchdog: apple: arm the WD2 backstop on hibernation entry too A restore-side hang is not the only way a cycle can leave the machine wedged: snapshot, image write, or the power-off reboot can also stick, and the restore kernel's backstop is not armed until after the image is found. Arm WD2 on the simple-reconfig cold-reset route at hibernation entry, before filesystems are frozen, and do not stop it in apple_wdt_suspend while that backstop is active. If the restore kernel finds WD2 already running, adopt it and refresh the timeout to the backstop value rather than the 30 s default, so a long image load is not cut short. Default timeout is 150 s, still under the ~178 s hardware wrap. Write the persistent restore crumb at entry as well, with more paths and open() errors, so a later default-kernel boot can tell whether entry ran. --- drivers/watchdog/apple_wdt.c | 26 +++++++++++++++++++++----- kernel/power/hibernate.c | 21 +++++++++++++++++++-- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 595e5748cca44..81639fee013c6 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -68,13 +68,14 @@ #define APPLE_WDT_TIMEOUT_DEFAULT 30 /* Default restore backstop: under the ~178 s U32 wrap at 24 MHz. */ -#define APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT 120 +#define APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT 150 struct apple_wdt { struct watchdog_device wdd; void __iomem *regs; void __iomem *reconfig; unsigned long clk_rate; + bool hib_backstop; }; /* @@ -102,7 +103,7 @@ 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 WD2 backstop timeout in seconds (0 = disable, default 120, capped by max_hw_heartbeat_ms)"); + "Hibernation-restore WD2 backstop timeout in seconds (0 = disable, default 150, capped by max_hw_heartbeat_ms)"); static struct apple_wdt *apple_wdt_instance; @@ -413,13 +414,22 @@ static int apple_wdt_probe(struct platform_device *pdev) 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, wdt->wdd.timeout)); + apple_wdt_wd2_arm(wdt, apple_wdt_timeout_ticks(wdt, s)); } else { if (wd2_ctrl) writel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS, @@ -476,8 +486,9 @@ int apple_wdt_arm_hibernation_restore(unsigned int timeout_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 restore: WD2 simple-reconfig cold-reset in %u s\n", s); + pr_info("hibernation backstop: WD2 simple-reconfig cold-reset in %u s\n", s); return 0; } EXPORT_SYMBOL_GPL(apple_wdt_arm_hibernation_restore); @@ -509,6 +520,7 @@ static int apple_wdt_resume(struct device *dev) 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 WD2 and stopped it\n"); return 0; @@ -529,6 +541,10 @@ static int apple_wdt_suspend(struct device *dev) if (wdt->reconfig && apple_sleep_wdt_active(dev)) return 0; + /* Leave a hibernation backstop ticking through snapshot, write, and reboot. */ + if (wdt->hib_backstop) + return 0; + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) apple_wdt_stop(&wdt->wdd); diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 9abcaabd00a33..4b0a989ae3e05 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -935,6 +935,7 @@ static void hibernation_write_crumb(const char *what) { static const char * const paths[] = { "/var/log/hibernate-restore.crumb", + "/var/lib/hibernate-restore.crumb", "/boot/hibernate-restore.crumb", }; char buf[256]; @@ -951,8 +952,11 @@ static void hibernation_write_crumb(const char *what) ssize_t w; f = filp_open(paths[i], O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); - if (IS_ERR(f)) + if (IS_ERR(f)) { + pr_warn("crumb %s open failed (%ld)\n", + paths[i], PTR_ERR(f)); continue; + } w = kernel_write(f, buf, n, &pos); vfs_fsync(f, 0); filp_close(f, NULL); @@ -1055,6 +1059,16 @@ int hibernate(void) } pr_info("hibernation entry\n"); + { + int wdt_err = apple_wdt_arm_hibernation_restore(0); + + if (wdt_err) + pr_err("WD2 entry backstop failed (%d); continuing\n", + wdt_err); + hibernation_write_crumb( + wdt_err ? "hibernation entry; WD2 backstop FAILED" + : "hibernation entry; WD2 backstop armed, about to snapshot/write"); + } pm_prepare_console(); error = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION); if (error) @@ -1112,14 +1126,17 @@ int hibernate(void) flags |= SF_COMPRESSION_ALG_LZO; } - pm_pr_dbg("Writing hibernation image.\n"); + pr_info("writing hibernation image\n"); error = swsusp_write(flags); 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(); From b1473c6c42acfe6feaf529957790b67109ba4311 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 18:10:40 +0100 Subject: [PATCH 083/140] watchdog: apple: use the SMC AP deadline on wdt-version 2 On wdt-version 2 with simple-reconfig-wdog-support, the runtime AP watchdog is an absolute second stamp at aon-misc+0x08 (wdt reg[2], AON_AP_DEADLINE). The SMC 1 s timer enters the AP-watchdog-logger when SMC uptime exceeds deadline - 1 and then bites the AP WDT block (PMU reset_in_1). A write of 0 disarms the deadline, matching the SMC boot path and sleep.c. WD2 bark is the sleep/ICC reconfig path (enableAONWatchdogForReconfig), not the version-2 runtime route. Programming WD2 IRQ_EN and RMW-ing reconfig bits 5:4 = 01 on this SoC took the machine down without a clean iBoot reboot. For version 2, map the deadline at reconfig_pa - 0x24 (the same aon-misc layout the sleep driver already documents, not a T6040 hard-code) and arm the hibernation/restart backstop there. The deadline stamp uses CNTPCT seconds as a stand-in for the firmware continuous time, since ktime_get_boottime() would omit the iBoot/m1n1 window. Everyday systemd pings stay on WD1 RESET_EN so a timebase error cannot take the machine down on first /dev/watchdog0 open. Version > 2 keeps the WD2 path, but replaces the reconfig low 8 bits (no leftover halt-on-expiration bit) instead of only RMW-ing bits 5:4. t6041 match data sets wdt-version 2. t6050 and t8142 keep the previous WD2 path until their firmware versions are confirmed. Signed-off-by: fbalazsy --- drivers/watchdog/apple_wdt.c | 376 ++++++++++++++++++++++++----- include/linux/soc/apple/watchdog.h | 9 +- 2 files changed, 321 insertions(+), 64 deletions(-) diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 81639fee013c6..def9dd92bad99 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include #include #include @@ -25,15 +27,33 @@ * 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 simple-reconfig-wdog-support the runtime reset path depends + * on firmware wdt-version (AppleARMWatchdogTimer): + * + * version 2 (t6041): the AP watchdog is the SMC deadline at + * aon-misc+0x08 (wdt reg[2], AON_AP_DEADLINE). Firmware + * _armWatchdogMechanism writes (continuous time + timeout) in + * seconds. The SMC 1 s timer enters the AP-watchdog-logger when SMC + * uptime > deadline - 1, then bites the AP WDT block (PMU reset_in_1). + * A write of 0 disarms (the SMC and Linux sleep.c both zero it). + * WD2 bark is the sleep/ICC reconfig path (enableAONWatchdogForReconfig), + * not the runtime cold-reset route. + * + * version > 2: _armWatchdogMechanism programs WD2 bark (IRQ_EN, BITE + * unused) and _writeApWatchdogConfiguration sets reconfig bit 4 + * (bits 5:4 = 01) as the runtime route. + * + * _writeApWatchdogConfiguration replaces the low 8 bits of the reconfig + * register: bit 0 = halt-on-expiration, bit 3 if !AWL, bit 4 only when + * version > 2. Linux never sets the halt bit. + * + * AON_AP_DEADLINE is aon-misc+0x08 and AON_WDT_SLEEP / reconfig is + * aon-misc+0x2c, so deadline_pa = reconfig_pa - 0x24. That layout is + * already used by the sleep driver; it is not a T6040 special case. * * 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. @@ -59,22 +79,39 @@ #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 (aon-misc+0x2c) low-8-bit policy from + * AppleARMWatchdogTimer::_writeApWatchdogConfiguration. 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 */ +/* aon-misc+0x2c minus aon-misc+0x08 */ +#define APPLE_WDT_DEADLINE_OFF_FROM_RECONFIG 0x24 + +/* ~40 ms bark delay before version>2 simple-reconfig cold reset */ #define APPLE_WDT_REBOOT_DELAY_MS 40 #define APPLE_WDT_TIMEOUT_DEFAULT 30 -/* Default restore backstop: under the ~178 s U32 wrap at 24 MHz. */ +/* + * 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; /* AON_AP_DEADLINE, wdt-version 2 */ unsigned long clk_rate; + u8 wdt_version; bool hib_backstop; }; @@ -82,13 +119,17 @@ struct apple_wdt { * Simple-reconfig physical address, used only when the DT has no named * "reconfig" resource. Addresses are the AON_WDT_SLEEP / wdt-aux + 0x2c * register already documented by the sleep driver for that SoC. + * wdt_version is the firmware wdt-version for that compatible (0 = unknown; + * keep the version>2 WD2 bark path). */ struct apple_wdt_match { u64 reconfig_pa; + u8 wdt_version; }; static const struct apple_wdt_match apple_wdt_t6041 = { .reconfig_pa = 0x50833002c, + .wdt_version = 2, /* t6041, firmware wdt-version 2 */ }; static const struct apple_wdt_match apple_wdt_t6050 = { @@ -103,7 +144,7 @@ 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 WD2 backstop timeout in seconds (0 = disable, default 150, capped by max_hw_heartbeat_ms)"); + "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; @@ -112,6 +153,11 @@ 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 && wdt->wdt_version == 2; +} + static u32 apple_wdt_timeout_ticks(struct apple_wdt *wdt, unsigned int s) { u32 actual = min(s, wdt->wdd.max_hw_heartbeat_ms / 1000); @@ -119,15 +165,77 @@ 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) +{ + /* + * Version > 2: 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) { /* @@ -160,6 +268,22 @@ static int apple_wdt_start(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); + /* + * Everyday systemd pings stay on WD1 for wdt-version 2. 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 0; + + if (apple_wdt_use_smc_deadline(wdt)) { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); + writel_relaxed(APPLE_WDT_CTRL_RESET_EN, + wdt->regs + APPLE_WDT_WD1_CTRL); + return 0; + } + if (wdt->reconfig) { apple_wdt_wd2_arm(wdt, apple_wdt_timeout_ticks(wdt, wdd->timeout)); @@ -175,9 +299,18 @@ static int apple_wdt_start(struct watchdog_device *wdd) static int apple_wdt_stop(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); - u32 ctrl_off = wdt->reconfig ? APPLE_WDT_WD2_CTRL : APPLE_WDT_WD1_CTRL; - writel_relaxed(0, wdt->regs + ctrl_off); + 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 + (wdt->reconfig ? APPLE_WDT_WD2_CTRL : + APPLE_WDT_WD1_CTRL)); return 0; } @@ -190,6 +323,15 @@ static int apple_wdt_ping(struct watchdog_device *wdd) if (wdt->reconfig && apple_sleep_wdt_active(wdd->parent)) return 0; + 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); @@ -215,8 +357,22 @@ static int apple_wdt_ping(struct watchdog_device *wdd) static int apple_wdt_set_timeout(struct watchdog_device *wdd, unsigned int s) { struct apple_wdt *wdt = to_apple_wdt(wdd); - u32 ticks = apple_wdt_timeout_ticks(wdt, s); + u32 ticks; + wdd->timeout = s; + + 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); writel_relaxed(ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME); @@ -225,15 +381,34 @@ static int apple_wdt_set_timeout(struct watchdog_device *wdd, unsigned int s) writel_relaxed(ticks, wdt->regs + APPLE_WDT_WD1_BITE_TIME); } - wdd->timeout = s; - return 0; } 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 @@ -270,6 +445,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, @@ -330,10 +516,24 @@ 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, + u64 reconfig_pa) +{ + u64 deadline_pa = reconfig_pa - APPLE_WDT_DEADLINE_OFF_FROM_RECONFIG; + + wdt->deadline = devm_ioremap(dev, deadline_pa, sizeof(u32)); + if (!wdt->deadline) + return -ENOMEM; + dev_info(dev, "SMC AP deadline at %#llx (aon-misc+0x08, wdt-version %u)\n", + (unsigned long long)deadline_pa, wdt->wdt_version); + return 0; +} + static int apple_wdt_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct resource *wdt_res, *reconfig_res; + const struct apple_wdt_match *match; struct apple_wdt *wdt; struct clk *clk; u32 wdt_ctrl; @@ -347,6 +547,10 @@ static int apple_wdt_probe(struct platform_device *pdev) if (IS_ERR(wdt->regs)) return PTR_ERR(wdt->regs); + match = of_device_get_match_data(dev); + if (match) + wdt->wdt_version = match->wdt_version; + reconfig_res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "reconfig"); if (reconfig_res) { if (resource_size(reconfig_res) < sizeof(u32)) @@ -355,18 +559,23 @@ static int apple_wdt_probe(struct platform_device *pdev) resource_size(reconfig_res)); if (!wdt->reconfig) return -ENOMEM; - } else { - const struct apple_wdt_match *match; - - match = of_device_get_match_data(dev); - if (match && match->reconfig_pa) { - wdt->reconfig = devm_ioremap(dev, match->reconfig_pa, - sizeof(u32)); - if (!wdt->reconfig) - return -ENOMEM; - dev_info(dev, - "simple-reconfig at %#llx (SoC match data)\n", - (unsigned long long)match->reconfig_pa); + if (wdt->wdt_version == 2) { + ret = apple_wdt_map_deadline(dev, wdt, reconfig_res->start); + if (ret) + return ret; + } + } else if (match && match->reconfig_pa) { + wdt->reconfig = devm_ioremap(dev, match->reconfig_pa, + sizeof(u32)); + if (!wdt->reconfig) + return -ENOMEM; + dev_info(dev, + "simple-reconfig at %#llx (SoC match data)\n", + (unsigned long long)match->reconfig_pa); + if (wdt->wdt_version == 2) { + ret = apple_wdt_map_deadline(dev, wdt, match->reconfig_pa); + if (ret) + return ret; } } @@ -389,7 +598,7 @@ static int apple_wdt_probe(struct platform_device *pdev) watchdog_init_timeout(&wdt->wdd, 0, dev); if (wdt->reconfig) { - u32 wd1_ctrl, wd2_ctrl; + u32 wd1_ctrl, wd2_ctrl, deadline; bool armed; /* @@ -407,34 +616,64 @@ static int apple_wdt_probe(struct platform_device *pdev) 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()) { - 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; + 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 WD2 backstop, refreshing to %u s\n", - s); + "adopting running SMC AP deadline 0x%x, refreshing to %u s\n", + deadline, s); + } else { + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); } - 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); + 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); @@ -467,11 +706,26 @@ int apple_wdt_arm_hibernation_restore(unsigned int timeout_s) { 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 = timeout_s ? timeout_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\n"); + pr_err("hibernation restore backstop needs simple-reconfig or an SMC AP deadline\n"); return -ENODEV; } @@ -497,6 +751,8 @@ 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); @@ -522,10 +778,10 @@ static int apple_wdt_resume(struct device *dev) apple_wdt_stop(&wdt->wdd); wdt->hib_backstop = false; clear_bit(WDOG_HW_RUNNING, &wdt->wdd.status); - dev_info(dev, "adopted hibernation-restore WD2 and stopped it\n"); + dev_info(dev, "adopted hibernation-restore backstop and stopped it\n"); return 0; } - dev_info(dev, "adopted hibernation-restore WD2; refreshing timeout\n"); + dev_info(dev, "adopted hibernation-restore backstop; refreshing timeout\n"); } if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) diff --git a/include/linux/soc/apple/watchdog.h b/include/linux/soc/apple/watchdog.h index cc55d37b17180..6e2965965f371 100644 --- a/include/linux/soc/apple/watchdog.h +++ b/include/linux/soc/apple/watchdog.h @@ -6,10 +6,11 @@ #include /* - * Arm WD2 on the simple-reconfig cold-reset route as a hibernation-restore - * backstop. @timeout_s of 0 uses the driver's default (capped below the - * ~178 s U32 wrap). Returns 0 if armed or disabled, or a negative errno - * if the hardware cannot be programmed. + * Arm a hibernation-restore backstop. On wdt-version 2 this programs the + * SMC AP deadline (aon-misc+0x08). On version > 2 it arms WD2 on the + * simple-reconfig cold-reset route. @timeout_s of 0 uses the driver's + * default. Returns 0 if armed or disabled, or a negative errno if the + * hardware cannot be programmed. */ #if IS_REACHABLE(CONFIG_APPLE_WATCHDOG) int apple_wdt_arm_hibernation_restore(unsigned int timeout_s); From 1138b641ab7b60f787514fcd9b6a8780e5285c93 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 18:47:13 +0100 Subject: [PATCH 084/140] PM: hibernation: defer probing while resume-from-disk is pending The restore kernel may bind display firmware from the initramfs (early KMS) before software_resume() has found the image. pm_hibernate_is_loading() is only true from PM_RESTORE_PREPARE, which is after that bind. Freezing a just-bound DCP around the jump then runs the sleep-stop sequence on a session that is not the one recorded in the image, and leaves the coprocessor running against host state the image is about to overwrite. Add pm_hibernate_resume_pending(), true from resume= (or a write to /sys/power/resume) until software_resume() has given up. Leave it set when the resume device is not ready at late_initcall so a later initramfs retry still sees it. On a failed attempt, clear the flag and trigger deferred probing so a normal boot still gets its displays. apple-dcp and the apple-drm display subsystem return -EPROBE_DEFER while the flag is set, so a standard initramfs can keep early KMS without the restore kernel starting firmware. The kernel restored from the image already has its own freeze/restore path. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/apple_drv.c | 8 ++++++ drivers/gpu/drm/apple/dcp.c | 9 ++++++ include/linux/device/driver.h | 1 + include/linux/suspend.h | 2 ++ kernel/power/hibernate.c | 47 +++++++++++++++++++++++++++++++ 5 files changed, 67 insertions(+) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 775abaa07d092..0937cad16b64d 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -2803,6 +2803,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) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 3bf9ebf332a4e..43d439f77e8ec 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9428,6 +9428,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); 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/suspend.h b/include/linux/suspend.h index 85ad46cb1b79d..4cda382699e9d 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -473,10 +473,12 @@ static inline bool pm_hibernation_mode_is_suspend(void) { return false; } #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 diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 4b0a989ae3e05..bc5e1e2c4f066 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -183,6 +183,46 @@ 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 @@ -1401,6 +1441,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(); @@ -1623,6 +1664,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; } @@ -1724,6 +1766,7 @@ static int __init resume_setup(char *str) return 1; strscpy(resume_file, str); + hibernate_set_resume_pending(); return 1; } @@ -1744,11 +1787,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(); @@ -1759,6 +1804,7 @@ static int __init hibernate_setup(char *str) static int __init noresume_setup(char *str) { noresume = 1; + hibernate_clear_resume_pending(); return 1; } @@ -1781,6 +1827,7 @@ static int __init nohibernate_setup(char *str) { noresume = 1; nohibernate = 1; + hibernate_clear_resume_pending(); return 1; } From cea6f9df38bdcf0639ffbf009f27afe3deb3a087 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 19:00:34 +0100 Subject: [PATCH 085/140] PM: hibernation: clear resume-pending if software_resume cannot run pm_hibernate_resume_pending() must not stay set when this kernel is not going to resume from disk. software_resume_initcall() used to return early on noresume or !hibernation_available() without clearing the flag, so drivers that defer their probe (apple-dcp, apple-drm) never bound on a boot where the platform check still refused hibernation. Clear the flag and trigger deferred probing in that path. Leave it set only when the resume device is not ready yet, so an initramfs retry can still see it. Signed-off-by: fbalazsy --- kernel/power/hibernate.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index bc5e1e2c4f066..dced2c2782cf7 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -1468,8 +1468,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(); From 561b67b3880d4912a1d9a9cf133b981e1da4561f Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 20:43:16 +0100 Subject: [PATCH 086/140] iommu: apple-dart: adopt locked roots after a hibernation restore After a resume from disk the boot loader has locked the DART again with fresh firmware-owned roots, while the restored kernel still describes the image's published slots. Republishing those slots returns -EBUSY, and later DMA mappings through the DART fail. Defer reimport of locked DARTs that a display subsystem scans out through, and of the PMP's DART, until the consumer is up (apple_dart_display_restore()). At that point, snapshot the boot loader's new roots and adopt them: keep a firmware slot only when the pre-image tables still mirror it, otherwise take the slot for Linux so the restarted coprocessor can map through it. Leave restore_pending set if the reimport fails, so a later consumer call can retry. Signed-off-by: fbalazsy --- drivers/iommu/apple-dart.c | 87 ++++++++++++++++++++++++++++++++------ 1 file changed, 75 insertions(+), 12 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 59a80c7e0deda..0581ce86e4f4e 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -1147,6 +1147,35 @@ static bool apple_dart_display_scanout(struct device_node *np) return false; } +/* + * 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; +} + /* 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) @@ -1300,7 +1329,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; @@ -1310,6 +1339,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)) @@ -1323,7 +1359,25 @@ 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)) { @@ -1698,7 +1752,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; @@ -1758,7 +1812,8 @@ 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; } @@ -3082,7 +3137,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); @@ -3095,7 +3150,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--; @@ -3115,7 +3170,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); @@ -3709,7 +3764,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) @@ -8464,7 +8519,7 @@ static int apple_dart_reimport_locked(struct apple_dart *dart) if (!cfg) continue; __set_bit(sid, stream.sidmap); - err = apple_dart_hw_sync_locked(cfg, &stream, false); + err = apple_dart_hw_sync_locked(cfg, &stream, false, true); if (!err) err = dart->hw->invalidate_tlb(&stream); if (err) { @@ -8485,10 +8540,16 @@ static int apple_dart_restore(struct device *dev) struct apple_dart *dart = dev_get_drvdata(dev); int ret; - /* No register of a block its display consumer took down can be read before it is up. */ - if (READ_ONCE(dart->display_unpowered)) { + /* + * 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_dbg(dev, "hibernation restore deferred to its display's power-up\n"); + dev_info(dev, "hibernation restore deferred until the consumer is up\n"); return 0; } ret = apple_dart_system_resume(dev); @@ -8541,7 +8602,9 @@ int apple_dart_display_restore(struct device *dev) return ret; ret = apple_dart_reimport_locked(dart); pm_runtime_put(dev); - dev_dbg(dev, "deferred hibernation restore at its display's power-up: %d\n", ret); + if (ret) + WRITE_ONCE(dart->restore_pending, true); + dev_info(dev, "hibernation restore at consumer power-up: %d\n", ret); #endif return ret; } From e94e9a3c03c0fc8c404d3db1748338e6fed475c3 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 20:43:16 +0100 Subject: [PATCH 087/140] drm/apple, soc/apple: restore deferred DARTs at hibernation power-up The DART core now defers reimport of locked display and PMP roots until apple_dart_display_restore(). Call that before DCP streams start (including the internal start path) and mark external DCP DARTs unpowered at freeze so .restore does not race the loader. The PMP PM notifier marks its DART at PM_HIBERNATION_PREPARE and reimports it at PM_POST_HIBERNATION, before apple_pmp_restore(). Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp.c | 17 +++++++++++-- drivers/soc/apple/pmp-export.c | 45 +++++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 43d439f77e8ec..72f267eb6d5b3 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -12875,8 +12875,17 @@ static int dcp_platform_freeze(struct device *dev) return -EBUSY; if (dcp_takeover_was_aborted(dcp) || READ_ONCE(dcp->ext_dead)) return 0; - if (dcp->external) - return dcp_platform_suspend(dev); + 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; @@ -14128,6 +14137,10 @@ static int dcp_t6041_start_one(struct device *dev, void *data) dev_warn(dev, "display child domains not on after the sleep: %#x\n", to); dcp_s2r_find_darts(dcp); + 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); diff --git a/drivers/soc/apple/pmp-export.c b/drivers/soc/apple/pmp-export.c index b7ed02455f167..1b68e6a6e53c1 100644 --- a/drivers/soc/apple/pmp-export.c +++ b/drivers/soc/apple/pmp-export.c @@ -6,7 +6,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -35,15 +38,55 @@ static bool pmp_asleep; * 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) +{ + 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) + 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); + } apple_pmp_restore(pmp_data); + } return NOTIFY_DONE; } From 00adb57a1d50e61289fa09457ab4ed36f62066f7 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 21:13:27 +0100 Subject: [PATCH 088/140] ASoC: tas2764: treat a hibernation restore as an expected power-on A firmware-driven sleep already restores the amps from a power-on reset. Hibernation drops the same rails, but pm_resume_via_firmware() is false, so the driver detected the reset and warned. Treat pm_hibernate_is_restored() as the same expected power-on path. An unexpected reset during s2idle still warns and restores. soc: apple: aop: drop stale EPIC replies after a hibernation restore After a restore the firmware can complete a request that this kernel does not have a call slot for. Drop those unmatched RETCODE replies quietly instead of warning. Give T6040 its own compatible and the same AFK sleep/wake order T6041 already uses, without putting that sequence on the T6040 match data other SoCs inherit. Signed-off-by: fbalazsy --- .../bindings/soc/apple/apple,t6041-aop.yaml | 1 + arch/arm64/boot/dts/apple/t6040.dtsi | 1 + drivers/soc/apple/aop.rs | 49 ++++++++++++++----- sound/soc/codecs/tas2764.c | 9 ++-- 4 files changed, 46 insertions(+), 14 deletions(-) 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/arch/arm64/boot/dts/apple/t6040.dtsi b/arch/arm64/boot/dts/apple/t6040.dtsi index 13ad6aed111e2..b93e74e89db6d 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/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 3099c44a084d1..131a951112920 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -797,6 +797,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 +872,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 +886,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()); @@ -3225,11 +3242,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 @@ -3394,6 +3420,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), diff --git a/sound/soc/codecs/tas2764.c b/sound/soc/codecs/tas2764.c index d1f9e3994cbbf..8687426a454fc 100644 --- a/sound/soc/codecs/tas2764.c +++ b/sound/soc/codecs/tas2764.c @@ -439,10 +439,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 && pm_resume_via_firmware(); + bool power_on = tas2764->sdz_group && + (pm_resume_via_firmware() || pm_hibernate_is_restored()); int ret; if (!tas2764->sdz_group) { From 1024711a57b3ee4e38ddd96e97cbd0a8beb15a7c Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Wed, 2 Dec 2026 23:00:18 +0100 Subject: [PATCH 089/140] PM: hibernation: report restore-phase timings After a successful restore, log how long device restore took inside dpm_resume, and add elapsed times for DART adopt at consumer power-up, GPU firmware bring-up steps, and DCP external-link / DPTX waits. Image load already reports its speed in the restore kernel via swsusp_show_speed(). The GPU init and DPTX / DCP link waits are already completion or wait-event based. The new logs show where the remaining wall time actually goes. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp.c | 38 ++++++++++++++++-------------- drivers/gpu/drm/asahi/g17/sleep.rs | 13 ++++++++++ drivers/iommu/apple-dart.c | 29 +++++++++++++---------- kernel/power/hibernate.c | 11 ++++++++- 4 files changed, 60 insertions(+), 31 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 72f267eb6d5b3..49f64f8dcd97a 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -3464,8 +3465,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); @@ -12599,23 +12601,23 @@ static void dcp_hib_ext_link_up(struct apple_dcp *dcp, const char *when) display = dcp_hib_ext_has_display(dcp); dcp_hib_ext_put(dcp, true, display); - 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)); + { + ktime_t link_start = ktime_get(); - dcp_hib_ext_relink(dcp); - dcp_hib_ext_put(dcp, false, true); - dev_dbg(dcp->dev, - "hibernation %s: external link replayed: display %d, route %s, cable %d, DPTX port 0 connected %d\n", - when, display, - READ_ONCE(dcp->active_typec_route) ? "Type-C" : - dcp->fixed_phy ? "fixed" : "none", - READ_ONCE(dcp->typec_cable_connected), - READ_ONCE(dcp->dptxport[0].connected)); + 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); + } } /* diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index 082f389be6443..72a14263248e7 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -766,6 +766,7 @@ impl Firmware { 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( @@ -837,6 +838,7 @@ impl Firmware { // 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 tables_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"))?; @@ -893,6 +895,7 @@ impl Firmware { } 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( @@ -901,6 +904,7 @@ impl Firmware { &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)?; } @@ -914,6 +918,7 @@ impl Firmware { 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 @@ -932,6 +937,14 @@ impl Firmware { first ); } + dev_info!( + shared.dev.as_ref(), + "GPU cold-boot steps: tables {} us, firmware up {} us, init accepted {} us, opening {} us\n", + tables_ns / 1000, + boot_ns.saturating_sub(tables_ns) / 1000, + accepted_ns.saturating_sub(boot_ns) / 1000, + opening_ns.saturating_sub(accepted_ns) / 1000 + ); Ok(()) } } diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 0581ce86e4f4e..20351e848ba4f 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -8591,20 +8591,25 @@ int apple_dart_display_restore(struct device *dev) if (!dart->restore_pending) return 0; WRITE_ONCE(dart->restore_pending, false); - ret = apple_dart_system_resume(dev); - if (ret || !dart->locked) { + { + 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) - dev_err(dev, "deferred hibernation restore failed: %d\n", ret); - return 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))); } - 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\n", ret); #endif return ret; } diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index dced2c2782cf7..907c54d5398c6 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -677,7 +677,16 @@ int hibernation_snapshot(int platform_mode) swsusp_free(); msg = hibernate_resume_event(error); - dpm_resume(msg); + 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(); From 308931a74aea6715b45e4b9f0234f7c0cf7329a8 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 00:40:42 +0100 Subject: [PATCH 090/140] watchdog: apple: hand the SMC AP deadline back after a hibernation restore The deadline armed on hibernation entry, and refreshed by the restore kernel, keeps the machine from hanging in the write, power-off or restore. Once the image is back it was never disarmed: with the backstop flag set, ping and start are no-ops on the SMC path, so the restored session was reset when the original deadline expired. Give the restore transition its own callback. When the SMC deadline is armed as the hibernation backstop, disarm it, clear the flag and return the everyday watchdog to WD1; other cases keep the resume behaviour. --- drivers/watchdog/apple_wdt.c | 37 +++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index def9dd92bad99..e8b290e074b69 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -807,7 +807,42 @@ 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); +/* + * The image is back in memory and every device has been restored: the SMC AP + * deadline 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. Hand the + * everyday watchdog back to WD1, which systemd keeps feeding. + */ +static int apple_wdt_restore(struct device *dev) +{ + struct apple_wdt *wdt = dev_get_drvdata(dev); + + if (!(apple_wdt_use_smc_deadline(wdt) && wdt->hib_backstop)) + return apple_wdt_resume(dev); + + 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; +} + +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_suspend), + .thaw = pm_sleep_ptr(apple_wdt_resume), + .poweroff = pm_sleep_ptr(apple_wdt_suspend), + .restore = pm_sleep_ptr(apple_wdt_restore), +}; static const struct of_device_id apple_wdt_of_match[] = { { .compatible = "apple,t6041-wdt", .data = &apple_wdt_t6041 }, From 8c78be1e152da8165c6ee6663a92678c3cb6843a Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 00:40:42 +0100 Subject: [PATCH 091/140] usb: dwc3-apple: resume the USB tree in order after a hibernation restore With async resume the hub port resets of the restored tree can race the parent hub coming back. Disable async suspend/resume for the xhci child tree while a hibernation is admitted and re-enable it afterwards, so only that transition is ordered and ordinary suspend keeps its async resume. --- drivers/usb/dwc3/dwc3-apple.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index 3d953192c739e..d0aadd5132e0d 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -2159,6 +2159,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) { @@ -2166,6 +2194,9 @@ static int dwc3_apple_pm_notify(struct notifier_block *nb, unsigned long action, unsigned long flags; bool start = false; + 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 || @@ -2213,6 +2244,8 @@ static int dwc3_apple_pm_notify(struct notifier_block *nb, unsigned long action, * 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); From 3e4189d03d8d9b30f1ae6ea437e3f04933a21abb Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 00:40:43 +0100 Subject: [PATCH 092/140] net: usb: r8152: stop resubmitting rx on -ESHUTDOWN When the host controller is removed under a bound interface, every rx resubmission fails with -ESHUTDOWN and the driver reschedules NAPI for each failure, spinning (thousands of log lines) until the disconnect finally arrives. -ESHUTDOWN cannot succeed on retry any more than -ENODEV, so treat it the same: mark the device unplugged and detach the netdev. --- drivers/net/usb/r8152.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/net/usb/r8152.c b/drivers/net/usb/r8152.c index f61686433031c..ebfa83daa653a 100644 --- a/drivers/net/usb/r8152.c +++ b/drivers/net/usb/r8152.c @@ -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) { From f1aa343fbef6e76773a2d3c5fc734b981973a380 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 00:40:43 +0100 Subject: [PATCH 093/140] drm/asahi: copy the kernel-window tables in one pass after a hibernation restore Restore the reserved kernel-window tables with a per-line copy that cleans each line to the point of coherency as it goes, instead of a copy followed by a second cache walk, and time the individual cold-boot steps (tables, retire, contexts, rtkit, firmware, init) so the restore cost can be attributed. --- drivers/gpu/drm/asahi/g17/sleep.rs | 12 +++++++++--- drivers/gpu/drm/asahi/mmu.rs | 6 +++--- drivers/gpu/drm/asahi/pgtable.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index 72a14263248e7..d8ee90ad0db0e 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -779,6 +779,7 @@ impl Firmware { 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 @@ -799,6 +800,7 @@ impl Firmware { // 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); // As a firmware restart does, pre-image clients are not carried over: // each sees a lost device and starts again, on new VMs. @@ -823,6 +825,7 @@ impl Firmware { // 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.seen_submissions = 0; // The firmware starts at its own effort, as at probe. @@ -838,7 +841,7 @@ impl Firmware { // 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 tables_ns = super::now_ns().saturating_sub(t0); + 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"))?; @@ -939,9 +942,12 @@ impl Firmware { } dev_info!( shared.dev.as_ref(), - "GPU cold-boot steps: tables {} us, firmware up {} us, init accepted {} us, opening {} us\n", + "GPU cold-boot steps: tables {} us, retire {} us, contexts {} us, rtkit {} us, firmware up {} us, init accepted {} us, opening {} us\n", tables_ns / 1000, - boot_ns.saturating_sub(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 ); diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 32caaede0075f..2d87bbdef0de9 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4524,10 +4524,10 @@ impl Uat { (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. - unsafe { core::ptr::copy_nonoverlapping(buf.as_ptr(), map.ptr(), size) }; - pgtable::clean_poc(map.ptr(), size); + // 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(); diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index 56ae8cd8d1c4d..14e88fee4ff0a 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. From 5af7ff826dc833f524d8e6b591b59dd33d34537f Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 00:40:43 +0100 Subject: [PATCH 094/140] PM: hibernation: report image write and read times --- kernel/power/hibernate.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 907c54d5398c6..be003d92f6995 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -1031,7 +1031,13 @@ 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 @@ -1176,7 +1182,13 @@ int hibernate(void) } pr_info("writing hibernation image\n"); - error = swsusp_write(flags); + { + 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"); From 94666ae6dafa7e9d7c02ee797f97b4c8e310cca0 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 02:25:32 +0100 Subject: [PATCH 095/140] PM: hibernate: wait for the transition lock when setting the compressor Writing /sys/module/hibernate/parameters/compressor fails with -EBUSY whenever anything holds system_transition_mutex, because the setter only tries the lock. At boot a driver loading its firmware under lock_system_sleep() is enough to make a one-shot service that selects the compressor fail, and hibernation then silently uses the default. Take the lock with lock_system_sleep() instead, as the other hibernation controls in sysfs do. Signed-off-by: fbalazsy --- kernel/power/hibernate.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index be003d92f6995..0828e902f7488 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -1866,10 +1866,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) { @@ -1880,7 +1885,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", From a6cabc597fef8c25e70996059f5b901353b9bc22 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 09:59:00 +0100 Subject: [PATCH 096/140] soc: apple: aop: Start the co-processor again after a resume from disk A resume from disk is a cold boot: the boot loader stages the AOP firmware anew and leaves it halted, and it places some of the firmware's DRAM segments elsewhere than on the boot the restored kernel was started on. The restored kernel kept talking to the session it had before the image, which no firmware holds any more: the first call filled the endpoint's ring and the firmware crashed. Firmware that a kernel has started cannot be booted afresh before the next reboot: clearing the run bit only pauses it, and after a shutdown it does not answer a new boot handshake. So: - The kernel that loads an image shuts its own session down in its freeze callback, so that the firmware stops writing into memory the image is about to overwrite. - The restored kernel's restore callback closes the transport at once, so no client waits on a dead session. When the run bit is clear, the device is probed again once tasks are thawed: the unbind drops the old session without a shutdown, and the probe maps this boot's firmware regions from the device tree the boot loader handed over at its fixed address, starts the firmware as at boot and registers the services again, each of which sets itself up from scratch. When the firmware runs, it holds the loading kernel's session: the AOP stays off until a reboot, and its clients get -ENODEV. The two aura-hibernate helpers this needs (the running boot's firmware regions of a device, and a re-probe after thaw) come back. Signed-off-by: fbalazsy --- drivers/soc/apple/aop.rs | 440 +++++++++++++++++++++-- drivers/soc/apple/aura-hibernate.c | 196 +++++++++- include/linux/soc/apple/aura-hibernate.h | 18 + rust/bindings/bindings_helper.h | 1 + 4 files changed, 629 insertions(+), 26 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 131a951112920..1a5c7a676fea8 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::{ @@ -1294,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) { @@ -1745,6 +1767,33 @@ 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(()); @@ -2199,17 +2248,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() { @@ -2222,13 +2270,76 @@ 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 @@ -2263,6 +2374,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 @@ -2292,13 +2406,155 @@ 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, + "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, - "Validated external data region at IOVA {:#x}, size {:#x}", - iova, - size + "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) } @@ -2526,6 +2782,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. @@ -2536,8 +2802,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. @@ -2545,7 +2813,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. @@ -3401,9 +3669,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() } }; @@ -3470,7 +3820,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 }; @@ -3512,6 +3875,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 @@ -3549,13 +3915,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/aura-hibernate.c b/drivers/soc/apple/aura-hibernate.c index 2d872d0a4a394..6e20eb89da5c8 100644 --- a/drivers/soc/apple/aura-hibernate.c +++ b/drivers/soc/apple/aura-hibernate.c @@ -18,7 +18,8 @@ * 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. + * 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()). @@ -35,7 +36,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -284,6 +287,197 @@ int aura_hibernate_boot_chosen_u64(const char *name, u64 *val) } 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)); diff --git a/include/linux/soc/apple/aura-hibernate.h b/include/linux/soc/apple/aura-hibernate.h index 23a7b1f6eb972..729ced7b3c4cb 100644 --- a/include/linux/soc/apple/aura-hibernate.h +++ b/include/linux/soc/apple/aura-hibernate.h @@ -5,6 +5,24 @@ #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 diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 01e0e6cfbced8..0b60050a638e5 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -108,6 +108,7 @@ #include #include #include +#include #include #include #include From e2528d5da125f5a352492c87c9cefb4863a79854 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 10:31:49 +0100 Subject: [PATCH 097/140] watchdog: apple: disarm the hibernation backstop when the system keeps running The backstop is armed on hibernation entry and on the jump into an image, and only the restore callback disarmed it. When the image could not be written (no swap device, for example), or could not be restored, the system went on running with the backstop armed and was reset when it expired. Disarm it at the end of hibernate() and when hibernation_restore() returns, and hand the everyday watchdog back. Signed-off-by: fbalazsy --- drivers/watchdog/apple_wdt.c | 21 +++++++++++++++++++++ include/linux/soc/apple/watchdog.h | 8 ++++++++ kernel/power/hibernate.c | 8 ++++++++ 3 files changed, 37 insertions(+) diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index e8b290e074b69..50104f4a405de 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -747,6 +747,27 @@ int apple_wdt_arm_hibernation_restore(unsigned int timeout_s) } EXPORT_SYMBOL_GPL(apple_wdt_arm_hibernation_restore); +void apple_wdt_disarm_hibernation_backstop(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" : ""); +} +EXPORT_SYMBOL_GPL(apple_wdt_disarm_hibernation_backstop); + static bool apple_wdt_hw_armed(struct apple_wdt *wdt) { u32 ctrl; diff --git a/include/linux/soc/apple/watchdog.h b/include/linux/soc/apple/watchdog.h index 6e2965965f371..2b77ef42b91c9 100644 --- a/include/linux/soc/apple/watchdog.h +++ b/include/linux/soc/apple/watchdog.h @@ -11,14 +11,22 @@ * simple-reconfig cold-reset route. @timeout_s of 0 uses the driver's * default. Returns 0 if armed or disabled, or a negative errno if the * hardware cannot be programmed. + * + * Disarm the backstop when the hibernation ends in the running system + * instead: the image was not written, or the image was not restored. */ #if IS_REACHABLE(CONFIG_APPLE_WATCHDOG) int apple_wdt_arm_hibernation_restore(unsigned int timeout_s); +void apple_wdt_disarm_hibernation_backstop(void); #else static inline int apple_wdt_arm_hibernation_restore(unsigned int timeout_s) { return -ENODEV; } + +static inline void apple_wdt_disarm_hibernation_backstop(void) +{ +} #endif #endif /* _LINUX_SOC_APPLE_WATCHDOG_H_ */ diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 0828e902f7488..556df6b47c206 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -830,6 +830,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. */ + apple_wdt_disarm_hibernation_backstop(); console_resume_all(); pm_restore_console(); return error; @@ -1250,6 +1252,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. + */ + apple_wdt_disarm_hibernation_backstop(); unlock_system_sleep(sleep_flags); pr_info("hibernation exit\n"); From fbbb637bceb3ac7eb084ffbc7b4b84aa39b6fe86 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 17:20:07 +0100 Subject: [PATCH 098/140] PM: hibernate: take the reset backstop from the platform The hibernation core armed and disarmed the Apple watchdog's backstop by name, and wrote a breadcrumb file to the root filesystem on entry and when an image was found. Let the platform register the backstop instead, as it registers its hibernation check: hibernation_set_backstop() takes an arm and a disarm operation, called where the watchdog's were. The Apple watchdog registers its own and the header that exported it goes. The breadcrumb goes as well; the log and the backstop's reset cover a hung restore. No change in when the backstop runs. Signed-off-by: fbalazsy --- drivers/watchdog/apple_wdt.c | 152 ++++++++++++++++------------- include/linux/soc/apple/watchdog.h | 32 ------ include/linux/suspend.h | 16 +++ kernel/power/hibernate.c | 108 ++++++++------------ 4 files changed, 141 insertions(+), 167 deletions(-) delete mode 100644 include/linux/soc/apple/watchdog.h diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 50104f4a405de..054b9c739b141 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include /* @@ -529,6 +529,86 @@ static int apple_wdt_map_deadline(struct device *dev, struct apple_wdt *wdt, return 0; } +/* + * The hibernation backstop: on wdt-version 2 the SMC AP deadline, on later + * versions 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; @@ -698,76 +778,14 @@ static int apple_wdt_probe(struct platform_device *pdev) 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; return devm_watchdog_register_device(dev, &wdt->wdd); } -int apple_wdt_arm_hibernation_restore(unsigned int timeout_s) -{ - 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 = timeout_s ? timeout_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 = timeout_s ? timeout_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; -} -EXPORT_SYMBOL_GPL(apple_wdt_arm_hibernation_restore); - -void apple_wdt_disarm_hibernation_backstop(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" : ""); -} -EXPORT_SYMBOL_GPL(apple_wdt_disarm_hibernation_backstop); - static bool apple_wdt_hw_armed(struct apple_wdt *wdt) { u32 ctrl; diff --git a/include/linux/soc/apple/watchdog.h b/include/linux/soc/apple/watchdog.h deleted file mode 100644 index 2b77ef42b91c9..0000000000000 --- a/include/linux/soc/apple/watchdog.h +++ /dev/null @@ -1,32 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ -#ifndef _LINUX_SOC_APPLE_WATCHDOG_H_ -#define _LINUX_SOC_APPLE_WATCHDOG_H_ - -#include -#include - -/* - * Arm a hibernation-restore backstop. On wdt-version 2 this programs the - * SMC AP deadline (aon-misc+0x08). On version > 2 it arms WD2 on the - * simple-reconfig cold-reset route. @timeout_s of 0 uses the driver's - * default. Returns 0 if armed or disabled, or a negative errno if the - * hardware cannot be programmed. - * - * Disarm the backstop when the hibernation ends in the running system - * instead: the image was not written, or the image was not restored. - */ -#if IS_REACHABLE(CONFIG_APPLE_WATCHDOG) -int apple_wdt_arm_hibernation_restore(unsigned int timeout_s); -void apple_wdt_disarm_hibernation_backstop(void); -#else -static inline int apple_wdt_arm_hibernation_restore(unsigned int timeout_s) -{ - return -ENODEV; -} - -static inline void apple_wdt_disarm_hibernation_backstop(void) -{ -} -#endif - -#endif /* _LINUX_SOC_APPLE_WATCHDOG_H_ */ diff --git a/include/linux/suspend.h b/include/linux/suspend.h index adab360564e0d..28c58c5b76779 100644 --- a/include/linux/suspend.h +++ b/include/linux/suspend.h @@ -436,6 +436,20 @@ 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); + +/** + * 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); +}; + +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); @@ -471,6 +485,8 @@ 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; } +struct hibernation_backstop; +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; diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 556df6b47c206..f72499ebac0b4 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -33,9 +33,7 @@ #include #include #include -#include #include -#include #include #include "power.h" @@ -276,6 +274,38 @@ void hibernation_set_platform_check(bool (*blocked)(void), const char *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) @@ -811,16 +841,12 @@ int hibernation_restore(int platform_mode) error = dpm_suspend_start(PMSG_QUIESCE); if (!error) { /* - * Arm WD2 after the restore-kernel has quiesced devices (so the - * driver's suspend callback cannot stop it) and after the image is - * already in memory. The counter survives the jump; a hang in - * restore_noirq then cold-resets within the programmed bound. + * 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. */ - int wdt_err = apple_wdt_arm_hibernation_restore(0); - - if (wdt_err) - pr_err("WD2 restore backstop failed (%d); continuing\n", - wdt_err); + hibernation_backstop_arm("restore"); error = resume_target_kernel(platform_mode); /* * The above should either succeed and jump to the new kernel, @@ -831,7 +857,7 @@ int hibernation_restore(int platform_mode) } dpm_resume_end(PMSG_RECOVER); /* The image was not restored: this kernel goes on booting. */ - apple_wdt_disarm_hibernation_backstop(); + hibernation_backstop_disarm(); console_resume_all(); pm_restore_console(); return error; @@ -976,49 +1002,6 @@ static void power_down(void) pr_err("Swap will be unusable! Try swapon -a.\n"); } -/* - * Persistent breadcrumb for a restore that hangs after the image is found. - * pstore/ramoops is compiled in on some platforms but has no reserved-memory - * in the firmware DT, so a file on the root fs is what a later default-kernel - * boot can still read. Written before filesystems_freeze(). - */ -static void hibernation_write_crumb(const char *what) -{ - static const char * const paths[] = { - "/var/log/hibernate-restore.crumb", - "/var/lib/hibernate-restore.crumb", - "/boot/hibernate-restore.crumb", - }; - char buf[256]; - int i, n; - - n = snprintf(buf, sizeof(buf), "%llu %s\n", - (unsigned long long)ktime_get_real_seconds(), what); - if (n <= 0) - return; - - for (i = 0; i < ARRAY_SIZE(paths); i++) { - struct file *f; - loff_t pos = 0; - ssize_t w; - - f = filp_open(paths[i], O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); - if (IS_ERR(f)) { - pr_warn("crumb %s open failed (%ld)\n", - paths[i], PTR_ERR(f)); - continue; - } - w = kernel_write(f, buf, n, &pos); - vfs_fsync(f, 0); - filp_close(f, NULL); - if (w == n) { - pr_info("wrote restore crumb to %s\n", paths[i]); - return; - } - } - pr_warn("could not write a restore crumb\n"); -} - static int load_image_and_restore(void) { int error; @@ -1116,16 +1099,7 @@ int hibernate(void) } pr_info("hibernation entry\n"); - { - int wdt_err = apple_wdt_arm_hibernation_restore(0); - - if (wdt_err) - pr_err("WD2 entry backstop failed (%d); continuing\n", - wdt_err); - hibernation_write_crumb( - wdt_err ? "hibernation entry; WD2 backstop FAILED" - : "hibernation entry; WD2 backstop armed, about to snapshot/write"); - } + hibernation_backstop_arm("entry"); pm_prepare_console(); error = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION); if (error) @@ -1257,7 +1231,7 @@ int hibernate(void) * test resume. After a real restore the watchdog's restore callback * has already disarmed the backstop. */ - apple_wdt_disarm_hibernation_backstop(); + hibernation_backstop_disarm(); unlock_system_sleep(sleep_flags); pr_info("hibernation exit\n"); @@ -1434,8 +1408,6 @@ static int software_resume(void) } pr_info("resume from hibernation\n"); - hibernation_write_crumb( - "image found; will load, then arm WD2 backstop before jump"); pm_prepare_console(); error = pm_notifier_call_chain_robust(PM_RESTORE_PREPARE, PM_POST_RESTORE); if (error) From 2e90d6645e2c6516368e9834ac929deff6ce9a22 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 17:21:28 +0100 Subject: [PATCH 099/140] drm/asahi: wrap a long safety comment in the window-table copy Keep the line within 100 columns. Signed-off-by: fbalazsy --- drivers/gpu/drm/asahi/mmu.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 631167415bdb4..2704abfa56945 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4574,7 +4574,8 @@ impl Uat { (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. + // 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); From 71b0ba3f7441e32bdb9476181aa2955c3a30badb Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 17:21:28 +0100 Subject: [PATCH 100/140] soc: apple: aop: wrap three long lines in the resume-from-disk path Keep them within 100 columns, as rustfmt lays them out. Signed-off-by: fbalazsy --- drivers/soc/apple/aop.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 1a5c7a676fea8..0bbfff670682c 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -1787,7 +1787,11 @@ impl AopData { 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), + Err(e) => dev_warn!( + self.dev, + "firmware shutdown before the image unconfirmed ({:?})\n", + e + ), } self.rtkit.lock().as_mut().set(Some(rtkit)); } @@ -2298,7 +2302,11 @@ impl AopData { 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)), + ( + r[0].load(CoreOrd::Relaxed), + r[1].load(CoreOrd::Relaxed), + r[2].load(CoreOrd::Relaxed), + ), GFP_KERNEL, )?; } @@ -2492,7 +2500,11 @@ impl AopData { 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) + 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); From 33502d57eb81af8719addc745423d22b262e0198 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 17:21:28 +0100 Subject: [PATCH 101/140] iommu: apple-dart: join a condition split against its parenthesis It fits on one line. Signed-off-by: fbalazsy --- drivers/iommu/apple-dart.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index a5e3420b2384f..bb059fc931663 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -1367,8 +1367,7 @@ static int apple_dart_publish_root(const struct apple_dart *dart, if (adopt && next) { if (apple_dart_fw_slot_owned(fw, live, i) && - apple_dart_fw_slot_mirrors(dart, fw, next, i, - entries)) { + apple_dart_fw_slot_mirrors(dart, fw, next, i, entries)) { fw->accepted[i] = next; continue; } From 2867c103dbcf79a436ccf3a66fb355970bee1181 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 17:38:22 +0100 Subject: [PATCH 102/140] drm/asahi: g17: leave the firmware running across the hibernation image .freeze stopped the firmware for the image: told to idle, its mailbox off and its CPU stopped. Once a kernel started it, the firmware does not start again before a reboot, neither warm nor cold, and every hibernation goes on in the hibernating kernel once the image is taken. The GPU was lost for the rest of the boot after an image that is not written, and on the hibernating kernel while the image is written. Leave it running and idle instead: .freeze closes publication and waits for quiet as before, and .thaw reopens publication. The restored kernel boots the firmware the boot loader staged; before that cold boot it closes the mailboxes and marks the CPUs stopped, as the image still holds the books of the firmware that ran when it was taken. Signed-off-by: fbalazsy --- drivers/gpu/drm/asahi/g17/sleep.rs | 55 +++++++++++++----------------- 1 file changed, 24 insertions(+), 31 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index a5dc31bd2b5bb..429c0dcc969f7 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -727,31 +727,21 @@ impl super::Gpu { } impl Firmware { - /// Stops the firmware for a hibernation image, from a process context: each instance is told - /// to idle and its acknowledgments are waited for, its mailbox goes off and its CPU stops, - /// then the domain is lowered as for a sleep. Told to idle, the firmware can't carry on, so - /// the stop goes on whatever an instance answers. - fn hib_stop(&mut self) { - let shared = self.primary.state.shared.clone(); + /// 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; }; - // An instance asleep with its memory kept answers EALREADY: as good as idle here. - match coprocessor.rtkit.with(|rtkit| rtkit.idle()) { - Ok(()) | Err(EALREADY) => {} - Err(error) => { - dev_warn!(shared.dev.as_ref(), "GPU firmware {:?} idle: {:?}\n", role, error) - } - } - // SAFETY: The instance was told to idle; a restart or a cold boot follows. + // SAFETY: Nothing runs on this instance; a cold boot follows. coprocessor .rtkit .with(|rtkit| unsafe { bindings::apple_rtkit_mailbox_off(rtkit.as_raw()) }); - coprocessor.stop(); + coprocessor.stopped_at_commit(); } - // The domain stays up with its request: the PMP still runs until the image is written, - // and reads the GPU's registers while it does. } /// Boots the firmware cold on this session's objects, on a restored image. The boot that @@ -964,9 +954,10 @@ impl Shared { .is_some_and(|firmware| firmware.hib.is_some()) } - /// Closes publication, waits for quiet and stops the firmware; `tables` is filled at the last - /// step before the image. A refusal changes nothing; a device already lost has nothing to - /// carry and doesn't refuse. + /// 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); @@ -987,7 +978,6 @@ impl Shared { if !firmware.sleep_quiet(super::now_ns())? { return Err(EBUSY); } - firmware.hib_stop(); firmware.hib = Some(tables); Ok(()) }); @@ -1015,14 +1005,14 @@ impl Shared { } } - /// The image is written or the hibernation failed: the firmware's memory is as it left it. + /// 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() { - let _ = self.sleep_up(); + self.sleep_cancel(false); } } @@ -1035,14 +1025,17 @@ impl Shared { 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_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(); - }), + 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), From fb2029d53b399a6cbeb5a4fd2c8918d111705b03 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 17:38:22 +0100 Subject: [PATCH 103/140] dmaengine: apple-sio: leave the firmware running across the hibernation image .freeze stopped the firmware for the image and .thaw reset the engine and booted it again as on a restored kernel. The firmware takes its start message, then refuses the device tree parameters with -ENXIO, and stays down for the rest of the boot after an image that is not written. On the hibernating kernel, leave the firmware as runtime PM has it: .freeze refuses a busy channel and suspends as for a sleep, and .thaw resumes the same way. The kernel that loads an image still stops it before the jump, so that the restored kernel boots it again once, as before; the image now holds the state of a running firmware, so the mailbox goes off first and runtime PM's stop is forgotten. Signed-off-by: fbalazsy --- drivers/dma/apple-sio.c | 50 +++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 044e30b85ef1c..b924f1e84ed4c 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -233,8 +233,6 @@ struct sio_hw_data { }; struct sio_data { - /* Stopped for a hibernation image: booted again at thaw or restore. */ - bool hib_stopped; const struct sio_hw_data *hw; void __iomem *base; struct dma_device dma; @@ -3457,16 +3455,18 @@ static int sio_restart_after_restore(struct sio_data *sio) } /* - * Hibernation: the firmware stops before the image is taken, so that nothing it writes lands - * after the snapshot, and again before the power goes off. A busy channel or a refused stop - * refuses the hibernation, the firmware still running. + * 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. The + * kernel that loads an image stops it before the jump, so that the restored kernel can boot it + * again. */ 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 || sio->hib_stopped) + if (sio->hw->commit_stop) return sio_system_suspend(dev); for (i = 0; i < sio->nchannels; i++) { if (sio_chan_busy(&sio->channels[i])) { @@ -3474,64 +3474,60 @@ static __maybe_unused int sio_hib_freeze(struct device *dev) 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_sleep_stop(sio->rtk, sio->base + REG_CPU_CONTROL); pm_runtime_put_noidle(dev); if (ret) { - dev_err(dev, "firmware did not stop for the hibernation: %d\n", ret); + dev_err(dev, "firmware did not stop before the image: %d\n", ret); return ret; } - sio->hib_stopped = true; - return sio_system_suspend(dev); + return 0; } -/* After the image is written, a failed hibernation or a restore: the firmware boots again. */ -static __maybe_unused int sio_hib_start(struct device *dev, bool restore) +/* + * 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. + */ +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; - if (!sio->hib_stopped && !restore) - return 0; ret = pm_runtime_resume_and_get(dev); if (ret < 0) return ret; + apple_rtkit_mailbox_off(sio->rtk); ret = sio_restart_after_restore(sio); pm_runtime_put(dev); if (ret) { dev_err(dev, "firmware not booted again after the hibernation: %d\n", ret); return 0; } - sio->hib_stopped = false; - dev_info(dev, "firmware booted again after the hibernation%s\n", - restore ? " restore" : ""); + dev_info(dev, "firmware booted again after the hibernation restore\n"); return 0; } -static __maybe_unused int sio_hib_thaw(struct device *dev) -{ - return sio_hib_start(dev, false); -} - -static __maybe_unused int sio_restore(struct device *dev) -{ - return sio_hib_start(dev, true); -} - static const struct dev_pm_ops sio_pm_ops = { .prepare = pm_sleep_ptr(sio_pm_prepare), .complete = pm_sleep_ptr(sio_pm_complete), .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_hib_thaw), + .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) From bd712da43272974a57bccca81ed09f491ccf4487 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 18:54:55 +0100 Subject: [PATCH 104/140] dt-bindings: watchdog: apple,wdt: Add the SMC AP deadline register On the T6041 generation the runtime watchdog of the application processor is a deadline the SMC compares with its own uptime: once the uptime passes the programmed value it resets the AP. That register sits next to the simple-reconfig routing register, outside the watchdog block, and replaces the WD2 route through it. Describe it as an optional third register, named "deadline". It is only meaningful together with "reconfig", which the item order enforces. Signed-off-by: fbalazsy --- Documentation/devicetree/bindings/watchdog/apple,wdt.yaml | 5 +++++ 1 file changed, 5 insertions(+) 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 From f30bd938a474103643621c2b6a7280cd32afb2d4 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 18:54:55 +0100 Subject: [PATCH 105/140] arm64: dts: apple: t604x: Describe the watchdog's reconfig and deadline registers The watchdog driver found the simple-reconfig register of this SoC in its match data and derived the SMC deadline from that address. Describe both registers in the watchdog node instead, as the T6050 DT already does for its reconfig register. Signed-off-by: fbalazsy --- arch/arm64/boot/dts/apple/t604x.dtsi | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t604x.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi index 4e25d040be20e..40c608cfdd3da 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 = ; From ffed007afccae7c62f9e02c2b4e4bd2428a27e4c Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 18:54:55 +0100 Subject: [PATCH 106/140] watchdog: apple: Take the reconfig and deadline registers from the DT The driver carried the physical address of the simple-reconfig register of three SoCs and a firmware version in its match data, used the address when the DT named no "reconfig" register, and derived the SMC deadline from it on version 2. Take both registers from the DT only. A "deadline" register next to "reconfig" now selects the SMC deadline route, so the per-SoC match entries, the version and the fixed offset go away. SoCs whose DT has no "reconfig" register keep the legacy WD1 path, as before the match data was added. Rewrite the comment on the reset routes in terms of the hardware. Signed-off-by: fbalazsy --- drivers/watchdog/apple_wdt.c | 135 ++++++++++------------------------- 1 file changed, 38 insertions(+), 97 deletions(-) diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 054b9c739b141..45e45c1852783 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -31,29 +31,22 @@ * reconfig register, WD1 triggers a normal machine reset via * APPLE_WDT_CTRL_RESET_EN when CUR_TIME >= BITE_TIME. * - * On SoCs with simple-reconfig-wdog-support the runtime reset path depends - * on firmware wdt-version (AppleARMWatchdogTimer): + * On SoCs with a "reconfig" routing register the runtime reset path depends + * on the generation: * - * version 2 (t6041): the AP watchdog is the SMC deadline at - * aon-misc+0x08 (wdt reg[2], AON_AP_DEADLINE). Firmware - * _armWatchdogMechanism writes (continuous time + timeout) in - * seconds. The SMC 1 s timer enters the AP-watchdog-logger when SMC - * uptime > deadline - 1, then bites the AP WDT block (PMU reset_in_1). - * A write of 0 disarms (the SMC and Linux sleep.c both zero it). - * WD2 bark is the sleep/ICC reconfig path (enableAONWatchdogForReconfig), - * not the runtime cold-reset route. + * 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. * - * version > 2: _armWatchdogMechanism programs WD2 bark (IRQ_EN, BITE - * unused) and _writeApWatchdogConfiguration sets reconfig bit 4 - * (bits 5:4 = 01) as the runtime route. + * Without one (t6050 and later): WD2 bark (IRQ_EN, BITE unused) with + * reconfig bits 5:4 = 01 is the runtime route. * - * _writeApWatchdogConfiguration replaces the low 8 bits of the reconfig - * register: bit 0 = halt-on-expiration, bit 3 if !AWL, bit 4 only when - * version > 2. Linux never sets the halt bit. - * - * AON_AP_DEADLINE is aon-misc+0x08 and AON_WDT_SLEEP / reconfig is - * aon-misc+0x2c, so deadline_pa = reconfig_pa - 0x24. That layout is - * already used by the sleep driver; it is not a T6040 special case. + * 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. @@ -80,8 +73,7 @@ #define APPLE_WDT_CTRL_RESET_EN BIT(2) /* - * Reconfig (aon-misc+0x2c) low-8-bit policy from - * AppleARMWatchdogTimer::_writeApWatchdogConfiguration. Bits 8+ are + * 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 @@ -90,10 +82,7 @@ #define APPLE_WDT_RECONFIG_MASK GENMASK(5, 4) #define APPLE_WDT_RECONFIG_WD2 BIT(4) -/* aon-misc+0x2c minus aon-misc+0x08 */ -#define APPLE_WDT_DEADLINE_OFF_FROM_RECONFIG 0x24 - -/* ~40 ms bark delay before version>2 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 @@ -109,37 +98,11 @@ struct apple_wdt { struct watchdog_device wdd; void __iomem *regs; void __iomem *reconfig; - void __iomem *deadline; /* AON_AP_DEADLINE, wdt-version 2 */ + void __iomem *deadline; /* optional SMC AP deadline */ unsigned long clk_rate; - u8 wdt_version; bool hib_backstop; }; -/* - * Simple-reconfig physical address, used only when the DT has no named - * "reconfig" resource. Addresses are the AON_WDT_SLEEP / wdt-aux + 0x2c - * register already documented by the sleep driver for that SoC. - * wdt_version is the firmware wdt-version for that compatible (0 = unknown; - * keep the version>2 WD2 bark path). - */ -struct apple_wdt_match { - u64 reconfig_pa; - u8 wdt_version; -}; - -static const struct apple_wdt_match apple_wdt_t6041 = { - .reconfig_pa = 0x50833002c, - .wdt_version = 2, /* t6041, firmware wdt-version 2 */ -}; - -static const struct apple_wdt_match apple_wdt_t6050 = { - .reconfig_pa = 0x28833002c, -}; - -static const struct apple_wdt_match apple_wdt_t8142 = { - .reconfig_pa = 0x3882b802c, -}; - static unsigned int hibernation_restore_timeout = APPLE_WDT_HIBERNATION_RESTORE_TIMEOUT_DEFAULT; module_param(hibernation_restore_timeout, uint, 0644); @@ -155,7 +118,7 @@ static struct apple_wdt *to_apple_wdt(struct watchdog_device *wdd) static bool apple_wdt_use_smc_deadline(const struct apple_wdt *wdt) { - return wdt->deadline && wdt->wdt_version == 2; + return wdt->deadline; } static u32 apple_wdt_timeout_ticks(struct apple_wdt *wdt, unsigned int s) @@ -177,7 +140,7 @@ static void apple_wdt_write_ap_config(struct apple_wdt *wdt, u32 lo) static void apple_wdt_enable_reconfig(struct apple_wdt *wdt) { /* - * Version > 2: replace the low 8 bits with !AWL | bit 4, preserving + * 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. */ @@ -241,16 +204,13 @@ 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. */ - /* - * Disarm first and drain that write: while IRQ_EN is set the block - * ignores a CUR_TIME update, and a posted disarm is not enough. - * A sleep or hibernation restore has to re-program an already-running - * counter; the same sequence is used at start and at ping. - */ 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); @@ -269,7 +229,7 @@ static int apple_wdt_start(struct watchdog_device *wdd) struct apple_wdt *wdt = to_apple_wdt(wdd); /* - * Everyday systemd pings stay on WD1 for wdt-version 2. The SMC + * 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. @@ -517,21 +477,20 @@ static void apple_wdt_sleep_unregister(void *data) } static int apple_wdt_map_deadline(struct device *dev, struct apple_wdt *wdt, - u64 reconfig_pa) + const struct resource *res) { - u64 deadline_pa = reconfig_pa - APPLE_WDT_DEADLINE_OFF_FROM_RECONFIG; - - wdt->deadline = devm_ioremap(dev, deadline_pa, sizeof(u32)); + 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 %#llx (aon-misc+0x08, wdt-version %u)\n", - (unsigned long long)deadline_pa, wdt->wdt_version); + dev_info(dev, "SMC AP deadline at %pR\n", res); return 0; } /* - * The hibernation backstop: on wdt-version 2 the SMC AP deadline, on later - * versions WD2 on the simple-reconfig cold-reset route, for + * 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) @@ -612,8 +571,7 @@ static void apple_wdt_hib_unregister(void *data) static int apple_wdt_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; - struct resource *wdt_res, *reconfig_res; - const struct apple_wdt_match *match; + struct resource *wdt_res, *reconfig_res, *deadline_res; struct apple_wdt *wdt; struct clk *clk; u32 wdt_ctrl; @@ -627,10 +585,6 @@ static int apple_wdt_probe(struct platform_device *pdev) if (IS_ERR(wdt->regs)) return PTR_ERR(wdt->regs); - match = of_device_get_match_data(dev); - if (match) - wdt->wdt_version = match->wdt_version; - reconfig_res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "reconfig"); if (reconfig_res) { if (resource_size(reconfig_res) < sizeof(u32)) @@ -639,24 +593,14 @@ static int apple_wdt_probe(struct platform_device *pdev) resource_size(reconfig_res)); if (!wdt->reconfig) return -ENOMEM; - if (wdt->wdt_version == 2) { - ret = apple_wdt_map_deadline(dev, wdt, reconfig_res->start); - if (ret) - return ret; - } - } else if (match && match->reconfig_pa) { - wdt->reconfig = devm_ioremap(dev, match->reconfig_pa, - sizeof(u32)); - if (!wdt->reconfig) - return -ENOMEM; - dev_info(dev, - "simple-reconfig at %#llx (SoC match data)\n", - (unsigned long long)match->reconfig_pa); - if (wdt->wdt_version == 2) { - ret = apple_wdt_map_deadline(dev, wdt, match->reconfig_pa); - if (ret) - return ret; - } + } + + /* 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; } clk = devm_clk_get_enabled(dev, NULL); @@ -884,9 +828,6 @@ static const struct dev_pm_ops apple_wdt_pm_ops = { }; static const struct of_device_id apple_wdt_of_match[] = { - { .compatible = "apple,t6041-wdt", .data = &apple_wdt_t6041 }, - { .compatible = "apple,t6050-wdt", .data = &apple_wdt_t6050 }, - { .compatible = "apple,t8142-wdt", .data = &apple_wdt_t8142 }, { .compatible = "apple,t8103-wdt" }, { .compatible = "apple,wdt" }, {}, From e01cfe9e55925e82391305a8be9da92a59e944db Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 18:55:23 +0100 Subject: [PATCH 107/140] watchdog: apple: Keep the restore backstop running only across a hibernation The suspend callback returned early whenever the restore backstop was armed, and probe also marks a WD2 bark that is already running as that backstop. After such a probe every later system sleep left WD2 running unfed until the next hibernation cleared the flag. Give freeze and poweroff their own callback that leaves the backstop running and otherwise stops the watchdog like a suspend. A suspend to RAM always stops it again. Signed-off-by: fbalazsy --- drivers/watchdog/apple_wdt.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 45e45c1852783..8a1b077829f7f 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -780,16 +780,23 @@ static int apple_wdt_suspend(struct device *dev) if (wdt->reconfig && apple_sleep_wdt_active(dev)) return 0; - /* Leave a hibernation backstop ticking through snapshot, write, and reboot. */ - if (wdt->hib_backstop) - return 0; - if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) apple_wdt_stop(&wdt->wdd); return 0; } +/* 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 SMC AP * deadline armed on hibernation entry (and refreshed by the restore kernel) has @@ -821,9 +828,9 @@ static int apple_wdt_restore(struct device *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_suspend), + .freeze = pm_sleep_ptr(apple_wdt_freeze), .thaw = pm_sleep_ptr(apple_wdt_resume), - .poweroff = pm_sleep_ptr(apple_wdt_suspend), + .poweroff = pm_sleep_ptr(apple_wdt_freeze), .restore = pm_sleep_ptr(apple_wdt_restore), }; From 2fd67f24966bdb0c44b281ce06e751ec97fc32a6 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 18:55:34 +0100 Subject: [PATCH 108/140] selftests: asahi: Follow the later hibernation changes in the host tests More harnesses stopped compiling or matching after the later hibernation changes: - apple-dart-fw, apple-dart-range, bcm4377-radio-sids: the deferred DART restore and the adopt argument of the root publication and of the stream sync. Stub the deferred restore as not pending, and add an adopt-foreign case that takes over a slot the boot loader refilled. - apple-wdt: the backstop, its timebase and the PM ops table. Mock them, expect the replaced low reconfig byte, keep the DT timeout where a running WD2 is adopted, check the backstop is dropped with the device, and follow the drained disarm in the mutations. An old revision still compiles. - bcm4377-resume, bcm4377-state-wait: the restore rebind is no failure, and the suspend body moved to __bcm4377_suspend(). - display26: the PMP bridge looks up its DART for the restore. - apple-dcp boot and readiness: the start ready-wait from match data. - g15-probe-init, g17-admission, g17-compute, g17-resource, mmu-retention: the boot-memory init, the packed queue count, the firmware-outlived check, the probe QID floor and the live-leaf check after an unmap. - t8132-sleep-refuse: the lost-mailbox refusal. No driver change. Signed-off-by: fbalazsy --- tools/asahi/apple-dart-fw-tests.py | 2 +- tools/asahi/apple-dart-fw/fixture.c | 17 ++-- tools/asahi/apple-dart-range-tests.py | 6 +- tools/asahi/apple-wdt-tests.py | 94 ++++++++++++++----- tools/asahi/bcm4377-resume-tests.py | 6 +- tools/asahi/bcm4377-resume/fixture.h | 4 +- tools/asahi/display26-tests.py | 8 +- tools/asahi/g15-probe-init-tests.py | 4 + tools/asahi/g17-admission-deadline-tests.py | 1 + tools/asahi/g17-compute-deadline-tests.py | 6 +- tools/asahi/g17-resource-tests.py | 2 +- tools/asahi/t8132-sleep-refuse-tests.c | 2 +- .../drivers/apple/bcm4377-radio-sids.py | 5 +- .../drivers/apple/bcm4377-state-wait.py | 2 + .../selftests/drivers/gpu/apple-dcp/boot.py | 2 + .../drivers/gpu/apple-dcp/lifecycle.py | 2 +- .../gpu/asahi-m4/test-mmu-retention.py | 4 +- 17 files changed, 118 insertions(+), 49 deletions(-) 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 df0327f757ede..8630a404a94fa 100644 --- a/tools/asahi/apple-dart-fw/fixture.c +++ b/tools/asahi/apple-dart-fw/fixture.c @@ -131,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) @@ -342,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 a6016ee862194..b0ab89b08c21a 100755 --- a/tools/asahi/apple-wdt-tests.py +++ b/tools/asahi/apple-wdt-tests.py @@ -53,7 +53,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] @@ -83,6 +89,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' @@ -94,6 +101,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' @@ -119,21 +127,19 @@ def apply_mutation(body, t6050_helpers, mutation): '\tif (wdt->reconfig) {\n' + reg_block + '\t}\n\treturn 0;') return mut, t6050_helpers if mutation == 'hwrunning-after-arm': - old = ('\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);\n' - '\t\t\tapple_wdt_wd2_arm(wdt,\n' - '\t\t\t\t\t apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout));') + 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' @@ -197,6 +203,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; @@ -515,6 +547,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''' @@ -690,8 +724,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 */ @@ -701,10 +737,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); @@ -717,7 +754,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); @@ -751,7 +788,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); @@ -762,7 +799,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); @@ -792,7 +829,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); @@ -829,7 +866,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)); @@ -841,16 +878,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 */ @@ -863,7 +902,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)); @@ -878,7 +917,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); @@ -908,7 +947,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)); @@ -997,6 +1036,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/bcm4377-resume-tests.py b/tools/asahi/bcm4377-resume-tests.py index 7fd03019fca8c..c8947a32b2af1 100755 --- a/tools/asahi/bcm4377-resume-tests.py +++ b/tools/asahi/bcm4377-resume-tests.py @@ -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), } diff --git a/tools/asahi/bcm4377-resume/fixture.h b/tools/asahi/bcm4377-resume/fixture.h index 4a444f52be5f9..693964889c053 100644 --- a/tools/asahi/bcm4377-resume/fixture.h +++ b/tools/asahi/bcm4377-resume/fixture.h @@ -139,9 +139,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/display26-tests.py b/tools/asahi/display26-tests.py index 637b4357c38d8..1405246f27791 100644 --- a/tools/asahi/display26-tests.py +++ b/tools/asahi/display26-tests.py @@ -102,13 +102,17 @@ def main(): 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' - '#define PM_POST_HIBERNATION 2\n#define PM_POST_RESTORE 6\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' @@ -189,6 +193,8 @@ def main(): 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); diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py index 04e344f6f3144..6f60568cdd136 100644 --- a/tools/asahi/g15-probe-init-tests.py +++ b/tools/asahi/g15-probe-init-tests.py @@ -157,6 +157,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-compute-deadline-tests.py b/tools/asahi/g17-compute-deadline-tests.py index fb3585ea7ec90..a6e7250ae63a0 100644 --- a/tools/asahi/g17-compute-deadline-tests.py +++ b/tools/asahi/g17-compute-deadline-tests.py @@ -87,12 +87,12 @@ 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{Ok(())}fn cancel_requested(&self)->bool{now_ns()>=CANCEL.load(Ordering::SeqCst)}fn is_published(&self)->bool{false}} struct DeferredBatch;impl DeferredBatch{fn publication()->Result{Ok(Self)}fn finish(&mut self){}} struct Recovery;impl Recovery{fn pending(&self)->bool{MODE.load(Ordering::SeqCst)==1}} 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{ @@ -151,7 +151,7 @@ def fixture(): } fn main(){ let b=Backend{owner:1,context:Context,compute_channels:1,sibling_backoff_until:AtomicU64::new(0),shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; - let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion,order:Order{wait_through:[None,None]}}); + 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); diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index 31d24d19afee2..0dca6e4609e5f 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/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/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 eac1006961ce7..db9618cf12b7b 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py @@ -50,6 +50,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 struct pci_dev *pci_dev_get(struct pci_dev *p) { p->refs++;return p; } static void queue_work(void *q, struct work_struct *w) { diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 8d067976f7e33..654841cad046a 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -427,6 +427,8 @@ def v27_panel_handoff(root): u8 firmware_dma_bits; /* Set in the T6030/T6031 profiles, not read by dcp_apply_dt_profile(). */ bool afk_name_fallback, v27_early_stop, only_120hz_modes; + /* Read by the DRM start's ready wait, not by dcp_apply_dt_profile(). */ + unsigned int ready_timeout_ms; const struct dcp_s2r_layout *s2r_layout; }; struct apple_dcp { diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index d44912302b7d6..4ceba837f2434 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1610,7 +1610,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/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index 8b39a4ce54783..acfdfe6c8e4f4 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>} From c492ab28843849fb2f82ab00b506fd5c72858e05 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 19:32:44 +0100 Subject: [PATCH 109/140] dmaengine: apple-sio: boot the firmware after a restore only if staged After a resume from disk the restored kernel reset the SIO and booted its firmware again. When the kernel that loaded the image had started that firmware, it answers the handshake and the start message, then refuses the first boot parameter (-ENXIO on the panic buffer), and the SIO stays down for the rest of the boot: a firmware that a kernel has started does not take a second boot before the next reboot, and an engine reset does not change that. Only firmware that the boot loader staged and left halted can be booted. So: - the kernel that loads an image and has started the firmware idles it and turns its mailbox off before the jump, but leaves its run bit set; - the restored kernel boots the firmware as probe does, without the engine reset, when the run bit is clear, and otherwise leaves the SIO off until the next boot (its channels return -EIO) with one warning instead of a failed boot. A kernel that does not bind the SIO before it loads the image (the SIO has no users there) leaves the firmware staged, and the restored kernel gets its DMA back. Signed-off-by: fbalazsy --- drivers/dma/apple-sio.c | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index b924f1e84ed4c..d96b2469d7b70 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -3405,20 +3405,14 @@ static __maybe_unused int sio_resume_early(struct device *dev) } /* - * After a hibernation restore the firmware runs as the boot that loaded the image started it, - * with that kernel's buffers and parameters. Reset the engine and boot the firmware again as - * probe does, on this kernel's buffers. The channels are idle: user space was frozen. + * 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_sleep_engine_reset(sio->dev); - if (err) { - dev_err(sio->dev, "engine reset after the hibernation: %d\n", err); - return err; - } err = apple_rtkit_reinit(sio->rtk); if (err) return err; @@ -3457,9 +3451,12 @@ static int sio_restart_after_restore(struct sio_data *sio) /* * 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. The - * kernel that loads an image stops it before the jump, so that the restored kernel can boot it - * again. + * 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) { @@ -3480,12 +3477,14 @@ static __maybe_unused int sio_hib_freeze(struct device *dev) ret = pm_runtime_resume_and_get(dev); if (ret < 0) return ret; - ret = apple_rtkit_sleep_stop(sio->rtk, sio->base + REG_CPU_CONTROL); - pm_runtime_put_noidle(dev); + ret = apple_rtkit_idle(sio->rtk); if (ret) { - dev_err(dev, "firmware did not stop before the image: %d\n", 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; } @@ -3494,7 +3493,8 @@ static __maybe_unused int sio_hib_freeze(struct device *dev) * 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. + * 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) { @@ -3510,9 +3510,16 @@ static __maybe_unused int sio_restore(struct device *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; } From 7a1180655d5453133092070067aee52e2a586664 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 19:32:44 +0100 Subject: [PATCH 110/140] net: usb: r8152: treat -ESHUTDOWN like -ENODEV on tx and interrupt resubmission When the host controller is stopped under a bound interface, as for a hibernation, every tx URB and the interrupt URB resubmission fail with -ESHUTDOWN, and each failure is logged ("failed tx_urb -108", "can't resubmit intr, status -108") until the disconnect arrives. With netconsole on the interface every such line is another transmit that fails the same way. As for rx, no resubmission can succeed: mark the device unplugged and detach the netdev. Signed-off-by: fbalazsy --- drivers/net/usb/r8152.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/usb/r8152.c b/drivers/net/usb/r8152.c index ebfa83daa653a..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 { From 77aea2ca35d2655eb0d1300b3e45283d3f7ea4b5 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 19:19:24 +0700 Subject: [PATCH 111/140] soc: apple: dockchannel, HID: dockchannel: restore IRQ masks and guard receive after hibernation After a hibernation restore, DockChannel's hardware IRQ mask register holds what the loading kernel left (0 if unloaded) while the restored interrupt descriptors keep the image's state. Restore the unmasked IRQ bits in .restore_noirq before FIFO clients resume. In a restored kernel (pm_hibernate_is_restored()), re-program a stale receive threshold on below-threshold RX interrupts instead of waking a client with insufficient data, and re-arm receive in dchid_handle_packet() on a short wake or header read failure so keyboard and trackpad input do not stall. Signed-off-by: Nick Signed-off-by: fbalazsy --- drivers/hid/dockchannel-hid/dockchannel-hid.c | 8 +++ drivers/soc/apple/dockchannel.c | 69 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid.c b/drivers/hid/dockchannel-hid/dockchannel-hid.c index d4290e457d69f..c103d3f0ab966 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid.c @@ -1915,8 +1915,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)) { diff --git a/drivers/soc/apple/dockchannel.c b/drivers/soc/apple/dockchannel.c index 291d81d2df2fa..e968adf4a5e32 100644 --- a/drivers/soc/apple/dockchannel.c +++ b/drivers/soc/apple/dockchannel.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -60,6 +61,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); }; @@ -72,6 +77,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. @@ -112,10 +120,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; disable_irq_nosync(irq); if (dockchannel->awaiting) { @@ -192,6 +231,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); enable_irq(dockchannel->rx_irq); @@ -238,6 +278,7 @@ int dockchannel_await(struct dockchannel *dockchannel, dockchannel->data_available = callback; dockchannel->cookie = cookie; dockchannel->awaiting = true; + WRITE_ONCE(dockchannel->rx_thresh, threshold); dockchannel_writel(threshold, dockchannel->config_base + CONFIG_RX_THRESH); enable_irq(dockchannel->rx_irq); @@ -449,6 +490,33 @@ static void dockchannel_remove(struct platform_device *pdev) 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 const struct of_device_id dockchannel_of_match[] = { { .compatible = "apple,dockchannel" }, {}, @@ -459,6 +527,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, From c6f9db9bc6312748fdac5ef4a55085e44dbcdf3a Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 08:53:25 +0700 Subject: [PATCH 112/140] soc/apple: rtkit: restore mailbox hardware enables on reinit apple_rtkit_reinit() and apple_rtkit_reinit_retaining_buffers() call apple_mbox_start(), which returns early without touching hardware when mbox->active is already set in a restored hibernation image. Follow apple_mbox_start() with apple_mbox_restore() so mailboxes with hardware enable or IRQ control bits re-enable them before the firmware boots. Signed-off-by: Nick Signed-off-by: fbalazsy --- drivers/soc/apple/rtkit.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index 7cacb76a88dbd..0f1168ce50ab3 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2838,6 +2838,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); @@ -2852,6 +2854,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); From 5f4a9facdab36fc5c264f5fefe1f2d6d29437b54 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 19:58:56 +0100 Subject: [PATCH 113/140] selftests: asahi: rtkit-oslog: Stub apple_mbox_restore() apple_rtkit_reinit() now restores the mailbox after starting it. Give the fixture a stub for it, as it has for apple_mbox_start(). Signed-off-by: fbalazsy --- tools/asahi/rtkit-oslog-tests.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/asahi/rtkit-oslog-tests.py b/tools/asahi/rtkit-oslog-tests.py index 944e07c67b887..b9b18aae9b495 100644 --- a/tools/asahi/rtkit-oslog-tests.py +++ b/tools/asahi/rtkit-oslog-tests.py @@ -88,6 +88,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, From e7d08ba0e304ffceed79c2be6e491e444b324659 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 20:51:15 +0100 Subject: [PATCH 114/140] usb: hub: stop resetting a port once its host controller is gone When the host controller goes away while a device below a hub is being reset (the UAS error handler resets the device after a command that failed because the controller is being removed), every port reset request fails with -ESHUTDOWN. hub_port_reset() logs each try and retries, and usb_reset_and_verify_device() repeats the whole sequence, so a device that is already gone produces dozens of "cannot reset (err = -108)", "Cannot enable" and "cannot disable" lines. Treat -ESHUTDOWN like -ENODEV in these paths: the controller does not come back for this device. Signed-off-by: fbalazsy --- drivers/usb/core/hub.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) 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); From 8d5d52f55c0d50b6859e4688fff28d9ab0a95c3e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Thu, 3 Dec 2026 20:51:15 +0100 Subject: [PATCH 115/140] HID: dockchannel: resynchronise the receive ring after a restore from disk The boot kernel of a resume from disk hands the running MTP firmware to the image. The receive ring indices in memory are then the image's, while the firmware carries on from the position of the boot kernel's session, so the first drain after the restore fails with -EPROTO and the frames in between are lost ("Receive ring failed: -71"). Mark the ring on restore and, on the first drain that does not add up, drop everything up to the producer the firmware published last and go on from there. A drain that reads a frame clears the mark. Signed-off-by: fbalazsy --- drivers/hid/dockchannel-hid/dockchannel-hid.c | 56 ++++++++++++++++++- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid.c b/drivers/hid/dockchannel-hid/dockchannel-hid.c index c103d3f0ab966..7adb945141a6c 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid.c @@ -249,6 +249,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]; @@ -1901,11 +1907,39 @@ static int dchid_drain_ring(struct dockchannel_hid *dchid) /* 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 void dchid_handle_packet(void *cookie, size_t avail) { struct dockchannel_hid *dchid = cookie; @@ -1938,6 +1972,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); } @@ -2319,8 +2355,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" }, From 37e46a21a834176c373d4b2a467618aec9c2472e Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 01:24:38 +0700 Subject: [PATCH 116/140] irqchip/apple-aic: restore global config and boot CPU FIQ on cold hibernation pm_hibernate_restored_cold() is already set before syscore_resume() runs in create_image(), yet aic_syscore_resume() only restored AIC2_TIMEOUT, AIC2_CLUSTER_PRIO, AIC2_CONFIG, and aic_resume_boot_cpu() for pm_resume_via_firmware(). Include pm_hibernate_restored_cold() so CPU 0's VM timer FIQ mask stays synchronized with per-CPU state after a cold hibernation restore. In apple-sleep, also clear mbox_lost once a valid S2R mailbox is re-mapped on restore and re-validate if mbox_lost was previously set. Signed-off-by: Nick (cherry picked from commit 388fdad4bc2d0229bb4bab12d77ca8b768b66842) Signed-off-by: fbalazsy --- drivers/irqchip/irq-apple-aic.c | 8 ++++++-- drivers/soc/apple/sleep.c | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index 747b87a99d622..76774ffa4c22a 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -1354,8 +1354,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); diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 93672eaaafce6..cdcb4af925d91 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -8215,7 +8215,7 @@ static int apple_sleep_restore(struct device *dev) dev_err(dev, "no S2R mailbox of this boot (%d): deep sleep off\n", ret); goto lost; } - if (pa == s->mbox_pa) + if (pa == s->mbox_pa && !s->mbox_lost) return 0; mbox = devm_memremap(dev, pa, sizeof(*mbox), MEMREMAP_WB); @@ -8236,6 +8236,7 @@ static int apple_sleep_restore(struct device *dev) 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; From 26cff0f05dc59aa560c85558a32ce444a350031a Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 01:05:13 +0700 Subject: [PATCH 117/140] soc: apple: restore cluster power gates and MCC cache allocation after cold hibernation After a cold hibernation restore, the boot ROM leaves the boot CPU's cluster power-gate word clear (preventing CPU 0's cluster from gating and causing subsequent suspend-to-RAM to hang in the sleep sequencer), and iBoot leaves MCC system-level cache allocation disabled. - apple-cluster-pwrgate: retain the mapped gate registers and register a syscore resume callback to re-set CLUSTER_PWRGATE_EN before secondary CPUs online. - apple-mcc: add .restore_noirq to restore ways and re-enable system level cache allocation on cold hibernation restore. Signed-off-by: Nick (cherry picked from commit 738126b53beba12d6f84df6230573aac9c378271) Signed-off-by: fbalazsy --- drivers/soc/apple/apple-cluster-pwrgate.c | 40 +++++++++++++++++++++ drivers/soc/apple/mcc.c | 44 ++++++++++++++++++++++- 2 files changed, 83 insertions(+), 1 deletion(-) 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/mcc.c b/drivers/soc/apple/mcc.c index fb2f8a6376246..c33c762de865e 100644 --- a/drivers/soc/apple/mcc.c +++ b/drivers/soc/apple/mcc.c @@ -661,8 +661,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[] = { From e5b21606f8620820c6d68ea8e46a782cf11f7ba8 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 00:47:57 +0700 Subject: [PATCH 118/140] cpufreq/power: apple: restore DVFS state and battery charge limit after cold hibernation In apple-soc-cpufreq, refresh expected_pstate from APPLE_DVFS_CMD after a cold hibernation restore (pm_hibernate_restored_cold()) just like firmware-driven sleep, and restart the fast die-temperature grace timer on hibernation restore while PMP re-initializes in PM_POST_HIBERNATION. In macsmc-power, save CHLS/CHWA on freeze/poweroff and restore the charge limit on cold hibernation restore so standard hibernation preserves the configured battery charge limit without userspace help. Signed-off-by: Nick (cherry picked from commit cc5ba7f64180ee4e942f763bb6b963c718dd9ebb) Signed-off-by: fbalazsy --- drivers/cpufreq/apple-soc-cpufreq.c | 21 +++++++--- drivers/power/supply/macsmc-power.c | 65 +++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 5 deletions(-) diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index 066b12a2493e9..4e0c350851312 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -1750,10 +1750,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) { @@ -1761,7 +1762,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); diff --git a/drivers/power/supply/macsmc-power.c b/drivers/power/supply/macsmc-power.c index c24ff5881206c..6fe6d21321c49 100644 --- a/drivers/power/supply/macsmc-power.c +++ b/drivers/power/supply/macsmc-power.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -132,6 +133,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); @@ -1396,7 +1405,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), }; From 9b547702505b257fbfa2ec3db9d6eaaae4254729 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 00:46:47 +0700 Subject: [PATCH 119/140] PM: apple: add system sleep and hibernation restore for I2C, SPI, and PWM Three Apple peripheral bus drivers lacked system sleep / hibernation restore coverage for registers lost across a cold reboot: - i2c-pasemi-platform: add LATE_SYSTEM_SLEEP_PM_OPS using pm_runtime_force_suspend/resume so buses that were runtime-active at freeze re-run pasemi_i2c_init() in restore_early before I2C clients (such as audio codecs and speaker amplifiers) issue restore transfers. - spi-apple: add runtime_resume calling apple_spi_init() and system sleep callbacks wrapping spi_controller_suspend/resume with pm_runtime_force_suspend/resume so SPI buses re-initialize PIN/CFG registers after domain power loss or cold hibernation restore. - pwm-apple: add LATE_SYSTEM_SLEEP_PM_OPS using pm_runtime_force_suspend/resume so active PWM outputs (keyboard backlight) restore ON_CYCLES/OFF_CYCLES/CTRL after cold reboot, and set APPLE_PWM_CTRL_UPDATE when re-enabling to latch shadowed cycles. Signed-off-by: Nick (cherry picked from commit af9bdf6c452bde4fa320928e06c7fdb84ad8f508) Signed-off-by: fbalazsy --- drivers/i2c/busses/i2c-pasemi-platform.c | 9 +++-- drivers/pwm/pwm-apple.c | 6 +++- drivers/spi/spi-apple.c | 45 ++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 4 deletions(-) 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/pwm/pwm-apple.c b/drivers/pwm/pwm-apple.c index d2ac662553290..5fcb6ac377944 100644 --- a/drivers/pwm/pwm-apple.c +++ b/drivers/pwm/pwm-apple.c @@ -151,7 +151,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; } @@ -169,6 +171,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/spi/spi-apple.c b/drivers/spi/spi-apple.c index 0f7d5d7b156df..d584f8196f144 100644 --- a/drivers/spi/spi-apple.c +++ b/drivers/spi/spi-apple.c @@ -724,6 +724,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) @@ -738,6 +740,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", }, @@ -750,6 +794,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); From a3b8732cc8142d1bfc1fe7efac4ff8f00fc7a0dd Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 00:45:31 +0700 Subject: [PATCH 120/140] PCI: apple-msi: restore MSI doorbell and map after cold hibernation On cold hibernation restore the bootloader re-trains the PCIe port without programming PORT_MSIADDR, PORT_MSIMAP, or PORT_MSICFG_EN. Add a .restore_noirq callback that calls apple_msi_hw_init() when pm_hibernate_restored_cold() is set, before PCI devices resume and before any port cycle saves the MSI table. Signed-off-by: Nick (cherry picked from commit 9381eb6354de9d3a3e015aeb457667a4a9cd10e0) Signed-off-by: fbalazsy --- drivers/pci/controller/pcie-apple-msi.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) 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) From 46c4d3c1e95ff10fdab03a2b6be688d0f0795bfe Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 20:15:43 +0700 Subject: [PATCH 121/140] thunderbolt: apple: clear keep-alive quirks on cold hibernation restore After a cold hibernation restore, the boot loader has reset the CIO controller and host router. Add .restore_noirq that clears any QUIRK_NO_SYSTEM_SLEEP and QUIRK_KEEP_TUNNELS flags left from an earlier s2idle when pm_hibernate_restored_cold() is true, so tb_domain_resume_noirq() restarts the NHI rings cleanly. Signed-off-by: Nick (cherry picked from commit 2b71613475248c3a8cc75bf62549941d262ebe7a) Signed-off-by: fbalazsy --- drivers/thunderbolt/apple.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 429cfa75e93bb..524e0f5911325 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -3354,6 +3354,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); @@ -3389,7 +3405,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, From c502a77976ea044ad9cee5c86a4e47fc161d8e4f Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 20:14:55 +0700 Subject: [PATCH 122/140] soc: apple-sep: trigger hibernation rebind only on cold restore An in-place test_resume sets pm_hibernate_is_restored() without restarting the enclave. Gate the hibernation rebind phase on pm_hibernate_restored_cold() so test_resume keeps the live SEP session while real cold restores still rebind the driver. Signed-off-by: Nick (cherry picked from commit abc4e033718fd1afb223fc5c7b8e3edc41a6af1a) Signed-off-by: fbalazsy --- drivers/soc/apple/pm_shim.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index c34f833cda94c..0fbb76a819857 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -90,14 +90,15 @@ static int sep_pm_notify(struct notifier_block *nb, unsigned long action, return NOTIFY_OK; case PM_POST_HIBERNATION: /* - * After a restored image 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. + * 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_is_restored()) + if (hib && pm_hibernate_restored_cold()) hib(2); event(false); sep_diag_sleep(false); - if (hib && !pm_hibernate_is_restored()) + if (hib && !pm_hibernate_restored_cold()) hib(1); return NOTIFY_OK; case PM_POST_SUSPEND: From 21b58c4d5355a349bd2ce9f626a6f986dd6487a7 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 20:14:42 +0700 Subject: [PATCH 123/140] dmaengine: apple-admac: mark channels lost on cold hibernation restore admac_resume_early() only marks controller and channel register state lost when pm_suspend_via_firmware() is true. Add .restore_early that marks them lost when pm_hibernate_restored_cold() is true so active audio DMA channels are cleanly reprogrammed after a cold boot. Signed-off-by: Nick (cherry picked from commit 23d1f70d298b589b02ef01ee42a1650dcd49cf49) Signed-off-by: fbalazsy --- drivers/dma/apple-admac.c | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) 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) }; From 6730a210cff2006fbbc5cc83a06ec1eaaecdff8f Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 20:14:39 +0700 Subject: [PATCH 124/140] clk: apple-nco: save and restore channel state across hibernation Cold boot resets the NCO audio clock channels while MCA and ASoC resume expect enabled channels to keep their programmed divisor and increments. Save each channel's control, divisor, and increment registers on .freeze_noirq/.poweroff_noirq and reprogram them on .restore_noirq when pm_hibernate_restored_cold() is true. Signed-off-by: Nick (cherry picked from commit 4edc6aa0ea259662e5ab610baf78515c533c33ab) Signed-off-by: fbalazsy --- drivers/clk/clk-apple-nco.c | 86 +++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/drivers/clk/clk-apple-nco.c b/drivers/clk/clk-apple-nco.c index 434c067968bbc..98d5fcbdab0d1 100644 --- a/drivers/clk/clk-apple-nco.c +++ b/drivers/clk/clk-apple-nco.c @@ -16,6 +16,7 @@ #include #include #include +#include #define NCO_CHANNEL_STRIDE 0x4000 #define NCO_CHANNEL_REGSIZE 20 @@ -70,6 +71,18 @@ struct applnco_channel { struct clk_hw hw; spinlock_t lock; +#ifdef CONFIG_HIBERNATION + u32 saved_ctrl; + u32 saved_div; + u32 saved_inc1; + u32 saved_inc2; + bool saved_valid; +#endif +}; + +struct applnco_data { + unsigned int nchannels; + struct applnco_channel **channels; }; #define to_applnco_channel(_hw) container_of(_hw, struct applnco_channel, hw) @@ -260,6 +273,7 @@ static int applnco_probe(struct platform_device *pdev) struct clk_parent_data pdata = { .index = 0 }; struct clk_init_data init; struct clk_hw_onecell_data *onecell_data; + struct applnco_data *nco; void __iomem *base; struct resource *res; struct applnco_tables *tbl; @@ -275,6 +289,15 @@ static int applnco_probe(struct platform_device *pdev) nchannels = (resource_size(res) - NCO_CHANNEL_REGSIZE) / NCO_CHANNEL_STRIDE + 1; + nco = devm_kzalloc(&pdev->dev, sizeof(*nco), GFP_KERNEL); + if (!nco) + return -ENOMEM; + nco->channels = devm_kcalloc(&pdev->dev, nchannels, + sizeof(*nco->channels), GFP_KERNEL); + if (!nco->channels) + return -ENOMEM; + nco->nchannels = nchannels; + onecell_data = devm_kzalloc(&pdev->dev, struct_size(onecell_data, hws, nchannels), GFP_KERNEL); if (!onecell_data) @@ -295,6 +318,7 @@ static int applnco_probe(struct platform_device *pdev) chan->base = base + NCO_CHANNEL_STRIDE * i; chan->tbl = tbl; spin_lock_init(&chan->lock); + nco->channels[i] = chan; memset(&init, 0, sizeof(init)); init.name = devm_kasprintf(&pdev->dev, GFP_KERNEL, @@ -315,10 +339,69 @@ static int applnco_probe(struct platform_device *pdev) onecell_data->hws[i] = &chan->hw; } + platform_set_drvdata(pdev, nco); + return devm_of_clk_add_hw_provider(&pdev->dev, of_clk_hw_onecell_get, onecell_data); } +#ifdef CONFIG_HIBERNATION +static int applnco_freeze_noirq(struct device *dev) +{ + struct applnco_data *nco = dev_get_drvdata(dev); + unsigned int i; + + for (i = 0; i < nco->nchannels; i++) { + struct applnco_channel *chan = nco->channels[i]; + unsigned long flags; + + spin_lock_irqsave(&chan->lock, flags); + chan->saved_ctrl = readl_relaxed(chan->base + REG_CTRL); + chan->saved_div = readl_relaxed(chan->base + REG_DIV); + chan->saved_inc1 = readl_relaxed(chan->base + REG_INC1); + chan->saved_inc2 = readl_relaxed(chan->base + REG_INC2); + chan->saved_valid = true; + spin_unlock_irqrestore(&chan->lock, flags); + } + return 0; +} + +static int applnco_restore_noirq(struct device *dev) +{ + struct applnco_data *nco = dev_get_drvdata(dev); + unsigned int i; + + if (!pm_hibernate_restored_cold()) + return 0; + + for (i = 0; i < nco->nchannels; i++) { + struct applnco_channel *chan = nco->channels[i]; + unsigned long flags; + + spin_lock_irqsave(&chan->lock, flags); + if (chan->saved_valid) { + writel_relaxed(chan->saved_ctrl & ~CTRL_ENABLE, + chan->base + REG_CTRL); + writel_relaxed(chan->saved_div, chan->base + REG_DIV); + writel_relaxed(chan->saved_inc1, chan->base + REG_INC1); + writel_relaxed(chan->saved_inc2, chan->base + REG_INC2); + writel_relaxed(1U << 31, chan->base + REG_ACCINIT); + if (chan->saved_ctrl & CTRL_ENABLE) + writel_relaxed(chan->saved_ctrl, + chan->base + REG_CTRL); + } + spin_unlock_irqrestore(&chan->lock, flags); + } + return 0; +} + +static const struct dev_pm_ops applnco_pm_ops = { + .freeze_noirq = applnco_freeze_noirq, + .poweroff_noirq = applnco_freeze_noirq, + .restore_noirq = applnco_restore_noirq, +}; +#endif + static const struct of_device_id applnco_ids[] = { { .compatible = "apple,t8103-nco" }, { .compatible = "apple,nco" }, @@ -330,6 +413,9 @@ static struct platform_driver applnco_driver = { .driver = { .name = "apple-nco", .of_match_table = applnco_ids, +#ifdef CONFIG_HIBERNATION + .pm = &applnco_pm_ops, +#endif }, .probe = applnco_probe, }; From e6bf32c0b1ec9500ed31523f158488ffad4c1b59 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 19:21:39 +0700 Subject: [PATCH 125/140] drm/apple: dcp: pause live-session DCP on freeze and preserve it across test_resume On live-session DCPs that cannot restart in place (such as T8142 v27), hold presentation and flush RTKit RX during .freeze/.poweroff and release them on .thaw. On an in-place test_resume (!pm_hibernate_restored_cold()), the boot loader never restarted the firmware, so thaw instead of marking the display dead. On a cold restore, mark both crashed and ext_dead so IOMFB traffic stops cleanly. Signed-off-by: Nick (cherry picked from commit 2ab4584f43fc399fa6d2b43cc34092774a88a71d) Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 4597961508540..bc45deb0668ac 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -14760,6 +14760,10 @@ static int dcp_platform_freeze(struct device *dev) 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; @@ -14788,6 +14792,7 @@ static int dcp_platform_thaw(struct device *dev) 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; /* @@ -14847,6 +14852,10 @@ static int dcp_platform_restore(struct device *dev) 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) @@ -14863,6 +14872,7 @@ static int dcp_platform_restore(struct device *dev) 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; } From 0393d6714ff35edb24084ebdb41bfbc596d5b179 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 19:19:21 +0700 Subject: [PATCH 126/140] accel/ane: H17: cycle the engine across hibernation as across suspend Like the H16 backend, the cold-cycling H17 ANE backend powers the engine off cleanly before sleep and boots the firmware again from the preload (or parks it until the next request) after wake. Nothing of the old firmware has to survive the transition, so map hibernation and restore PM notifier events to the suspend/post-suspend path when sleep_warm is false while keeping warm-sleep platforms refused. Extend ane_cold_sleep_test() to verify cold vs warm hibernation event mapping. Signed-off-by: Nick (cherry picked from commit 84b488dfc10bc236f38a4c446057b3a934958c28) Signed-off-by: fbalazsy --- drivers/accel/ane/ane_fw_cold.c | 27 ++++++++++++++++++++++++++- drivers/accel/ane/ane_fw_cold_test.c | 23 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index abd8574683fce..b686b497dcf02 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -1868,6 +1868,30 @@ static void ane_fw_sleep_unblock(struct ane_fw_backend *b) wake_up_all(&b->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_fw_cold_sleep_event(const struct ane_fw_backend *b, + unsigned long event) +{ + if (ane_fw_sleep_warm(b)) + 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_fw_pm_event(struct notifier_block *nb, unsigned long event, void *unused) { struct ane_fw_backend *b = container_of(nb, struct ane_fw_backend, pm_notifier); @@ -1880,6 +1904,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(b, event); if (event == PM_POST_SUSPEND) { ane_fw_sleep_resume(b); WRITE_ONCE(b->in_sleep, false); @@ -1924,7 +1949,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..a3ba04a299dd9 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -305,6 +305,29 @@ 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. */ + { + struct ane_fw_cold_soc cold_soc = ane_cold_t8140; + struct ane_fw_cold_soc warm_soc = ane_cold_t8140; + struct ane_fw_backend b = { .soc = &cold_soc }; + + cold_soc.sleep_warm = false; + warm_soc.sleep_warm = true; + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_HIBERNATION_PREPARE), + PM_SUSPEND_PREPARE); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_RESTORE_PREPARE), + PM_SUSPEND_PREPARE); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_POST_HIBERNATION), + PM_POST_SUSPEND); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_POST_RESTORE), + PM_POST_SUSPEND); + b.soc = &warm_soc; + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_HIBERNATION_PREPARE), + PM_HIBERNATION_PREPARE); + KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_RESTORE_PREPARE), + PM_RESTORE_PREPARE); + } } /* From 586d973d130ff076cf4a785480f355fce9d5adea Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 19:16:05 +0700 Subject: [PATCH 127/140] usb: typec: tipd: sn201202x: refresh LDCM and wake controller on hibernation restore On a cold hibernation restore, the resuming boot resets the SN201202x port controller (clearing any liquid-detection mitigation) and the loading kernel puts it to sleep at its freeze. Add a .restore callback that invalidates cached LDCM mitigation state when pm_hibernate_restored_cold() is true before waking the controller via sn201202x_resume(), so complete() reads the detector afresh. Signed-off-by: Nick (cherry picked from commit 744af9e433063ff6cba03a3eab39aa1cc867e9cd) Signed-off-by: fbalazsy --- drivers/usb/typec/tipd/spmi.c | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) 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) }; From 860e890aaea2ab1df530b43f990ed0903db21a4a Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 19:15:58 +0700 Subject: [PATCH 128/140] pmdomain: apple: pmc: restore voter enables and floors after hibernation A kernel restored from a hibernation image runs after a cold boot that started from a reset PMC with every agent disabled on every rail. The early resume callback skips restoring when pm_resume_via_firmware() is false, leaving agent enables, floors, DCS vote, and interfaces cleared. Add a dedicated .restore_early callback that always restores the tracked PMC state across hibernation. Signed-off-by: Nick (cherry picked from commit 312688326ba6cd43c50088e8e3894205aa0ca69f) Signed-off-by: fbalazsy --- drivers/pmdomain/apple/pmc.c | 40 +++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/drivers/pmdomain/apple/pmc.c b/drivers/pmdomain/apple/pmc.c index 5ad7df82f8023..ef90810e1aa08 100644 --- a/drivers/pmdomain/apple/pmc.c +++ b/drivers/pmdomain/apple/pmc.c @@ -1929,18 +1929,14 @@ static const struct apple_pmc_hw apple_pmc_hw_t6050 = { .has_pending = true, }; -/* - * 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); @@ -1969,8 +1965,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[] = { From 23f061f0a2410121c059da2c25b57435589f3f14 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 20:14:48 +0700 Subject: [PATCH 129/140] ASoC: codecs: cs42l84, tas2764: restore codec and amp state after cold hibernation cs42l84 gated its suspend/reset sequence on pm_suspend_via_firmware(), skipping cache-only reset and post-resume re-init across hibernation. Spell out freeze/thaw/poweroff/restore so cs42l84 resets cleanly before the image and re-initializes + re-detects the jack on restore. tas2764 gated power-on reset recovery on pm_resume_via_firmware(); also treat pm_hibernate_restored_cold() as a power-on reset so the amps run the full SW_RST, regcache_sync, init quirks, and fail-closed restore check after a cold boot. Signed-off-by: Nick (cherry picked from commit 851e410c4b5206d695ad87ec057df34a8f07d974) Signed-off-by: fbalazsy --- sound/soc/codecs/cs42l84.c | 22 +++++++++++++++++----- sound/soc/codecs/tas2764.c | 2 +- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/sound/soc/codecs/cs42l84.c b/sound/soc/codecs/cs42l84.c index 2ec20dac6e9c8..c341ea9d59608 100644 --- a/sound/soc/codecs/cs42l84.c +++ b/sound/soc/codecs/cs42l84.c @@ -1614,14 +1614,11 @@ static void cs42l84_sleep_quiesce(struct cs42l84_private *cs42l84, struct device * release it as the probe does and write everything back from the cache. * Other sleep states leave the codec alone, as before. */ -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()) - return 0; - /* Still down from a resume that failed. */ if (cs42l84->sleep_reset) return 0; @@ -1642,6 +1639,14 @@ static int cs42l84_suspend(struct device *dev) return 0; } +static int cs42l84_suspend(struct device *dev) +{ + if (!pm_suspend_via_firmware()) + return 0; + + return cs42l84_power_down(dev); +} + static int cs42l84_resume(struct device *dev) { struct i2c_client *i2c_client = to_i2c_client(dev); @@ -1765,7 +1770,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 65a866f622b3e..0ef092dedafdd 100644 --- a/sound/soc/codecs/tas2764.c +++ b/sound/soc/codecs/tas2764.c @@ -478,7 +478,7 @@ static int tas2764_codec_resume(struct snd_soc_component *component) * below, unless the amp itself shows a reset. */ bool power_on = tas2764->sdz_group && - (pm_resume_via_firmware() || pm_hibernate_is_restored()); + (pm_resume_via_firmware() || pm_hibernate_restored_cold()); int ret; if (!tas2764->sdz_group) { From d56d797a202ef01ccd01bfb58bb57a2846efa745 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 2 Dec 2026 20:14:45 +0700 Subject: [PATCH 130/140] ASoC: apple: mca: save and restore active clusters across hibernation apple_mca_suspend_late() and apple_mca_resume_early() gate on pm_suspend_via_firmware() / pm_resume_via_firmware(), skipping register save/restore across hibernation. Add .freeze_late/.poweroff_late, .thaw_early, and .restore_early (gated on pm_hibernate_restored_cold()) so active MCA clusters and SERDES settings survive a cold restore. Signed-off-by: Nick (cherry picked from commit 5d0565aaec82892edc3024bf50a5d1610d2fdd1d) Signed-off-by: fbalazsy --- sound/soc/apple/mca.c | 69 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/sound/soc/apple/mca.c b/sound/soc/apple/mca.c index 0bbacde383cd5..c073eb0edbf74 100644 --- a/sound/soc/apple/mca.c +++ b/sound/soc/apple/mca.c @@ -1641,12 +1641,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++) { @@ -1674,12 +1674,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++) { @@ -1720,8 +1720,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 = { From 1c1f3522ce395cd35747d825fd137e397c184ee7 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 08:53:24 +0700 Subject: [PATCH 131/140] soc/apple: pmp: replay report requests on cold hibernation restore After apple_pmp_restore() restarts a cold-booted PMP at PM_POST_HIBERNATION, call apple_pmp_report_wake(pmp_device, false) so all driver-owned power votes and DVFS floors are re-asserted onto the freshly booted PMP before display and GPU consumers wake up. Restrict apple_pmp_report_entry_pm_ops to .suspend_noirq/.resume_noirq so release-for-sleep entries do not poll a still-halted PMP during hibernation .restore_noirq, and remember pio_mapped on PmpData so apple,pio-ranges are not re-mapped with -EEXIST across cold restore. Signed-off-by: Nick (cherry picked from commit e93ba184d1127b95226304f0552f27211ac2f5f5) Signed-off-by: fbalazsy --- drivers/pmdomain/apple/pmp-report.c | 9 ++++++-- drivers/soc/apple/pmp-export.c | 3 ++- drivers/soc/apple/pmp.rs | 34 +++++++++++++++++++---------- tools/asahi/display26-tests.py | 1 + 4 files changed, 32 insertions(+), 15 deletions(-) diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index c790606badd8a..9e2801bd922e0 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -3515,9 +3515,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/soc/apple/pmp-export.c b/drivers/soc/apple/pmp-export.c index 47081ba4d3159..02d64ac9e6930 100644 --- a/drivers/soc/apple/pmp-export.c +++ b/drivers/soc/apple/pmp-export.c @@ -87,7 +87,8 @@ static int apple_pmp_pm_notify(struct notifier_block *nb, unsigned long action, "hibernation: DART restore failed: %d\n", ret); put_device(dart); } - apple_pmp_restore(pmp_data); + if (!apple_pmp_restore(pmp_data) && pm_hibernate_restored_cold()) + apple_pmp_report_wake(pmp_device, false); } return NOTIFY_DONE; } diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index 88f68f6a7d25e..6886fb6927ccf 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,8 @@ 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). @@ -247,6 +249,7 @@ 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, @@ -406,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 { @@ -430,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); diff --git a/tools/asahi/display26-tests.py b/tools/asahi/display26-tests.py index 1405246f27791..fb0ba4883de26 100644 --- a/tools/asahi/display26-tests.py +++ b/tools/asahi/display26-tests.py @@ -102,6 +102,7 @@ def main(): 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_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' From ee3faca0f8c0b3eb9d239f3743a0b22a83015167 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 3 Dec 2026 01:24:35 +0700 Subject: [PATCH 132/140] drm/apple: avoid double suspend in hibernation poweroff and harden DCP restore apple_platform_thaw() keeps outputs suspended (hib_thaw_skipped) while writing the hibernation image, so wiring .poweroff directly to apple_platform_freeze() called drm_mode_config_helper_suspend() a second time while suspend_state was already populated. Add an explicit apple_platform_poweroff() (and guard apple_platform_freeze()) to return early when outputs are already suspended. In dcp.c, also clear secure_answered when dcp_hib_quiesce() drops the old session, clear hib_poweroff_entered in dcp_platform_thaw(), and skip dcp_platform_restore_early() session teardown on warm in-place test_resume restores. Signed-off-by: Nick (cherry picked from commit dd4b1cdb1f75d22bdfcb7bac04e949d94785eb88) Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/apple_drv.c | 16 +++++++++++++++- drivers/gpu/drm/apple/dcp.c | 9 +++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 9248bafdabbff..56e9b6e8ebd9f 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -3036,6 +3036,20 @@ static int apple_platform_resume(struct device *dev) */ 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); } @@ -3126,7 +3140,7 @@ static const struct dev_pm_ops apple_platform_pm_ops = { #ifdef CONFIG_HIBERNATION .freeze = apple_platform_freeze, .thaw = apple_platform_thaw, - .poweroff = apple_platform_freeze, + .poweroff = apple_platform_poweroff, .restore = apple_platform_restore, #endif .complete = apple_platform_complete, diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index bc45deb0668ac..136f37a67cb62 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -13915,6 +13915,10 @@ static void dcp_hib_quiesce(struct apple_dcp *dcp) 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); @@ -14786,6 +14790,7 @@ 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) { @@ -14815,8 +14820,8 @@ static int dcp_platform_restore_early(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); - /* The power-off failed: .restore thaws. */ - if (!dcp || dcp->hib_poweroff_entered) + /* 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) || From c80d78247f3de9d7444bf903207d472f26585af4 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 4 Dec 2026 01:49:01 +0100 Subject: [PATCH 133/140] drm/asahi: g17: keep client VMs across a cold hibernation restore A hibernation restore boots the GPU firmware cold. Until now every client that was running before the image lost its device: its VM was declared outlived, every submit returned EIO and the compositor had to restart. The client VMs are host memory that the image holds, and the kernel window objects aliased into them are reused by the rebuild. Only the firmware-side state goes away: the context table slots, the queue records and the render pairs, all of which the cold boot already retires. Split the UAT epoch in two. The firmware epoch still moves on every cold boot, so roots published before it never touch a slot that a new client may own. A new client epoch moves only when the VMs are lost. Where the SoC sets hib_keep_clients, the cold boot moves only the firmware epoch. A queue whose context predates the boot then reports needs_rebuild, and the file builds it again on the same VM, with the arguments of its QUEUE_CREATE, before its next submission. Clients keep their VMs, objects and syncobjs and carry on without seeing a lost device. Enable it on T6040, where it was run through hibernation cycles with the compositor surviving. Other SoCs keep the previous behaviour. This follows the M5 cold-boot republish of live contexts. Suggested-by: Nick Signed-off-by: fbalazsy --- drivers/gpu/drm/asahi/file.rs | 85 +++++++++++++++++++++++-- drivers/gpu/drm/asahi/g17/context.rs | 12 ++++ drivers/gpu/drm/asahi/g17/mod.rs | 4 ++ drivers/gpu/drm/asahi/g17/queue/mod.rs | 4 ++ drivers/gpu/drm/asahi/g17/sleep.rs | 18 ++++-- drivers/gpu/drm/asahi/hw/t6040.rs | 1 + drivers/gpu/drm/asahi/hw/t6041.rs | 2 + drivers/gpu/drm/asahi/hw/t6041_25g83.rs | 1 + drivers/gpu/drm/asahi/hw/t6050.rs | 3 + drivers/gpu/drm/asahi/hw/t8140.rs | 1 + drivers/gpu/drm/asahi/hw/t8142.rs | 2 + drivers/gpu/drm/asahi/mmu.rs | 25 +++++++- drivers/gpu/drm/asahi/queue/mod.rs | 7 ++ 13 files changed, 151 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index b5c34c9851d28..67c2d861cdc86 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -379,13 +379,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; @@ -1823,12 +1878,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(), )?; @@ -1837,14 +1893,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, }), @@ -1984,6 +2053,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/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 3c72917468e85..27d373811c1ab 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -476,11 +476,23 @@ impl Context { /// 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/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index f0d0a69236dce..41a84494615ea 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>, diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index a42d389876b93..0aa2b2c2c7506 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -575,6 +575,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() { diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index 429c0dcc969f7..e9c3619222a22 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -747,8 +747,9 @@ impl Firmware { /// 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 and client VMs are not carried over; post-restore clients allocate - /// them fresh. + /// 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(); @@ -793,9 +794,16 @@ impl Firmware { self.render_rings.release_for_cold_boot(); let retire_ns = super::now_ns().saturating_sub(t0); - // 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(); + 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. 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 57382e9622126..f05c2fecbe469 100644 --- a/drivers/gpu/drm/asahi/hw/t6050.rs +++ b/drivers/gpu/drm/asahi/hw/t6050.rs @@ -41,6 +41,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, @@ -174,6 +175,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, @@ -317,6 +319,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 e427c7df585fb..b8e9b6fece4f3 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 8c5d90d9756c4..900350ec0112b 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 2704abfa56945..01b766064cf4d 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -1396,7 +1396,7 @@ 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::firmware_epoch`] when this VM was created. + /// [`UatInner::client_epoch`] when this VM was created. firmware_epoch: u32, } no_debug!(Vm); @@ -1432,6 +1432,11 @@ struct ExecutionRoot { } 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() } @@ -2337,6 +2342,10 @@ struct UatInner { /// 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, @@ -2661,7 +2670,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.firmware_epoch.load(Ordering::Acquire); + let firmware_epoch = uat_inner.client_epoch.load(Ordering::Acquire); let page_table = if let Some(ttb) = ttb { UatPageTable::new_with_ttb( @@ -3869,6 +3878,7 @@ impl Uat { 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, @@ -4522,6 +4532,14 @@ impl Uat { /// 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); } @@ -4726,6 +4744,7 @@ impl Uat { m4_adopted: false, failed: AtomicBool::new(false), firmware_epoch: AtomicU32::new(0), + client_epoch: AtomicU32::new(0), clean_poc: quirks.clean_tables, quirks, reserved, @@ -4923,7 +4942,7 @@ 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.firmware_epoch.load(Ordering::Acquire) != self.firmware_epoch + self.uat_inner.client_epoch.load(Ordering::Acquire) != self.firmware_epoch } /// Diagnostic reservation occupancy (including guards), not a placement promise. diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 3aff30fe273e4..19aa68c88aef7 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -186,6 +186,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); From 7575b8eaa217dd41a311458df1d2e1e24596e1cc Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 4 Dec 2026 08:05:50 +0100 Subject: [PATCH 134/140] PM: hibernate: Keep the image's swap pages until its signature is gone Two error paths release the swap pages of an image while the signature that points at them may still be on the disk: - test_resume: when swsusp_check() cannot read the header or cannot write the signature reset, the restore is skipped and swsusp_free_image_swap() frees the pages with the image still signed; - the image writer: when the device flush after the header write fails and so does the signature clear, swap_writer_finish() logs it and frees the pages anyway. In both cases ordinary swap can reuse those blocks after the tasks thaw, and a later boot then resumes an image whose pages were overwritten. Release the pages only after the signature is durably gone. swsusp_free_image_swap() opens the resume device and clears it first; swap_writer_finish() clears it on any error once the header write was attempted. If the clear fails, the pages stay reserved until the next boot, as they did before the test_resume free was added. A failed write of the last swap map page now fails the image as well, instead of leaving a signed image with a missing map page. swsusp_invalidate_sig() now returns 0 only when the header durably holds no image signature: it flushes the device whether this call or an earlier one reset it, and a header with neither signature is no longer reported as an error. tools/asahi/hibernate-signature-tests.py runs the three functions from swap.c against a device model with a volatile cache and injected read, write and flush errors. Fixes: 34e4080155215 ("PM: hibernate: Free the image's swap pages when a test_resume restore fails") Fixes: 0cc237ddf2223 ("PM: hibernate: Make the image signature handling durable") Signed-off-by: fbalazsy --- kernel/power/swap.c | 85 +++++--- tools/asahi/hibernate-signature-tests.py | 248 +++++++++++++++++++++++ tools/asahi/run-host-tests.py | 5 + 3 files changed, 311 insertions(+), 27 deletions(-) create mode 100755 tools/asahi/hibernate-signature-tests.py diff --git a/kernel/power/swap.c b/kernel/power/swap.c index 6dbe843590190..febb4dcf933e1 100644 --- a/kernel/power/swap.c +++ b/kernel/power/swap.c @@ -483,31 +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) { - int flush; + 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. A failed flush leaves no durable image: drop - * the signature durably (unlike swsusp_unmark()) so that no - * later boot resumes from freed swap. + * loses the image. */ - flush = blkdev_issue_flush(file_bdev(hib_resume_bdev_file)); - if (!error && flush) { - if (swsusp_invalidate_sig()) - pr_err("image flush failed and the signature could not be dropped\n"); - error = flush; - } + 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(); @@ -1654,6 +1664,9 @@ void swsusp_close(void) * 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) { @@ -1662,21 +1675,18 @@ int swsusp_invalidate_sig(void) 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; + } /* - * swsusp_check() normally reset the signature already; that write may - * still be in the device's volatile cache, so rewrite the header with - * FUA either way and make the reset durable before the restore. + * An earlier reset (swsusp_check()'s) may still sit in the device's + * volatile cache, and a device may ignore FUA: flush either way. */ - if (!memcmp(HIBERNATE_SIG, swsusp_header->sig, 10)) - memcpy(swsusp_header->sig, swsusp_header->orig_sig, 10); - else if (memcmp(swsusp_header->sig, swsusp_header->orig_sig, 10)) - return -ENODEV; - error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_FUA, - swsusp_resume_block, swsusp_header); - /* A device that ignores FUA still honours an explicit cache flush. */ - if (!error) - error = blkdev_issue_flush(file_bdev(hib_resume_bdev_file)); - return error; + return blkdev_issue_flush(file_bdev(hib_resume_bdev_file)); } /** @@ -1684,10 +1694,31 @@ int swsusp_invalidate_sig(void) * * 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), nothing frees them, and swapoff then waits for them forever. + * 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); } diff --git a/tools/asahi/hibernate-signature-tests.py b/tools/asahi/hibernate-signature-tests.py new file mode 100755 index 0000000000000..cfb8b1d004405 --- /dev/null +++ b/tools/asahi/hibernate-signature-tests.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""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/run-host-tests.py b/tools/asahi/run-host-tests.py index b7804570064fc..4ad1ed02180b1 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -173,6 +173,11 @@ def mutations(flag, names, base, expect=KILL): '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. From fe23d01aed3c43a63306f5f5fa9374e9614c2a6f Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 4 Dec 2026 08:21:56 +0100 Subject: [PATCH 135/140] drm/asahi: drop leftover no-op error closures on the hibernation paths The hibernation restore commits left `.map_err(|error| error)` wrappers in the kick ring, UAT and residency paths, and an error arm that only discards its value. They change nothing; drop them. No functional change. Signed-off-by: fbalazsy --- drivers/gpu/drm/asahi/g17/kick.rs | 15 +++------------ drivers/gpu/drm/asahi/mmu.rs | 16 ++++------------ 2 files changed, 7 insertions(+), 24 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 144701244ba13..9bf88b4ed3afb 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -741,10 +741,7 @@ impl Queue { Some(alias), )); } - Ok(None) => {} - Err(error) => { - let _ = error; - } + Ok(None) | Err(_) => {} } } let (vm, status) = (client.id(), client.status().cloned()); @@ -756,10 +753,7 @@ impl Queue { mmu::UAT_PGSZ as u64, mmu::PROT_FW_SHARED_RW, CpuMap::WriteCombined, - ) - .map_err(|error| { - error - })?; + )?; let mut range = alloc.uat.kernel_lower_dynamic_range(); let (low, client) = loop { let low = high @@ -768,10 +762,7 @@ impl Queue { range.clone(), mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, - ) - .map_err(|error| { - error - })?; + )?; let end = low .iova() .checked_add(KICK_RING_SIZE as u64) diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 7ff4265e1242b..a6735a9817b5b 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -1283,9 +1283,7 @@ impl VmInner { // the reserved shared-L2; only final leaf stores below already linked L3s are live. self.page_table.prepare_driver_map(node.start()..end)?; let uat_inner = self.uat_inner.clone(); - let handoff = uat_inner.lock_m4_upper(self.is_kernel).map_err(|error| { - error - })?; + let handoff = uat_inner.lock_m4_upper(self.is_kernel)?; // Refuse a range holding another mapping's leaves before writing anything: the // discard below clears the whole range. if let Err(error) = self.page_table.ensure_unmapped(node.start()..end) { @@ -3171,18 +3169,12 @@ impl Vm { return Err(EINVAL); } let reserved_size = size.checked_add(guard_size).ok_or(EOVERFLOW)?; - let _residency = self.enter_residency().map_err(|error| { - error - })?; + let _residency = self.enter_residency()?; // End the bound-device lease before entering firmware/GPUVM waits. let (_bind_lease, vm_bo) = { - let binding = self.device_binding.enter().map_err(|error| { - error - })?; + let binding = self.device_binding.enter()?; let dev = binding.device(); - let lease = crate::gem::held_sg_table(gem, dev).map_err(|error| { - error - })?.into_lease(); + let lease = crate::gem::held_sg_table(gem, dev)?.into_lease(); let bo = self.gpuvm.obtain( gem, pin_init!(VmBoData { From d806fb13c71f3cfe57e3caaf54af13ad3f42dbe0 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 4 Dec 2026 08:21:56 +0100 Subject: [PATCH 136/140] tools/asahi: hibernate-signature-tests: add SPDX tag and MAINTAINERS entry The host test added with the image signature fix had no SPDX line and no MAINTAINERS entry, unlike the other host tests. Add both. Signed-off-by: fbalazsy --- MAINTAINERS | 1 + tools/asahi/hibernate-signature-tests.py | 1 + 2 files changed, 2 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index e16b602d5b952..705d86beecac1 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2160,6 +2160,7 @@ 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/tools/asahi/hibernate-signature-tests.py b/tools/asahi/hibernate-signature-tests.py index cfb8b1d004405..4f3072d36e493 100755 --- a/tools/asahi/hibernate-signature-tests.py +++ b/tools/asahi/hibernate-signature-tests.py @@ -1,4 +1,5 @@ #!/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 From e5528b627c5b485528c7a3c38283ef848b114f15 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Fri, 4 Dec 2026 08:28:40 +0100 Subject: [PATCH 137/140] tools/asahi: apple-wdt-tests: expect the hibernation backstop on WD1-only watchdogs main's WD1 sleep handoff test was written against a driver that adds only the sleep handoff as a devm action for a watchdog without the reconfig register. On this branch every apple_wdt probe also registers the hibernation backstop, so devm unwinds the watchdog, the backstop and then the sleep handoff, as the WD2 cases already check. Expect the same order here, and the backstop gone after the teardown. Signed-off-by: fbalazsy --- tools/asahi/apple-wdt-tests.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/asahi/apple-wdt-tests.py b/tools/asahi/apple-wdt-tests.py index 13fe7e0609ae4..e798c6bde5e58 100755 --- a/tools/asahi/apple-wdt-tests.py +++ b/tools/asahi/apple-wdt-tests.py @@ -760,9 +760,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); /* From f489a2fc0063eceb001dc75bc4dfb38d6a22de8c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 5 Dec 2026 11:18:09 +1100 Subject: [PATCH 138/140] tools/aurora-sep: give the diag host shim atomic64_set a9e2f463 ("soc: apple-sep: Start the diag attach and ready times again at each bind") resets attach_ns and ready_ns with atomic64_set(), but the host shim in test_diag_sensor.py only defines atomic64_read and atomic64_cmpxchg, so the hosted SEP source diagnostics fail to compile diag_shim.c. Add atomic64_set next to atomic64_read. Signed-off-by: Ryan Murray --- tools/aurora-sep/tests/test_diag_sensor.py | 1 + 1 file changed, 1 insertion(+) 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, From 0a45b13f584bccbd7886eadfc14bb65e9a675fc4 Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sat, 5 Dec 2026 09:04:40 +0100 Subject: [PATCH 139/140] Fix KUnit builds and post-merge compute shared helper - accel/ane: move ane_fw_cold_sleep_event() to ane_fw_sleep.h taking a sleep_warm boolean so ane_fw_cold_test.c compiles as a standalone KUnit module without needing private backend definitions. - drm/apple/dcp: move DCP_S2R_PLUG_MS outside #ifdef CONFIG_HIBERNATION so dcp_ext_link_work() compiles under KUnit configs without CONFIG_HIBERNATION. - iommu/apple-dart: pass the adopt flag (false) in apple-dart-test.c calls to apple_dart_hw_sync_locked() and guard apple_dart_hib_defer_reimport() under #ifdef CONFIG_HIBERNATION. - drm/asahi: guard data.g16 in for_each_backend() under #[cfg(CONFIG_DRM_ASAHI_G16)], and drop the unused shared argument from publish_compute_shared() after main removed the compute pool backing. - rust/helpers/suspend.c: provide rust_helper_pm_hibernate_is_restored() under #ifndef CONFIG_HIBERNATION so aop.rs compiles when hibernation is disabled. --- drivers/accel/ane/ane_fw_cold.c | 26 +-------------------- drivers/accel/ane/ane_fw_cold_test.c | 33 ++++++++++----------------- drivers/accel/ane/ane_fw_sleep.h | 23 +++++++++++++++++++ drivers/gpu/drm/apple/dcp.c | 14 ++++++------ drivers/gpu/drm/asahi/driver.rs | 1 + drivers/gpu/drm/asahi/g17/initdata.rs | 10 ++++---- drivers/iommu/apple-dart-test.c | 20 ++++++++-------- drivers/iommu/apple-dart.c | 2 ++ rust/helpers/suspend.c | 7 ++++++ 9 files changed, 67 insertions(+), 69 deletions(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index b686b497dcf02..408ee880871a7 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -1868,30 +1868,6 @@ static void ane_fw_sleep_unblock(struct ane_fw_backend *b) wake_up_all(&b->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_fw_cold_sleep_event(const struct ane_fw_backend *b, - unsigned long event) -{ - if (ane_fw_sleep_warm(b)) - 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_fw_pm_event(struct notifier_block *nb, unsigned long event, void *unused) { struct ane_fw_backend *b = container_of(nb, struct ane_fw_backend, pm_notifier); @@ -1904,7 +1880,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(b, event); + 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); diff --git a/drivers/accel/ane/ane_fw_cold_test.c b/drivers/accel/ane/ane_fw_cold_test.c index a3ba04a299dd9..e83a1342840ce 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -307,27 +307,18 @@ static void ane_cold_sleep_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_fw_sleep_backstop(false), 0); /* Cold-cycling maps hibernation and restore to suspend/post-suspend; warm sleep does not. */ - { - struct ane_fw_cold_soc cold_soc = ane_cold_t8140; - struct ane_fw_cold_soc warm_soc = ane_cold_t8140; - struct ane_fw_backend b = { .soc = &cold_soc }; - - cold_soc.sleep_warm = false; - warm_soc.sleep_warm = true; - KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_HIBERNATION_PREPARE), - PM_SUSPEND_PREPARE); - KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_RESTORE_PREPARE), - PM_SUSPEND_PREPARE); - KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_POST_HIBERNATION), - PM_POST_SUSPEND); - KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_POST_RESTORE), - PM_POST_SUSPEND); - b.soc = &warm_soc; - KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_HIBERNATION_PREPARE), - PM_HIBERNATION_PREPARE); - KUNIT_EXPECT_EQ(test, ane_fw_cold_sleep_event(&b, PM_RESTORE_PREPARE), - PM_RESTORE_PREPARE); - } + 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/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 99caa3a2c25c9..cc84eabfe0b77 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -13985,6 +13985,13 @@ static int dcp_platform_resume(struct device *dev) return 0; } +/* + * 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 + #ifdef CONFIG_HIBERNATION /* * Hibernation. @@ -14638,13 +14645,6 @@ static bool dcp_hib_ext_has_display(struct apple_dcp *dcp) * above. The HPD interrupt that dcp_enable_dp2hdmi_hpd() enables was * disabled at freeze, or at restore. */ -/* - * 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 - static void dcp_fixed_phy_up(struct apple_dcp *dcp); static bool dcp_fixed_hdmi(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 4063d58ec2c67..04b0b786dec0e 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -397,6 +397,7 @@ unsafe fn for_each_backend(dev: *mut bindings::device, mut f: impl FnMut(&dyn Hi 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); } diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 8cb7183f8dcd9..c8cbe9b6e3d00 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -753,17 +753,15 @@ impl InitData { if self.compute_shared.is_some() { return Ok(()); } - self.publish_compute_shared(&mut shared)?; + 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 let Some(mut shared) = self.compute_shared.take() { - let result = self.publish_compute_shared(&mut shared); - self.compute_shared = Some(shared); - 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); @@ -776,7 +774,7 @@ impl InitData { Ok(()) } - fn publish_compute_shared(&mut self, shared: &mut ComputeShared) -> Result { + 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(); diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 73f8fbfc79081..96a02df9030f1 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. */ @@ -2167,7 +2167,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. */ @@ -2175,7 +2175,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); diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index e04115ebbebe3..18d395eb2b8e8 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -1151,6 +1151,7 @@ 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, @@ -1179,6 +1180,7 @@ static bool apple_dart_hib_defer_reimport(struct device_node *np) } 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, 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 From 2cb14af4958fa869d635e89c99e0d10a71e3840e Mon Sep 17 00:00:00 2001 From: fbalazsy Date: Sun, 6 Dec 2026 13:22:03 +0100 Subject: [PATCH 140/140] soc: apple: align host tests, KUnit fixtures, and SEP hibernation logging with main Fix CI failures and merge-up test mismatches: - tools/asahi/g17-admission-order-tests.py and tools/asahi/g17-render-submit-fastpath-tests.py: update Pool.queues fixtures for packed AtomicU64 generation/count and QueueSlot generation. - drivers/soc/apple/sep.rs and drivers/soc/apple/hibe.rs: switch hibernation log calls to rate-limited macros so test_log_ratelimit passes. - include/linux/suspend.h: define struct hibernation_backstop outside CONFIG_HIBERNATION so apple_wdt compiles when CONFIG_HIBERNATION=n. - drivers/watchdog/apple_wdt-test.c: expect the low-8-bit reconfig policy. - drivers/gpu/drm/apple/dcp_t6041_wake_test.c: update stub signature and relink_ext field name. - tools/testing/selftests/drivers/apple/dwc3-sleep-gadget.py: add sleep_hibernate to the mock struct dwc3_apple. Signed-off-by: fbalazsy --- drivers/gpu/drm/apple/dcp_t6041_wake_test.c | 8 +++--- drivers/soc/apple/hibe.rs | 8 +++--- drivers/soc/apple/sep.rs | 8 +++--- drivers/watchdog/apple_wdt-test.c | 6 +++-- include/linux/suspend.h | 25 +++++++++---------- tools/asahi/g17-admission-order-tests.py | 12 +++++---- .../asahi/g17-render-submit-fastpath-tests.py | 10 +++++--- .../drivers/apple/dwc3-sleep-gadget.py | 2 +- 8 files changed, 42 insertions(+), 37 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp_t6041_wake_test.c b/drivers/gpu/drm/apple/dcp_t6041_wake_test.c index 6665be21bfef3..ee5f625ac5f88 100644 --- a/drivers/gpu/drm/apple/dcp_t6041_wake_test.c +++ b/drivers/gpu/drm/apple/dcp_t6041_wake_test.c @@ -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/soc/apple/hibe.rs b/drivers/soc/apple/hibe.rs index 52c9e00d52044..bdf24d0e6673d 100644 --- a/drivers/soc/apple/hibe.rs +++ b/drivers/soc/apple/hibe.rs @@ -259,7 +259,7 @@ impl SepData { // 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!(self.dev, "hibe: prepare refused outside a hibernation flow\n"); + dev_warn_ratelimited!(self.dev, "hibe: prepare refused outside a hibernation flow\n"); return Err(EAGAIN); } self.hibe_register()?; @@ -267,11 +267,11 @@ impl SepData { 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!(self.dev, "hibe: prepare refused (msg0 {:#018x})\n", word); + 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!(self.dev, "hibe: prepare reply not written (msg0 {:#018x})\n", word); + 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)?; @@ -291,7 +291,7 @@ impl SepData { 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!(self.dev, "hibe: resume refused (msg0 {:#018x})\n", word); + dev_warn_ratelimited!(self.dev, "hibe: resume refused (msg0 {:#018x})\n", word); return Err(EIO); } Ok(word) diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index a94115d77150f..886563ba58845 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -1691,14 +1691,14 @@ impl SepData { this.control_wq.notify_all(); let Some(sep_node) = dt::sep_node() else { - dev_err!( + 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!( + dev_err_ratelimited!( this.dev, "hibernation: the registration marker stays ({:?}); the enclave stays unused\n", e @@ -1706,14 +1706,14 @@ impl SepData { return; } if let Err(e) = pm::rebind(&this.dev) { - dev_err!( + dev_err_ratelimited!( this.dev, "hibernation: the driver could not be bound again ({:?}); the enclave stays unused\n", e ); return; } - dev_info!( + dev_info_ratelimited!( this.dev, "hibernation: the enclave was started again; binding the driver again\n" ); 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/include/linux/suspend.h b/include/linux/suspend.h index 033fe6027c618..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); @@ -467,18 +479,6 @@ extern bool system_entering_hibernation(void); extern bool hibernation_available(void); void hibernation_set_platform_check(bool (*blocked)(void), const char *reason); -/** - * 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); -}; - void hibernation_set_backstop(const struct hibernation_backstop *backstop); asmlinkage int swsusp_save(void); extern struct pbe *restore_pblist; @@ -515,7 +515,6 @@ 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; } -struct hibernation_backstop; static inline void hibernation_set_backstop(const struct hibernation_backstop *backstop) {} static inline int hibernate_quiet_exec(int (*func)(void *data), void *data) { 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-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/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;