sys_pipe.c revision 1.170 1 /* $NetBSD: sys_pipe.c,v 1.170 2026/10/03 16:22:55 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.170 2026/10/03 16:22:55 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 pipebuf *bp = &rpipe->pipe_buffer;
415 kmutex_t *lock = rpipe->pipe_lock;
416 int error;
417 size_t nread = 0;
418 size_t size;
419 size_t ocnt;
420 unsigned int wakeup_state = 0;
421
422 /*
423 * Try to avoid locking the pipe if we have nothing to do.
424 *
425 * There are programs which share one pipe amongst multiple processes
426 * and perform non-blocking reads in parallel, even if the pipe is
427 * empty. This in particular is the case with BSD make, which when
428 * spawned with a high -j number can find itself with over half of the
429 * calls failing to find anything.
430 */
431 if ((fp->f_flag & FNONBLOCK) != 0) {
432 if (__predict_false(uio->uio_resid == 0))
433 return (0);
434 if (atomic_load_relaxed(&bp->cnt) == 0 &&
435 (atomic_load_relaxed(&rpipe->pipe_state) & PIPE_EOF) == 0)
436 return (EAGAIN);
437 }
438
439 mutex_enter(lock);
440 ++rpipe->pipe_busy;
441 ocnt = bp->cnt;
442
443 again:
444 error = pipelock(rpipe, true);
445 if (error)
446 goto unlocked_error;
447
448 while (uio->uio_resid) {
449 /*
450 * Normal pipe buffer receive.
451 */
452 if (bp->cnt > 0) {
453 size = bp->size - bp->out;
454 if (size > bp->cnt)
455 size = bp->cnt;
456 if (size > uio->uio_resid)
457 size = uio->uio_resid;
458
459 mutex_exit(lock);
460 error = uiomove((char *)bp->buffer + bp->out, size, uio);
461 mutex_enter(lock);
462 if (error)
463 break;
464
465 bp->out += size;
466 if (bp->out >= bp->size)
467 bp->out = 0;
468
469 bp->cnt -= size;
470
471 /*
472 * If there is no more to read in the pipe, reset
473 * its pointers to the beginning. This improves
474 * cache hit stats.
475 */
476 if (bp->cnt == 0) {
477 bp->in = 0;
478 bp->out = 0;
479 }
480 nread += size;
481 continue;
482 }
483
484 /*
485 * Break if some data was read.
486 */
487 if (nread > 0)
488 break;
489
490 /*
491 * Detect EOF condition.
492 * Read returns 0 on EOF, no need to set error.
493 */
494 if (rpipe->pipe_state & PIPE_EOF)
495 break;
496
497 /*
498 * Don't block on non-blocking I/O.
499 */
500 if (fp->f_flag & FNONBLOCK) {
501 error = EAGAIN;
502 break;
503 }
504
505 /*
506 * Unlock the pipe buffer for our remaining processing.
507 * We will either break out with an error or we will
508 * sleep and relock to loop.
509 */
510 pipeunlock(rpipe);
511
512 #if 1 /* XXX (dsl) I'm sure these aren't needed here ... */
513 /*
514 * We want to read more, wake up select/poll.
515 */
516 pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
517
518 /*
519 * If the "write-side" is blocked, wake it up now.
520 */
521 cv_broadcast(&rpipe->pipe_wcv);
522 #endif
523
524 if (wakeup_state & PIPE_RESTART) {
525 error = ERESTART;
526 goto unlocked_error;
527 }
528
529 /* Now wait until the pipe is filled */
530 error = cv_wait_sig(&rpipe->pipe_rcv, lock);
531 if (error != 0)
532 goto unlocked_error;
533 wakeup_state = rpipe->pipe_state;
534 goto again;
535 }
536
537 if (error == 0)
538 getnanotime(&rpipe->pipe_atime);
539 pipeunlock(rpipe);
540
541 unlocked_error:
542 --rpipe->pipe_busy;
543 if (rpipe->pipe_busy == 0) {
544 rpipe->pipe_state &= ~PIPE_RESTART;
545 cv_broadcast(&rpipe->pipe_draincv);
546 }
547 if (bp->cnt < MINPIPESIZE) {
548 cv_broadcast(&rpipe->pipe_wcv);
549 }
550
551 /*
552 * If anything was read off the buffer, signal to the writer it's
553 * possible to write more data. Also send signal if we are here for the
554 * first time after last write.
555 */
556 if ((bp->size - bp->cnt) >= PIPE_BUF
557 && (ocnt != bp->cnt || (rpipe->pipe_state & PIPE_SIGNALR))) {
558 pipeselwakeup(rpipe, rpipe->pipe_peer, POLL_OUT);
559 rpipe->pipe_state &= ~PIPE_SIGNALR;
560 }
561
562 mutex_exit(lock);
563 return (error);
564 }
565
566 static int
567 pipe_write(file_t *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
568 int flags)
569 {
570 struct pipe *wpipe, *rpipe;
571 struct pipebuf *bp;
572 kmutex_t *lock;
573 int error;
574 unsigned int wakeup_state = 0;
575
576 /* We want to write to our peer */
577 wpipe = fp->f_pipe;
578 lock = wpipe->pipe_lock;
579 error = 0;
580
581 mutex_enter(lock);
582 rpipe = wpipe->pipe_peer;
583
584 /*
585 * Detect loss of pipe read side, issue SIGPIPE if lost.
586 */
587 if (rpipe == NULL || (rpipe->pipe_state & PIPE_EOF) != 0) {
588 mutex_exit(lock);
589 return EPIPE;
590 }
591 ++rpipe->pipe_busy;
592
593 /* Acquire the long-term pipe lock */
594 if ((error = pipelock(rpipe, true)) != 0) {
595 --rpipe->pipe_busy;
596 if (rpipe->pipe_busy == 0) {
597 rpipe->pipe_state &= ~PIPE_RESTART;
598 cv_broadcast(&rpipe->pipe_draincv);
599 }
600 mutex_exit(lock);
601 return (error);
602 }
603
604 bp = &rpipe->pipe_buffer;
605
606 /*
607 * If it is advantageous to resize the pipe buffer, do so.
608 */
609 if ((uio->uio_resid > PIPE_SIZE) &&
610 (nbigpipe < maxbigpipes) &&
611 (bp->size <= PIPE_SIZE) && (bp->cnt == 0)) {
612
613 if (pipespace(rpipe, BIG_PIPE_SIZE) == 0)
614 atomic_inc_uint(&nbigpipe);
615 }
616
617 while (uio->uio_resid) {
618 size_t space;
619
620 space = bp->size - bp->cnt;
621
622 /* Writes of size <= PIPE_BUF must be atomic. */
623 if ((space < uio->uio_resid) && (uio->uio_resid <= PIPE_BUF))
624 space = 0;
625
626 if (space > 0) {
627 int size; /* Transfer size */
628 int segsize; /* first segment to transfer */
629
630 /*
631 * Transfer size is minimum of uio transfer
632 * and free space in pipe buffer.
633 */
634 if (space > uio->uio_resid)
635 size = uio->uio_resid;
636 else
637 size = space;
638 /*
639 * First segment to transfer is minimum of
640 * transfer size and contiguous space in
641 * pipe buffer. If first segment to transfer
642 * is less than the transfer size, we've got
643 * a wraparound in the buffer.
644 */
645 segsize = bp->size - bp->in;
646 if (segsize > size)
647 segsize = size;
648
649 /* Transfer first segment */
650 mutex_exit(lock);
651 error = uiomove((char *)bp->buffer + bp->in, segsize,
652 uio);
653
654 if (error == 0 && segsize < size) {
655 /*
656 * Transfer remaining part now, to
657 * support atomic writes. Wraparound
658 * happened.
659 */
660 KASSERT(bp->in + segsize == bp->size);
661 error = uiomove(bp->buffer,
662 size - segsize, uio);
663 }
664 mutex_enter(lock);
665 if (error)
666 break;
667
668 bp->in += size;
669 if (bp->in >= bp->size) {
670 KASSERT(bp->in == size - segsize + bp->size);
671 bp->in = size - segsize;
672 }
673
674 bp->cnt += size;
675 KASSERT(bp->cnt <= bp->size);
676 wakeup_state = 0;
677 } else {
678 /*
679 * If the "read-side" has been blocked, wake it up now.
680 */
681 cv_broadcast(&rpipe->pipe_rcv);
682
683 /*
684 * Don't block on non-blocking I/O.
685 */
686 if (fp->f_flag & FNONBLOCK) {
687 error = EAGAIN;
688 break;
689 }
690
691 /*
692 * We have no more space and have something to offer,
693 * wake up select/poll.
694 */
695 if (bp->cnt)
696 pipeselwakeup(rpipe, rpipe, POLL_IN);
697
698 if (wakeup_state & PIPE_RESTART) {
699 error = ERESTART;
700 break;
701 }
702
703 /*
704 * If read side wants to go away, we just issue a signal
705 * to ourselves.
706 */
707 if (rpipe->pipe_state & PIPE_EOF) {
708 error = EPIPE;
709 break;
710 }
711
712 pipeunlock(rpipe);
713 error = cv_wait_sig(&rpipe->pipe_wcv, lock);
714 (void)pipelock(rpipe, false);
715 if (error != 0)
716 break;
717 wakeup_state = rpipe->pipe_state;
718 }
719 }
720
721 --rpipe->pipe_busy;
722 if (rpipe->pipe_busy == 0) {
723 rpipe->pipe_state &= ~PIPE_RESTART;
724 cv_broadcast(&rpipe->pipe_draincv);
725 }
726 if (bp->cnt > 0) {
727 cv_broadcast(&rpipe->pipe_rcv);
728 }
729
730 /*
731 * Don't return EPIPE if I/O was successful
732 */
733 if (error == EPIPE && bp->cnt == 0 && uio->uio_resid == 0)
734 error = 0;
735
736 if (error == 0)
737 getnanotime(&rpipe->pipe_mtime);
738
739 /*
740 * We have something to offer, wake up select/poll.
741 */
742 if (bp->cnt)
743 pipeselwakeup(rpipe, rpipe, POLL_IN);
744
745 /*
746 * Arrange for next read(2) to do a signal.
747 */
748 rpipe->pipe_state |= PIPE_SIGNALR;
749
750 pipeunlock(rpipe);
751 mutex_exit(lock);
752 return (error);
753 }
754
755 /*
756 * We implement a very minimal set of ioctls for compatibility with sockets.
757 */
758 int
759 pipe_ioctl(file_t *fp, u_long cmd, void *data)
760 {
761 struct pipe *pipe = fp->f_pipe;
762 kmutex_t *lock = pipe->pipe_lock;
763
764 switch (cmd) {
765
766 case FIONBIO:
767 return (0);
768
769 case FIOASYNC:
770 mutex_enter(lock);
771 if (*(int *)data) {
772 pipe->pipe_state |= PIPE_ASYNC;
773 } else {
774 pipe->pipe_state &= ~PIPE_ASYNC;
775 }
776 mutex_exit(lock);
777 return (0);
778
779 case FIONREAD:
780 mutex_enter(lock);
781 *(int *)data = pipe->pipe_buffer.cnt;
782 mutex_exit(lock);
783 return (0);
784
785 case FIONWRITE:
786 /* Look at other side */
787 mutex_enter(lock);
788 pipe = pipe->pipe_peer;
789 if (pipe == NULL)
790 *(int *)data = 0;
791 else
792 *(int *)data = pipe->pipe_buffer.cnt;
793 mutex_exit(lock);
794 return (0);
795
796 case FIONSPACE:
797 /* Look at other side */
798 mutex_enter(lock);
799 pipe = pipe->pipe_peer;
800 if (pipe == NULL)
801 *(int *)data = 0;
802 else
803 *(int *)data = pipe->pipe_buffer.size -
804 pipe->pipe_buffer.cnt;
805 mutex_exit(lock);
806 return (0);
807
808 case TIOCSPGRP:
809 case FIOSETOWN:
810 return fsetown(&pipe->pipe_pgid, cmd, data);
811
812 case TIOCGPGRP:
813 case FIOGETOWN:
814 return fgetown(pipe->pipe_pgid, cmd, data);
815
816 }
817 return (EPASSTHROUGH);
818 }
819
820 int
821 pipe_poll(file_t *fp, int events)
822 {
823 struct pipe *pipe = fp->f_pipe;
824 struct pipe *ppipe;
825 int eof = 0;
826 int revents = 0;
827
828 mutex_enter(pipe->pipe_lock);
829 ppipe = pipe->pipe_peer;
830
831 if (events & (POLLIN | POLLRDNORM))
832 if ((pipe->pipe_buffer.cnt > 0) ||
833 (pipe->pipe_state & PIPE_EOF))
834 revents |= events & (POLLIN | POLLRDNORM);
835
836 eof |= (pipe->pipe_state & PIPE_EOF);
837
838 if (ppipe == NULL)
839 revents |= events & (POLLOUT | POLLWRNORM);
840 else {
841 if (events & (POLLOUT | POLLWRNORM))
842 if ((ppipe->pipe_state & PIPE_EOF) || (
843 (ppipe->pipe_buffer.size - ppipe->pipe_buffer.cnt) >= PIPE_BUF))
844 revents |= events & (POLLOUT | POLLWRNORM);
845
846 eof |= (ppipe->pipe_state & PIPE_EOF);
847 }
848
849 if (ppipe == NULL || eof)
850 revents |= POLLHUP;
851
852 if (revents == 0) {
853 if (events & (POLLIN | POLLRDNORM))
854 selrecord(curlwp, &pipe->pipe_sel);
855
856 if (events & (POLLOUT | POLLWRNORM))
857 selrecord(curlwp, &ppipe->pipe_sel);
858 }
859 mutex_exit(pipe->pipe_lock);
860
861 return (revents);
862 }
863
864 static int
865 pipe_stat(file_t *fp, struct stat *ub)
866 {
867 struct pipe *pipe = fp->f_pipe;
868
869 mutex_enter(pipe->pipe_lock);
870 memset(ub, 0, sizeof(*ub));
871 ub->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
872 ub->st_blksize = pipe->pipe_buffer.size;
873 if (ub->st_blksize == 0 && pipe->pipe_peer)
874 ub->st_blksize = pipe->pipe_peer->pipe_buffer.size;
875 ub->st_size = pipe->pipe_buffer.cnt;
876 ub->st_blocks = (ub->st_size) ? 1 : 0;
877 ub->st_atimespec = pipe->pipe_atime;
878 ub->st_mtimespec = pipe->pipe_mtime;
879 ub->st_ctimespec = ub->st_birthtimespec = pipe->pipe_btime;
880 ub->st_uid = kauth_cred_geteuid(fp->f_cred);
881 ub->st_gid = kauth_cred_getegid(fp->f_cred);
882
883 /*
884 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
885 * XXX (st_dev, st_ino) should be unique.
886 */
887 mutex_exit(pipe->pipe_lock);
888 return 0;
889 }
890
891 static int
892 pipe_close(file_t *fp)
893 {
894 struct pipe *pipe = fp->f_pipe;
895
896 fp->f_pipe = NULL;
897 pipeclose(pipe);
898 return (0);
899 }
900
901 static void
902 pipe_restart(file_t *fp)
903 {
904 struct pipe *pipe = fp->f_pipe;
905
906 /*
907 * Unblock blocked reads/writes in order to allow close() to complete.
908 * System calls return ERESTART so that the fd is revalidated.
909 * (Partial writes return the transfer length.)
910 */
911 mutex_enter(pipe->pipe_lock);
912 pipe->pipe_state |= PIPE_RESTART;
913 /* Wakeup both cvs, maybe we only need one, but maybe there are some
914 * other paths where wakeup is needed, and it saves deciding which! */
915 cv_broadcast(&pipe->pipe_rcv);
916 cv_broadcast(&pipe->pipe_wcv);
917 mutex_exit(pipe->pipe_lock);
918 }
919
920 static int
921 pipe_fpathconf(struct file *fp, int name, register_t *retval)
922 {
923
924 switch (name) {
925 case _PC_PIPE_BUF:
926 *retval = PIPE_BUF;
927 return 0;
928 default:
929 return EINVAL;
930 }
931 }
932
933 static int
934 pipe_posix_fadvise(struct file *fp, off_t offset, off_t len, int advice)
935 {
936
937 return ESPIPE;
938 }
939
940 static void
941 pipe_free_kmem(struct pipe *pipe)
942 {
943
944 if (pipe->pipe_buffer.buffer != NULL) {
945 if (pipe->pipe_buffer.size > PIPE_SIZE) {
946 atomic_dec_uint(&nbigpipe);
947 }
948 if (pipe->pipe_buffer.buffer != (void *)pipe->pipe_kmem) {
949 uvm_km_free(kernel_map,
950 (vaddr_t)pipe->pipe_buffer.buffer,
951 pipe->pipe_buffer.size, UVM_KMF_PAGEABLE);
952 atomic_add_int(&amountpipekva,
953 -pipe->pipe_buffer.size);
954 }
955 pipe->pipe_buffer.buffer = NULL;
956 }
957 }
958
959 /*
960 * Shutdown the pipe.
961 */
962 static void
963 pipeclose(struct pipe *pipe)
964 {
965 kmutex_t *lock;
966 struct pipe *ppipe;
967
968 KASSERT(cv_is_valid(&pipe->pipe_rcv));
969 KASSERT(cv_is_valid(&pipe->pipe_wcv));
970 KASSERT(cv_is_valid(&pipe->pipe_draincv));
971 KASSERT(cv_is_valid(&pipe->pipe_lkcv));
972
973 lock = pipe->pipe_lock;
974 KASSERT(lock != NULL);
975
976 mutex_enter(lock);
977 pipeselwakeup(pipe, pipe, POLL_HUP);
978
979 /*
980 * If the other side is blocked, wake it up saying that
981 * we want to close it down.
982 */
983 pipe->pipe_state |= PIPE_EOF;
984 if (pipe->pipe_busy) {
985 while (pipe->pipe_busy) {
986 cv_broadcast(&pipe->pipe_wcv);
987 cv_wait_sig(&pipe->pipe_draincv, lock);
988 }
989 }
990
991 /*
992 * Disconnect from peer.
993 */
994 if ((ppipe = pipe->pipe_peer) != NULL) {
995 pipeselwakeup(ppipe, ppipe, POLL_HUP);
996 ppipe->pipe_state |= PIPE_EOF;
997 cv_broadcast(&ppipe->pipe_rcv);
998 ppipe->pipe_peer = NULL;
999 }
1000
1001 /*
1002 * Any knote objects still left in the list are
1003 * the one attached by peer. Since no one will
1004 * traverse this list, we just clear it.
1005 *
1006 * XXX Exposes select/kqueue internals.
1007 */
1008 SLIST_INIT(&pipe->pipe_sel.sel_klist);
1009
1010 KASSERT((pipe->pipe_state & PIPE_LOCKFL) == 0);
1011 mutex_exit(lock);
1012 mutex_obj_free(lock);
1013
1014 /*
1015 * Free resources.
1016 */
1017 pipefree(pipe);
1018 }
1019
1020 static void
1021 pipefree(struct pipe *pipe)
1022 {
1023
1024 pipe->pipe_pgid = 0;
1025 pipe->pipe_state = PIPE_SIGNALR;
1026 pipe->pipe_peer = NULL;
1027 pipe->pipe_lock = NULL;
1028 pipe_free_kmem(pipe);
1029 if (pipe->pipe_kmem != 0) {
1030 pool_cache_put(pipe_rd_cache, pipe);
1031 } else {
1032 pool_cache_put(pipe_wr_cache, pipe);
1033 }
1034 }
1035
1036 static void
1037 filt_pipedetach(struct knote *kn)
1038 {
1039 struct pipe *pipe;
1040 kmutex_t *lock;
1041
1042 pipe = ((file_t *)kn->kn_obj)->f_pipe;
1043 lock = pipe->pipe_lock;
1044
1045 mutex_enter(lock);
1046
1047 switch(kn->kn_filter) {
1048 case EVFILT_WRITE:
1049 /* Need the peer structure, not our own. */
1050 pipe = pipe->pipe_peer;
1051
1052 /* If reader end already closed, just return. */
1053 if (pipe == NULL) {
1054 mutex_exit(lock);
1055 return;
1056 }
1057
1058 break;
1059 default:
1060 /* Nothing to do. */
1061 break;
1062 }
1063
1064 KASSERT(kn->kn_hook == pipe);
1065 selremove_knote(&pipe->pipe_sel, kn);
1066 mutex_exit(lock);
1067 }
1068
1069 static int
1070 filt_piperead(struct knote *kn, long hint)
1071 {
1072 struct pipe *pipe = ((file_t *)kn->kn_obj)->f_pipe;
1073 struct pipe *ppipe;
1074 int rv;
1075
1076 if ((hint & NOTE_SUBMIT) == 0) {
1077 mutex_enter(pipe->pipe_lock);
1078 }
1079 ppipe = pipe->pipe_peer;
1080 kn->kn_data = pipe->pipe_buffer.cnt;
1081
1082 if ((pipe->pipe_state & PIPE_EOF) ||
1083 (ppipe == NULL) || (ppipe->pipe_state & PIPE_EOF)) {
1084 knote_set_eof(kn, 0);
1085 rv = 1;
1086 } else {
1087 rv = kn->kn_data > 0;
1088 }
1089
1090 if ((hint & NOTE_SUBMIT) == 0) {
1091 mutex_exit(pipe->pipe_lock);
1092 }
1093 return rv;
1094 }
1095
1096 static int
1097 filt_pipewrite(struct knote *kn, long hint)
1098 {
1099 struct pipe *pipe = ((file_t *)kn->kn_obj)->f_pipe;
1100 struct pipe *ppipe;
1101 int rv;
1102
1103 if ((hint & NOTE_SUBMIT) == 0) {
1104 mutex_enter(pipe->pipe_lock);
1105 }
1106 ppipe = pipe->pipe_peer;
1107
1108 if ((ppipe == NULL) || (ppipe->pipe_state & PIPE_EOF)) {
1109 kn->kn_data = 0;
1110 knote_set_eof(kn, 0);
1111 rv = 1;
1112 } else {
1113 kn->kn_data = ppipe->pipe_buffer.size - ppipe->pipe_buffer.cnt;
1114 rv = kn->kn_data >= PIPE_BUF;
1115 }
1116
1117 if ((hint & NOTE_SUBMIT) == 0) {
1118 mutex_exit(pipe->pipe_lock);
1119 }
1120 return rv;
1121 }
1122
1123 static const struct filterops pipe_rfiltops = {
1124 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
1125 .f_attach = NULL,
1126 .f_detach = filt_pipedetach,
1127 .f_event = filt_piperead,
1128 };
1129
1130 static const struct filterops pipe_wfiltops = {
1131 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
1132 .f_attach = NULL,
1133 .f_detach = filt_pipedetach,
1134 .f_event = filt_pipewrite,
1135 };
1136
1137 static int
1138 pipe_kqfilter(file_t *fp, struct knote *kn)
1139 {
1140 struct pipe *pipe;
1141 kmutex_t *lock;
1142
1143 pipe = ((file_t *)kn->kn_obj)->f_pipe;
1144 lock = pipe->pipe_lock;
1145
1146 mutex_enter(lock);
1147
1148 switch (kn->kn_filter) {
1149 case EVFILT_READ:
1150 kn->kn_fop = &pipe_rfiltops;
1151 break;
1152 case EVFILT_WRITE:
1153 kn->kn_fop = &pipe_wfiltops;
1154 pipe = pipe->pipe_peer;
1155 if (pipe == NULL) {
1156 /* Other end of pipe has been closed. */
1157 mutex_exit(lock);
1158 return (EBADF);
1159 }
1160 break;
1161 default:
1162 mutex_exit(lock);
1163 return (EINVAL);
1164 }
1165
1166 kn->kn_hook = pipe;
1167 selrecord_knote(&pipe->pipe_sel, kn);
1168 mutex_exit(lock);
1169
1170 return (0);
1171 }
1172
1173 /*
1174 * Handle pipe sysctls.
1175 */
1176 SYSCTL_SETUP(sysctl_kern_pipe_setup, "sysctl kern.pipe subtree setup")
1177 {
1178
1179 sysctl_createv(clog, 0, NULL, NULL,
1180 CTLFLAG_PERMANENT,
1181 CTLTYPE_NODE, "pipe",
1182 SYSCTL_DESCR("Pipe settings"),
1183 NULL, 0, NULL, 0,
1184 CTL_KERN, KERN_PIPE, CTL_EOL);
1185
1186 sysctl_createv(clog, 0, NULL, NULL,
1187 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1188 CTLTYPE_INT, "maxbigpipes",
1189 SYSCTL_DESCR("Maximum number of \"big\" pipes"),
1190 NULL, 0, &maxbigpipes, 0,
1191 CTL_KERN, KERN_PIPE, KERN_PIPE_MAXBIGPIPES, CTL_EOL);
1192 sysctl_createv(clog, 0, NULL, NULL,
1193 CTLFLAG_PERMANENT,
1194 CTLTYPE_INT, "nbigpipes",
1195 SYSCTL_DESCR("Number of \"big\" pipes"),
1196 NULL, 0, &nbigpipe, 0,
1197 CTL_KERN, KERN_PIPE, KERN_PIPE_NBIGPIPES, CTL_EOL);
1198 sysctl_createv(clog, 0, NULL, NULL,
1199 CTLFLAG_PERMANENT,
1200 CTLTYPE_INT, "kvasize",
1201 SYSCTL_DESCR("Amount of kernel memory consumed by pipe "
1202 "buffers"),
1203 NULL, 0, &amountpipekva, 0,
1204 CTL_KERN, KERN_PIPE, KERN_PIPE_KVASIZE, CTL_EOL);
1205 }
1206