xref: /linux/fs/xfs/libxfs/xfs_alloc.c (revision 59024954a1e7e26b62680e1f2b5725249a6c09f7)
1 /*
2  * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_format.h"
21 #include "xfs_log_format.h"
22 #include "xfs_shared.h"
23 #include "xfs_trans_resv.h"
24 #include "xfs_bit.h"
25 #include "xfs_sb.h"
26 #include "xfs_mount.h"
27 #include "xfs_defer.h"
28 #include "xfs_inode.h"
29 #include "xfs_btree.h"
30 #include "xfs_rmap.h"
31 #include "xfs_alloc_btree.h"
32 #include "xfs_alloc.h"
33 #include "xfs_extent_busy.h"
34 #include "xfs_error.h"
35 #include "xfs_cksum.h"
36 #include "xfs_trace.h"
37 #include "xfs_trans.h"
38 #include "xfs_buf_item.h"
39 #include "xfs_log.h"
40 #include "xfs_ag_resv.h"
41 
42 struct workqueue_struct *xfs_alloc_wq;
43 
44 #define XFS_ABSDIFF(a,b)	(((a) <= (b)) ? ((b) - (a)) : ((a) - (b)))
45 
46 #define	XFSA_FIXUP_BNO_OK	1
47 #define	XFSA_FIXUP_CNT_OK	2
48 
49 STATIC int xfs_alloc_ag_vextent_exact(xfs_alloc_arg_t *);
50 STATIC int xfs_alloc_ag_vextent_near(xfs_alloc_arg_t *);
51 STATIC int xfs_alloc_ag_vextent_size(xfs_alloc_arg_t *);
52 STATIC int xfs_alloc_ag_vextent_small(xfs_alloc_arg_t *,
53 		xfs_btree_cur_t *, xfs_agblock_t *, xfs_extlen_t *, int *);
54 
55 xfs_extlen_t
56 xfs_prealloc_blocks(
57 	struct xfs_mount	*mp)
58 {
59 	if (xfs_sb_version_hasrmapbt(&mp->m_sb))
60 		return XFS_RMAP_BLOCK(mp) + 1;
61 	if (xfs_sb_version_hasfinobt(&mp->m_sb))
62 		return XFS_FIBT_BLOCK(mp) + 1;
63 	return XFS_IBT_BLOCK(mp) + 1;
64 }
65 
66 /*
67  * In order to avoid ENOSPC-related deadlock caused by out-of-order locking of
68  * AGF buffer (PV 947395), we place constraints on the relationship among
69  * actual allocations for data blocks, freelist blocks, and potential file data
70  * bmap btree blocks. However, these restrictions may result in no actual space
71  * allocated for a delayed extent, for example, a data block in a certain AG is
72  * allocated but there is no additional block for the additional bmap btree
73  * block due to a split of the bmap btree of the file. The result of this may
74  * lead to an infinite loop when the file gets flushed to disk and all delayed
75  * extents need to be actually allocated. To get around this, we explicitly set
76  * aside a few blocks which will not be reserved in delayed allocation.
77  *
78  * We need to reserve 4 fsbs _per AG_ for the freelist and 4 more to handle a
79  * potential split of the file's bmap btree.
80  */
81 unsigned int
82 xfs_alloc_set_aside(
83 	struct xfs_mount	*mp)
84 {
85 	unsigned int		blocks;
86 
87 	blocks = 4 + (mp->m_sb.sb_agcount * XFS_ALLOC_AGFL_RESERVE);
88 	return blocks;
89 }
90 
91 /*
92  * When deciding how much space to allocate out of an AG, we limit the
93  * allocation maximum size to the size the AG. However, we cannot use all the
94  * blocks in the AG - some are permanently used by metadata. These
95  * blocks are generally:
96  *	- the AG superblock, AGF, AGI and AGFL
97  *	- the AGF (bno and cnt) and AGI btree root blocks, and optionally
98  *	  the AGI free inode and rmap btree root blocks.
99  *	- blocks on the AGFL according to xfs_alloc_set_aside() limits
100  *	- the rmapbt root block
101  *
102  * The AG headers are sector sized, so the amount of space they take up is
103  * dependent on filesystem geometry. The others are all single blocks.
104  */
105 unsigned int
106 xfs_alloc_ag_max_usable(
107 	struct xfs_mount	*mp)
108 {
109 	unsigned int		blocks;
110 
111 	blocks = XFS_BB_TO_FSB(mp, XFS_FSS_TO_BB(mp, 4)); /* ag headers */
112 	blocks += XFS_ALLOC_AGFL_RESERVE;
113 	blocks += 3;			/* AGF, AGI btree root blocks */
114 	if (xfs_sb_version_hasfinobt(&mp->m_sb))
115 		blocks++;		/* finobt root block */
116 	if (xfs_sb_version_hasrmapbt(&mp->m_sb))
117 		blocks++; 		/* rmap root block */
118 
119 	return mp->m_sb.sb_agblocks - blocks;
120 }
121 
122 /*
123  * Lookup the record equal to [bno, len] in the btree given by cur.
124  */
125 STATIC int				/* error */
126 xfs_alloc_lookup_eq(
127 	struct xfs_btree_cur	*cur,	/* btree cursor */
128 	xfs_agblock_t		bno,	/* starting block of extent */
129 	xfs_extlen_t		len,	/* length of extent */
130 	int			*stat)	/* success/failure */
131 {
132 	cur->bc_rec.a.ar_startblock = bno;
133 	cur->bc_rec.a.ar_blockcount = len;
134 	return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
135 }
136 
137 /*
138  * Lookup the first record greater than or equal to [bno, len]
139  * in the btree given by cur.
140  */
141 int				/* error */
142 xfs_alloc_lookup_ge(
143 	struct xfs_btree_cur	*cur,	/* btree cursor */
144 	xfs_agblock_t		bno,	/* starting block of extent */
145 	xfs_extlen_t		len,	/* length of extent */
146 	int			*stat)	/* success/failure */
147 {
148 	cur->bc_rec.a.ar_startblock = bno;
149 	cur->bc_rec.a.ar_blockcount = len;
150 	return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
151 }
152 
153 /*
154  * Lookup the first record less than or equal to [bno, len]
155  * in the btree given by cur.
156  */
157 static int				/* error */
158 xfs_alloc_lookup_le(
159 	struct xfs_btree_cur	*cur,	/* btree cursor */
160 	xfs_agblock_t		bno,	/* starting block of extent */
161 	xfs_extlen_t		len,	/* length of extent */
162 	int			*stat)	/* success/failure */
163 {
164 	cur->bc_rec.a.ar_startblock = bno;
165 	cur->bc_rec.a.ar_blockcount = len;
166 	return xfs_btree_lookup(cur, XFS_LOOKUP_LE, stat);
167 }
168 
169 /*
170  * Update the record referred to by cur to the value given
171  * by [bno, len].
172  * This either works (return 0) or gets an EFSCORRUPTED error.
173  */
174 STATIC int				/* error */
175 xfs_alloc_update(
176 	struct xfs_btree_cur	*cur,	/* btree cursor */
177 	xfs_agblock_t		bno,	/* starting block of extent */
178 	xfs_extlen_t		len)	/* length of extent */
179 {
180 	union xfs_btree_rec	rec;
181 
182 	rec.alloc.ar_startblock = cpu_to_be32(bno);
183 	rec.alloc.ar_blockcount = cpu_to_be32(len);
184 	return xfs_btree_update(cur, &rec);
185 }
186 
187 /*
188  * Get the data from the pointed-to record.
189  */
190 int					/* error */
191 xfs_alloc_get_rec(
192 	struct xfs_btree_cur	*cur,	/* btree cursor */
193 	xfs_agblock_t		*bno,	/* output: starting block of extent */
194 	xfs_extlen_t		*len,	/* output: length of extent */
195 	int			*stat)	/* output: success/failure */
196 {
197 	union xfs_btree_rec	*rec;
198 	int			error;
199 
200 	error = xfs_btree_get_rec(cur, &rec, stat);
201 	if (!error && *stat == 1) {
202 		*bno = be32_to_cpu(rec->alloc.ar_startblock);
203 		*len = be32_to_cpu(rec->alloc.ar_blockcount);
204 	}
205 	return error;
206 }
207 
208 /*
209  * Compute aligned version of the found extent.
210  * Takes alignment and min length into account.
211  */
212 STATIC void
213 xfs_alloc_compute_aligned(
214 	xfs_alloc_arg_t	*args,		/* allocation argument structure */
215 	xfs_agblock_t	foundbno,	/* starting block in found extent */
216 	xfs_extlen_t	foundlen,	/* length in found extent */
217 	xfs_agblock_t	*resbno,	/* result block number */
218 	xfs_extlen_t	*reslen)	/* result length */
219 {
220 	xfs_agblock_t	bno;
221 	xfs_extlen_t	len;
222 	xfs_extlen_t	diff;
223 
224 	/* Trim busy sections out of found extent */
225 	xfs_extent_busy_trim(args, foundbno, foundlen, &bno, &len);
226 
227 	/*
228 	 * If we have a largish extent that happens to start before min_agbno,
229 	 * see if we can shift it into range...
230 	 */
231 	if (bno < args->min_agbno && bno + len > args->min_agbno) {
232 		diff = args->min_agbno - bno;
233 		if (len > diff) {
234 			bno += diff;
235 			len -= diff;
236 		}
237 	}
238 
239 	if (args->alignment > 1 && len >= args->minlen) {
240 		xfs_agblock_t	aligned_bno = roundup(bno, args->alignment);
241 
242 		diff = aligned_bno - bno;
243 
244 		*resbno = aligned_bno;
245 		*reslen = diff >= len ? 0 : len - diff;
246 	} else {
247 		*resbno = bno;
248 		*reslen = len;
249 	}
250 }
251 
252 /*
253  * Compute best start block and diff for "near" allocations.
254  * freelen >= wantlen already checked by caller.
255  */
256 STATIC xfs_extlen_t			/* difference value (absolute) */
257 xfs_alloc_compute_diff(
258 	xfs_agblock_t	wantbno,	/* target starting block */
259 	xfs_extlen_t	wantlen,	/* target length */
260 	xfs_extlen_t	alignment,	/* target alignment */
261 	int		datatype,	/* are we allocating data? */
262 	xfs_agblock_t	freebno,	/* freespace's starting block */
263 	xfs_extlen_t	freelen,	/* freespace's length */
264 	xfs_agblock_t	*newbnop)	/* result: best start block from free */
265 {
266 	xfs_agblock_t	freeend;	/* end of freespace extent */
267 	xfs_agblock_t	newbno1;	/* return block number */
268 	xfs_agblock_t	newbno2;	/* other new block number */
269 	xfs_extlen_t	newlen1=0;	/* length with newbno1 */
270 	xfs_extlen_t	newlen2=0;	/* length with newbno2 */
271 	xfs_agblock_t	wantend;	/* end of target extent */
272 	bool		userdata = xfs_alloc_is_userdata(datatype);
273 
274 	ASSERT(freelen >= wantlen);
275 	freeend = freebno + freelen;
276 	wantend = wantbno + wantlen;
277 	/*
278 	 * We want to allocate from the start of a free extent if it is past
279 	 * the desired block or if we are allocating user data and the free
280 	 * extent is before desired block. The second case is there to allow
281 	 * for contiguous allocation from the remaining free space if the file
282 	 * grows in the short term.
283 	 */
284 	if (freebno >= wantbno || (userdata && freeend < wantend)) {
285 		if ((newbno1 = roundup(freebno, alignment)) >= freeend)
286 			newbno1 = NULLAGBLOCK;
287 	} else if (freeend >= wantend && alignment > 1) {
288 		newbno1 = roundup(wantbno, alignment);
289 		newbno2 = newbno1 - alignment;
290 		if (newbno1 >= freeend)
291 			newbno1 = NULLAGBLOCK;
292 		else
293 			newlen1 = XFS_EXTLEN_MIN(wantlen, freeend - newbno1);
294 		if (newbno2 < freebno)
295 			newbno2 = NULLAGBLOCK;
296 		else
297 			newlen2 = XFS_EXTLEN_MIN(wantlen, freeend - newbno2);
298 		if (newbno1 != NULLAGBLOCK && newbno2 != NULLAGBLOCK) {
299 			if (newlen1 < newlen2 ||
300 			    (newlen1 == newlen2 &&
301 			     XFS_ABSDIFF(newbno1, wantbno) >
302 			     XFS_ABSDIFF(newbno2, wantbno)))
303 				newbno1 = newbno2;
304 		} else if (newbno2 != NULLAGBLOCK)
305 			newbno1 = newbno2;
306 	} else if (freeend >= wantend) {
307 		newbno1 = wantbno;
308 	} else if (alignment > 1) {
309 		newbno1 = roundup(freeend - wantlen, alignment);
310 		if (newbno1 > freeend - wantlen &&
311 		    newbno1 - alignment >= freebno)
312 			newbno1 -= alignment;
313 		else if (newbno1 >= freeend)
314 			newbno1 = NULLAGBLOCK;
315 	} else
316 		newbno1 = freeend - wantlen;
317 	*newbnop = newbno1;
318 	return newbno1 == NULLAGBLOCK ? 0 : XFS_ABSDIFF(newbno1, wantbno);
319 }
320 
321 /*
322  * Fix up the length, based on mod and prod.
323  * len should be k * prod + mod for some k.
324  * If len is too small it is returned unchanged.
325  * If len hits maxlen it is left alone.
326  */
327 STATIC void
328 xfs_alloc_fix_len(
329 	xfs_alloc_arg_t	*args)		/* allocation argument structure */
330 {
331 	xfs_extlen_t	k;
332 	xfs_extlen_t	rlen;
333 
334 	ASSERT(args->mod < args->prod);
335 	rlen = args->len;
336 	ASSERT(rlen >= args->minlen);
337 	ASSERT(rlen <= args->maxlen);
338 	if (args->prod <= 1 || rlen < args->mod || rlen == args->maxlen ||
339 	    (args->mod == 0 && rlen < args->prod))
340 		return;
341 	k = rlen % args->prod;
342 	if (k == args->mod)
343 		return;
344 	if (k > args->mod)
345 		rlen = rlen - (k - args->mod);
346 	else
347 		rlen = rlen - args->prod + (args->mod - k);
348 	/* casts to (int) catch length underflows */
349 	if ((int)rlen < (int)args->minlen)
350 		return;
351 	ASSERT(rlen >= args->minlen && rlen <= args->maxlen);
352 	ASSERT(rlen % args->prod == args->mod);
353 	args->len = rlen;
354 }
355 
356 /*
357  * Fix up length if there is too little space left in the a.g.
358  * Return 1 if ok, 0 if too little, should give up.
359  */
360 STATIC int
361 xfs_alloc_fix_minleft(
362 	xfs_alloc_arg_t	*args)		/* allocation argument structure */
363 {
364 	xfs_agf_t	*agf;		/* a.g. freelist header */
365 	int		diff;		/* free space difference */
366 
367 	if (args->minleft == 0)
368 		return 1;
369 	agf = XFS_BUF_TO_AGF(args->agbp);
370 	diff = be32_to_cpu(agf->agf_freeblks)
371 		- args->len - args->minleft;
372 	if (diff >= 0)
373 		return 1;
374 	args->len += diff;		/* shrink the allocated space */
375 	/* casts to (int) catch length underflows */
376 	if ((int)args->len >= (int)args->minlen)
377 		return 1;
378 	args->agbno = NULLAGBLOCK;
379 	return 0;
380 }
381 
382 /*
383  * Update the two btrees, logically removing from freespace the extent
384  * starting at rbno, rlen blocks.  The extent is contained within the
385  * actual (current) free extent fbno for flen blocks.
386  * Flags are passed in indicating whether the cursors are set to the
387  * relevant records.
388  */
389 STATIC int				/* error code */
390 xfs_alloc_fixup_trees(
391 	xfs_btree_cur_t	*cnt_cur,	/* cursor for by-size btree */
392 	xfs_btree_cur_t	*bno_cur,	/* cursor for by-block btree */
393 	xfs_agblock_t	fbno,		/* starting block of free extent */
394 	xfs_extlen_t	flen,		/* length of free extent */
395 	xfs_agblock_t	rbno,		/* starting block of returned extent */
396 	xfs_extlen_t	rlen,		/* length of returned extent */
397 	int		flags)		/* flags, XFSA_FIXUP_... */
398 {
399 	int		error;		/* error code */
400 	int		i;		/* operation results */
401 	xfs_agblock_t	nfbno1;		/* first new free startblock */
402 	xfs_agblock_t	nfbno2;		/* second new free startblock */
403 	xfs_extlen_t	nflen1=0;	/* first new free length */
404 	xfs_extlen_t	nflen2=0;	/* second new free length */
405 	struct xfs_mount *mp;
406 
407 	mp = cnt_cur->bc_mp;
408 
409 	/*
410 	 * Look up the record in the by-size tree if necessary.
411 	 */
412 	if (flags & XFSA_FIXUP_CNT_OK) {
413 #ifdef DEBUG
414 		if ((error = xfs_alloc_get_rec(cnt_cur, &nfbno1, &nflen1, &i)))
415 			return error;
416 		XFS_WANT_CORRUPTED_RETURN(mp,
417 			i == 1 && nfbno1 == fbno && nflen1 == flen);
418 #endif
419 	} else {
420 		if ((error = xfs_alloc_lookup_eq(cnt_cur, fbno, flen, &i)))
421 			return error;
422 		XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
423 	}
424 	/*
425 	 * Look up the record in the by-block tree if necessary.
426 	 */
427 	if (flags & XFSA_FIXUP_BNO_OK) {
428 #ifdef DEBUG
429 		if ((error = xfs_alloc_get_rec(bno_cur, &nfbno1, &nflen1, &i)))
430 			return error;
431 		XFS_WANT_CORRUPTED_RETURN(mp,
432 			i == 1 && nfbno1 == fbno && nflen1 == flen);
433 #endif
434 	} else {
435 		if ((error = xfs_alloc_lookup_eq(bno_cur, fbno, flen, &i)))
436 			return error;
437 		XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
438 	}
439 
440 #ifdef DEBUG
441 	if (bno_cur->bc_nlevels == 1 && cnt_cur->bc_nlevels == 1) {
442 		struct xfs_btree_block	*bnoblock;
443 		struct xfs_btree_block	*cntblock;
444 
445 		bnoblock = XFS_BUF_TO_BLOCK(bno_cur->bc_bufs[0]);
446 		cntblock = XFS_BUF_TO_BLOCK(cnt_cur->bc_bufs[0]);
447 
448 		XFS_WANT_CORRUPTED_RETURN(mp,
449 			bnoblock->bb_numrecs == cntblock->bb_numrecs);
450 	}
451 #endif
452 
453 	/*
454 	 * Deal with all four cases: the allocated record is contained
455 	 * within the freespace record, so we can have new freespace
456 	 * at either (or both) end, or no freespace remaining.
457 	 */
458 	if (rbno == fbno && rlen == flen)
459 		nfbno1 = nfbno2 = NULLAGBLOCK;
460 	else if (rbno == fbno) {
461 		nfbno1 = rbno + rlen;
462 		nflen1 = flen - rlen;
463 		nfbno2 = NULLAGBLOCK;
464 	} else if (rbno + rlen == fbno + flen) {
465 		nfbno1 = fbno;
466 		nflen1 = flen - rlen;
467 		nfbno2 = NULLAGBLOCK;
468 	} else {
469 		nfbno1 = fbno;
470 		nflen1 = rbno - fbno;
471 		nfbno2 = rbno + rlen;
472 		nflen2 = (fbno + flen) - nfbno2;
473 	}
474 	/*
475 	 * Delete the entry from the by-size btree.
476 	 */
477 	if ((error = xfs_btree_delete(cnt_cur, &i)))
478 		return error;
479 	XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
480 	/*
481 	 * Add new by-size btree entry(s).
482 	 */
483 	if (nfbno1 != NULLAGBLOCK) {
484 		if ((error = xfs_alloc_lookup_eq(cnt_cur, nfbno1, nflen1, &i)))
485 			return error;
486 		XFS_WANT_CORRUPTED_RETURN(mp, i == 0);
487 		if ((error = xfs_btree_insert(cnt_cur, &i)))
488 			return error;
489 		XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
490 	}
491 	if (nfbno2 != NULLAGBLOCK) {
492 		if ((error = xfs_alloc_lookup_eq(cnt_cur, nfbno2, nflen2, &i)))
493 			return error;
494 		XFS_WANT_CORRUPTED_RETURN(mp, i == 0);
495 		if ((error = xfs_btree_insert(cnt_cur, &i)))
496 			return error;
497 		XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
498 	}
499 	/*
500 	 * Fix up the by-block btree entry(s).
501 	 */
502 	if (nfbno1 == NULLAGBLOCK) {
503 		/*
504 		 * No remaining freespace, just delete the by-block tree entry.
505 		 */
506 		if ((error = xfs_btree_delete(bno_cur, &i)))
507 			return error;
508 		XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
509 	} else {
510 		/*
511 		 * Update the by-block entry to start later|be shorter.
512 		 */
513 		if ((error = xfs_alloc_update(bno_cur, nfbno1, nflen1)))
514 			return error;
515 	}
516 	if (nfbno2 != NULLAGBLOCK) {
517 		/*
518 		 * 2 resulting free entries, need to add one.
519 		 */
520 		if ((error = xfs_alloc_lookup_eq(bno_cur, nfbno2, nflen2, &i)))
521 			return error;
522 		XFS_WANT_CORRUPTED_RETURN(mp, i == 0);
523 		if ((error = xfs_btree_insert(bno_cur, &i)))
524 			return error;
525 		XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
526 	}
527 	return 0;
528 }
529 
530 static bool
531 xfs_agfl_verify(
532 	struct xfs_buf	*bp)
533 {
534 	struct xfs_mount *mp = bp->b_target->bt_mount;
535 	struct xfs_agfl	*agfl = XFS_BUF_TO_AGFL(bp);
536 	int		i;
537 
538 	if (!uuid_equal(&agfl->agfl_uuid, &mp->m_sb.sb_meta_uuid))
539 		return false;
540 	if (be32_to_cpu(agfl->agfl_magicnum) != XFS_AGFL_MAGIC)
541 		return false;
542 	/*
543 	 * during growfs operations, the perag is not fully initialised,
544 	 * so we can't use it for any useful checking. growfs ensures we can't
545 	 * use it by using uncached buffers that don't have the perag attached
546 	 * so we can detect and avoid this problem.
547 	 */
548 	if (bp->b_pag && be32_to_cpu(agfl->agfl_seqno) != bp->b_pag->pag_agno)
549 		return false;
550 
551 	for (i = 0; i < XFS_AGFL_SIZE(mp); i++) {
552 		if (be32_to_cpu(agfl->agfl_bno[i]) != NULLAGBLOCK &&
553 		    be32_to_cpu(agfl->agfl_bno[i]) >= mp->m_sb.sb_agblocks)
554 			return false;
555 	}
556 
557 	return xfs_log_check_lsn(mp,
558 				 be64_to_cpu(XFS_BUF_TO_AGFL(bp)->agfl_lsn));
559 }
560 
561 static void
562 xfs_agfl_read_verify(
563 	struct xfs_buf	*bp)
564 {
565 	struct xfs_mount *mp = bp->b_target->bt_mount;
566 
567 	/*
568 	 * There is no verification of non-crc AGFLs because mkfs does not
569 	 * initialise the AGFL to zero or NULL. Hence the only valid part of the
570 	 * AGFL is what the AGF says is active. We can't get to the AGF, so we
571 	 * can't verify just those entries are valid.
572 	 */
573 	if (!xfs_sb_version_hascrc(&mp->m_sb))
574 		return;
575 
576 	if (!xfs_buf_verify_cksum(bp, XFS_AGFL_CRC_OFF))
577 		xfs_buf_ioerror(bp, -EFSBADCRC);
578 	else if (!xfs_agfl_verify(bp))
579 		xfs_buf_ioerror(bp, -EFSCORRUPTED);
580 
581 	if (bp->b_error)
582 		xfs_verifier_error(bp);
583 }
584 
585 static void
586 xfs_agfl_write_verify(
587 	struct xfs_buf	*bp)
588 {
589 	struct xfs_mount *mp = bp->b_target->bt_mount;
590 	struct xfs_buf_log_item	*bip = bp->b_fspriv;
591 
592 	/* no verification of non-crc AGFLs */
593 	if (!xfs_sb_version_hascrc(&mp->m_sb))
594 		return;
595 
596 	if (!xfs_agfl_verify(bp)) {
597 		xfs_buf_ioerror(bp, -EFSCORRUPTED);
598 		xfs_verifier_error(bp);
599 		return;
600 	}
601 
602 	if (bip)
603 		XFS_BUF_TO_AGFL(bp)->agfl_lsn = cpu_to_be64(bip->bli_item.li_lsn);
604 
605 	xfs_buf_update_cksum(bp, XFS_AGFL_CRC_OFF);
606 }
607 
608 const struct xfs_buf_ops xfs_agfl_buf_ops = {
609 	.name = "xfs_agfl",
610 	.verify_read = xfs_agfl_read_verify,
611 	.verify_write = xfs_agfl_write_verify,
612 };
613 
614 /*
615  * Read in the allocation group free block array.
616  */
617 STATIC int				/* error */
618 xfs_alloc_read_agfl(
619 	xfs_mount_t	*mp,		/* mount point structure */
620 	xfs_trans_t	*tp,		/* transaction pointer */
621 	xfs_agnumber_t	agno,		/* allocation group number */
622 	xfs_buf_t	**bpp)		/* buffer for the ag free block array */
623 {
624 	xfs_buf_t	*bp;		/* return value */
625 	int		error;
626 
627 	ASSERT(agno != NULLAGNUMBER);
628 	error = xfs_trans_read_buf(
629 			mp, tp, mp->m_ddev_targp,
630 			XFS_AG_DADDR(mp, agno, XFS_AGFL_DADDR(mp)),
631 			XFS_FSS_TO_BB(mp, 1), 0, &bp, &xfs_agfl_buf_ops);
632 	if (error)
633 		return error;
634 	xfs_buf_set_ref(bp, XFS_AGFL_REF);
635 	*bpp = bp;
636 	return 0;
637 }
638 
639 STATIC int
640 xfs_alloc_update_counters(
641 	struct xfs_trans	*tp,
642 	struct xfs_perag	*pag,
643 	struct xfs_buf		*agbp,
644 	long			len)
645 {
646 	struct xfs_agf		*agf = XFS_BUF_TO_AGF(agbp);
647 
648 	pag->pagf_freeblks += len;
649 	be32_add_cpu(&agf->agf_freeblks, len);
650 
651 	xfs_trans_agblocks_delta(tp, len);
652 	if (unlikely(be32_to_cpu(agf->agf_freeblks) >
653 		     be32_to_cpu(agf->agf_length)))
654 		return -EFSCORRUPTED;
655 
656 	xfs_alloc_log_agf(tp, agbp, XFS_AGF_FREEBLKS);
657 	return 0;
658 }
659 
660 /*
661  * Allocation group level functions.
662  */
663 
664 /*
665  * Allocate a variable extent in the allocation group agno.
666  * Type and bno are used to determine where in the allocation group the
667  * extent will start.
668  * Extent's length (returned in *len) will be between minlen and maxlen,
669  * and of the form k * prod + mod unless there's nothing that large.
670  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
671  */
672 STATIC int			/* error */
673 xfs_alloc_ag_vextent(
674 	xfs_alloc_arg_t	*args)	/* argument structure for allocation */
675 {
676 	int		error=0;
677 	xfs_extlen_t	reservation;
678 	xfs_extlen_t	oldmax;
679 
680 	ASSERT(args->minlen > 0);
681 	ASSERT(args->maxlen > 0);
682 	ASSERT(args->minlen <= args->maxlen);
683 	ASSERT(args->mod < args->prod);
684 	ASSERT(args->alignment > 0);
685 
686 	/*
687 	 * Clamp maxlen to the amount of free space minus any reservations
688 	 * that have been made.
689 	 */
690 	oldmax = args->maxlen;
691 	reservation = xfs_ag_resv_needed(args->pag, args->resv);
692 	if (args->maxlen > args->pag->pagf_freeblks - reservation)
693 		args->maxlen = args->pag->pagf_freeblks - reservation;
694 	if (args->maxlen == 0) {
695 		args->agbno = NULLAGBLOCK;
696 		args->maxlen = oldmax;
697 		return 0;
698 	}
699 
700 	/*
701 	 * Branch to correct routine based on the type.
702 	 */
703 	args->wasfromfl = 0;
704 	switch (args->type) {
705 	case XFS_ALLOCTYPE_THIS_AG:
706 		error = xfs_alloc_ag_vextent_size(args);
707 		break;
708 	case XFS_ALLOCTYPE_NEAR_BNO:
709 		error = xfs_alloc_ag_vextent_near(args);
710 		break;
711 	case XFS_ALLOCTYPE_THIS_BNO:
712 		error = xfs_alloc_ag_vextent_exact(args);
713 		break;
714 	default:
715 		ASSERT(0);
716 		/* NOTREACHED */
717 	}
718 
719 	args->maxlen = oldmax;
720 
721 	if (error || args->agbno == NULLAGBLOCK)
722 		return error;
723 
724 	ASSERT(args->len >= args->minlen);
725 	ASSERT(args->len <= args->maxlen);
726 	ASSERT(!args->wasfromfl || args->resv != XFS_AG_RESV_AGFL);
727 	ASSERT(args->agbno % args->alignment == 0);
728 
729 	/* if not file data, insert new block into the reverse map btree */
730 	if (args->oinfo.oi_owner != XFS_RMAP_OWN_UNKNOWN) {
731 		error = xfs_rmap_alloc(args->tp, args->agbp, args->agno,
732 				       args->agbno, args->len, &args->oinfo);
733 		if (error)
734 			return error;
735 	}
736 
737 	if (!args->wasfromfl) {
738 		error = xfs_alloc_update_counters(args->tp, args->pag,
739 						  args->agbp,
740 						  -((long)(args->len)));
741 		if (error)
742 			return error;
743 
744 		ASSERT(!xfs_extent_busy_search(args->mp, args->agno,
745 					      args->agbno, args->len));
746 	}
747 
748 	xfs_ag_resv_alloc_extent(args->pag, args->resv, args);
749 
750 	XFS_STATS_INC(args->mp, xs_allocx);
751 	XFS_STATS_ADD(args->mp, xs_allocb, args->len);
752 	return error;
753 }
754 
755 /*
756  * Allocate a variable extent at exactly agno/bno.
757  * Extent's length (returned in *len) will be between minlen and maxlen,
758  * and of the form k * prod + mod unless there's nothing that large.
759  * Return the starting a.g. block (bno), or NULLAGBLOCK if we can't do it.
760  */
761 STATIC int			/* error */
762 xfs_alloc_ag_vextent_exact(
763 	xfs_alloc_arg_t	*args)	/* allocation argument structure */
764 {
765 	xfs_btree_cur_t	*bno_cur;/* by block-number btree cursor */
766 	xfs_btree_cur_t	*cnt_cur;/* by count btree cursor */
767 	int		error;
768 	xfs_agblock_t	fbno;	/* start block of found extent */
769 	xfs_extlen_t	flen;	/* length of found extent */
770 	xfs_agblock_t	tbno;	/* start block of trimmed extent */
771 	xfs_extlen_t	tlen;	/* length of trimmed extent */
772 	xfs_agblock_t	tend;	/* end block of trimmed extent */
773 	int		i;	/* success/failure of operation */
774 
775 	ASSERT(args->alignment == 1);
776 
777 	/*
778 	 * Allocate/initialize a cursor for the by-number freespace btree.
779 	 */
780 	bno_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
781 					  args->agno, XFS_BTNUM_BNO);
782 
783 	/*
784 	 * Lookup bno and minlen in the btree (minlen is irrelevant, really).
785 	 * Look for the closest free block <= bno, it must contain bno
786 	 * if any free block does.
787 	 */
788 	error = xfs_alloc_lookup_le(bno_cur, args->agbno, args->minlen, &i);
789 	if (error)
790 		goto error0;
791 	if (!i)
792 		goto not_found;
793 
794 	/*
795 	 * Grab the freespace record.
796 	 */
797 	error = xfs_alloc_get_rec(bno_cur, &fbno, &flen, &i);
798 	if (error)
799 		goto error0;
800 	XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
801 	ASSERT(fbno <= args->agbno);
802 
803 	/*
804 	 * Check for overlapping busy extents.
805 	 */
806 	xfs_extent_busy_trim(args, fbno, flen, &tbno, &tlen);
807 
808 	/*
809 	 * Give up if the start of the extent is busy, or the freespace isn't
810 	 * long enough for the minimum request.
811 	 */
812 	if (tbno > args->agbno)
813 		goto not_found;
814 	if (tlen < args->minlen)
815 		goto not_found;
816 	tend = tbno + tlen;
817 	if (tend < args->agbno + args->minlen)
818 		goto not_found;
819 
820 	/*
821 	 * End of extent will be smaller of the freespace end and the
822 	 * maximal requested end.
823 	 *
824 	 * Fix the length according to mod and prod if given.
825 	 */
826 	args->len = XFS_AGBLOCK_MIN(tend, args->agbno + args->maxlen)
827 						- args->agbno;
828 	xfs_alloc_fix_len(args);
829 	if (!xfs_alloc_fix_minleft(args))
830 		goto not_found;
831 
832 	ASSERT(args->agbno + args->len <= tend);
833 
834 	/*
835 	 * We are allocating agbno for args->len
836 	 * Allocate/initialize a cursor for the by-size btree.
837 	 */
838 	cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
839 		args->agno, XFS_BTNUM_CNT);
840 	ASSERT(args->agbno + args->len <=
841 		be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length));
842 	error = xfs_alloc_fixup_trees(cnt_cur, bno_cur, fbno, flen, args->agbno,
843 				      args->len, XFSA_FIXUP_BNO_OK);
844 	if (error) {
845 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
846 		goto error0;
847 	}
848 
849 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
850 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
851 
852 	args->wasfromfl = 0;
853 	trace_xfs_alloc_exact_done(args);
854 	return 0;
855 
856 not_found:
857 	/* Didn't find it, return null. */
858 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
859 	args->agbno = NULLAGBLOCK;
860 	trace_xfs_alloc_exact_notfound(args);
861 	return 0;
862 
863 error0:
864 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
865 	trace_xfs_alloc_exact_error(args);
866 	return error;
867 }
868 
869 /*
870  * Search the btree in a given direction via the search cursor and compare
871  * the records found against the good extent we've already found.
872  */
873 STATIC int
874 xfs_alloc_find_best_extent(
875 	struct xfs_alloc_arg	*args,	/* allocation argument structure */
876 	struct xfs_btree_cur	**gcur,	/* good cursor */
877 	struct xfs_btree_cur	**scur,	/* searching cursor */
878 	xfs_agblock_t		gdiff,	/* difference for search comparison */
879 	xfs_agblock_t		*sbno,	/* extent found by search */
880 	xfs_extlen_t		*slen,	/* extent length */
881 	xfs_agblock_t		*sbnoa,	/* aligned extent found by search */
882 	xfs_extlen_t		*slena,	/* aligned extent length */
883 	int			dir)	/* 0 = search right, 1 = search left */
884 {
885 	xfs_agblock_t		new;
886 	xfs_agblock_t		sdiff;
887 	int			error;
888 	int			i;
889 
890 	/* The good extent is perfect, no need to  search. */
891 	if (!gdiff)
892 		goto out_use_good;
893 
894 	/*
895 	 * Look until we find a better one, run out of space or run off the end.
896 	 */
897 	do {
898 		error = xfs_alloc_get_rec(*scur, sbno, slen, &i);
899 		if (error)
900 			goto error0;
901 		XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
902 		xfs_alloc_compute_aligned(args, *sbno, *slen, sbnoa, slena);
903 
904 		/*
905 		 * The good extent is closer than this one.
906 		 */
907 		if (!dir) {
908 			if (*sbnoa > args->max_agbno)
909 				goto out_use_good;
910 			if (*sbnoa >= args->agbno + gdiff)
911 				goto out_use_good;
912 		} else {
913 			if (*sbnoa < args->min_agbno)
914 				goto out_use_good;
915 			if (*sbnoa <= args->agbno - gdiff)
916 				goto out_use_good;
917 		}
918 
919 		/*
920 		 * Same distance, compare length and pick the best.
921 		 */
922 		if (*slena >= args->minlen) {
923 			args->len = XFS_EXTLEN_MIN(*slena, args->maxlen);
924 			xfs_alloc_fix_len(args);
925 
926 			sdiff = xfs_alloc_compute_diff(args->agbno, args->len,
927 						       args->alignment,
928 						       args->datatype, *sbnoa,
929 						       *slena, &new);
930 
931 			/*
932 			 * Choose closer size and invalidate other cursor.
933 			 */
934 			if (sdiff < gdiff)
935 				goto out_use_search;
936 			goto out_use_good;
937 		}
938 
939 		if (!dir)
940 			error = xfs_btree_increment(*scur, 0, &i);
941 		else
942 			error = xfs_btree_decrement(*scur, 0, &i);
943 		if (error)
944 			goto error0;
945 	} while (i);
946 
947 out_use_good:
948 	xfs_btree_del_cursor(*scur, XFS_BTREE_NOERROR);
949 	*scur = NULL;
950 	return 0;
951 
952 out_use_search:
953 	xfs_btree_del_cursor(*gcur, XFS_BTREE_NOERROR);
954 	*gcur = NULL;
955 	return 0;
956 
957 error0:
958 	/* caller invalidates cursors */
959 	return error;
960 }
961 
962 /*
963  * Allocate a variable extent near bno in the allocation group agno.
964  * Extent's length (returned in len) will be between minlen and maxlen,
965  * and of the form k * prod + mod unless there's nothing that large.
966  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
967  */
968 STATIC int				/* error */
969 xfs_alloc_ag_vextent_near(
970 	xfs_alloc_arg_t	*args)		/* allocation argument structure */
971 {
972 	xfs_btree_cur_t	*bno_cur_gt;	/* cursor for bno btree, right side */
973 	xfs_btree_cur_t	*bno_cur_lt;	/* cursor for bno btree, left side */
974 	xfs_btree_cur_t	*cnt_cur;	/* cursor for count btree */
975 	xfs_agblock_t	gtbno;		/* start bno of right side entry */
976 	xfs_agblock_t	gtbnoa;		/* aligned ... */
977 	xfs_extlen_t	gtdiff;		/* difference to right side entry */
978 	xfs_extlen_t	gtlen;		/* length of right side entry */
979 	xfs_extlen_t	gtlena;		/* aligned ... */
980 	xfs_agblock_t	gtnew;		/* useful start bno of right side */
981 	int		error;		/* error code */
982 	int		i;		/* result code, temporary */
983 	int		j;		/* result code, temporary */
984 	xfs_agblock_t	ltbno;		/* start bno of left side entry */
985 	xfs_agblock_t	ltbnoa;		/* aligned ... */
986 	xfs_extlen_t	ltdiff;		/* difference to left side entry */
987 	xfs_extlen_t	ltlen;		/* length of left side entry */
988 	xfs_extlen_t	ltlena;		/* aligned ... */
989 	xfs_agblock_t	ltnew;		/* useful start bno of left side */
990 	xfs_extlen_t	rlen;		/* length of returned extent */
991 	int		forced = 0;
992 #ifdef DEBUG
993 	/*
994 	 * Randomly don't execute the first algorithm.
995 	 */
996 	int		dofirst;	/* set to do first algorithm */
997 
998 	dofirst = prandom_u32() & 1;
999 #endif
1000 
1001 	/* handle unitialized agbno range so caller doesn't have to */
1002 	if (!args->min_agbno && !args->max_agbno)
1003 		args->max_agbno = args->mp->m_sb.sb_agblocks - 1;
1004 	ASSERT(args->min_agbno <= args->max_agbno);
1005 
1006 	/* clamp agbno to the range if it's outside */
1007 	if (args->agbno < args->min_agbno)
1008 		args->agbno = args->min_agbno;
1009 	if (args->agbno > args->max_agbno)
1010 		args->agbno = args->max_agbno;
1011 
1012 restart:
1013 	bno_cur_lt = NULL;
1014 	bno_cur_gt = NULL;
1015 	ltlen = 0;
1016 	gtlena = 0;
1017 	ltlena = 0;
1018 
1019 	/*
1020 	 * Get a cursor for the by-size btree.
1021 	 */
1022 	cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1023 		args->agno, XFS_BTNUM_CNT);
1024 
1025 	/*
1026 	 * See if there are any free extents as big as maxlen.
1027 	 */
1028 	if ((error = xfs_alloc_lookup_ge(cnt_cur, 0, args->maxlen, &i)))
1029 		goto error0;
1030 	/*
1031 	 * If none, then pick up the last entry in the tree unless the
1032 	 * tree is empty.
1033 	 */
1034 	if (!i) {
1035 		if ((error = xfs_alloc_ag_vextent_small(args, cnt_cur, &ltbno,
1036 				&ltlen, &i)))
1037 			goto error0;
1038 		if (i == 0 || ltlen == 0) {
1039 			xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1040 			trace_xfs_alloc_near_noentry(args);
1041 			return 0;
1042 		}
1043 		ASSERT(i == 1);
1044 	}
1045 	args->wasfromfl = 0;
1046 
1047 	/*
1048 	 * First algorithm.
1049 	 * If the requested extent is large wrt the freespaces available
1050 	 * in this a.g., then the cursor will be pointing to a btree entry
1051 	 * near the right edge of the tree.  If it's in the last btree leaf
1052 	 * block, then we just examine all the entries in that block
1053 	 * that are big enough, and pick the best one.
1054 	 * This is written as a while loop so we can break out of it,
1055 	 * but we never loop back to the top.
1056 	 */
1057 	while (xfs_btree_islastblock(cnt_cur, 0)) {
1058 		xfs_extlen_t	bdiff;
1059 		int		besti=0;
1060 		xfs_extlen_t	blen=0;
1061 		xfs_agblock_t	bnew=0;
1062 
1063 #ifdef DEBUG
1064 		if (dofirst)
1065 			break;
1066 #endif
1067 		/*
1068 		 * Start from the entry that lookup found, sequence through
1069 		 * all larger free blocks.  If we're actually pointing at a
1070 		 * record smaller than maxlen, go to the start of this block,
1071 		 * and skip all those smaller than minlen.
1072 		 */
1073 		if (ltlen || args->alignment > 1) {
1074 			cnt_cur->bc_ptrs[0] = 1;
1075 			do {
1076 				if ((error = xfs_alloc_get_rec(cnt_cur, &ltbno,
1077 						&ltlen, &i)))
1078 					goto error0;
1079 				XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1080 				if (ltlen >= args->minlen)
1081 					break;
1082 				if ((error = xfs_btree_increment(cnt_cur, 0, &i)))
1083 					goto error0;
1084 			} while (i);
1085 			ASSERT(ltlen >= args->minlen);
1086 			if (!i)
1087 				break;
1088 		}
1089 		i = cnt_cur->bc_ptrs[0];
1090 		for (j = 1, blen = 0, bdiff = 0;
1091 		     !error && j && (blen < args->maxlen || bdiff > 0);
1092 		     error = xfs_btree_increment(cnt_cur, 0, &j)) {
1093 			/*
1094 			 * For each entry, decide if it's better than
1095 			 * the previous best entry.
1096 			 */
1097 			if ((error = xfs_alloc_get_rec(cnt_cur, &ltbno, &ltlen, &i)))
1098 				goto error0;
1099 			XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1100 			xfs_alloc_compute_aligned(args, ltbno, ltlen,
1101 						  &ltbnoa, &ltlena);
1102 			if (ltlena < args->minlen)
1103 				continue;
1104 			if (ltbnoa < args->min_agbno || ltbnoa > args->max_agbno)
1105 				continue;
1106 			args->len = XFS_EXTLEN_MIN(ltlena, args->maxlen);
1107 			xfs_alloc_fix_len(args);
1108 			ASSERT(args->len >= args->minlen);
1109 			if (args->len < blen)
1110 				continue;
1111 			ltdiff = xfs_alloc_compute_diff(args->agbno, args->len,
1112 				args->alignment, args->datatype, ltbnoa,
1113 				ltlena, &ltnew);
1114 			if (ltnew != NULLAGBLOCK &&
1115 			    (args->len > blen || ltdiff < bdiff)) {
1116 				bdiff = ltdiff;
1117 				bnew = ltnew;
1118 				blen = args->len;
1119 				besti = cnt_cur->bc_ptrs[0];
1120 			}
1121 		}
1122 		/*
1123 		 * It didn't work.  We COULD be in a case where
1124 		 * there's a good record somewhere, so try again.
1125 		 */
1126 		if (blen == 0)
1127 			break;
1128 		/*
1129 		 * Point at the best entry, and retrieve it again.
1130 		 */
1131 		cnt_cur->bc_ptrs[0] = besti;
1132 		if ((error = xfs_alloc_get_rec(cnt_cur, &ltbno, &ltlen, &i)))
1133 			goto error0;
1134 		XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1135 		ASSERT(ltbno + ltlen <= be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length));
1136 		args->len = blen;
1137 		if (!xfs_alloc_fix_minleft(args)) {
1138 			xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1139 			trace_xfs_alloc_near_nominleft(args);
1140 			return 0;
1141 		}
1142 		blen = args->len;
1143 		/*
1144 		 * We are allocating starting at bnew for blen blocks.
1145 		 */
1146 		args->agbno = bnew;
1147 		ASSERT(bnew >= ltbno);
1148 		ASSERT(bnew + blen <= ltbno + ltlen);
1149 		/*
1150 		 * Set up a cursor for the by-bno tree.
1151 		 */
1152 		bno_cur_lt = xfs_allocbt_init_cursor(args->mp, args->tp,
1153 			args->agbp, args->agno, XFS_BTNUM_BNO);
1154 		/*
1155 		 * Fix up the btree entries.
1156 		 */
1157 		if ((error = xfs_alloc_fixup_trees(cnt_cur, bno_cur_lt, ltbno,
1158 				ltlen, bnew, blen, XFSA_FIXUP_CNT_OK)))
1159 			goto error0;
1160 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1161 		xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_NOERROR);
1162 
1163 		trace_xfs_alloc_near_first(args);
1164 		return 0;
1165 	}
1166 	/*
1167 	 * Second algorithm.
1168 	 * Search in the by-bno tree to the left and to the right
1169 	 * simultaneously, until in each case we find a space big enough,
1170 	 * or run into the edge of the tree.  When we run into the edge,
1171 	 * we deallocate that cursor.
1172 	 * If both searches succeed, we compare the two spaces and pick
1173 	 * the better one.
1174 	 * With alignment, it's possible for both to fail; the upper
1175 	 * level algorithm that picks allocation groups for allocations
1176 	 * is not supposed to do this.
1177 	 */
1178 	/*
1179 	 * Allocate and initialize the cursor for the leftward search.
1180 	 */
1181 	bno_cur_lt = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1182 		args->agno, XFS_BTNUM_BNO);
1183 	/*
1184 	 * Lookup <= bno to find the leftward search's starting point.
1185 	 */
1186 	if ((error = xfs_alloc_lookup_le(bno_cur_lt, args->agbno, args->maxlen, &i)))
1187 		goto error0;
1188 	if (!i) {
1189 		/*
1190 		 * Didn't find anything; use this cursor for the rightward
1191 		 * search.
1192 		 */
1193 		bno_cur_gt = bno_cur_lt;
1194 		bno_cur_lt = NULL;
1195 	}
1196 	/*
1197 	 * Found something.  Duplicate the cursor for the rightward search.
1198 	 */
1199 	else if ((error = xfs_btree_dup_cursor(bno_cur_lt, &bno_cur_gt)))
1200 		goto error0;
1201 	/*
1202 	 * Increment the cursor, so we will point at the entry just right
1203 	 * of the leftward entry if any, or to the leftmost entry.
1204 	 */
1205 	if ((error = xfs_btree_increment(bno_cur_gt, 0, &i)))
1206 		goto error0;
1207 	if (!i) {
1208 		/*
1209 		 * It failed, there are no rightward entries.
1210 		 */
1211 		xfs_btree_del_cursor(bno_cur_gt, XFS_BTREE_NOERROR);
1212 		bno_cur_gt = NULL;
1213 	}
1214 	/*
1215 	 * Loop going left with the leftward cursor, right with the
1216 	 * rightward cursor, until either both directions give up or
1217 	 * we find an entry at least as big as minlen.
1218 	 */
1219 	do {
1220 		if (bno_cur_lt) {
1221 			if ((error = xfs_alloc_get_rec(bno_cur_lt, &ltbno, &ltlen, &i)))
1222 				goto error0;
1223 			XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1224 			xfs_alloc_compute_aligned(args, ltbno, ltlen,
1225 						  &ltbnoa, &ltlena);
1226 			if (ltlena >= args->minlen && ltbnoa >= args->min_agbno)
1227 				break;
1228 			if ((error = xfs_btree_decrement(bno_cur_lt, 0, &i)))
1229 				goto error0;
1230 			if (!i || ltbnoa < args->min_agbno) {
1231 				xfs_btree_del_cursor(bno_cur_lt,
1232 						     XFS_BTREE_NOERROR);
1233 				bno_cur_lt = NULL;
1234 			}
1235 		}
1236 		if (bno_cur_gt) {
1237 			if ((error = xfs_alloc_get_rec(bno_cur_gt, &gtbno, &gtlen, &i)))
1238 				goto error0;
1239 			XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1240 			xfs_alloc_compute_aligned(args, gtbno, gtlen,
1241 						  &gtbnoa, &gtlena);
1242 			if (gtlena >= args->minlen && gtbnoa <= args->max_agbno)
1243 				break;
1244 			if ((error = xfs_btree_increment(bno_cur_gt, 0, &i)))
1245 				goto error0;
1246 			if (!i || gtbnoa > args->max_agbno) {
1247 				xfs_btree_del_cursor(bno_cur_gt,
1248 						     XFS_BTREE_NOERROR);
1249 				bno_cur_gt = NULL;
1250 			}
1251 		}
1252 	} while (bno_cur_lt || bno_cur_gt);
1253 
1254 	/*
1255 	 * Got both cursors still active, need to find better entry.
1256 	 */
1257 	if (bno_cur_lt && bno_cur_gt) {
1258 		if (ltlena >= args->minlen) {
1259 			/*
1260 			 * Left side is good, look for a right side entry.
1261 			 */
1262 			args->len = XFS_EXTLEN_MIN(ltlena, args->maxlen);
1263 			xfs_alloc_fix_len(args);
1264 			ltdiff = xfs_alloc_compute_diff(args->agbno, args->len,
1265 				args->alignment, args->datatype, ltbnoa,
1266 				ltlena, &ltnew);
1267 
1268 			error = xfs_alloc_find_best_extent(args,
1269 						&bno_cur_lt, &bno_cur_gt,
1270 						ltdiff, &gtbno, &gtlen,
1271 						&gtbnoa, &gtlena,
1272 						0 /* search right */);
1273 		} else {
1274 			ASSERT(gtlena >= args->minlen);
1275 
1276 			/*
1277 			 * Right side is good, look for a left side entry.
1278 			 */
1279 			args->len = XFS_EXTLEN_MIN(gtlena, args->maxlen);
1280 			xfs_alloc_fix_len(args);
1281 			gtdiff = xfs_alloc_compute_diff(args->agbno, args->len,
1282 				args->alignment, args->datatype, gtbnoa,
1283 				gtlena, &gtnew);
1284 
1285 			error = xfs_alloc_find_best_extent(args,
1286 						&bno_cur_gt, &bno_cur_lt,
1287 						gtdiff, &ltbno, &ltlen,
1288 						&ltbnoa, &ltlena,
1289 						1 /* search left */);
1290 		}
1291 
1292 		if (error)
1293 			goto error0;
1294 	}
1295 
1296 	/*
1297 	 * If we couldn't get anything, give up.
1298 	 */
1299 	if (bno_cur_lt == NULL && bno_cur_gt == NULL) {
1300 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1301 
1302 		if (!forced++) {
1303 			trace_xfs_alloc_near_busy(args);
1304 			xfs_log_force(args->mp, XFS_LOG_SYNC);
1305 			goto restart;
1306 		}
1307 		trace_xfs_alloc_size_neither(args);
1308 		args->agbno = NULLAGBLOCK;
1309 		return 0;
1310 	}
1311 
1312 	/*
1313 	 * At this point we have selected a freespace entry, either to the
1314 	 * left or to the right.  If it's on the right, copy all the
1315 	 * useful variables to the "left" set so we only have one
1316 	 * copy of this code.
1317 	 */
1318 	if (bno_cur_gt) {
1319 		bno_cur_lt = bno_cur_gt;
1320 		bno_cur_gt = NULL;
1321 		ltbno = gtbno;
1322 		ltbnoa = gtbnoa;
1323 		ltlen = gtlen;
1324 		ltlena = gtlena;
1325 		j = 1;
1326 	} else
1327 		j = 0;
1328 
1329 	/*
1330 	 * Fix up the length and compute the useful address.
1331 	 */
1332 	args->len = XFS_EXTLEN_MIN(ltlena, args->maxlen);
1333 	xfs_alloc_fix_len(args);
1334 	if (!xfs_alloc_fix_minleft(args)) {
1335 		trace_xfs_alloc_near_nominleft(args);
1336 		xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_NOERROR);
1337 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1338 		return 0;
1339 	}
1340 	rlen = args->len;
1341 	(void)xfs_alloc_compute_diff(args->agbno, rlen, args->alignment,
1342 				     args->datatype, ltbnoa, ltlena, &ltnew);
1343 	ASSERT(ltnew >= ltbno);
1344 	ASSERT(ltnew + rlen <= ltbnoa + ltlena);
1345 	ASSERT(ltnew + rlen <= be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length));
1346 	ASSERT(ltnew >= args->min_agbno && ltnew <= args->max_agbno);
1347 	args->agbno = ltnew;
1348 
1349 	if ((error = xfs_alloc_fixup_trees(cnt_cur, bno_cur_lt, ltbno, ltlen,
1350 			ltnew, rlen, XFSA_FIXUP_BNO_OK)))
1351 		goto error0;
1352 
1353 	if (j)
1354 		trace_xfs_alloc_near_greater(args);
1355 	else
1356 		trace_xfs_alloc_near_lesser(args);
1357 
1358 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1359 	xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_NOERROR);
1360 	return 0;
1361 
1362  error0:
1363 	trace_xfs_alloc_near_error(args);
1364 	if (cnt_cur != NULL)
1365 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1366 	if (bno_cur_lt != NULL)
1367 		xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_ERROR);
1368 	if (bno_cur_gt != NULL)
1369 		xfs_btree_del_cursor(bno_cur_gt, XFS_BTREE_ERROR);
1370 	return error;
1371 }
1372 
1373 /*
1374  * Allocate a variable extent anywhere in the allocation group agno.
1375  * Extent's length (returned in len) will be between minlen and maxlen,
1376  * and of the form k * prod + mod unless there's nothing that large.
1377  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
1378  */
1379 STATIC int				/* error */
1380 xfs_alloc_ag_vextent_size(
1381 	xfs_alloc_arg_t	*args)		/* allocation argument structure */
1382 {
1383 	xfs_btree_cur_t	*bno_cur;	/* cursor for bno btree */
1384 	xfs_btree_cur_t	*cnt_cur;	/* cursor for cnt btree */
1385 	int		error;		/* error result */
1386 	xfs_agblock_t	fbno;		/* start of found freespace */
1387 	xfs_extlen_t	flen;		/* length of found freespace */
1388 	int		i;		/* temp status variable */
1389 	xfs_agblock_t	rbno;		/* returned block number */
1390 	xfs_extlen_t	rlen;		/* length of returned extent */
1391 	int		forced = 0;
1392 
1393 restart:
1394 	/*
1395 	 * Allocate and initialize a cursor for the by-size btree.
1396 	 */
1397 	cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1398 		args->agno, XFS_BTNUM_CNT);
1399 	bno_cur = NULL;
1400 
1401 	/*
1402 	 * Look for an entry >= maxlen+alignment-1 blocks.
1403 	 */
1404 	if ((error = xfs_alloc_lookup_ge(cnt_cur, 0,
1405 			args->maxlen + args->alignment - 1, &i)))
1406 		goto error0;
1407 
1408 	/*
1409 	 * If none or we have busy extents that we cannot allocate from, then
1410 	 * we have to settle for a smaller extent. In the case that there are
1411 	 * no large extents, this will return the last entry in the tree unless
1412 	 * the tree is empty. In the case that there are only busy large
1413 	 * extents, this will return the largest small extent unless there
1414 	 * are no smaller extents available.
1415 	 */
1416 	if (!i || forced > 1) {
1417 		error = xfs_alloc_ag_vextent_small(args, cnt_cur,
1418 						   &fbno, &flen, &i);
1419 		if (error)
1420 			goto error0;
1421 		if (i == 0 || flen == 0) {
1422 			xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1423 			trace_xfs_alloc_size_noentry(args);
1424 			return 0;
1425 		}
1426 		ASSERT(i == 1);
1427 		xfs_alloc_compute_aligned(args, fbno, flen, &rbno, &rlen);
1428 	} else {
1429 		/*
1430 		 * Search for a non-busy extent that is large enough.
1431 		 * If we are at low space, don't check, or if we fall of
1432 		 * the end of the btree, turn off the busy check and
1433 		 * restart.
1434 		 */
1435 		for (;;) {
1436 			error = xfs_alloc_get_rec(cnt_cur, &fbno, &flen, &i);
1437 			if (error)
1438 				goto error0;
1439 			XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1440 
1441 			xfs_alloc_compute_aligned(args, fbno, flen,
1442 						  &rbno, &rlen);
1443 
1444 			if (rlen >= args->maxlen)
1445 				break;
1446 
1447 			error = xfs_btree_increment(cnt_cur, 0, &i);
1448 			if (error)
1449 				goto error0;
1450 			if (i == 0) {
1451 				/*
1452 				 * Our only valid extents must have been busy.
1453 				 * Make it unbusy by forcing the log out and
1454 				 * retrying. If we've been here before, forcing
1455 				 * the log isn't making the extents available,
1456 				 * which means they have probably been freed in
1457 				 * this transaction.  In that case, we have to
1458 				 * give up on them and we'll attempt a minlen
1459 				 * allocation the next time around.
1460 				 */
1461 				xfs_btree_del_cursor(cnt_cur,
1462 						     XFS_BTREE_NOERROR);
1463 				trace_xfs_alloc_size_busy(args);
1464 				if (!forced++)
1465 					xfs_log_force(args->mp, XFS_LOG_SYNC);
1466 				goto restart;
1467 			}
1468 		}
1469 	}
1470 
1471 	/*
1472 	 * In the first case above, we got the last entry in the
1473 	 * by-size btree.  Now we check to see if the space hits maxlen
1474 	 * once aligned; if not, we search left for something better.
1475 	 * This can't happen in the second case above.
1476 	 */
1477 	rlen = XFS_EXTLEN_MIN(args->maxlen, rlen);
1478 	XFS_WANT_CORRUPTED_GOTO(args->mp, rlen == 0 ||
1479 			(rlen <= flen && rbno + rlen <= fbno + flen), error0);
1480 	if (rlen < args->maxlen) {
1481 		xfs_agblock_t	bestfbno;
1482 		xfs_extlen_t	bestflen;
1483 		xfs_agblock_t	bestrbno;
1484 		xfs_extlen_t	bestrlen;
1485 
1486 		bestrlen = rlen;
1487 		bestrbno = rbno;
1488 		bestflen = flen;
1489 		bestfbno = fbno;
1490 		for (;;) {
1491 			if ((error = xfs_btree_decrement(cnt_cur, 0, &i)))
1492 				goto error0;
1493 			if (i == 0)
1494 				break;
1495 			if ((error = xfs_alloc_get_rec(cnt_cur, &fbno, &flen,
1496 					&i)))
1497 				goto error0;
1498 			XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1499 			if (flen < bestrlen)
1500 				break;
1501 			xfs_alloc_compute_aligned(args, fbno, flen,
1502 						  &rbno, &rlen);
1503 			rlen = XFS_EXTLEN_MIN(args->maxlen, rlen);
1504 			XFS_WANT_CORRUPTED_GOTO(args->mp, rlen == 0 ||
1505 				(rlen <= flen && rbno + rlen <= fbno + flen),
1506 				error0);
1507 			if (rlen > bestrlen) {
1508 				bestrlen = rlen;
1509 				bestrbno = rbno;
1510 				bestflen = flen;
1511 				bestfbno = fbno;
1512 				if (rlen == args->maxlen)
1513 					break;
1514 			}
1515 		}
1516 		if ((error = xfs_alloc_lookup_eq(cnt_cur, bestfbno, bestflen,
1517 				&i)))
1518 			goto error0;
1519 		XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1520 		rlen = bestrlen;
1521 		rbno = bestrbno;
1522 		flen = bestflen;
1523 		fbno = bestfbno;
1524 	}
1525 	args->wasfromfl = 0;
1526 	/*
1527 	 * Fix up the length.
1528 	 */
1529 	args->len = rlen;
1530 	if (rlen < args->minlen) {
1531 		if (!forced++) {
1532 			xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1533 			trace_xfs_alloc_size_busy(args);
1534 			xfs_log_force(args->mp, XFS_LOG_SYNC);
1535 			goto restart;
1536 		}
1537 		goto out_nominleft;
1538 	}
1539 	xfs_alloc_fix_len(args);
1540 
1541 	if (!xfs_alloc_fix_minleft(args))
1542 		goto out_nominleft;
1543 	rlen = args->len;
1544 	XFS_WANT_CORRUPTED_GOTO(args->mp, rlen <= flen, error0);
1545 	/*
1546 	 * Allocate and initialize a cursor for the by-block tree.
1547 	 */
1548 	bno_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1549 		args->agno, XFS_BTNUM_BNO);
1550 	if ((error = xfs_alloc_fixup_trees(cnt_cur, bno_cur, fbno, flen,
1551 			rbno, rlen, XFSA_FIXUP_CNT_OK)))
1552 		goto error0;
1553 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1554 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
1555 	cnt_cur = bno_cur = NULL;
1556 	args->len = rlen;
1557 	args->agbno = rbno;
1558 	XFS_WANT_CORRUPTED_GOTO(args->mp,
1559 		args->agbno + args->len <=
1560 			be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length),
1561 		error0);
1562 	trace_xfs_alloc_size_done(args);
1563 	return 0;
1564 
1565 error0:
1566 	trace_xfs_alloc_size_error(args);
1567 	if (cnt_cur)
1568 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1569 	if (bno_cur)
1570 		xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
1571 	return error;
1572 
1573 out_nominleft:
1574 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1575 	trace_xfs_alloc_size_nominleft(args);
1576 	args->agbno = NULLAGBLOCK;
1577 	return 0;
1578 }
1579 
1580 /*
1581  * Deal with the case where only small freespaces remain.
1582  * Either return the contents of the last freespace record,
1583  * or allocate space from the freelist if there is nothing in the tree.
1584  */
1585 STATIC int			/* error */
1586 xfs_alloc_ag_vextent_small(
1587 	xfs_alloc_arg_t	*args,	/* allocation argument structure */
1588 	xfs_btree_cur_t	*ccur,	/* by-size cursor */
1589 	xfs_agblock_t	*fbnop,	/* result block number */
1590 	xfs_extlen_t	*flenp,	/* result length */
1591 	int		*stat)	/* status: 0-freelist, 1-normal/none */
1592 {
1593 	struct xfs_owner_info	oinfo;
1594 	struct xfs_perag	*pag;
1595 	int		error;
1596 	xfs_agblock_t	fbno;
1597 	xfs_extlen_t	flen;
1598 	int		i;
1599 
1600 	if ((error = xfs_btree_decrement(ccur, 0, &i)))
1601 		goto error0;
1602 	if (i) {
1603 		if ((error = xfs_alloc_get_rec(ccur, &fbno, &flen, &i)))
1604 			goto error0;
1605 		XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1606 	}
1607 	/*
1608 	 * Nothing in the btree, try the freelist.  Make sure
1609 	 * to respect minleft even when pulling from the
1610 	 * freelist.
1611 	 */
1612 	else if (args->minlen == 1 && args->alignment == 1 &&
1613 		 args->resv != XFS_AG_RESV_AGFL &&
1614 		 (be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_flcount)
1615 		  > args->minleft)) {
1616 		error = xfs_alloc_get_freelist(args->tp, args->agbp, &fbno, 0);
1617 		if (error)
1618 			goto error0;
1619 		if (fbno != NULLAGBLOCK) {
1620 			xfs_extent_busy_reuse(args->mp, args->agno, fbno, 1,
1621 			      xfs_alloc_allow_busy_reuse(args->datatype));
1622 
1623 			if (xfs_alloc_is_userdata(args->datatype)) {
1624 				xfs_buf_t	*bp;
1625 
1626 				bp = xfs_btree_get_bufs(args->mp, args->tp,
1627 					args->agno, fbno, 0);
1628 				xfs_trans_binval(args->tp, bp);
1629 			}
1630 			args->len = 1;
1631 			args->agbno = fbno;
1632 			XFS_WANT_CORRUPTED_GOTO(args->mp,
1633 				args->agbno + args->len <=
1634 				be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length),
1635 				error0);
1636 			args->wasfromfl = 1;
1637 			trace_xfs_alloc_small_freelist(args);
1638 
1639 			/*
1640 			 * If we're feeding an AGFL block to something that
1641 			 * doesn't live in the free space, we need to clear
1642 			 * out the OWN_AG rmap and add the block back to
1643 			 * the AGFL per-AG reservation.
1644 			 */
1645 			xfs_rmap_ag_owner(&oinfo, XFS_RMAP_OWN_AG);
1646 			error = xfs_rmap_free(args->tp, args->agbp, args->agno,
1647 					fbno, 1, &oinfo);
1648 			if (error)
1649 				goto error0;
1650 			pag = xfs_perag_get(args->mp, args->agno);
1651 			xfs_ag_resv_free_extent(pag, XFS_AG_RESV_AGFL,
1652 					args->tp, 1);
1653 			xfs_perag_put(pag);
1654 
1655 			*stat = 0;
1656 			return 0;
1657 		}
1658 		/*
1659 		 * Nothing in the freelist.
1660 		 */
1661 		else
1662 			flen = 0;
1663 	}
1664 	/*
1665 	 * Can't allocate from the freelist for some reason.
1666 	 */
1667 	else {
1668 		fbno = NULLAGBLOCK;
1669 		flen = 0;
1670 	}
1671 	/*
1672 	 * Can't do the allocation, give up.
1673 	 */
1674 	if (flen < args->minlen) {
1675 		args->agbno = NULLAGBLOCK;
1676 		trace_xfs_alloc_small_notenough(args);
1677 		flen = 0;
1678 	}
1679 	*fbnop = fbno;
1680 	*flenp = flen;
1681 	*stat = 1;
1682 	trace_xfs_alloc_small_done(args);
1683 	return 0;
1684 
1685 error0:
1686 	trace_xfs_alloc_small_error(args);
1687 	return error;
1688 }
1689 
1690 /*
1691  * Free the extent starting at agno/bno for length.
1692  */
1693 STATIC int
1694 xfs_free_ag_extent(
1695 	xfs_trans_t		*tp,
1696 	xfs_buf_t		*agbp,
1697 	xfs_agnumber_t		agno,
1698 	xfs_agblock_t		bno,
1699 	xfs_extlen_t		len,
1700 	struct xfs_owner_info	*oinfo,
1701 	enum xfs_ag_resv_type	type)
1702 {
1703 	xfs_btree_cur_t	*bno_cur;	/* cursor for by-block btree */
1704 	xfs_btree_cur_t	*cnt_cur;	/* cursor for by-size btree */
1705 	int		error;		/* error return value */
1706 	xfs_agblock_t	gtbno;		/* start of right neighbor block */
1707 	xfs_extlen_t	gtlen;		/* length of right neighbor block */
1708 	int		haveleft;	/* have a left neighbor block */
1709 	int		haveright;	/* have a right neighbor block */
1710 	int		i;		/* temp, result code */
1711 	xfs_agblock_t	ltbno;		/* start of left neighbor block */
1712 	xfs_extlen_t	ltlen;		/* length of left neighbor block */
1713 	xfs_mount_t	*mp;		/* mount point struct for filesystem */
1714 	xfs_agblock_t	nbno;		/* new starting block of freespace */
1715 	xfs_extlen_t	nlen;		/* new length of freespace */
1716 	xfs_perag_t	*pag;		/* per allocation group data */
1717 
1718 	bno_cur = cnt_cur = NULL;
1719 	mp = tp->t_mountp;
1720 
1721 	if (oinfo->oi_owner != XFS_RMAP_OWN_UNKNOWN) {
1722 		error = xfs_rmap_free(tp, agbp, agno, bno, len, oinfo);
1723 		if (error)
1724 			goto error0;
1725 	}
1726 
1727 	/*
1728 	 * Allocate and initialize a cursor for the by-block btree.
1729 	 */
1730 	bno_cur = xfs_allocbt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_BNO);
1731 	/*
1732 	 * Look for a neighboring block on the left (lower block numbers)
1733 	 * that is contiguous with this space.
1734 	 */
1735 	if ((error = xfs_alloc_lookup_le(bno_cur, bno, len, &haveleft)))
1736 		goto error0;
1737 	if (haveleft) {
1738 		/*
1739 		 * There is a block to our left.
1740 		 */
1741 		if ((error = xfs_alloc_get_rec(bno_cur, &ltbno, &ltlen, &i)))
1742 			goto error0;
1743 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1744 		/*
1745 		 * It's not contiguous, though.
1746 		 */
1747 		if (ltbno + ltlen < bno)
1748 			haveleft = 0;
1749 		else {
1750 			/*
1751 			 * If this failure happens the request to free this
1752 			 * space was invalid, it's (partly) already free.
1753 			 * Very bad.
1754 			 */
1755 			XFS_WANT_CORRUPTED_GOTO(mp,
1756 						ltbno + ltlen <= bno, error0);
1757 		}
1758 	}
1759 	/*
1760 	 * Look for a neighboring block on the right (higher block numbers)
1761 	 * that is contiguous with this space.
1762 	 */
1763 	if ((error = xfs_btree_increment(bno_cur, 0, &haveright)))
1764 		goto error0;
1765 	if (haveright) {
1766 		/*
1767 		 * There is a block to our right.
1768 		 */
1769 		if ((error = xfs_alloc_get_rec(bno_cur, &gtbno, &gtlen, &i)))
1770 			goto error0;
1771 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1772 		/*
1773 		 * It's not contiguous, though.
1774 		 */
1775 		if (bno + len < gtbno)
1776 			haveright = 0;
1777 		else {
1778 			/*
1779 			 * If this failure happens the request to free this
1780 			 * space was invalid, it's (partly) already free.
1781 			 * Very bad.
1782 			 */
1783 			XFS_WANT_CORRUPTED_GOTO(mp, gtbno >= bno + len, error0);
1784 		}
1785 	}
1786 	/*
1787 	 * Now allocate and initialize a cursor for the by-size tree.
1788 	 */
1789 	cnt_cur = xfs_allocbt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_CNT);
1790 	/*
1791 	 * Have both left and right contiguous neighbors.
1792 	 * Merge all three into a single free block.
1793 	 */
1794 	if (haveleft && haveright) {
1795 		/*
1796 		 * Delete the old by-size entry on the left.
1797 		 */
1798 		if ((error = xfs_alloc_lookup_eq(cnt_cur, ltbno, ltlen, &i)))
1799 			goto error0;
1800 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1801 		if ((error = xfs_btree_delete(cnt_cur, &i)))
1802 			goto error0;
1803 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1804 		/*
1805 		 * Delete the old by-size entry on the right.
1806 		 */
1807 		if ((error = xfs_alloc_lookup_eq(cnt_cur, gtbno, gtlen, &i)))
1808 			goto error0;
1809 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1810 		if ((error = xfs_btree_delete(cnt_cur, &i)))
1811 			goto error0;
1812 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1813 		/*
1814 		 * Delete the old by-block entry for the right block.
1815 		 */
1816 		if ((error = xfs_btree_delete(bno_cur, &i)))
1817 			goto error0;
1818 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1819 		/*
1820 		 * Move the by-block cursor back to the left neighbor.
1821 		 */
1822 		if ((error = xfs_btree_decrement(bno_cur, 0, &i)))
1823 			goto error0;
1824 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1825 #ifdef DEBUG
1826 		/*
1827 		 * Check that this is the right record: delete didn't
1828 		 * mangle the cursor.
1829 		 */
1830 		{
1831 			xfs_agblock_t	xxbno;
1832 			xfs_extlen_t	xxlen;
1833 
1834 			if ((error = xfs_alloc_get_rec(bno_cur, &xxbno, &xxlen,
1835 					&i)))
1836 				goto error0;
1837 			XFS_WANT_CORRUPTED_GOTO(mp,
1838 				i == 1 && xxbno == ltbno && xxlen == ltlen,
1839 				error0);
1840 		}
1841 #endif
1842 		/*
1843 		 * Update remaining by-block entry to the new, joined block.
1844 		 */
1845 		nbno = ltbno;
1846 		nlen = len + ltlen + gtlen;
1847 		if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
1848 			goto error0;
1849 	}
1850 	/*
1851 	 * Have only a left contiguous neighbor.
1852 	 * Merge it together with the new freespace.
1853 	 */
1854 	else if (haveleft) {
1855 		/*
1856 		 * Delete the old by-size entry on the left.
1857 		 */
1858 		if ((error = xfs_alloc_lookup_eq(cnt_cur, ltbno, ltlen, &i)))
1859 			goto error0;
1860 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1861 		if ((error = xfs_btree_delete(cnt_cur, &i)))
1862 			goto error0;
1863 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1864 		/*
1865 		 * Back up the by-block cursor to the left neighbor, and
1866 		 * update its length.
1867 		 */
1868 		if ((error = xfs_btree_decrement(bno_cur, 0, &i)))
1869 			goto error0;
1870 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1871 		nbno = ltbno;
1872 		nlen = len + ltlen;
1873 		if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
1874 			goto error0;
1875 	}
1876 	/*
1877 	 * Have only a right contiguous neighbor.
1878 	 * Merge it together with the new freespace.
1879 	 */
1880 	else if (haveright) {
1881 		/*
1882 		 * Delete the old by-size entry on the right.
1883 		 */
1884 		if ((error = xfs_alloc_lookup_eq(cnt_cur, gtbno, gtlen, &i)))
1885 			goto error0;
1886 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1887 		if ((error = xfs_btree_delete(cnt_cur, &i)))
1888 			goto error0;
1889 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1890 		/*
1891 		 * Update the starting block and length of the right
1892 		 * neighbor in the by-block tree.
1893 		 */
1894 		nbno = bno;
1895 		nlen = len + gtlen;
1896 		if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
1897 			goto error0;
1898 	}
1899 	/*
1900 	 * No contiguous neighbors.
1901 	 * Insert the new freespace into the by-block tree.
1902 	 */
1903 	else {
1904 		nbno = bno;
1905 		nlen = len;
1906 		if ((error = xfs_btree_insert(bno_cur, &i)))
1907 			goto error0;
1908 		XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1909 	}
1910 	xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
1911 	bno_cur = NULL;
1912 	/*
1913 	 * In all cases we need to insert the new freespace in the by-size tree.
1914 	 */
1915 	if ((error = xfs_alloc_lookup_eq(cnt_cur, nbno, nlen, &i)))
1916 		goto error0;
1917 	XFS_WANT_CORRUPTED_GOTO(mp, i == 0, error0);
1918 	if ((error = xfs_btree_insert(cnt_cur, &i)))
1919 		goto error0;
1920 	XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1921 	xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1922 	cnt_cur = NULL;
1923 
1924 	/*
1925 	 * Update the freespace totals in the ag and superblock.
1926 	 */
1927 	pag = xfs_perag_get(mp, agno);
1928 	error = xfs_alloc_update_counters(tp, pag, agbp, len);
1929 	xfs_ag_resv_free_extent(pag, type, tp, len);
1930 	xfs_perag_put(pag);
1931 	if (error)
1932 		goto error0;
1933 
1934 	XFS_STATS_INC(mp, xs_freex);
1935 	XFS_STATS_ADD(mp, xs_freeb, len);
1936 
1937 	trace_xfs_free_extent(mp, agno, bno, len, type == XFS_AG_RESV_AGFL,
1938 			haveleft, haveright);
1939 
1940 	return 0;
1941 
1942  error0:
1943 	trace_xfs_free_extent(mp, agno, bno, len, type == XFS_AG_RESV_AGFL,
1944 			-1, -1);
1945 	if (bno_cur)
1946 		xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
1947 	if (cnt_cur)
1948 		xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1949 	return error;
1950 }
1951 
1952 /*
1953  * Visible (exported) allocation/free functions.
1954  * Some of these are used just by xfs_alloc_btree.c and this file.
1955  */
1956 
1957 /*
1958  * Compute and fill in value of m_ag_maxlevels.
1959  */
1960 void
1961 xfs_alloc_compute_maxlevels(
1962 	xfs_mount_t	*mp)	/* file system mount structure */
1963 {
1964 	mp->m_ag_maxlevels = xfs_btree_compute_maxlevels(mp, mp->m_alloc_mnr,
1965 			(mp->m_sb.sb_agblocks + 1) / 2);
1966 }
1967 
1968 /*
1969  * Find the length of the longest extent in an AG.  The 'need' parameter
1970  * specifies how much space we're going to need for the AGFL and the
1971  * 'reserved' parameter tells us how many blocks in this AG are reserved for
1972  * other callers.
1973  */
1974 xfs_extlen_t
1975 xfs_alloc_longest_free_extent(
1976 	struct xfs_mount	*mp,
1977 	struct xfs_perag	*pag,
1978 	xfs_extlen_t		need,
1979 	xfs_extlen_t		reserved)
1980 {
1981 	xfs_extlen_t		delta = 0;
1982 
1983 	/*
1984 	 * If the AGFL needs a recharge, we'll have to subtract that from the
1985 	 * longest extent.
1986 	 */
1987 	if (need > pag->pagf_flcount)
1988 		delta = need - pag->pagf_flcount;
1989 
1990 	/*
1991 	 * If we cannot maintain others' reservations with space from the
1992 	 * not-longest freesp extents, we'll have to subtract /that/ from
1993 	 * the longest extent too.
1994 	 */
1995 	if (pag->pagf_freeblks - pag->pagf_longest < reserved)
1996 		delta += reserved - (pag->pagf_freeblks - pag->pagf_longest);
1997 
1998 	/*
1999 	 * If the longest extent is long enough to satisfy all the
2000 	 * reservations and AGFL rules in place, we can return this extent.
2001 	 */
2002 	if (pag->pagf_longest > delta)
2003 		return pag->pagf_longest - delta;
2004 
2005 	/* Otherwise, let the caller try for 1 block if there's space. */
2006 	return pag->pagf_flcount > 0 || pag->pagf_longest > 0;
2007 }
2008 
2009 unsigned int
2010 xfs_alloc_min_freelist(
2011 	struct xfs_mount	*mp,
2012 	struct xfs_perag	*pag)
2013 {
2014 	unsigned int		min_free;
2015 
2016 	/* space needed by-bno freespace btree */
2017 	min_free = min_t(unsigned int, pag->pagf_levels[XFS_BTNUM_BNOi] + 1,
2018 				       mp->m_ag_maxlevels);
2019 	/* space needed by-size freespace btree */
2020 	min_free += min_t(unsigned int, pag->pagf_levels[XFS_BTNUM_CNTi] + 1,
2021 				       mp->m_ag_maxlevels);
2022 	/* space needed reverse mapping used space btree */
2023 	if (xfs_sb_version_hasrmapbt(&mp->m_sb))
2024 		min_free += min_t(unsigned int,
2025 				  pag->pagf_levels[XFS_BTNUM_RMAPi] + 1,
2026 				  mp->m_rmap_maxlevels);
2027 
2028 	return min_free;
2029 }
2030 
2031 /*
2032  * Check if the operation we are fixing up the freelist for should go ahead or
2033  * not. If we are freeing blocks, we always allow it, otherwise the allocation
2034  * is dependent on whether the size and shape of free space available will
2035  * permit the requested allocation to take place.
2036  */
2037 static bool
2038 xfs_alloc_space_available(
2039 	struct xfs_alloc_arg	*args,
2040 	xfs_extlen_t		min_free,
2041 	int			flags)
2042 {
2043 	struct xfs_perag	*pag = args->pag;
2044 	xfs_extlen_t		longest;
2045 	xfs_extlen_t		reservation; /* blocks that are still reserved */
2046 	int			available;
2047 
2048 	if (flags & XFS_ALLOC_FLAG_FREEING)
2049 		return true;
2050 
2051 	reservation = xfs_ag_resv_needed(pag, args->resv);
2052 
2053 	/* do we have enough contiguous free space for the allocation? */
2054 	longest = xfs_alloc_longest_free_extent(args->mp, pag, min_free,
2055 			reservation);
2056 	if ((args->minlen + args->alignment + args->minalignslop - 1) > longest)
2057 		return false;
2058 
2059 	/* do we have enough free space remaining for the allocation? */
2060 	available = (int)(pag->pagf_freeblks + pag->pagf_flcount -
2061 			  reservation - min_free - args->total);
2062 	if (available < (int)args->minleft || available <= 0)
2063 		return false;
2064 
2065 	return true;
2066 }
2067 
2068 /*
2069  * Decide whether to use this allocation group for this allocation.
2070  * If so, fix up the btree freelist's size.
2071  */
2072 int			/* error */
2073 xfs_alloc_fix_freelist(
2074 	struct xfs_alloc_arg	*args,	/* allocation argument structure */
2075 	int			flags)	/* XFS_ALLOC_FLAG_... */
2076 {
2077 	struct xfs_mount	*mp = args->mp;
2078 	struct xfs_perag	*pag = args->pag;
2079 	struct xfs_trans	*tp = args->tp;
2080 	struct xfs_buf		*agbp = NULL;
2081 	struct xfs_buf		*agflbp = NULL;
2082 	struct xfs_alloc_arg	targs;	/* local allocation arguments */
2083 	xfs_agblock_t		bno;	/* freelist block */
2084 	xfs_extlen_t		need;	/* total blocks needed in freelist */
2085 	int			error = 0;
2086 
2087 	if (!pag->pagf_init) {
2088 		error = xfs_alloc_read_agf(mp, tp, args->agno, flags, &agbp);
2089 		if (error)
2090 			goto out_no_agbp;
2091 		if (!pag->pagf_init) {
2092 			ASSERT(flags & XFS_ALLOC_FLAG_TRYLOCK);
2093 			ASSERT(!(flags & XFS_ALLOC_FLAG_FREEING));
2094 			goto out_agbp_relse;
2095 		}
2096 	}
2097 
2098 	/*
2099 	 * If this is a metadata preferred pag and we are user data then try
2100 	 * somewhere else if we are not being asked to try harder at this
2101 	 * point
2102 	 */
2103 	if (pag->pagf_metadata && xfs_alloc_is_userdata(args->datatype) &&
2104 	    (flags & XFS_ALLOC_FLAG_TRYLOCK)) {
2105 		ASSERT(!(flags & XFS_ALLOC_FLAG_FREEING));
2106 		goto out_agbp_relse;
2107 	}
2108 
2109 	need = xfs_alloc_min_freelist(mp, pag);
2110 	if (!xfs_alloc_space_available(args, need, flags))
2111 		goto out_agbp_relse;
2112 
2113 	/*
2114 	 * Get the a.g. freespace buffer.
2115 	 * Can fail if we're not blocking on locks, and it's held.
2116 	 */
2117 	if (!agbp) {
2118 		error = xfs_alloc_read_agf(mp, tp, args->agno, flags, &agbp);
2119 		if (error)
2120 			goto out_no_agbp;
2121 		if (!agbp) {
2122 			ASSERT(flags & XFS_ALLOC_FLAG_TRYLOCK);
2123 			ASSERT(!(flags & XFS_ALLOC_FLAG_FREEING));
2124 			goto out_no_agbp;
2125 		}
2126 	}
2127 
2128 	/* If there isn't enough total space or single-extent, reject it. */
2129 	need = xfs_alloc_min_freelist(mp, pag);
2130 	if (!xfs_alloc_space_available(args, need, flags))
2131 		goto out_agbp_relse;
2132 
2133 	/*
2134 	 * Make the freelist shorter if it's too long.
2135 	 *
2136 	 * Note that from this point onwards, we will always release the agf and
2137 	 * agfl buffers on error. This handles the case where we error out and
2138 	 * the buffers are clean or may not have been joined to the transaction
2139 	 * and hence need to be released manually. If they have been joined to
2140 	 * the transaction, then xfs_trans_brelse() will handle them
2141 	 * appropriately based on the recursion count and dirty state of the
2142 	 * buffer.
2143 	 *
2144 	 * XXX (dgc): When we have lots of free space, does this buy us
2145 	 * anything other than extra overhead when we need to put more blocks
2146 	 * back on the free list? Maybe we should only do this when space is
2147 	 * getting low or the AGFL is more than half full?
2148 	 *
2149 	 * The NOSHRINK flag prevents the AGFL from being shrunk if it's too
2150 	 * big; the NORMAP flag prevents AGFL expand/shrink operations from
2151 	 * updating the rmapbt.  Both flags are used in xfs_repair while we're
2152 	 * rebuilding the rmapbt, and neither are used by the kernel.  They're
2153 	 * both required to ensure that rmaps are correctly recorded for the
2154 	 * regenerated AGFL, bnobt, and cntbt.  See repair/phase5.c and
2155 	 * repair/rmap.c in xfsprogs for details.
2156 	 */
2157 	memset(&targs, 0, sizeof(targs));
2158 	if (flags & XFS_ALLOC_FLAG_NORMAP)
2159 		xfs_rmap_skip_owner_update(&targs.oinfo);
2160 	else
2161 		xfs_rmap_ag_owner(&targs.oinfo, XFS_RMAP_OWN_AG);
2162 	while (!(flags & XFS_ALLOC_FLAG_NOSHRINK) && pag->pagf_flcount > need) {
2163 		struct xfs_buf	*bp;
2164 
2165 		error = xfs_alloc_get_freelist(tp, agbp, &bno, 0);
2166 		if (error)
2167 			goto out_agbp_relse;
2168 		error = xfs_free_ag_extent(tp, agbp, args->agno, bno, 1,
2169 					   &targs.oinfo, XFS_AG_RESV_AGFL);
2170 		if (error)
2171 			goto out_agbp_relse;
2172 		bp = xfs_btree_get_bufs(mp, tp, args->agno, bno, 0);
2173 		xfs_trans_binval(tp, bp);
2174 	}
2175 
2176 	targs.tp = tp;
2177 	targs.mp = mp;
2178 	targs.agbp = agbp;
2179 	targs.agno = args->agno;
2180 	targs.alignment = targs.minlen = targs.prod = 1;
2181 	targs.type = XFS_ALLOCTYPE_THIS_AG;
2182 	targs.pag = pag;
2183 	error = xfs_alloc_read_agfl(mp, tp, targs.agno, &agflbp);
2184 	if (error)
2185 		goto out_agbp_relse;
2186 
2187 	/* Make the freelist longer if it's too short. */
2188 	while (pag->pagf_flcount < need) {
2189 		targs.agbno = 0;
2190 		targs.maxlen = need - pag->pagf_flcount;
2191 		targs.resv = XFS_AG_RESV_AGFL;
2192 
2193 		/* Allocate as many blocks as possible at once. */
2194 		error = xfs_alloc_ag_vextent(&targs);
2195 		if (error)
2196 			goto out_agflbp_relse;
2197 
2198 		/*
2199 		 * Stop if we run out.  Won't happen if callers are obeying
2200 		 * the restrictions correctly.  Can happen for free calls
2201 		 * on a completely full ag.
2202 		 */
2203 		if (targs.agbno == NULLAGBLOCK) {
2204 			if (flags & XFS_ALLOC_FLAG_FREEING)
2205 				break;
2206 			goto out_agflbp_relse;
2207 		}
2208 		/*
2209 		 * Put each allocated block on the list.
2210 		 */
2211 		for (bno = targs.agbno; bno < targs.agbno + targs.len; bno++) {
2212 			error = xfs_alloc_put_freelist(tp, agbp,
2213 							agflbp, bno, 0);
2214 			if (error)
2215 				goto out_agflbp_relse;
2216 		}
2217 	}
2218 	xfs_trans_brelse(tp, agflbp);
2219 	args->agbp = agbp;
2220 	return 0;
2221 
2222 out_agflbp_relse:
2223 	xfs_trans_brelse(tp, agflbp);
2224 out_agbp_relse:
2225 	if (agbp)
2226 		xfs_trans_brelse(tp, agbp);
2227 out_no_agbp:
2228 	args->agbp = NULL;
2229 	return error;
2230 }
2231 
2232 /*
2233  * Get a block from the freelist.
2234  * Returns with the buffer for the block gotten.
2235  */
2236 int				/* error */
2237 xfs_alloc_get_freelist(
2238 	xfs_trans_t	*tp,	/* transaction pointer */
2239 	xfs_buf_t	*agbp,	/* buffer containing the agf structure */
2240 	xfs_agblock_t	*bnop,	/* block address retrieved from freelist */
2241 	int		btreeblk) /* destination is a AGF btree */
2242 {
2243 	xfs_agf_t	*agf;	/* a.g. freespace structure */
2244 	xfs_buf_t	*agflbp;/* buffer for a.g. freelist structure */
2245 	xfs_agblock_t	bno;	/* block number returned */
2246 	__be32		*agfl_bno;
2247 	int		error;
2248 	int		logflags;
2249 	xfs_mount_t	*mp = tp->t_mountp;
2250 	xfs_perag_t	*pag;	/* per allocation group data */
2251 
2252 	/*
2253 	 * Freelist is empty, give up.
2254 	 */
2255 	agf = XFS_BUF_TO_AGF(agbp);
2256 	if (!agf->agf_flcount) {
2257 		*bnop = NULLAGBLOCK;
2258 		return 0;
2259 	}
2260 	/*
2261 	 * Read the array of free blocks.
2262 	 */
2263 	error = xfs_alloc_read_agfl(mp, tp, be32_to_cpu(agf->agf_seqno),
2264 				    &agflbp);
2265 	if (error)
2266 		return error;
2267 
2268 
2269 	/*
2270 	 * Get the block number and update the data structures.
2271 	 */
2272 	agfl_bno = XFS_BUF_TO_AGFL_BNO(mp, agflbp);
2273 	bno = be32_to_cpu(agfl_bno[be32_to_cpu(agf->agf_flfirst)]);
2274 	be32_add_cpu(&agf->agf_flfirst, 1);
2275 	xfs_trans_brelse(tp, agflbp);
2276 	if (be32_to_cpu(agf->agf_flfirst) == XFS_AGFL_SIZE(mp))
2277 		agf->agf_flfirst = 0;
2278 
2279 	pag = xfs_perag_get(mp, be32_to_cpu(agf->agf_seqno));
2280 	be32_add_cpu(&agf->agf_flcount, -1);
2281 	xfs_trans_agflist_delta(tp, -1);
2282 	pag->pagf_flcount--;
2283 	xfs_perag_put(pag);
2284 
2285 	logflags = XFS_AGF_FLFIRST | XFS_AGF_FLCOUNT;
2286 	if (btreeblk) {
2287 		be32_add_cpu(&agf->agf_btreeblks, 1);
2288 		pag->pagf_btreeblks++;
2289 		logflags |= XFS_AGF_BTREEBLKS;
2290 	}
2291 
2292 	xfs_alloc_log_agf(tp, agbp, logflags);
2293 	*bnop = bno;
2294 
2295 	return 0;
2296 }
2297 
2298 /*
2299  * Log the given fields from the agf structure.
2300  */
2301 void
2302 xfs_alloc_log_agf(
2303 	xfs_trans_t	*tp,	/* transaction pointer */
2304 	xfs_buf_t	*bp,	/* buffer for a.g. freelist header */
2305 	int		fields)	/* mask of fields to be logged (XFS_AGF_...) */
2306 {
2307 	int	first;		/* first byte offset */
2308 	int	last;		/* last byte offset */
2309 	static const short	offsets[] = {
2310 		offsetof(xfs_agf_t, agf_magicnum),
2311 		offsetof(xfs_agf_t, agf_versionnum),
2312 		offsetof(xfs_agf_t, agf_seqno),
2313 		offsetof(xfs_agf_t, agf_length),
2314 		offsetof(xfs_agf_t, agf_roots[0]),
2315 		offsetof(xfs_agf_t, agf_levels[0]),
2316 		offsetof(xfs_agf_t, agf_flfirst),
2317 		offsetof(xfs_agf_t, agf_fllast),
2318 		offsetof(xfs_agf_t, agf_flcount),
2319 		offsetof(xfs_agf_t, agf_freeblks),
2320 		offsetof(xfs_agf_t, agf_longest),
2321 		offsetof(xfs_agf_t, agf_btreeblks),
2322 		offsetof(xfs_agf_t, agf_uuid),
2323 		offsetof(xfs_agf_t, agf_rmap_blocks),
2324 		/* needed so that we don't log the whole rest of the structure: */
2325 		offsetof(xfs_agf_t, agf_spare64),
2326 		sizeof(xfs_agf_t)
2327 	};
2328 
2329 	trace_xfs_agf(tp->t_mountp, XFS_BUF_TO_AGF(bp), fields, _RET_IP_);
2330 
2331 	xfs_trans_buf_set_type(tp, bp, XFS_BLFT_AGF_BUF);
2332 
2333 	xfs_btree_offsets(fields, offsets, XFS_AGF_NUM_BITS, &first, &last);
2334 	xfs_trans_log_buf(tp, bp, (uint)first, (uint)last);
2335 }
2336 
2337 /*
2338  * Interface for inode allocation to force the pag data to be initialized.
2339  */
2340 int					/* error */
2341 xfs_alloc_pagf_init(
2342 	xfs_mount_t		*mp,	/* file system mount structure */
2343 	xfs_trans_t		*tp,	/* transaction pointer */
2344 	xfs_agnumber_t		agno,	/* allocation group number */
2345 	int			flags)	/* XFS_ALLOC_FLAGS_... */
2346 {
2347 	xfs_buf_t		*bp;
2348 	int			error;
2349 
2350 	if ((error = xfs_alloc_read_agf(mp, tp, agno, flags, &bp)))
2351 		return error;
2352 	if (bp)
2353 		xfs_trans_brelse(tp, bp);
2354 	return 0;
2355 }
2356 
2357 /*
2358  * Put the block on the freelist for the allocation group.
2359  */
2360 int					/* error */
2361 xfs_alloc_put_freelist(
2362 	xfs_trans_t		*tp,	/* transaction pointer */
2363 	xfs_buf_t		*agbp,	/* buffer for a.g. freelist header */
2364 	xfs_buf_t		*agflbp,/* buffer for a.g. free block array */
2365 	xfs_agblock_t		bno,	/* block being freed */
2366 	int			btreeblk) /* block came from a AGF btree */
2367 {
2368 	xfs_agf_t		*agf;	/* a.g. freespace structure */
2369 	__be32			*blockp;/* pointer to array entry */
2370 	int			error;
2371 	int			logflags;
2372 	xfs_mount_t		*mp;	/* mount structure */
2373 	xfs_perag_t		*pag;	/* per allocation group data */
2374 	__be32			*agfl_bno;
2375 	int			startoff;
2376 
2377 	agf = XFS_BUF_TO_AGF(agbp);
2378 	mp = tp->t_mountp;
2379 
2380 	if (!agflbp && (error = xfs_alloc_read_agfl(mp, tp,
2381 			be32_to_cpu(agf->agf_seqno), &agflbp)))
2382 		return error;
2383 	be32_add_cpu(&agf->agf_fllast, 1);
2384 	if (be32_to_cpu(agf->agf_fllast) == XFS_AGFL_SIZE(mp))
2385 		agf->agf_fllast = 0;
2386 
2387 	pag = xfs_perag_get(mp, be32_to_cpu(agf->agf_seqno));
2388 	be32_add_cpu(&agf->agf_flcount, 1);
2389 	xfs_trans_agflist_delta(tp, 1);
2390 	pag->pagf_flcount++;
2391 
2392 	logflags = XFS_AGF_FLLAST | XFS_AGF_FLCOUNT;
2393 	if (btreeblk) {
2394 		be32_add_cpu(&agf->agf_btreeblks, -1);
2395 		pag->pagf_btreeblks--;
2396 		logflags |= XFS_AGF_BTREEBLKS;
2397 	}
2398 	xfs_perag_put(pag);
2399 
2400 	xfs_alloc_log_agf(tp, agbp, logflags);
2401 
2402 	ASSERT(be32_to_cpu(agf->agf_flcount) <= XFS_AGFL_SIZE(mp));
2403 
2404 	agfl_bno = XFS_BUF_TO_AGFL_BNO(mp, agflbp);
2405 	blockp = &agfl_bno[be32_to_cpu(agf->agf_fllast)];
2406 	*blockp = cpu_to_be32(bno);
2407 	startoff = (char *)blockp - (char *)agflbp->b_addr;
2408 
2409 	xfs_alloc_log_agf(tp, agbp, logflags);
2410 
2411 	xfs_trans_buf_set_type(tp, agflbp, XFS_BLFT_AGFL_BUF);
2412 	xfs_trans_log_buf(tp, agflbp, startoff,
2413 			  startoff + sizeof(xfs_agblock_t) - 1);
2414 	return 0;
2415 }
2416 
2417 static bool
2418 xfs_agf_verify(
2419 	struct xfs_mount *mp,
2420 	struct xfs_buf	*bp)
2421  {
2422 	struct xfs_agf	*agf = XFS_BUF_TO_AGF(bp);
2423 
2424 	if (xfs_sb_version_hascrc(&mp->m_sb)) {
2425 		if (!uuid_equal(&agf->agf_uuid, &mp->m_sb.sb_meta_uuid))
2426 			return false;
2427 		if (!xfs_log_check_lsn(mp,
2428 				be64_to_cpu(XFS_BUF_TO_AGF(bp)->agf_lsn)))
2429 			return false;
2430 	}
2431 
2432 	if (!(agf->agf_magicnum == cpu_to_be32(XFS_AGF_MAGIC) &&
2433 	      XFS_AGF_GOOD_VERSION(be32_to_cpu(agf->agf_versionnum)) &&
2434 	      be32_to_cpu(agf->agf_freeblks) <= be32_to_cpu(agf->agf_length) &&
2435 	      be32_to_cpu(agf->agf_flfirst) < XFS_AGFL_SIZE(mp) &&
2436 	      be32_to_cpu(agf->agf_fllast) < XFS_AGFL_SIZE(mp) &&
2437 	      be32_to_cpu(agf->agf_flcount) <= XFS_AGFL_SIZE(mp)))
2438 		return false;
2439 
2440 	if (be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) > XFS_BTREE_MAXLEVELS ||
2441 	    be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) > XFS_BTREE_MAXLEVELS)
2442 		return false;
2443 
2444 	if (xfs_sb_version_hasrmapbt(&mp->m_sb) &&
2445 	    be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAP]) > XFS_BTREE_MAXLEVELS)
2446 		return false;
2447 
2448 	/*
2449 	 * during growfs operations, the perag is not fully initialised,
2450 	 * so we can't use it for any useful checking. growfs ensures we can't
2451 	 * use it by using uncached buffers that don't have the perag attached
2452 	 * so we can detect and avoid this problem.
2453 	 */
2454 	if (bp->b_pag && be32_to_cpu(agf->agf_seqno) != bp->b_pag->pag_agno)
2455 		return false;
2456 
2457 	if (xfs_sb_version_haslazysbcount(&mp->m_sb) &&
2458 	    be32_to_cpu(agf->agf_btreeblks) > be32_to_cpu(agf->agf_length))
2459 		return false;
2460 
2461 	return true;;
2462 
2463 }
2464 
2465 static void
2466 xfs_agf_read_verify(
2467 	struct xfs_buf	*bp)
2468 {
2469 	struct xfs_mount *mp = bp->b_target->bt_mount;
2470 
2471 	if (xfs_sb_version_hascrc(&mp->m_sb) &&
2472 	    !xfs_buf_verify_cksum(bp, XFS_AGF_CRC_OFF))
2473 		xfs_buf_ioerror(bp, -EFSBADCRC);
2474 	else if (XFS_TEST_ERROR(!xfs_agf_verify(mp, bp), mp,
2475 				XFS_ERRTAG_ALLOC_READ_AGF,
2476 				XFS_RANDOM_ALLOC_READ_AGF))
2477 		xfs_buf_ioerror(bp, -EFSCORRUPTED);
2478 
2479 	if (bp->b_error)
2480 		xfs_verifier_error(bp);
2481 }
2482 
2483 static void
2484 xfs_agf_write_verify(
2485 	struct xfs_buf	*bp)
2486 {
2487 	struct xfs_mount *mp = bp->b_target->bt_mount;
2488 	struct xfs_buf_log_item	*bip = bp->b_fspriv;
2489 
2490 	if (!xfs_agf_verify(mp, bp)) {
2491 		xfs_buf_ioerror(bp, -EFSCORRUPTED);
2492 		xfs_verifier_error(bp);
2493 		return;
2494 	}
2495 
2496 	if (!xfs_sb_version_hascrc(&mp->m_sb))
2497 		return;
2498 
2499 	if (bip)
2500 		XFS_BUF_TO_AGF(bp)->agf_lsn = cpu_to_be64(bip->bli_item.li_lsn);
2501 
2502 	xfs_buf_update_cksum(bp, XFS_AGF_CRC_OFF);
2503 }
2504 
2505 const struct xfs_buf_ops xfs_agf_buf_ops = {
2506 	.name = "xfs_agf",
2507 	.verify_read = xfs_agf_read_verify,
2508 	.verify_write = xfs_agf_write_verify,
2509 };
2510 
2511 /*
2512  * Read in the allocation group header (free/alloc section).
2513  */
2514 int					/* error */
2515 xfs_read_agf(
2516 	struct xfs_mount	*mp,	/* mount point structure */
2517 	struct xfs_trans	*tp,	/* transaction pointer */
2518 	xfs_agnumber_t		agno,	/* allocation group number */
2519 	int			flags,	/* XFS_BUF_ */
2520 	struct xfs_buf		**bpp)	/* buffer for the ag freelist header */
2521 {
2522 	int		error;
2523 
2524 	trace_xfs_read_agf(mp, agno);
2525 
2526 	ASSERT(agno != NULLAGNUMBER);
2527 	error = xfs_trans_read_buf(
2528 			mp, tp, mp->m_ddev_targp,
2529 			XFS_AG_DADDR(mp, agno, XFS_AGF_DADDR(mp)),
2530 			XFS_FSS_TO_BB(mp, 1), flags, bpp, &xfs_agf_buf_ops);
2531 	if (error)
2532 		return error;
2533 	if (!*bpp)
2534 		return 0;
2535 
2536 	ASSERT(!(*bpp)->b_error);
2537 	xfs_buf_set_ref(*bpp, XFS_AGF_REF);
2538 	return 0;
2539 }
2540 
2541 /*
2542  * Read in the allocation group header (free/alloc section).
2543  */
2544 int					/* error */
2545 xfs_alloc_read_agf(
2546 	struct xfs_mount	*mp,	/* mount point structure */
2547 	struct xfs_trans	*tp,	/* transaction pointer */
2548 	xfs_agnumber_t		agno,	/* allocation group number */
2549 	int			flags,	/* XFS_ALLOC_FLAG_... */
2550 	struct xfs_buf		**bpp)	/* buffer for the ag freelist header */
2551 {
2552 	struct xfs_agf		*agf;		/* ag freelist header */
2553 	struct xfs_perag	*pag;		/* per allocation group data */
2554 	int			error;
2555 
2556 	trace_xfs_alloc_read_agf(mp, agno);
2557 
2558 	ASSERT(agno != NULLAGNUMBER);
2559 	error = xfs_read_agf(mp, tp, agno,
2560 			(flags & XFS_ALLOC_FLAG_TRYLOCK) ? XBF_TRYLOCK : 0,
2561 			bpp);
2562 	if (error)
2563 		return error;
2564 	if (!*bpp)
2565 		return 0;
2566 	ASSERT(!(*bpp)->b_error);
2567 
2568 	agf = XFS_BUF_TO_AGF(*bpp);
2569 	pag = xfs_perag_get(mp, agno);
2570 	if (!pag->pagf_init) {
2571 		pag->pagf_freeblks = be32_to_cpu(agf->agf_freeblks);
2572 		pag->pagf_btreeblks = be32_to_cpu(agf->agf_btreeblks);
2573 		pag->pagf_flcount = be32_to_cpu(agf->agf_flcount);
2574 		pag->pagf_longest = be32_to_cpu(agf->agf_longest);
2575 		pag->pagf_levels[XFS_BTNUM_BNOi] =
2576 			be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNOi]);
2577 		pag->pagf_levels[XFS_BTNUM_CNTi] =
2578 			be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNTi]);
2579 		pag->pagf_levels[XFS_BTNUM_RMAPi] =
2580 			be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAPi]);
2581 		spin_lock_init(&pag->pagb_lock);
2582 		pag->pagb_count = 0;
2583 		pag->pagb_tree = RB_ROOT;
2584 		pag->pagf_init = 1;
2585 	}
2586 #ifdef DEBUG
2587 	else if (!XFS_FORCED_SHUTDOWN(mp)) {
2588 		ASSERT(pag->pagf_freeblks == be32_to_cpu(agf->agf_freeblks));
2589 		ASSERT(pag->pagf_btreeblks == be32_to_cpu(agf->agf_btreeblks));
2590 		ASSERT(pag->pagf_flcount == be32_to_cpu(agf->agf_flcount));
2591 		ASSERT(pag->pagf_longest == be32_to_cpu(agf->agf_longest));
2592 		ASSERT(pag->pagf_levels[XFS_BTNUM_BNOi] ==
2593 		       be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNOi]));
2594 		ASSERT(pag->pagf_levels[XFS_BTNUM_CNTi] ==
2595 		       be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNTi]));
2596 	}
2597 #endif
2598 	xfs_perag_put(pag);
2599 	return 0;
2600 }
2601 
2602 /*
2603  * Allocate an extent (variable-size).
2604  * Depending on the allocation type, we either look in a single allocation
2605  * group or loop over the allocation groups to find the result.
2606  */
2607 int				/* error */
2608 xfs_alloc_vextent(
2609 	xfs_alloc_arg_t	*args)	/* allocation argument structure */
2610 {
2611 	xfs_agblock_t	agsize;	/* allocation group size */
2612 	int		error;
2613 	int		flags;	/* XFS_ALLOC_FLAG_... locking flags */
2614 	xfs_extlen_t	minleft;/* minimum left value, temp copy */
2615 	xfs_mount_t	*mp;	/* mount structure pointer */
2616 	xfs_agnumber_t	sagno;	/* starting allocation group number */
2617 	xfs_alloctype_t	type;	/* input allocation type */
2618 	int		bump_rotor = 0;
2619 	int		no_min = 0;
2620 	xfs_agnumber_t	rotorstep = xfs_rotorstep; /* inode32 agf stepper */
2621 
2622 	mp = args->mp;
2623 	type = args->otype = args->type;
2624 	args->agbno = NULLAGBLOCK;
2625 	/*
2626 	 * Just fix this up, for the case where the last a.g. is shorter
2627 	 * (or there's only one a.g.) and the caller couldn't easily figure
2628 	 * that out (xfs_bmap_alloc).
2629 	 */
2630 	agsize = mp->m_sb.sb_agblocks;
2631 	if (args->maxlen > agsize)
2632 		args->maxlen = agsize;
2633 	if (args->alignment == 0)
2634 		args->alignment = 1;
2635 	ASSERT(XFS_FSB_TO_AGNO(mp, args->fsbno) < mp->m_sb.sb_agcount);
2636 	ASSERT(XFS_FSB_TO_AGBNO(mp, args->fsbno) < agsize);
2637 	ASSERT(args->minlen <= args->maxlen);
2638 	ASSERT(args->minlen <= agsize);
2639 	ASSERT(args->mod < args->prod);
2640 	if (XFS_FSB_TO_AGNO(mp, args->fsbno) >= mp->m_sb.sb_agcount ||
2641 	    XFS_FSB_TO_AGBNO(mp, args->fsbno) >= agsize ||
2642 	    args->minlen > args->maxlen || args->minlen > agsize ||
2643 	    args->mod >= args->prod) {
2644 		args->fsbno = NULLFSBLOCK;
2645 		trace_xfs_alloc_vextent_badargs(args);
2646 		return 0;
2647 	}
2648 	minleft = args->minleft;
2649 
2650 	switch (type) {
2651 	case XFS_ALLOCTYPE_THIS_AG:
2652 	case XFS_ALLOCTYPE_NEAR_BNO:
2653 	case XFS_ALLOCTYPE_THIS_BNO:
2654 		/*
2655 		 * These three force us into a single a.g.
2656 		 */
2657 		args->agno = XFS_FSB_TO_AGNO(mp, args->fsbno);
2658 		args->pag = xfs_perag_get(mp, args->agno);
2659 		args->minleft = 0;
2660 		error = xfs_alloc_fix_freelist(args, 0);
2661 		args->minleft = minleft;
2662 		if (error) {
2663 			trace_xfs_alloc_vextent_nofix(args);
2664 			goto error0;
2665 		}
2666 		if (!args->agbp) {
2667 			trace_xfs_alloc_vextent_noagbp(args);
2668 			break;
2669 		}
2670 		args->agbno = XFS_FSB_TO_AGBNO(mp, args->fsbno);
2671 		if ((error = xfs_alloc_ag_vextent(args)))
2672 			goto error0;
2673 		break;
2674 	case XFS_ALLOCTYPE_START_BNO:
2675 		/*
2676 		 * Try near allocation first, then anywhere-in-ag after
2677 		 * the first a.g. fails.
2678 		 */
2679 		if ((args->datatype & XFS_ALLOC_INITIAL_USER_DATA) &&
2680 		    (mp->m_flags & XFS_MOUNT_32BITINODES)) {
2681 			args->fsbno = XFS_AGB_TO_FSB(mp,
2682 					((mp->m_agfrotor / rotorstep) %
2683 					mp->m_sb.sb_agcount), 0);
2684 			bump_rotor = 1;
2685 		}
2686 		args->agbno = XFS_FSB_TO_AGBNO(mp, args->fsbno);
2687 		args->type = XFS_ALLOCTYPE_NEAR_BNO;
2688 		/* FALLTHROUGH */
2689 	case XFS_ALLOCTYPE_ANY_AG:
2690 	case XFS_ALLOCTYPE_START_AG:
2691 	case XFS_ALLOCTYPE_FIRST_AG:
2692 		/*
2693 		 * Rotate through the allocation groups looking for a winner.
2694 		 */
2695 		if (type == XFS_ALLOCTYPE_ANY_AG) {
2696 			/*
2697 			 * Start with the last place we left off.
2698 			 */
2699 			args->agno = sagno = (mp->m_agfrotor / rotorstep) %
2700 					mp->m_sb.sb_agcount;
2701 			args->type = XFS_ALLOCTYPE_THIS_AG;
2702 			flags = XFS_ALLOC_FLAG_TRYLOCK;
2703 		} else if (type == XFS_ALLOCTYPE_FIRST_AG) {
2704 			/*
2705 			 * Start with allocation group given by bno.
2706 			 */
2707 			args->agno = XFS_FSB_TO_AGNO(mp, args->fsbno);
2708 			args->type = XFS_ALLOCTYPE_THIS_AG;
2709 			sagno = 0;
2710 			flags = 0;
2711 		} else {
2712 			if (type == XFS_ALLOCTYPE_START_AG)
2713 				args->type = XFS_ALLOCTYPE_THIS_AG;
2714 			/*
2715 			 * Start with the given allocation group.
2716 			 */
2717 			args->agno = sagno = XFS_FSB_TO_AGNO(mp, args->fsbno);
2718 			flags = XFS_ALLOC_FLAG_TRYLOCK;
2719 		}
2720 		/*
2721 		 * Loop over allocation groups twice; first time with
2722 		 * trylock set, second time without.
2723 		 */
2724 		for (;;) {
2725 			args->pag = xfs_perag_get(mp, args->agno);
2726 			if (no_min) args->minleft = 0;
2727 			error = xfs_alloc_fix_freelist(args, flags);
2728 			args->minleft = minleft;
2729 			if (error) {
2730 				trace_xfs_alloc_vextent_nofix(args);
2731 				goto error0;
2732 			}
2733 			/*
2734 			 * If we get a buffer back then the allocation will fly.
2735 			 */
2736 			if (args->agbp) {
2737 				if ((error = xfs_alloc_ag_vextent(args)))
2738 					goto error0;
2739 				break;
2740 			}
2741 
2742 			trace_xfs_alloc_vextent_loopfailed(args);
2743 
2744 			/*
2745 			 * Didn't work, figure out the next iteration.
2746 			 */
2747 			if (args->agno == sagno &&
2748 			    type == XFS_ALLOCTYPE_START_BNO)
2749 				args->type = XFS_ALLOCTYPE_THIS_AG;
2750 			/*
2751 			* For the first allocation, we can try any AG to get
2752 			* space.  However, if we already have allocated a
2753 			* block, we don't want to try AGs whose number is below
2754 			* sagno. Otherwise, we may end up with out-of-order
2755 			* locking of AGF, which might cause deadlock.
2756 			*/
2757 			if (++(args->agno) == mp->m_sb.sb_agcount) {
2758 				if (args->firstblock != NULLFSBLOCK)
2759 					args->agno = sagno;
2760 				else
2761 					args->agno = 0;
2762 			}
2763 			/*
2764 			 * Reached the starting a.g., must either be done
2765 			 * or switch to non-trylock mode.
2766 			 */
2767 			if (args->agno == sagno) {
2768 				if (no_min == 1) {
2769 					args->agbno = NULLAGBLOCK;
2770 					trace_xfs_alloc_vextent_allfailed(args);
2771 					break;
2772 				}
2773 				if (flags == 0) {
2774 					no_min = 1;
2775 				} else {
2776 					flags = 0;
2777 					if (type == XFS_ALLOCTYPE_START_BNO) {
2778 						args->agbno = XFS_FSB_TO_AGBNO(mp,
2779 							args->fsbno);
2780 						args->type = XFS_ALLOCTYPE_NEAR_BNO;
2781 					}
2782 				}
2783 			}
2784 			xfs_perag_put(args->pag);
2785 		}
2786 		if (bump_rotor || (type == XFS_ALLOCTYPE_ANY_AG)) {
2787 			if (args->agno == sagno)
2788 				mp->m_agfrotor = (mp->m_agfrotor + 1) %
2789 					(mp->m_sb.sb_agcount * rotorstep);
2790 			else
2791 				mp->m_agfrotor = (args->agno * rotorstep + 1) %
2792 					(mp->m_sb.sb_agcount * rotorstep);
2793 		}
2794 		break;
2795 	default:
2796 		ASSERT(0);
2797 		/* NOTREACHED */
2798 	}
2799 	if (args->agbno == NULLAGBLOCK)
2800 		args->fsbno = NULLFSBLOCK;
2801 	else {
2802 		args->fsbno = XFS_AGB_TO_FSB(mp, args->agno, args->agbno);
2803 #ifdef DEBUG
2804 		ASSERT(args->len >= args->minlen);
2805 		ASSERT(args->len <= args->maxlen);
2806 		ASSERT(args->agbno % args->alignment == 0);
2807 		XFS_AG_CHECK_DADDR(mp, XFS_FSB_TO_DADDR(mp, args->fsbno),
2808 			args->len);
2809 #endif
2810 
2811 		/* Zero the extent if we were asked to do so */
2812 		if (args->datatype & XFS_ALLOC_USERDATA_ZERO) {
2813 			error = xfs_zero_extent(args->ip, args->fsbno, args->len);
2814 			if (error)
2815 				goto error0;
2816 		}
2817 
2818 	}
2819 	xfs_perag_put(args->pag);
2820 	return 0;
2821 error0:
2822 	xfs_perag_put(args->pag);
2823 	return error;
2824 }
2825 
2826 /* Ensure that the freelist is at full capacity. */
2827 int
2828 xfs_free_extent_fix_freelist(
2829 	struct xfs_trans	*tp,
2830 	xfs_agnumber_t		agno,
2831 	struct xfs_buf		**agbp)
2832 {
2833 	struct xfs_alloc_arg	args;
2834 	int			error;
2835 
2836 	memset(&args, 0, sizeof(struct xfs_alloc_arg));
2837 	args.tp = tp;
2838 	args.mp = tp->t_mountp;
2839 	args.agno = agno;
2840 
2841 	/*
2842 	 * validate that the block number is legal - the enables us to detect
2843 	 * and handle a silent filesystem corruption rather than crashing.
2844 	 */
2845 	if (args.agno >= args.mp->m_sb.sb_agcount)
2846 		return -EFSCORRUPTED;
2847 
2848 	args.pag = xfs_perag_get(args.mp, args.agno);
2849 	ASSERT(args.pag);
2850 
2851 	error = xfs_alloc_fix_freelist(&args, XFS_ALLOC_FLAG_FREEING);
2852 	if (error)
2853 		goto out;
2854 
2855 	*agbp = args.agbp;
2856 out:
2857 	xfs_perag_put(args.pag);
2858 	return error;
2859 }
2860 
2861 /*
2862  * Free an extent.
2863  * Just break up the extent address and hand off to xfs_free_ag_extent
2864  * after fixing up the freelist.
2865  */
2866 int				/* error */
2867 xfs_free_extent(
2868 	struct xfs_trans	*tp,	/* transaction pointer */
2869 	xfs_fsblock_t		bno,	/* starting block number of extent */
2870 	xfs_extlen_t		len,	/* length of extent */
2871 	struct xfs_owner_info	*oinfo,	/* extent owner */
2872 	enum xfs_ag_resv_type	type)	/* block reservation type */
2873 {
2874 	struct xfs_mount	*mp = tp->t_mountp;
2875 	struct xfs_buf		*agbp;
2876 	xfs_agnumber_t		agno = XFS_FSB_TO_AGNO(mp, bno);
2877 	xfs_agblock_t		agbno = XFS_FSB_TO_AGBNO(mp, bno);
2878 	int			error;
2879 
2880 	ASSERT(len != 0);
2881 	ASSERT(type != XFS_AG_RESV_AGFL);
2882 
2883 	if (XFS_TEST_ERROR(false, mp,
2884 			XFS_ERRTAG_FREE_EXTENT,
2885 			XFS_RANDOM_FREE_EXTENT))
2886 		return -EIO;
2887 
2888 	error = xfs_free_extent_fix_freelist(tp, agno, &agbp);
2889 	if (error)
2890 		return error;
2891 
2892 	XFS_WANT_CORRUPTED_GOTO(mp, agbno < mp->m_sb.sb_agblocks, err);
2893 
2894 	/* validate the extent size is legal now we have the agf locked */
2895 	XFS_WANT_CORRUPTED_GOTO(mp,
2896 		agbno + len <= be32_to_cpu(XFS_BUF_TO_AGF(agbp)->agf_length),
2897 				err);
2898 
2899 	error = xfs_free_ag_extent(tp, agbp, agno, agbno, len, oinfo, type);
2900 	if (error)
2901 		goto err;
2902 
2903 	xfs_extent_busy_insert(tp, agno, agbno, len, 0);
2904 	return 0;
2905 
2906 err:
2907 	xfs_trans_brelse(tp, agbp);
2908 	return error;
2909 }
2910