Home | History | Annotate | Line # | Download | only in kern
sys_pipe.c revision 1.87.2.4
      1 /*	$NetBSD: sys_pipe.c,v 1.87.2.4 2007/12/18 15:23:03 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.87.2.4 2007/12/18 15:23:03 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, 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 			return (error);
    730 	}
    731 
    732 	/* Loan the write buffer memory from writer process */
    733 	pgs = wpipe->pipe_map.pgs;
    734 	error = uvm_loan(&uio->uio_vmspace->vm_map, base, blen,
    735 			 pgs, UVM_LOAN_TOPAGE);
    736 	if (error) {
    737 		pipe_loan_free(wpipe);
    738 		return (ENOMEM); /* so that caller fallback to ordinary write */
    739 	}
    740 
    741 	/* Enter the loaned pages to kva */
    742 	kva = wpipe->pipe_map.kva;
    743 	for (j = 0; j < npages; j++, kva += PAGE_SIZE) {
    744 		pmap_kenter_pa(kva, VM_PAGE_TO_PHYS(pgs[j]), VM_PROT_READ);
    745 	}
    746 	pmap_update(pmap_kernel());
    747 
    748 	/* Now we can put the pipe in direct write mode */
    749 	wpipe->pipe_map.pos = bpos;
    750 	wpipe->pipe_map.cnt = bcnt;
    751 
    752 	/*
    753 	 * But before we can let someone do a direct read, we
    754 	 * have to wait until the pipe is drained.  Release the
    755 	 * pipe lock while we wait.
    756 	 */
    757 	mutex_enter(wpipe->pipe_lock);
    758 	wpipe->pipe_state |= PIPE_DIRECTW;
    759 	pipeunlock(wpipe);
    760 
    761 	while (error == 0 && wpipe->pipe_buffer.cnt > 0) {
    762 		if (wpipe->pipe_state & PIPE_WANTR) {
    763 			wpipe->pipe_state &= ~PIPE_WANTR;
    764 			cv_broadcast(&wpipe->pipe_cv);
    765 		}
    766 
    767 		wpipe->pipe_state |= PIPE_WANTW;
    768 		error = cv_wait_sig(&wpipe->pipe_cv, wpipe->pipe_lock);
    769 		if (error == 0 && wpipe->pipe_state & PIPE_EOF)
    770 			error = EPIPE;
    771 	}
    772 
    773 	/* Pipe is drained; next read will off the direct buffer */
    774 	wpipe->pipe_state |= PIPE_DIRECTR;
    775 
    776 	/* Wait until the reader is done */
    777 	while (error == 0 && (wpipe->pipe_state & PIPE_DIRECTR)) {
    778 		if (wpipe->pipe_state & PIPE_WANTR) {
    779 			wpipe->pipe_state &= ~PIPE_WANTR;
    780 			cv_broadcast(&wpipe->pipe_cv);
    781 		}
    782 		pipeselwakeup(wpipe, wpipe, POLL_IN);
    783 		error = cv_wait_sig(&wpipe->pipe_cv, wpipe->pipe_lock);
    784 		if (error == 0 && wpipe->pipe_state & PIPE_EOF)
    785 			error = EPIPE;
    786 	}
    787 
    788 	/* Take pipe out of direct write mode */
    789 	wpipe->pipe_state &= ~(PIPE_DIRECTW | PIPE_DIRECTR);
    790 
    791 	/* Acquire the pipe lock and cleanup */
    792 	(void)pipelock(wpipe, 0);
    793 	mutex_exit(wpipe->pipe_lock);
    794 
    795 	if (pgs != NULL) {
    796 		pmap_kremove(wpipe->pipe_map.kva, blen);
    797 		uvm_unloan(pgs, npages, UVM_LOAN_TOPAGE);
    798 	}
    799 	if (error || amountpipekva > maxpipekva)
    800 		pipe_loan_free(wpipe);
    801 
    802 	mutex_enter(wpipe->pipe_lock);
    803 	if (error) {
    804 		pipeselwakeup(wpipe, wpipe, POLL_ERR);
    805 
    806 		/*
    807 		 * If nothing was read from what we offered, return error
    808 		 * straight on. Otherwise update uio resid first. Caller
    809 		 * will deal with the error condition, returning short
    810 		 * write, error, or restarting the write(2) as appropriate.
    811 		 */
    812 		if (wpipe->pipe_map.cnt == bcnt) {
    813 			wpipe->pipe_map.cnt = 0;
    814 			cv_broadcast(&wpipe->pipe_cv);
    815 			mutex_exit(wpipe->pipe_lock);
    816 			return (error);
    817 		}
    818 
    819 		bcnt -= wpipe->pipe_map.cnt;
    820 	}
    821 
    822 	uio->uio_resid -= bcnt;
    823 	/* uio_offset not updated, not set/used for write(2) */
    824 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + bcnt;
    825 	uio->uio_iov->iov_len -= bcnt;
    826 	if (uio->uio_iov->iov_len == 0) {
    827 		uio->uio_iov++;
    828 		uio->uio_iovcnt--;
    829 	}
    830 
    831 	wpipe->pipe_map.cnt = 0;
    832 	return (error);
    833 }
    834 #endif /* !PIPE_NODIRECT */
    835 
    836 static int
    837 pipe_write(struct file *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
    838     int flags)
    839 {
    840 	struct pipe *wpipe, *rpipe;
    841 	struct pipebuf *bp;
    842 	int error;
    843 
    844 	/* We want to write to our peer */
    845 	rpipe = (struct pipe *) fp->f_data;
    846 	error = 0;
    847 
    848 	mutex_enter(rpipe->pipe_lock);
    849 	wpipe = rpipe->pipe_peer;
    850 
    851 	/*
    852 	 * Detect loss of pipe read side, issue SIGPIPE if lost.
    853 	 */
    854 	if (wpipe == NULL) {
    855 		mutex_exit(rpipe->pipe_lock);
    856 		return EPIPE;
    857 	} else if ((wpipe->pipe_state & PIPE_EOF) != 0) {
    858 		mutex_exit(rpipe->pipe_lock);
    859 		return EPIPE;
    860 	}
    861 	++wpipe->pipe_busy;
    862 
    863 	/* Aquire the long-term pipe lock */
    864 	if ((error = pipelock(wpipe,1)) != 0) {
    865 		--wpipe->pipe_busy;
    866 		if (wpipe->pipe_busy == 0
    867 		    && (wpipe->pipe_state & PIPE_WANTCLOSE)) {
    868 			wpipe->pipe_state &= ~(PIPE_WANTCLOSE | PIPE_WANTR);
    869 			cv_broadcast(&wpipe->pipe_cv);
    870 		}
    871 		mutex_exit(rpipe->pipe_lock);
    872 		return (error);
    873 	}
    874 
    875 	bp = &wpipe->pipe_buffer;
    876 
    877 	/*
    878 	 * If it is advantageous to resize the pipe buffer, do so.
    879 	 */
    880 	if ((uio->uio_resid > PIPE_SIZE) &&
    881 	    (nbigpipe < maxbigpipes) &&
    882 #ifndef PIPE_NODIRECT
    883 	    (wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
    884 #endif
    885 	    (bp->size <= PIPE_SIZE) && (bp->cnt == 0)) {
    886 
    887 		if (pipespace(wpipe, BIG_PIPE_SIZE) == 0)
    888 			atomic_inc_uint(&nbigpipe);
    889 	}
    890 
    891 	while (uio->uio_resid) {
    892 		size_t space;
    893 
    894 #ifndef PIPE_NODIRECT
    895 		/*
    896 		 * Pipe buffered writes cannot be coincidental with
    897 		 * direct writes.  Also, only one direct write can be
    898 		 * in progress at any one time.  We wait until the currently
    899 		 * executing direct write is completed before continuing.
    900 		 *
    901 		 * We break out if a signal occurs or the reader goes away.
    902 		 */
    903 		while (error == 0 && wpipe->pipe_state & PIPE_DIRECTW) {
    904 			if (wpipe->pipe_state & PIPE_WANTR) {
    905 				wpipe->pipe_state &= ~PIPE_WANTR;
    906 				cv_broadcast(&wpipe->pipe_cv);
    907 			}
    908 			pipeunlock(wpipe);
    909 			error = cv_wait_sig(&wpipe->pipe_cv,
    910 			    wpipe->pipe_lock);
    911 			(void)pipelock(wpipe, 0);
    912 			if (wpipe->pipe_state & PIPE_EOF)
    913 				error = EPIPE;
    914 		}
    915 		if (error)
    916 			break;
    917 
    918 		/*
    919 		 * If the transfer is large, we can gain performance if
    920 		 * we do process-to-process copies directly.
    921 		 * If the write is non-blocking, we don't use the
    922 		 * direct write mechanism.
    923 		 *
    924 		 * The direct write mechanism will detect the reader going
    925 		 * away on us.
    926 		 */
    927 		if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT) &&
    928 		    (fp->f_flag & FNONBLOCK) == 0 &&
    929 		    (wpipe->pipe_map.kva || (amountpipekva < limitpipekva))) {
    930 			error = pipe_direct_write(fp, wpipe, uio);
    931 
    932 			/*
    933 			 * Break out if error occurred, unless it's ENOMEM.
    934 			 * ENOMEM means we failed to allocate some resources
    935 			 * for direct write, so we just fallback to ordinary
    936 			 * write. If the direct write was successful,
    937 			 * process rest of data via ordinary write.
    938 			 */
    939 			if (error == 0)
    940 				continue;
    941 
    942 			if (error != ENOMEM)
    943 				break;
    944 		}
    945 #endif /* PIPE_NODIRECT */
    946 
    947 		space = bp->size - bp->cnt;
    948 
    949 		/* Writes of size <= PIPE_BUF must be atomic. */
    950 		if ((space < uio->uio_resid) && (uio->uio_resid <= PIPE_BUF))
    951 			space = 0;
    952 
    953 		if (space > 0) {
    954 			int size;	/* Transfer size */
    955 			int segsize;	/* first segment to transfer */
    956 
    957 			/*
    958 			 * Transfer size is minimum of uio transfer
    959 			 * and free space in pipe buffer.
    960 			 */
    961 			if (space > uio->uio_resid)
    962 				size = uio->uio_resid;
    963 			else
    964 				size = space;
    965 			/*
    966 			 * First segment to transfer is minimum of
    967 			 * transfer size and contiguous space in
    968 			 * pipe buffer.  If first segment to transfer
    969 			 * is less than the transfer size, we've got
    970 			 * a wraparound in the buffer.
    971 			 */
    972 			segsize = bp->size - bp->in;
    973 			if (segsize > size)
    974 				segsize = size;
    975 
    976 			/* Transfer first segment */
    977 			mutex_exit(wpipe->pipe_lock);
    978 			error = uiomove((char *)bp->buffer + bp->in, segsize,
    979 			    uio);
    980 
    981 			if (error == 0 && segsize < size) {
    982 				/*
    983 				 * Transfer remaining part now, to
    984 				 * support atomic writes.  Wraparound
    985 				 * happened.
    986 				 */
    987 #ifdef DEBUG
    988 				if (bp->in + segsize != bp->size)
    989 					panic("Expected pipe buffer wraparound disappeared");
    990 #endif
    991 
    992 				error = uiomove(bp->buffer,
    993 				    size - segsize, uio);
    994 			}
    995 			mutex_enter(wpipe->pipe_lock);
    996 			if (error)
    997 				break;
    998 
    999 			bp->in += size;
   1000 			if (bp->in >= bp->size) {
   1001 #ifdef DEBUG
   1002 				if (bp->in != size - segsize + bp->size)
   1003 					panic("Expected wraparound bad");
   1004 #endif
   1005 				bp->in = size - segsize;
   1006 			}
   1007 
   1008 			bp->cnt += size;
   1009 #ifdef DEBUG
   1010 			if (bp->cnt > bp->size)
   1011 				panic("Pipe buffer overflow");
   1012 #endif
   1013 		} else {
   1014 			/*
   1015 			 * If the "read-side" has been blocked, wake it up now.
   1016 			 */
   1017 			if (wpipe->pipe_state & PIPE_WANTR) {
   1018 				wpipe->pipe_state &= ~PIPE_WANTR;
   1019 				cv_broadcast(&wpipe->pipe_cv);
   1020 			}
   1021 
   1022 			/*
   1023 			 * don't block on non-blocking I/O
   1024 			 */
   1025 			if (fp->f_flag & FNONBLOCK) {
   1026 				error = EAGAIN;
   1027 				break;
   1028 			}
   1029 
   1030 			/*
   1031 			 * We have no more space and have something to offer,
   1032 			 * wake up select/poll.
   1033 			 */
   1034 			if (bp->cnt)
   1035 				pipeselwakeup(wpipe, wpipe, POLL_OUT);
   1036 
   1037 			pipeunlock(wpipe);
   1038 			wpipe->pipe_state |= PIPE_WANTW;
   1039 			error = cv_wait_sig(&wpipe->pipe_cv, wpipe->pipe_lock);
   1040 			(void)pipelock(wpipe, 0);
   1041 			if (error != 0)
   1042 				break;
   1043 			/*
   1044 			 * If read side wants to go away, we just issue a signal
   1045 			 * to ourselves.
   1046 			 */
   1047 			if (wpipe->pipe_state & PIPE_EOF) {
   1048 				error = EPIPE;
   1049 				break;
   1050 			}
   1051 		}
   1052 	}
   1053 
   1054 	--wpipe->pipe_busy;
   1055 	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANTCLOSE)) {
   1056 		wpipe->pipe_state &= ~(PIPE_WANTCLOSE | PIPE_WANTR);
   1057 		cv_broadcast(&wpipe->pipe_cv);
   1058 	} else if (bp->cnt > 0) {
   1059 		/*
   1060 		 * If we have put any characters in the buffer, we wake up
   1061 		 * the reader.
   1062 		 */
   1063 		if (wpipe->pipe_state & PIPE_WANTR) {
   1064 			wpipe->pipe_state &= ~PIPE_WANTR;
   1065 			cv_broadcast(&wpipe->pipe_cv);
   1066 		}
   1067 	}
   1068 
   1069 	/*
   1070 	 * Don't return EPIPE if I/O was successful
   1071 	 */
   1072 	if (error == EPIPE && bp->cnt == 0 && uio->uio_resid == 0)
   1073 		error = 0;
   1074 
   1075 	if (error == 0)
   1076 		getmicrotime(&wpipe->pipe_mtime);
   1077 
   1078 	/*
   1079 	 * We have something to offer, wake up select/poll.
   1080 	 * wpipe->pipe_map.cnt is always 0 in this point (direct write
   1081 	 * is only done synchronously), so check only wpipe->pipe_buffer.cnt
   1082 	 */
   1083 	if (bp->cnt)
   1084 		pipeselwakeup(wpipe, wpipe, POLL_OUT);
   1085 
   1086 	/*
   1087 	 * Arrange for next read(2) to do a signal.
   1088 	 */
   1089 	wpipe->pipe_state |= PIPE_SIGNALR;
   1090 
   1091 	pipeunlock(wpipe);
   1092 	mutex_exit(wpipe->pipe_lock);
   1093 	return (error);
   1094 }
   1095 
   1096 /*
   1097  * we implement a very minimal set of ioctls for compatibility with sockets.
   1098  */
   1099 int
   1100 pipe_ioctl(struct file *fp, u_long cmd, void *data, struct lwp *l)
   1101 {
   1102 	struct pipe *pipe = (struct pipe *)fp->f_data;
   1103 	struct proc *p = l->l_proc;
   1104 
   1105 	switch (cmd) {
   1106 
   1107 	case FIONBIO:
   1108 		return (0);
   1109 
   1110 	case FIOASYNC:
   1111 		mutex_enter(pipe->pipe_lock);
   1112 		if (*(int *)data) {
   1113 			pipe->pipe_state |= PIPE_ASYNC;
   1114 		} else {
   1115 			pipe->pipe_state &= ~PIPE_ASYNC;
   1116 		}
   1117 		mutex_exit(pipe->pipe_lock);
   1118 		return (0);
   1119 
   1120 	case FIONREAD:
   1121 		mutex_enter(pipe->pipe_lock);
   1122 #ifndef PIPE_NODIRECT
   1123 		if (pipe->pipe_state & PIPE_DIRECTW)
   1124 			*(int *)data = pipe->pipe_map.cnt;
   1125 		else
   1126 #endif
   1127 			*(int *)data = pipe->pipe_buffer.cnt;
   1128 		mutex_exit(pipe->pipe_lock);
   1129 		return (0);
   1130 
   1131 	case FIONWRITE:
   1132 		/* Look at other side */
   1133 		pipe = pipe->pipe_peer;
   1134 		mutex_enter(pipe->pipe_lock);
   1135 #ifndef PIPE_NODIRECT
   1136 		if (pipe->pipe_state & PIPE_DIRECTW)
   1137 			*(int *)data = pipe->pipe_map.cnt;
   1138 		else
   1139 #endif
   1140 			*(int *)data = pipe->pipe_buffer.cnt;
   1141 		mutex_exit(pipe->pipe_lock);
   1142 		return (0);
   1143 
   1144 	case FIONSPACE:
   1145 		/* Look at other side */
   1146 		pipe = pipe->pipe_peer;
   1147 		mutex_enter(pipe->pipe_lock);
   1148 #ifndef PIPE_NODIRECT
   1149 		/*
   1150 		 * If we're in direct-mode, we don't really have a
   1151 		 * send queue, and any other write will block. Thus
   1152 		 * zero seems like the best answer.
   1153 		 */
   1154 		if (pipe->pipe_state & PIPE_DIRECTW)
   1155 			*(int *)data = 0;
   1156 		else
   1157 #endif
   1158 			*(int *)data = pipe->pipe_buffer.size -
   1159 			    pipe->pipe_buffer.cnt;
   1160 		mutex_exit(pipe->pipe_lock);
   1161 		return (0);
   1162 
   1163 	case TIOCSPGRP:
   1164 	case FIOSETOWN:
   1165 		return fsetown(p, &pipe->pipe_pgid, cmd, data);
   1166 
   1167 	case TIOCGPGRP:
   1168 	case FIOGETOWN:
   1169 		return fgetown(p, pipe->pipe_pgid, cmd, data);
   1170 
   1171 	}
   1172 	return (EPASSTHROUGH);
   1173 }
   1174 
   1175 int
   1176 pipe_poll(struct file *fp, int events, struct lwp *l)
   1177 {
   1178 	struct pipe *rpipe = (struct pipe *)fp->f_data;
   1179 	struct pipe *wpipe;
   1180 	int eof = 0;
   1181 	int revents = 0;
   1182 
   1183 	mutex_enter(rpipe->pipe_lock);
   1184 	wpipe = rpipe->pipe_peer;
   1185 
   1186 	if (events & (POLLIN | POLLRDNORM))
   1187 		if ((rpipe->pipe_buffer.cnt > 0) ||
   1188 #ifndef PIPE_NODIRECT
   1189 		    (rpipe->pipe_state & PIPE_DIRECTR) ||
   1190 #endif
   1191 		    (rpipe->pipe_state & PIPE_EOF))
   1192 			revents |= events & (POLLIN | POLLRDNORM);
   1193 
   1194 	eof |= (rpipe->pipe_state & PIPE_EOF);
   1195 
   1196 	if (wpipe == NULL)
   1197 		revents |= events & (POLLOUT | POLLWRNORM);
   1198 	else {
   1199 		if (events & (POLLOUT | POLLWRNORM))
   1200 			if ((wpipe->pipe_state & PIPE_EOF) || (
   1201 #ifndef PIPE_NODIRECT
   1202 			     (wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
   1203 #endif
   1204 			     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
   1205 				revents |= events & (POLLOUT | POLLWRNORM);
   1206 
   1207 		eof |= (wpipe->pipe_state & PIPE_EOF);
   1208 	}
   1209 
   1210 	if (wpipe == NULL || eof)
   1211 		revents |= POLLHUP;
   1212 
   1213 	if (revents == 0) {
   1214 		if (events & (POLLIN | POLLRDNORM))
   1215 			selrecord(l, &rpipe->pipe_sel);
   1216 
   1217 		if (events & (POLLOUT | POLLWRNORM))
   1218 			selrecord(l, &wpipe->pipe_sel);
   1219 	}
   1220 	mutex_exit(rpipe->pipe_lock);
   1221 
   1222 	return (revents);
   1223 }
   1224 
   1225 static int
   1226 pipe_stat(struct file *fp, struct stat *ub, struct lwp *l)
   1227 {
   1228 	struct pipe *pipe = (struct pipe *)fp->f_data;
   1229 
   1230 	memset((void *)ub, 0, sizeof(*ub));
   1231 	ub->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
   1232 	ub->st_blksize = pipe->pipe_buffer.size;
   1233 	if (ub->st_blksize == 0 && pipe->pipe_peer)
   1234 		ub->st_blksize = pipe->pipe_peer->pipe_buffer.size;
   1235 	ub->st_size = pipe->pipe_buffer.cnt;
   1236 	ub->st_blocks = (ub->st_size) ? 1 : 0;
   1237 	TIMEVAL_TO_TIMESPEC(&pipe->pipe_atime, &ub->st_atimespec);
   1238 	TIMEVAL_TO_TIMESPEC(&pipe->pipe_mtime, &ub->st_mtimespec);
   1239 	TIMEVAL_TO_TIMESPEC(&pipe->pipe_ctime, &ub->st_ctimespec);
   1240 	ub->st_uid = kauth_cred_geteuid(fp->f_cred);
   1241 	ub->st_gid = kauth_cred_getegid(fp->f_cred);
   1242 
   1243 	/*
   1244 	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
   1245 	 * XXX (st_dev, st_ino) should be unique.
   1246 	 */
   1247 	return (0);
   1248 }
   1249 
   1250 /* ARGSUSED */
   1251 static int
   1252 pipe_close(struct file *fp, struct lwp *l)
   1253 {
   1254 	struct pipe *pipe = (struct pipe *)fp->f_data;
   1255 
   1256 	fp->f_data = NULL;
   1257 	pipeclose(fp, pipe);
   1258 	return (0);
   1259 }
   1260 
   1261 static void
   1262 pipe_free_kmem(struct pipe *pipe)
   1263 {
   1264 
   1265 	if (pipe->pipe_buffer.buffer != NULL) {
   1266 		if (pipe->pipe_buffer.size > PIPE_SIZE)
   1267 			atomic_dec_uint(&nbigpipe);
   1268 		atomic_add_int(&amountpipekva, -pipe->pipe_buffer.size);
   1269 		uvm_km_free(kernel_map,
   1270 			(vaddr_t)pipe->pipe_buffer.buffer,
   1271 			pipe->pipe_buffer.size, UVM_KMF_PAGEABLE);
   1272 		pipe->pipe_buffer.buffer = NULL;
   1273 	}
   1274 #ifndef PIPE_NODIRECT
   1275 	if (pipe->pipe_map.kva != 0) {
   1276 		pipe_loan_free(pipe);
   1277 		pipe->pipe_map.cnt = 0;
   1278 		pipe->pipe_map.kva = 0;
   1279 		pipe->pipe_map.pos = 0;
   1280 		pipe->pipe_map.npages = 0;
   1281 	}
   1282 #endif /* !PIPE_NODIRECT */
   1283 }
   1284 
   1285 /*
   1286  * shutdown the pipe
   1287  */
   1288 static void
   1289 pipeclose(struct file *fp, struct pipe *pipe)
   1290 {
   1291 	struct pipe_mutex *mutex;
   1292 	struct pipe *ppipe;
   1293 	u_int refcnt;
   1294 
   1295 	if (pipe == NULL)
   1296 		return;
   1297 
   1298 	mutex_enter(pipe->pipe_lock);
   1299 	pipeselwakeup(pipe, pipe, POLL_HUP);
   1300 
   1301 	/*
   1302 	 * If the other side is blocked, wake it up saying that
   1303 	 * we want to close it down.
   1304 	 */
   1305 	pipe->pipe_state |= PIPE_EOF;
   1306 	if (pipe->pipe_busy) {
   1307 		while (pipe->pipe_busy) {
   1308 			cv_broadcast(&pipe->pipe_cv);
   1309 			pipe->pipe_state |= PIPE_WANTCLOSE;
   1310 			cv_wait_sig(&pipe->pipe_cv, pipe->pipe_lock);
   1311 		}
   1312 	}
   1313 
   1314 	/*
   1315 	 * Disconnect from peer
   1316 	 */
   1317 	if ((ppipe = pipe->pipe_peer) != NULL) {
   1318 		pipeselwakeup(ppipe, ppipe, POLL_HUP);
   1319 		ppipe->pipe_state |= PIPE_EOF;
   1320 		cv_broadcast(&ppipe->pipe_cv);
   1321 		ppipe->pipe_peer = NULL;
   1322 	}
   1323 
   1324 	KASSERT((pipe->pipe_state & PIPE_LOCKFL) == 0);
   1325 
   1326 	mutex = (struct pipe_mutex *)pipe->pipe_lock;
   1327 	refcnt = --(mutex->pm_refcnt);
   1328 	KASSERT(refcnt == 0 || refcnt == 1);
   1329 	mutex_exit(pipe->pipe_lock);
   1330 
   1331 	/*
   1332 	 * free resources
   1333 	 */
   1334 	pipe_free_kmem(pipe);
   1335 	cv_destroy(&pipe->pipe_cv);
   1336 	cv_destroy(&pipe->pipe_lkcv);
   1337 	seldestroy(&pipe->pipe_sel);
   1338 	pool_cache_put(pipe_cache, pipe);
   1339 	if (refcnt == 0)
   1340 		pool_cache_put(pipe_mutex_cache, mutex);
   1341 }
   1342 
   1343 static void
   1344 filt_pipedetach(struct knote *kn)
   1345 {
   1346 	struct pipe *pipe = (struct pipe *)kn->kn_fp->f_data;
   1347 
   1348 	mutex_enter(pipe->pipe_lock);
   1349 
   1350 	switch(kn->kn_filter) {
   1351 	case EVFILT_WRITE:
   1352 		/* need the peer structure, not our own */
   1353 		pipe = pipe->pipe_peer;
   1354 
   1355 		/* if reader end already closed, just return */
   1356 		if (pipe == NULL) {
   1357 			mutex_exit(pipe->pipe_lock);
   1358 			return;
   1359 		}
   1360 
   1361 		break;
   1362 	default:
   1363 		/* nothing to do */
   1364 		break;
   1365 	}
   1366 
   1367 #ifdef DIAGNOSTIC
   1368 	if (kn->kn_hook != pipe)
   1369 		panic("filt_pipedetach: inconsistent knote");
   1370 #endif
   1371 
   1372 	SLIST_REMOVE(&pipe->pipe_sel.sel_klist, kn, knote, kn_selnext);
   1373 	mutex_exit(pipe->pipe_lock);
   1374 }
   1375 
   1376 /*ARGSUSED*/
   1377 static int
   1378 filt_piperead(struct knote *kn, long hint)
   1379 {
   1380 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->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 	kn->kn_data = rpipe->pipe_buffer.cnt;
   1388 
   1389 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
   1390 		kn->kn_data = rpipe->pipe_map.cnt;
   1391 
   1392 	if ((rpipe->pipe_state & PIPE_EOF) ||
   1393 	    (wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
   1394 		kn->kn_flags |= EV_EOF;
   1395 		if ((hint & NOTE_SUBMIT) == 0) {
   1396 			mutex_exit(rpipe->pipe_lock);
   1397 		}
   1398 		return (1);
   1399 	}
   1400 
   1401 	if ((hint & NOTE_SUBMIT) == 0) {
   1402 		mutex_exit(rpipe->pipe_lock);
   1403 	}
   1404 	return (kn->kn_data > 0);
   1405 }
   1406 
   1407 /*ARGSUSED*/
   1408 static int
   1409 filt_pipewrite(struct knote *kn, long hint)
   1410 {
   1411 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
   1412 	struct pipe *wpipe;
   1413 
   1414 	if ((hint & NOTE_SUBMIT) == 0) {
   1415 		mutex_enter(rpipe->pipe_lock);
   1416 	}
   1417 	wpipe = rpipe->pipe_peer;
   1418 
   1419 	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
   1420 		kn->kn_data = 0;
   1421 		kn->kn_flags |= EV_EOF;
   1422 		if ((hint & NOTE_SUBMIT) == 0) {
   1423 			mutex_exit(rpipe->pipe_lock);
   1424 		}
   1425 		return (1);
   1426 	}
   1427 	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
   1428 	if (wpipe->pipe_state & PIPE_DIRECTW)
   1429 		kn->kn_data = 0;
   1430 
   1431 	if ((hint & NOTE_SUBMIT) == 0) {
   1432 		mutex_exit(rpipe->pipe_lock);
   1433 	}
   1434 	return (kn->kn_data >= PIPE_BUF);
   1435 }
   1436 
   1437 static const struct filterops pipe_rfiltops =
   1438 	{ 1, NULL, filt_pipedetach, filt_piperead };
   1439 static const struct filterops pipe_wfiltops =
   1440 	{ 1, NULL, filt_pipedetach, filt_pipewrite };
   1441 
   1442 /*ARGSUSED*/
   1443 static int
   1444 pipe_kqfilter(struct file *fp, struct knote *kn)
   1445 {
   1446 	struct pipe *pipe;
   1447 
   1448 	pipe = (struct pipe *)kn->kn_fp->f_data;
   1449 	mutex_enter(pipe->pipe_lock);
   1450 
   1451 	switch (kn->kn_filter) {
   1452 	case EVFILT_READ:
   1453 		kn->kn_fop = &pipe_rfiltops;
   1454 		break;
   1455 	case EVFILT_WRITE:
   1456 		kn->kn_fop = &pipe_wfiltops;
   1457 		pipe = pipe->pipe_peer;
   1458 		if (pipe == NULL) {
   1459 			/* other end of pipe has been closed */
   1460 			mutex_exit(pipe->pipe_lock);
   1461 			return (EBADF);
   1462 		}
   1463 		break;
   1464 	default:
   1465 		mutex_exit(pipe->pipe_lock);
   1466 		return (EINVAL);
   1467 	}
   1468 
   1469 	kn->kn_hook = pipe;
   1470 	SLIST_INSERT_HEAD(&pipe->pipe_sel.sel_klist, kn, kn_selnext);
   1471 	mutex_exit(pipe->pipe_lock);
   1472 
   1473 	return (0);
   1474 }
   1475 
   1476 /*
   1477  * Handle pipe sysctls.
   1478  */
   1479 SYSCTL_SETUP(sysctl_kern_pipe_setup, "sysctl kern.pipe subtree setup")
   1480 {
   1481 
   1482 	sysctl_createv(clog, 0, NULL, NULL,
   1483 		       CTLFLAG_PERMANENT,
   1484 		       CTLTYPE_NODE, "kern", NULL,
   1485 		       NULL, 0, NULL, 0,
   1486 		       CTL_KERN, CTL_EOL);
   1487 	sysctl_createv(clog, 0, NULL, NULL,
   1488 		       CTLFLAG_PERMANENT,
   1489 		       CTLTYPE_NODE, "pipe",
   1490 		       SYSCTL_DESCR("Pipe settings"),
   1491 		       NULL, 0, NULL, 0,
   1492 		       CTL_KERN, KERN_PIPE, CTL_EOL);
   1493 
   1494 	sysctl_createv(clog, 0, NULL, NULL,
   1495 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1496 		       CTLTYPE_INT, "maxkvasz",
   1497 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
   1498 				    "used for pipes"),
   1499 		       NULL, 0, &maxpipekva, 0,
   1500 		       CTL_KERN, KERN_PIPE, KERN_PIPE_MAXKVASZ, CTL_EOL);
   1501 	sysctl_createv(clog, 0, NULL, NULL,
   1502 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1503 		       CTLTYPE_INT, "maxloankvasz",
   1504 		       SYSCTL_DESCR("Limit for direct transfers via page loan"),
   1505 		       NULL, 0, &limitpipekva, 0,
   1506 		       CTL_KERN, KERN_PIPE, KERN_PIPE_LIMITKVA, CTL_EOL);
   1507 	sysctl_createv(clog, 0, NULL, NULL,
   1508 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1509 		       CTLTYPE_INT, "maxbigpipes",
   1510 		       SYSCTL_DESCR("Maximum number of \"big\" pipes"),
   1511 		       NULL, 0, &maxbigpipes, 0,
   1512 		       CTL_KERN, KERN_PIPE, KERN_PIPE_MAXBIGPIPES, CTL_EOL);
   1513 	sysctl_createv(clog, 0, NULL, NULL,
   1514 		       CTLFLAG_PERMANENT,
   1515 		       CTLTYPE_INT, "nbigpipes",
   1516 		       SYSCTL_DESCR("Number of \"big\" pipes"),
   1517 		       NULL, 0, &nbigpipe, 0,
   1518 		       CTL_KERN, KERN_PIPE, KERN_PIPE_NBIGPIPES, CTL_EOL);
   1519 	sysctl_createv(clog, 0, NULL, NULL,
   1520 		       CTLFLAG_PERMANENT,
   1521 		       CTLTYPE_INT, "kvasize",
   1522 		       SYSCTL_DESCR("Amount of kernel memory consumed by pipe "
   1523 				    "buffers"),
   1524 		       NULL, 0, &amountpipekva, 0,
   1525 		       CTL_KERN, KERN_PIPE, KERN_PIPE_KVASIZE, CTL_EOL);
   1526 }
   1527