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