diff --git a/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8103-pmgr.dtsi index 8bcb24ec1a9e1..10a8dd9431b33 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 { diff --git a/drivers/dma/apple-sio-boot-test.c b/drivers/dma/apple-sio-boot-test.c index 5994518f619b0..2b9e6e1079d55 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,6 +209,171 @@ 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); + mutex_init(&chan->sync_lock); + init_waitqueue_head(&chan->sync_wait); + 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); +} + +/* + * 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)); } @@ -217,6 +384,8 @@ 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), + KUNIT_CASE(sio_rtk_unavailable_rejects_issue_test), {} }; diff --git a/drivers/dma/apple-sio-msg-test.c b/drivers/dma/apple-sio-msg-test.c index bfaf2b7bf52e0..dcf8a520c1f10 100644 --- a/drivers/dma/apple-sio-msg-test.c +++ b/drivers/dma/apple-sio-msg-test.c @@ -73,6 +73,14 @@ static void sio_test_ack_callback(struct sio_chan *chan, void *cookie, bool ok) ack->calls++; } +/* Undoes sio_test_alloc()'s runtime PM: the hold it took, then the enable. */ +static void sio_test_rpm_release(void *dev) +{ + pm_runtime_disable(dev); + pm_runtime_put_noidle(dev); + pm_runtime_set_suspended(dev); +} + static struct sio_data *sio_test_alloc(struct kunit *test, int nchannels) { struct sio_data *sio; @@ -86,6 +94,11 @@ static struct sio_data *sio_test_alloc(struct kunit *test, int nchannels) sio->dev = dev; sio->nchannels = nchannels; sio_init_tags(sio); + /* As probe leaves a running SIO: runtime-active, and held while in use. */ + pm_runtime_get_noresume(dev); + pm_runtime_set_active(dev); + pm_runtime_enable(dev); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, sio_test_rpm_release, dev), 0); for (i = 0; i < nchannels; i++) { struct sio_chan *chan = &sio->channels[i]; @@ -97,6 +110,7 @@ static struct sio_data *sio_test_alloc(struct kunit *test, int nchannels) init_waitqueue_head(&chan->drained); mutex_init(&chan->sync_lock); init_waitqueue_head(&chan->sync_wait); + INIT_WORK(&chan->issue_wq, sio_issue_work); INIT_WORK(&chan->terminate_wq, sio_terminate_work); } return sio; diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 93920409b1c9f..3a7781a17bffa 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -106,16 +106,28 @@ 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; 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 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 @@ -228,6 +240,13 @@ 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; + /* Runtime/sleep stop and immediate return both failed; closed until restart. */ + bool rtk_unavailable; + bool removing; + bool rtk_stopped; + bool rtk_shutdown_failed; /* * From a system sleep's prepare to its complete, with tasks frozen: * sio_synchronize() is bounded (sio_pm_prepare()). @@ -1007,7 +1026,9 @@ 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) || + READ_ONCE(siochan->host->rtk_unavailable) || + siochan->host->tables_mismatch || direction != sio_chan_direction(siochan->no)) return NULL; @@ -1018,6 +1039,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) { @@ -1030,7 +1107,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); @@ -1217,16 +1306,74 @@ 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) && + !READ_ONCE(sio->rtk_unavailable); +} + +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 : + (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 READ_ONCE(sio->rtk_unavailable) ? -EIO : 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 */ @@ -1237,7 +1384,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 (!sio_firmware_active(sio) || tx->ninflight >= SIO_MAX_NINFLIGHT || + tx->terminated) return false; static_assert(sizeof(dma_cookie_t) <= sizeof(void *)); @@ -1261,8 +1409,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 (!sio_firmware_active(sio) || !tx || siochan->issuing || + siochan->stopping || siochan->nissued >= SIO_MAX_NINFLIGHT) return false; d = tx->siodesc[tx->next]; @@ -1292,22 +1440,112 @@ 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 put_extra = false; + bool put_pm = false; + int ret; + + 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 (!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; + else + put_extra = true; + sio_update_current_tx_locked(siochan); + } else { + if (!siochan->current_tx && + (READ_ONCE(sio->removing) || READ_ONCE(sio->asleep) || + READ_ONCE(sio->rtk_unavailable))) + sio_abort_issued_locked(siochan); + put_extra = true; + } + put_pm = sio_take_tx_pm_put_locked(siochan); + spin_unlock_irqrestore(&siochan->vc.lock, flags); + + 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); unsigned long flags; + 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); - sio_update_current_tx_locked(siochan); + if (!siochan->current_tx && vchan_next_desc(&siochan->vc)) { + int ret = sio_try_get_tx_pm_locked(siochan); + + 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); + + sio_put_tx_pm(siochan, put_pm); } static int sio_terminate_all(struct dma_chan *chan) @@ -1315,6 +1553,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_pm; LIST_HEAD(to_free); spin_lock_irqsave(&siochan->vc.lock, flags); @@ -1346,8 +1585,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); + sio_put_tx_pm(siochan, put_pm); vchan_dma_desc_free_list(&siochan->vc, &to_free); return 0; @@ -1428,10 +1669,17 @@ static bool sio_stop_tx(struct sio_chan *siochan, struct sio_tx *tx, return false; } -/* Frees tx, ended, once the firmware no longer reads it, and starts the next transfer. */ +/* + * Frees tx, ended, once the firmware no longer reads it, and starts the next + * transfer. With no firmware to start it on (removal, or stopped), the issued + * descriptors are aborted instead of stranded. The channel's runtime PM + * reference goes with its last transfer. + */ static void sio_release_tx(struct sio_chan *siochan, struct sio_tx *tx) { + struct sio_data *sio = siochan->host; unsigned long flags; + bool put_tx_pm; tasklet_kill(&siochan->vc.task); @@ -1441,9 +1689,14 @@ static void sio_release_tx(struct sio_chan *siochan, struct sio_tx *tx) siochan->quarantined = false; sio_scrub_locked(siochan, tx); sio_update_current_tx_locked(siochan); + if (!siochan->current_tx && + (READ_ONCE(sio->removing) || !sio_firmware_active(sio))) + 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); + sio_put_tx_pm(siochan, put_tx_pm); sio_tx_free(&tx->vd); } @@ -1510,8 +1763,11 @@ static bool sio_stop_held(struct sio_chan *siochan, int (*terminate)(struct sio_ 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); tx = siochan->current_tx; @@ -1520,7 +1776,32 @@ static void sio_terminate_work(struct work_struct *wq) if (WARN_ON(!tx)) return; + /* + * TERMINATE needs the firmware up. If it cannot be resumed, sio_end_tx() + * still frees tx only once the firmware is known to have stopped reading + * it, and otherwise holds it with the channel. + */ + 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); + sio_end_tx(siochan, tx, sio_call_terminate); + + spin_lock_irqsave(&siochan->vc.lock, flags); + /* A next transfer started without its own reference takes this one. */ + if (resumed && siochan->current_tx && !siochan->tx_rpm_held && + IS_ENABLED(CONFIG_PM)) { + siochan->tx_rpm_held = true; + resumed = false; + } + spin_unlock_irqrestore(&siochan->vc.lock, flags); + + if (resumed) { + pm_runtime_mark_last_busy(sio->dev); + pm_runtime_put_autosuspend(sio->dev); + } } static bool sio_drained(struct sio_chan *siochan) @@ -1566,9 +1847,18 @@ static int sio_stop_quiet(struct sio_chan *siochan, int (*terminate)(struct sio_ unsigned long flags; struct sio_tx *tx; unsigned int i; + bool put_tx_pm; bool stopped; int ret; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) { + if (report) + dev_err(dev, "chan %d: runtime resume before stop failed: %d\n", + siochan->no, ret); + return ret; + } + if (report) dev_err(dev, "chan %d: issued descriptors did not complete, stopping it\n", siochan->no); @@ -1608,8 +1898,14 @@ static int sio_stop_quiet(struct sio_chan *siochan, int (*terminate)(struct sio_ } 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); + return stopped ? 0 : -EIO; } @@ -1700,11 +1996,18 @@ static int sio_sync(struct sio_chan *siochan, int (*terminate)(struct sio_chan * if (!sio_sync_lock(siochan, bounded)) return -EBUSY; + /* A deferred issue may start a transfer: settle it before ending any. */ + flush_work(&siochan->issue_wq); flush_work(&siochan->terminate_wq); if (!sio_stop_held(siochan, terminate, bounded)) ret = -EBUSY; if (READ_ONCE(siochan->ring) && !sio_wait_retired(siochan, terminate, bounded)) ret = -EBUSY; + /* + * Descriptors aborted without a transfer to end (a failed resume, or + * removal) completed through the tasklet: their callbacks are done too. + */ + tasklet_kill(&siochan->vc.task); sio_free_dead(siochan); sio_sync_unlock(siochan); @@ -1767,7 +2070,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); @@ -1799,16 +2102,22 @@ 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; } /* 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; @@ -1822,12 +2131,21 @@ 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; + ret = READ_ONCE(siochan->host->rtk_unavailable) ? -EIO : + (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; } @@ -1841,12 +2159,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_sync_lock(siochan, false); sio_clear_idle(siochan); sio_sync_unlock(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); } @@ -1925,13 +2250,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); } /* @@ -2227,6 +2556,15 @@ 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; + + if (READ_ONCE(sio->rtk_unavailable)) { + ret = -EIO; + goto out_rpm_put; + } + sio_write_config(sio->hw, cfg_shmem, &cfg); dma_wmb(); @@ -2243,6 +2581,10 @@ 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); + return ret; } @@ -2328,11 +2670,15 @@ 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); + 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) { + 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); @@ -2507,6 +2853,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; @@ -2566,15 +2917,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; } if (hw->oslog_echo) apple_rtkit_set_oslog_echo(sio->rtk, true); @@ -2606,6 +2958,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); @@ -2618,8 +2971,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"); @@ -2627,23 +2982,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; @@ -2651,23 +3013,28 @@ 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: @@ -2682,39 +3049,93 @@ static int sio_probe(struct platform_device *pdev) if (sio->commit_registered && hw->commit_early) apple_sleep_coproc_set_early(&pdev->dev); /* - * 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; } 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) - return; - - of_dma_controller_free(pdev->dev.of_node); - dma_async_device_unregister(&sio->dma); -} - -static __maybe_unused int sio_suspend(struct device *dev) -{ - /* - * TODO: SIO coproc sleep state - */ - return 0; -} + 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; -static __maybe_unused int sio_resume(struct device *dev) -{ - return 0; + 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. */ @@ -2724,25 +3145,123 @@ static bool sio_chan_busy(struct sio_chan *siochan) bool busy; spin_lock_irqsave(&siochan->vc.lock, flags); - busy = siochan->current_tx || siochan->idle || siochan->ring; + busy = siochan->current_tx || siochan->idle || siochan->ring || + siochan->pending || siochan->tx_rpm_held || + !list_empty(&siochan->vc.desc_issued); spin_unlock_irqrestore(&siochan->vc.lock, flags); return busy; } -/* One stopped in the commit stays up through the system suspend. */ +static __maybe_unused void sio_halt_cpu(struct sio_data *sio) +{ + 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); +} + +/* + * 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); + int i, ret; + + 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])) + return -EBUSY; + } + if (sio_tags_live(sio)) + 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"); + /* + * 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); + + return 0; +} + +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) && !READ_ONCE(sio->rtk_unavailable)) + return 0; + + /* + * 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; + } + /* 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; +} + +/* 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) @@ -2750,7 +3269,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++) { @@ -2774,12 +3293,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; } @@ -2792,11 +3311,13 @@ 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; } - sio->asleep = true; + WRITE_ONCE(sio->asleep, true); return 0; } @@ -2820,7 +3341,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) sio->rx_held = false; apple_rtkit_resume_rx(sio->rtk); } - sio->asleep = false; + WRITE_ONCE(sio->asleep, false); return 0; } } @@ -2837,7 +3358,7 @@ static __maybe_unused int sio_resume_early(struct device *dev) apple_rtkit_resume_rx(sio->rtk); } 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); @@ -2850,7 +3371,8 @@ static __maybe_unused int sio_resume_early(struct device *dev) return 0; } sio_release_stale(sio); - sio->asleep = false; + WRITE_ONCE(sio->asleep, false); + WRITE_ONCE(sio->rtk_unavailable, false); dev_info(dev, "sleep refused: firmware back after a reset\n"); return 0; } @@ -2864,7 +3386,8 @@ 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); + 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/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index e5a6c037ba307..455930b47a7a9 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -3245,15 +3245,66 @@ 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); } +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) { @@ -3270,6 +3321,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) { @@ -3288,33 +3373,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 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); @@ -3323,27 +3428,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(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); - if (!ret) { - writel(PS_ENGINE_RESET_0, sleep_power_reg(s, ps[i])); - ret = sleep_engine_reset_wait(s, ps[i], 0); - } - } - if (!ret) { - usleep_range(1000, 2000); - for (i = 0; i < n; i++) - writel(0, sleep_power_reg(s, ps[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)); - if (!ret) - writel(saved[i] & ~(PS_FLAGS | PS_RESET | PS_ACTUAL), - sleep_power_reg(s, ps[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); @@ -3354,6 +3439,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); diff --git a/sound/soc/apple/mca.c b/sound/soc/apple/mca.c index 7517c8fe61f7f..0bbacde383cd5 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; } /* @@ -1246,43 +1303,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) { @@ -1301,10 +1321,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); @@ -1316,7 +1333,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 @@ -1329,6 +1345,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; @@ -1344,7 +1361,6 @@ static const struct snd_soc_component_driver mca_component = { .sync_stop = mca_sync_stop, .pointer = mca_pointer, .pcm_new = mca_pcm_new, - .pcm_free = mca_pcm_free, }; static void apple_mca_release(struct mca_data *mca) @@ -1414,9 +1430,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 | @@ -1525,10 +1556,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; } @@ -1537,6 +1573,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); } @@ -1608,7 +1646,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++) { @@ -1641,7 +1679,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++) { diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py old mode 100755 new mode 100644 index c60b58486a190..56110efb2bda5 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -270,6 +270,17 @@ 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', + 'skip-remove-cancel', 'strand-on-resume-fail', + 'late-issue-rearms-tasklet', + 'clear-errors-on-start', + 'skip-remove-mailbox-off', + '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)] + mutations('--mutation', ('no-route', 'no-own-phy', 'class-device', 'no-err-check'), []), 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() diff --git a/tools/asahi/sio-rpm-issue-tests.c b/tools/asahi/sio-rpm-issue-tests.c new file mode 100644 index 0000000000000..f2ad403845224 --- /dev/null +++ b/tools/asahi/sio-rpm-issue-tests.c @@ -0,0 +1,1416 @@ +// 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; }) + +/* Single-threaded model: a mutex is a flag that must be free when taken. */ +struct mutex { + bool locked; +}; +static inline void mutex_lock(struct mutex *m) { assert(!m->locked); m->locked = true; } +static inline bool mutex_trylock(struct mutex *m) +{ + if (m->locked) + return false; + m->locked = true; + return true; +} +static inline void mutex_unlock(struct mutex *m) { assert(m->locked); m->locked = false; } + +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 +#define SIO_TERMINATE_TRIES 2 +#define SIO_DRAIN_TIMEOUT_MS 500 +#define SIO_HELD_REPORT_ROUNDS 30 +#define SIO_SYNC_LOCK_TIMEOUT_MS 1700 + +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; + /* The current transfer ended but was not stopped: held with the channel */ + bool quarantined; + struct list_head dead; + struct mutex sync_lock; + wait_queue_head_t sync_wait; +}; + +struct sio_data { + const struct sio_hw_data *hw; + u8 base[0x50]; + struct dma_device dma; + struct device *dev; + void *rtk; + bool asleep; + bool sleeping; + bool rpm_stopped; + bool rtk_unavailable; + 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; + /* The old accounting: ISSUEs acknowledged after the transfer ended */ + int nlate; + 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_sleep_stop; +static bool g_fail_sleep_return; +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); + } + if (g_fail_sleep_stop) + return -ETIME; + return 0; +} + +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; +} + +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); +#ifdef SIO_STOP_QUIET_TERMINATE +static int sio_stop_quiet(struct sio_chan *siochan, int (*terminate)(struct sio_chan *), + bool report) +{ + (void)siochan; + (void)terminate; + (void)report; + return 0; +} +#else +static int sio_stop_quiet(struct sio_chan *siochan) +{ + (void)siochan; + return 0; +} +#endif + +static bool apple_rtkit_is_crashed(void *rtk) +{ + (void)rtk; + return false; +} + +/* The model keeps no stale tags: every allocated tag waits for its reply. */ +static int g_release_stale_calls; +static bool sio_tags_live(struct sio_data *sio) +{ + return !bitmap_empty(sio->tags.allocated, SIO_NTAGS); +} + +static void sio_release_stale(struct sio_data *sio) +{ + (void)sio; + g_release_stale_calls++; +} +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_sleep_stop = false; + g_fail_sleep_return = false; + 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); + } + + /* + * 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 + 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..09088609378c2 --- /dev/null +++ b/tools/asahi/sio-rpm-issue-tests.py @@ -0,0 +1,276 @@ +#!/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_tx_drained_locked", + "sio_tx_drained", + "sio_call_terminate", + "sio_stop_tx", + "sio_release_tx", + "sio_end_tx", + "sio_stop_held", + "sio_terminate_work", + "sio_drained", + "sio_clear_idle", + "sio_set_idle", + "sio_ring_empty", + "sio_wait_retired", + "sio_sync_lock", + "sio_sync_unlock", + "sio_sync", + "sio_synchronize_chan", + "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) &&\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;", + ), + "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" + # Revisions whose stop and synchronize take the TERMINATE to send. + prelude = "" + if "int (*terminate)(struct sio_chan *)" in sio_src: + prelude = "#define SIO_STOP_QUIET_TERMINATE\n" + code = prelude + ( + 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())