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