1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * This file and its contents are supplied under the terms of the
4 * Common Development and Distribution License ("CDDL"), version 1.0.
5 * You may only use this file in accordance with the terms of version
6 * 1.0 of the CDDL.
7 *
8 * A full copy of the text of the CDDL should have accompanied this
9 * source. A copy of the CDDL is also available via the Internet at
10 * https://opensource.org/license/CDDL-1.0.
11 */
12
13 /*
14 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15 * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
16 * Copyright (c) 2015 by Chunwei Chen. All rights reserved.
17 * Copyright 2017 Nexenta Systems, Inc.
18 * Copyright (c) 2021, 2022 by Pawel Jakub Dawidek
19 * Copyright (c) 2025, Rob Norris <robn@despairlabs.com>
20 * Copyright (c) 2025, Klara, Inc.
21 */
22
23 /* Portions Copyright 2007 Jeremy Teo */
24 /* Portions Copyright 2010 Robert Milkowski */
25
26 #include <sys/types.h>
27 #include <sys/param.h>
28 #include <sys/time.h>
29 #include <sys/sysmacros.h>
30 #include <sys/vfs.h>
31 #include <sys/file.h>
32 #include <sys/stat.h>
33 #include <sys/kmem.h>
34 #include <sys/cmn_err.h>
35 #include <sys/errno.h>
36 #include <sys/zfs_dir.h>
37 #include <sys/zfs_acl.h>
38 #include <sys/zfs_ioctl.h>
39 #include <sys/fs/zfs.h>
40 #include <sys/dmu.h>
41 #include <sys/dmu_objset.h>
42 #include <sys/dsl_crypt.h>
43 #include <sys/dsl_dataset.h>
44 #include <sys/spa.h>
45 #include <sys/zio_checksum.h>
46 #include <sys/txg.h>
47 #include <sys/blkptr.h>
48 #include <sys/brt.h>
49 #include <sys/dbuf.h>
50 #include <sys/policy.h>
51 #include <sys/zfeature.h>
52 #include <sys/zfs_vnops.h>
53 #include <sys/zfs_quota.h>
54 #include <sys/zfs_vfsops.h>
55 #include <sys/zfs_znode.h>
56
57 /*
58 * Enables access to the block cloning feature. If this setting is 0, then even
59 * if feature@block_cloning is enabled, using functions and system calls that
60 * attempt to clone blocks will act as though the feature is disabled.
61 */
62 int zfs_bclone_enabled = 1;
63
64 /*
65 * Restricts block cloning between datasets with different properties
66 * (checksum, compression, copies, dedup, or special_small_blocks).
67 */
68 int zfs_bclone_strict_properties = 1;
69
70 /*
71 * When set to 1 the FICLONE and FICLONERANGE ioctls will wait for any dirty
72 * data to be written to disk before proceeding. This ensures that the clone
73 * operation reliably succeeds, even if a file is modified and then immediately
74 * cloned. Note that for small files this may be slower than simply copying
75 * the file. When set to 0 the clone operation will immediately fail if it
76 * encounters any dirty blocks. By default waiting is enabled.
77 */
78 int zfs_bclone_wait_dirty = 1;
79
80 /*
81 * Enable Direct I/O. If this setting is 0, then all I/O requests will be
82 * directed through the ARC acting as though the dataset property direct was
83 * set to disabled.
84 */
85 static int zfs_dio_enabled = 1;
86
87 /*
88 * Strictly enforce alignment for Direct I/O requests, returning EINVAL
89 * if not page-aligned instead of silently falling back to uncached I/O.
90 */
91 static int zfs_dio_strict = 0;
92
93
94 /*
95 * Maximum bytes to read per chunk in zfs_read().
96 */
97 #ifdef _ILP32
98 static uint64_t zfs_vnops_read_chunk_size = 1024 * 1024;
99 #else
100 static uint64_t zfs_vnops_read_chunk_size = DMU_MAX_ACCESS / 2;
101 #endif
102
103 int
zfs_fsync(znode_t * zp,int syncflag,cred_t * cr)104 zfs_fsync(znode_t *zp, int syncflag, cred_t *cr)
105 {
106 int error = 0;
107 zfsvfs_t *zfsvfs = ZTOZSB(zp);
108
109 if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
110 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
111 return (error);
112 error = zil_commit(zfsvfs->z_log, zp->z_id);
113 zfs_exit(zfsvfs, FTAG);
114 }
115 return (error);
116 }
117
118
119 #if defined(SEEK_HOLE) && defined(SEEK_DATA)
120 /*
121 * Lseek support for finding holes (cmd == SEEK_HOLE) and
122 * data (cmd == SEEK_DATA). "off" is an in/out parameter.
123 */
124 static int
zfs_holey_common(znode_t * zp,ulong_t cmd,loff_t * off)125 zfs_holey_common(znode_t *zp, ulong_t cmd, loff_t *off)
126 {
127 zfs_locked_range_t *lr;
128 uint64_t noff = (uint64_t)*off; /* new offset */
129 uint64_t file_sz;
130 int error;
131 boolean_t hole;
132
133 file_sz = zp->z_size;
134 if (noff >= file_sz) {
135 return (SET_ERROR(ENXIO));
136 }
137
138 if (cmd == F_SEEK_HOLE)
139 hole = B_TRUE;
140 else
141 hole = B_FALSE;
142
143 /* Flush any mmap()'d data to disk */
144 if (zn_has_cached_data(zp, 0, file_sz - 1))
145 zn_flush_cached_data(zp, B_TRUE);
146
147 lr = zfs_rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_READER);
148 error = dmu_offset_next(ZTOZSB(zp)->z_os, zp->z_id, hole, &noff);
149 zfs_rangelock_exit(lr);
150
151 if (error == ESRCH)
152 return (SET_ERROR(ENXIO));
153
154 /* File was dirty, so fall back to using generic logic */
155 if (error == EBUSY) {
156 if (hole)
157 *off = file_sz;
158
159 return (0);
160 }
161
162 /*
163 * We could find a hole that begins after the logical end-of-file,
164 * because dmu_offset_next() only works on whole blocks. If the
165 * EOF falls mid-block, then indicate that the "virtual hole"
166 * at the end of the file begins at the logical EOF, rather than
167 * at the end of the last block.
168 */
169 if (noff > file_sz) {
170 ASSERT(hole);
171 noff = file_sz;
172 }
173
174 if (noff < *off)
175 return (error);
176 *off = noff;
177 return (error);
178 }
179
180 int
zfs_holey(znode_t * zp,ulong_t cmd,loff_t * off)181 zfs_holey(znode_t *zp, ulong_t cmd, loff_t *off)
182 {
183 zfsvfs_t *zfsvfs = ZTOZSB(zp);
184 int error;
185
186 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
187 return (error);
188
189 error = zfs_holey_common(zp, cmd, off);
190
191 zfs_exit(zfsvfs, FTAG);
192 return (error);
193 }
194 #endif /* SEEK_HOLE && SEEK_DATA */
195
196 int
zfs_access(znode_t * zp,int mode,int flag,cred_t * cr)197 zfs_access(znode_t *zp, int mode, int flag, cred_t *cr)
198 {
199 zfsvfs_t *zfsvfs = ZTOZSB(zp);
200 int error;
201
202 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
203 return (error);
204
205 if (flag & V_ACE_MASK)
206 error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
207 else
208 error = zfs_zaccess_rwx(zp, mode, flag, cr);
209
210 zfs_exit(zfsvfs, FTAG);
211 return (error);
212 }
213
214 /*
215 * Determine if Direct I/O has been requested (either via the O_DIRECT flag or
216 * the "direct" dataset property). When inherited by the property only apply
217 * the O_DIRECT flag to correctly aligned IO requests. The rational for this
218 * is it allows the property to be safely set on a dataset without forcing
219 * all of the applications to be aware of the alignment restrictions. When
220 * O_DIRECT is explicitly requested by an application return EINVAL if the
221 * request is unaligned. In all cases, if the range for this request has
222 * been mmap'ed then we will perform buffered I/O to keep the mapped region
223 * synhronized with the ARC.
224 *
225 * It is possible that a file's pages could be mmap'ed after it is checked
226 * here. If so, that is handled coorarding in zfs_write(). See comments in the
227 * following area for how this is handled:
228 * zfs_write() -> update_pages()
229 */
230 static int
zfs_setup_direct(struct znode * zp,zfs_uio_t * uio,zfs_uio_rw_t rw,int * ioflagp)231 zfs_setup_direct(struct znode *zp, zfs_uio_t *uio, zfs_uio_rw_t rw,
232 int *ioflagp)
233 {
234 zfsvfs_t *zfsvfs = ZTOZSB(zp);
235 objset_t *os = zfsvfs->z_os;
236 int ioflag = *ioflagp;
237 int error = 0;
238
239 if (os->os_direct == ZFS_DIRECT_ALWAYS) {
240 /* Force either direct or uncached I/O. */
241 ioflag |= O_DIRECT;
242 }
243
244 if ((ioflag & O_DIRECT) == 0)
245 goto out;
246
247 if (!zfs_dio_enabled || os->os_direct == ZFS_DIRECT_DISABLED) {
248 /*
249 * Direct I/O is disabled. The I/O request will be directed
250 * through the ARC as uncached I/O.
251 */
252 goto out;
253 }
254
255 if (!zfs_uio_page_aligned(uio) ||
256 !zfs_uio_aligned(uio, PAGE_SIZE)) {
257 /*
258 * Misaligned requests can be executed through the ARC as
259 * uncached I/O. But if O_DIRECT was set by user and we
260 * were set to be strict, then it is a failure.
261 */
262 if ((*ioflagp & O_DIRECT) && zfs_dio_strict)
263 error = SET_ERROR(EINVAL);
264 goto out;
265 }
266
267 if (zn_has_cached_data(zp, zfs_uio_offset(uio),
268 zfs_uio_offset(uio) + zfs_uio_resid(uio) - 1)) {
269 /*
270 * The region is mmap'ed. The I/O request will be directed
271 * through the ARC as uncached I/O.
272 */
273 goto out;
274 }
275
276 /*
277 * For short writes the page mapping of Direct I/O makes no sense.
278 * Direct them through the ARC as uncached I/O.
279 */
280 if (rw == UIO_WRITE && zfs_uio_resid(uio) < zp->z_blksz)
281 goto out;
282
283 error = zfs_uio_get_dio_pages_alloc(uio, rw);
284 if (error)
285 goto out;
286 ASSERT(uio->uio_extflg & UIO_DIRECT);
287
288 out:
289 *ioflagp = ioflag;
290 return (error);
291 }
292
293 /*
294 * Read bytes from specified file into supplied buffer.
295 *
296 * IN: zp - inode of file to be read from.
297 * uio - structure supplying read location, range info,
298 * and return buffer.
299 * ioflag - O_SYNC flags; used to provide FRSYNC semantics.
300 * O_DIRECT flag; used to bypass page cache.
301 * cr - credentials of caller.
302 *
303 * OUT: uio - updated offset and range, buffer filled.
304 *
305 * RETURN: 0 on success, error code on failure.
306 *
307 * Side Effects:
308 * inode - atime updated if byte count > 0
309 */
310 int
zfs_read(struct znode * zp,zfs_uio_t * uio,int ioflag,cred_t * cr)311 zfs_read(struct znode *zp, zfs_uio_t *uio, int ioflag, cred_t *cr)
312 {
313 (void) cr;
314 int error = 0;
315 boolean_t frsync = B_FALSE;
316 boolean_t dio_checksum_failure = B_FALSE;
317
318 zfsvfs_t *zfsvfs = ZTOZSB(zp);
319 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
320 return (error);
321
322 if (zp->z_pflags & ZFS_AV_QUARANTINED) {
323 zfs_exit(zfsvfs, FTAG);
324 return (SET_ERROR(EACCES));
325 }
326
327 /* We don't copy out anything useful for directories. */
328 if (Z_ISDIR(ZTOTYPE(zp))) {
329 zfs_exit(zfsvfs, FTAG);
330 return (SET_ERROR(EISDIR));
331 }
332
333 /*
334 * Validate file offset
335 */
336 if (zfs_uio_offset(uio) < (offset_t)0) {
337 zfs_exit(zfsvfs, FTAG);
338 return (SET_ERROR(EINVAL));
339 }
340
341 /*
342 * Fasttrack empty reads
343 */
344 if (zfs_uio_resid(uio) == 0) {
345 zfs_exit(zfsvfs, FTAG);
346 return (0);
347 }
348
349 #ifdef FRSYNC
350 /*
351 * If we're in FRSYNC mode, sync out this znode before reading it.
352 * Only do this for non-snapshots.
353 *
354 * Some platforms do not support FRSYNC and instead map it
355 * to O_SYNC, which results in unnecessary calls to zil_commit. We
356 * only honor FRSYNC requests on platforms which support it.
357 */
358 frsync = !!(ioflag & FRSYNC);
359 #endif
360 if (zfsvfs->z_log &&
361 (frsync || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)) {
362 error = zil_commit(zfsvfs->z_log, zp->z_id);
363 if (error != 0) {
364 zfs_exit(zfsvfs, FTAG);
365 return (error);
366 }
367 }
368
369 /*
370 * Lock the range against changes.
371 */
372 zfs_locked_range_t *lr = zfs_rangelock_enter(&zp->z_rangelock,
373 zfs_uio_offset(uio), zfs_uio_resid(uio), RL_READER);
374
375 /*
376 * If we are reading past end-of-file we can skip
377 * to the end; but we might still need to set atime.
378 */
379 if (zfs_uio_offset(uio) >= zp->z_size) {
380 error = 0;
381 goto out;
382 }
383 ASSERT(zfs_uio_offset(uio) < zp->z_size);
384
385 /*
386 * Setting up Direct I/O if requested.
387 */
388 error = zfs_setup_direct(zp, uio, UIO_READ, &ioflag);
389 if (error) {
390 goto out;
391 }
392
393 #if defined(__linux__)
394 ssize_t start_offset = zfs_uio_offset(uio);
395 #endif
396 uint_t blksz = zp->z_blksz;
397 ssize_t chunk_size;
398 ssize_t n = MIN(zfs_uio_resid(uio), zp->z_size - zfs_uio_offset(uio));
399 ssize_t start_resid = n;
400 ssize_t dio_remaining_resid = 0;
401
402 dmu_flags_t dflags = DMU_READ_PREFETCH;
403 if (ioflag & O_DIRECT)
404 dflags |= DMU_UNCACHEDIO;
405 if (uio->uio_extflg & UIO_DIRECT) {
406 /*
407 * All pages for an O_DIRECT request ahve already been mapped
408 * so there's no compelling reason to handle this uio in
409 * smaller chunks.
410 */
411 chunk_size = DMU_MAX_ACCESS;
412
413 /*
414 * In the event that the O_DIRECT request is reading the entire
415 * file, it is possible file's length is not page sized
416 * aligned. However, lower layers expect that the Direct I/O
417 * request is page-aligned. In this case, as much of the file
418 * that can be read using Direct I/O happens and the remaining
419 * amount will be read through the ARC.
420 *
421 * This is still consistent with the semantics of Direct I/O in
422 * ZFS as at a minimum the I/O request must be page-aligned.
423 */
424 dio_remaining_resid = n - P2ALIGN_TYPED(n, PAGE_SIZE, ssize_t);
425 if (dio_remaining_resid != 0)
426 n -= dio_remaining_resid;
427 dflags |= DMU_DIRECTIO;
428 } else {
429 chunk_size = MIN(MAX(zfs_vnops_read_chunk_size, blksz),
430 DMU_MAX_ACCESS / 2);
431 }
432
433 while (n > 0) {
434 ssize_t nbytes = MIN(n, chunk_size -
435 P2PHASE(zfs_uio_offset(uio), blksz));
436 #ifdef UIO_NOCOPY
437 if (zfs_uio_segflg(uio) == UIO_NOCOPY)
438 error = mappedread_sf(zp, nbytes, uio);
439 else
440 #endif
441 if (zn_has_cached_data(zp, zfs_uio_offset(uio),
442 zfs_uio_offset(uio) + nbytes - 1)) {
443 error = mappedread(zp, nbytes, uio);
444 } else {
445 error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
446 uio, nbytes, dflags);
447 }
448
449 if (error) {
450 /* convert checksum errors into IO errors */
451 if (error == ECKSUM) {
452 /*
453 * If a Direct I/O read returned a checksum
454 * verify error, then it must be treated as
455 * suspicious. The contents of the buffer could
456 * have beeen manipulated while the I/O was in
457 * flight. In this case, the remainder of I/O
458 * request will just be reissued through the
459 * ARC.
460 */
461 if (uio->uio_extflg & UIO_DIRECT) {
462 dio_checksum_failure = B_TRUE;
463 uio->uio_extflg &= ~UIO_DIRECT;
464 n += dio_remaining_resid;
465 dio_remaining_resid = 0;
466 continue;
467 } else {
468 error = SET_ERROR(EIO);
469 }
470 }
471
472 #if defined(__linux__)
473 /*
474 * if we actually read some bytes, bubbling EFAULT
475 * up to become EAGAIN isn't what we want here...
476 *
477 * ...on Linux, at least. On FBSD, doing this breaks.
478 */
479 if (error == EFAULT &&
480 (zfs_uio_offset(uio) - start_offset) != 0)
481 error = 0;
482 #endif
483 break;
484 }
485
486 n -= nbytes;
487 }
488
489 if (error == 0 && (uio->uio_extflg & UIO_DIRECT) &&
490 dio_remaining_resid != 0) {
491 /*
492 * Temporarily remove the UIO_DIRECT flag from the UIO so the
493 * remainder of the file can be read using the ARC.
494 */
495 uio->uio_extflg &= ~UIO_DIRECT;
496 dflags &= ~DMU_DIRECTIO;
497
498 if (zn_has_cached_data(zp, zfs_uio_offset(uio),
499 zfs_uio_offset(uio) + dio_remaining_resid - 1)) {
500 error = mappedread(zp, dio_remaining_resid, uio);
501 } else {
502 error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl), uio,
503 dio_remaining_resid, dflags);
504 }
505 uio->uio_extflg |= UIO_DIRECT;
506 dflags |= DMU_DIRECTIO;
507
508 if (error != 0)
509 n += dio_remaining_resid;
510 } else if (error && (uio->uio_extflg & UIO_DIRECT)) {
511 n += dio_remaining_resid;
512 }
513 int64_t nread = start_resid - n;
514
515 dataset_kstats_update_read_kstats(&zfsvfs->z_kstat, nread);
516 out:
517 zfs_rangelock_exit(lr);
518
519 if (dio_checksum_failure == B_TRUE)
520 uio->uio_extflg |= UIO_DIRECT;
521
522 /*
523 * Cleanup for Direct I/O if requested.
524 */
525 if (uio->uio_extflg & UIO_DIRECT)
526 zfs_uio_free_dio_pages(uio, UIO_READ);
527
528 ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
529 zfs_exit(zfsvfs, FTAG);
530 return (error);
531 }
532
533 static void
zfs_clear_setid_bits_if_necessary(zfsvfs_t * zfsvfs,znode_t * zp,cred_t * cr,uint64_t * clear_setid_bits_txgp,dmu_tx_t * tx)534 zfs_clear_setid_bits_if_necessary(zfsvfs_t *zfsvfs, znode_t *zp, cred_t *cr,
535 uint64_t *clear_setid_bits_txgp, dmu_tx_t *tx)
536 {
537 zilog_t *zilog = zfsvfs->z_log;
538 const uint64_t uid = KUID_TO_SUID(ZTOUID(zp));
539
540 ASSERT(clear_setid_bits_txgp != NULL);
541 ASSERT(tx != NULL);
542
543 /*
544 * Clear Set-UID/Set-GID bits on successful write if not
545 * privileged and at least one of the execute bits is set.
546 *
547 * It would be nice to do this after all writes have
548 * been done, but that would still expose the ISUID/ISGID
549 * to another app after the partial write is committed.
550 *
551 * Note: we don't call zfs_fuid_map_id() here because
552 * user 0 is not an ephemeral uid.
553 */
554 mutex_enter(&zp->z_acl_lock);
555 if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) | (S_IXUSR >> 6))) != 0 &&
556 (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
557 secpolicy_vnode_setid_retain(zp, cr,
558 ((zp->z_mode & S_ISUID) != 0 && uid == 0)) != 0) {
559 uint64_t newmode;
560
561 zp->z_mode &= ~(S_ISUID | S_ISGID);
562 newmode = zp->z_mode;
563 (void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
564 (void *)&newmode, sizeof (uint64_t), tx);
565
566 mutex_exit(&zp->z_acl_lock);
567
568 /*
569 * Make sure SUID/SGID bits will be removed when we replay the
570 * log. If the setid bits are keep coming back, don't log more
571 * than one TX_SETATTR per transaction group.
572 */
573 if (*clear_setid_bits_txgp != dmu_tx_get_txg(tx)) {
574 vattr_t va = {0};
575
576 va.va_mask = ATTR_MODE;
577 va.va_nodeid = zp->z_id;
578 va.va_mode = newmode;
579 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, &va,
580 ATTR_MODE, NULL);
581 *clear_setid_bits_txgp = dmu_tx_get_txg(tx);
582 }
583 } else {
584 mutex_exit(&zp->z_acl_lock);
585 }
586 }
587
588 /*
589 * Write the bytes to a file.
590 *
591 * IN: zp - znode of file to be written to.
592 * uio - structure supplying write location, range info,
593 * and data buffer.
594 * ioflag - O_APPEND flag set if in append mode.
595 * O_DIRECT flag; used to bypass page cache.
596 * cr - credentials of caller.
597 *
598 * OUT: uio - updated offset and range.
599 *
600 * RETURN: 0 if success
601 * error code if failure
602 *
603 * Timestamps:
604 * ip - ctime|mtime updated if byte count > 0
605 */
606 int
zfs_write(znode_t * zp,zfs_uio_t * uio,int ioflag,cred_t * cr)607 zfs_write(znode_t *zp, zfs_uio_t *uio, int ioflag, cred_t *cr)
608 {
609 int error = 0, error1;
610 ssize_t start_resid = zfs_uio_resid(uio);
611 uint64_t clear_setid_bits_txg = 0;
612 boolean_t o_direct_defer = B_FALSE;
613
614 /*
615 * Fasttrack empty write
616 */
617 ssize_t n = start_resid;
618 if (n == 0)
619 return (0);
620
621 zfsvfs_t *zfsvfs = ZTOZSB(zp);
622 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
623 return (error);
624
625 sa_bulk_attr_t bulk[5];
626 int count = 0;
627 uint64_t mtime[2], ctime[2];
628 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
629 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
630 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
631 &zp->z_size, 8);
632 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
633 &zp->z_pflags, 8);
634 if (zp->z_is_sa)
635 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SEQ(zfsvfs), NULL,
636 &zp->z_seq, 8);
637
638 /*
639 * Callers might not be able to detect properly that we are read-only,
640 * so check it explicitly here.
641 */
642 if (zfs_is_readonly(zfsvfs)) {
643 zfs_exit(zfsvfs, FTAG);
644 return (SET_ERROR(EROFS));
645 }
646
647 /*
648 * If immutable or not appending then return EPERM.
649 * Intentionally allow ZFS_READONLY through here.
650 * See zfs_zaccess_common()
651 */
652 if ((zp->z_pflags & ZFS_IMMUTABLE) ||
653 ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & O_APPEND) &&
654 (zfs_uio_offset(uio) < zp->z_size))) {
655 zfs_exit(zfsvfs, FTAG);
656 return (SET_ERROR(EPERM));
657 }
658
659 /*
660 * Validate file offset
661 */
662 offset_t woff = ioflag & O_APPEND ? zp->z_size : zfs_uio_offset(uio);
663 if (woff < 0) {
664 zfs_exit(zfsvfs, FTAG);
665 return (SET_ERROR(EINVAL));
666 }
667
668 /*
669 * Setting up Direct I/O if requested.
670 */
671 error = zfs_setup_direct(zp, uio, UIO_WRITE, &ioflag);
672 if (error) {
673 zfs_exit(zfsvfs, FTAG);
674 return (SET_ERROR(error));
675 }
676
677 /*
678 * Pre-fault the pages to ensure slow (eg NFS) pages
679 * don't hold up txg.
680 */
681 ssize_t pfbytes = MIN(n, DMU_MAX_ACCESS >> 1);
682 if (zfs_uio_prefaultpages(pfbytes, uio)) {
683 zfs_exit(zfsvfs, FTAG);
684 return (SET_ERROR(EFAULT));
685 }
686
687 /*
688 * If in append mode, set the io offset pointer to eof.
689 */
690 zfs_locked_range_t *lr;
691 if (ioflag & O_APPEND) {
692 /*
693 * Obtain an appending range lock to guarantee file append
694 * semantics. We reset the write offset once we have the lock.
695 */
696 lr = zfs_rangelock_enter(&zp->z_rangelock, 0, n, RL_APPEND);
697 woff = lr->lr_offset;
698 if (lr->lr_length == UINT64_MAX) {
699 /*
700 * We overlocked the file because this write will cause
701 * the file block size to increase.
702 * Note that zp_size cannot change with this lock held.
703 */
704 woff = zp->z_size;
705 }
706 zfs_uio_setoffset(uio, woff);
707 /*
708 * We need to update the starting offset as well because it is
709 * set previously in the ZPL (Linux) and VNOPS (FreeBSD)
710 * layers.
711 */
712 zfs_uio_setsoffset(uio, woff);
713 } else {
714 /*
715 * Note that if the file block size will change as a result of
716 * this write, then this range lock will lock the entire file
717 * so that we can re-write the block safely.
718 */
719 lr = zfs_rangelock_enter(&zp->z_rangelock, woff, n, RL_WRITER);
720 }
721
722 if (zn_rlimit_fsize_uio(zp, uio)) {
723 zfs_rangelock_exit(lr);
724 zfs_exit(zfsvfs, FTAG);
725 return (SET_ERROR(EFBIG));
726 }
727
728 const rlim64_t limit = MAXOFFSET_T;
729
730 if (woff >= limit) {
731 zfs_rangelock_exit(lr);
732 zfs_exit(zfsvfs, FTAG);
733 return (SET_ERROR(EFBIG));
734 }
735
736 if (n > limit - woff)
737 n = limit - woff;
738
739 uint64_t end_size = MAX(zp->z_size, woff + n);
740 zilog_t *zilog = zfsvfs->z_log;
741 boolean_t commit = (ioflag & (O_SYNC | O_DSYNC)) ||
742 (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS);
743
744 const uint64_t uid = KUID_TO_SUID(ZTOUID(zp));
745 const uint64_t gid = KGID_TO_SGID(ZTOGID(zp));
746 const uint64_t projid = zp->z_projid;
747
748 /*
749 * In the event we are increasing the file block size
750 * (lr_length == UINT64_MAX), we will direct the write to the ARC.
751 * Because zfs_grow_blocksize() will read from the ARC in order to
752 * grow the dbuf, we avoid doing Direct I/O here as that would cause
753 * data written to disk to be overwritten by data in the ARC during
754 * the sync phase. Besides writing data twice to disk, we also
755 * want to avoid consistency concerns between data in the the ARC and
756 * on disk while growing the file's blocksize.
757 *
758 * We will only temporarily remove Direct I/O and put it back after
759 * we have grown the blocksize. We do this in the event a request
760 * is larger than max_blksz, so further requests to
761 * dmu_write_uio_dbuf() will still issue the requests using Direct
762 * IO.
763 *
764 * As an example:
765 * The first block to file is being written as a 4k request with
766 * a recorsize of 1K. The first 1K issued in the loop below will go
767 * through the ARC; however, the following 3 1K requests will
768 * use Direct I/O.
769 */
770 if (uio->uio_extflg & UIO_DIRECT && lr->lr_length == UINT64_MAX) {
771 uio->uio_extflg &= ~UIO_DIRECT;
772 o_direct_defer = B_TRUE;
773 }
774
775 /*
776 * Write the file in reasonable size chunks. Each chunk is written
777 * in a separate transaction; this keeps the intent log records small
778 * and allows us to do more fine-grained space accounting.
779 */
780 while (n > 0) {
781 woff = zfs_uio_offset(uio);
782
783 if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, uid) ||
784 zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, gid) ||
785 (projid != ZFS_DEFAULT_PROJID &&
786 zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
787 projid))) {
788 error = SET_ERROR(EDQUOT);
789 break;
790 }
791
792 uint64_t blksz;
793 if (lr->lr_length == UINT64_MAX && zp->z_size <= zp->z_blksz) {
794 if (zp->z_blksz > zfsvfs->z_max_blksz &&
795 !ISP2(zp->z_blksz)) {
796 /*
797 * File's blocksize is already larger than the
798 * "recordsize" property. Only let it grow to
799 * the next power of 2.
800 */
801 blksz = 1 << highbit64(zp->z_blksz);
802 } else {
803 blksz = zfsvfs->z_max_blksz;
804 }
805 blksz = MIN(blksz, P2ROUNDUP(end_size,
806 SPA_MINBLOCKSIZE));
807 blksz = MAX(blksz, zp->z_blksz);
808 } else {
809 blksz = zp->z_blksz;
810 }
811
812 arc_buf_t *abuf = NULL;
813 ssize_t nbytes = n;
814 if (n >= blksz && woff >= zp->z_size &&
815 P2PHASE(woff, blksz) == 0 &&
816 !(uio->uio_extflg & UIO_DIRECT) &&
817 (blksz >= SPA_OLD_MAXBLOCKSIZE || n < 4 * blksz)) {
818 /*
819 * This write covers a full block. "Borrow" a buffer
820 * from the dmu so that we can fill it before we enter
821 * a transaction. This avoids the possibility of
822 * holding up the transaction if the data copy hangs
823 * up on a pagefault (e.g., from an NFS server mapping).
824 */
825 abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
826 blksz);
827 ASSERT(abuf != NULL);
828 ASSERT(arc_buf_size(abuf) == blksz);
829 if ((error = zfs_uiocopy(abuf->b_data, blksz,
830 UIO_WRITE, uio, &nbytes))) {
831 dmu_return_arcbuf(abuf);
832 break;
833 }
834 ASSERT3S(nbytes, ==, blksz);
835 } else {
836 nbytes = MIN(n, (DMU_MAX_ACCESS >> 1) -
837 P2PHASE(woff, blksz));
838 if (pfbytes < nbytes) {
839 if (zfs_uio_prefaultpages(nbytes, uio)) {
840 error = SET_ERROR(EFAULT);
841 break;
842 }
843 pfbytes = nbytes;
844 }
845 }
846
847 /*
848 * Start a transaction.
849 */
850 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
851 dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
852 dmu_buf_impl_t *db = (dmu_buf_impl_t *)sa_get_db(zp->z_sa_hdl);
853 DB_DNODE_ENTER(db);
854 dmu_tx_hold_write_by_dnode(tx, DB_DNODE(db), woff, nbytes);
855 DB_DNODE_EXIT(db);
856 zfs_sa_upgrade_txholds(tx, zp);
857 error = dmu_tx_assign(tx, DMU_TX_WAIT);
858 if (error) {
859 dmu_tx_abort(tx);
860 if (abuf != NULL)
861 dmu_return_arcbuf(abuf);
862 break;
863 }
864
865 /*
866 * NB: We must call zfs_clear_setid_bits_if_necessary before
867 * committing the transaction!
868 */
869
870 /*
871 * If rangelock_enter() over-locked we grow the blocksize
872 * and then reduce the lock range. This will only happen
873 * on the first iteration since rangelock_reduce() will
874 * shrink down lr_length to the appropriate size.
875 */
876 if (lr->lr_length == UINT64_MAX) {
877 zfs_grow_blocksize(zp, blksz, tx);
878 zfs_rangelock_reduce(lr, woff, n);
879 }
880
881 dmu_flags_t dflags = DMU_READ_PREFETCH;
882 if (ioflag & O_DIRECT)
883 dflags |= DMU_UNCACHEDIO;
884 if (uio->uio_extflg & UIO_DIRECT)
885 dflags |= DMU_DIRECTIO;
886
887 ssize_t tx_bytes;
888 if (abuf == NULL) {
889 tx_bytes = zfs_uio_resid(uio);
890 zfs_uio_fault_disable(uio, B_TRUE);
891 error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
892 uio, nbytes, tx, dflags);
893 zfs_uio_fault_disable(uio, B_FALSE);
894 #ifdef __linux__
895 if (error == EFAULT) {
896 zfs_clear_setid_bits_if_necessary(zfsvfs, zp,
897 cr, &clear_setid_bits_txg, tx);
898 dmu_tx_commit(tx);
899 /*
900 * Account for partial writes before
901 * continuing the loop.
902 * Update needs to occur before the next
903 * zfs_uio_prefaultpages, or prefaultpages may
904 * error, and we may break the loop early.
905 */
906 n -= tx_bytes - zfs_uio_resid(uio);
907 /*
908 * The prefaulted pages still faulted, so force
909 * a re-prefault on the next pass. If they can
910 * no longer be faulted in (e.g. the calling
911 * process is exiting), zfs_uio_prefaultpages()
912 * fails and the loop breaks with EFAULT instead
913 * of spinning on them forever.
914 */
915 pfbytes = 0;
916 continue;
917 }
918 #endif
919 /*
920 * On FreeBSD, EFAULT should be propagated back to the
921 * VFS, which will handle faulting and will retry.
922 */
923 if (error != 0 && error != EFAULT) {
924 zfs_clear_setid_bits_if_necessary(zfsvfs, zp,
925 cr, &clear_setid_bits_txg, tx);
926 dmu_tx_commit(tx);
927 break;
928 }
929 tx_bytes -= zfs_uio_resid(uio);
930 } else {
931 /*
932 * Thus, we're writing a full block at a block-aligned
933 * offset and extending the file past EOF.
934 *
935 * dmu_assign_arcbuf_by_dbuf() will directly assign the
936 * arc buffer to a dbuf.
937 */
938 error = dmu_assign_arcbuf_by_dbuf(
939 sa_get_db(zp->z_sa_hdl), woff, abuf, tx, dflags);
940 if (error != 0) {
941 /*
942 * XXX This might not be necessary if
943 * dmu_assign_arcbuf_by_dbuf is guaranteed
944 * to be atomic.
945 */
946 zfs_clear_setid_bits_if_necessary(zfsvfs, zp,
947 cr, &clear_setid_bits_txg, tx);
948 dmu_return_arcbuf(abuf);
949 dmu_tx_commit(tx);
950 break;
951 }
952 ASSERT3S(nbytes, <=, zfs_uio_resid(uio));
953 zfs_uioskip(uio, nbytes);
954 tx_bytes = nbytes;
955 }
956 /*
957 * There is a window where a file's pages can be mmap'ed after
958 * zfs_setup_direct() is called. This is due to the fact that
959 * the rangelock in this function is acquired after calling
960 * zfs_setup_direct(). This is done so that
961 * zfs_uio_prefaultpages() does not attempt to fault in pages
962 * on Linux for Direct I/O requests. This is not necessary as
963 * the pages are pinned in memory and can not be faulted out.
964 * Ideally, the rangelock would be held before calling
965 * zfs_setup_direct() and zfs_uio_prefaultpages(); however,
966 * this can lead to a deadlock as zfs_getpage() also acquires
967 * the rangelock as a RL_WRITER and prefaulting the pages can
968 * lead to zfs_getpage() being called.
969 *
970 * In the case of the pages being mapped after
971 * zfs_setup_direct() is called, the call to update_pages()
972 * will still be made to make sure there is consistency between
973 * the ARC and the Linux page cache. This is an ufortunate
974 * situation as the data will be read back into the ARC after
975 * the Direct I/O write has completed, but this is the penality
976 * for writing to a mmap'ed region of a file using Direct I/O.
977 */
978 if (tx_bytes &&
979 zn_has_cached_data(zp, woff, woff + tx_bytes - 1)) {
980 update_pages(zp, woff, tx_bytes, zfsvfs->z_os);
981 }
982
983 /*
984 * If we made no progress, we're done. If we made even
985 * partial progress, update the znode and ZIL accordingly.
986 */
987 if (tx_bytes == 0) {
988 (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
989 (void *)&zp->z_size, sizeof (uint64_t), tx);
990 dmu_tx_commit(tx);
991 ASSERT(error != 0);
992 break;
993 }
994
995 zfs_clear_setid_bits_if_necessary(zfsvfs, zp, cr,
996 &clear_setid_bits_txg, tx);
997
998 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
999 if (zp->z_is_sa)
1000 zp->z_has_seq = B_TRUE;
1001
1002 /*
1003 * Update the file size (zp_size) if it has changed;
1004 * account for possible concurrent updates.
1005 */
1006 while ((end_size = zp->z_size) < zfs_uio_offset(uio)) {
1007 (void) atomic_cas_64(&zp->z_size, end_size,
1008 zfs_uio_offset(uio));
1009 ASSERT(error == 0 || error == EFAULT);
1010 }
1011 /*
1012 * If we are replaying and eof is non zero then force
1013 * the file size to the specified eof. Note, there's no
1014 * concurrency during replay.
1015 */
1016 if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
1017 zp->z_size = zfsvfs->z_replay_eof;
1018
1019 ASSERT3S(count, <=, ARRAY_SIZE(bulk));
1020 error1 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1021 if (error1 != 0)
1022 /* Avoid clobbering EFAULT. */
1023 error = error1;
1024
1025 /*
1026 * NB: During replay, the TX_SETATTR record logged by
1027 * zfs_clear_setid_bits_if_necessary must precede any of
1028 * the TX_WRITE records logged here.
1029 */
1030 zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, commit,
1031 uio->uio_extflg & UIO_DIRECT ? B_TRUE : B_FALSE, NULL,
1032 NULL);
1033
1034 dmu_tx_commit(tx);
1035
1036 /*
1037 * Direct I/O was deferred in order to grow the first block.
1038 * At this point it can be re-enabled for subsequent writes.
1039 */
1040 if (o_direct_defer) {
1041 ASSERT(ioflag & O_DIRECT);
1042 uio->uio_extflg |= UIO_DIRECT;
1043 o_direct_defer = B_FALSE;
1044 }
1045
1046 if (error != 0)
1047 break;
1048 ASSERT3S(tx_bytes, ==, nbytes);
1049 n -= nbytes;
1050 pfbytes -= nbytes;
1051 }
1052
1053 if (o_direct_defer) {
1054 ASSERT(ioflag & O_DIRECT);
1055 uio->uio_extflg |= UIO_DIRECT;
1056 o_direct_defer = B_FALSE;
1057 }
1058
1059 zfs_znode_update_vfs(zp);
1060 zfs_rangelock_exit(lr);
1061
1062 /*
1063 * Cleanup for Direct I/O if requested.
1064 */
1065 if (uio->uio_extflg & UIO_DIRECT)
1066 zfs_uio_free_dio_pages(uio, UIO_WRITE);
1067
1068 /*
1069 * If we're in replay mode, or we made no progress, or the
1070 * uio data is inaccessible return an error. Otherwise, it's
1071 * at least a partial write, so it's successful.
1072 */
1073 if (zfsvfs->z_replay || zfs_uio_resid(uio) == start_resid ||
1074 error == EFAULT) {
1075 zfs_exit(zfsvfs, FTAG);
1076 return (error);
1077 }
1078
1079 if (commit) {
1080 error = zil_commit(zilog, zp->z_id);
1081 if (error != 0) {
1082 zfs_exit(zfsvfs, FTAG);
1083 return (error);
1084 }
1085 }
1086
1087 int64_t nwritten = start_resid - zfs_uio_resid(uio);
1088 dataset_kstats_update_write_kstats(&zfsvfs->z_kstat, nwritten);
1089
1090 zfs_exit(zfsvfs, FTAG);
1091 return (0);
1092 }
1093
1094 /*
1095 * Check if a block should be skipped during rewrite.
1096 * Returns B_TRUE if block should be skipped.
1097 */
1098 static boolean_t
zfs_rewrite_skip(dmu_buf_t * db,objset_t * os,uint64_t flags)1099 zfs_rewrite_skip(dmu_buf_t *db, objset_t *os, uint64_t flags)
1100 {
1101 /*
1102 * This may be slightly stale and racy, but should be OK for
1103 * the advisory use.
1104 */
1105 blkptr_t *bp = dmu_buf_get_blkptr(db);
1106 if (bp == NULL)
1107 return (B_TRUE);
1108
1109 if (flags & ZFS_REWRITE_SKIP_SNAPSHOT) {
1110 if (dmu_objset_block_is_shared(os, bp))
1111 return (B_TRUE);
1112 }
1113
1114 if (flags & ZFS_REWRITE_SKIP_BRT) {
1115 if (brt_maybe_exists(os->os_spa, bp))
1116 return (B_TRUE);
1117 }
1118
1119 return (B_FALSE);
1120 }
1121
1122 /*
1123 * Rewrite a range of file as-is without modification.
1124 *
1125 * IN: zp - znode of file to be rewritten.
1126 * off - Offset of the range to rewrite.
1127 * len - Length of the range to rewrite.
1128 * flags - Random rewrite parameters.
1129 * arg - flags-specific argument.
1130 *
1131 * RETURN: 0 if success
1132 * error code if failure
1133 */
1134 int
zfs_rewrite(znode_t * zp,uint64_t off,uint64_t len,uint64_t flags,uint64_t arg)1135 zfs_rewrite(znode_t *zp, uint64_t off, uint64_t len, uint64_t flags,
1136 uint64_t arg)
1137 {
1138 int error;
1139
1140 #define ZFS_REWRITE_VALID_FLAGS \
1141 (ZFS_REWRITE_PHYSICAL | ZFS_REWRITE_SKIP_SNAPSHOT | \
1142 ZFS_REWRITE_SKIP_BRT)
1143
1144 if ((flags & ~ZFS_REWRITE_VALID_FLAGS) != 0 || arg != 0)
1145 return (SET_ERROR(EINVAL));
1146
1147 zfsvfs_t *zfsvfs = ZTOZSB(zp);
1148 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1149 return (error);
1150
1151 /* Check if physical rewrite is allowed */
1152 spa_t *spa = zfsvfs->z_os->os_spa;
1153 if ((flags & ZFS_REWRITE_PHYSICAL) &&
1154 !spa_feature_is_enabled(spa, SPA_FEATURE_PHYSICAL_REWRITE)) {
1155 zfs_exit(zfsvfs, FTAG);
1156 return (SET_ERROR(ENOTSUP));
1157 }
1158
1159 if (zfs_is_readonly(zfsvfs)) {
1160 zfs_exit(zfsvfs, FTAG);
1161 return (SET_ERROR(EROFS));
1162 }
1163
1164 if (off >= zp->z_size) {
1165 zfs_exit(zfsvfs, FTAG);
1166 return (0);
1167 }
1168 if (len == 0 || len > zp->z_size - off)
1169 len = zp->z_size - off;
1170
1171 /* Flush any mmap()'d data to disk */
1172 if (zn_has_cached_data(zp, off, off + len - 1))
1173 zn_flush_cached_data(zp, B_TRUE);
1174
1175 zfs_locked_range_t *lr;
1176 lr = zfs_rangelock_enter(&zp->z_rangelock, off, len, RL_WRITER);
1177
1178 const uint64_t uid = KUID_TO_SUID(ZTOUID(zp));
1179 const uint64_t gid = KGID_TO_SGID(ZTOGID(zp));
1180 const uint64_t projid = zp->z_projid;
1181
1182 dmu_buf_impl_t *db = (dmu_buf_impl_t *)sa_get_db(zp->z_sa_hdl);
1183 DB_DNODE_ENTER(db);
1184 dnode_t *dn = DB_DNODE(db);
1185
1186 uint64_t n, noff = off, nr = 0, nw = 0;
1187 while (len > 0) {
1188 /*
1189 * Rewrite only actual data, skipping any holes. This might
1190 * be inaccurate for dirty files, but we don't really care.
1191 */
1192 if (noff == off) {
1193 /* Find next data in the file. */
1194 error = dnode_next_offset(dn, 0, &noff, 1, 1, 0);
1195 if (error || noff >= off + len) {
1196 if (error == ESRCH) /* No more data. */
1197 error = 0;
1198 break;
1199 }
1200 ASSERT3U(noff, >=, off);
1201 len -= noff - off;
1202 off = noff;
1203
1204 /* Find where the data end. */
1205 error = dnode_next_offset(dn, DNODE_FIND_HOLE, &noff,
1206 1, 1, 0);
1207 if (error != 0)
1208 noff = off + len;
1209 }
1210 ASSERT3U(noff, >, off);
1211
1212 if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, uid) ||
1213 zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, gid) ||
1214 (projid != ZFS_DEFAULT_PROJID &&
1215 zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
1216 projid))) {
1217 error = SET_ERROR(EDQUOT);
1218 break;
1219 }
1220
1221 n = MIN(MIN(len, noff - off),
1222 DMU_MAX_ACCESS / 2 - P2PHASE(off, zp->z_blksz));
1223
1224 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
1225 dmu_tx_hold_write_by_dnode(tx, dn, off, n);
1226 error = dmu_tx_assign(tx, DMU_TX_WAIT);
1227 if (error) {
1228 dmu_tx_abort(tx);
1229 break;
1230 }
1231
1232 /* Mark all dbufs within range as dirty to trigger rewrite. */
1233 dmu_buf_t **dbp;
1234 int numbufs;
1235 error = dmu_buf_hold_array_by_dnode(dn, off, n, TRUE, FTAG,
1236 &numbufs, &dbp, DMU_READ_PREFETCH | DMU_UNCACHEDIO);
1237 if (error) {
1238 dmu_tx_commit(tx);
1239 break;
1240 }
1241 for (int i = 0; i < numbufs; i++) {
1242 nr += dbp[i]->db_size;
1243 if (dmu_buf_is_dirty(dbp[i], tx))
1244 continue;
1245
1246 if (zfs_rewrite_skip(dbp[i], zfsvfs->z_os, flags))
1247 continue;
1248
1249 nw += dbp[i]->db_size;
1250 if (flags & ZFS_REWRITE_PHYSICAL)
1251 dmu_buf_will_rewrite(dbp[i], tx);
1252 else
1253 dmu_buf_will_dirty(dbp[i], tx);
1254 }
1255 dmu_buf_rele_array(dbp, numbufs, FTAG);
1256
1257 dmu_tx_commit(tx);
1258
1259 len -= n;
1260 off += n;
1261
1262 if (issig()) {
1263 error = SET_ERROR(EINTR);
1264 break;
1265 }
1266 }
1267
1268 DB_DNODE_EXIT(db);
1269
1270 dataset_kstats_update_read_kstats(&zfsvfs->z_kstat, nr);
1271 dataset_kstats_update_write_kstats(&zfsvfs->z_kstat, nw);
1272
1273 zfs_rangelock_exit(lr);
1274 zfs_exit(zfsvfs, FTAG);
1275 return (error);
1276 }
1277
1278 int
zfs_getsecattr(znode_t * zp,vsecattr_t * vsecp,int flag,cred_t * cr)1279 zfs_getsecattr(znode_t *zp, vsecattr_t *vsecp, int flag, cred_t *cr)
1280 {
1281 zfsvfs_t *zfsvfs = ZTOZSB(zp);
1282 int error;
1283 boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
1284
1285 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1286 return (error);
1287 error = zfs_getacl(zp, vsecp, skipaclchk, cr);
1288 zfs_exit(zfsvfs, FTAG);
1289
1290 return (error);
1291 }
1292
1293 int
zfs_setsecattr(znode_t * zp,vsecattr_t * vsecp,int flag,cred_t * cr)1294 zfs_setsecattr(znode_t *zp, vsecattr_t *vsecp, int flag, cred_t *cr)
1295 {
1296 zfsvfs_t *zfsvfs = ZTOZSB(zp);
1297 int error;
1298 boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
1299 zilog_t *zilog;
1300
1301 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1302 return (error);
1303 zilog = zfsvfs->z_log;
1304 error = zfs_setacl(zp, vsecp, skipaclchk, cr);
1305
1306 if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1307 error = zil_commit(zilog, 0);
1308
1309 zfs_exit(zfsvfs, FTAG);
1310 return (error);
1311 }
1312
1313 /*
1314 * Get the optimal alignment to ensure direct IO can be performed without
1315 * incurring any RMW penalty on write. If direct IO is not enabled for this
1316 * file, returns an error.
1317 */
1318 int
zfs_get_direct_alignment(znode_t * zp,uint64_t * alignp)1319 zfs_get_direct_alignment(znode_t *zp, uint64_t *alignp)
1320 {
1321 zfsvfs_t *zfsvfs = ZTOZSB(zp);
1322
1323 if (!zfs_dio_enabled || zfsvfs->z_os->os_direct == ZFS_DIRECT_DISABLED)
1324 return (SET_ERROR(EOPNOTSUPP));
1325
1326 /*
1327 * If the file has multiple blocks, then its block size is fixed
1328 * forever, and so is the ideal alignment.
1329 *
1330 * If however it only has a single block, then we want to return the
1331 * max block size it could possibly grown to (ie, the dataset
1332 * recordsize). We do this so that a program querying alignment
1333 * immediately after the file is created gets a value that won't change
1334 * once the file has grown into the second block and beyond.
1335 *
1336 * Because we don't have a count of blocks easily available here, we
1337 * check if the apparent file size is smaller than its current block
1338 * size (meaning, the file hasn't yet grown into the current block
1339 * size) and then, check if the block size is smaller than the dataset
1340 * maximum (meaning, if the file grew past the current block size, the
1341 * block size could would be increased).
1342 */
1343 if (zp->z_size <= zp->z_blksz && zp->z_blksz < zfsvfs->z_max_blksz)
1344 *alignp = MAX(zfsvfs->z_max_blksz, PAGE_SIZE);
1345 else
1346 *alignp = MAX(zp->z_blksz, PAGE_SIZE);
1347
1348 return (0);
1349 }
1350
1351 #ifdef ZFS_DEBUG
1352 static int zil_fault_io = 0;
1353 #endif
1354
1355 static void zfs_get_done(zgd_t *zgd, int error);
1356
1357 /*
1358 * Get data to generate a TX_WRITE intent log record.
1359 */
1360 int
zfs_get_data(void * arg,uint64_t gen,lr_write_t * lr,char * buf,struct lwb * lwb,zio_t * zio)1361 zfs_get_data(void *arg, uint64_t gen, lr_write_t *lr, char *buf,
1362 struct lwb *lwb, zio_t *zio)
1363 {
1364 zfsvfs_t *zfsvfs = arg;
1365 objset_t *os = zfsvfs->z_os;
1366 znode_t *zp;
1367 uint64_t object = lr->lr_foid;
1368 uint64_t offset = lr->lr_offset;
1369 uint64_t size = lr->lr_length;
1370 zgd_t *zgd;
1371 int error = 0;
1372 uint64_t zp_gen;
1373
1374 ASSERT3P(lwb, !=, NULL);
1375 ASSERT3U(size, !=, 0);
1376
1377 /*
1378 * Nothing to do if the file has been removed
1379 */
1380 if (zfs_zget(zfsvfs, object, &zp) != 0)
1381 return (SET_ERROR(ENOENT));
1382 if (zp->z_unlinked) {
1383 /*
1384 * Release the vnode asynchronously as we currently have the
1385 * txg stopped from syncing.
1386 */
1387 zfs_zrele_async(zp);
1388 return (SET_ERROR(ENOENT));
1389 }
1390 /* check if generation number matches */
1391 if (sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs), &zp_gen,
1392 sizeof (zp_gen)) != 0) {
1393 zfs_zrele_async(zp);
1394 return (SET_ERROR(EIO));
1395 }
1396 if (zp_gen != gen) {
1397 zfs_zrele_async(zp);
1398 return (SET_ERROR(ENOENT));
1399 }
1400
1401 zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1402 zgd->zgd_lwb = lwb;
1403 zgd->zgd_private = zp;
1404
1405 /*
1406 * Write records come in two flavors: immediate and indirect.
1407 * For small writes it's cheaper to store the data with the
1408 * log record (immediate); for large writes it's cheaper to
1409 * sync the data and get a pointer to it (indirect) so that
1410 * we don't have to write the data twice.
1411 */
1412 if (buf != NULL) { /* immediate write */
1413 zgd->zgd_lr = zfs_rangelock_enter(&zp->z_rangelock, offset,
1414 size, RL_READER);
1415 /* test for truncation needs to be done while range locked */
1416 if (offset >= zp->z_size) {
1417 error = SET_ERROR(ENOENT);
1418 } else {
1419 error = dmu_read(os, object, offset, size, buf,
1420 DMU_READ_NO_PREFETCH | DMU_KEEP_CACHING);
1421 }
1422 ASSERT(error == 0 || error == ENOENT);
1423 } else { /* indirect write */
1424 ASSERT3P(zio, !=, NULL);
1425 /*
1426 * Have to lock the whole block to ensure when it's
1427 * written out and its checksum is being calculated
1428 * that no one can change the data. We need to re-check
1429 * blocksize after we get the lock in case it's changed!
1430 */
1431 for (;;) {
1432 uint64_t blkoff;
1433 size = zp->z_blksz;
1434 blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1435 offset -= blkoff;
1436 zgd->zgd_lr = zfs_rangelock_enter(&zp->z_rangelock,
1437 offset, size, RL_READER);
1438 if (zp->z_blksz == size)
1439 break;
1440 offset += blkoff;
1441 zfs_rangelock_exit(zgd->zgd_lr);
1442 }
1443 /* test for truncation needs to be done while range locked */
1444 if (lr->lr_offset >= zp->z_size)
1445 error = SET_ERROR(ENOENT);
1446 #ifdef ZFS_DEBUG
1447 if (zil_fault_io) {
1448 error = SET_ERROR(EIO);
1449 zil_fault_io = 0;
1450 }
1451 #endif
1452
1453 dmu_buf_t *dbp;
1454 if (error == 0)
1455 error = dmu_buf_hold_noread(os, object, offset, zgd,
1456 &dbp);
1457
1458 if (error == 0) {
1459 zgd->zgd_db = dbp;
1460 dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbp;
1461 boolean_t direct_write = B_FALSE;
1462 mutex_enter(&db->db_mtx);
1463 dbuf_dirty_record_t *dr =
1464 dbuf_find_dirty_eq(db, lr->lr_common.lrc_txg);
1465 if (dr != NULL && dr->dt.dl.dr_diowrite)
1466 direct_write = B_TRUE;
1467 mutex_exit(&db->db_mtx);
1468
1469 /*
1470 * All Direct I/O writes will have already completed and
1471 * the block pointer can be immediately stored in the
1472 * log record.
1473 */
1474 if (direct_write) {
1475 /*
1476 * A Direct I/O write always covers an entire
1477 * block.
1478 */
1479 ASSERT3U(dbp->db_size, ==, zp->z_blksz);
1480 lr->lr_blkptr = dr->dt.dl.dr_overridden_by;
1481 zfs_get_done(zgd, 0);
1482 return (0);
1483 }
1484
1485 blkptr_t *bp = &lr->lr_blkptr;
1486 zgd->zgd_bp = bp;
1487
1488 ASSERT3U(dbp->db_offset, ==, offset);
1489 ASSERT3U(dbp->db_size, ==, size);
1490
1491 error = dmu_sync(zio, lr->lr_common.lrc_txg,
1492 zfs_get_done, zgd);
1493 ASSERT(error || lr->lr_length <= size);
1494
1495 /*
1496 * On success, we need to wait for the write I/O
1497 * initiated by dmu_sync() to complete before we can
1498 * release this dbuf. We will finish everything up
1499 * in the zfs_get_done() callback.
1500 */
1501 if (error == 0)
1502 return (0);
1503
1504 if (error == EALREADY) {
1505 lr->lr_common.lrc_txtype = TX_WRITE2;
1506 /*
1507 * TX_WRITE2 relies on the data previously
1508 * written by the TX_WRITE that caused
1509 * EALREADY. We zero out the BP because
1510 * it is the old, currently-on-disk BP.
1511 */
1512 zgd->zgd_bp = NULL;
1513 BP_ZERO(bp);
1514 error = 0;
1515 }
1516 }
1517 }
1518
1519 zfs_get_done(zgd, error);
1520
1521 return (error);
1522 }
1523
1524 static void
zfs_get_done(zgd_t * zgd,int error)1525 zfs_get_done(zgd_t *zgd, int error)
1526 {
1527 (void) error;
1528 znode_t *zp = zgd->zgd_private;
1529
1530 if (zgd->zgd_db)
1531 dmu_buf_rele(zgd->zgd_db, zgd);
1532
1533 zfs_rangelock_exit(zgd->zgd_lr);
1534
1535 /*
1536 * Release the vnode asynchronously as we currently have the
1537 * txg stopped from syncing.
1538 */
1539 zfs_zrele_async(zp);
1540
1541 kmem_free(zgd, sizeof (zgd_t));
1542 }
1543
1544 static int
zfs_enter_two(zfsvfs_t * zfsvfs1,zfsvfs_t * zfsvfs2,const char * tag)1545 zfs_enter_two(zfsvfs_t *zfsvfs1, zfsvfs_t *zfsvfs2, const char *tag)
1546 {
1547 int error;
1548
1549 /* Swap. Not sure if the order of zfs_enter()s is important. */
1550 if (zfsvfs1 > zfsvfs2) {
1551 zfsvfs_t *tmpzfsvfs;
1552
1553 tmpzfsvfs = zfsvfs2;
1554 zfsvfs2 = zfsvfs1;
1555 zfsvfs1 = tmpzfsvfs;
1556 }
1557
1558 error = zfs_enter(zfsvfs1, tag);
1559 if (error != 0)
1560 return (error);
1561 if (zfsvfs1 != zfsvfs2) {
1562 error = zfs_enter(zfsvfs2, tag);
1563 if (error != 0) {
1564 zfs_exit(zfsvfs1, tag);
1565 return (error);
1566 }
1567 }
1568
1569 return (0);
1570 }
1571
1572 static void
zfs_exit_two(zfsvfs_t * zfsvfs1,zfsvfs_t * zfsvfs2,const char * tag)1573 zfs_exit_two(zfsvfs_t *zfsvfs1, zfsvfs_t *zfsvfs2, const char *tag)
1574 {
1575
1576 zfs_exit(zfsvfs1, tag);
1577 if (zfsvfs1 != zfsvfs2)
1578 zfs_exit(zfsvfs2, tag);
1579 }
1580
1581 /*
1582 * Checks shared by zfs_clone_range() and zfs_dedupe_range() that do not
1583 * depend on the offsets or length of the request. Both datasets must
1584 * already be entered with zfs_enter_two().
1585 */
1586 static int
zfs_clone_range_precheck(znode_t * inzp,znode_t * outzp)1587 zfs_clone_range_precheck(znode_t *inzp, znode_t *outzp)
1588 {
1589 zfsvfs_t *inzfsvfs = ZTOZSB(inzp);
1590 zfsvfs_t *outzfsvfs = ZTOZSB(outzp);
1591 objset_t *inos = inzfsvfs->z_os;
1592 objset_t *outos = outzfsvfs->z_os;
1593 int error;
1594
1595 /*
1596 * Both source and destination have to belong to the same storage pool.
1597 */
1598 if (dmu_objset_spa(inos) != dmu_objset_spa(outos))
1599 return (SET_ERROR(EXDEV));
1600
1601 /*
1602 * outos and inos belongs to the same storage pool.
1603 * see a few lines above, only one check.
1604 */
1605 if (!spa_feature_is_enabled(dmu_objset_spa(outos),
1606 SPA_FEATURE_BLOCK_CLONING))
1607 return (SET_ERROR(EOPNOTSUPP));
1608
1609 ASSERT(!outzfsvfs->z_replay);
1610
1611 /*
1612 * Block cloning from an unencrypted dataset into an encrypted
1613 * dataset and vice versa is not supported.
1614 */
1615 if (inos->os_encrypted != outos->os_encrypted)
1616 return (SET_ERROR(EXDEV));
1617
1618 /*
1619 * Cloning across encrypted datasets is possible only if they
1620 * share the same master key.
1621 */
1622 if (inos != outos && inos->os_encrypted &&
1623 !dmu_objset_crypto_key_equal(inos, outos))
1624 return (SET_ERROR(EXDEV));
1625
1626 /*
1627 * Cloning between datasets with different properties is possible,
1628 * but it may cause confusions when copying data between them and
1629 * expecting new properties to apply.
1630 */
1631 if (zfs_bclone_strict_properties && inos != outos &&
1632 !inzfsvfs->z_issnap &&
1633 (inos->os_checksum != outos->os_checksum ||
1634 inos->os_compress != outos->os_compress ||
1635 inos->os_copies != outos->os_copies ||
1636 inos->os_dedup_checksum != outos->os_dedup_checksum))
1637 return (SET_ERROR(EXDEV));
1638
1639 error = zfs_verify_zp(inzp);
1640 if (error == 0)
1641 error = zfs_verify_zp(outzp);
1642 if (error != 0)
1643 return (error);
1644
1645 /*
1646 * We don't copy source file's flags that's why we don't allow to clone
1647 * files that are in quarantine.
1648 */
1649 if (inzp->z_pflags & ZFS_AV_QUARANTINED)
1650 return (SET_ERROR(EACCES));
1651
1652 return (0);
1653 }
1654
1655 /*
1656 * Clone a range of blocks from inzp into outzp. The caller must have entered
1657 * both datasets, resolved the request against the source EOF, and be holding a
1658 * RL_READER range lock on inzp and a RL_WRITER range lock (outlr) on outzp.
1659 * The number of bytes cloned is returned via donep; the caller is responsible
1660 * for the trailing accounting (access time, zil_commit) and for dropping the
1661 * range locks.
1662 *
1663 * When dedup is set the caller is implementing FIDEDUPERANGE, where the file
1664 * content is unchanged: in that case we must not update the destination's
1665 * mtime/ctime or strip its setid bits, matching the Linux convention that
1666 * REMAP_FILE_DEDUP skips file_modified().
1667 */
1668 static int
zfs_clone_range_locked(znode_t * inzp,uint64_t inoff,znode_t * outzp,uint64_t outoff,uint64_t len,cred_t * cr,zfs_locked_range_t * outlr,boolean_t dedup,uint64_t * donep)1669 zfs_clone_range_locked(znode_t *inzp, uint64_t inoff, znode_t *outzp,
1670 uint64_t outoff, uint64_t len, cred_t *cr, zfs_locked_range_t *outlr,
1671 boolean_t dedup, uint64_t *donep)
1672 {
1673 zfsvfs_t *inzfsvfs = ZTOZSB(inzp);
1674 zfsvfs_t *outzfsvfs = ZTOZSB(outzp);
1675 objset_t *inos = inzfsvfs->z_os;
1676 objset_t *outos = outzfsvfs->z_os;
1677 dmu_buf_impl_t *db;
1678 dmu_tx_t *tx;
1679 zilog_t *zilog = outzfsvfs->z_log;
1680 uint64_t done = 0;
1681 uint64_t outsize, size;
1682 int error = 0;
1683 int count = 0;
1684 sa_bulk_attr_t bulk[5];
1685 uint64_t mtime[2], ctime[2];
1686 uint64_t uid, gid, projid;
1687 blkptr_t *bps;
1688 size_t maxblocks, nbps;
1689 uint_t inblksz;
1690 uint64_t clear_setid_bits_txg = 0;
1691 uint64_t last_synced_txg = 0;
1692
1693 *donep = 0;
1694
1695 inblksz = inzp->z_blksz;
1696
1697 /*
1698 * Cloning between datasets with different special_small_blocks would
1699 * bypass storage tier migration that would occur with a regular copy.
1700 */
1701 if (zfs_bclone_strict_properties && inos != outos &&
1702 !inzfsvfs->z_issnap && spa_has_special(dmu_objset_spa(inos))) {
1703 uint64_t in_smallblk = inos->os_zpl_special_smallblock;
1704 uint64_t out_smallblk = outos->os_zpl_special_smallblock;
1705 if (in_smallblk != out_smallblk) {
1706 uint64_t min_smallblk = MIN(in_smallblk, out_smallblk);
1707 uint64_t max_smallblk = MAX(in_smallblk, out_smallblk);
1708 if (min_smallblk < inblksz &&
1709 (inos->os_compress != ZIO_COMPRESS_OFF ||
1710 max_smallblk >= inblksz)) {
1711 return (SET_ERROR(EXDEV));
1712 }
1713 }
1714 }
1715
1716 /*
1717 * We cannot clone into a file with different block size if we can't
1718 * grow it (block size is already bigger, has more than one block, or
1719 * not locked for growth). There are other possible reasons for the
1720 * grow to fail, but we cover what we can before opening transaction
1721 * and the rest detect after we try to do it.
1722 */
1723 if (inblksz < outzp->z_blksz)
1724 return (SET_ERROR(EINVAL));
1725 if (inblksz != outzp->z_blksz && (outzp->z_size > outzp->z_blksz ||
1726 outlr->lr_length != UINT64_MAX))
1727 return (SET_ERROR(EINVAL));
1728
1729 /*
1730 * Block size must be power-of-2 if destination offset != 0.
1731 * There can be no multiple blocks of non-power-of-2 size.
1732 */
1733 if (outoff != 0 && !ISP2(inblksz))
1734 return (SET_ERROR(EINVAL));
1735
1736 /*
1737 * Offsets and len must be at block boundries.
1738 */
1739 if ((inoff % inblksz) != 0 || (outoff % inblksz) != 0)
1740 return (SET_ERROR(EINVAL));
1741 /*
1742 * Length must be multipe of blksz, except for the end of the file.
1743 */
1744 if ((len % inblksz) != 0 &&
1745 (len < inzp->z_size - inoff || len < outzp->z_size - outoff))
1746 return (SET_ERROR(EINVAL));
1747
1748 /*
1749 * If we are copying only one block and it is smaller than recordsize
1750 * property, do not allow destination to grow beyond one block if it
1751 * is not there yet. Otherwise the destination will get stuck with
1752 * that block size forever, that can be as small as 512 bytes, no
1753 * matter how big the destination grow later.
1754 */
1755 if (len <= inblksz && inblksz < outzfsvfs->z_max_blksz &&
1756 outzp->z_size <= inblksz && outoff + len > inblksz)
1757 return (SET_ERROR(EINVAL));
1758
1759 error = zn_rlimit_fsize(outoff + len);
1760 if (error != 0)
1761 return (error);
1762
1763 if (inoff >= MAXOFFSET_T || outoff >= MAXOFFSET_T)
1764 return (SET_ERROR(EFBIG));
1765
1766 /*
1767 * A dedupe leaves the destination's content and metadata alone: it can
1768 * only replace blocks with identical ones. The times must not move,
1769 * and size, flags and seq cannot change either - a dedupe never extends
1770 * the file, never clears setid bits and never bumps z_seq - so there is
1771 * nothing to write back at all.
1772 */
1773 if (!dedup) {
1774 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(outzfsvfs), NULL,
1775 &mtime, 16);
1776 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(outzfsvfs), NULL,
1777 &ctime, 16);
1778 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(outzfsvfs), NULL,
1779 &outzp->z_size, 8);
1780 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(outzfsvfs), NULL,
1781 &outzp->z_pflags, 8);
1782 if (outzp->z_is_sa)
1783 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SEQ(outzfsvfs),
1784 NULL, &outzp->z_seq, 8);
1785 }
1786
1787 maxblocks = zil_max_log_data(zilog, sizeof (lr_clone_range_t)) /
1788 sizeof (bps[0]);
1789
1790 uid = KUID_TO_SUID(ZTOUID(outzp));
1791 gid = KGID_TO_SGID(ZTOGID(outzp));
1792 projid = outzp->z_projid;
1793
1794 bps = vmem_alloc(sizeof (bps[0]) * maxblocks, KM_SLEEP);
1795
1796 /*
1797 * Clone the file in reasonable size chunks. Each chunk is cloned
1798 * in a separate transaction; this keeps the intent log records small
1799 * and allows us to do more fine-grained space accounting.
1800 */
1801 while (len > 0) {
1802 size = MIN(inblksz * maxblocks, len);
1803
1804 if (zfs_id_overblockquota(outzfsvfs, DMU_USERUSED_OBJECT,
1805 uid) ||
1806 zfs_id_overblockquota(outzfsvfs, DMU_GROUPUSED_OBJECT,
1807 gid) ||
1808 (projid != ZFS_DEFAULT_PROJID &&
1809 zfs_id_overblockquota(outzfsvfs, DMU_PROJECTUSED_OBJECT,
1810 projid))) {
1811 error = SET_ERROR(EDQUOT);
1812 break;
1813 }
1814
1815 nbps = maxblocks;
1816 last_synced_txg = spa_last_synced_txg(dmu_objset_spa(inos));
1817 error = dmu_read_l0_bps(inos, inzp->z_id, inoff, size, bps,
1818 &nbps);
1819 if (error != 0) {
1820 /*
1821 * If we are trying to clone a block that was created
1822 * in the current transaction group, the error will be
1823 * EAGAIN here. Based on zfs_bclone_wait_dirty either
1824 * return a shortened range to the caller so it can
1825 * fallback, or wait for the next TXG and check again.
1826 * A dedupe always waits: it has no fallback, so the
1827 * EAGAIN would surface to the FIDEDUPERANGE caller,
1828 * and the comparison already read this very data.
1829 */
1830 if (error == EAGAIN &&
1831 (dedup || zfs_bclone_wait_dirty)) {
1832 txg_wait_flag_t wait_flags =
1833 spa_get_failmode(dmu_objset_spa(inos)) ==
1834 ZIO_FAILURE_MODE_CONTINUE ?
1835 TXG_WAIT_SUSPEND : 0;
1836 error = txg_wait_synced_flags(
1837 dmu_objset_pool(inos), last_synced_txg + 1,
1838 wait_flags);
1839 if (error == 0)
1840 continue;
1841 ASSERT3U(error, ==, ESHUTDOWN);
1842 error = SET_ERROR(EIO);
1843 }
1844
1845 break;
1846 }
1847
1848 /*
1849 * Start a transaction.
1850 */
1851 tx = dmu_tx_create(outos);
1852 dmu_tx_hold_sa(tx, outzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(outzp));
1853 db = (dmu_buf_impl_t *)sa_get_db(outzp->z_sa_hdl);
1854 DB_DNODE_ENTER(db);
1855 dmu_tx_hold_clone_by_dnode(tx, DB_DNODE(db), outoff, size,
1856 inblksz);
1857 DB_DNODE_EXIT(db);
1858 zfs_sa_upgrade_txholds(tx, outzp);
1859 error = dmu_tx_assign(tx, DMU_TX_WAIT);
1860 if (error != 0) {
1861 dmu_tx_abort(tx);
1862 break;
1863 }
1864
1865 /*
1866 * Copy source znode's block size. This is done only if the
1867 * whole znode is locked (see zfs_rangelock_cb()) and only
1868 * on the first iteration since zfs_rangelock_reduce() will
1869 * shrink down lr_length to the appropriate size.
1870 */
1871 if (outlr->lr_length == UINT64_MAX) {
1872 zfs_grow_blocksize(outzp, inblksz, tx);
1873
1874 /*
1875 * Block growth may fail for many reasons we can not
1876 * predict here. If it happens, the cloning is doomed.
1877 */
1878 if (inblksz != outzp->z_blksz) {
1879 error = SET_ERROR(EINVAL);
1880 dmu_tx_commit(tx);
1881 break;
1882 }
1883
1884 /*
1885 * Round range lock up to the block boundary, so we
1886 * prevent appends until we are done.
1887 */
1888 zfs_rangelock_reduce(outlr, outoff,
1889 ((len - 1) / inblksz + 1) * inblksz);
1890 }
1891
1892 error = dmu_brt_clone(outos, outzp->z_id, outoff, size, tx,
1893 bps, nbps);
1894 if (error != 0) {
1895 dmu_tx_commit(tx);
1896 break;
1897 }
1898
1899 /*
1900 * A dedupe replaces the destination's blocks with blocks
1901 * holding the same bytes, so a page already cached for this
1902 * range stays correct and there is nothing to refresh. The
1903 * only page whose contents can differ from the DMU is one
1904 * carrying an mmap store made after the pre-compare flush,
1905 * and refreshing that would discard the store, which is a
1906 * modification a dedupe must never make.
1907 */
1908 if (!dedup &&
1909 zn_has_cached_data(outzp, outoff, outoff + size - 1)) {
1910 update_pages(outzp, outoff, size, outos);
1911 }
1912
1913 if (!dedup) {
1914 zfs_clear_setid_bits_if_necessary(outzfsvfs, outzp, cr,
1915 &clear_setid_bits_txg, tx);
1916
1917 zfs_tstamp_update_setup(outzp, CONTENT_MODIFIED, mtime,
1918 ctime);
1919
1920 if (outzp->z_is_sa)
1921 outzp->z_has_seq = B_TRUE;
1922
1923 /*
1924 * Update the file size (zp_size) if it has changed;
1925 * account for possible concurrent updates.
1926 */
1927 while ((outsize = outzp->z_size) < outoff + size) {
1928 (void) atomic_cas_64(&outzp->z_size, outsize,
1929 outoff + size);
1930 }
1931 } else {
1932 /* A dedupe can only ever rewrite blocks in place. */
1933 ASSERT3U(outoff + size, <=, outzp->z_size);
1934 }
1935
1936 if (count > 0) {
1937 ASSERT3S(count, <=, ARRAY_SIZE(bulk));
1938 error = sa_bulk_update(outzp->z_sa_hdl, bulk, count,
1939 tx);
1940 }
1941
1942 /*
1943 * A dedupe is not logged. It replaces the destination's blocks
1944 * with blocks holding the very same bytes, so if the txg is
1945 * lost to a crash and never replayed, the destination simply
1946 * keeps its own copy of that identical content: nothing a
1947 * reader can observe is lost, only the sharing. Sharing is all
1948 * FIDEDUPERANGE promises anyway, and it is the cheaper of the
1949 * alternatives. Logging a plain TX_CLONE_RANGE would restamp
1950 * the destination's mtime/ctime on replay, and telling a dedupe
1951 * apart with a record of its own would be an on-disk ZIL format
1952 * change: an old kernel meeting an unknown txtype fails
1953 * zil_parse(), and zil_replay() then destroys the whole log,
1954 * discarding every later record - including synced writes.
1955 */
1956 if (!dedup) {
1957 zfs_log_clone_range(zilog, tx, TX_CLONE_RANGE, outzp,
1958 outoff, size, inblksz, bps, nbps);
1959 }
1960
1961 dmu_tx_commit(tx);
1962
1963 if (error != 0)
1964 break;
1965
1966 inoff += size;
1967 outoff += size;
1968 len -= size;
1969 done += size;
1970
1971 if (issig()) {
1972 error = SET_ERROR(EINTR);
1973 break;
1974 }
1975 }
1976
1977 vmem_free(bps, sizeof (bps[0]) * maxblocks);
1978 zfs_znode_update_vfs(outzp);
1979
1980 *donep = done;
1981
1982 return (error);
1983 }
1984
1985 /*
1986 * Clone part of inzp file into outzp file. This must be done under range locks
1987 * held on both files so as to prevent it from being modified while the clone
1988 * takes place.
1989 *
1990 * Copies bytes from inzp->inoffp to outzp->outoffp, up to *lenp bytes. On
1991 * entry *lenp holds the requested length; on successful return it holds the
1992 * number of bytes actually cloned, and inoffp/outoffp are advanced by that
1993 * amount.
1994 *
1995 * If we make no progress at all, then the caller made a mistake or asked for
1996 * something impossible, and EINVAL (or another appropriate error) is returned.
1997 *
1998 * Note, it doesn't return how many bytes are left to be copied.
1999 * On errors which are caused by any file system limitations or
2000 * BRT limitations EINVAL is returned. In the most cases a user
2001 * requested bad parameters, it could be possible to clone the file but
2002 * some parameters don't match the requirements.
2003 */
2004 int
zfs_clone_range(znode_t * inzp,uint64_t * inoffp,znode_t * outzp,uint64_t * outoffp,uint64_t * lenp,cred_t * cr)2005 zfs_clone_range(znode_t *inzp, uint64_t *inoffp, znode_t *outzp,
2006 uint64_t *outoffp, uint64_t *lenp, cred_t *cr)
2007 {
2008 zfsvfs_t *inzfsvfs = ZTOZSB(inzp);
2009 zfsvfs_t *outzfsvfs = ZTOZSB(outzp);
2010 zfs_locked_range_t *inlr, *outlr;
2011 zilog_t *zilog;
2012 uint64_t inoff = *inoffp;
2013 uint64_t outoff = *outoffp;
2014 uint64_t len = *lenp;
2015 uint64_t done = 0;
2016 int error;
2017
2018 /*
2019 * We need to call zfs_enter() potentially on two different datasets,
2020 * so we need a dedicated function for that.
2021 */
2022 error = zfs_enter_two(inzfsvfs, outzfsvfs, FTAG);
2023 if (error != 0)
2024 return (error);
2025
2026 /*
2027 * Read z_log only after entering, so a suspend/resume (rollback,
2028 * zfs receive -F) cannot leave us with a stale or freed zilog.
2029 */
2030 zilog = outzfsvfs->z_log;
2031
2032 error = zfs_clone_range_precheck(inzp, outzp);
2033 if (error != 0)
2034 goto out;
2035
2036 /*
2037 * The range to clone must lie within the source file. Clamp it to the
2038 * source EOF and treat an empty range as a no-op.
2039 */
2040 if (inoff >= inzp->z_size) {
2041 *lenp = 0;
2042 goto out;
2043 }
2044 if (len > inzp->z_size - inoff)
2045 len = inzp->z_size - inoff;
2046 if (len == 0) {
2047 *lenp = 0;
2048 goto out;
2049 }
2050
2051 /*
2052 * Callers might not be able to detect properly that we are read-only,
2053 * so check it explicitly here.
2054 */
2055 if (zfs_is_readonly(outzfsvfs)) {
2056 error = SET_ERROR(EROFS);
2057 goto out;
2058 }
2059
2060 /*
2061 * If immutable then return EPERM. Intentionally allow ZFS_READONLY
2062 * through here. See zfs_zaccess_common().
2063 */
2064 if ((outzp->z_pflags & ZFS_IMMUTABLE) != 0) {
2065 error = SET_ERROR(EPERM);
2066 goto out;
2067 }
2068
2069 /*
2070 * No overlapping if we are cloning within the same file.
2071 */
2072 if (inzp == outzp) {
2073 if (inoff < outoff + len && outoff < inoff + len) {
2074 error = SET_ERROR(EINVAL);
2075 goto out;
2076 }
2077 }
2078
2079 /* Flush any mmap()'d data to disk */
2080 if (zn_has_cached_data(inzp, inoff, inoff + len - 1))
2081 zn_flush_cached_data(inzp, B_TRUE);
2082
2083 /*
2084 * Maintain predictable lock order.
2085 */
2086 if (inzp < outzp || (inzp == outzp && inoff < outoff)) {
2087 inlr = zfs_rangelock_enter(&inzp->z_rangelock, inoff, len,
2088 RL_READER);
2089 outlr = zfs_rangelock_enter(&outzp->z_rangelock, outoff, len,
2090 RL_WRITER);
2091 } else {
2092 outlr = zfs_rangelock_enter(&outzp->z_rangelock, outoff, len,
2093 RL_WRITER);
2094 inlr = zfs_rangelock_enter(&inzp->z_rangelock, inoff, len,
2095 RL_READER);
2096 }
2097
2098 error = zfs_clone_range_locked(inzp, inoff, outzp, outoff, len, cr,
2099 outlr, B_FALSE, &done);
2100
2101 zfs_rangelock_exit(outlr);
2102 zfs_rangelock_exit(inlr);
2103
2104 if (done > 0) {
2105 /*
2106 * If we have made at least partial progress, reset the error.
2107 */
2108 error = 0;
2109
2110 ZFS_ACCESSTIME_STAMP(inzfsvfs, inzp);
2111
2112 if (outzfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2113 error = zil_commit(zilog, outzp->z_id);
2114
2115 *inoffp += done;
2116 *outoffp += done;
2117 *lenp = done;
2118 } else {
2119 /*
2120 * If we made no progress, there must be a good reason.
2121 * EOF is handled explicitly above, before the loop.
2122 */
2123 ASSERT3S(error, !=, 0);
2124 }
2125
2126 out:
2127 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG);
2128
2129 return (error);
2130 }
2131
2132 /*
2133 * Compare two ranges by copying them out of the DMU into buffers and comparing
2134 * those. Only used where the dbuf comparison below cannot go; see there.
2135 */
2136 static int
zfs_dedupe_range_copy_memcmp(znode_t * inzp,uint64_t inoff,znode_t * outzp,uint64_t outoff,uint64_t len,boolean_t * eqp)2137 zfs_dedupe_range_copy_memcmp(znode_t *inzp, uint64_t inoff, znode_t *outzp,
2138 uint64_t outoff, uint64_t len, boolean_t *eqp)
2139 {
2140 objset_t *inos = ZTOZSB(inzp)->z_os;
2141 objset_t *outos = ZTOZSB(outzp)->z_os;
2142 uint64_t chunk = MIN(len, (uint64_t)zfs_vnops_read_chunk_size);
2143 char *inbuf, *outbuf;
2144 int error = 0;
2145
2146 *eqp = B_FALSE;
2147
2148 inbuf = vmem_alloc(chunk, KM_SLEEP);
2149 outbuf = vmem_alloc(chunk, KM_SLEEP);
2150
2151 while (len > 0) {
2152 uint64_t n = MIN(len, chunk);
2153
2154 if (issig()) {
2155 error = SET_ERROR(EINTR);
2156 break;
2157 }
2158
2159 error = dmu_read(inos, inzp->z_id, inoff, n, inbuf,
2160 DMU_READ_PREFETCH);
2161 if (error != 0)
2162 break;
2163 error = dmu_read(outos, outzp->z_id, outoff, n, outbuf,
2164 DMU_READ_PREFETCH);
2165 if (error != 0)
2166 break;
2167
2168 if (memcmp(inbuf, outbuf, n) != 0)
2169 break;
2170
2171 inoff += n;
2172 outoff += n;
2173 len -= n;
2174 }
2175
2176 if (error == 0 && len == 0)
2177 *eqp = B_TRUE;
2178
2179 vmem_free(inbuf, chunk);
2180 vmem_free(outbuf, chunk);
2181
2182 return (error);
2183 }
2184
2185 /*
2186 * Compare [inoff, inoff + len) in inzp with [outoff, outoff + len) in outzp by
2187 * reading the committed on-disk data through the DMU (the same data
2188 * zfs_clone_range_locked() will clone) and byte-comparing it. Both files must
2189 * be range locked by the caller. On return *eqp is set if the ranges are
2190 * byte-for-byte equal. This is the authoritative (and always-correct) path;
2191 * the DMU serves holes as zeros and decrypts transparently, so it needs no
2192 * special-casing for encryption, holes or embedded blocks.
2193 *
2194 * The comparison is done on the dbufs themselves. dmu_read() would only hold
2195 * the very same buffers and memcpy() out of them, so going through it would
2196 * cost two allocations and a copy of every byte, for nothing: we are not
2197 * keeping the data, only looking at it. Our range locks keep it still while
2198 * we do.
2199 */
2200 static int
zfs_dedupe_range_memcmp(znode_t * inzp,uint64_t inoff,znode_t * outzp,uint64_t outoff,uint64_t len,boolean_t * eqp)2201 zfs_dedupe_range_memcmp(znode_t *inzp, uint64_t inoff, znode_t *outzp,
2202 uint64_t outoff, uint64_t len, boolean_t *eqp)
2203 {
2204 objset_t *inos = ZTOZSB(inzp)->z_os;
2205 objset_t *outos = ZTOZSB(outzp)->z_os;
2206 dnode_t *indn, *outdn;
2207 uint64_t blksz, chunk;
2208 boolean_t diff = B_FALSE;
2209 int error;
2210
2211 *eqp = B_FALSE;
2212
2213 error = dnode_hold(inos, inzp->z_id, FTAG, &indn);
2214 if (error != 0)
2215 return (error);
2216 error = dnode_hold(outos, outzp->z_id, FTAG, &outdn);
2217 if (error != 0) {
2218 dnode_rele(indn, FTAG);
2219 return (error);
2220 }
2221
2222 /*
2223 * dmu_buf_hold_array_by_dnode() refuses to look past a single block
2224 * whose size is not a power of two, calling zfs_panic_recover() rather
2225 * than serving the tail as zeros the way dmu_read() does. A ZPL file
2226 * should never present that shape - zfs_grow_blocksize() only leaves a
2227 * block size alone once the file has outgrown it, so an odd-sized block
2228 * means the file still fits inside it and the range cannot reach past
2229 * it. Should one turn up regardless, fall back to copying rather than
2230 * add another way to take the pool down. Our caller reaches
2231 * dmu_read_l0_bps() first, which holds the same buffers and would trip
2232 * over such a file before we ever got here, so in practice this only
2233 * catches what gets past that on a pool running with zfs_recover set.
2234 */
2235 if ((indn->dn_datablkshift == 0 && inoff + len > indn->dn_datablksz) ||
2236 (outdn->dn_datablkshift == 0 &&
2237 outoff + len > outdn->dn_datablksz)) {
2238 dnode_rele(outdn, FTAG);
2239 dnode_rele(indn, FTAG);
2240 return (zfs_dedupe_range_copy_memcmp(inzp, inoff, outzp,
2241 outoff, len, eqp));
2242 }
2243
2244 /*
2245 * A block is read and decompressed in full whatever part of it we ask
2246 * for, so a chunk below the block size would buy nothing and only hold
2247 * the same buffer once per piece of it. Take whole blocks, at least
2248 * one, capped the way zfs_read() caps its own chunk so that a large
2249 * request does not pin an unbounded stretch of the ARC.
2250 *
2251 * zfs_dedupe_range() has already refused an unaligned range, so each
2252 * buffer we are handed begins at the offset we are comparing.
2253 */
2254 blksz = indn->dn_datablksz;
2255 ASSERT3U(outdn->dn_datablksz, ==, blksz);
2256 chunk = MAX(1, MIN(zfs_vnops_read_chunk_size, DMU_MAX_ACCESS / 2) /
2257 blksz) * blksz;
2258
2259 while (len > 0 && !diff) {
2260 uint64_t n = MIN(len, chunk);
2261 uint64_t left = n;
2262 dmu_buf_t **indbp, **outdbp;
2263 int innum, outnum;
2264
2265 if (issig()) {
2266 error = SET_ERROR(EINTR);
2267 break;
2268 }
2269
2270 error = dmu_buf_hold_array_by_dnode(indn, inoff, n, TRUE,
2271 FTAG, &innum, &indbp, DMU_READ_PREFETCH);
2272 if (error != 0)
2273 break;
2274 error = dmu_buf_hold_array_by_dnode(outdn, outoff, n, TRUE,
2275 FTAG, &outnum, &outdbp, DMU_READ_PREFETCH);
2276 if (error != 0) {
2277 dmu_buf_rele_array(indbp, innum, FTAG);
2278 break;
2279 }
2280
2281 /*
2282 * The two files share a block size and both offsets are block
2283 * aligned, so the two arrays cover the span the same way.
2284 * Should that assumption ever break, refuse rather than walk
2285 * the shorter array out of bounds.
2286 */
2287 ASSERT3S(innum, ==, outnum);
2288 if (innum != outnum) {
2289 dmu_buf_rele_array(outdbp, outnum, FTAG);
2290 dmu_buf_rele_array(indbp, innum, FTAG);
2291 error = SET_ERROR(EINVAL);
2292 break;
2293 }
2294
2295 for (int i = 0; i < innum; i++) {
2296 uint64_t tocmp;
2297
2298 ASSERT3U(indbp[i]->db_offset, ==, inoff);
2299 ASSERT3U(outdbp[i]->db_offset, ==, outoff);
2300 ASSERT3P(indbp[i]->db_data, !=, NULL);
2301 ASSERT3P(outdbp[i]->db_data, !=, NULL);
2302
2303 tocmp = MIN(indbp[i]->db_size, left);
2304
2305 if (memcmp(indbp[i]->db_data, outdbp[i]->db_data,
2306 tocmp) != 0) {
2307 diff = B_TRUE;
2308 break;
2309 }
2310
2311 inoff += tocmp;
2312 outoff += tocmp;
2313 left -= tocmp;
2314 }
2315
2316 dmu_buf_rele_array(outdbp, outnum, FTAG);
2317 dmu_buf_rele_array(indbp, innum, FTAG);
2318
2319 len -= (n - left);
2320 }
2321
2322 if (error == 0 && len == 0 && !diff)
2323 *eqp = B_TRUE;
2324
2325 dnode_rele(outdn, FTAG);
2326 dnode_rele(indn, FTAG);
2327
2328 return (error);
2329 }
2330
2331 /*
2332 * Decide, from the two L0 block pointers alone, whether they already name the
2333 * same data: the same physical block, or two holes. This is what a
2334 * previously cloned or deduped pair of ranges looks like, and it is the one
2335 * case where the clone step itself would have nothing left to do.
2336 */
2337 static boolean_t
zfs_dedupe_bp_same_block(const blkptr_t * bi,const blkptr_t * bo)2338 zfs_dedupe_bp_same_block(const blkptr_t *bi, const blkptr_t *bo)
2339 {
2340 /*
2341 * Two holes are both a run of zeros over the same block, so they are
2342 * equal without either one naming any storage. Their sizes are not
2343 * worth comparing and must not be: our caller pairs the two files
2344 * block for block over a block size they share, but a block that was
2345 * never written at all reaches us as an all-zero block pointer (see
2346 * dmu_read_l0_bps()), whose BP_GET_LSIZE() decodes to the minimum
2347 * block size rather than to the file's. Reading a hole to compare
2348 * its zeros against another hole's zeros is exactly what this avoids.
2349 */
2350 if (BP_IS_HOLE(bi) && BP_IS_HOLE(bo))
2351 return (B_TRUE);
2352
2353 if (BP_IS_HOLE(bi) || BP_IS_HOLE(bo) ||
2354 BP_IS_EMBEDDED(bi) || BP_IS_EMBEDDED(bo) ||
2355 BP_IS_REDACTED(bi) || BP_IS_REDACTED(bo))
2356 return (B_FALSE);
2357
2358 /*
2359 * One allocation is one DVA born in one txg, so a matching first DVA
2360 * at a matching physical birth means both pointers name the same
2361 * physical block - typically because the ranges were already cloned
2362 * or deduped. This needs no checksum and holds even where the
2363 * checksum test below cannot (encryption, weak checksums): the same
2364 * block under the same key decrypts to the same data. BP_EQUAL() is
2365 * too strict for this: it also compares the logical births, and
2366 * cloning restamps those on every clone.
2367 */
2368 return (BP_GET_PHYSICAL_BIRTH(bi) == BP_GET_PHYSICAL_BIRTH(bo) &&
2369 DVA_EQUAL(&bi->blk_dva[0], &bo->blk_dva[0]));
2370 }
2371
2372 /*
2373 * Decide, from the two L0 block pointers alone, whether the blocks provably
2374 * hold identical logical data. Modeled on the nopwrite guard set in
2375 * zio_nop_write(): a match of a cryptographically strong (dedup-grade)
2376 * checksum is trusted to imply data equality, exactly as ZFS dedup relies on
2377 * it. This can only ever prove equality; a mismatch (or any non-provable
2378 * case) is inconclusive and the caller must fall back to reading the data.
2379 * Embedded blocks are the exception to needing a checksum: their payload
2380 * lives in the pointer itself, so two of them are compared directly.
2381 *
2382 * All of the following must hold for a checksum match to be trusted:
2383 * - neither BP is embedded, a hole, or redacted (no usable blk_cksum);
2384 * - neither BP is encrypted (per-block IV/salt make the checksum data-
2385 * independent, so equal plaintext yields different checksums);
2386 * - both BPs use the same checksum function and it carries the DEDUP flag
2387 * (sha256/sha512/skein/blake3; fletcher and edonr are excluded);
2388 * - compression, PSIZE, LSIZE and byteorder match, since blk_cksum is
2389 * computed over the physical (post-compression) bytes.
2390 * Salted checksums (skein/blake3) are safe here because block cloning is
2391 * always intra-pool (zfs_clone_range_precheck() returns EXDEV otherwise) and
2392 * the salt is per-pool, so identical data yields identical checksums.
2393 */
2394 static boolean_t
zfs_dedupe_bp_provably_equal(const blkptr_t * bi,const blkptr_t * bo)2395 zfs_dedupe_bp_provably_equal(const blkptr_t *bi, const blkptr_t *bo)
2396 {
2397 enum zio_checksum ck;
2398
2399 if (zfs_dedupe_bp_same_block(bi, bo))
2400 return (B_TRUE);
2401
2402 /*
2403 * Two embedded blocks carry their (possibly compressed) payload in
2404 * the pointers themselves. The same payload bytes under the same
2405 * compression function decompress to the same data, so equality is
2406 * provable without decompressing anything. A payload mismatch
2407 * proves nothing - equal data can compress to different bytes - and
2408 * falls through to the read path like any other unprovable case.
2409 */
2410 if (BP_IS_EMBEDDED(bi) && BP_IS_EMBEDDED(bo)) {
2411 uint8_t pi[BPE_PAYLOAD_SIZE], po[BPE_PAYLOAD_SIZE];
2412
2413 if (BPE_GET_ETYPE(bi) != BP_EMBEDDED_TYPE_DATA ||
2414 BPE_GET_ETYPE(bo) != BP_EMBEDDED_TYPE_DATA ||
2415 BP_GET_COMPRESS(bi) != BP_GET_COMPRESS(bo) ||
2416 BPE_GET_LSIZE(bi) != BPE_GET_LSIZE(bo) ||
2417 BPE_GET_PSIZE(bi) != BPE_GET_PSIZE(bo) ||
2418 BP_GET_BYTEORDER(bi) != BP_GET_BYTEORDER(bo))
2419 return (B_FALSE);
2420
2421 /*
2422 * The psize bit field can encode more than the payload area
2423 * holds. No valid pointer does, but this is cheaper than
2424 * trusting that.
2425 */
2426 if (BPE_GET_PSIZE(bi) > BPE_PAYLOAD_SIZE)
2427 return (B_FALSE);
2428
2429 decode_embedded_bp_compressed(bi, pi);
2430 decode_embedded_bp_compressed(bo, po);
2431
2432 return (memcmp(pi, po, BPE_GET_PSIZE(bi)) == 0);
2433 }
2434
2435 if (BP_IS_EMBEDDED(bi) || BP_IS_EMBEDDED(bo) ||
2436 BP_IS_HOLE(bi) || BP_IS_HOLE(bo) ||
2437 BP_IS_REDACTED(bi) || BP_IS_REDACTED(bo) ||
2438 BP_IS_ENCRYPTED(bi) || BP_IS_ENCRYPTED(bo))
2439 return (B_FALSE);
2440
2441 ck = BP_GET_CHECKSUM(bi);
2442 if (ck != BP_GET_CHECKSUM(bo))
2443 return (B_FALSE);
2444 if ((zio_checksum_table[ck].ci_flags & ZCHECKSUM_FLAG_DEDUP) == 0)
2445 return (B_FALSE);
2446
2447 if (BP_GET_COMPRESS(bi) != BP_GET_COMPRESS(bo) ||
2448 BP_GET_PSIZE(bi) != BP_GET_PSIZE(bo) ||
2449 BP_GET_LSIZE(bi) != BP_GET_LSIZE(bo) ||
2450 BP_GET_BYTEORDER(bi) != BP_GET_BYTEORDER(bo))
2451 return (B_FALSE);
2452
2453 return (ZIO_CHECKSUM_EQUAL(bi->blk_cksum, bo->blk_cksum));
2454 }
2455
2456 /*
2457 * The mirror of zfs_dedupe_bp_provably_equal(): decide, from the two L0 block
2458 * pointers alone, whether the blocks provably hold *different* logical data,
2459 * so the caller can report the ranges as differing without reading them. This
2460 * can only ever prove inequality; anything not provable is inconclusive and
2461 * the caller must fall back to reading the data.
2462 *
2463 * A checksum covers the physical bytes, so unequal checksums prove only that
2464 * the physical bytes differ. Carrying that back to the logical data needs the
2465 * block stored verbatim, hence the insistence on compression being off: two
2466 * blocks holding identical data can perfectly well compress to different
2467 * bytes, say after the compression property was changed, and zstd records only
2468 * its algorithm in the BP, not its level. Encrypted blocks are excluded for
2469 * the same reason as in the equality test, to the opposite effect: per-block
2470 * IVs give identical plaintext different ciphertext, so unequal checksums
2471 * there would say nothing. Holes and embedded blocks carry no comparable
2472 * checksum at all.
2473 *
2474 * Unlike the equality test this does not need a dedup-grade checksum. Even a
2475 * weak one is deterministic, so equal data always gives equal checksums, and
2476 * unequal checksums therefore always mean unequal data.
2477 */
2478 static boolean_t
zfs_dedupe_bp_provably_unequal(const blkptr_t * bi,const blkptr_t * bo)2479 zfs_dedupe_bp_provably_unequal(const blkptr_t *bi, const blkptr_t *bo)
2480 {
2481 if (BP_IS_EMBEDDED(bi) || BP_IS_EMBEDDED(bo) ||
2482 BP_IS_HOLE(bi) || BP_IS_HOLE(bo) ||
2483 BP_IS_REDACTED(bi) || BP_IS_REDACTED(bo) ||
2484 BP_IS_ENCRYPTED(bi) || BP_IS_ENCRYPTED(bo))
2485 return (B_FALSE);
2486
2487 if (BP_GET_COMPRESS(bi) != ZIO_COMPRESS_OFF ||
2488 BP_GET_COMPRESS(bo) != ZIO_COMPRESS_OFF)
2489 return (B_FALSE);
2490
2491 if (BP_GET_CHECKSUM(bi) != BP_GET_CHECKSUM(bo) ||
2492 BP_GET_LSIZE(bi) != BP_GET_LSIZE(bo) ||
2493 BP_GET_BYTEORDER(bi) != BP_GET_BYTEORDER(bo))
2494 return (B_FALSE);
2495
2496 return (!ZIO_CHECKSUM_EQUAL(bi->blk_cksum, bo->blk_cksum));
2497 }
2498
2499 /*
2500 * Compare [inoff, inoff + len) in inzp with [outoff, outoff + len) in outzp,
2501 * setting *samep if the ranges are byte-for-byte equal. Both files must be
2502 * range locked by the caller.
2503 *
2504 * As a fast path, blocks are compared by their block-pointer checksums, which
2505 * can settle a block either way without reading it: equal, when a strong
2506 * checksum matches (zfs_dedupe_bp_provably_equal(), mirroring how ZFS dedup
2507 * trusts checksums), or unequal, when checksums over verbatim-stored blocks
2508 * differ (zfs_dedupe_bp_provably_unequal()). Whatever neither can settle - a
2509 * weak or mismatched checksum, encryption, a hole, compression, a dirty (not
2510 * yet synced) block, etc. - falls back to reading and byte-comparing the data.
2511 * Both tests only ever assert what the block pointers prove, so the result is
2512 * identical to a full byte compare.
2513 *
2514 * A trailing block the range only partly covers is no different: the two files
2515 * share a block size and both offsets are block aligned, so the tail occupies
2516 * the same intra-block span in each, and equal whole-block checksums prove the
2517 * whole blocks equal, hence any common prefix of them equal. Only the bytes
2518 * inside the range are ever compared.
2519 *
2520 * When the ranges match, *sharedp additionally reports whether every block
2521 * pair already names the same storage (or is a pair of holes), in which case
2522 * the clone step would only reinstall pointers that are already in place and
2523 * the caller can skip it.
2524 */
2525 static int
zfs_dedupe_range_compare(znode_t * inzp,uint64_t inoff,znode_t * outzp,uint64_t outoff,uint64_t len,boolean_t * samep,boolean_t * sharedp)2526 zfs_dedupe_range_compare(znode_t *inzp, uint64_t inoff, znode_t *outzp,
2527 uint64_t outoff, uint64_t len, boolean_t *samep, boolean_t *sharedp)
2528 {
2529 objset_t *inos = ZTOZSB(inzp)->z_os;
2530 objset_t *outos = ZTOZSB(outzp)->z_os;
2531 uint_t blksz = inzp->z_blksz;
2532 blkptr_t *bps_in = NULL, *bps_out = NULL;
2533 size_t maxblocks;
2534 uint64_t off = 0;
2535 boolean_t eq;
2536 boolean_t shared = B_TRUE;
2537 int error = 0;
2538
2539 *samep = B_FALSE;
2540 *sharedp = B_FALSE;
2541
2542 /*
2543 * zfs_dedupe_range() has already rejected differing block sizes and
2544 * unaligned offsets, so the two files' blocks line up one to one.
2545 */
2546 ASSERT3U(outzp->z_blksz, ==, blksz);
2547 ASSERT0(inoff % blksz);
2548 ASSERT0(outoff % blksz);
2549
2550 /*
2551 * Bound the block-pointer batch so the temporary arrays stay small and
2552 * each dmu_read_l0_bps() stays within DMU_MAX_ACCESS.
2553 */
2554 maxblocks = MAX(1, MIN((uint64_t)16, (DMU_MAX_ACCESS >> 1) / blksz));
2555 bps_in = kmem_alloc(sizeof (blkptr_t) * maxblocks, KM_SLEEP);
2556 bps_out = kmem_alloc(sizeof (blkptr_t) * maxblocks, KM_SLEEP);
2557
2558 while (off < len) {
2559 uint64_t span = MIN(len - off, (uint64_t)maxblocks * blksz);
2560 size_t nin = maxblocks, nout = maxblocks;
2561 int e1, e2;
2562
2563 if (issig()) {
2564 error = SET_ERROR(EINTR);
2565 goto out;
2566 }
2567
2568 e1 = dmu_read_l0_bps(inos, inzp->z_id, inoff + off, span,
2569 bps_in, &nin);
2570 e2 = dmu_read_l0_bps(outos, outzp->z_id, outoff + off, span,
2571 bps_out, &nout);
2572
2573 if (e1 != 0 || e2 != 0 || nin != nout) {
2574 /*
2575 * A block created in the current txg (EAGAIN), or any
2576 * other reason we could not get stable BPs, just means
2577 * we compare this span by reading it; the data path is
2578 * always correct, including for dirty blocks.
2579 */
2580 shared = B_FALSE;
2581 error = zfs_dedupe_range_memcmp(inzp, inoff + off,
2582 outzp, outoff + off, span, &eq);
2583 if (error != 0 || !eq)
2584 goto out;
2585 off += span;
2586 continue;
2587 }
2588
2589 for (size_t i = 0; i < nin; i++) {
2590 uint64_t cmpoff = off + (uint64_t)i * blksz;
2591 uint64_t cmplen = MIN((uint64_t)blksz, len - cmpoff);
2592
2593 if (zfs_dedupe_bp_same_block(&bps_in[i], &bps_out[i]))
2594 continue;
2595 shared = B_FALSE;
2596
2597 if (zfs_dedupe_bp_provably_equal(&bps_in[i],
2598 &bps_out[i]))
2599 continue;
2600
2601 /*
2602 * Blocks that provably differ make the whole range
2603 * differ - but only when the range covers all of this
2604 * one. Two differing blocks can still agree over the
2605 * part a trailing sub-block request covers.
2606 */
2607 if (cmplen == blksz &&
2608 zfs_dedupe_bp_provably_unequal(&bps_in[i],
2609 &bps_out[i]))
2610 goto out;
2611
2612 /*
2613 * Not provable from BPs: compare just this block, or
2614 * only the part of it the range covers.
2615 */
2616 error = zfs_dedupe_range_memcmp(inzp, inoff + cmpoff,
2617 outzp, outoff + cmpoff, cmplen, &eq);
2618 if (error != 0 || !eq)
2619 goto out;
2620 }
2621
2622 off += span;
2623 }
2624
2625 *samep = B_TRUE;
2626 *sharedp = shared;
2627
2628 out:
2629 kmem_free(bps_in, sizeof (blkptr_t) * maxblocks);
2630 kmem_free(bps_out, sizeof (blkptr_t) * maxblocks);
2631
2632 return (error);
2633 }
2634
2635 /*
2636 * Deduplicate a range of outzp against inzp: if [inoff, inoff + *lenp) and
2637 * [outoff, outoff + *lenp) hold identical data, clone the source blocks over
2638 * the destination so the two ranges share storage. Implements the Linux
2639 * FIDEDUPERANGE ioctl on top of block cloning.
2640 *
2641 * The comparison and the clone are performed while holding a RL_READER range
2642 * lock on inzp and a RL_WRITER range lock on outzp, so the blocks that get
2643 * cloned are exactly the bytes that were compared.
2644 *
2645 * On return:
2646 * error != 0 - the request failed;
2647 * *samep == B_FALSE - the ranges differ, nothing was deduped;
2648 * *samep == B_TRUE - the ranges matched and *lenp holds the number of
2649 * bytes deduped (0 if a shortened range aligned away
2650 * to nothing).
2651 *
2652 * Both ranges must lie within their files. A trailing partial block is
2653 * aligned away when can_shorten is set, and rejected with EINVAL when it is
2654 * not, so a dedupe can still cover less than the caller asked for.
2655 */
2656 int
zfs_dedupe_range(znode_t * inzp,uint64_t inoff,znode_t * outzp,uint64_t outoff,uint64_t * lenp,cred_t * cr,boolean_t can_shorten,boolean_t * samep)2657 zfs_dedupe_range(znode_t *inzp, uint64_t inoff, znode_t *outzp, uint64_t outoff,
2658 uint64_t *lenp, cred_t *cr, boolean_t can_shorten, boolean_t *samep)
2659 {
2660 zfsvfs_t *inzfsvfs = ZTOZSB(inzp);
2661 zfsvfs_t *outzfsvfs = ZTOZSB(outzp);
2662 zfs_locked_range_t *inlr = NULL, *outlr = NULL;
2663 uint64_t len = *lenp;
2664 uint64_t done = 0;
2665 uint_t inblksz;
2666 boolean_t shared = B_FALSE;
2667 int error;
2668
2669 *samep = B_FALSE;
2670
2671 error = zfs_enter_two(inzfsvfs, outzfsvfs, FTAG);
2672 if (error != 0)
2673 return (error);
2674
2675 error = zfs_clone_range_precheck(inzp, outzp);
2676 if (error != 0)
2677 goto out;
2678
2679 /*
2680 * Deduplicating nothing trivially succeeds.
2681 */
2682 if (len == 0) {
2683 *lenp = 0;
2684 *samep = B_TRUE;
2685 goto out;
2686 }
2687
2688 /*
2689 * Unlike a clone, a dedupe request is not silently clamped to the
2690 * source EOF: the whole compared range must lie within the source.
2691 */
2692 if (inoff >= inzp->z_size || len > inzp->z_size - inoff) {
2693 error = SET_ERROR(EINVAL);
2694 goto out;
2695 }
2696
2697 /*
2698 * The destination range must lie within the destination too. Trimming
2699 * it to the destination EOF would be invisible to the caller, because
2700 * the ioctl reports the length it was asked for rather than the one a
2701 * filesystem returns, so a shortened dedupe would be indistinguishable
2702 * from a complete one. generic_remap_checks() rejects this for the
2703 * filesystems that use it; do the same here.
2704 */
2705 if (outoff >= outzp->z_size || len > outzp->z_size - outoff) {
2706 error = SET_ERROR(EINVAL);
2707 goto out;
2708 }
2709
2710 /*
2711 * Callers might not be able to detect properly that we are read-only,
2712 * so check it explicitly here.
2713 */
2714 if (zfs_is_readonly(outzfsvfs)) {
2715 error = SET_ERROR(EROFS);
2716 goto out;
2717 }
2718
2719 /*
2720 * A dedupe leaves the content as it was, but it still frees the
2721 * destination's blocks and replaces them with shared ones, so honor
2722 * immutable here the way every other data-writing path does.
2723 */
2724 if ((outzp->z_pflags & ZFS_IMMUTABLE) != 0) {
2725 error = SET_ERROR(EPERM);
2726 goto out;
2727 }
2728
2729 /*
2730 * No overlapping if we are deduping within the same file.
2731 */
2732 if (inzp == outzp) {
2733 if (inoff < outoff + len && outoff < inoff + len) {
2734 error = SET_ERROR(EINVAL);
2735 goto out;
2736 }
2737 }
2738
2739 /* Flush any mmap()'d data on both files before we compare it. */
2740 if (zn_has_cached_data(inzp, inoff, inoff + len - 1))
2741 zn_flush_cached_data(inzp, B_TRUE);
2742 if (zn_has_cached_data(outzp, outoff, outoff + len - 1))
2743 zn_flush_cached_data(outzp, B_TRUE);
2744
2745 /*
2746 * Maintain predictable lock order.
2747 */
2748 if (inzp < outzp || (inzp == outzp && inoff < outoff)) {
2749 inlr = zfs_rangelock_enter(&inzp->z_rangelock, inoff, len,
2750 RL_READER);
2751 outlr = zfs_rangelock_enter(&outzp->z_rangelock, outoff, len,
2752 RL_WRITER);
2753 } else {
2754 outlr = zfs_rangelock_enter(&outzp->z_rangelock, outoff, len,
2755 RL_WRITER);
2756 inlr = zfs_rangelock_enter(&inzp->z_rangelock, inoff, len,
2757 RL_READER);
2758 }
2759
2760 /*
2761 * The clone step can only replace whole blocks of the destination with
2762 * whole blocks of the source, so the two files must agree on the block
2763 * size and both offsets must be block-aligned; those can never be
2764 * shortened away. A trailing partial block is handled after the
2765 * comparison below. Block sizes cannot change under us here: growing
2766 * one takes the whole-file rangelock, which our holds exclude.
2767 */
2768 inblksz = inzp->z_blksz;
2769 if (inblksz != outzp->z_blksz) {
2770 error = SET_ERROR(EINVAL);
2771 goto unlock;
2772 }
2773 if ((inoff % inblksz) != 0 || (outoff % inblksz) != 0) {
2774 error = SET_ERROR(EINVAL);
2775 goto unlock;
2776 }
2777 if ((len % inblksz) != 0 &&
2778 (len < inzp->z_size - inoff || len < outzp->z_size - outoff) &&
2779 !can_shorten) {
2780 error = SET_ERROR(EINVAL);
2781 goto unlock;
2782 }
2783
2784 /*
2785 * Compare the whole requested range under the locks, before aligning
2786 * it down for the clone. Comparing the full range is what makes a
2787 * differing trailing sub-block report DIFFERS rather than being
2788 * silently dropped by the alignment below (which, with a large
2789 * recordsize, can round the whole request away to nothing).
2790 */
2791 error = zfs_dedupe_range_compare(inzp, inoff, outzp, outoff, len,
2792 samep, &shared);
2793 if (error != 0 || !*samep)
2794 goto unlock;
2795
2796 /*
2797 * The ranges are identical. Align a trailing partial block away for
2798 * the clone step; the ranges still compared equal, so *samep stays
2799 * set even if this leaves nothing to share.
2800 */
2801 if ((len % inblksz) != 0 &&
2802 (len < inzp->z_size - inoff || len < outzp->z_size - outoff))
2803 len = P2ALIGN_TYPED(len, inblksz, uint64_t);
2804 if (len == 0)
2805 goto unlock;
2806
2807 /*
2808 * When every destination block already shares its source block (or
2809 * both are holes), the ranges were cloned or deduped before and the
2810 * clone would only reinstall the pointers the destination already
2811 * has - dirtying every block, restamping its logical birth (which
2812 * makes the next incremental send carry it again) and churning the
2813 * BRT for an end state that is already on disk. Dedupe tools cannot
2814 * see ZFS-level sharing, so they will keep finding the same identical
2815 * files; make rededuping them free.
2816 */
2817 if (shared) {
2818 done = len;
2819 goto unlock;
2820 }
2821
2822 error = zfs_clone_range_locked(inzp, inoff, outzp, outoff, len, cr,
2823 outlr, B_TRUE, &done);
2824
2825 unlock:
2826 zfs_rangelock_exit(outlr);
2827 zfs_rangelock_exit(inlr);
2828
2829 if (error == 0) {
2830 if (done > 0) {
2831 /*
2832 * No zil_commit() here: a dedupe logs nothing, so
2833 * there is no itx to wait for even with sync=always.
2834 */
2835 ZFS_ACCESSTIME_STAMP(inzfsvfs, inzp);
2836 }
2837 *lenp = done;
2838 }
2839
2840 out:
2841 zfs_exit_two(inzfsvfs, outzfsvfs, FTAG);
2842
2843 return (error);
2844 }
2845
2846 /*
2847 * Usual pattern would be to call zfs_clone_range() from zfs_replay_clone(),
2848 * but we cannot do that, because when replaying we don't have source znode
2849 * available. This is why we need a dedicated replay function.
2850 */
2851 int
zfs_clone_range_replay(znode_t * zp,uint64_t off,uint64_t len,uint64_t blksz,const blkptr_t * bps,size_t nbps)2852 zfs_clone_range_replay(znode_t *zp, uint64_t off, uint64_t len, uint64_t blksz,
2853 const blkptr_t *bps, size_t nbps)
2854 {
2855 zfsvfs_t *zfsvfs;
2856 dmu_buf_impl_t *db;
2857 dmu_tx_t *tx;
2858 int error;
2859 int count = 0;
2860 sa_bulk_attr_t bulk[5];
2861 uint64_t mtime[2], ctime[2];
2862
2863 ASSERT3U(off, <, MAXOFFSET_T);
2864 ASSERT3U(len, >, 0);
2865 ASSERT3U(nbps, >, 0);
2866
2867 zfsvfs = ZTOZSB(zp);
2868
2869 ASSERT(spa_feature_is_enabled(dmu_objset_spa(zfsvfs->z_os),
2870 SPA_FEATURE_BLOCK_CLONING));
2871
2872 if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
2873 return (error);
2874
2875 ASSERT(zfsvfs->z_replay);
2876 ASSERT(!zfs_is_readonly(zfsvfs));
2877
2878 if ((off % blksz) != 0) {
2879 zfs_exit(zfsvfs, FTAG);
2880 return (SET_ERROR(EINVAL));
2881 }
2882
2883 /*
2884 * Start a transaction.
2885 */
2886 tx = dmu_tx_create(zfsvfs->z_os);
2887
2888 dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
2889 db = (dmu_buf_impl_t *)sa_get_db(zp->z_sa_hdl);
2890 DB_DNODE_ENTER(db);
2891 dmu_tx_hold_clone_by_dnode(tx, DB_DNODE(db), off, len, blksz);
2892 DB_DNODE_EXIT(db);
2893 zfs_sa_upgrade_txholds(tx, zp);
2894 error = dmu_tx_assign(tx, DMU_TX_WAIT);
2895 if (error != 0) {
2896 dmu_tx_abort(tx);
2897 zfs_exit(zfsvfs, FTAG);
2898 return (error);
2899 }
2900
2901 if (zp->z_blksz < blksz)
2902 zfs_grow_blocksize(zp, blksz, tx);
2903
2904 if (blksz != zp->z_blksz) {
2905 error = SET_ERROR(EINVAL);
2906 dmu_tx_commit(tx);
2907 zfs_exit(zfsvfs, FTAG);
2908 return (error);
2909 }
2910
2911 error = dmu_brt_clone(zfsvfs->z_os, zp->z_id, off, len, tx, bps, nbps);
2912 if (error != 0) {
2913 dmu_tx_commit(tx);
2914 zfs_exit(zfsvfs, FTAG);
2915 return (error);
2916 }
2917
2918 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2919 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2920 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
2921 &zp->z_size, 8);
2922 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
2923 &zp->z_pflags, 8);
2924 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
2925 ZFS_PERSIST_SEQ(zp, bulk, count);
2926
2927 if (zp->z_size < off + len)
2928 zp->z_size = off + len;
2929
2930 ASSERT3S(count, <=, ARRAY_SIZE(bulk));
2931 error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2932
2933 /*
2934 * zil_replaying() not only check if we are replaying ZIL, but also
2935 * updates the ZIL header to record replay progress.
2936 */
2937 VERIFY(zil_replaying(zfsvfs->z_log, tx));
2938
2939 dmu_tx_commit(tx);
2940
2941 zfs_znode_update_vfs(zp);
2942
2943 zfs_exit(zfsvfs, FTAG);
2944
2945 return (error);
2946 }
2947
2948 EXPORT_SYMBOL(zfs_access);
2949 EXPORT_SYMBOL(zfs_fsync);
2950 EXPORT_SYMBOL(zfs_holey);
2951 EXPORT_SYMBOL(zfs_read);
2952 EXPORT_SYMBOL(zfs_write);
2953 EXPORT_SYMBOL(zfs_getsecattr);
2954 EXPORT_SYMBOL(zfs_setsecattr);
2955 EXPORT_SYMBOL(zfs_clone_range);
2956 EXPORT_SYMBOL(zfs_clone_range_replay);
2957 EXPORT_SYMBOL(zfs_dedupe_range);
2958
2959 ZFS_MODULE_PARAM(zfs_vnops, zfs_vnops_, read_chunk_size, U64, ZMOD_RW,
2960 "Bytes to read per chunk");
2961
2962 ZFS_MODULE_PARAM(zfs, zfs_, bclone_enabled, INT, ZMOD_RW,
2963 "Enable block cloning");
2964
2965 ZFS_MODULE_PARAM(zfs, zfs_, bclone_strict_properties, INT, ZMOD_RW,
2966 "Restrict cross-dataset cloning with different properties");
2967
2968 ZFS_MODULE_PARAM(zfs, zfs_, bclone_wait_dirty, INT, ZMOD_RW,
2969 "Wait for dirty blocks when cloning");
2970
2971 ZFS_MODULE_PARAM(zfs, zfs_, dio_enabled, INT, ZMOD_RW,
2972 "Enable Direct I/O");
2973
2974 ZFS_MODULE_PARAM(zfs, zfs_, dio_strict, INT, ZMOD_RW,
2975 "Return errors on misaligned Direct I/O");
2976