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