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