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