FreeBSD/Linux Kernel Cross Reference
sys/kern/sys_pipe.c
1 /*-
2 * SPDX-License-Identifier: BSD-4-Clause
3 *
4 * Copyright (c) 1996 John S. Dyson
5 * Copyright (c) 2012 Giovanni Trematerra
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice immediately at the beginning of the file, without modification,
13 * this list of conditions, and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Absolutely no warranty of function or purpose is made by the author
18 * John S. Dyson.
19 * 4. Modifications may be freely made to this file if the above conditions
20 * are met.
21 */
22
23 /*
24 * This file contains a high-performance replacement for the socket-based
25 * pipes scheme originally used in FreeBSD/4.4Lite. It does not support
26 * all features of sockets, but does do everything that pipes normally
27 * do.
28 */
29
30 /*
31 * This code has two modes of operation, a small write mode and a large
32 * write mode. The small write mode acts like conventional pipes with
33 * a kernel buffer. If the buffer is less than PIPE_MINDIRECT, then the
34 * "normal" pipe buffering is done. If the buffer is between PIPE_MINDIRECT
35 * and PIPE_SIZE in size, the sending process pins the underlying pages in
36 * memory, and the receiving process copies directly from these pinned pages
37 * in the sending process.
38 *
39 * If the sending process receives a signal, it is possible that it will
40 * go away, and certainly its address space can change, because control
41 * is returned back to the user-mode side. In that case, the pipe code
42 * arranges to copy the buffer supplied by the user process, to a pageable
43 * kernel buffer, and the receiving process will grab the data from the
44 * pageable kernel buffer. Since signals don't happen all that often,
45 * the copy operation is normally eliminated.
46 *
47 * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
48 * happen for small transfers so that the system will not spend all of
49 * its time context switching.
50 *
51 * In order to limit the resource use of pipes, two sysctls exist:
52 *
53 * kern.ipc.maxpipekva - This is a hard limit on the amount of pageable
54 * address space available to us in pipe_map. This value is normally
55 * autotuned, but may also be loader tuned.
56 *
57 * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
58 * memory in use by pipes.
59 *
60 * Based on how large pipekva is relative to maxpipekva, the following
61 * will happen:
62 *
63 * 0% - 50%:
64 * New pipes are given 16K of memory backing, pipes may dynamically
65 * grow to as large as 64K where needed.
66 * 50% - 75%:
67 * New pipes are given 4K (or PAGE_SIZE) of memory backing,
68 * existing pipes may NOT grow.
69 * 75% - 100%:
70 * New pipes are given 4K (or PAGE_SIZE) of memory backing,
71 * existing pipes will be shrunk down to 4K whenever possible.
72 *
73 * Resizing may be disabled by setting kern.ipc.piperesizeallowed=0. If
74 * that is set, the only resize that will occur is the 0 -> SMALL_PIPE_SIZE
75 * resize which MUST occur for reverse-direction pipes when they are
76 * first used.
77 *
78 * Additional information about the current state of pipes may be obtained
79 * from kern.ipc.pipes, kern.ipc.pipefragretry, kern.ipc.pipeallocfail,
80 * and kern.ipc.piperesizefail.
81 *
82 * Locking rules: There are two locks present here: A mutex, used via
83 * PIPE_LOCK, and a flag, used via pipelock(). All locking is done via
84 * the flag, as mutexes can not persist over uiomove. The mutex
85 * exists only to guard access to the flag, and is not in itself a
86 * locking mechanism. Also note that there is only a single mutex for
87 * both directions of a pipe.
88 *
89 * As pipelock() may have to sleep before it can acquire the flag, it
90 * is important to reread all data after a call to pipelock(); everything
91 * in the structure may have changed.
92 */
93
94 #include <sys/cdefs.h>
95 __FBSDID("$FreeBSD$");
96
97 #include <sys/param.h>
98 #include <sys/systm.h>
99 #include <sys/conf.h>
100 #include <sys/fcntl.h>
101 #include <sys/file.h>
102 #include <sys/filedesc.h>
103 #include <sys/filio.h>
104 #include <sys/kernel.h>
105 #include <sys/lock.h>
106 #include <sys/mutex.h>
107 #include <sys/ttycom.h>
108 #include <sys/stat.h>
109 #include <sys/malloc.h>
110 #include <sys/poll.h>
111 #include <sys/selinfo.h>
112 #include <sys/signalvar.h>
113 #include <sys/syscallsubr.h>
114 #include <sys/sysctl.h>
115 #include <sys/sysproto.h>
116 #include <sys/pipe.h>
117 #include <sys/proc.h>
118 #include <sys/vnode.h>
119 #include <sys/uio.h>
120 #include <sys/user.h>
121 #include <sys/event.h>
122
123 #include <security/mac/mac_framework.h>
124
125 #include <vm/vm.h>
126 #include <vm/vm_param.h>
127 #include <vm/vm_object.h>
128 #include <vm/vm_kern.h>
129 #include <vm/vm_extern.h>
130 #include <vm/pmap.h>
131 #include <vm/vm_map.h>
132 #include <vm/vm_page.h>
133 #include <vm/uma.h>
134
135 /*
136 * Use this define if you want to disable *fancy* VM things. Expect an
137 * approx 30% decrease in transfer rate. This could be useful for
138 * NetBSD or OpenBSD.
139 */
140 /* #define PIPE_NODIRECT */
141
142 #define PIPE_PEER(pipe) \
143 (((pipe)->pipe_type & PIPE_TYPE_NAMED) ? (pipe) : ((pipe)->pipe_peer))
144
145 /*
146 * interfaces to the outside world
147 */
148 static fo_rdwr_t pipe_read;
149 static fo_rdwr_t pipe_write;
150 static fo_truncate_t pipe_truncate;
151 static fo_ioctl_t pipe_ioctl;
152 static fo_poll_t pipe_poll;
153 static fo_kqfilter_t pipe_kqfilter;
154 static fo_stat_t pipe_stat;
155 static fo_close_t pipe_close;
156 static fo_chmod_t pipe_chmod;
157 static fo_chown_t pipe_chown;
158 static fo_fill_kinfo_t pipe_fill_kinfo;
159
160 struct fileops pipeops = {
161 .fo_read = pipe_read,
162 .fo_write = pipe_write,
163 .fo_truncate = pipe_truncate,
164 .fo_ioctl = pipe_ioctl,
165 .fo_poll = pipe_poll,
166 .fo_kqfilter = pipe_kqfilter,
167 .fo_stat = pipe_stat,
168 .fo_close = pipe_close,
169 .fo_chmod = pipe_chmod,
170 .fo_chown = pipe_chown,
171 .fo_sendfile = invfo_sendfile,
172 .fo_fill_kinfo = pipe_fill_kinfo,
173 .fo_flags = DFLAG_PASSABLE
174 };
175
176 static void filt_pipedetach(struct knote *kn);
177 static void filt_pipedetach_notsup(struct knote *kn);
178 static int filt_pipenotsup(struct knote *kn, long hint);
179 static int filt_piperead(struct knote *kn, long hint);
180 static int filt_pipewrite(struct knote *kn, long hint);
181
182 static struct filterops pipe_nfiltops = {
183 .f_isfd = 1,
184 .f_detach = filt_pipedetach_notsup,
185 .f_event = filt_pipenotsup
186 };
187 static struct filterops pipe_rfiltops = {
188 .f_isfd = 1,
189 .f_detach = filt_pipedetach,
190 .f_event = filt_piperead
191 };
192 static struct filterops pipe_wfiltops = {
193 .f_isfd = 1,
194 .f_detach = filt_pipedetach,
195 .f_event = filt_pipewrite
196 };
197
198 /*
199 * Default pipe buffer size(s), this can be kind-of large now because pipe
200 * space is pageable. The pipe code will try to maintain locality of
201 * reference for performance reasons, so small amounts of outstanding I/O
202 * will not wipe the cache.
203 */
204 #define MINPIPESIZE (PIPE_SIZE/3)
205 #define MAXPIPESIZE (2*PIPE_SIZE/3)
206
207 static long amountpipekva;
208 static int pipefragretry;
209 static int pipeallocfail;
210 static int piperesizefail;
211 static int piperesizeallowed = 1;
212 static long pipe_mindirect = PIPE_MINDIRECT;
213
214 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
215 &maxpipekva, 0, "Pipe KVA limit");
216 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
217 &amountpipekva, 0, "Pipe KVA usage");
218 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
219 &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
220 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
221 &pipeallocfail, 0, "Pipe allocation failures");
222 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
223 &piperesizefail, 0, "Pipe resize failures");
224 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
225 &piperesizeallowed, 0, "Pipe resizing allowed");
226 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipe_mindirect, CTLFLAG_RWTUN,
227 &pipe_mindirect, 0, "Pipe minimum I/OO size for VM optimization");
228
229 static void pipeinit(void *dummy __unused);
230 static void pipeclose(struct pipe *cpipe);
231 static void pipe_free_kmem(struct pipe *cpipe);
232 static int pipe_create(struct pipe *pipe, bool backing);
233 static int pipe_paircreate(struct thread *td, struct pipepair **p_pp);
234 static __inline int pipelock(struct pipe *cpipe, int catch);
235 static __inline void pipeunlock(struct pipe *cpipe);
236 static void pipe_timestamp(struct timespec *tsp);
237 #ifndef PIPE_NODIRECT
238 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
239 static void pipe_destroy_write_buffer(struct pipe *wpipe);
240 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
241 static void pipe_clone_write_buffer(struct pipe *wpipe);
242 #endif
243 static int pipespace(struct pipe *cpipe, int size);
244 static int pipespace_new(struct pipe *cpipe, int size);
245
246 static int pipe_zone_ctor(void *mem, int size, void *arg, int flags);
247 static int pipe_zone_init(void *mem, int size, int flags);
248 static void pipe_zone_fini(void *mem, int size);
249
250 static uma_zone_t pipe_zone;
251 static struct unrhdr64 pipeino_unr;
252 static dev_t pipedev_ino;
253
254 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
255
256 static void
257 pipeinit(void *dummy __unused)
258 {
259
260 pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
261 pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
262 UMA_ALIGN_PTR, 0);
263 KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
264 new_unrhdr64(&pipeino_unr, 1);
265 pipedev_ino = devfs_alloc_cdp_inode();
266 KASSERT(pipedev_ino > 0, ("pipe dev inode not initialized"));
267 }
268
269 static int
270 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
271 {
272 struct pipepair *pp;
273 struct pipe *rpipe, *wpipe;
274
275 KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
276
277 pp = (struct pipepair *)mem;
278
279 /*
280 * We zero both pipe endpoints to make sure all the kmem pointers
281 * are NULL, flag fields are zero'd, etc. We timestamp both
282 * endpoints with the same time.
283 */
284 rpipe = &pp->pp_rpipe;
285 bzero(rpipe, sizeof(*rpipe));
286 pipe_timestamp(&rpipe->pipe_ctime);
287 rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
288
289 wpipe = &pp->pp_wpipe;
290 bzero(wpipe, sizeof(*wpipe));
291 wpipe->pipe_ctime = rpipe->pipe_ctime;
292 wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
293
294 rpipe->pipe_peer = wpipe;
295 rpipe->pipe_pair = pp;
296 wpipe->pipe_peer = rpipe;
297 wpipe->pipe_pair = pp;
298
299 /*
300 * Mark both endpoints as present; they will later get free'd
301 * one at a time. When both are free'd, then the whole pair
302 * is released.
303 */
304 rpipe->pipe_present = PIPE_ACTIVE;
305 wpipe->pipe_present = PIPE_ACTIVE;
306
307 /*
308 * Eventually, the MAC Framework may initialize the label
309 * in ctor or init, but for now we do it elswhere to avoid
310 * blocking in ctor or init.
311 */
312 pp->pp_label = NULL;
313
314 return (0);
315 }
316
317 static int
318 pipe_zone_init(void *mem, int size, int flags)
319 {
320 struct pipepair *pp;
321
322 KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
323
324 pp = (struct pipepair *)mem;
325
326 mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_NEW);
327 return (0);
328 }
329
330 static void
331 pipe_zone_fini(void *mem, int size)
332 {
333 struct pipepair *pp;
334
335 KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
336
337 pp = (struct pipepair *)mem;
338
339 mtx_destroy(&pp->pp_mtx);
340 }
341
342 static int
343 pipe_paircreate(struct thread *td, struct pipepair **p_pp)
344 {
345 struct pipepair *pp;
346 struct pipe *rpipe, *wpipe;
347 int error;
348
349 *p_pp = pp = uma_zalloc(pipe_zone, M_WAITOK);
350 #ifdef MAC
351 /*
352 * The MAC label is shared between the connected endpoints. As a
353 * result mac_pipe_init() and mac_pipe_create() are called once
354 * for the pair, and not on the endpoints.
355 */
356 mac_pipe_init(pp);
357 mac_pipe_create(td->td_ucred, pp);
358 #endif
359 rpipe = &pp->pp_rpipe;
360 wpipe = &pp->pp_wpipe;
361
362 knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
363 knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
364
365 /*
366 * Only the forward direction pipe is backed by big buffer by
367 * default.
368 */
369 error = pipe_create(rpipe, true);
370 if (error != 0)
371 goto fail;
372 error = pipe_create(wpipe, false);
373 if (error != 0) {
374 /*
375 * This cleanup leaves the pipe inode number for rpipe
376 * still allocated, but never used. We do not free
377 * inode numbers for opened pipes, which is required
378 * for correctness because numbers must be unique.
379 * But also it avoids any memory use by the unr
380 * allocator, so stashing away the transient inode
381 * number is reasonable.
382 */
383 pipe_free_kmem(rpipe);
384 goto fail;
385 }
386
387 rpipe->pipe_state |= PIPE_DIRECTOK;
388 wpipe->pipe_state |= PIPE_DIRECTOK;
389 return (0);
390
391 fail:
392 knlist_destroy(&rpipe->pipe_sel.si_note);
393 knlist_destroy(&wpipe->pipe_sel.si_note);
394 #ifdef MAC
395 mac_pipe_destroy(pp);
396 #endif
397 uma_zfree(pipe_zone, pp);
398 return (error);
399 }
400
401 int
402 pipe_named_ctor(struct pipe **ppipe, struct thread *td)
403 {
404 struct pipepair *pp;
405 int error;
406
407 error = pipe_paircreate(td, &pp);
408 if (error != 0)
409 return (error);
410 pp->pp_rpipe.pipe_type |= PIPE_TYPE_NAMED;
411 *ppipe = &pp->pp_rpipe;
412 return (0);
413 }
414
415 void
416 pipe_dtor(struct pipe *dpipe)
417 {
418 struct pipe *peer;
419
420 peer = (dpipe->pipe_type & PIPE_TYPE_NAMED) != 0 ? dpipe->pipe_peer : NULL;
421 funsetown(&dpipe->pipe_sigio);
422 pipeclose(dpipe);
423 if (peer != NULL) {
424 funsetown(&peer->pipe_sigio);
425 pipeclose(peer);
426 }
427 }
428
429 /*
430 * Get a timestamp.
431 *
432 * This used to be vfs_timestamp but the higher precision is unnecessary and
433 * can very negatively affect performance in virtualized environments (e.g., on
434 * vms running on amd64 when using the rdtscp instruction).
435 */
436 static void
437 pipe_timestamp(struct timespec *tsp)
438 {
439
440 getnanotime(tsp);
441 }
442
443 /*
444 * The pipe system call for the DTYPE_PIPE type of pipes. If we fail, let
445 * the zone pick up the pieces via pipeclose().
446 */
447 int
448 kern_pipe(struct thread *td, int fildes[2], int flags, struct filecaps *fcaps1,
449 struct filecaps *fcaps2)
450 {
451 struct file *rf, *wf;
452 struct pipe *rpipe, *wpipe;
453 struct pipepair *pp;
454 int fd, fflags, error;
455
456 error = pipe_paircreate(td, &pp);
457 if (error != 0)
458 return (error);
459 rpipe = &pp->pp_rpipe;
460 wpipe = &pp->pp_wpipe;
461 error = falloc_caps(td, &rf, &fd, flags, fcaps1);
462 if (error) {
463 pipeclose(rpipe);
464 pipeclose(wpipe);
465 return (error);
466 }
467 /* An extra reference on `rf' has been held for us by falloc_caps(). */
468 fildes[0] = fd;
469
470 fflags = FREAD | FWRITE;
471 if ((flags & O_NONBLOCK) != 0)
472 fflags |= FNONBLOCK;
473
474 /*
475 * Warning: once we've gotten past allocation of the fd for the
476 * read-side, we can only drop the read side via fdrop() in order
477 * to avoid races against processes which manage to dup() the read
478 * side while we are blocked trying to allocate the write side.
479 */
480 finit(rf, fflags, DTYPE_PIPE, rpipe, &pipeops);
481 error = falloc_caps(td, &wf, &fd, flags, fcaps2);
482 if (error) {
483 fdclose(td, rf, fildes[0]);
484 fdrop(rf, td);
485 /* rpipe has been closed by fdrop(). */
486 pipeclose(wpipe);
487 return (error);
488 }
489 /* An extra reference on `wf' has been held for us by falloc_caps(). */
490 finit(wf, fflags, DTYPE_PIPE, wpipe, &pipeops);
491 fdrop(wf, td);
492 fildes[1] = fd;
493 fdrop(rf, td);
494
495 return (0);
496 }
497
498 #ifdef COMPAT_FREEBSD10
499 /* ARGSUSED */
500 int
501 freebsd10_pipe(struct thread *td, struct freebsd10_pipe_args *uap __unused)
502 {
503 int error;
504 int fildes[2];
505
506 error = kern_pipe(td, fildes, 0, NULL, NULL);
507 if (error)
508 return (error);
509
510 td->td_retval[0] = fildes[0];
511 td->td_retval[1] = fildes[1];
512
513 return (0);
514 }
515 #endif
516
517 int
518 sys_pipe2(struct thread *td, struct pipe2_args *uap)
519 {
520 int error, fildes[2];
521
522 if (uap->flags & ~(O_CLOEXEC | O_NONBLOCK))
523 return (EINVAL);
524 error = kern_pipe(td, fildes, uap->flags, NULL, NULL);
525 if (error)
526 return (error);
527 error = copyout(fildes, uap->fildes, 2 * sizeof(int));
528 if (error) {
529 (void)kern_close(td, fildes[0]);
530 (void)kern_close(td, fildes[1]);
531 }
532 return (error);
533 }
534
535 /*
536 * Allocate kva for pipe circular buffer, the space is pageable
537 * This routine will 'realloc' the size of a pipe safely, if it fails
538 * it will retain the old buffer.
539 * If it fails it will return ENOMEM.
540 */
541 static int
542 pipespace_new(struct pipe *cpipe, int size)
543 {
544 caddr_t buffer;
545 int error, cnt, firstseg;
546 static int curfail = 0;
547 static struct timeval lastfail;
548
549 KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
550 KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
551 ("pipespace: resize of direct writes not allowed"));
552 retry:
553 cnt = cpipe->pipe_buffer.cnt;
554 if (cnt > size)
555 size = cnt;
556
557 size = round_page(size);
558 buffer = (caddr_t) vm_map_min(pipe_map);
559
560 error = vm_map_find(pipe_map, NULL, 0, (vm_offset_t *)&buffer, size, 0,
561 VMFS_ANY_SPACE, VM_PROT_RW, VM_PROT_RW, 0);
562 if (error != KERN_SUCCESS) {
563 if (cpipe->pipe_buffer.buffer == NULL &&
564 size > SMALL_PIPE_SIZE) {
565 size = SMALL_PIPE_SIZE;
566 pipefragretry++;
567 goto retry;
568 }
569 if (cpipe->pipe_buffer.buffer == NULL) {
570 pipeallocfail++;
571 if (ppsratecheck(&lastfail, &curfail, 1))
572 printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
573 } else {
574 piperesizefail++;
575 }
576 return (ENOMEM);
577 }
578
579 /* copy data, then free old resources if we're resizing */
580 if (cnt > 0) {
581 if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
582 firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
583 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
584 buffer, firstseg);
585 if ((cnt - firstseg) > 0)
586 bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
587 cpipe->pipe_buffer.in);
588 } else {
589 bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
590 buffer, cnt);
591 }
592 }
593 pipe_free_kmem(cpipe);
594 cpipe->pipe_buffer.buffer = buffer;
595 cpipe->pipe_buffer.size = size;
596 cpipe->pipe_buffer.in = cnt;
597 cpipe->pipe_buffer.out = 0;
598 cpipe->pipe_buffer.cnt = cnt;
599 atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
600 return (0);
601 }
602
603 /*
604 * Wrapper for pipespace_new() that performs locking assertions.
605 */
606 static int
607 pipespace(struct pipe *cpipe, int size)
608 {
609
610 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
611 ("Unlocked pipe passed to pipespace"));
612 return (pipespace_new(cpipe, size));
613 }
614
615 /*
616 * lock a pipe for I/O, blocking other access
617 */
618 static __inline int
619 pipelock(struct pipe *cpipe, int catch)
620 {
621 int error, prio;
622
623 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
624
625 prio = PRIBIO;
626 if (catch)
627 prio |= PCATCH;
628 while (cpipe->pipe_state & PIPE_LOCKFL) {
629 KASSERT(cpipe->pipe_waiters >= 0,
630 ("%s: bad waiter count %d", __func__,
631 cpipe->pipe_waiters));
632 cpipe->pipe_waiters++;
633 error = msleep(cpipe, PIPE_MTX(cpipe),
634 prio, "pipelk", 0);
635 cpipe->pipe_waiters--;
636 if (error != 0)
637 return (error);
638 }
639 cpipe->pipe_state |= PIPE_LOCKFL;
640 return (0);
641 }
642
643 /*
644 * unlock a pipe I/O lock
645 */
646 static __inline void
647 pipeunlock(struct pipe *cpipe)
648 {
649
650 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
651 KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
652 ("Unlocked pipe passed to pipeunlock"));
653 KASSERT(cpipe->pipe_waiters >= 0,
654 ("%s: bad waiter count %d", __func__,
655 cpipe->pipe_waiters));
656 cpipe->pipe_state &= ~PIPE_LOCKFL;
657 if (cpipe->pipe_waiters > 0) {
658 wakeup_one(cpipe);
659 }
660 }
661
662 void
663 pipeselwakeup(struct pipe *cpipe)
664 {
665
666 PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
667 if (cpipe->pipe_state & PIPE_SEL) {
668 selwakeuppri(&cpipe->pipe_sel, PSOCK);
669 if (!SEL_WAITING(&cpipe->pipe_sel))
670 cpipe->pipe_state &= ~PIPE_SEL;
671 }
672 if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
673 pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
674 KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
675 }
676
677 /*
678 * Initialize and allocate VM and memory for pipe. The structure
679 * will start out zero'd from the ctor, so we just manage the kmem.
680 */
681 static int
682 pipe_create(struct pipe *pipe, bool large_backing)
683 {
684 int error;
685
686 error = pipespace_new(pipe, !large_backing || amountpipekva >
687 maxpipekva / 2 ? SMALL_PIPE_SIZE : PIPE_SIZE);
688 if (error == 0)
689 pipe->pipe_ino = alloc_unr64(&pipeino_unr);
690 return (error);
691 }
692
693 /* ARGSUSED */
694 static int
695 pipe_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
696 int flags, struct thread *td)
697 {
698 struct pipe *rpipe;
699 int error;
700 int nread = 0;
701 int size;
702
703 rpipe = fp->f_data;
704 PIPE_LOCK(rpipe);
705 ++rpipe->pipe_busy;
706 error = pipelock(rpipe, 1);
707 if (error)
708 goto unlocked_error;
709
710 #ifdef MAC
711 error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
712 if (error)
713 goto locked_error;
714 #endif
715 if (amountpipekva > (3 * maxpipekva) / 4) {
716 if ((rpipe->pipe_state & PIPE_DIRECTW) == 0 &&
717 rpipe->pipe_buffer.size > SMALL_PIPE_SIZE &&
718 rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE &&
719 piperesizeallowed == 1) {
720 PIPE_UNLOCK(rpipe);
721 pipespace(rpipe, SMALL_PIPE_SIZE);
722 PIPE_LOCK(rpipe);
723 }
724 }
725
726 while (uio->uio_resid) {
727 /*
728 * normal pipe buffer receive
729 */
730 if (rpipe->pipe_buffer.cnt > 0) {
731 size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
732 if (size > rpipe->pipe_buffer.cnt)
733 size = rpipe->pipe_buffer.cnt;
734 if (size > uio->uio_resid)
735 size = uio->uio_resid;
736
737 PIPE_UNLOCK(rpipe);
738 error = uiomove(
739 &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
740 size, uio);
741 PIPE_LOCK(rpipe);
742 if (error)
743 break;
744
745 rpipe->pipe_buffer.out += size;
746 if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
747 rpipe->pipe_buffer.out = 0;
748
749 rpipe->pipe_buffer.cnt -= size;
750
751 /*
752 * If there is no more to read in the pipe, reset
753 * its pointers to the beginning. This improves
754 * cache hit stats.
755 */
756 if (rpipe->pipe_buffer.cnt == 0) {
757 rpipe->pipe_buffer.in = 0;
758 rpipe->pipe_buffer.out = 0;
759 }
760 nread += size;
761 #ifndef PIPE_NODIRECT
762 /*
763 * Direct copy, bypassing a kernel buffer.
764 */
765 } else if ((size = rpipe->pipe_pages.cnt) != 0) {
766 if (size > uio->uio_resid)
767 size = (u_int) uio->uio_resid;
768 PIPE_UNLOCK(rpipe);
769 error = uiomove_fromphys(rpipe->pipe_pages.ms,
770 rpipe->pipe_pages.pos, size, uio);
771 PIPE_LOCK(rpipe);
772 if (error)
773 break;
774 nread += size;
775 rpipe->pipe_pages.pos += size;
776 rpipe->pipe_pages.cnt -= size;
777 if (rpipe->pipe_pages.cnt == 0) {
778 rpipe->pipe_state &= ~PIPE_WANTW;
779 wakeup(rpipe);
780 }
781 #endif
782 } else {
783 /*
784 * detect EOF condition
785 * read returns 0 on EOF, no need to set error
786 */
787 if (rpipe->pipe_state & PIPE_EOF)
788 break;
789
790 /*
791 * If the "write-side" has been blocked, wake it up now.
792 */
793 if (rpipe->pipe_state & PIPE_WANTW) {
794 rpipe->pipe_state &= ~PIPE_WANTW;
795 wakeup(rpipe);
796 }
797
798 /*
799 * Break if some data was read.
800 */
801 if (nread > 0)
802 break;
803
804 /*
805 * Unlock the pipe buffer for our remaining processing.
806 * We will either break out with an error or we will
807 * sleep and relock to loop.
808 */
809 pipeunlock(rpipe);
810
811 /*
812 * Handle non-blocking mode operation or
813 * wait for more data.
814 */
815 if (fp->f_flag & FNONBLOCK) {
816 error = EAGAIN;
817 } else {
818 rpipe->pipe_state |= PIPE_WANTR;
819 if ((error = msleep(rpipe, PIPE_MTX(rpipe),
820 PRIBIO | PCATCH,
821 "piperd", 0)) == 0)
822 error = pipelock(rpipe, 1);
823 }
824 if (error)
825 goto unlocked_error;
826 }
827 }
828 #ifdef MAC
829 locked_error:
830 #endif
831 pipeunlock(rpipe);
832
833 /* XXX: should probably do this before getting any locks. */
834 if (error == 0)
835 pipe_timestamp(&rpipe->pipe_atime);
836 unlocked_error:
837 --rpipe->pipe_busy;
838
839 /*
840 * PIPE_WANT processing only makes sense if pipe_busy is 0.
841 */
842 if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
843 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
844 wakeup(rpipe);
845 } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
846 /*
847 * Handle write blocking hysteresis.
848 */
849 if (rpipe->pipe_state & PIPE_WANTW) {
850 rpipe->pipe_state &= ~PIPE_WANTW;
851 wakeup(rpipe);
852 }
853 }
854
855 /*
856 * Only wake up writers if there was actually something read.
857 * Otherwise, when calling read(2) at EOF, a spurious wakeup occurs.
858 */
859 if (nread > 0 &&
860 rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt >= PIPE_BUF)
861 pipeselwakeup(rpipe);
862
863 PIPE_UNLOCK(rpipe);
864 if (nread > 0)
865 td->td_ru.ru_msgrcv++;
866 return (error);
867 }
868
869 #ifndef PIPE_NODIRECT
870 /*
871 * Map the sending processes' buffer into kernel space and wire it.
872 * This is similar to a physical write operation.
873 */
874 static int
875 pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio)
876 {
877 u_int size;
878 int i;
879
880 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
881 KASSERT((wpipe->pipe_state & PIPE_DIRECTW) == 0,
882 ("%s: PIPE_DIRECTW set on %p", __func__, wpipe));
883 KASSERT(wpipe->pipe_pages.cnt == 0,
884 ("%s: pipe map for %p contains residual data", __func__, wpipe));
885
886 if (uio->uio_iov->iov_len > wpipe->pipe_buffer.size)
887 size = wpipe->pipe_buffer.size;
888 else
889 size = uio->uio_iov->iov_len;
890
891 wpipe->pipe_state |= PIPE_DIRECTW;
892 PIPE_UNLOCK(wpipe);
893 i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
894 (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
895 wpipe->pipe_pages.ms, PIPENPAGES);
896 PIPE_LOCK(wpipe);
897 if (i < 0) {
898 wpipe->pipe_state &= ~PIPE_DIRECTW;
899 return (EFAULT);
900 }
901
902 wpipe->pipe_pages.npages = i;
903 wpipe->pipe_pages.pos =
904 ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
905 wpipe->pipe_pages.cnt = size;
906
907 uio->uio_iov->iov_len -= size;
908 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
909 if (uio->uio_iov->iov_len == 0)
910 uio->uio_iov++;
911 uio->uio_resid -= size;
912 uio->uio_offset += size;
913 return (0);
914 }
915
916 /*
917 * Unwire the process buffer.
918 */
919 static void
920 pipe_destroy_write_buffer(struct pipe *wpipe)
921 {
922
923 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
924 KASSERT((wpipe->pipe_state & PIPE_DIRECTW) != 0,
925 ("%s: PIPE_DIRECTW not set on %p", __func__, wpipe));
926 KASSERT(wpipe->pipe_pages.cnt == 0,
927 ("%s: pipe map for %p contains residual data", __func__, wpipe));
928
929 wpipe->pipe_state &= ~PIPE_DIRECTW;
930 vm_page_unhold_pages(wpipe->pipe_pages.ms, wpipe->pipe_pages.npages);
931 wpipe->pipe_pages.npages = 0;
932 }
933
934 /*
935 * In the case of a signal, the writing process might go away. This
936 * code copies the data into the circular buffer so that the source
937 * pages can be freed without loss of data.
938 */
939 static void
940 pipe_clone_write_buffer(struct pipe *wpipe)
941 {
942 struct uio uio;
943 struct iovec iov;
944 int size;
945 int pos;
946
947 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
948 KASSERT((wpipe->pipe_state & PIPE_DIRECTW) != 0,
949 ("%s: PIPE_DIRECTW not set on %p", __func__, wpipe));
950
951 size = wpipe->pipe_pages.cnt;
952 pos = wpipe->pipe_pages.pos;
953 wpipe->pipe_pages.cnt = 0;
954
955 wpipe->pipe_buffer.in = size;
956 wpipe->pipe_buffer.out = 0;
957 wpipe->pipe_buffer.cnt = size;
958
959 PIPE_UNLOCK(wpipe);
960 iov.iov_base = wpipe->pipe_buffer.buffer;
961 iov.iov_len = size;
962 uio.uio_iov = &iov;
963 uio.uio_iovcnt = 1;
964 uio.uio_offset = 0;
965 uio.uio_resid = size;
966 uio.uio_segflg = UIO_SYSSPACE;
967 uio.uio_rw = UIO_READ;
968 uio.uio_td = curthread;
969 uiomove_fromphys(wpipe->pipe_pages.ms, pos, size, &uio);
970 PIPE_LOCK(wpipe);
971 pipe_destroy_write_buffer(wpipe);
972 }
973
974 /*
975 * This implements the pipe buffer write mechanism. Note that only
976 * a direct write OR a normal pipe write can be pending at any given time.
977 * If there are any characters in the pipe buffer, the direct write will
978 * be deferred until the receiving process grabs all of the bytes from
979 * the pipe buffer. Then the direct mapping write is set-up.
980 */
981 static int
982 pipe_direct_write(struct pipe *wpipe, struct uio *uio)
983 {
984 int error;
985
986 retry:
987 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
988 if ((wpipe->pipe_state & PIPE_EOF) != 0) {
989 error = EPIPE;
990 goto error1;
991 }
992 if (wpipe->pipe_state & PIPE_DIRECTW) {
993 if (wpipe->pipe_state & PIPE_WANTR) {
994 wpipe->pipe_state &= ~PIPE_WANTR;
995 wakeup(wpipe);
996 }
997 pipeselwakeup(wpipe);
998 wpipe->pipe_state |= PIPE_WANTW;
999 pipeunlock(wpipe);
1000 error = msleep(wpipe, PIPE_MTX(wpipe),
1001 PRIBIO | PCATCH, "pipdww", 0);
1002 pipelock(wpipe, 0);
1003 if (error != 0)
1004 goto error1;
1005 goto retry;
1006 }
1007 if (wpipe->pipe_buffer.cnt > 0) {
1008 if (wpipe->pipe_state & PIPE_WANTR) {
1009 wpipe->pipe_state &= ~PIPE_WANTR;
1010 wakeup(wpipe);
1011 }
1012 pipeselwakeup(wpipe);
1013 wpipe->pipe_state |= PIPE_WANTW;
1014 pipeunlock(wpipe);
1015 error = msleep(wpipe, PIPE_MTX(wpipe),
1016 PRIBIO | PCATCH, "pipdwc", 0);
1017 pipelock(wpipe, 0);
1018 if (error != 0)
1019 goto error1;
1020 goto retry;
1021 }
1022
1023 error = pipe_build_write_buffer(wpipe, uio);
1024 if (error) {
1025 goto error1;
1026 }
1027
1028 while (wpipe->pipe_pages.cnt != 0 &&
1029 (wpipe->pipe_state & PIPE_EOF) == 0) {
1030 if (wpipe->pipe_state & PIPE_WANTR) {
1031 wpipe->pipe_state &= ~PIPE_WANTR;
1032 wakeup(wpipe);
1033 }
1034 pipeselwakeup(wpipe);
1035 wpipe->pipe_state |= PIPE_WANTW;
1036 pipeunlock(wpipe);
1037 error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
1038 "pipdwt", 0);
1039 pipelock(wpipe, 0);
1040 if (error != 0)
1041 break;
1042 }
1043
1044 if ((wpipe->pipe_state & PIPE_EOF) != 0) {
1045 wpipe->pipe_pages.cnt = 0;
1046 pipe_destroy_write_buffer(wpipe);
1047 pipeselwakeup(wpipe);
1048 error = EPIPE;
1049 } else if (error == EINTR || error == ERESTART) {
1050 pipe_clone_write_buffer(wpipe);
1051 } else {
1052 pipe_destroy_write_buffer(wpipe);
1053 }
1054 KASSERT((wpipe->pipe_state & PIPE_DIRECTW) == 0,
1055 ("pipe %p leaked PIPE_DIRECTW", wpipe));
1056 return (error);
1057
1058 error1:
1059 wakeup(wpipe);
1060 return (error);
1061 }
1062 #endif
1063
1064 static int
1065 pipe_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1066 int flags, struct thread *td)
1067 {
1068 struct pipe *wpipe, *rpipe;
1069 ssize_t orig_resid;
1070 int desiredsize, error;
1071
1072 rpipe = fp->f_data;
1073 wpipe = PIPE_PEER(rpipe);
1074 PIPE_LOCK(rpipe);
1075 error = pipelock(wpipe, 1);
1076 if (error) {
1077 PIPE_UNLOCK(rpipe);
1078 return (error);
1079 }
1080 /*
1081 * detect loss of pipe read side, issue SIGPIPE if lost.
1082 */
1083 if (wpipe->pipe_present != PIPE_ACTIVE ||
1084 (wpipe->pipe_state & PIPE_EOF)) {
1085 pipeunlock(wpipe);
1086 PIPE_UNLOCK(rpipe);
1087 return (EPIPE);
1088 }
1089 #ifdef MAC
1090 error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
1091 if (error) {
1092 pipeunlock(wpipe);
1093 PIPE_UNLOCK(rpipe);
1094 return (error);
1095 }
1096 #endif
1097 ++wpipe->pipe_busy;
1098
1099 /* Choose a larger size if it's advantageous */
1100 desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1101 while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1102 if (piperesizeallowed != 1)
1103 break;
1104 if (amountpipekva > maxpipekva / 2)
1105 break;
1106 if (desiredsize == BIG_PIPE_SIZE)
1107 break;
1108 desiredsize = desiredsize * 2;
1109 }
1110
1111 /* Choose a smaller size if we're in a OOM situation */
1112 if (amountpipekva > (3 * maxpipekva) / 4 &&
1113 wpipe->pipe_buffer.size > SMALL_PIPE_SIZE &&
1114 wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE &&
1115 piperesizeallowed == 1)
1116 desiredsize = SMALL_PIPE_SIZE;
1117
1118 /* Resize if the above determined that a new size was necessary */
1119 if (desiredsize != wpipe->pipe_buffer.size &&
1120 (wpipe->pipe_state & PIPE_DIRECTW) == 0) {
1121 PIPE_UNLOCK(wpipe);
1122 pipespace(wpipe, desiredsize);
1123 PIPE_LOCK(wpipe);
1124 }
1125 MPASS(wpipe->pipe_buffer.size != 0);
1126
1127 orig_resid = uio->uio_resid;
1128
1129 while (uio->uio_resid) {
1130 int space;
1131
1132 if (wpipe->pipe_state & PIPE_EOF) {
1133 error = EPIPE;
1134 break;
1135 }
1136 #ifndef PIPE_NODIRECT
1137 /*
1138 * If the transfer is large, we can gain performance if
1139 * we do process-to-process copies directly.
1140 * If the write is non-blocking, we don't use the
1141 * direct write mechanism.
1142 *
1143 * The direct write mechanism will detect the reader going
1144 * away on us.
1145 */
1146 if (uio->uio_segflg == UIO_USERSPACE &&
1147 uio->uio_iov->iov_len >= pipe_mindirect &&
1148 wpipe->pipe_buffer.size >= pipe_mindirect &&
1149 (fp->f_flag & FNONBLOCK) == 0) {
1150 error = pipe_direct_write(wpipe, uio);
1151 if (error != 0)
1152 break;
1153 continue;
1154 }
1155 #endif
1156
1157 /*
1158 * Pipe buffered writes cannot be coincidental with
1159 * direct writes. We wait until the currently executing
1160 * direct write is completed before we start filling the
1161 * pipe buffer. We break out if a signal occurs or the
1162 * reader goes away.
1163 */
1164 if (wpipe->pipe_pages.cnt != 0) {
1165 if (wpipe->pipe_state & PIPE_WANTR) {
1166 wpipe->pipe_state &= ~PIPE_WANTR;
1167 wakeup(wpipe);
1168 }
1169 pipeselwakeup(wpipe);
1170 wpipe->pipe_state |= PIPE_WANTW;
1171 pipeunlock(wpipe);
1172 error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1173 "pipbww", 0);
1174 pipelock(wpipe, 0);
1175 if (error != 0)
1176 break;
1177 continue;
1178 }
1179
1180 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1181
1182 /* Writes of size <= PIPE_BUF must be atomic. */
1183 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1184 space = 0;
1185
1186 if (space > 0) {
1187 int size; /* Transfer size */
1188 int segsize; /* first segment to transfer */
1189
1190 /*
1191 * Transfer size is minimum of uio transfer
1192 * and free space in pipe buffer.
1193 */
1194 if (space > uio->uio_resid)
1195 size = uio->uio_resid;
1196 else
1197 size = space;
1198 /*
1199 * First segment to transfer is minimum of
1200 * transfer size and contiguous space in
1201 * pipe buffer. If first segment to transfer
1202 * is less than the transfer size, we've got
1203 * a wraparound in the buffer.
1204 */
1205 segsize = wpipe->pipe_buffer.size -
1206 wpipe->pipe_buffer.in;
1207 if (segsize > size)
1208 segsize = size;
1209
1210 /* Transfer first segment */
1211
1212 PIPE_UNLOCK(rpipe);
1213 error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1214 segsize, uio);
1215 PIPE_LOCK(rpipe);
1216
1217 if (error == 0 && segsize < size) {
1218 KASSERT(wpipe->pipe_buffer.in + segsize ==
1219 wpipe->pipe_buffer.size,
1220 ("Pipe buffer wraparound disappeared"));
1221 /*
1222 * Transfer remaining part now, to
1223 * support atomic writes. Wraparound
1224 * happened.
1225 */
1226
1227 PIPE_UNLOCK(rpipe);
1228 error = uiomove(
1229 &wpipe->pipe_buffer.buffer[0],
1230 size - segsize, uio);
1231 PIPE_LOCK(rpipe);
1232 }
1233 if (error == 0) {
1234 wpipe->pipe_buffer.in += size;
1235 if (wpipe->pipe_buffer.in >=
1236 wpipe->pipe_buffer.size) {
1237 KASSERT(wpipe->pipe_buffer.in ==
1238 size - segsize +
1239 wpipe->pipe_buffer.size,
1240 ("Expected wraparound bad"));
1241 wpipe->pipe_buffer.in = size - segsize;
1242 }
1243
1244 wpipe->pipe_buffer.cnt += size;
1245 KASSERT(wpipe->pipe_buffer.cnt <=
1246 wpipe->pipe_buffer.size,
1247 ("Pipe buffer overflow"));
1248 }
1249 if (error != 0)
1250 break;
1251 continue;
1252 } else {
1253 /*
1254 * If the "read-side" has been blocked, wake it up now.
1255 */
1256 if (wpipe->pipe_state & PIPE_WANTR) {
1257 wpipe->pipe_state &= ~PIPE_WANTR;
1258 wakeup(wpipe);
1259 }
1260
1261 /*
1262 * don't block on non-blocking I/O
1263 */
1264 if (fp->f_flag & FNONBLOCK) {
1265 error = EAGAIN;
1266 break;
1267 }
1268
1269 /*
1270 * We have no more space and have something to offer,
1271 * wake up select/poll.
1272 */
1273 pipeselwakeup(wpipe);
1274
1275 wpipe->pipe_state |= PIPE_WANTW;
1276 pipeunlock(wpipe);
1277 error = msleep(wpipe, PIPE_MTX(rpipe),
1278 PRIBIO | PCATCH, "pipewr", 0);
1279 pipelock(wpipe, 0);
1280 if (error != 0)
1281 break;
1282 continue;
1283 }
1284 }
1285
1286 --wpipe->pipe_busy;
1287
1288 if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1289 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1290 wakeup(wpipe);
1291 } else if (wpipe->pipe_buffer.cnt > 0) {
1292 /*
1293 * If we have put any characters in the buffer, we wake up
1294 * the reader.
1295 */
1296 if (wpipe->pipe_state & PIPE_WANTR) {
1297 wpipe->pipe_state &= ~PIPE_WANTR;
1298 wakeup(wpipe);
1299 }
1300 }
1301
1302 /*
1303 * Don't return EPIPE if any byte was written.
1304 * EINTR and other interrupts are handled by generic I/O layer.
1305 * Do not pretend that I/O succeeded for obvious user error
1306 * like EFAULT.
1307 */
1308 if (uio->uio_resid != orig_resid && error == EPIPE)
1309 error = 0;
1310
1311 if (error == 0)
1312 pipe_timestamp(&wpipe->pipe_mtime);
1313
1314 /*
1315 * We have something to offer,
1316 * wake up select/poll.
1317 */
1318 if (wpipe->pipe_buffer.cnt)
1319 pipeselwakeup(wpipe);
1320
1321 pipeunlock(wpipe);
1322 PIPE_UNLOCK(rpipe);
1323 if (uio->uio_resid != orig_resid)
1324 td->td_ru.ru_msgsnd++;
1325 return (error);
1326 }
1327
1328 /* ARGSUSED */
1329 static int
1330 pipe_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1331 struct thread *td)
1332 {
1333 struct pipe *cpipe;
1334 int error;
1335
1336 cpipe = fp->f_data;
1337 if (cpipe->pipe_type & PIPE_TYPE_NAMED)
1338 error = vnops.fo_truncate(fp, length, active_cred, td);
1339 else
1340 error = invfo_truncate(fp, length, active_cred, td);
1341 return (error);
1342 }
1343
1344 /*
1345 * we implement a very minimal set of ioctls for compatibility with sockets.
1346 */
1347 static int
1348 pipe_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *active_cred,
1349 struct thread *td)
1350 {
1351 struct pipe *mpipe = fp->f_data;
1352 int error;
1353
1354 PIPE_LOCK(mpipe);
1355
1356 #ifdef MAC
1357 error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1358 if (error) {
1359 PIPE_UNLOCK(mpipe);
1360 return (error);
1361 }
1362 #endif
1363
1364 error = 0;
1365 switch (cmd) {
1366 case FIONBIO:
1367 break;
1368
1369 case FIOASYNC:
1370 if (*(int *)data) {
1371 mpipe->pipe_state |= PIPE_ASYNC;
1372 } else {
1373 mpipe->pipe_state &= ~PIPE_ASYNC;
1374 }
1375 break;
1376
1377 case FIONREAD:
1378 if (!(fp->f_flag & FREAD)) {
1379 *(int *)data = 0;
1380 PIPE_UNLOCK(mpipe);
1381 return (0);
1382 }
1383 if (mpipe->pipe_pages.cnt != 0)
1384 *(int *)data = mpipe->pipe_pages.cnt;
1385 else
1386 *(int *)data = mpipe->pipe_buffer.cnt;
1387 break;
1388
1389 case FIOSETOWN:
1390 PIPE_UNLOCK(mpipe);
1391 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1392 goto out_unlocked;
1393
1394 case FIOGETOWN:
1395 *(int *)data = fgetown(&mpipe->pipe_sigio);
1396 break;
1397
1398 /* This is deprecated, FIOSETOWN should be used instead. */
1399 case TIOCSPGRP:
1400 PIPE_UNLOCK(mpipe);
1401 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1402 goto out_unlocked;
1403
1404 /* This is deprecated, FIOGETOWN should be used instead. */
1405 case TIOCGPGRP:
1406 *(int *)data = -fgetown(&mpipe->pipe_sigio);
1407 break;
1408
1409 default:
1410 error = ENOTTY;
1411 break;
1412 }
1413 PIPE_UNLOCK(mpipe);
1414 out_unlocked:
1415 return (error);
1416 }
1417
1418 static int
1419 pipe_poll(struct file *fp, int events, struct ucred *active_cred,
1420 struct thread *td)
1421 {
1422 struct pipe *rpipe;
1423 struct pipe *wpipe;
1424 int levents, revents;
1425 #ifdef MAC
1426 int error;
1427 #endif
1428
1429 revents = 0;
1430 rpipe = fp->f_data;
1431 wpipe = PIPE_PEER(rpipe);
1432 PIPE_LOCK(rpipe);
1433 #ifdef MAC
1434 error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1435 if (error)
1436 goto locked_error;
1437 #endif
1438 if (fp->f_flag & FREAD && events & (POLLIN | POLLRDNORM))
1439 if (rpipe->pipe_pages.cnt > 0 || rpipe->pipe_buffer.cnt > 0)
1440 revents |= events & (POLLIN | POLLRDNORM);
1441
1442 if (fp->f_flag & FWRITE && events & (POLLOUT | POLLWRNORM))
1443 if (wpipe->pipe_present != PIPE_ACTIVE ||
1444 (wpipe->pipe_state & PIPE_EOF) ||
1445 ((wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
1446 ((wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF ||
1447 wpipe->pipe_buffer.size == 0)))
1448 revents |= events & (POLLOUT | POLLWRNORM);
1449
1450 levents = events &
1451 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM | POLLRDBAND);
1452 if (rpipe->pipe_type & PIPE_TYPE_NAMED && fp->f_flag & FREAD && levents &&
1453 fp->f_pipegen == rpipe->pipe_wgen)
1454 events |= POLLINIGNEOF;
1455
1456 if ((events & POLLINIGNEOF) == 0) {
1457 if (rpipe->pipe_state & PIPE_EOF) {
1458 if (fp->f_flag & FREAD)
1459 revents |= (events & (POLLIN | POLLRDNORM));
1460 if (wpipe->pipe_present != PIPE_ACTIVE ||
1461 (wpipe->pipe_state & PIPE_EOF))
1462 revents |= POLLHUP;
1463 }
1464 }
1465
1466 if (revents == 0) {
1467 /*
1468 * Add ourselves regardless of eventmask as we have to return
1469 * POLLHUP even if it was not asked for.
1470 */
1471 if ((fp->f_flag & FREAD) != 0) {
1472 selrecord(td, &rpipe->pipe_sel);
1473 if (SEL_WAITING(&rpipe->pipe_sel))
1474 rpipe->pipe_state |= PIPE_SEL;
1475 }
1476
1477 if ((fp->f_flag & FWRITE) != 0 &&
1478 wpipe->pipe_present == PIPE_ACTIVE) {
1479 selrecord(td, &wpipe->pipe_sel);
1480 if (SEL_WAITING(&wpipe->pipe_sel))
1481 wpipe->pipe_state |= PIPE_SEL;
1482 }
1483 }
1484 #ifdef MAC
1485 locked_error:
1486 #endif
1487 PIPE_UNLOCK(rpipe);
1488
1489 return (revents);
1490 }
1491
1492 /*
1493 * We shouldn't need locks here as we're doing a read and this should
1494 * be a natural race.
1495 */
1496 static int
1497 pipe_stat(struct file *fp, struct stat *ub, struct ucred *active_cred,
1498 struct thread *td)
1499 {
1500 struct pipe *pipe;
1501 #ifdef MAC
1502 int error;
1503 #endif
1504
1505 pipe = fp->f_data;
1506 #ifdef MAC
1507 if (mac_pipe_check_stat_enabled()) {
1508 PIPE_LOCK(pipe);
1509 error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1510 PIPE_UNLOCK(pipe);
1511 if (error) {
1512 return (error);
1513 }
1514 }
1515 #endif
1516
1517 /* For named pipes ask the underlying filesystem. */
1518 if (pipe->pipe_type & PIPE_TYPE_NAMED) {
1519 return (vnops.fo_stat(fp, ub, active_cred, td));
1520 }
1521
1522 bzero(ub, sizeof(*ub));
1523 ub->st_mode = S_IFIFO;
1524 ub->st_blksize = PAGE_SIZE;
1525 if (pipe->pipe_pages.cnt != 0)
1526 ub->st_size = pipe->pipe_pages.cnt;
1527 else
1528 ub->st_size = pipe->pipe_buffer.cnt;
1529 ub->st_blocks = howmany(ub->st_size, ub->st_blksize);
1530 ub->st_atim = pipe->pipe_atime;
1531 ub->st_mtim = pipe->pipe_mtime;
1532 ub->st_ctim = pipe->pipe_ctime;
1533 ub->st_uid = fp->f_cred->cr_uid;
1534 ub->st_gid = fp->f_cred->cr_gid;
1535 ub->st_dev = pipedev_ino;
1536 ub->st_ino = pipe->pipe_ino;
1537 /*
1538 * Left as 0: st_nlink, st_rdev, st_flags, st_gen.
1539 */
1540 return (0);
1541 }
1542
1543 /* ARGSUSED */
1544 static int
1545 pipe_close(struct file *fp, struct thread *td)
1546 {
1547
1548 if (fp->f_vnode != NULL)
1549 return vnops.fo_close(fp, td);
1550 fp->f_ops = &badfileops;
1551 pipe_dtor(fp->f_data);
1552 fp->f_data = NULL;
1553 return (0);
1554 }
1555
1556 static int
1557 pipe_chmod(struct file *fp, mode_t mode, struct ucred *active_cred, struct thread *td)
1558 {
1559 struct pipe *cpipe;
1560 int error;
1561
1562 cpipe = fp->f_data;
1563 if (cpipe->pipe_type & PIPE_TYPE_NAMED)
1564 error = vn_chmod(fp, mode, active_cred, td);
1565 else
1566 error = invfo_chmod(fp, mode, active_cred, td);
1567 return (error);
1568 }
1569
1570 static int
1571 pipe_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
1572 struct thread *td)
1573 {
1574 struct pipe *cpipe;
1575 int error;
1576
1577 cpipe = fp->f_data;
1578 if (cpipe->pipe_type & PIPE_TYPE_NAMED)
1579 error = vn_chown(fp, uid, gid, active_cred, td);
1580 else
1581 error = invfo_chown(fp, uid, gid, active_cred, td);
1582 return (error);
1583 }
1584
1585 static int
1586 pipe_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1587 {
1588 struct pipe *pi;
1589
1590 if (fp->f_type == DTYPE_FIFO)
1591 return (vn_fill_kinfo(fp, kif, fdp));
1592 kif->kf_type = KF_TYPE_PIPE;
1593 pi = fp->f_data;
1594 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
1595 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
1596 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
1597 return (0);
1598 }
1599
1600 static void
1601 pipe_free_kmem(struct pipe *cpipe)
1602 {
1603
1604 KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1605 ("pipe_free_kmem: pipe mutex locked"));
1606
1607 if (cpipe->pipe_buffer.buffer != NULL) {
1608 atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1609 vm_map_remove(pipe_map,
1610 (vm_offset_t)cpipe->pipe_buffer.buffer,
1611 (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1612 cpipe->pipe_buffer.buffer = NULL;
1613 }
1614 #ifndef PIPE_NODIRECT
1615 {
1616 cpipe->pipe_pages.cnt = 0;
1617 cpipe->pipe_pages.pos = 0;
1618 cpipe->pipe_pages.npages = 0;
1619 }
1620 #endif
1621 }
1622
1623 /*
1624 * shutdown the pipe
1625 */
1626 static void
1627 pipeclose(struct pipe *cpipe)
1628 {
1629 struct pipepair *pp;
1630 struct pipe *ppipe;
1631
1632 KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1633
1634 PIPE_LOCK(cpipe);
1635 pipelock(cpipe, 0);
1636 pp = cpipe->pipe_pair;
1637
1638 /*
1639 * If the other side is blocked, wake it up saying that
1640 * we want to close it down.
1641 */
1642 cpipe->pipe_state |= PIPE_EOF;
1643 while (cpipe->pipe_busy) {
1644 wakeup(cpipe);
1645 cpipe->pipe_state |= PIPE_WANT;
1646 pipeunlock(cpipe);
1647 msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1648 pipelock(cpipe, 0);
1649 }
1650
1651 pipeselwakeup(cpipe);
1652
1653 /*
1654 * Disconnect from peer, if any.
1655 */
1656 ppipe = cpipe->pipe_peer;
1657 if (ppipe->pipe_present == PIPE_ACTIVE) {
1658 ppipe->pipe_state |= PIPE_EOF;
1659 wakeup(ppipe);
1660 pipeselwakeup(ppipe);
1661 }
1662
1663 /*
1664 * Mark this endpoint as free. Release kmem resources. We
1665 * don't mark this endpoint as unused until we've finished
1666 * doing that, or the pipe might disappear out from under
1667 * us.
1668 */
1669 PIPE_UNLOCK(cpipe);
1670 pipe_free_kmem(cpipe);
1671 PIPE_LOCK(cpipe);
1672 cpipe->pipe_present = PIPE_CLOSING;
1673 pipeunlock(cpipe);
1674
1675 /*
1676 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1677 * PIPE_FINALIZED, that allows other end to free the
1678 * pipe_pair, only after the knotes are completely dismantled.
1679 */
1680 knlist_clear(&cpipe->pipe_sel.si_note, 1);
1681 cpipe->pipe_present = PIPE_FINALIZED;
1682 seldrain(&cpipe->pipe_sel);
1683 knlist_destroy(&cpipe->pipe_sel.si_note);
1684
1685 /*
1686 * If both endpoints are now closed, release the memory for the
1687 * pipe pair. If not, unlock.
1688 */
1689 if (ppipe->pipe_present == PIPE_FINALIZED) {
1690 PIPE_UNLOCK(cpipe);
1691 #ifdef MAC
1692 mac_pipe_destroy(pp);
1693 #endif
1694 uma_zfree(pipe_zone, cpipe->pipe_pair);
1695 } else
1696 PIPE_UNLOCK(cpipe);
1697 }
1698
1699 /*ARGSUSED*/
1700 static int
1701 pipe_kqfilter(struct file *fp, struct knote *kn)
1702 {
1703 struct pipe *cpipe;
1704
1705 /*
1706 * If a filter is requested that is not supported by this file
1707 * descriptor, don't return an error, but also don't ever generate an
1708 * event.
1709 */
1710 if ((kn->kn_filter == EVFILT_READ) && !(fp->f_flag & FREAD)) {
1711 kn->kn_fop = &pipe_nfiltops;
1712 return (0);
1713 }
1714 if ((kn->kn_filter == EVFILT_WRITE) && !(fp->f_flag & FWRITE)) {
1715 kn->kn_fop = &pipe_nfiltops;
1716 return (0);
1717 }
1718 cpipe = fp->f_data;
1719 PIPE_LOCK(cpipe);
1720 switch (kn->kn_filter) {
1721 case EVFILT_READ:
1722 kn->kn_fop = &pipe_rfiltops;
1723 break;
1724 case EVFILT_WRITE:
1725 kn->kn_fop = &pipe_wfiltops;
1726 if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1727 /* other end of pipe has been closed */
1728 PIPE_UNLOCK(cpipe);
1729 return (EPIPE);
1730 }
1731 cpipe = PIPE_PEER(cpipe);
1732 break;
1733 default:
1734 PIPE_UNLOCK(cpipe);
1735 return (EINVAL);
1736 }
1737
1738 kn->kn_hook = cpipe;
1739 knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1740 PIPE_UNLOCK(cpipe);
1741 return (0);
1742 }
1743
1744 static void
1745 filt_pipedetach(struct knote *kn)
1746 {
1747 struct pipe *cpipe = kn->kn_hook;
1748
1749 PIPE_LOCK(cpipe);
1750 knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1751 PIPE_UNLOCK(cpipe);
1752 }
1753
1754 /*ARGSUSED*/
1755 static int
1756 filt_piperead(struct knote *kn, long hint)
1757 {
1758 struct file *fp = kn->kn_fp;
1759 struct pipe *rpipe = kn->kn_hook;
1760
1761 PIPE_LOCK_ASSERT(rpipe, MA_OWNED);
1762 kn->kn_data = rpipe->pipe_buffer.cnt;
1763 if (kn->kn_data == 0)
1764 kn->kn_data = rpipe->pipe_pages.cnt;
1765
1766 if ((rpipe->pipe_state & PIPE_EOF) != 0 &&
1767 ((rpipe->pipe_type & PIPE_TYPE_NAMED) == 0 ||
1768 fp->f_pipegen != rpipe->pipe_wgen)) {
1769 kn->kn_flags |= EV_EOF;
1770 return (1);
1771 }
1772 kn->kn_flags &= ~EV_EOF;
1773 return (kn->kn_data > 0);
1774 }
1775
1776 /*ARGSUSED*/
1777 static int
1778 filt_pipewrite(struct knote *kn, long hint)
1779 {
1780 struct pipe *wpipe = kn->kn_hook;
1781
1782 /*
1783 * If this end of the pipe is closed, the knote was removed from the
1784 * knlist and the list lock (i.e., the pipe lock) is therefore not held.
1785 */
1786 if (wpipe->pipe_present == PIPE_ACTIVE ||
1787 (wpipe->pipe_type & PIPE_TYPE_NAMED) != 0) {
1788 PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
1789
1790 if (wpipe->pipe_state & PIPE_DIRECTW) {
1791 kn->kn_data = 0;
1792 } else if (wpipe->pipe_buffer.size > 0) {
1793 kn->kn_data = wpipe->pipe_buffer.size -
1794 wpipe->pipe_buffer.cnt;
1795 } else {
1796 kn->kn_data = PIPE_BUF;
1797 }
1798 }
1799
1800 if (wpipe->pipe_present != PIPE_ACTIVE ||
1801 (wpipe->pipe_state & PIPE_EOF)) {
1802 kn->kn_flags |= EV_EOF;
1803 return (1);
1804 }
1805 kn->kn_flags &= ~EV_EOF;
1806 return (kn->kn_data >= PIPE_BUF);
1807 }
1808
1809 static void
1810 filt_pipedetach_notsup(struct knote *kn)
1811 {
1812
1813 }
1814
1815 static int
1816 filt_pipenotsup(struct knote *kn, long hint)
1817 {
1818
1819 return (0);
1820 }
Cache object: bb21d3e82577dde6557e04a8196a2a5b
|