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 =
166 { 1, NULL, filt_pipedetach, filt_piperead };
167 static struct filterops pipe_wfiltops =
168 { 1, NULL, filt_pipedetach, filt_pipewrite };
171 * Default pipe buffer size(s), this can be kind-of large now because pipe
172 * space is pageable. The pipe code will try to maintain locality of
173 * reference for performance reasons, so small amounts of outstanding I/O
174 * will not wipe the cache.
176 #define MINPIPESIZE (PIPE_SIZE/3)
177 #define MAXPIPESIZE (2*PIPE_SIZE/3)
179 static long amountpipekva;
180 static int pipefragretry;
181 static int pipeallocfail;
182 static int piperesizefail;
183 static int piperesizeallowed = 1;
185 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
186 &maxpipekva, 0, "Pipe KVA limit");
187 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
188 &amountpipekva, 0, "Pipe KVA usage");
189 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
190 &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
191 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
192 &pipeallocfail, 0, "Pipe allocation failures");
193 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
194 &piperesizefail, 0, "Pipe resize failures");
195 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
196 &piperesizeallowed, 0, "Pipe resizing allowed");
198 static void pipeinit(void *dummy __unused);
199 static void pipeclose(struct pipe *cpipe);
200 static void pipe_free_kmem(struct pipe *cpipe);
201 static int pipe_create(struct pipe *pipe, int backing);
202 static __inline int pipelock(struct pipe *cpipe, int catch);
203 static __inline void pipeunlock(struct pipe *cpipe);
204 static __inline void pipeselwakeup(struct pipe *cpipe);
205 #ifndef PIPE_NODIRECT
206 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
207 static void pipe_destroy_write_buffer(struct pipe *wpipe);
208 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
209 static void pipe_clone_write_buffer(struct pipe *wpipe);
211 static int pipespace(struct pipe *cpipe, int size);
212 static int pipespace_new(struct pipe *cpipe, int size);
214 static int pipe_zone_ctor(void *mem, int size, void *arg, int flags);
215 static int pipe_zone_init(void *mem, int size, int flags);
216 static void pipe_zone_fini(void *mem, int size);
218 static uma_zone_t pipe_zone;
220 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
223 pipeinit(void *dummy __unused)
226 pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
227 pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
229 KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
233 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
236 struct pipe *rpipe, *wpipe;
238 KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
240 pp = (struct pipepair *)mem;
243 * We zero both pipe endpoints to make sure all the kmem pointers
244 * are NULL, flag fields are zero'd, etc. We timestamp both
245 * endpoints with the same time.
247 rpipe = &pp->pp_rpipe;
248 bzero(rpipe, sizeof(*rpipe));
249 vfs_timestamp(&rpipe->pipe_ctime);
250 rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
252 wpipe = &pp->pp_wpipe;
253 bzero(wpipe, sizeof(*wpipe));
254 wpipe->pipe_ctime = rpipe->pipe_ctime;
255 wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
257 rpipe->pipe_peer = wpipe;
258 rpipe->pipe_pair = pp;
259 wpipe->pipe_peer = rpipe;
260 wpipe->pipe_pair = pp;
263 * Mark both endpoints as present; they will later get free'd
264 * one at a time. When both are free'd, then the whole pair
267 rpipe->pipe_present = PIPE_ACTIVE;
268 wpipe->pipe_present = PIPE_ACTIVE;
271 * Eventually, the MAC Framework may initialize the label
272 * in ctor or init, but for now we do it elswhere to avoid
273 * blocking in ctor or init.
281 pipe_zone_init(void *mem, int size, int flags)
285 KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
287 pp = (struct pipepair *)mem;
289 mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
294 pipe_zone_fini(void *mem, int size)
298 KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
300 pp = (struct pipepair *)mem;
302 mtx_destroy(&pp->pp_mtx);
306 * The pipe system call for the DTYPE_PIPE type of pipes. If we fail, let
307 * the zone pick up the pieces via pipeclose().
310 kern_pipe(struct thread *td, int fildes[2])
312 struct filedesc *fdp = td->td_proc->p_fd;
313 struct file *rf, *wf;
315 struct pipe *rpipe, *wpipe;
318 pp = uma_zalloc(pipe_zone, M_WAITOK);
321 * The MAC label is shared between the connected endpoints. As a
322 * result mac_pipe_init() and mac_pipe_create() are called once
323 * for the pair, and not on the endpoints.
326 mac_pipe_create(td->td_ucred, pp);
328 rpipe = &pp->pp_rpipe;
329 wpipe = &pp->pp_wpipe;
331 knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
332 knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
334 /* Only the forward direction pipe is backed by default */
335 if ((error = pipe_create(rpipe, 1)) != 0 ||
336 (error = pipe_create(wpipe, 0)) != 0) {
342 rpipe->pipe_state |= PIPE_DIRECTOK;
343 wpipe->pipe_state |= PIPE_DIRECTOK;
345 error = falloc(td, &rf, &fd);
351 /* An extra reference on `rf' has been held for us by falloc(). */
355 * Warning: once we've gotten past allocation of the fd for the
356 * read-side, we can only drop the read side via fdrop() in order
357 * to avoid races against processes which manage to dup() the read
358 * side while we are blocked trying to allocate the write side.
360 finit(rf, FREAD | FWRITE, DTYPE_PIPE, rpipe, &pipeops);
361 error = falloc(td, &wf, &fd);
363 fdclose(fdp, rf, fildes[0], td);
365 /* rpipe has been closed by fdrop(). */
369 /* An extra reference on `wf' has been held for us by falloc(). */
370 finit(wf, FREAD | FWRITE, DTYPE_PIPE, wpipe, &pipeops);
380 pipe(struct thread *td, struct pipe_args *uap)
385 error = kern_pipe(td, fildes);
389 td->td_retval[0] = fildes[0];
390 td->td_retval[1] = fildes[1];
396 * Allocate kva for pipe circular buffer, the space is pageable
397 * This routine will 'realloc' the size of a pipe safely, if it fails
398 * it will retain the old buffer.
399 * If it fails it will return ENOMEM.
402 pipespace_new(cpipe, size)
407 int error, cnt, firstseg;
408 static int curfail = 0;
409 static struct timeval lastfail;
411 KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
412 KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
413 ("pipespace: resize of direct writes not allowed"));
415 cnt = cpipe->pipe_buffer.cnt;
419 size = round_page(size);
420 buffer = (caddr_t) vm_map_min(pipe_map);
422 error = vm_map_find(pipe_map, NULL, 0,
423 (vm_offset_t *) &buffer, size, 1,
424 VM_PROT_ALL, VM_PROT_ALL, 0);
425 if (error != KERN_SUCCESS) {
426 if ((cpipe->pipe_buffer.buffer == NULL) &&
427 (size > SMALL_PIPE_SIZE)) {
428 size = SMALL_PIPE_SIZE;
432 if (cpipe->pipe_buffer.buffer == NULL) {
434 if (ppsratecheck(&lastfail, &curfail, 1))
435 printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
442 /* copy data, then free old resources if we're resizing */
444 if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
445 firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
446 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
448 if ((cnt - firstseg) > 0)
449 bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
450 cpipe->pipe_buffer.in);
452 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
456 pipe_free_kmem(cpipe);
457 cpipe->pipe_buffer.buffer = buffer;
458 cpipe->pipe_buffer.size = size;
459 cpipe->pipe_buffer.in = cnt;
460 cpipe->pipe_buffer.out = 0;
461 cpipe->pipe_buffer.cnt = cnt;
462 atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
467 * Wrapper for pipespace_new() that performs locking assertions.
470 pipespace(cpipe, size)
475 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
476 ("Unlocked pipe passed to pipespace"));
477 return (pipespace_new(cpipe, size));
481 * lock a pipe for I/O, blocking other access
484 pipelock(cpipe, catch)
490 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
491 while (cpipe->pipe_state & PIPE_LOCKFL) {
492 cpipe->pipe_state |= PIPE_LWANT;
493 error = msleep(cpipe, PIPE_MTX(cpipe),
494 catch ? (PRIBIO | PCATCH) : PRIBIO,
499 cpipe->pipe_state |= PIPE_LOCKFL;
504 * unlock a pipe I/O lock
511 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
512 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
513 ("Unlocked pipe passed to pipeunlock"));
514 cpipe->pipe_state &= ~PIPE_LOCKFL;
515 if (cpipe->pipe_state & PIPE_LWANT) {
516 cpipe->pipe_state &= ~PIPE_LWANT;
526 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
527 if (cpipe->pipe_state & PIPE_SEL) {
528 selwakeuppri(&cpipe->pipe_sel, PSOCK);
529 if (!SEL_WAITING(&cpipe->pipe_sel))
530 cpipe->pipe_state &= ~PIPE_SEL;
532 if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
533 pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
534 KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
538 * Initialize and allocate VM and memory for pipe. The structure
539 * will start out zero'd from the ctor, so we just manage the kmem.
542 pipe_create(pipe, backing)
549 if (amountpipekva > maxpipekva / 2)
550 error = pipespace_new(pipe, SMALL_PIPE_SIZE);
552 error = pipespace_new(pipe, PIPE_SIZE);
554 /* If we're not backing this pipe, no need to do anything. */
562 pipe_read(fp, uio, active_cred, flags, td)
565 struct ucred *active_cred;
569 struct pipe *rpipe = fp->f_data;
576 error = pipelock(rpipe, 1);
581 error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
585 if (amountpipekva > (3 * maxpipekva) / 4) {
586 if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
587 (rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
588 (rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
589 (piperesizeallowed == 1)) {
591 pipespace(rpipe, SMALL_PIPE_SIZE);
596 while (uio->uio_resid) {
598 * normal pipe buffer receive
600 if (rpipe->pipe_buffer.cnt > 0) {
601 size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
602 if (size > rpipe->pipe_buffer.cnt)
603 size = rpipe->pipe_buffer.cnt;
604 if (size > (u_int) uio->uio_resid)
605 size = (u_int) uio->uio_resid;
609 &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
615 rpipe->pipe_buffer.out += size;
616 if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
617 rpipe->pipe_buffer.out = 0;
619 rpipe->pipe_buffer.cnt -= size;
622 * If there is no more to read in the pipe, reset
623 * its pointers to the beginning. This improves
626 if (rpipe->pipe_buffer.cnt == 0) {
627 rpipe->pipe_buffer.in = 0;
628 rpipe->pipe_buffer.out = 0;
631 #ifndef PIPE_NODIRECT
633 * Direct copy, bypassing a kernel buffer.
635 } else if ((size = rpipe->pipe_map.cnt) &&
636 (rpipe->pipe_state & PIPE_DIRECTW)) {
637 if (size > (u_int) uio->uio_resid)
638 size = (u_int) uio->uio_resid;
641 error = uiomove_fromphys(rpipe->pipe_map.ms,
642 rpipe->pipe_map.pos, size, uio);
647 rpipe->pipe_map.pos += size;
648 rpipe->pipe_map.cnt -= size;
649 if (rpipe->pipe_map.cnt == 0) {
650 rpipe->pipe_state &= ~PIPE_DIRECTW;
656 * detect EOF condition
657 * read returns 0 on EOF, no need to set error
659 if (rpipe->pipe_state & PIPE_EOF)
663 * If the "write-side" has been blocked, wake it up now.
665 if (rpipe->pipe_state & PIPE_WANTW) {
666 rpipe->pipe_state &= ~PIPE_WANTW;
671 * Break if some data was read.
677 * Unlock the pipe buffer for our remaining processing.
678 * We will either break out with an error or we will
679 * sleep and relock to loop.
684 * Handle non-blocking mode operation or
685 * wait for more data.
687 if (fp->f_flag & FNONBLOCK) {
690 rpipe->pipe_state |= PIPE_WANTR;
691 if ((error = msleep(rpipe, PIPE_MTX(rpipe),
694 error = pipelock(rpipe, 1);
705 /* XXX: should probably do this before getting any locks. */
707 vfs_timestamp(&rpipe->pipe_atime);
712 * PIPE_WANT processing only makes sense if pipe_busy is 0.
714 if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
715 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
717 } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
719 * Handle write blocking hysteresis.
721 if (rpipe->pipe_state & PIPE_WANTW) {
722 rpipe->pipe_state &= ~PIPE_WANTW;
727 if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
728 pipeselwakeup(rpipe);
734 #ifndef PIPE_NODIRECT
736 * Map the sending processes' buffer into kernel space and wire it.
737 * This is similar to a physical write operation.
740 pipe_build_write_buffer(wpipe, uio)
747 vm_offset_t addr, endaddr;
749 PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
750 KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
751 ("Clone attempt on non-direct write pipe!"));
753 size = (u_int) uio->uio_iov->iov_len;
754 if (size > wpipe->pipe_buffer.size)
755 size = wpipe->pipe_buffer.size;
757 pmap = vmspace_pmap(curproc->p_vmspace);
758 endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
759 addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
762 for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
764 * vm_fault_quick() can sleep. Consequently,
765 * vm_page_lock_queue() and vm_page_unlock_queue()
766 * should not be performed outside of this loop.
769 if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0) {
770 vm_page_lock_queues();
771 for (j = 0; j < i; j++)
772 vm_page_unhold(wpipe->pipe_map.ms[j]);
773 vm_page_unlock_queues();
776 wpipe->pipe_map.ms[i] = pmap_extract_and_hold(pmap, addr,
778 if (wpipe->pipe_map.ms[i] == NULL)
783 * set up the control block
785 wpipe->pipe_map.npages = i;
786 wpipe->pipe_map.pos =
787 ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
788 wpipe->pipe_map.cnt = size;
791 * and update the uio data
794 uio->uio_iov->iov_len -= size;
795 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
796 if (uio->uio_iov->iov_len == 0)
798 uio->uio_resid -= size;
799 uio->uio_offset += size;
804 * unmap and unwire the process buffer
807 pipe_destroy_write_buffer(wpipe)
812 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
813 vm_page_lock_queues();
814 for (i = 0; i < wpipe->pipe_map.npages; i++) {
815 vm_page_unhold(wpipe->pipe_map.ms[i]);
817 vm_page_unlock_queues();
818 wpipe->pipe_map.npages = 0;
822 * In the case of a signal, the writing process might go away. This
823 * code copies the data into the circular buffer so that the source
824 * pages can be freed without loss of data.
827 pipe_clone_write_buffer(wpipe)
835 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
836 size = wpipe->pipe_map.cnt;
837 pos = wpipe->pipe_map.pos;
839 wpipe->pipe_buffer.in = size;
840 wpipe->pipe_buffer.out = 0;
841 wpipe->pipe_buffer.cnt = size;
842 wpipe->pipe_state &= ~PIPE_DIRECTW;
845 iov.iov_base = wpipe->pipe_buffer.buffer;
850 uio.uio_resid = size;
851 uio.uio_segflg = UIO_SYSSPACE;
852 uio.uio_rw = UIO_READ;
853 uio.uio_td = curthread;
854 uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
856 pipe_destroy_write_buffer(wpipe);
860 * This implements the pipe buffer write mechanism. Note that only
861 * a direct write OR a normal pipe write can be pending at any given time.
862 * If there are any characters in the pipe buffer, the direct write will
863 * be deferred until the receiving process grabs all of the bytes from
864 * the pipe buffer. Then the direct mapping write is set-up.
867 pipe_direct_write(wpipe, uio)
874 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
875 error = pipelock(wpipe, 1);
876 if (wpipe->pipe_state & PIPE_EOF)
882 while (wpipe->pipe_state & PIPE_DIRECTW) {
883 if (wpipe->pipe_state & PIPE_WANTR) {
884 wpipe->pipe_state &= ~PIPE_WANTR;
887 pipeselwakeup(wpipe);
888 wpipe->pipe_state |= PIPE_WANTW;
890 error = msleep(wpipe, PIPE_MTX(wpipe),
891 PRIBIO | PCATCH, "pipdww", 0);
897 wpipe->pipe_map.cnt = 0; /* transfer not ready yet */
898 if (wpipe->pipe_buffer.cnt > 0) {
899 if (wpipe->pipe_state & PIPE_WANTR) {
900 wpipe->pipe_state &= ~PIPE_WANTR;
903 pipeselwakeup(wpipe);
904 wpipe->pipe_state |= PIPE_WANTW;
906 error = msleep(wpipe, PIPE_MTX(wpipe),
907 PRIBIO | PCATCH, "pipdwc", 0);
914 wpipe->pipe_state |= PIPE_DIRECTW;
917 error = pipe_build_write_buffer(wpipe, uio);
920 wpipe->pipe_state &= ~PIPE_DIRECTW;
926 while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
927 if (wpipe->pipe_state & PIPE_EOF) {
928 pipe_destroy_write_buffer(wpipe);
929 pipeselwakeup(wpipe);
934 if (wpipe->pipe_state & PIPE_WANTR) {
935 wpipe->pipe_state &= ~PIPE_WANTR;
938 pipeselwakeup(wpipe);
940 error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
945 if (wpipe->pipe_state & PIPE_EOF)
947 if (wpipe->pipe_state & PIPE_DIRECTW) {
949 * this bit of trickery substitutes a kernel buffer for
950 * the process that might be going away.
952 pipe_clone_write_buffer(wpipe);
954 pipe_destroy_write_buffer(wpipe);
966 pipe_write(fp, uio, active_cred, flags, td)
969 struct ucred *active_cred;
974 int desiredsize, orig_resid;
975 struct pipe *wpipe, *rpipe;
978 wpipe = rpipe->pipe_peer;
981 error = pipelock(wpipe, 1);
987 * detect loss of pipe read side, issue SIGPIPE if lost.
989 if (wpipe->pipe_present != PIPE_ACTIVE ||
990 (wpipe->pipe_state & PIPE_EOF)) {
996 error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
1005 /* Choose a larger size if it's advantageous */
1006 desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1007 while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1008 if (piperesizeallowed != 1)
1010 if (amountpipekva > maxpipekva / 2)
1012 if (desiredsize == BIG_PIPE_SIZE)
1014 desiredsize = desiredsize * 2;
1017 /* Choose a smaller size if we're in a OOM situation */
1018 if ((amountpipekva > (3 * maxpipekva) / 4) &&
1019 (wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1020 (wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1021 (piperesizeallowed == 1))
1022 desiredsize = SMALL_PIPE_SIZE;
1024 /* Resize if the above determined that a new size was necessary */
1025 if ((desiredsize != wpipe->pipe_buffer.size) &&
1026 ((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1028 pipespace(wpipe, desiredsize);
1031 if (wpipe->pipe_buffer.size == 0) {
1033 * This can only happen for reverse direction use of pipes
1034 * in a complete OOM situation.
1045 orig_resid = uio->uio_resid;
1047 while (uio->uio_resid) {
1051 if (wpipe->pipe_state & PIPE_EOF) {
1056 #ifndef PIPE_NODIRECT
1058 * If the transfer is large, we can gain performance if
1059 * we do process-to-process copies directly.
1060 * If the write is non-blocking, we don't use the
1061 * direct write mechanism.
1063 * The direct write mechanism will detect the reader going
1066 if (uio->uio_segflg == UIO_USERSPACE &&
1067 uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1068 wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1069 (fp->f_flag & FNONBLOCK) == 0) {
1071 error = pipe_direct_write(wpipe, uio);
1079 * Pipe buffered writes cannot be coincidental with
1080 * direct writes. We wait until the currently executing
1081 * direct write is completed before we start filling the
1082 * pipe buffer. We break out if a signal occurs or the
1085 if (wpipe->pipe_state & PIPE_DIRECTW) {
1086 if (wpipe->pipe_state & PIPE_WANTR) {
1087 wpipe->pipe_state &= ~PIPE_WANTR;
1090 pipeselwakeup(wpipe);
1091 wpipe->pipe_state |= PIPE_WANTW;
1093 error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1101 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1103 /* Writes of size <= PIPE_BUF must be atomic. */
1104 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1108 int size; /* Transfer size */
1109 int segsize; /* first segment to transfer */
1112 * Transfer size is minimum of uio transfer
1113 * and free space in pipe buffer.
1115 if (space > uio->uio_resid)
1116 size = uio->uio_resid;
1120 * First segment to transfer is minimum of
1121 * transfer size and contiguous space in
1122 * pipe buffer. If first segment to transfer
1123 * is less than the transfer size, we've got
1124 * a wraparound in the buffer.
1126 segsize = wpipe->pipe_buffer.size -
1127 wpipe->pipe_buffer.in;
1131 /* Transfer first segment */
1134 error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1138 if (error == 0 && segsize < size) {
1139 KASSERT(wpipe->pipe_buffer.in + segsize ==
1140 wpipe->pipe_buffer.size,
1141 ("Pipe buffer wraparound disappeared"));
1143 * Transfer remaining part now, to
1144 * support atomic writes. Wraparound
1150 &wpipe->pipe_buffer.buffer[0],
1151 size - segsize, uio);
1155 wpipe->pipe_buffer.in += size;
1156 if (wpipe->pipe_buffer.in >=
1157 wpipe->pipe_buffer.size) {
1158 KASSERT(wpipe->pipe_buffer.in ==
1160 wpipe->pipe_buffer.size,
1161 ("Expected wraparound bad"));
1162 wpipe->pipe_buffer.in = size - segsize;
1165 wpipe->pipe_buffer.cnt += size;
1166 KASSERT(wpipe->pipe_buffer.cnt <=
1167 wpipe->pipe_buffer.size,
1168 ("Pipe buffer overflow"));
1175 * If the "read-side" has been blocked, wake it up now.
1177 if (wpipe->pipe_state & PIPE_WANTR) {
1178 wpipe->pipe_state &= ~PIPE_WANTR;
1183 * don't block on non-blocking I/O
1185 if (fp->f_flag & FNONBLOCK) {
1192 * We have no more space and have something to offer,
1193 * wake up select/poll.
1195 pipeselwakeup(wpipe);
1197 wpipe->pipe_state |= PIPE_WANTW;
1199 error = msleep(wpipe, PIPE_MTX(rpipe),
1200 PRIBIO | PCATCH, "pipewr", 0);
1209 if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1210 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1212 } else if (wpipe->pipe_buffer.cnt > 0) {
1214 * If we have put any characters in the buffer, we wake up
1217 if (wpipe->pipe_state & PIPE_WANTR) {
1218 wpipe->pipe_state &= ~PIPE_WANTR;
1224 * Don't return EPIPE if I/O was successful
1226 if ((wpipe->pipe_buffer.cnt == 0) &&
1227 (uio->uio_resid == 0) &&
1233 vfs_timestamp(&wpipe->pipe_mtime);
1236 * We have something to offer,
1237 * wake up select/poll.
1239 if (wpipe->pipe_buffer.cnt)
1240 pipeselwakeup(wpipe);
1249 pipe_truncate(fp, length, active_cred, td)
1252 struct ucred *active_cred;
1260 * we implement a very minimal set of ioctls for compatibility with sockets.
1263 pipe_ioctl(fp, cmd, data, active_cred, td)
1267 struct ucred *active_cred;
1270 struct pipe *mpipe = fp->f_data;
1276 error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1291 mpipe->pipe_state |= PIPE_ASYNC;
1293 mpipe->pipe_state &= ~PIPE_ASYNC;
1298 if (mpipe->pipe_state & PIPE_DIRECTW)
1299 *(int *)data = mpipe->pipe_map.cnt;
1301 *(int *)data = mpipe->pipe_buffer.cnt;
1306 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1310 *(int *)data = fgetown(&mpipe->pipe_sigio);
1313 /* This is deprecated, FIOSETOWN should be used instead. */
1316 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1319 /* This is deprecated, FIOGETOWN should be used instead. */
1321 *(int *)data = -fgetown(&mpipe->pipe_sigio);
1334 pipe_poll(fp, events, active_cred, td)
1337 struct ucred *active_cred;
1340 struct pipe *rpipe = fp->f_data;
1347 wpipe = rpipe->pipe_peer;
1350 error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1354 if (events & (POLLIN | POLLRDNORM))
1355 if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1356 (rpipe->pipe_buffer.cnt > 0))
1357 revents |= events & (POLLIN | POLLRDNORM);
1359 if (events & (POLLOUT | POLLWRNORM))
1360 if (wpipe->pipe_present != PIPE_ACTIVE ||
1361 (wpipe->pipe_state & PIPE_EOF) ||
1362 (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1363 (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1364 revents |= events & (POLLOUT | POLLWRNORM);
1366 if ((events & POLLINIGNEOF) == 0) {
1367 if (rpipe->pipe_state & PIPE_EOF) {
1368 revents |= (events & (POLLIN | POLLRDNORM));
1369 if (wpipe->pipe_present != PIPE_ACTIVE ||
1370 (wpipe->pipe_state & PIPE_EOF))
1376 if (events & (POLLIN | POLLRDNORM)) {
1377 selrecord(td, &rpipe->pipe_sel);
1378 if (SEL_WAITING(&rpipe->pipe_sel))
1379 rpipe->pipe_state |= PIPE_SEL;
1382 if (events & (POLLOUT | POLLWRNORM)) {
1383 selrecord(td, &wpipe->pipe_sel);
1384 if (SEL_WAITING(&wpipe->pipe_sel))
1385 wpipe->pipe_state |= PIPE_SEL;
1397 * We shouldn't need locks here as we're doing a read and this should
1398 * be a natural race.
1401 pipe_stat(fp, ub, active_cred, td)
1404 struct ucred *active_cred;
1407 struct pipe *pipe = fp->f_data;
1412 error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1417 bzero(ub, sizeof(*ub));
1418 ub->st_mode = S_IFIFO;
1419 ub->st_blksize = PAGE_SIZE;
1420 if (pipe->pipe_state & PIPE_DIRECTW)
1421 ub->st_size = pipe->pipe_map.cnt;
1423 ub->st_size = pipe->pipe_buffer.cnt;
1424 ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1425 ub->st_atimespec = pipe->pipe_atime;
1426 ub->st_mtimespec = pipe->pipe_mtime;
1427 ub->st_ctimespec = pipe->pipe_ctime;
1428 ub->st_uid = fp->f_cred->cr_uid;
1429 ub->st_gid = fp->f_cred->cr_gid;
1431 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1432 * XXX (st_dev, st_ino) should be unique.
1443 struct pipe *cpipe = fp->f_data;
1445 fp->f_ops = &badfileops;
1447 funsetown(&cpipe->pipe_sigio);
1453 pipe_free_kmem(cpipe)
1457 KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1458 ("pipe_free_kmem: pipe mutex locked"));
1460 if (cpipe->pipe_buffer.buffer != NULL) {
1461 atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1462 vm_map_remove(pipe_map,
1463 (vm_offset_t)cpipe->pipe_buffer.buffer,
1464 (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1465 cpipe->pipe_buffer.buffer = NULL;
1467 #ifndef PIPE_NODIRECT
1469 cpipe->pipe_map.cnt = 0;
1470 cpipe->pipe_map.pos = 0;
1471 cpipe->pipe_map.npages = 0;
1483 struct pipepair *pp;
1486 KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1490 pp = cpipe->pipe_pair;
1492 pipeselwakeup(cpipe);
1495 * If the other side is blocked, wake it up saying that
1496 * we want to close it down.
1498 cpipe->pipe_state |= PIPE_EOF;
1499 while (cpipe->pipe_busy) {
1501 cpipe->pipe_state |= PIPE_WANT;
1503 msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1509 * Disconnect from peer, if any.
1511 ppipe = cpipe->pipe_peer;
1512 if (ppipe->pipe_present == PIPE_ACTIVE) {
1513 pipeselwakeup(ppipe);
1515 ppipe->pipe_state |= PIPE_EOF;
1517 KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1521 * Mark this endpoint as free. Release kmem resources. We
1522 * don't mark this endpoint as unused until we've finished
1523 * doing that, or the pipe might disappear out from under
1527 pipe_free_kmem(cpipe);
1529 cpipe->pipe_present = PIPE_CLOSING;
1533 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1534 * PIPE_FINALIZED, that allows other end to free the
1535 * pipe_pair, only after the knotes are completely dismantled.
1537 knlist_clear(&cpipe->pipe_sel.si_note, 1);
1538 cpipe->pipe_present = PIPE_FINALIZED;
1539 seldrain(&cpipe->pipe_sel);
1540 knlist_destroy(&cpipe->pipe_sel.si_note);
1543 * If both endpoints are now closed, release the memory for the
1544 * pipe pair. If not, unlock.
1546 if (ppipe->pipe_present == PIPE_FINALIZED) {
1549 mac_pipe_destroy(pp);
1551 uma_zfree(pipe_zone, cpipe->pipe_pair);
1558 pipe_kqfilter(struct file *fp, struct knote *kn)
1562 cpipe = kn->kn_fp->f_data;
1564 switch (kn->kn_filter) {
1566 kn->kn_fop = &pipe_rfiltops;
1569 kn->kn_fop = &pipe_wfiltops;
1570 if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1571 /* other end of pipe has been closed */
1575 cpipe = cpipe->pipe_peer;
1582 knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1588 filt_pipedetach(struct knote *kn)
1590 struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1593 if (kn->kn_filter == EVFILT_WRITE)
1594 cpipe = cpipe->pipe_peer;
1595 knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1601 filt_piperead(struct knote *kn, long hint)
1603 struct pipe *rpipe = kn->kn_fp->f_data;
1604 struct pipe *wpipe = rpipe->pipe_peer;
1608 kn->kn_data = rpipe->pipe_buffer.cnt;
1609 if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1610 kn->kn_data = rpipe->pipe_map.cnt;
1612 if ((rpipe->pipe_state & PIPE_EOF) ||
1613 wpipe->pipe_present != PIPE_ACTIVE ||
1614 (wpipe->pipe_state & PIPE_EOF)) {
1615 kn->kn_flags |= EV_EOF;
1619 ret = kn->kn_data > 0;
1626 filt_pipewrite(struct knote *kn, long hint)
1628 struct pipe *rpipe = kn->kn_fp->f_data;
1629 struct pipe *wpipe = rpipe->pipe_peer;
1632 if (wpipe->pipe_present != PIPE_ACTIVE ||
1633 (wpipe->pipe_state & PIPE_EOF)) {
1635 kn->kn_flags |= EV_EOF;
1639 kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1640 if (wpipe->pipe_state & PIPE_DIRECTW)
1644 return (kn->kn_data >= PIPE_BUF);