fs/pipe: reduce pipe->mutex contention by pre-allocating outside the lock
v2 cover fs/pipe: reduce pipe->mutex contention by pre-allocating outside the lock
While profiling Meta's caching code[1], I found pipe->mutex contention on the hot path. anon_pipe_write() currently calls alloc_page() once per page while holding pipe->mutex. The allocation can sleep doing direct reclaim and runs memcg charging, which extends the critical section and stalls any concurrent reader on the same mutex.
This series pre-allocates pages outside pipe->mutex in anon_pipe_write(): for writes that span more than one full page, up to PIPE_PREALLOC_MAX (8) pages are allocated via a per-page alloc_page() loop before the mutex is taken. anon_pipe_get_page() then drains the prealloc array first, falls back to the per-pipe tmp_page[] cache, and only enters the allocator under the mutex for the leftover pages (writes larger than PIPE_PREALLOC_MAX, single-page writes that skip prealloc, or shortfalls when the prealloc loop fails). Leftover prealloc pages are recycled into tmp_page[] before unlock and any remainder is put_page()'d after unlock, keeping the allocator out of the critical section on both sides.
alloc_pages_bulk_mempolicy() looked tempting but the bulk allocator refuses __GFP_ACCOUNT under memcg -- it returns at most one page when memcg_kmem_online() && (gfp & __GFP_ACCOUNT), see commit 8dcb3060d81d ("memcg: page_alloc: skip bulk allocator for __GFP_ACCOUNT"). A per-page loop keeps memcg accounting and the task NUMA mempolicy honoured uniformly without open-coding the charge.
I also vibe-coded a microbenchmark to validate the change. It sweeps writers x readers over {1,2,5} x {1,5,10} with 64KB writes against a 1 MB pipe and prints throughput + latency percentiles per config.
Measured on arm64 and also on x86 using virtme-ng (16 vCPUs, 64KB writes, 1 MB pipe). The numbers below were collected on v1 (alloc_pages_bulk()); v2's per-page loop preserves the dominant "allocation outside the mutex" win and is expected to land in the same range.
== No memory pressure (10s per config) ==
Throughput in MB/s (baseline -> patched, delta):
writers readers=1 readers=5 readers=10
1 1119 -> 1354 (+21%) 1132 -> 1195 (+6%) 1060 -> 1240 (+17%)
2 1162 -> 1487 (+28%) 1034 -> 1285 (+24%) 1069 -> 1213 (+14%)
5 1152 -> 1357 (+18%) 1021 -> 1164 (+14%) 997 -> 1239 (+24%)Avg write latency in ns (baseline -> patched, delta):
writers readers=1 readers=5 readers=10
1 55786 -> 46103 (-17%) 55164 -> 52260 (-5%) 58906 -> 50370 (-14%)
2 107546 -> 84011 (-22%) 120837 -> 97206 (-20%) 116860 -> 103036 (-12%)
5 271293 -> 230170 (-15%) 306089 -> 268429 (-12%) 313300 -> 252232 (-19%)Throughput improves +6% to +28% and average write latency drops 5% to 22% across every configuration.
== Under memory pressure (--memory-pressure, 6s per config) ==
stress-ng --vm 2 --vm-bytes 50% --vm-keep is forked alongside the sweep so the alloc_page() calls inside anon_pipe_write() routinely hit direct reclaim -- exactly the regime the patch targets.
Throughput in MB/s (baseline -> patched, delta):
writers readers=1 readers=5 readers=10
1 1088 -> 1438 (+32%) 996 -> 1477 (+48%) 989 -> 1194 (+21%)
2 1076 -> 1378 (+28%) 1007 -> 1269 (+26%) 1018 -> 1234 (+21%)
5 1052 -> 1311 (+25%) 986 -> 1225 (+24%) 972 -> 1249 (+29%)Avg write latency in ns (baseline -> patched, delta):
writers readers=1 readers=5 readers=10
1 57397 -> 43406 (-24%) 62690 -> 42272 (-33%) 63136 -> 52272 (-17%)
2 116121 -> 90700 (-22%) 124098 -> 98481 (-21%) 122754 -> 101217 (-18%)
5 297122 -> 238322 (-20%) 316836 -> 255095 (-19%) 321496 -> 250189 (-22%)Throughput improves +21% to +48% and average write latency drops 17% to 33% -- a noticeably bigger win than the no-pressure run.
That tracks: when alloc_page() has to dip into reclaim, the cost of holding pipe->mutex across it is highest, and pulling the allocation out of the critical section pays the most.
---
Changes in v2:
- Switch the prealloc path from alloc_pages_bulk_mempolicy() to a per-page alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT) loop.
- Split the prealloc work out of anon_pipe_write() into dedicated helpers (anon_pipe_get_page_prealloc / anon_pipe_prealloc_pop / anon_pipe_refill_tmp_pages / anon_pipe_free_pages) gathered in
struct anon_pipe_prealloc, so the write path stays readable.
- Recycle leftover prealloc pages into pipe->tmp_page[] before unlocking
- Link to v1: https://patch.msgid.link/[email protected]
To: Alexander Viro <[email protected]>
To: Christian Brauner <[email protected]>
To: Jan Kara <[email protected]>
To: Shuah Khan <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
---
Breno Leitao (2):
fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write selftests/pipe: add pipe_bench microbenchmark
fs/pipe.c | 105 ++++- tools/testing/selftests/Makefile | 1 + tools/testing/selftests/pipe/.gitignore | 1 + tools/testing/selftests/pipe/Makefile | 9 + tools/testing/selftests/pipe/pipe_bench.c | 616 ++++++++++++++++++++++++++++++ 5 files changed, 729 insertions(+), 3 deletions(-)
---
base-commit: e98d21c170b01ddef366f023bbfcf6b31509fa83
change-id: 20260515-fix_pipe-c91677c187e7
Best regards,
Signature · 1 line
Breno Leitao <[email protected]>
PATCH v2 1/2 fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
anon_pipe_write() takes pipe->mutex (aka "mutex protecting the whole thing") and then, from the per-iteration anon_pipe_get_page() helper, used to call alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT) once per page while still holding it.
That allocation can sleep doing direct reclaim and/or runs memcg charging, which extends the critical section and stalls a concurrent reader on the very same mutex.
Just pre-alloc the required pages before the lock in an array and just pop them inside the lock.
This can improve the pipe throughput up to 48% and reduce the latency in 33%, easily seen when there is memory pressure and direct reclaim.
--- fs/pipe.c | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 102 insertions(+), 3 deletions(-)
fs/pipe.c +102 -3
@@ -111,16 +111,76 @@ void pipe_double_lock(struct pipe_inode_info *pipe1,pipe_lock (pipe2); } -static struct page *anon_pipe_get_page (struct pipe_inode_info *pipe) +#define PIPE_PREALLOC_MAX 8 + +struct anon_pipe_prealloc { +struct page *pages[PIPE_PREALLOC_MAX ]; +unsigned int count; +}; + +/* +* Pre-allocate pages outside pipe->mutex for multi-page writes. +* alloc_page() with GFP_HIGHUSER can sleep in reclaim and runs memcg +* charging; doing it under the mutex stalls a concurrent reader. +* +* Loop alloc_page() instead of alloc_pages_bulk_*(): the bulk path refuses +* __GFP_ACCOUNT under memcg (see commit 8dcb3060d81d "memcg: page_alloc: +* skip bulk allocator for __GFP_ACCOUNT") and silently degrades to a single +* page. A per-page loop keeps memcg accounting and the task NUMA mempolicy +* honoured for every page; the per-call overhead is small compared to the +* pipe->mutex hold-time being shrunk. Any shortfall is covered by the +* in-lock alloc_page() fallback in anon_pipe_get_page(). +*/ +static void anon_pipe_get_page_prealloc (struct anon_pipe_prealloc *prealloc, +size_t total_len) +{ +unsigned int want, i; +struct page *page; + + prealloc->count =0 ; +if (total_len <=PAGE_SIZE ) +return ; + + want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE), +PIPE_PREALLOC_MAX ); + +for (i =0 ; i < want; i++) { + page =alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT); +if (!page) +break ; + prealloc->pages[prealloc->count++] = page; + } +} + +static struct page *anon_pipe_prealloc_pop (struct anon_pipe_prealloc *prealloc) +{ +if (!prealloc->count) +return NULL ; + + prealloc->count--; + +return prealloc->pages[prealloc->count]; +} + +static struct page *anon_pipe_get_page (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc) { +struct page *page; + +/* Drain prealloc first to keep tmp_page[] hot for later small writes. */ + page =anon_pipe_prealloc_pop (prealloc); +if (page) +return page; +for (int i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) {if (pipe->tmp_page[i]) { -struct page *page = pipe->tmp_page[i]; + page = pipe->tmp_page[i]; pipe->tmp_page[i] =NULL ;return page; } } +/* FWIW: This is called with pipe->mutex held */ return alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT); }
@@ -139,6 +199,38 @@ static void anon_pipe_put_page(struct pipe_inode_info *pipe,put_page (page); } +/* +* Stash leftover prealloc pages in tmp_page[] so the next write to this +* pipe gets a hot page without entering the allocator. +*/ +static void anon_pipe_refill_tmp_pages (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc) +{ +int i, idx; + +if (!prealloc->count) +return ; + +for (i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) { +if (pipe->tmp_page[i]) +continue ; +if (!prealloc->count) +return ; + idx = --prealloc->count; + pipe->tmp_page[i] = prealloc->pages[idx]; + prealloc->pages[idx] =NULL ; + } +} + +/* Runs after mutex_unlock() to keep put_page() out of the critical section. */ +static void anon_pipe_free_pages (struct anon_pipe_prealloc *prealloc) +{ +while (prealloc->count) { + prealloc->count--; +put_page (prealloc->pages[prealloc->count]); + } +} +static void anon_pipe_buf_release (struct pipe_inode_info *pipe,struct pipe_buffer *buf) {
@@ -432,6 +524,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) {struct file *filp = iocb->ki_filp;struct pipe_inode_info *pipe = filp->private_data; +struct anon_pipe_prealloc prealloc;unsigned int head;ssize_t ret =0 ;size_t total_len =iov_iter_count (from);
@@ -455,6 +548,8 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)if (unlikely (total_len ==0 ))return 0 ; +anon_pipe_get_page_prealloc (&prealloc, total_len); +mutex_lock (&pipe->mutex);if (!pipe->readers) {
@@ -512,7 +607,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)struct page *page;int copied; - page =anon_pipe_get_page (pipe); + page =anon_pipe_get_page (pipe, &prealloc);if (unlikely (!page)) {if (!ret) ret = -ENOMEM ;
@@ -566,7 +661,9 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* after waiting we need to re-check whether the pipe * become empty while we dropped the lock. */ +anon_pipe_refill_tmp_pages (pipe, &prealloc);mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);if (was_empty)wake_up_interruptible_sync_poll (&pipe->rd_wait,EPOLLIN |EPOLLRDNORM );kill_fasync (&pipe->fasync_readers,SIGIO ,POLL_IN );
@@ -576,9 +673,11 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) wake_next_writer = true; } out: +anon_pipe_refill_tmp_pages (pipe, &prealloc);if (pipe_is_full (pipe)) wake_next_writer = false;mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);/* * If we do do a wakeup event, we do a 'sync' wakeup, because we
Signature · 1 line
2.54.0
Re: [PATCH v2 1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
Quoted 59 lines · Breno Leitao
anon_pipe_write()takespipe->mutex(aka "mutex protecting the whole thing") and then, from the per-iterationanon_pipe_get_page()helper, used to callalloc_page(GFP_HIGHUSER | __GFP_ACCOUNT)once per page while still holding it.That allocation can sleep doing direct reclaim and/or runs memcg charging, which extends the critical section and stalls a concurrent reader on the very same mutex.
Just pre-alloc the required pages before the lock in an array and just pop them inside the lock.
This can improve the pipe throughput up to 48% and reduce the latency in 33%, easily seen when there is memory pressure and direct reclaim.
Signed-off-by Breno Leitao <[email protected]>--- fs/pipe.c | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 102 insertions(+), 3 deletions(-)fs/pipe.c +29
-1@@ -111,16 +111,76 @@ void pipe_double_lock(struct pipe_inode_info *pipe1,pipe_lock (pipe2); } -static struct page *anon_pipe_get_page (struct pipe_inode_info *pipe) +#define PIPE_PREALLOC_MAX 8 + +struct anon_pipe_prealloc { +struct page *pages[PIPE_PREALLOC_MAX ]; +unsigned int count; +}; + +/* +* Pre-allocate pages outside pipe->mutex for multi-page writes. +* alloc_page() with GFP_HIGHUSER can sleep in reclaim and runs memcg +* charging; doing it under the mutex stalls a concurrent reader. +* +* Loop alloc_page() instead of alloc_pages_bulk_*(): the bulk path refuses +* __GFP_ACCOUNT under memcg (see commit 8dcb3060d81d "memcg: page_alloc: +* skip bulk allocator for __GFP_ACCOUNT") and silently degrades to a single +* page. A per-page loop keeps memcg accounting and the task NUMA mempolicy +* honoured for every page; the per-call overhead is small compared to the +* pipe->mutex hold-time being shrunk. Any shortfall is covered by the +* in-lock alloc_page() fallback in anon_pipe_get_page(). +*/ +static void anon_pipe_get_page_prealloc (struct anon_pipe_prealloc *prealloc, +size_t total_len) +{ +unsigned int want, i; +struct page *page; + + prealloc->count =0 ; +if (total_len <=PAGE_SIZE ) +return ;
fs/pipe.c void pipe_double_lock(struct pipe_inode_info *pipe1, · line 152
Quoted 10 lines
fs/pipe.c +10
-0+ + want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE), +PIPE_PREALLOC_MAX ); + +for (i =0 ; i < want; i++) { + page =alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT); +if (!page) +break ; + prealloc->pages[prealloc->count++] = page; + }
I believe alloc_pages_bulk() is supposed to be more efficient when allocating several pages at once like this.
Quoted 122 lines
fs/pipe.c +63
-2+} + +static struct page *anon_pipe_prealloc_pop (struct anon_pipe_prealloc *prealloc) +{ +if (!prealloc->count) +return NULL ; + + prealloc->count--; + +return prealloc->pages[prealloc->count]; +} + +static struct page *anon_pipe_get_page (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc) { +struct page *page; + +/* Drain prealloc first to keep tmp_page[] hot for later small writes. */ + page =anon_pipe_prealloc_pop (prealloc); +if (page) +return page; +for (int i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) {if (pipe->tmp_page[i]) { -struct page *page = pipe->tmp_page[i]; + page = pipe->tmp_page[i]; pipe->tmp_page[i] =NULL ;return page; } } +/* FWIW: This is called with pipe->mutex held */ return alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT); }@@ -139,6 +199,38 @@ static void anon_pipe_put_page(struct pipe_inode_info *pipe,put_page (page); } +/* +* Stash leftover prealloc pages in tmp_page[] so the next write to this +* pipe gets a hot page without entering the allocator. +*/ +static void anon_pipe_refill_tmp_pages (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc) +{ +int i, idx; + +if (!prealloc->count) +return ; + +for (i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) { +if (pipe->tmp_page[i]) +continue ; +if (!prealloc->count) +return ; + idx = --prealloc->count; + pipe->tmp_page[i] = prealloc->pages[idx]; + prealloc->pages[idx] =NULL ; + } +} + +/* Runs after mutex_unlock() to keep put_page() out of the critical section. */ +static void anon_pipe_free_pages (struct anon_pipe_prealloc *prealloc) +{ +while (prealloc->count) { + prealloc->count--; +put_page (prealloc->pages[prealloc->count]); + } +} +static void anon_pipe_buf_release (struct pipe_inode_info *pipe,struct pipe_buffer *buf) {@@ -432,6 +524,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) {struct file *filp = iocb->ki_filp;struct pipe_inode_info *pipe = filp->private_data; +struct anon_pipe_prealloc prealloc;unsigned int head;ssize_t ret =0 ;size_t total_len =iov_iter_count (from);@@ -455,6 +548,8 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)if (unlikely (total_len ==0 ))return 0 ; +anon_pipe_get_page_prealloc (&prealloc, total_len); +mutex_lock (&pipe->mutex);if (!pipe->readers) {@@ -512,7 +607,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)struct page *page;int copied; - page =anon_pipe_get_page (pipe); + page =anon_pipe_get_page (pipe, &prealloc);if (unlikely (!page)) {if (!ret) ret = -ENOMEM ;@@ -566,7 +661,9 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* after waiting we need to re-check whether the pipe * become empty while we dropped the lock. */ +anon_pipe_refill_tmp_pages (pipe, &prealloc);mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);if (was_empty)wake_up_interruptible_sync_poll (&pipe->rd_wait,EPOLLIN |EPOLLRDNORM );kill_fasync (&pipe->fasync_readers,SIGIO ,POLL_IN );@@ -576,9 +673,11 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) wake_next_writer = true; } out: +anon_pipe_refill_tmp_pages (pipe, &prealloc);if (pipe_is_full (pipe)) wake_next_writer = false;mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);/* * If we do do a wakeup event, we do a 'sync' wakeup, because we
Signature · 1 line
Jeff Layton <[email protected]>
Re: [PATCH v2 1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
Quoted 28 lines · Jeff Layton
Quoted 27 lines · Breno Leitao
fs/pipe.c +27
-0+/* +* Pre-allocate pages outside pipe->mutex for multi-page writes. +* alloc_page() with GFP_HIGHUSER can sleep in reclaim and runs memcg +* charging; doing it under the mutex stalls a concurrent reader. +* +* Loop alloc_page() instead of alloc_pages_bulk_*(): the bulk path refuses +* __GFP_ACCOUNT under memcg (see commit 8dcb3060d81d "memcg: page_alloc: +* skip bulk allocator for __GFP_ACCOUNT") and silently degrades to a single +* page. A per-page loop keeps memcg accounting and the task NUMA mempolicy +* honoured for every page; the per-call overhead is small compared to the +* pipe->mutex hold-time being shrunk. Any shortfall is covered by the +* in-lock alloc_page() fallback in anon_pipe_get_page(). +*/ +static void anon_pipe_get_page_prealloc (struct anon_pipe_prealloc *prealloc, +size_t total_len) +{ +unsigned int want, i; +struct page *page; + + prealloc->count =0 ; +if (total_len <=PAGE_SIZE ) +return ; + + want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE), +PIPE_PREALLOC_MAX ); + +for (i =0 ; i < want; i++) {
Quoted 8 lines
fs/pipe.c void pipe_double_lock(struct pipe_inode_info *pipe1, · line 152
Quoted 5 lines
fs/pipe.c +5
-0+ page =alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT); +if (!page) +break ; + prealloc->pages[prealloc->count++] = page; + }I believe
alloc_pages_bulk()is supposed to be more efficient when allocating several pages at once like this.
Thanks Jeff. I understand bulk allocators refuses __GFP_ACCOUNT under memcg. (That is the reason I've CCed Shakeel in this patchset).
Anyway, reading the code it shows me:
unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
nodemask_t *nodemask, int nr_pages, struct page **page_array)
{
...
/* Bulk allocator does not support memcg accounting. */
if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
goto failed;Thanks for the review,
--breno
Re: [PATCH v2 1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
In reply to Breno LeitaoQuoted 181 lines · Breno Leitao
anon_pipe_write()takespipe->mutex(aka "mutex protecting the whole thing") and then, from the per-iterationanon_pipe_get_page()helper, used to callalloc_page(GFP_HIGHUSER | __GFP_ACCOUNT)once per page while still holding it.That allocation can sleep doing direct reclaim and/or runs memcg charging, which extends the critical section and stalls a concurrent reader on the very same mutex.
Just pre-alloc the required pages before the lock in an array and just pop them inside the lock.
This can improve the pipe throughput up to 48% and reduce the latency in 33%, easily seen when there is memory pressure and direct reclaim.
Signed-off-by Breno Leitao <[email protected]>--- fs/pipe.c | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 102 insertions(+), 3 deletions(-)fs/pipe.c +100
-3@@ -111,16 +111,76 @@ void pipe_double_lock(struct pipe_inode_info *pipe1,pipe_lock (pipe2); } -static struct page *anon_pipe_get_page (struct pipe_inode_info *pipe) +#define PIPE_PREALLOC_MAX 8 + +struct anon_pipe_prealloc { +struct page *pages[PIPE_PREALLOC_MAX ]; +unsigned int count; +}; + +/* +* Pre-allocate pages outside pipe->mutex for multi-page writes. +* alloc_page() with GFP_HIGHUSER can sleep in reclaim and runs memcg +* charging; doing it under the mutex stalls a concurrent reader. +* +* Loop alloc_page() instead of alloc_pages_bulk_*(): the bulk path refuses +* __GFP_ACCOUNT under memcg (see commit 8dcb3060d81d "memcg: page_alloc: +* skip bulk allocator for __GFP_ACCOUNT") and silently degrades to a single +* page. A per-page loop keeps memcg accounting and the task NUMA mempolicy +* honoured for every page; the per-call overhead is small compared to the +* pipe->mutex hold-time being shrunk. Any shortfall is covered by the +* in-lock alloc_page() fallback in anon_pipe_get_page(). +*/ +static void anon_pipe_get_page_prealloc (struct anon_pipe_prealloc *prealloc, +size_t total_len) +{ +unsigned int want, i; +struct page *page; + + prealloc->count =0 ; +if (total_len <=PAGE_SIZE ) +return ; + + want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE), +PIPE_PREALLOC_MAX ); + +for (i =0 ; i < want; i++) { + page =alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT); +if (!page) +break ; + prealloc->pages[prealloc->count++] = page; + } +} + +static struct page *anon_pipe_prealloc_pop (struct anon_pipe_prealloc *prealloc) +{ +if (!prealloc->count) +return NULL ; + + prealloc->count--; + +return prealloc->pages[prealloc->count]; +} + +static struct page *anon_pipe_get_page (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc) { +struct page *page; + +/* Drain prealloc first to keep tmp_page[] hot for later small writes. */ + page =anon_pipe_prealloc_pop (prealloc); +if (page) +return page; +for (int i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) {if (pipe->tmp_page[i]) { -struct page *page = pipe->tmp_page[i]; + page = pipe->tmp_page[i]; pipe->tmp_page[i] =NULL ;return page; } } +/* FWIW: This is called with pipe->mutex held */ return alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT); }@@ -139,6 +199,38 @@ static void anon_pipe_put_page(struct pipe_inode_info *pipe,put_page (page); } +/* +* Stash leftover prealloc pages in tmp_page[] so the next write to this +* pipe gets a hot page without entering the allocator. +*/ +static void anon_pipe_refill_tmp_pages (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc) +{ +int i, idx; + +if (!prealloc->count) +return ; + +for (i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) { +if (pipe->tmp_page[i]) +continue ; +if (!prealloc->count) +return ; + idx = --prealloc->count; + pipe->tmp_page[i] = prealloc->pages[idx]; + prealloc->pages[idx] =NULL ; + } +} + +/* Runs after mutex_unlock() to keep put_page() out of the critical section. */ +static void anon_pipe_free_pages (struct anon_pipe_prealloc *prealloc) +{ +while (prealloc->count) { + prealloc->count--; +put_page (prealloc->pages[prealloc->count]); + } +} +static void anon_pipe_buf_release (struct pipe_inode_info *pipe,struct pipe_buffer *buf) {@@ -432,6 +524,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) {struct file *filp = iocb->ki_filp;struct pipe_inode_info *pipe = filp->private_data; +struct anon_pipe_prealloc prealloc;unsigned int head;ssize_t ret =0 ;size_t total_len =iov_iter_count (from);@@ -455,6 +548,8 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)if (unlikely (total_len ==0 ))return 0 ; +anon_pipe_get_page_prealloc (&prealloc, total_len); +mutex_lock (&pipe->mutex);if (!pipe->readers) {@@ -512,7 +607,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)struct page *page;int copied; - page =anon_pipe_get_page (pipe); + page =anon_pipe_get_page (pipe, &prealloc);if (unlikely (!page)) {if (!ret) ret = -ENOMEM ;@@ -566,7 +661,9 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* after waiting we need to re-check whether the pipe * become empty while we dropped the lock. */ +anon_pipe_refill_tmp_pages (pipe, &prealloc);mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);if (was_empty)wake_up_interruptible_sync_poll (&pipe->rd_wait,EPOLLIN |EPOLLRDNORM );kill_fasync (&pipe->fasync_readers,SIGIO ,POLL_IN );
fs/pipe.c anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) · line 678
Quoted 6 lines
fs/pipe.c +1
-0@@ -576,9 +673,11 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) wake_next_writer = true; } out: +anon_pipe_refill_tmp_pages (pipe, &prealloc);if (pipe_is_full (pipe)) wake_next_writer = false;
maybe the new call would be nicer moved below pipe_is_full, but that's just cosmetics
Quoted 9 lines
fs/pipe.c +1
-1mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);/* * If we do do a wakeup event, we do a 'sync' wakeup, because we -- 2.54.0
Re: [PATCH v2 1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
In reply to Breno LeitaoTo be honest, I didn't read this patch carefully, but let me ask anyway.
Quoted 28 lines · Breno Leitao
fs/pipe.c +4
-1@@ -432,6 +524,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) {struct file *filp = iocb->ki_filp;struct pipe_inode_info *pipe = filp->private_data; +struct anon_pipe_prealloc prealloc;unsigned int head;ssize_t ret =0 ;size_t total_len =iov_iter_count (from);@@ -455,6 +548,8 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)if (unlikely (total_len ==0 ))return 0 ; +anon_pipe_get_page_prealloc (&prealloc, total_len); +mutex_lock (&pipe->mutex);if (!pipe->readers) {@@ -512,7 +607,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)struct page *page;int copied; - page =anon_pipe_get_page (pipe); + page =anon_pipe_get_page (pipe, &prealloc);if (unlikely (!page)) {if (!ret) ret = -ENOMEM ;
fs/pipe.c anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) · line 666
Quoted 6 lines
fs/pipe.c +2
-0@@ -566,7 +661,9 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* after waiting we need to re-check whether the pipe * become empty while we dropped the lock. */ +anon_pipe_refill_tmp_pages (pipe, &prealloc);mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);
Do we really want to call anon_pipe_free_pages() at this point?
The main loop will continue when pipe_writable() becomes true again...
Oleg.
Re: [PATCH v2 1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
Quoted 11 lines · Oleg Nesterov
fs/pipe.c anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) · line 666
Quoted 7 lines
fs/pipe.c +2
-0@@ -566,7 +661,9 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* after waiting we need to re-check whether the pipe * become empty while we dropped the lock. */ +anon_pipe_refill_tmp_pages (pipe, &prealloc);mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);Do we really want to call
anon_pipe_free_pages()at this point?The main loop will continue when
pipe_writable()becomes true again...
I went back and forth on this. The argument for freeing was that wait_event_interruptible_exclusive() can sleep arbitrarily long (slow or stopped reader), and holding up the prealloc pages felt antisocial -- especially under the memory pressure this series targets, where those pages are more useful on the freelists than parked on a sleeping task.
On the other side, on wakeup the loop is guaranteed to want pages again, and re-entering the allocator under the mutex puts us back in the contended state the patch removes. For any write() large enough to wait mid-syscall (which is the workload patch 2/2 measures), keeping them strictly wins on throughput / p99.
I think your read is the better one -- the throughput case is the whole point of the series, and the memory-hoarding concern is bounded (8 pages per blocked writer, freed in the out: path on syscall exit). Will drop the free_pages() call from the wait branch in v3 and keep only the one after the out: label, together with the nit from Mateusz.
Thanks for the review,
--breno
Re: [PATCH v2 1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
Quoted 20 lines · Breno Leitao
Quoted 11 lines · Oleg Nesterov
fs/pipe.c anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) · line 666
Quoted 7 lines
fs/pipe.c +2
-0@@ -566,7 +661,9 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* after waiting we need to re-check whether the pipe * become empty while we dropped the lock. */ +anon_pipe_refill_tmp_pages (pipe, &prealloc);mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);Do we really want to call
anon_pipe_free_pages()at this point?The main loop will continue when
pipe_writable()becomes true again...I went back and forth on this. The argument for freeing was that
wait_event_interruptible_exclusive()can sleep arbitrarily long (slow or stopped reader), and holding up the prealloc pages felt antisocial -- especially under the memory pressure this series targets, where those pages are more useful on the freelists than parked on a sleeping task.
Quoted 6 lines
On the other side, on wakeup the loop is guaranteed to want pages again, and re-entering the allocator under the mutex puts us back in the contended state the patch removes. For any
write()large enough to wait mid-syscall (which is the workload patch 2/2 measures), keeping them strictly wins on throughput / p99.
You can still prealloc after wakeup for whatever reminder you got though, but I can agree dropping these frees is a sensible way out and it is easier and I'm not going to insist on one way or the other.
However, I think it would be prudent to add a tracepoint to some machines on your fleet to find out how often they allocate pages under the mutex (and for what i/o size). Initial alloc for the first write < PAGE_SIZE definitely happens under the mutex which is probably not a problem, but for anything later? The tracepoint can have a trivial indicator if this is the first write if that matters. One can speculate all day, nothing beats checking what happens.
Re: [PATCH v2 1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
Hello Mateusz,
Quoted 28 lines · Mateusz Guzik
Quoted 20 lines · Breno Leitao
Quoted 11 lines · Oleg Nesterov
fs/pipe.c anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) · line 666
Quoted 7 lines
fs/pipe.c +2
-0@@ -566,7 +661,9 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* after waiting we need to re-check whether the pipe * become empty while we dropped the lock. */ +anon_pipe_refill_tmp_pages (pipe, &prealloc);mutex_unlock (&pipe->mutex); +anon_pipe_free_pages (&prealloc);Do we really want to call
anon_pipe_free_pages()at this point?The main loop will continue when
pipe_writable()becomes true again...I went back and forth on this. The argument for freeing was that
wait_event_interruptible_exclusive()can sleep arbitrarily long (slow or stopped reader), and holding up the prealloc pages felt antisocial -- especially under the memory pressure this series targets, where those pages are more useful on the freelists than parked on a sleeping task.Quoted 6 lines
On the other side, on wakeup the loop is guaranteed to want pages again, and re-entering the allocator under the mutex puts us back in the contended state the patch removes. For any
write()large enough to wait mid-syscall (which is the workload patch 2/2 measures), keeping them strictly wins on throughput / p99.
Quoted 3 lines
You can still prealloc after wakeup for whatever reminder you got though, but I can agree dropping these frees is a sensible way out and it is easier and I'm not going to insist on one way or the other.
Ack. I've sent a v3 with anon_pipe_free_pages() and anon_pipe_refill_tmp_pages() dropped.
Quoted 8 lines
However, I think it would be prudent to add a tracepoint to some machines on your fleet to find out how often they allocate pages under the mutex (and for what i/o size). Initial alloc for the first write <
PAGE_SIZEdefinitely happens under the mutex which is probably not a problem, but for anything later?The tracepoint can have a trivial
indicator if this is the first write if that matters. One can
Isn't this what I've reported earlier?
https://lore.kernel.org/all/[email protected]/
Adding a tracepoint is harder than usual, given kernel rollout takes ages.
But I hacked a bpftrace script and ran it on a random sample of fleet hosts (5 min each).
As reported earlier, multi-page pipe writes are not uncommon: on one host a single long-running process produced 196,476 under-mutex alloc_page() calls in 5 minutes, with allocs-per-write distributions reaching 16+ -- exactly the pattern this patch removes.
Most hosts sit at the boring ~20-30 allocs/sec dominated by one-page first-writes that the patch's total_len <= PAGE_SIZE early-return skips anyway, so the win is concentrated on the workloads that actually need it.
None of the allocs hit reclaim during the trace I ran, but I would expect direct reclaim to happen with the lock held.
Thanks for the review and direction,
--breno
PATCH v2 2/2 selftests/pipe: add pipe_bench microbenchmark
In reply to Breno LeitaoAdd a small selftest that stresses pipe->mutex contention by spawning N writer threads that hammer a single pipe with multi-page writes, plus M reader threads that drain. Each writer records its own write() latency samples into a log2-bucketed histogram; main aggregates and prints total writes, throughput, average and percentile (p50/p99) latencies, and the maximum observed latency.
Pass --memory-pressure to fork stress-ng (--vm 4 --vm-bytes 80% --vm-method all) for the duration of the run, so alloc_page() in anon_pipe_write() routinely hits direct reclaim. The flag fails fast if stress-ng is not on $PATH.
Program print something like the following, for different writes, readers, msgsizes and memory pressure:
config: writers=X readers=Y msgsize=Z duration=3 pipe_size=1048576 memory_pressure=[no|yes] writes: total=54451 rate=18150/s throughput_MBps: 1134.40 lat_avg_ns: 275355 lat_p50_ns_upper: 262143 lat_p99_ns_upper: 1048575 lat_max_ns: 2145633
--- tools/testing/selftests/Makefile | 1 + tools/testing/selftests/pipe/.gitignore | 1 + tools/testing/selftests/pipe/Makefile | 9 + tools/testing/selftests/pipe/pipe_bench.c | 616 ++++++++++++++++++++++++++++++ 4 files changed, 627 insertions(+)
tools/testing/selftests/Makefile +1 -0
@@ -91,6 +91,7 @@ TARGETS += pcie_bwctrl TARGETS += perf_events TARGETS += pidfd TARGETS += pid_namespace +TARGETS += pipe TARGETS += power_supply TARGETS += powerpc TARGETS += prctl
tools/testing/selftests/pipe/.gitignore new file +1 -0
@@ -0,0 +1 @@ +pipe_bench
tools/testing/selftests/pipe/Makefile new file +9 -0
@@ -0,0 +1,9 @@ +# SPDX-License-Identifier: GPL-2.0 +# Copyright (c) 2026 Meta Platforms, Inc. and affiliates +# Copyright (c) 2026 Breno Leitao <[email protected]> + +CFLAGS += -O2 -Wall -Wextra -pthread + +TEST_GEN_PROGS := pipe_bench + +include ../lib.mk
tools/testing/selftests/pipe/pipe_bench.c new file +616 -0
616 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v2 2/2] selftests/pipe: add pipe_bench microbenchmark
Quoted 16 lines · Breno Leitao
Add a small selftest that stresses
pipe->mutexcontention by spawning N writer threads that hammer a single pipe with multi-page writes, plus M reader threads that drain. Each writer records its ownwrite()latency samples into a log2-bucketed histogram; main aggregates and prints total writes, throughput, average and percentile (p50/p99) latencies, and the maximum observed latency.Pass --memory-pressure to fork stress-ng (--vm 4 --vm-bytes 80% --vm-method all) for the duration of the run, so
alloc_page()inanon_pipe_write()routinely hits direct reclaim. The flag fails fast if stress-ng is not on $PATH.Program print something like the following, for different writes, readers, msgsizes and memory pressure:
Quoted 8 lines
config: writers=X readers=Y msgsize=Z duration=3 pipe_size=1048576 memory_pressure=[no|yes] writes: total=54451 rate=18150/s throughput_MBps: 1134.40 lat_avg_ns: 275355 lat_p50_ns_upper: 262143 lat_p99_ns_upper: 1048575 lat_max_ns: 2145633
The more tests the better... but since it comes as 2/2, perhaps the changelog could mention the difference before/after 1/2 according to this test?
Oleg.
Re: [PATCH v2 2/2] selftests/pipe: add pipe_bench microbenchmark
Quoted 3 lines · Oleg Nesterov
The more tests the better... but since it comes as 2/2, perhaps the changelog could mention the difference before/after 1/2 according to this test?
Ah, I didn't read 0/2, sorry for the noise ;)
Oleg.
Quoted 112 lines · Breno Leitao
While profiling Meta's caching code[1], I found
pipe->mutexcontention on the hot path.anon_pipe_write()currently callsalloc_page()once per page while holdingpipe->mutex. The allocation can sleep doing direct reclaim and runs memcg charging, which extends the critical section and stalls any concurrent reader on the same mutex.This series pre-allocates pages outside
pipe->mutexinanon_pipe_write(): for writes that span more than one full page, up toPIPE_PREALLOC_MAX(8) pages are allocated via a per-pagealloc_page()loop before the mutex is taken.anon_pipe_get_page()then drains the prealloc array first, falls back to the per-pipe tmp_page[] cache, and only enters the allocator under the mutex for the leftover pages (writes larger thanPIPE_PREALLOC_MAX, single-page writes that skip prealloc, or shortfalls when the prealloc loop fails). Leftover prealloc pages are recycled into tmp_page[] before unlock and any remainder is put_page()'d after unlock, keeping the allocator out of the critical section on both sides.
alloc_pages_bulk_mempolicy()looked tempting but the bulk allocator refuses__GFP_ACCOUNTunder memcg -- it returns at most one page whenmemcg_kmem_online()&& (gfp &__GFP_ACCOUNT), see commit8dcb3060d81d("memcg:page_alloc: skip bulk allocator for__GFP_ACCOUNT"). A per-page loop keeps memcg accounting and the task NUMA mempolicy honoured uniformly without open-coding the charge.I also vibe-coded a microbenchmark to validate the change. It sweeps writers x readers over {1,2,5} x {1,5,10} with 64KB writes against a 1 MB pipe and prints throughput + latency percentiles per config.
Measured on arm64 and also on x86 using virtme-ng (16 vCPUs, 64KB writes, 1 MB pipe). The numbers below were collected on v1 (
alloc_pages_bulk()); v2's per-page loop preserves the dominant "allocation outside the mutex" win and is expected to land in the same range.== No memory pressure (10s per config) ==
Throughput in MB/s (baseline -> patched, delta):
writers readers=1 readers=5 readers=10 1 1119 -> 1354 (+21%) 1132 -> 1195 (+6%) 1060 -> 1240 (+17%) 2 1162 -> 1487 (+28%) 1034 -> 1285 (+24%) 1069 -> 1213 (+14%) 5 1152 -> 1357 (+18%) 1021 -> 1164 (+14%) 997 -> 1239 (+24%)Avg write latency in ns (baseline -> patched, delta):
writers readers=1 readers=5 readers=10 1 55786 -> 46103 (-17%) 55164 -> 52260 (-5%) 58906 -> 50370 (-14%) 2 107546 -> 84011 (-22%) 120837 -> 97206 (-20%) 116860 -> 103036 (-12%) 5 271293 -> 230170 (-15%) 306089 -> 268429 (-12%) 313300 -> 252232 (-19%)Throughput improves +6% to +28% and average write latency drops 5% to 22% across every configuration.
== Under memory pressure (--memory-pressure, 6s per config) ==
stress-ng --vm 2 --vm-bytes 50% --vm-keep is forked alongside the sweep so the
alloc_page()calls insideanon_pipe_write()routinely hit direct reclaim -- exactly the regime the patch targets.Throughput in MB/s (baseline -> patched, delta):
writers readers=1 readers=5 readers=10 1 1088 -> 1438 (+32%) 996 -> 1477 (+48%) 989 -> 1194 (+21%) 2 1076 -> 1378 (+28%) 1007 -> 1269 (+26%) 1018 -> 1234 (+21%) 5 1052 -> 1311 (+25%) 986 -> 1225 (+24%) 972 -> 1249 (+29%)Avg write latency in ns (baseline -> patched, delta):
writers readers=1 readers=5 readers=10 1 57397 -> 43406 (-24%) 62690 -> 42272 (-33%) 63136 -> 52272 (-17%) 2 116121 -> 90700 (-22%) 124098 -> 98481 (-21%) 122754 -> 101217 (-18%) 5 297122 -> 238322 (-20%) 316836 -> 255095 (-19%) 321496 -> 250189 (-22%)Throughput improves +21% to +48% and average write latency drops 17% to 33% -- a noticeably bigger win than the no-pressure run.
That tracks: when
alloc_page()has to dip into reclaim, the cost of holdingpipe->mutexacross it is highest, and pulling the allocation out of the critical section pays the most.Signed-off-by Breno Leitao <[email protected]>---
Changes in v2:
- Switch the prealloc path fromalloc_pages_bulk_mempolicy()to a per-pagealloc_page(GFP_HIGHUSER | __GFP_ACCOUNT)loop.
- Split the prealloc work out ofanon_pipe_write()into dedicated helpers (anon_pipe_get_page_prealloc/anon_pipe_prealloc_pop/anon_pipe_refill_tmp_pages/anon_pipe_free_pages) gathered in
structanon_pipe_prealloc, so the write path stays readable.
- Recycle leftover prealloc pages into pipe->tmp_page[] before unlocking
- Link to v1: https://patch.msgid.link/[email protected]To: Alexander Viro <[email protected]>
To: Christian Brauner <[email protected]>
To: Jan Kara <[email protected]>
To: Shuah Khan <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]---
Breno Leitao (2):
fs/pipe: pre-allocate pages outsidepipe->mutexinanon_pipe_writeselftests/pipe: addpipe_benchmicrobenchmarkfs/pipe.c | 105 ++++- tools/testing/selftests/Makefile | 1 + tools/testing/selftests/pipe/.gitignore | 1 + tools/testing/selftests/pipe/Makefile | 9 + tools/testing/selftests/pipe/pipe_bench.c | 616 ++++++++++++++++++++++++++++++ 5 files changed, 729 insertions(+), 3 deletions(-)
Quoted 7 lines
---
base-commit:e98d21c170b01ddef366f023bbfcf6b31509fa83
change-id: 20260515-fix_pipe-c91677c187e7Best regards,
Signature · 1 line
Breno Leitao <[email protected]>
Pity this can't use the bulk page allocator, but looks good otherwise.