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