• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/fs/ext4/ialloc.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  *  BSD ufs-inspired inode and directory allocation by
10  *  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 <linux/time.h>
16 #include <linux/fs.h>
17 #include <linux/jbd2.h>
18 #include <linux/stat.h>
19 #include <linux/string.h>
20 #include <linux/quotaops.h>
21 #include <linux/buffer_head.h>
22 #include <linux/random.h>
23 #include <linux/bitops.h>
24 #include <linux/blkdev.h>
25 #include <asm/byteorder.h>
26 
27 #include "ext4.h"
28 #include "ext4_jbd2.h"
29 #include "xattr.h"
30 #include "acl.h"
31 
32 #include <trace/events/ext4.h>
33 
34 /*
35  * ialloc.c contains the inodes allocation and deallocation routines
36  */
37 
38 /*
39  * The free inodes are managed by bitmaps.  A file system contains several
40  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
41  * block for inodes, N blocks for the inode table and data blocks.
42  *
43  * The file system contains group descriptors which are located after the
44  * super block.  Each descriptor contains the number of the bitmap block and
45  * the free blocks count in the block.
46  */
47 
48 /*
49  * To avoid calling the atomic setbit hundreds or thousands of times, we only
50  * need to use it within a single byte (to ensure we get endianness right).
51  * We can use memset for the rest of the bitmap as there are no other users.
52  */
ext4_mark_bitmap_end(int start_bit,int end_bit,char * bitmap)53 void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
54 {
55 	int i;
56 
57 	if (start_bit >= end_bit)
58 		return;
59 
60 	ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit);
61 	for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
62 		ext4_set_bit(i, bitmap);
63 	if (i < end_bit)
64 		memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
65 }
66 
67 /* Initializes an uninitialized inode bitmap */
ext4_init_inode_bitmap(struct super_block * sb,struct buffer_head * bh,ext4_group_t block_group,struct ext4_group_desc * gdp)68 static unsigned ext4_init_inode_bitmap(struct super_block *sb,
69 				       struct buffer_head *bh,
70 				       ext4_group_t block_group,
71 				       struct ext4_group_desc *gdp)
72 {
73 	struct ext4_sb_info *sbi = EXT4_SB(sb);
74 
75 	J_ASSERT_BH(bh, buffer_locked(bh));
76 
77 	/* If checksum is bad mark all blocks and inodes use to prevent
78 	 * allocation, essentially implementing a per-group read-only flag. */
79 	if (!ext4_group_desc_csum_verify(sbi, block_group, gdp)) {
80 		ext4_error(sb, "Checksum bad for group %u", block_group);
81 		ext4_free_group_clusters_set(sb, gdp, 0);
82 		ext4_free_inodes_set(sb, gdp, 0);
83 		ext4_itable_unused_set(sb, gdp, 0);
84 		memset(bh->b_data, 0xff, sb->s_blocksize);
85 		return 0;
86 	}
87 
88 	memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8);
89 	ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb), sb->s_blocksize * 8,
90 			bh->b_data);
91 
92 	return EXT4_INODES_PER_GROUP(sb);
93 }
94 
ext4_end_bitmap_read(struct buffer_head * bh,int uptodate)95 void ext4_end_bitmap_read(struct buffer_head *bh, int uptodate)
96 {
97 	if (uptodate) {
98 		set_buffer_uptodate(bh);
99 		set_bitmap_uptodate(bh);
100 	}
101 	unlock_buffer(bh);
102 	put_bh(bh);
103 }
104 
105 /*
106  * Read the inode allocation bitmap for a given block_group, reading
107  * into the specified slot in the superblock's bitmap cache.
108  *
109  * Return buffer_head of bitmap on success or NULL.
110  */
111 static struct buffer_head *
ext4_read_inode_bitmap(struct super_block * sb,ext4_group_t block_group)112 ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group)
113 {
114 	struct ext4_group_desc *desc;
115 	struct buffer_head *bh = NULL;
116 	ext4_fsblk_t bitmap_blk;
117 
118 	desc = ext4_get_group_desc(sb, block_group, NULL);
119 	if (!desc)
120 		return NULL;
121 
122 	bitmap_blk = ext4_inode_bitmap(sb, desc);
123 	bh = sb_getblk(sb, bitmap_blk);
124 	if (unlikely(!bh)) {
125 		ext4_error(sb, "Cannot read inode bitmap - "
126 			    "block_group = %u, inode_bitmap = %llu",
127 			    block_group, bitmap_blk);
128 		return NULL;
129 	}
130 	if (bitmap_uptodate(bh))
131 		return bh;
132 
133 	lock_buffer(bh);
134 	if (bitmap_uptodate(bh)) {
135 		unlock_buffer(bh);
136 		return bh;
137 	}
138 
139 	ext4_lock_group(sb, block_group);
140 	if (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
141 		ext4_init_inode_bitmap(sb, bh, block_group, desc);
142 		set_bitmap_uptodate(bh);
143 		set_buffer_uptodate(bh);
144 		ext4_unlock_group(sb, block_group);
145 		unlock_buffer(bh);
146 		return bh;
147 	}
148 	ext4_unlock_group(sb, block_group);
149 
150 	if (buffer_uptodate(bh)) {
151 		/*
152 		 * if not uninit if bh is uptodate,
153 		 * bitmap is also uptodate
154 		 */
155 		set_bitmap_uptodate(bh);
156 		unlock_buffer(bh);
157 		return bh;
158 	}
159 	/*
160 	 * submit the buffer_head for reading
161 	 */
162 	trace_ext4_load_inode_bitmap(sb, block_group);
163 	bh->b_end_io = ext4_end_bitmap_read;
164 	get_bh(bh);
165 	submit_bh(READ, bh);
166 	wait_on_buffer(bh);
167 	if (!buffer_uptodate(bh)) {
168 		put_bh(bh);
169 		ext4_error(sb, "Cannot read inode bitmap - "
170 			   "block_group = %u, inode_bitmap = %llu",
171 			   block_group, bitmap_blk);
172 		return NULL;
173 	}
174 	return bh;
175 }
176 
177 /*
178  * NOTE! When we get the inode, we're the only people
179  * that have access to it, and as such there are no
180  * race conditions we have to worry about. The inode
181  * is not on the hash-lists, and it cannot be reached
182  * through the filesystem because the directory entry
183  * has been deleted earlier.
184  *
185  * HOWEVER: we must make sure that we get no aliases,
186  * which means that we have to call "clear_inode()"
187  * _before_ we mark the inode not in use in the inode
188  * bitmaps. Otherwise a newly created file might use
189  * the same inode number (not actually the same pointer
190  * though), and then we'd have two inodes sharing the
191  * same inode number and space on the harddisk.
192  */
ext4_free_inode(handle_t * handle,struct inode * inode)193 void ext4_free_inode(handle_t *handle, struct inode *inode)
194 {
195 	struct super_block *sb = inode->i_sb;
196 	int is_directory;
197 	unsigned long ino;
198 	struct buffer_head *bitmap_bh = NULL;
199 	struct buffer_head *bh2;
200 	ext4_group_t block_group;
201 	unsigned long bit;
202 	struct ext4_group_desc *gdp;
203 	struct ext4_super_block *es;
204 	struct ext4_sb_info *sbi;
205 	int fatal = 0, err, count, cleared;
206 
207 	if (!sb) {
208 		printk(KERN_ERR "EXT4-fs: %s:%d: inode on "
209 		       "nonexistent device\n", __func__, __LINE__);
210 		return;
211 	}
212 	if (atomic_read(&inode->i_count) > 1) {
213 		ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: count=%d",
214 			 __func__, __LINE__, inode->i_ino,
215 			 atomic_read(&inode->i_count));
216 		return;
217 	}
218 	if (inode->i_nlink) {
219 		ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: nlink=%d\n",
220 			 __func__, __LINE__, inode->i_ino, inode->i_nlink);
221 		return;
222 	}
223 	sbi = EXT4_SB(sb);
224 
225 	ino = inode->i_ino;
226 	ext4_debug("freeing inode %lu\n", ino);
227 	trace_ext4_free_inode(inode);
228 
229 	/*
230 	 * Note: we must free any quota before locking the superblock,
231 	 * as writing the quota to disk may need the lock as well.
232 	 */
233 	dquot_initialize(inode);
234 	ext4_xattr_delete_inode(handle, inode);
235 	dquot_free_inode(inode);
236 	dquot_drop(inode);
237 
238 	is_directory = S_ISDIR(inode->i_mode);
239 
240 	/* Do this BEFORE marking the inode not in use or returning an error */
241 	ext4_clear_inode(inode);
242 
243 	es = EXT4_SB(sb)->s_es;
244 	if (ino < EXT4_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
245 		ext4_error(sb, "reserved or nonexistent inode %lu", ino);
246 		goto error_return;
247 	}
248 	block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
249 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
250 	bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
251 	if (!bitmap_bh)
252 		goto error_return;
253 
254 	BUFFER_TRACE(bitmap_bh, "get_write_access");
255 	fatal = ext4_journal_get_write_access(handle, bitmap_bh);
256 	if (fatal)
257 		goto error_return;
258 
259 	fatal = -ESRCH;
260 	gdp = ext4_get_group_desc(sb, block_group, &bh2);
261 	if (gdp) {
262 		BUFFER_TRACE(bh2, "get_write_access");
263 		fatal = ext4_journal_get_write_access(handle, bh2);
264 	}
265 	ext4_lock_group(sb, block_group);
266 	cleared = ext4_test_and_clear_bit(bit, bitmap_bh->b_data);
267 	if (fatal || !cleared) {
268 		ext4_unlock_group(sb, block_group);
269 		goto out;
270 	}
271 
272 	count = ext4_free_inodes_count(sb, gdp) + 1;
273 	ext4_free_inodes_set(sb, gdp, count);
274 	if (is_directory) {
275 		count = ext4_used_dirs_count(sb, gdp) - 1;
276 		ext4_used_dirs_set(sb, gdp, count);
277 		percpu_counter_dec(&sbi->s_dirs_counter);
278 	}
279 	gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
280 	ext4_unlock_group(sb, block_group);
281 
282 	percpu_counter_inc(&sbi->s_freeinodes_counter);
283 	if (sbi->s_log_groups_per_flex) {
284 		ext4_group_t f = ext4_flex_group(sbi, block_group);
285 
286 		atomic_inc(&sbi->s_flex_groups[f].free_inodes);
287 		if (is_directory)
288 			atomic_dec(&sbi->s_flex_groups[f].used_dirs);
289 	}
290 	BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata");
291 	fatal = ext4_handle_dirty_metadata(handle, NULL, bh2);
292 out:
293 	if (cleared) {
294 		BUFFER_TRACE(bitmap_bh, "call ext4_handle_dirty_metadata");
295 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
296 		if (!fatal)
297 			fatal = err;
298 		ext4_mark_super_dirty(sb);
299 	} else
300 		ext4_error(sb, "bit already cleared for inode %lu", ino);
301 
302 error_return:
303 	brelse(bitmap_bh);
304 	ext4_std_error(sb, fatal);
305 }
306 
307 struct orlov_stats {
308 	__u64 free_clusters;
309 	__u32 free_inodes;
310 	__u32 used_dirs;
311 };
312 
313 /*
314  * Helper function for Orlov's allocator; returns critical information
315  * for a particular block group or flex_bg.  If flex_size is 1, then g
316  * is a block group number; otherwise it is flex_bg number.
317  */
get_orlov_stats(struct super_block * sb,ext4_group_t g,int flex_size,struct orlov_stats * stats)318 static void get_orlov_stats(struct super_block *sb, ext4_group_t g,
319 			    int flex_size, struct orlov_stats *stats)
320 {
321 	struct ext4_group_desc *desc;
322 	struct flex_groups *flex_group = EXT4_SB(sb)->s_flex_groups;
323 
324 	if (flex_size > 1) {
325 		stats->free_inodes = atomic_read(&flex_group[g].free_inodes);
326 		stats->free_clusters = atomic64_read(&flex_group[g].free_clusters);
327 		stats->used_dirs = atomic_read(&flex_group[g].used_dirs);
328 		return;
329 	}
330 
331 	desc = ext4_get_group_desc(sb, g, NULL);
332 	if (desc) {
333 		stats->free_inodes = ext4_free_inodes_count(sb, desc);
334 		stats->free_clusters = ext4_free_group_clusters(sb, desc);
335 		stats->used_dirs = ext4_used_dirs_count(sb, desc);
336 	} else {
337 		stats->free_inodes = 0;
338 		stats->free_clusters = 0;
339 		stats->used_dirs = 0;
340 	}
341 }
342 
343 /*
344  * Orlov's allocator for directories.
345  *
346  * We always try to spread first-level directories.
347  *
348  * If there are blockgroups with both free inodes and free blocks counts
349  * not worse than average we return one with smallest directory count.
350  * Otherwise we simply return a random group.
351  *
352  * For the rest rules look so:
353  *
354  * It's OK to put directory into a group unless
355  * it has too many directories already (max_dirs) or
356  * it has too few free inodes left (min_inodes) or
357  * it has too few free blocks left (min_blocks) or
358  * Parent's group is preferred, if it doesn't satisfy these
359  * conditions we search cyclically through the rest. If none
360  * of the groups look good we just look for a group with more
361  * free inodes than average (starting at parent's group).
362  */
363 
find_group_orlov(struct super_block * sb,struct inode * parent,ext4_group_t * group,umode_t mode,const struct qstr * qstr)364 static int find_group_orlov(struct super_block *sb, struct inode *parent,
365 			    ext4_group_t *group, umode_t mode,
366 			    const struct qstr *qstr)
367 {
368 	ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
369 	struct ext4_sb_info *sbi = EXT4_SB(sb);
370 	ext4_group_t real_ngroups = ext4_get_groups_count(sb);
371 	int inodes_per_group = EXT4_INODES_PER_GROUP(sb);
372 	unsigned int freei, avefreei, grp_free;
373 	ext4_fsblk_t freeb, avefreec;
374 	unsigned int ndirs;
375 	int max_dirs, min_inodes;
376 	ext4_grpblk_t min_clusters;
377 	ext4_group_t i, grp, g, ngroups;
378 	struct ext4_group_desc *desc;
379 	struct orlov_stats stats;
380 	int flex_size = ext4_flex_bg_size(sbi);
381 	struct dx_hash_info hinfo;
382 
383 	ngroups = real_ngroups;
384 	if (flex_size > 1) {
385 		ngroups = (real_ngroups + flex_size - 1) >>
386 			sbi->s_log_groups_per_flex;
387 		parent_group >>= sbi->s_log_groups_per_flex;
388 	}
389 
390 	freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
391 	avefreei = freei / ngroups;
392 	freeb = EXT4_C2B(sbi,
393 		percpu_counter_read_positive(&sbi->s_freeclusters_counter));
394 	avefreec = freeb;
395 	do_div(avefreec, ngroups);
396 	ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
397 
398 	if (S_ISDIR(mode) &&
399 	    ((parent == sb->s_root->d_inode) ||
400 	     (ext4_test_inode_flag(parent, EXT4_INODE_TOPDIR)))) {
401 		int best_ndir = inodes_per_group;
402 		int ret = -1;
403 
404 		if (qstr) {
405 			hinfo.hash_version = DX_HASH_HALF_MD4;
406 			hinfo.seed = sbi->s_hash_seed;
407 			ext4fs_dirhash(qstr->name, qstr->len, &hinfo);
408 			grp = hinfo.hash;
409 		} else
410 			get_random_bytes(&grp, sizeof(grp));
411 		parent_group = (unsigned)grp % ngroups;
412 		for (i = 0; i < ngroups; i++) {
413 			g = (parent_group + i) % ngroups;
414 			get_orlov_stats(sb, g, flex_size, &stats);
415 			if (!stats.free_inodes)
416 				continue;
417 			if (stats.used_dirs >= best_ndir)
418 				continue;
419 			if (stats.free_inodes < avefreei)
420 				continue;
421 			if (stats.free_clusters < avefreec)
422 				continue;
423 			grp = g;
424 			ret = 0;
425 			best_ndir = stats.used_dirs;
426 		}
427 		if (ret)
428 			goto fallback;
429 	found_flex_bg:
430 		if (flex_size == 1) {
431 			*group = grp;
432 			return 0;
433 		}
434 
435 		/*
436 		 * We pack inodes at the beginning of the flexgroup's
437 		 * inode tables.  Block allocation decisions will do
438 		 * something similar, although regular files will
439 		 * start at 2nd block group of the flexgroup.  See
440 		 * ext4_ext_find_goal() and ext4_find_near().
441 		 */
442 		grp *= flex_size;
443 		for (i = 0; i < flex_size; i++) {
444 			if (grp+i >= real_ngroups)
445 				break;
446 			desc = ext4_get_group_desc(sb, grp+i, NULL);
447 			if (desc && ext4_free_inodes_count(sb, desc)) {
448 				*group = grp+i;
449 				return 0;
450 			}
451 		}
452 		goto fallback;
453 	}
454 
455 	max_dirs = ndirs / ngroups + inodes_per_group / 16;
456 	min_inodes = avefreei - inodes_per_group*flex_size / 4;
457 	if (min_inodes < 1)
458 		min_inodes = 1;
459 	min_clusters = avefreec - EXT4_CLUSTERS_PER_GROUP(sb)*flex_size / 4;
460 
461 	/*
462 	 * Start looking in the flex group where we last allocated an
463 	 * inode for this parent directory
464 	 */
465 	if (EXT4_I(parent)->i_last_alloc_group != ~0) {
466 		parent_group = EXT4_I(parent)->i_last_alloc_group;
467 		if (flex_size > 1)
468 			parent_group >>= sbi->s_log_groups_per_flex;
469 	}
470 
471 	for (i = 0; i < ngroups; i++) {
472 		grp = (parent_group + i) % ngroups;
473 		get_orlov_stats(sb, grp, flex_size, &stats);
474 		if (stats.used_dirs >= max_dirs)
475 			continue;
476 		if (stats.free_inodes < min_inodes)
477 			continue;
478 		if (stats.free_clusters < min_clusters)
479 			continue;
480 		goto found_flex_bg;
481 	}
482 
483 fallback:
484 	ngroups = real_ngroups;
485 	avefreei = freei / ngroups;
486 fallback_retry:
487 	parent_group = EXT4_I(parent)->i_block_group;
488 	for (i = 0; i < ngroups; i++) {
489 		grp = (parent_group + i) % ngroups;
490 		desc = ext4_get_group_desc(sb, grp, NULL);
491 		if (desc) {
492 			grp_free = ext4_free_inodes_count(sb, desc);
493 			if (grp_free && grp_free >= avefreei) {
494 				*group = grp;
495 				return 0;
496 			}
497 		}
498 	}
499 
500 	if (avefreei) {
501 		/*
502 		 * The free-inodes counter is approximate, and for really small
503 		 * filesystems the above test can fail to find any blockgroups
504 		 */
505 		avefreei = 0;
506 		goto fallback_retry;
507 	}
508 
509 	return -1;
510 }
511 
find_group_other(struct super_block * sb,struct inode * parent,ext4_group_t * group,umode_t mode)512 static int find_group_other(struct super_block *sb, struct inode *parent,
513 			    ext4_group_t *group, umode_t mode)
514 {
515 	ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
516 	ext4_group_t i, last, ngroups = ext4_get_groups_count(sb);
517 	struct ext4_group_desc *desc;
518 	int flex_size = ext4_flex_bg_size(EXT4_SB(sb));
519 
520 	/*
521 	 * Try to place the inode is the same flex group as its
522 	 * parent.  If we can't find space, use the Orlov algorithm to
523 	 * find another flex group, and store that information in the
524 	 * parent directory's inode information so that use that flex
525 	 * group for future allocations.
526 	 */
527 	if (flex_size > 1) {
528 		int retry = 0;
529 
530 	try_again:
531 		parent_group &= ~(flex_size-1);
532 		last = parent_group + flex_size;
533 		if (last > ngroups)
534 			last = ngroups;
535 		for  (i = parent_group; i < last; i++) {
536 			desc = ext4_get_group_desc(sb, i, NULL);
537 			if (desc && ext4_free_inodes_count(sb, desc)) {
538 				*group = i;
539 				return 0;
540 			}
541 		}
542 		if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) {
543 			retry = 1;
544 			parent_group = EXT4_I(parent)->i_last_alloc_group;
545 			goto try_again;
546 		}
547 		/*
548 		 * If this didn't work, use the Orlov search algorithm
549 		 * to find a new flex group; we pass in the mode to
550 		 * avoid the topdir algorithms.
551 		 */
552 		*group = parent_group + flex_size;
553 		if (*group > ngroups)
554 			*group = 0;
555 		return find_group_orlov(sb, parent, group, mode, NULL);
556 	}
557 
558 	/*
559 	 * Try to place the inode in its parent directory
560 	 */
561 	*group = parent_group;
562 	desc = ext4_get_group_desc(sb, *group, NULL);
563 	if (desc && ext4_free_inodes_count(sb, desc) &&
564 	    ext4_free_group_clusters(sb, desc))
565 		return 0;
566 
567 	/*
568 	 * We're going to place this inode in a different blockgroup from its
569 	 * parent.  We want to cause files in a common directory to all land in
570 	 * the same blockgroup.  But we want files which are in a different
571 	 * directory which shares a blockgroup with our parent to land in a
572 	 * different blockgroup.
573 	 *
574 	 * So add our directory's i_ino into the starting point for the hash.
575 	 */
576 	*group = (*group + parent->i_ino) % ngroups;
577 
578 	/*
579 	 * Use a quadratic hash to find a group with a free inode and some free
580 	 * blocks.
581 	 */
582 	for (i = 1; i < ngroups; i <<= 1) {
583 		*group += i;
584 		if (*group >= ngroups)
585 			*group -= ngroups;
586 		desc = ext4_get_group_desc(sb, *group, NULL);
587 		if (desc && ext4_free_inodes_count(sb, desc) &&
588 		    ext4_free_group_clusters(sb, desc))
589 			return 0;
590 	}
591 
592 	/*
593 	 * That failed: try linear search for a free inode, even if that group
594 	 * has no free blocks.
595 	 */
596 	*group = parent_group;
597 	for (i = 0; i < ngroups; i++) {
598 		if (++*group >= ngroups)
599 			*group = 0;
600 		desc = ext4_get_group_desc(sb, *group, NULL);
601 		if (desc && ext4_free_inodes_count(sb, desc))
602 			return 0;
603 	}
604 
605 	return -1;
606 }
607 
608 /*
609  * There are two policies for allocating an inode.  If the new inode is
610  * a directory, then a forward search is made for a block group with both
611  * free space and a low directory-to-inode ratio; if that fails, then of
612  * the groups with above-average free space, that group with the fewest
613  * directories already is chosen.
614  *
615  * For other inodes, search forward from the parent directory's block
616  * group to find a free inode.
617  */
ext4_new_inode(handle_t * handle,struct inode * dir,umode_t mode,const struct qstr * qstr,__u32 goal,uid_t * owner)618 struct inode *ext4_new_inode(handle_t *handle, struct inode *dir, umode_t mode,
619 			     const struct qstr *qstr, __u32 goal, uid_t *owner)
620 {
621 	struct super_block *sb;
622 	struct buffer_head *inode_bitmap_bh = NULL;
623 	struct buffer_head *group_desc_bh;
624 	ext4_group_t ngroups, group = 0;
625 	unsigned long ino = 0;
626 	struct inode *inode;
627 	struct ext4_group_desc *gdp = NULL;
628 	struct ext4_inode_info *ei;
629 	struct ext4_sb_info *sbi;
630 	int ret2, err = 0;
631 	struct inode *ret;
632 	ext4_group_t i;
633 	ext4_group_t flex_group;
634 
635 	/* Cannot create files in a deleted directory */
636 	if (!dir || !dir->i_nlink)
637 		return ERR_PTR(-EPERM);
638 
639 	sb = dir->i_sb;
640 	ngroups = ext4_get_groups_count(sb);
641 	trace_ext4_request_inode(dir, mode);
642 	inode = new_inode(sb);
643 	if (!inode)
644 		return ERR_PTR(-ENOMEM);
645 	ei = EXT4_I(inode);
646 	sbi = EXT4_SB(sb);
647 
648 	if (!goal)
649 		goal = sbi->s_inode_goal;
650 
651 	if (goal && goal <= le32_to_cpu(sbi->s_es->s_inodes_count)) {
652 		group = (goal - 1) / EXT4_INODES_PER_GROUP(sb);
653 		ino = (goal - 1) % EXT4_INODES_PER_GROUP(sb);
654 		ret2 = 0;
655 		goto got_group;
656 	}
657 
658 	if (S_ISDIR(mode))
659 		ret2 = find_group_orlov(sb, dir, &group, mode, qstr);
660 	else
661 		ret2 = find_group_other(sb, dir, &group, mode);
662 
663 got_group:
664 	EXT4_I(dir)->i_last_alloc_group = group;
665 	err = -ENOSPC;
666 	if (ret2 == -1)
667 		goto out;
668 
669 	/*
670 	 * Normally we will only go through one pass of this loop,
671 	 * unless we get unlucky and it turns out the group we selected
672 	 * had its last inode grabbed by someone else.
673 	 */
674 	for (i = 0; i < ngroups; i++, ino = 0) {
675 		err = -EIO;
676 
677 		gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
678 		if (!gdp)
679 			goto fail;
680 
681 		brelse(inode_bitmap_bh);
682 		inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
683 		if (!inode_bitmap_bh)
684 			goto fail;
685 
686 repeat_in_this_group:
687 		ino = ext4_find_next_zero_bit((unsigned long *)
688 					      inode_bitmap_bh->b_data,
689 					      EXT4_INODES_PER_GROUP(sb), ino);
690 		if (ino >= EXT4_INODES_PER_GROUP(sb))
691 			goto next_group;
692 		if (group == 0 && (ino+1) < EXT4_FIRST_INO(sb)) {
693 			ext4_error(sb, "reserved inode found cleared - "
694 				   "inode=%lu", ino + 1);
695 			continue;
696 		}
697 		BUFFER_TRACE(inode_bitmap_bh, "get_write_access");
698 		err = ext4_journal_get_write_access(handle, inode_bitmap_bh);
699 		if (err)
700 			goto fail;
701 		ext4_lock_group(sb, group);
702 		ret2 = ext4_test_and_set_bit(ino, inode_bitmap_bh->b_data);
703 		ext4_unlock_group(sb, group);
704 		ino++;		/* the inode bitmap is zero-based */
705 		if (!ret2)
706 			goto got; /* we grabbed the inode! */
707 		if (ino < EXT4_INODES_PER_GROUP(sb))
708 			goto repeat_in_this_group;
709 next_group:
710 		if (++group == ngroups)
711 			group = 0;
712 	}
713 	err = -ENOSPC;
714 	goto out;
715 
716 got:
717 	BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
718 	err = ext4_handle_dirty_metadata(handle, NULL, inode_bitmap_bh);
719 	if (err)
720 		goto fail;
721 
722 	/* We may have to initialize the block bitmap if it isn't already */
723 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM) &&
724 	    gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
725 		struct buffer_head *block_bitmap_bh;
726 
727 		block_bitmap_bh = ext4_read_block_bitmap(sb, group);
728 		BUFFER_TRACE(block_bitmap_bh, "get block bitmap access");
729 		err = ext4_journal_get_write_access(handle, block_bitmap_bh);
730 		if (err) {
731 			brelse(block_bitmap_bh);
732 			goto fail;
733 		}
734 
735 		BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
736 		err = ext4_handle_dirty_metadata(handle, NULL, block_bitmap_bh);
737 
738 		/* recheck and clear flag under lock if we still need to */
739 		ext4_lock_group(sb, group);
740 		if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
741 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
742 			ext4_free_group_clusters_set(sb, gdp,
743 				ext4_free_clusters_after_init(sb, group, gdp));
744 			gdp->bg_checksum = ext4_group_desc_csum(sbi, group,
745 								gdp);
746 		}
747 		ext4_unlock_group(sb, group);
748 		brelse(block_bitmap_bh);
749 
750 		if (err)
751 			goto fail;
752 	}
753 
754 	BUFFER_TRACE(group_desc_bh, "get_write_access");
755 	err = ext4_journal_get_write_access(handle, group_desc_bh);
756 	if (err)
757 		goto fail;
758 
759 	/* Update the relevant bg descriptor fields */
760 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
761 		int free;
762 		struct ext4_group_info *grp = ext4_get_group_info(sb, group);
763 
764 		down_read(&grp->alloc_sem); /* protect vs itable lazyinit */
765 		ext4_lock_group(sb, group); /* while we modify the bg desc */
766 		free = EXT4_INODES_PER_GROUP(sb) -
767 			ext4_itable_unused_count(sb, gdp);
768 		if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
769 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
770 			free = 0;
771 		}
772 		/*
773 		 * Check the relative inode number against the last used
774 		 * relative inode number in this group. if it is greater
775 		 * we need to update the bg_itable_unused count
776 		 */
777 		if (ino > free)
778 			ext4_itable_unused_set(sb, gdp,
779 					(EXT4_INODES_PER_GROUP(sb) - ino));
780 		up_read(&grp->alloc_sem);
781 	} else {
782 		ext4_lock_group(sb, group);
783 	}
784 
785 	ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
786 	if (S_ISDIR(mode)) {
787 		ext4_used_dirs_set(sb, gdp, ext4_used_dirs_count(sb, gdp) + 1);
788 		if (sbi->s_log_groups_per_flex) {
789 			ext4_group_t f = ext4_flex_group(sbi, group);
790 
791 			atomic_inc(&sbi->s_flex_groups[f].used_dirs);
792 		}
793 	}
794 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
795 		gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp);
796 	}
797 	ext4_unlock_group(sb, group);
798 
799 	BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata");
800 	err = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh);
801 	if (err)
802 		goto fail;
803 
804 	percpu_counter_dec(&sbi->s_freeinodes_counter);
805 	if (S_ISDIR(mode))
806 		percpu_counter_inc(&sbi->s_dirs_counter);
807 	ext4_mark_super_dirty(sb);
808 
809 	if (sbi->s_log_groups_per_flex) {
810 		flex_group = ext4_flex_group(sbi, group);
811 		atomic_dec(&sbi->s_flex_groups[flex_group].free_inodes);
812 	}
813 	if (owner) {
814 		inode->i_mode = mode;
815 		inode->i_uid = owner[0];
816 		inode->i_gid = owner[1];
817 	} else if (test_opt(sb, GRPID)) {
818 		inode->i_mode = mode;
819 		inode->i_uid = current_fsuid();
820 		inode->i_gid = dir->i_gid;
821 	} else
822 		inode_init_owner(inode, dir, mode);
823 
824 	inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
825 	/* This is the optimal IO size (for stat), not the fs block size */
826 	inode->i_blocks = 0;
827 	inode->i_mtime = inode->i_atime = inode->i_ctime = ei->i_crtime =
828 						       ext4_current_time(inode);
829 
830 	memset(ei->i_data, 0, sizeof(ei->i_data));
831 	ei->i_dir_start_lookup = 0;
832 	ei->i_disksize = 0;
833 
834 	/* Don't inherit extent flag from directory, amongst others. */
835 	ei->i_flags =
836 		ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED);
837 	ei->i_file_acl = 0;
838 	ei->i_dtime = 0;
839 	ei->i_block_group = group;
840 	ei->i_last_alloc_group = ~0;
841 
842 	ext4_set_inode_flags(inode);
843 	if (IS_DIRSYNC(inode))
844 		ext4_handle_sync(handle);
845 	if (insert_inode_locked(inode) < 0) {
846 		/*
847 		 * Likely a bitmap corruption causing inode to be allocated
848 		 * twice.
849 		 */
850 		err = -EIO;
851 		goto fail;
852 	}
853 	spin_lock(&sbi->s_next_gen_lock);
854 	inode->i_generation = sbi->s_next_generation++;
855 	spin_unlock(&sbi->s_next_gen_lock);
856 
857 	ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
858 	ext4_set_inode_state(inode, EXT4_STATE_NEW);
859 
860 	ei->i_extra_isize = EXT4_SB(sb)->s_want_extra_isize;
861 
862 	ret = inode;
863 	dquot_initialize(inode);
864 	err = dquot_alloc_inode(inode);
865 	if (err)
866 		goto fail_drop;
867 
868 	err = ext4_init_acl(handle, inode, dir);
869 	if (err)
870 		goto fail_free_drop;
871 
872 	err = ext4_init_security(handle, inode, dir, qstr);
873 	if (err)
874 		goto fail_free_drop;
875 
876 	if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
877 		/* set extent flag only for directory, file and normal symlink*/
878 		if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) {
879 			ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
880 			ext4_ext_tree_init(handle, inode);
881 		}
882 	}
883 
884 	if (ext4_handle_valid(handle)) {
885 		ei->i_sync_tid = handle->h_transaction->t_tid;
886 		ei->i_datasync_tid = handle->h_transaction->t_tid;
887 	}
888 
889 	err = ext4_mark_inode_dirty(handle, inode);
890 	if (err) {
891 		ext4_std_error(sb, err);
892 		goto fail_free_drop;
893 	}
894 
895 	ext4_debug("allocating inode %lu\n", inode->i_ino);
896 	trace_ext4_allocate_inode(inode, dir, mode);
897 	goto really_out;
898 fail:
899 	ext4_std_error(sb, err);
900 out:
901 	iput(inode);
902 	ret = ERR_PTR(err);
903 really_out:
904 	brelse(inode_bitmap_bh);
905 	return ret;
906 
907 fail_free_drop:
908 	dquot_free_inode(inode);
909 
910 fail_drop:
911 	dquot_drop(inode);
912 	inode->i_flags |= S_NOQUOTA;
913 	clear_nlink(inode);
914 	unlock_new_inode(inode);
915 	iput(inode);
916 	brelse(inode_bitmap_bh);
917 	return ERR_PTR(err);
918 }
919 
920 /* Verify that we are loading a valid orphan from disk */
ext4_orphan_get(struct super_block * sb,unsigned long ino)921 struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino)
922 {
923 	unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
924 	ext4_group_t block_group;
925 	int bit;
926 	struct buffer_head *bitmap_bh;
927 	struct inode *inode = NULL;
928 	long err = -EIO;
929 
930 	/* Error cases - e2fsck has already cleaned up for us */
931 	if (ino > max_ino) {
932 		ext4_warning(sb, "bad orphan ino %lu!  e2fsck was run?", ino);
933 		goto error;
934 	}
935 
936 	block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
937 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
938 	bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
939 	if (!bitmap_bh) {
940 		ext4_warning(sb, "inode bitmap error for orphan %lu", ino);
941 		goto error;
942 	}
943 
944 	/* Having the inode bit set should be a 100% indicator that this
945 	 * is a valid orphan (no e2fsck run on fs).  Orphans also include
946 	 * inodes that were being truncated, so we can't check i_nlink==0.
947 	 */
948 	if (!ext4_test_bit(bit, bitmap_bh->b_data))
949 		goto bad_orphan;
950 
951 	inode = ext4_iget(sb, ino);
952 	if (IS_ERR(inode))
953 		goto iget_failed;
954 
955 	/*
956 	 * If the orphans has i_nlinks > 0 then it should be able to be
957 	 * truncated, otherwise it won't be removed from the orphan list
958 	 * during processing and an infinite loop will result.
959 	 */
960 	if (inode->i_nlink && !ext4_can_truncate(inode))
961 		goto bad_orphan;
962 
963 	if (NEXT_ORPHAN(inode) > max_ino)
964 		goto bad_orphan;
965 	brelse(bitmap_bh);
966 	return inode;
967 
968 iget_failed:
969 	err = PTR_ERR(inode);
970 	inode = NULL;
971 bad_orphan:
972 	ext4_warning(sb, "bad orphan inode %lu!  e2fsck was run?", ino);
973 	printk(KERN_NOTICE "ext4_test_bit(bit=%d, block=%llu) = %d\n",
974 	       bit, (unsigned long long)bitmap_bh->b_blocknr,
975 	       ext4_test_bit(bit, bitmap_bh->b_data));
976 	printk(KERN_NOTICE "inode=%p\n", inode);
977 	if (inode) {
978 		printk(KERN_NOTICE "is_bad_inode(inode)=%d\n",
979 		       is_bad_inode(inode));
980 		printk(KERN_NOTICE "NEXT_ORPHAN(inode)=%u\n",
981 		       NEXT_ORPHAN(inode));
982 		printk(KERN_NOTICE "max_ino=%lu\n", max_ino);
983 		printk(KERN_NOTICE "i_nlink=%u\n", inode->i_nlink);
984 		/* Avoid freeing blocks if we got a bad deleted inode */
985 		if (inode->i_nlink == 0)
986 			inode->i_blocks = 0;
987 		iput(inode);
988 	}
989 	brelse(bitmap_bh);
990 error:
991 	return ERR_PTR(err);
992 }
993 
ext4_count_free_inodes(struct super_block * sb)994 unsigned long ext4_count_free_inodes(struct super_block *sb)
995 {
996 	unsigned long desc_count;
997 	struct ext4_group_desc *gdp;
998 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
999 #ifdef EXT4FS_DEBUG
1000 	struct ext4_super_block *es;
1001 	unsigned long bitmap_count, x;
1002 	struct buffer_head *bitmap_bh = NULL;
1003 
1004 	es = EXT4_SB(sb)->s_es;
1005 	desc_count = 0;
1006 	bitmap_count = 0;
1007 	gdp = NULL;
1008 	for (i = 0; i < ngroups; i++) {
1009 		gdp = ext4_get_group_desc(sb, i, NULL);
1010 		if (!gdp)
1011 			continue;
1012 		desc_count += ext4_free_inodes_count(sb, gdp);
1013 		brelse(bitmap_bh);
1014 		bitmap_bh = ext4_read_inode_bitmap(sb, i);
1015 		if (!bitmap_bh)
1016 			continue;
1017 
1018 		x = ext4_count_free(bitmap_bh->b_data,
1019 				    EXT4_INODES_PER_GROUP(sb) / 8);
1020 		printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n",
1021 			(unsigned long) i, ext4_free_inodes_count(sb, gdp), x);
1022 		bitmap_count += x;
1023 	}
1024 	brelse(bitmap_bh);
1025 	printk(KERN_DEBUG "ext4_count_free_inodes: "
1026 	       "stored = %u, computed = %lu, %lu\n",
1027 	       le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count);
1028 	return desc_count;
1029 #else
1030 	desc_count = 0;
1031 	for (i = 0; i < ngroups; i++) {
1032 		gdp = ext4_get_group_desc(sb, i, NULL);
1033 		if (!gdp)
1034 			continue;
1035 		desc_count += ext4_free_inodes_count(sb, gdp);
1036 		cond_resched();
1037 	}
1038 	return desc_count;
1039 #endif
1040 }
1041 
1042 /* Called at mount-time, super-block is locked */
ext4_count_dirs(struct super_block * sb)1043 unsigned long ext4_count_dirs(struct super_block * sb)
1044 {
1045 	unsigned long count = 0;
1046 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1047 
1048 	for (i = 0; i < ngroups; i++) {
1049 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
1050 		if (!gdp)
1051 			continue;
1052 		count += ext4_used_dirs_count(sb, gdp);
1053 	}
1054 	return count;
1055 }
1056 
1057 /*
1058  * Zeroes not yet zeroed inode table - just write zeroes through the whole
1059  * inode table. Must be called without any spinlock held. The only place
1060  * where it is called from on active part of filesystem is ext4lazyinit
1061  * thread, so we do not need any special locks, however we have to prevent
1062  * inode allocation from the current group, so we take alloc_sem lock, to
1063  * block ext4_new_inode() until we are finished.
1064  */
ext4_init_inode_table(struct super_block * sb,ext4_group_t group,int barrier)1065 int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,
1066 				 int barrier)
1067 {
1068 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
1069 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1070 	struct ext4_group_desc *gdp = NULL;
1071 	struct buffer_head *group_desc_bh;
1072 	handle_t *handle;
1073 	ext4_fsblk_t blk;
1074 	int num, ret = 0, used_blks = 0;
1075 
1076 	/* This should not happen, but just to be sure check this */
1077 	if (sb->s_flags & MS_RDONLY) {
1078 		ret = 1;
1079 		goto out;
1080 	}
1081 
1082 	gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
1083 	if (!gdp)
1084 		goto out;
1085 
1086 	/*
1087 	 * We do not need to lock this, because we are the only one
1088 	 * handling this flag.
1089 	 */
1090 	if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))
1091 		goto out;
1092 
1093 	handle = ext4_journal_start_sb(sb, 1);
1094 	if (IS_ERR(handle)) {
1095 		ret = PTR_ERR(handle);
1096 		goto out;
1097 	}
1098 
1099 	down_write(&grp->alloc_sem);
1100 	/*
1101 	 * If inode bitmap was already initialized there may be some
1102 	 * used inodes so we need to skip blocks with used inodes in
1103 	 * inode table.
1104 	 */
1105 	if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)))
1106 		used_blks = DIV_ROUND_UP((EXT4_INODES_PER_GROUP(sb) -
1107 			    ext4_itable_unused_count(sb, gdp)),
1108 			    sbi->s_inodes_per_block);
1109 
1110 	if ((used_blks < 0) || (used_blks > sbi->s_itb_per_group)) {
1111 		ext4_error(sb, "Something is wrong with group %u: "
1112 			   "used itable blocks: %d; "
1113 			   "itable unused count: %u",
1114 			   group, used_blks,
1115 			   ext4_itable_unused_count(sb, gdp));
1116 		ret = 1;
1117 		goto err_out;
1118 	}
1119 
1120 	blk = ext4_inode_table(sb, gdp) + used_blks;
1121 	num = sbi->s_itb_per_group - used_blks;
1122 
1123 	BUFFER_TRACE(group_desc_bh, "get_write_access");
1124 	ret = ext4_journal_get_write_access(handle,
1125 					    group_desc_bh);
1126 	if (ret)
1127 		goto err_out;
1128 
1129 	/*
1130 	 * Skip zeroout if the inode table is full. But we set the ZEROED
1131 	 * flag anyway, because obviously, when it is full it does not need
1132 	 * further zeroing.
1133 	 */
1134 	if (unlikely(num == 0))
1135 		goto skip_zeroout;
1136 
1137 	ext4_debug("going to zero out inode table in group %d\n",
1138 		   group);
1139 	ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS);
1140 	if (ret < 0)
1141 		goto err_out;
1142 	if (barrier)
1143 		blkdev_issue_flush(sb->s_bdev, GFP_NOFS, NULL);
1144 
1145 skip_zeroout:
1146 	ext4_lock_group(sb, group);
1147 	gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED);
1148 	gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp);
1149 	ext4_unlock_group(sb, group);
1150 
1151 	BUFFER_TRACE(group_desc_bh,
1152 		     "call ext4_handle_dirty_metadata");
1153 	ret = ext4_handle_dirty_metadata(handle, NULL,
1154 					 group_desc_bh);
1155 
1156 err_out:
1157 	up_write(&grp->alloc_sem);
1158 	ext4_journal_stop(handle);
1159 out:
1160 	return ret;
1161 }
1162