1 /* $NetBSD: kern_descrip.c,v 1.266 2025/07/16 19:14:13 kre Exp $ */ 2 3 /*- 4 * Copyright (c) 2008, 2009, 2023 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Andrew Doran. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 /* 33 * Copyright (c) 1982, 1986, 1989, 1991, 1993 34 * The Regents of the University of California. All rights reserved. 35 * (c) UNIX System Laboratories, Inc. 36 * All or some portions of this file are derived from material licensed 37 * to the University of California by American Telephone and Telegraph 38 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 39 * the permission of UNIX System Laboratories, Inc. 40 * 41 * Redistribution and use in source and binary forms, with or without 42 * modification, are permitted provided that the following conditions 43 * are met: 44 * 1. Redistributions of source code must retain the above copyright 45 * notice, this list of conditions and the following disclaimer. 46 * 2. Redistributions in binary form must reproduce the above copyright 47 * notice, this list of conditions and the following disclaimer in the 48 * documentation and/or other materials provided with the distribution. 49 * 3. Neither the name of the University nor the names of its contributors 50 * may be used to endorse or promote products derived from this software 51 * without specific prior written permission. 52 * 53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 63 * SUCH DAMAGE. 64 * 65 * @(#)kern_descrip.c 8.8 (Berkeley) 2/14/95 66 */ 67 68 /* 69 * File descriptor management. 70 */ 71 72 #include <sys/cdefs.h> 73 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.266 2025/07/16 19:14:13 kre Exp $"); 74 75 #include <sys/param.h> 76 #include <sys/systm.h> 77 #include <sys/filedesc.h> 78 #include <sys/kernel.h> 79 #include <sys/proc.h> 80 #include <sys/file.h> 81 #include <sys/socket.h> 82 #include <sys/socketvar.h> 83 #include <sys/stat.h> 84 #include <sys/ioctl.h> 85 #include <sys/fcntl.h> 86 #include <sys/pool.h> 87 #include <sys/unistd.h> 88 #include <sys/resourcevar.h> 89 #include <sys/conf.h> 90 #include <sys/event.h> 91 #include <sys/kauth.h> 92 #include <sys/atomic.h> 93 #include <sys/syscallargs.h> 94 #include <sys/cpu.h> 95 #include <sys/kmem.h> 96 #include <sys/vnode.h> 97 #include <sys/sysctl.h> 98 #include <sys/ktrace.h> 99 100 /* 101 * A list (head) of open files, counter, and lock protecting them. 102 */ 103 struct filelist filehead __cacheline_aligned; 104 static u_int nfiles __cacheline_aligned; 105 kmutex_t filelist_lock __cacheline_aligned; 106 107 static pool_cache_t filedesc_cache __read_mostly; 108 static pool_cache_t file_cache __read_mostly; 109 110 static int file_ctor(void *, void *, int); 111 static void file_dtor(void *, void *); 112 static void fdfile_ctor(fdfile_t *); 113 static void fdfile_dtor(fdfile_t *); 114 static int filedesc_ctor(void *, void *, int); 115 static void filedesc_dtor(void *, void *); 116 static int filedescopen(dev_t, int, int, lwp_t *); 117 118 static int sysctl_kern_file(SYSCTLFN_PROTO); 119 static int sysctl_kern_file2(SYSCTLFN_PROTO); 120 static void fill_file(struct file *, const struct file *); 121 static void fill_file2(struct kinfo_file *, const file_t *, const fdfile_t *, 122 int, pid_t); 123 124 const struct cdevsw filedesc_cdevsw = { 125 .d_open = filedescopen, 126 .d_close = noclose, 127 .d_read = noread, 128 .d_write = nowrite, 129 .d_ioctl = noioctl, 130 .d_stop = nostop, 131 .d_tty = notty, 132 .d_poll = nopoll, 133 .d_mmap = nommap, 134 .d_kqfilter = nokqfilter, 135 .d_discard = nodiscard, 136 .d_flag = D_OTHER | D_MPSAFE 137 }; 138 139 /* For ease of reading. */ 140 __strong_alias(fd_putvnode,fd_putfile) 141 __strong_alias(fd_putsock,fd_putfile) 142 143 /* 144 * Initialize the descriptor system. 145 */ 146 void 147 fd_sys_init(void) 148 { 149 static struct sysctllog *clog; 150 151 mutex_init(&filelist_lock, MUTEX_DEFAULT, IPL_NONE); 152 153 LIST_INIT(&filehead); 154 155 file_cache = pool_cache_init(sizeof(file_t), coherency_unit, 0, 156 0, "file", NULL, IPL_NONE, file_ctor, file_dtor, NULL); 157 KASSERT(file_cache != NULL); 158 159 filedesc_cache = pool_cache_init(sizeof(filedesc_t), coherency_unit, 160 0, 0, "filedesc", NULL, IPL_NONE, filedesc_ctor, filedesc_dtor, 161 NULL); 162 KASSERT(filedesc_cache != NULL); 163 164 sysctl_createv(&clog, 0, NULL, NULL, 165 CTLFLAG_PERMANENT, 166 CTLTYPE_STRUCT, "file", 167 SYSCTL_DESCR("System open file table"), 168 sysctl_kern_file, 0, NULL, 0, 169 CTL_KERN, KERN_FILE, CTL_EOL); 170 sysctl_createv(&clog, 0, NULL, NULL, 171 CTLFLAG_PERMANENT, 172 CTLTYPE_STRUCT, "file2", 173 SYSCTL_DESCR("System open file table"), 174 sysctl_kern_file2, 0, NULL, 0, 175 CTL_KERN, KERN_FILE2, CTL_EOL); 176 } 177 178 static bool 179 fd_isused(filedesc_t *fdp, unsigned fd) 180 { 181 u_int off = fd >> NDENTRYSHIFT; 182 183 KASSERT(fd < atomic_load_consume(&fdp->fd_dt)->dt_nfiles); 184 185 return (fdp->fd_lomap[off] & (1U << (fd & NDENTRYMASK))) != 0; 186 } 187 188 /* 189 * Verify that the bitmaps match the descriptor table. 190 */ 191 static inline void 192 fd_checkmaps(filedesc_t *fdp) 193 { 194 #ifdef DEBUG 195 fdtab_t *dt; 196 u_int fd; 197 198 KASSERT(fdp->fd_refcnt <= 1 || mutex_owned(&fdp->fd_lock)); 199 200 dt = fdp->fd_dt; 201 if (fdp->fd_refcnt == -1) { 202 /* 203 * fd_free tears down the table without maintaining its bitmap. 204 */ 205 return; 206 } 207 for (fd = 0; fd < dt->dt_nfiles; fd++) { 208 if (fd < NDFDFILE) { 209 KASSERT(dt->dt_ff[fd] == 210 (fdfile_t *)fdp->fd_dfdfile[fd]); 211 } 212 if (dt->dt_ff[fd] == NULL) { 213 KASSERT(!fd_isused(fdp, fd)); 214 } else if (dt->dt_ff[fd]->ff_file != NULL) { 215 KASSERT(fd_isused(fdp, fd)); 216 } 217 } 218 #endif 219 } 220 221 static int 222 fd_next_zero(filedesc_t *fdp, uint32_t *bitmap, int want, u_int bits) 223 { 224 int i, off, maxoff; 225 uint32_t sub; 226 227 KASSERT(mutex_owned(&fdp->fd_lock)); 228 229 fd_checkmaps(fdp); 230 231 if (want > bits) 232 return -1; 233 234 off = want >> NDENTRYSHIFT; 235 i = want & NDENTRYMASK; 236 if (i) { 237 sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i)); 238 if (sub != ~0) 239 goto found; 240 off++; 241 } 242 243 maxoff = NDLOSLOTS(bits); 244 while (off < maxoff) { 245 if ((sub = bitmap[off]) != ~0) 246 goto found; 247 off++; 248 } 249 250 return -1; 251 252 found: 253 return (off << NDENTRYSHIFT) + ffs(~sub) - 1; 254 } 255 256 static int 257 fd_last_set(filedesc_t *fd, int last) 258 { 259 int off, i; 260 fdfile_t **ff = fd->fd_dt->dt_ff; 261 uint32_t *bitmap = fd->fd_lomap; 262 263 KASSERT(mutex_owned(&fd->fd_lock)); 264 265 fd_checkmaps(fd); 266 267 off = (last - 1) >> NDENTRYSHIFT; 268 269 while (off >= 0 && !bitmap[off]) 270 off--; 271 272 if (off < 0) 273 return -1; 274 275 i = ((off + 1) << NDENTRYSHIFT) - 1; 276 if (i >= last) 277 i = last - 1; 278 279 /* XXX should use bitmap */ 280 while (i > 0 && (ff[i] == NULL || !ff[i]->ff_allocated)) 281 i--; 282 283 return i; 284 } 285 286 static inline void 287 fd_used(filedesc_t *fdp, unsigned fd) 288 { 289 u_int off = fd >> NDENTRYSHIFT; 290 fdfile_t *ff; 291 292 ff = fdp->fd_dt->dt_ff[fd]; 293 294 KASSERT(mutex_owned(&fdp->fd_lock)); 295 KASSERT((fdp->fd_lomap[off] & (1U << (fd & NDENTRYMASK))) == 0); 296 KASSERT(ff != NULL); 297 KASSERT(ff->ff_file == NULL); 298 KASSERT(!ff->ff_allocated); 299 300 ff->ff_allocated = true; 301 fdp->fd_lomap[off] |= 1U << (fd & NDENTRYMASK); 302 if (__predict_false(fdp->fd_lomap[off] == ~0)) { 303 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] & 304 (1U << (off & NDENTRYMASK))) == 0); 305 fdp->fd_himap[off >> NDENTRYSHIFT] |= 1U << (off & NDENTRYMASK); 306 } 307 308 if ((int)fd > fdp->fd_lastfile) { 309 fdp->fd_lastfile = fd; 310 } 311 312 fd_checkmaps(fdp); 313 } 314 315 static inline void 316 fd_unused(filedesc_t *fdp, unsigned fd) 317 { 318 u_int off = fd >> NDENTRYSHIFT; 319 fdfile_t *ff; 320 321 ff = fdp->fd_dt->dt_ff[fd]; 322 323 KASSERT(mutex_owned(&fdp->fd_lock)); 324 KASSERT(ff != NULL); 325 KASSERT(ff->ff_file == NULL); 326 KASSERT(ff->ff_allocated); 327 328 if (fd < fdp->fd_freefile) { 329 fdp->fd_freefile = fd; 330 } 331 332 if (fdp->fd_lomap[off] == ~0) { 333 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] & 334 (1U << (off & NDENTRYMASK))) != 0); 335 fdp->fd_himap[off >> NDENTRYSHIFT] &= 336 ~(1U << (off & NDENTRYMASK)); 337 } 338 KASSERT((fdp->fd_lomap[off] & (1U << (fd & NDENTRYMASK))) != 0); 339 fdp->fd_lomap[off] &= ~(1U << (fd & NDENTRYMASK)); 340 ff->ff_allocated = false; 341 342 KASSERT(fd <= fdp->fd_lastfile); 343 if (fd == fdp->fd_lastfile) { 344 fdp->fd_lastfile = fd_last_set(fdp, fd); 345 } 346 fd_checkmaps(fdp); 347 } 348 349 /* 350 * Look up the file structure corresponding to a file descriptor 351 * and return the file, holding a reference on the descriptor. 352 */ 353 file_t * 354 fd_getfile(unsigned fd) 355 { 356 filedesc_t *fdp; 357 fdfile_t *ff; 358 file_t *fp; 359 fdtab_t *dt; 360 361 /* 362 * Look up the fdfile structure representing this descriptor. 363 * We are doing this unlocked. See fd_tryexpand(). 364 */ 365 fdp = curlwp->l_fd; 366 dt = atomic_load_consume(&fdp->fd_dt); 367 if (__predict_false(fd >= dt->dt_nfiles)) { 368 return NULL; 369 } 370 ff = dt->dt_ff[fd]; 371 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]); 372 if (__predict_false(ff == NULL)) { 373 return NULL; 374 } 375 376 /* Now get a reference to the descriptor. */ 377 if (fdp->fd_refcnt == 1) { 378 /* 379 * Single threaded: don't need to worry about concurrent 380 * access (other than earlier calls to kqueue, which may 381 * hold a reference to the descriptor). 382 */ 383 ff->ff_refcnt++; 384 } else { 385 /* 386 * Multi threaded: issue a memory barrier to ensure that we 387 * acquire the file pointer _after_ adding a reference. If 388 * no memory barrier, we could fetch a stale pointer. 389 * 390 * In particular, we must coordinate the following four 391 * memory operations: 392 * 393 * A. fd_close store ff->ff_file = NULL 394 * B. fd_close refcnt = atomic_dec_uint_nv(&ff->ff_refcnt) 395 * C. fd_getfile atomic_inc_uint(&ff->ff_refcnt) 396 * D. fd_getfile load fp = ff->ff_file 397 * 398 * If the order is D;A;B;C: 399 * 400 * 1. D: fp = ff->ff_file 401 * 2. A: ff->ff_file = NULL 402 * 3. B: refcnt = atomic_dec_uint_nv(&ff->ff_refcnt) 403 * 4. C: atomic_inc_uint(&ff->ff_refcnt) 404 * 405 * then fd_close determines that there are no more 406 * references and decides to free fp immediately, at 407 * the same that fd_getfile ends up with an fp that's 408 * about to be freed. *boom* 409 * 410 * By making B a release operation in fd_close, and by 411 * making C an acquire operation in fd_getfile, since 412 * they are atomic operations on the same object, which 413 * has a total modification order, we guarantee either: 414 * 415 * - B happens before C. Then since A is 416 * sequenced before B in fd_close, and C is 417 * sequenced before D in fd_getfile, we 418 * guarantee A happens before D, so fd_getfile 419 * reads a null fp and safely fails. 420 * 421 * - C happens before B. Then fd_getfile may read 422 * null or nonnull, but either way, fd_close 423 * will safely wait for references to drain. 424 */ 425 atomic_inc_uint(&ff->ff_refcnt); 426 membar_acquire(); 427 } 428 429 /* 430 * If the file is not open or is being closed then put the 431 * reference back. 432 */ 433 fp = atomic_load_consume(&ff->ff_file); 434 if (__predict_true(fp != NULL)) { 435 return fp; 436 } 437 fd_putfile(fd); 438 return NULL; 439 } 440 441 /* 442 * Release a reference to a file descriptor acquired with fd_getfile(). 443 */ 444 void 445 fd_putfile(unsigned fd) 446 { 447 filedesc_t *fdp; 448 fdfile_t *ff; 449 u_int u, v; 450 451 fdp = curlwp->l_fd; 452 KASSERT(fd < atomic_load_consume(&fdp->fd_dt)->dt_nfiles); 453 ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd]; 454 455 KASSERT(ff != NULL); 456 KASSERT((ff->ff_refcnt & FR_MASK) > 0); 457 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]); 458 459 if (fdp->fd_refcnt == 1) { 460 /* 461 * Single threaded: don't need to worry about concurrent 462 * access (other than earlier calls to kqueue, which may 463 * hold a reference to the descriptor). 464 */ 465 if (__predict_false((ff->ff_refcnt & FR_CLOSING) != 0)) { 466 fd_close(fd); 467 return; 468 } 469 ff->ff_refcnt--; 470 return; 471 } 472 473 /* 474 * Ensure that any use of the file is complete and globally 475 * visible before dropping the final reference. If no membar, 476 * the current CPU could still access memory associated with 477 * the file after it has been freed or recycled by another 478 * CPU. 479 */ 480 membar_release(); 481 482 /* 483 * Be optimistic and start out with the assumption that no other 484 * threads are trying to close the descriptor. If the CAS fails, 485 * we lost a race and/or it's being closed. 486 */ 487 for (u = ff->ff_refcnt & FR_MASK;; u = v) { 488 v = atomic_cas_uint(&ff->ff_refcnt, u, u - 1); 489 if (__predict_true(u == v)) { 490 return; 491 } 492 if (__predict_false((v & FR_CLOSING) != 0)) { 493 break; 494 } 495 } 496 497 /* Another thread is waiting to close the file: join it. */ 498 (void)fd_close(fd); 499 } 500 501 /* 502 * Convenience wrapper around fd_getfile() that returns reference 503 * to a vnode. 504 */ 505 int 506 fd_getvnode(unsigned fd, file_t **fpp) 507 { 508 vnode_t *vp; 509 file_t *fp; 510 511 fp = fd_getfile(fd); 512 if (__predict_false(fp == NULL)) { 513 return EBADF; 514 } 515 if (__predict_false(fp->f_type != DTYPE_VNODE)) { 516 fd_putfile(fd); 517 return EINVAL; 518 } 519 vp = fp->f_vnode; 520 if (__predict_false(vp->v_type == VBAD)) { 521 /* XXX Is this case really necessary? */ 522 fd_putfile(fd); 523 return EBADF; 524 } 525 *fpp = fp; 526 return 0; 527 } 528 529 /* 530 * Convenience wrapper around fd_getfile() that returns reference 531 * to a socket. 532 */ 533 int 534 fd_getsock1(unsigned fd, struct socket **sop, file_t **fp) 535 { 536 *fp = fd_getfile(fd); 537 if (__predict_false(*fp == NULL)) { 538 return EBADF; 539 } 540 if (__predict_false((*fp)->f_type != DTYPE_SOCKET)) { 541 fd_putfile(fd); 542 return ENOTSOCK; 543 } 544 *sop = (*fp)->f_socket; 545 return 0; 546 } 547 548 int 549 fd_getsock(unsigned fd, struct socket **sop) 550 { 551 file_t *fp; 552 return fd_getsock1(fd, sop, &fp); 553 } 554 555 /* 556 * Look up the file structure corresponding to a file descriptor 557 * and return it with a reference held on the file, not the 558 * descriptor. 559 * 560 * This is heavyweight and only used when accessing descriptors 561 * from a foreign process. The caller must ensure that `p' does 562 * not exit or fork across this call. 563 * 564 * To release the file (not descriptor) reference, use closef(). 565 */ 566 file_t * 567 fd_getfile2(proc_t *p, unsigned fd) 568 { 569 filedesc_t *fdp; 570 fdfile_t *ff; 571 file_t *fp; 572 fdtab_t *dt; 573 574 fdp = p->p_fd; 575 mutex_enter(&fdp->fd_lock); 576 dt = fdp->fd_dt; 577 if (fd >= dt->dt_nfiles) { 578 mutex_exit(&fdp->fd_lock); 579 return NULL; 580 } 581 if ((ff = dt->dt_ff[fd]) == NULL) { 582 mutex_exit(&fdp->fd_lock); 583 return NULL; 584 } 585 if ((fp = atomic_load_consume(&ff->ff_file)) == NULL) { 586 mutex_exit(&fdp->fd_lock); 587 return NULL; 588 } 589 mutex_enter(&fp->f_lock); 590 fp->f_count++; 591 mutex_exit(&fp->f_lock); 592 mutex_exit(&fdp->fd_lock); 593 594 return fp; 595 } 596 597 /* 598 * Internal form of close. Must be called with a reference to the 599 * descriptor, and will drop the reference. When all descriptor 600 * references are dropped, releases the descriptor slot and a single 601 * reference to the file structure. 602 */ 603 int 604 fd_close(unsigned fd) 605 { 606 struct flock lf; 607 filedesc_t *fdp; 608 fdfile_t *ff; 609 file_t *fp; 610 proc_t *p; 611 lwp_t *l; 612 u_int refcnt; 613 614 l = curlwp; 615 p = l->l_proc; 616 fdp = l->l_fd; 617 ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd]; 618 619 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]); 620 621 mutex_enter(&fdp->fd_lock); 622 KASSERT((ff->ff_refcnt & FR_MASK) > 0); 623 fp = atomic_load_consume(&ff->ff_file); 624 if (__predict_false(fp == NULL)) { 625 /* 626 * Another user of the file is already closing, and is 627 * waiting for other users of the file to drain. Release 628 * our reference, and wake up the closer. 629 */ 630 membar_release(); 631 atomic_dec_uint(&ff->ff_refcnt); 632 cv_broadcast(&ff->ff_closing); 633 mutex_exit(&fdp->fd_lock); 634 635 /* 636 * An application error, so pretend that the descriptor 637 * was already closed. We can't safely wait for it to 638 * be closed without potentially deadlocking. 639 */ 640 return (EBADF); 641 } 642 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0); 643 644 /* 645 * There may be multiple users of this file within the process. 646 * Notify existing and new users that the file is closing. This 647 * will prevent them from adding additional uses to this file 648 * while we are closing it. 649 */ 650 atomic_store_relaxed(&ff->ff_file, NULL); 651 ff->ff_exclose = false; 652 ff->ff_foclose = false; 653 654 /* 655 * We expect the caller to hold a descriptor reference - drop it. 656 * The reference count may increase beyond zero at this point due 657 * to an erroneous descriptor reference by an application, but 658 * fd_getfile() will notice that the file is being closed and drop 659 * the reference again. 660 */ 661 if (fdp->fd_refcnt == 1) { 662 /* Single threaded. */ 663 refcnt = --(ff->ff_refcnt); 664 } else { 665 /* Multi threaded. */ 666 membar_release(); 667 refcnt = atomic_dec_uint_nv(&ff->ff_refcnt); 668 membar_acquire(); 669 } 670 if (__predict_false(refcnt != 0)) { 671 /* 672 * Wait for other references to drain. This is typically 673 * an application error - the descriptor is being closed 674 * while still in use. 675 * (Or just a threaded application trying to unblock its 676 * thread that sleeps in (say) accept()). 677 */ 678 atomic_or_uint(&ff->ff_refcnt, FR_CLOSING); 679 680 /* 681 * Remove any knotes attached to the file. A knote 682 * attached to the descriptor can hold references on it. 683 */ 684 mutex_exit(&fdp->fd_lock); 685 if (!SLIST_EMPTY(&ff->ff_knlist)) { 686 knote_fdclose(fd); 687 } 688 689 /* 690 * Since the file system code doesn't know which fd 691 * each request came from (think dup()), we have to 692 * ask it to return ERESTART for any long-term blocks. 693 * The re-entry through read/write/etc will detect the 694 * closed fd and return EBAFD. 695 * Blocked partial writes may return a short length. 696 */ 697 (*fp->f_ops->fo_restart)(fp); 698 mutex_enter(&fdp->fd_lock); 699 700 /* 701 * We need to see the count drop to zero at least once, 702 * in order to ensure that all pre-existing references 703 * have been drained. New references past this point are 704 * of no interest. 705 * XXX (dsl) this may need to call fo_restart() after a 706 * timeout to guarantee that all the system calls exit. 707 */ 708 while ((ff->ff_refcnt & FR_MASK) != 0) { 709 cv_wait(&ff->ff_closing, &fdp->fd_lock); 710 } 711 atomic_and_uint(&ff->ff_refcnt, ~FR_CLOSING); 712 } else { 713 /* If no references, there must be no knotes. */ 714 KASSERT(SLIST_EMPTY(&ff->ff_knlist)); 715 } 716 717 /* 718 * POSIX record locking dictates that any close releases ALL 719 * locks owned by this process. This is handled by setting 720 * a flag in the unlock to free ONLY locks obeying POSIX 721 * semantics, and not to free BSD-style file locks. 722 * If the descriptor was in a message, POSIX-style locks 723 * aren't passed with the descriptor. 724 */ 725 if (__predict_false((p->p_flag & PK_ADVLOCK) != 0) && 726 fp->f_ops->fo_advlock != NULL) { 727 lf.l_whence = SEEK_SET; 728 lf.l_start = 0; 729 lf.l_len = 0; 730 lf.l_type = F_UNLCK; 731 mutex_exit(&fdp->fd_lock); 732 (void)(*fp->f_ops->fo_advlock)(fp, p, F_UNLCK, &lf, F_POSIX); 733 mutex_enter(&fdp->fd_lock); 734 } 735 736 /* Free descriptor slot. */ 737 fd_unused(fdp, fd); 738 mutex_exit(&fdp->fd_lock); 739 740 /* Now drop reference to the file itself. */ 741 return closef(fp); 742 } 743 744 /* 745 * Duplicate a file descriptor. 746 */ 747 int 748 fd_dup(file_t *fp, int minfd, int *newp, bool exclose, bool foclose) 749 { 750 proc_t *p = curproc; 751 int error; 752 753 while ((error = fd_alloc(p, minfd, newp)) != 0) { 754 if (error != ENOSPC) { 755 return error; 756 } 757 fd_tryexpand(p); 758 } 759 760 fd_set_exclose(curlwp, *newp, exclose); 761 fd_set_foclose(curlwp, *newp, foclose); 762 fd_affix(p, fp, *newp); 763 return 0; 764 } 765 766 /* 767 * dup2 operation. 768 */ 769 int 770 fd_dup2(file_t *fp, unsigned newfd, int flags) 771 { 772 filedesc_t *fdp = curlwp->l_fd; 773 fdfile_t *ff; 774 fdtab_t *dt; 775 776 if (flags & ~(O_CLOEXEC|O_CLOFORK|O_NONBLOCK|O_NOSIGPIPE)) 777 return EINVAL; 778 /* 779 * Ensure there are enough slots in the descriptor table, 780 * and allocate an fdfile_t up front in case we need it. 781 */ 782 while (newfd >= atomic_load_consume(&fdp->fd_dt)->dt_nfiles) { 783 fd_tryexpand(curproc); 784 } 785 ff = kmem_alloc(sizeof(*ff), KM_SLEEP); 786 fdfile_ctor(ff); 787 788 /* 789 * If there is already a file open, close it. If the file is 790 * half open, wait for it to be constructed before closing it. 791 * XXX Potential for deadlock here? 792 */ 793 mutex_enter(&fdp->fd_lock); 794 while (fd_isused(fdp, newfd)) { 795 mutex_exit(&fdp->fd_lock); 796 if (fd_getfile(newfd) != NULL) { 797 (void)fd_close(newfd); 798 } else { 799 /* 800 * Crummy, but unlikely to happen. 801 * Can occur if we interrupt another 802 * thread while it is opening a file. 803 */ 804 kpause("dup2", false, 1, NULL); 805 } 806 mutex_enter(&fdp->fd_lock); 807 } 808 dt = fdp->fd_dt; 809 if (dt->dt_ff[newfd] == NULL) { 810 KASSERT(newfd >= NDFDFILE); 811 dt->dt_ff[newfd] = ff; 812 ff = NULL; 813 } 814 fd_used(fdp, newfd); 815 mutex_exit(&fdp->fd_lock); 816 817 fd_set_exclose(curlwp, newfd, (flags & O_CLOEXEC) != 0); 818 fd_set_foclose(curlwp, newfd, (flags & O_CLOFORK) != 0); 819 fp->f_flag |= flags & (FNONBLOCK|FNOSIGPIPE); 820 /* Slot is now allocated. Insert copy of the file. */ 821 fd_affix(curproc, fp, newfd); 822 if (ff != NULL) { 823 cv_destroy(&ff->ff_closing); 824 kmem_free(ff, sizeof(*ff)); 825 } 826 return 0; 827 } 828 829 /* 830 * Drop reference to a file structure. 831 */ 832 int 833 closef(file_t *fp) 834 { 835 struct flock lf; 836 int error; 837 838 /* 839 * Drop reference. If referenced elsewhere it's still open 840 * and we have nothing more to do. 841 */ 842 mutex_enter(&fp->f_lock); 843 KASSERT(fp->f_count > 0); 844 if (--fp->f_count > 0) { 845 mutex_exit(&fp->f_lock); 846 return 0; 847 } 848 KASSERT(fp->f_count == 0); 849 mutex_exit(&fp->f_lock); 850 851 /* We held the last reference - release locks, close and free. */ 852 if (fp->f_ops->fo_advlock == NULL) { 853 KASSERT((fp->f_flag & FHASLOCK) == 0); 854 } else if (fp->f_flag & FHASLOCK) { 855 lf.l_whence = SEEK_SET; 856 lf.l_start = 0; 857 lf.l_len = 0; 858 lf.l_type = F_UNLCK; 859 (void)(*fp->f_ops->fo_advlock)(fp, fp, F_UNLCK, &lf, F_FLOCK); 860 } 861 if (fp->f_ops != NULL) { 862 error = (*fp->f_ops->fo_close)(fp); 863 864 /* 865 * .fo_close is final, so real errors are frowned on 866 * (but allowed and passed on to close(2)), and 867 * ERESTART is absolutely forbidden because the file 868 * descriptor is gone and there is no chance to retry. 869 */ 870 KASSERTMSG(error != ERESTART, 871 "file %p f_ops %p fo_close %p returned ERESTART", 872 fp, fp->f_ops, fp->f_ops->fo_close); 873 } else { 874 error = 0; 875 } 876 KASSERT(fp->f_count == 0); 877 KASSERT(fp->f_cred != NULL); 878 pool_cache_put(file_cache, fp); 879 880 return error; 881 } 882 883 /* 884 * Allocate a file descriptor for the process. 885 * 886 * Future idea for experimentation: replace all of this with radixtree. 887 */ 888 int 889 fd_alloc(proc_t *p, int want, int *result) 890 { 891 filedesc_t *fdp = p->p_fd; 892 int i, lim, last, error, hi; 893 u_int off; 894 fdtab_t *dt; 895 896 KASSERT(p == curproc || p == &proc0); 897 898 /* 899 * Search for a free descriptor starting at the higher 900 * of want or fd_freefile. 901 */ 902 mutex_enter(&fdp->fd_lock); 903 fd_checkmaps(fdp); 904 dt = fdp->fd_dt; 905 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]); 906 lim = uimin((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles); 907 last = uimin(dt->dt_nfiles, lim); 908 909 for (;;) { 910 if ((i = want) < fdp->fd_freefile) 911 i = fdp->fd_freefile; 912 off = i >> NDENTRYSHIFT; 913 hi = fd_next_zero(fdp, fdp->fd_himap, off, 914 (last + NDENTRIES - 1) >> NDENTRYSHIFT); 915 if (hi == -1) 916 break; 917 i = fd_next_zero(fdp, &fdp->fd_lomap[hi], 918 hi > off ? 0 : i & NDENTRYMASK, NDENTRIES); 919 if (i == -1) { 920 /* 921 * Free file descriptor in this block was 922 * below want, try again with higher want. 923 */ 924 want = (hi + 1) << NDENTRYSHIFT; 925 continue; 926 } 927 i += (hi << NDENTRYSHIFT); 928 if (i >= last) { 929 break; 930 } 931 if (dt->dt_ff[i] == NULL) { 932 KASSERT(i >= NDFDFILE); 933 dt->dt_ff[i] = kmem_alloc(sizeof(fdfile_t), KM_SLEEP); 934 fdfile_ctor(dt->dt_ff[i]); 935 } 936 KASSERT(dt->dt_ff[i]->ff_file == NULL); 937 fd_used(fdp, i); 938 if (want <= fdp->fd_freefile) { 939 fdp->fd_freefile = i; 940 } 941 *result = i; 942 KASSERT(i >= NDFDFILE || 943 dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]); 944 fd_checkmaps(fdp); 945 mutex_exit(&fdp->fd_lock); 946 return 0; 947 } 948 949 /* No space in current array. Let the caller expand and retry. */ 950 error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC; 951 mutex_exit(&fdp->fd_lock); 952 return error; 953 } 954 955 /* 956 * Allocate memory for a descriptor table. 957 */ 958 static fdtab_t * 959 fd_dtab_alloc(int n) 960 { 961 fdtab_t *dt; 962 size_t sz; 963 964 KASSERT(n > NDFILE); 965 966 sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]); 967 dt = kmem_alloc(sz, KM_SLEEP); 968 #ifdef DIAGNOSTIC 969 memset(dt, 0xff, sz); 970 #endif 971 dt->dt_nfiles = n; 972 dt->dt_link = NULL; 973 return dt; 974 } 975 976 /* 977 * Free a descriptor table, and all tables linked for deferred free. 978 */ 979 static void 980 fd_dtab_free(fdtab_t *dt) 981 { 982 fdtab_t *next; 983 size_t sz; 984 985 do { 986 next = dt->dt_link; 987 KASSERT(dt->dt_nfiles > NDFILE); 988 sz = sizeof(*dt) + 989 (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]); 990 #ifdef DIAGNOSTIC 991 memset(dt, 0xff, sz); 992 #endif 993 kmem_free(dt, sz); 994 dt = next; 995 } while (dt != NULL); 996 } 997 998 /* 999 * Allocate descriptor bitmap. 1000 */ 1001 static void 1002 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi) 1003 { 1004 uint8_t *ptr; 1005 size_t szlo, szhi; 1006 1007 KASSERT(n > NDENTRIES); 1008 1009 szlo = NDLOSLOTS(n) * sizeof(uint32_t); 1010 szhi = NDHISLOTS(n) * sizeof(uint32_t); 1011 ptr = kmem_alloc(szlo + szhi, KM_SLEEP); 1012 *lo = (uint32_t *)ptr; 1013 *hi = (uint32_t *)(ptr + szlo); 1014 } 1015 1016 /* 1017 * Free descriptor bitmap. 1018 */ 1019 static void 1020 fd_map_free(int n, uint32_t *lo, uint32_t *hi) 1021 { 1022 size_t szlo, szhi; 1023 1024 KASSERT(n > NDENTRIES); 1025 1026 szlo = NDLOSLOTS(n) * sizeof(uint32_t); 1027 szhi = NDHISLOTS(n) * sizeof(uint32_t); 1028 KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo)); 1029 kmem_free(lo, szlo + szhi); 1030 } 1031 1032 /* 1033 * Expand a process' descriptor table. 1034 */ 1035 void 1036 fd_tryexpand(proc_t *p) 1037 { 1038 filedesc_t *fdp; 1039 int i, numfiles, oldnfiles; 1040 fdtab_t *newdt, *dt; 1041 uint32_t *newhimap, *newlomap; 1042 1043 KASSERT(p == curproc || p == &proc0); 1044 1045 fdp = p->p_fd; 1046 newhimap = NULL; 1047 newlomap = NULL; 1048 oldnfiles = atomic_load_consume(&fdp->fd_dt)->dt_nfiles; 1049 1050 if (oldnfiles < NDEXTENT) 1051 numfiles = NDEXTENT; 1052 else 1053 numfiles = 2 * oldnfiles; 1054 1055 newdt = fd_dtab_alloc(numfiles); 1056 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) { 1057 fd_map_alloc(numfiles, &newlomap, &newhimap); 1058 } 1059 1060 mutex_enter(&fdp->fd_lock); 1061 dt = fdp->fd_dt; 1062 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]); 1063 if (dt->dt_nfiles != oldnfiles) { 1064 /* fdp changed; caller must retry */ 1065 mutex_exit(&fdp->fd_lock); 1066 fd_dtab_free(newdt); 1067 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) { 1068 fd_map_free(numfiles, newlomap, newhimap); 1069 } 1070 return; 1071 } 1072 1073 /* Copy the existing descriptor table and zero the new portion. */ 1074 i = sizeof(fdfile_t *) * oldnfiles; 1075 memcpy(newdt->dt_ff, dt->dt_ff, i); 1076 memset((uint8_t *)newdt->dt_ff + i, 0, 1077 numfiles * sizeof(fdfile_t *) - i); 1078 1079 /* 1080 * Link old descriptor array into list to be discarded. We defer 1081 * freeing until the last reference to the descriptor table goes 1082 * away (usually process exit). This allows us to do lockless 1083 * lookups in fd_getfile(). 1084 */ 1085 if (oldnfiles > NDFILE) { 1086 if (fdp->fd_refcnt > 1) { 1087 newdt->dt_link = dt; 1088 } else { 1089 fd_dtab_free(dt); 1090 } 1091 } 1092 1093 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) { 1094 i = NDHISLOTS(oldnfiles) * sizeof(uint32_t); 1095 memcpy(newhimap, fdp->fd_himap, i); 1096 memset((uint8_t *)newhimap + i, 0, 1097 NDHISLOTS(numfiles) * sizeof(uint32_t) - i); 1098 1099 i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t); 1100 memcpy(newlomap, fdp->fd_lomap, i); 1101 memset((uint8_t *)newlomap + i, 0, 1102 NDLOSLOTS(numfiles) * sizeof(uint32_t) - i); 1103 1104 if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) { 1105 fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap); 1106 } 1107 fdp->fd_himap = newhimap; 1108 fdp->fd_lomap = newlomap; 1109 } 1110 1111 /* 1112 * All other modifications must become globally visible before 1113 * the change to fd_dt. See fd_getfile(). 1114 */ 1115 atomic_store_release(&fdp->fd_dt, newdt); 1116 KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]); 1117 fd_checkmaps(fdp); 1118 mutex_exit(&fdp->fd_lock); 1119 } 1120 1121 /* 1122 * Create a new open file structure and allocate a file descriptor 1123 * for the current process. 1124 */ 1125 int 1126 fd_allocfile(file_t **resultfp, int *resultfd) 1127 { 1128 proc_t *p = curproc; 1129 kauth_cred_t cred; 1130 file_t *fp; 1131 int error; 1132 1133 while ((error = fd_alloc(p, 0, resultfd)) != 0) { 1134 if (error != ENOSPC) { 1135 return error; 1136 } 1137 fd_tryexpand(p); 1138 } 1139 1140 fp = pool_cache_get(file_cache, PR_WAITOK); 1141 if (fp == NULL) { 1142 fd_abort(p, NULL, *resultfd); 1143 return ENFILE; 1144 } 1145 KASSERT(fp->f_count == 0); 1146 KASSERT(fp->f_msgcount == 0); 1147 KASSERT(fp->f_unpcount == 0); 1148 1149 /* Replace cached credentials if not what we need. */ 1150 cred = curlwp->l_cred; 1151 if (__predict_false(cred != fp->f_cred)) { 1152 kauth_cred_free(fp->f_cred); 1153 fp->f_cred = kauth_cred_hold(cred); 1154 } 1155 1156 /* 1157 * Don't allow recycled files to be scanned. 1158 * See uipc_usrreq.c. 1159 */ 1160 if (__predict_false((fp->f_flag & FSCAN) != 0)) { 1161 mutex_enter(&fp->f_lock); 1162 atomic_and_uint(&fp->f_flag, ~FSCAN); 1163 mutex_exit(&fp->f_lock); 1164 } 1165 1166 fp->f_advice = 0; 1167 fp->f_offset = 0; 1168 *resultfp = fp; 1169 1170 return 0; 1171 } 1172 1173 /* 1174 * Successful creation of a new descriptor: make visible to the process. 1175 */ 1176 void 1177 fd_affix(proc_t *p, file_t *fp, unsigned fd) 1178 { 1179 fdfile_t *ff; 1180 filedesc_t *fdp; 1181 fdtab_t *dt; 1182 1183 KASSERT(p == curproc || p == &proc0); 1184 1185 /* Add a reference to the file structure. */ 1186 mutex_enter(&fp->f_lock); 1187 fp->f_count++; 1188 mutex_exit(&fp->f_lock); 1189 1190 /* 1191 * Insert the new file into the descriptor slot. 1192 */ 1193 fdp = p->p_fd; 1194 dt = atomic_load_consume(&fdp->fd_dt); 1195 ff = dt->dt_ff[fd]; 1196 1197 KASSERT(ff != NULL); 1198 KASSERT(ff->ff_file == NULL); 1199 KASSERT(ff->ff_allocated); 1200 KASSERT(fd_isused(fdp, fd)); 1201 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]); 1202 1203 /* No need to lock in order to make file initially visible. */ 1204 atomic_store_release(&ff->ff_file, fp); 1205 } 1206 1207 /* 1208 * Abort creation of a new descriptor: free descriptor slot and file. 1209 */ 1210 void 1211 fd_abort(proc_t *p, file_t *fp, unsigned fd) 1212 { 1213 filedesc_t *fdp; 1214 fdfile_t *ff; 1215 1216 KASSERT(p == curproc || p == &proc0); 1217 1218 fdp = p->p_fd; 1219 ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd]; 1220 ff->ff_exclose = false; 1221 ff->ff_foclose = false; 1222 1223 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]); 1224 1225 mutex_enter(&fdp->fd_lock); 1226 KASSERT(fd_isused(fdp, fd)); 1227 fd_unused(fdp, fd); 1228 mutex_exit(&fdp->fd_lock); 1229 1230 if (fp != NULL) { 1231 KASSERT(fp->f_count == 0); 1232 KASSERT(fp->f_cred != NULL); 1233 pool_cache_put(file_cache, fp); 1234 } 1235 } 1236 1237 static int 1238 file_ctor(void *arg, void *obj, int flags) 1239 { 1240 /* 1241 * It's easy to exhaust the open file limit on a system with many 1242 * CPUs due to caching. Allow a bit of leeway to reduce the element 1243 * of surprise. 1244 */ 1245 u_int slop = PCG_NOBJECTS_NORMAL * (ncpu - 1); 1246 file_t *fp = obj; 1247 1248 memset(fp, 0, sizeof(*fp)); 1249 1250 mutex_enter(&filelist_lock); 1251 if (__predict_false(nfiles >= slop + maxfiles)) { 1252 mutex_exit(&filelist_lock); 1253 tablefull("file", "increase kern.maxfiles or MAXFILES"); 1254 return ENFILE; 1255 } 1256 nfiles++; 1257 LIST_INSERT_HEAD(&filehead, fp, f_list); 1258 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE); 1259 fp->f_cred = kauth_cred_hold(curlwp->l_cred); 1260 mutex_exit(&filelist_lock); 1261 1262 return 0; 1263 } 1264 1265 static void 1266 file_dtor(void *arg, void *obj) 1267 { 1268 file_t *fp = obj; 1269 1270 mutex_enter(&filelist_lock); 1271 nfiles--; 1272 LIST_REMOVE(fp, f_list); 1273 mutex_exit(&filelist_lock); 1274 1275 KASSERT(fp->f_count == 0); 1276 kauth_cred_free(fp->f_cred); 1277 mutex_destroy(&fp->f_lock); 1278 } 1279 1280 static void 1281 fdfile_ctor(fdfile_t *ff) 1282 { 1283 1284 memset(ff, 0, sizeof(*ff)); 1285 cv_init(&ff->ff_closing, "fdclose"); 1286 } 1287 1288 static void 1289 fdfile_dtor(fdfile_t *ff) 1290 { 1291 1292 cv_destroy(&ff->ff_closing); 1293 } 1294 1295 file_t * 1296 fgetdummy(void) 1297 { 1298 file_t *fp; 1299 1300 fp = kmem_zalloc(sizeof(*fp), KM_SLEEP); 1301 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE); 1302 return fp; 1303 } 1304 1305 void 1306 fputdummy(file_t *fp) 1307 { 1308 1309 mutex_destroy(&fp->f_lock); 1310 kmem_free(fp, sizeof(*fp)); 1311 } 1312 1313 /* 1314 * Create an initial filedesc structure. 1315 */ 1316 filedesc_t * 1317 fd_init(filedesc_t *fdp) 1318 { 1319 #ifdef DIAGNOSTIC 1320 unsigned fd; 1321 #endif 1322 1323 if (__predict_true(fdp == NULL)) { 1324 fdp = pool_cache_get(filedesc_cache, PR_WAITOK); 1325 } else { 1326 KASSERT(fdp == &filedesc0); 1327 filedesc_ctor(NULL, fdp, PR_WAITOK); 1328 } 1329 1330 #ifdef DIAGNOSTIC 1331 KASSERT(fdp->fd_lastfile == -1); 1332 KASSERT(fdp->fd_lastkqfile == -1); 1333 KASSERT(fdp->fd_knhash == NULL); 1334 KASSERT(fdp->fd_freefile == 0); 1335 KASSERT(fdp->fd_exclose == false); 1336 KASSERT(fdp->fd_foclose == false); 1337 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin); 1338 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE); 1339 for (fd = 0; fd < NDFDFILE; fd++) { 1340 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == 1341 (fdfile_t *)fdp->fd_dfdfile[fd]); 1342 } 1343 for (fd = NDFDFILE; fd < NDFILE; fd++) { 1344 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL); 1345 } 1346 KASSERT(fdp->fd_himap == fdp->fd_dhimap); 1347 KASSERT(fdp->fd_lomap == fdp->fd_dlomap); 1348 #endif /* DIAGNOSTIC */ 1349 1350 fdp->fd_refcnt = 1; 1351 fd_checkmaps(fdp); 1352 1353 return fdp; 1354 } 1355 1356 /* 1357 * Initialize a file descriptor table. 1358 */ 1359 static int 1360 filedesc_ctor(void *arg, void *obj, int flag) 1361 { 1362 filedesc_t *fdp = obj; 1363 fdfile_t **ffp; 1364 int i; 1365 1366 memset(fdp, 0, sizeof(*fdp)); 1367 mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE); 1368 fdp->fd_lastfile = -1; 1369 fdp->fd_lastkqfile = -1; 1370 fdp->fd_dt = &fdp->fd_dtbuiltin; 1371 fdp->fd_dtbuiltin.dt_nfiles = NDFILE; 1372 fdp->fd_himap = fdp->fd_dhimap; 1373 fdp->fd_lomap = fdp->fd_dlomap; 1374 1375 CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t)); 1376 for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) { 1377 fdfile_ctor(*ffp = (fdfile_t *)fdp->fd_dfdfile[i]); 1378 } 1379 1380 return 0; 1381 } 1382 1383 static void 1384 filedesc_dtor(void *arg, void *obj) 1385 { 1386 filedesc_t *fdp = obj; 1387 int i; 1388 1389 for (i = 0; i < NDFDFILE; i++) { 1390 fdfile_dtor((fdfile_t *)fdp->fd_dfdfile[i]); 1391 } 1392 1393 mutex_destroy(&fdp->fd_lock); 1394 } 1395 1396 /* 1397 * Make p share curproc's filedesc structure. 1398 */ 1399 void 1400 fd_share(struct proc *p) 1401 { 1402 filedesc_t *fdp; 1403 1404 fdp = curlwp->l_fd; 1405 p->p_fd = fdp; 1406 atomic_inc_uint(&fdp->fd_refcnt); 1407 } 1408 1409 /* 1410 * Acquire a hold on a filedesc structure. 1411 */ 1412 void 1413 fd_hold(lwp_t *l) 1414 { 1415 filedesc_t *fdp = l->l_fd; 1416 1417 atomic_inc_uint(&fdp->fd_refcnt); 1418 } 1419 1420 /* 1421 * Copy a filedesc structure. 1422 */ 1423 filedesc_t * 1424 fd_copy(void) 1425 { 1426 filedesc_t *newfdp, *fdp; 1427 fdfile_t *ff, **ffp, **nffp, *ff2; 1428 int i, j, numfiles, lastfile, newlast; 1429 file_t *fp; 1430 fdtab_t *newdt; 1431 1432 fdp = curproc->p_fd; 1433 newfdp = pool_cache_get(filedesc_cache, PR_WAITOK); 1434 newfdp->fd_refcnt = 1; 1435 1436 #ifdef DIAGNOSTIC 1437 KASSERT(newfdp->fd_lastfile == -1); 1438 KASSERT(newfdp->fd_lastkqfile == -1); 1439 KASSERT(newfdp->fd_knhash == NULL); 1440 KASSERT(newfdp->fd_freefile == 0); 1441 KASSERT(newfdp->fd_exclose == false); 1442 KASSERT(newfdp->fd_foclose == false); 1443 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin); 1444 KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE); 1445 for (i = 0; i < NDFDFILE; i++) { 1446 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == 1447 (fdfile_t *)&newfdp->fd_dfdfile[i]); 1448 } 1449 for (i = NDFDFILE; i < NDFILE; i++) { 1450 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL); 1451 } 1452 #endif /* DIAGNOSTIC */ 1453 1454 mutex_enter(&fdp->fd_lock); 1455 fd_checkmaps(fdp); 1456 numfiles = fdp->fd_dt->dt_nfiles; 1457 lastfile = fdp->fd_lastfile; 1458 1459 /* 1460 * If the number of open files fits in the internal arrays 1461 * of the open file structure, use them, otherwise allocate 1462 * additional memory for the number of descriptors currently 1463 * in use. 1464 */ 1465 if (lastfile < NDFILE) { 1466 i = NDFILE; 1467 newdt = newfdp->fd_dt; 1468 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin); 1469 } else { 1470 /* 1471 * Compute the smallest multiple of NDEXTENT needed 1472 * for the file descriptors currently in use, 1473 * allowing the table to shrink. 1474 */ 1475 i = numfiles; 1476 while (i >= 2 * NDEXTENT && i > lastfile * 2) { 1477 i /= 2; 1478 } 1479 KASSERT(i > NDFILE); 1480 newdt = fd_dtab_alloc(i); 1481 newfdp->fd_dt = newdt; 1482 memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff, 1483 NDFDFILE * sizeof(fdfile_t **)); 1484 memset(newdt->dt_ff + NDFDFILE, 0, 1485 (i - NDFDFILE) * sizeof(fdfile_t **)); 1486 } 1487 if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) { 1488 newfdp->fd_himap = newfdp->fd_dhimap; 1489 newfdp->fd_lomap = newfdp->fd_dlomap; 1490 } else { 1491 fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap); 1492 KASSERT(i >= NDENTRIES * NDENTRIES); 1493 memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t)); 1494 memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t)); 1495 } 1496 newfdp->fd_freefile = fdp->fd_freefile; 1497 newfdp->fd_exclose = fdp->fd_exclose; 1498 newfdp->fd_foclose = false; /* no close-on-fork will be copied */ 1499 1500 ffp = fdp->fd_dt->dt_ff; 1501 nffp = newdt->dt_ff; 1502 newlast = -1; 1503 for (i = 0; i <= lastfile; i++, ffp++, nffp++) { 1504 KASSERT(i >= NDFDFILE || 1505 *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]); 1506 ff = *ffp; 1507 if (ff == NULL || 1508 (fp = atomic_load_consume(&ff->ff_file)) == NULL) { 1509 /* Descriptor unused, or descriptor half open. */ 1510 KASSERT(!fd_isused(newfdp, i)); 1511 continue; 1512 } 1513 if (__predict_false(ff->ff_foclose || 1514 fp->f_type == DTYPE_KQUEUE)) { 1515 /* kqueue descriptors cannot be copied. */ 1516 /* close-on-fork descriptors aren't either */ 1517 if (i < newfdp->fd_freefile) { 1518 newfdp->fd_freefile = i; 1519 } 1520 continue; 1521 } 1522 /* It's active: add a reference to the file. */ 1523 mutex_enter(&fp->f_lock); 1524 fp->f_count++; 1525 mutex_exit(&fp->f_lock); 1526 1527 /* Allocate an fdfile_t to represent it. */ 1528 if (i >= NDFDFILE) { 1529 ff2 = kmem_alloc(sizeof(*ff2), KM_SLEEP); 1530 fdfile_ctor(ff2); 1531 *nffp = ff2; 1532 } else { 1533 ff2 = newdt->dt_ff[i]; 1534 } 1535 ff2->ff_file = fp; 1536 ff2->ff_exclose = ff->ff_exclose; 1537 ff2->ff_foclose = false; 1538 ff2->ff_allocated = true; 1539 1540 /* Fix up bitmaps. */ 1541 j = i >> NDENTRYSHIFT; 1542 KASSERT((newfdp->fd_lomap[j] & (1U << (i & NDENTRYMASK))) == 0); 1543 newfdp->fd_lomap[j] |= 1U << (i & NDENTRYMASK); 1544 if (__predict_false(newfdp->fd_lomap[j] == ~0)) { 1545 KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] & 1546 (1U << (j & NDENTRYMASK))) == 0); 1547 newfdp->fd_himap[j >> NDENTRYSHIFT] |= 1548 1U << (j & NDENTRYMASK); 1549 } 1550 newlast = i; 1551 } 1552 KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]); 1553 newfdp->fd_lastfile = newlast; 1554 fd_checkmaps(newfdp); 1555 mutex_exit(&fdp->fd_lock); 1556 1557 return newfdp; 1558 } 1559 1560 /* 1561 * Release a filedesc structure. 1562 */ 1563 void 1564 fd_free(void) 1565 { 1566 fdfile_t *ff; 1567 file_t *fp; 1568 int fd, nf; 1569 fdtab_t *dt; 1570 lwp_t * const l = curlwp; 1571 filedesc_t * const fdp = l->l_fd; 1572 const bool noadvlock = (l->l_proc->p_flag & PK_ADVLOCK) == 0; 1573 1574 KASSERT(atomic_load_consume(&fdp->fd_dt)->dt_ff[0] == 1575 (fdfile_t *)fdp->fd_dfdfile[0]); 1576 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE); 1577 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL); 1578 1579 membar_release(); 1580 if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0) 1581 return; 1582 membar_acquire(); 1583 1584 /* 1585 * Close any files that the process holds open. 1586 */ 1587 dt = fdp->fd_dt; 1588 fd_checkmaps(fdp); 1589 #ifdef DEBUG 1590 fdp->fd_refcnt = -1; /* see fd_checkmaps */ 1591 #endif 1592 for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) { 1593 ff = dt->dt_ff[fd]; 1594 KASSERT(fd >= NDFDFILE || 1595 ff == (fdfile_t *)fdp->fd_dfdfile[fd]); 1596 if (ff == NULL) 1597 continue; 1598 if ((fp = atomic_load_consume(&ff->ff_file)) != NULL) { 1599 /* 1600 * Must use fd_close() here if there is 1601 * a reference from kqueue or we might have posix 1602 * advisory locks. 1603 */ 1604 if (__predict_true(ff->ff_refcnt == 0) && 1605 (noadvlock || fp->f_type != DTYPE_VNODE)) { 1606 ff->ff_file = NULL; 1607 ff->ff_exclose = false; 1608 ff->ff_foclose = false; 1609 ff->ff_allocated = false; 1610 closef(fp); 1611 } else { 1612 ff->ff_refcnt++; 1613 fd_close(fd); 1614 } 1615 } 1616 KASSERT(ff->ff_refcnt == 0); 1617 KASSERT(ff->ff_file == NULL); 1618 KASSERT(!ff->ff_exclose); 1619 KASSERT(!ff->ff_foclose); 1620 KASSERT(!ff->ff_allocated); 1621 if (fd >= NDFDFILE) { 1622 cv_destroy(&ff->ff_closing); 1623 kmem_free(ff, sizeof(*ff)); 1624 dt->dt_ff[fd] = NULL; 1625 } 1626 } 1627 1628 /* 1629 * Clean out the descriptor table for the next user and return 1630 * to the cache. 1631 */ 1632 if (__predict_false(dt != &fdp->fd_dtbuiltin)) { 1633 fd_dtab_free(fdp->fd_dt); 1634 /* Otherwise, done above. */ 1635 memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0, 1636 (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0])); 1637 fdp->fd_dt = &fdp->fd_dtbuiltin; 1638 } 1639 if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) { 1640 KASSERT(fdp->fd_himap != fdp->fd_dhimap); 1641 KASSERT(fdp->fd_lomap != fdp->fd_dlomap); 1642 fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap); 1643 } 1644 if (__predict_false(fdp->fd_knhash != NULL)) { 1645 hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask); 1646 fdp->fd_knhash = NULL; 1647 fdp->fd_knhashmask = 0; 1648 } else { 1649 KASSERT(fdp->fd_knhashmask == 0); 1650 } 1651 fdp->fd_dt = &fdp->fd_dtbuiltin; 1652 fdp->fd_lastkqfile = -1; 1653 fdp->fd_lastfile = -1; 1654 fdp->fd_freefile = 0; 1655 fdp->fd_exclose = false; 1656 fdp->fd_foclose = false; 1657 memset(&fdp->fd_startzero, 0, sizeof(*fdp) - 1658 offsetof(filedesc_t, fd_startzero)); 1659 fdp->fd_himap = fdp->fd_dhimap; 1660 fdp->fd_lomap = fdp->fd_dlomap; 1661 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE); 1662 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL); 1663 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin); 1664 #ifdef DEBUG 1665 fdp->fd_refcnt = 0; /* see fd_checkmaps */ 1666 #endif 1667 fd_checkmaps(fdp); 1668 pool_cache_put(filedesc_cache, fdp); 1669 } 1670 1671 /* 1672 * File Descriptor pseudo-device driver (/dev/fd/). 1673 * 1674 * Opening minor device N dup()s the file (if any) connected to file 1675 * descriptor N belonging to the calling process. Note that this driver 1676 * consists of only the ``open()'' routine, because all subsequent 1677 * references to this file will be direct to the other driver. 1678 */ 1679 static int 1680 filedescopen(dev_t dev, int mode, int type, lwp_t *l) 1681 { 1682 1683 /* 1684 * XXX Kludge: set dupfd to contain the value of the 1685 * the file descriptor being sought for duplication. The error 1686 * return ensures that the vnode for this device will be released 1687 * by vn_open. Open will detect this special error and take the 1688 * actions in fd_dupopen below. Other callers of vn_open or VOP_OPEN 1689 * will simply report the error. 1690 */ 1691 l->l_dupfd = minor(dev); /* XXX */ 1692 return EDUPFD; 1693 } 1694 1695 /* 1696 * Duplicate the specified descriptor to a free descriptor. 1697 * 1698 * old is the original fd. 1699 * moveit is true if we should move rather than duplicate. 1700 * flags are the open flags (converted from O_* to F*). 1701 * newp returns the new fd on success. 1702 * 1703 * These two cases are produced by the EDUPFD and EMOVEFD magic 1704 * errnos, but in the interest of removing that regrettable interface, 1705 * vn_open has been changed to intercept them. Now vn_open returns 1706 * either a vnode or a filehandle, and the filehandle is accompanied 1707 * by a boolean that says whether we should dup (moveit == false) or 1708 * move (moveit == true) the fd. 1709 * 1710 * The dup case is used by /dev/stderr, /proc/self/fd, and such. The 1711 * move case is used by cloner devices that allocate a fd of their 1712 * own (a layering violation that should go away eventually) that 1713 * then needs to be put in the place open() expects it. 1714 */ 1715 int 1716 fd_dupopen(int old, bool moveit, int flags, int *newp) 1717 { 1718 filedesc_t *fdp; 1719 fdfile_t *ff; 1720 file_t *fp; 1721 fdtab_t *dt; 1722 int error; 1723 1724 if ((fp = fd_getfile(old)) == NULL) { 1725 return EBADF; 1726 } 1727 fdp = curlwp->l_fd; 1728 dt = atomic_load_consume(&fdp->fd_dt); 1729 ff = dt->dt_ff[old]; 1730 1731 /* 1732 * There are two cases of interest here. 1733 * 1734 * 1. moveit == false (used to be the EDUPFD magic errno): 1735 * simply dup (old) to file descriptor (new) and return. 1736 * 1737 * 2. moveit == true (used to be the EMOVEFD magic errno): 1738 * steal away the file structure from (old) and store it in 1739 * (new). (old) is effectively closed by this operation. 1740 */ 1741 if (moveit == false) { 1742 /* 1743 * Check that the mode the file is being opened for is a 1744 * subset of the mode of the existing descriptor. 1745 */ 1746 if (((flags & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) { 1747 error = EACCES; 1748 goto out; 1749 } 1750 1751 /* Copy it. */ 1752 error = fd_dup(fp, 0, newp, ff->ff_exclose, ff->ff_foclose); 1753 } else { 1754 /* Copy it. */ 1755 error = fd_dup(fp, 0, newp, ff->ff_exclose, ff->ff_foclose); 1756 if (error != 0) { 1757 goto out; 1758 } 1759 1760 /* Steal away the file pointer from 'old'. */ 1761 (void)fd_close(old); 1762 return 0; 1763 } 1764 1765 out: 1766 fd_putfile(old); 1767 return error; 1768 } 1769 1770 /* 1771 * Close open files on exec. 1772 */ 1773 void 1774 fd_closeexec(void) 1775 { 1776 proc_t *p; 1777 filedesc_t *fdp; 1778 fdfile_t *ff; 1779 lwp_t *l; 1780 fdtab_t *dt; 1781 int fd; 1782 1783 l = curlwp; 1784 p = l->l_proc; 1785 fdp = p->p_fd; 1786 1787 if (fdp->fd_refcnt > 1) { 1788 /* 1789 * Always unshare fd table on any exec 1790 */ 1791 fdp = fd_copy(); 1792 fd_free(); 1793 p->p_fd = fdp; 1794 l->l_fd = fdp; 1795 } 1796 1797 /* 1798 * If there are no "close-on" fd's nothing more to do 1799 */ 1800 if (!(fdp->fd_exclose || fdp->fd_foclose)) 1801 return; 1802 1803 fdp->fd_exclose = false; /* there will be none when done */ 1804 fdp->fd_foclose = false; 1805 1806 dt = atomic_load_consume(&fdp->fd_dt); 1807 1808 for (fd = 0; fd <= fdp->fd_lastfile; fd++) { 1809 if ((ff = dt->dt_ff[fd]) == NULL) { 1810 KASSERT(fd >= NDFDFILE); 1811 continue; 1812 } 1813 KASSERT(fd >= NDFDFILE || 1814 ff == (fdfile_t *)fdp->fd_dfdfile[fd]); 1815 if (ff->ff_file == NULL) 1816 continue; 1817 if (ff->ff_exclose) { 1818 /* 1819 * We need a reference to close the file. 1820 * No other threads can see the fdfile_t at 1821 * this point, so don't bother locking. 1822 */ 1823 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0); 1824 ff->ff_refcnt++; 1825 fd_close(fd); 1826 } else if (ff->ff_foclose) { 1827 /* 1828 * https://austingroupbugs.net/view.php?id=1851 1829 * (not yet approved, but probably will be: 202507) 1830 * FD_CLOFORK should not be preserved across exec 1831 */ 1832 ff->ff_foclose = false; 1833 } 1834 } 1835 } 1836 1837 1838 /* 1839 * Sets descriptor owner. If the owner is a process, 'pgid' 1840 * is set to positive value, process ID. If the owner is process group, 1841 * 'pgid' is set to -pg_id. 1842 */ 1843 int 1844 fsetown(pid_t *pgid, u_long cmd, const void *data) 1845 { 1846 pid_t id = *(const pid_t *)data; 1847 int error; 1848 1849 if (id <= INT_MIN) 1850 return EINVAL; 1851 1852 switch (cmd) { 1853 case TIOCSPGRP: 1854 if (id < 0) 1855 return EINVAL; 1856 id = -id; 1857 break; 1858 default: 1859 break; 1860 } 1861 if (id > 0) { 1862 mutex_enter(&proc_lock); 1863 error = proc_find(id) ? 0 : ESRCH; 1864 mutex_exit(&proc_lock); 1865 } else if (id < 0) { 1866 error = pgid_in_session(curproc, -id); 1867 } else { 1868 error = 0; 1869 } 1870 if (!error) { 1871 *pgid = id; 1872 } 1873 return error; 1874 } 1875 1876 void 1877 fd_set_exclose(struct lwp *l, int fd, bool exclose) 1878 { 1879 filedesc_t *fdp = l->l_fd; 1880 fdfile_t *ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd]; 1881 1882 ff->ff_exclose = exclose; 1883 if (exclose) 1884 fdp->fd_exclose = true; 1885 } 1886 1887 void 1888 fd_set_foclose(struct lwp *l, int fd, bool foclose) 1889 { 1890 filedesc_t *fdp = l->l_fd; 1891 fdfile_t *ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd]; 1892 1893 ff->ff_foclose = foclose; 1894 if (foclose) 1895 fdp->fd_foclose = true; 1896 } 1897 1898 /* 1899 * Return descriptor owner information. If the value is positive, 1900 * it's process ID. If it's negative, it's process group ID and 1901 * needs the sign removed before use. 1902 */ 1903 int 1904 fgetown(pid_t pgid, u_long cmd, void *data) 1905 { 1906 1907 switch (cmd) { 1908 case TIOCGPGRP: 1909 KASSERT(pgid > INT_MIN); 1910 *(int *)data = -pgid; 1911 break; 1912 default: 1913 *(int *)data = pgid; 1914 break; 1915 } 1916 return 0; 1917 } 1918 1919 /* 1920 * Send signal to descriptor owner, either process or process group. 1921 */ 1922 void 1923 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata) 1924 { 1925 ksiginfo_t ksi; 1926 1927 KASSERT(!cpu_intr_p()); 1928 1929 if (pgid == 0) { 1930 return; 1931 } 1932 1933 KSI_INIT(&ksi); 1934 ksi.ksi_signo = signo; 1935 ksi.ksi_code = code; 1936 ksi.ksi_band = band; 1937 1938 mutex_enter(&proc_lock); 1939 if (pgid > 0) { 1940 struct proc *p1; 1941 1942 p1 = proc_find(pgid); 1943 if (p1 != NULL) { 1944 kpsignal(p1, &ksi, fdescdata); 1945 } 1946 } else { 1947 struct pgrp *pgrp; 1948 1949 KASSERT(pgid < 0 && pgid > INT_MIN); 1950 pgrp = pgrp_find(-pgid); 1951 if (pgrp != NULL) { 1952 kpgsignal(pgrp, &ksi, fdescdata, 0); 1953 } 1954 } 1955 mutex_exit(&proc_lock); 1956 } 1957 1958 int 1959 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops, 1960 void *data) 1961 { 1962 1963 fp->f_flag = flag & FMASK; 1964 fd_set_exclose(curlwp, fd, (flag & O_CLOEXEC) != 0); 1965 fd_set_foclose(curlwp, fd, (flag & O_CLOFORK) != 0); 1966 fp->f_type = DTYPE_MISC; 1967 fp->f_ops = fops; 1968 fp->f_data = data; 1969 curlwp->l_dupfd = fd; 1970 fd_affix(curproc, fp, fd); 1971 1972 return EMOVEFD; 1973 } 1974 1975 int 1976 fnullop_fcntl(file_t *fp, u_int cmd, void *data) 1977 { 1978 1979 if (cmd == F_SETFL) 1980 return 0; 1981 1982 return EOPNOTSUPP; 1983 } 1984 1985 int 1986 fnullop_poll(file_t *fp, int which) 1987 { 1988 1989 return 0; 1990 } 1991 1992 int 1993 fnullop_kqfilter(file_t *fp, struct knote *kn) 1994 { 1995 1996 return EOPNOTSUPP; 1997 } 1998 1999 void 2000 fnullop_restart(file_t *fp) 2001 { 2002 2003 } 2004 2005 int 2006 fbadop_read(file_t *fp, off_t *offset, struct uio *uio, 2007 kauth_cred_t cred, int flags) 2008 { 2009 2010 return EOPNOTSUPP; 2011 } 2012 2013 int 2014 fbadop_write(file_t *fp, off_t *offset, struct uio *uio, 2015 kauth_cred_t cred, int flags) 2016 { 2017 2018 return EOPNOTSUPP; 2019 } 2020 2021 int 2022 fbadop_ioctl(file_t *fp, u_long com, void *data) 2023 { 2024 2025 return EOPNOTSUPP; 2026 } 2027 2028 int 2029 fbadop_stat(file_t *fp, struct stat *sb) 2030 { 2031 2032 return EOPNOTSUPP; 2033 } 2034 2035 int 2036 fbadop_close(file_t *fp) 2037 { 2038 2039 return EOPNOTSUPP; 2040 } 2041 2042 /* 2043 * sysctl routines pertaining to file descriptors 2044 */ 2045 2046 /* Initialized in sysctl_init() for now... */ 2047 extern kmutex_t sysctl_file_marker_lock; 2048 static u_int sysctl_file_marker = 1; 2049 2050 /* 2051 * Expects to be called with proc_lock and sysctl_file_marker_lock locked. 2052 */ 2053 static void 2054 sysctl_file_marker_reset(void) 2055 { 2056 struct proc *p; 2057 2058 PROCLIST_FOREACH(p, &allproc) { 2059 struct filedesc *fd = p->p_fd; 2060 fdtab_t *dt; 2061 u_int i; 2062 2063 mutex_enter(&fd->fd_lock); 2064 dt = fd->fd_dt; 2065 for (i = 0; i < dt->dt_nfiles; i++) { 2066 struct file *fp; 2067 fdfile_t *ff; 2068 2069 if ((ff = dt->dt_ff[i]) == NULL) { 2070 continue; 2071 } 2072 if ((fp = atomic_load_consume(&ff->ff_file)) == NULL) { 2073 continue; 2074 } 2075 fp->f_marker = 0; 2076 } 2077 mutex_exit(&fd->fd_lock); 2078 } 2079 } 2080 2081 /* 2082 * sysctl helper routine for kern.file pseudo-subtree. 2083 */ 2084 static int 2085 sysctl_kern_file(SYSCTLFN_ARGS) 2086 { 2087 const bool allowaddr = get_expose_address(curproc); 2088 struct filelist flist; 2089 int error; 2090 size_t buflen; 2091 struct file *fp, fbuf; 2092 char *start, *where; 2093 struct proc *p; 2094 2095 start = where = oldp; 2096 buflen = *oldlenp; 2097 2098 if (where == NULL) { 2099 /* 2100 * overestimate by 10 files 2101 */ 2102 *oldlenp = sizeof(filehead) + (nfiles + 10) * 2103 sizeof(struct file); 2104 return 0; 2105 } 2106 2107 /* 2108 * first sysctl_copyout filehead 2109 */ 2110 if (buflen < sizeof(filehead)) { 2111 *oldlenp = 0; 2112 return 0; 2113 } 2114 sysctl_unlock(); 2115 if (allowaddr) { 2116 memcpy(&flist, &filehead, sizeof(flist)); 2117 } else { 2118 memset(&flist, 0, sizeof(flist)); 2119 } 2120 error = sysctl_copyout(l, &flist, where, sizeof(flist)); 2121 if (error) { 2122 sysctl_relock(); 2123 return error; 2124 } 2125 buflen -= sizeof(flist); 2126 where += sizeof(flist); 2127 2128 /* 2129 * followed by an array of file structures 2130 */ 2131 mutex_enter(&sysctl_file_marker_lock); 2132 mutex_enter(&proc_lock); 2133 PROCLIST_FOREACH(p, &allproc) { 2134 struct filedesc *fd; 2135 fdtab_t *dt; 2136 u_int i; 2137 2138 if (p->p_stat == SIDL) { 2139 /* skip embryonic processes */ 2140 continue; 2141 } 2142 mutex_enter(p->p_lock); 2143 error = kauth_authorize_process(l->l_cred, 2144 KAUTH_PROCESS_CANSEE, p, 2145 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES), 2146 NULL, NULL); 2147 mutex_exit(p->p_lock); 2148 if (error != 0) { 2149 /* 2150 * Don't leak kauth retval if we're silently 2151 * skipping this entry. 2152 */ 2153 error = 0; 2154 continue; 2155 } 2156 2157 /* 2158 * Grab a hold on the process. 2159 */ 2160 if (!rw_tryenter(&p->p_reflock, RW_READER)) { 2161 continue; 2162 } 2163 mutex_exit(&proc_lock); 2164 2165 fd = p->p_fd; 2166 mutex_enter(&fd->fd_lock); 2167 dt = fd->fd_dt; 2168 for (i = 0; i < dt->dt_nfiles; i++) { 2169 fdfile_t *ff; 2170 2171 if ((ff = dt->dt_ff[i]) == NULL) { 2172 continue; 2173 } 2174 if ((fp = atomic_load_consume(&ff->ff_file)) == NULL) { 2175 continue; 2176 } 2177 2178 mutex_enter(&fp->f_lock); 2179 2180 if ((fp->f_count == 0) || 2181 (fp->f_marker == sysctl_file_marker)) { 2182 mutex_exit(&fp->f_lock); 2183 continue; 2184 } 2185 2186 /* Check that we have enough space. */ 2187 if (buflen < sizeof(struct file)) { 2188 *oldlenp = where - start; 2189 mutex_exit(&fp->f_lock); 2190 error = ENOMEM; 2191 break; 2192 } 2193 2194 fill_file(&fbuf, fp); 2195 mutex_exit(&fp->f_lock); 2196 error = sysctl_copyout(l, &fbuf, where, sizeof(fbuf)); 2197 if (error) { 2198 break; 2199 } 2200 buflen -= sizeof(struct file); 2201 where += sizeof(struct file); 2202 2203 fp->f_marker = sysctl_file_marker; 2204 } 2205 mutex_exit(&fd->fd_lock); 2206 2207 /* 2208 * Release reference to process. 2209 */ 2210 mutex_enter(&proc_lock); 2211 rw_exit(&p->p_reflock); 2212 2213 if (error) 2214 break; 2215 } 2216 2217 sysctl_file_marker++; 2218 /* Reset all markers if wrapped. */ 2219 if (sysctl_file_marker == 0) { 2220 sysctl_file_marker_reset(); 2221 sysctl_file_marker++; 2222 } 2223 2224 mutex_exit(&proc_lock); 2225 mutex_exit(&sysctl_file_marker_lock); 2226 2227 *oldlenp = where - start; 2228 sysctl_relock(); 2229 return error; 2230 } 2231 2232 /* 2233 * sysctl helper function for kern.file2 2234 */ 2235 static int 2236 sysctl_kern_file2(SYSCTLFN_ARGS) 2237 { 2238 struct proc *p; 2239 struct file *fp; 2240 struct filedesc *fd; 2241 struct kinfo_file kf; 2242 char *dp; 2243 u_int i, op; 2244 size_t len, needed, elem_size, out_size; 2245 int error, arg, elem_count; 2246 fdfile_t *ff; 2247 fdtab_t *dt; 2248 2249 if (namelen == 1 && name[0] == CTL_QUERY) 2250 return sysctl_query(SYSCTLFN_CALL(rnode)); 2251 2252 if (namelen != 4) 2253 return EINVAL; 2254 2255 error = 0; 2256 dp = oldp; 2257 len = (oldp != NULL) ? *oldlenp : 0; 2258 op = name[0]; 2259 arg = name[1]; 2260 elem_size = name[2]; 2261 elem_count = name[3]; 2262 out_size = MIN(sizeof(kf), elem_size); 2263 needed = 0; 2264 2265 if (elem_size < 1 || elem_count < 0) 2266 return EINVAL; 2267 2268 switch (op) { 2269 case KERN_FILE_BYFILE: 2270 case KERN_FILE_BYPID: 2271 /* 2272 * We're traversing the process list in both cases; the BYFILE 2273 * case does additional work of keeping track of files already 2274 * looked at. 2275 */ 2276 2277 /* doesn't use arg so it must be zero */ 2278 if ((op == KERN_FILE_BYFILE) && (arg != 0)) 2279 return EINVAL; 2280 2281 if ((op == KERN_FILE_BYPID) && (arg < -1)) 2282 /* -1 means all processes */ 2283 return EINVAL; 2284 2285 sysctl_unlock(); 2286 if (op == KERN_FILE_BYFILE) 2287 mutex_enter(&sysctl_file_marker_lock); 2288 mutex_enter(&proc_lock); 2289 PROCLIST_FOREACH(p, &allproc) { 2290 if (p->p_stat == SIDL) { 2291 /* skip embryonic processes */ 2292 continue; 2293 } 2294 if (arg > 0 && p->p_pid != arg) { 2295 /* pick only the one we want */ 2296 /* XXX want 0 to mean "kernel files" */ 2297 continue; 2298 } 2299 mutex_enter(p->p_lock); 2300 error = kauth_authorize_process(l->l_cred, 2301 KAUTH_PROCESS_CANSEE, p, 2302 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES), 2303 NULL, NULL); 2304 mutex_exit(p->p_lock); 2305 if (error != 0) { 2306 /* 2307 * Don't leak kauth retval if we're silently 2308 * skipping this entry. 2309 */ 2310 error = 0; 2311 continue; 2312 } 2313 2314 /* 2315 * Grab a hold on the process. 2316 */ 2317 if (!rw_tryenter(&p->p_reflock, RW_READER)) { 2318 continue; 2319 } 2320 mutex_exit(&proc_lock); 2321 2322 fd = p->p_fd; 2323 mutex_enter(&fd->fd_lock); 2324 dt = fd->fd_dt; 2325 for (i = 0; i < dt->dt_nfiles; i++) { 2326 if ((ff = dt->dt_ff[i]) == NULL) { 2327 continue; 2328 } 2329 if ((fp = atomic_load_consume(&ff->ff_file)) == 2330 NULL) { 2331 continue; 2332 } 2333 2334 if ((op == KERN_FILE_BYFILE) && 2335 (fp->f_marker == sysctl_file_marker)) { 2336 continue; 2337 } 2338 if (len >= elem_size && elem_count > 0) { 2339 mutex_enter(&fp->f_lock); 2340 fill_file2(&kf, fp, ff, i, p->p_pid); 2341 mutex_exit(&fp->f_lock); 2342 mutex_exit(&fd->fd_lock); 2343 error = sysctl_copyout(l, 2344 &kf, dp, out_size); 2345 mutex_enter(&fd->fd_lock); 2346 if (error) 2347 break; 2348 dp += elem_size; 2349 len -= elem_size; 2350 } 2351 if (op == KERN_FILE_BYFILE) 2352 fp->f_marker = sysctl_file_marker; 2353 needed += elem_size; 2354 if (elem_count > 0 && elem_count != INT_MAX) 2355 elem_count--; 2356 } 2357 mutex_exit(&fd->fd_lock); 2358 2359 /* 2360 * Release reference to process. 2361 */ 2362 mutex_enter(&proc_lock); 2363 rw_exit(&p->p_reflock); 2364 } 2365 if (op == KERN_FILE_BYFILE) { 2366 sysctl_file_marker++; 2367 2368 /* Reset all markers if wrapped. */ 2369 if (sysctl_file_marker == 0) { 2370 sysctl_file_marker_reset(); 2371 sysctl_file_marker++; 2372 } 2373 } 2374 mutex_exit(&proc_lock); 2375 if (op == KERN_FILE_BYFILE) 2376 mutex_exit(&sysctl_file_marker_lock); 2377 sysctl_relock(); 2378 break; 2379 default: 2380 return EINVAL; 2381 } 2382 2383 if (oldp == NULL) 2384 needed += KERN_FILESLOP * elem_size; 2385 *oldlenp = needed; 2386 2387 return error; 2388 } 2389 2390 static void 2391 fill_file(struct file *fp, const struct file *fpsrc) 2392 { 2393 const bool allowaddr = get_expose_address(curproc); 2394 2395 memset(fp, 0, sizeof(*fp)); 2396 2397 fp->f_offset = fpsrc->f_offset; 2398 COND_SET_PTR(fp->f_cred, fpsrc->f_cred, allowaddr); 2399 COND_SET_CPTR(fp->f_ops, fpsrc->f_ops, allowaddr); 2400 COND_SET_STRUCT(fp->f_undata, fpsrc->f_undata, allowaddr); 2401 COND_SET_STRUCT(fp->f_list, fpsrc->f_list, allowaddr); 2402 fp->f_flag = fpsrc->f_flag; 2403 fp->f_marker = fpsrc->f_marker; 2404 fp->f_type = fpsrc->f_type; 2405 fp->f_advice = fpsrc->f_advice; 2406 fp->f_count = fpsrc->f_count; 2407 fp->f_msgcount = fpsrc->f_msgcount; 2408 fp->f_unpcount = fpsrc->f_unpcount; 2409 COND_SET_STRUCT(fp->f_unplist, fpsrc->f_unplist, allowaddr); 2410 } 2411 2412 static void 2413 fill_file2(struct kinfo_file *kp, const file_t *fp, const fdfile_t *ff, 2414 int i, pid_t pid) 2415 { 2416 const bool allowaddr = get_expose_address(curproc); 2417 2418 memset(kp, 0, sizeof(*kp)); 2419 2420 COND_SET_VALUE(kp->ki_fileaddr, PTRTOUINT64(fp), allowaddr); 2421 kp->ki_flag = fp->f_flag; 2422 kp->ki_iflags = 0; 2423 kp->ki_ftype = fp->f_type; 2424 kp->ki_count = fp->f_count; 2425 kp->ki_msgcount = fp->f_msgcount; 2426 COND_SET_VALUE(kp->ki_fucred, PTRTOUINT64(fp->f_cred), allowaddr); 2427 kp->ki_fuid = kauth_cred_geteuid(fp->f_cred); 2428 kp->ki_fgid = kauth_cred_getegid(fp->f_cred); 2429 COND_SET_VALUE(kp->ki_fops, PTRTOUINT64(fp->f_ops), allowaddr); 2430 kp->ki_foffset = fp->f_offset; 2431 COND_SET_VALUE(kp->ki_fdata, PTRTOUINT64(fp->f_data), allowaddr); 2432 2433 /* vnode information to glue this file to something */ 2434 if (fp->f_type == DTYPE_VNODE) { 2435 struct vnode *vp = fp->f_vnode; 2436 2437 COND_SET_VALUE(kp->ki_vun, PTRTOUINT64(vp->v_un.vu_socket), 2438 allowaddr); 2439 kp->ki_vsize = vp->v_size; 2440 kp->ki_vtype = vp->v_type; 2441 kp->ki_vtag = vp->v_tag; 2442 COND_SET_VALUE(kp->ki_vdata, PTRTOUINT64(vp->v_data), 2443 allowaddr); 2444 } 2445 2446 /* process information when retrieved via KERN_FILE_BYPID */ 2447 if (ff != NULL) { 2448 kp->ki_pid = pid; 2449 kp->ki_fd = i; 2450 kp->ki_ofileflags = (ff->ff_exclose ? FD_CLOEXEC : 0) | 2451 (ff->ff_foclose ? FD_CLOFORK : 0); 2452 kp->ki_usecount = ff->ff_refcnt; 2453 } 2454 } 2455