[PATCH 2/2] mm: introduce vma_set_file function

From: Christian König
Date: Mon Sep 14 2020 - 09:39:01 EST


Add the new vma_set_file() function to allow changing
vma->vm_file with the necessary refcount dance.

Signed-off-by: Christian König <christian.koenig@xxxxxxx>
---
drivers/dma-buf/dma-buf.c | 16 +++++-----------
include/linux/mm.h | 2 ++
mm/mmap.c | 16 ++++++++++++++++
3 files changed, 23 insertions(+), 11 deletions(-)

diff --git a/drivers/dma-buf/dma-buf.c b/drivers/dma-buf/dma-buf.c
index 1699a8e309ef..672f3525ba74 100644
--- a/drivers/dma-buf/dma-buf.c
+++ b/drivers/dma-buf/dma-buf.c
@@ -1163,20 +1163,14 @@ int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
return -EINVAL;

/* readjust the vma */
- get_file(dmabuf->file);
- oldfile = vma->vm_file;
- vma->vm_file = dmabuf->file;
+ oldfile = vma_set_file(vma, dmabuf->file);
vma->vm_pgoff = pgoff;

ret = dmabuf->ops->mmap(dmabuf, vma);
- if (ret) {
- /* restore old parameters on failure */
- vma->vm_file = oldfile;
- fput(dmabuf->file);
- } else {
- if (oldfile)
- fput(oldfile);
- }
+ /* restore old parameters on failure */
+ if (ret)
+ vma_set_file(vma, oldfile);
+
return ret;

}
diff --git a/include/linux/mm.h b/include/linux/mm.h
index 1983e08f5906..398a6fdaad1e 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -2688,6 +2688,8 @@ static inline void vma_set_page_prot(struct vm_area_struct *vma)
}
#endif

+struct file *vma_set_file(struct vm_area_struct *vma, struct file *file);
+
#ifdef CONFIG_NUMA_BALANCING
unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long start, unsigned long end);
diff --git a/mm/mmap.c b/mm/mmap.c
index 40248d84ad5f..d3c3c510f643 100644
--- a/mm/mmap.c
+++ b/mm/mmap.c
@@ -136,6 +136,22 @@ void vma_set_page_prot(struct vm_area_struct *vma)
WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
}

+/*
+ * Change backing file, only valid to use during initial VMA setup.
+ */
+struct file *vma_set_file(struct vm_area_struct *vma, struct file *file)
+{
+ if (file)
+ get_file(file);
+
+ swap(vma->vm_file, file);
+
+ if (file)
+ fput(file);
+
+ return file;
+}
+
/*
* Requires inode->i_mapping->i_mmap_rwsem
*/
--
2.17.1