2 * Copyright (c) 1996 John S. Dyson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
16 * 4. Modifications may be freely made to this file if the above conditions
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
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
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.
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.
48 * In order to limit the resource use of pipes, two sysctls exist:
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.
54 * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
55 * memory in use by pipes.
57 * Based on how large pipekva is relative to maxpipekva, the following
61 * New pipes are given 16K of memory backing, pipes may dynamically
62 * grow to as large as 64K where needed.
64 * New pipes are given 4K (or PAGE_SIZE) of memory backing,
65 * existing pipes may NOT grow.
67 * New pipes are given 4K (or PAGE_SIZE) of memory backing,
68 * existing pipes will be shrunk down to 4K whenever possible.
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
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.
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.
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.
91 #include <sys/cdefs.h>
92 __FBSDID("$FreeBSD$");
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/fcntl.h>
98 #include <sys/filedesc.h>
99 #include <sys/filio.h>
100 #include <sys/kernel.h>
101 #include <sys/lock.h>
102 #include <sys/mutex.h>
103 #include <sys/ttycom.h>
104 #include <sys/stat.h>
105 #include <sys/malloc.h>
106 #include <sys/poll.h>
107 #include <sys/selinfo.h>
108 #include <sys/signalvar.h>
109 #include <sys/syscallsubr.h>
110 #include <sys/sysctl.h>
111 #include <sys/sysproto.h>
112 #include <sys/pipe.h>
113 #include <sys/proc.h>
114 #include <sys/vnode.h>
116 #include <sys/event.h>
118 #include <security/mac/mac_framework.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>
126 #include <vm/vm_map.h>
127 #include <vm/vm_page.h>
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
135 /* #define PIPE_NODIRECT */
138 * interfaces to the outside world
140 static fo_rdwr_t pipe_read;
141 static fo_rdwr_t pipe_write;
142 static fo_truncate_t pipe_truncate;
143 static fo_ioctl_t pipe_ioctl;
144 static fo_poll_t pipe_poll;
145 static fo_kqfilter_t pipe_kqfilter;
146 static fo_stat_t pipe_stat;
147 static fo_close_t pipe_close;
149 static struct fileops pipeops = {
150 .fo_read = pipe_read,
151 .fo_write = pipe_write,
152 .fo_truncate = pipe_truncate,
153 .fo_ioctl = pipe_ioctl,
154 .fo_poll = pipe_poll,
155 .fo_kqfilter = pipe_kqfilter,
156 .fo_stat = pipe_stat,
157 .fo_close = pipe_close,
158 .fo_flags = DFLAG_PASSABLE
161 static void filt_pipedetach(struct knote *kn);
162 static int filt_piperead(struct knote *kn, long hint);
163 static int filt_pipewrite(struct knote *kn, long hint);
165 static struct filterops pipe_rfiltops = {
167 .f_detach = filt_pipedetach,
168 .f_event = filt_piperead
170 static struct filterops pipe_wfiltops = {
172 .f_detach = filt_pipedetach,
173 .f_event = filt_pipewrite
177 * Default pipe buffer size(s), this can be kind-of large now because pipe
178 * space is pageable. The pipe code will try to maintain locality of
179 * reference for performance reasons, so small amounts of outstanding I/O
180 * will not wipe the cache.
182 #define MINPIPESIZE (PIPE_SIZE/3)
183 #define MAXPIPESIZE (2*PIPE_SIZE/3)
185 static long amountpipekva;
186 static int pipefragretry;
187 static int pipeallocfail;
188 static int piperesizefail;
189 static int piperesizeallowed = 1;
191 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
192 &maxpipekva, 0, "Pipe KVA limit");
193 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
194 &amountpipekva, 0, "Pipe KVA usage");
195 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
196 &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
197 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
198 &pipeallocfail, 0, "Pipe allocation failures");
199 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
200 &piperesizefail, 0, "Pipe resize failures");
201 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
202 &piperesizeallowed, 0, "Pipe resizing allowed");
204 static void pipeinit(void *dummy __unused);
205 static void pipeclose(struct pipe *cpipe);
206 static void pipe_free_kmem(struct pipe *cpipe);
207 static int pipe_create(struct pipe *pipe, int backing);
208 static __inline int pipelock(struct pipe *cpipe, int catch);
209 static __inline void pipeunlock(struct pipe *cpipe);
210 static __inline void pipeselwakeup(struct pipe *cpipe);
211 #ifndef PIPE_NODIRECT
212 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
213 static void pipe_destroy_write_buffer(struct pipe *wpipe);
214 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
215 static void pipe_clone_write_buffer(struct pipe *wpipe);
217 static int pipespace(struct pipe *cpipe, int size);
218 static int pipespace_new(struct pipe *cpipe, int size);
220 static int pipe_zone_ctor(void *mem, int size, void *arg, int flags);
221 static int pipe_zone_init(void *mem, int size, int flags);
222 static void pipe_zone_fini(void *mem, int size);
224 static uma_zone_t pipe_zone;
226 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
229 pipeinit(void *dummy __unused)
232 pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
233 pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
235 KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
239 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
242 struct pipe *rpipe, *wpipe;
244 KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
246 pp = (struct pipepair *)mem;
249 * We zero both pipe endpoints to make sure all the kmem pointers
250 * are NULL, flag fields are zero'd, etc. We timestamp both
251 * endpoints with the same time.
253 rpipe = &pp->pp_rpipe;
254 bzero(rpipe, sizeof(*rpipe));
255 vfs_timestamp(&rpipe->pipe_ctime);
256 rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
258 wpipe = &pp->pp_wpipe;
259 bzero(wpipe, sizeof(*wpipe));
260 wpipe->pipe_ctime = rpipe->pipe_ctime;
261 wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
263 rpipe->pipe_peer = wpipe;
264 rpipe->pipe_pair = pp;
265 wpipe->pipe_peer = rpipe;
266 wpipe->pipe_pair = pp;
269 * Mark both endpoints as present; they will later get free'd
270 * one at a time. When both are free'd, then the whole pair
273 rpipe->pipe_present = PIPE_ACTIVE;
274 wpipe->pipe_present = PIPE_ACTIVE;
277 * Eventually, the MAC Framework may initialize the label
278 * in ctor or init, but for now we do it elswhere to avoid
279 * blocking in ctor or init.
287 pipe_zone_init(void *mem, int size, int flags)
291 KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
293 pp = (struct pipepair *)mem;
295 mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
300 pipe_zone_fini(void *mem, int size)
304 KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
306 pp = (struct pipepair *)mem;
308 mtx_destroy(&pp->pp_mtx);
312 * The pipe system call for the DTYPE_PIPE type of pipes. If we fail, let
313 * the zone pick up the pieces via pipeclose().
316 kern_pipe(struct thread *td, int fildes[2])
318 struct filedesc *fdp = td->td_proc->p_fd;
319 struct file *rf, *wf;
321 struct pipe *rpipe, *wpipe;
324 pp = uma_zalloc(pipe_zone, M_WAITOK);
327 * The MAC label is shared between the connected endpoints. As a
328 * result mac_pipe_init() and mac_pipe_create() are called once
329 * for the pair, and not on the endpoints.
332 mac_pipe_create(td->td_ucred, pp);
334 rpipe = &pp->pp_rpipe;
335 wpipe = &pp->pp_wpipe;
337 knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
338 knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
340 /* Only the forward direction pipe is backed by default */
341 if ((error = pipe_create(rpipe, 1)) != 0 ||
342 (error = pipe_create(wpipe, 0)) != 0) {
348 rpipe->pipe_state |= PIPE_DIRECTOK;
349 wpipe->pipe_state |= PIPE_DIRECTOK;
351 error = falloc(td, &rf, &fd);
357 /* An extra reference on `rf' has been held for us by falloc(). */
361 * Warning: once we've gotten past allocation of the fd for the
362 * read-side, we can only drop the read side via fdrop() in order
363 * to avoid races against processes which manage to dup() the read
364 * side while we are blocked trying to allocate the write side.
366 finit(rf, FREAD | FWRITE, DTYPE_PIPE, rpipe, &pipeops);
367 error = falloc(td, &wf, &fd);
369 fdclose(fdp, rf, fildes[0], td);
371 /* rpipe has been closed by fdrop(). */
375 /* An extra reference on `wf' has been held for us by falloc(). */
376 finit(wf, FREAD | FWRITE, DTYPE_PIPE, wpipe, &pipeops);
386 pipe(struct thread *td, struct pipe_args *uap)
391 error = kern_pipe(td, fildes);
395 td->td_retval[0] = fildes[0];
396 td->td_retval[1] = fildes[1];
402 * Allocate kva for pipe circular buffer, the space is pageable
403 * This routine will 'realloc' the size of a pipe safely, if it fails
404 * it will retain the old buffer.
405 * If it fails it will return ENOMEM.
408 pipespace_new(cpipe, size)
413 int error, cnt, firstseg;
414 static int curfail = 0;
415 static struct timeval lastfail;
417 KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
418 KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
419 ("pipespace: resize of direct writes not allowed"));
421 cnt = cpipe->pipe_buffer.cnt;
425 size = round_page(size);
426 buffer = (caddr_t) vm_map_min(pipe_map);
428 error = vm_map_find(pipe_map, NULL, 0,
429 (vm_offset_t *) &buffer, size, 1,
430 VM_PROT_ALL, VM_PROT_ALL, 0);
431 if (error != KERN_SUCCESS) {
432 if ((cpipe->pipe_buffer.buffer == NULL) &&
433 (size > SMALL_PIPE_SIZE)) {
434 size = SMALL_PIPE_SIZE;
438 if (cpipe->pipe_buffer.buffer == NULL) {
440 if (ppsratecheck(&lastfail, &curfail, 1))
441 printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
448 /* copy data, then free old resources if we're resizing */
450 if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
451 firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
452 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
454 if ((cnt - firstseg) > 0)
455 bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
456 cpipe->pipe_buffer.in);
458 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
462 pipe_free_kmem(cpipe);
463 cpipe->pipe_buffer.buffer = buffer;
464 cpipe->pipe_buffer.size = size;
465 cpipe->pipe_buffer.in = cnt;
466 cpipe->pipe_buffer.out = 0;
467 cpipe->pipe_buffer.cnt = cnt;
468 atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
473 * Wrapper for pipespace_new() that performs locking assertions.
476 pipespace(cpipe, size)
481 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
482 ("Unlocked pipe passed to pipespace"));
483 return (pipespace_new(cpipe, size));
487 * lock a pipe for I/O, blocking other access
490 pipelock(cpipe, catch)
496 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
497 while (cpipe->pipe_state & PIPE_LOCKFL) {
498 cpipe->pipe_state |= PIPE_LWANT;
499 error = msleep(cpipe, PIPE_MTX(cpipe),
500 catch ? (PRIBIO | PCATCH) : PRIBIO,
505 cpipe->pipe_state |= PIPE_LOCKFL;
510 * unlock a pipe I/O lock
517 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
518 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
519 ("Unlocked pipe passed to pipeunlock"));
520 cpipe->pipe_state &= ~PIPE_LOCKFL;
521 if (cpipe->pipe_state & PIPE_LWANT) {
522 cpipe->pipe_state &= ~PIPE_LWANT;
532 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
533 if (cpipe->pipe_state & PIPE_SEL) {
534 selwakeuppri(&cpipe->pipe_sel, PSOCK);
535 if (!SEL_WAITING(&cpipe->pipe_sel))
536 cpipe->pipe_state &= ~PIPE_SEL;
538 if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
539 pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
540 KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
544 * Initialize and allocate VM and memory for pipe. The structure
545 * will start out zero'd from the ctor, so we just manage the kmem.
548 pipe_create(pipe, backing)
555 if (amountpipekva > maxpipekva / 2)
556 error = pipespace_new(pipe, SMALL_PIPE_SIZE);
558 error = pipespace_new(pipe, PIPE_SIZE);
560 /* If we're not backing this pipe, no need to do anything. */
568 pipe_read(fp, uio, active_cred, flags, td)
571 struct ucred *active_cred;
575 struct pipe *rpipe = fp->f_data;
582 error = pipelock(rpipe, 1);
587 error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
591 if (amountpipekva > (3 * maxpipekva) / 4) {
592 if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
593 (rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
594 (rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
595 (piperesizeallowed == 1)) {
597 pipespace(rpipe, SMALL_PIPE_SIZE);
602 while (uio->uio_resid) {
604 * normal pipe buffer receive
606 if (rpipe->pipe_buffer.cnt > 0) {
607 size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
608 if (size > rpipe->pipe_buffer.cnt)
609 size = rpipe->pipe_buffer.cnt;
610 if (size > (u_int) uio->uio_resid)
611 size = (u_int) uio->uio_resid;
615 &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
621 rpipe->pipe_buffer.out += size;
622 if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
623 rpipe->pipe_buffer.out = 0;
625 rpipe->pipe_buffer.cnt -= size;
628 * If there is no more to read in the pipe, reset
629 * its pointers to the beginning. This improves
632 if (rpipe->pipe_buffer.cnt == 0) {
633 rpipe->pipe_buffer.in = 0;
634 rpipe->pipe_buffer.out = 0;
637 #ifndef PIPE_NODIRECT
639 * Direct copy, bypassing a kernel buffer.
641 } else if ((size = rpipe->pipe_map.cnt) &&
642 (rpipe->pipe_state & PIPE_DIRECTW)) {
643 if (size > (u_int) uio->uio_resid)
644 size = (u_int) uio->uio_resid;
647 error = uiomove_fromphys(rpipe->pipe_map.ms,
648 rpipe->pipe_map.pos, size, uio);
653 rpipe->pipe_map.pos += size;
654 rpipe->pipe_map.cnt -= size;
655 if (rpipe->pipe_map.cnt == 0) {
656 rpipe->pipe_state &= ~PIPE_DIRECTW;
662 * detect EOF condition
663 * read returns 0 on EOF, no need to set error
665 if (rpipe->pipe_state & PIPE_EOF)
669 * If the "write-side" has been blocked, wake it up now.
671 if (rpipe->pipe_state & PIPE_WANTW) {
672 rpipe->pipe_state &= ~PIPE_WANTW;
677 * Break if some data was read.
683 * Unlock the pipe buffer for our remaining processing.
684 * We will either break out with an error or we will
685 * sleep and relock to loop.
690 * Handle non-blocking mode operation or
691 * wait for more data.
693 if (fp->f_flag & FNONBLOCK) {
696 rpipe->pipe_state |= PIPE_WANTR;
697 if ((error = msleep(rpipe, PIPE_MTX(rpipe),
700 error = pipelock(rpipe, 1);
711 /* XXX: should probably do this before getting any locks. */
713 vfs_timestamp(&rpipe->pipe_atime);
718 * PIPE_WANT processing only makes sense if pipe_busy is 0.
720 if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
721 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
723 } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
725 * Handle write blocking hysteresis.
727 if (rpipe->pipe_state & PIPE_WANTW) {
728 rpipe->pipe_state &= ~PIPE_WANTW;
733 if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
734 pipeselwakeup(rpipe);
740 #ifndef PIPE_NODIRECT
742 * Map the sending processes' buffer into kernel space and wire it.
743 * This is similar to a physical write operation.
746 pipe_build_write_buffer(wpipe, uio)
753 vm_offset_t addr, endaddr;
755 PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
756 KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
757 ("Clone attempt on non-direct write pipe!"));
759 size = (u_int) uio->uio_iov->iov_len;
760 if (size > wpipe->pipe_buffer.size)
761 size = wpipe->pipe_buffer.size;
763 pmap = vmspace_pmap(curproc->p_vmspace);
764 endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
765 addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
768 for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
770 * vm_fault_quick() can sleep.
773 if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0) {
774 for (j = 0; j < i; j++) {
775 vm_page_lock(wpipe->pipe_map.ms[j]);
776 vm_page_unhold(wpipe->pipe_map.ms[j]);
777 vm_page_unlock(wpipe->pipe_map.ms[j]);
781 wpipe->pipe_map.ms[i] = pmap_extract_and_hold(pmap, addr,
783 if (wpipe->pipe_map.ms[i] == NULL)
788 * set up the control block
790 wpipe->pipe_map.npages = i;
791 wpipe->pipe_map.pos =
792 ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
793 wpipe->pipe_map.cnt = size;
796 * and update the uio data
799 uio->uio_iov->iov_len -= size;
800 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
801 if (uio->uio_iov->iov_len == 0)
803 uio->uio_resid -= size;
804 uio->uio_offset += size;
809 * unmap and unwire the process buffer
812 pipe_destroy_write_buffer(wpipe)
817 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
818 for (i = 0; i < wpipe->pipe_map.npages; i++) {
819 vm_page_lock(wpipe->pipe_map.ms[i]);
820 vm_page_unhold(wpipe->pipe_map.ms[i]);
821 vm_page_unlock(wpipe->pipe_map.ms[i]);
823 wpipe->pipe_map.npages = 0;
827 * In the case of a signal, the writing process might go away. This
828 * code copies the data into the circular buffer so that the source
829 * pages can be freed without loss of data.
832 pipe_clone_write_buffer(wpipe)
840 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
841 size = wpipe->pipe_map.cnt;
842 pos = wpipe->pipe_map.pos;
844 wpipe->pipe_buffer.in = size;
845 wpipe->pipe_buffer.out = 0;
846 wpipe->pipe_buffer.cnt = size;
847 wpipe->pipe_state &= ~PIPE_DIRECTW;
850 iov.iov_base = wpipe->pipe_buffer.buffer;
855 uio.uio_resid = size;
856 uio.uio_segflg = UIO_SYSSPACE;
857 uio.uio_rw = UIO_READ;
858 uio.uio_td = curthread;
859 uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
861 pipe_destroy_write_buffer(wpipe);
865 * This implements the pipe buffer write mechanism. Note that only
866 * a direct write OR a normal pipe write can be pending at any given time.
867 * If there are any characters in the pipe buffer, the direct write will
868 * be deferred until the receiving process grabs all of the bytes from
869 * the pipe buffer. Then the direct mapping write is set-up.
872 pipe_direct_write(wpipe, uio)
879 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
880 error = pipelock(wpipe, 1);
881 if (wpipe->pipe_state & PIPE_EOF)
887 while (wpipe->pipe_state & PIPE_DIRECTW) {
888 if (wpipe->pipe_state & PIPE_WANTR) {
889 wpipe->pipe_state &= ~PIPE_WANTR;
892 pipeselwakeup(wpipe);
893 wpipe->pipe_state |= PIPE_WANTW;
895 error = msleep(wpipe, PIPE_MTX(wpipe),
896 PRIBIO | PCATCH, "pipdww", 0);
902 wpipe->pipe_map.cnt = 0; /* transfer not ready yet */
903 if (wpipe->pipe_buffer.cnt > 0) {
904 if (wpipe->pipe_state & PIPE_WANTR) {
905 wpipe->pipe_state &= ~PIPE_WANTR;
908 pipeselwakeup(wpipe);
909 wpipe->pipe_state |= PIPE_WANTW;
911 error = msleep(wpipe, PIPE_MTX(wpipe),
912 PRIBIO | PCATCH, "pipdwc", 0);
919 wpipe->pipe_state |= PIPE_DIRECTW;
922 error = pipe_build_write_buffer(wpipe, uio);
925 wpipe->pipe_state &= ~PIPE_DIRECTW;
931 while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
932 if (wpipe->pipe_state & PIPE_EOF) {
933 pipe_destroy_write_buffer(wpipe);
934 pipeselwakeup(wpipe);
939 if (wpipe->pipe_state & PIPE_WANTR) {
940 wpipe->pipe_state &= ~PIPE_WANTR;
943 pipeselwakeup(wpipe);
945 error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
950 if (wpipe->pipe_state & PIPE_EOF)
952 if (wpipe->pipe_state & PIPE_DIRECTW) {
954 * this bit of trickery substitutes a kernel buffer for
955 * the process that might be going away.
957 pipe_clone_write_buffer(wpipe);
959 pipe_destroy_write_buffer(wpipe);
971 pipe_write(fp, uio, active_cred, flags, td)
974 struct ucred *active_cred;
979 int desiredsize, orig_resid;
980 struct pipe *wpipe, *rpipe;
983 wpipe = rpipe->pipe_peer;
986 error = pipelock(wpipe, 1);
992 * detect loss of pipe read side, issue SIGPIPE if lost.
994 if (wpipe->pipe_present != PIPE_ACTIVE ||
995 (wpipe->pipe_state & PIPE_EOF)) {
1001 error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
1010 /* Choose a larger size if it's advantageous */
1011 desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1012 while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1013 if (piperesizeallowed != 1)
1015 if (amountpipekva > maxpipekva / 2)
1017 if (desiredsize == BIG_PIPE_SIZE)
1019 desiredsize = desiredsize * 2;
1022 /* Choose a smaller size if we're in a OOM situation */
1023 if ((amountpipekva > (3 * maxpipekva) / 4) &&
1024 (wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1025 (wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1026 (piperesizeallowed == 1))
1027 desiredsize = SMALL_PIPE_SIZE;
1029 /* Resize if the above determined that a new size was necessary */
1030 if ((desiredsize != wpipe->pipe_buffer.size) &&
1031 ((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1033 pipespace(wpipe, desiredsize);
1036 if (wpipe->pipe_buffer.size == 0) {
1038 * This can only happen for reverse direction use of pipes
1039 * in a complete OOM situation.
1050 orig_resid = uio->uio_resid;
1052 while (uio->uio_resid) {
1056 if (wpipe->pipe_state & PIPE_EOF) {
1061 #ifndef PIPE_NODIRECT
1063 * If the transfer is large, we can gain performance if
1064 * we do process-to-process copies directly.
1065 * If the write is non-blocking, we don't use the
1066 * direct write mechanism.
1068 * The direct write mechanism will detect the reader going
1071 if (uio->uio_segflg == UIO_USERSPACE &&
1072 uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1073 wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1074 (fp->f_flag & FNONBLOCK) == 0) {
1076 error = pipe_direct_write(wpipe, uio);
1084 * Pipe buffered writes cannot be coincidental with
1085 * direct writes. We wait until the currently executing
1086 * direct write is completed before we start filling the
1087 * pipe buffer. We break out if a signal occurs or the
1090 if (wpipe->pipe_state & PIPE_DIRECTW) {
1091 if (wpipe->pipe_state & PIPE_WANTR) {
1092 wpipe->pipe_state &= ~PIPE_WANTR;
1095 pipeselwakeup(wpipe);
1096 wpipe->pipe_state |= PIPE_WANTW;
1098 error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1106 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1108 /* Writes of size <= PIPE_BUF must be atomic. */
1109 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1113 int size; /* Transfer size */
1114 int segsize; /* first segment to transfer */
1117 * Transfer size is minimum of uio transfer
1118 * and free space in pipe buffer.
1120 if (space > uio->uio_resid)
1121 size = uio->uio_resid;
1125 * First segment to transfer is minimum of
1126 * transfer size and contiguous space in
1127 * pipe buffer. If first segment to transfer
1128 * is less than the transfer size, we've got
1129 * a wraparound in the buffer.
1131 segsize = wpipe->pipe_buffer.size -
1132 wpipe->pipe_buffer.in;
1136 /* Transfer first segment */
1139 error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1143 if (error == 0 && segsize < size) {
1144 KASSERT(wpipe->pipe_buffer.in + segsize ==
1145 wpipe->pipe_buffer.size,
1146 ("Pipe buffer wraparound disappeared"));
1148 * Transfer remaining part now, to
1149 * support atomic writes. Wraparound
1155 &wpipe->pipe_buffer.buffer[0],
1156 size - segsize, uio);
1160 wpipe->pipe_buffer.in += size;
1161 if (wpipe->pipe_buffer.in >=
1162 wpipe->pipe_buffer.size) {
1163 KASSERT(wpipe->pipe_buffer.in ==
1165 wpipe->pipe_buffer.size,
1166 ("Expected wraparound bad"));
1167 wpipe->pipe_buffer.in = size - segsize;
1170 wpipe->pipe_buffer.cnt += size;
1171 KASSERT(wpipe->pipe_buffer.cnt <=
1172 wpipe->pipe_buffer.size,
1173 ("Pipe buffer overflow"));
1180 * If the "read-side" has been blocked, wake it up now.
1182 if (wpipe->pipe_state & PIPE_WANTR) {
1183 wpipe->pipe_state &= ~PIPE_WANTR;
1188 * don't block on non-blocking I/O
1190 if (fp->f_flag & FNONBLOCK) {
1197 * We have no more space and have something to offer,
1198 * wake up select/poll.
1200 pipeselwakeup(wpipe);
1202 wpipe->pipe_state |= PIPE_WANTW;
1204 error = msleep(wpipe, PIPE_MTX(rpipe),
1205 PRIBIO | PCATCH, "pipewr", 0);
1214 if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1215 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1217 } else if (wpipe->pipe_buffer.cnt > 0) {
1219 * If we have put any characters in the buffer, we wake up
1222 if (wpipe->pipe_state & PIPE_WANTR) {
1223 wpipe->pipe_state &= ~PIPE_WANTR;
1229 * Don't return EPIPE if I/O was successful
1231 if ((wpipe->pipe_buffer.cnt == 0) &&
1232 (uio->uio_resid == 0) &&
1238 vfs_timestamp(&wpipe->pipe_mtime);
1241 * We have something to offer,
1242 * wake up select/poll.
1244 if (wpipe->pipe_buffer.cnt)
1245 pipeselwakeup(wpipe);
1254 pipe_truncate(fp, length, active_cred, td)
1257 struct ucred *active_cred;
1265 * we implement a very minimal set of ioctls for compatibility with sockets.
1268 pipe_ioctl(fp, cmd, data, active_cred, td)
1272 struct ucred *active_cred;
1275 struct pipe *mpipe = fp->f_data;
1281 error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1296 mpipe->pipe_state |= PIPE_ASYNC;
1298 mpipe->pipe_state &= ~PIPE_ASYNC;
1303 if (mpipe->pipe_state & PIPE_DIRECTW)
1304 *(int *)data = mpipe->pipe_map.cnt;
1306 *(int *)data = mpipe->pipe_buffer.cnt;
1311 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1315 *(int *)data = fgetown(&mpipe->pipe_sigio);
1318 /* This is deprecated, FIOSETOWN should be used instead. */
1321 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1324 /* This is deprecated, FIOGETOWN should be used instead. */
1326 *(int *)data = -fgetown(&mpipe->pipe_sigio);
1339 pipe_poll(fp, events, active_cred, td)
1342 struct ucred *active_cred;
1345 struct pipe *rpipe = fp->f_data;
1352 wpipe = rpipe->pipe_peer;
1355 error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1359 if (events & (POLLIN | POLLRDNORM))
1360 if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1361 (rpipe->pipe_buffer.cnt > 0))
1362 revents |= events & (POLLIN | POLLRDNORM);
1364 if (events & (POLLOUT | POLLWRNORM))
1365 if (wpipe->pipe_present != PIPE_ACTIVE ||
1366 (wpipe->pipe_state & PIPE_EOF) ||
1367 (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1368 (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1369 revents |= events & (POLLOUT | POLLWRNORM);
1371 if ((events & POLLINIGNEOF) == 0) {
1372 if (rpipe->pipe_state & PIPE_EOF) {
1373 revents |= (events & (POLLIN | POLLRDNORM));
1374 if (wpipe->pipe_present != PIPE_ACTIVE ||
1375 (wpipe->pipe_state & PIPE_EOF))
1381 if (events & (POLLIN | POLLRDNORM)) {
1382 selrecord(td, &rpipe->pipe_sel);
1383 if (SEL_WAITING(&rpipe->pipe_sel))
1384 rpipe->pipe_state |= PIPE_SEL;
1387 if (events & (POLLOUT | POLLWRNORM)) {
1388 selrecord(td, &wpipe->pipe_sel);
1389 if (SEL_WAITING(&wpipe->pipe_sel))
1390 wpipe->pipe_state |= PIPE_SEL;
1402 * We shouldn't need locks here as we're doing a read and this should
1403 * be a natural race.
1406 pipe_stat(fp, ub, active_cred, td)
1409 struct ucred *active_cred;
1412 struct pipe *pipe = fp->f_data;
1417 error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1422 bzero(ub, sizeof(*ub));
1423 ub->st_mode = S_IFIFO;
1424 ub->st_blksize = PAGE_SIZE;
1425 if (pipe->pipe_state & PIPE_DIRECTW)
1426 ub->st_size = pipe->pipe_map.cnt;
1428 ub->st_size = pipe->pipe_buffer.cnt;
1429 ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1430 ub->st_atim = pipe->pipe_atime;
1431 ub->st_mtim = pipe->pipe_mtime;
1432 ub->st_ctim = pipe->pipe_ctime;
1433 ub->st_uid = fp->f_cred->cr_uid;
1434 ub->st_gid = fp->f_cred->cr_gid;
1436 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1437 * XXX (st_dev, st_ino) should be unique.
1448 struct pipe *cpipe = fp->f_data;
1450 fp->f_ops = &badfileops;
1452 funsetown(&cpipe->pipe_sigio);
1458 pipe_free_kmem(cpipe)
1462 KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1463 ("pipe_free_kmem: pipe mutex locked"));
1465 if (cpipe->pipe_buffer.buffer != NULL) {
1466 atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1467 vm_map_remove(pipe_map,
1468 (vm_offset_t)cpipe->pipe_buffer.buffer,
1469 (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1470 cpipe->pipe_buffer.buffer = NULL;
1472 #ifndef PIPE_NODIRECT
1474 cpipe->pipe_map.cnt = 0;
1475 cpipe->pipe_map.pos = 0;
1476 cpipe->pipe_map.npages = 0;
1488 struct pipepair *pp;
1491 KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1495 pp = cpipe->pipe_pair;
1497 pipeselwakeup(cpipe);
1500 * If the other side is blocked, wake it up saying that
1501 * we want to close it down.
1503 cpipe->pipe_state |= PIPE_EOF;
1504 while (cpipe->pipe_busy) {
1506 cpipe->pipe_state |= PIPE_WANT;
1508 msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1514 * Disconnect from peer, if any.
1516 ppipe = cpipe->pipe_peer;
1517 if (ppipe->pipe_present == PIPE_ACTIVE) {
1518 pipeselwakeup(ppipe);
1520 ppipe->pipe_state |= PIPE_EOF;
1522 KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1526 * Mark this endpoint as free. Release kmem resources. We
1527 * don't mark this endpoint as unused until we've finished
1528 * doing that, or the pipe might disappear out from under
1532 pipe_free_kmem(cpipe);
1534 cpipe->pipe_present = PIPE_CLOSING;
1538 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1539 * PIPE_FINALIZED, that allows other end to free the
1540 * pipe_pair, only after the knotes are completely dismantled.
1542 knlist_clear(&cpipe->pipe_sel.si_note, 1);
1543 cpipe->pipe_present = PIPE_FINALIZED;
1544 knlist_destroy(&cpipe->pipe_sel.si_note);
1547 * If both endpoints are now closed, release the memory for the
1548 * pipe pair. If not, unlock.
1550 if (ppipe->pipe_present == PIPE_FINALIZED) {
1553 mac_pipe_destroy(pp);
1555 uma_zfree(pipe_zone, cpipe->pipe_pair);
1562 pipe_kqfilter(struct file *fp, struct knote *kn)
1566 cpipe = kn->kn_fp->f_data;
1568 switch (kn->kn_filter) {
1570 kn->kn_fop = &pipe_rfiltops;
1573 kn->kn_fop = &pipe_wfiltops;
1574 if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1575 /* other end of pipe has been closed */
1579 cpipe = cpipe->pipe_peer;
1586 knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1592 filt_pipedetach(struct knote *kn)
1594 struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1597 if (kn->kn_filter == EVFILT_WRITE)
1598 cpipe = cpipe->pipe_peer;
1599 knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1605 filt_piperead(struct knote *kn, long hint)
1607 struct pipe *rpipe = kn->kn_fp->f_data;
1608 struct pipe *wpipe = rpipe->pipe_peer;
1612 kn->kn_data = rpipe->pipe_buffer.cnt;
1613 if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1614 kn->kn_data = rpipe->pipe_map.cnt;
1616 if ((rpipe->pipe_state & PIPE_EOF) ||
1617 wpipe->pipe_present != PIPE_ACTIVE ||
1618 (wpipe->pipe_state & PIPE_EOF)) {
1619 kn->kn_flags |= EV_EOF;
1623 ret = kn->kn_data > 0;
1630 filt_pipewrite(struct knote *kn, long hint)
1632 struct pipe *rpipe = kn->kn_fp->f_data;
1633 struct pipe *wpipe = rpipe->pipe_peer;
1636 if (wpipe->pipe_present != PIPE_ACTIVE ||
1637 (wpipe->pipe_state & PIPE_EOF)) {
1639 kn->kn_flags |= EV_EOF;
1643 kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1644 if (wpipe->pipe_state & PIPE_DIRECTW)
1648 return (kn->kn_data >= PIPE_BUF);