ocfs2: Allocate inode groups from global_bitmap.
[safe/jmp/linux-2.6] / fs / ocfs2 / suballoc.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * suballoc.c
5  *
6  * metadata alloc and free
7  * Inspired by ext3 block groups.
8  *
9  * Copyright (C) 2002, 2004 Oracle.  All rights reserved.
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public
22  * License along with this program; if not, write to the
23  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24  * Boston, MA 021110-1307, USA.
25  */
26
27 #include <linux/fs.h>
28 #include <linux/types.h>
29 #include <linux/slab.h>
30 #include <linux/highmem.h>
31
32 #define MLOG_MASK_PREFIX ML_DISK_ALLOC
33 #include <cluster/masklog.h>
34
35 #include "ocfs2.h"
36
37 #include "alloc.h"
38 #include "blockcheck.h"
39 #include "dlmglue.h"
40 #include "inode.h"
41 #include "journal.h"
42 #include "localalloc.h"
43 #include "suballoc.h"
44 #include "super.h"
45 #include "sysfile.h"
46 #include "uptodate.h"
47
48 #include "buffer_head_io.h"
49
50 #define NOT_ALLOC_NEW_GROUP             0
51 #define ALLOC_NEW_GROUP                 0x1
52 #define ALLOC_GROUPS_FROM_GLOBAL        0x2
53
54 #define OCFS2_MAX_INODES_TO_STEAL       1024
55
56 static inline void ocfs2_debug_bg(struct ocfs2_group_desc *bg);
57 static inline void ocfs2_debug_suballoc_inode(struct ocfs2_dinode *fe);
58 static inline u16 ocfs2_find_victim_chain(struct ocfs2_chain_list *cl);
59 static int ocfs2_block_group_fill(handle_t *handle,
60                                   struct inode *alloc_inode,
61                                   struct buffer_head *bg_bh,
62                                   u64 group_blkno,
63                                   u16 my_chain,
64                                   struct ocfs2_chain_list *cl);
65 static int ocfs2_block_group_alloc(struct ocfs2_super *osb,
66                                    struct inode *alloc_inode,
67                                    struct buffer_head *bh,
68                                    u64 max_block,
69                                    int flags);
70
71 static int ocfs2_cluster_group_search(struct inode *inode,
72                                       struct buffer_head *group_bh,
73                                       u32 bits_wanted, u32 min_bits,
74                                       u64 max_block,
75                                       u16 *bit_off, u16 *bits_found);
76 static int ocfs2_block_group_search(struct inode *inode,
77                                     struct buffer_head *group_bh,
78                                     u32 bits_wanted, u32 min_bits,
79                                     u64 max_block,
80                                     u16 *bit_off, u16 *bits_found);
81 static int ocfs2_claim_suballoc_bits(struct ocfs2_super *osb,
82                                      struct ocfs2_alloc_context *ac,
83                                      handle_t *handle,
84                                      u32 bits_wanted,
85                                      u32 min_bits,
86                                      u16 *bit_off,
87                                      unsigned int *num_bits,
88                                      u64 *bg_blkno);
89 static int ocfs2_test_bg_bit_allocatable(struct buffer_head *bg_bh,
90                                          int nr);
91 static inline int ocfs2_block_group_set_bits(handle_t *handle,
92                                              struct inode *alloc_inode,
93                                              struct ocfs2_group_desc *bg,
94                                              struct buffer_head *group_bh,
95                                              unsigned int bit_off,
96                                              unsigned int num_bits);
97 static inline int ocfs2_block_group_clear_bits(handle_t *handle,
98                                                struct inode *alloc_inode,
99                                                struct ocfs2_group_desc *bg,
100                                                struct buffer_head *group_bh,
101                                                unsigned int bit_off,
102                                                unsigned int num_bits);
103
104 static int ocfs2_relink_block_group(handle_t *handle,
105                                     struct inode *alloc_inode,
106                                     struct buffer_head *fe_bh,
107                                     struct buffer_head *bg_bh,
108                                     struct buffer_head *prev_bg_bh,
109                                     u16 chain);
110 static inline int ocfs2_block_group_reasonably_empty(struct ocfs2_group_desc *bg,
111                                                      u32 wanted);
112 static inline u32 ocfs2_desc_bitmap_to_cluster_off(struct inode *inode,
113                                                    u64 bg_blkno,
114                                                    u16 bg_bit_off);
115 static inline void ocfs2_block_to_cluster_group(struct inode *inode,
116                                                 u64 data_blkno,
117                                                 u64 *bg_blkno,
118                                                 u16 *bg_bit_off);
119 static int ocfs2_reserve_clusters_with_limit(struct ocfs2_super *osb,
120                                              u32 bits_wanted, u64 max_block,
121                                              int flags,
122                                              struct ocfs2_alloc_context **ac);
123
124 void ocfs2_free_ac_resource(struct ocfs2_alloc_context *ac)
125 {
126         struct inode *inode = ac->ac_inode;
127
128         if (inode) {
129                 if (ac->ac_which != OCFS2_AC_USE_LOCAL)
130                         ocfs2_inode_unlock(inode, 1);
131
132                 mutex_unlock(&inode->i_mutex);
133
134                 iput(inode);
135                 ac->ac_inode = NULL;
136         }
137         brelse(ac->ac_bh);
138         ac->ac_bh = NULL;
139 }
140
141 void ocfs2_free_alloc_context(struct ocfs2_alloc_context *ac)
142 {
143         ocfs2_free_ac_resource(ac);
144         kfree(ac);
145 }
146
147 static u32 ocfs2_bits_per_group(struct ocfs2_chain_list *cl)
148 {
149         return (u32)le16_to_cpu(cl->cl_cpg) * (u32)le16_to_cpu(cl->cl_bpc);
150 }
151
152 #define do_error(fmt, ...)                                              \
153         do{                                                             \
154                 if (clean_error)                                        \
155                         mlog(ML_ERROR, fmt "\n", ##__VA_ARGS__);        \
156                 else                                                    \
157                         ocfs2_error(sb, fmt, ##__VA_ARGS__);            \
158         } while (0)
159
160 static int ocfs2_validate_gd_self(struct super_block *sb,
161                                   struct buffer_head *bh,
162                                   int clean_error)
163 {
164         struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
165
166         if (!OCFS2_IS_VALID_GROUP_DESC(gd)) {
167                 do_error("Group descriptor #%llu has bad signature %.*s",
168                          (unsigned long long)bh->b_blocknr, 7,
169                          gd->bg_signature);
170                 return -EINVAL;
171         }
172
173         if (le64_to_cpu(gd->bg_blkno) != bh->b_blocknr) {
174                 do_error("Group descriptor #%llu has an invalid bg_blkno "
175                          "of %llu",
176                          (unsigned long long)bh->b_blocknr,
177                          (unsigned long long)le64_to_cpu(gd->bg_blkno));
178                 return -EINVAL;
179         }
180
181         if (le32_to_cpu(gd->bg_generation) != OCFS2_SB(sb)->fs_generation) {
182                 do_error("Group descriptor #%llu has an invalid "
183                          "fs_generation of #%u",
184                          (unsigned long long)bh->b_blocknr,
185                          le32_to_cpu(gd->bg_generation));
186                 return -EINVAL;
187         }
188
189         if (le16_to_cpu(gd->bg_free_bits_count) > le16_to_cpu(gd->bg_bits)) {
190                 do_error("Group descriptor #%llu has bit count %u but "
191                          "claims that %u are free",
192                          (unsigned long long)bh->b_blocknr,
193                          le16_to_cpu(gd->bg_bits),
194                          le16_to_cpu(gd->bg_free_bits_count));
195                 return -EINVAL;
196         }
197
198         if (le16_to_cpu(gd->bg_bits) > (8 * le16_to_cpu(gd->bg_size))) {
199                 do_error("Group descriptor #%llu has bit count %u but "
200                          "max bitmap bits of %u",
201                          (unsigned long long)bh->b_blocknr,
202                          le16_to_cpu(gd->bg_bits),
203                          8 * le16_to_cpu(gd->bg_size));
204                 return -EINVAL;
205         }
206
207         return 0;
208 }
209
210 static int ocfs2_validate_gd_parent(struct super_block *sb,
211                                     struct ocfs2_dinode *di,
212                                     struct buffer_head *bh,
213                                     int clean_error)
214 {
215         unsigned int max_bits;
216         struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
217
218         if (di->i_blkno != gd->bg_parent_dinode) {
219                 do_error("Group descriptor #%llu has bad parent "
220                          "pointer (%llu, expected %llu)",
221                          (unsigned long long)bh->b_blocknr,
222                          (unsigned long long)le64_to_cpu(gd->bg_parent_dinode),
223                          (unsigned long long)le64_to_cpu(di->i_blkno));
224                 return -EINVAL;
225         }
226
227         max_bits = le16_to_cpu(di->id2.i_chain.cl_cpg) * le16_to_cpu(di->id2.i_chain.cl_bpc);
228         if (le16_to_cpu(gd->bg_bits) > max_bits) {
229                 do_error("Group descriptor #%llu has bit count of %u",
230                          (unsigned long long)bh->b_blocknr,
231                          le16_to_cpu(gd->bg_bits));
232                 return -EINVAL;
233         }
234
235         if (le16_to_cpu(gd->bg_chain) >=
236             le16_to_cpu(di->id2.i_chain.cl_next_free_rec)) {
237                 do_error("Group descriptor #%llu has bad chain %u",
238                          (unsigned long long)bh->b_blocknr,
239                          le16_to_cpu(gd->bg_chain));
240                 return -EINVAL;
241         }
242
243         return 0;
244 }
245
246 #undef do_error
247
248 /*
249  * This version only prints errors.  It does not fail the filesystem, and
250  * exists only for resize.
251  */
252 int ocfs2_check_group_descriptor(struct super_block *sb,
253                                  struct ocfs2_dinode *di,
254                                  struct buffer_head *bh)
255 {
256         int rc;
257         struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
258
259         BUG_ON(!buffer_uptodate(bh));
260
261         /*
262          * If the ecc fails, we return the error but otherwise
263          * leave the filesystem running.  We know any error is
264          * local to this block.
265          */
266         rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &gd->bg_check);
267         if (rc) {
268                 mlog(ML_ERROR,
269                      "Checksum failed for group descriptor %llu\n",
270                      (unsigned long long)bh->b_blocknr);
271         } else
272                 rc = ocfs2_validate_gd_self(sb, bh, 1);
273         if (!rc)
274                 rc = ocfs2_validate_gd_parent(sb, di, bh, 1);
275
276         return rc;
277 }
278
279 static int ocfs2_validate_group_descriptor(struct super_block *sb,
280                                            struct buffer_head *bh)
281 {
282         int rc;
283         struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
284
285         mlog(0, "Validating group descriptor %llu\n",
286              (unsigned long long)bh->b_blocknr);
287
288         BUG_ON(!buffer_uptodate(bh));
289
290         /*
291          * If the ecc fails, we return the error but otherwise
292          * leave the filesystem running.  We know any error is
293          * local to this block.
294          */
295         rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &gd->bg_check);
296         if (rc)
297                 return rc;
298
299         /*
300          * Errors after here are fatal.
301          */
302
303         return ocfs2_validate_gd_self(sb, bh, 0);
304 }
305
306 int ocfs2_read_group_descriptor(struct inode *inode, struct ocfs2_dinode *di,
307                                 u64 gd_blkno, struct buffer_head **bh)
308 {
309         int rc;
310         struct buffer_head *tmp = *bh;
311
312         rc = ocfs2_read_block(inode, gd_blkno, &tmp,
313                               ocfs2_validate_group_descriptor);
314         if (rc)
315                 goto out;
316
317         rc = ocfs2_validate_gd_parent(inode->i_sb, di, tmp, 0);
318         if (rc) {
319                 brelse(tmp);
320                 goto out;
321         }
322
323         /* If ocfs2_read_block() got us a new bh, pass it up. */
324         if (!*bh)
325                 *bh = tmp;
326
327 out:
328         return rc;
329 }
330
331 static int ocfs2_block_group_fill(handle_t *handle,
332                                   struct inode *alloc_inode,
333                                   struct buffer_head *bg_bh,
334                                   u64 group_blkno,
335                                   u16 my_chain,
336                                   struct ocfs2_chain_list *cl)
337 {
338         int status = 0;
339         struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
340         struct super_block * sb = alloc_inode->i_sb;
341
342         mlog_entry_void();
343
344         if (((unsigned long long) bg_bh->b_blocknr) != group_blkno) {
345                 ocfs2_error(alloc_inode->i_sb, "group block (%llu) != "
346                             "b_blocknr (%llu)",
347                             (unsigned long long)group_blkno,
348                             (unsigned long long) bg_bh->b_blocknr);
349                 status = -EIO;
350                 goto bail;
351         }
352
353         status = ocfs2_journal_access_gd(handle,
354                                          alloc_inode,
355                                          bg_bh,
356                                          OCFS2_JOURNAL_ACCESS_CREATE);
357         if (status < 0) {
358                 mlog_errno(status);
359                 goto bail;
360         }
361
362         memset(bg, 0, sb->s_blocksize);
363         strcpy(bg->bg_signature, OCFS2_GROUP_DESC_SIGNATURE);
364         bg->bg_generation = cpu_to_le32(OCFS2_SB(sb)->fs_generation);
365         bg->bg_size = cpu_to_le16(ocfs2_group_bitmap_size(sb));
366         bg->bg_bits = cpu_to_le16(ocfs2_bits_per_group(cl));
367         bg->bg_chain = cpu_to_le16(my_chain);
368         bg->bg_next_group = cl->cl_recs[my_chain].c_blkno;
369         bg->bg_parent_dinode = cpu_to_le64(OCFS2_I(alloc_inode)->ip_blkno);
370         bg->bg_blkno = cpu_to_le64(group_blkno);
371         /* set the 1st bit in the bitmap to account for the descriptor block */
372         ocfs2_set_bit(0, (unsigned long *)bg->bg_bitmap);
373         bg->bg_free_bits_count = cpu_to_le16(le16_to_cpu(bg->bg_bits) - 1);
374
375         status = ocfs2_journal_dirty(handle, bg_bh);
376         if (status < 0)
377                 mlog_errno(status);
378
379         /* There is no need to zero out or otherwise initialize the
380          * other blocks in a group - All valid FS metadata in a block
381          * group stores the superblock fs_generation value at
382          * allocation time. */
383
384 bail:
385         mlog_exit(status);
386         return status;
387 }
388
389 static inline u16 ocfs2_find_smallest_chain(struct ocfs2_chain_list *cl)
390 {
391         u16 curr, best;
392
393         best = curr = 0;
394         while (curr < le16_to_cpu(cl->cl_count)) {
395                 if (le32_to_cpu(cl->cl_recs[best].c_total) >
396                     le32_to_cpu(cl->cl_recs[curr].c_total))
397                         best = curr;
398                 curr++;
399         }
400         return best;
401 }
402
403 /*
404  * We expect the block group allocator to already be locked.
405  */
406 static int ocfs2_block_group_alloc(struct ocfs2_super *osb,
407                                    struct inode *alloc_inode,
408                                    struct buffer_head *bh,
409                                    u64 max_block,
410                                    int flags)
411 {
412         int status, credits;
413         struct ocfs2_dinode *fe = (struct ocfs2_dinode *) bh->b_data;
414         struct ocfs2_chain_list *cl;
415         struct ocfs2_alloc_context *ac = NULL;
416         handle_t *handle = NULL;
417         u32 bit_off, num_bits;
418         u16 alloc_rec;
419         u64 bg_blkno;
420         struct buffer_head *bg_bh = NULL;
421         struct ocfs2_group_desc *bg;
422
423         BUG_ON(ocfs2_is_cluster_bitmap(alloc_inode));
424
425         mlog_entry_void();
426
427         cl = &fe->id2.i_chain;
428         status = ocfs2_reserve_clusters_with_limit(osb,
429                                                    le16_to_cpu(cl->cl_cpg),
430                                                    max_block, flags, &ac);
431         if (status < 0) {
432                 if (status != -ENOSPC)
433                         mlog_errno(status);
434                 goto bail;
435         }
436
437         credits = ocfs2_calc_group_alloc_credits(osb->sb,
438                                                  le16_to_cpu(cl->cl_cpg));
439         handle = ocfs2_start_trans(osb, credits);
440         if (IS_ERR(handle)) {
441                 status = PTR_ERR(handle);
442                 handle = NULL;
443                 mlog_errno(status);
444                 goto bail;
445         }
446
447         status = ocfs2_claim_clusters(osb,
448                                       handle,
449                                       ac,
450                                       le16_to_cpu(cl->cl_cpg),
451                                       &bit_off,
452                                       &num_bits);
453         if (status < 0) {
454                 if (status != -ENOSPC)
455                         mlog_errno(status);
456                 goto bail;
457         }
458
459         alloc_rec = ocfs2_find_smallest_chain(cl);
460
461         /* setup the group */
462         bg_blkno = ocfs2_clusters_to_blocks(osb->sb, bit_off);
463         mlog(0, "new descriptor, record %u, at block %llu\n",
464              alloc_rec, (unsigned long long)bg_blkno);
465
466         bg_bh = sb_getblk(osb->sb, bg_blkno);
467         if (!bg_bh) {
468                 status = -EIO;
469                 mlog_errno(status);
470                 goto bail;
471         }
472         ocfs2_set_new_buffer_uptodate(alloc_inode, bg_bh);
473
474         status = ocfs2_block_group_fill(handle,
475                                         alloc_inode,
476                                         bg_bh,
477                                         bg_blkno,
478                                         alloc_rec,
479                                         cl);
480         if (status < 0) {
481                 mlog_errno(status);
482                 goto bail;
483         }
484
485         bg = (struct ocfs2_group_desc *) bg_bh->b_data;
486
487         status = ocfs2_journal_access_di(handle, alloc_inode,
488                                          bh, OCFS2_JOURNAL_ACCESS_WRITE);
489         if (status < 0) {
490                 mlog_errno(status);
491                 goto bail;
492         }
493
494         le32_add_cpu(&cl->cl_recs[alloc_rec].c_free,
495                      le16_to_cpu(bg->bg_free_bits_count));
496         le32_add_cpu(&cl->cl_recs[alloc_rec].c_total, le16_to_cpu(bg->bg_bits));
497         cl->cl_recs[alloc_rec].c_blkno  = cpu_to_le64(bg_blkno);
498         if (le16_to_cpu(cl->cl_next_free_rec) < le16_to_cpu(cl->cl_count))
499                 le16_add_cpu(&cl->cl_next_free_rec, 1);
500
501         le32_add_cpu(&fe->id1.bitmap1.i_used, le16_to_cpu(bg->bg_bits) -
502                                         le16_to_cpu(bg->bg_free_bits_count));
503         le32_add_cpu(&fe->id1.bitmap1.i_total, le16_to_cpu(bg->bg_bits));
504         le32_add_cpu(&fe->i_clusters, le16_to_cpu(cl->cl_cpg));
505
506         status = ocfs2_journal_dirty(handle, bh);
507         if (status < 0) {
508                 mlog_errno(status);
509                 goto bail;
510         }
511
512         spin_lock(&OCFS2_I(alloc_inode)->ip_lock);
513         OCFS2_I(alloc_inode)->ip_clusters = le32_to_cpu(fe->i_clusters);
514         fe->i_size = cpu_to_le64(ocfs2_clusters_to_bytes(alloc_inode->i_sb,
515                                              le32_to_cpu(fe->i_clusters)));
516         spin_unlock(&OCFS2_I(alloc_inode)->ip_lock);
517         i_size_write(alloc_inode, le64_to_cpu(fe->i_size));
518         alloc_inode->i_blocks = ocfs2_inode_sector_count(alloc_inode);
519
520         status = 0;
521 bail:
522         if (handle)
523                 ocfs2_commit_trans(osb, handle);
524
525         if (ac)
526                 ocfs2_free_alloc_context(ac);
527
528         brelse(bg_bh);
529
530         mlog_exit(status);
531         return status;
532 }
533
534 static int ocfs2_reserve_suballoc_bits(struct ocfs2_super *osb,
535                                        struct ocfs2_alloc_context *ac,
536                                        int type,
537                                        u32 slot,
538                                        int flags)
539 {
540         int status;
541         u32 bits_wanted = ac->ac_bits_wanted;
542         struct inode *alloc_inode;
543         struct buffer_head *bh = NULL;
544         struct ocfs2_dinode *fe;
545         u32 free_bits;
546
547         mlog_entry_void();
548
549         alloc_inode = ocfs2_get_system_file_inode(osb, type, slot);
550         if (!alloc_inode) {
551                 mlog_errno(-EINVAL);
552                 return -EINVAL;
553         }
554
555         mutex_lock(&alloc_inode->i_mutex);
556
557         status = ocfs2_inode_lock(alloc_inode, &bh, 1);
558         if (status < 0) {
559                 mutex_unlock(&alloc_inode->i_mutex);
560                 iput(alloc_inode);
561
562                 mlog_errno(status);
563                 return status;
564         }
565
566         ac->ac_inode = alloc_inode;
567         ac->ac_alloc_slot = slot;
568
569         fe = (struct ocfs2_dinode *) bh->b_data;
570
571         /* The bh was validated by the inode read inside
572          * ocfs2_inode_lock().  Any corruption is a code bug. */
573         BUG_ON(!OCFS2_IS_VALID_DINODE(fe));
574
575         if (!(fe->i_flags & cpu_to_le32(OCFS2_CHAIN_FL))) {
576                 ocfs2_error(alloc_inode->i_sb, "Invalid chain allocator %llu",
577                             (unsigned long long)le64_to_cpu(fe->i_blkno));
578                 status = -EIO;
579                 goto bail;
580         }
581
582         free_bits = le32_to_cpu(fe->id1.bitmap1.i_total) -
583                 le32_to_cpu(fe->id1.bitmap1.i_used);
584
585         if (bits_wanted > free_bits) {
586                 /* cluster bitmap never grows */
587                 if (ocfs2_is_cluster_bitmap(alloc_inode)) {
588                         mlog(0, "Disk Full: wanted=%u, free_bits=%u\n",
589                              bits_wanted, free_bits);
590                         status = -ENOSPC;
591                         goto bail;
592                 }
593
594                 if (!(flags & ALLOC_NEW_GROUP)) {
595                         mlog(0, "Alloc File %u Full: wanted=%u, free_bits=%u, "
596                              "and we don't alloc a new group for it.\n",
597                              slot, bits_wanted, free_bits);
598                         status = -ENOSPC;
599                         goto bail;
600                 }
601
602                 status = ocfs2_block_group_alloc(osb, alloc_inode, bh,
603                                                  ac->ac_max_block, flags);
604                 if (status < 0) {
605                         if (status != -ENOSPC)
606                                 mlog_errno(status);
607                         goto bail;
608                 }
609                 atomic_inc(&osb->alloc_stats.bg_extends);
610
611                 /* You should never ask for this much metadata */
612                 BUG_ON(bits_wanted >
613                        (le32_to_cpu(fe->id1.bitmap1.i_total)
614                         - le32_to_cpu(fe->id1.bitmap1.i_used)));
615         }
616
617         get_bh(bh);
618         ac->ac_bh = bh;
619 bail:
620         brelse(bh);
621
622         mlog_exit(status);
623         return status;
624 }
625
626 int ocfs2_reserve_new_metadata_blocks(struct ocfs2_super *osb,
627                                       int blocks,
628                                       struct ocfs2_alloc_context **ac)
629 {
630         int status;
631         u32 slot;
632
633         *ac = kzalloc(sizeof(struct ocfs2_alloc_context), GFP_KERNEL);
634         if (!(*ac)) {
635                 status = -ENOMEM;
636                 mlog_errno(status);
637                 goto bail;
638         }
639
640         (*ac)->ac_bits_wanted = blocks;
641         (*ac)->ac_which = OCFS2_AC_USE_META;
642         slot = osb->slot_num;
643         (*ac)->ac_group_search = ocfs2_block_group_search;
644
645         status = ocfs2_reserve_suballoc_bits(osb, (*ac),
646                                              EXTENT_ALLOC_SYSTEM_INODE,
647                                              slot, ALLOC_NEW_GROUP);
648         if (status < 0) {
649                 if (status != -ENOSPC)
650                         mlog_errno(status);
651                 goto bail;
652         }
653
654         status = 0;
655 bail:
656         if ((status < 0) && *ac) {
657                 ocfs2_free_alloc_context(*ac);
658                 *ac = NULL;
659         }
660
661         mlog_exit(status);
662         return status;
663 }
664
665 int ocfs2_reserve_new_metadata(struct ocfs2_super *osb,
666                                struct ocfs2_extent_list *root_el,
667                                struct ocfs2_alloc_context **ac)
668 {
669         return ocfs2_reserve_new_metadata_blocks(osb,
670                                         ocfs2_extend_meta_needed(root_el),
671                                         ac);
672 }
673
674 static int ocfs2_steal_inode_from_other_nodes(struct ocfs2_super *osb,
675                                               struct ocfs2_alloc_context *ac)
676 {
677         int i, status = -ENOSPC;
678         s16 slot = ocfs2_get_inode_steal_slot(osb);
679
680         /* Start to steal inodes from the first slot after ours. */
681         if (slot == OCFS2_INVALID_SLOT)
682                 slot = osb->slot_num + 1;
683
684         for (i = 0; i < osb->max_slots; i++, slot++) {
685                 if (slot == osb->max_slots)
686                         slot = 0;
687
688                 if (slot == osb->slot_num)
689                         continue;
690
691                 status = ocfs2_reserve_suballoc_bits(osb, ac,
692                                                      INODE_ALLOC_SYSTEM_INODE,
693                                                      slot, NOT_ALLOC_NEW_GROUP);
694                 if (status >= 0) {
695                         ocfs2_set_inode_steal_slot(osb, slot);
696                         break;
697                 }
698
699                 ocfs2_free_ac_resource(ac);
700         }
701
702         return status;
703 }
704
705 int ocfs2_reserve_new_inode(struct ocfs2_super *osb,
706                             struct ocfs2_alloc_context **ac)
707 {
708         int status;
709         s16 slot = ocfs2_get_inode_steal_slot(osb);
710
711         *ac = kzalloc(sizeof(struct ocfs2_alloc_context), GFP_KERNEL);
712         if (!(*ac)) {
713                 status = -ENOMEM;
714                 mlog_errno(status);
715                 goto bail;
716         }
717
718         (*ac)->ac_bits_wanted = 1;
719         (*ac)->ac_which = OCFS2_AC_USE_INODE;
720
721         (*ac)->ac_group_search = ocfs2_block_group_search;
722
723         /*
724          * stat(2) can't handle i_ino > 32bits, so we tell the
725          * lower levels not to allocate us a block group past that
726          * limit.  The 'inode64' mount option avoids this behavior.
727          */
728         if (!(osb->s_mount_opt & OCFS2_MOUNT_INODE64))
729                 (*ac)->ac_max_block = (u32)~0U;
730
731         /*
732          * slot is set when we successfully steal inode from other nodes.
733          * It is reset in 3 places:
734          * 1. when we flush the truncate log
735          * 2. when we complete local alloc recovery.
736          * 3. when we successfully allocate from our own slot.
737          * After it is set, we will go on stealing inodes until we find the
738          * need to check our slots to see whether there is some space for us.
739          */
740         if (slot != OCFS2_INVALID_SLOT &&
741             atomic_read(&osb->s_num_inodes_stolen) < OCFS2_MAX_INODES_TO_STEAL)
742                 goto inode_steal;
743
744         atomic_set(&osb->s_num_inodes_stolen, 0);
745         status = ocfs2_reserve_suballoc_bits(osb, *ac,
746                                              INODE_ALLOC_SYSTEM_INODE,
747                                              osb->slot_num,
748                                              ALLOC_NEW_GROUP |
749                                              ALLOC_GROUPS_FROM_GLOBAL);
750         if (status >= 0) {
751                 status = 0;
752
753                 /*
754                  * Some inodes must be freed by us, so try to allocate
755                  * from our own next time.
756                  */
757                 if (slot != OCFS2_INVALID_SLOT)
758                         ocfs2_init_inode_steal_slot(osb);
759                 goto bail;
760         } else if (status < 0 && status != -ENOSPC) {
761                 mlog_errno(status);
762                 goto bail;
763         }
764
765         ocfs2_free_ac_resource(*ac);
766
767 inode_steal:
768         status = ocfs2_steal_inode_from_other_nodes(osb, *ac);
769         atomic_inc(&osb->s_num_inodes_stolen);
770         if (status < 0) {
771                 if (status != -ENOSPC)
772                         mlog_errno(status);
773                 goto bail;
774         }
775
776         status = 0;
777 bail:
778         if ((status < 0) && *ac) {
779                 ocfs2_free_alloc_context(*ac);
780                 *ac = NULL;
781         }
782
783         mlog_exit(status);
784         return status;
785 }
786
787 /* local alloc code has to do the same thing, so rather than do this
788  * twice.. */
789 int ocfs2_reserve_cluster_bitmap_bits(struct ocfs2_super *osb,
790                                       struct ocfs2_alloc_context *ac)
791 {
792         int status;
793
794         ac->ac_which = OCFS2_AC_USE_MAIN;
795         ac->ac_group_search = ocfs2_cluster_group_search;
796
797         status = ocfs2_reserve_suballoc_bits(osb, ac,
798                                              GLOBAL_BITMAP_SYSTEM_INODE,
799                                              OCFS2_INVALID_SLOT,
800                                              ALLOC_NEW_GROUP);
801         if (status < 0 && status != -ENOSPC) {
802                 mlog_errno(status);
803                 goto bail;
804         }
805
806 bail:
807         return status;
808 }
809
810 /* Callers don't need to care which bitmap (local alloc or main) to
811  * use so we figure it out for them, but unfortunately this clutters
812  * things a bit. */
813 static int ocfs2_reserve_clusters_with_limit(struct ocfs2_super *osb,
814                                              u32 bits_wanted, u64 max_block,
815                                              int flags,
816                                              struct ocfs2_alloc_context **ac)
817 {
818         int status;
819
820         mlog_entry_void();
821
822         *ac = kzalloc(sizeof(struct ocfs2_alloc_context), GFP_KERNEL);
823         if (!(*ac)) {
824                 status = -ENOMEM;
825                 mlog_errno(status);
826                 goto bail;
827         }
828
829         (*ac)->ac_bits_wanted = bits_wanted;
830         (*ac)->ac_max_block = max_block;
831
832         status = -ENOSPC;
833         if (!(flags & ALLOC_GROUPS_FROM_GLOBAL) &&
834             ocfs2_alloc_should_use_local(osb, bits_wanted)) {
835                 status = ocfs2_reserve_local_alloc_bits(osb,
836                                                         bits_wanted,
837                                                         *ac);
838                 if (status == -EFBIG) {
839                         /* The local alloc window is outside ac_max_block.
840                          * use the main bitmap. */
841                         status = -ENOSPC;
842                 } else if ((status < 0) && (status != -ENOSPC)) {
843                         mlog_errno(status);
844                         goto bail;
845                 }
846         }
847
848         if (status == -ENOSPC) {
849                 status = ocfs2_reserve_cluster_bitmap_bits(osb, *ac);
850                 if (status < 0) {
851                         if (status != -ENOSPC)
852                                 mlog_errno(status);
853                         goto bail;
854                 }
855         }
856
857         status = 0;
858 bail:
859         if ((status < 0) && *ac) {
860                 ocfs2_free_alloc_context(*ac);
861                 *ac = NULL;
862         }
863
864         mlog_exit(status);
865         return status;
866 }
867
868 int ocfs2_reserve_clusters(struct ocfs2_super *osb,
869                            u32 bits_wanted,
870                            struct ocfs2_alloc_context **ac)
871 {
872         return ocfs2_reserve_clusters_with_limit(osb, bits_wanted, 0,
873                                                  ALLOC_NEW_GROUP, ac);
874 }
875
876 /*
877  * More or less lifted from ext3. I'll leave their description below:
878  *
879  * "For ext3 allocations, we must not reuse any blocks which are
880  * allocated in the bitmap buffer's "last committed data" copy.  This
881  * prevents deletes from freeing up the page for reuse until we have
882  * committed the delete transaction.
883  *
884  * If we didn't do this, then deleting something and reallocating it as
885  * data would allow the old block to be overwritten before the
886  * transaction committed (because we force data to disk before commit).
887  * This would lead to corruption if we crashed between overwriting the
888  * data and committing the delete.
889  *
890  * @@@ We may want to make this allocation behaviour conditional on
891  * data-writes at some point, and disable it for metadata allocations or
892  * sync-data inodes."
893  *
894  * Note: OCFS2 already does this differently for metadata vs data
895  * allocations, as those bitmaps are separate and undo access is never
896  * called on a metadata group descriptor.
897  */
898 static int ocfs2_test_bg_bit_allocatable(struct buffer_head *bg_bh,
899                                          int nr)
900 {
901         struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
902
903         if (ocfs2_test_bit(nr, (unsigned long *)bg->bg_bitmap))
904                 return 0;
905         if (!buffer_jbd(bg_bh) || !bh2jh(bg_bh)->b_committed_data)
906                 return 1;
907
908         bg = (struct ocfs2_group_desc *) bh2jh(bg_bh)->b_committed_data;
909         return !ocfs2_test_bit(nr, (unsigned long *)bg->bg_bitmap);
910 }
911
912 static int ocfs2_block_group_find_clear_bits(struct ocfs2_super *osb,
913                                              struct buffer_head *bg_bh,
914                                              unsigned int bits_wanted,
915                                              unsigned int total_bits,
916                                              u16 *bit_off,
917                                              u16 *bits_found)
918 {
919         void *bitmap;
920         u16 best_offset, best_size;
921         int offset, start, found, status = 0;
922         struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
923
924         /* Callers got this descriptor from
925          * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
926         BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
927
928         found = start = best_offset = best_size = 0;
929         bitmap = bg->bg_bitmap;
930
931         while((offset = ocfs2_find_next_zero_bit(bitmap, total_bits, start)) != -1) {
932                 if (offset == total_bits)
933                         break;
934
935                 if (!ocfs2_test_bg_bit_allocatable(bg_bh, offset)) {
936                         /* We found a zero, but we can't use it as it
937                          * hasn't been put to disk yet! */
938                         found = 0;
939                         start = offset + 1;
940                 } else if (offset == start) {
941                         /* we found a zero */
942                         found++;
943                         /* move start to the next bit to test */
944                         start++;
945                 } else {
946                         /* got a zero after some ones */
947                         found = 1;
948                         start = offset + 1;
949                 }
950                 if (found > best_size) {
951                         best_size = found;
952                         best_offset = start - found;
953                 }
954                 /* we got everything we needed */
955                 if (found == bits_wanted) {
956                         /* mlog(0, "Found it all!\n"); */
957                         break;
958                 }
959         }
960
961         /* XXX: I think the first clause is equivalent to the second
962          *      - jlbec */
963         if (found == bits_wanted) {
964                 *bit_off = start - found;
965                 *bits_found = found;
966         } else if (best_size) {
967                 *bit_off = best_offset;
968                 *bits_found = best_size;
969         } else {
970                 status = -ENOSPC;
971                 /* No error log here -- see the comment above
972                  * ocfs2_test_bg_bit_allocatable */
973         }
974
975         return status;
976 }
977
978 static inline int ocfs2_block_group_set_bits(handle_t *handle,
979                                              struct inode *alloc_inode,
980                                              struct ocfs2_group_desc *bg,
981                                              struct buffer_head *group_bh,
982                                              unsigned int bit_off,
983                                              unsigned int num_bits)
984 {
985         int status;
986         void *bitmap = bg->bg_bitmap;
987         int journal_type = OCFS2_JOURNAL_ACCESS_WRITE;
988
989         mlog_entry_void();
990
991         /* All callers get the descriptor via
992          * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
993         BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
994         BUG_ON(le16_to_cpu(bg->bg_free_bits_count) < num_bits);
995
996         mlog(0, "block_group_set_bits: off = %u, num = %u\n", bit_off,
997              num_bits);
998
999         if (ocfs2_is_cluster_bitmap(alloc_inode))
1000                 journal_type = OCFS2_JOURNAL_ACCESS_UNDO;
1001
1002         status = ocfs2_journal_access_gd(handle,
1003                                          alloc_inode,
1004                                          group_bh,
1005                                          journal_type);
1006         if (status < 0) {
1007                 mlog_errno(status);
1008                 goto bail;
1009         }
1010
1011         le16_add_cpu(&bg->bg_free_bits_count, -num_bits);
1012
1013         while(num_bits--)
1014                 ocfs2_set_bit(bit_off++, bitmap);
1015
1016         status = ocfs2_journal_dirty(handle,
1017                                      group_bh);
1018         if (status < 0) {
1019                 mlog_errno(status);
1020                 goto bail;
1021         }
1022
1023 bail:
1024         mlog_exit(status);
1025         return status;
1026 }
1027
1028 /* find the one with the most empty bits */
1029 static inline u16 ocfs2_find_victim_chain(struct ocfs2_chain_list *cl)
1030 {
1031         u16 curr, best;
1032
1033         BUG_ON(!cl->cl_next_free_rec);
1034
1035         best = curr = 0;
1036         while (curr < le16_to_cpu(cl->cl_next_free_rec)) {
1037                 if (le32_to_cpu(cl->cl_recs[curr].c_free) >
1038                     le32_to_cpu(cl->cl_recs[best].c_free))
1039                         best = curr;
1040                 curr++;
1041         }
1042
1043         BUG_ON(best >= le16_to_cpu(cl->cl_next_free_rec));
1044         return best;
1045 }
1046
1047 static int ocfs2_relink_block_group(handle_t *handle,
1048                                     struct inode *alloc_inode,
1049                                     struct buffer_head *fe_bh,
1050                                     struct buffer_head *bg_bh,
1051                                     struct buffer_head *prev_bg_bh,
1052                                     u16 chain)
1053 {
1054         int status;
1055         /* there is a really tiny chance the journal calls could fail,
1056          * but we wouldn't want inconsistent blocks in *any* case. */
1057         u64 fe_ptr, bg_ptr, prev_bg_ptr;
1058         struct ocfs2_dinode *fe = (struct ocfs2_dinode *) fe_bh->b_data;
1059         struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
1060         struct ocfs2_group_desc *prev_bg = (struct ocfs2_group_desc *) prev_bg_bh->b_data;
1061
1062         /* The caller got these descriptors from
1063          * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
1064         BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
1065         BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(prev_bg));
1066
1067         mlog(0, "Suballoc %llu, chain %u, move group %llu to top, prev = %llu\n",
1068              (unsigned long long)le64_to_cpu(fe->i_blkno), chain,
1069              (unsigned long long)le64_to_cpu(bg->bg_blkno),
1070              (unsigned long long)le64_to_cpu(prev_bg->bg_blkno));
1071
1072         fe_ptr = le64_to_cpu(fe->id2.i_chain.cl_recs[chain].c_blkno);
1073         bg_ptr = le64_to_cpu(bg->bg_next_group);
1074         prev_bg_ptr = le64_to_cpu(prev_bg->bg_next_group);
1075
1076         status = ocfs2_journal_access_gd(handle, alloc_inode, prev_bg_bh,
1077                                          OCFS2_JOURNAL_ACCESS_WRITE);
1078         if (status < 0) {
1079                 mlog_errno(status);
1080                 goto out_rollback;
1081         }
1082
1083         prev_bg->bg_next_group = bg->bg_next_group;
1084
1085         status = ocfs2_journal_dirty(handle, prev_bg_bh);
1086         if (status < 0) {
1087                 mlog_errno(status);
1088                 goto out_rollback;
1089         }
1090
1091         status = ocfs2_journal_access_gd(handle, alloc_inode, bg_bh,
1092                                          OCFS2_JOURNAL_ACCESS_WRITE);
1093         if (status < 0) {
1094                 mlog_errno(status);
1095                 goto out_rollback;
1096         }
1097
1098         bg->bg_next_group = fe->id2.i_chain.cl_recs[chain].c_blkno;
1099
1100         status = ocfs2_journal_dirty(handle, bg_bh);
1101         if (status < 0) {
1102                 mlog_errno(status);
1103                 goto out_rollback;
1104         }
1105
1106         status = ocfs2_journal_access_di(handle, alloc_inode, fe_bh,
1107                                          OCFS2_JOURNAL_ACCESS_WRITE);
1108         if (status < 0) {
1109                 mlog_errno(status);
1110                 goto out_rollback;
1111         }
1112
1113         fe->id2.i_chain.cl_recs[chain].c_blkno = bg->bg_blkno;
1114
1115         status = ocfs2_journal_dirty(handle, fe_bh);
1116         if (status < 0) {
1117                 mlog_errno(status);
1118                 goto out_rollback;
1119         }
1120
1121         status = 0;
1122 out_rollback:
1123         if (status < 0) {
1124                 fe->id2.i_chain.cl_recs[chain].c_blkno = cpu_to_le64(fe_ptr);
1125                 bg->bg_next_group = cpu_to_le64(bg_ptr);
1126                 prev_bg->bg_next_group = cpu_to_le64(prev_bg_ptr);
1127         }
1128
1129         mlog_exit(status);
1130         return status;
1131 }
1132
1133 static inline int ocfs2_block_group_reasonably_empty(struct ocfs2_group_desc *bg,
1134                                                      u32 wanted)
1135 {
1136         return le16_to_cpu(bg->bg_free_bits_count) > wanted;
1137 }
1138
1139 /* return 0 on success, -ENOSPC to keep searching and any other < 0
1140  * value on error. */
1141 static int ocfs2_cluster_group_search(struct inode *inode,
1142                                       struct buffer_head *group_bh,
1143                                       u32 bits_wanted, u32 min_bits,
1144                                       u64 max_block,
1145                                       u16 *bit_off, u16 *bits_found)
1146 {
1147         int search = -ENOSPC;
1148         int ret;
1149         u64 blkoff;
1150         struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *) group_bh->b_data;
1151         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1152         u16 tmp_off, tmp_found;
1153         unsigned int max_bits, gd_cluster_off;
1154
1155         BUG_ON(!ocfs2_is_cluster_bitmap(inode));
1156
1157         if (gd->bg_free_bits_count) {
1158                 max_bits = le16_to_cpu(gd->bg_bits);
1159
1160                 /* Tail groups in cluster bitmaps which aren't cpg
1161                  * aligned are prone to partial extention by a failed
1162                  * fs resize. If the file system resize never got to
1163                  * update the dinode cluster count, then we don't want
1164                  * to trust any clusters past it, regardless of what
1165                  * the group descriptor says. */
1166                 gd_cluster_off = ocfs2_blocks_to_clusters(inode->i_sb,
1167                                                           le64_to_cpu(gd->bg_blkno));
1168                 if ((gd_cluster_off + max_bits) >
1169                     OCFS2_I(inode)->ip_clusters) {
1170                         max_bits = OCFS2_I(inode)->ip_clusters - gd_cluster_off;
1171                         mlog(0, "Desc %llu, bg_bits %u, clusters %u, use %u\n",
1172                              (unsigned long long)le64_to_cpu(gd->bg_blkno),
1173                              le16_to_cpu(gd->bg_bits),
1174                              OCFS2_I(inode)->ip_clusters, max_bits);
1175                 }
1176
1177                 ret = ocfs2_block_group_find_clear_bits(OCFS2_SB(inode->i_sb),
1178                                                         group_bh, bits_wanted,
1179                                                         max_bits,
1180                                                         &tmp_off, &tmp_found);
1181                 if (ret)
1182                         return ret;
1183
1184                 if (max_block) {
1185                         blkoff = ocfs2_clusters_to_blocks(inode->i_sb,
1186                                                           gd_cluster_off +
1187                                                           tmp_off + tmp_found);
1188                         mlog(0, "Checking %llu against %llu\n",
1189                              (unsigned long long)blkoff,
1190                              (unsigned long long)max_block);
1191                         if (blkoff > max_block)
1192                                 return -ENOSPC;
1193                 }
1194
1195                 /* ocfs2_block_group_find_clear_bits() might
1196                  * return success, but we still want to return
1197                  * -ENOSPC unless it found the minimum number
1198                  * of bits. */
1199                 if (min_bits <= tmp_found) {
1200                         *bit_off = tmp_off;
1201                         *bits_found = tmp_found;
1202                         search = 0; /* success */
1203                 } else if (tmp_found) {
1204                         /*
1205                          * Don't show bits which we'll be returning
1206                          * for allocation to the local alloc bitmap.
1207                          */
1208                         ocfs2_local_alloc_seen_free_bits(osb, tmp_found);
1209                 }
1210         }
1211
1212         return search;
1213 }
1214
1215 static int ocfs2_block_group_search(struct inode *inode,
1216                                     struct buffer_head *group_bh,
1217                                     u32 bits_wanted, u32 min_bits,
1218                                     u64 max_block,
1219                                     u16 *bit_off, u16 *bits_found)
1220 {
1221         int ret = -ENOSPC;
1222         u64 blkoff;
1223         struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) group_bh->b_data;
1224
1225         BUG_ON(min_bits != 1);
1226         BUG_ON(ocfs2_is_cluster_bitmap(inode));
1227
1228         if (bg->bg_free_bits_count) {
1229                 ret = ocfs2_block_group_find_clear_bits(OCFS2_SB(inode->i_sb),
1230                                                         group_bh, bits_wanted,
1231                                                         le16_to_cpu(bg->bg_bits),
1232                                                         bit_off, bits_found);
1233                 if (!ret && max_block) {
1234                         blkoff = le64_to_cpu(bg->bg_blkno) + *bit_off +
1235                                 *bits_found;
1236                         mlog(0, "Checking %llu against %llu\n",
1237                              (unsigned long long)blkoff,
1238                              (unsigned long long)max_block);
1239                         if (blkoff > max_block)
1240                                 ret = -ENOSPC;
1241                 }
1242         }
1243
1244         return ret;
1245 }
1246
1247 static int ocfs2_alloc_dinode_update_counts(struct inode *inode,
1248                                        handle_t *handle,
1249                                        struct buffer_head *di_bh,
1250                                        u32 num_bits,
1251                                        u16 chain)
1252 {
1253         int ret;
1254         u32 tmp_used;
1255         struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
1256         struct ocfs2_chain_list *cl = (struct ocfs2_chain_list *) &di->id2.i_chain;
1257
1258         ret = ocfs2_journal_access_di(handle, inode, di_bh,
1259                                       OCFS2_JOURNAL_ACCESS_WRITE);
1260         if (ret < 0) {
1261                 mlog_errno(ret);
1262                 goto out;
1263         }
1264
1265         tmp_used = le32_to_cpu(di->id1.bitmap1.i_used);
1266         di->id1.bitmap1.i_used = cpu_to_le32(num_bits + tmp_used);
1267         le32_add_cpu(&cl->cl_recs[chain].c_free, -num_bits);
1268
1269         ret = ocfs2_journal_dirty(handle, di_bh);
1270         if (ret < 0)
1271                 mlog_errno(ret);
1272
1273 out:
1274         return ret;
1275 }
1276
1277 static int ocfs2_search_one_group(struct ocfs2_alloc_context *ac,
1278                                   handle_t *handle,
1279                                   u32 bits_wanted,
1280                                   u32 min_bits,
1281                                   u16 *bit_off,
1282                                   unsigned int *num_bits,
1283                                   u64 gd_blkno,
1284                                   u16 *bits_left)
1285 {
1286         int ret;
1287         u16 found;
1288         struct buffer_head *group_bh = NULL;
1289         struct ocfs2_group_desc *gd;
1290         struct ocfs2_dinode *di = (struct ocfs2_dinode *)ac->ac_bh->b_data;
1291         struct inode *alloc_inode = ac->ac_inode;
1292
1293         ret = ocfs2_read_group_descriptor(alloc_inode, di, gd_blkno,
1294                                           &group_bh);
1295         if (ret < 0) {
1296                 mlog_errno(ret);
1297                 return ret;
1298         }
1299
1300         gd = (struct ocfs2_group_desc *) group_bh->b_data;
1301         ret = ac->ac_group_search(alloc_inode, group_bh, bits_wanted, min_bits,
1302                                   ac->ac_max_block, bit_off, &found);
1303         if (ret < 0) {
1304                 if (ret != -ENOSPC)
1305                         mlog_errno(ret);
1306                 goto out;
1307         }
1308
1309         *num_bits = found;
1310
1311         ret = ocfs2_alloc_dinode_update_counts(alloc_inode, handle, ac->ac_bh,
1312                                                *num_bits,
1313                                                le16_to_cpu(gd->bg_chain));
1314         if (ret < 0) {
1315                 mlog_errno(ret);
1316                 goto out;
1317         }
1318
1319         ret = ocfs2_block_group_set_bits(handle, alloc_inode, gd, group_bh,
1320                                          *bit_off, *num_bits);
1321         if (ret < 0)
1322                 mlog_errno(ret);
1323
1324         *bits_left = le16_to_cpu(gd->bg_free_bits_count);
1325
1326 out:
1327         brelse(group_bh);
1328
1329         return ret;
1330 }
1331
1332 static int ocfs2_search_chain(struct ocfs2_alloc_context *ac,
1333                               handle_t *handle,
1334                               u32 bits_wanted,
1335                               u32 min_bits,
1336                               u16 *bit_off,
1337                               unsigned int *num_bits,
1338                               u64 *bg_blkno,
1339                               u16 *bits_left)
1340 {
1341         int status;
1342         u16 chain, tmp_bits;
1343         u32 tmp_used;
1344         u64 next_group;
1345         struct inode *alloc_inode = ac->ac_inode;
1346         struct buffer_head *group_bh = NULL;
1347         struct buffer_head *prev_group_bh = NULL;
1348         struct ocfs2_dinode *fe = (struct ocfs2_dinode *) ac->ac_bh->b_data;
1349         struct ocfs2_chain_list *cl = (struct ocfs2_chain_list *) &fe->id2.i_chain;
1350         struct ocfs2_group_desc *bg;
1351
1352         chain = ac->ac_chain;
1353         mlog(0, "trying to alloc %u bits from chain %u, inode %llu\n",
1354              bits_wanted, chain,
1355              (unsigned long long)OCFS2_I(alloc_inode)->ip_blkno);
1356
1357         status = ocfs2_read_group_descriptor(alloc_inode, fe,
1358                                              le64_to_cpu(cl->cl_recs[chain].c_blkno),
1359                                              &group_bh);
1360         if (status < 0) {
1361                 mlog_errno(status);
1362                 goto bail;
1363         }
1364         bg = (struct ocfs2_group_desc *) group_bh->b_data;
1365
1366         status = -ENOSPC;
1367         /* for now, the chain search is a bit simplistic. We just use
1368          * the 1st group with any empty bits. */
1369         while ((status = ac->ac_group_search(alloc_inode, group_bh,
1370                                              bits_wanted, min_bits,
1371                                              ac->ac_max_block, bit_off,
1372                                              &tmp_bits)) == -ENOSPC) {
1373                 if (!bg->bg_next_group)
1374                         break;
1375
1376                 brelse(prev_group_bh);
1377                 prev_group_bh = NULL;
1378
1379                 next_group = le64_to_cpu(bg->bg_next_group);
1380                 prev_group_bh = group_bh;
1381                 group_bh = NULL;
1382                 status = ocfs2_read_group_descriptor(alloc_inode, fe,
1383                                                      next_group, &group_bh);
1384                 if (status < 0) {
1385                         mlog_errno(status);
1386                         goto bail;
1387                 }
1388                 bg = (struct ocfs2_group_desc *) group_bh->b_data;
1389         }
1390         if (status < 0) {
1391                 if (status != -ENOSPC)
1392                         mlog_errno(status);
1393                 goto bail;
1394         }
1395
1396         mlog(0, "alloc succeeds: we give %u bits from block group %llu\n",
1397              tmp_bits, (unsigned long long)le64_to_cpu(bg->bg_blkno));
1398
1399         *num_bits = tmp_bits;
1400
1401         BUG_ON(*num_bits == 0);
1402
1403         /*
1404          * Keep track of previous block descriptor read. When
1405          * we find a target, if we have read more than X
1406          * number of descriptors, and the target is reasonably
1407          * empty, relink him to top of his chain.
1408          *
1409          * We've read 0 extra blocks and only send one more to
1410          * the transaction, yet the next guy to search has a
1411          * much easier time.
1412          *
1413          * Do this *after* figuring out how many bits we're taking out
1414          * of our target group.
1415          */
1416         if (ac->ac_allow_chain_relink &&
1417             (prev_group_bh) &&
1418             (ocfs2_block_group_reasonably_empty(bg, *num_bits))) {
1419                 status = ocfs2_relink_block_group(handle, alloc_inode,
1420                                                   ac->ac_bh, group_bh,
1421                                                   prev_group_bh, chain);
1422                 if (status < 0) {
1423                         mlog_errno(status);
1424                         goto bail;
1425                 }
1426         }
1427
1428         /* Ok, claim our bits now: set the info on dinode, chainlist
1429          * and then the group */
1430         status = ocfs2_journal_access_di(handle,
1431                                          alloc_inode,
1432                                          ac->ac_bh,
1433                                          OCFS2_JOURNAL_ACCESS_WRITE);
1434         if (status < 0) {
1435                 mlog_errno(status);
1436                 goto bail;
1437         }
1438
1439         tmp_used = le32_to_cpu(fe->id1.bitmap1.i_used);
1440         fe->id1.bitmap1.i_used = cpu_to_le32(*num_bits + tmp_used);
1441         le32_add_cpu(&cl->cl_recs[chain].c_free, -(*num_bits));
1442
1443         status = ocfs2_journal_dirty(handle,
1444                                      ac->ac_bh);
1445         if (status < 0) {
1446                 mlog_errno(status);
1447                 goto bail;
1448         }
1449
1450         status = ocfs2_block_group_set_bits(handle,
1451                                             alloc_inode,
1452                                             bg,
1453                                             group_bh,
1454                                             *bit_off,
1455                                             *num_bits);
1456         if (status < 0) {
1457                 mlog_errno(status);
1458                 goto bail;
1459         }
1460
1461         mlog(0, "Allocated %u bits from suballocator %llu\n", *num_bits,
1462              (unsigned long long)le64_to_cpu(fe->i_blkno));
1463
1464         *bg_blkno = le64_to_cpu(bg->bg_blkno);
1465         *bits_left = le16_to_cpu(bg->bg_free_bits_count);
1466 bail:
1467         brelse(group_bh);
1468         brelse(prev_group_bh);
1469
1470         mlog_exit(status);
1471         return status;
1472 }
1473
1474 /* will give out up to bits_wanted contiguous bits. */
1475 static int ocfs2_claim_suballoc_bits(struct ocfs2_super *osb,
1476                                      struct ocfs2_alloc_context *ac,
1477                                      handle_t *handle,
1478                                      u32 bits_wanted,
1479                                      u32 min_bits,
1480                                      u16 *bit_off,
1481                                      unsigned int *num_bits,
1482                                      u64 *bg_blkno)
1483 {
1484         int status;
1485         u16 victim, i;
1486         u16 bits_left = 0;
1487         u64 hint_blkno = ac->ac_last_group;
1488         struct ocfs2_chain_list *cl;
1489         struct ocfs2_dinode *fe;
1490
1491         mlog_entry_void();
1492
1493         BUG_ON(ac->ac_bits_given >= ac->ac_bits_wanted);
1494         BUG_ON(bits_wanted > (ac->ac_bits_wanted - ac->ac_bits_given));
1495         BUG_ON(!ac->ac_bh);
1496
1497         fe = (struct ocfs2_dinode *) ac->ac_bh->b_data;
1498
1499         /* The bh was validated by the inode read during
1500          * ocfs2_reserve_suballoc_bits().  Any corruption is a code bug. */
1501         BUG_ON(!OCFS2_IS_VALID_DINODE(fe));
1502
1503         if (le32_to_cpu(fe->id1.bitmap1.i_used) >=
1504             le32_to_cpu(fe->id1.bitmap1.i_total)) {
1505                 ocfs2_error(osb->sb, "Chain allocator dinode %llu has %u used "
1506                             "bits but only %u total.",
1507                             (unsigned long long)le64_to_cpu(fe->i_blkno),
1508                             le32_to_cpu(fe->id1.bitmap1.i_used),
1509                             le32_to_cpu(fe->id1.bitmap1.i_total));
1510                 status = -EIO;
1511                 goto bail;
1512         }
1513
1514         if (hint_blkno) {
1515                 /* Attempt to short-circuit the usual search mechanism
1516                  * by jumping straight to the most recently used
1517                  * allocation group. This helps us mantain some
1518                  * contiguousness across allocations. */
1519                 status = ocfs2_search_one_group(ac, handle, bits_wanted,
1520                                                 min_bits, bit_off, num_bits,
1521                                                 hint_blkno, &bits_left);
1522                 if (!status) {
1523                         /* Be careful to update *bg_blkno here as the
1524                          * caller is expecting it to be filled in, and
1525                          * ocfs2_search_one_group() won't do that for
1526                          * us. */
1527                         *bg_blkno = hint_blkno;
1528                         goto set_hint;
1529                 }
1530                 if (status < 0 && status != -ENOSPC) {
1531                         mlog_errno(status);
1532                         goto bail;
1533                 }
1534         }
1535
1536         cl = (struct ocfs2_chain_list *) &fe->id2.i_chain;
1537
1538         victim = ocfs2_find_victim_chain(cl);
1539         ac->ac_chain = victim;
1540         ac->ac_allow_chain_relink = 1;
1541
1542         status = ocfs2_search_chain(ac, handle, bits_wanted, min_bits, bit_off,
1543                                     num_bits, bg_blkno, &bits_left);
1544         if (!status)
1545                 goto set_hint;
1546         if (status < 0 && status != -ENOSPC) {
1547                 mlog_errno(status);
1548                 goto bail;
1549         }
1550
1551         mlog(0, "Search of victim chain %u came up with nothing, "
1552              "trying all chains now.\n", victim);
1553
1554         /* If we didn't pick a good victim, then just default to
1555          * searching each chain in order. Don't allow chain relinking
1556          * because we only calculate enough journal credits for one
1557          * relink per alloc. */
1558         ac->ac_allow_chain_relink = 0;
1559         for (i = 0; i < le16_to_cpu(cl->cl_next_free_rec); i ++) {
1560                 if (i == victim)
1561                         continue;
1562                 if (!cl->cl_recs[i].c_free)
1563                         continue;
1564
1565                 ac->ac_chain = i;
1566                 status = ocfs2_search_chain(ac, handle, bits_wanted, min_bits,
1567                                             bit_off, num_bits, bg_blkno,
1568                                             &bits_left);
1569                 if (!status)
1570                         break;
1571                 if (status < 0 && status != -ENOSPC) {
1572                         mlog_errno(status);
1573                         goto bail;
1574                 }
1575         }
1576
1577 set_hint:
1578         if (status != -ENOSPC) {
1579                 /* If the next search of this group is not likely to
1580                  * yield a suitable extent, then we reset the last
1581                  * group hint so as to not waste a disk read */
1582                 if (bits_left < min_bits)
1583                         ac->ac_last_group = 0;
1584                 else
1585                         ac->ac_last_group = *bg_blkno;
1586         }
1587
1588 bail:
1589         mlog_exit(status);
1590         return status;
1591 }
1592
1593 int ocfs2_claim_metadata(struct ocfs2_super *osb,
1594                          handle_t *handle,
1595                          struct ocfs2_alloc_context *ac,
1596                          u32 bits_wanted,
1597                          u16 *suballoc_bit_start,
1598                          unsigned int *num_bits,
1599                          u64 *blkno_start)
1600 {
1601         int status;
1602         u64 bg_blkno;
1603
1604         BUG_ON(!ac);
1605         BUG_ON(ac->ac_bits_wanted < (ac->ac_bits_given + bits_wanted));
1606         BUG_ON(ac->ac_which != OCFS2_AC_USE_META);
1607
1608         status = ocfs2_claim_suballoc_bits(osb,
1609                                            ac,
1610                                            handle,
1611                                            bits_wanted,
1612                                            1,
1613                                            suballoc_bit_start,
1614                                            num_bits,
1615                                            &bg_blkno);
1616         if (status < 0) {
1617                 mlog_errno(status);
1618                 goto bail;
1619         }
1620         atomic_inc(&osb->alloc_stats.bg_allocs);
1621
1622         *blkno_start = bg_blkno + (u64) *suballoc_bit_start;
1623         ac->ac_bits_given += (*num_bits);
1624         status = 0;
1625 bail:
1626         mlog_exit(status);
1627         return status;
1628 }
1629
1630 static void ocfs2_init_inode_ac_group(struct inode *dir,
1631                                       struct buffer_head *parent_fe_bh,
1632                                       struct ocfs2_alloc_context *ac)
1633 {
1634         struct ocfs2_dinode *fe = (struct ocfs2_dinode *)parent_fe_bh->b_data;
1635         /*
1636          * Try to allocate inodes from some specific group.
1637          *
1638          * If the parent dir has recorded the last group used in allocation,
1639          * cool, use it. Otherwise if we try to allocate new inode from the
1640          * same slot the parent dir belongs to, use the same chunk.
1641          *
1642          * We are very careful here to avoid the mistake of setting
1643          * ac_last_group to a group descriptor from a different (unlocked) slot.
1644          */
1645         if (OCFS2_I(dir)->ip_last_used_group &&
1646             OCFS2_I(dir)->ip_last_used_slot == ac->ac_alloc_slot)
1647                 ac->ac_last_group = OCFS2_I(dir)->ip_last_used_group;
1648         else if (le16_to_cpu(fe->i_suballoc_slot) == ac->ac_alloc_slot)
1649                 ac->ac_last_group = ocfs2_which_suballoc_group(
1650                                         le64_to_cpu(fe->i_blkno),
1651                                         le16_to_cpu(fe->i_suballoc_bit));
1652 }
1653
1654 static inline void ocfs2_save_inode_ac_group(struct inode *dir,
1655                                              struct ocfs2_alloc_context *ac)
1656 {
1657         OCFS2_I(dir)->ip_last_used_group = ac->ac_last_group;
1658         OCFS2_I(dir)->ip_last_used_slot = ac->ac_alloc_slot;
1659 }
1660
1661 int ocfs2_claim_new_inode(struct ocfs2_super *osb,
1662                           handle_t *handle,
1663                           struct inode *dir,
1664                           struct buffer_head *parent_fe_bh,
1665                           struct ocfs2_alloc_context *ac,
1666                           u16 *suballoc_bit,
1667                           u64 *fe_blkno)
1668 {
1669         int status;
1670         unsigned int num_bits;
1671         u64 bg_blkno;
1672
1673         mlog_entry_void();
1674
1675         BUG_ON(!ac);
1676         BUG_ON(ac->ac_bits_given != 0);
1677         BUG_ON(ac->ac_bits_wanted != 1);
1678         BUG_ON(ac->ac_which != OCFS2_AC_USE_INODE);
1679
1680         ocfs2_init_inode_ac_group(dir, parent_fe_bh, ac);
1681
1682         status = ocfs2_claim_suballoc_bits(osb,
1683                                            ac,
1684                                            handle,
1685                                            1,
1686                                            1,
1687                                            suballoc_bit,
1688                                            &num_bits,
1689                                            &bg_blkno);
1690         if (status < 0) {
1691                 mlog_errno(status);
1692                 goto bail;
1693         }
1694         atomic_inc(&osb->alloc_stats.bg_allocs);
1695
1696         BUG_ON(num_bits != 1);
1697
1698         *fe_blkno = bg_blkno + (u64) (*suballoc_bit);
1699         ac->ac_bits_given++;
1700         ocfs2_save_inode_ac_group(dir, ac);
1701         status = 0;
1702 bail:
1703         mlog_exit(status);
1704         return status;
1705 }
1706
1707 /* translate a group desc. blkno and it's bitmap offset into
1708  * disk cluster offset. */
1709 static inline u32 ocfs2_desc_bitmap_to_cluster_off(struct inode *inode,
1710                                                    u64 bg_blkno,
1711                                                    u16 bg_bit_off)
1712 {
1713         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1714         u32 cluster = 0;
1715
1716         BUG_ON(!ocfs2_is_cluster_bitmap(inode));
1717
1718         if (bg_blkno != osb->first_cluster_group_blkno)
1719                 cluster = ocfs2_blocks_to_clusters(inode->i_sb, bg_blkno);
1720         cluster += (u32) bg_bit_off;
1721         return cluster;
1722 }
1723
1724 /* given a cluster offset, calculate which block group it belongs to
1725  * and return that block offset. */
1726 u64 ocfs2_which_cluster_group(struct inode *inode, u32 cluster)
1727 {
1728         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1729         u32 group_no;
1730
1731         BUG_ON(!ocfs2_is_cluster_bitmap(inode));
1732
1733         group_no = cluster / osb->bitmap_cpg;
1734         if (!group_no)
1735                 return osb->first_cluster_group_blkno;
1736         return ocfs2_clusters_to_blocks(inode->i_sb,
1737                                         group_no * osb->bitmap_cpg);
1738 }
1739
1740 /* given the block number of a cluster start, calculate which cluster
1741  * group and descriptor bitmap offset that corresponds to. */
1742 static inline void ocfs2_block_to_cluster_group(struct inode *inode,
1743                                                 u64 data_blkno,
1744                                                 u64 *bg_blkno,
1745                                                 u16 *bg_bit_off)
1746 {
1747         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1748         u32 data_cluster = ocfs2_blocks_to_clusters(osb->sb, data_blkno);
1749
1750         BUG_ON(!ocfs2_is_cluster_bitmap(inode));
1751
1752         *bg_blkno = ocfs2_which_cluster_group(inode,
1753                                               data_cluster);
1754
1755         if (*bg_blkno == osb->first_cluster_group_blkno)
1756                 *bg_bit_off = (u16) data_cluster;
1757         else
1758                 *bg_bit_off = (u16) ocfs2_blocks_to_clusters(osb->sb,
1759                                                              data_blkno - *bg_blkno);
1760 }
1761
1762 /*
1763  * min_bits - minimum contiguous chunk from this total allocation we
1764  * can handle. set to what we asked for originally for a full
1765  * contig. allocation, set to '1' to indicate we can deal with extents
1766  * of any size.
1767  */
1768 int __ocfs2_claim_clusters(struct ocfs2_super *osb,
1769                            handle_t *handle,
1770                            struct ocfs2_alloc_context *ac,
1771                            u32 min_clusters,
1772                            u32 max_clusters,
1773                            u32 *cluster_start,
1774                            u32 *num_clusters)
1775 {
1776         int status;
1777         unsigned int bits_wanted = max_clusters;
1778         u64 bg_blkno = 0;
1779         u16 bg_bit_off;
1780
1781         mlog_entry_void();
1782
1783         BUG_ON(ac->ac_bits_given >= ac->ac_bits_wanted);
1784
1785         BUG_ON(ac->ac_which != OCFS2_AC_USE_LOCAL
1786                && ac->ac_which != OCFS2_AC_USE_MAIN);
1787
1788         if (ac->ac_which == OCFS2_AC_USE_LOCAL) {
1789                 status = ocfs2_claim_local_alloc_bits(osb,
1790                                                       handle,
1791                                                       ac,
1792                                                       bits_wanted,
1793                                                       cluster_start,
1794                                                       num_clusters);
1795                 if (!status)
1796                         atomic_inc(&osb->alloc_stats.local_data);
1797         } else {
1798                 if (min_clusters > (osb->bitmap_cpg - 1)) {
1799                         /* The only paths asking for contiguousness
1800                          * should know about this already. */
1801                         mlog(ML_ERROR, "minimum allocation requested %u exceeds "
1802                              "group bitmap size %u!\n", min_clusters,
1803                              osb->bitmap_cpg);
1804                         status = -ENOSPC;
1805                         goto bail;
1806                 }
1807                 /* clamp the current request down to a realistic size. */
1808                 if (bits_wanted > (osb->bitmap_cpg - 1))
1809                         bits_wanted = osb->bitmap_cpg - 1;
1810
1811                 status = ocfs2_claim_suballoc_bits(osb,
1812                                                    ac,
1813                                                    handle,
1814                                                    bits_wanted,
1815                                                    min_clusters,
1816                                                    &bg_bit_off,
1817                                                    num_clusters,
1818                                                    &bg_blkno);
1819                 if (!status) {
1820                         *cluster_start =
1821                                 ocfs2_desc_bitmap_to_cluster_off(ac->ac_inode,
1822                                                                  bg_blkno,
1823                                                                  bg_bit_off);
1824                         atomic_inc(&osb->alloc_stats.bitmap_data);
1825                 }
1826         }
1827         if (status < 0) {
1828                 if (status != -ENOSPC)
1829                         mlog_errno(status);
1830                 goto bail;
1831         }
1832
1833         ac->ac_bits_given += *num_clusters;
1834
1835 bail:
1836         mlog_exit(status);
1837         return status;
1838 }
1839
1840 int ocfs2_claim_clusters(struct ocfs2_super *osb,
1841                          handle_t *handle,
1842                          struct ocfs2_alloc_context *ac,
1843                          u32 min_clusters,
1844                          u32 *cluster_start,
1845                          u32 *num_clusters)
1846 {
1847         unsigned int bits_wanted = ac->ac_bits_wanted - ac->ac_bits_given;
1848
1849         return __ocfs2_claim_clusters(osb, handle, ac, min_clusters,
1850                                       bits_wanted, cluster_start, num_clusters);
1851 }
1852
1853 static inline int ocfs2_block_group_clear_bits(handle_t *handle,
1854                                                struct inode *alloc_inode,
1855                                                struct ocfs2_group_desc *bg,
1856                                                struct buffer_head *group_bh,
1857                                                unsigned int bit_off,
1858                                                unsigned int num_bits)
1859 {
1860         int status;
1861         unsigned int tmp;
1862         int journal_type = OCFS2_JOURNAL_ACCESS_WRITE;
1863         struct ocfs2_group_desc *undo_bg = NULL;
1864
1865         mlog_entry_void();
1866
1867         /* The caller got this descriptor from
1868          * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
1869         BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
1870
1871         mlog(0, "off = %u, num = %u\n", bit_off, num_bits);
1872
1873         if (ocfs2_is_cluster_bitmap(alloc_inode))
1874                 journal_type = OCFS2_JOURNAL_ACCESS_UNDO;
1875
1876         status = ocfs2_journal_access_gd(handle, alloc_inode, group_bh,
1877                                          journal_type);
1878         if (status < 0) {
1879                 mlog_errno(status);
1880                 goto bail;
1881         }
1882
1883         if (ocfs2_is_cluster_bitmap(alloc_inode))
1884                 undo_bg = (struct ocfs2_group_desc *) bh2jh(group_bh)->b_committed_data;
1885
1886         tmp = num_bits;
1887         while(tmp--) {
1888                 ocfs2_clear_bit((bit_off + tmp),
1889                                 (unsigned long *) bg->bg_bitmap);
1890                 if (ocfs2_is_cluster_bitmap(alloc_inode))
1891                         ocfs2_set_bit(bit_off + tmp,
1892                                       (unsigned long *) undo_bg->bg_bitmap);
1893         }
1894         le16_add_cpu(&bg->bg_free_bits_count, num_bits);
1895
1896         status = ocfs2_journal_dirty(handle, group_bh);
1897         if (status < 0)
1898                 mlog_errno(status);
1899 bail:
1900         return status;
1901 }
1902
1903 /*
1904  * expects the suballoc inode to already be locked.
1905  */
1906 int ocfs2_free_suballoc_bits(handle_t *handle,
1907                              struct inode *alloc_inode,
1908                              struct buffer_head *alloc_bh,
1909                              unsigned int start_bit,
1910                              u64 bg_blkno,
1911                              unsigned int count)
1912 {
1913         int status = 0;
1914         u32 tmp_used;
1915         struct ocfs2_dinode *fe = (struct ocfs2_dinode *) alloc_bh->b_data;
1916         struct ocfs2_chain_list *cl = &fe->id2.i_chain;
1917         struct buffer_head *group_bh = NULL;
1918         struct ocfs2_group_desc *group;
1919
1920         mlog_entry_void();
1921
1922         /* The alloc_bh comes from ocfs2_free_dinode() or
1923          * ocfs2_free_clusters().  The callers have all locked the
1924          * allocator and gotten alloc_bh from the lock call.  This
1925          * validates the dinode buffer.  Any corruption that has happended
1926          * is a code bug. */
1927         BUG_ON(!OCFS2_IS_VALID_DINODE(fe));
1928         BUG_ON((count + start_bit) > ocfs2_bits_per_group(cl));
1929
1930         mlog(0, "%llu: freeing %u bits from group %llu, starting at %u\n",
1931              (unsigned long long)OCFS2_I(alloc_inode)->ip_blkno, count,
1932              (unsigned long long)bg_blkno, start_bit);
1933
1934         status = ocfs2_read_group_descriptor(alloc_inode, fe, bg_blkno,
1935                                              &group_bh);
1936         if (status < 0) {
1937                 mlog_errno(status);
1938                 goto bail;
1939         }
1940         group = (struct ocfs2_group_desc *) group_bh->b_data;
1941
1942         BUG_ON((count + start_bit) > le16_to_cpu(group->bg_bits));
1943
1944         status = ocfs2_block_group_clear_bits(handle, alloc_inode,
1945                                               group, group_bh,
1946                                               start_bit, count);
1947         if (status < 0) {
1948                 mlog_errno(status);
1949                 goto bail;
1950         }
1951
1952         status = ocfs2_journal_access_di(handle, alloc_inode, alloc_bh,
1953                                          OCFS2_JOURNAL_ACCESS_WRITE);
1954         if (status < 0) {
1955                 mlog_errno(status);
1956                 goto bail;
1957         }
1958
1959         le32_add_cpu(&cl->cl_recs[le16_to_cpu(group->bg_chain)].c_free,
1960                      count);
1961         tmp_used = le32_to_cpu(fe->id1.bitmap1.i_used);
1962         fe->id1.bitmap1.i_used = cpu_to_le32(tmp_used - count);
1963
1964         status = ocfs2_journal_dirty(handle, alloc_bh);
1965         if (status < 0) {
1966                 mlog_errno(status);
1967                 goto bail;
1968         }
1969
1970 bail:
1971         brelse(group_bh);
1972
1973         mlog_exit(status);
1974         return status;
1975 }
1976
1977 int ocfs2_free_dinode(handle_t *handle,
1978                       struct inode *inode_alloc_inode,
1979                       struct buffer_head *inode_alloc_bh,
1980                       struct ocfs2_dinode *di)
1981 {
1982         u64 blk = le64_to_cpu(di->i_blkno);
1983         u16 bit = le16_to_cpu(di->i_suballoc_bit);
1984         u64 bg_blkno = ocfs2_which_suballoc_group(blk, bit);
1985
1986         return ocfs2_free_suballoc_bits(handle, inode_alloc_inode,
1987                                         inode_alloc_bh, bit, bg_blkno, 1);
1988 }
1989
1990 int ocfs2_free_clusters(handle_t *handle,
1991                        struct inode *bitmap_inode,
1992                        struct buffer_head *bitmap_bh,
1993                        u64 start_blk,
1994                        unsigned int num_clusters)
1995 {
1996         int status;
1997         u16 bg_start_bit;
1998         u64 bg_blkno;
1999         struct ocfs2_dinode *fe;
2000
2001         /* You can't ever have a contiguous set of clusters
2002          * bigger than a block group bitmap so we never have to worry
2003          * about looping on them. */
2004
2005         mlog_entry_void();
2006
2007         /* This is expensive. We can safely remove once this stuff has
2008          * gotten tested really well. */
2009         BUG_ON(start_blk != ocfs2_clusters_to_blocks(bitmap_inode->i_sb, ocfs2_blocks_to_clusters(bitmap_inode->i_sb, start_blk)));
2010
2011         fe = (struct ocfs2_dinode *) bitmap_bh->b_data;
2012
2013         ocfs2_block_to_cluster_group(bitmap_inode, start_blk, &bg_blkno,
2014                                      &bg_start_bit);
2015
2016         mlog(0, "want to free %u clusters starting at block %llu\n",
2017              num_clusters, (unsigned long long)start_blk);
2018         mlog(0, "bg_blkno = %llu, bg_start_bit = %u\n",
2019              (unsigned long long)bg_blkno, bg_start_bit);
2020
2021         status = ocfs2_free_suballoc_bits(handle, bitmap_inode, bitmap_bh,
2022                                           bg_start_bit, bg_blkno,
2023                                           num_clusters);
2024         if (status < 0) {
2025                 mlog_errno(status);
2026                 goto out;
2027         }
2028
2029         ocfs2_local_alloc_seen_free_bits(OCFS2_SB(bitmap_inode->i_sb),
2030                                          num_clusters);
2031
2032 out:
2033         mlog_exit(status);
2034         return status;
2035 }
2036
2037 static inline void ocfs2_debug_bg(struct ocfs2_group_desc *bg)
2038 {
2039         printk("Block Group:\n");
2040         printk("bg_signature:       %s\n", bg->bg_signature);
2041         printk("bg_size:            %u\n", bg->bg_size);
2042         printk("bg_bits:            %u\n", bg->bg_bits);
2043         printk("bg_free_bits_count: %u\n", bg->bg_free_bits_count);
2044         printk("bg_chain:           %u\n", bg->bg_chain);
2045         printk("bg_generation:      %u\n", le32_to_cpu(bg->bg_generation));
2046         printk("bg_next_group:      %llu\n",
2047                (unsigned long long)bg->bg_next_group);
2048         printk("bg_parent_dinode:   %llu\n",
2049                (unsigned long long)bg->bg_parent_dinode);
2050         printk("bg_blkno:           %llu\n",
2051                (unsigned long long)bg->bg_blkno);
2052 }
2053
2054 static inline void ocfs2_debug_suballoc_inode(struct ocfs2_dinode *fe)
2055 {
2056         int i;
2057
2058         printk("Suballoc Inode %llu:\n", (unsigned long long)fe->i_blkno);
2059         printk("i_signature:                  %s\n", fe->i_signature);
2060         printk("i_size:                       %llu\n",
2061                (unsigned long long)fe->i_size);
2062         printk("i_clusters:                   %u\n", fe->i_clusters);
2063         printk("i_generation:                 %u\n",
2064                le32_to_cpu(fe->i_generation));
2065         printk("id1.bitmap1.i_used:           %u\n",
2066                le32_to_cpu(fe->id1.bitmap1.i_used));
2067         printk("id1.bitmap1.i_total:          %u\n",
2068                le32_to_cpu(fe->id1.bitmap1.i_total));
2069         printk("id2.i_chain.cl_cpg:           %u\n", fe->id2.i_chain.cl_cpg);
2070         printk("id2.i_chain.cl_bpc:           %u\n", fe->id2.i_chain.cl_bpc);
2071         printk("id2.i_chain.cl_count:         %u\n", fe->id2.i_chain.cl_count);
2072         printk("id2.i_chain.cl_next_free_rec: %u\n",
2073                fe->id2.i_chain.cl_next_free_rec);
2074         for(i = 0; i < fe->id2.i_chain.cl_next_free_rec; i++) {
2075                 printk("fe->id2.i_chain.cl_recs[%d].c_free:  %u\n", i,
2076                        fe->id2.i_chain.cl_recs[i].c_free);
2077                 printk("fe->id2.i_chain.cl_recs[%d].c_total: %u\n", i,
2078                        fe->id2.i_chain.cl_recs[i].c_total);
2079                 printk("fe->id2.i_chain.cl_recs[%d].c_blkno: %llu\n", i,
2080                        (unsigned long long)fe->id2.i_chain.cl_recs[i].c_blkno);
2081         }
2082 }
2083
2084 /*
2085  * For a given allocation, determine which allocators will need to be
2086  * accessed, and lock them, reserving the appropriate number of bits.
2087  *
2088  * Sparse file systems call this from ocfs2_write_begin_nolock()
2089  * and ocfs2_allocate_unwritten_extents().
2090  *
2091  * File systems which don't support holes call this from
2092  * ocfs2_extend_allocation().
2093  */
2094 int ocfs2_lock_allocators(struct inode *inode,
2095                           struct ocfs2_extent_tree *et,
2096                           u32 clusters_to_add, u32 extents_to_split,
2097                           struct ocfs2_alloc_context **data_ac,
2098                           struct ocfs2_alloc_context **meta_ac)
2099 {
2100         int ret = 0, num_free_extents;
2101         unsigned int max_recs_needed = clusters_to_add + 2 * extents_to_split;
2102         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2103
2104         *meta_ac = NULL;
2105         if (data_ac)
2106                 *data_ac = NULL;
2107
2108         BUG_ON(clusters_to_add != 0 && data_ac == NULL);
2109
2110         num_free_extents = ocfs2_num_free_extents(osb, inode, et);
2111         if (num_free_extents < 0) {
2112                 ret = num_free_extents;
2113                 mlog_errno(ret);
2114                 goto out;
2115         }
2116
2117         /*
2118          * Sparse allocation file systems need to be more conservative
2119          * with reserving room for expansion - the actual allocation
2120          * happens while we've got a journal handle open so re-taking
2121          * a cluster lock (because we ran out of room for another
2122          * extent) will violate ordering rules.
2123          *
2124          * Most of the time we'll only be seeing this 1 cluster at a time
2125          * anyway.
2126          *
2127          * Always lock for any unwritten extents - we might want to
2128          * add blocks during a split.
2129          */
2130         if (!num_free_extents ||
2131             (ocfs2_sparse_alloc(osb) && num_free_extents < max_recs_needed)) {
2132                 ret = ocfs2_reserve_new_metadata(osb, et->et_root_el, meta_ac);
2133                 if (ret < 0) {
2134                         if (ret != -ENOSPC)
2135                                 mlog_errno(ret);
2136                         goto out;
2137                 }
2138         }
2139
2140         if (clusters_to_add == 0)
2141                 goto out;
2142
2143         ret = ocfs2_reserve_clusters(osb, clusters_to_add, data_ac);
2144         if (ret < 0) {
2145                 if (ret != -ENOSPC)
2146                         mlog_errno(ret);
2147                 goto out;
2148         }
2149
2150 out:
2151         if (ret) {
2152                 if (*meta_ac) {
2153                         ocfs2_free_alloc_context(*meta_ac);
2154                         *meta_ac = NULL;
2155                 }
2156
2157                 /*
2158                  * We cannot have an error and a non null *data_ac.
2159                  */
2160         }
2161
2162         return ret;
2163 }