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>
104 #include <sys/mutex.h>
105 #include <sys/ttycom.h>
106 #include <sys/stat.h>
107 #include <sys/malloc.h>
108 #include <sys/poll.h>
109 #include <sys/selinfo.h>
110 #include <sys/signalvar.h>
111 #include <sys/sysctl.h>
112 #include <sys/sysproto.h>
113 #include <sys/pipe.h>
114 #include <sys/proc.h>
115 #include <sys/vnode.h>
117 #include <sys/event.h>
119 #include <security/mac/mac_framework.h>
122 #include <vm/vm_param.h>
123 #include <vm/vm_object.h>
124 #include <vm/vm_kern.h>
125 #include <vm/vm_extern.h>
127 #include <vm/vm_map.h>
128 #include <vm/vm_page.h>
132 * Use this define if you want to disable *fancy* VM things. Expect an
133 * approx 30% decrease in transfer rate. This could be useful for
136 /* #define PIPE_NODIRECT */
139 * interfaces to the outside world
141 static fo_rdwr_t pipe_read;
142 static fo_rdwr_t pipe_write;
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_ioctl = pipe_ioctl,
153 .fo_poll = pipe_poll,
154 .fo_kqfilter = pipe_kqfilter,
155 .fo_stat = pipe_stat,
156 .fo_close = pipe_close,
157 .fo_flags = DFLAG_PASSABLE
160 static void filt_pipedetach(struct knote *kn);
161 static int filt_piperead(struct knote *kn, long hint);
162 static int filt_pipewrite(struct knote *kn, long hint);
164 static struct filterops pipe_rfiltops =
165 { 1, NULL, filt_pipedetach, filt_piperead };
166 static struct filterops pipe_wfiltops =
167 { 1, NULL, filt_pipedetach, filt_pipewrite };
170 * Default pipe buffer size(s), this can be kind-of large now because pipe
171 * space is pageable. The pipe code will try to maintain locality of
172 * reference for performance reasons, so small amounts of outstanding I/O
173 * will not wipe the cache.
175 #define MINPIPESIZE (PIPE_SIZE/3)
176 #define MAXPIPESIZE (2*PIPE_SIZE/3)
178 static int amountpipes;
179 static int amountpipekva;
180 static int pipefragretry;
181 static int pipeallocfail;
182 static int piperesizefail;
183 static int piperesizeallowed = 1;
185 SYSCTL_INT(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
186 &maxpipekva, 0, "Pipe KVA limit");
187 SYSCTL_INT(_kern_ipc, OID_AUTO, pipes, CTLFLAG_RD,
188 &amountpipes, 0, "Current # of pipes");
189 SYSCTL_INT(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
190 &amountpipekva, 0, "Pipe KVA usage");
191 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
192 &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
193 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
194 &pipeallocfail, 0, "Pipe allocation failures");
195 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
196 &piperesizefail, 0, "Pipe resize failures");
197 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
198 &piperesizeallowed, 0, "Pipe resizing allowed");
200 static void pipeinit(void *dummy __unused);
201 static void pipeclose(struct pipe *cpipe);
202 static void pipe_free_kmem(struct pipe *cpipe);
203 static int pipe_create(struct pipe *pipe, int backing);
204 static __inline int pipelock(struct pipe *cpipe, int catch);
205 static __inline void pipeunlock(struct pipe *cpipe);
206 static __inline void pipeselwakeup(struct pipe *cpipe);
207 #ifndef PIPE_NODIRECT
208 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
209 static void pipe_destroy_write_buffer(struct pipe *wpipe);
210 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
211 static void pipe_clone_write_buffer(struct pipe *wpipe);
213 static int pipespace(struct pipe *cpipe, int size);
214 static int pipespace_new(struct pipe *cpipe, int size);
216 static int pipe_zone_ctor(void *mem, int size, void *arg, int flags);
217 static void pipe_zone_dtor(void *mem, int size, void *arg);
218 static int pipe_zone_init(void *mem, int size, int flags);
219 static void pipe_zone_fini(void *mem, int size);
221 static uma_zone_t pipe_zone;
223 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
226 pipeinit(void *dummy __unused)
229 pipe_zone = uma_zcreate("PIPE", sizeof(struct pipepair),
230 pipe_zone_ctor, pipe_zone_dtor, pipe_zone_init, pipe_zone_fini,
232 KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
236 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
239 struct pipe *rpipe, *wpipe;
241 KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
243 pp = (struct pipepair *)mem;
246 * We zero both pipe endpoints to make sure all the kmem pointers
247 * are NULL, flag fields are zero'd, etc. We timestamp both
248 * endpoints with the same time.
250 rpipe = &pp->pp_rpipe;
251 bzero(rpipe, sizeof(*rpipe));
252 vfs_timestamp(&rpipe->pipe_ctime);
253 rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
255 wpipe = &pp->pp_wpipe;
256 bzero(wpipe, sizeof(*wpipe));
257 wpipe->pipe_ctime = rpipe->pipe_ctime;
258 wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
260 rpipe->pipe_peer = wpipe;
261 rpipe->pipe_pair = pp;
262 wpipe->pipe_peer = rpipe;
263 wpipe->pipe_pair = pp;
266 * Mark both endpoints as present; they will later get free'd
267 * one at a time. When both are free'd, then the whole pair
270 rpipe->pipe_present = 1;
271 wpipe->pipe_present = 1;
274 * Eventually, the MAC Framework may initialize the label
275 * in ctor or init, but for now we do it elswhere to avoid
276 * blocking in ctor or init.
280 atomic_add_int(&amountpipes, 2);
285 pipe_zone_dtor(void *mem, int size, void *arg)
289 KASSERT(size == sizeof(*pp), ("pipe_zone_dtor: wrong size"));
291 pp = (struct pipepair *)mem;
293 atomic_subtract_int(&amountpipes, 2);
297 pipe_zone_init(void *mem, int size, int flags)
301 KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
303 pp = (struct pipepair *)mem;
305 mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
310 pipe_zone_fini(void *mem, int size)
314 KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
316 pp = (struct pipepair *)mem;
318 mtx_destroy(&pp->pp_mtx);
322 * The pipe system call for the DTYPE_PIPE type of pipes. If we fail, let
323 * the zone pick up the pieces via pipeclose().
329 struct pipe_args /* {
333 struct filedesc *fdp = td->td_proc->p_fd;
334 struct file *rf, *wf;
336 struct pipe *rpipe, *wpipe;
339 pp = uma_zalloc(pipe_zone, M_WAITOK);
342 * The MAC label is shared between the connected endpoints. As a
343 * result mac_init_pipe() and mac_create_pipe() are called once
344 * for the pair, and not on the endpoints.
347 mac_create_pipe(td->td_ucred, pp);
349 rpipe = &pp->pp_rpipe;
350 wpipe = &pp->pp_wpipe;
352 knlist_init(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe), NULL, NULL,
354 knlist_init(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe), NULL, NULL,
357 /* Only the forward direction pipe is backed by default */
358 if ((error = pipe_create(rpipe, 1)) != 0 ||
359 (error = pipe_create(wpipe, 0)) != 0) {
365 rpipe->pipe_state |= PIPE_DIRECTOK;
366 wpipe->pipe_state |= PIPE_DIRECTOK;
368 error = falloc(td, &rf, &fd);
374 /* An extra reference on `rf' has been held for us by falloc(). */
375 td->td_retval[0] = fd;
378 * Warning: once we've gotten past allocation of the fd for the
379 * read-side, we can only drop the read side via fdrop() in order
380 * to avoid races against processes which manage to dup() the read
381 * side while we are blocked trying to allocate the write side.
384 rf->f_flag = FREAD | FWRITE;
385 rf->f_type = DTYPE_PIPE;
387 rf->f_ops = &pipeops;
389 error = falloc(td, &wf, &fd);
391 fdclose(fdp, rf, td->td_retval[0], td);
393 /* rpipe has been closed by fdrop(). */
397 /* An extra reference on `wf' has been held for us by falloc(). */
399 wf->f_flag = FREAD | FWRITE;
400 wf->f_type = DTYPE_PIPE;
402 wf->f_ops = &pipeops;
405 td->td_retval[1] = fd;
412 * Allocate kva for pipe circular buffer, the space is pageable
413 * This routine will 'realloc' the size of a pipe safely, if it fails
414 * it will retain the old buffer.
415 * If it fails it will return ENOMEM.
418 pipespace_new(cpipe, size)
423 int error, cnt, firstseg;
424 static int curfail = 0;
425 static struct timeval lastfail;
427 KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
428 KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
429 ("pipespace: resize of direct writes not allowed"));
431 cnt = cpipe->pipe_buffer.cnt;
435 size = round_page(size);
436 buffer = (caddr_t) vm_map_min(pipe_map);
438 error = vm_map_find(pipe_map, NULL, 0,
439 (vm_offset_t *) &buffer, size, 1,
440 VM_PROT_ALL, VM_PROT_ALL, 0);
441 if (error != KERN_SUCCESS) {
442 if ((cpipe->pipe_buffer.buffer == NULL) &&
443 (size > SMALL_PIPE_SIZE)) {
444 size = SMALL_PIPE_SIZE;
448 if (cpipe->pipe_buffer.buffer == NULL) {
450 if (ppsratecheck(&lastfail, &curfail, 1))
451 printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
458 /* copy data, then free old resources if we're resizing */
460 if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
461 firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
462 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
464 if ((cnt - firstseg) > 0)
465 bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
466 cpipe->pipe_buffer.in);
468 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
472 pipe_free_kmem(cpipe);
473 cpipe->pipe_buffer.buffer = buffer;
474 cpipe->pipe_buffer.size = size;
475 cpipe->pipe_buffer.in = cnt;
476 cpipe->pipe_buffer.out = 0;
477 cpipe->pipe_buffer.cnt = cnt;
478 atomic_add_int(&amountpipekva, cpipe->pipe_buffer.size);
483 * Wrapper for pipespace_new() that performs locking assertions.
486 pipespace(cpipe, size)
491 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
492 ("Unlocked pipe passed to pipespace"));
493 return (pipespace_new(cpipe, size));
497 * lock a pipe for I/O, blocking other access
500 pipelock(cpipe, catch)
506 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
507 while (cpipe->pipe_state & PIPE_LOCKFL) {
508 cpipe->pipe_state |= PIPE_LWANT;
509 error = msleep(cpipe, PIPE_MTX(cpipe),
510 catch ? (PRIBIO | PCATCH) : PRIBIO,
515 cpipe->pipe_state |= PIPE_LOCKFL;
520 * unlock a pipe I/O lock
527 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
528 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
529 ("Unlocked pipe passed to pipeunlock"));
530 cpipe->pipe_state &= ~PIPE_LOCKFL;
531 if (cpipe->pipe_state & PIPE_LWANT) {
532 cpipe->pipe_state &= ~PIPE_LWANT;
542 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
543 if (cpipe->pipe_state & PIPE_SEL) {
544 cpipe->pipe_state &= ~PIPE_SEL;
545 selwakeuppri(&cpipe->pipe_sel, PSOCK);
547 if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
548 pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
549 KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
553 * Initialize and allocate VM and memory for pipe. The structure
554 * will start out zero'd from the ctor, so we just manage the kmem.
557 pipe_create(pipe, backing)
564 if (amountpipekva > maxpipekva / 2)
565 error = pipespace_new(pipe, SMALL_PIPE_SIZE);
567 error = pipespace_new(pipe, PIPE_SIZE);
569 /* If we're not backing this pipe, no need to do anything. */
577 pipe_read(fp, uio, active_cred, flags, td)
580 struct ucred *active_cred;
584 struct pipe *rpipe = fp->f_data;
591 error = pipelock(rpipe, 1);
596 error = mac_check_pipe_read(active_cred, rpipe->pipe_pair);
600 if (amountpipekva > (3 * maxpipekva) / 4) {
601 if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
602 (rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
603 (rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
604 (piperesizeallowed == 1)) {
606 pipespace(rpipe, SMALL_PIPE_SIZE);
611 while (uio->uio_resid) {
613 * normal pipe buffer receive
615 if (rpipe->pipe_buffer.cnt > 0) {
616 size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
617 if (size > rpipe->pipe_buffer.cnt)
618 size = rpipe->pipe_buffer.cnt;
619 if (size > (u_int) uio->uio_resid)
620 size = (u_int) uio->uio_resid;
624 &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
630 rpipe->pipe_buffer.out += size;
631 if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
632 rpipe->pipe_buffer.out = 0;
634 rpipe->pipe_buffer.cnt -= size;
637 * If there is no more to read in the pipe, reset
638 * its pointers to the beginning. This improves
641 if (rpipe->pipe_buffer.cnt == 0) {
642 rpipe->pipe_buffer.in = 0;
643 rpipe->pipe_buffer.out = 0;
646 #ifndef PIPE_NODIRECT
648 * Direct copy, bypassing a kernel buffer.
650 } else if ((size = rpipe->pipe_map.cnt) &&
651 (rpipe->pipe_state & PIPE_DIRECTW)) {
652 if (size > (u_int) uio->uio_resid)
653 size = (u_int) uio->uio_resid;
656 error = uiomove_fromphys(rpipe->pipe_map.ms,
657 rpipe->pipe_map.pos, size, uio);
662 rpipe->pipe_map.pos += size;
663 rpipe->pipe_map.cnt -= size;
664 if (rpipe->pipe_map.cnt == 0) {
665 rpipe->pipe_state &= ~PIPE_DIRECTW;
671 * detect EOF condition
672 * read returns 0 on EOF, no need to set error
674 if (rpipe->pipe_state & PIPE_EOF)
678 * If the "write-side" has been blocked, wake it up now.
680 if (rpipe->pipe_state & PIPE_WANTW) {
681 rpipe->pipe_state &= ~PIPE_WANTW;
686 * Break if some data was read.
692 * Unlock the pipe buffer for our remaining processing.
693 * We will either break out with an error or we will
694 * sleep and relock to loop.
699 * Handle non-blocking mode operation or
700 * wait for more data.
702 if (fp->f_flag & FNONBLOCK) {
705 rpipe->pipe_state |= PIPE_WANTR;
706 if ((error = msleep(rpipe, PIPE_MTX(rpipe),
709 error = pipelock(rpipe, 1);
720 /* XXX: should probably do this before getting any locks. */
722 vfs_timestamp(&rpipe->pipe_atime);
727 * PIPE_WANT processing only makes sense if pipe_busy is 0.
729 if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
730 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
732 } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
734 * Handle write blocking hysteresis.
736 if (rpipe->pipe_state & PIPE_WANTW) {
737 rpipe->pipe_state &= ~PIPE_WANTW;
742 if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
743 pipeselwakeup(rpipe);
749 #ifndef PIPE_NODIRECT
751 * Map the sending processes' buffer into kernel space and wire it.
752 * This is similar to a physical write operation.
755 pipe_build_write_buffer(wpipe, uio)
762 vm_offset_t addr, endaddr;
764 PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
765 KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
766 ("Clone attempt on non-direct write pipe!"));
768 size = (u_int) uio->uio_iov->iov_len;
769 if (size > wpipe->pipe_buffer.size)
770 size = wpipe->pipe_buffer.size;
772 pmap = vmspace_pmap(curproc->p_vmspace);
773 endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
774 addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
775 for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
777 * vm_fault_quick() can sleep. Consequently,
778 * vm_page_lock_queue() and vm_page_unlock_queue()
779 * should not be performed outside of this loop.
782 if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0) {
783 vm_page_lock_queues();
784 for (j = 0; j < i; j++)
785 vm_page_unhold(wpipe->pipe_map.ms[j]);
786 vm_page_unlock_queues();
789 wpipe->pipe_map.ms[i] = pmap_extract_and_hold(pmap, addr,
791 if (wpipe->pipe_map.ms[i] == NULL)
796 * set up the control block
798 wpipe->pipe_map.npages = i;
799 wpipe->pipe_map.pos =
800 ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
801 wpipe->pipe_map.cnt = size;
804 * and update the uio data
807 uio->uio_iov->iov_len -= size;
808 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
809 if (uio->uio_iov->iov_len == 0)
811 uio->uio_resid -= size;
812 uio->uio_offset += size;
817 * unmap and unwire the process buffer
820 pipe_destroy_write_buffer(wpipe)
825 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
826 vm_page_lock_queues();
827 for (i = 0; i < wpipe->pipe_map.npages; i++) {
828 vm_page_unhold(wpipe->pipe_map.ms[i]);
830 vm_page_unlock_queues();
831 wpipe->pipe_map.npages = 0;
835 * In the case of a signal, the writing process might go away. This
836 * code copies the data into the circular buffer so that the source
837 * pages can be freed without loss of data.
840 pipe_clone_write_buffer(wpipe)
848 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
849 size = wpipe->pipe_map.cnt;
850 pos = wpipe->pipe_map.pos;
852 wpipe->pipe_buffer.in = size;
853 wpipe->pipe_buffer.out = 0;
854 wpipe->pipe_buffer.cnt = size;
855 wpipe->pipe_state &= ~PIPE_DIRECTW;
858 iov.iov_base = wpipe->pipe_buffer.buffer;
863 uio.uio_resid = size;
864 uio.uio_segflg = UIO_SYSSPACE;
865 uio.uio_rw = UIO_READ;
866 uio.uio_td = curthread;
867 uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
869 pipe_destroy_write_buffer(wpipe);
873 * This implements the pipe buffer write mechanism. Note that only
874 * a direct write OR a normal pipe write can be pending at any given time.
875 * If there are any characters in the pipe buffer, the direct write will
876 * be deferred until the receiving process grabs all of the bytes from
877 * the pipe buffer. Then the direct mapping write is set-up.
880 pipe_direct_write(wpipe, uio)
887 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
888 error = pipelock(wpipe, 1);
889 if (wpipe->pipe_state & PIPE_EOF)
895 while (wpipe->pipe_state & PIPE_DIRECTW) {
896 if (wpipe->pipe_state & PIPE_WANTR) {
897 wpipe->pipe_state &= ~PIPE_WANTR;
900 wpipe->pipe_state |= PIPE_WANTW;
902 error = msleep(wpipe, PIPE_MTX(wpipe),
903 PRIBIO | PCATCH, "pipdww", 0);
909 wpipe->pipe_map.cnt = 0; /* transfer not ready yet */
910 if (wpipe->pipe_buffer.cnt > 0) {
911 if (wpipe->pipe_state & PIPE_WANTR) {
912 wpipe->pipe_state &= ~PIPE_WANTR;
915 wpipe->pipe_state |= PIPE_WANTW;
917 error = msleep(wpipe, PIPE_MTX(wpipe),
918 PRIBIO | PCATCH, "pipdwc", 0);
925 wpipe->pipe_state |= PIPE_DIRECTW;
928 error = pipe_build_write_buffer(wpipe, uio);
931 wpipe->pipe_state &= ~PIPE_DIRECTW;
937 while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
938 if (wpipe->pipe_state & PIPE_EOF) {
939 pipe_destroy_write_buffer(wpipe);
940 pipeselwakeup(wpipe);
945 if (wpipe->pipe_state & PIPE_WANTR) {
946 wpipe->pipe_state &= ~PIPE_WANTR;
949 pipeselwakeup(wpipe);
951 error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
956 if (wpipe->pipe_state & PIPE_EOF)
958 if (wpipe->pipe_state & PIPE_DIRECTW) {
960 * this bit of trickery substitutes a kernel buffer for
961 * the process that might be going away.
963 pipe_clone_write_buffer(wpipe);
965 pipe_destroy_write_buffer(wpipe);
977 pipe_write(fp, uio, active_cred, flags, td)
980 struct ucred *active_cred;
985 int desiredsize, orig_resid;
986 struct pipe *wpipe, *rpipe;
989 wpipe = rpipe->pipe_peer;
992 error = pipelock(wpipe, 1);
998 * detect loss of pipe read side, issue SIGPIPE if lost.
1000 if ((!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1006 error = mac_check_pipe_write(active_cred, wpipe->pipe_pair);
1015 /* Choose a larger size if it's advantageous */
1016 desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1017 while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1018 if (piperesizeallowed != 1)
1020 if (amountpipekva > maxpipekva / 2)
1022 if (desiredsize == BIG_PIPE_SIZE)
1024 desiredsize = desiredsize * 2;
1027 /* Choose a smaller size if we're in a OOM situation */
1028 if ((amountpipekva > (3 * maxpipekva) / 4) &&
1029 (wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1030 (wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1031 (piperesizeallowed == 1))
1032 desiredsize = SMALL_PIPE_SIZE;
1034 /* Resize if the above determined that a new size was necessary */
1035 if ((desiredsize != wpipe->pipe_buffer.size) &&
1036 ((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1038 pipespace(wpipe, desiredsize);
1041 if (wpipe->pipe_buffer.size == 0) {
1043 * This can only happen for reverse direction use of pipes
1044 * in a complete OOM situation.
1055 orig_resid = uio->uio_resid;
1057 while (uio->uio_resid) {
1061 if (wpipe->pipe_state & PIPE_EOF) {
1066 #ifndef PIPE_NODIRECT
1068 * If the transfer is large, we can gain performance if
1069 * we do process-to-process copies directly.
1070 * If the write is non-blocking, we don't use the
1071 * direct write mechanism.
1073 * The direct write mechanism will detect the reader going
1076 if (uio->uio_segflg == UIO_USERSPACE &&
1077 uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1078 wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1079 (fp->f_flag & FNONBLOCK) == 0) {
1081 error = pipe_direct_write(wpipe, uio);
1089 * Pipe buffered writes cannot be coincidental with
1090 * direct writes. We wait until the currently executing
1091 * direct write is completed before we start filling the
1092 * pipe buffer. We break out if a signal occurs or the
1095 if (wpipe->pipe_state & PIPE_DIRECTW) {
1096 if (wpipe->pipe_state & PIPE_WANTR) {
1097 wpipe->pipe_state &= ~PIPE_WANTR;
1101 error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1109 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1111 /* Writes of size <= PIPE_BUF must be atomic. */
1112 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1116 int size; /* Transfer size */
1117 int segsize; /* first segment to transfer */
1120 * Transfer size is minimum of uio transfer
1121 * and free space in pipe buffer.
1123 if (space > uio->uio_resid)
1124 size = uio->uio_resid;
1128 * First segment to transfer is minimum of
1129 * transfer size and contiguous space in
1130 * pipe buffer. If first segment to transfer
1131 * is less than the transfer size, we've got
1132 * a wraparound in the buffer.
1134 segsize = wpipe->pipe_buffer.size -
1135 wpipe->pipe_buffer.in;
1139 /* Transfer first segment */
1142 error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1146 if (error == 0 && segsize < size) {
1147 KASSERT(wpipe->pipe_buffer.in + segsize ==
1148 wpipe->pipe_buffer.size,
1149 ("Pipe buffer wraparound disappeared"));
1151 * Transfer remaining part now, to
1152 * support atomic writes. Wraparound
1158 &wpipe->pipe_buffer.buffer[0],
1159 size - segsize, uio);
1163 wpipe->pipe_buffer.in += size;
1164 if (wpipe->pipe_buffer.in >=
1165 wpipe->pipe_buffer.size) {
1166 KASSERT(wpipe->pipe_buffer.in ==
1168 wpipe->pipe_buffer.size,
1169 ("Expected wraparound bad"));
1170 wpipe->pipe_buffer.in = size - segsize;
1173 wpipe->pipe_buffer.cnt += size;
1174 KASSERT(wpipe->pipe_buffer.cnt <=
1175 wpipe->pipe_buffer.size,
1176 ("Pipe buffer overflow"));
1183 * If the "read-side" has been blocked, wake it up now.
1185 if (wpipe->pipe_state & PIPE_WANTR) {
1186 wpipe->pipe_state &= ~PIPE_WANTR;
1191 * don't block on non-blocking I/O
1193 if (fp->f_flag & FNONBLOCK) {
1200 * We have no more space and have something to offer,
1201 * wake up select/poll.
1203 pipeselwakeup(wpipe);
1205 wpipe->pipe_state |= PIPE_WANTW;
1207 error = msleep(wpipe, PIPE_MTX(rpipe),
1208 PRIBIO | PCATCH, "pipewr", 0);
1217 if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1218 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1220 } else if (wpipe->pipe_buffer.cnt > 0) {
1222 * If we have put any characters in the buffer, we wake up
1225 if (wpipe->pipe_state & PIPE_WANTR) {
1226 wpipe->pipe_state &= ~PIPE_WANTR;
1232 * Don't return EPIPE if I/O was successful
1234 if ((wpipe->pipe_buffer.cnt == 0) &&
1235 (uio->uio_resid == 0) &&
1241 vfs_timestamp(&wpipe->pipe_mtime);
1244 * We have something to offer,
1245 * wake up select/poll.
1247 if (wpipe->pipe_buffer.cnt)
1248 pipeselwakeup(wpipe);
1256 * we implement a very minimal set of ioctls for compatibility with sockets.
1259 pipe_ioctl(fp, cmd, data, active_cred, td)
1263 struct ucred *active_cred;
1266 struct pipe *mpipe = fp->f_data;
1272 error = mac_check_pipe_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1287 mpipe->pipe_state |= PIPE_ASYNC;
1289 mpipe->pipe_state &= ~PIPE_ASYNC;
1294 if (mpipe->pipe_state & PIPE_DIRECTW)
1295 *(int *)data = mpipe->pipe_map.cnt;
1297 *(int *)data = mpipe->pipe_buffer.cnt;
1302 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1306 *(int *)data = fgetown(&mpipe->pipe_sigio);
1309 /* This is deprecated, FIOSETOWN should be used instead. */
1312 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1315 /* This is deprecated, FIOGETOWN should be used instead. */
1317 *(int *)data = -fgetown(&mpipe->pipe_sigio);
1330 pipe_poll(fp, events, active_cred, td)
1333 struct ucred *active_cred;
1336 struct pipe *rpipe = fp->f_data;
1343 wpipe = rpipe->pipe_peer;
1346 error = mac_check_pipe_poll(active_cred, rpipe->pipe_pair);
1350 if (events & (POLLIN | POLLRDNORM))
1351 if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1352 (rpipe->pipe_buffer.cnt > 0) ||
1353 (rpipe->pipe_state & PIPE_EOF))
1354 revents |= events & (POLLIN | POLLRDNORM);
1356 if (events & (POLLOUT | POLLWRNORM))
1357 if (!wpipe->pipe_present || (wpipe->pipe_state & PIPE_EOF) ||
1358 (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1359 (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1360 revents |= events & (POLLOUT | POLLWRNORM);
1362 if ((rpipe->pipe_state & PIPE_EOF) ||
1363 (!wpipe->pipe_present) ||
1364 (wpipe->pipe_state & PIPE_EOF))
1368 if (events & (POLLIN | POLLRDNORM)) {
1369 selrecord(td, &rpipe->pipe_sel);
1370 rpipe->pipe_state |= PIPE_SEL;
1373 if (events & (POLLOUT | POLLWRNORM)) {
1374 selrecord(td, &wpipe->pipe_sel);
1375 wpipe->pipe_state |= PIPE_SEL;
1387 * We shouldn't need locks here as we're doing a read and this should
1388 * be a natural race.
1391 pipe_stat(fp, ub, active_cred, td)
1394 struct ucred *active_cred;
1397 struct pipe *pipe = fp->f_data;
1402 error = mac_check_pipe_stat(active_cred, pipe->pipe_pair);
1407 bzero(ub, sizeof(*ub));
1408 ub->st_mode = S_IFIFO;
1409 ub->st_blksize = PAGE_SIZE;
1410 if (pipe->pipe_state & PIPE_DIRECTW)
1411 ub->st_size = pipe->pipe_map.cnt;
1413 ub->st_size = pipe->pipe_buffer.cnt;
1414 ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1415 ub->st_atimespec = pipe->pipe_atime;
1416 ub->st_mtimespec = pipe->pipe_mtime;
1417 ub->st_ctimespec = pipe->pipe_ctime;
1418 ub->st_uid = fp->f_cred->cr_uid;
1419 ub->st_gid = fp->f_cred->cr_gid;
1421 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1422 * XXX (st_dev, st_ino) should be unique.
1433 struct pipe *cpipe = fp->f_data;
1435 fp->f_ops = &badfileops;
1437 funsetown(&cpipe->pipe_sigio);
1443 pipe_free_kmem(cpipe)
1447 KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1448 ("pipe_free_kmem: pipe mutex locked"));
1450 if (cpipe->pipe_buffer.buffer != NULL) {
1451 atomic_subtract_int(&amountpipekva, cpipe->pipe_buffer.size);
1452 vm_map_remove(pipe_map,
1453 (vm_offset_t)cpipe->pipe_buffer.buffer,
1454 (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1455 cpipe->pipe_buffer.buffer = NULL;
1457 #ifndef PIPE_NODIRECT
1459 cpipe->pipe_map.cnt = 0;
1460 cpipe->pipe_map.pos = 0;
1461 cpipe->pipe_map.npages = 0;
1473 struct pipepair *pp;
1476 KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1480 pp = cpipe->pipe_pair;
1482 pipeselwakeup(cpipe);
1485 * If the other side is blocked, wake it up saying that
1486 * we want to close it down.
1488 cpipe->pipe_state |= PIPE_EOF;
1489 while (cpipe->pipe_busy) {
1491 cpipe->pipe_state |= PIPE_WANT;
1493 msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1499 * Disconnect from peer, if any.
1501 ppipe = cpipe->pipe_peer;
1502 if (ppipe->pipe_present != 0) {
1503 pipeselwakeup(ppipe);
1505 ppipe->pipe_state |= PIPE_EOF;
1507 KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1511 * Mark this endpoint as free. Release kmem resources. We
1512 * don't mark this endpoint as unused until we've finished
1513 * doing that, or the pipe might disappear out from under
1517 pipe_free_kmem(cpipe);
1519 cpipe->pipe_present = 0;
1521 knlist_clear(&cpipe->pipe_sel.si_note, 1);
1522 knlist_destroy(&cpipe->pipe_sel.si_note);
1525 * If both endpoints are now closed, release the memory for the
1526 * pipe pair. If not, unlock.
1528 if (ppipe->pipe_present == 0) {
1531 mac_destroy_pipe(pp);
1533 uma_zfree(pipe_zone, cpipe->pipe_pair);
1540 pipe_kqfilter(struct file *fp, struct knote *kn)
1544 cpipe = kn->kn_fp->f_data;
1546 switch (kn->kn_filter) {
1548 kn->kn_fop = &pipe_rfiltops;
1551 kn->kn_fop = &pipe_wfiltops;
1552 if (!cpipe->pipe_peer->pipe_present) {
1553 /* other end of pipe has been closed */
1557 cpipe = cpipe->pipe_peer;
1564 knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1570 filt_pipedetach(struct knote *kn)
1572 struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1575 if (kn->kn_filter == EVFILT_WRITE) {
1576 if (!cpipe->pipe_peer->pipe_present) {
1580 cpipe = cpipe->pipe_peer;
1582 knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1588 filt_piperead(struct knote *kn, long hint)
1590 struct pipe *rpipe = kn->kn_fp->f_data;
1591 struct pipe *wpipe = rpipe->pipe_peer;
1595 kn->kn_data = rpipe->pipe_buffer.cnt;
1596 if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1597 kn->kn_data = rpipe->pipe_map.cnt;
1599 if ((rpipe->pipe_state & PIPE_EOF) ||
1600 (!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1601 kn->kn_flags |= EV_EOF;
1605 ret = kn->kn_data > 0;
1612 filt_pipewrite(struct knote *kn, long hint)
1614 struct pipe *rpipe = kn->kn_fp->f_data;
1615 struct pipe *wpipe = rpipe->pipe_peer;
1618 if ((!wpipe->pipe_present) || (wpipe->pipe_state & PIPE_EOF)) {
1620 kn->kn_flags |= EV_EOF;
1624 kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1625 if (wpipe->pipe_state & PIPE_DIRECTW)
1629 return (kn->kn_data >= PIPE_BUF);