xref: /freebsd/sys/kern/sys_pipe.c (revision a0dd79dbdf917a8fbe2762d668f05a7c9f682b22)
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, the sending process pins the underlying pages in
33  * memory, and the receiving process copies directly from these pinned pages
34  * in the sending 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. This value is normally
52  * autotuned, but may also be loader tuned.
53  *
54  * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
55  * memory in use by pipes.
56  *
57  * Based on how large pipekva is relative to maxpipekva, the following
58  * will happen:
59  *
60  * 0% - 50%:
61  *     New pipes are given 16K of memory backing, pipes may dynamically
62  *     grow to as large as 64K where needed.
63  * 50% - 75%:
64  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
65  *     existing pipes may NOT grow.
66  * 75% - 100%:
67  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
68  *     existing pipes will be shrunk down to 4K whenever possible.
69  *
70  * Resizing may be disabled by setting kern.ipc.piperesizeallowed=0.  If
71  * that is set,  the only resize that will occur is the 0 -> SMALL_PIPE_SIZE
72  * resize which MUST occur for reverse-direction pipes when they are
73  * first used.
74  *
75  * Additional information about the current state of pipes may be obtained
76  * from kern.ipc.pipes, kern.ipc.pipefragretry, kern.ipc.pipeallocfail,
77  * and kern.ipc.piperesizefail.
78  *
79  * Locking rules:  There are two locks present here:  A mutex, used via
80  * PIPE_LOCK, and a flag, used via pipelock().  All locking is done via
81  * the flag, as mutexes can not persist over uiomove.  The mutex
82  * exists only to guard access to the flag, and is not in itself a
83  * locking mechanism.  Also note that there is only a single mutex for
84  * both directions of a pipe.
85  *
86  * As pipelock() may have to sleep before it can acquire the flag, it
87  * is important to reread all data after a call to pipelock(); everything
88  * in the structure may have changed.
89  */
90 
91 #include <sys/cdefs.h>
92 __FBSDID("$FreeBSD$");
93 
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/conf.h>
97 #include <sys/fcntl.h>
98 #include <sys/file.h>
99 #include <sys/filedesc.h>
100 #include <sys/filio.h>
101 #include <sys/kernel.h>
102 #include <sys/lock.h>
103 #include <sys/mutex.h>
104 #include <sys/ttycom.h>
105 #include <sys/stat.h>
106 #include <sys/malloc.h>
107 #include <sys/poll.h>
108 #include <sys/selinfo.h>
109 #include <sys/signalvar.h>
110 #include <sys/syscallsubr.h>
111 #include <sys/sysctl.h>
112 #include <sys/sysproto.h>
113 #include <sys/pipe.h>
114 #include <sys/proc.h>
115 #include <sys/vnode.h>
116 #include <sys/uio.h>
117 #include <sys/event.h>
118 
119 #include <security/mac/mac_framework.h>
120 
121 #include <vm/vm.h>
122 #include <vm/vm_param.h>
123 #include <vm/vm_object.h>
124 #include <vm/vm_kern.h>
125 #include <vm/vm_extern.h>
126 #include <vm/pmap.h>
127 #include <vm/vm_map.h>
128 #include <vm/vm_page.h>
129 #include <vm/uma.h>
130 
131 /*
132  * Use this define if you want to disable *fancy* VM things.  Expect an
133  * approx 30% decrease in transfer rate.  This could be useful for
134  * NetBSD or OpenBSD.
135  */
136 /* #define PIPE_NODIRECT */
137 
138 /*
139  * interfaces to the outside world
140  */
141 static fo_rdwr_t	pipe_read;
142 static fo_rdwr_t	pipe_write;
143 static fo_truncate_t	pipe_truncate;
144 static fo_ioctl_t	pipe_ioctl;
145 static fo_poll_t	pipe_poll;
146 static fo_kqfilter_t	pipe_kqfilter;
147 static fo_stat_t	pipe_stat;
148 static fo_close_t	pipe_close;
149 
150 static struct fileops pipeops = {
151 	.fo_read = pipe_read,
152 	.fo_write = pipe_write,
153 	.fo_truncate = pipe_truncate,
154 	.fo_ioctl = pipe_ioctl,
155 	.fo_poll = pipe_poll,
156 	.fo_kqfilter = pipe_kqfilter,
157 	.fo_stat = pipe_stat,
158 	.fo_close = pipe_close,
159 	.fo_chmod = invfo_chmod,
160 	.fo_chown = invfo_chown,
161 	.fo_flags = DFLAG_PASSABLE
162 };
163 
164 static void	filt_pipedetach(struct knote *kn);
165 static int	filt_piperead(struct knote *kn, long hint);
166 static int	filt_pipewrite(struct knote *kn, long hint);
167 
168 static struct filterops pipe_rfiltops = {
169 	.f_isfd = 1,
170 	.f_detach = filt_pipedetach,
171 	.f_event = filt_piperead
172 };
173 static struct filterops pipe_wfiltops = {
174 	.f_isfd = 1,
175 	.f_detach = filt_pipedetach,
176 	.f_event = filt_pipewrite
177 };
178 
179 /*
180  * Default pipe buffer size(s), this can be kind-of large now because pipe
181  * space is pageable.  The pipe code will try to maintain locality of
182  * reference for performance reasons, so small amounts of outstanding I/O
183  * will not wipe the cache.
184  */
185 #define MINPIPESIZE (PIPE_SIZE/3)
186 #define MAXPIPESIZE (2*PIPE_SIZE/3)
187 
188 static long amountpipekva;
189 static int pipefragretry;
190 static int pipeallocfail;
191 static int piperesizefail;
192 static int piperesizeallowed = 1;
193 
194 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
195 	   &maxpipekva, 0, "Pipe KVA limit");
196 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
197 	   &amountpipekva, 0, "Pipe KVA usage");
198 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
199 	  &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
200 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
201 	  &pipeallocfail, 0, "Pipe allocation failures");
202 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
203 	  &piperesizefail, 0, "Pipe resize failures");
204 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
205 	  &piperesizeallowed, 0, "Pipe resizing allowed");
206 
207 static void pipeinit(void *dummy __unused);
208 static void pipeclose(struct pipe *cpipe);
209 static void pipe_free_kmem(struct pipe *cpipe);
210 static int pipe_create(struct pipe *pipe, int backing);
211 static __inline int pipelock(struct pipe *cpipe, int catch);
212 static __inline void pipeunlock(struct pipe *cpipe);
213 static __inline void pipeselwakeup(struct pipe *cpipe);
214 #ifndef PIPE_NODIRECT
215 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
216 static void pipe_destroy_write_buffer(struct pipe *wpipe);
217 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
218 static void pipe_clone_write_buffer(struct pipe *wpipe);
219 #endif
220 static int pipespace(struct pipe *cpipe, int size);
221 static int pipespace_new(struct pipe *cpipe, int size);
222 
223 static int	pipe_zone_ctor(void *mem, int size, void *arg, int flags);
224 static int	pipe_zone_init(void *mem, int size, int flags);
225 static void	pipe_zone_fini(void *mem, int size);
226 
227 static uma_zone_t pipe_zone;
228 static struct unrhdr *pipeino_unr;
229 static dev_t pipedev_ino;
230 
231 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
232 
233 static void
234 pipeinit(void *dummy __unused)
235 {
236 
237 	pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
238 	    pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
239 	    UMA_ALIGN_PTR, 0);
240 	KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
241 	pipeino_unr = new_unrhdr(1, INT32_MAX, NULL);
242 	KASSERT(pipeino_unr != NULL, ("pipe fake inodes not initialized"));
243 	pipedev_ino = devfs_alloc_cdp_inode();
244 	KASSERT(pipedev_ino > 0, ("pipe dev inode not initialized"));
245 }
246 
247 static int
248 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
249 {
250 	struct pipepair *pp;
251 	struct pipe *rpipe, *wpipe;
252 
253 	KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
254 
255 	pp = (struct pipepair *)mem;
256 
257 	/*
258 	 * We zero both pipe endpoints to make sure all the kmem pointers
259 	 * are NULL, flag fields are zero'd, etc.  We timestamp both
260 	 * endpoints with the same time.
261 	 */
262 	rpipe = &pp->pp_rpipe;
263 	bzero(rpipe, sizeof(*rpipe));
264 	vfs_timestamp(&rpipe->pipe_ctime);
265 	rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
266 
267 	wpipe = &pp->pp_wpipe;
268 	bzero(wpipe, sizeof(*wpipe));
269 	wpipe->pipe_ctime = rpipe->pipe_ctime;
270 	wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
271 
272 	rpipe->pipe_peer = wpipe;
273 	rpipe->pipe_pair = pp;
274 	wpipe->pipe_peer = rpipe;
275 	wpipe->pipe_pair = pp;
276 
277 	/*
278 	 * Mark both endpoints as present; they will later get free'd
279 	 * one at a time.  When both are free'd, then the whole pair
280 	 * is released.
281 	 */
282 	rpipe->pipe_present = PIPE_ACTIVE;
283 	wpipe->pipe_present = PIPE_ACTIVE;
284 
285 	/*
286 	 * Eventually, the MAC Framework may initialize the label
287 	 * in ctor or init, but for now we do it elswhere to avoid
288 	 * blocking in ctor or init.
289 	 */
290 	pp->pp_label = NULL;
291 
292 	return (0);
293 }
294 
295 static int
296 pipe_zone_init(void *mem, int size, int flags)
297 {
298 	struct pipepair *pp;
299 
300 	KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
301 
302 	pp = (struct pipepair *)mem;
303 
304 	mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
305 	return (0);
306 }
307 
308 static void
309 pipe_zone_fini(void *mem, int size)
310 {
311 	struct pipepair *pp;
312 
313 	KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
314 
315 	pp = (struct pipepair *)mem;
316 
317 	mtx_destroy(&pp->pp_mtx);
318 }
319 
320 /*
321  * The pipe system call for the DTYPE_PIPE type of pipes.  If we fail, let
322  * the zone pick up the pieces via pipeclose().
323  */
324 int
325 kern_pipe(struct thread *td, int fildes[2])
326 {
327 	struct filedesc *fdp = td->td_proc->p_fd;
328 	struct file *rf, *wf;
329 	struct pipepair *pp;
330 	struct pipe *rpipe, *wpipe;
331 	int fd, error;
332 
333 	pp = uma_zalloc(pipe_zone, M_WAITOK);
334 #ifdef MAC
335 	/*
336 	 * The MAC label is shared between the connected endpoints.  As a
337 	 * result mac_pipe_init() and mac_pipe_create() are called once
338 	 * for the pair, and not on the endpoints.
339 	 */
340 	mac_pipe_init(pp);
341 	mac_pipe_create(td->td_ucred, pp);
342 #endif
343 	rpipe = &pp->pp_rpipe;
344 	wpipe = &pp->pp_wpipe;
345 
346 	knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
347 	knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
348 
349 	/* Only the forward direction pipe is backed by default */
350 	if ((error = pipe_create(rpipe, 1)) != 0 ||
351 	    (error = pipe_create(wpipe, 0)) != 0) {
352 		pipeclose(rpipe);
353 		pipeclose(wpipe);
354 		return (error);
355 	}
356 
357 	rpipe->pipe_state |= PIPE_DIRECTOK;
358 	wpipe->pipe_state |= PIPE_DIRECTOK;
359 
360 	error = falloc(td, &rf, &fd, 0);
361 	if (error) {
362 		pipeclose(rpipe);
363 		pipeclose(wpipe);
364 		return (error);
365 	}
366 	/* An extra reference on `rf' has been held for us by falloc(). */
367 	fildes[0] = fd;
368 
369 	/*
370 	 * Warning: once we've gotten past allocation of the fd for the
371 	 * read-side, we can only drop the read side via fdrop() in order
372 	 * to avoid races against processes which manage to dup() the read
373 	 * side while we are blocked trying to allocate the write side.
374 	 */
375 	finit(rf, FREAD | FWRITE, DTYPE_PIPE, rpipe, &pipeops);
376 	error = falloc(td, &wf, &fd, 0);
377 	if (error) {
378 		fdclose(fdp, rf, fildes[0], td);
379 		fdrop(rf, td);
380 		/* rpipe has been closed by fdrop(). */
381 		pipeclose(wpipe);
382 		return (error);
383 	}
384 	/* An extra reference on `wf' has been held for us by falloc(). */
385 	finit(wf, FREAD | FWRITE, DTYPE_PIPE, wpipe, &pipeops);
386 	fdrop(wf, td);
387 	fildes[1] = fd;
388 	fdrop(rf, td);
389 
390 	return (0);
391 }
392 
393 /* ARGSUSED */
394 int
395 sys_pipe(struct thread *td, struct pipe_args *uap)
396 {
397 	int error;
398 	int fildes[2];
399 
400 	error = kern_pipe(td, fildes);
401 	if (error)
402 		return (error);
403 
404 	td->td_retval[0] = fildes[0];
405 	td->td_retval[1] = fildes[1];
406 
407 	return (0);
408 }
409 
410 /*
411  * Allocate kva for pipe circular buffer, the space is pageable
412  * This routine will 'realloc' the size of a pipe safely, if it fails
413  * it will retain the old buffer.
414  * If it fails it will return ENOMEM.
415  */
416 static int
417 pipespace_new(cpipe, size)
418 	struct pipe *cpipe;
419 	int size;
420 {
421 	caddr_t buffer;
422 	int error, cnt, firstseg;
423 	static int curfail = 0;
424 	static struct timeval lastfail;
425 
426 	KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
427 	KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
428 		("pipespace: resize of direct writes not allowed"));
429 retry:
430 	cnt = cpipe->pipe_buffer.cnt;
431 	if (cnt > size)
432 		size = cnt;
433 
434 	size = round_page(size);
435 	buffer = (caddr_t) vm_map_min(pipe_map);
436 
437 	error = vm_map_find(pipe_map, NULL, 0,
438 		(vm_offset_t *) &buffer, size, 1,
439 		VM_PROT_ALL, VM_PROT_ALL, 0);
440 	if (error != KERN_SUCCESS) {
441 		if ((cpipe->pipe_buffer.buffer == NULL) &&
442 			(size > SMALL_PIPE_SIZE)) {
443 			size = SMALL_PIPE_SIZE;
444 			pipefragretry++;
445 			goto retry;
446 		}
447 		if (cpipe->pipe_buffer.buffer == NULL) {
448 			pipeallocfail++;
449 			if (ppsratecheck(&lastfail, &curfail, 1))
450 				printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
451 		} else {
452 			piperesizefail++;
453 		}
454 		return (ENOMEM);
455 	}
456 
457 	/* copy data, then free old resources if we're resizing */
458 	if (cnt > 0) {
459 		if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
460 			firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
461 			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
462 				buffer, firstseg);
463 			if ((cnt - firstseg) > 0)
464 				bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
465 					cpipe->pipe_buffer.in);
466 		} else {
467 			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
468 				buffer, cnt);
469 		}
470 	}
471 	pipe_free_kmem(cpipe);
472 	cpipe->pipe_buffer.buffer = buffer;
473 	cpipe->pipe_buffer.size = size;
474 	cpipe->pipe_buffer.in = cnt;
475 	cpipe->pipe_buffer.out = 0;
476 	cpipe->pipe_buffer.cnt = cnt;
477 	atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
478 	return (0);
479 }
480 
481 /*
482  * Wrapper for pipespace_new() that performs locking assertions.
483  */
484 static int
485 pipespace(cpipe, size)
486 	struct pipe *cpipe;
487 	int size;
488 {
489 
490 	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
491 		("Unlocked pipe passed to pipespace"));
492 	return (pipespace_new(cpipe, size));
493 }
494 
495 /*
496  * lock a pipe for I/O, blocking other access
497  */
498 static __inline int
499 pipelock(cpipe, catch)
500 	struct pipe *cpipe;
501 	int catch;
502 {
503 	int error;
504 
505 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
506 	while (cpipe->pipe_state & PIPE_LOCKFL) {
507 		cpipe->pipe_state |= PIPE_LWANT;
508 		error = msleep(cpipe, PIPE_MTX(cpipe),
509 		    catch ? (PRIBIO | PCATCH) : PRIBIO,
510 		    "pipelk", 0);
511 		if (error != 0)
512 			return (error);
513 	}
514 	cpipe->pipe_state |= PIPE_LOCKFL;
515 	return (0);
516 }
517 
518 /*
519  * unlock a pipe I/O lock
520  */
521 static __inline void
522 pipeunlock(cpipe)
523 	struct pipe *cpipe;
524 {
525 
526 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
527 	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
528 		("Unlocked pipe passed to pipeunlock"));
529 	cpipe->pipe_state &= ~PIPE_LOCKFL;
530 	if (cpipe->pipe_state & PIPE_LWANT) {
531 		cpipe->pipe_state &= ~PIPE_LWANT;
532 		wakeup(cpipe);
533 	}
534 }
535 
536 static __inline void
537 pipeselwakeup(cpipe)
538 	struct pipe *cpipe;
539 {
540 
541 	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
542 	if (cpipe->pipe_state & PIPE_SEL) {
543 		selwakeuppri(&cpipe->pipe_sel, PSOCK);
544 		if (!SEL_WAITING(&cpipe->pipe_sel))
545 			cpipe->pipe_state &= ~PIPE_SEL;
546 	}
547 	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
548 		pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
549 	KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
550 }
551 
552 /*
553  * Initialize and allocate VM and memory for pipe.  The structure
554  * will start out zero'd from the ctor, so we just manage the kmem.
555  */
556 static int
557 pipe_create(pipe, backing)
558 	struct pipe *pipe;
559 	int backing;
560 {
561 	int error;
562 
563 	if (backing) {
564 		if (amountpipekva > maxpipekva / 2)
565 			error = pipespace_new(pipe, SMALL_PIPE_SIZE);
566 		else
567 			error = pipespace_new(pipe, PIPE_SIZE);
568 	} else {
569 		/* If we're not backing this pipe, no need to do anything. */
570 		error = 0;
571 	}
572 	pipe->pipe_ino = -1;
573 	return (error);
574 }
575 
576 /* ARGSUSED */
577 static int
578 pipe_read(fp, uio, active_cred, flags, td)
579 	struct file *fp;
580 	struct uio *uio;
581 	struct ucred *active_cred;
582 	struct thread *td;
583 	int flags;
584 {
585 	struct pipe *rpipe = fp->f_data;
586 	int error;
587 	int nread = 0;
588 	u_int size;
589 
590 	PIPE_LOCK(rpipe);
591 	++rpipe->pipe_busy;
592 	error = pipelock(rpipe, 1);
593 	if (error)
594 		goto unlocked_error;
595 
596 #ifdef MAC
597 	error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
598 	if (error)
599 		goto locked_error;
600 #endif
601 	if (amountpipekva > (3 * maxpipekva) / 4) {
602 		if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
603 			(rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
604 			(rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
605 			(piperesizeallowed == 1)) {
606 			PIPE_UNLOCK(rpipe);
607 			pipespace(rpipe, SMALL_PIPE_SIZE);
608 			PIPE_LOCK(rpipe);
609 		}
610 	}
611 
612 	while (uio->uio_resid) {
613 		/*
614 		 * normal pipe buffer receive
615 		 */
616 		if (rpipe->pipe_buffer.cnt > 0) {
617 			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
618 			if (size > rpipe->pipe_buffer.cnt)
619 				size = rpipe->pipe_buffer.cnt;
620 			if (size > uio->uio_resid)
621 				size = (u_int) uio->uio_resid;
622 
623 			PIPE_UNLOCK(rpipe);
624 			error = uiomove(
625 			    &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
626 			    size, uio);
627 			PIPE_LOCK(rpipe);
628 			if (error)
629 				break;
630 
631 			rpipe->pipe_buffer.out += size;
632 			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
633 				rpipe->pipe_buffer.out = 0;
634 
635 			rpipe->pipe_buffer.cnt -= size;
636 
637 			/*
638 			 * If there is no more to read in the pipe, reset
639 			 * its pointers to the beginning.  This improves
640 			 * cache hit stats.
641 			 */
642 			if (rpipe->pipe_buffer.cnt == 0) {
643 				rpipe->pipe_buffer.in = 0;
644 				rpipe->pipe_buffer.out = 0;
645 			}
646 			nread += size;
647 #ifndef PIPE_NODIRECT
648 		/*
649 		 * Direct copy, bypassing a kernel buffer.
650 		 */
651 		} else if ((size = rpipe->pipe_map.cnt) &&
652 			   (rpipe->pipe_state & PIPE_DIRECTW)) {
653 			if (size > uio->uio_resid)
654 				size = (u_int) uio->uio_resid;
655 
656 			PIPE_UNLOCK(rpipe);
657 			error = uiomove_fromphys(rpipe->pipe_map.ms,
658 			    rpipe->pipe_map.pos, size, uio);
659 			PIPE_LOCK(rpipe);
660 			if (error)
661 				break;
662 			nread += size;
663 			rpipe->pipe_map.pos += size;
664 			rpipe->pipe_map.cnt -= size;
665 			if (rpipe->pipe_map.cnt == 0) {
666 				rpipe->pipe_state &= ~PIPE_DIRECTW;
667 				wakeup(rpipe);
668 			}
669 #endif
670 		} else {
671 			/*
672 			 * detect EOF condition
673 			 * read returns 0 on EOF, no need to set error
674 			 */
675 			if (rpipe->pipe_state & PIPE_EOF)
676 				break;
677 
678 			/*
679 			 * If the "write-side" has been blocked, wake it up now.
680 			 */
681 			if (rpipe->pipe_state & PIPE_WANTW) {
682 				rpipe->pipe_state &= ~PIPE_WANTW;
683 				wakeup(rpipe);
684 			}
685 
686 			/*
687 			 * Break if some data was read.
688 			 */
689 			if (nread > 0)
690 				break;
691 
692 			/*
693 			 * Unlock the pipe buffer for our remaining processing.
694 			 * We will either break out with an error or we will
695 			 * sleep and relock to loop.
696 			 */
697 			pipeunlock(rpipe);
698 
699 			/*
700 			 * Handle non-blocking mode operation or
701 			 * wait for more data.
702 			 */
703 			if (fp->f_flag & FNONBLOCK) {
704 				error = EAGAIN;
705 			} else {
706 				rpipe->pipe_state |= PIPE_WANTR;
707 				if ((error = msleep(rpipe, PIPE_MTX(rpipe),
708 				    PRIBIO | PCATCH,
709 				    "piperd", 0)) == 0)
710 					error = pipelock(rpipe, 1);
711 			}
712 			if (error)
713 				goto unlocked_error;
714 		}
715 	}
716 #ifdef MAC
717 locked_error:
718 #endif
719 	pipeunlock(rpipe);
720 
721 	/* XXX: should probably do this before getting any locks. */
722 	if (error == 0)
723 		vfs_timestamp(&rpipe->pipe_atime);
724 unlocked_error:
725 	--rpipe->pipe_busy;
726 
727 	/*
728 	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
729 	 */
730 	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
731 		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
732 		wakeup(rpipe);
733 	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
734 		/*
735 		 * Handle write blocking hysteresis.
736 		 */
737 		if (rpipe->pipe_state & PIPE_WANTW) {
738 			rpipe->pipe_state &= ~PIPE_WANTW;
739 			wakeup(rpipe);
740 		}
741 	}
742 
743 	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
744 		pipeselwakeup(rpipe);
745 
746 	PIPE_UNLOCK(rpipe);
747 	return (error);
748 }
749 
750 #ifndef PIPE_NODIRECT
751 /*
752  * Map the sending processes' buffer into kernel space and wire it.
753  * This is similar to a physical write operation.
754  */
755 static int
756 pipe_build_write_buffer(wpipe, uio)
757 	struct pipe *wpipe;
758 	struct uio *uio;
759 {
760 	u_int size;
761 	int i;
762 
763 	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
764 	KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
765 		("Clone attempt on non-direct write pipe!"));
766 
767 	if (uio->uio_iov->iov_len > wpipe->pipe_buffer.size)
768                 size = wpipe->pipe_buffer.size;
769 	else
770                 size = uio->uio_iov->iov_len;
771 
772 	if ((i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
773 	    (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
774 	    wpipe->pipe_map.ms, PIPENPAGES)) < 0)
775 		return (EFAULT);
776 
777 /*
778  * set up the control block
779  */
780 	wpipe->pipe_map.npages = i;
781 	wpipe->pipe_map.pos =
782 	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
783 	wpipe->pipe_map.cnt = size;
784 
785 /*
786  * and update the uio data
787  */
788 
789 	uio->uio_iov->iov_len -= size;
790 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
791 	if (uio->uio_iov->iov_len == 0)
792 		uio->uio_iov++;
793 	uio->uio_resid -= size;
794 	uio->uio_offset += size;
795 	return (0);
796 }
797 
798 /*
799  * unmap and unwire the process buffer
800  */
801 static void
802 pipe_destroy_write_buffer(wpipe)
803 	struct pipe *wpipe;
804 {
805 
806 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
807 	vm_page_unhold_pages(wpipe->pipe_map.ms, wpipe->pipe_map.npages);
808 	wpipe->pipe_map.npages = 0;
809 }
810 
811 /*
812  * In the case of a signal, the writing process might go away.  This
813  * code copies the data into the circular buffer so that the source
814  * pages can be freed without loss of data.
815  */
816 static void
817 pipe_clone_write_buffer(wpipe)
818 	struct pipe *wpipe;
819 {
820 	struct uio uio;
821 	struct iovec iov;
822 	int size;
823 	int pos;
824 
825 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
826 	size = wpipe->pipe_map.cnt;
827 	pos = wpipe->pipe_map.pos;
828 
829 	wpipe->pipe_buffer.in = size;
830 	wpipe->pipe_buffer.out = 0;
831 	wpipe->pipe_buffer.cnt = size;
832 	wpipe->pipe_state &= ~PIPE_DIRECTW;
833 
834 	PIPE_UNLOCK(wpipe);
835 	iov.iov_base = wpipe->pipe_buffer.buffer;
836 	iov.iov_len = size;
837 	uio.uio_iov = &iov;
838 	uio.uio_iovcnt = 1;
839 	uio.uio_offset = 0;
840 	uio.uio_resid = size;
841 	uio.uio_segflg = UIO_SYSSPACE;
842 	uio.uio_rw = UIO_READ;
843 	uio.uio_td = curthread;
844 	uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
845 	PIPE_LOCK(wpipe);
846 	pipe_destroy_write_buffer(wpipe);
847 }
848 
849 /*
850  * This implements the pipe buffer write mechanism.  Note that only
851  * a direct write OR a normal pipe write can be pending at any given time.
852  * If there are any characters in the pipe buffer, the direct write will
853  * be deferred until the receiving process grabs all of the bytes from
854  * the pipe buffer.  Then the direct mapping write is set-up.
855  */
856 static int
857 pipe_direct_write(wpipe, uio)
858 	struct pipe *wpipe;
859 	struct uio *uio;
860 {
861 	int error;
862 
863 retry:
864 	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
865 	error = pipelock(wpipe, 1);
866 	if (wpipe->pipe_state & PIPE_EOF)
867 		error = EPIPE;
868 	if (error) {
869 		pipeunlock(wpipe);
870 		goto error1;
871 	}
872 	while (wpipe->pipe_state & PIPE_DIRECTW) {
873 		if (wpipe->pipe_state & PIPE_WANTR) {
874 			wpipe->pipe_state &= ~PIPE_WANTR;
875 			wakeup(wpipe);
876 		}
877 		pipeselwakeup(wpipe);
878 		wpipe->pipe_state |= PIPE_WANTW;
879 		pipeunlock(wpipe);
880 		error = msleep(wpipe, PIPE_MTX(wpipe),
881 		    PRIBIO | PCATCH, "pipdww", 0);
882 		if (error)
883 			goto error1;
884 		else
885 			goto retry;
886 	}
887 	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
888 	if (wpipe->pipe_buffer.cnt > 0) {
889 		if (wpipe->pipe_state & PIPE_WANTR) {
890 			wpipe->pipe_state &= ~PIPE_WANTR;
891 			wakeup(wpipe);
892 		}
893 		pipeselwakeup(wpipe);
894 		wpipe->pipe_state |= PIPE_WANTW;
895 		pipeunlock(wpipe);
896 		error = msleep(wpipe, PIPE_MTX(wpipe),
897 		    PRIBIO | PCATCH, "pipdwc", 0);
898 		if (error)
899 			goto error1;
900 		else
901 			goto retry;
902 	}
903 
904 	wpipe->pipe_state |= PIPE_DIRECTW;
905 
906 	PIPE_UNLOCK(wpipe);
907 	error = pipe_build_write_buffer(wpipe, uio);
908 	PIPE_LOCK(wpipe);
909 	if (error) {
910 		wpipe->pipe_state &= ~PIPE_DIRECTW;
911 		pipeunlock(wpipe);
912 		goto error1;
913 	}
914 
915 	error = 0;
916 	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
917 		if (wpipe->pipe_state & PIPE_EOF) {
918 			pipe_destroy_write_buffer(wpipe);
919 			pipeselwakeup(wpipe);
920 			pipeunlock(wpipe);
921 			error = EPIPE;
922 			goto error1;
923 		}
924 		if (wpipe->pipe_state & PIPE_WANTR) {
925 			wpipe->pipe_state &= ~PIPE_WANTR;
926 			wakeup(wpipe);
927 		}
928 		pipeselwakeup(wpipe);
929 		pipeunlock(wpipe);
930 		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
931 		    "pipdwt", 0);
932 		pipelock(wpipe, 0);
933 	}
934 
935 	if (wpipe->pipe_state & PIPE_EOF)
936 		error = EPIPE;
937 	if (wpipe->pipe_state & PIPE_DIRECTW) {
938 		/*
939 		 * this bit of trickery substitutes a kernel buffer for
940 		 * the process that might be going away.
941 		 */
942 		pipe_clone_write_buffer(wpipe);
943 	} else {
944 		pipe_destroy_write_buffer(wpipe);
945 	}
946 	pipeunlock(wpipe);
947 	return (error);
948 
949 error1:
950 	wakeup(wpipe);
951 	return (error);
952 }
953 #endif
954 
955 static int
956 pipe_write(fp, uio, active_cred, flags, td)
957 	struct file *fp;
958 	struct uio *uio;
959 	struct ucred *active_cred;
960 	struct thread *td;
961 	int flags;
962 {
963 	int error = 0;
964 	size_t desiredsize, orig_resid;
965 	struct pipe *wpipe, *rpipe;
966 
967 	rpipe = fp->f_data;
968 	wpipe = rpipe->pipe_peer;
969 
970 	PIPE_LOCK(rpipe);
971 	error = pipelock(wpipe, 1);
972 	if (error) {
973 		PIPE_UNLOCK(rpipe);
974 		return (error);
975 	}
976 	/*
977 	 * detect loss of pipe read side, issue SIGPIPE if lost.
978 	 */
979 	if (wpipe->pipe_present != PIPE_ACTIVE ||
980 	    (wpipe->pipe_state & PIPE_EOF)) {
981 		pipeunlock(wpipe);
982 		PIPE_UNLOCK(rpipe);
983 		return (EPIPE);
984 	}
985 #ifdef MAC
986 	error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
987 	if (error) {
988 		pipeunlock(wpipe);
989 		PIPE_UNLOCK(rpipe);
990 		return (error);
991 	}
992 #endif
993 	++wpipe->pipe_busy;
994 
995 	/* Choose a larger size if it's advantageous */
996 	desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
997 	while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
998 		if (piperesizeallowed != 1)
999 			break;
1000 		if (amountpipekva > maxpipekva / 2)
1001 			break;
1002 		if (desiredsize == BIG_PIPE_SIZE)
1003 			break;
1004 		desiredsize = desiredsize * 2;
1005 	}
1006 
1007 	/* Choose a smaller size if we're in a OOM situation */
1008 	if ((amountpipekva > (3 * maxpipekva) / 4) &&
1009 		(wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1010 		(wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1011 		(piperesizeallowed == 1))
1012 		desiredsize = SMALL_PIPE_SIZE;
1013 
1014 	/* Resize if the above determined that a new size was necessary */
1015 	if ((desiredsize != wpipe->pipe_buffer.size) &&
1016 		((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1017 		PIPE_UNLOCK(wpipe);
1018 		pipespace(wpipe, desiredsize);
1019 		PIPE_LOCK(wpipe);
1020 	}
1021 	if (wpipe->pipe_buffer.size == 0) {
1022 		/*
1023 		 * This can only happen for reverse direction use of pipes
1024 		 * in a complete OOM situation.
1025 		 */
1026 		error = ENOMEM;
1027 		--wpipe->pipe_busy;
1028 		pipeunlock(wpipe);
1029 		PIPE_UNLOCK(wpipe);
1030 		return (error);
1031 	}
1032 
1033 	pipeunlock(wpipe);
1034 
1035 	orig_resid = uio->uio_resid;
1036 
1037 	while (uio->uio_resid) {
1038 		int space;
1039 
1040 		pipelock(wpipe, 0);
1041 		if (wpipe->pipe_state & PIPE_EOF) {
1042 			pipeunlock(wpipe);
1043 			error = EPIPE;
1044 			break;
1045 		}
1046 #ifndef PIPE_NODIRECT
1047 		/*
1048 		 * If the transfer is large, we can gain performance if
1049 		 * we do process-to-process copies directly.
1050 		 * If the write is non-blocking, we don't use the
1051 		 * direct write mechanism.
1052 		 *
1053 		 * The direct write mechanism will detect the reader going
1054 		 * away on us.
1055 		 */
1056 		if (uio->uio_segflg == UIO_USERSPACE &&
1057 		    uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1058 		    wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1059 		    (fp->f_flag & FNONBLOCK) == 0) {
1060 			pipeunlock(wpipe);
1061 			error = pipe_direct_write(wpipe, uio);
1062 			if (error)
1063 				break;
1064 			continue;
1065 		}
1066 #endif
1067 
1068 		/*
1069 		 * Pipe buffered writes cannot be coincidental with
1070 		 * direct writes.  We wait until the currently executing
1071 		 * direct write is completed before we start filling the
1072 		 * pipe buffer.  We break out if a signal occurs or the
1073 		 * reader goes away.
1074 		 */
1075 		if (wpipe->pipe_state & PIPE_DIRECTW) {
1076 			if (wpipe->pipe_state & PIPE_WANTR) {
1077 				wpipe->pipe_state &= ~PIPE_WANTR;
1078 				wakeup(wpipe);
1079 			}
1080 			pipeselwakeup(wpipe);
1081 			wpipe->pipe_state |= PIPE_WANTW;
1082 			pipeunlock(wpipe);
1083 			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1084 			    "pipbww", 0);
1085 			if (error)
1086 				break;
1087 			else
1088 				continue;
1089 		}
1090 
1091 		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1092 
1093 		/* Writes of size <= PIPE_BUF must be atomic. */
1094 		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1095 			space = 0;
1096 
1097 		if (space > 0) {
1098 			int size;	/* Transfer size */
1099 			int segsize;	/* first segment to transfer */
1100 
1101 			/*
1102 			 * Transfer size is minimum of uio transfer
1103 			 * and free space in pipe buffer.
1104 			 */
1105 			if (space > uio->uio_resid)
1106 				size = uio->uio_resid;
1107 			else
1108 				size = space;
1109 			/*
1110 			 * First segment to transfer is minimum of
1111 			 * transfer size and contiguous space in
1112 			 * pipe buffer.  If first segment to transfer
1113 			 * is less than the transfer size, we've got
1114 			 * a wraparound in the buffer.
1115 			 */
1116 			segsize = wpipe->pipe_buffer.size -
1117 				wpipe->pipe_buffer.in;
1118 			if (segsize > size)
1119 				segsize = size;
1120 
1121 			/* Transfer first segment */
1122 
1123 			PIPE_UNLOCK(rpipe);
1124 			error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1125 					segsize, uio);
1126 			PIPE_LOCK(rpipe);
1127 
1128 			if (error == 0 && segsize < size) {
1129 				KASSERT(wpipe->pipe_buffer.in + segsize ==
1130 					wpipe->pipe_buffer.size,
1131 					("Pipe buffer wraparound disappeared"));
1132 				/*
1133 				 * Transfer remaining part now, to
1134 				 * support atomic writes.  Wraparound
1135 				 * happened.
1136 				 */
1137 
1138 				PIPE_UNLOCK(rpipe);
1139 				error = uiomove(
1140 				    &wpipe->pipe_buffer.buffer[0],
1141 				    size - segsize, uio);
1142 				PIPE_LOCK(rpipe);
1143 			}
1144 			if (error == 0) {
1145 				wpipe->pipe_buffer.in += size;
1146 				if (wpipe->pipe_buffer.in >=
1147 				    wpipe->pipe_buffer.size) {
1148 					KASSERT(wpipe->pipe_buffer.in ==
1149 						size - segsize +
1150 						wpipe->pipe_buffer.size,
1151 						("Expected wraparound bad"));
1152 					wpipe->pipe_buffer.in = size - segsize;
1153 				}
1154 
1155 				wpipe->pipe_buffer.cnt += size;
1156 				KASSERT(wpipe->pipe_buffer.cnt <=
1157 					wpipe->pipe_buffer.size,
1158 					("Pipe buffer overflow"));
1159 			}
1160 			pipeunlock(wpipe);
1161 			if (error != 0)
1162 				break;
1163 		} else {
1164 			/*
1165 			 * If the "read-side" has been blocked, wake it up now.
1166 			 */
1167 			if (wpipe->pipe_state & PIPE_WANTR) {
1168 				wpipe->pipe_state &= ~PIPE_WANTR;
1169 				wakeup(wpipe);
1170 			}
1171 
1172 			/*
1173 			 * don't block on non-blocking I/O
1174 			 */
1175 			if (fp->f_flag & FNONBLOCK) {
1176 				error = EAGAIN;
1177 				pipeunlock(wpipe);
1178 				break;
1179 			}
1180 
1181 			/*
1182 			 * We have no more space and have something to offer,
1183 			 * wake up select/poll.
1184 			 */
1185 			pipeselwakeup(wpipe);
1186 
1187 			wpipe->pipe_state |= PIPE_WANTW;
1188 			pipeunlock(wpipe);
1189 			error = msleep(wpipe, PIPE_MTX(rpipe),
1190 			    PRIBIO | PCATCH, "pipewr", 0);
1191 			if (error != 0)
1192 				break;
1193 		}
1194 	}
1195 
1196 	pipelock(wpipe, 0);
1197 	--wpipe->pipe_busy;
1198 
1199 	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1200 		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1201 		wakeup(wpipe);
1202 	} else if (wpipe->pipe_buffer.cnt > 0) {
1203 		/*
1204 		 * If we have put any characters in the buffer, we wake up
1205 		 * the reader.
1206 		 */
1207 		if (wpipe->pipe_state & PIPE_WANTR) {
1208 			wpipe->pipe_state &= ~PIPE_WANTR;
1209 			wakeup(wpipe);
1210 		}
1211 	}
1212 
1213 	/*
1214 	 * Don't return EPIPE if I/O was successful
1215 	 */
1216 	if ((wpipe->pipe_buffer.cnt == 0) &&
1217 	    (uio->uio_resid == 0) &&
1218 	    (error == EPIPE)) {
1219 		error = 0;
1220 	}
1221 
1222 	if (error == 0)
1223 		vfs_timestamp(&wpipe->pipe_mtime);
1224 
1225 	/*
1226 	 * We have something to offer,
1227 	 * wake up select/poll.
1228 	 */
1229 	if (wpipe->pipe_buffer.cnt)
1230 		pipeselwakeup(wpipe);
1231 
1232 	pipeunlock(wpipe);
1233 	PIPE_UNLOCK(rpipe);
1234 	return (error);
1235 }
1236 
1237 /* ARGSUSED */
1238 static int
1239 pipe_truncate(fp, length, active_cred, td)
1240 	struct file *fp;
1241 	off_t length;
1242 	struct ucred *active_cred;
1243 	struct thread *td;
1244 {
1245 
1246 	return (EINVAL);
1247 }
1248 
1249 /*
1250  * we implement a very minimal set of ioctls for compatibility with sockets.
1251  */
1252 static int
1253 pipe_ioctl(fp, cmd, data, active_cred, td)
1254 	struct file *fp;
1255 	u_long cmd;
1256 	void *data;
1257 	struct ucred *active_cred;
1258 	struct thread *td;
1259 {
1260 	struct pipe *mpipe = fp->f_data;
1261 	int error;
1262 
1263 	PIPE_LOCK(mpipe);
1264 
1265 #ifdef MAC
1266 	error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1267 	if (error) {
1268 		PIPE_UNLOCK(mpipe);
1269 		return (error);
1270 	}
1271 #endif
1272 
1273 	error = 0;
1274 	switch (cmd) {
1275 
1276 	case FIONBIO:
1277 		break;
1278 
1279 	case FIOASYNC:
1280 		if (*(int *)data) {
1281 			mpipe->pipe_state |= PIPE_ASYNC;
1282 		} else {
1283 			mpipe->pipe_state &= ~PIPE_ASYNC;
1284 		}
1285 		break;
1286 
1287 	case FIONREAD:
1288 		if (mpipe->pipe_state & PIPE_DIRECTW)
1289 			*(int *)data = mpipe->pipe_map.cnt;
1290 		else
1291 			*(int *)data = mpipe->pipe_buffer.cnt;
1292 		break;
1293 
1294 	case FIOSETOWN:
1295 		PIPE_UNLOCK(mpipe);
1296 		error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1297 		goto out_unlocked;
1298 
1299 	case FIOGETOWN:
1300 		*(int *)data = fgetown(&mpipe->pipe_sigio);
1301 		break;
1302 
1303 	/* This is deprecated, FIOSETOWN should be used instead. */
1304 	case TIOCSPGRP:
1305 		PIPE_UNLOCK(mpipe);
1306 		error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1307 		goto out_unlocked;
1308 
1309 	/* This is deprecated, FIOGETOWN should be used instead. */
1310 	case TIOCGPGRP:
1311 		*(int *)data = -fgetown(&mpipe->pipe_sigio);
1312 		break;
1313 
1314 	default:
1315 		error = ENOTTY;
1316 		break;
1317 	}
1318 	PIPE_UNLOCK(mpipe);
1319 out_unlocked:
1320 	return (error);
1321 }
1322 
1323 static int
1324 pipe_poll(fp, events, active_cred, td)
1325 	struct file *fp;
1326 	int events;
1327 	struct ucred *active_cred;
1328 	struct thread *td;
1329 {
1330 	struct pipe *rpipe = fp->f_data;
1331 	struct pipe *wpipe;
1332 	int revents = 0;
1333 #ifdef MAC
1334 	int error;
1335 #endif
1336 
1337 	wpipe = rpipe->pipe_peer;
1338 	PIPE_LOCK(rpipe);
1339 #ifdef MAC
1340 	error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1341 	if (error)
1342 		goto locked_error;
1343 #endif
1344 	if (events & (POLLIN | POLLRDNORM))
1345 		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1346 		    (rpipe->pipe_buffer.cnt > 0))
1347 			revents |= events & (POLLIN | POLLRDNORM);
1348 
1349 	if (events & (POLLOUT | POLLWRNORM))
1350 		if (wpipe->pipe_present != PIPE_ACTIVE ||
1351 		    (wpipe->pipe_state & PIPE_EOF) ||
1352 		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1353 		     ((wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF ||
1354 			 wpipe->pipe_buffer.size == 0)))
1355 			revents |= events & (POLLOUT | POLLWRNORM);
1356 
1357 	if ((events & POLLINIGNEOF) == 0) {
1358 		if (rpipe->pipe_state & PIPE_EOF) {
1359 			revents |= (events & (POLLIN | POLLRDNORM));
1360 			if (wpipe->pipe_present != PIPE_ACTIVE ||
1361 			    (wpipe->pipe_state & PIPE_EOF))
1362 				revents |= POLLHUP;
1363 		}
1364 	}
1365 
1366 	if (revents == 0) {
1367 		if (events & (POLLIN | POLLRDNORM)) {
1368 			selrecord(td, &rpipe->pipe_sel);
1369 			if (SEL_WAITING(&rpipe->pipe_sel))
1370 				rpipe->pipe_state |= PIPE_SEL;
1371 		}
1372 
1373 		if (events & (POLLOUT | POLLWRNORM)) {
1374 			selrecord(td, &wpipe->pipe_sel);
1375 			if (SEL_WAITING(&wpipe->pipe_sel))
1376 				wpipe->pipe_state |= PIPE_SEL;
1377 		}
1378 	}
1379 #ifdef MAC
1380 locked_error:
1381 #endif
1382 	PIPE_UNLOCK(rpipe);
1383 
1384 	return (revents);
1385 }
1386 
1387 /*
1388  * We shouldn't need locks here as we're doing a read and this should
1389  * be a natural race.
1390  */
1391 static int
1392 pipe_stat(fp, ub, active_cred, td)
1393 	struct file *fp;
1394 	struct stat *ub;
1395 	struct ucred *active_cred;
1396 	struct thread *td;
1397 {
1398 	struct pipe *pipe;
1399 	int new_unr;
1400 #ifdef MAC
1401 	int error;
1402 #endif
1403 
1404 	pipe = fp->f_data;
1405 	PIPE_LOCK(pipe);
1406 #ifdef MAC
1407 	error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1408 	if (error) {
1409 		PIPE_UNLOCK(pipe);
1410 		return (error);
1411 	}
1412 #endif
1413 	/*
1414 	 * Lazily allocate an inode number for the pipe.  Most pipe
1415 	 * users do not call fstat(2) on the pipe, which means that
1416 	 * postponing the inode allocation until it is must be
1417 	 * returned to userland is useful.  If alloc_unr failed,
1418 	 * assign st_ino zero instead of returning an error.
1419 	 * Special pipe_ino values:
1420 	 *  -1 - not yet initialized;
1421 	 *  0  - alloc_unr failed, return 0 as st_ino forever.
1422 	 */
1423 	if (pipe->pipe_ino == (ino_t)-1) {
1424 		new_unr = alloc_unr(pipeino_unr);
1425 		if (new_unr != -1)
1426 			pipe->pipe_ino = new_unr;
1427 		else
1428 			pipe->pipe_ino = 0;
1429 	}
1430 	PIPE_UNLOCK(pipe);
1431 
1432 	bzero(ub, sizeof(*ub));
1433 	ub->st_mode = S_IFIFO;
1434 	ub->st_blksize = PAGE_SIZE;
1435 	if (pipe->pipe_state & PIPE_DIRECTW)
1436 		ub->st_size = pipe->pipe_map.cnt;
1437 	else
1438 		ub->st_size = pipe->pipe_buffer.cnt;
1439 	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1440 	ub->st_atim = pipe->pipe_atime;
1441 	ub->st_mtim = pipe->pipe_mtime;
1442 	ub->st_ctim = pipe->pipe_ctime;
1443 	ub->st_uid = fp->f_cred->cr_uid;
1444 	ub->st_gid = fp->f_cred->cr_gid;
1445 	ub->st_dev = pipedev_ino;
1446 	ub->st_ino = pipe->pipe_ino;
1447 	/*
1448 	 * Left as 0: st_nlink, st_rdev, st_flags, st_gen.
1449 	 */
1450 	return (0);
1451 }
1452 
1453 /* ARGSUSED */
1454 static int
1455 pipe_close(fp, td)
1456 	struct file *fp;
1457 	struct thread *td;
1458 {
1459 	struct pipe *cpipe = fp->f_data;
1460 
1461 	fp->f_ops = &badfileops;
1462 	fp->f_data = NULL;
1463 	funsetown(&cpipe->pipe_sigio);
1464 	pipeclose(cpipe);
1465 	return (0);
1466 }
1467 
1468 static void
1469 pipe_free_kmem(cpipe)
1470 	struct pipe *cpipe;
1471 {
1472 
1473 	KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1474 	    ("pipe_free_kmem: pipe mutex locked"));
1475 
1476 	if (cpipe->pipe_buffer.buffer != NULL) {
1477 		atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1478 		vm_map_remove(pipe_map,
1479 		    (vm_offset_t)cpipe->pipe_buffer.buffer,
1480 		    (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1481 		cpipe->pipe_buffer.buffer = NULL;
1482 	}
1483 #ifndef PIPE_NODIRECT
1484 	{
1485 		cpipe->pipe_map.cnt = 0;
1486 		cpipe->pipe_map.pos = 0;
1487 		cpipe->pipe_map.npages = 0;
1488 	}
1489 #endif
1490 }
1491 
1492 /*
1493  * shutdown the pipe
1494  */
1495 static void
1496 pipeclose(cpipe)
1497 	struct pipe *cpipe;
1498 {
1499 	struct pipepair *pp;
1500 	struct pipe *ppipe;
1501 	ino_t ino;
1502 
1503 	KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1504 
1505 	PIPE_LOCK(cpipe);
1506 	pipelock(cpipe, 0);
1507 	pp = cpipe->pipe_pair;
1508 
1509 	pipeselwakeup(cpipe);
1510 
1511 	/*
1512 	 * If the other side is blocked, wake it up saying that
1513 	 * we want to close it down.
1514 	 */
1515 	cpipe->pipe_state |= PIPE_EOF;
1516 	while (cpipe->pipe_busy) {
1517 		wakeup(cpipe);
1518 		cpipe->pipe_state |= PIPE_WANT;
1519 		pipeunlock(cpipe);
1520 		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1521 		pipelock(cpipe, 0);
1522 	}
1523 
1524 
1525 	/*
1526 	 * Disconnect from peer, if any.
1527 	 */
1528 	ppipe = cpipe->pipe_peer;
1529 	if (ppipe->pipe_present == PIPE_ACTIVE) {
1530 		pipeselwakeup(ppipe);
1531 
1532 		ppipe->pipe_state |= PIPE_EOF;
1533 		wakeup(ppipe);
1534 		KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1535 	}
1536 
1537 	/*
1538 	 * Mark this endpoint as free.  Release kmem resources.  We
1539 	 * don't mark this endpoint as unused until we've finished
1540 	 * doing that, or the pipe might disappear out from under
1541 	 * us.
1542 	 */
1543 	PIPE_UNLOCK(cpipe);
1544 	pipe_free_kmem(cpipe);
1545 	PIPE_LOCK(cpipe);
1546 	cpipe->pipe_present = PIPE_CLOSING;
1547 	pipeunlock(cpipe);
1548 
1549 	/*
1550 	 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1551 	 * PIPE_FINALIZED, that allows other end to free the
1552 	 * pipe_pair, only after the knotes are completely dismantled.
1553 	 */
1554 	knlist_clear(&cpipe->pipe_sel.si_note, 1);
1555 	cpipe->pipe_present = PIPE_FINALIZED;
1556 	seldrain(&cpipe->pipe_sel);
1557 	knlist_destroy(&cpipe->pipe_sel.si_note);
1558 
1559 	/*
1560 	 * Postpone the destroy of the fake inode number allocated for
1561 	 * our end, until pipe mtx is unlocked.
1562 	 */
1563 	ino = cpipe->pipe_ino;
1564 
1565 	/*
1566 	 * If both endpoints are now closed, release the memory for the
1567 	 * pipe pair.  If not, unlock.
1568 	 */
1569 	if (ppipe->pipe_present == PIPE_FINALIZED) {
1570 		PIPE_UNLOCK(cpipe);
1571 #ifdef MAC
1572 		mac_pipe_destroy(pp);
1573 #endif
1574 		uma_zfree(pipe_zone, cpipe->pipe_pair);
1575 	} else
1576 		PIPE_UNLOCK(cpipe);
1577 
1578 	if (ino != 0 && ino != (ino_t)-1)
1579 		free_unr(pipeino_unr, ino);
1580 }
1581 
1582 /*ARGSUSED*/
1583 static int
1584 pipe_kqfilter(struct file *fp, struct knote *kn)
1585 {
1586 	struct pipe *cpipe;
1587 
1588 	cpipe = kn->kn_fp->f_data;
1589 	PIPE_LOCK(cpipe);
1590 	switch (kn->kn_filter) {
1591 	case EVFILT_READ:
1592 		kn->kn_fop = &pipe_rfiltops;
1593 		break;
1594 	case EVFILT_WRITE:
1595 		kn->kn_fop = &pipe_wfiltops;
1596 		if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1597 			/* other end of pipe has been closed */
1598 			PIPE_UNLOCK(cpipe);
1599 			return (EPIPE);
1600 		}
1601 		cpipe = cpipe->pipe_peer;
1602 		break;
1603 	default:
1604 		PIPE_UNLOCK(cpipe);
1605 		return (EINVAL);
1606 	}
1607 
1608 	knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1609 	PIPE_UNLOCK(cpipe);
1610 	return (0);
1611 }
1612 
1613 static void
1614 filt_pipedetach(struct knote *kn)
1615 {
1616 	struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1617 
1618 	PIPE_LOCK(cpipe);
1619 	if (kn->kn_filter == EVFILT_WRITE)
1620 		cpipe = cpipe->pipe_peer;
1621 	knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1622 	PIPE_UNLOCK(cpipe);
1623 }
1624 
1625 /*ARGSUSED*/
1626 static int
1627 filt_piperead(struct knote *kn, long hint)
1628 {
1629 	struct pipe *rpipe = kn->kn_fp->f_data;
1630 	struct pipe *wpipe = rpipe->pipe_peer;
1631 	int ret;
1632 
1633 	PIPE_LOCK(rpipe);
1634 	kn->kn_data = rpipe->pipe_buffer.cnt;
1635 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1636 		kn->kn_data = rpipe->pipe_map.cnt;
1637 
1638 	if ((rpipe->pipe_state & PIPE_EOF) ||
1639 	    wpipe->pipe_present != PIPE_ACTIVE ||
1640 	    (wpipe->pipe_state & PIPE_EOF)) {
1641 		kn->kn_flags |= EV_EOF;
1642 		PIPE_UNLOCK(rpipe);
1643 		return (1);
1644 	}
1645 	ret = kn->kn_data > 0;
1646 	PIPE_UNLOCK(rpipe);
1647 	return ret;
1648 }
1649 
1650 /*ARGSUSED*/
1651 static int
1652 filt_pipewrite(struct knote *kn, long hint)
1653 {
1654 	struct pipe *rpipe = kn->kn_fp->f_data;
1655 	struct pipe *wpipe = rpipe->pipe_peer;
1656 
1657 	PIPE_LOCK(rpipe);
1658 	if (wpipe->pipe_present != PIPE_ACTIVE ||
1659 	    (wpipe->pipe_state & PIPE_EOF)) {
1660 		kn->kn_data = 0;
1661 		kn->kn_flags |= EV_EOF;
1662 		PIPE_UNLOCK(rpipe);
1663 		return (1);
1664 	}
1665 	kn->kn_data = (wpipe->pipe_buffer.size > 0) ?
1666 	    (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) : PIPE_BUF;
1667 	if (wpipe->pipe_state & PIPE_DIRECTW)
1668 		kn->kn_data = 0;
1669 
1670 	PIPE_UNLOCK(rpipe);
1671 	return (kn->kn_data >= PIPE_BUF);
1672 }
1673