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