spi: spi-mux, core, ti-qspi: error handling, delay fixes, KUnit tests, and lock context annotations
Subsystems (3)
cover spi: spi-mux, core, ti-qspi: error handling, delay fixes, KUnit tests, and lock context annotations
From: Joseph CT Chan <[email protected]>
Hi Mark,
This series fixes four categories of error-handling and configuration propagation bugs across the SPI core, spi-mux, and spi-ti-qspi (Patches 1-6), adds three KUnit test suites on ARCH=um with detailed inline comments explaining the expected vs. broken states at each assertion (Patches 7-9), and enables Clang compile-time lock context analysis across the SPI subsystem (Patches 10-14).
Detailed line-by-line code walkthroughs of the four bug mechanisms and the three KUnit test suites are also available at:
https://gist.github.com/joectchan/9a14b5e6facb75058ebc5a6ff1757131
Overview of the Bugs Fixed (Patches 1-6)
========================================
1. SPI core leaks message optimize state when queuing fails (Patch 1):
spi_async() and __spi_sync() call spi_maybe_optimize_message() before attempting to queue the message. Optimizing a message can allocate split transfers on msg->resources (via spi_split_transfers_maxsize()) and controller state in msg->opt_state (such as compiled command programs in spi-axi-spi-engine), and sets msg->optimized = true. Normally spi_finalize_current_message() unoptimizes the message after it runs, but when queuing fails (-EBUSY when another driver such as mmc_spi holds spi_bus_lock(), -ESHUTDOWN when the queue is stopped, or -ENOTSUPP when ctlr->transfer is NULL), the message was never queued and is never finalized. Patch 1 calls spi_maybe_unoptimize_message() on the queue failure paths in spi_async() and __spi_sync(), while preserving caller pre-optimized messages (msg->pre_optimized == true).
2. spi-mux leaks the mux semaphore on parent spi_setup() failure and ignores live spi_setup() updates from the active child (Patches 2-3):
- In spi_mux_select(), mux_control_select() acquires the mux
semaphore before calling spi_setup(priv->spi). If parent
spi_setup() fails, spi_mux_select() returned the error with the mux
semaphore still held and priv->current_cs already set to the failed
child's chip select. Patch 2 resets priv->current_cs =
SPI_MUX_NO_CS and calls mux_control_deselect(priv->mux) when
spi_setup(priv->spi) fails. - When the currently selected child updates its mode (for example mmc_spi flipping SPI_CS_HIGH), max_speed_hz, bits_per_word, or delays and calls spi_setup(), spi_mux_setup() left priv->current_cs unchanged, so the next transfer on that child hit the priv->current_cs == spi_get_chipselect(spi, 0) early return in spi_mux_select() and ran with stale parent settings. Patch 3 resets priv->current_cs = SPI_MUX_NO_CS in spi_mux_setup().
3. Early errors in spi-mux and spi-ti-qspi skip spi_finalize_current_message() and hang callers (Patches 4-5):
- spi-mux sets ctlr->must_async = true and ctlr->defer_optimize_message = true, so every child spi_sync() sleeps in wait_for_completion(&done) while validation is deferred to the parent spi_async(priv->spi, m) call inside spi_mux_transfer_one_message(). When spi_mux_select() failed (e.g. an I2C mux NACK or parent spi_setup() error) or parent spi_async() failed synchronously (e.g. -EBUSY while the parent bus is locked, or -EINVAL when parent __spi_validate() rejects an odd-length 16-bit transfer), spi_mux_transfer_one_message() returned the error without finalizing the message. Because spi_mux_complete_cb() never ran, the child caller slept forever holding mux_ctlr->bus_lock_mutex and, on parent spi_async() failure, leaked the mux semaphore and left msg->spi, msg->complete, and msg->context overwritten. Patch 4 finalizes the message on spi_mux_select() failure and invokes spi_mux_complete_cb(priv) on parent spi_async() failure.
- In spi-ti-qspi, when qspi_transfer_msg() failed (such as ti_qspi_poll_wc() timing out with -ETIMEDOUT), ti_qspi_start_transfer_one() unlocked list_lock and returned early without writing QSPI_INVAL, updating m->status, or calling spi_finalize_current_message(host). That left noqueue spi_sync() returning stale -EINPROGRESS with msg->optimized leaked and caused queued spi_async() callers to hang. Patch 5 breaks out of the loop on error so the common epilogue writes QSPI_INVAL, records status, and finalizes the message.
4. spi-mux drops child chip-select and word delays (Patch 6):
spi_mux_select() copied max_speed_hz, mode, and bits_per_word to priv->spi, but dropped cs_setup, cs_hold, cs_inactive, and word_delay. Because the SPI core and parent controller read all four delays from priv->spi after m->spi is rewritten, child device delays were ignored. Patch 6 saves the mux device's own delays at probe, merges each child CS delay with the mux's delay (taking the longer of the two so both timing requirements are met), forwards word_delay, and restores the mux's original delays via devm on unbind.
Overview of the KUnit Suites (Patches 7-9)
==========================================
All three KUnit suites run on User-Mode Linux (ARCH=um) without physical hardware and include detailed inline comments at each assertion documenting both the expected patched behavior and the broken unpatched behavior:
python3 tools/testing/kunit/kunit.py run \
--arch=um --kunitconfig=drivers/spi/tests- Patch 7 (spi_core_optimize, drivers/spi/tests/spi-core-kunit.c):
7 parameterized cases testing spi_async() and spi_sync() queue errors (-EBUSY on a locked bus, -ESHUTDOWN on a suspended controller, and -ENOTSUPP on a mem_ops-only controller) with max_transfer_size = 2 splitting a 4-byte transfer into two 2-byte transfers on msg.resources. Verifies that core-optimized messages are unoptimized on queue failure, caller pre-optimized messages are preserved, and messages can be reused after transient errors clear.
- Patch 8 (spi_ti_qspi, drivers/spi/tests/spi-ti-qspi-kunit.c):
Uses logic_iomem emulated MMIO at 0x30000000 on ARCH=um to withhold QSPI_WC on QSPI_SPI_STATUS_REG (0x4c), forcing ti_qspi_poll_wc() to time out with -ETIMEDOUT. Verifies that both noqueue spi_sync() and queued spi_async() return -ETIMEDOUT, unoptimize the message, write QSPI_INVAL to QSPI_SPI_CMD_REG (0x48), and recover cleanly on the next transfer.
- Patch 9 (spi_mux, drivers/spi/tests/spi-mux-kunit.c + kunit_spi_mux.dtso):
Applies a Device Tree overlay registering a fake mux_chip, a fake parent spi_controller, the real spi-mux driver, and two child SPI devices across 9 test executions: 4 forwarding error cases (bus_locked, rejects_odd_len, select_fails, parent_setup_fails), 4 CS delay merge cases (longer, tie, sck_zero, sck_set), and a 4-phase settings lifecycle test covering live child spi_setup(), channel switching, and driver unbind/re-attach delay restoration.
On unmodified upstream master (c339f4010dea), running the 3 suites produces 13 failures and 4 passing baseline guard cases (with bounded timeouts so none of the unfinalized message bugs hang the test runner). With Patches 1-6 applied, all 17 test cases pass.
Lock Context Analysis (Patches 10-14)
=====================================
Patches 10-14 (by Bart Van Assche) split spi_write_then_read(), add Clang thread-safety and lock context annotations (__acquires, __releases, __cond_acquires, __must_hold, __must_not_hold, and __guarded_by) for bus_lock_mutex and spi-mem, and enable CONTEXT_ANALYSIS := y in drivers/spi/Makefile and drivers/spi/tests/Makefile with zero warnings under Clang 23 (CONFIG_WARN_CONTEXT_ANALYSIS=y).
Please consider this patch series for the next merge window.
Thanks,
Joseph
Bart Van Assche (5):
spi: Split spi_write_then_read()
spi: Add lock context annotations for bus_lock_mutex
spi: spi-mem: Add lock context annotations
spi: microchip-core-qspi: Add lock context annotations
spi: Enable lock context analysis
Joseph CT Chan (9):
spi: unoptimize message when queuing it fails
spi: spi-mux: release mux when parent setup fails
spi: spi-mux: re-apply settings after child calls spi_setup()
spi: spi-mux: finalize message when forwarding fails
spi: spi-ti-qspi: finalize message on transfer error
spi: spi-mux: pass child CS and word delays to the parent
spi: add KUnit tests for message optimize state on queue errors
spi: spi-ti-qspi: add KUnit tests for transfer error finalization
spi: spi-mux: add KUnit tests for forwarding errors and settings
drivers/spi/Kconfig | 39 ++ drivers/spi/Makefile | 5 + drivers/spi/spi-mem.c | 4 + drivers/spi/spi-microchip-core-qspi.c | 6 + drivers/spi/spi-mux.c | 124 +++++- drivers/spi/spi-ti-qspi.c | 4 +- drivers/spi/spi.c | 107 +++-- drivers/spi/tests/.kunitconfig | 12 + drivers/spi/tests/Makefile | 6 + drivers/spi/tests/kunit_spi_mux.dtso | 42 ++ drivers/spi/tests/spi-core-kunit.c | 308 ++++++++++++++ drivers/spi/tests/spi-mux-kunit.c | 581 ++++++++++++++++++++++++++ drivers/spi/tests/spi-ti-qspi-kunit.c | 225 ++++++++++ include/linux/spi/spi.h | 12 +- 14 files changed, 1423 insertions(+), 52 deletions(-) create mode 100644 drivers/spi/tests/.kunitconfig create mode 100644 drivers/spi/tests/kunit_spi_mux.dtso create mode 100644 drivers/spi/tests/spi-core-kunit.c create mode 100644 drivers/spi/tests/spi-mux-kunit.c create mode 100644 drivers/spi/tests/spi-ti-qspi-kunit.c
base-commit: c339f4010dea8b0d754f84ace70cd1b089878ef8
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 1/14 spi: unoptimize message when queuing it fails
From: Joseph CT Chan <[email protected]>
spi_async() and spi_sync() optimize a message before they queue it. When queuing then fails, the message is never finalized, but finalizing is the only place where the core undoes its own optimization (spi_finalize_current_message() calls spi_maybe_unoptimize_message()). So the error paths leak the split transfers and the controller's optimize state, and leave msg->optimized set. A caller that resends the message then optimizes an already optimized message.
This happens when spi_async() returns -EBUSY because another device holds spi_bus_lock() on the controller (for example mmc_spi), when the controller's message queue is stopped (-ESHUTDOWN), when the controller has no ->transfer() callback (-ENOTSUPP), and when __spi_sync() gets an error from a controller's legacy ->transfer() callback.
Call spi_maybe_unoptimize_message() on these two error paths. It only acts on messages the core optimized itself, so messages optimized by the peripheral driver and controllers that defer optimization (such as spi-mux) are not affected. A queued message is never unoptimized here.
Tested with KUnit (spi_core_optimize: spi_core_queue_error_test, added later in this series) on ARCH=um; builds with W=1 on x86_64. Not tested on hardware.
--- drivers/spi/spi.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/spi/spi.c +7 -0
@@ -4906,6 +4906,10 @@ int spi_async(struct spi_device *spi, struct spi_message *message)spin_unlock_irqrestore (&ctlr->bus_lock_spinlock, flags); +/* The message was not queued, so it will not be finalized. */ +if (ret) +spi_maybe_unoptimize_message (message); +return ret; }EXPORT_SYMBOL_GPL (spi_async);
@@ -5009,6 +5013,9 @@ static int __spi_sync(struct spi_device *spi, struct spi_message *message)if (status ==0 ) {wait_for_completion (&done); status = message->status; + }else { +/* The message was not queued, so it will not be finalized. */ +spi_maybe_unoptimize_message (message); } message->complete =NULL ; message->context =NULL ;
Signature · 1 line
2.56.0.317.g454f8302e1-goog
Re: [PATCH 01/14] spi: unoptimize message when queuing it fails
Quoted 50 lines · Joseph CT Chan
From: Joseph CT Chan <[email protected]>
spi_async()andspi_sync()optimize a message before they queue it. When queuing then fails, the message is never finalized, but finalizing is the only place where the core undoes its own optimization (spi_finalize_current_message()callsspi_maybe_unoptimize_message()). So the error paths leak the split transfers and the controller's optimize state, and leavemsg->optimizedset. A caller that resends the message then optimizes an already optimized message.This happens when
spi_async()returns-EBUSYbecause another device holdsspi_bus_lock()on the controller (for examplemmc_spi), when the controller's message queue is stopped (-ESHUTDOWN), when the controller has no ->transfer() callback (-ENOTSUPP), and when__spi_sync()gets an error from a controller's legacy ->transfer() callback.Call
spi_maybe_unoptimize_message()on these two error paths. It only acts on messages the core optimized itself, so messages optimized by the peripheral driver and controllers that defer optimization (such as spi-mux) are not affected. A queued message is never unoptimized here.Tested with KUnit (
spi_core_optimize:spi_core_queue_error_test, added later in this series) on ARCH=um; builds with W=1 onx86_64. Not tested on hardware.Assisted-by Claude, GeminiFixes 7b1d87af14d9 ("spi: add spi_optimize_message() APIs")Fixes c86a918b1bdb ("spi: don't unoptimize message in spi_async()")Signed-off-by Joseph CT Chan <[email protected]>--- drivers/spi/spi.c | 7 +++++++ 1 file changed, 7 insertions(+)drivers/spi/spi.c +4
-0@@ -4906,6 +4906,10 @@ int spi_async(struct spi_device *spi, struct spi_message *message)spin_unlock_irqrestore (&ctlr->bus_lock_spinlock, flags); +/* The message was not queued, so it will not be finalized. */ +if (ret) +spi_maybe_unoptimize_message (message); +return ret; }EXPORT_SYMBOL_GPL (spi_async);
drivers/spi/spi.c static int __spi_sync(struct spi_device *spi, struct spi_message *message) · line 5021
Quoted 9 lines
drivers/spi/spi.c +3
-0@@ -5009,6 +5013,9 @@ static int __spi_sync(struct spi_device *spi, struct spi_message *message)if (status ==0 ) {wait_for_completion (&done); status = message->status; + }else { +/* The message was not queued, so it will not be finalized. */ +spi_maybe_unoptimize_message (message); } message->complete =NULL ; message->context =NULL ;
PATCH 2/14 spi: spi-mux: release mux when parent setup fails
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
When spi_mux_select() switches to a different child, it locks the mux with mux_control_select(), copies the child's settings into the spi-mux device and calls spi_setup() on the parent controller. If spi_setup() fails, spi_mux_select() returns the error without calling mux_control_deselect(), so the mux stays locked. The next message on any child of this mux then blocks forever in mux_control_select(), and so does every other user of the same mux control.
spi_mux_select() also records the new chip select in current_cs before spi_setup() runs. After a failure, the next message for the same child skips the copy and spi_setup(), and is sent with a parent that was never set up for it.
On spi_setup() failure, set current_cs to SPI_MUX_NO_CS, so the next message sets up the parent again, and release the mux. Record the new chip select only after spi_setup() succeeds.
Tested with KUnit (spi_mux: spi_mux_error_test, added later in this series) on ARCH=um; that case also needs "spi: spi-mux: finalize message when forwarding fails" to see the error status. Builds with W=1 on x86_64. Not tested on hardware.
--- drivers/spi/spi-mux.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
drivers/spi/spi-mux.c +8 -1
@@ -66,9 +66,16 @@ static int spi_mux_select(struct spi_device *spi) priv->spi->mode = spi->mode; priv->spi->bits_per_word = spi->bits_per_word; + ret =spi_setup (priv->spi); +if (ret) { + priv->current_cs =SPI_MUX_NO_CS ; +mux_control_deselect (priv->mux); +return ret; + } + priv->current_cs =spi_get_chipselect (spi,0 ); -return spi_setup (priv->spi); +return 0 ; }static int spi_mux_setup (struct spi_device *spi)
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 3/14 spi: spi-mux: re-apply settings after child calls spi_setup()
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
spi_mux_select() copies a child's max_speed_hz, mode and bits_per_word into the spi-mux device and sets up the parent controller only when the mux switches to a different child (current_cs differs). If the child that is already selected changes its settings and calls spi_setup(), spi_mux_setup() only calls spi_setup() on the spi-mux device with its old settings, and current_cs still matches. The next transfers of that child then run with the old speed and mode.
Set current_cs to SPI_MUX_NO_CS in spi_mux_setup(), so the next transfer copies the child's settings and sets up the parent again. spi_mux_setup() runs under the spi-mux controller's io_mutex, which the message pump holds while a message is forwarded, so this does not race with spi_mux_select(). The cost is one extra parent spi_setup() on the next transfer.
Tested with KUnit (spi_mux: spi_mux_settings_lifecycle_test, added later in this series) on ARCH=um; builds with W=1 on x86_64. Not tested on hardware.
--- drivers/spi/spi-mux.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/spi/spi-mux.c +6 -0
@@ -86,7 +86,13 @@ static int spi_mux_setup(struct spi_device *spi)* can be called multiple times, won't do a valid setup now but we will * change the settings when we do a transfer (necessary because we * can't predict from which device it will be anyway) +* +* The child may have changed its settings, so make the next transfer +* copy them again even if this child is the current one. This runs +* under our io_mutex, so no message is being forwarded right now. */ + priv->current_cs =SPI_MUX_NO_CS ; +return spi_setup (priv->spi); }
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 4/14 spi: spi-mux: finalize message when forwarding fails
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
spi_mux_transfer_one_message() forwards a child's message to the parent controller. When spi_mux_select() or spi_async() on the parent fails, it returns the error without finalizing the message. The SPI core then logs "failed to transfer one message from queue" and does not finalize it either, so the child's completion callback never runs and spi_sync() on the child waits forever. After a spi_async() failure the mux also stays locked, so the next message on any child of the mux blocks the spi-mux message pump in mux_control_select(), and the message keeps the spi-mux device and callback in place of the child's.
This is easy to hit: spi_async() on the parent returns -EBUSY whenever another device on the parent bus holds spi_bus_lock(), which mmc_spi does for every request. It also returns an error when the parent rejects the message, for example a transfer with 16-bit words and an odd length, which spi-mux does not validate because it defers message optimization to the parent.
On select failure, set the message status and finalize it; there is nothing to restore yet and, with patch 2 of this series ("spi: spi-mux:
release mux when parent setup fails"), spi_mux_select() has already released the mux. On spi_async() failure, set the status and call spi_mux_complete_cb(), which restores the child's pointers, finalizes the message and releases the mux, in the same order as a successful transfer. In both cases return 0: the message is already finalized with m->status set, so the error reaches the caller through the message, and the core does not wait for it. Returning the error would only make the core log "failed to transfer one message from queue" once per -EBUSY while another device holds the bus lock.
Behavior change: a device behind spi-mux now gets -EBUSY while another device holds spi_bus_lock() on the parent, instead of hanging. A device wired directly to the parent would instead wait in spi_sync(), because spi_sync() takes the bus_lock_mutex that spi_bus_lock() holds (drivers/spi/spi.c spi_sync() and spi_bus_lock()); spi-mux forwards with spi_async(), which returns -EBUSY while the bus is locked. Making spi-mux wait for the bus lock needs a core helper and is left for a follow-up.
This depends on patch 1 of this series ("spi: unoptimize message when queuing it fails"): spi_async() on the parent optimizes the message for the parent, and without patch 1 a failed spi_async() leaves it in that state when it is handed back to the child.
Tested with KUnit (spi_mux: spi_mux_error_test, added later in this series) on ARCH=um; before this patch they time out with the message never finalized. Builds with W=1 on x86_64. Not tested on hardware.
--- drivers/spi/spi-mux.c | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-)
drivers/spi/spi-mux.c +23 -3
@@ -117,8 +117,12 @@ static int spi_mux_transfer_one_message(struct spi_controller *ctlr,int ret; ret =spi_mux_select (spi); -if (ret) -return ret; +if (ret) { +/* spi_mux_select() released the mux on failure */ + m->status = ret; +spi_finalize_current_message (ctlr); +return 0 ; + }/* * Replace the complete callback, context and spi_device with our own
@@ -133,7 +137,23 @@ static int spi_mux_transfer_one_message(struct spi_controller *ctlr, m->spi = priv->spi;/* do the transfer */ -return spi_async (priv->spi, m); + ret =spi_async (priv->spi, m); +if (ret) { +/* +* The parent did not take the message, so it will not call +* spi_mux_complete_cb(). Call it here to restore the child's +* pointers, finalize the message and release the mux. +*/ + m->status = ret; +spi_mux_complete_cb (priv); + } + +/* +* On error the message is already finalized with m->status set, so +* the error reaches the caller; returning it would only make the core +* log it once more. +*/ +return 0 ; }static int spi_mux_probe (struct spi_device *spi)
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 5/14 spi: spi-ti-qspi: finalize message on transfer error
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
When ti_qspi_start_transfer_one() hits an error in qspi_transfer_msg(), such as a transfer timeout (-ETIMEDOUT), it unlocks qspi->list_lock and returns ret directly without writing QSPI_INVAL to QSPI_SPI_CMD_REG, setting m->status, or calling spi_finalize_current_message(host). Because the message is never finalized, spi_sync() or the spi_async() callback waits forever on queued transfers. If spi_sync() took the no-queue path, it returns -EINPROGRESS instead of the error, and the message's optimize state is never released. The frame is also left open, because the QSPI_INVAL write that ends it is skipped.
Set status to the transfer error and leave the transfer loop, so the error goes through the existing tail: unlock list_lock, write QSPI_INVAL, set m->status, and finalize the message. This fixes both paths, and the caller now gets the error from qspi_transfer_msg() instead of -EINVAL or -EINPROGRESS.
Tested at runtime with KUnit (spi_ti_qspi, ti_qspi_test, added later in this series) by injecting a QSPI_SPI_STATUS_REG WC poll timeout (-ETIMEDOUT) via logic_iomem emulated MMIO on ARCH=um.
--- drivers/spi/spi-ti-qspi.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/spi/spi-ti-qspi.c +2 -2
@@ -708,8 +708,8 @@ static int ti_qspi_start_transfer_one(struct spi_controller *host, ret =qspi_transfer_msg (qspi, t, transfer_len_words * wlen);if (ret) {dev_dbg (qspi->dev,"transfer message failed\n" ); -mutex_unlock (&qspi->list_lock); -return -EINVAL ; + status = ret; +break ; } m->actual_length += transfer_len_words * wlen;
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 6/14 spi: spi-mux: pass child CS and word delays to the parent
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
spi_mux_select() copies only max_speed_hz, mode and bits_per_word from the child to the spi-mux device on the parent controller. The child's cs_setup, cs_hold, cs_inactive and word_delay are never passed on, so the parent controller uses the spi-mux device's own delays (usually zero) for every child. A child that needs a CS setup time or a delay between words, for example from spi-cs-setup-delay-ns in its device tree node, does not get it when it sits behind a mux.
Save the spi-mux device's own delays at probe time, and when switching to a child, merge them with the child's in a new helper, spi_mux_merge_cs_delay(): use the longer CS delay of the two, so that the needs of the mux and of the child are both met; on a tie the spi-mux delay is kept. A delay given in SCK cycles cannot be converted to time without a transfer, so it cannot be compared: a child delay in SCK cycles is used when the spi-mux delay is zero, and otherwise the spi-mux delay is kept and a warning is printed once. If only the spi-mux delay is in SCK cycles, it is kept without a warning; device tree only gives delays in ns or us, so this case does not come from DT. The child's word_delay is used when it is set, else the spi-mux device's own. The delays are written before spi_setup() on the parent, so they reach both set_cs_timing() and the software CS delays in spi_set_cs().
spi_mux_select() overwrites the delays of the spi-mux device, so put its own delays back when the driver unbinds. Otherwise a later probe would save the last child's merged delays as the spi-mux device's own.
Unlike a device directly on a controller, whose CS delays are read on every message, the delays are now copied when the mux switches to the child or after the child calls spi_setup(). A child that changes its delays must call spi_setup() for the change to take effect.
This depends on patch 3 of this series ("spi: spi-mux: re-apply settings after child calls spi_setup()"), which makes the copy happen again after the child calls spi_setup().
Tested with KUnit (spi_mux: spi_mux_cs_delay_test and spi_mux_settings_lifecycle_test, added later in this series) on ARCH=um; they fail without this patch. Builds with W=1 on x86_64. Not tested on hardware.
--- drivers/spi/spi-mux.c | 83 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+)
drivers/spi/spi-mux.c +83 -0
@@ -34,6 +34,10 @@* @child_msg_dev: Used to store the spi_device pointer to the child * @mux: mux_control structure used to provide chip selects for * downstream spi devices +* @mux_cs_setup: CS setup delay of the spi-mux device itself +* @mux_cs_hold: CS hold delay of the spi-mux device itself +* @mux_cs_inactive: CS inactive delay of the spi-mux device itself +* @mux_word_delay: word delay of the spi-mux device itself */ struct spi_mux_priv {struct spi_device *spi;
@@ -43,8 +47,55 @@ struct spi_mux_priv {void *child_msg_context;struct spi_device *child_msg_dev;struct mux_control *mux; + +struct spi_delay mux_cs_setup; +struct spi_delay mux_cs_hold; +struct spi_delay mux_cs_inactive; +struct spi_delay mux_word_delay; }; +/* +* Pick the CS delay for the parent from the spi-mux device's own delay and +* the child's: the longer of the two, so that both are honored; on a tie the +* spi-mux delay is kept. A delay in SCK cycles cannot be converted to time +* without a transfer, so it cannot be compared: +* - a child delay in SCK cycles is used when the spi-mux delay is zero; +* otherwise the spi-mux delay is kept and a warning is printed once; +* - if only the spi-mux delay is in SCK cycles, it is kept. Device tree +* only gives delays in ns or us, so this case does not come from DT. +*/ +static void spi_mux_merge_cs_delay (struct spi_mux_priv *priv, +struct spi_delay *dst, +struct spi_delay *mux, +struct spi_delay *child) +{ +int mux_ns, child_ns; + +if (!child->value) { + *dst = *mux; +return ; + } + + mux_ns =spi_delay_to_ns (mux,NULL ); + child_ns =spi_delay_to_ns (child,NULL ); + +if (mux_ns >=0 && child_ns >=0 ) { + *dst = child_ns > mux_ns ? *child : *mux; +return ; + } + +if (child_ns <0 ) { +if (!mux->value) { + *dst = *child; +return ; + } +dev_warn_once (&priv->spi->dev, +"child CS delay in SCK cycles ignored, using the mux delay\n" ); + } + + *dst = *mux; +} +/* should not get called when the parent controller is doing a transfer */ static int spi_mux_select (struct spi_device *spi) {
@@ -65,6 +116,14 @@ static int spi_mux_select(struct spi_device *spi) priv->spi->max_speed_hz = spi->max_speed_hz; priv->spi->mode = spi->mode; priv->spi->bits_per_word = spi->bits_per_word; +spi_mux_merge_cs_delay (priv, &priv->spi->cs_setup, &priv->mux_cs_setup, + &spi->cs_setup); +spi_mux_merge_cs_delay (priv, &priv->spi->cs_hold, &priv->mux_cs_hold, + &spi->cs_hold); +spi_mux_merge_cs_delay (priv, &priv->spi->cs_inactive, + &priv->mux_cs_inactive, &spi->cs_inactive); + priv->spi->word_delay = spi->word_delay.value ? spi->word_delay : + priv->mux_word_delay; ret =spi_setup (priv->spi);if (ret) {
@@ -156,10 +215,26 @@ static int spi_mux_transfer_one_message(struct spi_controller *ctlr,return 0 ; } +/* +* spi_mux_select() overwrites the delays of the spi-mux device with the +* merged ones. Put its own delays back when the driver unbinds, so that a +* later probe does not take the last child's delays as its own. +*/ +static void spi_mux_restore_delays (void *data) +{ +struct spi_mux_priv *priv = data; + + priv->spi->cs_setup = priv->mux_cs_setup; + priv->spi->cs_hold = priv->mux_cs_hold; + priv->spi->cs_inactive = priv->mux_cs_inactive; + priv->spi->word_delay = priv->mux_word_delay; +} +static int spi_mux_probe (struct spi_device *spi) {struct spi_controller *ctlr;struct spi_mux_priv *priv; +int ret; ctlr =devm_spi_alloc_host (&spi->dev,sizeof (*priv));if (!ctlr)
@@ -168,6 +243,14 @@ static int spi_mux_probe(struct spi_device *spi)spi_set_drvdata (spi, ctlr); priv =spi_controller_get_devdata (ctlr); priv->spi = spi; + priv->mux_cs_setup = spi->cs_setup; + priv->mux_cs_hold = spi->cs_hold; + priv->mux_cs_inactive = spi->cs_inactive; + priv->mux_word_delay = spi->word_delay; + + ret =devm_add_action_or_reset (&spi->dev, spi_mux_restore_delays, priv); +if (ret) +return ret;/* * Increase lockdep class as these lock are taken while the parent bus
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 7/14 spi: add KUnit tests for message optimize state on queue errors
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
spi_async() and spi_sync() optimize a message before they queue it. If queuing fails, for example because another device holds spi_bus_lock() on the controller, because mem_ops rejects the message, or because the controller is suspended, the message is never finalized, and finalizing is where the core normally unoptimizes it.
Add KUnit tests with a fake controller that counts its optimize_message() and unoptimize_message() calls, splits transfers across a 2-byte boundary to exercise msg.resources, and tracks msg.opt_state. The tests cover both async and sync queue errors, verify split transfers are cleaned up and opt_state cleared, check that a message optimized by the peripheral driver is left alone on error, and check that a successful spi_sync() optimizes and unoptimizes the message exactly once on both queued and unqueued paths.
Without "spi: unoptimize message when queuing it fails" the queue error cases fail with unoptimize_count == 0, msg.resources leaked, and msg.optimized still true; the other cases pass.
Tested with KUnit on ARCH=um: all cases pass with the fixes in this series applied. Builds with W=1 on x86_64.
--- drivers/spi/Kconfig | 13 ++ drivers/spi/Makefile | 1 + drivers/spi/tests/.kunitconfig | 4 + drivers/spi/tests/Makefile | 1 + drivers/spi/tests/spi-core-kunit.c | 308 +++++++++++++++++++++++++++++ 5 files changed, 327 insertions(+) create mode 100644 drivers/spi/tests/.kunitconfig create mode 100644 drivers/spi/tests/spi-core-kunit.c
drivers/spi/Kconfig +13 -0
@@ -1398,6 +1398,19 @@ config SPI_DMA_KUNIT_TEST If unsure say N. +config SPI_CORE_KUNIT_TEST + tristate "KUnit tests for SPI core message optimize state" if !KUNIT_ALL_TESTS + depends on KUNIT + default KUNIT_ALL_TESTS + help + Build KUnit tests for the SPI core message optimize state. The tests + register a fake controller and check that spi_async() and spi_sync() + undo the optimization of a message they fail to queue, that a + message optimized by the peripheral driver is left alone, and that a + successful transfer optimizes and unoptimizes exactly once. + + If unsure say N. + config SPI_LOOPBACK_TEST tristate "spi loopback test framework support" depends on m
drivers/spi/Makefile +1 -0
@@ -14,6 +14,7 @@ obj-$(CONFIG_SPI_OFFLOAD) += spi-offload.o obj-$(CONFIG_SPI_SPIDEV) += spidev.o obj-$(CONFIG_SPI_LOOPBACK_TEST) += spi-loopback-test.o obj-$(CONFIG_SPI_DMA_KUNIT_TEST) += tests/ +obj-$(CONFIG_SPI_CORE_KUNIT_TEST) += tests/ # SPI master controller drivers (bus) obj-$(CONFIG_SPI_AIROHA_SNFI) += spi-airoha-snfi.o
drivers/spi/tests/.kunitconfig new file +4 -0
@@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_SPI=y +CONFIG_SPI_MASTER=y +CONFIG_SPI_CORE_KUNIT_TEST=y
drivers/spi/tests/Makefile +1 -0
@@ -1,3 +1,4 @@ # SPDX-License-Identifier: GPL-2.0-only obj-$(CONFIG_SPI_DMA_KUNIT_TEST) += spi-dma-kunit.o +obj-$(CONFIG_SPI_CORE_KUNIT_TEST) += spi-core-kunit.o
drivers/spi/tests/spi-core-kunit.c new file +308 -0
308 lines not on this page · raw message
Signature · 1 line
2.56.0.317.g454f8302e1-goog
Re: [PATCH 07/14] spi: add KUnit tests for message optimize state on queue errors
Quoted 5 lines · Joseph CT Chan
From: Joseph CT Chan <[email protected]>
spi_async()andspi_sync()optimize a message before they queue it. If queuing fails, for example because another device holdsspi_bus_lock()on the controller, becausemem_opsrejects the message, or because the
I was expecting a fake spi controller implementation rather than depending on an quirk of mem_ops to trigger the errors.
Quoted 3 lines
controller is suspended, the message is never finalized, and finalizing is where the core normally unoptimizes it.
...
drivers/spi/tests/spi-core-kunit.c line 132
Quoted 8 lines
drivers/spi/tests/spi-core-kunit.c new file +8
-0+static const struct spi_core_err_param spi_core_err_cases[] = { + {"bus_locked_async" ,ERR_BUS_LOCKED , -EBUSY }, + {"suspend_async" ,ERR_SUSPEND , -ESHUTDOWN }, + {"mem_ops_sync" ,ERR_MEM_OPS , -ENOTSUPP , true }, + {"pre_opt_locked" ,ERR_BUS_LOCKED , -EBUSY , false, true }, + {"pre_opt_mem_ops_sync" ,ERR_MEM_OPS , -ENOTSUPP , true, true }, + {"sync_success" ,ERR_NONE ,0 , true }, + {"sync_success_queued" ,ERR_NONE ,0 , true, false, true },
Can we get the field names here so we can see what true/false are actually doing?
Quoted 53 lines
drivers/spi/tests/spi-core-kunit.c new file +53
-0+KUNIT_EXPECT_EQ (test, ret, exp); +if (!exp) { +KUNIT_EXPECT_EQ (test, ctx->msg.actual_length,sizeof (ctx->tx)); +/* +* Normal error-free situation for the ERR_NONE control cases +* (sync_success on the noqueue fast-path and +* sync_success_queued on the kthread worker path): +* - Expected: (opt = 1, unopt = 1, state = false). +* Meaning: spi_sync() optimized ctx->msg once before the +* transfer (opt = 1) and unoptimized it once on completion +* (unopt = 1), leaving ctx->msg unoptimized (state = false: +* msg.resources is empty and the single 4-byte transfer is +* restored). +*/ +check_state (test, ctx,1 ,1 , false); +return ; + } + +/* +* Check message optimization state immediately after queuing fails +* across the 5 error test cases: +* +* Group A: Core-optimized queue failures (p->pre_opt == false) +* 1. bus_locked_async: spi_async() fails with -EBUSY while the bus +* lock is held by another caller. +* 2. suspend_async: spi_async() fails with -ESHUTDOWN while the +* controller queue is stopped by spi_controller_suspend(). +* 3. mem_ops_sync: spi_sync() fails with -ENOTSUPP on a controller +* that only implements mem_ops (ctlr->transfer == NULL). +* - Expected (patched): (opt = 1, unopt = 1, state = false). +* Meaning: spi_async() / __spi_sync() optimized ctx->msg (opt = 1) +* before queuing failed, and spi_maybe_unoptimize_message() on the +* error path immediately unoptimized it (unopt = 1), restoring +* ctx->msg to the clean unoptimized state (state = false: +* msg.optimized == false, msg.opt_state == NULL, split transfers +* in msg.resources freed, and original 1 transfer restored). +* - Broken behavior watched for (unpatched): (opt = 1, unopt = 0, +* state = true). +* Meaning: spi_async() / __spi_sync() returned the queue error +* without calling spi_maybe_unoptimize_message(), leaving +* unopt = 0 and ctx->msg stuck in the optimized state +* (state = true: msg.optimized == true, msg.opt_state == ctx, and +* the 2 split transfers leaked on msg.resources). +* +* Group B: Caller pre-optimized queue failures (p->pre_opt == true) +* 4. pre_opt_locked: caller pre-optimized ctx->msg via +* spi_optimize_message(), then spi_async() fails with -EBUSY. +* 5. pre_opt_mem_ops_sync: caller pre-optimized ctx->msg via +* spi_optimize_message(), then spi_sync() fails with -ENOTSUPP. +* - Expected (patched): (opt = 1, unopt = 0, state = true). +* Meaning: the caller explicitly pre-optimized ctx->msg (opt = 1, +* msg.pre_optimized == true) before submission, so +* spi_maybe_unoptimize_message() on the queue error path must
drivers/spi/tests/spi-core-kunit.c line 263
Quoted 10 lines
drivers/spi/tests/spi-core-kunit.c new file +10
-0+* preserve the caller's pre-optimization (unopt = 0, state = true) +* until the caller explicitly calls spi_unoptimize_message() below. +* - Broken behavior watched for (if error cleanup unconditionally +* called __spi_unoptimize_message() instead of +* spi_maybe_unoptimize_message()): (opt = 1, unopt = 1, +* state = false). +* Meaning: the error path would prematurely destroy the caller's +* pre-optimized state, causing a double-unoptimize when the caller +* later calls spi_unoptimize_message(). +*/
Do we really need the huge AI-generated comments?
Quoted 31 lines
drivers/spi/tests/spi-core-kunit.c new file +31
-0+check_state (test, ctx,1 , p->pre_opt ?0 :1 , p->pre_opt); +if (p->pre_opt) +spi_unoptimize_message (&ctx->msg); +if (p->mode ==ERR_MEM_OPS ) +return ; + +reinit_completion (&ctx->done); +KUNIT_ASSERT_EQ (test,spi_async (ctx->spi, &ctx->msg),0 ); +KUNIT_ASSERT_NE (test,wait_for_completion_timeout (&ctx->done,msecs_to_jiffies (1000 )),0 ); +KUNIT_EXPECT_EQ (test, ctx->msg.status,0 ); +/* +* Normal error-free situation after retry for the retryable error +* cases (bus_locked_async after spi_bus_unlock(), suspend_async after +* spi_controller_resume(), and pre_opt_locked after +* spi_unoptimize_message() + spi_bus_unlock()): +* - Expected (patched): (opt = 2, unopt = 2, state = false). +* Meaning: resubmitting the same ctx->msg after the transient error +* clears optimizes it a second time (opt = 2) and unoptimizes it on +* completion (unopt = 2), leaving ctx->msg unoptimized +* (state = false). +* - Broken behavior watched for (unpatched): (opt = 2, unopt = 1, +* state = false). +* Meaning: in bus_locked_async and suspend_async, the first failed +* attempt leaked ctx->msg in the optimized state (opt = 1, +* unopt = 0, state = true), so retrying the leaked message +* re-optimizes an already-optimized message (opt = 2) and only +* unoptimizes once when the retry completes (unopt = 1). +*/ +check_state (test, ctx,2 ,2 , false); +} +
Re: [PATCH 07/14] spi: add KUnit tests for message optimize state on queue errors
Quoted 2 lines · David Lechner
I was expecting a fake spi controller implementation rather than depending on an quirk of
mem_opsto trigger the errors.
Thanks for the review. For v2 I am trying to address this with a small
change: the mem_ops controller is gone, and the test controller gets its own transfer() that returns -EIO when a case asks for an error and otherwise hands the message to the normal queue. That keeps one fake controller for both the error and the retry. If you would rather see a separate controller with its own legacy transfer() set up before registration, let me know and I will do that instead.
Quoted 2 lines
Can we get the field names here so we can see what true/false are actually doing?
Will do in v2, here and in the spi-mux test tables.
Quoted 1 line
Do we really need the huge AI-generated comments?
No. v2 cuts them down to one-line comments in all three test files.
Thanks,
Joseph
PATCH 8/14 spi: spi-ti-qspi: add KUnit tests for transfer error finalization
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
Add KUnit tests for ti_qspi_start_transfer_one() covering the transfer error handling path.
On ARCH=um, emulate the TI QSPI controller MMIO via logic_iomem:
- ti_qspi_test: verify that queued and synchronous transfers hitting a ti_qspi_poll_wc() write completion timeout complete with -ETIMEDOUT, that QSPI_INVAL is written to end the frame, and that subsequent transfers succeed cleanly once QSPI_SPI_STATUS_REG reports QSPI_WC.
--- drivers/spi/Kconfig | 12 ++ drivers/spi/Makefile | 1 + drivers/spi/tests/.kunitconfig | 4 + drivers/spi/tests/Makefile | 1 + drivers/spi/tests/spi-ti-qspi-kunit.c | 225 ++++++++++++++++++++++++++ 5 files changed, 243 insertions(+) create mode 100644 drivers/spi/tests/spi-ti-qspi-kunit.c
drivers/spi/Kconfig +12 -0
@@ -1258,6 +1258,18 @@ config SPI_TI_QSPI This device supports single, dual and quad read support, while it only supports single write mode. +config SPI_TI_QSPI_KUNIT_TEST + bool "KUnit test for TI QSPI controller driver" if !KUNIT_ALL_TESTS + depends on KUNIT=y && SPI_TI_QSPI=y && INDIRECT_IOMEM && !HAVE_CLK + default KUNIT_ALL_TESTS + help + This option builds the KUnit test suite for the TI QSPI controller + driver. It verifies that transfer timeout errors are properly + finalized with -ETIMEDOUT and that QSPI_INVAL is written to the + command register. + + If unsure, say N. + config SPI_TLE62X0 tristate "Infineon TLE62X0 (for power switching)" depends on SYSFS
drivers/spi/Makefile +1 -0
@@ -15,6 +15,7 @@ obj-$(CONFIG_SPI_SPIDEV) += spidev.o obj-$(CONFIG_SPI_LOOPBACK_TEST) += spi-loopback-test.o obj-$(CONFIG_SPI_DMA_KUNIT_TEST) += tests/ obj-$(CONFIG_SPI_CORE_KUNIT_TEST) += tests/ +obj-$(CONFIG_SPI_TI_QSPI_KUNIT_TEST) += tests/ # SPI master controller drivers (bus) obj-$(CONFIG_SPI_AIROHA_SNFI) += spi-airoha-snfi.o
drivers/spi/tests/.kunitconfig +4 -0
@@ -1,4 +1,8 @@ CONFIG_KUNIT=y +CONFIG_KUNIT_UML_PCI=y CONFIG_SPI=y CONFIG_SPI_MASTER=y CONFIG_SPI_CORE_KUNIT_TEST=y +CONFIG_COMPILE_TEST=y +CONFIG_SPI_TI_QSPI=y +CONFIG_SPI_TI_QSPI_KUNIT_TEST=y
drivers/spi/tests/Makefile +1 -0
@@ -2,3 +2,4 @@ obj-$(CONFIG_SPI_DMA_KUNIT_TEST) += spi-dma-kunit.o obj-$(CONFIG_SPI_CORE_KUNIT_TEST) += spi-core-kunit.o +obj-$(CONFIG_SPI_TI_QSPI_KUNIT_TEST) += spi-ti-qspi-kunit.o
drivers/spi/tests/spi-ti-qspi-kunit.c new file +225 -0
225 lines not on this page · raw message
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 9/14 spi: spi-mux: add KUnit tests for forwarding errors and settings
In reply to Joseph CT ChanFrom: Joseph CT Chan <[email protected]>
Add a KUnit test suite (spi_mux) with a Device Tree overlay that instantiates a fake mux controller, a fake parent SPI controller, the real spi-mux driver, and two child SPI devices.
The suite covers three areas:
- spi_mux_error_test: forwarding errors (locked parent bus, invalid transfer length, mux select failure, and parent spi_setup() failure), verifying that the message is finalized, the mux is released, the caller's message fields and optimize state are restored, and subsequent transfers succeed.
- spi_mux_cs_delay_test: CS setup, hold, and inactive delay merging across ns, us, and SCK units, including zero-value SCK delays.
- spi_mux_settings_lifecycle_test: re-applying child mode, speed, bits_per_word, and delay changes after spi_setup(), switching between children with different delays, and restoring the spi-mux device's own delays on driver unbind.
--- drivers/spi/Kconfig | 14 + drivers/spi/Makefile | 1 + drivers/spi/tests/.kunitconfig | 4 + drivers/spi/tests/Makefile | 2 + drivers/spi/tests/kunit_spi_mux.dtso | 42 ++ drivers/spi/tests/spi-mux-kunit.c | 581 +++++++++++++++++++++++++++ 6 files changed, 644 insertions(+) create mode 100644 drivers/spi/tests/kunit_spi_mux.dtso create mode 100644 drivers/spi/tests/spi-mux-kunit.c
drivers/spi/Kconfig +14 -0
@@ -1386,6 +1386,20 @@ config SPI_MUX to be chip selects on this controller. It is still necessary to select one or more specific mux-controller drivers. +config SPI_MUX_KUNIT_TEST + tristate "KUnit tests for spi-mux" if !KUNIT_ALL_TESTS + depends on KUNIT && SPI_MUX && OF_OVERLAY + select DTC + default KUNIT_ALL_TESTS + help + Build KUnit tests for the SPI multiplexer driver. A device tree + overlay adds a fake parent controller, a test mux chip and an + spi-mux device with two children. The tests check that a message + which cannot be forwarded is completed with an error and releases + the mux, and that child settings and delays reach the parent. + + If unsure say N. + # # There are lots of SPI device types, with sensors and memory # being probably the most widely used ones.
drivers/spi/Makefile +1 -0
@@ -16,6 +16,7 @@ obj-$(CONFIG_SPI_LOOPBACK_TEST) += spi-loopback-test.o obj-$(CONFIG_SPI_DMA_KUNIT_TEST) += tests/ obj-$(CONFIG_SPI_CORE_KUNIT_TEST) += tests/ obj-$(CONFIG_SPI_TI_QSPI_KUNIT_TEST) += tests/ +obj-$(CONFIG_SPI_MUX_KUNIT_TEST) += tests/ # SPI master controller drivers (bus) obj-$(CONFIG_SPI_AIROHA_SNFI) += spi-airoha-snfi.o
drivers/spi/tests/.kunitconfig +4 -0
@@ -6,3 +6,7 @@ CONFIG_SPI_CORE_KUNIT_TEST=y CONFIG_COMPILE_TEST=y CONFIG_SPI_TI_QSPI=y CONFIG_SPI_TI_QSPI_KUNIT_TEST=y +CONFIG_OF=y +CONFIG_OF_OVERLAY=y +CONFIG_SPI_MUX=y +CONFIG_SPI_MUX_KUNIT_TEST=y
drivers/spi/tests/Makefile +2 -0
@@ -3,3 +3,5 @@ obj-$(CONFIG_SPI_DMA_KUNIT_TEST) += spi-dma-kunit.o obj-$(CONFIG_SPI_CORE_KUNIT_TEST) += spi-core-kunit.o obj-$(CONFIG_SPI_TI_QSPI_KUNIT_TEST) += spi-ti-qspi-kunit.o +obj-$(CONFIG_SPI_MUX_KUNIT_TEST) += spi-mux-kunit-test.o +spi-mux-kunit-test-y := spi-mux-kunit.o kunit_spi_mux.dtbo.o
drivers/spi/tests/kunit_spi_mux.dtso new file +42 -0
42 lines not on this page · raw message
drivers/spi/tests/spi-mux-kunit.c new file +581 -0
581 lines not on this page · raw message
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 10/14 spi: Split spi_write_then_read()
In reply to Joseph CT ChanFrom: Bart Van Assche <[email protected]>
Extract spi_write_then_read_buf() from spi_write_then_read(), move the buffer mutex to file scope as spi_buf_lock, and annotate buf with __guarded_by(&spi_buf_lock). Eliminate the correlated conditional unlock in spi_write_then_read() to enable Clang's static context analysis to verify lock balance and buffer access safety at compile time.
--- drivers/spi/spi.c | 95 ++++++++++++++++++++++++++--------------------- 1 file changed, 53 insertions(+), 42 deletions(-)
drivers/spi/spi.c +53 -42
@@ -5135,7 +5135,39 @@ EXPORT_SYMBOL_GPL(spi_bus_unlock);/* Portable code must never pass more than 32 bytes */ #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES) -static u8 *buf; +static DEFINE_MUTEX (spi_buf_lock); +static u8 *buf __guarded_by(&spi_buf_lock); + +static int spi_write_then_read_buf (struct spi_device *spi, +const void *txbuf,unsigned int n_tx, +void *rxbuf,unsigned int n_rx,u8 *local_buf) +{ +struct spi_message message; +struct spi_transfer x[2 ]; +int status; + +spi_message_init (&message); +memset (x,0 ,sizeof (x)); +if (n_tx) { + x[0 ].len = n_tx; +spi_message_add_tail (&x[0 ], &message); + } +if (n_rx) { + x[1 ].len = n_rx; +spi_message_add_tail (&x[1 ], &message); + } + +memcpy (local_buf, txbuf, n_tx); + x[0 ].tx_buf = local_buf; + x[1 ].rx_buf = local_buf + n_tx; + +/* Do the I/O */ + status =spi_sync (spi, &message); +if (status ==0 ) +memcpy (rxbuf, x[1 ].rx_buf, n_rx); + +return status; +}/** * spi_write_then_read - SPI synchronous write followed by read
@@ -5161,11 +5193,7 @@ int spi_write_then_read(struct spi_device *spi, const void *txbuf, unsigned n_tx, void *rxbuf, unsigned n_rx) { - static DEFINE_MUTEX(lock); - int status; -struct spi_message message; -struct spi_transfer x[2 ];u8 *local_buf;/*
@@ -5174,39 +5202,21 @@ int spi_write_then_read(struct spi_device *spi,* keep heap costs out of the hot path unless someone else is * using the pre-allocated buffer or the transfer is too large. */ -if ((n_tx + n_rx) >SPI_BUFSIZ || !mutex_trylock (&lock)) { - local_buf =kmalloc (max ((unsigned )SPI_BUFSIZ , n_tx + n_rx), -GFP_KERNEL |GFP_DMA ); -if (!local_buf) -return -ENOMEM ; - }else { - local_buf = buf; - } - -spi_message_init (&message); -memset (x,0 ,sizeof (x)); -if (n_tx) { - x[0 ].len = n_tx; -spi_message_add_tail (&x[0 ], &message); - } -if (n_rx) { - x[1 ].len = n_rx; -spi_message_add_tail (&x[1 ], &message); +if ((n_tx + n_rx) <=SPI_BUFSIZ &&mutex_trylock (&spi_buf_lock)) { + status =spi_write_then_read_buf (spi, txbuf, n_tx, rxbuf, n_rx, + buf); +mutex_unlock (&spi_buf_lock); +return status; } -memcpy (local_buf, txbuf, n_tx); - x[0 ].tx_buf = local_buf; - x[1 ].rx_buf = local_buf + n_tx; - -/* Do the I/O */ - status =spi_sync (spi, &message); -if (status ==0 ) -memcpy (rxbuf, x[1 ].rx_buf, n_rx); + local_buf =kmalloc (max ((unsigned int )SPI_BUFSIZ , n_tx + n_rx), +GFP_KERNEL |GFP_DMA ); +if (!local_buf) +return -ENOMEM ; -if (x[0 ].tx_buf == buf) -mutex_unlock (&lock); -else -kfree (local_buf); + status =spi_write_then_read_buf (spi, txbuf, n_tx, rxbuf, n_rx, + local_buf); +kfree (local_buf);return status; }
@@ -5371,10 +5381,10 @@ static int __init spi_init(void) {int status; - buf =kmalloc (SPI_BUFSIZ ,GFP_KERNEL ); -if (!buf) { - status = -ENOMEM ; - goto err0; + scoped_guard(mutex, &spi_buf_lock) { + buf =kmalloc (SPI_BUFSIZ ,GFP_KERNEL ); +if (!buf) +return -ENOMEM ; } status =bus_register (&spi_bus_type);
@@ -5403,9 +5413,10 @@ static int __init spi_init(void) err2:bus_unregister (&spi_bus_type); err1: -kfree (buf); - buf =NULL ; -err0: + scoped_guard(mutex, &spi_buf_lock) { +kfree (buf); + buf =NULL ; + }return status; }
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 11/14 spi: Add lock context annotations for bus_lock_mutex
In reply to Joseph CT ChanFrom: Bart Van Assche <[email protected]>
Annotate spi_bus_lock() with __acquires(), spi_bus_unlock() with __releases(), spi_sync_locked() and __spi_sync() with __must_hold(), and spi_sync() with __must_not_hold() for bus_lock_mutex in include/linux/spi/spi.h and drivers/spi/spi.c. Document exclusive SPI bus lock ownership and enable static context analysis to verify locking invariants across callers and the SPI core.
--- drivers/spi/spi.c | 5 +++++ include/linux/spi/spi.h | 12 ++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-)
drivers/spi/spi.c +5 -0
@@ -4959,6 +4959,7 @@ static void spi_complete(void *arg) }static int __spi_sync (struct spi_device *spi,struct spi_message *message) + __must_hold(&spi->controller->bus_lock_mutex) {DECLARE_COMPLETION_ONSTACK (done);unsigned long flags;
@@ -5045,6 +5046,7 @@ static int __spi_sync(struct spi_device *spi, struct spi_message *message)* Return: zero on success, else a negative error code. */ int spi_sync (struct spi_device *spi,struct spi_message *message) + __must_not_hold(&spi->controller->bus_lock_mutex) {int ret;
@@ -5073,6 +5075,7 @@ EXPORT_SYMBOL_GPL(spi_sync);* Return: zero on success, else a negative error code. */ int spi_sync_locked (struct spi_device *spi,struct spi_message *message) + __must_hold(&spi->controller->bus_lock_mutex) {return __spi_sync (spi, message); }
@@ -5094,6 +5097,7 @@ EXPORT_SYMBOL_GPL(spi_sync_locked);* Return: always zero. */ int spi_bus_lock (struct spi_controller *ctlr) + __acquires(&ctlr->bus_lock_mutex) {unsigned long flags;
@@ -5123,6 +5127,7 @@ EXPORT_SYMBOL_GPL(spi_bus_lock);* Return: always zero. */ int spi_bus_unlock (struct spi_controller *ctlr) + __releases(&ctlr->bus_lock_mutex) { ctlr->bus_lock_flag =0 ;
include/linux/spi/spi.h +8 -4
@@ -1497,10 +1497,14 @@ extern int spi_split_transfers_maxwords(struct spi_controller *ctlr,* they will sleep uninterruptibly until the async transfer completes. */ -extern int spi_sync (struct spi_device *spi,struct spi_message *message); -extern int spi_sync_locked (struct spi_device *spi,struct spi_message *message); -extern int spi_bus_lock (struct spi_controller *ctlr); -extern int spi_bus_unlock (struct spi_controller *ctlr); +extern int spi_sync(struct spi_device *spi, struct spi_message *message) + __must_not_hold(&spi->controller->bus_lock_mutex); +extern int spi_sync_locked(struct spi_device *spi, struct spi_message *message) + __must_hold(&spi->controller->bus_lock_mutex); +extern int spi_bus_lock(struct spi_controller *ctlr) + __acquires(&ctlr->bus_lock_mutex); +extern int spi_bus_unlock(struct spi_controller *ctlr) + __releases(&ctlr->bus_lock_mutex);/** * spi_sync_transfer - synchronous SPI data transfer
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 12/14 spi: spi-mem: Add lock context annotations
In reply to Joseph CT ChanFrom: Bart Van Assche <[email protected]>
Annotate spi_mem_access_start() with __cond_acquires() and spi_mem_access_end() with __releases() for both bus_lock_mutex and io_mutex in drivers/spi/spi-mem.c. Enable static context analysis to track controller lock ownership across SPI memory operations without false positive lock imbalance warnings.
--- drivers/spi/spi-mem.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/spi/spi-mem.c +4 -0
@@ -297,6 +297,8 @@ bool spi_mem_supports_op(struct spi_mem *mem, const struct spi_mem_op *op)EXPORT_SYMBOL_GPL (spi_mem_supports_op);static int spi_mem_access_start (struct spi_mem *mem) + __cond_acquires(0, &mem->spi->controller->bus_lock_mutex) + __cond_acquires(0, &mem->spi->controller->io_mutex) {struct spi_controller *ctlr = mem->spi->controller;
@@ -324,6 +326,8 @@ static int spi_mem_access_start(struct spi_mem *mem) }static void spi_mem_access_end (struct spi_mem *mem) + __releases(&mem->spi->controller->io_mutex) + __releases(&mem->spi->controller->bus_lock_mutex) {struct spi_controller *ctlr = mem->spi->controller;
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 13/14 spi: microchip-core-qspi: Add lock context annotations
In reply to Joseph CT ChanFrom: Bart Van Assche <[email protected]>
Annotate mchp_coreqspi_prepare_message() with __cond_acquires() and mchp_coreqspi_unprepare_message() with __releases() for op_lock in drivers/spi/spi-microchip-core-qspi.c. Document message-scoped ownership of op_lock across SPI core message preparation callbacks and enable static context analysis to verify error-path unlocking.
--- drivers/spi/spi-microchip-core-qspi.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/spi/spi-microchip-core-qspi.c +6 -0
@@ -603,7 +603,10 @@ static const struct spi_controller_mem_caps mchp_coreqspi_mem_caps = { .per_op_freq = true, }; +#define TO_MCHP_COREQSPI (ctlr) ((struct mchp_coreqspi *)spi_controller_get_devdata(ctlr)) +static int mchp_coreqspi_unprepare_message (struct spi_controller *ctlr,struct spi_message *m) + __releases(&TO_MCHP_COREQSPI(ctlr)->op_lock) {struct mchp_coreqspi *qspi =spi_controller_get_devdata (ctlr);
@@ -619,6 +622,7 @@ static int mchp_coreqspi_unprepare_message(struct spi_controller *ctlr, struct s }static int mchp_coreqspi_prepare_message (struct spi_controller *ctlr,struct spi_message *m) + __cond_acquires(0, &TO_MCHP_COREQSPI(ctlr)->op_lock) {struct mchp_coreqspi *qspi =spi_controller_get_devdata (ctlr);struct spi_transfer *t =NULL ;
@@ -685,6 +689,8 @@ static int mchp_coreqspi_prepare_message(struct spi_controller *ctlr, struct spireturn 0 ; }; +#undef TO_MCHP_COREQSPI +static int mchp_coreqspi_transfer_one (struct spi_controller *ctlr,struct spi_device *spi,struct spi_transfer *t) {
Signature · 1 line
2.56.0.317.g454f8302e1-goog
PATCH 14/14 spi: Enable lock context analysis
In reply to Joseph CT ChanFrom: Bart Van Assche <[email protected]>
Set CONTEXT_ANALYSIS := y in drivers/spi/Makefile and drivers/spi/tests/Makefile to enable compile-time lock context checking for the SPI core, controller drivers, and KUnit tests when building with CONFIG_WARN_CONTEXT_ANALYSIS=y.
--- drivers/spi/Makefile | 2 ++ drivers/spi/tests/Makefile | 2 ++ 2 files changed, 4 insertions(+)
drivers/spi/Makefile +2 -0
@@ -5,6 +5,8 @@ ccflags-$(CONFIG_SPI_DEBUG) := -DDEBUG +CONTEXT_ANALYSIS := y + # small core, mostly translating board-specific # config declarations into driver model code obj-$(CONFIG_SPI_MASTER) += spi.o
drivers/spi/tests/Makefile +2 -0
@@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only +CONTEXT_ANALYSIS := y + obj-$(CONFIG_SPI_DMA_KUNIT_TEST) += spi-dma-kunit.o obj-$(CONFIG_SPI_CORE_KUNIT_TEST) += spi-core-kunit.o obj-$(CONFIG_SPI_TI_QSPI_KUNIT_TEST) += spi-ti-qspi-kunit.o
Signature · 1 line
2.56.0.317.g454f8302e1-goog
Quoted 5 lines · Joseph CT Chan
From: Joseph CT Chan <[email protected]>
Hi Mark,
This series fixes four categories of error-handling and configuration
For future reference, it is easier on maintainers/reviewers if you split up independent patches into separate series.
For example, patches 1 and 7 could have been a series on it's own. 7 depends on 1, but none of the other patches are related AFAICT.
Quoted 6 lines
propagation bugs across the SPI core, spi-mux, and spi-ti-qspi (Patches 1-6), adds three KUnit test suites on ARCH=um with detailed inline comments explaining the expected vs. broken states at each assertion (Patches 7-9), and enables Clang compile-time lock context analysis across the SPI subsystem (Patches 10-14).
Quoted 5 lines · David Lechner
For future reference, it is easier on maintainers/reviewers if you split up independent patches into separate series.
For example, patches 1 and 7 could have been a series on it's own. 7 depends on 1, but none of the other patches are related AFAICT.
Thanks, that makes sense. I will send v2 as four series, with patches 1 and 7 on their own. One thing I found while splitting: the spi-mux test for a locked parent bus also needs patch 1, because spi-mux forwards the message with spi_async() on the parent and that is the path patch 1 fixes. The spi-mux and spi-ti-qspi fixes themselves apply on their own.
Thanks,
Joseph