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