xref: /linux/fs/pipe.c (revision 7d4e49a77d9930c69751b9192448fda6ff9100f1)
1 // SPDX-License-Identifier: GPL-2.0
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>
15 #include <linux/log2.h>
16 #include <linux/mount.h>
17 #include <linux/pseudo_fs.h>
18 #include <linux/magic.h>
19 #include <linux/pipe_fs_i.h>
20 #include <linux/uio.h>
21 #include <linux/highmem.h>
22 #include <linux/pagemap.h>
23 #include <linux/audit.h>
24 #include <linux/syscalls.h>
25 #include <linux/fcntl.h>
26 #include <linux/memcontrol.h>
27 #include <linux/watch_queue.h>
28 #include <linux/sysctl.h>
29 #include <linux/sort.h>
30 
31 #include <linux/uaccess.h>
32 #include <asm/ioctls.h>
33 
34 #include "internal.h"
35 
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 
51 /*
52  * The max size that a non-root user is allowed to grow the pipe. Can
53  * be set by root in /proc/sys/fs/pipe-max-size
54  */
55 static unsigned int pipe_max_size = 1048576;
56 
57 /* Maximum allocatable pages per user. Hard limit is unset by default, soft
58  * matches default values.
59  */
60 static unsigned long pipe_user_pages_hard;
61 static unsigned long pipe_user_pages_soft = PIPE_DEF_BUFFERS * INR_OPEN_CUR;
62 
63 /*
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  *
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 
80 #ifdef CONFIG_PROVE_LOCKING
pipe_lock_cmp_fn(const struct lockdep_map * a,const struct lockdep_map * b)81 static int pipe_lock_cmp_fn(const struct lockdep_map *a,
82 			    const struct lockdep_map *b)
83 {
84 	return cmp_int((unsigned long) a, (unsigned long) b);
85 }
86 #endif
87 
pipe_lock(struct pipe_inode_info * pipe)88 void pipe_lock(struct pipe_inode_info *pipe)
89 {
90 	if (pipe->files)
91 		mutex_lock(&pipe->mutex);
92 }
93 EXPORT_SYMBOL(pipe_lock);
94 
pipe_unlock(struct pipe_inode_info * pipe)95 void pipe_unlock(struct pipe_inode_info *pipe)
96 {
97 	if (pipe->files)
98 		mutex_unlock(&pipe->mutex);
99 }
100 EXPORT_SYMBOL(pipe_unlock);
101 
pipe_double_lock(struct pipe_inode_info * pipe1,struct pipe_inode_info * pipe2)102 void pipe_double_lock(struct pipe_inode_info *pipe1,
103 		      struct pipe_inode_info *pipe2)
104 {
105 	BUG_ON(pipe1 == pipe2);
106 
107 	if (pipe1 > pipe2)
108 		swap(pipe1, pipe2);
109 
110 	pipe_lock(pipe1);
111 	pipe_lock(pipe2);
112 }
113 
anon_pipe_get_page(struct pipe_inode_info * pipe)114 static 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 
anon_pipe_put_page(struct pipe_inode_info * pipe,struct page * page)127 static 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 
anon_pipe_buf_release(struct pipe_inode_info * pipe,struct pipe_buffer * buf)142 static void anon_pipe_buf_release(struct pipe_inode_info *pipe,
143 				  struct pipe_buffer *buf)
144 {
145 	struct page *page = buf->page;
146 
147 	anon_pipe_put_page(pipe, page);
148 }
149 
anon_pipe_buf_try_steal(struct pipe_inode_info * pipe,struct pipe_buffer * buf)150 static bool anon_pipe_buf_try_steal(struct pipe_inode_info *pipe,
151 		struct pipe_buffer *buf)
152 {
153 	struct page *page = buf->page;
154 
155 	if (page_count(page) != 1)
156 		return false;
157 	memcg_kmem_uncharge_page(page, 0);
158 	__SetPageLocked(page);
159 	return true;
160 }
161 
162 /**
163  * generic_pipe_buf_try_steal - attempt to take ownership of a &pipe_buffer
164  * @pipe:	the pipe that the buffer belongs to
165  * @buf:	the buffer to attempt to steal
166  *
167  * Description:
168  *	This function attempts to steal the &struct page attached to
169  *	@buf. If successful, this function returns 0 and returns with
170  *	the page locked. The caller may then reuse the page for whatever
171  *	he wishes; the typical use is insertion into a different file
172  *	page cache.
173  */
generic_pipe_buf_try_steal(struct pipe_inode_info * pipe,struct pipe_buffer * buf)174 bool generic_pipe_buf_try_steal(struct pipe_inode_info *pipe,
175 		struct pipe_buffer *buf)
176 {
177 	struct page *page = buf->page;
178 
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 	 */
184 	if (page_count(page) == 1) {
185 		lock_page(page);
186 		return true;
187 	}
188 	return false;
189 }
190 EXPORT_SYMBOL(generic_pipe_buf_try_steal);
191 
192 /**
193  * generic_pipe_buf_get - get a reference to a &struct pipe_buffer
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
199  *	the tee() system call, when we duplicate the buffers in one
200  *	pipe into another.
201  */
generic_pipe_buf_get(struct pipe_inode_info * pipe,struct pipe_buffer * buf)202 bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
203 {
204 	return try_get_page(buf->page);
205 }
206 EXPORT_SYMBOL(generic_pipe_buf_get);
207 
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  */
generic_pipe_buf_release(struct pipe_inode_info * pipe,struct pipe_buffer * buf)216 void generic_pipe_buf_release(struct pipe_inode_info *pipe,
217 			      struct pipe_buffer *buf)
218 {
219 	put_page(buf->page);
220 }
221 EXPORT_SYMBOL(generic_pipe_buf_release);
222 
223 static const struct pipe_buf_operations anon_pipe_buf_ops = {
224 	.release	= anon_pipe_buf_release,
225 	.try_steal	= anon_pipe_buf_try_steal,
226 	.get		= generic_pipe_buf_get,
227 };
228 
229 /* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
pipe_readable(const struct pipe_inode_info * pipe)230 static inline bool pipe_readable(const struct pipe_inode_info *pipe)
231 {
232 	union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
233 	unsigned int writers = READ_ONCE(pipe->writers);
234 
235 	return !pipe_empty(idx.head, idx.tail) || !writers;
236 }
237 
pipe_update_tail(struct pipe_inode_info * pipe,struct pipe_buffer * buf,unsigned int tail)238 static 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 
268 static ssize_t
anon_pipe_read(struct kiocb * iocb,struct iov_iter * to)269 anon_pipe_read(struct kiocb *iocb, struct iov_iter *to)
270 {
271 	size_t total_len = iov_iter_count(to);
272 	struct file *filp = iocb->ki_filp;
273 	struct pipe_inode_info *pipe = filp->private_data;
274 	bool wake_writer = false, wake_next_reader = false;
275 	ssize_t ret;
276 
277 	/* Null read succeeds. */
278 	if (unlikely(total_len == 0))
279 		return 0;
280 
281 	ret = 0;
282 	mutex_lock(&pipe->mutex);
283 
284 	/*
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.
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 	 */
292 	for (;;) {
293 		/* Read ->head with a barrier vs post_one_notification() */
294 		unsigned int head = smp_load_acquire(&pipe->head);
295 		unsigned int tail = pipe->tail;
296 
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 
321 		if (!pipe_empty(head, tail)) {
322 			struct pipe_buffer *buf = pipe_buf(pipe, tail);
323 			size_t chars = buf->len;
324 			size_t written;
325 			int error;
326 
327 			if (chars > total_len) {
328 				if (buf->flags & PIPE_BUF_FLAG_WHOLE) {
329 					if (ret == 0)
330 						ret = -ENOBUFS;
331 					break;
332 				}
333 				chars = total_len;
334 			}
335 
336 			error = pipe_buf_confirm(pipe, buf);
337 			if (error) {
338 				if (!ret)
339 					ret = error;
340 				break;
341 			}
342 
343 			written = copy_page_to_iter(buf->page, buf->offset, chars, to);
344 			if (unlikely(written < chars)) {
345 				if (!ret)
346 					ret = -EFAULT;
347 				break;
348 			}
349 			ret += chars;
350 			buf->offset += chars;
351 			buf->len -= chars;
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 
359 			if (!buf->len) {
360 				wake_writer |= pipe_full(head, tail, pipe->max_usage);
361 				tail = pipe_update_tail(pipe, buf, tail);
362 			}
363 			total_len -= chars;
364 			if (!total_len)
365 				break;	/* common path: read succeeded */
366 			if (!pipe_empty(head, tail))	/* More to do? */
367 				continue;
368 		}
369 
370 		if (!pipe->writers)
371 			break;
372 		if (ret)
373 			break;
374 		if ((filp->f_flags & O_NONBLOCK) ||
375 		    (iocb->ki_flags & IOCB_NOWAIT)) {
376 			ret = -EAGAIN;
377 			break;
378 		}
379 		mutex_unlock(&pipe->mutex);
380 		/*
381 		 * We only get here if we didn't actually read anything.
382 		 *
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 		 */
388 		if (wait_event_interruptible_exclusive(pipe->rd_wait, pipe_readable(pipe)) < 0)
389 			return -ERESTARTSYS;
390 
391 		wake_next_reader = true;
392 		mutex_lock(&pipe->mutex);
393 	}
394 	if (pipe_is_empty(pipe))
395 		wake_next_reader = false;
396 	mutex_unlock(&pipe->mutex);
397 
398 	if (wake_writer)
399 		wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
400 	if (wake_next_reader)
401 		wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
402 	kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
403 	return ret;
404 }
405 
406 static ssize_t
fifo_pipe_read(struct kiocb * iocb,struct iov_iter * to)407 fifo_pipe_read(struct kiocb *iocb, struct iov_iter *to)
408 {
409 	int ret = anon_pipe_read(iocb, to);
410 	if (ret > 0)
411 		file_accessed(iocb->ki_filp);
412 	return ret;
413 }
414 
is_packetized(struct file * file)415 static inline int is_packetized(struct file *file)
416 {
417 	return (file->f_flags & O_DIRECT) != 0;
418 }
419 
420 /* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
pipe_writable(const struct pipe_inode_info * pipe)421 static inline bool pipe_writable(const struct pipe_inode_info *pipe)
422 {
423 	union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
424 	unsigned int max_usage = READ_ONCE(pipe->max_usage);
425 
426 	return !pipe_full(idx.head, idx.tail, max_usage) ||
427 		!READ_ONCE(pipe->readers);
428 }
429 
430 static ssize_t
anon_pipe_write(struct kiocb * iocb,struct iov_iter * from)431 anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)
432 {
433 	struct file *filp = iocb->ki_filp;
434 	struct pipe_inode_info *pipe = filp->private_data;
435 	unsigned int head;
436 	ssize_t ret = 0;
437 	size_t total_len = iov_iter_count(from);
438 	ssize_t chars;
439 	bool was_empty = false;
440 	bool wake_next_writer = false;
441 
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 
454 	/* Null write succeeds. */
455 	if (unlikely(total_len == 0))
456 		return 0;
457 
458 	mutex_lock(&pipe->mutex);
459 
460 	if (!pipe->readers) {
461 		send_sig(SIGPIPE, current, 0);
462 		ret = -EPIPE;
463 		goto out;
464 	}
465 
466 	/*
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
471 	 * page-aligns the rest of the writes for large writes
472 	 * spanning multiple pages.
473 	 */
474 	head = pipe->head;
475 	was_empty = pipe_empty(head, pipe->tail);
476 	chars = total_len & (PAGE_SIZE-1);
477 	if (chars && !was_empty) {
478 		struct pipe_buffer *buf = pipe_buf(pipe, head - 1);
479 		int offset = buf->offset + buf->len;
480 
481 		if ((buf->flags & PIPE_BUF_FLAG_CAN_MERGE) &&
482 		    offset + chars <= PAGE_SIZE) {
483 			ret = pipe_buf_confirm(pipe, buf);
484 			if (ret)
485 				goto out;
486 
487 			ret = copy_page_from_iter(buf->page, offset, chars, from);
488 			if (unlikely(ret < chars)) {
489 				ret = -EFAULT;
490 				goto out;
491 			}
492 
493 			buf->len += ret;
494 			if (!iov_iter_count(from))
495 				goto out;
496 		}
497 	}
498 
499 	for (;;) {
500 		if (!pipe->readers) {
501 			send_sig(SIGPIPE, current, 0);
502 			if (!ret)
503 				ret = -EPIPE;
504 			break;
505 		}
506 
507 		head = pipe->head;
508 		if (!pipe_full(head, pipe->tail, pipe->max_usage)) {
509 			struct pipe_buffer *buf;
510 			struct page *page;
511 			int copied;
512 
513 			page = anon_pipe_get_page(pipe);
514 			if (unlikely(!page)) {
515 				if (!ret)
516 					ret = -ENOMEM;
517 				break;
518 			}
519 
520 			copied = copy_page_from_iter(page, 0, PAGE_SIZE, from);
521 			if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) {
522 				anon_pipe_put_page(pipe, page);
523 				if (!ret)
524 					ret = -EFAULT;
525 				break;
526 			}
527 
528 			pipe->head = head + 1;
529 			/* Insert it into the buffer array */
530 			buf = pipe_buf(pipe, head);
531 			buf->page = page;
532 			buf->ops = &anon_pipe_buf_ops;
533 			buf->offset = 0;
534 			if (is_packetized(filp))
535 				buf->flags = PIPE_BUF_FLAG_PACKET;
536 			else
537 				buf->flags = PIPE_BUF_FLAG_CAN_MERGE;
538 
539 			buf->len = copied;
540 			ret += copied;
541 
542 			if (!iov_iter_count(from))
543 				break;
544 
545 			continue;
546 		}
547 
548 		/* Wait for buffer space to become available. */
549 		if ((filp->f_flags & O_NONBLOCK) ||
550 		    (iocb->ki_flags & IOCB_NOWAIT)) {
551 			if (!ret)
552 				ret = -EAGAIN;
553 			break;
554 		}
555 		if (signal_pending(current)) {
556 			if (!ret)
557 				ret = -ERESTARTSYS;
558 			break;
559 		}
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 		 */
567 		mutex_unlock(&pipe->mutex);
568 		if (was_empty)
569 			wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
570 		kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
571 		wait_event_interruptible_exclusive(pipe->wr_wait, pipe_writable(pipe));
572 		mutex_lock(&pipe->mutex);
573 		was_empty = pipe_is_empty(pipe);
574 		wake_next_writer = true;
575 	}
576 out:
577 	if (pipe_is_full(pipe))
578 		wake_next_writer = false;
579 	mutex_unlock(&pipe->mutex);
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
589 	 *
590 	 * Epoll nonsensically wants a wakeup whether the pipe
591 	 * was already empty or not.
592 	 */
593 	if (was_empty || pipe->poll_usage)
594 		wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
595 	kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
596 	if (wake_next_writer)
597 		wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
598 	return ret;
599 }
600 
601 static ssize_t
fifo_pipe_write(struct kiocb * iocb,struct iov_iter * from)602 fifo_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 		}
613 	}
614 	return ret;
615 }
616 
pipe_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)617 static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
618 {
619 	struct pipe_inode_info *pipe = filp->private_data;
620 	unsigned int count, head, tail;
621 
622 	switch (cmd) {
623 	case FIONREAD:
624 		mutex_lock(&pipe->mutex);
625 		count = 0;
626 		head = pipe->head;
627 		tail = pipe->tail;
628 
629 		while (!pipe_empty(head, tail)) {
630 			count += pipe_buf(pipe, tail)->len;
631 			tail++;
632 		}
633 		mutex_unlock(&pipe->mutex);
634 
635 		return put_user(count, (int __user *)arg);
636 
637 #ifdef CONFIG_WATCH_QUEUE
638 	case IOC_WATCH_QUEUE_SET_SIZE: {
639 		int ret;
640 		mutex_lock(&pipe->mutex);
641 		ret = watch_queue_set_size(pipe, arg);
642 		mutex_unlock(&pipe->mutex);
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;
653 	}
654 }
655 
656 /* No kernel lock held - fine */
657 static __poll_t
pipe_poll(struct file * filp,poll_table * wait)658 pipe_poll(struct file *filp, poll_table *wait)
659 {
660 	__poll_t mask;
661 	struct pipe_inode_info *pipe = filp->private_data;
662 	union pipe_index idx;
663 
664 	/* Epoll has some historical nasty semantics, this enables them */
665 	WRITE_ONCE(pipe->poll_usage, true);
666 
667 	/*
668 	 * Reading pipe state only -- no need for acquiring the semaphore.
669 	 *
670 	 * But because this is racy, the code has to add the
671 	 * entry to the poll table _first_ ..
672 	 */
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);
677 
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 	 */
683 	idx.head_tail = READ_ONCE(pipe->head_tail);
684 
685 	mask = 0;
686 	if (filp->f_mode & FMODE_READ) {
687 		if (!pipe_empty(idx.head, idx.tail))
688 			mask |= EPOLLIN | EPOLLRDNORM;
689 		if (!pipe->writers && filp->f_pipe != pipe->w_counter)
690 			mask |= EPOLLHUP;
691 	}
692 
693 	if (filp->f_mode & FMODE_WRITE) {
694 		if (!pipe_full(idx.head, idx.tail, pipe->max_usage))
695 			mask |= EPOLLOUT | EPOLLWRNORM;
696 		/*
697 		 * Most Unices do not set EPOLLERR for FIFOs but on Linux they
698 		 * behave exactly like pipes for poll().
699 		 */
700 		if (!pipe->readers)
701 			mask |= EPOLLERR;
702 	}
703 
704 	return mask;
705 }
706 
put_pipe_info(struct inode * inode,struct pipe_inode_info * pipe)707 static 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 
722 static int
pipe_release(struct inode * inode,struct file * file)723 pipe_release(struct inode *inode, struct file *file)
724 {
725 	struct pipe_inode_info *pipe = file->private_data;
726 
727 	mutex_lock(&pipe->mutex);
728 	if (file->f_mode & FMODE_READ)
729 		pipe->readers--;
730 	if (file->f_mode & FMODE_WRITE)
731 		pipe->writers--;
732 
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);
737 		kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
738 		kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
739 	}
740 	mutex_unlock(&pipe->mutex);
741 
742 	put_pipe_info(inode, pipe);
743 	return 0;
744 }
745 
746 static int
pipe_fasync(int fd,struct file * filp,int on)747 pipe_fasync(int fd, struct file *filp, int on)
748 {
749 	struct pipe_inode_info *pipe = filp->private_data;
750 	int retval = 0;
751 
752 	mutex_lock(&pipe->mutex);
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) {
756 		retval = fasync_helper(fd, filp, on, &pipe->fasync_writers);
757 		if (retval < 0 && (filp->f_mode & FMODE_READ))
758 			/* this can happen only if on == T */
759 			fasync_helper(-1, filp, 0, &pipe->fasync_readers);
760 	}
761 	mutex_unlock(&pipe->mutex);
762 	return retval;
763 }
764 
account_pipe_buffers(struct user_struct * user,unsigned long old,unsigned long new)765 unsigned long account_pipe_buffers(struct user_struct *user,
766 				   unsigned long old, unsigned long new)
767 {
768 	return atomic_long_add_return(new - old, &user->pipe_bufs);
769 }
770 
too_many_pipe_buffers_soft(unsigned long user_bufs)771 bool too_many_pipe_buffers_soft(unsigned long user_bufs)
772 {
773 	unsigned long soft_limit = READ_ONCE(pipe_user_pages_soft);
774 
775 	return soft_limit && user_bufs > soft_limit;
776 }
777 
too_many_pipe_buffers_hard(unsigned long user_bufs)778 bool too_many_pipe_buffers_hard(unsigned long user_bufs)
779 {
780 	unsigned long hard_limit = READ_ONCE(pipe_user_pages_hard);
781 
782 	return hard_limit && user_bufs > hard_limit;
783 }
784 
pipe_is_unprivileged_user(void)785 bool pipe_is_unprivileged_user(void)
786 {
787 	return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN);
788 }
789 
alloc_pipe_info(void)790 struct pipe_inode_info *alloc_pipe_info(void)
791 {
792 	struct pipe_inode_info *pipe;
793 	unsigned long pipe_bufs = PIPE_DEF_BUFFERS;
794 	struct user_struct *user = get_current_user();
795 	unsigned long user_bufs;
796 	unsigned int max_size = READ_ONCE(pipe_max_size);
797 
798 	pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL_ACCOUNT);
799 	if (pipe == NULL)
800 		goto out_free_uid;
801 
802 	if (pipe_bufs * PAGE_SIZE > max_size && !capable(CAP_SYS_RESOURCE))
803 		pipe_bufs = max_size >> PAGE_SHIFT;
804 
805 	user_bufs = account_pipe_buffers(user, 0, pipe_bufs);
806 
807 	if (too_many_pipe_buffers_soft(user_bufs) && pipe_is_unprivileged_user()) {
808 		user_bufs = account_pipe_buffers(user, pipe_bufs, PIPE_MIN_DEF_BUFFERS);
809 		pipe_bufs = PIPE_MIN_DEF_BUFFERS;
810 	}
811 
812 	if (too_many_pipe_buffers_hard(user_bufs) && pipe_is_unprivileged_user())
813 		goto out_revert_acct;
814 
815 	pipe->bufs = kcalloc(pipe_bufs, sizeof(struct pipe_buffer),
816 			     GFP_KERNEL_ACCOUNT);
817 
818 	if (pipe->bufs) {
819 		init_waitqueue_head(&pipe->rd_wait);
820 		init_waitqueue_head(&pipe->wr_wait);
821 		pipe->r_counter = pipe->w_counter = 1;
822 		pipe->max_usage = pipe_bufs;
823 		pipe->ring_size = pipe_bufs;
824 		pipe->nr_accounted = pipe_bufs;
825 		pipe->user = user;
826 		mutex_init(&pipe->mutex);
827 		lock_set_cmp_fn(&pipe->mutex, pipe_lock_cmp_fn, NULL);
828 		return pipe;
829 	}
830 
831 out_revert_acct:
832 	(void) account_pipe_buffers(user, pipe_bufs, 0);
833 	kfree(pipe);
834 out_free_uid:
835 	free_uid(user);
836 	return NULL;
837 }
838 
free_pipe_info(struct pipe_inode_info * pipe)839 void free_pipe_info(struct pipe_inode_info *pipe)
840 {
841 	unsigned int i;
842 
843 #ifdef CONFIG_WATCH_QUEUE
844 	if (pipe->watch_queue)
845 		watch_queue_clear(pipe->watch_queue);
846 #endif
847 
848 	(void) account_pipe_buffers(pipe->user, pipe->nr_accounted, 0);
849 	free_uid(pipe->user);
850 	for (i = 0; i < pipe->ring_size; i++) {
851 		struct pipe_buffer *buf = pipe->bufs + i;
852 		if (buf->ops)
853 			pipe_buf_release(pipe, buf);
854 	}
855 #ifdef CONFIG_WATCH_QUEUE
856 	if (pipe->watch_queue)
857 		put_watch_queue(pipe->watch_queue);
858 #endif
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 	}
863 	kfree(pipe->bufs);
864 	kfree(pipe);
865 }
866 
867 static struct vfsmount *pipe_mnt __ro_after_init;
868 
869 /*
870  * pipefs_dname() is called from d_path().
871  */
pipefs_dname(struct dentry * dentry,char * buffer,int buflen)872 static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen)
873 {
874 	return dynamic_dname(buffer, buflen, "pipe:[%lu]",
875 				d_inode(dentry)->i_ino);
876 }
877 
878 static const struct dentry_operations pipefs_dentry_operations = {
879 	.d_dname	= pipefs_dname,
880 };
881 
882 static const struct file_operations pipeanon_fops;
883 
get_pipe_inode(void)884 static struct inode * get_pipe_inode(void)
885 {
886 	struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb);
887 	struct pipe_inode_info *pipe;
888 
889 	if (!inode)
890 		goto fail_inode;
891 
892 	inode->i_ino = get_next_ino();
893 
894 	pipe = alloc_pipe_info();
895 	if (!pipe)
896 		goto fail_iput;
897 
898 	inode->i_pipe = pipe;
899 	pipe->files = 2;
900 	pipe->readers = pipe->writers = 1;
901 	inode->i_fop = &pipeanon_fops;
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;
911 	inode->i_uid = current_fsuid();
912 	inode->i_gid = current_fsgid();
913 	simple_inode_init_ts(inode);
914 
915 	return inode;
916 
917 fail_iput:
918 	iput(inode);
919 
920 fail_inode:
921 	return NULL;
922 }
923 
create_pipe_files(struct file ** res,int flags)924 int create_pipe_files(struct file **res, int flags)
925 {
926 	struct inode *inode = get_pipe_inode();
927 	struct file *f;
928 	int error;
929 
930 	if (!inode)
931 		return -ENFILE;
932 
933 	if (flags & O_NOTIFICATION_PIPE) {
934 		error = watch_queue_init(inode->i_pipe);
935 		if (error) {
936 			free_pipe_info(inode->i_pipe);
937 			iput(inode);
938 			return error;
939 		}
940 	}
941 
942 	f = alloc_file_pseudo(inode, pipe_mnt, "",
943 				O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)),
944 				&pipeanon_fops);
945 	if (IS_ERR(f)) {
946 		free_pipe_info(inode->i_pipe);
947 		iput(inode);
948 		return PTR_ERR(f);
949 	}
950 
951 	f->private_data = inode->i_pipe;
952 	f->f_pipe = 0;
953 
954 	res[0] = alloc_file_clone(f, O_RDONLY | (flags & O_NONBLOCK),
955 				  &pipeanon_fops);
956 	if (IS_ERR(res[0])) {
957 		put_pipe_info(inode, inode->i_pipe);
958 		fput(f);
959 		return PTR_ERR(res[0]);
960 	}
961 	res[0]->private_data = inode->i_pipe;
962 	res[0]->f_pipe = 0;
963 	res[1] = f;
964 	stream_open(inode, res[0]);
965 	stream_open(inode, res[1]);
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);
972 	return 0;
973 }
974 
__do_pipe_flags(int * fd,struct file ** files,int flags)975 static int __do_pipe_flags(int *fd, struct file **files, int flags)
976 {
977 	int error;
978 	int fdw, fdr;
979 
980 	if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT | O_NOTIFICATION_PIPE))
981 		return -EINVAL;
982 
983 	error = create_pipe_files(files, flags);
984 	if (error)
985 		return error;
986 
987 	error = get_unused_fd_flags(flags);
988 	if (error < 0)
989 		goto err_read_pipe;
990 	fdr = error;
991 
992 	error = get_unused_fd_flags(flags);
993 	if (error < 0)
994 		goto err_fdr;
995 	fdw = error;
996 
997 	audit_fd_pair(fdr, fdw);
998 	fd[0] = fdr;
999 	fd[1] = fdw;
1000 	/* pipe groks IOCB_NOWAIT */
1001 	files[0]->f_mode |= FMODE_NOWAIT;
1002 	files[1]->f_mode |= FMODE_NOWAIT;
1003 	return 0;
1004 
1005  err_fdr:
1006 	put_unused_fd(fdr);
1007  err_read_pipe:
1008 	fput(files[0]);
1009 	fput(files[1]);
1010 	return error;
1011 }
1012 
do_pipe_flags(int * fd,int flags)1013 int 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 
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  */
do_pipe2(int __user * fildes,int flags)1028 static int do_pipe2(int __user *fildes, int flags)
1029 {
1030 	struct file *files[2];
1031 	int fd[2];
1032 	int error;
1033 
1034 	error = __do_pipe_flags(fd, files, flags);
1035 	if (!error) {
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]);
1041 			error = -EFAULT;
1042 		} else {
1043 			fd_install(fd[0], files[0]);
1044 			fd_install(fd[1], files[1]);
1045 		}
1046 	}
1047 	return error;
1048 }
1049 
SYSCALL_DEFINE2(pipe2,int __user *,fildes,int,flags)1050 SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)
1051 {
1052 	return do_pipe2(fildes, flags);
1053 }
1054 
SYSCALL_DEFINE1(pipe,int __user *,fildes)1055 SYSCALL_DEFINE1(pipe, int __user *, fildes)
1056 {
1057 	return do_pipe2(fildes, 0);
1058 }
1059 
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  */
pipe_wait_readable(struct pipe_inode_info * pipe)1069 void 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 
pipe_wait_writable(struct pipe_inode_info * pipe)1076 void 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  */
wait_for_partner(struct pipe_inode_info * pipe,unsigned int * cnt)1095 static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt)
1096 {
1097 	DEFINE_WAIT(rdwait);
1098 	int cur = *cnt;
1099 
1100 	while (cur == *cnt) {
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);
1106 		if (signal_pending(current))
1107 			break;
1108 	}
1109 	return cur == *cnt ? -ERESTARTSYS : 0;
1110 }
1111 
wake_up_partner(struct pipe_inode_info * pipe)1112 static void wake_up_partner(struct pipe_inode_info *pipe)
1113 {
1114 	wake_up_interruptible_all(&pipe->rd_wait);
1115 }
1116 
fifo_open(struct inode * inode,struct file * filp)1117 static int fifo_open(struct inode *inode, struct file *filp)
1118 {
1119 	bool is_pipe = inode->i_fop == &pipeanon_fops;
1120 	struct pipe_inode_info *pipe;
1121 	int ret;
1122 
1123 	filp->f_pipe = 0;
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);
1132 		pipe = alloc_pipe_info();
1133 		if (!pipe)
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);
1140 			free_pipe_info(pipe);
1141 			pipe = inode->i_pipe;
1142 		} else {
1143 			inode->i_pipe = pipe;
1144 			spin_unlock(&inode->i_lock);
1145 		}
1146 	}
1147 	filp->private_data = pipe;
1148 	/* OK, we have a pipe and it's pinned down */
1149 
1150 	mutex_lock(&pipe->mutex);
1151 
1152 	/* We can only do regular read/write on fifos */
1153 	stream_open(inode, filp);
1154 
1155 	switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) {
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 	 */
1162 		pipe->r_counter++;
1163 		if (pipe->readers++ == 0)
1164 			wake_up_partner(pipe);
1165 
1166 		if (!is_pipe && !pipe->writers) {
1167 			if ((filp->f_flags & O_NONBLOCK)) {
1168 				/* suppress EPOLLHUP until we have
1169 				 * seen a writer */
1170 				filp->f_pipe = pipe->w_counter;
1171 			} else {
1172 				if (wait_for_partner(pipe, &pipe->w_counter))
1173 					goto err_rd;
1174 			}
1175 		}
1176 		break;
1177 
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;
1185 		if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers)
1186 			goto err;
1187 
1188 		pipe->w_counter++;
1189 		if (!pipe->writers++)
1190 			wake_up_partner(pipe);
1191 
1192 		if (!is_pipe && !pipe->readers) {
1193 			if (wait_for_partner(pipe, &pipe->r_counter))
1194 				goto err_wr;
1195 		}
1196 		break;
1197 
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 	 */
1205 
1206 		pipe->readers++;
1207 		pipe->writers++;
1208 		pipe->r_counter++;
1209 		pipe->w_counter++;
1210 		if (pipe->readers == 1 || pipe->writers == 1)
1211 			wake_up_partner(pipe);
1212 		break;
1213 
1214 	default:
1215 		ret = -EINVAL;
1216 		goto err;
1217 	}
1218 
1219 	/* Ok! */
1220 	mutex_unlock(&pipe->mutex);
1221 	return 0;
1222 
1223 err_rd:
1224 	if (!--pipe->readers)
1225 		wake_up_interruptible(&pipe->wr_wait);
1226 	ret = -ERESTARTSYS;
1227 	goto err;
1228 
1229 err_wr:
1230 	if (!--pipe->writers)
1231 		wake_up_interruptible_all(&pipe->rd_wait);
1232 	ret = -ERESTARTSYS;
1233 	goto err;
1234 
1235 err:
1236 	mutex_unlock(&pipe->mutex);
1237 
1238 	put_pipe_info(inode, pipe);
1239 	return ret;
1240 }
1241 
1242 const struct file_operations pipefifo_fops = {
1243 	.open		= fifo_open,
1244 	.read_iter	= fifo_pipe_read,
1245 	.write_iter	= fifo_pipe_write,
1246 	.poll		= pipe_poll,
1247 	.unlocked_ioctl	= pipe_ioctl,
1248 	.release	= pipe_release,
1249 	.fasync		= pipe_fasync,
1250 	.splice_write	= iter_file_splice_write,
1251 };
1252 
1253 static const struct file_operations pipeanon_fops = {
1254 	.open		= fifo_open,
1255 	.read_iter	= anon_pipe_read,
1256 	.write_iter	= anon_pipe_write,
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 
1264 /*
1265  * Currently we rely on the pipe array holding a power-of-2 number
1266  * of pages. Returns 0 on error.
1267  */
round_pipe_size(unsigned int size)1268 unsigned int round_pipe_size(unsigned int size)
1269 {
1270 	if (size > (1U << 31))
1271 		return 0;
1272 
1273 	/* Minimum pipe size, as required by POSIX */
1274 	if (size < PAGE_SIZE)
1275 		return PAGE_SIZE;
1276 
1277 	return roundup_pow_of_two(size);
1278 }
1279 
1280 /*
1281  * Resize the pipe ring to a number of slots.
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.
1286  */
pipe_resize_ring(struct pipe_inode_info * pipe,unsigned int nr_slots)1287 int pipe_resize_ring(struct pipe_inode_info *pipe, unsigned int nr_slots)
1288 {
1289 	struct pipe_buffer *bufs;
1290 	unsigned int head, tail, mask, n;
1291 
1292 	/* nr_slots larger than limits of pipe->{head,tail} */
1293 	if (unlikely(nr_slots > (pipe_index_t)-1u))
1294 		return -EINVAL;
1295 
1296 	bufs = kcalloc(nr_slots, sizeof(*bufs),
1297 		       GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
1298 	if (unlikely(!bufs))
1299 		return -ENOMEM;
1300 
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 
1313 	/*
1314 	 * The pipe array wraps around, so just start the new one at zero
1315 	 * and adjust the indices.
1316 	 */
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 		}
1331 	}
1332 
1333 	head = n;
1334 	tail = 0;
1335 
1336 	kfree(pipe->bufs);
1337 	pipe->bufs = bufs;
1338 	pipe->ring_size = nr_slots;
1339 	if (pipe->max_usage > nr_slots)
1340 		pipe->max_usage = nr_slots;
1341 	pipe->tail = tail;
1342 	pipe->head = head;
1343 
1344 	if (!pipe_has_watch_queue(pipe)) {
1345 		pipe->max_usage = nr_slots;
1346 		pipe->nr_accounted = nr_slots;
1347 	}
1348 
1349 	spin_unlock_irq(&pipe->rd_wait.lock);
1350 
1351 	/* This might have made more room for writers */
1352 	wake_up_interruptible(&pipe->wr_wait);
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  */
pipe_set_size(struct pipe_inode_info * pipe,unsigned int arg)1360 static long pipe_set_size(struct pipe_inode_info *pipe, unsigned int arg)
1361 {
1362 	unsigned long user_bufs;
1363 	unsigned int nr_slots, size;
1364 	long ret = 0;
1365 
1366 	if (pipe_has_watch_queue(pipe))
1367 		return -EBUSY;
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 
1400 	return pipe->max_usage * PAGE_SIZE;
1401 
1402 out_revert_acct:
1403 	(void) account_pipe_buffers(pipe->user, nr_slots, pipe->nr_accounted);
1404 	return ret;
1405 }
1406 
1407 /*
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.
1410  */
get_pipe_info(struct file * file,bool for_splice)1411 struct pipe_inode_info *get_pipe_info(struct file *file, bool for_splice)
1412 {
1413 	struct pipe_inode_info *pipe = file->private_data;
1414 
1415 	if (!pipe)
1416 		return NULL;
1417 	if (file->f_op != &pipefifo_fops && file->f_op != &pipeanon_fops)
1418 		return NULL;
1419 	if (for_splice && pipe_has_watch_queue(pipe))
1420 		return NULL;
1421 	return pipe;
1422 }
1423 
pipe_fcntl(struct file * file,unsigned int cmd,unsigned int arg)1424 long pipe_fcntl(struct file *file, unsigned int cmd, unsigned int arg)
1425 {
1426 	struct pipe_inode_info *pipe;
1427 	long ret;
1428 
1429 	pipe = get_pipe_info(file, false);
1430 	if (!pipe)
1431 		return -EBADF;
1432 
1433 	mutex_lock(&pipe->mutex);
1434 
1435 	switch (cmd) {
1436 	case F_SETPIPE_SZ:
1437 		ret = pipe_set_size(pipe, arg);
1438 		break;
1439 	case F_GETPIPE_SZ:
1440 		ret = pipe->max_usage * PAGE_SIZE;
1441 		break;
1442 	default:
1443 		ret = -EINVAL;
1444 		break;
1445 	}
1446 
1447 	mutex_unlock(&pipe->mutex);
1448 	return ret;
1449 }
1450 
1451 static const struct super_operations pipefs_ops = {
1452 	.destroy_inode = free_inode_nonrcu,
1453 	.statfs = simple_statfs,
1454 };
1455 
1456 /*
1457  * pipefs should _never_ be mounted by userland - too much of security hassle,
1458  * no real gain from having the whole file system mounted. So we don't need
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  */
1462 
pipefs_init_fs_context(struct fs_context * fc)1463 static int pipefs_init_fs_context(struct fs_context *fc)
1464 {
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;
1471 }
1472 
1473 static struct file_system_type pipe_fs_type = {
1474 	.name		= "pipefs",
1475 	.init_fs_context = pipefs_init_fs_context,
1476 	.kill_sb	= kill_anon_super,
1477 };
1478 
1479 #ifdef CONFIG_SYSCTL
do_proc_dopipe_max_size_conv(unsigned long * lvalp,unsigned int * valp,int write,void * data)1480 static 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 
proc_dopipe_max_size(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)1500 static int proc_dopipe_max_size(const struct ctl_table *table, int write,
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 
1507 static const struct ctl_table fs_pipe_sysctls[] = {
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 	},
1529 };
1530 #endif
1531 
init_pipe_fs(void)1532 static int __init init_pipe_fs(void)
1533 {
1534 	int err = register_filesystem(&pipe_fs_type);
1535 
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 	}
1543 #ifdef CONFIG_SYSCTL
1544 	register_sysctl_init("fs", fs_pipe_sysctls);
1545 #endif
1546 	return err;
1547 }
1548 
1549 fs_initcall(init_pipe_fs);
1550