In sh_mobile_xfer(), i2c_put_dma_safe_msg_buf() is called immediately after wait_event_timeout(), before checking for a timeout or an active DMA transfer and calling sh_mobile_i2c_cleanup_dma(). On a timeout or early NACK wakeup while DMA is still running, the bounce buffer is freed while still mapped for DMA.
Select the DMA channel from the immutable message direction flag rather than mutable pd->dma_direction, always synchronise and terminate the channel in sh_mobile_xfer() before calling i2c_put_dma_safe_msg_buf(), re-check pd->dma_direction after dmaengine_terminate_sync() to avoid double unmapping, and update pd->pos, pd->stop_after_dma, and ICIC before clearing pd->dma_direction in sh_mobile_i2c_dma_callback().
Fixes: cebc07d84ad7 ("i2c: sh_mobile: fix leak when using DMA bounce buffer") Closes: https://sashiko.dev/#/bug/linux-af86edab-c752-40c1-9d09-2abb42f140f3 Cc: stable@vger.kernel.org Signed-off-by: Lee Jones lee@kernel.org --- drivers/i2c/busses/i2c-sh_mobile.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)
diff --git a/drivers/i2c/busses/i2c-sh_mobile.c b/drivers/i2c/busses/i2c-sh_mobile.c index 0d10742a8ec0..d7aa710767c7 100644 --- a/drivers/i2c/busses/i2c-sh_mobile.c +++ b/drivers/i2c/busses/i2c-sh_mobile.c @@ -445,12 +445,17 @@ static irqreturn_t sh_mobile_i2c_isr(int irq, void *dev_id)
static void sh_mobile_i2c_cleanup_dma(struct sh_mobile_i2c_data *pd, bool terminate) { - struct dma_chan *chan = pd->dma_direction == DMA_FROM_DEVICE + struct dma_chan *chan = (pd->msg->flags & I2C_M_RD) ? pd->dma_rx : pd->dma_tx;
/* only allowed from thread context! */ - if (terminate) + if (terminate) { + if (IS_ERR_OR_NULL(chan)) + return; dmaengine_terminate_sync(chan); + if (pd->dma_direction == DMA_NONE) + return; + }
dma_unmap_single(chan->device->dev, sg_dma_address(&pd->sg), pd->msg->len, pd->dma_direction); @@ -462,11 +467,10 @@ static void sh_mobile_i2c_dma_callback(void *data) { struct sh_mobile_i2c_data *pd = data;
- sh_mobile_i2c_cleanup_dma(pd, false); pd->pos = pd->msg->len; pd->stop_after_dma = true; - iic_set_clr(pd, ICIC, 0, ICIC_TDMAE | ICIC_RDMAE); + sh_mobile_i2c_cleanup_dma(pd, false); }
static struct dma_chan *sh_mobile_i2c_request_dma_chan(struct device *dev, @@ -682,15 +686,15 @@ static int sh_mobile_xfer(struct sh_mobile_i2c_data *pd, pd->sr & (ICSR_TACK | SW_DONE), pd->adap.timeout);
+ if (pd->dma_buf) + sh_mobile_i2c_cleanup_dma(pd, true); + /* 'stop_after_dma' tells if DMA xfer was complete */ i2c_put_dma_safe_msg_buf(pd->dma_buf, pd->msg, pd->stop_after_dma); }
if (!time_left) { - if (pd->dma_direction != DMA_NONE) - sh_mobile_i2c_cleanup_dma(pd, true); - err = -ETIMEDOUT; break; }