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