1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1989, 1993 5 * The Regents of the University of California. All rights reserved. 6 * (c) UNIX System Laboratories, Inc. 7 * All or some portions of this file are derived from material licensed 8 * to the University of California by American Telephone and Telegraph 9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 10 * the permission of UNIX System Laboratories, Inc. 11 * 12 * Copyright (c) 2012 Konstantin Belousov <kib@FreeBSD.org> 13 * Copyright (c) 2013, 2014 The FreeBSD Foundation 14 * 15 * Portions of this software were developed by Konstantin Belousov 16 * under sponsorship from the FreeBSD Foundation. 17 * 18 * Redistribution and use in source and binary forms, with or without 19 * modification, are permitted provided that the following conditions 20 * are met: 21 * 1. Redistributions of source code must retain the above copyright 22 * notice, this list of conditions and the following disclaimer. 23 * 2. Redistributions in binary form must reproduce the above copyright 24 * notice, this list of conditions and the following disclaimer in the 25 * documentation and/or other materials provided with the distribution. 26 * 3. Neither the name of the University nor the names of its contributors 27 * may be used to endorse or promote products derived from this software 28 * without specific prior written permission. 29 * 30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 40 * SUCH DAMAGE. 41 */ 42 43 #include <sys/cdefs.h> 44 #include "opt_hwpmc_hooks.h" 45 46 #include <sys/param.h> 47 #include <sys/systm.h> 48 #include <sys/disk.h> 49 #include <sys/fail.h> 50 #include <sys/fcntl.h> 51 #include <sys/file.h> 52 #include <sys/kdb.h> 53 #include <sys/ktr.h> 54 #include <sys/stat.h> 55 #include <sys/priv.h> 56 #include <sys/proc.h> 57 #include <sys/limits.h> 58 #include <sys/lock.h> 59 #include <sys/mman.h> 60 #include <sys/mount.h> 61 #include <sys/mutex.h> 62 #include <sys/namei.h> 63 #include <sys/vnode.h> 64 #include <sys/dirent.h> 65 #include <sys/bio.h> 66 #include <sys/buf.h> 67 #include <sys/filio.h> 68 #include <sys/resourcevar.h> 69 #include <sys/rwlock.h> 70 #include <sys/prng.h> 71 #include <sys/sx.h> 72 #include <sys/sleepqueue.h> 73 #include <sys/sysctl.h> 74 #include <sys/ttycom.h> 75 #include <sys/conf.h> 76 #include <sys/syslog.h> 77 #include <sys/unistd.h> 78 #include <sys/user.h> 79 #include <sys/ktrace.h> 80 81 #include <security/audit/audit.h> 82 #include <security/mac/mac_framework.h> 83 84 #include <vm/vm.h> 85 #include <vm/vm_extern.h> 86 #include <vm/pmap.h> 87 #include <vm/vm_map.h> 88 #include <vm/vm_object.h> 89 #include <vm/vm_page.h> 90 #include <vm/vm_pager.h> 91 #include <vm/vnode_pager.h> 92 93 #ifdef HWPMC_HOOKS 94 #include <sys/pmckern.h> 95 #endif 96 97 static fo_rdwr_t vn_read; 98 static fo_rdwr_t vn_write; 99 static fo_rdwr_t vn_io_fault; 100 static fo_truncate_t vn_truncate; 101 static fo_ioctl_t vn_ioctl; 102 static fo_poll_t vn_poll; 103 static fo_kqfilter_t vn_kqfilter; 104 static fo_close_t vn_closefile; 105 static fo_mmap_t vn_mmap; 106 static fo_fallocate_t vn_fallocate; 107 static fo_fspacectl_t vn_fspacectl; 108 109 const struct fileops vnops = { 110 .fo_read = vn_io_fault, 111 .fo_write = vn_io_fault, 112 .fo_truncate = vn_truncate, 113 .fo_ioctl = vn_ioctl, 114 .fo_poll = vn_poll, 115 .fo_kqfilter = vn_kqfilter, 116 .fo_stat = vn_statfile, 117 .fo_close = vn_closefile, 118 .fo_chmod = vn_chmod, 119 .fo_chown = vn_chown, 120 .fo_sendfile = vn_sendfile, 121 .fo_seek = vn_seek, 122 .fo_fill_kinfo = vn_fill_kinfo, 123 .fo_mmap = vn_mmap, 124 .fo_fallocate = vn_fallocate, 125 .fo_fspacectl = vn_fspacectl, 126 .fo_cmp = vn_cmp, 127 .fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE 128 }; 129 130 const u_int io_hold_cnt = 16; 131 static int vn_io_fault_enable = 1; 132 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RWTUN, 133 &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance"); 134 static int vn_io_fault_prefault = 0; 135 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_prefault, CTLFLAG_RWTUN, 136 &vn_io_fault_prefault, 0, "Enable vn_io_fault prefaulting"); 137 static int vn_io_pgcache_read_enable = 1; 138 SYSCTL_INT(_debug, OID_AUTO, vn_io_pgcache_read_enable, CTLFLAG_RWTUN, 139 &vn_io_pgcache_read_enable, 0, 140 "Enable copying from page cache for reads, avoiding fs"); 141 static u_long vn_io_faults_cnt; 142 SYSCTL_ULONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD, 143 &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers"); 144 145 static int vfs_allow_read_dir = 0; 146 SYSCTL_INT(_security_bsd, OID_AUTO, allow_read_dir, CTLFLAG_RW, 147 &vfs_allow_read_dir, 0, 148 "Enable read(2) of directory by root for filesystems that support it"); 149 150 /* 151 * Returns true if vn_io_fault mode of handling the i/o request should 152 * be used. 153 */ 154 static bool 155 do_vn_io_fault(struct vnode *vp, struct uio *uio) 156 { 157 struct mount *mp; 158 159 return (uio->uio_segflg == UIO_USERSPACE && vp->v_type == VREG && 160 (mp = vp->v_mount) != NULL && 161 (mp->mnt_kern_flag & MNTK_NO_IOPF) != 0 && vn_io_fault_enable); 162 } 163 164 /* 165 * Structure used to pass arguments to vn_io_fault1(), to do either 166 * file- or vnode-based I/O calls. 167 */ 168 struct vn_io_fault_args { 169 enum { 170 VN_IO_FAULT_FOP, 171 VN_IO_FAULT_VOP 172 } kind; 173 struct ucred *cred; 174 int flags; 175 union { 176 struct fop_args_tag { 177 struct file *fp; 178 fo_rdwr_t *doio; 179 } fop_args; 180 struct vop_args_tag { 181 struct vnode *vp; 182 } vop_args; 183 } args; 184 }; 185 186 static int vn_io_fault1(struct vnode *vp, struct uio *uio, 187 struct vn_io_fault_args *args, struct thread *td); 188 189 int 190 vn_open(struct nameidata *ndp, int *flagp, int cmode, struct file *fp) 191 { 192 struct thread *td = curthread; 193 194 return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp)); 195 } 196 197 static uint64_t 198 open2nameif(int fmode, u_int vn_open_flags) 199 { 200 uint64_t res; 201 202 res = ISOPEN | LOCKLEAF; 203 if ((fmode & O_RESOLVE_BENEATH) != 0) 204 res |= RBENEATH; 205 if ((fmode & O_EMPTY_PATH) != 0) 206 res |= EMPTYPATH; 207 if ((fmode & FREAD) != 0) 208 res |= OPENREAD; 209 if ((fmode & FWRITE) != 0) 210 res |= OPENWRITE; 211 if ((fmode & O_NAMEDATTR) != 0) { 212 res |= OPENNAMED; 213 if ((fmode & O_CREAT) != 0) 214 res |= CREATENAMED; 215 } 216 if ((vn_open_flags & VN_OPEN_NOAUDIT) == 0) 217 res |= AUDITVNODE1; 218 if ((vn_open_flags & VN_OPEN_NOCAPCHECK) != 0) 219 res |= NOCAPCHECK; 220 if ((vn_open_flags & VN_OPEN_WANTIOCTLCAPS) != 0) 221 res |= WANTIOCTLCAPS; 222 return (res); 223 } 224 225 /* 226 * For the O_NAMEDATTR case, check for a valid use of it. 227 */ 228 static int 229 vfs_check_namedattr(struct vnode *vp) 230 { 231 int error; 232 short irflag; 233 234 error = 0; 235 irflag = vn_irflag_read(vp); 236 if ((vp->v_mount->mnt_flag & MNT_NAMEDATTR) == 0 || 237 ((irflag & VIRF_NAMEDATTR) != 0 && vp->v_type != VREG)) 238 error = EINVAL; 239 else if ((irflag & (VIRF_NAMEDDIR | VIRF_NAMEDATTR)) == 0) 240 error = ENOATTR; 241 return (error); 242 } 243 244 /* 245 * Common code for vnode open operations via a name lookup. 246 * Lookup the vnode and invoke VOP_CREATE if needed. 247 * Check permissions, and call the VOP_OPEN or VOP_CREATE routine. 248 * 249 * Note that this does NOT free nameidata for the successful case, 250 * due to the NDINIT being done elsewhere. 251 */ 252 int 253 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags, 254 struct ucred *cred, struct file *fp) 255 { 256 struct vnode *vp; 257 struct mount *mp; 258 struct vattr vat; 259 struct vattr *vap = &vat; 260 int fmode, error; 261 bool first_open; 262 263 restart: 264 first_open = false; 265 fmode = *flagp; 266 if ((fmode & (O_CREAT | O_EXCL | O_DIRECTORY)) == (O_CREAT | 267 O_EXCL | O_DIRECTORY) || 268 (fmode & (O_CREAT | O_EMPTY_PATH)) == (O_CREAT | O_EMPTY_PATH)) 269 return (EINVAL); 270 else if ((fmode & (O_CREAT | O_DIRECTORY)) == O_CREAT) { 271 ndp->ni_cnd.cn_nameiop = CREATE; 272 ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags); 273 /* 274 * Set NOCACHE to avoid flushing the cache when 275 * rolling in many files at once. 276 * 277 * Set NC_KEEPPOSENTRY to keep positive entries if they already 278 * exist despite NOCACHE. 279 */ 280 ndp->ni_cnd.cn_flags |= LOCKPARENT | NOCACHE | NC_KEEPPOSENTRY; 281 if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0) 282 ndp->ni_cnd.cn_flags |= FOLLOW; 283 if ((vn_open_flags & VN_OPEN_INVFS) == 0) 284 bwillwrite(); 285 if ((error = namei(ndp)) != 0) 286 return (error); 287 if (ndp->ni_vp == NULL) { 288 if ((fmode & O_NAMEDATTR) != 0 && 289 (ndp->ni_dvp->v_mount->mnt_flag & MNT_NAMEDATTR) == 290 0) { 291 error = EINVAL; 292 vp = ndp->ni_dvp; 293 ndp->ni_dvp = NULL; 294 goto bad; 295 } 296 VATTR_NULL(vap); 297 vap->va_type = VREG; 298 vap->va_mode = cmode; 299 if (fmode & O_EXCL) 300 vap->va_vaflags |= VA_EXCLUSIVE; 301 if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) { 302 NDFREE_PNBUF(ndp); 303 vput(ndp->ni_dvp); 304 if ((error = vn_start_write(NULL, &mp, 305 V_XSLEEP | V_PCATCH)) != 0) 306 return (error); 307 NDREINIT(ndp); 308 goto restart; 309 } 310 if ((vn_open_flags & VN_OPEN_NAMECACHE) != 0) 311 ndp->ni_cnd.cn_flags |= MAKEENTRY; 312 #ifdef MAC 313 error = mac_vnode_check_create(cred, ndp->ni_dvp, 314 &ndp->ni_cnd, vap); 315 if (error == 0) 316 #endif 317 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp, 318 &ndp->ni_cnd, vap); 319 vp = ndp->ni_vp; 320 if (error == 0 && (fmode & O_EXCL) != 0 && 321 (fmode & (O_EXLOCK | O_SHLOCK)) != 0) { 322 VI_LOCK(vp); 323 vp->v_iflag |= VI_FOPENING; 324 VI_UNLOCK(vp); 325 first_open = true; 326 } 327 VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &vp : NULL, 328 false); 329 vn_finished_write(mp); 330 if (error) { 331 NDFREE_PNBUF(ndp); 332 if (error == ERELOOKUP) { 333 NDREINIT(ndp); 334 goto restart; 335 } 336 return (error); 337 } 338 fmode &= ~O_TRUNC; 339 } else { 340 if (ndp->ni_dvp == ndp->ni_vp) 341 vrele(ndp->ni_dvp); 342 else 343 vput(ndp->ni_dvp); 344 ndp->ni_dvp = NULL; 345 vp = ndp->ni_vp; 346 if (fmode & O_EXCL) { 347 error = EEXIST; 348 goto bad; 349 } 350 if ((fmode & O_NAMEDATTR) != 0) { 351 error = vfs_check_namedattr(vp); 352 if (error != 0) 353 goto bad; 354 } else if (vp->v_type == VDIR) { 355 error = EISDIR; 356 goto bad; 357 } 358 fmode &= ~O_CREAT; 359 } 360 } else { 361 ndp->ni_cnd.cn_nameiop = LOOKUP; 362 ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags); 363 ndp->ni_cnd.cn_flags |= (fmode & O_NOFOLLOW) != 0 ? NOFOLLOW : 364 FOLLOW; 365 if ((fmode & FWRITE) == 0) 366 ndp->ni_cnd.cn_flags |= LOCKSHARED; 367 if ((error = namei(ndp)) != 0) 368 return (error); 369 vp = ndp->ni_vp; 370 if ((fmode & O_NAMEDATTR) != 0) { 371 error = vfs_check_namedattr(vp); 372 if (error != 0) 373 goto bad; 374 } 375 } 376 error = vn_open_vnode(vp, fmode, cred, curthread, fp); 377 if (first_open) { 378 VI_LOCK(vp); 379 vp->v_iflag &= ~VI_FOPENING; 380 wakeup(vp); 381 VI_UNLOCK(vp); 382 } 383 if (error) 384 goto bad; 385 *flagp = fmode; 386 return (0); 387 bad: 388 NDFREE_PNBUF(ndp); 389 vput(vp); 390 *flagp = fmode; 391 ndp->ni_vp = NULL; 392 return (error); 393 } 394 395 static int 396 vn_open_vnode_advlock(struct vnode *vp, int fmode, struct file *fp) 397 { 398 struct flock lf; 399 int error, lock_flags, type; 400 401 ASSERT_VOP_LOCKED(vp, "vn_open_vnode_advlock"); 402 if ((fmode & (O_EXLOCK | O_SHLOCK)) == 0) 403 return (0); 404 KASSERT(fp != NULL, ("open with flock requires fp")); 405 if (fp->f_type != DTYPE_NONE && fp->f_type != DTYPE_VNODE) 406 return (EOPNOTSUPP); 407 408 lock_flags = VOP_ISLOCKED(vp); 409 VOP_UNLOCK(vp); 410 411 lf.l_whence = SEEK_SET; 412 lf.l_start = 0; 413 lf.l_len = 0; 414 lf.l_type = (fmode & O_EXLOCK) != 0 ? F_WRLCK : F_RDLCK; 415 type = F_FLOCK; 416 if ((fmode & FNONBLOCK) == 0) 417 type |= F_WAIT; 418 if ((fmode & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) 419 type |= F_FIRSTOPEN; 420 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type); 421 if (error == 0) 422 fp->f_flag |= FHASLOCK; 423 424 vn_lock(vp, lock_flags | LK_RETRY); 425 return (error); 426 } 427 428 /* 429 * Common code for vnode open operations once a vnode is located. 430 * Check permissions, and call the VOP_OPEN routine. 431 */ 432 int 433 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred, 434 struct thread *td, struct file *fp) 435 { 436 accmode_t accmode; 437 int error; 438 439 KASSERT((fmode & O_PATH) == 0 || (fmode & O_ACCMODE) == 0, 440 ("%s: O_PATH and O_ACCMODE are mutually exclusive", __func__)); 441 442 if (vp->v_type == VLNK) { 443 if ((fmode & O_PATH) == 0 || (fmode & FEXEC) != 0) 444 return (EMLINK); 445 } 446 if (vp->v_type != VDIR && fmode & O_DIRECTORY) 447 return (ENOTDIR); 448 449 accmode = 0; 450 if ((fmode & O_PATH) == 0) { 451 if (vp->v_type == VSOCK) 452 return (EOPNOTSUPP); 453 if ((fmode & (FWRITE | O_TRUNC)) != 0) { 454 if (vp->v_type == VDIR) 455 return (EISDIR); 456 accmode |= VWRITE; 457 } 458 if ((fmode & FREAD) != 0) 459 accmode |= VREAD; 460 if ((fmode & O_APPEND) && (fmode & FWRITE)) 461 accmode |= VAPPEND; 462 #ifdef MAC 463 if ((fmode & O_CREAT) != 0) 464 accmode |= VCREAT; 465 #endif 466 } 467 if ((fmode & FEXEC) != 0) 468 accmode |= VEXEC; 469 #ifdef MAC 470 if ((fmode & O_VERIFY) != 0) 471 accmode |= VVERIFY; 472 error = mac_vnode_check_open(cred, vp, accmode); 473 if (error != 0) 474 return (error); 475 476 accmode &= ~(VCREAT | VVERIFY); 477 #endif 478 if ((fmode & O_CREAT) == 0 && accmode != 0) { 479 error = VOP_ACCESS(vp, accmode, cred, td); 480 if (error != 0) 481 return (error); 482 } 483 if ((fmode & O_PATH) != 0) { 484 if (vp->v_type != VFIFO && vp->v_type != VSOCK && 485 VOP_ACCESS(vp, VREAD, cred, td) == 0) 486 fp->f_flag |= FKQALLOWED; 487 return (0); 488 } 489 490 if (vp->v_type == VFIFO && VOP_ISLOCKED(vp) != LK_EXCLUSIVE) 491 vn_lock(vp, LK_UPGRADE | LK_RETRY); 492 error = VOP_OPEN(vp, fmode, cred, td, fp); 493 if (error != 0) 494 return (error); 495 496 error = vn_open_vnode_advlock(vp, fmode, fp); 497 if (error == 0 && (fmode & FWRITE) != 0) { 498 error = VOP_ADD_WRITECOUNT(vp, 1); 499 if (error == 0) { 500 CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d", 501 __func__, vp, vp->v_writecount); 502 } 503 } 504 505 /* 506 * Error from advlock or VOP_ADD_WRITECOUNT() still requires 507 * calling VOP_CLOSE() to pair with earlier VOP_OPEN(). 508 */ 509 if (error != 0) { 510 if (fp != NULL) { 511 /* 512 * Arrange the call by having fdrop() to use 513 * vn_closefile(). This is to satisfy 514 * filesystems like devfs or tmpfs, which 515 * override fo_close(). 516 */ 517 fp->f_flag |= FOPENFAILED; 518 fp->f_vnode = vp; 519 if (fp->f_ops == &badfileops) { 520 fp->f_type = DTYPE_VNODE; 521 fp->f_ops = &vnops; 522 } 523 vref(vp); 524 } else { 525 /* 526 * If there is no fp, due to kernel-mode open, 527 * we can call VOP_CLOSE() now. 528 */ 529 if ((vp->v_type == VFIFO || 530 !MNT_EXTENDED_SHARED(vp->v_mount)) && 531 VOP_ISLOCKED(vp) != LK_EXCLUSIVE) 532 vn_lock(vp, LK_UPGRADE | LK_RETRY); 533 (void)VOP_CLOSE(vp, fmode & (FREAD | FWRITE | FEXEC), 534 cred, td); 535 } 536 } 537 538 ASSERT_VOP_LOCKED(vp, "vn_open_vnode"); 539 return (error); 540 541 } 542 543 /* 544 * Check for write permissions on the specified vnode. 545 * Prototype text segments cannot be written. 546 * It is racy. 547 */ 548 int 549 vn_writechk(struct vnode *vp) 550 { 551 552 ASSERT_VOP_LOCKED(vp, "vn_writechk"); 553 /* 554 * If there's shared text associated with 555 * the vnode, try to free it up once. If 556 * we fail, we can't allow writing. 557 */ 558 if (VOP_IS_TEXT(vp)) 559 return (ETXTBSY); 560 561 return (0); 562 } 563 564 /* 565 * Vnode close call 566 */ 567 static int 568 vn_close1(struct vnode *vp, int flags, struct ucred *file_cred, 569 struct thread *td, bool keep_ref) 570 { 571 struct mount *mp; 572 int error, lock_flags; 573 574 lock_flags = vp->v_type != VFIFO && MNT_EXTENDED_SHARED(vp->v_mount) ? 575 LK_SHARED : LK_EXCLUSIVE; 576 577 vn_start_write(vp, &mp, V_WAIT); 578 vn_lock(vp, lock_flags | LK_RETRY); 579 AUDIT_ARG_VNODE1(vp); 580 if ((flags & (FWRITE | FOPENFAILED)) == FWRITE) { 581 VOP_ADD_WRITECOUNT_CHECKED(vp, -1); 582 CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d", 583 __func__, vp, vp->v_writecount); 584 } 585 error = VOP_CLOSE(vp, flags, file_cred, td); 586 if (keep_ref) 587 VOP_UNLOCK(vp); 588 else 589 vput(vp); 590 vn_finished_write(mp); 591 return (error); 592 } 593 594 int 595 vn_close(struct vnode *vp, int flags, struct ucred *file_cred, 596 struct thread *td) 597 { 598 599 return (vn_close1(vp, flags, file_cred, td, false)); 600 } 601 602 /* 603 * Heuristic to detect sequential operation. 604 */ 605 static int 606 sequential_heuristic(struct uio *uio, struct file *fp) 607 { 608 enum uio_rw rw; 609 610 ASSERT_VOP_LOCKED(fp->f_vnode, __func__); 611 612 rw = uio->uio_rw; 613 if (fp->f_flag & FRDAHEAD) 614 return (fp->f_seqcount[rw] << IO_SEQSHIFT); 615 616 /* 617 * Offset 0 is handled specially. open() sets f_seqcount to 1 so 618 * that the first I/O is normally considered to be slightly 619 * sequential. Seeking to offset 0 doesn't change sequentiality 620 * unless previous seeks have reduced f_seqcount to 0, in which 621 * case offset 0 is not special. 622 */ 623 if ((uio->uio_offset == 0 && fp->f_seqcount[rw] > 0) || 624 uio->uio_offset == fp->f_nextoff[rw]) { 625 /* 626 * f_seqcount is in units of fixed-size blocks so that it 627 * depends mainly on the amount of sequential I/O and not 628 * much on the number of sequential I/O's. The fixed size 629 * of 16384 is hard-coded here since it is (not quite) just 630 * a magic size that works well here. This size is more 631 * closely related to the best I/O size for real disks than 632 * to any block size used by software. 633 */ 634 if (uio->uio_resid >= IO_SEQMAX * 16384) 635 fp->f_seqcount[rw] = IO_SEQMAX; 636 else { 637 fp->f_seqcount[rw] += howmany(uio->uio_resid, 16384); 638 if (fp->f_seqcount[rw] > IO_SEQMAX) 639 fp->f_seqcount[rw] = IO_SEQMAX; 640 } 641 return (fp->f_seqcount[rw] << IO_SEQSHIFT); 642 } 643 644 /* Not sequential. Quickly draw-down sequentiality. */ 645 if (fp->f_seqcount[rw] > 1) 646 fp->f_seqcount[rw] = 1; 647 else 648 fp->f_seqcount[rw] = 0; 649 return (0); 650 } 651 652 /* 653 * Package up an I/O request on a vnode into a uio and do it. 654 */ 655 int 656 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset, 657 enum uio_seg segflg, int ioflg, struct ucred *active_cred, 658 struct ucred *file_cred, ssize_t *aresid, struct thread *td) 659 { 660 struct uio auio; 661 struct iovec aiov; 662 struct mount *mp; 663 struct ucred *cred; 664 void *rl_cookie; 665 struct vn_io_fault_args args; 666 int error, lock_flags; 667 668 if (offset < 0 && vp->v_type != VCHR) 669 return (EINVAL); 670 auio.uio_iov = &aiov; 671 auio.uio_iovcnt = 1; 672 aiov.iov_base = base; 673 aiov.iov_len = len; 674 auio.uio_resid = len; 675 auio.uio_offset = offset; 676 auio.uio_segflg = segflg; 677 auio.uio_rw = rw; 678 auio.uio_td = td; 679 error = 0; 680 681 if ((ioflg & IO_NODELOCKED) == 0) { 682 if ((ioflg & IO_RANGELOCKED) == 0) { 683 if (rw == UIO_READ) { 684 rl_cookie = vn_rangelock_rlock(vp, offset, 685 offset + len); 686 } else if ((ioflg & IO_APPEND) != 0) { 687 rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX); 688 } else { 689 rl_cookie = vn_rangelock_wlock(vp, offset, 690 offset + len); 691 } 692 } else 693 rl_cookie = NULL; 694 mp = NULL; 695 if (rw == UIO_WRITE) { 696 if (vp->v_type != VCHR && 697 (error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH)) 698 != 0) 699 goto out; 700 lock_flags = vn_lktype_write(mp, vp); 701 } else 702 lock_flags = LK_SHARED; 703 vn_lock(vp, lock_flags | LK_RETRY); 704 } else 705 rl_cookie = NULL; 706 707 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held"); 708 #ifdef MAC 709 if ((ioflg & IO_NOMACCHECK) == 0) { 710 if (rw == UIO_READ) 711 error = mac_vnode_check_read(active_cred, file_cred, 712 vp); 713 else 714 error = mac_vnode_check_write(active_cred, file_cred, 715 vp); 716 } 717 #endif 718 if (error == 0) { 719 if (file_cred != NULL) 720 cred = file_cred; 721 else 722 cred = active_cred; 723 if (do_vn_io_fault(vp, &auio)) { 724 args.kind = VN_IO_FAULT_VOP; 725 args.cred = cred; 726 args.flags = ioflg; 727 args.args.vop_args.vp = vp; 728 error = vn_io_fault1(vp, &auio, &args, td); 729 } else if (rw == UIO_READ) { 730 error = VOP_READ(vp, &auio, ioflg, cred); 731 } else /* if (rw == UIO_WRITE) */ { 732 error = VOP_WRITE(vp, &auio, ioflg, cred); 733 } 734 } 735 if (aresid) 736 *aresid = auio.uio_resid; 737 else 738 if (auio.uio_resid && error == 0) 739 error = EIO; 740 if ((ioflg & IO_NODELOCKED) == 0) { 741 VOP_UNLOCK(vp); 742 if (mp != NULL) 743 vn_finished_write(mp); 744 } 745 out: 746 if (rl_cookie != NULL) 747 vn_rangelock_unlock(vp, rl_cookie); 748 return (error); 749 } 750 751 /* 752 * Package up an I/O request on a vnode into a uio and do it. The I/O 753 * request is split up into smaller chunks and we try to avoid saturating 754 * the buffer cache while potentially holding a vnode locked, so we 755 * check bwillwrite() before calling vn_rdwr(). We also call kern_yield() 756 * to give other processes a chance to lock the vnode (either other processes 757 * core'ing the same binary, or unrelated processes scanning the directory). 758 */ 759 int 760 vn_rdwr_inchunks(enum uio_rw rw, struct vnode *vp, void *base, size_t len, 761 off_t offset, enum uio_seg segflg, int ioflg, struct ucred *active_cred, 762 struct ucred *file_cred, size_t *aresid, struct thread *td) 763 { 764 int error = 0; 765 ssize_t iaresid; 766 767 do { 768 int chunk; 769 770 /* 771 * Force `offset' to a multiple of MAXBSIZE except possibly 772 * for the first chunk, so that filesystems only need to 773 * write full blocks except possibly for the first and last 774 * chunks. 775 */ 776 chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE; 777 778 if (chunk > len) 779 chunk = len; 780 if (rw != UIO_READ && vp->v_type == VREG) 781 bwillwrite(); 782 iaresid = 0; 783 error = vn_rdwr(rw, vp, base, chunk, offset, segflg, 784 ioflg, active_cred, file_cred, &iaresid, td); 785 len -= chunk; /* aresid calc already includes length */ 786 if (error) 787 break; 788 offset += chunk; 789 base = (char *)base + chunk; 790 kern_yield(PRI_USER); 791 } while (len); 792 if (aresid) 793 *aresid = len + iaresid; 794 return (error); 795 } 796 797 #if OFF_MAX <= LONG_MAX 798 off_t 799 foffset_lock(struct file *fp, int flags) 800 { 801 volatile short *flagsp; 802 off_t res; 803 short state; 804 805 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed")); 806 807 if ((flags & FOF_NOLOCK) != 0) 808 return (atomic_load_long(&fp->f_offset)); 809 810 /* 811 * According to McKusick the vn lock was protecting f_offset here. 812 * It is now protected by the FOFFSET_LOCKED flag. 813 */ 814 flagsp = &fp->f_vnread_flags; 815 if (atomic_cmpset_acq_16(flagsp, 0, FOFFSET_LOCKED)) 816 return (atomic_load_long(&fp->f_offset)); 817 818 sleepq_lock(&fp->f_vnread_flags); 819 state = atomic_load_16(flagsp); 820 for (;;) { 821 if ((state & FOFFSET_LOCKED) == 0) { 822 if (!atomic_fcmpset_acq_16(flagsp, &state, 823 FOFFSET_LOCKED)) 824 continue; 825 break; 826 } 827 if ((state & FOFFSET_LOCK_WAITING) == 0) { 828 if (!atomic_fcmpset_acq_16(flagsp, &state, 829 state | FOFFSET_LOCK_WAITING)) 830 continue; 831 } 832 DROP_GIANT(); 833 sleepq_add(&fp->f_vnread_flags, NULL, "vofflock", 0, 0); 834 sleepq_wait(&fp->f_vnread_flags, PUSER -1); 835 PICKUP_GIANT(); 836 sleepq_lock(&fp->f_vnread_flags); 837 state = atomic_load_16(flagsp); 838 } 839 res = atomic_load_long(&fp->f_offset); 840 sleepq_release(&fp->f_vnread_flags); 841 return (res); 842 } 843 844 void 845 foffset_unlock(struct file *fp, off_t val, int flags) 846 { 847 volatile short *flagsp; 848 short state; 849 850 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed")); 851 852 if ((flags & FOF_NOUPDATE) == 0) 853 atomic_store_long(&fp->f_offset, val); 854 if ((flags & FOF_NEXTOFF_R) != 0) 855 fp->f_nextoff[UIO_READ] = val; 856 if ((flags & FOF_NEXTOFF_W) != 0) 857 fp->f_nextoff[UIO_WRITE] = val; 858 859 if ((flags & FOF_NOLOCK) != 0) 860 return; 861 862 flagsp = &fp->f_vnread_flags; 863 state = atomic_load_16(flagsp); 864 if ((state & FOFFSET_LOCK_WAITING) == 0 && 865 atomic_cmpset_rel_16(flagsp, state, 0)) 866 return; 867 868 sleepq_lock(&fp->f_vnread_flags); 869 MPASS((fp->f_vnread_flags & FOFFSET_LOCKED) != 0); 870 MPASS((fp->f_vnread_flags & FOFFSET_LOCK_WAITING) != 0); 871 fp->f_vnread_flags = 0; 872 sleepq_broadcast(&fp->f_vnread_flags, SLEEPQ_SLEEP, 0, 0); 873 sleepq_release(&fp->f_vnread_flags); 874 } 875 876 static off_t 877 foffset_read(struct file *fp) 878 { 879 880 return (atomic_load_long(&fp->f_offset)); 881 } 882 #else 883 off_t 884 foffset_lock(struct file *fp, int flags) 885 { 886 struct mtx *mtxp; 887 off_t res; 888 889 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed")); 890 891 mtxp = mtx_pool_find(mtxpool_sleep, fp); 892 mtx_lock(mtxp); 893 if ((flags & FOF_NOLOCK) == 0) { 894 while (fp->f_vnread_flags & FOFFSET_LOCKED) { 895 fp->f_vnread_flags |= FOFFSET_LOCK_WAITING; 896 msleep(&fp->f_vnread_flags, mtxp, PUSER -1, 897 "vofflock", 0); 898 } 899 fp->f_vnread_flags |= FOFFSET_LOCKED; 900 } 901 res = fp->f_offset; 902 mtx_unlock(mtxp); 903 return (res); 904 } 905 906 void 907 foffset_unlock(struct file *fp, off_t val, int flags) 908 { 909 struct mtx *mtxp; 910 911 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed")); 912 913 mtxp = mtx_pool_find(mtxpool_sleep, fp); 914 mtx_lock(mtxp); 915 if ((flags & FOF_NOUPDATE) == 0) 916 fp->f_offset = val; 917 if ((flags & FOF_NEXTOFF_R) != 0) 918 fp->f_nextoff[UIO_READ] = val; 919 if ((flags & FOF_NEXTOFF_W) != 0) 920 fp->f_nextoff[UIO_WRITE] = val; 921 if ((flags & FOF_NOLOCK) == 0) { 922 KASSERT((fp->f_vnread_flags & FOFFSET_LOCKED) != 0, 923 ("Lost FOFFSET_LOCKED")); 924 if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING) 925 wakeup(&fp->f_vnread_flags); 926 fp->f_vnread_flags = 0; 927 } 928 mtx_unlock(mtxp); 929 } 930 931 static off_t 932 foffset_read(struct file *fp) 933 { 934 935 return (foffset_lock(fp, FOF_NOLOCK)); 936 } 937 #endif 938 939 void 940 foffset_lock_pair(struct file *fp1, off_t *off1p, struct file *fp2, off_t *off2p, 941 int flags) 942 { 943 KASSERT(fp1 != fp2, ("foffset_lock_pair: fp1 == fp2")); 944 945 /* Lock in a consistent order to avoid deadlock. */ 946 if ((uintptr_t)fp1 > (uintptr_t)fp2) { 947 struct file *tmpfp; 948 off_t *tmpoffp; 949 950 tmpfp = fp1, fp1 = fp2, fp2 = tmpfp; 951 tmpoffp = off1p, off1p = off2p, off2p = tmpoffp; 952 } 953 if (fp1 != NULL) 954 *off1p = foffset_lock(fp1, flags); 955 if (fp2 != NULL) 956 *off2p = foffset_lock(fp2, flags); 957 } 958 959 void 960 foffset_lock_uio(struct file *fp, struct uio *uio, int flags) 961 { 962 963 if ((flags & FOF_OFFSET) == 0) 964 uio->uio_offset = foffset_lock(fp, flags); 965 } 966 967 void 968 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags) 969 { 970 971 if ((flags & FOF_OFFSET) == 0) 972 foffset_unlock(fp, uio->uio_offset, flags); 973 } 974 975 static int 976 get_advice(struct file *fp, struct uio *uio) 977 { 978 struct mtx *mtxp; 979 int ret; 980 981 ret = POSIX_FADV_NORMAL; 982 if (fp->f_advice == NULL || fp->f_vnode->v_type != VREG) 983 return (ret); 984 985 mtxp = mtx_pool_find(mtxpool_sleep, fp); 986 mtx_lock(mtxp); 987 if (fp->f_advice != NULL && 988 uio->uio_offset >= fp->f_advice->fa_start && 989 uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end) 990 ret = fp->f_advice->fa_advice; 991 mtx_unlock(mtxp); 992 return (ret); 993 } 994 995 static int 996 get_write_ioflag(struct file *fp) 997 { 998 int ioflag; 999 struct mount *mp; 1000 struct vnode *vp; 1001 1002 ioflag = 0; 1003 vp = fp->f_vnode; 1004 mp = atomic_load_ptr(&vp->v_mount); 1005 1006 if ((fp->f_flag & O_DIRECT) != 0) 1007 ioflag |= IO_DIRECT; 1008 1009 if ((fp->f_flag & O_FSYNC) != 0 || 1010 (mp != NULL && (mp->mnt_flag & MNT_SYNCHRONOUS) != 0)) 1011 ioflag |= IO_SYNC; 1012 1013 /* 1014 * For O_DSYNC we set both IO_SYNC and IO_DATASYNC, so that VOP_WRITE() 1015 * or VOP_DEALLOCATE() implementations that don't understand IO_DATASYNC 1016 * fall back to full O_SYNC behavior. 1017 */ 1018 if ((fp->f_flag & O_DSYNC) != 0) 1019 ioflag |= IO_SYNC | IO_DATASYNC; 1020 1021 return (ioflag); 1022 } 1023 1024 int 1025 vn_read_from_obj(struct vnode *vp, struct uio *uio) 1026 { 1027 vm_object_t obj; 1028 vm_page_t ma[io_hold_cnt + 2]; 1029 off_t off, vsz; 1030 ssize_t resid; 1031 int error, i, j; 1032 1033 MPASS(uio->uio_resid <= ptoa(io_hold_cnt + 2)); 1034 obj = atomic_load_ptr(&vp->v_object); 1035 if (obj == NULL) 1036 return (EJUSTRETURN); 1037 1038 /* 1039 * Depends on type stability of vm_objects. 1040 */ 1041 vm_object_pip_add(obj, 1); 1042 if ((obj->flags & OBJ_DEAD) != 0) { 1043 /* 1044 * Note that object might be already reused from the 1045 * vnode, and the OBJ_DEAD flag cleared. This is fine, 1046 * we recheck for DOOMED vnode state after all pages 1047 * are busied, and retract then. 1048 * 1049 * But we check for OBJ_DEAD to ensure that we do not 1050 * busy pages while vm_object_terminate_pages() 1051 * processes the queue. 1052 */ 1053 error = EJUSTRETURN; 1054 goto out_pip; 1055 } 1056 1057 resid = uio->uio_resid; 1058 off = uio->uio_offset; 1059 for (i = 0; resid > 0; i++) { 1060 MPASS(i < io_hold_cnt + 2); 1061 ma[i] = vm_page_grab_unlocked(obj, atop(off), 1062 VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY | 1063 VM_ALLOC_NOWAIT); 1064 if (ma[i] == NULL) 1065 break; 1066 1067 /* 1068 * Skip invalid pages. Valid mask can be partial only 1069 * at EOF, and we clip later. 1070 */ 1071 if (vm_page_none_valid(ma[i])) { 1072 vm_page_sunbusy(ma[i]); 1073 break; 1074 } 1075 1076 resid -= PAGE_SIZE; 1077 off += PAGE_SIZE; 1078 } 1079 if (i == 0) { 1080 error = EJUSTRETURN; 1081 goto out_pip; 1082 } 1083 1084 /* 1085 * Check VIRF_DOOMED after we busied our pages. Since 1086 * vgonel() terminates the vnode' vm_object, it cannot 1087 * process past pages busied by us. 1088 */ 1089 if (VN_IS_DOOMED(vp)) { 1090 error = EJUSTRETURN; 1091 goto out; 1092 } 1093 1094 resid = PAGE_SIZE - (uio->uio_offset & PAGE_MASK) + ptoa(i - 1); 1095 if (resid > uio->uio_resid) 1096 resid = uio->uio_resid; 1097 1098 /* 1099 * Unlocked read of vnp_size is safe because truncation cannot 1100 * pass busied page. But we load vnp_size into a local 1101 * variable so that possible concurrent extension does not 1102 * break calculation. 1103 */ 1104 #if defined(__powerpc__) && !defined(__powerpc64__) 1105 vsz = obj->un_pager.vnp.vnp_size; 1106 #else 1107 vsz = atomic_load_64(&obj->un_pager.vnp.vnp_size); 1108 #endif 1109 if (uio->uio_offset >= vsz) { 1110 error = EJUSTRETURN; 1111 goto out; 1112 } 1113 if (uio->uio_offset + resid > vsz) 1114 resid = vsz - uio->uio_offset; 1115 1116 error = vn_io_fault_pgmove(ma, uio->uio_offset & PAGE_MASK, resid, uio); 1117 1118 out: 1119 for (j = 0; j < i; j++) { 1120 if (error == 0) 1121 vm_page_reference(ma[j]); 1122 vm_page_sunbusy(ma[j]); 1123 } 1124 out_pip: 1125 vm_object_pip_wakeup(obj); 1126 if (error != 0) 1127 return (error); 1128 return (uio->uio_resid == 0 ? 0 : EJUSTRETURN); 1129 } 1130 1131 /* 1132 * File table vnode read routine. 1133 */ 1134 static int 1135 vn_read(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, 1136 struct thread *td) 1137 { 1138 struct vnode *vp; 1139 off_t orig_offset; 1140 int error, ioflag; 1141 int advice; 1142 1143 KASSERT(uio->uio_td == td, ("uio_td %p is not td %p", 1144 uio->uio_td, td)); 1145 KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET")); 1146 vp = fp->f_vnode; 1147 ioflag = 0; 1148 if (fp->f_flag & FNONBLOCK) 1149 ioflag |= IO_NDELAY; 1150 if (fp->f_flag & O_DIRECT) 1151 ioflag |= IO_DIRECT; 1152 1153 /* 1154 * Try to read from page cache. VIRF_DOOMED check is racy but 1155 * allows us to avoid unneeded work outright. 1156 */ 1157 if (vn_io_pgcache_read_enable && !mac_vnode_check_read_enabled() && 1158 (vn_irflag_read(vp) & (VIRF_DOOMED | VIRF_PGREAD)) == VIRF_PGREAD) { 1159 error = VOP_READ_PGCACHE(vp, uio, ioflag, fp->f_cred); 1160 if (error == 0) { 1161 fp->f_nextoff[UIO_READ] = uio->uio_offset; 1162 return (0); 1163 } 1164 if (error != EJUSTRETURN) 1165 return (error); 1166 } 1167 1168 advice = get_advice(fp, uio); 1169 vn_lock(vp, LK_SHARED | LK_RETRY); 1170 1171 switch (advice) { 1172 case POSIX_FADV_NORMAL: 1173 case POSIX_FADV_SEQUENTIAL: 1174 case POSIX_FADV_NOREUSE: 1175 ioflag |= sequential_heuristic(uio, fp); 1176 break; 1177 case POSIX_FADV_RANDOM: 1178 /* Disable read-ahead for random I/O. */ 1179 break; 1180 } 1181 orig_offset = uio->uio_offset; 1182 1183 #ifdef MAC 1184 error = mac_vnode_check_read(active_cred, fp->f_cred, vp); 1185 if (error == 0) 1186 #endif 1187 error = VOP_READ(vp, uio, ioflag, fp->f_cred); 1188 fp->f_nextoff[UIO_READ] = uio->uio_offset; 1189 VOP_UNLOCK(vp); 1190 if (error == 0 && advice == POSIX_FADV_NOREUSE && 1191 orig_offset != uio->uio_offset) 1192 /* 1193 * Use POSIX_FADV_DONTNEED to flush pages and buffers 1194 * for the backing file after a POSIX_FADV_NOREUSE 1195 * read(2). 1196 */ 1197 error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1, 1198 POSIX_FADV_DONTNEED); 1199 return (error); 1200 } 1201 1202 /* 1203 * File table vnode write routine. 1204 */ 1205 static int 1206 vn_write(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, 1207 struct thread *td) 1208 { 1209 struct vnode *vp; 1210 struct mount *mp; 1211 off_t orig_offset; 1212 int error, ioflag; 1213 int advice; 1214 bool need_finished_write; 1215 1216 KASSERT(uio->uio_td == td, ("uio_td %p is not td %p", 1217 uio->uio_td, td)); 1218 KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET")); 1219 vp = fp->f_vnode; 1220 if (vp->v_type == VREG) 1221 bwillwrite(); 1222 ioflag = IO_UNIT; 1223 if (vp->v_type == VREG && (fp->f_flag & O_APPEND) != 0) 1224 ioflag |= IO_APPEND; 1225 if ((fp->f_flag & FNONBLOCK) != 0) 1226 ioflag |= IO_NDELAY; 1227 ioflag |= get_write_ioflag(fp); 1228 1229 mp = NULL; 1230 need_finished_write = false; 1231 if (vp->v_type != VCHR) { 1232 error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH); 1233 if (error != 0) 1234 goto unlock; 1235 need_finished_write = true; 1236 } 1237 1238 advice = get_advice(fp, uio); 1239 1240 vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY); 1241 switch (advice) { 1242 case POSIX_FADV_NORMAL: 1243 case POSIX_FADV_SEQUENTIAL: 1244 case POSIX_FADV_NOREUSE: 1245 ioflag |= sequential_heuristic(uio, fp); 1246 break; 1247 case POSIX_FADV_RANDOM: 1248 /* XXX: Is this correct? */ 1249 break; 1250 } 1251 orig_offset = uio->uio_offset; 1252 1253 #ifdef MAC 1254 error = mac_vnode_check_write(active_cred, fp->f_cred, vp); 1255 if (error == 0) 1256 #endif 1257 error = VOP_WRITE(vp, uio, ioflag, fp->f_cred); 1258 fp->f_nextoff[UIO_WRITE] = uio->uio_offset; 1259 VOP_UNLOCK(vp); 1260 if (need_finished_write) 1261 vn_finished_write(mp); 1262 if (error == 0 && advice == POSIX_FADV_NOREUSE && 1263 orig_offset != uio->uio_offset) 1264 /* 1265 * Use POSIX_FADV_DONTNEED to flush pages and buffers 1266 * for the backing file after a POSIX_FADV_NOREUSE 1267 * write(2). 1268 */ 1269 error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1, 1270 POSIX_FADV_DONTNEED); 1271 unlock: 1272 return (error); 1273 } 1274 1275 /* 1276 * The vn_io_fault() is a wrapper around vn_read() and vn_write() to 1277 * prevent the following deadlock: 1278 * 1279 * Assume that the thread A reads from the vnode vp1 into userspace 1280 * buffer buf1 backed by the pages of vnode vp2. If a page in buf1 is 1281 * currently not resident, then system ends up with the call chain 1282 * vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] -> 1283 * vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2) 1284 * which establishes lock order vp1->vn_lock, then vp2->vn_lock. 1285 * If, at the same time, thread B reads from vnode vp2 into buffer buf2 1286 * backed by the pages of vnode vp1, and some page in buf2 is not 1287 * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock. 1288 * 1289 * To prevent the lock order reversal and deadlock, vn_io_fault() does 1290 * not allow page faults to happen during VOP_READ() or VOP_WRITE(). 1291 * Instead, it first tries to do the whole range i/o with pagefaults 1292 * disabled. If all pages in the i/o buffer are resident and mapped, 1293 * VOP will succeed (ignoring the genuine filesystem errors). 1294 * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do 1295 * i/o in chunks, with all pages in the chunk prefaulted and held 1296 * using vm_fault_quick_hold_pages(). 1297 * 1298 * Filesystems using this deadlock avoidance scheme should use the 1299 * array of the held pages from uio, saved in the curthread->td_ma, 1300 * instead of doing uiomove(). A helper function 1301 * vn_io_fault_uiomove() converts uiomove request into 1302 * uiomove_fromphys() over td_ma array. 1303 * 1304 * Since vnode locks do not cover the whole i/o anymore, rangelocks 1305 * make the current i/o request atomic with respect to other i/os and 1306 * truncations. 1307 */ 1308 1309 /* 1310 * Decode vn_io_fault_args and perform the corresponding i/o. 1311 */ 1312 static int 1313 vn_io_fault_doio(struct vn_io_fault_args *args, struct uio *uio, 1314 struct thread *td) 1315 { 1316 int error, save; 1317 1318 error = 0; 1319 save = vm_fault_disable_pagefaults(); 1320 switch (args->kind) { 1321 case VN_IO_FAULT_FOP: 1322 error = (args->args.fop_args.doio)(args->args.fop_args.fp, 1323 uio, args->cred, args->flags, td); 1324 break; 1325 case VN_IO_FAULT_VOP: 1326 switch (uio->uio_rw) { 1327 case UIO_READ: 1328 error = VOP_READ(args->args.vop_args.vp, uio, 1329 args->flags, args->cred); 1330 break; 1331 case UIO_WRITE: 1332 error = VOP_WRITE(args->args.vop_args.vp, uio, 1333 args->flags, args->cred); 1334 break; 1335 } 1336 break; 1337 default: 1338 panic("vn_io_fault_doio: unknown kind of io %d %d", 1339 args->kind, uio->uio_rw); 1340 } 1341 vm_fault_enable_pagefaults(save); 1342 return (error); 1343 } 1344 1345 static int 1346 vn_io_fault_touch(char *base, const struct uio *uio) 1347 { 1348 int r; 1349 1350 r = fubyte(base); 1351 if (r == -1 || (uio->uio_rw == UIO_READ && subyte(base, r) == -1)) 1352 return (EFAULT); 1353 return (0); 1354 } 1355 1356 static int 1357 vn_io_fault_prefault_user(const struct uio *uio) 1358 { 1359 char *base; 1360 const struct iovec *iov; 1361 size_t len; 1362 ssize_t resid; 1363 int error, i; 1364 1365 KASSERT(uio->uio_segflg == UIO_USERSPACE, 1366 ("vn_io_fault_prefault userspace")); 1367 1368 error = i = 0; 1369 iov = uio->uio_iov; 1370 resid = uio->uio_resid; 1371 base = iov->iov_base; 1372 len = iov->iov_len; 1373 while (resid > 0) { 1374 error = vn_io_fault_touch(base, uio); 1375 if (error != 0) 1376 break; 1377 if (len < PAGE_SIZE) { 1378 if (len != 0) { 1379 error = vn_io_fault_touch(base + len - 1, uio); 1380 if (error != 0) 1381 break; 1382 resid -= len; 1383 } 1384 if (++i >= uio->uio_iovcnt) 1385 break; 1386 iov = uio->uio_iov + i; 1387 base = iov->iov_base; 1388 len = iov->iov_len; 1389 } else { 1390 len -= PAGE_SIZE; 1391 base += PAGE_SIZE; 1392 resid -= PAGE_SIZE; 1393 } 1394 } 1395 return (error); 1396 } 1397 1398 /* 1399 * Common code for vn_io_fault(), agnostic to the kind of i/o request. 1400 * Uses vn_io_fault_doio() to make the call to an actual i/o function. 1401 * Used from vn_rdwr() and vn_io_fault(), which encode the i/o request 1402 * into args and call vn_io_fault1() to handle faults during the user 1403 * mode buffer accesses. 1404 */ 1405 static int 1406 vn_io_fault1(struct vnode *vp, struct uio *uio, struct vn_io_fault_args *args, 1407 struct thread *td) 1408 { 1409 vm_page_t ma[io_hold_cnt + 2]; 1410 struct uio *uio_clone, short_uio; 1411 struct iovec short_iovec[1]; 1412 vm_page_t *prev_td_ma; 1413 vm_prot_t prot; 1414 vm_offset_t addr, end; 1415 size_t len, resid; 1416 ssize_t adv; 1417 int error, cnt, saveheld, prev_td_ma_cnt; 1418 1419 if (vn_io_fault_prefault) { 1420 error = vn_io_fault_prefault_user(uio); 1421 if (error != 0) 1422 return (error); /* Or ignore ? */ 1423 } 1424 1425 prot = uio->uio_rw == UIO_READ ? VM_PROT_WRITE : VM_PROT_READ; 1426 1427 /* 1428 * The UFS follows IO_UNIT directive and replays back both 1429 * uio_offset and uio_resid if an error is encountered during the 1430 * operation. But, since the iovec may be already advanced, 1431 * uio is still in an inconsistent state. 1432 * 1433 * Cache a copy of the original uio, which is advanced to the redo 1434 * point using UIO_NOCOPY below. 1435 */ 1436 uio_clone = cloneuio(uio); 1437 resid = uio->uio_resid; 1438 1439 short_uio.uio_segflg = UIO_USERSPACE; 1440 short_uio.uio_rw = uio->uio_rw; 1441 short_uio.uio_td = uio->uio_td; 1442 1443 error = vn_io_fault_doio(args, uio, td); 1444 if (error != EFAULT) 1445 goto out; 1446 1447 atomic_add_long(&vn_io_faults_cnt, 1); 1448 uio_clone->uio_segflg = UIO_NOCOPY; 1449 uiomove(NULL, resid - uio->uio_resid, uio_clone); 1450 uio_clone->uio_segflg = uio->uio_segflg; 1451 1452 saveheld = curthread_pflags_set(TDP_UIOHELD); 1453 prev_td_ma = td->td_ma; 1454 prev_td_ma_cnt = td->td_ma_cnt; 1455 1456 while (uio_clone->uio_resid != 0) { 1457 len = uio_clone->uio_iov->iov_len; 1458 if (len == 0) { 1459 KASSERT(uio_clone->uio_iovcnt >= 1, 1460 ("iovcnt underflow")); 1461 uio_clone->uio_iov++; 1462 uio_clone->uio_iovcnt--; 1463 continue; 1464 } 1465 if (len > ptoa(io_hold_cnt)) 1466 len = ptoa(io_hold_cnt); 1467 addr = (uintptr_t)uio_clone->uio_iov->iov_base; 1468 end = round_page(addr + len); 1469 if (end < addr) { 1470 error = EFAULT; 1471 break; 1472 } 1473 /* 1474 * A perfectly misaligned address and length could cause 1475 * both the start and the end of the chunk to use partial 1476 * page. +2 accounts for such a situation. 1477 */ 1478 cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map, 1479 addr, len, prot, ma, io_hold_cnt + 2); 1480 if (cnt == -1) { 1481 error = EFAULT; 1482 break; 1483 } 1484 short_uio.uio_iov = &short_iovec[0]; 1485 short_iovec[0].iov_base = (void *)addr; 1486 short_uio.uio_iovcnt = 1; 1487 short_uio.uio_resid = short_iovec[0].iov_len = len; 1488 short_uio.uio_offset = uio_clone->uio_offset; 1489 td->td_ma = ma; 1490 td->td_ma_cnt = cnt; 1491 1492 error = vn_io_fault_doio(args, &short_uio, td); 1493 vm_page_unhold_pages(ma, cnt); 1494 adv = len - short_uio.uio_resid; 1495 1496 uio_clone->uio_iov->iov_base = 1497 (char *)uio_clone->uio_iov->iov_base + adv; 1498 uio_clone->uio_iov->iov_len -= adv; 1499 uio_clone->uio_resid -= adv; 1500 uio_clone->uio_offset += adv; 1501 1502 uio->uio_resid -= adv; 1503 uio->uio_offset += adv; 1504 1505 if (error != 0 || adv == 0) 1506 break; 1507 } 1508 td->td_ma = prev_td_ma; 1509 td->td_ma_cnt = prev_td_ma_cnt; 1510 curthread_pflags_restore(saveheld); 1511 out: 1512 freeuio(uio_clone); 1513 return (error); 1514 } 1515 1516 static int 1517 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred, 1518 int flags, struct thread *td) 1519 { 1520 fo_rdwr_t *doio; 1521 struct vnode *vp; 1522 void *rl_cookie; 1523 struct vn_io_fault_args args; 1524 int error; 1525 bool do_io_fault, do_rangelock; 1526 1527 doio = uio->uio_rw == UIO_READ ? vn_read : vn_write; 1528 vp = fp->f_vnode; 1529 1530 /* 1531 * The ability to read(2) on a directory has historically been 1532 * allowed for all users, but this can and has been the source of 1533 * at least one security issue in the past. As such, it is now hidden 1534 * away behind a sysctl for those that actually need it to use it, and 1535 * restricted to root when it's turned on to make it relatively safe to 1536 * leave on for longer sessions of need. 1537 */ 1538 if (vp->v_type == VDIR) { 1539 KASSERT(uio->uio_rw == UIO_READ, 1540 ("illegal write attempted on a directory")); 1541 if (!vfs_allow_read_dir) 1542 return (EISDIR); 1543 if ((error = priv_check(td, PRIV_VFS_READ_DIR)) != 0) 1544 return (EISDIR); 1545 } 1546 1547 do_io_fault = do_vn_io_fault(vp, uio); 1548 do_rangelock = do_io_fault || (vn_irflag_read(vp) & VIRF_PGREAD) != 0; 1549 foffset_lock_uio(fp, uio, flags); 1550 if (do_rangelock) { 1551 if (uio->uio_rw == UIO_READ) { 1552 rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset, 1553 uio->uio_offset + uio->uio_resid); 1554 } else if ((fp->f_flag & O_APPEND) != 0 || 1555 (flags & FOF_OFFSET) == 0) { 1556 /* For appenders, punt and lock the whole range. */ 1557 rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX); 1558 } else { 1559 rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset, 1560 uio->uio_offset + uio->uio_resid); 1561 } 1562 } 1563 if (do_io_fault) { 1564 args.kind = VN_IO_FAULT_FOP; 1565 args.args.fop_args.fp = fp; 1566 args.args.fop_args.doio = doio; 1567 args.cred = active_cred; 1568 args.flags = flags | FOF_OFFSET; 1569 error = vn_io_fault1(vp, uio, &args, td); 1570 } else { 1571 error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td); 1572 } 1573 if (do_rangelock) 1574 vn_rangelock_unlock(vp, rl_cookie); 1575 foffset_unlock_uio(fp, uio, flags); 1576 return (error); 1577 } 1578 1579 /* 1580 * Helper function to perform the requested uiomove operation using 1581 * the held pages for io->uio_iov[0].iov_base buffer instead of 1582 * copyin/copyout. Access to the pages with uiomove_fromphys() 1583 * instead of iov_base prevents page faults that could occur due to 1584 * pmap_collect() invalidating the mapping created by 1585 * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or 1586 * object cleanup revoking the write access from page mappings. 1587 * 1588 * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove() 1589 * instead of plain uiomove(). 1590 */ 1591 int 1592 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio) 1593 { 1594 struct uio transp_uio; 1595 struct iovec transp_iov[1]; 1596 struct thread *td; 1597 size_t adv; 1598 int error, pgadv; 1599 1600 td = curthread; 1601 if ((td->td_pflags & TDP_UIOHELD) == 0 || 1602 uio->uio_segflg != UIO_USERSPACE) 1603 return (uiomove(data, xfersize, uio)); 1604 1605 KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt)); 1606 transp_iov[0].iov_base = data; 1607 transp_uio.uio_iov = &transp_iov[0]; 1608 transp_uio.uio_iovcnt = 1; 1609 if (xfersize > uio->uio_resid) 1610 xfersize = uio->uio_resid; 1611 transp_uio.uio_resid = transp_iov[0].iov_len = xfersize; 1612 transp_uio.uio_offset = 0; 1613 transp_uio.uio_segflg = UIO_SYSSPACE; 1614 /* 1615 * Since transp_iov points to data, and td_ma page array 1616 * corresponds to original uio->uio_iov, we need to invert the 1617 * direction of the i/o operation as passed to 1618 * uiomove_fromphys(). 1619 */ 1620 switch (uio->uio_rw) { 1621 case UIO_WRITE: 1622 transp_uio.uio_rw = UIO_READ; 1623 break; 1624 case UIO_READ: 1625 transp_uio.uio_rw = UIO_WRITE; 1626 break; 1627 } 1628 transp_uio.uio_td = uio->uio_td; 1629 error = uiomove_fromphys(td->td_ma, 1630 ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK, 1631 xfersize, &transp_uio); 1632 adv = xfersize - transp_uio.uio_resid; 1633 pgadv = 1634 (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) - 1635 (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT); 1636 td->td_ma += pgadv; 1637 KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt, 1638 pgadv)); 1639 td->td_ma_cnt -= pgadv; 1640 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv; 1641 uio->uio_iov->iov_len -= adv; 1642 uio->uio_resid -= adv; 1643 uio->uio_offset += adv; 1644 return (error); 1645 } 1646 1647 int 1648 vn_io_fault_pgmove(vm_page_t ma[], vm_offset_t offset, int xfersize, 1649 struct uio *uio) 1650 { 1651 struct thread *td; 1652 vm_offset_t iov_base; 1653 int cnt, pgadv; 1654 1655 td = curthread; 1656 if ((td->td_pflags & TDP_UIOHELD) == 0 || 1657 uio->uio_segflg != UIO_USERSPACE) 1658 return (uiomove_fromphys(ma, offset, xfersize, uio)); 1659 1660 KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt)); 1661 cnt = xfersize > uio->uio_resid ? uio->uio_resid : xfersize; 1662 iov_base = (vm_offset_t)uio->uio_iov->iov_base; 1663 switch (uio->uio_rw) { 1664 case UIO_WRITE: 1665 pmap_copy_pages(td->td_ma, iov_base & PAGE_MASK, ma, 1666 offset, cnt); 1667 break; 1668 case UIO_READ: 1669 pmap_copy_pages(ma, offset, td->td_ma, iov_base & PAGE_MASK, 1670 cnt); 1671 break; 1672 } 1673 pgadv = ((iov_base + cnt) >> PAGE_SHIFT) - (iov_base >> PAGE_SHIFT); 1674 td->td_ma += pgadv; 1675 KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt, 1676 pgadv)); 1677 td->td_ma_cnt -= pgadv; 1678 uio->uio_iov->iov_base = (char *)(iov_base + cnt); 1679 uio->uio_iov->iov_len -= cnt; 1680 uio->uio_resid -= cnt; 1681 uio->uio_offset += cnt; 1682 return (0); 1683 } 1684 1685 /* 1686 * File table truncate routine. 1687 */ 1688 static int 1689 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred, 1690 struct thread *td) 1691 { 1692 struct mount *mp; 1693 struct vnode *vp; 1694 void *rl_cookie; 1695 int error; 1696 1697 vp = fp->f_vnode; 1698 1699 retry: 1700 /* 1701 * Lock the whole range for truncation. Otherwise split i/o 1702 * might happen partly before and partly after the truncation. 1703 */ 1704 rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX); 1705 error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH); 1706 if (error) 1707 goto out1; 1708 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY); 1709 AUDIT_ARG_VNODE1(vp); 1710 if (vp->v_type == VDIR) { 1711 error = EISDIR; 1712 goto out; 1713 } 1714 #ifdef MAC 1715 error = mac_vnode_check_write(active_cred, fp->f_cred, vp); 1716 if (error) 1717 goto out; 1718 #endif 1719 error = vn_truncate_locked(vp, length, (fp->f_flag & O_FSYNC) != 0, 1720 fp->f_cred); 1721 out: 1722 VOP_UNLOCK(vp); 1723 vn_finished_write(mp); 1724 out1: 1725 vn_rangelock_unlock(vp, rl_cookie); 1726 if (error == ERELOOKUP) 1727 goto retry; 1728 return (error); 1729 } 1730 1731 /* 1732 * Truncate a file that is already locked. 1733 */ 1734 int 1735 vn_truncate_locked(struct vnode *vp, off_t length, bool sync, 1736 struct ucred *cred) 1737 { 1738 struct vattr vattr; 1739 int error; 1740 1741 error = VOP_ADD_WRITECOUNT(vp, 1); 1742 if (error == 0) { 1743 VATTR_NULL(&vattr); 1744 vattr.va_size = length; 1745 if (sync) 1746 vattr.va_vaflags |= VA_SYNC; 1747 error = VOP_SETATTR(vp, &vattr, cred); 1748 VOP_ADD_WRITECOUNT_CHECKED(vp, -1); 1749 } 1750 return (error); 1751 } 1752 1753 /* 1754 * File table vnode stat routine. 1755 */ 1756 int 1757 vn_statfile(struct file *fp, struct stat *sb, struct ucred *active_cred) 1758 { 1759 struct vnode *vp = fp->f_vnode; 1760 int error; 1761 1762 vn_lock(vp, LK_SHARED | LK_RETRY); 1763 error = VOP_STAT(vp, sb, active_cred, fp->f_cred); 1764 VOP_UNLOCK(vp); 1765 1766 return (error); 1767 } 1768 1769 /* 1770 * File table vnode ioctl routine. 1771 */ 1772 static int 1773 vn_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, 1774 struct thread *td) 1775 { 1776 struct vnode *vp; 1777 struct fiobmap2_arg *bmarg; 1778 off_t size; 1779 int error; 1780 1781 vp = fp->f_vnode; 1782 switch (vp->v_type) { 1783 case VDIR: 1784 case VREG: 1785 switch (com) { 1786 case FIONREAD: 1787 error = vn_getsize(vp, &size, active_cred); 1788 if (error == 0) 1789 *(int *)data = size - fp->f_offset; 1790 return (error); 1791 case FIOBMAP2: 1792 bmarg = (struct fiobmap2_arg *)data; 1793 vn_lock(vp, LK_SHARED | LK_RETRY); 1794 #ifdef MAC 1795 error = mac_vnode_check_read(active_cred, fp->f_cred, 1796 vp); 1797 if (error == 0) 1798 #endif 1799 error = VOP_BMAP(vp, bmarg->bn, NULL, 1800 &bmarg->bn, &bmarg->runp, &bmarg->runb); 1801 VOP_UNLOCK(vp); 1802 return (error); 1803 case FIONBIO: 1804 case FIOASYNC: 1805 return (0); 1806 default: 1807 return (VOP_IOCTL(vp, com, data, fp->f_flag, 1808 active_cred, td)); 1809 } 1810 break; 1811 case VCHR: 1812 return (VOP_IOCTL(vp, com, data, fp->f_flag, 1813 active_cred, td)); 1814 default: 1815 return (ENOTTY); 1816 } 1817 } 1818 1819 /* 1820 * File table vnode poll routine. 1821 */ 1822 static int 1823 vn_poll(struct file *fp, int events, struct ucred *active_cred, 1824 struct thread *td) 1825 { 1826 struct vnode *vp; 1827 int error; 1828 1829 vp = fp->f_vnode; 1830 #if defined(MAC) || defined(AUDIT) 1831 if (AUDITING_TD(td) || mac_vnode_check_poll_enabled()) { 1832 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY); 1833 AUDIT_ARG_VNODE1(vp); 1834 error = mac_vnode_check_poll(active_cred, fp->f_cred, vp); 1835 VOP_UNLOCK(vp); 1836 if (error != 0) 1837 return (error); 1838 } 1839 #endif 1840 error = VOP_POLL(vp, events, fp->f_cred, td); 1841 return (error); 1842 } 1843 1844 /* 1845 * Acquire the requested lock and then check for validity. LK_RETRY 1846 * permits vn_lock to return doomed vnodes. 1847 */ 1848 static int __noinline 1849 _vn_lock_fallback(struct vnode *vp, int flags, const char *file, int line, 1850 int error) 1851 { 1852 1853 KASSERT((flags & LK_RETRY) == 0 || error == 0, 1854 ("vn_lock: error %d incompatible with flags %#x", error, flags)); 1855 1856 if (error == 0) 1857 VNASSERT(VN_IS_DOOMED(vp), vp, ("vnode not doomed")); 1858 1859 if ((flags & LK_RETRY) == 0) { 1860 if (error == 0) { 1861 VOP_UNLOCK(vp); 1862 error = ENOENT; 1863 } 1864 return (error); 1865 } 1866 1867 /* 1868 * LK_RETRY case. 1869 * 1870 * Nothing to do if we got the lock. 1871 */ 1872 if (error == 0) 1873 return (0); 1874 1875 /* 1876 * Interlock was dropped by the call in _vn_lock. 1877 */ 1878 flags &= ~LK_INTERLOCK; 1879 do { 1880 error = VOP_LOCK1(vp, flags, file, line); 1881 } while (error != 0); 1882 return (0); 1883 } 1884 1885 int 1886 _vn_lock(struct vnode *vp, int flags, const char *file, int line) 1887 { 1888 int error; 1889 1890 VNASSERT((flags & LK_TYPE_MASK) != 0, vp, 1891 ("vn_lock: no locktype (%d passed)", flags)); 1892 VNPASS(vp->v_holdcnt > 0, vp); 1893 error = VOP_LOCK1(vp, flags, file, line); 1894 if (__predict_false(error != 0 || VN_IS_DOOMED(vp))) 1895 return (_vn_lock_fallback(vp, flags, file, line, error)); 1896 return (0); 1897 } 1898 1899 /* 1900 * File table vnode close routine. 1901 */ 1902 static int 1903 vn_closefile(struct file *fp, struct thread *td) 1904 { 1905 struct vnode *vp; 1906 struct flock lf; 1907 int error; 1908 bool ref; 1909 1910 vp = fp->f_vnode; 1911 fp->f_ops = &badfileops; 1912 ref = (fp->f_flag & FHASLOCK) != 0; 1913 1914 error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref); 1915 1916 if (__predict_false(ref)) { 1917 lf.l_whence = SEEK_SET; 1918 lf.l_start = 0; 1919 lf.l_len = 0; 1920 lf.l_type = F_UNLCK; 1921 (void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK); 1922 vrele(vp); 1923 } 1924 return (error); 1925 } 1926 1927 /* 1928 * Preparing to start a filesystem write operation. If the operation is 1929 * permitted, then we bump the count of operations in progress and 1930 * proceed. If a suspend request is in progress, we wait until the 1931 * suspension is over, and then proceed. 1932 */ 1933 static int 1934 vn_start_write_refed(struct mount *mp, int flags, bool mplocked) 1935 { 1936 struct mount_pcpu *mpcpu; 1937 int error, mflags; 1938 1939 if (__predict_true(!mplocked) && (flags & V_XSLEEP) == 0 && 1940 vfs_op_thread_enter(mp, mpcpu)) { 1941 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0); 1942 vfs_mp_count_add_pcpu(mpcpu, writeopcount, 1); 1943 vfs_op_thread_exit(mp, mpcpu); 1944 return (0); 1945 } 1946 1947 if (mplocked) 1948 mtx_assert(MNT_MTX(mp), MA_OWNED); 1949 else 1950 MNT_ILOCK(mp); 1951 1952 error = 0; 1953 1954 /* 1955 * Check on status of suspension. 1956 */ 1957 if ((curthread->td_pflags & TDP_IGNSUSP) == 0 || 1958 mp->mnt_susp_owner != curthread) { 1959 mflags = 0; 1960 if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) { 1961 if (flags & V_PCATCH) 1962 mflags |= PCATCH; 1963 } 1964 mflags |= (PUSER - 1); 1965 while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) { 1966 if ((flags & V_NOWAIT) != 0) { 1967 error = EWOULDBLOCK; 1968 goto unlock; 1969 } 1970 error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags, 1971 "suspfs", 0); 1972 if (error != 0) 1973 goto unlock; 1974 } 1975 } 1976 if ((flags & V_XSLEEP) != 0) 1977 goto unlock; 1978 mp->mnt_writeopcount++; 1979 unlock: 1980 if (error != 0 || (flags & V_XSLEEP) != 0) 1981 MNT_REL(mp); 1982 MNT_IUNLOCK(mp); 1983 return (error); 1984 } 1985 1986 int 1987 vn_start_write(struct vnode *vp, struct mount **mpp, int flags) 1988 { 1989 struct mount *mp; 1990 int error; 1991 1992 KASSERT((flags & ~V_VALID_FLAGS) == 0, 1993 ("%s: invalid flags passed %d\n", __func__, flags)); 1994 1995 error = 0; 1996 /* 1997 * If a vnode is provided, get and return the mount point that 1998 * to which it will write. 1999 */ 2000 if (vp != NULL) { 2001 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) { 2002 *mpp = NULL; 2003 if (error != EOPNOTSUPP) 2004 return (error); 2005 return (0); 2006 } 2007 } 2008 if ((mp = *mpp) == NULL) 2009 return (0); 2010 2011 /* 2012 * VOP_GETWRITEMOUNT() returns with the mp refcount held through 2013 * a vfs_ref(). 2014 * As long as a vnode is not provided we need to acquire a 2015 * refcount for the provided mountpoint too, in order to 2016 * emulate a vfs_ref(). 2017 */ 2018 if (vp == NULL) 2019 vfs_ref(mp); 2020 2021 error = vn_start_write_refed(mp, flags, false); 2022 if (error != 0 && (flags & V_NOWAIT) == 0) 2023 *mpp = NULL; 2024 return (error); 2025 } 2026 2027 /* 2028 * Secondary suspension. Used by operations such as vop_inactive 2029 * routines that are needed by the higher level functions. These 2030 * are allowed to proceed until all the higher level functions have 2031 * completed (indicated by mnt_writeopcount dropping to zero). At that 2032 * time, these operations are halted until the suspension is over. 2033 */ 2034 int 2035 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags) 2036 { 2037 struct mount *mp; 2038 int error, mflags; 2039 2040 KASSERT((flags & (~V_VALID_FLAGS | V_XSLEEP)) == 0, 2041 ("%s: invalid flags passed %d\n", __func__, flags)); 2042 2043 retry: 2044 if (vp != NULL) { 2045 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) { 2046 *mpp = NULL; 2047 if (error != EOPNOTSUPP) 2048 return (error); 2049 return (0); 2050 } 2051 } 2052 /* 2053 * If we are not suspended or have not yet reached suspended 2054 * mode, then let the operation proceed. 2055 */ 2056 if ((mp = *mpp) == NULL) 2057 return (0); 2058 2059 /* 2060 * VOP_GETWRITEMOUNT() returns with the mp refcount held through 2061 * a vfs_ref(). 2062 * As long as a vnode is not provided we need to acquire a 2063 * refcount for the provided mountpoint too, in order to 2064 * emulate a vfs_ref(). 2065 */ 2066 MNT_ILOCK(mp); 2067 if (vp == NULL) 2068 MNT_REF(mp); 2069 if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) { 2070 mp->mnt_secondary_writes++; 2071 mp->mnt_secondary_accwrites++; 2072 MNT_IUNLOCK(mp); 2073 return (0); 2074 } 2075 if ((flags & V_NOWAIT) != 0) { 2076 MNT_REL(mp); 2077 MNT_IUNLOCK(mp); 2078 *mpp = NULL; 2079 return (EWOULDBLOCK); 2080 } 2081 /* 2082 * Wait for the suspension to finish. 2083 */ 2084 mflags = 0; 2085 if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) { 2086 if ((flags & V_PCATCH) != 0) 2087 mflags |= PCATCH; 2088 } 2089 mflags |= (PUSER - 1) | PDROP; 2090 error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags, "suspfs", 0); 2091 vfs_rel(mp); 2092 if (error == 0) 2093 goto retry; 2094 *mpp = NULL; 2095 return (error); 2096 } 2097 2098 /* 2099 * Filesystem write operation has completed. If we are suspending and this 2100 * operation is the last one, notify the suspender that the suspension is 2101 * now in effect. 2102 */ 2103 void 2104 vn_finished_write(struct mount *mp) 2105 { 2106 struct mount_pcpu *mpcpu; 2107 int c; 2108 2109 if (mp == NULL) 2110 return; 2111 2112 if (vfs_op_thread_enter(mp, mpcpu)) { 2113 vfs_mp_count_sub_pcpu(mpcpu, writeopcount, 1); 2114 vfs_mp_count_sub_pcpu(mpcpu, ref, 1); 2115 vfs_op_thread_exit(mp, mpcpu); 2116 return; 2117 } 2118 2119 MNT_ILOCK(mp); 2120 vfs_assert_mount_counters(mp); 2121 MNT_REL(mp); 2122 c = --mp->mnt_writeopcount; 2123 if (mp->mnt_vfs_ops == 0) { 2124 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0); 2125 MNT_IUNLOCK(mp); 2126 return; 2127 } 2128 if (c < 0) 2129 vfs_dump_mount_counters(mp); 2130 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && c == 0) 2131 wakeup(&mp->mnt_writeopcount); 2132 MNT_IUNLOCK(mp); 2133 } 2134 2135 /* 2136 * Filesystem secondary write operation has completed. If we are 2137 * suspending and this operation is the last one, notify the suspender 2138 * that the suspension is now in effect. 2139 */ 2140 void 2141 vn_finished_secondary_write(struct mount *mp) 2142 { 2143 if (mp == NULL) 2144 return; 2145 MNT_ILOCK(mp); 2146 MNT_REL(mp); 2147 mp->mnt_secondary_writes--; 2148 if (mp->mnt_secondary_writes < 0) 2149 panic("vn_finished_secondary_write: neg cnt"); 2150 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && 2151 mp->mnt_secondary_writes <= 0) 2152 wakeup(&mp->mnt_secondary_writes); 2153 MNT_IUNLOCK(mp); 2154 } 2155 2156 /* 2157 * Request a filesystem to suspend write operations. 2158 */ 2159 int 2160 vfs_write_suspend(struct mount *mp, int flags) 2161 { 2162 int error; 2163 2164 vfs_op_enter(mp); 2165 2166 MNT_ILOCK(mp); 2167 vfs_assert_mount_counters(mp); 2168 if (mp->mnt_susp_owner == curthread) { 2169 vfs_op_exit_locked(mp); 2170 MNT_IUNLOCK(mp); 2171 return (EALREADY); 2172 } 2173 while (mp->mnt_kern_flag & MNTK_SUSPEND) 2174 msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0); 2175 2176 /* 2177 * Unmount holds a write reference on the mount point. If we 2178 * own busy reference and drain for writers, we deadlock with 2179 * the reference draining in the unmount path. Callers of 2180 * vfs_write_suspend() must specify VS_SKIP_UNMOUNT if 2181 * vfs_busy() reference is owned and caller is not in the 2182 * unmount context. 2183 */ 2184 if ((flags & VS_SKIP_UNMOUNT) != 0 && 2185 (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) { 2186 vfs_op_exit_locked(mp); 2187 MNT_IUNLOCK(mp); 2188 return (EBUSY); 2189 } 2190 2191 mp->mnt_kern_flag |= MNTK_SUSPEND; 2192 mp->mnt_susp_owner = curthread; 2193 if (mp->mnt_writeopcount > 0) 2194 (void) msleep(&mp->mnt_writeopcount, 2195 MNT_MTX(mp), (PUSER - 1)|PDROP, "suspwt", 0); 2196 else 2197 MNT_IUNLOCK(mp); 2198 if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0) { 2199 vfs_write_resume(mp, 0); 2200 /* vfs_write_resume does vfs_op_exit() for us */ 2201 } 2202 return (error); 2203 } 2204 2205 /* 2206 * Request a filesystem to resume write operations. 2207 */ 2208 void 2209 vfs_write_resume(struct mount *mp, int flags) 2210 { 2211 2212 MNT_ILOCK(mp); 2213 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) { 2214 KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner")); 2215 mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 | 2216 MNTK_SUSPENDED); 2217 mp->mnt_susp_owner = NULL; 2218 wakeup(&mp->mnt_writeopcount); 2219 wakeup(&mp->mnt_flag); 2220 curthread->td_pflags &= ~TDP_IGNSUSP; 2221 if ((flags & VR_START_WRITE) != 0) { 2222 MNT_REF(mp); 2223 mp->mnt_writeopcount++; 2224 } 2225 MNT_IUNLOCK(mp); 2226 if ((flags & VR_NO_SUSPCLR) == 0) 2227 VFS_SUSP_CLEAN(mp); 2228 vfs_op_exit(mp); 2229 } else if ((flags & VR_START_WRITE) != 0) { 2230 MNT_REF(mp); 2231 vn_start_write_refed(mp, 0, true); 2232 } else { 2233 MNT_IUNLOCK(mp); 2234 } 2235 } 2236 2237 /* 2238 * Helper loop around vfs_write_suspend() for filesystem unmount VFS 2239 * methods. 2240 */ 2241 int 2242 vfs_write_suspend_umnt(struct mount *mp) 2243 { 2244 int error; 2245 2246 KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0, 2247 ("vfs_write_suspend_umnt: recursed")); 2248 2249 /* dounmount() already called vn_start_write(). */ 2250 for (;;) { 2251 vn_finished_write(mp); 2252 error = vfs_write_suspend(mp, 0); 2253 if (error != 0) { 2254 vn_start_write(NULL, &mp, V_WAIT); 2255 return (error); 2256 } 2257 MNT_ILOCK(mp); 2258 if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0) 2259 break; 2260 MNT_IUNLOCK(mp); 2261 vn_start_write(NULL, &mp, V_WAIT); 2262 } 2263 mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2); 2264 wakeup(&mp->mnt_flag); 2265 MNT_IUNLOCK(mp); 2266 curthread->td_pflags |= TDP_IGNSUSP; 2267 return (0); 2268 } 2269 2270 /* 2271 * Implement kqueues for files by translating it to vnode operation. 2272 */ 2273 static int 2274 vn_kqfilter(struct file *fp, struct knote *kn) 2275 { 2276 2277 return (VOP_KQFILTER(fp->f_vnode, kn)); 2278 } 2279 2280 int 2281 vn_kqfilter_opath(struct file *fp, struct knote *kn) 2282 { 2283 if ((fp->f_flag & FKQALLOWED) == 0) 2284 return (EBADF); 2285 return (vn_kqfilter(fp, kn)); 2286 } 2287 2288 /* 2289 * Simplified in-kernel wrapper calls for extended attribute access. 2290 * Both calls pass in a NULL credential, authorizing as "kernel" access. 2291 * Set IO_NODELOCKED in ioflg if the vnode is already locked. 2292 */ 2293 int 2294 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace, 2295 const char *attrname, int *buflen, char *buf, struct thread *td) 2296 { 2297 struct uio auio; 2298 struct iovec iov; 2299 int error; 2300 2301 iov.iov_len = *buflen; 2302 iov.iov_base = buf; 2303 2304 auio.uio_iov = &iov; 2305 auio.uio_iovcnt = 1; 2306 auio.uio_rw = UIO_READ; 2307 auio.uio_segflg = UIO_SYSSPACE; 2308 auio.uio_td = td; 2309 auio.uio_offset = 0; 2310 auio.uio_resid = *buflen; 2311 2312 if ((ioflg & IO_NODELOCKED) == 0) 2313 vn_lock(vp, LK_SHARED | LK_RETRY); 2314 2315 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held"); 2316 2317 /* authorize attribute retrieval as kernel */ 2318 error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL, 2319 td); 2320 2321 if ((ioflg & IO_NODELOCKED) == 0) 2322 VOP_UNLOCK(vp); 2323 2324 if (error == 0) { 2325 *buflen = *buflen - auio.uio_resid; 2326 } 2327 2328 return (error); 2329 } 2330 2331 /* 2332 * XXX failure mode if partially written? 2333 */ 2334 int 2335 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace, 2336 const char *attrname, int buflen, char *buf, struct thread *td) 2337 { 2338 struct uio auio; 2339 struct iovec iov; 2340 struct mount *mp; 2341 int error; 2342 2343 iov.iov_len = buflen; 2344 iov.iov_base = buf; 2345 2346 auio.uio_iov = &iov; 2347 auio.uio_iovcnt = 1; 2348 auio.uio_rw = UIO_WRITE; 2349 auio.uio_segflg = UIO_SYSSPACE; 2350 auio.uio_td = td; 2351 auio.uio_offset = 0; 2352 auio.uio_resid = buflen; 2353 2354 if ((ioflg & IO_NODELOCKED) == 0) { 2355 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0) 2356 return (error); 2357 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY); 2358 } 2359 2360 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held"); 2361 2362 /* authorize attribute setting as kernel */ 2363 error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td); 2364 2365 if ((ioflg & IO_NODELOCKED) == 0) { 2366 vn_finished_write(mp); 2367 VOP_UNLOCK(vp); 2368 } 2369 2370 return (error); 2371 } 2372 2373 int 2374 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace, 2375 const char *attrname, struct thread *td) 2376 { 2377 struct mount *mp; 2378 int error; 2379 2380 if ((ioflg & IO_NODELOCKED) == 0) { 2381 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0) 2382 return (error); 2383 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY); 2384 } 2385 2386 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held"); 2387 2388 /* authorize attribute removal as kernel */ 2389 error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td); 2390 if (error == EOPNOTSUPP) 2391 error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL, 2392 NULL, td); 2393 2394 if ((ioflg & IO_NODELOCKED) == 0) { 2395 vn_finished_write(mp); 2396 VOP_UNLOCK(vp); 2397 } 2398 2399 return (error); 2400 } 2401 2402 static int 2403 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags, 2404 struct vnode **rvp) 2405 { 2406 2407 return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp)); 2408 } 2409 2410 int 2411 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp) 2412 { 2413 2414 return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino, 2415 lkflags, rvp)); 2416 } 2417 2418 int 2419 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg, 2420 int lkflags, struct vnode **rvp) 2421 { 2422 struct mount *mp; 2423 int ltype, error; 2424 2425 ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get"); 2426 mp = vp->v_mount; 2427 ltype = VOP_ISLOCKED(vp); 2428 KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED, 2429 ("vn_vget_ino: vp not locked")); 2430 error = vfs_busy(mp, MBF_NOWAIT); 2431 if (error != 0) { 2432 vfs_ref(mp); 2433 VOP_UNLOCK(vp); 2434 error = vfs_busy(mp, 0); 2435 vn_lock(vp, ltype | LK_RETRY); 2436 vfs_rel(mp); 2437 if (error != 0) 2438 return (ENOENT); 2439 if (VN_IS_DOOMED(vp)) { 2440 vfs_unbusy(mp); 2441 return (ENOENT); 2442 } 2443 } 2444 VOP_UNLOCK(vp); 2445 error = alloc(mp, alloc_arg, lkflags, rvp); 2446 vfs_unbusy(mp); 2447 if (error != 0 || *rvp != vp) 2448 vn_lock(vp, ltype | LK_RETRY); 2449 if (VN_IS_DOOMED(vp)) { 2450 if (error == 0) { 2451 if (*rvp == vp) 2452 vunref(vp); 2453 else 2454 vput(*rvp); 2455 } 2456 error = ENOENT; 2457 } 2458 return (error); 2459 } 2460 2461 static void 2462 vn_send_sigxfsz(struct proc *p) 2463 { 2464 PROC_LOCK(p); 2465 kern_psignal(p, SIGXFSZ); 2466 PROC_UNLOCK(p); 2467 } 2468 2469 int 2470 vn_rlimit_trunc(u_quad_t size, struct thread *td) 2471 { 2472 if (size <= lim_cur(td, RLIMIT_FSIZE)) 2473 return (0); 2474 vn_send_sigxfsz(td->td_proc); 2475 return (EFBIG); 2476 } 2477 2478 static int 2479 vn_rlimit_fsizex1(const struct vnode *vp, struct uio *uio, off_t maxfsz, 2480 bool adj, struct thread *td) 2481 { 2482 off_t lim; 2483 bool ktr_write; 2484 2485 if (vp->v_type != VREG) 2486 return (0); 2487 2488 /* 2489 * Handle file system maximum file size. 2490 */ 2491 if (maxfsz != 0 && uio->uio_offset + uio->uio_resid > maxfsz) { 2492 if (!adj || uio->uio_offset >= maxfsz) 2493 return (EFBIG); 2494 uio->uio_resid = maxfsz - uio->uio_offset; 2495 } 2496 2497 /* 2498 * This is kernel write (e.g. vnode_pager) or accounting 2499 * write, ignore limit. 2500 */ 2501 if (td == NULL || (td->td_pflags2 & TDP2_ACCT) != 0) 2502 return (0); 2503 2504 /* 2505 * Calculate file size limit. 2506 */ 2507 ktr_write = (td->td_pflags & TDP_INKTRACE) != 0; 2508 lim = __predict_false(ktr_write) ? td->td_ktr_io_lim : 2509 lim_cur(td, RLIMIT_FSIZE); 2510 2511 /* 2512 * Is the limit reached? 2513 */ 2514 if (__predict_true((uoff_t)uio->uio_offset + uio->uio_resid <= lim)) 2515 return (0); 2516 2517 /* 2518 * Prepared filesystems can handle writes truncated to the 2519 * file size limit. 2520 */ 2521 if (adj && (uoff_t)uio->uio_offset < lim) { 2522 uio->uio_resid = lim - (uoff_t)uio->uio_offset; 2523 return (0); 2524 } 2525 2526 if (!ktr_write || ktr_filesize_limit_signal) 2527 vn_send_sigxfsz(td->td_proc); 2528 return (EFBIG); 2529 } 2530 2531 /* 2532 * Helper for VOP_WRITE() implementations, the common code to 2533 * handle maximum supported file size on the filesystem, and 2534 * RLIMIT_FSIZE, except for special writes from accounting subsystem 2535 * and ktrace. 2536 * 2537 * For maximum file size (maxfsz argument): 2538 * - return EFBIG if uio_offset is beyond it 2539 * - otherwise, clamp uio_resid if write would extend file beyond maxfsz. 2540 * 2541 * For RLIMIT_FSIZE: 2542 * - return EFBIG and send SIGXFSZ if uio_offset is beyond the limit 2543 * - otherwise, clamp uio_resid if write would extend file beyond limit. 2544 * 2545 * If clamping occured, the adjustment for uio_resid is stored in 2546 * *resid_adj, to be re-applied by vn_rlimit_fsizex_res() on return 2547 * from the VOP. 2548 */ 2549 int 2550 vn_rlimit_fsizex(const struct vnode *vp, struct uio *uio, off_t maxfsz, 2551 ssize_t *resid_adj, struct thread *td) 2552 { 2553 ssize_t resid_orig; 2554 int error; 2555 bool adj; 2556 2557 resid_orig = uio->uio_resid; 2558 adj = resid_adj != NULL; 2559 error = vn_rlimit_fsizex1(vp, uio, maxfsz, adj, td); 2560 if (adj) 2561 *resid_adj = resid_orig - uio->uio_resid; 2562 return (error); 2563 } 2564 2565 void 2566 vn_rlimit_fsizex_res(struct uio *uio, ssize_t resid_adj) 2567 { 2568 uio->uio_resid += resid_adj; 2569 } 2570 2571 int 2572 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio, 2573 struct thread *td) 2574 { 2575 return (vn_rlimit_fsizex(vp, __DECONST(struct uio *, uio), 0, NULL, 2576 td)); 2577 } 2578 2579 int 2580 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred, 2581 struct thread *td) 2582 { 2583 struct vnode *vp; 2584 2585 vp = fp->f_vnode; 2586 #ifdef AUDIT 2587 vn_lock(vp, LK_SHARED | LK_RETRY); 2588 AUDIT_ARG_VNODE1(vp); 2589 VOP_UNLOCK(vp); 2590 #endif 2591 return (setfmode(td, active_cred, vp, mode)); 2592 } 2593 2594 int 2595 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred, 2596 struct thread *td) 2597 { 2598 struct vnode *vp; 2599 2600 vp = fp->f_vnode; 2601 #ifdef AUDIT 2602 vn_lock(vp, LK_SHARED | LK_RETRY); 2603 AUDIT_ARG_VNODE1(vp); 2604 VOP_UNLOCK(vp); 2605 #endif 2606 return (setfown(td, active_cred, vp, uid, gid)); 2607 } 2608 2609 /* 2610 * Remove pages in the range ["start", "end") from the vnode's VM object. If 2611 * "end" is 0, then the range extends to the end of the object. 2612 */ 2613 void 2614 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end) 2615 { 2616 vm_object_t object; 2617 2618 if ((object = vp->v_object) == NULL) 2619 return; 2620 VM_OBJECT_WLOCK(object); 2621 vm_object_page_remove(object, start, end, 0); 2622 VM_OBJECT_WUNLOCK(object); 2623 } 2624 2625 /* 2626 * Like vn_pages_remove(), but skips invalid pages, which by definition are not 2627 * mapped into any process' address space. Filesystems may use this in 2628 * preference to vn_pages_remove() to avoid blocking on pages busied in 2629 * preparation for a VOP_GETPAGES. 2630 */ 2631 void 2632 vn_pages_remove_valid(struct vnode *vp, vm_pindex_t start, vm_pindex_t end) 2633 { 2634 vm_object_t object; 2635 2636 if ((object = vp->v_object) == NULL) 2637 return; 2638 VM_OBJECT_WLOCK(object); 2639 vm_object_page_remove(object, start, end, OBJPR_VALIDONLY); 2640 VM_OBJECT_WUNLOCK(object); 2641 } 2642 2643 int 2644 vn_bmap_seekhole_locked(struct vnode *vp, u_long cmd, off_t *off, 2645 struct ucred *cred) 2646 { 2647 off_t size; 2648 daddr_t bn, bnp; 2649 uint64_t bsize; 2650 off_t noff; 2651 int error; 2652 2653 KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA, 2654 ("%s: Wrong command %lu", __func__, cmd)); 2655 ASSERT_VOP_ELOCKED(vp, "vn_bmap_seekhole_locked"); 2656 2657 if (vp->v_type != VREG) { 2658 error = ENOTTY; 2659 goto out; 2660 } 2661 error = vn_getsize_locked(vp, &size, cred); 2662 if (error != 0) 2663 goto out; 2664 noff = *off; 2665 if (noff < 0 || noff >= size) { 2666 error = ENXIO; 2667 goto out; 2668 } 2669 2670 /* See the comment in ufs_bmap_seekdata(). */ 2671 vnode_pager_clean_sync(vp); 2672 2673 bsize = vp->v_mount->mnt_stat.f_iosize; 2674 for (bn = noff / bsize; noff < size; bn++, noff += bsize - 2675 noff % bsize) { 2676 error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL); 2677 if (error == EOPNOTSUPP) { 2678 error = ENOTTY; 2679 goto out; 2680 } 2681 if ((bnp == -1 && cmd == FIOSEEKHOLE) || 2682 (bnp != -1 && cmd == FIOSEEKDATA)) { 2683 noff = bn * bsize; 2684 if (noff < *off) 2685 noff = *off; 2686 goto out; 2687 } 2688 } 2689 if (noff > size) 2690 noff = size; 2691 /* noff == size. There is an implicit hole at the end of file. */ 2692 if (cmd == FIOSEEKDATA) 2693 error = ENXIO; 2694 out: 2695 if (error == 0) 2696 *off = noff; 2697 return (error); 2698 } 2699 2700 int 2701 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred) 2702 { 2703 int error; 2704 2705 KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA, 2706 ("%s: Wrong command %lu", __func__, cmd)); 2707 2708 if (vn_lock(vp, LK_EXCLUSIVE) != 0) 2709 return (EBADF); 2710 error = vn_bmap_seekhole_locked(vp, cmd, off, cred); 2711 VOP_UNLOCK(vp); 2712 return (error); 2713 } 2714 2715 int 2716 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td) 2717 { 2718 struct ucred *cred; 2719 struct vnode *vp; 2720 off_t foffset, fsize, size; 2721 int error, noneg; 2722 2723 cred = td->td_ucred; 2724 vp = fp->f_vnode; 2725 noneg = (vp->v_type != VCHR); 2726 /* 2727 * Try to dodge locking for common case of querying the offset. 2728 */ 2729 if (whence == L_INCR && offset == 0) { 2730 foffset = foffset_read(fp); 2731 if (__predict_false(foffset < 0 && noneg)) { 2732 return (EOVERFLOW); 2733 } 2734 td->td_uretoff.tdu_off = foffset; 2735 return (0); 2736 } 2737 foffset = foffset_lock(fp, 0); 2738 error = 0; 2739 switch (whence) { 2740 case L_INCR: 2741 if (noneg && 2742 (foffset < 0 || 2743 (offset > 0 && foffset > OFF_MAX - offset))) { 2744 error = EOVERFLOW; 2745 break; 2746 } 2747 offset += foffset; 2748 break; 2749 case L_XTND: 2750 error = vn_getsize(vp, &fsize, cred); 2751 if (error != 0) 2752 break; 2753 2754 /* 2755 * If the file references a disk device, then fetch 2756 * the media size and use that to determine the ending 2757 * offset. 2758 */ 2759 if (fsize == 0 && vp->v_type == VCHR && 2760 fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0) 2761 fsize = size; 2762 if (noneg && offset > 0 && fsize > OFF_MAX - offset) { 2763 error = EOVERFLOW; 2764 break; 2765 } 2766 offset += fsize; 2767 break; 2768 case L_SET: 2769 break; 2770 case SEEK_DATA: 2771 error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td); 2772 if (error == ENOTTY) 2773 error = EINVAL; 2774 break; 2775 case SEEK_HOLE: 2776 error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td); 2777 if (error == ENOTTY) 2778 error = EINVAL; 2779 break; 2780 default: 2781 error = EINVAL; 2782 } 2783 if (error == 0 && noneg && offset < 0) 2784 error = EINVAL; 2785 if (error != 0) 2786 goto drop; 2787 VFS_KNOTE_UNLOCKED(vp, 0); 2788 td->td_uretoff.tdu_off = offset; 2789 drop: 2790 foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0); 2791 return (error); 2792 } 2793 2794 int 2795 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred, 2796 struct thread *td) 2797 { 2798 int error; 2799 2800 /* 2801 * Grant permission if the caller is the owner of the file, or 2802 * the super-user, or has ACL_WRITE_ATTRIBUTES permission on 2803 * on the file. If the time pointer is null, then write 2804 * permission on the file is also sufficient. 2805 * 2806 * From NFSv4.1, draft 21, 6.2.1.3.1, Discussion of Mask Attributes: 2807 * A user having ACL_WRITE_DATA or ACL_WRITE_ATTRIBUTES 2808 * will be allowed to set the times [..] to the current 2809 * server time. 2810 */ 2811 error = VOP_ACCESSX(vp, VWRITE_ATTRIBUTES, cred, td); 2812 if (error != 0 && (vap->va_vaflags & VA_UTIMES_NULL) != 0) 2813 error = VOP_ACCESS(vp, VWRITE, cred, td); 2814 return (error); 2815 } 2816 2817 int 2818 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) 2819 { 2820 struct vnode *vp; 2821 int error; 2822 2823 if (fp->f_type == DTYPE_FIFO) 2824 kif->kf_type = KF_TYPE_FIFO; 2825 else 2826 kif->kf_type = KF_TYPE_VNODE; 2827 vp = fp->f_vnode; 2828 vref(vp); 2829 FILEDESC_SUNLOCK(fdp); 2830 error = vn_fill_kinfo_vnode(vp, kif); 2831 vrele(vp); 2832 FILEDESC_SLOCK(fdp); 2833 return (error); 2834 } 2835 2836 static inline void 2837 vn_fill_junk(struct kinfo_file *kif) 2838 { 2839 size_t len, olen; 2840 2841 /* 2842 * Simulate vn_fullpath returning changing values for a given 2843 * vp during e.g. coredump. 2844 */ 2845 len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1; 2846 olen = strlen(kif->kf_path); 2847 if (len < olen) 2848 strcpy(&kif->kf_path[len - 1], "$"); 2849 else 2850 for (; olen < len; olen++) 2851 strcpy(&kif->kf_path[olen], "A"); 2852 } 2853 2854 int 2855 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif) 2856 { 2857 struct vattr va; 2858 char *fullpath, *freepath; 2859 int error; 2860 2861 kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type); 2862 freepath = NULL; 2863 fullpath = "-"; 2864 error = vn_fullpath(vp, &fullpath, &freepath); 2865 if (error == 0) { 2866 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path)); 2867 } 2868 if (freepath != NULL) 2869 free(freepath, M_TEMP); 2870 2871 KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path, 2872 vn_fill_junk(kif); 2873 ); 2874 2875 /* 2876 * Retrieve vnode attributes. 2877 */ 2878 va.va_fsid = VNOVAL; 2879 va.va_rdev = NODEV; 2880 vn_lock(vp, LK_SHARED | LK_RETRY); 2881 error = VOP_GETATTR(vp, &va, curthread->td_ucred); 2882 VOP_UNLOCK(vp); 2883 if (error != 0) 2884 return (error); 2885 if (va.va_fsid != VNOVAL) 2886 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid; 2887 else 2888 kif->kf_un.kf_file.kf_file_fsid = 2889 vp->v_mount->mnt_stat.f_fsid.val[0]; 2890 kif->kf_un.kf_file.kf_file_fsid_freebsd11 = 2891 kif->kf_un.kf_file.kf_file_fsid; /* truncate */ 2892 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid; 2893 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode); 2894 kif->kf_un.kf_file.kf_file_size = va.va_size; 2895 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev; 2896 kif->kf_un.kf_file.kf_file_rdev_freebsd11 = 2897 kif->kf_un.kf_file.kf_file_rdev; /* truncate */ 2898 kif->kf_un.kf_file.kf_file_nlink = va.va_nlink; 2899 return (0); 2900 } 2901 2902 int 2903 vn_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size, 2904 vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff, 2905 struct thread *td) 2906 { 2907 #ifdef HWPMC_HOOKS 2908 struct pmckern_map_in pkm; 2909 #endif 2910 struct mount *mp; 2911 struct vnode *vp; 2912 vm_object_t object; 2913 vm_prot_t maxprot; 2914 boolean_t writecounted; 2915 int error; 2916 2917 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \ 2918 defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) 2919 /* 2920 * POSIX shared-memory objects are defined to have 2921 * kernel persistence, and are not defined to support 2922 * read(2)/write(2) -- or even open(2). Thus, we can 2923 * use MAP_ASYNC to trade on-disk coherence for speed. 2924 * The shm_open(3) library routine turns on the FPOSIXSHM 2925 * flag to request this behavior. 2926 */ 2927 if ((fp->f_flag & FPOSIXSHM) != 0) 2928 flags |= MAP_NOSYNC; 2929 #endif 2930 vp = fp->f_vnode; 2931 2932 /* 2933 * Ensure that file and memory protections are 2934 * compatible. Note that we only worry about 2935 * writability if mapping is shared; in this case, 2936 * current and max prot are dictated by the open file. 2937 * XXX use the vnode instead? Problem is: what 2938 * credentials do we use for determination? What if 2939 * proc does a setuid? 2940 */ 2941 mp = vp->v_mount; 2942 if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) { 2943 maxprot = VM_PROT_NONE; 2944 if ((prot & VM_PROT_EXECUTE) != 0) 2945 return (EACCES); 2946 } else 2947 maxprot = VM_PROT_EXECUTE; 2948 if ((fp->f_flag & FREAD) != 0) 2949 maxprot |= VM_PROT_READ; 2950 else if ((prot & VM_PROT_READ) != 0) 2951 return (EACCES); 2952 2953 /* 2954 * If we are sharing potential changes via MAP_SHARED and we 2955 * are trying to get write permission although we opened it 2956 * without asking for it, bail out. 2957 */ 2958 if ((flags & MAP_SHARED) != 0) { 2959 if ((fp->f_flag & FWRITE) != 0) 2960 maxprot |= VM_PROT_WRITE; 2961 else if ((prot & VM_PROT_WRITE) != 0) 2962 return (EACCES); 2963 } else { 2964 maxprot |= VM_PROT_WRITE; 2965 cap_maxprot |= VM_PROT_WRITE; 2966 } 2967 maxprot &= cap_maxprot; 2968 2969 /* 2970 * For regular files and shared memory, POSIX requires that 2971 * the value of foff be a legitimate offset within the data 2972 * object. In particular, negative offsets are invalid. 2973 * Blocking negative offsets and overflows here avoids 2974 * possible wraparound or user-level access into reserved 2975 * ranges of the data object later. In contrast, POSIX does 2976 * not dictate how offsets are used by device drivers, so in 2977 * the case of a device mapping a negative offset is passed 2978 * on. 2979 */ 2980 if ( 2981 #ifdef _LP64 2982 size > OFF_MAX || 2983 #endif 2984 foff > OFF_MAX - size) 2985 return (EINVAL); 2986 2987 writecounted = FALSE; 2988 error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp, 2989 &foff, &object, &writecounted); 2990 if (error != 0) 2991 return (error); 2992 error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object, 2993 foff, writecounted, td); 2994 if (error != 0) { 2995 /* 2996 * If this mapping was accounted for in the vnode's 2997 * writecount, then undo that now. 2998 */ 2999 if (writecounted) 3000 vm_pager_release_writecount(object, 0, size); 3001 vm_object_deallocate(object); 3002 } 3003 #ifdef HWPMC_HOOKS 3004 /* Inform hwpmc(4) if an executable is being mapped. */ 3005 if (PMC_HOOK_INSTALLED(PMC_FN_MMAP)) { 3006 if ((prot & VM_PROT_EXECUTE) != 0 && error == 0) { 3007 pkm.pm_file = vp; 3008 pkm.pm_address = (uintptr_t) *addr; 3009 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm); 3010 } 3011 } 3012 #endif 3013 return (error); 3014 } 3015 3016 void 3017 vn_fsid(struct vnode *vp, struct vattr *va) 3018 { 3019 fsid_t *f; 3020 3021 f = &vp->v_mount->mnt_stat.f_fsid; 3022 va->va_fsid = (uint32_t)f->val[1]; 3023 va->va_fsid <<= sizeof(f->val[1]) * NBBY; 3024 va->va_fsid += (uint32_t)f->val[0]; 3025 } 3026 3027 int 3028 vn_fsync_buf(struct vnode *vp, int waitfor) 3029 { 3030 struct buf *bp, *nbp; 3031 struct bufobj *bo; 3032 struct mount *mp; 3033 int error, maxretry; 3034 3035 error = 0; 3036 maxretry = 10000; /* large, arbitrarily chosen */ 3037 mp = NULL; 3038 if (vp->v_type == VCHR) { 3039 VI_LOCK(vp); 3040 mp = vp->v_rdev->si_mountpt; 3041 VI_UNLOCK(vp); 3042 } 3043 bo = &vp->v_bufobj; 3044 BO_LOCK(bo); 3045 loop1: 3046 /* 3047 * MARK/SCAN initialization to avoid infinite loops. 3048 */ 3049 TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) { 3050 bp->b_vflags &= ~BV_SCANNED; 3051 bp->b_error = 0; 3052 } 3053 3054 /* 3055 * Flush all dirty buffers associated with a vnode. 3056 */ 3057 loop2: 3058 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) { 3059 if ((bp->b_vflags & BV_SCANNED) != 0) 3060 continue; 3061 bp->b_vflags |= BV_SCANNED; 3062 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) { 3063 if (waitfor != MNT_WAIT) 3064 continue; 3065 if (BUF_LOCK(bp, 3066 LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL, 3067 BO_LOCKPTR(bo)) != 0) { 3068 BO_LOCK(bo); 3069 goto loop1; 3070 } 3071 BO_LOCK(bo); 3072 } 3073 BO_UNLOCK(bo); 3074 KASSERT(bp->b_bufobj == bo, 3075 ("bp %p wrong b_bufobj %p should be %p", 3076 bp, bp->b_bufobj, bo)); 3077 if ((bp->b_flags & B_DELWRI) == 0) 3078 panic("fsync: not dirty"); 3079 if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) { 3080 vfs_bio_awrite(bp); 3081 } else { 3082 bremfree(bp); 3083 bawrite(bp); 3084 } 3085 if (maxretry < 1000) 3086 pause("dirty", hz < 1000 ? 1 : hz / 1000); 3087 BO_LOCK(bo); 3088 goto loop2; 3089 } 3090 3091 /* 3092 * If synchronous the caller expects us to completely resolve all 3093 * dirty buffers in the system. Wait for in-progress I/O to 3094 * complete (which could include background bitmap writes), then 3095 * retry if dirty blocks still exist. 3096 */ 3097 if (waitfor == MNT_WAIT) { 3098 bufobj_wwait(bo, 0, 0); 3099 if (bo->bo_dirty.bv_cnt > 0) { 3100 /* 3101 * If we are unable to write any of these buffers 3102 * then we fail now rather than trying endlessly 3103 * to write them out. 3104 */ 3105 TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) 3106 if ((error = bp->b_error) != 0) 3107 break; 3108 if ((mp != NULL && mp->mnt_secondary_writes > 0) || 3109 (error == 0 && --maxretry >= 0)) 3110 goto loop1; 3111 if (error == 0) 3112 error = EAGAIN; 3113 } 3114 } 3115 BO_UNLOCK(bo); 3116 if (error != 0) 3117 vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error); 3118 3119 return (error); 3120 } 3121 3122 /* 3123 * Copies a byte range from invp to outvp. Calls VOP_COPY_FILE_RANGE() 3124 * or vn_generic_copy_file_range() after rangelocking the byte ranges, 3125 * to do the actual copy. 3126 * vn_generic_copy_file_range() is factored out, so it can be called 3127 * from a VOP_COPY_FILE_RANGE() call as well, but handles vnodes from 3128 * different file systems. 3129 */ 3130 int 3131 vn_copy_file_range(struct vnode *invp, off_t *inoffp, struct vnode *outvp, 3132 off_t *outoffp, size_t *lenp, unsigned int flags, struct ucred *incred, 3133 struct ucred *outcred, struct thread *fsize_td) 3134 { 3135 struct mount *inmp, *outmp; 3136 struct vnode *invpl, *outvpl; 3137 int error; 3138 size_t len; 3139 uint64_t uval; 3140 3141 invpl = outvpl = NULL; 3142 len = *lenp; 3143 *lenp = 0; /* For error returns. */ 3144 error = 0; 3145 3146 /* Do some sanity checks on the arguments. */ 3147 if (invp->v_type == VDIR || outvp->v_type == VDIR) 3148 error = EISDIR; 3149 else if (*inoffp < 0 || *outoffp < 0 || 3150 invp->v_type != VREG || outvp->v_type != VREG) 3151 error = EINVAL; 3152 if (error != 0) 3153 goto out; 3154 3155 /* Ensure offset + len does not wrap around. */ 3156 uval = *inoffp; 3157 uval += len; 3158 if (uval > INT64_MAX) 3159 len = INT64_MAX - *inoffp; 3160 uval = *outoffp; 3161 uval += len; 3162 if (uval > INT64_MAX) 3163 len = INT64_MAX - *outoffp; 3164 if (len == 0) 3165 goto out; 3166 3167 error = VOP_GETLOWVNODE(invp, &invpl, FREAD); 3168 if (error != 0) 3169 goto out; 3170 error = VOP_GETLOWVNODE(outvp, &outvpl, FWRITE); 3171 if (error != 0) 3172 goto out1; 3173 3174 inmp = invpl->v_mount; 3175 outmp = outvpl->v_mount; 3176 if (inmp == NULL || outmp == NULL) 3177 goto out2; 3178 3179 for (;;) { 3180 error = vfs_busy(inmp, 0); 3181 if (error != 0) 3182 goto out2; 3183 if (inmp == outmp) 3184 break; 3185 error = vfs_busy(outmp, MBF_NOWAIT); 3186 if (error != 0) { 3187 vfs_unbusy(inmp); 3188 error = vfs_busy(outmp, 0); 3189 if (error == 0) { 3190 vfs_unbusy(outmp); 3191 continue; 3192 } 3193 goto out2; 3194 } 3195 break; 3196 } 3197 3198 /* 3199 * If the two vnodes are for the same file system type, call 3200 * VOP_COPY_FILE_RANGE(), otherwise call vn_generic_copy_file_range() 3201 * which can handle copies across multiple file system types. 3202 */ 3203 *lenp = len; 3204 if (inmp == outmp || inmp->mnt_vfc == outmp->mnt_vfc) 3205 error = VOP_COPY_FILE_RANGE(invpl, inoffp, outvpl, outoffp, 3206 lenp, flags, incred, outcred, fsize_td); 3207 else 3208 error = ENOSYS; 3209 if (error == ENOSYS) 3210 error = vn_generic_copy_file_range(invpl, inoffp, outvpl, 3211 outoffp, lenp, flags, incred, outcred, fsize_td); 3212 vfs_unbusy(outmp); 3213 if (inmp != outmp) 3214 vfs_unbusy(inmp); 3215 out2: 3216 if (outvpl != NULL) 3217 vrele(outvpl); 3218 out1: 3219 if (invpl != NULL) 3220 vrele(invpl); 3221 out: 3222 return (error); 3223 } 3224 3225 /* 3226 * Test len bytes of data starting at dat for all bytes == 0. 3227 * Return true if all bytes are zero, false otherwise. 3228 * Expects dat to be well aligned. 3229 */ 3230 static bool 3231 mem_iszero(void *dat, int len) 3232 { 3233 int i; 3234 const u_int *p; 3235 const char *cp; 3236 3237 for (p = dat; len > 0; len -= sizeof(*p), p++) { 3238 if (len >= sizeof(*p)) { 3239 if (*p != 0) 3240 return (false); 3241 } else { 3242 cp = (const char *)p; 3243 for (i = 0; i < len; i++, cp++) 3244 if (*cp != '\0') 3245 return (false); 3246 } 3247 } 3248 return (true); 3249 } 3250 3251 /* 3252 * Look for a hole in the output file and, if found, adjust *outoffp 3253 * and *xferp to skip past the hole. 3254 * *xferp is the entire hole length to be written and xfer2 is how many bytes 3255 * to be written as 0's upon return. 3256 */ 3257 static off_t 3258 vn_skip_hole(struct vnode *outvp, off_t xfer2, off_t *outoffp, off_t *xferp, 3259 off_t *dataoffp, off_t *holeoffp, struct ucred *cred) 3260 { 3261 int error; 3262 off_t delta; 3263 3264 if (*holeoffp == 0 || *holeoffp <= *outoffp) { 3265 *dataoffp = *outoffp; 3266 error = VOP_IOCTL(outvp, FIOSEEKDATA, dataoffp, 0, cred, 3267 curthread); 3268 if (error == 0) { 3269 *holeoffp = *dataoffp; 3270 error = VOP_IOCTL(outvp, FIOSEEKHOLE, holeoffp, 0, cred, 3271 curthread); 3272 } 3273 if (error != 0 || *holeoffp == *dataoffp) { 3274 /* 3275 * Since outvp is unlocked, it may be possible for 3276 * another thread to do a truncate(), lseek(), write() 3277 * creating a hole at startoff between the above 3278 * VOP_IOCTL() calls, if the other thread does not do 3279 * rangelocking. 3280 * If that happens, *holeoffp == *dataoffp and finding 3281 * the hole has failed, so disable vn_skip_hole(). 3282 */ 3283 *holeoffp = -1; /* Disable use of vn_skip_hole(). */ 3284 return (xfer2); 3285 } 3286 KASSERT(*dataoffp >= *outoffp, 3287 ("vn_skip_hole: dataoff=%jd < outoff=%jd", 3288 (intmax_t)*dataoffp, (intmax_t)*outoffp)); 3289 KASSERT(*holeoffp > *dataoffp, 3290 ("vn_skip_hole: holeoff=%jd <= dataoff=%jd", 3291 (intmax_t)*holeoffp, (intmax_t)*dataoffp)); 3292 } 3293 3294 /* 3295 * If there is a hole before the data starts, advance *outoffp and 3296 * *xferp past the hole. 3297 */ 3298 if (*dataoffp > *outoffp) { 3299 delta = *dataoffp - *outoffp; 3300 if (delta >= *xferp) { 3301 /* Entire *xferp is a hole. */ 3302 *outoffp += *xferp; 3303 *xferp = 0; 3304 return (0); 3305 } 3306 *xferp -= delta; 3307 *outoffp += delta; 3308 xfer2 = MIN(xfer2, *xferp); 3309 } 3310 3311 /* 3312 * If a hole starts before the end of this xfer2, reduce this xfer2 so 3313 * that the write ends at the start of the hole. 3314 * *holeoffp should always be greater than *outoffp, but for the 3315 * non-INVARIANTS case, check this to make sure xfer2 remains a sane 3316 * value. 3317 */ 3318 if (*holeoffp > *outoffp && *holeoffp < *outoffp + xfer2) 3319 xfer2 = *holeoffp - *outoffp; 3320 return (xfer2); 3321 } 3322 3323 /* 3324 * Write an xfer sized chunk to outvp in blksize blocks from dat. 3325 * dat is a maximum of blksize in length and can be written repeatedly in 3326 * the chunk. 3327 * If growfile == true, just grow the file via vn_truncate_locked() instead 3328 * of doing actual writes. 3329 * If checkhole == true, a hole is being punched, so skip over any hole 3330 * already in the output file. 3331 */ 3332 static int 3333 vn_write_outvp(struct vnode *outvp, char *dat, off_t outoff, off_t xfer, 3334 u_long blksize, bool growfile, bool checkhole, struct ucred *cred) 3335 { 3336 struct mount *mp; 3337 off_t dataoff, holeoff, xfer2; 3338 int error; 3339 3340 /* 3341 * Loop around doing writes of blksize until write has been completed. 3342 * Lock/unlock on each loop iteration so that a bwillwrite() can be 3343 * done for each iteration, since the xfer argument can be very 3344 * large if there is a large hole to punch in the output file. 3345 */ 3346 error = 0; 3347 holeoff = 0; 3348 do { 3349 xfer2 = MIN(xfer, blksize); 3350 if (checkhole) { 3351 /* 3352 * Punching a hole. Skip writing if there is 3353 * already a hole in the output file. 3354 */ 3355 xfer2 = vn_skip_hole(outvp, xfer2, &outoff, &xfer, 3356 &dataoff, &holeoff, cred); 3357 if (xfer == 0) 3358 break; 3359 if (holeoff < 0) 3360 checkhole = false; 3361 KASSERT(xfer2 > 0, ("vn_write_outvp: xfer2=%jd", 3362 (intmax_t)xfer2)); 3363 } 3364 bwillwrite(); 3365 mp = NULL; 3366 error = vn_start_write(outvp, &mp, V_WAIT); 3367 if (error != 0) 3368 break; 3369 if (growfile) { 3370 error = vn_lock(outvp, LK_EXCLUSIVE); 3371 if (error == 0) { 3372 error = vn_truncate_locked(outvp, outoff + xfer, 3373 false, cred); 3374 VOP_UNLOCK(outvp); 3375 } 3376 } else { 3377 error = vn_lock(outvp, vn_lktype_write(mp, outvp)); 3378 if (error == 0) { 3379 error = vn_rdwr(UIO_WRITE, outvp, dat, xfer2, 3380 outoff, UIO_SYSSPACE, IO_NODELOCKED, 3381 curthread->td_ucred, cred, NULL, curthread); 3382 outoff += xfer2; 3383 xfer -= xfer2; 3384 VOP_UNLOCK(outvp); 3385 } 3386 } 3387 if (mp != NULL) 3388 vn_finished_write(mp); 3389 } while (!growfile && xfer > 0 && error == 0); 3390 return (error); 3391 } 3392 3393 /* 3394 * Copy a byte range of one file to another. This function can handle the 3395 * case where invp and outvp are on different file systems. 3396 * It can also be called by a VOP_COPY_FILE_RANGE() to do the work, if there 3397 * is no better file system specific way to do it. 3398 */ 3399 int 3400 vn_generic_copy_file_range(struct vnode *invp, off_t *inoffp, 3401 struct vnode *outvp, off_t *outoffp, size_t *lenp, unsigned int flags, 3402 struct ucred *incred, struct ucred *outcred, struct thread *fsize_td) 3403 { 3404 struct vattr inva; 3405 struct mount *mp; 3406 off_t startoff, endoff, xfer, xfer2; 3407 u_long blksize; 3408 int error, interrupted; 3409 bool cantseek, readzeros, eof, first, lastblock, holetoeof, sparse; 3410 ssize_t aresid, r = 0; 3411 size_t copylen, len, savlen; 3412 off_t outsize; 3413 char *dat; 3414 long holein, holeout; 3415 struct timespec curts, endts; 3416 3417 holein = holeout = 0; 3418 savlen = len = *lenp; 3419 error = 0; 3420 interrupted = 0; 3421 dat = NULL; 3422 3423 error = vn_lock(invp, LK_SHARED); 3424 if (error != 0) 3425 goto out; 3426 if (VOP_PATHCONF(invp, _PC_MIN_HOLE_SIZE, &holein) != 0) 3427 holein = 0; 3428 error = VOP_GETATTR(invp, &inva, incred); 3429 if (error == 0 && inva.va_size > OFF_MAX) 3430 error = EFBIG; 3431 VOP_UNLOCK(invp); 3432 if (error != 0) 3433 goto out; 3434 3435 /* 3436 * Use va_bytes >= va_size as a hint that the file does not have 3437 * sufficient holes to justify the overhead of doing FIOSEEKHOLE. 3438 * This hint does not work well for file systems doing compression 3439 * and may fail when allocations for extended attributes increases 3440 * the value of va_bytes to >= va_size. 3441 */ 3442 sparse = true; 3443 if (holein != 0 && inva.va_bytes >= inva.va_size) { 3444 holein = 0; 3445 sparse = false; 3446 } 3447 3448 mp = NULL; 3449 error = vn_start_write(outvp, &mp, V_WAIT); 3450 if (error == 0) 3451 error = vn_lock(outvp, LK_EXCLUSIVE); 3452 if (error == 0) { 3453 /* 3454 * If fsize_td != NULL, do a vn_rlimit_fsizex() call, 3455 * now that outvp is locked. 3456 */ 3457 if (fsize_td != NULL) { 3458 struct uio io; 3459 3460 io.uio_offset = *outoffp; 3461 io.uio_resid = len; 3462 error = vn_rlimit_fsizex(outvp, &io, 0, &r, fsize_td); 3463 len = savlen = io.uio_resid; 3464 /* 3465 * No need to call vn_rlimit_fsizex_res before return, 3466 * since the uio is local. 3467 */ 3468 } 3469 if (VOP_PATHCONF(outvp, _PC_MIN_HOLE_SIZE, &holeout) != 0) 3470 holeout = 0; 3471 /* 3472 * Holes that are past EOF do not need to be written as a block 3473 * of zero bytes. So, truncate the output file as far as 3474 * possible and then use size to decide if writing 0 3475 * bytes is necessary in the loop below. 3476 */ 3477 if (error == 0) 3478 error = vn_getsize_locked(outvp, &outsize, outcred); 3479 if (error == 0 && outsize > *outoffp && 3480 *outoffp <= OFF_MAX - len && outsize <= *outoffp + len && 3481 *inoffp < inva.va_size && 3482 *outoffp <= OFF_MAX - (inva.va_size - *inoffp) && 3483 outsize <= *outoffp + (inva.va_size - *inoffp)) { 3484 #ifdef MAC 3485 error = mac_vnode_check_write(curthread->td_ucred, 3486 outcred, outvp); 3487 if (error == 0) 3488 #endif 3489 error = vn_truncate_locked(outvp, *outoffp, 3490 false, outcred); 3491 if (error == 0) 3492 outsize = *outoffp; 3493 } 3494 VOP_UNLOCK(outvp); 3495 } 3496 if (mp != NULL) 3497 vn_finished_write(mp); 3498 if (error != 0) 3499 goto out; 3500 3501 if (sparse && holein == 0 && holeout > 0) { 3502 /* 3503 * For this special case, the input data will be scanned 3504 * for blocks of all 0 bytes. For these blocks, the 3505 * write can be skipped for the output file to create 3506 * an unallocated region. 3507 * Therefore, use the appropriate size for the output file. 3508 */ 3509 blksize = holeout; 3510 if (blksize <= 512) { 3511 /* 3512 * Use f_iosize, since ZFS reports a _PC_MIN_HOLE_SIZE 3513 * of 512, although it actually only creates 3514 * unallocated regions for blocks >= f_iosize. 3515 */ 3516 blksize = outvp->v_mount->mnt_stat.f_iosize; 3517 } 3518 } else { 3519 /* 3520 * Use the larger of the two f_iosize values. If they are 3521 * not the same size, one will normally be an exact multiple of 3522 * the other, since they are both likely to be a power of 2. 3523 */ 3524 blksize = MAX(invp->v_mount->mnt_stat.f_iosize, 3525 outvp->v_mount->mnt_stat.f_iosize); 3526 } 3527 3528 /* Clip to sane limits. */ 3529 if (blksize < 4096) 3530 blksize = 4096; 3531 else if (blksize > maxphys) 3532 blksize = maxphys; 3533 dat = malloc(blksize, M_TEMP, M_WAITOK); 3534 3535 /* 3536 * If VOP_IOCTL(FIOSEEKHOLE) works for invp, use it and FIOSEEKDATA 3537 * to find holes. Otherwise, just scan the read block for all 0s 3538 * in the inner loop where the data copying is done. 3539 * Note that some file systems such as NFSv3, NFSv4.0 and NFSv4.1 may 3540 * support holes on the server, but do not support FIOSEEKHOLE. 3541 * The kernel flag COPY_FILE_RANGE_TIMEO1SEC is used to indicate 3542 * that this function should return after 1second with a partial 3543 * completion. 3544 */ 3545 if ((flags & COPY_FILE_RANGE_TIMEO1SEC) != 0) { 3546 getnanouptime(&endts); 3547 endts.tv_sec++; 3548 } else 3549 timespecclear(&endts); 3550 first = true; 3551 holetoeof = eof = false; 3552 while (len > 0 && error == 0 && !eof && interrupted == 0) { 3553 endoff = 0; /* To shut up compilers. */ 3554 cantseek = true; 3555 startoff = *inoffp; 3556 copylen = len; 3557 3558 /* 3559 * Find the next data area. If there is just a hole to EOF, 3560 * FIOSEEKDATA should fail with ENXIO. 3561 * (I do not know if any file system will report a hole to 3562 * EOF via FIOSEEKHOLE, but I am pretty sure FIOSEEKDATA 3563 * will fail for those file systems.) 3564 * 3565 * For input files that don't support FIOSEEKDATA/FIOSEEKHOLE, 3566 * the code just falls through to the inner copy loop. 3567 */ 3568 error = EINVAL; 3569 if (holein > 0) { 3570 error = VOP_IOCTL(invp, FIOSEEKDATA, &startoff, 0, 3571 incred, curthread); 3572 if (error == ENXIO) { 3573 startoff = endoff = inva.va_size; 3574 eof = holetoeof = true; 3575 error = 0; 3576 } 3577 } 3578 if (error == 0 && !holetoeof) { 3579 endoff = startoff; 3580 error = VOP_IOCTL(invp, FIOSEEKHOLE, &endoff, 0, 3581 incred, curthread); 3582 /* 3583 * Since invp is unlocked, it may be possible for 3584 * another thread to do a truncate(), lseek(), write() 3585 * creating a hole at startoff between the above 3586 * VOP_IOCTL() calls, if the other thread does not do 3587 * rangelocking. 3588 * If that happens, startoff == endoff and finding 3589 * the hole has failed, so set an error. 3590 */ 3591 if (error == 0 && startoff == endoff) 3592 error = EINVAL; /* Any error. Reset to 0. */ 3593 } 3594 if (error == 0) { 3595 if (startoff > *inoffp) { 3596 /* Found hole before data block. */ 3597 xfer = MIN(startoff - *inoffp, len); 3598 if (*outoffp < outsize) { 3599 /* Must write 0s to punch hole. */ 3600 xfer2 = MIN(outsize - *outoffp, 3601 xfer); 3602 memset(dat, 0, MIN(xfer2, blksize)); 3603 error = vn_write_outvp(outvp, dat, 3604 *outoffp, xfer2, blksize, false, 3605 holeout > 0, outcred); 3606 } 3607 3608 if (error == 0 && *outoffp + xfer > 3609 outsize && (xfer == len || holetoeof)) { 3610 /* Grow output file (hole at end). */ 3611 error = vn_write_outvp(outvp, dat, 3612 *outoffp, xfer, blksize, true, 3613 false, outcred); 3614 } 3615 if (error == 0) { 3616 *inoffp += xfer; 3617 *outoffp += xfer; 3618 len -= xfer; 3619 if (len < savlen) { 3620 interrupted = sig_intr(); 3621 if (timespecisset(&endts) && 3622 interrupted == 0) { 3623 getnanouptime(&curts); 3624 if (timespeccmp(&curts, 3625 &endts, >=)) 3626 interrupted = 3627 EINTR; 3628 } 3629 } 3630 } 3631 } 3632 copylen = MIN(len, endoff - startoff); 3633 cantseek = false; 3634 } else { 3635 cantseek = true; 3636 if (!sparse) 3637 cantseek = false; 3638 startoff = *inoffp; 3639 copylen = len; 3640 error = 0; 3641 } 3642 3643 xfer = blksize; 3644 if (cantseek) { 3645 /* 3646 * Set first xfer to end at a block boundary, so that 3647 * holes are more likely detected in the loop below via 3648 * the for all bytes 0 method. 3649 */ 3650 xfer -= (*inoffp % blksize); 3651 } 3652 3653 /* 3654 * Loop copying the data block. If this was our first attempt 3655 * to copy anything, allow a zero-length block so that the VOPs 3656 * get a chance to update metadata, specifically the atime. 3657 */ 3658 while (error == 0 && ((copylen > 0 && !eof) || first) && 3659 interrupted == 0) { 3660 if (copylen < xfer) 3661 xfer = copylen; 3662 first = false; 3663 error = vn_lock(invp, LK_SHARED); 3664 if (error != 0) 3665 goto out; 3666 error = vn_rdwr(UIO_READ, invp, dat, xfer, 3667 startoff, UIO_SYSSPACE, IO_NODELOCKED, 3668 curthread->td_ucred, incred, &aresid, 3669 curthread); 3670 VOP_UNLOCK(invp); 3671 lastblock = false; 3672 if (error == 0 && (xfer == 0 || aresid > 0)) { 3673 /* Stop the copy at EOF on the input file. */ 3674 xfer -= aresid; 3675 eof = true; 3676 lastblock = true; 3677 } 3678 if (error == 0) { 3679 /* 3680 * Skip the write for holes past the initial EOF 3681 * of the output file, unless this is the last 3682 * write of the output file at EOF. 3683 */ 3684 readzeros = cantseek ? mem_iszero(dat, xfer) : 3685 false; 3686 if (xfer == len) 3687 lastblock = true; 3688 if (!cantseek || *outoffp < outsize || 3689 lastblock || !readzeros) 3690 error = vn_write_outvp(outvp, dat, 3691 *outoffp, xfer, blksize, 3692 readzeros && lastblock && 3693 *outoffp >= outsize, false, 3694 outcred); 3695 if (error == 0) { 3696 *inoffp += xfer; 3697 startoff += xfer; 3698 *outoffp += xfer; 3699 copylen -= xfer; 3700 len -= xfer; 3701 if (len < savlen) { 3702 interrupted = sig_intr(); 3703 if (timespecisset(&endts) && 3704 interrupted == 0) { 3705 getnanouptime(&curts); 3706 if (timespeccmp(&curts, 3707 &endts, >=)) 3708 interrupted = 3709 EINTR; 3710 } 3711 } 3712 } 3713 } 3714 xfer = blksize; 3715 } 3716 } 3717 out: 3718 *lenp = savlen - len; 3719 free(dat, M_TEMP); 3720 return (error); 3721 } 3722 3723 static int 3724 vn_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td) 3725 { 3726 struct mount *mp; 3727 struct vnode *vp; 3728 off_t olen, ooffset; 3729 int error; 3730 #ifdef AUDIT 3731 int audited_vnode1 = 0; 3732 #endif 3733 3734 vp = fp->f_vnode; 3735 if (vp->v_type != VREG) 3736 return (ENODEV); 3737 3738 /* Allocating blocks may take a long time, so iterate. */ 3739 for (;;) { 3740 olen = len; 3741 ooffset = offset; 3742 3743 bwillwrite(); 3744 mp = NULL; 3745 error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH); 3746 if (error != 0) 3747 break; 3748 error = vn_lock(vp, LK_EXCLUSIVE); 3749 if (error != 0) { 3750 vn_finished_write(mp); 3751 break; 3752 } 3753 #ifdef AUDIT 3754 if (!audited_vnode1) { 3755 AUDIT_ARG_VNODE1(vp); 3756 audited_vnode1 = 1; 3757 } 3758 #endif 3759 #ifdef MAC 3760 error = mac_vnode_check_write(td->td_ucred, fp->f_cred, vp); 3761 if (error == 0) 3762 #endif 3763 error = VOP_ALLOCATE(vp, &offset, &len, 0, 3764 td->td_ucred); 3765 VOP_UNLOCK(vp); 3766 vn_finished_write(mp); 3767 3768 if (olen + ooffset != offset + len) { 3769 panic("offset + len changed from %jx/%jx to %jx/%jx", 3770 ooffset, olen, offset, len); 3771 } 3772 if (error != 0 || len == 0) 3773 break; 3774 KASSERT(olen > len, ("Iteration did not make progress?")); 3775 maybe_yield(); 3776 } 3777 3778 return (error); 3779 } 3780 3781 static int 3782 vn_deallocate_impl(struct vnode *vp, off_t *offset, off_t *length, int flags, 3783 int ioflag, struct ucred *cred, struct ucred *active_cred, 3784 struct ucred *file_cred) 3785 { 3786 struct mount *mp; 3787 void *rl_cookie; 3788 off_t off, len; 3789 int error; 3790 #ifdef AUDIT 3791 bool audited_vnode1 = false; 3792 #endif 3793 3794 rl_cookie = NULL; 3795 error = 0; 3796 mp = NULL; 3797 off = *offset; 3798 len = *length; 3799 3800 if ((ioflag & (IO_NODELOCKED | IO_RANGELOCKED)) == 0) 3801 rl_cookie = vn_rangelock_wlock(vp, off, off + len); 3802 while (len > 0 && error == 0) { 3803 /* 3804 * Try to deallocate the longest range in one pass. 3805 * In case a pass takes too long to be executed, it returns 3806 * partial result. The residue will be proceeded in the next 3807 * pass. 3808 */ 3809 3810 if ((ioflag & IO_NODELOCKED) == 0) { 3811 bwillwrite(); 3812 if ((error = vn_start_write(vp, &mp, 3813 V_WAIT | V_PCATCH)) != 0) 3814 goto out; 3815 vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY); 3816 } 3817 #ifdef AUDIT 3818 if (!audited_vnode1) { 3819 AUDIT_ARG_VNODE1(vp); 3820 audited_vnode1 = true; 3821 } 3822 #endif 3823 3824 #ifdef MAC 3825 if ((ioflag & IO_NOMACCHECK) == 0) 3826 error = mac_vnode_check_write(active_cred, file_cred, 3827 vp); 3828 #endif 3829 if (error == 0) 3830 error = VOP_DEALLOCATE(vp, &off, &len, flags, ioflag, 3831 cred); 3832 3833 if ((ioflag & IO_NODELOCKED) == 0) { 3834 VOP_UNLOCK(vp); 3835 if (mp != NULL) { 3836 vn_finished_write(mp); 3837 mp = NULL; 3838 } 3839 } 3840 if (error == 0 && len != 0) 3841 maybe_yield(); 3842 } 3843 out: 3844 if (rl_cookie != NULL) 3845 vn_rangelock_unlock(vp, rl_cookie); 3846 *offset = off; 3847 *length = len; 3848 return (error); 3849 } 3850 3851 /* 3852 * This function is supposed to be used in the situations where the deallocation 3853 * is not triggered by a user request. 3854 */ 3855 int 3856 vn_deallocate(struct vnode *vp, off_t *offset, off_t *length, int flags, 3857 int ioflag, struct ucred *active_cred, struct ucred *file_cred) 3858 { 3859 struct ucred *cred; 3860 3861 if (*offset < 0 || *length <= 0 || *length > OFF_MAX - *offset || 3862 flags != 0) 3863 return (EINVAL); 3864 if (vp->v_type != VREG) 3865 return (ENODEV); 3866 3867 cred = file_cred != NOCRED ? file_cred : active_cred; 3868 return (vn_deallocate_impl(vp, offset, length, flags, ioflag, cred, 3869 active_cred, file_cred)); 3870 } 3871 3872 static int 3873 vn_fspacectl(struct file *fp, int cmd, off_t *offset, off_t *length, int flags, 3874 struct ucred *active_cred, struct thread *td) 3875 { 3876 int error; 3877 struct vnode *vp; 3878 int ioflag; 3879 3880 KASSERT(cmd == SPACECTL_DEALLOC, ("vn_fspacectl: Invalid cmd")); 3881 KASSERT((flags & ~SPACECTL_F_SUPPORTED) == 0, 3882 ("vn_fspacectl: non-zero flags")); 3883 KASSERT(*offset >= 0 && *length > 0 && *length <= OFF_MAX - *offset, 3884 ("vn_fspacectl: offset/length overflow or underflow")); 3885 vp = fp->f_vnode; 3886 3887 if (vp->v_type != VREG) 3888 return (ENODEV); 3889 3890 ioflag = get_write_ioflag(fp); 3891 3892 switch (cmd) { 3893 case SPACECTL_DEALLOC: 3894 error = vn_deallocate_impl(vp, offset, length, flags, ioflag, 3895 active_cred, active_cred, fp->f_cred); 3896 break; 3897 default: 3898 panic("vn_fspacectl: unknown cmd %d", cmd); 3899 } 3900 3901 return (error); 3902 } 3903 3904 /* 3905 * Keep this assert as long as sizeof(struct dirent) is used as the maximum 3906 * entry size. 3907 */ 3908 _Static_assert(_GENERIC_MAXDIRSIZ == sizeof(struct dirent), 3909 "'struct dirent' size must be a multiple of its alignment " 3910 "(see _GENERIC_DIRLEN())"); 3911 3912 /* 3913 * Returns successive directory entries through some caller's provided buffer. 3914 * 3915 * This function automatically refills the provided buffer with calls to 3916 * VOP_READDIR() (after MAC permission checks). 3917 * 3918 * 'td' is used for credentials and passed to uiomove(). 'dirbuf' is the 3919 * caller's buffer to fill and 'dirbuflen' its allocated size. 'dirbuf' must 3920 * be properly aligned to access 'struct dirent' structures and 'dirbuflen' 3921 * must be greater than GENERIC_MAXDIRSIZ to avoid VOP_READDIR() returning 3922 * EINVAL (the latter is not a strong guarantee (yet); but EINVAL will always 3923 * be returned if this requirement is not verified). '*dpp' points to the 3924 * current directory entry in the buffer and '*len' contains the remaining 3925 * valid bytes in 'dirbuf' after 'dpp' (including the pointed entry). 3926 * 3927 * At first call (or when restarting the read), '*len' must have been set to 0, 3928 * '*off' to 0 (or any valid start offset) and '*eofflag' to 0. There are no 3929 * more entries as soon as '*len' is 0 after a call that returned 0. Calling 3930 * again this function after such a condition is considered an error and EINVAL 3931 * will be returned. Other possible error codes are those of VOP_READDIR(), 3932 * EINTEGRITY if the returned entries do not pass coherency tests, or EINVAL 3933 * (bad call). All errors are unrecoverable, i.e., the state ('*len', '*off' 3934 * and '*eofflag') must be re-initialized before a subsequent call. On error 3935 * or at end of directory, '*dpp' is reset to NULL. 3936 * 3937 * '*len', '*off' and '*eofflag' are internal state the caller should not 3938 * tamper with except as explained above. '*off' is the next directory offset 3939 * to read from to refill the buffer. '*eofflag' is set to 0 or 1 by the last 3940 * internal call to VOP_READDIR() that returned without error, indicating 3941 * whether it reached the end of the directory, and to 2 by this function after 3942 * all entries have been read. 3943 */ 3944 int 3945 vn_dir_next_dirent(struct vnode *vp, struct thread *td, 3946 char *dirbuf, size_t dirbuflen, 3947 struct dirent **dpp, size_t *len, off_t *off, int *eofflag) 3948 { 3949 struct dirent *dp = NULL; 3950 int reclen; 3951 int error; 3952 struct uio uio; 3953 struct iovec iov; 3954 3955 ASSERT_VOP_LOCKED(vp, "vnode not locked"); 3956 VNASSERT(vp->v_type == VDIR, vp, ("vnode is not a directory")); 3957 MPASS2((uintptr_t)dirbuf < (uintptr_t)dirbuf + dirbuflen, 3958 "Address space overflow"); 3959 3960 if (__predict_false(dirbuflen < GENERIC_MAXDIRSIZ)) { 3961 /* Don't take any chances in this case */ 3962 error = EINVAL; 3963 goto out; 3964 } 3965 3966 if (*len != 0) { 3967 dp = *dpp; 3968 3969 /* 3970 * The caller continued to call us after an error (we set dp to 3971 * NULL in a previous iteration). Bail out right now. 3972 */ 3973 if (__predict_false(dp == NULL)) 3974 return (EINVAL); 3975 3976 MPASS(*len <= dirbuflen); 3977 MPASS2((uintptr_t)dirbuf <= (uintptr_t)dp && 3978 (uintptr_t)dp + *len <= (uintptr_t)dirbuf + dirbuflen, 3979 "Filled range not inside buffer"); 3980 3981 reclen = dp->d_reclen; 3982 if (reclen >= *len) { 3983 /* End of buffer reached */ 3984 *len = 0; 3985 } else { 3986 dp = (struct dirent *)((char *)dp + reclen); 3987 *len -= reclen; 3988 } 3989 } 3990 3991 if (*len == 0) { 3992 dp = NULL; 3993 3994 /* Have to refill. */ 3995 switch (*eofflag) { 3996 case 0: 3997 break; 3998 3999 case 1: 4000 /* Nothing more to read. */ 4001 *eofflag = 2; /* Remember the caller reached EOF. */ 4002 goto success; 4003 4004 default: 4005 /* The caller didn't test for EOF. */ 4006 error = EINVAL; 4007 goto out; 4008 } 4009 4010 iov.iov_base = dirbuf; 4011 iov.iov_len = dirbuflen; 4012 4013 uio.uio_iov = &iov; 4014 uio.uio_iovcnt = 1; 4015 uio.uio_offset = *off; 4016 uio.uio_resid = dirbuflen; 4017 uio.uio_segflg = UIO_SYSSPACE; 4018 uio.uio_rw = UIO_READ; 4019 uio.uio_td = td; 4020 4021 #ifdef MAC 4022 error = mac_vnode_check_readdir(td->td_ucred, vp); 4023 if (error == 0) 4024 #endif 4025 error = VOP_READDIR(vp, &uio, td->td_ucred, eofflag, 4026 NULL, NULL); 4027 if (error != 0) 4028 goto out; 4029 4030 *len = dirbuflen - uio.uio_resid; 4031 *off = uio.uio_offset; 4032 4033 if (*len == 0) { 4034 /* Sanity check on INVARIANTS. */ 4035 MPASS(*eofflag != 0); 4036 *eofflag = 1; 4037 goto success; 4038 } 4039 4040 /* 4041 * Normalize the flag returned by VOP_READDIR(), since we use 2 4042 * as a sentinel value. 4043 */ 4044 if (*eofflag != 0) 4045 *eofflag = 1; 4046 4047 dp = (struct dirent *)dirbuf; 4048 } 4049 4050 if (__predict_false(*len < GENERIC_MINDIRSIZ || 4051 dp->d_reclen < GENERIC_MINDIRSIZ)) { 4052 error = EINTEGRITY; 4053 dp = NULL; 4054 goto out; 4055 } 4056 4057 success: 4058 error = 0; 4059 out: 4060 *dpp = dp; 4061 return (error); 4062 } 4063 4064 /* 4065 * Checks whether a directory is empty or not. 4066 * 4067 * If the directory is empty, returns 0, and if it is not, ENOTEMPTY. Other 4068 * values are genuine errors preventing the check. 4069 */ 4070 int 4071 vn_dir_check_empty(struct vnode *vp) 4072 { 4073 struct thread *const td = curthread; 4074 char *dirbuf; 4075 size_t dirbuflen, len; 4076 off_t off; 4077 int eofflag, error; 4078 struct dirent *dp; 4079 struct vattr va; 4080 4081 ASSERT_VOP_LOCKED(vp, "vfs_emptydir"); 4082 VNPASS(vp->v_type == VDIR, vp); 4083 4084 error = VOP_GETATTR(vp, &va, td->td_ucred); 4085 if (error != 0) 4086 return (error); 4087 4088 dirbuflen = max(DEV_BSIZE, GENERIC_MAXDIRSIZ); 4089 if (dirbuflen < va.va_blocksize) 4090 dirbuflen = va.va_blocksize; 4091 dirbuf = malloc(dirbuflen, M_TEMP, M_WAITOK); 4092 4093 len = 0; 4094 off = 0; 4095 eofflag = 0; 4096 4097 for (;;) { 4098 error = vn_dir_next_dirent(vp, td, dirbuf, dirbuflen, 4099 &dp, &len, &off, &eofflag); 4100 if (error != 0) 4101 goto end; 4102 4103 if (len == 0) { 4104 /* EOF */ 4105 error = 0; 4106 goto end; 4107 } 4108 4109 /* 4110 * Skip whiteouts. Unionfs operates on filesystems only and 4111 * not on hierarchies, so these whiteouts would be shadowed on 4112 * the system hierarchy but not for a union using the 4113 * filesystem of their directories as the upper layer. 4114 * Additionally, unionfs currently transparently exposes 4115 * union-specific metadata of its upper layer, meaning that 4116 * whiteouts can be seen through the union view in empty 4117 * directories. Taking into account these whiteouts would then 4118 * prevent mounting another filesystem on such effectively 4119 * empty directories. 4120 */ 4121 if (dp->d_type == DT_WHT) 4122 continue; 4123 4124 /* 4125 * Any file in the directory which is not '.' or '..' indicates 4126 * the directory is not empty. 4127 */ 4128 switch (dp->d_namlen) { 4129 case 2: 4130 if (dp->d_name[1] != '.') { 4131 /* Can't be '..' (nor '.') */ 4132 error = ENOTEMPTY; 4133 goto end; 4134 } 4135 /* FALLTHROUGH */ 4136 case 1: 4137 if (dp->d_name[0] != '.') { 4138 /* Can't be '..' nor '.' */ 4139 error = ENOTEMPTY; 4140 goto end; 4141 } 4142 break; 4143 4144 default: 4145 error = ENOTEMPTY; 4146 goto end; 4147 } 4148 } 4149 4150 end: 4151 free(dirbuf, M_TEMP); 4152 return (error); 4153 } 4154 4155 4156 static u_long vn_lock_pair_pause_cnt; 4157 SYSCTL_ULONG(_debug, OID_AUTO, vn_lock_pair_pause, CTLFLAG_RD, 4158 &vn_lock_pair_pause_cnt, 0, 4159 "Count of vn_lock_pair deadlocks"); 4160 4161 u_int vn_lock_pair_pause_max; 4162 SYSCTL_UINT(_debug, OID_AUTO, vn_lock_pair_pause_max, CTLFLAG_RW, 4163 &vn_lock_pair_pause_max, 0, 4164 "Max ticks for vn_lock_pair deadlock avoidance sleep"); 4165 4166 static void 4167 vn_lock_pair_pause(const char *wmesg) 4168 { 4169 atomic_add_long(&vn_lock_pair_pause_cnt, 1); 4170 pause(wmesg, prng32_bounded(vn_lock_pair_pause_max)); 4171 } 4172 4173 /* 4174 * Lock pair of (possibly same) vnodes vp1, vp2, avoiding lock order 4175 * reversal. vp1_locked indicates whether vp1 is locked; if not, vp1 4176 * must be unlocked. Same for vp2 and vp2_locked. One of the vnodes 4177 * can be NULL. 4178 * 4179 * The function returns with both vnodes exclusively or shared locked, 4180 * according to corresponding lkflags, and guarantees that it does not 4181 * create lock order reversal with other threads during its execution. 4182 * Both vnodes could be unlocked temporary (and reclaimed). 4183 * 4184 * If requesting shared locking, locked vnode lock must not be recursed. 4185 * 4186 * Only one of LK_SHARED and LK_EXCLUSIVE must be specified. 4187 * LK_NODDLKTREAT can be optionally passed. 4188 * 4189 * If vp1 == vp2, only one, most exclusive, lock is obtained on it. 4190 */ 4191 void 4192 vn_lock_pair(struct vnode *vp1, bool vp1_locked, int lkflags1, 4193 struct vnode *vp2, bool vp2_locked, int lkflags2) 4194 { 4195 int error, locked1; 4196 4197 MPASS((((lkflags1 & LK_SHARED) != 0) ^ ((lkflags1 & LK_EXCLUSIVE) != 0)) || 4198 (vp1 == NULL && lkflags1 == 0)); 4199 MPASS((lkflags1 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0); 4200 MPASS((((lkflags2 & LK_SHARED) != 0) ^ ((lkflags2 & LK_EXCLUSIVE) != 0)) || 4201 (vp2 == NULL && lkflags2 == 0)); 4202 MPASS((lkflags2 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0); 4203 4204 if (vp1 == NULL && vp2 == NULL) 4205 return; 4206 4207 if (vp1 == vp2) { 4208 MPASS(vp1_locked == vp2_locked); 4209 4210 /* Select the most exclusive mode for lock. */ 4211 if ((lkflags1 & LK_TYPE_MASK) != (lkflags2 & LK_TYPE_MASK)) 4212 lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE; 4213 4214 if (vp1_locked) { 4215 ASSERT_VOP_LOCKED(vp1, "vp1"); 4216 4217 /* No need to relock if any lock is exclusive. */ 4218 if ((vp1->v_vnlock->lock_object.lo_flags & 4219 LK_NOSHARE) != 0) 4220 return; 4221 4222 locked1 = VOP_ISLOCKED(vp1); 4223 if (((lkflags1 & LK_SHARED) != 0 && 4224 locked1 != LK_EXCLUSIVE) || 4225 ((lkflags1 & LK_EXCLUSIVE) != 0 && 4226 locked1 == LK_EXCLUSIVE)) 4227 return; 4228 VOP_UNLOCK(vp1); 4229 } 4230 4231 ASSERT_VOP_UNLOCKED(vp1, "vp1"); 4232 vn_lock(vp1, lkflags1 | LK_RETRY); 4233 return; 4234 } 4235 4236 if (vp1 != NULL) { 4237 if ((lkflags1 & LK_SHARED) != 0 && 4238 (vp1->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0) 4239 lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE; 4240 if (vp1_locked && VOP_ISLOCKED(vp1) != LK_EXCLUSIVE) { 4241 ASSERT_VOP_LOCKED(vp1, "vp1"); 4242 if ((lkflags1 & LK_EXCLUSIVE) != 0) { 4243 VOP_UNLOCK(vp1); 4244 ASSERT_VOP_UNLOCKED(vp1, 4245 "vp1 shared recursed"); 4246 vp1_locked = false; 4247 } 4248 } else if (!vp1_locked) 4249 ASSERT_VOP_UNLOCKED(vp1, "vp1"); 4250 } else { 4251 vp1_locked = true; 4252 } 4253 4254 if (vp2 != NULL) { 4255 if ((lkflags2 & LK_SHARED) != 0 && 4256 (vp2->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0) 4257 lkflags2 = (lkflags2 & ~LK_SHARED) | LK_EXCLUSIVE; 4258 if (vp2_locked && VOP_ISLOCKED(vp2) != LK_EXCLUSIVE) { 4259 ASSERT_VOP_LOCKED(vp2, "vp2"); 4260 if ((lkflags2 & LK_EXCLUSIVE) != 0) { 4261 VOP_UNLOCK(vp2); 4262 ASSERT_VOP_UNLOCKED(vp2, 4263 "vp2 shared recursed"); 4264 vp2_locked = false; 4265 } 4266 } else if (!vp2_locked) 4267 ASSERT_VOP_UNLOCKED(vp2, "vp2"); 4268 } else { 4269 vp2_locked = true; 4270 } 4271 4272 if (!vp1_locked && !vp2_locked) { 4273 vn_lock(vp1, lkflags1 | LK_RETRY); 4274 vp1_locked = true; 4275 } 4276 4277 while (!vp1_locked || !vp2_locked) { 4278 if (vp1_locked && vp2 != NULL) { 4279 if (vp1 != NULL) { 4280 error = VOP_LOCK1(vp2, lkflags2 | LK_NOWAIT, 4281 __FILE__, __LINE__); 4282 if (error == 0) 4283 break; 4284 VOP_UNLOCK(vp1); 4285 vp1_locked = false; 4286 vn_lock_pair_pause("vlp1"); 4287 } 4288 vn_lock(vp2, lkflags2 | LK_RETRY); 4289 vp2_locked = true; 4290 } 4291 if (vp2_locked && vp1 != NULL) { 4292 if (vp2 != NULL) { 4293 error = VOP_LOCK1(vp1, lkflags1 | LK_NOWAIT, 4294 __FILE__, __LINE__); 4295 if (error == 0) 4296 break; 4297 VOP_UNLOCK(vp2); 4298 vp2_locked = false; 4299 vn_lock_pair_pause("vlp2"); 4300 } 4301 vn_lock(vp1, lkflags1 | LK_RETRY); 4302 vp1_locked = true; 4303 } 4304 } 4305 if (vp1 != NULL) { 4306 if (lkflags1 == LK_EXCLUSIVE) 4307 ASSERT_VOP_ELOCKED(vp1, "vp1 ret"); 4308 else 4309 ASSERT_VOP_LOCKED(vp1, "vp1 ret"); 4310 } 4311 if (vp2 != NULL) { 4312 if (lkflags2 == LK_EXCLUSIVE) 4313 ASSERT_VOP_ELOCKED(vp2, "vp2 ret"); 4314 else 4315 ASSERT_VOP_LOCKED(vp2, "vp2 ret"); 4316 } 4317 } 4318 4319 int 4320 vn_lktype_write(struct mount *mp, struct vnode *vp) 4321 { 4322 if (MNT_SHARED_WRITES(mp) || 4323 (mp == NULL && MNT_SHARED_WRITES(vp->v_mount))) 4324 return (LK_SHARED); 4325 return (LK_EXCLUSIVE); 4326 } 4327 4328 int 4329 vn_cmp(struct file *fp1, struct file *fp2, struct thread *td) 4330 { 4331 if (fp2->f_type != DTYPE_VNODE) 4332 return (3); 4333 return (kcmp_cmp((uintptr_t)fp1->f_vnode, (uintptr_t)fp2->f_vnode)); 4334 } 4335