Merge tag 'io_uring-6.16-20250630' of git://git.kernel.dk/linux
[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]);
2a42754b
AG
966 /*
967 * Disable permission and pre-content events, but enable legacy
968 * inotify events for legacy users.
969 */
970 file_set_fsnotify_mode(res[0], FMODE_NONOTIFY_PERM);
971 file_set_fsnotify_mode(res[1], FMODE_NONOTIFY_PERM);
e4fad8e5 972 return 0;
d6cbd281
AK
973}
974
5b249b1b 975static int __do_pipe_flags(int *fd, struct file **files, int flags)
d6cbd281 976{
d6cbd281
AK
977 int error;
978 int fdw, fdr;
979
c73be61c 980 if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT | O_NOTIFICATION_PIPE))
ed8cae8b
UD
981 return -EINVAL;
982
e4fad8e5
AV
983 error = create_pipe_files(files, flags);
984 if (error)
985 return error;
d6cbd281 986
ed8cae8b 987 error = get_unused_fd_flags(flags);
d6cbd281
AK
988 if (error < 0)
989 goto err_read_pipe;
990 fdr = error;
991
ed8cae8b 992 error = get_unused_fd_flags(flags);
d6cbd281
AK
993 if (error < 0)
994 goto err_fdr;
995 fdw = error;
996
157cf649 997 audit_fd_pair(fdr, fdw);
d6cbd281
AK
998 fd[0] = fdr;
999 fd[1] = fdw;
afed6271
JA
1000 /* pipe groks IOCB_NOWAIT */
1001 files[0]->f_mode |= FMODE_NOWAIT;
1002 files[1]->f_mode |= FMODE_NOWAIT;
d6cbd281
AK
1003 return 0;
1004
1005 err_fdr:
1006 put_unused_fd(fdr);
1007 err_read_pipe:
e4fad8e5
AV
1008 fput(files[0]);
1009 fput(files[1]);
d6cbd281 1010 return error;
1da177e4
LT
1011}
1012
5b249b1b
AV
1013int do_pipe_flags(int *fd, int flags)
1014{
1015 struct file *files[2];
1016 int error = __do_pipe_flags(fd, files, flags);
1017 if (!error) {
1018 fd_install(fd[0], files[0]);
1019 fd_install(fd[1], files[1]);
1020 }
1021 return error;
1022}
1023
d35c7b0e
UD
1024/*
1025 * sys_pipe() is the normal C calling standard for creating
1026 * a pipe. It's not the way Unix traditionally does this, though.
1027 */
0a216dd1 1028static int do_pipe2(int __user *fildes, int flags)
d35c7b0e 1029{
5b249b1b 1030 struct file *files[2];
d35c7b0e
UD
1031 int fd[2];
1032 int error;
1033
5b249b1b 1034 error = __do_pipe_flags(fd, files, flags);
d35c7b0e 1035 if (!error) {
5b249b1b
AV
1036 if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) {
1037 fput(files[0]);
1038 fput(files[1]);
1039 put_unused_fd(fd[0]);
1040 put_unused_fd(fd[1]);
d35c7b0e 1041 error = -EFAULT;
5b249b1b
AV
1042 } else {
1043 fd_install(fd[0], files[0]);
1044 fd_install(fd[1], files[1]);
ba719bae 1045 }
d35c7b0e
UD
1046 }
1047 return error;
1048}
1049
0a216dd1
DB
1050SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)
1051{
1052 return do_pipe2(fildes, flags);
1053}
1054
2b664219 1055SYSCALL_DEFINE1(pipe, int __user *, fildes)
ed8cae8b 1056{
0a216dd1 1057 return do_pipe2(fildes, 0);
ed8cae8b
UD
1058}
1059
472e5b05
LT
1060/*
1061 * This is the stupid "wait for pipe to be readable or writable"
1062 * model.
1063 *
1064 * See pipe_read/write() for the proper kind of exclusive wait,
1065 * but that requires that we wake up any other readers/writers
1066 * if we then do not end up reading everything (ie the whole
1067 * "wake_next_reader/writer" logic in pipe_read/write()).
1068 */
1069void pipe_wait_readable(struct pipe_inode_info *pipe)
1070{
1071 pipe_unlock(pipe);
1072 wait_event_interruptible(pipe->rd_wait, pipe_readable(pipe));
1073 pipe_lock(pipe);
1074}
1075
1076void pipe_wait_writable(struct pipe_inode_info *pipe)
1077{
1078 pipe_unlock(pipe);
1079 wait_event_interruptible(pipe->wr_wait, pipe_writable(pipe));
1080 pipe_lock(pipe);
1081}
1082
1083/*
1084 * This depends on both the wait (here) and the wakeup (wake_up_partner)
1085 * holding the pipe lock, so "*cnt" is stable and we know a wakeup cannot
1086 * race with the count check and waitqueue prep.
1087 *
1088 * Normally in order to avoid races, you'd do the prepare_to_wait() first,
1089 * then check the condition you're waiting for, and only then sleep. But
1090 * because of the pipe lock, we can check the condition before being on
1091 * the wait queue.
1092 *
1093 * We use the 'rd_wait' waitqueue for pipe partner waiting.
1094 */
fc7478a2 1095static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt)
f776c738 1096{
472e5b05 1097 DEFINE_WAIT(rdwait);
8cefc107 1098 int cur = *cnt;
f776c738
AV
1099
1100 while (cur == *cnt) {
472e5b05
LT
1101 prepare_to_wait(&pipe->rd_wait, &rdwait, TASK_INTERRUPTIBLE);
1102 pipe_unlock(pipe);
1103 schedule();
1104 finish_wait(&pipe->rd_wait, &rdwait);
1105 pipe_lock(pipe);
f776c738
AV
1106 if (signal_pending(current))
1107 break;
1108 }
1109 return cur == *cnt ? -ERESTARTSYS : 0;
1110}
1111
fc7478a2 1112static void wake_up_partner(struct pipe_inode_info *pipe)
f776c738 1113{
6551d5c5 1114 wake_up_interruptible_all(&pipe->rd_wait);
f776c738
AV
1115}
1116
1117static int fifo_open(struct inode *inode, struct file *filp)
1118{
262b2fa9 1119 bool is_pipe = inode->i_fop == &pipeanon_fops;
f776c738
AV
1120 struct pipe_inode_info *pipe;
1121 int ret;
1122
5a957bba 1123 filp->f_pipe = 0;
ba5bb147
AV
1124
1125 spin_lock(&inode->i_lock);
1126 if (inode->i_pipe) {
1127 pipe = inode->i_pipe;
1128 pipe->files++;
1129 spin_unlock(&inode->i_lock);
1130 } else {
1131 spin_unlock(&inode->i_lock);
7bee130e 1132 pipe = alloc_pipe_info();
f776c738 1133 if (!pipe)
ba5bb147
AV
1134 return -ENOMEM;
1135 pipe->files = 1;
1136 spin_lock(&inode->i_lock);
1137 if (unlikely(inode->i_pipe)) {
1138 inode->i_pipe->files++;
1139 spin_unlock(&inode->i_lock);
4b8a8f1e 1140 free_pipe_info(pipe);
ba5bb147
AV
1141 pipe = inode->i_pipe;
1142 } else {
1143 inode->i_pipe = pipe;
1144 spin_unlock(&inode->i_lock);
1145 }
f776c738 1146 }
de32ec4c 1147 filp->private_data = pipe;
ba5bb147
AV
1148 /* OK, we have a pipe and it's pinned down */
1149
85f273a6 1150 mutex_lock(&pipe->mutex);
f776c738
AV
1151
1152 /* We can only do regular read/write on fifos */
d8e464ec 1153 stream_open(inode, filp);
f776c738 1154
d8e464ec 1155 switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) {
f776c738
AV
1156 case FMODE_READ:
1157 /*
1158 * O_RDONLY
1159 * POSIX.1 says that O_NONBLOCK means return with the FIFO
1160 * opened, even when there is no process writing the FIFO.
1161 */
f776c738
AV
1162 pipe->r_counter++;
1163 if (pipe->readers++ == 0)
fc7478a2 1164 wake_up_partner(pipe);
f776c738 1165
599a0ac1 1166 if (!is_pipe && !pipe->writers) {
f776c738 1167 if ((filp->f_flags & O_NONBLOCK)) {
a9a08845 1168 /* suppress EPOLLHUP until we have
f776c738 1169 * seen a writer */
5a957bba 1170 filp->f_pipe = pipe->w_counter;
f776c738 1171 } else {
fc7478a2 1172 if (wait_for_partner(pipe, &pipe->w_counter))
f776c738
AV
1173 goto err_rd;
1174 }
1175 }
1176 break;
8cefc107 1177
f776c738
AV
1178 case FMODE_WRITE:
1179 /*
1180 * O_WRONLY
1181 * POSIX.1 says that O_NONBLOCK means return -1 with
1182 * errno=ENXIO when there is no process reading the FIFO.
1183 */
1184 ret = -ENXIO;
599a0ac1 1185 if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers)
f776c738
AV
1186 goto err;
1187
f776c738
AV
1188 pipe->w_counter++;
1189 if (!pipe->writers++)
fc7478a2 1190 wake_up_partner(pipe);
f776c738 1191
599a0ac1 1192 if (!is_pipe && !pipe->readers) {
fc7478a2 1193 if (wait_for_partner(pipe, &pipe->r_counter))
f776c738
AV
1194 goto err_wr;
1195 }
1196 break;
8cefc107 1197
f776c738
AV
1198 case FMODE_READ | FMODE_WRITE:
1199 /*
1200 * O_RDWR
1201 * POSIX.1 leaves this case "undefined" when O_NONBLOCK is set.
1202 * This implementation will NEVER block on a O_RDWR open, since
1203 * the process can at least talk to itself.
1204 */
f776c738
AV
1205
1206 pipe->readers++;
1207 pipe->writers++;
1208 pipe->r_counter++;
1209 pipe->w_counter++;
1210 if (pipe->readers == 1 || pipe->writers == 1)
fc7478a2 1211 wake_up_partner(pipe);
f776c738
AV
1212 break;
1213
1214 default:
1215 ret = -EINVAL;
1216 goto err;
1217 }
1218
1219 /* Ok! */
85f273a6 1220 mutex_unlock(&pipe->mutex);
f776c738
AV
1221 return 0;
1222
1223err_rd:
1224 if (!--pipe->readers)
0ddad21d 1225 wake_up_interruptible(&pipe->wr_wait);
f776c738
AV
1226 ret = -ERESTARTSYS;
1227 goto err;
1228
1229err_wr:
1230 if (!--pipe->writers)
6551d5c5 1231 wake_up_interruptible_all(&pipe->rd_wait);
f776c738
AV
1232 ret = -ERESTARTSYS;
1233 goto err;
1234
1235err:
85f273a6 1236 mutex_unlock(&pipe->mutex);
b0d8d229
LT
1237
1238 put_pipe_info(inode, pipe);
f776c738
AV
1239 return ret;
1240}
1241
599a0ac1
AV
1242const struct file_operations pipefifo_fops = {
1243 .open = fifo_open,
f017b0a4
ON
1244 .read_iter = fifo_pipe_read,
1245 .write_iter = fifo_pipe_write,
a11e1d43 1246 .poll = pipe_poll,
599a0ac1
AV
1247 .unlocked_ioctl = pipe_ioctl,
1248 .release = pipe_release,
1249 .fasync = pipe_fasync,
f8ad8187 1250 .splice_write = iter_file_splice_write,
f776c738
AV
1251};
1252
262b2fa9
ON
1253static const struct file_operations pipeanon_fops = {
1254 .open = fifo_open,
f017b0a4
ON
1255 .read_iter = anon_pipe_read,
1256 .write_iter = anon_pipe_write,
262b2fa9
ON
1257 .poll = pipe_poll,
1258 .unlocked_ioctl = pipe_ioctl,
1259 .release = pipe_release,
1260 .fasync = pipe_fasync,
1261 .splice_write = iter_file_splice_write,
1262};
1263
f491bd71
MK
1264/*
1265 * Currently we rely on the pipe array holding a power-of-2 number
d3f14c48 1266 * of pages. Returns 0 on error.
f491bd71 1267 */
515c5046 1268unsigned int round_pipe_size(unsigned int size)
f491bd71 1269{
c4fed5a9 1270 if (size > (1U << 31))
96e99be4
EB
1271 return 0;
1272
4c2e4bef
EB
1273 /* Minimum pipe size, as required by POSIX */
1274 if (size < PAGE_SIZE)
c4fed5a9 1275 return PAGE_SIZE;
d3f14c48 1276
c4fed5a9 1277 return roundup_pow_of_two(size);
f491bd71
MK
1278}
1279
35f3d14d 1280/*
c73be61c 1281 * Resize the pipe ring to a number of slots.
189b0ddc
DH
1282 *
1283 * Note the pipe can be reduced in capacity, but only if the current
1284 * occupancy doesn't exceed nr_slots; if it does, EBUSY will be
1285 * returned instead.
35f3d14d 1286 */
c73be61c 1287int pipe_resize_ring(struct pipe_inode_info *pipe, unsigned int nr_slots)
35f3d14d
JA
1288{
1289 struct pipe_buffer *bufs;
c73be61c 1290 unsigned int head, tail, mask, n;
35f3d14d 1291
cf3d0c54
PN
1292 /* nr_slots larger than limits of pipe->{head,tail} */
1293 if (unlikely(nr_slots > (pipe_index_t)-1u))
1294 return -EINVAL;
1295
906f9040
LT
1296 bufs = kcalloc(nr_slots, sizeof(*bufs),
1297 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
c73be61c
DH
1298 if (unlikely(!bufs))
1299 return -ENOMEM;
35f3d14d 1300
189b0ddc
DH
1301 spin_lock_irq(&pipe->rd_wait.lock);
1302 mask = pipe->ring_size - 1;
1303 head = pipe->head;
1304 tail = pipe->tail;
1305
1306 n = pipe_occupancy(head, tail);
1307 if (nr_slots < n) {
1308 spin_unlock_irq(&pipe->rd_wait.lock);
1309 kfree(bufs);
1310 return -EBUSY;
1311 }
1312
35f3d14d
JA
1313 /*
1314 * The pipe array wraps around, so just start the new one at zero
8cefc107 1315 * and adjust the indices.
35f3d14d 1316 */
8cefc107
DH
1317 if (n > 0) {
1318 unsigned int h = head & mask;
1319 unsigned int t = tail & mask;
1320 if (h > t) {
1321 memcpy(bufs, pipe->bufs + t,
1322 n * sizeof(struct pipe_buffer));
1323 } else {
1324 unsigned int tsize = pipe->ring_size - t;
1325 if (h > 0)
1326 memcpy(bufs + tsize, pipe->bufs,
1327 h * sizeof(struct pipe_buffer));
1328 memcpy(bufs, pipe->bufs + t,
1329 tsize * sizeof(struct pipe_buffer));
1330 }
35f3d14d
JA
1331 }
1332
8cefc107
DH
1333 head = n;
1334 tail = 0;
1335
906f9040 1336 kfree(pipe->bufs);
35f3d14d 1337 pipe->bufs = bufs;
8cefc107 1338 pipe->ring_size = nr_slots;
c73be61c
DH
1339 if (pipe->max_usage > nr_slots)
1340 pipe->max_usage = nr_slots;
8cefc107
DH
1341 pipe->tail = tail;
1342 pipe->head = head;
6551d5c5 1343
e95aada4
LS
1344 if (!pipe_has_watch_queue(pipe)) {
1345 pipe->max_usage = nr_slots;
1346 pipe->nr_accounted = nr_slots;
1347 }
1348
189b0ddc
DH
1349 spin_unlock_irq(&pipe->rd_wait.lock);
1350
6551d5c5
LT
1351 /* This might have made more room for writers */
1352 wake_up_interruptible(&pipe->wr_wait);
c73be61c
DH
1353 return 0;
1354}
1355
1356/*
1357 * Allocate a new array of pipe buffers and copy the info over. Returns the
1358 * pipe size if successful, or return -ERROR on error.
1359 */
515c5046 1360static long pipe_set_size(struct pipe_inode_info *pipe, unsigned int arg)
c73be61c
DH
1361{
1362 unsigned long user_bufs;
1363 unsigned int nr_slots, size;
1364 long ret = 0;
1365
b4bd6b4b 1366 if (pipe_has_watch_queue(pipe))
c73be61c 1367 return -EBUSY;
c73be61c
DH
1368
1369 size = round_pipe_size(arg);
1370 nr_slots = size >> PAGE_SHIFT;
1371
1372 if (!nr_slots)
1373 return -EINVAL;
1374
1375 /*
1376 * If trying to increase the pipe capacity, check that an
1377 * unprivileged user is not trying to exceed various limits
1378 * (soft limit check here, hard limit check just below).
1379 * Decreasing the pipe capacity is always permitted, even
1380 * if the user is currently over a limit.
1381 */
1382 if (nr_slots > pipe->max_usage &&
1383 size > pipe_max_size && !capable(CAP_SYS_RESOURCE))
1384 return -EPERM;
1385
1386 user_bufs = account_pipe_buffers(pipe->user, pipe->nr_accounted, nr_slots);
1387
1388 if (nr_slots > pipe->max_usage &&
1389 (too_many_pipe_buffers_hard(user_bufs) ||
1390 too_many_pipe_buffers_soft(user_bufs)) &&
1391 pipe_is_unprivileged_user()) {
1392 ret = -EPERM;
1393 goto out_revert_acct;
1394 }
1395
1396 ret = pipe_resize_ring(pipe, nr_slots);
1397 if (ret < 0)
1398 goto out_revert_acct;
1399
6718b6f8 1400 return pipe->max_usage * PAGE_SIZE;
b0b91d18
MK
1401
1402out_revert_acct:
c73be61c 1403 (void) account_pipe_buffers(pipe->user, nr_slots, pipe->nr_accounted);
b0b91d18 1404 return ret;
35f3d14d
JA
1405}
1406
72083646 1407/*
4e7b5671
CH
1408 * Note that i_pipe and i_cdev share the same location, so checking ->i_pipe is
1409 * not enough to verify that this is a pipe.
72083646 1410 */
c73be61c 1411struct pipe_inode_info *get_pipe_info(struct file *file, bool for_splice)
72083646 1412{
c73be61c
DH
1413 struct pipe_inode_info *pipe = file->private_data;
1414
262b2fa9
ON
1415 if (!pipe)
1416 return NULL;
1417 if (file->f_op != &pipefifo_fops && file->f_op != &pipeanon_fops)
c73be61c 1418 return NULL;
b4bd6b4b 1419 if (for_splice && pipe_has_watch_queue(pipe))
c73be61c 1420 return NULL;
c73be61c 1421 return pipe;
72083646
LT
1422}
1423
515c5046 1424long pipe_fcntl(struct file *file, unsigned int cmd, unsigned int arg)
35f3d14d
JA
1425{
1426 struct pipe_inode_info *pipe;
1427 long ret;
1428
c73be61c 1429 pipe = get_pipe_info(file, false);
35f3d14d
JA
1430 if (!pipe)
1431 return -EBADF;
1432
85f273a6 1433 mutex_lock(&pipe->mutex);
35f3d14d
JA
1434
1435 switch (cmd) {
d37d4166
MK
1436 case F_SETPIPE_SZ:
1437 ret = pipe_set_size(pipe, arg);
35f3d14d
JA
1438 break;
1439 case F_GETPIPE_SZ:
6718b6f8 1440 ret = pipe->max_usage * PAGE_SIZE;
35f3d14d
JA
1441 break;
1442 default:
1443 ret = -EINVAL;
1444 break;
1445 }
1446
85f273a6 1447 mutex_unlock(&pipe->mutex);
35f3d14d
JA
1448 return ret;
1449}
1450
ff0c7d15
NP
1451static const struct super_operations pipefs_ops = {
1452 .destroy_inode = free_inode_nonrcu,
d70ef97b 1453 .statfs = simple_statfs,
ff0c7d15
NP
1454};
1455
1da177e4
LT
1456/*
1457 * pipefs should _never_ be mounted by userland - too much of security hassle,
33d8525d 1458 * no real gain from having the whole file system mounted. So we don't need
1da177e4
LT
1459 * any operations on the root directory. However, we need a non-trivial
1460 * d_name - pipe: will go nicely and kill the special-casing in procfs.
1461 */
4fa7ec5d
DH
1462
1463static int pipefs_init_fs_context(struct fs_context *fc)
1da177e4 1464{
4fa7ec5d
DH
1465 struct pseudo_fs_context *ctx = init_pseudo(fc, PIPEFS_MAGIC);
1466 if (!ctx)
1467 return -ENOMEM;
1468 ctx->ops = &pipefs_ops;
1469 ctx->dops = &pipefs_dentry_operations;
1470 return 0;
1da177e4
LT
1471}
1472
1473static struct file_system_type pipe_fs_type = {
1474 .name = "pipefs",
4fa7ec5d 1475 .init_fs_context = pipefs_init_fs_context,
1da177e4
LT
1476 .kill_sb = kill_anon_super,
1477};
1478
1998f193
LC
1479#ifdef CONFIG_SYSCTL
1480static int do_proc_dopipe_max_size_conv(unsigned long *lvalp,
1481 unsigned int *valp,
1482 int write, void *data)
1483{
1484 if (write) {
1485 unsigned int val;
1486
1487 val = round_pipe_size(*lvalp);
1488 if (val == 0)
1489 return -EINVAL;
1490
1491 *valp = val;
1492 } else {
1493 unsigned int val = *valp;
1494 *lvalp = (unsigned long) val;
1495 }
1496
1497 return 0;
1498}
1499
78eb4ea2 1500static int proc_dopipe_max_size(const struct ctl_table *table, int write,
1998f193
LC
1501 void *buffer, size_t *lenp, loff_t *ppos)
1502{
1503 return do_proc_douintvec(table, write, buffer, lenp, ppos,
1504 do_proc_dopipe_max_size_conv, NULL);
1505}
1506
1751f872 1507static const struct ctl_table fs_pipe_sysctls[] = {
1998f193
LC
1508 {
1509 .procname = "pipe-max-size",
1510 .data = &pipe_max_size,
1511 .maxlen = sizeof(pipe_max_size),
1512 .mode = 0644,
1513 .proc_handler = proc_dopipe_max_size,
1514 },
1515 {
1516 .procname = "pipe-user-pages-hard",
1517 .data = &pipe_user_pages_hard,
1518 .maxlen = sizeof(pipe_user_pages_hard),
1519 .mode = 0644,
1520 .proc_handler = proc_doulongvec_minmax,
1521 },
1522 {
1523 .procname = "pipe-user-pages-soft",
1524 .data = &pipe_user_pages_soft,
1525 .maxlen = sizeof(pipe_user_pages_soft),
1526 .mode = 0644,
1527 .proc_handler = proc_doulongvec_minmax,
1528 },
1998f193
LC
1529};
1530#endif
1531
1da177e4
LT
1532static int __init init_pipe_fs(void)
1533{
1534 int err = register_filesystem(&pipe_fs_type);
341b446b 1535
1da177e4
LT
1536 if (!err) {
1537 pipe_mnt = kern_mount(&pipe_fs_type);
1538 if (IS_ERR(pipe_mnt)) {
1539 err = PTR_ERR(pipe_mnt);
1540 unregister_filesystem(&pipe_fs_type);
1541 }
1542 }
1998f193
LC
1543#ifdef CONFIG_SYSCTL
1544 register_sysctl_init("fs", fs_pipe_sysctls);
1545#endif
1da177e4
LT
1546 return err;
1547}
1548
1da177e4 1549fs_initcall(init_pipe_fs);