Re: block: DMA alignment of IO buffer allocated from slab

From: Matthew Wilcox
Date: Mon Sep 24 2018 - 14:58:00 EST

On Mon, Sep 24, 2018 at 09:19:44AM -0700, Bart Van Assche wrote:
> That means that two buffers allocated with kmalloc() may share a cache line on
> x86-64. Since it is allowed to use a buffer allocated by kmalloc() for DMA, can
> this lead to data corruption, e.g. if the CPU writes into one buffer allocated
> with kmalloc() and a device performs a DMA write to another kmalloc() buffer and
> both write operations affect the same cache line?

You're not supposed to use kmalloc memory for DMA. This is why we have
dma_alloc_coherent() and friends. Also, from DMA-API.txt:

Memory coherency operates at a granularity called the cache
line width. In order for memory mapped by this API to operate
correctly, the mapped region must begin exactly on a cache line
boundary and end exactly on one (to prevent two separately mapped
regions from sharing a single cache line). Since the cache line size
may not be known at compile time, the API will not enforce this
requirement. Therefore, it is recommended that driver writers who
don't take special care to determine the cache line size at run time
only map virtual regions that begin and end on page boundaries (which
are guaranteed also to be cache line boundaries).