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