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$");
96 #include <sys/param.h>
97 #include <sys/systm.h>
98 #include <sys/fcntl.h>
100 #include <sys/filedesc.h>
101 #include <sys/filio.h>
102 #include <sys/kernel.h>
103 #include <sys/lock.h>
105 #include <sys/mutex.h>
106 #include <sys/ttycom.h>
107 #include <sys/stat.h>
108 #include <sys/malloc.h>
109 #include <sys/poll.h>
110 #include <sys/selinfo.h>
111 #include <sys/signalvar.h>
112 #include <sys/sysctl.h>
113 #include <sys/sysproto.h>
114 #include <sys/pipe.h>
115 #include <sys/proc.h>
116 #include <sys/vnode.h>
118 #include <sys/event.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_ioctl_t pipe_ioctl;
143 static fo_poll_t pipe_poll;
144 static fo_kqfilter_t pipe_kqfilter;
145 static fo_stat_t pipe_stat;
146 static fo_close_t pipe_close;
148 static struct fileops pipeops = {
149 .fo_read = pipe_read,
150 .fo_write = pipe_write,
151 .fo_ioctl = pipe_ioctl,
152 .fo_poll = pipe_poll,
153 .fo_kqfilter = pipe_kqfilter,
154 .fo_stat = pipe_stat,
155 .fo_close = pipe_close,
156 .fo_flags = DFLAG_PASSABLE
159 static void filt_pipedetach(struct knote *kn);
160 static int filt_piperead(struct knote *kn, long hint);
161 static int filt_pipewrite(struct knote *kn, long hint);
163 static struct filterops pipe_rfiltops =
164 { 1, NULL, filt_pipedetach, filt_piperead };
165 static struct filterops pipe_wfiltops =
166 { 1, NULL, filt_pipedetach, filt_pipewrite };
169 * Default pipe buffer size(s), this can be kind-of large now because pipe
170 * space is pageable. The pipe code will try to maintain locality of
171 * reference for performance reasons, so small amounts of outstanding I/O
172 * will not wipe the cache.
174 #define MINPIPESIZE (PIPE_SIZE/3)
175 #define MAXPIPESIZE (2*PIPE_SIZE/3)
177 static int amountpipes;
178 static int amountpipekva;
179 static int pipefragretry;
180 static int pipeallocfail;
181 static int piperesizefail;
182 static int piperesizeallowed = 1;
184 SYSCTL_DECL(_kern_ipc);
186 SYSCTL_INT(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
187 &maxpipekva, 0, "Pipe KVA limit");
188 SYSCTL_INT(_kern_ipc, OID_AUTO, pipes, CTLFLAG_RD,
189 &amountpipes, 0, "Current # of pipes");
190 SYSCTL_INT(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
191 &amountpipekva, 0, "Pipe KVA usage");
192 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
193 &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
194 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
195 &pipeallocfail, 0, "Pipe allocation failures");
196 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
197 &piperesizefail, 0, "Pipe resize failures");
198 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
199 &piperesizeallowed, 0, "Pipe resizing allowed");
201 static void pipeinit(void *dummy __unused);
202 static void pipeclose(struct pipe *cpipe);
203 static void pipe_free_kmem(struct pipe *cpipe);
204 static int pipe_create(struct pipe *pipe, int backing);
205 static __inline int pipelock(struct pipe *cpipe, int catch);
206 static __inline void pipeunlock(struct pipe *cpipe);
207 static __inline void pipeselwakeup(struct pipe *cpipe);
208 #ifndef PIPE_NODIRECT
209 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
210 static void pipe_destroy_write_buffer(struct pipe *wpipe);
211 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
212 static void pipe_clone_write_buffer(struct pipe *wpipe);
214 static int pipespace(struct pipe *cpipe, int size);
215 static int pipespace_new(struct pipe *cpipe, int size);
217 static int pipe_zone_ctor(void *mem, int size, void *arg, int flags);
218 static void pipe_zone_dtor(void *mem, int size, void *arg);
219 static int pipe_zone_init(void *mem, int size, int flags);
220 static void pipe_zone_fini(void *mem, int size);
222 static uma_zone_t pipe_zone;
224 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
227 pipeinit(void *dummy __unused)
230 pipe_zone = uma_zcreate("PIPE", sizeof(struct pipepair),
231 pipe_zone_ctor, pipe_zone_dtor, pipe_zone_init, pipe_zone_fini,
233 KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
237 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
240 struct pipe *rpipe, *wpipe;
242 KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
244 pp = (struct pipepair *)mem;
247 * We zero both pipe endpoints to make sure all the kmem pointers
248 * are NULL, flag fields are zero'd, etc. We timestamp both
249 * endpoints with the same time.
251 rpipe = &pp->pp_rpipe;
252 bzero(rpipe, sizeof(*rpipe));
253 vfs_timestamp(&rpipe->pipe_ctime);
254 rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
256 wpipe = &pp->pp_wpipe;
257 bzero(wpipe, sizeof(*wpipe));
258 wpipe->pipe_ctime = rpipe->pipe_ctime;
259 wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
261 rpipe->pipe_peer = wpipe;
262 rpipe->pipe_pair = pp;
263 wpipe->pipe_peer = rpipe;
264 wpipe->pipe_pair = pp;
267 * Mark both endpoints as present; they will later get free'd
268 * one at a time. When both are free'd, then the whole pair
271 rpipe->pipe_present = 1;
272 wpipe->pipe_present = 1;
275 * Eventually, the MAC Framework may initialize the label
276 * in ctor or init, but for now we do it elswhere to avoid
277 * blocking in ctor or init.
281 atomic_add_int(&amountpipes, 2);
286 pipe_zone_dtor(void *mem, int size, void *arg)
290 KASSERT(size == sizeof(*pp), ("pipe_zone_dtor: wrong size"));
292 pp = (struct pipepair *)mem;
294 atomic_subtract_int(&amountpipes, 2);
298 pipe_zone_init(void *mem, int size, int flags)
302 KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
304 pp = (struct pipepair *)mem;
306 mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
311 pipe_zone_fini(void *mem, int size)
315 KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
317 pp = (struct pipepair *)mem;
319 mtx_destroy(&pp->pp_mtx);
323 * The pipe system call for the DTYPE_PIPE type of pipes. If we fail,
324 * let the zone pick up the pieces via pipeclose().
331 struct pipe_args /* {
335 struct filedesc *fdp = td->td_proc->p_fd;
336 struct file *rf, *wf;
338 struct pipe *rpipe, *wpipe;
341 pp = uma_zalloc(pipe_zone, M_WAITOK);
344 * The MAC label is shared between the connected endpoints. As a
345 * result mac_init_pipe() and mac_create_pipe() are called once
346 * for the pair, and not on the endpoints.
349 mac_create_pipe(td->td_ucred, pp);
351 rpipe = &pp->pp_rpipe;
352 wpipe = &pp->pp_wpipe;
354 knlist_init(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe), NULL, NULL,
356 knlist_init(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe), NULL, NULL,
359 /* Only the forward direction pipe is backed by default */
360 if ((error = pipe_create(rpipe, 1)) != 0 ||
361 (error = pipe_create(wpipe, 0)) != 0) {
367 rpipe->pipe_state |= PIPE_DIRECTOK;
368 wpipe->pipe_state |= PIPE_DIRECTOK;
370 error = falloc(td, &rf, &fd);
376 /* An extra reference on `rf' has been held for us by falloc(). */
377 td->td_retval[0] = fd;
380 * Warning: once we've gotten past allocation of the fd for the
381 * read-side, we can only drop the read side via fdrop() in order
382 * to avoid races against processes which manage to dup() the read
383 * side while we are blocked trying to allocate the write side.
386 rf->f_flag = FREAD | FWRITE;
387 rf->f_type = DTYPE_PIPE;
389 rf->f_ops = &pipeops;
391 error = falloc(td, &wf, &fd);
393 fdclose(fdp, rf, td->td_retval[0], td);
395 /* rpipe has been closed by fdrop(). */
399 /* An extra reference on `wf' has been held for us by falloc(). */
401 wf->f_flag = FREAD | FWRITE;
402 wf->f_type = DTYPE_PIPE;
404 wf->f_ops = &pipeops;
407 td->td_retval[1] = fd;
414 * Allocate kva for pipe circular buffer, the space is pageable
415 * This routine will 'realloc' the size of a pipe safely, if it fails
416 * it will retain the old buffer.
417 * If it fails it will return ENOMEM.
420 pipespace_new(cpipe, size)
425 int error, cnt, firstseg;
426 static int curfail = 0;
427 static struct timeval lastfail;
429 KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
430 KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
431 ("pipespace: resize of direct writes not allowed"));
433 cnt = cpipe->pipe_buffer.cnt;
437 size = round_page(size);
438 buffer = (caddr_t) vm_map_min(pipe_map);
440 error = vm_map_find(pipe_map, NULL, 0,
441 (vm_offset_t *) &buffer, size, 1,
442 VM_PROT_ALL, VM_PROT_ALL, 0);
443 if (error != KERN_SUCCESS) {
444 if ((cpipe->pipe_buffer.buffer == NULL) &&
445 (size > SMALL_PIPE_SIZE)) {
446 size = SMALL_PIPE_SIZE;
450 if (cpipe->pipe_buffer.buffer == NULL) {
452 if (ppsratecheck(&lastfail, &curfail, 1))
453 printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
460 /* copy data, then free old resources if we're resizing */
462 if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
463 firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
464 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
466 if ((cnt - firstseg) > 0)
467 bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
468 cpipe->pipe_buffer.in);
470 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
474 pipe_free_kmem(cpipe);
475 cpipe->pipe_buffer.buffer = buffer;
476 cpipe->pipe_buffer.size = size;
477 cpipe->pipe_buffer.in = cnt;
478 cpipe->pipe_buffer.out = 0;
479 cpipe->pipe_buffer.cnt = cnt;
480 atomic_add_int(&amountpipekva, cpipe->pipe_buffer.size);
485 * Wrapper for pipespace_new() that performs locking assertions.
488 pipespace(cpipe, size)
493 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
494 ("Unlocked pipe passed to pipespace"));
495 return (pipespace_new(cpipe, size));
499 * lock a pipe for I/O, blocking other access
502 pipelock(cpipe, catch)
508 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
509 while (cpipe->pipe_state & PIPE_LOCKFL) {
510 cpipe->pipe_state |= PIPE_LWANT;
511 error = msleep(cpipe, PIPE_MTX(cpipe),
512 catch ? (PRIBIO | PCATCH) : PRIBIO,
517 cpipe->pipe_state |= PIPE_LOCKFL;
522 * unlock a pipe I/O lock
529 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
530 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
531 ("Unlocked pipe passed to pipeunlock"));
532 cpipe->pipe_state &= ~PIPE_LOCKFL;
533 if (cpipe->pipe_state & PIPE_LWANT) {
534 cpipe->pipe_state &= ~PIPE_LWANT;
544 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
545 if (cpipe->pipe_state & PIPE_SEL) {
546 cpipe->pipe_state &= ~PIPE_SEL;
547 selwakeuppri(&cpipe->pipe_sel, PSOCK);
549 if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
550 pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
551 KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
555 * Initialize and allocate VM and memory for pipe. The structure
556 * will start out zero'd from the ctor, so we just manage the kmem.
559 pipe_create(pipe, backing)
566 if (amountpipekva > maxpipekva / 2)
567 error = pipespace_new(pipe, SMALL_PIPE_SIZE);
569 error = pipespace_new(pipe, PIPE_SIZE);
571 /* If we're not backing this pipe, no need to do anything. */
579 pipe_read(fp, uio, active_cred, flags, td)
582 struct ucred *active_cred;
586 struct pipe *rpipe = fp->f_data;
593 error = pipelock(rpipe, 1);
598 error = mac_check_pipe_read(active_cred, rpipe->pipe_pair);
602 if (amountpipekva > (3 * maxpipekva) / 4) {
603 if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
604 (rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
605 (rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
606 (piperesizeallowed == 1)) {
608 pipespace(rpipe, SMALL_PIPE_SIZE);
613 while (uio->uio_resid) {
615 * normal pipe buffer receive
617 if (rpipe->pipe_buffer.cnt > 0) {
618 size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
619 if (size > rpipe->pipe_buffer.cnt)
620 size = rpipe->pipe_buffer.cnt;
621 if (size > (u_int) uio->uio_resid)
622 size = (u_int) uio->uio_resid;
626 &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
632 rpipe->pipe_buffer.out += size;
633 if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
634 rpipe->pipe_buffer.out = 0;
636 rpipe->pipe_buffer.cnt -= size;
639 * If there is no more to read in the pipe, reset
640 * its pointers to the beginning. This improves
643 if (rpipe->pipe_buffer.cnt == 0) {
644 rpipe->pipe_buffer.in = 0;
645 rpipe->pipe_buffer.out = 0;
648 #ifndef PIPE_NODIRECT
650 * Direct copy, bypassing a kernel buffer.
652 } else if ((size = rpipe->pipe_map.cnt) &&
653 (rpipe->pipe_state & PIPE_DIRECTW)) {
654 if (size > (u_int) uio->uio_resid)
655 size = (u_int) uio->uio_resid;
658 error = uiomove_fromphys(rpipe->pipe_map.ms,
659 rpipe->pipe_map.pos, size, uio);
664 rpipe->pipe_map.pos += size;
665 rpipe->pipe_map.cnt -= size;
666 if (rpipe->pipe_map.cnt == 0) {
667 rpipe->pipe_state &= ~PIPE_DIRECTW;
673 * detect EOF condition
674 * read returns 0 on EOF, no need to set error
676 if (rpipe->pipe_state & PIPE_EOF)
680 * If the "write-side" has been blocked, wake it up now.
682 if (rpipe->pipe_state & PIPE_WANTW) {
683 rpipe->pipe_state &= ~PIPE_WANTW;
688 * Break if some data was read.
694 * Unlock the pipe buffer for our remaining processing.
695 * We will either break out with an error or we will
696 * sleep and relock to loop.
701 * Handle non-blocking mode operation or
702 * wait for more data.
704 if (fp->f_flag & FNONBLOCK) {
707 rpipe->pipe_state |= PIPE_WANTR;
708 if ((error = msleep(rpipe, PIPE_MTX(rpipe),
711 error = pipelock(rpipe, 1);
722 /* XXX: should probably do this before getting any locks. */
724 vfs_timestamp(&rpipe->pipe_atime);
729 * PIPE_WANT processing only makes sense if pipe_busy is 0.
731 if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
732 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
734 } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
736 * Handle write blocking hysteresis.
738 if (rpipe->pipe_state & PIPE_WANTW) {
739 rpipe->pipe_state &= ~PIPE_WANTW;
744 if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
745 pipeselwakeup(rpipe);
751 #ifndef PIPE_NODIRECT
753 * Map the sending processes' buffer into kernel space and wire it.
754 * This is similar to a physical write operation.
757 pipe_build_write_buffer(wpipe, uio)
764 vm_offset_t addr, endaddr;
766 PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
767 KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
768 ("Clone attempt on non-direct write pipe!"));
770 size = (u_int) uio->uio_iov->iov_len;
771 if (size > wpipe->pipe_buffer.size)
772 size = wpipe->pipe_buffer.size;
774 pmap = vmspace_pmap(curproc->p_vmspace);
775 endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
776 addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
777 for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
779 * vm_fault_quick() can sleep. Consequently,
780 * vm_page_lock_queue() and vm_page_unlock_queue()
781 * should not be performed outside of this loop.
784 if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0) {
785 vm_page_lock_queues();
786 for (j = 0; j < i; j++)
787 vm_page_unhold(wpipe->pipe_map.ms[j]);
788 vm_page_unlock_queues();
791 wpipe->pipe_map.ms[i] = pmap_extract_and_hold(pmap, addr,
793 if (wpipe->pipe_map.ms[i] == NULL)
798 * set up the control block
800 wpipe->pipe_map.npages = i;
801 wpipe->pipe_map.pos =
802 ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
803 wpipe->pipe_map.cnt = size;
806 * and update the uio data
809 uio->uio_iov->iov_len -= size;
810 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
811 if (uio->uio_iov->iov_len == 0)
813 uio->uio_resid -= size;
814 uio->uio_offset += size;
819 * unmap and unwire the process buffer
822 pipe_destroy_write_buffer(wpipe)
827 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
828 vm_page_lock_queues();
829 for (i = 0; i < wpipe->pipe_map.npages; i++) {
830 vm_page_unhold(wpipe->pipe_map.ms[i]);
832 vm_page_unlock_queues();
833 wpipe->pipe_map.npages = 0;
837 * In the case of a signal, the writing process might go away. This
838 * code copies the data into the circular buffer so that the source
839 * pages can be freed without loss of data.
842 pipe_clone_write_buffer(wpipe)
850 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
851 size = wpipe->pipe_map.cnt;
852 pos = wpipe->pipe_map.pos;
854 wpipe->pipe_buffer.in = size;
855 wpipe->pipe_buffer.out = 0;
856 wpipe->pipe_buffer.cnt = size;
857 wpipe->pipe_state &= ~PIPE_DIRECTW;
860 iov.iov_base = wpipe->pipe_buffer.buffer;
865 uio.uio_resid = size;
866 uio.uio_segflg = UIO_SYSSPACE;
867 uio.uio_rw = UIO_READ;
868 uio.uio_td = curthread;
869 uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
871 pipe_destroy_write_buffer(wpipe);
875 * This implements the pipe buffer write mechanism. Note that only
876 * a direct write OR a normal pipe write can be pending at any given time.
877 * If there are any characters in the pipe buffer, the direct write will
878 * be deferred until the receiving process grabs all of the bytes from
879 * the pipe buffer. Then the direct mapping write is set-up.
882 pipe_direct_write(wpipe, uio)
889 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
890 error = pipelock(wpipe, 1);
891 if (wpipe->pipe_state & PIPE_EOF)
897 while (wpipe->pipe_state & PIPE_DIRECTW) {
898 if (wpipe->pipe_state & PIPE_WANTR) {
899 wpipe->pipe_state &= ~PIPE_WANTR;
902 wpipe->pipe_state |= PIPE_WANTW;
904 error = msleep(wpipe, PIPE_MTX(wpipe),
905 PRIBIO | PCATCH, "pipdww", 0);
911 wpipe->pipe_map.cnt = 0; /* transfer not ready yet */
912 if (wpipe->pipe_buffer.cnt > 0) {
913 if (wpipe->pipe_state & PIPE_WANTR) {
914 wpipe->pipe_state &= ~PIPE_WANTR;
917 wpipe->pipe_state |= PIPE_WANTW;
919 error = msleep(wpipe, PIPE_MTX(wpipe),
920 PRIBIO | PCATCH, "pipdwc", 0);
927 wpipe->pipe_state |= PIPE_DIRECTW;
930 error = pipe_build_write_buffer(wpipe, uio);
933 wpipe->pipe_state &= ~PIPE_DIRECTW;
939 while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
940 if (wpipe->pipe_state & PIPE_EOF) {
941 pipe_destroy_write_buffer(wpipe);
942 pipeselwakeup(wpipe);
947 if (wpipe->pipe_state & PIPE_WANTR) {
948 wpipe->pipe_state &= ~PIPE_WANTR;
951 pipeselwakeup(wpipe);
953 error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
958 if (wpipe->pipe_state & PIPE_EOF)
960 if (wpipe->pipe_state & PIPE_DIRECTW) {
962 * this bit of trickery substitutes a kernel buffer for
963 * the process that might be going away.
965 pipe_clone_write_buffer(wpipe);
967 pipe_destroy_write_buffer(wpipe);
979 pipe_write(fp, uio, active_cred, flags, td)
982 struct ucred *active_cred;
987 int desiredsize, orig_resid;
988 struct pipe *wpipe, *rpipe;
991 wpipe = rpipe->pipe_peer;
994 error = pipelock(wpipe, 1);
1000 * detect loss of pipe read side, issue SIGPIPE if lost.
1002 if ((!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1008 error = mac_check_pipe_write(active_cred, wpipe->pipe_pair);
1017 /* Choose a larger size if it's advantageous */
1018 desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1019 while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1020 if (piperesizeallowed != 1)
1022 if (amountpipekva > maxpipekva / 2)
1024 if (desiredsize == BIG_PIPE_SIZE)
1026 desiredsize = desiredsize * 2;
1029 /* Choose a smaller size if we're in a OOM situation */
1030 if ((amountpipekva > (3 * maxpipekva) / 4) &&
1031 (wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1032 (wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1033 (piperesizeallowed == 1))
1034 desiredsize = SMALL_PIPE_SIZE;
1036 /* Resize if the above determined that a new size was necessary */
1037 if ((desiredsize != wpipe->pipe_buffer.size) &&
1038 ((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1040 pipespace(wpipe, desiredsize);
1043 if (wpipe->pipe_buffer.size == 0) {
1045 * This can only happen for reverse direction use of pipes
1046 * in a complete OOM situation.
1057 orig_resid = uio->uio_resid;
1059 while (uio->uio_resid) {
1063 if (wpipe->pipe_state & PIPE_EOF) {
1068 #ifndef PIPE_NODIRECT
1070 * If the transfer is large, we can gain performance if
1071 * we do process-to-process copies directly.
1072 * If the write is non-blocking, we don't use the
1073 * direct write mechanism.
1075 * The direct write mechanism will detect the reader going
1078 if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT) &&
1079 (wpipe->pipe_buffer.size >= PIPE_MINDIRECT) &&
1080 (fp->f_flag & FNONBLOCK) == 0) {
1082 error = pipe_direct_write(wpipe, uio);
1090 * Pipe buffered writes cannot be coincidental with
1091 * direct writes. We wait until the currently executing
1092 * direct write is completed before we start filling the
1093 * pipe buffer. We break out if a signal occurs or the
1096 if (wpipe->pipe_state & PIPE_DIRECTW) {
1097 if (wpipe->pipe_state & PIPE_WANTR) {
1098 wpipe->pipe_state &= ~PIPE_WANTR;
1102 error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1110 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1112 /* Writes of size <= PIPE_BUF must be atomic. */
1113 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1117 int size; /* Transfer size */
1118 int segsize; /* first segment to transfer */
1121 * Transfer size is minimum of uio transfer
1122 * and free space in pipe buffer.
1124 if (space > uio->uio_resid)
1125 size = uio->uio_resid;
1129 * First segment to transfer is minimum of
1130 * transfer size and contiguous space in
1131 * pipe buffer. If first segment to transfer
1132 * is less than the transfer size, we've got
1133 * a wraparound in the buffer.
1135 segsize = wpipe->pipe_buffer.size -
1136 wpipe->pipe_buffer.in;
1140 /* Transfer first segment */
1143 error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1147 if (error == 0 && segsize < size) {
1148 KASSERT(wpipe->pipe_buffer.in + segsize ==
1149 wpipe->pipe_buffer.size,
1150 ("Pipe buffer wraparound disappeared"));
1152 * Transfer remaining part now, to
1153 * support atomic writes. Wraparound
1159 &wpipe->pipe_buffer.buffer[0],
1160 size - segsize, uio);
1164 wpipe->pipe_buffer.in += size;
1165 if (wpipe->pipe_buffer.in >=
1166 wpipe->pipe_buffer.size) {
1167 KASSERT(wpipe->pipe_buffer.in ==
1169 wpipe->pipe_buffer.size,
1170 ("Expected wraparound bad"));
1171 wpipe->pipe_buffer.in = size - segsize;
1174 wpipe->pipe_buffer.cnt += size;
1175 KASSERT(wpipe->pipe_buffer.cnt <=
1176 wpipe->pipe_buffer.size,
1177 ("Pipe buffer overflow"));
1184 * If the "read-side" has been blocked, wake it up now.
1186 if (wpipe->pipe_state & PIPE_WANTR) {
1187 wpipe->pipe_state &= ~PIPE_WANTR;
1192 * don't block on non-blocking I/O
1194 if (fp->f_flag & FNONBLOCK) {
1201 * We have no more space and have something to offer,
1202 * wake up select/poll.
1204 pipeselwakeup(wpipe);
1206 wpipe->pipe_state |= PIPE_WANTW;
1208 error = msleep(wpipe, PIPE_MTX(rpipe),
1209 PRIBIO | PCATCH, "pipewr", 0);
1218 if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1219 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1221 } else if (wpipe->pipe_buffer.cnt > 0) {
1223 * If we have put any characters in the buffer, we wake up
1226 if (wpipe->pipe_state & PIPE_WANTR) {
1227 wpipe->pipe_state &= ~PIPE_WANTR;
1233 * Don't return EPIPE if I/O was successful
1235 if ((wpipe->pipe_buffer.cnt == 0) &&
1236 (uio->uio_resid == 0) &&
1242 vfs_timestamp(&wpipe->pipe_mtime);
1245 * We have something to offer,
1246 * wake up select/poll.
1248 if (wpipe->pipe_buffer.cnt)
1249 pipeselwakeup(wpipe);
1257 * we implement a very minimal set of ioctls for compatibility with sockets.
1260 pipe_ioctl(fp, cmd, data, active_cred, td)
1264 struct ucred *active_cred;
1267 struct pipe *mpipe = fp->f_data;
1273 error = mac_check_pipe_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1288 mpipe->pipe_state |= PIPE_ASYNC;
1290 mpipe->pipe_state &= ~PIPE_ASYNC;
1295 if (mpipe->pipe_state & PIPE_DIRECTW)
1296 *(int *)data = mpipe->pipe_map.cnt;
1298 *(int *)data = mpipe->pipe_buffer.cnt;
1303 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1307 *(int *)data = fgetown(&mpipe->pipe_sigio);
1310 /* This is deprecated, FIOSETOWN should be used instead. */
1313 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1316 /* This is deprecated, FIOGETOWN should be used instead. */
1318 *(int *)data = -fgetown(&mpipe->pipe_sigio);
1331 pipe_poll(fp, events, active_cred, td)
1334 struct ucred *active_cred;
1337 struct pipe *rpipe = fp->f_data;
1344 wpipe = rpipe->pipe_peer;
1347 error = mac_check_pipe_poll(active_cred, rpipe->pipe_pair);
1351 if (events & (POLLIN | POLLRDNORM))
1352 if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1353 (rpipe->pipe_buffer.cnt > 0) ||
1354 (rpipe->pipe_state & PIPE_EOF))
1355 revents |= events & (POLLIN | POLLRDNORM);
1357 if (events & (POLLOUT | POLLWRNORM))
1358 if (!wpipe->pipe_present || (wpipe->pipe_state & PIPE_EOF) ||
1359 (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1360 (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1361 revents |= events & (POLLOUT | POLLWRNORM);
1363 if ((rpipe->pipe_state & PIPE_EOF) ||
1364 (!wpipe->pipe_present) ||
1365 (wpipe->pipe_state & PIPE_EOF))
1369 if (events & (POLLIN | POLLRDNORM)) {
1370 selrecord(td, &rpipe->pipe_sel);
1371 rpipe->pipe_state |= PIPE_SEL;
1374 if (events & (POLLOUT | POLLWRNORM)) {
1375 selrecord(td, &wpipe->pipe_sel);
1376 wpipe->pipe_state |= PIPE_SEL;
1388 * We shouldn't need locks here as we're doing a read and this should
1389 * be a natural race.
1392 pipe_stat(fp, ub, active_cred, td)
1395 struct ucred *active_cred;
1398 struct pipe *pipe = fp->f_data;
1403 error = mac_check_pipe_stat(active_cred, pipe->pipe_pair);
1408 bzero(ub, sizeof(*ub));
1409 ub->st_mode = S_IFIFO;
1410 ub->st_blksize = PAGE_SIZE;
1411 if (pipe->pipe_state & PIPE_DIRECTW)
1412 ub->st_size = pipe->pipe_map.cnt;
1414 ub->st_size = pipe->pipe_buffer.cnt;
1415 ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1416 ub->st_atimespec = pipe->pipe_atime;
1417 ub->st_mtimespec = pipe->pipe_mtime;
1418 ub->st_ctimespec = pipe->pipe_ctime;
1419 ub->st_uid = fp->f_cred->cr_uid;
1420 ub->st_gid = fp->f_cred->cr_gid;
1422 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1423 * XXX (st_dev, st_ino) should be unique.
1434 struct pipe *cpipe = fp->f_data;
1436 fp->f_ops = &badfileops;
1438 funsetown(&cpipe->pipe_sigio);
1444 pipe_free_kmem(cpipe)
1448 KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1449 ("pipe_free_kmem: pipe mutex locked"));
1451 if (cpipe->pipe_buffer.buffer != NULL) {
1452 atomic_subtract_int(&amountpipekva, cpipe->pipe_buffer.size);
1453 vm_map_remove(pipe_map,
1454 (vm_offset_t)cpipe->pipe_buffer.buffer,
1455 (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1456 cpipe->pipe_buffer.buffer = NULL;
1458 #ifndef PIPE_NODIRECT
1460 cpipe->pipe_map.cnt = 0;
1461 cpipe->pipe_map.pos = 0;
1462 cpipe->pipe_map.npages = 0;
1474 struct pipepair *pp;
1477 KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1481 pp = cpipe->pipe_pair;
1483 pipeselwakeup(cpipe);
1486 * If the other side is blocked, wake it up saying that
1487 * we want to close it down.
1489 cpipe->pipe_state |= PIPE_EOF;
1490 while (cpipe->pipe_busy) {
1492 cpipe->pipe_state |= PIPE_WANT;
1494 msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1500 * Disconnect from peer, if any.
1502 ppipe = cpipe->pipe_peer;
1503 if (ppipe->pipe_present != 0) {
1504 pipeselwakeup(ppipe);
1506 ppipe->pipe_state |= PIPE_EOF;
1508 KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1512 * Mark this endpoint as free. Release kmem resources. We
1513 * don't mark this endpoint as unused until we've finished
1514 * doing that, or the pipe might disappear out from under
1518 pipe_free_kmem(cpipe);
1520 cpipe->pipe_present = 0;
1522 knlist_clear(&cpipe->pipe_sel.si_note, 1);
1523 knlist_destroy(&cpipe->pipe_sel.si_note);
1526 * If both endpoints are now closed, release the memory for the
1527 * pipe pair. If not, unlock.
1529 if (ppipe->pipe_present == 0) {
1532 mac_destroy_pipe(pp);
1534 uma_zfree(pipe_zone, cpipe->pipe_pair);
1541 pipe_kqfilter(struct file *fp, struct knote *kn)
1545 cpipe = kn->kn_fp->f_data;
1547 switch (kn->kn_filter) {
1549 kn->kn_fop = &pipe_rfiltops;
1552 kn->kn_fop = &pipe_wfiltops;
1553 if (!cpipe->pipe_peer->pipe_present) {
1554 /* other end of pipe has been closed */
1558 cpipe = cpipe->pipe_peer;
1565 knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1571 filt_pipedetach(struct knote *kn)
1573 struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1576 if (kn->kn_filter == EVFILT_WRITE) {
1577 if (!cpipe->pipe_peer->pipe_present) {
1581 cpipe = cpipe->pipe_peer;
1583 knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1589 filt_piperead(struct knote *kn, long hint)
1591 struct pipe *rpipe = kn->kn_fp->f_data;
1592 struct pipe *wpipe = rpipe->pipe_peer;
1596 kn->kn_data = rpipe->pipe_buffer.cnt;
1597 if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1598 kn->kn_data = rpipe->pipe_map.cnt;
1600 if ((rpipe->pipe_state & PIPE_EOF) ||
1601 (!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1602 kn->kn_flags |= EV_EOF;
1606 ret = kn->kn_data > 0;
1613 filt_pipewrite(struct knote *kn, long hint)
1615 struct pipe *rpipe = kn->kn_fp->f_data;
1616 struct pipe *wpipe = rpipe->pipe_peer;
1619 if ((!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1621 kn->kn_flags |= EV_EOF;
1625 kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1626 if (wpipe->pipe_state & PIPE_DIRECTW)
1630 return (kn->kn_data >= PIPE_BUF);