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