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