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