1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 9 * or https://opensource.org/licenses/CDDL-1.0. 10 * See the License for the specific language governing permissions 11 * and limitations under the License. 12 * 13 * When distributing Covered Code, include this CDDL HEADER in each 14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 15 * If applicable, add the following below this CDDL HEADER, with the 16 * fields enclosed by brackets "[]" replaced with your own identifying 17 * information: Portions Copyright [yyyy] [name of copyright owner] 18 * 19 * CDDL HEADER END 20 */ 21 22 /* 23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. 24 * Copyright (c) 2012, 2018 by Delphix. All rights reserved. 25 * Copyright (c) 2015 by Chunwei Chen. All rights reserved. 26 * Copyright 2017 Nexenta Systems, Inc. 27 * Copyright (c) 2021, 2022 by Pawel Jakub Dawidek 28 */ 29 30 /* Portions Copyright 2007 Jeremy Teo */ 31 /* Portions Copyright 2010 Robert Milkowski */ 32 33 #include <sys/types.h> 34 #include <sys/param.h> 35 #include <sys/time.h> 36 #include <sys/sysmacros.h> 37 #include <sys/vfs.h> 38 #include <sys/file.h> 39 #include <sys/stat.h> 40 #include <sys/kmem.h> 41 #include <sys/cmn_err.h> 42 #include <sys/errno.h> 43 #include <sys/zfs_dir.h> 44 #include <sys/zfs_acl.h> 45 #include <sys/zfs_ioctl.h> 46 #include <sys/fs/zfs.h> 47 #include <sys/dmu.h> 48 #include <sys/dmu_objset.h> 49 #include <sys/dsl_crypt.h> 50 #include <sys/spa.h> 51 #include <sys/txg.h> 52 #include <sys/dbuf.h> 53 #include <sys/policy.h> 54 #include <sys/zfeature.h> 55 #include <sys/zfs_vnops.h> 56 #include <sys/zfs_quota.h> 57 #include <sys/zfs_vfsops.h> 58 #include <sys/zfs_znode.h> 59 60 /* 61 * Enable the experimental block cloning feature. If this setting is 0, then 62 * even if feature@block_cloning is enabled, attempts to clone blocks will act 63 * as though the feature is disabled. 64 */ 65 int zfs_bclone_enabled = 1; 66 67 /* 68 * When set zfs_clone_range() waits for dirty data to be written to disk. 69 * This allows the clone operation to reliably succeed when a file is modified 70 * and then immediately cloned. For small files this may be slower than making 71 * a copy of the file and is therefore not the default. However, in certain 72 * scenarios this behavior may be desirable so a tunable is provided. 73 */ 74 static int zfs_bclone_wait_dirty = 0; 75 76 /* 77 * Enable Direct I/O. If this setting is 0, then all I/O requests will be 78 * directed through the ARC acting as though the dataset property direct was 79 * set to disabled. 80 */ 81 static int zfs_dio_enabled = 0; 82 83 84 /* 85 * Maximum bytes to read per chunk in zfs_read(). 86 */ 87 static uint64_t zfs_vnops_read_chunk_size = 1024 * 1024; 88 89 int 90 zfs_fsync(znode_t *zp, int syncflag, cred_t *cr) 91 { 92 int error = 0; 93 zfsvfs_t *zfsvfs = ZTOZSB(zp); 94 95 if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) { 96 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 97 return (error); 98 atomic_inc_32(&zp->z_sync_writes_cnt); 99 zil_commit(zfsvfs->z_log, zp->z_id); 100 atomic_dec_32(&zp->z_sync_writes_cnt); 101 zfs_exit(zfsvfs, FTAG); 102 } 103 return (error); 104 } 105 106 107 #if defined(SEEK_HOLE) && defined(SEEK_DATA) 108 /* 109 * Lseek support for finding holes (cmd == SEEK_HOLE) and 110 * data (cmd == SEEK_DATA). "off" is an in/out parameter. 111 */ 112 static int 113 zfs_holey_common(znode_t *zp, ulong_t cmd, loff_t *off) 114 { 115 zfs_locked_range_t *lr; 116 uint64_t noff = (uint64_t)*off; /* new offset */ 117 uint64_t file_sz; 118 int error; 119 boolean_t hole; 120 121 file_sz = zp->z_size; 122 if (noff >= file_sz) { 123 return (SET_ERROR(ENXIO)); 124 } 125 126 if (cmd == F_SEEK_HOLE) 127 hole = B_TRUE; 128 else 129 hole = B_FALSE; 130 131 /* Flush any mmap()'d data to disk */ 132 if (zn_has_cached_data(zp, 0, file_sz - 1)) 133 zn_flush_cached_data(zp, B_TRUE); 134 135 lr = zfs_rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_READER); 136 error = dmu_offset_next(ZTOZSB(zp)->z_os, zp->z_id, hole, &noff); 137 zfs_rangelock_exit(lr); 138 139 if (error == ESRCH) 140 return (SET_ERROR(ENXIO)); 141 142 /* File was dirty, so fall back to using generic logic */ 143 if (error == EBUSY) { 144 if (hole) 145 *off = file_sz; 146 147 return (0); 148 } 149 150 /* 151 * We could find a hole that begins after the logical end-of-file, 152 * because dmu_offset_next() only works on whole blocks. If the 153 * EOF falls mid-block, then indicate that the "virtual hole" 154 * at the end of the file begins at the logical EOF, rather than 155 * at the end of the last block. 156 */ 157 if (noff > file_sz) { 158 ASSERT(hole); 159 noff = file_sz; 160 } 161 162 if (noff < *off) 163 return (error); 164 *off = noff; 165 return (error); 166 } 167 168 int 169 zfs_holey(znode_t *zp, ulong_t cmd, loff_t *off) 170 { 171 zfsvfs_t *zfsvfs = ZTOZSB(zp); 172 int error; 173 174 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 175 return (error); 176 177 error = zfs_holey_common(zp, cmd, off); 178 179 zfs_exit(zfsvfs, FTAG); 180 return (error); 181 } 182 #endif /* SEEK_HOLE && SEEK_DATA */ 183 184 int 185 zfs_access(znode_t *zp, int mode, int flag, cred_t *cr) 186 { 187 zfsvfs_t *zfsvfs = ZTOZSB(zp); 188 int error; 189 190 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 191 return (error); 192 193 if (flag & V_ACE_MASK) 194 #if defined(__linux__) 195 error = zfs_zaccess(zp, mode, flag, B_FALSE, cr, 196 zfs_init_idmap); 197 #else 198 error = zfs_zaccess(zp, mode, flag, B_FALSE, cr, 199 NULL); 200 #endif 201 else 202 #if defined(__linux__) 203 error = zfs_zaccess_rwx(zp, mode, flag, cr, zfs_init_idmap); 204 #else 205 error = zfs_zaccess_rwx(zp, mode, flag, cr, NULL); 206 #endif 207 208 zfs_exit(zfsvfs, FTAG); 209 return (error); 210 } 211 212 /* 213 * Determine if Direct I/O has been requested (either via the O_DIRECT flag or 214 * the "direct" dataset property). When inherited by the property only apply 215 * the O_DIRECT flag to correctly aligned IO requests. The rational for this 216 * is it allows the property to be safely set on a dataset without forcing 217 * all of the applications to be aware of the alignment restrictions. When 218 * O_DIRECT is explicitly requested by an application return EINVAL if the 219 * request is unaligned. In all cases, if the range for this request has 220 * been mmap'ed then we will perform buffered I/O to keep the mapped region 221 * synhronized with the ARC. 222 * 223 * It is possible that a file's pages could be mmap'ed after it is checked 224 * here. If so, that is handled coorarding in zfs_write(). See comments in the 225 * following area for how this is handled: 226 * zfs_write() -> update_pages() 227 */ 228 static int 229 zfs_setup_direct(struct znode *zp, zfs_uio_t *uio, zfs_uio_rw_t rw, 230 int *ioflagp) 231 { 232 zfsvfs_t *zfsvfs = ZTOZSB(zp); 233 objset_t *os = zfsvfs->z_os; 234 int ioflag = *ioflagp; 235 int error = 0; 236 237 if (!zfs_dio_enabled || os->os_direct == ZFS_DIRECT_DISABLED || 238 zn_has_cached_data(zp, zfs_uio_offset(uio), 239 zfs_uio_offset(uio) + zfs_uio_resid(uio) - 1)) { 240 /* 241 * Direct I/O is disabled or the region is mmap'ed. In either 242 * case the I/O request will just directed through the ARC. 243 */ 244 ioflag &= ~O_DIRECT; 245 goto out; 246 } else if (os->os_direct == ZFS_DIRECT_ALWAYS && 247 zfs_uio_page_aligned(uio) && 248 zfs_uio_aligned(uio, PAGE_SIZE)) { 249 if ((rw == UIO_WRITE && zfs_uio_resid(uio) >= zp->z_blksz) || 250 (rw == UIO_READ)) { 251 ioflag |= O_DIRECT; 252 } 253 } else if (os->os_direct == ZFS_DIRECT_ALWAYS && (ioflag & O_DIRECT)) { 254 /* 255 * Direct I/O was requested through the direct=always, but it 256 * is not properly PAGE_SIZE aligned. The request will be 257 * directed through the ARC. 258 */ 259 ioflag &= ~O_DIRECT; 260 } 261 262 if (ioflag & O_DIRECT) { 263 if (!zfs_uio_page_aligned(uio) || 264 !zfs_uio_aligned(uio, PAGE_SIZE)) { 265 error = SET_ERROR(EINVAL); 266 goto out; 267 } 268 269 error = zfs_uio_get_dio_pages_alloc(uio, rw); 270 if (error) { 271 goto out; 272 } 273 } 274 275 IMPLY(ioflag & O_DIRECT, uio->uio_extflg & UIO_DIRECT); 276 ASSERT0(error); 277 278 out: 279 *ioflagp = ioflag; 280 return (error); 281 } 282 283 /* 284 * Read bytes from specified file into supplied buffer. 285 * 286 * IN: zp - inode of file to be read from. 287 * uio - structure supplying read location, range info, 288 * and return buffer. 289 * ioflag - O_SYNC flags; used to provide FRSYNC semantics. 290 * O_DIRECT flag; used to bypass page cache. 291 * cr - credentials of caller. 292 * 293 * OUT: uio - updated offset and range, buffer filled. 294 * 295 * RETURN: 0 on success, error code on failure. 296 * 297 * Side Effects: 298 * inode - atime updated if byte count > 0 299 */ 300 int 301 zfs_read(struct znode *zp, zfs_uio_t *uio, int ioflag, cred_t *cr) 302 { 303 (void) cr; 304 int error = 0; 305 boolean_t frsync = B_FALSE; 306 307 zfsvfs_t *zfsvfs = ZTOZSB(zp); 308 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 309 return (error); 310 311 if (zp->z_pflags & ZFS_AV_QUARANTINED) { 312 zfs_exit(zfsvfs, FTAG); 313 return (SET_ERROR(EACCES)); 314 } 315 316 /* We don't copy out anything useful for directories. */ 317 if (Z_ISDIR(ZTOTYPE(zp))) { 318 zfs_exit(zfsvfs, FTAG); 319 return (SET_ERROR(EISDIR)); 320 } 321 322 /* 323 * Validate file offset 324 */ 325 if (zfs_uio_offset(uio) < (offset_t)0) { 326 zfs_exit(zfsvfs, FTAG); 327 return (SET_ERROR(EINVAL)); 328 } 329 330 /* 331 * Fasttrack empty reads 332 */ 333 if (zfs_uio_resid(uio) == 0) { 334 zfs_exit(zfsvfs, FTAG); 335 return (0); 336 } 337 338 #ifdef FRSYNC 339 /* 340 * If we're in FRSYNC mode, sync out this znode before reading it. 341 * Only do this for non-snapshots. 342 * 343 * Some platforms do not support FRSYNC and instead map it 344 * to O_SYNC, which results in unnecessary calls to zil_commit. We 345 * only honor FRSYNC requests on platforms which support it. 346 */ 347 frsync = !!(ioflag & FRSYNC); 348 #endif 349 if (zfsvfs->z_log && 350 (frsync || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)) 351 zil_commit(zfsvfs->z_log, zp->z_id); 352 353 /* 354 * Lock the range against changes. 355 */ 356 zfs_locked_range_t *lr = zfs_rangelock_enter(&zp->z_rangelock, 357 zfs_uio_offset(uio), zfs_uio_resid(uio), RL_READER); 358 359 /* 360 * If we are reading past end-of-file we can skip 361 * to the end; but we might still need to set atime. 362 */ 363 if (zfs_uio_offset(uio) >= zp->z_size) { 364 error = 0; 365 goto out; 366 } 367 ASSERT(zfs_uio_offset(uio) < zp->z_size); 368 369 /* 370 * Setting up Direct I/O if requested. 371 */ 372 error = zfs_setup_direct(zp, uio, UIO_READ, &ioflag); 373 if (error) { 374 goto out; 375 } 376 377 #if defined(__linux__) 378 ssize_t start_offset = zfs_uio_offset(uio); 379 #endif 380 ssize_t chunk_size = zfs_vnops_read_chunk_size; 381 ssize_t n = MIN(zfs_uio_resid(uio), zp->z_size - zfs_uio_offset(uio)); 382 ssize_t start_resid = n; 383 ssize_t dio_remaining_resid = 0; 384 385 if (uio->uio_extflg & UIO_DIRECT) { 386 /* 387 * All pages for an O_DIRECT request ahve already been mapped 388 * so there's no compelling reason to handle this uio in 389 * smaller chunks. 390 */ 391 chunk_size = DMU_MAX_ACCESS; 392 393 /* 394 * In the event that the O_DIRECT request is reading the entire 395 * file, it is possible file's length is not page sized 396 * aligned. However, lower layers expect that the Direct I/O 397 * request is page-aligned. In this case, as much of the file 398 * that can be read using Direct I/O happens and the remaining 399 * amount will be read through the ARC. 400 * 401 * This is still consistent with the semantics of Direct I/O in 402 * ZFS as at a minimum the I/O request must be page-aligned. 403 */ 404 dio_remaining_resid = n - P2ALIGN_TYPED(n, PAGE_SIZE, ssize_t); 405 if (dio_remaining_resid != 0) 406 n -= dio_remaining_resid; 407 } 408 409 while (n > 0) { 410 ssize_t nbytes = MIN(n, chunk_size - 411 P2PHASE(zfs_uio_offset(uio), chunk_size)); 412 #ifdef UIO_NOCOPY 413 if (zfs_uio_segflg(uio) == UIO_NOCOPY) 414 error = mappedread_sf(zp, nbytes, uio); 415 else 416 #endif 417 if (zn_has_cached_data(zp, zfs_uio_offset(uio), 418 zfs_uio_offset(uio) + nbytes - 1)) { 419 error = mappedread(zp, nbytes, uio); 420 } else { 421 error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl), 422 uio, nbytes); 423 } 424 425 if (error) { 426 /* convert checksum errors into IO errors */ 427 if (error == ECKSUM) 428 error = SET_ERROR(EIO); 429 430 #if defined(__linux__) 431 /* 432 * if we actually read some bytes, bubbling EFAULT 433 * up to become EAGAIN isn't what we want here... 434 * 435 * ...on Linux, at least. On FBSD, doing this breaks. 436 */ 437 if (error == EFAULT && 438 (zfs_uio_offset(uio) - start_offset) != 0) 439 error = 0; 440 #endif 441 break; 442 } 443 444 n -= nbytes; 445 } 446 447 if (error == 0 && (uio->uio_extflg & UIO_DIRECT) && 448 dio_remaining_resid != 0) { 449 /* 450 * Temporarily remove the UIO_DIRECT flag from the UIO so the 451 * remainder of the file can be read using the ARC. 452 */ 453 uio->uio_extflg &= ~UIO_DIRECT; 454 455 if (zn_has_cached_data(zp, zfs_uio_offset(uio), 456 zfs_uio_offset(uio) + dio_remaining_resid - 1)) { 457 error = mappedread(zp, dio_remaining_resid, uio); 458 } else { 459 error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl), uio, 460 dio_remaining_resid); 461 } 462 uio->uio_extflg |= UIO_DIRECT; 463 464 if (error != 0) 465 n += dio_remaining_resid; 466 } else if (error && (uio->uio_extflg & UIO_DIRECT)) { 467 n += dio_remaining_resid; 468 } 469 int64_t nread = start_resid - n; 470 471 dataset_kstats_update_read_kstats(&zfsvfs->z_kstat, nread); 472 out: 473 zfs_rangelock_exit(lr); 474 475 /* 476 * Cleanup for Direct I/O if requested. 477 */ 478 if (uio->uio_extflg & UIO_DIRECT) 479 zfs_uio_free_dio_pages(uio, UIO_READ); 480 481 ZFS_ACCESSTIME_STAMP(zfsvfs, zp); 482 zfs_exit(zfsvfs, FTAG); 483 return (error); 484 } 485 486 static void 487 zfs_clear_setid_bits_if_necessary(zfsvfs_t *zfsvfs, znode_t *zp, cred_t *cr, 488 uint64_t *clear_setid_bits_txgp, dmu_tx_t *tx) 489 { 490 zilog_t *zilog = zfsvfs->z_log; 491 const uint64_t uid = KUID_TO_SUID(ZTOUID(zp)); 492 493 ASSERT(clear_setid_bits_txgp != NULL); 494 ASSERT(tx != NULL); 495 496 /* 497 * Clear Set-UID/Set-GID bits on successful write if not 498 * privileged and at least one of the execute bits is set. 499 * 500 * It would be nice to do this after all writes have 501 * been done, but that would still expose the ISUID/ISGID 502 * to another app after the partial write is committed. 503 * 504 * Note: we don't call zfs_fuid_map_id() here because 505 * user 0 is not an ephemeral uid. 506 */ 507 mutex_enter(&zp->z_acl_lock); 508 if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) | (S_IXUSR >> 6))) != 0 && 509 (zp->z_mode & (S_ISUID | S_ISGID)) != 0 && 510 secpolicy_vnode_setid_retain(zp, cr, 511 ((zp->z_mode & S_ISUID) != 0 && uid == 0)) != 0) { 512 uint64_t newmode; 513 514 zp->z_mode &= ~(S_ISUID | S_ISGID); 515 newmode = zp->z_mode; 516 (void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs), 517 (void *)&newmode, sizeof (uint64_t), tx); 518 519 mutex_exit(&zp->z_acl_lock); 520 521 /* 522 * Make sure SUID/SGID bits will be removed when we replay the 523 * log. If the setid bits are keep coming back, don't log more 524 * than one TX_SETATTR per transaction group. 525 */ 526 if (*clear_setid_bits_txgp != dmu_tx_get_txg(tx)) { 527 vattr_t va = {0}; 528 529 va.va_mask = ATTR_MODE; 530 va.va_nodeid = zp->z_id; 531 va.va_mode = newmode; 532 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, &va, 533 ATTR_MODE, NULL); 534 *clear_setid_bits_txgp = dmu_tx_get_txg(tx); 535 } 536 } else { 537 mutex_exit(&zp->z_acl_lock); 538 } 539 } 540 541 /* 542 * Write the bytes to a file. 543 * 544 * IN: zp - znode of file to be written to. 545 * uio - structure supplying write location, range info, 546 * and data buffer. 547 * ioflag - O_APPEND flag set if in append mode. 548 * O_DIRECT flag; used to bypass page cache. 549 * cr - credentials of caller. 550 * 551 * OUT: uio - updated offset and range. 552 * 553 * RETURN: 0 if success 554 * error code if failure 555 * 556 * Timestamps: 557 * ip - ctime|mtime updated if byte count > 0 558 */ 559 int 560 zfs_write(znode_t *zp, zfs_uio_t *uio, int ioflag, cred_t *cr) 561 { 562 int error = 0, error1; 563 ssize_t start_resid = zfs_uio_resid(uio); 564 uint64_t clear_setid_bits_txg = 0; 565 boolean_t o_direct_defer = B_FALSE; 566 567 /* 568 * Fasttrack empty write 569 */ 570 ssize_t n = start_resid; 571 if (n == 0) 572 return (0); 573 574 zfsvfs_t *zfsvfs = ZTOZSB(zp); 575 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 576 return (error); 577 578 sa_bulk_attr_t bulk[4]; 579 int count = 0; 580 uint64_t mtime[2], ctime[2]; 581 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); 582 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); 583 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL, 584 &zp->z_size, 8); 585 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL, 586 &zp->z_pflags, 8); 587 588 /* 589 * Callers might not be able to detect properly that we are read-only, 590 * so check it explicitly here. 591 */ 592 if (zfs_is_readonly(zfsvfs)) { 593 zfs_exit(zfsvfs, FTAG); 594 return (SET_ERROR(EROFS)); 595 } 596 597 /* 598 * If immutable or not appending then return EPERM. 599 * Intentionally allow ZFS_READONLY through here. 600 * See zfs_zaccess_common() 601 */ 602 if ((zp->z_pflags & ZFS_IMMUTABLE) || 603 ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & O_APPEND) && 604 (zfs_uio_offset(uio) < zp->z_size))) { 605 zfs_exit(zfsvfs, FTAG); 606 return (SET_ERROR(EPERM)); 607 } 608 609 /* 610 * Validate file offset 611 */ 612 offset_t woff = ioflag & O_APPEND ? zp->z_size : zfs_uio_offset(uio); 613 if (woff < 0) { 614 zfs_exit(zfsvfs, FTAG); 615 return (SET_ERROR(EINVAL)); 616 } 617 618 /* 619 * Setting up Direct I/O if requested. 620 */ 621 error = zfs_setup_direct(zp, uio, UIO_WRITE, &ioflag); 622 if (error) { 623 zfs_exit(zfsvfs, FTAG); 624 return (SET_ERROR(error)); 625 } 626 627 /* 628 * Pre-fault the pages to ensure slow (eg NFS) pages 629 * don't hold up txg. 630 */ 631 ssize_t pfbytes = MIN(n, DMU_MAX_ACCESS >> 1); 632 if (zfs_uio_prefaultpages(pfbytes, uio)) { 633 zfs_exit(zfsvfs, FTAG); 634 return (SET_ERROR(EFAULT)); 635 } 636 637 /* 638 * If in append mode, set the io offset pointer to eof. 639 */ 640 zfs_locked_range_t *lr; 641 if (ioflag & O_APPEND) { 642 /* 643 * Obtain an appending range lock to guarantee file append 644 * semantics. We reset the write offset once we have the lock. 645 */ 646 lr = zfs_rangelock_enter(&zp->z_rangelock, 0, n, RL_APPEND); 647 woff = lr->lr_offset; 648 if (lr->lr_length == UINT64_MAX) { 649 /* 650 * We overlocked the file because this write will cause 651 * the file block size to increase. 652 * Note that zp_size cannot change with this lock held. 653 */ 654 woff = zp->z_size; 655 } 656 zfs_uio_setoffset(uio, woff); 657 /* 658 * We need to update the starting offset as well because it is 659 * set previously in the ZPL (Linux) and VNOPS (FreeBSD) 660 * layers. 661 */ 662 zfs_uio_setsoffset(uio, woff); 663 } else { 664 /* 665 * Note that if the file block size will change as a result of 666 * this write, then this range lock will lock the entire file 667 * so that we can re-write the block safely. 668 */ 669 lr = zfs_rangelock_enter(&zp->z_rangelock, woff, n, RL_WRITER); 670 } 671 672 if (zn_rlimit_fsize_uio(zp, uio)) { 673 zfs_rangelock_exit(lr); 674 zfs_exit(zfsvfs, FTAG); 675 return (SET_ERROR(EFBIG)); 676 } 677 678 const rlim64_t limit = MAXOFFSET_T; 679 680 if (woff >= limit) { 681 zfs_rangelock_exit(lr); 682 zfs_exit(zfsvfs, FTAG); 683 return (SET_ERROR(EFBIG)); 684 } 685 686 if (n > limit - woff) 687 n = limit - woff; 688 689 uint64_t end_size = MAX(zp->z_size, woff + n); 690 zilog_t *zilog = zfsvfs->z_log; 691 boolean_t commit = (ioflag & (O_SYNC | O_DSYNC)) || 692 (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS); 693 694 const uint64_t uid = KUID_TO_SUID(ZTOUID(zp)); 695 const uint64_t gid = KGID_TO_SGID(ZTOGID(zp)); 696 const uint64_t projid = zp->z_projid; 697 698 /* 699 * In the event we are increasing the file block size 700 * (lr_length == UINT64_MAX), we will direct the write to the ARC. 701 * Because zfs_grow_blocksize() will read from the ARC in order to 702 * grow the dbuf, we avoid doing Direct I/O here as that would cause 703 * data written to disk to be overwritten by data in the ARC during 704 * the sync phase. Besides writing data twice to disk, we also 705 * want to avoid consistency concerns between data in the the ARC and 706 * on disk while growing the file's blocksize. 707 * 708 * We will only temporarily remove Direct I/O and put it back after 709 * we have grown the blocksize. We do this in the event a request 710 * is larger than max_blksz, so further requests to 711 * dmu_write_uio_dbuf() will still issue the requests using Direct 712 * IO. 713 * 714 * As an example: 715 * The first block to file is being written as a 4k request with 716 * a recorsize of 1K. The first 1K issued in the loop below will go 717 * through the ARC; however, the following 3 1K requests will 718 * use Direct I/O. 719 */ 720 if (uio->uio_extflg & UIO_DIRECT && lr->lr_length == UINT64_MAX) { 721 uio->uio_extflg &= ~UIO_DIRECT; 722 o_direct_defer = B_TRUE; 723 } 724 725 /* 726 * Write the file in reasonable size chunks. Each chunk is written 727 * in a separate transaction; this keeps the intent log records small 728 * and allows us to do more fine-grained space accounting. 729 */ 730 while (n > 0) { 731 woff = zfs_uio_offset(uio); 732 733 if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, uid) || 734 zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, gid) || 735 (projid != ZFS_DEFAULT_PROJID && 736 zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT, 737 projid))) { 738 error = SET_ERROR(EDQUOT); 739 break; 740 } 741 742 uint64_t blksz; 743 if (lr->lr_length == UINT64_MAX && zp->z_size <= zp->z_blksz) { 744 if (zp->z_blksz > zfsvfs->z_max_blksz && 745 !ISP2(zp->z_blksz)) { 746 /* 747 * File's blocksize is already larger than the 748 * "recordsize" property. Only let it grow to 749 * the next power of 2. 750 */ 751 blksz = 1 << highbit64(zp->z_blksz); 752 } else { 753 blksz = zfsvfs->z_max_blksz; 754 } 755 blksz = MIN(blksz, P2ROUNDUP(end_size, 756 SPA_MINBLOCKSIZE)); 757 blksz = MAX(blksz, zp->z_blksz); 758 } else { 759 blksz = zp->z_blksz; 760 } 761 762 arc_buf_t *abuf = NULL; 763 ssize_t nbytes = n; 764 if (n >= blksz && woff >= zp->z_size && 765 P2PHASE(woff, blksz) == 0 && 766 !(uio->uio_extflg & UIO_DIRECT) && 767 (blksz >= SPA_OLD_MAXBLOCKSIZE || n < 4 * blksz)) { 768 /* 769 * This write covers a full block. "Borrow" a buffer 770 * from the dmu so that we can fill it before we enter 771 * a transaction. This avoids the possibility of 772 * holding up the transaction if the data copy hangs 773 * up on a pagefault (e.g., from an NFS server mapping). 774 */ 775 abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl), 776 blksz); 777 ASSERT(abuf != NULL); 778 ASSERT(arc_buf_size(abuf) == blksz); 779 if ((error = zfs_uiocopy(abuf->b_data, blksz, 780 UIO_WRITE, uio, &nbytes))) { 781 dmu_return_arcbuf(abuf); 782 break; 783 } 784 ASSERT3S(nbytes, ==, blksz); 785 } else { 786 nbytes = MIN(n, (DMU_MAX_ACCESS >> 1) - 787 P2PHASE(woff, blksz)); 788 if (pfbytes < nbytes) { 789 if (zfs_uio_prefaultpages(nbytes, uio)) { 790 error = SET_ERROR(EFAULT); 791 break; 792 } 793 pfbytes = nbytes; 794 } 795 } 796 797 /* 798 * Start a transaction. 799 */ 800 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os); 801 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE); 802 dmu_buf_impl_t *db = (dmu_buf_impl_t *)sa_get_db(zp->z_sa_hdl); 803 DB_DNODE_ENTER(db); 804 dmu_tx_hold_write_by_dnode(tx, DB_DNODE(db), woff, nbytes); 805 DB_DNODE_EXIT(db); 806 zfs_sa_upgrade_txholds(tx, zp); 807 error = dmu_tx_assign(tx, TXG_WAIT); 808 if (error) { 809 dmu_tx_abort(tx); 810 if (abuf != NULL) 811 dmu_return_arcbuf(abuf); 812 break; 813 } 814 815 /* 816 * NB: We must call zfs_clear_setid_bits_if_necessary before 817 * committing the transaction! 818 */ 819 820 /* 821 * If rangelock_enter() over-locked we grow the blocksize 822 * and then reduce the lock range. This will only happen 823 * on the first iteration since rangelock_reduce() will 824 * shrink down lr_length to the appropriate size. 825 */ 826 if (lr->lr_length == UINT64_MAX) { 827 zfs_grow_blocksize(zp, blksz, tx); 828 zfs_rangelock_reduce(lr, woff, n); 829 } 830 831 ssize_t tx_bytes; 832 if (abuf == NULL) { 833 tx_bytes = zfs_uio_resid(uio); 834 zfs_uio_fault_disable(uio, B_TRUE); 835 error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl), 836 uio, nbytes, tx); 837 zfs_uio_fault_disable(uio, B_FALSE); 838 #ifdef __linux__ 839 if (error == EFAULT) { 840 zfs_clear_setid_bits_if_necessary(zfsvfs, zp, 841 cr, &clear_setid_bits_txg, tx); 842 dmu_tx_commit(tx); 843 /* 844 * Account for partial writes before 845 * continuing the loop. 846 * Update needs to occur before the next 847 * zfs_uio_prefaultpages, or prefaultpages may 848 * error, and we may break the loop early. 849 */ 850 n -= tx_bytes - zfs_uio_resid(uio); 851 pfbytes -= tx_bytes - zfs_uio_resid(uio); 852 continue; 853 } 854 #endif 855 /* 856 * On FreeBSD, EFAULT should be propagated back to the 857 * VFS, which will handle faulting and will retry. 858 */ 859 if (error != 0 && error != EFAULT) { 860 zfs_clear_setid_bits_if_necessary(zfsvfs, zp, 861 cr, &clear_setid_bits_txg, tx); 862 dmu_tx_commit(tx); 863 break; 864 } 865 tx_bytes -= zfs_uio_resid(uio); 866 } else { 867 /* 868 * Thus, we're writing a full block at a block-aligned 869 * offset and extending the file past EOF. 870 * 871 * dmu_assign_arcbuf_by_dbuf() will directly assign the 872 * arc buffer to a dbuf. 873 */ 874 error = dmu_assign_arcbuf_by_dbuf( 875 sa_get_db(zp->z_sa_hdl), woff, abuf, tx); 876 if (error != 0) { 877 /* 878 * XXX This might not be necessary if 879 * dmu_assign_arcbuf_by_dbuf is guaranteed 880 * to be atomic. 881 */ 882 zfs_clear_setid_bits_if_necessary(zfsvfs, zp, 883 cr, &clear_setid_bits_txg, tx); 884 dmu_return_arcbuf(abuf); 885 dmu_tx_commit(tx); 886 break; 887 } 888 ASSERT3S(nbytes, <=, zfs_uio_resid(uio)); 889 zfs_uioskip(uio, nbytes); 890 tx_bytes = nbytes; 891 } 892 /* 893 * There is a window where a file's pages can be mmap'ed after 894 * zfs_setup_direct() is called. This is due to the fact that 895 * the rangelock in this function is acquired after calling 896 * zfs_setup_direct(). This is done so that 897 * zfs_uio_prefaultpages() does not attempt to fault in pages 898 * on Linux for Direct I/O requests. This is not necessary as 899 * the pages are pinned in memory and can not be faulted out. 900 * Ideally, the rangelock would be held before calling 901 * zfs_setup_direct() and zfs_uio_prefaultpages(); however, 902 * this can lead to a deadlock as zfs_getpage() also acquires 903 * the rangelock as a RL_WRITER and prefaulting the pages can 904 * lead to zfs_getpage() being called. 905 * 906 * In the case of the pages being mapped after 907 * zfs_setup_direct() is called, the call to update_pages() 908 * will still be made to make sure there is consistency between 909 * the ARC and the Linux page cache. This is an ufortunate 910 * situation as the data will be read back into the ARC after 911 * the Direct I/O write has completed, but this is the penality 912 * for writing to a mmap'ed region of a file using Direct I/O. 913 */ 914 if (tx_bytes && 915 zn_has_cached_data(zp, woff, woff + tx_bytes - 1)) { 916 update_pages(zp, woff, tx_bytes, zfsvfs->z_os); 917 } 918 919 /* 920 * If we made no progress, we're done. If we made even 921 * partial progress, update the znode and ZIL accordingly. 922 */ 923 if (tx_bytes == 0) { 924 (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs), 925 (void *)&zp->z_size, sizeof (uint64_t), tx); 926 dmu_tx_commit(tx); 927 ASSERT(error != 0); 928 break; 929 } 930 931 zfs_clear_setid_bits_if_necessary(zfsvfs, zp, cr, 932 &clear_setid_bits_txg, tx); 933 934 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime); 935 936 /* 937 * Update the file size (zp_size) if it has changed; 938 * account for possible concurrent updates. 939 */ 940 while ((end_size = zp->z_size) < zfs_uio_offset(uio)) { 941 (void) atomic_cas_64(&zp->z_size, end_size, 942 zfs_uio_offset(uio)); 943 ASSERT(error == 0 || error == EFAULT); 944 } 945 /* 946 * If we are replaying and eof is non zero then force 947 * the file size to the specified eof. Note, there's no 948 * concurrency during replay. 949 */ 950 if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0) 951 zp->z_size = zfsvfs->z_replay_eof; 952 953 error1 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx); 954 if (error1 != 0) 955 /* Avoid clobbering EFAULT. */ 956 error = error1; 957 958 /* 959 * NB: During replay, the TX_SETATTR record logged by 960 * zfs_clear_setid_bits_if_necessary must precede any of 961 * the TX_WRITE records logged here. 962 */ 963 zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, commit, 964 uio->uio_extflg & UIO_DIRECT ? B_TRUE : B_FALSE, NULL, 965 NULL); 966 967 dmu_tx_commit(tx); 968 969 /* 970 * Direct I/O was deferred in order to grow the first block. 971 * At this point it can be re-enabled for subsequent writes. 972 */ 973 if (o_direct_defer) { 974 ASSERT(ioflag & O_DIRECT); 975 uio->uio_extflg |= UIO_DIRECT; 976 o_direct_defer = B_FALSE; 977 } 978 979 if (error != 0) 980 break; 981 ASSERT3S(tx_bytes, ==, nbytes); 982 n -= nbytes; 983 pfbytes -= nbytes; 984 } 985 986 if (o_direct_defer) { 987 ASSERT(ioflag & O_DIRECT); 988 uio->uio_extflg |= UIO_DIRECT; 989 o_direct_defer = B_FALSE; 990 } 991 992 zfs_znode_update_vfs(zp); 993 zfs_rangelock_exit(lr); 994 995 /* 996 * Cleanup for Direct I/O if requested. 997 */ 998 if (uio->uio_extflg & UIO_DIRECT) 999 zfs_uio_free_dio_pages(uio, UIO_WRITE); 1000 1001 /* 1002 * If we're in replay mode, or we made no progress, or the 1003 * uio data is inaccessible return an error. Otherwise, it's 1004 * at least a partial write, so it's successful. 1005 */ 1006 if (zfsvfs->z_replay || zfs_uio_resid(uio) == start_resid || 1007 error == EFAULT) { 1008 zfs_exit(zfsvfs, FTAG); 1009 return (error); 1010 } 1011 1012 if (commit) 1013 zil_commit(zilog, zp->z_id); 1014 1015 int64_t nwritten = start_resid - zfs_uio_resid(uio); 1016 dataset_kstats_update_write_kstats(&zfsvfs->z_kstat, nwritten); 1017 1018 zfs_exit(zfsvfs, FTAG); 1019 return (0); 1020 } 1021 1022 int 1023 zfs_getsecattr(znode_t *zp, vsecattr_t *vsecp, int flag, cred_t *cr) 1024 { 1025 zfsvfs_t *zfsvfs = ZTOZSB(zp); 1026 int error; 1027 boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE; 1028 1029 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 1030 return (error); 1031 error = zfs_getacl(zp, vsecp, skipaclchk, cr); 1032 zfs_exit(zfsvfs, FTAG); 1033 1034 return (error); 1035 } 1036 1037 int 1038 zfs_setsecattr(znode_t *zp, vsecattr_t *vsecp, int flag, cred_t *cr) 1039 { 1040 zfsvfs_t *zfsvfs = ZTOZSB(zp); 1041 int error; 1042 boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE; 1043 zilog_t *zilog; 1044 1045 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 1046 return (error); 1047 zilog = zfsvfs->z_log; 1048 error = zfs_setacl(zp, vsecp, skipaclchk, cr); 1049 1050 if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS) 1051 zil_commit(zilog, 0); 1052 1053 zfs_exit(zfsvfs, FTAG); 1054 return (error); 1055 } 1056 1057 #ifdef ZFS_DEBUG 1058 static int zil_fault_io = 0; 1059 #endif 1060 1061 static void zfs_get_done(zgd_t *zgd, int error); 1062 1063 /* 1064 * Get data to generate a TX_WRITE intent log record. 1065 */ 1066 int 1067 zfs_get_data(void *arg, uint64_t gen, lr_write_t *lr, char *buf, 1068 struct lwb *lwb, zio_t *zio) 1069 { 1070 zfsvfs_t *zfsvfs = arg; 1071 objset_t *os = zfsvfs->z_os; 1072 znode_t *zp; 1073 uint64_t object = lr->lr_foid; 1074 uint64_t offset = lr->lr_offset; 1075 uint64_t size = lr->lr_length; 1076 zgd_t *zgd; 1077 int error = 0; 1078 uint64_t zp_gen; 1079 1080 ASSERT3P(lwb, !=, NULL); 1081 ASSERT3U(size, !=, 0); 1082 1083 /* 1084 * Nothing to do if the file has been removed 1085 */ 1086 if (zfs_zget(zfsvfs, object, &zp) != 0) 1087 return (SET_ERROR(ENOENT)); 1088 if (zp->z_unlinked) { 1089 /* 1090 * Release the vnode asynchronously as we currently have the 1091 * txg stopped from syncing. 1092 */ 1093 zfs_zrele_async(zp); 1094 return (SET_ERROR(ENOENT)); 1095 } 1096 /* check if generation number matches */ 1097 if (sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs), &zp_gen, 1098 sizeof (zp_gen)) != 0) { 1099 zfs_zrele_async(zp); 1100 return (SET_ERROR(EIO)); 1101 } 1102 if (zp_gen != gen) { 1103 zfs_zrele_async(zp); 1104 return (SET_ERROR(ENOENT)); 1105 } 1106 1107 zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP); 1108 zgd->zgd_lwb = lwb; 1109 zgd->zgd_private = zp; 1110 1111 /* 1112 * Write records come in two flavors: immediate and indirect. 1113 * For small writes it's cheaper to store the data with the 1114 * log record (immediate); for large writes it's cheaper to 1115 * sync the data and get a pointer to it (indirect) so that 1116 * we don't have to write the data twice. 1117 */ 1118 if (buf != NULL) { /* immediate write */ 1119 zgd->zgd_lr = zfs_rangelock_enter(&zp->z_rangelock, offset, 1120 size, RL_READER); 1121 /* test for truncation needs to be done while range locked */ 1122 if (offset >= zp->z_size) { 1123 error = SET_ERROR(ENOENT); 1124 } else { 1125 error = dmu_read(os, object, offset, size, buf, 1126 DMU_READ_NO_PREFETCH); 1127 } 1128 ASSERT(error == 0 || error == ENOENT); 1129 } else { /* indirect write */ 1130 ASSERT3P(zio, !=, NULL); 1131 /* 1132 * Have to lock the whole block to ensure when it's 1133 * written out and its checksum is being calculated 1134 * that no one can change the data. We need to re-check 1135 * blocksize after we get the lock in case it's changed! 1136 */ 1137 for (;;) { 1138 uint64_t blkoff; 1139 size = zp->z_blksz; 1140 blkoff = ISP2(size) ? P2PHASE(offset, size) : offset; 1141 offset -= blkoff; 1142 zgd->zgd_lr = zfs_rangelock_enter(&zp->z_rangelock, 1143 offset, size, RL_READER); 1144 if (zp->z_blksz == size) 1145 break; 1146 offset += blkoff; 1147 zfs_rangelock_exit(zgd->zgd_lr); 1148 } 1149 /* test for truncation needs to be done while range locked */ 1150 if (lr->lr_offset >= zp->z_size) 1151 error = SET_ERROR(ENOENT); 1152 #ifdef ZFS_DEBUG 1153 if (zil_fault_io) { 1154 error = SET_ERROR(EIO); 1155 zil_fault_io = 0; 1156 } 1157 #endif 1158 1159 dmu_buf_t *dbp; 1160 if (error == 0) 1161 error = dmu_buf_hold_noread(os, object, offset, zgd, 1162 &dbp); 1163 1164 if (error == 0) { 1165 zgd->zgd_db = dbp; 1166 dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbp; 1167 boolean_t direct_write = B_FALSE; 1168 mutex_enter(&db->db_mtx); 1169 dbuf_dirty_record_t *dr = 1170 dbuf_find_dirty_eq(db, lr->lr_common.lrc_txg); 1171 if (dr != NULL && dr->dt.dl.dr_diowrite) 1172 direct_write = B_TRUE; 1173 mutex_exit(&db->db_mtx); 1174 1175 /* 1176 * All Direct I/O writes will have already completed and 1177 * the block pointer can be immediately stored in the 1178 * log record. 1179 */ 1180 if (direct_write) { 1181 /* 1182 * A Direct I/O write always covers an entire 1183 * block. 1184 */ 1185 ASSERT3U(dbp->db_size, ==, zp->z_blksz); 1186 lr->lr_blkptr = dr->dt.dl.dr_overridden_by; 1187 zfs_get_done(zgd, 0); 1188 return (0); 1189 } 1190 1191 blkptr_t *bp = &lr->lr_blkptr; 1192 zgd->zgd_bp = bp; 1193 1194 ASSERT3U(dbp->db_offset, ==, offset); 1195 ASSERT3U(dbp->db_size, ==, size); 1196 1197 error = dmu_sync(zio, lr->lr_common.lrc_txg, 1198 zfs_get_done, zgd); 1199 ASSERT(error || lr->lr_length <= size); 1200 1201 /* 1202 * On success, we need to wait for the write I/O 1203 * initiated by dmu_sync() to complete before we can 1204 * release this dbuf. We will finish everything up 1205 * in the zfs_get_done() callback. 1206 */ 1207 if (error == 0) 1208 return (0); 1209 1210 if (error == EALREADY) { 1211 lr->lr_common.lrc_txtype = TX_WRITE2; 1212 /* 1213 * TX_WRITE2 relies on the data previously 1214 * written by the TX_WRITE that caused 1215 * EALREADY. We zero out the BP because 1216 * it is the old, currently-on-disk BP. 1217 */ 1218 zgd->zgd_bp = NULL; 1219 BP_ZERO(bp); 1220 error = 0; 1221 } 1222 } 1223 } 1224 1225 zfs_get_done(zgd, error); 1226 1227 return (error); 1228 } 1229 1230 static void 1231 zfs_get_done(zgd_t *zgd, int error) 1232 { 1233 (void) error; 1234 znode_t *zp = zgd->zgd_private; 1235 1236 if (zgd->zgd_db) 1237 dmu_buf_rele(zgd->zgd_db, zgd); 1238 1239 zfs_rangelock_exit(zgd->zgd_lr); 1240 1241 /* 1242 * Release the vnode asynchronously as we currently have the 1243 * txg stopped from syncing. 1244 */ 1245 zfs_zrele_async(zp); 1246 1247 kmem_free(zgd, sizeof (zgd_t)); 1248 } 1249 1250 static int 1251 zfs_enter_two(zfsvfs_t *zfsvfs1, zfsvfs_t *zfsvfs2, const char *tag) 1252 { 1253 int error; 1254 1255 /* Swap. Not sure if the order of zfs_enter()s is important. */ 1256 if (zfsvfs1 > zfsvfs2) { 1257 zfsvfs_t *tmpzfsvfs; 1258 1259 tmpzfsvfs = zfsvfs2; 1260 zfsvfs2 = zfsvfs1; 1261 zfsvfs1 = tmpzfsvfs; 1262 } 1263 1264 error = zfs_enter(zfsvfs1, tag); 1265 if (error != 0) 1266 return (error); 1267 if (zfsvfs1 != zfsvfs2) { 1268 error = zfs_enter(zfsvfs2, tag); 1269 if (error != 0) { 1270 zfs_exit(zfsvfs1, tag); 1271 return (error); 1272 } 1273 } 1274 1275 return (0); 1276 } 1277 1278 static void 1279 zfs_exit_two(zfsvfs_t *zfsvfs1, zfsvfs_t *zfsvfs2, const char *tag) 1280 { 1281 1282 zfs_exit(zfsvfs1, tag); 1283 if (zfsvfs1 != zfsvfs2) 1284 zfs_exit(zfsvfs2, tag); 1285 } 1286 1287 /* 1288 * We split each clone request in chunks that can fit into a single ZIL 1289 * log entry. Each ZIL log entry can fit 130816 bytes for a block cloning 1290 * operation (see zil_max_log_data() and zfs_log_clone_range()). This gives 1291 * us room for storing 1022 block pointers. 1292 * 1293 * On success, the function return the number of bytes copied in *lenp. 1294 * Note, it doesn't return how much bytes are left to be copied. 1295 * On errors which are caused by any file system limitations or 1296 * brt limitations `EINVAL` is returned. In the most cases a user 1297 * requested bad parameters, it could be possible to clone the file but 1298 * some parameters don't match the requirements. 1299 */ 1300 int 1301 zfs_clone_range(znode_t *inzp, uint64_t *inoffp, znode_t *outzp, 1302 uint64_t *outoffp, uint64_t *lenp, cred_t *cr) 1303 { 1304 zfsvfs_t *inzfsvfs, *outzfsvfs; 1305 objset_t *inos, *outos; 1306 zfs_locked_range_t *inlr, *outlr; 1307 dmu_buf_impl_t *db; 1308 dmu_tx_t *tx; 1309 zilog_t *zilog; 1310 uint64_t inoff, outoff, len, done; 1311 uint64_t outsize, size; 1312 int error; 1313 int count = 0; 1314 sa_bulk_attr_t bulk[3]; 1315 uint64_t mtime[2], ctime[2]; 1316 uint64_t uid, gid, projid; 1317 blkptr_t *bps; 1318 size_t maxblocks, nbps; 1319 uint_t inblksz; 1320 uint64_t clear_setid_bits_txg = 0; 1321 uint64_t last_synced_txg = 0; 1322 1323 inoff = *inoffp; 1324 outoff = *outoffp; 1325 len = *lenp; 1326 done = 0; 1327 1328 inzfsvfs = ZTOZSB(inzp); 1329 outzfsvfs = ZTOZSB(outzp); 1330 1331 /* 1332 * We need to call zfs_enter() potentially on two different datasets, 1333 * so we need a dedicated function for that. 1334 */ 1335 error = zfs_enter_two(inzfsvfs, outzfsvfs, FTAG); 1336 if (error != 0) 1337 return (error); 1338 1339 inos = inzfsvfs->z_os; 1340 outos = outzfsvfs->z_os; 1341 1342 /* 1343 * Both source and destination have to belong to the same storage pool. 1344 */ 1345 if (dmu_objset_spa(inos) != dmu_objset_spa(outos)) { 1346 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1347 return (SET_ERROR(EXDEV)); 1348 } 1349 1350 /* 1351 * outos and inos belongs to the same storage pool. 1352 * see a few lines above, only one check. 1353 */ 1354 if (!spa_feature_is_enabled(dmu_objset_spa(outos), 1355 SPA_FEATURE_BLOCK_CLONING)) { 1356 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1357 return (SET_ERROR(EOPNOTSUPP)); 1358 } 1359 1360 ASSERT(!outzfsvfs->z_replay); 1361 1362 /* 1363 * Block cloning from an unencrypted dataset into an encrypted 1364 * dataset and vice versa is not supported. 1365 */ 1366 if (inos->os_encrypted != outos->os_encrypted) { 1367 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1368 return (SET_ERROR(EXDEV)); 1369 } 1370 1371 /* 1372 * Cloning across encrypted datasets is possible only if they 1373 * share the same master key. 1374 */ 1375 if (inos != outos && inos->os_encrypted && 1376 !dmu_objset_crypto_key_equal(inos, outos)) { 1377 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1378 return (SET_ERROR(EXDEV)); 1379 } 1380 1381 error = zfs_verify_zp(inzp); 1382 if (error == 0) 1383 error = zfs_verify_zp(outzp); 1384 if (error != 0) { 1385 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1386 return (error); 1387 } 1388 1389 /* 1390 * We don't copy source file's flags that's why we don't allow to clone 1391 * files that are in quarantine. 1392 */ 1393 if (inzp->z_pflags & ZFS_AV_QUARANTINED) { 1394 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1395 return (SET_ERROR(EACCES)); 1396 } 1397 1398 if (inoff >= inzp->z_size) { 1399 *lenp = 0; 1400 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1401 return (0); 1402 } 1403 if (len > inzp->z_size - inoff) { 1404 len = inzp->z_size - inoff; 1405 } 1406 if (len == 0) { 1407 *lenp = 0; 1408 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1409 return (0); 1410 } 1411 1412 /* 1413 * Callers might not be able to detect properly that we are read-only, 1414 * so check it explicitly here. 1415 */ 1416 if (zfs_is_readonly(outzfsvfs)) { 1417 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1418 return (SET_ERROR(EROFS)); 1419 } 1420 1421 /* 1422 * If immutable or not appending then return EPERM. 1423 * Intentionally allow ZFS_READONLY through here. 1424 * See zfs_zaccess_common() 1425 */ 1426 if ((outzp->z_pflags & ZFS_IMMUTABLE) != 0) { 1427 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1428 return (SET_ERROR(EPERM)); 1429 } 1430 1431 /* 1432 * No overlapping if we are cloning within the same file. 1433 */ 1434 if (inzp == outzp) { 1435 if (inoff < outoff + len && outoff < inoff + len) { 1436 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1437 return (SET_ERROR(EINVAL)); 1438 } 1439 } 1440 1441 /* Flush any mmap()'d data to disk */ 1442 if (zn_has_cached_data(inzp, inoff, inoff + len - 1)) 1443 zn_flush_cached_data(inzp, B_TRUE); 1444 1445 /* 1446 * Maintain predictable lock order. 1447 */ 1448 if (inzp < outzp || (inzp == outzp && inoff < outoff)) { 1449 inlr = zfs_rangelock_enter(&inzp->z_rangelock, inoff, len, 1450 RL_READER); 1451 outlr = zfs_rangelock_enter(&outzp->z_rangelock, outoff, len, 1452 RL_WRITER); 1453 } else { 1454 outlr = zfs_rangelock_enter(&outzp->z_rangelock, outoff, len, 1455 RL_WRITER); 1456 inlr = zfs_rangelock_enter(&inzp->z_rangelock, inoff, len, 1457 RL_READER); 1458 } 1459 1460 inblksz = inzp->z_blksz; 1461 1462 /* 1463 * We cannot clone into a file with different block size if we can't 1464 * grow it (block size is already bigger, has more than one block, or 1465 * not locked for growth). There are other possible reasons for the 1466 * grow to fail, but we cover what we can before opening transaction 1467 * and the rest detect after we try to do it. 1468 */ 1469 if (inblksz < outzp->z_blksz) { 1470 error = SET_ERROR(EINVAL); 1471 goto unlock; 1472 } 1473 if (inblksz != outzp->z_blksz && (outzp->z_size > outzp->z_blksz || 1474 outlr->lr_length != UINT64_MAX)) { 1475 error = SET_ERROR(EINVAL); 1476 goto unlock; 1477 } 1478 1479 /* 1480 * Block size must be power-of-2 if destination offset != 0. 1481 * There can be no multiple blocks of non-power-of-2 size. 1482 */ 1483 if (outoff != 0 && !ISP2(inblksz)) { 1484 error = SET_ERROR(EINVAL); 1485 goto unlock; 1486 } 1487 1488 /* 1489 * Offsets and len must be at block boundries. 1490 */ 1491 if ((inoff % inblksz) != 0 || (outoff % inblksz) != 0) { 1492 error = SET_ERROR(EINVAL); 1493 goto unlock; 1494 } 1495 /* 1496 * Length must be multipe of blksz, except for the end of the file. 1497 */ 1498 if ((len % inblksz) != 0 && 1499 (len < inzp->z_size - inoff || len < outzp->z_size - outoff)) { 1500 error = SET_ERROR(EINVAL); 1501 goto unlock; 1502 } 1503 1504 /* 1505 * If we are copying only one block and it is smaller than recordsize 1506 * property, do not allow destination to grow beyond one block if it 1507 * is not there yet. Otherwise the destination will get stuck with 1508 * that block size forever, that can be as small as 512 bytes, no 1509 * matter how big the destination grow later. 1510 */ 1511 if (len <= inblksz && inblksz < outzfsvfs->z_max_blksz && 1512 outzp->z_size <= inblksz && outoff + len > inblksz) { 1513 error = SET_ERROR(EINVAL); 1514 goto unlock; 1515 } 1516 1517 error = zn_rlimit_fsize(outoff + len); 1518 if (error != 0) { 1519 goto unlock; 1520 } 1521 1522 if (inoff >= MAXOFFSET_T || outoff >= MAXOFFSET_T) { 1523 error = SET_ERROR(EFBIG); 1524 goto unlock; 1525 } 1526 1527 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(outzfsvfs), NULL, 1528 &mtime, 16); 1529 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(outzfsvfs), NULL, 1530 &ctime, 16); 1531 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(outzfsvfs), NULL, 1532 &outzp->z_size, 8); 1533 1534 zilog = outzfsvfs->z_log; 1535 maxblocks = zil_max_log_data(zilog, sizeof (lr_clone_range_t)) / 1536 sizeof (bps[0]); 1537 1538 uid = KUID_TO_SUID(ZTOUID(outzp)); 1539 gid = KGID_TO_SGID(ZTOGID(outzp)); 1540 projid = outzp->z_projid; 1541 1542 bps = vmem_alloc(sizeof (bps[0]) * maxblocks, KM_SLEEP); 1543 1544 /* 1545 * Clone the file in reasonable size chunks. Each chunk is cloned 1546 * in a separate transaction; this keeps the intent log records small 1547 * and allows us to do more fine-grained space accounting. 1548 */ 1549 while (len > 0) { 1550 size = MIN(inblksz * maxblocks, len); 1551 1552 if (zfs_id_overblockquota(outzfsvfs, DMU_USERUSED_OBJECT, 1553 uid) || 1554 zfs_id_overblockquota(outzfsvfs, DMU_GROUPUSED_OBJECT, 1555 gid) || 1556 (projid != ZFS_DEFAULT_PROJID && 1557 zfs_id_overblockquota(outzfsvfs, DMU_PROJECTUSED_OBJECT, 1558 projid))) { 1559 error = SET_ERROR(EDQUOT); 1560 break; 1561 } 1562 1563 nbps = maxblocks; 1564 last_synced_txg = spa_last_synced_txg(dmu_objset_spa(inos)); 1565 error = dmu_read_l0_bps(inos, inzp->z_id, inoff, size, bps, 1566 &nbps); 1567 if (error != 0) { 1568 /* 1569 * If we are trying to clone a block that was created 1570 * in the current transaction group, the error will be 1571 * EAGAIN here. Based on zfs_bclone_wait_dirty either 1572 * return a shortened range to the caller so it can 1573 * fallback, or wait for the next TXG and check again. 1574 */ 1575 if (error == EAGAIN && zfs_bclone_wait_dirty) { 1576 txg_wait_synced(dmu_objset_pool(inos), 1577 last_synced_txg + 1); 1578 continue; 1579 } 1580 1581 break; 1582 } 1583 1584 /* 1585 * Start a transaction. 1586 */ 1587 tx = dmu_tx_create(outos); 1588 dmu_tx_hold_sa(tx, outzp->z_sa_hdl, B_FALSE); 1589 db = (dmu_buf_impl_t *)sa_get_db(outzp->z_sa_hdl); 1590 DB_DNODE_ENTER(db); 1591 dmu_tx_hold_clone_by_dnode(tx, DB_DNODE(db), outoff, size); 1592 DB_DNODE_EXIT(db); 1593 zfs_sa_upgrade_txholds(tx, outzp); 1594 error = dmu_tx_assign(tx, TXG_WAIT); 1595 if (error != 0) { 1596 dmu_tx_abort(tx); 1597 break; 1598 } 1599 1600 /* 1601 * Copy source znode's block size. This is done only if the 1602 * whole znode is locked (see zfs_rangelock_cb()) and only 1603 * on the first iteration since zfs_rangelock_reduce() will 1604 * shrink down lr_length to the appropriate size. 1605 */ 1606 if (outlr->lr_length == UINT64_MAX) { 1607 zfs_grow_blocksize(outzp, inblksz, tx); 1608 1609 /* 1610 * Block growth may fail for many reasons we can not 1611 * predict here. If it happen the cloning is doomed. 1612 */ 1613 if (inblksz != outzp->z_blksz) { 1614 error = SET_ERROR(EINVAL); 1615 dmu_tx_abort(tx); 1616 break; 1617 } 1618 1619 /* 1620 * Round range lock up to the block boundary, so we 1621 * prevent appends until we are done. 1622 */ 1623 zfs_rangelock_reduce(outlr, outoff, 1624 ((len - 1) / inblksz + 1) * inblksz); 1625 } 1626 1627 error = dmu_brt_clone(outos, outzp->z_id, outoff, size, tx, 1628 bps, nbps); 1629 if (error != 0) { 1630 dmu_tx_commit(tx); 1631 break; 1632 } 1633 1634 if (zn_has_cached_data(outzp, outoff, outoff + size - 1)) { 1635 update_pages(outzp, outoff, size, outos); 1636 } 1637 1638 zfs_clear_setid_bits_if_necessary(outzfsvfs, outzp, cr, 1639 &clear_setid_bits_txg, tx); 1640 1641 zfs_tstamp_update_setup(outzp, CONTENT_MODIFIED, mtime, ctime); 1642 1643 /* 1644 * Update the file size (zp_size) if it has changed; 1645 * account for possible concurrent updates. 1646 */ 1647 while ((outsize = outzp->z_size) < outoff + size) { 1648 (void) atomic_cas_64(&outzp->z_size, outsize, 1649 outoff + size); 1650 } 1651 1652 error = sa_bulk_update(outzp->z_sa_hdl, bulk, count, tx); 1653 1654 zfs_log_clone_range(zilog, tx, TX_CLONE_RANGE, outzp, outoff, 1655 size, inblksz, bps, nbps); 1656 1657 dmu_tx_commit(tx); 1658 1659 if (error != 0) 1660 break; 1661 1662 inoff += size; 1663 outoff += size; 1664 len -= size; 1665 done += size; 1666 1667 if (issig()) { 1668 error = SET_ERROR(EINTR); 1669 break; 1670 } 1671 } 1672 1673 vmem_free(bps, sizeof (bps[0]) * maxblocks); 1674 zfs_znode_update_vfs(outzp); 1675 1676 unlock: 1677 zfs_rangelock_exit(outlr); 1678 zfs_rangelock_exit(inlr); 1679 1680 if (done > 0) { 1681 /* 1682 * If we have made at least partial progress, reset the error. 1683 */ 1684 error = 0; 1685 1686 ZFS_ACCESSTIME_STAMP(inzfsvfs, inzp); 1687 1688 if (outos->os_sync == ZFS_SYNC_ALWAYS) { 1689 zil_commit(zilog, outzp->z_id); 1690 } 1691 1692 *inoffp += done; 1693 *outoffp += done; 1694 *lenp = done; 1695 } else { 1696 /* 1697 * If we made no progress, there must be a good reason. 1698 * EOF is handled explicitly above, before the loop. 1699 */ 1700 ASSERT3S(error, !=, 0); 1701 } 1702 1703 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG); 1704 1705 return (error); 1706 } 1707 1708 /* 1709 * Usual pattern would be to call zfs_clone_range() from zfs_replay_clone(), 1710 * but we cannot do that, because when replaying we don't have source znode 1711 * available. This is why we need a dedicated replay function. 1712 */ 1713 int 1714 zfs_clone_range_replay(znode_t *zp, uint64_t off, uint64_t len, uint64_t blksz, 1715 const blkptr_t *bps, size_t nbps) 1716 { 1717 zfsvfs_t *zfsvfs; 1718 dmu_buf_impl_t *db; 1719 dmu_tx_t *tx; 1720 int error; 1721 int count = 0; 1722 sa_bulk_attr_t bulk[3]; 1723 uint64_t mtime[2], ctime[2]; 1724 1725 ASSERT3U(off, <, MAXOFFSET_T); 1726 ASSERT3U(len, >, 0); 1727 ASSERT3U(nbps, >, 0); 1728 1729 zfsvfs = ZTOZSB(zp); 1730 1731 ASSERT(spa_feature_is_enabled(dmu_objset_spa(zfsvfs->z_os), 1732 SPA_FEATURE_BLOCK_CLONING)); 1733 1734 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0) 1735 return (error); 1736 1737 ASSERT(zfsvfs->z_replay); 1738 ASSERT(!zfs_is_readonly(zfsvfs)); 1739 1740 if ((off % blksz) != 0) { 1741 zfs_exit(zfsvfs, FTAG); 1742 return (SET_ERROR(EINVAL)); 1743 } 1744 1745 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); 1746 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); 1747 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL, 1748 &zp->z_size, 8); 1749 1750 /* 1751 * Start a transaction. 1752 */ 1753 tx = dmu_tx_create(zfsvfs->z_os); 1754 1755 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE); 1756 db = (dmu_buf_impl_t *)sa_get_db(zp->z_sa_hdl); 1757 DB_DNODE_ENTER(db); 1758 dmu_tx_hold_clone_by_dnode(tx, DB_DNODE(db), off, len); 1759 DB_DNODE_EXIT(db); 1760 zfs_sa_upgrade_txholds(tx, zp); 1761 error = dmu_tx_assign(tx, TXG_WAIT); 1762 if (error != 0) { 1763 dmu_tx_abort(tx); 1764 zfs_exit(zfsvfs, FTAG); 1765 return (error); 1766 } 1767 1768 if (zp->z_blksz < blksz) 1769 zfs_grow_blocksize(zp, blksz, tx); 1770 1771 dmu_brt_clone(zfsvfs->z_os, zp->z_id, off, len, tx, bps, nbps); 1772 1773 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime); 1774 1775 if (zp->z_size < off + len) 1776 zp->z_size = off + len; 1777 1778 error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx); 1779 1780 /* 1781 * zil_replaying() not only check if we are replaying ZIL, but also 1782 * updates the ZIL header to record replay progress. 1783 */ 1784 VERIFY(zil_replaying(zfsvfs->z_log, tx)); 1785 1786 dmu_tx_commit(tx); 1787 1788 zfs_znode_update_vfs(zp); 1789 1790 zfs_exit(zfsvfs, FTAG); 1791 1792 return (error); 1793 } 1794 1795 EXPORT_SYMBOL(zfs_access); 1796 EXPORT_SYMBOL(zfs_fsync); 1797 EXPORT_SYMBOL(zfs_holey); 1798 EXPORT_SYMBOL(zfs_read); 1799 EXPORT_SYMBOL(zfs_write); 1800 EXPORT_SYMBOL(zfs_getsecattr); 1801 EXPORT_SYMBOL(zfs_setsecattr); 1802 EXPORT_SYMBOL(zfs_clone_range); 1803 EXPORT_SYMBOL(zfs_clone_range_replay); 1804 1805 ZFS_MODULE_PARAM(zfs_vnops, zfs_vnops_, read_chunk_size, U64, ZMOD_RW, 1806 "Bytes to read per chunk"); 1807 1808 ZFS_MODULE_PARAM(zfs, zfs_, bclone_enabled, INT, ZMOD_RW, 1809 "Enable block cloning"); 1810 1811 ZFS_MODULE_PARAM(zfs, zfs_, bclone_wait_dirty, INT, ZMOD_RW, 1812 "Wait for dirty blocks when cloning"); 1813 1814 ZFS_MODULE_PARAM(zfs, zfs_, dio_enabled, INT, ZMOD_RW, 1815 "Enable Direct I/O"); 1816