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