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