Skip to contentSkip to conversation

expand mmap_prepare functionality, port more users

PATCH Superseded Lorenzo Stoakes 8 participants 57 messages Sep 10, 2025 – Sep 19, 2025

Subsystems (26)

v2 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v2 cover expand mmap_prepare functionality, port more users

Since commit c84bf6dd2b83 ("mm: introduce new .mmap_prepare() file callback"), The f_op->mmap hook has been deprecated in favour of f_op->mmap_prepare.

This was introduced in order to make it possible for us to eventually eliminate the f_op->mmap hook which is highly problematic as it allows drivers and filesystems raw access to a VMA which is not yet correctly initialised.

This hook also introduced complexity for the memory mapping operation, as we must correctly unwind what we do should an error arises.

Overall this interface being so open has caused significant problems for us, including security issues, it is important for us to simply eliminate this as a source of problems.

Therefore this series continues what was established by extending the functionality further to permit more drivers and filesystems to use mmap_prepare.

We start by udpating some existing users who can use the mmap_prepare functionality as-is.

We then introduce the concept of an mmap 'action', which a user, on mmap_prepare, can request to be performed upon the VMA:

* Nothing - default, we're done
* Remap PFN - perform PFN remap with specified parameters
* Insert mixed - Insert a linear PFN range as a mixed map
* Insert mixed pages - Insert a set of specific pages as a mixed map
* Custom action - Should rarely be used, for operations that are truly custom. A hook is invoked.

By setting the action in mmap_prepare, this alows us to dynamically decide what to do next, so if a driver/filesystem needs to determine whether to e.g. remap or use a mixed map, it can do so then change which is done.

This significantly expands the capabilities of the mmap_prepare hook, while maintaining as much control as possible in the mm logic.

In the custom hook case, which unfortunately we have to provide for the obstinate drivers which insist on doing 'interesting' things, we make it possible for them to invoke mmap actions themselves via mmap_action_prepare() (to be called in mmap_prepare as necessary) and mmap_action_complete() (to be called in the custom hook).

This way, we keep as much logic in generic code as possible even in the custom case.

The point at which the VMA is accessible it is safe for it to be manipulated as it will already be fully established in the maple tree and error handling can be simplified to unmapping the VMA.

We split remap_pfn_range*() functions which allow for PFN remap (a typical mapping prepopulation operation) split between a prepare/complete step, as well as io_mremap_pfn_range_prepare, complete for a similar purpose.

From there we update various mm-adjacent logic to use this functionality as a first set of changes, as well as resctl and cramfs filesystems to round off the non-stacked filesystem instances.

We also add success and error hooks for post-action processing for e.g. output debug log on success and filtering error codes.

v2:
* Propagated tags, thanks everyone! :)
* Refactored resctl patch to avoid assigned-but-not-used variable.
* Updated resctl change to not use .mmap_abort as discussed with Jason.
* Removed .mmap_abort as discussed with Jason.
* Removed references to .mmap_abort from documentation.
* Fixed silly VM_WARN_ON_ONCE() mistake (asserting opposite of what we mean to) as per report from Alexander.
* Fixed relay kerneldoc error.
* Renamed __mmap_prelude to __mmap_setup, keep __mmap_complete the same as per David.
* Fixed docs typo in mmap_complete description + formatted bold rather than capitalised as per Randy.
* Eliminated mmap_complete and rework into actions specified in mmap_prepare (via vm_area_desc) which therefore eliminates the driver's ability to do anything crazy and allows us to control generic logic.
* Added helper functions for these - vma_desc_set_remap(), vma_desc_set_mixedmap().
* However unfortunately had to add post action hooks to vm_area_desc, as already hugetlbfs for instance needs to access the VMA to function correctly. It is at least the smallest possible means of doing this.
* Updated VMA test logic, the stacked filesystem compatibility layer and documentation to reflect this.
* Updated hugetlbfs implementation to use new approach, and refactored to accept desc where at all possible and to do as much as possible in .mmap_prepare, and the minimum required in the new post_hook callback.
* Updated /dev/mem and /dev/zero mmap logic to use the new mechanism.
* Updated cramfs, resctl to use the new mechanism.
* Updated proc_mmap hooks to only have proc_mmap_prepare.
* Updated the vmcore implementation to use the new hooks.
* Updated kcov to use the new hooks.
* Added hooks for success/failure for post-action handling.
* Added custom action hook for truly custom cases.
* Abstracted actions to separate type so we can use generic custom actions in custom handlers when necessary.
* Added callout re: lock issue raised in
https://lore.kernel.org/linux-mm/[email protected]/ as per discussion with Jason.

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

Lorenzo Stoakes (16):
mm/shmem: update shmem to use mmap_prepare device/dax: update devdax to use mmap_prepare
mm: add vma_desc_size(), vma_desc_pages() helpers
relay: update relay to use mmap_prepare
mm/vma: rename __mmap_prepare() function to avoid confusion
mm: add remap_pfn_range_prepare(), remap_pfn_range_complete()
mm: introduce io_remap_pfn_range_[prepare, complete]()
mm: add ability to take further action in vm_area_desc
doc: update porting, vfs documentation for mmap_prepare actions mm/hugetlbfs: update hugetlbfs to use mmap_prepare
mm: update mem char driver to use mmap_prepare
mm: update resctl to use mmap_prepare
mm: update cramfs to use mmap_prepare
fs/proc: add the proc_mmap_prepare hook for procfs fs/proc: update vmcore to use .proc_mmap_prepare
kcov: update kcov to use mmap_prepare

 Documentation/filesystems/porting.rst |   5 +
 Documentation/filesystems/vfs.rst     |   4 +
 arch/csky/include/asm/pgtable.h       |   5 +
 arch/mips/alchemy/common/setup.c      |  28 ++++-
 arch/mips/include/asm/pgtable.h       |  10 ++
 arch/s390/kernel/crash_dump.c         |   6 +-
 arch/sparc/include/asm/pgtable_32.h   |  29 ++++-
 arch/sparc/include/asm/pgtable_64.h   |  29 ++++-
 drivers/char/mem.c                    |  75 ++++++------
 drivers/dax/device.c                  |  32 +++--
 fs/cramfs/inode.c                     |  46 ++++----
 fs/hugetlbfs/inode.c                  |  30 +++--
 fs/ntfs3/file.c                       |   2 +-
 fs/proc/inode.c                       |  12 +-
 fs/proc/vmcore.c                      |  54 ++++++---
 fs/resctrl/pseudo_lock.c              |  22 ++--
 include/linux/hugetlb.h               |   9 +-
 include/linux/hugetlb_inline.h        |  15 ++-
 include/linux/mm.h                    |  83 ++++++++++++-
 include/linux/mm_types.h              |  61 ++++++++++
 include/linux/proc_fs.h               |   1 +
 include/linux/shmem_fs.h              |   3 +-
 include/linux/vmalloc.h               |  10 +-
 kernel/kcov.c                         |  42 ++++---
 kernel/relay.c                        |  33 +++---
 mm/hugetlb.c                          |  77 +++++++-----
 mm/memory.c                           | 128 ++++++++++++--------
 mm/secretmem.c                        |   2 +-
 mm/shmem.c                            |  49 ++++++--
 mm/util.c                             | 150 ++++++++++++++++++++++-
 mm/vma.c                              |  74 ++++++++----
 mm/vmalloc.c                          |  16 ++-
 tools/testing/vma/vma_internal.h      | 164 +++++++++++++++++++++++++-
 33 files changed, 1002 insertions(+), 304 deletions(-)

--
2.51.0

#1 lore raw

PATCH v2 1/16 mm/shmem: update shmem to use mmap_prepare

This simply assigns the vm_ops so is easily updated - do so.

---
 mm/shmem.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
mm/shmem.c +5 -4
index 45e7733d6612..990e33c6a776 100644
@@ -2938,16 +2938,17 @@ int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
 	return retval;
 }
 
-static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
+static int shmem_mmap_prepare(struct vm_area_desc *desc)
 {
+	struct file *file = desc->file;
 	struct inode *inode = file_inode(file);
 
 	file_accessed(file);
 	/* This is anonymous shared memory if it is unlinked at the time of mmap */
 	if (inode->i_nlink)
-		vma->vm_ops = &shmem_vm_ops;
+		desc->vm_ops = &shmem_vm_ops;
 	else
-		vma->vm_ops = &shmem_anon_vm_ops;
+		desc->vm_ops = &shmem_anon_vm_ops;
 	return 0;
 }
 
@@ -5217,7 +5218,7 @@ static const struct address_space_operations shmem_aops = {
 };
 
 static const struct file_operations shmem_file_operations = {
-	.mmap		= shmem_mmap,
+	.mmap_prepare	= shmem_mmap_prepare,
 	.open		= shmem_file_open,
 	.get_unmapped_area = shmem_get_unmapped_area,
 #ifdef CONFIG_TMPFS
Signature · 1 line
2.51.0
maintainer Reviewed-by on v2 1/16
#2 lore raw

Re: [PATCH v2 01/16] mm/shmem: update shmem to use mmap_prepare

Quoted 5 lines · Lorenzo Stoakes

This simply assigns the vm_ops so is easily updated - do so.

Looks good. Feel free to add:

Honza

Quoted 41 lines
---
 mm/shmem.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
mm/shmem.c +5 -4
index 45e7733d6612..990e33c6a776 100644
@@ -2938,16 +2938,17 @@ int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
 	return retval;
 }
 
-static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
+static int shmem_mmap_prepare(struct vm_area_desc *desc)
 {
+	struct file *file = desc->file;
 	struct inode *inode = file_inode(file);
 
 	file_accessed(file);
 	/* This is anonymous shared memory if it is unlinked at the time of mmap */
 	if (inode->i_nlink)
-		vma->vm_ops = &shmem_vm_ops;
+		desc->vm_ops = &shmem_vm_ops;
 	else
-		vma->vm_ops = &shmem_anon_vm_ops;
+		desc->vm_ops = &shmem_anon_vm_ops;
 	return 0;
 }
 
@@ -5217,7 +5218,7 @@ static const struct address_space_operations shmem_aops = {
 };
 
 static const struct file_operations shmem_file_operations = {
-	.mmap		= shmem_mmap,
+	.mmap_prepare	= shmem_mmap_prepare,
 	.open		= shmem_file_open,
 	.get_unmapped_area = shmem_get_unmapped_area,
 #ifdef CONFIG_TMPFS
Signature · 1 line
2.51.0
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
#3 lore raw

PATCH v2 2/16 device/dax: update devdax to use mmap_prepare

In reply to Lorenzo Stoakes

The devdax driver does nothing special in its f_op->mmap hook, so straightforwardly update it to use the mmap_prepare hook instead.

---
 drivers/dax/device.c | 32 +++++++++++++++++++++-----------
 1 file changed, 21 insertions(+), 11 deletions(-)
drivers/dax/device.c +21 -11
index 2bb40a6060af..c2181439f925 100644
@@ -13,8 +13,9 @@
 #include "dax-private.h"
 #include "bus.h"
 
-static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
-		const char *func)
+static int __check_vma(struct dev_dax *dev_dax, vm_flags_t vm_flags,
+		       unsigned long start, unsigned long end, struct file *file,
+		       const char *func)
 {
 	struct device *dev = &dev_dax->dev;
 	unsigned long mask;
@@ -23,7 +24,7 @@ static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
 		return -ENXIO;
 
 	/* prevent private mappings from being established */
-	if ((vma->vm_flags & VM_MAYSHARE) != VM_MAYSHARE) {
+	if ((vm_flags & VM_MAYSHARE) != VM_MAYSHARE) {
 		dev_info_ratelimited(dev,
 				"%s: %s: fail, attempted private mapping\n",
 				current->comm, func);
@@ -31,15 +32,15 @@ static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
 	}
 
 	mask = dev_dax->align - 1;
-	if (vma->vm_start & mask || vma->vm_end & mask) {
+	if (start & mask || end & mask) {
 		dev_info_ratelimited(dev,
 				"%s: %s: fail, unaligned vma (%#lx - %#lx, %#lx)\n",
-				current->comm, func, vma->vm_start, vma->vm_end,
+				current->comm, func, start, end,
 				mask);
 		return -EINVAL;
 	}
 
-	if (!vma_is_dax(vma)) {
+	if (!file_is_dax(file)) {
 		dev_info_ratelimited(dev,
 				"%s: %s: fail, vma is not DAX capable\n",
 				current->comm, func);
@@ -49,6 +50,13 @@ static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
 	return 0;
 }
 
+static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
+		     const char *func)
+{
+	return __check_vma(dev_dax, vma->vm_flags, vma->vm_start, vma->vm_end,
+			   vma->vm_file, func);
+}
+
 /* see "strong" declaration in tools/testing/nvdimm/dax-dev.c */
 __weak phys_addr_t dax_pgoff_to_phys(struct dev_dax *dev_dax, pgoff_t pgoff,
 		unsigned long size)
@@ -285,8 +293,9 @@ static const struct vm_operations_struct dax_vm_ops = {
 	.pagesize = dev_dax_pagesize,
 };
 
-static int dax_mmap(struct file *filp, struct vm_area_struct *vma)
+static int dax_mmap_prepare(struct vm_area_desc *desc)
 {
+	struct file *filp = desc->file;
 	struct dev_dax *dev_dax = filp->private_data;
 	int rc, id;
 
@@ -297,13 +306,14 @@ static int dax_mmap(struct file *filp, struct vm_area_struct *vma)
 	 * fault time.
 	 */
 	id = dax_read_lock();
-	rc = check_vma(dev_dax, vma, __func__);
+	rc = __check_vma(dev_dax, desc->vm_flags, desc->start, desc->end, filp,
+			 __func__);
 	dax_read_unlock(id);
 	if (rc)
 		return rc;
 
-	vma->vm_ops = &dax_vm_ops;
-	vm_flags_set(vma, VM_HUGEPAGE);
+	desc->vm_ops = &dax_vm_ops;
+	desc->vm_flags |= VM_HUGEPAGE;
 	return 0;
 }
 
@@ -377,7 +387,7 @@ static const struct file_operations dax_fops = {
 	.open = dax_open,
 	.release = dax_release,
 	.get_unmapped_area = dax_get_unmapped_area,
-	.mmap = dax_mmap,
+	.mmap_prepare = dax_mmap_prepare,
 	.fop_flags = FOP_MMAP_SYNC,
 };
 
Signature · 1 line
2.51.0
maintainer Reviewed-by on v2 2/16
#4 lore raw

Re: [PATCH v2 02/16] device/dax: update devdax to use mmap_prepare

Quoted 5 lines · Lorenzo Stoakes

The devdax driver does nothing special in its f_op->mmap hook, so straightforwardly update it to use the mmap_prepare hook instead.

Looks good. Feel free to add:

Honza

Quoted 103 lines
---
 drivers/dax/device.c | 32 +++++++++++++++++++++-----------
 1 file changed, 21 insertions(+), 11 deletions(-)
drivers/dax/device.c +21 -11
index 2bb40a6060af..c2181439f925 100644
@@ -13,8 +13,9 @@
 #include "dax-private.h"
 #include "bus.h"
 
-static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
-		const char *func)
+static int __check_vma(struct dev_dax *dev_dax, vm_flags_t vm_flags,
+		       unsigned long start, unsigned long end, struct file *file,
+		       const char *func)
 {
 	struct device *dev = &dev_dax->dev;
 	unsigned long mask;
@@ -23,7 +24,7 @@ static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
 		return -ENXIO;
 
 	/* prevent private mappings from being established */
-	if ((vma->vm_flags & VM_MAYSHARE) != VM_MAYSHARE) {
+	if ((vm_flags & VM_MAYSHARE) != VM_MAYSHARE) {
 		dev_info_ratelimited(dev,
 				"%s: %s: fail, attempted private mapping\n",
 				current->comm, func);
@@ -31,15 +32,15 @@ static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
 	}
 
 	mask = dev_dax->align - 1;
-	if (vma->vm_start & mask || vma->vm_end & mask) {
+	if (start & mask || end & mask) {
 		dev_info_ratelimited(dev,
 				"%s: %s: fail, unaligned vma (%#lx - %#lx, %#lx)\n",
-				current->comm, func, vma->vm_start, vma->vm_end,
+				current->comm, func, start, end,
 				mask);
 		return -EINVAL;
 	}
 
-	if (!vma_is_dax(vma)) {
+	if (!file_is_dax(file)) {
 		dev_info_ratelimited(dev,
 				"%s: %s: fail, vma is not DAX capable\n",
 				current->comm, func);
@@ -49,6 +50,13 @@ static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
 	return 0;
 }
 
+static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
+		     const char *func)
+{
+	return __check_vma(dev_dax, vma->vm_flags, vma->vm_start, vma->vm_end,
+			   vma->vm_file, func);
+}
+
 /* see "strong" declaration in tools/testing/nvdimm/dax-dev.c */
 __weak phys_addr_t dax_pgoff_to_phys(struct dev_dax *dev_dax, pgoff_t pgoff,
 		unsigned long size)
@@ -285,8 +293,9 @@ static const struct vm_operations_struct dax_vm_ops = {
 	.pagesize = dev_dax_pagesize,
 };
 
-static int dax_mmap(struct file *filp, struct vm_area_struct *vma)
+static int dax_mmap_prepare(struct vm_area_desc *desc)
 {
+	struct file *filp = desc->file;
 	struct dev_dax *dev_dax = filp->private_data;
 	int rc, id;
 
@@ -297,13 +306,14 @@ static int dax_mmap(struct file *filp, struct vm_area_struct *vma)
 	 * fault time.
 	 */
 	id = dax_read_lock();
-	rc = check_vma(dev_dax, vma, __func__);
+	rc = __check_vma(dev_dax, desc->vm_flags, desc->start, desc->end, filp,
+			 __func__);
 	dax_read_unlock(id);
 	if (rc)
 		return rc;
 
-	vma->vm_ops = &dax_vm_ops;
-	vm_flags_set(vma, VM_HUGEPAGE);
+	desc->vm_ops = &dax_vm_ops;
+	desc->vm_flags |= VM_HUGEPAGE;
 	return 0;
 }
 
@@ -377,7 +387,7 @@ static const struct file_operations dax_fops = {
 	.open = dax_open,
 	.release = dax_release,
 	.get_unmapped_area = dax_get_unmapped_area,
-	.mmap = dax_mmap,
+	.mmap_prepare = dax_mmap_prepare,
 	.fop_flags = FOP_MMAP_SYNC,
 };
 
Signature · 1 line
2.51.0
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
#5 lore raw

PATCH v2 3/16 mm: add vma_desc_size(), vma_desc_pages() helpers

In reply to Lorenzo Stoakes

It's useful to be able to determine the size of a VMA descriptor range used on f_op->mmap_prepare, expressed both in bytes and pages, so add helpers for both and update code that could make use of it to do so.

---
 fs/ntfs3/file.c    |  2 +-
 include/linux/mm.h | 10 ++++++++++
 mm/secretmem.c     |  2 +-
 3 files changed, 12 insertions(+), 2 deletions(-)
fs/ntfs3/file.c +1 -1
index c1ece707b195..86eb88f62714 100644
@@ -304,7 +304,7 @@ static int ntfs_file_mmap_prepare(struct vm_area_desc *desc)
 
 	if (rw) {
 		u64 to = min_t(loff_t, i_size_read(inode),
-			       from + desc->end - desc->start);
+			       from + vma_desc_size(desc));
 
 		if (is_sparsed(ni)) {
 			/* Allocate clusters for rw map. */
include/linux/mm.h +10 -0
index 892fe5dbf9de..0b97589aec6d 100644
@@ -3572,6 +3572,16 @@ static inline unsigned long vma_pages(const struct vm_area_struct *vma)
 	return (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
 }
 
+static inline unsigned long vma_desc_size(struct vm_area_desc *desc)
+{
+	return desc->end - desc->start;
+}
+
+static inline unsigned long vma_desc_pages(struct vm_area_desc *desc)
+{
+	return vma_desc_size(desc) >> PAGE_SHIFT;
+}
+
 /* Look up the first VMA which exactly match the interval vm_start ... vm_end */
 static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm,
 				unsigned long vm_start, unsigned long vm_end)
mm/secretmem.c +1 -1
index 60137305bc20..62066ddb1e9c 100644
@@ -120,7 +120,7 @@ static int secretmem_release(struct inode *inode, struct file *file)
 
 static int secretmem_mmap_prepare(struct vm_area_desc *desc)
 {
-	const unsigned long len = desc->end - desc->start;
+	const unsigned long len = vma_desc_size(desc);
 
 	if ((desc->vm_flags & (VM_SHARED | VM_MAYSHARE)) == 0)
 		return -EINVAL;
Signature · 1 line
2.51.0
maintainer Reviewed-by on v2 3/16
#6 lore raw

Re: [PATCH v2 03/16] mm: add vma_desc_size(), vma_desc_pages() helpers

Quoted 5 lines · Lorenzo Stoakes

It's useful to be able to determine the size of a VMA descriptor range used on f_op->mmap_prepare, expressed both in bytes and pages, so add helpers for both and update code that could make use of it to do so.

Looks good, I presume more users will come later in the series :). Feel free to add:

Honza

Quoted 56 lines
---
 fs/ntfs3/file.c    |  2 +-
 include/linux/mm.h | 10 ++++++++++
 mm/secretmem.c     |  2 +-
 3 files changed, 12 insertions(+), 2 deletions(-)
fs/ntfs3/file.c +1 -1
index c1ece707b195..86eb88f62714 100644
@@ -304,7 +304,7 @@ static int ntfs_file_mmap_prepare(struct vm_area_desc *desc)
 
 	if (rw) {
 		u64 to = min_t(loff_t, i_size_read(inode),
-			       from + desc->end - desc->start);
+			       from + vma_desc_size(desc));
 
 		if (is_sparsed(ni)) {
 			/* Allocate clusters for rw map. */
include/linux/mm.h +10 -0
index 892fe5dbf9de..0b97589aec6d 100644
@@ -3572,6 +3572,16 @@ static inline unsigned long vma_pages(const struct vm_area_struct *vma)
 	return (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
 }
 
+static inline unsigned long vma_desc_size(struct vm_area_desc *desc)
+{
+	return desc->end - desc->start;
+}
+
+static inline unsigned long vma_desc_pages(struct vm_area_desc *desc)
+{
+	return vma_desc_size(desc) >> PAGE_SHIFT;
+}
+
 /* Look up the first VMA which exactly match the interval vm_start ... vm_end */
 static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm,
 				unsigned long vm_start, unsigned long vm_end)
mm/secretmem.c +1 -1
index 60137305bc20..62066ddb1e9c 100644
@@ -120,7 +120,7 @@ static int secretmem_release(struct inode *inode, struct file *file)
 
 static int secretmem_mmap_prepare(struct vm_area_desc *desc)
 {
-	const unsigned long len = desc->end - desc->start;
+	const unsigned long len = vma_desc_size(desc);
 
 	if ((desc->vm_flags & (VM_SHARED | VM_MAYSHARE)) == 0)
 		return -EINVAL;
Signature · 1 line
2.51.0
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
Acked-by on v2 3/16
#7 lore raw

Re: [PATCH v2 03/16] mm: add vma_desc_size(), vma_desc_pages() helpers

In reply to Lorenzo Stoakes
Quoted 31 lines · Lorenzo Stoakes

It's useful to be able to determine the size of a VMA descriptor range used on f_op->mmap_prepare, expressed both in bytes and pages, so add helpers for both and update code that could make use of it to do so.

---
  fs/ntfs3/file.c    |  2 +-
  include/linux/mm.h | 10 ++++++++++
  mm/secretmem.c     |  2 +-
  3 files changed, 12 insertions(+), 2 deletions(-)
fs/ntfs3/file.c +1 -1
index c1ece707b195..86eb88f62714 100644
@@ -304,7 +304,7 @@ static int ntfs_file_mmap_prepare(struct vm_area_desc *desc)
 
  	if (rw) {
  		u64 to = min_t(loff_t, i_size_read(inode),
-			       from + desc->end - desc->start);
+			       from + vma_desc_size(desc));
 
  		if (is_sparsed(ni)) {
  			/* Allocate clusters for rw map. */
include/linux/mm.h +0 -0
index 892fe5dbf9de..0b97589aec6d 100644
@@ -3572,6 +3572,16 @@ static inline unsigned long vma_pages(const struct vm_area_struct *vma)
  	return (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
  }

include/linux/mm.h static inline unsigned long vma_pages(const struct vm_area_struct *vma) · line 3583

Quoted 10 lines
include/linux/mm.h +9 -0
 
+static inline unsigned long vma_desc_size(struct vm_area_desc *desc)
+{
+	return desc->end - desc->start;
+}
+
+static inline unsigned long vma_desc_pages(struct vm_area_desc *desc)
+{
+	return vma_desc_size(desc) >> PAGE_SHIFT;
+}

Should parameters in both functions be const * ?

Quoted 9 lines
include/linux/mm.h +1 -0
+
  /* Look up the first VMA which exactly match the interval vm_start ... vm_end */
  static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm,
  				unsigned long vm_start, unsigned long vm_end)
mm/secretmem.c +0 -0
index 60137305bc20..62066ddb1e9c 100644

mm/secretmem.c static int secretmem_release(struct inode *inode, struct file *file) · line 126

Quoted 8 lines
mm/secretmem.c +1 -1
@@ -120,7 +120,7 @@ static int secretmem_release(struct inode *inode, struct file *file)
 
  static int secretmem_mmap_prepare(struct vm_area_desc *desc)
  {
-	const unsigned long len = desc->end - desc->start;
+	const unsigned long len = vma_desc_size(desc);
 
  	if ((desc->vm_flags & (VM_SHARED | VM_MAYSHARE)) == 0)
  		return -EINVAL;
Signature · 3 lines
Cheers

David / dhildenb
#8 lore raw

Re: [PATCH v2 03/16] mm: add vma_desc_size(), vma_desc_pages() helpers

Quoted 33 lines · David Hildenbrand
Quoted 32 lines · Lorenzo Stoakes

It's useful to be able to determine the size of a VMA descriptor range used on f_op->mmap_prepare, expressed both in bytes and pages, so add helpers for both and update code that could make use of it to do so.

---
  fs/ntfs3/file.c    |  2 +-
  include/linux/mm.h | 10 ++++++++++
  mm/secretmem.c     |  2 +-
  3 files changed, 12 insertions(+), 2 deletions(-)
fs/ntfs3/file.c +1 -1
index c1ece707b195..86eb88f62714 100644
@@ -304,7 +304,7 @@ static int ntfs_file_mmap_prepare(struct vm_area_desc *desc)
  	if (rw) {
  		u64 to = min_t(loff_t, i_size_read(inode),
-			       from + desc->end - desc->start);
+			       from + vma_desc_size(desc));
  		if (is_sparsed(ni)) {
  			/* Allocate clusters for rw map. */
include/linux/mm.h +3 -0
index 892fe5dbf9de..0b97589aec6d 100644
@@ -3572,6 +3572,16 @@ static inline unsigned long vma_pages(const struct vm_area_struct *vma)
  	return (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
  }
+static inline unsigned long vma_desc_size(struct vm_area_desc *desc)
+{
+	return desc->end - desc->start;
Quoted 8 lines

include/linux/mm.h static inline unsigned long vma_pages(const struct vm_area_struct *vma) · line 3583

Quoted 6 lines
include/linux/mm.h +6 -0
+}
+
+static inline unsigned long vma_desc_pages(struct vm_area_desc *desc)
+{
+	return vma_desc_size(desc) >> PAGE_SHIFT;
+}

Should parameters in both functions be const * ?

Can do, will fix up if respin.

Quoted 10 lines
Quoted 10 lines
include/linux/mm.h +1 -0
+
  /* Look up the first VMA which exactly match the interval vm_start ... vm_end */
  static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm,
  				unsigned long vm_start, unsigned long vm_end)
mm/secretmem.c +0 -0
index 60137305bc20..62066ddb1e9c 100644
@@ -120,7 +120,7 @@ static int secretmem_release(struct inode *inode, struct file *file)
Quoted 8 lines

mm/secretmem.c static int secretmem_release(struct inode *inode, struct file *file) · line 126

Quoted 6 lines
mm/secretmem.c +1 -1
  static int secretmem_mmap_prepare(struct vm_area_desc *desc)
  {
-	const unsigned long len = desc->end - desc->start;
+	const unsigned long len = vma_desc_size(desc);
  	if ((desc->vm_flags & (VM_SHARED | VM_MAYSHARE)) == 0)
  		return -EINVAL;

Thanks!

Quoted 6 lines

--
Cheers

David / dhildenb

Cheers, Lorenzo

#9 lore raw

PATCH v2 4/16 relay: update relay to use mmap_prepare

In reply to Lorenzo Stoakes

It is relatively trivial to update this code to use the f_op->mmap_prepare hook in favour of the deprecated f_op->mmap hook, so do so.

---
 kernel/relay.c | 33 +++++++++++++++++----------------
 1 file changed, 17 insertions(+), 16 deletions(-)
kernel/relay.c +17 -16
index 8d915fe98198..e36f6b926f7f 100644
@@ -72,17 +72,18 @@ static void relay_free_page_array(struct page **array)
 }
 
 /**
- *	relay_mmap_buf: - mmap channel buffer to process address space
- *	@buf: relay channel buffer
- *	@vma: vm_area_struct describing memory to be mapped
+ *	relay_mmap_prepare_buf: - mmap channel buffer to process address space
+ *	@buf: the relay channel buffer
+ *	@desc: describing what to map
  *
  *	Returns 0 if ok, negative on error
  *
  *	Caller should already have grabbed mmap_lock.
  */
-static int relay_mmap_buf(struct rchan_buf *buf, struct vm_area_struct *vma)
+static int relay_mmap_prepare_buf(struct rchan_buf *buf,
+				  struct vm_area_desc *desc)
 {
-	unsigned long length = vma->vm_end - vma->vm_start;
+	unsigned long length = vma_desc_size(desc);
 
 	if (!buf)
 		return -EBADF;
@@ -90,9 +91,9 @@ static int relay_mmap_buf(struct rchan_buf *buf, struct vm_area_struct *vma)
 	if (length != (unsigned long)buf->chan->alloc_size)
 		return -EINVAL;
 
-	vma->vm_ops = &relay_file_mmap_ops;
-	vm_flags_set(vma, VM_DONTEXPAND);
-	vma->vm_private_data = buf;
+	desc->vm_ops = &relay_file_mmap_ops;
+	desc->vm_flags |= VM_DONTEXPAND;
+	desc->private_data = buf;
 
 	return 0;
 }
@@ -749,16 +750,16 @@ static int relay_file_open(struct inode *inode, struct file *filp)
 }
 
 /**
- *	relay_file_mmap - mmap file op for relay files
- *	@filp: the file
- *	@vma: the vma describing what to map
+ *	relay_file_mmap_prepare - mmap file op for relay files
+ *	@desc: describing what to map
  *
- *	Calls upon relay_mmap_buf() to map the file into user space.
+ *	Calls upon relay_mmap_prepare_buf() to map the file into user space.
  */
-static int relay_file_mmap(struct file *filp, struct vm_area_struct *vma)
+static int relay_file_mmap_prepare(struct vm_area_desc *desc)
 {
-	struct rchan_buf *buf = filp->private_data;
-	return relay_mmap_buf(buf, vma);
+	struct rchan_buf *buf = desc->file->private_data;
+
+	return relay_mmap_prepare_buf(buf, desc);
 }
 
 /**
@@ -1006,7 +1007,7 @@ static ssize_t relay_file_read(struct file *filp,
 const struct file_operations relay_file_operations = {
 	.open		= relay_file_open,
 	.poll		= relay_file_poll,
-	.mmap		= relay_file_mmap,
+	.mmap_prepare	= relay_file_mmap_prepare,
 	.read		= relay_file_read,
 	.release	= relay_file_release,
 };
Signature · 1 line
2.51.0
maintainer Reviewed-by on v2 4/16
#10 lore raw

Re: [PATCH v2 04/16] relay: update relay to use mmap_prepare

Quoted 5 lines · Lorenzo Stoakes

It is relatively trivial to update this code to use the f_op->mmap_prepare hook in favour of the deprecated f_op->mmap hook, so do so.

Looks good. Feel free to add:

Honza

Quoted 81 lines
---
 kernel/relay.c | 33 +++++++++++++++++----------------
 1 file changed, 17 insertions(+), 16 deletions(-)
kernel/relay.c +17 -16
index 8d915fe98198..e36f6b926f7f 100644
@@ -72,17 +72,18 @@ static void relay_free_page_array(struct page **array)
 }
 
 /**
- *	relay_mmap_buf: - mmap channel buffer to process address space
- *	@buf: relay channel buffer
- *	@vma: vm_area_struct describing memory to be mapped
+ *	relay_mmap_prepare_buf: - mmap channel buffer to process address space
+ *	@buf: the relay channel buffer
+ *	@desc: describing what to map
  *
  *	Returns 0 if ok, negative on error
  *
  *	Caller should already have grabbed mmap_lock.
  */
-static int relay_mmap_buf(struct rchan_buf *buf, struct vm_area_struct *vma)
+static int relay_mmap_prepare_buf(struct rchan_buf *buf,
+				  struct vm_area_desc *desc)
 {
-	unsigned long length = vma->vm_end - vma->vm_start;
+	unsigned long length = vma_desc_size(desc);
 
 	if (!buf)
 		return -EBADF;
@@ -90,9 +91,9 @@ static int relay_mmap_buf(struct rchan_buf *buf, struct vm_area_struct *vma)
 	if (length != (unsigned long)buf->chan->alloc_size)
 		return -EINVAL;
 
-	vma->vm_ops = &relay_file_mmap_ops;
-	vm_flags_set(vma, VM_DONTEXPAND);
-	vma->vm_private_data = buf;
+	desc->vm_ops = &relay_file_mmap_ops;
+	desc->vm_flags |= VM_DONTEXPAND;
+	desc->private_data = buf;
 
 	return 0;
 }
@@ -749,16 +750,16 @@ static int relay_file_open(struct inode *inode, struct file *filp)
 }
 
 /**
- *	relay_file_mmap - mmap file op for relay files
- *	@filp: the file
- *	@vma: the vma describing what to map
+ *	relay_file_mmap_prepare - mmap file op for relay files
+ *	@desc: describing what to map
  *
- *	Calls upon relay_mmap_buf() to map the file into user space.
+ *	Calls upon relay_mmap_prepare_buf() to map the file into user space.
  */
-static int relay_file_mmap(struct file *filp, struct vm_area_struct *vma)
+static int relay_file_mmap_prepare(struct vm_area_desc *desc)
 {
-	struct rchan_buf *buf = filp->private_data;
-	return relay_mmap_buf(buf, vma);
+	struct rchan_buf *buf = desc->file->private_data;
+
+	return relay_mmap_prepare_buf(buf, desc);
 }
 
 /**
@@ -1006,7 +1007,7 @@ static ssize_t relay_file_read(struct file *filp,
 const struct file_operations relay_file_operations = {
 	.open		= relay_file_open,
 	.poll		= relay_file_poll,
-	.mmap		= relay_file_mmap,
+	.mmap_prepare	= relay_file_mmap_prepare,
 	.read		= relay_file_read,
 	.release	= relay_file_release,
 };
Signature · 1 line
2.51.0
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
#11 lore raw

PATCH v2 5/16 mm/vma: rename __mmap_prepare() function to avoid confusion

In reply to Lorenzo Stoakes

Now we have the f_op->mmap_prepare() hook, having a static function called __mmap_prepare() that has nothing to do with it is confusing, so rename the function to __mmap_setup().

---
 mm/vma.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
mm/vma.c +4 -4
index abe0da33c844..36a9f4d453be 100644
@@ -2329,7 +2329,7 @@ static void update_ksm_flags(struct mmap_state *map)
 }
 
 /*
- * __mmap_prepare() - Prepare to gather any overlapping VMAs that need to be
+ * __mmap_setup() - Prepare to gather any overlapping VMAs that need to be
  * unmapped once the map operation is completed, check limits, account mapping
  * and clean up any pre-existing VMAs.
  *
@@ -2338,7 +2338,7 @@ static void update_ksm_flags(struct mmap_state *map)
  *
  * Returns: 0 on success, error code otherwise.
  */
-static int __mmap_prepare(struct mmap_state *map, struct list_head *uf)
+static int __mmap_setup(struct mmap_state *map, struct list_head *uf)
 {
 	int error;
 	struct vma_iterator *vmi = map->vmi;
@@ -2649,7 +2649,7 @@ static unsigned long __mmap_region(struct file *file, unsigned long addr,
 
 	map.check_ksm_early = can_set_ksm_flags_early(&map);
 
-	error = __mmap_prepare(&map, uf);
+	error = __mmap_setup(&map, uf);
 	if (!error && have_mmap_prepare)
 		error = call_mmap_prepare(&map);
 	if (error)
@@ -2679,7 +2679,7 @@ static unsigned long __mmap_region(struct file *file, unsigned long addr,
 
 	return addr;
 
-	/* Accounting was done by __mmap_prepare(). */
+	/* Accounting was done by __mmap_setup(). */
 unacct_error:
 	if (map.charged)
 		vm_unacct_memory(map.charged);
Signature · 1 line
2.51.0
Reviewed-by on v2 5/16
#12 lore raw

Re: [PATCH v2 05/16] mm/vma: rename __mmap_prepare() function to avoid confusion

Quoted 6 lines · Lorenzo Stoakes

Now we have the f_op->mmap_prepare() hook, having a static function called __mmap_prepare() that has nothing to do with it is confusing, so rename the function to __mmap_setup().

---

Signature · 3 lines
Cheers

David / dhildenb
#13 lore raw

Re: [PATCH v2 05/16] mm/vma: rename __mmap_prepare() function to avoid confusion

Quoted 9 lines · David Hildenbrand
Quoted 6 lines · Lorenzo Stoakes

Now we have the f_op->mmap_prepare() hook, having a static function called __mmap_prepare() that has nothing to do with it is confusing, so rename the function to __mmap_setup().

---

Thanks!

Quoted 6 lines

--
Cheers

David / dhildenb

#14 lore raw

PATCH v2 6/16 mm: add remap_pfn_range_prepare(), remap_pfn_range_complete()

In reply to Lorenzo Stoakes

We need the ability to split PFN remap between updating the VMA and performing the actual remap, in order to do away with the legacy f_op->mmap hook.

To do so, update the PFN remap code to provide shared logic, and also make remap_pfn_range_notrack() static, as its one user, io_mapping_map_user() was removed in commit 9a4f90e24661 ("mm: remove mm/io-mapping.c").

Then, introduce remap_pfn_range_prepare(), which accepts VMA descriptor and PFN parameters, and remap_pfn_range_complete() which accepts the same parameters as remap_pfn_rangte().

remap_pfn_range_prepare() will set the cow vma->vm_pgoff if necessary, so it must be supplied with a correct PFN to do so. If the caller must hold locks to be able to do this, those locks should be held across the operation, and mmap_abort() should be provided to revoke the lock should an error arise.

While we're here, also clean up the duplicated #ifdef __HAVE_PFNMAP_TRACKING check and put into a single #ifdef/#else block.

We would prefer to define these functions in mm/internal.h, however we will do the same for io_remap*() and these have arch defines that require access to the remap functions.

---
 include/linux/mm.h |  25 +++++++--
 mm/memory.c        | 128 ++++++++++++++++++++++++++++-----------------
 2 files changed, 102 insertions(+), 51 deletions(-)
include/linux/mm.h +21 -4
index 0b97589aec6d..0e256823799d 100644
@@ -489,6 +489,21 @@ extern unsigned int kobjsize(const void *objp);
  */
 #define VM_SPECIAL (VM_IO | VM_DONTEXPAND | VM_PFNMAP | VM_MIXEDMAP)
 
+/*
+ * Physically remapped pages are special. Tell the
+ * rest of the world about it:
+ *   VM_IO tells people not to look at these pages
+ *	(accesses can have side effects).
+ *   VM_PFNMAP tells the core MM that the base pages are just
+ *	raw PFN mappings, and do not have a "struct page" associated
+ *	with them.
+ *   VM_DONTEXPAND
+ *      Disable vma merging and expanding with mremap().
+ *   VM_DONTDUMP
+ *      Omit vma from core dump, even when VM_IO turned off.
+ */
+#define VM_REMAP_FLAGS (VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP)
+
 /* This mask prevents VMA from being scanned with khugepaged */
 #define VM_NO_KHUGEPAGED (VM_SPECIAL | VM_HUGETLB)
 
@@ -3623,10 +3638,12 @@ unsigned long change_prot_numa(struct vm_area_struct *vma,
 
 struct vm_area_struct *find_extend_vma_locked(struct mm_struct *,
 		unsigned long addr);
-int remap_pfn_range(struct vm_area_struct *, unsigned long addr,
-			unsigned long pfn, unsigned long size, pgprot_t);
-int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
-		unsigned long pfn, unsigned long size, pgprot_t prot);
+int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
+		    unsigned long pfn, unsigned long size, pgprot_t pgprot);
+void remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn);
+int remap_pfn_range_complete(struct vm_area_struct *vma, unsigned long addr,
+		unsigned long pfn, unsigned long size, pgprot_t pgprot);
+
 int vm_insert_page(struct vm_area_struct *, unsigned long addr, struct page *);
 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
 			struct page **pages, unsigned long *num);
mm/memory.c +81 -47

179 lines not on this page · raw message

Signature · 1 line
2.51.0
#15 lore raw

PATCH v2 7/16 mm: introduce io_remap_pfn_range_[prepare, complete]()

In reply to Lorenzo Stoakes

We introduce the io_remap*() equivalents of remap_pfn_range_prepare() and remap_pfn_range_complete() to allow for I/O remapping via mmap_prepare.

We have to make some architecture-specific changes for those architectures which define customised handlers.

It doesn't really make sense to make this internal-only as arches specify their version of these functions so we declare these in mm.h.

---
 arch/csky/include/asm/pgtable.h     |  5 +++++
 arch/mips/alchemy/common/setup.c    | 28 +++++++++++++++++++++++++---
 arch/mips/include/asm/pgtable.h     | 10 ++++++++++
 arch/sparc/include/asm/pgtable_32.h | 29 +++++++++++++++++++++++++----
 arch/sparc/include/asm/pgtable_64.h | 29 +++++++++++++++++++++++++----
 include/linux/mm.h                  | 18 ++++++++++++++++++
 6 files changed, 108 insertions(+), 11 deletions(-)
arch/csky/include/asm/pgtable.h +5 -0
index 5a394be09c35..c83505839a06 100644
@@ -266,4 +266,9 @@ void update_mmu_cache_range(struct vm_fault *vmf, struct vm_area_struct *vma,
 #define io_remap_pfn_range(vma, vaddr, pfn, size, prot) \
 	remap_pfn_range(vma, vaddr, pfn, size, prot)
 
+/* default io_remap_pfn_range_prepare can be used. */
+
+#define io_remap_pfn_range_complete(vma, addr, pfn, size, prot) \
+	remap_pfn_range_complete(vma, addr, pfn, size, prot)
+
 #endif /* __ASM_CSKY_PGTABLE_H */
arch/mips/alchemy/common/setup.c +25 -3
index a7a6d31a7a41..a4ab02776994 100644
@@ -94,12 +94,34 @@ phys_addr_t fixup_bigphys_addr(phys_addr_t phys_addr, phys_addr_t size)
 	return phys_addr;
 }
 
-int io_remap_pfn_range(struct vm_area_struct *vma, unsigned long vaddr,
-		unsigned long pfn, unsigned long size, pgprot_t prot)
+static unsigned long calc_pfn(unsigned long pfn, unsigned long size)
 {
 	phys_addr_t phys_addr = fixup_bigphys_addr(pfn << PAGE_SHIFT, size);
 
-	return remap_pfn_range(vma, vaddr, phys_addr >> PAGE_SHIFT, size, prot);
+	return phys_addr >> PAGE_SHIFT;
+}
+
+int io_remap_pfn_range(struct vm_area_struct *vma, unsigned long vaddr,
+		unsigned long pfn, unsigned long size, pgprot_t prot)
+{
+	return remap_pfn_range(vma, vaddr, calc_pfn(pfn, size), size, prot);
 }
 EXPORT_SYMBOL(io_remap_pfn_range);
+
+void io_remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn,
+			       unsigned long size)
+{
+	remap_pfn_range_prepare(desc, calc_pfn(pfn, size));
+}
+EXPORT_SYMBOL(io_remap_pfn_range_prepare);
+
+int io_remap_pfn_range_complete(struct vm_area_struct *vma,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t prot)
+{
+	return remap_pfn_range_complete(vma, addr, calc_pfn(pfn, size),
+			size, prot);
+}
+EXPORT_SYMBOL(io_remap_pfn_range_complete);
+
 #endif /* CONFIG_MIPS_FIXUP_BIGPHYS_ADDR */
arch/mips/include/asm/pgtable.h +10 -0
index ae73ecf4c41a..6a8964f55a31 100644
@@ -607,6 +607,16 @@ phys_addr_t fixup_bigphys_addr(phys_addr_t addr, phys_addr_t size);
 int io_remap_pfn_range(struct vm_area_struct *vma, unsigned long vaddr,
 		unsigned long pfn, unsigned long size, pgprot_t prot);
 #define io_remap_pfn_range io_remap_pfn_range
+
+void io_remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn,
+		unsigned long size);
+#define io_remap_pfn_range_prepare io_remap_pfn_range_prepare
+
+int io_remap_pfn_range_complete(struct vm_area_struct *vma,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t prot);
+#define io_remap_pfn_range_complete io_remap_pfn_range_complete
+
 #else
 #define fixup_bigphys_addr(addr, size)	(addr)
 #endif /* CONFIG_MIPS_FIXUP_BIGPHYS_ADDR */
arch/sparc/include/asm/pgtable_32.h +25 -4
index 7c199c003ffe..cfd764afc107 100644
@@ -398,9 +398,7 @@ __get_iospace (unsigned long addr)
 int remap_pfn_range(struct vm_area_struct *, unsigned long, unsigned long,
 		    unsigned long, pgprot_t);
 
-static inline int io_remap_pfn_range(struct vm_area_struct *vma,
-				     unsigned long from, unsigned long pfn,
-				     unsigned long size, pgprot_t prot)
+static inline unsigned long calc_io_remap_pfn(unsigned long pfn)
 {
 	unsigned long long offset, space, phys_base;
 
@@ -408,10 +406,33 @@ static inline int io_remap_pfn_range(struct vm_area_struct *vma,
 	space = GET_IOSPACE(pfn);
 	phys_base = offset | (space << 32ULL);
 
-	return remap_pfn_range(vma, from, phys_base >> PAGE_SHIFT, size, prot);
+	return phys_base >> PAGE_SHIFT;
+}
+
+static inline int io_remap_pfn_range(struct vm_area_struct *vma,
+				     unsigned long from, unsigned long pfn,
+				     unsigned long size, pgprot_t prot)
+{
+	return remap_pfn_range(vma, from, calc_io_remap_pfn(pfn), size, prot);
 }
 #define io_remap_pfn_range io_remap_pfn_range
 
+static inline void io_remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn,
+		unsigned long size)
+{
+	remap_pfn_range_prepare(desc, calc_io_remap_pfn(pfn));
+}
+#define io_remap_pfn_range_prepare io_remap_pfn_range_prepare
+
+static inline int io_remap_pfn_range_complete(struct vm_area_struct *vma,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t prot)
+{
+	return remap_pfn_range_complete(vma, addr, calc_io_remap_pfn(pfn),
+			size, prot);
+}
+#define io_remap_pfn_range_complete io_remap_pfn_range_complete
+
 #define __HAVE_ARCH_PTEP_SET_ACCESS_FLAGS
 #define ptep_set_access_flags(__vma, __address, __ptep, __entry, __dirty) \
 ({									  \
arch/sparc/include/asm/pgtable_64.h +25 -4
index 669cd02469a1..b8000ce4b59f 100644
@@ -1084,9 +1084,7 @@ static inline int arch_unmap_one(struct mm_struct *mm,
 	return 0;
 }
 
-static inline int io_remap_pfn_range(struct vm_area_struct *vma,
-				     unsigned long from, unsigned long pfn,
-				     unsigned long size, pgprot_t prot)
+static inline unsigned long calc_io_remap_pfn(unsigned long pfn)
 {
 	unsigned long offset = GET_PFN(pfn) << PAGE_SHIFT;
 	int space = GET_IOSPACE(pfn);
@@ -1094,10 +1092,33 @@ static inline int io_remap_pfn_range(struct vm_area_struct *vma,
 
 	phys_base = offset | (((unsigned long) space) << 32UL);
 
-	return remap_pfn_range(vma, from, phys_base >> PAGE_SHIFT, size, prot);
+	return phys_base >> PAGE_SHIFT;
+}
+
+static inline int io_remap_pfn_range(struct vm_area_struct *vma,
+				     unsigned long from, unsigned long pfn,
+				     unsigned long size, pgprot_t prot)
+{
+	return remap_pfn_range(vma, from, calc_io_remap_pfn(pfn), size, prot);
 }
 #define io_remap_pfn_range io_remap_pfn_range
 
+static inline void io_remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn,
+	unsigned long size)
+{
+	return remap_pfn_range_prepare(desc, calc_io_remap_pfn(pfn));
+}
+#define io_remap_pfn_range_prepare io_remap_pfn_range_prepare
+
+static inline int io_remap_pfn_range_complete(struct vm_area_struct *vma,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t prot)
+{
+	return remap_pfn_range_complete(vma, addr, calc_io_remap_pfn(pfn),
+					size, prot);
+}
+#define io_remap_pfn_range_complete io_remap_pfn_range_complete
+
 static inline unsigned long __untagged_addr(unsigned long start)
 {
 	if (adi_capable()) {
include/linux/mm.h +18 -0
index 0e256823799d..cca149bb8ef1 100644
@@ -3685,6 +3685,24 @@ static inline int io_remap_pfn_range(struct vm_area_struct *vma,
 }
 #endif
 
+#ifndef io_remap_pfn_range_prepare
+static inline void io_remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn,
+	unsigned long size)
+{
+	return remap_pfn_range_prepare(desc, pfn);
+}
+#endif
+
+#ifndef io_remap_pfn_range_complete
+static inline int io_remap_pfn_range_complete(struct vm_area_struct *vma,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t prot)
+{
+	return remap_pfn_range_complete(vma, addr, pfn, size,
+			pgprot_decrypted(prot));
+}
+#endif
+
 static inline vm_fault_t vmf_error(int err)
 {
 	if (err == -ENOMEM)
Signature · 1 line
2.51.0
#16 lore raw

Re: [PATCH v2 07/16] mm: introduce io_remap_pfn_range_[prepare, complete]()

Hi Andrew,

Could you apply the below fix-patch to address the delights and wonders of arch-specific header stuff? :)

Cheers, Lorenzo

----8<----
From 1a8ddbbb3aab15104e7b7b5b7a5a286dd23d8325 Mon Sep 17 00:00:00 2001
From: Lorenzo Stoakes <[email protected]>
Date: Fri, 12 Sep 2025 10:58:23 +0100
Subject: [PATCH] sparc fix

---
 arch/sparc/include/asm/pgtable_32.h | 3 +++
 arch/sparc/include/asm/pgtable_64.h | 3 +++
 2 files changed, 6 insertions(+)
arch/sparc/include/asm/pgtable_32.h +3 -0
index cfd764afc107..30749c5ffe95 100644
@@ -397,6 +397,9 @@ __get_iospace (unsigned long addr)
 
 int remap_pfn_range(struct vm_area_struct *, unsigned long, unsigned long,
 		    unsigned long, pgprot_t);
+void remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn);
+int remap_pfn_range_complete(struct vm_area_struct *vma, unsigned long addr,
+		unsigned long pfn, unsigned long size, pgprot_t pgprot);
 
 static inline unsigned long calc_io_remap_pfn(unsigned long pfn)
 {
arch/sparc/include/asm/pgtable_64.h +3 -0
index b8000ce4b59f..b06f55915653 100644
@@ -1050,6 +1050,9 @@ int page_in_phys_avail(unsigned long paddr);
 
 int remap_pfn_range(struct vm_area_struct *, unsigned long, unsigned long,
 		    unsigned long, pgprot_t);
+void remap_pfn_range_prepare(struct vm_area_desc *desc, unsigned long pfn);
+int remap_pfn_range_complete(struct vm_area_struct *vma, unsigned long addr,
+		unsigned long pfn, unsigned long size, pgprot_t pgprot);
 
 void adi_restore_tags(struct mm_struct *mm, struct vm_area_struct *vma,
 		      unsigned long addr, pte_t pte);

--
2.51.0

#17 lore raw

PATCH v2 8/16 mm: add ability to take further action in vm_area_desc

In reply to Lorenzo Stoakes

Some drivers/filesystems need to perform additional tasks after the VMA is set up. This is typically in the form of pre-population.

The forms of pre-population most likely to be performed are a PFN remap or insertion of a mixed map, so we provide this functionality, ensuring that we perform the appropriate actions at the appropriate time - that is setting flags at the point of .mmap_prepare, and performing the actual remap at the point at which the VMA is fully established.

This prevents the driver from doing anything too crazy with a VMA at any stage, and we retain complete control over how the mm functionality is applied.

Unfortunately callers still do often require some kind of custom action, so we add an optional success/error _hook to allow the caller to do something after the action has succeeded or failed.

This is done at the point when the VMA has already been established, so the harm that can be done is limited.

The error hook can be used to filter errors if necessary.

We implement actions as abstracted from the vm_area_desc, so we provide the ability for custom hooks to invoke actions distinct from the vma descriptor.

If any error arises on these final actions, we simply unmap the VMA altogether.

Also update the stacked filesystem compatibility layer to utilise the action behaviour, and update the VMA tests accordingly.

For drivers which perform truly custom logic, we provide a custom action hook which is invoked at the point of action execution.

This can then, in turn, update the desc object and perform other actions, such as partially remapping ranges for instance. We export vma_desc_action_prepare() and vma_desc_action_complete() for drivers to do this.

This is performed at a stage where the VMA is already established, immediately prior to mapping completion, so it is considerably less problematic than a general mmap hook.

Note that at the point of the action being taken, the VMA is visible via the rmap, only the VMA write lock is held, so if anything needs to access the VMA, it is able to.

Essentially the action is taken as if it were performed after the mapping, but is kept atomic with VMA state.

---
 include/linux/mm.h               |  30 ++++++
 include/linux/mm_types.h         |  61 ++++++++++++
 mm/util.c                        | 150 +++++++++++++++++++++++++++-
 mm/vma.c                         |  70 ++++++++-----
 tools/testing/vma/vma_internal.h | 164 ++++++++++++++++++++++++++++++-
 5 files changed, 447 insertions(+), 28 deletions(-)
include/linux/mm.h +30 -0
index cca149bb8ef1..2ceead3ffcf0 100644
@@ -3597,6 +3597,36 @@ static inline unsigned long vma_desc_pages(struct vm_area_desc *desc)
 	return vma_desc_size(desc) >> PAGE_SHIFT;
 }
 
+static inline void mmap_action_remap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t pgprot)
+{
+	action->type = MMAP_REMAP_PFN;
+
+	action->remap.addr = addr;
+	action->remap.pfn = pfn;
+	action->remap.size = size;
+	action->remap.pgprot = pgprot;
+}
+
+static inline void mmap_action_mixedmap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long num_pages)
+{
+	action->type = MMAP_INSERT_MIXED;
+
+	action->mixedmap.addr = addr;
+	action->mixedmap.pfn = pfn;
+	action->mixedmap.num_pages = num_pages;
+}
+
+struct page **mmap_action_mixedmap_pages(struct mmap_action *action,
+		unsigned long addr, unsigned long num_pages);
+
+void mmap_action_prepare(struct mmap_action *action,
+			     struct vm_area_desc *desc);
+int mmap_action_complete(struct mmap_action *action,
+			     struct vm_area_struct *vma);
+
 /* Look up the first VMA which exactly match the interval vm_start ... vm_end */
 static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm,
 				unsigned long vm_start, unsigned long vm_end)
include/linux/mm_types.h +61 -0

73 lines not on this page · raw message

mm/util.c +148 -2

169 lines not on this page · raw message

mm/vma.c +47 -23

132 lines not on this page · raw message

tools/testing/vma/vma_internal.h +161 -3

210 lines not on this page · raw message

Signature · 1 line
2.51.0
maintainer
#18 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Hi Lorenzo,

On 9/10/25 1:22 PM, Lorenzo Stoakes wrote:

...

Quoted 39 lines
include/linux/mm_types.h +31 -0
index 4a441f78340d..ae6c7a0a18a7 100644
@@ -770,6 +770,64 @@ struct pfnmap_track_ctx {
 };
 #endif
 
+/* What action should be taken after an .mmap_prepare call is complete? */
+enum mmap_action_type {
+	MMAP_NOTHING,		 /* Mapping is complete, no further action. */
+	MMAP_REMAP_PFN,		 /* Remap PFN range based on desc->remap. */
+	MMAP_INSERT_MIXED,	 /* Mixed map based on desc->mixedmap. */
+	MMAP_INSERT_MIXED_PAGES, /* Mixed map based on desc->mixedmap_pages. */
+	MMAP_CUSTOM_ACTION,	 /* User-provided hook. */
+};
+
+struct mmap_action {
+	union {
+		/* Remap range. */
+		struct {
+			unsigned long addr;
+			unsigned long pfn;
+			unsigned long size;
+			pgprot_t pgprot;
+		} remap;
+		/* Insert mixed map. */
+		struct {
+			unsigned long addr;
+			unsigned long pfn;
+			unsigned long num_pages;
+		} mixedmap;
+		/* Insert specific mixed map pages. */
+		struct {
+			unsigned long addr;
+			struct page **pages;
+			unsigned long num_pages;
+			/* kfree pages on completion? */
+			bool kfree_pages :1;

include/linux/mm_types.h struct pfnmap_track_ctx { · line 813

Quoted 10 lines
include/linux/mm_types.h +10 -0
+		} mixedmap_pages;
+		struct {
+			int (*action_hook)(struct vm_area_struct *vma);
+		} custom;
+	};
+	enum mmap_action_type type;
+
+	/*
+	 * If specified, this hook is invoked after the selected action has been
+	 * successfully completed. Not that the VMA write lock still held.

A typo that may trip tired eyes: Not -> Note ? (perhaps also "is still held"?) (also in the duplicate changes to tools/testing/vma/vma_internal.h)

Quoted 6 lines
include/linux/mm_types.h +6 -0
+	 *
+	 * The absolute minimum ought to be done here.
+	 *
+	 * Returns 0 on success, or an error code.
+	 */
+	int (*success_hook)(struct vm_area_struct *vma);

include/linux/mm_types.h struct pfnmap_track_ctx { · line 829

Quoted 10 lines
include/linux/mm_types.h +10 -0
+
+	/*
+	 * If specified, this hook is invoked when an error occurred when
+	 * attempting the selection action.
+	 *
+	 * The hook can return an error code in order to filter the error, but
+	 * it is not valid to clear the error here.
+	 */
+	int (*error_hook)(int err);
+};

Reinette

#19 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 50 lines · Reinette Chatre

Hi Lorenzo,

On 9/10/25 1:22 PM, Lorenzo Stoakes wrote:

...

Quoted 44 lines
include/linux/mm_types.h +36 -0
index 4a441f78340d..ae6c7a0a18a7 100644
@@ -770,6 +770,64 @@ struct pfnmap_track_ctx {
 };
 #endif
 
+/* What action should be taken after an .mmap_prepare call is complete? */
+enum mmap_action_type {
+	MMAP_NOTHING,		 /* Mapping is complete, no further action. */
+	MMAP_REMAP_PFN,		 /* Remap PFN range based on desc->remap. */
+	MMAP_INSERT_MIXED,	 /* Mixed map based on desc->mixedmap. */
+	MMAP_INSERT_MIXED_PAGES, /* Mixed map based on desc->mixedmap_pages. */
+	MMAP_CUSTOM_ACTION,	 /* User-provided hook. */
+};
+
+struct mmap_action {
+	union {
+		/* Remap range. */
+		struct {
+			unsigned long addr;
+			unsigned long pfn;
+			unsigned long size;
+			pgprot_t pgprot;
+		} remap;
+		/* Insert mixed map. */
+		struct {
+			unsigned long addr;
+			unsigned long pfn;
+			unsigned long num_pages;
+		} mixedmap;
+		/* Insert specific mixed map pages. */
+		struct {
+			unsigned long addr;
+			struct page **pages;
+			unsigned long num_pages;
+			/* kfree pages on completion? */
+			bool kfree_pages :1;
+		} mixedmap_pages;
+		struct {
+			int (*action_hook)(struct vm_area_struct *vma);
+		} custom;
+	};
Quoted 8 lines

include/linux/mm_types.h struct pfnmap_track_ctx { · line 813

Quoted 5 lines
include/linux/mm_types.h +5 -0
+	enum mmap_action_type type;
+
+	/*
+	 * If specified, this hook is invoked after the selected action has been
+	 * successfully completed. Not that the VMA write lock still held.

A typo that may trip tired eyes: Not -> Note ? (perhaps also "is still held"?) (also in the duplicate changes to tools/testing/vma/vma_internal.h)

Yeah good catch! Will fix if respin :)

Cheers, Lorenzo

#20 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

In reply to Lorenzo Stoakes

Hi Andrew,

Could you apply the below fix-patch to make nommu happy? It also has a couple trivial whitespace fixes in it.

Thanks, Lorenzo

----8<----
From 94d0d29ab23b48bd301eb7e4e9abe88546565d7a Mon Sep 17 00:00:00 2001
From: Lorenzo Stoakes <[email protected]>
Date: Fri, 12 Sep 2025 10:56:39 +0100
Subject: [PATCH] nommu fix

---
 mm/util.c | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 66 insertions(+), 2 deletions(-)
mm/util.c +66 -2
index 11752d67b89c..f0730efd34eb 100644
@@ -1302,6 +1302,7 @@ struct page **mmap_action_mixedmap_pages(struct mmap_action *action,
 }
 EXPORT_SYMBOL(mmap_action_mixedmap_pages);
 
+#ifdef CONFIG_MMU
 /**
  * mmap_action_prepare - Perform preparatory setup for an VMA descriptor
  * action which need to be performed.
@@ -1313,7 +1314,7 @@ EXPORT_SYMBOL(mmap_action_mixedmap_pages);
  * it wishes to perform.
  */
 void mmap_action_prepare(struct mmap_action *action,
-			    struct vm_area_desc *desc)
+			struct vm_area_desc *desc)
 {
 	switch (action->type) {
 	case MMAP_NOTHING:
@@ -1342,7 +1343,7 @@ EXPORT_SYMBOL(mmap_action_prepare);
  * Return: 0 on success, or error, at which point the VMA will be unmapped.
  */
 int mmap_action_complete(struct mmap_action *action,
-			    struct vm_area_struct *vma)
+			struct vm_area_struct *vma)
 {
 	int err = 0;
 
@@ -1424,6 +1425,69 @@ int mmap_action_complete(struct mmap_action *action,
 	return 0;
 }
 EXPORT_SYMBOL(mmap_action_complete);
+#else
+void mmap_action_prepare(struct mmap_action *action,
+			struct vm_area_desc *desc)
+{
+	switch (action->type) {
+	case MMAP_NOTHING:
+	case MMAP_CUSTOM_ACTION:
+		break;
+	case MMAP_REMAP_PFN:
+	case MMAP_INSERT_MIXED:
+	case MMAP_INSERT_MIXED_PAGES:
+		WARN_ON_ONCE(1); /* nommu cannot handle these. */
+		break;
+	}
+}
+EXPORT_SYMBOL(mmap_action_prepare);
+
+int mmap_action_complete(struct mmap_action *action,
+			struct vm_area_struct *vma)
+{
+	int err = 0;
+
+	switch (action->type) {
+	case MMAP_NOTHING:
+		break;
+	case MMAP_REMAP_PFN:
+	case MMAP_INSERT_MIXED:
+	case MMAP_INSERT_MIXED_PAGES:
+		WARN_ON_ONCE(1); /* nommu cannot handle these. */
+
+		break;
+	case MMAP_CUSTOM_ACTION:
+		err = action->custom.action_hook(vma);
+		break;
+	}
+
+	/*
+	* If an error occurs, unmap the VMA altogether and return an error. We
+	* only clear the newly allocated VMA, since this function is only
+	* invoked if we do NOT merge, so we only clean up the VMA we created.
+	*/
+	if (err) {
+		const size_t len = vma_pages(vma) << PAGE_SHIFT;
+
+		do_munmap(current->mm, vma->vm_start, len, NULL);
+
+		if (action->error_hook) {
+			/* We may want to filter the error. */
+			err = action->error_hook(err);
+
+			/* The caller should not clear the error. */
+			VM_WARN_ON_ONCE(!err);
+		}
+		return err;
+	}
+
+	if (action->success_hook)
+		err = action->success_hook(vma);
+
+	return 0;
+}
+EXPORT_SYMBOL(mmap_action_complete);
+#endif
 
 #ifdef CONFIG_MMU
 /**

--
2.51.0

#21 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

In reply to Lorenzo Stoakes

Hi Lorzeno,

Quoted 60 lines · Lorenzo Stoakes

Some drivers/filesystems need to perform additional tasks after the VMA is set up. This is typically in the form of pre-population.

The forms of pre-population most likely to be performed are a PFN remap or insertion of a mixed map, so we provide this functionality, ensuring that we perform the appropriate actions at the appropriate time - that is setting flags at the point of .mmap_prepare, and performing the actual remap at the point at which the VMA is fully established.

This prevents the driver from doing anything too crazy with a VMA at any stage, and we retain complete control over how the mm functionality is applied.

Unfortunately callers still do often require some kind of custom action, so we add an optional success/error _hook to allow the caller to do something after the action has succeeded or failed.

This is done at the point when the VMA has already been established, so the harm that can be done is limited.

The error hook can be used to filter errors if necessary.

We implement actions as abstracted from the vm_area_desc, so we provide the ability for custom hooks to invoke actions distinct from the vma descriptor.

If any error arises on these final actions, we simply unmap the VMA altogether.

Also update the stacked filesystem compatibility layer to utilise the action behaviour, and update the VMA tests accordingly.

For drivers which perform truly custom logic, we provide a custom action hook which is invoked at the point of action execution.

This can then, in turn, update the desc object and perform other actions, such as partially remapping ranges for instance. We export vma_desc_action_prepare() and vma_desc_action_complete() for drivers to do this.

This is performed at a stage where the VMA is already established, immediately prior to mapping completion, so it is considerably less problematic than a general mmap hook.

Note that at the point of the action being taken, the VMA is visible via the rmap, only the VMA write lock is held, so if anything needs to access the VMA, it is able to.

Essentially the action is taken as if it were performed after the mapping, but is kept atomic with VMA state.

---
 include/linux/mm.h               |  30 ++++++
 include/linux/mm_types.h         |  61 ++++++++++++
 mm/util.c                        | 150 +++++++++++++++++++++++++++-
 mm/vma.c                         |  70 ++++++++-----
 tools/testing/vma/vma_internal.h | 164 ++++++++++++++++++++++++++++++-
 5 files changed, 447 insertions(+), 28 deletions(-)

[ ... ]

Quoted 32 lines
mm/util.c +32 -0
+/**
+ * mmap_action_complete - Execute VMA descriptor action.
+ * @action: The action to perform.
+ * @vma: The VMA to perform the action upon.
+ *
+ * Similar to mmap_action_prepare(), other than internal mm usage this is
+ * intended for mmap_prepare users who implement a custom hook - with this
+ * function being called from the custom hook itself.
+ *
+ * Return: 0 on success, or error, at which point the VMA will be unmapped.
+ */
+int mmap_action_complete(struct mmap_action *action,
+			     struct vm_area_struct *vma)
+{
+	int err = 0;
+
+	switch (action->type) {
+	case MMAP_NOTHING:
+		break;
+	case MMAP_REMAP_PFN:
+		VM_WARN_ON_ONCE((vma->vm_flags & VM_REMAP_FLAGS) !=
+				VM_REMAP_FLAGS);
+
+		err = remap_pfn_range_complete(vma, action->remap.addr,
+				action->remap.pfn, action->remap.size,
+				action->remap.pgprot);
+
+		break;
+	case MMAP_INSERT_MIXED:
+	{
+		unsigned long pgnum = 0;
+		unsigned long pfn = action->mixedmap.pfn;

mm/util.c void snapshot_page(struct page_snapshot *ps, const struct page *page) · line 1374

Quoted 10 lines
mm/util.c +10 -0
+		unsigned long addr = action->mixedmap.addr;
+		unsigned long vaddr = vma->vm_start;
+
+		VM_WARN_ON_ONCE(!(vma->vm_flags & VM_MIXEDMAP));
+
+		for (; pgnum < action->mixedmap.num_pages;
+		     pgnum++, pfn++, addr += PAGE_SIZE, vaddr += PAGE_SIZE) {
+			vm_fault_t vmf;
+
+			vmf = vmf_insert_mixed(vma, vaddr, addr);
                                                          ^^^^^

Should this be pfn instead of addr?

-chris

#22 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 109 lines · Chris Mason

Hi Lorzeno,

Quoted 60 lines · Lorenzo Stoakes

Some drivers/filesystems need to perform additional tasks after the VMA is set up. This is typically in the form of pre-population.

The forms of pre-population most likely to be performed are a PFN remap or insertion of a mixed map, so we provide this functionality, ensuring that we perform the appropriate actions at the appropriate time - that is setting flags at the point of .mmap_prepare, and performing the actual remap at the point at which the VMA is fully established.

This prevents the driver from doing anything too crazy with a VMA at any stage, and we retain complete control over how the mm functionality is applied.

Unfortunately callers still do often require some kind of custom action, so we add an optional success/error _hook to allow the caller to do something after the action has succeeded or failed.

This is done at the point when the VMA has already been established, so the harm that can be done is limited.

The error hook can be used to filter errors if necessary.

We implement actions as abstracted from the vm_area_desc, so we provide the ability for custom hooks to invoke actions distinct from the vma descriptor.

If any error arises on these final actions, we simply unmap the VMA altogether.

Also update the stacked filesystem compatibility layer to utilise the action behaviour, and update the VMA tests accordingly.

For drivers which perform truly custom logic, we provide a custom action hook which is invoked at the point of action execution.

This can then, in turn, update the desc object and perform other actions, such as partially remapping ranges for instance. We export vma_desc_action_prepare() and vma_desc_action_complete() for drivers to do this.

This is performed at a stage where the VMA is already established, immediately prior to mapping completion, so it is considerably less problematic than a general mmap hook.

Note that at the point of the action being taken, the VMA is visible via the rmap, only the VMA write lock is held, so if anything needs to access the VMA, it is able to.

Essentially the action is taken as if it were performed after the mapping, but is kept atomic with VMA state.

---
 include/linux/mm.h               |  30 ++++++
 include/linux/mm_types.h         |  61 ++++++++++++
 mm/util.c                        | 150 +++++++++++++++++++++++++++-
 mm/vma.c                         |  70 ++++++++-----
 tools/testing/vma/vma_internal.h | 164 ++++++++++++++++++++++++++++++-
 5 files changed, 447 insertions(+), 28 deletions(-)

[ ... ]

Quoted 32 lines
mm/util.c +32 -0
+/**
+ * mmap_action_complete - Execute VMA descriptor action.
+ * @action: The action to perform.
+ * @vma: The VMA to perform the action upon.
+ *
+ * Similar to mmap_action_prepare(), other than internal mm usage this is
+ * intended for mmap_prepare users who implement a custom hook - with this
+ * function being called from the custom hook itself.
+ *
+ * Return: 0 on success, or error, at which point the VMA will be unmapped.
+ */
+int mmap_action_complete(struct mmap_action *action,
+			     struct vm_area_struct *vma)
+{
+	int err = 0;
+
+	switch (action->type) {
+	case MMAP_NOTHING:
+		break;
+	case MMAP_REMAP_PFN:
+		VM_WARN_ON_ONCE((vma->vm_flags & VM_REMAP_FLAGS) !=
+				VM_REMAP_FLAGS);
+
+		err = remap_pfn_range_complete(vma, action->remap.addr,
+				action->remap.pfn, action->remap.size,
+				action->remap.pgprot);
+
+		break;
+	case MMAP_INSERT_MIXED:
+	{
+		unsigned long pgnum = 0;
+		unsigned long pfn = action->mixedmap.pfn;

mm/util.c void snapshot_page(struct page_snapshot *ps, const struct page *page) · line 1374

Quoted 10 lines
mm/util.c +10 -0
+		unsigned long addr = action->mixedmap.addr;
+		unsigned long vaddr = vma->vm_start;
+
+		VM_WARN_ON_ONCE(!(vma->vm_flags & VM_MIXEDMAP));
+
+		for (; pgnum < action->mixedmap.num_pages;
+		     pgnum++, pfn++, addr += PAGE_SIZE, vaddr += PAGE_SIZE) {
+			vm_fault_t vmf;
+
+			vmf = vmf_insert_mixed(vma, vaddr, addr);
                                                          ^^^^^
Quoted 1 line

Should this be pfn instead of addr?

Yeah, sigh, this is a direct product of cramfs seemingly having a bug where it was passing PA's and not PFNs.

I thought I had fixed this but clearly I missed this here.

Let me send a fix-patch!

Quoted 2 lines

-chris

Cheers, Lorenzo

#23 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

In reply to Lorenzo Stoakes

Hi Andrew,

Could you apply the below fixpatch?

Thanks, Lorenzo

----8<----
From 35b96b949b44397c744b18f10b40a9989d4a92d2 Mon Sep 17 00:00:00 2001
From: Lorenzo Stoakes <[email protected]>
Date: Mon, 15 Sep 2025 11:01:06 +0100
Subject: [PATCH] mm: fix incorrect mixedmap implementation

This was typo'd due to staring too long at the cramfs implementation.

---
 mm/util.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
mm/util.c +2 -3
index 9bfef9509d35..23a2ec675344 100644
@@ -1364,15 +1364,14 @@ int mmap_action_complete(struct mmap_action *action,
 		unsigned long pgnum = 0;
 		unsigned long pfn = action->mixedmap.pfn;
 		unsigned long addr = action->mixedmap.addr;
-		unsigned long vaddr = vma->vm_start;
 
 		VM_WARN_ON_ONCE(!(vma->vm_flags & VM_MIXEDMAP));
 
 		for (; pgnum < action->mixedmap.num_pages;
-		    pgnum++, pfn++, addr += PAGE_SIZE, vaddr += PAGE_SIZE) {
+		    pgnum++, pfn++, addr += PAGE_SIZE) {
 			vm_fault_t vmf;
 
-			vmf = vmf_insert_mixed(vma, vaddr, addr);
+			vmf = vmf_insert_mixed(vma, addr, pfn);
 			if (vmf & VM_FAULT_ERROR) {
 				err = vm_fault_to_errno(vmf, 0);
 				break;

--
2.51.0

#24 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

In reply to Lorenzo Stoakes

include/linux/mm.h static inline unsigned long vma_desc_pages(struct vm_area_desc *desc) · line 3610

Quoted 11 lines · Lorenzo Stoakes
include/linux/mm.h +11 -0
+static inline void mmap_action_remap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t pgprot)
+{
+	action->type = MMAP_REMAP_PFN;
+
+	action->remap.addr = addr;
+	action->remap.pfn = pfn;
+	action->remap.size = size;
+	action->remap.pgprot = pgprot;
+}

These helpers drivers are supposed to call really should have kdocs.

Especially since 'addr' is sort of ambigous.

And I'm wondering why they don't take in the vm_area_desc? Eg shouldn't we be strongly discouraging using anything other than vma->vm_page_prot as the last argument?

I'd probably also have a small helper wrapper for the very common case of whole vma:

/* Fill the entire VMA with pfns starting at pfn. Caller must have
* already checked desc has an appropriate size */
mmap_action_remap_full(struct vm_area_desc *desc, unsigned long pfn)

It is not normal for a driver to partially populate a VMA, lets call those out as something weird.

mm/util.c void snapshot_page(struct page_snapshot *ps, const struct page *page) · line 1292

Quoted 8 lines
mm/util.c +8 -0
+struct page **mmap_action_mixedmap_pages(struct mmap_action *action,
+		unsigned long addr, unsigned long num_pages)
+{
+	struct page **pages;
+
+	pages = kmalloc_array(num_pages, sizeof(struct page *), GFP_KERNEL);
+	if (!pages)
+		return NULL;

This allocation seems like a shame, I doubt many places actually need it .. A callback to get each pfn would be better?

Jason

#25 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 15 lines · Jason Gunthorpe

include/linux/mm.h static inline unsigned long vma_desc_pages(struct vm_area_desc *desc) · line 3610

Quoted 11 lines · Lorenzo Stoakes
include/linux/mm.h +11 -0
+static inline void mmap_action_remap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t pgprot)
+{
+	action->type = MMAP_REMAP_PFN;
+
+	action->remap.addr = addr;
+	action->remap.pfn = pfn;
+	action->remap.size = size;
+	action->remap.pgprot = pgprot;
+}

These helpers drivers are supposed to call really should have kdocs.

Quoted 1 line

Especially since 'addr' is sort of ambigous.

OK.

Quoted 4 lines

And I'm wondering why they don't take in the vm_area_desc? Eg shouldn't we be strongly discouraging using anything other than vma->vm_page_prot as the last argument?

I need to abstract desc from action so custom handlers can perform sub-actions. It's unfortunate but there we go.

There'd be horrible confusion passing around a desc that has an action in it that you then ignore, otherwise. Better to abstract the concept of action altogether.

Quoted 7 lines

I'd probably also have a small helper wrapper for the very common case of whole vma:

/* Fill the entire VMA with pfns starting at pfn. Caller must have
* already checked desc has an appropriate size */
mmap_action_remap_full(struct vm_area_desc *desc, unsigned long pfn)

See above re: desc vs. action.

Quoted 4 lines

It is not normal for a driver to partially populate a VMA, lets call those out as something weird.

Quoted 11 lines

mm/util.c void snapshot_page(struct page_snapshot *ps, const struct page *page) · line 1292

Quoted 8 lines
mm/util.c +8 -0
+struct page **mmap_action_mixedmap_pages(struct mmap_action *action,
+		unsigned long addr, unsigned long num_pages)
+{
+	struct page **pages;
+
+	pages = kmalloc_array(num_pages, sizeof(struct page *), GFP_KERNEL);
+	if (!pages)
+		return NULL;

This allocation seems like a shame, I doubt many places actually need it .. A callback to get each pfn would be better?

It'd be hard to know how to get the context right that'd need to be supplied to the callback.

In kcov's case it'd be kcov->area + an offset.

So we'd need an offset parameter, the struct file *, whatever else to be passed.

And then we'll find a driver where that doesn't work and we're screwed.

I don't think optimising for mmap setup is really important.

We can always go back and refactor things later once this pattern is established.

And again with ~230 odd drivers to update, I'd rather keep things as simple as possible for now.

Quoted 2 lines

Jason

Cheers, Lorenzo

#26 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 21 lines · Lorenzo Stoakes
Quoted 15 lines · Jason Gunthorpe

include/linux/mm.h static inline unsigned long vma_desc_pages(struct vm_area_desc *desc) · line 3610

Quoted 11 lines · Lorenzo Stoakes
include/linux/mm.h +11 -0
+static inline void mmap_action_remap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t pgprot)
+{
+	action->type = MMAP_REMAP_PFN;
+
+	action->remap.addr = addr;
+	action->remap.pfn = pfn;
+	action->remap.size = size;
+	action->remap.pgprot = pgprot;
+}

These helpers drivers are supposed to call really should have kdocs.

Quoted 1 line

Especially since 'addr' is sort of ambigous.

OK.

Quoted 1 line
Quoted 6 lines
Quoted 3 lines

And I'm wondering why they don't take in the vm_area_desc? Eg shouldn't we be strongly discouraging using anything other than vma->vm_page_prot as the last argument?

I need to abstract desc from action so custom handlers can perform sub-actions. It's unfortunate but there we go.

Why? I don't see this as required

Just mark the functions as manipulating the action using the 'action' in the fuction name.

Quoted 8 lines
Quoted 6 lines

I'd probably also have a small helper wrapper for the very common case of whole vma:

/* Fill the entire VMA with pfns starting at pfn. Caller must have
* already checked desc has an appropriate size */
mmap_action_remap_full(struct vm_area_desc *desc, unsigned long pfn)

See above re: desc vs. action.

Yet, this is the API most places actually want.

Quoted 4 lines

It'd be hard to know how to get the context right that'd need to be supplied to the callback.

In kcov's case it'd be kcov->area + an offset.

Just use pgoff

Quoted 2 lines

So we'd need an offset parameter, the struct file *, whatever else to be passed.

Yes

Quoted 1 line

And then we'll find a driver where that doesn't work and we're screwed.

Bah, you keep saying that but we also may never even find one.

Jason

#27 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 26 lines · Jason Gunthorpe
Quoted 25 lines · Lorenzo Stoakes
Quoted 15 lines · Jason Gunthorpe

include/linux/mm.h static inline unsigned long vma_desc_pages(struct vm_area_desc *desc) · line 3610

Quoted 11 lines · Lorenzo Stoakes
include/linux/mm.h +11 -0
+static inline void mmap_action_remap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t pgprot)
+{
+	action->type = MMAP_REMAP_PFN;
+
+	action->remap.addr = addr;
+	action->remap.pfn = pfn;
+	action->remap.size = size;
+	action->remap.pgprot = pgprot;
+}

These helpers drivers are supposed to call really should have kdocs.

Quoted 1 line

Especially since 'addr' is sort of ambigous.

OK.

Quoted 4 lines

And I'm wondering why they don't take in the vm_area_desc? Eg shouldn't we be strongly discouraging using anything other than vma->vm_page_prot as the last argument?

Quoted 7 lines
Quoted 2 lines

I need to abstract desc from action so custom handlers can perform sub-actions. It's unfortunate but there we go.

Why? I don't see this as required

Just mark the functions as manipulating the action using the 'action' in the fuction name.

Because now sub-callers that partially map using one method and partially map using another now need to have a desc too that they have to 'just know' which fields to update or artificially set up.

The vmcore case does something like this.

Instead, we have actions where it's 100% clear what's going to happen.

Quoted 19 lines
Quoted 9 lines
Quoted 7 lines

I'd probably also have a small helper wrapper for the very common case of whole vma:

/* Fill the entire VMA with pfns starting at pfn. Caller must have
* already checked desc has an appropriate size */
mmap_action_remap_full(struct vm_area_desc *desc, unsigned long pfn)

See above re: desc vs. action.

Yet, this is the API most places actually want.

Quoted 4 lines

It'd be hard to know how to get the context right that'd need to be supplied to the callback.

In kcov's case it'd be kcov->area + an offset.

Just use pgoff

Quoted 8 lines
Quoted 2 lines

So we'd need an offset parameter, the struct file *, whatever else to be passed.

Yes

Quoted 1 line

And then we'll find a driver where that doesn't work and we're screwed.

Bah, you keep saying that but we also may never even find one.

OK let me try something like this, then. I guess I can update it later if we discover such a dirver.

Quoted 2 lines

Jason

Cheers, Lorenzo

#28 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 6 lines · Lorenzo Stoakes
Quoted 2 lines

Just mark the functions as manipulating the action using the 'action' in the fuction name.

Because now sub-callers that partially map using one method and partially map using another now need to have a desc too that they have to 'just know' which fields to update or artificially set up.

Huh? There is only on desc->action, how can you have more than one action with this scheme?

One action is the right thing anyhow, we can't meaningfully mix different action types in the same VMA. That's nonsense.

You may need more flexible ways to get the address lists down the road because not every driver will be contiguous, but that should still be one action.

Quoted 1 line

The vmcore case does something like this.

vmcore is a true MIXEDMAP, it isn't doing two actions. These mixedmap helpers just aren't good for what mixedmap needs.. Mixed map need a list of physical pfns with a bit indicating if they are "special" or not. If you do it with a callback or a kmalloc allocation it doesn't matter.

vmcore would then populate that list with its mixture of special and non-sepcial memory and do a single mixedmem action.

I think this series should drop the mixedmem stuff, it is the most complicated action type. A vmalloc_user action is better for kcov.

And maybe that is just a comment overall. This would be nicer if each series focused on adding one action with a three-four mmap users converted to use it as an example case.

Eg there are not that many places calling vmalloc_user(), a single series could convert alot of them.

If you did it this way we'd discover that there are already helpers for vmalloc_user():

	return remap_vmalloc_range(vma, mdev_state->memblk, 0);

And kcov looks buggy to not be using it already. The above gets the VMA type right and doesn't force mixedmap :)

Then the series goals are a bit better we can actually fully convert and remove things like remap_vmalloc_range() in single series. That looks feasible to me.

Jason

#29 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 10 lines · Jason Gunthorpe
Quoted 6 lines · Lorenzo Stoakes
Quoted 2 lines

Just mark the functions as manipulating the action using the 'action' in the fuction name.

Because now sub-callers that partially map using one method and partially map using another now need to have a desc too that they have to 'just know' which fields to update or artificially set up.

Huh? There is only on desc->action, how can you have more than one action with this scheme?

Because you use a custom hook that can in turn perform actions? As I've implemented for vmcore?

Quoted 3 lines

One action is the right thing anyhow, we can't meaningfully mix different action types in the same VMA. That's nonsense.

OK, except that's how 'true' mixed maps work though right? As vmcore is doing?

Quoted 5 lines

You may need more flexible ways to get the address lists down the road because not every driver will be contiguous, but that should still be one action.

Quoted 7 lines
Quoted 1 line

The vmcore case does something like this.

vmcore is a true MIXEDMAP, it isn't doing two actions. These mixedmap helpers just aren't good for what mixedmap needs.. Mixed map need a list of physical pfns with a bit indicating if they are "special" or not. If you do it with a callback or a kmalloc allocation it doesn't matter.

Well it's a mix of actions to accomodate PFNs and normal pages as implemented via a custom hook that can invoke each.

Quoted 3 lines

vmcore would then populate that list with its mixture of special and non-sepcial memory and do a single mixedmem action.

I'm confused as to why you say a helper would be no good here, then go on to delineate how a helper could work...

Quoted 3 lines

I think this series should drop the mixedmem stuff, it is the most complicated action type. A vmalloc_user action is better for kcov.

Fine, I mean if we could find a way to explicitly just give a list of stuff to map that'd be _great_ vs. having a custom hook.

If we can avoid custom hooks altogether that'd be ideal.

Anyway I'll drop the mixed map stuff, fine.

Quoted 4 lines

And maybe that is just a comment overall. This would be nicer if each series focused on adding one action with a three-four mmap users converted to use it as an example case.

In future series I'll try to group by the action type.

This series is _setting up this to be a possibility at all_.

The idea was that I could put fundamentals in that should cover most cases, I could then go on to implement them in (relative) peace...

I mean once I drop the mixed map stuff, and refactor to vmalloc_user(), then we are pretty much doing that, modulo a single vmalloc_user() case.

So maybe I should drop the vmalloc_user() bits too and make this a remap-only change...

But I don't want to tackle _all_ remap cases here.

I want to add this functionality in and have it ready for next cycle (yeah not so sure about that now...) so I can then do follow up work.

Am trying to do it before Kernel Recipes which I'll be at and then a (very very very needed) couple weeks vacaation.

Anyway maybe if I simplify there's still a shot at this landing in time...

Quoted 11 lines

Eg there are not that many places calling vmalloc_user(), a single series could convert alot of them.

If you did it this way we'd discover that there are already helpers for vmalloc_user():

	return remap_vmalloc_range(vma, mdev_state->memblk, 0);

And kcov looks buggy to not be using it already. The above gets the VMA type right and doesn't force mixedmap :)

Right, I mean maybe.

If I can take care of low hanging fruit relatively easily then maybe it'll be more practical to refactor the 'odd ones out'.

Quoted 4 lines

Then the series goals are a bit better we can actually fully convert and remove things like remap_vmalloc_range() in single series. That looks feasible to me.

Right.

I'd love to drop unused stuff earlier, so _that_ is not an unreasonable requirement.

Quoted 2 lines

Jason

I guess I'll do a respin then as per above.

Cheers, Lorenzo

#30 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 8 lines · Lorenzo Stoakes
Quoted 5 lines

vmcore is a true MIXEDMAP, it isn't doing two actions. These mixedmap helpers just aren't good for what mixedmap needs.. Mixed map need a list of physical pfns with a bit indicating if they are "special" or not. If you do it with a callback or a kmalloc allocation it doesn't matter.

Well it's a mix of actions to accomodate PFNs and normal pages as implemented via a custom hook that can invoke each.

No it's not a mix of actions. The mixedmap helpers are just wrong for actual mixedmap usage:

+static inline void mmap_action_remap(struct mmap_action *action,
+ unsigned long addr, unsigned long pfn, unsigned long size,
+ pgprot_t pgprot)
+
+static inline void mmap_action_mixedmap(struct mmap_action *action,
+ unsigned long addr, unsigned long pfn, unsigned long num_pages)

Mixed map is a list of PFNs and a flag if the PFN is special or not. That's what makes mixed map different from the other mapping cases.

One action per VMA, and mixed map is handled by supporting the above lis tin some way.

Quoted 5 lines
Quoted 2 lines

I think this series should drop the mixedmem stuff, it is the most complicated action type. A vmalloc_user action is better for kcov.

Fine, I mean if we could find a way to explicitly just give a list of stuff to map that'd be _great_ vs. having a custom hook.

You already proposed to allocate memory to hold an array, I suggested to have a per-range callback. Either could work as an API for mixedmap.

Quoted 2 lines

So maybe I should drop the vmalloc_user() bits too and make this a remap-only change...

Sure

Quoted 1 line

But I don't want to tackle _all_ remap cases here.

Due 4-5 or something to show the API is working. Things like my remark to have a better helper that does whole-vma only should show up more clearly with a few more conversions.

It is generally a good idea when doing these reworks to look across all the use cases patterns and try to simplify them. This is why a series per pattern is a good idea because you are saying you found a pattern, and here are N examples of the pattern to prove it.

Eg if a huge number of drivers are just mmaping a linear range of memory with a fixed pgoff then a helper to support exactly that pattern with minimal driver code should be developed.

Like below, apparently vmalloc_user() is already a pattern and already has a simplifying safe helper.

Quoted 1 line

Anyway maybe if I simplify there's still a shot at this landing in time...

Simplify is always good to help things get merged :)

Quoted 6 lines
Quoted 6 lines

Eg there are not that many places calling vmalloc_user(), a single series could convert alot of them.

If you did it this way we'd discover that there are already helpers for vmalloc_user():

Quoted 6 lines
Quoted 4 lines
	return remap_vmalloc_range(vma, mdev_state->memblk, 0);

And kcov looks buggy to not be using it already. The above gets the VMA type right and doesn't force mixedmap :)

Right, I mean maybe.

Maybe send out a single patch to change kcov to remap_vmalloc_range() for this cycle? Answer the maybe?

Jason

#31 lore raw

Re: [PATCH v2 08/16] mm: add ability to take further action in vm_area_desc

Quoted 20 lines · Jason Gunthorpe
Quoted 8 lines · Lorenzo Stoakes
Quoted 5 lines

vmcore is a true MIXEDMAP, it isn't doing two actions. These mixedmap helpers just aren't good for what mixedmap needs.. Mixed map need a list of physical pfns with a bit indicating if they are "special" or not. If you do it with a callback or a kmalloc allocation it doesn't matter.

Well it's a mix of actions to accomodate PFNs and normal pages as implemented via a custom hook that can invoke each.

No it's not a mix of actions. The mixedmap helpers are just wrong for actual mixedmap usage:

(quoted diff) +6 -0
+static inline void mmap_action_remap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long size,
+		pgprot_t pgprot)
+
+static inline void mmap_action_mixedmap(struct mmap_action *action,
+		unsigned long addr, unsigned long pfn, unsigned long num_pages)
Quoted 6 lines

Mixed map is a list of PFNs and a flag if the PFN is special or not. That's what makes mixed map different from the other mapping cases.

One action per VMA, and mixed map is handled by supporting the above lis tin some way.

I don't think any of the above is really useful for me to respond to, I think you've misunderstood what I'm saying, but it doesn't really matter because I agree that the interface you propose is better for mixed map.

Quoted 10 lines
Quoted 6 lines
Quoted 3 lines

I think this series should drop the mixedmem stuff, it is the most complicated action type. A vmalloc_user action is better for kcov.

Fine, I mean if we could find a way to explicitly just give a list of stuff to map that'd be _great_ vs. having a custom hook.

You already proposed to allocate memory to hold an array, I suggested to have a per-range callback. Either could work as an API for mixedmap.

Again, I think you've misunderstood me, but it's moot, because I agree, this kind of interface is better.

Quoted 11 lines
Quoted 3 lines

So maybe I should drop the vmalloc_user() bits too and make this a remap-only change...

Sure

Quoted 1 line

But I don't want to tackle _all_ remap cases here.

Due 4-5 or something to show the API is working. Things like my remark to have a better helper that does whole-vma only should show up more clearly with a few more conversions.

I was trying to limit to mm or mm-adjacent as per the cover letter.

But sure I will do that.

Quoted 2 lines

It is generally a good idea when doing these reworks to look across

It's not a rework :) cover letter describes why I'm doing this.

Quoted 7 lines

all the use cases patterns and try to simplify them. This is why a series per pattern is a good idea because you are saying you found a pattern, and here are N examples of the pattern to prove it.

Eg if a huge number of drivers are just mmaping a linear range of memory with a fixed pgoff then a helper to support exactly that pattern with minimal driver code should be developed.

Fine in spirit, let's be pragmatic also though.

Again this isn't a refactoring exercise. But I agree we should try to get the API right as best we can.

Quoted 7 lines

Like below, apparently vmalloc_user() is already a pattern and already has a simplifying safe helper.

Quoted 1 line

Anyway maybe if I simplify there's still a shot at this landing in time...

Simplify is always good to help things get merged :)

Yup :)

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

Eg there are not that many places calling vmalloc_user(), a single series could convert alot of them.

If you did it this way we'd discover that there are already helpers for vmalloc_user():

	return remap_vmalloc_range(vma, mdev_state->memblk, 0);
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

And kcov looks buggy to not be using it already. The above gets the VMA type right and doesn't force mixedmap :)

Right, I mean maybe.

Maybe send out a single patch to change kcov to remap_vmalloc_range() for this cycle? Answer the maybe?

Sure I can probably do that.

The question is time and, because most of my days are full of review as per my self-inflicted^W -selected role as a maintainer.

This series will be the priority obviously :)

Quoted 2 lines

Jason

Cheers, Lorenzo

#32 lore raw

PATCH v2 9/16 doc: update porting, vfs documentation for mmap_prepare actions

In reply to Lorenzo Stoakes

Now we have introduced the ability to specify that actions should be taken after a VMA is established via the vm_area_desc->action field as specified in mmap_prepare, update both the VFS documentation and the porting guide to describe this.

---
 Documentation/filesystems/porting.rst | 5 +++++
 Documentation/filesystems/vfs.rst     | 4 ++++
 2 files changed, 9 insertions(+)
Documentation/filesystems/porting.rst +5 -0
index 85f590254f07..6743ed0b9112 100644
@@ -1285,3 +1285,8 @@ rather than a VMA, as the VMA at this stage is not yet valid.
 The vm_area_desc provides the minimum required information for a filesystem
 to initialise state upon memory mapping of a file-backed region, and output
 parameters for the file system to set this state.
+
+In nearly all cases, this is all that is required for a filesystem. However, if
+a filesystem needs to perform an operation such a pre-population of page tables,
+then that action can be specified in the vm_area_desc->action field, which can
+be configured using the mmap_action_*() helpers.
Documentation/filesystems/vfs.rst +4 -0
index 486a91633474..9e96c46ee10e 100644
@@ -1236,6 +1236,10 @@ otherwise noted.
 	file-backed memory mapping, most notably establishing relevant
 	private state and VMA callbacks.
 
+	If further action such as pre-population of page tables is required,
+	this can be specified by the vm_area_desc->action field and related
+	parameters.
+
 Note that the file operations are implemented by the specific
 filesystem in which the inode resides.  When opening a device node
 (character or block special) most filesystems will call special
Signature · 1 line
2.51.0
maintainer Reviewed-by on v2 9/16
#33 lore raw

Re: [PATCH v2 09/16] doc: update porting, vfs documentation for mmap_prepare actions

Quoted 6 lines · Lorenzo Stoakes

Now we have introduced the ability to specify that actions should be taken after a VMA is established via the vm_area_desc->action field as specified in mmap_prepare, update both the VFS documentation and the porting guide to describe this.

Looks good. Feel free to add:

Honza

Quoted 36 lines
---
 Documentation/filesystems/porting.rst | 5 +++++
 Documentation/filesystems/vfs.rst     | 4 ++++
 2 files changed, 9 insertions(+)
Documentation/filesystems/porting.rst +5 -0
index 85f590254f07..6743ed0b9112 100644
@@ -1285,3 +1285,8 @@ rather than a VMA, as the VMA at this stage is not yet valid.
 The vm_area_desc provides the minimum required information for a filesystem
 to initialise state upon memory mapping of a file-backed region, and output
 parameters for the file system to set this state.
+
+In nearly all cases, this is all that is required for a filesystem. However, if
+a filesystem needs to perform an operation such a pre-population of page tables,
+then that action can be specified in the vm_area_desc->action field, which can
+be configured using the mmap_action_*() helpers.
Documentation/filesystems/vfs.rst +4 -0
index 486a91633474..9e96c46ee10e 100644
@@ -1236,6 +1236,10 @@ otherwise noted.
 	file-backed memory mapping, most notably establishing relevant
 	private state and VMA callbacks.
 
+	If further action such as pre-population of page tables is required,
+	this can be specified by the vm_area_desc->action field and related
+	parameters.
+
 Note that the file operations are implemented by the specific
 filesystem in which the inode resides.  When opening a device node
 (character or block special) most filesystems will call special
Signature · 1 line
2.51.0
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
#34 lore raw

Re: [PATCH v2 09/16] doc: update porting, vfs documentation for mmap_prepare actions

Quoted 11 lines · Jan Kara
Quoted 6 lines · Lorenzo Stoakes

Now we have introduced the ability to specify that actions should be taken after a VMA is established via the vm_area_desc->action field as specified in mmap_prepare, update both the VFS documentation and the porting guide to describe this.

Looks good. Feel free to add:

Thanks for this and all previous tags! :)

Cheers, Lorenzo

#35 lore raw

PATCH v2 10/16 mm/hugetlbfs: update hugetlbfs to use mmap_prepare

In reply to Lorenzo Stoakes

Since we can now perform actions after the VMA is established via mmap_prepare, use desc->action_success_hook to set up the hugetlb lock once the VMA is setup.

We also make changes throughout hugetlbfs to make this possible.

---
 fs/hugetlbfs/inode.c           | 30 +++++++------
 include/linux/hugetlb.h        |  9 +++-
 include/linux/hugetlb_inline.h | 15 ++++---
 mm/hugetlb.c                   | 77 ++++++++++++++++++++--------------
 4 files changed, 79 insertions(+), 52 deletions(-)
fs/hugetlbfs/inode.c +17 -13
index 3cfdf4091001..026bcc65bb79 100644
@@ -96,8 +96,9 @@ static const struct fs_parameter_spec hugetlb_fs_parameters[] = {
 #define PGOFF_LOFFT_MAX \
 	(((1UL << (PAGE_SHIFT + 1)) - 1) <<  (BITS_PER_LONG - (PAGE_SHIFT + 1)))
 
-static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
+static int hugetlbfs_file_mmap_prepare(struct vm_area_desc *desc)
 {
+	struct file *file = desc->file;
 	struct inode *inode = file_inode(file);
 	loff_t len, vma_len;
 	int ret;
@@ -112,8 +113,8 @@ static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
 	 * way when do_mmap unwinds (may be important on powerpc
 	 * and ia64).
 	 */
-	vm_flags_set(vma, VM_HUGETLB | VM_DONTEXPAND);
-	vma->vm_ops = &hugetlb_vm_ops;
+	desc->vm_flags |= VM_HUGETLB | VM_DONTEXPAND;
+	desc->vm_ops = &hugetlb_vm_ops;
 
 	/*
 	 * page based offset in vm_pgoff could be sufficiently large to
@@ -122,16 +123,16 @@ static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
 	 * sizeof(unsigned long).  So, only check in those instances.
 	 */
 	if (sizeof(unsigned long) == sizeof(loff_t)) {
-		if (vma->vm_pgoff & PGOFF_LOFFT_MAX)
+		if (desc->pgoff & PGOFF_LOFFT_MAX)
 			return -EINVAL;
 	}
 
 	/* must be huge page aligned */
-	if (vma->vm_pgoff & (~huge_page_mask(h) >> PAGE_SHIFT))
+	if (desc->pgoff & (~huge_page_mask(h) >> PAGE_SHIFT))
 		return -EINVAL;
 
-	vma_len = (loff_t)(vma->vm_end - vma->vm_start);
-	len = vma_len + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
+	vma_len = (loff_t)vma_desc_size(desc);
+	len = vma_len + ((loff_t)desc->pgoff << PAGE_SHIFT);
 	/* check for overflow */
 	if (len < vma_len)
 		return -EINVAL;
@@ -141,7 +142,7 @@ static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
 
 	ret = -ENOMEM;
 
-	vm_flags = vma->vm_flags;
+	vm_flags = desc->vm_flags;
 	/*
 	 * for SHM_HUGETLB, the pages are reserved in the shmget() call so skip
 	 * reserving here. Note: only for SHM hugetlbfs file, the inode
@@ -151,17 +152,20 @@ static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
 		vm_flags |= VM_NORESERVE;
 
 	if (hugetlb_reserve_pages(inode,
-				vma->vm_pgoff >> huge_page_order(h),
-				len >> huge_page_shift(h), vma,
-				vm_flags) < 0)
+			desc->pgoff >> huge_page_order(h),
+			len >> huge_page_shift(h), desc,
+			vm_flags) < 0)
 		goto out;
 
 	ret = 0;
-	if (vma->vm_flags & VM_WRITE && inode->i_size < len)
+	if ((desc->vm_flags & VM_WRITE) && inode->i_size < len)
 		i_size_write(inode, len);
 out:
 	inode_unlock(inode);
 
+	/* Allocate the VMA lock after we set it up. */
+	if (!ret)
+		desc->action.success_hook = hugetlb_vma_lock_alloc;
 	return ret;
 }
 
@@ -1219,7 +1223,7 @@ static void init_once(void *foo)
 
 static const struct file_operations hugetlbfs_file_operations = {
 	.read_iter		= hugetlbfs_read_iter,
-	.mmap			= hugetlbfs_file_mmap,
+	.mmap_prepare		= hugetlbfs_file_mmap_prepare,
 	.fsync			= noop_fsync,
 	.get_unmapped_area	= hugetlb_get_unmapped_area,
 	.llseek			= default_llseek,
include/linux/hugetlb.h +7 -2
index 526d27e88b3b..b39f2b70ccab 100644
@@ -150,8 +150,7 @@ int hugetlb_mfill_atomic_pte(pte_t *dst_pte,
 			     struct folio **foliop);
 #endif /* CONFIG_USERFAULTFD */
 long hugetlb_reserve_pages(struct inode *inode, long from, long to,
-						struct vm_area_struct *vma,
-						vm_flags_t vm_flags);
+			   struct vm_area_desc *desc, vm_flags_t vm_flags);
 long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
 						long freed);
 bool folio_isolate_hugetlb(struct folio *folio, struct list_head *list);
@@ -280,6 +279,7 @@ bool is_hugetlb_entry_hwpoisoned(pte_t pte);
 void hugetlb_unshare_all_pmds(struct vm_area_struct *vma);
 void fixup_hugetlb_reservations(struct vm_area_struct *vma);
 void hugetlb_split(struct vm_area_struct *vma, unsigned long addr);
+int hugetlb_vma_lock_alloc(struct vm_area_struct *vma);
 
 #else /* !CONFIG_HUGETLB_PAGE */
 
@@ -466,6 +466,11 @@ static inline void fixup_hugetlb_reservations(struct vm_area_struct *vma)
 
 static inline void hugetlb_split(struct vm_area_struct *vma, unsigned long addr) {}
 
+static inline int hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
+{
+	return 0;
+}
+
 #endif /* !CONFIG_HUGETLB_PAGE */
 
 #ifndef pgd_write
include/linux/hugetlb_inline.h +10 -5
index 0660a03d37d9..a27aa0162918 100644
@@ -2,22 +2,27 @@
 #ifndef _LINUX_HUGETLB_INLINE_H
 #define _LINUX_HUGETLB_INLINE_H
 
-#ifdef CONFIG_HUGETLB_PAGE
-
 #include <linux/mm.h>
 
-static inline bool is_vm_hugetlb_page(struct vm_area_struct *vma)
+#ifdef CONFIG_HUGETLB_PAGE
+
+static inline bool is_vm_hugetlb_flags(vm_flags_t vm_flags)
 {
-	return !!(vma->vm_flags & VM_HUGETLB);
+	return !!(vm_flags & VM_HUGETLB);
 }
 
 #else
 
-static inline bool is_vm_hugetlb_page(struct vm_area_struct *vma)
+static inline bool is_vm_hugetlb_flags(vm_flags_t vm_flags)
 {
 	return false;
 }
 
 #endif
 
+static inline bool is_vm_hugetlb_page(struct vm_area_struct *vma)
+{
+	return is_vm_hugetlb_flags(vma->vm_flags);
+}
+
 #endif
mm/hugetlb.c +45 -32

176 lines not on this page · raw message

Signature · 1 line
2.51.0
#36 lore raw

PATCH v2 11/16 mm: update mem char driver to use mmap_prepare

In reply to Lorenzo Stoakes

Update the mem char driver (backing /dev/mem and /dev/zero) to use f_op->mmap_prepare hook rather than the deprecated f_op->mmap.

The /dev/zero implementation has a very unique and rather concerning characteristic in that it converts MAP_PRIVATE mmap() mappings anonymous when they are, in fact, not.

The new f_op->mmap_prepare() can support this, but rather than introducing a helper function to perform this hack (and risk introducing other users), simply set desc->vm_op to NULL here and add a comment describing what's going on.

We also introduce shmem_zero_setup_desc() to allow for the shared mapping case via an f_op->mmap_prepare() hook, and generalise the code between this and shmem_zero_setup().

We also use the desc->action_error_hook to filter the remap error to -EAGAIN to keep behaviour consistent.

---
 drivers/char/mem.c       | 75 ++++++++++++++++++++++------------------
 include/linux/shmem_fs.h |  3 +-
 mm/shmem.c               | 40 ++++++++++++++++-----
 3 files changed, 76 insertions(+), 42 deletions(-)
drivers/char/mem.c +42 -33
index 34b815901b20..23194788ee41 100644
@@ -304,13 +304,13 @@ static unsigned zero_mmap_capabilities(struct file *file)
 }
 
 /* can't do an in-place private mapping if there's no MMU */
-static inline int private_mapping_ok(struct vm_area_struct *vma)
+static inline int private_mapping_ok(struct vm_area_desc *desc)
 {
-	return is_nommu_shared_mapping(vma->vm_flags);
+	return is_nommu_shared_mapping(desc->vm_flags);
 }
 #else
 
-static inline int private_mapping_ok(struct vm_area_struct *vma)
+static inline int private_mapping_ok(struct vm_area_desc *desc)
 {
 	return 1;
 }
@@ -322,46 +322,50 @@ static const struct vm_operations_struct mmap_mem_ops = {
 #endif
 };
 
-static int mmap_mem(struct file *file, struct vm_area_struct *vma)
+static int mmap_filter_error(int err)
 {
-	size_t size = vma->vm_end - vma->vm_start;
-	phys_addr_t offset = (phys_addr_t)vma->vm_pgoff << PAGE_SHIFT;
+	return -EAGAIN;
+}
+
+static int mmap_mem_prepare(struct vm_area_desc *desc)
+{
+	struct file *file = desc->file;
+	const size_t size = vma_desc_size(desc);
+	const phys_addr_t offset = (phys_addr_t)desc->pgoff << PAGE_SHIFT;
 
 	/* Does it even fit in phys_addr_t? */
-	if (offset >> PAGE_SHIFT != vma->vm_pgoff)
+	if (offset >> PAGE_SHIFT != desc->pgoff)
 		return -EINVAL;
 
 	/* It's illegal to wrap around the end of the physical address space. */
 	if (offset + (phys_addr_t)size - 1 < offset)
 		return -EINVAL;
 
-	if (!valid_mmap_phys_addr_range(vma->vm_pgoff, size))
+	if (!valid_mmap_phys_addr_range(desc->pgoff, size))
 		return -EINVAL;
 
-	if (!private_mapping_ok(vma))
+	if (!private_mapping_ok(desc))
 		return -ENOSYS;
 
-	if (!range_is_allowed(vma->vm_pgoff, size))
+	if (!range_is_allowed(desc->pgoff, size))
 		return -EPERM;
 
-	if (!phys_mem_access_prot_allowed(file, vma->vm_pgoff, size,
-						&vma->vm_page_prot))
+	if (!phys_mem_access_prot_allowed(file, desc->pgoff, size,
+					  &desc->page_prot))
 		return -EINVAL;
 
-	vma->vm_page_prot = phys_mem_access_prot(file, vma->vm_pgoff,
-						 size,
-						 vma->vm_page_prot);
+	desc->page_prot = phys_mem_access_prot(file, desc->pgoff,
+					       size,
+					       desc->page_prot);
 
-	vma->vm_ops = &mmap_mem_ops;
+	desc->vm_ops = &mmap_mem_ops;
 
 	/* Remap-pfn-range will mark the range VM_IO */
-	if (remap_pfn_range(vma,
-			    vma->vm_start,
-			    vma->vm_pgoff,
-			    size,
-			    vma->vm_page_prot)) {
-		return -EAGAIN;
-	}
+	mmap_action_remap(&desc->action, desc->start, desc->pgoff, size,
+			desc->page_prot);
+	/* We filter remap errors to -EAGAIN. */
+	desc->action.error_hook = mmap_filter_error;
+
 	return 0;
 }
 
@@ -501,14 +505,18 @@ static ssize_t read_zero(struct file *file, char __user *buf,
 	return cleared;
 }
 
-static int mmap_zero(struct file *file, struct vm_area_struct *vma)
+static int mmap_prepare_zero(struct vm_area_desc *desc)
 {
 #ifndef CONFIG_MMU
 	return -ENOSYS;
 #endif
-	if (vma->vm_flags & VM_SHARED)
-		return shmem_zero_setup(vma);
-	vma_set_anonymous(vma);
+	if (desc->vm_flags & VM_SHARED)
+		return shmem_zero_setup_desc(desc);
+	/*
+	 * This is a highly unique situation where we mark a MAP_PRIVATE mapping
+	 *of /dev/zero anonymous, despite it not being.
+	 */
+	desc->vm_ops = NULL;
 	return 0;
 }
 
@@ -526,10 +534,11 @@ static unsigned long get_unmapped_area_zero(struct file *file,
 {
 	if (flags & MAP_SHARED) {
 		/*
-		 * mmap_zero() will call shmem_zero_setup() to create a file,
-		 * so use shmem's get_unmapped_area in case it can be huge;
-		 * and pass NULL for file as in mmap.c's get_unmapped_area(),
-		 * so as not to confuse shmem with our handle on "/dev/zero".
+		 * mmap_prepare_zero() will call shmem_zero_setup() to create a
+		 * file, so use shmem's get_unmapped_area in case it can be
+		 * huge; and pass NULL for file as in mmap.c's
+		 * get_unmapped_area(), so as not to confuse shmem with our
+		 * handle on "/dev/zero".
 		 */
 		return shmem_get_unmapped_area(NULL, addr, len, pgoff, flags);
 	}
@@ -632,7 +641,7 @@ static const struct file_operations __maybe_unused mem_fops = {
 	.llseek		= memory_lseek,
 	.read		= read_mem,
 	.write		= write_mem,
-	.mmap		= mmap_mem,
+	.mmap_prepare	= mmap_mem_prepare,
 	.open		= open_mem,
 #ifndef CONFIG_MMU
 	.get_unmapped_area = get_unmapped_area_mem,
@@ -668,7 +677,7 @@ static const struct file_operations zero_fops = {
 	.write_iter	= write_iter_zero,
 	.splice_read	= copy_splice_read,
 	.splice_write	= splice_write_zero,
-	.mmap		= mmap_zero,
+	.mmap_prepare	= mmap_prepare_zero,
 	.get_unmapped_area = get_unmapped_area_zero,
 #ifndef CONFIG_MMU
 	.mmap_capabilities = zero_mmap_capabilities,
include/linux/shmem_fs.h +2 -1
index 0e47465ef0fd..5b368f9549d6 100644
@@ -94,7 +94,8 @@ extern struct file *shmem_kernel_file_setup(const char *name, loff_t size,
 					    unsigned long flags);
 extern struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt,
 		const char *name, loff_t size, unsigned long flags);
-extern int shmem_zero_setup(struct vm_area_struct *);
+int shmem_zero_setup(struct vm_area_struct *vma);
+int shmem_zero_setup_desc(struct vm_area_desc *desc);
 extern unsigned long shmem_get_unmapped_area(struct file *, unsigned long addr,
 		unsigned long len, unsigned long pgoff, unsigned long flags);
 extern int shmem_lock(struct file *file, int lock, struct ucounts *ucounts);
mm/shmem.c +32 -8
index 990e33c6a776..cb6ff00eb4cb 100644
@@ -5893,14 +5893,9 @@ struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
 }
 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
 
-/**
- * shmem_zero_setup - setup a shared anonymous mapping
- * @vma: the vma to be mmapped is prepared by do_mmap
- */
-int shmem_zero_setup(struct vm_area_struct *vma)
+static struct file *__shmem_zero_setup(unsigned long start, unsigned long end, vm_flags_t vm_flags)
 {
-	struct file *file;
-	loff_t size = vma->vm_end - vma->vm_start;
+	loff_t size = end - start;
 
 	/*
 	 * Cloning a new file under mmap_lock leads to a lock ordering conflict
@@ -5908,7 +5903,17 @@ int shmem_zero_setup(struct vm_area_struct *vma)
 	 * accessible to the user through its mapping, use S_PRIVATE flag to
 	 * bypass file security, in the same way as shmem_kernel_file_setup().
 	 */
-	file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
+	return shmem_kernel_file_setup("dev/zero", size, vm_flags);
+}
+
+/**
+ * shmem_zero_setup - setup a shared anonymous mapping
+ * @vma: the vma to be mmapped is prepared by do_mmap
+ */
+int shmem_zero_setup(struct vm_area_struct *vma)
+{
+	struct file *file = __shmem_zero_setup(vma->vm_start, vma->vm_end, vma->vm_flags);
+
 	if (IS_ERR(file))
 		return PTR_ERR(file);
 
@@ -5920,6 +5925,25 @@ int shmem_zero_setup(struct vm_area_struct *vma)
 	return 0;
 }
 
+/**
+ * shmem_zero_setup_desc - same as shmem_zero_setup, but determined by VMA
+ * descriptor for convenience.
+ * @desc: Describes VMA
+ * Returns: 0 on success, or error
+ */
+int shmem_zero_setup_desc(struct vm_area_desc *desc)
+{
+	struct file *file = __shmem_zero_setup(desc->start, desc->end, desc->vm_flags);
+
+	if (IS_ERR(file))
+		return PTR_ERR(file);
+
+	desc->vm_file = file;
+	desc->vm_ops = &shmem_anon_vm_ops;
+
+	return 0;
+}
+
 /**
  * shmem_read_folio_gfp - read into page cache, using specified page allocation flags.
  * @mapping:	the folio's address_space
Signature · 1 line
2.51.0
#37 lore raw

Re: [PATCH v2 11/16] mm: update mem char driver to use mmap_prepare

Quoted 26 lines · On Wed, 10 Sep 2025 21:22:06 +0100 Lorenzo Stoakes…

Update the mem char driver (backing /dev/mem and /dev/zero) to use f_op->mmap_prepare hook rather than the deprecated f_op->mmap.

The /dev/zero implementation has a very unique and rather concerning characteristic in that it converts MAP_PRIVATE mmap() mappings anonymous when they are, in fact, not.

The new f_op->mmap_prepare() can support this, but rather than introducing a helper function to perform this hack (and risk introducing other users), simply set desc->vm_op to NULL here and add a comment describing what's going on.

We also introduce shmem_zero_setup_desc() to allow for the shared mapping case via an f_op->mmap_prepare() hook, and generalise the code between this and shmem_zero_setup().

We also use the desc->action_error_hook to filter the remap error to -EAGAIN to keep behaviour consistent.

---
 drivers/char/mem.c       | 75 ++++++++++++++++++++++------------------
 include/linux/shmem_fs.h |  3 +-
 mm/shmem.c               | 40 ++++++++++++++++-----
 3 files changed, 76 insertions(+), 42 deletions(-)

[ ... ]

Quoted 4 lines
mm/shmem.c +0 -0
index 990e33c6a776..cb6ff00eb4cb 100644

[ ... ]

Quoted 13 lines
mm/shmem.c +9 -0
@@ -5920,6 +5925,25 @@ int shmem_zero_setup(struct vm_area_struct *vma)
 	return 0;
 }
 
+/**
+ * shmem_zero_setup_desc - same as shmem_zero_setup, but determined by VMA
+ * descriptor for convenience.
+ * @desc: Describes VMA
+ * Returns: 0 on success, or error
+ */
+int shmem_zero_setup_desc(struct vm_area_desc *desc)
+{
+	struct file *file = __shmem_zero_setup(desc->start, desc->end, desc->vm_flags);

mm/shmem.c int shmem_zero_setup(struct vm_area_struct *vma) · line 5946

Quoted 10 lines
mm/shmem.c +10 -0
+
+	if (IS_ERR(file))
+		return PTR_ERR(file);
+
+	desc->vm_file = file;
+	desc->vm_ops = &shmem_anon_vm_ops;
+
+	return 0;
+}
+

Hi Lorenzo,

shmem_zero_setup() does a if (vma->vm_file) fput(vma->vm_file) dance.

It looks like we need one here too?

-chris

#38 lore raw

Re: [PATCH v2 11/16] mm: update mem char driver to use mmap_prepare

Quoted 64 lines · Chris Mason
Quoted 26 lines · On Wed, 10 Sep 2025 21:22:06 +0100 Lorenzo Stoakes…

Update the mem char driver (backing /dev/mem and /dev/zero) to use f_op->mmap_prepare hook rather than the deprecated f_op->mmap.

The /dev/zero implementation has a very unique and rather concerning characteristic in that it converts MAP_PRIVATE mmap() mappings anonymous when they are, in fact, not.

The new f_op->mmap_prepare() can support this, but rather than introducing a helper function to perform this hack (and risk introducing other users), simply set desc->vm_op to NULL here and add a comment describing what's going on.

We also introduce shmem_zero_setup_desc() to allow for the shared mapping case via an f_op->mmap_prepare() hook, and generalise the code between this and shmem_zero_setup().

We also use the desc->action_error_hook to filter the remap error to -EAGAIN to keep behaviour consistent.

---
 drivers/char/mem.c       | 75 ++++++++++++++++++++++------------------
 include/linux/shmem_fs.h |  3 +-
 mm/shmem.c               | 40 ++++++++++++++++-----
 3 files changed, 76 insertions(+), 42 deletions(-)

[ ... ]

Quoted 4 lines
mm/shmem.c +0 -0
index 990e33c6a776..cb6ff00eb4cb 100644

[ ... ]

Quoted 13 lines
mm/shmem.c +9 -0
@@ -5920,6 +5925,25 @@ int shmem_zero_setup(struct vm_area_struct *vma)
 	return 0;
 }
 
+/**
+ * shmem_zero_setup_desc - same as shmem_zero_setup, but determined by VMA
+ * descriptor for convenience.
+ * @desc: Describes VMA
+ * Returns: 0 on success, or error
+ */
+int shmem_zero_setup_desc(struct vm_area_desc *desc)
+{
+	struct file *file = __shmem_zero_setup(desc->start, desc->end, desc->vm_flags);

mm/shmem.c int shmem_zero_setup(struct vm_area_struct *vma) · line 5946

Quoted 10 lines
mm/shmem.c +10 -0
+
+	if (IS_ERR(file))
+		return PTR_ERR(file);
+
+	desc->vm_file = file;
+	desc->vm_ops = &shmem_anon_vm_ops;
+
+	return 0;
+}
+

Hi Lorenzo,

Quoted 3 lines

shmem_zero_setup() does a if (vma->vm_file) fput(vma->vm_file) dance.

It looks like we need one here too?

No we don't, it's intentionally designed to avoid this because mmap_prepare is done at a time prior to the file pointer having had been pinned like this.

This is necessary in mmap() but not in mmap_prepare(), equally you can just assign VMA flags or any other field without any need for special helpers or lock/refcount dances etc.

Quoted 2 lines

-chris

Cheers, Lorenzo

#39 lore raw

PATCH v2 12/16 mm: update resctl to use mmap_prepare

In reply to Lorenzo Stoakes

Make use of the ability to specify a remap action within mmap_prepare to update the resctl pseudo-lock to use mmap_prepare in favour of the deprecated mmap hook.

---
 fs/resctrl/pseudo_lock.c | 22 +++++++++++-----------
 1 file changed, 11 insertions(+), 11 deletions(-)
fs/resctrl/pseudo_lock.c +11 -11
index 87bbc2605de1..e847df586766 100644
@@ -995,10 +995,11 @@ static const struct vm_operations_struct pseudo_mmap_ops = {
 	.mremap = pseudo_lock_dev_mremap,
 };
 
-static int pseudo_lock_dev_mmap(struct file *filp, struct vm_area_struct *vma)
+static int pseudo_lock_dev_mmap_prepare(struct vm_area_desc *desc)
 {
-	unsigned long vsize = vma->vm_end - vma->vm_start;
-	unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
+	unsigned long off = desc->pgoff << PAGE_SHIFT;
+	unsigned long vsize = vma_desc_size(desc);
+	struct file *filp = desc->file;
 	struct pseudo_lock_region *plr;
 	struct rdtgroup *rdtgrp;
 	unsigned long physical;
@@ -1043,7 +1044,7 @@ static int pseudo_lock_dev_mmap(struct file *filp, struct vm_area_struct *vma)
 	 * Ensure changes are carried directly to the memory being mapped,
 	 * do not allow copy-on-write mapping.
 	 */
-	if (!(vma->vm_flags & VM_SHARED)) {
+	if (!(desc->vm_flags & VM_SHARED)) {
 		mutex_unlock(&rdtgroup_mutex);
 		return -EINVAL;
 	}
@@ -1055,12 +1056,11 @@ static int pseudo_lock_dev_mmap(struct file *filp, struct vm_area_struct *vma)
 
 	memset(plr->kmem + off, 0, vsize);
 
-	if (remap_pfn_range(vma, vma->vm_start, physical + vma->vm_pgoff,
-			    vsize, vma->vm_page_prot)) {
-		mutex_unlock(&rdtgroup_mutex);
-		return -EAGAIN;
-	}
-	vma->vm_ops = &pseudo_mmap_ops;
+	desc->vm_ops = &pseudo_mmap_ops;
+
+	mmap_action_remap(&desc->action, desc->start, physical + desc->pgoff,
+			  vsize, desc->page_prot);
+
 	mutex_unlock(&rdtgroup_mutex);
 	return 0;
 }
@@ -1071,7 +1071,7 @@ static const struct file_operations pseudo_lock_dev_fops = {
 	.write =	NULL,
 	.open =		pseudo_lock_dev_open,
 	.release =	pseudo_lock_dev_release,
-	.mmap =		pseudo_lock_dev_mmap,
+	.mmap_prepare =	pseudo_lock_dev_mmap_prepare,
 };
 
 int rdt_pseudo_lock_init(void)
Signature · 1 line
2.51.0
maintainer Acked-by on v2 12/16
#40 lore raw

Re: [PATCH v2 12/16] mm: update resctl to use mmap_prepare

Hi Lorenzo,

Quoted 6 lines · Lorenzo Stoakes

Make use of the ability to specify a remap action within mmap_prepare to update the resctl pseudo-lock to use mmap_prepare in favour of the deprecated mmap hook.

---

Thank you.

This does not conflict with any of the resctrl changes currently being queued in tip tree for inclusion during next merge window.

Reinette

#41 lore raw

Re: [PATCH v2 12/16] mm: update resctl to use mmap_prepare

Quoted 7 lines · Reinette Chatre

Hi Lorenzo,

Quoted 4 lines · Lorenzo Stoakes

Make use of the ability to specify a remap action within mmap_prepare to update the resctl pseudo-lock to use mmap_prepare in favour of the deprecated mmap hook.

Quoted 6 lines
Quoted 2 lines

---

Thank you.

Thanks!

Quoted 3 lines

This does not conflict with any of the resctrl changes currently being queued in tip tree for inclusion during next merge window.

Great :)

Quoted 2 lines

Reinette

Cheers, Lorenzo

#42 lore raw

PATCH v2 13/16 mm: update cramfs to use mmap_prepare

In reply to Lorenzo Stoakes

cramfs uses either a PFN remap or a mixedmap insertion, we are able to determine this at the point of mmap_prepare and to select the appropriate action to perform using the vm_area_desc.

Note that there appears to have been a bug in this code, with the physical address being specified as the PFN (!!) to vmf_insert_mixed(). This patch fixes this issue.

Finally, we trivially have to update the pr_debug() message indicating what's happening to occur before the remap/mixedmap occurs.

---
 fs/cramfs/inode.c | 46 ++++++++++++++++++++--------------------------
 1 file changed, 20 insertions(+), 26 deletions(-)
fs/cramfs/inode.c +20 -26
index b002e9b734f9..2a41b30753a7 100644
@@ -342,16 +342,17 @@ static bool cramfs_last_page_is_shared(struct inode *inode)
 	return memchr_inv(tail_data, 0, PAGE_SIZE - partial) ? true : false;
 }
 
-static int cramfs_physmem_mmap(struct file *file, struct vm_area_struct *vma)
+static int cramfs_physmem_mmap_prepare(struct vm_area_desc *desc)
 {
+	struct file *file = desc->file;
 	struct inode *inode = file_inode(file);
 	struct cramfs_sb_info *sbi = CRAMFS_SB(inode->i_sb);
 	unsigned int pages, max_pages, offset;
-	unsigned long address, pgoff = vma->vm_pgoff;
+	unsigned long address, pgoff = desc->pgoff;
 	char *bailout_reason;
 	int ret;
 
-	ret = generic_file_readonly_mmap(file, vma);
+	ret = generic_file_readonly_mmap_prepare(desc);
 	if (ret)
 		return ret;
 
@@ -362,14 +363,14 @@ static int cramfs_physmem_mmap(struct file *file, struct vm_area_struct *vma)
 
 	/* Could COW work here? */
 	bailout_reason = "vma is writable";
-	if (vma->vm_flags & VM_WRITE)
+	if (desc->vm_flags & VM_WRITE)
 		goto bailout;
 
 	max_pages = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
 	bailout_reason = "beyond file limit";
 	if (pgoff >= max_pages)
 		goto bailout;
-	pages = min(vma_pages(vma), max_pages - pgoff);
+	pages = min(vma_desc_pages(desc), max_pages - pgoff);
 
 	offset = cramfs_get_block_range(inode, pgoff, &pages);
 	bailout_reason = "unsuitable block layout";
@@ -391,38 +392,31 @@ static int cramfs_physmem_mmap(struct file *file, struct vm_area_struct *vma)
 		goto bailout;
 	}
 
-	if (pages == vma_pages(vma)) {
+	pr_debug("mapping %pD[%lu] at 0x%08lx (%u/%lu pages) "
+		 "to vma 0x%08lx, page_prot 0x%llx\n", file,
+		 pgoff, address, pages, vma_desc_pages(desc), desc->start,
+		 (unsigned long long)pgprot_val(desc->page_prot));
+
+	if (pages == vma_desc_pages(desc)) {
 		/*
 		 * The entire vma is mappable. remap_pfn_range() will
 		 * make it distinguishable from a non-direct mapping
 		 * in /proc/<pid>/maps by substituting the file offset
 		 * with the actual physical address.
 		 */
-		ret = remap_pfn_range(vma, vma->vm_start, address >> PAGE_SHIFT,
-				      pages * PAGE_SIZE, vma->vm_page_prot);
+		mmap_action_remap(&desc->action, desc->start,
+				  address >> PAGE_SHIFT, pages * PAGE_SIZE,
+				  desc->page_prot);
 	} else {
 		/*
 		 * Let's create a mixed map if we can't map it all.
 		 * The normal paging machinery will take care of the
 		 * unpopulated ptes via cramfs_read_folio().
 		 */
-		int i;
-		vm_flags_set(vma, VM_MIXEDMAP);
-		for (i = 0; i < pages && !ret; i++) {
-			vm_fault_t vmf;
-			unsigned long off = i * PAGE_SIZE;
-			vmf = vmf_insert_mixed(vma, vma->vm_start + off,
-					address + off);
-			if (vmf & VM_FAULT_ERROR)
-				ret = vm_fault_to_errno(vmf, 0);
-		}
+		mmap_action_mixedmap(&desc->action, desc->start,
+				     address >> PAGE_SHIFT, pages);
 	}
 
-	if (!ret)
-		pr_debug("mapped %pD[%lu] at 0x%08lx (%u/%lu pages) "
-			 "to vma 0x%08lx, page_prot 0x%llx\n", file,
-			 pgoff, address, pages, vma_pages(vma), vma->vm_start,
-			 (unsigned long long)pgprot_val(vma->vm_page_prot));
 	return ret;
 
 bailout:
@@ -434,9 +428,9 @@ static int cramfs_physmem_mmap(struct file *file, struct vm_area_struct *vma)
 
 #else /* CONFIG_MMU */
 
-static int cramfs_physmem_mmap(struct file *file, struct vm_area_struct *vma)
+static int cramfs_physmem_mmap_prepare(struct vm_area_desc *desc)
 {
-	return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -ENOSYS;
+	return is_nommu_shared_mapping(desc->vm_flags) ? 0 : -ENOSYS;
 }
 
 static unsigned long cramfs_physmem_get_unmapped_area(struct file *file,
@@ -474,7 +468,7 @@ static const struct file_operations cramfs_physmem_fops = {
 	.llseek			= generic_file_llseek,
 	.read_iter		= generic_file_read_iter,
 	.splice_read		= filemap_splice_read,
-	.mmap			= cramfs_physmem_mmap,
+	.mmap_prepare		= cramfs_physmem_mmap_prepare,
 #ifndef CONFIG_MMU
 	.get_unmapped_area	= cramfs_physmem_get_unmapped_area,
 	.mmap_capabilities	= cramfs_physmem_mmap_capabilities,
Signature · 1 line
2.51.0
#43 lore raw

PATCH v2 14/16 fs/proc: add the proc_mmap_prepare hook for procfs

In reply to Lorenzo Stoakes

By adding this hook we enable procfs implementations to be able to use the .mmap_prepare hook rather than the deprecated .mmap one.

We treat this as if it were any other nested mmap hook and utilise the .mmap_prepare compatibility layer if necessary.

---
 fs/proc/inode.c         | 12 +++++++++---
 include/linux/proc_fs.h |  1 +
 2 files changed, 10 insertions(+), 3 deletions(-)
fs/proc/inode.c +9 -3
index 129490151be1..609abbc84bf4 100644
@@ -414,9 +414,15 @@ static long proc_reg_compat_ioctl(struct file *file, unsigned int cmd, unsigned
 
 static int pde_mmap(struct proc_dir_entry *pde, struct file *file, struct vm_area_struct *vma)
 {
-	__auto_type mmap = pde->proc_ops->proc_mmap;
-	if (mmap)
-		return mmap(file, vma);
+	const struct file_operations f_op = {
+		.mmap = pde->proc_ops->proc_mmap,
+		.mmap_prepare = pde->proc_ops->proc_mmap_prepare,
+	};
+
+	if (f_op.mmap)
+		return f_op.mmap(file, vma);
+	else if (f_op.mmap_prepare)
+		return __compat_vma_mmap_prepare(&f_op, file, vma);
 	return -EIO;
 }
 
include/linux/proc_fs.h +1 -0
index f139377f4b31..e5f65ebd62b8 100644
@@ -47,6 +47,7 @@ struct proc_ops {
 	long	(*proc_compat_ioctl)(struct file *, unsigned int, unsigned long);
 #endif
 	int	(*proc_mmap)(struct file *, struct vm_area_struct *);
+	int	(*proc_mmap_prepare)(struct vm_area_desc *);
 	unsigned long (*proc_get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
 } __randomize_layout;
 
Signature · 1 line
2.51.0
#44 lore raw

PATCH v2 15/16 fs/proc: update vmcore to use .proc_mmap_prepare

In reply to Lorenzo Stoakes

Now we have the ability to specify a custom hook we can handle even very customised behaviour.

As part of this change, we must also update remap_vmalloc_range_partial() to optionally not update VMA flags. Other than then remap_vmalloc_range() wrapper, vmcore is the only user of this function so we can simply go ahead and add a parameter.

---
 arch/s390/kernel/crash_dump.c |  6 ++--
 fs/proc/vmcore.c              | 54 +++++++++++++++++++++++------------
 include/linux/vmalloc.h       | 10 +++----
 mm/vmalloc.c                  | 16 +++++++++--
 4 files changed, 57 insertions(+), 29 deletions(-)
arch/s390/kernel/crash_dump.c +3 -3
index d4839de8ce9d..44d7902f7e41 100644
@@ -186,7 +186,7 @@ static int remap_oldmem_pfn_range_kdump(struct vm_area_struct *vma,
 
 	if (pfn < oldmem_data.size >> PAGE_SHIFT) {
 		size_old = min(size, oldmem_data.size - (pfn << PAGE_SHIFT));
-		rc = remap_pfn_range(vma, from,
+		rc = remap_pfn_range_complete(vma, from,
 				     pfn + (oldmem_data.start >> PAGE_SHIFT),
 				     size_old, prot);
 		if (rc || size == size_old)
@@ -195,7 +195,7 @@ static int remap_oldmem_pfn_range_kdump(struct vm_area_struct *vma,
 		from += size_old;
 		pfn += size_old >> PAGE_SHIFT;
 	}
-	return remap_pfn_range(vma, from, pfn, size, prot);
+	return remap_pfn_range_complete(vma, from, pfn, size, prot);
 }
 
 /*
@@ -220,7 +220,7 @@ static int remap_oldmem_pfn_range_zfcpdump(struct vm_area_struct *vma,
 		from += size_hsa;
 		pfn += size_hsa >> PAGE_SHIFT;
 	}
-	return remap_pfn_range(vma, from, pfn, size, prot);
+	return remap_pfn_range_complete(vma, from, pfn, size, prot);
 }
 
 /*
fs/proc/vmcore.c +36 -18

104 lines not on this page · raw message

include/linux/vmalloc.h +5 -5
index eb54b7b3202f..588810e571aa 100644
@@ -215,12 +215,12 @@ extern void *vmap(struct page **pages, unsigned int count,
 void *vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot);
 extern void vunmap(const void *addr);
 
-extern int remap_vmalloc_range_partial(struct vm_area_struct *vma,
-				       unsigned long uaddr, void *kaddr,
-				       unsigned long pgoff, unsigned long size);
+int remap_vmalloc_range_partial(struct vm_area_struct *vma,
+		unsigned long uaddr, void *kaddr, unsigned long pgoff,
+		unsigned long size, bool set_vma);
 
-extern int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
-							unsigned long pgoff);
+int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
+		unsigned long pgoff);
 
 int vmap_pages_range(unsigned long addr, unsigned long end, pgprot_t prot,
 		     struct page **pages, unsigned int page_shift);
mm/vmalloc.c +13 -3
index 9fc86ddf1711..3dd9d5c441d8 100644
@@ -4531,6 +4531,7 @@ long vread_iter(struct iov_iter *iter, const char *addr, size_t count)
  * @kaddr:		virtual address of vmalloc kernel memory
  * @pgoff:		offset from @kaddr to start at
  * @size:		size of map area
+ * @set_vma:		If true, update VMA flags
  *
  * Returns:	0 for success, -Exxx on failure
  *
@@ -4543,7 +4544,7 @@ long vread_iter(struct iov_iter *iter, const char *addr, size_t count)
  */
 int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
 				void *kaddr, unsigned long pgoff,
-				unsigned long size)
+				unsigned long size, bool set_vma)
 {
 	struct vm_struct *area;
 	unsigned long off;
@@ -4569,6 +4570,10 @@ int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
 		return -EINVAL;
 	kaddr += off;
 
+	/* If we shouldn't modify VMA flags, vm_insert_page() mustn't. */
+	if (!set_vma && !(vma->vm_flags & VM_MIXEDMAP))
+		return -EINVAL;
+
 	do {
 		struct page *page = vmalloc_to_page(kaddr);
 		int ret;
@@ -4582,7 +4587,11 @@ int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
 		size -= PAGE_SIZE;
 	} while (size > 0);
 
-	vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
+	if (set_vma)
+		vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
+	else
+		VM_WARN_ON_ONCE((vma->vm_flags & (VM_DONTEXPAND | VM_DONTDUMP)) !=
+				(VM_DONTEXPAND | VM_DONTDUMP));
 
 	return 0;
 }
@@ -4606,7 +4615,8 @@ int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
 {
 	return remap_vmalloc_range_partial(vma, vma->vm_start,
 					   addr, pgoff,
-					   vma->vm_end - vma->vm_start);
+					   vma->vm_end - vma->vm_start,
+					   /* set_vma= */ true);
 }
 EXPORT_SYMBOL(remap_vmalloc_range);
 
Signature · 1 line
2.51.0
#45 lore raw

Re: [PATCH v2 15/16] fs/proc: update vmcore to use .proc_mmap_prepare

kernel test robot noticed the following build warnings:

Hi Lorenzo,

kernel test robot noticed the following build warnings:

[auto build test WARNING on akpm-mm/mm-everything]
[cannot apply to brauner-vfs/vfs.all char-misc/char-misc-testing char-misc/char-misc-next char-misc/char-misc-linus s390/features lwn/docs-next linus/master v6.17-rc5 next-20250911] [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/Lorenzo-Stoakes/mm-shmem-update-shmem-to-use-mmap_prepare/20250911-042432
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/163fba3d7ec775ec3eb9a13bd641d3255e8ec96c.1757534913.git.lorenzo.stoakes%40oracle.com
patch subject: [PATCH v2 15/16] fs/proc: update vmcore to use .proc_mmap_prepare
config: x86_64-buildonly-randconfig-001-20250911 (https://download.01.org/0day-ci/archive/20250912/[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/20250912/[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 >>):

fs/proc/vmcore.c: In function 'mmap_prepare_action_vmcore':

>> fs/proc/vmcore.c:595:20: warning: variable 'end' set but not used [-Wunused-but-set-variable]
     595 |         u64 start, end, len, tsz;
         |                    ^~~

vim +/end +595 fs/proc/vmcore.c

0692dedcf64bf3 Vitaly Kuznetsov  2014-08-08  590  
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  591  static int mmap_prepare_action_vmcore(struct vm_area_struct *vma)
83086978c63afd HATAYAMA Daisuke  2013-07-03  592  {
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  593  	struct mmap_action action;
83086978c63afd HATAYAMA Daisuke  2013-07-03  594  	size_t size = vma->vm_end - vma->vm_start;
83086978c63afd HATAYAMA Daisuke  2013-07-03 @595  	u64 start, end, len, tsz;
819403c893551c David Hildenbrand 2024-12-04  596  	struct vmcore_range *m;
83086978c63afd HATAYAMA Daisuke  2013-07-03  597  
83086978c63afd HATAYAMA Daisuke  2013-07-03  598  	start = (u64)vma->vm_pgoff << PAGE_SHIFT;
83086978c63afd HATAYAMA Daisuke  2013-07-03  599  	end = start + size;
83086978c63afd HATAYAMA Daisuke  2013-07-03  600  	len = 0;
83086978c63afd HATAYAMA Daisuke  2013-07-03  601  
83086978c63afd HATAYAMA Daisuke  2013-07-03  602  	if (start < elfcorebuf_sz) {
83086978c63afd HATAYAMA Daisuke  2013-07-03  603  		u64 pfn;
83086978c63afd HATAYAMA Daisuke  2013-07-03  604  
83086978c63afd HATAYAMA Daisuke  2013-07-03  605  		tsz = min(elfcorebuf_sz - (size_t)start, size);
83086978c63afd HATAYAMA Daisuke  2013-07-03  606  		pfn = __pa(elfcorebuf + start) >> PAGE_SHIFT;
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  607  
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  608  		mmap_action_remap(&action, vma->vm_start, pfn, tsz,
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  609  				  vma->vm_page_prot);
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  610  		if (mmap_action_complete(&action, vma))
83086978c63afd HATAYAMA Daisuke  2013-07-03  611  			return -EAGAIN;
83086978c63afd HATAYAMA Daisuke  2013-07-03  612  		size -= tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  613  		start += tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  614  		len += tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  615  
83086978c63afd HATAYAMA Daisuke  2013-07-03  616  		if (size == 0)
83086978c63afd HATAYAMA Daisuke  2013-07-03  617  			return 0;
83086978c63afd HATAYAMA Daisuke  2013-07-03  618  	}
83086978c63afd HATAYAMA Daisuke  2013-07-03  619  
83086978c63afd HATAYAMA Daisuke  2013-07-03  620  	if (start < elfcorebuf_sz + elfnotes_sz) {
83086978c63afd HATAYAMA Daisuke  2013-07-03  621  		void *kaddr;
83086978c63afd HATAYAMA Daisuke  2013-07-03  622  
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  623  		/* We add device dumps before other elf notes because the
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  624  		 * other elf notes may not fill the elf notes buffer
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  625  		 * completely and we will end up with zero-filled data
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  626  		 * between the elf notes and the device dumps. Tools will
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  627  		 * then try to decode this zero-filled data as valid notes
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  628  		 * and we don't want that. Hence, adding device dumps before
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  629  		 * the other elf notes ensure that zero-filled data can be
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  630  		 * avoided. This also ensures that the device dumps and
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  631  		 * other elf notes can be properly mmaped at page aligned
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  632  		 * address.
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  633  		 */
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  634  #ifdef CONFIG_PROC_VMCORE_DEVICE_DUMP
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  635  		/* Read device dumps */
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  636  		if (start < elfcorebuf_sz + vmcoredd_orig_sz) {
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  637  			u64 start_off;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  638  
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  639  			tsz = min(elfcorebuf_sz + vmcoredd_orig_sz -
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  640  				  (size_t)start, size);
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  641  			start_off = start - elfcorebuf_sz;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  642  			if (vmcoredd_mmap_dumps(vma, vma->vm_start + len,
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  643  						start_off, tsz))
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  644  				goto fail;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  645  
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  646  			size -= tsz;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  647  			start += tsz;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  648  			len += tsz;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  649  
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  650  			/* leave now if filled buffer already */
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  651  			if (!size)
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  652  				return 0;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  653  		}
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  654  #endif /* CONFIG_PROC_VMCORE_DEVICE_DUMP */
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  655  
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  656  		/* Read remaining elf notes */
83086978c63afd HATAYAMA Daisuke  2013-07-03  657  		tsz = min(elfcorebuf_sz + elfnotes_sz - (size_t)start, size);
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  658  		kaddr = elfnotes_buf + start - elfcorebuf_sz - vmcoredd_orig_sz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  659  		if (remap_vmalloc_range_partial(vma, vma->vm_start + len,
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  660  				kaddr, 0, tsz, /* set_vma =*/false))
83086978c63afd HATAYAMA Daisuke  2013-07-03  661  			goto fail;
7efe48df8a3df6 Rahul Lakkireddy  2018-05-02  662  
83086978c63afd HATAYAMA Daisuke  2013-07-03  663  		size -= tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  664  		start += tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  665  		len += tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  666  
83086978c63afd HATAYAMA Daisuke  2013-07-03  667  		if (size == 0)
83086978c63afd HATAYAMA Daisuke  2013-07-03  668  			return 0;
83086978c63afd HATAYAMA Daisuke  2013-07-03  669  	}
83086978c63afd HATAYAMA Daisuke  2013-07-03  670  
83086978c63afd HATAYAMA Daisuke  2013-07-03  671  	list_for_each_entry(m, &vmcore_list, list) {
83086978c63afd HATAYAMA Daisuke  2013-07-03  672  		if (start < m->offset + m->size) {
83086978c63afd HATAYAMA Daisuke  2013-07-03  673  			u64 paddr = 0;
83086978c63afd HATAYAMA Daisuke  2013-07-03  674  
0b50a2d86d8e9a Dave Young        2016-03-17  675  			tsz = (size_t)min_t(unsigned long long,
0b50a2d86d8e9a Dave Young        2016-03-17  676  					    m->offset + m->size - start, size);
83086978c63afd HATAYAMA Daisuke  2013-07-03  677  			paddr = m->paddr + start - m->offset;
0692dedcf64bf3 Vitaly Kuznetsov  2014-08-08  678  			if (vmcore_remap_oldmem_pfn(vma, vma->vm_start + len,
83086978c63afd HATAYAMA Daisuke  2013-07-03  679  						    paddr >> PAGE_SHIFT, tsz,
83086978c63afd HATAYAMA Daisuke  2013-07-03  680  						    vma->vm_page_prot))
83086978c63afd HATAYAMA Daisuke  2013-07-03  681  				goto fail;
83086978c63afd HATAYAMA Daisuke  2013-07-03  682  			size -= tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  683  			start += tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  684  			len += tsz;
83086978c63afd HATAYAMA Daisuke  2013-07-03  685  
83086978c63afd HATAYAMA Daisuke  2013-07-03  686  			if (size == 0)
83086978c63afd HATAYAMA Daisuke  2013-07-03  687  				return 0;
83086978c63afd HATAYAMA Daisuke  2013-07-03  688  		}
83086978c63afd HATAYAMA Daisuke  2013-07-03  689  	}
83086978c63afd HATAYAMA Daisuke  2013-07-03  690  
83086978c63afd HATAYAMA Daisuke  2013-07-03  691  	return 0;
83086978c63afd HATAYAMA Daisuke  2013-07-03  692  fail:
897ab3e0c49e24 Mike Rapoport     2017-02-24  693  	do_munmap(vma->vm_mm, vma->vm_start, len, NULL);
83086978c63afd HATAYAMA Daisuke  2013-07-03  694  	return -EAGAIN;
83086978c63afd HATAYAMA Daisuke  2013-07-03  695  }
a8a91e1ced449b Lorenzo Stoakes   2025-09-10  696  
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#46 lore raw

Re: [PATCH v2 15/16] fs/proc: update vmcore to use .proc_mmap_prepare

Quoted 23 lines · kernel test robot

Hi Lorenzo,

kernel test robot noticed the following build warnings:

[auto build test WARNING on akpm-mm/mm-everything]
[cannot apply to brauner-vfs/vfs.all char-misc/char-misc-testing char-misc/char-misc-next char-misc/char-misc-linus s390/features lwn/docs-next linus/master v6.17-rc5 next-20250911] [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/Lorenzo-Stoakes/mm-shmem-update-shmem-to-use-mmap_prepare/20250911-042432
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/163fba3d7ec775ec3eb9a13bd641d3255e8ec96c.1757534913.git.lorenzo.stoakes%40oracle.com
patch subject: [PATCH v2 15/16] fs/proc: update vmcore to use .proc_mmap_prepare
config: x86_64-buildonly-randconfig-001-20250911 (https://download.01.org/0day-ci/archive/20250912/[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/20250912/[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]/

Quoted 6 lines

All warnings (new ones prefixed by >>):

fs/proc/vmcore.c: In function 'mmap_prepare_action_vmcore':

Quoted 1 line
Quoted 1 line

fs/proc/vmcore.c:595:20: warning: variable 'end' set but not used [-Wunused-but-set-variable]

     595 |         u64 start, end, len, tsz;
         |                    ^~~

Ack, will send fix patch.

#47 lore raw

Re: [PATCH v2 15/16] fs/proc: update vmcore to use .proc_mmap_prepare

In reply to Lorenzo Stoakes

Hi Andrew,

Can you apply the below fix-patch to address a trivial variable use warning, thanks!

Cheers, Lorenzo

----8<----
From b9d0c3b39d97309bf572af443e2190bb20f6b976 Mon Sep 17 00:00:00 2001
From: Lorenzo Stoakes <[email protected]>
Date: Fri, 12 Sep 2025 11:12:10 +0100
Subject: [PATCH] vmcore fix

---
 fs/proc/vmcore.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
fs/proc/vmcore.c +1 -2
index faf811ed9b15..028c8c904cbb 100644
@@ -592,11 +592,10 @@ static int mmap_prepare_action_vmcore(struct vm_area_struct *vma)
 {
 	struct mmap_action action;
 	size_t size = vma->vm_end - vma->vm_start;
-	u64 start, end, len, tsz;
+	u64 start, len, tsz;
 	struct vmcore_range *m;
 
 	start = (u64)vma->vm_pgoff << PAGE_SHIFT;
-	end = start + size;
 	len = 0;
 
 	if (start < elfcorebuf_sz) {

--
2.51.0

#48 lore raw

PATCH v2 16/16 kcov: update kcov to use mmap_prepare

In reply to Lorenzo Stoakes

We can use the mmap insert pages functionality provided for use in mmap_prepare to insert the kcov pages as required.

This does necessitate an allocation, but since it's in the mmap path this doesn't seem egregious. The allocation/freeing of the pages array is handled automatically by vma_desc_set_mixedmap_pages() and the mapping logic.

---
 kernel/kcov.c | 42 ++++++++++++++++++++++++++----------------
 1 file changed, 26 insertions(+), 16 deletions(-)
kernel/kcov.c +26 -16
index 1d85597057e1..2bcf403e5f6f 100644
@@ -484,31 +484,41 @@ void kcov_task_exit(struct task_struct *t)
 	kcov_put(kcov);
 }
 
-static int kcov_mmap(struct file *filep, struct vm_area_struct *vma)
+static int kcov_mmap_error(int err)
+{
+	pr_warn_once("kcov: vm_insert_page() failed\n");
+	return err;
+}
+
+static int kcov_mmap_prepare(struct vm_area_desc *desc)
 {
 	int res = 0;
-	struct kcov *kcov = vma->vm_file->private_data;
-	unsigned long size, off;
-	struct page *page;
+	struct kcov *kcov = desc->file->private_data;
+	unsigned long size, nr_pages, i;
+	struct page **pages;
 	unsigned long flags;
 
 	spin_lock_irqsave(&kcov->lock, flags);
 	size = kcov->size * sizeof(unsigned long);
-	if (kcov->area == NULL || vma->vm_pgoff != 0 ||
-	    vma->vm_end - vma->vm_start != size) {
+	if (kcov->area == NULL || desc->pgoff != 0 ||
+	    vma_desc_size(desc) != size) {
 		res = -EINVAL;
 		goto exit;
 	}
 	spin_unlock_irqrestore(&kcov->lock, flags);
-	vm_flags_set(vma, VM_DONTEXPAND);
-	for (off = 0; off < size; off += PAGE_SIZE) {
-		page = vmalloc_to_page(kcov->area + off);
-		res = vm_insert_page(vma, vma->vm_start + off, page);
-		if (res) {
-			pr_warn_once("kcov: vm_insert_page() failed\n");
-			return res;
-		}
-	}
+
+	desc->vm_flags |= VM_DONTEXPAND;
+	nr_pages = size >> PAGE_SHIFT;
+
+	pages = mmap_action_mixedmap_pages(&desc->action, desc->start,
+					   nr_pages);
+	if (!pages)
+		return -ENOMEM;
+
+	for (i = 0; i < nr_pages; i++)
+		pages[i] = vmalloc_to_page(kcov->area + i * PAGE_SIZE);
+	desc->action.error_hook = kcov_mmap_error;
+
 	return 0;
 exit:
 	spin_unlock_irqrestore(&kcov->lock, flags);
@@ -761,7 +771,7 @@ static const struct file_operations kcov_fops = {
 	.open		= kcov_open,
 	.unlocked_ioctl	= kcov_ioctl,
 	.compat_ioctl	= kcov_ioctl,
-	.mmap		= kcov_mmap,
+	.mmap_prepare	= kcov_mmap_prepare,
 	.release        = kcov_close,
 };
 
Signature · 1 line
2.51.0
#49 lore raw

Re: [PATCH v2 16/16] kcov: update kcov to use mmap_prepare

Quoted 7 lines · Lorenzo Stoakes
kernel/kcov.c +2 -3
+static int kcov_mmap_prepare(struct vm_area_desc *desc)
 {
 	int res = 0;
-	struct kcov *kcov = vma->vm_file->private_data;
-	unsigned long size, off;
-	struct page *page;
+	struct kcov *kcov = desc->file->private_data;

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 504

Quoted 10 lines
kernel/kcov.c +4 -2
+	unsigned long size, nr_pages, i;
+	struct page **pages;
 	unsigned long flags;
 
 	spin_lock_irqsave(&kcov->lock, flags);
 	size = kcov->size * sizeof(unsigned long);
-	if (kcov->area == NULL || vma->vm_pgoff != 0 ||
-	    vma->vm_end - vma->vm_start != size) {
+	if (kcov->area == NULL || desc->pgoff != 0 ||
+	    vma_desc_size(desc) != size) {

IMHO these range checks should be cleaned up into a helper:

/* Returns true if the VMA falls within starting_pgoff to
starting_pgoff + ROUND_DOWN(length_bytes, PAGE_SIZE))
Is careful to avoid any arithmetic overflow.
*/
vma_desc_check_range(desc, starting_pgoff=0, length_bytes=size);

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 519

Quoted 10 lines
kernel/kcov.c +10 -0
+	desc->vm_flags |= VM_DONTEXPAND;
+	nr_pages = size >> PAGE_SHIFT;
+
+	pages = mmap_action_mixedmap_pages(&desc->action, desc->start,
+					   nr_pages);
+	if (!pages)
+		return -ENOMEM;
+
+	for (i = 0; i < nr_pages; i++)
+		pages[i] = vmalloc_to_page(kcov->area + i * PAGE_SIZE);

This is not a mixed map.

All the memory comes from vmalloc_user() which makes them normal struct pages with refcounts.

If anything the action should be called mmap_action_vmalloc_user() to match how the memory was allocated instead of open coding something.

Jason

#50 lore raw

Re: [PATCH v2 16/16] kcov: update kcov to use mmap_prepare

Quoted 21 lines · Jason Gunthorpe
Quoted 7 lines · Lorenzo Stoakes
kernel/kcov.c +2 -3
+static int kcov_mmap_prepare(struct vm_area_desc *desc)
 {
 	int res = 0;
-	struct kcov *kcov = vma->vm_file->private_data;
-	unsigned long size, off;
-	struct page *page;
+	struct kcov *kcov = desc->file->private_data;

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 504

Quoted 10 lines
kernel/kcov.c +4 -2
+	unsigned long size, nr_pages, i;
+	struct page **pages;
 	unsigned long flags;
 
 	spin_lock_irqsave(&kcov->lock, flags);
 	size = kcov->size * sizeof(unsigned long);
-	if (kcov->area == NULL || vma->vm_pgoff != 0 ||
-	    vma->vm_end - vma->vm_start != size) {
+	if (kcov->area == NULL || desc->pgoff != 0 ||
+	    vma_desc_size(desc) != size) {

IMHO these range checks should be cleaned up into a helper:

Quoted 4 lines

/* Returns true if the VMA falls within starting_pgoff to
starting_pgoff + ROUND_DOWN(length_bytes, PAGE_SIZE))
Is careful to avoid any arithmetic overflow.
*/

Right, but I can't refactor every driver I touch, it's not really tractable. I'd like to get this change done before I retire :)

Quoted 15 lines

vma_desc_check_range(desc, starting_pgoff=0, length_bytes=size);

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 519

Quoted 10 lines
kernel/kcov.c +10 -0
+	desc->vm_flags |= VM_DONTEXPAND;
+	nr_pages = size >> PAGE_SHIFT;
+
+	pages = mmap_action_mixedmap_pages(&desc->action, desc->start,
+					   nr_pages);
+	if (!pages)
+		return -ENOMEM;
+
+	for (i = 0; i < nr_pages; i++)
+		pages[i] = vmalloc_to_page(kcov->area + i * PAGE_SIZE);

This is not a mixed map.

Quoted 5 lines

All the memory comes from vmalloc_user() which makes them normal struct pages with refcounts.

If anything the action should be called mmap_action_vmalloc_user() to match how the memory was allocated instead of open coding something.

Again we're getting into the same issue - my workload doesn't really permit me to refactor every user of .mmap beyond converting sensibly to the new scheme.

I think this kind of change is out of scope for the series.

I'd rather make this as apples-to-apples as possible for now so it can be done vaguely mechanically.

Of course we can follow up with improvements later.

Quoted 2 lines

Jason

Cheers, Lorenzo

#51 lore raw

Re: [PATCH v2 16/16] kcov: update kcov to use mmap_prepare

Quoted 5 lines · Lorenzo Stoakes
Quoted 5 lines

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 504

Quoted 2 lines
kernel/kcov.c +2 -0
+	if (kcov->area == NULL || desc->pgoff != 0 ||
+	    vma_desc_size(desc) != size) {

IMHO these range checks should be cleaned up into a helper:

Quoted 7 lines
Quoted 4 lines

/* Returns true if the VMA falls within starting_pgoff to
starting_pgoff + ROUND_DOWN(length_bytes, PAGE_SIZE))
Is careful to avoid any arithmetic overflow.
*/

Right, but I can't refactor every driver I touch, it's not really tractable. I'd like to get this change done before I retire :)

I don't think it is a big deal, and these helpers should be part of the new api. You are reading and touching anyhow.

Quoted 6 lines
Quoted 2 lines

If anything the action should be called mmap_action_vmalloc_user() to match how the memory was allocated instead of open coding something.

Again we're getting into the same issue - my workload doesn't really permit me to refactor every user of .mmap beyond converting sensibly to the new scheme.

If you are adding this explicit action concept then it should be a sane set of actions. Using a mixed map action to insert a vmalloc_user is not a reasonable thing to do.

Jason

#52 lore raw

Re: [PATCH v2 16/16] kcov: update kcov to use mmap_prepare

Quoted 11 lines · Jason Gunthorpe
Quoted 10 lines · Lorenzo Stoakes
Quoted 9 lines

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 504

Quoted 2 lines
kernel/kcov.c +2 -0
+	if (kcov->area == NULL || desc->pgoff != 0 ||
+	    vma_desc_size(desc) != size) {

IMHO these range checks should be cleaned up into a helper:

/* Returns true if the VMA falls within starting_pgoff to
starting_pgoff + ROUND_DOWN(length_bytes, PAGE_SIZE))
Is careful to avoid any arithmetic overflow.
*/

Quoted 5 lines
Quoted 2 lines

Right, but I can't refactor every driver I touch, it's not really tractable. I'd like to get this change done before I retire :)

I don't think it is a big deal, and these helpers should be part of the new api. You are reading and touching anyhow.

x ~230 becomes a big deal.

Quoted 11 lines
Quoted 7 lines
Quoted 3 lines

If anything the action should be called mmap_action_vmalloc_user() to match how the memory was allocated instead of open coding something.

Again we're getting into the same issue - my workload doesn't really permit me to refactor every user of .mmap beyond converting sensibly to the new scheme.

If you are adding this explicit action concept then it should be a sane set of actions. Using a mixed map action to insert a vmalloc_user is not a reasonable thing to do.

Right I'm obviously intending there to be a sane interface.

And there are users who use mixed map to insert actual mixed map pages, so having an interface for _that_ isn't crazy. So it's not like this is compromising that.

(I mean an aside is we need to clean up a lot there anyway, it's a mess, but that's out of scope here.)

Quoted 2 lines

Jason

Anwyay, for the sake of getting this series in since you seem adament, I'll go ahead and refactor in this case. But it's really not reasonable to expect me to do this in each instance.

I will obviously try my best to ensure the API is as good as it can be, and adapted to what mmap users need. That bit I am trying to get as right as I can...

But in each individual driver's case, we have to be pragmatic.

Cheers, Lorenzo

#53 lore raw

Re: [PATCH v2 16/16] kcov: update kcov to use mmap_prepare

In reply to Lorenzo Stoakes
Quoted 54 lines · On Wed, 10 Sep 2025 21:22:11 +0100 Lorenzo Stoakes…

We can use the mmap insert pages functionality provided for use in mmap_prepare to insert the kcov pages as required.

This does necessitate an allocation, but since it's in the mmap path this doesn't seem egregious. The allocation/freeing of the pages array is handled automatically by vma_desc_set_mixedmap_pages() and the mapping logic.

---
 kernel/kcov.c | 42 ++++++++++++++++++++++++++----------------
 1 file changed, 26 insertions(+), 16 deletions(-)
kernel/kcov.c +12 -11
index 1d85597057e1..2bcf403e5f6f 100644
@@ -484,31 +484,41 @@ void kcov_task_exit(struct task_struct *t)
 	kcov_put(kcov);
 }
 
-static int kcov_mmap(struct file *filep, struct vm_area_struct *vma)
+static int kcov_mmap_error(int err)
+{
+	pr_warn_once("kcov: vm_insert_page() failed\n");
+	return err;
+}
+
+static int kcov_mmap_prepare(struct vm_area_desc *desc)
 {
 	int res = 0;
-	struct kcov *kcov = vma->vm_file->private_data;
-	unsigned long size, off;
-	struct page *page;
+	struct kcov *kcov = desc->file->private_data;
+	unsigned long size, nr_pages, i;
+	struct page **pages;
 	unsigned long flags;
 
 	spin_lock_irqsave(&kcov->lock, flags);
 	size = kcov->size * sizeof(unsigned long);
-	if (kcov->area == NULL || vma->vm_pgoff != 0 ||
-	    vma->vm_end - vma->vm_start != size) {
+	if (kcov->area == NULL || desc->pgoff != 0 ||
+	    vma_desc_size(desc) != size) {
 		res = -EINVAL;
 		goto exit;
 	}
 	spin_unlock_irqrestore(&kcov->lock, flags);
-	vm_flags_set(vma, VM_DONTEXPAND);
-	for (off = 0; off < size; off += PAGE_SIZE) {
-		page = vmalloc_to_page(kcov->area + off);
-		res = vm_insert_page(vma, vma->vm_start + off, page);
-		if (res) {

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 514

Quoted 10 lines
kernel/kcov.c +6 -4
-			pr_warn_once("kcov: vm_insert_page() failed\n");
-			return res;
-		}
-	}
+
+	desc->vm_flags |= VM_DONTEXPAND;
+	nr_pages = size >> PAGE_SHIFT;
+
+	pages = mmap_action_mixedmap_pages(&desc->action, desc->start,
+					   nr_pages);

Hi Lorenzo,

Not sure if it belongs here before the EINVAL tests, but it looks like kcov->size doesn't have any page alignment. I think size could be 4000 bytes other unaligned values, so nr_pages should round up.

-chris

#54 lore raw

Re: [PATCH v2 16/16] kcov: update kcov to use mmap_prepare

Quoted 69 lines · Chris Mason
Quoted 54 lines · On Wed, 10 Sep 2025 21:22:11 +0100 Lorenzo Stoakes…

We can use the mmap insert pages functionality provided for use in mmap_prepare to insert the kcov pages as required.

This does necessitate an allocation, but since it's in the mmap path this doesn't seem egregious. The allocation/freeing of the pages array is handled automatically by vma_desc_set_mixedmap_pages() and the mapping logic.

---
 kernel/kcov.c | 42 ++++++++++++++++++++++++++----------------
 1 file changed, 26 insertions(+), 16 deletions(-)
kernel/kcov.c +12 -11
index 1d85597057e1..2bcf403e5f6f 100644
@@ -484,31 +484,41 @@ void kcov_task_exit(struct task_struct *t)
 	kcov_put(kcov);
 }
 
-static int kcov_mmap(struct file *filep, struct vm_area_struct *vma)
+static int kcov_mmap_error(int err)
+{
+	pr_warn_once("kcov: vm_insert_page() failed\n");
+	return err;
+}
+
+static int kcov_mmap_prepare(struct vm_area_desc *desc)
 {
 	int res = 0;
-	struct kcov *kcov = vma->vm_file->private_data;
-	unsigned long size, off;
-	struct page *page;
+	struct kcov *kcov = desc->file->private_data;
+	unsigned long size, nr_pages, i;
+	struct page **pages;
 	unsigned long flags;
 
 	spin_lock_irqsave(&kcov->lock, flags);
 	size = kcov->size * sizeof(unsigned long);
-	if (kcov->area == NULL || vma->vm_pgoff != 0 ||
-	    vma->vm_end - vma->vm_start != size) {
+	if (kcov->area == NULL || desc->pgoff != 0 ||
+	    vma_desc_size(desc) != size) {
 		res = -EINVAL;
 		goto exit;
 	}
 	spin_unlock_irqrestore(&kcov->lock, flags);
-	vm_flags_set(vma, VM_DONTEXPAND);
-	for (off = 0; off < size; off += PAGE_SIZE) {
-		page = vmalloc_to_page(kcov->area + off);
-		res = vm_insert_page(vma, vma->vm_start + off, page);
-		if (res) {

kernel/kcov.c void kcov_task_exit(struct task_struct *t) · line 514

Quoted 10 lines
kernel/kcov.c +6 -4
-			pr_warn_once("kcov: vm_insert_page() failed\n");
-			return res;
-		}
-	}
+
+	desc->vm_flags |= VM_DONTEXPAND;
+	nr_pages = size >> PAGE_SHIFT;
+
+	pages = mmap_action_mixedmap_pages(&desc->action, desc->start,
+					   nr_pages);

Hi Lorenzo,

Quoted 3 lines

Not sure if it belongs here before the EINVAL tests, but it looks like kcov->size doesn't have any page alignment. I think size could be 4000 bytes other unaligned values, so nr_pages should round up.

Thanks, you may well be right, but but this series has been respun and I no longer touch kcov. :)

Am at v4 now -
https://lore.kernel.org/linux-mm/[email protected]/
- apologies for the quick turnaround but going to kernel recipes soon and then on vacation so wanted to get this wrapped up!

Quoted 2 lines

-chris

Cheers, Lorenzo

maintainer
#55 lore raw
In reply to Lorenzo Stoakes
Quoted 12 lines · On Wed, 10 Sep 2025 21:21:55 +0100 Lorenzo Stoakes…

Since commit c84bf6dd2b83 ("mm: introduce new .mmap_prepare() file callback"), The f_op->mmap hook has been deprecated in favour of f_op->mmap_prepare.

This was introduced in order to make it possible for us to eventually eliminate the f_op->mmap hook which is highly problematic as it allows drivers and filesystems raw access to a VMA which is not yet correctly initialised.

This hook also introduced complexity for the memory mapping operation, as we must correctly unwind what we do should an error arises.

Quoted 7 lines

Overall this interface being so open has caused significant problems for us, including security issues, it is important for us to simply eliminate this as a source of problems.

Therefore this series continues what was established by extending the functionality further to permit more drivers and filesystems to use mmap_prepare.

Cool, I'll add this to mm-new but I'll suppress the usual emails.

#56 lore raw
Quoted 18 lines · Andrew Morton
Quoted 16 lines · On Wed, 10 Sep 2025 21:21:55 +0100 Lorenzo Stoakes…

Since commit c84bf6dd2b83 ("mm: introduce new .mmap_prepare() file callback"), The f_op->mmap hook has been deprecated in favour of f_op->mmap_prepare.

This was introduced in order to make it possible for us to eventually eliminate the f_op->mmap hook which is highly problematic as it allows drivers and filesystems raw access to a VMA which is not yet correctly initialised.

This hook also introduced complexity for the memory mapping operation, as we must correctly unwind what we do should an error arises.

Overall this interface being so open has caused significant problems for us, including security issues, it is important for us to simply eliminate this as a source of problems.

Quoted 5 lines
Quoted 3 lines

Therefore this series continues what was established by extending the functionality further to permit more drivers and filesystems to use mmap_prepare.

Cool, I'll add this to mm-new but I'll suppress the usual emails.

Thanks!