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