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