xref: /netbsd-src/sys/kern/sys_pipe.c (revision abb0f93cd77b67f080613360c65701f85e5f5cfe)
1 /*	$NetBSD: sys_pipe.c,v 1.123 2009/12/12 21:28:04 dsl Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2007, 2008, 2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Paul Kranenburg, and by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1996 John S. Dyson
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice immediately at the beginning of the file, without modification,
41  *    this list of conditions, and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Absolutely no warranty of function or purpose is made by the author
46  *    John S. Dyson.
47  * 4. Modifications may be freely made to this file if the above conditions
48  *    are met.
49  */
50 
51 /*
52  * This file contains a high-performance replacement for the socket-based
53  * pipes scheme originally used.  It does not support all features of
54  * sockets, but does do everything that pipes normally do.
55  *
56  * This code has two modes of operation, a small write mode and a large
57  * write mode.  The small write mode acts like conventional pipes with
58  * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
59  * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
60  * and PIPE_SIZE in size it is mapped read-only into the kernel address space
61  * using the UVM page loan facility from where the receiving process can copy
62  * the data directly from the pages in the sending process.
63  *
64  * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
65  * happen for small transfers so that the system will not spend all of
66  * its time context switching.  PIPE_SIZE is constrained by the
67  * amount of kernel virtual memory.
68  */
69 
70 #include <sys/cdefs.h>
71 __KERNEL_RCSID(0, "$NetBSD: sys_pipe.c,v 1.123 2009/12/12 21:28:04 dsl Exp $");
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/proc.h>
76 #include <sys/fcntl.h>
77 #include <sys/file.h>
78 #include <sys/filedesc.h>
79 #include <sys/filio.h>
80 #include <sys/kernel.h>
81 #include <sys/ttycom.h>
82 #include <sys/stat.h>
83 #include <sys/poll.h>
84 #include <sys/signalvar.h>
85 #include <sys/vnode.h>
86 #include <sys/uio.h>
87 #include <sys/select.h>
88 #include <sys/mount.h>
89 #include <sys/syscallargs.h>
90 #include <sys/sysctl.h>
91 #include <sys/kauth.h>
92 #include <sys/atomic.h>
93 #include <sys/pipe.h>
94 
95 #include <uvm/uvm.h>
96 
97 /*
98  * Use this to disable direct I/O and decrease the code size:
99  * #define PIPE_NODIRECT
100  */
101 
102 /* XXX Disabled for now; rare hangs switching between direct/buffered */
103 #define PIPE_NODIRECT
104 
105 static int	pipe_read(file_t *, off_t *, struct uio *, kauth_cred_t, int);
106 static int	pipe_write(file_t *, off_t *, struct uio *, kauth_cred_t, int);
107 static int	pipe_close(file_t *);
108 static int	pipe_poll(file_t *, int);
109 static int	pipe_kqfilter(file_t *, struct knote *);
110 static int	pipe_stat(file_t *, struct stat *);
111 static int	pipe_ioctl(file_t *, u_long, void *);
112 static void	pipe_abort(file_t *);
113 
114 static const struct fileops pipeops = {
115 	.fo_read = pipe_read,
116 	.fo_write = pipe_write,
117 	.fo_ioctl = pipe_ioctl,
118 	.fo_fcntl = fnullop_fcntl,
119 	.fo_poll = pipe_poll,
120 	.fo_stat = pipe_stat,
121 	.fo_close = pipe_close,
122 	.fo_kqfilter = pipe_kqfilter,
123 	.fo_abort = pipe_abort,
124 };
125 
126 /*
127  * Default pipe buffer size(s), this can be kind-of large now because pipe
128  * space is pageable.  The pipe code will try to maintain locality of
129  * reference for performance reasons, so small amounts of outstanding I/O
130  * will not wipe the cache.
131  */
132 #define	MINPIPESIZE	(PIPE_SIZE / 3)
133 #define	MAXPIPESIZE	(2 * PIPE_SIZE / 3)
134 
135 /*
136  * Maximum amount of kva for pipes -- this is kind-of a soft limit, but
137  * is there so that on large systems, we don't exhaust it.
138  */
139 #define	MAXPIPEKVA	(8 * 1024 * 1024)
140 static u_int	maxpipekva = MAXPIPEKVA;
141 
142 /*
143  * Limit for direct transfers, we cannot, of course limit
144  * the amount of kva for pipes in general though.
145  */
146 #define	LIMITPIPEKVA	(16 * 1024 * 1024)
147 static u_int	limitpipekva = LIMITPIPEKVA;
148 
149 /*
150  * Limit the number of "big" pipes
151  */
152 #define	LIMITBIGPIPES	32
153 static u_int	maxbigpipes = LIMITBIGPIPES;
154 static u_int	nbigpipe = 0;
155 
156 /*
157  * Amount of KVA consumed by pipe buffers.
158  */
159 static u_int	amountpipekva = 0;
160 
161 static void	pipeclose(struct pipe *);
162 static void	pipe_free_kmem(struct pipe *);
163 static int	pipe_create(struct pipe **, pool_cache_t);
164 static int	pipelock(struct pipe *, int);
165 static inline void pipeunlock(struct pipe *);
166 static void	pipeselwakeup(struct pipe *, struct pipe *, int);
167 #ifndef PIPE_NODIRECT
168 static int	pipe_direct_write(file_t *, struct pipe *, struct uio *);
169 #endif
170 static int	pipespace(struct pipe *, int);
171 static int	pipe_ctor(void *, void *, int);
172 static void	pipe_dtor(void *, void *);
173 
174 #ifndef PIPE_NODIRECT
175 static int	pipe_loan_alloc(struct pipe *, int);
176 static void	pipe_loan_free(struct pipe *);
177 #endif /* PIPE_NODIRECT */
178 
179 static pool_cache_t	pipe_wr_cache;
180 static pool_cache_t	pipe_rd_cache;
181 
182 void
183 pipe_init(void)
184 {
185 
186 	/* Writer side is not automatically allocated KVA. */
187 	pipe_wr_cache = pool_cache_init(sizeof(struct pipe), 0, 0, 0, "pipewr",
188 	    NULL, IPL_NONE, pipe_ctor, pipe_dtor, NULL);
189 	KASSERT(pipe_wr_cache != NULL);
190 
191 	/* Reader side gets preallocated KVA. */
192 	pipe_rd_cache = pool_cache_init(sizeof(struct pipe), 0, 0, 0, "piperd",
193 	    NULL, IPL_NONE, pipe_ctor, pipe_dtor, (void *)1);
194 	KASSERT(pipe_rd_cache != NULL);
195 }
196 
197 static int
198 pipe_ctor(void *arg, void *obj, int flags)
199 {
200 	struct pipe *pipe;
201 	vaddr_t va;
202 
203 	pipe = obj;
204 
205 	memset(pipe, 0, sizeof(struct pipe));
206 	if (arg != NULL) {
207 		/* Preallocate space. */
208 		va = uvm_km_alloc(kernel_map, PIPE_SIZE, 0,
209 		    UVM_KMF_PAGEABLE | UVM_KMF_WAITVA);
210 		KASSERT(va != 0);
211 		pipe->pipe_kmem = va;
212 		atomic_add_int(&amountpipekva, PIPE_SIZE);
213 	}
214 	cv_init(&pipe->pipe_rcv, "piperd");
215 	cv_init(&pipe->pipe_wcv, "pipewr");
216 	cv_init(&pipe->pipe_draincv, "pipedrain");
217 	cv_init(&pipe->pipe_lkcv, "pipelk");
218 	selinit(&pipe->pipe_sel);
219 	pipe->pipe_state = PIPE_SIGNALR;
220 
221 	return 0;
222 }
223 
224 static void
225 pipe_dtor(void *arg, void *obj)
226 {
227 	struct pipe *pipe;
228 
229 	pipe = obj;
230 
231 	cv_destroy(&pipe->pipe_rcv);
232 	cv_destroy(&pipe->pipe_wcv);
233 	cv_destroy(&pipe->pipe_draincv);
234 	cv_destroy(&pipe->pipe_lkcv);
235 	seldestroy(&pipe->pipe_sel);
236 	if (pipe->pipe_kmem != 0) {
237 		uvm_km_free(kernel_map, pipe->pipe_kmem, PIPE_SIZE,
238 		    UVM_KMF_PAGEABLE);
239 		atomic_add_int(&amountpipekva, -PIPE_SIZE);
240 	}
241 }
242 
243 /*
244  * The pipe system call for the DTYPE_PIPE type of pipes
245  */
246 int
247 sys_pipe(struct lwp *l, const void *v, register_t *retval)
248 {
249 	struct pipe *rpipe, *wpipe;
250 	file_t *rf, *wf;
251 	int fd, error;
252 	proc_t *p;
253 
254 	p = curproc;
255 	rpipe = wpipe = NULL;
256 	if (pipe_create(&rpipe, pipe_rd_cache) ||
257 	    pipe_create(&wpipe, pipe_wr_cache)) {
258 		error = ENOMEM;
259 		goto free2;
260 	}
261 	rpipe->pipe_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
262 	wpipe->pipe_lock = rpipe->pipe_lock;
263 	mutex_obj_hold(wpipe->pipe_lock);
264 
265 	error = fd_allocfile(&rf, &fd);
266 	if (error)
267 		goto free2;
268 	retval[0] = fd;
269 	rf->f_flag = FREAD;
270 	rf->f_type = DTYPE_PIPE;
271 	rf->f_data = (void *)rpipe;
272 	rf->f_ops = &pipeops;
273 
274 	error = fd_allocfile(&wf, &fd);
275 	if (error)
276 		goto free3;
277 	retval[1] = fd;
278 	wf->f_flag = FWRITE;
279 	wf->f_type = DTYPE_PIPE;
280 	wf->f_data = (void *)wpipe;
281 	wf->f_ops = &pipeops;
282 
283 	rpipe->pipe_peer = wpipe;
284 	wpipe->pipe_peer = rpipe;
285 
286 	fd_affix(p, rf, (int)retval[0]);
287 	fd_affix(p, wf, (int)retval[1]);
288 	return (0);
289 free3:
290 	fd_abort(p, rf, (int)retval[0]);
291 free2:
292 	pipeclose(wpipe);
293 	pipeclose(rpipe);
294 
295 	return (error);
296 }
297 
298 /*
299  * Allocate kva for pipe circular buffer, the space is pageable
300  * This routine will 'realloc' the size of a pipe safely, if it fails
301  * it will retain the old buffer.
302  * If it fails it will return ENOMEM.
303  */
304 static int
305 pipespace(struct pipe *pipe, int size)
306 {
307 	void *buffer;
308 
309 	/*
310 	 * Allocate pageable virtual address space.  Physical memory is
311 	 * allocated on demand.
312 	 */
313 	if (size == PIPE_SIZE && pipe->pipe_kmem != 0) {
314 		buffer = (void *)pipe->pipe_kmem;
315 	} else {
316 		buffer = (void *)uvm_km_alloc(kernel_map, round_page(size),
317 		    0, UVM_KMF_PAGEABLE);
318 		if (buffer == NULL)
319 			return (ENOMEM);
320 		atomic_add_int(&amountpipekva, size);
321 	}
322 
323 	/* free old resources if we're resizing */
324 	pipe_free_kmem(pipe);
325 	pipe->pipe_buffer.buffer = buffer;
326 	pipe->pipe_buffer.size = size;
327 	pipe->pipe_buffer.in = 0;
328 	pipe->pipe_buffer.out = 0;
329 	pipe->pipe_buffer.cnt = 0;
330 	return (0);
331 }
332 
333 /*
334  * Initialize and allocate VM and memory for pipe.
335  */
336 static int
337 pipe_create(struct pipe **pipep, pool_cache_t cache)
338 {
339 	struct pipe *pipe;
340 	int error;
341 
342 	pipe = pool_cache_get(cache, PR_WAITOK);
343 	KASSERT(pipe != NULL);
344 	*pipep = pipe;
345 	error = 0;
346 	getnanotime(&pipe->pipe_btime);
347 	pipe->pipe_atime = pipe->pipe_mtime = pipe->pipe_btime;
348 	pipe->pipe_lock = NULL;
349 	if (cache == pipe_rd_cache) {
350 		error = pipespace(pipe, PIPE_SIZE);
351 	} else {
352 		pipe->pipe_buffer.buffer = NULL;
353 		pipe->pipe_buffer.size = 0;
354 		pipe->pipe_buffer.in = 0;
355 		pipe->pipe_buffer.out = 0;
356 		pipe->pipe_buffer.cnt = 0;
357 	}
358 	return error;
359 }
360 
361 /*
362  * Lock a pipe for I/O, blocking other access
363  * Called with pipe spin lock held.
364  */
365 static int
366 pipelock(struct pipe *pipe, int catch)
367 {
368 	int error;
369 
370 	KASSERT(mutex_owned(pipe->pipe_lock));
371 
372 	while (pipe->pipe_state & PIPE_LOCKFL) {
373 		pipe->pipe_state |= PIPE_LWANT;
374 		if (catch) {
375 			error = cv_wait_sig(&pipe->pipe_lkcv, pipe->pipe_lock);
376 			if (error != 0)
377 				return error;
378 		} else
379 			cv_wait(&pipe->pipe_lkcv, pipe->pipe_lock);
380 	}
381 
382 	pipe->pipe_state |= PIPE_LOCKFL;
383 
384 	return 0;
385 }
386 
387 /*
388  * unlock a pipe I/O lock
389  */
390 static inline void
391 pipeunlock(struct pipe *pipe)
392 {
393 
394 	KASSERT(pipe->pipe_state & PIPE_LOCKFL);
395 
396 	pipe->pipe_state &= ~PIPE_LOCKFL;
397 	if (pipe->pipe_state & PIPE_LWANT) {
398 		pipe->pipe_state &= ~PIPE_LWANT;
399 		cv_broadcast(&pipe->pipe_lkcv);
400 	}
401 }
402 
403 /*
404  * Select/poll wakup. This also sends SIGIO to peer connected to
405  * 'sigpipe' side of pipe.
406  */
407 static void
408 pipeselwakeup(struct pipe *selp, struct pipe *sigp, int code)
409 {
410 	int band;
411 
412 	switch (code) {
413 	case POLL_IN:
414 		band = POLLIN|POLLRDNORM;
415 		break;
416 	case POLL_OUT:
417 		band = POLLOUT|POLLWRNORM;
418 		break;
419 	case POLL_HUP:
420 		band = POLLHUP;
421 		break;
422 	case POLL_ERR:
423 		band = POLLERR;
424 		break;
425 	default:
426 		band = 0;
427 #ifdef DIAGNOSTIC
428 		printf("bad siginfo code %d in pipe notification.\n", code);
429 #endif
430 		break;
431 	}
432 
433 	selnotify(&selp->pipe_sel, band, NOTE_SUBMIT);
434 
435 	if (sigp == NULL || (sigp->pipe_state & PIPE_ASYNC) == 0)
436 		return;
437 
438 	fownsignal(sigp->pipe_pgid, SIGIO, code, band, selp);
439 }
440 
441 static int
442 pipe_read(file_t *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
443     int flags)
444 {
445 	struct pipe *rpipe = (struct pipe *) fp->f_data;
446 	struct pipebuf *bp = &rpipe->pipe_buffer;
447 	kmutex_t *lock = rpipe->pipe_lock;
448 	int error;
449 	size_t nread = 0;
450 	size_t size;
451 	size_t ocnt;
452 
453 	mutex_enter(lock);
454 	++rpipe->pipe_busy;
455 	ocnt = bp->cnt;
456 
457 again:
458 	error = pipelock(rpipe, 1);
459 	if (error)
460 		goto unlocked_error;
461 
462 	while (uio->uio_resid) {
463 		/*
464 		 * Normal pipe buffer receive.
465 		 */
466 		if (bp->cnt > 0) {
467 			size = bp->size - bp->out;
468 			if (size > bp->cnt)
469 				size = bp->cnt;
470 			if (size > uio->uio_resid)
471 				size = uio->uio_resid;
472 
473 			mutex_exit(lock);
474 			error = uiomove((char *)bp->buffer + bp->out, size, uio);
475 			mutex_enter(lock);
476 			if (error)
477 				break;
478 
479 			bp->out += size;
480 			if (bp->out >= bp->size)
481 				bp->out = 0;
482 
483 			bp->cnt -= size;
484 
485 			/*
486 			 * If there is no more to read in the pipe, reset
487 			 * its pointers to the beginning.  This improves
488 			 * cache hit stats.
489 			 */
490 			if (bp->cnt == 0) {
491 				bp->in = 0;
492 				bp->out = 0;
493 			}
494 			nread += size;
495 			continue;
496 		}
497 
498 #ifndef PIPE_NODIRECT
499 		if ((rpipe->pipe_state & PIPE_DIRECTR) != 0) {
500 			/*
501 			 * Direct copy, bypassing a kernel buffer.
502 			 */
503 			void *va;
504 			u_int gen;
505 
506 			KASSERT(rpipe->pipe_state & PIPE_DIRECTW);
507 
508 			size = rpipe->pipe_map.cnt;
509 			if (size > uio->uio_resid)
510 				size = uio->uio_resid;
511 
512 			va = (char *)rpipe->pipe_map.kva + rpipe->pipe_map.pos;
513 			gen = rpipe->pipe_map.egen;
514 			mutex_exit(lock);
515 
516 			/*
517 			 * Consume emap and read the data from loaned pages.
518 			 */
519 			uvm_emap_consume(gen);
520 			error = uiomove(va, size, uio);
521 
522 			mutex_enter(lock);
523 			if (error)
524 				break;
525 			nread += size;
526 			rpipe->pipe_map.pos += size;
527 			rpipe->pipe_map.cnt -= size;
528 			if (rpipe->pipe_map.cnt == 0) {
529 				rpipe->pipe_state &= ~PIPE_DIRECTR;
530 				cv_broadcast(&rpipe->pipe_wcv);
531 			}
532 			continue;
533 		}
534 #endif
535 		/*
536 		 * Break if some data was read.
537 		 */
538 		if (nread > 0)
539 			break;
540 
541 		/*
542 		 * Detect EOF condition.
543 		 * Read returns 0 on EOF, no need to set error.
544 		 */
545 		if (rpipe->pipe_state & (PIPE_EOF | PIPE_ABORTED)) {
546 			if (rpipe->pipe_state & PIPE_ABORTED)
547 				/* Another thread has called close() */
548 				error = EBADF;
549 			break;
550 		}
551 
552 		/*
553 		 * Don't block on non-blocking I/O.
554 		 */
555 		if (fp->f_flag & FNONBLOCK) {
556 			error = EAGAIN;
557 			break;
558 		}
559 
560 		/*
561 		 * Unlock the pipe buffer for our remaining processing.
562 		 * We will either break out with an error or we will
563 		 * sleep and relock to loop.
564 		 */
565 		pipeunlock(rpipe);
566 
567 		/*
568 		 * Re-check to see if more direct writes are pending.
569 		 */
570 		if ((rpipe->pipe_state & PIPE_DIRECTR) != 0)
571 			goto again;
572 
573 		/*
574 		 * We want to read more, wake up select/poll.
575 		 */
576 		pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
577 
578 		/*
579 		 * If the "write-side" is blocked, wake it up now.
580 		 */
581 		cv_broadcast(&rpipe->pipe_wcv);
582 
583 		/* Now wait until the pipe is filled */
584 		error = cv_wait_sig(&rpipe->pipe_rcv, lock);
585 		if (error != 0)
586 			goto unlocked_error;
587 		goto again;
588 	}
589 
590 	if (error == 0)
591 		getnanotime(&rpipe->pipe_atime);
592 	pipeunlock(rpipe);
593 
594 unlocked_error:
595 	--rpipe->pipe_busy;
596 	if (rpipe->pipe_busy == 0) {
597 		cv_broadcast(&rpipe->pipe_draincv);
598 	}
599 	if (bp->cnt < MINPIPESIZE) {
600 		cv_broadcast(&rpipe->pipe_wcv);
601 	}
602 
603 	/*
604 	 * If anything was read off the buffer, signal to the writer it's
605 	 * possible to write more data. Also send signal if we are here for the
606 	 * first time after last write.
607 	 */
608 	if ((bp->size - bp->cnt) >= PIPE_BUF
609 	    && (ocnt != bp->cnt || (rpipe->pipe_state & PIPE_SIGNALR))) {
610 		pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
611 		rpipe->pipe_state &= ~PIPE_SIGNALR;
612 	}
613 
614 	mutex_exit(lock);
615 	return (error);
616 }
617 
618 #ifndef PIPE_NODIRECT
619 /*
620  * Allocate structure for loan transfer.
621  */
622 static int
623 pipe_loan_alloc(struct pipe *wpipe, int npages)
624 {
625 	vsize_t len;
626 
627 	len = (vsize_t)npages << PAGE_SHIFT;
628 	atomic_add_int(&amountpipekva, len);
629 	wpipe->pipe_map.kva = uvm_km_alloc(kernel_map, len, 0,
630 	    UVM_KMF_VAONLY | UVM_KMF_WAITVA);
631 	if (wpipe->pipe_map.kva == 0) {
632 		atomic_add_int(&amountpipekva, -len);
633 		return (ENOMEM);
634 	}
635 
636 	wpipe->pipe_map.npages = npages;
637 	wpipe->pipe_map.pgs = kmem_alloc(npages * sizeof(struct vm_page *),
638 	    KM_SLEEP);
639 	return (0);
640 }
641 
642 /*
643  * Free resources allocated for loan transfer.
644  */
645 static void
646 pipe_loan_free(struct pipe *wpipe)
647 {
648 	vsize_t len;
649 
650 	len = (vsize_t)wpipe->pipe_map.npages << PAGE_SHIFT;
651 	uvm_emap_remove(wpipe->pipe_map.kva, len);	/* XXX */
652 	uvm_km_free(kernel_map, wpipe->pipe_map.kva, len, UVM_KMF_VAONLY);
653 	wpipe->pipe_map.kva = 0;
654 	atomic_add_int(&amountpipekva, -len);
655 	kmem_free(wpipe->pipe_map.pgs,
656 	    wpipe->pipe_map.npages * sizeof(struct vm_page *));
657 	wpipe->pipe_map.pgs = NULL;
658 }
659 
660 /*
661  * NetBSD direct write, using uvm_loan() mechanism.
662  * This implements the pipe buffer write mechanism.  Note that only
663  * a direct write OR a normal pipe write can be pending at any given time.
664  * If there are any characters in the pipe buffer, the direct write will
665  * be deferred until the receiving process grabs all of the bytes from
666  * the pipe buffer.  Then the direct mapping write is set-up.
667  *
668  * Called with the long-term pipe lock held.
669  */
670 static int
671 pipe_direct_write(file_t *fp, struct pipe *wpipe, struct uio *uio)
672 {
673 	struct vm_page **pgs;
674 	vaddr_t bbase, base, bend;
675 	vsize_t blen, bcnt;
676 	int error, npages;
677 	voff_t bpos;
678 	kmutex_t *lock = wpipe->pipe_lock;
679 
680 	KASSERT(mutex_owned(wpipe->pipe_lock));
681 	KASSERT(wpipe->pipe_map.cnt == 0);
682 
683 	mutex_exit(lock);
684 
685 	/*
686 	 * Handle first PIPE_CHUNK_SIZE bytes of buffer. Deal with buffers
687 	 * not aligned to PAGE_SIZE.
688 	 */
689 	bbase = (vaddr_t)uio->uio_iov->iov_base;
690 	base = trunc_page(bbase);
691 	bend = round_page(bbase + uio->uio_iov->iov_len);
692 	blen = bend - base;
693 	bpos = bbase - base;
694 
695 	if (blen > PIPE_DIRECT_CHUNK) {
696 		blen = PIPE_DIRECT_CHUNK;
697 		bend = base + blen;
698 		bcnt = PIPE_DIRECT_CHUNK - bpos;
699 	} else {
700 		bcnt = uio->uio_iov->iov_len;
701 	}
702 	npages = blen >> PAGE_SHIFT;
703 
704 	/*
705 	 * Free the old kva if we need more pages than we have
706 	 * allocated.
707 	 */
708 	if (wpipe->pipe_map.kva != 0 && npages > wpipe->pipe_map.npages)
709 		pipe_loan_free(wpipe);
710 
711 	/* Allocate new kva. */
712 	if (wpipe->pipe_map.kva == 0) {
713 		error = pipe_loan_alloc(wpipe, npages);
714 		if (error) {
715 			mutex_enter(lock);
716 			return (error);
717 		}
718 	}
719 
720 	/* Loan the write buffer memory from writer process */
721 	pgs = wpipe->pipe_map.pgs;
722 	error = uvm_loan(&uio->uio_vmspace->vm_map, base, blen,
723 			 pgs, UVM_LOAN_TOPAGE);
724 	if (error) {
725 		pipe_loan_free(wpipe);
726 		mutex_enter(lock);
727 		return (ENOMEM); /* so that caller fallback to ordinary write */
728 	}
729 
730 	/* Enter the loaned pages to KVA, produce new emap generation number. */
731 	uvm_emap_enter(wpipe->pipe_map.kva, pgs, npages);
732 	wpipe->pipe_map.egen = uvm_emap_produce();
733 
734 	/* Now we can put the pipe in direct write mode */
735 	wpipe->pipe_map.pos = bpos;
736 	wpipe->pipe_map.cnt = bcnt;
737 
738 	/*
739 	 * But before we can let someone do a direct read, we
740 	 * have to wait until the pipe is drained.  Release the
741 	 * pipe lock while we wait.
742 	 */
743 	mutex_enter(lock);
744 	wpipe->pipe_state |= PIPE_DIRECTW;
745 	pipeunlock(wpipe);
746 
747 	while (error == 0 && wpipe->pipe_buffer.cnt > 0) {
748 		cv_broadcast(&wpipe->pipe_rcv);
749 		error = cv_wait_sig(&wpipe->pipe_wcv, lock);
750 		if (error == 0 && wpipe->pipe_state & PIPE_EOF)
751 			error = EPIPE;
752 	}
753 
754 	/* Pipe is drained; next read will off the direct buffer */
755 	wpipe->pipe_state |= PIPE_DIRECTR;
756 
757 	/* Wait until the reader is done */
758 	while (error == 0 && (wpipe->pipe_state & PIPE_DIRECTR)) {
759 		cv_broadcast(&wpipe->pipe_rcv);
760 		pipeselwakeup(wpipe, wpipe, POLL_IN);
761 		error = cv_wait_sig(&wpipe->pipe_wcv, lock);
762 		if (error == 0 && wpipe->pipe_state & PIPE_EOF)
763 			error = EPIPE;
764 	}
765 
766 	/* Take pipe out of direct write mode */
767 	wpipe->pipe_state &= ~(PIPE_DIRECTW | PIPE_DIRECTR);
768 
769 	/* Acquire the pipe lock and cleanup */
770 	(void)pipelock(wpipe, 0);
771 	mutex_exit(lock);
772 
773 	if (pgs != NULL) {
774 		/* XXX: uvm_emap_remove */
775 		uvm_unloan(pgs, npages, UVM_LOAN_TOPAGE);
776 	}
777 	if (error || amountpipekva > maxpipekva)
778 		pipe_loan_free(wpipe);
779 
780 	mutex_enter(lock);
781 	if (error) {
782 		pipeselwakeup(wpipe, wpipe, POLL_ERR);
783 
784 		/*
785 		 * If nothing was read from what we offered, return error
786 		 * straight on. Otherwise update uio resid first. Caller
787 		 * will deal with the error condition, returning short
788 		 * write, error, or restarting the write(2) as appropriate.
789 		 */
790 		if (wpipe->pipe_map.cnt == bcnt) {
791 			wpipe->pipe_map.cnt = 0;
792 			cv_broadcast(&wpipe->pipe_wcv);
793 			return (error);
794 		}
795 
796 		bcnt -= wpipe->pipe_map.cnt;
797 	}
798 
799 	uio->uio_resid -= bcnt;
800 	/* uio_offset not updated, not set/used for write(2) */
801 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + bcnt;
802 	uio->uio_iov->iov_len -= bcnt;
803 	if (uio->uio_iov->iov_len == 0) {
804 		uio->uio_iov++;
805 		uio->uio_iovcnt--;
806 	}
807 
808 	wpipe->pipe_map.cnt = 0;
809 	return (error);
810 }
811 #endif /* !PIPE_NODIRECT */
812 
813 static int
814 pipe_write(file_t *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
815     int flags)
816 {
817 	struct pipe *wpipe, *rpipe;
818 	struct pipebuf *bp;
819 	kmutex_t *lock;
820 	int error;
821 
822 	/* We want to write to our peer */
823 	rpipe = (struct pipe *) fp->f_data;
824 	lock = rpipe->pipe_lock;
825 	error = 0;
826 
827 	mutex_enter(lock);
828 	wpipe = rpipe->pipe_peer;
829 
830 	/*
831 	 * Detect loss of pipe read side, issue SIGPIPE if lost.
832 	 */
833 	if (wpipe == NULL || (wpipe->pipe_state & PIPE_EOF) != 0) {
834 		mutex_exit(lock);
835 		return EPIPE;
836 	}
837 	++wpipe->pipe_busy;
838 
839 	/* Aquire the long-term pipe lock */
840 	if ((error = pipelock(wpipe, 1)) != 0) {
841 		--wpipe->pipe_busy;
842 		if (wpipe->pipe_busy == 0) {
843 			cv_broadcast(&wpipe->pipe_draincv);
844 		}
845 		mutex_exit(lock);
846 		return (error);
847 	}
848 
849 	bp = &wpipe->pipe_buffer;
850 
851 	/*
852 	 * If it is advantageous to resize the pipe buffer, do so.
853 	 */
854 	if ((uio->uio_resid > PIPE_SIZE) &&
855 	    (nbigpipe < maxbigpipes) &&
856 #ifndef PIPE_NODIRECT
857 	    (wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
858 #endif
859 	    (bp->size <= PIPE_SIZE) && (bp->cnt == 0)) {
860 
861 		if (pipespace(wpipe, BIG_PIPE_SIZE) == 0)
862 			atomic_inc_uint(&nbigpipe);
863 	}
864 
865 	while (uio->uio_resid) {
866 		size_t space;
867 
868 #ifndef PIPE_NODIRECT
869 		/*
870 		 * Pipe buffered writes cannot be coincidental with
871 		 * direct writes.  Also, only one direct write can be
872 		 * in progress at any one time.  We wait until the currently
873 		 * executing direct write is completed before continuing.
874 		 *
875 		 * We break out if a signal occurs or the reader goes away.
876 		 */
877 		while (error == 0 && wpipe->pipe_state & PIPE_DIRECTW) {
878 			cv_broadcast(&wpipe->pipe_rcv);
879 			pipeunlock(wpipe);
880 			error = cv_wait_sig(&wpipe->pipe_wcv, lock);
881 			(void)pipelock(wpipe, 0);
882 			if (wpipe->pipe_state & PIPE_EOF)
883 				error = EPIPE;
884 		}
885 		if (error)
886 			break;
887 
888 		/*
889 		 * If the transfer is large, we can gain performance if
890 		 * we do process-to-process copies directly.
891 		 * If the write is non-blocking, we don't use the
892 		 * direct write mechanism.
893 		 *
894 		 * The direct write mechanism will detect the reader going
895 		 * away on us.
896 		 */
897 		if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT) &&
898 		    (fp->f_flag & FNONBLOCK) == 0 &&
899 		    (wpipe->pipe_map.kva || (amountpipekva < limitpipekva))) {
900 			error = pipe_direct_write(fp, wpipe, uio);
901 
902 			/*
903 			 * Break out if error occurred, unless it's ENOMEM.
904 			 * ENOMEM means we failed to allocate some resources
905 			 * for direct write, so we just fallback to ordinary
906 			 * write. If the direct write was successful,
907 			 * process rest of data via ordinary write.
908 			 */
909 			if (error == 0)
910 				continue;
911 
912 			if (error != ENOMEM)
913 				break;
914 		}
915 #endif /* PIPE_NODIRECT */
916 
917 		space = bp->size - bp->cnt;
918 
919 		/* Writes of size <= PIPE_BUF must be atomic. */
920 		if ((space < uio->uio_resid) && (uio->uio_resid <= PIPE_BUF))
921 			space = 0;
922 
923 		if (space > 0) {
924 			int size;	/* Transfer size */
925 			int segsize;	/* first segment to transfer */
926 
927 			/*
928 			 * Transfer size is minimum of uio transfer
929 			 * and free space in pipe buffer.
930 			 */
931 			if (space > uio->uio_resid)
932 				size = uio->uio_resid;
933 			else
934 				size = space;
935 			/*
936 			 * First segment to transfer is minimum of
937 			 * transfer size and contiguous space in
938 			 * pipe buffer.  If first segment to transfer
939 			 * is less than the transfer size, we've got
940 			 * a wraparound in the buffer.
941 			 */
942 			segsize = bp->size - bp->in;
943 			if (segsize > size)
944 				segsize = size;
945 
946 			/* Transfer first segment */
947 			mutex_exit(lock);
948 			error = uiomove((char *)bp->buffer + bp->in, segsize,
949 			    uio);
950 
951 			if (error == 0 && segsize < size) {
952 				/*
953 				 * Transfer remaining part now, to
954 				 * support atomic writes.  Wraparound
955 				 * happened.
956 				 */
957 				KASSERT(bp->in + segsize == bp->size);
958 				error = uiomove(bp->buffer,
959 				    size - segsize, uio);
960 			}
961 			mutex_enter(lock);
962 			if (error)
963 				break;
964 
965 			bp->in += size;
966 			if (bp->in >= bp->size) {
967 				KASSERT(bp->in == size - segsize + bp->size);
968 				bp->in = size - segsize;
969 			}
970 
971 			bp->cnt += size;
972 			KASSERT(bp->cnt <= bp->size);
973 		} else {
974 			/*
975 			 * If the "read-side" has been blocked, wake it up now.
976 			 */
977 			cv_broadcast(&wpipe->pipe_rcv);
978 
979 			/*
980 			 * Don't block on non-blocking I/O.
981 			 */
982 			if (fp->f_flag & FNONBLOCK) {
983 				error = EAGAIN;
984 				break;
985 			}
986 
987 			if (wpipe->pipe_state & PIPE_ABORTED) {
988 				/* Another thread has called close() */
989 				if (uio->uio_resid == 0)
990 					error = EBADF;
991 				break;
992 			}
993 
994 			/*
995 			 * We have no more space and have something to offer,
996 			 * wake up select/poll.
997 			 */
998 			if (bp->cnt)
999 				pipeselwakeup(wpipe, wpipe, POLL_IN);
1000 
1001 			pipeunlock(wpipe);
1002 			error = cv_wait_sig(&wpipe->pipe_wcv, lock);
1003 			(void)pipelock(wpipe, 0);
1004 			if (error != 0)
1005 				break;
1006 			/*
1007 			 * If read side wants to go away, we just issue a signal
1008 			 * to ourselves.
1009 			 */
1010 			if (wpipe->pipe_state & PIPE_EOF) {
1011 				error = EPIPE;
1012 				break;
1013 			}
1014 		}
1015 	}
1016 
1017 	--wpipe->pipe_busy;
1018 	if (wpipe->pipe_busy == 0) {
1019 		cv_broadcast(&wpipe->pipe_draincv);
1020 	}
1021 	if (bp->cnt > 0) {
1022 		cv_broadcast(&wpipe->pipe_rcv);
1023 	}
1024 
1025 	/*
1026 	 * Don't return EPIPE if I/O was successful
1027 	 */
1028 	if (error == EPIPE && bp->cnt == 0 && uio->uio_resid == 0)
1029 		error = 0;
1030 
1031 	if (error == 0)
1032 		getnanotime(&wpipe->pipe_mtime);
1033 
1034 	/*
1035 	 * We have something to offer, wake up select/poll.
1036 	 * wpipe->pipe_map.cnt is always 0 in this point (direct write
1037 	 * is only done synchronously), so check only wpipe->pipe_buffer.cnt
1038 	 */
1039 	if (bp->cnt)
1040 		pipeselwakeup(wpipe, wpipe, POLL_IN);
1041 
1042 	/*
1043 	 * Arrange for next read(2) to do a signal.
1044 	 */
1045 	wpipe->pipe_state |= PIPE_SIGNALR;
1046 
1047 	pipeunlock(wpipe);
1048 	mutex_exit(lock);
1049 	return (error);
1050 }
1051 
1052 /*
1053  * We implement a very minimal set of ioctls for compatibility with sockets.
1054  */
1055 int
1056 pipe_ioctl(file_t *fp, u_long cmd, void *data)
1057 {
1058 	struct pipe *pipe = fp->f_data;
1059 	kmutex_t *lock = pipe->pipe_lock;
1060 
1061 	switch (cmd) {
1062 
1063 	case FIONBIO:
1064 		return (0);
1065 
1066 	case FIOASYNC:
1067 		mutex_enter(lock);
1068 		if (*(int *)data) {
1069 			pipe->pipe_state |= PIPE_ASYNC;
1070 		} else {
1071 			pipe->pipe_state &= ~PIPE_ASYNC;
1072 		}
1073 		mutex_exit(lock);
1074 		return (0);
1075 
1076 	case FIONREAD:
1077 		mutex_enter(lock);
1078 #ifndef PIPE_NODIRECT
1079 		if (pipe->pipe_state & PIPE_DIRECTW)
1080 			*(int *)data = pipe->pipe_map.cnt;
1081 		else
1082 #endif
1083 			*(int *)data = pipe->pipe_buffer.cnt;
1084 		mutex_exit(lock);
1085 		return (0);
1086 
1087 	case FIONWRITE:
1088 		/* Look at other side */
1089 		pipe = pipe->pipe_peer;
1090 		mutex_enter(lock);
1091 #ifndef PIPE_NODIRECT
1092 		if (pipe->pipe_state & PIPE_DIRECTW)
1093 			*(int *)data = pipe->pipe_map.cnt;
1094 		else
1095 #endif
1096 			*(int *)data = pipe->pipe_buffer.cnt;
1097 		mutex_exit(lock);
1098 		return (0);
1099 
1100 	case FIONSPACE:
1101 		/* Look at other side */
1102 		pipe = pipe->pipe_peer;
1103 		mutex_enter(lock);
1104 #ifndef PIPE_NODIRECT
1105 		/*
1106 		 * If we're in direct-mode, we don't really have a
1107 		 * send queue, and any other write will block. Thus
1108 		 * zero seems like the best answer.
1109 		 */
1110 		if (pipe->pipe_state & PIPE_DIRECTW)
1111 			*(int *)data = 0;
1112 		else
1113 #endif
1114 			*(int *)data = pipe->pipe_buffer.size -
1115 			    pipe->pipe_buffer.cnt;
1116 		mutex_exit(lock);
1117 		return (0);
1118 
1119 	case TIOCSPGRP:
1120 	case FIOSETOWN:
1121 		return fsetown(&pipe->pipe_pgid, cmd, data);
1122 
1123 	case TIOCGPGRP:
1124 	case FIOGETOWN:
1125 		return fgetown(pipe->pipe_pgid, cmd, data);
1126 
1127 	}
1128 	return (EPASSTHROUGH);
1129 }
1130 
1131 int
1132 pipe_poll(file_t *fp, int events)
1133 {
1134 	struct pipe *rpipe = fp->f_data;
1135 	struct pipe *wpipe;
1136 	int eof = 0;
1137 	int revents = 0;
1138 
1139 	mutex_enter(rpipe->pipe_lock);
1140 	wpipe = rpipe->pipe_peer;
1141 
1142 	if (events & (POLLIN | POLLRDNORM))
1143 		if ((rpipe->pipe_buffer.cnt > 0) ||
1144 #ifndef PIPE_NODIRECT
1145 		    (rpipe->pipe_state & PIPE_DIRECTR) ||
1146 #endif
1147 		    (rpipe->pipe_state & PIPE_EOF))
1148 			revents |= events & (POLLIN | POLLRDNORM);
1149 
1150 	eof |= (rpipe->pipe_state & PIPE_EOF);
1151 
1152 	if (wpipe == NULL)
1153 		revents |= events & (POLLOUT | POLLWRNORM);
1154 	else {
1155 		if (events & (POLLOUT | POLLWRNORM))
1156 			if ((wpipe->pipe_state & PIPE_EOF) || (
1157 #ifndef PIPE_NODIRECT
1158 			     (wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
1159 #endif
1160 			     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1161 				revents |= events & (POLLOUT | POLLWRNORM);
1162 
1163 		eof |= (wpipe->pipe_state & PIPE_EOF);
1164 	}
1165 
1166 	if (wpipe == NULL || eof)
1167 		revents |= POLLHUP;
1168 
1169 	if (revents == 0) {
1170 		if (events & (POLLIN | POLLRDNORM))
1171 			selrecord(curlwp, &rpipe->pipe_sel);
1172 
1173 		if (events & (POLLOUT | POLLWRNORM))
1174 			selrecord(curlwp, &wpipe->pipe_sel);
1175 	}
1176 	mutex_exit(rpipe->pipe_lock);
1177 
1178 	return (revents);
1179 }
1180 
1181 static int
1182 pipe_stat(file_t *fp, struct stat *ub)
1183 {
1184 	struct pipe *pipe = fp->f_data;
1185 
1186 	mutex_enter(pipe->pipe_lock);
1187 	memset(ub, 0, sizeof(*ub));
1188 	ub->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
1189 	ub->st_blksize = pipe->pipe_buffer.size;
1190 	if (ub->st_blksize == 0 && pipe->pipe_peer)
1191 		ub->st_blksize = pipe->pipe_peer->pipe_buffer.size;
1192 	ub->st_size = pipe->pipe_buffer.cnt;
1193 	ub->st_blocks = (ub->st_size) ? 1 : 0;
1194 	ub->st_atimespec = pipe->pipe_atime;
1195 	ub->st_mtimespec = pipe->pipe_mtime;
1196 	ub->st_ctimespec = ub->st_birthtimespec = pipe->pipe_btime;
1197 	ub->st_uid = kauth_cred_geteuid(fp->f_cred);
1198 	ub->st_gid = kauth_cred_getegid(fp->f_cred);
1199 
1200 	/*
1201 	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1202 	 * XXX (st_dev, st_ino) should be unique.
1203 	 */
1204 	mutex_exit(pipe->pipe_lock);
1205 	return 0;
1206 }
1207 
1208 static int
1209 pipe_close(file_t *fp)
1210 {
1211 	struct pipe *pipe = fp->f_data;
1212 
1213 	fp->f_data = NULL;
1214 	pipeclose(pipe);
1215 	return (0);
1216 }
1217 
1218 static void
1219 pipe_abort(file_t *fp)
1220 {
1221 	struct pipe *pipe = fp->f_data;
1222 
1223 	/* Unblock blocked reads/writes - they will return EBADF. */
1224 	mutex_enter(pipe->pipe_lock);
1225 	pipe->pipe_state |= PIPE_ABORTED;
1226 	cv_broadcast(&pipe->pipe_rcv);
1227 	cv_broadcast(&pipe->pipe_wcv);
1228 	mutex_exit(pipe->pipe_lock);
1229 }
1230 
1231 static void
1232 pipe_free_kmem(struct pipe *pipe)
1233 {
1234 
1235 	if (pipe->pipe_buffer.buffer != NULL) {
1236 		if (pipe->pipe_buffer.size > PIPE_SIZE) {
1237 			atomic_dec_uint(&nbigpipe);
1238 		}
1239 		if (pipe->pipe_buffer.buffer != (void *)pipe->pipe_kmem) {
1240 			uvm_km_free(kernel_map,
1241 			    (vaddr_t)pipe->pipe_buffer.buffer,
1242 			    pipe->pipe_buffer.size, UVM_KMF_PAGEABLE);
1243 			atomic_add_int(&amountpipekva,
1244 			    -pipe->pipe_buffer.size);
1245 		}
1246 		pipe->pipe_buffer.buffer = NULL;
1247 	}
1248 #ifndef PIPE_NODIRECT
1249 	if (pipe->pipe_map.kva != 0) {
1250 		pipe_loan_free(pipe);
1251 		pipe->pipe_map.cnt = 0;
1252 		pipe->pipe_map.kva = 0;
1253 		pipe->pipe_map.pos = 0;
1254 		pipe->pipe_map.npages = 0;
1255 	}
1256 #endif /* !PIPE_NODIRECT */
1257 }
1258 
1259 /*
1260  * Shutdown the pipe.
1261  */
1262 static void
1263 pipeclose(struct pipe *pipe)
1264 {
1265 	kmutex_t *lock;
1266 	struct pipe *ppipe;
1267 
1268 	if (pipe == NULL)
1269 		return;
1270 
1271 	KASSERT(cv_is_valid(&pipe->pipe_rcv));
1272 	KASSERT(cv_is_valid(&pipe->pipe_wcv));
1273 	KASSERT(cv_is_valid(&pipe->pipe_draincv));
1274 	KASSERT(cv_is_valid(&pipe->pipe_lkcv));
1275 
1276 	lock = pipe->pipe_lock;
1277 	if (lock == NULL)
1278 		/* Must have failed during create */
1279 		goto free_resources;
1280 
1281 	mutex_enter(lock);
1282 	pipeselwakeup(pipe, pipe, POLL_HUP);
1283 
1284 	/*
1285 	 * If the other side is blocked, wake it up saying that
1286 	 * we want to close it down.
1287 	 */
1288 	pipe->pipe_state |= PIPE_EOF;
1289 	if (pipe->pipe_busy) {
1290 		while (pipe->pipe_busy) {
1291 			cv_broadcast(&pipe->pipe_wcv);
1292 			cv_wait_sig(&pipe->pipe_draincv, lock);
1293 		}
1294 	}
1295 
1296 	/*
1297 	 * Disconnect from peer.
1298 	 */
1299 	if ((ppipe = pipe->pipe_peer) != NULL) {
1300 		pipeselwakeup(ppipe, ppipe, POLL_HUP);
1301 		ppipe->pipe_state |= PIPE_EOF;
1302 		cv_broadcast(&ppipe->pipe_rcv);
1303 		ppipe->pipe_peer = NULL;
1304 	}
1305 
1306 	/*
1307 	 * Any knote objects still left in the list are
1308 	 * the one attached by peer.  Since no one will
1309 	 * traverse this list, we just clear it.
1310 	 */
1311 	SLIST_INIT(&pipe->pipe_sel.sel_klist);
1312 
1313 	KASSERT((pipe->pipe_state & PIPE_LOCKFL) == 0);
1314 	mutex_exit(lock);
1315 	mutex_obj_free(lock);
1316 
1317 	/*
1318 	 * Free resources.
1319 	 */
1320     free_resources:
1321 	pipe->pipe_pgid = 0;
1322 	pipe->pipe_state = PIPE_SIGNALR;
1323 	pipe_free_kmem(pipe);
1324 	if (pipe->pipe_kmem != 0) {
1325 		pool_cache_put(pipe_rd_cache, pipe);
1326 	} else {
1327 		pool_cache_put(pipe_wr_cache, pipe);
1328 	}
1329 }
1330 
1331 static void
1332 filt_pipedetach(struct knote *kn)
1333 {
1334 	struct pipe *pipe;
1335 	kmutex_t *lock;
1336 
1337 	pipe = ((file_t *)kn->kn_obj)->f_data;
1338 	lock = pipe->pipe_lock;
1339 
1340 	mutex_enter(lock);
1341 
1342 	switch(kn->kn_filter) {
1343 	case EVFILT_WRITE:
1344 		/* Need the peer structure, not our own. */
1345 		pipe = pipe->pipe_peer;
1346 
1347 		/* If reader end already closed, just return. */
1348 		if (pipe == NULL) {
1349 			mutex_exit(lock);
1350 			return;
1351 		}
1352 
1353 		break;
1354 	default:
1355 		/* Nothing to do. */
1356 		break;
1357 	}
1358 
1359 	KASSERT(kn->kn_hook == pipe);
1360 	SLIST_REMOVE(&pipe->pipe_sel.sel_klist, kn, knote, kn_selnext);
1361 	mutex_exit(lock);
1362 }
1363 
1364 static int
1365 filt_piperead(struct knote *kn, long hint)
1366 {
1367 	struct pipe *rpipe = ((file_t *)kn->kn_obj)->f_data;
1368 	struct pipe *wpipe;
1369 
1370 	if ((hint & NOTE_SUBMIT) == 0) {
1371 		mutex_enter(rpipe->pipe_lock);
1372 	}
1373 	wpipe = rpipe->pipe_peer;
1374 	kn->kn_data = rpipe->pipe_buffer.cnt;
1375 
1376 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1377 		kn->kn_data = rpipe->pipe_map.cnt;
1378 
1379 	if ((rpipe->pipe_state & PIPE_EOF) ||
1380 	    (wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1381 		kn->kn_flags |= EV_EOF;
1382 		if ((hint & NOTE_SUBMIT) == 0) {
1383 			mutex_exit(rpipe->pipe_lock);
1384 		}
1385 		return (1);
1386 	}
1387 
1388 	if ((hint & NOTE_SUBMIT) == 0) {
1389 		mutex_exit(rpipe->pipe_lock);
1390 	}
1391 	return (kn->kn_data > 0);
1392 }
1393 
1394 static int
1395 filt_pipewrite(struct knote *kn, long hint)
1396 {
1397 	struct pipe *rpipe = ((file_t *)kn->kn_obj)->f_data;
1398 	struct pipe *wpipe;
1399 
1400 	if ((hint & NOTE_SUBMIT) == 0) {
1401 		mutex_enter(rpipe->pipe_lock);
1402 	}
1403 	wpipe = rpipe->pipe_peer;
1404 
1405 	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1406 		kn->kn_data = 0;
1407 		kn->kn_flags |= EV_EOF;
1408 		if ((hint & NOTE_SUBMIT) == 0) {
1409 			mutex_exit(rpipe->pipe_lock);
1410 		}
1411 		return (1);
1412 	}
1413 	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1414 	if (wpipe->pipe_state & PIPE_DIRECTW)
1415 		kn->kn_data = 0;
1416 
1417 	if ((hint & NOTE_SUBMIT) == 0) {
1418 		mutex_exit(rpipe->pipe_lock);
1419 	}
1420 	return (kn->kn_data >= PIPE_BUF);
1421 }
1422 
1423 static const struct filterops pipe_rfiltops =
1424 	{ 1, NULL, filt_pipedetach, filt_piperead };
1425 static const struct filterops pipe_wfiltops =
1426 	{ 1, NULL, filt_pipedetach, filt_pipewrite };
1427 
1428 static int
1429 pipe_kqfilter(file_t *fp, struct knote *kn)
1430 {
1431 	struct pipe *pipe;
1432 	kmutex_t *lock;
1433 
1434 	pipe = ((file_t *)kn->kn_obj)->f_data;
1435 	lock = pipe->pipe_lock;
1436 
1437 	mutex_enter(lock);
1438 
1439 	switch (kn->kn_filter) {
1440 	case EVFILT_READ:
1441 		kn->kn_fop = &pipe_rfiltops;
1442 		break;
1443 	case EVFILT_WRITE:
1444 		kn->kn_fop = &pipe_wfiltops;
1445 		pipe = pipe->pipe_peer;
1446 		if (pipe == NULL) {
1447 			/* Other end of pipe has been closed. */
1448 			mutex_exit(lock);
1449 			return (EBADF);
1450 		}
1451 		break;
1452 	default:
1453 		mutex_exit(lock);
1454 		return (EINVAL);
1455 	}
1456 
1457 	kn->kn_hook = pipe;
1458 	SLIST_INSERT_HEAD(&pipe->pipe_sel.sel_klist, kn, kn_selnext);
1459 	mutex_exit(lock);
1460 
1461 	return (0);
1462 }
1463 
1464 /*
1465  * Handle pipe sysctls.
1466  */
1467 SYSCTL_SETUP(sysctl_kern_pipe_setup, "sysctl kern.pipe subtree setup")
1468 {
1469 
1470 	sysctl_createv(clog, 0, NULL, NULL,
1471 		       CTLFLAG_PERMANENT,
1472 		       CTLTYPE_NODE, "kern", NULL,
1473 		       NULL, 0, NULL, 0,
1474 		       CTL_KERN, CTL_EOL);
1475 	sysctl_createv(clog, 0, NULL, NULL,
1476 		       CTLFLAG_PERMANENT,
1477 		       CTLTYPE_NODE, "pipe",
1478 		       SYSCTL_DESCR("Pipe settings"),
1479 		       NULL, 0, NULL, 0,
1480 		       CTL_KERN, KERN_PIPE, CTL_EOL);
1481 
1482 	sysctl_createv(clog, 0, NULL, NULL,
1483 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1484 		       CTLTYPE_INT, "maxkvasz",
1485 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
1486 				    "used for pipes"),
1487 		       NULL, 0, &maxpipekva, 0,
1488 		       CTL_KERN, KERN_PIPE, KERN_PIPE_MAXKVASZ, CTL_EOL);
1489 	sysctl_createv(clog, 0, NULL, NULL,
1490 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1491 		       CTLTYPE_INT, "maxloankvasz",
1492 		       SYSCTL_DESCR("Limit for direct transfers via page loan"),
1493 		       NULL, 0, &limitpipekva, 0,
1494 		       CTL_KERN, KERN_PIPE, KERN_PIPE_LIMITKVA, CTL_EOL);
1495 	sysctl_createv(clog, 0, NULL, NULL,
1496 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1497 		       CTLTYPE_INT, "maxbigpipes",
1498 		       SYSCTL_DESCR("Maximum number of \"big\" pipes"),
1499 		       NULL, 0, &maxbigpipes, 0,
1500 		       CTL_KERN, KERN_PIPE, KERN_PIPE_MAXBIGPIPES, CTL_EOL);
1501 	sysctl_createv(clog, 0, NULL, NULL,
1502 		       CTLFLAG_PERMANENT,
1503 		       CTLTYPE_INT, "nbigpipes",
1504 		       SYSCTL_DESCR("Number of \"big\" pipes"),
1505 		       NULL, 0, &nbigpipe, 0,
1506 		       CTL_KERN, KERN_PIPE, KERN_PIPE_NBIGPIPES, CTL_EOL);
1507 	sysctl_createv(clog, 0, NULL, NULL,
1508 		       CTLFLAG_PERMANENT,
1509 		       CTLTYPE_INT, "kvasize",
1510 		       SYSCTL_DESCR("Amount of kernel memory consumed by pipe "
1511 				    "buffers"),
1512 		       NULL, 0, &amountpipekva, 0,
1513 		       CTL_KERN, KERN_PIPE, KERN_PIPE_KVASIZE, CTL_EOL);
1514 }
1515