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