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