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