Search code examples
clinux-kernellinux-device-driverdevice-driverdma

Can I call dma_unmap_single after dma_sync_single_for_cpu?


I have a situation where I need to call dma_unmap_single after dma_sync_single_for_cpu. Below is my scenario.

  1. Allocate memory for a buffer using kmalloc()
  2. Map the buffer to device using dma_map_single with DMA_FROM_DEVICE direction.
  3. After receiving packet, get buffer ownership using dma_sync_single_for_cpu.
  4. After some time, if some other function in kernel using same buffer, unmap buffer from device using dma_unmap_single with DMA_FROM_DEVICE direction.

Are all the above steps acceptable?


Solution

  • The buffer "ownership" (CPU or device) matters only for deciding who is allowed to access the buffer's contents.

    dma_unmap_single() does not care about the contents; it can be called in either state.

    Please note that after the DMA unmapping, the memory again "belongs" to the CPU. If you are doing only a single DMA transfer, you do not need to call dma_sync_single_for_cpu(); you can just read the buffer after the dma_unmap_single() call.