This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / fs / ext3 / balloc.c
1 /*
2  *  linux/fs/ext3/balloc.c
3  *
4  * Copyright (C) 1992, 1993, 1994, 1995
5  * Remy Card (card@masi.ibp.fr)
6  * Laboratoire MASI - Institut Blaise Pascal
7  * Universite Pierre et Marie Curie (Paris VI)
8  *
9  *  Enhanced block allocation by Stephen Tweedie (sct@redhat.com), 1993
10  *  Big-endian to little-endian byte-swapping/bitmaps by
11  *        David S. Miller (davem@caip.rutgers.edu), 1995
12  */
13
14 #include <linux/config.h>
15 #include <linux/time.h>
16 #include <linux/fs.h>
17 #include <linux/jbd.h>
18 #include <linux/ext3_fs.h>
19 #include <linux/ext3_jbd.h>
20 #include <linux/quotaops.h>
21 #include <linux/buffer_head.h>
22 #include <linux/vs_base.h>
23 #include <linux/vs_dlimit.h>
24
25 /*
26  * balloc.c contains the blocks allocation and deallocation routines
27  */
28
29 /*
30  * The free blocks are managed by bitmaps.  A file system contains several
31  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
32  * block for inodes, N blocks for the inode table and data blocks.
33  *
34  * The file system contains group descriptors which are located after the
35  * super block.  Each descriptor contains the number of the bitmap block and
36  * the free blocks count in the block.  The descriptors are loaded in memory
37  * when a file system is mounted (see ext3_read_super).
38  */
39
40
41 #define in_range(b, first, len) ((b) >= (first) && (b) <= (first) + (len) - 1)
42
43 struct ext3_group_desc * ext3_get_group_desc(struct super_block * sb,
44                                              unsigned int block_group,
45                                              struct buffer_head ** bh)
46 {
47         unsigned long group_desc;
48         unsigned long desc;
49         struct ext3_group_desc * gdp;
50
51         if (block_group >= EXT3_SB(sb)->s_groups_count) {
52                 ext3_error (sb, "ext3_get_group_desc",
53                             "block_group >= groups_count - "
54                             "block_group = %d, groups_count = %lu",
55                             block_group, EXT3_SB(sb)->s_groups_count);
56
57                 return NULL;
58         }
59         smp_rmb();
60
61         group_desc = block_group / EXT3_DESC_PER_BLOCK(sb);
62         desc = block_group % EXT3_DESC_PER_BLOCK(sb);
63         if (!EXT3_SB(sb)->s_group_desc[group_desc]) {
64                 ext3_error (sb, "ext3_get_group_desc",
65                             "Group descriptor not loaded - "
66                             "block_group = %d, group_desc = %lu, desc = %lu",
67                              block_group, group_desc, desc);
68                 return NULL;
69         }
70
71         gdp = (struct ext3_group_desc *) 
72               EXT3_SB(sb)->s_group_desc[group_desc]->b_data;
73         if (bh)
74                 *bh = EXT3_SB(sb)->s_group_desc[group_desc];
75         return gdp + desc;
76 }
77
78 /*
79  * Read the bitmap for a given block_group, reading into the specified 
80  * slot in the superblock's bitmap cache.
81  *
82  * Return buffer_head on success or NULL in case of failure.
83  */
84 static struct buffer_head *
85 read_block_bitmap(struct super_block *sb, unsigned int block_group)
86 {
87         struct ext3_group_desc * desc;
88         struct buffer_head * bh = NULL;
89
90         desc = ext3_get_group_desc (sb, block_group, NULL);
91         if (!desc)
92                 goto error_out;
93         bh = sb_bread(sb, le32_to_cpu(desc->bg_block_bitmap));
94         if (!bh)
95                 ext3_error (sb, "read_block_bitmap",
96                             "Cannot read block bitmap - "
97                             "block_group = %d, block_bitmap = %u",
98                             block_group, le32_to_cpu(desc->bg_block_bitmap));
99 error_out:
100         return bh;
101 }
102 /*
103  * The reservation window structure operations
104  * --------------------------------------------
105  * Operations include:
106  * dump, find, add, remove, is_empty, find_next_reservable_window, etc.
107  *
108  * We use sorted double linked list for the per-filesystem reservation
109  * window list. (like in vm_region).
110  *
111  * Initially, we keep those small operations in the abstract functions,
112  * so later if we need a better searching tree than double linked-list,
113  * we could easily switch to that without changing too much
114  * code.
115  */
116 #if 0
117 static void __rsv_window_dump(struct rb_root *root, int verbose, 
118                               const char *fn)
119 {
120         struct rb_node *n;
121         struct reserve_window_node *rsv, *prev;
122         int bad;
123         
124 restart:
125         n = rb_first(root);
126         bad = 0;
127         prev = NULL;
128         
129         printk("Block Allocation Reservation Windows Map (%s):\n", fn);
130         while (n) {
131                 rsv = list_entry(n, struct reserve_window_node, rsv_node);
132                 if (verbose)
133                         printk("reservation window 0x%p "
134                                "start:  %d, end:  %d\n",
135                                rsv, rsv->rsv_start, rsv->rsv_end);
136                 if (rsv->rsv_start && rsv->rsv_start >= rsv->rsv_end) {
137                         printk("Bad reservation %p (start >= end)\n", 
138                                rsv);
139                         bad = 1;
140                 }
141                 if (prev && prev->rsv_end >= rsv->rsv_start) {
142                         printk("Bad reservation %p (prev->end >= start)\n",
143                                rsv);
144                         bad = 1;
145                 }
146                 if (bad) {
147                         if (!verbose) {
148                                 printk("Restarting reservation walk in verbose mode\n");
149                                 verbose = 1;
150                                 goto restart;
151                         }
152                 }
153                 n = rb_next(n);
154                 prev = rsv;
155         }
156         printk("Window map complete.\n");
157         if (bad)
158                 BUG();
159 }
160 #define rsv_window_dump(root, verbose) \
161         __rsv_window_dump((root), (verbose), __FUNCTION__)
162 #else
163 #define rsv_window_dump(root, verbose) do {} while (0)
164 #endif
165
166 static int
167 goal_in_my_reservation(struct reserve_window *rsv, int goal,
168                         unsigned int group, struct super_block * sb)
169 {
170         unsigned long group_first_block, group_last_block;
171
172         group_first_block = le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block) +
173                                 group * EXT3_BLOCKS_PER_GROUP(sb);
174         group_last_block = group_first_block + EXT3_BLOCKS_PER_GROUP(sb) - 1;
175
176         if ((rsv->_rsv_start > group_last_block) ||
177             (rsv->_rsv_end < group_first_block))
178                 return 0;
179         if ((goal >= 0) && ((goal + group_first_block < rsv->_rsv_start)
180                 || (goal + group_first_block > rsv->_rsv_end)))
181                 return 0;
182         return 1;
183 }
184
185 /* 
186  * Find the reserved window which includes the goal, or the previous one
187  * if the goal is not in any window.
188  * Returns NULL if there are no windows or if all windows start after the goal.
189  */
190 static struct reserve_window_node *search_reserve_window(struct rb_root *root,
191                                                          unsigned long goal)
192 {
193         struct rb_node *n = root->rb_node;
194         struct reserve_window_node *rsv;
195
196         if (!n)
197                 return NULL;
198         
199         while (n)
200         {
201                 rsv = rb_entry(n, struct reserve_window_node, rsv_node);
202
203                 if (goal < rsv->rsv_start)
204                         n = n->rb_left;
205                 else if (goal > rsv->rsv_end)
206                         n = n->rb_right;
207                 else
208                         return rsv;
209         }
210         /* 
211          * We've fallen off the end of the tree: the goal wasn't inside
212          * any particular node.  OK, the previous node must be to one
213          * side of the interval containing the goal.  If it's the RHS,
214          * we need to back up one. 
215          */
216         if (rsv->rsv_start > goal) {
217                 n = rb_prev(&rsv->rsv_node);
218                 rsv = rb_entry(n, struct reserve_window_node, rsv_node);
219         }
220         return rsv; 
221 }
222
223 void rsv_window_add(struct super_block *sb,
224                     struct reserve_window_node *rsv)
225 {
226         struct rb_root *root = &EXT3_SB(sb)->s_rsv_window_root;
227         struct rb_node *node = &rsv->rsv_node;
228         unsigned int start = rsv->rsv_start;
229
230         struct rb_node ** p = &root->rb_node;
231         struct rb_node * parent = NULL;
232         struct reserve_window_node *this;
233         
234         while (*p)
235         {
236                 parent = *p;
237                 this = rb_entry(parent, struct reserve_window_node, rsv_node);
238
239                 if (start < this->rsv_start)
240                         p = &(*p)->rb_left;
241                 else if (start > this->rsv_end)
242                         p = &(*p)->rb_right;
243                 else
244                         BUG();
245         }
246
247         rb_link_node(node, parent, p);
248         rb_insert_color(node, root);
249 }
250
251 static void rsv_window_remove(struct super_block *sb,
252                               struct reserve_window_node *rsv)
253 {
254         rsv->rsv_start = EXT3_RESERVE_WINDOW_NOT_ALLOCATED;
255         rsv->rsv_end = EXT3_RESERVE_WINDOW_NOT_ALLOCATED;
256         atomic_set(&rsv->rsv_alloc_hit, 0);
257         rb_erase(&rsv->rsv_node, &EXT3_SB(sb)->s_rsv_window_root);
258 }
259
260 static inline int rsv_is_empty(struct reserve_window *rsv)
261 {
262         /* a valid reservation end block could not be 0 */
263         return (rsv->_rsv_end == EXT3_RESERVE_WINDOW_NOT_ALLOCATED);
264 }
265
266 void ext3_discard_reservation(struct inode *inode)
267 {
268         struct ext3_inode_info *ei = EXT3_I(inode);
269         struct reserve_window_node *rsv = &ei->i_rsv_window;
270         spinlock_t *rsv_lock = &EXT3_SB(inode->i_sb)->s_rsv_window_lock;
271
272         if (!rsv_is_empty(&rsv->rsv_window)) {
273                 spin_lock(rsv_lock);
274                 rsv_window_remove(inode->i_sb, rsv);
275                 spin_unlock(rsv_lock);
276         }
277 }
278
279 /* Free given blocks, update quota and i_blocks field */
280 void ext3_free_blocks_sb(handle_t *handle, struct super_block *sb,
281                          unsigned long block, unsigned long count,
282                          int *pdquot_freed_blocks)
283 {
284         struct buffer_head *bitmap_bh = NULL;
285         struct buffer_head *gd_bh;
286         unsigned long block_group;
287         unsigned long bit;
288         unsigned long i;
289         unsigned long overflow;
290         struct ext3_group_desc * gdp;
291         struct ext3_super_block * es;
292         struct ext3_sb_info *sbi;
293         int err = 0, ret;
294
295         *pdquot_freed_blocks = 0;
296         sbi = EXT3_SB(sb);
297         es = EXT3_SB(sb)->s_es;
298         if (block < le32_to_cpu(es->s_first_data_block) ||
299             block + count < block ||
300             block + count > le32_to_cpu(es->s_blocks_count)) {
301                 ext3_error (sb, "ext3_free_blocks",
302                             "Freeing blocks not in datazone - "
303                             "block = %lu, count = %lu", block, count);
304                 goto error_return;
305         }
306
307         ext3_debug ("freeing block %lu\n", block);
308
309 do_more:
310         overflow = 0;
311         block_group = (block - le32_to_cpu(es->s_first_data_block)) /
312                       EXT3_BLOCKS_PER_GROUP(sb);
313         bit = (block - le32_to_cpu(es->s_first_data_block)) %
314                       EXT3_BLOCKS_PER_GROUP(sb);
315         /*
316          * Check to see if we are freeing blocks across a group
317          * boundary.
318          */
319         if (bit + count > EXT3_BLOCKS_PER_GROUP(sb)) {
320                 overflow = bit + count - EXT3_BLOCKS_PER_GROUP(sb);
321                 count -= overflow;
322         }
323         brelse(bitmap_bh);
324         bitmap_bh = read_block_bitmap(sb, block_group);
325         if (!bitmap_bh)
326                 goto error_return;
327         gdp = ext3_get_group_desc (sb, block_group, &gd_bh);
328         if (!gdp)
329                 goto error_return;
330
331         if (in_range (le32_to_cpu(gdp->bg_block_bitmap), block, count) ||
332             in_range (le32_to_cpu(gdp->bg_inode_bitmap), block, count) ||
333             in_range (block, le32_to_cpu(gdp->bg_inode_table),
334                       EXT3_SB(sb)->s_itb_per_group) ||
335             in_range (block + count - 1, le32_to_cpu(gdp->bg_inode_table),
336                       EXT3_SB(sb)->s_itb_per_group))
337                 ext3_error (sb, "ext3_free_blocks",
338                             "Freeing blocks in system zones - "
339                             "Block = %lu, count = %lu",
340                             block, count);
341
342         /*
343          * We are about to start releasing blocks in the bitmap,
344          * so we need undo access.
345          */
346         /* @@@ check errors */
347         BUFFER_TRACE(bitmap_bh, "getting undo access");
348         err = ext3_journal_get_undo_access(handle, bitmap_bh, NULL);
349         if (err)
350                 goto error_return;
351
352         /*
353          * We are about to modify some metadata.  Call the journal APIs
354          * to unshare ->b_data if a currently-committing transaction is
355          * using it
356          */
357         BUFFER_TRACE(gd_bh, "get_write_access");
358         err = ext3_journal_get_write_access(handle, gd_bh);
359         if (err)
360                 goto error_return;
361
362         jbd_lock_bh_state(bitmap_bh);
363
364         for (i = 0; i < count; i++) {
365                 /*
366                  * An HJ special.  This is expensive...
367                  */
368 #ifdef CONFIG_JBD_DEBUG
369                 jbd_unlock_bh_state(bitmap_bh);
370                 {
371                         struct buffer_head *debug_bh;
372                         debug_bh = sb_find_get_block(sb, block + i);
373                         if (debug_bh) {
374                                 BUFFER_TRACE(debug_bh, "Deleted!");
375                                 if (!bh2jh(bitmap_bh)->b_committed_data)
376                                         BUFFER_TRACE(debug_bh,
377                                                 "No commited data in bitmap");
378                                 BUFFER_TRACE2(debug_bh, bitmap_bh, "bitmap");
379                                 __brelse(debug_bh);
380                         }
381                 }
382                 jbd_lock_bh_state(bitmap_bh);
383 #endif
384                 /* @@@ This prevents newly-allocated data from being
385                  * freed and then reallocated within the same
386                  * transaction. 
387                  * 
388                  * Ideally we would want to allow that to happen, but to
389                  * do so requires making journal_forget() capable of
390                  * revoking the queued write of a data block, which
391                  * implies blocking on the journal lock.  *forget()
392                  * cannot block due to truncate races.
393                  *
394                  * Eventually we can fix this by making journal_forget()
395                  * return a status indicating whether or not it was able
396                  * to revoke the buffer.  On successful revoke, it is
397                  * safe not to set the allocation bit in the committed
398                  * bitmap, because we know that there is no outstanding
399                  * activity on the buffer any more and so it is safe to
400                  * reallocate it.  
401                  */
402                 BUFFER_TRACE(bitmap_bh, "set in b_committed_data");
403                 J_ASSERT_BH(bitmap_bh,
404                                 bh2jh(bitmap_bh)->b_committed_data != NULL);
405                 ext3_set_bit_atomic(sb_bgl_lock(sbi, block_group), bit + i,
406                                 bh2jh(bitmap_bh)->b_committed_data);
407
408                 /*
409                  * We clear the bit in the bitmap after setting the committed
410                  * data bit, because this is the reverse order to that which
411                  * the allocator uses.
412                  */
413                 BUFFER_TRACE(bitmap_bh, "clear bit");
414                 if (!ext3_clear_bit_atomic(sb_bgl_lock(sbi, block_group),
415                                                 bit + i, bitmap_bh->b_data)) {
416                         jbd_unlock_bh_state(bitmap_bh);
417                         ext3_error(sb, __FUNCTION__,
418                                 "bit already cleared for block %lu", block + i);
419                         jbd_lock_bh_state(bitmap_bh);
420                         BUFFER_TRACE(bitmap_bh, "bit already cleared");
421                 } else {
422                         (*pdquot_freed_blocks)++;
423                 }
424         }
425         jbd_unlock_bh_state(bitmap_bh);
426
427         spin_lock(sb_bgl_lock(sbi, block_group));
428         gdp->bg_free_blocks_count =
429                 cpu_to_le16(le16_to_cpu(gdp->bg_free_blocks_count) +
430                         *pdquot_freed_blocks);
431         spin_unlock(sb_bgl_lock(sbi, block_group));
432         percpu_counter_mod(&sbi->s_freeblocks_counter, count);
433
434         /* We dirtied the bitmap block */
435         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
436         err = ext3_journal_dirty_metadata(handle, bitmap_bh);
437
438         /* And the group descriptor block */
439         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
440         ret = ext3_journal_dirty_metadata(handle, gd_bh);
441         if (!err) err = ret;
442
443         if (overflow && !err) {
444                 block += count;
445                 count = overflow;
446                 goto do_more;
447         }
448         sb->s_dirt = 1;
449 error_return:
450         brelse(bitmap_bh);
451         ext3_std_error(sb, err);
452         return;
453 }
454
455 /* Free given blocks, update quota and i_blocks field */
456 void ext3_free_blocks(handle_t *handle, struct inode *inode,
457                         unsigned long block, unsigned long count)
458 {
459         struct super_block * sb;
460         int dquot_freed_blocks;
461
462         sb = inode->i_sb;
463         if (!sb) {
464                 printk ("ext3_free_blocks: nonexistent device");
465                 return;
466         }
467         ext3_free_blocks_sb(handle, sb, block, count, &dquot_freed_blocks);
468         if (dquot_freed_blocks) {
469                 DLIMIT_FREE_BLOCK(sb, inode->i_xid, dquot_freed_blocks);
470                 DQUOT_FREE_BLOCK(inode, dquot_freed_blocks);
471         }
472         return;
473 }
474
475 /*
476  * For ext3 allocations, we must not reuse any blocks which are
477  * allocated in the bitmap buffer's "last committed data" copy.  This
478  * prevents deletes from freeing up the page for reuse until we have
479  * committed the delete transaction.
480  *
481  * If we didn't do this, then deleting something and reallocating it as
482  * data would allow the old block to be overwritten before the
483  * transaction committed (because we force data to disk before commit).
484  * This would lead to corruption if we crashed between overwriting the
485  * data and committing the delete. 
486  *
487  * @@@ We may want to make this allocation behaviour conditional on
488  * data-writes at some point, and disable it for metadata allocations or
489  * sync-data inodes.
490  */
491 static int ext3_test_allocatable(int nr, struct buffer_head *bh)
492 {
493         int ret;
494         struct journal_head *jh = bh2jh(bh);
495
496         if (ext3_test_bit(nr, bh->b_data))
497                 return 0;
498
499         jbd_lock_bh_state(bh);
500         if (!jh->b_committed_data)
501                 ret = 1;
502         else
503                 ret = !ext3_test_bit(nr, jh->b_committed_data);
504         jbd_unlock_bh_state(bh);
505         return ret;
506 }
507
508 static int
509 bitmap_search_next_usable_block(int start, struct buffer_head *bh,
510                                         int maxblocks)
511 {
512         int next;
513         struct journal_head *jh = bh2jh(bh);
514
515         /*
516          * The bitmap search --- search forward alternately through the actual
517          * bitmap and the last-committed copy until we find a bit free in
518          * both
519          */
520         while (start < maxblocks) {
521                 next = ext3_find_next_zero_bit(bh->b_data, maxblocks, start);
522                 if (next >= maxblocks)
523                         return -1;
524                 if (ext3_test_allocatable(next, bh))
525                         return next;
526                 jbd_lock_bh_state(bh);
527                 if (jh->b_committed_data)
528                         start = ext3_find_next_zero_bit(jh->b_committed_data,
529                                                         maxblocks, next);
530                 jbd_unlock_bh_state(bh);
531         }
532         return -1;
533 }
534
535 /*
536  * Find an allocatable block in a bitmap.  We honour both the bitmap and
537  * its last-committed copy (if that exists), and perform the "most
538  * appropriate allocation" algorithm of looking for a free block near
539  * the initial goal; then for a free byte somewhere in the bitmap; then
540  * for any free bit in the bitmap.
541  */
542 static int
543 find_next_usable_block(int start, struct buffer_head *bh, int maxblocks)
544 {
545         int here, next;
546         char *p, *r;
547
548         if (start > 0) {
549                 /*
550                  * The goal was occupied; search forward for a free 
551                  * block within the next XX blocks.
552                  *
553                  * end_goal is more or less random, but it has to be
554                  * less than EXT3_BLOCKS_PER_GROUP. Aligning up to the
555                  * next 64-bit boundary is simple..
556                  */
557                 int end_goal = (start + 63) & ~63;
558                 if (end_goal > maxblocks)
559                         end_goal = maxblocks;
560                 here = ext3_find_next_zero_bit(bh->b_data, end_goal, start);
561                 if (here < end_goal && ext3_test_allocatable(here, bh))
562                         return here;
563                 ext3_debug("Bit not found near goal\n");
564         }
565
566         here = start;
567         if (here < 0)
568                 here = 0;
569
570         p = ((char *)bh->b_data) + (here >> 3);
571         r = memscan(p, 0, (maxblocks - here + 7) >> 3);
572         next = (r - ((char *)bh->b_data)) << 3;
573
574         if (next < maxblocks && next >= start && ext3_test_allocatable(next, bh))
575                 return next;
576
577         /*
578          * The bitmap search --- search forward alternately through the actual
579          * bitmap and the last-committed copy until we find a bit free in
580          * both
581          */
582         here = bitmap_search_next_usable_block(here, bh, maxblocks);
583         return here;
584 }
585
586 /*
587  * We think we can allocate this block in this bitmap.  Try to set the bit.
588  * If that succeeds then check that nobody has allocated and then freed the
589  * block since we saw that is was not marked in b_committed_data.  If it _was_
590  * allocated and freed then clear the bit in the bitmap again and return
591  * zero (failure).
592  */
593 static inline int
594 claim_block(spinlock_t *lock, int block, struct buffer_head *bh)
595 {
596         struct journal_head *jh = bh2jh(bh);
597         int ret;
598
599         if (ext3_set_bit_atomic(lock, block, bh->b_data))
600                 return 0;
601         jbd_lock_bh_state(bh);
602         if (jh->b_committed_data && ext3_test_bit(block,jh->b_committed_data)) {
603                 ext3_clear_bit_atomic(lock, block, bh->b_data);
604                 ret = 0;
605         } else {
606                 ret = 1;
607         }
608         jbd_unlock_bh_state(bh);
609         return ret;
610 }
611
612 /*
613  * If we failed to allocate the desired block then we may end up crossing to a
614  * new bitmap.  In that case we must release write access to the old one via
615  * ext3_journal_release_buffer(), else we'll run out of credits.
616  */
617 static int
618 ext3_try_to_allocate(struct super_block *sb, handle_t *handle, int group,
619         struct buffer_head *bitmap_bh, int goal, struct reserve_window *my_rsv)
620 {
621         int group_first_block, start, end;
622
623         /* we do allocation within the reservation window if we have a window */
624         if (my_rsv) {
625                 group_first_block =
626                         le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block) +
627                         group * EXT3_BLOCKS_PER_GROUP(sb);
628                 if (my_rsv->_rsv_start >= group_first_block)
629                         start = my_rsv->_rsv_start - group_first_block;
630                 else
631                         /* reservation window cross group boundary */
632                         start = 0;
633                 end = my_rsv->_rsv_end - group_first_block + 1;
634                 if (end > EXT3_BLOCKS_PER_GROUP(sb))
635                         /* reservation window crosses group boundary */
636                         end = EXT3_BLOCKS_PER_GROUP(sb);
637                 if ((start <= goal) && (goal < end))
638                         start = goal;
639                 else
640                         goal = -1;
641         } else {
642                 if (goal > 0)
643                         start = goal;
644                 else
645                         start = 0;
646                 end = EXT3_BLOCKS_PER_GROUP(sb);
647         }
648
649         BUG_ON(start > EXT3_BLOCKS_PER_GROUP(sb));
650
651 repeat:
652         if (goal < 0 || !ext3_test_allocatable(goal, bitmap_bh)) {
653                 goal = find_next_usable_block(start, bitmap_bh, end);
654                 if (goal < 0)
655                         goto fail_access;
656                 if (!my_rsv) {
657                         int i;
658
659                         for (i = 0; i < 7 && goal > start &&
660                                         ext3_test_allocatable(goal - 1,
661                                                                 bitmap_bh);
662                                         i++, goal--)
663                                 ;
664                 }
665         }
666         start = goal;
667
668         if (!claim_block(sb_bgl_lock(EXT3_SB(sb), group), goal, bitmap_bh)) {
669                 /*
670                  * The block was allocated by another thread, or it was
671                  * allocated and then freed by another thread
672                  */
673                 start++;
674                 goal++;
675                 if (start >= end)
676                         goto fail_access;
677                 goto repeat;
678         }
679         return goal;
680 fail_access:
681         return -1;
682 }
683
684 /**
685  *      find_next_reservable_window():
686  *              find a reservable space within the given range.
687  *              It does not allocate the reservation window for now:
688  *              alloc_new_reservation() will do the work later.
689  *
690  *      @search_head: the head of the searching list;
691  *              This is not necessarily the list head of the whole filesystem
692  *
693  *              We have both head and start_block to assist the search
694  *              for the reservable space. The list starts from head,
695  *              but we will shift to the place where start_block is,
696  *              then start from there, when looking for a reservable space.
697  *
698  *      @size: the target new reservation window size
699  *
700  *      @group_first_block: the first block we consider to start
701  *                      the real search from
702  *
703  *      @last_block:
704  *              the maximum block number that our goal reservable space
705  *              could start from. This is normally the last block in this
706  *              group. The search will end when we found the start of next
707  *              possible reservable space is out of this boundary.
708  *              This could handle the cross boundary reservation window
709  *              request. 
710  *
711  *      basically we search from the given range, rather than the whole
712  *      reservation double linked list, (start_block, last_block)
713  *      to find a free region that is of my size and has not
714  *      been reserved.
715  *
716  *      on succeed, it returns the reservation window to be appended to.
717  *      failed, return NULL.
718  */
719 static struct reserve_window_node *find_next_reservable_window(
720                                 struct reserve_window_node *search_head,
721                                 unsigned long size, int *start_block,
722                                 int last_block)
723 {
724         struct rb_node *next;
725         struct reserve_window_node *rsv, *prev;
726         int cur;
727
728         /* TODO: make the start of the reservation window byte-aligned */
729         /* cur = *start_block & ~7;*/
730         cur = *start_block;
731         rsv = search_head;
732         if (!rsv) 
733                 return NULL;
734         
735         while (1) {
736                 if (cur <= rsv->rsv_end)
737                         cur = rsv->rsv_end + 1;
738
739                 /* TODO?
740                  * in the case we could not find a reservable space
741                  * that is what is expected, during the re-search, we could
742                  * remember what's the largest reservable space we could have
743                  * and return that one.
744                  *
745                  * For now it will fail if we could not find the reservable
746                  * space with expected-size (or more)...
747                  */
748                 if (cur > last_block)
749                         return NULL;            /* fail */
750
751                 prev = rsv;
752                 next = rb_next(&rsv->rsv_node);
753                 rsv = list_entry(next, struct reserve_window_node, rsv_node);
754
755                 /* 
756                  * Reached the last reservation, we can just append to the 
757                  * previous one. 
758                  */
759                 if (!next)
760                         break;
761
762                 if (cur + size <= rsv->rsv_start) {
763                         /*
764                          * Found a reserveable space big enough.  We could
765                          * have a reservation across the group boundary here
766                          */
767                         break;
768                 }
769         }
770         /*
771          * we come here either :
772          * when we reach the end of the whole list,
773          * and there is empty reservable space after last entry in the list.
774          * append it to the end of the list.
775          *
776          * or we found one reservable space in the middle of the list,
777          * return the reservation window that we could append to.
778          * succeed.
779          */
780         *start_block = cur;
781         return prev;
782 }
783
784 /**
785  *      alloc_new_reservation()--allocate a new reservation window
786  *              if there is an existing reservation, discard it first
787  *              then allocate the new one from there
788  *              otherwise allocate the new reservation from the given
789  *              start block, or the beginning of the group, if a goal
790  *              is not given.
791  *
792  *              To make a new reservation, we search part of the filesystem
793  *              reservation list (the list that inside the group).
794  *
795  *              If we have a old reservation, the search goal is the end of
796  *              last reservation. If we do not have a old reservation, then we
797  *              start from a given goal, or the first block of the group, if
798  *              the goal is not given.
799  *
800  *              We first find a reservable space after the goal, then from
801  *              there, we check the bitmap for the first free block after
802  *              it. If there is no free block until the end of group, then the
803  *              whole group is full, we failed. Otherwise, check if the free
804  *              block is inside the expected reservable space, if so, we
805  *              succeed.
806  *              If the first free block is outside the reservable space, then
807  *              start from the first free block, we search for next available
808  *              space, and go on.
809  *
810  *      on succeed, a new reservation will be found and inserted into the list
811  *      It contains at least one free block, and it does not overlap with other
812  *      reservation windows.
813  *
814  *      failed: we failed to find a reservation window in this group
815  *
816  *      @rsv: the reservation
817  *
818  *      @goal: The goal (group-relative).  It is where the search for a
819  *              free reservable space should start from.
820  *              if we have a old reservation, start_block is the end of
821  *              old reservation. Otherwise,
822  *              if we have a goal(goal >0 ), then start from there,
823  *              no goal(goal = -1), we start from the first block
824  *              of the group.
825  *
826  *      @sb: the super block
827  *      @group: the group we are trying to allocate in
828  *      @bitmap_bh: the block group block bitmap
829  */
830 static int alloc_new_reservation(struct reserve_window_node *my_rsv,
831                 int goal, struct super_block *sb,
832                 unsigned int group, struct buffer_head *bitmap_bh)
833 {
834         struct reserve_window_node *search_head;
835         int group_first_block, group_end_block, start_block;
836         int first_free_block;
837         int reservable_space_start;
838         struct reserve_window_node *prev_rsv;
839         struct rb_root *fs_rsv_root = &EXT3_SB(sb)->s_rsv_window_root;
840         unsigned long size;
841
842         group_first_block = le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block) +
843                                 group * EXT3_BLOCKS_PER_GROUP(sb);
844         group_end_block = group_first_block + EXT3_BLOCKS_PER_GROUP(sb) - 1;
845
846         if (goal < 0)
847                 start_block = group_first_block;
848         else
849                 start_block = goal + group_first_block;
850
851         size = atomic_read(&my_rsv->rsv_goal_size);
852         /* if we have a old reservation, start the search from the old rsv */
853         if (!rsv_is_empty(&my_rsv->rsv_window)) {
854                 /*
855                  * if the old reservation is cross group boundary
856                  * we will come here when we just failed to allocate from
857                  * the first part of the window. We still have another part
858                  * that belongs to the next group. In this case, there is no
859                  * point to discard our window and try to allocate a new one
860                  * in this group(which will fail). we should
861                  * keep the reservation window, just simply move on.
862                  *
863                  * Maybe we could shift the start block of the reservation
864                  * window to the first block of next group.
865                  */
866
867                 if ((my_rsv->rsv_start <= group_end_block) &&
868                                 (my_rsv->rsv_end > group_end_block))
869                         return -1;
870
871                 /* remember where we are before we discard the old one */
872                 if (my_rsv->rsv_end + 1 > start_block)
873                         start_block = my_rsv->rsv_end + 1;
874                 search_head = my_rsv;
875                 if ((atomic_read(&my_rsv->rsv_alloc_hit) > 
876                      (my_rsv->rsv_end - my_rsv->rsv_start + 1) / 2)) {
877                         /*
878                          * if we previously allocation hit ration is greater than half
879                          * we double the size of reservation window next time
880                          * otherwise keep the same
881                          */
882                         size = size * 2;
883                         if (size > EXT3_MAX_RESERVE_BLOCKS)
884                                 size = EXT3_MAX_RESERVE_BLOCKS;
885                         atomic_set(&my_rsv->rsv_goal_size, size);
886                 }
887         }
888         else {
889                 /*
890                  * we don't have a reservation,
891                  * we set our goal(start_block) and
892                  * the list head for the search
893                  */
894                 search_head = search_reserve_window(fs_rsv_root, start_block);
895         }
896
897         /*
898          * find_next_reservable_window() simply finds a reservable window
899          * inside the given range(start_block, group_end_block).
900          *
901          * To make sure the reservation window has a free bit inside it, we
902          * need to check the bitmap after we found a reservable window.
903          */
904 retry:
905         prev_rsv = find_next_reservable_window(search_head, size,
906                                                 &start_block, group_end_block);
907         if (prev_rsv == NULL)
908                 goto failed;
909         reservable_space_start = start_block;
910         /*
911          * On success, find_next_reservable_window() returns the
912          * reservation window where there is a reservable space after it.
913          * Before we reserve this reservable space, we need
914          * to make sure there is at least a free block inside this region.
915          *
916          * searching the first free bit on the block bitmap and copy of
917          * last committed bitmap alternatively, until we found a allocatable
918          * block. Search start from the start block of the reservable space
919          * we just found.
920          */
921         first_free_block = bitmap_search_next_usable_block(
922                         reservable_space_start - group_first_block,
923                         bitmap_bh, group_end_block - group_first_block + 1);
924
925         if (first_free_block < 0) {
926                 /*
927                  * no free block left on the bitmap, no point
928                  * to reserve the space. return failed.
929                  */
930                 goto failed;
931         }
932         start_block = first_free_block + group_first_block;
933         /*
934          * check if the first free block is within the
935          * free space we just found
936          */
937         if ((start_block >= reservable_space_start) &&
938           (start_block < reservable_space_start + size))
939                 goto found_rsv_window;
940         /*
941          * if the first free bit we found is out of the reservable space
942          * this means there is no free block on the reservable space
943          * we should continue search for next reservable space,
944          * start from where the free block is,
945          * we also shift the list head to where we stopped last time
946          */
947         search_head = prev_rsv;
948         goto retry;
949
950 found_rsv_window:
951         /*
952          * great! the reservable space contains some free blocks.
953          * if the search returns that we should add the new
954          * window just next to where the old window, we don't
955          * need to remove the old window first then add it to the
956          * same place, just update the new start and new end.
957          */
958         if (my_rsv != prev_rsv)  {
959                 if (!rsv_is_empty(&my_rsv->rsv_window))
960                         rsv_window_remove(sb, my_rsv);
961         }
962         my_rsv->rsv_start = reservable_space_start;
963         my_rsv->rsv_end = my_rsv->rsv_start + size - 1;
964         atomic_set(&my_rsv->rsv_alloc_hit, 0);
965         if (my_rsv != prev_rsv)  {
966                 rsv_window_add(sb, my_rsv);
967         }
968         return 0;               /* succeed */
969 failed:
970         return -1;              /* failed */
971 }
972
973 /*
974  * This is the main function used to allocate a new block and its reservation
975  * window.
976  *
977  * Each time when a new block allocation is need, first try to allocate from
978  * its own reservation.  If it does not have a reservation window, instead of
979  * looking for a free bit on bitmap first, then look up the reservation list to
980  * see if it is inside somebody else's reservation window, we try to allocate a
981  * reservation window for it starting from the goal first. Then do the block
982  * allocation within the reservation window.
983  *
984  * This will avoid keeping on searching the reservation list again and
985  * again when someboday is looking for a free block (without
986  * reservation), and there are lots of free blocks, but they are all
987  * being reserved.
988  *
989  * We use a sorted double linked list for the per-filesystem reservation list.
990  * The insert, remove and find a free space(non-reserved) operations for the
991  * sorted double linked list should be fast.
992  *
993  */
994 static int
995 ext3_try_to_allocate_with_rsv(struct super_block *sb, handle_t *handle,
996                         unsigned int group, struct buffer_head *bitmap_bh,
997                         int goal, struct reserve_window_node * my_rsv,
998                         int *errp)
999 {
1000         spinlock_t *rsv_lock;
1001         unsigned long group_first_block;
1002         int ret = 0;
1003         int fatal;
1004         int credits = 0;
1005
1006         *errp = 0;
1007
1008         /*
1009          * Make sure we use undo access for the bitmap, because it is critical
1010          * that we do the frozen_data COW on bitmap buffers in all cases even
1011          * if the buffer is in BJ_Forget state in the committing transaction.
1012          */
1013         BUFFER_TRACE(bitmap_bh, "get undo access for new block");
1014         fatal = ext3_journal_get_undo_access(handle, bitmap_bh, &credits);
1015         if (fatal) {
1016                 *errp = fatal;
1017                 return -1;
1018         }
1019
1020         /*
1021          * we don't deal with reservation when
1022          * filesystem is mounted without reservation
1023          * or the file is not a regular file
1024          * or last attempt to allocate a block with reservation turned on failed
1025          */
1026         if (my_rsv == NULL ) {
1027                 ret = ext3_try_to_allocate(sb, handle, group, bitmap_bh, goal, NULL);
1028                 goto out;
1029         }
1030         rsv_lock = &EXT3_SB(sb)->s_rsv_window_lock;
1031         /*
1032          * goal is a group relative block number (if there is a goal)
1033          * 0 < goal < EXT3_BLOCKS_PER_GROUP(sb)
1034          * first block is a filesystem wide block number
1035          * first block is the block number of the first block in this group
1036          */
1037         group_first_block = le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block) +
1038                         group * EXT3_BLOCKS_PER_GROUP(sb);
1039
1040         /*
1041          * Basically we will allocate a new block from inode's reservation
1042          * window.
1043          *
1044          * We need to allocate a new reservation window, if:
1045          * a) inode does not have a reservation window; or
1046          * b) last attempt to allocate a block from existing reservation
1047          *    failed; or
1048          * c) we come here with a goal and with a reservation window
1049          *
1050          * We do not need to allocate a new reservation window if we come here
1051          * at the beginning with a goal and the goal is inside the window, or
1052          * we don't have a goal but already have a reservation window.
1053          * then we could go to allocate from the reservation window directly.
1054          */
1055         while (1) {
1056                 struct reserve_window rsv_copy;
1057                 unsigned int seq;
1058                 
1059                 do {
1060                         seq = read_seqbegin(&my_rsv->rsv_seqlock);
1061                         rsv_copy._rsv_start = my_rsv->rsv_start;
1062                         rsv_copy._rsv_end = my_rsv->rsv_end;
1063                 } while (read_seqretry(&my_rsv->rsv_seqlock, seq));
1064
1065                 if (rsv_is_empty(&rsv_copy) || (ret < 0) ||
1066                         !goal_in_my_reservation(&rsv_copy, goal, group, sb)) {
1067                         spin_lock(rsv_lock);
1068                         write_seqlock(&my_rsv->rsv_seqlock);
1069                         ret = alloc_new_reservation(my_rsv, goal, sb,
1070                                                         group, bitmap_bh);
1071                         rsv_copy._rsv_start = my_rsv->rsv_start;
1072                         rsv_copy._rsv_end = my_rsv->rsv_end;
1073                         write_sequnlock(&my_rsv->rsv_seqlock);
1074                         spin_unlock(rsv_lock);
1075                         if (ret < 0)
1076                                 break;                  /* failed */
1077
1078                         if (!goal_in_my_reservation(&rsv_copy, goal, group, sb))
1079                                 goal = -1;
1080                 }
1081                 if ((rsv_copy._rsv_start >= group_first_block + EXT3_BLOCKS_PER_GROUP(sb))
1082                     || (rsv_copy._rsv_end < group_first_block))
1083                         BUG();
1084                 ret = ext3_try_to_allocate(sb, handle, group, bitmap_bh, goal,
1085                                            &rsv_copy);
1086                 if (ret >= 0) {
1087                         if (!read_seqretry(&my_rsv->rsv_seqlock, seq))
1088                                 atomic_inc(&my_rsv->rsv_alloc_hit);
1089                         break;                          /* succeed */
1090                 }
1091         }
1092 out:
1093         if (ret >= 0) {
1094                 BUFFER_TRACE(bitmap_bh, "journal_dirty_metadata for "
1095                                         "bitmap block");
1096                 fatal = ext3_journal_dirty_metadata(handle, bitmap_bh);
1097                 if (fatal) {
1098                         *errp = fatal;
1099                         return -1;
1100                 }
1101                 return ret;
1102         }
1103
1104         BUFFER_TRACE(bitmap_bh, "journal_release_buffer");
1105         ext3_journal_release_buffer(handle, bitmap_bh, credits);
1106         return ret;
1107 }
1108
1109 static int ext3_has_free_blocks(struct super_block *sb)
1110 {
1111         struct ext3_sb_info *sbi = EXT3_SB(sb);
1112         int free_blocks, root_blocks, cond;
1113
1114         free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
1115         root_blocks = le32_to_cpu(sbi->s_es->s_r_blocks_count);
1116
1117         vxdprintk(VXD_CBIT(dlim, 3),
1118                 "ext3_has_free_blocks(%p): free=%u, root=%u",
1119                 sb, free_blocks, root_blocks);
1120
1121         DLIMIT_ADJUST_BLOCK(sb, vx_current_xid(), &free_blocks, &root_blocks);
1122
1123         cond = (free_blocks < root_blocks + 1 &&
1124                 !capable(CAP_SYS_RESOURCE) &&
1125                 sbi->s_resuid != current->fsuid &&
1126                 (sbi->s_resgid == 0 || !in_group_p (sbi->s_resgid)));
1127
1128         vxdprintk(VXD_CBIT(dlim, 3),
1129                 "ext3_has_free_blocks(%p): %u<%u+1, %c, %u!=%u r=%d",
1130                 sb, free_blocks, root_blocks,
1131                 !capable(CAP_SYS_RESOURCE)?'1':'0',
1132                 sbi->s_resuid, current->fsuid, cond?0:1);
1133
1134         return (cond ? 0 : 1);
1135 }
1136
1137 /*
1138  * ext3_should_retry_alloc() is called when ENOSPC is returned, and if
1139  * it is profitable to retry the operation, this function will wait
1140  * for the current or commiting transaction to complete, and then
1141  * return TRUE.
1142  */
1143 int ext3_should_retry_alloc(struct super_block *sb, int *retries)
1144 {
1145         if (!ext3_has_free_blocks(sb) || (*retries)++ > 3)
1146                 return 0;
1147
1148         jbd_debug(1, "%s: retrying operation after ENOSPC\n", sb->s_id);
1149
1150         return journal_force_commit_nested(EXT3_SB(sb)->s_journal);
1151 }
1152
1153 /*
1154  * ext3_new_block uses a goal block to assist allocation.  If the goal is
1155  * free, or there is a free block within 32 blocks of the goal, that block
1156  * is allocated.  Otherwise a forward search is made for a free block; within 
1157  * each block group the search first looks for an entire free byte in the block
1158  * bitmap, and then for any free bit if that fails.
1159  * This function also updates quota and i_blocks field.
1160  */
1161 int ext3_new_block(handle_t *handle, struct inode *inode,
1162                         unsigned long goal, int *errp)
1163 {
1164         struct buffer_head *bitmap_bh = NULL;
1165         struct buffer_head *gdp_bh;
1166         int group_no;
1167         int goal_group;
1168         int ret_block;
1169         int bgi;                        /* blockgroup iteration index */
1170         int target_block;
1171         int fatal = 0, err;
1172         int performed_allocation = 0;
1173         int free_blocks;
1174         struct super_block *sb;
1175         struct ext3_group_desc *gdp;
1176         struct ext3_super_block *es;
1177         struct ext3_sb_info *sbi;
1178         struct reserve_window_node *my_rsv = NULL;
1179 #ifdef EXT3FS_DEBUG
1180         static int goal_hits, goal_attempts;
1181 #endif
1182         unsigned long ngroups;
1183
1184         *errp = -ENOSPC;
1185         sb = inode->i_sb;
1186         if (!sb) {
1187                 printk("ext3_new_block: nonexistent device");
1188                 return 0;
1189         }
1190
1191         /*
1192          * Check quota for allocation of this block.
1193          */
1194         if (DQUOT_ALLOC_BLOCK(inode, 1)) {
1195                 *errp = -EDQUOT;
1196                 return 0;
1197         }
1198         if (DLIMIT_ALLOC_BLOCK(sb, inode->i_xid, 1))
1199                 goto out_dlimit;
1200
1201         sbi = EXT3_SB(sb);
1202         es = EXT3_SB(sb)->s_es;
1203         ext3_debug("goal=%lu.\n", goal);
1204         if (test_opt(sb, RESERVATION) && S_ISREG(inode->i_mode))
1205                 my_rsv = &EXT3_I(inode)->i_rsv_window;
1206 #warning MEF was if (!ext3_has_free_blocks(sbi)) in 1.11-FC2
1207         if (!ext3_has_free_blocks(sb)) {
1208                 *errp = -ENOSPC;
1209                 goto out;
1210         }
1211
1212         /*
1213          * First, test whether the goal block is free.
1214          */
1215         if (goal < le32_to_cpu(es->s_first_data_block) ||
1216             goal >= le32_to_cpu(es->s_blocks_count))
1217                 goal = le32_to_cpu(es->s_first_data_block);
1218         group_no = (goal - le32_to_cpu(es->s_first_data_block)) /
1219                         EXT3_BLOCKS_PER_GROUP(sb);
1220         gdp = ext3_get_group_desc(sb, group_no, &gdp_bh);
1221         if (!gdp)
1222                 goto io_error;
1223
1224         goal_group = group_no;
1225 retry:
1226         free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
1227         if (free_blocks > 0) {
1228                 ret_block = ((goal - le32_to_cpu(es->s_first_data_block)) %
1229                                 EXT3_BLOCKS_PER_GROUP(sb));
1230                 bitmap_bh = read_block_bitmap(sb, group_no);
1231                 if (!bitmap_bh)
1232                         goto io_error;
1233                 ret_block = ext3_try_to_allocate_with_rsv(sb, handle, group_no,
1234                                         bitmap_bh, ret_block, my_rsv, &fatal);
1235                 if (fatal)
1236                         goto out;
1237                 if (ret_block >= 0)
1238                         goto allocated;
1239         }
1240
1241         ngroups = EXT3_SB(sb)->s_groups_count;
1242         smp_rmb();
1243
1244         /*
1245          * Now search the rest of the groups.  We assume that 
1246          * i and gdp correctly point to the last group visited.
1247          */
1248         for (bgi = 0; bgi < ngroups; bgi++) {
1249                 group_no++;
1250                 if (group_no >= ngroups)
1251                         group_no = 0;
1252                 gdp = ext3_get_group_desc(sb, group_no, &gdp_bh);
1253                 if (!gdp) {
1254                         *errp = -EIO;
1255                         goto out;
1256                 }
1257                 free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
1258                 if (free_blocks <= 0)
1259                         continue;
1260
1261                 brelse(bitmap_bh);
1262                 bitmap_bh = read_block_bitmap(sb, group_no);
1263                 if (!bitmap_bh)
1264                         goto io_error;
1265                 ret_block = ext3_try_to_allocate_with_rsv(sb, handle, group_no,
1266                                         bitmap_bh, -1, my_rsv, &fatal);
1267                 if (fatal)
1268                         goto out;
1269                 if (ret_block >= 0) 
1270                         goto allocated;
1271         }
1272         /*
1273          * We may end up a bogus ealier ENOSPC error due to
1274          * filesystem is "full" of reservations, but
1275          * there maybe indeed free blocks avaliable on disk
1276          * In this case, we just forget about the reservations
1277          * just do block allocation as without reservations.
1278          */
1279         if (my_rsv) {
1280                 my_rsv = NULL;
1281                 group_no = goal_group;
1282                 goto retry;
1283         }
1284         /* No space left on the device */
1285         *errp = -ENOSPC;
1286         goto out;
1287
1288 allocated:
1289
1290         ext3_debug("using block group %d(%d)\n",
1291                         group_no, gdp->bg_free_blocks_count);
1292
1293         BUFFER_TRACE(gdp_bh, "get_write_access");
1294         fatal = ext3_journal_get_write_access(handle, gdp_bh);
1295         if (fatal)
1296                 goto out;
1297
1298         target_block = ret_block + group_no * EXT3_BLOCKS_PER_GROUP(sb)
1299                                 + le32_to_cpu(es->s_first_data_block);
1300
1301         if (target_block == le32_to_cpu(gdp->bg_block_bitmap) ||
1302             target_block == le32_to_cpu(gdp->bg_inode_bitmap) ||
1303             in_range(target_block, le32_to_cpu(gdp->bg_inode_table),
1304                       EXT3_SB(sb)->s_itb_per_group))
1305                 ext3_error(sb, "ext3_new_block",
1306                             "Allocating block in system zone - "
1307                             "block = %u", target_block);
1308
1309         performed_allocation = 1;
1310
1311 #ifdef CONFIG_JBD_DEBUG
1312         {
1313                 struct buffer_head *debug_bh;
1314
1315                 /* Record bitmap buffer state in the newly allocated block */
1316                 debug_bh = sb_find_get_block(sb, target_block);
1317                 if (debug_bh) {
1318                         BUFFER_TRACE(debug_bh, "state when allocated");
1319                         BUFFER_TRACE2(debug_bh, bitmap_bh, "bitmap state");
1320                         brelse(debug_bh);
1321                 }
1322         }
1323         jbd_lock_bh_state(bitmap_bh);
1324         spin_lock(sb_bgl_lock(sbi, group_no));
1325         if (buffer_jbd(bitmap_bh) && bh2jh(bitmap_bh)->b_committed_data) {
1326                 if (ext3_test_bit(ret_block,
1327                                 bh2jh(bitmap_bh)->b_committed_data)) {
1328                         printk("%s: block was unexpectedly set in "
1329                                 "b_committed_data\n", __FUNCTION__);
1330                 }
1331         }
1332         ext3_debug("found bit %d\n", ret_block);
1333         spin_unlock(sb_bgl_lock(sbi, group_no));
1334         jbd_unlock_bh_state(bitmap_bh);
1335 #endif
1336
1337         /* ret_block was blockgroup-relative.  Now it becomes fs-relative */
1338         ret_block = target_block;
1339
1340         if (ret_block >= le32_to_cpu(es->s_blocks_count)) {
1341                 ext3_error(sb, "ext3_new_block",
1342                             "block(%d) >= blocks count(%d) - "
1343                             "block_group = %d, es == %p ", ret_block,
1344                         le32_to_cpu(es->s_blocks_count), group_no, es);
1345                 goto out;
1346         }
1347
1348         /*
1349          * It is up to the caller to add the new buffer to a journal
1350          * list of some description.  We don't know in advance whether
1351          * the caller wants to use it as metadata or data.
1352          */
1353         ext3_debug("allocating block %d. Goal hits %d of %d.\n",
1354                         ret_block, goal_hits, goal_attempts);
1355
1356         spin_lock(sb_bgl_lock(sbi, group_no));
1357         gdp->bg_free_blocks_count =
1358                         cpu_to_le16(le16_to_cpu(gdp->bg_free_blocks_count) - 1);
1359         spin_unlock(sb_bgl_lock(sbi, group_no));
1360         percpu_counter_mod(&sbi->s_freeblocks_counter, -1);
1361
1362         BUFFER_TRACE(gdp_bh, "journal_dirty_metadata for group descriptor");
1363         err = ext3_journal_dirty_metadata(handle, gdp_bh);
1364         if (!fatal)
1365                 fatal = err;
1366
1367         sb->s_dirt = 1;
1368         if (fatal)
1369                 goto out;
1370
1371         *errp = 0;
1372         brelse(bitmap_bh);
1373         return ret_block;
1374
1375 io_error:
1376         *errp = -EIO;
1377 out:
1378         if (!performed_allocation)
1379                 DLIMIT_FREE_BLOCK(sb, inode->i_xid, 1);
1380 out_dlimit:
1381         if (fatal) {
1382                 *errp = fatal;
1383                 ext3_std_error(sb, fatal);
1384         }
1385         /*
1386          * Undo the block allocation
1387          */
1388         if (!performed_allocation)
1389                 DQUOT_FREE_BLOCK(inode, 1);
1390         brelse(bitmap_bh);
1391         return 0;
1392 }
1393
1394 unsigned long ext3_count_free_blocks(struct super_block *sb)
1395 {
1396         unsigned long desc_count;
1397         struct ext3_group_desc *gdp;
1398         int i;
1399         unsigned long ngroups;
1400 #ifdef EXT3FS_DEBUG
1401         struct ext3_super_block *es;
1402         unsigned long bitmap_count, x;
1403         struct buffer_head *bitmap_bh = NULL;
1404
1405         lock_super(sb);
1406         es = EXT3_SB(sb)->s_es;
1407         desc_count = 0;
1408         bitmap_count = 0;
1409         gdp = NULL;
1410         for (i = 0; i < EXT3_SB(sb)->s_groups_count; i++) {
1411                 gdp = ext3_get_group_desc(sb, i, NULL);
1412                 if (!gdp)
1413                         continue;
1414                 desc_count += le16_to_cpu(gdp->bg_free_blocks_count);
1415                 brelse(bitmap_bh);
1416                 bitmap_bh = read_block_bitmap(sb, i);
1417                 if (bitmap_bh == NULL)
1418                         continue;
1419
1420                 x = ext3_count_free(bitmap_bh, sb->s_blocksize);
1421                 printk("group %d: stored = %d, counted = %lu\n",
1422                         i, le16_to_cpu(gdp->bg_free_blocks_count), x);
1423                 bitmap_count += x;
1424         }
1425         brelse(bitmap_bh);
1426         printk("ext3_count_free_blocks: stored = %u, computed = %lu, %lu\n",
1427                le32_to_cpu(es->s_free_blocks_count), desc_count, bitmap_count);
1428         unlock_super(sb);
1429         return bitmap_count;
1430 #else
1431         desc_count = 0;
1432         ngroups = EXT3_SB(sb)->s_groups_count;
1433         smp_rmb();
1434         for (i = 0; i < ngroups; i++) {
1435                 gdp = ext3_get_group_desc(sb, i, NULL);
1436                 if (!gdp)
1437                         continue;
1438                 desc_count += le16_to_cpu(gdp->bg_free_blocks_count);
1439         }
1440
1441         return desc_count;
1442 #endif
1443 }
1444
1445 static inline int block_in_use(unsigned long block,
1446                                 struct super_block * sb,
1447                                 unsigned char * map)
1448 {
1449         return ext3_test_bit ((block -
1450                 le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block)) %
1451                          EXT3_BLOCKS_PER_GROUP(sb), map);
1452 }
1453
1454 static inline int test_root(int a, int b)
1455 {
1456         if (a == 0)
1457                 return 1;
1458         while (1) {
1459                 if (a == 1)
1460                         return 1;
1461                 if (a % b)
1462                         return 0;
1463                 a = a / b;
1464         }
1465 }
1466
1467 int ext3_group_sparse(int group)
1468 {
1469         return (test_root(group, 3) || test_root(group, 5) ||
1470                 test_root(group, 7));
1471 }
1472
1473 /**
1474  *      ext3_bg_has_super - number of blocks used by the superblock in group
1475  *      @sb: superblock for filesystem
1476  *      @group: group number to check
1477  *
1478  *      Return the number of blocks used by the superblock (primary or backup)
1479  *      in this group.  Currently this will be only 0 or 1.
1480  */
1481 int ext3_bg_has_super(struct super_block *sb, int group)
1482 {
1483         if (EXT3_HAS_RO_COMPAT_FEATURE(sb,EXT3_FEATURE_RO_COMPAT_SPARSE_SUPER)&&
1484             !ext3_group_sparse(group))
1485                 return 0;
1486         return 1;
1487 }
1488
1489 /**
1490  *      ext3_bg_num_gdb - number of blocks used by the group table in group
1491  *      @sb: superblock for filesystem
1492  *      @group: group number to check
1493  *
1494  *      Return the number of blocks used by the group descriptor table
1495  *      (primary or backup) in this group.  In the future there may be a
1496  *      different number of descriptor blocks in each group.
1497  */
1498 unsigned long ext3_bg_num_gdb(struct super_block *sb, int group)
1499 {
1500         if (EXT3_HAS_RO_COMPAT_FEATURE(sb,EXT3_FEATURE_RO_COMPAT_SPARSE_SUPER)&&
1501             !ext3_group_sparse(group))
1502                 return 0;
1503         return EXT3_SB(sb)->s_gdb_count;
1504 }
1505
1506 #ifdef CONFIG_EXT3_CHECK
1507 /* Called at mount-time, super-block is locked */
1508 void ext3_check_blocks_bitmap (struct super_block * sb)
1509 {
1510         struct ext3_super_block *es;
1511         unsigned long desc_count, bitmap_count, x, j;
1512         unsigned long desc_blocks;
1513         struct buffer_head *bitmap_bh = NULL;
1514         struct ext3_group_desc *gdp;
1515         int i;
1516
1517         es = EXT3_SB(sb)->s_es;
1518         desc_count = 0;
1519         bitmap_count = 0;
1520         gdp = NULL;
1521         for (i = 0; i < EXT3_SB(sb)->s_groups_count; i++) {
1522                 gdp = ext3_get_group_desc (sb, i, NULL);
1523                 if (!gdp)
1524                         continue;
1525                 desc_count += le16_to_cpu(gdp->bg_free_blocks_count);
1526                 brelse(bitmap_bh);
1527                 bitmap_bh = read_block_bitmap(sb, i);
1528                 if (bitmap_bh == NULL)
1529                         continue;
1530
1531                 if (ext3_bg_has_super(sb, i) &&
1532                                 !ext3_test_bit(0, bitmap_bh->b_data))
1533                         ext3_error(sb, __FUNCTION__,
1534                                    "Superblock in group %d is marked free", i);
1535
1536                 desc_blocks = ext3_bg_num_gdb(sb, i);
1537                 for (j = 0; j < desc_blocks; j++)
1538                         if (!ext3_test_bit(j + 1, bitmap_bh->b_data))
1539                                 ext3_error(sb, __FUNCTION__,
1540                                            "Descriptor block #%ld in group "
1541                                            "%d is marked free", j, i);
1542
1543                 if (!block_in_use (le32_to_cpu(gdp->bg_block_bitmap),
1544                                                 sb, bitmap_bh->b_data))
1545                         ext3_error (sb, "ext3_check_blocks_bitmap",
1546                                     "Block bitmap for group %d is marked free",
1547                                     i);
1548
1549                 if (!block_in_use (le32_to_cpu(gdp->bg_inode_bitmap),
1550                                                 sb, bitmap_bh->b_data))
1551                         ext3_error (sb, "ext3_check_blocks_bitmap",
1552                                     "Inode bitmap for group %d is marked free",
1553                                     i);
1554
1555                 for (j = 0; j < EXT3_SB(sb)->s_itb_per_group; j++)
1556                         if (!block_in_use (le32_to_cpu(gdp->bg_inode_table) + j,
1557                                                         sb, bitmap_bh->b_data))
1558                                 ext3_error (sb, "ext3_check_blocks_bitmap",
1559                                             "Block #%d of the inode table in "
1560                                             "group %d is marked free", j, i);
1561
1562                 x = ext3_count_free(bitmap_bh, sb->s_blocksize);
1563                 if (le16_to_cpu(gdp->bg_free_blocks_count) != x)
1564                         ext3_error (sb, "ext3_check_blocks_bitmap",
1565                                     "Wrong free blocks count for group %d, "
1566                                     "stored = %d, counted = %lu", i,
1567                                     le16_to_cpu(gdp->bg_free_blocks_count), x);
1568                 bitmap_count += x;
1569         }
1570         brelse(bitmap_bh);
1571         if (le32_to_cpu(es->s_free_blocks_count) != bitmap_count)
1572                 ext3_error (sb, "ext3_check_blocks_bitmap",
1573                         "Wrong free blocks count in super block, "
1574                         "stored = %lu, counted = %lu",
1575                         (unsigned long)le32_to_cpu(es->s_free_blocks_count),
1576                         bitmap_count);
1577 }
1578 #endif