Skip to content

Commit fa2d1ea

Browse files
Mani-Sadhasivamcfriedt
authored andcommitted
drivers: spi: Use timeout for transfer completion
Instead of waiting forever for the SPI transfer to complete, let's use a timeout value and bail out if elapsed. The timeout value logic is, xfer_len/frequency + tolerance Tolerance value can be modified using a Kconfig symbol, CONFIG_SPI_COMPLETION_TIMEOUT_TOLERANCE. It defaults to 200ms. Fixes: #33192 Signed-off-by: Manivannan Sadhasivam <[email protected]>
1 parent a95457a commit fa2d1ea

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

drivers/spi/Kconfig

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ config SPI_INIT_PRIORITY
3131
help
3232
Device driver initialization priority.
3333

34+
config SPI_COMPLETION_TIMEOUT_TOLERANCE
35+
int "Completion timeout tolerance (ms)"
36+
default 200
37+
help
38+
The tolerance value in ms for the SPI completion timeout logic.
39+
3440
module = SPI
3541
module-str = spi
3642
source "subsys/logging/Kconfig.template.log_config"

drivers/spi/spi_context.h

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,25 @@ static inline void spi_context_release(struct spi_context *ctx, int status)
112112
static inline int spi_context_wait_for_completion(struct spi_context *ctx)
113113
{
114114
int status = 0;
115+
uint32_t timeout_ms;
116+
117+
timeout_ms = MAX(ctx->tx_len, ctx->rx_len) * 8 * 1000 /
118+
ctx->config->frequency;
119+
timeout_ms += CONFIG_SPI_COMPLETION_TIMEOUT_TOLERANCE;
120+
115121
#ifdef CONFIG_SPI_ASYNC
116122
if (!ctx->asynchronous) {
117-
k_sem_take(&ctx->sync, K_FOREVER);
123+
if (k_sem_take(&ctx->sync, K_MSEC(timeout_ms))) {
124+
LOG_ERR("Timeout waiting for transfer complete");
125+
return -ETIMEDOUT;
126+
}
118127
status = ctx->sync_status;
119128
}
120129
#else
121-
k_sem_take(&ctx->sync, K_FOREVER);
130+
if (k_sem_take(&ctx->sync, K_MSEC(timeout_ms))) {
131+
LOG_ERR("Timeout waiting for transfer complete");
132+
return -ETIMEDOUT;
133+
}
122134
status = ctx->sync_status;
123135
#endif /* CONFIG_SPI_ASYNC */
124136

0 commit comments

Comments
 (0)