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