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