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