Merge tag 'perf-tools-fixes-for-v6.17-2025-09-16' of git://git.kernel.org/pub/scm...
[linux-2.6-block.git] / fs / pipe.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
1da177e4
LT
2/*
3 * linux/fs/pipe.c
4 *
5 * Copyright (C) 1991, 1992, 1999 Linus Torvalds
6 */
7
8#include <linux/mm.h>
9#include <linux/file.h>
10#include <linux/poll.h>
11#include <linux/slab.h>
12#include <linux/module.h>
13#include <linux/init.h>
14#include <linux/fs.h>
35f3d14d 15#include <linux/log2.h>
1da177e4 16#include <linux/mount.h>
4fa7ec5d 17#include <linux/pseudo_fs.h>
b502bd11 18#include <linux/magic.h>
1da177e4
LT
19#include <linux/pipe_fs_i.h>
20#include <linux/uio.h>
21#include <linux/highmem.h>
5274f052 22#include <linux/pagemap.h>
db349509 23#include <linux/audit.h>
ba719bae 24#include <linux/syscalls.h>
b492e95b 25#include <linux/fcntl.h>
d86133bd 26#include <linux/memcontrol.h>
c73be61c 27#include <linux/watch_queue.h>
1998f193 28#include <linux/sysctl.h>
f3def827 29#include <linux/sort.h>
1da177e4 30
7c0f6ba6 31#include <linux/uaccess.h>
1da177e4
LT
32#include <asm/ioctls.h>
33
599a0ac1
AV
34#include "internal.h"
35
46c4c9d1
AXH
36/*
37 * New pipe buffers will be restricted to this size while the user is exceeding
38 * their pipe buffer quota. The general pipe use case needs at least two
39 * buffers: one for data yet to be read, and one for new data. If this is less
40 * than two, then a write to a non-empty pipe may block even if the pipe is not
41 * full. This can occur with GNU make jobserver or similar uses of pipes as
42 * semaphores: multiple processes may be waiting to write tokens back to the
43 * pipe before reading tokens: https://lore.kernel.org/lkml/1628086770.5rn8p04n6j.none@localhost/.
44 *
45 * Users can reduce their pipe buffers with F_SETPIPE_SZ below this at their
46 * own risk, namely: pipe writes to non-full pipes may block until the pipe is
47 * emptied.
48 */
49#define PIPE_MIN_DEF_BUFFERS 2
50
b492e95b
JA
51/*
52 * The max size that a non-root user is allowed to grow the pipe. Can
ff9da691 53 * be set by root in /proc/sys/fs/pipe-max-size
b492e95b 54 */
1998f193 55static unsigned int pipe_max_size = 1048576;
ff9da691 56
759c0114
WT
57/* Maximum allocatable pages per user. Hard limit is unset by default, soft
58 * matches default values.
59 */
1998f193
LC
60static unsigned long pipe_user_pages_hard;
61static unsigned long pipe_user_pages_soft = PIPE_DEF_BUFFERS * INR_OPEN_CUR;
759c0114 62
1da177e4 63/*
8cefc107
DH
64 * We use head and tail indices that aren't masked off, except at the point of
65 * dereference, but rather they're allowed to wrap naturally. This means there
66 * isn't a dead spot in the buffer, but the ring has to be a power of two and
67 * <= 2^31.
68 * -- David Howells 2019-09-23.
69 *
1da177e4
LT
70 * Reads with count = 0 should always return 0.
71 * -- Julian Bradfield 1999-06-07.
72 *
73 * FIFOs and Pipes now generate SIGIO for both readers and writers.
74 * -- Jeremy Elson <jelson@circlemud.org> 2001-08-16
75 *
76 * pipe_read & write cleanup
77 * -- Manfred Spraul <manfred@colorfullife.com> 2002-05-09
78 */
79
85f273a6
KO
80#ifdef CONFIG_PROVE_LOCKING
81static int pipe_lock_cmp_fn(const struct lockdep_map *a,
82 const struct lockdep_map *b)
61e0d47c 83{
85f273a6 84 return cmp_int((unsigned long) a, (unsigned long) b);
61e0d47c 85}
85f273a6 86#endif
61e0d47c
MS
87
88void pipe_lock(struct pipe_inode_info *pipe)
89{
85f273a6
KO
90 if (pipe->files)
91 mutex_lock(&pipe->mutex);
61e0d47c
MS
92}
93EXPORT_SYMBOL(pipe_lock);
94
95void pipe_unlock(struct pipe_inode_info *pipe)
96{
6447a3cf 97 if (pipe->files)
72b0d9aa 98 mutex_unlock(&pipe->mutex);
61e0d47c
MS
99}
100EXPORT_SYMBOL(pipe_unlock);
101
102void pipe_double_lock(struct pipe_inode_info *pipe1,
103 struct pipe_inode_info *pipe2)
104{
105 BUG_ON(pipe1 == pipe2);
106
85f273a6
KO
107 if (pipe1 > pipe2)
108 swap(pipe1, pipe2);
109
110 pipe_lock(pipe1);
111 pipe_lock(pipe2);
61e0d47c
MS
112}
113
46af8e24
MG
114static struct page *anon_pipe_get_page(struct pipe_inode_info *pipe)
115{
116 for (int i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
117 if (pipe->tmp_page[i]) {
118 struct page *page = pipe->tmp_page[i];
119 pipe->tmp_page[i] = NULL;
120 return page;
121 }
122 }
123
124 return alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT);
125}
126
127static void anon_pipe_put_page(struct pipe_inode_info *pipe,
128 struct page *page)
129{
130 if (page_count(page) == 1) {
131 for (int i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
132 if (!pipe->tmp_page[i]) {
133 pipe->tmp_page[i] = page;
134 return;
135 }
136 }
137 }
138
139 put_page(page);
140}
141
341b446b
IM
142static void anon_pipe_buf_release(struct pipe_inode_info *pipe,
143 struct pipe_buffer *buf)
1da177e4
LT
144{
145 struct page *page = buf->page;
146
46af8e24 147 anon_pipe_put_page(pipe, page);
1da177e4
LT
148}
149
c928f642
CH
150static bool anon_pipe_buf_try_steal(struct pipe_inode_info *pipe,
151 struct pipe_buffer *buf)
d86133bd
VD
152{
153 struct page *page = buf->page;
154
c928f642
CH
155 if (page_count(page) != 1)
156 return false;
157 memcg_kmem_uncharge_page(page, 0);
158 __SetPageLocked(page);
159 return true;
d86133bd
VD
160}
161
0845718d 162/**
c928f642 163 * generic_pipe_buf_try_steal - attempt to take ownership of a &pipe_buffer
0845718d
JA
164 * @pipe: the pipe that the buffer belongs to
165 * @buf: the buffer to attempt to steal
166 *
167 * Description:
b51d63c6 168 * This function attempts to steal the &struct page attached to
0845718d
JA
169 * @buf. If successful, this function returns 0 and returns with
170 * the page locked. The caller may then reuse the page for whatever
b51d63c6 171 * he wishes; the typical use is insertion into a different file
0845718d
JA
172 * page cache.
173 */
c928f642
CH
174bool generic_pipe_buf_try_steal(struct pipe_inode_info *pipe,
175 struct pipe_buffer *buf)
5abc97aa 176{
46e678c9
JA
177 struct page *page = buf->page;
178
0845718d
JA
179 /*
180 * A reference of one is golden, that means that the owner of this
181 * page is the only one holding a reference to it. lock the page
182 * and return OK.
183 */
46e678c9 184 if (page_count(page) == 1) {
46e678c9 185 lock_page(page);
c928f642 186 return true;
46e678c9 187 }
c928f642 188 return false;
5abc97aa 189}
c928f642 190EXPORT_SYMBOL(generic_pipe_buf_try_steal);
5abc97aa 191
0845718d 192/**
b51d63c6 193 * generic_pipe_buf_get - get a reference to a &struct pipe_buffer
0845718d
JA
194 * @pipe: the pipe that the buffer belongs to
195 * @buf: the buffer to get a reference to
196 *
197 * Description:
198 * This function grabs an extra reference to @buf. It's used in
3d742d4b 199 * the tee() system call, when we duplicate the buffers in one
0845718d
JA
200 * pipe into another.
201 */
15fab63e 202bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
70524490 203{
cd1adf1b 204 return try_get_page(buf->page);
70524490 205}
51921cb7 206EXPORT_SYMBOL(generic_pipe_buf_get);
70524490 207
6818173b
MS
208/**
209 * generic_pipe_buf_release - put a reference to a &struct pipe_buffer
210 * @pipe: the pipe that the buffer belongs to
211 * @buf: the buffer to put a reference to
212 *
213 * Description:
214 * This function releases a reference to @buf.
215 */
216void generic_pipe_buf_release(struct pipe_inode_info *pipe,
217 struct pipe_buffer *buf)
218{
09cbfeaf 219 put_page(buf->page);
6818173b 220}
51921cb7 221EXPORT_SYMBOL(generic_pipe_buf_release);
6818173b 222
d4c3cca9 223static const struct pipe_buf_operations anon_pipe_buf_ops = {
c928f642
CH
224 .release = anon_pipe_buf_release,
225 .try_steal = anon_pipe_buf_try_steal,
226 .get = generic_pipe_buf_get,
1da177e4
LT
227};
228
85190d15
LT
229/* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
230static inline bool pipe_readable(const struct pipe_inode_info *pipe)
231{
3d252160 232 union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
85190d15
LT
233 unsigned int writers = READ_ONCE(pipe->writers);
234
3d252160 235 return !pipe_empty(idx.head, idx.tail) || !writers;
85190d15
LT
236}
237
478dbf12
MK
238static inline unsigned int pipe_update_tail(struct pipe_inode_info *pipe,
239 struct pipe_buffer *buf,
240 unsigned int tail)
241{
242 pipe_buf_release(pipe, buf);
243
244 /*
245 * If the pipe has a watch_queue, we need additional protection
246 * by the spinlock because notifications get posted with only
247 * this spinlock, no mutex
248 */
249 if (pipe_has_watch_queue(pipe)) {
250 spin_lock_irq(&pipe->rd_wait.lock);
251#ifdef CONFIG_WATCH_QUEUE
252 if (buf->flags & PIPE_BUF_FLAG_LOSS)
253 pipe->note_loss = true;
254#endif
255 pipe->tail = ++tail;
256 spin_unlock_irq(&pipe->rd_wait.lock);
257 return tail;
258 }
259
260 /*
261 * Without a watch_queue, we can simply increment the tail
262 * without the spinlock - the mutex is enough.
263 */
264 pipe->tail = ++tail;
265 return tail;
266}
267
1da177e4 268static ssize_t
f017b0a4 269anon_pipe_read(struct kiocb *iocb, struct iov_iter *to)
1da177e4 270{
fb9096a3 271 size_t total_len = iov_iter_count(to);
ee0b3e67 272 struct file *filp = iocb->ki_filp;
de32ec4c 273 struct pipe_inode_info *pipe = filp->private_data;
aaec5a95 274 bool wake_writer = false, wake_next_reader = false;
1da177e4 275 ssize_t ret;
1da177e4 276
1da177e4
LT
277 /* Null read succeeds. */
278 if (unlikely(total_len == 0))
279 return 0;
280
1da177e4 281 ret = 0;
85f273a6 282 mutex_lock(&pipe->mutex);
f467a6a6
LT
283
284 /*
aaec5a95
ON
285 * We only wake up writers if the pipe was full when we started reading
286 * and it is no longer full after reading to avoid unnecessary wakeups.
f467a6a6
LT
287 *
288 * But when we do wake up writers, we do so using a sync wakeup
289 * (WF_SYNC), because we want them to get going and generate more
290 * data for us.
291 */
1da177e4 292 for (;;) {
2ed147f0
DH
293 /* Read ->head with a barrier vs post_one_notification() */
294 unsigned int head = smp_load_acquire(&pipe->head);
8cefc107 295 unsigned int tail = pipe->tail;
8cefc107 296
e7d553d6
DH
297#ifdef CONFIG_WATCH_QUEUE
298 if (pipe->note_loss) {
299 struct watch_notification n;
300
301 if (total_len < 8) {
302 if (ret == 0)
303 ret = -ENOBUFS;
304 break;
305 }
306
307 n.type = WATCH_TYPE_META;
308 n.subtype = WATCH_META_LOSS_NOTIFICATION;
309 n.info = watch_sizeof(n);
310 if (copy_to_iter(&n, sizeof(n), to) != sizeof(n)) {
311 if (ret == 0)
312 ret = -EFAULT;
313 break;
314 }
315 ret += sizeof(n);
316 total_len -= sizeof(n);
317 pipe->note_loss = false;
318 }
319#endif
320
8cefc107 321 if (!pipe_empty(head, tail)) {
ba082202 322 struct pipe_buffer *buf = pipe_buf(pipe, tail);
1da177e4 323 size_t chars = buf->len;
637b58c2
AV
324 size_t written;
325 int error;
1da177e4 326
8cfba763
DH
327 if (chars > total_len) {
328 if (buf->flags & PIPE_BUF_FLAG_WHOLE) {
329 if (ret == 0)
330 ret = -ENOBUFS;
331 break;
332 }
1da177e4 333 chars = total_len;
8cfba763 334 }
1da177e4 335
fba597db 336 error = pipe_buf_confirm(pipe, buf);
f84d7519 337 if (error) {
5274f052 338 if (!ret)
e5953cbd 339 ret = error;
5274f052
JA
340 break;
341 }
f84d7519 342
fb9096a3 343 written = copy_page_to_iter(buf->page, buf->offset, chars, to);
637b58c2 344 if (unlikely(written < chars)) {
341b446b 345 if (!ret)
637b58c2 346 ret = -EFAULT;
1da177e4
LT
347 break;
348 }
349 ret += chars;
350 buf->offset += chars;
351 buf->len -= chars;
9883035a
LT
352
353 /* Was it a packet buffer? Clean up and exit */
354 if (buf->flags & PIPE_BUF_FLAG_PACKET) {
355 total_len = chars;
356 buf->len = 0;
357 }
358
aaec5a95
ON
359 if (!buf->len) {
360 wake_writer |= pipe_full(head, tail, pipe->max_usage);
478dbf12 361 tail = pipe_update_tail(pipe, buf, tail);
aaec5a95 362 }
1da177e4
LT
363 total_len -= chars;
364 if (!total_len)
365 break; /* common path: read succeeded */
8cefc107
DH
366 if (!pipe_empty(head, tail)) /* More to do? */
367 continue;
1da177e4 368 }
8cefc107 369
923f4f23 370 if (!pipe->writers)
1da177e4 371 break;
a28c8b9d
LT
372 if (ret)
373 break;
c04fe8e3
JA
374 if ((filp->f_flags & O_NONBLOCK) ||
375 (iocb->ki_flags & IOCB_NOWAIT)) {
a28c8b9d
LT
376 ret = -EAGAIN;
377 break;
1da177e4 378 }
85f273a6 379 mutex_unlock(&pipe->mutex);
d1c6a2aa
LT
380 /*
381 * We only get here if we didn't actually read anything.
382 *
d1c6a2aa
LT
383 * But because we didn't read anything, at this point we can
384 * just return directly with -ERESTARTSYS if we're interrupted,
385 * since we've done any required wakeups and there's no need
386 * to mark anything accessed. And we've dropped the lock.
387 */
0ddad21d 388 if (wait_event_interruptible_exclusive(pipe->rd_wait, pipe_readable(pipe)) < 0)
d1c6a2aa
LT
389 return -ERESTARTSYS;
390
0ddad21d 391 wake_next_reader = true;
aaec5a95 392 mutex_lock(&pipe->mutex);
1da177e4 393 }
00a7d398 394 if (pipe_is_empty(pipe))
0ddad21d 395 wake_next_reader = false;
85f273a6 396 mutex_unlock(&pipe->mutex);
341b446b 397
aaec5a95 398 if (wake_writer)
0ddad21d 399 wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
0ddad21d
LT
400 if (wake_next_reader)
401 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
fe67f4dd 402 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
f017b0a4
ON
403 return ret;
404}
405
406static ssize_t
407fifo_pipe_read(struct kiocb *iocb, struct iov_iter *to)
408{
409 int ret = anon_pipe_read(iocb, to);
1da177e4 410 if (ret > 0)
f017b0a4 411 file_accessed(iocb->ki_filp);
1da177e4
LT
412 return ret;
413}
414
9883035a
LT
415static inline int is_packetized(struct file *file)
416{
417 return (file->f_flags & O_DIRECT) != 0;
418}
419
85190d15
LT
420/* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
421static inline bool pipe_writable(const struct pipe_inode_info *pipe)
422{
3d252160 423 union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
85190d15
LT
424 unsigned int max_usage = READ_ONCE(pipe->max_usage);
425
3d252160 426 return !pipe_full(idx.head, idx.tail, max_usage) ||
85190d15
LT
427 !READ_ONCE(pipe->readers);
428}
429
1da177e4 430static ssize_t
f017b0a4 431anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)
1da177e4 432{
ee0b3e67 433 struct file *filp = iocb->ki_filp;
de32ec4c 434 struct pipe_inode_info *pipe = filp->private_data;
8f868d68 435 unsigned int head;
f0d1bec9 436 ssize_t ret = 0;
f0d1bec9 437 size_t total_len = iov_iter_count(from);
1da177e4 438 ssize_t chars;
1b6b26ae 439 bool was_empty = false;
0ddad21d 440 bool wake_next_writer = false;
1da177e4 441
055ca835
JH
442 /*
443 * Reject writing to watch queue pipes before the point where we lock
444 * the pipe.
445 * Otherwise, lockdep would be unhappy if the caller already has another
446 * pipe locked.
447 * If we had to support locking a normal pipe and a notification pipe at
448 * the same time, we could set up lockdep annotations for that, but
449 * since we don't actually need that, it's simpler to just bail here.
450 */
451 if (pipe_has_watch_queue(pipe))
452 return -EXDEV;
453
1da177e4
LT
454 /* Null write succeeds. */
455 if (unlikely(total_len == 0))
456 return 0;
457
85f273a6 458 mutex_lock(&pipe->mutex);
1da177e4 459
923f4f23 460 if (!pipe->readers) {
1da177e4
LT
461 send_sig(SIGPIPE, current, 0);
462 ret = -EPIPE;
463 goto out;
464 }
465
1b6b26ae 466 /*
1b6b26ae
LT
467 * If it wasn't empty we try to merge new data into
468 * the last buffer.
469 *
470 * That naturally merges small writes, but it also
3a34b13a 471 * page-aligns the rest of the writes for large writes
1b6b26ae
LT
472 * spanning multiple pages.
473 */
8cefc107 474 head = pipe->head;
3b844826 475 was_empty = pipe_empty(head, pipe->tail);
1b6b26ae 476 chars = total_len & (PAGE_SIZE-1);
3b844826 477 if (chars && !was_empty) {
ba082202 478 struct pipe_buffer *buf = pipe_buf(pipe, head - 1);
1da177e4 479 int offset = buf->offset + buf->len;
341b446b 480
f6dd9755
CH
481 if ((buf->flags & PIPE_BUF_FLAG_CAN_MERGE) &&
482 offset + chars <= PAGE_SIZE) {
fba597db 483 ret = pipe_buf_confirm(pipe, buf);
6ae08069 484 if (ret)
5274f052 485 goto out;
f84d7519 486
f0d1bec9
AV
487 ret = copy_page_from_iter(buf->page, offset, chars, from);
488 if (unlikely(ret < chars)) {
6ae08069 489 ret = -EFAULT;
1da177e4 490 goto out;
f6762b7a 491 }
1b6b26ae 492
6ae08069 493 buf->len += ret;
f0d1bec9 494 if (!iov_iter_count(from))
1da177e4
LT
495 goto out;
496 }
497 }
498
499 for (;;) {
923f4f23 500 if (!pipe->readers) {
1da177e4 501 send_sig(SIGPIPE, current, 0);
341b446b
IM
502 if (!ret)
503 ret = -EPIPE;
1da177e4
LT
504 break;
505 }
8cefc107 506
a194dfe6 507 head = pipe->head;
8f868d68 508 if (!pipe_full(head, pipe->tail, pipe->max_usage)) {
fbaa530e 509 struct pipe_buffer *buf;
46af8e24 510 struct page *page;
f0d1bec9 511 int copied;
1da177e4 512
46af8e24
MG
513 page = anon_pipe_get_page(pipe);
514 if (unlikely(!page)) {
515 if (!ret)
516 ret = -ENOMEM;
517 break;
1da177e4 518 }
a194dfe6 519
ee5eda8e
ON
520 copied = copy_page_from_iter(page, 0, PAGE_SIZE, from);
521 if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) {
46af8e24 522 anon_pipe_put_page(pipe, page);
ee5eda8e
ON
523 if (!ret)
524 ret = -EFAULT;
525 break;
526 }
1da177e4 527
ee5eda8e 528 pipe->head = head + 1;
1da177e4 529 /* Insert it into the buffer array */
ba082202 530 buf = pipe_buf(pipe, head);
1da177e4
LT
531 buf->page = page;
532 buf->ops = &anon_pipe_buf_ops;
533 buf->offset = 0;
f6dd9755 534 if (is_packetized(filp))
9883035a 535 buf->flags = PIPE_BUF_FLAG_PACKET;
f6dd9755
CH
536 else
537 buf->flags = PIPE_BUF_FLAG_CAN_MERGE;
1da177e4 538
a194dfe6 539 buf->len = copied;
ee5eda8e 540 ret += copied;
a194dfe6 541
f0d1bec9 542 if (!iov_iter_count(from))
1da177e4 543 break;
8cefc107 544
1da177e4 545 continue;
a40cd584 546 }
8cefc107
DH
547
548 /* Wait for buffer space to become available. */
c04fe8e3
JA
549 if ((filp->f_flags & O_NONBLOCK) ||
550 (iocb->ki_flags & IOCB_NOWAIT)) {
341b446b
IM
551 if (!ret)
552 ret = -EAGAIN;
1da177e4
LT
553 break;
554 }
555 if (signal_pending(current)) {
341b446b
IM
556 if (!ret)
557 ret = -ERESTARTSYS;
1da177e4
LT
558 break;
559 }
1b6b26ae
LT
560
561 /*
562 * We're going to release the pipe lock and wait for more
563 * space. We wake up any readers if necessary, and then
564 * after waiting we need to re-check whether the pipe
565 * become empty while we dropped the lock.
566 */
85f273a6 567 mutex_unlock(&pipe->mutex);
fe67f4dd 568 if (was_empty)
0ddad21d 569 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
fe67f4dd 570 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
0ddad21d 571 wait_event_interruptible_exclusive(pipe->wr_wait, pipe_writable(pipe));
85f273a6 572 mutex_lock(&pipe->mutex);
00a7d398 573 was_empty = pipe_is_empty(pipe);
0ddad21d 574 wake_next_writer = true;
1da177e4
LT
575 }
576out:
00a7d398 577 if (pipe_is_full(pipe))
0ddad21d 578 wake_next_writer = false;
85f273a6 579 mutex_unlock(&pipe->mutex);
1b6b26ae
LT
580
581 /*
582 * If we do do a wakeup event, we do a 'sync' wakeup, because we
583 * want the reader to start processing things asap, rather than
584 * leave the data pending.
585 *
586 * This is particularly important for small writes, because of
587 * how (for example) the GNU make jobserver uses small writes to
588 * wake up pending jobs
3b844826
LT
589 *
590 * Epoll nonsensically wants a wakeup whether the pipe
591 * was already empty or not.
1b6b26ae 592 */
fe67f4dd 593 if (was_empty || pipe->poll_usage)
0ddad21d 594 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
fe67f4dd 595 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
0ddad21d
LT
596 if (wake_next_writer)
597 wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
f017b0a4
ON
598 return ret;
599}
600
601static ssize_t
602fifo_pipe_write(struct kiocb *iocb, struct iov_iter *from)
603{
604 int ret = anon_pipe_write(iocb, from);
605 if (ret > 0) {
606 struct file *filp = iocb->ki_filp;
607 if (sb_start_write_trylock(file_inode(filp)->i_sb)) {
608 int err = file_update_time(filp);
609 if (err)
610 ret = err;
611 sb_end_write(file_inode(filp)->i_sb);
612 }
c3b2da31 613 }
1da177e4
LT
614 return ret;
615}
616
d59d0b1b 617static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1da177e4 618{
de32ec4c 619 struct pipe_inode_info *pipe = filp->private_data;
d810d4c2 620 unsigned int count, head, tail;
1da177e4
LT
621
622 switch (cmd) {
c73be61c 623 case FIONREAD:
85f273a6 624 mutex_lock(&pipe->mutex);
c73be61c
DH
625 count = 0;
626 head = pipe->head;
627 tail = pipe->tail;
8cefc107 628
d810d4c2
LT
629 while (!pipe_empty(head, tail)) {
630 count += pipe_buf(pipe, tail)->len;
c73be61c
DH
631 tail++;
632 }
85f273a6 633 mutex_unlock(&pipe->mutex);
923f4f23 634
c73be61c 635 return put_user(count, (int __user *)arg);
923f4f23 636
c73be61c
DH
637#ifdef CONFIG_WATCH_QUEUE
638 case IOC_WATCH_QUEUE_SET_SIZE: {
639 int ret;
85f273a6 640 mutex_lock(&pipe->mutex);
c73be61c 641 ret = watch_queue_set_size(pipe, arg);
85f273a6 642 mutex_unlock(&pipe->mutex);
c73be61c
DH
643 return ret;
644 }
645
646 case IOC_WATCH_QUEUE_SET_FILTER:
647 return watch_queue_set_filter(
648 pipe, (struct watch_notification_filter __user *)arg);
649#endif
650
651 default:
652 return -ENOIOCTLCMD;
1da177e4
LT
653 }
654}
655
dd67081b 656/* No kernel lock held - fine */
a11e1d43
LT
657static __poll_t
658pipe_poll(struct file *filp, poll_table *wait)
dd67081b 659{
a11e1d43 660 __poll_t mask;
dd67081b 661 struct pipe_inode_info *pipe = filp->private_data;
3d252160 662 union pipe_index idx;
a11e1d43 663
3b844826 664 /* Epoll has some historical nasty semantics, this enables them */
f485922d 665 WRITE_ONCE(pipe->poll_usage, true);
3b844826 666
ad910e36 667 /*
0ddad21d 668 * Reading pipe state only -- no need for acquiring the semaphore.
ad910e36
LT
669 *
670 * But because this is racy, the code has to add the
671 * entry to the poll table _first_ ..
672 */
0ddad21d
LT
673 if (filp->f_mode & FMODE_READ)
674 poll_wait(filp, &pipe->rd_wait, wait);
675 if (filp->f_mode & FMODE_WRITE)
676 poll_wait(filp, &pipe->wr_wait, wait);
1da177e4 677
ad910e36
LT
678 /*
679 * .. and only then can you do the racy tests. That way,
680 * if something changes and you got it wrong, the poll
681 * table entry will wake you up and fix it.
682 */
3d252160 683 idx.head_tail = READ_ONCE(pipe->head_tail);
ad910e36 684
a11e1d43 685 mask = 0;
1da177e4 686 if (filp->f_mode & FMODE_READ) {
3d252160 687 if (!pipe_empty(idx.head, idx.tail))
8cefc107 688 mask |= EPOLLIN | EPOLLRDNORM;
5a957bba 689 if (!pipe->writers && filp->f_pipe != pipe->w_counter)
a9a08845 690 mask |= EPOLLHUP;
1da177e4
LT
691 }
692
693 if (filp->f_mode & FMODE_WRITE) {
3d252160 694 if (!pipe_full(idx.head, idx.tail, pipe->max_usage))
8cefc107 695 mask |= EPOLLOUT | EPOLLWRNORM;
5e5d7a22 696 /*
a9a08845 697 * Most Unices do not set EPOLLERR for FIFOs but on Linux they
5e5d7a22
PE
698 * behave exactly like pipes for poll().
699 */
923f4f23 700 if (!pipe->readers)
a9a08845 701 mask |= EPOLLERR;
1da177e4
LT
702 }
703
704 return mask;
705}
706
b0d8d229
LT
707static void put_pipe_info(struct inode *inode, struct pipe_inode_info *pipe)
708{
709 int kill = 0;
710
711 spin_lock(&inode->i_lock);
712 if (!--pipe->files) {
713 inode->i_pipe = NULL;
714 kill = 1;
715 }
716 spin_unlock(&inode->i_lock);
717
718 if (kill)
719 free_pipe_info(pipe);
720}
721
1da177e4 722static int
599a0ac1 723pipe_release(struct inode *inode, struct file *file)
1da177e4 724{
b0d8d229 725 struct pipe_inode_info *pipe = file->private_data;
923f4f23 726
85f273a6 727 mutex_lock(&pipe->mutex);
599a0ac1
AV
728 if (file->f_mode & FMODE_READ)
729 pipe->readers--;
730 if (file->f_mode & FMODE_WRITE)
731 pipe->writers--;
341b446b 732
6551d5c5
LT
733 /* Was that the last reader or writer, but not the other side? */
734 if (!pipe->readers != !pipe->writers) {
735 wake_up_interruptible_all(&pipe->rd_wait);
736 wake_up_interruptible_all(&pipe->wr_wait);
923f4f23
IM
737 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
738 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
1da177e4 739 }
85f273a6 740 mutex_unlock(&pipe->mutex);
ba5bb147 741
b0d8d229 742 put_pipe_info(inode, pipe);
1da177e4
LT
743 return 0;
744}
745
746static int
599a0ac1 747pipe_fasync(int fd, struct file *filp, int on)
1da177e4 748{
de32ec4c 749 struct pipe_inode_info *pipe = filp->private_data;
599a0ac1 750 int retval = 0;
1da177e4 751
85f273a6 752 mutex_lock(&pipe->mutex);
599a0ac1
AV
753 if (filp->f_mode & FMODE_READ)
754 retval = fasync_helper(fd, filp, on, &pipe->fasync_readers);
755 if ((filp->f_mode & FMODE_WRITE) && retval >= 0) {
341b446b 756 retval = fasync_helper(fd, filp, on, &pipe->fasync_writers);
599a0ac1
AV
757 if (retval < 0 && (filp->f_mode & FMODE_READ))
758 /* this can happen only if on == T */
e5bc49ba
ON
759 fasync_helper(-1, filp, 0, &pipe->fasync_readers);
760 }
85f273a6 761 mutex_unlock(&pipe->mutex);
60aa4924 762 return retval;
1da177e4
LT
763}
764
c73be61c
DH
765unsigned long account_pipe_buffers(struct user_struct *user,
766 unsigned long old, unsigned long new)
759c0114 767{
9c87bcf0 768 return atomic_long_add_return(new - old, &user->pipe_bufs);
759c0114
WT
769}
770
c73be61c 771bool too_many_pipe_buffers_soft(unsigned long user_bufs)
759c0114 772{
f7340761
EB
773 unsigned long soft_limit = READ_ONCE(pipe_user_pages_soft);
774
775 return soft_limit && user_bufs > soft_limit;
759c0114
WT
776}
777
c73be61c 778bool too_many_pipe_buffers_hard(unsigned long user_bufs)
759c0114 779{
f7340761
EB
780 unsigned long hard_limit = READ_ONCE(pipe_user_pages_hard);
781
782 return hard_limit && user_bufs > hard_limit;
759c0114
WT
783}
784
c73be61c 785bool pipe_is_unprivileged_user(void)
85c2dd54
EB
786{
787 return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN);
788}
789
7bee130e 790struct pipe_inode_info *alloc_pipe_info(void)
3a326a2c 791{
923f4f23 792 struct pipe_inode_info *pipe;
09b4d199
MK
793 unsigned long pipe_bufs = PIPE_DEF_BUFFERS;
794 struct user_struct *user = get_current_user();
9c87bcf0 795 unsigned long user_bufs;
f7340761 796 unsigned int max_size = READ_ONCE(pipe_max_size);
3a326a2c 797
d86133bd 798 pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL_ACCOUNT);
09b4d199
MK
799 if (pipe == NULL)
800 goto out_free_uid;
801
f7340761
EB
802 if (pipe_bufs * PAGE_SIZE > max_size && !capable(CAP_SYS_RESOURCE))
803 pipe_bufs = max_size >> PAGE_SHIFT;
086e774a 804
9c87bcf0 805 user_bufs = account_pipe_buffers(user, 0, pipe_bufs);
a005ca0e 806
c73be61c 807 if (too_many_pipe_buffers_soft(user_bufs) && pipe_is_unprivileged_user()) {
46c4c9d1
AXH
808 user_bufs = account_pipe_buffers(user, pipe_bufs, PIPE_MIN_DEF_BUFFERS);
809 pipe_bufs = PIPE_MIN_DEF_BUFFERS;
09b4d199 810 }
759c0114 811
c73be61c 812 if (too_many_pipe_buffers_hard(user_bufs) && pipe_is_unprivileged_user())
a005ca0e
MK
813 goto out_revert_acct;
814
906f9040 815 pipe->bufs = kcalloc(pipe_bufs, sizeof(struct pipe_buffer),
a005ca0e
MK
816 GFP_KERNEL_ACCOUNT);
817
09b4d199 818 if (pipe->bufs) {
0ddad21d
LT
819 init_waitqueue_head(&pipe->rd_wait);
820 init_waitqueue_head(&pipe->wr_wait);
09b4d199 821 pipe->r_counter = pipe->w_counter = 1;
6718b6f8 822 pipe->max_usage = pipe_bufs;
8cefc107 823 pipe->ring_size = pipe_bufs;
c73be61c 824 pipe->nr_accounted = pipe_bufs;
09b4d199 825 pipe->user = user;
09b4d199 826 mutex_init(&pipe->mutex);
85f273a6 827 lock_set_cmp_fn(&pipe->mutex, pipe_lock_cmp_fn, NULL);
09b4d199 828 return pipe;
3a326a2c
IM
829 }
830
a005ca0e 831out_revert_acct:
9c87bcf0 832 (void) account_pipe_buffers(user, pipe_bufs, 0);
09b4d199
MK
833 kfree(pipe);
834out_free_uid:
835 free_uid(user);
35f3d14d 836 return NULL;
3a326a2c
IM
837}
838
4b8a8f1e 839void free_pipe_info(struct pipe_inode_info *pipe)
1da177e4 840{
aeb213cd 841 unsigned int i;
1da177e4 842
c73be61c 843#ifdef CONFIG_WATCH_QUEUE
db8facfc 844 if (pipe->watch_queue)
c73be61c 845 watch_queue_clear(pipe->watch_queue);
c73be61c
DH
846#endif
847
848 (void) account_pipe_buffers(pipe->user, pipe->nr_accounted, 0);
759c0114 849 free_uid(pipe->user);
8cefc107 850 for (i = 0; i < pipe->ring_size; i++) {
923f4f23 851 struct pipe_buffer *buf = pipe->bufs + i;
1da177e4 852 if (buf->ops)
a779638c 853 pipe_buf_release(pipe, buf);
1da177e4 854 }
db8facfc
DH
855#ifdef CONFIG_WATCH_QUEUE
856 if (pipe->watch_queue)
857 put_watch_queue(pipe->watch_queue);
858#endif
46af8e24
MG
859 for (i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
860 if (pipe->tmp_page[i])
861 __free_page(pipe->tmp_page[i]);
862 }
906f9040 863 kfree(pipe->bufs);
923f4f23 864 kfree(pipe);
1da177e4
LT
865}
866
68279f9c 867static struct vfsmount *pipe_mnt __ro_after_init;
341b446b 868
c23fbb6b
ED
869/*
870 * pipefs_dname() is called from d_path().
871 */
872static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen)
873{
0f60d288 874 return dynamic_dname(buffer, buflen, "pipe:[%lu]",
75c3cfa8 875 d_inode(dentry)->i_ino);
c23fbb6b
ED
876}
877
3ba13d17 878static const struct dentry_operations pipefs_dentry_operations = {
c23fbb6b 879 .d_dname = pipefs_dname,
1da177e4
LT
880};
881
262b2fa9
ON
882static const struct file_operations pipeanon_fops;
883
1da177e4
LT
884static struct inode * get_pipe_inode(void)
885{
a209dfc7 886 struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb);
923f4f23 887 struct pipe_inode_info *pipe;
1da177e4
LT
888
889 if (!inode)
890 goto fail_inode;
891
85fe4025
CH
892 inode->i_ino = get_next_ino();
893
7bee130e 894 pipe = alloc_pipe_info();
923f4f23 895 if (!pipe)
1da177e4 896 goto fail_iput;
3a326a2c 897
ba5bb147
AV
898 inode->i_pipe = pipe;
899 pipe->files = 2;
923f4f23 900 pipe->readers = pipe->writers = 1;
262b2fa9 901 inode->i_fop = &pipeanon_fops;
1da177e4
LT
902
903 /*
904 * Mark the inode dirty from the very beginning,
905 * that way it will never be moved to the dirty
906 * list because "mark_inode_dirty()" will think
907 * that it already _is_ on the dirty list.
908 */
909 inode->i_state = I_DIRTY;
910 inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR;
da9592ed
DH
911 inode->i_uid = current_fsuid();
912 inode->i_gid = current_fsgid();
16a94965 913 simple_inode_init_ts(inode);
923f4f23 914
1da177e4
LT
915 return inode;
916
917fail_iput:
918 iput(inode);
341b446b 919
1da177e4
LT
920fail_inode:
921 return NULL;
922}
923
e4fad8e5 924int create_pipe_files(struct file **res, int flags)
1da177e4 925{
e4fad8e5 926 struct inode *inode = get_pipe_inode();
d6cbd281 927 struct file *f;
8a018eb5 928 int error;
1da177e4 929
1da177e4 930 if (!inode)
e4fad8e5 931 return -ENFILE;
1da177e4 932
c73be61c 933 if (flags & O_NOTIFICATION_PIPE) {
8a018eb5
QC
934 error = watch_queue_init(inode->i_pipe);
935 if (error) {
936 free_pipe_info(inode->i_pipe);
c73be61c 937 iput(inode);
8a018eb5 938 return error;
c73be61c 939 }
c73be61c
DH
940 }
941
152b6372
AV
942 f = alloc_file_pseudo(inode, pipe_mnt, "",
943 O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)),
262b2fa9 944 &pipeanon_fops);
e9bb1f9b 945 if (IS_ERR(f)) {
152b6372
AV
946 free_pipe_info(inode->i_pipe);
947 iput(inode);
948 return PTR_ERR(f);
e9bb1f9b 949 }
341b446b 950
de32ec4c 951 f->private_data = inode->i_pipe;
5a957bba 952 f->f_pipe = 0;
d6cbd281 953
183266f2 954 res[0] = alloc_file_clone(f, O_RDONLY | (flags & O_NONBLOCK),
262b2fa9 955 &pipeanon_fops);
e9bb1f9b 956 if (IS_ERR(res[0])) {
b10a4a9f
AV
957 put_pipe_info(inode, inode->i_pipe);
958 fput(f);
959 return PTR_ERR(res[0]);
e9bb1f9b 960 }
de32ec4c 961 res[0]->private_data = inode->i_pipe;
5a957bba 962 res[0]->f_pipe = 0;
e4fad8e5 963 res[1] = f;
d8e464ec
LT
964 stream_open(inode, res[0]);
965 stream_open(inode, res[1]);
dd765ba8
JA
966
967 /* pipe groks IOCB_NOWAIT */
968 res[0]->f_mode |= FMODE_NOWAIT;
969 res[1]->f_mode |= FMODE_NOWAIT;
970
2a42754b
AG
971 /*
972 * Disable permission and pre-content events, but enable legacy
973 * inotify events for legacy users.
974 */
975 file_set_fsnotify_mode(res[0], FMODE_NONOTIFY_PERM);
976 file_set_fsnotify_mode(res[1], FMODE_NONOTIFY_PERM);
e4fad8e5 977 return 0;
d6cbd281
AK
978}
979
5b249b1b 980static int __do_pipe_flags(int *fd, struct file **files, int flags)
d6cbd281 981{
d6cbd281
AK
982 int error;
983 int fdw, fdr;
984
c73be61c 985 if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT | O_NOTIFICATION_PIPE))
ed8cae8b
UD
986 return -EINVAL;
987
e4fad8e5
AV
988 error = create_pipe_files(files, flags);
989 if (error)
990 return error;
d6cbd281 991
ed8cae8b 992 error = get_unused_fd_flags(flags);
d6cbd281
AK
993 if (error < 0)
994 goto err_read_pipe;
995 fdr = error;
996
ed8cae8b 997 error = get_unused_fd_flags(flags);
d6cbd281
AK
998 if (error < 0)
999 goto err_fdr;
1000 fdw = error;
1001
157cf649 1002 audit_fd_pair(fdr, fdw);
d6cbd281
AK
1003 fd[0] = fdr;
1004 fd[1] = fdw;
d6cbd281
AK
1005 return 0;
1006
1007 err_fdr:
1008 put_unused_fd(fdr);
1009 err_read_pipe:
e4fad8e5
AV
1010 fput(files[0]);
1011 fput(files[1]);
d6cbd281 1012 return error;
1da177e4
LT
1013}
1014
5b249b1b
AV
1015int do_pipe_flags(int *fd, int flags)
1016{
1017 struct file *files[2];
1018 int error = __do_pipe_flags(fd, files, flags);
1019 if (!error) {
1020 fd_install(fd[0], files[0]);
1021 fd_install(fd[1], files[1]);
1022 }
1023 return error;
1024}
1025
d35c7b0e
UD
1026/*
1027 * sys_pipe() is the normal C calling standard for creating
1028 * a pipe. It's not the way Unix traditionally does this, though.
1029 */
0a216dd1 1030static int do_pipe2(int __user *fildes, int flags)
d35c7b0e 1031{
5b249b1b 1032 struct file *files[2];
d35c7b0e
UD
1033 int fd[2];
1034 int error;
1035
5b249b1b 1036 error = __do_pipe_flags(fd, files, flags);
d35c7b0e 1037 if (!error) {
5b249b1b
AV
1038 if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) {
1039 fput(files[0]);
1040 fput(files[1]);
1041 put_unused_fd(fd[0]);
1042 put_unused_fd(fd[1]);
d35c7b0e 1043 error = -EFAULT;
5b249b1b
AV
1044 } else {
1045 fd_install(fd[0], files[0]);
1046 fd_install(fd[1], files[1]);
ba719bae 1047 }
d35c7b0e
UD
1048 }
1049 return error;
1050}
1051
0a216dd1
DB
1052SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)
1053{
1054 return do_pipe2(fildes, flags);
1055}
1056
2b664219 1057SYSCALL_DEFINE1(pipe, int __user *, fildes)
ed8cae8b 1058{
0a216dd1 1059 return do_pipe2(fildes, 0);
ed8cae8b
UD
1060}
1061
472e5b05
LT
1062/*
1063 * This is the stupid "wait for pipe to be readable or writable"
1064 * model.
1065 *
1066 * See pipe_read/write() for the proper kind of exclusive wait,
1067 * but that requires that we wake up any other readers/writers
1068 * if we then do not end up reading everything (ie the whole
1069 * "wake_next_reader/writer" logic in pipe_read/write()).
1070 */
1071void pipe_wait_readable(struct pipe_inode_info *pipe)
1072{
1073 pipe_unlock(pipe);
1074 wait_event_interruptible(pipe->rd_wait, pipe_readable(pipe));
1075 pipe_lock(pipe);
1076}
1077
1078void pipe_wait_writable(struct pipe_inode_info *pipe)
1079{
1080 pipe_unlock(pipe);
1081 wait_event_interruptible(pipe->wr_wait, pipe_writable(pipe));
1082 pipe_lock(pipe);
1083}
1084
1085/*
1086 * This depends on both the wait (here) and the wakeup (wake_up_partner)
1087 * holding the pipe lock, so "*cnt" is stable and we know a wakeup cannot
1088 * race with the count check and waitqueue prep.
1089 *
1090 * Normally in order to avoid races, you'd do the prepare_to_wait() first,
1091 * then check the condition you're waiting for, and only then sleep. But
1092 * because of the pipe lock, we can check the condition before being on
1093 * the wait queue.
1094 *
1095 * We use the 'rd_wait' waitqueue for pipe partner waiting.
1096 */
fc7478a2 1097static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt)
f776c738 1098{
472e5b05 1099 DEFINE_WAIT(rdwait);
8cefc107 1100 int cur = *cnt;
f776c738
AV
1101
1102 while (cur == *cnt) {
472e5b05
LT
1103 prepare_to_wait(&pipe->rd_wait, &rdwait, TASK_INTERRUPTIBLE);
1104 pipe_unlock(pipe);
1105 schedule();
1106 finish_wait(&pipe->rd_wait, &rdwait);
1107 pipe_lock(pipe);
f776c738
AV
1108 if (signal_pending(current))
1109 break;
1110 }
1111 return cur == *cnt ? -ERESTARTSYS : 0;
1112}
1113
fc7478a2 1114static void wake_up_partner(struct pipe_inode_info *pipe)
f776c738 1115{
6551d5c5 1116 wake_up_interruptible_all(&pipe->rd_wait);
f776c738
AV
1117}
1118
1119static int fifo_open(struct inode *inode, struct file *filp)
1120{
262b2fa9 1121 bool is_pipe = inode->i_fop == &pipeanon_fops;
f776c738
AV
1122 struct pipe_inode_info *pipe;
1123 int ret;
1124
5a957bba 1125 filp->f_pipe = 0;
ba5bb147
AV
1126
1127 spin_lock(&inode->i_lock);
1128 if (inode->i_pipe) {
1129 pipe = inode->i_pipe;
1130 pipe->files++;
1131 spin_unlock(&inode->i_lock);
1132 } else {
1133 spin_unlock(&inode->i_lock);
7bee130e 1134 pipe = alloc_pipe_info();
f776c738 1135 if (!pipe)
ba5bb147
AV
1136 return -ENOMEM;
1137 pipe->files = 1;
1138 spin_lock(&inode->i_lock);
1139 if (unlikely(inode->i_pipe)) {
1140 inode->i_pipe->files++;
1141 spin_unlock(&inode->i_lock);
4b8a8f1e 1142 free_pipe_info(pipe);
ba5bb147
AV
1143 pipe = inode->i_pipe;
1144 } else {
1145 inode->i_pipe = pipe;
1146 spin_unlock(&inode->i_lock);
1147 }
f776c738 1148 }
de32ec4c 1149 filp->private_data = pipe;
ba5bb147
AV
1150 /* OK, we have a pipe and it's pinned down */
1151
85f273a6 1152 mutex_lock(&pipe->mutex);
f776c738
AV
1153
1154 /* We can only do regular read/write on fifos */
d8e464ec 1155 stream_open(inode, filp);
f776c738 1156
d8e464ec 1157 switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) {
f776c738
AV
1158 case FMODE_READ:
1159 /*
1160 * O_RDONLY
1161 * POSIX.1 says that O_NONBLOCK means return with the FIFO
1162 * opened, even when there is no process writing the FIFO.
1163 */
f776c738
AV
1164 pipe->r_counter++;
1165 if (pipe->readers++ == 0)
fc7478a2 1166 wake_up_partner(pipe);
f776c738 1167
599a0ac1 1168 if (!is_pipe && !pipe->writers) {
f776c738 1169 if ((filp->f_flags & O_NONBLOCK)) {
a9a08845 1170 /* suppress EPOLLHUP until we have
f776c738 1171 * seen a writer */
5a957bba 1172 filp->f_pipe = pipe->w_counter;
f776c738 1173 } else {
fc7478a2 1174 if (wait_for_partner(pipe, &pipe->w_counter))
f776c738
AV
1175 goto err_rd;
1176 }
1177 }
1178 break;
8cefc107 1179
f776c738
AV
1180 case FMODE_WRITE:
1181 /*
1182 * O_WRONLY
1183 * POSIX.1 says that O_NONBLOCK means return -1 with
1184 * errno=ENXIO when there is no process reading the FIFO.
1185 */
1186 ret = -ENXIO;
599a0ac1 1187 if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers)
f776c738
AV
1188 goto err;
1189
f776c738
AV
1190 pipe->w_counter++;
1191 if (!pipe->writers++)
fc7478a2 1192 wake_up_partner(pipe);
f776c738 1193
599a0ac1 1194 if (!is_pipe && !pipe->readers) {
fc7478a2 1195 if (wait_for_partner(pipe, &pipe->r_counter))
f776c738
AV
1196 goto err_wr;
1197 }
1198 break;
8cefc107 1199
f776c738
AV
1200 case FMODE_READ | FMODE_WRITE:
1201 /*
1202 * O_RDWR
1203 * POSIX.1 leaves this case "undefined" when O_NONBLOCK is set.
1204 * This implementation will NEVER block on a O_RDWR open, since
1205 * the process can at least talk to itself.
1206 */
f776c738
AV
1207
1208 pipe->readers++;
1209 pipe->writers++;
1210 pipe->r_counter++;
1211 pipe->w_counter++;
1212 if (pipe->readers == 1 || pipe->writers == 1)
fc7478a2 1213 wake_up_partner(pipe);
f776c738
AV
1214 break;
1215
1216 default:
1217 ret = -EINVAL;
1218 goto err;
1219 }
1220
1221 /* Ok! */
85f273a6 1222 mutex_unlock(&pipe->mutex);
f776c738
AV
1223 return 0;
1224
1225err_rd:
1226 if (!--pipe->readers)
0ddad21d 1227 wake_up_interruptible(&pipe->wr_wait);
f776c738
AV
1228 ret = -ERESTARTSYS;
1229 goto err;
1230
1231err_wr:
1232 if (!--pipe->writers)
6551d5c5 1233 wake_up_interruptible_all(&pipe->rd_wait);
f776c738
AV
1234 ret = -ERESTARTSYS;
1235 goto err;
1236
1237err:
85f273a6 1238 mutex_unlock(&pipe->mutex);
b0d8d229
LT
1239
1240 put_pipe_info(inode, pipe);
f776c738
AV
1241 return ret;
1242}
1243
599a0ac1
AV
1244const struct file_operations pipefifo_fops = {
1245 .open = fifo_open,
f017b0a4
ON
1246 .read_iter = fifo_pipe_read,
1247 .write_iter = fifo_pipe_write,
a11e1d43 1248 .poll = pipe_poll,
599a0ac1
AV
1249 .unlocked_ioctl = pipe_ioctl,
1250 .release = pipe_release,
1251 .fasync = pipe_fasync,
f8ad8187 1252 .splice_write = iter_file_splice_write,
f776c738
AV
1253};
1254
262b2fa9
ON
1255static const struct file_operations pipeanon_fops = {
1256 .open = fifo_open,
f017b0a4
ON
1257 .read_iter = anon_pipe_read,
1258 .write_iter = anon_pipe_write,
262b2fa9
ON
1259 .poll = pipe_poll,
1260 .unlocked_ioctl = pipe_ioctl,
1261 .release = pipe_release,
1262 .fasync = pipe_fasync,
1263 .splice_write = iter_file_splice_write,
1264};
1265
f491bd71
MK
1266/*
1267 * Currently we rely on the pipe array holding a power-of-2 number
d3f14c48 1268 * of pages. Returns 0 on error.
f491bd71 1269 */
515c5046 1270unsigned int round_pipe_size(unsigned int size)
f491bd71 1271{
c4fed5a9 1272 if (size > (1U << 31))
96e99be4
EB
1273 return 0;
1274
4c2e4bef
EB
1275 /* Minimum pipe size, as required by POSIX */
1276 if (size < PAGE_SIZE)
c4fed5a9 1277 return PAGE_SIZE;
d3f14c48 1278
c4fed5a9 1279 return roundup_pow_of_two(size);
f491bd71
MK
1280}
1281
35f3d14d 1282/*
c73be61c 1283 * Resize the pipe ring to a number of slots.
189b0ddc
DH
1284 *
1285 * Note the pipe can be reduced in capacity, but only if the current
1286 * occupancy doesn't exceed nr_slots; if it does, EBUSY will be
1287 * returned instead.
35f3d14d 1288 */
c73be61c 1289int pipe_resize_ring(struct pipe_inode_info *pipe, unsigned int nr_slots)
35f3d14d
JA
1290{
1291 struct pipe_buffer *bufs;
c73be61c 1292 unsigned int head, tail, mask, n;
35f3d14d 1293
cf3d0c54
PN
1294 /* nr_slots larger than limits of pipe->{head,tail} */
1295 if (unlikely(nr_slots > (pipe_index_t)-1u))
1296 return -EINVAL;
1297
906f9040
LT
1298 bufs = kcalloc(nr_slots, sizeof(*bufs),
1299 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
c73be61c
DH
1300 if (unlikely(!bufs))
1301 return -ENOMEM;
35f3d14d 1302
189b0ddc
DH
1303 spin_lock_irq(&pipe->rd_wait.lock);
1304 mask = pipe->ring_size - 1;
1305 head = pipe->head;
1306 tail = pipe->tail;
1307
1308 n = pipe_occupancy(head, tail);
1309 if (nr_slots < n) {
1310 spin_unlock_irq(&pipe->rd_wait.lock);
1311 kfree(bufs);
1312 return -EBUSY;
1313 }
1314
35f3d14d
JA
1315 /*
1316 * The pipe array wraps around, so just start the new one at zero
8cefc107 1317 * and adjust the indices.
35f3d14d 1318 */
8cefc107
DH
1319 if (n > 0) {
1320 unsigned int h = head & mask;
1321 unsigned int t = tail & mask;
1322 if (h > t) {
1323 memcpy(bufs, pipe->bufs + t,
1324 n * sizeof(struct pipe_buffer));
1325 } else {
1326 unsigned int tsize = pipe->ring_size - t;
1327 if (h > 0)
1328 memcpy(bufs + tsize, pipe->bufs,
1329 h * sizeof(struct pipe_buffer));
1330 memcpy(bufs, pipe->bufs + t,
1331 tsize * sizeof(struct pipe_buffer));
1332 }
35f3d14d
JA
1333 }
1334
8cefc107
DH
1335 head = n;
1336 tail = 0;
1337
906f9040 1338 kfree(pipe->bufs);
35f3d14d 1339 pipe->bufs = bufs;
8cefc107 1340 pipe->ring_size = nr_slots;
c73be61c
DH
1341 if (pipe->max_usage > nr_slots)
1342 pipe->max_usage = nr_slots;
8cefc107
DH
1343 pipe->tail = tail;
1344 pipe->head = head;
6551d5c5 1345
e95aada4
LS
1346 if (!pipe_has_watch_queue(pipe)) {
1347 pipe->max_usage = nr_slots;
1348 pipe->nr_accounted = nr_slots;
1349 }
1350
189b0ddc
DH
1351 spin_unlock_irq(&pipe->rd_wait.lock);
1352
6551d5c5
LT
1353 /* This might have made more room for writers */
1354 wake_up_interruptible(&pipe->wr_wait);
c73be61c
DH
1355 return 0;
1356}
1357
1358/*
1359 * Allocate a new array of pipe buffers and copy the info over. Returns the
1360 * pipe size if successful, or return -ERROR on error.
1361 */
515c5046 1362static long pipe_set_size(struct pipe_inode_info *pipe, unsigned int arg)
c73be61c
DH
1363{
1364 unsigned long user_bufs;
1365 unsigned int nr_slots, size;
1366 long ret = 0;
1367
b4bd6b4b 1368 if (pipe_has_watch_queue(pipe))
c73be61c 1369 return -EBUSY;
c73be61c
DH
1370
1371 size = round_pipe_size(arg);
1372 nr_slots = size >> PAGE_SHIFT;
1373
1374 if (!nr_slots)
1375 return -EINVAL;
1376
1377 /*
1378 * If trying to increase the pipe capacity, check that an
1379 * unprivileged user is not trying to exceed various limits
1380 * (soft limit check here, hard limit check just below).
1381 * Decreasing the pipe capacity is always permitted, even
1382 * if the user is currently over a limit.
1383 */
1384 if (nr_slots > pipe->max_usage &&
1385 size > pipe_max_size && !capable(CAP_SYS_RESOURCE))
1386 return -EPERM;
1387
1388 user_bufs = account_pipe_buffers(pipe->user, pipe->nr_accounted, nr_slots);
1389
1390 if (nr_slots > pipe->max_usage &&
1391 (too_many_pipe_buffers_hard(user_bufs) ||
1392 too_many_pipe_buffers_soft(user_bufs)) &&
1393 pipe_is_unprivileged_user()) {
1394 ret = -EPERM;
1395 goto out_revert_acct;
1396 }
1397
1398 ret = pipe_resize_ring(pipe, nr_slots);
1399 if (ret < 0)
1400 goto out_revert_acct;
1401
6718b6f8 1402 return pipe->max_usage * PAGE_SIZE;
b0b91d18
MK
1403
1404out_revert_acct:
c73be61c 1405 (void) account_pipe_buffers(pipe->user, nr_slots, pipe->nr_accounted);
b0b91d18 1406 return ret;
35f3d14d
JA
1407}
1408
72083646 1409/*
4e7b5671
CH
1410 * Note that i_pipe and i_cdev share the same location, so checking ->i_pipe is
1411 * not enough to verify that this is a pipe.
72083646 1412 */
c73be61c 1413struct pipe_inode_info *get_pipe_info(struct file *file, bool for_splice)
72083646 1414{
c73be61c
DH
1415 struct pipe_inode_info *pipe = file->private_data;
1416
262b2fa9
ON
1417 if (!pipe)
1418 return NULL;
1419 if (file->f_op != &pipefifo_fops && file->f_op != &pipeanon_fops)
c73be61c 1420 return NULL;
b4bd6b4b 1421 if (for_splice && pipe_has_watch_queue(pipe))
c73be61c 1422 return NULL;
c73be61c 1423 return pipe;
72083646
LT
1424}
1425
515c5046 1426long pipe_fcntl(struct file *file, unsigned int cmd, unsigned int arg)
35f3d14d
JA
1427{
1428 struct pipe_inode_info *pipe;
1429 long ret;
1430
c73be61c 1431 pipe = get_pipe_info(file, false);
35f3d14d
JA
1432 if (!pipe)
1433 return -EBADF;
1434
85f273a6 1435 mutex_lock(&pipe->mutex);
35f3d14d
JA
1436
1437 switch (cmd) {
d37d4166
MK
1438 case F_SETPIPE_SZ:
1439 ret = pipe_set_size(pipe, arg);
35f3d14d
JA
1440 break;
1441 case F_GETPIPE_SZ:
6718b6f8 1442 ret = pipe->max_usage * PAGE_SIZE;
35f3d14d
JA
1443 break;
1444 default:
1445 ret = -EINVAL;
1446 break;
1447 }
1448
85f273a6 1449 mutex_unlock(&pipe->mutex);
35f3d14d
JA
1450 return ret;
1451}
1452
ff0c7d15
NP
1453static const struct super_operations pipefs_ops = {
1454 .destroy_inode = free_inode_nonrcu,
d70ef97b 1455 .statfs = simple_statfs,
ff0c7d15
NP
1456};
1457
1da177e4
LT
1458/*
1459 * pipefs should _never_ be mounted by userland - too much of security hassle,
33d8525d 1460 * no real gain from having the whole file system mounted. So we don't need
1da177e4
LT
1461 * any operations on the root directory. However, we need a non-trivial
1462 * d_name - pipe: will go nicely and kill the special-casing in procfs.
1463 */
4fa7ec5d
DH
1464
1465static int pipefs_init_fs_context(struct fs_context *fc)
1da177e4 1466{
4fa7ec5d
DH
1467 struct pseudo_fs_context *ctx = init_pseudo(fc, PIPEFS_MAGIC);
1468 if (!ctx)
1469 return -ENOMEM;
1470 ctx->ops = &pipefs_ops;
1471 ctx->dops = &pipefs_dentry_operations;
1472 return 0;
1da177e4
LT
1473}
1474
1475static struct file_system_type pipe_fs_type = {
1476 .name = "pipefs",
4fa7ec5d 1477 .init_fs_context = pipefs_init_fs_context,
1da177e4
LT
1478 .kill_sb = kill_anon_super,
1479};
1480
1998f193
LC
1481#ifdef CONFIG_SYSCTL
1482static int do_proc_dopipe_max_size_conv(unsigned long *lvalp,
1483 unsigned int *valp,
1484 int write, void *data)
1485{
1486 if (write) {
1487 unsigned int val;
1488
1489 val = round_pipe_size(*lvalp);
1490 if (val == 0)
1491 return -EINVAL;
1492
1493 *valp = val;
1494 } else {
1495 unsigned int val = *valp;
1496 *lvalp = (unsigned long) val;
1497 }
1498
1499 return 0;
1500}
1501
78eb4ea2 1502static int proc_dopipe_max_size(const struct ctl_table *table, int write,
1998f193
LC
1503 void *buffer, size_t *lenp, loff_t *ppos)
1504{
1505 return do_proc_douintvec(table, write, buffer, lenp, ppos,
1506 do_proc_dopipe_max_size_conv, NULL);
1507}
1508
1751f872 1509static const struct ctl_table fs_pipe_sysctls[] = {
1998f193
LC
1510 {
1511 .procname = "pipe-max-size",
1512 .data = &pipe_max_size,
1513 .maxlen = sizeof(pipe_max_size),
1514 .mode = 0644,
1515 .proc_handler = proc_dopipe_max_size,
1516 },
1517 {
1518 .procname = "pipe-user-pages-hard",
1519 .data = &pipe_user_pages_hard,
1520 .maxlen = sizeof(pipe_user_pages_hard),
1521 .mode = 0644,
1522 .proc_handler = proc_doulongvec_minmax,
1523 },
1524 {
1525 .procname = "pipe-user-pages-soft",
1526 .data = &pipe_user_pages_soft,
1527 .maxlen = sizeof(pipe_user_pages_soft),
1528 .mode = 0644,
1529 .proc_handler = proc_doulongvec_minmax,
1530 },
1998f193
LC
1531};
1532#endif
1533
1da177e4
LT
1534static int __init init_pipe_fs(void)
1535{
1536 int err = register_filesystem(&pipe_fs_type);
341b446b 1537
1da177e4
LT
1538 if (!err) {
1539 pipe_mnt = kern_mount(&pipe_fs_type);
1540 if (IS_ERR(pipe_mnt)) {
1541 err = PTR_ERR(pipe_mnt);
1542 unregister_filesystem(&pipe_fs_type);
1543 }
1544 }
1998f193
LC
1545#ifdef CONFIG_SYSCTL
1546 register_sysctl_init("fs", fs_pipe_sysctls);
1547#endif
1da177e4
LT
1548 return err;
1549}
1550
1da177e4 1551fs_initcall(init_pipe_fs);