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