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