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