xref: /linux/fs/ext2/balloc.c (revision e5c86679d5e864947a52fb31e45a425dea3e7fa9)
1 /*
2  *  linux/fs/ext2/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 "ext2.h"
15 #include <linux/quotaops.h>
16 #include <linux/slab.h>
17 #include <linux/sched.h>
18 #include <linux/cred.h>
19 #include <linux/buffer_head.h>
20 #include <linux/capability.h>
21 
22 /*
23  * balloc.c contains the blocks allocation and deallocation routines
24  */
25 
26 /*
27  * The free blocks are managed by bitmaps.  A file system contains several
28  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
29  * block for inodes, N blocks for the inode table and data blocks.
30  *
31  * The file system contains group descriptors which are located after the
32  * super block.  Each descriptor contains the number of the bitmap block and
33  * the free blocks count in the block.  The descriptors are loaded in memory
34  * when a file system is mounted (see ext2_fill_super).
35  */
36 
37 
38 #define in_range(b, first, len)	((b) >= (first) && (b) <= (first) + (len) - 1)
39 
40 struct ext2_group_desc * ext2_get_group_desc(struct super_block * sb,
41 					     unsigned int block_group,
42 					     struct buffer_head ** bh)
43 {
44 	unsigned long group_desc;
45 	unsigned long offset;
46 	struct ext2_group_desc * desc;
47 	struct ext2_sb_info *sbi = EXT2_SB(sb);
48 
49 	if (block_group >= sbi->s_groups_count) {
50 		ext2_error (sb, "ext2_get_group_desc",
51 			    "block_group >= groups_count - "
52 			    "block_group = %d, groups_count = %lu",
53 			    block_group, sbi->s_groups_count);
54 
55 		return NULL;
56 	}
57 
58 	group_desc = block_group >> EXT2_DESC_PER_BLOCK_BITS(sb);
59 	offset = block_group & (EXT2_DESC_PER_BLOCK(sb) - 1);
60 	if (!sbi->s_group_desc[group_desc]) {
61 		ext2_error (sb, "ext2_get_group_desc",
62 			    "Group descriptor not loaded - "
63 			    "block_group = %d, group_desc = %lu, desc = %lu",
64 			     block_group, group_desc, offset);
65 		return NULL;
66 	}
67 
68 	desc = (struct ext2_group_desc *) sbi->s_group_desc[group_desc]->b_data;
69 	if (bh)
70 		*bh = sbi->s_group_desc[group_desc];
71 	return desc + offset;
72 }
73 
74 static int ext2_valid_block_bitmap(struct super_block *sb,
75 					struct ext2_group_desc *desc,
76 					unsigned int block_group,
77 					struct buffer_head *bh)
78 {
79 	ext2_grpblk_t offset;
80 	ext2_grpblk_t next_zero_bit;
81 	ext2_fsblk_t bitmap_blk;
82 	ext2_fsblk_t group_first_block;
83 
84 	group_first_block = ext2_group_first_block_no(sb, block_group);
85 
86 	/* check whether block bitmap block number is set */
87 	bitmap_blk = le32_to_cpu(desc->bg_block_bitmap);
88 	offset = bitmap_blk - group_first_block;
89 	if (!ext2_test_bit(offset, bh->b_data))
90 		/* bad block bitmap */
91 		goto err_out;
92 
93 	/* check whether the inode bitmap block number is set */
94 	bitmap_blk = le32_to_cpu(desc->bg_inode_bitmap);
95 	offset = bitmap_blk - group_first_block;
96 	if (!ext2_test_bit(offset, bh->b_data))
97 		/* bad block bitmap */
98 		goto err_out;
99 
100 	/* check whether the inode table block number is set */
101 	bitmap_blk = le32_to_cpu(desc->bg_inode_table);
102 	offset = bitmap_blk - group_first_block;
103 	next_zero_bit = ext2_find_next_zero_bit(bh->b_data,
104 				offset + EXT2_SB(sb)->s_itb_per_group,
105 				offset);
106 	if (next_zero_bit >= offset + EXT2_SB(sb)->s_itb_per_group)
107 		/* good bitmap for inode tables */
108 		return 1;
109 
110 err_out:
111 	ext2_error(sb, __func__,
112 			"Invalid block bitmap - "
113 			"block_group = %d, block = %lu",
114 			block_group, bitmap_blk);
115 	return 0;
116 }
117 
118 /*
119  * Read the bitmap for a given block_group,and validate the
120  * bits for block/inode/inode tables are set in the bitmaps
121  *
122  * Return buffer_head on success or NULL in case of failure.
123  */
124 static struct buffer_head *
125 read_block_bitmap(struct super_block *sb, unsigned int block_group)
126 {
127 	struct ext2_group_desc * desc;
128 	struct buffer_head * bh = NULL;
129 	ext2_fsblk_t bitmap_blk;
130 
131 	desc = ext2_get_group_desc(sb, block_group, NULL);
132 	if (!desc)
133 		return NULL;
134 	bitmap_blk = le32_to_cpu(desc->bg_block_bitmap);
135 	bh = sb_getblk(sb, bitmap_blk);
136 	if (unlikely(!bh)) {
137 		ext2_error(sb, __func__,
138 			    "Cannot read block bitmap - "
139 			    "block_group = %d, block_bitmap = %u",
140 			    block_group, le32_to_cpu(desc->bg_block_bitmap));
141 		return NULL;
142 	}
143 	if (likely(bh_uptodate_or_lock(bh)))
144 		return bh;
145 
146 	if (bh_submit_read(bh) < 0) {
147 		brelse(bh);
148 		ext2_error(sb, __func__,
149 			    "Cannot read block bitmap - "
150 			    "block_group = %d, block_bitmap = %u",
151 			    block_group, le32_to_cpu(desc->bg_block_bitmap));
152 		return NULL;
153 	}
154 
155 	ext2_valid_block_bitmap(sb, desc, block_group, bh);
156 	/*
157 	 * file system mounted not to panic on error, continue with corrupt
158 	 * bitmap
159 	 */
160 	return bh;
161 }
162 
163 static void group_adjust_blocks(struct super_block *sb, int group_no,
164 	struct ext2_group_desc *desc, struct buffer_head *bh, int count)
165 {
166 	if (count) {
167 		struct ext2_sb_info *sbi = EXT2_SB(sb);
168 		unsigned free_blocks;
169 
170 		spin_lock(sb_bgl_lock(sbi, group_no));
171 		free_blocks = le16_to_cpu(desc->bg_free_blocks_count);
172 		desc->bg_free_blocks_count = cpu_to_le16(free_blocks + count);
173 		spin_unlock(sb_bgl_lock(sbi, group_no));
174 		mark_buffer_dirty(bh);
175 	}
176 }
177 
178 /*
179  * The reservation window structure operations
180  * --------------------------------------------
181  * Operations include:
182  * dump, find, add, remove, is_empty, find_next_reservable_window, etc.
183  *
184  * We use a red-black tree to represent per-filesystem reservation
185  * windows.
186  *
187  */
188 
189 /**
190  * __rsv_window_dump() -- Dump the filesystem block allocation reservation map
191  * @rb_root:		root of per-filesystem reservation rb tree
192  * @verbose:		verbose mode
193  * @fn:			function which wishes to dump the reservation map
194  *
195  * If verbose is turned on, it will print the whole block reservation
196  * windows(start, end). Otherwise, it will only print out the "bad" windows,
197  * those windows that overlap with their immediate neighbors.
198  */
199 #if 1
200 static void __rsv_window_dump(struct rb_root *root, int verbose,
201 			      const char *fn)
202 {
203 	struct rb_node *n;
204 	struct ext2_reserve_window_node *rsv, *prev;
205 	int bad;
206 
207 restart:
208 	n = rb_first(root);
209 	bad = 0;
210 	prev = NULL;
211 
212 	printk("Block Allocation Reservation Windows Map (%s):\n", fn);
213 	while (n) {
214 		rsv = rb_entry(n, struct ext2_reserve_window_node, rsv_node);
215 		if (verbose)
216 			printk("reservation window 0x%p "
217 				"start: %lu, end: %lu\n",
218 				rsv, rsv->rsv_start, rsv->rsv_end);
219 		if (rsv->rsv_start && rsv->rsv_start >= rsv->rsv_end) {
220 			printk("Bad reservation %p (start >= end)\n",
221 			       rsv);
222 			bad = 1;
223 		}
224 		if (prev && prev->rsv_end >= rsv->rsv_start) {
225 			printk("Bad reservation %p (prev->end >= start)\n",
226 			       rsv);
227 			bad = 1;
228 		}
229 		if (bad) {
230 			if (!verbose) {
231 				printk("Restarting reservation walk in verbose mode\n");
232 				verbose = 1;
233 				goto restart;
234 			}
235 		}
236 		n = rb_next(n);
237 		prev = rsv;
238 	}
239 	printk("Window map complete.\n");
240 	BUG_ON(bad);
241 }
242 #define rsv_window_dump(root, verbose) \
243 	__rsv_window_dump((root), (verbose), __func__)
244 #else
245 #define rsv_window_dump(root, verbose) do {} while (0)
246 #endif
247 
248 /**
249  * goal_in_my_reservation()
250  * @rsv:		inode's reservation window
251  * @grp_goal:		given goal block relative to the allocation block group
252  * @group:		the current allocation block group
253  * @sb:			filesystem super block
254  *
255  * Test if the given goal block (group relative) is within the file's
256  * own block reservation window range.
257  *
258  * If the reservation window is outside the goal allocation group, return 0;
259  * grp_goal (given goal block) could be -1, which means no specific
260  * goal block. In this case, always return 1.
261  * If the goal block is within the reservation window, return 1;
262  * otherwise, return 0;
263  */
264 static int
265 goal_in_my_reservation(struct ext2_reserve_window *rsv, ext2_grpblk_t grp_goal,
266 			unsigned int group, struct super_block * sb)
267 {
268 	ext2_fsblk_t group_first_block, group_last_block;
269 
270 	group_first_block = ext2_group_first_block_no(sb, group);
271 	group_last_block = group_first_block + EXT2_BLOCKS_PER_GROUP(sb) - 1;
272 
273 	if ((rsv->_rsv_start > group_last_block) ||
274 	    (rsv->_rsv_end < group_first_block))
275 		return 0;
276 	if ((grp_goal >= 0) && ((grp_goal + group_first_block < rsv->_rsv_start)
277 		|| (grp_goal + group_first_block > rsv->_rsv_end)))
278 		return 0;
279 	return 1;
280 }
281 
282 /**
283  * search_reserve_window()
284  * @rb_root:		root of reservation tree
285  * @goal:		target allocation block
286  *
287  * Find the reserved window which includes the goal, or the previous one
288  * if the goal is not in any window.
289  * Returns NULL if there are no windows or if all windows start after the goal.
290  */
291 static struct ext2_reserve_window_node *
292 search_reserve_window(struct rb_root *root, ext2_fsblk_t goal)
293 {
294 	struct rb_node *n = root->rb_node;
295 	struct ext2_reserve_window_node *rsv;
296 
297 	if (!n)
298 		return NULL;
299 
300 	do {
301 		rsv = rb_entry(n, struct ext2_reserve_window_node, rsv_node);
302 
303 		if (goal < rsv->rsv_start)
304 			n = n->rb_left;
305 		else if (goal > rsv->rsv_end)
306 			n = n->rb_right;
307 		else
308 			return rsv;
309 	} while (n);
310 	/*
311 	 * We've fallen off the end of the tree: the goal wasn't inside
312 	 * any particular node.  OK, the previous node must be to one
313 	 * side of the interval containing the goal.  If it's the RHS,
314 	 * we need to back up one.
315 	 */
316 	if (rsv->rsv_start > goal) {
317 		n = rb_prev(&rsv->rsv_node);
318 		rsv = rb_entry(n, struct ext2_reserve_window_node, rsv_node);
319 	}
320 	return rsv;
321 }
322 
323 /*
324  * ext2_rsv_window_add() -- Insert a window to the block reservation rb tree.
325  * @sb:			super block
326  * @rsv:		reservation window to add
327  *
328  * Must be called with rsv_lock held.
329  */
330 void ext2_rsv_window_add(struct super_block *sb,
331 		    struct ext2_reserve_window_node *rsv)
332 {
333 	struct rb_root *root = &EXT2_SB(sb)->s_rsv_window_root;
334 	struct rb_node *node = &rsv->rsv_node;
335 	ext2_fsblk_t start = rsv->rsv_start;
336 
337 	struct rb_node ** p = &root->rb_node;
338 	struct rb_node * parent = NULL;
339 	struct ext2_reserve_window_node *this;
340 
341 	while (*p)
342 	{
343 		parent = *p;
344 		this = rb_entry(parent, struct ext2_reserve_window_node, rsv_node);
345 
346 		if (start < this->rsv_start)
347 			p = &(*p)->rb_left;
348 		else if (start > this->rsv_end)
349 			p = &(*p)->rb_right;
350 		else {
351 			rsv_window_dump(root, 1);
352 			BUG();
353 		}
354 	}
355 
356 	rb_link_node(node, parent, p);
357 	rb_insert_color(node, root);
358 }
359 
360 /**
361  * rsv_window_remove() -- unlink a window from the reservation rb tree
362  * @sb:			super block
363  * @rsv:		reservation window to remove
364  *
365  * Mark the block reservation window as not allocated, and unlink it
366  * from the filesystem reservation window rb tree. Must be called with
367  * rsv_lock held.
368  */
369 static void rsv_window_remove(struct super_block *sb,
370 			      struct ext2_reserve_window_node *rsv)
371 {
372 	rsv->rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
373 	rsv->rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
374 	rsv->rsv_alloc_hit = 0;
375 	rb_erase(&rsv->rsv_node, &EXT2_SB(sb)->s_rsv_window_root);
376 }
377 
378 /*
379  * rsv_is_empty() -- Check if the reservation window is allocated.
380  * @rsv:		given reservation window to check
381  *
382  * returns 1 if the end block is EXT2_RESERVE_WINDOW_NOT_ALLOCATED.
383  */
384 static inline int rsv_is_empty(struct ext2_reserve_window *rsv)
385 {
386 	/* a valid reservation end block could not be 0 */
387 	return (rsv->_rsv_end == EXT2_RESERVE_WINDOW_NOT_ALLOCATED);
388 }
389 
390 /**
391  * ext2_init_block_alloc_info()
392  * @inode:		file inode structure
393  *
394  * Allocate and initialize the  reservation window structure, and
395  * link the window to the ext2 inode structure at last
396  *
397  * The reservation window structure is only dynamically allocated
398  * and linked to ext2 inode the first time the open file
399  * needs a new block. So, before every ext2_new_block(s) call, for
400  * regular files, we should check whether the reservation window
401  * structure exists or not. In the latter case, this function is called.
402  * Fail to do so will result in block reservation being turned off for that
403  * open file.
404  *
405  * This function is called from ext2_get_blocks_handle(), also called
406  * when setting the reservation window size through ioctl before the file
407  * is open for write (needs block allocation).
408  *
409  * Needs truncate_mutex protection prior to calling this function.
410  */
411 void ext2_init_block_alloc_info(struct inode *inode)
412 {
413 	struct ext2_inode_info *ei = EXT2_I(inode);
414 	struct ext2_block_alloc_info *block_i;
415 	struct super_block *sb = inode->i_sb;
416 
417 	block_i = kmalloc(sizeof(*block_i), GFP_NOFS);
418 	if (block_i) {
419 		struct ext2_reserve_window_node *rsv = &block_i->rsv_window_node;
420 
421 		rsv->rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
422 		rsv->rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
423 
424 	 	/*
425 		 * if filesystem is mounted with NORESERVATION, the goal
426 		 * reservation window size is set to zero to indicate
427 		 * block reservation is off
428 		 */
429 		if (!test_opt(sb, RESERVATION))
430 			rsv->rsv_goal_size = 0;
431 		else
432 			rsv->rsv_goal_size = EXT2_DEFAULT_RESERVE_BLOCKS;
433 		rsv->rsv_alloc_hit = 0;
434 		block_i->last_alloc_logical_block = 0;
435 		block_i->last_alloc_physical_block = 0;
436 	}
437 	ei->i_block_alloc_info = block_i;
438 }
439 
440 /**
441  * ext2_discard_reservation()
442  * @inode:		inode
443  *
444  * Discard(free) block reservation window on last file close, or truncate
445  * or at last iput().
446  *
447  * It is being called in three cases:
448  * 	ext2_release_file(): last writer closes the file
449  * 	ext2_clear_inode(): last iput(), when nobody links to this file.
450  * 	ext2_truncate(): when the block indirect map is about to change.
451  */
452 void ext2_discard_reservation(struct inode *inode)
453 {
454 	struct ext2_inode_info *ei = EXT2_I(inode);
455 	struct ext2_block_alloc_info *block_i = ei->i_block_alloc_info;
456 	struct ext2_reserve_window_node *rsv;
457 	spinlock_t *rsv_lock = &EXT2_SB(inode->i_sb)->s_rsv_window_lock;
458 
459 	if (!block_i)
460 		return;
461 
462 	rsv = &block_i->rsv_window_node;
463 	if (!rsv_is_empty(&rsv->rsv_window)) {
464 		spin_lock(rsv_lock);
465 		if (!rsv_is_empty(&rsv->rsv_window))
466 			rsv_window_remove(inode->i_sb, rsv);
467 		spin_unlock(rsv_lock);
468 	}
469 }
470 
471 /**
472  * ext2_free_blocks() -- Free given blocks and update quota and i_blocks
473  * @inode:		inode
474  * @block:		start physical block to free
475  * @count:		number of blocks to free
476  */
477 void ext2_free_blocks (struct inode * inode, unsigned long block,
478 		       unsigned long count)
479 {
480 	struct buffer_head *bitmap_bh = NULL;
481 	struct buffer_head * bh2;
482 	unsigned long block_group;
483 	unsigned long bit;
484 	unsigned long i;
485 	unsigned long overflow;
486 	struct super_block * sb = inode->i_sb;
487 	struct ext2_sb_info * sbi = EXT2_SB(sb);
488 	struct ext2_group_desc * desc;
489 	struct ext2_super_block * es = sbi->s_es;
490 	unsigned freed = 0, group_freed;
491 
492 	if (block < le32_to_cpu(es->s_first_data_block) ||
493 	    block + count < block ||
494 	    block + count > le32_to_cpu(es->s_blocks_count)) {
495 		ext2_error (sb, "ext2_free_blocks",
496 			    "Freeing blocks not in datazone - "
497 			    "block = %lu, count = %lu", block, count);
498 		goto error_return;
499 	}
500 
501 	ext2_debug ("freeing block(s) %lu-%lu\n", block, block + count - 1);
502 
503 do_more:
504 	overflow = 0;
505 	block_group = (block - le32_to_cpu(es->s_first_data_block)) /
506 		      EXT2_BLOCKS_PER_GROUP(sb);
507 	bit = (block - le32_to_cpu(es->s_first_data_block)) %
508 		      EXT2_BLOCKS_PER_GROUP(sb);
509 	/*
510 	 * Check to see if we are freeing blocks across a group
511 	 * boundary.
512 	 */
513 	if (bit + count > EXT2_BLOCKS_PER_GROUP(sb)) {
514 		overflow = bit + count - EXT2_BLOCKS_PER_GROUP(sb);
515 		count -= overflow;
516 	}
517 	brelse(bitmap_bh);
518 	bitmap_bh = read_block_bitmap(sb, block_group);
519 	if (!bitmap_bh)
520 		goto error_return;
521 
522 	desc = ext2_get_group_desc (sb, block_group, &bh2);
523 	if (!desc)
524 		goto error_return;
525 
526 	if (in_range (le32_to_cpu(desc->bg_block_bitmap), block, count) ||
527 	    in_range (le32_to_cpu(desc->bg_inode_bitmap), block, count) ||
528 	    in_range (block, le32_to_cpu(desc->bg_inode_table),
529 		      sbi->s_itb_per_group) ||
530 	    in_range (block + count - 1, le32_to_cpu(desc->bg_inode_table),
531 		      sbi->s_itb_per_group)) {
532 		ext2_error (sb, "ext2_free_blocks",
533 			    "Freeing blocks in system zones - "
534 			    "Block = %lu, count = %lu",
535 			    block, count);
536 		goto error_return;
537 	}
538 
539 	for (i = 0, group_freed = 0; i < count; i++) {
540 		if (!ext2_clear_bit_atomic(sb_bgl_lock(sbi, block_group),
541 						bit + i, bitmap_bh->b_data)) {
542 			ext2_error(sb, __func__,
543 				"bit already cleared for block %lu", block + i);
544 		} else {
545 			group_freed++;
546 		}
547 	}
548 
549 	mark_buffer_dirty(bitmap_bh);
550 	if (sb->s_flags & MS_SYNCHRONOUS)
551 		sync_dirty_buffer(bitmap_bh);
552 
553 	group_adjust_blocks(sb, block_group, desc, bh2, group_freed);
554 	freed += group_freed;
555 
556 	if (overflow) {
557 		block += count;
558 		count = overflow;
559 		goto do_more;
560 	}
561 error_return:
562 	brelse(bitmap_bh);
563 	if (freed) {
564 		percpu_counter_add(&sbi->s_freeblocks_counter, freed);
565 		dquot_free_block_nodirty(inode, freed);
566 		mark_inode_dirty(inode);
567 	}
568 }
569 
570 /**
571  * bitmap_search_next_usable_block()
572  * @start:		the starting block (group relative) of the search
573  * @bh:			bufferhead contains the block group bitmap
574  * @maxblocks:		the ending block (group relative) of the reservation
575  *
576  * The bitmap search --- search forward through the actual bitmap on disk until
577  * we find a bit free.
578  */
579 static ext2_grpblk_t
580 bitmap_search_next_usable_block(ext2_grpblk_t start, struct buffer_head *bh,
581 					ext2_grpblk_t maxblocks)
582 {
583 	ext2_grpblk_t next;
584 
585 	next = ext2_find_next_zero_bit(bh->b_data, maxblocks, start);
586 	if (next >= maxblocks)
587 		return -1;
588 	return next;
589 }
590 
591 /**
592  * find_next_usable_block()
593  * @start:		the starting block (group relative) to find next
594  * 			allocatable block in bitmap.
595  * @bh:			bufferhead contains the block group bitmap
596  * @maxblocks:		the ending block (group relative) for the search
597  *
598  * Find an allocatable block in a bitmap.  We perform the "most
599  * appropriate allocation" algorithm of looking for a free block near
600  * the initial goal; then for a free byte somewhere in the bitmap;
601  * then for any free bit in the bitmap.
602  */
603 static ext2_grpblk_t
604 find_next_usable_block(int start, struct buffer_head *bh, int maxblocks)
605 {
606 	ext2_grpblk_t here, next;
607 	char *p, *r;
608 
609 	if (start > 0) {
610 		/*
611 		 * The goal was occupied; search forward for a free
612 		 * block within the next XX blocks.
613 		 *
614 		 * end_goal is more or less random, but it has to be
615 		 * less than EXT2_BLOCKS_PER_GROUP. Aligning up to the
616 		 * next 64-bit boundary is simple..
617 		 */
618 		ext2_grpblk_t end_goal = (start + 63) & ~63;
619 		if (end_goal > maxblocks)
620 			end_goal = maxblocks;
621 		here = ext2_find_next_zero_bit(bh->b_data, end_goal, start);
622 		if (here < end_goal)
623 			return here;
624 		ext2_debug("Bit not found near goal\n");
625 	}
626 
627 	here = start;
628 	if (here < 0)
629 		here = 0;
630 
631 	p = ((char *)bh->b_data) + (here >> 3);
632 	r = memscan(p, 0, ((maxblocks + 7) >> 3) - (here >> 3));
633 	next = (r - ((char *)bh->b_data)) << 3;
634 
635 	if (next < maxblocks && next >= here)
636 		return next;
637 
638 	here = bitmap_search_next_usable_block(here, bh, maxblocks);
639 	return here;
640 }
641 
642 /**
643  * ext2_try_to_allocate()
644  * @sb:			superblock
645  * @group:		given allocation block group
646  * @bitmap_bh:		bufferhead holds the block bitmap
647  * @grp_goal:		given target block within the group
648  * @count:		target number of blocks to allocate
649  * @my_rsv:		reservation window
650  *
651  * Attempt to allocate blocks within a give range. Set the range of allocation
652  * first, then find the first free bit(s) from the bitmap (within the range),
653  * and at last, allocate the blocks by claiming the found free bit as allocated.
654  *
655  * To set the range of this allocation:
656  * 	if there is a reservation window, only try to allocate block(s)
657  * 	from the file's own reservation window;
658  * 	Otherwise, the allocation range starts from the give goal block,
659  * 	ends at the block group's last block.
660  *
661  * If we failed to allocate the desired block then we may end up crossing to a
662  * new bitmap.
663  */
664 static int
665 ext2_try_to_allocate(struct super_block *sb, int group,
666 			struct buffer_head *bitmap_bh, ext2_grpblk_t grp_goal,
667 			unsigned long *count,
668 			struct ext2_reserve_window *my_rsv)
669 {
670 	ext2_fsblk_t group_first_block;
671        	ext2_grpblk_t start, end;
672 	unsigned long num = 0;
673 
674 	/* we do allocation within the reservation window if we have a window */
675 	if (my_rsv) {
676 		group_first_block = ext2_group_first_block_no(sb, group);
677 		if (my_rsv->_rsv_start >= group_first_block)
678 			start = my_rsv->_rsv_start - group_first_block;
679 		else
680 			/* reservation window cross group boundary */
681 			start = 0;
682 		end = my_rsv->_rsv_end - group_first_block + 1;
683 		if (end > EXT2_BLOCKS_PER_GROUP(sb))
684 			/* reservation window crosses group boundary */
685 			end = EXT2_BLOCKS_PER_GROUP(sb);
686 		if ((start <= grp_goal) && (grp_goal < end))
687 			start = grp_goal;
688 		else
689 			grp_goal = -1;
690 	} else {
691 		if (grp_goal > 0)
692 			start = grp_goal;
693 		else
694 			start = 0;
695 		end = EXT2_BLOCKS_PER_GROUP(sb);
696 	}
697 
698 	BUG_ON(start > EXT2_BLOCKS_PER_GROUP(sb));
699 
700 repeat:
701 	if (grp_goal < 0) {
702 		grp_goal = find_next_usable_block(start, bitmap_bh, end);
703 		if (grp_goal < 0)
704 			goto fail_access;
705 		if (!my_rsv) {
706 			int i;
707 
708 			for (i = 0; i < 7 && grp_goal > start &&
709 					!ext2_test_bit(grp_goal - 1,
710 					     		bitmap_bh->b_data);
711 			     		i++, grp_goal--)
712 				;
713 		}
714 	}
715 	start = grp_goal;
716 
717 	if (ext2_set_bit_atomic(sb_bgl_lock(EXT2_SB(sb), group), grp_goal,
718 			       				bitmap_bh->b_data)) {
719 		/*
720 		 * The block was allocated by another thread, or it was
721 		 * allocated and then freed by another thread
722 		 */
723 		start++;
724 		grp_goal++;
725 		if (start >= end)
726 			goto fail_access;
727 		goto repeat;
728 	}
729 	num++;
730 	grp_goal++;
731 	while (num < *count && grp_goal < end
732 		&& !ext2_set_bit_atomic(sb_bgl_lock(EXT2_SB(sb), group),
733 					grp_goal, bitmap_bh->b_data)) {
734 		num++;
735 		grp_goal++;
736 	}
737 	*count = num;
738 	return grp_goal - num;
739 fail_access:
740 	*count = num;
741 	return -1;
742 }
743 
744 /**
745  * 	find_next_reservable_window():
746  *		find a reservable space within the given range.
747  *		It does not allocate the reservation window for now:
748  *		alloc_new_reservation() will do the work later.
749  *
750  * 	@search_head: the head of the searching list;
751  *		This is not necessarily the list head of the whole filesystem
752  *
753  *		We have both head and start_block to assist the search
754  *		for the reservable space. The list starts from head,
755  *		but we will shift to the place where start_block is,
756  *		then start from there, when looking for a reservable space.
757  *
758  * 	@size: the target new reservation window size
759  *
760  * 	@group_first_block: the first block we consider to start
761  *			the real search from
762  *
763  * 	@last_block:
764  *		the maximum block number that our goal reservable space
765  *		could start from. This is normally the last block in this
766  *		group. The search will end when we found the start of next
767  *		possible reservable space is out of this boundary.
768  *		This could handle the cross boundary reservation window
769  *		request.
770  *
771  * 	basically we search from the given range, rather than the whole
772  * 	reservation double linked list, (start_block, last_block)
773  * 	to find a free region that is of my size and has not
774  * 	been reserved.
775  *
776  */
777 static int find_next_reservable_window(
778 				struct ext2_reserve_window_node *search_head,
779 				struct ext2_reserve_window_node *my_rsv,
780 				struct super_block * sb,
781 				ext2_fsblk_t start_block,
782 				ext2_fsblk_t last_block)
783 {
784 	struct rb_node *next;
785 	struct ext2_reserve_window_node *rsv, *prev;
786 	ext2_fsblk_t cur;
787 	int size = my_rsv->rsv_goal_size;
788 
789 	/* TODO: make the start of the reservation window byte-aligned */
790 	/* cur = *start_block & ~7;*/
791 	cur = start_block;
792 	rsv = search_head;
793 	if (!rsv)
794 		return -1;
795 
796 	while (1) {
797 		if (cur <= rsv->rsv_end)
798 			cur = rsv->rsv_end + 1;
799 
800 		/* TODO?
801 		 * in the case we could not find a reservable space
802 		 * that is what is expected, during the re-search, we could
803 		 * remember what's the largest reservable space we could have
804 		 * and return that one.
805 		 *
806 		 * For now it will fail if we could not find the reservable
807 		 * space with expected-size (or more)...
808 		 */
809 		if (cur > last_block)
810 			return -1;		/* fail */
811 
812 		prev = rsv;
813 		next = rb_next(&rsv->rsv_node);
814 		rsv = rb_entry(next,struct ext2_reserve_window_node,rsv_node);
815 
816 		/*
817 		 * Reached the last reservation, we can just append to the
818 		 * previous one.
819 		 */
820 		if (!next)
821 			break;
822 
823 		if (cur + size <= rsv->rsv_start) {
824 			/*
825 			 * Found a reserveable space big enough.  We could
826 			 * have a reservation across the group boundary here
827 		 	 */
828 			break;
829 		}
830 	}
831 	/*
832 	 * we come here either :
833 	 * when we reach the end of the whole list,
834 	 * and there is empty reservable space after last entry in the list.
835 	 * append it to the end of the list.
836 	 *
837 	 * or we found one reservable space in the middle of the list,
838 	 * return the reservation window that we could append to.
839 	 * succeed.
840 	 */
841 
842 	if ((prev != my_rsv) && (!rsv_is_empty(&my_rsv->rsv_window)))
843 		rsv_window_remove(sb, my_rsv);
844 
845 	/*
846 	 * Let's book the whole available window for now.  We will check the
847 	 * disk bitmap later and then, if there are free blocks then we adjust
848 	 * the window size if it's larger than requested.
849 	 * Otherwise, we will remove this node from the tree next time
850 	 * call find_next_reservable_window.
851 	 */
852 	my_rsv->rsv_start = cur;
853 	my_rsv->rsv_end = cur + size - 1;
854 	my_rsv->rsv_alloc_hit = 0;
855 
856 	if (prev != my_rsv)
857 		ext2_rsv_window_add(sb, my_rsv);
858 
859 	return 0;
860 }
861 
862 /**
863  * 	alloc_new_reservation()--allocate a new reservation window
864  *
865  *		To make a new reservation, we search part of the filesystem
866  *		reservation list (the list that inside the group). We try to
867  *		allocate a new reservation window near the allocation goal,
868  *		or the beginning of the group, if there is no goal.
869  *
870  *		We first find a reservable space after the goal, then from
871  *		there, we check the bitmap for the first free block after
872  *		it. If there is no free block until the end of group, then the
873  *		whole group is full, we failed. Otherwise, check if the free
874  *		block is inside the expected reservable space, if so, we
875  *		succeed.
876  *		If the first free block is outside the reservable space, then
877  *		start from the first free block, we search for next available
878  *		space, and go on.
879  *
880  *	on succeed, a new reservation will be found and inserted into the list
881  *	It contains at least one free block, and it does not overlap with other
882  *	reservation windows.
883  *
884  *	failed: we failed to find a reservation window in this group
885  *
886  *	@rsv: the reservation
887  *
888  *	@grp_goal: The goal (group-relative).  It is where the search for a
889  *		free reservable space should start from.
890  *		if we have a goal(goal >0 ), then start from there,
891  *		no goal(goal = -1), we start from the first block
892  *		of the group.
893  *
894  *	@sb: the super block
895  *	@group: the group we are trying to allocate in
896  *	@bitmap_bh: the block group block bitmap
897  *
898  */
899 static int alloc_new_reservation(struct ext2_reserve_window_node *my_rsv,
900 		ext2_grpblk_t grp_goal, struct super_block *sb,
901 		unsigned int group, struct buffer_head *bitmap_bh)
902 {
903 	struct ext2_reserve_window_node *search_head;
904 	ext2_fsblk_t group_first_block, group_end_block, start_block;
905 	ext2_grpblk_t first_free_block;
906 	struct rb_root *fs_rsv_root = &EXT2_SB(sb)->s_rsv_window_root;
907 	unsigned long size;
908 	int ret;
909 	spinlock_t *rsv_lock = &EXT2_SB(sb)->s_rsv_window_lock;
910 
911 	group_first_block = ext2_group_first_block_no(sb, group);
912 	group_end_block = group_first_block + (EXT2_BLOCKS_PER_GROUP(sb) - 1);
913 
914 	if (grp_goal < 0)
915 		start_block = group_first_block;
916 	else
917 		start_block = grp_goal + group_first_block;
918 
919 	size = my_rsv->rsv_goal_size;
920 
921 	if (!rsv_is_empty(&my_rsv->rsv_window)) {
922 		/*
923 		 * if the old reservation is cross group boundary
924 		 * and if the goal is inside the old reservation window,
925 		 * we will come here when we just failed to allocate from
926 		 * the first part of the window. We still have another part
927 		 * that belongs to the next group. In this case, there is no
928 		 * point to discard our window and try to allocate a new one
929 		 * in this group(which will fail). we should
930 		 * keep the reservation window, just simply move on.
931 		 *
932 		 * Maybe we could shift the start block of the reservation
933 		 * window to the first block of next group.
934 		 */
935 
936 		if ((my_rsv->rsv_start <= group_end_block) &&
937 				(my_rsv->rsv_end > group_end_block) &&
938 				(start_block >= my_rsv->rsv_start))
939 			return -1;
940 
941 		if ((my_rsv->rsv_alloc_hit >
942 		     (my_rsv->rsv_end - my_rsv->rsv_start + 1) / 2)) {
943 			/*
944 			 * if the previously allocation hit ratio is
945 			 * greater than 1/2, then we double the size of
946 			 * the reservation window the next time,
947 			 * otherwise we keep the same size window
948 			 */
949 			size = size * 2;
950 			if (size > EXT2_MAX_RESERVE_BLOCKS)
951 				size = EXT2_MAX_RESERVE_BLOCKS;
952 			my_rsv->rsv_goal_size= size;
953 		}
954 	}
955 
956 	spin_lock(rsv_lock);
957 	/*
958 	 * shift the search start to the window near the goal block
959 	 */
960 	search_head = search_reserve_window(fs_rsv_root, start_block);
961 
962 	/*
963 	 * find_next_reservable_window() simply finds a reservable window
964 	 * inside the given range(start_block, group_end_block).
965 	 *
966 	 * To make sure the reservation window has a free bit inside it, we
967 	 * need to check the bitmap after we found a reservable window.
968 	 */
969 retry:
970 	ret = find_next_reservable_window(search_head, my_rsv, sb,
971 						start_block, group_end_block);
972 
973 	if (ret == -1) {
974 		if (!rsv_is_empty(&my_rsv->rsv_window))
975 			rsv_window_remove(sb, my_rsv);
976 		spin_unlock(rsv_lock);
977 		return -1;
978 	}
979 
980 	/*
981 	 * On success, find_next_reservable_window() returns the
982 	 * reservation window where there is a reservable space after it.
983 	 * Before we reserve this reservable space, we need
984 	 * to make sure there is at least a free block inside this region.
985 	 *
986 	 * Search the first free bit on the block bitmap.  Search starts from
987 	 * the start block of the reservable space we just found.
988 	 */
989 	spin_unlock(rsv_lock);
990 	first_free_block = bitmap_search_next_usable_block(
991 			my_rsv->rsv_start - group_first_block,
992 			bitmap_bh, group_end_block - group_first_block + 1);
993 
994 	if (first_free_block < 0) {
995 		/*
996 		 * no free block left on the bitmap, no point
997 		 * to reserve the space. return failed.
998 		 */
999 		spin_lock(rsv_lock);
1000 		if (!rsv_is_empty(&my_rsv->rsv_window))
1001 			rsv_window_remove(sb, my_rsv);
1002 		spin_unlock(rsv_lock);
1003 		return -1;		/* failed */
1004 	}
1005 
1006 	start_block = first_free_block + group_first_block;
1007 	/*
1008 	 * check if the first free block is within the
1009 	 * free space we just reserved
1010 	 */
1011 	if (start_block >= my_rsv->rsv_start && start_block <= my_rsv->rsv_end)
1012 		return 0;		/* success */
1013 	/*
1014 	 * if the first free bit we found is out of the reservable space
1015 	 * continue search for next reservable space,
1016 	 * start from where the free block is,
1017 	 * we also shift the list head to where we stopped last time
1018 	 */
1019 	search_head = my_rsv;
1020 	spin_lock(rsv_lock);
1021 	goto retry;
1022 }
1023 
1024 /**
1025  * try_to_extend_reservation()
1026  * @my_rsv:		given reservation window
1027  * @sb:			super block
1028  * @size:		the delta to extend
1029  *
1030  * Attempt to expand the reservation window large enough to have
1031  * required number of free blocks
1032  *
1033  * Since ext2_try_to_allocate() will always allocate blocks within
1034  * the reservation window range, if the window size is too small,
1035  * multiple blocks allocation has to stop at the end of the reservation
1036  * window. To make this more efficient, given the total number of
1037  * blocks needed and the current size of the window, we try to
1038  * expand the reservation window size if necessary on a best-effort
1039  * basis before ext2_new_blocks() tries to allocate blocks.
1040  */
1041 static void try_to_extend_reservation(struct ext2_reserve_window_node *my_rsv,
1042 			struct super_block *sb, int size)
1043 {
1044 	struct ext2_reserve_window_node *next_rsv;
1045 	struct rb_node *next;
1046 	spinlock_t *rsv_lock = &EXT2_SB(sb)->s_rsv_window_lock;
1047 
1048 	if (!spin_trylock(rsv_lock))
1049 		return;
1050 
1051 	next = rb_next(&my_rsv->rsv_node);
1052 
1053 	if (!next)
1054 		my_rsv->rsv_end += size;
1055 	else {
1056 		next_rsv = rb_entry(next, struct ext2_reserve_window_node, rsv_node);
1057 
1058 		if ((next_rsv->rsv_start - my_rsv->rsv_end - 1) >= size)
1059 			my_rsv->rsv_end += size;
1060 		else
1061 			my_rsv->rsv_end = next_rsv->rsv_start - 1;
1062 	}
1063 	spin_unlock(rsv_lock);
1064 }
1065 
1066 /**
1067  * ext2_try_to_allocate_with_rsv()
1068  * @sb:			superblock
1069  * @group:		given allocation block group
1070  * @bitmap_bh:		bufferhead holds the block bitmap
1071  * @grp_goal:		given target block within the group
1072  * @count:		target number of blocks to allocate
1073  * @my_rsv:		reservation window
1074  *
1075  * This is the main function used to allocate a new block and its reservation
1076  * window.
1077  *
1078  * Each time when a new block allocation is need, first try to allocate from
1079  * its own reservation.  If it does not have a reservation window, instead of
1080  * looking for a free bit on bitmap first, then look up the reservation list to
1081  * see if it is inside somebody else's reservation window, we try to allocate a
1082  * reservation window for it starting from the goal first. Then do the block
1083  * allocation within the reservation window.
1084  *
1085  * This will avoid keeping on searching the reservation list again and
1086  * again when somebody is looking for a free block (without
1087  * reservation), and there are lots of free blocks, but they are all
1088  * being reserved.
1089  *
1090  * We use a red-black tree for the per-filesystem reservation list.
1091  */
1092 static ext2_grpblk_t
1093 ext2_try_to_allocate_with_rsv(struct super_block *sb, unsigned int group,
1094 			struct buffer_head *bitmap_bh, ext2_grpblk_t grp_goal,
1095 			struct ext2_reserve_window_node * my_rsv,
1096 			unsigned long *count)
1097 {
1098 	ext2_fsblk_t group_first_block, group_last_block;
1099 	ext2_grpblk_t ret = 0;
1100 	unsigned long num = *count;
1101 
1102 	/*
1103 	 * we don't deal with reservation when
1104 	 * filesystem is mounted without reservation
1105 	 * or the file is not a regular file
1106 	 * or last attempt to allocate a block with reservation turned on failed
1107 	 */
1108 	if (my_rsv == NULL) {
1109 		return ext2_try_to_allocate(sb, group, bitmap_bh,
1110 						grp_goal, count, NULL);
1111 	}
1112 	/*
1113 	 * grp_goal is a group relative block number (if there is a goal)
1114 	 * 0 <= grp_goal < EXT2_BLOCKS_PER_GROUP(sb)
1115 	 * first block is a filesystem wide block number
1116 	 * first block is the block number of the first block in this group
1117 	 */
1118 	group_first_block = ext2_group_first_block_no(sb, group);
1119 	group_last_block = group_first_block + (EXT2_BLOCKS_PER_GROUP(sb) - 1);
1120 
1121 	/*
1122 	 * Basically we will allocate a new block from inode's reservation
1123 	 * window.
1124 	 *
1125 	 * We need to allocate a new reservation window, if:
1126 	 * a) inode does not have a reservation window; or
1127 	 * b) last attempt to allocate a block from existing reservation
1128 	 *    failed; or
1129 	 * c) we come here with a goal and with a reservation window
1130 	 *
1131 	 * We do not need to allocate a new reservation window if we come here
1132 	 * at the beginning with a goal and the goal is inside the window, or
1133 	 * we don't have a goal but already have a reservation window.
1134 	 * then we could go to allocate from the reservation window directly.
1135 	 */
1136 	while (1) {
1137 		if (rsv_is_empty(&my_rsv->rsv_window) || (ret < 0) ||
1138 			!goal_in_my_reservation(&my_rsv->rsv_window,
1139 						grp_goal, group, sb)) {
1140 			if (my_rsv->rsv_goal_size < *count)
1141 				my_rsv->rsv_goal_size = *count;
1142 			ret = alloc_new_reservation(my_rsv, grp_goal, sb,
1143 							group, bitmap_bh);
1144 			if (ret < 0)
1145 				break;			/* failed */
1146 
1147 			if (!goal_in_my_reservation(&my_rsv->rsv_window,
1148 							grp_goal, group, sb))
1149 				grp_goal = -1;
1150 		} else if (grp_goal >= 0) {
1151 			int curr = my_rsv->rsv_end -
1152 					(grp_goal + group_first_block) + 1;
1153 
1154 			if (curr < *count)
1155 				try_to_extend_reservation(my_rsv, sb,
1156 							*count - curr);
1157 		}
1158 
1159 		if ((my_rsv->rsv_start > group_last_block) ||
1160 				(my_rsv->rsv_end < group_first_block)) {
1161 			rsv_window_dump(&EXT2_SB(sb)->s_rsv_window_root, 1);
1162 			BUG();
1163 		}
1164 		ret = ext2_try_to_allocate(sb, group, bitmap_bh, grp_goal,
1165 					   &num, &my_rsv->rsv_window);
1166 		if (ret >= 0) {
1167 			my_rsv->rsv_alloc_hit += num;
1168 			*count = num;
1169 			break;				/* succeed */
1170 		}
1171 		num = *count;
1172 	}
1173 	return ret;
1174 }
1175 
1176 /**
1177  * ext2_has_free_blocks()
1178  * @sbi:		in-core super block structure.
1179  *
1180  * Check if filesystem has at least 1 free block available for allocation.
1181  */
1182 static int ext2_has_free_blocks(struct ext2_sb_info *sbi)
1183 {
1184 	ext2_fsblk_t free_blocks, root_blocks;
1185 
1186 	free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
1187 	root_blocks = le32_to_cpu(sbi->s_es->s_r_blocks_count);
1188 	if (free_blocks < root_blocks + 1 && !capable(CAP_SYS_RESOURCE) &&
1189 		!uid_eq(sbi->s_resuid, current_fsuid()) &&
1190 		(gid_eq(sbi->s_resgid, GLOBAL_ROOT_GID) ||
1191 		 !in_group_p (sbi->s_resgid))) {
1192 		return 0;
1193 	}
1194 	return 1;
1195 }
1196 
1197 /*
1198  * Returns 1 if the passed-in block region is valid; 0 if some part overlaps
1199  * with filesystem metadata blocksi.
1200  */
1201 int ext2_data_block_valid(struct ext2_sb_info *sbi, ext2_fsblk_t start_blk,
1202 			  unsigned int count)
1203 {
1204 	if ((start_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
1205 	    (start_blk + count < start_blk) ||
1206 	    (start_blk > le32_to_cpu(sbi->s_es->s_blocks_count)))
1207 		return 0;
1208 
1209 	/* Ensure we do not step over superblock */
1210 	if ((start_blk <= sbi->s_sb_block) &&
1211 	    (start_blk + count >= sbi->s_sb_block))
1212 		return 0;
1213 
1214 
1215 	return 1;
1216 }
1217 
1218 /*
1219  * ext2_new_blocks() -- core block(s) allocation function
1220  * @inode:		file inode
1221  * @goal:		given target block(filesystem wide)
1222  * @count:		target number of blocks to allocate
1223  * @errp:		error code
1224  *
1225  * ext2_new_blocks uses a goal block to assist allocation.  If the goal is
1226  * free, or there is a free block within 32 blocks of the goal, that block
1227  * is allocated.  Otherwise a forward search is made for a free block; within
1228  * each block group the search first looks for an entire free byte in the block
1229  * bitmap, and then for any free bit if that fails.
1230  * This function also updates quota and i_blocks field.
1231  */
1232 ext2_fsblk_t ext2_new_blocks(struct inode *inode, ext2_fsblk_t goal,
1233 		    unsigned long *count, int *errp)
1234 {
1235 	struct buffer_head *bitmap_bh = NULL;
1236 	struct buffer_head *gdp_bh;
1237 	int group_no;
1238 	int goal_group;
1239 	ext2_grpblk_t grp_target_blk;	/* blockgroup relative goal block */
1240 	ext2_grpblk_t grp_alloc_blk;	/* blockgroup-relative allocated block*/
1241 	ext2_fsblk_t ret_block;		/* filesyetem-wide allocated block */
1242 	int bgi;			/* blockgroup iteration index */
1243 	int performed_allocation = 0;
1244 	ext2_grpblk_t free_blocks;	/* number of free blocks in a group */
1245 	struct super_block *sb;
1246 	struct ext2_group_desc *gdp;
1247 	struct ext2_super_block *es;
1248 	struct ext2_sb_info *sbi;
1249 	struct ext2_reserve_window_node *my_rsv = NULL;
1250 	struct ext2_block_alloc_info *block_i;
1251 	unsigned short windowsz = 0;
1252 	unsigned long ngroups;
1253 	unsigned long num = *count;
1254 	int ret;
1255 
1256 	*errp = -ENOSPC;
1257 	sb = inode->i_sb;
1258 
1259 	/*
1260 	 * Check quota for allocation of this block.
1261 	 */
1262 	ret = dquot_alloc_block(inode, num);
1263 	if (ret) {
1264 		*errp = ret;
1265 		return 0;
1266 	}
1267 
1268 	sbi = EXT2_SB(sb);
1269 	es = EXT2_SB(sb)->s_es;
1270 	ext2_debug("goal=%lu.\n", goal);
1271 	/*
1272 	 * Allocate a block from reservation only when
1273 	 * filesystem is mounted with reservation(default,-o reservation), and
1274 	 * it's a regular file, and
1275 	 * the desired window size is greater than 0 (One could use ioctl
1276 	 * command EXT2_IOC_SETRSVSZ to set the window size to 0 to turn off
1277 	 * reservation on that particular file)
1278 	 */
1279 	block_i = EXT2_I(inode)->i_block_alloc_info;
1280 	if (block_i) {
1281 		windowsz = block_i->rsv_window_node.rsv_goal_size;
1282 		if (windowsz > 0)
1283 			my_rsv = &block_i->rsv_window_node;
1284 	}
1285 
1286 	if (!ext2_has_free_blocks(sbi)) {
1287 		*errp = -ENOSPC;
1288 		goto out;
1289 	}
1290 
1291 	/*
1292 	 * First, test whether the goal block is free.
1293 	 */
1294 	if (goal < le32_to_cpu(es->s_first_data_block) ||
1295 	    goal >= le32_to_cpu(es->s_blocks_count))
1296 		goal = le32_to_cpu(es->s_first_data_block);
1297 	group_no = (goal - le32_to_cpu(es->s_first_data_block)) /
1298 			EXT2_BLOCKS_PER_GROUP(sb);
1299 	goal_group = group_no;
1300 retry_alloc:
1301 	gdp = ext2_get_group_desc(sb, group_no, &gdp_bh);
1302 	if (!gdp)
1303 		goto io_error;
1304 
1305 	free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
1306 	/*
1307 	 * if there is not enough free blocks to make a new resevation
1308 	 * turn off reservation for this allocation
1309 	 */
1310 	if (my_rsv && (free_blocks < windowsz)
1311 		&& (free_blocks > 0)
1312 		&& (rsv_is_empty(&my_rsv->rsv_window)))
1313 		my_rsv = NULL;
1314 
1315 	if (free_blocks > 0) {
1316 		grp_target_blk = ((goal - le32_to_cpu(es->s_first_data_block)) %
1317 				EXT2_BLOCKS_PER_GROUP(sb));
1318 		bitmap_bh = read_block_bitmap(sb, group_no);
1319 		if (!bitmap_bh)
1320 			goto io_error;
1321 		grp_alloc_blk = ext2_try_to_allocate_with_rsv(sb, group_no,
1322 					bitmap_bh, grp_target_blk,
1323 					my_rsv, &num);
1324 		if (grp_alloc_blk >= 0)
1325 			goto allocated;
1326 	}
1327 
1328 	ngroups = EXT2_SB(sb)->s_groups_count;
1329 	smp_rmb();
1330 
1331 	/*
1332 	 * Now search the rest of the groups.  We assume that
1333 	 * group_no and gdp correctly point to the last group visited.
1334 	 */
1335 	for (bgi = 0; bgi < ngroups; bgi++) {
1336 		group_no++;
1337 		if (group_no >= ngroups)
1338 			group_no = 0;
1339 		gdp = ext2_get_group_desc(sb, group_no, &gdp_bh);
1340 		if (!gdp)
1341 			goto io_error;
1342 
1343 		free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
1344 		/*
1345 		 * skip this group (and avoid loading bitmap) if there
1346 		 * are no free blocks
1347 		 */
1348 		if (!free_blocks)
1349 			continue;
1350 		/*
1351 		 * skip this group if the number of
1352 		 * free blocks is less than half of the reservation
1353 		 * window size.
1354 		 */
1355 		if (my_rsv && (free_blocks <= (windowsz/2)))
1356 			continue;
1357 
1358 		brelse(bitmap_bh);
1359 		bitmap_bh = read_block_bitmap(sb, group_no);
1360 		if (!bitmap_bh)
1361 			goto io_error;
1362 		/*
1363 		 * try to allocate block(s) from this group, without a goal(-1).
1364 		 */
1365 		grp_alloc_blk = ext2_try_to_allocate_with_rsv(sb, group_no,
1366 					bitmap_bh, -1, my_rsv, &num);
1367 		if (grp_alloc_blk >= 0)
1368 			goto allocated;
1369 	}
1370 	/*
1371 	 * We may end up a bogus earlier ENOSPC error due to
1372 	 * filesystem is "full" of reservations, but
1373 	 * there maybe indeed free blocks available on disk
1374 	 * In this case, we just forget about the reservations
1375 	 * just do block allocation as without reservations.
1376 	 */
1377 	if (my_rsv) {
1378 		my_rsv = NULL;
1379 		windowsz = 0;
1380 		group_no = goal_group;
1381 		goto retry_alloc;
1382 	}
1383 	/* No space left on the device */
1384 	*errp = -ENOSPC;
1385 	goto out;
1386 
1387 allocated:
1388 
1389 	ext2_debug("using block group %d(%d)\n",
1390 			group_no, gdp->bg_free_blocks_count);
1391 
1392 	ret_block = grp_alloc_blk + ext2_group_first_block_no(sb, group_no);
1393 
1394 	if (in_range(le32_to_cpu(gdp->bg_block_bitmap), ret_block, num) ||
1395 	    in_range(le32_to_cpu(gdp->bg_inode_bitmap), ret_block, num) ||
1396 	    in_range(ret_block, le32_to_cpu(gdp->bg_inode_table),
1397 		      EXT2_SB(sb)->s_itb_per_group) ||
1398 	    in_range(ret_block + num - 1, le32_to_cpu(gdp->bg_inode_table),
1399 		      EXT2_SB(sb)->s_itb_per_group)) {
1400 		ext2_error(sb, "ext2_new_blocks",
1401 			    "Allocating block in system zone - "
1402 			    "blocks from "E2FSBLK", length %lu",
1403 			    ret_block, num);
1404 		/*
1405 		 * ext2_try_to_allocate marked the blocks we allocated as in
1406 		 * use.  So we may want to selectively mark some of the blocks
1407 		 * as free
1408 		 */
1409 		goto retry_alloc;
1410 	}
1411 
1412 	performed_allocation = 1;
1413 
1414 	if (ret_block + num - 1 >= le32_to_cpu(es->s_blocks_count)) {
1415 		ext2_error(sb, "ext2_new_blocks",
1416 			    "block("E2FSBLK") >= blocks count(%d) - "
1417 			    "block_group = %d, es == %p ", ret_block,
1418 			le32_to_cpu(es->s_blocks_count), group_no, es);
1419 		goto out;
1420 	}
1421 
1422 	group_adjust_blocks(sb, group_no, gdp, gdp_bh, -num);
1423 	percpu_counter_sub(&sbi->s_freeblocks_counter, num);
1424 
1425 	mark_buffer_dirty(bitmap_bh);
1426 	if (sb->s_flags & MS_SYNCHRONOUS)
1427 		sync_dirty_buffer(bitmap_bh);
1428 
1429 	*errp = 0;
1430 	brelse(bitmap_bh);
1431 	if (num < *count) {
1432 		dquot_free_block_nodirty(inode, *count-num);
1433 		mark_inode_dirty(inode);
1434 		*count = num;
1435 	}
1436 	return ret_block;
1437 
1438 io_error:
1439 	*errp = -EIO;
1440 out:
1441 	/*
1442 	 * Undo the block allocation
1443 	 */
1444 	if (!performed_allocation) {
1445 		dquot_free_block_nodirty(inode, *count);
1446 		mark_inode_dirty(inode);
1447 	}
1448 	brelse(bitmap_bh);
1449 	return 0;
1450 }
1451 
1452 ext2_fsblk_t ext2_new_block(struct inode *inode, unsigned long goal, int *errp)
1453 {
1454 	unsigned long count = 1;
1455 
1456 	return ext2_new_blocks(inode, goal, &count, errp);
1457 }
1458 
1459 #ifdef EXT2FS_DEBUG
1460 
1461 unsigned long ext2_count_free(struct buffer_head *map, unsigned int numchars)
1462 {
1463 	return numchars * BITS_PER_BYTE - memweight(map->b_data, numchars);
1464 }
1465 
1466 #endif  /*  EXT2FS_DEBUG  */
1467 
1468 unsigned long ext2_count_free_blocks (struct super_block * sb)
1469 {
1470 	struct ext2_group_desc * desc;
1471 	unsigned long desc_count = 0;
1472 	int i;
1473 #ifdef EXT2FS_DEBUG
1474 	unsigned long bitmap_count, x;
1475 	struct ext2_super_block *es;
1476 
1477 	es = EXT2_SB(sb)->s_es;
1478 	desc_count = 0;
1479 	bitmap_count = 0;
1480 	desc = NULL;
1481 	for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
1482 		struct buffer_head *bitmap_bh;
1483 		desc = ext2_get_group_desc (sb, i, NULL);
1484 		if (!desc)
1485 			continue;
1486 		desc_count += le16_to_cpu(desc->bg_free_blocks_count);
1487 		bitmap_bh = read_block_bitmap(sb, i);
1488 		if (!bitmap_bh)
1489 			continue;
1490 
1491 		x = ext2_count_free(bitmap_bh, sb->s_blocksize);
1492 		printk ("group %d: stored = %d, counted = %lu\n",
1493 			i, le16_to_cpu(desc->bg_free_blocks_count), x);
1494 		bitmap_count += x;
1495 		brelse(bitmap_bh);
1496 	}
1497 	printk("ext2_count_free_blocks: stored = %lu, computed = %lu, %lu\n",
1498 		(long)le32_to_cpu(es->s_free_blocks_count),
1499 		desc_count, bitmap_count);
1500 	return bitmap_count;
1501 #else
1502         for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
1503                 desc = ext2_get_group_desc (sb, i, NULL);
1504                 if (!desc)
1505                         continue;
1506                 desc_count += le16_to_cpu(desc->bg_free_blocks_count);
1507 	}
1508 	return desc_count;
1509 #endif
1510 }
1511 
1512 static inline int test_root(int a, int b)
1513 {
1514 	int num = b;
1515 
1516 	while (a > num)
1517 		num *= b;
1518 	return num == a;
1519 }
1520 
1521 static int ext2_group_sparse(int group)
1522 {
1523 	if (group <= 1)
1524 		return 1;
1525 	return (test_root(group, 3) || test_root(group, 5) ||
1526 		test_root(group, 7));
1527 }
1528 
1529 /**
1530  *	ext2_bg_has_super - number of blocks used by the superblock in group
1531  *	@sb: superblock for filesystem
1532  *	@group: group number to check
1533  *
1534  *	Return the number of blocks used by the superblock (primary or backup)
1535  *	in this group.  Currently this will be only 0 or 1.
1536  */
1537 int ext2_bg_has_super(struct super_block *sb, int group)
1538 {
1539 	if (EXT2_HAS_RO_COMPAT_FEATURE(sb,EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)&&
1540 	    !ext2_group_sparse(group))
1541 		return 0;
1542 	return 1;
1543 }
1544 
1545 /**
1546  *	ext2_bg_num_gdb - number of blocks used by the group table in group
1547  *	@sb: superblock for filesystem
1548  *	@group: group number to check
1549  *
1550  *	Return the number of blocks used by the group descriptor table
1551  *	(primary or backup) in this group.  In the future there may be a
1552  *	different number of descriptor blocks in each group.
1553  */
1554 unsigned long ext2_bg_num_gdb(struct super_block *sb, int group)
1555 {
1556 	return ext2_bg_has_super(sb, group) ? EXT2_SB(sb)->s_gdb_count : 0;
1557 }
1558 
1559