xref: /linux/fs/xfs/libxfs/xfs_ialloc.c (revision bb29b957eaaa15be33243550d9ee576c2d601669)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_bit.h"
13 #include "xfs_mount.h"
14 #include "xfs_inode.h"
15 #include "xfs_btree.h"
16 #include "xfs_ialloc.h"
17 #include "xfs_ialloc_btree.h"
18 #include "xfs_alloc.h"
19 #include "xfs_errortag.h"
20 #include "xfs_error.h"
21 #include "xfs_bmap.h"
22 #include "xfs_trans.h"
23 #include "xfs_buf_item.h"
24 #include "xfs_icreate_item.h"
25 #include "xfs_icache.h"
26 #include "xfs_trace.h"
27 #include "xfs_log.h"
28 #include "xfs_rmap.h"
29 #include "xfs_ag.h"
30 #include "xfs_health.h"
31 
32 /*
33  * Lookup a record by ino in the btree given by cur.
34  */
35 int					/* error */
36 xfs_inobt_lookup(
37 	struct xfs_btree_cur	*cur,	/* btree cursor */
38 	xfs_agino_t		ino,	/* starting inode of chunk */
39 	xfs_lookup_t		dir,	/* <=, >=, == */
40 	int			*stat)	/* success/failure */
41 {
42 	cur->bc_rec.i.ir_startino = ino;
43 	cur->bc_rec.i.ir_holemask = 0;
44 	cur->bc_rec.i.ir_count = 0;
45 	cur->bc_rec.i.ir_freecount = 0;
46 	cur->bc_rec.i.ir_free = 0;
47 	return xfs_btree_lookup(cur, dir, stat);
48 }
49 
50 /*
51  * Update the record referred to by cur to the value given.
52  * This either works (return 0) or gets an EFSCORRUPTED error.
53  */
54 STATIC int				/* error */
55 xfs_inobt_update(
56 	struct xfs_btree_cur	*cur,	/* btree cursor */
57 	xfs_inobt_rec_incore_t	*irec)	/* btree record */
58 {
59 	union xfs_btree_rec	rec;
60 
61 	rec.inobt.ir_startino = cpu_to_be32(irec->ir_startino);
62 	if (xfs_has_sparseinodes(cur->bc_mp)) {
63 		rec.inobt.ir_u.sp.ir_holemask = cpu_to_be16(irec->ir_holemask);
64 		rec.inobt.ir_u.sp.ir_count = irec->ir_count;
65 		rec.inobt.ir_u.sp.ir_freecount = irec->ir_freecount;
66 	} else {
67 		/* ir_holemask/ir_count not supported on-disk */
68 		rec.inobt.ir_u.f.ir_freecount = cpu_to_be32(irec->ir_freecount);
69 	}
70 	rec.inobt.ir_free = cpu_to_be64(irec->ir_free);
71 	return xfs_btree_update(cur, &rec);
72 }
73 
74 /* Convert on-disk btree record to incore inobt record. */
75 void
76 xfs_inobt_btrec_to_irec(
77 	struct xfs_mount		*mp,
78 	const union xfs_btree_rec	*rec,
79 	struct xfs_inobt_rec_incore	*irec)
80 {
81 	irec->ir_startino = be32_to_cpu(rec->inobt.ir_startino);
82 	if (xfs_has_sparseinodes(mp)) {
83 		irec->ir_holemask = be16_to_cpu(rec->inobt.ir_u.sp.ir_holemask);
84 		irec->ir_count = rec->inobt.ir_u.sp.ir_count;
85 		irec->ir_freecount = rec->inobt.ir_u.sp.ir_freecount;
86 	} else {
87 		/*
88 		 * ir_holemask/ir_count not supported on-disk. Fill in hardcoded
89 		 * values for full inode chunks.
90 		 */
91 		irec->ir_holemask = XFS_INOBT_HOLEMASK_FULL;
92 		irec->ir_count = XFS_INODES_PER_CHUNK;
93 		irec->ir_freecount =
94 				be32_to_cpu(rec->inobt.ir_u.f.ir_freecount);
95 	}
96 	irec->ir_free = be64_to_cpu(rec->inobt.ir_free);
97 }
98 
99 /* Compute the freecount of an incore inode record. */
100 uint8_t
101 xfs_inobt_rec_freecount(
102 	const struct xfs_inobt_rec_incore	*irec)
103 {
104 	uint64_t				realfree = irec->ir_free;
105 
106 	if (xfs_inobt_issparse(irec->ir_holemask))
107 		realfree &= xfs_inobt_irec_to_allocmask(irec);
108 	return hweight64(realfree);
109 }
110 
111 /* Simple checks for inode records. */
112 xfs_failaddr_t
113 xfs_inobt_check_irec(
114 	struct xfs_perag			*pag,
115 	const struct xfs_inobt_rec_incore	*irec)
116 {
117 	/* Record has to be properly aligned within the AG. */
118 	if (!xfs_verify_agino(pag, irec->ir_startino))
119 		return __this_address;
120 	if (!xfs_verify_agino(pag,
121 				irec->ir_startino + XFS_INODES_PER_CHUNK - 1))
122 		return __this_address;
123 	if (irec->ir_count < XFS_INODES_PER_HOLEMASK_BIT ||
124 	    irec->ir_count > XFS_INODES_PER_CHUNK)
125 		return __this_address;
126 	if (irec->ir_freecount > XFS_INODES_PER_CHUNK)
127 		return __this_address;
128 
129 	if (xfs_inobt_rec_freecount(irec) != irec->ir_freecount)
130 		return __this_address;
131 
132 	return NULL;
133 }
134 
135 static inline int
136 xfs_inobt_complain_bad_rec(
137 	struct xfs_btree_cur		*cur,
138 	xfs_failaddr_t			fa,
139 	const struct xfs_inobt_rec_incore *irec)
140 {
141 	struct xfs_mount		*mp = cur->bc_mp;
142 
143 	xfs_warn(mp,
144 		"%sbt record corruption in AG %d detected at %pS!",
145 		cur->bc_ops->name, cur->bc_group->xg_gno, fa);
146 	xfs_warn(mp,
147 "start inode 0x%x, count 0x%x, free 0x%x freemask 0x%llx, holemask 0x%x",
148 		irec->ir_startino, irec->ir_count, irec->ir_freecount,
149 		irec->ir_free, irec->ir_holemask);
150 	xfs_btree_mark_sick(cur);
151 	return -EFSCORRUPTED;
152 }
153 
154 /*
155  * Get the data from the pointed-to record.
156  */
157 int
158 xfs_inobt_get_rec(
159 	struct xfs_btree_cur		*cur,
160 	struct xfs_inobt_rec_incore	*irec,
161 	int				*stat)
162 {
163 	struct xfs_mount		*mp = cur->bc_mp;
164 	union xfs_btree_rec		*rec;
165 	xfs_failaddr_t			fa;
166 	int				error;
167 
168 	error = xfs_btree_get_rec(cur, &rec, stat);
169 	if (error || *stat == 0)
170 		return error;
171 
172 	xfs_inobt_btrec_to_irec(mp, rec, irec);
173 	fa = xfs_inobt_check_irec(to_perag(cur->bc_group), irec);
174 	if (fa)
175 		return xfs_inobt_complain_bad_rec(cur, fa, irec);
176 
177 	return 0;
178 }
179 
180 /*
181  * Insert a single inobt record. Cursor must already point to desired location.
182  */
183 int
184 xfs_inobt_insert_rec(
185 	struct xfs_btree_cur	*cur,
186 	uint16_t		holemask,
187 	uint8_t			count,
188 	int32_t			freecount,
189 	xfs_inofree_t		free,
190 	int			*stat)
191 {
192 	cur->bc_rec.i.ir_holemask = holemask;
193 	cur->bc_rec.i.ir_count = count;
194 	cur->bc_rec.i.ir_freecount = freecount;
195 	cur->bc_rec.i.ir_free = free;
196 	return xfs_btree_insert(cur, stat);
197 }
198 
199 /*
200  * Insert records describing a newly allocated inode chunk into the inobt.
201  */
202 STATIC int
203 xfs_inobt_insert(
204 	struct xfs_perag	*pag,
205 	struct xfs_trans	*tp,
206 	struct xfs_buf		*agbp,
207 	xfs_agino_t		newino,
208 	xfs_agino_t		newlen,
209 	bool			is_finobt)
210 {
211 	struct xfs_btree_cur	*cur;
212 	xfs_agino_t		thisino;
213 	int			i;
214 	int			error;
215 
216 	if (is_finobt)
217 		cur = xfs_finobt_init_cursor(pag, tp, agbp);
218 	else
219 		cur = xfs_inobt_init_cursor(pag, tp, agbp);
220 
221 	for (thisino = newino;
222 	     thisino < newino + newlen;
223 	     thisino += XFS_INODES_PER_CHUNK) {
224 		error = xfs_inobt_lookup(cur, thisino, XFS_LOOKUP_EQ, &i);
225 		if (error) {
226 			xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
227 			return error;
228 		}
229 		ASSERT(i == 0);
230 
231 		error = xfs_inobt_insert_rec(cur, XFS_INOBT_HOLEMASK_FULL,
232 					     XFS_INODES_PER_CHUNK,
233 					     XFS_INODES_PER_CHUNK,
234 					     XFS_INOBT_ALL_FREE, &i);
235 		if (error) {
236 			xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
237 			return error;
238 		}
239 		ASSERT(i == 1);
240 	}
241 
242 	xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
243 
244 	return 0;
245 }
246 
247 /*
248  * Verify that the number of free inodes in the AGI is correct.
249  */
250 #ifdef DEBUG
251 static int
252 xfs_check_agi_freecount(
253 	struct xfs_btree_cur	*cur)
254 {
255 	if (cur->bc_nlevels == 1) {
256 		xfs_inobt_rec_incore_t rec;
257 		int		freecount = 0;
258 		int		error;
259 		int		i;
260 
261 		error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &i);
262 		if (error)
263 			return error;
264 
265 		do {
266 			error = xfs_inobt_get_rec(cur, &rec, &i);
267 			if (error)
268 				return error;
269 
270 			if (i) {
271 				freecount += rec.ir_freecount;
272 				error = xfs_btree_increment(cur, 0, &i);
273 				if (error)
274 					return error;
275 			}
276 		} while (i == 1);
277 
278 		if (!xfs_is_shutdown(cur->bc_mp)) {
279 			ASSERT(freecount ==
280 				to_perag(cur->bc_group)->pagi_freecount);
281 		}
282 	}
283 	return 0;
284 }
285 #else
286 #define xfs_check_agi_freecount(cur)	0
287 #endif
288 
289 /*
290  * Initialise a new set of inodes. When called without a transaction context
291  * (e.g. from recovery) we initiate a delayed write of the inode buffers rather
292  * than logging them (which in a transaction context puts them into the AIL
293  * for writeback rather than the xfsbufd queue).
294  */
295 int
296 xfs_ialloc_inode_init(
297 	struct xfs_mount	*mp,
298 	struct xfs_trans	*tp,
299 	struct list_head	*buffer_list,
300 	int			icount,
301 	xfs_agnumber_t		agno,
302 	xfs_agblock_t		agbno,
303 	xfs_agblock_t		length,
304 	unsigned int		gen)
305 {
306 	struct xfs_buf		*fbuf;
307 	struct xfs_dinode	*free;
308 	int			nbufs;
309 	int			version;
310 	int			i, j;
311 	xfs_daddr_t		d;
312 	xfs_ino_t		ino = 0;
313 	int			error;
314 
315 	/*
316 	 * Loop over the new block(s), filling in the inodes.  For small block
317 	 * sizes, manipulate the inodes in buffers  which are multiples of the
318 	 * blocks size.
319 	 */
320 	nbufs = length / M_IGEO(mp)->blocks_per_cluster;
321 
322 	/*
323 	 * Figure out what version number to use in the inodes we create.  If
324 	 * the superblock version has caught up to the one that supports the new
325 	 * inode format, then use the new inode version.  Otherwise use the old
326 	 * version so that old kernels will continue to be able to use the file
327 	 * system.
328 	 *
329 	 * For v3 inodes, we also need to write the inode number into the inode,
330 	 * so calculate the first inode number of the chunk here as
331 	 * XFS_AGB_TO_AGINO() only works within a filesystem block, not
332 	 * across multiple filesystem blocks (such as a cluster) and so cannot
333 	 * be used in the cluster buffer loop below.
334 	 *
335 	 * Further, because we are writing the inode directly into the buffer
336 	 * and calculating a CRC on the entire inode, we have ot log the entire
337 	 * inode so that the entire range the CRC covers is present in the log.
338 	 * That means for v3 inode we log the entire buffer rather than just the
339 	 * inode cores.
340 	 */
341 	if (xfs_has_v3inodes(mp)) {
342 		version = 3;
343 		ino = XFS_AGINO_TO_INO(mp, agno, XFS_AGB_TO_AGINO(mp, agbno));
344 
345 		/*
346 		 * log the initialisation that is about to take place as an
347 		 * logical operation. This means the transaction does not
348 		 * need to log the physical changes to the inode buffers as log
349 		 * recovery will know what initialisation is actually needed.
350 		 * Hence we only need to log the buffers as "ordered" buffers so
351 		 * they track in the AIL as if they were physically logged.
352 		 */
353 		if (tp)
354 			xfs_icreate_log(tp, agno, agbno, icount,
355 					mp->m_sb.sb_inodesize, length, gen);
356 	} else
357 		version = 2;
358 
359 	for (j = 0; j < nbufs; j++) {
360 		/*
361 		 * Get the block.
362 		 */
363 		d = XFS_AGB_TO_DADDR(mp, agno, agbno +
364 				(j * M_IGEO(mp)->blocks_per_cluster));
365 		error = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
366 				mp->m_bsize * M_IGEO(mp)->blocks_per_cluster,
367 				0, &fbuf);
368 		if (error)
369 			return error;
370 
371 		/* Initialize the inode buffers and log them appropriately. */
372 		fbuf->b_ops = &xfs_inode_buf_ops;
373 		xfs_buf_zero(fbuf, 0, BBTOB(fbuf->b_length));
374 		for (i = 0; i < M_IGEO(mp)->inodes_per_cluster; i++) {
375 			int	ioffset = i << mp->m_sb.sb_inodelog;
376 
377 			free = xfs_make_iptr(mp, fbuf, i);
378 			free->di_magic = cpu_to_be16(XFS_DINODE_MAGIC);
379 			free->di_version = version;
380 			free->di_gen = cpu_to_be32(gen);
381 			free->di_next_unlinked = cpu_to_be32(NULLAGINO);
382 
383 			if (version == 3) {
384 				free->di_ino = cpu_to_be64(ino);
385 				ino++;
386 				uuid_copy(&free->di_uuid,
387 					  &mp->m_sb.sb_meta_uuid);
388 				xfs_dinode_calc_crc(mp, free);
389 			} else if (tp) {
390 				/* just log the inode core */
391 				xfs_trans_log_buf(tp, fbuf, ioffset,
392 					  ioffset + XFS_DINODE_SIZE(mp) - 1);
393 			}
394 		}
395 
396 		if (tp) {
397 			/*
398 			 * Mark the buffer as an inode allocation buffer so it
399 			 * sticks in AIL at the point of this allocation
400 			 * transaction. This ensures the they are on disk before
401 			 * the tail of the log can be moved past this
402 			 * transaction (i.e. by preventing relogging from moving
403 			 * it forward in the log).
404 			 */
405 			xfs_trans_inode_alloc_buf(tp, fbuf);
406 			if (version == 3) {
407 				/*
408 				 * Mark the buffer as ordered so that they are
409 				 * not physically logged in the transaction but
410 				 * still tracked in the AIL as part of the
411 				 * transaction and pin the log appropriately.
412 				 */
413 				xfs_trans_ordered_buf(tp, fbuf);
414 			}
415 		} else {
416 			xfs_buf_set_uptodate(fbuf);
417 			xfs_buf_delwri_queue(fbuf, buffer_list);
418 			xfs_buf_relse(fbuf);
419 		}
420 	}
421 	return 0;
422 }
423 
424 /*
425  * Align startino and allocmask for a recently allocated sparse chunk such that
426  * they are fit for insertion (or merge) into the on-disk inode btrees.
427  *
428  * Background:
429  *
430  * When enabled, sparse inode support increases the inode alignment from cluster
431  * size to inode chunk size. This means that the minimum range between two
432  * non-adjacent inode records in the inobt is large enough for a full inode
433  * record. This allows for cluster sized, cluster aligned block allocation
434  * without need to worry about whether the resulting inode record overlaps with
435  * another record in the tree. Without this basic rule, we would have to deal
436  * with the consequences of overlap by potentially undoing recent allocations in
437  * the inode allocation codepath.
438  *
439  * Because of this alignment rule (which is enforced on mount), there are two
440  * inobt possibilities for newly allocated sparse chunks. One is that the
441  * aligned inode record for the chunk covers a range of inodes not already
442  * covered in the inobt (i.e., it is safe to insert a new sparse record). The
443  * other is that a record already exists at the aligned startino that considers
444  * the newly allocated range as sparse. In the latter case, record content is
445  * merged in hope that sparse inode chunks fill to full chunks over time.
446  */
447 STATIC void
448 xfs_align_sparse_ino(
449 	struct xfs_mount		*mp,
450 	xfs_agino_t			*startino,
451 	uint16_t			*allocmask)
452 {
453 	xfs_agblock_t			agbno;
454 	xfs_agblock_t			mod;
455 	int				offset;
456 
457 	agbno = XFS_AGINO_TO_AGBNO(mp, *startino);
458 	mod = agbno % mp->m_sb.sb_inoalignmt;
459 	if (!mod)
460 		return;
461 
462 	/* calculate the inode offset and align startino */
463 	offset = XFS_AGB_TO_AGINO(mp, mod);
464 	*startino -= offset;
465 
466 	/*
467 	 * Since startino has been aligned down, left shift allocmask such that
468 	 * it continues to represent the same physical inodes relative to the
469 	 * new startino.
470 	 */
471 	*allocmask <<= offset / XFS_INODES_PER_HOLEMASK_BIT;
472 }
473 
474 /*
475  * Determine whether the source inode record can merge into the target. Both
476  * records must be sparse, the inode ranges must match and there must be no
477  * allocation overlap between the records.
478  */
479 STATIC bool
480 __xfs_inobt_can_merge(
481 	struct xfs_inobt_rec_incore	*trec,	/* tgt record */
482 	struct xfs_inobt_rec_incore	*srec)	/* src record */
483 {
484 	uint64_t			talloc;
485 	uint64_t			salloc;
486 
487 	/* records must cover the same inode range */
488 	if (trec->ir_startino != srec->ir_startino)
489 		return false;
490 
491 	/* both records must be sparse */
492 	if (!xfs_inobt_issparse(trec->ir_holemask) ||
493 	    !xfs_inobt_issparse(srec->ir_holemask))
494 		return false;
495 
496 	/* both records must track some inodes */
497 	if (!trec->ir_count || !srec->ir_count)
498 		return false;
499 
500 	/* can't exceed capacity of a full record */
501 	if (trec->ir_count + srec->ir_count > XFS_INODES_PER_CHUNK)
502 		return false;
503 
504 	/* verify there is no allocation overlap */
505 	talloc = xfs_inobt_irec_to_allocmask(trec);
506 	salloc = xfs_inobt_irec_to_allocmask(srec);
507 	if (talloc & salloc)
508 		return false;
509 
510 	return true;
511 }
512 
513 /*
514  * Merge the source inode record into the target. The caller must call
515  * __xfs_inobt_can_merge() to ensure the merge is valid.
516  */
517 STATIC void
518 __xfs_inobt_rec_merge(
519 	struct xfs_inobt_rec_incore	*trec,	/* target */
520 	struct xfs_inobt_rec_incore	*srec)	/* src */
521 {
522 	ASSERT(trec->ir_startino == srec->ir_startino);
523 
524 	/* combine the counts */
525 	trec->ir_count += srec->ir_count;
526 	trec->ir_freecount += srec->ir_freecount;
527 
528 	/*
529 	 * Merge the holemask and free mask. For both fields, 0 bits refer to
530 	 * allocated inodes. We combine the allocated ranges with bitwise AND.
531 	 */
532 	trec->ir_holemask &= srec->ir_holemask;
533 	trec->ir_free &= srec->ir_free;
534 }
535 
536 /*
537  * Insert a new sparse inode chunk into the associated inode allocation btree.
538  * The inode record for the sparse chunk is pre-aligned to a startino that
539  * should match any pre-existing sparse inode record in the tree. This allows
540  * sparse chunks to fill over time.
541  *
542  * If no preexisting record exists, the provided record is inserted.
543  * If there is a preexisting record, the provided record is merged with the
544  * existing record and updated in place. The merged record is returned in nrec.
545  *
546  * It is considered corruption if a merge is requested and not possible. Given
547  * the sparse inode alignment constraints, this should never happen.
548  */
549 STATIC int
550 xfs_inobt_insert_sprec(
551 	struct xfs_perag		*pag,
552 	struct xfs_trans		*tp,
553 	struct xfs_buf			*agbp,
554 	struct xfs_inobt_rec_incore	*nrec)	/* in/out: new/merged rec. */
555 {
556 	struct xfs_mount		*mp = pag_mount(pag);
557 	struct xfs_btree_cur		*cur;
558 	int				error;
559 	int				i;
560 	struct xfs_inobt_rec_incore	rec;
561 
562 	cur = xfs_inobt_init_cursor(pag, tp, agbp);
563 
564 	/* the new record is pre-aligned so we know where to look */
565 	error = xfs_inobt_lookup(cur, nrec->ir_startino, XFS_LOOKUP_EQ, &i);
566 	if (error)
567 		goto error;
568 	/* if nothing there, insert a new record and return */
569 	if (i == 0) {
570 		error = xfs_inobt_insert_rec(cur, nrec->ir_holemask,
571 					     nrec->ir_count, nrec->ir_freecount,
572 					     nrec->ir_free, &i);
573 		if (error)
574 			goto error;
575 		if (XFS_IS_CORRUPT(mp, i != 1)) {
576 			xfs_btree_mark_sick(cur);
577 			error = -EFSCORRUPTED;
578 			goto error;
579 		}
580 
581 		goto out;
582 	}
583 
584 	/*
585 	 * A record exists at this startino.  Merge the records.
586 	 */
587 	error = xfs_inobt_get_rec(cur, &rec, &i);
588 	if (error)
589 		goto error;
590 	if (XFS_IS_CORRUPT(mp, i != 1)) {
591 		xfs_btree_mark_sick(cur);
592 		error = -EFSCORRUPTED;
593 		goto error;
594 	}
595 	if (XFS_IS_CORRUPT(mp, rec.ir_startino != nrec->ir_startino)) {
596 		xfs_btree_mark_sick(cur);
597 		error = -EFSCORRUPTED;
598 		goto error;
599 	}
600 
601 	/*
602 	 * This should never fail. If we have coexisting records that
603 	 * cannot merge, something is seriously wrong.
604 	 */
605 	if (XFS_IS_CORRUPT(mp, !__xfs_inobt_can_merge(nrec, &rec))) {
606 		xfs_btree_mark_sick(cur);
607 		error = -EFSCORRUPTED;
608 		goto error;
609 	}
610 
611 	trace_xfs_irec_merge_pre(pag, &rec, nrec);
612 
613 	/* merge to nrec to output the updated record */
614 	__xfs_inobt_rec_merge(nrec, &rec);
615 
616 	trace_xfs_irec_merge_post(pag, nrec);
617 
618 	error = xfs_inobt_rec_check_count(nrec);
619 	if (error)
620 		goto error;
621 
622 	error = xfs_inobt_update(cur, nrec);
623 	if (error)
624 		goto error;
625 
626 out:
627 	xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
628 	return 0;
629 error:
630 	xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
631 	return error;
632 }
633 
634 /*
635  * Insert a new sparse inode chunk into the free inode btree. The inode
636  * record for the sparse chunk is pre-aligned to a startino that should match
637  * any pre-existing sparse inode record in the tree. This allows sparse chunks
638  * to fill over time.
639  *
640  * The new record is always inserted, overwriting a pre-existing record if
641  * there is one.
642  */
643 STATIC int
644 xfs_finobt_insert_sprec(
645 	struct xfs_perag		*pag,
646 	struct xfs_trans		*tp,
647 	struct xfs_buf			*agbp,
648 	struct xfs_inobt_rec_incore	*nrec)	/* in/out: new rec. */
649 {
650 	struct xfs_mount		*mp = pag_mount(pag);
651 	struct xfs_btree_cur		*cur;
652 	int				error;
653 	int				i;
654 
655 	cur = xfs_finobt_init_cursor(pag, tp, agbp);
656 
657 	/* the new record is pre-aligned so we know where to look */
658 	error = xfs_inobt_lookup(cur, nrec->ir_startino, XFS_LOOKUP_EQ, &i);
659 	if (error)
660 		goto error;
661 	/* if nothing there, insert a new record and return */
662 	if (i == 0) {
663 		error = xfs_inobt_insert_rec(cur, nrec->ir_holemask,
664 					     nrec->ir_count, nrec->ir_freecount,
665 					     nrec->ir_free, &i);
666 		if (error)
667 			goto error;
668 		if (XFS_IS_CORRUPT(mp, i != 1)) {
669 			xfs_btree_mark_sick(cur);
670 			error = -EFSCORRUPTED;
671 			goto error;
672 		}
673 	} else {
674 		error = xfs_inobt_update(cur, nrec);
675 		if (error)
676 			goto error;
677 	}
678 
679 	xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
680 	return 0;
681 error:
682 	xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
683 	return error;
684 }
685 
686 
687 /*
688  * Allocate new inodes in the allocation group specified by agbp.  Returns 0 if
689  * inodes were allocated in this AG; -EAGAIN if there was no space in this AG so
690  * the caller knows it can try another AG, a hard -ENOSPC when over the maximum
691  * inode count threshold, or the usual negative error code for other errors.
692  */
693 STATIC int
694 xfs_ialloc_ag_alloc(
695 	struct xfs_perag	*pag,
696 	struct xfs_trans	*tp,
697 	struct xfs_buf		*agbp)
698 {
699 	struct xfs_agi		*agi;
700 	struct xfs_alloc_arg	args;
701 	int			error;
702 	xfs_agino_t		newino;		/* new first inode's number */
703 	xfs_agino_t		newlen;		/* new number of inodes */
704 	int			isaligned = 0;	/* inode allocation at stripe */
705 						/* unit boundary */
706 	/* init. to full chunk */
707 	struct xfs_inobt_rec_incore rec;
708 	struct xfs_ino_geometry	*igeo = M_IGEO(tp->t_mountp);
709 	uint16_t		allocmask = (uint16_t) -1;
710 	int			do_sparse = 0;
711 
712 	memset(&args, 0, sizeof(args));
713 	args.tp = tp;
714 	args.mp = tp->t_mountp;
715 	args.fsbno = NULLFSBLOCK;
716 	args.oinfo = XFS_RMAP_OINFO_INODES;
717 	args.pag = pag;
718 
719 #ifdef DEBUG
720 	/* randomly do sparse inode allocations */
721 	if (xfs_has_sparseinodes(tp->t_mountp) &&
722 	    igeo->ialloc_min_blks < igeo->ialloc_blks)
723 		do_sparse = get_random_u32_below(2);
724 #endif
725 
726 	/*
727 	 * Locking will ensure that we don't have two callers in here
728 	 * at one time.
729 	 */
730 	newlen = igeo->ialloc_inos;
731 	if (igeo->maxicount &&
732 	    percpu_counter_read_positive(&args.mp->m_icount) + newlen >
733 							igeo->maxicount)
734 		return -ENOSPC;
735 	args.minlen = args.maxlen = igeo->ialloc_blks;
736 
737 	/* Allow space for the inode btree to split. */
738 	args.minleft = igeo->inobt_maxlevels;
739 
740 	/*
741 	 * First try to allocate inodes contiguous with the last-allocated
742 	 * chunk of inodes.  If the filesystem is striped, this will fill
743 	 * an entire stripe unit with inodes.
744 	 */
745 	agi = agbp->b_addr;
746 	newino = be32_to_cpu(agi->agi_newino);
747 	args.agbno = XFS_AGINO_TO_AGBNO(args.mp, newino) +
748 		     igeo->ialloc_blks;
749 	if (do_sparse)
750 		goto sparse_alloc;
751 	if (likely(newino != NULLAGINO &&
752 		  (args.agbno < be32_to_cpu(agi->agi_length)))) {
753 		args.prod = 1;
754 
755 		/*
756 		 * We need to take into account alignment here to ensure that
757 		 * we don't modify the free list if we fail to have an exact
758 		 * block. If we don't have an exact match, and every oher
759 		 * attempt allocation attempt fails, we'll end up cancelling
760 		 * a dirty transaction and shutting down.
761 		 *
762 		 * For an exact allocation, alignment must be 1,
763 		 * however we need to take cluster alignment into account when
764 		 * fixing up the freelist. Use the minalignslop field to
765 		 * indicate that extra blocks might be required for alignment,
766 		 * but not to use them in the actual exact allocation.
767 		 */
768 		args.alignment = 1;
769 		args.minalignslop = igeo->cluster_align - 1;
770 
771 		error = xfs_alloc_vextent_exact_bno(&args,
772 				xfs_agbno_to_fsb(pag, args.agbno));
773 		if (error)
774 			return error;
775 
776 		/*
777 		 * This request might have dirtied the transaction if the AG can
778 		 * satisfy the request, but the exact block was not available.
779 		 * If the allocation did fail, subsequent requests will relax
780 		 * the exact agbno requirement and increase the alignment
781 		 * instead. It is critical that the total size of the request
782 		 * (len + alignment + slop) does not increase from this point
783 		 * on, so reset minalignslop to ensure it is not included in
784 		 * subsequent requests.
785 		 */
786 		args.minalignslop = 0;
787 	}
788 
789 	if (unlikely(args.fsbno == NULLFSBLOCK)) {
790 		/*
791 		 * Set the alignment for the allocation.
792 		 * If stripe alignment is turned on then align at stripe unit
793 		 * boundary.
794 		 * If the cluster size is smaller than a filesystem block
795 		 * then we're doing I/O for inodes in filesystem block size
796 		 * pieces, so don't need alignment anyway.
797 		 */
798 		isaligned = 0;
799 		if (igeo->ialloc_align) {
800 			ASSERT(!xfs_has_noalign(args.mp));
801 			args.alignment = args.mp->m_dalign;
802 			isaligned = 1;
803 		} else
804 			args.alignment = igeo->cluster_align;
805 		/*
806 		 * Allocate a fixed-size extent of inodes.
807 		 */
808 		args.prod = 1;
809 		error = xfs_alloc_vextent_near_bno(&args,
810 				xfs_agbno_to_fsb(pag,
811 					be32_to_cpu(agi->agi_root)));
812 		if (error)
813 			return error;
814 	}
815 
816 	/*
817 	 * If stripe alignment is turned on, then try again with cluster
818 	 * alignment.
819 	 */
820 	if (isaligned && args.fsbno == NULLFSBLOCK) {
821 		args.alignment = igeo->cluster_align;
822 		error = xfs_alloc_vextent_near_bno(&args,
823 				xfs_agbno_to_fsb(pag,
824 					be32_to_cpu(agi->agi_root)));
825 		if (error)
826 			return error;
827 	}
828 
829 	/*
830 	 * Finally, try a sparse allocation if the filesystem supports it and
831 	 * the sparse allocation length is smaller than a full chunk.
832 	 */
833 	if (xfs_has_sparseinodes(args.mp) &&
834 	    igeo->ialloc_min_blks < igeo->ialloc_blks &&
835 	    args.fsbno == NULLFSBLOCK) {
836 sparse_alloc:
837 		args.alignment = args.mp->m_sb.sb_spino_align;
838 		args.prod = 1;
839 
840 		args.minlen = igeo->ialloc_min_blks;
841 		args.maxlen = args.minlen;
842 
843 		/*
844 		 * The inode record will be aligned to full chunk size. We must
845 		 * prevent sparse allocation from AG boundaries that result in
846 		 * invalid inode records, such as records that start at agbno 0
847 		 * or extend beyond the AG.
848 		 *
849 		 * Set min agbno to the first chunk aligned, non-zero agbno and
850 		 * max to one less than the last chunk aligned agbno from the
851 		 * end of the AG. We subtract 1 from max so that the cluster
852 		 * allocation alignment takes over and allows allocation within
853 		 * the last full inode chunk in the AG.
854 		 */
855 		args.min_agbno = args.mp->m_sb.sb_inoalignmt;
856 		args.max_agbno = round_down(xfs_ag_block_count(args.mp,
857 							pag_agno(pag)),
858 					    args.mp->m_sb.sb_inoalignmt) - 1;
859 
860 		error = xfs_alloc_vextent_near_bno(&args,
861 				xfs_agbno_to_fsb(pag,
862 					be32_to_cpu(agi->agi_root)));
863 		if (error)
864 			return error;
865 
866 		newlen = XFS_AGB_TO_AGINO(args.mp, args.len);
867 		ASSERT(newlen <= XFS_INODES_PER_CHUNK);
868 		allocmask = (1 << (newlen / XFS_INODES_PER_HOLEMASK_BIT)) - 1;
869 	}
870 
871 	if (args.fsbno == NULLFSBLOCK)
872 		return -EAGAIN;
873 
874 	ASSERT(args.len == args.minlen);
875 
876 	/*
877 	 * Stamp and write the inode buffers.
878 	 *
879 	 * Seed the new inode cluster with a random generation number. This
880 	 * prevents short-term reuse of generation numbers if a chunk is
881 	 * freed and then immediately reallocated. We use random numbers
882 	 * rather than a linear progression to prevent the next generation
883 	 * number from being easily guessable.
884 	 */
885 	error = xfs_ialloc_inode_init(args.mp, tp, NULL, newlen, pag_agno(pag),
886 			args.agbno, args.len, get_random_u32());
887 
888 	if (error)
889 		return error;
890 	/*
891 	 * Convert the results.
892 	 */
893 	newino = XFS_AGB_TO_AGINO(args.mp, args.agbno);
894 
895 	if (xfs_inobt_issparse(~allocmask)) {
896 		/*
897 		 * We've allocated a sparse chunk. Align the startino and mask.
898 		 */
899 		xfs_align_sparse_ino(args.mp, &newino, &allocmask);
900 
901 		rec.ir_startino = newino;
902 		rec.ir_holemask = ~allocmask;
903 		rec.ir_count = newlen;
904 		rec.ir_freecount = newlen;
905 		rec.ir_free = XFS_INOBT_ALL_FREE;
906 
907 		/*
908 		 * Insert the sparse record into the inobt and allow for a merge
909 		 * if necessary. If a merge does occur, rec is updated to the
910 		 * merged record.
911 		 */
912 		error = xfs_inobt_insert_sprec(pag, tp, agbp, &rec);
913 		if (error == -EFSCORRUPTED) {
914 			xfs_alert(args.mp,
915 	"invalid sparse inode record: ino 0x%llx holemask 0x%x count %u",
916 				  xfs_agino_to_ino(pag, rec.ir_startino),
917 				  rec.ir_holemask, rec.ir_count);
918 			xfs_force_shutdown(args.mp, SHUTDOWN_CORRUPT_INCORE);
919 		}
920 		if (error)
921 			return error;
922 
923 		/*
924 		 * We can't merge the part we've just allocated as for the inobt
925 		 * due to finobt semantics. The original record may or may not
926 		 * exist independent of whether physical inodes exist in this
927 		 * sparse chunk.
928 		 *
929 		 * We must update the finobt record based on the inobt record.
930 		 * rec contains the fully merged and up to date inobt record
931 		 * from the previous call. Set merge false to replace any
932 		 * existing record with this one.
933 		 */
934 		if (xfs_has_finobt(args.mp)) {
935 			error = xfs_finobt_insert_sprec(pag, tp, agbp, &rec);
936 			if (error)
937 				return error;
938 		}
939 	} else {
940 		/* full chunk - insert new records to both btrees */
941 		error = xfs_inobt_insert(pag, tp, agbp, newino, newlen, false);
942 		if (error)
943 			return error;
944 
945 		if (xfs_has_finobt(args.mp)) {
946 			error = xfs_inobt_insert(pag, tp, agbp, newino,
947 						 newlen, true);
948 			if (error)
949 				return error;
950 		}
951 	}
952 
953 	/*
954 	 * Update AGI counts and newino.
955 	 */
956 	be32_add_cpu(&agi->agi_count, newlen);
957 	be32_add_cpu(&agi->agi_freecount, newlen);
958 	pag->pagi_freecount += newlen;
959 	pag->pagi_count += newlen;
960 	agi->agi_newino = cpu_to_be32(newino);
961 
962 	/*
963 	 * Log allocation group header fields
964 	 */
965 	xfs_ialloc_log_agi(tp, agbp,
966 		XFS_AGI_COUNT | XFS_AGI_FREECOUNT | XFS_AGI_NEWINO);
967 	/*
968 	 * Modify/log superblock values for inode count and inode free count.
969 	 */
970 	xfs_trans_mod_sb(tp, XFS_TRANS_SB_ICOUNT, (long)newlen);
971 	xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, (long)newlen);
972 	return 0;
973 }
974 
975 /*
976  * Try to retrieve the next record to the left/right from the current one.
977  */
978 STATIC int
979 xfs_ialloc_next_rec(
980 	struct xfs_btree_cur	*cur,
981 	xfs_inobt_rec_incore_t	*rec,
982 	int			*done,
983 	int			left)
984 {
985 	int                     error;
986 	int			i;
987 
988 	if (left)
989 		error = xfs_btree_decrement(cur, 0, &i);
990 	else
991 		error = xfs_btree_increment(cur, 0, &i);
992 
993 	if (error)
994 		return error;
995 	*done = !i;
996 	if (i) {
997 		error = xfs_inobt_get_rec(cur, rec, &i);
998 		if (error)
999 			return error;
1000 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1001 			xfs_btree_mark_sick(cur);
1002 			return -EFSCORRUPTED;
1003 		}
1004 	}
1005 
1006 	return 0;
1007 }
1008 
1009 STATIC int
1010 xfs_ialloc_get_rec(
1011 	struct xfs_btree_cur	*cur,
1012 	xfs_agino_t		agino,
1013 	xfs_inobt_rec_incore_t	*rec,
1014 	int			*done)
1015 {
1016 	int                     error;
1017 	int			i;
1018 
1019 	error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_EQ, &i);
1020 	if (error)
1021 		return error;
1022 	*done = !i;
1023 	if (i) {
1024 		error = xfs_inobt_get_rec(cur, rec, &i);
1025 		if (error)
1026 			return error;
1027 		if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1028 			xfs_btree_mark_sick(cur);
1029 			return -EFSCORRUPTED;
1030 		}
1031 	}
1032 
1033 	return 0;
1034 }
1035 
1036 /*
1037  * Return the offset of the first free inode in the record. If the inode chunk
1038  * is sparsely allocated, we convert the record holemask to inode granularity
1039  * and mask off the unallocated regions from the inode free mask.
1040  */
1041 STATIC int
1042 xfs_inobt_first_free_inode(
1043 	struct xfs_inobt_rec_incore	*rec)
1044 {
1045 	xfs_inofree_t			realfree;
1046 
1047 	/* if there are no holes, return the first available offset */
1048 	if (!xfs_inobt_issparse(rec->ir_holemask))
1049 		return xfs_lowbit64(rec->ir_free);
1050 
1051 	realfree = xfs_inobt_irec_to_allocmask(rec);
1052 	realfree &= rec->ir_free;
1053 
1054 	return xfs_lowbit64(realfree);
1055 }
1056 
1057 /*
1058  * If this AG has corrupt inodes, check if allocating this inode would fail
1059  * with corruption errors.  Returns 0 if we're clear, or EAGAIN to try again
1060  * somewhere else.
1061  */
1062 static int
1063 xfs_dialloc_check_ino(
1064 	struct xfs_perag	*pag,
1065 	struct xfs_trans	*tp,
1066 	xfs_ino_t		ino)
1067 {
1068 	struct xfs_imap		imap;
1069 	struct xfs_buf		*bp;
1070 	int			error;
1071 
1072 	error = xfs_imap(pag, tp, ino, &imap, 0);
1073 	if (error)
1074 		return -EAGAIN;
1075 
1076 	error = xfs_read_icluster(pag, tp, imap.im_agbno, &bp);
1077 	if (error)
1078 		return -EAGAIN;
1079 
1080 	xfs_trans_brelse(tp, bp);
1081 	return 0;
1082 }
1083 
1084 /*
1085  * Allocate an inode using the inobt-only algorithm.
1086  */
1087 STATIC int
1088 xfs_dialloc_ag_inobt(
1089 	struct xfs_perag	*pag,
1090 	struct xfs_trans	*tp,
1091 	struct xfs_buf		*agbp,
1092 	xfs_ino_t		parent,
1093 	xfs_ino_t		*inop)
1094 {
1095 	struct xfs_mount	*mp = tp->t_mountp;
1096 	struct xfs_agi		*agi = agbp->b_addr;
1097 	xfs_agnumber_t		pagno = XFS_INO_TO_AGNO(mp, parent);
1098 	xfs_agino_t		pagino = XFS_INO_TO_AGINO(mp, parent);
1099 	struct xfs_btree_cur	*cur, *tcur;
1100 	struct xfs_inobt_rec_incore rec, trec;
1101 	xfs_ino_t		ino;
1102 	int			error;
1103 	int			offset;
1104 	int			i, j;
1105 	int			searchdistance = 10;
1106 
1107 	ASSERT(xfs_perag_initialised_agi(pag));
1108 	ASSERT(xfs_perag_allows_inodes(pag));
1109 	ASSERT(pag->pagi_freecount > 0);
1110 
1111  restart_pagno:
1112 	cur = xfs_inobt_init_cursor(pag, tp, agbp);
1113 	/*
1114 	 * If pagino is 0 (this is the root inode allocation) use newino.
1115 	 * This must work because we've just allocated some.
1116 	 */
1117 	if (!pagino)
1118 		pagino = be32_to_cpu(agi->agi_newino);
1119 
1120 	error = xfs_check_agi_freecount(cur);
1121 	if (error)
1122 		goto error0;
1123 
1124 	/*
1125 	 * If in the same AG as the parent, try to get near the parent.
1126 	 */
1127 	if (pagno == pag_agno(pag)) {
1128 		int		doneleft;	/* done, to the left */
1129 		int		doneright;	/* done, to the right */
1130 
1131 		error = xfs_inobt_lookup(cur, pagino, XFS_LOOKUP_LE, &i);
1132 		if (error)
1133 			goto error0;
1134 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1135 			xfs_btree_mark_sick(cur);
1136 			error = -EFSCORRUPTED;
1137 			goto error0;
1138 		}
1139 
1140 		error = xfs_inobt_get_rec(cur, &rec, &j);
1141 		if (error)
1142 			goto error0;
1143 		if (XFS_IS_CORRUPT(mp, j != 1)) {
1144 			xfs_btree_mark_sick(cur);
1145 			error = -EFSCORRUPTED;
1146 			goto error0;
1147 		}
1148 
1149 		if (rec.ir_freecount > 0) {
1150 			/*
1151 			 * Found a free inode in the same chunk
1152 			 * as the parent, done.
1153 			 */
1154 			goto alloc_inode;
1155 		}
1156 
1157 
1158 		/*
1159 		 * In the same AG as parent, but parent's chunk is full.
1160 		 */
1161 
1162 		/* duplicate the cursor, search left & right simultaneously */
1163 		error = xfs_btree_dup_cursor(cur, &tcur);
1164 		if (error)
1165 			goto error0;
1166 
1167 		/*
1168 		 * Skip to last blocks looked up if same parent inode.
1169 		 */
1170 		if (pagino != NULLAGINO &&
1171 		    pag->pagl_pagino == pagino &&
1172 		    pag->pagl_leftrec != NULLAGINO &&
1173 		    pag->pagl_rightrec != NULLAGINO) {
1174 			error = xfs_ialloc_get_rec(tcur, pag->pagl_leftrec,
1175 						   &trec, &doneleft);
1176 			if (error)
1177 				goto error1;
1178 
1179 			error = xfs_ialloc_get_rec(cur, pag->pagl_rightrec,
1180 						   &rec, &doneright);
1181 			if (error)
1182 				goto error1;
1183 		} else {
1184 			/* search left with tcur, back up 1 record */
1185 			error = xfs_ialloc_next_rec(tcur, &trec, &doneleft, 1);
1186 			if (error)
1187 				goto error1;
1188 
1189 			/* search right with cur, go forward 1 record. */
1190 			error = xfs_ialloc_next_rec(cur, &rec, &doneright, 0);
1191 			if (error)
1192 				goto error1;
1193 		}
1194 
1195 		/*
1196 		 * Loop until we find an inode chunk with a free inode.
1197 		 */
1198 		while (--searchdistance > 0 && (!doneleft || !doneright)) {
1199 			int	useleft;  /* using left inode chunk this time */
1200 
1201 			/* figure out the closer block if both are valid. */
1202 			if (!doneleft && !doneright) {
1203 				useleft = pagino -
1204 				 (trec.ir_startino + XFS_INODES_PER_CHUNK - 1) <
1205 				  rec.ir_startino - pagino;
1206 			} else {
1207 				useleft = !doneleft;
1208 			}
1209 
1210 			/* free inodes to the left? */
1211 			if (useleft && trec.ir_freecount) {
1212 				xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1213 				cur = tcur;
1214 
1215 				pag->pagl_leftrec = trec.ir_startino;
1216 				pag->pagl_rightrec = rec.ir_startino;
1217 				pag->pagl_pagino = pagino;
1218 				rec = trec;
1219 				goto alloc_inode;
1220 			}
1221 
1222 			/* free inodes to the right? */
1223 			if (!useleft && rec.ir_freecount) {
1224 				xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
1225 
1226 				pag->pagl_leftrec = trec.ir_startino;
1227 				pag->pagl_rightrec = rec.ir_startino;
1228 				pag->pagl_pagino = pagino;
1229 				goto alloc_inode;
1230 			}
1231 
1232 			/* get next record to check */
1233 			if (useleft) {
1234 				error = xfs_ialloc_next_rec(tcur, &trec,
1235 								 &doneleft, 1);
1236 			} else {
1237 				error = xfs_ialloc_next_rec(cur, &rec,
1238 								 &doneright, 0);
1239 			}
1240 			if (error)
1241 				goto error1;
1242 		}
1243 
1244 		if (searchdistance <= 0) {
1245 			/*
1246 			 * Not in range - save last search
1247 			 * location and allocate a new inode
1248 			 */
1249 			xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
1250 			pag->pagl_leftrec = trec.ir_startino;
1251 			pag->pagl_rightrec = rec.ir_startino;
1252 			pag->pagl_pagino = pagino;
1253 
1254 		} else {
1255 			/*
1256 			 * We've reached the end of the btree. because
1257 			 * we are only searching a small chunk of the
1258 			 * btree each search, there is obviously free
1259 			 * inodes closer to the parent inode than we
1260 			 * are now. restart the search again.
1261 			 */
1262 			pag->pagl_pagino = NULLAGINO;
1263 			pag->pagl_leftrec = NULLAGINO;
1264 			pag->pagl_rightrec = NULLAGINO;
1265 			xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
1266 			xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1267 			goto restart_pagno;
1268 		}
1269 	}
1270 
1271 	/*
1272 	 * In a different AG from the parent.
1273 	 * See if the most recently allocated block has any free.
1274 	 */
1275 	if (agi->agi_newino != cpu_to_be32(NULLAGINO)) {
1276 		error = xfs_inobt_lookup(cur, be32_to_cpu(agi->agi_newino),
1277 					 XFS_LOOKUP_EQ, &i);
1278 		if (error)
1279 			goto error0;
1280 
1281 		if (i == 1) {
1282 			error = xfs_inobt_get_rec(cur, &rec, &j);
1283 			if (error)
1284 				goto error0;
1285 
1286 			if (j == 1 && rec.ir_freecount > 0) {
1287 				/*
1288 				 * The last chunk allocated in the group
1289 				 * still has a free inode.
1290 				 */
1291 				goto alloc_inode;
1292 			}
1293 		}
1294 	}
1295 
1296 	/*
1297 	 * None left in the last group, search the whole AG
1298 	 */
1299 	error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &i);
1300 	if (error)
1301 		goto error0;
1302 	if (XFS_IS_CORRUPT(mp, i != 1)) {
1303 		xfs_btree_mark_sick(cur);
1304 		error = -EFSCORRUPTED;
1305 		goto error0;
1306 	}
1307 
1308 	for (;;) {
1309 		error = xfs_inobt_get_rec(cur, &rec, &i);
1310 		if (error)
1311 			goto error0;
1312 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1313 			xfs_btree_mark_sick(cur);
1314 			error = -EFSCORRUPTED;
1315 			goto error0;
1316 		}
1317 		if (rec.ir_freecount > 0)
1318 			break;
1319 		error = xfs_btree_increment(cur, 0, &i);
1320 		if (error)
1321 			goto error0;
1322 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1323 			xfs_btree_mark_sick(cur);
1324 			error = -EFSCORRUPTED;
1325 			goto error0;
1326 		}
1327 	}
1328 
1329 alloc_inode:
1330 	offset = xfs_inobt_first_free_inode(&rec);
1331 	ASSERT(offset >= 0);
1332 	ASSERT(offset < XFS_INODES_PER_CHUNK);
1333 	ASSERT((XFS_AGINO_TO_OFFSET(mp, rec.ir_startino) %
1334 				   XFS_INODES_PER_CHUNK) == 0);
1335 	ino = xfs_agino_to_ino(pag, rec.ir_startino + offset);
1336 
1337 	if (xfs_ag_has_sickness(pag, XFS_SICK_AG_INODES)) {
1338 		error = xfs_dialloc_check_ino(pag, tp, ino);
1339 		if (error)
1340 			goto error0;
1341 	}
1342 
1343 	rec.ir_free &= ~XFS_INOBT_MASK(offset);
1344 	rec.ir_freecount--;
1345 	error = xfs_inobt_update(cur, &rec);
1346 	if (error)
1347 		goto error0;
1348 	be32_add_cpu(&agi->agi_freecount, -1);
1349 	xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
1350 	pag->pagi_freecount--;
1351 
1352 	error = xfs_check_agi_freecount(cur);
1353 	if (error)
1354 		goto error0;
1355 
1356 	xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1357 	xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -1);
1358 	*inop = ino;
1359 	return 0;
1360 error1:
1361 	xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
1362 error0:
1363 	xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1364 	return error;
1365 }
1366 
1367 /*
1368  * Use the free inode btree to allocate an inode based on distance from the
1369  * parent. Note that the provided cursor may be deleted and replaced.
1370  */
1371 STATIC int
1372 xfs_dialloc_ag_finobt_near(
1373 	xfs_agino_t			pagino,
1374 	struct xfs_btree_cur		**ocur,
1375 	struct xfs_inobt_rec_incore	*rec)
1376 {
1377 	struct xfs_btree_cur		*lcur = *ocur;	/* left search cursor */
1378 	struct xfs_btree_cur		*rcur;	/* right search cursor */
1379 	struct xfs_inobt_rec_incore	rrec;
1380 	int				error;
1381 	int				i, j;
1382 
1383 	error = xfs_inobt_lookup(lcur, pagino, XFS_LOOKUP_LE, &i);
1384 	if (error)
1385 		return error;
1386 
1387 	if (i == 1) {
1388 		error = xfs_inobt_get_rec(lcur, rec, &i);
1389 		if (error)
1390 			return error;
1391 		if (XFS_IS_CORRUPT(lcur->bc_mp, i != 1)) {
1392 			xfs_btree_mark_sick(lcur);
1393 			return -EFSCORRUPTED;
1394 		}
1395 
1396 		/*
1397 		 * See if we've landed in the parent inode record. The finobt
1398 		 * only tracks chunks with at least one free inode, so record
1399 		 * existence is enough.
1400 		 */
1401 		if (pagino >= rec->ir_startino &&
1402 		    pagino < (rec->ir_startino + XFS_INODES_PER_CHUNK))
1403 			return 0;
1404 	}
1405 
1406 	error = xfs_btree_dup_cursor(lcur, &rcur);
1407 	if (error)
1408 		return error;
1409 
1410 	error = xfs_inobt_lookup(rcur, pagino, XFS_LOOKUP_GE, &j);
1411 	if (error)
1412 		goto error_rcur;
1413 	if (j == 1) {
1414 		error = xfs_inobt_get_rec(rcur, &rrec, &j);
1415 		if (error)
1416 			goto error_rcur;
1417 		if (XFS_IS_CORRUPT(lcur->bc_mp, j != 1)) {
1418 			xfs_btree_mark_sick(lcur);
1419 			error = -EFSCORRUPTED;
1420 			goto error_rcur;
1421 		}
1422 	}
1423 
1424 	if (XFS_IS_CORRUPT(lcur->bc_mp, i != 1 && j != 1)) {
1425 		xfs_btree_mark_sick(lcur);
1426 		error = -EFSCORRUPTED;
1427 		goto error_rcur;
1428 	}
1429 	if (i == 1 && j == 1) {
1430 		/*
1431 		 * Both the left and right records are valid. Choose the closer
1432 		 * inode chunk to the target.
1433 		 */
1434 		if ((pagino - rec->ir_startino + XFS_INODES_PER_CHUNK - 1) >
1435 		    (rrec.ir_startino - pagino)) {
1436 			*rec = rrec;
1437 			xfs_btree_del_cursor(lcur, XFS_BTREE_NOERROR);
1438 			*ocur = rcur;
1439 		} else {
1440 			xfs_btree_del_cursor(rcur, XFS_BTREE_NOERROR);
1441 		}
1442 	} else if (j == 1) {
1443 		/* only the right record is valid */
1444 		*rec = rrec;
1445 		xfs_btree_del_cursor(lcur, XFS_BTREE_NOERROR);
1446 		*ocur = rcur;
1447 	} else if (i == 1) {
1448 		/* only the left record is valid */
1449 		xfs_btree_del_cursor(rcur, XFS_BTREE_NOERROR);
1450 	}
1451 
1452 	return 0;
1453 
1454 error_rcur:
1455 	xfs_btree_del_cursor(rcur, XFS_BTREE_ERROR);
1456 	return error;
1457 }
1458 
1459 /*
1460  * Use the free inode btree to find a free inode based on a newino hint. If
1461  * the hint is NULL, find the first free inode in the AG.
1462  */
1463 STATIC int
1464 xfs_dialloc_ag_finobt_newino(
1465 	struct xfs_agi			*agi,
1466 	struct xfs_btree_cur		*cur,
1467 	struct xfs_inobt_rec_incore	*rec)
1468 {
1469 	int error;
1470 	int i;
1471 
1472 	if (agi->agi_newino != cpu_to_be32(NULLAGINO)) {
1473 		error = xfs_inobt_lookup(cur, be32_to_cpu(agi->agi_newino),
1474 					 XFS_LOOKUP_EQ, &i);
1475 		if (error)
1476 			return error;
1477 		if (i == 1) {
1478 			error = xfs_inobt_get_rec(cur, rec, &i);
1479 			if (error)
1480 				return error;
1481 			if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1482 				xfs_btree_mark_sick(cur);
1483 				return -EFSCORRUPTED;
1484 			}
1485 			return 0;
1486 		}
1487 	}
1488 
1489 	/*
1490 	 * Find the first inode available in the AG.
1491 	 */
1492 	error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &i);
1493 	if (error)
1494 		return error;
1495 	if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1496 		xfs_btree_mark_sick(cur);
1497 		return -EFSCORRUPTED;
1498 	}
1499 
1500 	error = xfs_inobt_get_rec(cur, rec, &i);
1501 	if (error)
1502 		return error;
1503 	if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1504 		xfs_btree_mark_sick(cur);
1505 		return -EFSCORRUPTED;
1506 	}
1507 
1508 	return 0;
1509 }
1510 
1511 /*
1512  * Update the inobt based on a modification made to the finobt. Also ensure that
1513  * the records from both trees are equivalent post-modification.
1514  */
1515 STATIC int
1516 xfs_dialloc_ag_update_inobt(
1517 	struct xfs_btree_cur		*cur,	/* inobt cursor */
1518 	struct xfs_inobt_rec_incore	*frec,	/* finobt record */
1519 	int				offset) /* inode offset */
1520 {
1521 	struct xfs_inobt_rec_incore	rec;
1522 	int				error;
1523 	int				i;
1524 
1525 	error = xfs_inobt_lookup(cur, frec->ir_startino, XFS_LOOKUP_EQ, &i);
1526 	if (error)
1527 		return error;
1528 	if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1529 		xfs_btree_mark_sick(cur);
1530 		return -EFSCORRUPTED;
1531 	}
1532 
1533 	error = xfs_inobt_get_rec(cur, &rec, &i);
1534 	if (error)
1535 		return error;
1536 	if (XFS_IS_CORRUPT(cur->bc_mp, i != 1)) {
1537 		xfs_btree_mark_sick(cur);
1538 		return -EFSCORRUPTED;
1539 	}
1540 	ASSERT((XFS_AGINO_TO_OFFSET(cur->bc_mp, rec.ir_startino) %
1541 				   XFS_INODES_PER_CHUNK) == 0);
1542 
1543 	rec.ir_free &= ~XFS_INOBT_MASK(offset);
1544 	rec.ir_freecount--;
1545 
1546 	if (XFS_IS_CORRUPT(cur->bc_mp,
1547 			   rec.ir_free != frec->ir_free ||
1548 			   rec.ir_freecount != frec->ir_freecount)) {
1549 		xfs_btree_mark_sick(cur);
1550 		return -EFSCORRUPTED;
1551 	}
1552 
1553 	return xfs_inobt_update(cur, &rec);
1554 }
1555 
1556 /*
1557  * Allocate an inode using the free inode btree, if available. Otherwise, fall
1558  * back to the inobt search algorithm.
1559  *
1560  * The caller selected an AG for us, and made sure that free inodes are
1561  * available.
1562  */
1563 static int
1564 xfs_dialloc_ag(
1565 	struct xfs_perag	*pag,
1566 	struct xfs_trans	*tp,
1567 	struct xfs_buf		*agbp,
1568 	xfs_ino_t		parent,
1569 	xfs_ino_t		*inop)
1570 {
1571 	struct xfs_mount		*mp = tp->t_mountp;
1572 	struct xfs_agi			*agi = agbp->b_addr;
1573 	xfs_agnumber_t			pagno = XFS_INO_TO_AGNO(mp, parent);
1574 	xfs_agino_t			pagino = XFS_INO_TO_AGINO(mp, parent);
1575 	struct xfs_btree_cur		*cur;	/* finobt cursor */
1576 	struct xfs_btree_cur		*icur;	/* inobt cursor */
1577 	struct xfs_inobt_rec_incore	rec;
1578 	xfs_ino_t			ino;
1579 	int				error;
1580 	int				offset;
1581 	int				i;
1582 
1583 	if (!xfs_has_finobt(mp))
1584 		return xfs_dialloc_ag_inobt(pag, tp, agbp, parent, inop);
1585 
1586 	/*
1587 	 * If pagino is 0 (this is the root inode allocation) use newino.
1588 	 * This must work because we've just allocated some.
1589 	 */
1590 	if (!pagino)
1591 		pagino = be32_to_cpu(agi->agi_newino);
1592 
1593 	cur = xfs_finobt_init_cursor(pag, tp, agbp);
1594 
1595 	error = xfs_check_agi_freecount(cur);
1596 	if (error)
1597 		goto error_cur;
1598 
1599 	/*
1600 	 * The search algorithm depends on whether we're in the same AG as the
1601 	 * parent. If so, find the closest available inode to the parent. If
1602 	 * not, consider the agi hint or find the first free inode in the AG.
1603 	 */
1604 	if (pag_agno(pag) == pagno)
1605 		error = xfs_dialloc_ag_finobt_near(pagino, &cur, &rec);
1606 	else
1607 		error = xfs_dialloc_ag_finobt_newino(agi, cur, &rec);
1608 	if (error)
1609 		goto error_cur;
1610 
1611 	offset = xfs_inobt_first_free_inode(&rec);
1612 	ASSERT(offset >= 0);
1613 	ASSERT(offset < XFS_INODES_PER_CHUNK);
1614 	ASSERT((XFS_AGINO_TO_OFFSET(mp, rec.ir_startino) %
1615 				   XFS_INODES_PER_CHUNK) == 0);
1616 	ino = xfs_agino_to_ino(pag, rec.ir_startino + offset);
1617 
1618 	if (xfs_ag_has_sickness(pag, XFS_SICK_AG_INODES)) {
1619 		error = xfs_dialloc_check_ino(pag, tp, ino);
1620 		if (error)
1621 			goto error_cur;
1622 	}
1623 
1624 	/*
1625 	 * Modify or remove the finobt record.
1626 	 */
1627 	rec.ir_free &= ~XFS_INOBT_MASK(offset);
1628 	rec.ir_freecount--;
1629 	if (rec.ir_freecount) {
1630 		error = xfs_inobt_update(cur, &rec);
1631 		if (error)
1632 			goto error_cur;
1633 	} else {
1634 		error = xfs_btree_delete(cur, &i);
1635 		if (error)
1636 			goto error_cur;
1637 		if (XFS_IS_CORRUPT(mp, i != 1)) {
1638 			xfs_btree_mark_sick(cur);
1639 			error = -EFSCORRUPTED;
1640 			goto error_cur;
1641 		}
1642 	}
1643 
1644 	/*
1645 	 * The finobt has now been updated appropriately. We haven't updated the
1646 	 * agi and superblock yet, so we can create an inobt cursor and validate
1647 	 * the original freecount. If all is well, make the equivalent update to
1648 	 * the inobt using the finobt record and offset information.
1649 	 */
1650 	icur = xfs_inobt_init_cursor(pag, tp, agbp);
1651 
1652 	error = xfs_check_agi_freecount(icur);
1653 	if (error)
1654 		goto error_icur;
1655 
1656 	error = xfs_dialloc_ag_update_inobt(icur, &rec, offset);
1657 	if (error)
1658 		goto error_icur;
1659 
1660 	/*
1661 	 * Both trees have now been updated. We must update the perag and
1662 	 * superblock before we can check the freecount for each btree.
1663 	 */
1664 	be32_add_cpu(&agi->agi_freecount, -1);
1665 	xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
1666 	pag->pagi_freecount--;
1667 
1668 	xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -1);
1669 
1670 	error = xfs_check_agi_freecount(icur);
1671 	if (error)
1672 		goto error_icur;
1673 	error = xfs_check_agi_freecount(cur);
1674 	if (error)
1675 		goto error_icur;
1676 
1677 	xfs_btree_del_cursor(icur, XFS_BTREE_NOERROR);
1678 	xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1679 	*inop = ino;
1680 	return 0;
1681 
1682 error_icur:
1683 	xfs_btree_del_cursor(icur, XFS_BTREE_ERROR);
1684 error_cur:
1685 	xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1686 	return error;
1687 }
1688 
1689 static int
1690 xfs_dialloc_roll(
1691 	struct xfs_trans	**tpp,
1692 	struct xfs_buf		*agibp)
1693 {
1694 	struct xfs_trans	*tp = *tpp;
1695 	struct xfs_dquot_acct	*dqinfo;
1696 	int			error;
1697 
1698 	/*
1699 	 * Hold to on to the agibp across the commit so no other allocation can
1700 	 * come in and take the free inodes we just allocated for our caller.
1701 	 */
1702 	xfs_trans_bhold(tp, agibp);
1703 
1704 	/*
1705 	 * We want the quota changes to be associated with the next transaction,
1706 	 * NOT this one. So, detach the dqinfo from this and attach it to the
1707 	 * next transaction.
1708 	 */
1709 	dqinfo = tp->t_dqinfo;
1710 	tp->t_dqinfo = NULL;
1711 
1712 	error = xfs_trans_roll(&tp);
1713 
1714 	/* Re-attach the quota info that we detached from prev trx. */
1715 	tp->t_dqinfo = dqinfo;
1716 
1717 	/*
1718 	 * Join the buffer even on commit error so that the buffer is released
1719 	 * when the caller cancels the transaction and doesn't have to handle
1720 	 * this error case specially.
1721 	 */
1722 	xfs_trans_bjoin(tp, agibp);
1723 	*tpp = tp;
1724 	return error;
1725 }
1726 
1727 static bool
1728 xfs_dialloc_good_ag(
1729 	struct xfs_perag	*pag,
1730 	struct xfs_trans	*tp,
1731 	umode_t			mode,
1732 	int			flags,
1733 	bool			ok_alloc)
1734 {
1735 	struct xfs_mount	*mp = tp->t_mountp;
1736 	xfs_extlen_t		ineed;
1737 	xfs_extlen_t		longest = 0;
1738 	int			needspace;
1739 	int			error;
1740 
1741 	if (!pag)
1742 		return false;
1743 	if (!xfs_perag_allows_inodes(pag))
1744 		return false;
1745 
1746 	if (!xfs_perag_initialised_agi(pag)) {
1747 		error = xfs_ialloc_read_agi(pag, tp, 0, NULL);
1748 		if (error)
1749 			return false;
1750 	}
1751 
1752 	if (pag->pagi_freecount)
1753 		return true;
1754 	if (!ok_alloc)
1755 		return false;
1756 
1757 	if (!xfs_perag_initialised_agf(pag)) {
1758 		error = xfs_alloc_read_agf(pag, tp, flags, NULL);
1759 		if (error)
1760 			return false;
1761 	}
1762 
1763 	/*
1764 	 * Check that there is enough free space for the file plus a chunk of
1765 	 * inodes if we need to allocate some. If this is the first pass across
1766 	 * the AGs, take into account the potential space needed for alignment
1767 	 * of inode chunks when checking the longest contiguous free space in
1768 	 * the AG - this prevents us from getting ENOSPC because we have free
1769 	 * space larger than ialloc_blks but alignment constraints prevent us
1770 	 * from using it.
1771 	 *
1772 	 * If we can't find an AG with space for full alignment slack to be
1773 	 * taken into account, we must be near ENOSPC in all AGs.  Hence we
1774 	 * don't include alignment for the second pass and so if we fail
1775 	 * allocation due to alignment issues then it is most likely a real
1776 	 * ENOSPC condition.
1777 	 *
1778 	 * XXX(dgc): this calculation is now bogus thanks to the per-ag
1779 	 * reservations that xfs_alloc_fix_freelist() now does via
1780 	 * xfs_alloc_space_available(). When the AG fills up, pagf_freeblks will
1781 	 * be more than large enough for the check below to succeed, but
1782 	 * xfs_alloc_space_available() will fail because of the non-zero
1783 	 * metadata reservation and hence we won't actually be able to allocate
1784 	 * more inodes in this AG. We do soooo much unnecessary work near ENOSPC
1785 	 * because of this.
1786 	 */
1787 	ineed = M_IGEO(mp)->ialloc_min_blks;
1788 	if (flags && ineed > 1)
1789 		ineed += M_IGEO(mp)->cluster_align;
1790 	longest = pag->pagf_longest;
1791 	if (!longest)
1792 		longest = pag->pagf_flcount > 0;
1793 	needspace = S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode);
1794 
1795 	if (pag->pagf_freeblks < needspace + ineed || longest < ineed)
1796 		return false;
1797 	return true;
1798 }
1799 
1800 static int
1801 xfs_dialloc_try_ag(
1802 	struct xfs_perag	*pag,
1803 	struct xfs_trans	**tpp,
1804 	xfs_ino_t		parent,
1805 	xfs_ino_t		*new_ino,
1806 	bool			ok_alloc)
1807 {
1808 	struct xfs_buf		*agbp;
1809 	xfs_ino_t		ino;
1810 	int			error;
1811 
1812 	/*
1813 	 * Then read in the AGI buffer and recheck with the AGI buffer
1814 	 * lock held.
1815 	 */
1816 	error = xfs_ialloc_read_agi(pag, *tpp, 0, &agbp);
1817 	if (error)
1818 		return error;
1819 
1820 	if (!pag->pagi_freecount) {
1821 		if (!ok_alloc) {
1822 			error = -EAGAIN;
1823 			goto out_release;
1824 		}
1825 
1826 		error = xfs_ialloc_ag_alloc(pag, *tpp, agbp);
1827 		if (error < 0)
1828 			goto out_release;
1829 
1830 		/*
1831 		 * We successfully allocated space for an inode cluster in this
1832 		 * AG.  Roll the transaction so that we can allocate one of the
1833 		 * new inodes.
1834 		 */
1835 		ASSERT(pag->pagi_freecount > 0);
1836 		error = xfs_dialloc_roll(tpp, agbp);
1837 		if (error)
1838 			goto out_release;
1839 	}
1840 
1841 	/* Allocate an inode in the found AG */
1842 	error = xfs_dialloc_ag(pag, *tpp, agbp, parent, &ino);
1843 	if (!error)
1844 		*new_ino = ino;
1845 	return error;
1846 
1847 out_release:
1848 	xfs_trans_brelse(*tpp, agbp);
1849 	return error;
1850 }
1851 
1852 /*
1853  * Pick an AG for the new inode.
1854  *
1855  * Directories, symlinks, and regular files frequently allocate at least one
1856  * block, so factor that potential expansion when we examine whether an AG has
1857  * enough space for file creation.  Try to keep metadata files all in the same
1858  * AG.
1859  */
1860 static inline xfs_agnumber_t
1861 xfs_dialloc_pick_ag(
1862 	struct xfs_mount	*mp,
1863 	struct xfs_inode	*dp,
1864 	umode_t			mode)
1865 {
1866 	xfs_agnumber_t		start_agno;
1867 
1868 	if (!dp)
1869 		return 0;
1870 	if (xfs_is_metadir_inode(dp)) {
1871 		if (mp->m_sb.sb_logstart)
1872 			return XFS_FSB_TO_AGNO(mp, mp->m_sb.sb_logstart);
1873 		return 0;
1874 	}
1875 
1876 	if (S_ISDIR(mode))
1877 		return (atomic_inc_return(&mp->m_agirotor) - 1) % mp->m_maxagi;
1878 
1879 	start_agno = XFS_INODE_TO_AGNO(dp);
1880 	if (start_agno >= mp->m_maxagi)
1881 		start_agno = 0;
1882 
1883 	return start_agno;
1884 }
1885 
1886 /*
1887  * Allocate an on-disk inode.
1888  *
1889  * Mode is used to tell whether the new inode is a directory and hence where to
1890  * locate it. The on-disk inode that is allocated will be returned in @new_ino
1891  * on success, otherwise an error will be set to indicate the failure (e.g.
1892  * -ENOSPC).
1893  */
1894 int
1895 xfs_dialloc(
1896 	struct xfs_trans	**tpp,
1897 	const struct xfs_icreate_args *args,
1898 	xfs_ino_t		*new_ino)
1899 {
1900 	struct xfs_mount	*mp = (*tpp)->t_mountp;
1901 	struct xfs_perag	*pag;
1902 	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
1903 	xfs_ino_t		ino = NULLFSINO;
1904 	xfs_ino_t		parent = args->pip ? I_INO(args->pip) : 0;
1905 	xfs_agnumber_t		agno;
1906 	xfs_agnumber_t		start_agno;
1907 	umode_t			mode = args->mode & S_IFMT;
1908 	bool			ok_alloc = true;
1909 	bool			low_space = false;
1910 	int			flags;
1911 	int			error = 0;
1912 
1913 	start_agno = xfs_dialloc_pick_ag(mp, args->pip, mode);
1914 
1915 	/*
1916 	 * If we have already hit the ceiling of inode blocks then clear
1917 	 * ok_alloc so we scan all available agi structures for a free
1918 	 * inode.
1919 	 *
1920 	 * Read rough value of mp->m_icount by percpu_counter_read_positive,
1921 	 * which will sacrifice the preciseness but improve the performance.
1922 	 */
1923 	if (igeo->maxicount &&
1924 	    percpu_counter_read_positive(&mp->m_icount) + igeo->ialloc_inos
1925 							> igeo->maxicount) {
1926 		ok_alloc = false;
1927 	}
1928 
1929 	/*
1930 	 * If we are near to ENOSPC, we want to prefer allocation from AGs that
1931 	 * have free inodes in them rather than use up free space allocating new
1932 	 * inode chunks. Hence we turn off allocation for the first non-blocking
1933 	 * pass through the AGs if we are near ENOSPC to consume free inodes
1934 	 * that we can immediately allocate, but then we allow allocation on the
1935 	 * second pass if we fail to find an AG with free inodes in it.
1936 	 */
1937 	if (xfs_estimate_freecounter(mp, XC_FREE_BLOCKS) <
1938 			mp->m_low_space[XFS_LOWSP_1_PCNT]) {
1939 		ok_alloc = false;
1940 		low_space = true;
1941 	}
1942 
1943 	/*
1944 	 * Loop until we find an allocation group that either has free inodes
1945 	 * or in which we can allocate some inodes.  Iterate through the
1946 	 * allocation groups upward, wrapping at the end.
1947 	 */
1948 	flags = XFS_ALLOC_FLAG_TRYLOCK;
1949 retry:
1950 	for_each_perag_wrap_at(mp, start_agno, mp->m_maxagi, agno, pag) {
1951 		if (xfs_dialloc_good_ag(pag, *tpp, mode, flags, ok_alloc)) {
1952 			error = xfs_dialloc_try_ag(pag, tpp, parent,
1953 					&ino, ok_alloc);
1954 			if (error != -EAGAIN)
1955 				break;
1956 			error = 0;
1957 		}
1958 
1959 		if (xfs_is_shutdown(mp)) {
1960 			error = -EFSCORRUPTED;
1961 			break;
1962 		}
1963 	}
1964 	if (pag)
1965 		xfs_perag_rele(pag);
1966 	if (error)
1967 		return error;
1968 	if (ino == NULLFSINO) {
1969 		if (flags) {
1970 			flags = 0;
1971 			if (low_space)
1972 				ok_alloc = true;
1973 			goto retry;
1974 		}
1975 		return -ENOSPC;
1976 	}
1977 
1978 	/*
1979 	 * Protect against obviously corrupt allocation btree records. Later
1980 	 * xfs_iget checks will catch re-allocation of other active in-memory
1981 	 * and on-disk inodes. If we don't catch reallocating the parent inode
1982 	 * here we will deadlock in xfs_iget() so we have to do these checks
1983 	 * first.
1984 	 */
1985 	if (ino == parent || !xfs_verify_dir_ino(mp, ino)) {
1986 		xfs_alert(mp, "Allocated a known in-use inode 0x%llx!", ino);
1987 		xfs_agno_mark_sick(mp, XFS_INO_TO_AGNO(mp, ino),
1988 				XFS_SICK_AG_INOBT);
1989 		return -EFSCORRUPTED;
1990 	}
1991 
1992 	*new_ino = ino;
1993 	return 0;
1994 }
1995 
1996 /*
1997  * Free the blocks of an inode chunk. We must consider that the inode chunk
1998  * might be sparse and only free the regions that are allocated as part of the
1999  * chunk.
2000  */
2001 static int
2002 xfs_difree_inode_chunk(
2003 	struct xfs_trans		*tp,
2004 	struct xfs_perag		*pag,
2005 	struct xfs_inobt_rec_incore	*rec)
2006 {
2007 	struct xfs_mount		*mp = tp->t_mountp;
2008 	xfs_agblock_t			sagbno = XFS_AGINO_TO_AGBNO(mp,
2009 							rec->ir_startino);
2010 	int				startidx, endidx;
2011 	int				nextbit;
2012 	xfs_agblock_t			agbno;
2013 	int				contigblk;
2014 	DECLARE_BITMAP(holemask, XFS_INOBT_HOLEMASK_BITS);
2015 
2016 	if (!xfs_inobt_issparse(rec->ir_holemask)) {
2017 		/* not sparse, calculate extent info directly */
2018 		return xfs_free_extent_later(tp, xfs_agbno_to_fsb(pag, sagbno),
2019 				M_IGEO(mp)->ialloc_blks, &XFS_RMAP_OINFO_INODES,
2020 				XFS_AG_RESV_NONE, 0);
2021 	}
2022 
2023 	/* holemask is only 16-bits (fits in an unsigned long) */
2024 	ASSERT(sizeof(rec->ir_holemask) <= sizeof(holemask[0]));
2025 	holemask[0] = rec->ir_holemask;
2026 
2027 	/*
2028 	 * Find contiguous ranges of zeroes (i.e., allocated regions) in the
2029 	 * holemask and convert the start/end index of each range to an extent.
2030 	 * We start with the start and end index both pointing at the first 0 in
2031 	 * the mask.
2032 	 */
2033 	startidx = endidx = find_first_zero_bit(holemask,
2034 						XFS_INOBT_HOLEMASK_BITS);
2035 	nextbit = startidx + 1;
2036 	while (startidx < XFS_INOBT_HOLEMASK_BITS) {
2037 		int error;
2038 
2039 		nextbit = find_next_zero_bit(holemask, XFS_INOBT_HOLEMASK_BITS,
2040 					     nextbit);
2041 		/*
2042 		 * If the next zero bit is contiguous, update the end index of
2043 		 * the current range and continue.
2044 		 */
2045 		if (nextbit != XFS_INOBT_HOLEMASK_BITS &&
2046 		    nextbit == endidx + 1) {
2047 			endidx = nextbit;
2048 			goto next;
2049 		}
2050 
2051 		/*
2052 		 * nextbit is not contiguous with the current end index. Convert
2053 		 * the current start/end to an extent and add it to the free
2054 		 * list.
2055 		 */
2056 		agbno = sagbno + (startidx * XFS_INODES_PER_HOLEMASK_BIT) /
2057 				  mp->m_sb.sb_inopblock;
2058 		contigblk = ((endidx - startidx + 1) *
2059 			     XFS_INODES_PER_HOLEMASK_BIT) /
2060 			    mp->m_sb.sb_inopblock;
2061 
2062 		ASSERT(agbno % mp->m_sb.sb_spino_align == 0);
2063 		ASSERT(contigblk % mp->m_sb.sb_spino_align == 0);
2064 		error = xfs_free_extent_later(tp, xfs_agbno_to_fsb(pag, agbno),
2065 				contigblk, &XFS_RMAP_OINFO_INODES,
2066 				XFS_AG_RESV_NONE, 0);
2067 		if (error)
2068 			return error;
2069 
2070 		/* reset range to current bit and carry on... */
2071 		startidx = endidx = nextbit;
2072 
2073 next:
2074 		nextbit++;
2075 	}
2076 	return 0;
2077 }
2078 
2079 STATIC int
2080 xfs_difree_inobt(
2081 	struct xfs_perag		*pag,
2082 	struct xfs_trans		*tp,
2083 	struct xfs_buf			*agbp,
2084 	xfs_agino_t			agino,
2085 	struct xfs_icluster		*xic,
2086 	struct xfs_inobt_rec_incore	*orec)
2087 {
2088 	struct xfs_mount		*mp = pag_mount(pag);
2089 	struct xfs_agi			*agi = agbp->b_addr;
2090 	struct xfs_btree_cur		*cur;
2091 	struct xfs_inobt_rec_incore	rec;
2092 	int				ilen;
2093 	int				error;
2094 	int				i;
2095 	int				off;
2096 
2097 	ASSERT(agi->agi_magicnum == cpu_to_be32(XFS_AGI_MAGIC));
2098 	ASSERT(XFS_AGINO_TO_AGBNO(mp, agino) < be32_to_cpu(agi->agi_length));
2099 
2100 	/*
2101 	 * Initialize the cursor.
2102 	 */
2103 	cur = xfs_inobt_init_cursor(pag, tp, agbp);
2104 
2105 	error = xfs_check_agi_freecount(cur);
2106 	if (error)
2107 		goto error0;
2108 
2109 	/*
2110 	 * Look for the entry describing this inode.
2111 	 */
2112 	if ((error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_LE, &i))) {
2113 		xfs_warn(mp, "%s: xfs_inobt_lookup() returned error %d.",
2114 			__func__, error);
2115 		goto error0;
2116 	}
2117 	if (XFS_IS_CORRUPT(mp, i != 1)) {
2118 		xfs_btree_mark_sick(cur);
2119 		error = -EFSCORRUPTED;
2120 		goto error0;
2121 	}
2122 	error = xfs_inobt_get_rec(cur, &rec, &i);
2123 	if (error) {
2124 		xfs_warn(mp, "%s: xfs_inobt_get_rec() returned error %d.",
2125 			__func__, error);
2126 		goto error0;
2127 	}
2128 	if (XFS_IS_CORRUPT(mp, i != 1)) {
2129 		xfs_btree_mark_sick(cur);
2130 		error = -EFSCORRUPTED;
2131 		goto error0;
2132 	}
2133 	/*
2134 	 * Get the offset in the inode chunk.
2135 	 */
2136 	off = agino - rec.ir_startino;
2137 	ASSERT(off >= 0 && off < XFS_INODES_PER_CHUNK);
2138 	ASSERT(!(rec.ir_free & XFS_INOBT_MASK(off)));
2139 	/*
2140 	 * Mark the inode free & increment the count.
2141 	 */
2142 	rec.ir_free |= XFS_INOBT_MASK(off);
2143 	rec.ir_freecount++;
2144 
2145 	/*
2146 	 * When an inode chunk is free, it becomes eligible for removal. Don't
2147 	 * remove the chunk if the block size is large enough for multiple inode
2148 	 * chunks (that might not be free).
2149 	 */
2150 	if (rec.ir_free == XFS_INOBT_ALL_FREE &&
2151 	    mp->m_sb.sb_inopblock <= XFS_INODES_PER_CHUNK) {
2152 		xic->deleted = true;
2153 		xic->first_ino = xfs_agino_to_ino(pag, rec.ir_startino);
2154 		xic->alloc = xfs_inobt_irec_to_allocmask(&rec);
2155 
2156 		/*
2157 		 * Remove the inode cluster from the AGI B+Tree, adjust the
2158 		 * AGI and Superblock inode counts, and mark the disk space
2159 		 * to be freed when the transaction is committed.
2160 		 */
2161 		ilen = rec.ir_freecount;
2162 		be32_add_cpu(&agi->agi_count, -ilen);
2163 		be32_add_cpu(&agi->agi_freecount, -(ilen - 1));
2164 		xfs_ialloc_log_agi(tp, agbp, XFS_AGI_COUNT | XFS_AGI_FREECOUNT);
2165 		pag->pagi_freecount -= ilen - 1;
2166 		pag->pagi_count -= ilen;
2167 		xfs_trans_mod_sb(tp, XFS_TRANS_SB_ICOUNT, -ilen);
2168 		xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -(ilen - 1));
2169 
2170 		if ((error = xfs_btree_delete(cur, &i))) {
2171 			xfs_warn(mp, "%s: xfs_btree_delete returned error %d.",
2172 				__func__, error);
2173 			goto error0;
2174 		}
2175 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2176 			xfs_btree_mark_sick(cur);
2177 			error = -EFSCORRUPTED;
2178 			goto error0;
2179 		}
2180 
2181 		error = xfs_difree_inode_chunk(tp, pag, &rec);
2182 		if (error)
2183 			goto error0;
2184 	} else {
2185 		xic->deleted = false;
2186 
2187 		error = xfs_inobt_update(cur, &rec);
2188 		if (error) {
2189 			xfs_warn(mp, "%s: xfs_inobt_update returned error %d.",
2190 				__func__, error);
2191 			goto error0;
2192 		}
2193 
2194 		/*
2195 		 * Change the inode free counts and log the ag/sb changes.
2196 		 */
2197 		be32_add_cpu(&agi->agi_freecount, 1);
2198 		xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
2199 		pag->pagi_freecount++;
2200 		xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, 1);
2201 	}
2202 
2203 	error = xfs_check_agi_freecount(cur);
2204 	if (error)
2205 		goto error0;
2206 
2207 	*orec = rec;
2208 	xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
2209 	return 0;
2210 
2211 error0:
2212 	xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
2213 	return error;
2214 }
2215 
2216 /*
2217  * Free an inode in the free inode btree.
2218  */
2219 STATIC int
2220 xfs_difree_finobt(
2221 	struct xfs_perag		*pag,
2222 	struct xfs_trans		*tp,
2223 	struct xfs_buf			*agbp,
2224 	xfs_agino_t			agino,
2225 	struct xfs_inobt_rec_incore	*ibtrec) /* inobt record */
2226 {
2227 	struct xfs_mount		*mp = pag_mount(pag);
2228 	struct xfs_btree_cur		*cur;
2229 	struct xfs_inobt_rec_incore	rec;
2230 	int				offset = agino - ibtrec->ir_startino;
2231 	int				error;
2232 	int				i;
2233 
2234 	cur = xfs_finobt_init_cursor(pag, tp, agbp);
2235 
2236 	error = xfs_inobt_lookup(cur, ibtrec->ir_startino, XFS_LOOKUP_EQ, &i);
2237 	if (error)
2238 		goto error;
2239 	if (i == 0) {
2240 		/*
2241 		 * If the record does not exist in the finobt, we must have just
2242 		 * freed an inode in a previously fully allocated chunk. If not,
2243 		 * something is out of sync.
2244 		 */
2245 		if (XFS_IS_CORRUPT(mp, ibtrec->ir_freecount != 1)) {
2246 			xfs_btree_mark_sick(cur);
2247 			error = -EFSCORRUPTED;
2248 			goto error;
2249 		}
2250 
2251 		error = xfs_inobt_insert_rec(cur, ibtrec->ir_holemask,
2252 					     ibtrec->ir_count,
2253 					     ibtrec->ir_freecount,
2254 					     ibtrec->ir_free, &i);
2255 		if (error)
2256 			goto error;
2257 		ASSERT(i == 1);
2258 
2259 		goto out;
2260 	}
2261 
2262 	/*
2263 	 * Read and update the existing record. We could just copy the ibtrec
2264 	 * across here, but that would defeat the purpose of having redundant
2265 	 * metadata. By making the modifications independently, we can catch
2266 	 * corruptions that we wouldn't see if we just copied from one record
2267 	 * to another.
2268 	 */
2269 	error = xfs_inobt_get_rec(cur, &rec, &i);
2270 	if (error)
2271 		goto error;
2272 	if (XFS_IS_CORRUPT(mp, i != 1)) {
2273 		xfs_btree_mark_sick(cur);
2274 		error = -EFSCORRUPTED;
2275 		goto error;
2276 	}
2277 
2278 	rec.ir_free |= XFS_INOBT_MASK(offset);
2279 	rec.ir_freecount++;
2280 
2281 	if (XFS_IS_CORRUPT(mp,
2282 			   rec.ir_free != ibtrec->ir_free ||
2283 			   rec.ir_freecount != ibtrec->ir_freecount)) {
2284 		xfs_btree_mark_sick(cur);
2285 		error = -EFSCORRUPTED;
2286 		goto error;
2287 	}
2288 
2289 	/*
2290 	 * The content of inobt records should always match between the inobt
2291 	 * and finobt. The lifecycle of records in the finobt is different from
2292 	 * the inobt in that the finobt only tracks records with at least one
2293 	 * free inode. Hence, if all of the inodes are free and we aren't
2294 	 * keeping inode chunks permanently on disk, remove the record.
2295 	 * Otherwise, update the record with the new information.
2296 	 *
2297 	 * Note that we currently can't free chunks when the block size is large
2298 	 * enough for multiple chunks. Leave the finobt record to remain in sync
2299 	 * with the inobt.
2300 	 */
2301 	if (rec.ir_free == XFS_INOBT_ALL_FREE &&
2302 	    mp->m_sb.sb_inopblock <= XFS_INODES_PER_CHUNK) {
2303 		error = xfs_btree_delete(cur, &i);
2304 		if (error)
2305 			goto error;
2306 		if (XFS_IS_CORRUPT(mp, i != 1)) {
2307 			xfs_btree_mark_sick(cur);
2308 			error = -EFSCORRUPTED;
2309 			goto error;
2310 		}
2311 	} else {
2312 		error = xfs_inobt_update(cur, &rec);
2313 		if (error)
2314 			goto error;
2315 	}
2316 
2317 out:
2318 	error = xfs_check_agi_freecount(cur);
2319 	if (error)
2320 		goto error;
2321 
2322 	xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
2323 	return 0;
2324 
2325 error:
2326 	xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
2327 	return error;
2328 }
2329 
2330 /*
2331  * Free disk inode.  Carefully avoids touching the incore inode, all
2332  * manipulations incore are the caller's responsibility.
2333  * The on-disk inode is not changed by this operation, only the
2334  * btree (free inode mask) is changed.
2335  */
2336 int
2337 xfs_difree(
2338 	struct xfs_trans	*tp,
2339 	struct xfs_perag	*pag,
2340 	xfs_ino_t		inode,
2341 	struct xfs_icluster	*xic)
2342 {
2343 	/* REFERENCED */
2344 	xfs_agblock_t		agbno;	/* block number containing inode */
2345 	struct xfs_buf		*agbp;	/* buffer for allocation group header */
2346 	xfs_agino_t		agino;	/* allocation group inode number */
2347 	int			error;	/* error return value */
2348 	struct xfs_mount	*mp = tp->t_mountp;
2349 	struct xfs_inobt_rec_incore rec;/* btree record */
2350 
2351 	/*
2352 	 * Break up inode number into its components.
2353 	 */
2354 	if (pag_agno(pag) != XFS_INO_TO_AGNO(mp, inode)) {
2355 		xfs_warn(mp, "%s: agno != pag_agno(pag) (%d != %d).",
2356 			__func__, XFS_INO_TO_AGNO(mp, inode), pag_agno(pag));
2357 		ASSERT(0);
2358 		return -EINVAL;
2359 	}
2360 	agino = XFS_INO_TO_AGINO(mp, inode);
2361 	if (inode != xfs_agino_to_ino(pag, agino))  {
2362 		xfs_warn(mp, "%s: inode != xfs_agino_to_ino() (%llu != %llu).",
2363 			__func__, (unsigned long long)inode,
2364 			(unsigned long long)xfs_agino_to_ino(pag, agino));
2365 		ASSERT(0);
2366 		return -EINVAL;
2367 	}
2368 	agbno = XFS_AGINO_TO_AGBNO(mp, agino);
2369 	if (agbno >= xfs_ag_block_count(mp, pag_agno(pag))) {
2370 		xfs_warn(mp, "%s: agbno >= xfs_ag_block_count (%d >= %d).",
2371 			__func__, agbno, xfs_ag_block_count(mp, pag_agno(pag)));
2372 		ASSERT(0);
2373 		return -EINVAL;
2374 	}
2375 	/*
2376 	 * Get the allocation group header.
2377 	 */
2378 	error = xfs_ialloc_read_agi(pag, tp, 0, &agbp);
2379 	if (error) {
2380 		xfs_warn(mp, "%s: xfs_ialloc_read_agi() returned error %d.",
2381 			__func__, error);
2382 		return error;
2383 	}
2384 
2385 	/*
2386 	 * Fix up the inode allocation btree.
2387 	 */
2388 	error = xfs_difree_inobt(pag, tp, agbp, agino, xic, &rec);
2389 	if (error)
2390 		goto error0;
2391 
2392 	/*
2393 	 * Fix up the free inode btree.
2394 	 */
2395 	if (xfs_has_finobt(mp)) {
2396 		error = xfs_difree_finobt(pag, tp, agbp, agino, &rec);
2397 		if (error)
2398 			goto error0;
2399 	}
2400 
2401 	return 0;
2402 
2403 error0:
2404 	return error;
2405 }
2406 
2407 STATIC int
2408 xfs_imap_lookup(
2409 	struct xfs_perag	*pag,
2410 	struct xfs_trans	*tp,
2411 	xfs_agino_t		agino,
2412 	xfs_agblock_t		agbno,
2413 	xfs_agblock_t		*chunk_agbno,
2414 	xfs_agblock_t		*offset_agbno,
2415 	int			flags)
2416 {
2417 	struct xfs_mount	*mp = pag_mount(pag);
2418 	struct xfs_inobt_rec_incore rec;
2419 	struct xfs_btree_cur	*cur;
2420 	struct xfs_buf		*agbp;
2421 	int			error;
2422 	int			i;
2423 
2424 	error = xfs_ialloc_read_agi(pag, tp, 0, &agbp);
2425 	if (error) {
2426 		xfs_alert(mp,
2427 			"%s: xfs_ialloc_read_agi() returned error %d, agno %d",
2428 			__func__, error, pag_agno(pag));
2429 		return error;
2430 	}
2431 
2432 	/*
2433 	 * Lookup the inode record for the given agino. If the record cannot be
2434 	 * found, then it's an invalid inode number and we should abort. Once
2435 	 * we have a record, we need to ensure it contains the inode number
2436 	 * we are looking up.
2437 	 */
2438 	cur = xfs_inobt_init_cursor(pag, tp, agbp);
2439 	error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_LE, &i);
2440 	if (!error) {
2441 		if (i)
2442 			error = xfs_inobt_get_rec(cur, &rec, &i);
2443 		if (!error && i == 0)
2444 			error = -EINVAL;
2445 	}
2446 
2447 	xfs_trans_brelse(tp, agbp);
2448 	xfs_btree_del_cursor(cur, error);
2449 	if (error)
2450 		return error;
2451 
2452 	/* check that the returned record contains the required inode */
2453 	if (rec.ir_startino > agino ||
2454 	    rec.ir_startino + M_IGEO(mp)->ialloc_inos <= agino)
2455 		return -EINVAL;
2456 
2457 	/* for untrusted inodes check it is allocated first */
2458 	if ((flags & XFS_IGET_UNTRUSTED) &&
2459 	    (rec.ir_free & XFS_INOBT_MASK(agino - rec.ir_startino)))
2460 		return -EINVAL;
2461 
2462 	*chunk_agbno = XFS_AGINO_TO_AGBNO(mp, rec.ir_startino);
2463 	*offset_agbno = agbno - *chunk_agbno;
2464 	return 0;
2465 }
2466 
2467 /*
2468  * Return the location of the inode in imap, for mapping it into a buffer.
2469  */
2470 int
2471 xfs_imap(
2472 	struct xfs_perag	*pag,
2473 	struct xfs_trans	*tp,
2474 	xfs_ino_t		ino,	/* inode to locate */
2475 	struct xfs_imap		*imap,	/* location map structure */
2476 	uint			flags)	/* flags for inode btree lookup */
2477 {
2478 	struct xfs_mount	*mp = pag_mount(pag);
2479 	xfs_agblock_t		agbno;	/* block number of inode in the alloc group */
2480 	xfs_agino_t		agino;	/* inode number within alloc group */
2481 	xfs_agblock_t		chunk_agbno;	/* first block in inode chunk */
2482 	xfs_agblock_t		cluster_agbno;	/* first block in inode cluster */
2483 	int			error;	/* error code */
2484 	int			offset;	/* index of inode in its buffer */
2485 	xfs_agblock_t		offset_agbno;	/* blks from chunk start to inode */
2486 
2487 	ASSERT(ino != NULLFSINO);
2488 
2489 	/*
2490 	 * Split up the inode number into its parts.
2491 	 */
2492 	agino = XFS_INO_TO_AGINO(mp, ino);
2493 	agbno = XFS_AGINO_TO_AGBNO(mp, agino);
2494 	if (agbno >= xfs_ag_block_count(mp, pag_agno(pag)) ||
2495 	    ino != xfs_agino_to_ino(pag, agino)) {
2496 		error = -EINVAL;
2497 #ifdef DEBUG
2498 		/*
2499 		 * Don't output diagnostic information for untrusted inodes
2500 		 * as they can be invalid without implying corruption.
2501 		 */
2502 		if (flags & XFS_IGET_UNTRUSTED)
2503 			return error;
2504 		if (agbno >= xfs_ag_block_count(mp, pag_agno(pag))) {
2505 			xfs_alert(mp,
2506 		"%s: agbno (0x%llx) >= mp->m_sb.sb_agblocks (0x%lx)",
2507 				__func__, (unsigned long long)agbno,
2508 				(unsigned long)xfs_ag_block_count(mp,
2509 							pag_agno(pag)));
2510 		}
2511 		if (ino != xfs_agino_to_ino(pag, agino)) {
2512 			xfs_alert(mp,
2513 		"%s: ino (0x%llx) != xfs_agino_to_ino() (0x%llx)",
2514 				__func__, ino,
2515 				xfs_agino_to_ino(pag, agino));
2516 		}
2517 		xfs_stack_trace();
2518 #endif /* DEBUG */
2519 		return error;
2520 	}
2521 
2522 	/*
2523 	 * For bulkstat and handle lookups, we have an untrusted inode number
2524 	 * that we have to verify is valid. We cannot do this just by reading
2525 	 * the inode buffer as it may have been unlinked and removed leaving
2526 	 * inodes in stale state on disk. Hence we have to do a btree lookup
2527 	 * in all cases where an untrusted inode number is passed.
2528 	 */
2529 	if (!(flags & XFS_IGET_UNTRUSTED)) {
2530 		/*
2531 		 * If the inode cluster size is the same or smaller than the
2532 		 * blocksize, get to the buffer by simple arithmetics.
2533 		 */
2534 		if (M_IGEO(mp)->blocks_per_cluster == 1) {
2535 			cluster_agbno = agbno;
2536 			offset = XFS_INO_TO_OFFSET(mp, ino);
2537 			ASSERT(offset < mp->m_sb.sb_inopblock);
2538 			goto out;
2539 		}
2540 
2541 		/*
2542 		 * If the inode chunks are aligned, use simple maths to find the
2543 		 * location.
2544 		 */
2545 		if (M_IGEO(mp)->inoalign_mask) {
2546 			offset_agbno = agbno & M_IGEO(mp)->inoalign_mask;
2547 			chunk_agbno = agbno - offset_agbno;
2548 			goto out_map;
2549 		}
2550 
2551 		/*
2552 		 * Otherwise we have to do a btree lookup to find the location.
2553 		 */
2554 	}
2555 
2556 	error = xfs_imap_lookup(pag, tp, agino, agbno, &chunk_agbno,
2557 			&offset_agbno, flags);
2558 	if (error)
2559 		return error;
2560 
2561 out_map:
2562 	ASSERT(agbno >= chunk_agbno);
2563 	cluster_agbno = chunk_agbno +
2564 		((offset_agbno / M_IGEO(mp)->blocks_per_cluster) *
2565 		 M_IGEO(mp)->blocks_per_cluster);
2566 	offset = ((agbno - cluster_agbno) * mp->m_sb.sb_inopblock) +
2567 		XFS_INO_TO_OFFSET(mp, ino);
2568 out:
2569 	imap->im_agbno = cluster_agbno;
2570 	imap->im_boffset = (unsigned short)(offset << mp->m_sb.sb_inodelog);
2571 	if (imap->im_agbno + M_IGEO(mp)->blocks_per_cluster >
2572 	    pag_group(pag)->xg_block_count) {
2573 		xfs_alert(mp, "inode cluster out of range: %u/%u > %u",
2574 			imap->im_agbno, M_IGEO(mp)->blocks_per_cluster,
2575 			pag_group(pag)->xg_block_count);
2576 		return -EINVAL;
2577 	}
2578 	return 0;
2579 }
2580 
2581 /*
2582  * Log specified fields for the ag hdr (inode section). The growth of the agi
2583  * structure over time requires that we interpret the buffer as two logical
2584  * regions delineated by the end of the unlinked list. This is due to the size
2585  * of the hash table and its location in the middle of the agi.
2586  *
2587  * For example, a request to log a field before agi_unlinked and a field after
2588  * agi_unlinked could cause us to log the entire hash table and use an excessive
2589  * amount of log space. To avoid this behavior, log the region up through
2590  * agi_unlinked in one call and the region after agi_unlinked through the end of
2591  * the structure in another.
2592  */
2593 void
2594 xfs_ialloc_log_agi(
2595 	struct xfs_trans	*tp,
2596 	struct xfs_buf		*bp,
2597 	uint32_t		fields)
2598 {
2599 	int			first;		/* first byte number */
2600 	int			last;		/* last byte number */
2601 	static const short	offsets[] = {	/* field starting offsets */
2602 					/* keep in sync with bit definitions */
2603 		offsetof(xfs_agi_t, agi_magicnum),
2604 		offsetof(xfs_agi_t, agi_versionnum),
2605 		offsetof(xfs_agi_t, agi_seqno),
2606 		offsetof(xfs_agi_t, agi_length),
2607 		offsetof(xfs_agi_t, agi_count),
2608 		offsetof(xfs_agi_t, agi_root),
2609 		offsetof(xfs_agi_t, agi_level),
2610 		offsetof(xfs_agi_t, agi_freecount),
2611 		offsetof(xfs_agi_t, agi_newino),
2612 		offsetof(xfs_agi_t, agi_dirino),
2613 		offsetof(xfs_agi_t, agi_unlinked),
2614 		offsetof(xfs_agi_t, agi_free_root),
2615 		offsetof(xfs_agi_t, agi_free_level),
2616 		offsetof(xfs_agi_t, agi_iblocks),
2617 		sizeof(xfs_agi_t)
2618 	};
2619 #ifdef DEBUG
2620 	struct xfs_agi		*agi = bp->b_addr;
2621 
2622 	ASSERT(agi->agi_magicnum == cpu_to_be32(XFS_AGI_MAGIC));
2623 #endif
2624 
2625 	/*
2626 	 * Compute byte offsets for the first and last fields in the first
2627 	 * region and log the agi buffer. This only logs up through
2628 	 * agi_unlinked.
2629 	 */
2630 	if (fields & XFS_AGI_ALL_BITS_R1) {
2631 		xfs_btree_offsets(fields, offsets, XFS_AGI_NUM_BITS_R1,
2632 				  &first, &last);
2633 		xfs_trans_log_buf(tp, bp, first, last);
2634 	}
2635 
2636 	/*
2637 	 * Mask off the bits in the first region and calculate the first and
2638 	 * last field offsets for any bits in the second region.
2639 	 */
2640 	fields &= ~XFS_AGI_ALL_BITS_R1;
2641 	if (fields) {
2642 		xfs_btree_offsets(fields, offsets, XFS_AGI_NUM_BITS_R2,
2643 				  &first, &last);
2644 		xfs_trans_log_buf(tp, bp, first, last);
2645 	}
2646 }
2647 
2648 static xfs_failaddr_t
2649 xfs_agi_verify(
2650 	struct xfs_buf		*bp)
2651 {
2652 	struct xfs_mount	*mp = bp->b_mount;
2653 	struct xfs_agi		*agi = bp->b_addr;
2654 	xfs_failaddr_t		fa;
2655 	uint32_t		agi_seqno = be32_to_cpu(agi->agi_seqno);
2656 	uint32_t		agi_length = be32_to_cpu(agi->agi_length);
2657 	int			i;
2658 
2659 	if (xfs_has_crc(mp)) {
2660 		if (!uuid_equal(&agi->agi_uuid, &mp->m_sb.sb_meta_uuid))
2661 			return __this_address;
2662 		if (!xfs_log_check_lsn(mp, be64_to_cpu(agi->agi_lsn)))
2663 			return __this_address;
2664 	}
2665 
2666 	/*
2667 	 * Validate the magic number of the agi block.
2668 	 */
2669 	if (!xfs_verify_magic(bp, agi->agi_magicnum))
2670 		return __this_address;
2671 	if (!XFS_AGI_GOOD_VERSION(be32_to_cpu(agi->agi_versionnum)))
2672 		return __this_address;
2673 
2674 	fa = xfs_validate_ag_length(bp, agi_seqno, agi_length);
2675 	if (fa)
2676 		return fa;
2677 
2678 	if (be32_to_cpu(agi->agi_level) < 1 ||
2679 	    be32_to_cpu(agi->agi_level) > M_IGEO(mp)->inobt_maxlevels)
2680 		return __this_address;
2681 
2682 	if (xfs_has_finobt(mp) &&
2683 	    (be32_to_cpu(agi->agi_free_level) < 1 ||
2684 	     be32_to_cpu(agi->agi_free_level) > M_IGEO(mp)->inobt_maxlevels))
2685 		return __this_address;
2686 
2687 	for (i = 0; i < XFS_AGI_UNLINKED_BUCKETS; i++) {
2688 		if (agi->agi_unlinked[i] == cpu_to_be32(NULLAGINO))
2689 			continue;
2690 		if (!xfs_verify_ino(mp, be32_to_cpu(agi->agi_unlinked[i])))
2691 			return __this_address;
2692 	}
2693 
2694 	return NULL;
2695 }
2696 
2697 static void
2698 xfs_agi_read_verify(
2699 	struct xfs_buf	*bp)
2700 {
2701 	struct xfs_mount *mp = bp->b_mount;
2702 	xfs_failaddr_t	fa;
2703 
2704 	if (xfs_has_crc(mp) &&
2705 	    !xfs_buf_verify_cksum(bp, XFS_AGI_CRC_OFF))
2706 		xfs_verifier_error(bp, -EFSBADCRC, __this_address);
2707 	else {
2708 		fa = xfs_agi_verify(bp);
2709 		if (fa || XFS_TEST_ERROR(mp, XFS_ERRTAG_IALLOC_READ_AGI))
2710 			xfs_verifier_error(bp, -EFSCORRUPTED, fa);
2711 	}
2712 }
2713 
2714 static void
2715 xfs_agi_write_verify(
2716 	struct xfs_buf	*bp)
2717 {
2718 	struct xfs_mount	*mp = bp->b_mount;
2719 	struct xfs_buf_log_item	*bip = bp->b_log_item;
2720 	struct xfs_agi		*agi = bp->b_addr;
2721 	xfs_failaddr_t		fa;
2722 
2723 	fa = xfs_agi_verify(bp);
2724 	if (fa) {
2725 		xfs_verifier_error(bp, -EFSCORRUPTED, fa);
2726 		return;
2727 	}
2728 
2729 	if (!xfs_has_crc(mp))
2730 		return;
2731 
2732 	if (bip)
2733 		agi->agi_lsn = cpu_to_be64(bip->bli_item.li_lsn);
2734 	xfs_buf_update_cksum(bp, XFS_AGI_CRC_OFF);
2735 }
2736 
2737 const struct xfs_buf_ops xfs_agi_buf_ops = {
2738 	.name = "xfs_agi",
2739 	.magic = { cpu_to_be32(XFS_AGI_MAGIC), cpu_to_be32(XFS_AGI_MAGIC) },
2740 	.verify_read = xfs_agi_read_verify,
2741 	.verify_write = xfs_agi_write_verify,
2742 	.verify_struct = xfs_agi_verify,
2743 };
2744 
2745 /*
2746  * Read in the allocation group header (inode allocation section)
2747  */
2748 int
2749 xfs_read_agi(
2750 	struct xfs_perag	*pag,
2751 	struct xfs_trans	*tp,
2752 	xfs_buf_flags_t		flags,
2753 	struct xfs_buf		**agibpp)
2754 {
2755 	struct xfs_mount	*mp = pag_mount(pag);
2756 	int			error;
2757 
2758 	trace_xfs_read_agi(pag);
2759 
2760 	error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp,
2761 			XFS_AG_DADDR(mp, pag_agno(pag), XFS_AGI_DADDR(mp)),
2762 			XFS_FSS_TO_BB(mp, 1), flags, agibpp, &xfs_agi_buf_ops);
2763 	if (xfs_metadata_is_sick(error))
2764 		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2765 	if (error)
2766 		return error;
2767 	if (tp)
2768 		xfs_trans_buf_set_type(tp, *agibpp, XFS_BLFT_AGI_BUF);
2769 
2770 	xfs_buf_set_ref(*agibpp, XFS_AGI_REF);
2771 	return 0;
2772 }
2773 
2774 /*
2775  * Read in the agi and initialise the per-ag data. If the caller supplies a
2776  * @agibpp, return the locked AGI buffer to them, otherwise release it.
2777  */
2778 int
2779 xfs_ialloc_read_agi(
2780 	struct xfs_perag	*pag,
2781 	struct xfs_trans	*tp,
2782 	int			flags,
2783 	struct xfs_buf		**agibpp)
2784 {
2785 	struct xfs_buf		*agibp;
2786 	struct xfs_agi		*agi;
2787 	int			error;
2788 
2789 	trace_xfs_ialloc_read_agi(pag);
2790 
2791 	error = xfs_read_agi(pag, tp,
2792 			(flags & XFS_IALLOC_FLAG_TRYLOCK) ? XBF_TRYLOCK : 0,
2793 			&agibp);
2794 	if (error)
2795 		return error;
2796 
2797 	agi = agibp->b_addr;
2798 	if (!xfs_perag_initialised_agi(pag)) {
2799 		pag->pagi_freecount = be32_to_cpu(agi->agi_freecount);
2800 		pag->pagi_count = be32_to_cpu(agi->agi_count);
2801 		set_bit(XFS_AGSTATE_AGI_INIT, &pag->pag_opstate);
2802 	}
2803 
2804 #ifdef DEBUG
2805 	/*
2806 	 * It's possible for the AGF to be out of sync if the block device is
2807 	 * silently dropping writes. This can happen in fstests with dmflakey
2808 	 * enabled, which allows the buffer to be cleaned and reclaimed by
2809 	 * memory pressure and then re-read from disk here. We will get a
2810 	 * stale version of the AGF from disk, and nothing good can happen from
2811 	 * here. Hence if we detect this situation, immediately shut down the
2812 	 * filesystem.
2813 	 *
2814 	 * This can also happen if we are already in the middle of a forced
2815 	 * shutdown, so don't bother checking if we are already shut down.
2816 	 */
2817 	if (!xfs_is_shutdown(pag_mount(pag))) {
2818 		bool	ok = true;
2819 
2820 		ok &= pag->pagi_freecount == be32_to_cpu(agi->agi_freecount);
2821 		ok &= pag->pagi_count == be32_to_cpu(agi->agi_count);
2822 
2823 		if (XFS_IS_CORRUPT(pag_mount(pag), !ok)) {
2824 			xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2825 			xfs_trans_brelse(tp, agibp);
2826 			xfs_force_shutdown(pag_mount(pag),
2827 					SHUTDOWN_CORRUPT_ONDISK);
2828 			return -EFSCORRUPTED;
2829 		}
2830 	}
2831 #endif /* DEBUG */
2832 
2833 	if (agibpp)
2834 		*agibpp = agibp;
2835 	else
2836 		xfs_trans_brelse(tp, agibp);
2837 	return 0;
2838 }
2839 
2840 /* How many inodes are backed by inode clusters ondisk? */
2841 STATIC int
2842 xfs_ialloc_count_ondisk(
2843 	struct xfs_btree_cur		*cur,
2844 	xfs_agino_t			low,
2845 	xfs_agino_t			high,
2846 	unsigned int			*allocated)
2847 {
2848 	struct xfs_inobt_rec_incore	irec;
2849 	unsigned int			ret = 0;
2850 	int				has_record;
2851 	int				error;
2852 
2853 	error = xfs_inobt_lookup(cur, low, XFS_LOOKUP_LE, &has_record);
2854 	if (error)
2855 		return error;
2856 
2857 	while (has_record) {
2858 		unsigned int		i, hole_idx;
2859 
2860 		error = xfs_inobt_get_rec(cur, &irec, &has_record);
2861 		if (error)
2862 			return error;
2863 		if (XFS_IS_CORRUPT(cur->bc_mp, has_record != 1)) {
2864 			xfs_btree_mark_sick(cur);
2865 			return -EFSCORRUPTED;
2866 		}
2867 
2868 		if (irec.ir_startino > high)
2869 			break;
2870 
2871 		for (i = 0; i < XFS_INODES_PER_CHUNK; i++) {
2872 			if (irec.ir_startino + i < low)
2873 				continue;
2874 			if (irec.ir_startino + i > high)
2875 				break;
2876 
2877 			hole_idx = i / XFS_INODES_PER_HOLEMASK_BIT;
2878 			if (!(irec.ir_holemask & (1U << hole_idx)))
2879 				ret++;
2880 		}
2881 
2882 		error = xfs_btree_increment(cur, 0, &has_record);
2883 		if (error)
2884 			return error;
2885 	}
2886 
2887 	*allocated = ret;
2888 	return 0;
2889 }
2890 
2891 /* Is there an inode record covering a given extent? */
2892 int
2893 xfs_ialloc_has_inodes_at_extent(
2894 	struct xfs_btree_cur	*cur,
2895 	xfs_agblock_t		bno,
2896 	xfs_extlen_t		len,
2897 	enum xbtree_recpacking	*outcome)
2898 {
2899 	xfs_agino_t		agino;
2900 	xfs_agino_t		last_agino;
2901 	unsigned int		allocated;
2902 	int			error;
2903 
2904 	agino = XFS_AGB_TO_AGINO(cur->bc_mp, bno);
2905 	last_agino = XFS_AGB_TO_AGINO(cur->bc_mp, bno + len) - 1;
2906 
2907 	error = xfs_ialloc_count_ondisk(cur, agino, last_agino, &allocated);
2908 	if (error)
2909 		return error;
2910 
2911 	if (allocated == 0)
2912 		*outcome = XBTREE_RECPACKING_EMPTY;
2913 	else if (allocated == last_agino - agino + 1)
2914 		*outcome = XBTREE_RECPACKING_FULL;
2915 	else
2916 		*outcome = XBTREE_RECPACKING_SPARSE;
2917 	return 0;
2918 }
2919 
2920 struct xfs_ialloc_count_inodes {
2921 	xfs_agino_t			count;
2922 	xfs_agino_t			freecount;
2923 };
2924 
2925 /* Record inode counts across all inobt records. */
2926 STATIC int
2927 xfs_ialloc_count_inodes_rec(
2928 	struct xfs_btree_cur		*cur,
2929 	const union xfs_btree_rec	*rec,
2930 	void				*priv)
2931 {
2932 	struct xfs_inobt_rec_incore	irec;
2933 	struct xfs_ialloc_count_inodes	*ci = priv;
2934 	xfs_failaddr_t			fa;
2935 
2936 	xfs_inobt_btrec_to_irec(cur->bc_mp, rec, &irec);
2937 	fa = xfs_inobt_check_irec(to_perag(cur->bc_group), &irec);
2938 	if (fa)
2939 		return xfs_inobt_complain_bad_rec(cur, fa, &irec);
2940 
2941 	ci->count += irec.ir_count;
2942 	ci->freecount += irec.ir_freecount;
2943 
2944 	return 0;
2945 }
2946 
2947 /* Count allocated and free inodes under an inobt. */
2948 int
2949 xfs_ialloc_count_inodes(
2950 	struct xfs_btree_cur		*cur,
2951 	xfs_agino_t			*count,
2952 	xfs_agino_t			*freecount)
2953 {
2954 	struct xfs_ialloc_count_inodes	ci = {0};
2955 	int				error;
2956 
2957 	ASSERT(xfs_btree_is_ino(cur->bc_ops));
2958 	error = xfs_btree_query_all(cur, xfs_ialloc_count_inodes_rec, &ci);
2959 	if (error)
2960 		return error;
2961 
2962 	*count = ci.count;
2963 	*freecount = ci.freecount;
2964 	return 0;
2965 }
2966 
2967 /*
2968  * Initialize inode-related geometry information.
2969  *
2970  * Compute the inode btree min and max levels and set maxicount.
2971  *
2972  * Set the inode cluster size.  This may still be overridden by the file
2973  * system block size if it is larger than the chosen cluster size.
2974  *
2975  * For v5 filesystems, scale the cluster size with the inode size to keep a
2976  * constant ratio of inode per cluster buffer, but only if mkfs has set the
2977  * inode alignment value appropriately for larger cluster sizes.
2978  *
2979  * Then compute the inode cluster alignment information.
2980  */
2981 void
2982 xfs_ialloc_setup_geometry(
2983 	struct xfs_mount	*mp)
2984 {
2985 	struct xfs_sb		*sbp = &mp->m_sb;
2986 	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
2987 	uint64_t		icount;
2988 	uint			inodes;
2989 
2990 	igeo->new_diflags2 = 0;
2991 	if (xfs_has_bigtime(mp))
2992 		igeo->new_diflags2 |= XFS_DIFLAG2_BIGTIME;
2993 	if (xfs_has_large_extent_counts(mp))
2994 		igeo->new_diflags2 |= XFS_DIFLAG2_NREXT64;
2995 
2996 	/* Compute inode btree geometry. */
2997 	igeo->agino_log = sbp->sb_inopblog + sbp->sb_agblklog;
2998 	igeo->inobt_mxr[0] = xfs_inobt_maxrecs(mp, sbp->sb_blocksize, true);
2999 	igeo->inobt_mxr[1] = xfs_inobt_maxrecs(mp, sbp->sb_blocksize, false);
3000 	igeo->inobt_mnr[0] = igeo->inobt_mxr[0] / 2;
3001 	igeo->inobt_mnr[1] = igeo->inobt_mxr[1] / 2;
3002 
3003 	igeo->ialloc_inos = max_t(uint16_t, XFS_INODES_PER_CHUNK,
3004 			sbp->sb_inopblock);
3005 	igeo->ialloc_blks = igeo->ialloc_inos >> sbp->sb_inopblog;
3006 
3007 	if (sbp->sb_spino_align)
3008 		igeo->ialloc_min_blks = sbp->sb_spino_align;
3009 	else
3010 		igeo->ialloc_min_blks = igeo->ialloc_blks;
3011 
3012 	/* Compute and fill in value of m_ino_geo.inobt_maxlevels. */
3013 	inodes = (1LL << XFS_INO_AGINO_BITS(mp)) >> XFS_INODES_PER_CHUNK_LOG;
3014 	igeo->inobt_maxlevels = xfs_btree_compute_maxlevels(igeo->inobt_mnr,
3015 			inodes);
3016 	ASSERT(igeo->inobt_maxlevels <= xfs_iallocbt_maxlevels_ondisk());
3017 
3018 	/*
3019 	 * Set the maximum inode count for this filesystem, being careful not
3020 	 * to use obviously garbage sb_inopblog/sb_inopblock values.  Regular
3021 	 * users should never get here due to failing sb verification, but
3022 	 * certain users (xfs_db) need to be usable even with corrupt metadata.
3023 	 */
3024 	if (sbp->sb_imax_pct && igeo->ialloc_blks) {
3025 		/*
3026 		 * Make sure the maximum inode count is a multiple
3027 		 * of the units we allocate inodes in.
3028 		 */
3029 		icount = sbp->sb_dblocks * sbp->sb_imax_pct;
3030 		do_div(icount, 100);
3031 		do_div(icount, igeo->ialloc_blks);
3032 		igeo->maxicount = XFS_FSB_TO_INO(mp,
3033 				icount * igeo->ialloc_blks);
3034 	} else {
3035 		igeo->maxicount = 0;
3036 	}
3037 
3038 	/*
3039 	 * Compute the desired size of an inode cluster buffer size, which
3040 	 * starts at 8K and (on v5 filesystems) scales up with larger inode
3041 	 * sizes.
3042 	 *
3043 	 * Preserve the desired inode cluster size because the sparse inodes
3044 	 * feature uses that desired size (not the actual size) to compute the
3045 	 * sparse inode alignment.  The mount code validates this value, so we
3046 	 * cannot change the behavior.
3047 	 */
3048 	igeo->inode_cluster_size_raw = XFS_INODE_BIG_CLUSTER_SIZE;
3049 	if (xfs_has_v3inodes(mp)) {
3050 		int	new_size = igeo->inode_cluster_size_raw;
3051 
3052 		new_size *= mp->m_sb.sb_inodesize / XFS_DINODE_MIN_SIZE;
3053 		if (mp->m_sb.sb_inoalignmt >= XFS_B_TO_FSBT(mp, new_size))
3054 			igeo->inode_cluster_size_raw = new_size;
3055 	}
3056 
3057 	/* Calculate inode cluster ratios. */
3058 	if (igeo->inode_cluster_size_raw > mp->m_sb.sb_blocksize)
3059 		igeo->blocks_per_cluster = XFS_B_TO_FSBT(mp,
3060 				igeo->inode_cluster_size_raw);
3061 	else
3062 		igeo->blocks_per_cluster = 1;
3063 	igeo->inode_cluster_size = XFS_FSB_TO_B(mp, igeo->blocks_per_cluster);
3064 	igeo->inodes_per_cluster = XFS_FSB_TO_INO(mp, igeo->blocks_per_cluster);
3065 
3066 	/* Calculate inode cluster alignment. */
3067 	if (xfs_has_align(mp) &&
3068 	    mp->m_sb.sb_inoalignmt >= igeo->blocks_per_cluster)
3069 		igeo->cluster_align = mp->m_sb.sb_inoalignmt;
3070 	else
3071 		igeo->cluster_align = 1;
3072 	igeo->inoalign_mask = igeo->cluster_align - 1;
3073 	igeo->cluster_align_inodes = XFS_FSB_TO_INO(mp, igeo->cluster_align);
3074 
3075 	/*
3076 	 * If we are using stripe alignment, check whether
3077 	 * the stripe unit is a multiple of the inode alignment
3078 	 */
3079 	if (mp->m_dalign && igeo->inoalign_mask &&
3080 	    !(mp->m_dalign & igeo->inoalign_mask))
3081 		igeo->ialloc_align = mp->m_dalign;
3082 	else
3083 		igeo->ialloc_align = 0;
3084 
3085 	if (mp->m_sb.sb_blocksize > PAGE_SIZE)
3086 		igeo->min_folio_order = mp->m_sb.sb_blocklog - PAGE_SHIFT;
3087 	else
3088 		igeo->min_folio_order = 0;
3089 }
3090 
3091 /* Compute the location of the root directory inode that is laid out by mkfs. */
3092 xfs_ino_t
3093 xfs_ialloc_calc_rootino(
3094 	struct xfs_mount	*mp,
3095 	int			sunit)
3096 {
3097 	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
3098 	xfs_agblock_t		first_bno;
3099 	unsigned int		min_free;
3100 
3101 	/*
3102 	 * Pre-calculate the geometry of AG 0.  We know what it looks like
3103 	 * because libxfs knows how to create allocation groups now.
3104 	 *
3105 	 * first_bno is the first block in which mkfs could possibly have
3106 	 * allocated the root directory inode, once we factor in the metadata
3107 	 * that mkfs formats before it.  Namely, the four AG headers...
3108 	 */
3109 	first_bno = howmany(4 * mp->m_sb.sb_sectsize, mp->m_sb.sb_blocksize);
3110 
3111 	/* ...the two free space btree roots... */
3112 	first_bno += 2;
3113 
3114 	/* ...the inode btree root... */
3115 	first_bno += 1;
3116 
3117 	/* ...the initial AGFL... */
3118 	xfs_alloc_freelist(mp, NULL, &min_free, NULL);
3119 	first_bno += min_free;
3120 
3121 	/* ...the free inode btree root... */
3122 	if (xfs_has_finobt(mp))
3123 		first_bno++;
3124 
3125 	/* ...the reverse mapping btree root... */
3126 	if (xfs_has_rmapbt(mp))
3127 		first_bno++;
3128 
3129 	/* ...the reference count btree... */
3130 	if (xfs_has_reflink(mp))
3131 		first_bno++;
3132 
3133 	/*
3134 	 * ...and the log, if it is allocated in the first allocation group.
3135 	 *
3136 	 * This can happen with filesystems that only have a single
3137 	 * allocation group, or very odd geometries created by old mkfs
3138 	 * versions on very small filesystems.
3139 	 */
3140 	if (xfs_ag_contains_log(mp, 0))
3141 		 first_bno += mp->m_sb.sb_logblocks;
3142 
3143 	/*
3144 	 * Now round first_bno up to whatever allocation alignment is given
3145 	 * by the filesystem or was passed in.
3146 	 */
3147 	if (xfs_has_dalign(mp) && igeo->ialloc_align > 0)
3148 		first_bno = roundup(first_bno, sunit);
3149 	else if (xfs_has_align(mp) &&
3150 			mp->m_sb.sb_inoalignmt > 1)
3151 		first_bno = roundup(first_bno, mp->m_sb.sb_inoalignmt);
3152 
3153 	return XFS_AGINO_TO_INO(mp, 0, XFS_AGB_TO_AGINO(mp, first_bno));
3154 }
3155 
3156 /*
3157  * Ensure there are not sparse inode clusters that cross the new EOAG.
3158  *
3159  * This is a no-op for non-spinode filesystems since clusters are always fully
3160  * allocated and checking the bnobt suffices.  However, a spinode filesystem
3161  * could have a record where the upper inodes are free blocks.  If those blocks
3162  * were removed from the filesystem, the inode record would extend beyond EOAG,
3163  * which will be flagged as corruption.
3164  */
3165 int
3166 xfs_ialloc_check_shrink(
3167 	struct xfs_perag	*pag,
3168 	struct xfs_trans	*tp,
3169 	struct xfs_buf		*agibp,
3170 	xfs_agblock_t		new_length)
3171 {
3172 	struct xfs_inobt_rec_incore rec;
3173 	struct xfs_btree_cur	*cur;
3174 	xfs_agino_t		agino;
3175 	int			has;
3176 	int			error;
3177 
3178 	if (!xfs_has_sparseinodes(pag_mount(pag)))
3179 		return 0;
3180 
3181 	cur = xfs_inobt_init_cursor(pag, tp, agibp);
3182 
3183 	/* Look up the inobt record that would correspond to the new EOFS. */
3184 	agino = XFS_AGB_TO_AGINO(pag_mount(pag), new_length);
3185 	error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_LE, &has);
3186 	if (error || !has)
3187 		goto out;
3188 
3189 	error = xfs_inobt_get_rec(cur, &rec, &has);
3190 	if (error)
3191 		goto out;
3192 
3193 	if (!has) {
3194 		xfs_ag_mark_sick(pag, XFS_SICK_AG_INOBT);
3195 		error = -EFSCORRUPTED;
3196 		goto out;
3197 	}
3198 
3199 	/* If the record covers inodes that would be beyond EOFS, bail out. */
3200 	if (rec.ir_startino + XFS_INODES_PER_CHUNK > agino) {
3201 		error = -ENOSPC;
3202 		goto out;
3203 	}
3204 out:
3205 	xfs_btree_del_cursor(cur, error);
3206 	return error;
3207 }
3208