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