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, the sending process pins the underlying pages in
33 * memory, and the receiving process copies directly from these pinned pages
34 * in the sending process.
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_chmod = invfo_chmod,
159 .fo_chown = invfo_chown,
160 .fo_flags = DFLAG_PASSABLE
163 static void filt_pipedetach(struct knote *kn);
164 static int filt_piperead(struct knote *kn, long hint);
165 static int filt_pipewrite(struct knote *kn, long hint);
167 static struct filterops pipe_rfiltops = {
169 .f_detach = filt_pipedetach,
170 .f_event = filt_piperead
172 static struct filterops pipe_wfiltops = {
174 .f_detach = filt_pipedetach,
175 .f_event = filt_pipewrite
179 * Default pipe buffer size(s), this can be kind-of large now because pipe
180 * space is pageable. The pipe code will try to maintain locality of
181 * reference for performance reasons, so small amounts of outstanding I/O
182 * will not wipe the cache.
184 #define MINPIPESIZE (PIPE_SIZE/3)
185 #define MAXPIPESIZE (2*PIPE_SIZE/3)
187 static long amountpipekva;
188 static int pipefragretry;
189 static int pipeallocfail;
190 static int piperesizefail;
191 static int piperesizeallowed = 1;
193 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
194 &maxpipekva, 0, "Pipe KVA limit");
195 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
196 &amountpipekva, 0, "Pipe KVA usage");
197 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
198 &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
199 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
200 &pipeallocfail, 0, "Pipe allocation failures");
201 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
202 &piperesizefail, 0, "Pipe resize failures");
203 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
204 &piperesizeallowed, 0, "Pipe resizing allowed");
206 static void pipeinit(void *dummy __unused);
207 static void pipeclose(struct pipe *cpipe);
208 static void pipe_free_kmem(struct pipe *cpipe);
209 static int pipe_create(struct pipe *pipe, int backing);
210 static __inline int pipelock(struct pipe *cpipe, int catch);
211 static __inline void pipeunlock(struct pipe *cpipe);
212 static __inline void pipeselwakeup(struct pipe *cpipe);
213 #ifndef PIPE_NODIRECT
214 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
215 static void pipe_destroy_write_buffer(struct pipe *wpipe);
216 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
217 static void pipe_clone_write_buffer(struct pipe *wpipe);
219 static int pipespace(struct pipe *cpipe, int size);
220 static int pipespace_new(struct pipe *cpipe, int size);
222 static int pipe_zone_ctor(void *mem, int size, void *arg, int flags);
223 static int pipe_zone_init(void *mem, int size, int flags);
224 static void pipe_zone_fini(void *mem, int size);
226 static uma_zone_t pipe_zone;
228 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
231 pipeinit(void *dummy __unused)
234 pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
235 pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
237 KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
241 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
244 struct pipe *rpipe, *wpipe;
246 KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
248 pp = (struct pipepair *)mem;
251 * We zero both pipe endpoints to make sure all the kmem pointers
252 * are NULL, flag fields are zero'd, etc. We timestamp both
253 * endpoints with the same time.
255 rpipe = &pp->pp_rpipe;
256 bzero(rpipe, sizeof(*rpipe));
257 vfs_timestamp(&rpipe->pipe_ctime);
258 rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
260 wpipe = &pp->pp_wpipe;
261 bzero(wpipe, sizeof(*wpipe));
262 wpipe->pipe_ctime = rpipe->pipe_ctime;
263 wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
265 rpipe->pipe_peer = wpipe;
266 rpipe->pipe_pair = pp;
267 wpipe->pipe_peer = rpipe;
268 wpipe->pipe_pair = pp;
271 * Mark both endpoints as present; they will later get free'd
272 * one at a time. When both are free'd, then the whole pair
275 rpipe->pipe_present = PIPE_ACTIVE;
276 wpipe->pipe_present = PIPE_ACTIVE;
279 * Eventually, the MAC Framework may initialize the label
280 * in ctor or init, but for now we do it elswhere to avoid
281 * blocking in ctor or init.
289 pipe_zone_init(void *mem, int size, int flags)
293 KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
295 pp = (struct pipepair *)mem;
297 mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
302 pipe_zone_fini(void *mem, int size)
306 KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
308 pp = (struct pipepair *)mem;
310 mtx_destroy(&pp->pp_mtx);
314 * The pipe system call for the DTYPE_PIPE type of pipes. If we fail, let
315 * the zone pick up the pieces via pipeclose().
318 kern_pipe(struct thread *td, int fildes[2])
320 struct filedesc *fdp = td->td_proc->p_fd;
321 struct file *rf, *wf;
323 struct pipe *rpipe, *wpipe;
326 pp = uma_zalloc(pipe_zone, M_WAITOK);
329 * The MAC label is shared between the connected endpoints. As a
330 * result mac_pipe_init() and mac_pipe_create() are called once
331 * for the pair, and not on the endpoints.
334 mac_pipe_create(td->td_ucred, pp);
336 rpipe = &pp->pp_rpipe;
337 wpipe = &pp->pp_wpipe;
339 knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
340 knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
342 /* Only the forward direction pipe is backed by default */
343 if ((error = pipe_create(rpipe, 1)) != 0 ||
344 (error = pipe_create(wpipe, 0)) != 0) {
350 rpipe->pipe_state |= PIPE_DIRECTOK;
351 wpipe->pipe_state |= PIPE_DIRECTOK;
353 error = falloc(td, &rf, &fd, 0);
359 /* An extra reference on `rf' has been held for us by falloc(). */
363 * Warning: once we've gotten past allocation of the fd for the
364 * read-side, we can only drop the read side via fdrop() in order
365 * to avoid races against processes which manage to dup() the read
366 * side while we are blocked trying to allocate the write side.
368 finit(rf, FREAD | FWRITE, DTYPE_PIPE, rpipe, &pipeops);
369 error = falloc(td, &wf, &fd, 0);
371 fdclose(fdp, rf, fildes[0], td);
373 /* rpipe has been closed by fdrop(). */
377 /* An extra reference on `wf' has been held for us by falloc(). */
378 finit(wf, FREAD | FWRITE, DTYPE_PIPE, wpipe, &pipeops);
388 sys_pipe(struct thread *td, struct pipe_args *uap)
393 error = kern_pipe(td, fildes);
397 td->td_retval[0] = fildes[0];
398 td->td_retval[1] = fildes[1];
404 * Allocate kva for pipe circular buffer, the space is pageable
405 * This routine will 'realloc' the size of a pipe safely, if it fails
406 * it will retain the old buffer.
407 * If it fails it will return ENOMEM.
410 pipespace_new(cpipe, size)
415 int error, cnt, firstseg;
416 static int curfail = 0;
417 static struct timeval lastfail;
419 KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
420 KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
421 ("pipespace: resize of direct writes not allowed"));
423 cnt = cpipe->pipe_buffer.cnt;
427 size = round_page(size);
428 buffer = (caddr_t) vm_map_min(pipe_map);
430 error = vm_map_find(pipe_map, NULL, 0,
431 (vm_offset_t *) &buffer, size, 1,
432 VM_PROT_ALL, VM_PROT_ALL, 0);
433 if (error != KERN_SUCCESS) {
434 if ((cpipe->pipe_buffer.buffer == NULL) &&
435 (size > SMALL_PIPE_SIZE)) {
436 size = SMALL_PIPE_SIZE;
440 if (cpipe->pipe_buffer.buffer == NULL) {
442 if (ppsratecheck(&lastfail, &curfail, 1))
443 printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
450 /* copy data, then free old resources if we're resizing */
452 if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
453 firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
454 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
456 if ((cnt - firstseg) > 0)
457 bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
458 cpipe->pipe_buffer.in);
460 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
464 pipe_free_kmem(cpipe);
465 cpipe->pipe_buffer.buffer = buffer;
466 cpipe->pipe_buffer.size = size;
467 cpipe->pipe_buffer.in = cnt;
468 cpipe->pipe_buffer.out = 0;
469 cpipe->pipe_buffer.cnt = cnt;
470 atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
475 * Wrapper for pipespace_new() that performs locking assertions.
478 pipespace(cpipe, size)
483 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
484 ("Unlocked pipe passed to pipespace"));
485 return (pipespace_new(cpipe, size));
489 * lock a pipe for I/O, blocking other access
492 pipelock(cpipe, catch)
498 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
499 while (cpipe->pipe_state & PIPE_LOCKFL) {
500 cpipe->pipe_state |= PIPE_LWANT;
501 error = msleep(cpipe, PIPE_MTX(cpipe),
502 catch ? (PRIBIO | PCATCH) : PRIBIO,
507 cpipe->pipe_state |= PIPE_LOCKFL;
512 * unlock a pipe I/O lock
519 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
520 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
521 ("Unlocked pipe passed to pipeunlock"));
522 cpipe->pipe_state &= ~PIPE_LOCKFL;
523 if (cpipe->pipe_state & PIPE_LWANT) {
524 cpipe->pipe_state &= ~PIPE_LWANT;
534 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
535 if (cpipe->pipe_state & PIPE_SEL) {
536 selwakeuppri(&cpipe->pipe_sel, PSOCK);
537 if (!SEL_WAITING(&cpipe->pipe_sel))
538 cpipe->pipe_state &= ~PIPE_SEL;
540 if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
541 pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
542 KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
546 * Initialize and allocate VM and memory for pipe. The structure
547 * will start out zero'd from the ctor, so we just manage the kmem.
550 pipe_create(pipe, backing)
557 if (amountpipekva > maxpipekva / 2)
558 error = pipespace_new(pipe, SMALL_PIPE_SIZE);
560 error = pipespace_new(pipe, PIPE_SIZE);
562 /* If we're not backing this pipe, no need to do anything. */
570 pipe_read(fp, uio, active_cred, flags, td)
573 struct ucred *active_cred;
577 struct pipe *rpipe = fp->f_data;
584 error = pipelock(rpipe, 1);
589 error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
593 if (amountpipekva > (3 * maxpipekva) / 4) {
594 if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
595 (rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
596 (rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
597 (piperesizeallowed == 1)) {
599 pipespace(rpipe, SMALL_PIPE_SIZE);
604 while (uio->uio_resid) {
606 * normal pipe buffer receive
608 if (rpipe->pipe_buffer.cnt > 0) {
609 size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
610 if (size > rpipe->pipe_buffer.cnt)
611 size = rpipe->pipe_buffer.cnt;
612 if (size > (u_int) uio->uio_resid)
613 size = (u_int) uio->uio_resid;
617 &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
623 rpipe->pipe_buffer.out += size;
624 if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
625 rpipe->pipe_buffer.out = 0;
627 rpipe->pipe_buffer.cnt -= size;
630 * If there is no more to read in the pipe, reset
631 * its pointers to the beginning. This improves
634 if (rpipe->pipe_buffer.cnt == 0) {
635 rpipe->pipe_buffer.in = 0;
636 rpipe->pipe_buffer.out = 0;
639 #ifndef PIPE_NODIRECT
641 * Direct copy, bypassing a kernel buffer.
643 } else if ((size = rpipe->pipe_map.cnt) &&
644 (rpipe->pipe_state & PIPE_DIRECTW)) {
645 if (size > (u_int) uio->uio_resid)
646 size = (u_int) uio->uio_resid;
649 error = uiomove_fromphys(rpipe->pipe_map.ms,
650 rpipe->pipe_map.pos, size, uio);
655 rpipe->pipe_map.pos += size;
656 rpipe->pipe_map.cnt -= size;
657 if (rpipe->pipe_map.cnt == 0) {
658 rpipe->pipe_state &= ~PIPE_DIRECTW;
664 * detect EOF condition
665 * read returns 0 on EOF, no need to set error
667 if (rpipe->pipe_state & PIPE_EOF)
671 * If the "write-side" has been blocked, wake it up now.
673 if (rpipe->pipe_state & PIPE_WANTW) {
674 rpipe->pipe_state &= ~PIPE_WANTW;
679 * Break if some data was read.
685 * Unlock the pipe buffer for our remaining processing.
686 * We will either break out with an error or we will
687 * sleep and relock to loop.
692 * Handle non-blocking mode operation or
693 * wait for more data.
695 if (fp->f_flag & FNONBLOCK) {
698 rpipe->pipe_state |= PIPE_WANTR;
699 if ((error = msleep(rpipe, PIPE_MTX(rpipe),
702 error = pipelock(rpipe, 1);
713 /* XXX: should probably do this before getting any locks. */
715 vfs_timestamp(&rpipe->pipe_atime);
720 * PIPE_WANT processing only makes sense if pipe_busy is 0.
722 if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
723 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
725 } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
727 * Handle write blocking hysteresis.
729 if (rpipe->pipe_state & PIPE_WANTW) {
730 rpipe->pipe_state &= ~PIPE_WANTW;
735 if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
736 pipeselwakeup(rpipe);
742 #ifndef PIPE_NODIRECT
744 * Map the sending processes' buffer into kernel space and wire it.
745 * This is similar to a physical write operation.
748 pipe_build_write_buffer(wpipe, uio)
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 if ((i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
764 (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
765 wpipe->pipe_map.ms, PIPENPAGES)) < 0)
769 * set up the control block
771 wpipe->pipe_map.npages = i;
772 wpipe->pipe_map.pos =
773 ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
774 wpipe->pipe_map.cnt = size;
777 * and update the uio data
780 uio->uio_iov->iov_len -= size;
781 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
782 if (uio->uio_iov->iov_len == 0)
784 uio->uio_resid -= size;
785 uio->uio_offset += size;
790 * unmap and unwire the process buffer
793 pipe_destroy_write_buffer(wpipe)
797 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
798 vm_page_unhold_pages(wpipe->pipe_map.ms, wpipe->pipe_map.npages);
799 wpipe->pipe_map.npages = 0;
803 * In the case of a signal, the writing process might go away. This
804 * code copies the data into the circular buffer so that the source
805 * pages can be freed without loss of data.
808 pipe_clone_write_buffer(wpipe)
816 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
817 size = wpipe->pipe_map.cnt;
818 pos = wpipe->pipe_map.pos;
820 wpipe->pipe_buffer.in = size;
821 wpipe->pipe_buffer.out = 0;
822 wpipe->pipe_buffer.cnt = size;
823 wpipe->pipe_state &= ~PIPE_DIRECTW;
826 iov.iov_base = wpipe->pipe_buffer.buffer;
831 uio.uio_resid = size;
832 uio.uio_segflg = UIO_SYSSPACE;
833 uio.uio_rw = UIO_READ;
834 uio.uio_td = curthread;
835 uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
837 pipe_destroy_write_buffer(wpipe);
841 * This implements the pipe buffer write mechanism. Note that only
842 * a direct write OR a normal pipe write can be pending at any given time.
843 * If there are any characters in the pipe buffer, the direct write will
844 * be deferred until the receiving process grabs all of the bytes from
845 * the pipe buffer. Then the direct mapping write is set-up.
848 pipe_direct_write(wpipe, uio)
855 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
856 error = pipelock(wpipe, 1);
857 if (wpipe->pipe_state & PIPE_EOF)
863 while (wpipe->pipe_state & PIPE_DIRECTW) {
864 if (wpipe->pipe_state & PIPE_WANTR) {
865 wpipe->pipe_state &= ~PIPE_WANTR;
868 pipeselwakeup(wpipe);
869 wpipe->pipe_state |= PIPE_WANTW;
871 error = msleep(wpipe, PIPE_MTX(wpipe),
872 PRIBIO | PCATCH, "pipdww", 0);
878 wpipe->pipe_map.cnt = 0; /* transfer not ready yet */
879 if (wpipe->pipe_buffer.cnt > 0) {
880 if (wpipe->pipe_state & PIPE_WANTR) {
881 wpipe->pipe_state &= ~PIPE_WANTR;
884 pipeselwakeup(wpipe);
885 wpipe->pipe_state |= PIPE_WANTW;
887 error = msleep(wpipe, PIPE_MTX(wpipe),
888 PRIBIO | PCATCH, "pipdwc", 0);
895 wpipe->pipe_state |= PIPE_DIRECTW;
898 error = pipe_build_write_buffer(wpipe, uio);
901 wpipe->pipe_state &= ~PIPE_DIRECTW;
907 while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
908 if (wpipe->pipe_state & PIPE_EOF) {
909 pipe_destroy_write_buffer(wpipe);
910 pipeselwakeup(wpipe);
915 if (wpipe->pipe_state & PIPE_WANTR) {
916 wpipe->pipe_state &= ~PIPE_WANTR;
919 pipeselwakeup(wpipe);
921 error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
926 if (wpipe->pipe_state & PIPE_EOF)
928 if (wpipe->pipe_state & PIPE_DIRECTW) {
930 * this bit of trickery substitutes a kernel buffer for
931 * the process that might be going away.
933 pipe_clone_write_buffer(wpipe);
935 pipe_destroy_write_buffer(wpipe);
947 pipe_write(fp, uio, active_cred, flags, td)
950 struct ucred *active_cred;
955 int desiredsize, orig_resid;
956 struct pipe *wpipe, *rpipe;
959 wpipe = rpipe->pipe_peer;
962 error = pipelock(wpipe, 1);
968 * detect loss of pipe read side, issue SIGPIPE if lost.
970 if (wpipe->pipe_present != PIPE_ACTIVE ||
971 (wpipe->pipe_state & PIPE_EOF)) {
977 error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
986 /* Choose a larger size if it's advantageous */
987 desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
988 while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
989 if (piperesizeallowed != 1)
991 if (amountpipekva > maxpipekva / 2)
993 if (desiredsize == BIG_PIPE_SIZE)
995 desiredsize = desiredsize * 2;
998 /* Choose a smaller size if we're in a OOM situation */
999 if ((amountpipekva > (3 * maxpipekva) / 4) &&
1000 (wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1001 (wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1002 (piperesizeallowed == 1))
1003 desiredsize = SMALL_PIPE_SIZE;
1005 /* Resize if the above determined that a new size was necessary */
1006 if ((desiredsize != wpipe->pipe_buffer.size) &&
1007 ((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1009 pipespace(wpipe, desiredsize);
1012 if (wpipe->pipe_buffer.size == 0) {
1014 * This can only happen for reverse direction use of pipes
1015 * in a complete OOM situation.
1026 orig_resid = uio->uio_resid;
1028 while (uio->uio_resid) {
1032 if (wpipe->pipe_state & PIPE_EOF) {
1037 #ifndef PIPE_NODIRECT
1039 * If the transfer is large, we can gain performance if
1040 * we do process-to-process copies directly.
1041 * If the write is non-blocking, we don't use the
1042 * direct write mechanism.
1044 * The direct write mechanism will detect the reader going
1047 if (uio->uio_segflg == UIO_USERSPACE &&
1048 uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1049 wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1050 (fp->f_flag & FNONBLOCK) == 0) {
1052 error = pipe_direct_write(wpipe, uio);
1060 * Pipe buffered writes cannot be coincidental with
1061 * direct writes. We wait until the currently executing
1062 * direct write is completed before we start filling the
1063 * pipe buffer. We break out if a signal occurs or the
1066 if (wpipe->pipe_state & PIPE_DIRECTW) {
1067 if (wpipe->pipe_state & PIPE_WANTR) {
1068 wpipe->pipe_state &= ~PIPE_WANTR;
1071 pipeselwakeup(wpipe);
1072 wpipe->pipe_state |= PIPE_WANTW;
1074 error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1082 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1084 /* Writes of size <= PIPE_BUF must be atomic. */
1085 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1089 int size; /* Transfer size */
1090 int segsize; /* first segment to transfer */
1093 * Transfer size is minimum of uio transfer
1094 * and free space in pipe buffer.
1096 if (space > uio->uio_resid)
1097 size = uio->uio_resid;
1101 * First segment to transfer is minimum of
1102 * transfer size and contiguous space in
1103 * pipe buffer. If first segment to transfer
1104 * is less than the transfer size, we've got
1105 * a wraparound in the buffer.
1107 segsize = wpipe->pipe_buffer.size -
1108 wpipe->pipe_buffer.in;
1112 /* Transfer first segment */
1115 error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1119 if (error == 0 && segsize < size) {
1120 KASSERT(wpipe->pipe_buffer.in + segsize ==
1121 wpipe->pipe_buffer.size,
1122 ("Pipe buffer wraparound disappeared"));
1124 * Transfer remaining part now, to
1125 * support atomic writes. Wraparound
1131 &wpipe->pipe_buffer.buffer[0],
1132 size - segsize, uio);
1136 wpipe->pipe_buffer.in += size;
1137 if (wpipe->pipe_buffer.in >=
1138 wpipe->pipe_buffer.size) {
1139 KASSERT(wpipe->pipe_buffer.in ==
1141 wpipe->pipe_buffer.size,
1142 ("Expected wraparound bad"));
1143 wpipe->pipe_buffer.in = size - segsize;
1146 wpipe->pipe_buffer.cnt += size;
1147 KASSERT(wpipe->pipe_buffer.cnt <=
1148 wpipe->pipe_buffer.size,
1149 ("Pipe buffer overflow"));
1156 * If the "read-side" has been blocked, wake it up now.
1158 if (wpipe->pipe_state & PIPE_WANTR) {
1159 wpipe->pipe_state &= ~PIPE_WANTR;
1164 * don't block on non-blocking I/O
1166 if (fp->f_flag & FNONBLOCK) {
1173 * We have no more space and have something to offer,
1174 * wake up select/poll.
1176 pipeselwakeup(wpipe);
1178 wpipe->pipe_state |= PIPE_WANTW;
1180 error = msleep(wpipe, PIPE_MTX(rpipe),
1181 PRIBIO | PCATCH, "pipewr", 0);
1190 if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1191 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1193 } else if (wpipe->pipe_buffer.cnt > 0) {
1195 * If we have put any characters in the buffer, we wake up
1198 if (wpipe->pipe_state & PIPE_WANTR) {
1199 wpipe->pipe_state &= ~PIPE_WANTR;
1205 * Don't return EPIPE if I/O was successful
1207 if ((wpipe->pipe_buffer.cnt == 0) &&
1208 (uio->uio_resid == 0) &&
1214 vfs_timestamp(&wpipe->pipe_mtime);
1217 * We have something to offer,
1218 * wake up select/poll.
1220 if (wpipe->pipe_buffer.cnt)
1221 pipeselwakeup(wpipe);
1230 pipe_truncate(fp, length, active_cred, td)
1233 struct ucred *active_cred;
1241 * we implement a very minimal set of ioctls for compatibility with sockets.
1244 pipe_ioctl(fp, cmd, data, active_cred, td)
1248 struct ucred *active_cred;
1251 struct pipe *mpipe = fp->f_data;
1257 error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1272 mpipe->pipe_state |= PIPE_ASYNC;
1274 mpipe->pipe_state &= ~PIPE_ASYNC;
1279 if (mpipe->pipe_state & PIPE_DIRECTW)
1280 *(int *)data = mpipe->pipe_map.cnt;
1282 *(int *)data = mpipe->pipe_buffer.cnt;
1287 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1291 *(int *)data = fgetown(&mpipe->pipe_sigio);
1294 /* This is deprecated, FIOSETOWN should be used instead. */
1297 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1300 /* This is deprecated, FIOGETOWN should be used instead. */
1302 *(int *)data = -fgetown(&mpipe->pipe_sigio);
1315 pipe_poll(fp, events, active_cred, td)
1318 struct ucred *active_cred;
1321 struct pipe *rpipe = fp->f_data;
1328 wpipe = rpipe->pipe_peer;
1331 error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1335 if (events & (POLLIN | POLLRDNORM))
1336 if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1337 (rpipe->pipe_buffer.cnt > 0))
1338 revents |= events & (POLLIN | POLLRDNORM);
1340 if (events & (POLLOUT | POLLWRNORM))
1341 if (wpipe->pipe_present != PIPE_ACTIVE ||
1342 (wpipe->pipe_state & PIPE_EOF) ||
1343 (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1344 (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1345 revents |= events & (POLLOUT | POLLWRNORM);
1347 if ((events & POLLINIGNEOF) == 0) {
1348 if (rpipe->pipe_state & PIPE_EOF) {
1349 revents |= (events & (POLLIN | POLLRDNORM));
1350 if (wpipe->pipe_present != PIPE_ACTIVE ||
1351 (wpipe->pipe_state & PIPE_EOF))
1357 if (events & (POLLIN | POLLRDNORM)) {
1358 selrecord(td, &rpipe->pipe_sel);
1359 if (SEL_WAITING(&rpipe->pipe_sel))
1360 rpipe->pipe_state |= PIPE_SEL;
1363 if (events & (POLLOUT | POLLWRNORM)) {
1364 selrecord(td, &wpipe->pipe_sel);
1365 if (SEL_WAITING(&wpipe->pipe_sel))
1366 wpipe->pipe_state |= PIPE_SEL;
1378 * We shouldn't need locks here as we're doing a read and this should
1379 * be a natural race.
1382 pipe_stat(fp, ub, active_cred, td)
1385 struct ucred *active_cred;
1388 struct pipe *pipe = fp->f_data;
1393 error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1398 bzero(ub, sizeof(*ub));
1399 ub->st_mode = S_IFIFO;
1400 ub->st_blksize = PAGE_SIZE;
1401 if (pipe->pipe_state & PIPE_DIRECTW)
1402 ub->st_size = pipe->pipe_map.cnt;
1404 ub->st_size = pipe->pipe_buffer.cnt;
1405 ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1406 ub->st_atim = pipe->pipe_atime;
1407 ub->st_mtim = pipe->pipe_mtime;
1408 ub->st_ctim = pipe->pipe_ctime;
1409 ub->st_uid = fp->f_cred->cr_uid;
1410 ub->st_gid = fp->f_cred->cr_gid;
1412 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1413 * XXX (st_dev, st_ino) should be unique.
1424 struct pipe *cpipe = fp->f_data;
1426 fp->f_ops = &badfileops;
1428 funsetown(&cpipe->pipe_sigio);
1434 pipe_free_kmem(cpipe)
1438 KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1439 ("pipe_free_kmem: pipe mutex locked"));
1441 if (cpipe->pipe_buffer.buffer != NULL) {
1442 atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1443 vm_map_remove(pipe_map,
1444 (vm_offset_t)cpipe->pipe_buffer.buffer,
1445 (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1446 cpipe->pipe_buffer.buffer = NULL;
1448 #ifndef PIPE_NODIRECT
1450 cpipe->pipe_map.cnt = 0;
1451 cpipe->pipe_map.pos = 0;
1452 cpipe->pipe_map.npages = 0;
1464 struct pipepair *pp;
1467 KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1471 pp = cpipe->pipe_pair;
1473 pipeselwakeup(cpipe);
1476 * If the other side is blocked, wake it up saying that
1477 * we want to close it down.
1479 cpipe->pipe_state |= PIPE_EOF;
1480 while (cpipe->pipe_busy) {
1482 cpipe->pipe_state |= PIPE_WANT;
1484 msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1490 * Disconnect from peer, if any.
1492 ppipe = cpipe->pipe_peer;
1493 if (ppipe->pipe_present == PIPE_ACTIVE) {
1494 pipeselwakeup(ppipe);
1496 ppipe->pipe_state |= PIPE_EOF;
1498 KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1502 * Mark this endpoint as free. Release kmem resources. We
1503 * don't mark this endpoint as unused until we've finished
1504 * doing that, or the pipe might disappear out from under
1508 pipe_free_kmem(cpipe);
1510 cpipe->pipe_present = PIPE_CLOSING;
1514 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1515 * PIPE_FINALIZED, that allows other end to free the
1516 * pipe_pair, only after the knotes are completely dismantled.
1518 knlist_clear(&cpipe->pipe_sel.si_note, 1);
1519 cpipe->pipe_present = PIPE_FINALIZED;
1520 seldrain(&cpipe->pipe_sel);
1521 knlist_destroy(&cpipe->pipe_sel.si_note);
1524 * If both endpoints are now closed, release the memory for the
1525 * pipe pair. If not, unlock.
1527 if (ppipe->pipe_present == PIPE_FINALIZED) {
1530 mac_pipe_destroy(pp);
1532 uma_zfree(pipe_zone, cpipe->pipe_pair);
1539 pipe_kqfilter(struct file *fp, struct knote *kn)
1543 cpipe = kn->kn_fp->f_data;
1545 switch (kn->kn_filter) {
1547 kn->kn_fop = &pipe_rfiltops;
1550 kn->kn_fop = &pipe_wfiltops;
1551 if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1552 /* other end of pipe has been closed */
1556 cpipe = cpipe->pipe_peer;
1563 knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1569 filt_pipedetach(struct knote *kn)
1571 struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1574 if (kn->kn_filter == EVFILT_WRITE)
1575 cpipe = cpipe->pipe_peer;
1576 knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1582 filt_piperead(struct knote *kn, long hint)
1584 struct pipe *rpipe = kn->kn_fp->f_data;
1585 struct pipe *wpipe = rpipe->pipe_peer;
1589 kn->kn_data = rpipe->pipe_buffer.cnt;
1590 if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1591 kn->kn_data = rpipe->pipe_map.cnt;
1593 if ((rpipe->pipe_state & PIPE_EOF) ||
1594 wpipe->pipe_present != PIPE_ACTIVE ||
1595 (wpipe->pipe_state & PIPE_EOF)) {
1596 kn->kn_flags |= EV_EOF;
1600 ret = kn->kn_data > 0;
1607 filt_pipewrite(struct knote *kn, long hint)
1609 struct pipe *rpipe = kn->kn_fp->f_data;
1610 struct pipe *wpipe = rpipe->pipe_peer;
1613 if (wpipe->pipe_present != PIPE_ACTIVE ||
1614 (wpipe->pipe_state & PIPE_EOF)) {
1616 kn->kn_flags |= EV_EOF;
1620 kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1621 if (wpipe->pipe_state & PIPE_DIRECTW)
1625 return (kn->kn_data >= PIPE_BUF);