xref: /freebsd/sys/kern/sys_pipe.c (revision 82431678fce5c893ef9c7418ad6d998ad4187de6)
1 /*-
2  * Copyright (c) 1996 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Absolutely no warranty of function or purpose is made by the author
15  *    John S. Dyson.
16  * 4. Modifications may be freely made to this file if the above conditions
17  *    are met.
18  */
19 
20 /*
21  * This file contains a high-performance replacement for the socket-based
22  * pipes scheme originally used in FreeBSD/4.4Lite.  It does not support
23  * all features of sockets, but does do everything that pipes normally
24  * do.
25  */
26 
27 /*
28  * This code has two modes of operation, a small write mode and a large
29  * write mode.  The small write mode acts like conventional pipes with
30  * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
31  * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
32  * and PIPE_SIZE in size, it is fully mapped and wired into the kernel, and
33  * the receiving process can copy it directly from the pages in the sending
34  * process.
35  *
36  * If the sending process receives a signal, it is possible that it will
37  * go away, and certainly its address space can change, because control
38  * is returned back to the user-mode side.  In that case, the pipe code
39  * arranges to copy the buffer supplied by the user process, to a pageable
40  * kernel buffer, and the receiving process will grab the data from the
41  * pageable kernel buffer.  Since signals don't happen all that often,
42  * the copy operation is normally eliminated.
43  *
44  * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
45  * happen for small transfers so that the system will not spend all of
46  * its time context switching.
47  *
48  * In order to limit the resource use of pipes, two sysctls exist:
49  *
50  * kern.ipc.maxpipekva - This is a hard limit on the amount of pageable
51  * address space available to us in pipe_map. This value is normally
52  * autotuned, but may also be loader tuned.
53  *
54  * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
55  * memory in use by pipes.
56  *
57  * Based on how large pipekva is relative to maxpipekva, the following
58  * will happen:
59  *
60  * 0% - 50%:
61  *     New pipes are given 16K of memory backing, pipes may dynamically
62  *     grow to as large as 64K where needed.
63  * 50% - 75%:
64  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
65  *     existing pipes may NOT grow.
66  * 75% - 100%:
67  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
68  *     existing pipes will be shrunk down to 4K whenever possible.
69  *
70  * Resizing may be disabled by setting kern.ipc.piperesizeallowed=0.  If
71  * that is set,  the only resize that will occur is the 0 -> SMALL_PIPE_SIZE
72  * resize which MUST occur for reverse-direction pipes when they are
73  * first used.
74  *
75  * Additional information about the current state of pipes may be obtained
76  * from kern.ipc.pipes, kern.ipc.pipefragretry, kern.ipc.pipeallocfail,
77  * and kern.ipc.piperesizefail.
78  *
79  * Locking rules:  There are two locks present here:  A mutex, used via
80  * PIPE_LOCK, and a flag, used via pipelock().  All locking is done via
81  * the flag, as mutexes can not persist over uiomove.  The mutex
82  * exists only to guard access to the flag, and is not in itself a
83  * locking mechanism.  Also note that there is only a single mutex for
84  * both directions of a pipe.
85  *
86  * As pipelock() may have to sleep before it can acquire the flag, it
87  * is important to reread all data after a call to pipelock(); everything
88  * in the structure may have changed.
89  */
90 
91 #include <sys/cdefs.h>
92 __FBSDID("$FreeBSD$");
93 
94 #include "opt_mac.h"
95 
96 #include <sys/param.h>
97 #include <sys/systm.h>
98 #include <sys/fcntl.h>
99 #include <sys/file.h>
100 #include <sys/filedesc.h>
101 #include <sys/filio.h>
102 #include <sys/kernel.h>
103 #include <sys/lock.h>
104 #include <sys/mutex.h>
105 #include <sys/ttycom.h>
106 #include <sys/stat.h>
107 #include <sys/malloc.h>
108 #include <sys/poll.h>
109 #include <sys/selinfo.h>
110 #include <sys/signalvar.h>
111 #include <sys/syscallsubr.h>
112 #include <sys/sysctl.h>
113 #include <sys/sysproto.h>
114 #include <sys/pipe.h>
115 #include <sys/proc.h>
116 #include <sys/vnode.h>
117 #include <sys/uio.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 /*
140  * interfaces to the outside world
141  */
142 static fo_rdwr_t	pipe_read;
143 static fo_rdwr_t	pipe_write;
144 static fo_truncate_t	pipe_truncate;
145 static fo_ioctl_t	pipe_ioctl;
146 static fo_poll_t	pipe_poll;
147 static fo_kqfilter_t	pipe_kqfilter;
148 static fo_stat_t	pipe_stat;
149 static fo_close_t	pipe_close;
150 
151 static struct fileops pipeops = {
152 	.fo_read = pipe_read,
153 	.fo_write = pipe_write,
154 	.fo_truncate = pipe_truncate,
155 	.fo_ioctl = pipe_ioctl,
156 	.fo_poll = pipe_poll,
157 	.fo_kqfilter = pipe_kqfilter,
158 	.fo_stat = pipe_stat,
159 	.fo_close = pipe_close,
160 	.fo_flags = DFLAG_PASSABLE
161 };
162 
163 static void	filt_pipedetach(struct knote *kn);
164 static int	filt_piperead(struct knote *kn, long hint);
165 static int	filt_pipewrite(struct knote *kn, long hint);
166 
167 static struct filterops pipe_rfiltops =
168 	{ 1, NULL, filt_pipedetach, filt_piperead };
169 static struct filterops pipe_wfiltops =
170 	{ 1, NULL, filt_pipedetach, filt_pipewrite };
171 
172 /*
173  * Default pipe buffer size(s), this can be kind-of large now because pipe
174  * space is pageable.  The pipe code will try to maintain locality of
175  * reference for performance reasons, so small amounts of outstanding I/O
176  * will not wipe the cache.
177  */
178 #define MINPIPESIZE (PIPE_SIZE/3)
179 #define MAXPIPESIZE (2*PIPE_SIZE/3)
180 
181 static long amountpipekva;
182 static int pipefragretry;
183 static int pipeallocfail;
184 static int piperesizefail;
185 static int piperesizeallowed = 1;
186 
187 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
188 	   &maxpipekva, 0, "Pipe KVA limit");
189 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
190 	   &amountpipekva, 0, "Pipe KVA usage");
191 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
192 	  &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
193 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
194 	  &pipeallocfail, 0, "Pipe allocation failures");
195 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
196 	  &piperesizefail, 0, "Pipe resize failures");
197 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
198 	  &piperesizeallowed, 0, "Pipe resizing allowed");
199 
200 static void pipeinit(void *dummy __unused);
201 static void pipeclose(struct pipe *cpipe);
202 static void pipe_free_kmem(struct pipe *cpipe);
203 static int pipe_create(struct pipe *pipe, int backing);
204 static __inline int pipelock(struct pipe *cpipe, int catch);
205 static __inline void pipeunlock(struct pipe *cpipe);
206 static __inline void pipeselwakeup(struct pipe *cpipe);
207 #ifndef PIPE_NODIRECT
208 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
209 static void pipe_destroy_write_buffer(struct pipe *wpipe);
210 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
211 static void pipe_clone_write_buffer(struct pipe *wpipe);
212 #endif
213 static int pipespace(struct pipe *cpipe, int size);
214 static int pipespace_new(struct pipe *cpipe, int size);
215 
216 static int	pipe_zone_ctor(void *mem, int size, void *arg, int flags);
217 static int	pipe_zone_init(void *mem, int size, int flags);
218 static void	pipe_zone_fini(void *mem, int size);
219 
220 static uma_zone_t pipe_zone;
221 
222 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
223 
224 static void
225 pipeinit(void *dummy __unused)
226 {
227 
228 	pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
229 	    pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
230 	    UMA_ALIGN_PTR, 0);
231 	KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
232 }
233 
234 static int
235 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
236 {
237 	struct pipepair *pp;
238 	struct pipe *rpipe, *wpipe;
239 
240 	KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
241 
242 	pp = (struct pipepair *)mem;
243 
244 	/*
245 	 * We zero both pipe endpoints to make sure all the kmem pointers
246 	 * are NULL, flag fields are zero'd, etc.  We timestamp both
247 	 * endpoints with the same time.
248 	 */
249 	rpipe = &pp->pp_rpipe;
250 	bzero(rpipe, sizeof(*rpipe));
251 	vfs_timestamp(&rpipe->pipe_ctime);
252 	rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
253 
254 	wpipe = &pp->pp_wpipe;
255 	bzero(wpipe, sizeof(*wpipe));
256 	wpipe->pipe_ctime = rpipe->pipe_ctime;
257 	wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
258 
259 	rpipe->pipe_peer = wpipe;
260 	rpipe->pipe_pair = pp;
261 	wpipe->pipe_peer = rpipe;
262 	wpipe->pipe_pair = pp;
263 
264 	/*
265 	 * Mark both endpoints as present; they will later get free'd
266 	 * one at a time.  When both are free'd, then the whole pair
267 	 * is released.
268 	 */
269 	rpipe->pipe_present = PIPE_ACTIVE;
270 	wpipe->pipe_present = PIPE_ACTIVE;
271 
272 	/*
273 	 * Eventually, the MAC Framework may initialize the label
274 	 * in ctor or init, but for now we do it elswhere to avoid
275 	 * blocking in ctor or init.
276 	 */
277 	pp->pp_label = NULL;
278 
279 	return (0);
280 }
281 
282 static int
283 pipe_zone_init(void *mem, int size, int flags)
284 {
285 	struct pipepair *pp;
286 
287 	KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
288 
289 	pp = (struct pipepair *)mem;
290 
291 	mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
292 	return (0);
293 }
294 
295 static void
296 pipe_zone_fini(void *mem, int size)
297 {
298 	struct pipepair *pp;
299 
300 	KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
301 
302 	pp = (struct pipepair *)mem;
303 
304 	mtx_destroy(&pp->pp_mtx);
305 }
306 
307 /*
308  * The pipe system call for the DTYPE_PIPE type of pipes.  If we fail, let
309  * the zone pick up the pieces via pipeclose().
310  */
311 int
312 kern_pipe(struct thread *td, int fildes[2])
313 {
314 	struct filedesc *fdp = td->td_proc->p_fd;
315 	struct file *rf, *wf;
316 	struct pipepair *pp;
317 	struct pipe *rpipe, *wpipe;
318 	int fd, error;
319 
320 	pp = uma_zalloc(pipe_zone, M_WAITOK);
321 #ifdef MAC
322 	/*
323 	 * The MAC label is shared between the connected endpoints.  As a
324 	 * result mac_pipe_init() and mac_pipe_create() are called once
325 	 * for the pair, and not on the endpoints.
326 	 */
327 	mac_pipe_init(pp);
328 	mac_pipe_create(td->td_ucred, pp);
329 #endif
330 	rpipe = &pp->pp_rpipe;
331 	wpipe = &pp->pp_wpipe;
332 
333 	knlist_init(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe), NULL, NULL,
334 	    NULL);
335 	knlist_init(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe), NULL, NULL,
336 	    NULL);
337 
338 	/* Only the forward direction pipe is backed by default */
339 	if ((error = pipe_create(rpipe, 1)) != 0 ||
340 	    (error = pipe_create(wpipe, 0)) != 0) {
341 		pipeclose(rpipe);
342 		pipeclose(wpipe);
343 		return (error);
344 	}
345 
346 	rpipe->pipe_state |= PIPE_DIRECTOK;
347 	wpipe->pipe_state |= PIPE_DIRECTOK;
348 
349 	error = falloc(td, &rf, &fd);
350 	if (error) {
351 		pipeclose(rpipe);
352 		pipeclose(wpipe);
353 		return (error);
354 	}
355 	/* An extra reference on `rf' has been held for us by falloc(). */
356 	fildes[0] = fd;
357 
358 	/*
359 	 * Warning: once we've gotten past allocation of the fd for the
360 	 * read-side, we can only drop the read side via fdrop() in order
361 	 * to avoid races against processes which manage to dup() the read
362 	 * side while we are blocked trying to allocate the write side.
363 	 */
364 	finit(rf, FREAD | FWRITE, DTYPE_PIPE, rpipe, &pipeops);
365 	error = falloc(td, &wf, &fd);
366 	if (error) {
367 		fdclose(fdp, rf, fildes[0], td);
368 		fdrop(rf, td);
369 		/* rpipe has been closed by fdrop(). */
370 		pipeclose(wpipe);
371 		return (error);
372 	}
373 	/* An extra reference on `wf' has been held for us by falloc(). */
374 	finit(wf, FREAD | FWRITE, DTYPE_PIPE, wpipe, &pipeops);
375 	fdrop(wf, td);
376 	fildes[1] = fd;
377 	fdrop(rf, td);
378 
379 	return (0);
380 }
381 
382 /* ARGSUSED */
383 int
384 pipe(struct thread *td, struct pipe_args *uap)
385 {
386 	int error;
387 	int fildes[2];
388 
389 	error = kern_pipe(td, fildes);
390 	if (error)
391 		return (error);
392 
393 	td->td_retval[0] = fildes[0];
394 	td->td_retval[1] = fildes[1];
395 
396 	return (0);
397 }
398 
399 /*
400  * Allocate kva for pipe circular buffer, the space is pageable
401  * This routine will 'realloc' the size of a pipe safely, if it fails
402  * it will retain the old buffer.
403  * If it fails it will return ENOMEM.
404  */
405 static int
406 pipespace_new(cpipe, size)
407 	struct pipe *cpipe;
408 	int size;
409 {
410 	caddr_t buffer;
411 	int error, cnt, firstseg;
412 	static int curfail = 0;
413 	static struct timeval lastfail;
414 
415 	KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
416 	KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
417 		("pipespace: resize of direct writes not allowed"));
418 retry:
419 	cnt = cpipe->pipe_buffer.cnt;
420 	if (cnt > size)
421 		size = cnt;
422 
423 	size = round_page(size);
424 	buffer = (caddr_t) vm_map_min(pipe_map);
425 
426 	error = vm_map_find(pipe_map, NULL, 0,
427 		(vm_offset_t *) &buffer, size, 1,
428 		VM_PROT_ALL, VM_PROT_ALL, 0);
429 	if (error != KERN_SUCCESS) {
430 		if ((cpipe->pipe_buffer.buffer == NULL) &&
431 			(size > SMALL_PIPE_SIZE)) {
432 			size = SMALL_PIPE_SIZE;
433 			pipefragretry++;
434 			goto retry;
435 		}
436 		if (cpipe->pipe_buffer.buffer == NULL) {
437 			pipeallocfail++;
438 			if (ppsratecheck(&lastfail, &curfail, 1))
439 				printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
440 		} else {
441 			piperesizefail++;
442 		}
443 		return (ENOMEM);
444 	}
445 
446 	/* copy data, then free old resources if we're resizing */
447 	if (cnt > 0) {
448 		if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
449 			firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
450 			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
451 				buffer, firstseg);
452 			if ((cnt - firstseg) > 0)
453 				bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
454 					cpipe->pipe_buffer.in);
455 		} else {
456 			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
457 				buffer, cnt);
458 		}
459 	}
460 	pipe_free_kmem(cpipe);
461 	cpipe->pipe_buffer.buffer = buffer;
462 	cpipe->pipe_buffer.size = size;
463 	cpipe->pipe_buffer.in = cnt;
464 	cpipe->pipe_buffer.out = 0;
465 	cpipe->pipe_buffer.cnt = cnt;
466 	atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
467 	return (0);
468 }
469 
470 /*
471  * Wrapper for pipespace_new() that performs locking assertions.
472  */
473 static int
474 pipespace(cpipe, size)
475 	struct pipe *cpipe;
476 	int size;
477 {
478 
479 	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
480 		("Unlocked pipe passed to pipespace"));
481 	return (pipespace_new(cpipe, size));
482 }
483 
484 /*
485  * lock a pipe for I/O, blocking other access
486  */
487 static __inline int
488 pipelock(cpipe, catch)
489 	struct pipe *cpipe;
490 	int catch;
491 {
492 	int error;
493 
494 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
495 	while (cpipe->pipe_state & PIPE_LOCKFL) {
496 		cpipe->pipe_state |= PIPE_LWANT;
497 		error = msleep(cpipe, PIPE_MTX(cpipe),
498 		    catch ? (PRIBIO | PCATCH) : PRIBIO,
499 		    "pipelk", 0);
500 		if (error != 0)
501 			return (error);
502 	}
503 	cpipe->pipe_state |= PIPE_LOCKFL;
504 	return (0);
505 }
506 
507 /*
508  * unlock a pipe I/O lock
509  */
510 static __inline void
511 pipeunlock(cpipe)
512 	struct pipe *cpipe;
513 {
514 
515 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
516 	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
517 		("Unlocked pipe passed to pipeunlock"));
518 	cpipe->pipe_state &= ~PIPE_LOCKFL;
519 	if (cpipe->pipe_state & PIPE_LWANT) {
520 		cpipe->pipe_state &= ~PIPE_LWANT;
521 		wakeup(cpipe);
522 	}
523 }
524 
525 static __inline void
526 pipeselwakeup(cpipe)
527 	struct pipe *cpipe;
528 {
529 
530 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
531 	if (cpipe->pipe_state & PIPE_SEL) {
532 		selwakeuppri(&cpipe->pipe_sel, PSOCK);
533 		if (!SEL_WAITING(&cpipe->pipe_sel))
534 			cpipe->pipe_state &= ~PIPE_SEL;
535 	}
536 	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
537 		pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
538 	KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
539 }
540 
541 /*
542  * Initialize and allocate VM and memory for pipe.  The structure
543  * will start out zero'd from the ctor, so we just manage the kmem.
544  */
545 static int
546 pipe_create(pipe, backing)
547 	struct pipe *pipe;
548 	int backing;
549 {
550 	int error;
551 
552 	if (backing) {
553 		if (amountpipekva > maxpipekva / 2)
554 			error = pipespace_new(pipe, SMALL_PIPE_SIZE);
555 		else
556 			error = pipespace_new(pipe, PIPE_SIZE);
557 	} else {
558 		/* If we're not backing this pipe, no need to do anything. */
559 		error = 0;
560 	}
561 	return (error);
562 }
563 
564 /* ARGSUSED */
565 static int
566 pipe_read(fp, uio, active_cred, flags, td)
567 	struct file *fp;
568 	struct uio *uio;
569 	struct ucred *active_cred;
570 	struct thread *td;
571 	int flags;
572 {
573 	struct pipe *rpipe = fp->f_data;
574 	int error;
575 	int nread = 0;
576 	u_int size;
577 
578 	PIPE_LOCK(rpipe);
579 	++rpipe->pipe_busy;
580 	error = pipelock(rpipe, 1);
581 	if (error)
582 		goto unlocked_error;
583 
584 #ifdef MAC
585 	error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
586 	if (error)
587 		goto locked_error;
588 #endif
589 	if (amountpipekva > (3 * maxpipekva) / 4) {
590 		if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
591 			(rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
592 			(rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
593 			(piperesizeallowed == 1)) {
594 			PIPE_UNLOCK(rpipe);
595 			pipespace(rpipe, SMALL_PIPE_SIZE);
596 			PIPE_LOCK(rpipe);
597 		}
598 	}
599 
600 	while (uio->uio_resid) {
601 		/*
602 		 * normal pipe buffer receive
603 		 */
604 		if (rpipe->pipe_buffer.cnt > 0) {
605 			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
606 			if (size > rpipe->pipe_buffer.cnt)
607 				size = rpipe->pipe_buffer.cnt;
608 			if (size > (u_int) uio->uio_resid)
609 				size = (u_int) uio->uio_resid;
610 
611 			PIPE_UNLOCK(rpipe);
612 			error = uiomove(
613 			    &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
614 			    size, uio);
615 			PIPE_LOCK(rpipe);
616 			if (error)
617 				break;
618 
619 			rpipe->pipe_buffer.out += size;
620 			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
621 				rpipe->pipe_buffer.out = 0;
622 
623 			rpipe->pipe_buffer.cnt -= size;
624 
625 			/*
626 			 * If there is no more to read in the pipe, reset
627 			 * its pointers to the beginning.  This improves
628 			 * cache hit stats.
629 			 */
630 			if (rpipe->pipe_buffer.cnt == 0) {
631 				rpipe->pipe_buffer.in = 0;
632 				rpipe->pipe_buffer.out = 0;
633 			}
634 			nread += size;
635 #ifndef PIPE_NODIRECT
636 		/*
637 		 * Direct copy, bypassing a kernel buffer.
638 		 */
639 		} else if ((size = rpipe->pipe_map.cnt) &&
640 			   (rpipe->pipe_state & PIPE_DIRECTW)) {
641 			if (size > (u_int) uio->uio_resid)
642 				size = (u_int) uio->uio_resid;
643 
644 			PIPE_UNLOCK(rpipe);
645 			error = uiomove_fromphys(rpipe->pipe_map.ms,
646 			    rpipe->pipe_map.pos, size, uio);
647 			PIPE_LOCK(rpipe);
648 			if (error)
649 				break;
650 			nread += size;
651 			rpipe->pipe_map.pos += size;
652 			rpipe->pipe_map.cnt -= size;
653 			if (rpipe->pipe_map.cnt == 0) {
654 				rpipe->pipe_state &= ~PIPE_DIRECTW;
655 				wakeup(rpipe);
656 			}
657 #endif
658 		} else {
659 			/*
660 			 * detect EOF condition
661 			 * read returns 0 on EOF, no need to set error
662 			 */
663 			if (rpipe->pipe_state & PIPE_EOF)
664 				break;
665 
666 			/*
667 			 * If the "write-side" has been blocked, wake it up now.
668 			 */
669 			if (rpipe->pipe_state & PIPE_WANTW) {
670 				rpipe->pipe_state &= ~PIPE_WANTW;
671 				wakeup(rpipe);
672 			}
673 
674 			/*
675 			 * Break if some data was read.
676 			 */
677 			if (nread > 0)
678 				break;
679 
680 			/*
681 			 * Unlock the pipe buffer for our remaining processing.
682 			 * We will either break out with an error or we will
683 			 * sleep and relock to loop.
684 			 */
685 			pipeunlock(rpipe);
686 
687 			/*
688 			 * Handle non-blocking mode operation or
689 			 * wait for more data.
690 			 */
691 			if (fp->f_flag & FNONBLOCK) {
692 				error = EAGAIN;
693 			} else {
694 				rpipe->pipe_state |= PIPE_WANTR;
695 				if ((error = msleep(rpipe, PIPE_MTX(rpipe),
696 				    PRIBIO | PCATCH,
697 				    "piperd", 0)) == 0)
698 					error = pipelock(rpipe, 1);
699 			}
700 			if (error)
701 				goto unlocked_error;
702 		}
703 	}
704 #ifdef MAC
705 locked_error:
706 #endif
707 	pipeunlock(rpipe);
708 
709 	/* XXX: should probably do this before getting any locks. */
710 	if (error == 0)
711 		vfs_timestamp(&rpipe->pipe_atime);
712 unlocked_error:
713 	--rpipe->pipe_busy;
714 
715 	/*
716 	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
717 	 */
718 	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
719 		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
720 		wakeup(rpipe);
721 	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
722 		/*
723 		 * Handle write blocking hysteresis.
724 		 */
725 		if (rpipe->pipe_state & PIPE_WANTW) {
726 			rpipe->pipe_state &= ~PIPE_WANTW;
727 			wakeup(rpipe);
728 		}
729 	}
730 
731 	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
732 		pipeselwakeup(rpipe);
733 
734 	PIPE_UNLOCK(rpipe);
735 	return (error);
736 }
737 
738 #ifndef PIPE_NODIRECT
739 /*
740  * Map the sending processes' buffer into kernel space and wire it.
741  * This is similar to a physical write operation.
742  */
743 static int
744 pipe_build_write_buffer(wpipe, uio)
745 	struct pipe *wpipe;
746 	struct uio *uio;
747 {
748 	pmap_t pmap;
749 	u_int size;
750 	int i, j;
751 	vm_offset_t addr, endaddr;
752 
753 	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
754 	KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
755 		("Clone attempt on non-direct write pipe!"));
756 
757 	size = (u_int) uio->uio_iov->iov_len;
758 	if (size > wpipe->pipe_buffer.size)
759 		size = wpipe->pipe_buffer.size;
760 
761 	pmap = vmspace_pmap(curproc->p_vmspace);
762 	endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
763 	addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
764 	for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
765 		/*
766 		 * vm_fault_quick() can sleep.  Consequently,
767 		 * vm_page_lock_queue() and vm_page_unlock_queue()
768 		 * should not be performed outside of this loop.
769 		 */
770 	race:
771 		if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0) {
772 			vm_page_lock_queues();
773 			for (j = 0; j < i; j++)
774 				vm_page_unhold(wpipe->pipe_map.ms[j]);
775 			vm_page_unlock_queues();
776 			return (EFAULT);
777 		}
778 		wpipe->pipe_map.ms[i] = pmap_extract_and_hold(pmap, addr,
779 		    VM_PROT_READ);
780 		if (wpipe->pipe_map.ms[i] == NULL)
781 			goto race;
782 	}
783 
784 /*
785  * set up the control block
786  */
787 	wpipe->pipe_map.npages = i;
788 	wpipe->pipe_map.pos =
789 	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
790 	wpipe->pipe_map.cnt = size;
791 
792 /*
793  * and update the uio data
794  */
795 
796 	uio->uio_iov->iov_len -= size;
797 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
798 	if (uio->uio_iov->iov_len == 0)
799 		uio->uio_iov++;
800 	uio->uio_resid -= size;
801 	uio->uio_offset += size;
802 	return (0);
803 }
804 
805 /*
806  * unmap and unwire the process buffer
807  */
808 static void
809 pipe_destroy_write_buffer(wpipe)
810 	struct pipe *wpipe;
811 {
812 	int i;
813 
814 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
815 	vm_page_lock_queues();
816 	for (i = 0; i < wpipe->pipe_map.npages; i++) {
817 		vm_page_unhold(wpipe->pipe_map.ms[i]);
818 	}
819 	vm_page_unlock_queues();
820 	wpipe->pipe_map.npages = 0;
821 }
822 
823 /*
824  * In the case of a signal, the writing process might go away.  This
825  * code copies the data into the circular buffer so that the source
826  * pages can be freed without loss of data.
827  */
828 static void
829 pipe_clone_write_buffer(wpipe)
830 	struct pipe *wpipe;
831 {
832 	struct uio uio;
833 	struct iovec iov;
834 	int size;
835 	int pos;
836 
837 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
838 	size = wpipe->pipe_map.cnt;
839 	pos = wpipe->pipe_map.pos;
840 
841 	wpipe->pipe_buffer.in = size;
842 	wpipe->pipe_buffer.out = 0;
843 	wpipe->pipe_buffer.cnt = size;
844 	wpipe->pipe_state &= ~PIPE_DIRECTW;
845 
846 	PIPE_UNLOCK(wpipe);
847 	iov.iov_base = wpipe->pipe_buffer.buffer;
848 	iov.iov_len = size;
849 	uio.uio_iov = &iov;
850 	uio.uio_iovcnt = 1;
851 	uio.uio_offset = 0;
852 	uio.uio_resid = size;
853 	uio.uio_segflg = UIO_SYSSPACE;
854 	uio.uio_rw = UIO_READ;
855 	uio.uio_td = curthread;
856 	uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
857 	PIPE_LOCK(wpipe);
858 	pipe_destroy_write_buffer(wpipe);
859 }
860 
861 /*
862  * This implements the pipe buffer write mechanism.  Note that only
863  * a direct write OR a normal pipe write can be pending at any given time.
864  * If there are any characters in the pipe buffer, the direct write will
865  * be deferred until the receiving process grabs all of the bytes from
866  * the pipe buffer.  Then the direct mapping write is set-up.
867  */
868 static int
869 pipe_direct_write(wpipe, uio)
870 	struct pipe *wpipe;
871 	struct uio *uio;
872 {
873 	int error;
874 
875 retry:
876 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
877 	error = pipelock(wpipe, 1);
878 	if (wpipe->pipe_state & PIPE_EOF)
879 		error = EPIPE;
880 	if (error) {
881 		pipeunlock(wpipe);
882 		goto error1;
883 	}
884 	while (wpipe->pipe_state & PIPE_DIRECTW) {
885 		if (wpipe->pipe_state & PIPE_WANTR) {
886 			wpipe->pipe_state &= ~PIPE_WANTR;
887 			wakeup(wpipe);
888 		}
889 		pipeselwakeup(wpipe);
890 		wpipe->pipe_state |= PIPE_WANTW;
891 		pipeunlock(wpipe);
892 		error = msleep(wpipe, PIPE_MTX(wpipe),
893 		    PRIBIO | PCATCH, "pipdww", 0);
894 		if (error)
895 			goto error1;
896 		else
897 			goto retry;
898 	}
899 	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
900 	if (wpipe->pipe_buffer.cnt > 0) {
901 		if (wpipe->pipe_state & PIPE_WANTR) {
902 			wpipe->pipe_state &= ~PIPE_WANTR;
903 			wakeup(wpipe);
904 		}
905 		pipeselwakeup(wpipe);
906 		wpipe->pipe_state |= PIPE_WANTW;
907 		pipeunlock(wpipe);
908 		error = msleep(wpipe, PIPE_MTX(wpipe),
909 		    PRIBIO | PCATCH, "pipdwc", 0);
910 		if (error)
911 			goto error1;
912 		else
913 			goto retry;
914 	}
915 
916 	wpipe->pipe_state |= PIPE_DIRECTW;
917 
918 	PIPE_UNLOCK(wpipe);
919 	error = pipe_build_write_buffer(wpipe, uio);
920 	PIPE_LOCK(wpipe);
921 	if (error) {
922 		wpipe->pipe_state &= ~PIPE_DIRECTW;
923 		pipeunlock(wpipe);
924 		goto error1;
925 	}
926 
927 	error = 0;
928 	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
929 		if (wpipe->pipe_state & PIPE_EOF) {
930 			pipe_destroy_write_buffer(wpipe);
931 			pipeselwakeup(wpipe);
932 			pipeunlock(wpipe);
933 			error = EPIPE;
934 			goto error1;
935 		}
936 		if (wpipe->pipe_state & PIPE_WANTR) {
937 			wpipe->pipe_state &= ~PIPE_WANTR;
938 			wakeup(wpipe);
939 		}
940 		pipeselwakeup(wpipe);
941 		pipeunlock(wpipe);
942 		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
943 		    "pipdwt", 0);
944 		pipelock(wpipe, 0);
945 	}
946 
947 	if (wpipe->pipe_state & PIPE_EOF)
948 		error = EPIPE;
949 	if (wpipe->pipe_state & PIPE_DIRECTW) {
950 		/*
951 		 * this bit of trickery substitutes a kernel buffer for
952 		 * the process that might be going away.
953 		 */
954 		pipe_clone_write_buffer(wpipe);
955 	} else {
956 		pipe_destroy_write_buffer(wpipe);
957 	}
958 	pipeunlock(wpipe);
959 	return (error);
960 
961 error1:
962 	wakeup(wpipe);
963 	return (error);
964 }
965 #endif
966 
967 static int
968 pipe_write(fp, uio, active_cred, flags, td)
969 	struct file *fp;
970 	struct uio *uio;
971 	struct ucred *active_cred;
972 	struct thread *td;
973 	int flags;
974 {
975 	int error = 0;
976 	int desiredsize, orig_resid;
977 	struct pipe *wpipe, *rpipe;
978 
979 	rpipe = fp->f_data;
980 	wpipe = rpipe->pipe_peer;
981 
982 	PIPE_LOCK(rpipe);
983 	error = pipelock(wpipe, 1);
984 	if (error) {
985 		PIPE_UNLOCK(rpipe);
986 		return (error);
987 	}
988 	/*
989 	 * detect loss of pipe read side, issue SIGPIPE if lost.
990 	 */
991 	if (wpipe->pipe_present != PIPE_ACTIVE ||
992 	    (wpipe->pipe_state & PIPE_EOF)) {
993 		pipeunlock(wpipe);
994 		PIPE_UNLOCK(rpipe);
995 		return (EPIPE);
996 	}
997 #ifdef MAC
998 	error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
999 	if (error) {
1000 		pipeunlock(wpipe);
1001 		PIPE_UNLOCK(rpipe);
1002 		return (error);
1003 	}
1004 #endif
1005 	++wpipe->pipe_busy;
1006 
1007 	/* Choose a larger size if it's advantageous */
1008 	desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1009 	while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1010 		if (piperesizeallowed != 1)
1011 			break;
1012 		if (amountpipekva > maxpipekva / 2)
1013 			break;
1014 		if (desiredsize == BIG_PIPE_SIZE)
1015 			break;
1016 		desiredsize = desiredsize * 2;
1017 	}
1018 
1019 	/* Choose a smaller size if we're in a OOM situation */
1020 	if ((amountpipekva > (3 * maxpipekva) / 4) &&
1021 		(wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1022 		(wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1023 		(piperesizeallowed == 1))
1024 		desiredsize = SMALL_PIPE_SIZE;
1025 
1026 	/* Resize if the above determined that a new size was necessary */
1027 	if ((desiredsize != wpipe->pipe_buffer.size) &&
1028 		((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1029 		PIPE_UNLOCK(wpipe);
1030 		pipespace(wpipe, desiredsize);
1031 		PIPE_LOCK(wpipe);
1032 	}
1033 	if (wpipe->pipe_buffer.size == 0) {
1034 		/*
1035 		 * This can only happen for reverse direction use of pipes
1036 		 * in a complete OOM situation.
1037 		 */
1038 		error = ENOMEM;
1039 		--wpipe->pipe_busy;
1040 		pipeunlock(wpipe);
1041 		PIPE_UNLOCK(wpipe);
1042 		return (error);
1043 	}
1044 
1045 	pipeunlock(wpipe);
1046 
1047 	orig_resid = uio->uio_resid;
1048 
1049 	while (uio->uio_resid) {
1050 		int space;
1051 
1052 		pipelock(wpipe, 0);
1053 		if (wpipe->pipe_state & PIPE_EOF) {
1054 			pipeunlock(wpipe);
1055 			error = EPIPE;
1056 			break;
1057 		}
1058 #ifndef PIPE_NODIRECT
1059 		/*
1060 		 * If the transfer is large, we can gain performance if
1061 		 * we do process-to-process copies directly.
1062 		 * If the write is non-blocking, we don't use the
1063 		 * direct write mechanism.
1064 		 *
1065 		 * The direct write mechanism will detect the reader going
1066 		 * away on us.
1067 		 */
1068 		if (uio->uio_segflg == UIO_USERSPACE &&
1069 		    uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1070 		    wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1071 		    (fp->f_flag & FNONBLOCK) == 0) {
1072 			pipeunlock(wpipe);
1073 			error = pipe_direct_write(wpipe, uio);
1074 			if (error)
1075 				break;
1076 			continue;
1077 		}
1078 #endif
1079 
1080 		/*
1081 		 * Pipe buffered writes cannot be coincidental with
1082 		 * direct writes.  We wait until the currently executing
1083 		 * direct write is completed before we start filling the
1084 		 * pipe buffer.  We break out if a signal occurs or the
1085 		 * reader goes away.
1086 		 */
1087 		if (wpipe->pipe_state & PIPE_DIRECTW) {
1088 			if (wpipe->pipe_state & PIPE_WANTR) {
1089 				wpipe->pipe_state &= ~PIPE_WANTR;
1090 				wakeup(wpipe);
1091 			}
1092 			pipeselwakeup(wpipe);
1093 			wpipe->pipe_state |= PIPE_WANTW;
1094 			pipeunlock(wpipe);
1095 			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1096 			    "pipbww", 0);
1097 			if (error)
1098 				break;
1099 			else
1100 				continue;
1101 		}
1102 
1103 		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1104 
1105 		/* Writes of size <= PIPE_BUF must be atomic. */
1106 		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1107 			space = 0;
1108 
1109 		if (space > 0) {
1110 			int size;	/* Transfer size */
1111 			int segsize;	/* first segment to transfer */
1112 
1113 			/*
1114 			 * Transfer size is minimum of uio transfer
1115 			 * and free space in pipe buffer.
1116 			 */
1117 			if (space > uio->uio_resid)
1118 				size = uio->uio_resid;
1119 			else
1120 				size = space;
1121 			/*
1122 			 * First segment to transfer is minimum of
1123 			 * transfer size and contiguous space in
1124 			 * pipe buffer.  If first segment to transfer
1125 			 * is less than the transfer size, we've got
1126 			 * a wraparound in the buffer.
1127 			 */
1128 			segsize = wpipe->pipe_buffer.size -
1129 				wpipe->pipe_buffer.in;
1130 			if (segsize > size)
1131 				segsize = size;
1132 
1133 			/* Transfer first segment */
1134 
1135 			PIPE_UNLOCK(rpipe);
1136 			error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1137 					segsize, uio);
1138 			PIPE_LOCK(rpipe);
1139 
1140 			if (error == 0 && segsize < size) {
1141 				KASSERT(wpipe->pipe_buffer.in + segsize ==
1142 					wpipe->pipe_buffer.size,
1143 					("Pipe buffer wraparound disappeared"));
1144 				/*
1145 				 * Transfer remaining part now, to
1146 				 * support atomic writes.  Wraparound
1147 				 * happened.
1148 				 */
1149 
1150 				PIPE_UNLOCK(rpipe);
1151 				error = uiomove(
1152 				    &wpipe->pipe_buffer.buffer[0],
1153 				    size - segsize, uio);
1154 				PIPE_LOCK(rpipe);
1155 			}
1156 			if (error == 0) {
1157 				wpipe->pipe_buffer.in += size;
1158 				if (wpipe->pipe_buffer.in >=
1159 				    wpipe->pipe_buffer.size) {
1160 					KASSERT(wpipe->pipe_buffer.in ==
1161 						size - segsize +
1162 						wpipe->pipe_buffer.size,
1163 						("Expected wraparound bad"));
1164 					wpipe->pipe_buffer.in = size - segsize;
1165 				}
1166 
1167 				wpipe->pipe_buffer.cnt += size;
1168 				KASSERT(wpipe->pipe_buffer.cnt <=
1169 					wpipe->pipe_buffer.size,
1170 					("Pipe buffer overflow"));
1171 			}
1172 			pipeunlock(wpipe);
1173 			if (error != 0)
1174 				break;
1175 		} else {
1176 			/*
1177 			 * If the "read-side" has been blocked, wake it up now.
1178 			 */
1179 			if (wpipe->pipe_state & PIPE_WANTR) {
1180 				wpipe->pipe_state &= ~PIPE_WANTR;
1181 				wakeup(wpipe);
1182 			}
1183 
1184 			/*
1185 			 * don't block on non-blocking I/O
1186 			 */
1187 			if (fp->f_flag & FNONBLOCK) {
1188 				error = EAGAIN;
1189 				pipeunlock(wpipe);
1190 				break;
1191 			}
1192 
1193 			/*
1194 			 * We have no more space and have something to offer,
1195 			 * wake up select/poll.
1196 			 */
1197 			pipeselwakeup(wpipe);
1198 
1199 			wpipe->pipe_state |= PIPE_WANTW;
1200 			pipeunlock(wpipe);
1201 			error = msleep(wpipe, PIPE_MTX(rpipe),
1202 			    PRIBIO | PCATCH, "pipewr", 0);
1203 			if (error != 0)
1204 				break;
1205 		}
1206 	}
1207 
1208 	pipelock(wpipe, 0);
1209 	--wpipe->pipe_busy;
1210 
1211 	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1212 		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1213 		wakeup(wpipe);
1214 	} else if (wpipe->pipe_buffer.cnt > 0) {
1215 		/*
1216 		 * If we have put any characters in the buffer, we wake up
1217 		 * the reader.
1218 		 */
1219 		if (wpipe->pipe_state & PIPE_WANTR) {
1220 			wpipe->pipe_state &= ~PIPE_WANTR;
1221 			wakeup(wpipe);
1222 		}
1223 	}
1224 
1225 	/*
1226 	 * Don't return EPIPE if I/O was successful
1227 	 */
1228 	if ((wpipe->pipe_buffer.cnt == 0) &&
1229 	    (uio->uio_resid == 0) &&
1230 	    (error == EPIPE)) {
1231 		error = 0;
1232 	}
1233 
1234 	if (error == 0)
1235 		vfs_timestamp(&wpipe->pipe_mtime);
1236 
1237 	/*
1238 	 * We have something to offer,
1239 	 * wake up select/poll.
1240 	 */
1241 	if (wpipe->pipe_buffer.cnt)
1242 		pipeselwakeup(wpipe);
1243 
1244 	pipeunlock(wpipe);
1245 	PIPE_UNLOCK(rpipe);
1246 	return (error);
1247 }
1248 
1249 /* ARGSUSED */
1250 static int
1251 pipe_truncate(fp, length, active_cred, td)
1252 	struct file *fp;
1253 	off_t length;
1254 	struct ucred *active_cred;
1255 	struct thread *td;
1256 {
1257 
1258 	return (EINVAL);
1259 }
1260 
1261 /*
1262  * we implement a very minimal set of ioctls for compatibility with sockets.
1263  */
1264 static int
1265 pipe_ioctl(fp, cmd, data, active_cred, td)
1266 	struct file *fp;
1267 	u_long cmd;
1268 	void *data;
1269 	struct ucred *active_cred;
1270 	struct thread *td;
1271 {
1272 	struct pipe *mpipe = fp->f_data;
1273 	int error;
1274 
1275 	PIPE_LOCK(mpipe);
1276 
1277 #ifdef MAC
1278 	error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1279 	if (error) {
1280 		PIPE_UNLOCK(mpipe);
1281 		return (error);
1282 	}
1283 #endif
1284 
1285 	error = 0;
1286 	switch (cmd) {
1287 
1288 	case FIONBIO:
1289 		break;
1290 
1291 	case FIOASYNC:
1292 		if (*(int *)data) {
1293 			mpipe->pipe_state |= PIPE_ASYNC;
1294 		} else {
1295 			mpipe->pipe_state &= ~PIPE_ASYNC;
1296 		}
1297 		break;
1298 
1299 	case FIONREAD:
1300 		if (mpipe->pipe_state & PIPE_DIRECTW)
1301 			*(int *)data = mpipe->pipe_map.cnt;
1302 		else
1303 			*(int *)data = mpipe->pipe_buffer.cnt;
1304 		break;
1305 
1306 	case FIOSETOWN:
1307 		PIPE_UNLOCK(mpipe);
1308 		error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1309 		goto out_unlocked;
1310 
1311 	case FIOGETOWN:
1312 		*(int *)data = fgetown(&mpipe->pipe_sigio);
1313 		break;
1314 
1315 	/* This is deprecated, FIOSETOWN should be used instead. */
1316 	case TIOCSPGRP:
1317 		PIPE_UNLOCK(mpipe);
1318 		error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1319 		goto out_unlocked;
1320 
1321 	/* This is deprecated, FIOGETOWN should be used instead. */
1322 	case TIOCGPGRP:
1323 		*(int *)data = -fgetown(&mpipe->pipe_sigio);
1324 		break;
1325 
1326 	default:
1327 		error = ENOTTY;
1328 		break;
1329 	}
1330 	PIPE_UNLOCK(mpipe);
1331 out_unlocked:
1332 	return (error);
1333 }
1334 
1335 static int
1336 pipe_poll(fp, events, active_cred, td)
1337 	struct file *fp;
1338 	int events;
1339 	struct ucred *active_cred;
1340 	struct thread *td;
1341 {
1342 	struct pipe *rpipe = fp->f_data;
1343 	struct pipe *wpipe;
1344 	int revents = 0;
1345 #ifdef MAC
1346 	int error;
1347 #endif
1348 
1349 	wpipe = rpipe->pipe_peer;
1350 	PIPE_LOCK(rpipe);
1351 #ifdef MAC
1352 	error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1353 	if (error)
1354 		goto locked_error;
1355 #endif
1356 	if (events & (POLLIN | POLLRDNORM))
1357 		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1358 		    (rpipe->pipe_buffer.cnt > 0) ||
1359 		    (rpipe->pipe_state & PIPE_EOF))
1360 			revents |= events & (POLLIN | POLLRDNORM);
1361 
1362 	if (events & (POLLOUT | POLLWRNORM))
1363 		if (wpipe->pipe_present != PIPE_ACTIVE ||
1364 		    (wpipe->pipe_state & PIPE_EOF) ||
1365 		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1366 		     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1367 			revents |= events & (POLLOUT | POLLWRNORM);
1368 
1369 	if ((rpipe->pipe_state & PIPE_EOF) ||
1370 	    wpipe->pipe_present != PIPE_ACTIVE ||
1371 	    (wpipe->pipe_state & PIPE_EOF))
1372 		revents |= POLLHUP;
1373 
1374 	if (revents == 0) {
1375 		if (events & (POLLIN | POLLRDNORM)) {
1376 			selrecord(td, &rpipe->pipe_sel);
1377 			if (SEL_WAITING(&rpipe->pipe_sel))
1378 				rpipe->pipe_state |= PIPE_SEL;
1379 		}
1380 
1381 		if (events & (POLLOUT | POLLWRNORM)) {
1382 			selrecord(td, &wpipe->pipe_sel);
1383 			if (SEL_WAITING(&wpipe->pipe_sel))
1384 				wpipe->pipe_state |= PIPE_SEL;
1385 		}
1386 	}
1387 #ifdef MAC
1388 locked_error:
1389 #endif
1390 	PIPE_UNLOCK(rpipe);
1391 
1392 	return (revents);
1393 }
1394 
1395 /*
1396  * We shouldn't need locks here as we're doing a read and this should
1397  * be a natural race.
1398  */
1399 static int
1400 pipe_stat(fp, ub, active_cred, td)
1401 	struct file *fp;
1402 	struct stat *ub;
1403 	struct ucred *active_cred;
1404 	struct thread *td;
1405 {
1406 	struct pipe *pipe = fp->f_data;
1407 #ifdef MAC
1408 	int error;
1409 
1410 	PIPE_LOCK(pipe);
1411 	error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1412 	PIPE_UNLOCK(pipe);
1413 	if (error)
1414 		return (error);
1415 #endif
1416 	bzero(ub, sizeof(*ub));
1417 	ub->st_mode = S_IFIFO;
1418 	ub->st_blksize = PAGE_SIZE;
1419 	if (pipe->pipe_state & PIPE_DIRECTW)
1420 		ub->st_size = pipe->pipe_map.cnt;
1421 	else
1422 		ub->st_size = pipe->pipe_buffer.cnt;
1423 	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1424 	ub->st_atimespec = pipe->pipe_atime;
1425 	ub->st_mtimespec = pipe->pipe_mtime;
1426 	ub->st_ctimespec = pipe->pipe_ctime;
1427 	ub->st_uid = fp->f_cred->cr_uid;
1428 	ub->st_gid = fp->f_cred->cr_gid;
1429 	/*
1430 	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1431 	 * XXX (st_dev, st_ino) should be unique.
1432 	 */
1433 	return (0);
1434 }
1435 
1436 /* ARGSUSED */
1437 static int
1438 pipe_close(fp, td)
1439 	struct file *fp;
1440 	struct thread *td;
1441 {
1442 	struct pipe *cpipe = fp->f_data;
1443 
1444 	fp->f_ops = &badfileops;
1445 	fp->f_data = NULL;
1446 	funsetown(&cpipe->pipe_sigio);
1447 	pipeclose(cpipe);
1448 	return (0);
1449 }
1450 
1451 static void
1452 pipe_free_kmem(cpipe)
1453 	struct pipe *cpipe;
1454 {
1455 
1456 	KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1457 	    ("pipe_free_kmem: pipe mutex locked"));
1458 
1459 	if (cpipe->pipe_buffer.buffer != NULL) {
1460 		atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1461 		vm_map_remove(pipe_map,
1462 		    (vm_offset_t)cpipe->pipe_buffer.buffer,
1463 		    (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1464 		cpipe->pipe_buffer.buffer = NULL;
1465 	}
1466 #ifndef PIPE_NODIRECT
1467 	{
1468 		cpipe->pipe_map.cnt = 0;
1469 		cpipe->pipe_map.pos = 0;
1470 		cpipe->pipe_map.npages = 0;
1471 	}
1472 #endif
1473 }
1474 
1475 /*
1476  * shutdown the pipe
1477  */
1478 static void
1479 pipeclose(cpipe)
1480 	struct pipe *cpipe;
1481 {
1482 	struct pipepair *pp;
1483 	struct pipe *ppipe;
1484 
1485 	KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1486 
1487 	PIPE_LOCK(cpipe);
1488 	pipelock(cpipe, 0);
1489 	pp = cpipe->pipe_pair;
1490 
1491 	pipeselwakeup(cpipe);
1492 
1493 	/*
1494 	 * If the other side is blocked, wake it up saying that
1495 	 * we want to close it down.
1496 	 */
1497 	cpipe->pipe_state |= PIPE_EOF;
1498 	while (cpipe->pipe_busy) {
1499 		wakeup(cpipe);
1500 		cpipe->pipe_state |= PIPE_WANT;
1501 		pipeunlock(cpipe);
1502 		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1503 		pipelock(cpipe, 0);
1504 	}
1505 
1506 
1507 	/*
1508 	 * Disconnect from peer, if any.
1509 	 */
1510 	ppipe = cpipe->pipe_peer;
1511 	if (ppipe->pipe_present == PIPE_ACTIVE) {
1512 		pipeselwakeup(ppipe);
1513 
1514 		ppipe->pipe_state |= PIPE_EOF;
1515 		wakeup(ppipe);
1516 		KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1517 	}
1518 
1519 	/*
1520 	 * Mark this endpoint as free.  Release kmem resources.  We
1521 	 * don't mark this endpoint as unused until we've finished
1522 	 * doing that, or the pipe might disappear out from under
1523 	 * us.
1524 	 */
1525 	PIPE_UNLOCK(cpipe);
1526 	pipe_free_kmem(cpipe);
1527 	PIPE_LOCK(cpipe);
1528 	cpipe->pipe_present = PIPE_CLOSING;
1529 	pipeunlock(cpipe);
1530 
1531 	/*
1532 	 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1533 	 * PIPE_FINALIZED, that allows other end to free the
1534 	 * pipe_pair, only after the knotes are completely dismantled.
1535 	 */
1536 	knlist_clear(&cpipe->pipe_sel.si_note, 1);
1537 	cpipe->pipe_present = PIPE_FINALIZED;
1538 	knlist_destroy(&cpipe->pipe_sel.si_note);
1539 
1540 	/*
1541 	 * If both endpoints are now closed, release the memory for the
1542 	 * pipe pair.  If not, unlock.
1543 	 */
1544 	if (ppipe->pipe_present == PIPE_FINALIZED) {
1545 		PIPE_UNLOCK(cpipe);
1546 #ifdef MAC
1547 		mac_pipe_destroy(pp);
1548 #endif
1549 		uma_zfree(pipe_zone, cpipe->pipe_pair);
1550 	} else
1551 		PIPE_UNLOCK(cpipe);
1552 }
1553 
1554 /*ARGSUSED*/
1555 static int
1556 pipe_kqfilter(struct file *fp, struct knote *kn)
1557 {
1558 	struct pipe *cpipe;
1559 
1560 	cpipe = kn->kn_fp->f_data;
1561 	PIPE_LOCK(cpipe);
1562 	switch (kn->kn_filter) {
1563 	case EVFILT_READ:
1564 		kn->kn_fop = &pipe_rfiltops;
1565 		break;
1566 	case EVFILT_WRITE:
1567 		kn->kn_fop = &pipe_wfiltops;
1568 		if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1569 			/* other end of pipe has been closed */
1570 			PIPE_UNLOCK(cpipe);
1571 			return (EPIPE);
1572 		}
1573 		cpipe = cpipe->pipe_peer;
1574 		break;
1575 	default:
1576 		PIPE_UNLOCK(cpipe);
1577 		return (EINVAL);
1578 	}
1579 
1580 	knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1581 	PIPE_UNLOCK(cpipe);
1582 	return (0);
1583 }
1584 
1585 static void
1586 filt_pipedetach(struct knote *kn)
1587 {
1588 	struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1589 
1590 	PIPE_LOCK(cpipe);
1591 	if (kn->kn_filter == EVFILT_WRITE)
1592 		cpipe = cpipe->pipe_peer;
1593 	knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1594 	PIPE_UNLOCK(cpipe);
1595 }
1596 
1597 /*ARGSUSED*/
1598 static int
1599 filt_piperead(struct knote *kn, long hint)
1600 {
1601 	struct pipe *rpipe = kn->kn_fp->f_data;
1602 	struct pipe *wpipe = rpipe->pipe_peer;
1603 	int ret;
1604 
1605 	PIPE_LOCK(rpipe);
1606 	kn->kn_data = rpipe->pipe_buffer.cnt;
1607 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1608 		kn->kn_data = rpipe->pipe_map.cnt;
1609 
1610 	if ((rpipe->pipe_state & PIPE_EOF) ||
1611 	    wpipe->pipe_present != PIPE_ACTIVE ||
1612 	    (wpipe->pipe_state & PIPE_EOF)) {
1613 		kn->kn_flags |= EV_EOF;
1614 		PIPE_UNLOCK(rpipe);
1615 		return (1);
1616 	}
1617 	ret = kn->kn_data > 0;
1618 	PIPE_UNLOCK(rpipe);
1619 	return ret;
1620 }
1621 
1622 /*ARGSUSED*/
1623 static int
1624 filt_pipewrite(struct knote *kn, long hint)
1625 {
1626 	struct pipe *rpipe = kn->kn_fp->f_data;
1627 	struct pipe *wpipe = rpipe->pipe_peer;
1628 
1629 	PIPE_LOCK(rpipe);
1630 	if (wpipe->pipe_present != PIPE_ACTIVE ||
1631 	    (wpipe->pipe_state & PIPE_EOF)) {
1632 		kn->kn_data = 0;
1633 		kn->kn_flags |= EV_EOF;
1634 		PIPE_UNLOCK(rpipe);
1635 		return (1);
1636 	}
1637 	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1638 	if (wpipe->pipe_state & PIPE_DIRECTW)
1639 		kn->kn_data = 0;
1640 
1641 	PIPE_UNLOCK(rpipe);
1642 	return (kn->kn_data >= PIPE_BUF);
1643 }
1644