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