[PATCH v2 1/6] spi: Allow spi_delay_exec() to be used from atomic contexts

Heiko Stuebner heiko at sntech.de
Fri Nov 13 05:50:12 PST 2026


From: Heiko Stuebner <heiko.stuebner at cherry.de>

When using spi_delay_exec() only the fsleep in the subsequent
_spi_transfer_delay_ns() can actually sleep.

As we might want to use spi_delay_exec() from atomic contexts in the
future, move the might_sleep() up to the actual place that matters
and fall back to the existing ndelay if called from an atomic context.

This also introduces a helper spi_in_atomic_mode() to determine when
that is the case. As this should really only be used in very special
occasions, it really restricts things to late system states.

Signed-off-by: Heiko Stuebner <heiko.stuebner at cherry.de>
---
 drivers/spi/spi.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c
index 40cda0037ea5..e79f16aca1a3 100644
--- a/drivers/spi/spi.c
+++ b/drivers/spi/spi.c
@@ -1700,15 +1700,27 @@ static int spi_transfer_wait(struct spi_controller *ctlr,
 	return 0;
 }
 
+/*
+ * We only allow atomic transfers for very late communication, e.g. to access a
+ * PMIC when powering down. Atomic transfers are a corner case and not for
+ * generic use!
+ */
+static inline bool spi_in_atomic_mode(void)
+{
+	return system_state > SYSTEM_RUNNING &&
+	       (IS_ENABLED(CONFIG_PREEMPT_COUNT) ? !preemptible() : irqs_disabled());
+}
+
 static void _spi_transfer_delay_ns(u32 ns)
 {
 	if (!ns)
 		return;
-	if (ns <= NSEC_PER_USEC) {
+	if (ns <= NSEC_PER_USEC || spi_in_atomic_mode()) {
 		ndelay(ns);
 	} else {
 		u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
 
+		might_sleep();
 		fsleep(us);
 	}
 }
@@ -1756,8 +1768,6 @@ int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
 {
 	int delay;
 
-	might_sleep();
-
 	if (!_delay)
 		return -EINVAL;
 
-- 
2.53.0




More information about the Linux-rockchip mailing list