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