sys_pipe.c revision 1.172 1 /* $NetBSD: sys_pipe.c,v 1.172 2026/10/03 16:23:46 riastradh Exp $ */
2
3 /*-
4 * Copyright (c) 2003, 2007, 2008, 2009, 2023 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Paul Kranenburg, and by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (c) 1996 John S. Dyson
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 * notice immediately at the beginning of the file, without modification,
41 * this list of conditions, and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. Absolutely no warranty of function or purpose is made by the author
46 * John S. Dyson.
47 * 4. Modifications may be freely made to this file if the above conditions
48 * are met.
49 */
50
51 /*
52 * This file contains a high-performance replacement for the socket-based
53 * pipes scheme originally used. It does not support all features of
54 * sockets, but does do everything that pipes normally do.
55 */
56
57 #include <sys/cdefs.h>
58 __KERNEL_RCSID(0, "$NetBSD: sys_pipe.c,v 1.172 2026/10/03 16:23:46 riastradh Exp $");
59
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/proc.h>
63 #include <sys/fcntl.h>
64 #include <sys/file.h>
65 #include <sys/filedesc.h>
66 #include <sys/filio.h>
67 #include <sys/kernel.h>
68 #include <sys/ttycom.h>
69 #include <sys/stat.h>
70 #include <sys/poll.h>
71 #include <sys/signalvar.h>
72 #include <sys/vnode.h>
73 #include <sys/uio.h>
74 #include <sys/select.h>
75 #include <sys/mount.h>
76 #include <sys/syscallargs.h>
77 #include <sys/sysctl.h>
78 #include <sys/kauth.h>
79 #include <sys/atomic.h>
80 #include <sys/pipe.h>
81
82 static int pipe_read(file_t *, off_t *, struct uio *, kauth_cred_t, int);
83 static int pipe_write(file_t *, off_t *, struct uio *, kauth_cred_t, int);
84 static int pipe_close(file_t *);
85 static int pipe_poll(file_t *, int);
86 static int pipe_kqfilter(file_t *, struct knote *);
87 static int pipe_stat(file_t *, struct stat *);
88 static int pipe_ioctl(file_t *, u_long, void *);
89 static void pipe_restart(file_t *);
90 static int pipe_fpathconf(file_t *, int, register_t *);
91 static int pipe_posix_fadvise(file_t *, off_t, off_t, int);
92
93 static const struct fileops pipeops = {
94 .fo_name = "pipe",
95 .fo_read = pipe_read,
96 .fo_write = pipe_write,
97 .fo_ioctl = pipe_ioctl,
98 .fo_fcntl = fnullop_fcntl,
99 .fo_poll = pipe_poll,
100 .fo_stat = pipe_stat,
101 .fo_close = pipe_close,
102 .fo_kqfilter = pipe_kqfilter,
103 .fo_restart = pipe_restart,
104 .fo_fpathconf = pipe_fpathconf,
105 .fo_posix_fadvise = pipe_posix_fadvise,
106 };
107
108 /*
109 * Default pipe buffer size(s), this can be kind-of large now because pipe
110 * space is pageable. The pipe code will try to maintain locality of
111 * reference for performance reasons, so small amounts of outstanding I/O
112 * will not wipe the cache.
113 */
114 #define MINPIPESIZE (PIPE_SIZE / 3)
115 #define MAXPIPESIZE (2 * PIPE_SIZE / 3)
116
117 /*
118 * Limit the number of "big" pipes
119 */
120 #define LIMITBIGPIPES 32
121 static u_int maxbigpipes __read_mostly = LIMITBIGPIPES;
122 static u_int nbigpipe = 0;
123
124 /*
125 * Amount of KVA consumed by pipe buffers.
126 */
127 static u_int amountpipekva = 0;
128
129 static void pipeclose(struct pipe *);
130 static void pipefree(struct pipe *);
131 static void pipe_free_kmem(struct pipe *);
132 static int pipe_create(struct pipe **, pool_cache_t, struct timespec *);
133 static int pipelock(struct pipe *, bool);
134 static inline void pipeunlock(struct pipe *);
135 static void pipeselwakeup(struct pipe *, struct pipe *, int);
136 static int pipespace(struct pipe *, int);
137 static int pipe_ctor(void *, void *, int);
138 static void pipe_dtor(void *, void *);
139
140 static pool_cache_t pipe_wr_cache;
141 static pool_cache_t pipe_rd_cache;
142
143 void
144 pipe_init(void)
145 {
146
147 /* Writer side is not automatically allocated KVA. */
148 pipe_wr_cache = pool_cache_init(sizeof(struct pipe), 0, 0, 0, "pipewr",
149 NULL, IPL_NONE, pipe_ctor, pipe_dtor, NULL);
150 KASSERT(pipe_wr_cache != NULL);
151
152 /* Reader side gets preallocated KVA. */
153 pipe_rd_cache = pool_cache_init(sizeof(struct pipe), 0, 0, 0, "piperd",
154 NULL, IPL_NONE, pipe_ctor, pipe_dtor, (void *)1);
155 KASSERT(pipe_rd_cache != NULL);
156 }
157
158 static int
159 pipe_ctor(void *arg, void *obj, int flags)
160 {
161 struct pipe *pipe;
162 vaddr_t va;
163
164 pipe = obj;
165
166 memset(pipe, 0, sizeof(struct pipe));
167 if (arg != NULL) {
168 /* Preallocate space. */
169 va = uvm_km_alloc(kernel_map, PIPE_SIZE, 0,
170 UVM_KMF_PAGEABLE | UVM_KMF_WAITVA);
171 KASSERT(va != 0);
172 pipe->pipe_kmem = va;
173 atomic_add_int(&amountpipekva, PIPE_SIZE);
174 }
175 cv_init(&pipe->pipe_rcv, "pipe_rd");
176 cv_init(&pipe->pipe_wcv, "pipe_wr");
177 cv_init(&pipe->pipe_draincv, "pipe_drn");
178 cv_init(&pipe->pipe_lkcv, "pipe_lk");
179 selinit(&pipe->pipe_sel);
180 pipe->pipe_state = PIPE_SIGNALR;
181
182 return 0;
183 }
184
185 static void
186 pipe_dtor(void *arg, void *obj)
187 {
188 struct pipe *pipe;
189
190 pipe = obj;
191
192 cv_destroy(&pipe->pipe_rcv);
193 cv_destroy(&pipe->pipe_wcv);
194 cv_destroy(&pipe->pipe_draincv);
195 cv_destroy(&pipe->pipe_lkcv);
196 seldestroy(&pipe->pipe_sel);
197 if (pipe->pipe_kmem != 0) {
198 uvm_km_free(kernel_map, pipe->pipe_kmem, PIPE_SIZE,
199 UVM_KMF_PAGEABLE);
200 atomic_add_int(&amountpipekva, -PIPE_SIZE);
201 }
202 }
203
204 /*
205 * The pipe system call for the DTYPE_PIPE type of pipes
206 */
207 int
208 pipe1(struct lwp *l, int *fildes, int flags)
209 {
210 struct pipe *rpipe, *wpipe;
211 struct timespec nt;
212 file_t *rf, *wf;
213 int fd, error;
214 proc_t *p;
215
216 if (flags & ~(O_CLOEXEC|O_CLOFORK|O_NONBLOCK|O_NOSIGPIPE))
217 return EINVAL;
218 p = curproc;
219 rpipe = wpipe = NULL;
220 getnanotime(&nt);
221 if ((error = pipe_create(&rpipe, pipe_rd_cache, &nt)) ||
222 (error = pipe_create(&wpipe, pipe_wr_cache, &nt))) {
223 goto free2;
224 }
225 rpipe->pipe_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
226 wpipe->pipe_lock = rpipe->pipe_lock;
227 mutex_obj_hold(wpipe->pipe_lock);
228
229 error = fd_allocfile(&rf, &fd);
230 if (error)
231 goto free2;
232 fildes[0] = fd;
233
234 error = fd_allocfile(&wf, &fd);
235 if (error)
236 goto free3;
237 fildes[1] = fd;
238
239 rf->f_flag = FREAD | flags;
240 rf->f_type = DTYPE_PIPE;
241 rf->f_pipe = rpipe;
242 rf->f_ops = &pipeops;
243 fd_set_exclose(l, fildes[0], (flags & O_CLOEXEC) != 0);
244 fd_set_foclose(l, fildes[0], (flags & O_CLOFORK) != 0);
245
246 wf->f_flag = FWRITE | flags;
247 wf->f_type = DTYPE_PIPE;
248 wf->f_pipe = wpipe;
249 wf->f_ops = &pipeops;
250 fd_set_exclose(l, fildes[1], (flags & O_CLOEXEC) != 0);
251 fd_set_foclose(l, fildes[1], (flags & O_CLOFORK) != 0);
252
253 rpipe->pipe_peer = wpipe;
254 wpipe->pipe_peer = rpipe;
255
256 fd_affix(p, rf, fildes[0]);
257 fd_affix(p, wf, fildes[1]);
258 return (0);
259 free3:
260 fd_abort(p, rf, fildes[0]);
261 free2:
262 if (wpipe)
263 pipefree(wpipe);
264 if (rpipe)
265 pipefree(rpipe);
266
267 return (error);
268 }
269
270 /*
271 * Allocate kva for pipe circular buffer, the space is pageable
272 * This routine will 'realloc' the size of a pipe safely, if it fails
273 * it will retain the old buffer.
274 * If it fails it will return ENOMEM.
275 */
276 static int
277 pipespace(struct pipe *pipe, int size)
278 {
279 void *buffer;
280
281 /*
282 * Allocate pageable virtual address space. Physical memory is
283 * allocated on demand.
284 */
285 if (size == PIPE_SIZE && pipe->pipe_kmem != 0) {
286 buffer = (void *)pipe->pipe_kmem;
287 } else {
288 buffer = (void *)uvm_km_alloc(kernel_map, round_page(size),
289 0, UVM_KMF_PAGEABLE);
290 if (buffer == NULL)
291 return (ENOMEM);
292 atomic_add_int(&amountpipekva, size);
293 }
294
295 /* free old resources if we're resizing */
296 pipe_free_kmem(pipe);
297 pipe->pipe_buffer.buffer = buffer;
298 pipe->pipe_buffer.size = size;
299 pipe->pipe_buffer.in = 0;
300 pipe->pipe_buffer.out = 0;
301 pipe->pipe_buffer.cnt = 0;
302 return (0);
303 }
304
305 /*
306 * Initialize and allocate VM and memory for pipe.
307 */
308 static int
309 pipe_create(struct pipe **pipep, pool_cache_t cache, struct timespec *nt)
310 {
311 struct pipe *pipe;
312 int error;
313
314 pipe = pool_cache_get(cache, PR_WAITOK);
315 KASSERT(pipe != NULL);
316 *pipep = pipe;
317 error = 0;
318 pipe->pipe_atime = pipe->pipe_mtime = pipe->pipe_btime = *nt;
319 pipe->pipe_lock = NULL;
320 if (cache == pipe_rd_cache) {
321 error = pipespace(pipe, PIPE_SIZE);
322 } else {
323 pipe->pipe_buffer.buffer = NULL;
324 pipe->pipe_buffer.size = 0;
325 pipe->pipe_buffer.in = 0;
326 pipe->pipe_buffer.out = 0;
327 pipe->pipe_buffer.cnt = 0;
328 }
329 return error;
330 }
331
332 /*
333 * Lock a pipe for I/O, blocking other access
334 * Called with pipe spin lock held.
335 */
336 static int
337 pipelock(struct pipe *pipe, bool catch_p)
338 {
339 int error;
340
341 KASSERT(mutex_owned(pipe->pipe_lock));
342
343 while (pipe->pipe_state & PIPE_LOCKFL) {
344 if (catch_p) {
345 error = cv_wait_sig(&pipe->pipe_lkcv, pipe->pipe_lock);
346 if (error != 0) {
347 return error;
348 }
349 } else
350 cv_wait(&pipe->pipe_lkcv, pipe->pipe_lock);
351 }
352
353 pipe->pipe_state |= PIPE_LOCKFL;
354
355 return 0;
356 }
357
358 /*
359 * unlock a pipe I/O lock
360 */
361 static inline void
362 pipeunlock(struct pipe *pipe)
363 {
364
365 KASSERT(pipe->pipe_state & PIPE_LOCKFL);
366
367 pipe->pipe_state &= ~PIPE_LOCKFL;
368 cv_signal(&pipe->pipe_lkcv);
369 }
370
371 /*
372 * Select/poll wakeup. This also sends SIGIO to peer connected to
373 * 'sigpipe' side of pipe.
374 */
375 static void
376 pipeselwakeup(struct pipe *selp, struct pipe *sigp, int code)
377 {
378 int band;
379
380 switch (code) {
381 case POLL_IN:
382 band = POLLIN|POLLRDNORM;
383 break;
384 case POLL_OUT:
385 band = POLLOUT|POLLWRNORM;
386 break;
387 case POLL_HUP:
388 band = POLLHUP;
389 break;
390 case POLL_ERR:
391 band = POLLERR;
392 break;
393 default:
394 band = 0;
395 #ifdef DIAGNOSTIC
396 printf("bad siginfo code %d in pipe notification.\n", code);
397 #endif
398 break;
399 }
400
401 selnotify(&selp->pipe_sel, band, NOTE_SUBMIT);
402
403 if (sigp == NULL || (sigp->pipe_state & PIPE_ASYNC) == 0)
404 return;
405
406 fownsignal(sigp->pipe_pgid, SIGIO, code, band, selp);
407 }
408
409 static int
410 pipe_read(file_t *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
411 int flags)
412 {
413 struct pipe *rpipe = fp->f_pipe;
414 struct pipe *wpipe;
415 struct pipebuf *bp = &rpipe->pipe_buffer;
416 kmutex_t *lock = rpipe->pipe_lock;
417 int error;
418 size_t nread = 0;
419 size_t size;
420 size_t ocnt;
421 unsigned int wakeup_state = 0;
422
423 /*
424 * Try to avoid locking the pipe if we have nothing to do.
425 *
426 * There are programs which share one pipe amongst multiple processes
427 * and perform non-blocking reads in parallel, even if the pipe is
428 * empty. This in particular is the case with BSD make, which when
429 * spawned with a high -j number can find itself with over half of the
430 * calls failing to find anything.
431 */
432 if ((fp->f_flag & FNONBLOCK) != 0) {
433 if (__predict_false(uio->uio_resid == 0))
434 return (0);
435 if (atomic_load_relaxed(&bp->cnt) == 0 &&
436 (atomic_load_relaxed(&rpipe->pipe_state) & PIPE_EOF) == 0)
437 return (EAGAIN);
438 }
439
440 mutex_enter(lock);
441 ++rpipe->pipe_busy;
442 ocnt = bp->cnt;
443
444 again:
445 error = pipelock(rpipe, true);
446 if (error)
447 goto unlocked_error;
448
449 while (uio->uio_resid) {
450 /*
451 * Normal pipe buffer receive.
452 */
453 if (bp->cnt > 0) {
454 size = bp->size - bp->out;
455 if (size > bp->cnt)
456 size = bp->cnt;
457 if (size > uio->uio_resid)
458 size = uio->uio_resid;
459
460 mutex_exit(lock);
461 error = uiomove((char *)bp->buffer + bp->out, size, uio);
462 mutex_enter(lock);
463 if (error)
464 break;
465
466 bp->out += size;
467 if (bp->out >= bp->size)
468 bp->out = 0;
469
470 bp->cnt -= size;
471
472 /*
473 * If there is no more to read in the pipe, reset
474 * its pointers to the beginning. This improves
475 * cache hit stats.
476 */
477 if (bp->cnt == 0) {
478 bp->in = 0;
479 bp->out = 0;
480 }
481 nread += size;
482 continue;
483 }
484
485 /*
486 * Break if some data was read.
487 */
488 if (nread > 0)
489 break;
490
491 /*
492 * Detect EOF condition.
493 * Read returns 0 on EOF, no need to set error.
494 *
495 * XXX Why rpipe->pipe_state and not wpipe->pipe_state?
496 * XXX Distinguish reader-closed from writer-closed?
497 */
498 if (rpipe->pipe_state & PIPE_EOF)
499 break;
500
501 /*
502 * Don't block on non-blocking I/O.
503 */
504 if (fp->f_flag & FNONBLOCK) {
505 error = EAGAIN;
506 break;
507 }
508
509 /*
510 * Unlock the pipe buffer for our remaining processing.
511 * We will either break out with an error or we will
512 * sleep and relock to loop.
513 */
514 pipeunlock(rpipe);
515
516 /*
517 * We want to read more, wake up select/poll.
518 */
519 pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
520
521 /*
522 * If the "write-side" is blocked, wake it up now.
523 */
524 wpipe = rpipe->pipe_peer;
525 cv_broadcast(&wpipe->pipe_wcv);
526
527 if (wakeup_state & PIPE_RESTART) {
528 error = ERESTART;
529 goto unlocked_error;
530 }
531
532 /* Now wait until the pipe is filled */
533 error = cv_wait_sig(&rpipe->pipe_rcv, lock);
534 if (error != 0)
535 goto unlocked_error;
536 wakeup_state = rpipe->pipe_state;
537 goto again;
538 }
539
540 if (error == 0)
541 getnanotime(&rpipe->pipe_atime);
542 pipeunlock(rpipe);
543
544 unlocked_error:
545 --rpipe->pipe_busy;
546 if (rpipe->pipe_busy == 0) {
547 rpipe->pipe_state &= ~PIPE_RESTART;
548 cv_broadcast(&rpipe->pipe_draincv);
549 }
550 if (bp->cnt < MINPIPESIZE) {
551 if ((wpipe = rpipe->pipe_peer) != NULL)
552 cv_broadcast(&wpipe->pipe_wcv);
553 }
554
555 /*
556 * If anything was read off the buffer, signal to the writer it's
557 * possible to write more data. Also send signal if we are here for the
558 * first time after last write.
559 */
560 if ((bp->size - bp->cnt) >= PIPE_BUF
561 && (ocnt != bp->cnt || (rpipe->pipe_state & PIPE_SIGNALR))) {
562 pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
563 rpipe->pipe_state &= ~PIPE_SIGNALR;
564 }
565
566 mutex_exit(lock);
567 return (error);
568 }
569
570 static int
571 pipe_write(file_t *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
572 int flags)
573 {
574 struct pipe *wpipe, *rpipe;
575 struct pipebuf *bp;
576 kmutex_t *lock;
577 int error;
578 unsigned int wakeup_state = 0;
579
580 /* We want to write to our peer */
581 wpipe = fp->f_pipe;
582 lock = wpipe->pipe_lock;
583 error = 0;
584
585 mutex_enter(lock);
586 rpipe = wpipe->pipe_peer;
587
588 /*
589 * Detect loss of pipe read side, issue SIGPIPE if lost.
590 */
591 if (rpipe == NULL || (rpipe->pipe_state & PIPE_EOF) != 0) {
592 mutex_exit(lock);
593 return EPIPE;
594 }
595 ++wpipe->pipe_busy;
596
597 /* Acquire the long-term pipe lock */
598 if ((error = pipelock(rpipe, true)) != 0) {
599 --wpipe->pipe_busy;
600 if (wpipe->pipe_busy == 0) {
601 wpipe->pipe_state &= ~PIPE_RESTART;
602 cv_broadcast(&wpipe->pipe_draincv);
603 }
604 mutex_exit(lock);
605 return (error);
606 }
607
608 bp = &rpipe->pipe_buffer;
609
610 /*
611 * If it is advantageous to resize the pipe buffer, do so.
612 */
613 if ((uio->uio_resid > PIPE_SIZE) &&
614 (nbigpipe < maxbigpipes) &&
615 (bp->size <= PIPE_SIZE) && (bp->cnt == 0)) {
616
617 if (pipespace(rpipe, BIG_PIPE_SIZE) == 0)
618 atomic_inc_uint(&nbigpipe);
619 }
620
621 while (uio->uio_resid) {
622 size_t space;
623
624 space = bp->size - bp->cnt;
625
626 /* Writes of size <= PIPE_BUF must be atomic. */
627 if ((space < uio->uio_resid) && (uio->uio_resid <= PIPE_BUF))
628 space = 0;
629
630 if (space > 0) {
631 int size; /* Transfer size */
632 int segsize; /* first segment to transfer */
633
634 /*
635 * Transfer size is minimum of uio transfer
636 * and free space in pipe buffer.
637 */
638 if (space > uio->uio_resid)
639 size = uio->uio_resid;
640 else
641 size = space;
642 /*
643 * First segment to transfer is minimum of
644 * transfer size and contiguous space in
645 * pipe buffer. If first segment to transfer
646 * is less than the transfer size, we've got
647 * a wraparound in the buffer.
648 */
649 segsize = bp->size - bp->in;
650 if (segsize > size)
651 segsize = size;
652
653 /* Transfer first segment */
654 mutex_exit(lock);
655 error = uiomove((char *)bp->buffer + bp->in, segsize,
656 uio);
657
658 if (error == 0 && segsize < size) {
659 /*
660 * Transfer remaining part now, to
661 * support atomic writes. Wraparound
662 * happened.
663 */
664 KASSERT(bp->in + segsize == bp->size);
665 error = uiomove(bp->buffer,
666 size - segsize, uio);
667 }
668 mutex_enter(lock);
669 if (error)
670 break;
671
672 bp->in += size;
673 if (bp->in >= bp->size) {
674 KASSERT(bp->in == size - segsize + bp->size);
675 bp->in = size - segsize;
676 }
677
678 bp->cnt += size;
679 KASSERT(bp->cnt <= bp->size);
680 wakeup_state = 0;
681 } else {
682 /*
683 * If the "read-side" has been blocked, wake it up now.
684 */
685 cv_broadcast(&rpipe->pipe_rcv);
686
687 /*
688 * Don't block on non-blocking I/O.
689 */
690 if (fp->f_flag & FNONBLOCK) {
691 error = EAGAIN;
692 break;
693 }
694
695 /*
696 * We have no more space and have something to offer,
697 * wake up select/poll.
698 */
699 if (bp->cnt)
700 pipeselwakeup(rpipe, rpipe, POLL_IN);
701
702 if (wakeup_state & PIPE_RESTART) {
703 error = ERESTART;
704 break;
705 }
706
707 /*
708 * If read side wants to go away, we just issue a signal
709 * to ourselves.
710 *
711 * XXX Shouldn't this happen before we uiomove anything?
712 *
713 * XXX Why rpipe->pipe_state and not wpipe->pipe_state?
714 * XXX Distinguish reader-closed from writer-closed?
715 */
716 if (rpipe->pipe_state & PIPE_EOF) {
717 error = EPIPE;
718 break;
719 }
720
721 pipeunlock(rpipe);
722 error = cv_wait_sig(&wpipe->pipe_wcv, lock);
723 (void)pipelock(rpipe, false);
724 if (error != 0)
725 break;
726 wakeup_state = wpipe->pipe_state;
727 }
728 }
729
730 --wpipe->pipe_busy;
731 if (wpipe->pipe_busy == 0) {
732 wpipe->pipe_state &= ~PIPE_RESTART;
733 cv_broadcast(&wpipe->pipe_draincv);
734 }
735 if (bp->cnt > 0) {
736 cv_broadcast(&rpipe->pipe_rcv);
737 }
738
739 /*
740 * Don't return EPIPE if I/O was successful
741 *
742 * XXX Shouldn't we avoid returning _any_ error if we
743 * transmitted _any_ positive number of bytes? Or does that
744 * happen downstream of here, and if so, why do we need to do
745 * that here?
746 */
747 if (error == EPIPE && bp->cnt == 0 && uio->uio_resid == 0)
748 error = 0;
749
750 if (error == 0)
751 getnanotime(&rpipe->pipe_mtime);
752
753 /*
754 * We have something to offer, wake up select/poll.
755 */
756 if (bp->cnt)
757 pipeselwakeup(rpipe, rpipe, POLL_IN);
758
759 /*
760 * Arrange for next read(2) to do a signal.
761 */
762 rpipe->pipe_state |= PIPE_SIGNALR;
763
764 pipeunlock(rpipe);
765 mutex_exit(lock);
766 return (error);
767 }
768
769 /*
770 * We implement a very minimal set of ioctls for compatibility with sockets.
771 */
772 int
773 pipe_ioctl(file_t *fp, u_long cmd, void *data)
774 {
775 struct pipe *pipe = fp->f_pipe;
776 kmutex_t *lock = pipe->pipe_lock;
777
778 switch (cmd) {
779
780 case FIONBIO:
781 return (0);
782
783 case FIOASYNC:
784 mutex_enter(lock);
785 if (*(int *)data) {
786 pipe->pipe_state |= PIPE_ASYNC;
787 } else {
788 pipe->pipe_state &= ~PIPE_ASYNC;
789 }
790 mutex_exit(lock);
791 return (0);
792
793 case FIONREAD:
794 mutex_enter(lock);
795 *(int *)data = pipe->pipe_buffer.cnt;
796 mutex_exit(lock);
797 return (0);
798
799 case FIONWRITE:
800 /* Look at other side */
801 mutex_enter(lock);
802 pipe = pipe->pipe_peer;
803 if (pipe == NULL)
804 *(int *)data = 0;
805 else
806 *(int *)data = pipe->pipe_buffer.cnt;
807 mutex_exit(lock);
808 return (0);
809
810 case FIONSPACE:
811 /* Look at other side */
812 mutex_enter(lock);
813 pipe = pipe->pipe_peer;
814 if (pipe == NULL)
815 *(int *)data = 0;
816 else
817 *(int *)data = pipe->pipe_buffer.size -
818 pipe->pipe_buffer.cnt;
819 mutex_exit(lock);
820 return (0);
821
822 case TIOCSPGRP:
823 case FIOSETOWN:
824 return fsetown(&pipe->pipe_pgid, cmd, data);
825
826 case TIOCGPGRP:
827 case FIOGETOWN:
828 return fgetown(pipe->pipe_pgid, cmd, data);
829
830 }
831 return (EPASSTHROUGH);
832 }
833
834 int
835 pipe_poll(file_t *fp, int events)
836 {
837 struct pipe *pipe = fp->f_pipe;
838 struct pipe *ppipe;
839 int eof = 0;
840 int revents = 0;
841
842 mutex_enter(pipe->pipe_lock);
843 ppipe = pipe->pipe_peer;
844
845 if (events & (POLLIN | POLLRDNORM))
846 if ((pipe->pipe_buffer.cnt > 0) ||
847 (pipe->pipe_state & PIPE_EOF))
848 revents |= events & (POLLIN | POLLRDNORM);
849
850 eof |= (pipe->pipe_state & PIPE_EOF);
851
852 if (ppipe == NULL)
853 revents |= events & (POLLOUT | POLLWRNORM);
854 else {
855 if (events & (POLLOUT | POLLWRNORM))
856 if ((ppipe->pipe_state & PIPE_EOF) || (
857 (ppipe->pipe_buffer.size - ppipe->pipe_buffer.cnt) >= PIPE_BUF))
858 revents |= events & (POLLOUT | POLLWRNORM);
859
860 eof |= (ppipe->pipe_state & PIPE_EOF);
861 }
862
863 if (ppipe == NULL || eof)
864 revents |= POLLHUP;
865
866 if (revents == 0) {
867 if (events & (POLLIN | POLLRDNORM))
868 selrecord(curlwp, &pipe->pipe_sel);
869
870 if (events & (POLLOUT | POLLWRNORM))
871 selrecord(curlwp, &ppipe->pipe_sel);
872 }
873 mutex_exit(pipe->pipe_lock);
874
875 return (revents);
876 }
877
878 static int
879 pipe_stat(file_t *fp, struct stat *ub)
880 {
881 struct pipe *pipe = fp->f_pipe;
882
883 mutex_enter(pipe->pipe_lock);
884 memset(ub, 0, sizeof(*ub));
885 ub->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
886 ub->st_blksize = pipe->pipe_buffer.size;
887 if (ub->st_blksize == 0 && pipe->pipe_peer)
888 ub->st_blksize = pipe->pipe_peer->pipe_buffer.size;
889 ub->st_size = pipe->pipe_buffer.cnt;
890 ub->st_blocks = (ub->st_size) ? 1 : 0;
891 ub->st_atimespec = pipe->pipe_atime;
892 ub->st_mtimespec = pipe->pipe_mtime;
893 ub->st_ctimespec = ub->st_birthtimespec = pipe->pipe_btime;
894 ub->st_uid = kauth_cred_geteuid(fp->f_cred);
895 ub->st_gid = kauth_cred_getegid(fp->f_cred);
896
897 /*
898 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
899 * XXX (st_dev, st_ino) should be unique.
900 */
901 mutex_exit(pipe->pipe_lock);
902 return 0;
903 }
904
905 static int
906 pipe_close(file_t *fp)
907 {
908 struct pipe *pipe = fp->f_pipe;
909
910 fp->f_pipe = NULL;
911 pipeclose(pipe);
912 return (0);
913 }
914
915 static void
916 pipe_restart(file_t *fp)
917 {
918 struct pipe *pipe = fp->f_pipe;
919
920 /*
921 * Unblock blocked reads/writes in order to allow close() to complete.
922 * System calls return ERESTART so that the fd is revalidated.
923 * (Partial writes return the transfer length.)
924 */
925 mutex_enter(pipe->pipe_lock);
926 pipe->pipe_state |= PIPE_RESTART;
927 /*
928 * At most one of these is in use at any time, depending on
929 * whether fp->f_flag has FREAD or FWRITE set, but there's no
930 * harm in waking both here.
931 */
932 cv_broadcast(&pipe->pipe_rcv);
933 cv_broadcast(&pipe->pipe_wcv);
934 mutex_exit(pipe->pipe_lock);
935 }
936
937 static int
938 pipe_fpathconf(struct file *fp, int name, register_t *retval)
939 {
940
941 switch (name) {
942 case _PC_PIPE_BUF:
943 *retval = PIPE_BUF;
944 return 0;
945 default:
946 return EINVAL;
947 }
948 }
949
950 static int
951 pipe_posix_fadvise(struct file *fp, off_t offset, off_t len, int advice)
952 {
953
954 return ESPIPE;
955 }
956
957 static void
958 pipe_free_kmem(struct pipe *pipe)
959 {
960
961 if (pipe->pipe_buffer.buffer != NULL) {
962 if (pipe->pipe_buffer.size > PIPE_SIZE) {
963 atomic_dec_uint(&nbigpipe);
964 }
965 if (pipe->pipe_buffer.buffer != (void *)pipe->pipe_kmem) {
966 uvm_km_free(kernel_map,
967 (vaddr_t)pipe->pipe_buffer.buffer,
968 pipe->pipe_buffer.size, UVM_KMF_PAGEABLE);
969 atomic_add_int(&amountpipekva,
970 -pipe->pipe_buffer.size);
971 }
972 pipe->pipe_buffer.buffer = NULL;
973 }
974 }
975
976 /*
977 * Shutdown the pipe.
978 */
979 static void
980 pipeclose(struct pipe *pipe)
981 {
982 kmutex_t *lock;
983 struct pipe *ppipe;
984
985 KASSERT(cv_is_valid(&pipe->pipe_rcv));
986 KASSERT(cv_is_valid(&pipe->pipe_wcv));
987 KASSERT(cv_is_valid(&pipe->pipe_draincv));
988 KASSERT(cv_is_valid(&pipe->pipe_lkcv));
989
990 lock = pipe->pipe_lock;
991 KASSERT(lock != NULL);
992
993 mutex_enter(lock);
994 pipeselwakeup(pipe, pipe, POLL_HUP);
995
996 /*
997 * fd_close has issued .fo_restart to wake all waiters on this
998 * side of the pipe, blocked new references, and waited for all
999 * references to drain, so it should not be possible for there
1000 * to be any waiters remaining. (Only one of the condvars was
1001 * ever in use anyway depending on whether this is the reader
1002 * side or the writer side of the pipe.)
1003 */
1004 KASSERT(!cv_has_waiters(&pipe->pipe_rcv));
1005 KASSERT(!cv_has_waiters(&pipe->pipe_wcv));
1006
1007 /*
1008 * If the other side is busy, wake it up saying that
1009 * we want to close it down, which will prevent peers
1010 * from starting new I/O. Once it is no longer busy,
1011 * disconnect it.
1012 */
1013 pipe->pipe_state |= PIPE_EOF;
1014 if ((ppipe = pipe->pipe_peer) != NULL) {
1015 pipeselwakeup(ppipe, ppipe, POLL_HUP);
1016 ppipe->pipe_state |= PIPE_EOF;
1017 if (ppipe->pipe_busy) {
1018 cv_broadcast(&ppipe->pipe_rcv);
1019 cv_broadcast(&ppipe->pipe_wcv);
1020 while (ppipe->pipe_busy)
1021 cv_wait_sig(&ppipe->pipe_draincv, lock);
1022 }
1023 ppipe->pipe_peer = NULL;
1024 }
1025
1026 /*
1027 * Any knote objects still left in the list are
1028 * the one attached by peer. Since no one will
1029 * traverse this list, we just clear it.
1030 *
1031 * XXX Exposes select/kqueue internals.
1032 */
1033 SLIST_INIT(&pipe->pipe_sel.sel_klist);
1034
1035 KASSERT((pipe->pipe_state & PIPE_LOCKFL) == 0);
1036 mutex_exit(lock);
1037 mutex_obj_free(lock);
1038
1039 /*
1040 * Free resources.
1041 */
1042 pipefree(pipe);
1043 }
1044
1045 static void
1046 pipefree(struct pipe *pipe)
1047 {
1048
1049 pipe->pipe_pgid = 0;
1050 pipe->pipe_state = PIPE_SIGNALR;
1051 pipe->pipe_peer = NULL;
1052 pipe->pipe_lock = NULL;
1053 pipe_free_kmem(pipe);
1054 if (pipe->pipe_kmem != 0) {
1055 pool_cache_put(pipe_rd_cache, pipe);
1056 } else {
1057 pool_cache_put(pipe_wr_cache, pipe);
1058 }
1059 }
1060
1061 static void
1062 filt_pipedetach(struct knote *kn)
1063 {
1064 struct pipe *pipe;
1065 kmutex_t *lock;
1066
1067 pipe = ((file_t *)kn->kn_obj)->f_pipe;
1068 lock = pipe->pipe_lock;
1069
1070 mutex_enter(lock);
1071
1072 switch(kn->kn_filter) {
1073 case EVFILT_WRITE:
1074 /* Need the peer structure, not our own. */
1075 pipe = pipe->pipe_peer;
1076
1077 /* If reader end already closed, just return. */
1078 if (pipe == NULL) {
1079 mutex_exit(lock);
1080 return;
1081 }
1082
1083 break;
1084 default:
1085 /* Nothing to do. */
1086 break;
1087 }
1088
1089 KASSERT(kn->kn_hook == pipe);
1090 selremove_knote(&pipe->pipe_sel, kn);
1091 mutex_exit(lock);
1092 }
1093
1094 static int
1095 filt_piperead(struct knote *kn, long hint)
1096 {
1097 struct pipe *pipe = ((file_t *)kn->kn_obj)->f_pipe;
1098 struct pipe *ppipe;
1099 int rv;
1100
1101 if ((hint & NOTE_SUBMIT) == 0) {
1102 mutex_enter(pipe->pipe_lock);
1103 }
1104 ppipe = pipe->pipe_peer;
1105 kn->kn_data = pipe->pipe_buffer.cnt;
1106
1107 if ((pipe->pipe_state & PIPE_EOF) ||
1108 (ppipe == NULL) || (ppipe->pipe_state & PIPE_EOF)) {
1109 knote_set_eof(kn, 0);
1110 rv = 1;
1111 } else {
1112 rv = kn->kn_data > 0;
1113 }
1114
1115 if ((hint & NOTE_SUBMIT) == 0) {
1116 mutex_exit(pipe->pipe_lock);
1117 }
1118 return rv;
1119 }
1120
1121 static int
1122 filt_pipewrite(struct knote *kn, long hint)
1123 {
1124 struct pipe *pipe = ((file_t *)kn->kn_obj)->f_pipe;
1125 struct pipe *ppipe;
1126 int rv;
1127
1128 if ((hint & NOTE_SUBMIT) == 0) {
1129 mutex_enter(pipe->pipe_lock);
1130 }
1131 ppipe = pipe->pipe_peer;
1132
1133 if ((ppipe == NULL) || (ppipe->pipe_state & PIPE_EOF)) {
1134 kn->kn_data = 0;
1135 knote_set_eof(kn, 0);
1136 rv = 1;
1137 } else {
1138 kn->kn_data = ppipe->pipe_buffer.size - ppipe->pipe_buffer.cnt;
1139 rv = kn->kn_data >= PIPE_BUF;
1140 }
1141
1142 if ((hint & NOTE_SUBMIT) == 0) {
1143 mutex_exit(pipe->pipe_lock);
1144 }
1145 return rv;
1146 }
1147
1148 static const struct filterops pipe_rfiltops = {
1149 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
1150 .f_attach = NULL,
1151 .f_detach = filt_pipedetach,
1152 .f_event = filt_piperead,
1153 };
1154
1155 static const struct filterops pipe_wfiltops = {
1156 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
1157 .f_attach = NULL,
1158 .f_detach = filt_pipedetach,
1159 .f_event = filt_pipewrite,
1160 };
1161
1162 static int
1163 pipe_kqfilter(file_t *fp, struct knote *kn)
1164 {
1165 struct pipe *pipe;
1166 kmutex_t *lock;
1167
1168 pipe = ((file_t *)kn->kn_obj)->f_pipe;
1169 lock = pipe->pipe_lock;
1170
1171 mutex_enter(lock);
1172
1173 switch (kn->kn_filter) {
1174 case EVFILT_READ:
1175 kn->kn_fop = &pipe_rfiltops;
1176 break;
1177 case EVFILT_WRITE:
1178 kn->kn_fop = &pipe_wfiltops;
1179 pipe = pipe->pipe_peer;
1180 if (pipe == NULL) {
1181 /* Other end of pipe has been closed. */
1182 mutex_exit(lock);
1183 return (EBADF);
1184 }
1185 break;
1186 default:
1187 mutex_exit(lock);
1188 return (EINVAL);
1189 }
1190
1191 kn->kn_hook = pipe;
1192 selrecord_knote(&pipe->pipe_sel, kn);
1193 mutex_exit(lock);
1194
1195 return (0);
1196 }
1197
1198 /*
1199 * Handle pipe sysctls.
1200 */
1201 SYSCTL_SETUP(sysctl_kern_pipe_setup, "sysctl kern.pipe subtree setup")
1202 {
1203
1204 sysctl_createv(clog, 0, NULL, NULL,
1205 CTLFLAG_PERMANENT,
1206 CTLTYPE_NODE, "pipe",
1207 SYSCTL_DESCR("Pipe settings"),
1208 NULL, 0, NULL, 0,
1209 CTL_KERN, KERN_PIPE, CTL_EOL);
1210
1211 sysctl_createv(clog, 0, NULL, NULL,
1212 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1213 CTLTYPE_INT, "maxbigpipes",
1214 SYSCTL_DESCR("Maximum number of \"big\" pipes"),
1215 NULL, 0, &maxbigpipes, 0,
1216 CTL_KERN, KERN_PIPE, KERN_PIPE_MAXBIGPIPES, CTL_EOL);
1217 sysctl_createv(clog, 0, NULL, NULL,
1218 CTLFLAG_PERMANENT,
1219 CTLTYPE_INT, "nbigpipes",
1220 SYSCTL_DESCR("Number of \"big\" pipes"),
1221 NULL, 0, &nbigpipe, 0,
1222 CTL_KERN, KERN_PIPE, KERN_PIPE_NBIGPIPES, CTL_EOL);
1223 sysctl_createv(clog, 0, NULL, NULL,
1224 CTLFLAG_PERMANENT,
1225 CTLTYPE_INT, "kvasize",
1226 SYSCTL_DESCR("Amount of kernel memory consumed by pipe "
1227 "buffers"),
1228 NULL, 0, &amountpipekva, 0,
1229 CTL_KERN, KERN_PIPE, KERN_PIPE_KVASIZE, CTL_EOL);
1230 }
1231