• Hans Verkuil's avatar
    V4L/DVB: videobuf-dma-sg: set correct size in last sg element · 2fc11536
    Hans Verkuil authored
    This fixes a nasty memory corruption bug when using userptr I/O.
    The function videobuf_pages_to_sg() sets up the scatter-gather list for the
    DMA transfer to the userspace pages. The first transfer is setup correctly
    (the size is set to PAGE_SIZE - offset), but all other transfers have size
    PAGE_SIZE. This is wrong for the last transfer which may be less than PAGE_SIZE.
    
    Most, if not all, drivers will program the boards DMA engine correctly, i.e.
    even though the size in the last sg element is wrong, they will do their
    own size calculations and make sure the right amount is DMA-ed, and so seemingly
    prevent memory corruption.
    
    However, behind the scenes the dynamic DMA mapping support (in lib/swiotlb.c)
    may create bounce buffers if the memory pages are not in DMA-able memory.
    This happens for example on a 64-bit linux with a board that only supports
    32-bit DMA.
    
    These bounce buffers DO use the information in the sg list to determine the
    size. So while the DMA engine transfers the correct amount of data, when the
    data is 'bounced' back too much is copied, causing buffer overwrites.
    
    The fix is simple: calculate and set the correct size for the last sg list
    element.
    Signed-off-by: default avatarHans Verkuil <hans.verkuil@tandberg.com>
    Cc: stable@kernel.org
    Signed-off-by: default avatarMauro Carvalho Chehab <mchehab@redhat.com>
    2fc11536
videobuf-dma-sg.c 16.2 KB