fs/pipe: reduce pipe->mutex contention by pre-allocating outside the lock
Subsystems (3)
v3 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 v3:
- Drop the anon_pipe_free_pages() call from the wait branch so
leftover prealloc pages survive the wait_event sleep. The loop resumes once pipe_writable() becomes true and immediately wants
pages again; freeing them forced the next iteration back into alloc_page() under pipe->mutex, defeating the patch for any write large enough to block mid-syscall. The out: label still frees any remainder on syscall exit, so nothing leaks. (Suggested by Oleg Nesterov.)
- Drop the in-loop anon_pipe_refill_tmp_pages() call in the wait
branch as well: its only purpose was to rescue pages from the free_pages() above. With prealloc surviving the sleep, anon_pipe_get_page() drains it directly on the next iteration, and the out: label still refills tmp_page[] at syscall exit.
- Link to v2: https://patch.msgid.link/[email protected]
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 | 103 ++++- 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, 727 insertions(+), 3 deletions(-)
---
base-commit: e98d21c170b01ddef366f023bbfcf6b31509fa83
change-id: 20260515-fix_pipe-c91677c187e7
Best regards,
Signature · 1 line
Breno Leitao <[email protected]>
PATCH v3 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 | 103 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 100 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 ;
@@ -576,9 +671,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
PATCH v3 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
Quoted 18 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.
Quoted 1 line
[...]
Applied to the vfs-7.2.misc branch of the vfs/vfs.git tree. Patches in the vfs-7.2.misc branch should appear in linux-next soon.
Please report any outstanding bugs that were missed during review in a new review to the original patch series allowing us to drop it.
It's encouraged to provide Acked-bys and Reviewed-bys even though the patch has now been applied. If possible patch trailers will be updated.
Note that commit hashes shown below are subject to change due to rebase, trailer updates or similar. If in doubt, please check the listed branch.
tree: https://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs.git branch: vfs-7.2.misc
[1/2] fs/pipe: pre-allocate pages outside pipe->mutex in anon_pipe_write
https://git.kernel.org/vfs/vfs/c/212ed884a1ae [2/2] selftests/pipe: add pipe_bench microbenchmark https://git.kernel.org/vfs/vfs/c/d29bd8efe162
Quoted 11 lines · Breno Leitao
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.
[...]
Quoted 3 lines
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.
How do the numbers compare with 1-byte writes/reads? (It's fine if they're not *faster*, just want to make sure they don't get any *worse*. This case comes up a lot with pipes used for synchronization or event reporting, such as with make.)
Quoted 14 lines · Josh Triplett
Quoted 11 lines · Breno Leitao
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.[...]
Quoted 8 lines
Quoted 3 lines
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.
How do the numbers compare with 1-byte writes/reads? (It's fine if they're not *faster*, just want to make sure they don't get any *worse*. This case comes up a lot with pipes used for synchronization or event reporting, such as with make.)
Note the "for writes that span more than one full page" above. Pre-allocate does nothing if total_len <= PAGE_SIZE.
Oleg.
Quoted 19 lines · Oleg Nesterov
Quoted 18 lines · Josh Triplett
Quoted 11 lines · Breno Leitao
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.[...]
Quoted 3 lines
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.
Quoted 7 lines
Quoted 4 lines
How do the numbers compare with 1-byte writes/reads? (It's fine if they're not *faster*, just want to make sure they don't get any *worse*. This case comes up a lot with pipes used for synchronization or event reporting, such as with make.)
Note the "for writes that span more than one full page" above. Pre-allocate does nothing if
total_len<=PAGE_SIZE.
Exactly.
The pre-allocation only triggers for multi-page writes:
anon_pipe_get_page_prealloc() returns immediately when total_len <= PAGE_SIZE, so a 1-byte (or any sub-page) write never enters the new path.
anon_pipe_get_page() then falls through to the existing tmp_page/alloc_page logic exactly as before; the only added cost is one length check and a NULL prealloc pop, both trivially predicted.
Measured it to _just be sure_, 1-byte ping-pong (perf bench sched pipe -s 1):
baseline: 2.674 usecs/op
patched: 2.710 usecs/op (+1.3%, within run-to-run noise)--breno
Quoted 41 lines · Breno Leitao
Quoted 19 lines · Oleg Nesterov
Quoted 18 lines · Josh Triplett
Quoted 11 lines · Breno Leitao
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.[...]
Quoted 3 lines
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.
Quoted 7 lines
Quoted 4 lines
How do the numbers compare with 1-byte writes/reads? (It's fine if they're not *faster*, just want to make sure they don't get any *worse*. This case comes up a lot with pipes used for synchronization or event reporting, such as with make.)
Note the "for writes that span more than one full page" above. Pre-allocate does nothing if
total_len<=PAGE_SIZE.Exactly.
The pre-allocation only triggers for multi-page writes:
anon_pipe_get_page_prealloc()returns immediately whentotal_len<=PAGE_SIZE, so a 1-byte (or any sub-page) write never enters the new path.
anon_pipe_get_page()then falls through to the existing tmp_page/alloc_page logic exactly as before; the only added cost is one length check and a NULL prealloc pop, both trivially predicted.
Quoted 6 lines
Measured it to
_justbesure_, 1-byte ping-pong (perf bench sched pipe -s 1):baseline: 2.674 usecs/op patched: 2.710 usecs/op (+1.3%, within run-to-run noise)--breno
There are trivial touch ups which can be done by adding a bunch of predicts and inlining kill_fasync if someone can be bothered.
Quoted 3 lines · Mateusz Guzik
There are trivial touch ups which can be done by adding a bunch of predicts and inlining
kill_fasyncif someone can be bothered.
I was thinking about another change, see below. It assumes that in the likely case another writer won't steal the pages from ->tmp_page[] before we take pipe->mutex.
I'm not sure this makes sense, and I have no idea how it would impact performance in "real" workloads.
Oleg.
---
fs/pipe.c +8 -2
@@ -131,7 +131,8 @@ struct anon_pipe_prealloc {* 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, +static void anon_pipe_get_page_prealloc (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc,size_t total_len) {unsigned int want, i;
@@ -144,6 +145,11 @@ static void anon_pipe_get_page_prealloc(struct anon_pipe_prealloc *prealloc, want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE),PIPE_PREALLOC_MAX ); +for (i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) { +if (pipe->tmp_page[i] && !--want) +return ; + } +for (i =0 ; i < want; i++) { page =alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT);if (!page)
@@ -548,7 +554,7 @@ 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); +anon_pipe_get_page_prealloc (pipe, &prealloc, total_len);mutex_lock (&pipe->mutex);
Hello Mateusz,
Quoted 8 lines · Oleg Nesterov
Quoted 3 lines · Mateusz Guzik
There are trivial touch ups which can be done by adding a bunch of predicts and inlining
kill_fasyncif someone can be bothered.I was thinking about another change, see below. It assumes that in the likely case another writer won't steal the pages from ->tmp_page[] before we take
pipe->mutex.
Do you think we could eventually eliminate the tmp_page[] array and consolidate everything into the prealloc pages? That would unify the two page pools currently used in the pipe write path.
When I examined this previously, it appeared non-trivial but potentially feasible.
What is your view on it?
Thanks,
--breno
Quoted 13 lines · Breno Leitao
Hello Mateusz,
Quoted 8 lines · Oleg Nesterov
Quoted 3 lines · Mateusz Guzik
There are trivial touch ups which can be done by adding a bunch of predicts and inlining
kill_fasyncif someone can be bothered.I was thinking about another change, see below. It assumes that in the likely case another writer won't steal the pages from ->tmp_page[] before we take
pipe->mutex.
Quoted 7 lines
Do you think we could eventually eliminate the tmp_page[] array and consolidate everything into the prealloc pages? That would unify the two page pools currently used in the pipe write path.
When I examined this previously, it appeared non-trivial but potentially feasible.
I think I commented on this in my first e-mail.
In order for this to be acceptable there would have to be a way to reclaim these pages in case of memory shortage. Otherwise, say you cached 8 pages and the pipe remains unused afterwards -- all the pages are actively being wasted with no means to free them.
Now that I wrote it though, I think this is very much doable.
Naively you could add a list for all allocated pipes, but that's terrible from perf standpoint even if said list is distributed enough to not have contention on pipe creation/destruction in a real setting.
But suppose pipes are allocated from a dedicated slab. There is presumably a way to walk all of the created pipes, regardless if they are is "allocated" or "freed", in which case such shrinker could be implemented without extra overhead for the write side. Someone familiar with slab (slub?) internals would have to chime in though.
Quoted 18 lines · Mateusz Guzik
Quoted 17 lines · Breno Leitao
Hello Mateusz,
Quoted 8 lines · Oleg Nesterov
Quoted 3 lines · Mateusz Guzik
There are trivial touch ups which can be done by adding a bunch of predicts and inlining
kill_fasyncif someone can be bothered.I was thinking about another change, see below. It assumes that in the likely case another writer won't steal the pages from ->tmp_page[] before we take
pipe->mutex.Do you think we could eventually eliminate the tmp_page[] array and consolidate everything into the prealloc pages? That would unify the two page pools currently used in the pipe write path.
Quoted 8 lines
Quoted 3 lines
When I examined this previously, it appeared non-trivial but potentially feasible.
I think I commented on this in my first e-mail.
In order for this to be acceptable there would have to be a way to reclaim these pages in case of memory shortage.
Hmm, I understand scenario doesn't apply to the patch that got accepted. The series doesn't grow the cache: tmp_page[] is still the existing 2-entry array
anon_pipe_refill_tmp_pages() only fills empty tmp_page[] slots; every other prealloc page is put_page()'d before the write() returns.
So an idle pipe holds at most 2 cached pages — the same cap mainline already maintains via anon_pipe_put_page() on the release side, freed in free_pipe_info().
/* 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]);
}
}Net new unreclaimable footprint from this series is zero.
Quoted 9 lines · Breno Leitao
Hello Mateusz,
Quoted 5 lines · Oleg Nesterov
Quoted 3 lines · Mateusz Guzik
There are trivial touch ups which can be done by adding a bunch of predicts and inlining
kill_fasyncif someone can be bothered.
Quoted 7 lines
Quoted 3 lines
I was thinking about another change, see below. It assumes that in the likely case another writer won't steal the pages from ->tmp_page[] before we take
pipe->mutex.Do you think we could eventually eliminate the tmp_page[] array and consolidate everything into the prealloc pages? That would unify the two page pools currently used in the pipe write path.
Cough... When I saw the 1st version of your patches, my first thought was:
we need to unify prealloc and tmp_page[] somehow.
But nothing simple came to my mind ;)
Oleg.
Quoted 44 lines · Oleg Nesterov
Quoted 3 lines · Mateusz Guzik
There are trivial touch ups which can be done by adding a bunch of predicts and inlining
kill_fasyncif someone can be bothered.I was thinking about another change, see below. It assumes that in the likely case another writer won't steal the pages from ->tmp_page[] before we take
pipe->mutex.I'm not sure this makes sense, and I have no idea how it would impact performance in "real" workloads.
Oleg.
---fs/pipe.c +7
-1@@ -131,7 +131,8 @@ struct anon_pipe_prealloc {* 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, +static void anon_pipe_get_page_prealloc (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc,size_t total_len) {unsigned int want, i;@@ -144,6 +145,11 @@ static void anon_pipe_get_page_prealloc(struct anon_pipe_prealloc *prealloc, want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE),PIPE_PREALLOC_MAX ); +for (i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) { +if (pipe->tmp_page[i] && !--want) +return ; + } +for (i =0 ; i < want; i++) { page =alloc_page (GFP_HIGHUSER | __GFP_ACCOUNT);if (!page)
fs/pipe.c anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) · line 560
Quoted 8 lines
fs/pipe.c +1
-1@@ -548,7 +554,7 @@ 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); +anon_pipe_get_page_prealloc (pipe, &prealloc, total_len);mutex_lock (&pipe->mutex);
As proposed this will guarantee a big write which fits fine into pages cached into tmp_page followed by a small write will have to resort to an allocation under the mutex, partially defeating the original patch. So you would need to add some provisions to check if you need to allocate something even in that case.
Quoted 11 lines · Mateusz Guzik
Quoted 11 lines
fs/pipe.c +2
-1-static void anon_pipe_get_page_prealloc (struct anon_pipe_prealloc *prealloc, +static void anon_pipe_get_page_prealloc (struct pipe_inode_info *pipe, +struct anon_pipe_prealloc *prealloc,size_t total_len) {unsigned int want, i;@@ -144,6 +145,11 @@ static void anon_pipe_get_page_prealloc(struct anon_pipe_prealloc *prealloc, want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE),PIPE_PREALLOC_MAX );
Quoted 10 lines
fs/pipe.c static void anon_pipe_get_page_prealloc(struct anon_pipe_prealloc *prealloc, · line 151
Quoted 4 lines
fs/pipe.c +4
-0+for (i =0 ; i <ARRAY_SIZE (pipe->tmp_page); i++) { +if (pipe->tmp_page[i] && !--want) +return ; + }As proposed this will guarantee a big write which fits fine into pages cached into
tmp_pagefollowed by a small write will have to resort to an allocation under the mutex, partially defeating the original patch. So you would need to add some provisions to check if you need to allocate something even in that case.
Yes, with the change like this, at least the "total_len <= PAGE_SIZE" check should be revisited.
But let me repeat: I'm not sure this makes sense, and I have no idea how it would impact performance in "real" workloads.
In particular, I don't know if the case when another writer steals the pages from ->tmp_page[] is actually "unlikely".
Oleg.
Quoted 3 lines · Mateusz Guzik
There are trivial touch ups which can be done by adding a bunch of predicts and inlining
kill_fasyncif someone can be bothered.
Speaking of trivial touch ups...
anon_pipe_write() does:
* Epoll nonsensically wants a wakeup whether the pipe * was already empty or not. */ if (was_empty || pipe->poll_usage) wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
Again, I have no idea if the unnecessary wakeup affects the performance, probably not. But somehow this "|| poll_usage" condition looks annoying to me...
Perhaps it makes sense to change pipe_poll() to not set ->poll_usage unconditionally?
Oleg.
---
fs/pipe.c +4 -2
@@ -760,10 +760,12 @@ pipe_poll(struct file *filp, poll_table *wait)struct pipe_inode_info *pipe = filp->private_data;union pipe_index idx; +#ifdef CONFIG_EPOLL /* Epoll has some historical nasty semantics, this enables them */ -if (unlikely (!READ_ONCE (pipe->poll_usage))) +if ((filp->f_mode &FMODE_READ ) && filp->f_ep + &&unlikely (!READ_ONCE (pipe->poll_usage)))WRITE_ONCE (pipe->poll_usage, true); - +#endif /* * Reading pipe state only -- no need for acquiring the semaphore. *
Quoted 5 lines · Breno Leitao
Measured it to
_justbesure_, 1-byte ping-pong (perf bench sched pipe -s 1):baseline: 2.674 usecs/op patched: 2.710 usecs/op (+1.3%, within run-to-run noise)
Can you try this:
fs/fcntl.c +8 -17
@@ -1118,11 +1118,14 @@ int fasync_helper(int fd, struct file * filp, int on, struct fasync_struct **fapEXPORT_SYMBOL (fasync_helper); -/* -* rcu_read_lock() is held -*/ -static void kill_fasync_rcu (struct fasync_struct *fa,int sig,int band) +void __kill_fasync (struct fasync_struct **fp,int sig,int band) { +struct fasync_struct *fa; + +guard (rcu)(); + + fa =rcu_dereference (*fp); +while (fa) {struct fown_struct *fown;unsigned long flags;
@@ -1148,19 +1151,7 @@ static void kill_fasync_rcu(struct fasync_struct *fa, int sig, int band) fa =rcu_dereference (fa->fa_next); } } - -void kill_fasync (struct fasync_struct **fp,int sig,int band) -{ -/* First a quick test without locking: usually -* the list is empty. -*/ -if (*fp) { -rcu_read_lock (); -kill_fasync_rcu (rcu_dereference (*fp), sig, band); -rcu_read_unlock (); - } -} -EXPORT_SYMBOL (kill_fasync); +EXPORT_SYMBOL (__kill_fasync);static int __init fcntl_init (void ) {
fs/pipe.c +4 -4
@@ -426,7 +426,7 @@ anon_pipe_read(struct kiocb *iocb, struct iov_iter *to) } error =pipe_buf_confirm (pipe, buf); -if (error) { +if (unlikely (error)) {if (!ret) ret = error;break ;
@@ -541,7 +541,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)* the same time, we could set up lockdep annotations for that, but * since we don't actually need that, it's simpler to just bail here. */ -if (pipe_has_watch_queue (pipe)) +if (unlikely (pipe_has_watch_queue (pipe)))return -EXDEV ;/* Null write succeeds. */
@@ -552,7 +552,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)mutex_lock (&pipe->mutex); -if (!pipe->readers) { +if (unlikely (!pipe->readers)) {if ((iocb->ki_flags &IOCB_NOSIGNAL ) ==0 )send_sig (SIGPIPE , current,0 ); ret = -EPIPE ;
@@ -593,7 +593,7 @@ anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) }for (;;) { -if (!pipe->readers) { +if (unlikely (!pipe->readers)) {if ((iocb->ki_flags &IOCB_NOSIGNAL ) ==0 )send_sig (SIGPIPE , current,0 );if (!ret)
include/linux/fs.h +6 -1
@@ -1383,7 +1383,12 @@ extern struct fasync_struct *fasync_alloc(void);extern void fasync_free (struct fasync_struct *);/* can be called from interrupts */ -extern void kill_fasync (struct fasync_struct **,int ,int ); +void __kill_fasync (struct fasync_struct **fp,int sig,int band); +static inline void kill_fasync (struct fasync_struct **fp,int sig,int band) +{ +if (unlikely (*fp)) +__kill_fasync (fp, sig, band); +}extern void __f_setown (struct file *filp,struct pid *,enum pid_type ,int force);extern int f_setown (struct file *filp,int who,int force);
Quoted 8 lines · Mateusz Guzik
Quoted 5 lines · Breno Leitao
Measured it to
_justbesure_, 1-byte ping-pong (perf bench sched pipe -s 1):baseline: 2.674 usecs/op patched: 2.710 usecs/op (+1.3%, within run-to-run noise)Can you try this:
I've tested this change, but the results show no real measurable improvement beyond measurement noise.
patched + your change: ~2.66 usecs/op (-1.7%, within noise)
In my experience, branch hints haven't proven particularly effective, at least that was the case when I worked on PowerPC some time ago.
Quoted 2 lines · Breno Leitao
Throughput improves +6% to +28% and average write latency drops 5% to 22% across every configuration.
FWIW: Kernel Test Robot detected similar and slightly better numbers with this patch, and reported 29.1% improvement on lmbench3
%stddev %change %stddev
\ | \
37316 +29.1% 48191 ± 2% lmbench3.PIPE.bandwidth.MB/sec
5690 ± 9% +153.5% 14426 ± 18% lmbench3.time.involuntary_context_switches