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