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