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