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