xref: /freebsd/sys/kern/sys_pipe.c (revision 30d239bc4c510432e65a84fa1c14ed67a3ab1c92)
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 		cpipe->pipe_state &= ~PIPE_SEL;
528 		selwakeuppri(&cpipe->pipe_sel, PSOCK);
529 	}
530 	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
531 		pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
532 	KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
533 }
534 
535 /*
536  * Initialize and allocate VM and memory for pipe.  The structure
537  * will start out zero'd from the ctor, so we just manage the kmem.
538  */
539 static int
540 pipe_create(pipe, backing)
541 	struct pipe *pipe;
542 	int backing;
543 {
544 	int error;
545 
546 	if (backing) {
547 		if (amountpipekva > maxpipekva / 2)
548 			error = pipespace_new(pipe, SMALL_PIPE_SIZE);
549 		else
550 			error = pipespace_new(pipe, PIPE_SIZE);
551 	} else {
552 		/* If we're not backing this pipe, no need to do anything. */
553 		error = 0;
554 	}
555 	return (error);
556 }
557 
558 /* ARGSUSED */
559 static int
560 pipe_read(fp, uio, active_cred, flags, td)
561 	struct file *fp;
562 	struct uio *uio;
563 	struct ucred *active_cred;
564 	struct thread *td;
565 	int flags;
566 {
567 	struct pipe *rpipe = fp->f_data;
568 	int error;
569 	int nread = 0;
570 	u_int size;
571 
572 	PIPE_LOCK(rpipe);
573 	++rpipe->pipe_busy;
574 	error = pipelock(rpipe, 1);
575 	if (error)
576 		goto unlocked_error;
577 
578 #ifdef MAC
579 	error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
580 	if (error)
581 		goto locked_error;
582 #endif
583 	if (amountpipekva > (3 * maxpipekva) / 4) {
584 		if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
585 			(rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
586 			(rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
587 			(piperesizeallowed == 1)) {
588 			PIPE_UNLOCK(rpipe);
589 			pipespace(rpipe, SMALL_PIPE_SIZE);
590 			PIPE_LOCK(rpipe);
591 		}
592 	}
593 
594 	while (uio->uio_resid) {
595 		/*
596 		 * normal pipe buffer receive
597 		 */
598 		if (rpipe->pipe_buffer.cnt > 0) {
599 			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
600 			if (size > rpipe->pipe_buffer.cnt)
601 				size = rpipe->pipe_buffer.cnt;
602 			if (size > (u_int) uio->uio_resid)
603 				size = (u_int) uio->uio_resid;
604 
605 			PIPE_UNLOCK(rpipe);
606 			error = uiomove(
607 			    &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
608 			    size, uio);
609 			PIPE_LOCK(rpipe);
610 			if (error)
611 				break;
612 
613 			rpipe->pipe_buffer.out += size;
614 			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
615 				rpipe->pipe_buffer.out = 0;
616 
617 			rpipe->pipe_buffer.cnt -= size;
618 
619 			/*
620 			 * If there is no more to read in the pipe, reset
621 			 * its pointers to the beginning.  This improves
622 			 * cache hit stats.
623 			 */
624 			if (rpipe->pipe_buffer.cnt == 0) {
625 				rpipe->pipe_buffer.in = 0;
626 				rpipe->pipe_buffer.out = 0;
627 			}
628 			nread += size;
629 #ifndef PIPE_NODIRECT
630 		/*
631 		 * Direct copy, bypassing a kernel buffer.
632 		 */
633 		} else if ((size = rpipe->pipe_map.cnt) &&
634 			   (rpipe->pipe_state & PIPE_DIRECTW)) {
635 			if (size > (u_int) uio->uio_resid)
636 				size = (u_int) uio->uio_resid;
637 
638 			PIPE_UNLOCK(rpipe);
639 			error = uiomove_fromphys(rpipe->pipe_map.ms,
640 			    rpipe->pipe_map.pos, size, uio);
641 			PIPE_LOCK(rpipe);
642 			if (error)
643 				break;
644 			nread += size;
645 			rpipe->pipe_map.pos += size;
646 			rpipe->pipe_map.cnt -= size;
647 			if (rpipe->pipe_map.cnt == 0) {
648 				rpipe->pipe_state &= ~PIPE_DIRECTW;
649 				wakeup(rpipe);
650 			}
651 #endif
652 		} else {
653 			/*
654 			 * detect EOF condition
655 			 * read returns 0 on EOF, no need to set error
656 			 */
657 			if (rpipe->pipe_state & PIPE_EOF)
658 				break;
659 
660 			/*
661 			 * If the "write-side" has been blocked, wake it up now.
662 			 */
663 			if (rpipe->pipe_state & PIPE_WANTW) {
664 				rpipe->pipe_state &= ~PIPE_WANTW;
665 				wakeup(rpipe);
666 			}
667 
668 			/*
669 			 * Break if some data was read.
670 			 */
671 			if (nread > 0)
672 				break;
673 
674 			/*
675 			 * Unlock the pipe buffer for our remaining processing.
676 			 * We will either break out with an error or we will
677 			 * sleep and relock to loop.
678 			 */
679 			pipeunlock(rpipe);
680 
681 			/*
682 			 * Handle non-blocking mode operation or
683 			 * wait for more data.
684 			 */
685 			if (fp->f_flag & FNONBLOCK) {
686 				error = EAGAIN;
687 			} else {
688 				rpipe->pipe_state |= PIPE_WANTR;
689 				if ((error = msleep(rpipe, PIPE_MTX(rpipe),
690 				    PRIBIO | PCATCH,
691 				    "piperd", 0)) == 0)
692 					error = pipelock(rpipe, 1);
693 			}
694 			if (error)
695 				goto unlocked_error;
696 		}
697 	}
698 #ifdef MAC
699 locked_error:
700 #endif
701 	pipeunlock(rpipe);
702 
703 	/* XXX: should probably do this before getting any locks. */
704 	if (error == 0)
705 		vfs_timestamp(&rpipe->pipe_atime);
706 unlocked_error:
707 	--rpipe->pipe_busy;
708 
709 	/*
710 	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
711 	 */
712 	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
713 		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
714 		wakeup(rpipe);
715 	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
716 		/*
717 		 * Handle write blocking hysteresis.
718 		 */
719 		if (rpipe->pipe_state & PIPE_WANTW) {
720 			rpipe->pipe_state &= ~PIPE_WANTW;
721 			wakeup(rpipe);
722 		}
723 	}
724 
725 	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
726 		pipeselwakeup(rpipe);
727 
728 	PIPE_UNLOCK(rpipe);
729 	return (error);
730 }
731 
732 #ifndef PIPE_NODIRECT
733 /*
734  * Map the sending processes' buffer into kernel space and wire it.
735  * This is similar to a physical write operation.
736  */
737 static int
738 pipe_build_write_buffer(wpipe, uio)
739 	struct pipe *wpipe;
740 	struct uio *uio;
741 {
742 	pmap_t pmap;
743 	u_int size;
744 	int i, j;
745 	vm_offset_t addr, endaddr;
746 
747 	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
748 	KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
749 		("Clone attempt on non-direct write pipe!"));
750 
751 	size = (u_int) uio->uio_iov->iov_len;
752 	if (size > wpipe->pipe_buffer.size)
753 		size = wpipe->pipe_buffer.size;
754 
755 	pmap = vmspace_pmap(curproc->p_vmspace);
756 	endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
757 	addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
758 	for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
759 		/*
760 		 * vm_fault_quick() can sleep.  Consequently,
761 		 * vm_page_lock_queue() and vm_page_unlock_queue()
762 		 * should not be performed outside of this loop.
763 		 */
764 	race:
765 		if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0) {
766 			vm_page_lock_queues();
767 			for (j = 0; j < i; j++)
768 				vm_page_unhold(wpipe->pipe_map.ms[j]);
769 			vm_page_unlock_queues();
770 			return (EFAULT);
771 		}
772 		wpipe->pipe_map.ms[i] = pmap_extract_and_hold(pmap, addr,
773 		    VM_PROT_READ);
774 		if (wpipe->pipe_map.ms[i] == NULL)
775 			goto race;
776 	}
777 
778 /*
779  * set up the control block
780  */
781 	wpipe->pipe_map.npages = i;
782 	wpipe->pipe_map.pos =
783 	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
784 	wpipe->pipe_map.cnt = size;
785 
786 /*
787  * and update the uio data
788  */
789 
790 	uio->uio_iov->iov_len -= size;
791 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
792 	if (uio->uio_iov->iov_len == 0)
793 		uio->uio_iov++;
794 	uio->uio_resid -= size;
795 	uio->uio_offset += size;
796 	return (0);
797 }
798 
799 /*
800  * unmap and unwire the process buffer
801  */
802 static void
803 pipe_destroy_write_buffer(wpipe)
804 	struct pipe *wpipe;
805 {
806 	int i;
807 
808 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
809 	vm_page_lock_queues();
810 	for (i = 0; i < wpipe->pipe_map.npages; i++) {
811 		vm_page_unhold(wpipe->pipe_map.ms[i]);
812 	}
813 	vm_page_unlock_queues();
814 	wpipe->pipe_map.npages = 0;
815 }
816 
817 /*
818  * In the case of a signal, the writing process might go away.  This
819  * code copies the data into the circular buffer so that the source
820  * pages can be freed without loss of data.
821  */
822 static void
823 pipe_clone_write_buffer(wpipe)
824 	struct pipe *wpipe;
825 {
826 	struct uio uio;
827 	struct iovec iov;
828 	int size;
829 	int pos;
830 
831 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
832 	size = wpipe->pipe_map.cnt;
833 	pos = wpipe->pipe_map.pos;
834 
835 	wpipe->pipe_buffer.in = size;
836 	wpipe->pipe_buffer.out = 0;
837 	wpipe->pipe_buffer.cnt = size;
838 	wpipe->pipe_state &= ~PIPE_DIRECTW;
839 
840 	PIPE_UNLOCK(wpipe);
841 	iov.iov_base = wpipe->pipe_buffer.buffer;
842 	iov.iov_len = size;
843 	uio.uio_iov = &iov;
844 	uio.uio_iovcnt = 1;
845 	uio.uio_offset = 0;
846 	uio.uio_resid = size;
847 	uio.uio_segflg = UIO_SYSSPACE;
848 	uio.uio_rw = UIO_READ;
849 	uio.uio_td = curthread;
850 	uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
851 	PIPE_LOCK(wpipe);
852 	pipe_destroy_write_buffer(wpipe);
853 }
854 
855 /*
856  * This implements the pipe buffer write mechanism.  Note that only
857  * a direct write OR a normal pipe write can be pending at any given time.
858  * If there are any characters in the pipe buffer, the direct write will
859  * be deferred until the receiving process grabs all of the bytes from
860  * the pipe buffer.  Then the direct mapping write is set-up.
861  */
862 static int
863 pipe_direct_write(wpipe, uio)
864 	struct pipe *wpipe;
865 	struct uio *uio;
866 {
867 	int error;
868 
869 retry:
870 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
871 	error = pipelock(wpipe, 1);
872 	if (wpipe->pipe_state & PIPE_EOF)
873 		error = EPIPE;
874 	if (error) {
875 		pipeunlock(wpipe);
876 		goto error1;
877 	}
878 	while (wpipe->pipe_state & PIPE_DIRECTW) {
879 		if (wpipe->pipe_state & PIPE_WANTR) {
880 			wpipe->pipe_state &= ~PIPE_WANTR;
881 			wakeup(wpipe);
882 		}
883 		wpipe->pipe_state |= PIPE_WANTW;
884 		pipeunlock(wpipe);
885 		error = msleep(wpipe, PIPE_MTX(wpipe),
886 		    PRIBIO | PCATCH, "pipdww", 0);
887 		if (error)
888 			goto error1;
889 		else
890 			goto retry;
891 	}
892 	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
893 	if (wpipe->pipe_buffer.cnt > 0) {
894 		if (wpipe->pipe_state & PIPE_WANTR) {
895 			wpipe->pipe_state &= ~PIPE_WANTR;
896 			wakeup(wpipe);
897 		}
898 		wpipe->pipe_state |= PIPE_WANTW;
899 		pipeunlock(wpipe);
900 		error = msleep(wpipe, PIPE_MTX(wpipe),
901 		    PRIBIO | PCATCH, "pipdwc", 0);
902 		if (error)
903 			goto error1;
904 		else
905 			goto retry;
906 	}
907 
908 	wpipe->pipe_state |= PIPE_DIRECTW;
909 
910 	PIPE_UNLOCK(wpipe);
911 	error = pipe_build_write_buffer(wpipe, uio);
912 	PIPE_LOCK(wpipe);
913 	if (error) {
914 		wpipe->pipe_state &= ~PIPE_DIRECTW;
915 		pipeunlock(wpipe);
916 		goto error1;
917 	}
918 
919 	error = 0;
920 	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
921 		if (wpipe->pipe_state & PIPE_EOF) {
922 			pipe_destroy_write_buffer(wpipe);
923 			pipeselwakeup(wpipe);
924 			pipeunlock(wpipe);
925 			error = EPIPE;
926 			goto error1;
927 		}
928 		if (wpipe->pipe_state & PIPE_WANTR) {
929 			wpipe->pipe_state &= ~PIPE_WANTR;
930 			wakeup(wpipe);
931 		}
932 		pipeselwakeup(wpipe);
933 		pipeunlock(wpipe);
934 		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
935 		    "pipdwt", 0);
936 		pipelock(wpipe, 0);
937 	}
938 
939 	if (wpipe->pipe_state & PIPE_EOF)
940 		error = EPIPE;
941 	if (wpipe->pipe_state & PIPE_DIRECTW) {
942 		/*
943 		 * this bit of trickery substitutes a kernel buffer for
944 		 * the process that might be going away.
945 		 */
946 		pipe_clone_write_buffer(wpipe);
947 	} else {
948 		pipe_destroy_write_buffer(wpipe);
949 	}
950 	pipeunlock(wpipe);
951 	return (error);
952 
953 error1:
954 	wakeup(wpipe);
955 	return (error);
956 }
957 #endif
958 
959 static int
960 pipe_write(fp, uio, active_cred, flags, td)
961 	struct file *fp;
962 	struct uio *uio;
963 	struct ucred *active_cred;
964 	struct thread *td;
965 	int flags;
966 {
967 	int error = 0;
968 	int desiredsize, orig_resid;
969 	struct pipe *wpipe, *rpipe;
970 
971 	rpipe = fp->f_data;
972 	wpipe = rpipe->pipe_peer;
973 
974 	PIPE_LOCK(rpipe);
975 	error = pipelock(wpipe, 1);
976 	if (error) {
977 		PIPE_UNLOCK(rpipe);
978 		return (error);
979 	}
980 	/*
981 	 * detect loss of pipe read side, issue SIGPIPE if lost.
982 	 */
983 	if ((!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
984 		pipeunlock(wpipe);
985 		PIPE_UNLOCK(rpipe);
986 		return (EPIPE);
987 	}
988 #ifdef MAC
989 	error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
990 	if (error) {
991 		pipeunlock(wpipe);
992 		PIPE_UNLOCK(rpipe);
993 		return (error);
994 	}
995 #endif
996 	++wpipe->pipe_busy;
997 
998 	/* Choose a larger size if it's advantageous */
999 	desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1000 	while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1001 		if (piperesizeallowed != 1)
1002 			break;
1003 		if (amountpipekva > maxpipekva / 2)
1004 			break;
1005 		if (desiredsize == BIG_PIPE_SIZE)
1006 			break;
1007 		desiredsize = desiredsize * 2;
1008 	}
1009 
1010 	/* Choose a smaller size if we're in a OOM situation */
1011 	if ((amountpipekva > (3 * maxpipekva) / 4) &&
1012 		(wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1013 		(wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1014 		(piperesizeallowed == 1))
1015 		desiredsize = SMALL_PIPE_SIZE;
1016 
1017 	/* Resize if the above determined that a new size was necessary */
1018 	if ((desiredsize != wpipe->pipe_buffer.size) &&
1019 		((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1020 		PIPE_UNLOCK(wpipe);
1021 		pipespace(wpipe, desiredsize);
1022 		PIPE_LOCK(wpipe);
1023 	}
1024 	if (wpipe->pipe_buffer.size == 0) {
1025 		/*
1026 		 * This can only happen for reverse direction use of pipes
1027 		 * in a complete OOM situation.
1028 		 */
1029 		error = ENOMEM;
1030 		--wpipe->pipe_busy;
1031 		pipeunlock(wpipe);
1032 		PIPE_UNLOCK(wpipe);
1033 		return (error);
1034 	}
1035 
1036 	pipeunlock(wpipe);
1037 
1038 	orig_resid = uio->uio_resid;
1039 
1040 	while (uio->uio_resid) {
1041 		int space;
1042 
1043 		pipelock(wpipe, 0);
1044 		if (wpipe->pipe_state & PIPE_EOF) {
1045 			pipeunlock(wpipe);
1046 			error = EPIPE;
1047 			break;
1048 		}
1049 #ifndef PIPE_NODIRECT
1050 		/*
1051 		 * If the transfer is large, we can gain performance if
1052 		 * we do process-to-process copies directly.
1053 		 * If the write is non-blocking, we don't use the
1054 		 * direct write mechanism.
1055 		 *
1056 		 * The direct write mechanism will detect the reader going
1057 		 * away on us.
1058 		 */
1059 		if (uio->uio_segflg == UIO_USERSPACE &&
1060 		    uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1061 		    wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1062 		    (fp->f_flag & FNONBLOCK) == 0) {
1063 			pipeunlock(wpipe);
1064 			error = pipe_direct_write(wpipe, uio);
1065 			if (error)
1066 				break;
1067 			continue;
1068 		}
1069 #endif
1070 
1071 		/*
1072 		 * Pipe buffered writes cannot be coincidental with
1073 		 * direct writes.  We wait until the currently executing
1074 		 * direct write is completed before we start filling the
1075 		 * pipe buffer.  We break out if a signal occurs or the
1076 		 * reader goes away.
1077 		 */
1078 		if (wpipe->pipe_state & PIPE_DIRECTW) {
1079 			if (wpipe->pipe_state & PIPE_WANTR) {
1080 				wpipe->pipe_state &= ~PIPE_WANTR;
1081 				wakeup(wpipe);
1082 			}
1083 			pipeunlock(wpipe);
1084 			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1085 			    "pipbww", 0);
1086 			if (error)
1087 				break;
1088 			else
1089 				continue;
1090 		}
1091 
1092 		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1093 
1094 		/* Writes of size <= PIPE_BUF must be atomic. */
1095 		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1096 			space = 0;
1097 
1098 		if (space > 0) {
1099 			int size;	/* Transfer size */
1100 			int segsize;	/* first segment to transfer */
1101 
1102 			/*
1103 			 * Transfer size is minimum of uio transfer
1104 			 * and free space in pipe buffer.
1105 			 */
1106 			if (space > uio->uio_resid)
1107 				size = uio->uio_resid;
1108 			else
1109 				size = space;
1110 			/*
1111 			 * First segment to transfer is minimum of
1112 			 * transfer size and contiguous space in
1113 			 * pipe buffer.  If first segment to transfer
1114 			 * is less than the transfer size, we've got
1115 			 * a wraparound in the buffer.
1116 			 */
1117 			segsize = wpipe->pipe_buffer.size -
1118 				wpipe->pipe_buffer.in;
1119 			if (segsize > size)
1120 				segsize = size;
1121 
1122 			/* Transfer first segment */
1123 
1124 			PIPE_UNLOCK(rpipe);
1125 			error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1126 					segsize, uio);
1127 			PIPE_LOCK(rpipe);
1128 
1129 			if (error == 0 && segsize < size) {
1130 				KASSERT(wpipe->pipe_buffer.in + segsize ==
1131 					wpipe->pipe_buffer.size,
1132 					("Pipe buffer wraparound disappeared"));
1133 				/*
1134 				 * Transfer remaining part now, to
1135 				 * support atomic writes.  Wraparound
1136 				 * happened.
1137 				 */
1138 
1139 				PIPE_UNLOCK(rpipe);
1140 				error = uiomove(
1141 				    &wpipe->pipe_buffer.buffer[0],
1142 				    size - segsize, uio);
1143 				PIPE_LOCK(rpipe);
1144 			}
1145 			if (error == 0) {
1146 				wpipe->pipe_buffer.in += size;
1147 				if (wpipe->pipe_buffer.in >=
1148 				    wpipe->pipe_buffer.size) {
1149 					KASSERT(wpipe->pipe_buffer.in ==
1150 						size - segsize +
1151 						wpipe->pipe_buffer.size,
1152 						("Expected wraparound bad"));
1153 					wpipe->pipe_buffer.in = size - segsize;
1154 				}
1155 
1156 				wpipe->pipe_buffer.cnt += size;
1157 				KASSERT(wpipe->pipe_buffer.cnt <=
1158 					wpipe->pipe_buffer.size,
1159 					("Pipe buffer overflow"));
1160 			}
1161 			pipeunlock(wpipe);
1162 			if (error != 0)
1163 				break;
1164 		} else {
1165 			/*
1166 			 * If the "read-side" has been blocked, wake it up now.
1167 			 */
1168 			if (wpipe->pipe_state & PIPE_WANTR) {
1169 				wpipe->pipe_state &= ~PIPE_WANTR;
1170 				wakeup(wpipe);
1171 			}
1172 
1173 			/*
1174 			 * don't block on non-blocking I/O
1175 			 */
1176 			if (fp->f_flag & FNONBLOCK) {
1177 				error = EAGAIN;
1178 				pipeunlock(wpipe);
1179 				break;
1180 			}
1181 
1182 			/*
1183 			 * We have no more space and have something to offer,
1184 			 * wake up select/poll.
1185 			 */
1186 			pipeselwakeup(wpipe);
1187 
1188 			wpipe->pipe_state |= PIPE_WANTW;
1189 			pipeunlock(wpipe);
1190 			error = msleep(wpipe, PIPE_MTX(rpipe),
1191 			    PRIBIO | PCATCH, "pipewr", 0);
1192 			if (error != 0)
1193 				break;
1194 		}
1195 	}
1196 
1197 	pipelock(wpipe, 0);
1198 	--wpipe->pipe_busy;
1199 
1200 	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1201 		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1202 		wakeup(wpipe);
1203 	} else if (wpipe->pipe_buffer.cnt > 0) {
1204 		/*
1205 		 * If we have put any characters in the buffer, we wake up
1206 		 * the reader.
1207 		 */
1208 		if (wpipe->pipe_state & PIPE_WANTR) {
1209 			wpipe->pipe_state &= ~PIPE_WANTR;
1210 			wakeup(wpipe);
1211 		}
1212 	}
1213 
1214 	/*
1215 	 * Don't return EPIPE if I/O was successful
1216 	 */
1217 	if ((wpipe->pipe_buffer.cnt == 0) &&
1218 	    (uio->uio_resid == 0) &&
1219 	    (error == EPIPE)) {
1220 		error = 0;
1221 	}
1222 
1223 	if (error == 0)
1224 		vfs_timestamp(&wpipe->pipe_mtime);
1225 
1226 	/*
1227 	 * We have something to offer,
1228 	 * wake up select/poll.
1229 	 */
1230 	if (wpipe->pipe_buffer.cnt)
1231 		pipeselwakeup(wpipe);
1232 
1233 	pipeunlock(wpipe);
1234 	PIPE_UNLOCK(rpipe);
1235 	return (error);
1236 }
1237 
1238 /*
1239  * we implement a very minimal set of ioctls for compatibility with sockets.
1240  */
1241 static int
1242 pipe_ioctl(fp, cmd, data, active_cred, td)
1243 	struct file *fp;
1244 	u_long cmd;
1245 	void *data;
1246 	struct ucred *active_cred;
1247 	struct thread *td;
1248 {
1249 	struct pipe *mpipe = fp->f_data;
1250 	int error;
1251 
1252 	PIPE_LOCK(mpipe);
1253 
1254 #ifdef MAC
1255 	error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1256 	if (error) {
1257 		PIPE_UNLOCK(mpipe);
1258 		return (error);
1259 	}
1260 #endif
1261 
1262 	error = 0;
1263 	switch (cmd) {
1264 
1265 	case FIONBIO:
1266 		break;
1267 
1268 	case FIOASYNC:
1269 		if (*(int *)data) {
1270 			mpipe->pipe_state |= PIPE_ASYNC;
1271 		} else {
1272 			mpipe->pipe_state &= ~PIPE_ASYNC;
1273 		}
1274 		break;
1275 
1276 	case FIONREAD:
1277 		if (mpipe->pipe_state & PIPE_DIRECTW)
1278 			*(int *)data = mpipe->pipe_map.cnt;
1279 		else
1280 			*(int *)data = mpipe->pipe_buffer.cnt;
1281 		break;
1282 
1283 	case FIOSETOWN:
1284 		PIPE_UNLOCK(mpipe);
1285 		error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1286 		goto out_unlocked;
1287 
1288 	case FIOGETOWN:
1289 		*(int *)data = fgetown(&mpipe->pipe_sigio);
1290 		break;
1291 
1292 	/* This is deprecated, FIOSETOWN should be used instead. */
1293 	case TIOCSPGRP:
1294 		PIPE_UNLOCK(mpipe);
1295 		error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1296 		goto out_unlocked;
1297 
1298 	/* This is deprecated, FIOGETOWN should be used instead. */
1299 	case TIOCGPGRP:
1300 		*(int *)data = -fgetown(&mpipe->pipe_sigio);
1301 		break;
1302 
1303 	default:
1304 		error = ENOTTY;
1305 		break;
1306 	}
1307 	PIPE_UNLOCK(mpipe);
1308 out_unlocked:
1309 	return (error);
1310 }
1311 
1312 static int
1313 pipe_poll(fp, events, active_cred, td)
1314 	struct file *fp;
1315 	int events;
1316 	struct ucred *active_cred;
1317 	struct thread *td;
1318 {
1319 	struct pipe *rpipe = fp->f_data;
1320 	struct pipe *wpipe;
1321 	int revents = 0;
1322 #ifdef MAC
1323 	int error;
1324 #endif
1325 
1326 	wpipe = rpipe->pipe_peer;
1327 	PIPE_LOCK(rpipe);
1328 #ifdef MAC
1329 	error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1330 	if (error)
1331 		goto locked_error;
1332 #endif
1333 	if (events & (POLLIN | POLLRDNORM))
1334 		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1335 		    (rpipe->pipe_buffer.cnt > 0) ||
1336 		    (rpipe->pipe_state & PIPE_EOF))
1337 			revents |= events & (POLLIN | POLLRDNORM);
1338 
1339 	if (events & (POLLOUT | POLLWRNORM))
1340 		if (!wpipe->pipe_present || (wpipe->pipe_state & PIPE_EOF) ||
1341 		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1342 		     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1343 			revents |= events & (POLLOUT | POLLWRNORM);
1344 
1345 	if ((rpipe->pipe_state & PIPE_EOF) ||
1346 	    (!wpipe->pipe_present) ||
1347 	    (wpipe->pipe_state & PIPE_EOF))
1348 		revents |= POLLHUP;
1349 
1350 	if (revents == 0) {
1351 		if (events & (POLLIN | POLLRDNORM)) {
1352 			selrecord(td, &rpipe->pipe_sel);
1353 			rpipe->pipe_state |= PIPE_SEL;
1354 		}
1355 
1356 		if (events & (POLLOUT | POLLWRNORM)) {
1357 			selrecord(td, &wpipe->pipe_sel);
1358 			wpipe->pipe_state |= PIPE_SEL;
1359 		}
1360 	}
1361 #ifdef MAC
1362 locked_error:
1363 #endif
1364 	PIPE_UNLOCK(rpipe);
1365 
1366 	return (revents);
1367 }
1368 
1369 /*
1370  * We shouldn't need locks here as we're doing a read and this should
1371  * be a natural race.
1372  */
1373 static int
1374 pipe_stat(fp, ub, active_cred, td)
1375 	struct file *fp;
1376 	struct stat *ub;
1377 	struct ucred *active_cred;
1378 	struct thread *td;
1379 {
1380 	struct pipe *pipe = fp->f_data;
1381 #ifdef MAC
1382 	int error;
1383 
1384 	PIPE_LOCK(pipe);
1385 	error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1386 	PIPE_UNLOCK(pipe);
1387 	if (error)
1388 		return (error);
1389 #endif
1390 	bzero(ub, sizeof(*ub));
1391 	ub->st_mode = S_IFIFO;
1392 	ub->st_blksize = PAGE_SIZE;
1393 	if (pipe->pipe_state & PIPE_DIRECTW)
1394 		ub->st_size = pipe->pipe_map.cnt;
1395 	else
1396 		ub->st_size = pipe->pipe_buffer.cnt;
1397 	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1398 	ub->st_atimespec = pipe->pipe_atime;
1399 	ub->st_mtimespec = pipe->pipe_mtime;
1400 	ub->st_ctimespec = pipe->pipe_ctime;
1401 	ub->st_uid = fp->f_cred->cr_uid;
1402 	ub->st_gid = fp->f_cred->cr_gid;
1403 	/*
1404 	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1405 	 * XXX (st_dev, st_ino) should be unique.
1406 	 */
1407 	return (0);
1408 }
1409 
1410 /* ARGSUSED */
1411 static int
1412 pipe_close(fp, td)
1413 	struct file *fp;
1414 	struct thread *td;
1415 {
1416 	struct pipe *cpipe = fp->f_data;
1417 
1418 	fp->f_ops = &badfileops;
1419 	fp->f_data = NULL;
1420 	funsetown(&cpipe->pipe_sigio);
1421 	pipeclose(cpipe);
1422 	return (0);
1423 }
1424 
1425 static void
1426 pipe_free_kmem(cpipe)
1427 	struct pipe *cpipe;
1428 {
1429 
1430 	KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1431 	    ("pipe_free_kmem: pipe mutex locked"));
1432 
1433 	if (cpipe->pipe_buffer.buffer != NULL) {
1434 		atomic_subtract_int(&amountpipekva, cpipe->pipe_buffer.size);
1435 		vm_map_remove(pipe_map,
1436 		    (vm_offset_t)cpipe->pipe_buffer.buffer,
1437 		    (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1438 		cpipe->pipe_buffer.buffer = NULL;
1439 	}
1440 #ifndef PIPE_NODIRECT
1441 	{
1442 		cpipe->pipe_map.cnt = 0;
1443 		cpipe->pipe_map.pos = 0;
1444 		cpipe->pipe_map.npages = 0;
1445 	}
1446 #endif
1447 }
1448 
1449 /*
1450  * shutdown the pipe
1451  */
1452 static void
1453 pipeclose(cpipe)
1454 	struct pipe *cpipe;
1455 {
1456 	struct pipepair *pp;
1457 	struct pipe *ppipe;
1458 
1459 	KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1460 
1461 	PIPE_LOCK(cpipe);
1462 	pipelock(cpipe, 0);
1463 	pp = cpipe->pipe_pair;
1464 
1465 	pipeselwakeup(cpipe);
1466 
1467 	/*
1468 	 * If the other side is blocked, wake it up saying that
1469 	 * we want to close it down.
1470 	 */
1471 	cpipe->pipe_state |= PIPE_EOF;
1472 	while (cpipe->pipe_busy) {
1473 		wakeup(cpipe);
1474 		cpipe->pipe_state |= PIPE_WANT;
1475 		pipeunlock(cpipe);
1476 		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1477 		pipelock(cpipe, 0);
1478 	}
1479 
1480 
1481 	/*
1482 	 * Disconnect from peer, if any.
1483 	 */
1484 	ppipe = cpipe->pipe_peer;
1485 	if (ppipe->pipe_present != 0) {
1486 		pipeselwakeup(ppipe);
1487 
1488 		ppipe->pipe_state |= PIPE_EOF;
1489 		wakeup(ppipe);
1490 		KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1491 	}
1492 
1493 	/*
1494 	 * Mark this endpoint as free.  Release kmem resources.  We
1495 	 * don't mark this endpoint as unused until we've finished
1496 	 * doing that, or the pipe might disappear out from under
1497 	 * us.
1498 	 */
1499 	PIPE_UNLOCK(cpipe);
1500 	pipe_free_kmem(cpipe);
1501 	PIPE_LOCK(cpipe);
1502 	cpipe->pipe_present = 0;
1503 	pipeunlock(cpipe);
1504 	knlist_clear(&cpipe->pipe_sel.si_note, 1);
1505 	knlist_destroy(&cpipe->pipe_sel.si_note);
1506 
1507 	/*
1508 	 * If both endpoints are now closed, release the memory for the
1509 	 * pipe pair.  If not, unlock.
1510 	 */
1511 	if (ppipe->pipe_present == 0) {
1512 		PIPE_UNLOCK(cpipe);
1513 #ifdef MAC
1514 		mac_pipe_destroy(pp);
1515 #endif
1516 		uma_zfree(pipe_zone, cpipe->pipe_pair);
1517 	} else
1518 		PIPE_UNLOCK(cpipe);
1519 }
1520 
1521 /*ARGSUSED*/
1522 static int
1523 pipe_kqfilter(struct file *fp, struct knote *kn)
1524 {
1525 	struct pipe *cpipe;
1526 
1527 	cpipe = kn->kn_fp->f_data;
1528 	PIPE_LOCK(cpipe);
1529 	switch (kn->kn_filter) {
1530 	case EVFILT_READ:
1531 		kn->kn_fop = &pipe_rfiltops;
1532 		break;
1533 	case EVFILT_WRITE:
1534 		kn->kn_fop = &pipe_wfiltops;
1535 		if (!cpipe->pipe_peer->pipe_present) {
1536 			/* other end of pipe has been closed */
1537 			PIPE_UNLOCK(cpipe);
1538 			return (EPIPE);
1539 		}
1540 		cpipe = cpipe->pipe_peer;
1541 		break;
1542 	default:
1543 		PIPE_UNLOCK(cpipe);
1544 		return (EINVAL);
1545 	}
1546 
1547 	knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1548 	PIPE_UNLOCK(cpipe);
1549 	return (0);
1550 }
1551 
1552 static void
1553 filt_pipedetach(struct knote *kn)
1554 {
1555 	struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1556 
1557 	PIPE_LOCK(cpipe);
1558 	if (kn->kn_filter == EVFILT_WRITE) {
1559 		if (!cpipe->pipe_peer->pipe_present) {
1560 			PIPE_UNLOCK(cpipe);
1561 			return;
1562 		}
1563 		cpipe = cpipe->pipe_peer;
1564 	}
1565 	knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1566 	PIPE_UNLOCK(cpipe);
1567 }
1568 
1569 /*ARGSUSED*/
1570 static int
1571 filt_piperead(struct knote *kn, long hint)
1572 {
1573 	struct pipe *rpipe = kn->kn_fp->f_data;
1574 	struct pipe *wpipe = rpipe->pipe_peer;
1575 	int ret;
1576 
1577 	PIPE_LOCK(rpipe);
1578 	kn->kn_data = rpipe->pipe_buffer.cnt;
1579 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1580 		kn->kn_data = rpipe->pipe_map.cnt;
1581 
1582 	if ((rpipe->pipe_state & PIPE_EOF) ||
1583 	    (!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1584 		kn->kn_flags |= EV_EOF;
1585 		PIPE_UNLOCK(rpipe);
1586 		return (1);
1587 	}
1588 	ret = kn->kn_data > 0;
1589 	PIPE_UNLOCK(rpipe);
1590 	return ret;
1591 }
1592 
1593 /*ARGSUSED*/
1594 static int
1595 filt_pipewrite(struct knote *kn, long hint)
1596 {
1597 	struct pipe *rpipe = kn->kn_fp->f_data;
1598 	struct pipe *wpipe = rpipe->pipe_peer;
1599 
1600 	PIPE_LOCK(rpipe);
1601 	if ((!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1602 		kn->kn_data = 0;
1603 		kn->kn_flags |= EV_EOF;
1604 		PIPE_UNLOCK(rpipe);
1605 		return (1);
1606 	}
1607 	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1608 	if (wpipe->pipe_state & PIPE_DIRECTW)
1609 		kn->kn_data = 0;
1610 
1611 	PIPE_UNLOCK(rpipe);
1612 	return (kn->kn_data >= PIPE_BUF);
1613 }
1614