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