xref: /openbmc/linux/fs/xfs/libxfs/xfs_alloc.c (revision 11976fe2)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs.h"
7 #include "xfs_fs.h"
8 #include "xfs_format.h"
9 #include "xfs_log_format.h"
10 #include "xfs_shared.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_bit.h"
13 #include "xfs_mount.h"
14 #include "xfs_defer.h"
15 #include "xfs_btree.h"
16 #include "xfs_rmap.h"
17 #include "xfs_alloc_btree.h"
18 #include "xfs_alloc.h"
19 #include "xfs_extent_busy.h"
20 #include "xfs_errortag.h"
21 #include "xfs_error.h"
22 #include "xfs_trace.h"
23 #include "xfs_trans.h"
24 #include "xfs_buf_item.h"
25 #include "xfs_log.h"
26 #include "xfs_ag.h"
27 #include "xfs_ag_resv.h"
28 #include "xfs_bmap.h"
29 
30 struct kmem_cache	*xfs_extfree_item_cache;
31 
32 struct workqueue_struct *xfs_alloc_wq;
33 
34 #define XFS_ABSDIFF(a,b)	(((a) <= (b)) ? ((b) - (a)) : ((a) - (b)))
35 
36 #define	XFSA_FIXUP_BNO_OK	1
37 #define	XFSA_FIXUP_CNT_OK	2
38 
39 /*
40  * Size of the AGFL.  For CRC-enabled filesystes we steal a couple of slots in
41  * the beginning of the block for a proper header with the location information
42  * and CRC.
43  */
44 unsigned int
45 xfs_agfl_size(
46 	struct xfs_mount	*mp)
47 {
48 	unsigned int		size = mp->m_sb.sb_sectsize;
49 
50 	if (xfs_has_crc(mp))
51 		size -= sizeof(struct xfs_agfl);
52 
53 	return size / sizeof(xfs_agblock_t);
54 }
55 
56 unsigned int
57 xfs_refc_block(
58 	struct xfs_mount	*mp)
59 {
60 	if (xfs_has_rmapbt(mp))
61 		return XFS_RMAP_BLOCK(mp) + 1;
62 	if (xfs_has_finobt(mp))
63 		return XFS_FIBT_BLOCK(mp) + 1;
64 	return XFS_IBT_BLOCK(mp) + 1;
65 }
66 
67 xfs_extlen_t
68 xfs_prealloc_blocks(
69 	struct xfs_mount	*mp)
70 {
71 	if (xfs_has_reflink(mp))
72 		return xfs_refc_block(mp) + 1;
73 	if (xfs_has_rmapbt(mp))
74 		return XFS_RMAP_BLOCK(mp) + 1;
75 	if (xfs_has_finobt(mp))
76 		return XFS_FIBT_BLOCK(mp) + 1;
77 	return XFS_IBT_BLOCK(mp) + 1;
78 }
79 
80 /*
81  * The number of blocks per AG that we withhold from xfs_mod_fdblocks to
82  * guarantee that we can refill the AGFL prior to allocating space in a nearly
83  * full AG.  Although the space described by the free space btrees, the
84  * blocks used by the freesp btrees themselves, and the blocks owned by the
85  * AGFL are counted in the ondisk fdblocks, it's a mistake to let the ondisk
86  * free space in the AG drop so low that the free space btrees cannot refill an
87  * empty AGFL up to the minimum level.  Rather than grind through empty AGs
88  * until the fs goes down, we subtract this many AG blocks from the incore
89  * fdblocks to ensure user allocation does not overcommit the space the
90  * filesystem needs for the AGFLs.  The rmap btree uses a per-AG reservation to
91  * withhold space from xfs_mod_fdblocks, so we do not account for that here.
92  */
93 #define XFS_ALLOCBT_AGFL_RESERVE	4
94 
95 /*
96  * Compute the number of blocks that we set aside to guarantee the ability to
97  * refill the AGFL and handle a full bmap btree split.
98  *
99  * In order to avoid ENOSPC-related deadlock caused by out-of-order locking of
100  * AGF buffer (PV 947395), we place constraints on the relationship among
101  * actual allocations for data blocks, freelist blocks, and potential file data
102  * bmap btree blocks. However, these restrictions may result in no actual space
103  * allocated for a delayed extent, for example, a data block in a certain AG is
104  * allocated but there is no additional block for the additional bmap btree
105  * block due to a split of the bmap btree of the file. The result of this may
106  * lead to an infinite loop when the file gets flushed to disk and all delayed
107  * extents need to be actually allocated. To get around this, we explicitly set
108  * aside a few blocks which will not be reserved in delayed allocation.
109  *
110  * For each AG, we need to reserve enough blocks to replenish a totally empty
111  * AGFL and 4 more to handle a potential split of the file's bmap btree.
112  */
113 unsigned int
114 xfs_alloc_set_aside(
115 	struct xfs_mount	*mp)
116 {
117 	return mp->m_sb.sb_agcount * (XFS_ALLOCBT_AGFL_RESERVE + 4);
118 }
119 
120 /*
121  * When deciding how much space to allocate out of an AG, we limit the
122  * allocation maximum size to the size the AG. However, we cannot use all the
123  * blocks in the AG - some are permanently used by metadata. These
124  * blocks are generally:
125  *	- the AG superblock, AGF, AGI and AGFL
126  *	- the AGF (bno and cnt) and AGI btree root blocks, and optionally
127  *	  the AGI free inode and rmap btree root blocks.
128  *	- blocks on the AGFL according to xfs_alloc_set_aside() limits
129  *	- the rmapbt root block
130  *
131  * The AG headers are sector sized, so the amount of space they take up is
132  * dependent on filesystem geometry. The others are all single blocks.
133  */
134 unsigned int
135 xfs_alloc_ag_max_usable(
136 	struct xfs_mount	*mp)
137 {
138 	unsigned int		blocks;
139 
140 	blocks = XFS_BB_TO_FSB(mp, XFS_FSS_TO_BB(mp, 4)); /* ag headers */
141 	blocks += XFS_ALLOCBT_AGFL_RESERVE;
142 	blocks += 3;			/* AGF, AGI btree root blocks */
143 	if (xfs_has_finobt(mp))
144 		blocks++;		/* finobt root block */
145 	if (xfs_has_rmapbt(mp))
146 		blocks++;		/* rmap root block */
147 	if (xfs_has_reflink(mp))
148 		blocks++;		/* refcount root block */
149 
150 	return mp->m_sb.sb_agblocks - blocks;
151 }
152 
153 /*
154  * Lookup the record equal to [bno, len] in the btree given by cur.
155  */
156 STATIC int				/* error */
157 xfs_alloc_lookup_eq(
158 	struct xfs_btree_cur	*cur,	/* btree cursor */
159 	xfs_agblock_t		bno,	/* starting block of extent */
160 	xfs_extlen_t		len,	/* length of extent */
161 	int			*stat)	/* success/failure */
162 {
163 	int			error;
164 
165 	cur->bc_rec.a.ar_startblock = bno;
166 	cur->bc_rec.a.ar_blockcount = len;
167 	error = xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
168 	cur->bc_ag.abt.active = (*stat == 1);
169 	return error;
170 }
171 
172 /*
173  * Lookup the first record greater than or equal to [bno, len]
174  * in the btree given by cur.
175  */
176 int				/* error */
177 xfs_alloc_lookup_ge(
178 	struct xfs_btree_cur	*cur,	/* btree cursor */
179 	xfs_agblock_t		bno,	/* starting block of extent */
180 	xfs_extlen_t		len,	/* length of extent */
181 	int			*stat)	/* success/failure */
182 {
183 	int			error;
184 
185 	cur->bc_rec.a.ar_startblock = bno;
186 	cur->bc_rec.a.ar_blockcount = len;
187 	error = xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
188 	cur->bc_ag.abt.active = (*stat == 1);
189 	return error;
190 }
191 
192 /*
193  * Lookup the first record less than or equal to [bno, len]
194  * in the btree given by cur.
195  */
196 int					/* error */
197 xfs_alloc_lookup_le(
198 	struct xfs_btree_cur	*cur,	/* btree cursor */
199 	xfs_agblock_t		bno,	/* starting block of extent */
200 	xfs_extlen_t		len,	/* length of extent */
201 	int			*stat)	/* success/failure */
202 {
203 	int			error;
204 	cur->bc_rec.a.ar_startblock = bno;
205 	cur->bc_rec.a.ar_blockcount = len;
206 	error = xfs_btree_lookup(cur, XFS_LOOKUP_LE, stat);
207 	cur->bc_ag.abt.active = (*stat == 1);
208 	return error;
209 }
210 
211 static inline bool
212 xfs_alloc_cur_active(
213 	struct xfs_btree_cur	*cur)
214 {
215 	return cur && cur->bc_ag.abt.active;
216 }
217 
218 /*
219  * Update the record referred to by cur to the value given
220  * by [bno, len].
221  * This either works (return 0) or gets an EFSCORRUPTED error.
222  */
223 STATIC int				/* error */
224 xfs_alloc_update(
225 	struct xfs_btree_cur	*cur,	/* btree cursor */
226 	xfs_agblock_t		bno,	/* starting block of extent */
227 	xfs_extlen_t		len)	/* length of extent */
228 {
229 	union xfs_btree_rec	rec;
230 
231 	rec.alloc.ar_startblock = cpu_to_be32(bno);
232 	rec.alloc.ar_blockcount = cpu_to_be32(len);
233 	return xfs_btree_update(cur, &rec);
234 }
235 
236 /* Convert the ondisk btree record to its incore representation. */
237 void
238 xfs_alloc_btrec_to_irec(
239 	const union xfs_btree_rec	*rec,
240 	struct xfs_alloc_rec_incore	*irec)
241 {
242 	irec->ar_startblock = be32_to_cpu(rec->alloc.ar_startblock);
243 	irec->ar_blockcount = be32_to_cpu(rec->alloc.ar_blockcount);
244 }
245 
246 /* Simple checks for free space records. */
247 xfs_failaddr_t
248 xfs_alloc_check_irec(
249 	struct xfs_btree_cur		*cur,
250 	const struct xfs_alloc_rec_incore *irec)
251 {
252 	struct xfs_perag		*pag = cur->bc_ag.pag;
253 
254 	if (irec->ar_blockcount == 0)
255 		return __this_address;
256 
257 	/* check for valid extent range, including overflow */
258 	if (!xfs_verify_agbext(pag, irec->ar_startblock, irec->ar_blockcount))
259 		return __this_address;
260 
261 	return NULL;
262 }
263 
264 static inline int
265 xfs_alloc_complain_bad_rec(
266 	struct xfs_btree_cur		*cur,
267 	xfs_failaddr_t			fa,
268 	const struct xfs_alloc_rec_incore *irec)
269 {
270 	struct xfs_mount		*mp = cur->bc_mp;
271 
272 	xfs_warn(mp,
273 		"%s Freespace BTree record corruption in AG %d detected at %pS!",
274 		cur->bc_btnum == XFS_BTNUM_BNO ? "Block" : "Size",
275 		cur->bc_ag.pag->pag_agno, fa);
276 	xfs_warn(mp,
277 		"start block 0x%x block count 0x%x", irec->ar_startblock,
278 		irec->ar_blockcount);
279 	return -EFSCORRUPTED;
280 }
281 
282 /*
283  * Get the data from the pointed-to record.
284  */
285 int					/* error */
286 xfs_alloc_get_rec(
287 	struct xfs_btree_cur	*cur,	/* btree cursor */
288 	xfs_agblock_t		*bno,	/* output: starting block of extent */
289 	xfs_extlen_t		*len,	/* output: length of extent */
290 	int			*stat)	/* output: success/failure */
291 {
292 	struct xfs_alloc_rec_incore irec;
293 	union xfs_btree_rec	*rec;
294 	xfs_failaddr_t		fa;
295 	int			error;
296 
297 	error = xfs_btree_get_rec(cur, &rec, stat);
298 	if (error || !(*stat))
299 		return error;
300 
301 	xfs_alloc_btrec_to_irec(rec, &irec);
302 	fa = xfs_alloc_check_irec(cur, &irec);
303 	if (fa)
304 		return xfs_alloc_complain_bad_rec(cur, fa, &irec);
305 
306 	*bno = irec.ar_startblock;
307 	*len = irec.ar_blockcount;
308 	return 0;
309 }
310 
311 /*
312  * Compute aligned version of the found extent.
313  * Takes alignment and min length into account.
314  */
315 STATIC bool
316 xfs_alloc_compute_aligned(
317 	xfs_alloc_arg_t	*args,		/* allocation argument structure */
318 	xfs_agblock_t	foundbno,	/* starting block in found extent */
319 	xfs_extlen_t	foundlen,	/* length in found extent */
320 	xfs_agblock_t	*resbno,	/* result block number */
321 	xfs_extlen_t	*reslen,	/* result length */
322 	unsigned	*busy_gen)
323 {
324 	xfs_agblock_t	bno = foundbno;
325 	xfs_extlen_t	len = foundlen;
326 	xfs_extlen_t	diff;
327 	bool		busy;
328 
329 	/* Trim busy sections out of found extent */
330 	busy = xfs_extent_busy_trim(args, &bno, &len, busy_gen);
331 
332 	/*
333 	 * If we have a largish extent that happens to start before min_agbno,
334 	 * see if we can shift it into range...
335 	 */
336 	if (bno < args->min_agbno && bno + len > args->min_agbno) {
337 		diff = args->min_agbno - bno;
338 		if (len > diff) {
339 			bno += diff;
340 			len -= diff;
341 		}
342 	}
343 
344 	if (args->alignment > 1 && len >= args->minlen) {
345 		xfs_agblock_t	aligned_bno = roundup(bno, args->alignment);
346 
347 		diff = aligned_bno - bno;
348 
349 		*resbno = aligned_bno;
350 		*reslen = diff >= len ? 0 : len - diff;
351 	} else {
352 		*resbno = bno;
353 		*reslen = len;
354 	}
355 
356 	return busy;
357 }
358 
359 /*
360  * Compute best start block and diff for "near" allocations.
361  * freelen >= wantlen already checked by caller.
362  */
363 STATIC xfs_extlen_t			/* difference value (absolute) */
364 xfs_alloc_compute_diff(
365 	xfs_agblock_t	wantbno,	/* target starting block */
366 	xfs_extlen_t	wantlen,	/* target length */
367 	xfs_extlen_t	alignment,	/* target alignment */
368 	int		datatype,	/* are we allocating data? */
369 	xfs_agblock_t	freebno,	/* freespace's starting block */
370 	xfs_extlen_t	freelen,	/* freespace's length */
371 	xfs_agblock_t	*newbnop)	/* result: best start block from free */
372 {
373 	xfs_agblock_t	freeend;	/* end of freespace extent */
374 	xfs_agblock_t	newbno1;	/* return block number */
375 	xfs_agblock_t	newbno2;	/* other new block number */
376 	xfs_extlen_t	newlen1=0;	/* length with newbno1 */
377 	xfs_extlen_t	newlen2=0;	/* length with newbno2 */
378 	xfs_agblock_t	wantend;	/* end of target extent */
379 	bool		userdata = datatype & XFS_ALLOC_USERDATA;
380 
381 	ASSERT(freelen >= wantlen);
382 	freeend = freebno + freelen;
383 	wantend = wantbno + wantlen;
384 	/*
385 	 * We want to allocate from the start of a free extent if it is past
386 	 * the desired block or if we are allocating user data and the free
387 	 * extent is before desired block. The second case is there to allow
388 	 * for contiguous allocation from the remaining free space if the file
389 	 * grows in the short term.
390 	 */
391 	if (freebno >= wantbno || (userdata && freeend < wantend)) {
392 		if ((newbno1 = roundup(freebno, alignment)) >= freeend)
393 			newbno1 = NULLAGBLOCK;
394 	} else if (freeend >= wantend && alignment > 1) {
395 		newbno1 = roundup(wantbno, alignment);
396 		newbno2 = newbno1 - alignment;
397 		if (newbno1 >= freeend)
398 			newbno1 = NULLAGBLOCK;
399 		else
400 			newlen1 = XFS_EXTLEN_MIN(wantlen, freeend - newbno1);
401 		if (newbno2 < freebno)
402 			newbno2 = NULLAGBLOCK;
403 		else
404 			newlen2 = XFS_EXTLEN_MIN(wantlen, freeend - newbno2);
405 		if (newbno1 != NULLAGBLOCK && newbno2 != NULLAGBLOCK) {
406 			if (newlen1 < newlen2 ||
407 			    (newlen1 == newlen2 &&
408 			     XFS_ABSDIFF(newbno1, wantbno) >
409 			     XFS_ABSDIFF(newbno2, wantbno)))
410 				newbno1 = newbno2;
411 		} else if (newbno2 != NULLAGBLOCK)
412 			newbno1 = newbno2;
413 	} else if (freeend >= wantend) {
414 		newbno1 = wantbno;
415 	} else if (alignment > 1) {
416 		newbno1 = roundup(freeend - wantlen, alignment);
417 		if (newbno1 > freeend - wantlen &&
418 		    newbno1 - alignment >= freebno)
419 			newbno1 -= alignment;
420 		else if (newbno1 >= freeend)
421 			newbno1 = NULLAGBLOCK;
422 	} else
423 		newbno1 = freeend - wantlen;
424 	*newbnop = newbno1;
425 	return newbno1 == NULLAGBLOCK ? 0 : XFS_ABSDIFF(newbno1, wantbno);
426 }
427 
428 /*
429  * Fix up the length, based on mod and prod.
430  * len should be k * prod + mod for some k.
431  * If len is too small it is returned unchanged.
432  * If len hits maxlen it is left alone.
433  */
434 STATIC void
435 xfs_alloc_fix_len(
436 	xfs_alloc_arg_t	*args)		/* allocation argument structure */
437 {
438 	xfs_extlen_t	k;
439 	xfs_extlen_t	rlen;
440 
441 	ASSERT(args->mod < args->prod);
442 	rlen = args->len;
443 	ASSERT(rlen >= args->minlen);
444 	ASSERT(rlen <= args->maxlen);
445 	if (args->prod <= 1 || rlen < args->mod || rlen == args->maxlen ||
446 	    (args->mod == 0 && rlen < args->prod))
447 		return;
448 	k = rlen % args->prod;
449 	if (k == args->mod)
450 		return;
451 	if (k > args->mod)
452 		rlen = rlen - (k - args->mod);
453 	else
454 		rlen = rlen - args->prod + (args->mod - k);
455 	/* casts to (int) catch length underflows */
456 	if ((int)rlen < (int)args->minlen)
457 		return;
458 	ASSERT(rlen >= args->minlen && rlen <= args->maxlen);
459 	ASSERT(rlen % args->prod == args->mod);
460 	ASSERT(args->pag->pagf_freeblks + args->pag->pagf_flcount >=
461 		rlen + args->minleft);
462 	args->len = rlen;
463 }
464 
465 /*
466  * Update the two btrees, logically removing from freespace the extent
467  * starting at rbno, rlen blocks.  The extent is contained within the
468  * actual (current) free extent fbno for flen blocks.
469  * Flags are passed in indicating whether the cursors are set to the
470  * relevant records.
471  */
472 STATIC int				/* error code */
473 xfs_alloc_fixup_trees(
474 	struct xfs_btree_cur *cnt_cur,	/* cursor for by-size btree */
475 	struct xfs_btree_cur *bno_cur,	/* cursor for by-block btree */
476 	xfs_agblock_t	fbno,		/* starting block of free extent */
477 	xfs_extlen_t	flen,		/* length of free extent */
478 	xfs_agblock_t	rbno,		/* starting block of returned extent */
479 	xfs_extlen_t	rlen,		/* length of returned extent */
480 	int		flags)		/* flags, XFSA_FIXUP_... */
481 {
482 	int		error;		/* error code */
483 	int		i;		/* operation results */
484 	xfs_agblock_t	nfbno1;		/* first new free startblock */
485 	xfs_agblock_t	nfbno2;		/* second new free startblock */
486 	xfs_extlen_t	nflen1=0;	/* first new free length */
487 	xfs_extlen_t	nflen2=0;	/* second new free length */
488 	struct xfs_mount *mp;
489 
490 	mp = cnt_cur->bc_mp;
491 
492 	/*
493 	 * Look up the record in the by-size tree if necessary.
494 	 */
495 	if (flags & XFSA_FIXUP_CNT_OK) {
496 #ifdef DEBUG
497 		if ((error = xfs_alloc_get_rec(cnt_cur, &nfbno1, &nflen1, &i)))
498 			return error;
499 		if (XFS_IS_CORRUPT(mp,
500 				   i != 1 ||
501 				   nfbno1 != fbno ||
502 				   nflen1 != flen))
503 			return -EFSCORRUPTED;
504 #endif
505 	} else {
506 		if ((error = xfs_alloc_lookup_eq(cnt_cur, fbno, flen, &i)))
507 			return error;
508 		if (XFS_IS_CORRUPT(mp, i != 1))
509 			return -EFSCORRUPTED;
510 	}
511 	/*
512 	 * Look up the record in the by-block tree if necessary.
513 	 */
514 	if (flags & XFSA_FIXUP_BNO_OK) {
515 #ifdef DEBUG
516 		if ((error = xfs_alloc_get_rec(bno_cur, &nfbno1, &nflen1, &i)))
517 			return error;
518 		if (XFS_IS_CORRUPT(mp,
519 				   i != 1 ||
520 				   nfbno1 != fbno ||
521 				   nflen1 != flen))
522 			return -EFSCORRUPTED;
523 #endif
524 	} else {
525 		if ((error = xfs_alloc_lookup_eq(bno_cur, fbno, flen, &i)))
526 			return error;
527 		if (XFS_IS_CORRUPT(mp, i != 1))
528 			return -EFSCORRUPTED;
529 	}
530 
531 #ifdef DEBUG
532 	if (bno_cur->bc_nlevels == 1 && cnt_cur->bc_nlevels == 1) {
533 		struct xfs_btree_block	*bnoblock;
534 		struct xfs_btree_block	*cntblock;
535 
536 		bnoblock = XFS_BUF_TO_BLOCK(bno_cur->bc_levels[0].bp);
537 		cntblock = XFS_BUF_TO_BLOCK(cnt_cur->bc_levels[0].bp);
538 
539 		if (XFS_IS_CORRUPT(mp,
540 				   bnoblock->bb_numrecs !=
541 				   cntblock->bb_numrecs))
542 			return -EFSCORRUPTED;
543 	}
544 #endif
545 
546 	/*
547 	 * Deal with all four cases: the allocated record is contained
548 	 * within the freespace record, so we can have new freespace
549 	 * at either (or both) end, or no freespace remaining.
550 	 */
551 	if (rbno == fbno && rlen == flen)
552 		nfbno1 = nfbno2 = NULLAGBLOCK;
553 	else if (rbno == fbno) {
554 		nfbno1 = rbno + rlen;
555 		nflen1 = flen - rlen;
556 		nfbno2 = NULLAGBLOCK;
557 	} else if (rbno + rlen == fbno + flen) {
558 		nfbno1 = fbno;
559 		nflen1 = flen - rlen;
560 		nfbno2 = NULLAGBLOCK;
561 	} else {
562 		nfbno1 = fbno;
563 		nflen1 = rbno - fbno;
564 		nfbno2 = rbno + rlen;
565 		nflen2 = (fbno + flen) - nfbno2;
566 	}
567 	/*
568 	 * Delete the entry from the by-size btree.
569 	 */
570 	if ((error = xfs_btree_delete(cnt_cur, &i)))
571 		return error;
572 	if (XFS_IS_CORRUPT(mp, i != 1))
573 		return -EFSCORRUPTED;
574 	/*
575 	 * Add new by-size btree entry(s).
576 	 */
577 	if (nfbno1 != NULLAGBLOCK) {
578 		if ((error = xfs_alloc_lookup_eq(cnt_cur, nfbno1, nflen1, &i)))
579 			return error;
580 		if (XFS_IS_CORRUPT(mp, i != 0))
581 			return -EFSCORRUPTED;
582 		if ((error = xfs_btree_insert(cnt_cur, &i)))
583 			return error;
584 		if (XFS_IS_CORRUPT(mp, i != 1))
585 			return -EFSCORRUPTED;
586 	}
587 	if (nfbno2 != NULLAGBLOCK) {
588 		if ((error = xfs_alloc_lookup_eq(cnt_cur, nfbno2, nflen2, &i)))
589 			return error;
590 		if (XFS_IS_CORRUPT(mp, i != 0))
591 			return -EFSCORRUPTED;
592 		if ((error = xfs_btree_insert(cnt_cur, &i)))
593 			return error;
594 		if (XFS_IS_CORRUPT(mp, i != 1))
595 			return -EFSCORRUPTED;
596 	}
597 	/*
598 	 * Fix up the by-block btree entry(s).
599 	 */
600 	if (nfbno1 == NULLAGBLOCK) {
601 		/*
602 		 * No remaining freespace, just delete the by-block tree entry.
603 		 */
604 		if ((error = xfs_btree_delete(bno_cur, &i)))
605 			return error;
606 		if (XFS_IS_CORRUPT(mp, i != 1))
607 			return -EFSCORRUPTED;
608 	} else {
609 		/*
610 		 * Update the by-block entry to start later|be shorter.
611 		 */
612 		if ((error = xfs_alloc_update(bno_cur, nfbno1, nflen1)))
613 			return error;
614 	}
615 	if (nfbno2 != NULLAGBLOCK) {
616 		/*
617 		 * 2 resulting free entries, need to add one.
618 		 */
619 		if ((error = xfs_alloc_lookup_eq(bno_cur, nfbno2, nflen2, &i)))
620 			return error;
621 		if (XFS_IS_CORRUPT(mp, i != 0))
622 			return -EFSCORRUPTED;
623 		if ((error = xfs_btree_insert(bno_cur, &i)))
624 			return error;
625 		if (XFS_IS_CORRUPT(mp, i != 1))
626 			return -EFSCORRUPTED;
627 	}
628 	return 0;
629 }
630 
631 /*
632  * We do not verify the AGFL contents against AGF-based index counters here,
633  * even though we may have access to the perag that contains shadow copies. We
634  * don't know if the AGF based counters have been checked, and if they have they
635  * still may be inconsistent because they haven't yet been reset on the first
636  * allocation after the AGF has been read in.
637  *
638  * This means we can only check that all agfl entries contain valid or null
639  * values because we can't reliably determine the active range to exclude
640  * NULLAGBNO as a valid value.
641  *
642  * However, we can't even do that for v4 format filesystems because there are
643  * old versions of mkfs out there that does not initialise the AGFL to known,
644  * verifiable values. HEnce we can't tell the difference between a AGFL block
645  * allocated by mkfs and a corrupted AGFL block here on v4 filesystems.
646  *
647  * As a result, we can only fully validate AGFL block numbers when we pull them
648  * from the freelist in xfs_alloc_get_freelist().
649  */
650 static xfs_failaddr_t
651 xfs_agfl_verify(
652 	struct xfs_buf	*bp)
653 {
654 	struct xfs_mount *mp = bp->b_mount;
655 	struct xfs_agfl	*agfl = XFS_BUF_TO_AGFL(bp);
656 	__be32		*agfl_bno = xfs_buf_to_agfl_bno(bp);
657 	int		i;
658 
659 	if (!xfs_has_crc(mp))
660 		return NULL;
661 
662 	if (!xfs_verify_magic(bp, agfl->agfl_magicnum))
663 		return __this_address;
664 	if (!uuid_equal(&agfl->agfl_uuid, &mp->m_sb.sb_meta_uuid))
665 		return __this_address;
666 	/*
667 	 * during growfs operations, the perag is not fully initialised,
668 	 * so we can't use it for any useful checking. growfs ensures we can't
669 	 * use it by using uncached buffers that don't have the perag attached
670 	 * so we can detect and avoid this problem.
671 	 */
672 	if (bp->b_pag && be32_to_cpu(agfl->agfl_seqno) != bp->b_pag->pag_agno)
673 		return __this_address;
674 
675 	for (i = 0; i < xfs_agfl_size(mp); i++) {
676 		if (be32_to_cpu(agfl_bno[i]) != NULLAGBLOCK &&
677 		    be32_to_cpu(agfl_bno[i]) >= mp->m_sb.sb_agblocks)
678 			return __this_address;
679 	}
680 
681 	if (!xfs_log_check_lsn(mp, be64_to_cpu(XFS_BUF_TO_AGFL(bp)->agfl_lsn)))
682 		return __this_address;
683 	return NULL;
684 }
685 
686 static void
687 xfs_agfl_read_verify(
688 	struct xfs_buf	*bp)
689 {
690 	struct xfs_mount *mp = bp->b_mount;
691 	xfs_failaddr_t	fa;
692 
693 	/*
694 	 * There is no verification of non-crc AGFLs because mkfs does not
695 	 * initialise the AGFL to zero or NULL. Hence the only valid part of the
696 	 * AGFL is what the AGF says is active. We can't get to the AGF, so we
697 	 * can't verify just those entries are valid.
698 	 */
699 	if (!xfs_has_crc(mp))
700 		return;
701 
702 	if (!xfs_buf_verify_cksum(bp, XFS_AGFL_CRC_OFF))
703 		xfs_verifier_error(bp, -EFSBADCRC, __this_address);
704 	else {
705 		fa = xfs_agfl_verify(bp);
706 		if (fa)
707 			xfs_verifier_error(bp, -EFSCORRUPTED, fa);
708 	}
709 }
710 
711 static void
712 xfs_agfl_write_verify(
713 	struct xfs_buf	*bp)
714 {
715 	struct xfs_mount	*mp = bp->b_mount;
716 	struct xfs_buf_log_item	*bip = bp->b_log_item;
717 	xfs_failaddr_t		fa;
718 
719 	/* no verification of non-crc AGFLs */
720 	if (!xfs_has_crc(mp))
721 		return;
722 
723 	fa = xfs_agfl_verify(bp);
724 	if (fa) {
725 		xfs_verifier_error(bp, -EFSCORRUPTED, fa);
726 		return;
727 	}
728 
729 	if (bip)
730 		XFS_BUF_TO_AGFL(bp)->agfl_lsn = cpu_to_be64(bip->bli_item.li_lsn);
731 
732 	xfs_buf_update_cksum(bp, XFS_AGFL_CRC_OFF);
733 }
734 
735 const struct xfs_buf_ops xfs_agfl_buf_ops = {
736 	.name = "xfs_agfl",
737 	.magic = { cpu_to_be32(XFS_AGFL_MAGIC), cpu_to_be32(XFS_AGFL_MAGIC) },
738 	.verify_read = xfs_agfl_read_verify,
739 	.verify_write = xfs_agfl_write_verify,
740 	.verify_struct = xfs_agfl_verify,
741 };
742 
743 /*
744  * Read in the allocation group free block array.
745  */
746 int
747 xfs_alloc_read_agfl(
748 	struct xfs_perag	*pag,
749 	struct xfs_trans	*tp,
750 	struct xfs_buf		**bpp)
751 {
752 	struct xfs_mount	*mp = pag->pag_mount;
753 	struct xfs_buf		*bp;
754 	int			error;
755 
756 	error = xfs_trans_read_buf(
757 			mp, tp, mp->m_ddev_targp,
758 			XFS_AG_DADDR(mp, pag->pag_agno, XFS_AGFL_DADDR(mp)),
759 			XFS_FSS_TO_BB(mp, 1), 0, &bp, &xfs_agfl_buf_ops);
760 	if (error)
761 		return error;
762 	xfs_buf_set_ref(bp, XFS_AGFL_REF);
763 	*bpp = bp;
764 	return 0;
765 }
766 
767 STATIC int
768 xfs_alloc_update_counters(
769 	struct xfs_trans	*tp,
770 	struct xfs_buf		*agbp,
771 	long			len)
772 {
773 	struct xfs_agf		*agf = agbp->b_addr;
774 
775 	agbp->b_pag->pagf_freeblks += len;
776 	be32_add_cpu(&agf->agf_freeblks, len);
777 
778 	if (unlikely(be32_to_cpu(agf->agf_freeblks) >
779 		     be32_to_cpu(agf->agf_length))) {
780 		xfs_buf_mark_corrupt(agbp);
781 		return -EFSCORRUPTED;
782 	}
783 
784 	xfs_alloc_log_agf(tp, agbp, XFS_AGF_FREEBLKS);
785 	return 0;
786 }
787 
788 /*
789  * Block allocation algorithm and data structures.
790  */
791 struct xfs_alloc_cur {
792 	struct xfs_btree_cur		*cnt;	/* btree cursors */
793 	struct xfs_btree_cur		*bnolt;
794 	struct xfs_btree_cur		*bnogt;
795 	xfs_extlen_t			cur_len;/* current search length */
796 	xfs_agblock_t			rec_bno;/* extent startblock */
797 	xfs_extlen_t			rec_len;/* extent length */
798 	xfs_agblock_t			bno;	/* alloc bno */
799 	xfs_extlen_t			len;	/* alloc len */
800 	xfs_extlen_t			diff;	/* diff from search bno */
801 	unsigned int			busy_gen;/* busy state */
802 	bool				busy;
803 };
804 
805 /*
806  * Set up cursors, etc. in the extent allocation cursor. This function can be
807  * called multiple times to reset an initialized structure without having to
808  * reallocate cursors.
809  */
810 static int
811 xfs_alloc_cur_setup(
812 	struct xfs_alloc_arg	*args,
813 	struct xfs_alloc_cur	*acur)
814 {
815 	int			error;
816 	int			i;
817 
818 	acur->cur_len = args->maxlen;
819 	acur->rec_bno = 0;
820 	acur->rec_len = 0;
821 	acur->bno = 0;
822 	acur->len = 0;
823 	acur->diff = -1;
824 	acur->busy = false;
825 	acur->busy_gen = 0;
826 
827 	/*
828 	 * Perform an initial cntbt lookup to check for availability of maxlen
829 	 * extents. If this fails, we'll return -ENOSPC to signal the caller to
830 	 * attempt a small allocation.
831 	 */
832 	if (!acur->cnt)
833 		acur->cnt = xfs_allocbt_init_cursor(args->mp, args->tp,
834 					args->agbp, args->pag, XFS_BTNUM_CNT);
835 	error = xfs_alloc_lookup_ge(acur->cnt, 0, args->maxlen, &i);
836 	if (error)
837 		return error;
838 
839 	/*
840 	 * Allocate the bnobt left and right search cursors.
841 	 */
842 	if (!acur->bnolt)
843 		acur->bnolt = xfs_allocbt_init_cursor(args->mp, args->tp,
844 					args->agbp, args->pag, XFS_BTNUM_BNO);
845 	if (!acur->bnogt)
846 		acur->bnogt = xfs_allocbt_init_cursor(args->mp, args->tp,
847 					args->agbp, args->pag, XFS_BTNUM_BNO);
848 	return i == 1 ? 0 : -ENOSPC;
849 }
850 
851 static void
852 xfs_alloc_cur_close(
853 	struct xfs_alloc_cur	*acur,
854 	bool			error)
855 {
856 	int			cur_error = XFS_BTREE_NOERROR;
857 
858 	if (error)
859 		cur_error = XFS_BTREE_ERROR;
860 
861 	if (acur->cnt)
862 		xfs_btree_del_cursor(acur->cnt, cur_error);
863 	if (acur->bnolt)
864 		xfs_btree_del_cursor(acur->bnolt, cur_error);
865 	if (acur->bnogt)
866 		xfs_btree_del_cursor(acur->bnogt, cur_error);
867 	acur->cnt = acur->bnolt = acur->bnogt = NULL;
868 }
869 
870 /*
871  * Check an extent for allocation and track the best available candidate in the
872  * allocation structure. The cursor is deactivated if it has entered an out of
873  * range state based on allocation arguments. Optionally return the extent
874  * extent geometry and allocation status if requested by the caller.
875  */
876 static int
877 xfs_alloc_cur_check(
878 	struct xfs_alloc_arg	*args,
879 	struct xfs_alloc_cur	*acur,
880 	struct xfs_btree_cur	*cur,
881 	int			*new)
882 {
883 	int			error, i;
884 	xfs_agblock_t		bno, bnoa, bnew;
885 	xfs_extlen_t		len, lena, diff = -1;
886 	bool			busy;
887 	unsigned		busy_gen = 0;
888 	bool			deactivate = false;
889 	bool			isbnobt = cur->bc_btnum == XFS_BTNUM_BNO;
890 
891 	*new = 0;
892 
893 	error = xfs_alloc_get_rec(cur, &bno, &len, &i);
894 	if (error)
895 		return error;
896 	if (XFS_IS_CORRUPT(args->mp, i != 1))
897 		return -EFSCORRUPTED;
898 
899 	/*
900 	 * Check minlen and deactivate a cntbt cursor if out of acceptable size
901 	 * range (i.e., walking backwards looking for a minlen extent).
902 	 */
903 	if (len < args->minlen) {
904 		deactivate = !isbnobt;
905 		goto out;
906 	}
907 
908 	busy = xfs_alloc_compute_aligned(args, bno, len, &bnoa, &lena,
909 					 &busy_gen);
910 	acur->busy |= busy;
911 	if (busy)
912 		acur->busy_gen = busy_gen;
913 	/* deactivate a bnobt cursor outside of locality range */
914 	if (bnoa < args->min_agbno || bnoa > args->max_agbno) {
915 		deactivate = isbnobt;
916 		goto out;
917 	}
918 	if (lena < args->minlen)
919 		goto out;
920 
921 	args->len = XFS_EXTLEN_MIN(lena, args->maxlen);
922 	xfs_alloc_fix_len(args);
923 	ASSERT(args->len >= args->minlen);
924 	if (args->len < acur->len)
925 		goto out;
926 
927 	/*
928 	 * We have an aligned record that satisfies minlen and beats or matches
929 	 * the candidate extent size. Compare locality for near allocation mode.
930 	 */
931 	diff = xfs_alloc_compute_diff(args->agbno, args->len,
932 				      args->alignment, args->datatype,
933 				      bnoa, lena, &bnew);
934 	if (bnew == NULLAGBLOCK)
935 		goto out;
936 
937 	/*
938 	 * Deactivate a bnobt cursor with worse locality than the current best.
939 	 */
940 	if (diff > acur->diff) {
941 		deactivate = isbnobt;
942 		goto out;
943 	}
944 
945 	ASSERT(args->len > acur->len ||
946 	       (args->len == acur->len && diff <= acur->diff));
947 	acur->rec_bno = bno;
948 	acur->rec_len = len;
949 	acur->bno = bnew;
950 	acur->len = args->len;
951 	acur->diff = diff;
952 	*new = 1;
953 
954 	/*
955 	 * We're done if we found a perfect allocation. This only deactivates
956 	 * the current cursor, but this is just an optimization to terminate a
957 	 * cntbt search that otherwise runs to the edge of the tree.
958 	 */
959 	if (acur->diff == 0 && acur->len == args->maxlen)
960 		deactivate = true;
961 out:
962 	if (deactivate)
963 		cur->bc_ag.abt.active = false;
964 	trace_xfs_alloc_cur_check(args->mp, cur->bc_btnum, bno, len, diff,
965 				  *new);
966 	return 0;
967 }
968 
969 /*
970  * Complete an allocation of a candidate extent. Remove the extent from both
971  * trees and update the args structure.
972  */
973 STATIC int
974 xfs_alloc_cur_finish(
975 	struct xfs_alloc_arg	*args,
976 	struct xfs_alloc_cur	*acur)
977 {
978 	struct xfs_agf __maybe_unused *agf = args->agbp->b_addr;
979 	int			error;
980 
981 	ASSERT(acur->cnt && acur->bnolt);
982 	ASSERT(acur->bno >= acur->rec_bno);
983 	ASSERT(acur->bno + acur->len <= acur->rec_bno + acur->rec_len);
984 	ASSERT(acur->rec_bno + acur->rec_len <= be32_to_cpu(agf->agf_length));
985 
986 	error = xfs_alloc_fixup_trees(acur->cnt, acur->bnolt, acur->rec_bno,
987 				      acur->rec_len, acur->bno, acur->len, 0);
988 	if (error)
989 		return error;
990 
991 	args->agbno = acur->bno;
992 	args->len = acur->len;
993 	args->wasfromfl = 0;
994 
995 	trace_xfs_alloc_cur(args);
996 	return 0;
997 }
998 
999 /*
1000  * Locality allocation lookup algorithm. This expects a cntbt cursor and uses
1001  * bno optimized lookup to search for extents with ideal size and locality.
1002  */
1003 STATIC int
1004 xfs_alloc_cntbt_iter(
1005 	struct xfs_alloc_arg		*args,
1006 	struct xfs_alloc_cur		*acur)
1007 {
1008 	struct xfs_btree_cur	*cur = acur->cnt;
1009 	xfs_agblock_t		bno;
1010 	xfs_extlen_t		len, cur_len;
1011 	int			error;
1012 	int			i;
1013 
1014 	if (!xfs_alloc_cur_active(cur))
1015 		return 0;
1016 
1017 	/* locality optimized lookup */
1018 	cur_len = acur->cur_len;
1019 	error = xfs_alloc_lookup_ge(cur, args->agbno, cur_len, &i);
1020 	if (error)
1021 		return error;
1022 	if (i == 0)
1023 		return 0;
1024 	error = xfs_alloc_get_rec(cur, &bno, &len, &i);
1025 	if (error)
1026 		return error;
1027 
1028 	/* check the current record and update search length from it */
1029 	error = xfs_alloc_cur_check(args, acur, cur, &i);
1030 	if (error)
1031 		return error;
1032 	ASSERT(len >= acur->cur_len);
1033 	acur->cur_len = len;
1034 
1035 	/*
1036 	 * We looked up the first record >= [agbno, len] above. The agbno is a
1037 	 * secondary key and so the current record may lie just before or after
1038 	 * agbno. If it is past agbno, check the previous record too so long as
1039 	 * the length matches as it may be closer. Don't check a smaller record
1040 	 * because that could deactivate our cursor.
1041 	 */
1042 	if (bno > args->agbno) {
1043 		error = xfs_btree_decrement(cur, 0, &i);
1044 		if (!error && i) {
1045 			error = xfs_alloc_get_rec(cur, &bno, &len, &i);
1046 			if (!error && i && len == acur->cur_len)
1047 				error = xfs_alloc_cur_check(args, acur, cur,
1048 							    &i);
1049 		}
1050 		if (error)
1051 			return error;
1052 	}
1053 
1054 	/*
1055 	 * Increment the search key until we find at least one allocation
1056 	 * candidate or if the extent we found was larger. Otherwise, double the
1057 	 * search key to optimize the search. Efficiency is more important here
1058 	 * than absolute best locality.
1059 	 */
1060 	cur_len <<= 1;
1061 	if (!acur->len || acur->cur_len >= cur_len)
1062 		acur->cur_len++;
1063 	else
1064 		acur->cur_len = cur_len;
1065 
1066 	return error;
1067 }
1068 
1069 /*
1070  * Deal with the case where only small freespaces remain. Either return the
1071  * contents of the last freespace record, or allocate space from the freelist if
1072  * there is nothing in the tree.
1073  */
1074 STATIC int			/* error */
1075 xfs_alloc_ag_vextent_small(
1076 	struct xfs_alloc_arg	*args,	/* allocation argument structure */
1077 	struct xfs_btree_cur	*ccur,	/* optional by-size cursor */
1078 	xfs_agblock_t		*fbnop,	/* result block number */
1079 	xfs_extlen_t		*flenp,	/* result length */
1080 	int			*stat)	/* status: 0-freelist, 1-normal/none */
1081 {
1082 	struct xfs_agf		*agf = args->agbp->b_addr;
1083 	int			error = 0;
1084 	xfs_agblock_t		fbno = NULLAGBLOCK;
1085 	xfs_extlen_t		flen = 0;
1086 	int			i = 0;
1087 
1088 	/*
1089 	 * If a cntbt cursor is provided, try to allocate the largest record in
1090 	 * the tree. Try the AGFL if the cntbt is empty, otherwise fail the
1091 	 * allocation. Make sure to respect minleft even when pulling from the
1092 	 * freelist.
1093 	 */
1094 	if (ccur)
1095 		error = xfs_btree_decrement(ccur, 0, &i);
1096 	if (error)
1097 		goto error;
1098 	if (i) {
1099 		error = xfs_alloc_get_rec(ccur, &fbno, &flen, &i);
1100 		if (error)
1101 			goto error;
1102 		if (XFS_IS_CORRUPT(args->mp, i != 1)) {
1103 			error = -EFSCORRUPTED;
1104 			goto error;
1105 		}
1106 		goto out;
1107 	}
1108 
1109 	if (args->minlen != 1 || args->alignment != 1 ||
1110 	    args->resv == XFS_AG_RESV_AGFL ||
1111 	    be32_to_cpu(agf->agf_flcount) <= args->minleft)
1112 		goto out;
1113 
1114 	error = xfs_alloc_get_freelist(args->pag, args->tp, args->agbp,
1115 			&fbno, 0);
1116 	if (error)
1117 		goto error;
1118 	if (fbno == NULLAGBLOCK)
1119 		goto out;
1120 
1121 	xfs_extent_busy_reuse(args->mp, args->pag, fbno, 1,
1122 			      (args->datatype & XFS_ALLOC_NOBUSY));
1123 
1124 	if (args->datatype & XFS_ALLOC_USERDATA) {
1125 		struct xfs_buf	*bp;
1126 
1127 		error = xfs_trans_get_buf(args->tp, args->mp->m_ddev_targp,
1128 				XFS_AGB_TO_DADDR(args->mp, args->agno, fbno),
1129 				args->mp->m_bsize, 0, &bp);
1130 		if (error)
1131 			goto error;
1132 		xfs_trans_binval(args->tp, bp);
1133 	}
1134 	*fbnop = args->agbno = fbno;
1135 	*flenp = args->len = 1;
1136 	if (XFS_IS_CORRUPT(args->mp, fbno >= be32_to_cpu(agf->agf_length))) {
1137 		error = -EFSCORRUPTED;
1138 		goto error;
1139 	}
1140 	args->wasfromfl = 1;
1141 	trace_xfs_alloc_small_freelist(args);
1142 
1143 	/*
1144 	 * If we're feeding an AGFL block to something that doesn't live in the
1145 	 * free space, we need to clear out the OWN_AG rmap.
1146 	 */
1147 	error = xfs_rmap_free(args->tp, args->agbp, args->pag, fbno, 1,
1148 			      &XFS_RMAP_OINFO_AG);
1149 	if (error)
1150 		goto error;
1151 
1152 	*stat = 0;
1153 	return 0;
1154 
1155 out:
1156 	/*
1157 	 * Can't do the allocation, give up.
1158 	 */
1159 	if (flen < args->minlen) {
1160 		args->agbno = NULLAGBLOCK;
1161 		trace_xfs_alloc_small_notenough(args);
1162 		flen = 0;
1163 	}
1164 	*fbnop = fbno;
1165 	*flenp = flen;
1166 	*stat = 1;
1167 	trace_xfs_alloc_small_done(args);
1168 	return 0;
1169 
1170 error:
1171 	trace_xfs_alloc_small_error(args);
1172 	return error;
1173 }
1174 
1175 /*
1176  * Allocate a variable extent at exactly agno/bno.
1177  * Extent's length (returned in *len) will be between minlen and maxlen,
1178  * and of the form k * prod + mod unless there's nothing that large.
1179  * Return the starting a.g. block (bno), or NULLAGBLOCK if we can't do it.
1180  */
1181 STATIC int			/* error */
1182 xfs_alloc_ag_vextent_exact(
1183 	xfs_alloc_arg_t	*args)	/* allocation argument structure */
1184 {
1185 	struct xfs_agf __maybe_unused *agf = args->agbp->b_addr;
1186 	struct xfs_btree_cur *bno_cur;/* by block-number btree cursor */
1187 	struct xfs_btree_cur *cnt_cur;/* by count btree cursor */
1188 	int		error;
1189 	xfs_agblock_t	fbno;	/* start block of found extent */
1190 	xfs_extlen_t	flen;	/* length of found extent */
1191 	xfs_agblock_t	tbno;	/* start block of busy extent */
1192 	xfs_extlen_t	tlen;	/* length of busy extent */
1193 	xfs_agblock_t	tend;	/* end block of busy extent */
1194 	int		i;	/* success/failure of operation */
1195 	unsigned	busy_gen;
1196 
1197 	ASSERT(args->alignment == 1);
1198 
1199 	/*
1200 	 * Allocate/initialize a cursor for the by-number freespace btree.
1201 	 */
1202 	bno_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1203 					  args->pag, XFS_BTNUM_BNO);
1204 
1205 	/*
1206 	 * Lookup bno and minlen in the btree (minlen is irrelevant, really).
1207 	 * Look for the closest free block <= bno, it must contain bno
1208 	 * if any free block does.
1209 	 */
1210 	error = xfs_alloc_lookup_le(bno_cur, args->agbno, args->minlen, &i);
1211 	if (error)
1212 		goto error0;
1213 	if (!i)
1214 		goto not_found;
1215 
1216 	/*
1217 	 * Grab the freespace record.
1218 	 */
1219 	error = xfs_alloc_get_rec(bno_cur, &fbno, &flen, &i);
1220 	if (error)
1221 		goto error0;
1222 	if (XFS_IS_CORRUPT(args->mp, i != 1)) {
1223 		error = -EFSCORRUPTED;
1224 		goto error0;
1225 	}
1226 	ASSERT(fbno <= args->agbno);
1227 
1228 	/*
1229 	 * Check for overlapping busy extents.
1230 	 */
1231 	tbno = fbno;
1232 	tlen = flen;
1233 	xfs_extent_busy_trim(args, &tbno, &tlen, &busy_gen);
1234 
1235 	/*
1236 	 * Give up if the start of the extent is busy, or the freespace isn't
1237 	 * long enough for the minimum request.
1238 	 */
1239 	if (tbno > args->agbno)
1240 		goto not_found;
1241 	if (tlen < args->minlen)
1242 		goto not_found;
1243 	tend = tbno + tlen;
1244 	if (tend < args->agbno + args->minlen)
1245 		goto not_found;
1246 
1247 	/*
1248 	 * End of extent will be smaller of the freespace end and the
1249 	 * maximal requested end.
1250 	 *
1251 	 * Fix the length according to mod and prod if given.
1252 	 */
1253 	args->len = XFS_AGBLOCK_MIN(tend, args->agbno + args->maxlen)
1254 						- args->agbno;
1255 	xfs_alloc_fix_len(args);
1256 	ASSERT(args->agbno + args->len <= tend);
1257 
1258 	/*
1259 	 * We are allocating agbno for args->len
1260 	 * Allocate/initialize a cursor for the by-size btree.
1261 	 */
1262 	cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1263 					args->pag, XFS_BTNUM_CNT);
1264 	ASSERT(args->agbno + args->len <= be32_to_cpu(agf->agf_length));
1265 	error = xfs_alloc_fixup_trees(cnt_cur, bno_cur, fbno, flen, args->agbno,
1266 				      args->len, XFSA_FIXUP_BNO_OK);
1267 	if (error) {
1268 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1269 		goto error0;
1270 	}
1271 
1272 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
1273 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1274 
1275 	args->wasfromfl = 0;
1276 	trace_xfs_alloc_exact_done(args);
1277 	return 0;
1278 
1279 not_found:
1280 	/* Didn't find it, return null. */
1281 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
1282 	args->agbno = NULLAGBLOCK;
1283 	trace_xfs_alloc_exact_notfound(args);
1284 	return 0;
1285 
1286 error0:
1287 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
1288 	trace_xfs_alloc_exact_error(args);
1289 	return error;
1290 }
1291 
1292 /*
1293  * Search a given number of btree records in a given direction. Check each
1294  * record against the good extent we've already found.
1295  */
1296 STATIC int
1297 xfs_alloc_walk_iter(
1298 	struct xfs_alloc_arg	*args,
1299 	struct xfs_alloc_cur	*acur,
1300 	struct xfs_btree_cur	*cur,
1301 	bool			increment,
1302 	bool			find_one, /* quit on first candidate */
1303 	int			count,    /* rec count (-1 for infinite) */
1304 	int			*stat)
1305 {
1306 	int			error;
1307 	int			i;
1308 
1309 	*stat = 0;
1310 
1311 	/*
1312 	 * Search so long as the cursor is active or we find a better extent.
1313 	 * The cursor is deactivated if it extends beyond the range of the
1314 	 * current allocation candidate.
1315 	 */
1316 	while (xfs_alloc_cur_active(cur) && count) {
1317 		error = xfs_alloc_cur_check(args, acur, cur, &i);
1318 		if (error)
1319 			return error;
1320 		if (i == 1) {
1321 			*stat = 1;
1322 			if (find_one)
1323 				break;
1324 		}
1325 		if (!xfs_alloc_cur_active(cur))
1326 			break;
1327 
1328 		if (increment)
1329 			error = xfs_btree_increment(cur, 0, &i);
1330 		else
1331 			error = xfs_btree_decrement(cur, 0, &i);
1332 		if (error)
1333 			return error;
1334 		if (i == 0)
1335 			cur->bc_ag.abt.active = false;
1336 
1337 		if (count > 0)
1338 			count--;
1339 	}
1340 
1341 	return 0;
1342 }
1343 
1344 /*
1345  * Search the by-bno and by-size btrees in parallel in search of an extent with
1346  * ideal locality based on the NEAR mode ->agbno locality hint.
1347  */
1348 STATIC int
1349 xfs_alloc_ag_vextent_locality(
1350 	struct xfs_alloc_arg	*args,
1351 	struct xfs_alloc_cur	*acur,
1352 	int			*stat)
1353 {
1354 	struct xfs_btree_cur	*fbcur = NULL;
1355 	int			error;
1356 	int			i;
1357 	bool			fbinc;
1358 
1359 	ASSERT(acur->len == 0);
1360 
1361 	*stat = 0;
1362 
1363 	error = xfs_alloc_lookup_ge(acur->cnt, args->agbno, acur->cur_len, &i);
1364 	if (error)
1365 		return error;
1366 	error = xfs_alloc_lookup_le(acur->bnolt, args->agbno, 0, &i);
1367 	if (error)
1368 		return error;
1369 	error = xfs_alloc_lookup_ge(acur->bnogt, args->agbno, 0, &i);
1370 	if (error)
1371 		return error;
1372 
1373 	/*
1374 	 * Search the bnobt and cntbt in parallel. Search the bnobt left and
1375 	 * right and lookup the closest extent to the locality hint for each
1376 	 * extent size key in the cntbt. The entire search terminates
1377 	 * immediately on a bnobt hit because that means we've found best case
1378 	 * locality. Otherwise the search continues until the cntbt cursor runs
1379 	 * off the end of the tree. If no allocation candidate is found at this
1380 	 * point, give up on locality, walk backwards from the end of the cntbt
1381 	 * and take the first available extent.
1382 	 *
1383 	 * The parallel tree searches balance each other out to provide fairly
1384 	 * consistent performance for various situations. The bnobt search can
1385 	 * have pathological behavior in the worst case scenario of larger
1386 	 * allocation requests and fragmented free space. On the other hand, the
1387 	 * bnobt is able to satisfy most smaller allocation requests much more
1388 	 * quickly than the cntbt. The cntbt search can sift through fragmented
1389 	 * free space and sets of free extents for larger allocation requests
1390 	 * more quickly than the bnobt. Since the locality hint is just a hint
1391 	 * and we don't want to scan the entire bnobt for perfect locality, the
1392 	 * cntbt search essentially bounds the bnobt search such that we can
1393 	 * find good enough locality at reasonable performance in most cases.
1394 	 */
1395 	while (xfs_alloc_cur_active(acur->bnolt) ||
1396 	       xfs_alloc_cur_active(acur->bnogt) ||
1397 	       xfs_alloc_cur_active(acur->cnt)) {
1398 
1399 		trace_xfs_alloc_cur_lookup(args);
1400 
1401 		/*
1402 		 * Search the bnobt left and right. In the case of a hit, finish
1403 		 * the search in the opposite direction and we're done.
1404 		 */
1405 		error = xfs_alloc_walk_iter(args, acur, acur->bnolt, false,
1406 					    true, 1, &i);
1407 		if (error)
1408 			return error;
1409 		if (i == 1) {
1410 			trace_xfs_alloc_cur_left(args);
1411 			fbcur = acur->bnogt;
1412 			fbinc = true;
1413 			break;
1414 		}
1415 		error = xfs_alloc_walk_iter(args, acur, acur->bnogt, true, true,
1416 					    1, &i);
1417 		if (error)
1418 			return error;
1419 		if (i == 1) {
1420 			trace_xfs_alloc_cur_right(args);
1421 			fbcur = acur->bnolt;
1422 			fbinc = false;
1423 			break;
1424 		}
1425 
1426 		/*
1427 		 * Check the extent with best locality based on the current
1428 		 * extent size search key and keep track of the best candidate.
1429 		 */
1430 		error = xfs_alloc_cntbt_iter(args, acur);
1431 		if (error)
1432 			return error;
1433 		if (!xfs_alloc_cur_active(acur->cnt)) {
1434 			trace_xfs_alloc_cur_lookup_done(args);
1435 			break;
1436 		}
1437 	}
1438 
1439 	/*
1440 	 * If we failed to find anything due to busy extents, return empty
1441 	 * handed so the caller can flush and retry. If no busy extents were
1442 	 * found, walk backwards from the end of the cntbt as a last resort.
1443 	 */
1444 	if (!xfs_alloc_cur_active(acur->cnt) && !acur->len && !acur->busy) {
1445 		error = xfs_btree_decrement(acur->cnt, 0, &i);
1446 		if (error)
1447 			return error;
1448 		if (i) {
1449 			acur->cnt->bc_ag.abt.active = true;
1450 			fbcur = acur->cnt;
1451 			fbinc = false;
1452 		}
1453 	}
1454 
1455 	/*
1456 	 * Search in the opposite direction for a better entry in the case of
1457 	 * a bnobt hit or walk backwards from the end of the cntbt.
1458 	 */
1459 	if (fbcur) {
1460 		error = xfs_alloc_walk_iter(args, acur, fbcur, fbinc, true, -1,
1461 					    &i);
1462 		if (error)
1463 			return error;
1464 	}
1465 
1466 	if (acur->len)
1467 		*stat = 1;
1468 
1469 	return 0;
1470 }
1471 
1472 /* Check the last block of the cnt btree for allocations. */
1473 static int
1474 xfs_alloc_ag_vextent_lastblock(
1475 	struct xfs_alloc_arg	*args,
1476 	struct xfs_alloc_cur	*acur,
1477 	xfs_agblock_t		*bno,
1478 	xfs_extlen_t		*len,
1479 	bool			*allocated)
1480 {
1481 	int			error;
1482 	int			i;
1483 
1484 #ifdef DEBUG
1485 	/* Randomly don't execute the first algorithm. */
1486 	if (get_random_u32_below(2))
1487 		return 0;
1488 #endif
1489 
1490 	/*
1491 	 * Start from the entry that lookup found, sequence through all larger
1492 	 * free blocks.  If we're actually pointing at a record smaller than
1493 	 * maxlen, go to the start of this block, and skip all those smaller
1494 	 * than minlen.
1495 	 */
1496 	if (*len || args->alignment > 1) {
1497 		acur->cnt->bc_levels[0].ptr = 1;
1498 		do {
1499 			error = xfs_alloc_get_rec(acur->cnt, bno, len, &i);
1500 			if (error)
1501 				return error;
1502 			if (XFS_IS_CORRUPT(args->mp, i != 1))
1503 				return -EFSCORRUPTED;
1504 			if (*len >= args->minlen)
1505 				break;
1506 			error = xfs_btree_increment(acur->cnt, 0, &i);
1507 			if (error)
1508 				return error;
1509 		} while (i);
1510 		ASSERT(*len >= args->minlen);
1511 		if (!i)
1512 			return 0;
1513 	}
1514 
1515 	error = xfs_alloc_walk_iter(args, acur, acur->cnt, true, false, -1, &i);
1516 	if (error)
1517 		return error;
1518 
1519 	/*
1520 	 * It didn't work.  We COULD be in a case where there's a good record
1521 	 * somewhere, so try again.
1522 	 */
1523 	if (acur->len == 0)
1524 		return 0;
1525 
1526 	trace_xfs_alloc_near_first(args);
1527 	*allocated = true;
1528 	return 0;
1529 }
1530 
1531 /*
1532  * Allocate a variable extent near bno in the allocation group agno.
1533  * Extent's length (returned in len) will be between minlen and maxlen,
1534  * and of the form k * prod + mod unless there's nothing that large.
1535  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
1536  */
1537 STATIC int
1538 xfs_alloc_ag_vextent_near(
1539 	struct xfs_alloc_arg	*args)
1540 {
1541 	struct xfs_alloc_cur	acur = {};
1542 	int			error;		/* error code */
1543 	int			i;		/* result code, temporary */
1544 	xfs_agblock_t		bno;
1545 	xfs_extlen_t		len;
1546 
1547 	/* handle uninitialized agbno range so caller doesn't have to */
1548 	if (!args->min_agbno && !args->max_agbno)
1549 		args->max_agbno = args->mp->m_sb.sb_agblocks - 1;
1550 	ASSERT(args->min_agbno <= args->max_agbno);
1551 
1552 	/* clamp agbno to the range if it's outside */
1553 	if (args->agbno < args->min_agbno)
1554 		args->agbno = args->min_agbno;
1555 	if (args->agbno > args->max_agbno)
1556 		args->agbno = args->max_agbno;
1557 
1558 restart:
1559 	len = 0;
1560 
1561 	/*
1562 	 * Set up cursors and see if there are any free extents as big as
1563 	 * maxlen. If not, pick the last entry in the tree unless the tree is
1564 	 * empty.
1565 	 */
1566 	error = xfs_alloc_cur_setup(args, &acur);
1567 	if (error == -ENOSPC) {
1568 		error = xfs_alloc_ag_vextent_small(args, acur.cnt, &bno,
1569 				&len, &i);
1570 		if (error)
1571 			goto out;
1572 		if (i == 0 || len == 0) {
1573 			trace_xfs_alloc_near_noentry(args);
1574 			goto out;
1575 		}
1576 		ASSERT(i == 1);
1577 	} else if (error) {
1578 		goto out;
1579 	}
1580 
1581 	/*
1582 	 * First algorithm.
1583 	 * If the requested extent is large wrt the freespaces available
1584 	 * in this a.g., then the cursor will be pointing to a btree entry
1585 	 * near the right edge of the tree.  If it's in the last btree leaf
1586 	 * block, then we just examine all the entries in that block
1587 	 * that are big enough, and pick the best one.
1588 	 */
1589 	if (xfs_btree_islastblock(acur.cnt, 0)) {
1590 		bool		allocated = false;
1591 
1592 		error = xfs_alloc_ag_vextent_lastblock(args, &acur, &bno, &len,
1593 				&allocated);
1594 		if (error)
1595 			goto out;
1596 		if (allocated)
1597 			goto alloc_finish;
1598 	}
1599 
1600 	/*
1601 	 * Second algorithm. Combined cntbt and bnobt search to find ideal
1602 	 * locality.
1603 	 */
1604 	error = xfs_alloc_ag_vextent_locality(args, &acur, &i);
1605 	if (error)
1606 		goto out;
1607 
1608 	/*
1609 	 * If we couldn't get anything, give up.
1610 	 */
1611 	if (!acur.len) {
1612 		if (acur.busy) {
1613 			trace_xfs_alloc_near_busy(args);
1614 			xfs_extent_busy_flush(args->mp, args->pag,
1615 					      acur.busy_gen);
1616 			goto restart;
1617 		}
1618 		trace_xfs_alloc_size_neither(args);
1619 		args->agbno = NULLAGBLOCK;
1620 		goto out;
1621 	}
1622 
1623 alloc_finish:
1624 	/* fix up btrees on a successful allocation */
1625 	error = xfs_alloc_cur_finish(args, &acur);
1626 
1627 out:
1628 	xfs_alloc_cur_close(&acur, error);
1629 	return error;
1630 }
1631 
1632 /*
1633  * Allocate a variable extent anywhere in the allocation group agno.
1634  * Extent's length (returned in len) will be between minlen and maxlen,
1635  * and of the form k * prod + mod unless there's nothing that large.
1636  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
1637  */
1638 STATIC int				/* error */
1639 xfs_alloc_ag_vextent_size(
1640 	xfs_alloc_arg_t	*args)		/* allocation argument structure */
1641 {
1642 	struct xfs_agf	*agf = args->agbp->b_addr;
1643 	struct xfs_btree_cur *bno_cur;	/* cursor for bno btree */
1644 	struct xfs_btree_cur *cnt_cur;	/* cursor for cnt btree */
1645 	int		error;		/* error result */
1646 	xfs_agblock_t	fbno;		/* start of found freespace */
1647 	xfs_extlen_t	flen;		/* length of found freespace */
1648 	int		i;		/* temp status variable */
1649 	xfs_agblock_t	rbno;		/* returned block number */
1650 	xfs_extlen_t	rlen;		/* length of returned extent */
1651 	bool		busy;
1652 	unsigned	busy_gen;
1653 
1654 restart:
1655 	/*
1656 	 * Allocate and initialize a cursor for the by-size btree.
1657 	 */
1658 	cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1659 					args->pag, XFS_BTNUM_CNT);
1660 	bno_cur = NULL;
1661 
1662 	/*
1663 	 * Look for an entry >= maxlen+alignment-1 blocks.
1664 	 */
1665 	if ((error = xfs_alloc_lookup_ge(cnt_cur, 0,
1666 			args->maxlen + args->alignment - 1, &i)))
1667 		goto error0;
1668 
1669 	/*
1670 	 * If none then we have to settle for a smaller extent. In the case that
1671 	 * there are no large extents, this will return the last entry in the
1672 	 * tree unless the tree is empty. In the case that there are only busy
1673 	 * large extents, this will return the largest small extent unless there
1674 	 * are no smaller extents available.
1675 	 */
1676 	if (!i) {
1677 		error = xfs_alloc_ag_vextent_small(args, cnt_cur,
1678 						   &fbno, &flen, &i);
1679 		if (error)
1680 			goto error0;
1681 		if (i == 0 || flen == 0) {
1682 			xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1683 			trace_xfs_alloc_size_noentry(args);
1684 			return 0;
1685 		}
1686 		ASSERT(i == 1);
1687 		busy = xfs_alloc_compute_aligned(args, fbno, flen, &rbno,
1688 				&rlen, &busy_gen);
1689 	} else {
1690 		/*
1691 		 * Search for a non-busy extent that is large enough.
1692 		 */
1693 		for (;;) {
1694 			error = xfs_alloc_get_rec(cnt_cur, &fbno, &flen, &i);
1695 			if (error)
1696 				goto error0;
1697 			if (XFS_IS_CORRUPT(args->mp, i != 1)) {
1698 				error = -EFSCORRUPTED;
1699 				goto error0;
1700 			}
1701 
1702 			busy = xfs_alloc_compute_aligned(args, fbno, flen,
1703 					&rbno, &rlen, &busy_gen);
1704 
1705 			if (rlen >= args->maxlen)
1706 				break;
1707 
1708 			error = xfs_btree_increment(cnt_cur, 0, &i);
1709 			if (error)
1710 				goto error0;
1711 			if (i == 0) {
1712 				/*
1713 				 * Our only valid extents must have been busy.
1714 				 * Make it unbusy by forcing the log out and
1715 				 * retrying.
1716 				 */
1717 				xfs_btree_del_cursor(cnt_cur,
1718 						     XFS_BTREE_NOERROR);
1719 				trace_xfs_alloc_size_busy(args);
1720 				xfs_extent_busy_flush(args->mp,
1721 							args->pag, busy_gen);
1722 				goto restart;
1723 			}
1724 		}
1725 	}
1726 
1727 	/*
1728 	 * In the first case above, we got the last entry in the
1729 	 * by-size btree.  Now we check to see if the space hits maxlen
1730 	 * once aligned; if not, we search left for something better.
1731 	 * This can't happen in the second case above.
1732 	 */
1733 	rlen = XFS_EXTLEN_MIN(args->maxlen, rlen);
1734 	if (XFS_IS_CORRUPT(args->mp,
1735 			   rlen != 0 &&
1736 			   (rlen > flen ||
1737 			    rbno + rlen > fbno + flen))) {
1738 		error = -EFSCORRUPTED;
1739 		goto error0;
1740 	}
1741 	if (rlen < args->maxlen) {
1742 		xfs_agblock_t	bestfbno;
1743 		xfs_extlen_t	bestflen;
1744 		xfs_agblock_t	bestrbno;
1745 		xfs_extlen_t	bestrlen;
1746 
1747 		bestrlen = rlen;
1748 		bestrbno = rbno;
1749 		bestflen = flen;
1750 		bestfbno = fbno;
1751 		for (;;) {
1752 			if ((error = xfs_btree_decrement(cnt_cur, 0, &i)))
1753 				goto error0;
1754 			if (i == 0)
1755 				break;
1756 			if ((error = xfs_alloc_get_rec(cnt_cur, &fbno, &flen,
1757 					&i)))
1758 				goto error0;
1759 			if (XFS_IS_CORRUPT(args->mp, i != 1)) {
1760 				error = -EFSCORRUPTED;
1761 				goto error0;
1762 			}
1763 			if (flen < bestrlen)
1764 				break;
1765 			busy = xfs_alloc_compute_aligned(args, fbno, flen,
1766 					&rbno, &rlen, &busy_gen);
1767 			rlen = XFS_EXTLEN_MIN(args->maxlen, rlen);
1768 			if (XFS_IS_CORRUPT(args->mp,
1769 					   rlen != 0 &&
1770 					   (rlen > flen ||
1771 					    rbno + rlen > fbno + flen))) {
1772 				error = -EFSCORRUPTED;
1773 				goto error0;
1774 			}
1775 			if (rlen > bestrlen) {
1776 				bestrlen = rlen;
1777 				bestrbno = rbno;
1778 				bestflen = flen;
1779 				bestfbno = fbno;
1780 				if (rlen == args->maxlen)
1781 					break;
1782 			}
1783 		}
1784 		if ((error = xfs_alloc_lookup_eq(cnt_cur, bestfbno, bestflen,
1785 				&i)))
1786 			goto error0;
1787 		if (XFS_IS_CORRUPT(args->mp, i != 1)) {
1788 			error = -EFSCORRUPTED;
1789 			goto error0;
1790 		}
1791 		rlen = bestrlen;
1792 		rbno = bestrbno;
1793 		flen = bestflen;
1794 		fbno = bestfbno;
1795 	}
1796 	args->wasfromfl = 0;
1797 	/*
1798 	 * Fix up the length.
1799 	 */
1800 	args->len = rlen;
1801 	if (rlen < args->minlen) {
1802 		if (busy) {
1803 			xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1804 			trace_xfs_alloc_size_busy(args);
1805 			xfs_extent_busy_flush(args->mp, args->pag, busy_gen);
1806 			goto restart;
1807 		}
1808 		goto out_nominleft;
1809 	}
1810 	xfs_alloc_fix_len(args);
1811 
1812 	rlen = args->len;
1813 	if (XFS_IS_CORRUPT(args->mp, rlen > flen)) {
1814 		error = -EFSCORRUPTED;
1815 		goto error0;
1816 	}
1817 	/*
1818 	 * Allocate and initialize a cursor for the by-block tree.
1819 	 */
1820 	bno_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1821 					args->pag, XFS_BTNUM_BNO);
1822 	if ((error = xfs_alloc_fixup_trees(cnt_cur, bno_cur, fbno, flen,
1823 			rbno, rlen, XFSA_FIXUP_CNT_OK)))
1824 		goto error0;
1825 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1826 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
1827 	cnt_cur = bno_cur = NULL;
1828 	args->len = rlen;
1829 	args->agbno = rbno;
1830 	if (XFS_IS_CORRUPT(args->mp,
1831 			   args->agbno + args->len >
1832 			   be32_to_cpu(agf->agf_length))) {
1833 		error = -EFSCORRUPTED;
1834 		goto error0;
1835 	}
1836 	trace_xfs_alloc_size_done(args);
1837 	return 0;
1838 
1839 error0:
1840 	trace_xfs_alloc_size_error(args);
1841 	if (cnt_cur)
1842 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1843 	if (bno_cur)
1844 		xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
1845 	return error;
1846 
1847 out_nominleft:
1848 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1849 	trace_xfs_alloc_size_nominleft(args);
1850 	args->agbno = NULLAGBLOCK;
1851 	return 0;
1852 }
1853 
1854 /*
1855  * Free the extent starting at agno/bno for length.
1856  */
1857 STATIC int
1858 xfs_free_ag_extent(
1859 	struct xfs_trans		*tp,
1860 	struct xfs_buf			*agbp,
1861 	xfs_agnumber_t			agno,
1862 	xfs_agblock_t			bno,
1863 	xfs_extlen_t			len,
1864 	const struct xfs_owner_info	*oinfo,
1865 	enum xfs_ag_resv_type		type)
1866 {
1867 	struct xfs_mount		*mp;
1868 	struct xfs_btree_cur		*bno_cur;
1869 	struct xfs_btree_cur		*cnt_cur;
1870 	xfs_agblock_t			gtbno; /* start of right neighbor */
1871 	xfs_extlen_t			gtlen; /* length of right neighbor */
1872 	xfs_agblock_t			ltbno; /* start of left neighbor */
1873 	xfs_extlen_t			ltlen; /* length of left neighbor */
1874 	xfs_agblock_t			nbno; /* new starting block of freesp */
1875 	xfs_extlen_t			nlen; /* new length of freespace */
1876 	int				haveleft; /* have a left neighbor */
1877 	int				haveright; /* have a right neighbor */
1878 	int				i;
1879 	int				error;
1880 	struct xfs_perag		*pag = agbp->b_pag;
1881 
1882 	bno_cur = cnt_cur = NULL;
1883 	mp = tp->t_mountp;
1884 
1885 	if (!xfs_rmap_should_skip_owner_update(oinfo)) {
1886 		error = xfs_rmap_free(tp, agbp, pag, bno, len, oinfo);
1887 		if (error)
1888 			goto error0;
1889 	}
1890 
1891 	/*
1892 	 * Allocate and initialize a cursor for the by-block btree.
1893 	 */
1894 	bno_cur = xfs_allocbt_init_cursor(mp, tp, agbp, pag, XFS_BTNUM_BNO);
1895 	/*
1896 	 * Look for a neighboring block on the left (lower block numbers)
1897 	 * that is contiguous with this space.
1898 	 */
1899 	if ((error = xfs_alloc_lookup_le(bno_cur, bno, len, &haveleft)))
1900 		goto error0;
1901 	if (haveleft) {
1902 		/*
1903 		 * There is a block to our left.
1904 		 */
1905 		if ((error = xfs_alloc_get_rec(bno_cur, &ltbno, &ltlen, &i)))
1906 			goto error0;
1907 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1908 			error = -EFSCORRUPTED;
1909 			goto error0;
1910 		}
1911 		/*
1912 		 * It's not contiguous, though.
1913 		 */
1914 		if (ltbno + ltlen < bno)
1915 			haveleft = 0;
1916 		else {
1917 			/*
1918 			 * If this failure happens the request to free this
1919 			 * space was invalid, it's (partly) already free.
1920 			 * Very bad.
1921 			 */
1922 			if (XFS_IS_CORRUPT(mp, ltbno + ltlen > bno)) {
1923 				error = -EFSCORRUPTED;
1924 				goto error0;
1925 			}
1926 		}
1927 	}
1928 	/*
1929 	 * Look for a neighboring block on the right (higher block numbers)
1930 	 * that is contiguous with this space.
1931 	 */
1932 	if ((error = xfs_btree_increment(bno_cur, 0, &haveright)))
1933 		goto error0;
1934 	if (haveright) {
1935 		/*
1936 		 * There is a block to our right.
1937 		 */
1938 		if ((error = xfs_alloc_get_rec(bno_cur, &gtbno, &gtlen, &i)))
1939 			goto error0;
1940 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1941 			error = -EFSCORRUPTED;
1942 			goto error0;
1943 		}
1944 		/*
1945 		 * It's not contiguous, though.
1946 		 */
1947 		if (bno + len < gtbno)
1948 			haveright = 0;
1949 		else {
1950 			/*
1951 			 * If this failure happens the request to free this
1952 			 * space was invalid, it's (partly) already free.
1953 			 * Very bad.
1954 			 */
1955 			if (XFS_IS_CORRUPT(mp, bno + len > gtbno)) {
1956 				error = -EFSCORRUPTED;
1957 				goto error0;
1958 			}
1959 		}
1960 	}
1961 	/*
1962 	 * Now allocate and initialize a cursor for the by-size tree.
1963 	 */
1964 	cnt_cur = xfs_allocbt_init_cursor(mp, tp, agbp, pag, XFS_BTNUM_CNT);
1965 	/*
1966 	 * Have both left and right contiguous neighbors.
1967 	 * Merge all three into a single free block.
1968 	 */
1969 	if (haveleft && haveright) {
1970 		/*
1971 		 * Delete the old by-size entry on the left.
1972 		 */
1973 		if ((error = xfs_alloc_lookup_eq(cnt_cur, ltbno, ltlen, &i)))
1974 			goto error0;
1975 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1976 			error = -EFSCORRUPTED;
1977 			goto error0;
1978 		}
1979 		if ((error = xfs_btree_delete(cnt_cur, &i)))
1980 			goto error0;
1981 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1982 			error = -EFSCORRUPTED;
1983 			goto error0;
1984 		}
1985 		/*
1986 		 * Delete the old by-size entry on the right.
1987 		 */
1988 		if ((error = xfs_alloc_lookup_eq(cnt_cur, gtbno, gtlen, &i)))
1989 			goto error0;
1990 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1991 			error = -EFSCORRUPTED;
1992 			goto error0;
1993 		}
1994 		if ((error = xfs_btree_delete(cnt_cur, &i)))
1995 			goto error0;
1996 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1997 			error = -EFSCORRUPTED;
1998 			goto error0;
1999 		}
2000 		/*
2001 		 * Delete the old by-block entry for the right block.
2002 		 */
2003 		if ((error = xfs_btree_delete(bno_cur, &i)))
2004 			goto error0;
2005 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2006 			error = -EFSCORRUPTED;
2007 			goto error0;
2008 		}
2009 		/*
2010 		 * Move the by-block cursor back to the left neighbor.
2011 		 */
2012 		if ((error = xfs_btree_decrement(bno_cur, 0, &i)))
2013 			goto error0;
2014 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2015 			error = -EFSCORRUPTED;
2016 			goto error0;
2017 		}
2018 #ifdef DEBUG
2019 		/*
2020 		 * Check that this is the right record: delete didn't
2021 		 * mangle the cursor.
2022 		 */
2023 		{
2024 			xfs_agblock_t	xxbno;
2025 			xfs_extlen_t	xxlen;
2026 
2027 			if ((error = xfs_alloc_get_rec(bno_cur, &xxbno, &xxlen,
2028 					&i)))
2029 				goto error0;
2030 			if (XFS_IS_CORRUPT(mp,
2031 					   i != 1 ||
2032 					   xxbno != ltbno ||
2033 					   xxlen != ltlen)) {
2034 				error = -EFSCORRUPTED;
2035 				goto error0;
2036 			}
2037 		}
2038 #endif
2039 		/*
2040 		 * Update remaining by-block entry to the new, joined block.
2041 		 */
2042 		nbno = ltbno;
2043 		nlen = len + ltlen + gtlen;
2044 		if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
2045 			goto error0;
2046 	}
2047 	/*
2048 	 * Have only a left contiguous neighbor.
2049 	 * Merge it together with the new freespace.
2050 	 */
2051 	else if (haveleft) {
2052 		/*
2053 		 * Delete the old by-size entry on the left.
2054 		 */
2055 		if ((error = xfs_alloc_lookup_eq(cnt_cur, ltbno, ltlen, &i)))
2056 			goto error0;
2057 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2058 			error = -EFSCORRUPTED;
2059 			goto error0;
2060 		}
2061 		if ((error = xfs_btree_delete(cnt_cur, &i)))
2062 			goto error0;
2063 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2064 			error = -EFSCORRUPTED;
2065 			goto error0;
2066 		}
2067 		/*
2068 		 * Back up the by-block cursor to the left neighbor, and
2069 		 * update its length.
2070 		 */
2071 		if ((error = xfs_btree_decrement(bno_cur, 0, &i)))
2072 			goto error0;
2073 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2074 			error = -EFSCORRUPTED;
2075 			goto error0;
2076 		}
2077 		nbno = ltbno;
2078 		nlen = len + ltlen;
2079 		if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
2080 			goto error0;
2081 	}
2082 	/*
2083 	 * Have only a right contiguous neighbor.
2084 	 * Merge it together with the new freespace.
2085 	 */
2086 	else if (haveright) {
2087 		/*
2088 		 * Delete the old by-size entry on the right.
2089 		 */
2090 		if ((error = xfs_alloc_lookup_eq(cnt_cur, gtbno, gtlen, &i)))
2091 			goto error0;
2092 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2093 			error = -EFSCORRUPTED;
2094 			goto error0;
2095 		}
2096 		if ((error = xfs_btree_delete(cnt_cur, &i)))
2097 			goto error0;
2098 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2099 			error = -EFSCORRUPTED;
2100 			goto error0;
2101 		}
2102 		/*
2103 		 * Update the starting block and length of the right
2104 		 * neighbor in the by-block tree.
2105 		 */
2106 		nbno = bno;
2107 		nlen = len + gtlen;
2108 		if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
2109 			goto error0;
2110 	}
2111 	/*
2112 	 * No contiguous neighbors.
2113 	 * Insert the new freespace into the by-block tree.
2114 	 */
2115 	else {
2116 		nbno = bno;
2117 		nlen = len;
2118 		if ((error = xfs_btree_insert(bno_cur, &i)))
2119 			goto error0;
2120 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2121 			error = -EFSCORRUPTED;
2122 			goto error0;
2123 		}
2124 	}
2125 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
2126 	bno_cur = NULL;
2127 	/*
2128 	 * In all cases we need to insert the new freespace in the by-size tree.
2129 	 */
2130 	if ((error = xfs_alloc_lookup_eq(cnt_cur, nbno, nlen, &i)))
2131 		goto error0;
2132 	if (XFS_IS_CORRUPT(mp, i != 0)) {
2133 		error = -EFSCORRUPTED;
2134 		goto error0;
2135 	}
2136 	if ((error = xfs_btree_insert(cnt_cur, &i)))
2137 		goto error0;
2138 	if (XFS_IS_CORRUPT(mp, i != 1)) {
2139 		error = -EFSCORRUPTED;
2140 		goto error0;
2141 	}
2142 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
2143 	cnt_cur = NULL;
2144 
2145 	/*
2146 	 * Update the freespace totals in the ag and superblock.
2147 	 */
2148 	error = xfs_alloc_update_counters(tp, agbp, len);
2149 	xfs_ag_resv_free_extent(agbp->b_pag, type, tp, len);
2150 	if (error)
2151 		goto error0;
2152 
2153 	XFS_STATS_INC(mp, xs_freex);
2154 	XFS_STATS_ADD(mp, xs_freeb, len);
2155 
2156 	trace_xfs_free_extent(mp, agno, bno, len, type, haveleft, haveright);
2157 
2158 	return 0;
2159 
2160  error0:
2161 	trace_xfs_free_extent(mp, agno, bno, len, type, -1, -1);
2162 	if (bno_cur)
2163 		xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
2164 	if (cnt_cur)
2165 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
2166 	return error;
2167 }
2168 
2169 /*
2170  * Visible (exported) allocation/free functions.
2171  * Some of these are used just by xfs_alloc_btree.c and this file.
2172  */
2173 
2174 /*
2175  * Compute and fill in value of m_alloc_maxlevels.
2176  */
2177 void
2178 xfs_alloc_compute_maxlevels(
2179 	xfs_mount_t	*mp)	/* file system mount structure */
2180 {
2181 	mp->m_alloc_maxlevels = xfs_btree_compute_maxlevels(mp->m_alloc_mnr,
2182 			(mp->m_sb.sb_agblocks + 1) / 2);
2183 	ASSERT(mp->m_alloc_maxlevels <= xfs_allocbt_maxlevels_ondisk());
2184 }
2185 
2186 /*
2187  * Find the length of the longest extent in an AG.  The 'need' parameter
2188  * specifies how much space we're going to need for the AGFL and the
2189  * 'reserved' parameter tells us how many blocks in this AG are reserved for
2190  * other callers.
2191  */
2192 xfs_extlen_t
2193 xfs_alloc_longest_free_extent(
2194 	struct xfs_perag	*pag,
2195 	xfs_extlen_t		need,
2196 	xfs_extlen_t		reserved)
2197 {
2198 	xfs_extlen_t		delta = 0;
2199 
2200 	/*
2201 	 * If the AGFL needs a recharge, we'll have to subtract that from the
2202 	 * longest extent.
2203 	 */
2204 	if (need > pag->pagf_flcount)
2205 		delta = need - pag->pagf_flcount;
2206 
2207 	/*
2208 	 * If we cannot maintain others' reservations with space from the
2209 	 * not-longest freesp extents, we'll have to subtract /that/ from
2210 	 * the longest extent too.
2211 	 */
2212 	if (pag->pagf_freeblks - pag->pagf_longest < reserved)
2213 		delta += reserved - (pag->pagf_freeblks - pag->pagf_longest);
2214 
2215 	/*
2216 	 * If the longest extent is long enough to satisfy all the
2217 	 * reservations and AGFL rules in place, we can return this extent.
2218 	 */
2219 	if (pag->pagf_longest > delta)
2220 		return min_t(xfs_extlen_t, pag->pag_mount->m_ag_max_usable,
2221 				pag->pagf_longest - delta);
2222 
2223 	/* Otherwise, let the caller try for 1 block if there's space. */
2224 	return pag->pagf_flcount > 0 || pag->pagf_longest > 0;
2225 }
2226 
2227 /*
2228  * Compute the minimum length of the AGFL in the given AG.  If @pag is NULL,
2229  * return the largest possible minimum length.
2230  */
2231 unsigned int
2232 xfs_alloc_min_freelist(
2233 	struct xfs_mount	*mp,
2234 	struct xfs_perag	*pag)
2235 {
2236 	/* AG btrees have at least 1 level. */
2237 	static const uint8_t	fake_levels[XFS_BTNUM_AGF] = {1, 1, 1};
2238 	const uint8_t		*levels = pag ? pag->pagf_levels : fake_levels;
2239 	unsigned int		min_free;
2240 
2241 	ASSERT(mp->m_alloc_maxlevels > 0);
2242 
2243 	/* space needed by-bno freespace btree */
2244 	min_free = min_t(unsigned int, levels[XFS_BTNUM_BNOi] + 1,
2245 				       mp->m_alloc_maxlevels);
2246 	/* space needed by-size freespace btree */
2247 	min_free += min_t(unsigned int, levels[XFS_BTNUM_CNTi] + 1,
2248 				       mp->m_alloc_maxlevels);
2249 	/* space needed reverse mapping used space btree */
2250 	if (xfs_has_rmapbt(mp))
2251 		min_free += min_t(unsigned int, levels[XFS_BTNUM_RMAPi] + 1,
2252 						mp->m_rmap_maxlevels);
2253 
2254 	return min_free;
2255 }
2256 
2257 /*
2258  * Check if the operation we are fixing up the freelist for should go ahead or
2259  * not. If we are freeing blocks, we always allow it, otherwise the allocation
2260  * is dependent on whether the size and shape of free space available will
2261  * permit the requested allocation to take place.
2262  */
2263 static bool
2264 xfs_alloc_space_available(
2265 	struct xfs_alloc_arg	*args,
2266 	xfs_extlen_t		min_free,
2267 	int			flags)
2268 {
2269 	struct xfs_perag	*pag = args->pag;
2270 	xfs_extlen_t		alloc_len, longest;
2271 	xfs_extlen_t		reservation; /* blocks that are still reserved */
2272 	int			available;
2273 	xfs_extlen_t		agflcount;
2274 
2275 	if (flags & XFS_ALLOC_FLAG_FREEING)
2276 		return true;
2277 
2278 	reservation = xfs_ag_resv_needed(pag, args->resv);
2279 
2280 	/* do we have enough contiguous free space for the allocation? */
2281 	alloc_len = args->minlen + (args->alignment - 1) + args->minalignslop;
2282 	longest = xfs_alloc_longest_free_extent(pag, min_free, reservation);
2283 	if (longest < alloc_len)
2284 		return false;
2285 
2286 	/*
2287 	 * Do we have enough free space remaining for the allocation? Don't
2288 	 * account extra agfl blocks because we are about to defer free them,
2289 	 * making them unavailable until the current transaction commits.
2290 	 */
2291 	agflcount = min_t(xfs_extlen_t, pag->pagf_flcount, min_free);
2292 	available = (int)(pag->pagf_freeblks + agflcount -
2293 			  reservation - min_free - args->minleft);
2294 	if (available < (int)max(args->total, alloc_len))
2295 		return false;
2296 
2297 	/*
2298 	 * Clamp maxlen to the amount of free space available for the actual
2299 	 * extent allocation.
2300 	 */
2301 	if (available < (int)args->maxlen && !(flags & XFS_ALLOC_FLAG_CHECK)) {
2302 		args->maxlen = available;
2303 		ASSERT(args->maxlen > 0);
2304 		ASSERT(args->maxlen >= args->minlen);
2305 	}
2306 
2307 	return true;
2308 }
2309 
2310 int
2311 xfs_free_agfl_block(
2312 	struct xfs_trans	*tp,
2313 	xfs_agnumber_t		agno,
2314 	xfs_agblock_t		agbno,
2315 	struct xfs_buf		*agbp,
2316 	struct xfs_owner_info	*oinfo)
2317 {
2318 	int			error;
2319 	struct xfs_buf		*bp;
2320 
2321 	error = xfs_free_ag_extent(tp, agbp, agno, agbno, 1, oinfo,
2322 				   XFS_AG_RESV_AGFL);
2323 	if (error)
2324 		return error;
2325 
2326 	error = xfs_trans_get_buf(tp, tp->t_mountp->m_ddev_targp,
2327 			XFS_AGB_TO_DADDR(tp->t_mountp, agno, agbno),
2328 			tp->t_mountp->m_bsize, 0, &bp);
2329 	if (error)
2330 		return error;
2331 	xfs_trans_binval(tp, bp);
2332 
2333 	return 0;
2334 }
2335 
2336 /*
2337  * Check the agfl fields of the agf for inconsistency or corruption.
2338  *
2339  * The original purpose was to detect an agfl header padding mismatch between
2340  * current and early v5 kernels. This problem manifests as a 1-slot size
2341  * difference between the on-disk flcount and the active [first, last] range of
2342  * a wrapped agfl.
2343  *
2344  * However, we need to use these same checks to catch agfl count corruptions
2345  * unrelated to padding. This could occur on any v4 or v5 filesystem, so either
2346  * way, we need to reset the agfl and warn the user.
2347  *
2348  * Return true if a reset is required before the agfl can be used, false
2349  * otherwise.
2350  */
2351 static bool
2352 xfs_agfl_needs_reset(
2353 	struct xfs_mount	*mp,
2354 	struct xfs_agf		*agf)
2355 {
2356 	uint32_t		f = be32_to_cpu(agf->agf_flfirst);
2357 	uint32_t		l = be32_to_cpu(agf->agf_fllast);
2358 	uint32_t		c = be32_to_cpu(agf->agf_flcount);
2359 	int			agfl_size = xfs_agfl_size(mp);
2360 	int			active;
2361 
2362 	/*
2363 	 * The agf read verifier catches severe corruption of these fields.
2364 	 * Repeat some sanity checks to cover a packed -> unpacked mismatch if
2365 	 * the verifier allows it.
2366 	 */
2367 	if (f >= agfl_size || l >= agfl_size)
2368 		return true;
2369 	if (c > agfl_size)
2370 		return true;
2371 
2372 	/*
2373 	 * Check consistency between the on-disk count and the active range. An
2374 	 * agfl padding mismatch manifests as an inconsistent flcount.
2375 	 */
2376 	if (c && l >= f)
2377 		active = l - f + 1;
2378 	else if (c)
2379 		active = agfl_size - f + l + 1;
2380 	else
2381 		active = 0;
2382 
2383 	return active != c;
2384 }
2385 
2386 /*
2387  * Reset the agfl to an empty state. Ignore/drop any existing blocks since the
2388  * agfl content cannot be trusted. Warn the user that a repair is required to
2389  * recover leaked blocks.
2390  *
2391  * The purpose of this mechanism is to handle filesystems affected by the agfl
2392  * header padding mismatch problem. A reset keeps the filesystem online with a
2393  * relatively minor free space accounting inconsistency rather than suffer the
2394  * inevitable crash from use of an invalid agfl block.
2395  */
2396 static void
2397 xfs_agfl_reset(
2398 	struct xfs_trans	*tp,
2399 	struct xfs_buf		*agbp,
2400 	struct xfs_perag	*pag)
2401 {
2402 	struct xfs_mount	*mp = tp->t_mountp;
2403 	struct xfs_agf		*agf = agbp->b_addr;
2404 
2405 	ASSERT(xfs_perag_agfl_needs_reset(pag));
2406 	trace_xfs_agfl_reset(mp, agf, 0, _RET_IP_);
2407 
2408 	xfs_warn(mp,
2409 	       "WARNING: Reset corrupted AGFL on AG %u. %d blocks leaked. "
2410 	       "Please unmount and run xfs_repair.",
2411 	         pag->pag_agno, pag->pagf_flcount);
2412 
2413 	agf->agf_flfirst = 0;
2414 	agf->agf_fllast = cpu_to_be32(xfs_agfl_size(mp) - 1);
2415 	agf->agf_flcount = 0;
2416 	xfs_alloc_log_agf(tp, agbp, XFS_AGF_FLFIRST | XFS_AGF_FLLAST |
2417 				    XFS_AGF_FLCOUNT);
2418 
2419 	pag->pagf_flcount = 0;
2420 	clear_bit(XFS_AGSTATE_AGFL_NEEDS_RESET, &pag->pag_opstate);
2421 }
2422 
2423 /*
2424  * Defer an AGFL block free. This is effectively equivalent to
2425  * xfs_free_extent_later() with some special handling particular to AGFL blocks.
2426  *
2427  * Deferring AGFL frees helps prevent log reservation overruns due to too many
2428  * allocation operations in a transaction. AGFL frees are prone to this problem
2429  * because for one they are always freed one at a time. Further, an immediate
2430  * AGFL block free can cause a btree join and require another block free before
2431  * the real allocation can proceed. Deferring the free disconnects freeing up
2432  * the AGFL slot from freeing the block.
2433  */
2434 static int
2435 xfs_defer_agfl_block(
2436 	struct xfs_trans		*tp,
2437 	xfs_agnumber_t			agno,
2438 	xfs_fsblock_t			agbno,
2439 	struct xfs_owner_info		*oinfo)
2440 {
2441 	struct xfs_mount		*mp = tp->t_mountp;
2442 	struct xfs_extent_free_item	*xefi;
2443 
2444 	ASSERT(xfs_extfree_item_cache != NULL);
2445 	ASSERT(oinfo != NULL);
2446 
2447 	xefi = kmem_cache_zalloc(xfs_extfree_item_cache,
2448 			       GFP_KERNEL | __GFP_NOFAIL);
2449 	xefi->xefi_startblock = XFS_AGB_TO_FSB(mp, agno, agbno);
2450 	xefi->xefi_blockcount = 1;
2451 	xefi->xefi_owner = oinfo->oi_owner;
2452 
2453 	if (XFS_IS_CORRUPT(mp, !xfs_verify_fsbno(mp, xefi->xefi_startblock)))
2454 		return -EFSCORRUPTED;
2455 
2456 	trace_xfs_agfl_free_defer(mp, agno, 0, agbno, 1);
2457 
2458 	xfs_extent_free_get_group(mp, xefi);
2459 	xfs_defer_add(tp, XFS_DEFER_OPS_TYPE_AGFL_FREE, &xefi->xefi_list);
2460 	return 0;
2461 }
2462 
2463 /*
2464  * Add the extent to the list of extents to be free at transaction end.
2465  * The list is maintained sorted (by block number).
2466  */
2467 int
2468 __xfs_free_extent_later(
2469 	struct xfs_trans		*tp,
2470 	xfs_fsblock_t			bno,
2471 	xfs_filblks_t			len,
2472 	const struct xfs_owner_info	*oinfo,
2473 	bool				skip_discard)
2474 {
2475 	struct xfs_extent_free_item	*xefi;
2476 	struct xfs_mount		*mp = tp->t_mountp;
2477 #ifdef DEBUG
2478 	xfs_agnumber_t			agno;
2479 	xfs_agblock_t			agbno;
2480 
2481 	ASSERT(bno != NULLFSBLOCK);
2482 	ASSERT(len > 0);
2483 	ASSERT(len <= XFS_MAX_BMBT_EXTLEN);
2484 	ASSERT(!isnullstartblock(bno));
2485 	agno = XFS_FSB_TO_AGNO(mp, bno);
2486 	agbno = XFS_FSB_TO_AGBNO(mp, bno);
2487 	ASSERT(agno < mp->m_sb.sb_agcount);
2488 	ASSERT(agbno < mp->m_sb.sb_agblocks);
2489 	ASSERT(len < mp->m_sb.sb_agblocks);
2490 	ASSERT(agbno + len <= mp->m_sb.sb_agblocks);
2491 #endif
2492 	ASSERT(xfs_extfree_item_cache != NULL);
2493 
2494 	if (XFS_IS_CORRUPT(mp, !xfs_verify_fsbext(mp, bno, len)))
2495 		return -EFSCORRUPTED;
2496 
2497 	xefi = kmem_cache_zalloc(xfs_extfree_item_cache,
2498 			       GFP_KERNEL | __GFP_NOFAIL);
2499 	xefi->xefi_startblock = bno;
2500 	xefi->xefi_blockcount = (xfs_extlen_t)len;
2501 	if (skip_discard)
2502 		xefi->xefi_flags |= XFS_EFI_SKIP_DISCARD;
2503 	if (oinfo) {
2504 		ASSERT(oinfo->oi_offset == 0);
2505 
2506 		if (oinfo->oi_flags & XFS_OWNER_INFO_ATTR_FORK)
2507 			xefi->xefi_flags |= XFS_EFI_ATTR_FORK;
2508 		if (oinfo->oi_flags & XFS_OWNER_INFO_BMBT_BLOCK)
2509 			xefi->xefi_flags |= XFS_EFI_BMBT_BLOCK;
2510 		xefi->xefi_owner = oinfo->oi_owner;
2511 	} else {
2512 		xefi->xefi_owner = XFS_RMAP_OWN_NULL;
2513 	}
2514 	trace_xfs_bmap_free_defer(mp,
2515 			XFS_FSB_TO_AGNO(tp->t_mountp, bno), 0,
2516 			XFS_FSB_TO_AGBNO(tp->t_mountp, bno), len);
2517 
2518 	xfs_extent_free_get_group(mp, xefi);
2519 	xfs_defer_add(tp, XFS_DEFER_OPS_TYPE_FREE, &xefi->xefi_list);
2520 	return 0;
2521 }
2522 
2523 #ifdef DEBUG
2524 /*
2525  * Check if an AGF has a free extent record whose length is equal to
2526  * args->minlen.
2527  */
2528 STATIC int
2529 xfs_exact_minlen_extent_available(
2530 	struct xfs_alloc_arg	*args,
2531 	struct xfs_buf		*agbp,
2532 	int			*stat)
2533 {
2534 	struct xfs_btree_cur	*cnt_cur;
2535 	xfs_agblock_t		fbno;
2536 	xfs_extlen_t		flen;
2537 	int			error = 0;
2538 
2539 	cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, agbp,
2540 					args->pag, XFS_BTNUM_CNT);
2541 	error = xfs_alloc_lookup_ge(cnt_cur, 0, args->minlen, stat);
2542 	if (error)
2543 		goto out;
2544 
2545 	if (*stat == 0) {
2546 		error = -EFSCORRUPTED;
2547 		goto out;
2548 	}
2549 
2550 	error = xfs_alloc_get_rec(cnt_cur, &fbno, &flen, stat);
2551 	if (error)
2552 		goto out;
2553 
2554 	if (*stat == 1 && flen != args->minlen)
2555 		*stat = 0;
2556 
2557 out:
2558 	xfs_btree_del_cursor(cnt_cur, error);
2559 
2560 	return error;
2561 }
2562 #endif
2563 
2564 /*
2565  * Decide whether to use this allocation group for this allocation.
2566  * If so, fix up the btree freelist's size.
2567  */
2568 int			/* error */
2569 xfs_alloc_fix_freelist(
2570 	struct xfs_alloc_arg	*args,	/* allocation argument structure */
2571 	int			flags)	/* XFS_ALLOC_FLAG_... */
2572 {
2573 	struct xfs_mount	*mp = args->mp;
2574 	struct xfs_perag	*pag = args->pag;
2575 	struct xfs_trans	*tp = args->tp;
2576 	struct xfs_buf		*agbp = NULL;
2577 	struct xfs_buf		*agflbp = NULL;
2578 	struct xfs_alloc_arg	targs;	/* local allocation arguments */
2579 	xfs_agblock_t		bno;	/* freelist block */
2580 	xfs_extlen_t		need;	/* total blocks needed in freelist */
2581 	int			error = 0;
2582 
2583 	/* deferred ops (AGFL block frees) require permanent transactions */
2584 	ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES);
2585 
2586 	if (!xfs_perag_initialised_agf(pag)) {
2587 		error = xfs_alloc_read_agf(pag, tp, flags, &agbp);
2588 		if (error) {
2589 			/* Couldn't lock the AGF so skip this AG. */
2590 			if (error == -EAGAIN)
2591 				error = 0;
2592 			goto out_no_agbp;
2593 		}
2594 	}
2595 
2596 	/*
2597 	 * If this is a metadata preferred pag and we are user data then try
2598 	 * somewhere else if we are not being asked to try harder at this
2599 	 * point
2600 	 */
2601 	if (xfs_perag_prefers_metadata(pag) &&
2602 	    (args->datatype & XFS_ALLOC_USERDATA) &&
2603 	    (flags & XFS_ALLOC_FLAG_TRYLOCK)) {
2604 		ASSERT(!(flags & XFS_ALLOC_FLAG_FREEING));
2605 		goto out_agbp_relse;
2606 	}
2607 
2608 	need = xfs_alloc_min_freelist(mp, pag);
2609 	if (!xfs_alloc_space_available(args, need, flags |
2610 			XFS_ALLOC_FLAG_CHECK))
2611 		goto out_agbp_relse;
2612 
2613 	/*
2614 	 * Get the a.g. freespace buffer.
2615 	 * Can fail if we're not blocking on locks, and it's held.
2616 	 */
2617 	if (!agbp) {
2618 		error = xfs_alloc_read_agf(pag, tp, flags, &agbp);
2619 		if (error) {
2620 			/* Couldn't lock the AGF so skip this AG. */
2621 			if (error == -EAGAIN)
2622 				error = 0;
2623 			goto out_no_agbp;
2624 		}
2625 	}
2626 
2627 	/* reset a padding mismatched agfl before final free space check */
2628 	if (xfs_perag_agfl_needs_reset(pag))
2629 		xfs_agfl_reset(tp, agbp, pag);
2630 
2631 	/* If there isn't enough total space or single-extent, reject it. */
2632 	need = xfs_alloc_min_freelist(mp, pag);
2633 	if (!xfs_alloc_space_available(args, need, flags))
2634 		goto out_agbp_relse;
2635 
2636 #ifdef DEBUG
2637 	if (args->alloc_minlen_only) {
2638 		int stat;
2639 
2640 		error = xfs_exact_minlen_extent_available(args, agbp, &stat);
2641 		if (error || !stat)
2642 			goto out_agbp_relse;
2643 	}
2644 #endif
2645 	/*
2646 	 * Make the freelist shorter if it's too long.
2647 	 *
2648 	 * Note that from this point onwards, we will always release the agf and
2649 	 * agfl buffers on error. This handles the case where we error out and
2650 	 * the buffers are clean or may not have been joined to the transaction
2651 	 * and hence need to be released manually. If they have been joined to
2652 	 * the transaction, then xfs_trans_brelse() will handle them
2653 	 * appropriately based on the recursion count and dirty state of the
2654 	 * buffer.
2655 	 *
2656 	 * XXX (dgc): When we have lots of free space, does this buy us
2657 	 * anything other than extra overhead when we need to put more blocks
2658 	 * back on the free list? Maybe we should only do this when space is
2659 	 * getting low or the AGFL is more than half full?
2660 	 *
2661 	 * The NOSHRINK flag prevents the AGFL from being shrunk if it's too
2662 	 * big; the NORMAP flag prevents AGFL expand/shrink operations from
2663 	 * updating the rmapbt.  Both flags are used in xfs_repair while we're
2664 	 * rebuilding the rmapbt, and neither are used by the kernel.  They're
2665 	 * both required to ensure that rmaps are correctly recorded for the
2666 	 * regenerated AGFL, bnobt, and cntbt.  See repair/phase5.c and
2667 	 * repair/rmap.c in xfsprogs for details.
2668 	 */
2669 	memset(&targs, 0, sizeof(targs));
2670 	/* struct copy below */
2671 	if (flags & XFS_ALLOC_FLAG_NORMAP)
2672 		targs.oinfo = XFS_RMAP_OINFO_SKIP_UPDATE;
2673 	else
2674 		targs.oinfo = XFS_RMAP_OINFO_AG;
2675 	while (!(flags & XFS_ALLOC_FLAG_NOSHRINK) && pag->pagf_flcount > need) {
2676 		error = xfs_alloc_get_freelist(pag, tp, agbp, &bno, 0);
2677 		if (error)
2678 			goto out_agbp_relse;
2679 
2680 		/* defer agfl frees */
2681 		error = xfs_defer_agfl_block(tp, args->agno, bno, &targs.oinfo);
2682 		if (error)
2683 			goto out_agbp_relse;
2684 	}
2685 
2686 	targs.tp = tp;
2687 	targs.mp = mp;
2688 	targs.agbp = agbp;
2689 	targs.agno = args->agno;
2690 	targs.alignment = targs.minlen = targs.prod = 1;
2691 	targs.pag = pag;
2692 	error = xfs_alloc_read_agfl(pag, tp, &agflbp);
2693 	if (error)
2694 		goto out_agbp_relse;
2695 
2696 	/* Make the freelist longer if it's too short. */
2697 	while (pag->pagf_flcount < need) {
2698 		targs.agbno = 0;
2699 		targs.maxlen = need - pag->pagf_flcount;
2700 		targs.resv = XFS_AG_RESV_AGFL;
2701 
2702 		/* Allocate as many blocks as possible at once. */
2703 		error = xfs_alloc_ag_vextent_size(&targs);
2704 		if (error)
2705 			goto out_agflbp_relse;
2706 
2707 		/*
2708 		 * Stop if we run out.  Won't happen if callers are obeying
2709 		 * the restrictions correctly.  Can happen for free calls
2710 		 * on a completely full ag.
2711 		 */
2712 		if (targs.agbno == NULLAGBLOCK) {
2713 			if (flags & XFS_ALLOC_FLAG_FREEING)
2714 				break;
2715 			goto out_agflbp_relse;
2716 		}
2717 
2718 		if (!xfs_rmap_should_skip_owner_update(&targs.oinfo)) {
2719 			error = xfs_rmap_alloc(tp, agbp, pag,
2720 				       targs.agbno, targs.len, &targs.oinfo);
2721 			if (error)
2722 				goto out_agflbp_relse;
2723 		}
2724 		error = xfs_alloc_update_counters(tp, agbp,
2725 						  -((long)(targs.len)));
2726 		if (error)
2727 			goto out_agflbp_relse;
2728 
2729 		/*
2730 		 * Put each allocated block on the list.
2731 		 */
2732 		for (bno = targs.agbno; bno < targs.agbno + targs.len; bno++) {
2733 			error = xfs_alloc_put_freelist(pag, tp, agbp,
2734 							agflbp, bno, 0);
2735 			if (error)
2736 				goto out_agflbp_relse;
2737 		}
2738 	}
2739 	xfs_trans_brelse(tp, agflbp);
2740 	args->agbp = agbp;
2741 	return 0;
2742 
2743 out_agflbp_relse:
2744 	xfs_trans_brelse(tp, agflbp);
2745 out_agbp_relse:
2746 	if (agbp)
2747 		xfs_trans_brelse(tp, agbp);
2748 out_no_agbp:
2749 	args->agbp = NULL;
2750 	return error;
2751 }
2752 
2753 /*
2754  * Get a block from the freelist.
2755  * Returns with the buffer for the block gotten.
2756  */
2757 int
2758 xfs_alloc_get_freelist(
2759 	struct xfs_perag	*pag,
2760 	struct xfs_trans	*tp,
2761 	struct xfs_buf		*agbp,
2762 	xfs_agblock_t		*bnop,
2763 	int			btreeblk)
2764 {
2765 	struct xfs_agf		*agf = agbp->b_addr;
2766 	struct xfs_buf		*agflbp;
2767 	xfs_agblock_t		bno;
2768 	__be32			*agfl_bno;
2769 	int			error;
2770 	uint32_t		logflags;
2771 	struct xfs_mount	*mp = tp->t_mountp;
2772 
2773 	/*
2774 	 * Freelist is empty, give up.
2775 	 */
2776 	if (!agf->agf_flcount) {
2777 		*bnop = NULLAGBLOCK;
2778 		return 0;
2779 	}
2780 	/*
2781 	 * Read the array of free blocks.
2782 	 */
2783 	error = xfs_alloc_read_agfl(pag, tp, &agflbp);
2784 	if (error)
2785 		return error;
2786 
2787 
2788 	/*
2789 	 * Get the block number and update the data structures.
2790 	 */
2791 	agfl_bno = xfs_buf_to_agfl_bno(agflbp);
2792 	bno = be32_to_cpu(agfl_bno[be32_to_cpu(agf->agf_flfirst)]);
2793 	if (XFS_IS_CORRUPT(tp->t_mountp, !xfs_verify_agbno(pag, bno)))
2794 		return -EFSCORRUPTED;
2795 
2796 	be32_add_cpu(&agf->agf_flfirst, 1);
2797 	xfs_trans_brelse(tp, agflbp);
2798 	if (be32_to_cpu(agf->agf_flfirst) == xfs_agfl_size(mp))
2799 		agf->agf_flfirst = 0;
2800 
2801 	ASSERT(!xfs_perag_agfl_needs_reset(pag));
2802 	be32_add_cpu(&agf->agf_flcount, -1);
2803 	pag->pagf_flcount--;
2804 
2805 	logflags = XFS_AGF_FLFIRST | XFS_AGF_FLCOUNT;
2806 	if (btreeblk) {
2807 		be32_add_cpu(&agf->agf_btreeblks, 1);
2808 		pag->pagf_btreeblks++;
2809 		logflags |= XFS_AGF_BTREEBLKS;
2810 	}
2811 
2812 	xfs_alloc_log_agf(tp, agbp, logflags);
2813 	*bnop = bno;
2814 
2815 	return 0;
2816 }
2817 
2818 /*
2819  * Log the given fields from the agf structure.
2820  */
2821 void
2822 xfs_alloc_log_agf(
2823 	struct xfs_trans	*tp,
2824 	struct xfs_buf		*bp,
2825 	uint32_t		fields)
2826 {
2827 	int	first;		/* first byte offset */
2828 	int	last;		/* last byte offset */
2829 	static const short	offsets[] = {
2830 		offsetof(xfs_agf_t, agf_magicnum),
2831 		offsetof(xfs_agf_t, agf_versionnum),
2832 		offsetof(xfs_agf_t, agf_seqno),
2833 		offsetof(xfs_agf_t, agf_length),
2834 		offsetof(xfs_agf_t, agf_roots[0]),
2835 		offsetof(xfs_agf_t, agf_levels[0]),
2836 		offsetof(xfs_agf_t, agf_flfirst),
2837 		offsetof(xfs_agf_t, agf_fllast),
2838 		offsetof(xfs_agf_t, agf_flcount),
2839 		offsetof(xfs_agf_t, agf_freeblks),
2840 		offsetof(xfs_agf_t, agf_longest),
2841 		offsetof(xfs_agf_t, agf_btreeblks),
2842 		offsetof(xfs_agf_t, agf_uuid),
2843 		offsetof(xfs_agf_t, agf_rmap_blocks),
2844 		offsetof(xfs_agf_t, agf_refcount_blocks),
2845 		offsetof(xfs_agf_t, agf_refcount_root),
2846 		offsetof(xfs_agf_t, agf_refcount_level),
2847 		/* needed so that we don't log the whole rest of the structure: */
2848 		offsetof(xfs_agf_t, agf_spare64),
2849 		sizeof(xfs_agf_t)
2850 	};
2851 
2852 	trace_xfs_agf(tp->t_mountp, bp->b_addr, fields, _RET_IP_);
2853 
2854 	xfs_trans_buf_set_type(tp, bp, XFS_BLFT_AGF_BUF);
2855 
2856 	xfs_btree_offsets(fields, offsets, XFS_AGF_NUM_BITS, &first, &last);
2857 	xfs_trans_log_buf(tp, bp, (uint)first, (uint)last);
2858 }
2859 
2860 /*
2861  * Put the block on the freelist for the allocation group.
2862  */
2863 int
2864 xfs_alloc_put_freelist(
2865 	struct xfs_perag	*pag,
2866 	struct xfs_trans	*tp,
2867 	struct xfs_buf		*agbp,
2868 	struct xfs_buf		*agflbp,
2869 	xfs_agblock_t		bno,
2870 	int			btreeblk)
2871 {
2872 	struct xfs_mount	*mp = tp->t_mountp;
2873 	struct xfs_agf		*agf = agbp->b_addr;
2874 	__be32			*blockp;
2875 	int			error;
2876 	uint32_t		logflags;
2877 	__be32			*agfl_bno;
2878 	int			startoff;
2879 
2880 	if (!agflbp) {
2881 		error = xfs_alloc_read_agfl(pag, tp, &agflbp);
2882 		if (error)
2883 			return error;
2884 	}
2885 
2886 	be32_add_cpu(&agf->agf_fllast, 1);
2887 	if (be32_to_cpu(agf->agf_fllast) == xfs_agfl_size(mp))
2888 		agf->agf_fllast = 0;
2889 
2890 	ASSERT(!xfs_perag_agfl_needs_reset(pag));
2891 	be32_add_cpu(&agf->agf_flcount, 1);
2892 	pag->pagf_flcount++;
2893 
2894 	logflags = XFS_AGF_FLLAST | XFS_AGF_FLCOUNT;
2895 	if (btreeblk) {
2896 		be32_add_cpu(&agf->agf_btreeblks, -1);
2897 		pag->pagf_btreeblks--;
2898 		logflags |= XFS_AGF_BTREEBLKS;
2899 	}
2900 
2901 	xfs_alloc_log_agf(tp, agbp, logflags);
2902 
2903 	ASSERT(be32_to_cpu(agf->agf_flcount) <= xfs_agfl_size(mp));
2904 
2905 	agfl_bno = xfs_buf_to_agfl_bno(agflbp);
2906 	blockp = &agfl_bno[be32_to_cpu(agf->agf_fllast)];
2907 	*blockp = cpu_to_be32(bno);
2908 	startoff = (char *)blockp - (char *)agflbp->b_addr;
2909 
2910 	xfs_alloc_log_agf(tp, agbp, logflags);
2911 
2912 	xfs_trans_buf_set_type(tp, agflbp, XFS_BLFT_AGFL_BUF);
2913 	xfs_trans_log_buf(tp, agflbp, startoff,
2914 			  startoff + sizeof(xfs_agblock_t) - 1);
2915 	return 0;
2916 }
2917 
2918 /*
2919  * Verify the AGF is consistent.
2920  *
2921  * We do not verify the AGFL indexes in the AGF are fully consistent here
2922  * because of issues with variable on-disk structure sizes. Instead, we check
2923  * the agfl indexes for consistency when we initialise the perag from the AGF
2924  * information after a read completes.
2925  *
2926  * If the index is inconsistent, then we mark the perag as needing an AGFL
2927  * reset. The first AGFL update performed then resets the AGFL indexes and
2928  * refills the AGFL with known good free blocks, allowing the filesystem to
2929  * continue operating normally at the cost of a few leaked free space blocks.
2930  */
2931 static xfs_failaddr_t
2932 xfs_agf_verify(
2933 	struct xfs_buf		*bp)
2934 {
2935 	struct xfs_mount	*mp = bp->b_mount;
2936 	struct xfs_agf		*agf = bp->b_addr;
2937 
2938 	if (xfs_has_crc(mp)) {
2939 		if (!uuid_equal(&agf->agf_uuid, &mp->m_sb.sb_meta_uuid))
2940 			return __this_address;
2941 		if (!xfs_log_check_lsn(mp, be64_to_cpu(agf->agf_lsn)))
2942 			return __this_address;
2943 	}
2944 
2945 	if (!xfs_verify_magic(bp, agf->agf_magicnum))
2946 		return __this_address;
2947 
2948 	if (!(XFS_AGF_GOOD_VERSION(be32_to_cpu(agf->agf_versionnum)) &&
2949 	      be32_to_cpu(agf->agf_freeblks) <= be32_to_cpu(agf->agf_length) &&
2950 	      be32_to_cpu(agf->agf_flfirst) < xfs_agfl_size(mp) &&
2951 	      be32_to_cpu(agf->agf_fllast) < xfs_agfl_size(mp) &&
2952 	      be32_to_cpu(agf->agf_flcount) <= xfs_agfl_size(mp)))
2953 		return __this_address;
2954 
2955 	if (be32_to_cpu(agf->agf_length) > mp->m_sb.sb_dblocks)
2956 		return __this_address;
2957 
2958 	if (be32_to_cpu(agf->agf_freeblks) < be32_to_cpu(agf->agf_longest) ||
2959 	    be32_to_cpu(agf->agf_freeblks) > be32_to_cpu(agf->agf_length))
2960 		return __this_address;
2961 
2962 	if (be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) < 1 ||
2963 	    be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) < 1 ||
2964 	    be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) >
2965 						mp->m_alloc_maxlevels ||
2966 	    be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) >
2967 						mp->m_alloc_maxlevels)
2968 		return __this_address;
2969 
2970 	if (xfs_has_rmapbt(mp) &&
2971 	    (be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAP]) < 1 ||
2972 	     be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAP]) >
2973 						mp->m_rmap_maxlevels))
2974 		return __this_address;
2975 
2976 	if (xfs_has_rmapbt(mp) &&
2977 	    be32_to_cpu(agf->agf_rmap_blocks) > be32_to_cpu(agf->agf_length))
2978 		return __this_address;
2979 
2980 	/*
2981 	 * during growfs operations, the perag is not fully initialised,
2982 	 * so we can't use it for any useful checking. growfs ensures we can't
2983 	 * use it by using uncached buffers that don't have the perag attached
2984 	 * so we can detect and avoid this problem.
2985 	 */
2986 	if (bp->b_pag && be32_to_cpu(agf->agf_seqno) != bp->b_pag->pag_agno)
2987 		return __this_address;
2988 
2989 	if (xfs_has_lazysbcount(mp) &&
2990 	    be32_to_cpu(agf->agf_btreeblks) > be32_to_cpu(agf->agf_length))
2991 		return __this_address;
2992 
2993 	if (xfs_has_reflink(mp) &&
2994 	    be32_to_cpu(agf->agf_refcount_blocks) >
2995 	    be32_to_cpu(agf->agf_length))
2996 		return __this_address;
2997 
2998 	if (xfs_has_reflink(mp) &&
2999 	    (be32_to_cpu(agf->agf_refcount_level) < 1 ||
3000 	     be32_to_cpu(agf->agf_refcount_level) > mp->m_refc_maxlevels))
3001 		return __this_address;
3002 
3003 	return NULL;
3004 }
3005 
3006 static void
3007 xfs_agf_read_verify(
3008 	struct xfs_buf	*bp)
3009 {
3010 	struct xfs_mount *mp = bp->b_mount;
3011 	xfs_failaddr_t	fa;
3012 
3013 	if (xfs_has_crc(mp) &&
3014 	    !xfs_buf_verify_cksum(bp, XFS_AGF_CRC_OFF))
3015 		xfs_verifier_error(bp, -EFSBADCRC, __this_address);
3016 	else {
3017 		fa = xfs_agf_verify(bp);
3018 		if (XFS_TEST_ERROR(fa, mp, XFS_ERRTAG_ALLOC_READ_AGF))
3019 			xfs_verifier_error(bp, -EFSCORRUPTED, fa);
3020 	}
3021 }
3022 
3023 static void
3024 xfs_agf_write_verify(
3025 	struct xfs_buf	*bp)
3026 {
3027 	struct xfs_mount	*mp = bp->b_mount;
3028 	struct xfs_buf_log_item	*bip = bp->b_log_item;
3029 	struct xfs_agf		*agf = bp->b_addr;
3030 	xfs_failaddr_t		fa;
3031 
3032 	fa = xfs_agf_verify(bp);
3033 	if (fa) {
3034 		xfs_verifier_error(bp, -EFSCORRUPTED, fa);
3035 		return;
3036 	}
3037 
3038 	if (!xfs_has_crc(mp))
3039 		return;
3040 
3041 	if (bip)
3042 		agf->agf_lsn = cpu_to_be64(bip->bli_item.li_lsn);
3043 
3044 	xfs_buf_update_cksum(bp, XFS_AGF_CRC_OFF);
3045 }
3046 
3047 const struct xfs_buf_ops xfs_agf_buf_ops = {
3048 	.name = "xfs_agf",
3049 	.magic = { cpu_to_be32(XFS_AGF_MAGIC), cpu_to_be32(XFS_AGF_MAGIC) },
3050 	.verify_read = xfs_agf_read_verify,
3051 	.verify_write = xfs_agf_write_verify,
3052 	.verify_struct = xfs_agf_verify,
3053 };
3054 
3055 /*
3056  * Read in the allocation group header (free/alloc section).
3057  */
3058 int
3059 xfs_read_agf(
3060 	struct xfs_perag	*pag,
3061 	struct xfs_trans	*tp,
3062 	int			flags,
3063 	struct xfs_buf		**agfbpp)
3064 {
3065 	struct xfs_mount	*mp = pag->pag_mount;
3066 	int			error;
3067 
3068 	trace_xfs_read_agf(pag->pag_mount, pag->pag_agno);
3069 
3070 	error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp,
3071 			XFS_AG_DADDR(mp, pag->pag_agno, XFS_AGF_DADDR(mp)),
3072 			XFS_FSS_TO_BB(mp, 1), flags, agfbpp, &xfs_agf_buf_ops);
3073 	if (error)
3074 		return error;
3075 
3076 	xfs_buf_set_ref(*agfbpp, XFS_AGF_REF);
3077 	return 0;
3078 }
3079 
3080 /*
3081  * Read in the allocation group header (free/alloc section) and initialise the
3082  * perag structure if necessary. If the caller provides @agfbpp, then return the
3083  * locked buffer to the caller, otherwise free it.
3084  */
3085 int
3086 xfs_alloc_read_agf(
3087 	struct xfs_perag	*pag,
3088 	struct xfs_trans	*tp,
3089 	int			flags,
3090 	struct xfs_buf		**agfbpp)
3091 {
3092 	struct xfs_buf		*agfbp;
3093 	struct xfs_agf		*agf;
3094 	int			error;
3095 	int			allocbt_blks;
3096 
3097 	trace_xfs_alloc_read_agf(pag->pag_mount, pag->pag_agno);
3098 
3099 	/* We don't support trylock when freeing. */
3100 	ASSERT((flags & (XFS_ALLOC_FLAG_FREEING | XFS_ALLOC_FLAG_TRYLOCK)) !=
3101 			(XFS_ALLOC_FLAG_FREEING | XFS_ALLOC_FLAG_TRYLOCK));
3102 	error = xfs_read_agf(pag, tp,
3103 			(flags & XFS_ALLOC_FLAG_TRYLOCK) ? XBF_TRYLOCK : 0,
3104 			&agfbp);
3105 	if (error)
3106 		return error;
3107 
3108 	agf = agfbp->b_addr;
3109 	if (!xfs_perag_initialised_agf(pag)) {
3110 		pag->pagf_freeblks = be32_to_cpu(agf->agf_freeblks);
3111 		pag->pagf_btreeblks = be32_to_cpu(agf->agf_btreeblks);
3112 		pag->pagf_flcount = be32_to_cpu(agf->agf_flcount);
3113 		pag->pagf_longest = be32_to_cpu(agf->agf_longest);
3114 		pag->pagf_levels[XFS_BTNUM_BNOi] =
3115 			be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNOi]);
3116 		pag->pagf_levels[XFS_BTNUM_CNTi] =
3117 			be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNTi]);
3118 		pag->pagf_levels[XFS_BTNUM_RMAPi] =
3119 			be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAPi]);
3120 		pag->pagf_refcount_level = be32_to_cpu(agf->agf_refcount_level);
3121 		if (xfs_agfl_needs_reset(pag->pag_mount, agf))
3122 			set_bit(XFS_AGSTATE_AGFL_NEEDS_RESET, &pag->pag_opstate);
3123 		else
3124 			clear_bit(XFS_AGSTATE_AGFL_NEEDS_RESET, &pag->pag_opstate);
3125 
3126 		/*
3127 		 * Update the in-core allocbt counter. Filter out the rmapbt
3128 		 * subset of the btreeblks counter because the rmapbt is managed
3129 		 * by perag reservation. Subtract one for the rmapbt root block
3130 		 * because the rmap counter includes it while the btreeblks
3131 		 * counter only tracks non-root blocks.
3132 		 */
3133 		allocbt_blks = pag->pagf_btreeblks;
3134 		if (xfs_has_rmapbt(pag->pag_mount))
3135 			allocbt_blks -= be32_to_cpu(agf->agf_rmap_blocks) - 1;
3136 		if (allocbt_blks > 0)
3137 			atomic64_add(allocbt_blks,
3138 					&pag->pag_mount->m_allocbt_blks);
3139 
3140 		set_bit(XFS_AGSTATE_AGF_INIT, &pag->pag_opstate);
3141 	}
3142 #ifdef DEBUG
3143 	else if (!xfs_is_shutdown(pag->pag_mount)) {
3144 		ASSERT(pag->pagf_freeblks == be32_to_cpu(agf->agf_freeblks));
3145 		ASSERT(pag->pagf_btreeblks == be32_to_cpu(agf->agf_btreeblks));
3146 		ASSERT(pag->pagf_flcount == be32_to_cpu(agf->agf_flcount));
3147 		ASSERT(pag->pagf_longest == be32_to_cpu(agf->agf_longest));
3148 		ASSERT(pag->pagf_levels[XFS_BTNUM_BNOi] ==
3149 		       be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNOi]));
3150 		ASSERT(pag->pagf_levels[XFS_BTNUM_CNTi] ==
3151 		       be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNTi]));
3152 	}
3153 #endif
3154 	if (agfbpp)
3155 		*agfbpp = agfbp;
3156 	else
3157 		xfs_trans_brelse(tp, agfbp);
3158 	return 0;
3159 }
3160 
3161 /*
3162  * Pre-proces allocation arguments to set initial state that we don't require
3163  * callers to set up correctly, as well as bounds check the allocation args
3164  * that are set up.
3165  */
3166 static int
3167 xfs_alloc_vextent_check_args(
3168 	struct xfs_alloc_arg	*args,
3169 	xfs_fsblock_t		target,
3170 	xfs_agnumber_t		*minimum_agno)
3171 {
3172 	struct xfs_mount	*mp = args->mp;
3173 	xfs_agblock_t		agsize;
3174 
3175 	args->fsbno = NULLFSBLOCK;
3176 
3177 	*minimum_agno = 0;
3178 	if (args->tp->t_highest_agno != NULLAGNUMBER)
3179 		*minimum_agno = args->tp->t_highest_agno;
3180 
3181 	/*
3182 	 * Just fix this up, for the case where the last a.g. is shorter
3183 	 * (or there's only one a.g.) and the caller couldn't easily figure
3184 	 * that out (xfs_bmap_alloc).
3185 	 */
3186 	agsize = mp->m_sb.sb_agblocks;
3187 	if (args->maxlen > agsize)
3188 		args->maxlen = agsize;
3189 	if (args->alignment == 0)
3190 		args->alignment = 1;
3191 
3192 	ASSERT(args->minlen > 0);
3193 	ASSERT(args->maxlen > 0);
3194 	ASSERT(args->alignment > 0);
3195 	ASSERT(args->resv != XFS_AG_RESV_AGFL);
3196 
3197 	ASSERT(XFS_FSB_TO_AGNO(mp, target) < mp->m_sb.sb_agcount);
3198 	ASSERT(XFS_FSB_TO_AGBNO(mp, target) < agsize);
3199 	ASSERT(args->minlen <= args->maxlen);
3200 	ASSERT(args->minlen <= agsize);
3201 	ASSERT(args->mod < args->prod);
3202 
3203 	if (XFS_FSB_TO_AGNO(mp, target) >= mp->m_sb.sb_agcount ||
3204 	    XFS_FSB_TO_AGBNO(mp, target) >= agsize ||
3205 	    args->minlen > args->maxlen || args->minlen > agsize ||
3206 	    args->mod >= args->prod) {
3207 		trace_xfs_alloc_vextent_badargs(args);
3208 		return -ENOSPC;
3209 	}
3210 
3211 	if (args->agno != NULLAGNUMBER && *minimum_agno > args->agno) {
3212 		trace_xfs_alloc_vextent_skip_deadlock(args);
3213 		return -ENOSPC;
3214 	}
3215 	return 0;
3216 
3217 }
3218 
3219 /*
3220  * Prepare an AG for allocation. If the AG is not prepared to accept the
3221  * allocation, return failure.
3222  *
3223  * XXX(dgc): The complexity of "need_pag" will go away as all caller paths are
3224  * modified to hold their own perag references.
3225  */
3226 static int
3227 xfs_alloc_vextent_prepare_ag(
3228 	struct xfs_alloc_arg	*args,
3229 	uint32_t		flags)
3230 {
3231 	bool			need_pag = !args->pag;
3232 	int			error;
3233 
3234 	if (need_pag)
3235 		args->pag = xfs_perag_get(args->mp, args->agno);
3236 
3237 	args->agbp = NULL;
3238 	error = xfs_alloc_fix_freelist(args, flags);
3239 	if (error) {
3240 		trace_xfs_alloc_vextent_nofix(args);
3241 		if (need_pag)
3242 			xfs_perag_put(args->pag);
3243 		args->agbno = NULLAGBLOCK;
3244 		return error;
3245 	}
3246 	if (!args->agbp) {
3247 		/* cannot allocate in this AG at all */
3248 		trace_xfs_alloc_vextent_noagbp(args);
3249 		args->agbno = NULLAGBLOCK;
3250 		return 0;
3251 	}
3252 	args->wasfromfl = 0;
3253 	return 0;
3254 }
3255 
3256 /*
3257  * Post-process allocation results to account for the allocation if it succeed
3258  * and set the allocated block number correctly for the caller.
3259  *
3260  * XXX: we should really be returning ENOSPC for ENOSPC, not
3261  * hiding it behind a "successful" NULLFSBLOCK allocation.
3262  */
3263 static int
3264 xfs_alloc_vextent_finish(
3265 	struct xfs_alloc_arg	*args,
3266 	xfs_agnumber_t		minimum_agno,
3267 	int			alloc_error,
3268 	bool			drop_perag)
3269 {
3270 	struct xfs_mount	*mp = args->mp;
3271 	int			error = 0;
3272 
3273 	/*
3274 	 * We can end up here with a locked AGF. If we failed, the caller is
3275 	 * likely going to try to allocate again with different parameters, and
3276 	 * that can widen the AGs that are searched for free space. If we have
3277 	 * to do BMBT block allocation, we have to do a new allocation.
3278 	 *
3279 	 * Hence leaving this function with the AGF locked opens up potential
3280 	 * ABBA AGF deadlocks because a future allocation attempt in this
3281 	 * transaction may attempt to lock a lower number AGF.
3282 	 *
3283 	 * We can't release the AGF until the transaction is commited, so at
3284 	 * this point we must update the "first allocation" tracker to point at
3285 	 * this AG if the tracker is empty or points to a lower AG. This allows
3286 	 * the next allocation attempt to be modified appropriately to avoid
3287 	 * deadlocks.
3288 	 */
3289 	if (args->agbp &&
3290 	    (args->tp->t_highest_agno == NULLAGNUMBER ||
3291 	     args->agno > minimum_agno))
3292 		args->tp->t_highest_agno = args->agno;
3293 
3294 	/*
3295 	 * If the allocation failed with an error or we had an ENOSPC result,
3296 	 * preserve the returned error whilst also marking the allocation result
3297 	 * as "no extent allocated". This ensures that callers that fail to
3298 	 * capture the error will still treat it as a failed allocation.
3299 	 */
3300 	if (alloc_error || args->agbno == NULLAGBLOCK) {
3301 		args->fsbno = NULLFSBLOCK;
3302 		error = alloc_error;
3303 		goto out_drop_perag;
3304 	}
3305 
3306 	args->fsbno = XFS_AGB_TO_FSB(mp, args->agno, args->agbno);
3307 
3308 	ASSERT(args->len >= args->minlen);
3309 	ASSERT(args->len <= args->maxlen);
3310 	ASSERT(args->agbno % args->alignment == 0);
3311 	XFS_AG_CHECK_DADDR(mp, XFS_FSB_TO_DADDR(mp, args->fsbno), args->len);
3312 
3313 	/* if not file data, insert new block into the reverse map btree */
3314 	if (!xfs_rmap_should_skip_owner_update(&args->oinfo)) {
3315 		error = xfs_rmap_alloc(args->tp, args->agbp, args->pag,
3316 				       args->agbno, args->len, &args->oinfo);
3317 		if (error)
3318 			goto out_drop_perag;
3319 	}
3320 
3321 	if (!args->wasfromfl) {
3322 		error = xfs_alloc_update_counters(args->tp, args->agbp,
3323 						  -((long)(args->len)));
3324 		if (error)
3325 			goto out_drop_perag;
3326 
3327 		ASSERT(!xfs_extent_busy_search(mp, args->pag, args->agbno,
3328 				args->len));
3329 	}
3330 
3331 	xfs_ag_resv_alloc_extent(args->pag, args->resv, args);
3332 
3333 	XFS_STATS_INC(mp, xs_allocx);
3334 	XFS_STATS_ADD(mp, xs_allocb, args->len);
3335 
3336 	trace_xfs_alloc_vextent_finish(args);
3337 
3338 out_drop_perag:
3339 	if (drop_perag && args->pag) {
3340 		xfs_perag_rele(args->pag);
3341 		args->pag = NULL;
3342 	}
3343 	return error;
3344 }
3345 
3346 /*
3347  * Allocate within a single AG only. This uses a best-fit length algorithm so if
3348  * you need an exact sized allocation without locality constraints, this is the
3349  * fastest way to do it.
3350  *
3351  * Caller is expected to hold a perag reference in args->pag.
3352  */
3353 int
3354 xfs_alloc_vextent_this_ag(
3355 	struct xfs_alloc_arg	*args,
3356 	xfs_agnumber_t		agno)
3357 {
3358 	struct xfs_mount	*mp = args->mp;
3359 	xfs_agnumber_t		minimum_agno;
3360 	int			error;
3361 
3362 	ASSERT(args->pag != NULL);
3363 	ASSERT(args->pag->pag_agno == agno);
3364 
3365 	args->agno = agno;
3366 	args->agbno = 0;
3367 
3368 	trace_xfs_alloc_vextent_this_ag(args);
3369 
3370 	error = xfs_alloc_vextent_check_args(args, XFS_AGB_TO_FSB(mp, agno, 0),
3371 			&minimum_agno);
3372 	if (error) {
3373 		if (error == -ENOSPC)
3374 			return 0;
3375 		return error;
3376 	}
3377 
3378 	error = xfs_alloc_vextent_prepare_ag(args, 0);
3379 	if (!error && args->agbp)
3380 		error = xfs_alloc_ag_vextent_size(args);
3381 
3382 	return xfs_alloc_vextent_finish(args, minimum_agno, error, false);
3383 }
3384 
3385 /*
3386  * Iterate all AGs trying to allocate an extent starting from @start_ag.
3387  *
3388  * If the incoming allocation type is XFS_ALLOCTYPE_NEAR_BNO, it means the
3389  * allocation attempts in @start_agno have locality information. If we fail to
3390  * allocate in that AG, then we revert to anywhere-in-AG for all the other AGs
3391  * we attempt to allocation in as there is no locality optimisation possible for
3392  * those allocations.
3393  *
3394  * On return, args->pag may be left referenced if we finish before the "all
3395  * failed" return point. The allocation finish still needs the perag, and
3396  * so the caller will release it once they've finished the allocation.
3397  *
3398  * When we wrap the AG iteration at the end of the filesystem, we have to be
3399  * careful not to wrap into AGs below ones we already have locked in the
3400  * transaction if we are doing a blocking iteration. This will result in an
3401  * out-of-order locking of AGFs and hence can cause deadlocks.
3402  */
3403 static int
3404 xfs_alloc_vextent_iterate_ags(
3405 	struct xfs_alloc_arg	*args,
3406 	xfs_agnumber_t		minimum_agno,
3407 	xfs_agnumber_t		start_agno,
3408 	xfs_agblock_t		target_agbno,
3409 	uint32_t		flags)
3410 {
3411 	struct xfs_mount	*mp = args->mp;
3412 	xfs_agnumber_t		restart_agno = minimum_agno;
3413 	xfs_agnumber_t		agno;
3414 	int			error = 0;
3415 
3416 	if (flags & XFS_ALLOC_FLAG_TRYLOCK)
3417 		restart_agno = 0;
3418 restart:
3419 	for_each_perag_wrap_range(mp, start_agno, restart_agno,
3420 			mp->m_sb.sb_agcount, agno, args->pag) {
3421 		args->agno = agno;
3422 		error = xfs_alloc_vextent_prepare_ag(args, flags);
3423 		if (error)
3424 			break;
3425 		if (!args->agbp) {
3426 			trace_xfs_alloc_vextent_loopfailed(args);
3427 			continue;
3428 		}
3429 
3430 		/*
3431 		 * Allocation is supposed to succeed now, so break out of the
3432 		 * loop regardless of whether we succeed or not.
3433 		 */
3434 		if (args->agno == start_agno && target_agbno) {
3435 			args->agbno = target_agbno;
3436 			error = xfs_alloc_ag_vextent_near(args);
3437 		} else {
3438 			args->agbno = 0;
3439 			error = xfs_alloc_ag_vextent_size(args);
3440 		}
3441 		break;
3442 	}
3443 	if (error) {
3444 		xfs_perag_rele(args->pag);
3445 		args->pag = NULL;
3446 		return error;
3447 	}
3448 	if (args->agbp)
3449 		return 0;
3450 
3451 	/*
3452 	 * We didn't find an AG we can alloation from. If we were given
3453 	 * constraining flags by the caller, drop them and retry the allocation
3454 	 * without any constraints being set.
3455 	 */
3456 	if (flags) {
3457 		flags = 0;
3458 		restart_agno = minimum_agno;
3459 		goto restart;
3460 	}
3461 
3462 	ASSERT(args->pag == NULL);
3463 	trace_xfs_alloc_vextent_allfailed(args);
3464 	return 0;
3465 }
3466 
3467 /*
3468  * Iterate from the AGs from the start AG to the end of the filesystem, trying
3469  * to allocate blocks. It starts with a near allocation attempt in the initial
3470  * AG, then falls back to anywhere-in-ag after the first AG fails. It will wrap
3471  * back to zero if allowed by previous allocations in this transaction,
3472  * otherwise will wrap back to the start AG and run a second blocking pass to
3473  * the end of the filesystem.
3474  */
3475 int
3476 xfs_alloc_vextent_start_ag(
3477 	struct xfs_alloc_arg	*args,
3478 	xfs_fsblock_t		target)
3479 {
3480 	struct xfs_mount	*mp = args->mp;
3481 	xfs_agnumber_t		minimum_agno;
3482 	xfs_agnumber_t		start_agno;
3483 	xfs_agnumber_t		rotorstep = xfs_rotorstep;
3484 	bool			bump_rotor = false;
3485 	int			error;
3486 
3487 	ASSERT(args->pag == NULL);
3488 
3489 	args->agno = NULLAGNUMBER;
3490 	args->agbno = NULLAGBLOCK;
3491 
3492 	trace_xfs_alloc_vextent_start_ag(args);
3493 
3494 	error = xfs_alloc_vextent_check_args(args, target, &minimum_agno);
3495 	if (error) {
3496 		if (error == -ENOSPC)
3497 			return 0;
3498 		return error;
3499 	}
3500 
3501 	if ((args->datatype & XFS_ALLOC_INITIAL_USER_DATA) &&
3502 	    xfs_is_inode32(mp)) {
3503 		target = XFS_AGB_TO_FSB(mp,
3504 				((mp->m_agfrotor / rotorstep) %
3505 				mp->m_sb.sb_agcount), 0);
3506 		bump_rotor = 1;
3507 	}
3508 
3509 	start_agno = max(minimum_agno, XFS_FSB_TO_AGNO(mp, target));
3510 	error = xfs_alloc_vextent_iterate_ags(args, minimum_agno, start_agno,
3511 			XFS_FSB_TO_AGBNO(mp, target), XFS_ALLOC_FLAG_TRYLOCK);
3512 
3513 	if (bump_rotor) {
3514 		if (args->agno == start_agno)
3515 			mp->m_agfrotor = (mp->m_agfrotor + 1) %
3516 				(mp->m_sb.sb_agcount * rotorstep);
3517 		else
3518 			mp->m_agfrotor = (args->agno * rotorstep + 1) %
3519 				(mp->m_sb.sb_agcount * rotorstep);
3520 	}
3521 
3522 	return xfs_alloc_vextent_finish(args, minimum_agno, error, true);
3523 }
3524 
3525 /*
3526  * Iterate from the agno indicated via @target through to the end of the
3527  * filesystem attempting blocking allocation. This does not wrap or try a second
3528  * pass, so will not recurse into AGs lower than indicated by the target.
3529  */
3530 int
3531 xfs_alloc_vextent_first_ag(
3532 	struct xfs_alloc_arg	*args,
3533 	xfs_fsblock_t		target)
3534  {
3535 	struct xfs_mount	*mp = args->mp;
3536 	xfs_agnumber_t		minimum_agno;
3537 	xfs_agnumber_t		start_agno;
3538 	int			error;
3539 
3540 	ASSERT(args->pag == NULL);
3541 
3542 	args->agno = NULLAGNUMBER;
3543 	args->agbno = NULLAGBLOCK;
3544 
3545 	trace_xfs_alloc_vextent_first_ag(args);
3546 
3547 	error = xfs_alloc_vextent_check_args(args, target, &minimum_agno);
3548 	if (error) {
3549 		if (error == -ENOSPC)
3550 			return 0;
3551 		return error;
3552 	}
3553 
3554 	start_agno = max(minimum_agno, XFS_FSB_TO_AGNO(mp, target));
3555 	error = xfs_alloc_vextent_iterate_ags(args, minimum_agno, start_agno,
3556 			XFS_FSB_TO_AGBNO(mp, target), 0);
3557 	return xfs_alloc_vextent_finish(args, minimum_agno, error, true);
3558 }
3559 
3560 /*
3561  * Allocate at the exact block target or fail. Caller is expected to hold a
3562  * perag reference in args->pag.
3563  */
3564 int
3565 xfs_alloc_vextent_exact_bno(
3566 	struct xfs_alloc_arg	*args,
3567 	xfs_fsblock_t		target)
3568 {
3569 	struct xfs_mount	*mp = args->mp;
3570 	xfs_agnumber_t		minimum_agno;
3571 	int			error;
3572 
3573 	ASSERT(args->pag != NULL);
3574 	ASSERT(args->pag->pag_agno == XFS_FSB_TO_AGNO(mp, target));
3575 
3576 	args->agno = XFS_FSB_TO_AGNO(mp, target);
3577 	args->agbno = XFS_FSB_TO_AGBNO(mp, target);
3578 
3579 	trace_xfs_alloc_vextent_exact_bno(args);
3580 
3581 	error = xfs_alloc_vextent_check_args(args, target, &minimum_agno);
3582 	if (error) {
3583 		if (error == -ENOSPC)
3584 			return 0;
3585 		return error;
3586 	}
3587 
3588 	error = xfs_alloc_vextent_prepare_ag(args, 0);
3589 	if (!error && args->agbp)
3590 		error = xfs_alloc_ag_vextent_exact(args);
3591 
3592 	return xfs_alloc_vextent_finish(args, minimum_agno, error, false);
3593 }
3594 
3595 /*
3596  * Allocate an extent as close to the target as possible. If there are not
3597  * viable candidates in the AG, then fail the allocation.
3598  *
3599  * Caller may or may not have a per-ag reference in args->pag.
3600  */
3601 int
3602 xfs_alloc_vextent_near_bno(
3603 	struct xfs_alloc_arg	*args,
3604 	xfs_fsblock_t		target)
3605 {
3606 	struct xfs_mount	*mp = args->mp;
3607 	xfs_agnumber_t		minimum_agno;
3608 	bool			needs_perag = args->pag == NULL;
3609 	int			error;
3610 
3611 	if (!needs_perag)
3612 		ASSERT(args->pag->pag_agno == XFS_FSB_TO_AGNO(mp, target));
3613 
3614 	args->agno = XFS_FSB_TO_AGNO(mp, target);
3615 	args->agbno = XFS_FSB_TO_AGBNO(mp, target);
3616 
3617 	trace_xfs_alloc_vextent_near_bno(args);
3618 
3619 	error = xfs_alloc_vextent_check_args(args, target, &minimum_agno);
3620 	if (error) {
3621 		if (error == -ENOSPC)
3622 			return 0;
3623 		return error;
3624 	}
3625 
3626 	if (needs_perag)
3627 		args->pag = xfs_perag_grab(mp, args->agno);
3628 
3629 	error = xfs_alloc_vextent_prepare_ag(args, 0);
3630 	if (!error && args->agbp)
3631 		error = xfs_alloc_ag_vextent_near(args);
3632 
3633 	return xfs_alloc_vextent_finish(args, minimum_agno, error, needs_perag);
3634 }
3635 
3636 /* Ensure that the freelist is at full capacity. */
3637 int
3638 xfs_free_extent_fix_freelist(
3639 	struct xfs_trans	*tp,
3640 	struct xfs_perag	*pag,
3641 	struct xfs_buf		**agbp)
3642 {
3643 	struct xfs_alloc_arg	args;
3644 	int			error;
3645 
3646 	memset(&args, 0, sizeof(struct xfs_alloc_arg));
3647 	args.tp = tp;
3648 	args.mp = tp->t_mountp;
3649 	args.agno = pag->pag_agno;
3650 	args.pag = pag;
3651 
3652 	/*
3653 	 * validate that the block number is legal - the enables us to detect
3654 	 * and handle a silent filesystem corruption rather than crashing.
3655 	 */
3656 	if (args.agno >= args.mp->m_sb.sb_agcount)
3657 		return -EFSCORRUPTED;
3658 
3659 	error = xfs_alloc_fix_freelist(&args, XFS_ALLOC_FLAG_FREEING);
3660 	if (error)
3661 		return error;
3662 
3663 	*agbp = args.agbp;
3664 	return 0;
3665 }
3666 
3667 /*
3668  * Free an extent.
3669  * Just break up the extent address and hand off to xfs_free_ag_extent
3670  * after fixing up the freelist.
3671  */
3672 int
3673 __xfs_free_extent(
3674 	struct xfs_trans		*tp,
3675 	struct xfs_perag		*pag,
3676 	xfs_agblock_t			agbno,
3677 	xfs_extlen_t			len,
3678 	const struct xfs_owner_info	*oinfo,
3679 	enum xfs_ag_resv_type		type,
3680 	bool				skip_discard)
3681 {
3682 	struct xfs_mount		*mp = tp->t_mountp;
3683 	struct xfs_buf			*agbp;
3684 	struct xfs_agf			*agf;
3685 	int				error;
3686 	unsigned int			busy_flags = 0;
3687 
3688 	ASSERT(len != 0);
3689 	ASSERT(type != XFS_AG_RESV_AGFL);
3690 
3691 	if (XFS_TEST_ERROR(false, mp,
3692 			XFS_ERRTAG_FREE_EXTENT))
3693 		return -EIO;
3694 
3695 	error = xfs_free_extent_fix_freelist(tp, pag, &agbp);
3696 	if (error)
3697 		return error;
3698 	agf = agbp->b_addr;
3699 
3700 	if (XFS_IS_CORRUPT(mp, agbno >= mp->m_sb.sb_agblocks)) {
3701 		error = -EFSCORRUPTED;
3702 		goto err_release;
3703 	}
3704 
3705 	/* validate the extent size is legal now we have the agf locked */
3706 	if (XFS_IS_CORRUPT(mp, agbno + len > be32_to_cpu(agf->agf_length))) {
3707 		error = -EFSCORRUPTED;
3708 		goto err_release;
3709 	}
3710 
3711 	error = xfs_free_ag_extent(tp, agbp, pag->pag_agno, agbno, len, oinfo,
3712 			type);
3713 	if (error)
3714 		goto err_release;
3715 
3716 	if (skip_discard)
3717 		busy_flags |= XFS_EXTENT_BUSY_SKIP_DISCARD;
3718 	xfs_extent_busy_insert(tp, pag, agbno, len, busy_flags);
3719 	return 0;
3720 
3721 err_release:
3722 	xfs_trans_brelse(tp, agbp);
3723 	return error;
3724 }
3725 
3726 struct xfs_alloc_query_range_info {
3727 	xfs_alloc_query_range_fn	fn;
3728 	void				*priv;
3729 };
3730 
3731 /* Format btree record and pass to our callback. */
3732 STATIC int
3733 xfs_alloc_query_range_helper(
3734 	struct xfs_btree_cur		*cur,
3735 	const union xfs_btree_rec	*rec,
3736 	void				*priv)
3737 {
3738 	struct xfs_alloc_query_range_info	*query = priv;
3739 	struct xfs_alloc_rec_incore		irec;
3740 	xfs_failaddr_t				fa;
3741 
3742 	xfs_alloc_btrec_to_irec(rec, &irec);
3743 	fa = xfs_alloc_check_irec(cur, &irec);
3744 	if (fa)
3745 		return xfs_alloc_complain_bad_rec(cur, fa, &irec);
3746 
3747 	return query->fn(cur, &irec, query->priv);
3748 }
3749 
3750 /* Find all free space within a given range of blocks. */
3751 int
3752 xfs_alloc_query_range(
3753 	struct xfs_btree_cur			*cur,
3754 	const struct xfs_alloc_rec_incore	*low_rec,
3755 	const struct xfs_alloc_rec_incore	*high_rec,
3756 	xfs_alloc_query_range_fn		fn,
3757 	void					*priv)
3758 {
3759 	union xfs_btree_irec			low_brec;
3760 	union xfs_btree_irec			high_brec;
3761 	struct xfs_alloc_query_range_info	query;
3762 
3763 	ASSERT(cur->bc_btnum == XFS_BTNUM_BNO);
3764 	low_brec.a = *low_rec;
3765 	high_brec.a = *high_rec;
3766 	query.priv = priv;
3767 	query.fn = fn;
3768 	return xfs_btree_query_range(cur, &low_brec, &high_brec,
3769 			xfs_alloc_query_range_helper, &query);
3770 }
3771 
3772 /* Find all free space records. */
3773 int
3774 xfs_alloc_query_all(
3775 	struct xfs_btree_cur			*cur,
3776 	xfs_alloc_query_range_fn		fn,
3777 	void					*priv)
3778 {
3779 	struct xfs_alloc_query_range_info	query;
3780 
3781 	ASSERT(cur->bc_btnum == XFS_BTNUM_BNO);
3782 	query.priv = priv;
3783 	query.fn = fn;
3784 	return xfs_btree_query_all(cur, xfs_alloc_query_range_helper, &query);
3785 }
3786 
3787 /*
3788  * Scan part of the keyspace of the free space and tell us if the area has no
3789  * records, is fully mapped by records, or is partially filled.
3790  */
3791 int
3792 xfs_alloc_has_records(
3793 	struct xfs_btree_cur	*cur,
3794 	xfs_agblock_t		bno,
3795 	xfs_extlen_t		len,
3796 	enum xbtree_recpacking	*outcome)
3797 {
3798 	union xfs_btree_irec	low;
3799 	union xfs_btree_irec	high;
3800 
3801 	memset(&low, 0, sizeof(low));
3802 	low.a.ar_startblock = bno;
3803 	memset(&high, 0xFF, sizeof(high));
3804 	high.a.ar_startblock = bno + len - 1;
3805 
3806 	return xfs_btree_has_records(cur, &low, &high, NULL, outcome);
3807 }
3808 
3809 /*
3810  * Walk all the blocks in the AGFL.  The @walk_fn can return any negative
3811  * error code or XFS_ITER_*.
3812  */
3813 int
3814 xfs_agfl_walk(
3815 	struct xfs_mount	*mp,
3816 	struct xfs_agf		*agf,
3817 	struct xfs_buf		*agflbp,
3818 	xfs_agfl_walk_fn	walk_fn,
3819 	void			*priv)
3820 {
3821 	__be32			*agfl_bno;
3822 	unsigned int		i;
3823 	int			error;
3824 
3825 	agfl_bno = xfs_buf_to_agfl_bno(agflbp);
3826 	i = be32_to_cpu(agf->agf_flfirst);
3827 
3828 	/* Nothing to walk in an empty AGFL. */
3829 	if (agf->agf_flcount == cpu_to_be32(0))
3830 		return 0;
3831 
3832 	/* Otherwise, walk from first to last, wrapping as needed. */
3833 	for (;;) {
3834 		error = walk_fn(mp, be32_to_cpu(agfl_bno[i]), priv);
3835 		if (error)
3836 			return error;
3837 		if (i == be32_to_cpu(agf->agf_fllast))
3838 			break;
3839 		if (++i == xfs_agfl_size(mp))
3840 			i = 0;
3841 	}
3842 
3843 	return 0;
3844 }
3845 
3846 int __init
3847 xfs_extfree_intent_init_cache(void)
3848 {
3849 	xfs_extfree_item_cache = kmem_cache_create("xfs_extfree_intent",
3850 			sizeof(struct xfs_extent_free_item),
3851 			0, 0, NULL);
3852 
3853 	return xfs_extfree_item_cache != NULL ? 0 : -ENOMEM;
3854 }
3855 
3856 void
3857 xfs_extfree_intent_destroy_cache(void)
3858 {
3859 	kmem_cache_destroy(xfs_extfree_item_cache);
3860 	xfs_extfree_item_cache = NULL;
3861 }
3862