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