Home | History | Annotate | Line # | Download | only in kern
sys_pipe.c revision 1.109
      1 /*	$NetBSD: sys_pipe.c,v 1.109 2009/04/04 10:12:51 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003, 2007, 2008, 2009 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  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1996 John S. Dyson
     34  * All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice immediately at the beginning of the file, without modification,
     41  *    this list of conditions, and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. Absolutely no warranty of function or purpose is made by the author
     46  *    John S. Dyson.
     47  * 4. Modifications may be freely made to this file if the above conditions
     48  *    are met.
     49  */
     50 
     51 /*
     52  * This file contains a high-performance replacement for the socket-based
     53  * pipes scheme originally used.  It does not support all features of
     54  * sockets, but does do everything that pipes normally do.
     55  *
     56  * This code has two modes of operation, a small write mode and a large
     57  * write mode.  The small write mode acts like conventional pipes with
     58  * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
     59  * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
     60  * and PIPE_SIZE in size it is mapped read-only into the kernel address space
     61  * using the UVM page loan facility from where the receiving process can copy
     62  * the data directly from the pages in the sending process.
     63  *
     64  * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
     65  * happen for small transfers so that the system will not spend all of
     66  * its time context switching.  PIPE_SIZE is constrained by the
     67  * amount of kernel virtual memory.
     68  */
     69 
     70 #include <sys/cdefs.h>
     71 __KERNEL_RCSID(0, "$NetBSD: sys_pipe.c,v 1.109 2009/04/04 10:12:51 ad Exp $");
     72 
     73 #include <sys/param.h>
     74 #include <sys/systm.h>
     75 #include <sys/proc.h>
     76 #include <sys/fcntl.h>
     77 #include <sys/file.h>
     78 #include <sys/filedesc.h>
     79 #include <sys/filio.h>
     80 #include <sys/kernel.h>
     81 #include <sys/ttycom.h>
     82 #include <sys/stat.h>
     83 #include <sys/poll.h>
     84 #include <sys/signalvar.h>
     85 #include <sys/vnode.h>
     86 #include <sys/uio.h>
     87 #include <sys/select.h>
     88 #include <sys/mount.h>
     89 #include <sys/syscallargs.h>
     90 #include <sys/sysctl.h>
     91 #include <sys/kauth.h>
     92 #include <sys/atomic.h>
     93 #include <sys/pipe.h>
     94 
     95 #include <uvm/uvm.h>
     96 
     97 /* Use this define if you want to disable *fancy* VM things. */
     98 /* XXX Disabled for now; rare hangs switching between direct/buffered */
     99 #define PIPE_NODIRECT
    100 
    101 /*
    102  * interfaces to the outside world
    103  */
    104 static int pipe_read(struct file *fp, off_t *offset, struct uio *uio,
    105 		kauth_cred_t cred, int flags);
    106 static int pipe_write(struct file *fp, off_t *offset, struct uio *uio,
    107 		kauth_cred_t cred, int flags);
    108 static int pipe_close(struct file *fp);
    109 static int pipe_poll(struct file *fp, int events);
    110 static int pipe_kqfilter(struct file *fp, struct knote *kn);
    111 static int pipe_stat(struct file *fp, struct stat *sb);
    112 static int pipe_ioctl(struct file *fp, u_long cmd, void *data);
    113 
    114 static const struct fileops pipeops = {
    115 	.fo_read = pipe_read,
    116 	.fo_write = pipe_write,
    117 	.fo_ioctl = pipe_ioctl,
    118 	.fo_fcntl = fnullop_fcntl,
    119 	.fo_poll = pipe_poll,
    120 	.fo_stat = pipe_stat,
    121 	.fo_close = pipe_close,
    122 	.fo_kqfilter = pipe_kqfilter,
    123 	.fo_drain = fnullop_drain,
    124 };
    125 
    126 /*
    127  * Default pipe buffer size(s), this can be kind-of large now because pipe
    128  * space is pageable.  The pipe code will try to maintain locality of
    129  * reference for performance reasons, so small amounts of outstanding I/O
    130  * will not wipe the cache.
    131  */
    132 #define MINPIPESIZE (PIPE_SIZE/3)
    133 #define MAXPIPESIZE (2*PIPE_SIZE/3)
    134 
    135 /*
    136  * Maximum amount of kva for pipes -- this is kind-of a soft limit, but
    137  * is there so that on large systems, we don't exhaust it.
    138  */
    139 #define MAXPIPEKVA (8*1024*1024)
    140 static u_int maxpipekva = MAXPIPEKVA;
    141 
    142 /*
    143  * Limit for direct transfers, we cannot, of course limit
    144  * the amount of kva for pipes in general though.
    145  */
    146 #define LIMITPIPEKVA (16*1024*1024)
    147 static u_int limitpipekva = LIMITPIPEKVA;
    148 
    149 /*
    150  * Limit the number of "big" pipes
    151  */
    152 #define LIMITBIGPIPES  32
    153 static u_int maxbigpipes = LIMITBIGPIPES;
    154 static u_int nbigpipe = 0;
    155 
    156 /*
    157  * Amount of KVA consumed by pipe buffers.
    158  */
    159 static u_int amountpipekva = 0;
    160 
    161 static void pipeclose(struct file *fp, struct pipe *pipe);
    162 static void pipe_free_kmem(struct pipe *pipe);
    163 static int pipe_create(struct pipe **pipep, pool_cache_t, kmutex_t *);
    164 static int pipelock(struct pipe *pipe, int catch);
    165 static inline void pipeunlock(struct pipe *pipe);
    166 static void pipeselwakeup(struct pipe *pipe, struct pipe *sigp, int code);
    167 #ifndef PIPE_NODIRECT
    168 static int pipe_direct_write(struct file *fp, struct pipe *wpipe,
    169     struct uio *uio);
    170 #endif
    171 static int pipespace(struct pipe *pipe, int size);
    172 static int pipe_ctor(void *, void *, int);
    173 static void pipe_dtor(void *, void *);
    174 
    175 #ifndef PIPE_NODIRECT
    176 static int pipe_loan_alloc(struct pipe *, int);
    177 static void pipe_loan_free(struct pipe *);
    178 #endif /* PIPE_NODIRECT */
    179 
    180 static pool_cache_t pipe_wr_cache;
    181 static pool_cache_t pipe_rd_cache;
    182 
    183 void
    184 pipe_init(void)
    185 {
    186 
    187 	/* Writer side is not automatically allocated KVA. */
    188 	pipe_wr_cache = pool_cache_init(sizeof(struct pipe), 0, 0, 0, "pipewr",
    189 	    NULL, IPL_NONE, pipe_ctor, pipe_dtor, NULL);
    190 	KASSERT(pipe_wr_cache != NULL);
    191 
    192 	/* Reader side gets preallocated KVA. */
    193 	pipe_rd_cache = pool_cache_init(sizeof(struct pipe), 0, 0, 0, "piperd",
    194 	    NULL, IPL_NONE, pipe_ctor, pipe_dtor, (void *)1);
    195 	KASSERT(pipe_rd_cache != NULL);
    196 }
    197 
    198 static int
    199 pipe_ctor(void *arg, void *obj, int flags)
    200 {
    201 	struct pipe *pipe;
    202 	vaddr_t va;
    203 
    204 	pipe = obj;
    205 
    206 	memset(pipe, 0, sizeof(struct pipe));
    207 	if (arg != NULL) {
    208 		/* Preallocate space. */
    209 		va = uvm_km_alloc(kernel_map, PIPE_SIZE, 0,
    210 		    UVM_KMF_PAGEABLE | UVM_KMF_WAITVA);
    211 		KASSERT(va != 0);
    212 		pipe->pipe_kmem = va;
    213 		atomic_add_int(&amountpipekva, PIPE_SIZE);
    214 	}
    215 	cv_init(&pipe->pipe_rcv, "piperd");
    216 	cv_init(&pipe->pipe_wcv, "pipewr");
    217 	cv_init(&pipe->pipe_draincv, "pipedrain");
    218 	cv_init(&pipe->pipe_lkcv, "pipelk");
    219 	selinit(&pipe->pipe_sel);
    220 	pipe->pipe_state = PIPE_SIGNALR;
    221 
    222 	return 0;
    223 }
    224 
    225 static void
    226 pipe_dtor(void *arg, void *obj)
    227 {
    228 	struct pipe *pipe;
    229 
    230 	pipe = obj;
    231 
    232 	cv_destroy(&pipe->pipe_rcv);
    233 	cv_destroy(&pipe->pipe_wcv);
    234 	cv_destroy(&pipe->pipe_draincv);
    235 	cv_destroy(&pipe->pipe_lkcv);
    236 	seldestroy(&pipe->pipe_sel);
    237 	if (pipe->pipe_kmem != 0) {
    238 		uvm_km_free(kernel_map, pipe->pipe_kmem, PIPE_SIZE,
    239 		    UVM_KMF_PAGEABLE);
    240 		atomic_add_int(&amountpipekva, -PIPE_SIZE);
    241 	}
    242 }
    243 
    244 /*
    245  * The pipe system call for the DTYPE_PIPE type of pipes
    246  */
    247 
    248 /* ARGSUSED */
    249 int
    250 sys_pipe(struct lwp *l, const void *v, register_t *retval)
    251 {
    252 	struct file *rf, *wf;
    253 	struct pipe *rpipe, *wpipe;
    254 	kmutex_t *mutex;
    255 	int fd, error;
    256 	proc_t *p;
    257 
    258 	p = curproc;
    259 	rpipe = wpipe = NULL;
    260 	mutex = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    261 	if (mutex == NULL)
    262 		return (ENOMEM);
    263 	mutex_obj_hold(mutex);
    264 	if (pipe_create(&rpipe, pipe_rd_cache, mutex) ||
    265 	    pipe_create(&wpipe, pipe_wr_cache, mutex)) {
    266 		pipeclose(NULL, rpipe);
    267 		pipeclose(NULL, wpipe);
    268 		return (ENFILE);
    269 	}
    270 
    271 	error = fd_allocfile(&rf, &fd);
    272 	if (error)
    273 		goto free2;
    274 	retval[0] = fd;
    275 	rf->f_flag = FREAD;
    276 	rf->f_type = DTYPE_PIPE;
    277 	rf->f_data = (void *)rpipe;
    278 	rf->f_ops = &pipeops;
    279 
    280 	error = fd_allocfile(&wf, &fd);
    281 	if (error)
    282 		goto free3;
    283 	retval[1] = fd;
    284 	wf->f_flag = FWRITE;
    285 	wf->f_type = DTYPE_PIPE;
    286 	wf->f_data = (void *)wpipe;
    287 	wf->f_ops = &pipeops;
    288 
    289 	rpipe->pipe_peer = wpipe;
    290 	wpipe->pipe_peer = rpipe;
    291 
    292 	fd_affix(p, rf, (int)retval[0]);
    293 	fd_affix(p, wf, (int)retval[1]);
    294 	return (0);
    295 free3:
    296 	fd_abort(p, rf, (int)retval[0]);
    297 free2:
    298 	pipeclose(NULL, wpipe);
    299 	pipeclose(NULL, rpipe);
    300 
    301 	return (error);
    302 }
    303 
    304 /*
    305  * Allocate kva for pipe circular buffer, the space is pageable
    306  * This routine will 'realloc' the size of a pipe safely, if it fails
    307  * it will retain the old buffer.
    308  * If it fails it will return ENOMEM.
    309  */
    310 static int
    311 pipespace(struct pipe *pipe, int size)
    312 {
    313 	void *buffer;
    314 
    315 	/*
    316 	 * Allocate pageable virtual address space.  Physical memory is
    317 	 * allocated on demand.
    318 	 */
    319 	if (size == PIPE_SIZE && pipe->pipe_kmem != 0) {
    320 		buffer = (void *)pipe->pipe_kmem;
    321 	} else {
    322 		buffer = (void *)uvm_km_alloc(kernel_map, round_page(size),
    323 		    0, UVM_KMF_PAGEABLE);
    324 		if (buffer == NULL)
    325 			return (ENOMEM);
    326 		atomic_add_int(&amountpipekva, size);
    327 	}
    328 
    329 	/* free old resources if we're resizing */
    330 	pipe_free_kmem(pipe);
    331 	pipe->pipe_buffer.buffer = buffer;
    332 	pipe->pipe_buffer.size = size;
    333 	pipe->pipe_buffer.in = 0;
    334 	pipe->pipe_buffer.out = 0;
    335 	pipe->pipe_buffer.cnt = 0;
    336 	return (0);
    337 }
    338 
    339 /*
    340  * Initialize and allocate VM and memory for pipe.
    341  */
    342 static int
    343 pipe_create(struct pipe **pipep, pool_cache_t cache, kmutex_t *mutex)
    344 {
    345 	struct pipe *pipe;
    346 	int error;
    347 
    348 	pipe = pool_cache_get(cache, PR_WAITOK);
    349 	KASSERT(pipe != NULL);
    350 	*pipep = pipe;
    351 	error = 0;
    352 	getmicrotime(&pipe->pipe_ctime);
    353 	pipe->pipe_atime = pipe->pipe_ctime;
    354 	pipe->pipe_mtime = pipe->pipe_ctime;
    355 	pipe->pipe_lock = mutex;
    356 	if (cache == pipe_rd_cache) {
    357 		error = pipespace(pipe, PIPE_SIZE);
    358 	} else {
    359 		pipe->pipe_buffer.buffer = NULL;
    360 		pipe->pipe_buffer.size = 0;
    361 		pipe->pipe_buffer.in = 0;
    362 		pipe->pipe_buffer.out = 0;
    363 		pipe->pipe_buffer.cnt = 0;
    364 	}
    365 	return error;
    366 }
    367 
    368 /*
    369  * Lock a pipe for I/O, blocking other access
    370  * Called with pipe spin lock held.
    371  * Return with pipe spin lock released on success.
    372  */
    373 static int
    374 pipelock(struct pipe *pipe, int catch)
    375 {
    376 	int error;
    377 
    378 	KASSERT(mutex_owned(pipe->pipe_lock));
    379 
    380 	while (pipe->pipe_state & PIPE_LOCKFL) {
    381 		pipe->pipe_state |= PIPE_LWANT;
    382 		if (catch) {
    383 			error = cv_wait_sig(&pipe->pipe_lkcv, pipe->pipe_lock);
    384 			if (error != 0)
    385 				return error;
    386 		} else
    387 			cv_wait(&pipe->pipe_lkcv, pipe->pipe_lock);
    388 	}
    389 
    390 	pipe->pipe_state |= PIPE_LOCKFL;
    391 
    392 	return 0;
    393 }
    394 
    395 /*
    396  * unlock a pipe I/O lock
    397  */
    398 static inline void
    399 pipeunlock(struct pipe *pipe)
    400 {
    401 
    402 	KASSERT(pipe->pipe_state & PIPE_LOCKFL);
    403 
    404 	pipe->pipe_state &= ~PIPE_LOCKFL;
    405 	if (pipe->pipe_state & PIPE_LWANT) {
    406 		pipe->pipe_state &= ~PIPE_LWANT;
    407 		cv_broadcast(&pipe->pipe_lkcv);
    408 	}
    409 }
    410 
    411 /*
    412  * Select/poll wakup. This also sends SIGIO to peer connected to
    413  * 'sigpipe' side of pipe.
    414  */
    415 static void
    416 pipeselwakeup(struct pipe *selp, struct pipe *sigp, int code)
    417 {
    418 	int band;
    419 
    420 	switch (code) {
    421 	case POLL_IN:
    422 		band = POLLIN|POLLRDNORM;
    423 		break;
    424 	case POLL_OUT:
    425 		band = POLLOUT|POLLWRNORM;
    426 		break;
    427 	case POLL_HUP:
    428 		band = POLLHUP;
    429 		break;
    430 	case POLL_ERR:
    431 		band = POLLERR;
    432 		break;
    433 	default:
    434 		band = 0;
    435 #ifdef DIAGNOSTIC
    436 		printf("bad siginfo code %d in pipe notification.\n", code);
    437 #endif
    438 		break;
    439 	}
    440 
    441 	selnotify(&selp->pipe_sel, band, NOTE_SUBMIT);
    442 
    443 	if (sigp == NULL || (sigp->pipe_state & PIPE_ASYNC) == 0)
    444 		return;
    445 
    446 	fownsignal(sigp->pipe_pgid, SIGIO, code, band, selp);
    447 }
    448 
    449 /* ARGSUSED */
    450 static int
    451 pipe_read(struct file *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
    452     int flags)
    453 {
    454 	struct pipe *rpipe = (struct pipe *) fp->f_data;
    455 	struct pipebuf *bp = &rpipe->pipe_buffer;
    456 	kmutex_t *lock = rpipe->pipe_lock;
    457 	int error;
    458 	size_t nread = 0;
    459 	size_t size;
    460 	size_t ocnt;
    461 
    462 	mutex_enter(lock);
    463 	++rpipe->pipe_busy;
    464 	ocnt = bp->cnt;
    465 
    466 again:
    467 	error = pipelock(rpipe, 1);
    468 	if (error)
    469 		goto unlocked_error;
    470 
    471 	while (uio->uio_resid) {
    472 		/*
    473 		 * normal pipe buffer receive
    474 		 */
    475 		if (bp->cnt > 0) {
    476 			size = bp->size - bp->out;
    477 			if (size > bp->cnt)
    478 				size = bp->cnt;
    479 			if (size > uio->uio_resid)
    480 				size = uio->uio_resid;
    481 
    482 			mutex_exit(lock);
    483 			error = uiomove((char *)bp->buffer + bp->out, size, uio);
    484 			mutex_enter(lock);
    485 			if (error)
    486 				break;
    487 
    488 			bp->out += size;
    489 			if (bp->out >= bp->size)
    490 				bp->out = 0;
    491 
    492 			bp->cnt -= size;
    493 
    494 			/*
    495 			 * If there is no more to read in the pipe, reset
    496 			 * its pointers to the beginning.  This improves
    497 			 * cache hit stats.
    498 			 */
    499 			if (bp->cnt == 0) {
    500 				bp->in = 0;
    501 				bp->out = 0;
    502 			}
    503 			nread += size;
    504 			continue;
    505 		}
    506 
    507 #ifndef PIPE_NODIRECT
    508 		if ((rpipe->pipe_state & PIPE_DIRECTR) != 0) {
    509 			/*
    510 			 * Direct copy, bypassing a kernel buffer.
    511 			 */
    512 			void *	va;
    513 
    514 			KASSERT(rpipe->pipe_state & PIPE_DIRECTW);
    515 
    516 			size = rpipe->pipe_map.cnt;
    517 			if (size > uio->uio_resid)
    518 				size = uio->uio_resid;
    519 
    520 			va = (char *)rpipe->pipe_map.kva + rpipe->pipe_map.pos;
    521 			mutex_exit(lock);
    522 			error = uiomove(va, size, uio);
    523 			mutex_enter(lock);
    524 			if (error)
    525 				break;
    526 			nread += size;
    527 			rpipe->pipe_map.pos += size;
    528 			rpipe->pipe_map.cnt -= size;
    529 			if (rpipe->pipe_map.cnt == 0) {
    530 				rpipe->pipe_state &= ~PIPE_DIRECTR;
    531 				cv_broadcast(&rpipe->pipe_wcv);
    532 			}
    533 			continue;
    534 		}
    535 #endif
    536 		/*
    537 		 * Break if some data was read.
    538 		 */
    539 		if (nread > 0)
    540 			break;
    541 
    542 		/*
    543 		 * detect EOF condition
    544 		 * read returns 0 on EOF, no need to set error
    545 		 */
    546 		if (rpipe->pipe_state & PIPE_EOF)
    547 			break;
    548 
    549 		/*
    550 		 * don't block on non-blocking I/O
    551 		 */
    552 		if (fp->f_flag & FNONBLOCK) {
    553 			error = EAGAIN;
    554 			break;
    555 		}
    556 
    557 		/*
    558 		 * Unlock the pipe buffer for our remaining processing.
    559 		 * We will either break out with an error or we will
    560 		 * sleep and relock to loop.
    561 		 */
    562 		pipeunlock(rpipe);
    563 
    564 		/*
    565 		 * Re-check to see if more direct writes are pending.
    566 		 */
    567 		if ((rpipe->pipe_state & PIPE_DIRECTR) != 0)
    568 			goto again;
    569 
    570 		/*
    571 		 * We want to read more, wake up select/poll.
    572 		 */
    573 		pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
    574 
    575 		/*
    576 		 * If the "write-side" is blocked, wake it up now.
    577 		 */
    578 		cv_broadcast(&rpipe->pipe_wcv);
    579 
    580 		/* Now wait until the pipe is filled */
    581 		error = cv_wait_sig(&rpipe->pipe_rcv, lock);
    582 		if (error != 0)
    583 			goto unlocked_error;
    584 		goto again;
    585 	}
    586 
    587 	if (error == 0)
    588 		getmicrotime(&rpipe->pipe_atime);
    589 	pipeunlock(rpipe);
    590 
    591 unlocked_error:
    592 	--rpipe->pipe_busy;
    593 	if (rpipe->pipe_busy == 0) {
    594 		cv_broadcast(&rpipe->pipe_draincv);
    595 	}
    596 	if (bp->cnt < MINPIPESIZE) {
    597 		cv_broadcast(&rpipe->pipe_wcv);
    598 	}
    599 
    600 	/*
    601 	 * If anything was read off the buffer, signal to the writer it's
    602 	 * possible to write more data. Also send signal if we are here for the
    603 	 * first time after last write.
    604 	 */
    605 	if ((bp->size - bp->cnt) >= PIPE_BUF
    606 	    && (ocnt != bp->cnt || (rpipe->pipe_state & PIPE_SIGNALR))) {
    607 		pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
    608 		rpipe->pipe_state &= ~PIPE_SIGNALR;
    609 	}
    610 
    611 	mutex_exit(lock);
    612 	return (error);
    613 }
    614 
    615 #ifndef PIPE_NODIRECT
    616 /*
    617  * Allocate structure for loan transfer.
    618  */
    619 static int
    620 pipe_loan_alloc(struct pipe *wpipe, int npages)
    621 {
    622 	vsize_t len;
    623 
    624 	len = (vsize_t)npages << PAGE_SHIFT;
    625 	atomic_add_int(&amountpipekva, len);
    626 	wpipe->pipe_map.kva = uvm_km_alloc(kernel_map, len, 0,
    627 	    UVM_KMF_VAONLY | UVM_KMF_WAITVA);
    628 	if (wpipe->pipe_map.kva == 0) {
    629 		atomic_add_int(&amountpipekva, -len);
    630 		return (ENOMEM);
    631 	}
    632 
    633 	wpipe->pipe_map.npages = npages;
    634 	wpipe->pipe_map.pgs = kmem_alloc(npages * sizeof(struct vm_page *),
    635 	    KM_SLEEP);
    636 	return (0);
    637 }
    638 
    639 /*
    640  * Free resources allocated for loan transfer.
    641  */
    642 static void
    643 pipe_loan_free(struct pipe *wpipe)
    644 {
    645 	vsize_t len;
    646 
    647 	len = (vsize_t)wpipe->pipe_map.npages << PAGE_SHIFT;
    648 	uvm_km_free(kernel_map, wpipe->pipe_map.kva, len, UVM_KMF_VAONLY);
    649 	wpipe->pipe_map.kva = 0;
    650 	atomic_add_int(&amountpipekva, -len);
    651 	kmem_free(wpipe->pipe_map.pgs,
    652 	    wpipe->pipe_map.npages * sizeof(struct vm_page *));
    653 	wpipe->pipe_map.pgs = NULL;
    654 }
    655 
    656 /*
    657  * NetBSD direct write, using uvm_loan() mechanism.
    658  * This implements the pipe buffer write mechanism.  Note that only
    659  * a direct write OR a normal pipe write can be pending at any given time.
    660  * If there are any characters in the pipe buffer, the direct write will
    661  * be deferred until the receiving process grabs all of the bytes from
    662  * the pipe buffer.  Then the direct mapping write is set-up.
    663  *
    664  * Called with the long-term pipe lock held.
    665  */
    666 static int
    667 pipe_direct_write(struct file *fp, struct pipe *wpipe, struct uio *uio)
    668 {
    669 	int error, npages, j;
    670 	struct vm_page **pgs;
    671 	vaddr_t bbase, kva, base, bend;
    672 	vsize_t blen, bcnt;
    673 	voff_t bpos;
    674 	kmutex_t *lock = wpipe->pipe_lock;
    675 
    676 	KASSERT(mutex_owned(wpipe->pipe_lock));
    677 	KASSERT(wpipe->pipe_map.cnt == 0);
    678 
    679 	mutex_exit(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(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(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(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_rcv);
    748 		error = cv_wait_sig(&wpipe->pipe_wcv, 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_rcv);
    759 		pipeselwakeup(wpipe, wpipe, POLL_IN);
    760 		error = cv_wait_sig(&wpipe->pipe_wcv, 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(lock);
    771 
    772 	if (pgs != NULL) {
    773 		pmap_kremove(wpipe->pipe_map.kva, blen);
    774 		pmap_update(pmap_kernel());
    775 		uvm_unloan(pgs, npages, UVM_LOAN_TOPAGE);
    776 	}
    777 	if (error || amountpipekva > maxpipekva)
    778 		pipe_loan_free(wpipe);
    779 
    780 	mutex_enter(lock);
    781 	if (error) {
    782 		pipeselwakeup(wpipe, wpipe, POLL_ERR);
    783 
    784 		/*
    785 		 * If nothing was read from what we offered, return error
    786 		 * straight on. Otherwise update uio resid first. Caller
    787 		 * will deal with the error condition, returning short
    788 		 * write, error, or restarting the write(2) as appropriate.
    789 		 */
    790 		if (wpipe->pipe_map.cnt == bcnt) {
    791 			wpipe->pipe_map.cnt = 0;
    792 			cv_broadcast(&wpipe->pipe_wcv);
    793 			return (error);
    794 		}
    795 
    796 		bcnt -= wpipe->pipe_map.cnt;
    797 	}
    798 
    799 	uio->uio_resid -= bcnt;
    800 	/* uio_offset not updated, not set/used for write(2) */
    801 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + bcnt;
    802 	uio->uio_iov->iov_len -= bcnt;
    803 	if (uio->uio_iov->iov_len == 0) {
    804 		uio->uio_iov++;
    805 		uio->uio_iovcnt--;
    806 	}
    807 
    808 	wpipe->pipe_map.cnt = 0;
    809 	return (error);
    810 }
    811 #endif /* !PIPE_NODIRECT */
    812 
    813 static int
    814 pipe_write(struct file *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
    815     int flags)
    816 {
    817 	struct pipe *wpipe, *rpipe;
    818 	struct pipebuf *bp;
    819 	kmutex_t *lock;
    820 	int error;
    821 
    822 	/* We want to write to our peer */
    823 	rpipe = (struct pipe *) fp->f_data;
    824 	lock = rpipe->pipe_lock;
    825 	error = 0;
    826 
    827 	mutex_enter(lock);
    828 	wpipe = rpipe->pipe_peer;
    829 
    830 	/*
    831 	 * Detect loss of pipe read side, issue SIGPIPE if lost.
    832 	 */
    833 	if (wpipe == NULL || (wpipe->pipe_state & PIPE_EOF) != 0) {
    834 		mutex_exit(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_draincv);
    844 		}
    845 		mutex_exit(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_rcv);
    879 			pipeunlock(wpipe);
    880 			error = cv_wait_sig(&wpipe->pipe_wcv, lock);
    881 			(void)pipelock(wpipe, 0);
    882 			if (wpipe->pipe_state & PIPE_EOF)
    883 				error = EPIPE;
    884 		}
    885 		if (error)
    886 			break;
    887 
    888 		/*
    889 		 * If the transfer is large, we can gain performance if
    890 		 * we do process-to-process copies directly.
    891 		 * If the write is non-blocking, we don't use the
    892 		 * direct write mechanism.
    893 		 *
    894 		 * The direct write mechanism will detect the reader going
    895 		 * away on us.
    896 		 */
    897 		if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT) &&
    898 		    (fp->f_flag & FNONBLOCK) == 0 &&
    899 		    (wpipe->pipe_map.kva || (amountpipekva < limitpipekva))) {
    900 			error = pipe_direct_write(fp, wpipe, uio);
    901 
    902 			/*
    903 			 * Break out if error occurred, unless it's ENOMEM.
    904 			 * ENOMEM means we failed to allocate some resources
    905 			 * for direct write, so we just fallback to ordinary
    906 			 * write. If the direct write was successful,
    907 			 * process rest of data via ordinary write.
    908 			 */
    909 			if (error == 0)
    910 				continue;
    911 
    912 			if (error != ENOMEM)
    913 				break;
    914 		}
    915 #endif /* PIPE_NODIRECT */
    916 
    917 		space = bp->size - bp->cnt;
    918 
    919 		/* Writes of size <= PIPE_BUF must be atomic. */
    920 		if ((space < uio->uio_resid) && (uio->uio_resid <= PIPE_BUF))
    921 			space = 0;
    922 
    923 		if (space > 0) {
    924 			int size;	/* Transfer size */
    925 			int segsize;	/* first segment to transfer */
    926 
    927 			/*
    928 			 * Transfer size is minimum of uio transfer
    929 			 * and free space in pipe buffer.
    930 			 */
    931 			if (space > uio->uio_resid)
    932 				size = uio->uio_resid;
    933 			else
    934 				size = space;
    935 			/*
    936 			 * First segment to transfer is minimum of
    937 			 * transfer size and contiguous space in
    938 			 * pipe buffer.  If first segment to transfer
    939 			 * is less than the transfer size, we've got
    940 			 * a wraparound in the buffer.
    941 			 */
    942 			segsize = bp->size - bp->in;
    943 			if (segsize > size)
    944 				segsize = size;
    945 
    946 			/* Transfer first segment */
    947 			mutex_exit(lock);
    948 			error = uiomove((char *)bp->buffer + bp->in, segsize,
    949 			    uio);
    950 
    951 			if (error == 0 && segsize < size) {
    952 				/*
    953 				 * Transfer remaining part now, to
    954 				 * support atomic writes.  Wraparound
    955 				 * happened.
    956 				 */
    957 #ifdef DEBUG
    958 				if (bp->in + segsize != bp->size)
    959 					panic("Expected pipe buffer wraparound disappeared");
    960 #endif
    961 
    962 				error = uiomove(bp->buffer,
    963 				    size - segsize, uio);
    964 			}
    965 			mutex_enter(lock);
    966 			if (error)
    967 				break;
    968 
    969 			bp->in += size;
    970 			if (bp->in >= bp->size) {
    971 #ifdef DEBUG
    972 				if (bp->in != size - segsize + bp->size)
    973 					panic("Expected wraparound bad");
    974 #endif
    975 				bp->in = size - segsize;
    976 			}
    977 
    978 			bp->cnt += size;
    979 #ifdef DEBUG
    980 			if (bp->cnt > bp->size)
    981 				panic("Pipe buffer overflow");
    982 #endif
    983 		} else {
    984 			/*
    985 			 * If the "read-side" has been blocked, wake it up now.
    986 			 */
    987 			cv_broadcast(&wpipe->pipe_rcv);
    988 
    989 			/*
    990 			 * don't block on non-blocking I/O
    991 			 */
    992 			if (fp->f_flag & FNONBLOCK) {
    993 				error = EAGAIN;
    994 				break;
    995 			}
    996 
    997 			/*
    998 			 * We have no more space and have something to offer,
    999 			 * wake up select/poll.
   1000 			 */
   1001 			if (bp->cnt)
   1002 				pipeselwakeup(wpipe, wpipe, POLL_IN);
   1003 
   1004 			pipeunlock(wpipe);
   1005 			error = cv_wait_sig(&wpipe->pipe_wcv, lock);
   1006 			(void)pipelock(wpipe, 0);
   1007 			if (error != 0)
   1008 				break;
   1009 			/*
   1010 			 * If read side wants to go away, we just issue a signal
   1011 			 * to ourselves.
   1012 			 */
   1013 			if (wpipe->pipe_state & PIPE_EOF) {
   1014 				error = EPIPE;
   1015 				break;
   1016 			}
   1017 		}
   1018 	}
   1019 
   1020 	--wpipe->pipe_busy;
   1021 	if (wpipe->pipe_busy == 0) {
   1022 		cv_broadcast(&wpipe->pipe_draincv);
   1023 	}
   1024 	if (bp->cnt > 0) {
   1025 		cv_broadcast(&wpipe->pipe_rcv);
   1026 	}
   1027 
   1028 	/*
   1029 	 * Don't return EPIPE if I/O was successful
   1030 	 */
   1031 	if (error == EPIPE && bp->cnt == 0 && uio->uio_resid == 0)
   1032 		error = 0;
   1033 
   1034 	if (error == 0)
   1035 		getmicrotime(&wpipe->pipe_mtime);
   1036 
   1037 	/*
   1038 	 * We have something to offer, wake up select/poll.
   1039 	 * wpipe->pipe_map.cnt is always 0 in this point (direct write
   1040 	 * is only done synchronously), so check only wpipe->pipe_buffer.cnt
   1041 	 */
   1042 	if (bp->cnt)
   1043 		pipeselwakeup(wpipe, wpipe, POLL_IN);
   1044 
   1045 	/*
   1046 	 * Arrange for next read(2) to do a signal.
   1047 	 */
   1048 	wpipe->pipe_state |= PIPE_SIGNALR;
   1049 
   1050 	pipeunlock(wpipe);
   1051 	mutex_exit(lock);
   1052 	return (error);
   1053 }
   1054 
   1055 /*
   1056  * we implement a very minimal set of ioctls for compatibility with sockets.
   1057  */
   1058 int
   1059 pipe_ioctl(struct file *fp, u_long cmd, void *data)
   1060 {
   1061 	struct pipe *pipe = fp->f_data;
   1062 	kmutex_t *lock = pipe->pipe_lock;
   1063 
   1064 	switch (cmd) {
   1065 
   1066 	case FIONBIO:
   1067 		return (0);
   1068 
   1069 	case FIOASYNC:
   1070 		mutex_enter(lock);
   1071 		if (*(int *)data) {
   1072 			pipe->pipe_state |= PIPE_ASYNC;
   1073 		} else {
   1074 			pipe->pipe_state &= ~PIPE_ASYNC;
   1075 		}
   1076 		mutex_exit(lock);
   1077 		return (0);
   1078 
   1079 	case FIONREAD:
   1080 		mutex_enter(lock);
   1081 #ifndef PIPE_NODIRECT
   1082 		if (pipe->pipe_state & PIPE_DIRECTW)
   1083 			*(int *)data = pipe->pipe_map.cnt;
   1084 		else
   1085 #endif
   1086 			*(int *)data = pipe->pipe_buffer.cnt;
   1087 		mutex_exit(lock);
   1088 		return (0);
   1089 
   1090 	case FIONWRITE:
   1091 		/* Look at other side */
   1092 		pipe = pipe->pipe_peer;
   1093 		mutex_enter(lock);
   1094 #ifndef PIPE_NODIRECT
   1095 		if (pipe->pipe_state & PIPE_DIRECTW)
   1096 			*(int *)data = pipe->pipe_map.cnt;
   1097 		else
   1098 #endif
   1099 			*(int *)data = pipe->pipe_buffer.cnt;
   1100 		mutex_exit(lock);
   1101 		return (0);
   1102 
   1103 	case FIONSPACE:
   1104 		/* Look at other side */
   1105 		pipe = pipe->pipe_peer;
   1106 		mutex_enter(lock);
   1107 #ifndef PIPE_NODIRECT
   1108 		/*
   1109 		 * If we're in direct-mode, we don't really have a
   1110 		 * send queue, and any other write will block. Thus
   1111 		 * zero seems like the best answer.
   1112 		 */
   1113 		if (pipe->pipe_state & PIPE_DIRECTW)
   1114 			*(int *)data = 0;
   1115 		else
   1116 #endif
   1117 			*(int *)data = pipe->pipe_buffer.size -
   1118 			    pipe->pipe_buffer.cnt;
   1119 		mutex_exit(lock);
   1120 		return (0);
   1121 
   1122 	case TIOCSPGRP:
   1123 	case FIOSETOWN:
   1124 		return fsetown(&pipe->pipe_pgid, cmd, data);
   1125 
   1126 	case TIOCGPGRP:
   1127 	case FIOGETOWN:
   1128 		return fgetown(pipe->pipe_pgid, cmd, data);
   1129 
   1130 	}
   1131 	return (EPASSTHROUGH);
   1132 }
   1133 
   1134 int
   1135 pipe_poll(struct file *fp, int events)
   1136 {
   1137 	struct pipe *rpipe = fp->f_data;
   1138 	struct pipe *wpipe;
   1139 	int eof = 0;
   1140 	int revents = 0;
   1141 
   1142 	mutex_enter(rpipe->pipe_lock);
   1143 	wpipe = rpipe->pipe_peer;
   1144 
   1145 	if (events & (POLLIN | POLLRDNORM))
   1146 		if ((rpipe->pipe_buffer.cnt > 0) ||
   1147 #ifndef PIPE_NODIRECT
   1148 		    (rpipe->pipe_state & PIPE_DIRECTR) ||
   1149 #endif
   1150 		    (rpipe->pipe_state & PIPE_EOF))
   1151 			revents |= events & (POLLIN | POLLRDNORM);
   1152 
   1153 	eof |= (rpipe->pipe_state & PIPE_EOF);
   1154 
   1155 	if (wpipe == NULL)
   1156 		revents |= events & (POLLOUT | POLLWRNORM);
   1157 	else {
   1158 		if (events & (POLLOUT | POLLWRNORM))
   1159 			if ((wpipe->pipe_state & PIPE_EOF) || (
   1160 #ifndef PIPE_NODIRECT
   1161 			     (wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
   1162 #endif
   1163 			     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
   1164 				revents |= events & (POLLOUT | POLLWRNORM);
   1165 
   1166 		eof |= (wpipe->pipe_state & PIPE_EOF);
   1167 	}
   1168 
   1169 	if (wpipe == NULL || eof)
   1170 		revents |= POLLHUP;
   1171 
   1172 	if (revents == 0) {
   1173 		if (events & (POLLIN | POLLRDNORM))
   1174 			selrecord(curlwp, &rpipe->pipe_sel);
   1175 
   1176 		if (events & (POLLOUT | POLLWRNORM))
   1177 			selrecord(curlwp, &wpipe->pipe_sel);
   1178 	}
   1179 	mutex_exit(rpipe->pipe_lock);
   1180 
   1181 	return (revents);
   1182 }
   1183 
   1184 static int
   1185 pipe_stat(struct file *fp, struct stat *ub)
   1186 {
   1187 	struct pipe *pipe = fp->f_data;
   1188 
   1189 	memset((void *)ub, 0, sizeof(*ub));
   1190 	ub->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
   1191 	ub->st_blksize = pipe->pipe_buffer.size;
   1192 	if (ub->st_blksize == 0 && pipe->pipe_peer)
   1193 		ub->st_blksize = pipe->pipe_peer->pipe_buffer.size;
   1194 	ub->st_size = pipe->pipe_buffer.cnt;
   1195 	ub->st_blocks = (ub->st_size) ? 1 : 0;
   1196 	TIMEVAL_TO_TIMESPEC(&pipe->pipe_atime, &ub->st_atimespec);
   1197 	TIMEVAL_TO_TIMESPEC(&pipe->pipe_mtime, &ub->st_mtimespec);
   1198 	TIMEVAL_TO_TIMESPEC(&pipe->pipe_ctime, &ub->st_ctimespec);
   1199 	ub->st_uid = kauth_cred_geteuid(fp->f_cred);
   1200 	ub->st_gid = kauth_cred_getegid(fp->f_cred);
   1201 
   1202 	/*
   1203 	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
   1204 	 * XXX (st_dev, st_ino) should be unique.
   1205 	 */
   1206 	return (0);
   1207 }
   1208 
   1209 /* ARGSUSED */
   1210 static int
   1211 pipe_close(struct file *fp)
   1212 {
   1213 	struct pipe *pipe = fp->f_data;
   1214 
   1215 	fp->f_data = NULL;
   1216 	pipeclose(fp, pipe);
   1217 	return (0);
   1218 }
   1219 
   1220 static void
   1221 pipe_free_kmem(struct pipe *pipe)
   1222 {
   1223 
   1224 	if (pipe->pipe_buffer.buffer != NULL) {
   1225 		if (pipe->pipe_buffer.size > PIPE_SIZE) {
   1226 			atomic_dec_uint(&nbigpipe);
   1227 		}
   1228 		if (pipe->pipe_buffer.buffer != (void *)pipe->pipe_kmem) {
   1229 			uvm_km_free(kernel_map,
   1230 			    (vaddr_t)pipe->pipe_buffer.buffer,
   1231 			    pipe->pipe_buffer.size, UVM_KMF_PAGEABLE);
   1232 			atomic_add_int(&amountpipekva,
   1233 			    -pipe->pipe_buffer.size);
   1234 		}
   1235 		pipe->pipe_buffer.buffer = NULL;
   1236 	}
   1237 #ifndef PIPE_NODIRECT
   1238 	if (pipe->pipe_map.kva != 0) {
   1239 		pipe_loan_free(pipe);
   1240 		pipe->pipe_map.cnt = 0;
   1241 		pipe->pipe_map.kva = 0;
   1242 		pipe->pipe_map.pos = 0;
   1243 		pipe->pipe_map.npages = 0;
   1244 	}
   1245 #endif /* !PIPE_NODIRECT */
   1246 }
   1247 
   1248 /*
   1249  * shutdown the pipe
   1250  */
   1251 static void
   1252 pipeclose(struct file *fp, struct pipe *pipe)
   1253 {
   1254 	kmutex_t *lock;
   1255 	struct pipe *ppipe;
   1256 
   1257 	if (pipe == NULL)
   1258 		return;
   1259 
   1260 	KASSERT(cv_is_valid(&pipe->pipe_rcv));
   1261 	KASSERT(cv_is_valid(&pipe->pipe_wcv));
   1262 	KASSERT(cv_is_valid(&pipe->pipe_draincv));
   1263 	KASSERT(cv_is_valid(&pipe->pipe_lkcv));
   1264 
   1265 	lock = pipe->pipe_lock;
   1266 	mutex_enter(lock);
   1267 	pipeselwakeup(pipe, pipe, POLL_HUP);
   1268 
   1269 	/*
   1270 	 * If the other side is blocked, wake it up saying that
   1271 	 * we want to close it down.
   1272 	 */
   1273 	pipe->pipe_state |= PIPE_EOF;
   1274 	if (pipe->pipe_busy) {
   1275 		while (pipe->pipe_busy) {
   1276 			cv_broadcast(&pipe->pipe_wcv);
   1277 			cv_wait_sig(&pipe->pipe_draincv, lock);
   1278 		}
   1279 	}
   1280 
   1281 	/*
   1282 	 * Disconnect from peer
   1283 	 */
   1284 	if ((ppipe = pipe->pipe_peer) != NULL) {
   1285 		pipeselwakeup(ppipe, ppipe, POLL_HUP);
   1286 		ppipe->pipe_state |= PIPE_EOF;
   1287 		cv_broadcast(&ppipe->pipe_rcv);
   1288 		ppipe->pipe_peer = NULL;
   1289 	}
   1290 
   1291 	/*
   1292 	 * Any knote objects still left in the list are
   1293 	 * the one attached by peer.  Since no one will
   1294 	 * traverse this list, we just clear it.
   1295 	 */
   1296 	SLIST_INIT(&pipe->pipe_sel.sel_klist);
   1297 
   1298 	KASSERT((pipe->pipe_state & PIPE_LOCKFL) == 0);
   1299 	mutex_exit(lock);
   1300 
   1301 	/*
   1302 	 * free resources
   1303 	 */
   1304 	pipe->pipe_pgid = 0;
   1305 	pipe->pipe_state = PIPE_SIGNALR;
   1306 	pipe_free_kmem(pipe);
   1307 	if (pipe->pipe_kmem != 0) {
   1308 		pool_cache_put(pipe_rd_cache, pipe);
   1309 	} else {
   1310 		pool_cache_put(pipe_wr_cache, pipe);
   1311 	}
   1312 	mutex_obj_free(lock);
   1313 }
   1314 
   1315 static void
   1316 filt_pipedetach(struct knote *kn)
   1317 {
   1318 	struct pipe *pipe;
   1319 	kmutex_t *lock;
   1320 
   1321 	pipe = ((file_t *)kn->kn_obj)->f_data;
   1322 	lock = pipe->pipe_lock;
   1323 
   1324 	mutex_enter(lock);
   1325 
   1326 	switch(kn->kn_filter) {
   1327 	case EVFILT_WRITE:
   1328 		/* need the peer structure, not our own */
   1329 		pipe = pipe->pipe_peer;
   1330 
   1331 		/* if reader end already closed, just return */
   1332 		if (pipe == NULL) {
   1333 			mutex_exit(lock);
   1334 			return;
   1335 		}
   1336 
   1337 		break;
   1338 	default:
   1339 		/* nothing to do */
   1340 		break;
   1341 	}
   1342 
   1343 #ifdef DIAGNOSTIC
   1344 	if (kn->kn_hook != pipe)
   1345 		panic("filt_pipedetach: inconsistent knote");
   1346 #endif
   1347 
   1348 	SLIST_REMOVE(&pipe->pipe_sel.sel_klist, kn, knote, kn_selnext);
   1349 	mutex_exit(lock);
   1350 }
   1351 
   1352 /*ARGSUSED*/
   1353 static int
   1354 filt_piperead(struct knote *kn, long hint)
   1355 {
   1356 	struct pipe *rpipe = ((file_t *)kn->kn_obj)->f_data;
   1357 	struct pipe *wpipe;
   1358 
   1359 	if ((hint & NOTE_SUBMIT) == 0) {
   1360 		mutex_enter(rpipe->pipe_lock);
   1361 	}
   1362 	wpipe = rpipe->pipe_peer;
   1363 	kn->kn_data = rpipe->pipe_buffer.cnt;
   1364 
   1365 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
   1366 		kn->kn_data = rpipe->pipe_map.cnt;
   1367 
   1368 	if ((rpipe->pipe_state & PIPE_EOF) ||
   1369 	    (wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
   1370 		kn->kn_flags |= EV_EOF;
   1371 		if ((hint & NOTE_SUBMIT) == 0) {
   1372 			mutex_exit(rpipe->pipe_lock);
   1373 		}
   1374 		return (1);
   1375 	}
   1376 
   1377 	if ((hint & NOTE_SUBMIT) == 0) {
   1378 		mutex_exit(rpipe->pipe_lock);
   1379 	}
   1380 	return (kn->kn_data > 0);
   1381 }
   1382 
   1383 /*ARGSUSED*/
   1384 static int
   1385 filt_pipewrite(struct knote *kn, long hint)
   1386 {
   1387 	struct pipe *rpipe = ((file_t *)kn->kn_obj)->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 
   1395 	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
   1396 		kn->kn_data = 0;
   1397 		kn->kn_flags |= EV_EOF;
   1398 		if ((hint & NOTE_SUBMIT) == 0) {
   1399 			mutex_exit(rpipe->pipe_lock);
   1400 		}
   1401 		return (1);
   1402 	}
   1403 	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
   1404 	if (wpipe->pipe_state & PIPE_DIRECTW)
   1405 		kn->kn_data = 0;
   1406 
   1407 	if ((hint & NOTE_SUBMIT) == 0) {
   1408 		mutex_exit(rpipe->pipe_lock);
   1409 	}
   1410 	return (kn->kn_data >= PIPE_BUF);
   1411 }
   1412 
   1413 static const struct filterops pipe_rfiltops =
   1414 	{ 1, NULL, filt_pipedetach, filt_piperead };
   1415 static const struct filterops pipe_wfiltops =
   1416 	{ 1, NULL, filt_pipedetach, filt_pipewrite };
   1417 
   1418 /*ARGSUSED*/
   1419 static int
   1420 pipe_kqfilter(struct file *fp, struct knote *kn)
   1421 {
   1422 	struct pipe *pipe;
   1423 	kmutex_t *lock;
   1424 
   1425 	pipe = ((file_t *)kn->kn_obj)->f_data;
   1426 	lock = pipe->pipe_lock;
   1427 
   1428 	mutex_enter(lock);
   1429 
   1430 	switch (kn->kn_filter) {
   1431 	case EVFILT_READ:
   1432 		kn->kn_fop = &pipe_rfiltops;
   1433 		break;
   1434 	case EVFILT_WRITE:
   1435 		kn->kn_fop = &pipe_wfiltops;
   1436 		pipe = pipe->pipe_peer;
   1437 		if (pipe == NULL) {
   1438 			/* other end of pipe has been closed */
   1439 			mutex_exit(lock);
   1440 			return (EBADF);
   1441 		}
   1442 		break;
   1443 	default:
   1444 		mutex_exit(lock);
   1445 		return (EINVAL);
   1446 	}
   1447 
   1448 	kn->kn_hook = pipe;
   1449 	SLIST_INSERT_HEAD(&pipe->pipe_sel.sel_klist, kn, kn_selnext);
   1450 	mutex_exit(lock);
   1451 
   1452 	return (0);
   1453 }
   1454 
   1455 /*
   1456  * Handle pipe sysctls.
   1457  */
   1458 SYSCTL_SETUP(sysctl_kern_pipe_setup, "sysctl kern.pipe subtree setup")
   1459 {
   1460 
   1461 	sysctl_createv(clog, 0, NULL, NULL,
   1462 		       CTLFLAG_PERMANENT,
   1463 		       CTLTYPE_NODE, "kern", NULL,
   1464 		       NULL, 0, NULL, 0,
   1465 		       CTL_KERN, CTL_EOL);
   1466 	sysctl_createv(clog, 0, NULL, NULL,
   1467 		       CTLFLAG_PERMANENT,
   1468 		       CTLTYPE_NODE, "pipe",
   1469 		       SYSCTL_DESCR("Pipe settings"),
   1470 		       NULL, 0, NULL, 0,
   1471 		       CTL_KERN, KERN_PIPE, CTL_EOL);
   1472 
   1473 	sysctl_createv(clog, 0, NULL, NULL,
   1474 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1475 		       CTLTYPE_INT, "maxkvasz",
   1476 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
   1477 				    "used for pipes"),
   1478 		       NULL, 0, &maxpipekva, 0,
   1479 		       CTL_KERN, KERN_PIPE, KERN_PIPE_MAXKVASZ, CTL_EOL);
   1480 	sysctl_createv(clog, 0, NULL, NULL,
   1481 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1482 		       CTLTYPE_INT, "maxloankvasz",
   1483 		       SYSCTL_DESCR("Limit for direct transfers via page loan"),
   1484 		       NULL, 0, &limitpipekva, 0,
   1485 		       CTL_KERN, KERN_PIPE, KERN_PIPE_LIMITKVA, CTL_EOL);
   1486 	sysctl_createv(clog, 0, NULL, NULL,
   1487 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1488 		       CTLTYPE_INT, "maxbigpipes",
   1489 		       SYSCTL_DESCR("Maximum number of \"big\" pipes"),
   1490 		       NULL, 0, &maxbigpipes, 0,
   1491 		       CTL_KERN, KERN_PIPE, KERN_PIPE_MAXBIGPIPES, CTL_EOL);
   1492 	sysctl_createv(clog, 0, NULL, NULL,
   1493 		       CTLFLAG_PERMANENT,
   1494 		       CTLTYPE_INT, "nbigpipes",
   1495 		       SYSCTL_DESCR("Number of \"big\" pipes"),
   1496 		       NULL, 0, &nbigpipe, 0,
   1497 		       CTL_KERN, KERN_PIPE, KERN_PIPE_NBIGPIPES, CTL_EOL);
   1498 	sysctl_createv(clog, 0, NULL, NULL,
   1499 		       CTLFLAG_PERMANENT,
   1500 		       CTLTYPE_INT, "kvasize",
   1501 		       SYSCTL_DESCR("Amount of kernel memory consumed by pipe "
   1502 				    "buffers"),
   1503 		       NULL, 0, &amountpipekva, 0,
   1504 		       CTL_KERN, KERN_PIPE, KERN_PIPE_KVASIZE, CTL_EOL);
   1505 }
   1506