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