xref: /freebsd/sys/kern/sys_pipe.c (revision 11f0b352e05306cf6f1f85e9087022c0a92624a3)
1 /*
2  * Copyright (c) 1996 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Absolutely no warranty of function or purpose is made by the author
15  *    John S. Dyson.
16  * 4. Modifications may be freely made to this file if the above conditions
17  *    are met.
18  *
19  * $FreeBSD$
20  */
21 
22 /*
23  * This file contains a high-performance replacement for the socket-based
24  * pipes scheme originally used in FreeBSD/4.4Lite.  It does not support
25  * all features of sockets, but does do everything that pipes normally
26  * do.
27  */
28 
29 /*
30  * This code has two modes of operation, a small write mode and a large
31  * write mode.  The small write mode acts like conventional pipes with
32  * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
33  * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
34  * and PIPE_SIZE in size, it is fully mapped and wired into the kernel, and
35  * the receiving process can copy it directly from the pages in the sending
36  * process.
37  *
38  * If the sending process receives a signal, it is possible that it will
39  * go away, and certainly its address space can change, because control
40  * is returned back to the user-mode side.  In that case, the pipe code
41  * arranges to copy the buffer supplied by the user process, to a pageable
42  * kernel buffer, and the receiving process will grab the data from the
43  * pageable kernel buffer.  Since signals don't happen all that often,
44  * the copy operation is normally eliminated.
45  *
46  * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
47  * happen for small transfers so that the system will not spend all of
48  * its time context switching.  PIPE_SIZE is constrained by the
49  * amount of kernel virtual memory.
50  */
51 
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/fcntl.h>
55 #include <sys/file.h>
56 #include <sys/filedesc.h>
57 #include <sys/filio.h>
58 #include <sys/kernel.h>
59 #include <sys/lock.h>
60 #include <sys/mutex.h>
61 #include <sys/ttycom.h>
62 #include <sys/stat.h>
63 #include <sys/malloc.h>
64 #include <sys/poll.h>
65 #include <sys/selinfo.h>
66 #include <sys/signalvar.h>
67 #include <sys/sysproto.h>
68 #include <sys/pipe.h>
69 #include <sys/proc.h>
70 #include <sys/vnode.h>
71 #include <sys/uio.h>
72 #include <sys/event.h>
73 
74 #include <vm/vm.h>
75 #include <vm/vm_param.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_extern.h>
79 #include <vm/pmap.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/uma.h>
83 
84 /*
85  * Use this define if you want to disable *fancy* VM things.  Expect an
86  * approx 30% decrease in transfer rate.  This could be useful for
87  * NetBSD or OpenBSD.
88  */
89 /* #define PIPE_NODIRECT */
90 
91 /*
92  * interfaces to the outside world
93  */
94 static int pipe_read(struct file *fp, struct uio *uio,
95 		struct ucred *cred, int flags, struct thread *td);
96 static int pipe_write(struct file *fp, struct uio *uio,
97 		struct ucred *cred, int flags, struct thread *td);
98 static int pipe_close(struct file *fp, struct thread *td);
99 static int pipe_poll(struct file *fp, int events, struct ucred *cred,
100 		struct thread *td);
101 static int pipe_kqfilter(struct file *fp, struct knote *kn);
102 static int pipe_stat(struct file *fp, struct stat *sb, struct thread *td);
103 static int pipe_ioctl(struct file *fp, u_long cmd, void *data,
104     struct thread *td);
105 
106 static struct fileops pipeops = {
107 	pipe_read, pipe_write, pipe_ioctl, pipe_poll, pipe_kqfilter,
108 	pipe_stat, pipe_close
109 };
110 
111 static void	filt_pipedetach(struct knote *kn);
112 static int	filt_piperead(struct knote *kn, long hint);
113 static int	filt_pipewrite(struct knote *kn, long hint);
114 
115 static struct filterops pipe_rfiltops =
116 	{ 1, NULL, filt_pipedetach, filt_piperead };
117 static struct filterops pipe_wfiltops =
118 	{ 1, NULL, filt_pipedetach, filt_pipewrite };
119 
120 #define PIPE_GET_GIANT(pipe)						\
121 	do {								\
122 		KASSERT(((pipe)->pipe_state & PIPE_LOCKFL) != 0,	\
123 		    ("%s:%d PIPE_GET_GIANT: line pipe not locked",	\
124 		     __FILE__, __LINE__));				\
125 		PIPE_UNLOCK(pipe);					\
126 		mtx_lock(&Giant);					\
127 	} while (0)
128 
129 #define PIPE_DROP_GIANT(pipe)						\
130 	do {								\
131 		mtx_unlock(&Giant);					\
132 		PIPE_LOCK(pipe);					\
133 	} while (0)
134 
135 /*
136  * Default pipe buffer size(s), this can be kind-of large now because pipe
137  * space is pageable.  The pipe code will try to maintain locality of
138  * reference for performance reasons, so small amounts of outstanding I/O
139  * will not wipe the cache.
140  */
141 #define MINPIPESIZE (PIPE_SIZE/3)
142 #define MAXPIPESIZE (2*PIPE_SIZE/3)
143 
144 /*
145  * Maximum amount of kva for pipes -- this is kind-of a soft limit, but
146  * is there so that on large systems, we don't exhaust it.
147  */
148 #define MAXPIPEKVA (8*1024*1024)
149 
150 /*
151  * Limit for direct transfers, we cannot, of course limit
152  * the amount of kva for pipes in general though.
153  */
154 #define LIMITPIPEKVA (16*1024*1024)
155 
156 /*
157  * Limit the number of "big" pipes
158  */
159 #define LIMITBIGPIPES	32
160 static int nbigpipe;
161 
162 static int amountpipekva;
163 
164 static void pipeinit(void *dummy __unused);
165 static void pipeclose(struct pipe *cpipe);
166 static void pipe_free_kmem(struct pipe *cpipe);
167 static int pipe_create(struct pipe **cpipep);
168 static __inline int pipelock(struct pipe *cpipe, int catch);
169 static __inline void pipeunlock(struct pipe *cpipe);
170 static __inline void pipeselwakeup(struct pipe *cpipe);
171 #ifndef PIPE_NODIRECT
172 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
173 static void pipe_destroy_write_buffer(struct pipe *wpipe);
174 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
175 static void pipe_clone_write_buffer(struct pipe *wpipe);
176 #endif
177 static int pipespace(struct pipe *cpipe, int size);
178 
179 static uma_zone_t pipe_zone;
180 
181 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
182 
183 static void
184 pipeinit(void *dummy __unused)
185 {
186 	pipe_zone = uma_zcreate("PIPE", sizeof(struct pipe), NULL,
187 	    NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
188 }
189 
190 /*
191  * The pipe system call for the DTYPE_PIPE type of pipes
192  */
193 
194 /* ARGSUSED */
195 int
196 pipe(td, uap)
197 	struct thread *td;
198 	struct pipe_args /* {
199 		int	dummy;
200 	} */ *uap;
201 {
202 	struct filedesc *fdp = td->td_proc->p_fd;
203 	struct file *rf, *wf;
204 	struct pipe *rpipe, *wpipe;
205 	struct mtx *pmtx;
206 	int fd, error;
207 
208 	KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
209 
210 	pmtx = malloc(sizeof(*pmtx), M_TEMP, M_WAITOK | M_ZERO);
211 
212 	rpipe = wpipe = NULL;
213 	if (pipe_create(&rpipe) || pipe_create(&wpipe)) {
214 		pipeclose(rpipe);
215 		pipeclose(wpipe);
216 		free(pmtx, M_TEMP);
217 		return (ENFILE);
218 	}
219 
220 	rpipe->pipe_state |= PIPE_DIRECTOK;
221 	wpipe->pipe_state |= PIPE_DIRECTOK;
222 
223 	error = falloc(td, &rf, &fd);
224 	if (error) {
225 		pipeclose(rpipe);
226 		pipeclose(wpipe);
227 		free(pmtx, M_TEMP);
228 		return (error);
229 	}
230 	fhold(rf);
231 	td->td_retval[0] = fd;
232 
233 	/*
234 	 * Warning: once we've gotten past allocation of the fd for the
235 	 * read-side, we can only drop the read side via fdrop() in order
236 	 * to avoid races against processes which manage to dup() the read
237 	 * side while we are blocked trying to allocate the write side.
238 	 */
239 	FILE_LOCK(rf);
240 	rf->f_flag = FREAD | FWRITE;
241 	rf->f_type = DTYPE_PIPE;
242 	rf->f_data = (caddr_t)rpipe;
243 	rf->f_ops = &pipeops;
244 	FILE_UNLOCK(rf);
245 	error = falloc(td, &wf, &fd);
246 	if (error) {
247 		FILEDESC_LOCK(fdp);
248 		if (fdp->fd_ofiles[td->td_retval[0]] == rf) {
249 			fdp->fd_ofiles[td->td_retval[0]] = NULL;
250 			FILEDESC_UNLOCK(fdp);
251 			fdrop(rf, td);
252 		} else
253 			FILEDESC_UNLOCK(fdp);
254 		fdrop(rf, td);
255 		/* rpipe has been closed by fdrop(). */
256 		pipeclose(wpipe);
257 		free(pmtx, M_TEMP);
258 		return (error);
259 	}
260 	FILE_LOCK(wf);
261 	wf->f_flag = FREAD | FWRITE;
262 	wf->f_type = DTYPE_PIPE;
263 	wf->f_data = (caddr_t)wpipe;
264 	wf->f_ops = &pipeops;
265 	FILE_UNLOCK(wf);
266 	td->td_retval[1] = fd;
267 	rpipe->pipe_peer = wpipe;
268 	wpipe->pipe_peer = rpipe;
269 	mtx_init(pmtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
270 	rpipe->pipe_mtxp = wpipe->pipe_mtxp = pmtx;
271 	fdrop(rf, td);
272 
273 	return (0);
274 }
275 
276 /*
277  * Allocate kva for pipe circular buffer, the space is pageable
278  * This routine will 'realloc' the size of a pipe safely, if it fails
279  * it will retain the old buffer.
280  * If it fails it will return ENOMEM.
281  */
282 static int
283 pipespace(cpipe, size)
284 	struct pipe *cpipe;
285 	int size;
286 {
287 	struct vm_object *object;
288 	caddr_t buffer;
289 	int npages, error;
290 
291 	GIANT_REQUIRED;
292 	KASSERT(cpipe->pipe_mtxp == NULL || !mtx_owned(PIPE_MTX(cpipe)),
293 	       ("pipespace: pipe mutex locked"));
294 
295 	npages = round_page(size)/PAGE_SIZE;
296 	/*
297 	 * Create an object, I don't like the idea of paging to/from
298 	 * kernel_object.
299 	 * XXX -- minor change needed here for NetBSD/OpenBSD VM systems.
300 	 */
301 	object = vm_object_allocate(OBJT_DEFAULT, npages);
302 	buffer = (caddr_t) vm_map_min(kernel_map);
303 
304 	/*
305 	 * Insert the object into the kernel map, and allocate kva for it.
306 	 * The map entry is, by default, pageable.
307 	 * XXX -- minor change needed here for NetBSD/OpenBSD VM systems.
308 	 */
309 	error = vm_map_find(kernel_map, object, 0,
310 		(vm_offset_t *) &buffer, size, 1,
311 		VM_PROT_ALL, VM_PROT_ALL, 0);
312 
313 	if (error != KERN_SUCCESS) {
314 		vm_object_deallocate(object);
315 		return (ENOMEM);
316 	}
317 
318 	/* free old resources if we're resizing */
319 	pipe_free_kmem(cpipe);
320 	cpipe->pipe_buffer.object = object;
321 	cpipe->pipe_buffer.buffer = buffer;
322 	cpipe->pipe_buffer.size = size;
323 	cpipe->pipe_buffer.in = 0;
324 	cpipe->pipe_buffer.out = 0;
325 	cpipe->pipe_buffer.cnt = 0;
326 	amountpipekva += cpipe->pipe_buffer.size;
327 	return (0);
328 }
329 
330 /*
331  * initialize and allocate VM and memory for pipe
332  */
333 static int
334 pipe_create(cpipep)
335 	struct pipe **cpipep;
336 {
337 	struct pipe *cpipe;
338 	int error;
339 
340 	*cpipep = uma_zalloc(pipe_zone, M_WAITOK);
341 	if (*cpipep == NULL)
342 		return (ENOMEM);
343 
344 	cpipe = *cpipep;
345 
346 	/* so pipespace()->pipe_free_kmem() doesn't follow junk pointer */
347 	cpipe->pipe_buffer.object = NULL;
348 #ifndef PIPE_NODIRECT
349 	cpipe->pipe_map.kva = NULL;
350 #endif
351 	/*
352 	 * protect so pipeclose() doesn't follow a junk pointer
353 	 * if pipespace() fails.
354 	 */
355 	bzero(&cpipe->pipe_sel, sizeof(cpipe->pipe_sel));
356 	cpipe->pipe_state = 0;
357 	cpipe->pipe_peer = NULL;
358 	cpipe->pipe_busy = 0;
359 
360 #ifndef PIPE_NODIRECT
361 	/*
362 	 * pipe data structure initializations to support direct pipe I/O
363 	 */
364 	cpipe->pipe_map.cnt = 0;
365 	cpipe->pipe_map.kva = 0;
366 	cpipe->pipe_map.pos = 0;
367 	cpipe->pipe_map.npages = 0;
368 	/* cpipe->pipe_map.ms[] = invalid */
369 #endif
370 
371 	cpipe->pipe_mtxp = NULL;	/* avoid pipespace assertion */
372 	error = pipespace(cpipe, PIPE_SIZE);
373 	if (error)
374 		return (error);
375 
376 	vfs_timestamp(&cpipe->pipe_ctime);
377 	cpipe->pipe_atime = cpipe->pipe_ctime;
378 	cpipe->pipe_mtime = cpipe->pipe_ctime;
379 
380 	return (0);
381 }
382 
383 
384 /*
385  * lock a pipe for I/O, blocking other access
386  */
387 static __inline int
388 pipelock(cpipe, catch)
389 	struct pipe *cpipe;
390 	int catch;
391 {
392 	int error;
393 
394 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
395 	while (cpipe->pipe_state & PIPE_LOCKFL) {
396 		cpipe->pipe_state |= PIPE_LWANT;
397 		error = msleep(cpipe, PIPE_MTX(cpipe),
398 		    catch ? (PRIBIO | PCATCH) : PRIBIO,
399 		    "pipelk", 0);
400 		if (error != 0)
401 			return (error);
402 	}
403 	cpipe->pipe_state |= PIPE_LOCKFL;
404 	return (0);
405 }
406 
407 /*
408  * unlock a pipe I/O lock
409  */
410 static __inline void
411 pipeunlock(cpipe)
412 	struct pipe *cpipe;
413 {
414 
415 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
416 	cpipe->pipe_state &= ~PIPE_LOCKFL;
417 	if (cpipe->pipe_state & PIPE_LWANT) {
418 		cpipe->pipe_state &= ~PIPE_LWANT;
419 		wakeup(cpipe);
420 	}
421 }
422 
423 static __inline void
424 pipeselwakeup(cpipe)
425 	struct pipe *cpipe;
426 {
427 
428 	if (cpipe->pipe_state & PIPE_SEL) {
429 		cpipe->pipe_state &= ~PIPE_SEL;
430 		selwakeup(&cpipe->pipe_sel);
431 	}
432 	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
433 		pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
434 	KNOTE(&cpipe->pipe_sel.si_note, 0);
435 }
436 
437 /* ARGSUSED */
438 static int
439 pipe_read(fp, uio, cred, flags, td)
440 	struct file *fp;
441 	struct uio *uio;
442 	struct ucred *cred;
443 	struct thread *td;
444 	int flags;
445 {
446 	struct pipe *rpipe = (struct pipe *) fp->f_data;
447 	int error;
448 	int nread = 0;
449 	u_int size;
450 
451 	PIPE_LOCK(rpipe);
452 	++rpipe->pipe_busy;
453 	error = pipelock(rpipe, 1);
454 	if (error)
455 		goto unlocked_error;
456 
457 	while (uio->uio_resid) {
458 		/*
459 		 * normal pipe buffer receive
460 		 */
461 		if (rpipe->pipe_buffer.cnt > 0) {
462 			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
463 			if (size > rpipe->pipe_buffer.cnt)
464 				size = rpipe->pipe_buffer.cnt;
465 			if (size > (u_int) uio->uio_resid)
466 				size = (u_int) uio->uio_resid;
467 
468 			PIPE_UNLOCK(rpipe);
469 			error = uiomove(&rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
470 					size, uio);
471 			PIPE_LOCK(rpipe);
472 			if (error)
473 				break;
474 
475 			rpipe->pipe_buffer.out += size;
476 			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
477 				rpipe->pipe_buffer.out = 0;
478 
479 			rpipe->pipe_buffer.cnt -= size;
480 
481 			/*
482 			 * If there is no more to read in the pipe, reset
483 			 * its pointers to the beginning.  This improves
484 			 * cache hit stats.
485 			 */
486 			if (rpipe->pipe_buffer.cnt == 0) {
487 				rpipe->pipe_buffer.in = 0;
488 				rpipe->pipe_buffer.out = 0;
489 			}
490 			nread += size;
491 #ifndef PIPE_NODIRECT
492 		/*
493 		 * Direct copy, bypassing a kernel buffer.
494 		 */
495 		} else if ((size = rpipe->pipe_map.cnt) &&
496 			   (rpipe->pipe_state & PIPE_DIRECTW)) {
497 			caddr_t	va;
498 			if (size > (u_int) uio->uio_resid)
499 				size = (u_int) uio->uio_resid;
500 
501 			va = (caddr_t) rpipe->pipe_map.kva +
502 			    rpipe->pipe_map.pos;
503 			PIPE_UNLOCK(rpipe);
504 			error = uiomove(va, size, uio);
505 			PIPE_LOCK(rpipe);
506 			if (error)
507 				break;
508 			nread += size;
509 			rpipe->pipe_map.pos += size;
510 			rpipe->pipe_map.cnt -= size;
511 			if (rpipe->pipe_map.cnt == 0) {
512 				rpipe->pipe_state &= ~PIPE_DIRECTW;
513 				wakeup(rpipe);
514 			}
515 #endif
516 		} else {
517 			/*
518 			 * detect EOF condition
519 			 * read returns 0 on EOF, no need to set error
520 			 */
521 			if (rpipe->pipe_state & PIPE_EOF)
522 				break;
523 
524 			/*
525 			 * If the "write-side" has been blocked, wake it up now.
526 			 */
527 			if (rpipe->pipe_state & PIPE_WANTW) {
528 				rpipe->pipe_state &= ~PIPE_WANTW;
529 				wakeup(rpipe);
530 			}
531 
532 			/*
533 			 * Break if some data was read.
534 			 */
535 			if (nread > 0)
536 				break;
537 
538 			/*
539 			 * Unlock the pipe buffer for our remaining processing.  We
540 			 * will either break out with an error or we will sleep and
541 			 * relock to loop.
542 			 */
543 			pipeunlock(rpipe);
544 
545 			/*
546 			 * Handle non-blocking mode operation or
547 			 * wait for more data.
548 			 */
549 			if (fp->f_flag & FNONBLOCK) {
550 				error = EAGAIN;
551 			} else {
552 				rpipe->pipe_state |= PIPE_WANTR;
553 				if ((error = msleep(rpipe, PIPE_MTX(rpipe),
554 				    PRIBIO | PCATCH,
555 				    "piperd", 0)) == 0)
556 					error = pipelock(rpipe, 1);
557 			}
558 			if (error)
559 				goto unlocked_error;
560 		}
561 	}
562 	pipeunlock(rpipe);
563 
564 	/* XXX: should probably do this before getting any locks. */
565 	if (error == 0)
566 		vfs_timestamp(&rpipe->pipe_atime);
567 unlocked_error:
568 	--rpipe->pipe_busy;
569 
570 	/*
571 	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
572 	 */
573 	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
574 		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
575 		wakeup(rpipe);
576 	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
577 		/*
578 		 * Handle write blocking hysteresis.
579 		 */
580 		if (rpipe->pipe_state & PIPE_WANTW) {
581 			rpipe->pipe_state &= ~PIPE_WANTW;
582 			wakeup(rpipe);
583 		}
584 	}
585 
586 	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
587 		pipeselwakeup(rpipe);
588 
589 	PIPE_UNLOCK(rpipe);
590 	return (error);
591 }
592 
593 #ifndef PIPE_NODIRECT
594 /*
595  * Map the sending processes' buffer into kernel space and wire it.
596  * This is similar to a physical write operation.
597  */
598 static int
599 pipe_build_write_buffer(wpipe, uio)
600 	struct pipe *wpipe;
601 	struct uio *uio;
602 {
603 	u_int size;
604 	int i;
605 	vm_offset_t addr, endaddr, paddr;
606 
607 	GIANT_REQUIRED;
608 	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
609 
610 	size = (u_int) uio->uio_iov->iov_len;
611 	if (size > wpipe->pipe_buffer.size)
612 		size = wpipe->pipe_buffer.size;
613 
614 	endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
615 	addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
616 	for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
617 		vm_page_t m;
618 
619 		if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0 ||
620 		    (paddr = pmap_extract(vmspace_pmap(curproc->p_vmspace),
621 		     addr)) == 0) {
622 			int j;
623 
624 			for (j = 0; j < i; j++)
625 				vm_page_unwire(wpipe->pipe_map.ms[j], 1);
626 			return (EFAULT);
627 		}
628 
629 		m = PHYS_TO_VM_PAGE(paddr);
630 		vm_page_wire(m);
631 		wpipe->pipe_map.ms[i] = m;
632 	}
633 
634 /*
635  * set up the control block
636  */
637 	wpipe->pipe_map.npages = i;
638 	wpipe->pipe_map.pos =
639 	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
640 	wpipe->pipe_map.cnt = size;
641 
642 /*
643  * and map the buffer
644  */
645 	if (wpipe->pipe_map.kva == 0) {
646 		/*
647 		 * We need to allocate space for an extra page because the
648 		 * address range might (will) span pages at times.
649 		 */
650 		wpipe->pipe_map.kva = kmem_alloc_pageable(kernel_map,
651 			wpipe->pipe_buffer.size + PAGE_SIZE);
652 		amountpipekva += wpipe->pipe_buffer.size + PAGE_SIZE;
653 	}
654 	pmap_qenter(wpipe->pipe_map.kva, wpipe->pipe_map.ms,
655 		wpipe->pipe_map.npages);
656 
657 /*
658  * and update the uio data
659  */
660 
661 	uio->uio_iov->iov_len -= size;
662 	uio->uio_iov->iov_base += size;
663 	if (uio->uio_iov->iov_len == 0)
664 		uio->uio_iov++;
665 	uio->uio_resid -= size;
666 	uio->uio_offset += size;
667 	return (0);
668 }
669 
670 /*
671  * unmap and unwire the process buffer
672  */
673 static void
674 pipe_destroy_write_buffer(wpipe)
675 	struct pipe *wpipe;
676 {
677 	int i;
678 
679 	GIANT_REQUIRED;
680 	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
681 
682 	if (wpipe->pipe_map.kva) {
683 		pmap_qremove(wpipe->pipe_map.kva, wpipe->pipe_map.npages);
684 
685 		if (amountpipekva > MAXPIPEKVA) {
686 			vm_offset_t kva = wpipe->pipe_map.kva;
687 			wpipe->pipe_map.kva = 0;
688 			kmem_free(kernel_map, kva,
689 				wpipe->pipe_buffer.size + PAGE_SIZE);
690 			amountpipekva -= wpipe->pipe_buffer.size + PAGE_SIZE;
691 		}
692 	}
693 	for (i = 0; i < wpipe->pipe_map.npages; i++)
694 		vm_page_unwire(wpipe->pipe_map.ms[i], 1);
695 	wpipe->pipe_map.npages = 0;
696 }
697 
698 /*
699  * In the case of a signal, the writing process might go away.  This
700  * code copies the data into the circular buffer so that the source
701  * pages can be freed without loss of data.
702  */
703 static void
704 pipe_clone_write_buffer(wpipe)
705 	struct pipe *wpipe;
706 {
707 	int size;
708 	int pos;
709 
710 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
711 	size = wpipe->pipe_map.cnt;
712 	pos = wpipe->pipe_map.pos;
713 
714 	wpipe->pipe_buffer.in = size;
715 	wpipe->pipe_buffer.out = 0;
716 	wpipe->pipe_buffer.cnt = size;
717 	wpipe->pipe_state &= ~PIPE_DIRECTW;
718 
719 	PIPE_GET_GIANT(wpipe);
720 	bcopy((caddr_t) wpipe->pipe_map.kva + pos,
721 	    (caddr_t) wpipe->pipe_buffer.buffer, size);
722 	pipe_destroy_write_buffer(wpipe);
723 	PIPE_DROP_GIANT(wpipe);
724 }
725 
726 /*
727  * This implements the pipe buffer write mechanism.  Note that only
728  * a direct write OR a normal pipe write can be pending at any given time.
729  * If there are any characters in the pipe buffer, the direct write will
730  * be deferred until the receiving process grabs all of the bytes from
731  * the pipe buffer.  Then the direct mapping write is set-up.
732  */
733 static int
734 pipe_direct_write(wpipe, uio)
735 	struct pipe *wpipe;
736 	struct uio *uio;
737 {
738 	int error;
739 
740 retry:
741 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
742 	while (wpipe->pipe_state & PIPE_DIRECTW) {
743 		if (wpipe->pipe_state & PIPE_WANTR) {
744 			wpipe->pipe_state &= ~PIPE_WANTR;
745 			wakeup(wpipe);
746 		}
747 		wpipe->pipe_state |= PIPE_WANTW;
748 		error = msleep(wpipe, PIPE_MTX(wpipe),
749 		    PRIBIO | PCATCH, "pipdww", 0);
750 		if (error)
751 			goto error1;
752 		if (wpipe->pipe_state & PIPE_EOF) {
753 			error = EPIPE;
754 			goto error1;
755 		}
756 	}
757 	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
758 	if (wpipe->pipe_buffer.cnt > 0) {
759 		if (wpipe->pipe_state & PIPE_WANTR) {
760 			wpipe->pipe_state &= ~PIPE_WANTR;
761 			wakeup(wpipe);
762 		}
763 
764 		wpipe->pipe_state |= PIPE_WANTW;
765 		error = msleep(wpipe, PIPE_MTX(wpipe),
766 		    PRIBIO | PCATCH, "pipdwc", 0);
767 		if (error)
768 			goto error1;
769 		if (wpipe->pipe_state & PIPE_EOF) {
770 			error = EPIPE;
771 			goto error1;
772 		}
773 		goto retry;
774 	}
775 
776 	wpipe->pipe_state |= PIPE_DIRECTW;
777 
778 	pipelock(wpipe, 0);
779 	PIPE_GET_GIANT(wpipe);
780 	error = pipe_build_write_buffer(wpipe, uio);
781 	PIPE_DROP_GIANT(wpipe);
782 	pipeunlock(wpipe);
783 	if (error) {
784 		wpipe->pipe_state &= ~PIPE_DIRECTW;
785 		goto error1;
786 	}
787 
788 	error = 0;
789 	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
790 		if (wpipe->pipe_state & PIPE_EOF) {
791 			pipelock(wpipe, 0);
792 			PIPE_GET_GIANT(wpipe);
793 			pipe_destroy_write_buffer(wpipe);
794 			PIPE_DROP_GIANT(wpipe);
795 			pipeunlock(wpipe);
796 			pipeselwakeup(wpipe);
797 			error = EPIPE;
798 			goto error1;
799 		}
800 		if (wpipe->pipe_state & PIPE_WANTR) {
801 			wpipe->pipe_state &= ~PIPE_WANTR;
802 			wakeup(wpipe);
803 		}
804 		pipeselwakeup(wpipe);
805 		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
806 		    "pipdwt", 0);
807 	}
808 
809 	pipelock(wpipe,0);
810 	if (wpipe->pipe_state & PIPE_DIRECTW) {
811 		/*
812 		 * this bit of trickery substitutes a kernel buffer for
813 		 * the process that might be going away.
814 		 */
815 		pipe_clone_write_buffer(wpipe);
816 	} else {
817 		PIPE_GET_GIANT(wpipe);
818 		pipe_destroy_write_buffer(wpipe);
819 		PIPE_DROP_GIANT(wpipe);
820 	}
821 	pipeunlock(wpipe);
822 	return (error);
823 
824 error1:
825 	wakeup(wpipe);
826 	return (error);
827 }
828 #endif
829 
830 static int
831 pipe_write(fp, uio, cred, flags, td)
832 	struct file *fp;
833 	struct uio *uio;
834 	struct ucred *cred;
835 	struct thread *td;
836 	int flags;
837 {
838 	int error = 0;
839 	int orig_resid;
840 	struct pipe *wpipe, *rpipe;
841 
842 	rpipe = (struct pipe *) fp->f_data;
843 	wpipe = rpipe->pipe_peer;
844 
845 	PIPE_LOCK(rpipe);
846 	/*
847 	 * detect loss of pipe read side, issue SIGPIPE if lost.
848 	 */
849 	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
850 		PIPE_UNLOCK(rpipe);
851 		return (EPIPE);
852 	}
853 	++wpipe->pipe_busy;
854 
855 	/*
856 	 * If it is advantageous to resize the pipe buffer, do
857 	 * so.
858 	 */
859 	if ((uio->uio_resid > PIPE_SIZE) &&
860 		(nbigpipe < LIMITBIGPIPES) &&
861 		(wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
862 		(wpipe->pipe_buffer.size <= PIPE_SIZE) &&
863 		(wpipe->pipe_buffer.cnt == 0)) {
864 
865 		if ((error = pipelock(wpipe,1)) == 0) {
866 			PIPE_GET_GIANT(wpipe);
867 			if (pipespace(wpipe, BIG_PIPE_SIZE) == 0)
868 				nbigpipe++;
869 			PIPE_DROP_GIANT(wpipe);
870 			pipeunlock(wpipe);
871 		}
872 	}
873 
874 	/*
875 	 * If an early error occured unbusy and return, waking up any pending
876 	 * readers.
877 	 */
878 	if (error) {
879 		--wpipe->pipe_busy;
880 		if ((wpipe->pipe_busy == 0) &&
881 		    (wpipe->pipe_state & PIPE_WANT)) {
882 			wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
883 			wakeup(wpipe);
884 		}
885 		PIPE_UNLOCK(rpipe);
886 		return(error);
887 	}
888 
889 	KASSERT(wpipe->pipe_buffer.buffer != NULL, ("pipe buffer gone"));
890 
891 	orig_resid = uio->uio_resid;
892 
893 	while (uio->uio_resid) {
894 		int space;
895 
896 #ifndef PIPE_NODIRECT
897 		/*
898 		 * If the transfer is large, we can gain performance if
899 		 * we do process-to-process copies directly.
900 		 * If the write is non-blocking, we don't use the
901 		 * direct write mechanism.
902 		 *
903 		 * The direct write mechanism will detect the reader going
904 		 * away on us.
905 		 */
906 		if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT) &&
907 		    (fp->f_flag & FNONBLOCK) == 0 &&
908 			(wpipe->pipe_map.kva || (amountpipekva < LIMITPIPEKVA)) &&
909 			(uio->uio_iov->iov_len >= PIPE_MINDIRECT)) {
910 			error = pipe_direct_write( wpipe, uio);
911 			if (error)
912 				break;
913 			continue;
914 		}
915 #endif
916 
917 		/*
918 		 * Pipe buffered writes cannot be coincidental with
919 		 * direct writes.  We wait until the currently executing
920 		 * direct write is completed before we start filling the
921 		 * pipe buffer.  We break out if a signal occurs or the
922 		 * reader goes away.
923 		 */
924 	retrywrite:
925 		while (wpipe->pipe_state & PIPE_DIRECTW) {
926 			if (wpipe->pipe_state & PIPE_WANTR) {
927 				wpipe->pipe_state &= ~PIPE_WANTR;
928 				wakeup(wpipe);
929 			}
930 			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
931 			    "pipbww", 0);
932 			if (wpipe->pipe_state & PIPE_EOF)
933 				break;
934 			if (error)
935 				break;
936 		}
937 		if (wpipe->pipe_state & PIPE_EOF) {
938 			error = EPIPE;
939 			break;
940 		}
941 
942 		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
943 
944 		/* Writes of size <= PIPE_BUF must be atomic. */
945 		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
946 			space = 0;
947 
948 		if (space > 0 && (wpipe->pipe_buffer.cnt < PIPE_SIZE)) {
949 			if ((error = pipelock(wpipe,1)) == 0) {
950 				int size;	/* Transfer size */
951 				int segsize;	/* first segment to transfer */
952 
953 				/*
954 				 * It is possible for a direct write to
955 				 * slip in on us... handle it here...
956 				 */
957 				if (wpipe->pipe_state & PIPE_DIRECTW) {
958 					pipeunlock(wpipe);
959 					goto retrywrite;
960 				}
961 				/*
962 				 * If a process blocked in uiomove, our
963 				 * value for space might be bad.
964 				 *
965 				 * XXX will we be ok if the reader has gone
966 				 * away here?
967 				 */
968 				if (space > wpipe->pipe_buffer.size -
969 				    wpipe->pipe_buffer.cnt) {
970 					pipeunlock(wpipe);
971 					goto retrywrite;
972 				}
973 
974 				/*
975 				 * Transfer size is minimum of uio transfer
976 				 * and free space in pipe buffer.
977 				 */
978 				if (space > uio->uio_resid)
979 					size = uio->uio_resid;
980 				else
981 					size = space;
982 				/*
983 				 * First segment to transfer is minimum of
984 				 * transfer size and contiguous space in
985 				 * pipe buffer.  If first segment to transfer
986 				 * is less than the transfer size, we've got
987 				 * a wraparound in the buffer.
988 				 */
989 				segsize = wpipe->pipe_buffer.size -
990 					wpipe->pipe_buffer.in;
991 				if (segsize > size)
992 					segsize = size;
993 
994 				/* Transfer first segment */
995 
996 				PIPE_UNLOCK(rpipe);
997 				error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
998 						segsize, uio);
999 				PIPE_LOCK(rpipe);
1000 
1001 				if (error == 0 && segsize < size) {
1002 					/*
1003 					 * Transfer remaining part now, to
1004 					 * support atomic writes.  Wraparound
1005 					 * happened.
1006 					 */
1007 					if (wpipe->pipe_buffer.in + segsize !=
1008 					    wpipe->pipe_buffer.size)
1009 						panic("Expected pipe buffer wraparound disappeared");
1010 
1011 					PIPE_UNLOCK(rpipe);
1012 					error = uiomove(&wpipe->pipe_buffer.buffer[0],
1013 							size - segsize, uio);
1014 					PIPE_LOCK(rpipe);
1015 				}
1016 				if (error == 0) {
1017 					wpipe->pipe_buffer.in += size;
1018 					if (wpipe->pipe_buffer.in >=
1019 					    wpipe->pipe_buffer.size) {
1020 						if (wpipe->pipe_buffer.in != size - segsize + wpipe->pipe_buffer.size)
1021 							panic("Expected wraparound bad");
1022 						wpipe->pipe_buffer.in = size - segsize;
1023 					}
1024 
1025 					wpipe->pipe_buffer.cnt += size;
1026 					if (wpipe->pipe_buffer.cnt > wpipe->pipe_buffer.size)
1027 						panic("Pipe buffer overflow");
1028 
1029 				}
1030 				pipeunlock(wpipe);
1031 			}
1032 			if (error)
1033 				break;
1034 
1035 		} else {
1036 			/*
1037 			 * If the "read-side" has been blocked, wake it up now.
1038 			 */
1039 			if (wpipe->pipe_state & PIPE_WANTR) {
1040 				wpipe->pipe_state &= ~PIPE_WANTR;
1041 				wakeup(wpipe);
1042 			}
1043 
1044 			/*
1045 			 * don't block on non-blocking I/O
1046 			 */
1047 			if (fp->f_flag & FNONBLOCK) {
1048 				error = EAGAIN;
1049 				break;
1050 			}
1051 
1052 			/*
1053 			 * We have no more space and have something to offer,
1054 			 * wake up select/poll.
1055 			 */
1056 			pipeselwakeup(wpipe);
1057 
1058 			wpipe->pipe_state |= PIPE_WANTW;
1059 			error = msleep(wpipe, PIPE_MTX(rpipe),
1060 			    PRIBIO | PCATCH, "pipewr", 0);
1061 			if (error != 0)
1062 				break;
1063 			/*
1064 			 * If read side wants to go away, we just issue a signal
1065 			 * to ourselves.
1066 			 */
1067 			if (wpipe->pipe_state & PIPE_EOF) {
1068 				error = EPIPE;
1069 				break;
1070 			}
1071 		}
1072 	}
1073 
1074 	--wpipe->pipe_busy;
1075 
1076 	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1077 		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1078 		wakeup(wpipe);
1079 	} else if (wpipe->pipe_buffer.cnt > 0) {
1080 		/*
1081 		 * If we have put any characters in the buffer, we wake up
1082 		 * the reader.
1083 		 */
1084 		if (wpipe->pipe_state & PIPE_WANTR) {
1085 			wpipe->pipe_state &= ~PIPE_WANTR;
1086 			wakeup(wpipe);
1087 		}
1088 	}
1089 
1090 	/*
1091 	 * Don't return EPIPE if I/O was successful
1092 	 */
1093 	if ((wpipe->pipe_buffer.cnt == 0) &&
1094 	    (uio->uio_resid == 0) &&
1095 	    (error == EPIPE)) {
1096 		error = 0;
1097 	}
1098 
1099 	if (error == 0)
1100 		vfs_timestamp(&wpipe->pipe_mtime);
1101 
1102 	/*
1103 	 * We have something to offer,
1104 	 * wake up select/poll.
1105 	 */
1106 	if (wpipe->pipe_buffer.cnt)
1107 		pipeselwakeup(wpipe);
1108 
1109 	PIPE_UNLOCK(rpipe);
1110 	return (error);
1111 }
1112 
1113 /*
1114  * we implement a very minimal set of ioctls for compatibility with sockets.
1115  */
1116 int
1117 pipe_ioctl(fp, cmd, data, td)
1118 	struct file *fp;
1119 	u_long cmd;
1120 	void *data;
1121 	struct thread *td;
1122 {
1123 	struct pipe *mpipe = (struct pipe *)fp->f_data;
1124 
1125 	switch (cmd) {
1126 
1127 	case FIONBIO:
1128 		return (0);
1129 
1130 	case FIOASYNC:
1131 		PIPE_LOCK(mpipe);
1132 		if (*(int *)data) {
1133 			mpipe->pipe_state |= PIPE_ASYNC;
1134 		} else {
1135 			mpipe->pipe_state &= ~PIPE_ASYNC;
1136 		}
1137 		PIPE_UNLOCK(mpipe);
1138 		return (0);
1139 
1140 	case FIONREAD:
1141 		PIPE_LOCK(mpipe);
1142 		if (mpipe->pipe_state & PIPE_DIRECTW)
1143 			*(int *)data = mpipe->pipe_map.cnt;
1144 		else
1145 			*(int *)data = mpipe->pipe_buffer.cnt;
1146 		PIPE_UNLOCK(mpipe);
1147 		return (0);
1148 
1149 	case FIOSETOWN:
1150 		return (fsetown(*(int *)data, &mpipe->pipe_sigio));
1151 
1152 	case FIOGETOWN:
1153 		*(int *)data = fgetown(mpipe->pipe_sigio);
1154 		return (0);
1155 
1156 	/* This is deprecated, FIOSETOWN should be used instead. */
1157 	case TIOCSPGRP:
1158 		return (fsetown(-(*(int *)data), &mpipe->pipe_sigio));
1159 
1160 	/* This is deprecated, FIOGETOWN should be used instead. */
1161 	case TIOCGPGRP:
1162 		*(int *)data = -fgetown(mpipe->pipe_sigio);
1163 		return (0);
1164 
1165 	}
1166 	return (ENOTTY);
1167 }
1168 
1169 int
1170 pipe_poll(fp, events, cred, td)
1171 	struct file *fp;
1172 	int events;
1173 	struct ucred *cred;
1174 	struct thread *td;
1175 {
1176 	struct pipe *rpipe = (struct pipe *)fp->f_data;
1177 	struct pipe *wpipe;
1178 	int revents = 0;
1179 
1180 	wpipe = rpipe->pipe_peer;
1181 	PIPE_LOCK(rpipe);
1182 	if (events & (POLLIN | POLLRDNORM))
1183 		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1184 		    (rpipe->pipe_buffer.cnt > 0) ||
1185 		    (rpipe->pipe_state & PIPE_EOF))
1186 			revents |= events & (POLLIN | POLLRDNORM);
1187 
1188 	if (events & (POLLOUT | POLLWRNORM))
1189 		if (wpipe == NULL || (wpipe->pipe_state & PIPE_EOF) ||
1190 		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1191 		     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1192 			revents |= events & (POLLOUT | POLLWRNORM);
1193 
1194 	if ((rpipe->pipe_state & PIPE_EOF) ||
1195 	    (wpipe == NULL) ||
1196 	    (wpipe->pipe_state & PIPE_EOF))
1197 		revents |= POLLHUP;
1198 
1199 	if (revents == 0) {
1200 		if (events & (POLLIN | POLLRDNORM)) {
1201 			selrecord(td, &rpipe->pipe_sel);
1202 			rpipe->pipe_state |= PIPE_SEL;
1203 		}
1204 
1205 		if (events & (POLLOUT | POLLWRNORM)) {
1206 			selrecord(td, &wpipe->pipe_sel);
1207 			wpipe->pipe_state |= PIPE_SEL;
1208 		}
1209 	}
1210 	PIPE_UNLOCK(rpipe);
1211 
1212 	return (revents);
1213 }
1214 
1215 /*
1216  * We shouldn't need locks here as we're doing a read and this should
1217  * be a natural race.
1218  */
1219 static int
1220 pipe_stat(fp, ub, td)
1221 	struct file *fp;
1222 	struct stat *ub;
1223 	struct thread *td;
1224 {
1225 	struct pipe *pipe = (struct pipe *)fp->f_data;
1226 
1227 	bzero((caddr_t)ub, sizeof(*ub));
1228 	ub->st_mode = S_IFIFO;
1229 	ub->st_blksize = pipe->pipe_buffer.size;
1230 	ub->st_size = pipe->pipe_buffer.cnt;
1231 	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1232 	ub->st_atimespec = pipe->pipe_atime;
1233 	ub->st_mtimespec = pipe->pipe_mtime;
1234 	ub->st_ctimespec = pipe->pipe_ctime;
1235 	ub->st_uid = fp->f_cred->cr_uid;
1236 	ub->st_gid = fp->f_cred->cr_gid;
1237 	/*
1238 	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1239 	 * XXX (st_dev, st_ino) should be unique.
1240 	 */
1241 	return (0);
1242 }
1243 
1244 /* ARGSUSED */
1245 static int
1246 pipe_close(fp, td)
1247 	struct file *fp;
1248 	struct thread *td;
1249 {
1250 	struct pipe *cpipe = (struct pipe *)fp->f_data;
1251 
1252 	fp->f_ops = &badfileops;
1253 	fp->f_data = NULL;
1254 	funsetown(&cpipe->pipe_sigio);
1255 	pipeclose(cpipe);
1256 	return (0);
1257 }
1258 
1259 static void
1260 pipe_free_kmem(cpipe)
1261 	struct pipe *cpipe;
1262 {
1263 
1264 	GIANT_REQUIRED;
1265 	KASSERT(cpipe->pipe_mtxp == NULL || !mtx_owned(PIPE_MTX(cpipe)),
1266 	       ("pipespace: pipe mutex locked"));
1267 
1268 	if (cpipe->pipe_buffer.buffer != NULL) {
1269 		if (cpipe->pipe_buffer.size > PIPE_SIZE)
1270 			--nbigpipe;
1271 		amountpipekva -= cpipe->pipe_buffer.size;
1272 		kmem_free(kernel_map,
1273 			(vm_offset_t)cpipe->pipe_buffer.buffer,
1274 			cpipe->pipe_buffer.size);
1275 		cpipe->pipe_buffer.buffer = NULL;
1276 	}
1277 #ifndef PIPE_NODIRECT
1278 	if (cpipe->pipe_map.kva != NULL) {
1279 		amountpipekva -= cpipe->pipe_buffer.size + PAGE_SIZE;
1280 		kmem_free(kernel_map,
1281 			cpipe->pipe_map.kva,
1282 			cpipe->pipe_buffer.size + PAGE_SIZE);
1283 		cpipe->pipe_map.cnt = 0;
1284 		cpipe->pipe_map.kva = 0;
1285 		cpipe->pipe_map.pos = 0;
1286 		cpipe->pipe_map.npages = 0;
1287 	}
1288 #endif
1289 }
1290 
1291 /*
1292  * shutdown the pipe
1293  */
1294 static void
1295 pipeclose(cpipe)
1296 	struct pipe *cpipe;
1297 {
1298 	struct pipe *ppipe;
1299 	int hadpeer;
1300 
1301 	if (cpipe == NULL)
1302 		return;
1303 
1304 	hadpeer = 0;
1305 
1306 	/* partially created pipes won't have a valid mutex. */
1307 	if (PIPE_MTX(cpipe) != NULL)
1308 		PIPE_LOCK(cpipe);
1309 
1310 	pipeselwakeup(cpipe);
1311 
1312 	/*
1313 	 * If the other side is blocked, wake it up saying that
1314 	 * we want to close it down.
1315 	 */
1316 	while (cpipe->pipe_busy) {
1317 		wakeup(cpipe);
1318 		cpipe->pipe_state |= PIPE_WANT | PIPE_EOF;
1319 		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1320 	}
1321 
1322 	/*
1323 	 * Disconnect from peer
1324 	 */
1325 	if ((ppipe = cpipe->pipe_peer) != NULL) {
1326 		hadpeer++;
1327 		pipeselwakeup(ppipe);
1328 
1329 		ppipe->pipe_state |= PIPE_EOF;
1330 		wakeup(ppipe);
1331 		KNOTE(&ppipe->pipe_sel.si_note, 0);
1332 		ppipe->pipe_peer = NULL;
1333 	}
1334 	/*
1335 	 * free resources
1336 	 */
1337 	if (PIPE_MTX(cpipe) != NULL) {
1338 		PIPE_UNLOCK(cpipe);
1339 		if (!hadpeer) {
1340 			mtx_destroy(PIPE_MTX(cpipe));
1341 			free(PIPE_MTX(cpipe), M_TEMP);
1342 		}
1343 	}
1344 	mtx_lock(&Giant);
1345 	pipe_free_kmem(cpipe);
1346 	uma_zfree(pipe_zone, cpipe);
1347 	mtx_unlock(&Giant);
1348 }
1349 
1350 /*ARGSUSED*/
1351 static int
1352 pipe_kqfilter(struct file *fp, struct knote *kn)
1353 {
1354 	struct pipe *cpipe;
1355 
1356 	cpipe = (struct pipe *)kn->kn_fp->f_data;
1357 	switch (kn->kn_filter) {
1358 	case EVFILT_READ:
1359 		kn->kn_fop = &pipe_rfiltops;
1360 		break;
1361 	case EVFILT_WRITE:
1362 		kn->kn_fop = &pipe_wfiltops;
1363 		cpipe = cpipe->pipe_peer;
1364 		break;
1365 	default:
1366 		return (1);
1367 	}
1368 	kn->kn_hook = (caddr_t)cpipe;
1369 
1370 	PIPE_LOCK(cpipe);
1371 	SLIST_INSERT_HEAD(&cpipe->pipe_sel.si_note, kn, kn_selnext);
1372 	PIPE_UNLOCK(cpipe);
1373 	return (0);
1374 }
1375 
1376 static void
1377 filt_pipedetach(struct knote *kn)
1378 {
1379 	struct pipe *cpipe = (struct pipe *)kn->kn_hook;
1380 
1381 	PIPE_LOCK(cpipe);
1382 	SLIST_REMOVE(&cpipe->pipe_sel.si_note, kn, knote, kn_selnext);
1383 	PIPE_UNLOCK(cpipe);
1384 }
1385 
1386 /*ARGSUSED*/
1387 static int
1388 filt_piperead(struct knote *kn, long hint)
1389 {
1390 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1391 	struct pipe *wpipe = rpipe->pipe_peer;
1392 
1393 	PIPE_LOCK(rpipe);
1394 	kn->kn_data = rpipe->pipe_buffer.cnt;
1395 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1396 		kn->kn_data = rpipe->pipe_map.cnt;
1397 
1398 	if ((rpipe->pipe_state & PIPE_EOF) ||
1399 	    (wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1400 		kn->kn_flags |= EV_EOF;
1401 		PIPE_UNLOCK(rpipe);
1402 		return (1);
1403 	}
1404 	PIPE_UNLOCK(rpipe);
1405 	return (kn->kn_data > 0);
1406 }
1407 
1408 /*ARGSUSED*/
1409 static int
1410 filt_pipewrite(struct knote *kn, long hint)
1411 {
1412 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1413 	struct pipe *wpipe = rpipe->pipe_peer;
1414 
1415 	PIPE_LOCK(rpipe);
1416 	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1417 		kn->kn_data = 0;
1418 		kn->kn_flags |= EV_EOF;
1419 		PIPE_UNLOCK(rpipe);
1420 		return (1);
1421 	}
1422 	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1423 	if (wpipe->pipe_state & PIPE_DIRECTW)
1424 		kn->kn_data = 0;
1425 
1426 	PIPE_UNLOCK(rpipe);
1427 	return (kn->kn_data >= PIPE_BUF);
1428 }
1429