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