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