Skip to contentSkip to conversation

udmabuf: speed up mmap() of huge page backed buffers

PATCH In review Qiliang Yuan 3 participants 8 messages Dec 1 – Dec 4

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v3 cover udmabuf: speed up mmap() of huge page backed buffers

QEMU and crosvm export virtio-gpu blob resources from guest memory as udmabufs, which the host renderer and display mmap(). The guest memory is often backed by 2 MiB huge pages, yet udmabuf maps it 4 KiB at a time:
mapping and touching a 4 GiB buffer inserts a million PTEs and takes over 200 ms.

Patch 1 has mmap() of a dma-buf align large mappings to PMD boundaries, which any exporter mapping contiguous memory with PMDs needs, such as the proposed VFIO dma-buf mmap() [1]. Patch 2 maps the huge page backed ranges of a udmabuf with PMDs, which cuts the time to map and touch it by 93% for hugetlb and shmem THP backed buffers and adds under 1 ms per GiB for 4 KiB backed ones. It depends on Lorenzo's series in mm/core [2]. Patch 3 adds selftests.

[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]

---
V2 -> V3:
- 1/3: Add Reviewed-by (T.J. Mercier).
- 2/3: Pre-fault only the PMD-sized range of the fault in all cases and drop the THP check before it (T.J. Mercier).
- 2/3: Say in the commit message that it depends on Lorenzo's series and that 4 KiB backed buffers now take a fault per PMD-sized range, with numbers for them under PR_SET_THP_DISABLE (T.J. Mercier).
- 2/3: Comment that the THP sysfs settings don't apply to the mapping (T.J. Mercier).
- 3/3: Size the buffer from hpage_pmd_size and Hugepagesize, use 8 huge pages, and test a buffer at a one page offset and a fault next to a PMD after THP was disabled (T.J. Mercier).

V1 -> V2:
- 1/3: Add Reviewed-by (Christian König).
- 2/3: Pre-fault only the faulting PMD range when the VMA can't have PMDs, so that disabling THP after a PMD was mapped no longer has vmf_insert_pfn() walk into that PMD (Sashiko review).
- 3/3: Give each huge page its own data pattern, skip the alignment check for 32-bit tasks and read the inherited mapping in the forked child (Sashiko review).

v2: https://lore.kernel.org/r/[email protected]
v1: https://lore.kernel.org/r/[email protected]

---
Qiliang Yuan (3):
dma-buf: align large mappings to PMD boundaries
udmabuf: map huge page backed ranges with PMDs selftests/udmabuf: test mapping a huge page backed udmabuf

 drivers/dma-buf/dma-buf.c                         |   1 +
 drivers/dma-buf/udmabuf.c                         |  73 ++++++++-
 tools/testing/selftests/drivers/dma-buf/udmabuf.c | 171 +++++++++++++++++++++-
 3 files changed, 239 insertions(+), 6 deletions(-)

---
base-commit: 28f286b0dfa9610d4ee2447415e964e8bc603056
change-id: 20261121-feat-udmabuf-huge-pfnmap-3258272d077e

Best regards,

Signature · 1 line
Qiliang Yuan <[email protected]>
#1 lore raw

PATCH v3 1/3 dma-buf: align large mappings to PMD boundaries

A dma-buf exporter whose buffer is backed by physically contiguous memory can map it with PMDs from a ->huge_fault() handler, which only works where the user address and the buffer offset are aligned alike to PMD_SIZE.

dma_buf_fops has no ->get_unmapped_area(), so mmap() places a dma-buf at whatever page aligned address the default allocator returns. A 4 GiB udmabuf, for one, lands 616 KiB past a 2 MiB boundary, and then none of its PMD-sized ranges can be mapped with a PMD.

Use thp_get_unmapped_area(), as filesystems that support huge mappings do. It aligns a mapping that covers at least one whole PMD to the buffer offset and leaves smaller mappings where they would be placed anyway.

---
 drivers/dma-buf/dma-buf.c | 1 +
 1 file changed, 1 insertion(+)
drivers/dma-buf/dma-buf.c +1 -0
index c81c0e2ed4f87..2db3059824c71 100644
@@ -608,6 +608,7 @@ static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
 static const struct file_operations dma_buf_fops = {
 	.release	= dma_buf_file_release,
 	.mmap		= dma_buf_mmap_internal,
+	.get_unmapped_area = thp_get_unmapped_area,
 	.llseek		= dma_buf_llseek,
 	.poll		= dma_buf_poll,
 	.unlocked_ioctl	= dma_buf_ioctl,
Signature · 1 line
2.43.0
#2 lore raw

PATCH v3 2/3 udmabuf: map huge page backed ranges with PMDs

In reply to Qiliang Yuan

QEMU and crosvm hand guest memory to the host renderer and display as udmabufs for virtio-gpu blob resources. The guest memory is a memfd that is often backed by 2 MiB huge pages, and the host process mmap()s the dma-buf to access it with the CPU.

udmabuf maps every page with its own PTE: the first fault inserts a PFN for each 4 KiB page of the whole VMA. Mapping and touching 4 GiB this way takes over 200 ms and a million PTEs, although the memory behind it is 2048 huge pages.

Add a ->huge_fault() handler that maps a PMD-sized range with one PMD when it is backed by an aligned run of contiguous PFNs, and falls back to PTEs otherwise. Limit the pre-mapping on a fault to the PMD-sized range of the fault, so that it stays within one page table and never covers a range that is mapped with a PMD. Buffers backed by 4 KiB pages now take a fault for each PMD-sized range rather than one for the whole VMA, about 1.5 us each, or under 1 ms per GiB. The THP settings in sysfs don't apply to VM_PFNMAP mappings, so only MADV_NOHUGEPAGE and PR_SET_THP_DISABLE stop the PMD mappings.

This depends on the series "mm: fix races between huge and non-huge faults in PFN mappings", which keeps a PTE fault that races with a PMD fault on the same range, after THP was disabled, from hitting a VM_BUG_ON or failing with VM_FAULT_OOM.

Mapping a udmabuf over a memfd filled with data and reading a byte of each 4 KiB page through the mapping, base and patched kernels alternating over 6 rounds of 5 runs (7 runs for shmem 4K), median of the per-round medians and range in parentheses; nothp marks a task with PR_SET_THP_DISABLE set:

backing size before (ms) after (ms) change

  hugetlb         256M    12.7 (12.6-13.9)      0.9 (0.9-0.9)     -93%
  hugetlb           1G    50.5 (50.5-50.9)      3.7 (3.6-3.7)     -93%
  hugetlb           4G       201 (201-202)   13.8 (13.5-13.9)     -93%
  hugetlb           8G       402 (402-403)   26.8 (26.3-27.0)     -93%
  shmem THP         1G    50.6 (50.6-50.8)      3.7 (3.6-3.7)     -93%
  shmem THP         4G       201 (199-203)   13.7 (13.3-13.8)     -93%
  shmem 4K          1G    50.5 (50.0-50.6)   51.4 (51.2-52.1)      +2%
  shmem 4K nothp    1G    50.5 (50.2-50.7)   51.4 (51.1-51.5)      +2%
  shmem 4K          4G       202 (201-202)      204 (204-205)      +1%
---
 drivers/dma-buf/udmabuf.c | 73 +++++++++++++++++++++++++++++++++++++++++++----
 1 file changed, 68 insertions(+), 5 deletions(-)
drivers/dma-buf/udmabuf.c +68 -5
index 018937435356e..dd98d5a1b69fc 100644
@@ -44,12 +44,67 @@ struct udmabuf {
 	struct miscdevice *device;
 };
 
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+/*
+ * Return whether the PMD-sized range of @vma at @addr is backed by one aligned
+ * run of contiguous PFNs, which can then be mapped with a single PMD.
+ */
+static bool udmabuf_pmd_mappable(struct vm_area_struct *vma, unsigned long addr,
+				 unsigned long *pfn)
+{
+	struct udmabuf *ubuf = vma->vm_private_data;
+	const pgoff_t nr = PMD_SIZE >> PAGE_SHIFT;
+	unsigned long first;
+	pgoff_t pgoff, i;
+
+	if (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP))
+		return false;
+
+	if (!IS_ALIGNED(addr, PMD_SIZE) || addr < vma->vm_start ||
+	    vma->vm_end - addr < PMD_SIZE)
+		return false;
+
+	pgoff = vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT);
+	if (pgoff >= ubuf->pagecount || ubuf->pagecount - pgoff < nr)
+		return false;
+
+	first = page_to_pfn(ubuf->pages[pgoff]);
+	if (!IS_ALIGNED(first, nr))
+		return false;
+
+	for (i = 1; i < nr; i++) {
+		if (page_to_pfn(ubuf->pages[pgoff + i]) != first + i)
+			return false;
+	}
+
+	*pfn = first;
+	return true;
+}
+
+/*
+ * The THP settings in /sys/kernel/mm/transparent_hugepage/ don't apply to
+ * VM_PFNMAP mappings, so this is called even when THP is set to "never".
+ * Only MADV_NOHUGEPAGE or PR_SET_THP_DISABLE keep it from being called.
+ */
+static vm_fault_t udmabuf_vm_huge_fault(struct vm_fault *vmf,
+					unsigned int order)
+{
+	unsigned long pfn;
+
+	if (order != PMD_ORDER ||
+	    !udmabuf_pmd_mappable(vmf->vma, vmf->address & PMD_MASK, &pfn))
+		return VM_FAULT_FALLBACK;
+
+	return vmf_insert_pfn_pmd(vmf, pfn, vmf->flags & FAULT_FLAG_WRITE);
+}
+#endif
+
 static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 {
 	struct vm_area_struct *vma = vmf->vma;
 	struct udmabuf *ubuf = vma->vm_private_data;
 	pgoff_t pgoff = vmf->pgoff;
-	unsigned long addr, pfn;
+	unsigned long addr, end, pfn;
 	vm_fault_t ret;
 
 	if (pgoff >= ubuf->pagecount)
@@ -61,11 +116,16 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 	if (ret & VM_FAULT_ERROR)
 		return ret;
 
-	/* pre fault */
-	pgoff = vma->vm_pgoff;
-	addr = vma->vm_start;
+	/*
+	 * Pre-fault the rest of the PMD-sized range of the fault. Staying
+	 * within its page table keeps the walk off the ranges that
+	 * udmabuf_vm_huge_fault() maps with a PMD.
+	 */
+	addr = max(vma->vm_start, vmf->address & PMD_MASK);
+	end = pmd_addr_end(vmf->address, vma->vm_end);
+	pgoff = vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT);
 
-	for (; addr < vma->vm_end; pgoff++, addr += PAGE_SIZE) {
+	for (; addr < end; pgoff++, addr += PAGE_SIZE) {
 		if (addr == vmf->address)
 			continue;
 
@@ -89,6 +149,9 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 
 static const struct vm_operations_struct udmabuf_vm_ops = {
 	.fault = udmabuf_vm_fault,
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+	.huge_fault = udmabuf_vm_huge_fault,
+#endif
 };
 
 static int mmap_udmabuf(struct dma_buf *buf, struct vm_area_struct *vma)
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH v3 2/3] udmabuf: map huge page backed ranges with PMDs

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] udmabuf: race between udmabuf_vm_huge_fault() and udmabuf_vm_fault() - [Medium] udmabuf: unclamped…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] udmabuf: race between udmabuf_vm_huge_fault() and udmabuf_vm_fault()
- [Medium] udmabuf: unclamped pre-fault range via pmd_addr_end() in udmabuf_vm_fault()
--

commit ebe4e072f46637cdd8bfd0a954132a421bec39c8
Author: Qiliang Yuan <[email protected]>

udmabuf: map huge page backed ranges with PMDs

This commit adds a ->huge_fault() handler to udmabuf to map PMD-aligned contiguous PFN ranges with PMDs and restricts PTE pre-faulting in udmabuf_vm_fault() to a single PMD-sized range.

Quoted 9 lines
drivers/dma-buf/udmabuf.c +1 -0
index 018937435356e..dd98d5a1b69fc 100644
@@ -44,12 +44,67 @@ struct udmabuf {
 	struct miscdevice *device;
 };
 
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP

[ ... ]

drivers/dma-buf/udmabuf.c struct udmabuf { · line 100

Quoted 12 lines
drivers/dma-buf/udmabuf.c +12 -0
+static vm_fault_t udmabuf_vm_huge_fault(struct vm_fault *vmf,
+					unsigned int order)
+{
+	unsigned long pfn;
+
+	if (order != PMD_ORDER ||
+	    !udmabuf_pmd_mappable(vmf->vma, vmf->address & PMD_MASK, &pfn))
+		return VM_FAULT_FALLBACK;
+
+	return vmf_insert_pfn_pmd(vmf, pfn, vmf->flags & FAULT_FLAG_WRITE);
+}
+#endif

[Severity: High]
Can udmabuf_vm_huge_fault() and udmabuf_vm_fault() race on the same PMD entry when the prerequisite "mm: fix races between huge and non-huge faults in PFN mappings" series is not present in the tree?

Neither fault handler takes a driver lock, and under CONFIG_PER_VMA_LOCK both run under the per-VMA read lock while prctl(PR_SET_THP_DISABLE) sets MMF_DISABLE_THP_COMPLETELY without taking per-VMA write locks:

CPU0 CPU1
__handle_mm_fault()
create_huge_pmd()

    udmabuf_vm_huge_fault()
      udmabuf_pmd_mappable()
                                      prctl(PR_SET_THP_DISABLE, 1, ...)
                                      __handle_mm_fault()
                                        handle_pte_fault()
                                          udmabuf_vm_fault()
      vmf_insert_pfn_pmd()
        insert_pmd()
                                            vmf_insert_pfn()
                                              insert_pfn()
                                                get_locked_pte()
                                                  walk_to_pmd()
                                                    VM_BUG_ON(
                                                      pmd_trans_huge(*pmd))

When CONFIG_DEBUG_VM is disabled, get_locked_pte() returns NULL on the huge PMD and insert_pfn() returns a spurious VM_FAULT_OOM.

If udmabuf_vm_fault() installs a PTE page table first instead, insert_pmd() sees !pmd_none(*pmd) without checking pmd_trans_huge(*pmd); on a write fault it compares pmd_pfn(*pmd) against pfn, hits WARN_ON_ONCE(!is_huge_zero_pmd(*pmd)), and returns VM_FAULT_NOPAGE instead of VM_FAULT_FALLBACK.

Quoted 14 lines

static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf) {

drivers/dma-buf/udmabuf.c +1 -1
 	struct vm_area_struct *vma = vmf->vma;
 	struct udmabuf *ubuf = vma->vm_private_data;
 	pgoff_t pgoff = vmf->pgoff;
-	unsigned long addr, pfn;
+	unsigned long addr, end, pfn;
 	vm_fault_t ret;
 
 	if (pgoff >= ubuf->pagecount)
@@ -61,11 +116,16 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 	if (ret & VM_FAULT_ERROR)
 		return ret;
 

drivers/dma-buf/udmabuf.c static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf) · line 125

Quoted 10 lines
drivers/dma-buf/udmabuf.c +7 -3
-	/* pre fault */
-	pgoff = vma->vm_pgoff;
-	addr = vma->vm_start;
+	/*
+	 * Pre-fault the rest of the PMD-sized range of the fault. Staying
+	 * within its page table keeps the walk off the ranges that
+	 * udmabuf_vm_huge_fault() maps with a PMD.
+	 */
+	addr = max(vma->vm_start, vmf->address & PMD_MASK);
+	end = pmd_addr_end(vmf->address, vma->vm_end);

[Severity: Medium]
Does pmd_addr_end(vmf->address, vma->vm_end) fail to clamp end to a single page table on architectures with folded PMDs?

When include/asm-generic/pgtable-nopmd.h is used, pmd_addr_end(addr, end) is defined as (end) because it assumes end was already clamped by pgd_addr_end() -> p4d_addr_end() -> pud_addr_end(), while PMD_MASK and PMD_SIZE match PGDIR_MASK and PGDIR_SIZE. As a result, addr is clamped with PMD_MASK, but end stays at vma->vm_end and the loop pre-faults across all remaining page tables to the end of the VMA.

Calculating the upper bound explicitly from (vmf->address & PMD_MASK) + PMD_SIZE (as folio_pte_range() does in mm/memory.c) would clamp the range on folded-PMD kernels as well.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#4 lore raw

Re: [PATCH v3 2/3] udmabuf: map huge page backed ranges with PMDs

Quoted 4 lines · On Tue, 01 Dec 2026 17:34:31 +0000, [email protected] wrote:

[Severity: High]
Can udmabuf_vm_huge_fault() and udmabuf_vm_fault() race on the same PMD entry when the prerequisite "mm: fix races between huge and non-huge faults in PFN mappings" series is not present in the tree?

[...]

Only without that series, as the commit message says: the patch depends on it, and it fixes exactly these three cases in walk_to_pmd(), insert_pfn() and insert_pmd(). It is in mm-core (core-7.5.misc) and linux-next.

Quoted 3 lines

[Severity: Medium]
Does pmd_addr_end(vmf->address, vma->vm_end) fail to clamp end to a single page table on architectures with folded PMDs?

[...]

Quoted 3 lines

Calculating the upper bound explicitly from (vmf->address & PMD_MASK) + PMD_SIZE (as folio_pte_range() does in mm/memory.c) would clamp the range on folded-PMD kernels as well.

Right, with a folded PMD pmd_addr_end() returns vma->vm_end and the pre-fault runs to the end of the VMA, as before this patch. Nothing maps a PMD there, so it is not a correctness issue, but the range is not limited as the commit message says. I'll compute the bound from (vmf->address & PMD_MASK) + PMD_SIZE in v4.

Thanks,
Qiliang

#5 lore raw

Re: [PATCH v3 2/3] udmabuf: map huge page backed ranges with PMDs

In reply to Qiliang Yuan
Quoted 53 lines · Qiliang Yuan

QEMU and crosvm hand guest memory to the host renderer and display as udmabufs for virtio-gpu blob resources. The guest memory is a memfd that is often backed by 2 MiB huge pages, and the host process mmap()s the dma-buf to access it with the CPU.

udmabuf maps every page with its own PTE: the first fault inserts a PFN for each 4 KiB page of the whole VMA. Mapping and touching 4 GiB this way takes over 200 ms and a million PTEs, although the memory behind it is 2048 huge pages.

Add a ->huge_fault() handler that maps a PMD-sized range with one PMD when it is backed by an aligned run of contiguous PFNs, and falls back to PTEs otherwise. Limit the pre-mapping on a fault to the PMD-sized range of the fault, so that it stays within one page table and never covers a range that is mapped with a PMD. Buffers backed by 4 KiB pages now take a fault for each PMD-sized range rather than one for the whole VMA, about 1.5 us each, or under 1 ms per GiB. The THP settings in sysfs don't apply to VM_PFNMAP mappings, so only MADV_NOHUGEPAGE and PR_SET_THP_DISABLE stop the PMD mappings.

This depends on the series "mm: fix races between huge and non-huge faults in PFN mappings", which keeps a PTE fault that races with a PMD fault on the same range, after THP was disabled, from hitting a VM_BUG_ON or failing with VM_FAULT_OOM.

Mapping a udmabuf over a memfd filled with data and reading a byte of each 4 KiB page through the mapping, base and patched kernels alternating over 6 rounds of 5 runs (7 runs for shmem 4K), median of the per-round medians and range in parentheses; nothp marks a task with PR_SET_THP_DISABLE set:

backing size before (ms) after (ms) change

  hugetlb         256M    12.7 (12.6-13.9)      0.9 (0.9-0.9)     -93%
  hugetlb           1G    50.5 (50.5-50.9)      3.7 (3.6-3.7)     -93%
  hugetlb           4G       201 (201-202)   13.8 (13.5-13.9)     -93%
  hugetlb           8G       402 (402-403)   26.8 (26.3-27.0)     -93%
  shmem THP         1G    50.6 (50.6-50.8)      3.7 (3.6-3.7)     -93%
  shmem THP         4G       201 (199-203)   13.7 (13.3-13.8)     -93%
  shmem 4K          1G    50.5 (50.0-50.6)   51.4 (51.2-52.1)      +2%
  shmem 4K nothp    1G    50.5 (50.2-50.7)   51.4 (51.1-51.5)      +2%
  shmem 4K          4G       202 (201-202)      204 (204-205)      +1%
---
 drivers/dma-buf/udmabuf.c | 73 +++++++++++++++++++++++++++++++++++++++++++----
 1 file changed, 68 insertions(+), 5 deletions(-)
drivers/dma-buf/udmabuf.c +0 -0
index 018937435356e..dd98d5a1b69fc 100644

drivers/dma-buf/udmabuf.c struct udmabuf { · line 47

Quoted 4 lines
drivers/dma-buf/udmabuf.c +1 -0
@@ -44,12 +44,67 @@ struct udmabuf {
        struct miscdevice *device;
 };
 
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP

I think you can switch both guards to CONFIG_ARCH_SUPPORTS_PMD_PFNMAP and drop the if (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP)) below. (That's also what the DRM helper does in drm_gem_shmem_helper.c.)

Quoted 10 lines
drivers/dma-buf/udmabuf.c +10 -0
+/*
+ * Return whether the PMD-sized range of @vma at @addr is backed by one aligned
+ * run of contiguous PFNs, which can then be mapped with a single PMD.
+ */
+static bool udmabuf_pmd_mappable(struct vm_area_struct *vma, unsigned long addr,
+                                unsigned long *pfn)
+{
+       struct udmabuf *ubuf = vma->vm_private_data;
+       const pgoff_t nr = PMD_SIZE >> PAGE_SHIFT;
+       unsigned long first;

drivers/dma-buf/udmabuf.c struct udmabuf { · line 67

Quoted 10 lines
drivers/dma-buf/udmabuf.c +10 -0
+       pgoff_t pgoff, i;
+
+       if (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP))
+               return false;
+
+       if (!IS_ALIGNED(addr, PMD_SIZE) || addr < vma->vm_start ||
+           vma->vm_end - addr < PMD_SIZE)
+               return false;
+
+       pgoff = vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT);

You can use linear_page_index(vma, addr) here and below in udmabuf_vm_fault().

Quoted 49 lines
drivers/dma-buf/udmabuf.c +35 -2
+       if (pgoff >= ubuf->pagecount || ubuf->pagecount - pgoff < nr)
+               return false;
+
+       first = page_to_pfn(ubuf->pages[pgoff]);
+       if (!IS_ALIGNED(first, nr))
+               return false;
+
+       for (i = 1; i < nr; i++) {
+               if (page_to_pfn(ubuf->pages[pgoff + i]) != first + i)
+                       return false;
+       }
+
+       *pfn = first;
+       return true;
+}
+
+/*
+ * The THP settings in /sys/kernel/mm/transparent_hugepage/ don't apply to
+ * VM_PFNMAP mappings, so this is called even when THP is set to "never".
+ * Only MADV_NOHUGEPAGE or PR_SET_THP_DISABLE keep it from being called.
+ */
+static vm_fault_t udmabuf_vm_huge_fault(struct vm_fault *vmf,
+                                       unsigned int order)
+{
+       unsigned long pfn;
+
+       if (order != PMD_ORDER ||
+           !udmabuf_pmd_mappable(vmf->vma, vmf->address & PMD_MASK, &pfn))
+               return VM_FAULT_FALLBACK;
+
+       return vmf_insert_pfn_pmd(vmf, pfn, vmf->flags & FAULT_FLAG_WRITE);
+}
+#endif
+
 static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 {
        struct vm_area_struct *vma = vmf->vma;
        struct udmabuf *ubuf = vma->vm_private_data;
        pgoff_t pgoff = vmf->pgoff;
-       unsigned long addr, pfn;
+       unsigned long addr, end, pfn;
        vm_fault_t ret;
 
        if (pgoff >= ubuf->pagecount)
@@ -61,11 +116,16 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
        if (ret & VM_FAULT_ERROR)
                return ret;
 
-       /* pre fault */

drivers/dma-buf/udmabuf.c static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf) · line 126

Quoted 10 lines
drivers/dma-buf/udmabuf.c +8 -2
-       pgoff = vma->vm_pgoff;
-       addr = vma->vm_start;
+       /*
+        * Pre-fault the rest of the PMD-sized range of the fault. Staying
+        * within its page table keeps the walk off the ranges that
+        * udmabuf_vm_huge_fault() maps with a PMD.
+        */
+       addr = max(vma->vm_start, vmf->address & PMD_MASK);
+       end = pmd_addr_end(vmf->address, vma->vm_end);
+       pgoff = vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT);

I saw your reply to sashiko. Kind of too bad we can't use pte_table_clamped_end(vmf->address, vma->vm_end) (commit 169169e26ab4) here yet since drm-misc-next is based on 7.4-rc2 and doesn't have it yet. I guess we have to wait on Lorenzo's series anyway.

Quoted 19 lines
drivers/dma-buf/udmabuf.c +4 -2
-       for (; addr < vma->vm_end; pgoff++, addr += PAGE_SIZE) {
+       for (; addr < end; pgoff++, addr += PAGE_SIZE) {
                if (addr == vmf->address)
                        continue;
 
@@ -89,6 +149,9 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 
 static const struct vm_operations_struct udmabuf_vm_ops = {
        .fault = udmabuf_vm_fault,
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+       .huge_fault = udmabuf_vm_huge_fault,
+#endif
 };
 
 static int mmap_udmabuf(struct dma_buf *buf, struct vm_area_struct *vma)
 
--

2.43.0

#6 lore raw

PATCH v3 3/3 selftests/udmabuf: test mapping a huge page backed udmabuf

In reply to Qiliang Yuan

udmabuf maps the ranges of a buffer that are backed by huge pages with PMDs, provided the mapping covers whole PMDs at an aligned address.

The existing tests of huge page backed buffers only map a few pages, so they never get a PMD mapping or check what is read through one.

Map a udmabuf of 8 huge pages, sized from hpage_pmd_size and the hugetlb page size so that it also fits 16 KiB and 64 KiB base pages, and read back what was written to the memfd, with a different pattern in each huge page: through a mapping of the whole buffer, which must be PMD aligned for a 64-bit task when THP support is built in, through a mapping at an unaligned offset, from a forked child that inherits the mapping of the whole buffer, through a buffer that starts one page into the memfd so that only PTEs can map it, and next to a mapped PMD after THP was disabled for the mapping with MADV_NOHUGEPAGE.

---
 tools/testing/selftests/drivers/dma-buf/udmabuf.c | 171 +++++++++++++++++++++-
 1 file changed, 170 insertions(+), 1 deletion(-)
tools/testing/selftests/drivers/dma-buf/udmabuf.c +170 -1
index d78aec662586b..1f4b7dd1f610e 100644
@@ -14,6 +14,7 @@
 #include <sys/ioctl.h>
 #include <sys/syscall.h>
 #include <sys/mman.h>
+#include <sys/wait.h>
 #include <linux/memfd.h>
 #include <linux/udmabuf.h>
 #include "kselftest.h"
@@ -130,6 +131,172 @@ static int compare_chunks(void *addr1, void *addr2, off64_t memfd_size)
 	return ret;
 }
 
+/* Read a size in bytes from @path, or from the "@key: <n> kB" line of @path */
+static size_t read_size(const char *path, const char *key)
+{
+	unsigned long val = 0;
+	size_t len = key ? strlen(key) : 0;
+	char line[128];
+	FILE *f;
+
+	f = fopen(path, "r");
+	if (!f)
+		return 0;
+	while (fgets(line, sizeof(line), f)) {
+		if (!key) {
+			val = strtoul(line, NULL, 10);
+			break;
+		}
+		if (!strncmp(line, key, len) && line[len] == ':') {
+			val = strtoul(line + len + 1, NULL, 10) << 10;
+			break;
+		}
+	}
+	fclose(f);
+	return val;
+}
+
+/* Fill each page of @mem with a byte that differs between huge pages */
+static void fill_huge(char *mem, size_t len, size_t hpage)
+{
+	size_t i;
+
+	for (i = 0; i < len; i += getpagesize())
+		mem[i] = (char)(i / getpagesize() + i / hpage);
+}
+
+/* Check that @len bytes mapped at @addr match @mem at @off */
+static bool check_huge_mapping(char *addr, char *mem, off_t off, size_t len)
+{
+	size_t i;
+
+	for (i = 0; i < len; i += getpagesize()) {
+		if (addr[i] != mem[off + i])
+			return false;
+	}
+	return true;
+}
+
+/* Check that @len bytes of @buf at @off read back what was written to @mem */
+static bool check_huge_range(int buf, char *mem, off_t off, size_t len)
+{
+	char *addr;
+	bool ok;
+
+	addr = mmap(NULL, len, PROT_READ, MAP_SHARED, buf, off);
+	if (addr == MAP_FAILED)
+		return false;
+
+	ok = check_huge_mapping(addr, mem, off, len);
+	munmap(addr, len);
+	return ok;
+}
+
+static void report(bool ok, int test)
+{
+	if (ok)
+		ksft_test_result_pass("%s: [PASS,test-%d]\n", TEST_PREFIX, test);
+	else
+		ksft_test_result_fail("%s: [FAIL,test-%d]\n", TEST_PREFIX, test);
+}
+
+/*
+ * Map a udmabuf backed by huge pages, which can be mapped with PMDs, and read
+ * it back: from a PMD-aligned address, a sub-range at an unaligned offset, a
+ * forked child that inherits the mapping, a buffer that starts one page into
+ * the memfd so that no PMD can map it, and a mapping that has THP disabled
+ * after a PMD was mapped.
+ */
+static void test_huge_mapping(int devfd)
+{
+	size_t pmd = read_size("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size",
+			       NULL);
+	size_t hpage = read_size("/proc/meminfo", "Hugepagesize");
+	struct udmabuf_create create = {};
+	int memfd, buf, sub, status, test;
+	size_t unit, size;
+	char *mem, *addr;
+	pid_t pid;
+	bool ok;
+
+	if (!hpage) {
+		for (test = 8; test <= 11; test++)
+			ksft_test_result_skip("%s: [SKIP,test-%d]\n",
+					      TEST_PREFIX, test);
+		return;
+	}
+	unit = hpage > pmd ? hpage : pmd;
+	size = 8 * unit;
+
+	memfd = create_memfd_with_seals(size, true);
+	mem = mmap_fd(memfd, size);
+	fill_huge(mem, size, hpage);
+
+	create.memfd = memfd;
+	create.size = size;
+	buf = ioctl(devfd, UDMABUF_CREATE, &create);
+	if (buf < 0) {
+		for (test = 8; test <= 11; test++)
+			ksft_test_result_fail("%s: [FAIL,test-%d]\n",
+					      TEST_PREFIX, test);
+		goto out;
+	}
+
+	/* The address is only aligned for 64-bit tasks with THP support */
+	addr = mmap(NULL, size, PROT_READ, MAP_SHARED, buf, 0);
+	ok = addr != MAP_FAILED &&
+	     (sizeof(long) != 8 || !pmd || !((unsigned long)addr % pmd)) &&
+	     check_huge_mapping(addr, mem, 0, size);
+	report(ok, 8);
+
+	ok = check_huge_range(buf, mem, unit + getpagesize(),
+			      5 * unit + 3 * getpagesize());
+	pid = addr == MAP_FAILED ? -1 : fork();
+	if (!pid)
+		_exit(check_huge_mapping(addr, mem, 0, size) ? 0 : 1);
+	if (pid < 0 || waitpid(pid, &status, 0) != pid ||
+	    !WIFEXITED(status) || WEXITSTATUS(status))
+		ok = false;
+	if (addr != MAP_FAILED)
+		munmap(addr, size);
+	report(ok, 9);
+
+	/* Only PTEs can map a buffer that starts one page into a huge page */
+	create.offset = getpagesize();
+	create.size = 4 * unit;
+	sub = ioctl(devfd, UDMABUF_CREATE, &create);
+	ok = sub >= 0;
+	if (ok) {
+		addr = mmap(NULL, create.size, PROT_READ, MAP_SHARED, sub, 0);
+		ok = addr != MAP_FAILED &&
+		     check_huge_mapping(addr, mem, create.offset, create.size);
+		if (addr != MAP_FAILED)
+			munmap(addr, create.size);
+		close(sub);
+	}
+	report(ok, 10);
+
+	/* Map a PMD, disable THP for the mapping, then fault next to the PMD */
+	addr = mmap(NULL, size, PROT_READ, MAP_SHARED, buf, 0);
+	ok = addr != MAP_FAILED && addr[0] == mem[0];
+	if (ok && madvise(addr, size, MADV_NOHUGEPAGE)) {
+		munmap(addr, size);
+		ksft_test_result_skip("%s: [SKIP,test-11]\n", TEST_PREFIX);
+	} else {
+		ok = ok && check_huge_mapping(addr + 3 * unit, mem, 3 * unit,
+					      unit) &&
+		     check_huge_mapping(addr, mem, 0, size);
+		if (addr != MAP_FAILED)
+			munmap(addr, size);
+		report(ok, 11);
+	}
+
+	close(buf);
+out:
+	munmap(mem, size);
+	close(memfd);
+}
+
 int main(int argc, char *argv[])
 {
 	struct udmabuf_create create;
@@ -138,7 +305,7 @@ int main(int argc, char *argv[])
 	void *addr1, *addr2;
 
 	ksft_print_header();
-	ksft_set_plan(7);
+	ksft_set_plan(11);
 
 	devfd = open("/dev/udmabuf", O_RDWR);
 	if (devfd < 0) {
@@ -268,6 +435,8 @@ int main(int argc, char *argv[])
 
 	close(buf);
 	close(memfd);
+
+	test_huge_mapping(devfd);
 	close(devfd);
 
 	ksft_print_msg("%s: ok\n", TEST_PREFIX);
Signature · 1 line
2.43.0
Reviewed-by on v3 3/3
#7 lore raw

Re: [PATCH v3 3/3] selftests/udmabuf: test mapping a huge page backed udmabuf

Quoted 17 lines · Qiliang Yuan

udmabuf maps the ranges of a buffer that are backed by huge pages with PMDs, provided the mapping covers whole PMDs at an aligned address.

The existing tests of huge page backed buffers only map a few pages, so they never get a PMD mapping or check what is read through one.

Map a udmabuf of 8 huge pages, sized from hpage_pmd_size and the hugetlb page size so that it also fits 16 KiB and 64 KiB base pages, and read back what was written to the memfd, with a different pattern in each huge page: through a mapping of the whole buffer, which must be PMD aligned for a 64-bit task when THP support is built in, through a mapping at an unaligned offset, from a forked child that inherits the mapping of the whole buffer, through a buffer that starts one page into the memfd so that only PTEs can map it, and next to a mapped PMD after THP was disabled for the mapping with MADV_NOHUGEPAGE.

Quoted 1 line