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