xref: /linux/fs/xfs/xfs_exchrange.c (revision 7dfb218c829c1acb626e0fe92c5fddb9a26a03e9)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2020-2024 Oracle.  All Rights Reserved.
4  * Author: Darrick J. Wong <djwong@kernel.org>
5  */
6 #include "xfs_platform.h"
7 #include "xfs_shared.h"
8 #include "xfs_format.h"
9 #include "xfs_log_format.h"
10 #include "xfs_trans_resv.h"
11 #include "xfs_mount.h"
12 #include "xfs_defer.h"
13 #include "xfs_inode.h"
14 #include "xfs_trans.h"
15 #include "xfs_quota.h"
16 #include "xfs_bmap_util.h"
17 #include "xfs_reflink.h"
18 #include "xfs_trace.h"
19 #include "xfs_exchrange.h"
20 #include "xfs_exchmaps.h"
21 #include "xfs_sb.h"
22 #include "xfs_icache.h"
23 #include "xfs_log.h"
24 #include "xfs_rtbitmap.h"
25 #include <linux/fsnotify.h>
26 
27 /* Lock (and optionally join) two inodes for a file range exchange. */
28 void
29 xfs_exchrange_ilock(
30 	struct xfs_trans	*tp,
31 	struct xfs_inode	*ip1,
32 	struct xfs_inode	*ip2)
33 {
34 	if (ip1 != ip2)
35 		xfs_lock_two_inodes(ip1, XFS_ILOCK_EXCL,
36 				    ip2, XFS_ILOCK_EXCL);
37 	else
38 		xfs_ilock(ip1, XFS_ILOCK_EXCL);
39 	if (tp) {
40 		xfs_trans_ijoin(tp, ip1, 0);
41 		if (ip2 != ip1)
42 			xfs_trans_ijoin(tp, ip2, 0);
43 	}
44 
45 }
46 
47 /* Unlock two inodes after a file range exchange operation. */
48 void
49 xfs_exchrange_iunlock(
50 	struct xfs_inode	*ip1,
51 	struct xfs_inode	*ip2)
52 {
53 	if (ip2 != ip1)
54 		xfs_iunlock(ip2, XFS_ILOCK_EXCL);
55 	xfs_iunlock(ip1, XFS_ILOCK_EXCL);
56 }
57 
58 /*
59  * Estimate the resource requirements to exchange file contents between the two
60  * files.  The caller is required to hold the IOLOCK and the MMAPLOCK and to
61  * have flushed both inodes' pagecache and active direct-ios.
62  */
63 int
64 xfs_exchrange_estimate(
65 	struct xfs_exchmaps_req	*req)
66 {
67 	int			error;
68 
69 	xfs_exchrange_ilock(NULL, req->ip1, req->ip2);
70 	error = xfs_exchmaps_estimate(req);
71 	xfs_exchrange_iunlock(req->ip1, req->ip2);
72 	return error;
73 }
74 
75 /*
76  * Check that file2's metadata agree with the snapshot that we took for the
77  * range commit request.
78  *
79  * This should be called after the filesystem has locked /all/ inode metadata
80  * against modification.
81  */
82 STATIC int
83 xfs_exchrange_check_freshness(
84 	const struct xfs_exchrange	*fxr,
85 	struct xfs_inode		*ip2)
86 {
87 	struct inode			*inode2 = VFS_I(ip2);
88 	struct timespec64		ctime = inode_get_ctime(inode2);
89 	struct timespec64		mtime = inode_get_mtime(inode2);
90 
91 	trace_xfs_exchrange_freshness(fxr, ip2);
92 
93 	/* Check that file2 hasn't otherwise been modified. */
94 	if (fxr->file2_ino != inode2->i_ino ||
95 	    fxr->file2_gen != inode2->i_generation ||
96 	    !timespec64_equal(&fxr->file2_ctime, &ctime) ||
97 	    !timespec64_equal(&fxr->file2_mtime, &mtime))
98 		return -EBUSY;
99 
100 	return 0;
101 }
102 
103 #define QRETRY_IP1	(0x1)
104 #define QRETRY_IP2	(0x2)
105 
106 /*
107  * Obtain a quota reservation to make sure we don't hit EDQUOT.  We can skip
108  * this if quota enforcement is disabled or if both inodes' dquots are the
109  * same.  The qretry structure must be initialized to zeroes before the first
110  * call to this function.
111  */
112 STATIC int
113 xfs_exchrange_reserve_quota(
114 	struct xfs_trans		*tp,
115 	const struct xfs_exchmaps_req	*req,
116 	unsigned int			*qretry)
117 {
118 	int64_t				ddelta, rdelta;
119 	int				ip1_error = 0;
120 	int				error;
121 
122 	ASSERT(!xfs_is_metadir_inode(req->ip1));
123 	ASSERT(!xfs_is_metadir_inode(req->ip2));
124 
125 	/*
126 	 * Don't bother with a quota reservation if we're not enforcing them
127 	 * or the two inodes have the same dquots.
128 	 */
129 	if (!XFS_IS_QUOTA_ON(tp->t_mountp) || req->ip1 == req->ip2 ||
130 	    (req->ip1->i_udquot == req->ip2->i_udquot &&
131 	     req->ip1->i_gdquot == req->ip2->i_gdquot &&
132 	     req->ip1->i_pdquot == req->ip2->i_pdquot))
133 		return 0;
134 
135 	*qretry = 0;
136 
137 	/*
138 	 * For each file, compute the net gain in the number of regular blocks
139 	 * that will be mapped into that file and reserve that much quota.  The
140 	 * quota counts must be able to absorb at least that much space.
141 	 */
142 	ddelta = req->ip2_bcount - req->ip1_bcount;
143 	rdelta = req->ip2_rtbcount - req->ip1_rtbcount;
144 	if (ddelta > 0 || rdelta > 0) {
145 		error = xfs_trans_reserve_quota_nblks(tp, req->ip1,
146 				ddelta > 0 ? ddelta : 0,
147 				rdelta > 0 ? rdelta : 0,
148 				false);
149 		if (error == -EDQUOT || error == -ENOSPC) {
150 			/*
151 			 * Save this error and see what happens if we try to
152 			 * reserve quota for ip2.  Then report both.
153 			 */
154 			*qretry |= QRETRY_IP1;
155 			ip1_error = error;
156 			error = 0;
157 		}
158 		if (error)
159 			return error;
160 	}
161 	if (ddelta < 0 || rdelta < 0) {
162 		error = xfs_trans_reserve_quota_nblks(tp, req->ip2,
163 				ddelta < 0 ? -ddelta : 0,
164 				rdelta < 0 ? -rdelta : 0,
165 				false);
166 		if (error == -EDQUOT || error == -ENOSPC)
167 			*qretry |= QRETRY_IP2;
168 		if (error)
169 			return error;
170 	}
171 	if (ip1_error)
172 		return ip1_error;
173 
174 	/*
175 	 * For each file, forcibly reserve the gross gain in mapped blocks so
176 	 * that we don't trip over any quota block reservation assertions.
177 	 * We must reserve the gross gain because the quota code subtracts from
178 	 * bcount the number of blocks that we unmap; it does not add that
179 	 * quantity back to the quota block reservation.
180 	 */
181 	error = xfs_trans_reserve_quota_nblks(tp, req->ip1, req->ip1_bcount,
182 			req->ip1_rtbcount, true);
183 	if (error)
184 		return error;
185 
186 	return xfs_trans_reserve_quota_nblks(tp, req->ip2, req->ip2_bcount,
187 			req->ip2_rtbcount, true);
188 }
189 
190 /* Exchange the mappings (and hence the contents) of two files' forks. */
191 STATIC int
192 xfs_exchrange_mappings(
193 	const struct xfs_exchrange	*fxr,
194 	struct xfs_inode		*ip1,
195 	struct xfs_inode		*ip2)
196 {
197 	struct xfs_mount		*mp = ip1->i_mount;
198 	struct xfs_exchmaps_req		req = {
199 		.ip1			= ip1,
200 		.ip2			= ip2,
201 		.startoff1		= XFS_B_TO_FSBT(mp, fxr->file1_offset),
202 		.startoff2		= XFS_B_TO_FSBT(mp, fxr->file2_offset),
203 		.blockcount		= XFS_B_TO_FSB(mp, fxr->length),
204 	};
205 	struct xfs_trans		*tp;
206 	unsigned int			qretry;
207 	bool				retried = false;
208 	int				error;
209 
210 	trace_xfs_exchrange_mappings(fxr, ip1, ip2);
211 
212 	if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF)
213 		req.flags |= XFS_EXCHMAPS_SET_SIZES;
214 	if (fxr->flags & XFS_EXCHANGE_RANGE_FILE1_WRITTEN)
215 		req.flags |= XFS_EXCHMAPS_INO1_WRITTEN;
216 
217 	/*
218 	 * Round the request length up to the nearest file allocation unit.
219 	 * The prep function already checked that the request offsets and
220 	 * length in @fxr are safe to round up.
221 	 */
222 	if (xfs_inode_has_bigrtalloc(ip2))
223 		req.blockcount = xfs_blen_roundup_rtx(mp, req.blockcount);
224 
225 	error = xfs_exchrange_estimate(&req);
226 	if (error)
227 		return error;
228 
229 retry:
230 	/* Allocate the transaction, lock the inodes, and join them. */
231 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, req.resblks, 0,
232 			XFS_TRANS_RES_FDBLKS, &tp);
233 	if (error)
234 		return error;
235 
236 	xfs_exchrange_ilock(tp, ip1, ip2);
237 
238 	trace_xfs_exchrange_before(ip2, 2);
239 	trace_xfs_exchrange_before(ip1, 1);
240 
241 	error = xfs_exchmaps_check_forks(mp, &req);
242 	if (error)
243 		goto out_trans_cancel;
244 
245 	/*
246 	 * Reserve ourselves some quota if any of them are in enforcing mode.
247 	 * In theory we only need enough to satisfy the change in the number
248 	 * of blocks between the two ranges being remapped.
249 	 */
250 	error = xfs_exchrange_reserve_quota(tp, &req, &qretry);
251 	if ((error == -EDQUOT || error == -ENOSPC) && !retried) {
252 		xfs_trans_cancel(tp);
253 		xfs_exchrange_iunlock(ip1, ip2);
254 		if (qretry & QRETRY_IP1)
255 			xfs_blockgc_free_quota(ip1, 0);
256 		if (qretry & QRETRY_IP2)
257 			xfs_blockgc_free_quota(ip2, 0);
258 		retried = true;
259 		goto retry;
260 	}
261 	if (error)
262 		goto out_trans_cancel;
263 
264 	/* If we got this far on a dry run, all parameters are ok. */
265 	if (fxr->flags & XFS_EXCHANGE_RANGE_DRY_RUN)
266 		goto out_trans_cancel;
267 
268 	/* Update the mtime and ctime of both files. */
269 	if (fxr->flags & __XFS_EXCHANGE_RANGE_UPD_CMTIME1)
270 		xfs_trans_ichgtime(tp, ip1, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
271 	if (fxr->flags & __XFS_EXCHANGE_RANGE_UPD_CMTIME2)
272 		xfs_trans_ichgtime(tp, ip2, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
273 
274 	xfs_exchange_mappings(tp, &req);
275 
276 	/*
277 	 * Force the log to persist metadata updates if the caller or the
278 	 * administrator requires this.  The generic prep function already
279 	 * flushed the relevant parts of the page cache.
280 	 */
281 	if (xfs_has_wsync(mp) || (fxr->flags & XFS_EXCHANGE_RANGE_DSYNC))
282 		xfs_trans_set_sync(tp);
283 
284 	error = xfs_trans_commit(tp);
285 
286 	trace_xfs_exchrange_after(ip2, 2);
287 	trace_xfs_exchrange_after(ip1, 1);
288 
289 	if (error)
290 		goto out_unlock;
291 
292 	/*
293 	 * If the caller wanted, set each file's size to that file's exchange
294 	 * offset + length exchanged from the other file because the ranges in
295 	 * each file might be different lengths.  This should be safe because
296 	 * we flushed both files' page caches, exchanged all the mappings, and
297 	 * updated the ondisk sizes.
298 	 */
299 	if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF) {
300 		loff_t	old_ip1_size = i_size_read(VFS_I(ip1));
301 		loff_t	old_ip2_size = i_size_read(VFS_I(ip2));
302 
303 		i_size_write(VFS_I(ip2), fxr->file2_offset +
304 				(old_ip1_size - fxr->file1_offset));
305 		i_size_write(VFS_I(ip1), fxr->file1_offset +
306 				(old_ip2_size - fxr->file2_offset));
307 	}
308 
309 out_unlock:
310 	xfs_exchrange_iunlock(ip1, ip2);
311 	return error;
312 
313 out_trans_cancel:
314 	xfs_trans_cancel(tp);
315 	goto out_unlock;
316 }
317 
318 /*
319  * Generic code for exchanging ranges of two files via XFS_IOC_EXCHANGE_RANGE.
320  * This part deals with struct file objects and byte ranges and does not deal
321  * with XFS-specific data structures such as xfs_inodes and block ranges.  This
322  * separation may some day facilitate porting to another filesystem.
323  *
324  * The goal is to exchange fxr.length bytes starting at fxr.file1_offset in
325  * file1 with the same number of bytes starting at fxr.file2_offset in file2.
326  * Implementations must call xfs_exchange_range_prep to prepare the two
327  * files prior to taking locks; and they must update the inode change and mod
328  * times of both files as part of the metadata update.  The timestamp update
329  * and freshness checks must be done atomically as part of the data exchange
330  * operation to ensure correctness of the freshness check.
331  * xfs_exchange_range_finish must be called after the operation completes
332  * successfully but before locks are dropped.
333  */
334 
335 /*
336  * Performs necessary checks before doing a range exchange, having stabilized
337  * mutable inode attributes via i_rwsem.
338  */
339 static inline int
340 xfs_exchange_range_checks(
341 	struct xfs_exchrange	*fxr,
342 	unsigned int		alloc_unit)
343 {
344 	struct inode		*inode1 = file_inode(fxr->file1);
345 	loff_t			size1 = i_size_read(inode1);
346 	struct inode		*inode2 = file_inode(fxr->file2);
347 	loff_t			size2 = i_size_read(inode2);
348 	uint64_t		allocmask = alloc_unit - 1;
349 	int64_t			test_len;
350 	uint64_t		blen;
351 	loff_t			tmp;
352 	int			error;
353 
354 	/* Don't touch certain kinds of inodes */
355 	if (IS_IMMUTABLE(inode1) || IS_IMMUTABLE(inode2))
356 		return -EPERM;
357 	if (IS_SWAPFILE(inode1) || IS_SWAPFILE(inode2))
358 		return -ETXTBSY;
359 
360 	/* Ranges cannot start after EOF. */
361 	if (fxr->file1_offset > size1 || fxr->file2_offset > size2)
362 		return -EINVAL;
363 
364 	if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF) {
365 		/*
366 		 * If the caller said to exchange to EOF, we set the length of
367 		 * the request large enough to cover everything to the end of
368 		 * both files.
369 		 */
370 		fxr->length = max_t(int64_t, size1 - fxr->file1_offset,
371 					     size2 - fxr->file2_offset);
372 	} else {
373 		/*
374 		 * Otherwise we require both ranges to end within EOF.
375 		 */
376 		if (fxr->file1_offset + fxr->length > size1 ||
377 		    fxr->file2_offset + fxr->length > size2)
378 			return -EINVAL;
379 	}
380 
381 	/*
382 	 * The start of both ranges must be aligned to the file allocation
383 	 * unit.
384 	 */
385 	if (!IS_ALIGNED(fxr->file1_offset, alloc_unit) ||
386 	    !IS_ALIGNED(fxr->file2_offset, alloc_unit))
387 		return -EINVAL;
388 
389 	/* Ensure offsets don't wrap. */
390 	if (check_add_overflow(fxr->file1_offset, fxr->length, &tmp) ||
391 	    check_add_overflow(fxr->file2_offset, fxr->length, &tmp))
392 		return -EINVAL;
393 
394 	/*
395 	 * Make sure we don't hit any file size limits.  If we hit any size
396 	 * limits such that test_length was adjusted, we abort the whole
397 	 * operation.
398 	 */
399 	test_len = fxr->length;
400 	error = generic_write_check_limits(fxr->file2, fxr->file2_offset,
401 			&test_len);
402 	if (error)
403 		return error;
404 	error = generic_write_check_limits(fxr->file1, fxr->file1_offset,
405 			&test_len);
406 	if (error)
407 		return error;
408 	if (test_len != fxr->length)
409 		return -EINVAL;
410 
411 	/*
412 	 * If the user wanted us to exchange up to the infile's EOF, round up
413 	 * to the next allocation unit boundary for this check.  Do the same
414 	 * for the outfile.
415 	 *
416 	 * Otherwise, reject the range length if it's not aligned to an
417 	 * allocation unit.
418 	 */
419 	if (fxr->file1_offset + fxr->length == size1)
420 		blen = ALIGN(size1, alloc_unit) - fxr->file1_offset;
421 	else if (fxr->file2_offset + fxr->length == size2)
422 		blen = ALIGN(size2, alloc_unit) - fxr->file2_offset;
423 	else if (!IS_ALIGNED(fxr->length, alloc_unit))
424 		return -EINVAL;
425 	else
426 		blen = fxr->length;
427 
428 	/* Don't allow overlapped exchanges within the same file. */
429 	if (inode1 == inode2 &&
430 	    fxr->file2_offset + blen > fxr->file1_offset &&
431 	    fxr->file1_offset + blen > fxr->file2_offset)
432 		return -EINVAL;
433 
434 	/*
435 	 * Ensure that we don't exchange a partial EOF block into the middle of
436 	 * another file.
437 	 */
438 	if ((fxr->length & allocmask) == 0)
439 		return 0;
440 
441 	blen = fxr->length;
442 	if (fxr->file2_offset + blen < size2)
443 		blen &= ~allocmask;
444 
445 	if (fxr->file1_offset + blen < size1)
446 		blen &= ~allocmask;
447 
448 	return blen == fxr->length ? 0 : -EINVAL;
449 }
450 
451 /* Flush all relevant dirty pagecache near the range to be exchanged. */
452 static inline int
453 xfs_exchange_range_flush(
454 	struct xfs_inode		*ip,
455 	const struct xfs_exchrange	*fxr,
456 	loff_t				offset)
457 {
458 	/*
459 	 * If TO_EOF is set, the ondisk file size update logic depends on the
460 	 * ondisk file size matching the incore file size.  Flush everything.
461 	 */
462 	if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF)
463 		return filemap_write_and_wait(VFS_I(ip)->i_mapping);
464 
465 	/*
466 	 * Because we're updating the ondisk mappings, flush all dirty data
467 	 * between the ondisk size and the exchange offset to reduce the chance
468 	 * of zeroed file contents in that gap after a crash.
469 	 */
470 	return filemap_write_and_wait_range(VFS_I(ip)->i_mapping,
471 			min(offset, ip->i_disk_size),
472 			offset + fxr->length - 1);
473 }
474 
475 /*
476  * Check that the two inodes are eligible for range exchanges, the ranges make
477  * sense, and then flush all dirty data.  Caller must ensure that the inodes
478  * have been locked against any other modifications.
479  */
480 static inline int
481 xfs_exchange_range_prep(
482 	struct xfs_exchrange	*fxr,
483 	unsigned int		alloc_unit)
484 {
485 	struct inode		*inode1 = file_inode(fxr->file1);
486 	struct inode		*inode2 = file_inode(fxr->file2);
487 	bool			same_inode = (inode1 == inode2);
488 	int			error;
489 
490 	/* Check that we don't violate system file offset limits. */
491 	error = xfs_exchange_range_checks(fxr, alloc_unit);
492 	if (error || fxr->length == 0)
493 		return error;
494 
495 	/* Wait for the completion of any pending IOs on both files */
496 	inode_dio_wait(inode1);
497 	if (!same_inode)
498 		inode_dio_wait(inode2);
499 
500 	error = xfs_exchange_range_flush(XFS_I(inode1), fxr, fxr->file1_offset);
501 	if (error)
502 		return error;
503 
504 	error = xfs_exchange_range_flush(XFS_I(inode2), fxr, fxr->file2_offset);
505 	if (error)
506 		return error;
507 
508 	/*
509 	 * If the files or inodes involved require synchronous writes, amend
510 	 * the request to force the filesystem to flush all data and metadata
511 	 * to disk after the operation completes.
512 	 */
513 	if (((fxr->file1->f_flags | fxr->file2->f_flags) & O_SYNC) ||
514 	    IS_SYNC(inode1) || IS_SYNC(inode2))
515 		fxr->flags |= XFS_EXCHANGE_RANGE_DSYNC;
516 
517 	return 0;
518 }
519 
520 /*
521  * Finish a range exchange operation, if it was successful.  Caller must ensure
522  * that the inodes are still locked against any other modifications.
523  */
524 static inline int
525 xfs_exchange_range_finish(
526 	struct xfs_exchrange	*fxr)
527 {
528 	int			error;
529 
530 	if (fxr->flags & XFS_EXCHANGE_RANGE_DRY_RUN)
531 		return 0;
532 
533 	error = file_remove_privs(fxr->file1);
534 	if (error)
535 		return error;
536 	if (file_inode(fxr->file1) == file_inode(fxr->file2))
537 		return 0;
538 
539 	return file_remove_privs(fxr->file2);
540 }
541 
542 /*
543  * Check the alignment of an exchange request when the allocation unit size
544  * isn't a power of two.  The generic file-level helpers use (fast)
545  * bitmask-based alignment checks, but here we have to use slow long division.
546  */
547 static int
548 xfs_exchrange_check_rtalign(
549 	const struct xfs_exchrange	*fxr,
550 	struct xfs_inode		*ip1,
551 	struct xfs_inode		*ip2,
552 	unsigned int			alloc_unit)
553 {
554 	uint64_t			length = fxr->length;
555 	uint64_t			blen;
556 	loff_t				size1, size2;
557 
558 	size1 = i_size_read(VFS_I(ip1));
559 	size2 = i_size_read(VFS_I(ip2));
560 
561 	/* The start of both ranges must be aligned to a rt extent. */
562 	if (!isaligned_64(fxr->file1_offset, alloc_unit) ||
563 	    !isaligned_64(fxr->file2_offset, alloc_unit))
564 		return -EINVAL;
565 
566 	if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF)
567 		length = max_t(int64_t, size1 - fxr->file1_offset,
568 					size2 - fxr->file2_offset);
569 
570 	/*
571 	 * If the user wanted us to exchange up to the infile's EOF, round up
572 	 * to the next rt extent boundary for this check.  Do the same for the
573 	 * outfile.
574 	 *
575 	 * Otherwise, reject the range length if it's not rt extent aligned.
576 	 * We already confirmed the starting offsets' rt extent block
577 	 * alignment.
578 	 */
579 	if (fxr->file1_offset + length == size1)
580 		blen = roundup_64(size1, alloc_unit) - fxr->file1_offset;
581 	else if (fxr->file2_offset + length == size2)
582 		blen = roundup_64(size2, alloc_unit) - fxr->file2_offset;
583 	else if (!isaligned_64(length, alloc_unit))
584 		return -EINVAL;
585 	else
586 		blen = length;
587 
588 	/* Don't allow overlapped exchanges within the same file. */
589 	if (ip1 == ip2 &&
590 	    fxr->file2_offset + blen > fxr->file1_offset &&
591 	    fxr->file1_offset + blen > fxr->file2_offset)
592 		return -EINVAL;
593 
594 	/*
595 	 * Ensure that we don't exchange a partial EOF rt extent into the
596 	 * middle of another file.
597 	 */
598 	if (isaligned_64(length, alloc_unit))
599 		return 0;
600 
601 	blen = length;
602 	if (fxr->file2_offset + length < size2)
603 		blen = rounddown_64(blen, alloc_unit);
604 
605 	if (fxr->file1_offset + blen < size1)
606 		blen = rounddown_64(blen, alloc_unit);
607 
608 	return blen == length ? 0 : -EINVAL;
609 }
610 
611 /* Prepare two files to have their data exchanged. */
612 STATIC int
613 xfs_exchrange_prep(
614 	struct xfs_exchrange	*fxr,
615 	struct xfs_inode	*ip1,
616 	struct xfs_inode	*ip2)
617 {
618 	struct xfs_mount	*mp = ip2->i_mount;
619 	unsigned int		alloc_unit = xfs_inode_alloc_unitsize(ip2);
620 	int			error;
621 
622 	trace_xfs_exchrange_prep(fxr, ip1, ip2);
623 
624 	/* Verify both files are either real-time or non-realtime */
625 	if (XFS_IS_REALTIME_INODE(ip1) != XFS_IS_REALTIME_INODE(ip2))
626 		return -EINVAL;
627 
628 	/* Check non-power of two alignment issues, if necessary. */
629 	if (!is_power_of_2(alloc_unit)) {
630 		error = xfs_exchrange_check_rtalign(fxr, ip1, ip2, alloc_unit);
631 		if (error)
632 			return error;
633 
634 		/*
635 		 * Do the generic file-level checks with the regular block
636 		 * alignment.
637 		 */
638 		alloc_unit = mp->m_sb.sb_blocksize;
639 	}
640 
641 	error = xfs_exchange_range_prep(fxr, alloc_unit);
642 	if (error || fxr->length == 0)
643 		return error;
644 
645 	if (fxr->flags & __XFS_EXCHANGE_RANGE_CHECK_FRESH2) {
646 		error = xfs_exchrange_check_freshness(fxr, ip2);
647 		if (error)
648 			return error;
649 	}
650 
651 	/* Attach dquots to both inodes before changing block maps. */
652 	error = xfs_qm_dqattach(ip2);
653 	if (error)
654 		return error;
655 	error = xfs_qm_dqattach(ip1);
656 	if (error)
657 		return error;
658 
659 	if (fxr->flags & XFS_EXCHANGE_RANGE_DRY_RUN)
660 		return 0;
661 
662 	trace_xfs_exchrange_flush(fxr, ip1, ip2);
663 
664 	/* Flush the relevant ranges of both files. */
665 	error = xfs_flush_unmap_range(ip2, fxr->file2_offset, fxr->length);
666 	if (error)
667 		return error;
668 	error = xfs_flush_unmap_range(ip1, fxr->file1_offset, fxr->length);
669 	if (error)
670 		return error;
671 
672 	/*
673 	 * Cancel CoW fork preallocations for the ranges of both files.  The
674 	 * prep function should have flushed all the dirty data, so the only
675 	 * CoW mappings remaining should be speculative.
676 	 */
677 	if (xfs_inode_has_cow_data(ip1)) {
678 		error = xfs_reflink_cancel_cow_range(ip1, fxr->file1_offset,
679 				fxr->length, true);
680 		if (error)
681 			return error;
682 	}
683 
684 	if (xfs_inode_has_cow_data(ip2)) {
685 		error = xfs_reflink_cancel_cow_range(ip2, fxr->file2_offset,
686 				fxr->length, true);
687 		if (error)
688 			return error;
689 	}
690 
691 	return 0;
692 }
693 
694 /*
695  * Exchange contents of files.  This is the binding between the generic
696  * file-level concepts and the XFS inode-specific implementation.
697  */
698 STATIC int
699 xfs_exchrange_contents(
700 	struct xfs_exchrange	*fxr)
701 {
702 	struct inode		*inode1 = file_inode(fxr->file1);
703 	struct inode		*inode2 = file_inode(fxr->file2);
704 	struct xfs_inode	*ip1 = XFS_I(inode1);
705 	struct xfs_inode	*ip2 = XFS_I(inode2);
706 	struct xfs_mount	*mp = ip1->i_mount;
707 	int			error;
708 
709 	if (!xfs_has_exchange_range(mp))
710 		return -EOPNOTSUPP;
711 
712 	if (fxr->flags & ~(XFS_EXCHANGE_RANGE_ALL_FLAGS |
713 			   XFS_EXCHANGE_RANGE_PRIV_FLAGS))
714 		return -EINVAL;
715 
716 	if (xfs_is_shutdown(mp))
717 		return -EIO;
718 
719 	/* Lock both files against IO */
720 	error = xfs_ilock2_io_mmap(ip1, ip2);
721 	if (error)
722 		goto out_err;
723 
724 	/* Prepare and then exchange file contents. */
725 	error = xfs_exchrange_prep(fxr, ip1, ip2);
726 	if (error)
727 		goto out_unlock;
728 
729 	error = xfs_exchrange_mappings(fxr, ip1, ip2);
730 	if (error)
731 		goto out_unlock;
732 
733 	/*
734 	 * Finish the exchange by removing special file privileges like any
735 	 * other file write would do.  This may involve turning on support for
736 	 * logged xattrs if either file has security capabilities.
737 	 */
738 	if (!(fxr->flags & XFS_EXCHANGE_RANGE_DRY_RUN)) {
739 		error = xfs_exchange_range_finish(fxr);
740 		if (error)
741 			goto out_unlock;
742 	}
743 
744 out_unlock:
745 	xfs_iunlock2_io_mmap(ip1, ip2);
746 out_err:
747 	if (error)
748 		trace_xfs_exchrange_error(ip2, error, _RET_IP_);
749 	return error;
750 }
751 
752 /* Exchange parts of two files. */
753 static int
754 xfs_exchange_range(
755 	struct xfs_exchrange	*fxr)
756 {
757 	struct inode		*inode1 = file_inode(fxr->file1);
758 	struct inode		*inode2 = file_inode(fxr->file2);
759 	loff_t			check_len = fxr->length;
760 	int			ret;
761 
762 	BUILD_BUG_ON(XFS_EXCHANGE_RANGE_ALL_FLAGS &
763 		     XFS_EXCHANGE_RANGE_PRIV_FLAGS);
764 
765 	/* Both files must be on the same mount/filesystem. */
766 	if (fxr->file1->f_path.mnt != fxr->file2->f_path.mnt)
767 		return -EXDEV;
768 
769 	if (fxr->flags & ~(XFS_EXCHANGE_RANGE_ALL_FLAGS |
770 			 __XFS_EXCHANGE_RANGE_CHECK_FRESH2))
771 		return -EINVAL;
772 
773 	/* Userspace requests only honored for regular files. */
774 	if (S_ISDIR(inode1->i_mode) || S_ISDIR(inode2->i_mode))
775 		return -EISDIR;
776 	if (!S_ISREG(inode1->i_mode) || !S_ISREG(inode2->i_mode))
777 		return -EINVAL;
778 
779 	/* Both files must be opened for read and write. */
780 	if (!(fxr->file1->f_mode & FMODE_READ) ||
781 	    !(fxr->file1->f_mode & FMODE_WRITE) ||
782 	    !(fxr->file2->f_mode & FMODE_READ) ||
783 	    !(fxr->file2->f_mode & FMODE_WRITE))
784 		return -EBADF;
785 
786 	/* Neither file can be opened append-only. */
787 	if ((fxr->file1->f_flags & O_APPEND) ||
788 	    (fxr->file2->f_flags & O_APPEND))
789 		return -EBADF;
790 
791 	/*
792 	 * If we're exchanging to EOF we can't calculate the length until taking
793 	 * the iolock.  Pass a 0 length to remap_verify_area similar to the
794 	 * FICLONE and FICLONERANGE ioctls that support cloning to EOF as well.
795 	 */
796 	if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF)
797 		check_len = 0;
798 	ret = remap_verify_area(fxr->file1, fxr->file1_offset, check_len, true);
799 	if (ret)
800 		return ret;
801 	ret = remap_verify_area(fxr->file2, fxr->file2_offset, check_len, true);
802 	if (ret)
803 		return ret;
804 
805 	/* Update cmtime if the fd/inode don't forbid it. */
806 	if (!(fxr->file1->f_mode & FMODE_NOCMTIME) && !IS_NOCMTIME(inode1))
807 		fxr->flags |= __XFS_EXCHANGE_RANGE_UPD_CMTIME1;
808 	if (!(fxr->file2->f_mode & FMODE_NOCMTIME) && !IS_NOCMTIME(inode2))
809 		fxr->flags |= __XFS_EXCHANGE_RANGE_UPD_CMTIME2;
810 
811 	file_start_write(fxr->file2);
812 	ret = xfs_exchrange_contents(fxr);
813 	file_end_write(fxr->file2);
814 	if (ret)
815 		return ret;
816 
817 	if (!(fxr->flags & XFS_EXCHANGE_RANGE_DRY_RUN)) {
818 		fsnotify_modify(fxr->file1);
819 		if (fxr->file2 != fxr->file1)
820 			fsnotify_modify(fxr->file2);
821 	}
822 
823 	return 0;
824 }
825 
826 /* Collect exchange-range arguments from userspace. */
827 long
828 xfs_ioc_exchange_range(
829 	struct file			*file,
830 	struct xfs_exchange_range __user *argp)
831 {
832 	struct xfs_exchrange		fxr = {
833 		.file2			= file,
834 	};
835 	struct xfs_exchange_range	args;
836 
837 	if (copy_from_user(&args, argp, sizeof(args)))
838 		return -EFAULT;
839 	if (memchr_inv(&args.pad, 0, sizeof(args.pad)))
840 		return -EINVAL;
841 	if (args.flags & ~XFS_EXCHANGE_RANGE_ALL_FLAGS)
842 		return -EINVAL;
843 
844 	fxr.file1_offset	= args.file1_offset;
845 	fxr.file2_offset	= args.file2_offset;
846 	fxr.length		= args.length;
847 	fxr.flags		= args.flags;
848 
849 	CLASS(fd, file1)(args.file1_fd);
850 	if (fd_empty(file1))
851 		return -EBADF;
852 	fxr.file1 = fd_file(file1);
853 
854 	return xfs_exchange_range(&fxr);
855 }
856 
857 /* Opaque freshness blob for XFS_IOC_COMMIT_RANGE */
858 struct xfs_commit_range_fresh {
859 	xfs_fsid_t	fsid;		/* m_fixedfsid */
860 	__u64		file2_ino;	/* inode number */
861 	__s64		file2_mtime;	/* modification time */
862 	__s64		file2_ctime;	/* change time */
863 	__s32		file2_mtime_nsec; /* mod time, nsec */
864 	__s32		file2_ctime_nsec; /* change time, nsec */
865 	__u32		file2_gen;	/* inode generation */
866 	__u32		magic;		/* zero */
867 };
868 #define XCR_FRESH_MAGIC	0x444F524B	/* DORK */
869 
870 /* Set up a commitrange operation by sampling file2's write-related attrs */
871 long
872 xfs_ioc_start_commit(
873 	struct file			*file,
874 	struct xfs_commit_range __user	*argp)
875 {
876 	struct xfs_commit_range		args = { };
877 	struct kstat			kstat = { };
878 	struct xfs_commit_range_fresh	*kern_f;
879 	struct xfs_commit_range_fresh	__user *user_f;
880 	struct inode			*inode2 = file_inode(file);
881 	struct xfs_inode		*ip2 = XFS_I(inode2);
882 	const unsigned int		lockflags = XFS_IOLOCK_SHARED |
883 						    XFS_MMAPLOCK_SHARED |
884 						    XFS_ILOCK_SHARED;
885 
886 	BUILD_BUG_ON(sizeof(struct xfs_commit_range_fresh) !=
887 		     sizeof(args.file2_freshness));
888 
889 	kern_f = (struct xfs_commit_range_fresh *)&args.file2_freshness;
890 
891 	memcpy(&kern_f->fsid, ip2->i_mount->m_fixedfsid, sizeof(xfs_fsid_t));
892 
893 	xfs_ilock(ip2, lockflags);
894 	/* Force writing of a distinct ctime if any writes happen. */
895 	fill_mg_cmtime(&kstat, STATX_CTIME | STATX_MTIME, inode2);
896 	kern_f->file2_ctime		= kstat.ctime.tv_sec;
897 	kern_f->file2_ctime_nsec	= kstat.ctime.tv_nsec;
898 	kern_f->file2_mtime		= kstat.mtime.tv_sec;
899 	kern_f->file2_mtime_nsec	= kstat.mtime.tv_nsec;
900 	kern_f->file2_ino		= inode2->i_ino;
901 	kern_f->file2_gen		= inode2->i_generation;
902 	kern_f->magic			= XCR_FRESH_MAGIC;
903 	xfs_iunlock(ip2, lockflags);
904 
905 	user_f = (struct xfs_commit_range_fresh __user *)&argp->file2_freshness;
906 	if (copy_to_user(user_f, kern_f, sizeof(*kern_f)))
907 		return -EFAULT;
908 
909 	return 0;
910 }
911 
912 /*
913  * Exchange file1 and file2 contents if file2 has not been written since the
914  * start commit operation.
915  */
916 long
917 xfs_ioc_commit_range(
918 	struct file			*file,
919 	struct xfs_commit_range __user	*argp)
920 {
921 	struct xfs_exchrange		fxr = {
922 		.file2			= file,
923 	};
924 	struct xfs_commit_range		args;
925 	struct xfs_commit_range_fresh	*kern_f;
926 	struct xfs_inode		*ip2 = XFS_I(file_inode(file));
927 	struct xfs_mount		*mp = ip2->i_mount;
928 
929 	kern_f = (struct xfs_commit_range_fresh *)&args.file2_freshness;
930 
931 	if (copy_from_user(&args, argp, sizeof(args)))
932 		return -EFAULT;
933 	if (args.pad || (args.flags & ~XFS_EXCHANGE_RANGE_ALL_FLAGS))
934 		return -EINVAL;
935 	if (kern_f->magic != XCR_FRESH_MAGIC)
936 		return -EBUSY;
937 	if (memcmp(&kern_f->fsid, mp->m_fixedfsid, sizeof(xfs_fsid_t)))
938 		return -EBUSY;
939 
940 	fxr.file1_offset	= args.file1_offset;
941 	fxr.file2_offset	= args.file2_offset;
942 	fxr.length		= args.length;
943 	fxr.flags		= args.flags | __XFS_EXCHANGE_RANGE_CHECK_FRESH2;
944 	fxr.file2_ino		= kern_f->file2_ino;
945 	fxr.file2_gen		= kern_f->file2_gen;
946 	fxr.file2_mtime.tv_sec	= kern_f->file2_mtime;
947 	fxr.file2_mtime.tv_nsec	= kern_f->file2_mtime_nsec;
948 	fxr.file2_ctime.tv_sec	= kern_f->file2_ctime;
949 	fxr.file2_ctime.tv_nsec	= kern_f->file2_ctime_nsec;
950 
951 	CLASS(fd, file1)(args.file1_fd);
952 	if (fd_empty(file1))
953 		return -EBADF;
954 	fxr.file1 = fd_file(file1);
955 
956 	return xfs_exchange_range(&fxr);
957 }
958