From ddf95fc58b08f70a70513f30c73f7fcc8d17c46f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 00:23:16 -0500 Subject: [PATCH 1/9] dmaengine: apple-sio: stop and restart SIO firmware across runtime PM sio_probe() released its runtime PM reference while sio_suspend() was a no-op stub, leaving sio_mbox active and risking ps_sio_cpu powering off under live SIO firmware whenever no other consumer pinned sio_dart. Implement sio_suspend() and sio_resume() for controllers that are not deferred to the sleep commit boundary (!commit_stop && !stop_at_commit): - Stop idle SIO firmware in sio_suspend() with apple_rtkit_sleep_stop() once all channels are quiet and no mailbox tags are outstanding, using a 500 ms autosuspend delay so back-to-back calls do not thrash it. - Restart SIO in sio_resume() via apple_rtkit_power_cycled_return(), falling back to apple_sleep_engine_reset() when a sibling domain kept the shared SIO power switch on across runtime suspend. - Hold runtime PM across sio_device_config(), sio_terminate_work(), sio_stop_quiet(), and active idle transfers (sio_set_idle() through sio_clear_idle()). - Keep commit_stop and stop_at_commit controllers active at runtime and through system suspend so commit-time stops run untouched; avoid double-stopping or waking an already runtime-suspended SIO across system sleep. - Allow apple_sleep_engine_reset() to fall back to reg index 0 when reg-names is absent and to map apple,pmgr directly when apple_sleep is not bound, so the engine-reset recovery works on every board with standard apple,pmgr-pwrstate domains. Signed-off-by: Erik Bourget --- drivers/dma/apple-sio.c | 258 +++++++++++++++++++++++++++++--------- drivers/soc/apple/sleep.c | 105 ++++++++++++---- 2 files changed, 280 insertions(+), 83 deletions(-) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index b6f5286904459..044f4ad528707 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -188,6 +188,8 @@ struct sio_data { struct apple_rtkit *rtk; /* The firmware is stopped for a system sleep. */ bool asleep; + /* The firmware is stopped while runtime-suspended. */ + bool rpm_stopped; bool firmware_only; /* Protocol 10 firmware given the earlier boot tables: no DMA, which would crash it */ bool tables_mismatch; @@ -1221,8 +1223,10 @@ static int sio_terminate_all(struct dma_chan *chan) static void sio_terminate_work(struct work_struct *wq) { struct sio_chan *siochan = container_of(wq, struct sio_chan, terminate_wq); + struct sio_data *sio = siochan->host; struct sio_tx *tx; unsigned long flags; + bool resumed; int ret; spin_lock_irqsave(&siochan->vc.lock, flags); @@ -1232,15 +1236,22 @@ static void sio_terminate_work(struct work_struct *wq) if (WARN_ON(!tx)) return; - ret = sio_call(siochan->host, FIELD_PREP(SIOMSG_EP, siochan->no) | - FIELD_PREP(SIOMSG_TYPE, MSG_TERMINATE)); - if (ret < 0) - dev_err(siochan->host->dev, "terminate call on chan %d failed: %d\n", + ret = pm_runtime_resume_and_get(sio->dev); + resumed = ret >= 0; + if (!resumed) { + dev_err(sio->dev, "runtime resume before terminate on chan %d failed: %d\n", siochan->no, ret); + } else { + ret = sio_call(sio, FIELD_PREP(SIOMSG_EP, siochan->no) | + FIELD_PREP(SIOMSG_TYPE, MSG_TERMINATE)); + if (ret < 0) + dev_err(sio->dev, "terminate call on chan %d failed: %d\n", + siochan->no, ret); - ret = wait_for_completion_timeout(&tx->done, msecs_to_jiffies(500)); - if (!ret) - dev_err(siochan->host->dev, "terminate descriptor wait timed out\n"); + ret = wait_for_completion_timeout(&tx->done, msecs_to_jiffies(500)); + if (!ret) + dev_err(sio->dev, "terminate descriptor wait timed out\n"); + } tasklet_kill(&siochan->vc.task); @@ -1252,6 +1263,11 @@ static void sio_terminate_work(struct work_struct *wq) sio_ring_leave_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); + if (resumed) { + pm_runtime_mark_last_busy(sio->dev); + pm_runtime_put_autosuspend(sio->dev); + } + sio_tx_free(&tx->vd); } @@ -1297,6 +1313,13 @@ static int sio_stop_quiet(struct sio_chan *siochan) unsigned int i; int ret; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) { + dev_err(dev, "chan %d: runtime resume before stop failed: %d\n", + siochan->no, ret); + return ret; + } + dev_err(dev, "chan %d: issued descriptors did not complete, stopping it\n", siochan->no); spin_lock_irqsave(&siochan->vc.lock, flags); siochan->stopping = true; @@ -1337,6 +1360,9 @@ static int sio_stop_quiet(struct sio_chan *siochan) sio_fill_in_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); + return ret == 1 ? 0 : -EIO; } @@ -1424,12 +1450,16 @@ static int sio_clear_idle(struct sio_chan *siochan) sio_tx_free(&idle->vd); sio_free_dead(siochan); + + pm_runtime_mark_last_busy(siochan->host->dev); + pm_runtime_put_autosuspend(siochan->host->dev); return 0; } /* See struct apple_sio_idle */ static int sio_set_idle(struct sio_chan *siochan, const struct apple_sio_idle *config) { + struct device *dev = siochan->host->dev; struct sio_tx *idle; unsigned long flags; int ret; @@ -1443,12 +1473,20 @@ static int sio_set_idle(struct sio_chan *siochan, const struct apple_sio_idle *c if (!idle) return -ENOMEM; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) { + sio_tx_free(&idle->vd); + return ret; + } + spin_lock_irqsave(&siochan->vc.lock, flags); ret = siochan->idle ? -EBUSY : 0; if (!ret && !siochan->ring) ret = sio_ring_enter_locked(siochan); if (ret) { spin_unlock_irqrestore(&siochan->vc.lock, flags); + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); sio_tx_free(&idle->vd); return ret; } @@ -1770,6 +1808,10 @@ static int sio_device_config(struct dma_chan *chan, if (siochan->configured && memcmp(&siochan->cfg, &cfg, sizeof(cfg))) return -EBUSY; + ret = pm_runtime_resume_and_get(sio->dev); + if (ret < 0) + return ret; + sio_write_config(sio->hw, cfg_shmem, &cfg); dma_wmb(); @@ -1786,6 +1828,9 @@ static int sio_device_config(struct dma_chan *chan, siochan->cfg = cfg; } + pm_runtime_mark_last_busy(sio->dev); + pm_runtime_put_autosuspend(sio->dev); + return ret; } @@ -1871,11 +1916,13 @@ static void sio_free_v9_shmem(void *data) struct sio_data *sio = data; int err; - /* An acknowledged shutdown must precede releasing firmware DMA targets. */ - err = apple_rtkit_shutdown(sio->rtk); - if (err) { - dev_err(sio->dev, "SIO shutdown failed: %d; retaining DMA buffers\n", err); - return; + if (!sio->rpm_stopped && !sio->asleep) { + /* An acknowledged shutdown must precede releasing firmware DMA targets. */ + err = apple_rtkit_shutdown(sio->rtk); + if (err) { + dev_err(sio->dev, "SIO shutdown failed: %d; retaining DMA buffers\n", err); + return; + } } dma_free_coherent(sio->dev, sio->arrays->responses * sio->arrays->response_size, sio->responses, sio->responses_iova); @@ -2045,6 +2092,11 @@ static int sio_commit_stop(void *data) return ret; } +static bool sio_can_runtime_suspend(const struct sio_data *sio) +{ + return !sio->hw->commit_stop && !sio->hw->stop_at_commit; +} + static int sio_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; @@ -2104,15 +2156,16 @@ static int sio_probe(struct platform_device *pdev) pm_runtime_get_noresume(&pdev->dev); pm_runtime_set_active(&pdev->dev); err = devm_pm_runtime_enable(&pdev->dev); - if (err < 0) - return dev_err_probe(&pdev->dev, err, - "pm_runtime_enable failed: %d\n", err); + if (err < 0) { + dev_err_probe(&pdev->dev, err, "pm_runtime_enable failed: %d\n", err); + goto err_rpm_put; + } sio->rtk = devm_apple_rtkit_init(&pdev->dev, sio, NULL, 0, &sio_rtkit_ops); if (IS_ERR(sio->rtk)) { err = PTR_ERR(sio->rtk); dev_err(&pdev->dev, "couldn't initialize rtkit\n"); - goto rpm_put; + goto err_rpm_put; } for (i = 0; i < SIO_NTAGS; i++) init_completion(&sio->tags.completions[i]); @@ -2153,8 +2206,10 @@ static int sio_probe(struct platform_device *pdev) writel(CPU_CONTROL_RUN, sio->base + REG_CPU_CONTROL); err = apple_rtkit_boot(sio->rtk); - if (err) - return dev_err_probe(&pdev->dev, err, "SIO did not boot\n"); + if (err) { + dev_err_probe(&pdev->dev, err, "SIO did not boot\n"); + goto err_rpm_put; + } if (sio->firmware_only) { dev_info(&pdev->dev, "firmware running, no DMA service\n"); @@ -2162,23 +2217,30 @@ static int sio_probe(struct platform_device *pdev) } err = apple_rtkit_start_ep(sio->rtk, EP_SIO); - if (err) - return dev_err_probe(&pdev->dev, err, "starting SIO endpoint\n"); + if (err) { + dev_err_probe(&pdev->dev, err, "starting SIO endpoint\n"); + goto err_rpm_put; + } err = sio_call(sio, FIELD_PREP(SIOMSG_TYPE, MSG_START)); if (err < 1) { if (err == 0) err = -ENXIO; - return dev_err_probe(&pdev->dev, err, "starting SIO service\n"); + dev_err_probe(&pdev->dev, err, "starting SIO service\n"); + goto err_rpm_put; + } + if (hw->protocol && sio->protocol != hw->protocol) { + err = dev_err_probe(&pdev->dev, -ENODEV, + "SIO firmware protocol %u, this SoC's is %u\n", + sio->protocol, hw->protocol); + goto err_rpm_put; } - if (hw->protocol && sio->protocol != hw->protocol) - return dev_err_probe(&pdev->dev, -ENODEV, - "SIO firmware protocol %u, this SoC's is %u\n", - sio->protocol, hw->protocol); err = sio_send_dt_params(sio); - if (err < 0) - return dev_err_probe(&pdev->dev, err, "failed to send boot-up parameters\n"); + if (err < 0) { + dev_err_probe(&pdev->dev, err, "failed to send boot-up parameters\n"); + goto err_rpm_put; + } if (sio->tables_mismatch) { sio->firmware_only = true; goto rpm_put; @@ -2186,36 +2248,52 @@ static int sio_probe(struct platform_device *pdev) err = sio_alloc_shmem(sio); if (err < 0) - return err; + goto err_rpm_put; if (hw->commit_stop) { err = apple_sleep_coproc_register(&pdev->dev, sio->base, false, sio_commit_stop, sio); - if (err) - return dev_err_probe(&pdev->dev, err, "registering the sleep's stop\n"); + if (err) { + dev_err_probe(&pdev->dev, err, "registering the sleep's stop\n"); + goto err_rpm_put; + } apple_sleep_coproc_set_early(&pdev->dev); } err = dma_async_device_register(&sio->dma); - if (err) - return dev_err_probe(&pdev->dev, err, "failed to register DMA device\n"); + if (err) { + dev_err_probe(&pdev->dev, err, "failed to register DMA device\n"); + goto err_unregister_coproc; + } err = of_dma_controller_register(pdev->dev.of_node, sio_dma_of_xlate, sio); if (err) { dma_async_device_unregister(&sio->dma); - return dev_err_probe(&pdev->dev, err, "failed to register with OF\n"); + dev_err_probe(&pdev->dev, err, "failed to register with OF\n"); + goto err_unregister_coproc; } rpm_put: - if (!err && hw->stop_at_commit) + if (hw->stop_at_commit) sio->commit_registered = !apple_sleep_coproc_register(&pdev->dev, sio->base, false, sio_commit_stop, sio); /* - * One stopped by the sleep's commit runs until then: a runtime suspend would let its domain - * go off under the firmware. + * Firmware stopped at the sleep commit stays active at runtime: a runtime + * suspend would let its domain go off under live firmware. */ - if (!hw->commit_stop) - pm_runtime_put(&pdev->dev); + if (sio_can_runtime_suspend(sio)) { + pm_runtime_set_autosuspend_delay(&pdev->dev, 500); + pm_runtime_use_autosuspend(&pdev->dev); + pm_runtime_mark_last_busy(&pdev->dev); + pm_runtime_put_autosuspend(&pdev->dev); + } + + return 0; +err_unregister_coproc: + if (hw->commit_stop) + apple_sleep_coproc_unregister(&pdev->dev); +err_rpm_put: + pm_runtime_put_noidle(&pdev->dev); return err; } @@ -2225,52 +2303,112 @@ static void sio_remove(struct platform_device *pdev) if (sio->commit_registered || sio->hw->commit_stop) apple_sleep_coproc_unregister(&pdev->dev); - if (sio->firmware_only) - return; + if (!sio->firmware_only) { + of_dma_controller_free(pdev->dev.of_node); + dma_async_device_unregister(&sio->dma); + } + if (sio_can_runtime_suspend(sio)) { + pm_runtime_dont_use_autosuspend(&pdev->dev); + pm_runtime_barrier(&pdev->dev); + } else { + pm_runtime_put_noidle(&pdev->dev); + } +} - of_dma_controller_free(pdev->dev.of_node); - dma_async_device_unregister(&sio->dma); +/* A channel with a transfer can't be carried through a firmware restart. */ +static bool sio_chan_busy(struct sio_chan *siochan) +{ + unsigned long flags; + bool busy; + + spin_lock_irqsave(&siochan->vc.lock, flags); + busy = siochan->current_tx || siochan->idle || siochan->ring || + siochan->pending; + spin_unlock_irqrestore(&siochan->vc.lock, flags); + + return busy; } -static __maybe_unused int sio_suspend(struct device *dev) +static __maybe_unused void sio_halt_cpu(struct sio_data *sio) { - /* - * TODO: SIO coproc sleep state - */ - return 0; + apple_rtkit_mailbox_off(sio->rtk); + writel(readl(sio->base + REG_CPU_CONTROL) & ~CPU_CONTROL_RUN, + sio->base + REG_CPU_CONTROL); + writel(readl(sio->base + REG_CPU_CONTROL) & ~CPU_CONTROL_RUN, + sio->base + REG_CPU_CONTROL); } -static __maybe_unused int sio_resume(struct device *dev) +static __maybe_unused int sio_suspend(struct device *dev) { + struct sio_data *sio = dev_get_drvdata(dev); + int i, ret; + + if (!sio_can_runtime_suspend(sio) || sio->asleep || sio->rpm_stopped) + return 0; + + for (i = 0; i < sio->nchannels; i++) { + if (sio_chan_busy(&sio->channels[i])) + return -EBUSY; + } + if (!bitmap_empty(sio->tags.allocated, SIO_NTAGS)) + return -EBUSY; + + ret = apple_rtkit_sleep_stop(sio->rtk, sio->base + REG_CPU_CONTROL); + if (ret) { + dev_err(dev, "firmware did not stop for runtime suspend: %d\n", ret); + if (apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL)) + dev_err(dev, "firmware did not come back\n"); + return ret; + } + sio->rpm_stopped = true; + return 0; } -/* A channel with a transfer can't be carried through a firmware restart. */ -static bool sio_chan_busy(struct sio_chan *siochan) +static __maybe_unused int sio_resume(struct device *dev) { - unsigned long flags; - bool busy; + struct sio_data *sio = dev_get_drvdata(dev); + int ret; - spin_lock_irqsave(&siochan->vc.lock, flags); - busy = siochan->current_tx || siochan->idle || siochan->ring; - spin_unlock_irqrestore(&siochan->vc.lock, flags); + if (!sio->rpm_stopped) + return 0; - return busy; + /* + * A sibling domain (for example SPI or audio) can keep SIO's shared + * power switch up across runtime suspend, leaving the idled firmware + * in place where power_cycled_return() would time out after 1 s. + * Pulse the PMGR engine reset first when available so resume finishes + * cleanly regardless of whether the domain power-cycled. + */ + ret = apple_sleep_engine_reset(dev); + if (ret && ret != -ENODEV && ret != -EOPNOTSUPP) { + dev_err(dev, "engine reset before runtime resume failed: %d\n", ret); + return ret; + } + ret = apple_rtkit_power_cycled_return(sio->rtk, sio->base + REG_CPU_CONTROL); + if (ret) { + sio_halt_cpu(sio); + dev_err(dev, "firmware did not come back from runtime suspend: %d\n", ret); + return ret; + } + sio->rpm_stopped = false; + + return 0; } -/* One stopped in the commit stays up through the system suspend. */ +/* One stopped at the sleep commit stays up through system suspend. */ static __maybe_unused int sio_system_suspend(struct device *dev) { struct sio_data *sio = dev_get_drvdata(dev); - return sio->hw->commit_stop ? 0 : pm_runtime_force_suspend(dev); + return sio_can_runtime_suspend(sio) ? pm_runtime_force_suspend(dev) : 0; } static __maybe_unused int sio_system_resume(struct device *dev) { struct sio_data *sio = dev_get_drvdata(dev); - return sio->hw->commit_stop ? 0 : pm_runtime_force_resume(dev); + return sio_can_runtime_suspend(sio) ? pm_runtime_force_resume(dev) : 0; } static __maybe_unused int sio_suspend_late(struct device *dev) @@ -2278,7 +2416,7 @@ static __maybe_unused int sio_suspend_late(struct device *dev) struct sio_data *sio = dev_get_drvdata(dev); int i, ret; - if (!pm_suspend_via_firmware() || sio->asleep) + if (!pm_suspend_via_firmware() || sio->asleep || sio->rpm_stopped) return 0; for (i = 0; i < sio->nchannels; i++) { diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 4c25f5fd21cbf..e71e53b67f3bc 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -3101,11 +3101,11 @@ EXPORT_SYMBOL_GPL(apple_sleep_domain_is_down); #define ENGINE_RESET_PS 4 #define ENGINE_RESET_DARTS 2 -static int sleep_engine_reset_wait(struct apple_sleep *s, u32 offset, u32 actual) +static int sleep_engine_reset_wait(void __iomem *reg, u32 actual) { u32 val; - return readl_poll_timeout_atomic(sleep_power_reg(s, offset), val, + return readl_poll_timeout_atomic(reg, val, FIELD_GET(PS_ACTUAL, val) == actual && !(val & PS_BUSY), 10, PS_OFF_TIMEOUT_US); } @@ -3126,6 +3126,40 @@ static bool sleep_ps_domain(struct apple_sleep *s, struct device_node *pd, u32 * return ours; } +/* Map a PMGR power-state word directly when apple_sleep is not bound on this board. */ +static void __iomem *sleep_map_pmgr_domain(struct device_node *pd, void __iomem **map) +{ + struct device_node *parent; + struct resource res; + void __iomem *base; + u32 offset; + + if (!(of_device_is_compatible(pd, "apple,pmgr-pwrstate") || + of_device_is_compatible(pd, "apple,t8103-pmgr-pwrstate")) || + of_property_read_bool(pd, "apple,firmware-owned") || + of_property_read_bool(pd, "apple,inherited-on") || + of_property_read_bool(pd, "apple,auto-managed") || + of_property_read_u32(pd, "reg", &offset)) + return NULL; + + parent = of_get_parent(pd); + if (!parent || !of_device_is_compatible(parent, "apple,pmgr") || + of_address_to_resource(parent, 0, &res) || + resource_size(&res) < sizeof(u32) || + offset > resource_size(&res) - sizeof(u32)) { + of_node_put(parent); + return NULL; + } + + base = of_iomap(parent, 0); + of_node_put(parent); + if (!base) + return NULL; + + *map = base; + return base + offset; +} + /* The @index-th DART in @np's iommus, a reference held, or NULL past the last. */ static struct device *sleep_iommus_dart(struct device_node *np, int index) { @@ -3144,33 +3178,53 @@ int apple_sleep_engine_reset(struct device *dev) { struct apple_sleep *s = apple_sleep; struct device *darts[ENGINE_RESET_DARTS] = {}; - u32 ps[ENGINE_RESET_PS], saved[ENGINE_RESET_PS], val; + void __iomem *ps_regs[ENGINE_RESET_PS]; + void __iomem *pmgr_maps[ENGINE_RESET_PS] = {}; + u32 saved[ENGINE_RESET_PS], val; struct of_phandle_iterator it; void __iomem *asc; int i, n = 0, idx, err, ret = 0; - if (!s) - return -ENODEV; - if (s->soc->regions) + if (s && s->soc->regions) return -EOPNOTSUPP; /* T6050 has no standalone engine reset here. */ of_for_each_phandle(&it, err, dev->of_node, "power-domains", NULL, 0) { - if (!sleep_ps_domain(s, it.node, &val)) - continue; + void __iomem *map = NULL; + void __iomem *reg; + + if (s) { + if (!sleep_ps_domain(s, it.node, &val)) + continue; + reg = sleep_power_reg(s, val); + } else { + reg = sleep_map_pmgr_domain(it.node, &map); + if (!reg) + continue; + } if (n == ENGINE_RESET_PS) { + if (map) + iounmap(map); of_node_put(it.node); - return -E2BIG; + ret = -E2BIG; + goto out_unmap; } - ps[n++] = val; + pmgr_maps[n] = map; + ps_regs[n++] = reg; + } + if (!n) { + ret = -ENODEV; + goto out_unmap; } - if (!n) - return -ENODEV; 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"); + 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; + if (!asc) { + ret = -ENODEV; + goto out_unmap; + } for (i = 0; i < ENGINE_RESET_DARTS; i++) { darts[i] = sleep_iommus_dart(dev->of_node, i); @@ -3180,24 +3234,24 @@ int apple_sleep_engine_reset(struct device *dev) } for (i = 0; i < n && !ret; i++) { - saved[i] = readl(sleep_power_reg(s, ps[i])); - writel(PS_ENGINE_RESET_4, sleep_power_reg(s, ps[i])); - ret = sleep_engine_reset_wait(s, ps[i], 4); + saved[i] = readl(ps_regs[i]); + writel(PS_ENGINE_RESET_4, ps_regs[i]); + ret = sleep_engine_reset_wait(ps_regs[i], 4); if (!ret) { - writel(PS_ENGINE_RESET_0, sleep_power_reg(s, ps[i])); - ret = sleep_engine_reset_wait(s, ps[i], 0); + writel(PS_ENGINE_RESET_0, ps_regs[i]); + ret = sleep_engine_reset_wait(ps_regs[i], 0); } } if (!ret) { usleep_range(1000, 2000); for (i = 0; i < n; i++) - writel(0, sleep_power_reg(s, ps[i])); + writel(0, ps_regs[i]); for (i = n - 1; i >= 0 && !ret; i--) { - writel(PS_TARGET, sleep_power_reg(s, ps[i])); - ret = sleep_engine_reset_wait(s, ps[i], FIELD_MAX(PS_ACTUAL)); + writel(PS_TARGET, ps_regs[i]); + ret = sleep_engine_reset_wait(ps_regs[i], FIELD_MAX(PS_ACTUAL)); if (!ret) writel(saved[i] & ~(PS_FLAGS | PS_RESET | PS_ACTUAL), - sleep_power_reg(s, ps[i])); + ps_regs[i]); } } if (!ret) @@ -3210,6 +3264,11 @@ int apple_sleep_engine_reset(struct device *dev) } iounmap(asc); +out_unmap: + for (i = 0; i < n; i++) + if (pmgr_maps[i]) + iounmap(pmgr_maps[i]); + return ret; } EXPORT_SYMBOL_GPL(apple_sleep_engine_reset); From a8d2f37caf8953f54470eb4d54bfb21e903846d3 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 00:24:41 -0500 Subject: [PATCH 2/9] ASoC: apple: mca: enable runtime PM on audio_p and allocate ADMAC channels on open apple_mca_probe() pinned the audio_p power domain via mca->pd_link (DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE) without enabling runtime PM on mca->dev, and mca_pcm_new() held ADMAC channels for the lifetime of the card, pinning ps_sio_adma, sio_dart, and the SIO power-domain hierarchy permanently on even when no audio stream is open. Enable runtime PM on MCA and allocate ADMAC channels lazily on open: - Cache DAI BCLK polarity and TX/RX bitstart in mca_fe_set_fmt() and program them in mca_fe_hw_params() / mca_configure_serdes() so ps_audio_p can safely power off between streams. - Enable runtime PM on mca->dev with a 200 ms autosuspend delay in apple_mca_probe(), holding a reference across mca_pcm_open()/mca_close() and mca_be_startup()/mca_be_shutdown(), and skip MMIO in apple_mca_suspend_late()/apple_mca_resume_early() when already runtime-suspended. - Format DMA channel names in a stack buffer in mca_request_dma_channel() instead of devm_kasprintf() to avoid leaking memory across open/close cycles. - Request ADMAC channels briefly in mca_pcm_new() to validate presence and configure managed PCM buffers, then allocate them in mca_pcm_open() and release them in mca_close() via snd_dmaengine_pcm_close_release_chan(). Signed-off-by: Erik Bourget --- sound/soc/apple/mca.c | 188 +++++++++++++++++++++++++----------------- 1 file changed, 113 insertions(+), 75 deletions(-) diff --git a/sound/soc/apple/mca.c b/sound/soc/apple/mca.c index a36266b1aa080..e11ee21dd452a 100644 --- a/sound/soc/apple/mca.c +++ b/sound/soc/apple/mca.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -137,7 +138,6 @@ struct mca_cluster { struct mca_data *host; struct device *pd_dev; struct clk *clk_parent; - struct dma_chan *dma_chans[SNDRV_PCM_STREAM_LAST + 1]; bool clk_provider; @@ -152,8 +152,10 @@ struct mca_cluster { unsigned int bclk_ratio; - /* RX bit start of the DAI format, once set_fmt has run */ + /* DAI format state cached from set_fmt and applied in hw_params */ bool fmt_set; + u32 serdes_bclk_pol; + u32 tx_bitstart; u32 rx_bitstart; /* BCLKs by which data received on this cluster's port arrives late */ u32 rx_delay; @@ -472,6 +474,11 @@ static int mca_configure_serdes(struct mca_cluster *cl, int serdes_unit, goto err; } + if (cl->fmt_set) { + serdes_conf_mask |= SERDES_CONF_BCLK_POL; + serdes_conf |= cl->serdes_bclk_pol; + } + serdes_conf_mask |= SERDES_CONF_SYNC_SEL; serdes_conf |= FIELD_PREP(SERDES_CONF_SYNC_SEL, cl->no + 1); @@ -606,14 +613,8 @@ static int mca_fe_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) if (!fpol_inv) goto err; - mca_modify(cl, CLUSTER_TX_OFF + REG_TX_SERDES_CONF, - SERDES_CONF_BCLK_POL, serdes_conf); - mca_modify(cl, CLUSTER_RX_OFF + REG_RX_SERDES_CONF, - SERDES_CONF_BCLK_POL, serdes_conf); - writel_relaxed(bitstart, - cl->base + CLUSTER_TX_OFF + REG_TX_SERDES_BITSTART); - writel_relaxed(bitstart, - cl->base + CLUSTER_RX_OFF + REG_RX_SERDES_BITSTART); + cl->serdes_bclk_pol = serdes_conf; + cl->tx_bitstart = bitstart; cl->rx_bitstart = bitstart; cl->fmt_set = true; @@ -718,10 +719,15 @@ static int mca_fe_hw_params(struct snd_pcm_substream *substream, if (ret) return ret; - /* Sample late data as late as the slowest port it comes from */ - if (!is_tx && cl->fmt_set) - writel_relaxed(cl->rx_bitstart + mca_ports_rx_delay(mca, portmask), - cl->base + CLUSTER_RX_OFF + REG_RX_SERDES_BITSTART); + if (cl->fmt_set) { + if (is_tx) + writel_relaxed(cl->tx_bitstart, + cl->base + CLUSTER_TX_OFF + REG_TX_SERDES_BITSTART); + else + /* Sample late data as late as the slowest port it comes from */ + writel_relaxed(cl->rx_bitstart + mca_ports_rx_delay(mca, portmask), + cl->base + CLUSTER_RX_OFF + REG_RX_SERDES_BITSTART); + } pad = 32 - params_width(params); @@ -870,11 +876,24 @@ static int mca_be_startup(struct snd_pcm_substream *substream, struct mca_cluster *cl = mca_dai_to_cluster(dai); struct mca_cluster *fe_cl; struct mca_data *mca = cl->host; + int ret; if (!fe) return -EINVAL; fe_cl = mca_dai_to_cluster(snd_soc_rtd_to_cpu(fe, 0)); + /* + * If the port is already started in the other direction, make sure + * there isn't a conflict with another cluster driving the port clocks. + */ + if (fe_cl->clk_provider && mca_be_clk_started(cl) && + cl->port_clk_driver != fe_cl->no) + return -EINVAL; + + ret = pm_runtime_resume_and_get(mca->dev); + if (ret < 0) + return ret; + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { writel_relaxed(PORT_DATA_SEL_TXA(fe_cl->no), cl->base + REG_PORT_DATA_SEL); @@ -886,14 +905,6 @@ static int mca_be_startup(struct snd_pcm_substream *substream, return 0; if (mca_be_clk_started(cl)) { - /* - * Port is already started in the other direction. - * Make sure there isn't a conflict with another cluster - * driving the port clocks. - */ - if (cl->port_clk_driver != fe_cl->no) - return -EINVAL; - cl->port_clk_started[substream->stream] = true; return 0; } @@ -940,7 +951,7 @@ static void mca_be_shutdown(struct snd_pcm_substream *substream, } if (!fe) - return; + goto out; fe_cl = mca_dai_to_cluster(snd_soc_rtd_to_cpu(fe, 0)); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { @@ -949,7 +960,7 @@ static void mca_be_shutdown(struct snd_pcm_substream *substream, } if (!fe_cl->clk_provider) - return; + goto out; cl->port_clk_started[substream->stream] = false; if (!mca_be_clk_started(cl)) { @@ -961,8 +972,11 @@ static void mca_be_shutdown(struct snd_pcm_substream *substream, writel_relaxed(0, cl->base + REG_PORT_CLOCK_SEL); scoped_guard(mutex, &mca->port_mutex) cl->port_clk_driver = -1; - } + +out: + pm_runtime_mark_last_busy(mca->dev); + pm_runtime_put_autosuspend(mca->dev); } static const struct snd_soc_dai_ops mca_be_ops = { @@ -1020,22 +1034,58 @@ static int mca_set_runtime_hwparams(struct snd_soc_component *component, return snd_soc_set_runtime_hwparams(substream, &hw); } +static struct dma_chan *mca_request_dma_channel(struct mca_cluster *cl, + unsigned int stream) +{ + bool is_tx = (stream == SNDRV_PCM_STREAM_PLAYBACK); + char name[16]; + +#ifndef USE_RXB_FOR_CAPTURE + snprintf(name, sizeof(name), is_tx ? "tx%da" : "rx%da", cl->no); +#else + snprintf(name, sizeof(name), is_tx ? "tx%da" : "rx%db", cl->no); +#endif + return of_dma_request_slave_channel(cl->host->dev->of_node, name); +} + static int mca_pcm_open(struct snd_soc_component *component, struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct mca_cluster *cl = mca_dai_to_cluster(snd_soc_rtd_to_cpu(rtd, 0)); - struct dma_chan *chan = cl->dma_chans[substream->stream]; + struct mca_data *mca = cl->host; + struct dma_chan *chan; int ret; if (rtd->dai_link->no_pcm) return 0; + ret = pm_runtime_resume_and_get(mca->dev); + if (ret < 0) + return ret; + + chan = mca_request_dma_channel(cl, substream->stream); + if (IS_ERR_OR_NULL(chan)) { + ret = chan ? PTR_ERR(chan) : -EINVAL; + goto err_rpm_put; + } + ret = mca_set_runtime_hwparams(component, substream, chan); if (ret) - return ret; + goto err_release_chan; + + ret = snd_dmaengine_pcm_open(substream, chan); + if (ret) + goto err_release_chan; - return snd_dmaengine_pcm_open(substream, chan); + return 0; + +err_release_chan: + dma_release_channel(chan); +err_rpm_put: + pm_runtime_mark_last_busy(mca->dev); + pm_runtime_put_autosuspend(mca->dev); + return ret; } static int mca_hw_params(struct snd_soc_component *component, @@ -1070,11 +1120,18 @@ static int mca_close(struct snd_soc_component *component, struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct mca_cluster *cl = mca_dai_to_cluster(snd_soc_rtd_to_cpu(rtd, 0)); + struct mca_data *mca = cl->host; + int ret; if (rtd->dai_link->no_pcm) return 0; - return snd_dmaengine_pcm_close(substream); + ret = snd_dmaengine_pcm_close_release_chan(substream); + pm_runtime_mark_last_busy(mca->dev); + pm_runtime_put_autosuspend(mca->dev); + + return ret; } /* @@ -1210,43 +1267,6 @@ static snd_pcm_uframes_t mca_pointer(struct snd_soc_component *component, return pos; } -static struct dma_chan *mca_request_dma_channel(struct mca_cluster *cl, unsigned int stream) -{ - bool is_tx = (stream == SNDRV_PCM_STREAM_PLAYBACK); -#ifndef USE_RXB_FOR_CAPTURE - char *name = devm_kasprintf(cl->host->dev, GFP_KERNEL, - is_tx ? "tx%da" : "rx%da", cl->no); -#else - char *name = devm_kasprintf(cl->host->dev, GFP_KERNEL, - is_tx ? "tx%da" : "rx%db", cl->no); -#endif - return of_dma_request_slave_channel(cl->host->dev->of_node, name); - -} - -static void mca_pcm_free(struct snd_soc_component *component, - struct snd_pcm *pcm) -{ - struct snd_soc_pcm_runtime *rtd = snd_pcm_chip(pcm); - struct mca_cluster *cl = mca_dai_to_cluster(snd_soc_rtd_to_cpu(rtd, 0)); - unsigned int i; - - if (rtd->dai_link->no_pcm) - return; - - for_each_pcm_streams(i) { - struct snd_pcm_substream *substream = - rtd->pcm->streams[i].substream; - - if (!substream || !cl->dma_chans[i]) - continue; - - dma_release_channel(cl->dma_chans[i]); - cl->dma_chans[i] = NULL; - } -} - - static int mca_pcm_new(struct snd_soc_component *component, struct snd_soc_pcm_runtime *rtd) { @@ -1265,10 +1285,7 @@ static int mca_pcm_new(struct snd_soc_component *component, continue; chan = mca_request_dma_channel(cl, i); - if (IS_ERR_OR_NULL(chan)) { - mca_pcm_free(component, rtd->pcm); - if (chan && PTR_ERR(chan) == -EPROBE_DEFER) return PTR_ERR(chan); @@ -1280,7 +1297,6 @@ static int mca_pcm_new(struct snd_soc_component *component, return PTR_ERR(chan); } - cl->dma_chans[i] = chan; /* * Capture is read by the CPU: cacheable, synced in mca_pointer(). * Allocated at hw_params to the buffer's own size, as ALSA syncs @@ -1293,6 +1309,7 @@ static int mca_pcm_new(struct snd_soc_component *component, snd_pcm_set_managed_buffer(substream, SNDRV_DMA_TYPE_DEV_IRAM, chan->device->dev, MCA_BUFFER_BYTES_MAX, SIZE_MAX); + dma_release_channel(chan); } return 0; @@ -1306,7 +1323,6 @@ static const struct snd_soc_component_driver mca_component = { .trigger = mca_trigger, .pointer = mca_pointer, .pcm_new = mca_pcm_new, - .pcm_free = mca_pcm_free, }; static void apple_mca_release(struct mca_data *mca) @@ -1376,9 +1392,24 @@ static int apple_mca_probe(struct platform_device *pdev) if (!dai_drivers) return -ENOMEM; + pm_runtime_get_noresume(&pdev->dev); + pm_runtime_set_active(&pdev->dev); + pm_runtime_set_autosuspend_delay(&pdev->dev, 200); + pm_runtime_use_autosuspend(&pdev->dev); + ret = devm_pm_runtime_enable(&pdev->dev); + if (ret) { + pm_runtime_dont_use_autosuspend(&pdev->dev); + pm_runtime_put_noidle(&pdev->dev); + return ret; + } + mca->pd_dev = dev_pm_domain_attach_by_id(&pdev->dev, 0); - if (IS_ERR(mca->pd_dev)) - return -EINVAL; + if (IS_ERR(mca->pd_dev)) { + ret = -EINVAL; + /* Prevent an unbalanced reset rearm */ + mca->rstc = NULL; + goto err_release; + } mca->pd_link = device_link_add(&pdev->dev, mca->pd_dev, DL_FLAG_STATELESS | DL_FLAG_PM_RUNTIME | @@ -1487,10 +1518,15 @@ static int apple_mca_probe(struct platform_device *pdev) goto err_release; } + pm_runtime_mark_last_busy(&pdev->dev); + pm_runtime_put_autosuspend(&pdev->dev); + return 0; err_release: + pm_runtime_dont_use_autosuspend(&pdev->dev); apple_mca_release(mca); + pm_runtime_put_noidle(&pdev->dev); return ret; } @@ -1499,6 +1535,8 @@ static void apple_mca_remove(struct platform_device *pdev) struct mca_data *mca = platform_get_drvdata(pdev); snd_soc_unregister_component(&pdev->dev); + pm_runtime_dont_use_autosuspend(&pdev->dev); + pm_runtime_barrier(&pdev->dev); apple_mca_release(mca); } @@ -1570,7 +1608,7 @@ static int __maybe_unused apple_mca_suspend_late(struct device *dev) struct mca_data *mca = dev_get_drvdata(dev); int i, j, n = 0; - if (!pm_suspend_via_firmware()) + if (!pm_suspend_via_firmware() || pm_runtime_status_suspended(dev)) return 0; for (i = 0; i < mca->nclusters; i++) { @@ -1603,7 +1641,7 @@ static int __maybe_unused apple_mca_resume_early(struct device *dev) struct mca_data *mca = dev_get_drvdata(dev); int i, j, n = 0; - if (!pm_resume_via_firmware()) + if (!pm_resume_via_firmware() || pm_runtime_status_suspended(dev)) return 0; for (i = 0; i < mca->nclusters; i++) { From e5a7623da91c9d112cb890674b2b62cde6e17158 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 13:27:13 -0500 Subject: [PATCH 3/9] arm64: dts: apple: t8103: parent ps_fpwm0..2 under ps_sio FPWM0..2 sit behind the SIO fabric on T8103, matching t600x, t8112, t602x, t6030, t6040, and t8140. Without power-domains = <&ps_sio>, letting ps_sio power down at runtime idle allows pwm_apple (for example during led_pwm_shutdown() on reboot) to write FPWM MMIO registers with the SIO fabric powered off, triggering an asynchronous SError in apple_pwm_apply(). Parent ps_fpwm0, ps_fpwm1, and ps_fpwm2 under ps_sio so active PWM users hold ps_sio up while idle PWM (duty cycle 0) lets ps_fpwm* and ps_sio suspend together. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103-pmgr.dtsi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi index c3230cd4bb81a..ebf39a29d7425 100644 --- a/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi @@ -243,6 +243,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "fpwm0"; + power-domains = <&ps_sio>; }; ps_fpwm1: power-controller@1e0 { @@ -251,6 +252,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "fpwm1"; + power-domains = <&ps_sio>; }; ps_fpwm2: power-controller@1e8 { @@ -259,6 +261,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "fpwm2"; + power-domains = <&ps_sio>; }; ps_i2c0: power-controller@1f0 { From 457a940bfff4574219bc6954009243286010e9ae Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 13:27:13 -0500 Subject: [PATCH 4/9] dmaengine: apple-sio: hold runtime PM across issued transfers sio_device_config() drops its temporary runtime PM reference on return, so a client calling sio_issue_pending() after the 500 ms autosuspend delay could publish descriptors while SIO firmware is stopped or mid-suspend. Track a per-channel transfer runtime PM reference (tx_rpm_held) held while current_tx is active: - Acquire it in atomic context via pm_runtime_get_if_active() when SIO is active; otherwise keep the descriptor on vc.desc_issued and defer activation to sio_issue_work(), which calls pm_runtime_resume_and_get() before publishing. - Guard sio_fill_in_old_locked() and sio_fill_in_ring_locked() against rpm_stopped, mark channels with tx_rpm_held or queued vc.desc_issued entries busy in sio_chan_busy(), and flush issue_wq before terminate_wq in sio_synchronize(). - Release tx_rpm_held when current_tx clears without a queued successor (in ring-to-idle handover and sio_terminate_work()). - Add KUnit coverage for issuing after autosuspend, draining deferred descriptors, busy accounting, and ring handover PM release. Signed-off-by: Erik Bourget --- drivers/dma/apple-sio-boot-test.c | 98 +++++++++++++++++++++++++ drivers/dma/apple-sio.c | 116 +++++++++++++++++++++++++++--- 2 files changed, 205 insertions(+), 9 deletions(-) diff --git a/drivers/dma/apple-sio-boot-test.c b/drivers/dma/apple-sio-boot-test.c index 5994518f619b0..64870f2b0fef5 100644 --- a/drivers/dma/apple-sio-boot-test.c +++ b/drivers/dma/apple-sio-boot-test.c @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Included by apple-sio.c: exercise protocol-9 publication and ACK failures. */ +#include #include struct sio_boot_test { @@ -196,6 +197,7 @@ static void sio_sleep_busy_test(struct kunit *test) KUNIT_ASSERT_NOT_NULL(test, chan); KUNIT_ASSERT_NOT_NULL(test, tx); spin_lock_init(&chan->vc.lock); + INIT_LIST_HEAD(&chan->vc.desc_issued); KUNIT_EXPECT_FALSE(test, sio_chan_busy(chan)); chan->current_tx = tx; @@ -207,9 +209,104 @@ static void sio_sleep_busy_test(struct kunit *test) chan->ring = true; KUNIT_EXPECT_TRUE(test, sio_chan_busy(chan)); chan->ring = false; + chan->tx_rpm_held = true; + KUNIT_EXPECT_TRUE(test, sio_chan_busy(chan)); + chan->tx_rpm_held = false; + list_add_tail(&tx->vd.node, &chan->vc.desc_issued); + KUNIT_EXPECT_TRUE(test, sio_chan_busy(chan)); + list_del_init(&tx->vd.node); KUNIT_EXPECT_FALSE(test, sio_chan_busy(chan)); } +static void sio_test_noop_desc_free(struct virt_dma_desc *vd) +{ +} + +static void sio_test_pm_runtime_disable(void *dev) +{ + pm_runtime_disable(dev); +} + +/* + * Issuing a descriptor after SIO runtime-suspends must not publish to stopped + * firmware; it stays queued until resume, and terminate/synchronize drains it + * and releases any held transfer runtime PM reference. + */ +static void sio_issue_pending_after_autosuspend_test(struct kunit *test) +{ + struct device *dev = kunit_device_register(test, "apple-sio-rpm-test"); + struct sio_data *sio; + struct sio_chan *chan; + struct sio_tx *tx, *idle_tx; + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + sio = kunit_kzalloc(test, struct_size(sio, channels, 1), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sio); + tx = kunit_kzalloc(test, sizeof(*tx), GFP_KERNEL); + idle_tx = kunit_kzalloc(test, sizeof(*idle_tx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, tx); + KUNIT_ASSERT_NOT_NULL(test, idle_tx); + + sio->dev = dev; + sio->nchannels = 1; + WRITE_ONCE(sio->rpm_stopped, true); + INIT_LIST_HEAD(&sio->dma.channels); + + chan = &sio->channels[0]; + chan->host = sio; + chan->no = 0; + chan->configured = true; + chan->vc.desc_free = sio_test_noop_desc_free; + tx->vd.tx.chan = &chan->vc.chan; + idle_tx->vd.tx.chan = &chan->vc.chan; + INIT_WORK(&chan->issue_wq, sio_issue_work); + INIT_WORK(&chan->terminate_wq, sio_terminate_work); + INIT_LIST_HEAD(&chan->retired); + INIT_LIST_HEAD(&chan->dead); + init_waitqueue_head(&chan->drained); + vchan_init(&chan->vc, &sio->dma); + + pm_runtime_set_suspended(dev); + pm_runtime_enable(dev); + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, sio_test_pm_runtime_disable, dev), + 0); + + /* Queue a submitted descriptor and issue while firmware is stopped. */ + list_add_tail(&tx->vd.node, &chan->vc.desc_submitted); + sio_issue_pending(&chan->vc.chan); + flush_work(&chan->issue_wq); + + KUNIT_EXPECT_NULL(test, chan->current_tx); + KUNIT_EXPECT_FALSE(test, chan->tx_rpm_held); + KUNIT_EXPECT_TRUE(test, sio_chan_busy(chan)); + KUNIT_EXPECT_TRUE(test, bitmap_empty(sio->tags.allocated, SIO_NTAGS)); + KUNIT_EXPECT_EQ(test, atomic_read(&dev->power.usage_count), 0); + + /* Terminating drains the deferred descriptor cleanly. */ + KUNIT_EXPECT_EQ(test, sio_terminate_all(&chan->vc.chan), 0); + sio_synchronize(&chan->vc.chan); + KUNIT_EXPECT_FALSE(test, sio_chan_busy(chan)); + KUNIT_EXPECT_EQ(test, atomic_read(&dev->power.usage_count), 0); + + /* Ring handover to an idle transfer releases the active transfer PM ref. */ + pm_runtime_get_noresume(dev); + chan->ring = true; + chan->idle = idle_tx; + chan->current_tx = tx; + chan->tx_rpm_held = true; + tx->vd.tx.cookie = DMA_MIN_COOKIE; + tx->terminated = false; + KUNIT_EXPECT_EQ(test, sio_terminate_all(&chan->vc.chan), 0); + KUNIT_EXPECT_NULL(test, chan->current_tx); + KUNIT_EXPECT_FALSE(test, chan->tx_rpm_held); + KUNIT_EXPECT_EQ(test, atomic_read(&dev->power.usage_count), 0); + chan->idle = NULL; + chan->ring = false; + INIT_LIST_HEAD(&chan->dead); + INIT_LIST_HEAD(&chan->retired); +} + static struct kunit_case sio_boot_test_cases[] = { KUNIT_CASE(sio_boot_order_test), KUNIT_CASE(sio_boot_optional_tables_test), @@ -217,6 +314,7 @@ static struct kunit_case sio_boot_test_cases[] = { KUNIT_CASE(sio_boot_control_ack_failure_test), KUNIT_CASE(sio_boot_dma_arrays_test), KUNIT_CASE(sio_sleep_busy_test), + KUNIT_CASE(sio_issue_pending_after_autosuspend_test), {} }; diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 044f4ad528707..5a36259048c72 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -109,12 +109,15 @@ struct sio_chan { unsigned int no; struct sio_data *host; struct virt_dma_chan vc; + struct work_struct issue_wq; struct work_struct terminate_wq; bool configured; struct sio_shmem_chan_config cfg; struct sio_tx *current_tx; + /* Holds a runtime PM reference while current_tx is active. */ + bool tx_rpm_held; /* * Until a client sets an idle transfer, the channel keeps the old @@ -1104,7 +1107,8 @@ static bool sio_fill_in_old_locked(struct sio_chan *siochan) struct sio_coproc_desc *d = tx->siodesc[tx->next]; int ret; - if (tx->ninflight >= SIO_MAX_NINFLIGHT || tx->terminated) + if (READ_ONCE(sio->rpm_stopped) || + tx->ninflight >= SIO_MAX_NINFLIGHT || tx->terminated) return false; static_assert(sizeof(dma_cookie_t) <= sizeof(void *)); @@ -1128,8 +1132,8 @@ static bool sio_fill_in_ring_locked(struct sio_chan *siochan) struct sio_coproc_desc *d; int ret; - if (!tx || siochan->issuing || siochan->stopping || - siochan->nissued >= SIO_MAX_NINFLIGHT) + if (READ_ONCE(sio->rpm_stopped) || !tx || siochan->issuing || + siochan->stopping || siochan->nissued >= SIO_MAX_NINFLIGHT) return false; d = tx->siodesc[tx->next]; @@ -1166,15 +1170,80 @@ static void sio_update_current_tx_locked(struct sio_chan *siochan) } } +static void sio_issue_work(struct work_struct *wq) +{ + struct sio_chan *siochan = container_of(wq, struct sio_chan, issue_wq); + struct sio_data *sio = siochan->host; + unsigned long flags; + bool need_start; + bool put_rpm = true; + int ret; + + spin_lock_irqsave(&siochan->vc.lock, flags); + need_start = !siochan->current_tx && vchan_next_desc(&siochan->vc); + spin_unlock_irqrestore(&siochan->vc.lock, flags); + if (!need_start) + return; + + ret = pm_runtime_resume_and_get(sio->dev); + if (ret < 0) { + dev_err(sio->dev, "runtime resume before issue on chan %d failed: %d\n", + siochan->no, ret); + return; + } + + spin_lock_irqsave(&siochan->vc.lock, flags); + if (!siochan->current_tx && vchan_next_desc(&siochan->vc) && + !READ_ONCE(sio->rpm_stopped)) { + if (!siochan->tx_rpm_held) { + siochan->tx_rpm_held = true; + put_rpm = false; + } + sio_update_current_tx_locked(siochan); + } + spin_unlock_irqrestore(&siochan->vc.lock, flags); + + if (put_rpm) { + pm_runtime_mark_last_busy(sio->dev); + pm_runtime_put_autosuspend(sio->dev); + } +} + static void sio_issue_pending(struct dma_chan *chan) { struct sio_chan *siochan = to_sio_chan(chan); + struct sio_data *sio = siochan->host; unsigned long flags; + bool defer = false; spin_lock_irqsave(&siochan->vc.lock, flags); vchan_issue_pending(&siochan->vc); - sio_update_current_tx_locked(siochan); + if (!siochan->current_tx && vchan_next_desc(&siochan->vc)) { + if (siochan->tx_rpm_held) { + if (READ_ONCE(sio->rpm_stopped)) + defer = true; + else + sio_update_current_tx_locked(siochan); + } else if (!IS_ENABLED(CONFIG_PM)) { + if (!READ_ONCE(sio->rpm_stopped)) + sio_update_current_tx_locked(siochan); + } else { + int ret = pm_runtime_get_if_active(sio->dev); + + if (ret > 0 && !READ_ONCE(sio->rpm_stopped)) { + siochan->tx_rpm_held = true; + sio_update_current_tx_locked(siochan); + } else { + if (ret > 0) + pm_runtime_put_noidle(sio->dev); + defer = true; + } + } + } spin_unlock_irqrestore(&siochan->vc.lock, flags); + + if (defer) + schedule_work(&siochan->issue_wq); } static int sio_terminate_all(struct dma_chan *chan) @@ -1182,6 +1251,7 @@ static int sio_terminate_all(struct dma_chan *chan) struct sio_chan *siochan = to_sio_chan(chan); struct sio_tx *tx; unsigned long flags; + bool put_rpm = false; LIST_HEAD(to_free); spin_lock_irqsave(&siochan->vc.lock, flags); @@ -1198,6 +1268,10 @@ static int sio_terminate_all(struct dma_chan *chan) if (siochan->vc.cyclic == &tx->vd) siochan->vc.cyclic = NULL; siochan->current_tx = NULL; + if (siochan->tx_rpm_held) { + siochan->tx_rpm_held = false; + put_rpm = true; + } /* Its callback may be running: sio_free_dead() frees it. */ if (sio_tx_quiet_locked(siochan, tx)) { list_add_tail(&tx->vd.node, &siochan->dead); @@ -1215,6 +1289,11 @@ static int sio_terminate_all(struct dma_chan *chan) vchan_get_all_descriptors(&siochan->vc, &to_free); spin_unlock_irqrestore(&siochan->vc.lock, flags); + if (put_rpm) { + pm_runtime_mark_last_busy(siochan->host->dev); + pm_runtime_put_autosuspend(siochan->host->dev); + } + vchan_dma_desc_free_list(&siochan->vc, &to_free); return 0; @@ -1226,6 +1305,7 @@ static void sio_terminate_work(struct work_struct *wq) struct sio_data *sio = siochan->host; struct sio_tx *tx; unsigned long flags; + bool put_tx_rpm = false; bool resumed; int ret; @@ -1259,10 +1339,25 @@ static void sio_terminate_work(struct work_struct *wq) WARN_ON(siochan->current_tx != tx); siochan->current_tx = NULL; sio_scrub_locked(siochan, tx); - sio_update_current_tx_locked(siochan); + if (resumed && !READ_ONCE(sio->rpm_stopped) && + vchan_next_desc(&siochan->vc)) { + if (!siochan->tx_rpm_held && IS_ENABLED(CONFIG_PM)) { + siochan->tx_rpm_held = true; + resumed = false; + } + sio_update_current_tx_locked(siochan); + } else if (siochan->tx_rpm_held) { + siochan->tx_rpm_held = false; + put_tx_rpm = true; + } sio_ring_leave_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); + if (put_tx_rpm) { + pm_runtime_mark_last_busy(sio->dev); + pm_runtime_put_autosuspend(sio->dev); + } + if (resumed) { pm_runtime_mark_last_busy(sio->dev); pm_runtime_put_autosuspend(sio->dev); @@ -1391,6 +1486,7 @@ static void sio_synchronize(struct dma_chan *chan) { struct sio_chan *siochan = to_sio_chan(chan); + flush_work(&siochan->issue_wq); flush_work(&siochan->terminate_wq); if (READ_ONCE(siochan->ring)) { /* The caller frees the buffer on return; nothing can stop that. */ @@ -2196,6 +2292,7 @@ static int sio_probe(struct platform_device *pdev) siochan->host = sio; siochan->no = i; siochan->vc.desc_free = sio_tx_free; + INIT_WORK(&siochan->issue_wq, sio_issue_work); INIT_WORK(&siochan->terminate_wq, sio_terminate_work); INIT_LIST_HEAD(&siochan->retired); INIT_LIST_HEAD(&siochan->dead); @@ -2323,7 +2420,8 @@ static bool sio_chan_busy(struct sio_chan *siochan) spin_lock_irqsave(&siochan->vc.lock, flags); busy = siochan->current_tx || siochan->idle || siochan->ring || - siochan->pending; + siochan->pending || siochan->tx_rpm_held || + !list_empty(&siochan->vc.desc_issued); spin_unlock_irqrestore(&siochan->vc.lock, flags); return busy; @@ -2360,7 +2458,7 @@ static __maybe_unused int sio_suspend(struct device *dev) dev_err(dev, "firmware did not come back\n"); return ret; } - sio->rpm_stopped = true; + WRITE_ONCE(sio->rpm_stopped, true); return 0; } @@ -2370,7 +2468,7 @@ static __maybe_unused int sio_resume(struct device *dev) struct sio_data *sio = dev_get_drvdata(dev); int ret; - if (!sio->rpm_stopped) + if (!READ_ONCE(sio->rpm_stopped)) return 0; /* @@ -2391,7 +2489,7 @@ static __maybe_unused int sio_resume(struct device *dev) dev_err(dev, "firmware did not come back from runtime suspend: %d\n", ret); return ret; } - sio->rpm_stopped = false; + WRITE_ONCE(sio->rpm_stopped, false); return 0; } From 4295db09de607ec485b815b20ce963690f209c54 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 14:32:57 -0500 Subject: [PATCH 5/9] dmaengine: apple-sio: harden runtime PM transfer lifecycle, teardown, and error reporting Harden the apple-sio transfer runtime PM lifecycle, teardown ordering, and aborted-descriptor reporting on top of the active-transfer reference tracking: - Gate descriptor publication on firmware being active (!rpm_stopped && !asleep) via sio_firmware_active(), and release tx_rpm_held across all quiet paths (issue ACK, report processing, stop_quiet, clear_idle, terminate_all, and terminate_work) once current_tx, non-idle ring state, retired list, and pending ACKs are clear. - Check READ_ONCE(sio->removing) under vc.lock before vchan_issue_pending() in sio_issue_pending() and in sio_prep_dma_cyclic() so late issue calls after teardown admission closes neither move submitted descriptors to desc_issued nor invoke vchan_cookie_complete() to rearm vc.task. - In sio_remove(), close admission under vc.lock, cancel issue_wq, flush terminate_wq before and after unregistering the DMA provider, refuse new runtime suspends and quiesce runtime PM via pm_runtime_dont_use_autosuspend() + pm_runtime_barrier(), and shut down/disable RTKit mailbox RX (apple_rtkit_shutdown() when sio->arrays is present, plus apple_rtkit_mailbox_off()) before the final drain and tasklet_kill(). - Abort deferred vc.desc_issued descriptors with DMA_TRANS_ABORTED on resume/RPM failure or teardown instead of stranding them, and record each aborted cookie with its exact u32 residue in a bounded 16-entry FIFO ring (siochan->error_cookies) preserved across subsequent healthy transfers until cookie reuse or channel resource release. Signed-off-by: Erik Bourget --- drivers/dma/apple-sio.c | 388 +++++++++++++++++++++++++++++++--------- 1 file changed, 306 insertions(+), 82 deletions(-) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 5a36259048c72..cce06c04538a9 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -105,6 +105,13 @@ struct sio_shmem_chan_config { struct sio_data; struct sio_tx; +#define SIO_MAX_ERROR_COOKIES 16 + +struct sio_error_cookie { + dma_cookie_t cookie; + u32 residue; +}; + struct sio_chan { unsigned int no; struct sio_data *host; @@ -116,8 +123,10 @@ struct sio_chan { struct sio_shmem_chan_config cfg; struct sio_tx *current_tx; - /* Holds a runtime PM reference while current_tx is active. */ + /* Holds a runtime PM reference across active or pending channel work. */ bool tx_rpm_held; + struct sio_error_cookie error_cookies[SIO_MAX_ERROR_COOKIES]; + unsigned int error_head; /* * Until a client sets an idle transfer, the channel keeps the old @@ -193,6 +202,9 @@ struct sio_data { bool asleep; /* The firmware is stopped while runtime-suspended. */ bool rpm_stopped; + bool removing; + bool rtk_stopped; + bool rtk_shutdown_failed; bool firmware_only; /* Protocol 10 firmware given the earlier boot tables: no DMA, which would crash it */ bool tables_mismatch; @@ -883,7 +895,8 @@ static struct dma_async_tx_descriptor *sio_prep_dma_cyclic( struct sio_chan *siochan = to_sio_chan(chan); struct sio_tx *siotx; - if (siochan->host->tables_mismatch || + if (READ_ONCE(siochan->host->removing) || + siochan->host->tables_mismatch || direction != sio_chan_direction(siochan->no)) return NULL; @@ -894,6 +907,62 @@ static struct dma_async_tx_descriptor *sio_prep_dma_cyclic( return vchan_tx_prep(&siochan->vc, &siotx->vd, flags); } +static void sio_record_error_locked(struct sio_chan *siochan, + dma_cookie_t cookie, u32 residue) +{ + unsigned int i; + + if (cookie < DMA_MIN_COOKIE) + return; + + for (i = 0; i < ARRAY_SIZE(siochan->error_cookies); i++) { + if (siochan->error_cookies[i].cookie == cookie) { + siochan->error_cookies[i].residue = residue; + return; + } + } + + /* Bounded FIFO ring: evict the oldest recorded failure when full. */ + siochan->error_cookies[siochan->error_head].cookie = cookie; + siochan->error_cookies[siochan->error_head].residue = residue; + siochan->error_head = (siochan->error_head + 1) % + ARRAY_SIZE(siochan->error_cookies); +} + +static void sio_clear_error_locked(struct sio_chan *siochan, + dma_cookie_t cookie) +{ + unsigned int i; + + if (cookie < DMA_MIN_COOKIE) + return; + + for (i = 0; i < ARRAY_SIZE(siochan->error_cookies); i++) { + if (siochan->error_cookies[i].cookie == cookie) { + siochan->error_cookies[i].cookie = 0; + siochan->error_cookies[i].residue = 0; + return; + } + } +} + +static bool sio_lookup_error_locked(const struct sio_chan *siochan, + dma_cookie_t cookie, u32 *residue) +{ + unsigned int i; + + if (cookie < DMA_MIN_COOKIE) + return false; + + for (i = 0; i < ARRAY_SIZE(siochan->error_cookies); i++) { + if (siochan->error_cookies[i].cookie == cookie) { + *residue = siochan->error_cookies[i].residue; + return true; + } + } + return false; +} + static enum dma_status sio_tx_status(struct dma_chan *chan, dma_cookie_t cookie, struct dma_tx_state *txstate) { @@ -906,7 +975,19 @@ static enum dma_status sio_tx_status(struct dma_chan *chan, dma_cookie_t cookie, size_t residue; ret = dma_cookie_status(chan, cookie, txstate); - if (ret == DMA_COMPLETE || !txstate) + if (ret == DMA_COMPLETE) { + u32 err_residue; + + spin_lock_irqsave(&siochan->vc.lock, flags); + if (sio_lookup_error_locked(siochan, cookie, &err_residue)) { + ret = DMA_ERROR; + if (txstate) + dma_set_residue(txstate, err_residue); + } + spin_unlock_irqrestore(&siochan->vc.lock, flags); + return ret; + } + if (!txstate) return ret; spin_lock_irqsave(&siochan->vc.lock, flags); @@ -1087,16 +1168,72 @@ static void sio_ring_issue_ack_locked(struct sio_chan *siochan, bool ok) sio_fill_in_locked(siochan); } +static bool sio_firmware_active(const struct sio_data *sio) +{ + return !READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->asleep); +} + +static bool sio_chan_tx_busy_locked(const struct sio_chan *siochan) +{ + return siochan->current_tx || !list_empty(&siochan->retired) || + (siochan->ring && !siochan->idle) || siochan->pending; +} + +static int sio_try_get_tx_pm_locked(struct sio_chan *siochan) +{ + struct sio_data *sio = siochan->host; + int ret; + + if (siochan->tx_rpm_held) + return sio_firmware_active(sio) ? 1 : 0; + + ret = pm_runtime_get_if_active(sio->dev); + if (ret > 0) { + if (!sio_firmware_active(sio)) { + pm_runtime_put_noidle(sio->dev); + return 0; + } + siochan->tx_rpm_held = true; + return 1; + } + if (ret < 0) + return (!IS_ENABLED(CONFIG_PM) && sio_firmware_active(sio)) ? 1 : ret; + + return 0; +} + +static bool sio_take_tx_pm_put_locked(struct sio_chan *siochan) +{ + if (!siochan->tx_rpm_held || sio_chan_tx_busy_locked(siochan)) + return false; + siochan->tx_rpm_held = false; + return true; +} + +static void sio_put_tx_pm(struct sio_chan *siochan, bool put) +{ + if (put) { + pm_runtime_mark_last_busy(siochan->host->dev); + pm_runtime_put_autosuspend(siochan->host->dev); + } +} + static void sio_handle_issue_ack(struct sio_chan *siochan, void *cookie, bool ok) { unsigned long flags; + bool put_pm; spin_lock_irqsave(&siochan->vc.lock, flags); - if (siochan->ring) + if (siochan->ring) { sio_ring_issue_ack_locked(siochan, ok); - else + sio_ring_leave_locked(siochan); + } else { sio_old_issue_ack_locked(siochan, (unsigned long)cookie, ok); + } + put_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); + + sio_put_tx_pm(siochan, put_pm); } /* The old accounting: the current transfer's next descriptor */ @@ -1107,8 +1244,8 @@ static bool sio_fill_in_old_locked(struct sio_chan *siochan) struct sio_coproc_desc *d = tx->siodesc[tx->next]; int ret; - if (READ_ONCE(sio->rpm_stopped) || - tx->ninflight >= SIO_MAX_NINFLIGHT || tx->terminated) + if (!sio_firmware_active(sio) || tx->ninflight >= SIO_MAX_NINFLIGHT || + tx->terminated) return false; static_assert(sizeof(dma_cookie_t) <= sizeof(void *)); @@ -1132,7 +1269,7 @@ static bool sio_fill_in_ring_locked(struct sio_chan *siochan) struct sio_coproc_desc *d; int ret; - if (READ_ONCE(sio->rpm_stopped) || !tx || siochan->issuing || + if (!sio_firmware_active(sio) || !tx || siochan->issuing || siochan->stopping || siochan->nissued >= SIO_MAX_NINFLIGHT) return false; @@ -1163,87 +1300,111 @@ static void sio_update_current_tx_locked(struct sio_chan *siochan) { struct virt_dma_desc *vd = vchan_next_desc(&siochan->vc); - if (vd && !siochan->current_tx) { + if (vd && !siochan->current_tx && !READ_ONCE(siochan->host->removing) && + sio_firmware_active(siochan->host)) { list_del(&vd->node); + /* Retire any stale wrapped-around entry for this reused cookie. */ + sio_clear_error_locked(siochan, vd->tx.cookie); siochan->current_tx = to_sio_tx(&vd->tx); sio_fill_in_locked(siochan); } } +static void sio_abort_issued_locked(struct sio_chan *siochan) +{ + struct virt_dma_desc *vd, *tmp; + + list_for_each_entry_safe(vd, tmp, &siochan->vc.desc_issued, node) { + struct sio_tx *tx = to_sio_tx(&vd->tx); + u32 residue = tx->period_len * tx->nperiods; + + list_del(&vd->node); + vd->tx_result.result = DMA_TRANS_ABORTED; + vd->tx_result.residue = residue; + sio_record_error_locked(siochan, vd->tx.cookie, residue); + vchan_cookie_complete(vd); + } +} + static void sio_issue_work(struct work_struct *wq) { struct sio_chan *siochan = container_of(wq, struct sio_chan, issue_wq); struct sio_data *sio = siochan->host; unsigned long flags; - bool need_start; - bool put_rpm = true; + bool put_extra = false; + bool put_pm = false; int ret; - spin_lock_irqsave(&siochan->vc.lock, flags); - need_start = !siochan->current_tx && vchan_next_desc(&siochan->vc); - spin_unlock_irqrestore(&siochan->vc.lock, flags); - if (!need_start) + if (READ_ONCE(sio->removing)) { + spin_lock_irqsave(&siochan->vc.lock, flags); + if (!siochan->current_tx) + sio_abort_issued_locked(siochan); + put_pm = sio_take_tx_pm_put_locked(siochan); + spin_unlock_irqrestore(&siochan->vc.lock, flags); + sio_put_tx_pm(siochan, put_pm); return; + } ret = pm_runtime_resume_and_get(sio->dev); if (ret < 0) { dev_err(sio->dev, "runtime resume before issue on chan %d failed: %d\n", siochan->no, ret); + spin_lock_irqsave(&siochan->vc.lock, flags); + if (!siochan->current_tx) + sio_abort_issued_locked(siochan); + put_pm = sio_take_tx_pm_put_locked(siochan); + spin_unlock_irqrestore(&siochan->vc.lock, flags); + sio_put_tx_pm(siochan, put_pm); return; } spin_lock_irqsave(&siochan->vc.lock, flags); - if (!siochan->current_tx && vchan_next_desc(&siochan->vc) && - !READ_ONCE(sio->rpm_stopped)) { - if (!siochan->tx_rpm_held) { + if (!READ_ONCE(sio->removing) && !siochan->current_tx && + vchan_next_desc(&siochan->vc) && sio_firmware_active(sio)) { + if (!siochan->tx_rpm_held) siochan->tx_rpm_held = true; - put_rpm = false; - } + else + put_extra = true; sio_update_current_tx_locked(siochan); + } else { + if (!siochan->current_tx && + (READ_ONCE(sio->removing) || READ_ONCE(sio->asleep))) + sio_abort_issued_locked(siochan); + put_extra = true; } + put_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); - if (put_rpm) { - pm_runtime_mark_last_busy(sio->dev); - pm_runtime_put_autosuspend(sio->dev); - } + sio_put_tx_pm(siochan, put_extra); + sio_put_tx_pm(siochan, put_pm); } static void sio_issue_pending(struct dma_chan *chan) { struct sio_chan *siochan = to_sio_chan(chan); - struct sio_data *sio = siochan->host; unsigned long flags; - bool defer = false; + bool put_pm; spin_lock_irqsave(&siochan->vc.lock, flags); + if (READ_ONCE(siochan->host->removing)) { + spin_unlock_irqrestore(&siochan->vc.lock, flags); + return; + } vchan_issue_pending(&siochan->vc); if (!siochan->current_tx && vchan_next_desc(&siochan->vc)) { - if (siochan->tx_rpm_held) { - if (READ_ONCE(sio->rpm_stopped)) - defer = true; - else - sio_update_current_tx_locked(siochan); - } else if (!IS_ENABLED(CONFIG_PM)) { - if (!READ_ONCE(sio->rpm_stopped)) - sio_update_current_tx_locked(siochan); - } else { - int ret = pm_runtime_get_if_active(sio->dev); + int ret = sio_try_get_tx_pm_locked(siochan); - if (ret > 0 && !READ_ONCE(sio->rpm_stopped)) { - siochan->tx_rpm_held = true; - sio_update_current_tx_locked(siochan); - } else { - if (ret > 0) - pm_runtime_put_noidle(sio->dev); - defer = true; - } - } + if (ret > 0) + sio_update_current_tx_locked(siochan); + else if (ret == 0) + schedule_work(&siochan->issue_wq); + else + sio_abort_issued_locked(siochan); } + put_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); - if (defer) - schedule_work(&siochan->issue_wq); + sio_put_tx_pm(siochan, put_pm); } static int sio_terminate_all(struct dma_chan *chan) @@ -1251,7 +1412,7 @@ static int sio_terminate_all(struct dma_chan *chan) struct sio_chan *siochan = to_sio_chan(chan); struct sio_tx *tx; unsigned long flags; - bool put_rpm = false; + bool put_pm; LIST_HEAD(to_free); spin_lock_irqsave(&siochan->vc.lock, flags); @@ -1268,10 +1429,6 @@ static int sio_terminate_all(struct dma_chan *chan) if (siochan->vc.cyclic == &tx->vd) siochan->vc.cyclic = NULL; siochan->current_tx = NULL; - if (siochan->tx_rpm_held) { - siochan->tx_rpm_held = false; - put_rpm = true; - } /* Its callback may be running: sio_free_dead() frees it. */ if (sio_tx_quiet_locked(siochan, tx)) { list_add_tail(&tx->vd.node, &siochan->dead); @@ -1287,13 +1444,10 @@ static int sio_terminate_all(struct dma_chan *chan) } } vchan_get_all_descriptors(&siochan->vc, &to_free); + put_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); - if (put_rpm) { - pm_runtime_mark_last_busy(siochan->host->dev); - pm_runtime_put_autosuspend(siochan->host->dev); - } - + sio_put_tx_pm(siochan, put_pm); vchan_dma_desc_free_list(&siochan->vc, &to_free); return 0; @@ -1305,7 +1459,7 @@ static void sio_terminate_work(struct work_struct *wq) struct sio_data *sio = siochan->host; struct sio_tx *tx; unsigned long flags; - bool put_tx_rpm = false; + bool put_tx_pm; bool resumed; int ret; @@ -1339,25 +1493,21 @@ static void sio_terminate_work(struct work_struct *wq) WARN_ON(siochan->current_tx != tx); siochan->current_tx = NULL; sio_scrub_locked(siochan, tx); - if (resumed && !READ_ONCE(sio->rpm_stopped) && - vchan_next_desc(&siochan->vc)) { - if (!siochan->tx_rpm_held && IS_ENABLED(CONFIG_PM)) { + if (!READ_ONCE(sio->removing) && resumed && sio_firmware_active(sio)) { + sio_update_current_tx_locked(siochan); + if (siochan->current_tx && !siochan->tx_rpm_held && + IS_ENABLED(CONFIG_PM)) { siochan->tx_rpm_held = true; resumed = false; } - sio_update_current_tx_locked(siochan); - } else if (siochan->tx_rpm_held) { - siochan->tx_rpm_held = false; - put_tx_rpm = true; + } else { + sio_abort_issued_locked(siochan); } sio_ring_leave_locked(siochan); + put_tx_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); - if (put_tx_rpm) { - pm_runtime_mark_last_busy(sio->dev); - pm_runtime_put_autosuspend(sio->dev); - } - + sio_put_tx_pm(siochan, put_tx_pm); if (resumed) { pm_runtime_mark_last_busy(sio->dev); pm_runtime_put_autosuspend(sio->dev); @@ -1406,6 +1556,7 @@ static int sio_stop_quiet(struct sio_chan *siochan) unsigned long flags; struct sio_tx *tx; unsigned int i; + bool put_tx_pm; int ret; ret = pm_runtime_resume_and_get(dev); @@ -1453,8 +1604,11 @@ static int sio_stop_quiet(struct sio_chan *siochan) } siochan->stopping = false; sio_fill_in_locked(siochan); + sio_ring_leave_locked(siochan); + put_tx_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); + sio_put_tx_pm(siochan, put_tx_pm); pm_runtime_mark_last_busy(dev); pm_runtime_put_autosuspend(dev); @@ -1497,8 +1651,8 @@ static void sio_synchronize(struct dma_chan *chan) "chan %d: synchronized without being stopped\n", siochan->no); /* No callback of an ended transfer runs after this. */ - tasklet_kill(&siochan->vc.task); } + tasklet_kill(&siochan->vc.task); sio_free_dead(siochan); } @@ -1510,7 +1664,7 @@ static int sio_clear_idle(struct sio_chan *siochan) { struct sio_tx *idle; unsigned long flags; - bool quiet, stop; + bool quiet, stop, put_tx_pm; int ret; spin_lock_irqsave(&siochan->vc.lock, flags); @@ -1542,11 +1696,13 @@ static int sio_clear_idle(struct sio_chan *siochan) siochan->idle = NULL; sio_scrub_locked(siochan, idle); sio_ring_leave_locked(siochan); + put_tx_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); sio_tx_free(&idle->vd); sio_free_dead(siochan); + sio_put_tx_pm(siochan, put_tx_pm); pm_runtime_mark_last_busy(siochan->host->dev); pm_runtime_put_autosuspend(siochan->host->dev); return 0; @@ -1595,10 +1751,19 @@ static int sio_set_idle(struct sio_chan *siochan, const struct apple_sio_idle *c static void sio_free_chan_resources(struct dma_chan *chan) { + struct sio_chan *siochan = to_sio_chan(chan); + unsigned long flags; + sio_terminate_all(chan); sio_synchronize(chan); - sio_clear_idle(to_sio_chan(chan)); - vchan_free_chan_resources(&to_sio_chan(chan)->vc); + sio_clear_idle(siochan); + + spin_lock_irqsave(&siochan->vc.lock, flags); + memset(siochan->error_cookies, 0, sizeof(siochan->error_cookies)); + siochan->error_head = 0; + spin_unlock_irqrestore(&siochan->vc.lock, flags); + + vchan_free_chan_resources(&siochan->vc); } static struct dma_chan *sio_dma_of_xlate(struct of_phandle_args *dma_spec, @@ -1669,13 +1834,17 @@ static void sio_ring_report_locked(struct sio_chan *siochan) static void sio_process_report(struct sio_chan *siochan) { unsigned long flags; + bool put_pm; spin_lock_irqsave(&siochan->vc.lock, flags); if (siochan->ring) sio_ring_report_locked(siochan); else sio_old_report_locked(siochan); + put_pm = sio_take_tx_pm_put_locked(siochan); spin_unlock_irqrestore(&siochan->vc.lock, flags); + + sio_put_tx_pm(siochan, put_pm); } /* @@ -2012,7 +2181,9 @@ static void sio_free_v9_shmem(void *data) struct sio_data *sio = data; int err; - if (!sio->rpm_stopped && !sio->asleep) { + if (sio->rtk_shutdown_failed) + return; + if (!sio->rpm_stopped && !sio->asleep && !sio->rtk_stopped) { /* An acknowledged shutdown must precede releasing firmware DMA targets. */ err = apple_rtkit_shutdown(sio->rtk); if (err) { @@ -2397,19 +2568,70 @@ static int sio_probe(struct platform_device *pdev) static void sio_remove(struct platform_device *pdev) { struct sio_data *sio = platform_get_drvdata(pdev); + int i; + WRITE_ONCE(sio->removing, true); + for (i = 0; i < sio->nchannels; i++) { + struct sio_chan *siochan = &sio->channels[i]; + unsigned long flags; + bool put_pm; + + spin_lock_irqsave(&siochan->vc.lock, flags); + spin_unlock_irqrestore(&siochan->vc.lock, flags); + cancel_work_sync(&siochan->issue_wq); + flush_work(&siochan->terminate_wq); + spin_lock_irqsave(&siochan->vc.lock, flags); + if (!siochan->current_tx) + sio_abort_issued_locked(siochan); + put_pm = sio_take_tx_pm_put_locked(siochan); + spin_unlock_irqrestore(&siochan->vc.lock, flags); + sio_put_tx_pm(siochan, put_pm); + tasklet_kill(&siochan->vc.task); + } if (sio->commit_registered || sio->hw->commit_stop) apple_sleep_coproc_unregister(&pdev->dev); if (!sio->firmware_only) { of_dma_controller_free(pdev->dev.of_node); dma_async_device_unregister(&sio->dma); } + /* Quiesce terminate producers before runtime PM and RTKit teardown. */ + for (i = 0; i < sio->nchannels; i++) + flush_work(&sio->channels[i].terminate_wq); if (sio_can_runtime_suspend(sio)) { pm_runtime_dont_use_autosuspend(&pdev->dev); pm_runtime_barrier(&pdev->dev); } else { pm_runtime_put_noidle(&pdev->dev); } + /* Quiesce RTKit report producers before the final drain and tasklet kill. */ + if (!READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->asleep)) { + if (sio->arrays) { + int err = apple_rtkit_shutdown(sio->rtk); + + if (err) { + dev_err(sio->dev, + "SIO shutdown failed: %d; retaining DMA buffers\n", + err); + sio->rtk_shutdown_failed = true; + } else { + sio->rtk_stopped = true; + } + } + apple_rtkit_mailbox_off(sio->rtk); + } + for (i = 0; i < sio->nchannels; i++) { + struct sio_chan *siochan = &sio->channels[i]; + unsigned long flags; + bool put_pm; + + spin_lock_irqsave(&siochan->vc.lock, flags); + if (!siochan->current_tx) + sio_abort_issued_locked(siochan); + put_pm = sio_take_tx_pm_put_locked(siochan); + spin_unlock_irqrestore(&siochan->vc.lock, flags); + sio_put_tx_pm(siochan, put_pm); + tasklet_kill(&siochan->vc.task); + } } /* A channel with a transfer can't be carried through a firmware restart. */ @@ -2443,6 +2665,8 @@ static __maybe_unused int sio_suspend(struct device *dev) if (!sio_can_runtime_suspend(sio) || sio->asleep || sio->rpm_stopped) return 0; + if (READ_ONCE(sio->removing)) + return -EBUSY; for (i = 0; i < sio->nchannels; i++) { if (sio_chan_busy(&sio->channels[i])) @@ -2534,12 +2758,12 @@ static __maybe_unused int sio_suspend_late(struct device *dev) */ device_set_wakeup_path(dev); sio->commit_used = true; - sio->asleep = true; + WRITE_ONCE(sio->asleep, true); return 0; } if (sio->hw->commit_stop) { apple_sleep_coproc_set_ready(dev, true); - sio->asleep = true; + WRITE_ONCE(sio->asleep, true); return 0; } @@ -2556,7 +2780,7 @@ static __maybe_unused int sio_suspend_late(struct device *dev) dev_err(dev, "firmware did not come back\n"); return ret; } - sio->asleep = true; + WRITE_ONCE(sio->asleep, true); return 0; } @@ -2576,7 +2800,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) sio->commit_used = false; apple_sleep_coproc_set_ready(dev, false); if (!pm_resume_via_firmware() && !stopped) { - sio->asleep = false; + WRITE_ONCE(sio->asleep, false); return 0; } } @@ -2589,7 +2813,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) */ if (!pm_resume_via_firmware()) { if (!apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL)) { - sio->asleep = false; + WRITE_ONCE(sio->asleep, false); return 0; } ret = apple_sleep_engine_reset(dev); @@ -2601,7 +2825,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) ret); return 0; } - sio->asleep = false; + WRITE_ONCE(sio->asleep, false); dev_info(dev, "sleep refused: firmware back after a reset\n"); return 0; } @@ -2614,7 +2838,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) t6050 ? "SIO: not restarted after the sleep: " : "", ret); return 0; } - sio->asleep = false; + WRITE_ONCE(sio->asleep, false); /* T6050: one line per wake: the start reply's line is the probe's alone. */ if (t6050) dev_info(dev, "SIO: restarted after the sleep, firmware up, protocol v%u, CPU control 0x%x\n", From e9cfcbd1b8fbd2219d23cca242e90db8a290bf37 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 14:32:57 -0500 Subject: [PATCH 6/9] tools/asahi: add apple-sio runtime PM issue lifecycle host test Extract the apple-sio.c runtime PM, descriptor issue, terminate, ring handover, error ring, and remove paths into a host model registered in tools/asahi/run-host-tests.py. Covers issuing after autosuspend and mid-suspend (both desc_issued refusal and concurrent sleep_stop race), cancel before issue_wq runs, ring/idle handover with clear_idle(), commit_stop and asleep guards, per-cookie DMA_ERROR residues across subsequent healthy transfers, late issue_pending() after remove admission closes, and active sio_remove() quiescing apple_rtkit_shutdown() -> apple_rtkit_mailbox_off() before final tasklet_kill(), plus 10 targeted mutations and pre-fix regression baseline a8d2f37caf89. Signed-off-by: Erik Bourget --- tools/asahi/run-host-tests.py | 9 + tools/asahi/sio-rpm-issue-tests.c | 1243 ++++++++++++++++++++++++++++ tools/asahi/sio-rpm-issue-tests.py | 246 ++++++ 3 files changed, 1498 insertions(+) create mode 100644 tools/asahi/sio-rpm-issue-tests.c create mode 100644 tools/asahi/sio-rpm-issue-tests.py diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 623b19ebacc16..949160af3ba04 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -214,6 +214,15 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('bound-only', 'stopped-holds', 'invert-runs', 'no-lock', 'leak-device', 'leak-node', 'ignore-dcp'), out()) + [(out() + ['--ref', 'a7638d51880ce077cfb3edfa7ff638de2be74c85'], KILL)], + 'sio-rpm-issue-tests.py': [(out(), PASS)] + + mutations('--mutation', ('publish-while-suspended', 'skip-rpm-get', + 'drop-tx-pm-early', 'skip-issue-flush', + 'skip-remove-cancel', 'strand-on-resume-fail', + 'late-issue-rearms-tasklet', + 'clear-errors-on-start', + 'skip-remove-mailbox-off', + 'skip-remove-shutdown'), out()) + + [(out() + ['--ref', 'a8d2f37caf8953f54470eb4d54bfb21e903846d3'], KILL)], # A DCP whose firmware runs through the sleep holds its DP PHYs' domains. 'dcp-sleep-phy-hold-tests.py': [([], PASS)] + mutations('--mutation', ('no-route', 'no-own-phy', 'class-device', 'no-err-check'), []), diff --git a/tools/asahi/sio-rpm-issue-tests.c b/tools/asahi/sio-rpm-issue-tests.c new file mode 100644 index 0000000000000..82d8af52983ca --- /dev/null +++ b/tools/asahi/sio-rpm-issue-tests.c @@ -0,0 +1,1243 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Host model of drivers/dma/apple-sio.c runtime PM + descriptor issue lifecycle. + * Exercises the actual extracted functions from apple-sio.c against a runtime PM, + * virt-dma, and RTKit firmware state model. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#define __maybe_unused +#define __force +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define BIT(nr) (1UL << (nr)) +#define GENMASK(h, l) (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (64 - 1 - (h)))) +#define FIELD_PREP(mask, val) (((uint64_t)(val) << __builtin_ctzll(mask)) & (mask)) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define WARN_ON(cond) ({ \ + bool __c = !!(cond); \ + if (__c) \ + fprintf(stderr, "WARN_ON(%s)\n", #cond); \ + __c; \ +}) +static inline void dev_err(const void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } +static inline void dev_err_ratelimited(const void *dev, const char *fmt, ...) +{ + (void)dev; + (void)fmt; +} +static inline void dev_warn(const void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } +static inline void dev_warn_ratelimited(const void *dev, const char *fmt, ...) +{ + (void)dev; + (void)fmt; +} +static inline void dev_WARN_ONCE(const void *dev, bool cond, const char *fmt, ...) +{ + (void)dev; + (void)cond; + (void)fmt; +} +static inline void dev_info(const void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } +static inline void dev_dbg(const void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } +#define msecs_to_jiffies(m) (m) +#define dma_wmb() ((void)0) +#define spin_lock_irqsave(lock, flags) do { \ + bool *__l = (lock); \ + (void)(flags); \ + assert(!*__l); \ + *__l = true; \ +} while (0) +#define spin_unlock_irqrestore(lock, flags) do { \ + bool *__l = (lock); \ + (void)(flags); \ + assert(*__l); \ + *__l = false; \ +} while (0) + +#define u8 uint8_t +#define u32 uint32_t +#define u64 uint64_t +#define dma_addr_t uintptr_t +#define dma_cookie_t int +#define gfp_t unsigned int +#define DMA_MIN_COOKIE 1 +#define GFP_KERNEL 0 +#define GFP_NOWAIT 0 + +enum dma_transfer_direction { DMA_MEM_TO_DEV, DMA_DEV_TO_MEM }; +enum dma_slave_buswidth { + DMA_SLAVE_BUSWIDTH_1_BYTE = 1, + DMA_SLAVE_BUSWIDTH_2_BYTES = 2, + DMA_SLAVE_BUSWIDTH_4_BYTES = 4, +}; + +struct list_head { + struct list_head *next, *prev; +}; + +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list; + list->prev = list; +} + +#define LIST_HEAD(name) struct list_head name = { &(name), &(name) } + +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + struct list_head *prev = head->prev; + + new->next = head; + new->prev = prev; + prev->next = new; + head->prev = new; +} + +static inline void list_del(struct list_head *entry) +{ + entry->prev->next = entry->next; + entry->next->prev = entry->prev; + entry->next = entry->prev = NULL; +} + +static inline void list_move_tail(struct list_head *list, struct list_head *head) +{ + list_del(list); + list_add_tail(list, head); +} + +static inline bool list_empty(const struct list_head *head) +{ + return head->next == head; +} + +static inline void list_splice_init(struct list_head *list, struct list_head *head) +{ + if (!list_empty(list)) { + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->next; + + first->prev = head; + head->next = first; + last->next = at; + at->prev = last; + INIT_LIST_HEAD(list); + } +} + +static inline void list_splice_tail_init(struct list_head *list, struct list_head *head) +{ + if (!list_empty(list)) { + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->prev; + + first->prev = at; + at->next = first; + last->next = head; + head->prev = last; + INIT_LIST_HEAD(list); + } +} + +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - offsetof(type, member))) + +#define list_first_entry(ptr, type, member) \ + container_of((ptr)->next, type, member) + +#define list_for_each_entry(pos, head, member) \ + for (pos = container_of((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = container_of(pos->member.next, typeof(*pos), member)) + +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = container_of((head)->next, typeof(*pos), member), \ + n = container_of(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = container_of(n->member.next, typeof(*pos), member)) + +struct completion { + bool done; +}; + +static inline void init_completion(struct completion *c) +{ + c->done = false; +} + +static inline void complete(struct completion *c) +{ + c->done = true; +} +static inline unsigned long wait_for_completion_timeout(struct completion *c, unsigned long t) +{ + (void)t; + return c->done ? 1 : 0; +} + +struct wait_queue_head { + int wakes; +}; +#define wait_queue_head_t struct wait_queue_head +static inline void wake_up(wait_queue_head_t *q) { q->wakes++; } +#define wait_event_timeout(wq, cond, t) ((void)(wq), (void)(t), (cond) ? 1 : 0) + +struct work_struct { + void (*func)(struct work_struct *work); + bool pending; +}; +#define INIT_WORK(w, fn) do { (w)->func = (fn); (w)->pending = false; } while (0) +static inline bool schedule_work(struct work_struct *w) +{ + if (w->pending) + return false; + w->pending = true; + return true; +} +static inline bool cancel_work_sync(struct work_struct *w) +{ + bool was_pending = w->pending; + + w->pending = false; + return was_pending; +} +static inline void flush_work(struct work_struct *w) +{ + while (w->pending) { + w->pending = false; + w->func(w); + } +} + +struct tasklet_struct { + int kills; + bool scheduled; +}; +static inline void tasklet_kill(struct tasklet_struct *t); + +enum rpm_status { + RPM_ACTIVE, + RPM_SUSPENDING, + RPM_SUSPENDED, + RPM_RESUMING, +}; + +struct device_node { + int unused; +}; + +struct device { + void *drvdata; + struct device_node *of_node; + enum rpm_status rpm_status; + int usage_count; + int disable_depth; + bool autosuspend_pending; +}; + +struct platform_device { + struct device dev; +}; + +static inline void *dev_get_drvdata(const struct device *dev) { return dev->drvdata; } +static inline void *platform_get_drvdata(const struct platform_device *pdev) +{ + return dev_get_drvdata(&pdev->dev); +} + +enum dma_status { + DMA_COMPLETE, + DMA_IN_PROGRESS, + DMA_PAUSED, + DMA_ERROR, + DMA_OUT_OF_ORDER, +}; + +enum dmaengine_tx_result { + DMA_TRANS_NOERROR = 0, + DMA_TRANS_ABORTED, +}; + +struct dmaengine_result { + enum dmaengine_tx_result result; + u32 residue; +}; + +struct dma_tx_state { + dma_cookie_t last; + dma_cookie_t used; + u32 residue; + u32 in_flight_bytes; +}; + +struct dma_device { + int unused; +}; + +struct dma_chan { + dma_cookie_t cookie; + dma_cookie_t completed_cookie; +}; + +struct dma_async_tx_descriptor { + struct dma_chan *chan; + dma_cookie_t cookie; +}; + +struct dma_slave_config { + enum dma_transfer_direction direction; + enum dma_slave_buswidth src_addr_width; + enum dma_slave_buswidth dst_addr_width; + void *peripheral_config; + size_t peripheral_size; +}; + +struct apple_sio_idle { + dma_addr_t addr; + size_t len; + size_t period_len; +}; + +struct virt_dma_desc { + struct dma_async_tx_descriptor tx; + struct dmaengine_result tx_result; + struct list_head node; +}; + +struct virt_dma_chan { + struct dma_chan chan; + bool lock; + struct tasklet_struct task; + struct list_head desc_submitted; + struct list_head desc_issued; + struct list_head desc_completed; + struct virt_dma_desc *cyclic; + void (*desc_free)(struct virt_dma_desc *vd); +}; + +static inline void dma_cookie_complete(struct dma_async_tx_descriptor *tx) +{ + tx->chan->completed_cookie = tx->cookie; + tx->cookie = 0; +} + +static inline enum dma_status dma_cookie_status(struct dma_chan *chan, + dma_cookie_t cookie, + struct dma_tx_state *state) +{ + if (state) { + state->last = chan->completed_cookie; + state->used = chan->cookie; + state->residue = 0; + state->in_flight_bytes = 0; + } + return cookie <= chan->completed_cookie ? DMA_COMPLETE : DMA_IN_PROGRESS; +} + +static inline void dma_set_residue(struct dma_tx_state *state, u32 residue) +{ + if (state) + state->residue = residue; +} + +static inline struct virt_dma_desc *vchan_find_desc(struct virt_dma_chan *vc, + dma_cookie_t cookie) +{ + struct virt_dma_desc *vd; + + list_for_each_entry(vd, &vc->desc_issued, node) + if (vd->tx.cookie == cookie) + return vd; + return NULL; +} + +static inline void vchan_cookie_complete(struct virt_dma_desc *vd) +{ + struct virt_dma_chan *vc = container_of(vd->tx.chan, struct virt_dma_chan, chan); + + dma_cookie_complete(&vd->tx); + list_add_tail(&vd->node, &vc->desc_completed); + vc->task.scheduled = true; +} + +static inline bool vchan_issue_pending(struct virt_dma_chan *vc) +{ + bool pending = !list_empty(&vc->desc_submitted); + + list_splice_tail_init(&vc->desc_submitted, &vc->desc_issued); + return pending; +} + +static inline struct virt_dma_desc *vchan_next_desc(struct virt_dma_chan *vc) +{ + if (list_empty(&vc->desc_issued)) + return NULL; + return list_first_entry(&vc->desc_issued, struct virt_dma_desc, node); +} + +static inline void vchan_get_all_descriptors(struct virt_dma_chan *vc, struct list_head *head) +{ + list_splice_tail_init(&vc->desc_submitted, head); + list_splice_tail_init(&vc->desc_issued, head); + list_splice_tail_init(&vc->desc_completed, head); +} + +static inline void vchan_dma_desc_free_list(struct virt_dma_chan *vc, struct list_head *head) +{ + struct virt_dma_desc *vd, *_vd; + + list_for_each_entry_safe(vd, _vd, head, node) { + list_del(&vd->node); + vc->desc_free(vd); + } +} + +static inline void vchan_cyclic_callback(struct virt_dma_desc *vd) { (void)vd; } + +static inline bool bitmap_empty(const unsigned long *src, unsigned int nbits) +{ + (void)nbits; + return *src == 0; +} + +#define REG_CPU_CONTROL 0x44 +#define CPU_CONTROL_RUN BIT(4) +#define SIOMSG_DATA GENMASK(63, 32) +#define SIOMSG_TYPE GENMASK(23, 16) +#define SIOMSG_EP GENMASK(7, 0) +#define MSG_CONFIGURE 0x5 +#define MSG_ISSUE 0x6 +#define MSG_TERMINATE 0x8 +#define SIO_MAX_NINFLIGHT 4 +#define SIO_NTAGS 16 +#define SIO_MAX_ERROR_COOKIES 16 + +struct sio_error_cookie { + dma_cookie_t cookie; + u32 residue; +}; + +struct sio_coproc_desc { + u32 pad1; + u32 flag; + u64 unk; + u64 iova; + u64 size; + u64 pad2; + u64 pad3; +} __packed; + +struct sio_shmem_chan_config { + u32 datashape; + u32 timeout; + u32 fifo; + u32 threshold; + u32 limit; +} __packed; + +struct sio_data; +struct sio_chan; +struct sio_tx; +typedef void (*sio_ack_callback)(struct sio_chan *, void *, bool); + +struct sio_hw_data { + u32 fifo_threshold; + u32 cfg_word4; + bool cfg_six_words; + bool stop_at_commit; + bool commit_stop; +}; + +struct sio_chan { + unsigned int no; + struct sio_data *host; + struct virt_dma_chan vc; + struct work_struct terminate_wq; +/* EXTRA_CHAN_FIELDS */ + bool configured; + struct sio_shmem_chan_config cfg; + struct sio_tx *current_tx; + unsigned int pending; + bool ring; + struct sio_tx *idle; + struct list_head retired; + wait_queue_head_t drained; + struct sio_tx *issued[SIO_MAX_NINFLIGHT]; + unsigned int issued_head; + unsigned int nissued; + bool issuing; + bool stopping; + struct list_head dead; +}; + +struct sio_data { + const struct sio_hw_data *hw; + u8 base[0x50]; + struct dma_device dma; + struct device *dev; + void *rtk; + bool asleep; + bool rpm_stopped; + bool removing; + bool rtk_stopped; + bool rtk_shutdown_failed; + bool firmware_only; + bool commit_registered; + bool tables_mismatch; + const void *arrays; + u32 fifo_threshold; + u32 cfg_word4; + struct sio_shmem_chan_config shmem[2]; + struct { + unsigned long allocated[1]; + } tags; + int nchannels; + struct sio_chan channels[2]; +}; + +struct sio_tx { + struct virt_dma_desc vd; + struct completion done; + bool terminated; + bool retired; + size_t period_len; + int nperiods; + int ninflight; + int next; + struct sio_coproc_desc *siodesc[]; +}; + +static inline u32 readl(const void *addr) +{ + return *(const u32 *)addr; +} + +static inline void writel(u32 val, void *addr) +{ + *(u32 *)addr = val; +} + +static struct sio_chan *to_sio_chan(struct dma_chan *chan) +{ + return container_of(chan, struct sio_chan, vc.chan); +} + +static struct sio_tx *to_sio_tx(struct dma_async_tx_descriptor *tx) +{ + return container_of(tx, struct sio_tx, vd.tx); +} + +static enum dma_transfer_direction sio_chan_direction(int channo) +{ + return (channo & 1) ? DMA_DEV_TO_MEM : DMA_MEM_TO_DEV; +} + +static int sio_coproc_desc_slot(struct sio_data *sio, struct sio_coproc_desc *d) +{ + (void)sio; + return (int)(uintptr_t)d; +} + +/* Global mock hardware/firmware state */ +static int g_issue_calls; +static int g_config_calls; +static int g_terminate_calls; +static int g_stop_calls; +static int g_resume_calls; +static int g_reset_calls; +static int g_tx_freed; +static int g_completed_callbacks; +static enum dmaengine_tx_result g_last_tx_result; +static u32 g_last_tx_residue; +static bool g_fail_resume; +static bool g_unregistered; +static bool g_rpm_barrier; +static int g_mailbox_off_calls; +static int g_shutdown_calls; +static int g_shutdown_at_mailbox_off; +static int g_total_tasklet_kills; +static int g_kills_at_mailbox_off; +static struct sio_chan *g_sleep_stop_ch; +static void (*g_sleep_stop_hook)(struct sio_chan *ch); + +static inline void tasklet_kill(struct tasklet_struct *t) +{ + struct virt_dma_chan *vc = container_of(t, struct virt_dma_chan, task); + struct virt_dma_desc *vd, *tmp; + + t->kills++; + g_total_tasklet_kills++; + if (!t->scheduled) + return; + t->scheduled = false; + list_for_each_entry_safe(vd, tmp, &vc->desc_completed, node) { + g_last_tx_result = vd->tx_result.result; + g_last_tx_residue = vd->tx_result.residue; + g_completed_callbacks++; + list_del(&vd->node); + vc->desc_free(vd); + } +} + +static int sio_suspend(struct device *dev); +static int sio_resume(struct device *dev); + +static void apple_sleep_coproc_unregister(struct device *dev) { (void)dev; } + +static void of_dma_controller_free(struct device_node *np) { (void)np; } + +static void dma_async_device_unregister(struct dma_device *dma) +{ + struct sio_data *sio = container_of(dma, struct sio_data, dma); + + assert(sio->removing); + for (int i = 0; i < sio->nchannels; i++) { +#ifdef HAVE_ISSUE_WORK + assert(!sio->channels[i].issue_wq.pending); +#endif + assert(!sio->channels[i].terminate_wq.pending); + assert(!sio->channels[i].vc.task.scheduled); + } + g_unregistered = true; +} + +static void pm_runtime_dont_use_autosuspend(struct device *dev) +{ + dev->autosuspend_pending = false; +} + +static void pm_runtime_barrier(struct device *dev) +{ + struct sio_data *sio = dev_get_drvdata(dev); + + for (int i = 0; i < sio->nchannels; i++) { +#ifdef HAVE_ISSUE_WORK + assert(!sio->channels[i].issue_wq.pending); +#endif + assert(!sio->channels[i].terminate_wq.pending); + } + g_rpm_barrier = true; +} + +static void pm_runtime_put_noidle(struct device *dev) +{ + assert(dev->usage_count > 0); + dev->usage_count--; +} + +static int pm_runtime_get_if_active(struct device *dev) +{ + if (dev->disable_depth > 0) + return -EINVAL; + if (dev->rpm_status != RPM_ACTIVE) + return 0; + dev->usage_count++; + dev->autosuspend_pending = false; + return 1; +} + +static int pm_runtime_resume_and_get(struct device *dev) +{ + int ret; + + if (dev->disable_depth > 0) + return -EACCES; + if (dev->rpm_status == RPM_SUSPENDING) { + ret = sio_suspend(dev); + dev->rpm_status = ret ? RPM_ACTIVE : RPM_SUSPENDED; + } + if (dev->rpm_status == RPM_SUSPENDED) { + dev->rpm_status = RPM_RESUMING; + ret = sio_resume(dev); + if (ret) { + dev->rpm_status = RPM_SUSPENDED; + return ret; + } + dev->rpm_status = RPM_ACTIVE; + } + dev->usage_count++; + dev->autosuspend_pending = false; + return 0; +} + +static void pm_runtime_mark_last_busy(struct device *dev) { (void)dev; } + +static int pm_runtime_put_autosuspend(struct device *dev) +{ + assert(dev->usage_count > 0); + dev->usage_count--; + if (dev->usage_count == 0) + dev->autosuspend_pending = true; + return 0; +} + +static void apple_rtkit_mailbox_off(void *rtk) +{ + (void)rtk; + g_shutdown_at_mailbox_off = g_shutdown_calls; + g_mailbox_off_calls++; + g_kills_at_mailbox_off = g_total_tasklet_kills; +} + +static int apple_rtkit_shutdown(void *rtk) +{ + (void)rtk; + assert(g_mailbox_off_calls == 0); + g_shutdown_calls++; + return 0; +} + +static int apple_rtkit_sleep_stop(void *rtk, void *cpu_ctrl) +{ + (void)rtk; + (void)cpu_ctrl; + g_stop_calls++; + if (g_sleep_stop_hook) { + void (*hook)(struct sio_chan *ch) = g_sleep_stop_hook; + struct sio_chan *ch = g_sleep_stop_ch; + + g_sleep_stop_hook = NULL; + g_sleep_stop_ch = NULL; + hook(ch); + } + return 0; +} + +static int apple_rtkit_sleep_return(void *rtk, void *cpu_ctrl) +{ + (void)rtk; + (void)cpu_ctrl; + return 0; +} + +static int apple_sleep_engine_reset(struct device *dev) +{ + (void)dev; + g_reset_calls++; + return 0; +} + +static int apple_rtkit_power_cycled_return(void *rtk, void *cpu_ctrl) +{ + (void)rtk; + (void)cpu_ctrl; + g_resume_calls++; + if (g_fail_resume) + return -ETIMEDOUT; + return 0; +} + +static int sio_send_siomsg_atomic(struct sio_data *sio, u64 msg, + sio_ack_callback ack_callback, void *cookie) +{ + u8 type = (msg & SIOMSG_TYPE) >> 16; + + (void)ack_callback; + (void)cookie; + /* Firmware MUST be live and active with a held runtime PM reference. */ + assert(sio->dev->rpm_status == RPM_ACTIVE); + assert(!sio->rpm_stopped && !sio->asleep); + assert(sio->dev->usage_count > 0); + if (type == MSG_ISSUE) + g_issue_calls++; + return 0; +} + +static int sio_call(struct sio_data *sio, u64 msg) +{ + u8 type = (msg & SIOMSG_TYPE) >> 16; + + assert(sio->dev->rpm_status == RPM_ACTIVE); + assert(!sio->rpm_stopped && !sio->asleep); + assert(sio->dev->usage_count > 0); + if (type == MSG_CONFIGURE) + g_config_calls++; + else if (type == MSG_TERMINATE) + g_terminate_calls++; + return 1; +} + +static struct sio_tx *sio_alloc_tx(struct sio_chan *siochan, dma_addr_t addr, + size_t len, size_t period_len, gfp_t gfp) +{ + struct sio_tx *tx; + int nperiods = (int)(len / period_len); + int i; + + (void)addr; + (void)gfp; + tx = calloc(1, sizeof(*tx) + nperiods * sizeof(tx->siodesc[0])); + assert(tx); + init_completion(&tx->done); + tx->vd.tx.chan = &siochan->vc.chan; + tx->period_len = period_len; + tx->nperiods = nperiods; + for (i = 0; i < nperiods; i++) + tx->siodesc[i] = (struct sio_coproc_desc *)(uintptr_t)(0x100 + i * 4); + return tx; +} + +static void sio_tx_free(struct virt_dma_desc *vd) +{ + g_tx_freed++; + free(to_sio_tx(&vd->tx)); +} + +static void sio_write_config(const struct sio_hw_data *hw, void *shmem, + const struct sio_shmem_chan_config *cfg) +{ + (void)hw; + memcpy(shmem, cfg, sizeof(*cfg)); +} + +static bool sio_chan_busy(struct sio_chan *siochan); +static int sio_stop_quiet(struct sio_chan *siochan) +{ + (void)siochan; + return 0; +} +static void sio_free_dead(struct sio_chan *siochan) +{ + struct sio_tx *tx, *n; + + list_for_each_entry_safe(tx, n, &siochan->dead, vd.node) { + list_del(&tx->vd.node); + sio_tx_free(&tx->vd); + } +} + +/* ACTUAL_SIO_FUNCTIONS */ + +static void run_autosuspend(struct device *dev) +{ + int ret; + + assert(dev->autosuspend_pending); + assert(dev->usage_count == 0); + assert(dev->rpm_status == RPM_ACTIVE); + dev->autosuspend_pending = false; + dev->rpm_status = RPM_SUSPENDING; + ret = sio_suspend(dev); + dev->rpm_status = ret ? RPM_ACTIVE : RPM_SUSPENDED; +} + +static void reset_env(struct sio_data *sio, struct device *dev, struct sio_hw_data *hw) +{ + struct sio_chan *ch = &sio->channels[0]; + + memset(sio, 0, sizeof(*sio)); + memset(dev, 0, sizeof(*dev)); + memset(hw, 0, sizeof(*hw)); + hw->fifo_threshold = 0x800; + hw->cfg_word4 = 0x800; + dev->drvdata = sio; + dev->rpm_status = RPM_ACTIVE; + sio->hw = hw; + sio->dev = dev; + sio->nchannels = 1; + sio->fifo_threshold = hw->fifo_threshold; + sio->cfg_word4 = hw->cfg_word4; + + ch->host = sio; + ch->no = 0; + ch->vc.desc_free = sio_tx_free; + INIT_LIST_HEAD(&ch->vc.desc_submitted); + INIT_LIST_HEAD(&ch->vc.desc_issued); + INIT_LIST_HEAD(&ch->vc.desc_completed); + INIT_LIST_HEAD(&ch->retired); + INIT_LIST_HEAD(&ch->dead); + INIT_WORK(&ch->terminate_wq, sio_terminate_work); +#ifdef HAVE_ISSUE_WORK + INIT_WORK(&ch->issue_wq, sio_issue_work); +#endif + g_issue_calls = g_config_calls = g_terminate_calls = 0; + g_stop_calls = g_resume_calls = g_reset_calls = g_tx_freed = 0; + g_completed_callbacks = 0; + g_last_tx_result = DMA_TRANS_NOERROR; + g_last_tx_residue = 0; + g_fail_resume = false; + g_unregistered = false; + g_rpm_barrier = false; + g_mailbox_off_calls = 0; + g_shutdown_calls = 0; + g_shutdown_at_mailbox_off = 0; + g_total_tasklet_kills = 0; + g_kills_at_mailbox_off = 0; + g_sleep_stop_ch = NULL; + g_sleep_stop_hook = NULL; +} + +static struct sio_tx *submit_cyclic_len(struct sio_chan *ch, dma_cookie_t cookie, + size_t len) +{ + struct sio_tx *tx = sio_alloc_tx(ch, 0x10000, len, 0x1000, GFP_NOWAIT); + + tx->vd.tx.cookie = cookie; + ch->vc.chan.cookie = cookie; + list_add_tail(&tx->vd.node, &ch->vc.desc_submitted); + return tx; +} + +static struct sio_tx *submit_cyclic(struct sio_chan *ch, dma_cookie_t cookie) +{ + return submit_cyclic_len(ch, cookie, 0x2000); +} + +static struct sio_tx *g_mid_suspend_tx; + +static void mid_suspend_issue_hook(struct sio_chan *ch) +{ + g_mid_suspend_tx = submit_cyclic(ch, 20); + sio_issue_pending(&ch->vc.chan); +} + +int main(void) +{ + struct sio_data sio; + struct device dev; + struct sio_hw_data hw; + struct sio_chan *ch = &sio.channels[0]; + struct dma_slave_config cfg = { + .direction = DMA_MEM_TO_DEV, + .dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES, + }; + + /* 1. Configure channel, let autosuspend expire, then issue descriptor. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + assert(g_config_calls == 1); + assert(dev.usage_count == 0); + assert(dev.autosuspend_pending); + + run_autosuspend(&dev); + assert(dev.rpm_status == RPM_SUSPENDED); + assert(sio.rpm_stopped); + assert(g_stop_calls == 1); + + struct sio_tx *tx1 = submit_cyclic(ch, 1); + + sio_issue_pending(&ch->vc.chan); + /* Must NOT have published while suspended! */ + assert(g_issue_calls == 0); + assert(ch->current_tx == NULL); +#ifdef HAVE_ISSUE_WORK + assert(ch->issue_wq.pending); + flush_work(&ch->issue_wq); +#endif + assert(dev.rpm_status == RPM_ACTIVE); + assert(!sio.rpm_stopped); + assert(dev.usage_count == 1); + assert(g_resume_calls == 1); + assert(g_issue_calls == 1); + assert(ch->current_tx == tx1); + /* Autosuspend must refuse while channel has an active transfer. */ + assert(sio_suspend(&dev) == -EBUSY); + + /* Ack the 1st issued descriptor (queues 2nd), then terminate + synchronize. */ + sio_handle_issue_ack(ch, (void *)(uintptr_t)1, true); + assert(dev.usage_count == 1); + sio_terminate_all(&ch->vc.chan); + complete(&tx1->done); + sio_synchronize(&ch->vc.chan); + assert(ch->current_tx == NULL); + /* 2nd ISSUE is still pending its ACK, so PM ref stays held until ACK arrives. */ + assert(ch->pending == 1); + assert(dev.usage_count == 1); + sio_handle_issue_ack(ch, (void *)(uintptr_t)1, true); + assert(ch->pending == 0); + assert(dev.usage_count == 0); + assert(dev.autosuspend_pending); + assert(g_tx_freed == 1); + run_autosuspend(&dev); + assert(sio.rpm_stopped); + + /* 2. Issue while RPM_SUSPENDING (mid-suspend): must defer, not publish. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + dev.autosuspend_pending = false; + dev.rpm_status = RPM_SUSPENDING; + struct sio_tx *tx2 = submit_cyclic(ch, 2); + + sio_issue_pending(&ch->vc.chan); + assert(g_issue_calls == 0); + assert(ch->current_tx == NULL); + /* Pending desc_issued refuses suspend; issue_wq then starts tx2. */ + assert(sio_suspend(&dev) == -EBUSY); + dev.rpm_status = RPM_ACTIVE; + assert(!sio.rpm_stopped); +#ifdef HAVE_ISSUE_WORK + flush_work(&ch->issue_wq); +#endif + assert(dev.rpm_status == RPM_ACTIVE); + assert(!sio.rpm_stopped); + assert(g_issue_calls == 1); + assert(ch->current_tx == tx2); + assert(dev.usage_count == 1); + sio_handle_issue_ack(ch, (void *)(uintptr_t)2, true); + sio_terminate_all(&ch->vc.chan); + complete(&tx2->done); + sio_synchronize(&ch->vc.chan); + sio_handle_issue_ack(ch, (void *)(uintptr_t)2, true); + assert(dev.usage_count == 0); + + /* 2b. Issue during apple_rtkit_sleep_stop(): suspend completes, worker wakes. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + dev.autosuspend_pending = false; + dev.rpm_status = RPM_SUSPENDING; + g_sleep_stop_ch = ch; + g_sleep_stop_hook = mid_suspend_issue_hook; + g_mid_suspend_tx = NULL; + assert(sio_suspend(&dev) == 0); + dev.rpm_status = RPM_SUSPENDED; + assert(sio.rpm_stopped); + assert(g_issue_calls == 0); + assert(ch->current_tx == NULL); +#ifdef HAVE_ISSUE_WORK + flush_work(&ch->issue_wq); +#endif + assert(dev.rpm_status == RPM_ACTIVE); + assert(!sio.rpm_stopped); + assert(g_issue_calls == 1); + assert(ch->current_tx == g_mid_suspend_tx); + assert(dev.usage_count == 1); + sio_handle_issue_ack(ch, (void *)(uintptr_t)20, true); + sio_terminate_all(&ch->vc.chan); + complete(&g_mid_suspend_tx->done); + sio_synchronize(&ch->vc.chan); + sio_handle_issue_ack(ch, (void *)(uintptr_t)20, true); + assert(dev.usage_count == 0); + + /* 3. Cancel before issue_wq runs: no publish, no leaked PM ref. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + run_autosuspend(&dev); + submit_cyclic(ch, 3); + sio_issue_pending(&ch->vc.chan); + assert(g_issue_calls == 0); + sio_terminate_all(&ch->vc.chan); + sio_synchronize(&ch->vc.chan); +#ifdef HAVE_ISSUE_WORK + assert(!ch->issue_wq.pending); +#endif + assert(g_issue_calls == 0); + assert(ch->current_tx == NULL); + assert(dev.usage_count == 0); + assert(g_tx_freed == 1); + + /* 4. Active window issue + ring/idle handover + drain after clear_idle. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + struct apple_sio_idle idle = { .addr = 0x20000, .len = 0x2000, .period_len = 0x1000 }; + + assert(sio_set_idle(ch, &idle) == 0); /* issues idle #0 */ + assert(dev.usage_count == 1); + sio_handle_issue_ack(ch, NULL, true); /* acks idle #0, issues idle #1 */ + struct sio_tx *tx4 = submit_cyclic(ch, 4); + + sio_issue_pending(&ch->vc.chan); + assert(ch->current_tx == tx4); + assert(dev.usage_count == 2); /* idle + tx_pm */ + sio_handle_issue_ack(ch, NULL, true); /* acks idle #1, issues tx4 #0 */ + sio_handle_issue_ack(ch, NULL, true); /* acks tx4 #0, issues tx4 #1 */ + /* acks tx4 #1; issued=[idle#0, idle#1, tx4#0, tx4#1] */ + sio_handle_issue_ack(ch, NULL, true); + /* Handover to retired while idle is active. */ + sio_terminate_all(&ch->vc.chan); + assert(ch->current_tx == NULL); + assert(!list_empty(&ch->retired)); + assert(dev.usage_count == 2); + /* Drain the two idle descriptors; tx4 #0 and #1 remain in retired. */ + sio_process_report(ch); /* idle #0 -> issues idle */ + sio_handle_issue_ack(ch, NULL, true); + sio_process_report(ch); /* idle #1 -> issues idle */ + sio_handle_issue_ack(ch, NULL, true); + assert(!list_empty(&ch->retired)); + /* Drain tx4 #0 -> still 1 tx4 left in retired. */ + sio_process_report(ch); + assert(!list_empty(&ch->retired)); + /* Clear idle while tx4 #1 is still in retired: idle PM ref drops, tx_pm stays! */ + struct apple_sio_idle idle_off = { .len = 0 }; + + complete(&ch->idle->done); + assert(sio_set_idle(ch, &idle_off) == 0); + assert(dev.usage_count == 1); + assert(ch->ring); + /* Drain tx4 #1 + remaining idle descriptors: ring leaves and tx_pm drops. */ + for (int k = 0; k < 8 && ch->nissued; k++) { + if (ch->issuing) + sio_handle_issue_ack(ch, NULL, true); + sio_process_report(ch); + } + sio_free_dead(ch); + assert(list_empty(&ch->retired)); + assert(!ch->ring); + assert(dev.usage_count == 0); + assert(dev.autosuspend_pending); + + /* 5. Commit-stop controller stays active (usage_count >= 1 from probe). */ + reset_env(&sio, &dev, &hw); + hw.commit_stop = true; + dev.usage_count = 1; + struct sio_tx *tx5 = submit_cyclic(ch, 5); + + sio_issue_pending(&ch->vc.chan); + assert(ch->current_tx == tx5); + assert(dev.usage_count == 2); + sio_handle_issue_ack(ch, (void *)(uintptr_t)5, true); + sio_terminate_all(&ch->vc.chan); + complete(&tx5->done); + sio_synchronize(&ch->vc.chan); + sio_handle_issue_ack(ch, (void *)(uintptr_t)5, true); + assert(dev.usage_count == 1); + + /* 6. System-sleep stopped firmware (asleep=true) must not publish descriptors. */ + reset_env(&sio, &dev, &hw); + hw.commit_stop = true; + dev.usage_count = 1; + sio.asleep = true; + submit_cyclic(ch, 6); + sio_issue_pending(&ch->vc.chan); + assert(g_issue_calls == 0); + assert(ch->current_tx == NULL); + sio_terminate_all(&ch->vc.chan); + sio_synchronize(&ch->vc.chan); + assert(dev.usage_count == 1); + +#ifdef HAVE_ISSUE_WORK + /* + * 7. Failed runtime resume aborts multiple differently sized descriptors + * with per-cookie residues preserved across subsequent healthy work. + */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + run_autosuspend(&dev); + g_fail_resume = true; + submit_cyclic_len(ch, 7, 0x2000); + submit_cyclic_len(ch, 8, 0x3000); + sio_issue_pending(&ch->vc.chan); + assert(ch->issue_wq.pending); + flush_work(&ch->issue_wq); + assert(g_resume_calls == 1); + assert(g_issue_calls == 0); + assert(!ch->current_tx); + assert(!ch->tx_rpm_held); + assert(dev.usage_count == 0); + assert(!sio_chan_busy(ch)); + assert(list_empty(&ch->vc.desc_issued)); + assert(ch->vc.task.scheduled); + { + struct dma_tx_state txstate = { 0 }; + + assert(sio_tx_status(&ch->vc.chan, 7, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x2000); + assert(sio_tx_status(&ch->vc.chan, 8, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x3000); + sio_synchronize(&ch->vc.chan); + assert(g_completed_callbacks == 2); + assert(g_last_tx_result == DMA_TRANS_ABORTED); + assert(g_last_tx_residue == 0x3000); + assert(g_tx_freed == 2); + + /* Starting and completing a healthy transfer must retain both errors. */ + g_fail_resume = false; + struct sio_tx *tx9 = submit_cyclic_len(ch, 9, 0x4000); + + sio_issue_pending(&ch->vc.chan); + flush_work(&ch->issue_wq); + assert(ch->current_tx == tx9); + assert(g_issue_calls == 1); + assert(sio_tx_status(&ch->vc.chan, 9, &txstate) == DMA_IN_PROGRESS); + assert(sio_tx_status(&ch->vc.chan, 7, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x2000); + assert(sio_tx_status(&ch->vc.chan, 8, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x3000); + sio_handle_issue_ack(ch, (void *)(uintptr_t)9, true); + sio_terminate_all(&ch->vc.chan); + complete(&tx9->done); + sio_synchronize(&ch->vc.chan); + sio_handle_issue_ack(ch, (void *)(uintptr_t)9, true); + assert(sio_tx_status(&ch->vc.chan, 9, &txstate) == DMA_COMPLETE); + assert(sio_tx_status(&ch->vc.chan, 7, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x2000); + assert(sio_tx_status(&ch->vc.chan, 8, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x3000); + assert(dev.usage_count == 0); + } + + /* 8. Platform remove closes admission and cancels issue_wq before unregister. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + run_autosuspend(&dev); + submit_cyclic(ch, 9); + sio_issue_pending(&ch->vc.chan); + assert(ch->issue_wq.pending); + { + struct platform_device pdev = { .dev = dev }; + + pdev.dev.drvdata = &sio; + sio.dev = &pdev.dev; + sio_remove(&pdev); + assert(sio.removing); + assert(!ch->issue_wq.pending); + assert(g_unregistered); + assert(g_rpm_barrier); + assert(g_resume_calls == 0); + assert(g_issue_calls == 0); + assert(list_empty(&ch->vc.desc_issued)); + assert(!ch->vc.task.scheduled); + assert(g_completed_callbacks == 1); + assert(g_last_tx_result == DMA_TRANS_ABORTED); + assert(g_tx_freed == 1); + assert(pdev.dev.usage_count == 0); + } + /* Late issue after admission closes must not move descriptors or rearm vc.task. */ + submit_cyclic(ch, 10); + sio_issue_pending(&ch->vc.chan); + assert(!ch->issue_wq.pending); + assert(g_issue_calls == 0); + assert(list_empty(&ch->vc.desc_issued)); + assert(!list_empty(&ch->vc.desc_submitted)); + assert(list_empty(&ch->vc.desc_completed)); + assert(!ch->vc.task.scheduled); + assert(g_completed_callbacks == 1); + sio_terminate_all(&ch->vc.chan); + assert(!ch->vc.task.scheduled); + assert(g_completed_callbacks == 1); + assert(g_tx_freed == 2); + + /* 8b. Active remove quiesces RTKit report producers before final tasklet kill. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + { + static const int dummy_arrays; + struct platform_device pdev = { .dev = dev }; + + sio.arrays = &dummy_arrays; + pdev.dev.drvdata = &sio; + sio.dev = &pdev.dev; + sio_remove(&pdev); + assert(sio.removing); + assert(sio.rtk_stopped); + assert(g_shutdown_calls == 1); + assert(g_mailbox_off_calls == 1); + assert(g_shutdown_at_mailbox_off == 1); + assert(g_kills_at_mailbox_off < ch->vc.task.kills); + assert(!ch->vc.task.scheduled); + } + printf("all 8 SIO runtime PM issue lifecycle scenarios passed\n"); +#else + printf("all 6 SIO runtime PM issue lifecycle scenarios passed\n"); +#endif + return 0; +} diff --git a/tools/asahi/sio-rpm-issue-tests.py b/tools/asahi/sio-rpm-issue-tests.py new file mode 100644 index 0000000000000..b06ed39adb43b --- /dev/null +++ b/tools/asahi/sio-rpm-issue-tests.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual apple-sio.c runtime PM and issue lifecycle code in a host model. + +Verifies that a configured channel issuing after autosuspend or mid-suspend +defers descriptor publication to a resume worker rather than sending MSG_ISSUE +to stopped firmware, holds a runtime PM reference until the channel is quiet, +and releases it cleanly across terminate, synchronize, report, and idle paths. +""" +import argparse +import json +import os +import re +import resource +import subprocess +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SIO = "drivers/dma/apple-sio.c" + +FUNCTIONS = [ + "sio_issued_slot", + "sio_tx_quiet_locked", + "sio_scrub_locked", + "sio_source_locked", + "sio_ring_enter_locked", + "sio_ring_leave_locked", + "sio_settle_locked", + "sio_old_issue_ack_locked", + "sio_ring_issue_ack_locked", + "sio_firmware_active", + "sio_chan_tx_busy_locked", + "sio_try_get_tx_pm_locked", + "sio_take_tx_pm_put_locked", + "sio_put_tx_pm", + "sio_handle_issue_ack", + "sio_fill_in_old_locked", + "sio_fill_in_ring_locked", + "sio_fill_in_locked", + "sio_record_error_locked", + "sio_clear_error_locked", + "sio_lookup_error_locked", + "sio_update_current_tx_locked", + "sio_tx_status", + "sio_abort_issued_locked", + "sio_issue_work", + "sio_issue_pending", + "sio_terminate_all", + "sio_terminate_work", + "sio_drained", + "sio_clear_idle", + "sio_set_idle", + "sio_synchronize", + "sio_old_report_locked", + "sio_ring_report_locked", + "sio_process_report", + "sio_device_config", + "sio_can_runtime_suspend", + "sio_remove", + "sio_chan_busy", + "sio_halt_cpu", + "sio_suspend", + "sio_resume", +] + +MUTATIONS = { + "publish-while-suspended": ( + "return !READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->asleep);", + "(void)sio;\n\treturn true;", + ), + "skip-rpm-get": ( + "ret = pm_runtime_get_if_active(sio->dev);", + "ret = 1;", + ), + "drop-tx-pm-early": ( + "if (!siochan->tx_rpm_held || sio_chan_tx_busy_locked(siochan))", + "if (!siochan->tx_rpm_held)", + ), + "skip-issue-flush": ( + "\tflush_work(&siochan->issue_wq);\n", + "", + ), + "skip-remove-cancel": ( + "\t\tcancel_work_sync(&siochan->issue_wq);\n", + "", + ), + "strand-on-resume-fail": ( + "\t\tdev_err(sio->dev, \"runtime resume before issue on chan %d failed: %d\\n\",\n" + "\t\t\tsiochan->no, ret);\n" + "\t\tspin_lock_irqsave(&siochan->vc.lock, flags);\n" + "\t\tif (!siochan->current_tx)\n" + "\t\t\tsio_abort_issued_locked(siochan);", + "\t\tdev_err(sio->dev, \"runtime resume before issue on chan %d failed: %d\\n\",\n" + "\t\t\tsiochan->no, ret);\n" + "\t\tspin_lock_irqsave(&siochan->vc.lock, flags);", + ), + "late-issue-rearms-tasklet": ( + "\tif (READ_ONCE(siochan->host->removing)) {\n" + "\t\tspin_unlock_irqrestore(&siochan->vc.lock, flags);\n" + "\t\treturn;\n" + "\t}\n" + "\tvchan_issue_pending(&siochan->vc);", + "\tvchan_issue_pending(&siochan->vc);\n" + "\tif (READ_ONCE(siochan->host->removing)) {\n" + "\t\tif (!siochan->current_tx)\n" + "\t\t\tsio_abort_issued_locked(siochan);\n" + "\t\tspin_unlock_irqrestore(&siochan->vc.lock, flags);\n" + "\t\treturn;\n" + "\t}", + ), + "clear-errors-on-start": ( + "\t\t/* Retire any stale wrapped-around entry for this reused cookie. */\n" + "\t\tsio_clear_error_locked(siochan, vd->tx.cookie);", + "\t\tmemset(siochan->error_cookies, 0, sizeof(siochan->error_cookies));", + ), + "skip-remove-mailbox-off": ( + "\t\tapple_rtkit_mailbox_off(sio->rtk);\n", + "", + ), + "skip-remove-shutdown": ( + "\t\tif (sio->arrays) {\n" + "\t\t\tint err = apple_rtkit_shutdown(sio->rtk);", + "\t\tif (0 && sio->arrays) {\n" + "\t\t\tint err = apple_rtkit_shutdown(sio->rtk);", + ), +} + + +def block(text, start): + begin = text.index("{", start) + depth, end = 1, begin + 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return end + + +def extract_function(text, name): + pat = re.compile( + r"^(?:static [^\n;]*?\b)" + re.escape(name) + r"\([^;]*?\)\n\{", + re.M | re.S, + ) + match = pat.search(text) + if not match: + return None + return text[match.start():block(text, match.start())] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) + parser.add_argument("--ref", help="read apple-sio.c from this revision") + parser.add_argument("--mutation", choices=sorted(MUTATIONS)) + parser.add_argument("--out", type=Path) + args = parser.parse_args() + + if args.ref: + sio_src = subprocess.check_output( + ["git", "show", f"{args.ref}:{SIO}"], cwd=ROOT, text=True + ) + else: + sio_src = (ROOT / SIO).read_text() + + if args.mutation: + old, new = MUTATIONS[args.mutation] + if sio_src.count(old) != 1: + raise RuntimeError(f"mutation {args.mutation} did not match once") + sio_src = sio_src.replace(old, new) + + extracted = [] + has_issue_work = False + for fn in FUNCTIONS: + body = extract_function(sio_src, fn) + if body: + extracted.append(body) + if fn == "sio_issue_work": + has_issue_work = True + + extra_fields = "" + if has_issue_work: + extra_fields = ( + "\tstruct work_struct issue_wq;\n" + "\tbool tx_rpm_held;\n" + "\tstruct sio_error_cookie error_cookies[SIO_MAX_ERROR_COOKIES];\n" + "\tunsigned int error_head;" + ) + + fwd = "static bool sio_fill_in_locked(struct sio_chan *siochan);\n" + code = ( + Path(__file__).with_suffix(".c") + .read_text() + .replace("/* EXTRA_CHAN_FIELDS */", extra_fields) + .replace("/* ACTUAL_SIO_FUNCTIONS */", fwd + "\n".join(extracted)) + ) + + def run(out): + out.mkdir(parents=True, exist_ok=True) + source = out / "sio-rpm-issue.c" + binary = out / "sio-rpm-issue" + source.write_text(code) + subprocess.run( + [ + os.environ.get("CC", "cc"), + "-std=gnu11", + "-O1", + "-g", + "-Wall", + "-Wextra", + "-Werror", + "-Wno-unused-function", + "-fsanitize=address,undefined", + "-fno-sanitize-recover=all", + "-D__packed=__attribute__((packed))", + "-DIS_ENABLED(option)=1", + ] + + (["-DHAVE_ISSUE_WORK"] if has_issue_work else []) + + [str(source), "-o", str(binary)], + check=True, + ) + result = subprocess.run([str(binary)], capture_output=True, text=True) + (out / "results.json").write_text( + json.dumps( + { + "exit": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "ref": args.ref, + "mutation": args.mutation, + "limits": "Host model of pm_runtime, virt-dma, and RTKit; no real SIO hardware.", + }, + indent=2, + ) + + "\n" + ) + print(result.stdout + result.stderr, end="") + return result.returncode != 0 + + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + if args.out: + return run(args.out.resolve()) + with tempfile.TemporaryDirectory(prefix="sio-rpm-issue-") as out: + return run(Path(out)) + + +if __name__ == "__main__": + raise SystemExit(main()) From daf99763dd959d8647803d50722150aba381cf42 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Mon, 30 Nov 2026 19:10:21 -0500 Subject: [PATCH 7/9] dmaengine: apple-sio: let a stale tag not hold the SIO up at runtime A call that times out keeps its tag until its late reply comes or the firmware is reset, and runtime suspend refused while any tag was allocated. One firmware call that never got its reply then kept the SIO firmware running for good. A kept tag answers nothing any more: runtime suspend now refuses only for a tag whose request still waits for its reply. The runtime resume restarts the firmware from reset, after which no late reply comes, so it releases the kept tags, as the refused-sleep restart already does. Signed-off-by: Erik Bourget --- drivers/dma/apple-sio.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 22d2f6ed163e6..190eb5c5924a2 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -3124,6 +3124,24 @@ static __maybe_unused void sio_halt_cpu(struct sio_data *sio) sio->base + REG_CPU_CONTROL); } +/* + * Whether a tag still waits for its reply. One kept for a call that timed out + * (stale) does not: runtime suspend stops the firmware, and its resume + * restarts it from reset, after which no late reply comes. + */ +static bool sio_tags_live(struct sio_data *sio) +{ + struct sio_tagdata *tags = &sio->tags; + unsigned long flags; + bool live; + + spin_lock_irqsave(&tags->lock, flags); + live = !bitmap_subset(tags->allocated, tags->stale, SIO_NTAGS); + spin_unlock_irqrestore(&tags->lock, flags); + + return live; +} + static __maybe_unused int sio_suspend(struct device *dev) { struct sio_data *sio = dev_get_drvdata(dev); @@ -3138,7 +3156,7 @@ static __maybe_unused int sio_suspend(struct device *dev) if (sio_chan_busy(&sio->channels[i])) return -EBUSY; } - if (!bitmap_empty(sio->tags.allocated, SIO_NTAGS)) + if (sio_tags_live(sio)) return -EBUSY; ret = apple_rtkit_sleep_stop(sio->rtk, sio->base + REG_CPU_CONTROL); @@ -3179,6 +3197,8 @@ static __maybe_unused int sio_resume(struct device *dev) dev_err(dev, "firmware did not come back from runtime suspend: %d\n", ret); return ret; } + /* Restarted from reset: no late reply comes for a timed-out call. */ + sio_release_stale(sio); WRITE_ONCE(sio->rpm_stopped, false); return 0; From 0e6b27f5a2a8e6acddf027c53574e84d3a794548 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 1 Dec 2026 02:38:06 -0500 Subject: [PATCH 8/9] dmaengine: apple-sio: close admission on suspend stop/return double failure When apple_rtkit_sleep_stop() fails in sio_suspend() and the immediate apple_rtkit_sleep_return() fallback also fails, runtime PM returns the device to RPM_ACTIVE while RTKit remains unavailable. Because pm_runtime_get_if_active() succeeds on an RPM_ACTIVE device, sio_issue_pending() could otherwise accept and publish a descriptor to unavailable firmware. Mark the controller unavailable (rtk_unavailable) when both runtime/sleep stop and immediate return fail, rejecting cyclic prep, config, idle setup, and descriptor issue (aborting queued descriptors with DMA_TRANS_ABORTED) until sio_resume() or sio_resume_early() confirms an RTKit restart. Add KUnit and host unit test coverage for the double-failure admission closure, rejection while RPM_ACTIVE or mid-suspend, and reopening after a confirmed RTKit restart. Signed-off-by: Erik Bourget --- drivers/dma/apple-sio-boot-test.c | 69 +++++++++++++++++ drivers/dma/apple-sio.c | 40 ++++++++-- tools/asahi/run-host-tests.py | 3 +- tools/asahi/sio-rpm-issue-tests.c | 120 ++++++++++++++++++++++++++++- tools/asahi/sio-rpm-issue-tests.py | 15 +++- 5 files changed, 236 insertions(+), 11 deletions(-) diff --git a/drivers/dma/apple-sio-boot-test.c b/drivers/dma/apple-sio-boot-test.c index 7e87f046fb958..2b9e6e1079d55 100644 --- a/drivers/dma/apple-sio-boot-test.c +++ b/drivers/dma/apple-sio-boot-test.c @@ -309,6 +309,74 @@ static void sio_issue_pending_after_autosuspend_test(struct kunit *test) INIT_LIST_HEAD(&chan->retired); } +/* + * When SIO is marked unavailable (e.g. after runtime suspend stop and immediate + * return both fail) while runtime PM remains RPM_ACTIVE, new cyclic prep is + * refused and already-submitted descriptors are aborted rather than issued. + */ +static void sio_rtk_unavailable_rejects_issue_test(struct kunit *test) +{ + struct device *dev = kunit_device_register(test, "apple-sio-unavail-test"); + struct sio_data *sio; + struct sio_chan *chan; + struct sio_tx *tx; + struct dma_tx_state txstate = { 0 }; + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + sio = kunit_kzalloc(test, struct_size(sio, channels, 1), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sio); + tx = kunit_kzalloc(test, sizeof(*tx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, tx); + + sio->dev = dev; + sio->nchannels = 1; + WRITE_ONCE(sio->rtk_unavailable, true); + INIT_LIST_HEAD(&sio->dma.channels); + + chan = &sio->channels[0]; + chan->host = sio; + chan->no = 0; + chan->configured = true; + chan->vc.desc_free = sio_test_noop_desc_free; + tx->vd.tx.chan = &chan->vc.chan; + tx->vd.tx.cookie = DMA_MIN_COOKIE; + tx->period_len = 0x1000; + tx->nperiods = 2; + chan->vc.chan.cookie = DMA_MIN_COOKIE; + INIT_WORK(&chan->issue_wq, sio_issue_work); + INIT_WORK(&chan->terminate_wq, sio_terminate_work); + INIT_LIST_HEAD(&chan->retired); + INIT_LIST_HEAD(&chan->dead); + init_waitqueue_head(&chan->drained); + mutex_init(&chan->sync_lock); + init_waitqueue_head(&chan->sync_wait); + vchan_init(&chan->vc, &sio->dma); + + pm_runtime_set_active(dev); + pm_runtime_enable(dev); + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, sio_test_pm_runtime_disable, dev), + 0); + + KUNIT_EXPECT_NULL(test, sio_prep_dma_cyclic(&chan->vc.chan, 0x10000, 0x2000, + 0x1000, DMA_MEM_TO_DEV, 0)); + list_add_tail(&tx->vd.node, &chan->vc.desc_submitted); + sio_issue_pending(&chan->vc.chan); + flush_work(&chan->issue_wq); + + KUNIT_EXPECT_NULL(test, chan->current_tx); + KUNIT_EXPECT_FALSE(test, chan->tx_rpm_held); + KUNIT_EXPECT_FALSE(test, sio_chan_busy(chan)); + KUNIT_EXPECT_TRUE(test, list_empty(&chan->vc.desc_issued)); + KUNIT_EXPECT_EQ(test, atomic_read(&dev->power.usage_count), 0); + KUNIT_EXPECT_EQ(test, sio_tx_status(&chan->vc.chan, DMA_MIN_COOKIE, &txstate), + DMA_ERROR); + KUNIT_EXPECT_EQ(test, txstate.residue, 0x2000U); + + sio_synchronize(&chan->vc.chan); + KUNIT_EXPECT_FALSE(test, sio_chan_busy(chan)); +} + static struct kunit_case sio_boot_test_cases[] = { KUNIT_CASE(sio_boot_order_test), KUNIT_CASE(sio_boot_optional_tables_test), @@ -317,6 +385,7 @@ static struct kunit_case sio_boot_test_cases[] = { KUNIT_CASE(sio_boot_dma_arrays_test), KUNIT_CASE(sio_sleep_busy_test), KUNIT_CASE(sio_issue_pending_after_autosuspend_test), + KUNIT_CASE(sio_rtk_unavailable_rejects_issue_test), {} }; diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 190eb5c5924a2..954e4e04b1d08 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -236,6 +236,8 @@ struct sio_data { bool asleep; /* The firmware is stopped while runtime-suspended. */ bool rpm_stopped; + /* Runtime/sleep stop and immediate return both failed; closed until restart. */ + bool rtk_unavailable; bool removing; bool rtk_stopped; bool rtk_shutdown_failed; @@ -1014,6 +1016,7 @@ static struct dma_async_tx_descriptor *sio_prep_dma_cyclic( struct sio_tx *siotx; if (READ_ONCE(siochan->host->removing) || + READ_ONCE(siochan->host->rtk_unavailable) || siochan->host->tables_mismatch || direction != sio_chan_direction(siochan->no)) return NULL; @@ -1294,7 +1297,8 @@ static void sio_ring_issue_ack_locked(struct sio_chan *siochan, bool ok) static bool sio_firmware_active(const struct sio_data *sio) { - return !READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->asleep); + return !READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->asleep) && + !READ_ONCE(sio->rtk_unavailable); } static bool sio_chan_tx_busy_locked(const struct sio_chan *siochan) @@ -1309,13 +1313,14 @@ static int sio_try_get_tx_pm_locked(struct sio_chan *siochan) int ret; if (siochan->tx_rpm_held) - return sio_firmware_active(sio) ? 1 : 0; + return sio_firmware_active(sio) ? 1 : + (READ_ONCE(sio->rtk_unavailable) ? -EIO : 0); ret = pm_runtime_get_if_active(sio->dev); if (ret > 0) { if (!sio_firmware_active(sio)) { pm_runtime_put_noidle(sio->dev); - return 0; + return READ_ONCE(sio->rtk_unavailable) ? -EIO : 0; } siochan->tx_rpm_held = true; return 1; @@ -1492,7 +1497,8 @@ static void sio_issue_work(struct work_struct *wq) sio_update_current_tx_locked(siochan); } else { if (!siochan->current_tx && - (READ_ONCE(sio->removing) || READ_ONCE(sio->asleep))) + (READ_ONCE(sio->removing) || READ_ONCE(sio->asleep) || + READ_ONCE(sio->rtk_unavailable))) sio_abort_issued_locked(siochan); put_extra = true; } @@ -2121,7 +2127,8 @@ static int sio_set_idle(struct sio_chan *siochan, const struct apple_sio_idle *c } spin_lock_irqsave(&siochan->vc.lock, flags); - ret = siochan->idle ? -EBUSY : 0; + ret = READ_ONCE(siochan->host->rtk_unavailable) ? -EIO : + (siochan->idle ? -EBUSY : 0); if (!ret && !siochan->ring) ret = sio_ring_enter_locked(siochan); if (ret) { @@ -2542,6 +2549,11 @@ static int sio_device_config(struct dma_chan *chan, if (ret < 0) return ret; + if (READ_ONCE(sio->rtk_unavailable)) { + ret = -EIO; + goto out_rpm_put; + } + sio_write_config(sio->hw, cfg_shmem, &cfg); dma_wmb(); @@ -2558,6 +2570,7 @@ static int sio_device_config(struct dma_chan *chan, siochan->cfg = cfg; } +out_rpm_put: pm_runtime_mark_last_busy(sio->dev); pm_runtime_put_autosuspend(sio->dev); @@ -3162,8 +3175,14 @@ static __maybe_unused int sio_suspend(struct device *dev) ret = apple_rtkit_sleep_stop(sio->rtk, sio->base + REG_CPU_CONTROL); if (ret) { dev_err(dev, "firmware did not stop for runtime suspend: %d\n", ret); - if (apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL)) + if (apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL)) { dev_err(dev, "firmware did not come back\n"); + /* + * Runtime PM returns dev to RPM_ACTIVE on suspend error: + * keep admission closed until RTKit restarts cleanly. + */ + WRITE_ONCE(sio->rtk_unavailable, true); + } return ret; } WRITE_ONCE(sio->rpm_stopped, true); @@ -3176,7 +3195,7 @@ static __maybe_unused int sio_resume(struct device *dev) struct sio_data *sio = dev_get_drvdata(dev); int ret; - if (!READ_ONCE(sio->rpm_stopped)) + if (!READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->rtk_unavailable)) return 0; /* @@ -3200,6 +3219,7 @@ static __maybe_unused int sio_resume(struct device *dev) /* Restarted from reset: no late reply comes for a timed-out call. */ sio_release_stale(sio); WRITE_ONCE(sio->rpm_stopped, false); + WRITE_ONCE(sio->rtk_unavailable, false); return 0; } @@ -3262,8 +3282,10 @@ static __maybe_unused int sio_suspend_late(struct device *dev) ret = apple_rtkit_sleep_stop(sio->rtk, sio->base + REG_CPU_CONTROL); if (ret) { dev_err(dev, "firmware did not stop for sleep: %d\n", ret); - if (apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL)) + if (apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL)) { dev_err(dev, "firmware did not come back\n"); + WRITE_ONCE(sio->rtk_unavailable, true); + } return ret; } WRITE_ONCE(sio->asleep, true); @@ -3313,6 +3335,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) } sio_release_stale(sio); WRITE_ONCE(sio->asleep, false); + WRITE_ONCE(sio->rtk_unavailable, false); dev_info(dev, "sleep refused: firmware back after a reset\n"); return 0; } @@ -3326,6 +3349,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) return 0; } WRITE_ONCE(sio->asleep, false); + WRITE_ONCE(sio->rtk_unavailable, false); /* T6050: one line per wake: the start reply's line is the probe's alone. */ if (t6050) dev_info(dev, "SIO: restarted after the sleep, firmware up, protocol v%u, CPU control 0x%x\n", diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index be1eda7b060fa..1328cac73a80a 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -257,7 +257,8 @@ def mutations(flag, names, base, expect=KILL): 'late-issue-rearms-tasklet', 'clear-errors-on-start', 'skip-remove-mailbox-off', - 'skip-remove-shutdown'), out()) + 'skip-remove-shutdown', + 'admit-after-suspend-double-fail'), out()) + [(out() + ['--ref', 'a8d2f37caf8953f54470eb4d54bfb21e903846d3'], KILL)], # A DCP whose firmware runs through the sleep holds its DP PHYs' domains. 'dcp-sleep-phy-hold-tests.py': [([], PASS)] diff --git a/tools/asahi/sio-rpm-issue-tests.c b/tools/asahi/sio-rpm-issue-tests.c index 1a28c2d89eb6b..f2ad403845224 100644 --- a/tools/asahi/sio-rpm-issue-tests.c +++ b/tools/asahi/sio-rpm-issue-tests.c @@ -511,6 +511,7 @@ struct sio_data { bool asleep; bool sleeping; bool rpm_stopped; + bool rtk_unavailable; bool removing; bool rtk_stopped; bool rtk_shutdown_failed; @@ -584,6 +585,8 @@ static int g_tx_freed; static int g_completed_callbacks; static enum dmaengine_tx_result g_last_tx_result; static u32 g_last_tx_residue; +static bool g_fail_sleep_stop; +static bool g_fail_sleep_return; static bool g_fail_resume; static bool g_unregistered; static bool g_rpm_barrier; @@ -735,6 +738,8 @@ static int apple_rtkit_sleep_stop(void *rtk, void *cpu_ctrl) g_sleep_stop_ch = NULL; hook(ch); } + if (g_fail_sleep_stop) + return -ETIME; return 0; } @@ -742,6 +747,8 @@ static int apple_rtkit_sleep_return(void *rtk, void *cpu_ctrl) { (void)rtk; (void)cpu_ctrl; + if (g_fail_sleep_return) + return -EAGAIN; return 0; } @@ -920,6 +927,8 @@ static void reset_env(struct sio_data *sio, struct device *dev, struct sio_hw_da g_completed_callbacks = 0; g_last_tx_result = DMA_TRANS_NOERROR; g_last_tx_residue = 0; + g_fail_sleep_stop = false; + g_fail_sleep_return = false; g_fail_resume = false; g_unregistered = false; g_rpm_barrier = false; @@ -1290,7 +1299,116 @@ int main(void) assert(g_kills_at_mailbox_off < ch->vc.task.kills); assert(!ch->vc.task.scheduled); } - printf("all 8 SIO runtime PM issue lifecycle scenarios passed\n"); + + /* + * 9. Runtime stop + sleep_return double-failure closes admission even + * though runtime PM returns the device to RPM_ACTIVE, until a + * confirmed RTKit restart succeeds. + */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + g_fail_sleep_stop = true; + g_fail_sleep_return = true; + run_autosuspend(&dev); + assert(dev.rpm_status == RPM_ACTIVE); + assert(!sio.rpm_stopped); + assert(sio.rtk_unavailable); + + submit_cyclic_len(ch, 11, 0x2000); + sio_issue_pending(&ch->vc.chan); + flush_work(&ch->issue_wq); + assert(g_issue_calls == 0); + assert(!ch->current_tx); + assert(!ch->tx_rpm_held); + assert(dev.usage_count == 0); + assert(!sio_chan_busy(ch)); + assert(list_empty(&ch->vc.desc_issued)); + { + struct dma_tx_state txstate = { 0 }; + + assert(sio_tx_status(&ch->vc.chan, 11, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x2000); + } + sio_synchronize(&ch->vc.chan); + assert(g_completed_callbacks == 1); + assert(g_last_tx_result == DMA_TRANS_ABORTED); + assert(g_last_tx_residue == 0x2000); + assert(g_tx_freed == 1); + + /* Config and idle setup also reject while unavailable. */ + assert(sio_device_config(&ch->vc.chan, &cfg) == -EIO); + assert(dev.usage_count == 0); + assert(sio_set_idle(ch, &idle) == -EIO); + assert(dev.usage_count == 0); + assert(g_tx_freed == 2); + + /* A failed RTKit restart keeps admission closed. */ + g_fail_resume = true; + assert(sio_resume(&dev) == -ETIMEDOUT); + assert(sio.rtk_unavailable); + submit_cyclic_len(ch, 12, 0x2000); + sio_issue_pending(&ch->vc.chan); + flush_work(&ch->issue_wq); + assert(g_issue_calls == 0); + assert(!ch->current_tx); + sio_synchronize(&ch->vc.chan); + assert(g_completed_callbacks == 2); + assert(g_tx_freed == 3); + + /* Confirmed RTKit restart reopens admission. */ + g_fail_sleep_stop = false; + g_fail_sleep_return = false; + g_fail_resume = false; + assert(sio_resume(&dev) == 0); + assert(!sio.rtk_unavailable); + assert(!sio.rpm_stopped); + assert(g_reset_calls == 2); + assert(g_resume_calls == 2); + + struct sio_tx *tx13 = submit_cyclic_len(ch, 13, 0x3000); + + sio_issue_pending(&ch->vc.chan); + assert(ch->current_tx == tx13); + assert(g_issue_calls == 1); + assert(dev.usage_count == 1); + sio_handle_issue_ack(ch, (void *)(uintptr_t)13, true); + sio_terminate_all(&ch->vc.chan); + complete(&tx13->done); + sio_synchronize(&ch->vc.chan); + sio_handle_issue_ack(ch, (void *)(uintptr_t)13, true); + assert(dev.usage_count == 0); + assert(g_tx_freed == 4); + + /* 9b. Concurrent issue during double-failing sleep_stop is aborted by issue_wq. */ + reset_env(&sio, &dev, &hw); + assert(sio_device_config(&ch->vc.chan, &cfg) == 0); + dev.autosuspend_pending = false; + dev.rpm_status = RPM_SUSPENDING; + g_fail_sleep_stop = true; + g_fail_sleep_return = true; + g_sleep_stop_ch = ch; + g_sleep_stop_hook = mid_suspend_issue_hook; + assert(sio_suspend(&dev) == -ETIME); + dev.rpm_status = RPM_ACTIVE; + assert(sio.rtk_unavailable); + assert(ch->issue_wq.pending); + flush_work(&ch->issue_wq); + assert(g_issue_calls == 0); + assert(!ch->current_tx); + assert(!ch->tx_rpm_held); + assert(dev.usage_count == 0); + assert(list_empty(&ch->vc.desc_issued)); + { + struct dma_tx_state txstate = { 0 }; + + assert(sio_tx_status(&ch->vc.chan, 20, &txstate) == DMA_ERROR); + assert(txstate.residue == 0x2000); + } + sio_synchronize(&ch->vc.chan); + assert(g_completed_callbacks == 1); + assert(g_tx_freed == 1); + + printf("all 9 SIO runtime PM issue lifecycle scenarios passed\n"); #else printf("all 6 SIO runtime PM issue lifecycle scenarios passed\n"); #endif diff --git a/tools/asahi/sio-rpm-issue-tests.py b/tools/asahi/sio-rpm-issue-tests.py index 4b4fde1333e55..09088609378c2 100644 --- a/tools/asahi/sio-rpm-issue-tests.py +++ b/tools/asahi/sio-rpm-issue-tests.py @@ -79,9 +79,22 @@ MUTATIONS = { "publish-while-suspended": ( - "return !READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->asleep);", + "return !READ_ONCE(sio->rpm_stopped) && !READ_ONCE(sio->asleep) &&\n" + "\t !READ_ONCE(sio->rtk_unavailable);", "(void)sio;\n\treturn true;", ), + "admit-after-suspend-double-fail": ( + "\t\tif (apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL)) {\n" + "\t\t\tdev_err(dev, \"firmware did not come back\\n\");\n" + "\t\t\t/*\n" + "\t\t\t * Runtime PM returns dev to RPM_ACTIVE on suspend error:\n" + "\t\t\t * keep admission closed until RTKit restarts cleanly.\n" + "\t\t\t */\n" + "\t\t\tWRITE_ONCE(sio->rtk_unavailable, true);\n" + "\t\t}", + "\t\tif (apple_rtkit_sleep_return(sio->rtk, sio->base + REG_CPU_CONTROL))\n" + "\t\t\tdev_err(dev, \"firmware did not come back\\n\");", + ), "skip-rpm-get": ( "ret = pm_runtime_get_if_active(sio->dev);", "ret = 1;", From 4a086af941a9269d04e4cef19e207092aa5e75b8 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Tue, 1 Dec 2026 21:56:58 -0500 Subject: [PATCH 9/9] soc: apple: sleep: restore PMGR domains when an engine reset fails SIO runtime resume resets the engine even when a sibling has kept its power switch on. If either reset poll or the subsequent power-on poll times out, the engine reset can leave a domain forced into reset or targeting off while genpd still has it on. Save the control state and restore every touched word in reverse order before restoring DART state. Check the restored request and report any domain that fails to settle while preserving the original reset error. Inject failures at each reset and power-on poll in the host test. Signed-off-by: DjDeveloperr --- drivers/soc/apple/sleep.c | 75 ++++++++++++----- tools/asahi/run-host-tests.py | 1 + tools/asahi/sio-engine-reset-tests.py | 114 ++++++++++++++++++++++++++ 3 files changed, 168 insertions(+), 22 deletions(-) mode change 100755 => 100644 tools/asahi/run-host-tests.py create mode 100644 tools/asahi/sio-engine-reset-tests.py diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index dc27f7938a99c..b547850e0de96 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -3129,6 +3129,57 @@ static int sleep_engine_reset_wait(void __iomem *reg, u32 actual) 10, PS_OFF_TIMEOUT_US); } +static int sleep_engine_reset_power(struct device *dev, void __iomem **ps_regs, int n) +{ + u32 saved[ENGINE_RESET_PS], val, mask; + int i, touched = 0, ret; + + for (i = 0; i < n; i++) + saved[i] = readl(ps_regs[i]) & ~(PS_FLAGS | PS_RESET | PS_BUSY | PS_ACTUAL); + + for (i = 0; i < n; i++) { + touched = i + 1; + writel(PS_ENGINE_RESET_4, ps_regs[i]); + ret = sleep_engine_reset_wait(ps_regs[i], 4); + if (ret) + goto rollback; + writel(PS_ENGINE_RESET_0, ps_regs[i]); + ret = sleep_engine_reset_wait(ps_regs[i], 0); + if (ret) + goto rollback; + } + + usleep_range(1000, 2000); + for (i = 0; i < n; i++) + writel(0, ps_regs[i]); + for (i = n - 1; i >= 0; i--) { + writel(PS_TARGET, ps_regs[i]); + ret = sleep_engine_reset_wait(ps_regs[i], FIELD_MAX(PS_ACTUAL)); + if (ret) + goto rollback; + writel(saved[i], ps_regs[i]); + } + + return 0; + +rollback: + /* Restore parents before children, including the domain that timed out. */ + mask = PS_RESET | PS_BUSY | PS_AUTO_ENABLE | PS_TARGET; + for (i = touched - 1; i >= 0; i--) { + u32 target = FIELD_GET(PS_TARGET, saved[i]); + + writel(saved[i], ps_regs[i]); + if (readl_poll_timeout_atomic(ps_regs[i], val, + (val & mask) == (saved[i] & mask) && + ((saved[i] & PS_AUTO_ENABLE) || + FIELD_GET(PS_ACTUAL, val) == target), + 10, PS_OFF_TIMEOUT_US)) + dev_err(dev, "engine reset rollback failed for domain %d: %#x\n", i, val); + } + + return ret; +} + /* A domain of the PMGR block mapped here as "ps", and its offset in it. */ static bool sleep_ps_domain(struct apple_sleep *s, struct device_node *pd, u32 *offset) { @@ -3199,7 +3250,7 @@ int apple_sleep_engine_reset(struct device *dev) struct device *darts[ENGINE_RESET_DARTS] = {}; void __iomem *ps_regs[ENGINE_RESET_PS]; void __iomem *pmgr_maps[ENGINE_RESET_PS] = {}; - u32 saved[ENGINE_RESET_PS], val; + u32 val; struct of_phandle_iterator it; void __iomem *asc; int i, n = 0, idx, err, ret = 0; @@ -3252,27 +3303,7 @@ int apple_sleep_engine_reset(struct device *dev) apple_dart_state_save(darts[i]); } - for (i = 0; i < n && !ret; i++) { - saved[i] = readl(ps_regs[i]); - writel(PS_ENGINE_RESET_4, ps_regs[i]); - ret = sleep_engine_reset_wait(ps_regs[i], 4); - if (!ret) { - writel(PS_ENGINE_RESET_0, ps_regs[i]); - ret = sleep_engine_reset_wait(ps_regs[i], 0); - } - } - if (!ret) { - usleep_range(1000, 2000); - for (i = 0; i < n; i++) - writel(0, ps_regs[i]); - for (i = n - 1; i >= 0 && !ret; i--) { - writel(PS_TARGET, ps_regs[i]); - ret = sleep_engine_reset_wait(ps_regs[i], FIELD_MAX(PS_ACTUAL)); - if (!ret) - writel(saved[i] & ~(PS_FLAGS | PS_RESET | PS_ACTUAL), - ps_regs[i]); - } - } + ret = sleep_engine_reset_power(dev, ps_regs, n); if (!ret) ret = readl_poll_timeout(asc + ASC_CPU_STATUS, val, val & ASC_CPU_STATUS_READY, 10, 100 * USEC_PER_MSEC); diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py old mode 100755 new mode 100644 index 1328cac73a80a..a15ac0301c6cd --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -250,6 +250,7 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('bound-only', 'stopped-holds', 'invert-runs', 'no-lock', 'leak-device', 'leak-node', 'ignore-dcp'), out()) + [(out() + ['--ref', 'a7638d51880ce077cfb3edfa7ff638de2be74c85'], KILL)], + 'sio-engine-reset-tests.py': [([], PASS)], 'sio-rpm-issue-tests.py': [(out(), PASS)] + mutations('--mutation', ('publish-while-suspended', 'skip-rpm-get', 'drop-tx-pm-early', 'skip-issue-flush', diff --git a/tools/asahi/sio-engine-reset-tests.py b/tools/asahi/sio-engine-reset-tests.py new file mode 100644 index 0000000000000..db36d88407872 --- /dev/null +++ b/tools/asahi/sio-engine-reset-tests.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Inject PMGR timeouts into the SIO engine-reset power sequence.""" + +import os +import re +import resource +import subprocess +import tempfile +from pathlib import Path + +SOURCE = Path(__file__).resolve().parents[2] / "drivers/soc/apple/sleep.c" + +HARNESS = r""" +#include +#include +#include +#include + +typedef uint32_t u32; +#define __iomem +#define BIT(n) (1U << (n)) +#define GENMASK(h, l) ((UINT32_MAX >> (31 - (h))) & (UINT32_MAX << (l))) +#define FIELD_GET(mask, val) (((val) & (mask)) >> __builtin_ctz(mask)) +#define FIELD_MAX(mask) FIELD_GET(mask, mask) +#define FIELD_PREP(mask, val) (((val) << __builtin_ctz(mask)) & (mask)) + +/* Registers in leaf-to-root order, as passed by the power-domain list. */ +static u32 regs[3]; +static unsigned int polls, fail_poll, writes_after_failure, restored[3]; + +struct device { unsigned int rollback_errors; }; + +#define dev_err(dev, ...) ((dev)->rollback_errors++) +#define usleep_range(min, max) ((void)0) +#define readl(reg) (*(u32 *)(reg)) +#define readl_poll_timeout_atomic(reg, val, cond, delay, timeout) ({ \ + (val) = readl(reg); \ + (++polls == fail_poll || !(cond)) ? -ETIMEDOUT : 0; \ +}) + +/* DEFINES */ + +static void writel(u32 value, u32 *reg) +{ + if (value != PS_ENGINE_RESET_4 && value != PS_ENGINE_RESET_0) + assert(!(value & (PS_FLAGS | PS_BUSY | PS_ACTUAL))); + if (fail_poll && polls >= fail_poll) { + assert(writes_after_failure < 3); + restored[writes_after_failure++] = reg - regs; + } + *reg = (value & ~(PS_FLAGS | PS_ACTUAL)) | (*reg & PS_FLAGS & ~value); + if (!(value & PS_AUTO_ENABLE)) + *reg |= FIELD_PREP(PS_ACTUAL, FIELD_GET(PS_TARGET, value)); +} + +/* FUNCTIONS */ + +int main(void) +{ + const u32 initial[] = { PS_TARGET | PS_ACTUAL, PS_TARGET | PS_ACTUAL, + PS_TARGET | PS_AUTO_ENABLE }; + void *domains[] = { ®s[0], ®s[1], ®s[2] }; + + for (fail_poll = 0; fail_poll <= 9; fail_poll++) { + unsigned int touched = fail_poll <= 6 ? (fail_poll + 1) / 2 : 3; + struct device dev = {}; + int ret; + + polls = writes_after_failure = 0; + for (unsigned int i = 0; i < 3; i++) + regs[i] = initial[i] | PS_FLAGS; + ret = sleep_engine_reset_power(&dev, domains, 3); + assert(ret == (fail_poll ? -ETIMEDOUT : 0)); + assert(!dev.rollback_errors); + assert(writes_after_failure == touched); + for (unsigned int i = 0; i < touched; i++) + assert(restored[i] == touched - i - 1); + for (unsigned int i = 0; i < 3; i++) { + u32 mask = PS_RESET | PS_BUSY | PS_AUTO_ENABLE | PS_TARGET; + + assert((regs[i] & mask) == (initial[i] & mask)); + if (fail_poll && i >= touched) + assert(regs[i] == (initial[i] | PS_FLAGS)); + } + } + puts("SIO engine reset: success and all 9 timeout points passed"); + return 0; +} +""" + + +def main(): + source = SOURCE.read_text() + names = ("PS_(?:FLAGS|ACTUAL|TARGET|BUSY|RESET|AUTO_ENABLE|ENGINE_RESET_[40])" + "|ENGINE_RESET_PS") + defines = re.findall(rf"^#define (?:{names})\s+[^\n]+", source, re.M) + start = source.index("static int sleep_engine_reset_wait(") + end = source.index("/* A domain of the PMGR block", start) + code = HARNESS.replace("/* DEFINES */", "\n".join(defines)) + code = code.replace("/* FUNCTIONS */", source[start:end]) + + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + with tempfile.TemporaryDirectory(prefix="sio-engine-reset-") as output: + program = Path(output) / "engine-reset.c" + binary = program.with_suffix("") + program.write_text(code) + subprocess.run([os.environ.get("CC", "cc"), "-std=gnu11", "-Wall", "-Wextra", + "-Werror", str(program), "-o", str(binary)], check=True) + subprocess.run([str(binary)], check=True) + + +if __name__ == "__main__": + main()