1/*
2 *  linux/fs/ext2/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@dcs.ed.ac.uk), 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/quotaops.h>
16#include <linux/sched.h>
17#include <linux/backing-dev.h>
18#include <linux/buffer_head.h>
19#include <linux/random.h>
20#include "ext2.h"
21#include "xattr.h"
22#include "acl.h"
23
24/*
25 * ialloc.c contains the inodes allocation and deallocation routines
26 */
27
28/*
29 * The free inodes are managed by bitmaps.  A file system contains several
30 * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
31 * block for inodes, N blocks for the inode table and data blocks.
32 *
33 * The file system contains group descriptors which are located after the
34 * super block.  Each descriptor contains the number of the bitmap block and
35 * the free blocks count in the block.
36 */
37
38
39/*
40 * Read the inode allocation bitmap for a given block_group, reading
41 * into the specified slot in the superblock's bitmap cache.
42 *
43 * Return buffer_head of bitmap on success or NULL.
44 */
45static struct buffer_head *
46read_inode_bitmap(struct super_block * sb, unsigned long block_group)
47{
48	struct ext2_group_desc *desc;
49	struct buffer_head *bh = NULL;
50
51	desc = ext2_get_group_desc(sb, block_group, NULL);
52	if (!desc)
53		goto error_out;
54
55	bh = sb_bread(sb, le32_to_cpu(desc->bg_inode_bitmap));
56	if (!bh)
57		ext2_error(sb, "read_inode_bitmap",
58			    "Cannot read inode bitmap - "
59			    "block_group = %lu, inode_bitmap = %u",
60			    block_group, le32_to_cpu(desc->bg_inode_bitmap));
61error_out:
62	return bh;
63}
64
65static void ext2_release_inode(struct super_block *sb, int group, int dir)
66{
67	struct ext2_group_desc * desc;
68	struct buffer_head *bh;
69
70	desc = ext2_get_group_desc(sb, group, &bh);
71	if (!desc) {
72		ext2_error(sb, "ext2_release_inode",
73			"can't get descriptor for group %d", group);
74		return;
75	}
76
77	spin_lock(sb_bgl_lock(EXT2_SB(sb), group));
78	le16_add_cpu(&desc->bg_free_inodes_count, 1);
79	if (dir)
80		le16_add_cpu(&desc->bg_used_dirs_count, -1);
81	spin_unlock(sb_bgl_lock(EXT2_SB(sb), group));
82	if (dir)
83		percpu_counter_dec(&EXT2_SB(sb)->s_dirs_counter);
84	sb->s_dirt = 1;
85	mark_buffer_dirty(bh);
86}
87
88/*
89 * NOTE! When we get the inode, we're the only people
90 * that have access to it, and as such there are no
91 * race conditions we have to worry about. The inode
92 * is not on the hash-lists, and it cannot be reached
93 * through the filesystem because the directory entry
94 * has been deleted earlier.
95 *
96 * HOWEVER: we must make sure that we get no aliases,
97 * which means that we have to call "clear_inode()"
98 * _before_ we mark the inode not in use in the inode
99 * bitmaps. Otherwise a newly created file might use
100 * the same inode number (not actually the same pointer
101 * though), and then we'd have two inodes sharing the
102 * same inode number and space on the harddisk.
103 */
104void ext2_free_inode (struct inode * inode)
105{
106	struct super_block * sb = inode->i_sb;
107	int is_directory;
108	unsigned long ino;
109	struct buffer_head *bitmap_bh;
110	unsigned long block_group;
111	unsigned long bit;
112	struct ext2_super_block * es;
113
114	ino = inode->i_ino;
115	ext2_debug ("freeing inode %lu\n", ino);
116
117	/*
118	 * Note: we must free any quota before locking the superblock,
119	 * as writing the quota to disk may need the lock as well.
120	 */
121	/* Quota is already initialized in iput() */
122	ext2_xattr_delete_inode(inode);
123	dquot_free_inode(inode);
124	dquot_drop(inode);
125
126	es = EXT2_SB(sb)->s_es;
127	is_directory = S_ISDIR(inode->i_mode);
128
129	if (ino < EXT2_FIRST_INO(sb) ||
130	    ino > le32_to_cpu(es->s_inodes_count)) {
131		ext2_error (sb, "ext2_free_inode",
132			    "reserved or nonexistent inode %lu", ino);
133		return;
134	}
135	block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb);
136	bit = (ino - 1) % EXT2_INODES_PER_GROUP(sb);
137	bitmap_bh = read_inode_bitmap(sb, block_group);
138	if (!bitmap_bh)
139		return;
140
141	/* Ok, now we can actually update the inode bitmaps.. */
142	if (!ext2_clear_bit_atomic(sb_bgl_lock(EXT2_SB(sb), block_group),
143				bit, (void *) bitmap_bh->b_data))
144		ext2_error (sb, "ext2_free_inode",
145			      "bit already cleared for inode %lu", ino);
146	else
147		ext2_release_inode(sb, block_group, is_directory);
148	mark_buffer_dirty(bitmap_bh);
149	if (sb->s_flags & MS_SYNCHRONOUS)
150		sync_dirty_buffer(bitmap_bh);
151
152	brelse(bitmap_bh);
153}
154
155static void ext2_preread_inode(struct inode *inode)
156{
157	unsigned long block_group;
158	unsigned long offset;
159	unsigned long block;
160	struct ext2_group_desc * gdp;
161	struct backing_dev_info *bdi;
162
163	bdi = inode->i_mapping->backing_dev_info;
164	if (bdi_read_congested(bdi))
165		return;
166	if (bdi_write_congested(bdi))
167		return;
168
169	block_group = (inode->i_ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
170	gdp = ext2_get_group_desc(inode->i_sb, block_group, NULL);
171	if (gdp == NULL)
172		return;
173
174	/*
175	 * Figure out the offset within the block group inode table
176	 */
177	offset = ((inode->i_ino - 1) % EXT2_INODES_PER_GROUP(inode->i_sb)) *
178				EXT2_INODE_SIZE(inode->i_sb);
179	block = le32_to_cpu(gdp->bg_inode_table) +
180				(offset >> EXT2_BLOCK_SIZE_BITS(inode->i_sb));
181	sb_breadahead(inode->i_sb, block);
182}
183
184/*
185 * There are two policies for allocating an inode.  If the new inode is
186 * a directory, then a forward search is made for a block group with both
187 * free space and a low directory-to-inode ratio; if that fails, then of
188 * the groups with above-average free space, that group with the fewest
189 * directories already is chosen.
190 *
191 * For other inodes, search forward from the parent directory\'s block
192 * group to find a free inode.
193 */
194static int find_group_dir(struct super_block *sb, struct inode *parent)
195{
196	int ngroups = EXT2_SB(sb)->s_groups_count;
197	int avefreei = ext2_count_free_inodes(sb) / ngroups;
198	struct ext2_group_desc *desc, *best_desc = NULL;
199	int group, best_group = -1;
200
201	for (group = 0; group < ngroups; group++) {
202		desc = ext2_get_group_desc (sb, group, NULL);
203		if (!desc || !desc->bg_free_inodes_count)
204			continue;
205		if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
206			continue;
207		if (!best_desc ||
208		    (le16_to_cpu(desc->bg_free_blocks_count) >
209		     le16_to_cpu(best_desc->bg_free_blocks_count))) {
210			best_group = group;
211			best_desc = desc;
212		}
213	}
214	if (!best_desc)
215		return -1;
216
217	return best_group;
218}
219
220/*
221 * Orlov's allocator for directories.
222 *
223 * We always try to spread first-level directories.
224 *
225 * If there are blockgroups with both free inodes and free blocks counts
226 * not worse than average we return one with smallest directory count.
227 * Otherwise we simply return a random group.
228 *
229 * For the rest rules look so:
230 *
231 * It's OK to put directory into a group unless
232 * it has too many directories already (max_dirs) or
233 * it has too few free inodes left (min_inodes) or
234 * it has too few free blocks left (min_blocks) or
235 * it's already running too large debt (max_debt).
236 * Parent's group is preferred, if it doesn't satisfy these
237 * conditions we search cyclically through the rest. If none
238 * of the groups look good we just look for a group with more
239 * free inodes than average (starting at parent's group).
240 *
241 * Debt is incremented each time we allocate a directory and decremented
242 * when we allocate an inode, within 0--255.
243 */
244
245#define INODE_COST 64
246#define BLOCK_COST 256
247
248static int find_group_orlov(struct super_block *sb, struct inode *parent)
249{
250	int parent_group = EXT2_I(parent)->i_block_group;
251	struct ext2_sb_info *sbi = EXT2_SB(sb);
252	struct ext2_super_block *es = sbi->s_es;
253	int ngroups = sbi->s_groups_count;
254	int inodes_per_group = EXT2_INODES_PER_GROUP(sb);
255	int freei;
256	int avefreei;
257	int free_blocks;
258	int avefreeb;
259	int blocks_per_dir;
260	int ndirs;
261	int max_debt, max_dirs, min_blocks, min_inodes;
262	int group = -1, i;
263	struct ext2_group_desc *desc;
264
265	freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
266	avefreei = freei / ngroups;
267	free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
268	avefreeb = free_blocks / ngroups;
269	ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
270
271	if ((parent == sb->s_root->d_inode) ||
272	    (EXT2_I(parent)->i_flags & EXT2_TOPDIR_FL)) {
273		struct ext2_group_desc *best_desc = NULL;
274		int best_ndir = inodes_per_group;
275		int best_group = -1;
276
277		get_random_bytes(&group, sizeof(group));
278		parent_group = (unsigned)group % ngroups;
279		for (i = 0; i < ngroups; i++) {
280			group = (parent_group + i) % ngroups;
281			desc = ext2_get_group_desc (sb, group, NULL);
282			if (!desc || !desc->bg_free_inodes_count)
283				continue;
284			if (le16_to_cpu(desc->bg_used_dirs_count) >= best_ndir)
285				continue;
286			if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
287				continue;
288			if (le16_to_cpu(desc->bg_free_blocks_count) < avefreeb)
289				continue;
290			best_group = group;
291			best_ndir = le16_to_cpu(desc->bg_used_dirs_count);
292			best_desc = desc;
293		}
294		if (best_group >= 0) {
295			desc = best_desc;
296			group = best_group;
297			goto found;
298		}
299		goto fallback;
300	}
301
302	if (ndirs == 0)
303		ndirs = 1;	/* percpu_counters are approximate... */
304
305	blocks_per_dir = (le32_to_cpu(es->s_blocks_count)-free_blocks) / ndirs;
306
307	max_dirs = ndirs / ngroups + inodes_per_group / 16;
308	min_inodes = avefreei - inodes_per_group / 4;
309	min_blocks = avefreeb - EXT2_BLOCKS_PER_GROUP(sb) / 4;
310
311	max_debt = EXT2_BLOCKS_PER_GROUP(sb) / max(blocks_per_dir, BLOCK_COST);
312	if (max_debt * INODE_COST > inodes_per_group)
313		max_debt = inodes_per_group / INODE_COST;
314	if (max_debt > 255)
315		max_debt = 255;
316	if (max_debt == 0)
317		max_debt = 1;
318
319	for (i = 0; i < ngroups; i++) {
320		group = (parent_group + i) % ngroups;
321		desc = ext2_get_group_desc (sb, group, NULL);
322		if (!desc || !desc->bg_free_inodes_count)
323			continue;
324		if (sbi->s_debts[group] >= max_debt)
325			continue;
326		if (le16_to_cpu(desc->bg_used_dirs_count) >= max_dirs)
327			continue;
328		if (le16_to_cpu(desc->bg_free_inodes_count) < min_inodes)
329			continue;
330		if (le16_to_cpu(desc->bg_free_blocks_count) < min_blocks)
331			continue;
332		goto found;
333	}
334
335fallback:
336	for (i = 0; i < ngroups; i++) {
337		group = (parent_group + i) % ngroups;
338		desc = ext2_get_group_desc (sb, group, NULL);
339		if (!desc || !desc->bg_free_inodes_count)
340			continue;
341		if (le16_to_cpu(desc->bg_free_inodes_count) >= avefreei)
342			goto found;
343	}
344
345	if (avefreei) {
346		/*
347		 * The free-inodes counter is approximate, and for really small
348		 * filesystems the above test can fail to find any blockgroups
349		 */
350		avefreei = 0;
351		goto fallback;
352	}
353
354	return -1;
355
356found:
357	return group;
358}
359
360static int find_group_other(struct super_block *sb, struct inode *parent)
361{
362	int parent_group = EXT2_I(parent)->i_block_group;
363	int ngroups = EXT2_SB(sb)->s_groups_count;
364	struct ext2_group_desc *desc;
365	int group, i;
366
367	/*
368	 * Try to place the inode in its parent directory
369	 */
370	group = parent_group;
371	desc = ext2_get_group_desc (sb, group, NULL);
372	if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
373			le16_to_cpu(desc->bg_free_blocks_count))
374		goto found;
375
376	/*
377	 * We're going to place this inode in a different blockgroup from its
378	 * parent.  We want to cause files in a common directory to all land in
379	 * the same blockgroup.  But we want files which are in a different
380	 * directory which shares a blockgroup with our parent to land in a
381	 * different blockgroup.
382	 *
383	 * So add our directory's i_ino into the starting point for the hash.
384	 */
385	group = (group + parent->i_ino) % ngroups;
386
387	/*
388	 * Use a quadratic hash to find a group with a free inode and some
389	 * free blocks.
390	 */
391	for (i = 1; i < ngroups; i <<= 1) {
392		group += i;
393		if (group >= ngroups)
394			group -= ngroups;
395		desc = ext2_get_group_desc (sb, group, NULL);
396		if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
397				le16_to_cpu(desc->bg_free_blocks_count))
398			goto found;
399	}
400
401	/*
402	 * That failed: try linear search for a free inode, even if that group
403	 * has no free blocks.
404	 */
405	group = parent_group;
406	for (i = 0; i < ngroups; i++) {
407		if (++group >= ngroups)
408			group = 0;
409		desc = ext2_get_group_desc (sb, group, NULL);
410		if (desc && le16_to_cpu(desc->bg_free_inodes_count))
411			goto found;
412	}
413
414	return -1;
415
416found:
417	return group;
418}
419
420struct inode *ext2_new_inode(struct inode *dir, int mode)
421{
422	struct super_block *sb;
423	struct buffer_head *bitmap_bh = NULL;
424	struct buffer_head *bh2;
425	int group, i;
426	ino_t ino = 0;
427	struct inode * inode;
428	struct ext2_group_desc *gdp;
429	struct ext2_super_block *es;
430	struct ext2_inode_info *ei;
431	struct ext2_sb_info *sbi;
432	int err;
433
434	sb = dir->i_sb;
435	inode = new_inode(sb);
436	if (!inode)
437		return ERR_PTR(-ENOMEM);
438
439	ei = EXT2_I(inode);
440	sbi = EXT2_SB(sb);
441	es = sbi->s_es;
442	if (S_ISDIR(mode)) {
443		if (test_opt(sb, OLDALLOC))
444			group = find_group_dir(sb, dir);
445		else
446			group = find_group_orlov(sb, dir);
447	} else
448		group = find_group_other(sb, dir);
449
450	if (group == -1) {
451		err = -ENOSPC;
452		goto fail;
453	}
454
455	for (i = 0; i < sbi->s_groups_count; i++) {
456		gdp = ext2_get_group_desc(sb, group, &bh2);
457		brelse(bitmap_bh);
458		bitmap_bh = read_inode_bitmap(sb, group);
459		if (!bitmap_bh) {
460			err = -EIO;
461			goto fail;
462		}
463		ino = 0;
464
465repeat_in_this_group:
466		ino = ext2_find_next_zero_bit((unsigned long *)bitmap_bh->b_data,
467					      EXT2_INODES_PER_GROUP(sb), ino);
468		if (ino >= EXT2_INODES_PER_GROUP(sb)) {
469			/*
470			 * Rare race: find_group_xx() decided that there were
471			 * free inodes in this group, but by the time we tried
472			 * to allocate one, they're all gone.  This can also
473			 * occur because the counters which find_group_orlov()
474			 * uses are approximate.  So just go and search the
475			 * next block group.
476			 */
477			if (++group == sbi->s_groups_count)
478				group = 0;
479			continue;
480		}
481		if (ext2_set_bit_atomic(sb_bgl_lock(sbi, group),
482						ino, bitmap_bh->b_data)) {
483			/* we lost this inode */
484			if (++ino >= EXT2_INODES_PER_GROUP(sb)) {
485				/* this group is exhausted, try next group */
486				if (++group == sbi->s_groups_count)
487					group = 0;
488				continue;
489			}
490			/* try to find free inode in the same group */
491			goto repeat_in_this_group;
492		}
493		goto got;
494	}
495
496	/*
497	 * Scanned all blockgroups.
498	 */
499	err = -ENOSPC;
500	goto fail;
501got:
502	mark_buffer_dirty(bitmap_bh);
503	if (sb->s_flags & MS_SYNCHRONOUS)
504		sync_dirty_buffer(bitmap_bh);
505	brelse(bitmap_bh);
506
507	ino += group * EXT2_INODES_PER_GROUP(sb) + 1;
508	if (ino < EXT2_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
509		ext2_error (sb, "ext2_new_inode",
510			    "reserved inode or inode > inodes count - "
511			    "block_group = %d,inode=%lu", group,
512			    (unsigned long) ino);
513		err = -EIO;
514		goto fail;
515	}
516
517	percpu_counter_add(&sbi->s_freeinodes_counter, -1);
518	if (S_ISDIR(mode))
519		percpu_counter_inc(&sbi->s_dirs_counter);
520
521	spin_lock(sb_bgl_lock(sbi, group));
522	le16_add_cpu(&gdp->bg_free_inodes_count, -1);
523	if (S_ISDIR(mode)) {
524		if (sbi->s_debts[group] < 255)
525			sbi->s_debts[group]++;
526		le16_add_cpu(&gdp->bg_used_dirs_count, 1);
527	} else {
528		if (sbi->s_debts[group])
529			sbi->s_debts[group]--;
530	}
531	spin_unlock(sb_bgl_lock(sbi, group));
532
533	sb->s_dirt = 1;
534	mark_buffer_dirty(bh2);
535	if (test_opt(sb, GRPID)) {
536		inode->i_mode = mode;
537		inode->i_uid = current_fsuid();
538		inode->i_gid = dir->i_gid;
539	} else
540		inode_init_owner(inode, dir, mode);
541
542	inode->i_ino = ino;
543	inode->i_blocks = 0;
544	inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC;
545	memset(ei->i_data, 0, sizeof(ei->i_data));
546	ei->i_flags =
547		ext2_mask_flags(mode, EXT2_I(dir)->i_flags & EXT2_FL_INHERITED);
548	ei->i_faddr = 0;
549	ei->i_frag_no = 0;
550	ei->i_frag_size = 0;
551	ei->i_file_acl = 0;
552	ei->i_dir_acl = 0;
553	ei->i_dtime = 0;
554	ei->i_block_alloc_info = NULL;
555	ei->i_block_group = group;
556	ei->i_dir_start_lookup = 0;
557	ei->i_state = EXT2_STATE_NEW;
558	ext2_set_inode_flags(inode);
559	spin_lock(&sbi->s_next_gen_lock);
560	inode->i_generation = sbi->s_next_generation++;
561	spin_unlock(&sbi->s_next_gen_lock);
562	if (insert_inode_locked(inode) < 0) {
563		err = -EINVAL;
564		goto fail_drop;
565	}
566
567	dquot_initialize(inode);
568	err = dquot_alloc_inode(inode);
569	if (err)
570		goto fail_drop;
571
572	err = ext2_init_acl(inode, dir);
573	if (err)
574		goto fail_free_drop;
575
576	err = ext2_init_security(inode,dir);
577	if (err)
578		goto fail_free_drop;
579
580	mark_inode_dirty(inode);
581	ext2_debug("allocating inode %lu\n", inode->i_ino);
582	ext2_preread_inode(inode);
583	return inode;
584
585fail_free_drop:
586	dquot_free_inode(inode);
587
588fail_drop:
589	dquot_drop(inode);
590	inode->i_flags |= S_NOQUOTA;
591	inode->i_nlink = 0;
592	unlock_new_inode(inode);
593	iput(inode);
594	return ERR_PTR(err);
595
596fail:
597	make_bad_inode(inode);
598	iput(inode);
599	return ERR_PTR(err);
600}
601
602unsigned long ext2_count_free_inodes (struct super_block * sb)
603{
604	struct ext2_group_desc *desc;
605	unsigned long desc_count = 0;
606	int i;
607
608#ifdef EXT2FS_DEBUG
609	struct ext2_super_block *es;
610	unsigned long bitmap_count = 0;
611	struct buffer_head *bitmap_bh = NULL;
612
613	es = EXT2_SB(sb)->s_es;
614	for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
615		unsigned x;
616
617		desc = ext2_get_group_desc (sb, i, NULL);
618		if (!desc)
619			continue;
620		desc_count += le16_to_cpu(desc->bg_free_inodes_count);
621		brelse(bitmap_bh);
622		bitmap_bh = read_inode_bitmap(sb, i);
623		if (!bitmap_bh)
624			continue;
625
626		x = ext2_count_free(bitmap_bh, EXT2_INODES_PER_GROUP(sb) / 8);
627		printk("group %d: stored = %d, counted = %u\n",
628			i, le16_to_cpu(desc->bg_free_inodes_count), x);
629		bitmap_count += x;
630	}
631	brelse(bitmap_bh);
632	printk("ext2_count_free_inodes: stored = %lu, computed = %lu, %lu\n",
633		percpu_counter_read(&EXT2_SB(sb)->s_freeinodes_counter),
634		desc_count, bitmap_count);
635	return desc_count;
636#else
637	for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
638		desc = ext2_get_group_desc (sb, i, NULL);
639		if (!desc)
640			continue;
641		desc_count += le16_to_cpu(desc->bg_free_inodes_count);
642	}
643	return desc_count;
644#endif
645}
646
647/* Called at mount-time, super-block is locked */
648unsigned long ext2_count_dirs (struct super_block * sb)
649{
650	unsigned long count = 0;
651	int i;
652
653	for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
654		struct ext2_group_desc *gdp = ext2_get_group_desc (sb, i, NULL);
655		if (!gdp)
656			continue;
657		count += le16_to_cpu(gdp->bg_used_dirs_count);
658	}
659	return count;
660}
661