xfs: validate btree records on retrieval
[platform/kernel/linux-rpi.git] / fs / xfs / libxfs / xfs_refcount.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_sb.h"
27 #include "xfs_mount.h"
28 #include "xfs_defer.h"
29 #include "xfs_btree.h"
30 #include "xfs_bmap.h"
31 #include "xfs_refcount_btree.h"
32 #include "xfs_alloc.h"
33 #include "xfs_errortag.h"
34 #include "xfs_error.h"
35 #include "xfs_trace.h"
36 #include "xfs_cksum.h"
37 #include "xfs_trans.h"
38 #include "xfs_bit.h"
39 #include "xfs_refcount.h"
40 #include "xfs_rmap.h"
41
42 /* Allowable refcount adjustment amounts. */
43 enum xfs_refc_adjust_op {
44         XFS_REFCOUNT_ADJUST_INCREASE    = 1,
45         XFS_REFCOUNT_ADJUST_DECREASE    = -1,
46         XFS_REFCOUNT_ADJUST_COW_ALLOC   = 0,
47         XFS_REFCOUNT_ADJUST_COW_FREE    = -1,
48 };
49
50 STATIC int __xfs_refcount_cow_alloc(struct xfs_btree_cur *rcur,
51                 xfs_agblock_t agbno, xfs_extlen_t aglen,
52                 struct xfs_defer_ops *dfops);
53 STATIC int __xfs_refcount_cow_free(struct xfs_btree_cur *rcur,
54                 xfs_agblock_t agbno, xfs_extlen_t aglen,
55                 struct xfs_defer_ops *dfops);
56
57 /*
58  * Look up the first record less than or equal to [bno, len] in the btree
59  * given by cur.
60  */
61 int
62 xfs_refcount_lookup_le(
63         struct xfs_btree_cur    *cur,
64         xfs_agblock_t           bno,
65         int                     *stat)
66 {
67         trace_xfs_refcount_lookup(cur->bc_mp, cur->bc_private.a.agno, bno,
68                         XFS_LOOKUP_LE);
69         cur->bc_rec.rc.rc_startblock = bno;
70         cur->bc_rec.rc.rc_blockcount = 0;
71         return xfs_btree_lookup(cur, XFS_LOOKUP_LE, stat);
72 }
73
74 /*
75  * Look up the first record greater than or equal to [bno, len] in the btree
76  * given by cur.
77  */
78 int
79 xfs_refcount_lookup_ge(
80         struct xfs_btree_cur    *cur,
81         xfs_agblock_t           bno,
82         int                     *stat)
83 {
84         trace_xfs_refcount_lookup(cur->bc_mp, cur->bc_private.a.agno, bno,
85                         XFS_LOOKUP_GE);
86         cur->bc_rec.rc.rc_startblock = bno;
87         cur->bc_rec.rc.rc_blockcount = 0;
88         return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
89 }
90
91 /*
92  * Look up the first record equal to [bno, len] in the btree
93  * given by cur.
94  */
95 int
96 xfs_refcount_lookup_eq(
97         struct xfs_btree_cur    *cur,
98         xfs_agblock_t           bno,
99         int                     *stat)
100 {
101         trace_xfs_refcount_lookup(cur->bc_mp, cur->bc_private.a.agno, bno,
102                         XFS_LOOKUP_LE);
103         cur->bc_rec.rc.rc_startblock = bno;
104         cur->bc_rec.rc.rc_blockcount = 0;
105         return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
106 }
107
108 /* Convert on-disk record to in-core format. */
109 void
110 xfs_refcount_btrec_to_irec(
111         union xfs_btree_rec             *rec,
112         struct xfs_refcount_irec        *irec)
113 {
114         irec->rc_startblock = be32_to_cpu(rec->refc.rc_startblock);
115         irec->rc_blockcount = be32_to_cpu(rec->refc.rc_blockcount);
116         irec->rc_refcount = be32_to_cpu(rec->refc.rc_refcount);
117 }
118
119 /*
120  * Get the data from the pointed-to record.
121  */
122 int
123 xfs_refcount_get_rec(
124         struct xfs_btree_cur            *cur,
125         struct xfs_refcount_irec        *irec,
126         int                             *stat)
127 {
128         struct xfs_mount                *mp = cur->bc_mp;
129         xfs_agnumber_t                  agno = cur->bc_private.a.agno;
130         union xfs_btree_rec             *rec;
131         int                             error;
132         xfs_agblock_t                   realstart;
133
134         error = xfs_btree_get_rec(cur, &rec, stat);
135         if (error || !*stat)
136                 return error;
137
138         xfs_refcount_btrec_to_irec(rec, irec);
139
140         agno = cur->bc_private.a.agno;
141         if (irec->rc_blockcount == 0 || irec->rc_blockcount > MAXREFCEXTLEN)
142                 goto out_bad_rec;
143
144         /* handle special COW-staging state */
145         realstart = irec->rc_startblock;
146         if (realstart & XFS_REFC_COW_START) {
147                 if (irec->rc_refcount != 1)
148                         goto out_bad_rec;
149                 realstart &= ~XFS_REFC_COW_START;
150         } else if (irec->rc_refcount < 2) {
151                 goto out_bad_rec;
152         }
153
154         /* check for valid extent range, including overflow */
155         if (!xfs_verify_agbno(mp, agno, realstart))
156                 goto out_bad_rec;
157         if (realstart > realstart + irec->rc_blockcount)
158                 goto out_bad_rec;
159         if (!xfs_verify_agbno(mp, agno, realstart + irec->rc_blockcount - 1))
160                 goto out_bad_rec;
161
162         if (irec->rc_refcount == 0 || irec->rc_refcount > MAXREFCOUNT)
163                 goto out_bad_rec;
164
165         trace_xfs_refcount_get(cur->bc_mp, cur->bc_private.a.agno, irec);
166         return 0;
167
168 out_bad_rec:
169         xfs_warn(mp,
170                 "Refcount BTree record corruption in AG %d detected!", agno);
171         xfs_warn(mp,
172                 "Start block 0x%x, block count 0x%x, references 0x%x",
173                 irec->rc_startblock, irec->rc_blockcount, irec->rc_refcount);
174         return -EFSCORRUPTED;
175 }
176
177 /*
178  * Update the record referred to by cur to the value given
179  * by [bno, len, refcount].
180  * This either works (return 0) or gets an EFSCORRUPTED error.
181  */
182 STATIC int
183 xfs_refcount_update(
184         struct xfs_btree_cur            *cur,
185         struct xfs_refcount_irec        *irec)
186 {
187         union xfs_btree_rec     rec;
188         int                     error;
189
190         trace_xfs_refcount_update(cur->bc_mp, cur->bc_private.a.agno, irec);
191         rec.refc.rc_startblock = cpu_to_be32(irec->rc_startblock);
192         rec.refc.rc_blockcount = cpu_to_be32(irec->rc_blockcount);
193         rec.refc.rc_refcount = cpu_to_be32(irec->rc_refcount);
194         error = xfs_btree_update(cur, &rec);
195         if (error)
196                 trace_xfs_refcount_update_error(cur->bc_mp,
197                                 cur->bc_private.a.agno, error, _RET_IP_);
198         return error;
199 }
200
201 /*
202  * Insert the record referred to by cur to the value given
203  * by [bno, len, refcount].
204  * This either works (return 0) or gets an EFSCORRUPTED error.
205  */
206 int
207 xfs_refcount_insert(
208         struct xfs_btree_cur            *cur,
209         struct xfs_refcount_irec        *irec,
210         int                             *i)
211 {
212         int                             error;
213
214         trace_xfs_refcount_insert(cur->bc_mp, cur->bc_private.a.agno, irec);
215         cur->bc_rec.rc.rc_startblock = irec->rc_startblock;
216         cur->bc_rec.rc.rc_blockcount = irec->rc_blockcount;
217         cur->bc_rec.rc.rc_refcount = irec->rc_refcount;
218         error = xfs_btree_insert(cur, i);
219         if (error)
220                 goto out_error;
221         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, *i == 1, out_error);
222
223 out_error:
224         if (error)
225                 trace_xfs_refcount_insert_error(cur->bc_mp,
226                                 cur->bc_private.a.agno, error, _RET_IP_);
227         return error;
228 }
229
230 /*
231  * Remove the record referred to by cur, then set the pointer to the spot
232  * where the record could be re-inserted, in case we want to increment or
233  * decrement the cursor.
234  * This either works (return 0) or gets an EFSCORRUPTED error.
235  */
236 STATIC int
237 xfs_refcount_delete(
238         struct xfs_btree_cur    *cur,
239         int                     *i)
240 {
241         struct xfs_refcount_irec        irec;
242         int                     found_rec;
243         int                     error;
244
245         error = xfs_refcount_get_rec(cur, &irec, &found_rec);
246         if (error)
247                 goto out_error;
248         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
249         trace_xfs_refcount_delete(cur->bc_mp, cur->bc_private.a.agno, &irec);
250         error = xfs_btree_delete(cur, i);
251         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, *i == 1, out_error);
252         if (error)
253                 goto out_error;
254         error = xfs_refcount_lookup_ge(cur, irec.rc_startblock, &found_rec);
255 out_error:
256         if (error)
257                 trace_xfs_refcount_delete_error(cur->bc_mp,
258                                 cur->bc_private.a.agno, error, _RET_IP_);
259         return error;
260 }
261
262 /*
263  * Adjusting the Reference Count
264  *
265  * As stated elsewhere, the reference count btree (refcbt) stores
266  * >1 reference counts for extents of physical blocks.  In this
267  * operation, we're either raising or lowering the reference count of
268  * some subrange stored in the tree:
269  *
270  *      <------ adjustment range ------>
271  * ----+   +---+-----+ +--+--------+---------
272  *  2  |   | 3 |  4  | |17|   55   |   10
273  * ----+   +---+-----+ +--+--------+---------
274  * X axis is physical blocks number;
275  * reference counts are the numbers inside the rectangles
276  *
277  * The first thing we need to do is to ensure that there are no
278  * refcount extents crossing either boundary of the range to be
279  * adjusted.  For any extent that does cross a boundary, split it into
280  * two extents so that we can increment the refcount of one of the
281  * pieces later:
282  *
283  *      <------ adjustment range ------>
284  * ----+   +---+-----+ +--+--------+----+----
285  *  2  |   | 3 |  2  | |17|   55   | 10 | 10
286  * ----+   +---+-----+ +--+--------+----+----
287  *
288  * For this next step, let's assume that all the physical blocks in
289  * the adjustment range are mapped to a file and are therefore in use
290  * at least once.  Therefore, we can infer that any gap in the
291  * refcount tree within the adjustment range represents a physical
292  * extent with refcount == 1:
293  *
294  *      <------ adjustment range ------>
295  * ----+---+---+-----+-+--+--------+----+----
296  *  2  |"1"| 3 |  2  |1|17|   55   | 10 | 10
297  * ----+---+---+-----+-+--+--------+----+----
298  *      ^
299  *
300  * For each extent that falls within the interval range, figure out
301  * which extent is to the left or the right of that extent.  Now we
302  * have a left, current, and right extent.  If the new reference count
303  * of the center extent enables us to merge left, center, and right
304  * into one record covering all three, do so.  If the center extent is
305  * at the left end of the range, abuts the left extent, and its new
306  * reference count matches the left extent's record, then merge them.
307  * If the center extent is at the right end of the range, abuts the
308  * right extent, and the reference counts match, merge those.  In the
309  * example, we can left merge (assuming an increment operation):
310  *
311  *      <------ adjustment range ------>
312  * --------+---+-----+-+--+--------+----+----
313  *    2    | 3 |  2  |1|17|   55   | 10 | 10
314  * --------+---+-----+-+--+--------+----+----
315  *          ^
316  *
317  * For all other extents within the range, adjust the reference count
318  * or delete it if the refcount falls below 2.  If we were
319  * incrementing, the end result looks like this:
320  *
321  *      <------ adjustment range ------>
322  * --------+---+-----+-+--+--------+----+----
323  *    2    | 4 |  3  |2|18|   56   | 11 | 10
324  * --------+---+-----+-+--+--------+----+----
325  *
326  * The result of a decrement operation looks as such:
327  *
328  *      <------ adjustment range ------>
329  * ----+   +---+       +--+--------+----+----
330  *  2  |   | 2 |       |16|   54   |  9 | 10
331  * ----+   +---+       +--+--------+----+----
332  *      DDDD    111111DD
333  *
334  * The blocks marked "D" are freed; the blocks marked "1" are only
335  * referenced once and therefore the record is removed from the
336  * refcount btree.
337  */
338
339 /* Next block after this extent. */
340 static inline xfs_agblock_t
341 xfs_refc_next(
342         struct xfs_refcount_irec        *rc)
343 {
344         return rc->rc_startblock + rc->rc_blockcount;
345 }
346
347 /*
348  * Split a refcount extent that crosses agbno.
349  */
350 STATIC int
351 xfs_refcount_split_extent(
352         struct xfs_btree_cur            *cur,
353         xfs_agblock_t                   agbno,
354         bool                            *shape_changed)
355 {
356         struct xfs_refcount_irec        rcext, tmp;
357         int                             found_rec;
358         int                             error;
359
360         *shape_changed = false;
361         error = xfs_refcount_lookup_le(cur, agbno, &found_rec);
362         if (error)
363                 goto out_error;
364         if (!found_rec)
365                 return 0;
366
367         error = xfs_refcount_get_rec(cur, &rcext, &found_rec);
368         if (error)
369                 goto out_error;
370         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
371         if (rcext.rc_startblock == agbno || xfs_refc_next(&rcext) <= agbno)
372                 return 0;
373
374         *shape_changed = true;
375         trace_xfs_refcount_split_extent(cur->bc_mp, cur->bc_private.a.agno,
376                         &rcext, agbno);
377
378         /* Establish the right extent. */
379         tmp = rcext;
380         tmp.rc_startblock = agbno;
381         tmp.rc_blockcount -= (agbno - rcext.rc_startblock);
382         error = xfs_refcount_update(cur, &tmp);
383         if (error)
384                 goto out_error;
385
386         /* Insert the left extent. */
387         tmp = rcext;
388         tmp.rc_blockcount = agbno - rcext.rc_startblock;
389         error = xfs_refcount_insert(cur, &tmp, &found_rec);
390         if (error)
391                 goto out_error;
392         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
393         return error;
394
395 out_error:
396         trace_xfs_refcount_split_extent_error(cur->bc_mp,
397                         cur->bc_private.a.agno, error, _RET_IP_);
398         return error;
399 }
400
401 /*
402  * Merge the left, center, and right extents.
403  */
404 STATIC int
405 xfs_refcount_merge_center_extents(
406         struct xfs_btree_cur            *cur,
407         struct xfs_refcount_irec        *left,
408         struct xfs_refcount_irec        *center,
409         struct xfs_refcount_irec        *right,
410         unsigned long long              extlen,
411         xfs_extlen_t                    *aglen)
412 {
413         int                             error;
414         int                             found_rec;
415
416         trace_xfs_refcount_merge_center_extents(cur->bc_mp,
417                         cur->bc_private.a.agno, left, center, right);
418
419         /*
420          * Make sure the center and right extents are not in the btree.
421          * If the center extent was synthesized, the first delete call
422          * removes the right extent and we skip the second deletion.
423          * If center and right were in the btree, then the first delete
424          * call removes the center and the second one removes the right
425          * extent.
426          */
427         error = xfs_refcount_lookup_ge(cur, center->rc_startblock,
428                         &found_rec);
429         if (error)
430                 goto out_error;
431         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
432
433         error = xfs_refcount_delete(cur, &found_rec);
434         if (error)
435                 goto out_error;
436         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
437
438         if (center->rc_refcount > 1) {
439                 error = xfs_refcount_delete(cur, &found_rec);
440                 if (error)
441                         goto out_error;
442                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1,
443                                 out_error);
444         }
445
446         /* Enlarge the left extent. */
447         error = xfs_refcount_lookup_le(cur, left->rc_startblock,
448                         &found_rec);
449         if (error)
450                 goto out_error;
451         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
452
453         left->rc_blockcount = extlen;
454         error = xfs_refcount_update(cur, left);
455         if (error)
456                 goto out_error;
457
458         *aglen = 0;
459         return error;
460
461 out_error:
462         trace_xfs_refcount_merge_center_extents_error(cur->bc_mp,
463                         cur->bc_private.a.agno, error, _RET_IP_);
464         return error;
465 }
466
467 /*
468  * Merge with the left extent.
469  */
470 STATIC int
471 xfs_refcount_merge_left_extent(
472         struct xfs_btree_cur            *cur,
473         struct xfs_refcount_irec        *left,
474         struct xfs_refcount_irec        *cleft,
475         xfs_agblock_t                   *agbno,
476         xfs_extlen_t                    *aglen)
477 {
478         int                             error;
479         int                             found_rec;
480
481         trace_xfs_refcount_merge_left_extent(cur->bc_mp,
482                         cur->bc_private.a.agno, left, cleft);
483
484         /* If the extent at agbno (cleft) wasn't synthesized, remove it. */
485         if (cleft->rc_refcount > 1) {
486                 error = xfs_refcount_lookup_le(cur, cleft->rc_startblock,
487                                 &found_rec);
488                 if (error)
489                         goto out_error;
490                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1,
491                                 out_error);
492
493                 error = xfs_refcount_delete(cur, &found_rec);
494                 if (error)
495                         goto out_error;
496                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1,
497                                 out_error);
498         }
499
500         /* Enlarge the left extent. */
501         error = xfs_refcount_lookup_le(cur, left->rc_startblock,
502                         &found_rec);
503         if (error)
504                 goto out_error;
505         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
506
507         left->rc_blockcount += cleft->rc_blockcount;
508         error = xfs_refcount_update(cur, left);
509         if (error)
510                 goto out_error;
511
512         *agbno += cleft->rc_blockcount;
513         *aglen -= cleft->rc_blockcount;
514         return error;
515
516 out_error:
517         trace_xfs_refcount_merge_left_extent_error(cur->bc_mp,
518                         cur->bc_private.a.agno, error, _RET_IP_);
519         return error;
520 }
521
522 /*
523  * Merge with the right extent.
524  */
525 STATIC int
526 xfs_refcount_merge_right_extent(
527         struct xfs_btree_cur            *cur,
528         struct xfs_refcount_irec        *right,
529         struct xfs_refcount_irec        *cright,
530         xfs_extlen_t                    *aglen)
531 {
532         int                             error;
533         int                             found_rec;
534
535         trace_xfs_refcount_merge_right_extent(cur->bc_mp,
536                         cur->bc_private.a.agno, cright, right);
537
538         /*
539          * If the extent ending at agbno+aglen (cright) wasn't synthesized,
540          * remove it.
541          */
542         if (cright->rc_refcount > 1) {
543                 error = xfs_refcount_lookup_le(cur, cright->rc_startblock,
544                         &found_rec);
545                 if (error)
546                         goto out_error;
547                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1,
548                                 out_error);
549
550                 error = xfs_refcount_delete(cur, &found_rec);
551                 if (error)
552                         goto out_error;
553                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1,
554                                 out_error);
555         }
556
557         /* Enlarge the right extent. */
558         error = xfs_refcount_lookup_le(cur, right->rc_startblock,
559                         &found_rec);
560         if (error)
561                 goto out_error;
562         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
563
564         right->rc_startblock -= cright->rc_blockcount;
565         right->rc_blockcount += cright->rc_blockcount;
566         error = xfs_refcount_update(cur, right);
567         if (error)
568                 goto out_error;
569
570         *aglen -= cright->rc_blockcount;
571         return error;
572
573 out_error:
574         trace_xfs_refcount_merge_right_extent_error(cur->bc_mp,
575                         cur->bc_private.a.agno, error, _RET_IP_);
576         return error;
577 }
578
579 #define XFS_FIND_RCEXT_SHARED   1
580 #define XFS_FIND_RCEXT_COW      2
581 /*
582  * Find the left extent and the one after it (cleft).  This function assumes
583  * that we've already split any extent crossing agbno.
584  */
585 STATIC int
586 xfs_refcount_find_left_extents(
587         struct xfs_btree_cur            *cur,
588         struct xfs_refcount_irec        *left,
589         struct xfs_refcount_irec        *cleft,
590         xfs_agblock_t                   agbno,
591         xfs_extlen_t                    aglen,
592         int                             flags)
593 {
594         struct xfs_refcount_irec        tmp;
595         int                             error;
596         int                             found_rec;
597
598         left->rc_startblock = cleft->rc_startblock = NULLAGBLOCK;
599         error = xfs_refcount_lookup_le(cur, agbno - 1, &found_rec);
600         if (error)
601                 goto out_error;
602         if (!found_rec)
603                 return 0;
604
605         error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
606         if (error)
607                 goto out_error;
608         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
609
610         if (xfs_refc_next(&tmp) != agbno)
611                 return 0;
612         if ((flags & XFS_FIND_RCEXT_SHARED) && tmp.rc_refcount < 2)
613                 return 0;
614         if ((flags & XFS_FIND_RCEXT_COW) && tmp.rc_refcount > 1)
615                 return 0;
616         /* We have a left extent; retrieve (or invent) the next right one */
617         *left = tmp;
618
619         error = xfs_btree_increment(cur, 0, &found_rec);
620         if (error)
621                 goto out_error;
622         if (found_rec) {
623                 error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
624                 if (error)
625                         goto out_error;
626                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1,
627                                 out_error);
628
629                 /* if tmp starts at the end of our range, just use that */
630                 if (tmp.rc_startblock == agbno)
631                         *cleft = tmp;
632                 else {
633                         /*
634                          * There's a gap in the refcntbt at the start of the
635                          * range we're interested in (refcount == 1) so
636                          * synthesize the implied extent and pass it back.
637                          * We assume here that the agbno/aglen range was
638                          * passed in from a data fork extent mapping and
639                          * therefore is allocated to exactly one owner.
640                          */
641                         cleft->rc_startblock = agbno;
642                         cleft->rc_blockcount = min(aglen,
643                                         tmp.rc_startblock - agbno);
644                         cleft->rc_refcount = 1;
645                 }
646         } else {
647                 /*
648                  * No extents, so pretend that there's one covering the whole
649                  * range.
650                  */
651                 cleft->rc_startblock = agbno;
652                 cleft->rc_blockcount = aglen;
653                 cleft->rc_refcount = 1;
654         }
655         trace_xfs_refcount_find_left_extent(cur->bc_mp, cur->bc_private.a.agno,
656                         left, cleft, agbno);
657         return error;
658
659 out_error:
660         trace_xfs_refcount_find_left_extent_error(cur->bc_mp,
661                         cur->bc_private.a.agno, error, _RET_IP_);
662         return error;
663 }
664
665 /*
666  * Find the right extent and the one before it (cright).  This function
667  * assumes that we've already split any extents crossing agbno + aglen.
668  */
669 STATIC int
670 xfs_refcount_find_right_extents(
671         struct xfs_btree_cur            *cur,
672         struct xfs_refcount_irec        *right,
673         struct xfs_refcount_irec        *cright,
674         xfs_agblock_t                   agbno,
675         xfs_extlen_t                    aglen,
676         int                             flags)
677 {
678         struct xfs_refcount_irec        tmp;
679         int                             error;
680         int                             found_rec;
681
682         right->rc_startblock = cright->rc_startblock = NULLAGBLOCK;
683         error = xfs_refcount_lookup_ge(cur, agbno + aglen, &found_rec);
684         if (error)
685                 goto out_error;
686         if (!found_rec)
687                 return 0;
688
689         error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
690         if (error)
691                 goto out_error;
692         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1, out_error);
693
694         if (tmp.rc_startblock != agbno + aglen)
695                 return 0;
696         if ((flags & XFS_FIND_RCEXT_SHARED) && tmp.rc_refcount < 2)
697                 return 0;
698         if ((flags & XFS_FIND_RCEXT_COW) && tmp.rc_refcount > 1)
699                 return 0;
700         /* We have a right extent; retrieve (or invent) the next left one */
701         *right = tmp;
702
703         error = xfs_btree_decrement(cur, 0, &found_rec);
704         if (error)
705                 goto out_error;
706         if (found_rec) {
707                 error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
708                 if (error)
709                         goto out_error;
710                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, found_rec == 1,
711                                 out_error);
712
713                 /* if tmp ends at the end of our range, just use that */
714                 if (xfs_refc_next(&tmp) == agbno + aglen)
715                         *cright = tmp;
716                 else {
717                         /*
718                          * There's a gap in the refcntbt at the end of the
719                          * range we're interested in (refcount == 1) so
720                          * create the implied extent and pass it back.
721                          * We assume here that the agbno/aglen range was
722                          * passed in from a data fork extent mapping and
723                          * therefore is allocated to exactly one owner.
724                          */
725                         cright->rc_startblock = max(agbno, xfs_refc_next(&tmp));
726                         cright->rc_blockcount = right->rc_startblock -
727                                         cright->rc_startblock;
728                         cright->rc_refcount = 1;
729                 }
730         } else {
731                 /*
732                  * No extents, so pretend that there's one covering the whole
733                  * range.
734                  */
735                 cright->rc_startblock = agbno;
736                 cright->rc_blockcount = aglen;
737                 cright->rc_refcount = 1;
738         }
739         trace_xfs_refcount_find_right_extent(cur->bc_mp, cur->bc_private.a.agno,
740                         cright, right, agbno + aglen);
741         return error;
742
743 out_error:
744         trace_xfs_refcount_find_right_extent_error(cur->bc_mp,
745                         cur->bc_private.a.agno, error, _RET_IP_);
746         return error;
747 }
748
749 /* Is this extent valid? */
750 static inline bool
751 xfs_refc_valid(
752         struct xfs_refcount_irec        *rc)
753 {
754         return rc->rc_startblock != NULLAGBLOCK;
755 }
756
757 /*
758  * Try to merge with any extents on the boundaries of the adjustment range.
759  */
760 STATIC int
761 xfs_refcount_merge_extents(
762         struct xfs_btree_cur    *cur,
763         xfs_agblock_t           *agbno,
764         xfs_extlen_t            *aglen,
765         enum xfs_refc_adjust_op adjust,
766         int                     flags,
767         bool                    *shape_changed)
768 {
769         struct xfs_refcount_irec        left = {0}, cleft = {0};
770         struct xfs_refcount_irec        cright = {0}, right = {0};
771         int                             error;
772         unsigned long long              ulen;
773         bool                            cequal;
774
775         *shape_changed = false;
776         /*
777          * Find the extent just below agbno [left], just above agbno [cleft],
778          * just below (agbno + aglen) [cright], and just above (agbno + aglen)
779          * [right].
780          */
781         error = xfs_refcount_find_left_extents(cur, &left, &cleft, *agbno,
782                         *aglen, flags);
783         if (error)
784                 return error;
785         error = xfs_refcount_find_right_extents(cur, &right, &cright, *agbno,
786                         *aglen, flags);
787         if (error)
788                 return error;
789
790         /* No left or right extent to merge; exit. */
791         if (!xfs_refc_valid(&left) && !xfs_refc_valid(&right))
792                 return 0;
793
794         cequal = (cleft.rc_startblock == cright.rc_startblock) &&
795                  (cleft.rc_blockcount == cright.rc_blockcount);
796
797         /* Try to merge left, cleft, and right.  cleft must == cright. */
798         ulen = (unsigned long long)left.rc_blockcount + cleft.rc_blockcount +
799                         right.rc_blockcount;
800         if (xfs_refc_valid(&left) && xfs_refc_valid(&right) &&
801             xfs_refc_valid(&cleft) && xfs_refc_valid(&cright) && cequal &&
802             left.rc_refcount == cleft.rc_refcount + adjust &&
803             right.rc_refcount == cleft.rc_refcount + adjust &&
804             ulen < MAXREFCEXTLEN) {
805                 *shape_changed = true;
806                 return xfs_refcount_merge_center_extents(cur, &left, &cleft,
807                                 &right, ulen, aglen);
808         }
809
810         /* Try to merge left and cleft. */
811         ulen = (unsigned long long)left.rc_blockcount + cleft.rc_blockcount;
812         if (xfs_refc_valid(&left) && xfs_refc_valid(&cleft) &&
813             left.rc_refcount == cleft.rc_refcount + adjust &&
814             ulen < MAXREFCEXTLEN) {
815                 *shape_changed = true;
816                 error = xfs_refcount_merge_left_extent(cur, &left, &cleft,
817                                 agbno, aglen);
818                 if (error)
819                         return error;
820
821                 /*
822                  * If we just merged left + cleft and cleft == cright,
823                  * we no longer have a cright to merge with right.  We're done.
824                  */
825                 if (cequal)
826                         return 0;
827         }
828
829         /* Try to merge cright and right. */
830         ulen = (unsigned long long)right.rc_blockcount + cright.rc_blockcount;
831         if (xfs_refc_valid(&right) && xfs_refc_valid(&cright) &&
832             right.rc_refcount == cright.rc_refcount + adjust &&
833             ulen < MAXREFCEXTLEN) {
834                 *shape_changed = true;
835                 return xfs_refcount_merge_right_extent(cur, &right, &cright,
836                                 aglen);
837         }
838
839         return error;
840 }
841
842 /*
843  * XXX: This is a pretty hand-wavy estimate.  The penalty for guessing
844  * true incorrectly is a shutdown FS; the penalty for guessing false
845  * incorrectly is more transaction rolls than might be necessary.
846  * Be conservative here.
847  */
848 static bool
849 xfs_refcount_still_have_space(
850         struct xfs_btree_cur            *cur)
851 {
852         unsigned long                   overhead;
853
854         overhead = cur->bc_private.a.priv.refc.shape_changes *
855                         xfs_allocfree_log_count(cur->bc_mp, 1);
856         overhead *= cur->bc_mp->m_sb.sb_blocksize;
857
858         /*
859          * Only allow 2 refcount extent updates per transaction if the
860          * refcount continue update "error" has been injected.
861          */
862         if (cur->bc_private.a.priv.refc.nr_ops > 2 &&
863             XFS_TEST_ERROR(false, cur->bc_mp,
864                         XFS_ERRTAG_REFCOUNT_CONTINUE_UPDATE))
865                 return false;
866
867         if (cur->bc_private.a.priv.refc.nr_ops == 0)
868                 return true;
869         else if (overhead > cur->bc_tp->t_log_res)
870                 return false;
871         return  cur->bc_tp->t_log_res - overhead >
872                 cur->bc_private.a.priv.refc.nr_ops * XFS_REFCOUNT_ITEM_OVERHEAD;
873 }
874
875 /*
876  * Adjust the refcounts of middle extents.  At this point we should have
877  * split extents that crossed the adjustment range; merged with adjacent
878  * extents; and updated agbno/aglen to reflect the merges.  Therefore,
879  * all we have to do is update the extents inside [agbno, agbno + aglen].
880  */
881 STATIC int
882 xfs_refcount_adjust_extents(
883         struct xfs_btree_cur    *cur,
884         xfs_agblock_t           *agbno,
885         xfs_extlen_t            *aglen,
886         enum xfs_refc_adjust_op adj,
887         struct xfs_defer_ops    *dfops,
888         struct xfs_owner_info   *oinfo)
889 {
890         struct xfs_refcount_irec        ext, tmp;
891         int                             error;
892         int                             found_rec, found_tmp;
893         xfs_fsblock_t                   fsbno;
894
895         /* Merging did all the work already. */
896         if (*aglen == 0)
897                 return 0;
898
899         error = xfs_refcount_lookup_ge(cur, *agbno, &found_rec);
900         if (error)
901                 goto out_error;
902
903         while (*aglen > 0 && xfs_refcount_still_have_space(cur)) {
904                 error = xfs_refcount_get_rec(cur, &ext, &found_rec);
905                 if (error)
906                         goto out_error;
907                 if (!found_rec) {
908                         ext.rc_startblock = cur->bc_mp->m_sb.sb_agblocks;
909                         ext.rc_blockcount = 0;
910                         ext.rc_refcount = 0;
911                 }
912
913                 /*
914                  * Deal with a hole in the refcount tree; if a file maps to
915                  * these blocks and there's no refcountbt record, pretend that
916                  * there is one with refcount == 1.
917                  */
918                 if (ext.rc_startblock != *agbno) {
919                         tmp.rc_startblock = *agbno;
920                         tmp.rc_blockcount = min(*aglen,
921                                         ext.rc_startblock - *agbno);
922                         tmp.rc_refcount = 1 + adj;
923                         trace_xfs_refcount_modify_extent(cur->bc_mp,
924                                         cur->bc_private.a.agno, &tmp);
925
926                         /*
927                          * Either cover the hole (increment) or
928                          * delete the range (decrement).
929                          */
930                         if (tmp.rc_refcount) {
931                                 error = xfs_refcount_insert(cur, &tmp,
932                                                 &found_tmp);
933                                 if (error)
934                                         goto out_error;
935                                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
936                                                 found_tmp == 1, out_error);
937                                 cur->bc_private.a.priv.refc.nr_ops++;
938                         } else {
939                                 fsbno = XFS_AGB_TO_FSB(cur->bc_mp,
940                                                 cur->bc_private.a.agno,
941                                                 tmp.rc_startblock);
942                                 xfs_bmap_add_free(cur->bc_mp, dfops, fsbno,
943                                                 tmp.rc_blockcount, oinfo);
944                         }
945
946                         (*agbno) += tmp.rc_blockcount;
947                         (*aglen) -= tmp.rc_blockcount;
948
949                         error = xfs_refcount_lookup_ge(cur, *agbno,
950                                         &found_rec);
951                         if (error)
952                                 goto out_error;
953                 }
954
955                 /* Stop if there's nothing left to modify */
956                 if (*aglen == 0 || !xfs_refcount_still_have_space(cur))
957                         break;
958
959                 /*
960                  * Adjust the reference count and either update the tree
961                  * (incr) or free the blocks (decr).
962                  */
963                 if (ext.rc_refcount == MAXREFCOUNT)
964                         goto skip;
965                 ext.rc_refcount += adj;
966                 trace_xfs_refcount_modify_extent(cur->bc_mp,
967                                 cur->bc_private.a.agno, &ext);
968                 if (ext.rc_refcount > 1) {
969                         error = xfs_refcount_update(cur, &ext);
970                         if (error)
971                                 goto out_error;
972                         cur->bc_private.a.priv.refc.nr_ops++;
973                 } else if (ext.rc_refcount == 1) {
974                         error = xfs_refcount_delete(cur, &found_rec);
975                         if (error)
976                                 goto out_error;
977                         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
978                                         found_rec == 1, out_error);
979                         cur->bc_private.a.priv.refc.nr_ops++;
980                         goto advloop;
981                 } else {
982                         fsbno = XFS_AGB_TO_FSB(cur->bc_mp,
983                                         cur->bc_private.a.agno,
984                                         ext.rc_startblock);
985                         xfs_bmap_add_free(cur->bc_mp, dfops, fsbno,
986                                         ext.rc_blockcount, oinfo);
987                 }
988
989 skip:
990                 error = xfs_btree_increment(cur, 0, &found_rec);
991                 if (error)
992                         goto out_error;
993
994 advloop:
995                 (*agbno) += ext.rc_blockcount;
996                 (*aglen) -= ext.rc_blockcount;
997         }
998
999         return error;
1000 out_error:
1001         trace_xfs_refcount_modify_extent_error(cur->bc_mp,
1002                         cur->bc_private.a.agno, error, _RET_IP_);
1003         return error;
1004 }
1005
1006 /* Adjust the reference count of a range of AG blocks. */
1007 STATIC int
1008 xfs_refcount_adjust(
1009         struct xfs_btree_cur    *cur,
1010         xfs_agblock_t           agbno,
1011         xfs_extlen_t            aglen,
1012         xfs_agblock_t           *new_agbno,
1013         xfs_extlen_t            *new_aglen,
1014         enum xfs_refc_adjust_op adj,
1015         struct xfs_defer_ops    *dfops,
1016         struct xfs_owner_info   *oinfo)
1017 {
1018         bool                    shape_changed;
1019         int                     shape_changes = 0;
1020         int                     error;
1021
1022         *new_agbno = agbno;
1023         *new_aglen = aglen;
1024         if (adj == XFS_REFCOUNT_ADJUST_INCREASE)
1025                 trace_xfs_refcount_increase(cur->bc_mp, cur->bc_private.a.agno,
1026                                 agbno, aglen);
1027         else
1028                 trace_xfs_refcount_decrease(cur->bc_mp, cur->bc_private.a.agno,
1029                                 agbno, aglen);
1030
1031         /*
1032          * Ensure that no rcextents cross the boundary of the adjustment range.
1033          */
1034         error = xfs_refcount_split_extent(cur, agbno, &shape_changed);
1035         if (error)
1036                 goto out_error;
1037         if (shape_changed)
1038                 shape_changes++;
1039
1040         error = xfs_refcount_split_extent(cur, agbno + aglen, &shape_changed);
1041         if (error)
1042                 goto out_error;
1043         if (shape_changed)
1044                 shape_changes++;
1045
1046         /*
1047          * Try to merge with the left or right extents of the range.
1048          */
1049         error = xfs_refcount_merge_extents(cur, new_agbno, new_aglen, adj,
1050                         XFS_FIND_RCEXT_SHARED, &shape_changed);
1051         if (error)
1052                 goto out_error;
1053         if (shape_changed)
1054                 shape_changes++;
1055         if (shape_changes)
1056                 cur->bc_private.a.priv.refc.shape_changes++;
1057
1058         /* Now that we've taken care of the ends, adjust the middle extents */
1059         error = xfs_refcount_adjust_extents(cur, new_agbno, new_aglen,
1060                         adj, dfops, oinfo);
1061         if (error)
1062                 goto out_error;
1063
1064         return 0;
1065
1066 out_error:
1067         trace_xfs_refcount_adjust_error(cur->bc_mp, cur->bc_private.a.agno,
1068                         error, _RET_IP_);
1069         return error;
1070 }
1071
1072 /* Clean up after calling xfs_refcount_finish_one. */
1073 void
1074 xfs_refcount_finish_one_cleanup(
1075         struct xfs_trans        *tp,
1076         struct xfs_btree_cur    *rcur,
1077         int                     error)
1078 {
1079         struct xfs_buf          *agbp;
1080
1081         if (rcur == NULL)
1082                 return;
1083         agbp = rcur->bc_private.a.agbp;
1084         xfs_btree_del_cursor(rcur, error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
1085         if (error)
1086                 xfs_trans_brelse(tp, agbp);
1087 }
1088
1089 /*
1090  * Process one of the deferred refcount operations.  We pass back the
1091  * btree cursor to maintain our lock on the btree between calls.
1092  * This saves time and eliminates a buffer deadlock between the
1093  * superblock and the AGF because we'll always grab them in the same
1094  * order.
1095  */
1096 int
1097 xfs_refcount_finish_one(
1098         struct xfs_trans                *tp,
1099         struct xfs_defer_ops            *dfops,
1100         enum xfs_refcount_intent_type   type,
1101         xfs_fsblock_t                   startblock,
1102         xfs_extlen_t                    blockcount,
1103         xfs_fsblock_t                   *new_fsb,
1104         xfs_extlen_t                    *new_len,
1105         struct xfs_btree_cur            **pcur)
1106 {
1107         struct xfs_mount                *mp = tp->t_mountp;
1108         struct xfs_btree_cur            *rcur;
1109         struct xfs_buf                  *agbp = NULL;
1110         int                             error = 0;
1111         xfs_agnumber_t                  agno;
1112         xfs_agblock_t                   bno;
1113         xfs_agblock_t                   new_agbno;
1114         unsigned long                   nr_ops = 0;
1115         int                             shape_changes = 0;
1116
1117         agno = XFS_FSB_TO_AGNO(mp, startblock);
1118         ASSERT(agno != NULLAGNUMBER);
1119         bno = XFS_FSB_TO_AGBNO(mp, startblock);
1120
1121         trace_xfs_refcount_deferred(mp, XFS_FSB_TO_AGNO(mp, startblock),
1122                         type, XFS_FSB_TO_AGBNO(mp, startblock),
1123                         blockcount);
1124
1125         if (XFS_TEST_ERROR(false, mp,
1126                         XFS_ERRTAG_REFCOUNT_FINISH_ONE))
1127                 return -EIO;
1128
1129         /*
1130          * If we haven't gotten a cursor or the cursor AG doesn't match
1131          * the startblock, get one now.
1132          */
1133         rcur = *pcur;
1134         if (rcur != NULL && rcur->bc_private.a.agno != agno) {
1135                 nr_ops = rcur->bc_private.a.priv.refc.nr_ops;
1136                 shape_changes = rcur->bc_private.a.priv.refc.shape_changes;
1137                 xfs_refcount_finish_one_cleanup(tp, rcur, 0);
1138                 rcur = NULL;
1139                 *pcur = NULL;
1140         }
1141         if (rcur == NULL) {
1142                 error = xfs_alloc_read_agf(tp->t_mountp, tp, agno,
1143                                 XFS_ALLOC_FLAG_FREEING, &agbp);
1144                 if (error)
1145                         return error;
1146                 if (!agbp)
1147                         return -EFSCORRUPTED;
1148
1149                 rcur = xfs_refcountbt_init_cursor(mp, tp, agbp, agno, dfops);
1150                 if (!rcur) {
1151                         error = -ENOMEM;
1152                         goto out_cur;
1153                 }
1154                 rcur->bc_private.a.priv.refc.nr_ops = nr_ops;
1155                 rcur->bc_private.a.priv.refc.shape_changes = shape_changes;
1156         }
1157         *pcur = rcur;
1158
1159         switch (type) {
1160         case XFS_REFCOUNT_INCREASE:
1161                 error = xfs_refcount_adjust(rcur, bno, blockcount, &new_agbno,
1162                         new_len, XFS_REFCOUNT_ADJUST_INCREASE, dfops, NULL);
1163                 *new_fsb = XFS_AGB_TO_FSB(mp, agno, new_agbno);
1164                 break;
1165         case XFS_REFCOUNT_DECREASE:
1166                 error = xfs_refcount_adjust(rcur, bno, blockcount, &new_agbno,
1167                         new_len, XFS_REFCOUNT_ADJUST_DECREASE, dfops, NULL);
1168                 *new_fsb = XFS_AGB_TO_FSB(mp, agno, new_agbno);
1169                 break;
1170         case XFS_REFCOUNT_ALLOC_COW:
1171                 *new_fsb = startblock + blockcount;
1172                 *new_len = 0;
1173                 error = __xfs_refcount_cow_alloc(rcur, bno, blockcount, dfops);
1174                 break;
1175         case XFS_REFCOUNT_FREE_COW:
1176                 *new_fsb = startblock + blockcount;
1177                 *new_len = 0;
1178                 error = __xfs_refcount_cow_free(rcur, bno, blockcount, dfops);
1179                 break;
1180         default:
1181                 ASSERT(0);
1182                 error = -EFSCORRUPTED;
1183         }
1184         if (!error && *new_len > 0)
1185                 trace_xfs_refcount_finish_one_leftover(mp, agno, type,
1186                                 bno, blockcount, new_agbno, *new_len);
1187         return error;
1188
1189 out_cur:
1190         xfs_trans_brelse(tp, agbp);
1191
1192         return error;
1193 }
1194
1195 /*
1196  * Record a refcount intent for later processing.
1197  */
1198 static int
1199 __xfs_refcount_add(
1200         struct xfs_mount                *mp,
1201         struct xfs_defer_ops            *dfops,
1202         enum xfs_refcount_intent_type   type,
1203         xfs_fsblock_t                   startblock,
1204         xfs_extlen_t                    blockcount)
1205 {
1206         struct xfs_refcount_intent      *ri;
1207
1208         trace_xfs_refcount_defer(mp, XFS_FSB_TO_AGNO(mp, startblock),
1209                         type, XFS_FSB_TO_AGBNO(mp, startblock),
1210                         blockcount);
1211
1212         ri = kmem_alloc(sizeof(struct xfs_refcount_intent),
1213                         KM_SLEEP | KM_NOFS);
1214         INIT_LIST_HEAD(&ri->ri_list);
1215         ri->ri_type = type;
1216         ri->ri_startblock = startblock;
1217         ri->ri_blockcount = blockcount;
1218
1219         xfs_defer_add(dfops, XFS_DEFER_OPS_TYPE_REFCOUNT, &ri->ri_list);
1220         return 0;
1221 }
1222
1223 /*
1224  * Increase the reference count of the blocks backing a file's extent.
1225  */
1226 int
1227 xfs_refcount_increase_extent(
1228         struct xfs_mount                *mp,
1229         struct xfs_defer_ops            *dfops,
1230         struct xfs_bmbt_irec            *PREV)
1231 {
1232         if (!xfs_sb_version_hasreflink(&mp->m_sb))
1233                 return 0;
1234
1235         return __xfs_refcount_add(mp, dfops, XFS_REFCOUNT_INCREASE,
1236                         PREV->br_startblock, PREV->br_blockcount);
1237 }
1238
1239 /*
1240  * Decrease the reference count of the blocks backing a file's extent.
1241  */
1242 int
1243 xfs_refcount_decrease_extent(
1244         struct xfs_mount                *mp,
1245         struct xfs_defer_ops            *dfops,
1246         struct xfs_bmbt_irec            *PREV)
1247 {
1248         if (!xfs_sb_version_hasreflink(&mp->m_sb))
1249                 return 0;
1250
1251         return __xfs_refcount_add(mp, dfops, XFS_REFCOUNT_DECREASE,
1252                         PREV->br_startblock, PREV->br_blockcount);
1253 }
1254
1255 /*
1256  * Given an AG extent, find the lowest-numbered run of shared blocks
1257  * within that range and return the range in fbno/flen.  If
1258  * find_end_of_shared is set, return the longest contiguous extent of
1259  * shared blocks; if not, just return the first extent we find.  If no
1260  * shared blocks are found, fbno and flen will be set to NULLAGBLOCK
1261  * and 0, respectively.
1262  */
1263 int
1264 xfs_refcount_find_shared(
1265         struct xfs_btree_cur            *cur,
1266         xfs_agblock_t                   agbno,
1267         xfs_extlen_t                    aglen,
1268         xfs_agblock_t                   *fbno,
1269         xfs_extlen_t                    *flen,
1270         bool                            find_end_of_shared)
1271 {
1272         struct xfs_refcount_irec        tmp;
1273         int                             i;
1274         int                             have;
1275         int                             error;
1276
1277         trace_xfs_refcount_find_shared(cur->bc_mp, cur->bc_private.a.agno,
1278                         agbno, aglen);
1279
1280         /* By default, skip the whole range */
1281         *fbno = NULLAGBLOCK;
1282         *flen = 0;
1283
1284         /* Try to find a refcount extent that crosses the start */
1285         error = xfs_refcount_lookup_le(cur, agbno, &have);
1286         if (error)
1287                 goto out_error;
1288         if (!have) {
1289                 /* No left extent, look at the next one */
1290                 error = xfs_btree_increment(cur, 0, &have);
1291                 if (error)
1292                         goto out_error;
1293                 if (!have)
1294                         goto done;
1295         }
1296         error = xfs_refcount_get_rec(cur, &tmp, &i);
1297         if (error)
1298                 goto out_error;
1299         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, out_error);
1300
1301         /* If the extent ends before the start, look at the next one */
1302         if (tmp.rc_startblock + tmp.rc_blockcount <= agbno) {
1303                 error = xfs_btree_increment(cur, 0, &have);
1304                 if (error)
1305                         goto out_error;
1306                 if (!have)
1307                         goto done;
1308                 error = xfs_refcount_get_rec(cur, &tmp, &i);
1309                 if (error)
1310                         goto out_error;
1311                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, out_error);
1312         }
1313
1314         /* If the extent starts after the range we want, bail out */
1315         if (tmp.rc_startblock >= agbno + aglen)
1316                 goto done;
1317
1318         /* We found the start of a shared extent! */
1319         if (tmp.rc_startblock < agbno) {
1320                 tmp.rc_blockcount -= (agbno - tmp.rc_startblock);
1321                 tmp.rc_startblock = agbno;
1322         }
1323
1324         *fbno = tmp.rc_startblock;
1325         *flen = min(tmp.rc_blockcount, agbno + aglen - *fbno);
1326         if (!find_end_of_shared)
1327                 goto done;
1328
1329         /* Otherwise, find the end of this shared extent */
1330         while (*fbno + *flen < agbno + aglen) {
1331                 error = xfs_btree_increment(cur, 0, &have);
1332                 if (error)
1333                         goto out_error;
1334                 if (!have)
1335                         break;
1336                 error = xfs_refcount_get_rec(cur, &tmp, &i);
1337                 if (error)
1338                         goto out_error;
1339                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, out_error);
1340                 if (tmp.rc_startblock >= agbno + aglen ||
1341                     tmp.rc_startblock != *fbno + *flen)
1342                         break;
1343                 *flen = min(*flen + tmp.rc_blockcount, agbno + aglen - *fbno);
1344         }
1345
1346 done:
1347         trace_xfs_refcount_find_shared_result(cur->bc_mp,
1348                         cur->bc_private.a.agno, *fbno, *flen);
1349
1350 out_error:
1351         if (error)
1352                 trace_xfs_refcount_find_shared_error(cur->bc_mp,
1353                                 cur->bc_private.a.agno, error, _RET_IP_);
1354         return error;
1355 }
1356
1357 /*
1358  * Recovering CoW Blocks After a Crash
1359  *
1360  * Due to the way that the copy on write mechanism works, there's a window of
1361  * opportunity in which we can lose track of allocated blocks during a crash.
1362  * Because CoW uses delayed allocation in the in-core CoW fork, writeback
1363  * causes blocks to be allocated and stored in the CoW fork.  The blocks are
1364  * no longer in the free space btree but are not otherwise recorded anywhere
1365  * until the write completes and the blocks are mapped into the file.  A crash
1366  * in between allocation and remapping results in the replacement blocks being
1367  * lost.  This situation is exacerbated by the CoW extent size hint because
1368  * allocations can hang around for long time.
1369  *
1370  * However, there is a place where we can record these allocations before they
1371  * become mappings -- the reference count btree.  The btree does not record
1372  * extents with refcount == 1, so we can record allocations with a refcount of
1373  * 1.  Blocks being used for CoW writeout cannot be shared, so there should be
1374  * no conflict with shared block records.  These mappings should be created
1375  * when we allocate blocks to the CoW fork and deleted when they're removed
1376  * from the CoW fork.
1377  *
1378  * Minor nit: records for in-progress CoW allocations and records for shared
1379  * extents must never be merged, to preserve the property that (except for CoW
1380  * allocations) there are no refcount btree entries with refcount == 1.  The
1381  * only time this could potentially happen is when unsharing a block that's
1382  * adjacent to CoW allocations, so we must be careful to avoid this.
1383  *
1384  * At mount time we recover lost CoW allocations by searching the refcount
1385  * btree for these refcount == 1 mappings.  These represent CoW allocations
1386  * that were in progress at the time the filesystem went down, so we can free
1387  * them to get the space back.
1388  *
1389  * This mechanism is superior to creating EFIs for unmapped CoW extents for
1390  * several reasons -- first, EFIs pin the tail of the log and would have to be
1391  * periodically relogged to avoid filling up the log.  Second, CoW completions
1392  * will have to file an EFD and create new EFIs for whatever remains in the
1393  * CoW fork; this partially takes care of (1) but extent-size reservations
1394  * will have to periodically relog even if there's no writeout in progress.
1395  * This can happen if the CoW extent size hint is set, which you really want.
1396  * Third, EFIs cannot currently be automatically relogged into newer
1397  * transactions to advance the log tail.  Fourth, stuffing the log full of
1398  * EFIs places an upper bound on the number of CoW allocations that can be
1399  * held filesystem-wide at any given time.  Recording them in the refcount
1400  * btree doesn't require us to maintain any state in memory and doesn't pin
1401  * the log.
1402  */
1403 /*
1404  * Adjust the refcounts of CoW allocations.  These allocations are "magic"
1405  * in that they're not referenced anywhere else in the filesystem, so we
1406  * stash them in the refcount btree with a refcount of 1 until either file
1407  * remapping (or CoW cancellation) happens.
1408  */
1409 STATIC int
1410 xfs_refcount_adjust_cow_extents(
1411         struct xfs_btree_cur    *cur,
1412         xfs_agblock_t           agbno,
1413         xfs_extlen_t            aglen,
1414         enum xfs_refc_adjust_op adj)
1415 {
1416         struct xfs_refcount_irec        ext, tmp;
1417         int                             error;
1418         int                             found_rec, found_tmp;
1419
1420         if (aglen == 0)
1421                 return 0;
1422
1423         /* Find any overlapping refcount records */
1424         error = xfs_refcount_lookup_ge(cur, agbno, &found_rec);
1425         if (error)
1426                 goto out_error;
1427         error = xfs_refcount_get_rec(cur, &ext, &found_rec);
1428         if (error)
1429                 goto out_error;
1430         if (!found_rec) {
1431                 ext.rc_startblock = cur->bc_mp->m_sb.sb_agblocks +
1432                                 XFS_REFC_COW_START;
1433                 ext.rc_blockcount = 0;
1434                 ext.rc_refcount = 0;
1435         }
1436
1437         switch (adj) {
1438         case XFS_REFCOUNT_ADJUST_COW_ALLOC:
1439                 /* Adding a CoW reservation, there should be nothing here. */
1440                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
1441                                 ext.rc_startblock >= agbno + aglen, out_error);
1442
1443                 tmp.rc_startblock = agbno;
1444                 tmp.rc_blockcount = aglen;
1445                 tmp.rc_refcount = 1;
1446                 trace_xfs_refcount_modify_extent(cur->bc_mp,
1447                                 cur->bc_private.a.agno, &tmp);
1448
1449                 error = xfs_refcount_insert(cur, &tmp,
1450                                 &found_tmp);
1451                 if (error)
1452                         goto out_error;
1453                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
1454                                 found_tmp == 1, out_error);
1455                 break;
1456         case XFS_REFCOUNT_ADJUST_COW_FREE:
1457                 /* Removing a CoW reservation, there should be one extent. */
1458                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
1459                         ext.rc_startblock == agbno, out_error);
1460                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
1461                         ext.rc_blockcount == aglen, out_error);
1462                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
1463                         ext.rc_refcount == 1, out_error);
1464
1465                 ext.rc_refcount = 0;
1466                 trace_xfs_refcount_modify_extent(cur->bc_mp,
1467                                 cur->bc_private.a.agno, &ext);
1468                 error = xfs_refcount_delete(cur, &found_rec);
1469                 if (error)
1470                         goto out_error;
1471                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp,
1472                                 found_rec == 1, out_error);
1473                 break;
1474         default:
1475                 ASSERT(0);
1476         }
1477
1478         return error;
1479 out_error:
1480         trace_xfs_refcount_modify_extent_error(cur->bc_mp,
1481                         cur->bc_private.a.agno, error, _RET_IP_);
1482         return error;
1483 }
1484
1485 /*
1486  * Add or remove refcount btree entries for CoW reservations.
1487  */
1488 STATIC int
1489 xfs_refcount_adjust_cow(
1490         struct xfs_btree_cur    *cur,
1491         xfs_agblock_t           agbno,
1492         xfs_extlen_t            aglen,
1493         enum xfs_refc_adjust_op adj)
1494 {
1495         bool                    shape_changed;
1496         int                     error;
1497
1498         agbno += XFS_REFC_COW_START;
1499
1500         /*
1501          * Ensure that no rcextents cross the boundary of the adjustment range.
1502          */
1503         error = xfs_refcount_split_extent(cur, agbno, &shape_changed);
1504         if (error)
1505                 goto out_error;
1506
1507         error = xfs_refcount_split_extent(cur, agbno + aglen, &shape_changed);
1508         if (error)
1509                 goto out_error;
1510
1511         /*
1512          * Try to merge with the left or right extents of the range.
1513          */
1514         error = xfs_refcount_merge_extents(cur, &agbno, &aglen, adj,
1515                         XFS_FIND_RCEXT_COW, &shape_changed);
1516         if (error)
1517                 goto out_error;
1518
1519         /* Now that we've taken care of the ends, adjust the middle extents */
1520         error = xfs_refcount_adjust_cow_extents(cur, agbno, aglen, adj);
1521         if (error)
1522                 goto out_error;
1523
1524         return 0;
1525
1526 out_error:
1527         trace_xfs_refcount_adjust_cow_error(cur->bc_mp, cur->bc_private.a.agno,
1528                         error, _RET_IP_);
1529         return error;
1530 }
1531
1532 /*
1533  * Record a CoW allocation in the refcount btree.
1534  */
1535 STATIC int
1536 __xfs_refcount_cow_alloc(
1537         struct xfs_btree_cur    *rcur,
1538         xfs_agblock_t           agbno,
1539         xfs_extlen_t            aglen,
1540         struct xfs_defer_ops    *dfops)
1541 {
1542         trace_xfs_refcount_cow_increase(rcur->bc_mp, rcur->bc_private.a.agno,
1543                         agbno, aglen);
1544
1545         /* Add refcount btree reservation */
1546         return xfs_refcount_adjust_cow(rcur, agbno, aglen,
1547                         XFS_REFCOUNT_ADJUST_COW_ALLOC);
1548 }
1549
1550 /*
1551  * Remove a CoW allocation from the refcount btree.
1552  */
1553 STATIC int
1554 __xfs_refcount_cow_free(
1555         struct xfs_btree_cur    *rcur,
1556         xfs_agblock_t           agbno,
1557         xfs_extlen_t            aglen,
1558         struct xfs_defer_ops    *dfops)
1559 {
1560         trace_xfs_refcount_cow_decrease(rcur->bc_mp, rcur->bc_private.a.agno,
1561                         agbno, aglen);
1562
1563         /* Remove refcount btree reservation */
1564         return xfs_refcount_adjust_cow(rcur, agbno, aglen,
1565                         XFS_REFCOUNT_ADJUST_COW_FREE);
1566 }
1567
1568 /* Record a CoW staging extent in the refcount btree. */
1569 int
1570 xfs_refcount_alloc_cow_extent(
1571         struct xfs_mount                *mp,
1572         struct xfs_defer_ops            *dfops,
1573         xfs_fsblock_t                   fsb,
1574         xfs_extlen_t                    len)
1575 {
1576         int                             error;
1577
1578         if (!xfs_sb_version_hasreflink(&mp->m_sb))
1579                 return 0;
1580
1581         error = __xfs_refcount_add(mp, dfops, XFS_REFCOUNT_ALLOC_COW,
1582                         fsb, len);
1583         if (error)
1584                 return error;
1585
1586         /* Add rmap entry */
1587         return xfs_rmap_alloc_extent(mp, dfops, XFS_FSB_TO_AGNO(mp, fsb),
1588                         XFS_FSB_TO_AGBNO(mp, fsb), len, XFS_RMAP_OWN_COW);
1589 }
1590
1591 /* Forget a CoW staging event in the refcount btree. */
1592 int
1593 xfs_refcount_free_cow_extent(
1594         struct xfs_mount                *mp,
1595         struct xfs_defer_ops            *dfops,
1596         xfs_fsblock_t                   fsb,
1597         xfs_extlen_t                    len)
1598 {
1599         int                             error;
1600
1601         if (!xfs_sb_version_hasreflink(&mp->m_sb))
1602                 return 0;
1603
1604         /* Remove rmap entry */
1605         error = xfs_rmap_free_extent(mp, dfops, XFS_FSB_TO_AGNO(mp, fsb),
1606                         XFS_FSB_TO_AGBNO(mp, fsb), len, XFS_RMAP_OWN_COW);
1607         if (error)
1608                 return error;
1609
1610         return __xfs_refcount_add(mp, dfops, XFS_REFCOUNT_FREE_COW,
1611                         fsb, len);
1612 }
1613
1614 struct xfs_refcount_recovery {
1615         struct list_head                rr_list;
1616         struct xfs_refcount_irec        rr_rrec;
1617 };
1618
1619 /* Stuff an extent on the recovery list. */
1620 STATIC int
1621 xfs_refcount_recover_extent(
1622         struct xfs_btree_cur            *cur,
1623         union xfs_btree_rec             *rec,
1624         void                            *priv)
1625 {
1626         struct list_head                *debris = priv;
1627         struct xfs_refcount_recovery    *rr;
1628
1629         if (be32_to_cpu(rec->refc.rc_refcount) != 1)
1630                 return -EFSCORRUPTED;
1631
1632         rr = kmem_alloc(sizeof(struct xfs_refcount_recovery), KM_SLEEP);
1633         xfs_refcount_btrec_to_irec(rec, &rr->rr_rrec);
1634         list_add_tail(&rr->rr_list, debris);
1635
1636         return 0;
1637 }
1638
1639 /* Find and remove leftover CoW reservations. */
1640 int
1641 xfs_refcount_recover_cow_leftovers(
1642         struct xfs_mount                *mp,
1643         xfs_agnumber_t                  agno)
1644 {
1645         struct xfs_trans                *tp;
1646         struct xfs_btree_cur            *cur;
1647         struct xfs_buf                  *agbp;
1648         struct xfs_refcount_recovery    *rr, *n;
1649         struct list_head                debris;
1650         union xfs_btree_irec            low;
1651         union xfs_btree_irec            high;
1652         struct xfs_defer_ops            dfops;
1653         xfs_fsblock_t                   fsb;
1654         xfs_agblock_t                   agbno;
1655         int                             error;
1656
1657         if (mp->m_sb.sb_agblocks >= XFS_REFC_COW_START)
1658                 return -EOPNOTSUPP;
1659
1660         INIT_LIST_HEAD(&debris);
1661
1662         /*
1663          * In this first part, we use an empty transaction to gather up
1664          * all the leftover CoW extents so that we can subsequently
1665          * delete them.  The empty transaction is used to avoid
1666          * a buffer lock deadlock if there happens to be a loop in the
1667          * refcountbt because we're allowed to re-grab a buffer that is
1668          * already attached to our transaction.  When we're done
1669          * recording the CoW debris we cancel the (empty) transaction
1670          * and everything goes away cleanly.
1671          */
1672         error = xfs_trans_alloc_empty(mp, &tp);
1673         if (error)
1674                 return error;
1675
1676         error = xfs_alloc_read_agf(mp, tp, agno, 0, &agbp);
1677         if (error)
1678                 goto out_trans;
1679         if (!agbp) {
1680                 error = -ENOMEM;
1681                 goto out_trans;
1682         }
1683         cur = xfs_refcountbt_init_cursor(mp, tp, agbp, agno, NULL);
1684
1685         /* Find all the leftover CoW staging extents. */
1686         memset(&low, 0, sizeof(low));
1687         memset(&high, 0, sizeof(high));
1688         low.rc.rc_startblock = XFS_REFC_COW_START;
1689         high.rc.rc_startblock = -1U;
1690         error = xfs_btree_query_range(cur, &low, &high,
1691                         xfs_refcount_recover_extent, &debris);
1692         if (error)
1693                 goto out_cursor;
1694         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1695         xfs_trans_brelse(tp, agbp);
1696         xfs_trans_cancel(tp);
1697
1698         /* Now iterate the list to free the leftovers */
1699         list_for_each_entry_safe(rr, n, &debris, rr_list) {
1700                 /* Set up transaction. */
1701                 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0, 0, &tp);
1702                 if (error)
1703                         goto out_free;
1704
1705                 trace_xfs_refcount_recover_extent(mp, agno, &rr->rr_rrec);
1706
1707                 /* Free the orphan record */
1708                 xfs_defer_init(&dfops, &fsb);
1709                 agbno = rr->rr_rrec.rc_startblock - XFS_REFC_COW_START;
1710                 fsb = XFS_AGB_TO_FSB(mp, agno, agbno);
1711                 error = xfs_refcount_free_cow_extent(mp, &dfops, fsb,
1712                                 rr->rr_rrec.rc_blockcount);
1713                 if (error)
1714                         goto out_defer;
1715
1716                 /* Free the block. */
1717                 xfs_bmap_add_free(mp, &dfops, fsb,
1718                                 rr->rr_rrec.rc_blockcount, NULL);
1719
1720                 error = xfs_defer_finish(&tp, &dfops);
1721                 if (error)
1722                         goto out_defer;
1723
1724                 error = xfs_trans_commit(tp);
1725                 if (error)
1726                         goto out_free;
1727
1728                 list_del(&rr->rr_list);
1729                 kmem_free(rr);
1730         }
1731
1732         return error;
1733 out_defer:
1734         xfs_defer_cancel(&dfops);
1735 out_trans:
1736         xfs_trans_cancel(tp);
1737 out_free:
1738         /* Free the leftover list */
1739         list_for_each_entry_safe(rr, n, &debris, rr_list) {
1740                 list_del(&rr->rr_list);
1741                 kmem_free(rr);
1742         }
1743         return error;
1744
1745 out_cursor:
1746         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1747         xfs_trans_brelse(tp, agbp);
1748         goto out_trans;
1749 }
1750
1751 /* Is there a record covering a given extent? */
1752 int
1753 xfs_refcount_has_record(
1754         struct xfs_btree_cur    *cur,
1755         xfs_agblock_t           bno,
1756         xfs_extlen_t            len,
1757         bool                    *exists)
1758 {
1759         union xfs_btree_irec    low;
1760         union xfs_btree_irec    high;
1761
1762         memset(&low, 0, sizeof(low));
1763         low.rc.rc_startblock = bno;
1764         memset(&high, 0xFF, sizeof(high));
1765         high.rc.rc_startblock = bno + len - 1;
1766
1767         return xfs_btree_has_record(cur, &low, &high, exists);
1768 }