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