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