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