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