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 	ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
785 	if (S_ISDIR(mode)) {
786 		ext4_used_dirs_set(sb, gdp, ext4_used_dirs_count(sb, gdp) + 1);
787 		if (sbi->s_log_groups_per_flex) {
788 			ext4_group_t f = ext4_flex_group(sbi, group);
789 
790 			atomic_inc(&sbi->s_flex_groups[f].used_dirs);
791 		}
792 	}
793 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
794 		gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp);
795 	}
796 	ext4_unlock_group(sb, group);
797 
798 	BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata");
799 	err = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh);
800 	if (err)
801 		goto fail;
802 
803 	percpu_counter_dec(&sbi->s_freeinodes_counter);
804 	if (S_ISDIR(mode))
805 		percpu_counter_inc(&sbi->s_dirs_counter);
806 	ext4_mark_super_dirty(sb);
807 
808 	if (sbi->s_log_groups_per_flex) {
809 		flex_group = ext4_flex_group(sbi, group);
810 		atomic_dec(&sbi->s_flex_groups[flex_group].free_inodes);
811 	}
812 	if (owner) {
813 		inode->i_mode = mode;
814 		inode->i_uid = owner[0];
815 		inode->i_gid = owner[1];
816 	} else if (test_opt(sb, GRPID)) {
817 		inode->i_mode = mode;
818 		inode->i_uid = current_fsuid();
819 		inode->i_gid = dir->i_gid;
820 	} else
821 		inode_init_owner(inode, dir, mode);
822 
823 	inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
824 	/* This is the optimal IO size (for stat), not the fs block size */
825 	inode->i_blocks = 0;
826 	inode->i_mtime = inode->i_atime = inode->i_ctime = ei->i_crtime =
827 						       ext4_current_time(inode);
828 
829 	memset(ei->i_data, 0, sizeof(ei->i_data));
830 	ei->i_dir_start_lookup = 0;
831 	ei->i_disksize = 0;
832 
833 	/* Don't inherit extent flag from directory, amongst others. */
834 	ei->i_flags =
835 		ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED);
836 	ei->i_file_acl = 0;
837 	ei->i_dtime = 0;
838 	ei->i_block_group = group;
839 	ei->i_last_alloc_group = ~0;
840 
841 	ext4_set_inode_flags(inode);
842 	if (IS_DIRSYNC(inode))
843 		ext4_handle_sync(handle);
844 	if (insert_inode_locked(inode) < 0) {
845 		/*
846 		 * Likely a bitmap corruption causing inode to be allocated
847 		 * twice.
848 		 */
849 		err = -EIO;
850 		goto fail;
851 	}
852 	spin_lock(&sbi->s_next_gen_lock);
853 	inode->i_generation = sbi->s_next_generation++;
854 	spin_unlock(&sbi->s_next_gen_lock);
855 
856 	ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
857 	ext4_set_inode_state(inode, EXT4_STATE_NEW);
858 
859 	ei->i_extra_isize = EXT4_SB(sb)->s_want_extra_isize;
860 
861 	ret = inode;
862 	dquot_initialize(inode);
863 	err = dquot_alloc_inode(inode);
864 	if (err)
865 		goto fail_drop;
866 
867 	err = ext4_init_acl(handle, inode, dir);
868 	if (err)
869 		goto fail_free_drop;
870 
871 	err = ext4_init_security(handle, inode, dir, qstr);
872 	if (err)
873 		goto fail_free_drop;
874 
875 	if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
876 		/* set extent flag only for directory, file and normal symlink*/
877 		if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) {
878 			ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
879 			ext4_ext_tree_init(handle, inode);
880 		}
881 	}
882 
883 	if (ext4_handle_valid(handle)) {
884 		ei->i_sync_tid = handle->h_transaction->t_tid;
885 		ei->i_datasync_tid = handle->h_transaction->t_tid;
886 	}
887 
888 	err = ext4_mark_inode_dirty(handle, inode);
889 	if (err) {
890 		ext4_std_error(sb, err);
891 		goto fail_free_drop;
892 	}
893 
894 	ext4_debug("allocating inode %lu\n", inode->i_ino);
895 	trace_ext4_allocate_inode(inode, dir, mode);
896 	goto really_out;
897 fail:
898 	ext4_std_error(sb, err);
899 out:
900 	iput(inode);
901 	ret = ERR_PTR(err);
902 really_out:
903 	brelse(inode_bitmap_bh);
904 	return ret;
905 
906 fail_free_drop:
907 	dquot_free_inode(inode);
908 
909 fail_drop:
910 	dquot_drop(inode);
911 	inode->i_flags |= S_NOQUOTA;
912 	clear_nlink(inode);
913 	unlock_new_inode(inode);
914 	iput(inode);
915 	brelse(inode_bitmap_bh);
916 	return ERR_PTR(err);
917 }
918 
919 /* Verify that we are loading a valid orphan from disk */
ext4_orphan_get(struct super_block * sb,unsigned long ino)920 struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino)
921 {
922 	unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
923 	ext4_group_t block_group;
924 	int bit;
925 	struct buffer_head *bitmap_bh;
926 	struct inode *inode = NULL;
927 	long err = -EIO;
928 
929 	/* Error cases - e2fsck has already cleaned up for us */
930 	if (ino > max_ino) {
931 		ext4_warning(sb, "bad orphan ino %lu!  e2fsck was run?", ino);
932 		goto error;
933 	}
934 
935 	block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
936 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
937 	bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
938 	if (!bitmap_bh) {
939 		ext4_warning(sb, "inode bitmap error for orphan %lu", ino);
940 		goto error;
941 	}
942 
943 	/* Having the inode bit set should be a 100% indicator that this
944 	 * is a valid orphan (no e2fsck run on fs).  Orphans also include
945 	 * inodes that were being truncated, so we can't check i_nlink==0.
946 	 */
947 	if (!ext4_test_bit(bit, bitmap_bh->b_data))
948 		goto bad_orphan;
949 
950 	inode = ext4_iget(sb, ino);
951 	if (IS_ERR(inode))
952 		goto iget_failed;
953 
954 	/*
955 	 * If the orphans has i_nlinks > 0 then it should be able to be
956 	 * truncated, otherwise it won't be removed from the orphan list
957 	 * during processing and an infinite loop will result.
958 	 */
959 	if (inode->i_nlink && !ext4_can_truncate(inode))
960 		goto bad_orphan;
961 
962 	if (NEXT_ORPHAN(inode) > max_ino)
963 		goto bad_orphan;
964 	brelse(bitmap_bh);
965 	return inode;
966 
967 iget_failed:
968 	err = PTR_ERR(inode);
969 	inode = NULL;
970 bad_orphan:
971 	ext4_warning(sb, "bad orphan inode %lu!  e2fsck was run?", ino);
972 	printk(KERN_NOTICE "ext4_test_bit(bit=%d, block=%llu) = %d\n",
973 	       bit, (unsigned long long)bitmap_bh->b_blocknr,
974 	       ext4_test_bit(bit, bitmap_bh->b_data));
975 	printk(KERN_NOTICE "inode=%p\n", inode);
976 	if (inode) {
977 		printk(KERN_NOTICE "is_bad_inode(inode)=%d\n",
978 		       is_bad_inode(inode));
979 		printk(KERN_NOTICE "NEXT_ORPHAN(inode)=%u\n",
980 		       NEXT_ORPHAN(inode));
981 		printk(KERN_NOTICE "max_ino=%lu\n", max_ino);
982 		printk(KERN_NOTICE "i_nlink=%u\n", inode->i_nlink);
983 		/* Avoid freeing blocks if we got a bad deleted inode */
984 		if (inode->i_nlink == 0)
985 			inode->i_blocks = 0;
986 		iput(inode);
987 	}
988 	brelse(bitmap_bh);
989 error:
990 	return ERR_PTR(err);
991 }
992 
ext4_count_free_inodes(struct super_block * sb)993 unsigned long ext4_count_free_inodes(struct super_block *sb)
994 {
995 	unsigned long desc_count;
996 	struct ext4_group_desc *gdp;
997 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
998 #ifdef EXT4FS_DEBUG
999 	struct ext4_super_block *es;
1000 	unsigned long bitmap_count, x;
1001 	struct buffer_head *bitmap_bh = NULL;
1002 
1003 	es = EXT4_SB(sb)->s_es;
1004 	desc_count = 0;
1005 	bitmap_count = 0;
1006 	gdp = NULL;
1007 	for (i = 0; i < ngroups; i++) {
1008 		gdp = ext4_get_group_desc(sb, i, NULL);
1009 		if (!gdp)
1010 			continue;
1011 		desc_count += ext4_free_inodes_count(sb, gdp);
1012 		brelse(bitmap_bh);
1013 		bitmap_bh = ext4_read_inode_bitmap(sb, i);
1014 		if (!bitmap_bh)
1015 			continue;
1016 
1017 		x = ext4_count_free(bitmap_bh->b_data,
1018 				    EXT4_INODES_PER_GROUP(sb) / 8);
1019 		printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n",
1020 			(unsigned long) i, ext4_free_inodes_count(sb, gdp), x);
1021 		bitmap_count += x;
1022 	}
1023 	brelse(bitmap_bh);
1024 	printk(KERN_DEBUG "ext4_count_free_inodes: "
1025 	       "stored = %u, computed = %lu, %lu\n",
1026 	       le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count);
1027 	return desc_count;
1028 #else
1029 	desc_count = 0;
1030 	for (i = 0; i < ngroups; i++) {
1031 		gdp = ext4_get_group_desc(sb, i, NULL);
1032 		if (!gdp)
1033 			continue;
1034 		desc_count += ext4_free_inodes_count(sb, gdp);
1035 		cond_resched();
1036 	}
1037 	return desc_count;
1038 #endif
1039 }
1040 
1041 /* Called at mount-time, super-block is locked */
ext4_count_dirs(struct super_block * sb)1042 unsigned long ext4_count_dirs(struct super_block * sb)
1043 {
1044 	unsigned long count = 0;
1045 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1046 
1047 	for (i = 0; i < ngroups; i++) {
1048 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
1049 		if (!gdp)
1050 			continue;
1051 		count += ext4_used_dirs_count(sb, gdp);
1052 	}
1053 	return count;
1054 }
1055 
1056 /*
1057  * Zeroes not yet zeroed inode table - just write zeroes through the whole
1058  * inode table. Must be called without any spinlock held. The only place
1059  * where it is called from on active part of filesystem is ext4lazyinit
1060  * thread, so we do not need any special locks, however we have to prevent
1061  * inode allocation from the current group, so we take alloc_sem lock, to
1062  * block ext4_new_inode() until we are finished.
1063  */
ext4_init_inode_table(struct super_block * sb,ext4_group_t group,int barrier)1064 int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,
1065 				 int barrier)
1066 {
1067 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
1068 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1069 	struct ext4_group_desc *gdp = NULL;
1070 	struct buffer_head *group_desc_bh;
1071 	handle_t *handle;
1072 	ext4_fsblk_t blk;
1073 	int num, ret = 0, used_blks = 0;
1074 
1075 	/* This should not happen, but just to be sure check this */
1076 	if (sb->s_flags & MS_RDONLY) {
1077 		ret = 1;
1078 		goto out;
1079 	}
1080 
1081 	gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
1082 	if (!gdp)
1083 		goto out;
1084 
1085 	/*
1086 	 * We do not need to lock this, because we are the only one
1087 	 * handling this flag.
1088 	 */
1089 	if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))
1090 		goto out;
1091 
1092 	handle = ext4_journal_start_sb(sb, 1);
1093 	if (IS_ERR(handle)) {
1094 		ret = PTR_ERR(handle);
1095 		goto out;
1096 	}
1097 
1098 	down_write(&grp->alloc_sem);
1099 	/*
1100 	 * If inode bitmap was already initialized there may be some
1101 	 * used inodes so we need to skip blocks with used inodes in
1102 	 * inode table.
1103 	 */
1104 	if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)))
1105 		used_blks = DIV_ROUND_UP((EXT4_INODES_PER_GROUP(sb) -
1106 			    ext4_itable_unused_count(sb, gdp)),
1107 			    sbi->s_inodes_per_block);
1108 
1109 	if ((used_blks < 0) || (used_blks > sbi->s_itb_per_group)) {
1110 		ext4_error(sb, "Something is wrong with group %u: "
1111 			   "used itable blocks: %d; "
1112 			   "itable unused count: %u",
1113 			   group, used_blks,
1114 			   ext4_itable_unused_count(sb, gdp));
1115 		ret = 1;
1116 		goto err_out;
1117 	}
1118 
1119 	blk = ext4_inode_table(sb, gdp) + used_blks;
1120 	num = sbi->s_itb_per_group - used_blks;
1121 
1122 	BUFFER_TRACE(group_desc_bh, "get_write_access");
1123 	ret = ext4_journal_get_write_access(handle,
1124 					    group_desc_bh);
1125 	if (ret)
1126 		goto err_out;
1127 
1128 	/*
1129 	 * Skip zeroout if the inode table is full. But we set the ZEROED
1130 	 * flag anyway, because obviously, when it is full it does not need
1131 	 * further zeroing.
1132 	 */
1133 	if (unlikely(num == 0))
1134 		goto skip_zeroout;
1135 
1136 	ext4_debug("going to zero out inode table in group %d\n",
1137 		   group);
1138 	ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS);
1139 	if (ret < 0)
1140 		goto err_out;
1141 	if (barrier)
1142 		blkdev_issue_flush(sb->s_bdev, GFP_NOFS, NULL);
1143 
1144 skip_zeroout:
1145 	ext4_lock_group(sb, group);
1146 	gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED);
1147 	gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp);
1148 	ext4_unlock_group(sb, group);
1149 
1150 	BUFFER_TRACE(group_desc_bh,
1151 		     "call ext4_handle_dirty_metadata");
1152 	ret = ext4_handle_dirty_metadata(handle, NULL,
1153 					 group_desc_bh);
1154 
1155 err_out:
1156 	up_write(&grp->alloc_sem);
1157 	ext4_journal_stop(handle);
1158 out:
1159 	return ret;
1160 }
1161