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