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