xfs: factor out debug checks from xfs_dialloc and xfs_difree
[safe/jmp/linux-2.6] / fs / xfs / 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_types.h"
21 #include "xfs_bit.h"
22 #include "xfs_log.h"
23 #include "xfs_inum.h"
24 #include "xfs_trans.h"
25 #include "xfs_sb.h"
26 #include "xfs_ag.h"
27 #include "xfs_dir2.h"
28 #include "xfs_dmapi.h"
29 #include "xfs_mount.h"
30 #include "xfs_bmap_btree.h"
31 #include "xfs_alloc_btree.h"
32 #include "xfs_ialloc_btree.h"
33 #include "xfs_dir2_sf.h"
34 #include "xfs_attr_sf.h"
35 #include "xfs_dinode.h"
36 #include "xfs_inode.h"
37 #include "xfs_btree.h"
38 #include "xfs_ialloc.h"
39 #include "xfs_alloc.h"
40 #include "xfs_rtalloc.h"
41 #include "xfs_error.h"
42 #include "xfs_bmap.h"
43
44
45 /*
46  * Allocation group level functions.
47  */
48 static inline int
49 xfs_ialloc_cluster_alignment(
50         xfs_alloc_arg_t *args)
51 {
52         if (xfs_sb_version_hasalign(&args->mp->m_sb) &&
53             args->mp->m_sb.sb_inoalignmt >=
54              XFS_B_TO_FSBT(args->mp, XFS_INODE_CLUSTER_SIZE(args->mp)))
55                 return args->mp->m_sb.sb_inoalignmt;
56         return 1;
57 }
58
59 /*
60  * Lookup the record equal to ino in the btree given by cur.
61  */
62 STATIC int                              /* error */
63 xfs_inobt_lookup_eq(
64         struct xfs_btree_cur    *cur,   /* btree cursor */
65         xfs_agino_t             ino,    /* starting inode of chunk */
66         __int32_t               fcnt,   /* free inode count */
67         xfs_inofree_t           free,   /* free inode mask */
68         int                     *stat)  /* success/failure */
69 {
70         cur->bc_rec.i.ir_startino = ino;
71         cur->bc_rec.i.ir_freecount = fcnt;
72         cur->bc_rec.i.ir_free = free;
73         return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
74 }
75
76 /*
77  * Lookup the first record greater than or equal to ino
78  * in the btree given by cur.
79  */
80 int                                     /* error */
81 xfs_inobt_lookup_ge(
82         struct xfs_btree_cur    *cur,   /* btree cursor */
83         xfs_agino_t             ino,    /* starting inode of chunk */
84         __int32_t               fcnt,   /* free inode count */
85         xfs_inofree_t           free,   /* free inode mask */
86         int                     *stat)  /* success/failure */
87 {
88         cur->bc_rec.i.ir_startino = ino;
89         cur->bc_rec.i.ir_freecount = fcnt;
90         cur->bc_rec.i.ir_free = free;
91         return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
92 }
93
94 /*
95  * Lookup the first record less than or equal to ino
96  * in the btree given by cur.
97  */
98 int                                     /* error */
99 xfs_inobt_lookup_le(
100         struct xfs_btree_cur    *cur,   /* btree cursor */
101         xfs_agino_t             ino,    /* starting inode of chunk */
102         __int32_t               fcnt,   /* free inode count */
103         xfs_inofree_t           free,   /* free inode mask */
104         int                     *stat)  /* success/failure */
105 {
106         cur->bc_rec.i.ir_startino = ino;
107         cur->bc_rec.i.ir_freecount = fcnt;
108         cur->bc_rec.i.ir_free = free;
109         return xfs_btree_lookup(cur, XFS_LOOKUP_LE, stat);
110 }
111
112 /*
113  * Update the record referred to by cur to the value given.
114  * This either works (return 0) or gets an EFSCORRUPTED error.
115  */
116 STATIC int                              /* error */
117 xfs_inobt_update(
118         struct xfs_btree_cur    *cur,   /* btree cursor */
119         xfs_inobt_rec_incore_t  *irec)  /* btree record */
120 {
121         union xfs_btree_rec     rec;
122
123         rec.inobt.ir_startino = cpu_to_be32(irec->ir_startino);
124         rec.inobt.ir_freecount = cpu_to_be32(irec->ir_freecount);
125         rec.inobt.ir_free = cpu_to_be64(irec->ir_free);
126         return xfs_btree_update(cur, &rec);
127 }
128
129 /*
130  * Get the data from the pointed-to record.
131  */
132 int                                     /* error */
133 xfs_inobt_get_rec(
134         struct xfs_btree_cur    *cur,   /* btree cursor */
135         xfs_inobt_rec_incore_t  *irec,  /* btree record */
136         int                     *stat)  /* output: success/failure */
137 {
138         union xfs_btree_rec     *rec;
139         int                     error;
140
141         error = xfs_btree_get_rec(cur, &rec, stat);
142         if (!error && *stat == 1) {
143                 irec->ir_startino = be32_to_cpu(rec->inobt.ir_startino);
144                 irec->ir_freecount = be32_to_cpu(rec->inobt.ir_freecount);
145                 irec->ir_free = be64_to_cpu(rec->inobt.ir_free);
146         }
147         return error;
148 }
149
150 /*
151  * Verify that the number of free inodes in the AGI is correct.
152  */
153 #ifdef DEBUG
154 STATIC int
155 xfs_check_agi_freecount(
156         struct xfs_btree_cur    *cur,
157         struct xfs_agi          *agi)
158 {
159         if (cur->bc_nlevels == 1) {
160                 xfs_inobt_rec_incore_t rec;
161                 int             freecount = 0;
162                 int             error;
163                 int             i;
164
165                 error = xfs_inobt_lookup_ge(cur, 0, 0, 0, &i);
166                 if (error)
167                         return error;
168
169                 do {
170                         error = xfs_inobt_get_rec(cur, &rec, &i);
171                         if (error)
172                                 return error;
173
174                         if (i) {
175                                 freecount += rec.ir_freecount;
176                                 error = xfs_btree_increment(cur, 0, &i);
177                                 if (error)
178                                         return error;
179                         }
180                 } while (i == 1);
181
182                 if (!XFS_FORCED_SHUTDOWN(cur->bc_mp))
183                         ASSERT(freecount == be32_to_cpu(agi->agi_freecount));
184         }
185         return 0;
186 }
187 #else
188 #define xfs_check_agi_freecount(cur, agi)       0
189 #endif
190
191 /*
192  * Initialise a new set of inodes.
193  */
194 STATIC void
195 xfs_ialloc_inode_init(
196         struct xfs_mount        *mp,
197         struct xfs_trans        *tp,
198         xfs_agnumber_t          agno,
199         xfs_agblock_t           agbno,
200         xfs_agblock_t           length,
201         unsigned int            gen)
202 {
203         struct xfs_buf          *fbuf;
204         struct xfs_dinode       *free;
205         int                     blks_per_cluster, nbufs, ninodes;
206         int                     version;
207         int                     i, j;
208         xfs_daddr_t             d;
209
210         /*
211          * Loop over the new block(s), filling in the inodes.
212          * For small block sizes, manipulate the inodes in buffers
213          * which are multiples of the blocks size.
214          */
215         if (mp->m_sb.sb_blocksize >= XFS_INODE_CLUSTER_SIZE(mp)) {
216                 blks_per_cluster = 1;
217                 nbufs = length;
218                 ninodes = mp->m_sb.sb_inopblock;
219         } else {
220                 blks_per_cluster = XFS_INODE_CLUSTER_SIZE(mp) /
221                                    mp->m_sb.sb_blocksize;
222                 nbufs = length / blks_per_cluster;
223                 ninodes = blks_per_cluster * mp->m_sb.sb_inopblock;
224         }
225
226         /*
227          * Figure out what version number to use in the inodes we create.
228          * If the superblock version has caught up to the one that supports
229          * the new inode format, then use the new inode version.  Otherwise
230          * use the old version so that old kernels will continue to be
231          * able to use the file system.
232          */
233         if (xfs_sb_version_hasnlink(&mp->m_sb))
234                 version = 2;
235         else
236                 version = 1;
237
238         for (j = 0; j < nbufs; j++) {
239                 /*
240                  * Get the block.
241                  */
242                 d = XFS_AGB_TO_DADDR(mp, agno, agbno + (j * blks_per_cluster));
243                 fbuf = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
244                                          mp->m_bsize * blks_per_cluster,
245                                          XFS_BUF_LOCK);
246                 ASSERT(fbuf);
247                 ASSERT(!XFS_BUF_GETERROR(fbuf));
248
249                 /*
250                  * Initialize all inodes in this buffer and then log them.
251                  *
252                  * XXX: It would be much better if we had just one transaction
253                  *      to log a whole cluster of inodes instead of all the
254                  *      individual transactions causing a lot of log traffic.
255                  */
256                 xfs_biozero(fbuf, 0, ninodes << mp->m_sb.sb_inodelog);
257                 for (i = 0; i < ninodes; i++) {
258                         int     ioffset = i << mp->m_sb.sb_inodelog;
259                         uint    isize = sizeof(struct xfs_dinode);
260
261                         free = xfs_make_iptr(mp, fbuf, i);
262                         free->di_magic = cpu_to_be16(XFS_DINODE_MAGIC);
263                         free->di_version = version;
264                         free->di_gen = cpu_to_be32(gen);
265                         free->di_next_unlinked = cpu_to_be32(NULLAGINO);
266                         xfs_trans_log_buf(tp, fbuf, ioffset, ioffset + isize - 1);
267                 }
268                 xfs_trans_inode_alloc_buf(tp, fbuf);
269         }
270 }
271
272 /*
273  * Allocate new inodes in the allocation group specified by agbp.
274  * Return 0 for success, else error code.
275  */
276 STATIC int                              /* error code or 0 */
277 xfs_ialloc_ag_alloc(
278         xfs_trans_t     *tp,            /* transaction pointer */
279         xfs_buf_t       *agbp,          /* alloc group buffer */
280         int             *alloc)
281 {
282         xfs_agi_t       *agi;           /* allocation group header */
283         xfs_alloc_arg_t args;           /* allocation argument structure */
284         xfs_btree_cur_t *cur;           /* inode btree cursor */
285         xfs_agnumber_t  agno;
286         int             error;
287         int             i;
288         xfs_agino_t     newino;         /* new first inode's number */
289         xfs_agino_t     newlen;         /* new number of inodes */
290         xfs_agino_t     thisino;        /* current inode number, for loop */
291         int             isaligned = 0;  /* inode allocation at stripe unit */
292                                         /* boundary */
293
294         args.tp = tp;
295         args.mp = tp->t_mountp;
296
297         /*
298          * Locking will ensure that we don't have two callers in here
299          * at one time.
300          */
301         newlen = XFS_IALLOC_INODES(args.mp);
302         if (args.mp->m_maxicount &&
303             args.mp->m_sb.sb_icount + newlen > args.mp->m_maxicount)
304                 return XFS_ERROR(ENOSPC);
305         args.minlen = args.maxlen = XFS_IALLOC_BLOCKS(args.mp);
306         /*
307          * First try to allocate inodes contiguous with the last-allocated
308          * chunk of inodes.  If the filesystem is striped, this will fill
309          * an entire stripe unit with inodes.
310          */
311         agi = XFS_BUF_TO_AGI(agbp);
312         newino = be32_to_cpu(agi->agi_newino);
313         agno = be32_to_cpu(agi->agi_seqno);
314         args.agbno = XFS_AGINO_TO_AGBNO(args.mp, newino) +
315                         XFS_IALLOC_BLOCKS(args.mp);
316         if (likely(newino != NULLAGINO &&
317                   (args.agbno < be32_to_cpu(agi->agi_length)))) {
318                 args.fsbno = XFS_AGB_TO_FSB(args.mp, agno, args.agbno);
319                 args.type = XFS_ALLOCTYPE_THIS_BNO;
320                 args.mod = args.total = args.wasdel = args.isfl =
321                         args.userdata = args.minalignslop = 0;
322                 args.prod = 1;
323
324                 /*
325                  * We need to take into account alignment here to ensure that
326                  * we don't modify the free list if we fail to have an exact
327                  * block. If we don't have an exact match, and every oher
328                  * attempt allocation attempt fails, we'll end up cancelling
329                  * a dirty transaction and shutting down.
330                  *
331                  * For an exact allocation, alignment must be 1,
332                  * however we need to take cluster alignment into account when
333                  * fixing up the freelist. Use the minalignslop field to
334                  * indicate that extra blocks might be required for alignment,
335                  * but not to use them in the actual exact allocation.
336                  */
337                 args.alignment = 1;
338                 args.minalignslop = xfs_ialloc_cluster_alignment(&args) - 1;
339
340                 /* Allow space for the inode btree to split. */
341                 args.minleft = args.mp->m_in_maxlevels - 1;
342                 if ((error = xfs_alloc_vextent(&args)))
343                         return error;
344         } else
345                 args.fsbno = NULLFSBLOCK;
346
347         if (unlikely(args.fsbno == NULLFSBLOCK)) {
348                 /*
349                  * Set the alignment for the allocation.
350                  * If stripe alignment is turned on then align at stripe unit
351                  * boundary.
352                  * If the cluster size is smaller than a filesystem block
353                  * then we're doing I/O for inodes in filesystem block size
354                  * pieces, so don't need alignment anyway.
355                  */
356                 isaligned = 0;
357                 if (args.mp->m_sinoalign) {
358                         ASSERT(!(args.mp->m_flags & XFS_MOUNT_NOALIGN));
359                         args.alignment = args.mp->m_dalign;
360                         isaligned = 1;
361                 } else
362                         args.alignment = xfs_ialloc_cluster_alignment(&args);
363                 /*
364                  * Need to figure out where to allocate the inode blocks.
365                  * Ideally they should be spaced out through the a.g.
366                  * For now, just allocate blocks up front.
367                  */
368                 args.agbno = be32_to_cpu(agi->agi_root);
369                 args.fsbno = XFS_AGB_TO_FSB(args.mp, agno, args.agbno);
370                 /*
371                  * Allocate a fixed-size extent of inodes.
372                  */
373                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
374                 args.mod = args.total = args.wasdel = args.isfl =
375                         args.userdata = args.minalignslop = 0;
376                 args.prod = 1;
377                 /*
378                  * Allow space for the inode btree to split.
379                  */
380                 args.minleft = args.mp->m_in_maxlevels - 1;
381                 if ((error = xfs_alloc_vextent(&args)))
382                         return error;
383         }
384
385         /*
386          * If stripe alignment is turned on, then try again with cluster
387          * alignment.
388          */
389         if (isaligned && args.fsbno == NULLFSBLOCK) {
390                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
391                 args.agbno = be32_to_cpu(agi->agi_root);
392                 args.fsbno = XFS_AGB_TO_FSB(args.mp, agno, args.agbno);
393                 args.alignment = xfs_ialloc_cluster_alignment(&args);
394                 if ((error = xfs_alloc_vextent(&args)))
395                         return error;
396         }
397
398         if (args.fsbno == NULLFSBLOCK) {
399                 *alloc = 0;
400                 return 0;
401         }
402         ASSERT(args.len == args.minlen);
403
404         /*
405          * Stamp and write the inode buffers.
406          *
407          * Seed the new inode cluster with a random generation number. This
408          * prevents short-term reuse of generation numbers if a chunk is
409          * freed and then immediately reallocated. We use random numbers
410          * rather than a linear progression to prevent the next generation
411          * number from being easily guessable.
412          */
413         xfs_ialloc_inode_init(args.mp, tp, agno, args.agbno, args.len,
414                               random32());
415
416         /*
417          * Convert the results.
418          */
419         newino = XFS_OFFBNO_TO_AGINO(args.mp, args.agbno, 0);
420         be32_add_cpu(&agi->agi_count, newlen);
421         be32_add_cpu(&agi->agi_freecount, newlen);
422         down_read(&args.mp->m_peraglock);
423         args.mp->m_perag[agno].pagi_freecount += newlen;
424         up_read(&args.mp->m_peraglock);
425         agi->agi_newino = cpu_to_be32(newino);
426
427         /*
428          * Insert records describing the new inode chunk into the btree.
429          */
430         cur = xfs_inobt_init_cursor(args.mp, tp, agbp, agno);
431         for (thisino = newino;
432              thisino < newino + newlen;
433              thisino += XFS_INODES_PER_CHUNK) {
434                 if ((error = xfs_inobt_lookup_eq(cur, thisino,
435                                 XFS_INODES_PER_CHUNK, XFS_INOBT_ALL_FREE, &i))) {
436                         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
437                         return error;
438                 }
439                 ASSERT(i == 0);
440                 if ((error = xfs_btree_insert(cur, &i))) {
441                         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
442                         return error;
443                 }
444                 ASSERT(i == 1);
445         }
446         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
447         /*
448          * Log allocation group header fields
449          */
450         xfs_ialloc_log_agi(tp, agbp,
451                 XFS_AGI_COUNT | XFS_AGI_FREECOUNT | XFS_AGI_NEWINO);
452         /*
453          * Modify/log superblock values for inode count and inode free count.
454          */
455         xfs_trans_mod_sb(tp, XFS_TRANS_SB_ICOUNT, (long)newlen);
456         xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, (long)newlen);
457         *alloc = 1;
458         return 0;
459 }
460
461 STATIC_INLINE xfs_agnumber_t
462 xfs_ialloc_next_ag(
463         xfs_mount_t     *mp)
464 {
465         xfs_agnumber_t  agno;
466
467         spin_lock(&mp->m_agirotor_lock);
468         agno = mp->m_agirotor;
469         if (++mp->m_agirotor == mp->m_maxagi)
470                 mp->m_agirotor = 0;
471         spin_unlock(&mp->m_agirotor_lock);
472
473         return agno;
474 }
475
476 /*
477  * Select an allocation group to look for a free inode in, based on the parent
478  * inode and then mode.  Return the allocation group buffer.
479  */
480 STATIC xfs_buf_t *                      /* allocation group buffer */
481 xfs_ialloc_ag_select(
482         xfs_trans_t     *tp,            /* transaction pointer */
483         xfs_ino_t       parent,         /* parent directory inode number */
484         mode_t          mode,           /* bits set to indicate file type */
485         int             okalloc)        /* ok to allocate more space */
486 {
487         xfs_buf_t       *agbp;          /* allocation group header buffer */
488         xfs_agnumber_t  agcount;        /* number of ag's in the filesystem */
489         xfs_agnumber_t  agno;           /* current ag number */
490         int             flags;          /* alloc buffer locking flags */
491         xfs_extlen_t    ineed;          /* blocks needed for inode allocation */
492         xfs_extlen_t    longest = 0;    /* longest extent available */
493         xfs_mount_t     *mp;            /* mount point structure */
494         int             needspace;      /* file mode implies space allocated */
495         xfs_perag_t     *pag;           /* per allocation group data */
496         xfs_agnumber_t  pagno;          /* parent (starting) ag number */
497
498         /*
499          * Files of these types need at least one block if length > 0
500          * (and they won't fit in the inode, but that's hard to figure out).
501          */
502         needspace = S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode);
503         mp = tp->t_mountp;
504         agcount = mp->m_maxagi;
505         if (S_ISDIR(mode))
506                 pagno = xfs_ialloc_next_ag(mp);
507         else {
508                 pagno = XFS_INO_TO_AGNO(mp, parent);
509                 if (pagno >= agcount)
510                         pagno = 0;
511         }
512         ASSERT(pagno < agcount);
513         /*
514          * Loop through allocation groups, looking for one with a little
515          * free space in it.  Note we don't look for free inodes, exactly.
516          * Instead, we include whether there is a need to allocate inodes
517          * to mean that blocks must be allocated for them,
518          * if none are currently free.
519          */
520         agno = pagno;
521         flags = XFS_ALLOC_FLAG_TRYLOCK;
522         down_read(&mp->m_peraglock);
523         for (;;) {
524                 pag = &mp->m_perag[agno];
525                 if (!pag->pagi_init) {
526                         if (xfs_ialloc_read_agi(mp, tp, agno, &agbp)) {
527                                 agbp = NULL;
528                                 goto nextag;
529                         }
530                 } else
531                         agbp = NULL;
532
533                 if (!pag->pagi_inodeok) {
534                         xfs_ialloc_next_ag(mp);
535                         goto unlock_nextag;
536                 }
537
538                 /*
539                  * Is there enough free space for the file plus a block
540                  * of inodes (if we need to allocate some)?
541                  */
542                 ineed = pag->pagi_freecount ? 0 : XFS_IALLOC_BLOCKS(mp);
543                 if (ineed && !pag->pagf_init) {
544                         if (agbp == NULL &&
545                             xfs_ialloc_read_agi(mp, tp, agno, &agbp)) {
546                                 agbp = NULL;
547                                 goto nextag;
548                         }
549                         (void)xfs_alloc_pagf_init(mp, tp, agno, flags);
550                 }
551                 if (!ineed || pag->pagf_init) {
552                         if (ineed && !(longest = pag->pagf_longest))
553                                 longest = pag->pagf_flcount > 0;
554                         if (!ineed ||
555                             (pag->pagf_freeblks >= needspace + ineed &&
556                              longest >= ineed &&
557                              okalloc)) {
558                                 if (agbp == NULL &&
559                                     xfs_ialloc_read_agi(mp, tp, agno, &agbp)) {
560                                         agbp = NULL;
561                                         goto nextag;
562                                 }
563                                 up_read(&mp->m_peraglock);
564                                 return agbp;
565                         }
566                 }
567 unlock_nextag:
568                 if (agbp)
569                         xfs_trans_brelse(tp, agbp);
570 nextag:
571                 /*
572                  * No point in iterating over the rest, if we're shutting
573                  * down.
574                  */
575                 if (XFS_FORCED_SHUTDOWN(mp)) {
576                         up_read(&mp->m_peraglock);
577                         return NULL;
578                 }
579                 agno++;
580                 if (agno >= agcount)
581                         agno = 0;
582                 if (agno == pagno) {
583                         if (flags == 0) {
584                                 up_read(&mp->m_peraglock);
585                                 return NULL;
586                         }
587                         flags = 0;
588                 }
589         }
590 }
591
592
593 /*
594  * Visible inode allocation functions.
595  */
596
597 /*
598  * Allocate an inode on disk.
599  * Mode is used to tell whether the new inode will need space, and whether
600  * it is a directory.
601  *
602  * The arguments IO_agbp and alloc_done are defined to work within
603  * the constraint of one allocation per transaction.
604  * xfs_dialloc() is designed to be called twice if it has to do an
605  * allocation to make more free inodes.  On the first call,
606  * IO_agbp should be set to NULL. If an inode is available,
607  * i.e., xfs_dialloc() did not need to do an allocation, an inode
608  * number is returned.  In this case, IO_agbp would be set to the
609  * current ag_buf and alloc_done set to false.
610  * If an allocation needed to be done, xfs_dialloc would return
611  * the current ag_buf in IO_agbp and set alloc_done to true.
612  * The caller should then commit the current transaction, allocate a new
613  * transaction, and call xfs_dialloc() again, passing in the previous
614  * value of IO_agbp.  IO_agbp should be held across the transactions.
615  * Since the agbp is locked across the two calls, the second call is
616  * guaranteed to have a free inode available.
617  *
618  * Once we successfully pick an inode its number is returned and the
619  * on-disk data structures are updated.  The inode itself is not read
620  * in, since doing so would break ordering constraints with xfs_reclaim.
621  */
622 int
623 xfs_dialloc(
624         xfs_trans_t     *tp,            /* transaction pointer */
625         xfs_ino_t       parent,         /* parent inode (directory) */
626         mode_t          mode,           /* mode bits for new inode */
627         int             okalloc,        /* ok to allocate more space */
628         xfs_buf_t       **IO_agbp,      /* in/out ag header's buffer */
629         boolean_t       *alloc_done,    /* true if we needed to replenish
630                                            inode freelist */
631         xfs_ino_t       *inop)          /* inode number allocated */
632 {
633         xfs_agnumber_t  agcount;        /* number of allocation groups */
634         xfs_buf_t       *agbp;          /* allocation group header's buffer */
635         xfs_agnumber_t  agno;           /* allocation group number */
636         xfs_agi_t       *agi;           /* allocation group header structure */
637         xfs_btree_cur_t *cur;           /* inode allocation btree cursor */
638         int             error;          /* error return value */
639         int             i;              /* result code */
640         int             ialloced;       /* inode allocation status */
641         int             noroom = 0;     /* no space for inode blk allocation */
642         xfs_ino_t       ino;            /* fs-relative inode to be returned */
643         /* REFERENCED */
644         int             j;              /* result code */
645         xfs_mount_t     *mp;            /* file system mount structure */
646         int             offset;         /* index of inode in chunk */
647         xfs_agino_t     pagino;         /* parent's a.g. relative inode # */
648         xfs_agnumber_t  pagno;          /* parent's allocation group number */
649         xfs_inobt_rec_incore_t rec;     /* inode allocation record */
650         xfs_agnumber_t  tagno;          /* testing allocation group number */
651         xfs_btree_cur_t *tcur;          /* temp cursor */
652         xfs_inobt_rec_incore_t trec;    /* temp inode allocation record */
653
654
655         if (*IO_agbp == NULL) {
656                 /*
657                  * We do not have an agbp, so select an initial allocation
658                  * group for inode allocation.
659                  */
660                 agbp = xfs_ialloc_ag_select(tp, parent, mode, okalloc);
661                 /*
662                  * Couldn't find an allocation group satisfying the
663                  * criteria, give up.
664                  */
665                 if (!agbp) {
666                         *inop = NULLFSINO;
667                         return 0;
668                 }
669                 agi = XFS_BUF_TO_AGI(agbp);
670                 ASSERT(be32_to_cpu(agi->agi_magicnum) == XFS_AGI_MAGIC);
671         } else {
672                 /*
673                  * Continue where we left off before.  In this case, we
674                  * know that the allocation group has free inodes.
675                  */
676                 agbp = *IO_agbp;
677                 agi = XFS_BUF_TO_AGI(agbp);
678                 ASSERT(be32_to_cpu(agi->agi_magicnum) == XFS_AGI_MAGIC);
679                 ASSERT(be32_to_cpu(agi->agi_freecount) > 0);
680         }
681         mp = tp->t_mountp;
682         agcount = mp->m_sb.sb_agcount;
683         agno = be32_to_cpu(agi->agi_seqno);
684         tagno = agno;
685         pagno = XFS_INO_TO_AGNO(mp, parent);
686         pagino = XFS_INO_TO_AGINO(mp, parent);
687
688         /*
689          * If we have already hit the ceiling of inode blocks then clear
690          * okalloc so we scan all available agi structures for a free
691          * inode.
692          */
693
694         if (mp->m_maxicount &&
695             mp->m_sb.sb_icount + XFS_IALLOC_INODES(mp) > mp->m_maxicount) {
696                 noroom = 1;
697                 okalloc = 0;
698         }
699
700         /*
701          * Loop until we find an allocation group that either has free inodes
702          * or in which we can allocate some inodes.  Iterate through the
703          * allocation groups upward, wrapping at the end.
704          */
705         *alloc_done = B_FALSE;
706         while (!agi->agi_freecount) {
707                 /*
708                  * Don't do anything if we're not supposed to allocate
709                  * any blocks, just go on to the next ag.
710                  */
711                 if (okalloc) {
712                         /*
713                          * Try to allocate some new inodes in the allocation
714                          * group.
715                          */
716                         if ((error = xfs_ialloc_ag_alloc(tp, agbp, &ialloced))) {
717                                 xfs_trans_brelse(tp, agbp);
718                                 if (error == ENOSPC) {
719                                         *inop = NULLFSINO;
720                                         return 0;
721                                 } else
722                                         return error;
723                         }
724                         if (ialloced) {
725                                 /*
726                                  * We successfully allocated some inodes, return
727                                  * the current context to the caller so that it
728                                  * can commit the current transaction and call
729                                  * us again where we left off.
730                                  */
731                                 ASSERT(be32_to_cpu(agi->agi_freecount) > 0);
732                                 *alloc_done = B_TRUE;
733                                 *IO_agbp = agbp;
734                                 *inop = NULLFSINO;
735                                 return 0;
736                         }
737                 }
738                 /*
739                  * If it failed, give up on this ag.
740                  */
741                 xfs_trans_brelse(tp, agbp);
742                 /*
743                  * Go on to the next ag: get its ag header.
744                  */
745 nextag:
746                 if (++tagno == agcount)
747                         tagno = 0;
748                 if (tagno == agno) {
749                         *inop = NULLFSINO;
750                         return noroom ? ENOSPC : 0;
751                 }
752                 down_read(&mp->m_peraglock);
753                 if (mp->m_perag[tagno].pagi_inodeok == 0) {
754                         up_read(&mp->m_peraglock);
755                         goto nextag;
756                 }
757                 error = xfs_ialloc_read_agi(mp, tp, tagno, &agbp);
758                 up_read(&mp->m_peraglock);
759                 if (error)
760                         goto nextag;
761                 agi = XFS_BUF_TO_AGI(agbp);
762                 ASSERT(be32_to_cpu(agi->agi_magicnum) == XFS_AGI_MAGIC);
763         }
764         /*
765          * Here with an allocation group that has a free inode.
766          * Reset agno since we may have chosen a new ag in the
767          * loop above.
768          */
769         agno = tagno;
770         *IO_agbp = NULL;
771         cur = xfs_inobt_init_cursor(mp, tp, agbp, be32_to_cpu(agi->agi_seqno));
772         /*
773          * If pagino is 0 (this is the root inode allocation) use newino.
774          * This must work because we've just allocated some.
775          */
776         if (!pagino)
777                 pagino = be32_to_cpu(agi->agi_newino);
778
779         error = xfs_check_agi_freecount(cur, agi);
780         if (error)
781                 goto error0;
782
783         /*
784          * If in the same a.g. as the parent, try to get near the parent.
785          */
786         if (pagno == agno) {
787                 if ((error = xfs_inobt_lookup_le(cur, pagino, 0, 0, &i)))
788                         goto error0;
789                 if (i != 0 &&
790                     (error = xfs_inobt_get_rec(cur, &rec, &j)) == 0 &&
791                     j == 1 &&
792                     rec.ir_freecount > 0) {
793                         /*
794                          * Found a free inode in the same chunk
795                          * as parent, done.
796                          */
797                 }
798                 /*
799                  * In the same a.g. as parent, but parent's chunk is full.
800                  */
801                 else {
802                         int     doneleft;       /* done, to the left */
803                         int     doneright;      /* done, to the right */
804
805                         if (error)
806                                 goto error0;
807                         ASSERT(i == 1);
808                         ASSERT(j == 1);
809                         /*
810                          * Duplicate the cursor, search left & right
811                          * simultaneously.
812                          */
813                         if ((error = xfs_btree_dup_cursor(cur, &tcur)))
814                                 goto error0;
815                         /*
816                          * Search left with tcur, back up 1 record.
817                          */
818                         if ((error = xfs_btree_decrement(tcur, 0, &i)))
819                                 goto error1;
820                         doneleft = !i;
821                         if (!doneleft) {
822                                 error = xfs_inobt_get_rec(tcur, &trec, &i);
823                                 if (error)
824                                         goto error1;
825                                 XFS_WANT_CORRUPTED_GOTO(i == 1, error1);
826                         }
827                         /*
828                          * Search right with cur, go forward 1 record.
829                          */
830                         if ((error = xfs_btree_increment(cur, 0, &i)))
831                                 goto error1;
832                         doneright = !i;
833                         if (!doneright) {
834                                 error = xfs_inobt_get_rec(cur, &rec, &i);
835                                 if (error)
836                                         goto error1;
837                                 XFS_WANT_CORRUPTED_GOTO(i == 1, error1);
838                         }
839                         /*
840                          * Loop until we find the closest inode chunk
841                          * with a free one.
842                          */
843                         while (!doneleft || !doneright) {
844                                 int     useleft;  /* using left inode
845                                                      chunk this time */
846
847                                 /*
848                                  * Figure out which block is closer,
849                                  * if both are valid.
850                                  */
851                                 if (!doneleft && !doneright)
852                                         useleft =
853                                                 pagino -
854                                                 (trec.ir_startino +
855                                                  XFS_INODES_PER_CHUNK - 1) <
856                                                  rec.ir_startino - pagino;
857                                 else
858                                         useleft = !doneleft;
859                                 /*
860                                  * If checking the left, does it have
861                                  * free inodes?
862                                  */
863                                 if (useleft && trec.ir_freecount) {
864                                         /*
865                                          * Yes, set it up as the chunk to use.
866                                          */
867                                         rec = trec;
868                                         xfs_btree_del_cursor(cur,
869                                                 XFS_BTREE_NOERROR);
870                                         cur = tcur;
871                                         break;
872                                 }
873                                 /*
874                                  * If checking the right, does it have
875                                  * free inodes?
876                                  */
877                                 if (!useleft && rec.ir_freecount) {
878                                         /*
879                                          * Yes, it's already set up.
880                                          */
881                                         xfs_btree_del_cursor(tcur,
882                                                 XFS_BTREE_NOERROR);
883                                         break;
884                                 }
885                                 /*
886                                  * If used the left, get another one
887                                  * further left.
888                                  */
889                                 if (useleft) {
890                                         if ((error = xfs_btree_decrement(tcur, 0,
891                                                         &i)))
892                                                 goto error1;
893                                         doneleft = !i;
894                                         if (!doneleft) {
895                                                 error = xfs_inobt_get_rec(
896                                                             tcur, &trec, &i);
897                                                 if (error)
898                                                         goto error1;
899                                                 XFS_WANT_CORRUPTED_GOTO(i == 1,
900                                                         error1);
901                                         }
902                                 }
903                                 /*
904                                  * If used the right, get another one
905                                  * further right.
906                                  */
907                                 else {
908                                         if ((error = xfs_btree_increment(cur, 0,
909                                                         &i)))
910                                                 goto error1;
911                                         doneright = !i;
912                                         if (!doneright) {
913                                                 error = xfs_inobt_get_rec(
914                                                             cur, &rec, &i);
915                                                 if (error)
916                                                         goto error1;
917                                                 XFS_WANT_CORRUPTED_GOTO(i == 1,
918                                                         error1);
919                                         }
920                                 }
921                         }
922                         ASSERT(!doneleft || !doneright);
923                 }
924         }
925         /*
926          * In a different a.g. from the parent.
927          * See if the most recently allocated block has any free.
928          */
929         else if (be32_to_cpu(agi->agi_newino) != NULLAGINO) {
930                 if ((error = xfs_inobt_lookup_eq(cur,
931                                 be32_to_cpu(agi->agi_newino), 0, 0, &i)))
932                         goto error0;
933                 if (i == 1 &&
934                     (error = xfs_inobt_get_rec(cur, &rec, &j)) == 0 &&
935                     j == 1 &&
936                     rec.ir_freecount > 0) {
937                         /*
938                          * The last chunk allocated in the group still has
939                          * a free inode.
940                          */
941                 }
942                 /*
943                  * None left in the last group, search the whole a.g.
944                  */
945                 else {
946                         if (error)
947                                 goto error0;
948                         if ((error = xfs_inobt_lookup_ge(cur, 0, 0, 0, &i)))
949                                 goto error0;
950                         ASSERT(i == 1);
951                         for (;;) {
952                                 error = xfs_inobt_get_rec(cur, &rec, &i);
953                                 if (error)
954                                         goto error0;
955                                 XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
956                                 if (rec.ir_freecount > 0)
957                                         break;
958                                 if ((error = xfs_btree_increment(cur, 0, &i)))
959                                         goto error0;
960                                 XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
961                         }
962                 }
963         }
964         offset = xfs_ialloc_find_free(&rec.ir_free);
965         ASSERT(offset >= 0);
966         ASSERT(offset < XFS_INODES_PER_CHUNK);
967         ASSERT((XFS_AGINO_TO_OFFSET(mp, rec.ir_startino) %
968                                    XFS_INODES_PER_CHUNK) == 0);
969         ino = XFS_AGINO_TO_INO(mp, agno, rec.ir_startino + offset);
970         rec.ir_free &= ~XFS_INOBT_MASK(offset);
971         rec.ir_freecount--;
972         error = xfs_inobt_update(cur, &rec);
973         if (error)
974                 goto error0;
975         be32_add_cpu(&agi->agi_freecount, -1);
976         xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
977         down_read(&mp->m_peraglock);
978         mp->m_perag[tagno].pagi_freecount--;
979         up_read(&mp->m_peraglock);
980
981         error = xfs_check_agi_freecount(cur, agi);
982         if (error)
983                 goto error0;
984
985         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
986         xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -1);
987         *inop = ino;
988         return 0;
989 error1:
990         xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
991 error0:
992         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
993         return error;
994 }
995
996 /*
997  * Free disk inode.  Carefully avoids touching the incore inode, all
998  * manipulations incore are the caller's responsibility.
999  * The on-disk inode is not changed by this operation, only the
1000  * btree (free inode mask) is changed.
1001  */
1002 int
1003 xfs_difree(
1004         xfs_trans_t     *tp,            /* transaction pointer */
1005         xfs_ino_t       inode,          /* inode to be freed */
1006         xfs_bmap_free_t *flist,         /* extents to free */
1007         int             *delete,        /* set if inode cluster was deleted */
1008         xfs_ino_t       *first_ino)     /* first inode in deleted cluster */
1009 {
1010         /* REFERENCED */
1011         xfs_agblock_t   agbno;  /* block number containing inode */
1012         xfs_buf_t       *agbp;  /* buffer containing allocation group header */
1013         xfs_agino_t     agino;  /* inode number relative to allocation group */
1014         xfs_agnumber_t  agno;   /* allocation group number */
1015         xfs_agi_t       *agi;   /* allocation group header */
1016         xfs_btree_cur_t *cur;   /* inode btree cursor */
1017         int             error;  /* error return value */
1018         int             i;      /* result code */
1019         int             ilen;   /* inodes in an inode cluster */
1020         xfs_mount_t     *mp;    /* mount structure for filesystem */
1021         int             off;    /* offset of inode in inode chunk */
1022         xfs_inobt_rec_incore_t rec;     /* btree record */
1023
1024         mp = tp->t_mountp;
1025
1026         /*
1027          * Break up inode number into its components.
1028          */
1029         agno = XFS_INO_TO_AGNO(mp, inode);
1030         if (agno >= mp->m_sb.sb_agcount)  {
1031                 cmn_err(CE_WARN,
1032                         "xfs_difree: agno >= mp->m_sb.sb_agcount (%d >= %d) on %s.  Returning EINVAL.",
1033                         agno, mp->m_sb.sb_agcount, mp->m_fsname);
1034                 ASSERT(0);
1035                 return XFS_ERROR(EINVAL);
1036         }
1037         agino = XFS_INO_TO_AGINO(mp, inode);
1038         if (inode != XFS_AGINO_TO_INO(mp, agno, agino))  {
1039                 cmn_err(CE_WARN,
1040                         "xfs_difree: inode != XFS_AGINO_TO_INO() "
1041                         "(%llu != %llu) on %s.  Returning EINVAL.",
1042                         (unsigned long long)inode,
1043                         (unsigned long long)XFS_AGINO_TO_INO(mp, agno, agino),
1044                         mp->m_fsname);
1045                 ASSERT(0);
1046                 return XFS_ERROR(EINVAL);
1047         }
1048         agbno = XFS_AGINO_TO_AGBNO(mp, agino);
1049         if (agbno >= mp->m_sb.sb_agblocks)  {
1050                 cmn_err(CE_WARN,
1051                         "xfs_difree: agbno >= mp->m_sb.sb_agblocks (%d >= %d) on %s.  Returning EINVAL.",
1052                         agbno, mp->m_sb.sb_agblocks, mp->m_fsname);
1053                 ASSERT(0);
1054                 return XFS_ERROR(EINVAL);
1055         }
1056         /*
1057          * Get the allocation group header.
1058          */
1059         down_read(&mp->m_peraglock);
1060         error = xfs_ialloc_read_agi(mp, tp, agno, &agbp);
1061         up_read(&mp->m_peraglock);
1062         if (error) {
1063                 cmn_err(CE_WARN,
1064                         "xfs_difree: xfs_ialloc_read_agi() returned an error %d on %s.  Returning error.",
1065                         error, mp->m_fsname);
1066                 return error;
1067         }
1068         agi = XFS_BUF_TO_AGI(agbp);
1069         ASSERT(be32_to_cpu(agi->agi_magicnum) == XFS_AGI_MAGIC);
1070         ASSERT(agbno < be32_to_cpu(agi->agi_length));
1071         /*
1072          * Initialize the cursor.
1073          */
1074         cur = xfs_inobt_init_cursor(mp, tp, agbp, agno);
1075
1076         error = xfs_check_agi_freecount(cur, agi);
1077         if (error)
1078                 goto error0;
1079
1080         /*
1081          * Look for the entry describing this inode.
1082          */
1083         if ((error = xfs_inobt_lookup_le(cur, agino, 0, 0, &i))) {
1084                 cmn_err(CE_WARN,
1085                         "xfs_difree: xfs_inobt_lookup_le returned()  an error %d on %s.  Returning error.",
1086                         error, mp->m_fsname);
1087                 goto error0;
1088         }
1089         XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
1090         error = xfs_inobt_get_rec(cur, &rec, &i);
1091         if (error) {
1092                 cmn_err(CE_WARN,
1093                         "xfs_difree: xfs_inobt_get_rec()  returned an error %d on %s.  Returning error.",
1094                         error, mp->m_fsname);
1095                 goto error0;
1096         }
1097         XFS_WANT_CORRUPTED_GOTO(i == 1, error0);
1098         /*
1099          * Get the offset in the inode chunk.
1100          */
1101         off = agino - rec.ir_startino;
1102         ASSERT(off >= 0 && off < XFS_INODES_PER_CHUNK);
1103         ASSERT(!(rec.ir_free & XFS_INOBT_MASK(off)));
1104         /*
1105          * Mark the inode free & increment the count.
1106          */
1107         rec.ir_free |= XFS_INOBT_MASK(off);
1108         rec.ir_freecount++;
1109
1110         /*
1111          * When an inode cluster is free, it becomes eligible for removal
1112          */
1113         if (!(mp->m_flags & XFS_MOUNT_IKEEP) &&
1114             (rec.ir_freecount == XFS_IALLOC_INODES(mp))) {
1115
1116                 *delete = 1;
1117                 *first_ino = XFS_AGINO_TO_INO(mp, agno, rec.ir_startino);
1118
1119                 /*
1120                  * Remove the inode cluster from the AGI B+Tree, adjust the
1121                  * AGI and Superblock inode counts, and mark the disk space
1122                  * to be freed when the transaction is committed.
1123                  */
1124                 ilen = XFS_IALLOC_INODES(mp);
1125                 be32_add_cpu(&agi->agi_count, -ilen);
1126                 be32_add_cpu(&agi->agi_freecount, -(ilen - 1));
1127                 xfs_ialloc_log_agi(tp, agbp, XFS_AGI_COUNT | XFS_AGI_FREECOUNT);
1128                 down_read(&mp->m_peraglock);
1129                 mp->m_perag[agno].pagi_freecount -= ilen - 1;
1130                 up_read(&mp->m_peraglock);
1131                 xfs_trans_mod_sb(tp, XFS_TRANS_SB_ICOUNT, -ilen);
1132                 xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, -(ilen - 1));
1133
1134                 if ((error = xfs_btree_delete(cur, &i))) {
1135                         cmn_err(CE_WARN, "xfs_difree: xfs_btree_delete returned an error %d on %s.\n",
1136                                 error, mp->m_fsname);
1137                         goto error0;
1138                 }
1139
1140                 xfs_bmap_add_free(XFS_AGB_TO_FSB(mp,
1141                                 agno, XFS_INO_TO_AGBNO(mp,rec.ir_startino)),
1142                                 XFS_IALLOC_BLOCKS(mp), flist, mp);
1143         } else {
1144                 *delete = 0;
1145
1146                 error = xfs_inobt_update(cur, &rec);
1147                 if (error) {
1148                         cmn_err(CE_WARN,
1149         "xfs_difree: xfs_inobt_update returned an error %d on %s.",
1150                                 error, mp->m_fsname);
1151                         goto error0;
1152                 }
1153
1154                 /* 
1155                  * Change the inode free counts and log the ag/sb changes.
1156                  */
1157                 be32_add_cpu(&agi->agi_freecount, 1);
1158                 xfs_ialloc_log_agi(tp, agbp, XFS_AGI_FREECOUNT);
1159                 down_read(&mp->m_peraglock);
1160                 mp->m_perag[agno].pagi_freecount++;
1161                 up_read(&mp->m_peraglock);
1162                 xfs_trans_mod_sb(tp, XFS_TRANS_SB_IFREE, 1);
1163         }
1164
1165         error = xfs_check_agi_freecount(cur, agi);
1166         if (error)
1167                 goto error0;
1168
1169         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1170         return 0;
1171
1172 error0:
1173         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1174         return error;
1175 }
1176
1177 /*
1178  * Return the location of the inode in imap, for mapping it into a buffer.
1179  */
1180 int
1181 xfs_imap(
1182         xfs_mount_t      *mp,   /* file system mount structure */
1183         xfs_trans_t      *tp,   /* transaction pointer */
1184         xfs_ino_t       ino,    /* inode to locate */
1185         struct xfs_imap *imap,  /* location map structure */
1186         uint            flags)  /* flags for inode btree lookup */
1187 {
1188         xfs_agblock_t   agbno;  /* block number of inode in the alloc group */
1189         xfs_agino_t     agino;  /* inode number within alloc group */
1190         xfs_agnumber_t  agno;   /* allocation group number */
1191         int             blks_per_cluster; /* num blocks per inode cluster */
1192         xfs_agblock_t   chunk_agbno;    /* first block in inode chunk */
1193         xfs_agblock_t   cluster_agbno;  /* first block in inode cluster */
1194         int             error;  /* error code */
1195         int             offset; /* index of inode in its buffer */
1196         int             offset_agbno;   /* blks from chunk start to inode */
1197
1198         ASSERT(ino != NULLFSINO);
1199
1200         /*
1201          * Split up the inode number into its parts.
1202          */
1203         agno = XFS_INO_TO_AGNO(mp, ino);
1204         agino = XFS_INO_TO_AGINO(mp, ino);
1205         agbno = XFS_AGINO_TO_AGBNO(mp, agino);
1206         if (agno >= mp->m_sb.sb_agcount || agbno >= mp->m_sb.sb_agblocks ||
1207             ino != XFS_AGINO_TO_INO(mp, agno, agino)) {
1208 #ifdef DEBUG
1209                 /* no diagnostics for bulkstat, ino comes from userspace */
1210                 if (flags & XFS_IGET_BULKSTAT)
1211                         return XFS_ERROR(EINVAL);
1212                 if (agno >= mp->m_sb.sb_agcount) {
1213                         xfs_fs_cmn_err(CE_ALERT, mp,
1214                                         "xfs_imap: agno (%d) >= "
1215                                         "mp->m_sb.sb_agcount (%d)",
1216                                         agno,  mp->m_sb.sb_agcount);
1217                 }
1218                 if (agbno >= mp->m_sb.sb_agblocks) {
1219                         xfs_fs_cmn_err(CE_ALERT, mp,
1220                                         "xfs_imap: agbno (0x%llx) >= "
1221                                         "mp->m_sb.sb_agblocks (0x%lx)",
1222                                         (unsigned long long) agbno,
1223                                         (unsigned long) mp->m_sb.sb_agblocks);
1224                 }
1225                 if (ino != XFS_AGINO_TO_INO(mp, agno, agino)) {
1226                         xfs_fs_cmn_err(CE_ALERT, mp,
1227                                         "xfs_imap: ino (0x%llx) != "
1228                                         "XFS_AGINO_TO_INO(mp, agno, agino) "
1229                                         "(0x%llx)",
1230                                         ino, XFS_AGINO_TO_INO(mp, agno, agino));
1231                 }
1232                 xfs_stack_trace();
1233 #endif /* DEBUG */
1234                 return XFS_ERROR(EINVAL);
1235         }
1236
1237         /*
1238          * If the inode cluster size is the same as the blocksize or
1239          * smaller we get to the buffer by simple arithmetics.
1240          */
1241         if (XFS_INODE_CLUSTER_SIZE(mp) <= mp->m_sb.sb_blocksize) {
1242                 offset = XFS_INO_TO_OFFSET(mp, ino);
1243                 ASSERT(offset < mp->m_sb.sb_inopblock);
1244
1245                 imap->im_blkno = XFS_AGB_TO_DADDR(mp, agno, agbno);
1246                 imap->im_len = XFS_FSB_TO_BB(mp, 1);
1247                 imap->im_boffset = (ushort)(offset << mp->m_sb.sb_inodelog);
1248                 return 0;
1249         }
1250
1251         blks_per_cluster = XFS_INODE_CLUSTER_SIZE(mp) >> mp->m_sb.sb_blocklog;
1252
1253         /*
1254          * If we get a block number passed from bulkstat we can use it to
1255          * find the buffer easily.
1256          */
1257         if (imap->im_blkno) {
1258                 offset = XFS_INO_TO_OFFSET(mp, ino);
1259                 ASSERT(offset < mp->m_sb.sb_inopblock);
1260
1261                 cluster_agbno = xfs_daddr_to_agbno(mp, imap->im_blkno);
1262                 offset += (agbno - cluster_agbno) * mp->m_sb.sb_inopblock;
1263
1264                 imap->im_len = XFS_FSB_TO_BB(mp, blks_per_cluster);
1265                 imap->im_boffset = (ushort)(offset << mp->m_sb.sb_inodelog);
1266                 return 0;
1267         }
1268
1269         /*
1270          * If the inode chunks are aligned then use simple maths to
1271          * find the location. Otherwise we have to do a btree
1272          * lookup to find the location.
1273          */
1274         if (mp->m_inoalign_mask) {
1275                 offset_agbno = agbno & mp->m_inoalign_mask;
1276                 chunk_agbno = agbno - offset_agbno;
1277         } else {
1278                 xfs_btree_cur_t *cur;   /* inode btree cursor */
1279                 xfs_inobt_rec_incore_t chunk_rec;
1280                 xfs_buf_t       *agbp;  /* agi buffer */
1281                 int             i;      /* temp state */
1282
1283                 down_read(&mp->m_peraglock);
1284                 error = xfs_ialloc_read_agi(mp, tp, agno, &agbp);
1285                 up_read(&mp->m_peraglock);
1286                 if (error) {
1287                         xfs_fs_cmn_err(CE_ALERT, mp, "xfs_imap: "
1288                                         "xfs_ialloc_read_agi() returned "
1289                                         "error %d, agno %d",
1290                                         error, agno);
1291                         return error;
1292                 }
1293
1294                 cur = xfs_inobt_init_cursor(mp, tp, agbp, agno);
1295                 error = xfs_inobt_lookup_le(cur, agino, 0, 0, &i);
1296                 if (error) {
1297                         xfs_fs_cmn_err(CE_ALERT, mp, "xfs_imap: "
1298                                         "xfs_inobt_lookup_le() failed");
1299                         goto error0;
1300                 }
1301
1302                 error = xfs_inobt_get_rec(cur, &chunk_rec, &i);
1303                 if (error) {
1304                         xfs_fs_cmn_err(CE_ALERT, mp, "xfs_imap: "
1305                                         "xfs_inobt_get_rec() failed");
1306                         goto error0;
1307                 }
1308                 if (i == 0) {
1309 #ifdef DEBUG
1310                         xfs_fs_cmn_err(CE_ALERT, mp, "xfs_imap: "
1311                                         "xfs_inobt_get_rec() failed");
1312 #endif /* DEBUG */
1313                         error = XFS_ERROR(EINVAL);
1314                 }
1315  error0:
1316                 xfs_trans_brelse(tp, agbp);
1317                 xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
1318                 if (error)
1319                         return error;
1320                 chunk_agbno = XFS_AGINO_TO_AGBNO(mp, chunk_rec.ir_startino);
1321                 offset_agbno = agbno - chunk_agbno;
1322         }
1323
1324         ASSERT(agbno >= chunk_agbno);
1325         cluster_agbno = chunk_agbno +
1326                 ((offset_agbno / blks_per_cluster) * blks_per_cluster);
1327         offset = ((agbno - cluster_agbno) * mp->m_sb.sb_inopblock) +
1328                 XFS_INO_TO_OFFSET(mp, ino);
1329
1330         imap->im_blkno = XFS_AGB_TO_DADDR(mp, agno, cluster_agbno);
1331         imap->im_len = XFS_FSB_TO_BB(mp, blks_per_cluster);
1332         imap->im_boffset = (ushort)(offset << mp->m_sb.sb_inodelog);
1333
1334         /*
1335          * If the inode number maps to a block outside the bounds
1336          * of the file system then return NULL rather than calling
1337          * read_buf and panicing when we get an error from the
1338          * driver.
1339          */
1340         if ((imap->im_blkno + imap->im_len) >
1341             XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks)) {
1342                 xfs_fs_cmn_err(CE_ALERT, mp, "xfs_imap: "
1343                         "(imap->im_blkno (0x%llx) + imap->im_len (0x%llx)) > "
1344                         " XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks) (0x%llx)",
1345                         (unsigned long long) imap->im_blkno,
1346                         (unsigned long long) imap->im_len,
1347                         XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks));
1348                 return XFS_ERROR(EINVAL);
1349         }
1350
1351         return 0;
1352 }
1353
1354 /*
1355  * Compute and fill in value of m_in_maxlevels.
1356  */
1357 void
1358 xfs_ialloc_compute_maxlevels(
1359         xfs_mount_t     *mp)            /* file system mount structure */
1360 {
1361         int             level;
1362         uint            maxblocks;
1363         uint            maxleafents;
1364         int             minleafrecs;
1365         int             minnoderecs;
1366
1367         maxleafents = (1LL << XFS_INO_AGINO_BITS(mp)) >>
1368                 XFS_INODES_PER_CHUNK_LOG;
1369         minleafrecs = mp->m_alloc_mnr[0];
1370         minnoderecs = mp->m_alloc_mnr[1];
1371         maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs;
1372         for (level = 1; maxblocks > 1; level++)
1373                 maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs;
1374         mp->m_in_maxlevels = level;
1375 }
1376
1377 /*
1378  * Log specified fields for the ag hdr (inode section)
1379  */
1380 void
1381 xfs_ialloc_log_agi(
1382         xfs_trans_t     *tp,            /* transaction pointer */
1383         xfs_buf_t       *bp,            /* allocation group header buffer */
1384         int             fields)         /* bitmask of fields to log */
1385 {
1386         int                     first;          /* first byte number */
1387         int                     last;           /* last byte number */
1388         static const short      offsets[] = {   /* field starting offsets */
1389                                         /* keep in sync with bit definitions */
1390                 offsetof(xfs_agi_t, agi_magicnum),
1391                 offsetof(xfs_agi_t, agi_versionnum),
1392                 offsetof(xfs_agi_t, agi_seqno),
1393                 offsetof(xfs_agi_t, agi_length),
1394                 offsetof(xfs_agi_t, agi_count),
1395                 offsetof(xfs_agi_t, agi_root),
1396                 offsetof(xfs_agi_t, agi_level),
1397                 offsetof(xfs_agi_t, agi_freecount),
1398                 offsetof(xfs_agi_t, agi_newino),
1399                 offsetof(xfs_agi_t, agi_dirino),
1400                 offsetof(xfs_agi_t, agi_unlinked),
1401                 sizeof(xfs_agi_t)
1402         };
1403 #ifdef DEBUG
1404         xfs_agi_t               *agi;   /* allocation group header */
1405
1406         agi = XFS_BUF_TO_AGI(bp);
1407         ASSERT(be32_to_cpu(agi->agi_magicnum) == XFS_AGI_MAGIC);
1408 #endif
1409         /*
1410          * Compute byte offsets for the first and last fields.
1411          */
1412         xfs_btree_offsets(fields, offsets, XFS_AGI_NUM_BITS, &first, &last);
1413         /*
1414          * Log the allocation group inode header buffer.
1415          */
1416         xfs_trans_log_buf(tp, bp, first, last);
1417 }
1418
1419 #ifdef DEBUG
1420 STATIC void
1421 xfs_check_agi_unlinked(
1422         struct xfs_agi          *agi)
1423 {
1424         int                     i;
1425
1426         for (i = 0; i < XFS_AGI_UNLINKED_BUCKETS; i++)
1427                 ASSERT(agi->agi_unlinked[i]);
1428 }
1429 #else
1430 #define xfs_check_agi_unlinked(agi)
1431 #endif
1432
1433 /*
1434  * Read in the allocation group header (inode allocation section)
1435  */
1436 int
1437 xfs_read_agi(
1438         struct xfs_mount        *mp,    /* file system mount structure */
1439         struct xfs_trans        *tp,    /* transaction pointer */
1440         xfs_agnumber_t          agno,   /* allocation group number */
1441         struct xfs_buf          **bpp)  /* allocation group hdr buf */
1442 {
1443         struct xfs_agi          *agi;   /* allocation group header */
1444         int                     agi_ok; /* agi is consistent */
1445         int                     error;
1446
1447         ASSERT(agno != NULLAGNUMBER);
1448
1449         error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp,
1450                         XFS_AG_DADDR(mp, agno, XFS_AGI_DADDR(mp)),
1451                         XFS_FSS_TO_BB(mp, 1), 0, bpp);
1452         if (error)
1453                 return error;
1454
1455         ASSERT(*bpp && !XFS_BUF_GETERROR(*bpp));
1456         agi = XFS_BUF_TO_AGI(*bpp);
1457
1458         /*
1459          * Validate the magic number of the agi block.
1460          */
1461         agi_ok = be32_to_cpu(agi->agi_magicnum) == XFS_AGI_MAGIC &&
1462                 XFS_AGI_GOOD_VERSION(be32_to_cpu(agi->agi_versionnum)) &&
1463                 be32_to_cpu(agi->agi_seqno) == agno;
1464         if (unlikely(XFS_TEST_ERROR(!agi_ok, mp, XFS_ERRTAG_IALLOC_READ_AGI,
1465                         XFS_RANDOM_IALLOC_READ_AGI))) {
1466                 XFS_CORRUPTION_ERROR("xfs_read_agi", XFS_ERRLEVEL_LOW,
1467                                      mp, agi);
1468                 xfs_trans_brelse(tp, *bpp);
1469                 return XFS_ERROR(EFSCORRUPTED);
1470         }
1471
1472         XFS_BUF_SET_VTYPE_REF(*bpp, B_FS_AGI, XFS_AGI_REF);
1473
1474         xfs_check_agi_unlinked(agi);
1475         return 0;
1476 }
1477
1478 int
1479 xfs_ialloc_read_agi(
1480         struct xfs_mount        *mp,    /* file system mount structure */
1481         struct xfs_trans        *tp,    /* transaction pointer */
1482         xfs_agnumber_t          agno,   /* allocation group number */
1483         struct xfs_buf          **bpp)  /* allocation group hdr buf */
1484 {
1485         struct xfs_agi          *agi;   /* allocation group header */
1486         struct xfs_perag        *pag;   /* per allocation group data */
1487         int                     error;
1488
1489         error = xfs_read_agi(mp, tp, agno, bpp);
1490         if (error)
1491                 return error;
1492
1493         agi = XFS_BUF_TO_AGI(*bpp);
1494         pag = &mp->m_perag[agno];
1495
1496         if (!pag->pagi_init) {
1497                 pag->pagi_freecount = be32_to_cpu(agi->agi_freecount);
1498                 pag->pagi_count = be32_to_cpu(agi->agi_count);
1499                 pag->pagi_init = 1;
1500         }
1501
1502         /*
1503          * It's possible for these to be out of sync if
1504          * we are in the middle of a forced shutdown.
1505          */
1506         ASSERT(pag->pagi_freecount == be32_to_cpu(agi->agi_freecount) ||
1507                 XFS_FORCED_SHUTDOWN(mp));
1508         return 0;
1509 }
1510
1511 /*
1512  * Read in the agi to initialise the per-ag data in the mount structure
1513  */
1514 int
1515 xfs_ialloc_pagi_init(
1516         xfs_mount_t     *mp,            /* file system mount structure */
1517         xfs_trans_t     *tp,            /* transaction pointer */
1518         xfs_agnumber_t  agno)           /* allocation group number */
1519 {
1520         xfs_buf_t       *bp = NULL;
1521         int             error;
1522
1523         error = xfs_ialloc_read_agi(mp, tp, agno, &bp);
1524         if (error)
1525                 return error;
1526         if (bp)
1527                 xfs_trans_brelse(tp, bp);
1528         return 0;
1529 }