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