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