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