PROBLEM
- Normally if you want to allocate a DMA buffer, or get a physical address, this is done in kernel space, as user code should never have to muck around with physical addresses.
- Hugetlbfs only provides user-space mappings to allocate 1GB huge pages, and get user-space virtual addresses
- No function exists to map a user hugepage virtual address to a physical address
EUREKA
But the function does exist! Buried deep in the 2.6 kernel source code lies this function to get a struct page from a virtual address, marked as "just for testing" and blocked with #if 0:
#if 0 /* This is just for testing */
struct page *
follow_huge_addr(struct mm_struct *mm, unsigned long address, int write)
{
unsigned long start = address;
int length = 1;
int nr;
struct page *page;
struct vm_area_struct *vma;
vma = find_vma(mm, addr);
if (!vma || !is_vm_hugetlb_page(vma))
return ERR_PTR(-EINVAL);
pte = huge_pte_offset(mm, address);
/* hugetlb should be locked, and hence, prefaulted */
WARN_ON(!pte || pte_none(*pte));
page = &pte_page(*pte)[vpfn % (HPAGE_SIZE/PAGE_SIZE)];
WARN_ON(!PageHead(page));
return page;
}
SOLUTION: Since the function above isn't actually compiled into the kernel, you will need to add it to your driver source.
USER SIDE WORKFLOW
- Allocate 1gb hugepages at boot with kernel boot options
- Call get_huge_pages() with hugetlbfs to get user space pointer (virtual address)
- Pass user virtual address (normal pointer cast to unsigned long) to driver ioctl
KERNEL DRIVER WORKFLOW
- Accept user virtual address via ioctl
- Call follow_huge_addr to get the struct page*
- Call page_to_phys on the struct page* to get the physical address
- Provide physical address to device for DMA
- Call kmap on the struct page* if you also want a kernel virtual pointer
DISCLAIMER
- The above steps are being recollected several years later. I have lost access to the original source code. Do your due diligence and make sure I'm not forgetting a step.
- The only reason this works is because 1GB huge pages are allocated at boot time and their physical addresses are permanently locked. Don't try to map a non-1GBhugepage-backed user virtual address into a DMA physical address! You're going to have a bad time!
- Test carefully on your system to confirm that your 1GB huge pages are in fact locked in physical memory and that everything is working exactly. This code worked flawlessly on my setup, but there is great danger here if something goes wrong.
- This code is only guaranteed to work on x86/x64 architecture (where physical address == bus address), and on kernel version 2.6.XX. There may be an easier way to do this on later kernel versions, or it may be completely impossible now.