mm/vfio: huge pfnmaps with !MAP_FIXED mappings
Subsystems (8)
v2 cover mm/vfio: huge pfnmaps with !MAP_FIXED mappings
This series is based on v6.18. It allows mmap(!MAP_FIXED) to work with huge pfnmaps with best effort. Meanwhile, it enables it for vfio-pci as the first user.
v1: https://lore.kernel.org/r/[email protected]
A changelog may not apply because all the patches were rewrote based on a new interface this v2 introduced. Hence omitted.
In this version, a new file operation, get_mapping_order(), is introduced (based on discussion with Jason on v1) to minimize the code needed for drivers to implement this. It also helps avoid exporting any mm functions. One can refer to the discussion in v1 for more information.
Currently, get_mapping_order() API is define as:
int (*get_mapping_order)(struct file *file, unsigned long pgoff, size_t len);
The first argument is the file pointer, the 2nd+3rd are the pgoff+len specified from a mmap() request. The driver can use this interface to opt-in providing mapping order hints to core mm on VA allocations for the range of the file specified. I kept the interface as simple for now, so that core mm will always do the alignment with pgoff assuming that would always work. The driver can only report the order from pgoff+len, which will be used to do the alignment.
Before this series, an userapp in most cases need to be modified to benefit from huge mappings to provide huge size aligned VA using MAP_FIXED. After this series, the userapp can benefit from huge pfnmap automatically after the kernel upgrades, with no userspace modifications.
It's still best-effort, because the auto-alignment will require a larger VA range to be allocated via the per-arch allocator, hence if the huge-mapping aligned VA cannot be allocated then it'll still fallback to small mappings like before. However that's from theory POV: in reality I don't yet know when it'll fail especially when on a 64bits system.
So far, only vfio-pci is supported. But the logic should be applicable to all the drivers that support or will support huge pfnmaps. I've copied some more people in this version too from hardware perspective.
For testings:
- checkpatch.pl
- cross build harness
- unit test that I got from Alex [1], checking mmap() alignments on a QEMU instance with an 128MB bar.
Checking the alignments look all sane with mmap(!MAP_FIXED), and huge mappings properly installed. I didn't observe anything wrong.
I currently lack larger bars to test PUD sizes. Please kindly report if one can run this with 1G+ bars and hit issues.
Alex Mastro: thanks for the testing offered in v1, but since this series was rewritten, a re-test will be needed. I hence didn't collect the T-b.
Comments welcomed, thanks.
[1] https://github.com/awilliam/tests/blob/vfio-pci-device-map-alignment/vfio-pci-device-map-alignment.c
Peter Xu (4):
mm/thp: Allow thp_get_unmapped_area_vmflags() to take alignment
mm: Add file_operations.get_mapping_order()
vfio: Introduce vfio_device_ops.get_mapping_order hook
vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
Documentation/filesystems/vfs.rst | 4 +++ drivers/vfio/pci/vfio_pci.c | 1 + drivers/vfio/pci/vfio_pci_core.c | 49 ++++++++++++++++++++++++++ drivers/vfio/vfio_main.c | 14 ++++++++ include/linux/fs.h | 1 + include/linux/huge_mm.h | 5 +-- include/linux/vfio.h | 5 +++ include/linux/vfio_pci_core.h | 2 ++ mm/huge_memory.c | 7 ++-- mm/mmap.c | 58 +++++++++++++++++++++++++++---- 10 files changed, 135 insertions(+), 11 deletions(-)
Signature · 1 line
2.50.1
PATCH v2 1/4 mm/thp: Allow thp_get_unmapped_area_vmflags() to take alignment
Add "align" parameter to thp_get_unmapped_area_vmflags() so that it allows get unmapped area with any alignment.
There're two existing callers, use PMD_SIZE explicitly for them.
No functional change intended.
--- include/linux/huge_mm.h | 5 +++-- mm/huge_memory.c | 7 ++++--- mm/mmap.c | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-)
include/linux/huge_mm.h +3 -2
@@ -362,7 +362,7 @@ unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags);unsigned long thp_get_unmapped_area_vmflags (struct file *filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags, -vm_flags_t vm_flags); +unsigned long align,vm_flags_t vm_flags);bool can_split_folio (struct folio *folio,int caller_pins,int *pextra_pins); int split_huge_page_to_list_to_order(struct page *page, struct list_head *list,
@@ -559,7 +559,8 @@ static inline unsigned long thp_vma_allowable_orders(struct vm_area_struct *vma,static inline unsigned long thp_get_unmapped_area_vmflags (struct file *filp,unsigned long addr,unsigned long len,unsigned long pgoff, -unsigned long flags,vm_flags_t vm_flags) +unsigned long flags,unsigned long align, +vm_flags_t vm_flags) {return 0 ; }
mm/huge_memory.c +4 -3
@@ -1155,12 +1155,12 @@ static unsigned long __thp_get_unmapped_area(struct file *filp,unsigned long thp_get_unmapped_area_vmflags (struct file *filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags, -vm_flags_t vm_flags) +unsigned long align,vm_flags_t vm_flags) {unsigned long ret;loff_t off = (loff_t )pgoff <<PAGE_SHIFT ; - ret =__thp_get_unmapped_area (filp, addr, len, off, flags,PMD_SIZE , vm_flags); + ret =__thp_get_unmapped_area (filp, addr, len, off, flags, align, vm_flags);if (ret)return ret;
@@ -1171,7 +1171,8 @@ unsigned long thp_get_unmapped_area_vmflags(struct file *filp, unsigned long addunsigned long thp_get_unmapped_area (struct file *filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags) { -return thp_get_unmapped_area_vmflags (filp, addr, len, pgoff, flags,0 ); +return thp_get_unmapped_area_vmflags (filp, addr, len, pgoff, flags, +PMD_SIZE ,0 ); }EXPORT_SYMBOL_GPL (thp_get_unmapped_area);
mm/mmap.c +2 -1
@@ -846,7 +846,8 @@ __get_unmapped_area(struct file *file, unsigned long addr, unsigned long len, && IS_ALIGNED(len, PMD_SIZE)) { /* Ensures that larger anonymous mappings are THP aligned. */ addr = thp_get_unmapped_area_vmflags(file, addr, len, - pgoff, flags, vm_flags); + pgoff, flags, PMD_SIZE, + vm_flags); } else { addr =mm_get_unmapped_area_vmflags (current->mm, file, addr, len, pgoff, flags, vm_flags);
Signature · 1 line
2.50.1
PATCH v2 2/4 mm: Add file_operations.get_mapping_order()
In reply to Peter XuAdd one new file operation, get_mapping_order(). It can be used by file backends to report mapping order hints.
By default, Linux assumed we will map in PAGE_SIZE chunks. With this hint, the driver can report the possibility of mapping chunks that are larger than PAGE_SIZE. Then, the VA allocator will try to use that as alignment when allocating the VA ranges.
This is useful because when chunks to be mapped are larger than PAGE_SIZE, VA alignment matters and it needs to be aligned with the size of the chunk to be mapped.
Said that, no matter what is the alignment used for the VA allocation, the driver can still decide which size to map the chunks. It is also not an issue if it keeps mapping in PAGE_SIZE.
get_mapping_order() is defined to take three parameters. Besides the 1st parameter which will be the file object pointer, the 2nd + 3rd parameters being the pgoff + size of the mmap() request. Its retval is defined as the order, which must be non-negative to enable the alignment. When zero is returned, it should behave like when the hint is not provided, IOW, alignment will still be PAGE_SIZE.
When the order is too big, ignore the hint. Normally drivers are trusted, so it's more of an extra layer of safety measure.
--- Documentation/filesystems/vfs.rst | 4 +++ include/linux/fs.h | 1 + mm/mmap.c | 59 +++++++++++++++++++++++++++---- 3 files changed, 57 insertions(+), 7 deletions(-)
Documentation/filesystems/vfs.rst +4 -0
@@ -1069,6 +1069,7 @@ This describes how the VFS can manipulate an open file. As of kernel int (*fasync) (int, struct file *, int); int (*lock) (struct file *, int, struct file_lock *); unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); + int (*get_mapping_order)(struct file *, unsigned long, size_t); int (*check_flags)(int); int (*flock) (struct file *, int, struct file_lock *); ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
@@ -1165,6 +1166,9 @@ otherwise noted. ``get_unmapped_area`` called by the mmap(2) system call +``get_mapping_order`` + called by the mmap(2) system call to get mapping order hint + ``check_flags`` called by the fcntl(2) system call for F_SETFL command
include/linux/fs.h +1 -0
@@ -2287,6 +2287,7 @@ struct file_operations {int (*fasync) (int ,struct file *,int );int (*lock) (struct file *,int ,struct file_lock *);unsigned long (*get_unmapped_area)(struct file *,unsigned long ,unsigned long ,unsigned long ,unsigned long ); +int (*get_mapping_order)(struct file *file,unsigned long pgoff,size_t len);int (*check_flags)(int );int (*flock) (struct file *,int ,struct file_lock *);ssize_t (*splice_write)(struct pipe_inode_info *,struct file *,loff_t *,size_t ,unsigned int );
mm/mmap.c +52 -7
79 lines not on this page · raw message
Signature · 1 line
2.50.1
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
I forgot to copy mm/fs maintainers for the 1st/2nd patches in this series, my apologies. Whole series can be found here:
https://lore.kernel.org/r/[email protected]
I'll modify the cc list when repost.
Thanks,
Quoted 157 lines · Peter Xu
Add one new file operation,
get_mapping_order(). It can be used by file backends to report mapping order hints.By default, Linux assumed we will map in
PAGE_SIZEchunks. With this hint, the driver can report the possibility of mapping chunks that are larger thanPAGE_SIZE. Then, the VA allocator will try to use that as alignment when allocating the VA ranges.This is useful because when chunks to be mapped are larger than
PAGE_SIZE, VA alignment matters and it needs to be aligned with the size of the chunk to be mapped.Said that, no matter what is the alignment used for the VA allocation, the driver can still decide which size to map the chunks. It is also not an issue if it keeps mapping in
PAGE_SIZE.
get_mapping_order()is defined to take three parameters. Besides the 1st parameter which will be the file object pointer, the 2nd + 3rd parameters being the pgoff + size of themmap()request. Its retval is defined as the order, which must be non-negative to enable the alignment. When zero is returned, it should behave like when the hint is not provided, IOW, alignment will still bePAGE_SIZE.When the order is too big, ignore the hint. Normally drivers are trusted, so it's more of an extra layer of safety measure.
Suggested-by Jason Gunthorpe <[email protected]>Signed-off-by Peter Xu <[email protected]>--- Documentation/filesystems/vfs.rst | 4 +++ include/linux/fs.h | 1 + mm/mmap.c | 59 +++++++++++++++++++++++++++---- 3 files changed, 57 insertions(+), 7 deletions(-)Documentation/filesystems/vfs.rst +4
-0@@ -1069,6 +1069,7 @@ This describes how the VFS can manipulate an open file. As of kernel int (*fasync) (int, struct file *, int); int (*lock) (struct file *, int, struct file_lock *); unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); + int (*get_mapping_order)(struct file *, unsigned long, size_t); int (*check_flags)(int); int (*flock) (struct file *, int, struct file_lock *); ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);@@ -1165,6 +1166,9 @@ otherwise noted. ``get_unmapped_area`` called by the mmap(2) system call +``get_mapping_order`` + called by the mmap(2) system call to get mapping order hint + ``check_flags`` called by the fcntl(2) system call for F_SETFL commandinclude/linux/fs.h +1
-0@@ -2287,6 +2287,7 @@ struct file_operations {int (*fasync) (int ,struct file *,int );int (*lock) (struct file *,int ,struct file_lock *);unsigned long (*get_unmapped_area)(struct file *,unsigned long ,unsigned long ,unsigned long ,unsigned long ); +int (*get_mapping_order)(struct file *file,unsigned long pgoff,size_t len);int (*check_flags)(int );int (*flock) (struct file *,int ,struct file_lock *);ssize_t (*splice_write)(struct pipe_inode_info *,struct file *,loff_t *,size_t ,unsigned int );mm/mmap.c +52
-7@@ -808,6 +808,33 @@ unsigned long mm_get_unmapped_area_vmflags(struct mm_struct *mm, struct file *fireturn arch_get_unmapped_area (filp, addr, len, pgoff, flags, vm_flags); } +static inline bool file_has_mmap_order_hint (struct file *file) +{ +return file && file->f_op && file->f_op->get_mapping_order; +} + +static inline bool +mmap_should_align (struct file *file,unsigned long addr,unsigned long len) +{ +/* When THP not enabled at all, skip */ +if (!IS_ENABLED (CONFIG_TRANSPARENT_HUGEPAGE )) +return false; + +/* Never try any alignment if the mmap() address hint is provided */ +if (addr) +return false; + +/* Anonymous THP could use some better alignment when len aligned */ +if (!file) +return IS_ALIGNED (len,PMD_SIZE ); + +/* +* It's a file mapping, no address hint provided by caller, try any +* alignment if the file backend would provide a hint +*/ +return file_has_mmap_order_hint (file); +} +unsigned long __get_unmapped_area (struct file *file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags,vm_flags_t vm_flags)@@ -815,8 +842,9 @@ __get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,unsigned long (*get_area)(struct file *,unsigned long ,unsigned long ,unsigned long ,unsigned long ) =NULL ; -unsigned long error =arch_mmap_check (addr, len, flags); +unsigned long align; +if (error)return error;@@ -841,13 +869,30 @@ __get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,if (get_area) { addr =get_area (file, addr, len, pgoff, flags); - }else if (IS_ENABLED (CONFIG_TRANSPARENT_HUGEPAGE ) && !file - && !addr/* no hint */ - &&IS_ALIGNED (len,PMD_SIZE )) { -/* Ensures that larger anonymous mappings are THP aligned. */ + }else if (mmap_should_align (file, addr, len)) { +if (file_has_mmap_order_hint (file)) { +int order; +/* +* Allow driver to opt-in on the order hint. +* +* Sanity check on the order returned. Treating +* either negative or too big order to be invalid, +* where alignment will be skipped. +*/ + order = file->f_op->get_mapping_order (file, pgoff, len); +if (order <0 ) + order =0 ; +if (check_shl_overflow (PAGE_SIZE , order, &align)) +/* No alignment applied */ + align =PAGE_SIZE ; + }else { +/* Default alignment for anonymous THPs */ + align =PMD_SIZE ; + } + addr =thp_get_unmapped_area_vmflags (file, addr, len, - pgoff, flags,PMD_SIZE , - vm_flags); + pgoff, flags, + align, vm_flags); }else { addr =mm_get_unmapped_area_vmflags (current->mm, file, addr, len, pgoff, flags, vm_flags);Signature · 1 line
2.50.1
Signature · 1 line
Peter Xu
Matthew Wilcox
maintainerRe: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 2 lines · Peter Xu
Quoted 2 lines
Add one new file operation,
get_mapping_order(). It can be used by file backends to report mapping order hints.
This seems like a terrible idea. I'll look at it after Plumbers.
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 5 lines · Matthew Wilcox
Quoted 2 lines · Peter Xu
Quoted 2 lines
Add one new file operation,
get_mapping_order(). It can be used by file backends to report mapping order hints.This seems like a terrible idea. I'll look at it after Plumbers.
Sure, no rush, please feel free to go through discussion in v1 when it comes, that's where we landed to this API based on suggestions from Jason.
I'm open to other suggestions.
Signature · 1 line
Peter Xu
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
In reply to Peter XuQuoted 16 lines · Peter Xu
Add one new file operation,
get_mapping_order(). It can be used by file backends to report mapping order hints.By default, Linux assumed we will map in
PAGE_SIZEchunks. With this hint, the driver can report the possibility of mapping chunks that are larger thanPAGE_SIZE. Then, the VA allocator will try to use that as alignment when allocating the VA ranges.This is useful because when chunks to be mapped are larger than
PAGE_SIZE, VA alignment matters and it needs to be aligned with the size of the chunk to be mapped.Said that, no matter what is the alignment used for the VA allocation, the driver can still decide which size to map the chunks. It is also not an issue if it keeps mapping in
PAGE_SIZE.
Quoted 6 lines
get_mapping_order()is defined to take three parameters. Besides the 1st parameter which will be the file object pointer, the 2nd + 3rd parameters being the pgoff + size of themmap()request. Its retval is defined as the order, which must be non-negative to enable the alignment. When zero is returned, it should behave like when the hint is not provided, IOW, alignment will still bePAGE_SIZE.
This should explain how it works when the incoming pgoff is not aligned..
I think for dpdk we want to support mapping around the MSI hole so something like
pgoff 0 -> 2M
skip 4k
2m + 4k -> 64M
Should setup the last VMA to align to 2M + 4k so the first PMD is fragmented to 4k pages but the remaning part is 2M sized or better.
We just noticed a bug very similer to this in qemu around it's manual alignment scheme where it would de-align things around the MSI window and spoil the PMDs.
I guess ideally the file could return the order assuming an aligned-to-start pgoff and the core code could use that order to compute an adjustment for
the actual pgoff so we maintain:
va % order = pgoff % order
Jason
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 24 lines · Jason Gunthorpe
Quoted 16 lines · Peter Xu
Add one new file operation,
get_mapping_order(). It can be used by file backends to report mapping order hints.By default, Linux assumed we will map in
PAGE_SIZEchunks. With this hint, the driver can report the possibility of mapping chunks that are larger thanPAGE_SIZE. Then, the VA allocator will try to use that as alignment when allocating the VA ranges.This is useful because when chunks to be mapped are larger than
PAGE_SIZE, VA alignment matters and it needs to be aligned with the size of the chunk to be mapped.Said that, no matter what is the alignment used for the VA allocation, the driver can still decide which size to map the chunks. It is also not an issue if it keeps mapping in
PAGE_SIZE.Quoted 6 lines
get_mapping_order()is defined to take three parameters. Besides the 1st parameter which will be the file object pointer, the 2nd + 3rd parameters being the pgoff + size of themmap()request. Its retval is defined as the order, which must be non-negative to enable the alignment. When zero is returned, it should behave like when the hint is not provided, IOW, alignment will still bePAGE_SIZE.
Quoted 2 lines
This should explain how it works when the incoming pgoff is not aligned..
Hmm, I thought the charm of this new proposal (based on suggestions of your v1 reviews) is to not need to worry on this.. Or maybe you meant I should add some doc comments in the commit message?
If so I can do that.
thp_get_unmapped_area_vmflags() should have taken all kinds of pgoff unalignment into account. It's just that this v2 is better than v1 when using this new API because that THP function doesn't need to be exported anymore.
Quoted 8 lines
I think for dpdk we want to support mapping around the MSI hole so something like
pgoff 0 -> 2M
skip 4k
2m + 4k -> 64M
Quoted 6 lines
Should setup the last VMA to align to 2M + 4k so the first PMD is fragmented to 4k pages but the remaning part is 2M sized or better.
We just noticed a bug very similer to this in qemu around it's manual alignment scheme where it would de-align things around the MSI window and spoil the PMDs.
Right, IIUC this series should work all fine exactly as you said.
Here the driver should only care about what owns the content of (pgoff, len) range, and the proper order to map these chunks. In case of VFIO, it will know what BAR it's mapping, so as to return a proper order for that specific bar pointed by (pgoff, len).
The driver doesn't need to worry on anything else like above.
Let me know if I misread your question, or if this series doesn't achieve what you're asking here..
Thanks,
Quoted 9 lines
I guess ideally the file could return the order assuming an aligned-to-start pgoff and the core code could use that order to compute an adjustment for
the actual pgoff so we maintain:
va % order = pgoff % orderJason
Signature · 1 line
Peter Xu
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 25 lines · Peter Xu
Quoted 24 lines · Jason Gunthorpe
Quoted 22 lines · Peter Xu
Add one new file operation,
get_mapping_order(). It can be used by file backends to report mapping order hints.By default, Linux assumed we will map in
PAGE_SIZEchunks. With this hint, the driver can report the possibility of mapping chunks that are larger thanPAGE_SIZE. Then, the VA allocator will try to use that as alignment when allocating the VA ranges.This is useful because when chunks to be mapped are larger than
PAGE_SIZE, VA alignment matters and it needs to be aligned with the size of the chunk to be mapped.Said that, no matter what is the alignment used for the VA allocation, the driver can still decide which size to map the chunks. It is also not an issue if it keeps mapping in
PAGE_SIZE.
get_mapping_order()is defined to take three parameters. Besides the 1st parameter which will be the file object pointer, the 2nd + 3rd parameters being the pgoff + size of themmap()request. Its retval is defined as the order, which must be non-negative to enable the alignment. When zero is returned, it should behave like when the hint is not provided, IOW, alignment will still bePAGE_SIZE.
Quoted 6 lines
Quoted 2 lines
This should explain how it works when the incoming pgoff is not aligned..
Hmm, I thought the charm of this new proposal (based on suggestions of your v1 reviews) is to not need to worry on this.. Or maybe you meant I should add some doc comments in the commit message?
It can't be ignored, I don't think I ever said that. I said the driver shouldn't have to worry about it, the core MM should deal with this.
Quoted 7 lines
Quoted 7 lines
I think for dpdk we want to support mapping around the MSI hole so something like
pgoff 0 -> 2M
skip 4k
2m + 4k -> 64M
Quoted 8 lines
Quoted 6 lines
Should setup the last VMA to align to 2M + 4k so the first PMD is fragmented to 4k pages but the remaning part is 2M sized or better.
We just noticed a bug very similer to this in qemu around it's manual alignment scheme where it would de-align things around the MSI window and spoil the PMDs.
Right, IIUC this series should work all fine exactly as you said.
Are you sure? I did not see code doing this. The second mapping needs to select a VA such that
VA % 2M == 4k
And I don't see it doing that.
Jason
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 50 lines · Jason Gunthorpe
Quoted 25 lines · Peter Xu
Quoted 24 lines · Jason Gunthorpe
Quoted 22 lines · Peter Xu
Add one new file operation,
get_mapping_order(). It can be used by file backends to report mapping order hints.By default, Linux assumed we will map in
PAGE_SIZEchunks. With this hint, the driver can report the possibility of mapping chunks that are larger thanPAGE_SIZE. Then, the VA allocator will try to use that as alignment when allocating the VA ranges.This is useful because when chunks to be mapped are larger than
PAGE_SIZE, VA alignment matters and it needs to be aligned with the size of the chunk to be mapped.Said that, no matter what is the alignment used for the VA allocation, the driver can still decide which size to map the chunks. It is also not an issue if it keeps mapping in
PAGE_SIZE.
get_mapping_order()is defined to take three parameters. Besides the 1st parameter which will be the file object pointer, the 2nd + 3rd parameters being the pgoff + size of themmap()request. Its retval is defined as the order, which must be non-negative to enable the alignment. When zero is returned, it should behave like when the hint is not provided, IOW, alignment will still bePAGE_SIZE.Quoted 6 lines
Quoted 2 lines
This should explain how it works when the incoming pgoff is not aligned..
Hmm, I thought the charm of this new proposal (based on suggestions of your v1 reviews) is to not need to worry on this.. Or maybe you meant I should add some doc comments in the commit message?
It can't be ignored, I don't think I ever said that. I said the driver shouldn't have to worry about it, the core MM should deal with this.
Quoted 14 lines
Quoted 13 lines
I think for dpdk we want to support mapping around the MSI hole so something like
pgoff 0 -> 2M
skip 4k
2m + 4k -> 64MShould setup the last VMA to align to 2M + 4k so the first PMD is fragmented to 4k pages but the remaning part is 2M sized or better.
We just noticed a bug very similer to this in qemu around it's manual alignment scheme where it would de-align things around the MSI window and spoil the PMDs.
Quoted 8 lines
Quoted 1 line
Right, IIUC this series should work all fine exactly as you said.
Are you sure? I did not see code doing this. The second mapping needs to select a VA such that
VA % 2M == 4k
And I don't see it doing that.
I have an old program tested this, I ran it but I didn't mention it in the cover letter. I'm 99% sure it works like it, unless I'm seriously wrong somewhere.
See:
https://github.com/xzpeter/clibs/blob/master/misc/vfio-pci-nofix.c
mmap BAR with memory ENABLED and read (offset=0x0, size=0x8000000) mmap()=0x7f4395a00000 - 0.000117s
read(32768) - 0.085376s
mmap BAR with memory ENABLED and read (offset=0x1000, size=0x7fff000) mmap()=0x7f4395a01000 - 0.000012s
read(32767) - 0.088642s
mmap BAR with memory ENABLED and read (offset=0x0, size=0x7fff000) mmap()=0x7f4395a00000 - 0.000015s
read(32767) - 0.093850s
mmap BAR with memory ENABLED and read (offset=0x1000, size=0x7ffe000) mmap()=0x7f4395a01000 - 0.000011s
read(32766) - 0.093248s
Also see __thp_get_unmapped_area() processed such pgoff, it allocates VA with len_pad (not len), and pad the retval at last.
Please let me know if it didn't work like it, then it might be a bug.
Thanks,
Signature · 1 line
Peter Xu
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 4 lines · Peter Xu
Also see
__thp_get_unmapped_area()processed such pgoff, it allocates VA withlen_pad(not len), and pad the retval at last.Please let me know if it didn't work like it, then it might be a bug.
It should all be documented then in the kdoc for the new ops, in this kind of language that the resulting VA flows from pgoff
Jason
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 8 lines · Jason Gunthorpe
Quoted 4 lines · Peter Xu
Also see
__thp_get_unmapped_area()processed such pgoff, it allocates VA withlen_pad(not len), and pad the retval at last.Please let me know if it didn't work like it, then it might be a bug.
It should all be documented then in the kdoc for the new ops, in this kind of language that the resulting VA flows from pgoff
IMHO that's one of the major benefits of this API, so that there's no need to mention impl details like this.
I thought that's also what you wanted as well.. as you're further suggesting to offload order adjustments to core mm, which I tend to agree.
Here the point is, the driver should only care about the size of mapping, nothing else like how exactly the alignments will be calculated, and how that interacts with pgoff. The kernel mm manages that. It's done exactly like what anon thp does already when len is pmd aligned.
Or maybe I misunderstood what you're suggesting to document? If so, please let me know; some example would be greatly helpful.
Thanks,
Signature · 1 line
Peter Xu
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 5 lines · Peter Xu
Quoted 4 lines · Jason Gunthorpe
Quoted 3 lines · Peter Xu
Also see
__thp_get_unmapped_area()processed such pgoff, it allocates VA withlen_pad(not len), and pad the retval at last.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
Please let me know if it didn't work like it, then it might be a bug.
It should all be documented then in the kdoc for the new ops, in this kind of language that the resulting VA flows from pgoff
IMHO that's one of the major benefits of this API, so that there's no need to mention impl details like this.
It needs to be clearly explained exactly how pgoff and the returned order are related because it impacts how the drivers need to manage their pgoff space.
Quoted 4 lines
Here the point is, the driver should only care about the size of mapping, nothing else like how exactly the alignments will be calculated, and how that interacts with pgoff. The kernel mm manages that. It's done exactly like what anon thp does already when len is pmd aligned.
The driver owns the pgoff number space, it has to care about how that relates to the PTEs.
Quoted 2 lines
Or maybe I misunderstood what you're suggesting to document? If so, please let me know; some example would be greatly helpful.
Just document the 'VA % order = pgoff % order' equation in the kdoc for the new op.
Jason
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 11 lines · Jason Gunthorpe
Quoted 10 lines · Peter Xu
Quoted 8 lines · Jason Gunthorpe
Quoted 4 lines · Peter Xu
Also see
__thp_get_unmapped_area()processed such pgoff, it allocates VA withlen_pad(not len), and pad the retval at last.Please let me know if it didn't work like it, then it might be a bug.
It should all be documented then in the kdoc for the new ops, in this kind of language that the resulting VA flows from pgoff
Quoted 6 lines
Quoted 2 lines
IMHO that's one of the major benefits of this API, so that there's no need to mention impl details like this.
It needs to be clearly explained exactly how pgoff and the returned order are related because it impacts how the drivers need to manage their pgoff space.
Here "pgoff" plays two roles:
(1) as a range, (pgoff, len) on top of the fd, decides which device blob to be mapped. This is relevant to the driver, for sure..
(2) as an offset, pgoff is relevant when we want to make sure mmap() request's VA will be aligned in a way so that we can maximize huge mappings. This has, IMHO, nothing to do with the driver, and that's what I want to make the new API transparent of.
I agree drivers need to know pgoff for (1) in terms of get_mapping_order(), not (2).
Quoted 6 lines
Quoted 5 lines
Here the point is, the driver should only care about the size of mapping, nothing else like how exactly the alignments will be calculated, and how that interacts with pgoff. The kernel mm manages that. It's done exactly like what anon thp does already when len is pmd aligned.
Quoted 8 lines
The driver owns the pgoff number space, it has to care about how that relates to the PTEs.
Quoted 2 lines
Or maybe I misunderstood what you're suggesting to document? If so, please let me know; some example would be greatly helpful.
Just document the 'VA % order = pgoff % order' equation in the kdoc for the new op.
When it's "related to PTEs", it's talking about (2) above, so that's really what I want to avoid mentioning.
Docuemnt anything about VA is just confusing on its own especially when "int get_mapping_order(fd, pgoff, len)" doesn't even have anything in param or retval that is relevant to the virtual address space..
If you think missing such info is harder for reviews, I can definitely add a rich comment when repost explaining how __thp_get_unmapped_area() works here.
We can also pause this a bit and wait for Matthew's review on the API, where he showed concerns. If there's major reason this API is rejected, we don't need to bother this part of detail either.
Thanks,
Signature · 1 line
Peter Xu
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 8 lines · Peter Xu
Quoted 5 lines
Quoted 2 lines
Or maybe I misunderstood what you're suggesting to document? If so, please let me know; some example would be greatly helpful.
Just document the 'VA % order = pgoff % order' equation in the kdoc for the new op.
When it's "related to PTEs", it's talking about (2) above, so that's really what I want to avoid mentioning.
You can't avoid it. Drivers must ensure that
pgoff % order == physical % order
And that is something only drivers can do by knowing about this requirement.
Jason
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 10 lines · Jason Gunthorpe
Quoted 8 lines · Peter Xu
Quoted 5 lines
Quoted 2 lines
Or maybe I misunderstood what you're suggesting to document? If so, please let me know; some example would be greatly helpful.
Just document the 'VA % order = pgoff % order' equation in the kdoc for the new op.
When it's "related to PTEs", it's talking about (2) above, so that's really what I want to avoid mentioning.
Quoted 6 lines
You can't avoid it. Drivers must ensure that
pgoff % order == physical % order
And that is something only drivers can do by knowing about this requirement.
This is a current limitation that above must be guaranteed, there's not much the driver can do, IMHO.
If you could remember, that's the only reason why I used to suggest (while we were discussing this in v1) to make it *pgoff instead of pgoff, so that drivers can change *pgoff to make it relevant to HPA.
I didn't take that approach as I want to make this simple until it's justified to be required.
It holds true for vfio-pci, I hope it holds true forever. If not, this API will stop working, afaict.
Signature · 1 line
Peter Xu
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 13 lines · Peter Xu
Quoted 12 lines · Jason Gunthorpe
Quoted 8 lines · Peter Xu
Quoted 5 lines
Quoted 2 lines
Or maybe I misunderstood what you're suggesting to document? If so, please let me know; some example would be greatly helpful.
Just document the 'VA % order = pgoff % order' equation in the kdoc for the new op.
When it's "related to PTEs", it's talking about (2) above, so that's really what I want to avoid mentioning.
You can't avoid it. Drivers must ensure that
Quoted 7 lines
Quoted 4 lines
pgoff % order == physical % order
And that is something only drivers can do by knowing about this requirement.
This is a current limitation that above must be guaranteed, there's not much the driver can do, IMHO.
There is alot the driver can do! The driver decides on the pgoff values it is using, it needs to keep the above in mind when it builds its pgoff number space!
Quoted 3 lines
If you could remember, that's the only reason why I used to suggest (while we were discussing this in v1) to make it *pgoff instead of pgoff, so that drivers can change *pgoff to make it relevant to HPA.
What? That's nonsense. The pgoff space is assigned by the driver and needs to remain a fixed relationship to the underlying phys the driver is mapping in. It shouldn't be changing pgoff during mmap!
Jason
Re: [PATCH v2 2/4] mm: Add file_operations.get_mapping_order()
Quoted 19 lines · Jason Gunthorpe
Quoted 18 lines · Peter Xu
Quoted 16 lines · Jason Gunthorpe
Quoted 8 lines · Peter Xu
Quoted 5 lines
Quoted 2 lines
Or maybe I misunderstood what you're suggesting to document? If so, please let me know; some example would be greatly helpful.
Just document the 'VA % order = pgoff % order' equation in the kdoc for the new op.
When it's "related to PTEs", it's talking about (2) above, so that's really what I want to avoid mentioning.
You can't avoid it. Drivers must ensure that
pgoff % order == physical % order
And that is something only drivers can do by knowing about this requirement.
Quoted 6 lines
Quoted 2 lines
This is a current limitation that above must be guaranteed, there's not much the driver can do, IMHO.
There is alot the driver can do! The driver decides on the pgoff values it is using, it needs to keep the above in mind when it builds its pgoff number space!
Yeah, if so, it's reassuring. :)
Quoted 8 lines
Quoted 4 lines
If you could remember, that's the only reason why I used to suggest (while we were discussing this in v1) to make it *pgoff instead of pgoff, so that drivers can change *pgoff to make it relevant to HPA.
What? That's nonsense. The pgoff space is assigned by the driver and needs to remain a fixed relationship to the underlying phys the driver is mapping in. It shouldn't be changing pgoff during mmap!
I meant, return *pgoff as a hint, not changing the pgoff to be used.. Only changing the pgoff (as an integer) to be used in the VA calculations.
Thanks for sharing above information to ease my mind, if drivers are all smart enough (I'll trust you more than myself on driver knowledges!) I think we're all good..
Signature · 1 line
Peter Xu
PATCH v2 3/4 vfio: Introduce vfio_device_ops.get_mapping_order hook
In reply to Peter XuAdd a hook to vfio_device_ops to allow sub-modules provide mapping order hint for an mmap() request. When not available, use the default value (0).
Note that this patch will change the code path for vfio on mmap() when allocating the virtual address range to be mapped, however it should not change the result of the VA allocated, because the default value (0) should be the old behavior.
--- drivers/vfio/vfio_main.c | 14 ++++++++++++++ include/linux/vfio.h | 5 +++++ 2 files changed, 19 insertions(+)
drivers/vfio/vfio_main.c +14 -0
@@ -1372,6 +1372,19 @@ static void vfio_device_show_fdinfo(struct seq_file *m, struct file *filep) }#endif +static int vfio_device_get_mapping_order (struct file *file, +unsigned long pgoff, +size_t len) +{ +struct vfio_device_file *df = file->private_data; +struct vfio_device *device = df->device; + +if (device->ops->get_mapping_order) +return device->ops->get_mapping_order (device, pgoff, len); + +return 0 ; +} +const struct file_operations vfio_device_fops = { .owner =THIS_MODULE , .open = vfio_device_fops_cdev_open,
@@ -1384,6 +1397,7 @@ const struct file_operations vfio_device_fops = {#ifdef CONFIG_PROC_FS .show_fdinfo = vfio_device_show_fdinfo, #endif + .get_mapping_order = vfio_device_get_mapping_order, };static struct vfio_device *vfio_device_from_file (struct file *file)
include/linux/vfio.h +5 -0
@@ -111,6 +111,8 @@ struct vfio_device {* @dma_unmap: Called when userspace unmaps IOVA from the container * this device is attached to. * @device_feature: Optional, fill in the VFIO_DEVICE_FEATURE ioctl +* @get_mapping_order: Optional, provide mapping order hints for mmap(). +* When unavailable, use the default order (zero). */ struct vfio_device_ops {char *name;
@@ -139,6 +141,9 @@ 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); +int (*get_mapping_order)(struct vfio_device *device, +unsigned long pgoff, +size_t len); };#if IS_ENABLED (CONFIG_IOMMUFD )
Signature · 1 line
2.50.1
PATCH v2 4/4 vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
In reply to Peter XuThis patch enables best-effort mmap() for vfio-pci bars even without MAP_FIXED, so as to utilize huge pfnmaps as much as possible. It should also avoid userspace changes (switching to MAP_FIXED with pre-aligned VA addresses) to start enabling huge pfnmaps on VFIO bars.
Here the trick is making sure the MMIO PFNs will be aligned with the VAs allocated from mmap() when !MAP_FIXED, so that whatever returned from mmap(!MAP_FIXED) of vfio-pci MMIO regions will be automatically suitable for huge pfnmaps as much as possible.
To achieve that, a custom vfio_device's get_mapping_hint() for vfio-pci devices is needed.
Note that BAR's MMIO physical addresses should normally be guaranteed to be BAR-size aligned. It means the MMIO address will also always be aligned with vfio-pci's file offset address space, per VFIO_PCI_OFFSET_SHIFT.
With that guaranteed, VA allocator can calculate the alignment with pgoff, which will be further aligned with the MMIO physical addresses to be mapped in the VMA later.
So far, stick with the simple plan to rely on the hardware assumption that should always be true. Leave it for later if pgoff needs adjustments when there's a real demand of it when calculating the alignment.
For discussion on the requirement of this feature, see:
https://lore.kernel.org/linux-pci/[email protected]/
--- drivers/vfio/pci/vfio_pci.c | 1 + drivers/vfio/pci/vfio_pci_core.c | 49 ++++++++++++++++++++++++++++++++ include/linux/vfio_pci_core.h | 2 ++ 3 files changed, 52 insertions(+)
drivers/vfio/pci/vfio_pci.c +1 -0
@@ -145,6 +145,7 @@ static const struct vfio_device_ops vfio_pci_ops = { .detach_ioas = vfio_iommufd_physical_detach_ioas, .pasid_attach_ioas = vfio_iommufd_physical_pasid_attach_ioas, .pasid_detach_ioas = vfio_iommufd_physical_pasid_detach_ioas, + .get_mapping_order = vfio_pci_core_get_mapping_order, };static int vfio_pci_probe (struct pci_dev *pdev,const struct pci_device_id *id)
drivers/vfio/pci/vfio_pci_core.c +49 -0
55 lines not on this page · raw message
include/linux/vfio_pci_core.h +2 -0
@@ -119,6 +119,8 @@ ssize_t vfio_pci_core_read(struct vfio_device *core_vdev, char __user *buf, size_t count, loff_t *ppos);ssize_t vfio_pci_core_write (struct vfio_device *core_vdev,const char __user *buf,size_t count,loff_t *ppos); +int vfio_pci_core_get_mapping_order (struct vfio_device *device, +unsigned long pgoff,size_t len);int vfio_pci_core_mmap (struct vfio_device *core_vdev,struct vm_area_struct *vma);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);
Signature · 1 line
2.50.1
kernel test robot
build botRe: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
kernel test robot noticed the following build warnings:
Hi Peter,
kernel test robot noticed the following build warnings:
[auto build test WARNING on awilliam-vfio/for-linus]
[also build test WARNING on linus/master v6.18]
[cannot apply to akpm-mm/mm-everything awilliam-vfio/next brauner-vfs/vfs.all next-20251204] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Peter-Xu/mm-thp-Allow-thp_get_unmapped_area_vmflags-to-take-alignment/20251204-231258 base: https://github.com/awilliam/linux-vfio.git for-linus patch link: https://lore.kernel.org/r/20251204151003.171039-5-peterx%40redhat.com patch subject: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings config: i386-buildonly-randconfig-004-20251205 (https://download.01.org/0day-ci/archive/20251205/[email protected]/config) compiler: gcc-14 (Debian 14.2.0-19) 14.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251205/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
drivers/vfio/pci/vfio_pci_core.c: In function 'vfio_pci_core_get_mapping_order':
>> drivers/vfio/pci/vfio_pci_core.c:1670:51: warning: left shift count >= width of type [-Wshift-count-overflow]
1670 | req_start = (pgoff << PAGE_SHIFT) & ((1UL << VFIO_PCI_OFFSET_SHIFT) - 1);
| ^~vim +1670 drivers/vfio/pci/vfio_pci_core.c
1642
1643 /*
1644 * Hint function for mmap() about the size of mapping to be carried out.
1645 * This helps to enable huge pfnmaps as much as possible on BAR mappings.
1646 *
1647 * This function does the minimum check on mmap() parameters to make the
1648 * hint valid only. The majority of mmap() sanity check will be done later
1649 * in mmap().
1650 */
1651 int vfio_pci_core_get_mapping_order(struct vfio_device *device,
1652 unsigned long pgoff, size_t len)
1653 {
1654 struct vfio_pci_core_device *vdev =
1655 container_of(device, struct vfio_pci_core_device, vdev);
1656 struct pci_dev *pdev = vdev->pdev;
1657 unsigned int index = pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1658 unsigned long req_start;
1659 size_t phys_len;
1660
1661 /* Currently, only bars 0-5 supports huge pfnmap */
1662 if (index >= VFIO_PCI_ROM_REGION_INDEX)
1663 return 0;
1664
1665 /*
1666 * NOTE: we're keeping things simple as of now, assuming the
1667 * physical address of BARs (aka, pci_resource_start(pdev, index))
1668 * should always be aligned with pgoff in vfio-pci's address space.
1669 */
> 1670 req_start = (pgoff << PAGE_SHIFT) & ((1UL << VFIO_PCI_OFFSET_SHIFT) - 1);
1671 phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1672
1673 /*
1674 * If this happens, it will probably fail mmap() later.. mapping
1675 * hint isn't important anymore.
1676 */
1677 if (req_start >= phys_len)
1678 return 0;
1679
1680 phys_len = MIN(phys_len - req_start, len);
1681
1682 if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PUD_PFNMAP) && phys_len >= PUD_SIZE)
1683 return PUD_ORDER;
1684
1685 if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP) && phys_len >= PMD_SIZE)
1686 return PMD_ORDER;
1687
1688 return 0;
1689 }
1690 EXPORT_SYMBOL_GPL(vfio_pci_core_get_mapping_order);
1691
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
kernel test robot
build botRe: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
In reply to Peter Xukernel test robot noticed the following build warnings:
Hi Peter,
kernel test robot noticed the following build warnings:
[auto build test WARNING on awilliam-vfio/for-linus]
[also build test WARNING on v6.18]
[cannot apply to akpm-mm/mm-everything awilliam-vfio/next brauner-vfs/vfs.all linus/master next-20251205] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Peter-Xu/mm-thp-Allow-thp_get_unmapped_area_vmflags-to-take-alignment/20251204-231258 base: https://github.com/awilliam/linux-vfio.git for-linus patch link: https://lore.kernel.org/r/20251204151003.171039-5-peterx%40redhat.com patch subject: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings config: i386-randconfig-006-20251205 (https://download.01.org/0day-ci/archive/20251205/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251205/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> drivers/vfio/pci/vfio_pci_core.c:1670:44: warning: shift count >= width of type [-Wshift-count-overflow]
1670 | req_start = (pgoff << PAGE_SHIFT) & ((1UL << VFIO_PCI_OFFSET_SHIFT) - 1);
| ^ ~~~~~~~~~~~~~~~~~~~~~1 warning generated.
vim +1670 drivers/vfio/pci/vfio_pci_core.c
1642
1643 /*
1644 * Hint function for mmap() about the size of mapping to be carried out.
1645 * This helps to enable huge pfnmaps as much as possible on BAR mappings.
1646 *
1647 * This function does the minimum check on mmap() parameters to make the
1648 * hint valid only. The majority of mmap() sanity check will be done later
1649 * in mmap().
1650 */
1651 int vfio_pci_core_get_mapping_order(struct vfio_device *device,
1652 unsigned long pgoff, size_t len)
1653 {
1654 struct vfio_pci_core_device *vdev =
1655 container_of(device, struct vfio_pci_core_device, vdev);
1656 struct pci_dev *pdev = vdev->pdev;
1657 unsigned int index = pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1658 unsigned long req_start;
1659 size_t phys_len;
1660
1661 /* Currently, only bars 0-5 supports huge pfnmap */
1662 if (index >= VFIO_PCI_ROM_REGION_INDEX)
1663 return 0;
1664
1665 /*
1666 * NOTE: we're keeping things simple as of now, assuming the
1667 * physical address of BARs (aka, pci_resource_start(pdev, index))
1668 * should always be aligned with pgoff in vfio-pci's address space.
1669 */
> 1670 req_start = (pgoff << PAGE_SHIFT) & ((1UL << VFIO_PCI_OFFSET_SHIFT) - 1);
1671 phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1672
1673 /*
1674 * If this happens, it will probably fail mmap() later.. mapping
1675 * hint isn't important anymore.
1676 */
1677 if (req_start >= phys_len)
1678 return 0;
1679
1680 phys_len = MIN(phys_len - req_start, len);
1681
1682 if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PUD_PFNMAP) && phys_len >= PUD_SIZE)
1683 return PUD_ORDER;
1684
1685 if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP) && phys_len >= PMD_SIZE)
1686 return PMD_ORDER;
1687
1688 return 0;
1689 }
1690 EXPORT_SYMBOL_GPL(vfio_pci_core_get_mapping_order);
1691
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Re: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
In reply to Peter XuQuoted 35 lines · Peter Xu
drivers/vfio/pci/vfio_pci_core.c +35
-0+/* +* Hint function for mmap() about the size of mapping to be carried out. +* This helps to enable huge pfnmaps as much as possible on BAR mappings. +* +* This function does the minimum check on mmap() parameters to make the +* hint valid only. The majority of mmap() sanity check will be done later +* in mmap(). +*/ +int vfio_pci_core_get_mapping_order (struct vfio_device *device, +unsigned long pgoff,size_t len) +{ +struct vfio_pci_core_device *vdev = + container_of(device, struct vfio_pci_core_device, vdev); +struct pci_dev *pdev = vdev->pdev; +unsigned int index = pgoff >> (VFIO_PCI_OFFSET_SHIFT -PAGE_SHIFT ); +unsigned long req_start; +size_t phys_len; + +/* Currently, only bars 0-5 supports huge pfnmap */ +if (index >=VFIO_PCI_ROM_REGION_INDEX ) +return 0 ; + +/* +* NOTE: we're keeping things simple as of now, assuming the +* physical address of BARs (aka, pci_resource_start(pdev, index)) +* should always be aligned with pgoff in vfio-pci's address space. +*/ + req_start = (pgoff <<PAGE_SHIFT ) & ((1UL <<VFIO_PCI_OFFSET_SHIFT ) -1 ); + phys_len =PAGE_ALIGN (pci_resource_len (pdev, index)); + +/* +* If this happens, it will probably fail mmap() later.. mapping +* hint isn't important anymore. +*/ +if (req_start >= phys_len)
drivers/vfio/pci/vfio_pci_core.c static unsigned long vma_to_pfn(struct vm_area_struct *vma) · line 1687
Quoted 10 lines
drivers/vfio/pci/vfio_pci_core.c +10
-0+return 0 ; + + phys_len =MIN (phys_len - req_start, len); + +if (IS_ENABLED (CONFIG_ARCH_SUPPORTS_PUD_PFNMAP ) && phys_len >=PUD_SIZE ) +return PUD_ORDER ; + +if (IS_ENABLED (CONFIG_ARCH_SUPPORTS_PMD_PFNMAP ) && phys_len >=PMD_SIZE ) +return PMD_ORDER ; +
This seems a bit weird, the vma length is already known, it is len, why do we go to all this trouble to recalculate len in terms of phys?
If the length is wrong the mmap will fail, so there is no issue with returning a larger order here.
I feel this should just return the order based on pci_resource_len()?
And shouldn't the mm be the one aligning it to what the arch can do not drives?
Jason
Re: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
Quoted 51 lines · Jason Gunthorpe
Quoted 35 lines · Peter Xu
drivers/vfio/pci/vfio_pci_core.c +35
-0+/* +* Hint function for mmap() about the size of mapping to be carried out. +* This helps to enable huge pfnmaps as much as possible on BAR mappings. +* +* This function does the minimum check on mmap() parameters to make the +* hint valid only. The majority of mmap() sanity check will be done later +* in mmap(). +*/ +int vfio_pci_core_get_mapping_order (struct vfio_device *device, +unsigned long pgoff,size_t len) +{ +struct vfio_pci_core_device *vdev = + container_of(device, struct vfio_pci_core_device, vdev); +struct pci_dev *pdev = vdev->pdev; +unsigned int index = pgoff >> (VFIO_PCI_OFFSET_SHIFT -PAGE_SHIFT ); +unsigned long req_start; +size_t phys_len; + +/* Currently, only bars 0-5 supports huge pfnmap */ +if (index >=VFIO_PCI_ROM_REGION_INDEX ) +return 0 ; + +/* +* NOTE: we're keeping things simple as of now, assuming the +* physical address of BARs (aka, pci_resource_start(pdev, index)) +* should always be aligned with pgoff in vfio-pci's address space. +*/ + req_start = (pgoff <<PAGE_SHIFT ) & ((1UL <<VFIO_PCI_OFFSET_SHIFT ) -1 ); + phys_len =PAGE_ALIGN (pci_resource_len (pdev, index)); + +/* +* If this happens, it will probably fail mmap() later.. mapping +* hint isn't important anymore. +*/ +if (req_start >= phys_len)drivers/vfio/pci/vfio_pci_core.c static unsigned long vma_to_pfn(struct vm_area_struct *vma) · line 1687
Quoted 10 lines
drivers/vfio/pci/vfio_pci_core.c +10
-0+return 0 ; + + phys_len =MIN (phys_len - req_start, len); + +if (IS_ENABLED (CONFIG_ARCH_SUPPORTS_PUD_PFNMAP ) && phys_len >=PUD_SIZE ) +return PUD_ORDER ; + +if (IS_ENABLED (CONFIG_ARCH_SUPPORTS_PMD_PFNMAP ) && phys_len >=PMD_SIZE ) +return PMD_ORDER ; +This seems a bit weird, the vma length is already known, it is len, why do we go to all this trouble to recalculate len in terms of phys?
Quoted 4 lines
If the length is wrong the mmap will fail, so there is no issue with returning a larger order here.
I feel this should just return the order based on
pci_resource_len()?
IIUC there's a trivial difference when partial of a huge bar is mapped.
Example: 1G bar, map range (pgoff=2M, size=1G-2M).
If we return bar size order, we'd say 1G, however then it means we'll do the alignment with 1G. __thp_get_unmapped_area() will think it's not proper, because:
loff_t off_end = off + len; loff_t off_align = round_up(off, size); if (off_end <= off_align || (off_end - off_align) < size) return 0;
Here what we really want is to map (2M, 1G-2M) with 2M huge, not 1G, nor 4K.
Quoted 3 lines
And shouldn't the mm be the one aligning it to what the arch can do not drives?
Note that here checking CONFIG_ARCH_SUPPORTS_P*D_PFNMAP is a vfio behavior, pairing with the huge_fault() of vfio-pci driver. It implies if vfio-pci's huge pfnmap is enabled or not. If it's not enabled, we don't need to report larger orders here.
Said that, this is still a valid point, that core mm should likely also check against the configs when the kernel was built, though it should not check against CONFIG_ARCH_SUPPORTS_PMD_PFNMAP.. Instead, it should check HAVE_ARCH_TRANSPARENT_HUGEPAGE*.
But then... I really want to avoid adding more dependencies to THPs in core mm on pfnmaps. I used to decouple THP and huge mappings, that series wasn't going anywhere, but adding these checks will add more dependencies..
Shall I keep it simple to leave it to drivers, until we have something more solid (I think we need HAVE_ARCH_HUGE_P*D_LEAVES here)?
Even with that config ready, drivers should always still do proper check on its own (drivers need to support huge pfnmaps here first before reporting high orders). So what I can add into core mm to check arch support would only be an extra layer of safety net, not much real help but burn some cpu cycles, IMHO...
Thanks,
Signature · 1 line
Peter Xu
Re: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
Quoted 16 lines · Peter Xu
Quoted 7 lines
This seems a bit weird, the vma length is already known, it is len, why do we go to all this trouble to recalculate len in terms of phys?
If the length is wrong the mmap will fail, so there is no issue with returning a larger order here.
I feel this should just return the order based on
pci_resource_len()?IIUC there's a trivial difference when partial of a huge bar is mapped.
Example: 1G bar, map range (pgoff=2M, size=1G-2M).
If we return bar size order, we'd say 1G, however then it means we'll do the alignment with 1G.
__thp_get_unmapped_area()will think it's not proper, because:
Quoted 8 lines
loff_t off_end = off + len; loff_t off_align = round_up(off, size); if (off_end <= off_align || (off_end - off_align) < size) return 0;Here what we really want is to map (2M, 1G-2M) with 2M huge, not 1G, nor 4K.
This was the point of my prior email, the alignment calculation can't just be 'align to a size'. The core code needs to choose a VA such that:
VA % (1 << order) == pg_off % (1 << order)
So if VFIO returns 1G then the VA should be aligned to 2M within a 1G region. This allows opportunities to increase the alignment as the mapping continues, eg if the arch supports a 32M 16x2M contiguous page then we'd get 32M mappings with your example.
The core code should adjust the target order from the driver by:
lowest of order or size rounded down to a power of two
then
highest arch supported leaf size below the above
None of this logic should be in drivers.
The way to think about this is that the driver is returning an order which indicates the maximum case where:
VA % (1 << order) == pg_off % (1 << order)
Could be true. Eg a PCI BAR returns an order that is the size of the BAR because it is always true. Something that stores at most 1G pages would return 1G pages, etc.
Quoted 4 lines
Note that here checking CONFIG_ARCH_SUPPORTS_P*D_PFNMAP is a vfio behavior, pairing with the
huge_fault()of vfio-pci driver. It implies if vfio-pci's huge pfnmap is enabled or not. If it's not enabled, we don't need to report larger orders here.
Honestly, I'd ignore this, and I'm not sure VFIO should be testing those in the huge_fault either. Again the core code should deal with it.
Quoted 2 lines
Shall I keep it simple to leave it to drivers, until we have something more solid (I think we need HAVE_ARCH_HUGE_P*D_LEAVES here)?
Logic like this should not be in drivers.
Quoted 3 lines
Even with that config ready, drivers should always still do proper check on its own (drivers need to support huge pfnmaps here first before reporting high orders).
Drivers shouldn't implement this alignment function without also implementing huge fault, it is pointless. Don't see a reason to add extra complexity.
Jason
Re: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
Quoted 23 lines · Jason Gunthorpe
Quoted 22 lines · Peter Xu
Quoted 7 lines
This seems a bit weird, the vma length is already known, it is len, why do we go to all this trouble to recalculate len in terms of phys?
If the length is wrong the mmap will fail, so there is no issue with returning a larger order here.
I feel this should just return the order based on
pci_resource_len()?IIUC there's a trivial difference when partial of a huge bar is mapped.
Example: 1G bar, map range (pgoff=2M, size=1G-2M).
If we return bar size order, we'd say 1G, however then it means we'll do the alignment with 1G.
__thp_get_unmapped_area()will think it's not proper, because:loff_t off_end = off + len; loff_t off_align = round_up(off, size); if (off_end <= off_align || (off_end - off_align) < size) return 0;
Quoted 6 lines
Quoted 2 lines
Here what we really want is to map (2M, 1G-2M) with 2M huge, not 1G, nor 4K.
This was the point of my prior email, the alignment calculation can't just be 'align to a size'. The core code needs to choose a VA such that:
IMHO these are two different things we're discussing here. I've replied in the other email about pgoff alignments, I think it's properly done, let's keep the discussion there. I'll reply to the other issue raised.
Quoted 8 lines
VA % (1 << order) == pg_off % (1 << order)So if VFIO returns 1G then the VA should be aligned to 2M within a 1G region. This allows opportunities to increase the alignment as the mapping continues, eg if the arch supports a 32M 16x2M contiguous page then we'd get 32M mappings with your example.
Quoted 4 lines
The core code should adjust the target order from the driver by:
lowest of order or size rounded down to a power of two
then
highest arch supported leaf size below the above
Yes, maybe this would be better.
E.g. I would expect if a driver has 32M returned (order=13), then on x86_64 it should be adjusted to 2M (order=9), but on a 4K pgsize arm64 it should be kept as 32M (order=13) as it matches contpmds.
Do we have any function that we can fetch the best mapping lower than a specific order?
Quoted 2 lines
None of this logic should be in drivers.
I still think it's the driver's decision to have its own macro controlling the huge pfnmap behavior. I agree with you core mm can have it, I don't see it blocks the driver not returning huge order if huge pfnmap is turned off. VFIO-PCI currently indeed only depends directly on global THP configs, but I don't see why it's strictly needed. So I think it's fine if a driver (even if global THP enabled for pmd/pud) deselect huge pfnmap for other reasons, then here the order returned can still always be PSIZE for the driver. It's really not a huge deal to me.
Quoted 24 lines
The way to think about this is that the driver is returning an order which indicates the maximum case where:
VA % (1 << order) == pg_off % (1 << order)Could be true. Eg a PCI BAR returns an order that is the size of the BAR because it is always true. Something that stores at most 1G pages would return 1G pages, etc.
Quoted 4 lines
Note that here checking CONFIG_ARCH_SUPPORTS_P*D_PFNMAP is a vfio behavior, pairing with the
huge_fault()of vfio-pci driver. It implies if vfio-pci's huge pfnmap is enabled or not. If it's not enabled, we don't need to report larger orders here.Honestly, I'd ignore this, and I'm not sure VFIO should be testing those in the
huge_faulteither. Again the core code should deal with it.Quoted 2 lines
Shall I keep it simple to leave it to drivers, until we have something more solid (I think we need HAVE_ARCH_HUGE_P*D_LEAVES here)?
Logic like this should not be in drivers.
Quoted 7 lines
Quoted 3 lines
Even with that config ready, drivers should always still do proper check on its own (drivers need to support huge pfnmaps here first before reporting high orders).
Drivers shouldn't implement this alignment function without also implementing huge fault, it is pointless. Don't see a reason to add extra complexity.
It's not implementing the order hint without huge fault. It's when both are turned off in a kernel config.. then the order hint (even from driver POV) shouldn't need to be reported.
I don't know why you have so strong feeling on having a config check in vfio-pci drivers is bad. I still think it's good to have it pairing with the same macro in huge_fault(), because it's essentially part of the whole pfnmap feature so it's fair they're guarded by the same kernel config, but I'm ok either way in case of current case of vfio-pci where it 100% depends on global THP setups.
Signature · 1 line
Peter Xu
Re: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
Quoted 2 lines · Peter Xu
Do we have any function that we can fetch the best mapping lower than a specific order?
I'm not aware of anything
Quoted 10 lines
Quoted 1 line
None of this logic should be in drivers.
I still think it's the driver's decision to have its own macro controlling the huge pfnmap behavior. I agree with you core mm can have it, I don't see it blocks the driver not returning huge order if huge pfnmap is turned off. VFIO-PCI currently indeed only depends directly on global THP configs, but I don't see why it's strictly needed. So I think it's fine if a driver (even if global THP enabled for pmd/pud) deselect huge pfnmap for other reasons, then here the order returned can still always be PSIZE for the driver. It's really not a huge deal to me.
All these APIs should be around the idea that the driver just returns what it has and the core mm places it into ptes. There is not a good reason drivers should be overriding this logic or doing their own thing.
Quoted 7 lines
Quoted 3 lines
Drivers shouldn't implement this alignment function without also implementing huge fault, it is pointless. Don't see a reason to add extra complexity.
It's not implementing the order hint without huge fault. It's when both are turned off in a kernel config.. then the order hint (even from driver POV) shouldn't need to be reported.
No, it should still all be the same the core code just won't call the function.
Quoted 2 lines
I don't know why you have so strong feeling on having a config check in vfio-pci drivers is bad.
It is leaking MM details into drivers that should not be in drivers.
Quoted 2 lines
I still think it's good to have it pairing with the same macro in
huge_fault(),
It should not be there either.
Jason
Re: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
Quoted 5 lines · Jason Gunthorpe
Quoted 2 lines · Peter Xu
Do we have any function that we can fetch the best mapping lower than a specific order?
I'm not aware of anything
Maybe I can introduce a per-arch helper for it, then. I'll see if I can cover some tests from ARM side, or I'll enable x86_64 first so we can do it in two steps.
Quoted 12 lines
Quoted 11 lines
Quoted 2 lines
None of this logic should be in drivers.
I still think it's the driver's decision to have its own macro controlling the huge pfnmap behavior. I agree with you core mm can have it, I don't see it blocks the driver not returning huge order if huge pfnmap is turned off. VFIO-PCI currently indeed only depends directly on global THP configs, but I don't see why it's strictly needed. So I think it's fine if a driver (even if global THP enabled for pmd/pud) deselect huge pfnmap for other reasons, then here the order returned can still always be PSIZE for the driver. It's really not a huge deal to me.
Quoted 4 lines
All these APIs should be around the idea that the driver just returns what it has and the core mm places it into ptes. There is not a good reason drivers should be overriding this logic or doing their own thing.
I'll make sure the driver will not need to consider size of mapping that arch would support.
Quoted 9 lines
Quoted 8 lines
Quoted 4 lines
Drivers shouldn't implement this alignment function without also implementing huge fault, it is pointless. Don't see a reason to add extra complexity.
It's not implementing the order hint without huge fault. It's when both are turned off in a kernel config.. then the order hint (even from driver POV) shouldn't need to be reported.
Quoted 7 lines
No, it should still all be the same the core code just won't call the function.
Quoted 2 lines
I don't know why you have so strong feeling on having a config check in vfio-pci drivers is bad.
It is leaking MM details into drivers that should not be in drivers.
To me it still makes perfect sense here to pair with huge_fault(), and it's driver knowledge alone. It has nothing to do with leaking mm details.
I think I get your point above, maybe when the core mm fallback paths not available yet we can mix things together. I'll see what I can do when repost.
Signature · 1 line
Peter Xu
Re: [PATCH v2 4/4] vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappings
In reply to Peter XuQuoted 2 lines · Peter Xu
To achieve that, a custom vfio_device's
get_mapping_hint()for vfio-pci devices is needed.
nit get_mapping_order()
Quoted 48 lines · Peter Xu
This series is based on v6.18. It allows
mmap(!MAP_FIXED)to work with huge pfnmaps with best effort. Meanwhile, it enables it for vfio-pci as the first user.v1: https://lore.kernel.org/r/[email protected]
A changelog may not apply because all the patches were rewrote based on a new interface this v2 introduced. Hence omitted.
In this version, a new file operation,
get_mapping_order(), is introduced (based on discussion with Jason on v1) to minimize the code needed for drivers to implement this. It also helps avoid exporting any mm functions. One can refer to the discussion in v1 for more information.Currently,
get_mapping_order()API is define as:int (*get_mapping_order)(struct file *file, unsigned long pgoff, size_t len);The first argument is the file pointer, the 2nd+3rd are the pgoff+len specified from a
mmap()request. The driver can use this interface to opt-in providing mapping order hints to core mm on VA allocations for the range of the file specified. I kept the interface as simple for now, so that core mm will always do the alignment with pgoff assuming that would always work. The driver can only report the order from pgoff+len, which will be used to do the alignment.Before this series, an userapp in most cases need to be modified to benefit from huge mappings to provide huge size aligned VA using
MAP_FIXED. After this series, the userapp can benefit from huge pfnmap automatically after the kernel upgrades, with no userspace modifications.It's still best-effort, because the auto-alignment will require a larger VA range to be allocated via the per-arch allocator, hence if the huge-mapping aligned VA cannot be allocated then it'll still fallback to small mappings like before. However that's from theory POV: in reality I don't yet know when it'll fail especially when on a 64bits system.
So far, only vfio-pci is supported. But the logic should be applicable to all the drivers that support or will support huge pfnmaps. I've copied some more people in this version too from hardware perspective.
For testings:
- checkpatch.pl
- cross build harness
- unit test that I got from Alex [1], checkingmmap()alignments on a QEMU instance with an 128MB bar.
Quoted 5 lines
Checking the alignments look all sane with
mmap(!MAP_FIXED), and huge mappings properly installed. I didn't observe anything wrong.I currently lack larger bars to test PUD sizes. Please kindly report if one can run this with 1G+ bars and hit issues.
LGTM, with a 32G BAR :
Using device 0000:02:00.0 in IOMMU group 27
Device 0000:02:00.0 supports 9 regions, 5 irqs
[BAR0]: size 0x1000000, order 24, offset 0x0, flags 0xf Testing BAR0, require at least 21 bit alignment
[PASS] Minimum alignment 21
Testing random offset
[PASS] Random offset
Testing random size
[PASS] Random size
[BAR1]: size 0x800000000, order 35, offset 0x10000000000, flags 0x7 Testing BAR1, require at least 30 bit alignment
[PASS] Minimum alignment 31
Testing random offset
[PASS] Random offset
Testing random size
[PASS] Random size
[BAR3]: size 0x2000000, order 25, offset 0x30000000000, flags 0x7 Testing BAR3, require at least 21 bit alignment
[PASS] Minimum alignment 21
Testing random offset
[PASS] Random offset
Testing random size
[PASS] Random size
C.
Quoted 26 lines
Alex Mastro: thanks for the testing offered in v1, but since this series was rewritten, a re-test will be needed. I hence didn't collect the T-b.
Comments welcomed, thanks.
[1] https://github.com/awilliam/tests/blob/vfio-pci-device-map-alignment/vfio-pci-device-map-alignment.c
Peter Xu (4):
mm/thp: Allowthp_get_unmapped_area_vmflags()to take alignment
mm: Addfile_operations.get_mapping_order()
vfio: Introduce vfio_device_ops.get_mapping_order hook
vfio-pci: Best-effort huge pfnmaps with !MAP_FIXED mappingsDocumentation/filesystems/vfs.rst | 4 +++ drivers/vfio/pci/vfio_pci.c | 1 + drivers/vfio/pci/vfio_pci_core.c | 49 ++++++++++++++++++++++++++ drivers/vfio/vfio_main.c | 14 ++++++++ include/linux/fs.h | 1 + include/linux/huge_mm.h | 5 +-- include/linux/vfio.h | 5 +++ include/linux/vfio_pci_core.h | 2 ++ mm/huge_memory.c | 7 ++-- mm/mmap.c | 58 +++++++++++++++++++++++++++---- 10 files changed, 135 insertions(+), 11 deletions(-)
Quoted 2 lines · Peter Xu
Alex Mastro: thanks for the testing offered in v1, but since this series was rewritten, a re-test will be needed. I hence didn't collect the T-b.
Thank Peter, LGTM.
$ cc -Og -Wall -Wextra test_vfio_map_dma.c -o test_vfio_map_dma $ ./test_vfio_map_dma 0000:05:00.0 4 0x600000 0x800000000 0x100000000 opening 0000:05:00.0 via /dev/vfio/39 BAR 4: size=0x2000000000, offset=0x40000000000, flags=0x7 mmap'd BAR 4: offset=0x600000, size=0x800000000 -> vaddr=0x7fdac0600000 VFIO_IOMMU_MAP_DMA: vaddr=0x7fdac0600000, iova=0x100000000, size=0x800000000
$ sudo bpftrace -q -e 'fexit:vfio_pci_mmap_huge_fault { printf("order=%d, ret=0x%x\n", args.order, retval); }' 2>&1 > ~/dump
$ cat ~/dump | sort | uniq -c | sort -nr
512 order=9, ret=0x100
31 order=18, ret=0x100
2
1 order=18, ret=0x800test_vfio_map_dma.c
---
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <linux/limits.h>
#include <linux/types.h>
#include <linux/vfio.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#define ensure(cond) \
do { \
if (!(cond)) { \
fprintf(stderr, \
"%s:%d Condition failed: '%s' (errno=%d: %s)\n", \
__FILE__, __LINE__, #cond, errno, \
strerror(errno)); \
exit(EXIT_FAILURE); \
} \
} while (0)static uint32_t group_for_bdf(const char *bdf)
{
char path[PATH_MAX];
char link[PATH_MAX];
int ret;
snprintf(path, sizeof(path), "/sys/bus/pci/devices/%s/iommu_group",
bdf);
ret = readlink(path, link, sizeof(link));
ensure(ret > 0);
const char *filename = basename(link);
ensure(filename);
return strtoul(filename, NULL, 0);
}int main(int argc, char **argv)
{
int ret;
if (argc != 6) {
printf("usage: %s <vfio_bdf> <bar_idx> <bar_offset> <size> <iova>\n",
argv[0]);
printf("example: %s 0000:05:00.0 2 0x20000 0x1000 0x100000\n",
argv[0]);
return 1;
}
const char *bdf = argv[1];
uint32_t bar_idx = strtoul(argv[2], NULL, 0);
uint64_t bar_offs = strtoull(argv[3], NULL, 0);
uint64_t size = strtoull(argv[4], NULL, 0);
uint64_t iova = strtoull(argv[5], NULL, 0);
uint32_t group_num = group_for_bdf(bdf);
char group_path[PATH_MAX];
snprintf(group_path, sizeof(group_path), "/dev/vfio/%u", group_num);
int container_fd = open("/dev/vfio/vfio", O_RDWR);
ensure(container_fd >= 0);
printf("opening %s via %s\n", bdf, group_path);
int group_fd = open(group_path, O_RDWR);
ensure(group_fd >= 0);
ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container_fd);
ensure(!ret);
ret = ioctl(container_fd, VFIO_SET_IOMMU, VFIO_TYPE1v2_IOMMU);
ensure(!ret);
int device_fd = ioctl(group_fd, VFIO_GROUP_GET_DEVICE_FD, bdf);
ensure(device_fd >= 0);
/* Get region info for the BAR */
struct vfio_region_info region_info = {
.argsz = sizeof(region_info),
.index = bar_idx,
};
ret = ioctl(device_fd, VFIO_DEVICE_GET_REGION_INFO, ®ion_info);
ensure(!ret);
printf("BAR %u: size=0x%llx, offset=0x%llx, flags=0x%x\n", bar_idx,
region_info.size, region_info.offset, region_info.flags);
ensure(region_info.flags & VFIO_REGION_INFO_FLAG_MMAP);
ensure(bar_offs + size <= region_info.size);
/* mmap the BAR at the specified offset */
void *bar_mmap = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED,
device_fd, region_info.offset + bar_offs);
ensure(bar_mmap != MAP_FAILED);
ret = madvise(bar_mmap, size, MADV_HUGEPAGE);
ensure(!ret);
printf("mmap'd BAR %u: offset=0x%lx, size=0x%lx -> vaddr=%p\n", bar_idx,
bar_offs, size, bar_mmap);
/* Map the mmap'd address into IOMMU using VFIO_IOMMU_MAP_DMA */
struct vfio_iommu_type1_dma_map dma_map = {
.argsz = sizeof(dma_map),
.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE,
.vaddr = (uint64_t)bar_mmap,
.iova = iova,
.size = size,
};
printf("VFIO_IOMMU_MAP_DMA: vaddr=%p, iova=0x%llx, size=0x%lx\n",
bar_mmap, (unsigned long long)dma_map.iova, size);
ret = ioctl(container_fd, VFIO_IOMMU_MAP_DMA, &dma_map);
ensure(!ret);
/* Cleanup */
struct vfio_iommu_type1_dma_unmap dma_unmap = {
.argsz = sizeof(dma_unmap),
.iova = dma_map.iova,
.size = size,
};
ret = ioctl(container_fd, VFIO_IOMMU_UNMAP_DMA, &dma_unmap);
ensure(!ret);
ret = munmap(bar_mmap, size);
ensure(!ret);
close(device_fd);
close(group_fd);
close(container_fd);
return 0;
}