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