Skip to contentSkip to conversation

vfio/pci: Provide kernel-side BAR alignment for huge page mapping

PATCH Superseded Guanghui Feng 4 participants 12 messages Nov 24

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

cover vfio/pci: Provide kernel-side BAR alignment for huge page mapping

VFIO PCI BAR regions support PMD/PUD huge page mapping via vfio_pci_mmap_huge_fault() since commit f9e54c3a2f5b ("vfio/pci:
implement huge_fault support"). The huge_fault path requires both the VA and the PFN to be aligned to the huge page boundary, checked by is_aligned_for_order(). When alignment fails, huge_fault silently returns VM_FAULT_FALLBACK and the mapping degrades to 4KB pages.

QEMU already handles this by pre-allocating an aligned VA region and using MAP_FIXED, see QEMU commits 00b519c0bc ("vfio/helpers: Align mmaps") and 3863e47828 ("hw/vfio: align mmap to power-of-2 of region size for hugepfnmap"). Other userspace consumers (DPDK, custom VMMs, test tools, and QEMU releases predating that change) typically call mmap(fd, offset) with addr=0, relying on the kernel to select a suitable VA. Without kernel-side alignment guidance, these consumers silently get 4KB mappings for large BARs.

This series adds a .get_unmapped_area callback to the VFIO device file_operations, modelled after drivers/dax/device.c, that provides PMD/PUD-aligned VA selection for BAR mappings. It also sets VM_HUGEPAGE on BAR VMAs, which keeps the huge mapping available to a process that called prctl(PR_SET_THP_DISABLE, PR_THP_DISABLE_EXCEPT_ADVISED).

Note: CONFIG_TRANSPARENT_HUGEPAGE=y is required at compile time for the huge pfnmap infrastructure. The runtime THP sysfs policy (enabled=never) does NOT block VFIO BAR huge pages -- vma_file_bypass_thp_tuneables() already bypasses it for PFNMAP VMAs with a .huge_fault handler (commit e384abeb559d).

Performance impact for a 256MB BAR, 4KB pages vs PMD huge pages:
- Page faults: 65536 -> 128 (512x reduction)
- Page table memory: ~516KB -> ~4KB (129x reduction)
- TLB pressure: 65536 entries (exceeds STLB) -> 128 entries (fits)

Patch 1 adds the vfio_device_ops callback infrastructure. Patch 2 implements the PCI BAR alignment logic and VM_HUGEPAGE.

Compiled with W=1, checkpatch --strict clean (0 errors, 0 warnings). Each patch compiles independently (bisect-safe).

Guanghui Feng (2):
vfio: Add get_unmapped_area callback to vfio_device_ops vfio/pci: Align BAR mappings for huge page support

 drivers/vfio/pci/vfio_pci.c      |  3 +
 drivers/vfio/pci/vfio_pci_core.c | 95 ++++++++++++++++++++++++++++++++
 drivers/vfio/vfio_main.c         | 34 ++++++++++++
 include/linux/vfio.h             | 12 ++++
 include/linux/vfio_pci_core.h    |  8 +++
 5 files changed, 152 insertions(+)
Signature · 1 line
2.43.7
#1 lore raw

PATCH 1/2 vfio: Add get_unmapped_area callback to vfio_device_ops

vfio exposes device regions through the device file descriptor and a bus driver backs a region with pfnmaps over the device MMIO space when the user calls mmap(2) on it. Unless the user asks for a specific address, the virtual address of the resulting VMA is picked by the generic address selection in mm_get_unmapped_area(), which only guarantees PAGE_SIZE alignment.

That is enough for the base mapping, but it keeps a driver from ever backing a region with huge pfnmaps. huge_fault() only installs a PMD or PUD sized pfnmap when both the fault address and the pfn are aligned to that page size, see is_aligned_for_order(). A driver can only influence the first of those, and it cannot do so from its mmap() callback because the address has already been fixed up by then.

Add a get_unmapped_area() callback to vfio_device_ops along with a dispatcher in vfio_device_fops, so a bus driver can ask for an address that is aligned to the largest page size its region can be mapped with before the VMA is created. Drivers that do not provide the callback, and configurations without huge pfnmap support, fall back to mm_get_unmapped_area() and keep the existing behaviour.

The hook is only consulted when the kernel has to choose the address:
a MAP_FIXED mapping never reaches it, and an explicit address hint is passed through to the driver, which is expected to honour it. The callback therefore serves the userspace consumers that call mmap(fd, offset) with addr=0 and rely on the kernel to pick a suitable address for them, rather than trying to second guess userspace that already arranges the alignment itself.

This mirrors what drivers/dax/device.c does with dax_get_unmapped_area(), which has to satisfy the same alignment requirement for its PMD sized pfnmaps.

---
 drivers/vfio/vfio_main.c | 34 ++++++++++++++++++++++++++++++++++
 include/linux/vfio.h     | 12 ++++++++++++
 2 files changed, 46 insertions(+)
drivers/vfio/vfio_main.c +34 -0
index 4e5d738ccf4b..edf9eb4cd477 100644
@@ -28,6 +28,7 @@
 #include <linux/pseudo_fs.h>
 #include <linux/rwsem.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/seq_file.h>
 #include <linux/slab.h>
 #include <linux/stat.h>
@@ -1431,6 +1432,36 @@ static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
 	return device->ops->mmap(device, vma);
 }
 
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+/*
+ * Give the bus driver a chance to request a virtual address that allows the
+ * mapping to be backed by huge pages, fex. a PCI BAR mapping that could be
+ * faulted in with PMD or PUD sized pfnmaps.  Anything the driver cannot
+ * handle, including devices without huge mapping support, falls back to the
+ * generic address selection, which is also what happens without this
+ * callback.
+ */
+static unsigned long vfio_device_fops_get_unmapped_area(struct file *filep,
+							unsigned long addr,
+							unsigned long len,
+							unsigned long pgoff,
+							unsigned long flags)
+{
+	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device *device = df->device;
+
+	/* Paired with smp_store_release() following vfio_df_open() */
+	if (!smp_load_acquire(&df->access_granted))
+		goto out;
+
+	if (device->ops->get_unmapped_area)
+		return device->ops->get_unmapped_area(device, filep, addr, len,
+						      pgoff, flags);
+out:
+	return mm_get_unmapped_area(filep, addr, len, pgoff, flags);
+}
+#endif
+
 #ifdef CONFIG_PROC_FS
 static void vfio_device_show_fdinfo(struct seq_file *m, struct file *filep)
 {
@@ -1456,6 +1487,9 @@ const struct file_operations vfio_device_fops = {
 	.unlocked_ioctl	= vfio_device_fops_unl_ioctl,
 	.compat_ioctl	= compat_ptr_ioctl,
 	.mmap		= vfio_device_fops_mmap,
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+	.get_unmapped_area = vfio_device_fops_get_unmapped_area,
+#endif
 #ifdef CONFIG_PROC_FS
 	.show_fdinfo	= vfio_device_show_fdinfo,
 #endif
include/linux/vfio.h +12 -0
index 0cc91c6f96d2..68a84a1fd3fd 100644
@@ -102,6 +102,12 @@ struct vfio_device {
  * @ioctl: Perform ioctl(2) on device file descriptor, supporting VFIO_DEVICE_*
  *         operations documented below
  * @mmap: Perform mmap(2) on a region of the device file descriptor
+ * @get_unmapped_area: Optional, suggest a virtual address for mmap(2) of a
+ *         device region such that the mapping can be backed by huge pages,
+ *         ie. the address is aligned to the largest page size the region can
+ *         be mapped with.  Drivers that don't support huge mappings, and
+ *         configurations without huge pfnmap support, leave this unset and
+ *         the generic address selection is used.
  * @request: Request for the bus driver to release the device
  * @match: Optional device name match callback (return: 0 for no-match, >0 for
  *         match, -errno for abort (ex. match with insufficient or incorrect
@@ -143,6 +149,12 @@ struct vfio_device_ops {
 	void	(*dma_unmap)(struct vfio_device *vdev, u64 iova, u64 length);
 	int	(*device_feature)(struct vfio_device *device, u32 flags,
 				  void __user *arg, size_t argsz);
+	unsigned long (*get_unmapped_area)(struct vfio_device *vdev,
+					   struct file *filp,
+					   unsigned long addr,
+					   unsigned long len,
+					   unsigned long pgoff,
+					   unsigned long flags);
 };
 
 #if IS_ENABLED(CONFIG_IOMMUFD)
Signature · 1 line
2.43.7
#2 lore raw

Re: [PATCH 1/2] vfio: Add get_unmapped_area callback to vfio_device_ops

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] vfio: MAP_FIXED mappings reach device->ops->get_unmapped_area() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] vfio: MAP_FIXED mappings reach device->ops->get_unmapped_area()
--

commit c2dec2a94cdf65407cd97caccc3240752b010cec
Author: Guanghui Feng <[email protected]>

vfio: Add get_unmapped_area callback to vfio_device_ops

This commit adds an optional get_unmapped_area callback to vfio_device_ops and dispatches to it from vfio_device_fops so bus drivers can align VMA virtual addresses for huge pfnmaps.

Quoted 4 lines
drivers/vfio/vfio_main.c +0 -0
index 4e5d738ccf4be..edf9eb4cd4778 100644

[ ... ]

Quoted 23 lines
drivers/vfio/vfio_main.c +19 -0
@@ -1431,6 +1432,36 @@ static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
 	return device->ops->mmap(device, vma);
 }
 
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+/*
+ * Give the bus driver a chance to request a virtual address that allows the
+ * mapping to be backed by huge pages, fex. a PCI BAR mapping that could be
+ * faulted in with PMD or PUD sized pfnmaps.  Anything the driver cannot
+ * handle, including devices without huge mapping support, falls back to the
+ * generic address selection, which is also what happens without this
+ * callback.
+ */
+static unsigned long vfio_device_fops_get_unmapped_area(struct file *filep,
+							unsigned long addr,
+							unsigned long len,
+							unsigned long pgoff,
+							unsigned long flags)
+{
+	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device *device = df->device;
+
+	/* Paired with smp_store_release() following vfio_df_open() */

drivers/vfio/vfio_main.c static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma) · line 1463

Quoted 10 lines
drivers/vfio/vfio_main.c +10 -0
+	if (!smp_load_acquire(&df->access_granted))
+		goto out;
+
+	if (device->ops->get_unmapped_area)
+		return device->ops->get_unmapped_area(device, filep, addr, len,
+						      pgoff, flags);
+out:
+	return mm_get_unmapped_area(filep, addr, len, pgoff, flags);
+}
+#endif

[Severity: Medium]
Should vfio_device_fops_get_unmapped_area() bail out to out when flags & MAP_FIXED is set?

The commit message states that a MAP_FIXED mapping never reaches the hook, however do_mmap() and __get_unmapped_area() invoke file->f_op->get_unmapped_area() unconditionally even when MAP_FIXED or MAP_FIXED_NOREPLACE is set (the MAP_FIXED check only happens inside generic_get_unmapped_area() / generic_get_unmapped_area_topdown() via mm_get_unmapped_area()). If a bus driver implements get_unmapped_area() by only checking whether addr is non-zero (like dax_get_unmapped_area()), a MAP_FIXED request at addr == 0 with an unaligned file offset can have its fixed address shifted to a non-zero aligned offset, violating MAP_FIXED semantics and overwriting mappings at the shifted address.

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

PATCH 2/2 vfio/pci: Align BAR mappings for huge page support

In reply to Guanghui Feng

vfio_pci_mmap_huge_fault() is already wired up as the huge_fault handler for BAR mappings and can install PMD or PUD sized pfnmaps when CONFIG_TRANSPARENT_HUGEPAGE is enabled. Whether it ever gets to do so depends on the address the BAR VMA ended up at: is_aligned_for_order() requires both the fault address and the pfn to be aligned to the huge page size, and the generic mm_get_unmapped_area() only guarantees PAGE_SIZE alignment. When the address is unaligned the check fails, huge_fault() returns VM_FAULT_FALLBACK without having inserted anything, and the region silently degrades to one PAGE_SIZE fault per page.

A PCI BAR is required by the PCI bus specification to occupy a naturally aligned, power of two sized region of physical address space, so the pfn side of the check is already satisfied for any BAR that is at least 2MB in size. What is missing is the virtual address side, and that is only fixable before the VMA is created.

QEMU already works around this in userspace: it reserves an oversized anonymous region, rounds its address up to an alignment of MIN(pow2ceil(region->size), 1GiB), unmaps the slack at both ends and remaps every sparse subregion with MAP_FIXED at the aligned address, see QEMU commits 00b519c0bc ("vfio/helpers: Align mmaps") and 3863e47828 ("hw/vfio: align mmap to power-of-2 of region size for hugepfnmap"). Other consumers do not. DPDK, custom VMMs, test tools and QEMU releases predating that change typically call mmap(fd, offset) with addr=0 and leave the address selection to the kernel, so they are the ones that silently lose the huge mapping on a large BAR. Providing the alignment in the kernel is defence in depth as well: the kernel should not quietly give up on a huge mapping it is able to provide just because today's userspace happens to compensate for its absence.

Implement vfio_pci_core_get_unmapped_area() on top of the new vfio_device_ops callback, modelled after dax_get_unmapped_area() in drivers/dax/device.c. It derives the largest usable page size from the BAR length, capped at PUD_SIZE and at PMD_SIZE when the architecture lacks CONFIG_ARCH_SUPPORTS_PUD_PFNMAP, asks for an area with enough slack to shift the mapping up to the next aligned address, and applies that shift. Shifting the address preserves the offset of the mapping within the BAR, so aligning the address also aligns the pfn.

Everything this cannot improve keeps the current behaviour. A non-zero address returns early, which makes the change transparent for userspace such as QEMU that aligns the mapping itself: MAP_FIXED never reaches the hook at all, and an explicit hint without MAP_FIXED is honoured as is. Regions that are not mmap'able BARs, BARs smaller than PMD_SIZE, and mappings too short to span one fully aligned huge page all take the same fallback path.

Also set VM_HUGEPAGE on the BAR VMA. The THP sysfs policy does not need it, since huge pfnmaps are uncompactable and so vma_file_bypass_thp_tuneables() ignores the tuneables for a PFNMAP VMA that has a huge_fault handler.
thp_vma_allowable_order() is still consulted before create_huge_pmd() and create_huge_pud() are reached, though, and it calls vma_thp_disabled(), which reports the VMA as disabled once the process has called prctl(PR_SET_THP_DISABLE, PR_THP_DISABLE_EXCEPT_ADVISED) unless VM_HUGEPAGE is set. Marking the VMA keeps the huge mapping available for such a process instead of leaving it at the mercy of that single bypass, and makes the intent explicit regardless of how the process or the administrator configured THP.

---
 drivers/vfio/pci/vfio_pci.c      |  3 +
 drivers/vfio/pci/vfio_pci_core.c | 95 ++++++++++++++++++++++++++++++++
 include/linux/vfio_pci_core.h    |  8 +++
 3 files changed, 106 insertions(+)
drivers/vfio/pci/vfio_pci.c +3 -0
index e7c012febe91..2757ff9075d2 100644
@@ -158,6 +158,9 @@ static const struct vfio_device_ops vfio_pci_ops = {
 	.read		= vfio_pci_core_read,
 	.write		= vfio_pci_core_write,
 	.mmap		= vfio_pci_core_mmap,
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+	.get_unmapped_area = vfio_pci_core_get_unmapped_area,
+#endif
 	.request	= vfio_pci_core_request,
 	.match		= vfio_pci_core_match,
 	.match_token_uuid = vfio_pci_core_match_token_uuid,
drivers/vfio/pci/vfio_pci_core.c +95 -0

107 lines not on this page · raw message

include/linux/vfio_pci_core.h +8 -0
index 2f3fa2787737..98350c87d2ea 100644
@@ -187,6 +187,14 @@ vm_fault_t vfio_pci_vmf_insert_pfn(struct vfio_pci_core_device *vdev,
 				   struct vm_fault *vmf, unsigned long pfn,
 				   unsigned int order);
 int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma);
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+unsigned long vfio_pci_core_get_unmapped_area(struct vfio_device *core_vdev,
+					      struct file *filp,
+					      unsigned long addr,
+					      unsigned long len,
+					      unsigned long pgoff,
+					      unsigned long flags);
+#endif
 void vfio_pci_core_request(struct vfio_device *core_vdev, unsigned int count);
 int vfio_pci_core_match(struct vfio_device *core_vdev, char *buf);
 int vfio_pci_core_match_token_uuid(struct vfio_device *core_vdev,
Signature · 1 line
2.43.7
#4 lore raw

Re: [PATCH 2/2] vfio/pci: Align BAR mappings for huge page support

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] vfio/pci: wrong align and no PMD fallback in vfio_pci_core_get_unmapped_area() - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] vfio/pci: wrong align and no PMD fallback in vfio_pci_core_get_unmapped_area()
- [Medium] vfio/pci: missing MAP_FIXED check in vfio_pci_core_get_unmapped_area()
--

commit 22651b52e2b64249734636f112ebe4aa3bd8ca86
Author: Guanghui Feng <[email protected]>

vfio/pci: Align BAR mappings for huge page support

This commit implements vfio_pci_core_get_unmapped_area() to align BAR virtual addresses for PMD and PUD pfnmaps and sets VM_HUGEPAGE on BAR VMAs.

Quoted 5 lines
drivers/vfio/pci/vfio_pci_core.c +0 -0
index f2d5b6857925f..dd437f23b9384 100644
@@ -1878,12 +1878,107 @@ int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma

[ ... ]

Quoted 7 lines
drivers/vfio/pci/vfio_pci_core.c +7 -0
+unsigned long vfio_pci_core_get_unmapped_area(struct vfio_device *core_vdev,
+					      struct file *filp,
+					      unsigned long addr,
+					      unsigned long len,
+					      unsigned long pgoff,
+					      unsigned long flags)
+{

drivers/vfio/pci/vfio_pci_core.c int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma · line 1922

Quoted 10 lines
drivers/vfio/pci/vfio_pci_core.c +10 -0
+	struct vfio_pci_core_device *vdev =
+		container_of(core_vdev, struct vfio_pci_core_device, vdev);
+	struct pci_dev *pdev = vdev->pdev;
+	unsigned long align, off, off_end, off_align, len_align, addr_align;
+	unsigned int index;
+	u64 bar_len;
+
+	/* The user asked for a specific address, don't second guess it */
+	if (addr)
+		goto out;

[Severity: Medium]
Can this shift a fixed mapping at address 0 to a non-zero address when flags has MAP_FIXED or MAP_FIXED_NOREPLACE set?

do_mmap() and vrm_set_new_addr() still invoke __get_unmapped_area() when MAP_FIXED is set. With addr == 0 and MAP_FIXED, mm_get_unmapped_area() returns 0 immediately, and the shift below changes the returned address to off & (align - 1). When (off & (align - 1)) >= mmap_min_addr, do_mmap() with MAP_FIXED will then unmap and overwrite existing VMAs at [off & (align - 1), (off & (align - 1)) + len) instead of failing on address 0.

Checking if (addr || (flags & MAP_FIXED)) before aligning avoids mutating a fixed address.

Quoted 22 lines
drivers/vfio/pci/vfio_pci_core.c +22 -0
+
+	index = pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
+	if (index >= VFIO_PCI_ROM_REGION_INDEX || !vdev->bar_mmap_supported[index])
+		goto out;
+
+	bar_len = pci_resource_len(pdev, index);
+	if (!bar_len)
+		goto out;
+
+	/* The BAR size caps the page size we can map it with */
+	align = min_t(unsigned long, PUD_SIZE,
+		      rounddown_pow_of_two((unsigned long)bar_len));
+	if (align < PMD_SIZE)
+		goto out;
+	if (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_PUD_PFNMAP) && align > PMD_SIZE)
+		align = PMD_SIZE;
+
+	/* Only an alignment that fits within the mapping length is useful */
+	while (align > PMD_SIZE && len < align)
+		align >>= 1;
+	if (align < PMD_SIZE)
+		goto out;

drivers/vfio/pci/vfio_pci_core.c int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma · line 1954

Quoted 10 lines
drivers/vfio/pci/vfio_pci_core.c +10 -0
+
+	off = pgoff << PAGE_SHIFT;
+	off_end = off + len;
+	if (off_end < off)
+		goto out;
+	off_align = round_up(off, align);
+
+	/* The mapping has to span at least one fully aligned huge page */
+	if (off_end <= off_align || off_end - off_align < align)
+		goto out;

[Severity: Medium]
When CONFIG_ARCH_SUPPORTS_PUD_PFNMAP is enabled, doesn't this pick intermediate power-of-two alignments between PMD_SIZE and PUD_SIZE, and give up on PMD_SIZE alignment whenever the range does not span a full block at that larger alignment?

vfio_pci_vmf_insert_pfn() only installs huge mappings at PUD_ORDER and PMD_ORDER. For a BAR or mapping length between PMD_SIZE and PUD_SIZE (for example, a 16 MiB BAR with a 4 KiB MSI-X hole at the start and a 4 KiB PBA hole at the end), align becomes 8 MiB, off_align rounds up to 8 MiB, and off_end - off_align < align jumps to out with PAGE_SIZE alignment instead of aligning to PMD_SIZE. Even when off is 0, a BAR between 4 MiB and 512 MiB reserves up to 512 MiB of extra virtual address slack when only PMD_SIZE pages can be faulted in. Also, the second if (align < PMD_SIZE) check after the while loop cannot be reached because align >= PMD_SIZE before the loop and the loop stops at PMD_SIZE.

Trying PUD_SIZE only when CONFIG_ARCH_SUPPORTS_PUD_PFNMAP is enabled and the mapping spans a PUD_SIZE-aligned block, and falling back to PMD_SIZE otherwise, would handle both full and sparse BAR mappings.

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

v2 cover vfio/pci: Provide kernel-side BAR alignment for huge page mapping

In reply to Guanghui Feng

VFIO PCI BAR regions support PMD/PUD huge page mapping via vfio_pci_mmap_huge_fault() since commit f9e54c3a2f5b ("vfio/pci:
implement huge_fault support"). The huge_fault path requires both the VA and the PFN to be aligned to the huge page boundary, checked by is_aligned_for_order(). When alignment fails, huge_fault silently returns VM_FAULT_FALLBACK and the mapping degrades to 4KB pages.

QEMU already handles this by pre-allocating an aligned VA region and using MAP_FIXED, see QEMU commits 00b519c0bc ("vfio/helpers: Align mmaps") and 3863e47828 ("hw/vfio: align mmap to power-of-2 of region size for hugepfnmap"). Other userspace consumers (DPDK, custom VMMs, test tools, and QEMU releases predating that change) typically call mmap(fd, offset) with addr=0, relying on the kernel to select a suitable VA. Without kernel-side alignment guidance, these consumers silently get 4KB mappings for large BARs.

This series adds a .get_unmapped_area callback to the VFIO device file_operations, modelled after drivers/dax/device.c, that provides PMD/PUD-aligned VA selection for BAR mappings. It also sets VM_HUGEPAGE on BAR VMAs, which keeps the huge mapping available to a process that called prctl(PR_SET_THP_DISABLE, PR_THP_DISABLE_EXCEPT_ADVISED).

Note: CONFIG_TRANSPARENT_HUGEPAGE=y is required at compile time for the huge pfnmap infrastructure. The runtime THP sysfs policy (enabled=never) does NOT block VFIO BAR huge pages -- vma_file_bypass_thp_tuneables() already bypasses it for PFNMAP VMAs with a .huge_fault handler (commit e384abeb559d).

Performance impact for a 256MB BAR, 4KB pages vs PMD huge pages:
- Page faults: 65536 -> 128 (512x reduction)
- Page table memory: ~516KB -> ~4KB (129x reduction)
- TLB pressure: 65536 entries (exceeds STLB) -> 128 entries (fits)

Patch 1 adds the vfio_device_ops callback infrastructure. Patch 2 implements the PCI BAR alignment logic and VM_HUGEPAGE.

Compiled with W=1, checkpatch --strict clean (0 errors, 0 warnings). Each patch compiles independently (bisect-safe).

---
v2:
- Add MAP_FIXED/MAP_FIXED_NOREPLACE check to avoid interfering with fixed-address mappings (Sashiko AI review)
- Simplify align selection to only PMD_SIZE or PUD_SIZE, eliminating intermediate power-of-2 values that cannot be installed by vfio_pci_vmf_insert_pfn() and could cause alignment failure for sparse BAR regions (Sashiko AI review)
- Remove unreachable dead code (second align < PMD_SIZE check)

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

Guanghui Feng (2):
vfio: Add get_unmapped_area callback to vfio_device_ops vfio/pci: Align BAR mappings for huge page support

 drivers/vfio/pci/vfio_pci.c      |  3 +
 drivers/vfio/pci/vfio_pci_core.c | 95 ++++++++++++++++++++++++++++++++
 drivers/vfio/vfio_main.c         | 34 ++++++++++++
 include/linux/vfio.h             | 12 ++++
 include/linux/vfio_pci_core.h    |  8 +++
 5 files changed, 152 insertions(+)
Signature · 1 line
2.43.7
#6 lore raw

PATCH v2 1/2 vfio: Add get_unmapped_area callback to vfio_device_ops

vfio exposes device regions through the device file descriptor and a bus driver backs a region with pfnmaps over the device MMIO space when the user calls mmap(2) on it. Unless the user asks for a specific address, the virtual address of the resulting VMA is picked by the generic address selection in mm_get_unmapped_area(), which only guarantees PAGE_SIZE alignment.

That is enough for the base mapping, but it keeps a driver from ever backing a region with huge pfnmaps. huge_fault() only installs a PMD or PUD sized pfnmap when both the fault address and the pfn are aligned to that page size, see is_aligned_for_order(). A driver can only influence the first of those, and it cannot do so from its mmap() callback because the address has already been fixed up by then.

Add a get_unmapped_area() callback to vfio_device_ops along with a dispatcher in vfio_device_fops, so a bus driver can ask for an address that is aligned to the largest page size its region can be mapped with before the VMA is created. Drivers that do not provide the callback, and configurations without huge pfnmap support, fall back to mm_get_unmapped_area() and keep the existing behaviour.

The hook is only consulted when the kernel has to choose the address:
a MAP_FIXED mapping never reaches it, and an explicit address hint is passed through to the driver, which is expected to honour it. The callback therefore serves the userspace consumers that call mmap(fd, offset) with addr=0 and rely on the kernel to pick a suitable address for them, rather than trying to second guess userspace that already arranges the alignment itself.

This mirrors what drivers/dax/device.c does with dax_get_unmapped_area(), which has to satisfy the same alignment requirement for its PMD sized pfnmaps.

---
 drivers/vfio/vfio_main.c | 34 ++++++++++++++++++++++++++++++++++
 include/linux/vfio.h     | 12 ++++++++++++
 2 files changed, 46 insertions(+)
drivers/vfio/vfio_main.c +34 -0
index 4e5d738ccf4b..edf9eb4cd477 100644
@@ -28,6 +28,7 @@
 #include <linux/pseudo_fs.h>
 #include <linux/rwsem.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/seq_file.h>
 #include <linux/slab.h>
 #include <linux/stat.h>
@@ -1431,6 +1432,36 @@ static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
 	return device->ops->mmap(device, vma);
 }
 
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+/*
+ * Give the bus driver a chance to request a virtual address that allows the
+ * mapping to be backed by huge pages, fex. a PCI BAR mapping that could be
+ * faulted in with PMD or PUD sized pfnmaps.  Anything the driver cannot
+ * handle, including devices without huge mapping support, falls back to the
+ * generic address selection, which is also what happens without this
+ * callback.
+ */
+static unsigned long vfio_device_fops_get_unmapped_area(struct file *filep,
+							unsigned long addr,
+							unsigned long len,
+							unsigned long pgoff,
+							unsigned long flags)
+{
+	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device *device = df->device;
+
+	/* Paired with smp_store_release() following vfio_df_open() */
+	if (!smp_load_acquire(&df->access_granted))
+		goto out;
+
+	if (device->ops->get_unmapped_area)
+		return device->ops->get_unmapped_area(device, filep, addr, len,
+						      pgoff, flags);
+out:
+	return mm_get_unmapped_area(filep, addr, len, pgoff, flags);
+}
+#endif
+
 #ifdef CONFIG_PROC_FS
 static void vfio_device_show_fdinfo(struct seq_file *m, struct file *filep)
 {
@@ -1456,6 +1487,9 @@ const struct file_operations vfio_device_fops = {
 	.unlocked_ioctl	= vfio_device_fops_unl_ioctl,
 	.compat_ioctl	= compat_ptr_ioctl,
 	.mmap		= vfio_device_fops_mmap,
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+	.get_unmapped_area = vfio_device_fops_get_unmapped_area,
+#endif
 #ifdef CONFIG_PROC_FS
 	.show_fdinfo	= vfio_device_show_fdinfo,
 #endif
include/linux/vfio.h +12 -0
index 0cc91c6f96d2..68a84a1fd3fd 100644
@@ -102,6 +102,12 @@ struct vfio_device {
  * @ioctl: Perform ioctl(2) on device file descriptor, supporting VFIO_DEVICE_*
  *         operations documented below
  * @mmap: Perform mmap(2) on a region of the device file descriptor
+ * @get_unmapped_area: Optional, suggest a virtual address for mmap(2) of a
+ *         device region such that the mapping can be backed by huge pages,
+ *         ie. the address is aligned to the largest page size the region can
+ *         be mapped with.  Drivers that don't support huge mappings, and
+ *         configurations without huge pfnmap support, leave this unset and
+ *         the generic address selection is used.
  * @request: Request for the bus driver to release the device
  * @match: Optional device name match callback (return: 0 for no-match, >0 for
  *         match, -errno for abort (ex. match with insufficient or incorrect
@@ -143,6 +149,12 @@ struct vfio_device_ops {
 	void	(*dma_unmap)(struct vfio_device *vdev, u64 iova, u64 length);
 	int	(*device_feature)(struct vfio_device *device, u32 flags,
 				  void __user *arg, size_t argsz);
+	unsigned long (*get_unmapped_area)(struct vfio_device *vdev,
+					   struct file *filp,
+					   unsigned long addr,
+					   unsigned long len,
+					   unsigned long pgoff,
+					   unsigned long flags);
 };
 
 #if IS_ENABLED(CONFIG_IOMMUFD)
Signature · 1 line
2.43.7
#7 lore raw

Re: [PATCH v2 1/2] vfio: Add get_unmapped_area callback to vfio_device_ops

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] vfio: MAP_FIXED mappings reach device->ops->get_unmapped_area() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] vfio: MAP_FIXED mappings reach device->ops->get_unmapped_area()
--

commit 0477ef7e38ed92136abaf6feac25d75050278697
Author: Guanghui Feng <[email protected]>

vfio: Add get_unmapped_area callback to vfio_device_ops

This commit adds an optional get_unmapped_area callback to vfio_device_ops and a corresponding vfio_device_fops dispatcher so bus drivers can align mmap virtual addresses for huge pfnmaps.

Quoted 4 lines
drivers/vfio/vfio_main.c +0 -0
index 4e5d738ccf4be..edf9eb4cd4778 100644

[ ... ]

Quoted 23 lines
drivers/vfio/vfio_main.c +19 -0
@@ -1431,6 +1432,36 @@ static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
 	return device->ops->mmap(device, vma);
 }
 
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+/*
+ * Give the bus driver a chance to request a virtual address that allows the
+ * mapping to be backed by huge pages, fex. a PCI BAR mapping that could be
+ * faulted in with PMD or PUD sized pfnmaps.  Anything the driver cannot
+ * handle, including devices without huge mapping support, falls back to the
+ * generic address selection, which is also what happens without this
+ * callback.
+ */
+static unsigned long vfio_device_fops_get_unmapped_area(struct file *filep,
+							unsigned long addr,
+							unsigned long len,
+							unsigned long pgoff,
+							unsigned long flags)
+{
+	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device *device = df->device;
+
+	/* Paired with smp_store_release() following vfio_df_open() */

drivers/vfio/vfio_main.c static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma) · line 1463

Quoted 10 lines
drivers/vfio/vfio_main.c +10 -0
+	if (!smp_load_acquire(&df->access_granted))
+		goto out;
+
+	if (device->ops->get_unmapped_area)
+		return device->ops->get_unmapped_area(device, filep, addr, len,
+						      pgoff, flags);
+out:
+	return mm_get_unmapped_area(filep, addr, len, pgoff, flags);
+}
+#endif

[Severity: Medium]
Should vfio_device_fops_get_unmapped_area() skip device->ops->get_unmapped_area() and fall back to mm_get_unmapped_area() when flags & MAP_FIXED is set?

The commit message states that a MAP_FIXED mapping never reaches the hook, which matches dax_get_unmapped_area() only checking whether addr is non-zero. However, do_mmap() folds MAP_FIXED_NOREPLACE into MAP_FIXED, skips round_hint_to_min(addr) when MAP_FIXED is set, and still invokes __get_unmapped_area() -> file->f_op->get_unmapped_area(). If a driver implements this callback assuming MAP_FIXED cannot reach it (or checks only !addr), calling mmap() with addr == 0 and MAP_FIXED will run the driver's alignment logic and shift the requested fixed address instead of mapping at 0.

The follow-up commit "vfio/pci: Align BAR mappings for huge page support" checks flags & (MAP_FIXED | MAP_FIXED_NOREPLACE) in vfio_pci_core_get_unmapped_area(), but checking flags & MAP_FIXED here in vfio_device_fops_get_unmapped_area() would enforce the documented contract for all VFIO bus drivers.

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

PATCH v2 2/2 vfio/pci: Align BAR mappings for huge page support

In reply to Guanghui Feng

vfio_pci_mmap_huge_fault() is already wired up as the huge_fault handler for BAR mappings and can install PMD or PUD sized pfnmaps when CONFIG_TRANSPARENT_HUGEPAGE is enabled. Whether it ever gets to do so depends on the address the BAR VMA ended up at: is_aligned_for_order() requires both the fault address and the pfn to be aligned to the huge page size, and the generic mm_get_unmapped_area() only guarantees PAGE_SIZE alignment. When the address is unaligned the check fails, huge_fault() returns VM_FAULT_FALLBACK without having inserted anything, and the region silently degrades to one PAGE_SIZE fault per page.

A PCI BAR is required by the PCI bus specification to occupy a naturally aligned, power of two sized region of physical address space, so the pfn side of the check is already satisfied for any BAR that is at least 2MB in size. What is missing is the virtual address side, and that is only fixable before the VMA is created.

QEMU already works around this in userspace: it reserves an oversized anonymous region, rounds its address up to an alignment of MIN(pow2ceil(region->size), 1GiB), unmaps the slack at both ends and remaps every sparse subregion with MAP_FIXED at the aligned address, see QEMU commits 00b519c0bc ("vfio/helpers: Align mmaps") and 3863e47828 ("hw/vfio: align mmap to power-of-2 of region size for hugepfnmap"). Other consumers do not. DPDK, custom VMMs, test tools and QEMU releases predating that change typically call mmap(fd, offset) with addr=0 and leave the address selection to the kernel, so they are the ones that silently lose the huge mapping on a large BAR. Providing the alignment in the kernel is defence in depth as well: the kernel should not quietly give up on a huge mapping it is able to provide just because today's userspace happens to compensate for its absence.

Implement vfio_pci_core_get_unmapped_area() on top of the new vfio_device_ops callback, modelled after dax_get_unmapped_area() in drivers/dax/device.c. It derives the largest usable page size from the BAR length, capped at PUD_SIZE and at PMD_SIZE when the architecture lacks CONFIG_ARCH_SUPPORTS_PUD_PFNMAP, asks for an area with enough slack to shift the mapping up to the next aligned address, and applies that shift. Shifting the address preserves the offset of the mapping within the BAR, so aligning the address also aligns the pfn.

Everything this cannot improve keeps the current behaviour. A non-zero address returns early, which makes the change transparent for userspace such as QEMU that aligns the mapping itself: MAP_FIXED never reaches the hook at all, and an explicit hint without MAP_FIXED is honoured as is. Regions that are not mmap'able BARs, BARs smaller than PMD_SIZE, and mappings too short to span one fully aligned huge page all take the same fallback path.

Also set VM_HUGEPAGE on the BAR VMA. The THP sysfs policy does not need it, since huge pfnmaps are uncompactable and so vma_file_bypass_thp_tuneables() ignores the tuneables for a PFNMAP VMA that has a huge_fault handler.
thp_vma_allowable_order() is still consulted before create_huge_pmd() and create_huge_pud() are reached, though, and it calls vma_thp_disabled(), which reports the VMA as disabled once the process has called prctl(PR_SET_THP_DISABLE, PR_THP_DISABLE_EXCEPT_ADVISED) unless VM_HUGEPAGE is set. Marking the VMA keeps the huge mapping available for such a process instead of leaving it at the mercy of that single bypass, and makes the intent explicit regardless of how the process or the administrator configured THP.

---
 drivers/vfio/pci/vfio_pci.c      |  3 +
 drivers/vfio/pci/vfio_pci_core.c | 95 ++++++++++++++++++++++++++++++++
 include/linux/vfio_pci_core.h    |  8 +++
 3 files changed, 106 insertions(+)
drivers/vfio/pci/vfio_pci.c +3 -0
index e7c012febe91..2757ff9075d2 100644
@@ -158,6 +158,9 @@ static const struct vfio_device_ops vfio_pci_ops = {
 	.read		= vfio_pci_core_read,
 	.write		= vfio_pci_core_write,
 	.mmap		= vfio_pci_core_mmap,
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+	.get_unmapped_area = vfio_pci_core_get_unmapped_area,
+#endif
 	.request	= vfio_pci_core_request,
 	.match		= vfio_pci_core_match,
 	.match_token_uuid = vfio_pci_core_match_token_uuid,
drivers/vfio/pci/vfio_pci_core.c +95 -0

113 lines not on this page · raw message

include/linux/vfio_pci_core.h +8 -0
index 2f3fa2787737..98350c87d2ea 100644
@@ -187,6 +187,14 @@ vm_fault_t vfio_pci_vmf_insert_pfn(struct vfio_pci_core_device *vdev,
 				   struct vm_fault *vmf, unsigned long pfn,
 				   unsigned int order);
 int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma);
+#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
+unsigned long vfio_pci_core_get_unmapped_area(struct vfio_device *core_vdev,
+					      struct file *filp,
+					      unsigned long addr,
+					      unsigned long len,
+					      unsigned long pgoff,
+					      unsigned long flags);
+#endif
 void vfio_pci_core_request(struct vfio_device *core_vdev, unsigned int count);
 int vfio_pci_core_match(struct vfio_device *core_vdev, char *buf);
 int vfio_pci_core_match_token_uuid(struct vfio_device *core_vdev,
Signature · 1 line
2.43.7
#9 lore raw

Re: [PATCH v2 2/2] vfio/pci: Align BAR mappings for huge page support

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] vfio/pci: missing PMD_SIZE fallback in vfio_pci_core_get_unmapped_area() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] vfio/pci: missing PMD_SIZE fallback in vfio_pci_core_get_unmapped_area()
--

commit 3832a7d37e0d4c0624cff5984fcc1260c28a37ab
Author: Guanghui Feng <[email protected]>

vfio/pci: Align BAR mappings for huge page support

This commit implements vfio_pci_core_get_unmapped_area() to align BAR VMA addresses to PMD_SIZE or PUD_SIZE and sets VM_HUGEPAGE on BAR mappings so vfio_pci_mmap_huge_fault() can install huge pfnmaps.

Quoted 4 lines
drivers/vfio/pci/vfio_pci_core.c +0 -0
index f2d5b6857925f..a1ccdd5f4657f 100644

[ ... ]

Quoted 1 line
drivers/vfio/pci/vfio_pci_core.c +0 -0
@@ -1878,12 +1879,106 @@ int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma

[ ... ]

Quoted 7 lines
drivers/vfio/pci/vfio_pci_core.c +7 -0
+unsigned long vfio_pci_core_get_unmapped_area(struct vfio_device *core_vdev,
+					      struct file *filp,
+					      unsigned long addr,
+					      unsigned long len,
+					      unsigned long pgoff,
+					      unsigned long flags)
+{

[ ... ]

Quoted 32 lines
drivers/vfio/pci/vfio_pci_core.c +32 -0
+	/*
+	 * Select the largest huge page size that the BAR physical alignment,
+	 * mapping length, and arch support can all satisfy.  Only PMD and PUD
+	 * orders are supported by vfio_pci_vmf_insert_pfn().
+	 */
+	if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PUD_PFNMAP) &&
+	    bar_len >= PUD_SIZE && len >= PUD_SIZE)
+		align = PUD_SIZE;
+	else if (bar_len >= PMD_SIZE && len >= PMD_SIZE)
+		align = PMD_SIZE;
+	else
+		goto out;
+
+	off = pgoff << PAGE_SHIFT;
+	off_end = off + len;
+	if (off_end < off)
+		goto out;
+	off_align = round_up(off, align);
+
+	/* The mapping has to span at least one fully aligned huge page */
+	if (off_end <= off_align || off_end - off_align < align)
+		goto out;
+
+	len_align = len + align;
+	if (len_align < len)
+		goto out;
+
+	/*
+	 * Find an area that can hold the mapping plus the slack needed to
+	 * shift it up to the next aligned address, then apply that shift.
+	 * The shift preserves the relative alignment of the file offset,
+	 * which is what makes the pfn alignment work out.

drivers/vfio/pci/vfio_pci_core.c int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma · line 1974

Quoted 10 lines
drivers/vfio/pci/vfio_pci_core.c +10 -0
+	 */
+	addr_align = mm_get_unmapped_area(filp, addr, len_align, pgoff, flags);
+	if (!IS_ERR_VALUE(addr_align)) {
+		addr_align += (off - addr_align) & (align - 1);
+		return addr_align;
+	}
+
+out:
+	return mm_get_unmapped_area(filp, addr, len, pgoff, flags);
+}

[Severity: Medium]
Should vfio_pci_core_get_unmapped_area() fall back to PMD_SIZE when PUD_SIZE alignment cannot be satisfied?

When CONFIG_ARCH_SUPPORTS_PUD_PFNMAP is enabled and both bar_len and len are at least PUD_SIZE, align is set to PUD_SIZE before checking whether [off, off_end) spans a PUD_SIZE-aligned boundary or whether mm_get_unmapped_area() can find a len + PUD_SIZE range. If a mapping on a 2 GiB BAR starts at a non-1GiB-aligned offset (for example to skip an MSI-X table at the start of the BAR) and does not enclose a full 1 GiB PUD page, or if virtual address space is too fragmented for len + PUD_SIZE, this jumps straight to out and returns a PAGE_SIZE-aligned VMA. is_aligned_for_order() in vfio_pci_mmap_huge_fault() then fails for PMD_ORDER as well, degrading the entire mapping to PAGE_SIZE faults instead of using PMD huge pfnmaps.

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

Re: [PATCH v2 2/2] vfio/pci: Align BAR mappings for huge page support

In reply to Guanghui Feng
Quoted 53 lines · Guanghui Feng
drivers/vfio/pci/vfio_pci_core.c +53 -0
+unsigned long vfio_pci_core_get_unmapped_area(struct vfio_device *core_vdev,
+					      struct file *filp,
+					      unsigned long addr,
+					      unsigned long len,
+					      unsigned long pgoff,
+					      unsigned long flags)
+{
+	struct vfio_pci_core_device *vdev =
+		container_of(core_vdev, struct vfio_pci_core_device, vdev);
+	struct pci_dev *pdev = vdev->pdev;
+	unsigned long align, off, off_end, off_align, len_align, addr_align;
+	unsigned int index;
+	u64 bar_len;
+
+	/* Don't interfere with explicit address requests or fixed mappings */
+	if (addr || (flags & (MAP_FIXED | MAP_FIXED_NOREPLACE)))
+		goto out;
+
+	index = pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
+	if (index >= VFIO_PCI_ROM_REGION_INDEX || !vdev->bar_mmap_supported[index])
+		goto out;
+
+	bar_len = pci_resource_len(pdev, index);
+	if (!bar_len)
+		goto out;
+
+	/*
+	 * Select the largest huge page size that the BAR physical alignment,
+	 * mapping length, and arch support can all satisfy.  Only PMD and PUD
+	 * orders are supported by vfio_pci_vmf_insert_pfn().
+	 */
+	if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PUD_PFNMAP) &&
+	    bar_len >= PUD_SIZE && len >= PUD_SIZE)
+		align = PUD_SIZE;
+	else if (bar_len >= PMD_SIZE && len >= PMD_SIZE)
+		align = PMD_SIZE;
+	else
+		goto out;
+
+	off = pgoff << PAGE_SHIFT;
+	off_end = off + len;
+	if (off_end < off)
+		goto out;
+	off_align = round_up(off, align);
+
+	/* The mapping has to span at least one fully aligned huge page */
+	if (off_end <= off_align || off_end - off_align < align)
+		goto out;
+
+	len_align = len + align;
+	if (len_align < len)
+		goto out;
+

drivers/vfio/pci/vfio_pci_core.c int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma · line 1969

Quoted 10 lines
drivers/vfio/pci/vfio_pci_core.c +10 -0
+	/*
+	 * Find an area that can hold the mapping plus the slack needed to
+	 * shift it up to the next aligned address, then apply that shift.
+	 * The shift preserves the relative alignment of the file offset,
+	 * which is what makes the pfn alignment work out.
+	 */
+	addr_align = mm_get_unmapped_area(filp, addr, len_align, pgoff, flags);
+	if (!IS_ERR_VALUE(addr_align)) {
+		addr_align += (off - addr_align) & (align - 1);
+		return addr_align;

PeterX was working on this previously and last time I was not excited to see all this mm logic open coded in drivers.

I was hoping to see that the core mm could provide some helper scheme for drivers that already know what they want to map to get a vma alignment that is optimal for the architecutre.

Peter had a design that seemed like a good exploration at least..

Jason

#11 lore raw

Re: [PATCH v2 2/2] vfio/pci: Align BAR mappings for huge page support

Quoted 69 lines · Jason Gunthorpe
Quoted 53 lines · Guanghui Feng
drivers/vfio/pci/vfio_pci_core.c +53 -0
+unsigned long vfio_pci_core_get_unmapped_area(struct vfio_device *core_vdev,
+					      struct file *filp,
+					      unsigned long addr,
+					      unsigned long len,
+					      unsigned long pgoff,
+					      unsigned long flags)
+{
+	struct vfio_pci_core_device *vdev =
+		container_of(core_vdev, struct vfio_pci_core_device, vdev);
+	struct pci_dev *pdev = vdev->pdev;
+	unsigned long align, off, off_end, off_align, len_align, addr_align;
+	unsigned int index;
+	u64 bar_len;
+
+	/* Don't interfere with explicit address requests or fixed mappings */
+	if (addr || (flags & (MAP_FIXED | MAP_FIXED_NOREPLACE)))
+		goto out;
+
+	index = pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
+	if (index >= VFIO_PCI_ROM_REGION_INDEX || !vdev->bar_mmap_supported[index])
+		goto out;
+
+	bar_len = pci_resource_len(pdev, index);
+	if (!bar_len)
+		goto out;
+
+	/*
+	 * Select the largest huge page size that the BAR physical alignment,
+	 * mapping length, and arch support can all satisfy.  Only PMD and PUD
+	 * orders are supported by vfio_pci_vmf_insert_pfn().
+	 */
+	if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PUD_PFNMAP) &&
+	    bar_len >= PUD_SIZE && len >= PUD_SIZE)
+		align = PUD_SIZE;
+	else if (bar_len >= PMD_SIZE && len >= PMD_SIZE)
+		align = PMD_SIZE;
+	else
+		goto out;
+
+	off = pgoff << PAGE_SHIFT;
+	off_end = off + len;
+	if (off_end < off)
+		goto out;
+	off_align = round_up(off, align);
+
+	/* The mapping has to span at least one fully aligned huge page */
+	if (off_end <= off_align || off_end - off_align < align)
+		goto out;
+
+	len_align = len + align;
+	if (len_align < len)
+		goto out;
+

drivers/vfio/pci/vfio_pci_core.c int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma · line 1969

Quoted 10 lines
drivers/vfio/pci/vfio_pci_core.c +10 -0
+	/*
+	 * Find an area that can hold the mapping plus the slack needed to
+	 * shift it up to the next aligned address, then apply that shift.
+	 * The shift preserves the relative alignment of the file offset,
+	 * which is what makes the pfn alignment work out.
+	 */
+	addr_align = mm_get_unmapped_area(filp, addr, len_align, pgoff, flags);
+	if (!IS_ERR_VALUE(addr_align)) {
+		addr_align += (off - addr_align) & (align - 1);
+		return addr_align;

PeterX was working on this previously and last time I was not excited to see all this mm logic open coded in drivers.

Quoted 5 lines

I was hoping to see that the core mm could provide some helper scheme for drivers that already know what they want to map to get a vma alignment that is optimal for the architecutre.

Peter had a design that seemed like a good exploration at least..

Well you and Matthew and I were discussing something similar previously also?

The AI fixgeddon is delaying any nice-to-haves of late, but in spirit yes, it's appalling to have this mm code duplicated and it clearly shows a gap in the API.

Quoted 2 lines

Jason

--
Cheers, Lorenzo