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