[PATCH 1/6] kernfs: create vm_operations_struct without page_mkwrite()

From: Martin Oliveira
Date: Wed Jun 05 2024 - 15:30:57 EST


The standard kernfs vm_ops installs a page_mkwrite() operator which
modifies the file update time on write.

This not always required (or makes sense), such as in the P2PDMA, which
uses the sysfs file as an allocator from userspace.

Furthermore, having the page_mkwrite() operator causes
writable_file_mapping_allowed() to fail due to
vma_needs_dirty_tracking() on the gup flow, which is a pre-requisite for
enabling P2PDMA over RDMA.

Fix this by adding a new boolean on kernfs_ops to differentiate between
the different behaviours.

Co-developed-by: Logan Gunthorpe <logang@xxxxxxxxxxxx>
Signed-off-by: Logan Gunthorpe <logang@xxxxxxxxxxxx>
Signed-off-by: Martin Oliveira <martin.oliveira@xxxxxxxxxxxxx>
---
fs/kernfs/file.c | 15 ++++++++++++++-
include/linux/kernfs.h | 7 +++++++
2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/fs/kernfs/file.c b/fs/kernfs/file.c
index 8502ef68459b..d5e9fbded3dd 100644
--- a/fs/kernfs/file.c
+++ b/fs/kernfs/file.c
@@ -436,6 +436,12 @@ static const struct vm_operations_struct kernfs_vm_ops = {
.access = kernfs_vma_access,
};

+static const struct vm_operations_struct kernfs_vm_ops_mmap_allocates = {
+ .open = kernfs_vma_open,
+ .fault = kernfs_vma_fault,
+ .access = kernfs_vma_access,
+};
+
static int kernfs_fop_mmap(struct file *file, struct vm_area_struct *vma)
{
struct kernfs_open_file *of = kernfs_of(file);
@@ -482,13 +488,20 @@ static int kernfs_fop_mmap(struct file *file, struct vm_area_struct *vma)
if (vma->vm_ops && vma->vm_ops->close)
goto out_put;

+ if (ops->mmap_allocates)
+ vma->vm_ops = &kernfs_vm_ops_mmap_allocates;
+ else
+ vma->vm_ops = &kernfs_vm_ops;
+
+ if (ops->mmap_allocates && vma->vm_ops->page_mkwrite)
+ goto out_put;
+
rc = 0;
if (!of->mmapped) {
of->mmapped = true;
of_on(of)->nr_mmapped++;
of->vm_ops = vma->vm_ops;
}
- vma->vm_ops = &kernfs_vm_ops;
out_put:
kernfs_put_active(of->kn);
out_unlock:
diff --git a/include/linux/kernfs.h b/include/linux/kernfs.h
index 87c79d076d6d..d6ae7d4b0011 100644
--- a/include/linux/kernfs.h
+++ b/include/linux/kernfs.h
@@ -311,6 +311,13 @@ struct kernfs_ops {
* ->prealloc. Provide ->read and ->write with ->prealloc.
*/
bool prealloc;
+ /*
+ * Use the file as an allocator from userspace. This disables
+ * page_mkwrite() to prevent the file time from being updated on write
+ * which enables using GUP with FOLL_LONGTERM with memory that's been
+ * mmaped.
+ */
+ bool mmap_allocates;
ssize_t (*write)(struct kernfs_open_file *of, char *buf, size_t bytes,
loff_t off);

--
2.34.1