Search code examples
network-programmingdriverlinux-device-driverdmapci-e

difference between pci_alloc_consistent and dma_alloc_coherent


I am working on pcie based network driver. Different examples use one of pci_alloc_consistent or dma_alloc_coherent to get memory for transmission and reception descriptors. Which one is better if any and what is the difference between the two?


Solution

  • The difference is subtle but quite important. pci_alloc_consistent() is the older function of the two and legacy drivers still use it. Nowadays, pci_alloc_consistent() just calls dma_alloc_coherent().

    The difference? The type of the allocated memory.

    • pci_alloc_consistent() - Allocates memory of type GFP_ATOMIC. Allocation does not sleep, for use in e.g. interrupt handlers, bottom halves.

    • dma_alloc_coherent()- You specify yourself what type of memory to allocate. You should not use the high priority GFP_ATOMIC memory unless you need it and in most cases, you will be fine with GFP_KERNEL allocations.

    Kernel 3.18 definition of pci_alloc_consistent() is very simple, namely:

     static inline void *
     pci_alloc_consistent(struct pci_dev *hwdev, size_t size,
                          dma_addr_t *dma_handle)
     {
             return dma_alloc_coherent(hwdev == NULL ? NULL : &hwdev->dev, size, dma_handle, GFP_ATOMIC);
     }
    

    In short, use dma_alloc_coherent().