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