xfs: merge xfs_ag.h into xfs_format.h
[firefly-linux-kernel-4.4.55.git] / fs / xfs / libxfs / xfs_ialloc.c
1 /*
2  * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_shared.h"
21 #include "xfs_format.h"
22 #include "xfs_log_format.h"
23 #include "xfs_trans_resv.h"
24 #include "xfs_bit.h"
25 #include "xfs_inum.h"
26 #include "xfs_sb.h"
27 #include "xfs_mount.h"
28 #include "xfs_inode.h"
29 #include "xfs_btree.h"
30 #include "xfs_ialloc.h"
31 #include "xfs_ialloc_btree.h"
32 #include "xfs_alloc.h"
33 #include "xfs_rtalloc.h"
34 #include "xfs_error.h"
35 #include "xfs_bmap.h"
36 #include "xfs_cksum.h"
37 #include "xfs_trans.h"
38 #include "xfs_buf_item.h"
39 #include "xfs_icreate_item.h"
40 #include "xfs_icache.h"
41 #include "xfs_trace.h"
42
43
44 /*
45  * Allocation group level functions.
46  */
47 static inline int
48 xfs_ialloc_cluster_alignment(
49         xfs_alloc_arg_t *args)
50 {
51         if (xfs_sb_version_hasalign(&args->mp->m_sb) &&
52             args->mp->m_sb.sb_inoalignmt >=
53              XFS_B_TO_FSBT(args->mp, args->mp->m_inode_cluster_size))
54                 return args->mp->m_sb.sb_inoalignmt;
55         return 1;
56 }
57
58 /*
59  * Lookup a record by ino in the btree given by cur.
60  */
61 int                                     /* error */
62 xfs_inobt_lookup(
63         struct xfs_btree_cur    *cur,   /* btree cursor */
64         xfs_agino_t             ino,    /* starting inode of chunk */
65         xfs_lookup_t            dir,    /* <=, >=, == */
66         int                     *stat)  /* success/failure */
67 {
68         cur->bc_rec.i.ir_startino = ino;
69         cur->bc_rec.i.ir_freecount = 0;
70         cur->bc_rec.i.ir_free = 0;
71         return xfs_btree_lookup(cur, dir, stat);
72 }
73
74 /*
75  * Update the record referred to by cur to the value given.
76  * This either works (return 0) or gets an EFSCORRUPTED error.
77  */
78 STATIC int                              /* error */
79 xfs_inobt_update(
80         struct xfs_btree_cur    *cur,   /* btree cursor */
81         xfs_inobt_rec_incore_t  *irec)  /* btree record */
82 {
83         union xfs_btree_rec     rec;
84
85         rec.inobt.ir_startino = cpu_to_be32(irec->ir_startino);
86         rec.inobt.ir_freecount = cpu_to_be32(irec->ir_freecount);
87         rec.inobt.ir_free = cpu_to_be64(irec->ir_free);
88         return xfs_btree_update(cur, &rec);
89 }
90
91 /*
92  * Get the data from the pointed-to record.
93  */
94 int                                     /* error */
95 xfs_inobt_get_rec(
96         struct xfs_btree_cur    *cur,   /* btree cursor */
97         xfs_inobt_rec_incore_t  *irec,  /* btree record */
98         int                     *stat)  /* output: success/failure */
99 {
100         union xfs_btree_rec     *rec;
101         int                     error;
102
103         error = xfs_btree_get_rec(cur, &rec, stat);
104         if (!error && *stat == 1) {
105                 irec->ir_startino = be32_to_cpu(rec->inobt.ir_startino);
106                 irec->ir_freecount = be32_to_cpu(rec->inobt.ir_freecount);
107                 irec->ir_free = be64_to_cpu(rec->inobt.ir_free);
108         }
109         return error;
110 }
111
112 /*
113  * Insert a single inobt record. Cursor must already point to desired location.
114  */
115 STATIC int
116 xfs_inobt_insert_rec(
117         struct xfs_btree_cur    *cur,
118         __int32_t               freecount,
119         xfs_inofree_t           free,
120         int                     *stat)
121 {
122         cur->bc_rec.i.ir_freecount = freecount;
123         cur->bc_rec.i.ir_free = free;
124         return xfs_btree_insert(cur, stat);
125 }
126
127 /*
128  * Insert records describing a newly allocated inode chunk into the inobt.
129  */
130 STATIC int
131 xfs_inobt_insert(
132         struct xfs_mount        *mp,
133         struct xfs_trans        *tp,
134         struct xfs_buf          *agbp,
135         xfs_agino_t             newino,
136         xfs_agino_t             newlen,
137         xfs_btnum_t             btnum)
138 {
139         struct xfs_btree_cur    *cur;
140         struct xfs_agi          *agi = XFS_BUF_TO_AGI(agbp);
141         xfs_agnumber_t          agno = be32_to_cpu(agi->agi_seqno);
142         xfs_agino_t             thisino;
143         int                     i;
144         int                     error;
145
146         cur = xfs_inobt_init_cursor(mp, tp, agbp, agno, btnum);
147
148         for (thisino = newino;
149              thisino < newino + newlen;
150              thisino += XFS_INODES_PER_CHUNK) {
151                 error = xfs_inobt_lookup(cur, thisino, XFS_LOOKUP_EQ, &i);
152                 if (error) {
153                         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
154                         return error;
155                 }
156                 ASSERT(i == 0);
157
158                 error = xfs_inobt_insert_rec(cur, XFS_INODES_PER_CHUNK,
159                                              XFS_INOBT_ALL_FREE, &i);
160                 if (error) {
161                         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
162                         return error;
163                 }
164                 ASSERT(i == 1);
165         }
166
167         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
168
169         return 0;
170 }
171
172 /*
173  * Verify that the number of free inodes in the AGI is correct.
174  */
175 #ifdef DEBUG
176 STATIC int
177 xfs_check_agi_freecount(
178         struct xfs_btree_cur    *cur,
179         struct xfs_agi          *agi)
180 {
181         if (cur->bc_nlevels == 1) {
182                 xfs_inobt_rec_incore_t rec;
183                 int             freecount = 0;
184                 int             error;
185                 int             i;
186
187                 error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &i);
188                 if (error)
189                         return error;
190
191                 do {
192                         error = xfs_inobt_get_rec(cur, &rec, &i);
193                         if (error)
194                                 return error;
195
196                         if (i) {
197                                 freecount += rec.ir_freecount;
198                                 error = xfs_btree_increment(cur, 0, &i);
199                                 if (error)
200                                         return error;
201                         }
202                 } while (i == 1);
203
204                 if (!XFS_FORCED_SHUTDOWN(cur->bc_mp))
205                         ASSERT(freecount == be32_to_cpu(agi->agi_freecount));
206         }
207         return 0;
208 }
209 #else
210 #define xfs_check_agi_freecount(cur, agi)       0
211 #endif
212
213 /*
214  * Initialise a new set of inodes. When called without a transaction context
215  * (e.g. from recovery) we initiate a delayed write of the inode buffers rather
216  * than logging them (which in a transaction context puts them into the AIL
217  * for writeback rather than the xfsbufd queue).
218  */
219 int
220 xfs_ialloc_inode_init(
221         struct xfs_mount        *mp,
222         struct xfs_trans        *tp,
223         struct list_head        *buffer_list,
224         xfs_agnumber_t          agno,
225         xfs_agblock_t           agbno,
226         xfs_agblock_t           length,
227         unsigned int            gen)
228 {
229         struct xfs_buf          *fbuf;
230         struct xfs_dinode       *free;
231         int                     nbufs, blks_per_cluster, inodes_per_cluster;
232         int                     version;
233         int                     i, j;
234         xfs_daddr_t             d;
235         xfs_ino_t               ino = 0;
236
237         /*
238          * Loop over the new block(s), filling in the inodes.  For small block
239          * sizes, manipulate the inodes in buffers  which are multiples of the
240          * blocks size.
241          */
242         blks_per_cluster = xfs_icluster_size_fsb(mp);
243         inodes_per_cluster = blks_per_cluster << mp->m_sb.sb_inopblog;
244         nbufs = length / blks_per_cluster;
245
246         /*
247          * Figure out what version number to use in the inodes we create.  If
248          * the superblock version has caught up to the one that supports the new
249          * inode format, then use the new inode version.  Otherwise use the old
250          * version so that old kernels will continue to be able to use the file
251          * system.
252          *
253          * For v3 inodes, we also need to write the inode number into the inode,
254          * so calculate the first inode number of the chunk here as
255          * XFS_OFFBNO_TO_AGINO() only works within a filesystem block, not
256          * across multiple filesystem blocks (such as a cluster) and so cannot
257          * be used in the cluster buffer loop below.
258          *
259          * Further, because we are writing the inode directly into the buffer
260          * and calculating a CRC on the entire inode, we have ot log the entire
261          * inode so that the entire range the CRC covers is present in the log.
262          * That means for v3 inode we log the entire buffer rather than just the
263          * inode cores.
264          */
265         if (xfs_sb_version_hascrc(&mp->m_sb)) {
266                 version = 3;
267                 ino = XFS_AGINO_TO_INO(mp, agno,
268                                        XFS_OFFBNO_TO_AGINO(mp, agbno, 0));
269
270                 /*
271                  * log the initialisation that is about to take place as an
272                  * logical operation. This means the transaction does not
273                  * need to log the physical changes to the inode buffers as log
274                  * recovery will know what initialisation is actually needed.
275                  * Hence we only need to log the buffers as "ordered" buffers so
276                  * they track in the AIL as if they were physically logged.
277                  */
278                 if (tp)
279                         xfs_icreate_log(tp, agno, agbno, mp->m_ialloc_inos,
280                                         mp->m_sb.sb_inodesize, length, gen);
281         } else
282                 version = 2;
283
284         for (j = 0; j < nbufs; j++) {
285                 /*
286                  * Get the block.
287                  */
288                 d = XFS_AGB_TO_DADDR(mp, agno, agbno + (j * blks_per_cluster));
289                 fbuf = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
290                                          mp->m_bsize * blks_per_cluster,
291                                          XBF_UNMAPPED);
292                 if (!fbuf)
293                         return -ENOMEM;
294
295                 /* Initialize the inode buffers and log them appropriately. */
296                 fbuf->b_ops = &xfs_inode_buf_ops;
297                 xfs_buf_zero(fbuf, 0, BBTOB(fbuf->b_length));
298                 for (i = 0; i < inodes_per_cluster; i++) {
299                         int     ioffset = i << mp->m_sb.sb_inodelog;
300                         uint    isize = xfs_dinode_size(version);
301
302                         free = xfs_make_iptr(mp, fbuf, i);
303                         free->di_magic = cpu_to_be16(XFS_DINODE_MAGIC);
304                         free->di_version = version;
305                         free->di_gen = cpu_to_be32(gen);
306                         free->di_next_unlinked = cpu_to_be32(NULLAGINO);
307
308                         if (version == 3) {
309                                 free->di_ino = cpu_to_be64(ino);
310                                 ino++;
311                                 uuid_copy(&free->di_uuid, &mp->m_sb.sb_uuid);
312                                 xfs_dinode_calc_crc(mp, free);
313                         } else if (tp) {
314                                 /* just log the inode core */
315                                 xfs_trans_log_buf(tp, fbuf, ioffset,
316                                                   ioffset + isize - 1);
317                         }
318                 }
319
320                 if (tp) {
321                         /*
322                          * Mark the buffer as an inode allocation buffer so it
323                          * sticks in AIL at the point of this allocation
324                          * transaction. This ensures the they are on disk before
325                          * the tail of the log can be moved past this
326                          * transaction (i.e. by preventing relogging from moving
327                          * it forward in the log).
328                          */
329                         xfs_trans_inode_alloc_buf(tp, fbuf);
330                         if (version == 3) {
331                                 /*
332                                  * Mark the buffer as ordered so that they are
333                                  * not physically logged in the transaction but
334                                  * still tracked in the AIL as part of the
335                                  * transaction and pin the log appropriately.
336                                  */
337                                 xfs_trans_ordered_buf(tp, fbuf);
338                                 xfs_trans_log_buf(tp, fbuf, 0,
339                                                   BBTOB(fbuf->b_length) - 1);
340                         }
341                 } else {
342                         fbuf->b_flags |= XBF_DONE;
343                         xfs_buf_delwri_queue(fbuf, buffer_list);
344                         xfs_buf_relse(fbuf);
345                 }
346         }
347         return 0;
348 }
349
350 /*
351  * Allocate new inodes in the allocation group specified by agbp.
352  * Return 0 for success, else error code.
353  */
354 STATIC int                              /* error code or 0 */
355 xfs_ialloc_ag_alloc(
356         xfs_trans_t     *tp,            /* transaction pointer */
357         xfs_buf_t       *agbp,          /* alloc group buffer */
358         int             *alloc)
359 {
360         xfs_agi_t       *agi;           /* allocation group header */
361         xfs_alloc_arg_t args;           /* allocation argument structure */
362         xfs_agnumber_t  agno;
363         int             error;
364         xfs_agino_t     newino;         /* new first inode's number */
365         xfs_agino_t     newlen;         /* new number of inodes */
366         int             isaligned = 0;  /* inode allocation at stripe unit */
367                                         /* boundary */
368         struct xfs_perag *pag;
369
370         memset(&args, 0, sizeof(args));
371         args.tp = tp;
372         args.mp = tp->t_mountp;
373
374         /*
375          * Locking will ensure that we don't have two callers in here
376          * at one time.
377          */
378         newlen = args.mp->m_ialloc_inos;
379         if (args.mp->m_maxicount &&
380             args.mp->m_sb.sb_icount + newlen > args.mp->m_maxicount)
381                 return -ENOSPC;
382         args.minlen = args.maxlen = args.mp->m_ialloc_blks;
383         /*
384          * First try to allocate inodes contiguous with the last-allocated
385          * chunk of inodes.  If the filesystem is striped, this will fill
386          * an entire stripe unit with inodes.
387          */
388         agi = XFS_BUF_TO_AGI(agbp);
389         newino = be32_to_cpu(agi->agi_newino);
390         agno = be32_to_cpu(agi->agi_seqno);
391         args.agbno = XFS_AGINO_TO_AGBNO(args.mp, newino) +
392                      args.mp->m_ialloc_blks;
393         if (likely(newino != NULLAGINO &&
394                   (args.agbno < be32_to_cpu(agi->agi_length)))) {
395                 args.fsbno = XFS_AGB_TO_FSB(args.mp, agno, args.agbno);
396                 args.type = XFS_ALLOCTYPE_THIS_BNO;
397                 args.prod = 1;
398
399                 /*
400                  * We need to take into account alignment here to ensure that
401                  * we don't modify the free list if we fail to have an exact
402                  * block. If we don't have an exact match, and every oher
403                  * attempt allocation attempt fails, we'll end up cancelling
404                  * a dirty transaction and shutting down.
405                  *
406                  * For an exact allocation, alignment must be 1,
407                  * however we need to take cluster alignment into account when
408                  * fixing up the freelist. Use the minalignslop field to
409                  * indicate that extra blocks might be required for alignment,
410                  * but not to use them in the actual exact allocation.
411                  */
412                 args.alignment = 1;
413                 args.minalignslop = xfs_ialloc_cluster_alignment(&args) - 1;
414
415                 /* Allow space for the inode btree to split. */
416                 args.minleft = args.mp->m_in_maxlevels - 1;
417                 if ((error = xfs_alloc_vextent(&args)))
418                         return error;
419
420                 /*
421                  * This request might have dirtied the transaction if the AG can
422                  * satisfy the request, but the exact block was not available.
423                  * If the allocation did fail, subsequent requests will relax
424                  * the exact agbno requirement and increase the alignment
425                  * instead. It is critical that the total size of the request
426                  * (len + alignment + slop) does not increase from this point
427                  * on, so reset minalignslop to ensure it is not included in
428                  * subsequent requests.
429                  */
430                 args.minalignslop = 0;
431         } else
432                 args.fsbno = NULLFSBLOCK;
433
434         if (unlikely(args.fsbno == NULLFSBLOCK)) {
435                 /*
436                  * Set the alignment for the allocation.
437                  * If stripe alignment is turned on then align at stripe unit
438                  * boundary.
439                  * If the cluster size is smaller than a filesystem block
440                  * then we're doing I/O for inodes in filesystem block size
441                  * pieces, so don't need alignment anyway.
442                  */
443                 isaligned = 0;
444                 if (args.mp->m_sinoalign) {
445                         ASSERT(!(args.mp->m_flags & XFS_MOUNT_NOALIGN));
446                         args.alignment = args.mp->m_dalign;
447                         isaligned = 1;
448                 } else
449                         args.alignment = xfs_ialloc_cluster_alignment(&args);
450                 /*
451                  * Need to figure out where to allocate the inode blocks.
452                  * Ideally they should be spaced out through the a.g.
453                  * For now, just allocate blocks up front.
454                  */
455                 args.agbno = be32_to_cpu(agi->agi_root);
456                 args.fsbno = XFS_AGB_TO_FSB(args.mp, agno, args.agbno);
457                 /*
458                  * Allocate a fixed-size extent of inodes.
459                  */
460                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
461                 args.prod = 1;
462                 /*
463                  * Allow space for the inode btree to split.
464                  */
465                 args.minleft = args.mp->m_in_maxlevels - 1;
466                 if ((error = xfs_alloc_vextent(&args)))
467                         return error;
468         }
469
470         /*
471          * If stripe alignment is turned on, then try again with cluster
472          * alignment.
473          */
474         if (isaligned && args.fsbno == NULLFSBLOCK) {
475                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
476                 args.agbno = be32_to_cpu(agi->agi_root);
477                 args.fsbno = XFS_AGB_TO_FSB(args.mp, agno, args.agbno);
478                 args.alignment = xfs_ialloc_cluster_alignment(&args);
479                 if ((error = xfs_alloc_vextent(&args)))
480                         return error;
481         }
482
483         if (args.fsbno == NULLFSBLOCK) {
484                 *alloc = 0;
485                 return 0;
486         }
487         ASSERT(args.len == args.minlen);
488
489         /*
490          * Stamp and write the inode buffers.
491          *
492          * Seed the new inode cluster with a random generation number. This
493          * prevents short-term reuse of generation numbers if a chunk is
494          * freed and then immediately reallocated. We use random numbers
495          * rather than a linear progression to prevent the next generation
496          * number from being easily guessable.
497          */
498         error = xfs_ialloc_inode_init(args.mp, tp, NULL, agno, args.agbno,
499                         args.len, prandom_u32());
500
501         if (error)
502                 return error;
503         /*
504          * Convert the results.
505          */
506         newino = XFS_OFFBNO_TO_AGINO(args.mp, args.agbno, 0);
507         be32_add_cpu(&agi->agi_count, newlen);
508         be32_add_cpu(&agi->agi_freecount, newlen);
509         pag = xfs_perag_get(args.mp, agno);
510         pag->pagi_freecount += newlen;
511         xfs_perag_put(pag);
512         agi->agi_newino = cpu_to_be32(newino);
513
514         /*
515          * Insert records describing the new inode chunk into the btrees.
516          */
517         error = xfs_inobt_insert(args.mp, tp, agbp, newino, newlen,
518                                  XFS_BTNUM_INO);
519         if (error)
520                 return error;
521
522         if (xfs_sb_version_hasfinobt(&args.mp->m_sb)) {
523                 error = xfs_inobt_insert(args.mp, tp, agbp, newino, newlen,
524                                          XFS_BTNUM_FINO);
525                 if (error)
526                         return error;
527         }
528         /*
529          * Log allocation group header fields
530          */
531         xfs_ialloc_log_agi(tp, agbp,
532                 XFS_AGI_COUNT | XFS_AGI_FREECOUNT | XFS_AGI_NEWINO);
533         /*
534          * Modify/log superblock values for inode count and inode free count.
535          */
536         xfs_trans_mod_sb(tp, XFS_TRANS_SB_ICOUNT, (long)newlen);
537         xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, (long)newlen);
538         *alloc = 1;
539         return 0;
540 }
541
542 STATIC xfs_agnumber_t
543 xfs_ialloc_next_ag(
544         xfs_mount_t     *mp)
545 {
546         xfs_agnumber_t  agno;
547
548         spin_lock(&mp->m_agirotor_lock);
549         agno = mp->m_agirotor;
550         if (++mp->m_agirotor >= mp->m_maxagi)
551                 mp->m_agirotor = 0;
552         spin_unlock(&mp->m_agirotor_lock);
553
554         return agno;
555 }
556
557 /*
558  * Select an allocation group to look for a free inode in, based on the parent
559  * inode and the mode.  Return the allocation group buffer.
560  */
561 STATIC xfs_agnumber_t
562 xfs_ialloc_ag_select(
563         xfs_trans_t     *tp,            /* transaction pointer */
564         xfs_ino_t       parent,         /* parent directory inode number */
565         umode_t         mode,           /* bits set to indicate file type */
566         int             okalloc)        /* ok to allocate more space */
567 {
568         xfs_agnumber_t  agcount;        /* number of ag's in the filesystem */
569         xfs_agnumber_t  agno;           /* current ag number */
570         int             flags;          /* alloc buffer locking flags */
571         xfs_extlen_t    ineed;          /* blocks needed for inode allocation */
572         xfs_extlen_t    longest = 0;    /* longest extent available */
573         xfs_mount_t     *mp;            /* mount point structure */
574         int             needspace;      /* file mode implies space allocated */
575         xfs_perag_t     *pag;           /* per allocation group data */
576         xfs_agnumber_t  pagno;          /* parent (starting) ag number */
577         int             error;
578
579         /*
580          * Files of these types need at least one block if length > 0
581          * (and they won't fit in the inode, but that's hard to figure out).
582          */
583         needspace = S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode);
584         mp = tp->t_mountp;
585         agcount = mp->m_maxagi;
586         if (S_ISDIR(mode))
587                 pagno = xfs_ialloc_next_ag(mp);
588         else {
589                 pagno = XFS_INO_TO_AGNO(mp, parent);
590                 if (pagno >= agcount)
591                         pagno = 0;
592         }
593
594         ASSERT(pagno < agcount);
595
596         /*
597          * Loop through allocation groups, looking for one with a little
598          * free space in it.  Note we don't look for free inodes, exactly.
599          * Instead, we include whether there is a need to allocate inodes
600          * to mean that blocks must be allocated for them,
601          * if none are currently free.
602          */
603         agno = pagno;
604         flags = XFS_ALLOC_FLAG_TRYLOCK;
605         for (;;) {
606                 pag = xfs_perag_get(mp, agno);
607                 if (!pag->pagi_inodeok) {
608                         xfs_ialloc_next_ag(mp);
609                         goto nextag;
610                 }
611
612                 if (!pag->pagi_init) {
613                         error = xfs_ialloc_pagi_init(mp, tp, agno);
614                         if (error)
615                                 goto nextag;
616                 }
617
618                 if (pag->pagi_freecount) {
619                         xfs_perag_put(pag);
620                         return agno;
621                 }
622
623                 if (!okalloc)
624                         goto nextag;
625
626                 if (!pag->pagf_init) {
627                         error = xfs_alloc_pagf_init(mp, tp, agno, flags);
628                         if (error)
629                                 goto nextag;
630                 }
631
632                 /*
633                  * Is there enough free space for the file plus a block of
634                  * inodes? (if we need to allocate some)?
635                  */
636                 ineed = mp->m_ialloc_blks;
637                 longest = pag->pagf_longest;
638                 if (!longest)
639                         longest = pag->pagf_flcount > 0;
640
641                 if (pag->pagf_freeblks >= needspace + ineed &&
642                     longest >= ineed) {
643                         xfs_perag_put(pag);
644                         return agno;
645                 }
646 nextag:
647                 xfs_perag_put(pag);
648                 /*
649                  * No point in iterating over the rest, if we're shutting
650                  * down.
651                  */
652                 if (XFS_FORCED_SHUTDOWN(mp))
653                         return NULLAGNUMBER;
654                 agno++;
655                 if (agno >= agcount)
656                         agno = 0;
657                 if (agno == pagno) {
658                         if (flags == 0)
659                                 return NULLAGNUMBER;
660                         flags = 0;
661                 }
662         }
663 }
664
665 /*
666  * Try to retrieve the next record to the left/right from the current one.
667  */
668 STATIC int
669 xfs_ialloc_next_rec(
670         struct xfs_btree_cur    *cur,
671         xfs_inobt_rec_incore_t  *rec,
672         int                     *done,
673         int                     left)
674 {
675         int                     error;
676         int                     i;
677
678         if (left)
679                 error = xfs_btree_decrement(cur, 0, &i);
680         else
681                 error = xfs_btree_increment(cur, 0, &i);
682
683         if (error)
684                 return error;
685         *done = !i;
686         if (i) {
687                 error = xfs_inobt_get_rec(cur, rec, &i);
688                 if (error)
689                         return error;
690                 XFS_WANT_CORRUPTED_RETURN(i == 1);
691         }
692
693         return 0;
694 }
695
696 STATIC int
697 xfs_ialloc_get_rec(
698         struct xfs_btree_cur    *cur,
699         xfs_agino_t             agino,
700         xfs_inobt_rec_incore_t  *rec,
701         int                     *done)
702 {
703         int                     error;
704         int                     i;
705
706         error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_EQ, &i);
707         if (error)
708                 return error;
709         *done = !i;
710         if (i) {
711                 error = xfs_inobt_get_rec(cur, rec, &i);
712                 if (error)
713                         return error;
714                 XFS_WANT_CORRUPTED_RETURN(i == 1);
715         }
716
717         return 0;
718 }
719
720 /*
721  * Allocate an inode using the inobt-only algorithm.
722  */
723 STATIC int
724 xfs_dialloc_ag_inobt(
725         struct xfs_trans        *tp,
726         struct xfs_buf          *agbp,
727         xfs_ino_t               parent,
728         xfs_ino_t               *inop)
729 {
730         struct xfs_mount        *mp = tp->t_mountp;
731         struct xfs_agi          *agi = XFS_BUF_TO_AGI(agbp);
732         xfs_agnumber_t          agno = be32_to_cpu(agi->agi_seqno);
733         xfs_agnumber_t          pagno = XFS_INO_TO_AGNO(mp, parent);
734         xfs_agino_t             pagino = XFS_INO_TO_AGINO(mp, parent);
735         struct xfs_perag        *pag;
736         struct xfs_btree_cur    *cur, *tcur;
737         struct xfs_inobt_rec_incore rec, trec;
738         xfs_ino_t               ino;
739         int                     error;
740         int                     offset;
741         int                     i, j;
742
743         pag = xfs_perag_get(mp, agno);
744
745         ASSERT(pag->pagi_init);
746         ASSERT(pag->pagi_inodeok);
747         ASSERT(pag->pagi_freecount > 0);
748
749  restart_pagno:
750         cur = xfs_inobt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_INO);
751         /*
752          * If pagino is 0 (this is the root inode allocation) use newino.
753          * This must work because we've just allocated some.
754          */
755         if (!pagino)
756                 pagino = be32_to_cpu(agi->agi_newino);
757
758         error = xfs_check_agi_freecount(cur, agi);
759         if (error)
760                 goto error0;
761
762         /*
763          * If in the same AG as the parent, try to get near the parent.
764          */
765         if (pagno == agno) {
766                 int             doneleft;       /* done, to the left */
767                 int             doneright;      /* done, to the right */
768                 int             searchdistance = 10;
769
770                 error = xfs_inobt_lookup(cur, pagino, XFS_LOOKUP_LE, &i);
771                 if (error)
772                         goto error0;
773                 XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
774
775                 error = xfs_inobt_get_rec(cur, &rec, &j);
776                 if (error)
777                         goto error0;
778                 XFS_WANT_CORRUPTED_GOTO(j == 1, error0);
779
780                 if (rec.ir_freecount > 0) {
781                         /*
782                          * Found a free inode in the same chunk
783                          * as the parent, done.
784                          */
785                         goto alloc_inode;
786                 }
787
788
789                 /*
790                  * In the same AG as parent, but parent's chunk is full.
791                  */
792
793                 /* duplicate the cursor, search left & right simultaneously */
794                 error = xfs_btree_dup_cursor(cur, &tcur);
795                 if (error)
796                         goto error0;
797
798                 /*
799                  * Skip to last blocks looked up if same parent inode.
800                  */
801                 if (pagino != NULLAGINO &&
802                     pag->pagl_pagino == pagino &&
803                     pag->pagl_leftrec != NULLAGINO &&
804                     pag->pagl_rightrec != NULLAGINO) {
805                         error = xfs_ialloc_get_rec(tcur, pag->pagl_leftrec,
806                                                    &trec, &doneleft);
807                         if (error)
808                                 goto error1;
809
810                         error = xfs_ialloc_get_rec(cur, pag->pagl_rightrec,
811                                                    &rec, &doneright);
812                         if (error)
813                                 goto error1;
814                 } else {
815                         /* search left with tcur, back up 1 record */
816                         error = xfs_ialloc_next_rec(tcur, &trec, &doneleft, 1);
817                         if (error)
818                                 goto error1;
819
820                         /* search right with cur, go forward 1 record. */
821                         error = xfs_ialloc_next_rec(cur, &rec, &doneright, 0);
822                         if (error)
823                                 goto error1;
824                 }
825
826                 /*
827                  * Loop until we find an inode chunk with a free inode.
828                  */
829                 while (!doneleft || !doneright) {
830                         int     useleft;  /* using left inode chunk this time */
831
832                         if (!--searchdistance) {
833                                 /*
834                                  * Not in range - save last search
835                                  * location and allocate a new inode
836                                  */
837                                 xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
838                                 pag->pagl_leftrec = trec.ir_startino;
839                                 pag->pagl_rightrec = rec.ir_startino;
840                                 pag->pagl_pagino = pagino;
841                                 goto newino;
842                         }
843
844                         /* figure out the closer block if both are valid. */
845                         if (!doneleft && !doneright) {
846                                 useleft = pagino -
847                                  (trec.ir_startino + XFS_INODES_PER_CHUNK - 1) <
848                                   rec.ir_startino - pagino;
849                         } else {
850                                 useleft = !doneleft;
851                         }
852
853                         /* free inodes to the left? */
854                         if (useleft && trec.ir_freecount) {
855                                 rec = trec;
856                                 xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
857                                 cur = tcur;
858
859                                 pag->pagl_leftrec = trec.ir_startino;
860                                 pag->pagl_rightrec = rec.ir_startino;
861                                 pag->pagl_pagino = pagino;
862                                 goto alloc_inode;
863                         }
864
865                         /* free inodes to the right? */
866                         if (!useleft && rec.ir_freecount) {
867                                 xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
868
869                                 pag->pagl_leftrec = trec.ir_startino;
870                                 pag->pagl_rightrec = rec.ir_startino;
871                                 pag->pagl_pagino = pagino;
872                                 goto alloc_inode;
873                         }
874
875                         /* get next record to check */
876                         if (useleft) {
877                                 error = xfs_ialloc_next_rec(tcur, &trec,
878                                                                  &doneleft, 1);
879                         } else {
880                                 error = xfs_ialloc_next_rec(cur, &rec,
881                                                                  &doneright, 0);
882                         }
883                         if (error)
884                                 goto error1;
885                 }
886
887                 /*
888                  * We've reached the end of the btree. because
889                  * we are only searching a small chunk of the
890                  * btree each search, there is obviously free
891                  * inodes closer to the parent inode than we
892                  * are now. restart the search again.
893                  */
894                 pag->pagl_pagino = NULLAGINO;
895                 pag->pagl_leftrec = NULLAGINO;
896                 pag->pagl_rightrec = NULLAGINO;
897                 xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
898                 xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
899                 goto restart_pagno;
900         }
901
902         /*
903          * In a different AG from the parent.
904          * See if the most recently allocated block has any free.
905          */
906 newino:
907         if (agi->agi_newino != cpu_to_be32(NULLAGINO)) {
908                 error = xfs_inobt_lookup(cur, be32_to_cpu(agi->agi_newino),
909                                          XFS_LOOKUP_EQ, &i);
910                 if (error)
911                         goto error0;
912
913                 if (i == 1) {
914                         error = xfs_inobt_get_rec(cur, &rec, &j);
915                         if (error)
916                                 goto error0;
917
918                         if (j == 1 && rec.ir_freecount > 0) {
919                                 /*
920                                  * The last chunk allocated in the group
921                                  * still has a free inode.
922                                  */
923                                 goto alloc_inode;
924                         }
925                 }
926         }
927
928         /*
929          * None left in the last group, search the whole AG
930          */
931         error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &i);
932         if (error)
933                 goto error0;
934         XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
935
936         for (;;) {
937                 error = xfs_inobt_get_rec(cur, &rec, &i);
938                 if (error)
939                         goto error0;
940                 XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
941                 if (rec.ir_freecount > 0)
942                         break;
943                 error = xfs_btree_increment(cur, 0, &i);
944                 if (error)
945                         goto error0;
946                 XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
947         }
948
949 alloc_inode:
950         offset = xfs_lowbit64(rec.ir_free);
951         ASSERT(offset >= 0);
952         ASSERT(offset < XFS_INODES_PER_CHUNK);
953         ASSERT((XFS_AGINO_TO_OFFSET(mp, rec.ir_startino) %
954                                    XFS_INODES_PER_CHUNK) == 0);
955         ino = XFS_AGINO_TO_INO(mp, agno, rec.ir_startino + offset);
956         rec.ir_free &= ~XFS_INOBT_MASK(offset);
957         rec.ir_freecount--;
958         error = xfs_inobt_update(cur, &rec);
959         if (error)
960                 goto error0;
961         be32_add_cpu(&agi->agi_freecount, -1);
962         xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
963         pag->pagi_freecount--;
964
965         error = xfs_check_agi_freecount(cur, agi);
966         if (error)
967                 goto error0;
968
969         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
970         xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -1);
971         xfs_perag_put(pag);
972         *inop = ino;
973         return 0;
974 error1:
975         xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
976 error0:
977         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
978         xfs_perag_put(pag);
979         return error;
980 }
981
982 /*
983  * Use the free inode btree to allocate an inode based on distance from the
984  * parent. Note that the provided cursor may be deleted and replaced.
985  */
986 STATIC int
987 xfs_dialloc_ag_finobt_near(
988         xfs_agino_t                     pagino,
989         struct xfs_btree_cur            **ocur,
990         struct xfs_inobt_rec_incore     *rec)
991 {
992         struct xfs_btree_cur            *lcur = *ocur;  /* left search cursor */
993         struct xfs_btree_cur            *rcur;  /* right search cursor */
994         struct xfs_inobt_rec_incore     rrec;
995         int                             error;
996         int                             i, j;
997
998         error = xfs_inobt_lookup(lcur, pagino, XFS_LOOKUP_LE, &i);
999         if (error)
1000                 return error;
1001
1002         if (i == 1) {
1003                 error = xfs_inobt_get_rec(lcur, rec, &i);
1004                 if (error)
1005                         return error;
1006                 XFS_WANT_CORRUPTED_RETURN(i == 1);
1007
1008                 /*
1009                  * See if we've landed in the parent inode record. The finobt
1010                  * only tracks chunks with at least one free inode, so record
1011                  * existence is enough.
1012                  */
1013                 if (pagino >= rec->ir_startino &&
1014                     pagino < (rec->ir_startino + XFS_INODES_PER_CHUNK))
1015                         return 0;
1016         }
1017
1018         error = xfs_btree_dup_cursor(lcur, &rcur);
1019         if (error)
1020                 return error;
1021
1022         error = xfs_inobt_lookup(rcur, pagino, XFS_LOOKUP_GE, &j);
1023         if (error)
1024                 goto error_rcur;
1025         if (j == 1) {
1026                 error = xfs_inobt_get_rec(rcur, &rrec, &j);
1027                 if (error)
1028                         goto error_rcur;
1029                 XFS_WANT_CORRUPTED_GOTO(j == 1, error_rcur);
1030         }
1031
1032         XFS_WANT_CORRUPTED_GOTO(i == 1 || j == 1, error_rcur);
1033         if (i == 1 && j == 1) {
1034                 /*
1035                  * Both the left and right records are valid. Choose the closer
1036                  * inode chunk to the target.
1037                  */
1038                 if ((pagino - rec->ir_startino + XFS_INODES_PER_CHUNK - 1) >
1039                     (rrec.ir_startino - pagino)) {
1040                         *rec = rrec;
1041                         xfs_btree_del_cursor(lcur, XFS_BTREE_NOERROR);
1042                         *ocur = rcur;
1043                 } else {
1044                         xfs_btree_del_cursor(rcur, XFS_BTREE_NOERROR);
1045                 }
1046         } else if (j == 1) {
1047                 /* only the right record is valid */
1048                 *rec = rrec;
1049                 xfs_btree_del_cursor(lcur, XFS_BTREE_NOERROR);
1050                 *ocur = rcur;
1051         } else if (i == 1) {
1052                 /* only the left record is valid */
1053                 xfs_btree_del_cursor(rcur, XFS_BTREE_NOERROR);
1054         }
1055
1056         return 0;
1057
1058 error_rcur:
1059         xfs_btree_del_cursor(rcur, XFS_BTREE_ERROR);
1060         return error;
1061 }
1062
1063 /*
1064  * Use the free inode btree to find a free inode based on a newino hint. If
1065  * the hint is NULL, find the first free inode in the AG.
1066  */
1067 STATIC int
1068 xfs_dialloc_ag_finobt_newino(
1069         struct xfs_agi                  *agi,
1070         struct xfs_btree_cur            *cur,
1071         struct xfs_inobt_rec_incore     *rec)
1072 {
1073         int error;
1074         int i;
1075
1076         if (agi->agi_newino != cpu_to_be32(NULLAGINO)) {
1077                 error = xfs_inobt_lookup(cur, be32_to_cpu(agi->agi_newino),
1078                                          XFS_LOOKUP_EQ, &i);
1079                 if (error)
1080                         return error;
1081                 if (i == 1) {
1082                         error = xfs_inobt_get_rec(cur, rec, &i);
1083                         if (error)
1084                                 return error;
1085                         XFS_WANT_CORRUPTED_RETURN(i == 1);
1086                         return 0;
1087                 }
1088         }
1089
1090         /*
1091          * Find the first inode available in the AG.
1092          */
1093         error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &i);
1094         if (error)
1095                 return error;
1096         XFS_WANT_CORRUPTED_RETURN(i == 1);
1097
1098         error = xfs_inobt_get_rec(cur, rec, &i);
1099         if (error)
1100                 return error;
1101         XFS_WANT_CORRUPTED_RETURN(i == 1);
1102
1103         return 0;
1104 }
1105
1106 /*
1107  * Update the inobt based on a modification made to the finobt. Also ensure that
1108  * the records from both trees are equivalent post-modification.
1109  */
1110 STATIC int
1111 xfs_dialloc_ag_update_inobt(
1112         struct xfs_btree_cur            *cur,   /* inobt cursor */
1113         struct xfs_inobt_rec_incore     *frec,  /* finobt record */
1114         int                             offset) /* inode offset */
1115 {
1116         struct xfs_inobt_rec_incore     rec;
1117         int                             error;
1118         int                             i;
1119
1120         error = xfs_inobt_lookup(cur, frec->ir_startino, XFS_LOOKUP_EQ, &i);
1121         if (error)
1122                 return error;
1123         XFS_WANT_CORRUPTED_RETURN(i == 1);
1124
1125         error = xfs_inobt_get_rec(cur, &rec, &i);
1126         if (error)
1127                 return error;
1128         XFS_WANT_CORRUPTED_RETURN(i == 1);
1129         ASSERT((XFS_AGINO_TO_OFFSET(cur->bc_mp, rec.ir_startino) %
1130                                    XFS_INODES_PER_CHUNK) == 0);
1131
1132         rec.ir_free &= ~XFS_INOBT_MASK(offset);
1133         rec.ir_freecount--;
1134
1135         XFS_WANT_CORRUPTED_RETURN((rec.ir_free == frec->ir_free) &&
1136                                   (rec.ir_freecount == frec->ir_freecount));
1137
1138         error = xfs_inobt_update(cur, &rec);
1139         if (error)
1140                 return error;
1141
1142         return 0;
1143 }
1144
1145 /*
1146  * Allocate an inode using the free inode btree, if available. Otherwise, fall
1147  * back to the inobt search algorithm.
1148  *
1149  * The caller selected an AG for us, and made sure that free inodes are
1150  * available.
1151  */
1152 STATIC int
1153 xfs_dialloc_ag(
1154         struct xfs_trans        *tp,
1155         struct xfs_buf          *agbp,
1156         xfs_ino_t               parent,
1157         xfs_ino_t               *inop)
1158 {
1159         struct xfs_mount                *mp = tp->t_mountp;
1160         struct xfs_agi                  *agi = XFS_BUF_TO_AGI(agbp);
1161         xfs_agnumber_t                  agno = be32_to_cpu(agi->agi_seqno);
1162         xfs_agnumber_t                  pagno = XFS_INO_TO_AGNO(mp, parent);
1163         xfs_agino_t                     pagino = XFS_INO_TO_AGINO(mp, parent);
1164         struct xfs_perag                *pag;
1165         struct xfs_btree_cur            *cur;   /* finobt cursor */
1166         struct xfs_btree_cur            *icur;  /* inobt cursor */
1167         struct xfs_inobt_rec_incore     rec;
1168         xfs_ino_t                       ino;
1169         int                             error;
1170         int                             offset;
1171         int                             i;
1172
1173         if (!xfs_sb_version_hasfinobt(&mp->m_sb))
1174                 return xfs_dialloc_ag_inobt(tp, agbp, parent, inop);
1175
1176         pag = xfs_perag_get(mp, agno);
1177
1178         /*
1179          * If pagino is 0 (this is the root inode allocation) use newino.
1180          * This must work because we've just allocated some.
1181          */
1182         if (!pagino)
1183                 pagino = be32_to_cpu(agi->agi_newino);
1184
1185         cur = xfs_inobt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_FINO);
1186
1187         error = xfs_check_agi_freecount(cur, agi);
1188         if (error)
1189                 goto error_cur;
1190
1191         /*
1192          * The search algorithm depends on whether we're in the same AG as the
1193          * parent. If so, find the closest available inode to the parent. If
1194          * not, consider the agi hint or find the first free inode in the AG.
1195          */
1196         if (agno == pagno)
1197                 error = xfs_dialloc_ag_finobt_near(pagino, &cur, &rec);
1198         else
1199                 error = xfs_dialloc_ag_finobt_newino(agi, cur, &rec);
1200         if (error)
1201                 goto error_cur;
1202
1203         offset = xfs_lowbit64(rec.ir_free);
1204         ASSERT(offset >= 0);
1205         ASSERT(offset < XFS_INODES_PER_CHUNK);
1206         ASSERT((XFS_AGINO_TO_OFFSET(mp, rec.ir_startino) %
1207                                    XFS_INODES_PER_CHUNK) == 0);
1208         ino = XFS_AGINO_TO_INO(mp, agno, rec.ir_startino + offset);
1209
1210         /*
1211          * Modify or remove the finobt record.
1212          */
1213         rec.ir_free &= ~XFS_INOBT_MASK(offset);
1214         rec.ir_freecount--;
1215         if (rec.ir_freecount)
1216                 error = xfs_inobt_update(cur, &rec);
1217         else
1218                 error = xfs_btree_delete(cur, &i);
1219         if (error)
1220                 goto error_cur;
1221
1222         /*
1223          * The finobt has now been updated appropriately. We haven't updated the
1224          * agi and superblock yet, so we can create an inobt cursor and validate
1225          * the original freecount. If all is well, make the equivalent update to
1226          * the inobt using the finobt record and offset information.
1227          */
1228         icur = xfs_inobt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_INO);
1229
1230         error = xfs_check_agi_freecount(icur, agi);
1231         if (error)
1232                 goto error_icur;
1233
1234         error = xfs_dialloc_ag_update_inobt(icur, &rec, offset);
1235         if (error)
1236                 goto error_icur;
1237
1238         /*
1239          * Both trees have now been updated. We must update the perag and
1240          * superblock before we can check the freecount for each btree.
1241          */
1242         be32_add_cpu(&agi->agi_freecount, -1);
1243         xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
1244         pag->pagi_freecount--;
1245
1246         xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -1);
1247
1248         error = xfs_check_agi_freecount(icur, agi);
1249         if (error)
1250                 goto error_icur;
1251         error = xfs_check_agi_freecount(cur, agi);
1252         if (error)
1253                 goto error_icur;
1254
1255         xfs_btree_del_cursor(icur, XFS_BTREE_NOERROR);
1256         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1257         xfs_perag_put(pag);
1258         *inop = ino;
1259         return 0;
1260
1261 error_icur:
1262         xfs_btree_del_cursor(icur, XFS_BTREE_ERROR);
1263 error_cur:
1264         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1265         xfs_perag_put(pag);
1266         return error;
1267 }
1268
1269 /*
1270  * Allocate an inode on disk.
1271  *
1272  * Mode is used to tell whether the new inode will need space, and whether it
1273  * is a directory.
1274  *
1275  * This function is designed to be called twice if it has to do an allocation
1276  * to make more free inodes.  On the first call, *IO_agbp should be set to NULL.
1277  * If an inode is available without having to performn an allocation, an inode
1278  * number is returned.  In this case, *IO_agbp is set to NULL.  If an allocation
1279  * needs to be done, xfs_dialloc returns the current AGI buffer in *IO_agbp.
1280  * The caller should then commit the current transaction, allocate a
1281  * new transaction, and call xfs_dialloc() again, passing in the previous value
1282  * of *IO_agbp.  IO_agbp should be held across the transactions. Since the AGI
1283  * buffer is locked across the two calls, the second call is guaranteed to have
1284  * a free inode available.
1285  *
1286  * Once we successfully pick an inode its number is returned and the on-disk
1287  * data structures are updated.  The inode itself is not read in, since doing so
1288  * would break ordering constraints with xfs_reclaim.
1289  */
1290 int
1291 xfs_dialloc(
1292         struct xfs_trans        *tp,
1293         xfs_ino_t               parent,
1294         umode_t                 mode,
1295         int                     okalloc,
1296         struct xfs_buf          **IO_agbp,
1297         xfs_ino_t               *inop)
1298 {
1299         struct xfs_mount        *mp = tp->t_mountp;
1300         struct xfs_buf          *agbp;
1301         xfs_agnumber_t          agno;
1302         int                     error;
1303         int                     ialloced;
1304         int                     noroom = 0;
1305         xfs_agnumber_t          start_agno;
1306         struct xfs_perag        *pag;
1307
1308         if (*IO_agbp) {
1309                 /*
1310                  * If the caller passes in a pointer to the AGI buffer,
1311                  * continue where we left off before.  In this case, we
1312                  * know that the allocation group has free inodes.
1313                  */
1314                 agbp = *IO_agbp;
1315                 goto out_alloc;
1316         }
1317
1318         /*
1319          * We do not have an agbp, so select an initial allocation
1320          * group for inode allocation.
1321          */
1322         start_agno = xfs_ialloc_ag_select(tp, parent, mode, okalloc);
1323         if (start_agno == NULLAGNUMBER) {
1324                 *inop = NULLFSINO;
1325                 return 0;
1326         }
1327
1328         /*
1329          * If we have already hit the ceiling of inode blocks then clear
1330          * okalloc so we scan all available agi structures for a free
1331          * inode.
1332          */
1333         if (mp->m_maxicount &&
1334             mp->m_sb.sb_icount + mp->m_ialloc_inos > mp->m_maxicount) {
1335                 noroom = 1;
1336                 okalloc = 0;
1337         }
1338
1339         /*
1340          * Loop until we find an allocation group that either has free inodes
1341          * or in which we can allocate some inodes.  Iterate through the
1342          * allocation groups upward, wrapping at the end.
1343          */
1344         agno = start_agno;
1345         for (;;) {
1346                 pag = xfs_perag_get(mp, agno);
1347                 if (!pag->pagi_inodeok) {
1348                         xfs_ialloc_next_ag(mp);
1349                         goto nextag;
1350                 }
1351
1352                 if (!pag->pagi_init) {
1353                         error = xfs_ialloc_pagi_init(mp, tp, agno);
1354                         if (error)
1355                                 goto out_error;
1356                 }
1357
1358                 /*
1359                  * Do a first racy fast path check if this AG is usable.
1360                  */
1361                 if (!pag->pagi_freecount && !okalloc)
1362                         goto nextag;
1363
1364                 /*
1365                  * Then read in the AGI buffer and recheck with the AGI buffer
1366                  * lock held.
1367                  */
1368                 error = xfs_ialloc_read_agi(mp, tp, agno, &agbp);
1369                 if (error)
1370                         goto out_error;
1371
1372                 if (pag->pagi_freecount) {
1373                         xfs_perag_put(pag);
1374                         goto out_alloc;
1375                 }
1376
1377                 if (!okalloc)
1378                         goto nextag_relse_buffer;
1379
1380
1381                 error = xfs_ialloc_ag_alloc(tp, agbp, &ialloced);
1382                 if (error) {
1383                         xfs_trans_brelse(tp, agbp);
1384
1385                         if (error != -ENOSPC)
1386                                 goto out_error;
1387
1388                         xfs_perag_put(pag);
1389                         *inop = NULLFSINO;
1390                         return 0;
1391                 }
1392
1393                 if (ialloced) {
1394                         /*
1395                          * We successfully allocated some inodes, return
1396                          * the current context to the caller so that it
1397                          * can commit the current transaction and call
1398                          * us again where we left off.
1399                          */
1400                         ASSERT(pag->pagi_freecount > 0);
1401                         xfs_perag_put(pag);
1402
1403                         *IO_agbp = agbp;
1404                         *inop = NULLFSINO;
1405                         return 0;
1406                 }
1407
1408 nextag_relse_buffer:
1409                 xfs_trans_brelse(tp, agbp);
1410 nextag:
1411                 xfs_perag_put(pag);
1412                 if (++agno == mp->m_sb.sb_agcount)
1413                         agno = 0;
1414                 if (agno == start_agno) {
1415                         *inop = NULLFSINO;
1416                         return noroom ? -ENOSPC : 0;
1417                 }
1418         }
1419
1420 out_alloc:
1421         *IO_agbp = NULL;
1422         return xfs_dialloc_ag(tp, agbp, parent, inop);
1423 out_error:
1424         xfs_perag_put(pag);
1425         return error;
1426 }
1427
1428 STATIC int
1429 xfs_difree_inobt(
1430         struct xfs_mount                *mp,
1431         struct xfs_trans                *tp,
1432         struct xfs_buf                  *agbp,
1433         xfs_agino_t                     agino,
1434         struct xfs_bmap_free            *flist,
1435         int                             *deleted,
1436         xfs_ino_t                       *first_ino,
1437         struct xfs_inobt_rec_incore     *orec)
1438 {
1439         struct xfs_agi                  *agi = XFS_BUF_TO_AGI(agbp);
1440         xfs_agnumber_t                  agno = be32_to_cpu(agi->agi_seqno);
1441         struct xfs_perag                *pag;
1442         struct xfs_btree_cur            *cur;
1443         struct xfs_inobt_rec_incore     rec;
1444         int                             ilen;
1445         int                             error;
1446         int                             i;
1447         int                             off;
1448
1449         ASSERT(agi->agi_magicnum == cpu_to_be32(XFS_AGI_MAGIC));
1450         ASSERT(XFS_AGINO_TO_AGBNO(mp, agino) < be32_to_cpu(agi->agi_length));
1451
1452         /*
1453          * Initialize the cursor.
1454          */
1455         cur = xfs_inobt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_INO);
1456
1457         error = xfs_check_agi_freecount(cur, agi);
1458         if (error)
1459                 goto error0;
1460
1461         /*
1462          * Look for the entry describing this inode.
1463          */
1464         if ((error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_LE, &i))) {
1465                 xfs_warn(mp, "%s: xfs_inobt_lookup() returned error %d.",
1466                         __func__, error);
1467                 goto error0;
1468         }
1469         XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
1470         error = xfs_inobt_get_rec(cur, &rec, &i);
1471         if (error) {
1472                 xfs_warn(mp, "%s: xfs_inobt_get_rec() returned error %d.",
1473                         __func__, error);
1474                 goto error0;
1475         }
1476         XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
1477         /*
1478          * Get the offset in the inode chunk.
1479          */
1480         off = agino - rec.ir_startino;
1481         ASSERT(off >= 0 && off < XFS_INODES_PER_CHUNK);
1482         ASSERT(!(rec.ir_free & XFS_INOBT_MASK(off)));
1483         /*
1484          * Mark the inode free & increment the count.
1485          */
1486         rec.ir_free |= XFS_INOBT_MASK(off);
1487         rec.ir_freecount++;
1488
1489         /*
1490          * When an inode cluster is free, it becomes eligible for removal
1491          */
1492         if (!(mp->m_flags & XFS_MOUNT_IKEEP) &&
1493             (rec.ir_freecount == mp->m_ialloc_inos)) {
1494
1495                 *deleted = 1;
1496                 *first_ino = XFS_AGINO_TO_INO(mp, agno, rec.ir_startino);
1497
1498                 /*
1499                  * Remove the inode cluster from the AGI B+Tree, adjust the
1500                  * AGI and Superblock inode counts, and mark the disk space
1501                  * to be freed when the transaction is committed.
1502                  */
1503                 ilen = mp->m_ialloc_inos;
1504                 be32_add_cpu(&agi->agi_count, -ilen);
1505                 be32_add_cpu(&agi->agi_freecount, -(ilen - 1));
1506                 xfs_ialloc_log_agi(tp, agbp, XFS_AGI_COUNT | XFS_AGI_FREECOUNT);
1507                 pag = xfs_perag_get(mp, agno);
1508                 pag->pagi_freecount -= ilen - 1;
1509                 xfs_perag_put(pag);
1510                 xfs_trans_mod_sb(tp, XFS_TRANS_SB_ICOUNT, -ilen);
1511                 xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -(ilen - 1));
1512
1513                 if ((error = xfs_btree_delete(cur, &i))) {
1514                         xfs_warn(mp, "%s: xfs_btree_delete returned error %d.",
1515                                 __func__, error);
1516                         goto error0;
1517                 }
1518
1519                 xfs_bmap_add_free(XFS_AGB_TO_FSB(mp, agno,
1520                                   XFS_AGINO_TO_AGBNO(mp, rec.ir_startino)),
1521                                   mp->m_ialloc_blks, flist, mp);
1522         } else {
1523                 *deleted = 0;
1524
1525                 error = xfs_inobt_update(cur, &rec);
1526                 if (error) {
1527                         xfs_warn(mp, "%s: xfs_inobt_update returned error %d.",
1528                                 __func__, error);
1529                         goto error0;
1530                 }
1531
1532                 /* 
1533                  * Change the inode free counts and log the ag/sb changes.
1534                  */
1535                 be32_add_cpu(&agi->agi_freecount, 1);
1536                 xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
1537                 pag = xfs_perag_get(mp, agno);
1538                 pag->pagi_freecount++;
1539                 xfs_perag_put(pag);
1540                 xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, 1);
1541         }
1542
1543         error = xfs_check_agi_freecount(cur, agi);
1544         if (error)
1545                 goto error0;
1546
1547         *orec = rec;
1548         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1549         return 0;
1550
1551 error0:
1552         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1553         return error;
1554 }
1555
1556 /*
1557  * Free an inode in the free inode btree.
1558  */
1559 STATIC int
1560 xfs_difree_finobt(
1561         struct xfs_mount                *mp,
1562         struct xfs_trans                *tp,
1563         struct xfs_buf                  *agbp,
1564         xfs_agino_t                     agino,
1565         struct xfs_inobt_rec_incore     *ibtrec) /* inobt record */
1566 {
1567         struct xfs_agi                  *agi = XFS_BUF_TO_AGI(agbp);
1568         xfs_agnumber_t                  agno = be32_to_cpu(agi->agi_seqno);
1569         struct xfs_btree_cur            *cur;
1570         struct xfs_inobt_rec_incore     rec;
1571         int                             offset = agino - ibtrec->ir_startino;
1572         int                             error;
1573         int                             i;
1574
1575         cur = xfs_inobt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_FINO);
1576
1577         error = xfs_inobt_lookup(cur, ibtrec->ir_startino, XFS_LOOKUP_EQ, &i);
1578         if (error)
1579                 goto error;
1580         if (i == 0) {
1581                 /*
1582                  * If the record does not exist in the finobt, we must have just
1583                  * freed an inode in a previously fully allocated chunk. If not,
1584                  * something is out of sync.
1585                  */
1586                 XFS_WANT_CORRUPTED_GOTO(ibtrec->ir_freecount == 1, error);
1587
1588                 error = xfs_inobt_insert_rec(cur, ibtrec->ir_freecount,
1589                                              ibtrec->ir_free, &i);
1590                 if (error)
1591                         goto error;
1592                 ASSERT(i == 1);
1593
1594                 goto out;
1595         }
1596
1597         /*
1598          * Read and update the existing record. We could just copy the ibtrec
1599          * across here, but that would defeat the purpose of having redundant
1600          * metadata. By making the modifications independently, we can catch
1601          * corruptions that we wouldn't see if we just copied from one record
1602          * to another.
1603          */
1604         error = xfs_inobt_get_rec(cur, &rec, &i);
1605         if (error)
1606                 goto error;
1607         XFS_WANT_CORRUPTED_GOTO(i == 1, error);
1608
1609         rec.ir_free |= XFS_INOBT_MASK(offset);
1610         rec.ir_freecount++;
1611
1612         XFS_WANT_CORRUPTED_GOTO((rec.ir_free == ibtrec->ir_free) &&
1613                                 (rec.ir_freecount == ibtrec->ir_freecount),
1614                                 error);
1615
1616         /*
1617          * The content of inobt records should always match between the inobt
1618          * and finobt. The lifecycle of records in the finobt is different from
1619          * the inobt in that the finobt only tracks records with at least one
1620          * free inode. Hence, if all of the inodes are free and we aren't
1621          * keeping inode chunks permanently on disk, remove the record.
1622          * Otherwise, update the record with the new information.
1623          */
1624         if (rec.ir_freecount == mp->m_ialloc_inos &&
1625             !(mp->m_flags & XFS_MOUNT_IKEEP)) {
1626                 error = xfs_btree_delete(cur, &i);
1627                 if (error)
1628                         goto error;
1629                 ASSERT(i == 1);
1630         } else {
1631                 error = xfs_inobt_update(cur, &rec);
1632                 if (error)
1633                         goto error;
1634         }
1635
1636 out:
1637         error = xfs_check_agi_freecount(cur, agi);
1638         if (error)
1639                 goto error;
1640
1641         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1642         return 0;
1643
1644 error:
1645         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1646         return error;
1647 }
1648
1649 /*
1650  * Free disk inode.  Carefully avoids touching the incore inode, all
1651  * manipulations incore are the caller's responsibility.
1652  * The on-disk inode is not changed by this operation, only the
1653  * btree (free inode mask) is changed.
1654  */
1655 int
1656 xfs_difree(
1657         struct xfs_trans        *tp,            /* transaction pointer */
1658         xfs_ino_t               inode,          /* inode to be freed */
1659         struct xfs_bmap_free    *flist,         /* extents to free */
1660         int                     *deleted,/* set if inode cluster was deleted */
1661         xfs_ino_t               *first_ino)/* first inode in deleted cluster */
1662 {
1663         /* REFERENCED */
1664         xfs_agblock_t           agbno;  /* block number containing inode */
1665         struct xfs_buf          *agbp;  /* buffer for allocation group header */
1666         xfs_agino_t             agino;  /* allocation group inode number */
1667         xfs_agnumber_t          agno;   /* allocation group number */
1668         int                     error;  /* error return value */
1669         struct xfs_mount        *mp;    /* mount structure for filesystem */
1670         struct xfs_inobt_rec_incore rec;/* btree record */
1671
1672         mp = tp->t_mountp;
1673
1674         /*
1675          * Break up inode number into its components.
1676          */
1677         agno = XFS_INO_TO_AGNO(mp, inode);
1678         if (agno >= mp->m_sb.sb_agcount)  {
1679                 xfs_warn(mp, "%s: agno >= mp->m_sb.sb_agcount (%d >= %d).",
1680                         __func__, agno, mp->m_sb.sb_agcount);
1681                 ASSERT(0);
1682                 return -EINVAL;
1683         }
1684         agino = XFS_INO_TO_AGINO(mp, inode);
1685         if (inode != XFS_AGINO_TO_INO(mp, agno, agino))  {
1686                 xfs_warn(mp, "%s: inode != XFS_AGINO_TO_INO() (%llu != %llu).",
1687                         __func__, (unsigned long long)inode,
1688                         (unsigned long long)XFS_AGINO_TO_INO(mp, agno, agino));
1689                 ASSERT(0);
1690                 return -EINVAL;
1691         }
1692         agbno = XFS_AGINO_TO_AGBNO(mp, agino);
1693         if (agbno >= mp->m_sb.sb_agblocks)  {
1694                 xfs_warn(mp, "%s: agbno >= mp->m_sb.sb_agblocks (%d >= %d).",
1695                         __func__, agbno, mp->m_sb.sb_agblocks);
1696                 ASSERT(0);
1697                 return -EINVAL;
1698         }
1699         /*
1700          * Get the allocation group header.
1701          */
1702         error = xfs_ialloc_read_agi(mp, tp, agno, &agbp);
1703         if (error) {
1704                 xfs_warn(mp, "%s: xfs_ialloc_read_agi() returned error %d.",
1705                         __func__, error);
1706                 return error;
1707         }
1708
1709         /*
1710          * Fix up the inode allocation btree.
1711          */
1712         error = xfs_difree_inobt(mp, tp, agbp, agino, flist, deleted, first_ino,
1713                                  &rec);
1714         if (error)
1715                 goto error0;
1716
1717         /*
1718          * Fix up the free inode btree.
1719          */
1720         if (xfs_sb_version_hasfinobt(&mp->m_sb)) {
1721                 error = xfs_difree_finobt(mp, tp, agbp, agino, &rec);
1722                 if (error)
1723                         goto error0;
1724         }
1725
1726         return 0;
1727
1728 error0:
1729         return error;
1730 }
1731
1732 STATIC int
1733 xfs_imap_lookup(
1734         struct xfs_mount        *mp,
1735         struct xfs_trans        *tp,
1736         xfs_agnumber_t          agno,
1737         xfs_agino_t             agino,
1738         xfs_agblock_t           agbno,
1739         xfs_agblock_t           *chunk_agbno,
1740         xfs_agblock_t           *offset_agbno,
1741         int                     flags)
1742 {
1743         struct xfs_inobt_rec_incore rec;
1744         struct xfs_btree_cur    *cur;
1745         struct xfs_buf          *agbp;
1746         int                     error;
1747         int                     i;
1748
1749         error = xfs_ialloc_read_agi(mp, tp, agno, &agbp);
1750         if (error) {
1751                 xfs_alert(mp,
1752                         "%s: xfs_ialloc_read_agi() returned error %d, agno %d",
1753                         __func__, error, agno);
1754                 return error;
1755         }
1756
1757         /*
1758          * Lookup the inode record for the given agino. If the record cannot be
1759          * found, then it's an invalid inode number and we should abort. Once
1760          * we have a record, we need to ensure it contains the inode number
1761          * we are looking up.
1762          */
1763         cur = xfs_inobt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_INO);
1764         error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_LE, &i);
1765         if (!error) {
1766                 if (i)
1767                         error = xfs_inobt_get_rec(cur, &rec, &i);
1768                 if (!error && i == 0)
1769                         error = -EINVAL;
1770         }
1771
1772         xfs_trans_brelse(tp, agbp);
1773         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1774         if (error)
1775                 return error;
1776
1777         /* check that the returned record contains the required inode */
1778         if (rec.ir_startino > agino ||
1779             rec.ir_startino + mp->m_ialloc_inos <= agino)
1780                 return -EINVAL;
1781
1782         /* for untrusted inodes check it is allocated first */
1783         if ((flags & XFS_IGET_UNTRUSTED) &&
1784             (rec.ir_free & XFS_INOBT_MASK(agino - rec.ir_startino)))
1785                 return -EINVAL;
1786
1787         *chunk_agbno = XFS_AGINO_TO_AGBNO(mp, rec.ir_startino);
1788         *offset_agbno = agbno - *chunk_agbno;
1789         return 0;
1790 }
1791
1792 /*
1793  * Return the location of the inode in imap, for mapping it into a buffer.
1794  */
1795 int
1796 xfs_imap(
1797         xfs_mount_t      *mp,   /* file system mount structure */
1798         xfs_trans_t      *tp,   /* transaction pointer */
1799         xfs_ino_t       ino,    /* inode to locate */
1800         struct xfs_imap *imap,  /* location map structure */
1801         uint            flags)  /* flags for inode btree lookup */
1802 {
1803         xfs_agblock_t   agbno;  /* block number of inode in the alloc group */
1804         xfs_agino_t     agino;  /* inode number within alloc group */
1805         xfs_agnumber_t  agno;   /* allocation group number */
1806         int             blks_per_cluster; /* num blocks per inode cluster */
1807         xfs_agblock_t   chunk_agbno;    /* first block in inode chunk */
1808         xfs_agblock_t   cluster_agbno;  /* first block in inode cluster */
1809         int             error;  /* error code */
1810         int             offset; /* index of inode in its buffer */
1811         xfs_agblock_t   offset_agbno;   /* blks from chunk start to inode */
1812
1813         ASSERT(ino != NULLFSINO);
1814
1815         /*
1816          * Split up the inode number into its parts.
1817          */
1818         agno = XFS_INO_TO_AGNO(mp, ino);
1819         agino = XFS_INO_TO_AGINO(mp, ino);
1820         agbno = XFS_AGINO_TO_AGBNO(mp, agino);
1821         if (agno >= mp->m_sb.sb_agcount || agbno >= mp->m_sb.sb_agblocks ||
1822             ino != XFS_AGINO_TO_INO(mp, agno, agino)) {
1823 #ifdef DEBUG
1824                 /*
1825                  * Don't output diagnostic information for untrusted inodes
1826                  * as they can be invalid without implying corruption.
1827                  */
1828                 if (flags & XFS_IGET_UNTRUSTED)
1829                         return -EINVAL;
1830                 if (agno >= mp->m_sb.sb_agcount) {
1831                         xfs_alert(mp,
1832                                 "%s: agno (%d) >= mp->m_sb.sb_agcount (%d)",
1833                                 __func__, agno, mp->m_sb.sb_agcount);
1834                 }
1835                 if (agbno >= mp->m_sb.sb_agblocks) {
1836                         xfs_alert(mp,
1837                 "%s: agbno (0x%llx) >= mp->m_sb.sb_agblocks (0x%lx)",
1838                                 __func__, (unsigned long long)agbno,
1839                                 (unsigned long)mp->m_sb.sb_agblocks);
1840                 }
1841                 if (ino != XFS_AGINO_TO_INO(mp, agno, agino)) {
1842                         xfs_alert(mp,
1843                 "%s: ino (0x%llx) != XFS_AGINO_TO_INO() (0x%llx)",
1844                                 __func__, ino,
1845                                 XFS_AGINO_TO_INO(mp, agno, agino));
1846                 }
1847                 xfs_stack_trace();
1848 #endif /* DEBUG */
1849                 return -EINVAL;
1850         }
1851
1852         blks_per_cluster = xfs_icluster_size_fsb(mp);
1853
1854         /*
1855          * For bulkstat and handle lookups, we have an untrusted inode number
1856          * that we have to verify is valid. We cannot do this just by reading
1857          * the inode buffer as it may have been unlinked and removed leaving
1858          * inodes in stale state on disk. Hence we have to do a btree lookup
1859          * in all cases where an untrusted inode number is passed.
1860          */
1861         if (flags & XFS_IGET_UNTRUSTED) {
1862                 error = xfs_imap_lookup(mp, tp, agno, agino, agbno,
1863                                         &chunk_agbno, &offset_agbno, flags);
1864                 if (error)
1865                         return error;
1866                 goto out_map;
1867         }
1868
1869         /*
1870          * If the inode cluster size is the same as the blocksize or
1871          * smaller we get to the buffer by simple arithmetics.
1872          */
1873         if (blks_per_cluster == 1) {
1874                 offset = XFS_INO_TO_OFFSET(mp, ino);
1875                 ASSERT(offset < mp->m_sb.sb_inopblock);
1876
1877                 imap->im_blkno = XFS_AGB_TO_DADDR(mp, agno, agbno);
1878                 imap->im_len = XFS_FSB_TO_BB(mp, 1);
1879                 imap->im_boffset = (ushort)(offset << mp->m_sb.sb_inodelog);
1880                 return 0;
1881         }
1882
1883         /*
1884          * If the inode chunks are aligned then use simple maths to
1885          * find the location. Otherwise we have to do a btree
1886          * lookup to find the location.
1887          */
1888         if (mp->m_inoalign_mask) {
1889                 offset_agbno = agbno & mp->m_inoalign_mask;
1890                 chunk_agbno = agbno - offset_agbno;
1891         } else {
1892                 error = xfs_imap_lookup(mp, tp, agno, agino, agbno,
1893                                         &chunk_agbno, &offset_agbno, flags);
1894                 if (error)
1895                         return error;
1896         }
1897
1898 out_map:
1899         ASSERT(agbno >= chunk_agbno);
1900         cluster_agbno = chunk_agbno +
1901                 ((offset_agbno / blks_per_cluster) * blks_per_cluster);
1902         offset = ((agbno - cluster_agbno) * mp->m_sb.sb_inopblock) +
1903                 XFS_INO_TO_OFFSET(mp, ino);
1904
1905         imap->im_blkno = XFS_AGB_TO_DADDR(mp, agno, cluster_agbno);
1906         imap->im_len = XFS_FSB_TO_BB(mp, blks_per_cluster);
1907         imap->im_boffset = (ushort)(offset << mp->m_sb.sb_inodelog);
1908
1909         /*
1910          * If the inode number maps to a block outside the bounds
1911          * of the file system then return NULL rather than calling
1912          * read_buf and panicing when we get an error from the
1913          * driver.
1914          */
1915         if ((imap->im_blkno + imap->im_len) >
1916             XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks)) {
1917                 xfs_alert(mp,
1918         "%s: (im_blkno (0x%llx) + im_len (0x%llx)) > sb_dblocks (0x%llx)",
1919                         __func__, (unsigned long long) imap->im_blkno,
1920                         (unsigned long long) imap->im_len,
1921                         XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks));
1922                 return -EINVAL;
1923         }
1924         return 0;
1925 }
1926
1927 /*
1928  * Compute and fill in value of m_in_maxlevels.
1929  */
1930 void
1931 xfs_ialloc_compute_maxlevels(
1932         xfs_mount_t     *mp)            /* file system mount structure */
1933 {
1934         int             level;
1935         uint            maxblocks;
1936         uint            maxleafents;
1937         int             minleafrecs;
1938         int             minnoderecs;
1939
1940         maxleafents = (1LL << XFS_INO_AGINO_BITS(mp)) >>
1941                 XFS_INODES_PER_CHUNK_LOG;
1942         minleafrecs = mp->m_alloc_mnr[0];
1943         minnoderecs = mp->m_alloc_mnr[1];
1944         maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs;
1945         for (level = 1; maxblocks > 1; level++)
1946                 maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs;
1947         mp->m_in_maxlevels = level;
1948 }
1949
1950 /*
1951  * Log specified fields for the ag hdr (inode section). The growth of the agi
1952  * structure over time requires that we interpret the buffer as two logical
1953  * regions delineated by the end of the unlinked list. This is due to the size
1954  * of the hash table and its location in the middle of the agi.
1955  *
1956  * For example, a request to log a field before agi_unlinked and a field after
1957  * agi_unlinked could cause us to log the entire hash table and use an excessive
1958  * amount of log space. To avoid this behavior, log the region up through
1959  * agi_unlinked in one call and the region after agi_unlinked through the end of
1960  * the structure in another.
1961  */
1962 void
1963 xfs_ialloc_log_agi(
1964         xfs_trans_t     *tp,            /* transaction pointer */
1965         xfs_buf_t       *bp,            /* allocation group header buffer */
1966         int             fields)         /* bitmask of fields to log */
1967 {
1968         int                     first;          /* first byte number */
1969         int                     last;           /* last byte number */
1970         static const short      offsets[] = {   /* field starting offsets */
1971                                         /* keep in sync with bit definitions */
1972                 offsetof(xfs_agi_t, agi_magicnum),
1973                 offsetof(xfs_agi_t, agi_versionnum),
1974                 offsetof(xfs_agi_t, agi_seqno),
1975                 offsetof(xfs_agi_t, agi_length),
1976                 offsetof(xfs_agi_t, agi_count),
1977                 offsetof(xfs_agi_t, agi_root),
1978                 offsetof(xfs_agi_t, agi_level),
1979                 offsetof(xfs_agi_t, agi_freecount),
1980                 offsetof(xfs_agi_t, agi_newino),
1981                 offsetof(xfs_agi_t, agi_dirino),
1982                 offsetof(xfs_agi_t, agi_unlinked),
1983                 offsetof(xfs_agi_t, agi_free_root),
1984                 offsetof(xfs_agi_t, agi_free_level),
1985                 sizeof(xfs_agi_t)
1986         };
1987 #ifdef DEBUG
1988         xfs_agi_t               *agi;   /* allocation group header */
1989
1990         agi = XFS_BUF_TO_AGI(bp);
1991         ASSERT(agi->agi_magicnum == cpu_to_be32(XFS_AGI_MAGIC));
1992 #endif
1993
1994         xfs_trans_buf_set_type(tp, bp, XFS_BLFT_AGI_BUF);
1995
1996         /*
1997          * Compute byte offsets for the first and last fields in the first
1998          * region and log the agi buffer. This only logs up through
1999          * agi_unlinked.
2000          */
2001         if (fields & XFS_AGI_ALL_BITS_R1) {
2002                 xfs_btree_offsets(fields, offsets, XFS_AGI_NUM_BITS_R1,
2003                                   &first, &last);
2004                 xfs_trans_log_buf(tp, bp, first, last);
2005         }
2006
2007         /*
2008          * Mask off the bits in the first region and calculate the first and
2009          * last field offsets for any bits in the second region.
2010          */
2011         fields &= ~XFS_AGI_ALL_BITS_R1;
2012         if (fields) {
2013                 xfs_btree_offsets(fields, offsets, XFS_AGI_NUM_BITS_R2,
2014                                   &first, &last);
2015                 xfs_trans_log_buf(tp, bp, first, last);
2016         }
2017 }
2018
2019 #ifdef DEBUG
2020 STATIC void
2021 xfs_check_agi_unlinked(
2022         struct xfs_agi          *agi)
2023 {
2024         int                     i;
2025
2026         for (i = 0; i < XFS_AGI_UNLINKED_BUCKETS; i++)
2027                 ASSERT(agi->agi_unlinked[i]);
2028 }
2029 #else
2030 #define xfs_check_agi_unlinked(agi)
2031 #endif
2032
2033 static bool
2034 xfs_agi_verify(
2035         struct xfs_buf  *bp)
2036 {
2037         struct xfs_mount *mp = bp->b_target->bt_mount;
2038         struct xfs_agi  *agi = XFS_BUF_TO_AGI(bp);
2039
2040         if (xfs_sb_version_hascrc(&mp->m_sb) &&
2041             !uuid_equal(&agi->agi_uuid, &mp->m_sb.sb_uuid))
2042                         return false;
2043         /*
2044          * Validate the magic number of the agi block.
2045          */
2046         if (agi->agi_magicnum != cpu_to_be32(XFS_AGI_MAGIC))
2047                 return false;
2048         if (!XFS_AGI_GOOD_VERSION(be32_to_cpu(agi->agi_versionnum)))
2049                 return false;
2050
2051         if (be32_to_cpu(agi->agi_level) > XFS_BTREE_MAXLEVELS)
2052                 return false;
2053         /*
2054          * during growfs operations, the perag is not fully initialised,
2055          * so we can't use it for any useful checking. growfs ensures we can't
2056          * use it by using uncached buffers that don't have the perag attached
2057          * so we can detect and avoid this problem.
2058          */
2059         if (bp->b_pag && be32_to_cpu(agi->agi_seqno) != bp->b_pag->pag_agno)
2060                 return false;
2061
2062         xfs_check_agi_unlinked(agi);
2063         return true;
2064 }
2065
2066 static void
2067 xfs_agi_read_verify(
2068         struct xfs_buf  *bp)
2069 {
2070         struct xfs_mount *mp = bp->b_target->bt_mount;
2071
2072         if (xfs_sb_version_hascrc(&mp->m_sb) &&
2073             !xfs_buf_verify_cksum(bp, XFS_AGI_CRC_OFF))
2074                 xfs_buf_ioerror(bp, -EFSBADCRC);
2075         else if (XFS_TEST_ERROR(!xfs_agi_verify(bp), mp,
2076                                 XFS_ERRTAG_IALLOC_READ_AGI,
2077                                 XFS_RANDOM_IALLOC_READ_AGI))
2078                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
2079
2080         if (bp->b_error)
2081                 xfs_verifier_error(bp);
2082 }
2083
2084 static void
2085 xfs_agi_write_verify(
2086         struct xfs_buf  *bp)
2087 {
2088         struct xfs_mount *mp = bp->b_target->bt_mount;
2089         struct xfs_buf_log_item *bip = bp->b_fspriv;
2090
2091         if (!xfs_agi_verify(bp)) {
2092                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
2093                 xfs_verifier_error(bp);
2094                 return;
2095         }
2096
2097         if (!xfs_sb_version_hascrc(&mp->m_sb))
2098                 return;
2099
2100         if (bip)
2101                 XFS_BUF_TO_AGI(bp)->agi_lsn = cpu_to_be64(bip->bli_item.li_lsn);
2102         xfs_buf_update_cksum(bp, XFS_AGI_CRC_OFF);
2103 }
2104
2105 const struct xfs_buf_ops xfs_agi_buf_ops = {
2106         .verify_read = xfs_agi_read_verify,
2107         .verify_write = xfs_agi_write_verify,
2108 };
2109
2110 /*
2111  * Read in the allocation group header (inode allocation section)
2112  */
2113 int
2114 xfs_read_agi(
2115         struct xfs_mount        *mp,    /* file system mount structure */
2116         struct xfs_trans        *tp,    /* transaction pointer */
2117         xfs_agnumber_t          agno,   /* allocation group number */
2118         struct xfs_buf          **bpp)  /* allocation group hdr buf */
2119 {
2120         int                     error;
2121
2122         trace_xfs_read_agi(mp, agno);
2123
2124         ASSERT(agno != NULLAGNUMBER);
2125         error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp,
2126                         XFS_AG_DADDR(mp, agno, XFS_AGI_DADDR(mp)),
2127                         XFS_FSS_TO_BB(mp, 1), 0, bpp, &xfs_agi_buf_ops);
2128         if (error)
2129                 return error;
2130
2131         xfs_buf_set_ref(*bpp, XFS_AGI_REF);
2132         return 0;
2133 }
2134
2135 int
2136 xfs_ialloc_read_agi(
2137         struct xfs_mount        *mp,    /* file system mount structure */
2138         struct xfs_trans        *tp,    /* transaction pointer */
2139         xfs_agnumber_t          agno,   /* allocation group number */
2140         struct xfs_buf          **bpp)  /* allocation group hdr buf */
2141 {
2142         struct xfs_agi          *agi;   /* allocation group header */
2143         struct xfs_perag        *pag;   /* per allocation group data */
2144         int                     error;
2145
2146         trace_xfs_ialloc_read_agi(mp, agno);
2147
2148         error = xfs_read_agi(mp, tp, agno, bpp);
2149         if (error)
2150                 return error;
2151
2152         agi = XFS_BUF_TO_AGI(*bpp);
2153         pag = xfs_perag_get(mp, agno);
2154         if (!pag->pagi_init) {
2155                 pag->pagi_freecount = be32_to_cpu(agi->agi_freecount);
2156                 pag->pagi_count = be32_to_cpu(agi->agi_count);
2157                 pag->pagi_init = 1;
2158         }
2159
2160         /*
2161          * It's possible for these to be out of sync if
2162          * we are in the middle of a forced shutdown.
2163          */
2164         ASSERT(pag->pagi_freecount == be32_to_cpu(agi->agi_freecount) ||
2165                 XFS_FORCED_SHUTDOWN(mp));
2166         xfs_perag_put(pag);
2167         return 0;
2168 }
2169
2170 /*
2171  * Read in the agi to initialise the per-ag data in the mount structure
2172  */
2173 int
2174 xfs_ialloc_pagi_init(
2175         xfs_mount_t     *mp,            /* file system mount structure */
2176         xfs_trans_t     *tp,            /* transaction pointer */
2177         xfs_agnumber_t  agno)           /* allocation group number */
2178 {
2179         xfs_buf_t       *bp = NULL;
2180         int             error;
2181
2182         error = xfs_ialloc_read_agi(mp, tp, agno, &bp);
2183         if (error)
2184                 return error;
2185         if (bp)
2186                 xfs_trans_brelse(tp, bp);
2187         return 0;
2188 }