xref: /freebsd/sys/kern/sys_pipe.c (revision e60f608eb9cf3b38099948545934d699de9bbcea)
1 /*-
2  * Copyright (c) 1996 John S. Dyson
3  * Copyright (c) 2012 Giovanni Trematerra
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice immediately at the beginning of the file, without modification,
11  *    this list of conditions, and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Absolutely no warranty of function or purpose is made by the author
16  *    John S. Dyson.
17  * 4. Modifications may be freely made to this file if the above conditions
18  *    are met.
19  */
20 
21 /*
22  * This file contains a high-performance replacement for the socket-based
23  * pipes scheme originally used in FreeBSD/4.4Lite.  It does not support
24  * all features of sockets, but does do everything that pipes normally
25  * do.
26  */
27 
28 /*
29  * This code has two modes of operation, a small write mode and a large
30  * write mode.  The small write mode acts like conventional pipes with
31  * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
32  * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
33  * and PIPE_SIZE in size, the sending process pins the underlying pages in
34  * memory, and the receiving process copies directly from these pinned pages
35  * in the sending process.
36  *
37  * If the sending process receives a signal, it is possible that it will
38  * go away, and certainly its address space can change, because control
39  * is returned back to the user-mode side.  In that case, the pipe code
40  * arranges to copy the buffer supplied by the user process, to a pageable
41  * kernel buffer, and the receiving process will grab the data from the
42  * pageable kernel buffer.  Since signals don't happen all that often,
43  * the copy operation is normally eliminated.
44  *
45  * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
46  * happen for small transfers so that the system will not spend all of
47  * its time context switching.
48  *
49  * In order to limit the resource use of pipes, two sysctls exist:
50  *
51  * kern.ipc.maxpipekva - This is a hard limit on the amount of pageable
52  * address space available to us in pipe_map. This value is normally
53  * autotuned, but may also be loader tuned.
54  *
55  * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
56  * memory in use by pipes.
57  *
58  * Based on how large pipekva is relative to maxpipekva, the following
59  * will happen:
60  *
61  * 0% - 50%:
62  *     New pipes are given 16K of memory backing, pipes may dynamically
63  *     grow to as large as 64K where needed.
64  * 50% - 75%:
65  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
66  *     existing pipes may NOT grow.
67  * 75% - 100%:
68  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
69  *     existing pipes will be shrunk down to 4K whenever possible.
70  *
71  * Resizing may be disabled by setting kern.ipc.piperesizeallowed=0.  If
72  * that is set,  the only resize that will occur is the 0 -> SMALL_PIPE_SIZE
73  * resize which MUST occur for reverse-direction pipes when they are
74  * first used.
75  *
76  * Additional information about the current state of pipes may be obtained
77  * from kern.ipc.pipes, kern.ipc.pipefragretry, kern.ipc.pipeallocfail,
78  * and kern.ipc.piperesizefail.
79  *
80  * Locking rules:  There are two locks present here:  A mutex, used via
81  * PIPE_LOCK, and a flag, used via pipelock().  All locking is done via
82  * the flag, as mutexes can not persist over uiomove.  The mutex
83  * exists only to guard access to the flag, and is not in itself a
84  * locking mechanism.  Also note that there is only a single mutex for
85  * both directions of a pipe.
86  *
87  * As pipelock() may have to sleep before it can acquire the flag, it
88  * is important to reread all data after a call to pipelock(); everything
89  * in the structure may have changed.
90  */
91 
92 #include <sys/param.h>
93 #include <sys/systm.h>
94 #include <sys/conf.h>
95 #include <sys/fcntl.h>
96 #include <sys/file.h>
97 #include <sys/filedesc.h>
98 #include <sys/filio.h>
99 #include <sys/kernel.h>
100 #include <sys/lock.h>
101 #include <sys/mutex.h>
102 #include <sys/ttycom.h>
103 #include <sys/stat.h>
104 #include <sys/malloc.h>
105 #include <sys/poll.h>
106 #include <sys/priv.h>
107 #include <sys/selinfo.h>
108 #include <sys/signalvar.h>
109 #include <sys/syscallsubr.h>
110 #include <sys/sysctl.h>
111 #include <sys/sysproto.h>
112 #include <sys/pipe.h>
113 #include <sys/proc.h>
114 #include <sys/vnode.h>
115 #include <sys/uio.h>
116 #include <sys/user.h>
117 #include <sys/event.h>
118 
119 #include <security/mac/mac_framework.h>
120 
121 #include <vm/vm.h>
122 #include <vm/vm_param.h>
123 #include <vm/vm_object.h>
124 #include <vm/vm_kern.h>
125 #include <vm/vm_extern.h>
126 #include <vm/pmap.h>
127 #include <vm/vm_map.h>
128 #include <vm/vm_page.h>
129 #include <vm/uma.h>
130 
131 /*
132  * Use this define if you want to disable *fancy* VM things.  Expect an
133  * approx 30% decrease in transfer rate.  This could be useful for
134  * NetBSD or OpenBSD.
135  */
136 /* #define PIPE_NODIRECT */
137 
138 #define PIPE_PEER(pipe)	\
139 	(((pipe)->pipe_type & PIPE_TYPE_NAMED) ? (pipe) : ((pipe)->pipe_peer))
140 
141 /*
142  * interfaces to the outside world
143  */
144 static fo_rdwr_t	pipe_read;
145 static fo_rdwr_t	pipe_write;
146 static fo_truncate_t	pipe_truncate;
147 static fo_ioctl_t	pipe_ioctl;
148 static fo_poll_t	pipe_poll;
149 static fo_kqfilter_t	pipe_kqfilter;
150 static fo_stat_t	pipe_stat;
151 static fo_close_t	pipe_close;
152 static fo_chmod_t	pipe_chmod;
153 static fo_chown_t	pipe_chown;
154 static fo_fill_kinfo_t	pipe_fill_kinfo;
155 
156 const struct fileops pipeops = {
157 	.fo_read = pipe_read,
158 	.fo_write = pipe_write,
159 	.fo_truncate = pipe_truncate,
160 	.fo_ioctl = pipe_ioctl,
161 	.fo_poll = pipe_poll,
162 	.fo_kqfilter = pipe_kqfilter,
163 	.fo_stat = pipe_stat,
164 	.fo_close = pipe_close,
165 	.fo_chmod = pipe_chmod,
166 	.fo_chown = pipe_chown,
167 	.fo_sendfile = invfo_sendfile,
168 	.fo_fill_kinfo = pipe_fill_kinfo,
169 	.fo_cmp = file_kcmp_generic,
170 	.fo_flags = DFLAG_PASSABLE
171 };
172 
173 static void	filt_pipedetach(struct knote *kn);
174 static void	filt_pipedetach_notsup(struct knote *kn);
175 static int	filt_pipenotsup(struct knote *kn, long hint);
176 static int	filt_piperead(struct knote *kn, long hint);
177 static int	filt_pipewrite(struct knote *kn, long hint);
178 static int	filt_pipedump(struct proc *p, struct knote *kn,
179     struct kinfo_knote *kin);
180 
181 static const struct filterops pipe_nfiltops = {
182 	.f_isfd = 1,
183 	.f_detach = filt_pipedetach_notsup,
184 	.f_event = filt_pipenotsup
185 	/* no userdump */
186 };
187 static const struct filterops pipe_rfiltops = {
188 	.f_isfd = 1,
189 	.f_detach = filt_pipedetach,
190 	.f_event = filt_piperead,
191 	.f_userdump = filt_pipedump,
192 };
193 static const struct filterops pipe_wfiltops = {
194 	.f_isfd = 1,
195 	.f_detach = filt_pipedetach,
196 	.f_event = filt_pipewrite,
197 	.f_userdump = filt_pipedump,
198 };
199 
200 /*
201  * Default pipe buffer size(s), this can be kind-of large now because pipe
202  * space is pageable.  The pipe code will try to maintain locality of
203  * reference for performance reasons, so small amounts of outstanding I/O
204  * will not wipe the cache.
205  */
206 #define MINPIPESIZE (PIPE_SIZE/3)
207 #define MAXPIPESIZE (2*PIPE_SIZE/3)
208 
209 static long amountpipekva;
210 static int pipefragretry;
211 static int pipeallocfail;
212 static int piperesizefail;
213 static int piperesizeallowed = 1;
214 static long pipe_mindirect = PIPE_MINDIRECT;
215 static int pipebuf_reserv = 2;
216 
217 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
218 	   &maxpipekva, 0, "Pipe KVA limit");
219 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
220 	   &amountpipekva, 0, "Pipe KVA usage");
221 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
222 	  &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
223 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
224 	  &pipeallocfail, 0, "Pipe allocation failures");
225 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
226 	  &piperesizefail, 0, "Pipe resize failures");
227 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
228 	  &piperesizeallowed, 0, "Pipe resizing allowed");
229 SYSCTL_INT(_kern_ipc, OID_AUTO, pipebuf_reserv, CTLFLAG_RW,
230     &pipebuf_reserv, 0,
231     "Superuser-reserved percentage of the pipe buffers space");
232 
233 static void pipeinit(void *dummy __unused);
234 static void pipeclose(struct pipe *cpipe);
235 static void pipe_free_kmem(struct pipe *cpipe);
236 static int pipe_create(struct pipe *pipe, bool backing);
237 static int pipe_paircreate(struct thread *td, struct pipepair **p_pp);
238 static __inline int pipelock(struct pipe *cpipe, bool catch);
239 static __inline void pipeunlock(struct pipe *cpipe);
240 static void pipe_timestamp(struct timespec *tsp);
241 #ifndef PIPE_NODIRECT
242 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
243 static void pipe_destroy_write_buffer(struct pipe *wpipe);
244 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
245 static void pipe_clone_write_buffer(struct pipe *wpipe);
246 #endif
247 static int pipespace(struct pipe *cpipe, int size);
248 static int pipespace_new(struct pipe *cpipe, int size);
249 
250 static int	pipe_zone_ctor(void *mem, int size, void *arg, int flags);
251 static int	pipe_zone_init(void *mem, int size, int flags);
252 static void	pipe_zone_fini(void *mem, int size);
253 
254 static uma_zone_t pipe_zone;
255 static struct unrhdr64 pipeino_unr;
256 static dev_t pipedev_ino;
257 
258 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
259 
260 static void
pipeinit(void * dummy __unused)261 pipeinit(void *dummy __unused)
262 {
263 
264 	pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
265 	    pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
266 	    UMA_ALIGN_PTR, 0);
267 	KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
268 	new_unrhdr64(&pipeino_unr, 1);
269 	pipedev_ino = devfs_alloc_cdp_inode();
270 	KASSERT(pipedev_ino > 0, ("pipe dev inode not initialized"));
271 }
272 
273 static int
sysctl_handle_pipe_mindirect(SYSCTL_HANDLER_ARGS)274 sysctl_handle_pipe_mindirect(SYSCTL_HANDLER_ARGS)
275 {
276 	int error = 0;
277 	long tmp_pipe_mindirect = pipe_mindirect;
278 
279 	error = sysctl_handle_long(oidp, &tmp_pipe_mindirect, arg2, req);
280 	if (error != 0 || req->newptr == NULL)
281 		return (error);
282 
283 	/*
284 	 * Don't allow pipe_mindirect to be set so low that we violate
285 	 * atomicity requirements.
286 	 */
287 	if (tmp_pipe_mindirect <= PIPE_BUF)
288 		return (EINVAL);
289 	pipe_mindirect = tmp_pipe_mindirect;
290 	return (0);
291 }
292 SYSCTL_OID(_kern_ipc, OID_AUTO, pipe_mindirect, CTLTYPE_LONG | CTLFLAG_RW,
293     &pipe_mindirect, 0, sysctl_handle_pipe_mindirect, "L",
294     "Minimum write size triggering VM optimization");
295 
296 static int
pipe_zone_ctor(void * mem,int size,void * arg,int flags)297 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
298 {
299 	struct pipepair *pp;
300 	struct pipe *rpipe, *wpipe;
301 
302 	KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
303 
304 	pp = (struct pipepair *)mem;
305 
306 	/*
307 	 * We zero both pipe endpoints to make sure all the kmem pointers
308 	 * are NULL, flag fields are zero'd, etc.  We timestamp both
309 	 * endpoints with the same time.
310 	 */
311 	rpipe = &pp->pp_rpipe;
312 	bzero(rpipe, sizeof(*rpipe));
313 	pipe_timestamp(&rpipe->pipe_ctime);
314 	rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
315 
316 	wpipe = &pp->pp_wpipe;
317 	bzero(wpipe, sizeof(*wpipe));
318 	wpipe->pipe_ctime = rpipe->pipe_ctime;
319 	wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
320 
321 	rpipe->pipe_peer = wpipe;
322 	rpipe->pipe_pair = pp;
323 	wpipe->pipe_peer = rpipe;
324 	wpipe->pipe_pair = pp;
325 
326 	/*
327 	 * Mark both endpoints as present; they will later get free'd
328 	 * one at a time.  When both are free'd, then the whole pair
329 	 * is released.
330 	 */
331 	rpipe->pipe_present = PIPE_ACTIVE;
332 	wpipe->pipe_present = PIPE_ACTIVE;
333 
334 	/*
335 	 * Eventually, the MAC Framework may initialize the label
336 	 * in ctor or init, but for now we do it elswhere to avoid
337 	 * blocking in ctor or init.
338 	 */
339 	pp->pp_label = NULL;
340 
341 	return (0);
342 }
343 
344 static int
pipe_zone_init(void * mem,int size,int flags)345 pipe_zone_init(void *mem, int size, int flags)
346 {
347 	struct pipepair *pp;
348 
349 	KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
350 
351 	pp = (struct pipepair *)mem;
352 
353 	mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_NEW);
354 	return (0);
355 }
356 
357 static void
pipe_zone_fini(void * mem,int size)358 pipe_zone_fini(void *mem, int size)
359 {
360 	struct pipepair *pp;
361 
362 	KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
363 
364 	pp = (struct pipepair *)mem;
365 
366 	mtx_destroy(&pp->pp_mtx);
367 }
368 
369 static int
pipe_paircreate(struct thread * td,struct pipepair ** p_pp)370 pipe_paircreate(struct thread *td, struct pipepair **p_pp)
371 {
372 	struct pipepair *pp;
373 	struct pipe *rpipe, *wpipe;
374 	int error;
375 
376 	*p_pp = pp = uma_zalloc(pipe_zone, M_WAITOK);
377 #ifdef MAC
378 	/*
379 	 * The MAC label is shared between the connected endpoints.  As a
380 	 * result mac_pipe_init() and mac_pipe_create() are called once
381 	 * for the pair, and not on the endpoints.
382 	 */
383 	mac_pipe_init(pp);
384 	mac_pipe_create(td->td_ucred, pp);
385 #endif
386 	rpipe = &pp->pp_rpipe;
387 	wpipe = &pp->pp_wpipe;
388 	pp->pp_owner = crhold(td->td_ucred);
389 
390 	knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
391 	knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
392 
393 	/*
394 	 * Only the forward direction pipe is backed by big buffer by
395 	 * default.
396 	 */
397 	error = pipe_create(rpipe, true);
398 	if (error != 0)
399 		goto fail;
400 	error = pipe_create(wpipe, false);
401 	if (error != 0) {
402 		/*
403 		 * This cleanup leaves the pipe inode number for rpipe
404 		 * still allocated, but never used.  We do not free
405 		 * inode numbers for opened pipes, which is required
406 		 * for correctness because numbers must be unique.
407 		 * But also it avoids any memory use by the unr
408 		 * allocator, so stashing away the transient inode
409 		 * number is reasonable.
410 		 */
411 		pipe_free_kmem(rpipe);
412 		goto fail;
413 	}
414 
415 	rpipe->pipe_state |= PIPE_DIRECTOK;
416 	wpipe->pipe_state |= PIPE_DIRECTOK;
417 	return (0);
418 
419 fail:
420 	knlist_destroy(&rpipe->pipe_sel.si_note);
421 	knlist_destroy(&wpipe->pipe_sel.si_note);
422 	crfree(pp->pp_owner);
423 #ifdef MAC
424 	mac_pipe_destroy(pp);
425 #endif
426 	uma_zfree(pipe_zone, pp);
427 	return (error);
428 }
429 
430 int
pipe_named_ctor(struct pipe ** ppipe,struct thread * td)431 pipe_named_ctor(struct pipe **ppipe, struct thread *td)
432 {
433 	struct pipepair *pp;
434 	int error;
435 
436 	error = pipe_paircreate(td, &pp);
437 	if (error != 0)
438 		return (error);
439 	pp->pp_rpipe.pipe_type |= PIPE_TYPE_NAMED;
440 	*ppipe = &pp->pp_rpipe;
441 	return (0);
442 }
443 
444 void
pipe_dtor(struct pipe * dpipe)445 pipe_dtor(struct pipe *dpipe)
446 {
447 	struct pipe *peer;
448 
449 	peer = (dpipe->pipe_type & PIPE_TYPE_NAMED) != 0 ? dpipe->pipe_peer : NULL;
450 	funsetown(&dpipe->pipe_sigio);
451 	pipeclose(dpipe);
452 	if (peer != NULL) {
453 		funsetown(&peer->pipe_sigio);
454 		pipeclose(peer);
455 	}
456 }
457 
458 /*
459  * Get a timestamp.
460  *
461  * This used to be vfs_timestamp but the higher precision is unnecessary and
462  * can very negatively affect performance in virtualized environments (e.g., on
463  * vms running on amd64 when using the rdtscp instruction).
464  */
465 static void
pipe_timestamp(struct timespec * tsp)466 pipe_timestamp(struct timespec *tsp)
467 {
468 
469 	getnanotime(tsp);
470 }
471 
472 /*
473  * The pipe system call for the DTYPE_PIPE type of pipes.  If we fail, let
474  * the zone pick up the pieces via pipeclose().
475  */
476 int
kern_pipe(struct thread * td,int fildes[2],int flags,struct filecaps * fcaps1,struct filecaps * fcaps2)477 kern_pipe(struct thread *td, int fildes[2], int flags, struct filecaps *fcaps1,
478     struct filecaps *fcaps2)
479 {
480 	struct file *rf, *wf;
481 	struct pipe *rpipe, *wpipe;
482 	struct pipepair *pp;
483 	int fd, fflags, error;
484 
485 	error = pipe_paircreate(td, &pp);
486 	if (error != 0)
487 		return (error);
488 	rpipe = &pp->pp_rpipe;
489 	wpipe = &pp->pp_wpipe;
490 	error = falloc_caps(td, &rf, &fd, flags, fcaps1);
491 	if (error) {
492 		pipeclose(rpipe);
493 		pipeclose(wpipe);
494 		return (error);
495 	}
496 	/* An extra reference on `rf' has been held for us by falloc_caps(). */
497 	fildes[0] = fd;
498 
499 	fflags = FREAD | FWRITE;
500 	if ((flags & O_NONBLOCK) != 0)
501 		fflags |= FNONBLOCK;
502 
503 	/*
504 	 * Warning: once we've gotten past allocation of the fd for the
505 	 * read-side, we can only drop the read side via fdrop() in order
506 	 * to avoid races against processes which manage to dup() the read
507 	 * side while we are blocked trying to allocate the write side.
508 	 */
509 	finit(rf, fflags, DTYPE_PIPE, rpipe, &pipeops);
510 	error = falloc_caps(td, &wf, &fd, flags, fcaps2);
511 	if (error) {
512 		fdclose(td, rf, fildes[0]);
513 		fdrop(rf, td);
514 		/* rpipe has been closed by fdrop(). */
515 		pipeclose(wpipe);
516 		return (error);
517 	}
518 	/* An extra reference on `wf' has been held for us by falloc_caps(). */
519 	finit(wf, fflags, DTYPE_PIPE, wpipe, &pipeops);
520 	fdrop(wf, td);
521 	fildes[1] = fd;
522 	fdrop(rf, td);
523 
524 	return (0);
525 }
526 
527 #ifdef COMPAT_FREEBSD10
528 /* ARGSUSED */
529 int
freebsd10_pipe(struct thread * td,struct freebsd10_pipe_args * uap __unused)530 freebsd10_pipe(struct thread *td, struct freebsd10_pipe_args *uap __unused)
531 {
532 	int error;
533 	int fildes[2];
534 
535 	error = kern_pipe(td, fildes, 0, NULL, NULL);
536 	if (error)
537 		return (error);
538 
539 	td->td_retval[0] = fildes[0];
540 	td->td_retval[1] = fildes[1];
541 
542 	return (0);
543 }
544 #endif
545 
546 int
sys_pipe2(struct thread * td,struct pipe2_args * uap)547 sys_pipe2(struct thread *td, struct pipe2_args *uap)
548 {
549 	int error, fildes[2];
550 
551 	if (uap->flags & ~(O_CLOEXEC | O_NONBLOCK))
552 		return (EINVAL);
553 	error = kern_pipe(td, fildes, uap->flags, NULL, NULL);
554 	if (error)
555 		return (error);
556 	error = copyout(fildes, uap->fildes, 2 * sizeof(int));
557 	if (error) {
558 		(void)kern_close(td, fildes[0]);
559 		(void)kern_close(td, fildes[1]);
560 	}
561 	return (error);
562 }
563 
564 /*
565  * Allocate kva for pipe circular buffer, the space is pageable
566  * This routine will 'realloc' the size of a pipe safely, if it fails
567  * it will retain the old buffer.
568  * If it fails it will return ENOMEM.
569  */
570 static int
pipespace_new(struct pipe * cpipe,int size)571 pipespace_new(struct pipe *cpipe, int size)
572 {
573 	caddr_t buffer;
574 	int error, cnt, firstseg;
575 	static int curfail = 0;
576 	static struct timeval lastfail;
577 
578 	KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
579 	KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
580 		("pipespace: resize of direct writes not allowed"));
581 retry:
582 	cnt = cpipe->pipe_buffer.cnt;
583 	if (cnt > size)
584 		size = cnt;
585 
586 	size = round_page(size);
587 	buffer = (caddr_t) vm_map_min(pipe_map);
588 
589 	if (!chgpipecnt(cpipe->pipe_pair->pp_owner->cr_ruidinfo,
590 	    size, lim_cur(curthread, RLIMIT_PIPEBUF))) {
591 		if (cpipe->pipe_buffer.buffer == NULL &&
592 		    size > SMALL_PIPE_SIZE) {
593 			size = SMALL_PIPE_SIZE;
594 			goto retry;
595 		}
596 		return (ENOMEM);
597 	}
598 
599 	vm_map_lock(pipe_map);
600 	if (priv_check(curthread, PRIV_PIPEBUF) != 0 && maxpipekva / 100 *
601 	    (100 - pipebuf_reserv) < amountpipekva + size) {
602 		vm_map_unlock(pipe_map);
603 		chgpipecnt(cpipe->pipe_pair->pp_owner->cr_ruidinfo, -size, 0);
604 		if (cpipe->pipe_buffer.buffer == NULL &&
605 		    size > SMALL_PIPE_SIZE) {
606 			size = SMALL_PIPE_SIZE;
607 			pipefragretry++;
608 			goto retry;
609 		}
610 		return (ENOMEM);
611 	}
612 	error = vm_map_find_locked(pipe_map, NULL, 0, (vm_offset_t *)&buffer,
613 	    size, 0, VMFS_ANY_SPACE, VM_PROT_RW, VM_PROT_RW, 0);
614 	vm_map_unlock(pipe_map);
615 	if (error != KERN_SUCCESS) {
616 		chgpipecnt(cpipe->pipe_pair->pp_owner->cr_ruidinfo, -size, 0);
617 		if (cpipe->pipe_buffer.buffer == NULL &&
618 		    size > SMALL_PIPE_SIZE) {
619 			size = SMALL_PIPE_SIZE;
620 			pipefragretry++;
621 			goto retry;
622 		}
623 		if (cpipe->pipe_buffer.buffer == NULL) {
624 			pipeallocfail++;
625 			if (ppsratecheck(&lastfail, &curfail, 1))
626 				printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
627 		} else {
628 			piperesizefail++;
629 		}
630 		return (ENOMEM);
631 	}
632 
633 	/* copy data, then free old resources if we're resizing */
634 	if (cnt > 0) {
635 		if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
636 			firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
637 			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
638 				buffer, firstseg);
639 			if ((cnt - firstseg) > 0)
640 				bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
641 					cpipe->pipe_buffer.in);
642 		} else {
643 			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
644 				buffer, cnt);
645 		}
646 	}
647 	pipe_free_kmem(cpipe);
648 	cpipe->pipe_buffer.buffer = buffer;
649 	cpipe->pipe_buffer.size = size;
650 	cpipe->pipe_buffer.in = cnt;
651 	cpipe->pipe_buffer.out = 0;
652 	cpipe->pipe_buffer.cnt = cnt;
653 	atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
654 	return (0);
655 }
656 
657 /*
658  * Wrapper for pipespace_new() that performs locking assertions.
659  */
660 static int
pipespace(struct pipe * cpipe,int size)661 pipespace(struct pipe *cpipe, int size)
662 {
663 
664 	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
665 	    ("Unlocked pipe passed to pipespace"));
666 	return (pipespace_new(cpipe, size));
667 }
668 
669 /*
670  * lock a pipe for I/O, blocking other access
671  */
672 static __inline int
pipelock(struct pipe * cpipe,bool catch)673 pipelock(struct pipe *cpipe, bool catch)
674 {
675 	int error, prio;
676 
677 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
678 
679 	prio = PRIBIO;
680 	if (catch)
681 		prio |= PCATCH;
682 	while (cpipe->pipe_state & PIPE_LOCKFL) {
683 		KASSERT(cpipe->pipe_waiters >= 0,
684 		    ("%s: bad waiter count %d", __func__,
685 		    cpipe->pipe_waiters));
686 		cpipe->pipe_waiters++;
687 		error = msleep(&cpipe->pipe_waiters, PIPE_MTX(cpipe), prio,
688 		    "pipelk", 0);
689 		cpipe->pipe_waiters--;
690 		if (error != 0)
691 			return (error);
692 	}
693 	cpipe->pipe_state |= PIPE_LOCKFL;
694 	return (0);
695 }
696 
697 /*
698  * unlock a pipe I/O lock
699  */
700 static __inline void
pipeunlock(struct pipe * cpipe)701 pipeunlock(struct pipe *cpipe)
702 {
703 
704 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
705 	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
706 		("Unlocked pipe passed to pipeunlock"));
707 	KASSERT(cpipe->pipe_waiters >= 0,
708 	    ("%s: bad waiter count %d", __func__,
709 	    cpipe->pipe_waiters));
710 	cpipe->pipe_state &= ~PIPE_LOCKFL;
711 	if (cpipe->pipe_waiters > 0)
712 		wakeup_one(&cpipe->pipe_waiters);
713 }
714 
715 void
pipeselwakeup(struct pipe * cpipe)716 pipeselwakeup(struct pipe *cpipe)
717 {
718 
719 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
720 	if (cpipe->pipe_state & PIPE_SEL) {
721 		selwakeuppri(&cpipe->pipe_sel, PSOCK);
722 		if (!SEL_WAITING(&cpipe->pipe_sel))
723 			cpipe->pipe_state &= ~PIPE_SEL;
724 	}
725 	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
726 		pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
727 	KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
728 }
729 
730 /*
731  * Initialize and allocate VM and memory for pipe.  The structure
732  * will start out zero'd from the ctor, so we just manage the kmem.
733  */
734 static int
pipe_create(struct pipe * pipe,bool large_backing)735 pipe_create(struct pipe *pipe, bool large_backing)
736 {
737 	int error;
738 
739 	error = pipespace_new(pipe, !large_backing || amountpipekva >
740 	    maxpipekva / 2 ? SMALL_PIPE_SIZE : PIPE_SIZE);
741 	if (error == 0)
742 		pipe->pipe_ino = alloc_unr64(&pipeino_unr);
743 	return (error);
744 }
745 
746 /* ARGSUSED */
747 static int
pipe_read(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)748 pipe_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
749     int flags, struct thread *td)
750 {
751 	struct pipe *rpipe;
752 	int error;
753 	int nread = 0;
754 	int size;
755 
756 	rpipe = fp->f_data;
757 
758 	/*
759 	 * Try to avoid locking the pipe if we have nothing to do.
760 	 *
761 	 * There are programs which share one pipe amongst multiple processes
762 	 * and perform non-blocking reads in parallel, even if the pipe is
763 	 * empty.  This in particular is the case with BSD make, which when
764 	 * spawned with a high -j number can find itself with over half of the
765 	 * calls failing to find anything.
766 	 */
767 	if ((fp->f_flag & FNONBLOCK) != 0 && !mac_pipe_check_read_enabled()) {
768 		if (__predict_false(uio->uio_resid == 0))
769 			return (0);
770 		if ((atomic_load_short(&rpipe->pipe_state) & PIPE_EOF) == 0 &&
771 		    atomic_load_int(&rpipe->pipe_buffer.cnt) == 0 &&
772 		    atomic_load_int(&rpipe->pipe_pages.cnt) == 0)
773 			return (EAGAIN);
774 	}
775 
776 	PIPE_LOCK(rpipe);
777 	++rpipe->pipe_busy;
778 	error = pipelock(rpipe, true);
779 	if (error)
780 		goto unlocked_error;
781 
782 #ifdef MAC
783 	error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
784 	if (error)
785 		goto locked_error;
786 #endif
787 	if (amountpipekva > (3 * maxpipekva) / 4) {
788 		if ((rpipe->pipe_state & PIPE_DIRECTW) == 0 &&
789 		    rpipe->pipe_buffer.size > SMALL_PIPE_SIZE &&
790 		    rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE &&
791 		    piperesizeallowed == 1) {
792 			PIPE_UNLOCK(rpipe);
793 			pipespace(rpipe, SMALL_PIPE_SIZE);
794 			PIPE_LOCK(rpipe);
795 		}
796 	}
797 
798 	while (uio->uio_resid) {
799 		/*
800 		 * normal pipe buffer receive
801 		 */
802 		if (rpipe->pipe_buffer.cnt > 0) {
803 			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
804 			if (size > rpipe->pipe_buffer.cnt)
805 				size = rpipe->pipe_buffer.cnt;
806 			if (size > uio->uio_resid)
807 				size = uio->uio_resid;
808 
809 			PIPE_UNLOCK(rpipe);
810 			error = uiomove(
811 			    &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
812 			    size, uio);
813 			PIPE_LOCK(rpipe);
814 			if (error)
815 				break;
816 
817 			rpipe->pipe_buffer.out += size;
818 			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
819 				rpipe->pipe_buffer.out = 0;
820 
821 			rpipe->pipe_buffer.cnt -= size;
822 
823 			/*
824 			 * If there is no more to read in the pipe, reset
825 			 * its pointers to the beginning.  This improves
826 			 * cache hit stats.
827 			 */
828 			if (rpipe->pipe_buffer.cnt == 0) {
829 				rpipe->pipe_buffer.in = 0;
830 				rpipe->pipe_buffer.out = 0;
831 			}
832 			nread += size;
833 #ifndef PIPE_NODIRECT
834 		/*
835 		 * Direct copy, bypassing a kernel buffer.
836 		 */
837 		} else if ((size = rpipe->pipe_pages.cnt) != 0) {
838 			if (size > uio->uio_resid)
839 				size = (u_int) uio->uio_resid;
840 			PIPE_UNLOCK(rpipe);
841 			error = uiomove_fromphys(rpipe->pipe_pages.ms,
842 			    rpipe->pipe_pages.pos, size, uio);
843 			PIPE_LOCK(rpipe);
844 			if (error)
845 				break;
846 			nread += size;
847 			rpipe->pipe_pages.pos += size;
848 			rpipe->pipe_pages.cnt -= size;
849 			if (rpipe->pipe_pages.cnt == 0) {
850 				rpipe->pipe_state &= ~PIPE_WANTW;
851 				wakeup(rpipe);
852 			}
853 #endif
854 		} else {
855 			/*
856 			 * detect EOF condition
857 			 * read returns 0 on EOF, no need to set error
858 			 */
859 			if (rpipe->pipe_state & PIPE_EOF)
860 				break;
861 
862 			/*
863 			 * If the "write-side" has been blocked, wake it up now.
864 			 */
865 			if (rpipe->pipe_state & PIPE_WANTW) {
866 				rpipe->pipe_state &= ~PIPE_WANTW;
867 				wakeup(rpipe);
868 			}
869 
870 			/*
871 			 * Break if some data was read.
872 			 */
873 			if (nread > 0)
874 				break;
875 
876 			/*
877 			 * Unlock the pipe buffer for our remaining processing.
878 			 * We will either break out with an error or we will
879 			 * sleep and relock to loop.
880 			 */
881 			pipeunlock(rpipe);
882 
883 			/*
884 			 * Handle non-blocking mode operation or
885 			 * wait for more data.
886 			 */
887 			if (fp->f_flag & FNONBLOCK) {
888 				error = EAGAIN;
889 			} else {
890 				rpipe->pipe_state |= PIPE_WANTR;
891 				if ((error = msleep(rpipe, PIPE_MTX(rpipe),
892 				    PRIBIO | PCATCH,
893 				    "piperd", 0)) == 0)
894 					error = pipelock(rpipe, true);
895 			}
896 			if (error)
897 				goto unlocked_error;
898 		}
899 	}
900 #ifdef MAC
901 locked_error:
902 #endif
903 	pipeunlock(rpipe);
904 
905 	/* XXX: should probably do this before getting any locks. */
906 	if (error == 0)
907 		pipe_timestamp(&rpipe->pipe_atime);
908 unlocked_error:
909 	--rpipe->pipe_busy;
910 
911 	/*
912 	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
913 	 */
914 	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
915 		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
916 		wakeup(rpipe);
917 	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
918 		/*
919 		 * Handle write blocking hysteresis.
920 		 */
921 		if (rpipe->pipe_state & PIPE_WANTW) {
922 			rpipe->pipe_state &= ~PIPE_WANTW;
923 			wakeup(rpipe);
924 		}
925 	}
926 
927 	/*
928 	 * Only wake up writers if there was actually something read.
929 	 * Otherwise, when calling read(2) at EOF, a spurious wakeup occurs.
930 	 */
931 	if (nread > 0 &&
932 	    rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt >= PIPE_BUF)
933 		pipeselwakeup(rpipe);
934 
935 	PIPE_UNLOCK(rpipe);
936 	if (nread > 0)
937 		td->td_ru.ru_msgrcv++;
938 	return (error);
939 }
940 
941 #ifndef PIPE_NODIRECT
942 /*
943  * Map the sending processes' buffer into kernel space and wire it.
944  * This is similar to a physical write operation.
945  */
946 static int
pipe_build_write_buffer(struct pipe * wpipe,struct uio * uio)947 pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio)
948 {
949 	u_int size;
950 	int i;
951 
952 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
953 	KASSERT((wpipe->pipe_state & PIPE_DIRECTW) == 0,
954 	    ("%s: PIPE_DIRECTW set on %p", __func__, wpipe));
955 	KASSERT(wpipe->pipe_pages.cnt == 0,
956 	    ("%s: pipe map for %p contains residual data", __func__, wpipe));
957 
958 	if (uio->uio_iov->iov_len > wpipe->pipe_buffer.size)
959                 size = wpipe->pipe_buffer.size;
960 	else
961                 size = uio->uio_iov->iov_len;
962 
963 	wpipe->pipe_state |= PIPE_DIRECTW;
964 	PIPE_UNLOCK(wpipe);
965 	i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
966 	    (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
967 	    wpipe->pipe_pages.ms, PIPENPAGES);
968 	PIPE_LOCK(wpipe);
969 	if (i < 0) {
970 		wpipe->pipe_state &= ~PIPE_DIRECTW;
971 		return (EFAULT);
972 	}
973 
974 	wpipe->pipe_pages.npages = i;
975 	wpipe->pipe_pages.pos =
976 	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
977 	wpipe->pipe_pages.cnt = size;
978 
979 	uio->uio_iov->iov_len -= size;
980 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
981 	if (uio->uio_iov->iov_len == 0) {
982 		uio->uio_iov++;
983 		uio->uio_iovcnt--;
984 	}
985 	uio->uio_resid -= size;
986 	uio->uio_offset += size;
987 	return (0);
988 }
989 
990 /*
991  * Unwire the process buffer.
992  */
993 static void
pipe_destroy_write_buffer(struct pipe * wpipe)994 pipe_destroy_write_buffer(struct pipe *wpipe)
995 {
996 
997 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
998 	KASSERT((wpipe->pipe_state & PIPE_DIRECTW) != 0,
999 	    ("%s: PIPE_DIRECTW not set on %p", __func__, wpipe));
1000 	KASSERT(wpipe->pipe_pages.cnt == 0,
1001 	    ("%s: pipe map for %p contains residual data", __func__, wpipe));
1002 
1003 	wpipe->pipe_state &= ~PIPE_DIRECTW;
1004 	vm_page_unhold_pages(wpipe->pipe_pages.ms, wpipe->pipe_pages.npages);
1005 	wpipe->pipe_pages.npages = 0;
1006 }
1007 
1008 /*
1009  * In the case of a signal, the writing process might go away.  This
1010  * code copies the data into the circular buffer so that the source
1011  * pages can be freed without loss of data.
1012  */
1013 static void
pipe_clone_write_buffer(struct pipe * wpipe)1014 pipe_clone_write_buffer(struct pipe *wpipe)
1015 {
1016 	struct uio uio;
1017 	struct iovec iov;
1018 	int size;
1019 	int pos;
1020 
1021 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
1022 	KASSERT((wpipe->pipe_state & PIPE_DIRECTW) != 0,
1023 	    ("%s: PIPE_DIRECTW not set on %p", __func__, wpipe));
1024 
1025 	size = wpipe->pipe_pages.cnt;
1026 	pos = wpipe->pipe_pages.pos;
1027 	wpipe->pipe_pages.cnt = 0;
1028 
1029 	wpipe->pipe_buffer.in = size;
1030 	wpipe->pipe_buffer.out = 0;
1031 	wpipe->pipe_buffer.cnt = size;
1032 
1033 	PIPE_UNLOCK(wpipe);
1034 	iov.iov_base = wpipe->pipe_buffer.buffer;
1035 	iov.iov_len = size;
1036 	uio.uio_iov = &iov;
1037 	uio.uio_iovcnt = 1;
1038 	uio.uio_offset = 0;
1039 	uio.uio_resid = size;
1040 	uio.uio_segflg = UIO_SYSSPACE;
1041 	uio.uio_rw = UIO_READ;
1042 	uio.uio_td = curthread;
1043 	uiomove_fromphys(wpipe->pipe_pages.ms, pos, size, &uio);
1044 	PIPE_LOCK(wpipe);
1045 	pipe_destroy_write_buffer(wpipe);
1046 }
1047 
1048 /*
1049  * This implements the pipe buffer write mechanism.  Note that only
1050  * a direct write OR a normal pipe write can be pending at any given time.
1051  * If there are any characters in the pipe buffer, the direct write will
1052  * be deferred until the receiving process grabs all of the bytes from
1053  * the pipe buffer.  Then the direct mapping write is set-up.
1054  */
1055 static int
pipe_direct_write(struct pipe * wpipe,struct uio * uio)1056 pipe_direct_write(struct pipe *wpipe, struct uio *uio)
1057 {
1058 	int error;
1059 
1060 retry:
1061 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
1062 	if ((wpipe->pipe_state & PIPE_EOF) != 0) {
1063 		error = EPIPE;
1064 		goto error1;
1065 	}
1066 	if (wpipe->pipe_state & PIPE_DIRECTW) {
1067 		if (wpipe->pipe_state & PIPE_WANTR) {
1068 			wpipe->pipe_state &= ~PIPE_WANTR;
1069 			wakeup(wpipe);
1070 		}
1071 		pipeselwakeup(wpipe);
1072 		wpipe->pipe_state |= PIPE_WANTW;
1073 		pipeunlock(wpipe);
1074 		error = msleep(wpipe, PIPE_MTX(wpipe),
1075 		    PRIBIO | PCATCH, "pipdww", 0);
1076 		pipelock(wpipe, false);
1077 		if (error != 0)
1078 			goto error1;
1079 		goto retry;
1080 	}
1081 	if (wpipe->pipe_buffer.cnt > 0) {
1082 		if (wpipe->pipe_state & PIPE_WANTR) {
1083 			wpipe->pipe_state &= ~PIPE_WANTR;
1084 			wakeup(wpipe);
1085 		}
1086 		pipeselwakeup(wpipe);
1087 		wpipe->pipe_state |= PIPE_WANTW;
1088 		pipeunlock(wpipe);
1089 		error = msleep(wpipe, PIPE_MTX(wpipe),
1090 		    PRIBIO | PCATCH, "pipdwc", 0);
1091 		pipelock(wpipe, false);
1092 		if (error != 0)
1093 			goto error1;
1094 		goto retry;
1095 	}
1096 
1097 	error = pipe_build_write_buffer(wpipe, uio);
1098 	if (error) {
1099 		goto error1;
1100 	}
1101 
1102 	while (wpipe->pipe_pages.cnt != 0 &&
1103 	    (wpipe->pipe_state & PIPE_EOF) == 0) {
1104 		if (wpipe->pipe_state & PIPE_WANTR) {
1105 			wpipe->pipe_state &= ~PIPE_WANTR;
1106 			wakeup(wpipe);
1107 		}
1108 		pipeselwakeup(wpipe);
1109 		wpipe->pipe_state |= PIPE_WANTW;
1110 		pipeunlock(wpipe);
1111 		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
1112 		    "pipdwt", 0);
1113 		pipelock(wpipe, false);
1114 		if (error != 0)
1115 			break;
1116 	}
1117 
1118 	if ((wpipe->pipe_state & PIPE_EOF) != 0) {
1119 		wpipe->pipe_pages.cnt = 0;
1120 		pipe_destroy_write_buffer(wpipe);
1121 		pipeselwakeup(wpipe);
1122 		error = EPIPE;
1123 	} else if (error == EINTR || error == ERESTART) {
1124 		pipe_clone_write_buffer(wpipe);
1125 	} else {
1126 		pipe_destroy_write_buffer(wpipe);
1127 	}
1128 	KASSERT((wpipe->pipe_state & PIPE_DIRECTW) == 0,
1129 	    ("pipe %p leaked PIPE_DIRECTW", wpipe));
1130 	return (error);
1131 
1132 error1:
1133 	wakeup(wpipe);
1134 	return (error);
1135 }
1136 #endif
1137 
1138 static int
pipe_write(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1139 pipe_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1140     int flags, struct thread *td)
1141 {
1142 	struct pipe *wpipe, *rpipe;
1143 	ssize_t orig_resid;
1144 	int desiredsize, error;
1145 
1146 	rpipe = fp->f_data;
1147 	wpipe = PIPE_PEER(rpipe);
1148 	PIPE_LOCK(rpipe);
1149 	error = pipelock(wpipe, true);
1150 	if (error) {
1151 		PIPE_UNLOCK(rpipe);
1152 		return (error);
1153 	}
1154 	/*
1155 	 * detect loss of pipe read side, issue SIGPIPE if lost.
1156 	 */
1157 	if (wpipe->pipe_present != PIPE_ACTIVE ||
1158 	    (wpipe->pipe_state & PIPE_EOF)) {
1159 		pipeunlock(wpipe);
1160 		PIPE_UNLOCK(rpipe);
1161 		return (EPIPE);
1162 	}
1163 #ifdef MAC
1164 	error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
1165 	if (error) {
1166 		pipeunlock(wpipe);
1167 		PIPE_UNLOCK(rpipe);
1168 		return (error);
1169 	}
1170 #endif
1171 	++wpipe->pipe_busy;
1172 
1173 	/* Choose a larger size if it's advantageous */
1174 	desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1175 	while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1176 		if (piperesizeallowed != 1)
1177 			break;
1178 		if (amountpipekva > maxpipekva / 2)
1179 			break;
1180 		if (desiredsize == BIG_PIPE_SIZE)
1181 			break;
1182 		desiredsize = desiredsize * 2;
1183 	}
1184 
1185 	/* Choose a smaller size if we're in a OOM situation */
1186 	if (amountpipekva > (3 * maxpipekva) / 4 &&
1187 	    wpipe->pipe_buffer.size > SMALL_PIPE_SIZE &&
1188 	    wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE &&
1189 	    piperesizeallowed == 1)
1190 		desiredsize = SMALL_PIPE_SIZE;
1191 
1192 	/* Resize if the above determined that a new size was necessary */
1193 	if (desiredsize != wpipe->pipe_buffer.size &&
1194 	    (wpipe->pipe_state & PIPE_DIRECTW) == 0) {
1195 		PIPE_UNLOCK(wpipe);
1196 		pipespace(wpipe, desiredsize);
1197 		PIPE_LOCK(wpipe);
1198 	}
1199 	MPASS(wpipe->pipe_buffer.size != 0);
1200 
1201 	orig_resid = uio->uio_resid;
1202 
1203 	while (uio->uio_resid) {
1204 		int space;
1205 
1206 		if (wpipe->pipe_state & PIPE_EOF) {
1207 			error = EPIPE;
1208 			break;
1209 		}
1210 #ifndef PIPE_NODIRECT
1211 		/*
1212 		 * If the transfer is large, we can gain performance if
1213 		 * we do process-to-process copies directly.
1214 		 * If the write is non-blocking, we don't use the
1215 		 * direct write mechanism.
1216 		 *
1217 		 * The direct write mechanism will detect the reader going
1218 		 * away on us.
1219 		 */
1220 		if (uio->uio_segflg == UIO_USERSPACE &&
1221 		    uio->uio_iov->iov_len >= pipe_mindirect &&
1222 		    wpipe->pipe_buffer.size >= pipe_mindirect &&
1223 		    (fp->f_flag & FNONBLOCK) == 0) {
1224 			error = pipe_direct_write(wpipe, uio);
1225 			if (error != 0)
1226 				break;
1227 			continue;
1228 		}
1229 #endif
1230 
1231 		/*
1232 		 * Pipe buffered writes cannot be coincidental with
1233 		 * direct writes.  We wait until the currently executing
1234 		 * direct write is completed before we start filling the
1235 		 * pipe buffer.  We break out if a signal occurs or the
1236 		 * reader goes away.
1237 		 */
1238 		if (wpipe->pipe_pages.cnt != 0) {
1239 			if (wpipe->pipe_state & PIPE_WANTR) {
1240 				wpipe->pipe_state &= ~PIPE_WANTR;
1241 				wakeup(wpipe);
1242 			}
1243 			pipeselwakeup(wpipe);
1244 			wpipe->pipe_state |= PIPE_WANTW;
1245 			pipeunlock(wpipe);
1246 			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1247 			    "pipbww", 0);
1248 			pipelock(wpipe, false);
1249 			if (error != 0)
1250 				break;
1251 			continue;
1252 		}
1253 
1254 		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1255 
1256 		/* Writes of size <= PIPE_BUF must be atomic. */
1257 		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1258 			space = 0;
1259 
1260 		if (space > 0) {
1261 			int size;	/* Transfer size */
1262 			int segsize;	/* first segment to transfer */
1263 
1264 			/*
1265 			 * Transfer size is minimum of uio transfer
1266 			 * and free space in pipe buffer.
1267 			 */
1268 			if (space > uio->uio_resid)
1269 				size = uio->uio_resid;
1270 			else
1271 				size = space;
1272 			/*
1273 			 * First segment to transfer is minimum of
1274 			 * transfer size and contiguous space in
1275 			 * pipe buffer.  If first segment to transfer
1276 			 * is less than the transfer size, we've got
1277 			 * a wraparound in the buffer.
1278 			 */
1279 			segsize = wpipe->pipe_buffer.size -
1280 				wpipe->pipe_buffer.in;
1281 			if (segsize > size)
1282 				segsize = size;
1283 
1284 			/* Transfer first segment */
1285 
1286 			PIPE_UNLOCK(rpipe);
1287 			error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1288 					segsize, uio);
1289 			PIPE_LOCK(rpipe);
1290 
1291 			if (error == 0 && segsize < size) {
1292 				KASSERT(wpipe->pipe_buffer.in + segsize ==
1293 					wpipe->pipe_buffer.size,
1294 					("Pipe buffer wraparound disappeared"));
1295 				/*
1296 				 * Transfer remaining part now, to
1297 				 * support atomic writes.  Wraparound
1298 				 * happened.
1299 				 */
1300 
1301 				PIPE_UNLOCK(rpipe);
1302 				error = uiomove(
1303 				    &wpipe->pipe_buffer.buffer[0],
1304 				    size - segsize, uio);
1305 				PIPE_LOCK(rpipe);
1306 			}
1307 			if (error == 0) {
1308 				wpipe->pipe_buffer.in += size;
1309 				if (wpipe->pipe_buffer.in >=
1310 				    wpipe->pipe_buffer.size) {
1311 					KASSERT(wpipe->pipe_buffer.in ==
1312 						size - segsize +
1313 						wpipe->pipe_buffer.size,
1314 						("Expected wraparound bad"));
1315 					wpipe->pipe_buffer.in = size - segsize;
1316 				}
1317 
1318 				wpipe->pipe_buffer.cnt += size;
1319 				KASSERT(wpipe->pipe_buffer.cnt <=
1320 					wpipe->pipe_buffer.size,
1321 					("Pipe buffer overflow"));
1322 			}
1323 			if (error != 0)
1324 				break;
1325 			continue;
1326 		} else {
1327 			/*
1328 			 * If the "read-side" has been blocked, wake it up now.
1329 			 */
1330 			if (wpipe->pipe_state & PIPE_WANTR) {
1331 				wpipe->pipe_state &= ~PIPE_WANTR;
1332 				wakeup(wpipe);
1333 			}
1334 
1335 			/*
1336 			 * don't block on non-blocking I/O
1337 			 */
1338 			if (fp->f_flag & FNONBLOCK) {
1339 				error = EAGAIN;
1340 				break;
1341 			}
1342 
1343 			/*
1344 			 * We have no more space and have something to offer,
1345 			 * wake up select/poll.
1346 			 */
1347 			pipeselwakeup(wpipe);
1348 
1349 			wpipe->pipe_state |= PIPE_WANTW;
1350 			pipeunlock(wpipe);
1351 			error = msleep(wpipe, PIPE_MTX(rpipe),
1352 			    PRIBIO | PCATCH, "pipewr", 0);
1353 			pipelock(wpipe, false);
1354 			if (error != 0)
1355 				break;
1356 			continue;
1357 		}
1358 	}
1359 
1360 	--wpipe->pipe_busy;
1361 
1362 	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1363 		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1364 		wakeup(wpipe);
1365 	} else if (wpipe->pipe_buffer.cnt > 0) {
1366 		/*
1367 		 * If we have put any characters in the buffer, we wake up
1368 		 * the reader.
1369 		 */
1370 		if (wpipe->pipe_state & PIPE_WANTR) {
1371 			wpipe->pipe_state &= ~PIPE_WANTR;
1372 			wakeup(wpipe);
1373 		}
1374 	}
1375 
1376 	/*
1377 	 * Don't return EPIPE if any byte was written.
1378 	 * EINTR and other interrupts are handled by generic I/O layer.
1379 	 * Do not pretend that I/O succeeded for obvious user error
1380 	 * like EFAULT.
1381 	 */
1382 	if (uio->uio_resid != orig_resid && error == EPIPE)
1383 		error = 0;
1384 
1385 	if (error == 0)
1386 		pipe_timestamp(&wpipe->pipe_mtime);
1387 
1388 	/*
1389 	 * We have something to offer,
1390 	 * wake up select/poll.
1391 	 */
1392 	if (wpipe->pipe_buffer.cnt)
1393 		pipeselwakeup(wpipe);
1394 
1395 	pipeunlock(wpipe);
1396 	PIPE_UNLOCK(rpipe);
1397 	if (uio->uio_resid != orig_resid)
1398 		td->td_ru.ru_msgsnd++;
1399 	return (error);
1400 }
1401 
1402 /* ARGSUSED */
1403 static int
pipe_truncate(struct file * fp,off_t length,struct ucred * active_cred,struct thread * td)1404 pipe_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1405     struct thread *td)
1406 {
1407 	struct pipe *cpipe;
1408 	int error;
1409 
1410 	cpipe = fp->f_data;
1411 	if (cpipe->pipe_type & PIPE_TYPE_NAMED)
1412 		error = vnops.fo_truncate(fp, length, active_cred, td);
1413 	else
1414 		error = invfo_truncate(fp, length, active_cred, td);
1415 	return (error);
1416 }
1417 
1418 /*
1419  * we implement a very minimal set of ioctls for compatibility with sockets.
1420  */
1421 static int
pipe_ioctl(struct file * fp,u_long cmd,void * data,struct ucred * active_cred,struct thread * td)1422 pipe_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *active_cred,
1423     struct thread *td)
1424 {
1425 	struct pipe *mpipe = fp->f_data;
1426 	int error;
1427 
1428 	PIPE_LOCK(mpipe);
1429 
1430 #ifdef MAC
1431 	error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1432 	if (error) {
1433 		PIPE_UNLOCK(mpipe);
1434 		return (error);
1435 	}
1436 #endif
1437 
1438 	error = 0;
1439 	switch (cmd) {
1440 	case FIONBIO:
1441 		break;
1442 
1443 	case FIOASYNC:
1444 		if (*(int *)data) {
1445 			mpipe->pipe_state |= PIPE_ASYNC;
1446 		} else {
1447 			mpipe->pipe_state &= ~PIPE_ASYNC;
1448 		}
1449 		break;
1450 
1451 	case FIONREAD:
1452 		if (!(fp->f_flag & FREAD)) {
1453 			*(int *)data = 0;
1454 			PIPE_UNLOCK(mpipe);
1455 			return (0);
1456 		}
1457 		if (mpipe->pipe_pages.cnt != 0)
1458 			*(int *)data = mpipe->pipe_pages.cnt;
1459 		else
1460 			*(int *)data = mpipe->pipe_buffer.cnt;
1461 		break;
1462 
1463 	case FIOSETOWN:
1464 		PIPE_UNLOCK(mpipe);
1465 		error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1466 		goto out_unlocked;
1467 
1468 	case FIOGETOWN:
1469 		*(int *)data = fgetown(&mpipe->pipe_sigio);
1470 		break;
1471 
1472 	/* This is deprecated, FIOSETOWN should be used instead. */
1473 	case TIOCSPGRP:
1474 		PIPE_UNLOCK(mpipe);
1475 		error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1476 		goto out_unlocked;
1477 
1478 	/* This is deprecated, FIOGETOWN should be used instead. */
1479 	case TIOCGPGRP:
1480 		*(int *)data = -fgetown(&mpipe->pipe_sigio);
1481 		break;
1482 
1483 	default:
1484 		error = ENOTTY;
1485 		break;
1486 	}
1487 	PIPE_UNLOCK(mpipe);
1488 out_unlocked:
1489 	return (error);
1490 }
1491 
1492 static int
pipe_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)1493 pipe_poll(struct file *fp, int events, struct ucred *active_cred,
1494     struct thread *td)
1495 {
1496 	struct pipe *rpipe;
1497 	struct pipe *wpipe;
1498 	int levents, revents;
1499 #ifdef MAC
1500 	int error;
1501 #endif
1502 
1503 	revents = 0;
1504 	rpipe = fp->f_data;
1505 	wpipe = PIPE_PEER(rpipe);
1506 	PIPE_LOCK(rpipe);
1507 #ifdef MAC
1508 	error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1509 	if (error)
1510 		goto locked_error;
1511 #endif
1512 	if (fp->f_flag & FREAD && events & (POLLIN | POLLRDNORM))
1513 		if (rpipe->pipe_pages.cnt > 0 || rpipe->pipe_buffer.cnt > 0)
1514 			revents |= events & (POLLIN | POLLRDNORM);
1515 
1516 	if (fp->f_flag & FWRITE && events & (POLLOUT | POLLWRNORM))
1517 		if (wpipe->pipe_present != PIPE_ACTIVE ||
1518 		    (wpipe->pipe_state & PIPE_EOF) ||
1519 		    ((wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
1520 		     ((wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF ||
1521 			 wpipe->pipe_buffer.size == 0)))
1522 			revents |= events & (POLLOUT | POLLWRNORM);
1523 
1524 	levents = events &
1525 	    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM | POLLRDBAND);
1526 	if (rpipe->pipe_type & PIPE_TYPE_NAMED && fp->f_flag & FREAD && levents &&
1527 	    fp->f_pipegen == rpipe->pipe_wgen)
1528 		events |= POLLINIGNEOF;
1529 
1530 	if ((events & POLLINIGNEOF) == 0) {
1531 		if (rpipe->pipe_state & PIPE_EOF) {
1532 			if (fp->f_flag & FREAD)
1533 				revents |= (events & (POLLIN | POLLRDNORM));
1534 			if (wpipe->pipe_present != PIPE_ACTIVE ||
1535 			    (wpipe->pipe_state & PIPE_EOF))
1536 				revents |= POLLHUP;
1537 		}
1538 	}
1539 
1540 	if (revents == 0) {
1541 		/*
1542 		 * Add ourselves regardless of eventmask as we have to return
1543 		 * POLLHUP even if it was not asked for.
1544 		 */
1545 		if ((fp->f_flag & FREAD) != 0) {
1546 			selrecord(td, &rpipe->pipe_sel);
1547 			if (SEL_WAITING(&rpipe->pipe_sel))
1548 				rpipe->pipe_state |= PIPE_SEL;
1549 		}
1550 
1551 		if ((fp->f_flag & FWRITE) != 0 &&
1552 		    wpipe->pipe_present == PIPE_ACTIVE) {
1553 			selrecord(td, &wpipe->pipe_sel);
1554 			if (SEL_WAITING(&wpipe->pipe_sel))
1555 				wpipe->pipe_state |= PIPE_SEL;
1556 		}
1557 	}
1558 #ifdef MAC
1559 locked_error:
1560 #endif
1561 	PIPE_UNLOCK(rpipe);
1562 
1563 	return (revents);
1564 }
1565 
1566 /*
1567  * We shouldn't need locks here as we're doing a read and this should
1568  * be a natural race.
1569  */
1570 static int
pipe_stat(struct file * fp,struct stat * ub,struct ucred * active_cred)1571 pipe_stat(struct file *fp, struct stat *ub, struct ucred *active_cred)
1572 {
1573 	struct pipe *pipe;
1574 #ifdef MAC
1575 	int error;
1576 #endif
1577 
1578 	pipe = fp->f_data;
1579 #ifdef MAC
1580 	if (mac_pipe_check_stat_enabled()) {
1581 		PIPE_LOCK(pipe);
1582 		error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1583 		PIPE_UNLOCK(pipe);
1584 		if (error) {
1585 			return (error);
1586 		}
1587 	}
1588 #endif
1589 
1590 	/* For named pipes ask the underlying filesystem. */
1591 	if (pipe->pipe_type & PIPE_TYPE_NAMED) {
1592 		return (vnops.fo_stat(fp, ub, active_cred));
1593 	}
1594 
1595 	bzero(ub, sizeof(*ub));
1596 	ub->st_mode = S_IFIFO;
1597 	ub->st_blksize = PAGE_SIZE;
1598 	if (pipe->pipe_pages.cnt != 0)
1599 		ub->st_size = pipe->pipe_pages.cnt;
1600 	else
1601 		ub->st_size = pipe->pipe_buffer.cnt;
1602 	ub->st_blocks = howmany(ub->st_size, ub->st_blksize);
1603 	ub->st_atim = pipe->pipe_atime;
1604 	ub->st_mtim = pipe->pipe_mtime;
1605 	ub->st_ctim = pipe->pipe_ctime;
1606 	ub->st_uid = fp->f_cred->cr_uid;
1607 	ub->st_gid = fp->f_cred->cr_gid;
1608 	ub->st_dev = pipedev_ino;
1609 	ub->st_ino = pipe->pipe_ino;
1610 	/*
1611 	 * Left as 0: st_nlink, st_rdev, st_flags, st_gen.
1612 	 */
1613 	return (0);
1614 }
1615 
1616 /* ARGSUSED */
1617 static int
pipe_close(struct file * fp,struct thread * td)1618 pipe_close(struct file *fp, struct thread *td)
1619 {
1620 
1621 	if (fp->f_vnode != NULL)
1622 		return vnops.fo_close(fp, td);
1623 	fp->f_ops = &badfileops;
1624 	pipe_dtor(fp->f_data);
1625 	fp->f_data = NULL;
1626 	return (0);
1627 }
1628 
1629 static int
pipe_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)1630 pipe_chmod(struct file *fp, mode_t mode, struct ucred *active_cred, struct thread *td)
1631 {
1632 	struct pipe *cpipe;
1633 	int error;
1634 
1635 	cpipe = fp->f_data;
1636 	if (cpipe->pipe_type & PIPE_TYPE_NAMED)
1637 		error = vn_chmod(fp, mode, active_cred, td);
1638 	else
1639 		error = invfo_chmod(fp, mode, active_cred, td);
1640 	return (error);
1641 }
1642 
1643 static int
pipe_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)1644 pipe_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
1645     struct thread *td)
1646 {
1647 	struct pipe *cpipe;
1648 	int error;
1649 
1650 	cpipe = fp->f_data;
1651 	if (cpipe->pipe_type & PIPE_TYPE_NAMED)
1652 		error = vn_chown(fp, uid, gid, active_cred, td);
1653 	else
1654 		error = invfo_chown(fp, uid, gid, active_cred, td);
1655 	return (error);
1656 }
1657 
1658 static int
pipe_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)1659 pipe_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1660 {
1661 	struct pipe *pi;
1662 
1663 	if (fp->f_type == DTYPE_FIFO)
1664 		return (vn_fill_kinfo(fp, kif, fdp));
1665 	kif->kf_type = KF_TYPE_PIPE;
1666 	pi = fp->f_data;
1667 	kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
1668 	kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
1669 	kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
1670 	kif->kf_un.kf_pipe.kf_pipe_buffer_in = pi->pipe_buffer.in;
1671 	kif->kf_un.kf_pipe.kf_pipe_buffer_out = pi->pipe_buffer.out;
1672 	kif->kf_un.kf_pipe.kf_pipe_buffer_size = pi->pipe_buffer.size;
1673 	return (0);
1674 }
1675 
1676 static void
pipe_free_kmem(struct pipe * cpipe)1677 pipe_free_kmem(struct pipe *cpipe)
1678 {
1679 
1680 	KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1681 	    ("pipe_free_kmem: pipe mutex locked"));
1682 
1683 	if (cpipe->pipe_buffer.buffer != NULL) {
1684 		atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1685 		chgpipecnt(cpipe->pipe_pair->pp_owner->cr_ruidinfo,
1686 		    -cpipe->pipe_buffer.size, 0);
1687 		vm_map_remove(pipe_map,
1688 		    (vm_offset_t)cpipe->pipe_buffer.buffer,
1689 		    (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1690 		cpipe->pipe_buffer.buffer = NULL;
1691 	}
1692 #ifndef PIPE_NODIRECT
1693 	{
1694 		cpipe->pipe_pages.cnt = 0;
1695 		cpipe->pipe_pages.pos = 0;
1696 		cpipe->pipe_pages.npages = 0;
1697 	}
1698 #endif
1699 }
1700 
1701 /*
1702  * shutdown the pipe
1703  */
1704 static void
pipeclose(struct pipe * cpipe)1705 pipeclose(struct pipe *cpipe)
1706 {
1707 #ifdef MAC
1708 	struct pipepair *pp;
1709 #endif
1710 	struct pipe *ppipe;
1711 
1712 	KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1713 
1714 	PIPE_LOCK(cpipe);
1715 	pipelock(cpipe, false);
1716 #ifdef MAC
1717 	pp = cpipe->pipe_pair;
1718 #endif
1719 
1720 	/*
1721 	 * If the other side is blocked, wake it up saying that
1722 	 * we want to close it down.
1723 	 */
1724 	cpipe->pipe_state |= PIPE_EOF;
1725 	while (cpipe->pipe_busy) {
1726 		wakeup(cpipe);
1727 		cpipe->pipe_state |= PIPE_WANT;
1728 		pipeunlock(cpipe);
1729 		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1730 		pipelock(cpipe, false);
1731 	}
1732 
1733 	pipeselwakeup(cpipe);
1734 
1735 	/*
1736 	 * Disconnect from peer, if any.
1737 	 */
1738 	ppipe = cpipe->pipe_peer;
1739 	if (ppipe->pipe_present == PIPE_ACTIVE) {
1740 		ppipe->pipe_state |= PIPE_EOF;
1741 		wakeup(ppipe);
1742 		pipeselwakeup(ppipe);
1743 	}
1744 
1745 	/*
1746 	 * Mark this endpoint as free.  Release kmem resources.  We
1747 	 * don't mark this endpoint as unused until we've finished
1748 	 * doing that, or the pipe might disappear out from under
1749 	 * us.
1750 	 */
1751 	PIPE_UNLOCK(cpipe);
1752 	pipe_free_kmem(cpipe);
1753 	PIPE_LOCK(cpipe);
1754 	cpipe->pipe_present = PIPE_CLOSING;
1755 	pipeunlock(cpipe);
1756 
1757 	/*
1758 	 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1759 	 * PIPE_FINALIZED, that allows other end to free the
1760 	 * pipe_pair, only after the knotes are completely dismantled.
1761 	 */
1762 	knlist_clear(&cpipe->pipe_sel.si_note, 1);
1763 	cpipe->pipe_present = PIPE_FINALIZED;
1764 	seldrain(&cpipe->pipe_sel);
1765 	knlist_destroy(&cpipe->pipe_sel.si_note);
1766 
1767 	/*
1768 	 * If both endpoints are now closed, release the memory for the
1769 	 * pipe pair.  If not, unlock.
1770 	 */
1771 	if (ppipe->pipe_present == PIPE_FINALIZED) {
1772 		PIPE_UNLOCK(cpipe);
1773 		crfree(cpipe->pipe_pair->pp_owner);
1774 #ifdef MAC
1775 		mac_pipe_destroy(pp);
1776 #endif
1777 		uma_zfree(pipe_zone, cpipe->pipe_pair);
1778 	} else
1779 		PIPE_UNLOCK(cpipe);
1780 }
1781 
1782 /*ARGSUSED*/
1783 static int
pipe_kqfilter(struct file * fp,struct knote * kn)1784 pipe_kqfilter(struct file *fp, struct knote *kn)
1785 {
1786 	struct pipe *cpipe;
1787 
1788 	/*
1789 	 * If a filter is requested that is not supported by this file
1790 	 * descriptor, don't return an error, but also don't ever generate an
1791 	 * event.
1792 	 */
1793 	if ((kn->kn_filter == EVFILT_READ) && !(fp->f_flag & FREAD)) {
1794 		kn->kn_fop = &pipe_nfiltops;
1795 		return (0);
1796 	}
1797 	if ((kn->kn_filter == EVFILT_WRITE) && !(fp->f_flag & FWRITE)) {
1798 		kn->kn_fop = &pipe_nfiltops;
1799 		return (0);
1800 	}
1801 	cpipe = fp->f_data;
1802 	PIPE_LOCK(cpipe);
1803 	switch (kn->kn_filter) {
1804 	case EVFILT_READ:
1805 		kn->kn_fop = &pipe_rfiltops;
1806 		break;
1807 	case EVFILT_WRITE:
1808 		kn->kn_fop = &pipe_wfiltops;
1809 		if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1810 			/* other end of pipe has been closed */
1811 			PIPE_UNLOCK(cpipe);
1812 			return (EPIPE);
1813 		}
1814 		cpipe = PIPE_PEER(cpipe);
1815 		break;
1816 	default:
1817 		if ((cpipe->pipe_type & PIPE_TYPE_NAMED) != 0) {
1818 			PIPE_UNLOCK(cpipe);
1819 			return (vnops.fo_kqfilter(fp, kn));
1820 		}
1821 		PIPE_UNLOCK(cpipe);
1822 		return (EINVAL);
1823 	}
1824 
1825 	kn->kn_hook = cpipe;
1826 	knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1827 	PIPE_UNLOCK(cpipe);
1828 	return (0);
1829 }
1830 
1831 static void
filt_pipedetach(struct knote * kn)1832 filt_pipedetach(struct knote *kn)
1833 {
1834 	struct pipe *cpipe = kn->kn_hook;
1835 
1836 	PIPE_LOCK(cpipe);
1837 	knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1838 	PIPE_UNLOCK(cpipe);
1839 }
1840 
1841 /*ARGSUSED*/
1842 static int
filt_piperead(struct knote * kn,long hint)1843 filt_piperead(struct knote *kn, long hint)
1844 {
1845 	struct file *fp = kn->kn_fp;
1846 	struct pipe *rpipe = kn->kn_hook;
1847 
1848 	PIPE_LOCK_ASSERT(rpipe, MA_OWNED);
1849 	kn->kn_data = rpipe->pipe_buffer.cnt;
1850 	if (kn->kn_data == 0)
1851 		kn->kn_data = rpipe->pipe_pages.cnt;
1852 
1853 	if ((rpipe->pipe_state & PIPE_EOF) != 0 &&
1854 	    ((rpipe->pipe_type & PIPE_TYPE_NAMED) == 0 ||
1855 	    fp->f_pipegen != rpipe->pipe_wgen)) {
1856 		kn->kn_flags |= EV_EOF;
1857 		return (1);
1858 	}
1859 	kn->kn_flags &= ~EV_EOF;
1860 	return (kn->kn_data > 0);
1861 }
1862 
1863 /*ARGSUSED*/
1864 static int
filt_pipewrite(struct knote * kn,long hint)1865 filt_pipewrite(struct knote *kn, long hint)
1866 {
1867 	struct pipe *wpipe = kn->kn_hook;
1868 
1869 	/*
1870 	 * If this end of the pipe is closed, the knote was removed from the
1871 	 * knlist and the list lock (i.e., the pipe lock) is therefore not held.
1872 	 */
1873 	if (wpipe->pipe_present == PIPE_ACTIVE ||
1874 	    (wpipe->pipe_type & PIPE_TYPE_NAMED) != 0) {
1875 		PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
1876 
1877 		if (wpipe->pipe_state & PIPE_DIRECTW) {
1878 			kn->kn_data = 0;
1879 		} else if (wpipe->pipe_buffer.size > 0) {
1880 			kn->kn_data = wpipe->pipe_buffer.size -
1881 			    wpipe->pipe_buffer.cnt;
1882 		} else {
1883 			kn->kn_data = PIPE_BUF;
1884 		}
1885 	}
1886 
1887 	if (wpipe->pipe_present != PIPE_ACTIVE ||
1888 	    (wpipe->pipe_state & PIPE_EOF)) {
1889 		kn->kn_flags |= EV_EOF;
1890 		return (1);
1891 	}
1892 	kn->kn_flags &= ~EV_EOF;
1893 	return (kn->kn_data >= PIPE_BUF);
1894 }
1895 
1896 static void
filt_pipedetach_notsup(struct knote * kn)1897 filt_pipedetach_notsup(struct knote *kn)
1898 {
1899 
1900 }
1901 
1902 static int
filt_pipenotsup(struct knote * kn,long hint)1903 filt_pipenotsup(struct knote *kn, long hint)
1904 {
1905 
1906 	return (0);
1907 }
1908 
1909 static int
filt_pipedump(struct proc * p,struct knote * kn,struct kinfo_knote * kin)1910 filt_pipedump(struct proc *p, struct knote *kn,
1911     struct kinfo_knote *kin)
1912 {
1913 	struct pipe *pipe = kn->kn_hook;
1914 
1915 	kin->knt_extdata = KNOTE_EXTDATA_PIPE;
1916 	kin->knt_pipe.knt_pipe_ino = pipe->pipe_ino;
1917 	return (0);
1918 }
1919