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