xref: /linux/fs/xfs/xfs_reflink.c (revision ab93e0dd72c37d378dd936f031ffb83ff2bd87ce)
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.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		dblocks = 0, rblocks = 0;
444 	int			nimaps;
445 	int			error;
446 	bool			found;
447 
448 	resaligned = xfs_aligned_fsb_count(imap->br_startoff,
449 		imap->br_blockcount, xfs_get_cowextsz_hint(ip));
450 	if (XFS_IS_REALTIME_INODE(ip)) {
451 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
452 		rblocks = resaligned;
453 	} else {
454 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, resaligned);
455 		rblocks = 0;
456 	}
457 
458 	xfs_iunlock(ip, *lockmode);
459 	*lockmode = 0;
460 
461 	error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, dblocks,
462 			rblocks, false, &tp);
463 	if (error)
464 		return error;
465 
466 	*lockmode = XFS_ILOCK_EXCL;
467 
468 	error = xfs_find_trim_cow_extent(ip, imap, cmap, shared, &found);
469 	if (error || !*shared)
470 		goto out_trans_cancel;
471 
472 	if (found) {
473 		xfs_trans_cancel(tp);
474 		goto convert;
475 	}
476 
477 	/* Allocate the entire reservation as unwritten blocks. */
478 	nimaps = 1;
479 	error = xfs_bmapi_write(tp, ip, imap->br_startoff, imap->br_blockcount,
480 			XFS_BMAPI_COWFORK | XFS_BMAPI_PREALLOC, 0, cmap,
481 			&nimaps);
482 	if (error)
483 		goto out_trans_cancel;
484 
485 	xfs_inode_set_cowblocks_tag(ip);
486 	error = xfs_trans_commit(tp);
487 	if (error)
488 		return error;
489 
490 convert:
491 	return xfs_reflink_convert_unwritten(ip, imap, cmap, convert_now);
492 
493 out_trans_cancel:
494 	xfs_trans_cancel(tp);
495 	return error;
496 }
497 
498 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)499 xfs_reflink_fill_delalloc(
500 	struct xfs_inode	*ip,
501 	struct xfs_bmbt_irec	*imap,
502 	struct xfs_bmbt_irec	*cmap,
503 	bool			*shared,
504 	uint			*lockmode,
505 	bool			convert_now)
506 {
507 	struct xfs_mount	*mp = ip->i_mount;
508 	struct xfs_trans	*tp;
509 	int			nimaps;
510 	int			error;
511 	bool			found;
512 
513 	do {
514 		xfs_iunlock(ip, *lockmode);
515 		*lockmode = 0;
516 
517 		error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, 0, 0,
518 				false, &tp);
519 		if (error)
520 			return error;
521 
522 		*lockmode = XFS_ILOCK_EXCL;
523 
524 		error = xfs_find_trim_cow_extent(ip, imap, cmap, shared,
525 				&found);
526 		if (error || !*shared)
527 			goto out_trans_cancel;
528 
529 		if (found) {
530 			xfs_trans_cancel(tp);
531 			break;
532 		}
533 
534 		ASSERT(isnullstartblock(cmap->br_startblock) ||
535 		       cmap->br_startblock == DELAYSTARTBLOCK);
536 
537 		/*
538 		 * Replace delalloc reservation with an unwritten extent.
539 		 */
540 		nimaps = 1;
541 		error = xfs_bmapi_write(tp, ip, cmap->br_startoff,
542 				cmap->br_blockcount,
543 				XFS_BMAPI_COWFORK | XFS_BMAPI_PREALLOC, 0,
544 				cmap, &nimaps);
545 		if (error)
546 			goto out_trans_cancel;
547 
548 		xfs_inode_set_cowblocks_tag(ip);
549 		error = xfs_trans_commit(tp);
550 		if (error)
551 			return error;
552 	} while (cmap->br_startoff + cmap->br_blockcount <= imap->br_startoff);
553 
554 	return xfs_reflink_convert_unwritten(ip, imap, cmap, convert_now);
555 
556 out_trans_cancel:
557 	xfs_trans_cancel(tp);
558 	return error;
559 }
560 
561 /* Allocate all CoW reservations covering a range of blocks in a file. */
562 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)563 xfs_reflink_allocate_cow(
564 	struct xfs_inode	*ip,
565 	struct xfs_bmbt_irec	*imap,
566 	struct xfs_bmbt_irec	*cmap,
567 	bool			*shared,
568 	uint			*lockmode,
569 	bool			convert_now)
570 {
571 	int			error;
572 	bool			found;
573 
574 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
575 	if (!ip->i_cowfp) {
576 		ASSERT(!xfs_is_reflink_inode(ip));
577 		xfs_ifork_init_cow(ip);
578 	}
579 
580 	error = xfs_find_trim_cow_extent(ip, imap, cmap, shared, &found);
581 	if (error || !*shared)
582 		return error;
583 
584 	/* CoW fork has a real extent */
585 	if (found)
586 		return xfs_reflink_convert_unwritten(ip, imap, cmap,
587 				convert_now);
588 
589 	/*
590 	 * CoW fork does not have an extent and data extent is shared.
591 	 * Allocate a real extent in the CoW fork.
592 	 */
593 	if (cmap->br_startoff > imap->br_startoff)
594 		return xfs_reflink_fill_cow_hole(ip, imap, cmap, shared,
595 				lockmode, convert_now);
596 
597 	/*
598 	 * CoW fork has a delalloc reservation. Replace it with a real extent.
599 	 * There may or may not be a data fork mapping.
600 	 */
601 	if (isnullstartblock(cmap->br_startblock) ||
602 	    cmap->br_startblock == DELAYSTARTBLOCK)
603 		return xfs_reflink_fill_delalloc(ip, imap, cmap, shared,
604 				lockmode, convert_now);
605 
606 	/* Shouldn't get here. */
607 	ASSERT(0);
608 	return -EFSCORRUPTED;
609 }
610 
611 /*
612  * Cancel CoW reservations for some block range of an inode.
613  *
614  * If cancel_real is true this function cancels all COW fork extents for the
615  * inode; if cancel_real is false, real extents are not cleared.
616  *
617  * Caller must have already joined the inode to the current transaction. The
618  * inode will be joined to the transaction returned to the caller.
619  */
620 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)621 xfs_reflink_cancel_cow_blocks(
622 	struct xfs_inode		*ip,
623 	struct xfs_trans		**tpp,
624 	xfs_fileoff_t			offset_fsb,
625 	xfs_fileoff_t			end_fsb,
626 	bool				cancel_real)
627 {
628 	struct xfs_ifork		*ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
629 	struct xfs_bmbt_irec		got, del;
630 	struct xfs_iext_cursor		icur;
631 	bool				isrt = XFS_IS_REALTIME_INODE(ip);
632 	int				error = 0;
633 
634 	if (!xfs_inode_has_cow_data(ip))
635 		return 0;
636 	if (!xfs_iext_lookup_extent_before(ip, ifp, &end_fsb, &icur, &got))
637 		return 0;
638 
639 	/* Walk backwards until we're out of the I/O range... */
640 	while (got.br_startoff + got.br_blockcount > offset_fsb) {
641 		del = got;
642 		xfs_trim_extent(&del, offset_fsb, end_fsb - offset_fsb);
643 
644 		/* Extent delete may have bumped ext forward */
645 		if (!del.br_blockcount) {
646 			xfs_iext_prev(ifp, &icur);
647 			goto next_extent;
648 		}
649 
650 		trace_xfs_reflink_cancel_cow(ip, &del);
651 
652 		if (isnullstartblock(del.br_startblock)) {
653 			xfs_bmap_del_extent_delay(ip, XFS_COW_FORK, &icur, &got,
654 					&del, 0);
655 		} else if (del.br_state == XFS_EXT_UNWRITTEN || cancel_real) {
656 			ASSERT((*tpp)->t_highest_agno == NULLAGNUMBER);
657 
658 			/* Free the CoW orphan record. */
659 			xfs_refcount_free_cow_extent(*tpp, isrt,
660 					del.br_startblock, del.br_blockcount);
661 
662 			error = xfs_free_extent_later(*tpp, del.br_startblock,
663 					del.br_blockcount, NULL,
664 					XFS_AG_RESV_NONE,
665 					isrt ? XFS_FREE_EXTENT_REALTIME : 0);
666 			if (error)
667 				break;
668 
669 			/* Roll the transaction */
670 			error = xfs_defer_finish(tpp);
671 			if (error)
672 				break;
673 
674 			/* Remove the mapping from the CoW fork. */
675 			xfs_bmap_del_extent_cow(ip, &icur, &got, &del);
676 
677 			/* Remove the quota reservation */
678 			xfs_quota_unreserve_blkres(ip, del.br_blockcount);
679 		} else {
680 			/* Didn't do anything, push cursor back. */
681 			xfs_iext_prev(ifp, &icur);
682 		}
683 next_extent:
684 		if (!xfs_iext_get_extent(ifp, &icur, &got))
685 			break;
686 	}
687 
688 	/* clear tag if cow fork is emptied */
689 	if (!ifp->if_bytes)
690 		xfs_inode_clear_cowblocks_tag(ip);
691 	return error;
692 }
693 
694 /*
695  * Cancel CoW reservations for some byte range of an inode.
696  *
697  * If cancel_real is true this function cancels all COW fork extents for the
698  * inode; if cancel_real is false, real extents are not cleared.
699  */
700 int
xfs_reflink_cancel_cow_range(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t count,bool cancel_real)701 xfs_reflink_cancel_cow_range(
702 	struct xfs_inode	*ip,
703 	xfs_off_t		offset,
704 	xfs_off_t		count,
705 	bool			cancel_real)
706 {
707 	struct xfs_trans	*tp;
708 	xfs_fileoff_t		offset_fsb;
709 	xfs_fileoff_t		end_fsb;
710 	int			error;
711 
712 	trace_xfs_reflink_cancel_cow_range(ip, offset, count);
713 	ASSERT(ip->i_cowfp);
714 
715 	offset_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
716 	if (count == NULLFILEOFF)
717 		end_fsb = NULLFILEOFF;
718 	else
719 		end_fsb = XFS_B_TO_FSB(ip->i_mount, offset + count);
720 
721 	/* Start a rolling transaction to remove the mappings */
722 	error = xfs_trans_alloc(ip->i_mount, &M_RES(ip->i_mount)->tr_write,
723 			0, 0, 0, &tp);
724 	if (error)
725 		goto out;
726 
727 	xfs_ilock(ip, XFS_ILOCK_EXCL);
728 	xfs_trans_ijoin(tp, ip, 0);
729 
730 	/* Scrape out the old CoW reservations */
731 	error = xfs_reflink_cancel_cow_blocks(ip, &tp, offset_fsb, end_fsb,
732 			cancel_real);
733 	if (error)
734 		goto out_cancel;
735 
736 	error = xfs_trans_commit(tp);
737 
738 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
739 	return error;
740 
741 out_cancel:
742 	xfs_trans_cancel(tp);
743 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
744 out:
745 	trace_xfs_reflink_cancel_cow_range_error(ip, error, _RET_IP_);
746 	return error;
747 }
748 
749 #ifdef CONFIG_XFS_QUOTA
750 /*
751  * Update quota accounting for a remapping operation.  When we're remapping
752  * something from the CoW fork to the data fork, we must update the quota
753  * accounting for delayed allocations.  For remapping from the data fork to the
754  * data fork, use regular block accounting.
755  */
756 static inline void
xfs_reflink_update_quota(struct xfs_trans * tp,struct xfs_inode * ip,bool is_cow,int64_t blocks)757 xfs_reflink_update_quota(
758 	struct xfs_trans	*tp,
759 	struct xfs_inode	*ip,
760 	bool			is_cow,
761 	int64_t			blocks)
762 {
763 	unsigned int		qflag;
764 
765 	if (XFS_IS_REALTIME_INODE(ip)) {
766 		qflag = is_cow ? XFS_TRANS_DQ_DELRTBCOUNT :
767 				 XFS_TRANS_DQ_RTBCOUNT;
768 	} else {
769 		qflag = is_cow ? XFS_TRANS_DQ_DELBCOUNT :
770 				 XFS_TRANS_DQ_BCOUNT;
771 	}
772 	xfs_trans_mod_dquot_byino(tp, ip, qflag, blocks);
773 }
774 #else
775 # define xfs_reflink_update_quota(tp, ip, is_cow, blocks)	((void)0)
776 #endif
777 
778 /*
779  * Remap part of the CoW fork into the data fork.
780  *
781  * We aim to remap the range starting at @offset_fsb and ending at @end_fsb
782  * into the data fork; this function will remap what it can (at the end of the
783  * range) and update @end_fsb appropriately.  Each remap gets its own
784  * transaction because we can end up merging and splitting bmbt blocks for
785  * every remap operation and we'd like to keep the block reservation
786  * requirements as low as possible.
787  */
788 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)789 xfs_reflink_end_cow_extent_locked(
790 	struct xfs_trans	*tp,
791 	struct xfs_inode	*ip,
792 	xfs_fileoff_t		*offset_fsb,
793 	xfs_fileoff_t		end_fsb)
794 {
795 	struct xfs_iext_cursor	icur;
796 	struct xfs_bmbt_irec	got, del, data;
797 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
798 	int			nmaps;
799 	bool			isrt = XFS_IS_REALTIME_INODE(ip);
800 	int			error;
801 
802 	/*
803 	 * In case of racing, overlapping AIO writes no COW extents might be
804 	 * left by the time I/O completes for the loser of the race.  In that
805 	 * case we are done.
806 	 */
807 	if (!xfs_iext_lookup_extent(ip, ifp, *offset_fsb, &icur, &got) ||
808 	    got.br_startoff >= end_fsb) {
809 		*offset_fsb = end_fsb;
810 		return 0;
811 	}
812 
813 	/*
814 	 * Only remap real extents that contain data.  With AIO, speculative
815 	 * preallocations can leak into the range we are called upon, and we
816 	 * need to skip them.  Preserve @got for the eventual CoW fork
817 	 * deletion; from now on @del represents the mapping that we're
818 	 * actually remapping.
819 	 */
820 	while (!xfs_bmap_is_written_extent(&got)) {
821 		if (!xfs_iext_next_extent(ifp, &icur, &got) ||
822 		    got.br_startoff >= end_fsb) {
823 			*offset_fsb = end_fsb;
824 			return 0;
825 		}
826 	}
827 	del = got;
828 	xfs_trim_extent(&del, *offset_fsb, end_fsb - *offset_fsb);
829 
830 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
831 			XFS_IEXT_REFLINK_END_COW_CNT);
832 	if (error)
833 		return error;
834 
835 	/* Grab the corresponding mapping in the data fork. */
836 	nmaps = 1;
837 	error = xfs_bmapi_read(ip, del.br_startoff, del.br_blockcount, &data,
838 			&nmaps, 0);
839 	if (error)
840 		return error;
841 
842 	/* We can only remap the smaller of the two extent sizes. */
843 	data.br_blockcount = min(data.br_blockcount, del.br_blockcount);
844 	del.br_blockcount = data.br_blockcount;
845 
846 	trace_xfs_reflink_cow_remap_from(ip, &del);
847 	trace_xfs_reflink_cow_remap_to(ip, &data);
848 
849 	if (xfs_bmap_is_real_extent(&data)) {
850 		/*
851 		 * If the extent we're remapping is backed by storage (written
852 		 * or not), unmap the extent and drop its refcount.
853 		 */
854 		xfs_bmap_unmap_extent(tp, ip, XFS_DATA_FORK, &data);
855 		xfs_refcount_decrease_extent(tp, isrt, &data);
856 		xfs_reflink_update_quota(tp, ip, false, -data.br_blockcount);
857 	} else if (data.br_startblock == DELAYSTARTBLOCK) {
858 		int		done;
859 
860 		/*
861 		 * If the extent we're remapping is a delalloc reservation,
862 		 * we can use the regular bunmapi function to release the
863 		 * incore state.  Dropping the delalloc reservation takes care
864 		 * of the quota reservation for us.
865 		 */
866 		error = xfs_bunmapi(NULL, ip, data.br_startoff,
867 				data.br_blockcount, 0, 1, &done);
868 		if (error)
869 			return error;
870 		ASSERT(done);
871 	}
872 
873 	/* Free the CoW orphan record. */
874 	xfs_refcount_free_cow_extent(tp, isrt, del.br_startblock,
875 			del.br_blockcount);
876 
877 	/* Map the new blocks into the data fork. */
878 	xfs_bmap_map_extent(tp, ip, XFS_DATA_FORK, &del);
879 
880 	/* Charge this new data fork mapping to the on-disk quota. */
881 	xfs_reflink_update_quota(tp, ip, true, del.br_blockcount);
882 
883 	/* Remove the mapping from the CoW fork. */
884 	xfs_bmap_del_extent_cow(ip, &icur, &got, &del);
885 
886 	/* Update the caller about how much progress we made. */
887 	*offset_fsb = del.br_startoff + del.br_blockcount;
888 	return 0;
889 }
890 
891 /*
892  * Remap part of the CoW fork into the data fork.
893  *
894  * We aim to remap the range starting at @offset_fsb and ending at @end_fsb
895  * into the data fork; this function will remap what it can (at the end of the
896  * range) and update @end_fsb appropriately.  Each remap gets its own
897  * transaction because we can end up merging and splitting bmbt blocks for
898  * every remap operation and we'd like to keep the block reservation
899  * requirements as low as possible.
900  */
901 STATIC int
xfs_reflink_end_cow_extent(struct xfs_inode * ip,xfs_fileoff_t * offset_fsb,xfs_fileoff_t end_fsb)902 xfs_reflink_end_cow_extent(
903 	struct xfs_inode	*ip,
904 	xfs_fileoff_t		*offset_fsb,
905 	xfs_fileoff_t		end_fsb)
906 {
907 	struct xfs_mount	*mp = ip->i_mount;
908 	struct xfs_trans	*tp;
909 	unsigned int		resblks;
910 	int			error;
911 
912 	resblks = XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK);
913 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0,
914 			XFS_TRANS_RESERVE, &tp);
915 	if (error)
916 		return error;
917 	xfs_ilock(ip, XFS_ILOCK_EXCL);
918 	xfs_trans_ijoin(tp, ip, 0);
919 
920 	error = xfs_reflink_end_cow_extent_locked(tp, ip, offset_fsb, end_fsb);
921 	if (error)
922 		xfs_trans_cancel(tp);
923 	else
924 		error = xfs_trans_commit(tp);
925 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
926 	return error;
927 }
928 
929 /*
930  * Remap parts of a file's data fork after a successful CoW.
931  */
932 int
xfs_reflink_end_cow(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t count)933 xfs_reflink_end_cow(
934 	struct xfs_inode		*ip,
935 	xfs_off_t			offset,
936 	xfs_off_t			count)
937 {
938 	xfs_fileoff_t			offset_fsb;
939 	xfs_fileoff_t			end_fsb;
940 	int				error = 0;
941 
942 	trace_xfs_reflink_end_cow(ip, offset, count);
943 
944 	offset_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
945 	end_fsb = XFS_B_TO_FSB(ip->i_mount, offset + count);
946 
947 	/*
948 	 * Walk forwards until we've remapped the I/O range.  The loop function
949 	 * repeatedly cycles the ILOCK to allocate one transaction per remapped
950 	 * extent.
951 	 *
952 	 * If we're being called by writeback then the pages will still
953 	 * have PageWriteback set, which prevents races with reflink remapping
954 	 * and truncate.  Reflink remapping prevents races with writeback by
955 	 * taking the iolock and mmaplock before flushing the pages and
956 	 * remapping, which means there won't be any further writeback or page
957 	 * cache dirtying until the reflink completes.
958 	 *
959 	 * We should never have two threads issuing writeback for the same file
960 	 * region.  There are also have post-eof checks in the writeback
961 	 * preparation code so that we don't bother writing out pages that are
962 	 * about to be truncated.
963 	 *
964 	 * If we're being called as part of directio write completion, the dio
965 	 * count is still elevated, which reflink and truncate will wait for.
966 	 * Reflink remapping takes the iolock and mmaplock and waits for
967 	 * pending dio to finish, which should prevent any directio until the
968 	 * remap completes.  Multiple concurrent directio writes to the same
969 	 * region are handled by end_cow processing only occurring for the
970 	 * threads which succeed; the outcome of multiple overlapping direct
971 	 * writes is not well defined anyway.
972 	 *
973 	 * It's possible that a buffered write and a direct write could collide
974 	 * here (the buffered write stumbles in after the dio flushes and
975 	 * invalidates the page cache and immediately queues writeback), but we
976 	 * have never supported this 100%.  If either disk write succeeds the
977 	 * blocks will be remapped.
978 	 */
979 	while (end_fsb > offset_fsb && !error)
980 		error = xfs_reflink_end_cow_extent(ip, &offset_fsb, end_fsb);
981 
982 	if (error)
983 		trace_xfs_reflink_end_cow_error(ip, error, _RET_IP_);
984 	return error;
985 }
986 
987 /*
988  * Fully remap all of the file's data fork at once, which is the critical part
989  * in achieving atomic behaviour.
990  * The regular CoW end path does not use function as to keep the block
991  * reservation per transaction as low as possible.
992  */
993 int
xfs_reflink_end_atomic_cow(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t count)994 xfs_reflink_end_atomic_cow(
995 	struct xfs_inode		*ip,
996 	xfs_off_t			offset,
997 	xfs_off_t			count)
998 {
999 	xfs_fileoff_t			offset_fsb;
1000 	xfs_fileoff_t			end_fsb;
1001 	int				error = 0;
1002 	struct xfs_mount		*mp = ip->i_mount;
1003 	struct xfs_trans		*tp;
1004 	unsigned int			resblks;
1005 
1006 	trace_xfs_reflink_end_cow(ip, offset, count);
1007 
1008 	offset_fsb = XFS_B_TO_FSBT(mp, offset);
1009 	end_fsb = XFS_B_TO_FSB(mp, offset + count);
1010 
1011 	/*
1012 	 * Each remapping operation could cause a btree split, so in the worst
1013 	 * case that's one for each block.
1014 	 */
1015 	resblks = (end_fsb - offset_fsb) *
1016 			XFS_NEXTENTADD_SPACE_RES(mp, 1, XFS_DATA_FORK);
1017 
1018 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_atomic_ioend, resblks, 0,
1019 			XFS_TRANS_RESERVE, &tp);
1020 	if (error)
1021 		return error;
1022 
1023 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1024 	xfs_trans_ijoin(tp, ip, 0);
1025 
1026 	while (end_fsb > offset_fsb && !error) {
1027 		error = xfs_reflink_end_cow_extent_locked(tp, ip, &offset_fsb,
1028 				end_fsb);
1029 	}
1030 	if (error) {
1031 		trace_xfs_reflink_end_cow_error(ip, error, _RET_IP_);
1032 		goto out_cancel;
1033 	}
1034 	error = xfs_trans_commit(tp);
1035 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1036 	return error;
1037 out_cancel:
1038 	xfs_trans_cancel(tp);
1039 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1040 	return error;
1041 }
1042 
1043 /* Compute the largest atomic write that we can complete through software. */
1044 xfs_extlen_t
xfs_reflink_max_atomic_cow(struct xfs_mount * mp)1045 xfs_reflink_max_atomic_cow(
1046 	struct xfs_mount	*mp)
1047 {
1048 	/* We cannot do any atomic writes without out of place writes. */
1049 	if (!xfs_can_sw_atomic_write(mp))
1050 		return 0;
1051 
1052 	/*
1053 	 * Atomic write limits must always be a power-of-2, according to
1054 	 * generic_atomic_write_valid.
1055 	 */
1056 	return rounddown_pow_of_two(xfs_calc_max_atomic_write_fsblocks(mp));
1057 }
1058 
1059 /*
1060  * Free all CoW staging blocks that are still referenced by the ondisk refcount
1061  * metadata.  The ondisk metadata does not track which inode created the
1062  * staging extent, so callers must ensure that there are no cached inodes with
1063  * live CoW staging extents.
1064  */
1065 int
xfs_reflink_recover_cow(struct xfs_mount * mp)1066 xfs_reflink_recover_cow(
1067 	struct xfs_mount	*mp)
1068 {
1069 	struct xfs_perag	*pag = NULL;
1070 	struct xfs_rtgroup	*rtg = NULL;
1071 	int			error = 0;
1072 
1073 	if (!xfs_has_reflink(mp))
1074 		return 0;
1075 
1076 	while ((pag = xfs_perag_next(mp, pag))) {
1077 		error = xfs_refcount_recover_cow_leftovers(pag_group(pag));
1078 		if (error) {
1079 			xfs_perag_rele(pag);
1080 			return error;
1081 		}
1082 	}
1083 
1084 	while ((rtg = xfs_rtgroup_next(mp, rtg))) {
1085 		error = xfs_refcount_recover_cow_leftovers(rtg_group(rtg));
1086 		if (error) {
1087 			xfs_rtgroup_rele(rtg);
1088 			return error;
1089 		}
1090 	}
1091 
1092 	return 0;
1093 }
1094 
1095 /*
1096  * Reflinking (Block) Ranges of Two Files Together
1097  *
1098  * First, ensure that the reflink flag is set on both inodes.  The flag is an
1099  * optimization to avoid unnecessary refcount btree lookups in the write path.
1100  *
1101  * Now we can iteratively remap the range of extents (and holes) in src to the
1102  * corresponding ranges in dest.  Let drange and srange denote the ranges of
1103  * logical blocks in dest and src touched by the reflink operation.
1104  *
1105  * While the length of drange is greater than zero,
1106  *    - Read src's bmbt at the start of srange ("imap")
1107  *    - If imap doesn't exist, make imap appear to start at the end of srange
1108  *      with zero length.
1109  *    - If imap starts before srange, advance imap to start at srange.
1110  *    - If imap goes beyond srange, truncate imap to end at the end of srange.
1111  *    - Punch (imap start - srange start + imap len) blocks from dest at
1112  *      offset (drange start).
1113  *    - If imap points to a real range of pblks,
1114  *         > Increase the refcount of the imap's pblks
1115  *         > Map imap's pblks into dest at the offset
1116  *           (drange start + imap start - srange start)
1117  *    - Advance drange and srange by (imap start - srange start + imap len)
1118  *
1119  * Finally, if the reflink made dest longer, update both the in-core and
1120  * on-disk file sizes.
1121  *
1122  * ASCII Art Demonstration:
1123  *
1124  * Let's say we want to reflink this source file:
1125  *
1126  * ----SSSSSSS-SSSSS----SSSSSS (src file)
1127  *   <-------------------->
1128  *
1129  * into this destination file:
1130  *
1131  * --DDDDDDDDDDDDDDDDDDD--DDD (dest file)
1132  *        <-------------------->
1133  * '-' means a hole, and 'S' and 'D' are written blocks in the src and dest.
1134  * Observe that the range has different logical offsets in either file.
1135  *
1136  * Consider that the first extent in the source file doesn't line up with our
1137  * reflink range.  Unmapping  and remapping are separate operations, so we can
1138  * unmap more blocks from the destination file than we remap.
1139  *
1140  * ----SSSSSSS-SSSSS----SSSSSS
1141  *   <------->
1142  * --DDDDD---------DDDDD--DDD
1143  *        <------->
1144  *
1145  * Now remap the source extent into the destination file:
1146  *
1147  * ----SSSSSSS-SSSSS----SSSSSS
1148  *   <------->
1149  * --DDDDD--SSSSSSSDDDDD--DDD
1150  *        <------->
1151  *
1152  * Do likewise with the second hole and extent in our range.  Holes in the
1153  * unmap range don't affect our operation.
1154  *
1155  * ----SSSSSSS-SSSSS----SSSSSS
1156  *            <---->
1157  * --DDDDD--SSSSSSS-SSSSS-DDD
1158  *                 <---->
1159  *
1160  * Finally, unmap and remap part of the third extent.  This will increase the
1161  * size of the destination file.
1162  *
1163  * ----SSSSSSS-SSSSS----SSSSSS
1164  *                  <----->
1165  * --DDDDD--SSSSSSS-SSSSS----SSS
1166  *                       <----->
1167  *
1168  * Once we update the destination file's i_size, we're done.
1169  */
1170 
1171 /*
1172  * Ensure the reflink bit is set in both inodes.
1173  */
1174 STATIC int
xfs_reflink_set_inode_flag(struct xfs_inode * src,struct xfs_inode * dest)1175 xfs_reflink_set_inode_flag(
1176 	struct xfs_inode	*src,
1177 	struct xfs_inode	*dest)
1178 {
1179 	struct xfs_mount	*mp = src->i_mount;
1180 	int			error;
1181 	struct xfs_trans	*tp;
1182 
1183 	if (xfs_is_reflink_inode(src) && xfs_is_reflink_inode(dest))
1184 		return 0;
1185 
1186 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);
1187 	if (error)
1188 		goto out_error;
1189 
1190 	/* Lock both files against IO */
1191 	if (src->i_ino == dest->i_ino)
1192 		xfs_ilock(src, XFS_ILOCK_EXCL);
1193 	else
1194 		xfs_lock_two_inodes(src, XFS_ILOCK_EXCL, dest, XFS_ILOCK_EXCL);
1195 
1196 	if (!xfs_is_reflink_inode(src)) {
1197 		trace_xfs_reflink_set_inode_flag(src);
1198 		xfs_trans_ijoin(tp, src, XFS_ILOCK_EXCL);
1199 		src->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1200 		xfs_trans_log_inode(tp, src, XFS_ILOG_CORE);
1201 		xfs_ifork_init_cow(src);
1202 	} else
1203 		xfs_iunlock(src, XFS_ILOCK_EXCL);
1204 
1205 	if (src->i_ino == dest->i_ino)
1206 		goto commit_flags;
1207 
1208 	if (!xfs_is_reflink_inode(dest)) {
1209 		trace_xfs_reflink_set_inode_flag(dest);
1210 		xfs_trans_ijoin(tp, dest, XFS_ILOCK_EXCL);
1211 		dest->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1212 		xfs_trans_log_inode(tp, dest, XFS_ILOG_CORE);
1213 		xfs_ifork_init_cow(dest);
1214 	} else
1215 		xfs_iunlock(dest, XFS_ILOCK_EXCL);
1216 
1217 commit_flags:
1218 	error = xfs_trans_commit(tp);
1219 	if (error)
1220 		goto out_error;
1221 	return error;
1222 
1223 out_error:
1224 	trace_xfs_reflink_set_inode_flag_error(dest, error, _RET_IP_);
1225 	return error;
1226 }
1227 
1228 /*
1229  * Update destination inode size & cowextsize hint, if necessary.
1230  */
1231 int
xfs_reflink_update_dest(struct xfs_inode * dest,xfs_off_t newlen,xfs_extlen_t cowextsize,unsigned int remap_flags)1232 xfs_reflink_update_dest(
1233 	struct xfs_inode	*dest,
1234 	xfs_off_t		newlen,
1235 	xfs_extlen_t		cowextsize,
1236 	unsigned int		remap_flags)
1237 {
1238 	struct xfs_mount	*mp = dest->i_mount;
1239 	struct xfs_trans	*tp;
1240 	int			error;
1241 
1242 	if (newlen <= i_size_read(VFS_I(dest)) && cowextsize == 0)
1243 		return 0;
1244 
1245 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);
1246 	if (error)
1247 		goto out_error;
1248 
1249 	xfs_ilock(dest, XFS_ILOCK_EXCL);
1250 	xfs_trans_ijoin(tp, dest, XFS_ILOCK_EXCL);
1251 
1252 	if (newlen > i_size_read(VFS_I(dest))) {
1253 		trace_xfs_reflink_update_inode_size(dest, newlen);
1254 		i_size_write(VFS_I(dest), newlen);
1255 		dest->i_disk_size = newlen;
1256 	}
1257 
1258 	if (cowextsize) {
1259 		dest->i_cowextsize = cowextsize;
1260 		dest->i_diflags2 |= XFS_DIFLAG2_COWEXTSIZE;
1261 	}
1262 
1263 	xfs_trans_log_inode(tp, dest, XFS_ILOG_CORE);
1264 
1265 	error = xfs_trans_commit(tp);
1266 	if (error)
1267 		goto out_error;
1268 	return error;
1269 
1270 out_error:
1271 	trace_xfs_reflink_update_inode_size_error(dest, error, _RET_IP_);
1272 	return error;
1273 }
1274 
1275 /*
1276  * Do we have enough reserve in this AG to handle a reflink?  The refcount
1277  * btree already reserved all the space it needs, but the rmap btree can grow
1278  * infinitely, so we won't allow more reflinks when the AG is down to the
1279  * btree reserves.
1280  */
1281 static int
xfs_reflink_ag_has_free_space(struct xfs_mount * mp,struct xfs_inode * ip,xfs_fsblock_t fsb)1282 xfs_reflink_ag_has_free_space(
1283 	struct xfs_mount	*mp,
1284 	struct xfs_inode	*ip,
1285 	xfs_fsblock_t		fsb)
1286 {
1287 	struct xfs_perag	*pag;
1288 	xfs_agnumber_t		agno;
1289 	int			error = 0;
1290 
1291 	if (!xfs_has_rmapbt(mp))
1292 		return 0;
1293 	if (XFS_IS_REALTIME_INODE(ip)) {
1294 		if (xfs_metafile_resv_critical(mp))
1295 			return -ENOSPC;
1296 		return 0;
1297 	}
1298 
1299 	agno = XFS_FSB_TO_AGNO(mp, fsb);
1300 	pag = xfs_perag_get(mp, agno);
1301 	if (xfs_ag_resv_critical(pag, XFS_AG_RESV_RMAPBT) ||
1302 	    xfs_ag_resv_critical(pag, XFS_AG_RESV_METADATA))
1303 		error = -ENOSPC;
1304 	xfs_perag_put(pag);
1305 	return error;
1306 }
1307 
1308 /*
1309  * Remap the given extent into the file.  The dmap blockcount will be set to
1310  * the number of blocks that were actually remapped.
1311  */
1312 STATIC int
xfs_reflink_remap_extent(struct xfs_inode * ip,struct xfs_bmbt_irec * dmap,xfs_off_t new_isize)1313 xfs_reflink_remap_extent(
1314 	struct xfs_inode	*ip,
1315 	struct xfs_bmbt_irec	*dmap,
1316 	xfs_off_t		new_isize)
1317 {
1318 	struct xfs_bmbt_irec	smap;
1319 	struct xfs_mount	*mp = ip->i_mount;
1320 	struct xfs_trans	*tp;
1321 	xfs_off_t		newlen;
1322 	int64_t			qdelta = 0;
1323 	unsigned int		dblocks, rblocks, resblks;
1324 	bool			quota_reserved = true;
1325 	bool			smap_real;
1326 	bool			dmap_written = xfs_bmap_is_written_extent(dmap);
1327 	bool			isrt = XFS_IS_REALTIME_INODE(ip);
1328 	int			iext_delta = 0;
1329 	int			nimaps;
1330 	int			error;
1331 
1332 	/*
1333 	 * Start a rolling transaction to switch the mappings.
1334 	 *
1335 	 * Adding a written extent to the extent map can cause a bmbt split,
1336 	 * and removing a mapped extent from the extent can cause a bmbt split.
1337 	 * The two operations cannot both cause a split since they operate on
1338 	 * the same index in the bmap btree, so we only need a reservation for
1339 	 * one bmbt split if either thing is happening.  However, we haven't
1340 	 * locked the inode yet, so we reserve assuming this is the case.
1341 	 *
1342 	 * The first allocation call tries to reserve enough space to handle
1343 	 * mapping dmap into a sparse part of the file plus the bmbt split.  We
1344 	 * haven't locked the inode or read the existing mapping yet, so we do
1345 	 * not know for sure that we need the space.  This should succeed most
1346 	 * of the time.
1347 	 *
1348 	 * If the first attempt fails, try again but reserving only enough
1349 	 * space to handle a bmbt split.  This is the hard minimum requirement,
1350 	 * and we revisit quota reservations later when we know more about what
1351 	 * we're remapping.
1352 	 */
1353 	resblks = XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK);
1354 	if (XFS_IS_REALTIME_INODE(ip)) {
1355 		dblocks = resblks;
1356 		rblocks = dmap->br_blockcount;
1357 	} else {
1358 		dblocks = resblks + dmap->br_blockcount;
1359 		rblocks = 0;
1360 	}
1361 	error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write,
1362 			dblocks, rblocks, false, &tp);
1363 	if (error == -EDQUOT || error == -ENOSPC) {
1364 		quota_reserved = false;
1365 		error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write,
1366 				resblks, 0, false, &tp);
1367 	}
1368 	if (error)
1369 		goto out;
1370 
1371 	/*
1372 	 * Read what's currently mapped in the destination file into smap.
1373 	 * If smap isn't a hole, we will have to remove it before we can add
1374 	 * dmap to the destination file.
1375 	 */
1376 	nimaps = 1;
1377 	error = xfs_bmapi_read(ip, dmap->br_startoff, dmap->br_blockcount,
1378 			&smap, &nimaps, 0);
1379 	if (error)
1380 		goto out_cancel;
1381 	ASSERT(nimaps == 1 && smap.br_startoff == dmap->br_startoff);
1382 	smap_real = xfs_bmap_is_real_extent(&smap);
1383 
1384 	/*
1385 	 * We can only remap as many blocks as the smaller of the two extent
1386 	 * maps, because we can only remap one extent at a time.
1387 	 */
1388 	dmap->br_blockcount = min(dmap->br_blockcount, smap.br_blockcount);
1389 	ASSERT(dmap->br_blockcount == smap.br_blockcount);
1390 
1391 	trace_xfs_reflink_remap_extent_dest(ip, &smap);
1392 
1393 	/*
1394 	 * Two extents mapped to the same physical block must not have
1395 	 * different states; that's filesystem corruption.  Move on to the next
1396 	 * extent if they're both holes or both the same physical extent.
1397 	 */
1398 	if (dmap->br_startblock == smap.br_startblock) {
1399 		if (dmap->br_state != smap.br_state) {
1400 			xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
1401 			error = -EFSCORRUPTED;
1402 		}
1403 		goto out_cancel;
1404 	}
1405 
1406 	/* If both extents are unwritten, leave them alone. */
1407 	if (dmap->br_state == XFS_EXT_UNWRITTEN &&
1408 	    smap.br_state == XFS_EXT_UNWRITTEN)
1409 		goto out_cancel;
1410 
1411 	/* No reflinking if the AG of the dest mapping is low on space. */
1412 	if (dmap_written) {
1413 		error = xfs_reflink_ag_has_free_space(mp, ip,
1414 				dmap->br_startblock);
1415 		if (error)
1416 			goto out_cancel;
1417 	}
1418 
1419 	/*
1420 	 * Increase quota reservation if we think the quota block counter for
1421 	 * this file could increase.
1422 	 *
1423 	 * If we are mapping a written extent into the file, we need to have
1424 	 * enough quota block count reservation to handle the blocks in that
1425 	 * extent.  We log only the delta to the quota block counts, so if the
1426 	 * extent we're unmapping also has blocks allocated to it, we don't
1427 	 * need a quota reservation for the extent itself.
1428 	 *
1429 	 * Note that if we're replacing a delalloc reservation with a written
1430 	 * extent, we have to take the full quota reservation because removing
1431 	 * the delalloc reservation gives the block count back to the quota
1432 	 * count.  This is suboptimal, but the VFS flushed the dest range
1433 	 * before we started.  That should have removed all the delalloc
1434 	 * reservations, but we code defensively.
1435 	 *
1436 	 * xfs_trans_alloc_inode above already tried to grab an even larger
1437 	 * quota reservation, and kicked off a blockgc scan if it couldn't.
1438 	 * If we can't get a potentially smaller quota reservation now, we're
1439 	 * done.
1440 	 */
1441 	if (!quota_reserved && !smap_real && dmap_written) {
1442 		if (XFS_IS_REALTIME_INODE(ip)) {
1443 			dblocks = 0;
1444 			rblocks = dmap->br_blockcount;
1445 		} else {
1446 			dblocks = dmap->br_blockcount;
1447 			rblocks = 0;
1448 		}
1449 		error = xfs_trans_reserve_quota_nblks(tp, ip, dblocks, rblocks,
1450 				false);
1451 		if (error)
1452 			goto out_cancel;
1453 	}
1454 
1455 	if (smap_real)
1456 		++iext_delta;
1457 
1458 	if (dmap_written)
1459 		++iext_delta;
1460 
1461 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK, iext_delta);
1462 	if (error)
1463 		goto out_cancel;
1464 
1465 	if (smap_real) {
1466 		/*
1467 		 * If the extent we're unmapping is backed by storage (written
1468 		 * or not), unmap the extent and drop its refcount.
1469 		 */
1470 		xfs_bmap_unmap_extent(tp, ip, XFS_DATA_FORK, &smap);
1471 		xfs_refcount_decrease_extent(tp, isrt, &smap);
1472 		qdelta -= smap.br_blockcount;
1473 	} else if (smap.br_startblock == DELAYSTARTBLOCK) {
1474 		int		done;
1475 
1476 		/*
1477 		 * If the extent we're unmapping is a delalloc reservation,
1478 		 * we can use the regular bunmapi function to release the
1479 		 * incore state.  Dropping the delalloc reservation takes care
1480 		 * of the quota reservation for us.
1481 		 */
1482 		error = xfs_bunmapi(NULL, ip, smap.br_startoff,
1483 				smap.br_blockcount, 0, 1, &done);
1484 		if (error)
1485 			goto out_cancel;
1486 		ASSERT(done);
1487 	}
1488 
1489 	/*
1490 	 * If the extent we're sharing is backed by written storage, increase
1491 	 * its refcount and map it into the file.
1492 	 */
1493 	if (dmap_written) {
1494 		xfs_refcount_increase_extent(tp, isrt, dmap);
1495 		xfs_bmap_map_extent(tp, ip, XFS_DATA_FORK, dmap);
1496 		qdelta += dmap->br_blockcount;
1497 	}
1498 
1499 	xfs_reflink_update_quota(tp, ip, false, qdelta);
1500 
1501 	/* Update dest isize if needed. */
1502 	newlen = XFS_FSB_TO_B(mp, dmap->br_startoff + dmap->br_blockcount);
1503 	newlen = min_t(xfs_off_t, newlen, new_isize);
1504 	if (newlen > i_size_read(VFS_I(ip))) {
1505 		trace_xfs_reflink_update_inode_size(ip, newlen);
1506 		i_size_write(VFS_I(ip), newlen);
1507 		ip->i_disk_size = newlen;
1508 		xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1509 	}
1510 
1511 	/* Commit everything and unlock. */
1512 	error = xfs_trans_commit(tp);
1513 	goto out_unlock;
1514 
1515 out_cancel:
1516 	xfs_trans_cancel(tp);
1517 out_unlock:
1518 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1519 out:
1520 	if (error)
1521 		trace_xfs_reflink_remap_extent_error(ip, error, _RET_IP_);
1522 	return error;
1523 }
1524 
1525 /* Remap a range of one file to the other. */
1526 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)1527 xfs_reflink_remap_blocks(
1528 	struct xfs_inode	*src,
1529 	loff_t			pos_in,
1530 	struct xfs_inode	*dest,
1531 	loff_t			pos_out,
1532 	loff_t			remap_len,
1533 	loff_t			*remapped)
1534 {
1535 	struct xfs_bmbt_irec	imap;
1536 	struct xfs_mount	*mp = src->i_mount;
1537 	xfs_fileoff_t		srcoff = XFS_B_TO_FSBT(mp, pos_in);
1538 	xfs_fileoff_t		destoff = XFS_B_TO_FSBT(mp, pos_out);
1539 	xfs_filblks_t		len;
1540 	xfs_filblks_t		remapped_len = 0;
1541 	xfs_off_t		new_isize = pos_out + remap_len;
1542 	int			nimaps;
1543 	int			error = 0;
1544 
1545 	len = min_t(xfs_filblks_t, XFS_B_TO_FSB(mp, remap_len),
1546 			XFS_MAX_FILEOFF);
1547 
1548 	trace_xfs_reflink_remap_blocks(src, srcoff, len, dest, destoff);
1549 
1550 	while (len > 0) {
1551 		unsigned int	lock_mode;
1552 
1553 		/* Read extent from the source file */
1554 		nimaps = 1;
1555 		lock_mode = xfs_ilock_data_map_shared(src);
1556 		error = xfs_bmapi_read(src, srcoff, len, &imap, &nimaps, 0);
1557 		xfs_iunlock(src, lock_mode);
1558 		if (error)
1559 			break;
1560 		/*
1561 		 * The caller supposedly flushed all dirty pages in the source
1562 		 * file range, which means that writeback should have allocated
1563 		 * or deleted all delalloc reservations in that range.  If we
1564 		 * find one, that's a good sign that something is seriously
1565 		 * wrong here.
1566 		 */
1567 		ASSERT(nimaps == 1 && imap.br_startoff == srcoff);
1568 		if (imap.br_startblock == DELAYSTARTBLOCK) {
1569 			ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1570 			xfs_bmap_mark_sick(src, XFS_DATA_FORK);
1571 			error = -EFSCORRUPTED;
1572 			break;
1573 		}
1574 
1575 		trace_xfs_reflink_remap_extent_src(src, &imap);
1576 
1577 		/* Remap into the destination file at the given offset. */
1578 		imap.br_startoff = destoff;
1579 		error = xfs_reflink_remap_extent(dest, &imap, new_isize);
1580 		if (error)
1581 			break;
1582 
1583 		if (fatal_signal_pending(current)) {
1584 			error = -EINTR;
1585 			break;
1586 		}
1587 
1588 		/* Advance drange/srange */
1589 		srcoff += imap.br_blockcount;
1590 		destoff += imap.br_blockcount;
1591 		len -= imap.br_blockcount;
1592 		remapped_len += imap.br_blockcount;
1593 		cond_resched();
1594 	}
1595 
1596 	if (error)
1597 		trace_xfs_reflink_remap_blocks_error(dest, error, _RET_IP_);
1598 	*remapped = min_t(loff_t, remap_len,
1599 			  XFS_FSB_TO_B(src->i_mount, remapped_len));
1600 	return error;
1601 }
1602 
1603 /*
1604  * If we're reflinking to a point past the destination file's EOF, we must
1605  * zero any speculative post-EOF preallocations that sit between the old EOF
1606  * and the destination file offset.
1607  */
1608 static int
xfs_reflink_zero_posteof(struct xfs_inode * ip,loff_t pos)1609 xfs_reflink_zero_posteof(
1610 	struct xfs_inode	*ip,
1611 	loff_t			pos)
1612 {
1613 	loff_t			isize = i_size_read(VFS_I(ip));
1614 
1615 	if (pos <= isize)
1616 		return 0;
1617 
1618 	trace_xfs_zero_eof(ip, isize, pos - isize);
1619 	return xfs_zero_range(ip, isize, pos - isize, NULL, NULL);
1620 }
1621 
1622 /*
1623  * Prepare two files for range cloning.  Upon a successful return both inodes
1624  * will have the iolock and mmaplock held, the page cache of the out file will
1625  * be truncated, and any leases on the out file will have been broken.  This
1626  * function borrows heavily from xfs_file_aio_write_checks.
1627  *
1628  * The VFS allows partial EOF blocks to "match" for dedupe even though it hasn't
1629  * checked that the bytes beyond EOF physically match. Hence we cannot use the
1630  * EOF block in the source dedupe range because it's not a complete block match,
1631  * hence can introduce a corruption into the file that has it's block replaced.
1632  *
1633  * In similar fashion, the VFS file cloning also allows partial EOF blocks to be
1634  * "block aligned" for the purposes of cloning entire files.  However, if the
1635  * source file range includes the EOF block and it lands within the existing EOF
1636  * of the destination file, then we can expose stale data from beyond the source
1637  * file EOF in the destination file.
1638  *
1639  * XFS doesn't support partial block sharing, so in both cases we have check
1640  * these cases ourselves. For dedupe, we can simply round the length to dedupe
1641  * down to the previous whole block and ignore the partial EOF block. While this
1642  * means we can't dedupe the last block of a file, this is an acceptible
1643  * tradeoff for simplicity on implementation.
1644  *
1645  * For cloning, we want to share the partial EOF block if it is also the new EOF
1646  * block of the destination file. If the partial EOF block lies inside the
1647  * existing destination EOF, then we have to abort the clone to avoid exposing
1648  * stale data in the destination file. Hence we reject these clone attempts with
1649  * -EINVAL in this case.
1650  */
1651 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)1652 xfs_reflink_remap_prep(
1653 	struct file		*file_in,
1654 	loff_t			pos_in,
1655 	struct file		*file_out,
1656 	loff_t			pos_out,
1657 	loff_t			*len,
1658 	unsigned int		remap_flags)
1659 {
1660 	struct inode		*inode_in = file_inode(file_in);
1661 	struct xfs_inode	*src = XFS_I(inode_in);
1662 	struct inode		*inode_out = file_inode(file_out);
1663 	struct xfs_inode	*dest = XFS_I(inode_out);
1664 	int			ret;
1665 
1666 	/* Lock both files against IO */
1667 	ret = xfs_ilock2_io_mmap(src, dest);
1668 	if (ret)
1669 		return ret;
1670 
1671 	/* Check file eligibility and prepare for block sharing. */
1672 	ret = -EINVAL;
1673 	/* Can't reflink between data and rt volumes */
1674 	if (XFS_IS_REALTIME_INODE(src) != XFS_IS_REALTIME_INODE(dest))
1675 		goto out_unlock;
1676 
1677 	/* Don't share DAX file data with non-DAX file. */
1678 	if (IS_DAX(inode_in) != IS_DAX(inode_out))
1679 		goto out_unlock;
1680 
1681 	if (!IS_DAX(inode_in))
1682 		ret = generic_remap_file_range_prep(file_in, pos_in, file_out,
1683 				pos_out, len, remap_flags);
1684 	else
1685 		ret = dax_remap_file_range_prep(file_in, pos_in, file_out,
1686 				pos_out, len, remap_flags, &xfs_read_iomap_ops);
1687 	if (ret || *len == 0)
1688 		goto out_unlock;
1689 
1690 	/* Attach dquots to dest inode before changing block map */
1691 	ret = xfs_qm_dqattach(dest);
1692 	if (ret)
1693 		goto out_unlock;
1694 
1695 	/*
1696 	 * Zero existing post-eof speculative preallocations in the destination
1697 	 * file.
1698 	 */
1699 	ret = xfs_reflink_zero_posteof(dest, pos_out);
1700 	if (ret)
1701 		goto out_unlock;
1702 
1703 	/* Set flags and remap blocks. */
1704 	ret = xfs_reflink_set_inode_flag(src, dest);
1705 	if (ret)
1706 		goto out_unlock;
1707 
1708 	/*
1709 	 * If pos_out > EOF, we may have dirtied blocks between EOF and
1710 	 * pos_out. In that case, we need to extend the flush and unmap to cover
1711 	 * from EOF to the end of the copy length.
1712 	 */
1713 	if (pos_out > XFS_ISIZE(dest)) {
1714 		loff_t	flen = *len + (pos_out - XFS_ISIZE(dest));
1715 		ret = xfs_flush_unmap_range(dest, XFS_ISIZE(dest), flen);
1716 	} else {
1717 		ret = xfs_flush_unmap_range(dest, pos_out, *len);
1718 	}
1719 	if (ret)
1720 		goto out_unlock;
1721 
1722 	xfs_iflags_set(src, XFS_IREMAPPING);
1723 	if (inode_in != inode_out)
1724 		xfs_ilock_demote(src, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL);
1725 
1726 	return 0;
1727 out_unlock:
1728 	xfs_iunlock2_io_mmap(src, dest);
1729 	return ret;
1730 }
1731 
1732 /* Does this inode need the reflink flag? */
1733 int
xfs_reflink_inode_has_shared_extents(struct xfs_trans * tp,struct xfs_inode * ip,bool * has_shared)1734 xfs_reflink_inode_has_shared_extents(
1735 	struct xfs_trans		*tp,
1736 	struct xfs_inode		*ip,
1737 	bool				*has_shared)
1738 {
1739 	struct xfs_bmbt_irec		got;
1740 	struct xfs_mount		*mp = ip->i_mount;
1741 	struct xfs_ifork		*ifp;
1742 	struct xfs_iext_cursor		icur;
1743 	bool				found;
1744 	int				error;
1745 
1746 	ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);
1747 	error = xfs_iread_extents(tp, ip, XFS_DATA_FORK);
1748 	if (error)
1749 		return error;
1750 
1751 	*has_shared = false;
1752 	found = xfs_iext_lookup_extent(ip, ifp, 0, &icur, &got);
1753 	while (found) {
1754 		xfs_extlen_t		shared_offset, shared_len;
1755 
1756 		if (isnullstartblock(got.br_startblock) ||
1757 		    got.br_state != XFS_EXT_NORM)
1758 			goto next;
1759 
1760 		if (XFS_IS_REALTIME_INODE(ip))
1761 			error = xfs_reflink_find_rtshared(mp, tp, &got,
1762 					&shared_offset, &shared_len, false);
1763 		else
1764 			error = xfs_reflink_find_shared(mp, tp, &got,
1765 					&shared_offset, &shared_len, false);
1766 		if (error)
1767 			return error;
1768 
1769 		/* Is there still a shared block here? */
1770 		if (shared_len) {
1771 			*has_shared = true;
1772 			return 0;
1773 		}
1774 next:
1775 		found = xfs_iext_next_extent(ifp, &icur, &got);
1776 	}
1777 
1778 	return 0;
1779 }
1780 
1781 /*
1782  * Clear the inode reflink flag if there are no shared extents.
1783  *
1784  * The caller is responsible for joining the inode to the transaction passed in.
1785  * The inode will be joined to the transaction that is returned to the caller.
1786  */
1787 int
xfs_reflink_clear_inode_flag(struct xfs_inode * ip,struct xfs_trans ** tpp)1788 xfs_reflink_clear_inode_flag(
1789 	struct xfs_inode	*ip,
1790 	struct xfs_trans	**tpp)
1791 {
1792 	bool			needs_flag;
1793 	int			error = 0;
1794 
1795 	ASSERT(xfs_is_reflink_inode(ip));
1796 
1797 	if (!xfs_can_free_cowblocks(ip))
1798 		return 0;
1799 
1800 	error = xfs_reflink_inode_has_shared_extents(*tpp, ip, &needs_flag);
1801 	if (error || needs_flag)
1802 		return error;
1803 
1804 	/*
1805 	 * We didn't find any shared blocks so turn off the reflink flag.
1806 	 * First, get rid of any leftover CoW mappings.
1807 	 */
1808 	error = xfs_reflink_cancel_cow_blocks(ip, tpp, 0, XFS_MAX_FILEOFF,
1809 			true);
1810 	if (error)
1811 		return error;
1812 
1813 	/* Clear the inode flag. */
1814 	trace_xfs_reflink_unset_inode_flag(ip);
1815 	ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1816 	xfs_inode_clear_cowblocks_tag(ip);
1817 	xfs_trans_log_inode(*tpp, ip, XFS_ILOG_CORE);
1818 
1819 	return error;
1820 }
1821 
1822 /*
1823  * Clear the inode reflink flag if there are no shared extents and the size
1824  * hasn't changed.
1825  */
1826 STATIC int
xfs_reflink_try_clear_inode_flag(struct xfs_inode * ip)1827 xfs_reflink_try_clear_inode_flag(
1828 	struct xfs_inode	*ip)
1829 {
1830 	struct xfs_mount	*mp = ip->i_mount;
1831 	struct xfs_trans	*tp;
1832 	int			error = 0;
1833 
1834 	/* Start a rolling transaction to remove the mappings */
1835 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0, 0, &tp);
1836 	if (error)
1837 		return error;
1838 
1839 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1840 	xfs_trans_ijoin(tp, ip, 0);
1841 
1842 	error = xfs_reflink_clear_inode_flag(ip, &tp);
1843 	if (error)
1844 		goto cancel;
1845 
1846 	error = xfs_trans_commit(tp);
1847 	if (error)
1848 		goto out;
1849 
1850 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1851 	return 0;
1852 cancel:
1853 	xfs_trans_cancel(tp);
1854 out:
1855 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1856 	return error;
1857 }
1858 
1859 /*
1860  * Pre-COW all shared blocks within a given byte range of a file and turn off
1861  * the reflink flag if we unshare all of the file's blocks.
1862  */
1863 int
xfs_reflink_unshare(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t len)1864 xfs_reflink_unshare(
1865 	struct xfs_inode	*ip,
1866 	xfs_off_t		offset,
1867 	xfs_off_t		len)
1868 {
1869 	struct inode		*inode = VFS_I(ip);
1870 	int			error;
1871 
1872 	if (!xfs_is_reflink_inode(ip))
1873 		return 0;
1874 
1875 	trace_xfs_reflink_unshare(ip, offset, len);
1876 
1877 	inode_dio_wait(inode);
1878 
1879 	if (IS_DAX(inode))
1880 		error = dax_file_unshare(inode, offset, len,
1881 				&xfs_dax_write_iomap_ops);
1882 	else
1883 		error = iomap_file_unshare(inode, offset, len,
1884 				&xfs_buffered_write_iomap_ops,
1885 				&xfs_iomap_write_ops);
1886 	if (error)
1887 		goto out;
1888 
1889 	error = filemap_write_and_wait_range(inode->i_mapping, offset,
1890 			offset + len - 1);
1891 	if (error)
1892 		goto out;
1893 
1894 	/* Turn off the reflink flag if possible. */
1895 	error = xfs_reflink_try_clear_inode_flag(ip);
1896 	if (error)
1897 		goto out;
1898 	return 0;
1899 
1900 out:
1901 	trace_xfs_reflink_unshare_error(ip, error, _RET_IP_);
1902 	return error;
1903 }
1904 
1905 /*
1906  * Can we use reflink with this realtime extent size?  Note that we don't check
1907  * for rblocks > 0 here because this can be called as part of attaching a new
1908  * rt section.
1909  */
1910 bool
xfs_reflink_supports_rextsize(struct xfs_mount * mp,unsigned int rextsize)1911 xfs_reflink_supports_rextsize(
1912 	struct xfs_mount	*mp,
1913 	unsigned int		rextsize)
1914 {
1915 	/* reflink on the realtime device requires rtgroups */
1916 	if (!xfs_has_rtgroups(mp))
1917 	       return false;
1918 
1919 	/*
1920 	 * Reflink doesn't support rt extent size larger than a single fsblock
1921 	 * because we would have to perform CoW-around for unaligned write
1922 	 * requests to guarantee that we always remap entire rt extents.
1923 	 */
1924 	if (rextsize != 1)
1925 		return false;
1926 
1927 	return true;
1928 }
1929