Re: [PATCH] spi: Ensure memory used for spi_write_then_read() is DMA safe

From: Arnd Bergmann
Date: Wed Mar 26 2025 - 17:46:29 EST


On Wed, Mar 26, 2025, at 17:20, Mark Brown wrote:
> On Fri, Mar 21, 2025 at 08:42:12PM +0100, Arnd Bergmann wrote:
>> Using dma_alloc_noncoherent() should make the implementation
>> much nicer than GFP_DMA in the past, so we could add a bus
>> specific helper for SPI that checks if the controller actually
>> wants to do DMA and whether the buffer is problematic at all,
>> and then decides to either allocate a bounce buffer and
>> fill the sg table with the correct DMA address, map the
>> existing buffer, or pass it without mapping depending on
>> what the device needs.
>
> That query feels a lot like spi_optimize_message(). Which should
> possibly then just do the bouncing if it's needed.

Would that require attaching the temporary buffer to the message
or could that be a permanent bounce buffer?

The idea I had come up with was to have one or two pages
permanently allocated in the spi_controller, the spi_device
or the regmap and then use appropriate serialization to
ensure only one transfer uses it at a time, similar to
how spi_controller->dummy_tx gets allocated, or how
spi_write_then_read() uses its small global buffer.

The advantage of using a permanent buffer is that it
avoids both the kmalloc and the iommu mapping in the fast
path and only needs to do the dma_sync_single_()
for cache management, which should be faster for small
transfers.

The downside would be a higher memory usage and the
need for a mutex.

Arnd