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