xref: /linux/fs/xfs/xfs_reflink.c (revision fab183d632628381b466a41479489541ac0e29a0)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2016 Oracle.  All Rights Reserved.
4  * Author: Darrick J. Wong <darrick.wong@oracle.com>
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_defer.h"
14 #include "xfs_inode.h"
15 #include "xfs_trans.h"
16 #include "xfs_bmap.h"
17 #include "xfs_bmap_util.h"
18 #include "xfs_trace.h"
19 #include "xfs_icache.h"
20 #include "xfs_btree.h"
21 #include "xfs_refcount_btree.h"
22 #include "xfs_refcount.h"
23 #include "xfs_bmap_btree.h"
24 #include "xfs_trans_space.h"
25 #include "xfs_bit.h"
26 #include "xfs_alloc.h"
27 #include "xfs_quota.h"
28 #include "xfs_reflink.h"
29 #include "xfs_iomap.h"
30 #include "xfs_ag.h"
31 #include "xfs_ag_resv.h"
32 #include "xfs_health.h"
33 #include "xfs_rtrefcount_btree.h"
34 #include "xfs_rtalloc.h"
35 #include "xfs_rtgroup.h"
36 #include "xfs_metafile.h"
37 
38 /*
39  * Copy on Write of Shared Blocks
40  *
41  * XFS must preserve "the usual" file semantics even when two files share
42  * the same physical blocks.  This means that a write to one file must not
43  * alter the blocks in a different file; the way that we'll do that is
44  * through the use of a copy-on-write mechanism.  At a high level, that
45  * means that when we want to write to a shared block, we allocate a new
46  * block, write the data to the new block, and if that succeeds we map the
47  * new block into the file.
48  *
49  * XFS provides a "delayed allocation" mechanism that defers the allocation
50  * of disk blocks to dirty-but-not-yet-mapped file blocks as long as
51  * possible.  This reduces fragmentation by enabling the filesystem to ask
52  * for bigger chunks less often, which is exactly what we want for CoW.
53  *
54  * The delalloc mechanism begins when the kernel wants to make a block
55  * writable (write_begin or page_mkwrite).  If the offset is not mapped, we
56  * create a delalloc mapping, which is a regular in-core extent, but without
57  * a real startblock.  (For delalloc mappings, the startblock encodes both
58  * a flag that this is a delalloc mapping, and a worst-case estimate of how
59  * many blocks might be required to put the mapping into the BMBT.)  delalloc
60  * mappings are a reservation against the free space in the filesystem;
61  * adjacent mappings can also be combined into fewer larger mappings.
62  *
63  * As an optimization, the CoW extent size hint (cowextsz) creates
64  * outsized aligned delalloc reservations in the hope of landing out of
65  * order nearby CoW writes in a single extent on disk, thereby reducing
66  * fragmentation and improving future performance.
67  *
68  * D: --RRRRRRSSSRRRRRRRR--- (data fork)
69  * C: ------DDDDDDD--------- (CoW fork)
70  *
71  * When dirty pages are being written out (typically in writepage), the
72  * delalloc reservations are converted into unwritten mappings by
73  * allocating blocks and replacing the delalloc mapping with real ones.
74  * A delalloc mapping can be replaced by several unwritten ones if the
75  * free space is fragmented.
76  *
77  * D: --RRRRRRSSSRRRRRRRR---
78  * C: ------UUUUUUU---------
79  *
80  * We want to adapt the delalloc mechanism for copy-on-write, since the
81  * write paths are similar.  The first two steps (creating the reservation
82  * and allocating the blocks) are exactly the same as delalloc except that
83  * the mappings must be stored in a separate CoW fork because we do not want
84  * to disturb the mapping in the data fork until we're sure that the write
85  * succeeded.  IO completion in this case is the process of removing the old
86  * mapping from the data fork and moving the new mapping from the CoW fork to
87  * the data fork.  This will be discussed shortly.
88  *
89  * For now, unaligned directio writes will be bounced back to the page cache.
90  * Block-aligned directio writes will use the same mechanism as buffered
91  * writes.
92  *
93  * Just prior to submitting the actual disk write requests, we convert
94  * the extents representing the range of the file actually being written
95  * (as opposed to extra pieces created for the cowextsize hint) to real
96  * extents.  This will become important in the next step:
97  *
98  * D: --RRRRRRSSSRRRRRRRR---
99  * C: ------UUrrUUU---------
100  *
101  * CoW remapping must be done after the data block write completes,
102  * because we don't want to destroy the old data fork map until we're sure
103  * the new block has been written.  Since the new mappings are kept in a
104  * separate fork, we can simply iterate these mappings to find the ones
105  * that cover the file blocks that we just CoW'd.  For each extent, simply
106  * unmap the corresponding range in the data fork, map the new range into
107  * the data fork, and remove the extent from the CoW fork.  Because of
108  * the presence of the cowextsize hint, however, we must be careful
109  * only to remap the blocks that we've actually written out --  we must
110  * never remap delalloc reservations nor CoW staging blocks that have
111  * yet to be written.  This corresponds exactly to the real extents in
112  * the CoW fork:
113  *
114  * D: --RRRRRRrrSRRRRRRRR---
115  * C: ------UU--UUU---------
116  *
117  * Since the remapping operation can be applied to an arbitrary file
118  * range, we record the need for the remap step as a flag in the ioend
119  * instead of declaring a new IO type.  This is required for direct io
120  * because we only have ioend for the whole dio, and we have to be able to
121  * remember the presence of unwritten blocks and CoW blocks with a single
122  * ioend structure.  Better yet, the more ground we can cover with one
123  * ioend, the better.
124  */
125 
126 /*
127  * Given a file mapping for the data device, find the lowest-numbered run of
128  * shared blocks within that mapping and return it in shared_offset/shared_len.
129  * The offset is relative to the start of irec.
130  *
131  * If find_end_of_shared is true, return the longest contiguous extent of shared
132  * blocks.  If there are no shared extents, shared_offset and shared_len will be
133  * set to 0;
134  */
135 static int
xfs_reflink_find_shared(struct xfs_mount * mp,struct xfs_trans * tp,const struct xfs_bmbt_irec * irec,xfs_extlen_t * shared_offset,xfs_extlen_t * shared_len,bool find_end_of_shared)136 xfs_reflink_find_shared(
137 	struct xfs_mount	*mp,
138 	struct xfs_trans	*tp,
139 	const struct xfs_bmbt_irec *irec,
140 	xfs_extlen_t		*shared_offset,
141 	xfs_extlen_t		*shared_len,
142 	bool			find_end_of_shared)
143 {
144 	struct xfs_buf		*agbp;
145 	struct xfs_perag	*pag;
146 	struct xfs_btree_cur	*cur;
147 	int			error;
148 	xfs_agblock_t		orig_bno, found_bno;
149 
150 	pag = xfs_perag_get(mp, XFS_FSB_TO_AGNO(mp, irec->br_startblock));
151 	orig_bno = XFS_FSB_TO_AGBNO(mp, irec->br_startblock);
152 
153 	error = xfs_alloc_read_agf(pag, tp, 0, &agbp);
154 	if (error)
155 		goto out;
156 
157 	cur = xfs_refcountbt_init_cursor(mp, tp, agbp, pag);
158 	error = xfs_refcount_find_shared(cur, orig_bno, irec->br_blockcount,
159 			&found_bno, shared_len, find_end_of_shared);
160 	xfs_btree_del_cursor(cur, error);
161 	xfs_trans_brelse(tp, agbp);
162 
163 	if (!error && *shared_len)
164 		*shared_offset = found_bno - orig_bno;
165 out:
166 	xfs_perag_put(pag);
167 	return error;
168 }
169 
170 /*
171  * Given a file mapping for the rt device, find the lowest-numbered run of
172  * shared blocks within that mapping and return it in shared_offset/shared_len.
173  * The offset is relative to the start of irec.
174  *
175  * If find_end_of_shared is true, return the longest contiguous extent of shared
176  * blocks.  If there are no shared extents, shared_offset and shared_len will be
177  * set to 0;
178  */
179 static int
xfs_reflink_find_rtshared(struct xfs_mount * mp,struct xfs_trans * tp,const struct xfs_bmbt_irec * irec,xfs_extlen_t * shared_offset,xfs_extlen_t * shared_len,bool find_end_of_shared)180 xfs_reflink_find_rtshared(
181 	struct xfs_mount	*mp,
182 	struct xfs_trans	*tp,
183 	const struct xfs_bmbt_irec *irec,
184 	xfs_extlen_t		*shared_offset,
185 	xfs_extlen_t		*shared_len,
186 	bool			find_end_of_shared)
187 {
188 	struct xfs_rtgroup	*rtg;
189 	struct xfs_btree_cur	*cur;
190 	xfs_rgblock_t		orig_bno;
191 	xfs_agblock_t		found_bno;
192 	int			error;
193 
194 	BUILD_BUG_ON(NULLRGBLOCK != NULLAGBLOCK);
195 
196 	/*
197 	 * Note: this uses the not quite correct xfs_agblock_t type because
198 	 * xfs_refcount_find_shared is shared between the RT and data device
199 	 * refcount code.
200 	 */
201 	orig_bno = xfs_rtb_to_rgbno(mp, irec->br_startblock);
202 	rtg = xfs_rtgroup_get(mp, xfs_rtb_to_rgno(mp, irec->br_startblock));
203 
204 	xfs_rtgroup_lock(rtg, XFS_RTGLOCK_REFCOUNT);
205 	cur = xfs_rtrefcountbt_init_cursor(tp, rtg);
206 	error = xfs_refcount_find_shared(cur, orig_bno, irec->br_blockcount,
207 			&found_bno, shared_len, find_end_of_shared);
208 	xfs_btree_del_cursor(cur, error);
209 	xfs_rtgroup_unlock(rtg, XFS_RTGLOCK_REFCOUNT);
210 	xfs_rtgroup_put(rtg);
211 
212 	if (!error && *shared_len)
213 		*shared_offset = found_bno - orig_bno;
214 	return error;
215 }
216 
217 /*
218  * Trim the mapping to the next block where there's a change in the
219  * shared/unshared status.  More specifically, this means that we
220  * find the lowest-numbered extent of shared blocks that coincides with
221  * the given block mapping.  If the shared extent overlaps the start of
222  * the mapping, trim the mapping to the end of the shared extent.  If
223  * the shared region intersects the mapping, trim the mapping to the
224  * start of the shared extent.  If there are no shared regions that
225  * overlap, just return the original extent.
226  */
227 int
xfs_reflink_trim_around_shared(struct xfs_inode * ip,struct xfs_bmbt_irec * irec,bool * shared)228 xfs_reflink_trim_around_shared(
229 	struct xfs_inode	*ip,
230 	struct xfs_bmbt_irec	*irec,
231 	bool			*shared)
232 {
233 	struct xfs_mount	*mp = ip->i_mount;
234 	xfs_extlen_t		shared_offset, shared_len;
235 	int			error = 0;
236 
237 	/* Holes, unwritten, and delalloc extents cannot be shared */
238 	if (!xfs_is_reflink_inode(ip) || !xfs_bmap_is_written_extent(irec)) {
239 		*shared = false;
240 		return 0;
241 	}
242 
243 	trace_xfs_reflink_trim_around_shared(ip, irec);
244 
245 	if (XFS_IS_REALTIME_INODE(ip))
246 		error = xfs_reflink_find_rtshared(mp, NULL, irec,
247 				&shared_offset, &shared_len, true);
248 	else
249 		error = xfs_reflink_find_shared(mp, NULL, irec,
250 				&shared_offset, &shared_len, true);
251 	if (error)
252 		return error;
253 
254 	if (!shared_len) {
255 		/* No shared blocks at all. */
256 		*shared = false;
257 	} else if (!shared_offset) {
258 		/*
259 		 * The start of this mapping points to shared space.  Truncate
260 		 * the mapping at the end of the shared region so that a
261 		 * subsequent iteration starts at the start of the unshared
262 		 * region.
263 		 */
264 		irec->br_blockcount = shared_len;
265 		*shared = true;
266 	} else {
267 		/*
268 		 * There's a shared region that doesn't start at the beginning
269 		 * of the mapping.  Truncate the mapping at the start of the
270 		 * shared extent so that a subsequent iteration starts at the
271 		 * start of the shared region.
272 		 */
273 		irec->br_blockcount = shared_offset;
274 		*shared = false;
275 	}
276 	return 0;
277 }
278 
279 int
xfs_bmap_trim_cow(struct xfs_inode * ip,struct xfs_bmbt_irec * imap,bool * shared)280 xfs_bmap_trim_cow(
281 	struct xfs_inode	*ip,
282 	struct xfs_bmbt_irec	*imap,
283 	bool			*shared)
284 {
285 	/* We can't update any real extents in always COW mode. */
286 	if (xfs_is_always_cow_inode(ip) &&
287 	    !isnullstartblock(imap->br_startblock)) {
288 		*shared = true;
289 		return 0;
290 	}
291 
292 	/* Trim the mapping to the nearest shared extent boundary. */
293 	return xfs_reflink_trim_around_shared(ip, imap, shared);
294 }
295 
296 int
xfs_reflink_convert_cow_locked(struct xfs_inode * ip,xfs_fileoff_t offset_fsb,xfs_filblks_t count_fsb)297 xfs_reflink_convert_cow_locked(
298 	struct xfs_inode	*ip,
299 	xfs_fileoff_t		offset_fsb,
300 	xfs_filblks_t		count_fsb)
301 {
302 	struct xfs_iext_cursor	icur;
303 	struct xfs_bmbt_irec	got;
304 	struct xfs_btree_cur	*dummy_cur = NULL;
305 	int			dummy_logflags;
306 	int			error = 0;
307 
308 	if (!xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &got))
309 		return 0;
310 
311 	do {
312 		if (got.br_startoff >= offset_fsb + count_fsb)
313 			break;
314 		if (got.br_state == XFS_EXT_NORM)
315 			continue;
316 		if (WARN_ON_ONCE(isnullstartblock(got.br_startblock)))
317 			return -EIO;
318 
319 		xfs_trim_extent(&got, offset_fsb, count_fsb);
320 		if (!got.br_blockcount)
321 			continue;
322 
323 		got.br_state = XFS_EXT_NORM;
324 		error = xfs_bmap_add_extent_unwritten_real(NULL, ip,
325 				XFS_COW_FORK, &icur, &dummy_cur, &got,
326 				&dummy_logflags);
327 		if (error)
328 			return error;
329 	} while (xfs_iext_next_extent(ip->i_cowfp, &icur, &got));
330 
331 	return error;
332 }
333 
334 /* Convert all of the unwritten CoW extents in a file's range to real ones. */
335 int
xfs_reflink_convert_cow(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t count)336 xfs_reflink_convert_cow(
337 	struct xfs_inode	*ip,
338 	xfs_off_t		offset,
339 	xfs_off_t		count)
340 {
341 	struct xfs_mount	*mp = ip->i_mount;
342 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
343 	xfs_fileoff_t		end_fsb = XFS_B_TO_FSB(mp, offset + count);
344 	xfs_filblks_t		count_fsb = end_fsb - offset_fsb;
345 	int			error;
346 
347 	ASSERT(count != 0);
348 
349 	xfs_ilock(ip, XFS_ILOCK_EXCL);
350 	error = xfs_reflink_convert_cow_locked(ip, offset_fsb, count_fsb);
351 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
352 	return error;
353 }
354 
355 /*
356  * Find the extent that maps the given range in the COW fork. Even if the extent
357  * is not shared we might have a preallocation for it in the COW fork. If so we
358  * use it that rather than trigger a new allocation.
359  */
360 static int
xfs_find_trim_cow_extent(struct xfs_inode * ip,struct xfs_bmbt_irec * imap,struct xfs_bmbt_irec * cmap,bool * shared,bool * found)361 xfs_find_trim_cow_extent(
362 	struct xfs_inode	*ip,
363 	struct xfs_bmbt_irec	*imap,
364 	struct xfs_bmbt_irec	*cmap,
365 	bool			*shared,
366 	bool			*found)
367 {
368 	xfs_fileoff_t		offset_fsb = imap->br_startoff;
369 	xfs_filblks_t		count_fsb = imap->br_blockcount;
370 	struct xfs_iext_cursor	icur;
371 
372 	*found = false;
373 
374 	/*
375 	 * If we don't find an overlapping extent, trim the range we need to
376 	 * allocate to fit the hole we found.
377 	 */
378 	if (!xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, cmap))
379 		cmap->br_startoff = offset_fsb + count_fsb;
380 	if (cmap->br_startoff > offset_fsb) {
381 		xfs_trim_extent(imap, imap->br_startoff,
382 				cmap->br_startoff - imap->br_startoff);
383 		return xfs_bmap_trim_cow(ip, imap, shared);
384 	}
385 
386 	*shared = true;
387 	if (isnullstartblock(cmap->br_startblock)) {
388 		xfs_trim_extent(imap, cmap->br_startoff, cmap->br_blockcount);
389 		return 0;
390 	}
391 
392 	/* real extent found - no need to allocate */
393 	xfs_trim_extent(cmap, offset_fsb, count_fsb);
394 	*found = true;
395 	return 0;
396 }
397 
398 static int
xfs_reflink_convert_unwritten(struct xfs_inode * ip,struct xfs_bmbt_irec * imap,struct xfs_bmbt_irec * cmap,bool convert_now)399 xfs_reflink_convert_unwritten(
400 	struct xfs_inode	*ip,
401 	struct xfs_bmbt_irec	*imap,
402 	struct xfs_bmbt_irec	*cmap,
403 	bool			convert_now)
404 {
405 	xfs_fileoff_t		offset_fsb = imap->br_startoff;
406 	xfs_filblks_t		count_fsb = imap->br_blockcount;
407 	int			error;
408 
409 	/*
410 	 * cmap might larger than imap due to cowextsize hint.
411 	 */
412 	xfs_trim_extent(cmap, offset_fsb, count_fsb);
413 
414 	/*
415 	 * COW fork extents are supposed to remain unwritten until we're ready
416 	 * to initiate a disk write.  For direct I/O we are going to write the
417 	 * data and need the conversion, but for buffered writes we're done.
418 	 */
419 	if (!convert_now || cmap->br_state == XFS_EXT_NORM)
420 		return 0;
421 
422 	trace_xfs_reflink_convert_cow(ip, cmap);
423 
424 	error = xfs_reflink_convert_cow_locked(ip, offset_fsb, count_fsb);
425 	if (!error)
426 		cmap->br_state = XFS_EXT_NORM;
427 
428 	return error;
429 }
430 
431 static int
xfs_reflink_fill_cow_hole(struct xfs_inode * ip,struct xfs_bmbt_irec * imap,struct xfs_bmbt_irec * cmap,bool * shared,uint * lockmode,bool convert_now)432 xfs_reflink_fill_cow_hole(
433 	struct xfs_inode	*ip,
434 	struct xfs_bmbt_irec	*imap,
435 	struct xfs_bmbt_irec	*cmap,
436 	bool			*shared,
437 	uint			*lockmode,
438 	bool			convert_now)
439 {
440 	struct xfs_mount	*mp = ip->i_mount;
441 	struct xfs_trans	*tp;
442 	xfs_filblks_t		resaligned;
443 	unsigned int		seq_before = READ_ONCE(ip->i_df.if_seq);
444 	unsigned int		dblocks = 0, rblocks = 0;
445 	int			nimaps;
446 	int			error;
447 	bool			found;
448 
449 	resaligned = xfs_aligned_fsb_count(imap->br_startoff,
450 		imap->br_blockcount, xfs_get_cowextsz_hint(ip));
451 	if (XFS_IS_REALTIME_INODE(ip)) {
452 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
453 		rblocks = resaligned;
454 	} else {
455 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, resaligned);
456 		rblocks = 0;
457 	}
458 
459 	xfs_iunlock(ip, *lockmode);
460 	*lockmode = 0;
461 
462 	error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, dblocks,
463 			rblocks, false, &tp);
464 	if (error)
465 		return error;
466 
467 	*lockmode = XFS_ILOCK_EXCL;
468 
469 	/*
470 	 * The data fork mapping may have changed while we dropped the ILOCK
471 	 * (a racing O_DIRECT writer under IOLOCK_SHARED can complete a full
472 	 * CoW cycle including xfs_reflink_end_cow(), which remaps this offset
473 	 * and drops the refcount of the old shared block).  Re-read it so the
474 	 * shared-status recheck below and the caller's in-place iomap both
475 	 * operate on the current mapping rather than a stale physical block.
476 	 */
477 	if (seq_before != READ_ONCE(ip->i_df.if_seq)) {
478 		nimaps = 1;
479 		error = xfs_bmapi_read(ip, imap->br_startoff,
480 				imap->br_blockcount, imap, &nimaps, 0);
481 		if (error)
482 			goto out_trans_cancel;
483 	}
484 
485 	error = xfs_find_trim_cow_extent(ip, imap, cmap, shared, &found);
486 	if (error || !*shared)
487 		goto out_trans_cancel;
488 
489 	if (found) {
490 		xfs_trans_cancel(tp);
491 		goto convert;
492 	}
493 
494 	/* Allocate the entire reservation as unwritten blocks. */
495 	nimaps = 1;
496 	error = xfs_bmapi_write(tp, ip, imap->br_startoff, imap->br_blockcount,
497 			XFS_BMAPI_COWFORK | XFS_BMAPI_PREALLOC, 0, cmap,
498 			&nimaps);
499 	if (error)
500 		goto out_trans_cancel;
501 
502 	xfs_inode_set_cowblocks_tag(ip);
503 	error = xfs_trans_commit(tp);
504 	if (error)
505 		return error;
506 
507 convert:
508 	return xfs_reflink_convert_unwritten(ip, imap, cmap, convert_now);
509 
510 out_trans_cancel:
511 	xfs_trans_cancel(tp);
512 	return error;
513 }
514 
515 static int
xfs_reflink_fill_delalloc(struct xfs_inode * ip,struct xfs_bmbt_irec * imap,struct xfs_bmbt_irec * cmap,bool * shared,uint * lockmode,bool convert_now)516 xfs_reflink_fill_delalloc(
517 	struct xfs_inode	*ip,
518 	struct xfs_bmbt_irec	*imap,
519 	struct xfs_bmbt_irec	*cmap,
520 	bool			*shared,
521 	uint			*lockmode,
522 	bool			convert_now)
523 {
524 	struct xfs_mount	*mp = ip->i_mount;
525 	struct xfs_trans	*tp;
526 	int			nimaps;
527 	int			error;
528 	bool			found;
529 
530 	do {
531 		unsigned int	seq_before = READ_ONCE(ip->i_df.if_seq);
532 
533 		xfs_iunlock(ip, *lockmode);
534 		*lockmode = 0;
535 
536 		error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, 0, 0,
537 				false, &tp);
538 		if (error)
539 			return error;
540 
541 		*lockmode = XFS_ILOCK_EXCL;
542 
543 		/*
544 		 * The data fork mapping may have changed while we dropped the
545 		 * ILOCK (a racing O_DIRECT writer under IOLOCK_SHARED can
546 		 * complete a full CoW cycle including xfs_reflink_end_cow(),
547 		 * which remaps this offset and drops the refcount of the old
548 		 * shared block).  Re-read it so the shared-status recheck
549 		 * below and the caller's in-place iomap both operate on the
550 		 * current mapping rather than a stale physical block.
551 		 */
552 		if (seq_before != READ_ONCE(ip->i_df.if_seq)) {
553 			nimaps = 1;
554 			error = xfs_bmapi_read(ip, imap->br_startoff,
555 					imap->br_blockcount, imap, &nimaps, 0);
556 			if (error)
557 				goto out_trans_cancel;
558 		}
559 
560 		error = xfs_find_trim_cow_extent(ip, imap, cmap, shared,
561 				&found);
562 		if (error || !*shared)
563 			goto out_trans_cancel;
564 
565 		if (found) {
566 			xfs_trans_cancel(tp);
567 			break;
568 		}
569 
570 		ASSERT(isnullstartblock(cmap->br_startblock) ||
571 		       cmap->br_startblock == DELAYSTARTBLOCK);
572 
573 		/*
574 		 * Replace delalloc reservation with an unwritten extent.
575 		 */
576 		nimaps = 1;
577 		error = xfs_bmapi_write(tp, ip, cmap->br_startoff,
578 				cmap->br_blockcount,
579 				XFS_BMAPI_COWFORK | XFS_BMAPI_PREALLOC, 0,
580 				cmap, &nimaps);
581 		if (error)
582 			goto out_trans_cancel;
583 
584 		xfs_inode_set_cowblocks_tag(ip);
585 		error = xfs_trans_commit(tp);
586 		if (error)
587 			return error;
588 	} while (cmap->br_startoff + cmap->br_blockcount <= imap->br_startoff);
589 
590 	return xfs_reflink_convert_unwritten(ip, imap, cmap, convert_now);
591 
592 out_trans_cancel:
593 	xfs_trans_cancel(tp);
594 	return error;
595 }
596 
597 /* Allocate all CoW reservations covering a range of blocks in a file. */
598 int
xfs_reflink_allocate_cow(struct xfs_inode * ip,struct xfs_bmbt_irec * imap,struct xfs_bmbt_irec * cmap,bool * shared,uint * lockmode,bool convert_now)599 xfs_reflink_allocate_cow(
600 	struct xfs_inode	*ip,
601 	struct xfs_bmbt_irec	*imap,
602 	struct xfs_bmbt_irec	*cmap,
603 	bool			*shared,
604 	uint			*lockmode,
605 	bool			convert_now)
606 {
607 	int			error;
608 	bool			found;
609 
610 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
611 	if (!ip->i_cowfp) {
612 		ASSERT(!xfs_is_reflink_inode(ip));
613 		xfs_ifork_init_cow(ip);
614 	}
615 
616 	error = xfs_find_trim_cow_extent(ip, imap, cmap, shared, &found);
617 	if (error || !*shared)
618 		return error;
619 
620 	/* CoW fork has a real extent */
621 	if (found)
622 		return xfs_reflink_convert_unwritten(ip, imap, cmap,
623 				convert_now);
624 
625 	/*
626 	 * CoW fork does not have an extent and data extent is shared.
627 	 * Allocate a real extent in the CoW fork.
628 	 */
629 	if (cmap->br_startoff > imap->br_startoff)
630 		return xfs_reflink_fill_cow_hole(ip, imap, cmap, shared,
631 				lockmode, convert_now);
632 
633 	/*
634 	 * CoW fork has a delalloc reservation. Replace it with a real extent.
635 	 * There may or may not be a data fork mapping.
636 	 */
637 	if (isnullstartblock(cmap->br_startblock) ||
638 	    cmap->br_startblock == DELAYSTARTBLOCK)
639 		return xfs_reflink_fill_delalloc(ip, imap, cmap, shared,
640 				lockmode, convert_now);
641 
642 	/* Shouldn't get here. */
643 	ASSERT(0);
644 	return -EFSCORRUPTED;
645 }
646 
647 /*
648  * Cancel CoW reservations for some block range of an inode.
649  *
650  * If cancel_real is true this function cancels all COW fork extents for the
651  * inode; if cancel_real is false, real extents are not cleared.
652  *
653  * Caller must have already joined the inode to the current transaction. The
654  * inode will be joined to the transaction returned to the caller.
655  */
656 int
xfs_reflink_cancel_cow_blocks(struct xfs_inode * ip,struct xfs_trans ** tpp,xfs_fileoff_t offset_fsb,xfs_fileoff_t end_fsb,bool cancel_real)657 xfs_reflink_cancel_cow_blocks(
658 	struct xfs_inode		*ip,
659 	struct xfs_trans		**tpp,
660 	xfs_fileoff_t			offset_fsb,
661 	xfs_fileoff_t			end_fsb,
662 	bool				cancel_real)
663 {
664 	struct xfs_ifork		*ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
665 	struct xfs_bmbt_irec		got, del;
666 	struct xfs_iext_cursor		icur;
667 	bool				isrt = XFS_IS_REALTIME_INODE(ip);
668 	int				error = 0;
669 
670 	if (!xfs_inode_has_cow_data(ip))
671 		return 0;
672 	if (!xfs_iext_lookup_extent_before(ip, ifp, &end_fsb, &icur, &got))
673 		return 0;
674 
675 	/* Walk backwards until we're out of the I/O range... */
676 	while (got.br_startoff + got.br_blockcount > offset_fsb) {
677 		del = got;
678 		xfs_trim_extent(&del, offset_fsb, end_fsb - offset_fsb);
679 
680 		/* Extent delete may have bumped ext forward */
681 		if (!del.br_blockcount) {
682 			xfs_iext_prev(ifp, &icur);
683 			goto next_extent;
684 		}
685 
686 		trace_xfs_reflink_cancel_cow(ip, &del);
687 
688 		if (isnullstartblock(del.br_startblock)) {
689 			xfs_bmap_del_extent_delay(ip, XFS_COW_FORK, &icur, &got,
690 					&del, 0);
691 		} else if (del.br_state == XFS_EXT_UNWRITTEN || cancel_real) {
692 			ASSERT((*tpp)->t_highest_agno == NULLAGNUMBER);
693 
694 			/* Free the CoW orphan record. */
695 			xfs_refcount_free_cow_extent(*tpp, isrt,
696 					del.br_startblock, del.br_blockcount);
697 
698 			error = xfs_free_extent_later(*tpp, del.br_startblock,
699 					del.br_blockcount, NULL,
700 					XFS_AG_RESV_NONE,
701 					isrt ? XFS_FREE_EXTENT_REALTIME : 0);
702 			if (error)
703 				break;
704 
705 			/* Roll the transaction */
706 			error = xfs_defer_finish(tpp);
707 			if (error)
708 				break;
709 
710 			/* Remove the mapping from the CoW fork. */
711 			xfs_bmap_del_extent_cow(ip, &icur, &got, &del);
712 
713 			/* Remove the quota reservation */
714 			xfs_quota_unreserve_blkres(ip, del.br_blockcount);
715 		} else {
716 			/* Didn't do anything, push cursor back. */
717 			xfs_iext_prev(ifp, &icur);
718 		}
719 next_extent:
720 		if (!xfs_iext_get_extent(ifp, &icur, &got))
721 			break;
722 	}
723 
724 	/* clear tag if cow fork is emptied */
725 	if (!ifp->if_bytes)
726 		xfs_inode_clear_cowblocks_tag(ip);
727 	return error;
728 }
729 
730 /*
731  * Cancel CoW reservations for some byte range of an inode.
732  *
733  * If cancel_real is true this function cancels all COW fork extents for the
734  * inode; if cancel_real is false, real extents are not cleared.
735  */
736 int
xfs_reflink_cancel_cow_range(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t count,bool cancel_real)737 xfs_reflink_cancel_cow_range(
738 	struct xfs_inode	*ip,
739 	xfs_off_t		offset,
740 	xfs_off_t		count,
741 	bool			cancel_real)
742 {
743 	struct xfs_trans	*tp;
744 	xfs_fileoff_t		offset_fsb;
745 	xfs_fileoff_t		end_fsb;
746 	int			error;
747 
748 	trace_xfs_reflink_cancel_cow_range(ip, offset, count);
749 	ASSERT(ip->i_cowfp);
750 
751 	offset_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
752 	if (count == NULLFILEOFF)
753 		end_fsb = NULLFILEOFF;
754 	else
755 		end_fsb = XFS_B_TO_FSB(ip->i_mount, offset + count);
756 
757 	/* Start a rolling transaction to remove the mappings */
758 	error = xfs_trans_alloc(ip->i_mount, &M_RES(ip->i_mount)->tr_write,
759 			0, 0, 0, &tp);
760 	if (error)
761 		goto out;
762 
763 	xfs_ilock(ip, XFS_ILOCK_EXCL);
764 	xfs_trans_ijoin(tp, ip, 0);
765 
766 	/* Scrape out the old CoW reservations */
767 	error = xfs_reflink_cancel_cow_blocks(ip, &tp, offset_fsb, end_fsb,
768 			cancel_real);
769 	if (error)
770 		goto out_cancel;
771 
772 	error = xfs_trans_commit(tp);
773 
774 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
775 	return error;
776 
777 out_cancel:
778 	xfs_trans_cancel(tp);
779 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
780 out:
781 	trace_xfs_reflink_cancel_cow_range_error(ip, error, _RET_IP_);
782 	return error;
783 }
784 
785 #ifdef CONFIG_XFS_QUOTA
786 /*
787  * Update quota accounting for a remapping operation.  When we're remapping
788  * something from the CoW fork to the data fork, we must update the quota
789  * accounting for delayed allocations.  For remapping from the data fork to the
790  * data fork, use regular block accounting.
791  */
792 static inline void
xfs_reflink_update_quota(struct xfs_trans * tp,struct xfs_inode * ip,bool is_cow,int64_t blocks)793 xfs_reflink_update_quota(
794 	struct xfs_trans	*tp,
795 	struct xfs_inode	*ip,
796 	bool			is_cow,
797 	int64_t			blocks)
798 {
799 	unsigned int		qflag;
800 
801 	if (XFS_IS_REALTIME_INODE(ip)) {
802 		qflag = is_cow ? XFS_TRANS_DQ_DELRTBCOUNT :
803 				 XFS_TRANS_DQ_RTBCOUNT;
804 	} else {
805 		qflag = is_cow ? XFS_TRANS_DQ_DELBCOUNT :
806 				 XFS_TRANS_DQ_BCOUNT;
807 	}
808 	xfs_trans_mod_dquot_byino(tp, ip, qflag, blocks);
809 }
810 #else
811 # define xfs_reflink_update_quota(tp, ip, is_cow, blocks)	((void)0)
812 #endif
813 
814 /*
815  * Remap part of the CoW fork into the data fork.
816  *
817  * We aim to remap the range starting at @offset_fsb and ending at @end_fsb
818  * into the data fork; this function will remap what it can (at the end of the
819  * range) and update @end_fsb appropriately.  Each remap gets its own
820  * transaction because we can end up merging and splitting bmbt blocks for
821  * every remap operation and we'd like to keep the block reservation
822  * requirements as low as possible.
823  */
824 STATIC int
xfs_reflink_end_cow_extent_locked(struct xfs_trans * tp,struct xfs_inode * ip,xfs_fileoff_t * offset_fsb,xfs_fileoff_t end_fsb)825 xfs_reflink_end_cow_extent_locked(
826 	struct xfs_trans	*tp,
827 	struct xfs_inode	*ip,
828 	xfs_fileoff_t		*offset_fsb,
829 	xfs_fileoff_t		end_fsb)
830 {
831 	struct xfs_iext_cursor	icur;
832 	struct xfs_bmbt_irec	got, del, data;
833 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
834 	int			nmaps;
835 	bool			isrt = XFS_IS_REALTIME_INODE(ip);
836 	int			error;
837 
838 	/*
839 	 * In case of racing, overlapping AIO writes no COW extents might be
840 	 * left by the time I/O completes for the loser of the race.  In that
841 	 * case we are done.
842 	 */
843 	if (!xfs_iext_lookup_extent(ip, ifp, *offset_fsb, &icur, &got) ||
844 	    got.br_startoff >= end_fsb) {
845 		*offset_fsb = end_fsb;
846 		return 0;
847 	}
848 
849 	/*
850 	 * Only remap real extents that contain data.  With AIO, speculative
851 	 * preallocations can leak into the range we are called upon, and we
852 	 * need to skip them.  Preserve @got for the eventual CoW fork
853 	 * deletion; from now on @del represents the mapping that we're
854 	 * actually remapping.
855 	 */
856 	while (!xfs_bmap_is_written_extent(&got)) {
857 		if (!xfs_iext_next_extent(ifp, &icur, &got) ||
858 		    got.br_startoff >= end_fsb) {
859 			*offset_fsb = end_fsb;
860 			return 0;
861 		}
862 	}
863 	del = got;
864 	xfs_trim_extent(&del, *offset_fsb, end_fsb - *offset_fsb);
865 
866 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
867 			XFS_IEXT_REFLINK_END_COW_CNT);
868 	if (error)
869 		return error;
870 
871 	/* Grab the corresponding mapping in the data fork. */
872 	nmaps = 1;
873 	error = xfs_bmapi_read(ip, del.br_startoff, del.br_blockcount, &data,
874 			&nmaps, 0);
875 	if (error)
876 		return error;
877 
878 	/* We can only remap the smaller of the two extent sizes. */
879 	data.br_blockcount = min(data.br_blockcount, del.br_blockcount);
880 	del.br_blockcount = data.br_blockcount;
881 
882 	trace_xfs_reflink_cow_remap_from(ip, &del);
883 	trace_xfs_reflink_cow_remap_to(ip, &data);
884 
885 	if (xfs_bmap_is_real_extent(&data)) {
886 		/*
887 		 * If the extent we're remapping is backed by storage (written
888 		 * or not), unmap the extent and drop its refcount.
889 		 */
890 		xfs_bmap_unmap_extent(tp, ip, XFS_DATA_FORK, &data);
891 		xfs_refcount_decrease_extent(tp, isrt, &data);
892 		xfs_reflink_update_quota(tp, ip, false, -data.br_blockcount);
893 	} else if (data.br_startblock == DELAYSTARTBLOCK) {
894 		int		done;
895 
896 		/*
897 		 * If the extent we're remapping is a delalloc reservation,
898 		 * we can use the regular bunmapi function to release the
899 		 * incore state.  Dropping the delalloc reservation takes care
900 		 * of the quota reservation for us.
901 		 */
902 		error = xfs_bunmapi(NULL, ip, data.br_startoff,
903 				data.br_blockcount, 0, 1, &done);
904 		if (error)
905 			return error;
906 		ASSERT(done);
907 	}
908 
909 	/* Free the CoW orphan record. */
910 	xfs_refcount_free_cow_extent(tp, isrt, del.br_startblock,
911 			del.br_blockcount);
912 
913 	/* Map the new blocks into the data fork. */
914 	xfs_bmap_map_extent(tp, ip, XFS_DATA_FORK, &del);
915 
916 	/* Charge this new data fork mapping to the on-disk quota. */
917 	xfs_reflink_update_quota(tp, ip, true, del.br_blockcount);
918 
919 	/* Remove the mapping from the CoW fork. */
920 	xfs_bmap_del_extent_cow(ip, &icur, &got, &del);
921 
922 	/* Update the caller about how much progress we made. */
923 	*offset_fsb = del.br_startoff + del.br_blockcount;
924 	return 0;
925 }
926 
927 /*
928  * Remap part of the CoW fork into the data fork.
929  *
930  * We aim to remap the range starting at @offset_fsb and ending at @end_fsb
931  * into the data fork; this function will remap what it can (at the end of the
932  * range) and update @end_fsb appropriately.  Each remap gets its own
933  * transaction because we can end up merging and splitting bmbt blocks for
934  * every remap operation and we'd like to keep the block reservation
935  * requirements as low as possible.
936  */
937 STATIC int
xfs_reflink_end_cow_extent(struct xfs_inode * ip,xfs_fileoff_t * offset_fsb,xfs_fileoff_t end_fsb)938 xfs_reflink_end_cow_extent(
939 	struct xfs_inode	*ip,
940 	xfs_fileoff_t		*offset_fsb,
941 	xfs_fileoff_t		end_fsb)
942 {
943 	struct xfs_mount	*mp = ip->i_mount;
944 	struct xfs_trans	*tp;
945 	unsigned int		resblks;
946 	int			error;
947 
948 	resblks = XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK);
949 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0,
950 			XFS_TRANS_RESERVE, &tp);
951 	if (error)
952 		return error;
953 	xfs_ilock(ip, XFS_ILOCK_EXCL);
954 	xfs_trans_ijoin(tp, ip, 0);
955 
956 	error = xfs_reflink_end_cow_extent_locked(tp, ip, offset_fsb, end_fsb);
957 	if (error)
958 		xfs_trans_cancel(tp);
959 	else
960 		error = xfs_trans_commit(tp);
961 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
962 	return error;
963 }
964 
965 /*
966  * Remap parts of a file's data fork after a successful CoW.
967  */
968 int
xfs_reflink_end_cow(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t count)969 xfs_reflink_end_cow(
970 	struct xfs_inode		*ip,
971 	xfs_off_t			offset,
972 	xfs_off_t			count)
973 {
974 	xfs_fileoff_t			offset_fsb;
975 	xfs_fileoff_t			end_fsb;
976 	int				error = 0;
977 
978 	trace_xfs_reflink_end_cow(ip, offset, count);
979 
980 	offset_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
981 	end_fsb = XFS_B_TO_FSB(ip->i_mount, offset + count);
982 
983 	/*
984 	 * Walk forwards until we've remapped the I/O range.  The loop function
985 	 * repeatedly cycles the ILOCK to allocate one transaction per remapped
986 	 * extent.
987 	 *
988 	 * If we're being called by writeback then the folios will still
989 	 * have the writeback flag set, which prevents races with reflink
990 	 * remapping and truncate.  Reflink remapping prevents races with
991 	 * writeback by taking the iolock and mmaplock before flushing
992 	 * the folios and remapping, which means there won't be any further
993 	 * writeback or page cache dirtying until the reflink completes.
994 	 *
995 	 * We should never have two threads issuing writeback for the same file
996 	 * region.  There are also have post-eof checks in the writeback
997 	 * preparation code so that we don't bother writing out folios that are
998 	 * about to be truncated.
999 	 *
1000 	 * If we're being called as part of directio write completion, the dio
1001 	 * count is still elevated, which reflink and truncate will wait for.
1002 	 * Reflink remapping takes the iolock and mmaplock and waits for
1003 	 * pending dio to finish, which should prevent any directio until the
1004 	 * remap completes.  Multiple concurrent directio writes to the same
1005 	 * region are handled by end_cow processing only occurring for the
1006 	 * threads which succeed; the outcome of multiple overlapping direct
1007 	 * writes is not well defined anyway.
1008 	 *
1009 	 * It's possible that a buffered write and a direct write could collide
1010 	 * here (the buffered write stumbles in after the dio flushes and
1011 	 * invalidates the page cache and immediately queues writeback), but we
1012 	 * have never supported this 100%.  If either disk write succeeds the
1013 	 * blocks will be remapped.
1014 	 */
1015 	while (end_fsb > offset_fsb && !error)
1016 		error = xfs_reflink_end_cow_extent(ip, &offset_fsb, end_fsb);
1017 
1018 	if (error)
1019 		trace_xfs_reflink_end_cow_error(ip, error, _RET_IP_);
1020 	return error;
1021 }
1022 
1023 /*
1024  * Fully remap all of the file's data fork at once, which is the critical part
1025  * in achieving atomic behaviour.
1026  * The regular CoW end path does not use function as to keep the block
1027  * reservation per transaction as low as possible.
1028  */
1029 int
xfs_reflink_end_atomic_cow(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t count)1030 xfs_reflink_end_atomic_cow(
1031 	struct xfs_inode		*ip,
1032 	xfs_off_t			offset,
1033 	xfs_off_t			count)
1034 {
1035 	xfs_fileoff_t			offset_fsb;
1036 	xfs_fileoff_t			end_fsb;
1037 	int				error = 0;
1038 	struct xfs_mount		*mp = ip->i_mount;
1039 	struct xfs_trans		*tp;
1040 	unsigned int			resblks;
1041 
1042 	trace_xfs_reflink_end_cow(ip, offset, count);
1043 
1044 	offset_fsb = XFS_B_TO_FSBT(mp, offset);
1045 	end_fsb = XFS_B_TO_FSB(mp, offset + count);
1046 
1047 	/*
1048 	 * Each remapping operation could cause a btree split, so in the worst
1049 	 * case that's one for each block.
1050 	 */
1051 	resblks = (end_fsb - offset_fsb) *
1052 			XFS_NEXTENTADD_SPACE_RES(mp, 1, XFS_DATA_FORK);
1053 
1054 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_atomic_ioend, resblks, 0,
1055 			XFS_TRANS_RESERVE, &tp);
1056 	if (error)
1057 		return error;
1058 
1059 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1060 	xfs_trans_ijoin(tp, ip, 0);
1061 
1062 	while (end_fsb > offset_fsb && !error) {
1063 		error = xfs_reflink_end_cow_extent_locked(tp, ip, &offset_fsb,
1064 				end_fsb);
1065 	}
1066 	if (error) {
1067 		trace_xfs_reflink_end_cow_error(ip, error, _RET_IP_);
1068 		goto out_cancel;
1069 	}
1070 	error = xfs_trans_commit(tp);
1071 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1072 	return error;
1073 out_cancel:
1074 	xfs_trans_cancel(tp);
1075 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1076 	return error;
1077 }
1078 
1079 /* Compute the largest atomic write that we can complete through software. */
1080 xfs_extlen_t
xfs_reflink_max_atomic_cow(struct xfs_mount * mp)1081 xfs_reflink_max_atomic_cow(
1082 	struct xfs_mount	*mp)
1083 {
1084 	/* We cannot do any atomic writes without out of place writes. */
1085 	if (!xfs_can_sw_atomic_write(mp))
1086 		return 0;
1087 
1088 	/*
1089 	 * Atomic write limits must always be a power-of-2, according to
1090 	 * generic_atomic_write_valid.
1091 	 */
1092 	return rounddown_pow_of_two(xfs_calc_max_atomic_write_fsblocks(mp));
1093 }
1094 
1095 /*
1096  * Free all CoW staging blocks that are still referenced by the ondisk refcount
1097  * metadata.  The ondisk metadata does not track which inode created the
1098  * staging extent, so callers must ensure that there are no cached inodes with
1099  * live CoW staging extents.
1100  */
1101 int
xfs_reflink_recover_cow(struct xfs_mount * mp)1102 xfs_reflink_recover_cow(
1103 	struct xfs_mount	*mp)
1104 {
1105 	struct xfs_perag	*pag = NULL;
1106 	struct xfs_rtgroup	*rtg = NULL;
1107 	int			error = 0;
1108 
1109 	if (!xfs_has_reflink(mp))
1110 		return 0;
1111 
1112 	while ((pag = xfs_perag_next(mp, pag))) {
1113 		error = xfs_refcount_recover_cow_leftovers(pag_group(pag));
1114 		if (error) {
1115 			xfs_perag_rele(pag);
1116 			return error;
1117 		}
1118 	}
1119 
1120 	while ((rtg = xfs_rtgroup_next(mp, rtg))) {
1121 		error = xfs_refcount_recover_cow_leftovers(rtg_group(rtg));
1122 		if (error) {
1123 			xfs_rtgroup_rele(rtg);
1124 			return error;
1125 		}
1126 	}
1127 
1128 	return 0;
1129 }
1130 
1131 /*
1132  * Reflinking (Block) Ranges of Two Files Together
1133  *
1134  * First, ensure that the reflink flag is set on both inodes.  The flag is an
1135  * optimization to avoid unnecessary refcount btree lookups in the write path.
1136  *
1137  * Now we can iteratively remap the range of extents (and holes) in src to the
1138  * corresponding ranges in dest.  Let drange and srange denote the ranges of
1139  * logical blocks in dest and src touched by the reflink operation.
1140  *
1141  * While the length of drange is greater than zero,
1142  *    - Read src's bmbt at the start of srange ("imap")
1143  *    - If imap doesn't exist, make imap appear to start at the end of srange
1144  *      with zero length.
1145  *    - If imap starts before srange, advance imap to start at srange.
1146  *    - If imap goes beyond srange, truncate imap to end at the end of srange.
1147  *    - Punch (imap start - srange start + imap len) blocks from dest at
1148  *      offset (drange start).
1149  *    - If imap points to a real range of pblks,
1150  *         > Increase the refcount of the imap's pblks
1151  *         > Map imap's pblks into dest at the offset
1152  *           (drange start + imap start - srange start)
1153  *    - Advance drange and srange by (imap start - srange start + imap len)
1154  *
1155  * Finally, if the reflink made dest longer, update both the in-core and
1156  * on-disk file sizes.
1157  *
1158  * ASCII Art Demonstration:
1159  *
1160  * Let's say we want to reflink this source file:
1161  *
1162  * ----SSSSSSS-SSSSS----SSSSSS (src file)
1163  *   <-------------------->
1164  *
1165  * into this destination file:
1166  *
1167  * --DDDDDDDDDDDDDDDDDDD--DDD (dest file)
1168  *        <-------------------->
1169  * '-' means a hole, and 'S' and 'D' are written blocks in the src and dest.
1170  * Observe that the range has different logical offsets in either file.
1171  *
1172  * Consider that the first extent in the source file doesn't line up with our
1173  * reflink range.  Unmapping  and remapping are separate operations, so we can
1174  * unmap more blocks from the destination file than we remap.
1175  *
1176  * ----SSSSSSS-SSSSS----SSSSSS
1177  *   <------->
1178  * --DDDDD---------DDDDD--DDD
1179  *        <------->
1180  *
1181  * Now remap the source extent into the destination file:
1182  *
1183  * ----SSSSSSS-SSSSS----SSSSSS
1184  *   <------->
1185  * --DDDDD--SSSSSSSDDDDD--DDD
1186  *        <------->
1187  *
1188  * Do likewise with the second hole and extent in our range.  Holes in the
1189  * unmap range don't affect our operation.
1190  *
1191  * ----SSSSSSS-SSSSS----SSSSSS
1192  *            <---->
1193  * --DDDDD--SSSSSSS-SSSSS-DDD
1194  *                 <---->
1195  *
1196  * Finally, unmap and remap part of the third extent.  This will increase the
1197  * size of the destination file.
1198  *
1199  * ----SSSSSSS-SSSSS----SSSSSS
1200  *                  <----->
1201  * --DDDDD--SSSSSSS-SSSSS----SSS
1202  *                       <----->
1203  *
1204  * Once we update the destination file's i_size, we're done.
1205  */
1206 
1207 /*
1208  * Ensure the reflink bit is set in both inodes.
1209  */
1210 STATIC int
xfs_reflink_set_inode_flag(struct xfs_inode * src,struct xfs_inode * dest)1211 xfs_reflink_set_inode_flag(
1212 	struct xfs_inode	*src,
1213 	struct xfs_inode	*dest)
1214 {
1215 	struct xfs_mount	*mp = src->i_mount;
1216 	int			error;
1217 	struct xfs_trans	*tp;
1218 
1219 	if (xfs_is_reflink_inode(src) && xfs_is_reflink_inode(dest))
1220 		return 0;
1221 
1222 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);
1223 	if (error)
1224 		goto out_error;
1225 
1226 	/* Lock both files against IO */
1227 	if (I_INO(src) == I_INO(dest))
1228 		xfs_ilock(src, XFS_ILOCK_EXCL);
1229 	else
1230 		xfs_lock_two_inodes(src, XFS_ILOCK_EXCL, dest, XFS_ILOCK_EXCL);
1231 
1232 	if (!xfs_is_reflink_inode(src)) {
1233 		trace_xfs_reflink_set_inode_flag(src);
1234 		xfs_trans_ijoin(tp, src, XFS_ILOCK_EXCL);
1235 		src->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1236 		xfs_trans_log_inode(tp, src, XFS_ILOG_CORE);
1237 		xfs_ifork_init_cow(src);
1238 	} else
1239 		xfs_iunlock(src, XFS_ILOCK_EXCL);
1240 
1241 	if (I_INO(src) == I_INO(dest))
1242 		goto commit_flags;
1243 
1244 	if (!xfs_is_reflink_inode(dest)) {
1245 		trace_xfs_reflink_set_inode_flag(dest);
1246 		xfs_trans_ijoin(tp, dest, XFS_ILOCK_EXCL);
1247 		dest->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1248 		xfs_trans_log_inode(tp, dest, XFS_ILOG_CORE);
1249 		xfs_ifork_init_cow(dest);
1250 	} else
1251 		xfs_iunlock(dest, XFS_ILOCK_EXCL);
1252 
1253 commit_flags:
1254 	error = xfs_trans_commit(tp);
1255 	if (error)
1256 		goto out_error;
1257 	return error;
1258 
1259 out_error:
1260 	trace_xfs_reflink_set_inode_flag_error(dest, error, _RET_IP_);
1261 	return error;
1262 }
1263 
1264 /*
1265  * Update destination inode size & cowextsize hint, if necessary.
1266  */
1267 int
xfs_reflink_update_dest(struct xfs_inode * dest,xfs_off_t newlen,xfs_extlen_t cowextsize,unsigned int remap_flags)1268 xfs_reflink_update_dest(
1269 	struct xfs_inode	*dest,
1270 	xfs_off_t		newlen,
1271 	xfs_extlen_t		cowextsize,
1272 	unsigned int		remap_flags)
1273 {
1274 	struct xfs_mount	*mp = dest->i_mount;
1275 	struct xfs_trans	*tp;
1276 	int			error;
1277 
1278 	if (newlen <= i_size_read(VFS_I(dest)) && cowextsize == 0)
1279 		return 0;
1280 
1281 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);
1282 	if (error)
1283 		goto out_error;
1284 
1285 	xfs_ilock(dest, XFS_ILOCK_EXCL);
1286 	xfs_trans_ijoin(tp, dest, XFS_ILOCK_EXCL);
1287 
1288 	if (newlen > i_size_read(VFS_I(dest))) {
1289 		trace_xfs_reflink_update_inode_size(dest, newlen);
1290 		i_size_write(VFS_I(dest), newlen);
1291 		dest->i_disk_size = newlen;
1292 	}
1293 
1294 	if (cowextsize) {
1295 		dest->i_cowextsize = cowextsize;
1296 		dest->i_diflags2 |= XFS_DIFLAG2_COWEXTSIZE;
1297 	}
1298 
1299 	xfs_trans_log_inode(tp, dest, XFS_ILOG_CORE);
1300 
1301 	error = xfs_trans_commit(tp);
1302 	if (error)
1303 		goto out_error;
1304 	return error;
1305 
1306 out_error:
1307 	trace_xfs_reflink_update_inode_size_error(dest, error, _RET_IP_);
1308 	return error;
1309 }
1310 
1311 /*
1312  * Do we have enough reserve in this AG to handle a reflink?  The refcount
1313  * btree already reserved all the space it needs, but the rmap btree can grow
1314  * infinitely, so we won't allow more reflinks when the AG is down to the
1315  * btree reserves.
1316  */
1317 static int
xfs_reflink_ag_has_free_space(struct xfs_mount * mp,struct xfs_inode * ip,xfs_fsblock_t fsb)1318 xfs_reflink_ag_has_free_space(
1319 	struct xfs_mount	*mp,
1320 	struct xfs_inode	*ip,
1321 	xfs_fsblock_t		fsb)
1322 {
1323 	struct xfs_perag	*pag;
1324 	xfs_agnumber_t		agno;
1325 	int			error = 0;
1326 
1327 	if (!xfs_has_rmapbt(mp))
1328 		return 0;
1329 	if (XFS_IS_REALTIME_INODE(ip)) {
1330 		if (xfs_metafile_resv_critical(mp))
1331 			return -ENOSPC;
1332 		return 0;
1333 	}
1334 
1335 	agno = XFS_FSB_TO_AGNO(mp, fsb);
1336 	pag = xfs_perag_get(mp, agno);
1337 	if (xfs_ag_resv_critical(pag, XFS_AG_RESV_RMAPBT) ||
1338 	    xfs_ag_resv_critical(pag, XFS_AG_RESV_METADATA))
1339 		error = -ENOSPC;
1340 	xfs_perag_put(pag);
1341 	return error;
1342 }
1343 
1344 /*
1345  * Remap the given extent into the file.  The dmap blockcount will be set to
1346  * the number of blocks that were actually remapped.
1347  */
1348 STATIC int
xfs_reflink_remap_extent(struct xfs_inode * ip,struct xfs_bmbt_irec * dmap,xfs_off_t new_isize)1349 xfs_reflink_remap_extent(
1350 	struct xfs_inode	*ip,
1351 	struct xfs_bmbt_irec	*dmap,
1352 	xfs_off_t		new_isize)
1353 {
1354 	struct xfs_bmbt_irec	smap;
1355 	struct xfs_mount	*mp = ip->i_mount;
1356 	struct xfs_trans	*tp;
1357 	xfs_off_t		newlen;
1358 	int64_t			qdelta = 0;
1359 	unsigned int		dblocks, rblocks, resblks;
1360 	bool			quota_reserved = true;
1361 	bool			smap_real;
1362 	bool			dmap_written = xfs_bmap_is_written_extent(dmap);
1363 	bool			isrt = XFS_IS_REALTIME_INODE(ip);
1364 	int			iext_delta = 0;
1365 	int			nimaps;
1366 	int			error;
1367 
1368 	/*
1369 	 * Start a rolling transaction to switch the mappings.
1370 	 *
1371 	 * Adding a written extent to the extent map can cause a bmbt split,
1372 	 * and removing a mapped extent from the extent can cause a bmbt split.
1373 	 * The two operations cannot both cause a split since they operate on
1374 	 * the same index in the bmap btree, so we only need a reservation for
1375 	 * one bmbt split if either thing is happening.  However, we haven't
1376 	 * locked the inode yet, so we reserve assuming this is the case.
1377 	 *
1378 	 * The first allocation call tries to reserve enough space to handle
1379 	 * mapping dmap into a sparse part of the file plus the bmbt split.  We
1380 	 * haven't locked the inode or read the existing mapping yet, so we do
1381 	 * not know for sure that we need the space.  This should succeed most
1382 	 * of the time.
1383 	 *
1384 	 * If the first attempt fails, try again but reserving only enough
1385 	 * space to handle a bmbt split.  This is the hard minimum requirement,
1386 	 * and we revisit quota reservations later when we know more about what
1387 	 * we're remapping.
1388 	 */
1389 	resblks = XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK);
1390 	if (XFS_IS_REALTIME_INODE(ip)) {
1391 		dblocks = resblks;
1392 		rblocks = dmap->br_blockcount;
1393 	} else {
1394 		dblocks = resblks + dmap->br_blockcount;
1395 		rblocks = 0;
1396 	}
1397 	error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write,
1398 			dblocks, rblocks, false, &tp);
1399 	if (error == -EDQUOT || error == -ENOSPC) {
1400 		quota_reserved = false;
1401 		error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write,
1402 				resblks, 0, false, &tp);
1403 	}
1404 	if (error)
1405 		goto out;
1406 
1407 	/*
1408 	 * Read what's currently mapped in the destination file into smap.
1409 	 * If smap isn't a hole, we will have to remove it before we can add
1410 	 * dmap to the destination file.
1411 	 */
1412 	nimaps = 1;
1413 	error = xfs_bmapi_read(ip, dmap->br_startoff, dmap->br_blockcount,
1414 			&smap, &nimaps, 0);
1415 	if (error)
1416 		goto out_cancel;
1417 	ASSERT(nimaps == 1 && smap.br_startoff == dmap->br_startoff);
1418 	smap_real = xfs_bmap_is_real_extent(&smap);
1419 
1420 	/*
1421 	 * We can only remap as many blocks as the smaller of the two extent
1422 	 * maps, because we can only remap one extent at a time.
1423 	 */
1424 	dmap->br_blockcount = min(dmap->br_blockcount, smap.br_blockcount);
1425 	ASSERT(dmap->br_blockcount == smap.br_blockcount);
1426 
1427 	trace_xfs_reflink_remap_extent_dest(ip, &smap);
1428 
1429 	/*
1430 	 * Two extents mapped to the same physical block must not have
1431 	 * different states; that's filesystem corruption.  Move on to the next
1432 	 * extent if they're both holes or both the same physical extent.
1433 	 */
1434 	if (dmap->br_startblock == smap.br_startblock) {
1435 		if (dmap->br_state != smap.br_state) {
1436 			xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
1437 			error = -EFSCORRUPTED;
1438 		}
1439 		goto out_cancel;
1440 	}
1441 
1442 	/* If both extents are unwritten, leave them alone. */
1443 	if (dmap->br_state == XFS_EXT_UNWRITTEN &&
1444 	    smap.br_state == XFS_EXT_UNWRITTEN)
1445 		goto out_cancel;
1446 
1447 	/* No reflinking if the AG of the dest mapping is low on space. */
1448 	if (dmap_written) {
1449 		error = xfs_reflink_ag_has_free_space(mp, ip,
1450 				dmap->br_startblock);
1451 		if (error)
1452 			goto out_cancel;
1453 	}
1454 
1455 	/*
1456 	 * Increase quota reservation if we think the quota block counter for
1457 	 * this file could increase.
1458 	 *
1459 	 * If we are mapping a written extent into the file, we need to have
1460 	 * enough quota block count reservation to handle the blocks in that
1461 	 * extent.  We log only the delta to the quota block counts, so if the
1462 	 * extent we're unmapping also has blocks allocated to it, we don't
1463 	 * need a quota reservation for the extent itself.
1464 	 *
1465 	 * Note that if we're replacing a delalloc reservation with a written
1466 	 * extent, we have to take the full quota reservation because removing
1467 	 * the delalloc reservation gives the block count back to the quota
1468 	 * count.  This is suboptimal, but the VFS flushed the dest range
1469 	 * before we started.  That should have removed all the delalloc
1470 	 * reservations, but we code defensively.
1471 	 *
1472 	 * xfs_trans_alloc_inode above already tried to grab an even larger
1473 	 * quota reservation, and kicked off a blockgc scan if it couldn't.
1474 	 * If we can't get a potentially smaller quota reservation now, we're
1475 	 * done.
1476 	 */
1477 	if (!quota_reserved && !smap_real && dmap_written) {
1478 		if (XFS_IS_REALTIME_INODE(ip)) {
1479 			dblocks = 0;
1480 			rblocks = dmap->br_blockcount;
1481 		} else {
1482 			dblocks = dmap->br_blockcount;
1483 			rblocks = 0;
1484 		}
1485 		error = xfs_trans_reserve_quota_nblks(tp, ip, dblocks, rblocks,
1486 				false);
1487 		if (error)
1488 			goto out_cancel;
1489 	}
1490 
1491 	if (smap_real)
1492 		++iext_delta;
1493 
1494 	if (dmap_written)
1495 		++iext_delta;
1496 
1497 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK, iext_delta);
1498 	if (error)
1499 		goto out_cancel;
1500 
1501 	if (smap_real) {
1502 		/*
1503 		 * If the extent we're unmapping is backed by storage (written
1504 		 * or not), unmap the extent and drop its refcount.
1505 		 */
1506 		xfs_bmap_unmap_extent(tp, ip, XFS_DATA_FORK, &smap);
1507 		xfs_refcount_decrease_extent(tp, isrt, &smap);
1508 		qdelta -= smap.br_blockcount;
1509 	} else if (smap.br_startblock == DELAYSTARTBLOCK) {
1510 		int		done;
1511 
1512 		/*
1513 		 * If the extent we're unmapping is a delalloc reservation,
1514 		 * we can use the regular bunmapi function to release the
1515 		 * incore state.  Dropping the delalloc reservation takes care
1516 		 * of the quota reservation for us.
1517 		 */
1518 		error = xfs_bunmapi(NULL, ip, smap.br_startoff,
1519 				smap.br_blockcount, 0, 1, &done);
1520 		if (error)
1521 			goto out_cancel;
1522 		ASSERT(done);
1523 	}
1524 
1525 	/*
1526 	 * If the extent we're sharing is backed by written storage, increase
1527 	 * its refcount and map it into the file.
1528 	 */
1529 	if (dmap_written) {
1530 		xfs_refcount_increase_extent(tp, isrt, dmap);
1531 		xfs_bmap_map_extent(tp, ip, XFS_DATA_FORK, dmap);
1532 		qdelta += dmap->br_blockcount;
1533 	}
1534 
1535 	xfs_reflink_update_quota(tp, ip, false, qdelta);
1536 
1537 	/* Update dest isize if needed. */
1538 	newlen = XFS_FSB_TO_B(mp, dmap->br_startoff + dmap->br_blockcount);
1539 	newlen = min_t(xfs_off_t, newlen, new_isize);
1540 	if (newlen > i_size_read(VFS_I(ip))) {
1541 		trace_xfs_reflink_update_inode_size(ip, newlen);
1542 		i_size_write(VFS_I(ip), newlen);
1543 		ip->i_disk_size = newlen;
1544 		xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1545 	}
1546 
1547 	/* Commit everything and unlock. */
1548 	error = xfs_trans_commit(tp);
1549 	goto out_unlock;
1550 
1551 out_cancel:
1552 	xfs_trans_cancel(tp);
1553 out_unlock:
1554 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1555 out:
1556 	if (error)
1557 		trace_xfs_reflink_remap_extent_error(ip, error, _RET_IP_);
1558 	return error;
1559 }
1560 
1561 /* Remap a range of one file to the other. */
1562 int
xfs_reflink_remap_blocks(struct xfs_inode * src,loff_t pos_in,struct xfs_inode * dest,loff_t pos_out,loff_t remap_len,loff_t * remapped)1563 xfs_reflink_remap_blocks(
1564 	struct xfs_inode	*src,
1565 	loff_t			pos_in,
1566 	struct xfs_inode	*dest,
1567 	loff_t			pos_out,
1568 	loff_t			remap_len,
1569 	loff_t			*remapped)
1570 {
1571 	struct xfs_bmbt_irec	imap;
1572 	struct xfs_mount	*mp = src->i_mount;
1573 	xfs_fileoff_t		srcoff = XFS_B_TO_FSBT(mp, pos_in);
1574 	xfs_fileoff_t		destoff = XFS_B_TO_FSBT(mp, pos_out);
1575 	xfs_filblks_t		len;
1576 	xfs_filblks_t		remapped_len = 0;
1577 	xfs_off_t		new_isize = pos_out + remap_len;
1578 	int			nimaps;
1579 	int			error = 0;
1580 
1581 	len = min_t(xfs_filblks_t, XFS_B_TO_FSB(mp, remap_len),
1582 			XFS_MAX_FILEOFF);
1583 
1584 	trace_xfs_reflink_remap_blocks(src, srcoff, len, dest, destoff);
1585 
1586 	while (len > 0) {
1587 		unsigned int	lock_mode;
1588 
1589 		/* Read extent from the source file */
1590 		nimaps = 1;
1591 		lock_mode = xfs_ilock_data_map_shared(src);
1592 		error = xfs_bmapi_read(src, srcoff, len, &imap, &nimaps, 0);
1593 		xfs_iunlock(src, lock_mode);
1594 		if (error)
1595 			break;
1596 		/*
1597 		 * The caller supposedly flushed all dirty pages in the source
1598 		 * file range, which means that writeback should have allocated
1599 		 * or deleted all delalloc reservations in that range.  If we
1600 		 * find one, that's a good sign that something is seriously
1601 		 * wrong here.
1602 		 */
1603 		ASSERT(nimaps == 1 && imap.br_startoff == srcoff);
1604 		if (imap.br_startblock == DELAYSTARTBLOCK) {
1605 			ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1606 			xfs_bmap_mark_sick(src, XFS_DATA_FORK);
1607 			error = -EFSCORRUPTED;
1608 			break;
1609 		}
1610 
1611 		trace_xfs_reflink_remap_extent_src(src, &imap);
1612 
1613 		/* Remap into the destination file at the given offset. */
1614 		imap.br_startoff = destoff;
1615 		error = xfs_reflink_remap_extent(dest, &imap, new_isize);
1616 		if (error)
1617 			break;
1618 
1619 		if (fatal_signal_pending(current)) {
1620 			error = -EINTR;
1621 			break;
1622 		}
1623 
1624 		/* Advance drange/srange */
1625 		srcoff += imap.br_blockcount;
1626 		destoff += imap.br_blockcount;
1627 		len -= imap.br_blockcount;
1628 		remapped_len += imap.br_blockcount;
1629 		cond_resched();
1630 	}
1631 
1632 	if (error)
1633 		trace_xfs_reflink_remap_blocks_error(dest, error, _RET_IP_);
1634 	*remapped = min_t(loff_t, remap_len,
1635 			  XFS_FSB_TO_B(src->i_mount, remapped_len));
1636 	return error;
1637 }
1638 
1639 /*
1640  * If we're reflinking to a point past the destination file's EOF, we must
1641  * zero any speculative post-EOF preallocations that sit between the old EOF
1642  * and the destination file offset.
1643  */
1644 static int
xfs_reflink_zero_posteof(struct xfs_inode * ip,loff_t pos)1645 xfs_reflink_zero_posteof(
1646 	struct xfs_inode	*ip,
1647 	loff_t			pos)
1648 {
1649 	loff_t			isize = i_size_read(VFS_I(ip));
1650 
1651 	if (pos <= isize)
1652 		return 0;
1653 
1654 	trace_xfs_zero_eof(ip, isize, pos - isize);
1655 	return xfs_zero_range(ip, isize, pos - isize, NULL, NULL);
1656 }
1657 
1658 /*
1659  * Prepare two files for range cloning.  Upon a successful return both inodes
1660  * will have the iolock and mmaplock held, the page cache of the out file will
1661  * be truncated, and any leases on the out file will have been broken.  This
1662  * function borrows heavily from xfs_file_aio_write_checks.
1663  *
1664  * The VFS allows partial EOF blocks to "match" for dedupe even though it hasn't
1665  * checked that the bytes beyond EOF physically match. Hence we cannot use the
1666  * EOF block in the source dedupe range because it's not a complete block match,
1667  * hence can introduce a corruption into the file that has it's block replaced.
1668  *
1669  * In similar fashion, the VFS file cloning also allows partial EOF blocks to be
1670  * "block aligned" for the purposes of cloning entire files.  However, if the
1671  * source file range includes the EOF block and it lands within the existing EOF
1672  * of the destination file, then we can expose stale data from beyond the source
1673  * file EOF in the destination file.
1674  *
1675  * XFS doesn't support partial block sharing, so in both cases we have check
1676  * these cases ourselves. For dedupe, we can simply round the length to dedupe
1677  * down to the previous whole block and ignore the partial EOF block. While this
1678  * means we can't dedupe the last block of a file, this is an acceptible
1679  * tradeoff for simplicity on implementation.
1680  *
1681  * For cloning, we want to share the partial EOF block if it is also the new EOF
1682  * block of the destination file. If the partial EOF block lies inside the
1683  * existing destination EOF, then we have to abort the clone to avoid exposing
1684  * stale data in the destination file. Hence we reject these clone attempts with
1685  * -EINVAL in this case.
1686  */
1687 int
xfs_reflink_remap_prep(struct file * file_in,loff_t pos_in,struct file * file_out,loff_t pos_out,loff_t * len,unsigned int remap_flags)1688 xfs_reflink_remap_prep(
1689 	struct file		*file_in,
1690 	loff_t			pos_in,
1691 	struct file		*file_out,
1692 	loff_t			pos_out,
1693 	loff_t			*len,
1694 	unsigned int		remap_flags)
1695 {
1696 	struct inode		*inode_in = file_inode(file_in);
1697 	struct xfs_inode	*src = XFS_I(inode_in);
1698 	struct inode		*inode_out = file_inode(file_out);
1699 	struct xfs_inode	*dest = XFS_I(inode_out);
1700 	int			ret;
1701 
1702 	/* Lock both files against IO */
1703 	ret = xfs_ilock2_io_mmap(src, dest);
1704 	if (ret)
1705 		return ret;
1706 
1707 	/* Check file eligibility and prepare for block sharing. */
1708 	ret = -EINVAL;
1709 	/* Can't reflink between data and rt volumes */
1710 	if (XFS_IS_REALTIME_INODE(src) != XFS_IS_REALTIME_INODE(dest))
1711 		goto out_unlock;
1712 
1713 	/* Don't share DAX file data with non-DAX file. */
1714 	if (IS_DAX(inode_in) != IS_DAX(inode_out))
1715 		goto out_unlock;
1716 
1717 	if (!IS_DAX(inode_in))
1718 		ret = generic_remap_file_range_prep(file_in, pos_in, file_out,
1719 				pos_out, len, remap_flags);
1720 	else
1721 		ret = dax_remap_file_range_prep(file_in, pos_in, file_out,
1722 				pos_out, len, remap_flags, &xfs_read_iomap_ops);
1723 	if (ret || *len == 0)
1724 		goto out_unlock;
1725 
1726 	/* Attach dquots to dest inode before changing block map */
1727 	ret = xfs_qm_dqattach(dest);
1728 	if (ret)
1729 		goto out_unlock;
1730 
1731 	/*
1732 	 * Zero existing post-eof speculative preallocations in the destination
1733 	 * file.
1734 	 */
1735 	ret = xfs_reflink_zero_posteof(dest, pos_out);
1736 	if (ret)
1737 		goto out_unlock;
1738 
1739 	/* Set flags and remap blocks. */
1740 	ret = xfs_reflink_set_inode_flag(src, dest);
1741 	if (ret)
1742 		goto out_unlock;
1743 
1744 	/*
1745 	 * If pos_out > EOF, we may have dirtied blocks between EOF and
1746 	 * pos_out. In that case, we need to extend the flush and unmap to cover
1747 	 * from EOF to the end of the copy length.
1748 	 */
1749 	if (pos_out > XFS_ISIZE(dest)) {
1750 		loff_t	flen = *len + (pos_out - XFS_ISIZE(dest));
1751 		ret = xfs_flush_unmap_range(dest, XFS_ISIZE(dest), flen);
1752 	} else {
1753 		ret = xfs_flush_unmap_range(dest, pos_out, *len);
1754 	}
1755 	if (ret)
1756 		goto out_unlock;
1757 
1758 	xfs_iflags_set(src, XFS_IREMAPPING);
1759 	if (inode_in != inode_out)
1760 		xfs_ilock_demote(src, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL);
1761 
1762 	return 0;
1763 out_unlock:
1764 	xfs_iunlock2_io_mmap(src, dest);
1765 	return ret;
1766 }
1767 
1768 /* Does this inode need the reflink flag? */
1769 int
xfs_reflink_inode_has_shared_extents(struct xfs_trans * tp,struct xfs_inode * ip,bool * has_shared)1770 xfs_reflink_inode_has_shared_extents(
1771 	struct xfs_trans		*tp,
1772 	struct xfs_inode		*ip,
1773 	bool				*has_shared)
1774 {
1775 	struct xfs_bmbt_irec		got;
1776 	struct xfs_mount		*mp = ip->i_mount;
1777 	struct xfs_ifork		*ifp;
1778 	struct xfs_iext_cursor		icur;
1779 	bool				found;
1780 	int				error;
1781 
1782 	ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);
1783 	error = xfs_iread_extents(tp, ip, XFS_DATA_FORK);
1784 	if (error)
1785 		return error;
1786 
1787 	*has_shared = false;
1788 	found = xfs_iext_lookup_extent(ip, ifp, 0, &icur, &got);
1789 	while (found) {
1790 		xfs_extlen_t		shared_offset, shared_len;
1791 
1792 		if (isnullstartblock(got.br_startblock) ||
1793 		    got.br_state != XFS_EXT_NORM)
1794 			goto next;
1795 
1796 		if (XFS_IS_REALTIME_INODE(ip))
1797 			error = xfs_reflink_find_rtshared(mp, tp, &got,
1798 					&shared_offset, &shared_len, false);
1799 		else
1800 			error = xfs_reflink_find_shared(mp, tp, &got,
1801 					&shared_offset, &shared_len, false);
1802 		if (error)
1803 			return error;
1804 
1805 		/* Is there still a shared block here? */
1806 		if (shared_len) {
1807 			*has_shared = true;
1808 			return 0;
1809 		}
1810 next:
1811 		found = xfs_iext_next_extent(ifp, &icur, &got);
1812 	}
1813 
1814 	return 0;
1815 }
1816 
1817 /*
1818  * Clear the inode reflink flag if there are no shared extents.
1819  *
1820  * The caller is responsible for joining the inode to the transaction passed in.
1821  * The inode will be joined to the transaction that is returned to the caller.
1822  */
1823 int
xfs_reflink_clear_inode_flag(struct xfs_inode * ip,struct xfs_trans ** tpp)1824 xfs_reflink_clear_inode_flag(
1825 	struct xfs_inode	*ip,
1826 	struct xfs_trans	**tpp)
1827 {
1828 	bool			needs_flag;
1829 	int			error = 0;
1830 
1831 	ASSERT(xfs_is_reflink_inode(ip));
1832 
1833 	if (!xfs_can_free_cowblocks(ip))
1834 		return 0;
1835 
1836 	error = xfs_reflink_inode_has_shared_extents(*tpp, ip, &needs_flag);
1837 	if (error || needs_flag)
1838 		return error;
1839 
1840 	/*
1841 	 * We didn't find any shared blocks so turn off the reflink flag.
1842 	 * First, get rid of any leftover CoW mappings.
1843 	 */
1844 	error = xfs_reflink_cancel_cow_blocks(ip, tpp, 0, XFS_MAX_FILEOFF,
1845 			true);
1846 	if (error)
1847 		return error;
1848 
1849 	/* Clear the inode flag. */
1850 	trace_xfs_reflink_unset_inode_flag(ip);
1851 	ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1852 	xfs_inode_clear_cowblocks_tag(ip);
1853 	xfs_trans_log_inode(*tpp, ip, XFS_ILOG_CORE);
1854 
1855 	return error;
1856 }
1857 
1858 /*
1859  * Clear the inode reflink flag if there are no shared extents and the size
1860  * hasn't changed.
1861  */
1862 STATIC int
xfs_reflink_try_clear_inode_flag(struct xfs_inode * ip)1863 xfs_reflink_try_clear_inode_flag(
1864 	struct xfs_inode	*ip)
1865 {
1866 	struct xfs_mount	*mp = ip->i_mount;
1867 	struct xfs_trans	*tp;
1868 	int			error = 0;
1869 
1870 	/* Start a rolling transaction to remove the mappings */
1871 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0, 0, &tp);
1872 	if (error)
1873 		return error;
1874 
1875 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1876 	xfs_trans_ijoin(tp, ip, 0);
1877 
1878 	error = xfs_reflink_clear_inode_flag(ip, &tp);
1879 	if (error)
1880 		goto cancel;
1881 
1882 	error = xfs_trans_commit(tp);
1883 	if (error)
1884 		goto out;
1885 
1886 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1887 	return 0;
1888 cancel:
1889 	xfs_trans_cancel(tp);
1890 out:
1891 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1892 	return error;
1893 }
1894 
1895 /*
1896  * Pre-COW all shared blocks within a given byte range of a file and turn off
1897  * the reflink flag if we unshare all of the file's blocks.
1898  */
1899 int
xfs_reflink_unshare(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t len)1900 xfs_reflink_unshare(
1901 	struct xfs_inode	*ip,
1902 	xfs_off_t		offset,
1903 	xfs_off_t		len)
1904 {
1905 	struct inode		*inode = VFS_I(ip);
1906 	int			error;
1907 
1908 	if (!xfs_is_reflink_inode(ip))
1909 		return 0;
1910 
1911 	trace_xfs_reflink_unshare(ip, offset, len);
1912 
1913 	inode_dio_wait(inode);
1914 
1915 	if (IS_DAX(inode))
1916 		error = dax_file_unshare(inode, offset, len,
1917 				&xfs_dax_write_iomap_ops);
1918 	else
1919 		error = iomap_file_unshare(inode, offset, len,
1920 				&xfs_buffered_write_iomap_ops,
1921 				&xfs_iomap_write_ops);
1922 	if (error)
1923 		goto out;
1924 
1925 	error = filemap_write_and_wait_range(inode->i_mapping, offset,
1926 			offset + len - 1);
1927 	if (error)
1928 		goto out;
1929 
1930 	/* Turn off the reflink flag if possible. */
1931 	error = xfs_reflink_try_clear_inode_flag(ip);
1932 	if (error)
1933 		goto out;
1934 	return 0;
1935 
1936 out:
1937 	trace_xfs_reflink_unshare_error(ip, error, _RET_IP_);
1938 	return error;
1939 }
1940 
1941 /*
1942  * Can we use reflink with this realtime extent size?  Note that we don't check
1943  * for rblocks > 0 here because this can be called as part of attaching a new
1944  * rt section.
1945  */
1946 bool
xfs_reflink_supports_rextsize(struct xfs_mount * mp,unsigned int rextsize)1947 xfs_reflink_supports_rextsize(
1948 	struct xfs_mount	*mp,
1949 	unsigned int		rextsize)
1950 {
1951 	/* reflink on the realtime device requires rtgroups */
1952 	if (!xfs_has_rtgroups(mp))
1953 	       return false;
1954 
1955 	/*
1956 	 * Reflink doesn't support rt extent size larger than a single fsblock
1957 	 * because we would have to perform CoW-around for unaligned write
1958 	 * requests to guarantee that we always remap entire rt extents.
1959 	 */
1960 	if (rextsize != 1)
1961 		return false;
1962 
1963 	return true;
1964 }
1965