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