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