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