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