Skip to contentSkip to conversation

mm: alloc_pages_bulk: remove assumption of populating only NULL elements

PATCH NAK Yunsheng Lin 7 participants 23 messages Feb 28, 2025 – Mar 12, 2025

Subsystems (15)
lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 mm: alloc_pages_bulk: remove assumption of populating only NULL elements

As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users.

Through analyzing of bulk allocation API used in fs, it
seems that the callers are depending on the assumption of populating only NULL elements in fs/btrfs/extent_io.c and net/sunrpc/svc_xprt.c while erofs and btrfs don't, see:
commit 91d6ac1d62c3 ("btrfs: allocate page arrays using bulk page allocator") commit d6db47e571dc ("erofs: do not use pagepool in z_erofs_gbuf_growsize()") commit c9fa563072e1 ("xfs: use alloc_pages_bulk_array() for buffers") commit f6e70aab9dfe ("SUNRPC: refresh rq_pages using a bulk page allocator")

Change SUNRPC and btrfs to not depend on the assumption. Other existing callers seems to be passing all NULL elements via memset, kzalloc, etc.

Remove assumption of populating only NULL elements and treat page_array as output parameter like kmem_cache_alloc_bulk(). Remove the above assumption also enable the caller to not zero the array before calling the page bulk allocating API, which has about 1~2 ns performance improvement for the test case of time_bench_page_pool03_slow() for page_pool in a x86 vm system, this reduces some performance impact of fixing the DMA API misuse problem in [2], performance improves from 87.886 ns to 86.429 ns.

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

CC Jesper Dangaard Brouer <[email protected]>
CC Luiz Capitulino <[email protected]>
CC Mel Gorman <[email protected]>
CC Dave Chinner <[email protected]>
CC Chuck Lever <[email protected]>

---
V2:
1. Drop RFC tag and rebased on latest linux-next.
2. Fix a compile error for xfs.
3. Defragmemt the page_array for SUNRPC and btrfs.

---
 drivers/vfio/pci/virtio/migrate.c |  2 --
 fs/btrfs/extent_io.c              | 23 +++++++++++++++++-----
 fs/erofs/zutil.c                  | 12 ++++++------
 fs/xfs/xfs_buf.c                  |  9 +++++----
 mm/page_alloc.c                   | 32 +++++--------------------------
 net/core/page_pool.c              |  3 ---
 net/sunrpc/svc_xprt.c             | 22 +++++++++++++++++----
 7 files changed, 52 insertions(+), 51 deletions(-)
drivers/vfio/pci/virtio/migrate.c +0 -2
index ba92bb4e9af9..9f003a237dec 100644
@@ -91,8 +91,6 @@ static int virtiovf_add_migration_pages(struct virtiovf_data_buffer *buf,
 		if (ret)
 			goto err_append;
 		buf->allocated_length += filled * PAGE_SIZE;
-		/* clean input for another bulk allocation */
-		memset(page_list, 0, filled * sizeof(*page_list));
 		to_fill = min_t(unsigned int, to_alloc,
 				PAGE_SIZE / sizeof(*page_list));
 	} while (to_alloc > 0);
fs/btrfs/extent_io.c +18 -5
index f0a1da40d641..ef52cedd9873 100644
@@ -623,13 +623,26 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,
 			   bool nofail)
 {
 	const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) : GFP_NOFS;
-	unsigned int allocated;
+	unsigned int allocated, ret;
 
-	for (allocated = 0; allocated < nr_pages;) {
-		unsigned int last = allocated;
+	/* Defragment page_array so pages can be bulk allocated into remaining
+	 * NULL elements sequentially.
+	 */
+	for (allocated = 0, ret = 0; ret < nr_pages; ret++) {
+		if (page_array[ret]) {
+			page_array[allocated] = page_array[ret];
+			if (ret != allocated)
+				page_array[ret] = NULL;
+
+			allocated++;
+		}
+	}
 
-		allocated = alloc_pages_bulk(gfp, nr_pages, page_array);
-		if (unlikely(allocated == last)) {
+	while (allocated < nr_pages) {
+		ret = alloc_pages_bulk(gfp, nr_pages - allocated,
+				       page_array + allocated);
+		allocated += ret;
+		if (unlikely(!ret)) {
 			/* No progress, fail and do cleanup. */
 			for (int i = 0; i < allocated; i++) {
 				__free_page(page_array[i]);
fs/erofs/zutil.c +6 -6
index 55ff2ab5128e..1c50b5e27371 100644
@@ -85,13 +85,13 @@ int z_erofs_gbuf_growsize(unsigned int nrpages)
 
 		for (j = 0; j < gbuf->nrpages; ++j)
 			tmp_pages[j] = gbuf->pages[j];
-		do {
-			last = j;
-			j = alloc_pages_bulk(GFP_KERNEL, nrpages,
-					     tmp_pages);
-			if (last == j)
+
+		for (last = j; last < nrpages; last += j) {
+			j = alloc_pages_bulk(GFP_KERNEL, nrpages - last,
+					     tmp_pages + last);
+			if (!j)
 				goto out;
-		} while (j != nrpages);
+		}
 
 		ptr = vmap(tmp_pages, nrpages, VM_MAP, PAGE_KERNEL);
 		if (!ptr)
fs/xfs/xfs_buf.c +5 -4
index 5d560e9073f4..b4e95b2dd0f0 100644
@@ -319,16 +319,17 @@ xfs_buf_alloc_pages(
 	 * least one extra page.
 	 */
 	for (;;) {
-		long	last = filled;
+		long	alloc;
 
-		filled = alloc_pages_bulk(gfp_mask, bp->b_page_count,
-					  bp->b_pages);
+		alloc = alloc_pages_bulk(gfp_mask, bp->b_page_count - filled,
+					 bp->b_pages + filled);
+		filled += alloc;
 		if (filled == bp->b_page_count) {
 			XFS_STATS_INC(bp->b_mount, xb_page_found);
 			break;
 		}
 
-		if (filled != last)
+		if (alloc)
 			continue;
 
 		if (flags & XBF_READ_AHEAD) {
mm/page_alloc.c +5 -27
index f07c95eb5ac1..625d14ee4a41 100644
@@ -4599,9 +4599,6 @@ static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
  * This is a batched version of the page allocator that attempts to
  * allocate nr_pages quickly. Pages are added to the page_array.
  *
- * Note that only NULL elements are populated with pages and nr_pages
- * is the maximum number of pages that will be stored in the array.
- *
  * Returns the number of pages in the array.
  */
 unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
@@ -4617,29 +4614,18 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	struct alloc_context ac;
 	gfp_t alloc_gfp;
 	unsigned int alloc_flags = ALLOC_WMARK_LOW;
-	int nr_populated = 0, nr_account = 0;
-
-	/*
-	 * Skip populated array elements to determine if any pages need
-	 * to be allocated before disabling IRQs.
-	 */
-	while (nr_populated < nr_pages && page_array[nr_populated])
-		nr_populated++;
+	int nr_populated = 0;
 
 	/* No pages requested? */
 	if (unlikely(nr_pages <= 0))
 		goto out;
 
-	/* Already populated array? */
-	if (unlikely(nr_pages - nr_populated == 0))
-		goto out;
-
 	/* Bulk allocator does not support memcg accounting. */
 	if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
 		goto failed;
 
 	/* Use the single page allocator for one page. */
-	if (nr_pages - nr_populated == 1)
+	if (nr_pages == 1)
 		goto failed;
 
 #ifdef CONFIG_PAGE_OWNER
@@ -4711,24 +4697,16 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	/* Attempt the batch allocation */
 	pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
 	while (nr_populated < nr_pages) {
-
-		/* Skip existing pages */
-		if (page_array[nr_populated]) {
-			nr_populated++;
-			continue;
-		}
-
 		page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
 								pcp, pcp_list);
 		if (unlikely(!page)) {
 			/* Try and allocate at least one page */
-			if (!nr_account) {
+			if (!nr_populated) {
 				pcp_spin_unlock(pcp);
 				goto failed_irq;
 			}
 			break;
 		}
-		nr_account++;
 
 		prep_new_page(page, 0, gfp, 0);
 		set_page_refcounted(page);
@@ -4738,8 +4716,8 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	pcp_spin_unlock(pcp);
 	pcp_trylock_finish(UP_flags);
 
-	__count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
-	zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
+	__count_zid_vm_events(PGALLOC, zone_idx(zone), nr_populated);
+	zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_populated);
 
 out:
 	return nr_populated;
net/core/page_pool.c +0 -3
index acef1fcd8ddc..200b99375cb6 100644
@@ -544,9 +544,6 @@ static noinline netmem_ref __page_pool_alloc_pages_slow(struct page_pool *pool,
 	if (unlikely(pool->alloc.count > 0))
 		return pool->alloc.cache[--pool->alloc.count];
 
-	/* Mark empty alloc.cache slots "empty" for alloc_pages_bulk */
-	memset(&pool->alloc.cache, 0, sizeof(void *) * bulk);
-
 	nr_pages = alloc_pages_bulk_node(gfp, pool->p.nid, bulk,
 					 (struct page **)pool->alloc.cache);
 	if (unlikely(!nr_pages))
net/sunrpc/svc_xprt.c +18 -4
index ae25405d8bd2..80fbc4ffef6d 100644
@@ -663,9 +663,23 @@ static bool svc_alloc_arg(struct svc_rqst *rqstp)
 		pages = RPCSVC_MAXPAGES;
 	}
 
-	for (filled = 0; filled < pages; filled = ret) {
-		ret = alloc_pages_bulk(GFP_KERNEL, pages, rqstp->rq_pages);
-		if (ret > filled)
+	/* Defragment the rqstp->rq_pages so pages can be bulk allocated into
+	 * remaining NULL elements sequentially.
+	 */
+	for (filled = 0, ret = 0; ret < pages; ret++) {
+		if (rqstp->rq_pages[ret]) {
+			rqstp->rq_pages[filled] = rqstp->rq_pages[ret];
+			if (ret != filled)
+				rqstp->rq_pages[ret] = NULL;
+
+			filled++;
+		}
+	}
+
+	for (; filled < pages; filled += ret) {
+		ret = alloc_pages_bulk(GFP_KERNEL, pages - filled,
+				       rqstp->rq_pages + filled);
+		if (ret)
 			/* Made progress, don't sleep yet */
 			continue;
 
@@ -674,7 +688,7 @@ static bool svc_alloc_arg(struct svc_rqst *rqstp)
 			set_current_state(TASK_RUNNING);
 			return false;
 		}
-		trace_svc_alloc_arg_err(pages, ret);
+		trace_svc_alloc_arg_err(pages, filled);
 		memalloc_retry_wait(GFP_KERNEL);
 	}
 	rqstp->rq_page_end = &rqstp->rq_pages[pages];
Signature · 1 line
2.33.0
#1 lore raw
Quoted 5 lines · Yunsheng Lin

As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users.

Sorry, but this still makes a claim without providing any data to back it up. Why can callers "do a better job"?

Quoted 37 lines

Through analyzing of bulk allocation API used in fs, it
seems that the callers are depending on the assumption of populating only NULL elements in fs/btrfs/extent_io.c and net/sunrpc/svc_xprt.c while erofs and btrfs don't, see:
commit 91d6ac1d62c3 ("btrfs: allocate page arrays using bulk page allocator") commit d6db47e571dc ("erofs: do not use pagepool in z_erofs_gbuf_growsize()") commit c9fa563072e1 ("xfs: use alloc_pages_bulk_array() for buffers") commit f6e70aab9dfe ("SUNRPC: refresh rq_pages using a bulk page allocator")

Change SUNRPC and btrfs to not depend on the assumption. Other existing callers seems to be passing all NULL elements via memset, kzalloc, etc.

Remove assumption of populating only NULL elements and treat page_array as output parameter like kmem_cache_alloc_bulk(). Remove the above assumption also enable the caller to not zero the array before calling the page bulk allocating API, which has about 1~2 ns performance improvement for the test case of time_bench_page_pool03_slow() for page_pool in a x86 vm system, this reduces some performance impact of fixing the DMA API misuse problem in [2], performance improves from 87.886 ns to 86.429 ns.

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

CC Jesper Dangaard Brouer <[email protected]>
CC Luiz Capitulino <[email protected]>
CC Mel Gorman <[email protected]>
CC Dave Chinner <[email protected]>
CC Chuck Lever <[email protected]>

---
V2:
1. Drop RFC tag and rebased on latest linux-next.
2. Fix a compile error for xfs.
3. Defragmemt the page_array for SUNRPC and btrfs.

Quoted 9 lines
---
 drivers/vfio/pci/virtio/migrate.c |  2 --
 fs/btrfs/extent_io.c              | 23 +++++++++++++++++-----
 fs/erofs/zutil.c                  | 12 ++++++------
 fs/xfs/xfs_buf.c                  |  9 +++++----
 mm/page_alloc.c                   | 32 +++++--------------------------
 net/core/page_pool.c              |  3 ---
 net/sunrpc/svc_xprt.c             | 22 +++++++++++++++++----
 7 files changed, 52 insertions(+), 51 deletions(-)

52:51 is not an improvement. 1-2 ns is barely worth mentioning. The sunrpc and btrfs callers are more complex and carry duplicated code.

Not an outright objection from me, but it's hard to justify this change.

Quoted 236 lines
drivers/vfio/pci/virtio/migrate.c +0 -2
index ba92bb4e9af9..9f003a237dec 100644
@@ -91,8 +91,6 @@ static int virtiovf_add_migration_pages(struct virtiovf_data_buffer *buf,
 		if (ret)
 			goto err_append;
 		buf->allocated_length += filled * PAGE_SIZE;
-		/* clean input for another bulk allocation */
-		memset(page_list, 0, filled * sizeof(*page_list));
 		to_fill = min_t(unsigned int, to_alloc,
 				PAGE_SIZE / sizeof(*page_list));
 	} while (to_alloc > 0);
fs/btrfs/extent_io.c +18 -5
index f0a1da40d641..ef52cedd9873 100644
@@ -623,13 +623,26 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,
 			   bool nofail)
 {
 	const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) : GFP_NOFS;
-	unsigned int allocated;
+	unsigned int allocated, ret;
 
-	for (allocated = 0; allocated < nr_pages;) {
-		unsigned int last = allocated;
+	/* Defragment page_array so pages can be bulk allocated into remaining
+	 * NULL elements sequentially.
+	 */
+	for (allocated = 0, ret = 0; ret < nr_pages; ret++) {
+		if (page_array[ret]) {
+			page_array[allocated] = page_array[ret];
+			if (ret != allocated)
+				page_array[ret] = NULL;
+
+			allocated++;
+		}
+	}
 
-		allocated = alloc_pages_bulk(gfp, nr_pages, page_array);
-		if (unlikely(allocated == last)) {
+	while (allocated < nr_pages) {
+		ret = alloc_pages_bulk(gfp, nr_pages - allocated,
+				       page_array + allocated);
+		allocated += ret;
+		if (unlikely(!ret)) {
 			/* No progress, fail and do cleanup. */
 			for (int i = 0; i < allocated; i++) {
 				__free_page(page_array[i]);
fs/erofs/zutil.c +6 -6
index 55ff2ab5128e..1c50b5e27371 100644
@@ -85,13 +85,13 @@ int z_erofs_gbuf_growsize(unsigned int nrpages)
 
 		for (j = 0; j < gbuf->nrpages; ++j)
 			tmp_pages[j] = gbuf->pages[j];
-		do {
-			last = j;
-			j = alloc_pages_bulk(GFP_KERNEL, nrpages,
-					     tmp_pages);
-			if (last == j)
+
+		for (last = j; last < nrpages; last += j) {
+			j = alloc_pages_bulk(GFP_KERNEL, nrpages - last,
+					     tmp_pages + last);
+			if (!j)
 				goto out;
-		} while (j != nrpages);
+		}
 
 		ptr = vmap(tmp_pages, nrpages, VM_MAP, PAGE_KERNEL);
 		if (!ptr)
fs/xfs/xfs_buf.c +5 -4
index 5d560e9073f4..b4e95b2dd0f0 100644
@@ -319,16 +319,17 @@ xfs_buf_alloc_pages(
 	 * least one extra page.
 	 */
 	for (;;) {
-		long	last = filled;
+		long	alloc;
 
-		filled = alloc_pages_bulk(gfp_mask, bp->b_page_count,
-					  bp->b_pages);
+		alloc = alloc_pages_bulk(gfp_mask, bp->b_page_count - filled,
+					 bp->b_pages + filled);
+		filled += alloc;
 		if (filled == bp->b_page_count) {
 			XFS_STATS_INC(bp->b_mount, xb_page_found);
 			break;
 		}
 
-		if (filled != last)
+		if (alloc)
 			continue;
 
 		if (flags & XBF_READ_AHEAD) {
mm/page_alloc.c +5 -27
index f07c95eb5ac1..625d14ee4a41 100644
@@ -4599,9 +4599,6 @@ static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
  * This is a batched version of the page allocator that attempts to
  * allocate nr_pages quickly. Pages are added to the page_array.
  *
- * Note that only NULL elements are populated with pages and nr_pages
- * is the maximum number of pages that will be stored in the array.
- *
  * Returns the number of pages in the array.
  */
 unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
@@ -4617,29 +4614,18 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	struct alloc_context ac;
 	gfp_t alloc_gfp;
 	unsigned int alloc_flags = ALLOC_WMARK_LOW;
-	int nr_populated = 0, nr_account = 0;
-
-	/*
-	 * Skip populated array elements to determine if any pages need
-	 * to be allocated before disabling IRQs.
-	 */
-	while (nr_populated < nr_pages && page_array[nr_populated])
-		nr_populated++;
+	int nr_populated = 0;
 
 	/* No pages requested? */
 	if (unlikely(nr_pages <= 0))
 		goto out;
 
-	/* Already populated array? */
-	if (unlikely(nr_pages - nr_populated == 0))
-		goto out;
-
 	/* Bulk allocator does not support memcg accounting. */
 	if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
 		goto failed;
 
 	/* Use the single page allocator for one page. */
-	if (nr_pages - nr_populated == 1)
+	if (nr_pages == 1)
 		goto failed;
 
 #ifdef CONFIG_PAGE_OWNER
@@ -4711,24 +4697,16 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	/* Attempt the batch allocation */
 	pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
 	while (nr_populated < nr_pages) {
-
-		/* Skip existing pages */
-		if (page_array[nr_populated]) {
-			nr_populated++;
-			continue;
-		}
-
 		page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
 								pcp, pcp_list);
 		if (unlikely(!page)) {
 			/* Try and allocate at least one page */
-			if (!nr_account) {
+			if (!nr_populated) {
 				pcp_spin_unlock(pcp);
 				goto failed_irq;
 			}
 			break;
 		}
-		nr_account++;
 
 		prep_new_page(page, 0, gfp, 0);
 		set_page_refcounted(page);
@@ -4738,8 +4716,8 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	pcp_spin_unlock(pcp);
 	pcp_trylock_finish(UP_flags);
 
-	__count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
-	zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
+	__count_zid_vm_events(PGALLOC, zone_idx(zone), nr_populated);
+	zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_populated);
 
 out:
 	return nr_populated;
net/core/page_pool.c +0 -3
index acef1fcd8ddc..200b99375cb6 100644
@@ -544,9 +544,6 @@ static noinline netmem_ref __page_pool_alloc_pages_slow(struct page_pool *pool,
 	if (unlikely(pool->alloc.count > 0))
 		return pool->alloc.cache[--pool->alloc.count];
 
-	/* Mark empty alloc.cache slots "empty" for alloc_pages_bulk */
-	memset(&pool->alloc.cache, 0, sizeof(void *) * bulk);
-
 	nr_pages = alloc_pages_bulk_node(gfp, pool->p.nid, bulk,
 					 (struct page **)pool->alloc.cache);
 	if (unlikely(!nr_pages))
net/sunrpc/svc_xprt.c +18 -4
index ae25405d8bd2..80fbc4ffef6d 100644
@@ -663,9 +663,23 @@ static bool svc_alloc_arg(struct svc_rqst *rqstp)
 		pages = RPCSVC_MAXPAGES;
 	}
 
-	for (filled = 0; filled < pages; filled = ret) {
-		ret = alloc_pages_bulk(GFP_KERNEL, pages, rqstp->rq_pages);
-		if (ret > filled)
+	/* Defragment the rqstp->rq_pages so pages can be bulk allocated into
+	 * remaining NULL elements sequentially.
+	 */
+	for (filled = 0, ret = 0; ret < pages; ret++) {
+		if (rqstp->rq_pages[ret]) {
+			rqstp->rq_pages[filled] = rqstp->rq_pages[ret];
+			if (ret != filled)
+				rqstp->rq_pages[ret] = NULL;
+
+			filled++;
+		}
+	}
+
+	for (; filled < pages; filled += ret) {
+		ret = alloc_pages_bulk(GFP_KERNEL, pages - filled,
+				       rqstp->rq_pages + filled);
+		if (ret)
 			/* Made progress, don't sleep yet */
 			continue;
 
@@ -674,7 +688,7 @@ static bool svc_alloc_arg(struct svc_rqst *rqstp)
 			set_current_state(TASK_RUNNING);
 			return false;
 		}
-		trace_svc_alloc_arg_err(pages, ret);
+		trace_svc_alloc_arg_err(pages, filled);
 		memalloc_retry_wait(GFP_KERNEL);
 	}
 	rqstp->rq_page_end = &rqstp->rq_pages[pages];
Signature · 1 line
Chuck Lever
#2 lore raw
Quoted 9 lines · Chuck Lever
Quoted 5 lines · Yunsheng Lin

As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users.

Sorry, but this still makes a claim without providing any data to back it up. Why can callers "do a better job"?

What I meant "do a better job" is that callers are already keeping track of how many pages have been allocated, and it seems convenient to just pass 'page_array + nr_allocated' and 'nr_pages - nr_allocated' when calling subsequent page bulk alloc API so that NULL checking can be avoided, which seems to be the pattern I see in alloc_pages_bulk_interleave().

Quoted 49 lines
Quoted 39 lines

Through analyzing of bulk allocation API used in fs, it
seems that the callers are depending on the assumption of populating only NULL elements in fs/btrfs/extent_io.c and net/sunrpc/svc_xprt.c while erofs and btrfs don't, see:
commit 91d6ac1d62c3 ("btrfs: allocate page arrays using bulk page allocator") commit d6db47e571dc ("erofs: do not use pagepool in z_erofs_gbuf_growsize()") commit c9fa563072e1 ("xfs: use alloc_pages_bulk_array() for buffers") commit f6e70aab9dfe ("SUNRPC: refresh rq_pages using a bulk page allocator")

Change SUNRPC and btrfs to not depend on the assumption. Other existing callers seems to be passing all NULL elements via memset, kzalloc, etc.

Remove assumption of populating only NULL elements and treat page_array as output parameter like kmem_cache_alloc_bulk(). Remove the above assumption also enable the caller to not zero the array before calling the page bulk allocating API, which has about 1~2 ns performance improvement for the test case of time_bench_page_pool03_slow() for page_pool in a x86 vm system, this reduces some performance impact of fixing the DMA API misuse problem in [2], performance improves from 87.886 ns to 86.429 ns.

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

CC Jesper Dangaard Brouer <[email protected]>
CC Luiz Capitulino <[email protected]>
CC Mel Gorman <[email protected]>
CC Dave Chinner <[email protected]>
CC Chuck Lever <[email protected]>

---
V2:
1. Drop RFC tag and rebased on latest linux-next.
2. Fix a compile error for xfs.
3. Defragmemt the page_array for SUNRPC and btrfs.

Quoted 9 lines
---
 drivers/vfio/pci/virtio/migrate.c |  2 --
 fs/btrfs/extent_io.c              | 23 +++++++++++++++++-----
 fs/erofs/zutil.c                  | 12 ++++++------
 fs/xfs/xfs_buf.c                  |  9 +++++----
 mm/page_alloc.c                   | 32 +++++--------------------------
 net/core/page_pool.c              |  3 ---
 net/sunrpc/svc_xprt.c             | 22 +++++++++++++++++----
 7 files changed, 52 insertions(+), 51 deletions(-)
Quoted 2 lines

52:51 is not an improvement. 1-2 ns is barely worth mentioning. The sunrpc and btrfs callers are more complex and carry duplicated code.

Yes, the hard part is to find common file to place the common function as something as below:

void defragment_pointer_array(void** array, int size) {
    int slow = 0;
    for (int fast = 0; fast < size; fast++) {
        if (array[fast] != NULL) {
            swap(&array[fast], &array[slow]);
            slow++;
        }
    }
}

Or introduce a function as something like alloc_pages_refill_array() for the usecase of sunrpc and xfs and do the array defragment in alloc_pages_refill_array() before calling alloc_pages_bulk()? Any suggestion?

Quoted 2 lines

Not an outright objection from me, but it's hard to justify this change.

The above should reduce the number to something like 40:51.

Also, I looked more closely at other callers calling alloc_pages_bulk(), it seems vm_module_tags_populate() doesn't clear next_page[i] to NULL after __free_page() when doing 'Clean up and error out', I am not sure if vm_module_tags_populate() will be called multi-times as vm_module_tags->pages seems to be only set to all NULL once, see alloc_tag_init() -> alloc_mod_tags_mem().

Cc Suren to see if there is some clarifying for the above.

#3 lore raw
In reply to Yunsheng Lin
Quoted 19 lines · Yunsheng Lin

As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users.

Through analyzing of bulk allocation API used in fs, it
seems that the callers are depending on the assumption of populating only NULL elements in fs/btrfs/extent_io.c and net/sunrpc/svc_xprt.c while erofs and btrfs don't, see:
commit 91d6ac1d62c3 ("btrfs: allocate page arrays using bulk page allocator") commit d6db47e571dc ("erofs: do not use pagepool in z_erofs_gbuf_growsize()") commit c9fa563072e1 ("xfs: use alloc_pages_bulk_array() for buffers") commit f6e70aab9dfe ("SUNRPC: refresh rq_pages using a bulk page allocator")

Change SUNRPC and btrfs to not depend on the assumption. Other existing callers seems to be passing all NULL elements via memset, kzalloc, etc.

Quoted 9 lines

Remove assumption of populating only NULL elements and treat page_array as output parameter like kmem_cache_alloc_bulk(). Remove the above assumption also enable the caller to not zero the array before calling the page bulk allocating API, which has about 1~2 ns performance improvement for the test case of time_bench_page_pool03_slow() for page_pool in a x86 vm system, this reduces some performance impact of fixing the DMA API misuse problem in [2], performance improves from 87.886 ns to 86.429 ns.

How much slower did you make btrfs and sunrpc by adding all the defragmenting code there?

Quoted 10 lines

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

CC Jesper Dangaard Brouer <[email protected]>
CC Luiz Capitulino <[email protected]>
CC Mel Gorman <[email protected]>
CC Dave Chinner <[email protected]>
CC Chuck Lever <[email protected]>
Quoted 4 lines

---
V2:
1. Drop RFC tag and rebased on latest linux-next.
2. Fix a compile error for xfs.

And you still haven't tested the code changes to XFS, because this patch is also broken.

Quoted 14 lines
fs/xfs/xfs_buf.c +2 -3
index 5d560e9073f4..b4e95b2dd0f0 100644
@@ -319,16 +319,17 @@ xfs_buf_alloc_pages(
 	 * least one extra page.
 	 */
 	for (;;) {
-		long	last = filled;
+		long	alloc;
 
-		filled = alloc_pages_bulk(gfp_mask, bp->b_page_count,
-					  bp->b_pages);
+		alloc = alloc_pages_bulk(gfp_mask, bp->b_page_count - filled,

fs/xfs/xfs_buf.c xfs_buf_alloc_pages( · line 333

Quoted 10 lines
fs/xfs/xfs_buf.c +3 -1
+					 bp->b_pages + filled);
+		filled += alloc;
 		if (filled == bp->b_page_count) {
 			XFS_STATS_INC(bp->b_mount, xb_page_found);
 			break;
 		}
 
-		if (filled != last)
+		if (alloc)
 			continue;

alloc_pages_bulk() now returns the number of pages allocated in the array. So if we ask for 4 pages, then get 2, filled is now 2. Then we loop, ask for another 2 pages, get those two pages and it returns
4. Now filled is 6, and we continue.

Now we ask alloc_pages_bulk() for -2 pages, which returns 4 pages...

Worse behaviour: second time around, no page allocation succeeds so it returns 2 pages. Filled is now 4, which is the number of pages we need, so we break out of the loop with only 2 pages allocated. There's about to be kernel crashes occur.....

Once is a mistake, twice is compeltely unacceptable. When XFS stops using alloc_pages_bulk (probably 6.15) I won't care anymore. But until then, please stop trying to change this code.

NACK.

-Dave.

Signature · 2 lines
Dave Chinner
[email protected]
#4 lore raw

On 2025/3/4 16:18, Dave Chinner wrote:

...

Quoted 16 lines
Quoted 11 lines

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

CC Jesper Dangaard Brouer <[email protected]>
CC Luiz Capitulino <[email protected]>
CC Mel Gorman <[email protected]>
CC Dave Chinner <[email protected]>
CC Chuck Lever <[email protected]>
Quoted 4 lines

---
V2:
1. Drop RFC tag and rebased on latest linux-next.
2. Fix a compile error for xfs.

Quoted 2 lines

And you still haven't tested the code changes to XFS, because this patch is also broken.

I tested XFS using the below cmd and testcase, testing seems to be working fine, or am I missing something obvious here as I am not realy familiar with fs subsystem yet:

Step to setup the xfs:
dd if=/dev/zero of=xfs_image bs=1M count=1024
losetup -f xfs_image
losetup -a
./mkfs.xfs /dev/loop0
mkdir xfs_test
mount /dev/loop0 xfs_test/

Test shell file:
#!/bin/bash

# Configuration parameters
DIR="/home/xfs_test" # Directory to perform file operations

FILE_COUNT=100              # Maximum number of files to create in each loop
MAX_FILE_SIZE=1024          # Maximum file size in KB
MIN_FILE_SIZE=10            # Minimum file size in KB
OPERATIONS=10               # Number of create/delete operations per loop

TOTAL_RUNS=10000 # Total number of loops to run

# Check if the directory exists
if [ ! -d "$DIR" ]; then
echo "Directory $DIR does not exist. Please create the directory first!" exit 1
fi

echo "Starting file system test on: $DIR"

for ((run=1; run<=TOTAL_RUNS; run++)); do
echo "Run $run of $TOTAL_RUNS"

# Randomly create files
for ((i=1; i<=OPERATIONS; i++)); do
# Generate a random file size between MIN_FILE_SIZE and MAX_FILE_SIZE (in KB) FILE_SIZE=$((RANDOM % (MAX_FILE_SIZE - MIN_FILE_SIZE + 1) + MIN_FILE_SIZE)) # Generate a unique file name using timestamp and random number FILE_NAME="$DIR/file_$(date +%s)_$RANDOM"
# Create a file with random content
dd if=/dev/urandom of="$FILE_NAME" bs=1K count=$FILE_SIZE &>/dev/null echo "Created file: $FILE_NAME, Size: $FILE_SIZE KB"
done

# Randomly delete files
for ((i=1; i<=OPERATIONS; i++)); do
# List all files in the directory FILE_LIST=($(ls $DIR))
# Check if there are any files to delete
if [ ${#FILE_LIST[@]} -gt 0 ]; then
# Randomly select a file to delete RANDOM_FILE=${FILE_LIST[$RANDOM % ${#FILE_LIST[@]}]} rm -f "$DIR/$RANDOM_FILE"
echo "Deleted file: $DIR/$RANDOM_FILE"
fi
done

echo "Completed run $run"
done

echo "Test completed!"

Quoted 22 lines
Quoted 22 lines
fs/xfs/xfs_buf.c +4 -3
index 5d560e9073f4..b4e95b2dd0f0 100644
@@ -319,16 +319,17 @@ xfs_buf_alloc_pages(
 	 * least one extra page.
 	 */
 	for (;;) {
-		long	last = filled;
+		long	alloc;
 
-		filled = alloc_pages_bulk(gfp_mask, bp->b_page_count,
-					  bp->b_pages);
+		alloc = alloc_pages_bulk(gfp_mask, bp->b_page_count - filled,
+					 bp->b_pages + filled);
+		filled += alloc;
 		if (filled == bp->b_page_count) {
 			XFS_STATS_INC(bp->b_mount, xb_page_found);
 			break;
 		}
 
Quoted 8 lines

fs/xfs/xfs_buf.c xfs_buf_alloc_pages( · line 333

Quoted 3 lines
fs/xfs/xfs_buf.c +1 -1
-		if (filled != last)
+		if (alloc)
 			continue;

alloc_pages_bulk() now returns the number of pages allocated in the array. So if we ask for 4 pages, then get 2, filled is now 2. Then we loop, ask for another 2 pages, get those two pages and it returns
4. Now filled is 6, and we continue.

It will be returning 2 instead of 4 for the second loop if I understand it correctly as 'bp->b_pages + filled' and 'bp->b_page_count - filled' is passing to alloc_pages_bulk() API now.

Quoted 15 lines

Now we ask alloc_pages_bulk() for -2 pages, which returns 4 pages...

Worse behaviour: second time around, no page allocation succeeds so it returns 2 pages. Filled is now 4, which is the number of pages we need, so we break out of the loop with only 2 pages allocated. There's about to be kernel crashes occur.....

Once is a mistake, twice is compeltely unacceptable. When XFS stops using alloc_pages_bulk (probably 6.15) I won't care anymore. But until then, please stop trying to change this code.

NACK.

-Dave.

#5 lore raw
Quoted 20 lines · Yunsheng Lin

On 2025/3/4 16:18, Dave Chinner wrote:

...

Quoted 16 lines
Quoted 15 lines

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

CC Jesper Dangaard Brouer <[email protected]>
CC Luiz Capitulino <[email protected]>
CC Mel Gorman <[email protected]>
CC Dave Chinner <[email protected]>
CC Chuck Lever <[email protected]>

---
V2:
1. Drop RFC tag and rebased on latest linux-next.
2. Fix a compile error for xfs.

Quoted 6 lines
Quoted 2 lines

And you still haven't tested the code changes to XFS, because this patch is also broken.

I tested XFS using the below cmd and testcase, testing seems to be working fine, or am I missing something obvious here as I am not realy familiar with fs subsystem yet:

That's hardly what I'd call a test. It barely touches the filesystem at all, and it is not exercising memory allocation failure paths at all.

Go look up fstests and use that to test the filesystem changes you are making. You can use that to test btrfs and NFS, too.

-Dave.

Signature · 2 lines
Dave Chinner
[email protected]
#6 lore raw

On 3/8/2025 2:43 PM, Dave Chinner wrote:

...

Quoted 10 lines
Quoted 3 lines

I tested XFS using the below cmd and testcase, testing seems to be working fine, or am I missing something obvious here as I am not realy familiar with fs subsystem yet:

That's hardly what I'd call a test. It barely touches the filesystem at all, and it is not exercising memory allocation failure paths at all.

Go look up fstests and use that to test the filesystem changes you are making. You can use that to test btrfs and NFS, too.

Thanks for the suggestion.
I used the below xfstests to do the testing in a VM, the smoke testing seems fine for now, will do a full testing too:
https://github.com/tytso/xfstests-bld

Also, it seems the fstests doesn't support erofs yet?

Quoted 3 lines

-Dave.

#7 lore raw
Quoted 15 lines · Yunsheng Lin

On 3/8/2025 2:43 PM, Dave Chinner wrote:

...

Quoted 10 lines
Quoted 3 lines

I tested XFS using the below cmd and testcase, testing seems to be working fine, or am I missing something obvious here as I am not realy familiar with fs subsystem yet:

That's hardly what I'd call a test. It barely touches the filesystem at all, and it is not exercising memory allocation failure paths at all.

Go look up fstests and use that to test the filesystem changes you are making. You can use that to test btrfs and NFS, too.

Quoted 6 lines

Thanks for the suggestion.
I used the below xfstests to do the testing in a VM, the smoke testing seems fine for now, will do a full testing too:
https://github.com/tytso/xfstests-bld

Also, it seems the fstests doesn't support erofs yet?

erofs is an read-only filesystem, and almost all xfstests cases is unsuitable for erofs since erofs needs to preset dataset in advance for runtime testing and only read-related interfaces are cared:

You could check erofs-specfic test cases here:
https://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git/log/?h=experimental-tests

Also the stress test:
https://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git/commit/?id=6fa861e282408f8df9ab1654b77b563444b17ea1

BTW, I don't like your new interface either, I don't know why you must insist on this work now that others are already nak this. Why do you insist on it so much?

Thanks,
Gao Xiang

Quoted 4 lines
Quoted 4 lines

-Dave.

#8 lore raw

On 2025/3/10 8:32, Gao Xiang wrote:

...

Quoted 8 lines
Quoted 2 lines

Also, it seems the fstests doesn't support erofs yet?

erofs is an read-only filesystem, and almost all xfstests cases is unsuitable for erofs since erofs needs to preset dataset in advance for runtime testing and only read-related interfaces are cared:

Quoted 5 lines

You could check erofs-specfic test cases here:
https://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git/log/?h=experimental-tests

Also the stress test:
https://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git/commit/?id=6fa861e282408f8df9ab1654b77b563444b17ea1

Thanks.

Quoted 4 lines

BTW, I don't like your new interface either, I don't know why you must insist on this work now that others are already nak this.  Why do you insist on it so much?

If the idea was not making any sense to me and it was nack'ed with clearer reasoning and without any supporting of the idea, I would have stopped working on it.

The background I started working at is something like below in the commit log:
"As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users."

"Remove assumption of populating only NULL elements and treat page_array as output parameter like kmem_cache_alloc_bulk(). Remove the above assumption also enable the caller to not zero the array before calling the page bulk allocating API, which has about 1~2 ns performance improvement for the test case of time_bench_page_pool03_slow() for page_pool in a x86 vm system, this reduces some performance impact of fixing the DMA API misuse problem in [2], performance improves from 87.886 ns to 86.429 ns."

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

There is no 'must' here, it is just me taking some of my hoppy time and some of my work time trying to make the alloc_pages_bulk API simpler and more efficient here, and I also learnt a lot during that process.

Anyway, if there is still any hard nack after all the discussion, it would be good to make it more explicit with a clearer reasoning.

#9 lore raw
Quoted 47 lines · Yunsheng Lin

On 2025/3/10 8:32, Gao Xiang wrote:

...

Quoted 8 lines
Quoted 2 lines

Also, it seems the fstests doesn't support erofs yet?

erofs is an read-only filesystem, and almost all xfstests cases is unsuitable for erofs since erofs needs to preset dataset in advance for runtime testing and only read-related interfaces are cared:

Quoted 5 lines

You could check erofs-specfic test cases here:
https://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git/log/?h=experimental-tests

Also the stress test:
https://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git/commit/?id=6fa861e282408f8df9ab1654b77b563444b17ea1

Thanks.

Quoted 4 lines

BTW, I don't like your new interface either, I don't know why you must insist on this work now that others are already nak this.  Why do you insist on it so much?

If the idea was not making any sense to me and it was nack'ed with clearer reasoning and without any supporting of the idea, I would have stopped working on it.

The background I started working at is something like below in the commit log:
"As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users."

"Remove assumption of populating only NULL elements and treat page_array as output parameter like kmem_cache_alloc_bulk(). Remove the above assumption also enable the caller to not zero the array before calling the page bulk allocating API, which has about 1~2 ns performance improvement for the test case of time_bench_page_pool03_slow() for page_pool in a x86 vm system, this reduces some performance impact of fixing the DMA API misuse problem in [2], performance improves from 87.886 ns to 86.429 ns."

Quoted 7 lines

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

There is no 'must' here, it is just me taking some of my hoppy time and some of my work time trying to make the alloc_pages_bulk API simpler and more efficient here, and I also learnt a lot during that process.

Here are my own premature thoughts just for reference:

- If you'd like to provide some performance gain, it would be much better to get a better end-to-end case to show your improvement is important and attractive to some in-tree user (rather than show 1~2ns instruction-level micro-benchmark margin, is it really important to some end use case? At least, the new api is not important to erofs since it may only impact our mount time by only 1~2ns, which is almost nothing, so I have no interest to follow the whole thread) since it involves some api behavior changes rather than some trivial cleanups.

- Your new api covers narrow cases compared to the existing api, although all in-tree callers may be converted properly, but it increases mental burden of all users. And maybe complicate future potential users again which really have to "check NULL elements in the middle of page bulk allocating" again.

To make it clearer, it's not nak from me. But I don't have any interest to follow your work due to "the real benefit vs behavior changes".

Thanks,
Gao Xiang

#10 lore raw
Quoted 7 lines · Gao Xiang

- Your new api covers narrow cases compared to the existing api, although all in-tree callers may be converted properly, but it increases mental burden of all users. And maybe complicate future potential users again which really have to "check NULL elements in the middle of page bulk allocating" again.

I think that the current API adds a mental burden for most users. For most users, their code would be much cleaner if the interface accepted an uninitialised array with length, and were told how many pages had been stored in that array.

A (very) few users benefit from the complexity. So having two interfaces, one simple and one full-featured, makes sense.

Thanks,
NeilBrown

#11 lore raw
Quoted 9 lines · NeilBrown
Quoted 7 lines · Gao Xiang

- Your new api covers narrow cases compared to the existing api, although all in-tree callers may be converted properly, but it increases mental burden of all users. And maybe complicate future potential users again which really have to "check NULL elements in the middle of page bulk allocating" again.

Quoted 5 lines

I think that the current API adds a mental burden for most users. For
most users, their code would be much cleaner if the interface accepted
an uninitialised array with length, and were told how many pages had
been stored in that array.> A (very) few users benefit from the complexity. So having two interfaces, one simple and one full-featured, makes sense.

Ok, I think for this part, diferrent people has different perference on API since there is no absolutely right and wrong in the API design area.

But I have no interest to follow this for now.

Thanks,
Gao Xiang

#12 lore raw
Quoted 12 lines · Gao Xiang
Quoted 9 lines · NeilBrown
Quoted 7 lines · Gao Xiang

   - Your new api covers narrow cases compared to the existing api, although all in-tree callers may be converted properly, but it increases mental burden of all users. And maybe complicate future potential users again which really have to "check NULL elements in the middle of page bulk allocating" again.

Quoted 5 lines
Quoted 5 lines

I think that the current API adds a mental burden for most users.  For
most users, their code would be much cleaner if the interface accepted
an uninitialised array with length, and were told how many pages had
been stored in that array.> A (very) few users benefit from the complexity.  So having two interfaces, one simple and one full-featured, makes sense.

Thanks for the above clear summarization.

Quoted 6 lines

Ok, I think for this part, diferrent people has different perference on API since there is no absolutely right and wrong in the API design area.

But I have no interest to follow this for now.

Just to be clearer, as erofs seems to be able to be changed to use a simple interface, do you prefer to keep using the full-featured interface or change to use the simple interface?

Quoted 3 lines

Thanks,
Gao Xiang

#13 lore raw
Quoted 26 lines · Yunsheng Lin
Quoted 12 lines · Gao Xiang
Quoted 9 lines · NeilBrown
Quoted 7 lines · Gao Xiang

   - Your new api covers narrow cases compared to the existing api, although all in-tree callers may be converted properly, but it increases mental burden of all users. And maybe complicate future potential users again which really have to "check NULL elements in the middle of page bulk allocating" again.

Quoted 5 lines
Quoted 5 lines

I think that the current API adds a mental burden for most users.  For
most users, their code would be much cleaner if the interface accepted
an uninitialised array with length, and were told how many pages had
been stored in that array.> A (very) few users benefit from the complexity.  So having two interfaces, one simple and one full-featured, makes sense.

Thanks for the above clear summarization.

Quoted 5 lines

Ok, I think for this part, diferrent people has different perference on API since there is no absolutely right and wrong in the API design area.

Quoted 5 lines
Quoted 1 line

But I have no interest to follow this for now.

Just to be clearer, as erofs seems to be able to be changed to use a simple interface, do you prefer to keep using the full-featured interface or change to use the simple interface?

Please keep using the old interface because I don't have any bandwidth on this considering no real benefit.

Thanks,
Gao Xiang

#14 lore raw
In reply to Yunsheng Lin
Quoted 11 lines · Yunsheng Lin

As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users.

Through analyzing of bulk allocation API used in fs, it
seems that the callers are depending on the assumption of populating only NULL elements in fs/btrfs/extent_io.c and net/sunrpc/svc_xprt.c while erofs and btrfs don't, see:
commit 91d6ac1d62c3 ("btrfs: allocate page arrays using bulk page allocator")

If you want to change the btrfs part, please run full fstests with SCRATCH_DEV_POOL populated at least.

[...]

Quoted 8 lines
fs/btrfs/extent_io.c +0 -0
index f0a1da40d641..ef52cedd9873 100644
@@ -623,13 +623,26 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,
  			   bool nofail)
  {
  	const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) : GFP_NOFS;

fs/btrfs/extent_io.c int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array, · line 632

Quoted 10 lines
fs/btrfs/extent_io.c +6 -3
-	unsigned int allocated;
+	unsigned int allocated, ret;
 
-	for (allocated = 0; allocated < nr_pages;) {
-		unsigned int last = allocated;
+	/* Defragment page_array so pages can be bulk allocated into remaining
+	 * NULL elements sequentially.
+	 */
+	for (allocated = 0, ret = 0; ret < nr_pages; ret++) {
+		if (page_array[ret]) {

You just prove how bad the design is.

All the callers have their page array members to initialized to NULL, or do not care and just want alloc_pages_bulk() to overwrite the uninitialized values.

The best example here is btrfs_encoded_read_regular(). Now your code will just crash encoded read.

Read the context before doing stupid things.

I find it unacceptable that you just change the code, without any testing, nor even just check all the involved callers.

fs/btrfs/extent_io.c int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array, · line 643

Quoted 13 lines
fs/btrfs/extent_io.c +10 -2
+			page_array[allocated] = page_array[ret];
+			if (ret != allocated)
+				page_array[ret] = NULL;
+
+			allocated++;
+		}
+	}
 
-		allocated = alloc_pages_bulk(gfp, nr_pages, page_array);
-		if (unlikely(allocated == last)) {
+	while (allocated < nr_pages) {
+		ret = alloc_pages_bulk(gfp, nr_pages - allocated,
+				       page_array + allocated);

I see the new interface way worse than the existing one.

All btrfs usage only wants a simple retry-until-all-fulfilled behavior.

NACK for btrfs part, and I find you very unresponsible not even bother running any testsuit and just submit such a mess.

Just stop this, no one will ever take you serious anymore.

Thanks,
Qu

#15 lore raw
Quoted 9 lines · Qu Wenruo
Quoted 6 lines · Yunsheng Lin

As mentioned in [1], it seems odd to check NULL elements in the middle of page bulk allocating, and it seems caller can do a better job of bulk allocating pages into a whole array sequentially without checking NULL elements first before doing the page bulk allocation for most of existing users.

Quoted 4 lines
Quoted 4 lines

Through analyzing of bulk allocation API used in fs, it seems that the callers are depending on the assumption of populating only NULL elements in fs/btrfs/extent_io.c and net/sunrpc/svc_xprt.c while erofs and btrfs don't, see:

I should have said 'while erofs and xfs don't depend on the assumption of populating only NULL elements'.

Quoted 3 lines
Quoted 1 line

commit 91d6ac1d62c3 ("btrfs: allocate page arrays using bulk page allocator")

If you want to change the btrfs part, please run full fstests with SCRATCH_DEV_POOL populated at least.

The above is a helpful suggestion/comment to someone like me, who is not very familiar with fs yet, thanks for the suggestion.

But I am not sure about some of the other comments below.

Quoted 13 lines

[...]

Quoted 11 lines
fs/btrfs/extent_io.c +1 -1
index f0a1da40d641..ef52cedd9873 100644
@@ -623,13 +623,26 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,
                  bool nofail)
   {
       const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) : GFP_NOFS;
-    unsigned int allocated;
+    unsigned int allocated, ret;
   -    for (allocated = 0; allocated < nr_pages;) {
Quoted 9 lines

fs/btrfs/extent_io.c int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array, · line 632

Quoted 6 lines
fs/btrfs/extent_io.c +5 -1
-        unsigned int last = allocated;
+    /* Defragment page_array so pages can be bulk allocated into remaining
+     * NULL elements sequentially.
+     */
+    for (allocated = 0, ret = 0; ret < nr_pages; ret++) {
+        if (page_array[ret]) {

You just prove how bad the design is.

Below is the reason you think the design is bad? If not, it would be good to be more specific about why it is a bad design.

Quoted 1 line

All the callers have their page array members to initialized to NULL, or do not care and just want alloc_pages_bulk() to overwrite the uninitialized values.

Actually there are two use cases here as mentioned in the commit log:
1. Allocating an array of pages sequentially by providing an array as output parameter.
2. Refilling pages to NULL elements in an array by providing an array as both input and output parameter.

Most of users calling the bulk alloc API is allocating an array of pages sequentially except btrfs and sunrpc, the current page bulk alloc API implementation is not only doing the unnecessay NULL checking for most users, but also require most of its callers to pass all NULL array via memset, kzalloc, etc, which is also unnecessary overhead.

That means there is some space for improvement from performance and easy-to-use perspective for most existing use cases here, this patch just change alloc_pages_bulk() API to treat the page_array as only the output parameter by mirroring kmem_cache_alloc_bulk() API.

For the existing btrfs and sunrpc case, I am agreed that there might be valid use cases too, we just need to discuss how to meet the requirements of different use cases using simpler, more unified and effective APIs.

Quoted 3 lines

The best example here is btrfs_encoded_read_regular(). Now your code will just crash encoded read.

It would be good to be more specific about the 'crash' here, as simple testing mentioned in below seems fine for btrfs fs too, but I will do more testing by running full fstests with SCRATCH_DEV_POOL populated after I learn how to use the fstests.

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

Quoted 4 lines

Read the context before doing stupid things.

I find it unacceptable that you just change the code, without any testing, nor even just check all the involved callers.

What exactly is the above 'context' is referring to? If it is a good advice, I think I will take it seriously.

May I suggest that it might be better to be more humble and discuss more before jumpping to conclusion here as it seems hard for one person to be familiar with all the subsystem in the kernel?

Quoted 14 lines

fs/btrfs/extent_io.c int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array, · line 643

Quoted 13 lines
fs/btrfs/extent_io.c +10 -1
+            page_array[allocated] = page_array[ret];
+            if (ret != allocated)
+                page_array[ret] = NULL;
+
+            allocated++;
+        }
+    }
   -        allocated = alloc_pages_bulk(gfp, nr_pages, page_array);
-        if (unlikely(allocated == last)) {
+    while (allocated < nr_pages) {
+        ret = alloc_pages_bulk(gfp, nr_pages - allocated,
+                       page_array + allocated);
Quoted 3 lines

I see the new interface way worse than the existing one.

All btrfs usage only wants a simple retry-until-all-fulfilled behavior.

As above, I am agreed that the above might be what btrfs usage want, so let's discuss how to meet the requirements of different use cases using simpler, more unified and effective API, like introducing a function like alloc_pages_refill_array() to meet the above requirement as mentioned in below?
https://lore.kernel.org/all/[email protected]/

Quoted 9 lines

NACK for btrfs part, and I find you very unresponsible not even bother running any testsuit and just submit such a mess.

Just stop this, no one will ever take you serious anymore.

Thanks,
Qu

#16 lore raw
Quoted 5 lines · Yunsheng Lin

For the existing btrfs and sunrpc case, I am agreed that there might be valid use cases too, we just need to discuss how to meet the requirements of different use cases using simpler, more unified and effective APIs.

We don't need "more unified".

If there are genuinely two different use cases with clearly different needs - even if only slightly different - then it is acceptable to have two different interfaces. Be sure to choose names which emphasise the differences.

Thanks,
NeilBrown

#17 lore raw
Quoted 8 lines · NeilBrown
Quoted 5 lines · Yunsheng Lin

For the existing btrfs and sunrpc case, I am agreed that there might be valid use cases too, we just need to discuss how to meet the requirements of different use cases using simpler, more unified and effective APIs.

We don't need "more unified".

What I meant about 'more unified' is how to avoid duplicated code as much as possible for two different interfaces with similar‌ functionality.

The best way I tried to avoid duplicated code as much as possible is to defragment the page_array before calling the alloc_pages_bulk() for the use case of btrfs and sunrpc so that alloc_pages_bulk() can be removed of the assumption populating only NULL elements, so that the API is simpler and more efficient.

Quoted 5 lines

If there are genuinely two different use cases with clearly different needs - even if only slightly different - then it is acceptable to have two different interfaces. Be sure to choose names which emphasise the differences.

The best name I can come up with for the use case of btrfs and sunrpc is something like alloc_pages_bulk_refill(), any better suggestion about the naming?

Quoted 3 lines

Thanks,
NeilBrown

#18 lore raw
Quoted 20 lines · Yunsheng Lin
Quoted 8 lines · NeilBrown
Quoted 5 lines · Yunsheng Lin

For the existing btrfs and sunrpc case, I am agreed that there might be valid use cases too, we just need to discuss how to meet the requirements of different use cases using simpler, more unified and effective APIs.

We don't need "more unified".

What I meant about 'more unified' is how to avoid duplicated code as much as possible for two different interfaces with similar‌ functionality.

The best way I tried to avoid duplicated code as much as possible is to defragment the page_array before calling the alloc_pages_bulk() for the use case of btrfs and sunrpc so that alloc_pages_bulk() can be removed of the assumption populating only NULL elements, so that the API is simpler and more efficient.

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

If there are genuinely two different use cases with clearly different needs - even if only slightly different - then it is acceptable to have two different interfaces. Be sure to choose names which emphasise the differences.

The best name I can come up with for the use case of btrfs and sunrpc is something like alloc_pages_bulk_refill(), any better suggestion about the naming?

I think alloc_pages_bulk_refill() is a good name.

So:
- alloc_pages_bulk() would be given an uninitialised array of page pointers and a required count and would return the number of pages that were allocated
- alloc_pages_bulk_refill() would be given an initialised array of page pointers some of which might be NULL. It would attempt to allocate pages for the non-NULL pointers and return the total number of allocated pages in the array - just like the current alloc_pages_bulk().

sunrpc could usefully use both of these interfaces.

alloc_pages_bulk() could be implemented by initialising the array and then calling alloc_pages_bulk_refill(). Or alloc_pages_bulk_refill() could be implemented by compacting the pages and then calling alloc_pages_bulk().
If we could duplicate the code and have two similar but different functions.

The documentation for _refill() should make it clear that the pages might get re-ordered.

Having looked at some of the callers I agree that the current interface is not ideal for many of them, and that providing a simpler interface would help.

Thanks,
NeilBrown

#19 lore raw
Quoted 32 lines · NeilBrown
Quoted 20 lines · Yunsheng Lin
Quoted 8 lines · NeilBrown
Quoted 5 lines · Yunsheng Lin

For the existing btrfs and sunrpc case, I am agreed that there might be valid use cases too, we just need to discuss how to meet the requirements of different use cases using simpler, more unified and effective APIs.

We don't need "more unified".

What I meant about 'more unified' is how to avoid duplicated code as much as possible for two different interfaces with similar‌ functionality.

The best way I tried to avoid duplicated code as much as possible is to defragment the page_array before calling the alloc_pages_bulk() for the use case of btrfs and sunrpc so that alloc_pages_bulk() can be removed of the assumption populating only NULL elements, so that the API is simpler and more efficient.

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

If there are genuinely two different use cases with clearly different needs - even if only slightly different - then it is acceptable to have two different interfaces. Be sure to choose names which emphasise the differences.

The best name I can come up with for the use case of btrfs and sunrpc is something like alloc_pages_bulk_refill(), any better suggestion about the naming?

I think alloc_pages_bulk_refill() is a good name.

Quoted 7 lines

So:
- alloc_pages_bulk() would be given an uninitialised array of page pointers and a required count and would return the number of pages that were allocated
- alloc_pages_bulk_refill() would be given an initialised array of page pointers some of which might be NULL. It would attempt to allocate pages for the non-NULL pointers and return the total number of

You meant 'NULL pointers' instead of 'non-NULL pointers' above?

Quoted 2 lines

allocated pages in the array - just like the current alloc_pages_bulk().

I guess 'the total number of allocated pages in the array ' include the pages which are already in the array before calling the above API?

I guess it is worth mentioning that the current alloc_pages_bulk() may return different value with the same size of arrays, but with different layout of the same number of NULL pointers.
For the same size of arrays with different layout for the NULL pointer below('*' indicate NULL pointer), and suppose buddy allocator is only able to allocate two pages:
1. P**P*P: will return 4.
2. P*PP**: will return 5.

If the new API do the page defragmentation, then it will always return the same value for different layout of the same number of NULL pointers. I guess the new one is the more perfered behavior as it provides a more defined semantic.

Quoted 10 lines

sunrpc could usefully use both of these interfaces.

alloc_pages_bulk() could be implemented by initialising the array and then calling alloc_pages_bulk_refill(). Or alloc_pages_bulk_refill() could be implemented by compacting the pages and then calling alloc_pages_bulk().
If we could duplicate the code and have two similar but different functions.

Quoted 2 lines

The documentation for _refill() should make it clear that the pages might get re-ordered.

Does 'the pages might get re-ordered' mean defragmenting the page_array? If yes, it makes sense to make it clear.

Quoted 4 lines

Having looked at some of the callers I agree that the current interface is not ideal for many of them, and that providing a simpler interface would help.

+1

Quoted 3 lines

Thanks,
NeilBrown

#20 lore raw
Quoted 41 lines · Yunsheng Lin
Quoted 32 lines · NeilBrown
Quoted 20 lines · Yunsheng Lin
Quoted 8 lines · NeilBrown
Quoted 5 lines · Yunsheng Lin

For the existing btrfs and sunrpc case, I am agreed that there might be valid use cases too, we just need to discuss how to meet the requirements of different use cases using simpler, more unified and effective APIs.

We don't need "more unified".

What I meant about 'more unified' is how to avoid duplicated code as much as possible for two different interfaces with similar‌ functionality.

The best way I tried to avoid duplicated code as much as possible is to defragment the page_array before calling the alloc_pages_bulk() for the use case of btrfs and sunrpc so that alloc_pages_bulk() can be removed of the assumption populating only NULL elements, so that the API is simpler and more efficient.

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

If there are genuinely two different use cases with clearly different needs - even if only slightly different - then it is acceptable to have two different interfaces. Be sure to choose names which emphasise the differences.

The best name I can come up with for the use case of btrfs and sunrpc is something like alloc_pages_bulk_refill(), any better suggestion about the naming?

I think alloc_pages_bulk_refill() is a good name.

Quoted 7 lines

So:
- alloc_pages_bulk() would be given an uninitialised array of page pointers and a required count and would return the number of pages that were allocated
- alloc_pages_bulk_refill() would be given an initialised array of page pointers some of which might be NULL. It would attempt to allocate pages for the non-NULL pointers and return the total number of

Quoted 1 line

You meant 'NULL pointers' instead of 'non-NULL pointers' above?

Correct - thanks.

Quoted 7 lines
Quoted 3 lines

allocated pages in the array - just like the current alloc_pages_bulk().

I guess 'the total number of allocated pages in the array ' include the pages which are already in the array before calling the above API?

Yes - just what the current function does. Though I don't know that we really need that detail. I think there are three interesting return values:

- hard failure - don't bother trying again soon: maybe -ENOMEM
- success - all pages are allocated: maybe 0 (or 1?)
- partial success - at least one page allocated, ok to try again immediately - maybe -EAGAIN (or 0).

Quoted 9 lines

I guess it is worth mentioning that the current alloc_pages_bulk() may return different value with the same size of arrays, but with different layout of the same number of NULL pointers.
For the same size of arrays with different layout for the NULL pointer below('*' indicate NULL pointer), and suppose buddy allocator is only able to allocate two pages:
1. P**P*P: will return 4.
2. P*PP**: will return 5.

I guess the documentation for the function is wrong then. They lends weight to the suggestion that the current return value isn't ideal.

Quoted 16 lines

If the new API do the page defragmentation, then it will always return the same value for different layout of the same number of NULL pointers. I guess the new one is the more perfered behavior as it provides a more defined semantic.

Quoted 10 lines

sunrpc could usefully use both of these interfaces.

alloc_pages_bulk() could be implemented by initialising the array and then calling alloc_pages_bulk_refill(). Or alloc_pages_bulk_refill() could be implemented by compacting the pages and then calling alloc_pages_bulk().
If we could duplicate the code and have two similar but different functions.

Quoted 5 lines
Quoted 2 lines

The documentation for _refill() should make it clear that the pages might get re-ordered.

Does 'the pages might get re-ordered' mean defragmenting the page_array? If yes, it makes sense to make it clear.

Correct. Defragmentation is an option for implementing refill. We shouldn't promise to do that, but we should define the API in such a way that it is allowed.

Quoted 12 lines
Quoted 5 lines

Having looked at some of the callers I agree that the current interface is not ideal for many of them, and that providing a simpler interface would help.

+1

Quoted 3 lines

Thanks,
NeilBrown

If I were do work on this (and I'm not, so you don't have to follow my ideas) I would separate the bulk_alloc into several inline functions and combine them into the different interfaces that you want. This will result in duplicated object code without duplicated source code. The object code should be optimal.

The parts of the function are:
- validity checks - fallback to single page allocation
- select zone - fallback to single page allocation
- allocate multiple pages in the zone and dispose of them
- allocate a single page

The "dispose of them" is one of
- add to a linked list
- add to end of array
- add to next hole in array

These three could be inline functions that the "allocate multiple pages" and "allocate single page" functions call. We can pass these as function arguments and the compile will inline them.
I imagine these little function would take one page and return a bool indicating if any more are wanted.

The three functions: alloc_bulk_array alloc_bulk_list alloc_bulk_refill_array would each look like:

validity checks: do we need to allocate anything?

if want more than one page &&

     am allowed to do mulipage (e.g. not __GFP_ACCOUNT) &&
     zone = choose_zone() {
        alloc_multi_from_zone(zone, dispose_function)

}
if nothing allocated
alloc_single_page(dispose_function)

Each would have a different dispose_function and the initial checks would be quite different, as would the return value.

Thanks for working on this.

NeilBrown

#21 lore raw

On 3/8/2025 5:02 AM, NeilBrown wrote:

...

Quoted 8 lines
Quoted 7 lines
Quoted 3 lines

allocated pages in the array - just like the current alloc_pages_bulk().

I guess 'the total number of allocated pages in the array ' include the pages which are already in the array before calling the above API?

Quoted 8 lines

Yes - just what the current function does. Though I don't know that we really need that detail. I think there are three interesting return values:

- hard failure - don't bother trying again soon: maybe -ENOMEM
- success - all pages are allocated: maybe 0 (or 1?)
- partial success - at least one page allocated, ok to try again immediately - maybe -EAGAIN (or 0).

Yes, the above makes sense. And I guess returning '-ENOMEM' & '0' & '-EAGAIN' seems like a more explicit value.

Quoted 2 lines
Quoted 2 lines

...

Quoted 7 lines
Quoted 1 line

If I were do work on this (and I'm not, so you don't have to follow my ideas) I would separate the bulk_alloc into several inline functions and combine them into the different interfaces that you want. This will result in duplicated object code without duplicated source code. The object code should be optimal.

Thanks for the detailed suggestion, it seems feasible.
If the 'add to a linked list' dispose was not removed in the [1], I guess it is worth trying.
But I am not sure if it is still worth it at the cost of the above mentioned 'duplicated object code' considering the array defragmenting seem to be able to unify the dispose of 'add to end of array' and 'add to next hole in array'.

I guess I can try with the easier one using array defragmenting first, and try below if there is more complicated use case.

1. https://lore.kernel.org/all/f1c75db91d08cafd211eca6a3b199b629d4ffe16.1734991165.git.luizcap@redhat.com/

Quoted 38 lines

The parts of the function are:
- validity checks - fallback to single page allocation
- select zone - fallback to single page allocation
- allocate multiple pages in the zone and dispose of them
- allocate a single page

The "dispose of them" is one of
- add to a linked list
- add to end of array
- add to next hole in array

These three could be inline functions that the "allocate multiple pages" and "allocate single page" functions call. We can pass these as function arguments and the compile will inline them.
I imagine these little function would take one page and return a bool indicating if any more are wanted.

The three functions: alloc_bulk_array alloc_bulk_list alloc_bulk_refill_array would each look like:

validity checks: do we need to allocate anything?

if want more than one page &&

      am allowed to do mulipage (e.g. not __GFP_ACCOUNT) &&
      zone = choose_zone() {
         alloc_multi_from_zone(zone, dispose_function)

}
if nothing allocated
alloc_single_page(dispose_function)

Each would have a different dispose_function and the initial checks would be quite different, as would the return value.

Thanks for working on this.

NeilBrown

#22 lore raw
Quoted 45 lines · Yunsheng Lin

On 3/8/2025 5:02 AM, NeilBrown wrote:

...

Quoted 8 lines
Quoted 7 lines
Quoted 3 lines

allocated pages in the array - just like the current alloc_pages_bulk().

I guess 'the total number of allocated pages in the array ' include the pages which are already in the array before calling the above API?

Quoted 8 lines

Yes - just what the current function does. Though I don't know that we really need that detail. I think there are three interesting return values:

- hard failure - don't bother trying again soon: maybe -ENOMEM
- success - all pages are allocated: maybe 0 (or 1?)
- partial success - at least one page allocated, ok to try again immediately - maybe -EAGAIN (or 0).

Yes, the above makes sense. And I guess returning '-ENOMEM' & '0' & '-EAGAIN' seems like a more explicit value.

Quoted 2 lines
Quoted 2 lines

...

Quoted 7 lines
Quoted 1 line

If I were do work on this (and I'm not, so you don't have to follow my ideas) I would separate the bulk_alloc into several inline functions and combine them into the different interfaces that you want. This will result in duplicated object code without duplicated source code. The object code should be optimal.

Thanks for the detailed suggestion, it seems feasible.
If the 'add to a linked list' dispose was not removed in the [1], I guess it is worth trying.
But I am not sure if it is still worth it at the cost of the above mentioned 'duplicated object code' considering the array defragmenting seem to be able to unify the dispose of 'add to end of array' and 'add to next hole in array'.

Quoted 2 lines

I guess I can try with the easier one using array defragmenting first, and try below if there is more complicated use case.

Your post observes a performance improvement - slight though it is. I might be worth measuring the performance change for a case that requires defragmenting to see how that compares.

Thanks,
NeilBrown

Quoted 44 lines

1.
https://lore.kernel.org/all/f1c75db91d08cafd211eca6a3b199b629d4ffe16.1734991165.git.luizcap@redhat.com/

Quoted 38 lines

The parts of the function are:
- validity checks - fallback to single page allocation
- select zone - fallback to single page allocation
- allocate multiple pages in the zone and dispose of them
- allocate a single page

The "dispose of them" is one of
- add to a linked list
- add to end of array
- add to next hole in array

These three could be inline functions that the "allocate multiple pages" and "allocate single page" functions call. We can pass these as function arguments and the compile will inline them.
I imagine these little function would take one page and return a bool indicating if any more are wanted.

The three functions: alloc_bulk_array alloc_bulk_list alloc_bulk_refill_array would each look like:

validity checks: do we need to allocate anything?

if want more than one page &&

      am allowed to do mulipage (e.g. not __GFP_ACCOUNT) &&
      zone = choose_zone() {
         alloc_multi_from_zone(zone, dispose_function)

}
if nothing allocated
alloc_single_page(dispose_function)

Each would have a different dispose_function and the initial checks would be quite different, as would the return value.

Thanks for working on this.

NeilBrown