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