]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blame - fs/xfs/xfs_reflink.c
xfs: use new extent lookup helpers in __xfs_reflink_reserve_cow
[mirror_ubuntu-zesty-kernel.git] / fs / xfs / xfs_reflink.c
CommitLineData
3993baeb
DW
1/*
2 * Copyright (C) 2016 Oracle. All Rights Reserved.
3 *
4 * Author: Darrick J. Wong <darrick.wong@oracle.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it would be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
19 */
20#include "xfs.h"
21#include "xfs_fs.h"
22#include "xfs_shared.h"
23#include "xfs_format.h"
24#include "xfs_log_format.h"
25#include "xfs_trans_resv.h"
26#include "xfs_mount.h"
27#include "xfs_defer.h"
28#include "xfs_da_format.h"
29#include "xfs_da_btree.h"
30#include "xfs_inode.h"
31#include "xfs_trans.h"
32#include "xfs_inode_item.h"
33#include "xfs_bmap.h"
34#include "xfs_bmap_util.h"
35#include "xfs_error.h"
36#include "xfs_dir2.h"
37#include "xfs_dir2_priv.h"
38#include "xfs_ioctl.h"
39#include "xfs_trace.h"
40#include "xfs_log.h"
41#include "xfs_icache.h"
42#include "xfs_pnfs.h"
174edb0e 43#include "xfs_btree.h"
3993baeb
DW
44#include "xfs_refcount_btree.h"
45#include "xfs_refcount.h"
46#include "xfs_bmap_btree.h"
47#include "xfs_trans_space.h"
48#include "xfs_bit.h"
49#include "xfs_alloc.h"
50#include "xfs_quota_defs.h"
51#include "xfs_quota.h"
52#include "xfs_btree.h"
53#include "xfs_bmap_btree.h"
54#include "xfs_reflink.h"
2a06705c 55#include "xfs_iomap.h"
43caeb18 56#include "xfs_rmap_btree.h"
6fa164b8
DW
57#include "xfs_sb.h"
58#include "xfs_ag_resv.h"
3993baeb
DW
59
60/*
61 * Copy on Write of Shared Blocks
62 *
63 * XFS must preserve "the usual" file semantics even when two files share
64 * the same physical blocks. This means that a write to one file must not
65 * alter the blocks in a different file; the way that we'll do that is
66 * through the use of a copy-on-write mechanism. At a high level, that
67 * means that when we want to write to a shared block, we allocate a new
68 * block, write the data to the new block, and if that succeeds we map the
69 * new block into the file.
70 *
71 * XFS provides a "delayed allocation" mechanism that defers the allocation
72 * of disk blocks to dirty-but-not-yet-mapped file blocks as long as
73 * possible. This reduces fragmentation by enabling the filesystem to ask
74 * for bigger chunks less often, which is exactly what we want for CoW.
75 *
76 * The delalloc mechanism begins when the kernel wants to make a block
77 * writable (write_begin or page_mkwrite). If the offset is not mapped, we
78 * create a delalloc mapping, which is a regular in-core extent, but without
79 * a real startblock. (For delalloc mappings, the startblock encodes both
80 * a flag that this is a delalloc mapping, and a worst-case estimate of how
81 * many blocks might be required to put the mapping into the BMBT.) delalloc
82 * mappings are a reservation against the free space in the filesystem;
83 * adjacent mappings can also be combined into fewer larger mappings.
84 *
85 * When dirty pages are being written out (typically in writepage), the
86 * delalloc reservations are converted into real mappings by allocating
87 * blocks and replacing the delalloc mapping with real ones. A delalloc
88 * mapping can be replaced by several real ones if the free space is
89 * fragmented.
90 *
91 * We want to adapt the delalloc mechanism for copy-on-write, since the
92 * write paths are similar. The first two steps (creating the reservation
93 * and allocating the blocks) are exactly the same as delalloc except that
94 * the mappings must be stored in a separate CoW fork because we do not want
95 * to disturb the mapping in the data fork until we're sure that the write
96 * succeeded. IO completion in this case is the process of removing the old
97 * mapping from the data fork and moving the new mapping from the CoW fork to
98 * the data fork. This will be discussed shortly.
99 *
100 * For now, unaligned directio writes will be bounced back to the page cache.
101 * Block-aligned directio writes will use the same mechanism as buffered
102 * writes.
103 *
104 * CoW remapping must be done after the data block write completes,
105 * because we don't want to destroy the old data fork map until we're sure
106 * the new block has been written. Since the new mappings are kept in a
107 * separate fork, we can simply iterate these mappings to find the ones
108 * that cover the file blocks that we just CoW'd. For each extent, simply
109 * unmap the corresponding range in the data fork, map the new range into
110 * the data fork, and remove the extent from the CoW fork.
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 */
2a06705c
DW
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 */
128int
129xfs_reflink_find_shared(
130 struct xfs_mount *mp,
131 xfs_agnumber_t agno,
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(mp, NULL, agno, 0, &agbp);
143 if (error)
144 return error;
145
146 cur = xfs_refcountbt_init_cursor(mp, NULL, agbp, agno, NULL);
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 ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
152
153 xfs_buf_relse(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 */
167int
168xfs_reflink_trim_around_shared(
169 struct xfs_inode *ip,
170 struct xfs_bmbt_irec *irec,
171 bool *shared,
172 bool *trimmed)
173{
174 xfs_agnumber_t agno;
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_reflink_inode(ip) ||
183 ISUNWRITTEN(irec) ||
184 irec->br_startblock == HOLESTARTBLOCK ||
62c5ac89
CH
185 irec->br_startblock == DELAYSTARTBLOCK ||
186 isnullstartblock(irec->br_startblock)) {
2a06705c
DW
187 *shared = false;
188 return 0;
189 }
190
191 trace_xfs_reflink_trim_around_shared(ip, irec);
192
193 agno = XFS_FSB_TO_AGNO(ip->i_mount, irec->br_startblock);
194 agbno = XFS_FSB_TO_AGBNO(ip->i_mount, irec->br_startblock);
195 aglen = irec->br_blockcount;
196
197 error = xfs_reflink_find_shared(ip->i_mount, agno, agbno,
198 aglen, &fbno, &flen, true);
199 if (error)
200 return error;
201
202 *shared = *trimmed = false;
203 if (fbno == NULLAGBLOCK) {
204 /* No shared blocks at all. */
205 return 0;
206 } else if (fbno == agbno) {
207 /*
208 * The start of this extent is shared. Truncate the
209 * mapping at the end of the shared region so that a
210 * subsequent iteration starts at the start of the
211 * unshared region.
212 */
213 irec->br_blockcount = flen;
214 *shared = true;
215 if (flen != aglen)
216 *trimmed = true;
217 return 0;
218 } else {
219 /*
220 * There's a shared extent midway through this extent.
221 * Truncate the mapping at the start of the shared
222 * extent so that a subsequent iteration starts at the
223 * start of the shared region.
224 */
225 irec->br_blockcount = fbno - agbno;
226 *trimmed = true;
227 return 0;
228 }
229}
230
3ba020be
CH
231/*
232 * Trim the passed in imap to the next shared/unshared extent boundary, and
233 * if imap->br_startoff points to a shared extent reserve space for it in the
234 * COW fork. In this case *shared is set to true, else to false.
235 *
236 * Note that imap will always contain the block numbers for the existing blocks
237 * in the data fork, as the upper layers need them for read-modify-write
238 * operations.
239 */
240int
241xfs_reflink_reserve_cow(
2a06705c 242 struct xfs_inode *ip,
3ba020be
CH
243 struct xfs_bmbt_irec *imap,
244 bool *shared)
2a06705c 245{
2755fc44
CH
246 struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_COW_FORK);
247 struct xfs_bmbt_irec got;
3ba020be 248 xfs_fileoff_t end_fsb, orig_end_fsb;
2755fc44
CH
249 int error = 0;
250 bool eof = false, trimmed;
2a06705c 251 xfs_extnum_t idx;
f7ca3522 252 xfs_extlen_t align;
2a06705c 253
3ba020be
CH
254 /*
255 * Search the COW fork extent list first. This serves two purposes:
256 * first this implement the speculative preallocation using cowextisze,
257 * so that we also unshared block adjacent to shared blocks instead
258 * of just the shared blocks themselves. Second the lookup in the
259 * extent list is generally faster than going out to the shared extent
260 * tree.
261 */
2755fc44
CH
262
263 if (!xfs_iext_lookup_extent(ip, ifp, imap->br_startoff, &idx, &got))
264 eof = true;
3ba020be
CH
265 if (!eof && got.br_startoff <= imap->br_startoff) {
266 trace_xfs_reflink_cow_found(ip, imap);
267 xfs_trim_extent(imap, got.br_startoff, got.br_blockcount);
2a06705c 268
3ba020be
CH
269 *shared = true;
270 return 0;
271 }
2a06705c
DW
272
273 /* Trim the mapping to the nearest shared extent boundary. */
3ba020be 274 error = xfs_reflink_trim_around_shared(ip, imap, shared, &trimmed);
2a06705c 275 if (error)
3ba020be 276 return error;
2a06705c
DW
277
278 /* Not shared? Just report the (potentially capped) extent. */
3ba020be
CH
279 if (!*shared)
280 return 0;
2a06705c
DW
281
282 /*
283 * Fork all the shared blocks from our write offset until the end of
284 * the extent.
285 */
286 error = xfs_qm_dqattach_locked(ip, 0);
287 if (error)
3ba020be
CH
288 return error;
289
290 end_fsb = orig_end_fsb = imap->br_startoff + imap->br_blockcount;
2a06705c 291
f7ca3522
DW
292 align = xfs_eof_alignment(ip, xfs_get_cowextsz_hint(ip));
293 if (align)
294 end_fsb = roundup_64(end_fsb, align);
295
2a06705c 296retry:
3ba020be 297 error = xfs_bmapi_reserve_delalloc(ip, XFS_COW_FORK, imap->br_startoff,
65c5f419 298 end_fsb - imap->br_startoff, &got, &idx, eof);
2a06705c
DW
299 switch (error) {
300 case 0:
301 break;
302 case -ENOSPC:
303 case -EDQUOT:
304 /* retry without any preallocation */
3ba020be 305 trace_xfs_reflink_cow_enospc(ip, imap);
2a06705c
DW
306 if (end_fsb != orig_end_fsb) {
307 end_fsb = orig_end_fsb;
308 goto retry;
309 }
310 /*FALLTHRU*/
311 default:
3ba020be 312 return error;
2a06705c
DW
313 }
314
83104d44
DW
315 if (end_fsb != orig_end_fsb)
316 xfs_inode_set_cowblocks_tag(ip);
317
2a06705c 318 trace_xfs_reflink_cow_alloc(ip, &got);
3ba020be 319 return 0;
2a06705c 320}
ef473667 321
0613f16c
DW
322/* Allocate all CoW reservations covering a range of blocks in a file. */
323static int
324__xfs_reflink_allocate_cow(
325 struct xfs_inode *ip,
326 xfs_fileoff_t *offset_fsb,
327 xfs_fileoff_t end_fsb)
328{
329 struct xfs_mount *mp = ip->i_mount;
330 struct xfs_bmbt_irec imap;
331 struct xfs_defer_ops dfops;
332 struct xfs_trans *tp;
333 xfs_fsblock_t first_block;
0613f16c 334 int nimaps = 1, error;
3ba020be 335 bool shared;
0613f16c
DW
336
337 xfs_defer_init(&dfops, &first_block);
338
339 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0,
340 XFS_TRANS_RESERVE, &tp);
341 if (error)
342 return error;
343
344 xfs_ilock(ip, XFS_ILOCK_EXCL);
345
3ba020be
CH
346 /* Read extent from the source file. */
347 nimaps = 1;
348 error = xfs_bmapi_read(ip, *offset_fsb, end_fsb - *offset_fsb,
349 &imap, &nimaps, 0);
350 if (error)
351 goto out_unlock;
352 ASSERT(nimaps == 1);
353
354 error = xfs_reflink_reserve_cow(ip, &imap, &shared);
0613f16c
DW
355 if (error)
356 goto out_trans_cancel;
357
3ba020be
CH
358 if (!shared) {
359 *offset_fsb = imap.br_startoff + imap.br_blockcount;
0613f16c
DW
360 goto out_trans_cancel;
361 }
362
363 xfs_trans_ijoin(tp, ip, 0);
3ba020be 364 error = xfs_bmapi_write(tp, ip, imap.br_startoff, imap.br_blockcount,
0613f16c
DW
365 XFS_BMAPI_COWFORK, &first_block,
366 XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK),
367 &imap, &nimaps, &dfops);
368 if (error)
369 goto out_trans_cancel;
370
0613f16c
DW
371 error = xfs_defer_finish(&tp, &dfops, NULL);
372 if (error)
373 goto out_trans_cancel;
374
375 error = xfs_trans_commit(tp);
376
3ba020be 377 *offset_fsb = imap.br_startoff + imap.br_blockcount;
0613f16c
DW
378out_unlock:
379 xfs_iunlock(ip, XFS_ILOCK_EXCL);
380 return error;
381out_trans_cancel:
382 xfs_defer_cancel(&dfops);
383 xfs_trans_cancel(tp);
384 goto out_unlock;
385}
386
387/* Allocate all CoW reservations covering a part of a file. */
388int
389xfs_reflink_allocate_cow_range(
390 struct xfs_inode *ip,
391 xfs_off_t offset,
392 xfs_off_t count)
393{
394 struct xfs_mount *mp = ip->i_mount;
395 xfs_fileoff_t offset_fsb = XFS_B_TO_FSBT(mp, offset);
396 xfs_fileoff_t end_fsb = XFS_B_TO_FSB(mp, offset + count);
397 int error;
398
399 ASSERT(xfs_is_reflink_inode(ip));
400
401 trace_xfs_reflink_allocate_cow_range(ip, offset, count);
402
403 /*
404 * Make sure that the dquots are there.
405 */
406 error = xfs_qm_dqattach(ip, 0);
407 if (error)
408 return error;
409
410 while (offset_fsb < end_fsb) {
411 error = __xfs_reflink_allocate_cow(ip, &offset_fsb, end_fsb);
412 if (error) {
413 trace_xfs_reflink_allocate_cow_range_error(ip, error,
414 _RET_IP_);
415 break;
416 }
417 }
418
419 return error;
420}
421
ef473667
DW
422/*
423 * Find the CoW reservation (and whether or not it needs block allocation)
424 * for a given byte offset of a file.
425 */
426bool
427xfs_reflink_find_cow_mapping(
428 struct xfs_inode *ip,
429 xfs_off_t offset,
430 struct xfs_bmbt_irec *imap,
431 bool *need_alloc)
432{
433 struct xfs_bmbt_irec irec;
434 struct xfs_ifork *ifp;
435 struct xfs_bmbt_rec_host *gotp;
436 xfs_fileoff_t bno;
437 xfs_extnum_t idx;
438
439 ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL | XFS_ILOCK_SHARED));
440 ASSERT(xfs_is_reflink_inode(ip));
441
442 /* Find the extent in the CoW fork. */
443 ifp = XFS_IFORK_PTR(ip, XFS_COW_FORK);
444 bno = XFS_B_TO_FSBT(ip->i_mount, offset);
445 gotp = xfs_iext_bno_to_ext(ifp, bno, &idx);
446 if (!gotp)
447 return false;
448
449 xfs_bmbt_get_all(gotp, &irec);
450 if (bno >= irec.br_startoff + irec.br_blockcount ||
451 bno < irec.br_startoff)
452 return false;
453
454 trace_xfs_reflink_find_cow_mapping(ip, offset, 1, XFS_IO_OVERWRITE,
455 &irec);
456
457 /* If it's still delalloc, we must allocate later. */
458 *imap = irec;
459 *need_alloc = !!(isnullstartblock(irec.br_startblock));
460
461 return true;
462}
463
464/*
465 * Trim an extent to end at the next CoW reservation past offset_fsb.
466 */
467int
468xfs_reflink_trim_irec_to_next_cow(
469 struct xfs_inode *ip,
470 xfs_fileoff_t offset_fsb,
471 struct xfs_bmbt_irec *imap)
472{
473 struct xfs_bmbt_irec irec;
474 struct xfs_ifork *ifp;
475 struct xfs_bmbt_rec_host *gotp;
476 xfs_extnum_t idx;
477
478 if (!xfs_is_reflink_inode(ip))
479 return 0;
480
481 /* Find the extent in the CoW fork. */
482 ifp = XFS_IFORK_PTR(ip, XFS_COW_FORK);
483 gotp = xfs_iext_bno_to_ext(ifp, offset_fsb, &idx);
484 if (!gotp)
485 return 0;
486 xfs_bmbt_get_all(gotp, &irec);
487
488 /* This is the extent before; try sliding up one. */
489 if (irec.br_startoff < offset_fsb) {
490 idx++;
5d829300 491 if (idx >= xfs_iext_count(ifp))
ef473667
DW
492 return 0;
493 gotp = xfs_iext_get_ext(ifp, idx);
494 xfs_bmbt_get_all(gotp, &irec);
495 }
496
497 if (irec.br_startoff >= imap->br_startoff + imap->br_blockcount)
498 return 0;
499
500 imap->br_blockcount = irec.br_startoff - imap->br_startoff;
501 trace_xfs_reflink_trim_irec(ip, imap);
502
503 return 0;
504}
43caeb18
DW
505
506/*
507 * Cancel all pending CoW reservations for some block range of an inode.
508 */
509int
510xfs_reflink_cancel_cow_blocks(
511 struct xfs_inode *ip,
512 struct xfs_trans **tpp,
513 xfs_fileoff_t offset_fsb,
514 xfs_fileoff_t end_fsb)
515{
3e0ee78f
CH
516 struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_COW_FORK);
517 struct xfs_bmbt_irec got, prev, del;
518 xfs_extnum_t idx;
43caeb18
DW
519 xfs_fsblock_t firstfsb;
520 struct xfs_defer_ops dfops;
3e0ee78f 521 int error = 0, eof = 0;
43caeb18
DW
522
523 if (!xfs_is_reflink_inode(ip))
524 return 0;
525
3e0ee78f
CH
526 xfs_bmap_search_extents(ip, offset_fsb, XFS_COW_FORK, &eof, &idx,
527 &got, &prev);
528 if (eof)
529 return 0;
43caeb18 530
3e0ee78f
CH
531 while (got.br_startoff < end_fsb) {
532 del = got;
533 xfs_trim_extent(&del, offset_fsb, end_fsb - offset_fsb);
534 trace_xfs_reflink_cancel_cow(ip, &del);
43caeb18 535
3e0ee78f
CH
536 if (isnullstartblock(del.br_startblock)) {
537 error = xfs_bmap_del_extent_delay(ip, XFS_COW_FORK,
538 &idx, &got, &del);
43caeb18
DW
539 if (error)
540 break;
43caeb18
DW
541 } else {
542 xfs_trans_ijoin(*tpp, ip, 0);
543 xfs_defer_init(&dfops, &firstfsb);
544
174edb0e
DW
545 /* Free the CoW orphan record. */
546 error = xfs_refcount_free_cow_extent(ip->i_mount,
3e0ee78f
CH
547 &dfops, del.br_startblock,
548 del.br_blockcount);
174edb0e
DW
549 if (error)
550 break;
551
43caeb18 552 xfs_bmap_add_free(ip->i_mount, &dfops,
3e0ee78f 553 del.br_startblock, del.br_blockcount,
43caeb18
DW
554 NULL);
555
556 /* Update quota accounting */
557 xfs_trans_mod_dquot_byino(*tpp, ip, XFS_TRANS_DQ_BCOUNT,
3e0ee78f 558 -(long)del.br_blockcount);
43caeb18
DW
559
560 /* Roll the transaction */
561 error = xfs_defer_finish(tpp, &dfops, ip);
562 if (error) {
563 xfs_defer_cancel(&dfops);
564 break;
565 }
566
567 /* Remove the mapping from the CoW fork. */
3e0ee78f 568 xfs_bmap_del_extent_cow(ip, &idx, &got, &del);
43caeb18
DW
569 }
570
5d829300 571 if (++idx >= xfs_iext_count(ifp))
c17a8ef4 572 break;
3e0ee78f 573 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, idx), &got);
43caeb18
DW
574 }
575
c17a8ef4
BF
576 /* clear tag if cow fork is emptied */
577 if (!ifp->if_bytes)
578 xfs_inode_clear_cowblocks_tag(ip);
579
43caeb18
DW
580 return error;
581}
582
583/*
584 * Cancel all pending CoW reservations for some byte range of an inode.
585 */
586int
587xfs_reflink_cancel_cow_range(
588 struct xfs_inode *ip,
589 xfs_off_t offset,
590 xfs_off_t count)
591{
592 struct xfs_trans *tp;
593 xfs_fileoff_t offset_fsb;
594 xfs_fileoff_t end_fsb;
595 int error;
596
597 trace_xfs_reflink_cancel_cow_range(ip, offset, count);
63646fc5 598 ASSERT(xfs_is_reflink_inode(ip));
43caeb18
DW
599
600 offset_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
601 if (count == NULLFILEOFF)
602 end_fsb = NULLFILEOFF;
603 else
604 end_fsb = XFS_B_TO_FSB(ip->i_mount, offset + count);
605
606 /* Start a rolling transaction to remove the mappings */
607 error = xfs_trans_alloc(ip->i_mount, &M_RES(ip->i_mount)->tr_write,
608 0, 0, 0, &tp);
609 if (error)
610 goto out;
611
612 xfs_ilock(ip, XFS_ILOCK_EXCL);
613 xfs_trans_ijoin(tp, ip, 0);
614
615 /* Scrape out the old CoW reservations */
616 error = xfs_reflink_cancel_cow_blocks(ip, &tp, offset_fsb, end_fsb);
617 if (error)
618 goto out_cancel;
619
620 error = xfs_trans_commit(tp);
621
622 xfs_iunlock(ip, XFS_ILOCK_EXCL);
623 return error;
624
625out_cancel:
626 xfs_trans_cancel(tp);
627 xfs_iunlock(ip, XFS_ILOCK_EXCL);
628out:
629 trace_xfs_reflink_cancel_cow_range_error(ip, error, _RET_IP_);
630 return error;
631}
632
633/*
634 * Remap parts of a file's data fork after a successful CoW.
635 */
636int
637xfs_reflink_end_cow(
638 struct xfs_inode *ip,
639 xfs_off_t offset,
640 xfs_off_t count)
641{
c1112b6e
CH
642 struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_COW_FORK);
643 struct xfs_bmbt_irec got, prev, del;
43caeb18
DW
644 struct xfs_trans *tp;
645 xfs_fileoff_t offset_fsb;
646 xfs_fileoff_t end_fsb;
43caeb18
DW
647 xfs_fsblock_t firstfsb;
648 struct xfs_defer_ops dfops;
c1112b6e 649 int error, eof = 0;
43caeb18 650 unsigned int resblks;
43caeb18 651 xfs_filblks_t rlen;
c1112b6e 652 xfs_extnum_t idx;
43caeb18
DW
653
654 trace_xfs_reflink_end_cow(ip, offset, count);
655
c1112b6e
CH
656 /* No COW extents? That's easy! */
657 if (ifp->if_bytes == 0)
658 return 0;
659
43caeb18
DW
660 offset_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
661 end_fsb = XFS_B_TO_FSB(ip->i_mount, offset + count);
43caeb18
DW
662
663 /* Start a rolling transaction to switch the mappings */
664 resblks = XFS_EXTENTADD_SPACE_RES(ip->i_mount, XFS_DATA_FORK);
665 error = xfs_trans_alloc(ip->i_mount, &M_RES(ip->i_mount)->tr_write,
666 resblks, 0, 0, &tp);
667 if (error)
668 goto out;
669
670 xfs_ilock(ip, XFS_ILOCK_EXCL);
671 xfs_trans_ijoin(tp, ip, 0);
672
c1112b6e
CH
673 xfs_bmap_search_extents(ip, end_fsb - 1, XFS_COW_FORK, &eof, &idx,
674 &got, &prev);
43caeb18 675
c1112b6e
CH
676 /* If there is a hole at end_fsb - 1 go to the previous extent */
677 if (eof || got.br_startoff > end_fsb) {
678 ASSERT(idx > 0);
679 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, --idx), &got);
680 }
43caeb18 681
c1112b6e
CH
682 /* Walk backwards until we're out of the I/O range... */
683 while (got.br_startoff + got.br_blockcount > offset_fsb) {
684 del = got;
685 xfs_trim_extent(&del, offset_fsb, end_fsb - offset_fsb);
686
687 /* Extent delete may have bumped idx forward */
688 if (!del.br_blockcount) {
689 idx--;
43caeb18 690 goto next_extent;
c1112b6e
CH
691 }
692
693 ASSERT(!isnullstartblock(got.br_startblock));
43caeb18
DW
694
695 /* Unmap the old blocks in the data fork. */
c1112b6e
CH
696 xfs_defer_init(&dfops, &firstfsb);
697 rlen = del.br_blockcount;
698 error = __xfs_bunmapi(tp, ip, del.br_startoff, &rlen, 0, 1,
699 &firstfsb, &dfops);
700 if (error)
701 goto out_defer;
43caeb18 702
c1112b6e
CH
703 /* Trim the extent to whatever got unmapped. */
704 if (rlen) {
705 xfs_trim_extent(&del, del.br_startoff + rlen,
706 del.br_blockcount - rlen);
707 }
708 trace_xfs_reflink_cow_remap(ip, &del);
174edb0e 709
c1112b6e
CH
710 /* Free the CoW orphan record. */
711 error = xfs_refcount_free_cow_extent(tp->t_mountp, &dfops,
712 del.br_startblock, del.br_blockcount);
713 if (error)
714 goto out_defer;
43caeb18 715
c1112b6e
CH
716 /* Map the new blocks into the data fork. */
717 error = xfs_bmap_map_extent(tp->t_mountp, &dfops, ip, &del);
718 if (error)
719 goto out_defer;
43caeb18 720
c1112b6e
CH
721 /* Remove the mapping from the CoW fork. */
722 xfs_bmap_del_extent_cow(ip, &idx, &got, &del);
723
724 error = xfs_defer_finish(&tp, &dfops, ip);
725 if (error)
726 goto out_defer;
43caeb18
DW
727
728next_extent:
c1112b6e
CH
729 if (idx < 0)
730 break;
731 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, idx), &got);
43caeb18
DW
732 }
733
734 error = xfs_trans_commit(tp);
735 xfs_iunlock(ip, XFS_ILOCK_EXCL);
736 if (error)
737 goto out;
738 return 0;
739
740out_defer:
741 xfs_defer_cancel(&dfops);
43caeb18
DW
742 xfs_trans_cancel(tp);
743 xfs_iunlock(ip, XFS_ILOCK_EXCL);
744out:
745 trace_xfs_reflink_end_cow_error(ip, error, _RET_IP_);
746 return error;
747}
174edb0e
DW
748
749/*
750 * Free leftover CoW reservations that didn't get cleaned out.
751 */
752int
753xfs_reflink_recover_cow(
754 struct xfs_mount *mp)
755{
756 xfs_agnumber_t agno;
757 int error = 0;
758
759 if (!xfs_sb_version_hasreflink(&mp->m_sb))
760 return 0;
761
762 for (agno = 0; agno < mp->m_sb.sb_agcount; agno++) {
763 error = xfs_refcount_recover_cow_leftovers(mp, agno);
764 if (error)
765 break;
766 }
767
768 return error;
769}
862bb360
DW
770
771/*
772 * Reflinking (Block) Ranges of Two Files Together
773 *
774 * First, ensure that the reflink flag is set on both inodes. The flag is an
775 * optimization to avoid unnecessary refcount btree lookups in the write path.
776 *
777 * Now we can iteratively remap the range of extents (and holes) in src to the
778 * corresponding ranges in dest. Let drange and srange denote the ranges of
779 * logical blocks in dest and src touched by the reflink operation.
780 *
781 * While the length of drange is greater than zero,
782 * - Read src's bmbt at the start of srange ("imap")
783 * - If imap doesn't exist, make imap appear to start at the end of srange
784 * with zero length.
785 * - If imap starts before srange, advance imap to start at srange.
786 * - If imap goes beyond srange, truncate imap to end at the end of srange.
787 * - Punch (imap start - srange start + imap len) blocks from dest at
788 * offset (drange start).
789 * - If imap points to a real range of pblks,
790 * > Increase the refcount of the imap's pblks
791 * > Map imap's pblks into dest at the offset
792 * (drange start + imap start - srange start)
793 * - Advance drange and srange by (imap start - srange start + imap len)
794 *
795 * Finally, if the reflink made dest longer, update both the in-core and
796 * on-disk file sizes.
797 *
798 * ASCII Art Demonstration:
799 *
800 * Let's say we want to reflink this source file:
801 *
802 * ----SSSSSSS-SSSSS----SSSSSS (src file)
803 * <-------------------->
804 *
805 * into this destination file:
806 *
807 * --DDDDDDDDDDDDDDDDDDD--DDD (dest file)
808 * <-------------------->
809 * '-' means a hole, and 'S' and 'D' are written blocks in the src and dest.
810 * Observe that the range has different logical offsets in either file.
811 *
812 * Consider that the first extent in the source file doesn't line up with our
813 * reflink range. Unmapping and remapping are separate operations, so we can
814 * unmap more blocks from the destination file than we remap.
815 *
816 * ----SSSSSSS-SSSSS----SSSSSS
817 * <------->
818 * --DDDDD---------DDDDD--DDD
819 * <------->
820 *
821 * Now remap the source extent into the destination file:
822 *
823 * ----SSSSSSS-SSSSS----SSSSSS
824 * <------->
825 * --DDDDD--SSSSSSSDDDDD--DDD
826 * <------->
827 *
828 * Do likewise with the second hole and extent in our range. Holes in the
829 * unmap range don't affect our operation.
830 *
831 * ----SSSSSSS-SSSSS----SSSSSS
832 * <---->
833 * --DDDDD--SSSSSSS-SSSSS-DDD
834 * <---->
835 *
836 * Finally, unmap and remap part of the third extent. This will increase the
837 * size of the destination file.
838 *
839 * ----SSSSSSS-SSSSS----SSSSSS
840 * <----->
841 * --DDDDD--SSSSSSS-SSSSS----SSS
842 * <----->
843 *
844 * Once we update the destination file's i_size, we're done.
845 */
846
847/*
848 * Ensure the reflink bit is set in both inodes.
849 */
850STATIC int
851xfs_reflink_set_inode_flag(
852 struct xfs_inode *src,
853 struct xfs_inode *dest)
854{
855 struct xfs_mount *mp = src->i_mount;
856 int error;
857 struct xfs_trans *tp;
858
859 if (xfs_is_reflink_inode(src) && xfs_is_reflink_inode(dest))
860 return 0;
861
862 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);
863 if (error)
864 goto out_error;
865
866 /* Lock both files against IO */
867 if (src->i_ino == dest->i_ino)
868 xfs_ilock(src, XFS_ILOCK_EXCL);
869 else
870 xfs_lock_two_inodes(src, dest, XFS_ILOCK_EXCL);
871
872 if (!xfs_is_reflink_inode(src)) {
873 trace_xfs_reflink_set_inode_flag(src);
874 xfs_trans_ijoin(tp, src, XFS_ILOCK_EXCL);
875 src->i_d.di_flags2 |= XFS_DIFLAG2_REFLINK;
876 xfs_trans_log_inode(tp, src, XFS_ILOG_CORE);
877 xfs_ifork_init_cow(src);
878 } else
879 xfs_iunlock(src, XFS_ILOCK_EXCL);
880
881 if (src->i_ino == dest->i_ino)
882 goto commit_flags;
883
884 if (!xfs_is_reflink_inode(dest)) {
885 trace_xfs_reflink_set_inode_flag(dest);
886 xfs_trans_ijoin(tp, dest, XFS_ILOCK_EXCL);
887 dest->i_d.di_flags2 |= XFS_DIFLAG2_REFLINK;
888 xfs_trans_log_inode(tp, dest, XFS_ILOG_CORE);
889 xfs_ifork_init_cow(dest);
890 } else
891 xfs_iunlock(dest, XFS_ILOCK_EXCL);
892
893commit_flags:
894 error = xfs_trans_commit(tp);
895 if (error)
896 goto out_error;
897 return error;
898
899out_error:
900 trace_xfs_reflink_set_inode_flag_error(dest, error, _RET_IP_);
901 return error;
902}
903
904/*
f7ca3522 905 * Update destination inode size & cowextsize hint, if necessary.
862bb360
DW
906 */
907STATIC int
908xfs_reflink_update_dest(
909 struct xfs_inode *dest,
f7ca3522
DW
910 xfs_off_t newlen,
911 xfs_extlen_t cowextsize)
862bb360
DW
912{
913 struct xfs_mount *mp = dest->i_mount;
914 struct xfs_trans *tp;
915 int error;
916
f7ca3522 917 if (newlen <= i_size_read(VFS_I(dest)) && cowextsize == 0)
862bb360
DW
918 return 0;
919
920 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);
921 if (error)
922 goto out_error;
923
924 xfs_ilock(dest, XFS_ILOCK_EXCL);
925 xfs_trans_ijoin(tp, dest, XFS_ILOCK_EXCL);
926
f7ca3522
DW
927 if (newlen > i_size_read(VFS_I(dest))) {
928 trace_xfs_reflink_update_inode_size(dest, newlen);
929 i_size_write(VFS_I(dest), newlen);
930 dest->i_d.di_size = newlen;
931 }
932
933 if (cowextsize) {
934 dest->i_d.di_cowextsize = cowextsize;
935 dest->i_d.di_flags2 |= XFS_DIFLAG2_COWEXTSIZE;
936 }
937
862bb360
DW
938 xfs_trans_log_inode(tp, dest, XFS_ILOG_CORE);
939
940 error = xfs_trans_commit(tp);
941 if (error)
942 goto out_error;
943 return error;
944
945out_error:
946 trace_xfs_reflink_update_inode_size_error(dest, error, _RET_IP_);
947 return error;
948}
949
6fa164b8
DW
950/*
951 * Do we have enough reserve in this AG to handle a reflink? The refcount
952 * btree already reserved all the space it needs, but the rmap btree can grow
953 * infinitely, so we won't allow more reflinks when the AG is down to the
954 * btree reserves.
955 */
956static int
957xfs_reflink_ag_has_free_space(
958 struct xfs_mount *mp,
959 xfs_agnumber_t agno)
960{
961 struct xfs_perag *pag;
962 int error = 0;
963
964 if (!xfs_sb_version_hasrmapbt(&mp->m_sb))
965 return 0;
966
967 pag = xfs_perag_get(mp, agno);
968 if (xfs_ag_resv_critical(pag, XFS_AG_RESV_AGFL) ||
969 xfs_ag_resv_critical(pag, XFS_AG_RESV_METADATA))
970 error = -ENOSPC;
971 xfs_perag_put(pag);
972 return error;
973}
974
862bb360
DW
975/*
976 * Unmap a range of blocks from a file, then map other blocks into the hole.
977 * The range to unmap is (destoff : destoff + srcioff + irec->br_blockcount).
978 * The extent irec is mapped into dest at irec->br_startoff.
979 */
980STATIC int
981xfs_reflink_remap_extent(
982 struct xfs_inode *ip,
983 struct xfs_bmbt_irec *irec,
984 xfs_fileoff_t destoff,
985 xfs_off_t new_isize)
986{
987 struct xfs_mount *mp = ip->i_mount;
988 struct xfs_trans *tp;
989 xfs_fsblock_t firstfsb;
990 unsigned int resblks;
991 struct xfs_defer_ops dfops;
992 struct xfs_bmbt_irec uirec;
993 bool real_extent;
994 xfs_filblks_t rlen;
995 xfs_filblks_t unmap_len;
996 xfs_off_t newlen;
997 int error;
998
999 unmap_len = irec->br_startoff + irec->br_blockcount - destoff;
1000 trace_xfs_reflink_punch_range(ip, destoff, unmap_len);
1001
1002 /* Only remap normal extents. */
1003 real_extent = (irec->br_startblock != HOLESTARTBLOCK &&
1004 irec->br_startblock != DELAYSTARTBLOCK &&
1005 !ISUNWRITTEN(irec));
1006
6fa164b8
DW
1007 /* No reflinking if we're low on space */
1008 if (real_extent) {
1009 error = xfs_reflink_ag_has_free_space(mp,
1010 XFS_FSB_TO_AGNO(mp, irec->br_startblock));
1011 if (error)
1012 goto out;
1013 }
1014
862bb360
DW
1015 /* Start a rolling transaction to switch the mappings */
1016 resblks = XFS_EXTENTADD_SPACE_RES(ip->i_mount, XFS_DATA_FORK);
1017 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0, 0, &tp);
1018 if (error)
1019 goto out;
1020
1021 xfs_ilock(ip, XFS_ILOCK_EXCL);
1022 xfs_trans_ijoin(tp, ip, 0);
1023
1024 /* If we're not just clearing space, then do we have enough quota? */
1025 if (real_extent) {
1026 error = xfs_trans_reserve_quota_nblks(tp, ip,
1027 irec->br_blockcount, 0, XFS_QMOPT_RES_REGBLKS);
1028 if (error)
1029 goto out_cancel;
1030 }
1031
1032 trace_xfs_reflink_remap(ip, irec->br_startoff,
1033 irec->br_blockcount, irec->br_startblock);
1034
1035 /* Unmap the old blocks in the data fork. */
1036 rlen = unmap_len;
1037 while (rlen) {
1038 xfs_defer_init(&dfops, &firstfsb);
1039 error = __xfs_bunmapi(tp, ip, destoff, &rlen, 0, 1,
1040 &firstfsb, &dfops);
1041 if (error)
1042 goto out_defer;
1043
1044 /*
1045 * Trim the extent to whatever got unmapped.
1046 * Remember, bunmapi works backwards.
1047 */
1048 uirec.br_startblock = irec->br_startblock + rlen;
1049 uirec.br_startoff = irec->br_startoff + rlen;
1050 uirec.br_blockcount = unmap_len - rlen;
1051 unmap_len = rlen;
1052
1053 /* If this isn't a real mapping, we're done. */
1054 if (!real_extent || uirec.br_blockcount == 0)
1055 goto next_extent;
1056
1057 trace_xfs_reflink_remap(ip, uirec.br_startoff,
1058 uirec.br_blockcount, uirec.br_startblock);
1059
1060 /* Update the refcount tree */
1061 error = xfs_refcount_increase_extent(mp, &dfops, &uirec);
1062 if (error)
1063 goto out_defer;
1064
1065 /* Map the new blocks into the data fork. */
1066 error = xfs_bmap_map_extent(mp, &dfops, ip, &uirec);
1067 if (error)
1068 goto out_defer;
1069
1070 /* Update quota accounting. */
1071 xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT,
1072 uirec.br_blockcount);
1073
1074 /* Update dest isize if needed. */
1075 newlen = XFS_FSB_TO_B(mp,
1076 uirec.br_startoff + uirec.br_blockcount);
1077 newlen = min_t(xfs_off_t, newlen, new_isize);
1078 if (newlen > i_size_read(VFS_I(ip))) {
1079 trace_xfs_reflink_update_inode_size(ip, newlen);
1080 i_size_write(VFS_I(ip), newlen);
1081 ip->i_d.di_size = newlen;
1082 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1083 }
1084
1085next_extent:
1086 /* Process all the deferred stuff. */
1087 error = xfs_defer_finish(&tp, &dfops, ip);
1088 if (error)
1089 goto out_defer;
1090 }
1091
1092 error = xfs_trans_commit(tp);
1093 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1094 if (error)
1095 goto out;
1096 return 0;
1097
1098out_defer:
1099 xfs_defer_cancel(&dfops);
1100out_cancel:
1101 xfs_trans_cancel(tp);
1102 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1103out:
1104 trace_xfs_reflink_remap_extent_error(ip, error, _RET_IP_);
1105 return error;
1106}
1107
1108/*
1109 * Iteratively remap one file's extents (and holes) to another's.
1110 */
1111STATIC int
1112xfs_reflink_remap_blocks(
1113 struct xfs_inode *src,
1114 xfs_fileoff_t srcoff,
1115 struct xfs_inode *dest,
1116 xfs_fileoff_t destoff,
1117 xfs_filblks_t len,
1118 xfs_off_t new_isize)
1119{
1120 struct xfs_bmbt_irec imap;
1121 int nimaps;
1122 int error = 0;
1123 xfs_filblks_t range_len;
1124
1125 /* drange = (destoff, destoff + len); srange = (srcoff, srcoff + len) */
1126 while (len) {
1127 trace_xfs_reflink_remap_blocks_loop(src, srcoff, len,
1128 dest, destoff);
1129 /* Read extent from the source file */
1130 nimaps = 1;
1131 xfs_ilock(src, XFS_ILOCK_EXCL);
1132 error = xfs_bmapi_read(src, srcoff, len, &imap, &nimaps, 0);
1133 xfs_iunlock(src, XFS_ILOCK_EXCL);
1134 if (error)
1135 goto err;
1136 ASSERT(nimaps == 1);
1137
1138 trace_xfs_reflink_remap_imap(src, srcoff, len, XFS_IO_OVERWRITE,
1139 &imap);
1140
1141 /* Translate imap into the destination file. */
1142 range_len = imap.br_startoff + imap.br_blockcount - srcoff;
1143 imap.br_startoff += destoff - srcoff;
1144
1145 /* Clear dest from destoff to the end of imap and map it in. */
1146 error = xfs_reflink_remap_extent(dest, &imap, destoff,
1147 new_isize);
1148 if (error)
1149 goto err;
1150
1151 if (fatal_signal_pending(current)) {
1152 error = -EINTR;
1153 goto err;
1154 }
1155
1156 /* Advance drange/srange */
1157 srcoff += range_len;
1158 destoff += range_len;
1159 len -= range_len;
1160 }
1161
1162 return 0;
1163
1164err:
1165 trace_xfs_reflink_remap_blocks_error(dest, error, _RET_IP_);
1166 return error;
1167}
1168
cc714660
DW
1169/*
1170 * Read a page's worth of file data into the page cache. Return the page
1171 * locked.
1172 */
1173static struct page *
1174xfs_get_page(
1175 struct inode *inode,
1176 xfs_off_t offset)
1177{
1178 struct address_space *mapping;
1179 struct page *page;
1180 pgoff_t n;
1181
1182 n = offset >> PAGE_SHIFT;
1183 mapping = inode->i_mapping;
1184 page = read_mapping_page(mapping, n, NULL);
1185 if (IS_ERR(page))
1186 return page;
1187 if (!PageUptodate(page)) {
1188 put_page(page);
1189 return ERR_PTR(-EIO);
1190 }
1191 lock_page(page);
1192 return page;
1193}
1194
1195/*
1196 * Compare extents of two files to see if they are the same.
1197 */
1198static int
1199xfs_compare_extents(
1200 struct inode *src,
1201 xfs_off_t srcoff,
1202 struct inode *dest,
1203 xfs_off_t destoff,
1204 xfs_off_t len,
1205 bool *is_same)
1206{
1207 xfs_off_t src_poff;
1208 xfs_off_t dest_poff;
1209 void *src_addr;
1210 void *dest_addr;
1211 struct page *src_page;
1212 struct page *dest_page;
1213 xfs_off_t cmp_len;
1214 bool same;
1215 int error;
1216
1217 error = -EINVAL;
1218 same = true;
1219 while (len) {
1220 src_poff = srcoff & (PAGE_SIZE - 1);
1221 dest_poff = destoff & (PAGE_SIZE - 1);
1222 cmp_len = min(PAGE_SIZE - src_poff,
1223 PAGE_SIZE - dest_poff);
1224 cmp_len = min(cmp_len, len);
1225 ASSERT(cmp_len > 0);
1226
1227 trace_xfs_reflink_compare_extents(XFS_I(src), srcoff, cmp_len,
1228 XFS_I(dest), destoff);
1229
1230 src_page = xfs_get_page(src, srcoff);
1231 if (IS_ERR(src_page)) {
1232 error = PTR_ERR(src_page);
1233 goto out_error;
1234 }
1235 dest_page = xfs_get_page(dest, destoff);
1236 if (IS_ERR(dest_page)) {
1237 error = PTR_ERR(dest_page);
1238 unlock_page(src_page);
1239 put_page(src_page);
1240 goto out_error;
1241 }
1242 src_addr = kmap_atomic(src_page);
1243 dest_addr = kmap_atomic(dest_page);
1244
1245 flush_dcache_page(src_page);
1246 flush_dcache_page(dest_page);
1247
1248 if (memcmp(src_addr + src_poff, dest_addr + dest_poff, cmp_len))
1249 same = false;
1250
1251 kunmap_atomic(dest_addr);
1252 kunmap_atomic(src_addr);
1253 unlock_page(dest_page);
1254 unlock_page(src_page);
1255 put_page(dest_page);
1256 put_page(src_page);
1257
1258 if (!same)
1259 break;
1260
1261 srcoff += cmp_len;
1262 destoff += cmp_len;
1263 len -= cmp_len;
1264 }
1265
1266 *is_same = same;
1267 return 0;
1268
1269out_error:
1270 trace_xfs_reflink_compare_extents_error(XFS_I(dest), error, _RET_IP_);
1271 return error;
1272}
1273
862bb360
DW
1274/*
1275 * Link a range of blocks from one file to another.
1276 */
1277int
1278xfs_reflink_remap_range(
5faaf4fa
CH
1279 struct file *file_in,
1280 loff_t pos_in,
1281 struct file *file_out,
1282 loff_t pos_out,
1283 u64 len,
1284 bool is_dedupe)
862bb360 1285{
5faaf4fa
CH
1286 struct inode *inode_in = file_inode(file_in);
1287 struct xfs_inode *src = XFS_I(inode_in);
1288 struct inode *inode_out = file_inode(file_out);
1289 struct xfs_inode *dest = XFS_I(inode_out);
862bb360 1290 struct xfs_mount *mp = src->i_mount;
5faaf4fa
CH
1291 loff_t bs = inode_out->i_sb->s_blocksize;
1292 bool same_inode = (inode_in == inode_out);
862bb360
DW
1293 xfs_fileoff_t sfsbno, dfsbno;
1294 xfs_filblks_t fsblen;
f7ca3522 1295 xfs_extlen_t cowextsize;
5faaf4fa
CH
1296 loff_t isize;
1297 ssize_t ret;
1298 loff_t blen;
862bb360
DW
1299
1300 if (!xfs_sb_version_hasreflink(&mp->m_sb))
1301 return -EOPNOTSUPP;
1302
1303 if (XFS_FORCED_SHUTDOWN(mp))
1304 return -EIO;
1305
5faaf4fa
CH
1306 /* Lock both files against IO */
1307 if (same_inode) {
1308 xfs_ilock(src, XFS_IOLOCK_EXCL);
1309 xfs_ilock(src, XFS_MMAPLOCK_EXCL);
1310 } else {
1311 xfs_lock_two_inodes(src, dest, XFS_IOLOCK_EXCL);
1312 xfs_lock_two_inodes(src, dest, XFS_MMAPLOCK_EXCL);
1313 }
1314
1315 /* Don't touch certain kinds of inodes */
1316 ret = -EPERM;
1317 if (IS_IMMUTABLE(inode_out))
1318 goto out_unlock;
1319
1320 ret = -ETXTBSY;
1321 if (IS_SWAPFILE(inode_in) || IS_SWAPFILE(inode_out))
1322 goto out_unlock;
1323
1324
1325 /* Don't reflink dirs, pipes, sockets... */
1326 ret = -EISDIR;
1327 if (S_ISDIR(inode_in->i_mode) || S_ISDIR(inode_out->i_mode))
1328 goto out_unlock;
1329 ret = -EINVAL;
1330 if (S_ISFIFO(inode_in->i_mode) || S_ISFIFO(inode_out->i_mode))
1331 goto out_unlock;
1332 if (!S_ISREG(inode_in->i_mode) || !S_ISREG(inode_out->i_mode))
1333 goto out_unlock;
1334
862bb360
DW
1335 /* Don't reflink realtime inodes */
1336 if (XFS_IS_REALTIME_INODE(src) || XFS_IS_REALTIME_INODE(dest))
5faaf4fa
CH
1337 goto out_unlock;
1338
1339 /* Don't share DAX file data for now. */
1340 if (IS_DAX(inode_in) || IS_DAX(inode_out))
1341 goto out_unlock;
1342
1343 /* Are we going all the way to the end? */
1344 isize = i_size_read(inode_in);
1345 if (isize == 0) {
1346 ret = 0;
1347 goto out_unlock;
1348 }
1349
1350 if (len == 0)
1351 len = isize - pos_in;
1352
1353 /* Ensure offsets don't wrap and the input is inside i_size */
1354 if (pos_in + len < pos_in || pos_out + len < pos_out ||
1355 pos_in + len > isize)
1356 goto out_unlock;
862bb360 1357
5faaf4fa
CH
1358 /* Don't allow dedupe past EOF in the dest file */
1359 if (is_dedupe) {
1360 loff_t disize;
cc714660 1361
5faaf4fa
CH
1362 disize = i_size_read(inode_out);
1363 if (pos_out >= disize || pos_out + len > disize)
1364 goto out_unlock;
1365 }
1366
1367 /* If we're linking to EOF, continue to the block boundary. */
1368 if (pos_in + len == isize)
1369 blen = ALIGN(isize, bs) - pos_in;
1370 else
1371 blen = len;
1372
1373 /* Only reflink if we're aligned to block boundaries */
1374 if (!IS_ALIGNED(pos_in, bs) || !IS_ALIGNED(pos_in + blen, bs) ||
1375 !IS_ALIGNED(pos_out, bs) || !IS_ALIGNED(pos_out + blen, bs))
1376 goto out_unlock;
1377
1378 /* Don't allow overlapped reflink within the same file */
1379 if (same_inode) {
1380 if (pos_out + blen > pos_in && pos_out < pos_in + blen)
1381 goto out_unlock;
1382 }
1383
1384 /* Wait for the completion of any pending IOs on both files */
1385 inode_dio_wait(inode_in);
1386 if (!same_inode)
1387 inode_dio_wait(inode_out);
1388
1389 ret = filemap_write_and_wait_range(inode_in->i_mapping,
1390 pos_in, pos_in + len - 1);
1391 if (ret)
1392 goto out_unlock;
1393
1394 ret = filemap_write_and_wait_range(inode_out->i_mapping,
1395 pos_out, pos_out + len - 1);
1396 if (ret)
1397 goto out_unlock;
1398
1399 trace_xfs_reflink_remap_range(src, pos_in, len, dest, pos_out);
862bb360 1400
cc714660
DW
1401 /*
1402 * Check that the extents are the same.
1403 */
5faaf4fa
CH
1404 if (is_dedupe) {
1405 bool is_same = false;
1406
1407 ret = xfs_compare_extents(inode_in, pos_in, inode_out, pos_out,
1408 len, &is_same);
1409 if (ret)
1410 goto out_unlock;
cc714660 1411 if (!is_same) {
5faaf4fa
CH
1412 ret = -EBADE;
1413 goto out_unlock;
cc714660
DW
1414 }
1415 }
1416
5faaf4fa
CH
1417 ret = xfs_reflink_set_inode_flag(src, dest);
1418 if (ret)
1419 goto out_unlock;
862bb360
DW
1420
1421 /*
1422 * Invalidate the page cache so that we can clear any CoW mappings
1423 * in the destination file.
1424 */
5faaf4fa
CH
1425 truncate_inode_pages_range(&inode_out->i_data, pos_out,
1426 PAGE_ALIGN(pos_out + len) - 1);
862bb360 1427
5faaf4fa
CH
1428 dfsbno = XFS_B_TO_FSBT(mp, pos_out);
1429 sfsbno = XFS_B_TO_FSBT(mp, pos_in);
862bb360 1430 fsblen = XFS_B_TO_FSB(mp, len);
5faaf4fa
CH
1431 ret = xfs_reflink_remap_blocks(src, sfsbno, dest, dfsbno, fsblen,
1432 pos_out + len);
1433 if (ret)
1434 goto out_unlock;
862bb360 1435
f7ca3522
DW
1436 /*
1437 * Carry the cowextsize hint from src to dest if we're sharing the
1438 * entire source file to the entire destination file, the source file
1439 * has a cowextsize hint, and the destination file does not.
1440 */
1441 cowextsize = 0;
5faaf4fa 1442 if (pos_in == 0 && len == i_size_read(inode_in) &&
f7ca3522 1443 (src->i_d.di_flags2 & XFS_DIFLAG2_COWEXTSIZE) &&
5faaf4fa 1444 pos_out == 0 && len >= i_size_read(inode_out) &&
f7ca3522
DW
1445 !(dest->i_d.di_flags2 & XFS_DIFLAG2_COWEXTSIZE))
1446 cowextsize = src->i_d.di_cowextsize;
1447
5faaf4fa 1448 ret = xfs_reflink_update_dest(dest, pos_out + len, cowextsize);
862bb360 1449
5faaf4fa
CH
1450out_unlock:
1451 xfs_iunlock(src, XFS_MMAPLOCK_EXCL);
1452 xfs_iunlock(src, XFS_IOLOCK_EXCL);
1453 if (src->i_ino != dest->i_ino) {
1454 xfs_iunlock(dest, XFS_MMAPLOCK_EXCL);
1455 xfs_iunlock(dest, XFS_IOLOCK_EXCL);
1456 }
1457 if (ret)
1458 trace_xfs_reflink_remap_range_error(dest, ret, _RET_IP_);
1459 return ret;
862bb360 1460}
98cc2db5
DW
1461
1462/*
1463 * The user wants to preemptively CoW all shared blocks in this file,
1464 * which enables us to turn off the reflink flag. Iterate all
1465 * extents which are not prealloc/delalloc to see which ranges are
1466 * mentioned in the refcount tree, then read those blocks into the
1467 * pagecache, dirty them, fsync them back out, and then we can update
1468 * the inode flag. What happens if we run out of memory? :)
1469 */
1470STATIC int
1471xfs_reflink_dirty_extents(
1472 struct xfs_inode *ip,
1473 xfs_fileoff_t fbno,
1474 xfs_filblks_t end,
1475 xfs_off_t isize)
1476{
1477 struct xfs_mount *mp = ip->i_mount;
1478 xfs_agnumber_t agno;
1479 xfs_agblock_t agbno;
1480 xfs_extlen_t aglen;
1481 xfs_agblock_t rbno;
1482 xfs_extlen_t rlen;
1483 xfs_off_t fpos;
1484 xfs_off_t flen;
1485 struct xfs_bmbt_irec map[2];
1486 int nmaps;
9780643c 1487 int error = 0;
98cc2db5
DW
1488
1489 while (end - fbno > 0) {
1490 nmaps = 1;
1491 /*
1492 * Look for extents in the file. Skip holes, delalloc, or
1493 * unwritten extents; they can't be reflinked.
1494 */
1495 error = xfs_bmapi_read(ip, fbno, end - fbno, map, &nmaps, 0);
1496 if (error)
1497 goto out;
1498 if (nmaps == 0)
1499 break;
1500 if (map[0].br_startblock == HOLESTARTBLOCK ||
1501 map[0].br_startblock == DELAYSTARTBLOCK ||
1502 ISUNWRITTEN(&map[0]))
1503 goto next;
1504
1505 map[1] = map[0];
1506 while (map[1].br_blockcount) {
1507 agno = XFS_FSB_TO_AGNO(mp, map[1].br_startblock);
1508 agbno = XFS_FSB_TO_AGBNO(mp, map[1].br_startblock);
1509 aglen = map[1].br_blockcount;
1510
1511 error = xfs_reflink_find_shared(mp, agno, agbno, aglen,
1512 &rbno, &rlen, true);
1513 if (error)
1514 goto out;
1515 if (rbno == NULLAGBLOCK)
1516 break;
1517
1518 /* Dirty the pages */
1519 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1520 fpos = XFS_FSB_TO_B(mp, map[1].br_startoff +
1521 (rbno - agbno));
1522 flen = XFS_FSB_TO_B(mp, rlen);
1523 if (fpos + flen > isize)
1524 flen = isize - fpos;
1525 error = iomap_file_dirty(VFS_I(ip), fpos, flen,
1526 &xfs_iomap_ops);
1527 xfs_ilock(ip, XFS_ILOCK_EXCL);
1528 if (error)
1529 goto out;
1530
1531 map[1].br_blockcount -= (rbno - agbno + rlen);
1532 map[1].br_startoff += (rbno - agbno + rlen);
1533 map[1].br_startblock += (rbno - agbno + rlen);
1534 }
1535
1536next:
1537 fbno = map[0].br_startoff + map[0].br_blockcount;
1538 }
1539out:
1540 return error;
1541}
1542
1543/* Clear the inode reflink flag if there are no shared extents. */
1544int
1545xfs_reflink_clear_inode_flag(
1546 struct xfs_inode *ip,
1547 struct xfs_trans **tpp)
1548{
1549 struct xfs_mount *mp = ip->i_mount;
1550 xfs_fileoff_t fbno;
1551 xfs_filblks_t end;
1552 xfs_agnumber_t agno;
1553 xfs_agblock_t agbno;
1554 xfs_extlen_t aglen;
1555 xfs_agblock_t rbno;
1556 xfs_extlen_t rlen;
024adf48 1557 struct xfs_bmbt_irec map;
98cc2db5
DW
1558 int nmaps;
1559 int error = 0;
1560
63646fc5 1561 ASSERT(xfs_is_reflink_inode(ip));
98cc2db5
DW
1562
1563 fbno = 0;
1564 end = XFS_B_TO_FSB(mp, i_size_read(VFS_I(ip)));
1565 while (end - fbno > 0) {
1566 nmaps = 1;
1567 /*
1568 * Look for extents in the file. Skip holes, delalloc, or
1569 * unwritten extents; they can't be reflinked.
1570 */
024adf48 1571 error = xfs_bmapi_read(ip, fbno, end - fbno, &map, &nmaps, 0);
98cc2db5
DW
1572 if (error)
1573 return error;
1574 if (nmaps == 0)
1575 break;
024adf48
DW
1576 if (map.br_startblock == HOLESTARTBLOCK ||
1577 map.br_startblock == DELAYSTARTBLOCK ||
1578 ISUNWRITTEN(&map))
98cc2db5
DW
1579 goto next;
1580
024adf48
DW
1581 agno = XFS_FSB_TO_AGNO(mp, map.br_startblock);
1582 agbno = XFS_FSB_TO_AGBNO(mp, map.br_startblock);
1583 aglen = map.br_blockcount;
98cc2db5 1584
024adf48
DW
1585 error = xfs_reflink_find_shared(mp, agno, agbno, aglen,
1586 &rbno, &rlen, false);
1587 if (error)
1588 return error;
1589 /* Is there still a shared block here? */
1590 if (rbno != NULLAGBLOCK)
1591 return 0;
98cc2db5 1592next:
024adf48 1593 fbno = map.br_startoff + map.br_blockcount;
98cc2db5
DW
1594 }
1595
1596 /*
1597 * We didn't find any shared blocks so turn off the reflink flag.
1598 * First, get rid of any leftover CoW mappings.
1599 */
1600 error = xfs_reflink_cancel_cow_blocks(ip, tpp, 0, NULLFILEOFF);
1601 if (error)
1602 return error;
1603
1604 /* Clear the inode flag. */
1605 trace_xfs_reflink_unset_inode_flag(ip);
1606 ip->i_d.di_flags2 &= ~XFS_DIFLAG2_REFLINK;
83104d44 1607 xfs_inode_clear_cowblocks_tag(ip);
98cc2db5
DW
1608 xfs_trans_ijoin(*tpp, ip, 0);
1609 xfs_trans_log_inode(*tpp, ip, XFS_ILOG_CORE);
1610
1611 return error;
1612}
1613
1614/*
1615 * Clear the inode reflink flag if there are no shared extents and the size
1616 * hasn't changed.
1617 */
1618STATIC int
1619xfs_reflink_try_clear_inode_flag(
97a1b87e 1620 struct xfs_inode *ip)
98cc2db5
DW
1621{
1622 struct xfs_mount *mp = ip->i_mount;
1623 struct xfs_trans *tp;
1624 int error = 0;
1625
1626 /* Start a rolling transaction to remove the mappings */
1627 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0, 0, &tp);
1628 if (error)
1629 return error;
1630
1631 xfs_ilock(ip, XFS_ILOCK_EXCL);
1632 xfs_trans_ijoin(tp, ip, 0);
1633
98cc2db5
DW
1634 error = xfs_reflink_clear_inode_flag(ip, &tp);
1635 if (error)
1636 goto cancel;
1637
1638 error = xfs_trans_commit(tp);
1639 if (error)
1640 goto out;
1641
1642 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1643 return 0;
1644cancel:
1645 xfs_trans_cancel(tp);
1646out:
1647 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1648 return error;
1649}
1650
1651/*
1652 * Pre-COW all shared blocks within a given byte range of a file and turn off
1653 * the reflink flag if we unshare all of the file's blocks.
1654 */
1655int
1656xfs_reflink_unshare(
1657 struct xfs_inode *ip,
1658 xfs_off_t offset,
1659 xfs_off_t len)
1660{
1661 struct xfs_mount *mp = ip->i_mount;
1662 xfs_fileoff_t fbno;
1663 xfs_filblks_t end;
1664 xfs_off_t isize;
1665 int error;
1666
1667 if (!xfs_is_reflink_inode(ip))
1668 return 0;
1669
1670 trace_xfs_reflink_unshare(ip, offset, len);
1671
1672 inode_dio_wait(VFS_I(ip));
1673
1674 /* Try to CoW the selected ranges */
1675 xfs_ilock(ip, XFS_ILOCK_EXCL);
97a1b87e 1676 fbno = XFS_B_TO_FSBT(mp, offset);
98cc2db5
DW
1677 isize = i_size_read(VFS_I(ip));
1678 end = XFS_B_TO_FSB(mp, offset + len);
1679 error = xfs_reflink_dirty_extents(ip, fbno, end, isize);
1680 if (error)
1681 goto out_unlock;
1682 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1683
1684 /* Wait for the IO to finish */
1685 error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
1686 if (error)
1687 goto out;
1688
97a1b87e
DW
1689 /* Turn off the reflink flag if possible. */
1690 error = xfs_reflink_try_clear_inode_flag(ip);
1691 if (error)
1692 goto out;
98cc2db5
DW
1693
1694 return 0;
1695
1696out_unlock:
1697 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1698out:
1699 trace_xfs_reflink_unshare_error(ip, error, _RET_IP_);
1700 return error;
1701}