xref: /linux/fs/xfs/libxfs/xfs_refcount.c (revision 6fe0d151eaada4f3ea4947b19ac048b8894b9e88)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2016 Oracle.  All Rights Reserved.
4  * Author: Darrick J. Wong <darrick.wong@oracle.com>
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_defer.h"
14 #include "xfs_btree.h"
15 #include "xfs_bmap.h"
16 #include "xfs_refcount_btree.h"
17 #include "xfs_alloc.h"
18 #include "xfs_errortag.h"
19 #include "xfs_error.h"
20 #include "xfs_trace.h"
21 #include "xfs_trans.h"
22 #include "xfs_bit.h"
23 #include "xfs_refcount.h"
24 #include "xfs_rmap.h"
25 #include "xfs_ag.h"
26 #include "xfs_health.h"
27 #include "xfs_refcount_item.h"
28 #include "xfs_rtgroup.h"
29 #include "xfs_rtrefcount_btree.h"
30 
31 struct kmem_cache	*xfs_refcount_intent_cache;
32 
33 /* Allowable refcount adjustment amounts. */
34 enum xfs_refc_adjust_op {
35 	XFS_REFCOUNT_ADJUST_INCREASE	= 1,
36 	XFS_REFCOUNT_ADJUST_DECREASE	= -1,
37 	XFS_REFCOUNT_ADJUST_COW_ALLOC	= 0,
38 	XFS_REFCOUNT_ADJUST_COW_FREE	= -1,
39 };
40 
41 STATIC int __xfs_refcount_cow_alloc(struct xfs_btree_cur *rcur,
42 		xfs_agblock_t agbno, xfs_extlen_t aglen);
43 STATIC int __xfs_refcount_cow_free(struct xfs_btree_cur *rcur,
44 		xfs_agblock_t agbno, xfs_extlen_t aglen);
45 
46 /*
47  * Look up the first record less than or equal to [bno, len] in the btree
48  * given by cur.
49  */
50 int
51 xfs_refcount_lookup_le(
52 	struct xfs_btree_cur	*cur,
53 	enum xfs_refc_domain	domain,
54 	xfs_agblock_t		bno,
55 	int			*stat)
56 {
57 	trace_xfs_refcount_lookup(cur,
58 			xfs_refcount_encode_startblock(bno, domain),
59 			XFS_LOOKUP_LE);
60 	cur->bc_rec.rc.rc_startblock = bno;
61 	cur->bc_rec.rc.rc_blockcount = 0;
62 	cur->bc_rec.rc.rc_domain = domain;
63 	return xfs_btree_lookup(cur, XFS_LOOKUP_LE, stat);
64 }
65 
66 /*
67  * Look up the first record greater than or equal to [bno, len] in the btree
68  * given by cur.
69  */
70 int
71 xfs_refcount_lookup_ge(
72 	struct xfs_btree_cur	*cur,
73 	enum xfs_refc_domain	domain,
74 	xfs_agblock_t		bno,
75 	int			*stat)
76 {
77 	trace_xfs_refcount_lookup(cur,
78 			xfs_refcount_encode_startblock(bno, domain),
79 			XFS_LOOKUP_GE);
80 	cur->bc_rec.rc.rc_startblock = bno;
81 	cur->bc_rec.rc.rc_blockcount = 0;
82 	cur->bc_rec.rc.rc_domain = domain;
83 	return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
84 }
85 
86 /*
87  * Look up the first record equal to [bno, len] in the btree
88  * given by cur.
89  */
90 int
91 xfs_refcount_lookup_eq(
92 	struct xfs_btree_cur	*cur,
93 	enum xfs_refc_domain	domain,
94 	xfs_agblock_t		bno,
95 	int			*stat)
96 {
97 	trace_xfs_refcount_lookup(cur,
98 			xfs_refcount_encode_startblock(bno, domain),
99 			XFS_LOOKUP_LE);
100 	cur->bc_rec.rc.rc_startblock = bno;
101 	cur->bc_rec.rc.rc_blockcount = 0;
102 	cur->bc_rec.rc.rc_domain = domain;
103 	return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
104 }
105 
106 /* Convert on-disk record to in-core format. */
107 void
108 xfs_refcount_btrec_to_irec(
109 	const union xfs_btree_rec	*rec,
110 	struct xfs_refcount_irec	*irec)
111 {
112 	uint32_t			start;
113 
114 	start = be32_to_cpu(rec->refc.rc_startblock);
115 	if (start & XFS_REFC_COWFLAG) {
116 		start &= ~XFS_REFC_COWFLAG;
117 		irec->rc_domain = XFS_REFC_DOMAIN_COW;
118 	} else {
119 		irec->rc_domain = XFS_REFC_DOMAIN_SHARED;
120 	}
121 
122 	irec->rc_startblock = start;
123 	irec->rc_blockcount = be32_to_cpu(rec->refc.rc_blockcount);
124 	irec->rc_refcount = be32_to_cpu(rec->refc.rc_refcount);
125 }
126 
127 /* Simple checks for refcount records. */
128 xfs_failaddr_t
129 xfs_refcount_check_irec(
130 	struct xfs_perag		*pag,
131 	const struct xfs_refcount_irec	*irec)
132 {
133 	if (irec->rc_blockcount == 0 || irec->rc_blockcount > XFS_REFC_LEN_MAX)
134 		return __this_address;
135 
136 	if (!xfs_refcount_check_domain(irec))
137 		return __this_address;
138 
139 	/* check for valid extent range, including overflow */
140 	if (!xfs_verify_agbext(pag, irec->rc_startblock, irec->rc_blockcount))
141 		return __this_address;
142 
143 	if (irec->rc_refcount == 0 || irec->rc_refcount > XFS_REFC_REFCOUNT_MAX)
144 		return __this_address;
145 
146 	return NULL;
147 }
148 
149 xfs_failaddr_t
150 xfs_rtrefcount_check_irec(
151 	struct xfs_rtgroup		*rtg,
152 	const struct xfs_refcount_irec	*irec)
153 {
154 	if (irec->rc_blockcount == 0 || irec->rc_blockcount > XFS_REFC_LEN_MAX)
155 		return __this_address;
156 
157 	if (!xfs_refcount_check_domain(irec))
158 		return __this_address;
159 
160 	/* check for valid extent range, including overflow */
161 	if (!xfs_verify_rgbext(rtg, irec->rc_startblock, irec->rc_blockcount))
162 		return __this_address;
163 
164 	if (irec->rc_refcount == 0 || irec->rc_refcount > XFS_REFC_REFCOUNT_MAX)
165 		return __this_address;
166 
167 	return NULL;
168 }
169 
170 static inline xfs_failaddr_t
171 xfs_refcount_check_btrec(
172 	struct xfs_btree_cur		*cur,
173 	const struct xfs_refcount_irec	*irec)
174 {
175 	if (xfs_btree_is_rtrefcount(cur->bc_ops))
176 		return xfs_rtrefcount_check_irec(to_rtg(cur->bc_group), irec);
177 	return xfs_refcount_check_irec(to_perag(cur->bc_group), irec);
178 }
179 
180 static inline int
181 xfs_refcount_complain_bad_rec(
182 	struct xfs_btree_cur		*cur,
183 	xfs_failaddr_t			fa,
184 	const struct xfs_refcount_irec	*irec)
185 {
186 	struct xfs_mount		*mp = cur->bc_mp;
187 
188 	if (xfs_btree_is_rtrefcount(cur->bc_ops)) {
189 		xfs_warn(mp,
190  "RT Refcount BTree record corruption in rtgroup %u detected at %pS!",
191 				cur->bc_group->xg_gno, fa);
192 	} else {
193 		xfs_warn(mp,
194  "Refcount BTree record corruption in AG %d detected at %pS!",
195 				cur->bc_group->xg_gno, fa);
196 	}
197 	xfs_warn(mp,
198 		"Start block 0x%x, block count 0x%x, references 0x%x",
199 		irec->rc_startblock, irec->rc_blockcount, irec->rc_refcount);
200 	xfs_btree_mark_sick(cur);
201 	return -EFSCORRUPTED;
202 }
203 
204 /*
205  * Get the data from the pointed-to record.
206  */
207 int
208 xfs_refcount_get_rec(
209 	struct xfs_btree_cur		*cur,
210 	struct xfs_refcount_irec	*irec,
211 	int				*stat)
212 {
213 	union xfs_btree_rec		*rec;
214 	xfs_failaddr_t			fa;
215 	int				error;
216 
217 	error = xfs_btree_get_rec(cur, &rec, stat);
218 	if (error || !*stat)
219 		return error;
220 
221 	xfs_refcount_btrec_to_irec(rec, irec);
222 	fa = xfs_refcount_check_btrec(cur, irec);
223 	if (fa)
224 		return xfs_refcount_complain_bad_rec(cur, fa, irec);
225 
226 	trace_xfs_refcount_get(cur, irec);
227 	return 0;
228 }
229 
230 /*
231  * Update the record referred to by cur to the value given
232  * by [bno, len, refcount].
233  * This either works (return 0) or gets an EFSCORRUPTED error.
234  */
235 STATIC int
236 xfs_refcount_update(
237 	struct xfs_btree_cur		*cur,
238 	struct xfs_refcount_irec	*irec)
239 {
240 	union xfs_btree_rec	rec;
241 	uint32_t		start;
242 	int			error;
243 
244 	trace_xfs_refcount_update(cur, irec);
245 
246 	start = xfs_refcount_encode_startblock(irec->rc_startblock,
247 			irec->rc_domain);
248 	rec.refc.rc_startblock = cpu_to_be32(start);
249 	rec.refc.rc_blockcount = cpu_to_be32(irec->rc_blockcount);
250 	rec.refc.rc_refcount = cpu_to_be32(irec->rc_refcount);
251 
252 	error = xfs_btree_update(cur, &rec);
253 	if (error)
254 		trace_xfs_refcount_update_error(cur, error, _RET_IP_);
255 	return error;
256 }
257 
258 /*
259  * Insert the record referred to by cur to the value given
260  * by [bno, len, refcount].
261  * This either works (return 0) or gets an EFSCORRUPTED error.
262  */
263 int
264 xfs_refcount_insert(
265 	struct xfs_btree_cur		*cur,
266 	struct xfs_refcount_irec	*irec,
267 	int				*i)
268 {
269 	int				error;
270 
271 	trace_xfs_refcount_insert(cur, irec);
272 
273 	cur->bc_rec.rc.rc_startblock = irec->rc_startblock;
274 	cur->bc_rec.rc.rc_blockcount = irec->rc_blockcount;
275 	cur->bc_rec.rc.rc_refcount = irec->rc_refcount;
276 	cur->bc_rec.rc.rc_domain = irec->rc_domain;
277 
278 	error = xfs_btree_insert(cur, i);
279 	if (error)
280 		goto out_error;
281 	if (XFS_IS_CORRUPT(cur->bc_mp, *i != 1)) {
282 		xfs_btree_mark_sick(cur);
283 		error = -EFSCORRUPTED;
284 		goto out_error;
285 	}
286 
287 out_error:
288 	if (error)
289 		trace_xfs_refcount_insert_error(cur, error, _RET_IP_);
290 	return error;
291 }
292 
293 /*
294  * Remove the record referred to by cur, then set the pointer to the spot
295  * where the record could be re-inserted, in case we want to increment or
296  * decrement the cursor.
297  * This either works (return 0) or gets an EFSCORRUPTED error.
298  */
299 STATIC int
300 xfs_refcount_delete(
301 	struct xfs_btree_cur	*cur,
302 	int			*i)
303 {
304 	struct xfs_refcount_irec	irec;
305 	int			found_rec;
306 	int			error;
307 
308 	error = xfs_refcount_get_rec(cur, &irec, &found_rec);
309 	if (error)
310 		goto out_error;
311 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
312 		xfs_btree_mark_sick(cur);
313 		error = -EFSCORRUPTED;
314 		goto out_error;
315 	}
316 	trace_xfs_refcount_delete(cur, &irec);
317 	error = xfs_btree_delete(cur, i);
318 	if (XFS_IS_CORRUPT(cur->bc_mp, *i != 1)) {
319 		xfs_btree_mark_sick(cur);
320 		error = -EFSCORRUPTED;
321 		goto out_error;
322 	}
323 	if (error)
324 		goto out_error;
325 	error = xfs_refcount_lookup_ge(cur, irec.rc_domain, irec.rc_startblock,
326 			&found_rec);
327 out_error:
328 	if (error)
329 		trace_xfs_refcount_delete_error(cur, error, _RET_IP_);
330 	return error;
331 }
332 
333 /*
334  * Adjusting the Reference Count
335  *
336  * As stated elsewhere, the reference count btree (refcbt) stores
337  * >1 reference counts for extents of physical blocks.  In this
338  * operation, we're either raising or lowering the reference count of
339  * some subrange stored in the tree:
340  *
341  *      <------ adjustment range ------>
342  * ----+   +---+-----+ +--+--------+---------
343  *  2  |   | 3 |  4  | |17|   55   |   10
344  * ----+   +---+-----+ +--+--------+---------
345  * X axis is physical blocks number;
346  * reference counts are the numbers inside the rectangles
347  *
348  * The first thing we need to do is to ensure that there are no
349  * refcount extents crossing either boundary of the range to be
350  * adjusted.  For any extent that does cross a boundary, split it into
351  * two extents so that we can increment the refcount of one of the
352  * pieces later:
353  *
354  *      <------ adjustment range ------>
355  * ----+   +---+-----+ +--+--------+----+----
356  *  2  |   | 3 |  2  | |17|   55   | 10 | 10
357  * ----+   +---+-----+ +--+--------+----+----
358  *
359  * For this next step, let's assume that all the physical blocks in
360  * the adjustment range are mapped to a file and are therefore in use
361  * at least once.  Therefore, we can infer that any gap in the
362  * refcount tree within the adjustment range represents a physical
363  * extent with refcount == 1:
364  *
365  *      <------ adjustment range ------>
366  * ----+---+---+-----+-+--+--------+----+----
367  *  2  |"1"| 3 |  2  |1|17|   55   | 10 | 10
368  * ----+---+---+-----+-+--+--------+----+----
369  *      ^
370  *
371  * For each extent that falls within the interval range, figure out
372  * which extent is to the left or the right of that extent.  Now we
373  * have a left, current, and right extent.  If the new reference count
374  * of the center extent enables us to merge left, center, and right
375  * into one record covering all three, do so.  If the center extent is
376  * at the left end of the range, abuts the left extent, and its new
377  * reference count matches the left extent's record, then merge them.
378  * If the center extent is at the right end of the range, abuts the
379  * right extent, and the reference counts match, merge those.  In the
380  * example, we can left merge (assuming an increment operation):
381  *
382  *      <------ adjustment range ------>
383  * --------+---+-----+-+--+--------+----+----
384  *    2    | 3 |  2  |1|17|   55   | 10 | 10
385  * --------+---+-----+-+--+--------+----+----
386  *          ^
387  *
388  * For all other extents within the range, adjust the reference count
389  * or delete it if the refcount falls below 2.  If we were
390  * incrementing, the end result looks like this:
391  *
392  *      <------ adjustment range ------>
393  * --------+---+-----+-+--+--------+----+----
394  *    2    | 4 |  3  |2|18|   56   | 11 | 10
395  * --------+---+-----+-+--+--------+----+----
396  *
397  * The result of a decrement operation looks as such:
398  *
399  *      <------ adjustment range ------>
400  * ----+   +---+       +--+--------+----+----
401  *  2  |   | 2 |       |16|   54   |  9 | 10
402  * ----+   +---+       +--+--------+----+----
403  *      DDDD    111111DD
404  *
405  * The blocks marked "D" are freed; the blocks marked "1" are only
406  * referenced once and therefore the record is removed from the
407  * refcount btree.
408  */
409 
410 /* Next block after this extent. */
411 static inline xfs_agblock_t
412 xfs_refc_next(
413 	struct xfs_refcount_irec	*rc)
414 {
415 	return rc->rc_startblock + rc->rc_blockcount;
416 }
417 
418 /*
419  * Split a refcount extent that crosses agbno.
420  */
421 STATIC int
422 xfs_refcount_split_extent(
423 	struct xfs_btree_cur		*cur,
424 	enum xfs_refc_domain		domain,
425 	xfs_agblock_t			agbno,
426 	bool				*shape_changed)
427 {
428 	struct xfs_refcount_irec	rcext, tmp;
429 	int				found_rec;
430 	int				error;
431 
432 	*shape_changed = false;
433 	error = xfs_refcount_lookup_le(cur, domain, agbno, &found_rec);
434 	if (error)
435 		goto out_error;
436 	if (!found_rec)
437 		return 0;
438 
439 	error = xfs_refcount_get_rec(cur, &rcext, &found_rec);
440 	if (error)
441 		goto out_error;
442 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
443 		xfs_btree_mark_sick(cur);
444 		error = -EFSCORRUPTED;
445 		goto out_error;
446 	}
447 	if (rcext.rc_domain != domain)
448 		return 0;
449 	if (rcext.rc_startblock == agbno || xfs_refc_next(&rcext) <= agbno)
450 		return 0;
451 
452 	*shape_changed = true;
453 	trace_xfs_refcount_split_extent(cur, &rcext, agbno);
454 
455 	/* Establish the right extent. */
456 	tmp = rcext;
457 	tmp.rc_startblock = agbno;
458 	tmp.rc_blockcount -= (agbno - rcext.rc_startblock);
459 	error = xfs_refcount_update(cur, &tmp);
460 	if (error)
461 		goto out_error;
462 
463 	/* Insert the left extent. */
464 	tmp = rcext;
465 	tmp.rc_blockcount = agbno - rcext.rc_startblock;
466 	error = xfs_refcount_insert(cur, &tmp, &found_rec);
467 	if (error)
468 		goto out_error;
469 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
470 		xfs_btree_mark_sick(cur);
471 		error = -EFSCORRUPTED;
472 		goto out_error;
473 	}
474 	return error;
475 
476 out_error:
477 	trace_xfs_refcount_split_extent_error(cur, error, _RET_IP_);
478 	return error;
479 }
480 
481 /*
482  * Merge the left, center, and right extents.
483  */
484 STATIC int
485 xfs_refcount_merge_center_extents(
486 	struct xfs_btree_cur		*cur,
487 	struct xfs_refcount_irec	*left,
488 	struct xfs_refcount_irec	*center,
489 	struct xfs_refcount_irec	*right,
490 	unsigned long long		extlen,
491 	xfs_extlen_t			*aglen)
492 {
493 	int				error;
494 	int				found_rec;
495 
496 	trace_xfs_refcount_merge_center_extents(cur, left, center, right);
497 
498 	ASSERT(left->rc_domain == center->rc_domain);
499 	ASSERT(right->rc_domain == center->rc_domain);
500 
501 	/*
502 	 * Make sure the center and right extents are not in the btree.
503 	 * If the center extent was synthesized, the first delete call
504 	 * removes the right extent and we skip the second deletion.
505 	 * If center and right were in the btree, then the first delete
506 	 * call removes the center and the second one removes the right
507 	 * extent.
508 	 */
509 	error = xfs_refcount_lookup_ge(cur, center->rc_domain,
510 			center->rc_startblock, &found_rec);
511 	if (error)
512 		goto out_error;
513 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
514 		xfs_btree_mark_sick(cur);
515 		error = -EFSCORRUPTED;
516 		goto out_error;
517 	}
518 
519 	error = xfs_refcount_delete(cur, &found_rec);
520 	if (error)
521 		goto out_error;
522 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
523 		xfs_btree_mark_sick(cur);
524 		error = -EFSCORRUPTED;
525 		goto out_error;
526 	}
527 
528 	if (center->rc_refcount > 1) {
529 		error = xfs_refcount_delete(cur, &found_rec);
530 		if (error)
531 			goto out_error;
532 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
533 			xfs_btree_mark_sick(cur);
534 			error = -EFSCORRUPTED;
535 			goto out_error;
536 		}
537 	}
538 
539 	/* Enlarge the left extent. */
540 	error = xfs_refcount_lookup_le(cur, left->rc_domain,
541 			left->rc_startblock, &found_rec);
542 	if (error)
543 		goto out_error;
544 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
545 		xfs_btree_mark_sick(cur);
546 		error = -EFSCORRUPTED;
547 		goto out_error;
548 	}
549 
550 	left->rc_blockcount = extlen;
551 	error = xfs_refcount_update(cur, left);
552 	if (error)
553 		goto out_error;
554 
555 	*aglen = 0;
556 	return error;
557 
558 out_error:
559 	trace_xfs_refcount_merge_center_extents_error(cur, error, _RET_IP_);
560 	return error;
561 }
562 
563 /*
564  * Merge with the left extent.
565  */
566 STATIC int
567 xfs_refcount_merge_left_extent(
568 	struct xfs_btree_cur		*cur,
569 	struct xfs_refcount_irec	*left,
570 	struct xfs_refcount_irec	*cleft,
571 	xfs_agblock_t			*agbno,
572 	xfs_extlen_t			*aglen)
573 {
574 	int				error;
575 	int				found_rec;
576 
577 	trace_xfs_refcount_merge_left_extent(cur, left, cleft);
578 
579 	ASSERT(left->rc_domain == cleft->rc_domain);
580 
581 	/* If the extent at agbno (cleft) wasn't synthesized, remove it. */
582 	if (cleft->rc_refcount > 1) {
583 		error = xfs_refcount_lookup_le(cur, cleft->rc_domain,
584 				cleft->rc_startblock, &found_rec);
585 		if (error)
586 			goto out_error;
587 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
588 			xfs_btree_mark_sick(cur);
589 			error = -EFSCORRUPTED;
590 			goto out_error;
591 		}
592 
593 		error = xfs_refcount_delete(cur, &found_rec);
594 		if (error)
595 			goto out_error;
596 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
597 			xfs_btree_mark_sick(cur);
598 			error = -EFSCORRUPTED;
599 			goto out_error;
600 		}
601 	}
602 
603 	/* Enlarge the left extent. */
604 	error = xfs_refcount_lookup_le(cur, left->rc_domain,
605 			left->rc_startblock, &found_rec);
606 	if (error)
607 		goto out_error;
608 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
609 		xfs_btree_mark_sick(cur);
610 		error = -EFSCORRUPTED;
611 		goto out_error;
612 	}
613 
614 	left->rc_blockcount += cleft->rc_blockcount;
615 	error = xfs_refcount_update(cur, left);
616 	if (error)
617 		goto out_error;
618 
619 	*agbno += cleft->rc_blockcount;
620 	*aglen -= cleft->rc_blockcount;
621 	return error;
622 
623 out_error:
624 	trace_xfs_refcount_merge_left_extent_error(cur, error, _RET_IP_);
625 	return error;
626 }
627 
628 /*
629  * Merge with the right extent.
630  */
631 STATIC int
632 xfs_refcount_merge_right_extent(
633 	struct xfs_btree_cur		*cur,
634 	struct xfs_refcount_irec	*right,
635 	struct xfs_refcount_irec	*cright,
636 	xfs_extlen_t			*aglen)
637 {
638 	int				error;
639 	int				found_rec;
640 
641 	trace_xfs_refcount_merge_right_extent(cur, cright, right);
642 
643 	ASSERT(right->rc_domain == cright->rc_domain);
644 
645 	/*
646 	 * If the extent ending at agbno+aglen (cright) wasn't synthesized,
647 	 * remove it.
648 	 */
649 	if (cright->rc_refcount > 1) {
650 		error = xfs_refcount_lookup_le(cur, cright->rc_domain,
651 				cright->rc_startblock, &found_rec);
652 		if (error)
653 			goto out_error;
654 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
655 			xfs_btree_mark_sick(cur);
656 			error = -EFSCORRUPTED;
657 			goto out_error;
658 		}
659 
660 		error = xfs_refcount_delete(cur, &found_rec);
661 		if (error)
662 			goto out_error;
663 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
664 			xfs_btree_mark_sick(cur);
665 			error = -EFSCORRUPTED;
666 			goto out_error;
667 		}
668 	}
669 
670 	/* Enlarge the right extent. */
671 	error = xfs_refcount_lookup_le(cur, right->rc_domain,
672 			right->rc_startblock, &found_rec);
673 	if (error)
674 		goto out_error;
675 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
676 		xfs_btree_mark_sick(cur);
677 		error = -EFSCORRUPTED;
678 		goto out_error;
679 	}
680 
681 	right->rc_startblock -= cright->rc_blockcount;
682 	right->rc_blockcount += cright->rc_blockcount;
683 	error = xfs_refcount_update(cur, right);
684 	if (error)
685 		goto out_error;
686 
687 	*aglen -= cright->rc_blockcount;
688 	return error;
689 
690 out_error:
691 	trace_xfs_refcount_merge_right_extent_error(cur, error, _RET_IP_);
692 	return error;
693 }
694 
695 /*
696  * Find the left extent and the one after it (cleft).  This function assumes
697  * that we've already split any extent crossing agbno.
698  */
699 STATIC int
700 xfs_refcount_find_left_extents(
701 	struct xfs_btree_cur		*cur,
702 	struct xfs_refcount_irec	*left,
703 	struct xfs_refcount_irec	*cleft,
704 	enum xfs_refc_domain		domain,
705 	xfs_agblock_t			agbno,
706 	xfs_extlen_t			aglen)
707 {
708 	struct xfs_refcount_irec	tmp;
709 	int				error;
710 	int				found_rec;
711 
712 	left->rc_startblock = cleft->rc_startblock = NULLAGBLOCK;
713 	error = xfs_refcount_lookup_le(cur, domain, agbno - 1, &found_rec);
714 	if (error)
715 		goto out_error;
716 	if (!found_rec)
717 		return 0;
718 
719 	error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
720 	if (error)
721 		goto out_error;
722 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
723 		xfs_btree_mark_sick(cur);
724 		error = -EFSCORRUPTED;
725 		goto out_error;
726 	}
727 
728 	if (tmp.rc_domain != domain)
729 		return 0;
730 	if (xfs_refc_next(&tmp) != agbno)
731 		return 0;
732 	/* We have a left extent; retrieve (or invent) the next right one */
733 	*left = tmp;
734 
735 	error = xfs_btree_increment(cur, 0, &found_rec);
736 	if (error)
737 		goto out_error;
738 	if (found_rec) {
739 		error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
740 		if (error)
741 			goto out_error;
742 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
743 			xfs_btree_mark_sick(cur);
744 			error = -EFSCORRUPTED;
745 			goto out_error;
746 		}
747 
748 		if (tmp.rc_domain != domain)
749 			goto not_found;
750 
751 		/* if tmp starts at the end of our range, just use that */
752 		if (tmp.rc_startblock == agbno)
753 			*cleft = tmp;
754 		else {
755 			/*
756 			 * There's a gap in the refcntbt at the start of the
757 			 * range we're interested in (refcount == 1) so
758 			 * synthesize the implied extent and pass it back.
759 			 * We assume here that the agbno/aglen range was
760 			 * passed in from a data fork extent mapping and
761 			 * therefore is allocated to exactly one owner.
762 			 */
763 			cleft->rc_startblock = agbno;
764 			cleft->rc_blockcount = min(aglen,
765 					tmp.rc_startblock - agbno);
766 			cleft->rc_refcount = 1;
767 			cleft->rc_domain = domain;
768 		}
769 	} else {
770 not_found:
771 		/*
772 		 * No extents, so pretend that there's one covering the whole
773 		 * range.
774 		 */
775 		cleft->rc_startblock = agbno;
776 		cleft->rc_blockcount = aglen;
777 		cleft->rc_refcount = 1;
778 		cleft->rc_domain = domain;
779 	}
780 	trace_xfs_refcount_find_left_extent(cur, left, cleft, agbno);
781 	return error;
782 
783 out_error:
784 	trace_xfs_refcount_find_left_extent_error(cur, error, _RET_IP_);
785 	return error;
786 }
787 
788 /*
789  * Find the right extent and the one before it (cright).  This function
790  * assumes that we've already split any extents crossing agbno + aglen.
791  */
792 STATIC int
793 xfs_refcount_find_right_extents(
794 	struct xfs_btree_cur		*cur,
795 	struct xfs_refcount_irec	*right,
796 	struct xfs_refcount_irec	*cright,
797 	enum xfs_refc_domain		domain,
798 	xfs_agblock_t			agbno,
799 	xfs_extlen_t			aglen)
800 {
801 	struct xfs_refcount_irec	tmp;
802 	int				error;
803 	int				found_rec;
804 
805 	right->rc_startblock = cright->rc_startblock = NULLAGBLOCK;
806 	error = xfs_refcount_lookup_ge(cur, domain, agbno + aglen, &found_rec);
807 	if (error)
808 		goto out_error;
809 	if (!found_rec)
810 		return 0;
811 
812 	error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
813 	if (error)
814 		goto out_error;
815 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
816 		xfs_btree_mark_sick(cur);
817 		error = -EFSCORRUPTED;
818 		goto out_error;
819 	}
820 
821 	if (tmp.rc_domain != domain)
822 		return 0;
823 	if (tmp.rc_startblock != agbno + aglen)
824 		return 0;
825 	/* We have a right extent; retrieve (or invent) the next left one */
826 	*right = tmp;
827 
828 	error = xfs_btree_decrement(cur, 0, &found_rec);
829 	if (error)
830 		goto out_error;
831 	if (found_rec) {
832 		error = xfs_refcount_get_rec(cur, &tmp, &found_rec);
833 		if (error)
834 			goto out_error;
835 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
836 			xfs_btree_mark_sick(cur);
837 			error = -EFSCORRUPTED;
838 			goto out_error;
839 		}
840 
841 		if (tmp.rc_domain != domain)
842 			goto not_found;
843 
844 		/* if tmp ends at the end of our range, just use that */
845 		if (xfs_refc_next(&tmp) == agbno + aglen)
846 			*cright = tmp;
847 		else {
848 			/*
849 			 * There's a gap in the refcntbt at the end of the
850 			 * range we're interested in (refcount == 1) so
851 			 * create the implied extent and pass it back.
852 			 * We assume here that the agbno/aglen range was
853 			 * passed in from a data fork extent mapping and
854 			 * therefore is allocated to exactly one owner.
855 			 */
856 			cright->rc_startblock = max(agbno, xfs_refc_next(&tmp));
857 			cright->rc_blockcount = right->rc_startblock -
858 					cright->rc_startblock;
859 			cright->rc_refcount = 1;
860 			cright->rc_domain = domain;
861 		}
862 	} else {
863 not_found:
864 		/*
865 		 * No extents, so pretend that there's one covering the whole
866 		 * range.
867 		 */
868 		cright->rc_startblock = agbno;
869 		cright->rc_blockcount = aglen;
870 		cright->rc_refcount = 1;
871 		cright->rc_domain = domain;
872 	}
873 	trace_xfs_refcount_find_right_extent(cur, cright, right,
874 			agbno + aglen);
875 	return error;
876 
877 out_error:
878 	trace_xfs_refcount_find_right_extent_error(cur, error, _RET_IP_);
879 	return error;
880 }
881 
882 /* Is this extent valid? */
883 static inline bool
884 xfs_refc_valid(
885 	const struct xfs_refcount_irec	*rc)
886 {
887 	return rc->rc_startblock != NULLAGBLOCK;
888 }
889 
890 static inline xfs_nlink_t
891 xfs_refc_merge_refcount(
892 	const struct xfs_refcount_irec	*irec,
893 	enum xfs_refc_adjust_op		adjust)
894 {
895 	/* Once a record hits XFS_REFC_REFCOUNT_MAX, it is pinned forever */
896 	if (irec->rc_refcount == XFS_REFC_REFCOUNT_MAX)
897 		return XFS_REFC_REFCOUNT_MAX;
898 	return irec->rc_refcount + adjust;
899 }
900 
901 static inline bool
902 xfs_refc_want_merge_center(
903 	const struct xfs_refcount_irec	*left,
904 	const struct xfs_refcount_irec	*cleft,
905 	const struct xfs_refcount_irec	*cright,
906 	const struct xfs_refcount_irec	*right,
907 	bool				cleft_is_cright,
908 	enum xfs_refc_adjust_op		adjust,
909 	unsigned long long		*ulenp)
910 {
911 	unsigned long long		ulen = left->rc_blockcount;
912 	xfs_nlink_t			new_refcount;
913 
914 	/*
915 	 * To merge with a center record, both shoulder records must be
916 	 * adjacent to the record we want to adjust.  This is only true if
917 	 * find_left and find_right made all four records valid.
918 	 */
919 	if (!xfs_refc_valid(left)  || !xfs_refc_valid(right) ||
920 	    !xfs_refc_valid(cleft) || !xfs_refc_valid(cright))
921 		return false;
922 
923 	/* There must only be one record for the entire range. */
924 	if (!cleft_is_cright)
925 		return false;
926 
927 	/* The shoulder record refcounts must match the new refcount. */
928 	new_refcount = xfs_refc_merge_refcount(cleft, adjust);
929 	if (left->rc_refcount != new_refcount)
930 		return false;
931 	if (right->rc_refcount != new_refcount)
932 		return false;
933 
934 	/*
935 	 * The new record cannot exceed the max length.  ulen is a ULL as the
936 	 * individual record block counts can be up to (u32 - 1) in length
937 	 * hence we need to catch u32 addition overflows here.
938 	 */
939 	ulen += cleft->rc_blockcount + right->rc_blockcount;
940 	if (ulen >= XFS_REFC_LEN_MAX)
941 		return false;
942 
943 	*ulenp = ulen;
944 	return true;
945 }
946 
947 static inline bool
948 xfs_refc_want_merge_left(
949 	const struct xfs_refcount_irec	*left,
950 	const struct xfs_refcount_irec	*cleft,
951 	enum xfs_refc_adjust_op		adjust)
952 {
953 	unsigned long long		ulen = left->rc_blockcount;
954 	xfs_nlink_t			new_refcount;
955 
956 	/*
957 	 * For a left merge, the left shoulder record must be adjacent to the
958 	 * start of the range.  If this is true, find_left made left and cleft
959 	 * contain valid contents.
960 	 */
961 	if (!xfs_refc_valid(left) || !xfs_refc_valid(cleft))
962 		return false;
963 
964 	/* Left shoulder record refcount must match the new refcount. */
965 	new_refcount = xfs_refc_merge_refcount(cleft, adjust);
966 	if (left->rc_refcount != new_refcount)
967 		return false;
968 
969 	/*
970 	 * The new record cannot exceed the max length.  ulen is a ULL as the
971 	 * individual record block counts can be up to (u32 - 1) in length
972 	 * hence we need to catch u32 addition overflows here.
973 	 */
974 	ulen += cleft->rc_blockcount;
975 	if (ulen >= XFS_REFC_LEN_MAX)
976 		return false;
977 
978 	return true;
979 }
980 
981 static inline bool
982 xfs_refc_want_merge_right(
983 	const struct xfs_refcount_irec	*cright,
984 	const struct xfs_refcount_irec	*right,
985 	enum xfs_refc_adjust_op		adjust)
986 {
987 	unsigned long long		ulen = right->rc_blockcount;
988 	xfs_nlink_t			new_refcount;
989 
990 	/*
991 	 * For a right merge, the right shoulder record must be adjacent to the
992 	 * end of the range.  If this is true, find_right made cright and right
993 	 * contain valid contents.
994 	 */
995 	if (!xfs_refc_valid(right) || !xfs_refc_valid(cright))
996 		return false;
997 
998 	/* Right shoulder record refcount must match the new refcount. */
999 	new_refcount = xfs_refc_merge_refcount(cright, adjust);
1000 	if (right->rc_refcount != new_refcount)
1001 		return false;
1002 
1003 	/*
1004 	 * The new record cannot exceed the max length.  ulen is a ULL as the
1005 	 * individual record block counts can be up to (u32 - 1) in length
1006 	 * hence we need to catch u32 addition overflows here.
1007 	 */
1008 	ulen += cright->rc_blockcount;
1009 	if (ulen >= XFS_REFC_LEN_MAX)
1010 		return false;
1011 
1012 	return true;
1013 }
1014 
1015 /*
1016  * Try to merge with any extents on the boundaries of the adjustment range.
1017  */
1018 STATIC int
1019 xfs_refcount_merge_extents(
1020 	struct xfs_btree_cur	*cur,
1021 	enum xfs_refc_domain	domain,
1022 	xfs_agblock_t		*agbno,
1023 	xfs_extlen_t		*aglen,
1024 	enum xfs_refc_adjust_op adjust,
1025 	bool			*shape_changed)
1026 {
1027 	struct xfs_refcount_irec	left = {0}, cleft = {0};
1028 	struct xfs_refcount_irec	cright = {0}, right = {0};
1029 	int				error;
1030 	unsigned long long		ulen;
1031 	bool				cequal;
1032 
1033 	*shape_changed = false;
1034 	/*
1035 	 * Find the extent just below agbno [left], just above agbno [cleft],
1036 	 * just below (agbno + aglen) [cright], and just above (agbno + aglen)
1037 	 * [right].
1038 	 */
1039 	error = xfs_refcount_find_left_extents(cur, &left, &cleft, domain,
1040 			*agbno, *aglen);
1041 	if (error)
1042 		return error;
1043 	error = xfs_refcount_find_right_extents(cur, &right, &cright, domain,
1044 			*agbno, *aglen);
1045 	if (error)
1046 		return error;
1047 
1048 	/* No left or right extent to merge; exit. */
1049 	if (!xfs_refc_valid(&left) && !xfs_refc_valid(&right))
1050 		return 0;
1051 
1052 	cequal = (cleft.rc_startblock == cright.rc_startblock) &&
1053 		 (cleft.rc_blockcount == cright.rc_blockcount);
1054 
1055 	/* Try to merge left, cleft, and right.  cleft must == cright. */
1056 	if (xfs_refc_want_merge_center(&left, &cleft, &cright, &right, cequal,
1057 				adjust, &ulen)) {
1058 		*shape_changed = true;
1059 		return xfs_refcount_merge_center_extents(cur, &left, &cleft,
1060 				&right, ulen, aglen);
1061 	}
1062 
1063 	/* Try to merge left and cleft. */
1064 	if (xfs_refc_want_merge_left(&left, &cleft, adjust)) {
1065 		*shape_changed = true;
1066 		error = xfs_refcount_merge_left_extent(cur, &left, &cleft,
1067 				agbno, aglen);
1068 		if (error)
1069 			return error;
1070 
1071 		/*
1072 		 * If we just merged left + cleft and cleft == cright,
1073 		 * we no longer have a cright to merge with right.  We're done.
1074 		 */
1075 		if (cequal)
1076 			return 0;
1077 	}
1078 
1079 	/* Try to merge cright and right. */
1080 	if (xfs_refc_want_merge_right(&cright, &right, adjust)) {
1081 		*shape_changed = true;
1082 		return xfs_refcount_merge_right_extent(cur, &right, &cright,
1083 				aglen);
1084 	}
1085 
1086 	return 0;
1087 }
1088 
1089 /*
1090  * XXX: This is a pretty hand-wavy estimate.  The penalty for guessing
1091  * true incorrectly is a shutdown FS; the penalty for guessing false
1092  * incorrectly is more transaction rolls than might be necessary.
1093  * Be conservative here.
1094  */
1095 static bool
1096 xfs_refcount_still_have_space(
1097 	struct xfs_btree_cur		*cur)
1098 {
1099 	unsigned long			overhead;
1100 
1101 	/*
1102 	 * Worst case estimate: full splits of the free space and rmap btrees
1103 	 * to handle each of the shape changes to the refcount btree.
1104 	 */
1105 	overhead = xfs_allocfree_block_count(cur->bc_mp,
1106 				cur->bc_refc.shape_changes);
1107 	overhead += cur->bc_maxlevels;
1108 	overhead *= cur->bc_mp->m_sb.sb_blocksize;
1109 
1110 	/*
1111 	 * Only allow 2 refcount extent updates per transaction if the
1112 	 * refcount continue update "error" has been injected.
1113 	 */
1114 	if (cur->bc_refc.nr_ops > 2 &&
1115 	    XFS_TEST_ERROR(cur->bc_mp, XFS_ERRTAG_REFCOUNT_CONTINUE_UPDATE))
1116 		return false;
1117 
1118 	if (cur->bc_refc.nr_ops == 0)
1119 		return true;
1120 	else if (overhead > cur->bc_tp->t_log_res)
1121 		return false;
1122 	return cur->bc_tp->t_log_res - overhead >
1123 		cur->bc_refc.nr_ops * XFS_REFCOUNT_ITEM_OVERHEAD;
1124 }
1125 
1126 /* Schedule an extent free. */
1127 static int
1128 xrefc_free_extent(
1129 	struct xfs_btree_cur		*cur,
1130 	struct xfs_refcount_irec	*rec)
1131 {
1132 	unsigned int			flags = 0;
1133 
1134 	if (xfs_btree_is_rtrefcount(cur->bc_ops))
1135 		flags |= XFS_FREE_EXTENT_REALTIME;
1136 
1137 	return xfs_free_extent_later(cur->bc_tp,
1138 			xfs_gbno_to_fsb(cur->bc_group, rec->rc_startblock),
1139 			rec->rc_blockcount, NULL, XFS_AG_RESV_NONE, flags);
1140 }
1141 
1142 /*
1143  * Adjust the refcounts of middle extents.  At this point we should have
1144  * split extents that crossed the adjustment range; merged with adjacent
1145  * extents; and updated agbno/aglen to reflect the merges.  Therefore,
1146  * all we have to do is update the extents inside [agbno, agbno + aglen].
1147  */
1148 STATIC int
1149 xfs_refcount_adjust_extents(
1150 	struct xfs_btree_cur	*cur,
1151 	xfs_agblock_t		*agbno,
1152 	xfs_extlen_t		*aglen,
1153 	enum xfs_refc_adjust_op	adj)
1154 {
1155 	struct xfs_refcount_irec	ext, tmp;
1156 	int				error;
1157 	int				found_rec, found_tmp;
1158 
1159 	/* Merging did all the work already. */
1160 	if (*aglen == 0)
1161 		return 0;
1162 
1163 	error = xfs_refcount_lookup_ge(cur, XFS_REFC_DOMAIN_SHARED, *agbno,
1164 			&found_rec);
1165 	if (error)
1166 		goto out_error;
1167 
1168 	while (*aglen > 0 && xfs_refcount_still_have_space(cur)) {
1169 		error = xfs_refcount_get_rec(cur, &ext, &found_rec);
1170 		if (error)
1171 			goto out_error;
1172 		if (!found_rec || ext.rc_domain != XFS_REFC_DOMAIN_SHARED) {
1173 			ext.rc_startblock = xfs_group_max_blocks(cur->bc_group);
1174 			ext.rc_blockcount = 0;
1175 			ext.rc_refcount = 0;
1176 			ext.rc_domain = XFS_REFC_DOMAIN_SHARED;
1177 		}
1178 
1179 		/*
1180 		 * Deal with a hole in the refcount tree; if a file maps to
1181 		 * these blocks and there's no refcountbt record, pretend that
1182 		 * there is one with refcount == 1.
1183 		 */
1184 		if (ext.rc_startblock != *agbno) {
1185 			tmp.rc_startblock = *agbno;
1186 			tmp.rc_blockcount = min(*aglen,
1187 					ext.rc_startblock - *agbno);
1188 			tmp.rc_refcount = 1 + adj;
1189 			tmp.rc_domain = XFS_REFC_DOMAIN_SHARED;
1190 
1191 			trace_xfs_refcount_modify_extent(cur, &tmp);
1192 
1193 			/*
1194 			 * Either cover the hole (increment) or
1195 			 * delete the range (decrement).
1196 			 */
1197 			cur->bc_refc.nr_ops++;
1198 			if (tmp.rc_refcount) {
1199 				error = xfs_refcount_insert(cur, &tmp,
1200 						&found_tmp);
1201 				if (error)
1202 					goto out_error;
1203 				if (XFS_IS_CORRUPT(cur->bc_mp,
1204 						   found_tmp != 1)) {
1205 					xfs_btree_mark_sick(cur);
1206 					error = -EFSCORRUPTED;
1207 					goto out_error;
1208 				}
1209 			} else {
1210 				error = xrefc_free_extent(cur, &tmp);
1211 				if (error)
1212 					goto out_error;
1213 			}
1214 
1215 			(*agbno) += tmp.rc_blockcount;
1216 			(*aglen) -= tmp.rc_blockcount;
1217 
1218 			/* Stop if there's nothing left to modify */
1219 			if (*aglen == 0 || !xfs_refcount_still_have_space(cur))
1220 				break;
1221 
1222 			/* Move the cursor to the start of ext. */
1223 			error = xfs_refcount_lookup_ge(cur,
1224 					XFS_REFC_DOMAIN_SHARED, *agbno,
1225 					&found_rec);
1226 			if (error)
1227 				goto out_error;
1228 		}
1229 
1230 		/*
1231 		 * A previous step trimmed agbno/aglen such that the end of the
1232 		 * range would not be in the middle of the record.  If this is
1233 		 * no longer the case, something is seriously wrong with the
1234 		 * btree.  Make sure we never feed the synthesized record into
1235 		 * the processing loop below.
1236 		 */
1237 		if (XFS_IS_CORRUPT(cur->bc_mp, ext.rc_blockcount == 0) ||
1238 		    XFS_IS_CORRUPT(cur->bc_mp, ext.rc_blockcount > *aglen)) {
1239 			xfs_btree_mark_sick(cur);
1240 			error = -EFSCORRUPTED;
1241 			goto out_error;
1242 		}
1243 
1244 		/*
1245 		 * Adjust the reference count and either update the tree
1246 		 * (incr) or free the blocks (decr).
1247 		 */
1248 		if (ext.rc_refcount == XFS_REFC_REFCOUNT_MAX)
1249 			goto skip;
1250 		ext.rc_refcount += adj;
1251 		trace_xfs_refcount_modify_extent(cur, &ext);
1252 		cur->bc_refc.nr_ops++;
1253 		if (ext.rc_refcount > 1) {
1254 			error = xfs_refcount_update(cur, &ext);
1255 			if (error)
1256 				goto out_error;
1257 		} else if (ext.rc_refcount == 1) {
1258 			error = xfs_refcount_delete(cur, &found_rec);
1259 			if (error)
1260 				goto out_error;
1261 			if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
1262 				xfs_btree_mark_sick(cur);
1263 				error = -EFSCORRUPTED;
1264 				goto out_error;
1265 			}
1266 			goto advloop;
1267 		} else {
1268 			error = xrefc_free_extent(cur, &ext);
1269 			if (error)
1270 				goto out_error;
1271 		}
1272 
1273 skip:
1274 		error = xfs_btree_increment(cur, 0, &found_rec);
1275 		if (error)
1276 			goto out_error;
1277 
1278 advloop:
1279 		(*agbno) += ext.rc_blockcount;
1280 		(*aglen) -= ext.rc_blockcount;
1281 	}
1282 
1283 	return error;
1284 out_error:
1285 	trace_xfs_refcount_modify_extent_error(cur, error, _RET_IP_);
1286 	return error;
1287 }
1288 
1289 /* Adjust the reference count of a range of AG blocks. */
1290 STATIC int
1291 xfs_refcount_adjust(
1292 	struct xfs_btree_cur	*cur,
1293 	xfs_agblock_t		*agbno,
1294 	xfs_extlen_t		*aglen,
1295 	enum xfs_refc_adjust_op	adj)
1296 {
1297 	bool			shape_changed;
1298 	int			shape_changes = 0;
1299 	int			error;
1300 
1301 	if (adj == XFS_REFCOUNT_ADJUST_INCREASE)
1302 		trace_xfs_refcount_increase(cur, *agbno, *aglen);
1303 	else
1304 		trace_xfs_refcount_decrease(cur, *agbno, *aglen);
1305 
1306 	/*
1307 	 * Ensure that no rcextents cross the boundary of the adjustment range.
1308 	 */
1309 	error = xfs_refcount_split_extent(cur, XFS_REFC_DOMAIN_SHARED,
1310 			*agbno, &shape_changed);
1311 	if (error)
1312 		goto out_error;
1313 	if (shape_changed)
1314 		shape_changes++;
1315 
1316 	error = xfs_refcount_split_extent(cur, XFS_REFC_DOMAIN_SHARED,
1317 			*agbno + *aglen, &shape_changed);
1318 	if (error)
1319 		goto out_error;
1320 	if (shape_changed)
1321 		shape_changes++;
1322 
1323 	/*
1324 	 * Try to merge with the left or right extents of the range.
1325 	 */
1326 	error = xfs_refcount_merge_extents(cur, XFS_REFC_DOMAIN_SHARED,
1327 			agbno, aglen, adj, &shape_changed);
1328 	if (error)
1329 		goto out_error;
1330 	if (shape_changed)
1331 		shape_changes++;
1332 	if (shape_changes)
1333 		cur->bc_refc.shape_changes++;
1334 
1335 	/* Now that we've taken care of the ends, adjust the middle extents */
1336 	error = xfs_refcount_adjust_extents(cur, agbno, aglen, adj);
1337 	if (error)
1338 		goto out_error;
1339 
1340 	return 0;
1341 
1342 out_error:
1343 	trace_xfs_refcount_adjust_error(cur, error, _RET_IP_);
1344 	return error;
1345 }
1346 
1347 /*
1348  * Set up a continuation a deferred refcount operation by updating the intent.
1349  * Checks to make sure we're not going to run off the end of the AG.
1350  */
1351 static inline int
1352 xfs_refcount_continue_op(
1353 	struct xfs_btree_cur		*cur,
1354 	struct xfs_refcount_intent	*ri,
1355 	xfs_agblock_t			new_agbno)
1356 {
1357 	struct xfs_mount		*mp = cur->bc_mp;
1358 	struct xfs_perag		*pag = to_perag(cur->bc_group);
1359 
1360 	if (XFS_IS_CORRUPT(mp, !xfs_verify_agbext(pag, new_agbno,
1361 					ri->ri_blockcount))) {
1362 		xfs_btree_mark_sick(cur);
1363 		return -EFSCORRUPTED;
1364 	}
1365 
1366 	ri->ri_startblock = xfs_agbno_to_fsb(pag, new_agbno);
1367 
1368 	ASSERT(xfs_verify_fsbext(mp, ri->ri_startblock, ri->ri_blockcount));
1369 	ASSERT(pag_agno(pag) == XFS_FSB_TO_AGNO(mp, ri->ri_startblock));
1370 
1371 	return 0;
1372 }
1373 
1374 /*
1375  * Process one of the deferred refcount operations.  We pass back the
1376  * btree cursor to maintain our lock on the btree between calls.
1377  * This saves time and eliminates a buffer deadlock between the
1378  * superblock and the AGF because we'll always grab them in the same
1379  * order.
1380  */
1381 int
1382 xfs_refcount_finish_one(
1383 	struct xfs_trans		*tp,
1384 	struct xfs_refcount_intent	*ri,
1385 	struct xfs_btree_cur		**pcur)
1386 {
1387 	struct xfs_mount		*mp = tp->t_mountp;
1388 	struct xfs_btree_cur		*rcur = *pcur;
1389 	struct xfs_buf			*agbp = NULL;
1390 	int				error = 0;
1391 	xfs_agblock_t			bno;
1392 	unsigned long			nr_ops = 0;
1393 	int				shape_changes = 0;
1394 
1395 	bno = XFS_FSB_TO_AGBNO(mp, ri->ri_startblock);
1396 
1397 	trace_xfs_refcount_deferred(mp, ri);
1398 
1399 	if (XFS_TEST_ERROR(mp, XFS_ERRTAG_REFCOUNT_FINISH_ONE))
1400 		return -EIO;
1401 
1402 	/*
1403 	 * If we haven't gotten a cursor or the cursor AG doesn't match
1404 	 * the startblock, get one now.
1405 	 */
1406 	if (rcur != NULL && rcur->bc_group != ri->ri_group) {
1407 		nr_ops = rcur->bc_refc.nr_ops;
1408 		shape_changes = rcur->bc_refc.shape_changes;
1409 		xfs_btree_del_cursor(rcur, 0);
1410 		rcur = NULL;
1411 		*pcur = NULL;
1412 	}
1413 	if (rcur == NULL) {
1414 		struct xfs_perag	*pag = to_perag(ri->ri_group);
1415 
1416 		error = xfs_alloc_read_agf(pag, tp, 0, &agbp);
1417 		if (error)
1418 			return error;
1419 
1420 		*pcur = rcur = xfs_refcountbt_init_cursor(mp, tp, agbp, pag);
1421 		rcur->bc_refc.nr_ops = nr_ops;
1422 		rcur->bc_refc.shape_changes = shape_changes;
1423 	}
1424 
1425 	switch (ri->ri_type) {
1426 	case XFS_REFCOUNT_INCREASE:
1427 		error = xfs_refcount_adjust(rcur, &bno, &ri->ri_blockcount,
1428 				XFS_REFCOUNT_ADJUST_INCREASE);
1429 		if (error)
1430 			return error;
1431 		if (ri->ri_blockcount > 0)
1432 			error = xfs_refcount_continue_op(rcur, ri, bno);
1433 		break;
1434 	case XFS_REFCOUNT_DECREASE:
1435 		error = xfs_refcount_adjust(rcur, &bno, &ri->ri_blockcount,
1436 				XFS_REFCOUNT_ADJUST_DECREASE);
1437 		if (error)
1438 			return error;
1439 		if (ri->ri_blockcount > 0)
1440 			error = xfs_refcount_continue_op(rcur, ri, bno);
1441 		break;
1442 	case XFS_REFCOUNT_ALLOC_COW:
1443 		error = __xfs_refcount_cow_alloc(rcur, bno, ri->ri_blockcount);
1444 		if (error)
1445 			return error;
1446 		ri->ri_blockcount = 0;
1447 		break;
1448 	case XFS_REFCOUNT_FREE_COW:
1449 		error = __xfs_refcount_cow_free(rcur, bno, ri->ri_blockcount);
1450 		if (error)
1451 			return error;
1452 		ri->ri_blockcount = 0;
1453 		break;
1454 	default:
1455 		ASSERT(0);
1456 		return -EFSCORRUPTED;
1457 	}
1458 	if (!error && ri->ri_blockcount > 0)
1459 		trace_xfs_refcount_finish_one_leftover(mp, ri);
1460 	return error;
1461 }
1462 
1463 /*
1464  * Set up a continuation a deferred rtrefcount operation by updating the
1465  * intent.  Checks to make sure we're not going to run off the end of the
1466  * rtgroup.
1467  */
1468 static inline int
1469 xfs_rtrefcount_continue_op(
1470 	struct xfs_btree_cur		*cur,
1471 	struct xfs_refcount_intent	*ri,
1472 	xfs_agblock_t			new_agbno)
1473 {
1474 	struct xfs_mount		*mp = cur->bc_mp;
1475 	struct xfs_rtgroup		*rtg = to_rtg(ri->ri_group);
1476 
1477 	if (XFS_IS_CORRUPT(mp, !xfs_verify_rgbext(rtg, new_agbno,
1478 					ri->ri_blockcount))) {
1479 		xfs_btree_mark_sick(cur);
1480 		return -EFSCORRUPTED;
1481 	}
1482 
1483 	ri->ri_startblock = xfs_rgbno_to_rtb(rtg, new_agbno);
1484 
1485 	ASSERT(xfs_verify_rtbext(mp, ri->ri_startblock, ri->ri_blockcount));
1486 	return 0;
1487 }
1488 
1489 /*
1490  * Process one of the deferred realtime refcount operations.  We pass back the
1491  * btree cursor to maintain our lock on the btree between calls.
1492  */
1493 int
1494 xfs_rtrefcount_finish_one(
1495 	struct xfs_trans		*tp,
1496 	struct xfs_refcount_intent	*ri,
1497 	struct xfs_btree_cur		**pcur)
1498 {
1499 	struct xfs_mount		*mp = tp->t_mountp;
1500 	struct xfs_rtgroup		*rtg = to_rtg(ri->ri_group);
1501 	struct xfs_btree_cur		*rcur = *pcur;
1502 	int				error = 0;
1503 	xfs_rgblock_t			bno;
1504 	unsigned long			nr_ops = 0;
1505 	int				shape_changes = 0;
1506 
1507 	bno = xfs_rtb_to_rgbno(mp, ri->ri_startblock);
1508 
1509 	trace_xfs_refcount_deferred(mp, ri);
1510 
1511 	if (XFS_TEST_ERROR(mp, XFS_ERRTAG_REFCOUNT_FINISH_ONE))
1512 		return -EIO;
1513 
1514 	/*
1515 	 * If we haven't gotten a cursor or the cursor AG doesn't match
1516 	 * the startblock, get one now.
1517 	 */
1518 	if (rcur != NULL && rcur->bc_group != ri->ri_group) {
1519 		nr_ops = rcur->bc_refc.nr_ops;
1520 		shape_changes = rcur->bc_refc.shape_changes;
1521 		xfs_btree_del_cursor(rcur, 0);
1522 		rcur = NULL;
1523 		*pcur = NULL;
1524 	}
1525 	if (rcur == NULL) {
1526 		xfs_rtgroup_lock(rtg, XFS_RTGLOCK_REFCOUNT);
1527 		xfs_rtgroup_trans_join(tp, rtg, XFS_RTGLOCK_REFCOUNT);
1528 		*pcur = rcur = xfs_rtrefcountbt_init_cursor(tp, rtg);
1529 
1530 		rcur->bc_refc.nr_ops = nr_ops;
1531 		rcur->bc_refc.shape_changes = shape_changes;
1532 	}
1533 
1534 	switch (ri->ri_type) {
1535 	case XFS_REFCOUNT_INCREASE:
1536 		error = xfs_refcount_adjust(rcur, &bno, &ri->ri_blockcount,
1537 				XFS_REFCOUNT_ADJUST_INCREASE);
1538 		if (error)
1539 			return error;
1540 		if (ri->ri_blockcount > 0)
1541 			error = xfs_rtrefcount_continue_op(rcur, ri, bno);
1542 		break;
1543 	case XFS_REFCOUNT_DECREASE:
1544 		error = xfs_refcount_adjust(rcur, &bno, &ri->ri_blockcount,
1545 				XFS_REFCOUNT_ADJUST_DECREASE);
1546 		if (error)
1547 			return error;
1548 		if (ri->ri_blockcount > 0)
1549 			error = xfs_rtrefcount_continue_op(rcur, ri, bno);
1550 		break;
1551 	case XFS_REFCOUNT_ALLOC_COW:
1552 		error = __xfs_refcount_cow_alloc(rcur, bno, ri->ri_blockcount);
1553 		if (error)
1554 			return error;
1555 		ri->ri_blockcount = 0;
1556 		break;
1557 	case XFS_REFCOUNT_FREE_COW:
1558 		error = __xfs_refcount_cow_free(rcur, bno, ri->ri_blockcount);
1559 		if (error)
1560 			return error;
1561 		ri->ri_blockcount = 0;
1562 		break;
1563 	default:
1564 		ASSERT(0);
1565 		return -EFSCORRUPTED;
1566 	}
1567 	if (!error && ri->ri_blockcount > 0)
1568 		trace_xfs_refcount_finish_one_leftover(mp, ri);
1569 	return error;
1570 }
1571 
1572 /*
1573  * Record a refcount intent for later processing.
1574  */
1575 static void
1576 __xfs_refcount_add(
1577 	struct xfs_trans		*tp,
1578 	enum xfs_refcount_intent_type	type,
1579 	bool				isrt,
1580 	xfs_fsblock_t			startblock,
1581 	xfs_extlen_t			blockcount)
1582 {
1583 	struct xfs_refcount_intent	*ri;
1584 
1585 	ri = kmem_cache_alloc(xfs_refcount_intent_cache,
1586 			GFP_KERNEL | __GFP_NOFAIL);
1587 	INIT_LIST_HEAD(&ri->ri_list);
1588 	ri->ri_type = type;
1589 	ri->ri_startblock = startblock;
1590 	ri->ri_blockcount = blockcount;
1591 	ri->ri_realtime = isrt;
1592 
1593 	xfs_refcount_defer_add(tp, ri);
1594 }
1595 
1596 /*
1597  * Increase the reference count of the blocks backing a file's extent.
1598  */
1599 void
1600 xfs_refcount_increase_extent(
1601 	struct xfs_trans		*tp,
1602 	bool				isrt,
1603 	struct xfs_bmbt_irec		*PREV)
1604 {
1605 	if (!xfs_has_reflink(tp->t_mountp))
1606 		return;
1607 
1608 	__xfs_refcount_add(tp, XFS_REFCOUNT_INCREASE, isrt, PREV->br_startblock,
1609 			PREV->br_blockcount);
1610 }
1611 
1612 /*
1613  * Decrease the reference count of the blocks backing a file's extent.
1614  */
1615 void
1616 xfs_refcount_decrease_extent(
1617 	struct xfs_trans		*tp,
1618 	bool				isrt,
1619 	struct xfs_bmbt_irec		*PREV)
1620 {
1621 	if (!xfs_has_reflink(tp->t_mountp))
1622 		return;
1623 
1624 	__xfs_refcount_add(tp, XFS_REFCOUNT_DECREASE, isrt, PREV->br_startblock,
1625 			PREV->br_blockcount);
1626 }
1627 
1628 /*
1629  * Given an AG extent, find the lowest-numbered run of shared blocks
1630  * within that range and return the range in fbno/flen.  If
1631  * find_end_of_shared is set, return the longest contiguous extent of
1632  * shared blocks; if not, just return the first extent we find.  If no
1633  * shared blocks are found, fbno and flen will be set to NULLAGBLOCK
1634  * and 0, respectively.
1635  */
1636 int
1637 xfs_refcount_find_shared(
1638 	struct xfs_btree_cur		*cur,
1639 	xfs_agblock_t			agbno,
1640 	xfs_extlen_t			aglen,
1641 	xfs_agblock_t			*fbno,
1642 	xfs_extlen_t			*flen,
1643 	bool				find_end_of_shared)
1644 {
1645 	struct xfs_refcount_irec	tmp;
1646 	int				i;
1647 	int				have;
1648 	int				error;
1649 
1650 	trace_xfs_refcount_find_shared(cur, agbno, aglen);
1651 
1652 	/* By default, skip the whole range */
1653 	*fbno = NULLAGBLOCK;
1654 	*flen = 0;
1655 
1656 	/* Try to find a refcount extent that crosses the start */
1657 	error = xfs_refcount_lookup_le(cur, XFS_REFC_DOMAIN_SHARED, agbno,
1658 			&have);
1659 	if (error)
1660 		goto out_error;
1661 	if (!have) {
1662 		/* No left extent, look at the next one */
1663 		error = xfs_btree_increment(cur, 0, &have);
1664 		if (error)
1665 			goto out_error;
1666 		if (!have)
1667 			goto done;
1668 	}
1669 	error = xfs_refcount_get_rec(cur, &tmp, &i);
1670 	if (error)
1671 		goto out_error;
1672 	if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1673 		xfs_btree_mark_sick(cur);
1674 		error = -EFSCORRUPTED;
1675 		goto out_error;
1676 	}
1677 	if (tmp.rc_domain != XFS_REFC_DOMAIN_SHARED)
1678 		goto done;
1679 
1680 	/* If the extent ends before the start, look at the next one */
1681 	if (tmp.rc_startblock + tmp.rc_blockcount <= agbno) {
1682 		error = xfs_btree_increment(cur, 0, &have);
1683 		if (error)
1684 			goto out_error;
1685 		if (!have)
1686 			goto done;
1687 		error = xfs_refcount_get_rec(cur, &tmp, &i);
1688 		if (error)
1689 			goto out_error;
1690 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1691 			xfs_btree_mark_sick(cur);
1692 			error = -EFSCORRUPTED;
1693 			goto out_error;
1694 		}
1695 		if (tmp.rc_domain != XFS_REFC_DOMAIN_SHARED)
1696 			goto done;
1697 	}
1698 
1699 	/* If the extent starts after the range we want, bail out */
1700 	if (tmp.rc_startblock >= agbno + aglen)
1701 		goto done;
1702 
1703 	/* We found the start of a shared extent! */
1704 	if (tmp.rc_startblock < agbno) {
1705 		tmp.rc_blockcount -= (agbno - tmp.rc_startblock);
1706 		tmp.rc_startblock = agbno;
1707 	}
1708 
1709 	*fbno = tmp.rc_startblock;
1710 	*flen = min(tmp.rc_blockcount, agbno + aglen - *fbno);
1711 	if (!find_end_of_shared)
1712 		goto done;
1713 
1714 	/* Otherwise, find the end of this shared extent */
1715 	while (*fbno + *flen < agbno + aglen) {
1716 		error = xfs_btree_increment(cur, 0, &have);
1717 		if (error)
1718 			goto out_error;
1719 		if (!have)
1720 			break;
1721 		error = xfs_refcount_get_rec(cur, &tmp, &i);
1722 		if (error)
1723 			goto out_error;
1724 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1725 			xfs_btree_mark_sick(cur);
1726 			error = -EFSCORRUPTED;
1727 			goto out_error;
1728 		}
1729 		if (tmp.rc_domain != XFS_REFC_DOMAIN_SHARED ||
1730 		    tmp.rc_startblock >= agbno + aglen ||
1731 		    tmp.rc_startblock != *fbno + *flen)
1732 			break;
1733 		*flen = min(*flen + tmp.rc_blockcount, agbno + aglen - *fbno);
1734 	}
1735 
1736 done:
1737 	trace_xfs_refcount_find_shared_result(cur, *fbno, *flen);
1738 
1739 out_error:
1740 	if (error)
1741 		trace_xfs_refcount_find_shared_error(cur, error, _RET_IP_);
1742 	return error;
1743 }
1744 
1745 /*
1746  * Recovering CoW Blocks After a Crash
1747  *
1748  * Due to the way that the copy on write mechanism works, there's a window of
1749  * opportunity in which we can lose track of allocated blocks during a crash.
1750  * Because CoW uses delayed allocation in the in-core CoW fork, writeback
1751  * causes blocks to be allocated and stored in the CoW fork.  The blocks are
1752  * no longer in the free space btree but are not otherwise recorded anywhere
1753  * until the write completes and the blocks are mapped into the file.  A crash
1754  * in between allocation and remapping results in the replacement blocks being
1755  * lost.  This situation is exacerbated by the CoW extent size hint because
1756  * allocations can hang around for long time.
1757  *
1758  * However, there is a place where we can record these allocations before they
1759  * become mappings -- the reference count btree.  The btree does not record
1760  * extents with refcount == 1, so we can record allocations with a refcount of
1761  * 1.  Blocks being used for CoW writeout cannot be shared, so there should be
1762  * no conflict with shared block records.  These mappings should be created
1763  * when we allocate blocks to the CoW fork and deleted when they're removed
1764  * from the CoW fork.
1765  *
1766  * Minor nit: records for in-progress CoW allocations and records for shared
1767  * extents must never be merged, to preserve the property that (except for CoW
1768  * allocations) there are no refcount btree entries with refcount == 1.  The
1769  * only time this could potentially happen is when unsharing a block that's
1770  * adjacent to CoW allocations, so we must be careful to avoid this.
1771  *
1772  * At mount time we recover lost CoW allocations by searching the refcount
1773  * btree for these refcount == 1 mappings.  These represent CoW allocations
1774  * that were in progress at the time the filesystem went down, so we can free
1775  * them to get the space back.
1776  *
1777  * This mechanism is superior to creating EFIs for unmapped CoW extents for
1778  * several reasons -- first, EFIs pin the tail of the log and would have to be
1779  * periodically relogged to avoid filling up the log.  Second, CoW completions
1780  * will have to file an EFD and create new EFIs for whatever remains in the
1781  * CoW fork; this partially takes care of (1) but extent-size reservations
1782  * will have to periodically relog even if there's no writeout in progress.
1783  * This can happen if the CoW extent size hint is set, which you really want.
1784  * Third, EFIs cannot currently be automatically relogged into newer
1785  * transactions to advance the log tail.  Fourth, stuffing the log full of
1786  * EFIs places an upper bound on the number of CoW allocations that can be
1787  * held filesystem-wide at any given time.  Recording them in the refcount
1788  * btree doesn't require us to maintain any state in memory and doesn't pin
1789  * the log.
1790  */
1791 /*
1792  * Adjust the refcounts of CoW allocations.  These allocations are "magic"
1793  * in that they're not referenced anywhere else in the filesystem, so we
1794  * stash them in the refcount btree with a refcount of 1 until either file
1795  * remapping (or CoW cancellation) happens.
1796  */
1797 STATIC int
1798 xfs_refcount_adjust_cow_extents(
1799 	struct xfs_btree_cur	*cur,
1800 	xfs_agblock_t		agbno,
1801 	xfs_extlen_t		aglen,
1802 	enum xfs_refc_adjust_op	adj)
1803 {
1804 	struct xfs_refcount_irec	ext, tmp;
1805 	int				error;
1806 	int				found_rec, found_tmp;
1807 
1808 	if (aglen == 0)
1809 		return 0;
1810 
1811 	/* Find any overlapping refcount records */
1812 	error = xfs_refcount_lookup_ge(cur, XFS_REFC_DOMAIN_COW, agbno,
1813 			&found_rec);
1814 	if (error)
1815 		goto out_error;
1816 	error = xfs_refcount_get_rec(cur, &ext, &found_rec);
1817 	if (error)
1818 		goto out_error;
1819 	if (XFS_IS_CORRUPT(cur->bc_mp, found_rec &&
1820 				ext.rc_domain != XFS_REFC_DOMAIN_COW)) {
1821 		xfs_btree_mark_sick(cur);
1822 		error = -EFSCORRUPTED;
1823 		goto out_error;
1824 	}
1825 	if (!found_rec) {
1826 		ext.rc_startblock = xfs_group_max_blocks(cur->bc_group);
1827 		ext.rc_blockcount = 0;
1828 		ext.rc_refcount = 0;
1829 		ext.rc_domain = XFS_REFC_DOMAIN_COW;
1830 	}
1831 
1832 	switch (adj) {
1833 	case XFS_REFCOUNT_ADJUST_COW_ALLOC:
1834 		/* Adding a CoW reservation, there should be nothing here. */
1835 		if (XFS_IS_CORRUPT(cur->bc_mp,
1836 				   agbno + aglen > ext.rc_startblock)) {
1837 			xfs_btree_mark_sick(cur);
1838 			error = -EFSCORRUPTED;
1839 			goto out_error;
1840 		}
1841 
1842 		tmp.rc_startblock = agbno;
1843 		tmp.rc_blockcount = aglen;
1844 		tmp.rc_refcount = 1;
1845 		tmp.rc_domain = XFS_REFC_DOMAIN_COW;
1846 
1847 		trace_xfs_refcount_modify_extent(cur, &tmp);
1848 
1849 		error = xfs_refcount_insert(cur, &tmp,
1850 				&found_tmp);
1851 		if (error)
1852 			goto out_error;
1853 		if (XFS_IS_CORRUPT(cur->bc_mp, found_tmp != 1)) {
1854 			xfs_btree_mark_sick(cur);
1855 			error = -EFSCORRUPTED;
1856 			goto out_error;
1857 		}
1858 		break;
1859 	case XFS_REFCOUNT_ADJUST_COW_FREE:
1860 		/* Removing a CoW reservation, there should be one extent. */
1861 		if (XFS_IS_CORRUPT(cur->bc_mp, ext.rc_startblock != agbno)) {
1862 			xfs_btree_mark_sick(cur);
1863 			error = -EFSCORRUPTED;
1864 			goto out_error;
1865 		}
1866 		if (XFS_IS_CORRUPT(cur->bc_mp, ext.rc_blockcount != aglen)) {
1867 			xfs_btree_mark_sick(cur);
1868 			error = -EFSCORRUPTED;
1869 			goto out_error;
1870 		}
1871 		if (XFS_IS_CORRUPT(cur->bc_mp, ext.rc_refcount != 1)) {
1872 			xfs_btree_mark_sick(cur);
1873 			error = -EFSCORRUPTED;
1874 			goto out_error;
1875 		}
1876 
1877 		ext.rc_refcount = 0;
1878 		trace_xfs_refcount_modify_extent(cur, &ext);
1879 		error = xfs_refcount_delete(cur, &found_rec);
1880 		if (error)
1881 			goto out_error;
1882 		if (XFS_IS_CORRUPT(cur->bc_mp, found_rec != 1)) {
1883 			xfs_btree_mark_sick(cur);
1884 			error = -EFSCORRUPTED;
1885 			goto out_error;
1886 		}
1887 		break;
1888 	default:
1889 		ASSERT(0);
1890 	}
1891 
1892 	return error;
1893 out_error:
1894 	trace_xfs_refcount_modify_extent_error(cur, error, _RET_IP_);
1895 	return error;
1896 }
1897 
1898 /*
1899  * Add or remove refcount btree entries for CoW reservations.
1900  */
1901 STATIC int
1902 xfs_refcount_adjust_cow(
1903 	struct xfs_btree_cur	*cur,
1904 	xfs_agblock_t		agbno,
1905 	xfs_extlen_t		aglen,
1906 	enum xfs_refc_adjust_op	adj)
1907 {
1908 	bool			shape_changed;
1909 	int			error;
1910 
1911 	/*
1912 	 * Ensure that no rcextents cross the boundary of the adjustment range.
1913 	 */
1914 	error = xfs_refcount_split_extent(cur, XFS_REFC_DOMAIN_COW,
1915 			agbno, &shape_changed);
1916 	if (error)
1917 		goto out_error;
1918 
1919 	error = xfs_refcount_split_extent(cur, XFS_REFC_DOMAIN_COW,
1920 			agbno + aglen, &shape_changed);
1921 	if (error)
1922 		goto out_error;
1923 
1924 	/*
1925 	 * Try to merge with the left or right extents of the range.
1926 	 */
1927 	error = xfs_refcount_merge_extents(cur, XFS_REFC_DOMAIN_COW, &agbno,
1928 			&aglen, adj, &shape_changed);
1929 	if (error)
1930 		goto out_error;
1931 
1932 	/* Now that we've taken care of the ends, adjust the middle extents */
1933 	error = xfs_refcount_adjust_cow_extents(cur, agbno, aglen, adj);
1934 	if (error)
1935 		goto out_error;
1936 
1937 	return 0;
1938 
1939 out_error:
1940 	trace_xfs_refcount_adjust_cow_error(cur, error, _RET_IP_);
1941 	return error;
1942 }
1943 
1944 /*
1945  * Record a CoW allocation in the refcount btree.
1946  */
1947 STATIC int
1948 __xfs_refcount_cow_alloc(
1949 	struct xfs_btree_cur	*rcur,
1950 	xfs_agblock_t		agbno,
1951 	xfs_extlen_t		aglen)
1952 {
1953 	trace_xfs_refcount_cow_increase(rcur, agbno, aglen);
1954 
1955 	/* Add refcount btree reservation */
1956 	return xfs_refcount_adjust_cow(rcur, agbno, aglen,
1957 			XFS_REFCOUNT_ADJUST_COW_ALLOC);
1958 }
1959 
1960 /*
1961  * Remove a CoW allocation from the refcount btree.
1962  */
1963 STATIC int
1964 __xfs_refcount_cow_free(
1965 	struct xfs_btree_cur	*rcur,
1966 	xfs_agblock_t		agbno,
1967 	xfs_extlen_t		aglen)
1968 {
1969 	trace_xfs_refcount_cow_decrease(rcur, agbno, aglen);
1970 
1971 	/* Remove refcount btree reservation */
1972 	return xfs_refcount_adjust_cow(rcur, agbno, aglen,
1973 			XFS_REFCOUNT_ADJUST_COW_FREE);
1974 }
1975 
1976 /* Record a CoW staging extent in the refcount btree. */
1977 void
1978 xfs_refcount_alloc_cow_extent(
1979 	struct xfs_trans		*tp,
1980 	bool				isrt,
1981 	xfs_fsblock_t			fsb,
1982 	xfs_extlen_t			len)
1983 {
1984 	struct xfs_mount		*mp = tp->t_mountp;
1985 
1986 	if (!xfs_has_reflink(mp))
1987 		return;
1988 
1989 	__xfs_refcount_add(tp, XFS_REFCOUNT_ALLOC_COW, isrt, fsb, len);
1990 
1991 	/* Add rmap entry */
1992 	xfs_rmap_alloc_extent(tp, isrt, fsb, len, XFS_RMAP_OWN_COW);
1993 }
1994 
1995 /* Forget a CoW staging event in the refcount btree. */
1996 void
1997 xfs_refcount_free_cow_extent(
1998 	struct xfs_trans		*tp,
1999 	bool				isrt,
2000 	xfs_fsblock_t			fsb,
2001 	xfs_extlen_t			len)
2002 {
2003 	struct xfs_mount		*mp = tp->t_mountp;
2004 
2005 	if (!xfs_has_reflink(mp))
2006 		return;
2007 
2008 	/* Remove rmap entry */
2009 	xfs_rmap_free_extent(tp, isrt, fsb, len, XFS_RMAP_OWN_COW);
2010 	__xfs_refcount_add(tp, XFS_REFCOUNT_FREE_COW, isrt, fsb, len);
2011 }
2012 
2013 struct xfs_refcount_recovery {
2014 	struct list_head		rr_list;
2015 	struct xfs_refcount_irec	rr_rrec;
2016 };
2017 
2018 /* Stuff an extent on the recovery list. */
2019 STATIC int
2020 xfs_refcount_recover_extent(
2021 	struct xfs_btree_cur		*cur,
2022 	const union xfs_btree_rec	*rec,
2023 	void				*priv)
2024 {
2025 	struct list_head		*debris = priv;
2026 	struct xfs_refcount_recovery	*rr;
2027 
2028 	if (XFS_IS_CORRUPT(cur->bc_mp,
2029 			   be32_to_cpu(rec->refc.rc_refcount) != 1)) {
2030 		xfs_btree_mark_sick(cur);
2031 		return -EFSCORRUPTED;
2032 	}
2033 
2034 	rr = kmalloc_obj(struct xfs_refcount_recovery,
2035 			 GFP_KERNEL | __GFP_NOFAIL);
2036 	INIT_LIST_HEAD(&rr->rr_list);
2037 	xfs_refcount_btrec_to_irec(rec, &rr->rr_rrec);
2038 
2039 	if (xfs_refcount_check_btrec(cur, &rr->rr_rrec) != NULL ||
2040 	    XFS_IS_CORRUPT(cur->bc_mp,
2041 			   rr->rr_rrec.rc_domain != XFS_REFC_DOMAIN_COW)) {
2042 		xfs_btree_mark_sick(cur);
2043 		kfree(rr);
2044 		return -EFSCORRUPTED;
2045 	}
2046 
2047 	list_add_tail(&rr->rr_list, debris);
2048 	return 0;
2049 }
2050 
2051 /* Find and remove leftover CoW reservations. */
2052 int
2053 xfs_refcount_recover_cow_leftovers(
2054 	struct xfs_group		*xg)
2055 {
2056 	struct xfs_mount		*mp = xg->xg_mount;
2057 	bool				isrt = xg->xg_type == XG_TYPE_RTG;
2058 	struct xfs_trans		*tp;
2059 	struct xfs_btree_cur		*cur;
2060 	struct xfs_buf			*agbp = NULL;
2061 	struct xfs_refcount_recovery	*rr, *n;
2062 	struct list_head		debris;
2063 	union xfs_btree_irec		low = {
2064 		.rc.rc_domain		= XFS_REFC_DOMAIN_COW,
2065 	};
2066 	union xfs_btree_irec		high = {
2067 		.rc.rc_domain		= XFS_REFC_DOMAIN_COW,
2068 		.rc.rc_startblock	= -1U,
2069 	};
2070 	xfs_fsblock_t			fsb;
2071 	int				error;
2072 
2073 	/* reflink filesystems must not have groups larger than 2^31-1 blocks */
2074 	BUILD_BUG_ON(XFS_MAX_RGBLOCKS >= XFS_REFC_COWFLAG);
2075 	BUILD_BUG_ON(XFS_MAX_CRC_AG_BLOCKS >= XFS_REFC_COWFLAG);
2076 
2077 	if (isrt) {
2078 		if (!xfs_has_rtgroups(mp))
2079 			return 0;
2080 		if (xfs_group_max_blocks(xg) >= XFS_MAX_RGBLOCKS)
2081 			return -EOPNOTSUPP;
2082 	} else {
2083 		if (xfs_group_max_blocks(xg) > XFS_MAX_CRC_AG_BLOCKS)
2084 			return -EOPNOTSUPP;
2085 	}
2086 
2087 	INIT_LIST_HEAD(&debris);
2088 
2089 	/*
2090 	 * In this first part, we use an empty transaction to gather up
2091 	 * all the leftover CoW extents so that we can subsequently
2092 	 * delete them.  The empty transaction is used to avoid
2093 	 * a buffer lock deadlock if there happens to be a loop in the
2094 	 * refcountbt because we're allowed to re-grab a buffer that is
2095 	 * already attached to our transaction.  When we're done
2096 	 * recording the CoW debris we cancel the (empty) transaction
2097 	 * and everything goes away cleanly.
2098 	 */
2099 	tp = xfs_trans_alloc_empty(mp);
2100 
2101 	if (isrt) {
2102 		xfs_rtgroup_lock(to_rtg(xg), XFS_RTGLOCK_REFCOUNT);
2103 		cur = xfs_rtrefcountbt_init_cursor(tp, to_rtg(xg));
2104 	} else {
2105 		error = xfs_alloc_read_agf(to_perag(xg), tp, 0, &agbp);
2106 		if (error)
2107 			goto out_trans;
2108 		cur = xfs_refcountbt_init_cursor(mp, tp, agbp, to_perag(xg));
2109 	}
2110 
2111 	/* Find all the leftover CoW staging extents. */
2112 	error = xfs_btree_query_range(cur, &low, &high,
2113 			xfs_refcount_recover_extent, &debris);
2114 	xfs_btree_del_cursor(cur, error);
2115 	if (agbp)
2116 		xfs_trans_brelse(tp, agbp);
2117 	else
2118 		xfs_rtgroup_unlock(to_rtg(xg), XFS_RTGLOCK_REFCOUNT);
2119 	xfs_trans_cancel(tp);
2120 	if (error)
2121 		goto out_free;
2122 
2123 	/* Now iterate the list to free the leftovers */
2124 	list_for_each_entry_safe(rr, n, &debris, rr_list) {
2125 		/* Set up transaction. */
2126 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0, 0, &tp);
2127 		if (error)
2128 			goto out_free;
2129 
2130 		/* Free the orphan record */
2131 		fsb = xfs_gbno_to_fsb(xg, rr->rr_rrec.rc_startblock);
2132 		xfs_refcount_free_cow_extent(tp, isrt, fsb,
2133 				rr->rr_rrec.rc_blockcount);
2134 
2135 		/* Free the block. */
2136 		error = xfs_free_extent_later(tp, fsb,
2137 				rr->rr_rrec.rc_blockcount, NULL,
2138 				XFS_AG_RESV_NONE,
2139 				isrt ? XFS_FREE_EXTENT_REALTIME : 0);
2140 		if (error)
2141 			goto out_trans;
2142 
2143 		error = xfs_trans_commit(tp);
2144 		if (error)
2145 			goto out_free;
2146 
2147 		list_del(&rr->rr_list);
2148 		kfree(rr);
2149 	}
2150 
2151 	return error;
2152 out_trans:
2153 	xfs_trans_cancel(tp);
2154 out_free:
2155 	/* Free the leftover list */
2156 	list_for_each_entry_safe(rr, n, &debris, rr_list) {
2157 		list_del(&rr->rr_list);
2158 		kfree(rr);
2159 	}
2160 	return error;
2161 }
2162 
2163 /*
2164  * Scan part of the keyspace of the refcount records and tell us if the area
2165  * has no records, is fully mapped by records, or is partially filled.
2166  */
2167 int
2168 xfs_refcount_has_records(
2169 	struct xfs_btree_cur	*cur,
2170 	enum xfs_refc_domain	domain,
2171 	xfs_agblock_t		bno,
2172 	xfs_extlen_t		len,
2173 	enum xbtree_recpacking	*outcome)
2174 {
2175 	union xfs_btree_irec	low;
2176 	union xfs_btree_irec	high;
2177 
2178 	memset(&low, 0, sizeof(low));
2179 	low.rc.rc_startblock = bno;
2180 	memset(&high, 0xFF, sizeof(high));
2181 	high.rc.rc_startblock = bno + len - 1;
2182 	low.rc.rc_domain = high.rc.rc_domain = domain;
2183 
2184 	return xfs_btree_has_records(cur, &low, &high, NULL, outcome);
2185 }
2186 
2187 struct xfs_refcount_query_range_info {
2188 	xfs_refcount_query_range_fn	fn;
2189 	void				*priv;
2190 };
2191 
2192 /* Format btree record and pass to our callback. */
2193 STATIC int
2194 xfs_refcount_query_range_helper(
2195 	struct xfs_btree_cur		*cur,
2196 	const union xfs_btree_rec	*rec,
2197 	void				*priv)
2198 {
2199 	struct xfs_refcount_query_range_info	*query = priv;
2200 	struct xfs_refcount_irec	irec;
2201 	xfs_failaddr_t			fa;
2202 
2203 	xfs_refcount_btrec_to_irec(rec, &irec);
2204 	fa = xfs_refcount_check_btrec(cur, &irec);
2205 	if (fa)
2206 		return xfs_refcount_complain_bad_rec(cur, fa, &irec);
2207 
2208 	return query->fn(cur, &irec, query->priv);
2209 }
2210 
2211 /* Find all refcount records between two keys. */
2212 int
2213 xfs_refcount_query_range(
2214 	struct xfs_btree_cur		*cur,
2215 	const struct xfs_refcount_irec	*low_rec,
2216 	const struct xfs_refcount_irec	*high_rec,
2217 	xfs_refcount_query_range_fn	fn,
2218 	void				*priv)
2219 {
2220 	union xfs_btree_irec		low_brec = { .rc = *low_rec };
2221 	union xfs_btree_irec		high_brec = { .rc = *high_rec };
2222 	struct xfs_refcount_query_range_info query = { .priv = priv, .fn = fn };
2223 
2224 	return xfs_btree_query_range(cur, &low_brec, &high_brec,
2225 			xfs_refcount_query_range_helper, &query);
2226 }
2227 
2228 int __init
2229 xfs_refcount_intent_init_cache(void)
2230 {
2231 	xfs_refcount_intent_cache = kmem_cache_create("xfs_refc_intent",
2232 			sizeof(struct xfs_refcount_intent),
2233 			0, 0, NULL);
2234 
2235 	return xfs_refcount_intent_cache != NULL ? 0 : -ENOMEM;
2236 }
2237 
2238 void
2239 xfs_refcount_intent_destroy_cache(void)
2240 {
2241 	kmem_cache_destroy(xfs_refcount_intent_cache);
2242 	xfs_refcount_intent_cache = NULL;
2243 }
2244