Skip to contentSkip to conversation

udmabuf bug fix and some improvements

PATCH In review Huan Yang 2 participants 10 messages Sep 18, 2024 – Sep 23, 2024

Subsystems (3)
lore
Share & tools
lore

Huan Yang

author
#0 lore raw

v7 cover udmabuf bug fix and some improvements

This patchset attempts to fix some errors in udmabuf and remove the upin_list structure, also try clean up code.

By this patchset, udmabuf remove page struct relay, only use pfn and folios.

Some of this fix just gather the patches which I upload before.

Any patch has passed the udmabuf self-test suite's tests. Suggested by Kasireddy, Vivek <[email protected]> Patch6 modified the unpin function, therefore running the udmabuf self-test program in a loop did not reveal any memory leaks.

Notice: Test item 6 maybe requires running the command:
echo 1024 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages

Changelog
===
v6 - > v7:
A little change, update some commit message.
Patch3: add fixes tag.
Patch4: update ack tag, remove the redundant if (!memfd) check from
check_memfd_seals(). update commit message.
Patch6: update commit message to describe how unpin array worked.
Patch7: update commit message to describe why need reuse the folios
array.
v5 -> v6:
Patch1 use Vivek's comments(thank you), fix code style, update ack-tag. Patch2, 3 no change.
Patch4 fix memfd miss fput, use Vivek's comments(thank you),
fix code style, update suggested-by.
Patch5 update ack-tag, fix error word in commit message. Patch6 update ack-tag, use xmas style.
Patch7 update ack-tag, remove unused ret variable.

---
v4 -> v5:
Patch1 doc why pre-fault failed not report error.
Patch2 no change
Patch3 update ack tag marked in v4
Patch4 split some change into patch5 and patch7, this only contains
udmabuf pin folio's function
Patch5 add helper init/deini to clean udmabuf struct initialized Patch6 remove unnecessary code
Patch7 remove reuse folio remove v4 patch4

---
v3 -> v4:
Patch1 fill vma area with pfn only when true access. Patch2 no change
Patch3 select VMAP_PFN
Patch4 use function pin each item.
Patch5 use pinned folio array instead udmabuf_folio struct.

---
v2 -> v3:
Patch1, avoid use page, instead, use pfn, and use vmf_insert_pfn map suggested-by Kasireddy, Vivek <[email protected]>

Patch2, update acked-by Kasireddy, Vivek <[email protected]> And keep the kvcalloc on the same line.

Patch3, avoid use page, instead, use pfn, then use vmap_pfn map

Patch4, split v2 patch4, single update codestyle to keep review easy.

Patch5, another way to remove udmabuf_folio

---
v1 -> v2:
Patch1, 3 Rectify the improper use of the sg table. suggested-by Christian König <[email protected]>

Patch2 add acked-by Christian K�nig <[email protected]> which marked in v1

Patch4
Modify the data structure to restore the use of pages and correct the misunderstanding of loop conditions such as "pgcnt". make sure pass self test.

remove v1's patch4
v6
https://lore.kernel.org/all/[email protected]/
v5
https://lore.kernel.org/all/[email protected]/
v4
https://lore.kernel.org/all/[email protected]/
v3
https://lore.kernel.org/all/[email protected]/
v2
https://lore.kernel.org/all/[email protected]/
v1
https://lore.kernel.org/all/[email protected]/

Huan Yang (7):
udmabuf: pre-fault when first page fault
udmabuf: change folios array from kmalloc to kvmalloc
udmabuf: fix vmap_udmabuf error page set
udmabuf: udmabuf_create pin folio codestyle cleanup
udmabuf: introduce udmabuf init and deinit helper
udmabuf: remove udmabuf_folio
udmabuf: reuse folio array when pin folios

 drivers/dma-buf/Kconfig   |   1 +
 drivers/dma-buf/udmabuf.c | 275 +++++++++++++++++++++++---------------
 2 files changed, 169 insertions(+), 107 deletions(-)

base-commit: 57f962b956f1d116cd64d5c406776c4975de549d

Signature · 1 line
2.45.2
author
#1 lore raw

PATCH v7 1/7 udmabuf: pre-fault when first page fault

The current udmabuf mmap only fills the physical memory to the corresponding virtual address when the user actually accesses the virtual address.

However, the current udmabuf has already obtained and pinned the folio upon completion of the creation.This means that the physical memory has already been acquired, rather than being accessed dynamically.

As a result, the page fault has lost its purpose as a demanding page. Due to the fact that page fault requires trapping into kernel mode and filling in when accessing the corresponding virtual address in mmap, when creating a large size udmabuf, this represents a considerable overhead.

This patch fill the pfn into page table, and then pre-fault each pfn into vma, when first access.

Notice, if anything wrong , we do not return an error during this pre-fault step. However, an error will be returned if the failure occurs when the addr is truly accessed

---
 drivers/dma-buf/udmabuf.c | 33 +++++++++++++++++++++++++++++++--
 1 file changed, 31 insertions(+), 2 deletions(-)
drivers/dma-buf/udmabuf.c +31 -2
index 047c3cd2ceff..2170d975cc76 100644
@@ -43,7 +43,8 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 	struct vm_area_struct *vma = vmf->vma;
 	struct udmabuf *ubuf = vma->vm_private_data;
 	pgoff_t pgoff = vmf->pgoff;
-	unsigned long pfn;
+	unsigned long addr, pfn;
+	vm_fault_t ret;
 
 	if (pgoff >= ubuf->pagecount)
 		return VM_FAULT_SIGBUS;
@@ -51,7 +52,35 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
 	pfn = folio_pfn(ubuf->folios[pgoff]);
 	pfn += ubuf->offsets[pgoff] >> PAGE_SHIFT;
 
-	return vmf_insert_pfn(vma, vmf->address, pfn);
+	ret = vmf_insert_pfn(vma, vmf->address, pfn);
+	if (ret & VM_FAULT_ERROR)
+		return ret;
+
+	/* pre fault */
+	pgoff = vma->vm_pgoff;
+	addr = vma->vm_start;
+
+	for (; addr < vma->vm_end; pgoff++, addr += PAGE_SIZE) {
+		if (addr == vmf->address)
+			continue;
+
+		if (WARN_ON(pgoff >= ubuf->pagecount))
+			break;
+
+		pfn = folio_pfn(ubuf->folios[pgoff]);
+		pfn += ubuf->offsets[pgoff] >> PAGE_SHIFT;
+
+		/**
+		 * If the below vmf_insert_pfn() fails, we do not return an
+		 * error here during this pre-fault step. However, an error
+		 * will be returned if the failure occurs when the addr is
+		 * truly accessed.
+		 */
+		if (vmf_insert_pfn(vma, addr, pfn) & VM_FAULT_ERROR)
+			break;
+	}
+
+	return ret;
 }
 
 static const struct vm_operations_struct udmabuf_vm_ops = {
Signature · 1 line
2.45.2
author
#2 lore raw

PATCH v7 2/7 udmabuf: change folios array from kmalloc to kvmalloc

In reply to Huan Yang

When PAGE_SIZE 4096, MAX_PAGE_ORDER 10, 64bit machine, page_alloc only support 4MB.
If above this, trigger this warn and return NULL.

udmabuf can change size limit, if change it to 3072(3GB), and then alloc 3GB udmabuf, will fail create.

[ 4080.876581] ------------[ cut here ]------------
[ 4080.876843] WARNING: CPU: 3 PID: 2015 at mm/page_alloc.c:4556 __alloc_pages+0x2c8/0x350
[ 4080.878839] RIP: 0010:__alloc_pages+0x2c8/0x350
[ 4080.879470] Call Trace:
[ 4080.879473]  <TASK>
[ 4080.879473]  ? __alloc_pages+0x2c8/0x350
[ 4080.879475]  ? __warn.cold+0x8e/0xe8
[ 4080.880647]  ? __alloc_pages+0x2c8/0x350
[ 4080.880909]  ? report_bug+0xff/0x140
[ 4080.881175]  ? handle_bug+0x3c/0x80
[ 4080.881556]  ? exc_invalid_op+0x17/0x70
[ 4080.881559]  ? asm_exc_invalid_op+0x1a/0x20
[ 4080.882077]  ? udmabuf_create+0x131/0x400

Because MAX_PAGE_ORDER, kmalloc can max alloc 4096 * (1 << 10), 4MB memory, each array entry is pointer(8byte), so can save 524288 pages(2GB).

Further more, costly order(order 3) may not be guaranteed that it can be applied for, due to fragmentation.

This patch change udmabuf array use kvmalloc_array, this can fallback alloc into vmalloc, which can guarantee allocation for any size and does not affect the performance of kmalloc allocations.

---
 drivers/dma-buf/udmabuf.c | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)
drivers/dma-buf/udmabuf.c +13 -13
index 2170d975cc76..ba9dbc7caf71 100644
@@ -109,7 +109,7 @@ static int vmap_udmabuf(struct dma_buf *buf, struct iosys_map *map)
 
 	dma_resv_assert_held(buf->resv);
 
-	pages = kmalloc_array(ubuf->pagecount, sizeof(*pages), GFP_KERNEL);
+	pages = kvmalloc_array(ubuf->pagecount, sizeof(*pages), GFP_KERNEL);
 	if (!pages)
 		return -ENOMEM;
 
@@ -117,7 +117,7 @@ static int vmap_udmabuf(struct dma_buf *buf, struct iosys_map *map)
 		pages[pg] = &ubuf->folios[pg]->page;
 
 	vaddr = vm_map_ram(pages, ubuf->pagecount, -1);
-	kfree(pages);
+	kvfree(pages);
 	if (!vaddr)
 		return -EINVAL;
 
@@ -225,8 +225,8 @@ static void release_udmabuf(struct dma_buf *buf)
 		put_sg_table(dev, ubuf->sg, DMA_BIDIRECTIONAL);
 
 	unpin_all_folios(&ubuf->unpin_list);
-	kfree(ubuf->offsets);
-	kfree(ubuf->folios);
+	kvfree(ubuf->offsets);
+	kvfree(ubuf->folios);
 	kfree(ubuf);
 }
 
@@ -351,14 +351,14 @@ static long udmabuf_create(struct miscdevice *device,
 	if (!ubuf->pagecount)
 		goto err;
 
-	ubuf->folios = kmalloc_array(ubuf->pagecount, sizeof(*ubuf->folios),
-				    GFP_KERNEL);
+	ubuf->folios = kvmalloc_array(ubuf->pagecount, sizeof(*ubuf->folios),
+				      GFP_KERNEL);
 	if (!ubuf->folios) {
 		ret = -ENOMEM;
 		goto err;
 	}
-	ubuf->offsets = kcalloc(ubuf->pagecount, sizeof(*ubuf->offsets),
-				GFP_KERNEL);
+	ubuf->offsets = kvcalloc(ubuf->pagecount, sizeof(*ubuf->offsets),
+				 GFP_KERNEL);
 	if (!ubuf->offsets) {
 		ret = -ENOMEM;
 		goto err;
@@ -372,7 +372,7 @@ static long udmabuf_create(struct miscdevice *device,
 			goto err;
 
 		pgcnt = list[i].size >> PAGE_SHIFT;
-		folios = kmalloc_array(pgcnt, sizeof(*folios), GFP_KERNEL);
+		folios = kvmalloc_array(pgcnt, sizeof(*folios), GFP_KERNEL);
 		if (!folios) {
 			ret = -ENOMEM;
 			goto err;
@@ -382,7 +382,7 @@ static long udmabuf_create(struct miscdevice *device,
 		ret = memfd_pin_folios(memfd, list[i].offset, end,
 				       folios, pgcnt, &pgoff);
 		if (ret <= 0) {
-			kfree(folios);
+			kvfree(folios);
 			if (!ret)
 				ret = -EINVAL;
 			goto err;
@@ -411,7 +411,7 @@ static long udmabuf_create(struct miscdevice *device,
 			}
 		}
 
-		kfree(folios);
+		kvfree(folios);
 		fput(memfd);
 		memfd = NULL;
 	}
@@ -427,8 +427,8 @@ static long udmabuf_create(struct miscdevice *device,
 	if (memfd)
 		fput(memfd);
 	unpin_all_folios(&ubuf->unpin_list);
-	kfree(ubuf->offsets);
-	kfree(ubuf->folios);
+	kvfree(ubuf->offsets);
+	kvfree(ubuf->folios);
 	kfree(ubuf);
 	return ret;
 }
Signature · 1 line
2.45.2
author
#3 lore raw

PATCH v7 3/7 udmabuf: fix vmap_udmabuf error page set

In reply to Huan Yang

Currently vmap_udmabuf set page's array by each folio. But, ubuf->folios is only contain's the folio's head page.

That mean we repeatedly mapped the folio head page to the vmalloc area.

Due to udmabuf can use hugetlb, if HVO enabled, tail page may not exist, so, we can't use page array to map, instead, use pfn array.

By this, we removed page usage in udmabuf totally.

Fixes 5e72b2b41a21 ("udmabuf: convert udmabuf driver to use folios")
---
 drivers/dma-buf/Kconfig   |  1 +
 drivers/dma-buf/udmabuf.c | 22 +++++++++++++++-------
 2 files changed, 16 insertions(+), 7 deletions(-)
drivers/dma-buf/Kconfig +1 -0
index b46eb8a552d7..fee04fdb0822 100644
@@ -36,6 +36,7 @@ config UDMABUF
 	depends on DMA_SHARED_BUFFER
 	depends on MEMFD_CREATE || COMPILE_TEST
 	depends on MMU
+	select VMAP_PFN
 	help
 	  A driver to let userspace turn memfd regions into dma-bufs.
 	  Qemu can use this to create host dmabufs for guest framebuffers.
drivers/dma-buf/udmabuf.c +15 -7
index ba9dbc7caf71..aa182a9dcdfa 100644
@@ -103,21 +103,29 @@ static int mmap_udmabuf(struct dma_buf *buf, struct vm_area_struct *vma)
 static int vmap_udmabuf(struct dma_buf *buf, struct iosys_map *map)
 {
 	struct udmabuf *ubuf = buf->priv;
-	struct page **pages;
+	unsigned long *pfns;
 	void *vaddr;
 	pgoff_t pg;
 
 	dma_resv_assert_held(buf->resv);
 
-	pages = kvmalloc_array(ubuf->pagecount, sizeof(*pages), GFP_KERNEL);
-	if (!pages)
+	/**
+	 * HVO may free tail pages, so just use pfn to map each folio
+	 * into vmalloc area.
+	 */
+	pfns = kvmalloc_array(ubuf->pagecount, sizeof(*pfns), GFP_KERNEL);
+	if (!pfns)
 		return -ENOMEM;
 
-	for (pg = 0; pg < ubuf->pagecount; pg++)
-		pages[pg] = &ubuf->folios[pg]->page;
+	for (pg = 0; pg < ubuf->pagecount; pg++) {
+		unsigned long pfn = folio_pfn(ubuf->folios[pg]);
 
-	vaddr = vm_map_ram(pages, ubuf->pagecount, -1);
-	kvfree(pages);
+		pfn += ubuf->offsets[pg] >> PAGE_SHIFT;
+		pfns[pg] = pfn;
+	}
+
+	vaddr = vmap_pfn(pfns, ubuf->pagecount, PAGE_KERNEL);
+	kvfree(pfns);
 	if (!vaddr)
 		return -EINVAL;
 
Signature · 1 line
2.45.2
author
#4 lore raw

PATCH v7 4/7 udmabuf: udmabuf_create pin folio codestyle cleanup

In reply to Huan Yang

This patch aim to simplify the memfd folio pin during the udmabuf create. No functional changes.

This patch create a udmabuf_pin_folios function, in this, do the memfd pin folio and then record each pinned folio, offset.

This patch simplify the pinned folio record, iter by each pinned folio, and then record each offset in it.

Compare to iter by pgcnt, more readable.

---
 drivers/dma-buf/udmabuf.c | 137 +++++++++++++++++++++-----------------
 1 file changed, 76 insertions(+), 61 deletions(-)
drivers/dma-buf/udmabuf.c +76 -61
index aa182a9dcdfa..9d58c045b8eb 100644
@@ -291,9 +291,6 @@ static int check_memfd_seals(struct file *memfd)
 {
 	int seals;
 
-	if (!memfd)
-		return -EBADFD;
-
 	if (!shmem_file(memfd) && !is_file_hugepages(memfd))
 		return -EBADFD;
 
@@ -328,17 +325,68 @@ static int export_udmabuf(struct udmabuf *ubuf,
 	return dma_buf_fd(buf, flags);
 }
 
+static long udmabuf_pin_folios(struct udmabuf *ubuf, struct file *memfd,
+			       loff_t start, loff_t size)
+{
+	pgoff_t pgoff, pgcnt, upgcnt = ubuf->pagecount;
+	struct folio **folios = NULL;
+	u32 cur_folio, cur_pgcnt;
+	long nr_folios;
+	long ret = 0;
+	loff_t end;
+
+	pgcnt = size >> PAGE_SHIFT;
+	folios = kvmalloc_array(pgcnt, sizeof(*folios), GFP_KERNEL);
+	if (!folios)
+		return -ENOMEM;
+
+	end = start + (pgcnt << PAGE_SHIFT) - 1;
+	nr_folios = memfd_pin_folios(memfd, start, end, folios, pgcnt, &pgoff);
+	if (nr_folios <= 0) {
+		ret = nr_folios ? nr_folios : -EINVAL;
+		goto end;
+	}
+
+	cur_pgcnt = 0;
+	for (cur_folio = 0; cur_folio < nr_folios; ++cur_folio) {
+		pgoff_t subpgoff = pgoff;
+		size_t fsize = folio_size(folios[cur_folio]);
+
+		ret = add_to_unpin_list(&ubuf->unpin_list, folios[cur_folio]);
+		if (ret < 0)
+			goto end;
+
+		for (; subpgoff < fsize; subpgoff += PAGE_SIZE) {
+			ubuf->folios[upgcnt] = folios[cur_folio];
+			ubuf->offsets[upgcnt] = subpgoff;
+			++upgcnt;
+
+			if (++cur_pgcnt >= pgcnt)
+				goto end;
+		}
+
+		/**
+		 * In a given range, only the first subpage of the first folio
+		 * has an offset, that is returned by memfd_pin_folios().
+		 * The first subpages of other folios (in the range) have an
+		 * offset of 0.
+		 */
+		pgoff = 0;
+	}
+end:
+	ubuf->pagecount = upgcnt;
+	kvfree(folios);
+	return ret;
+}
+
 static long udmabuf_create(struct miscdevice *device,
 			   struct udmabuf_create_list *head,
 			   struct udmabuf_create_item *list)
 {
-	pgoff_t pgoff, pgcnt, pglimit, pgbuf = 0;
-	long nr_folios, ret = -EINVAL;
-	struct file *memfd = NULL;
-	struct folio **folios;
+	pgoff_t pgcnt = 0, pglimit;
 	struct udmabuf *ubuf;
-	u32 i, j, k, flags;
-	loff_t end;
+	long ret = -EINVAL;
+	u32 i, flags;
 
 	ubuf = kzalloc(sizeof(*ubuf), GFP_KERNEL);
 	if (!ubuf)
@@ -347,81 +395,50 @@ static long udmabuf_create(struct miscdevice *device,
 	INIT_LIST_HEAD(&ubuf->unpin_list);
 	pglimit = (size_limit_mb * 1024 * 1024) >> PAGE_SHIFT;
 	for (i = 0; i < head->count; i++) {
-		if (!IS_ALIGNED(list[i].offset, PAGE_SIZE))
+		if (!PAGE_ALIGNED(list[i].offset))
 			goto err;
-		if (!IS_ALIGNED(list[i].size, PAGE_SIZE))
+		if (!PAGE_ALIGNED(list[i].size))
 			goto err;
-		ubuf->pagecount += list[i].size >> PAGE_SHIFT;
-		if (ubuf->pagecount > pglimit)
+
+		pgcnt += list[i].size >> PAGE_SHIFT;
+		if (pgcnt > pglimit)
 			goto err;
 	}
 
-	if (!ubuf->pagecount)
+	if (!pgcnt)
 		goto err;
 
-	ubuf->folios = kvmalloc_array(ubuf->pagecount, sizeof(*ubuf->folios),
-				      GFP_KERNEL);
+	ubuf->folios = kvmalloc_array(pgcnt, sizeof(*ubuf->folios), GFP_KERNEL);
 	if (!ubuf->folios) {
 		ret = -ENOMEM;
 		goto err;
 	}
-	ubuf->offsets = kvcalloc(ubuf->pagecount, sizeof(*ubuf->offsets),
-				 GFP_KERNEL);
+
+	ubuf->offsets = kvcalloc(pgcnt, sizeof(*ubuf->offsets), GFP_KERNEL);
 	if (!ubuf->offsets) {
 		ret = -ENOMEM;
 		goto err;
 	}
 
-	pgbuf = 0;
 	for (i = 0; i < head->count; i++) {
-		memfd = fget(list[i].memfd);
-		ret = check_memfd_seals(memfd);
-		if (ret < 0)
-			goto err;
+		struct file *memfd = fget(list[i].memfd);
 
-		pgcnt = list[i].size >> PAGE_SHIFT;
-		folios = kvmalloc_array(pgcnt, sizeof(*folios), GFP_KERNEL);
-		if (!folios) {
-			ret = -ENOMEM;
+		if (!memfd) {
+			ret = -EBADFD;
 			goto err;
 		}
 
-		end = list[i].offset + (pgcnt << PAGE_SHIFT) - 1;
-		ret = memfd_pin_folios(memfd, list[i].offset, end,
-				       folios, pgcnt, &pgoff);
-		if (ret <= 0) {
-			kvfree(folios);
-			if (!ret)
-				ret = -EINVAL;
+		ret = check_memfd_seals(memfd);
+		if (ret < 0) {
+			fput(memfd);
 			goto err;
 		}
 
-		nr_folios = ret;
-		pgoff >>= PAGE_SHIFT;
-		for (j = 0, k = 0; j < pgcnt; j++) {
-			ubuf->folios[pgbuf] = folios[k];
-			ubuf->offsets[pgbuf] = pgoff << PAGE_SHIFT;
-
-			if (j == 0 || ubuf->folios[pgbuf-1] != folios[k]) {
-				ret = add_to_unpin_list(&ubuf->unpin_list,
-							folios[k]);
-				if (ret < 0) {
-					kfree(folios);
-					goto err;
-				}
-			}
-
-			pgbuf++;
-			if (++pgoff == folio_nr_pages(folios[k])) {
-				pgoff = 0;
-				if (++k == nr_folios)
-					break;
-			}
-		}
-
-		kvfree(folios);
+		ret = udmabuf_pin_folios(ubuf, memfd, list[i].offset,
+					 list[i].size);
 		fput(memfd);
-		memfd = NULL;
+		if (ret)
+			goto err;
 	}
 
 	flags = head->flags & UDMABUF_FLAGS_CLOEXEC ? O_CLOEXEC : 0;
@@ -432,8 +449,6 @@ static long udmabuf_create(struct miscdevice *device,
 	return ret;
 
 err:
-	if (memfd)
-		fput(memfd);
 	unpin_all_folios(&ubuf->unpin_list);
 	kvfree(ubuf->offsets);
 	kvfree(ubuf->folios);
Signature · 1 line
2.45.2
author
#5 lore raw

PATCH v7 5/7 udmabuf: introduce udmabuf init and deinit helper

In reply to Huan Yang

After udmabuf is allocated, its resources need to be initialized, including various array structures. The current array structure has already been greatly expanded.

Also, before udmabuf needs to be kfree, the occupied resources need to be released.

This part is repetitive and maybe overlooked.

This patch give a helper function when init and deinit, by this, reduce duplicate code.

---
 drivers/dma-buf/udmabuf.c | 52 +++++++++++++++++++++++----------------
 1 file changed, 31 insertions(+), 21 deletions(-)
drivers/dma-buf/udmabuf.c +31 -21
index 9d58c045b8eb..40ebff2c77f4 100644
@@ -224,6 +224,28 @@ static int add_to_unpin_list(struct list_head *unpin_list,
 	return 0;
 }
 
+static __always_inline int init_udmabuf(struct udmabuf *ubuf, pgoff_t pgcnt)
+{
+	INIT_LIST_HEAD(&ubuf->unpin_list);
+
+	ubuf->folios = kvmalloc_array(pgcnt, sizeof(*ubuf->folios), GFP_KERNEL);
+	if (!ubuf->folios)
+		return -ENOMEM;
+
+	ubuf->offsets = kvcalloc(pgcnt, sizeof(*ubuf->offsets), GFP_KERNEL);
+	if (!ubuf->offsets)
+		return -ENOMEM;
+
+	return 0;
+}
+
+static __always_inline void deinit_udmabuf(struct udmabuf *ubuf)
+{
+	unpin_all_folios(&ubuf->unpin_list);
+	kvfree(ubuf->offsets);
+	kvfree(ubuf->folios);
+}
+
 static void release_udmabuf(struct dma_buf *buf)
 {
 	struct udmabuf *ubuf = buf->priv;
@@ -232,9 +254,7 @@ static void release_udmabuf(struct dma_buf *buf)
 	if (ubuf->sg)
 		put_sg_table(dev, ubuf->sg, DMA_BIDIRECTIONAL);
 
-	unpin_all_folios(&ubuf->unpin_list);
-	kvfree(ubuf->offsets);
-	kvfree(ubuf->folios);
+	deinit_udmabuf(ubuf);
 	kfree(ubuf);
 }
 
@@ -392,33 +412,24 @@ static long udmabuf_create(struct miscdevice *device,
 	if (!ubuf)
 		return -ENOMEM;
 
-	INIT_LIST_HEAD(&ubuf->unpin_list);
 	pglimit = (size_limit_mb * 1024 * 1024) >> PAGE_SHIFT;
 	for (i = 0; i < head->count; i++) {
 		if (!PAGE_ALIGNED(list[i].offset))
-			goto err;
+			goto err_noinit;
 		if (!PAGE_ALIGNED(list[i].size))
-			goto err;
+			goto err_noinit;
 
 		pgcnt += list[i].size >> PAGE_SHIFT;
 		if (pgcnt > pglimit)
-			goto err;
+			goto err_noinit;
 	}
 
 	if (!pgcnt)
-		goto err;
+		goto err_noinit;
 
-	ubuf->folios = kvmalloc_array(pgcnt, sizeof(*ubuf->folios), GFP_KERNEL);
-	if (!ubuf->folios) {
-		ret = -ENOMEM;
+	ret = init_udmabuf(ubuf, pgcnt);
+	if (ret)
 		goto err;
-	}
-
-	ubuf->offsets = kvcalloc(pgcnt, sizeof(*ubuf->offsets), GFP_KERNEL);
-	if (!ubuf->offsets) {
-		ret = -ENOMEM;
-		goto err;
-	}
 
 	for (i = 0; i < head->count; i++) {
 		struct file *memfd = fget(list[i].memfd);
@@ -449,9 +460,8 @@ static long udmabuf_create(struct miscdevice *device,
 	return ret;
 
 err:
-	unpin_all_folios(&ubuf->unpin_list);
-	kvfree(ubuf->offsets);
-	kvfree(ubuf->folios);
+	deinit_udmabuf(ubuf);
+err_noinit:
 	kfree(ubuf);
 	return ret;
 }
Signature · 1 line
2.45.2
author
#6 lore raw

PATCH v7 6/7 udmabuf: remove udmabuf_folio

In reply to Huan Yang

Currently, udmabuf handles folio by create an unpin list to record each folio obtained from the list and unpinning them when released. To maintain this, many struct have been established.

However, maintain this requires a significant amount of memory and iter the list is a substantial overhead, which is not friendly to the CPU cache.

When create, we arranged the folio array in the order of pin and set the offset according to pgcnt. So, if record each pinned folio when create, then can easy unpin it. Compare to use list to record it, an array also can do this.

Hence, this patch setup a pinned_folios array(size is the pgcnt) to instead of udmabuf_folio struct, it record each folio which pinned when invoke memfd_pin_folios, then unpin folio by iter pinned_folios.

Note that, since a folio may be pinned multiple times, each folio can be added to pinned_folios multiple times, depend on how many times the folio has been pinned when create.

Compare to udmabuf_folio(24 byte size), a folio pointer is 8 byte, if no large folio - each folio is PAGE_SIZE - and need to unpin when release. So need to record each folio, by this patch, each folio can save 16 byte.

But if large folio used, depend on the large folio's number, the pinned_folios array may take more memory, but it still can makes unpin access more cache-friendly.

---
 drivers/dma-buf/udmabuf.c | 65 +++++++++++++++++----------------------
 1 file changed, 29 insertions(+), 36 deletions(-)
drivers/dma-buf/udmabuf.c +29 -36
index 40ebff2c77f4..24badfefa6b4 100644
@@ -27,15 +27,21 @@ MODULE_PARM_DESC(size_limit_mb, "Max size of a dmabuf, in megabytes. Default is
 struct udmabuf {
 	pgoff_t pagecount;
 	struct folio **folios;
+
+	/**
+	 * Unlike folios, pinned_folios is only used for unpin.
+	 * So, nr_pinned is not the same to pagecount, the pinned_folios
+	 * only set each folio which already pinned when udmabuf_create.
+	 * Note that, since a folio may be pinned multiple times, each folio
+	 * can be added to pinned_folios multiple times, depending on how many
+	 * times the folio has been pinned when create.
+	 */
+	pgoff_t nr_pinned;
+	struct folio **pinned_folios;
+
 	struct sg_table *sg;
 	struct miscdevice *device;
 	pgoff_t *offsets;
-	struct list_head unpin_list;
-};
-
-struct udmabuf_folio {
-	struct folio *folio;
-	struct list_head list;
 };
 
 static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
@@ -196,38 +202,18 @@ static void unmap_udmabuf(struct dma_buf_attachment *at,
 	return put_sg_table(at->dev, sg, direction);
 }
 
-static void unpin_all_folios(struct list_head *unpin_list)
+static void unpin_all_folios(struct udmabuf *ubuf)
 {
-	struct udmabuf_folio *ubuf_folio;
+	pgoff_t i;
 
-	while (!list_empty(unpin_list)) {
-		ubuf_folio = list_first_entry(unpin_list,
-					      struct udmabuf_folio, list);
-		unpin_folio(ubuf_folio->folio);
+	for (i = 0; i < ubuf->nr_pinned; ++i)
+		unpin_folio(ubuf->pinned_folios[i]);
 
-		list_del(&ubuf_folio->list);
-		kfree(ubuf_folio);
-	}
-}
-
-static int add_to_unpin_list(struct list_head *unpin_list,
-			     struct folio *folio)
-{
-	struct udmabuf_folio *ubuf_folio;
-
-	ubuf_folio = kzalloc(sizeof(*ubuf_folio), GFP_KERNEL);
-	if (!ubuf_folio)
-		return -ENOMEM;
-
-	ubuf_folio->folio = folio;
-	list_add_tail(&ubuf_folio->list, unpin_list);
-	return 0;
+	kvfree(ubuf->pinned_folios);
 }
 
 static __always_inline int init_udmabuf(struct udmabuf *ubuf, pgoff_t pgcnt)
 {
-	INIT_LIST_HEAD(&ubuf->unpin_list);
-
 	ubuf->folios = kvmalloc_array(pgcnt, sizeof(*ubuf->folios), GFP_KERNEL);
 	if (!ubuf->folios)
 		return -ENOMEM;
@@ -236,12 +222,18 @@ static __always_inline int init_udmabuf(struct udmabuf *ubuf, pgoff_t pgcnt)
 	if (!ubuf->offsets)
 		return -ENOMEM;
 
+	ubuf->pinned_folios = kvmalloc_array(pgcnt,
+					     sizeof(*ubuf->pinned_folios),
+					     GFP_KERNEL);
+	if (!ubuf->pinned_folios)
+		return -ENOMEM;
+
 	return 0;
 }
 
 static __always_inline void deinit_udmabuf(struct udmabuf *ubuf)
 {
-	unpin_all_folios(&ubuf->unpin_list);
+	unpin_all_folios(ubuf);
 	kvfree(ubuf->offsets);
 	kvfree(ubuf->folios);
 }
@@ -348,9 +340,11 @@ static int export_udmabuf(struct udmabuf *ubuf,
 static long udmabuf_pin_folios(struct udmabuf *ubuf, struct file *memfd,
 			       loff_t start, loff_t size)
 {
-	pgoff_t pgoff, pgcnt, upgcnt = ubuf->pagecount;
+	pgoff_t nr_pinned = ubuf->nr_pinned;
+	pgoff_t upgcnt = ubuf->pagecount;
 	struct folio **folios = NULL;
 	u32 cur_folio, cur_pgcnt;
+	pgoff_t pgoff, pgcnt;
 	long nr_folios;
 	long ret = 0;
 	loff_t end;
@@ -372,9 +366,7 @@ static long udmabuf_pin_folios(struct udmabuf *ubuf, struct file *memfd,
 		pgoff_t subpgoff = pgoff;
 		size_t fsize = folio_size(folios[cur_folio]);
 
-		ret = add_to_unpin_list(&ubuf->unpin_list, folios[cur_folio]);
-		if (ret < 0)
-			goto end;
+		ubuf->pinned_folios[nr_pinned++] = folios[cur_folio];
 
 		for (; subpgoff < fsize; subpgoff += PAGE_SIZE) {
 			ubuf->folios[upgcnt] = folios[cur_folio];
@@ -395,6 +387,7 @@ static long udmabuf_pin_folios(struct udmabuf *ubuf, struct file *memfd,
 	}
 end:
 	ubuf->pagecount = upgcnt;
+	ubuf->nr_pinned = nr_pinned;
 	kvfree(folios);
 	return ret;
 }
Signature · 1 line
2.45.2
author
#7 lore raw

PATCH v7 7/7 udmabuf: reuse folio array when pin folios

In reply to Huan Yang

When invoke memfd_pin_folios, we need offer an array to save each folio which we pinned.

The current way is dynamic alloc an array(use kvmalloc), get folios, save into udmabuf and then free.

Depend on the size, kvmalloc can do something different:

Below PAGE_SIZE, slab allocator will be used, which have good alloc performance, due to it cached page.

PAGE_SIZE - PCP Order, PCP(per-cpu-pageset) also given buddy page a cache in each CPU, so different CPU no need to hold some lock(zone or some) to get the locally page. If PCP cached page, the access also fast.

PAGE_SIZE - BUDDY_MAX, try to get page from buddy, due to kvmalloc adjusted the gfp flags, if zone freelist can't alloc page(fast path), we will not enter slowpath to reclaim memory. Due to need hold lock and check, may slow, but still fast than vmalloc.

Anything wrong will fallback into vmalloc to alloc memory, it obtains contiguous virtual addresses by loop alloc order 0 page(PAGE_SIZE), and then map it into vmalloc area. If necessary, page alloc may enter slowpath to reclaim memory. Hence, if fallback into vmalloc, it's slow.

When create, we need to iter each udmabuf item, then pin it's range folios, if each item's range folio's count is large, we may fallback each into vmalloc.

This patch find the largest range folio in items, then alloc this size's folio array. When pin range folios, reuse this array.

---
 drivers/dma-buf/udmabuf.c | 36 +++++++++++++++++++++---------------
 1 file changed, 21 insertions(+), 15 deletions(-)
drivers/dma-buf/udmabuf.c +21 -15
index 24badfefa6b4..8ce1f074c2d3 100644
@@ -338,28 +338,20 @@ static int export_udmabuf(struct udmabuf *ubuf,
 }
 
 static long udmabuf_pin_folios(struct udmabuf *ubuf, struct file *memfd,
-			       loff_t start, loff_t size)
+			       loff_t start, loff_t size, struct folio **folios)
 {
 	pgoff_t nr_pinned = ubuf->nr_pinned;
 	pgoff_t upgcnt = ubuf->pagecount;
-	struct folio **folios = NULL;
 	u32 cur_folio, cur_pgcnt;
 	pgoff_t pgoff, pgcnt;
 	long nr_folios;
-	long ret = 0;
 	loff_t end;
 
 	pgcnt = size >> PAGE_SHIFT;
-	folios = kvmalloc_array(pgcnt, sizeof(*folios), GFP_KERNEL);
-	if (!folios)
-		return -ENOMEM;
-
 	end = start + (pgcnt << PAGE_SHIFT) - 1;
 	nr_folios = memfd_pin_folios(memfd, start, end, folios, pgcnt, &pgoff);
-	if (nr_folios <= 0) {
-		ret = nr_folios ? nr_folios : -EINVAL;
-		goto end;
-	}
+	if (nr_folios <= 0)
+		return nr_folios ? nr_folios : -EINVAL;
 
 	cur_pgcnt = 0;
 	for (cur_folio = 0; cur_folio < nr_folios; ++cur_folio) {
@@ -388,14 +380,15 @@ static long udmabuf_pin_folios(struct udmabuf *ubuf, struct file *memfd,
 end:
 	ubuf->pagecount = upgcnt;
 	ubuf->nr_pinned = nr_pinned;
-	kvfree(folios);
-	return ret;
+	return 0;
 }
 
 static long udmabuf_create(struct miscdevice *device,
 			   struct udmabuf_create_list *head,
 			   struct udmabuf_create_item *list)
 {
+	unsigned long max_nr_folios = 0;
+	struct folio **folios = NULL;
 	pgoff_t pgcnt = 0, pglimit;
 	struct udmabuf *ubuf;
 	long ret = -EINVAL;
@@ -407,14 +400,19 @@ static long udmabuf_create(struct miscdevice *device,
 
 	pglimit = (size_limit_mb * 1024 * 1024) >> PAGE_SHIFT;
 	for (i = 0; i < head->count; i++) {
+		pgoff_t subpgcnt;
+
 		if (!PAGE_ALIGNED(list[i].offset))
 			goto err_noinit;
 		if (!PAGE_ALIGNED(list[i].size))
 			goto err_noinit;
 
-		pgcnt += list[i].size >> PAGE_SHIFT;
+		subpgcnt = list[i].size >> PAGE_SHIFT;
+		pgcnt += subpgcnt;
 		if (pgcnt > pglimit)
 			goto err_noinit;
+
+		max_nr_folios = max_t(unsigned long, subpgcnt, max_nr_folios);
 	}
 
 	if (!pgcnt)
@@ -424,6 +422,12 @@ static long udmabuf_create(struct miscdevice *device,
 	if (ret)
 		goto err;
 
+	folios = kvmalloc_array(max_nr_folios, sizeof(*folios), GFP_KERNEL);
+	if (!folios) {
+		ret = -ENOMEM;
+		goto err;
+	}
+
 	for (i = 0; i < head->count; i++) {
 		struct file *memfd = fget(list[i].memfd);
 
@@ -439,7 +443,7 @@ static long udmabuf_create(struct miscdevice *device,
 		}
 
 		ret = udmabuf_pin_folios(ubuf, memfd, list[i].offset,
-					 list[i].size);
+					 list[i].size, folios);
 		fput(memfd);
 		if (ret)
 			goto err;
@@ -450,12 +454,14 @@ static long udmabuf_create(struct miscdevice *device,
 	if (ret < 0)
 		goto err;
 
+	kvfree(folios);
 	return ret;
 
 err:
 	deinit_udmabuf(ubuf);
 err_noinit:
 	kfree(ubuf);
+	kvfree(folios);
 	return ret;
 }
 
Signature · 1 line
2.45.2
maintainer
#8 lore raw
In reply to Huan Yang

Hi Huan,

Quoted 10 lines

Subject: [PATCH v7 0/7] udmabuf bug fix and some improvements

This patchset attempts to fix some errors in udmabuf and remove the upin_list structure, also try clean up code.

By this patchset, udmabuf remove page struct relay, only use pfn and folios.

Some of this fix just gather the patches which I upload before.

Quoted 7 lines

Any patch has passed the udmabuf self-test suite's tests. Suggested by Kasireddy, Vivek <[email protected]> Patch6 modified the unpin function, therefore running the udmabuf self-test program in a loop did not reveal any memory leaks.

Notice: Test item 6 maybe requires running the command:
echo 1024 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages

Thank you for the patches. Series applied to drm-misc-next.

Thanks,
Vivek

Quoted 97 lines

Changelog
===
v6 - > v7:
A little change, update some commit message.
Patch3: add fixes tag.
Patch4: update ack tag, remove the redundant if (!memfd) check from
check_memfd_seals(). update commit message.
Patch6: update commit message to describe how unpin array worked.
Patch7: update commit message to describe why need reuse the folios
array.
v5 -> v6:
Patch1 use Vivek's comments(thank you), fix code style, update ack-tag. Patch2, 3 no change.
Patch4 fix memfd miss fput, use Vivek's comments(thank you),
fix code style, update suggested-by.
Patch5 update ack-tag, fix error word in commit message. Patch6 update ack-tag, use xmas style.
Patch7 update ack-tag, remove unused ret variable.

---
v4 -> v5:
Patch1 doc why pre-fault failed not report error.
Patch2 no change
Patch3 update ack tag marked in v4
Patch4 split some change into patch5 and patch7, this only contains
udmabuf pin folio's function
Patch5 add helper init/deini to clean udmabuf struct initialized Patch6 remove unnecessary code
Patch7 remove reuse folio remove v4 patch4

---
v3 -> v4:
Patch1 fill vma area with pfn only when true access. Patch2 no change
Patch3 select VMAP_PFN
Patch4 use function pin each item.
Patch5 use pinned folio array instead udmabuf_folio struct.

---
v2 -> v3:
Patch1, avoid use page, instead, use pfn, and use vmf_insert_pfn map suggested-by Kasireddy, Vivek <[email protected]>

Patch2, update acked-by Kasireddy, Vivek <[email protected]> And keep the kvcalloc on the same line.

Patch3, avoid use page, instead, use pfn, then use vmap_pfn map

Patch4, split v2 patch4, single update codestyle to keep review easy.

Patch5, another way to remove udmabuf_folio

---
v1 -> v2:
Patch1, 3 Rectify the improper use of the sg table. suggested-by Christian König <[email protected]>

Patch2 add acked-by Christian K�nig <[email protected]> which marked in v1

Patch4
Modify the data structure to restore the use of pages and correct the misunderstanding of loop conditions such as "pgcnt". make sure pass self test.

remove v1's patch4
v6
https://lore.kernel.org/all/[email protected]/
v5
https://lore.kernel.org/all/[email protected]/
v4
https://lore.kernel.org/all/[email protected]/
v3
https://lore.kernel.org/all/[email protected]/
v2
https://lore.kernel.org/all/[email protected]/
v1
https://lore.kernel.org/all/[email protected]/

Huan Yang (7):
udmabuf: pre-fault when first page fault
udmabuf: change folios array from kmalloc to kvmalloc
udmabuf: fix vmap_udmabuf error page set
udmabuf: udmabuf_create pin folio codestyle cleanup
udmabuf: introduce udmabuf init and deinit helper
udmabuf: remove udmabuf_folio
udmabuf: reuse folio array when pin folios

 drivers/dma-buf/Kconfig   |   1 +
 drivers/dma-buf/udmabuf.c | 275 +++++++++++++++++++++++---------------
 2 files changed, 169 insertions(+), 107 deletions(-)

base-commit: 57f962b956f1d116cd64d5c406776c4975de549d --
2.45.2

author
#9 lore raw
Quoted 12 lines · Vivek

Hi Huan,

Quoted 10 lines

Subject: [PATCH v7 0/7] udmabuf bug fix and some improvements

This patchset attempts to fix some errors in udmabuf and remove the upin_list structure, also try clean up code.

By this patchset, udmabuf remove page struct relay, only use pfn and folios.

Some of this fix just gather the patches which I upload before.

Quoted 8 lines
Quoted 7 lines

Any patch has passed the udmabuf self-test suite's tests. Suggested by Kasireddy, Vivek <[email protected]> Patch6 modified the unpin function, therefore running the udmabuf self-test program in a loop did not reveal any memory leaks.

Notice: Test item 6 maybe requires running the command:

   echo 1024 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages

Thank you for the patches. Series applied to drm-misc-next.

OK, Thanks. :)

Quoted 101 lines

Thanks,
Vivek

Quoted 97 lines

Changelog
===
v6 - > v7:
A little change, update some commit message.
Patch3: add fixes tag.
Patch4: update ack tag, remove the redundant if (!memfd) check from
check_memfd_seals(). update commit message.
Patch6: update commit message to describe how unpin array worked.
Patch7: update commit message to describe why need reuse the folios
array.
v5 -> v6:
Patch1 use Vivek's comments(thank you), fix code style, update ack-tag. Patch2, 3 no change.
Patch4 fix memfd miss fput, use Vivek's comments(thank you),
fix code style, update suggested-by.
Patch5 update ack-tag, fix error word in commit message. Patch6 update ack-tag, use xmas style.
Patch7 update ack-tag, remove unused ret variable.

---
v4 -> v5:
Patch1 doc why pre-fault failed not report error. Patch2 no change
Patch3 update ack tag marked in v4
Patch4 split some change into patch5 and patch7, this only contains
udmabuf pin folio's function
Patch5 add helper init/deini to clean udmabuf struct initialized Patch6 remove unnecessary code
Patch7 remove reuse folio remove v4 patch4

---
v3 -> v4:
Patch1 fill vma area with pfn only when true access. Patch2 no change
Patch3 select VMAP_PFN
Patch4 use function pin each item.
Patch5 use pinned folio array instead udmabuf_folio struct.

---
v2 -> v3:
Patch1, avoid use page, instead, use pfn, and use vmf_insert_pfn map suggested-by Kasireddy, Vivek <[email protected]>

Patch2, update acked-by Kasireddy, Vivek <[email protected]> And keep the kvcalloc on the same line.

Patch3, avoid use page, instead, use pfn, then use vmap_pfn map

Patch4, split v2 patch4, single update codestyle to keep review easy.

Patch5, another way to remove udmabuf_folio

---
v1 -> v2:
Patch1, 3 Rectify the improper use of the sg table. suggested-by Christian König <[email protected]>

Patch2 add acked-by Christian K�nig <[email protected]> which marked in v1

Patch4
Modify the data structure to restore the use of pages and correct the misunderstanding of loop conditions such as "pgcnt". make sure pass self test.

remove v1's patch4
v6
https://lore.kernel.org/all/[email protected]/
v5
https://lore.kernel.org/all/[email protected]/
v4
https://lore.kernel.org/all/[email protected]/
v3
https://lore.kernel.org/all/[email protected]/
v2
https://lore.kernel.org/all/[email protected]/
v1
https://lore.kernel.org/all/[email protected]/

Huan Yang (7):
udmabuf: pre-fault when first page fault
udmabuf: change folios array from kmalloc to kvmalloc
udmabuf: fix vmap_udmabuf error page set
udmabuf: udmabuf_create pin folio codestyle cleanup
udmabuf: introduce udmabuf init and deinit helper
udmabuf: remove udmabuf_folio
udmabuf: reuse folio array when pin folios

  drivers/dma-buf/Kconfig   |   1 +
  drivers/dma-buf/udmabuf.c | 275 +++++++++++++++++++++++---------------
  2 files changed, 169 insertions(+), 107 deletions(-)

base-commit: 57f962b956f1d116cd64d5c406776c4975de549d --
2.45.2