628d2ce50a346a6caa4ebe40b62e47a3e46d694d
[linux.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 #include "ext4.h"
27 #include "ext4_jbd2.h"
28 #include "xattr.h"
29 #include "acl.h"
30 #include "group.h"
31
32 /*
33  * ialloc.c contains the inodes allocation and deallocation routines
34  */
35
36 /*
37  * The free inodes are managed by bitmaps.  A file system contains several
38  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
39  * block for inodes, N blocks for the inode table and data blocks.
40  *
41  * The file system contains group descriptors which are located after the
42  * super block.  Each descriptor contains the number of the bitmap block and
43  * the free blocks count in the block.
44  */
45
46 /*
47  * To avoid calling the atomic setbit hundreds or thousands of times, we only
48  * need to use it within a single byte (to ensure we get endianness right).
49  * We can use memset for the rest of the bitmap as there are no other users.
50  */
51 void mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
52 {
53         int i;
54
55         if (start_bit >= end_bit)
56                 return;
57
58         ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit);
59         for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
60                 ext4_set_bit(i, bitmap);
61         if (i < end_bit)
62                 memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
63 }
64
65 /* Initializes an uninitialized inode bitmap */
66 unsigned ext4_init_inode_bitmap(struct super_block *sb, struct buffer_head *bh,
67                                 ext4_group_t block_group,
68                                 struct ext4_group_desc *gdp)
69 {
70         struct ext4_sb_info *sbi = EXT4_SB(sb);
71
72         J_ASSERT_BH(bh, buffer_locked(bh));
73
74         /* If checksum is bad mark all blocks and inodes use to prevent
75          * allocation, essentially implementing a per-group read-only flag. */
76         if (!ext4_group_desc_csum_verify(sbi, block_group, gdp)) {
77                 ext4_error(sb, __func__, "Checksum bad for group %lu\n",
78                            block_group);
79                 gdp->bg_free_blocks_count = 0;
80                 gdp->bg_free_inodes_count = 0;
81                 gdp->bg_itable_unused = 0;
82                 memset(bh->b_data, 0xff, sb->s_blocksize);
83                 return 0;
84         }
85
86         memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8);
87         mark_bitmap_end(EXT4_INODES_PER_GROUP(sb), sb->s_blocksize * 8,
88                         bh->b_data);
89
90         return EXT4_INODES_PER_GROUP(sb);
91 }
92
93 /*
94  * Read the inode allocation bitmap for a given block_group, reading
95  * into the specified slot in the superblock's bitmap cache.
96  *
97  * Return buffer_head of bitmap on success or NULL.
98  */
99 static struct buffer_head *
100 ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group)
101 {
102         struct ext4_group_desc *desc;
103         struct buffer_head *bh = NULL;
104         ext4_fsblk_t bitmap_blk;
105
106         desc = ext4_get_group_desc(sb, block_group, NULL);
107         if (!desc)
108                 return NULL;
109         bitmap_blk = ext4_inode_bitmap(sb, desc);
110         bh = sb_getblk(sb, bitmap_blk);
111         if (unlikely(!bh)) {
112                 ext4_error(sb, __func__,
113                             "Cannot read inode bitmap - "
114                             "block_group = %lu, inode_bitmap = %llu",
115                             block_group, bitmap_blk);
116                 return NULL;
117         }
118         if (bitmap_uptodate(bh))
119                 return bh;
120
121         lock_buffer(bh);
122         if (bitmap_uptodate(bh)) {
123                 unlock_buffer(bh);
124                 return bh;
125         }
126         spin_lock(sb_bgl_lock(EXT4_SB(sb), block_group));
127         if (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
128                 ext4_init_inode_bitmap(sb, bh, block_group, desc);
129                 set_bitmap_uptodate(bh);
130                 set_buffer_uptodate(bh);
131                 unlock_buffer(bh);
132                 spin_unlock(sb_bgl_lock(EXT4_SB(sb), block_group));
133                 return bh;
134         }
135         spin_unlock(sb_bgl_lock(EXT4_SB(sb), block_group));
136         if (buffer_uptodate(bh)) {
137                 /*
138                  * if not uninit if bh is uptodate,
139                  * bitmap is also uptodate
140                  */
141                 set_bitmap_uptodate(bh);
142                 unlock_buffer(bh);
143                 return bh;
144         }
145         /*
146          * submit the buffer_head for read. We can
147          * safely mark the bitmap as uptodate now.
148          * We do it here so the bitmap uptodate bit
149          * get set with buffer lock held.
150          */
151         set_bitmap_uptodate(bh);
152         if (bh_submit_read(bh) < 0) {
153                 put_bh(bh);
154                 ext4_error(sb, __func__,
155                             "Cannot read inode bitmap - "
156                             "block_group = %lu, inode_bitmap = %llu",
157                             block_group, bitmap_blk);
158                 return NULL;
159         }
160         return bh;
161 }
162
163 /*
164  * NOTE! When we get the inode, we're the only people
165  * that have access to it, and as such there are no
166  * race conditions we have to worry about. The inode
167  * is not on the hash-lists, and it cannot be reached
168  * through the filesystem because the directory entry
169  * has been deleted earlier.
170  *
171  * HOWEVER: we must make sure that we get no aliases,
172  * which means that we have to call "clear_inode()"
173  * _before_ we mark the inode not in use in the inode
174  * bitmaps. Otherwise a newly created file might use
175  * the same inode number (not actually the same pointer
176  * though), and then we'd have two inodes sharing the
177  * same inode number and space on the harddisk.
178  */
179 void ext4_free_inode (handle_t *handle, struct inode * inode)
180 {
181         struct super_block * sb = inode->i_sb;
182         int is_directory;
183         unsigned long ino;
184         struct buffer_head *bitmap_bh = NULL;
185         struct buffer_head *bh2;
186         ext4_group_t block_group;
187         unsigned long bit;
188         struct ext4_group_desc * gdp;
189         struct ext4_super_block * es;
190         struct ext4_sb_info *sbi;
191         int fatal = 0, err, cleared;
192         ext4_group_t flex_group;
193
194         if (atomic_read(&inode->i_count) > 1) {
195                 printk ("ext4_free_inode: inode has count=%d\n",
196                                         atomic_read(&inode->i_count));
197                 return;
198         }
199         if (inode->i_nlink) {
200                 printk ("ext4_free_inode: inode has nlink=%d\n",
201                         inode->i_nlink);
202                 return;
203         }
204         if (!sb) {
205                 printk("ext4_free_inode: inode on nonexistent device\n");
206                 return;
207         }
208         sbi = EXT4_SB(sb);
209
210         ino = inode->i_ino;
211         ext4_debug ("freeing inode %lu\n", ino);
212
213         /*
214          * Note: we must free any quota before locking the superblock,
215          * as writing the quota to disk may need the lock as well.
216          */
217         DQUOT_INIT(inode);
218         ext4_xattr_delete_inode(handle, inode);
219         DQUOT_FREE_INODE(inode);
220         DQUOT_DROP(inode);
221
222         is_directory = S_ISDIR(inode->i_mode);
223
224         /* Do this BEFORE marking the inode not in use or returning an error */
225         clear_inode (inode);
226
227         es = EXT4_SB(sb)->s_es;
228         if (ino < EXT4_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
229                 ext4_error (sb, "ext4_free_inode",
230                             "reserved or nonexistent inode %lu", ino);
231                 goto error_return;
232         }
233         block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
234         bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
235         bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
236         if (!bitmap_bh)
237                 goto error_return;
238
239         BUFFER_TRACE(bitmap_bh, "get_write_access");
240         fatal = ext4_journal_get_write_access(handle, bitmap_bh);
241         if (fatal)
242                 goto error_return;
243
244         /* Ok, now we can actually update the inode bitmaps.. */
245         spin_lock(sb_bgl_lock(sbi, block_group));
246         cleared = ext4_clear_bit(bit, bitmap_bh->b_data);
247         spin_unlock(sb_bgl_lock(sbi, block_group));
248         if (!cleared)
249                 ext4_error(sb, "ext4_free_inode",
250                            "bit already cleared for inode %lu", ino);
251         else {
252                 gdp = ext4_get_group_desc (sb, block_group, &bh2);
253
254                 BUFFER_TRACE(bh2, "get_write_access");
255                 fatal = ext4_journal_get_write_access(handle, bh2);
256                 if (fatal) goto error_return;
257
258                 if (gdp) {
259                         spin_lock(sb_bgl_lock(sbi, block_group));
260                         le16_add_cpu(&gdp->bg_free_inodes_count, 1);
261                         if (is_directory)
262                                 le16_add_cpu(&gdp->bg_used_dirs_count, -1);
263                         gdp->bg_checksum = ext4_group_desc_csum(sbi,
264                                                         block_group, gdp);
265                         spin_unlock(sb_bgl_lock(sbi, block_group));
266                         percpu_counter_inc(&sbi->s_freeinodes_counter);
267                         if (is_directory)
268                                 percpu_counter_dec(&sbi->s_dirs_counter);
269
270                         if (sbi->s_log_groups_per_flex) {
271                                 flex_group = ext4_flex_group(sbi, block_group);
272                                 spin_lock(sb_bgl_lock(sbi, flex_group));
273                                 sbi->s_flex_groups[flex_group].free_inodes++;
274                                 spin_unlock(sb_bgl_lock(sbi, flex_group));
275                         }
276                 }
277                 BUFFER_TRACE(bh2, "call ext4_journal_dirty_metadata");
278                 err = ext4_journal_dirty_metadata(handle, bh2);
279                 if (!fatal) fatal = err;
280         }
281         BUFFER_TRACE(bitmap_bh, "call ext4_journal_dirty_metadata");
282         err = ext4_journal_dirty_metadata(handle, bitmap_bh);
283         if (!fatal)
284                 fatal = err;
285         sb->s_dirt = 1;
286 error_return:
287         brelse(bitmap_bh);
288         ext4_std_error(sb, fatal);
289 }
290
291 /*
292  * There are two policies for allocating an inode.  If the new inode is
293  * a directory, then a forward search is made for a block group with both
294  * free space and a low directory-to-inode ratio; if that fails, then of
295  * the groups with above-average free space, that group with the fewest
296  * directories already is chosen.
297  *
298  * For other inodes, search forward from the parent directory\'s block
299  * group to find a free inode.
300  */
301 static int find_group_dir(struct super_block *sb, struct inode *parent,
302                                 ext4_group_t *best_group)
303 {
304         ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
305         unsigned int freei, avefreei;
306         struct ext4_group_desc *desc, *best_desc = NULL;
307         ext4_group_t group;
308         int ret = -1;
309
310         freei = percpu_counter_read_positive(&EXT4_SB(sb)->s_freeinodes_counter);
311         avefreei = freei / ngroups;
312
313         for (group = 0; group < ngroups; group++) {
314                 desc = ext4_get_group_desc (sb, group, NULL);
315                 if (!desc || !desc->bg_free_inodes_count)
316                         continue;
317                 if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
318                         continue;
319                 if (!best_desc ||
320                     (le16_to_cpu(desc->bg_free_blocks_count) >
321                      le16_to_cpu(best_desc->bg_free_blocks_count))) {
322                         *best_group = group;
323                         best_desc = desc;
324                         ret = 0;
325                 }
326         }
327         return ret;
328 }
329
330 #define free_block_ratio 10
331
332 static int find_group_flex(struct super_block *sb, struct inode *parent,
333                            ext4_group_t *best_group)
334 {
335         struct ext4_sb_info *sbi = EXT4_SB(sb);
336         struct ext4_group_desc *desc;
337         struct buffer_head *bh;
338         struct flex_groups *flex_group = sbi->s_flex_groups;
339         ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
340         ext4_group_t parent_fbg_group = ext4_flex_group(sbi, parent_group);
341         ext4_group_t ngroups = sbi->s_groups_count;
342         int flex_size = ext4_flex_bg_size(sbi);
343         ext4_group_t best_flex = parent_fbg_group;
344         int blocks_per_flex = sbi->s_blocks_per_group * flex_size;
345         int flexbg_free_blocks;
346         int flex_freeb_ratio;
347         ext4_group_t n_fbg_groups;
348         ext4_group_t i;
349
350         n_fbg_groups = (sbi->s_groups_count + flex_size - 1) >>
351                 sbi->s_log_groups_per_flex;
352
353 find_close_to_parent:
354         flexbg_free_blocks = flex_group[best_flex].free_blocks;
355         flex_freeb_ratio = flexbg_free_blocks * 100 / blocks_per_flex;
356         if (flex_group[best_flex].free_inodes &&
357             flex_freeb_ratio > free_block_ratio)
358                 goto found_flexbg;
359
360         if (best_flex && best_flex == parent_fbg_group) {
361                 best_flex--;
362                 goto find_close_to_parent;
363         }
364
365         for (i = 0; i < n_fbg_groups; i++) {
366                 if (i == parent_fbg_group || i == parent_fbg_group - 1)
367                         continue;
368
369                 flexbg_free_blocks = flex_group[i].free_blocks;
370                 flex_freeb_ratio = flexbg_free_blocks * 100 / blocks_per_flex;
371
372                 if (flex_freeb_ratio > free_block_ratio &&
373                     flex_group[i].free_inodes) {
374                         best_flex = i;
375                         goto found_flexbg;
376                 }
377
378                 if (flex_group[best_flex].free_inodes == 0 ||
379                     (flex_group[i].free_blocks >
380                      flex_group[best_flex].free_blocks &&
381                      flex_group[i].free_inodes))
382                         best_flex = i;
383         }
384
385         if (!flex_group[best_flex].free_inodes ||
386             !flex_group[best_flex].free_blocks)
387                 return -1;
388
389 found_flexbg:
390         for (i = best_flex * flex_size; i < ngroups &&
391                      i < (best_flex + 1) * flex_size; i++) {
392                 desc = ext4_get_group_desc(sb, i, &bh);
393                 if (le16_to_cpu(desc->bg_free_inodes_count)) {
394                         *best_group = i;
395                         goto out;
396                 }
397         }
398
399         return -1;
400 out:
401         return 0;
402 }
403
404 /*
405  * Orlov's allocator for directories.
406  *
407  * We always try to spread first-level directories.
408  *
409  * If there are blockgroups with both free inodes and free blocks counts
410  * not worse than average we return one with smallest directory count.
411  * Otherwise we simply return a random group.
412  *
413  * For the rest rules look so:
414  *
415  * It's OK to put directory into a group unless
416  * it has too many directories already (max_dirs) or
417  * it has too few free inodes left (min_inodes) or
418  * it has too few free blocks left (min_blocks) or
419  * it's already running too large debt (max_debt).
420  * Parent's group is preferred, if it doesn't satisfy these
421  * conditions we search cyclically through the rest. If none
422  * of the groups look good we just look for a group with more
423  * free inodes than average (starting at parent's group).
424  *
425  * Debt is incremented each time we allocate a directory and decremented
426  * when we allocate an inode, within 0--255.
427  */
428
429 #define INODE_COST 64
430 #define BLOCK_COST 256
431
432 static int find_group_orlov(struct super_block *sb, struct inode *parent,
433                                 ext4_group_t *group)
434 {
435         ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
436         struct ext4_sb_info *sbi = EXT4_SB(sb);
437         struct ext4_super_block *es = sbi->s_es;
438         ext4_group_t ngroups = sbi->s_groups_count;
439         int inodes_per_group = EXT4_INODES_PER_GROUP(sb);
440         unsigned int freei, avefreei;
441         ext4_fsblk_t freeb, avefreeb;
442         ext4_fsblk_t blocks_per_dir;
443         unsigned int ndirs;
444         int max_debt, max_dirs, min_inodes;
445         ext4_grpblk_t min_blocks;
446         ext4_group_t i;
447         struct ext4_group_desc *desc;
448
449         freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
450         avefreei = freei / ngroups;
451         freeb = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
452         avefreeb = freeb;
453         do_div(avefreeb, ngroups);
454         ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
455
456         if ((parent == sb->s_root->d_inode) ||
457             (EXT4_I(parent)->i_flags & EXT4_TOPDIR_FL)) {
458                 int best_ndir = inodes_per_group;
459                 ext4_group_t grp;
460                 int ret = -1;
461
462                 get_random_bytes(&grp, sizeof(grp));
463                 parent_group = (unsigned)grp % ngroups;
464                 for (i = 0; i < ngroups; i++) {
465                         grp = (parent_group + i) % ngroups;
466                         desc = ext4_get_group_desc(sb, grp, NULL);
467                         if (!desc || !desc->bg_free_inodes_count)
468                                 continue;
469                         if (le16_to_cpu(desc->bg_used_dirs_count) >= best_ndir)
470                                 continue;
471                         if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
472                                 continue;
473                         if (le16_to_cpu(desc->bg_free_blocks_count) < avefreeb)
474                                 continue;
475                         *group = grp;
476                         ret = 0;
477                         best_ndir = le16_to_cpu(desc->bg_used_dirs_count);
478                 }
479                 if (ret == 0)
480                         return ret;
481                 goto fallback;
482         }
483
484         blocks_per_dir = ext4_blocks_count(es) - freeb;
485         do_div(blocks_per_dir, ndirs);
486
487         max_dirs = ndirs / ngroups + inodes_per_group / 16;
488         min_inodes = avefreei - inodes_per_group / 4;
489         min_blocks = avefreeb - EXT4_BLOCKS_PER_GROUP(sb) / 4;
490
491         max_debt = EXT4_BLOCKS_PER_GROUP(sb);
492         max_debt /= max_t(int, blocks_per_dir, BLOCK_COST);
493         if (max_debt * INODE_COST > inodes_per_group)
494                 max_debt = inodes_per_group / INODE_COST;
495         if (max_debt > 255)
496                 max_debt = 255;
497         if (max_debt == 0)
498                 max_debt = 1;
499
500         for (i = 0; i < ngroups; i++) {
501                 *group = (parent_group + i) % ngroups;
502                 desc = ext4_get_group_desc(sb, *group, NULL);
503                 if (!desc || !desc->bg_free_inodes_count)
504                         continue;
505                 if (le16_to_cpu(desc->bg_used_dirs_count) >= max_dirs)
506                         continue;
507                 if (le16_to_cpu(desc->bg_free_inodes_count) < min_inodes)
508                         continue;
509                 if (le16_to_cpu(desc->bg_free_blocks_count) < min_blocks)
510                         continue;
511                 return 0;
512         }
513
514 fallback:
515         for (i = 0; i < ngroups; i++) {
516                 *group = (parent_group + i) % ngroups;
517                 desc = ext4_get_group_desc(sb, *group, NULL);
518                 if (desc && desc->bg_free_inodes_count &&
519                         le16_to_cpu(desc->bg_free_inodes_count) >= avefreei)
520                         return 0;
521         }
522
523         if (avefreei) {
524                 /*
525                  * The free-inodes counter is approximate, and for really small
526                  * filesystems the above test can fail to find any blockgroups
527                  */
528                 avefreei = 0;
529                 goto fallback;
530         }
531
532         return -1;
533 }
534
535 static int find_group_other(struct super_block *sb, struct inode *parent,
536                                 ext4_group_t *group)
537 {
538         ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
539         ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
540         struct ext4_group_desc *desc;
541         ext4_group_t i;
542
543         /*
544          * Try to place the inode in its parent directory
545          */
546         *group = parent_group;
547         desc = ext4_get_group_desc(sb, *group, NULL);
548         if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
549                         le16_to_cpu(desc->bg_free_blocks_count))
550                 return 0;
551
552         /*
553          * We're going to place this inode in a different blockgroup from its
554          * parent.  We want to cause files in a common directory to all land in
555          * the same blockgroup.  But we want files which are in a different
556          * directory which shares a blockgroup with our parent to land in a
557          * different blockgroup.
558          *
559          * So add our directory's i_ino into the starting point for the hash.
560          */
561         *group = (*group + parent->i_ino) % ngroups;
562
563         /*
564          * Use a quadratic hash to find a group with a free inode and some free
565          * blocks.
566          */
567         for (i = 1; i < ngroups; i <<= 1) {
568                 *group += i;
569                 if (*group >= ngroups)
570                         *group -= ngroups;
571                 desc = ext4_get_group_desc(sb, *group, NULL);
572                 if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
573                                 le16_to_cpu(desc->bg_free_blocks_count))
574                         return 0;
575         }
576
577         /*
578          * That failed: try linear search for a free inode, even if that group
579          * has no free blocks.
580          */
581         *group = parent_group;
582         for (i = 0; i < ngroups; i++) {
583                 if (++*group >= ngroups)
584                         *group = 0;
585                 desc = ext4_get_group_desc(sb, *group, NULL);
586                 if (desc && le16_to_cpu(desc->bg_free_inodes_count))
587                         return 0;
588         }
589
590         return -1;
591 }
592
593 /*
594  * claim the inode from the inode bitmap. If the group
595  * is uninit we need to take the groups's sb_bgl_lock
596  * and clear the uninit flag. The inode bitmap update
597  * and group desc uninit flag clear should be done
598  * after holding sb_bgl_lock so that ext4_read_inode_bitmap
599  * doesn't race with the ext4_claim_inode
600  */
601 static int ext4_claim_inode(struct super_block *sb,
602                         struct buffer_head *inode_bitmap_bh,
603                         unsigned long ino, ext4_group_t group, int mode)
604 {
605         int free = 0, retval = 0;
606         struct ext4_sb_info *sbi = EXT4_SB(sb);
607         struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group, NULL);
608
609         spin_lock(sb_bgl_lock(sbi, group));
610         if (ext4_set_bit(ino, inode_bitmap_bh->b_data)) {
611                 /* not a free inode */
612                 retval = 1;
613                 goto err_ret;
614         }
615         ino++;
616         if ((group == 0 && ino < EXT4_FIRST_INO(sb)) ||
617                         ino > EXT4_INODES_PER_GROUP(sb)) {
618                 spin_unlock(sb_bgl_lock(sbi, group));
619                 ext4_error(sb, __func__,
620                            "reserved inode or inode > inodes count - "
621                            "block_group = %lu, inode=%lu", group,
622                            ino + group * EXT4_INODES_PER_GROUP(sb));
623                 return 1;
624         }
625         /* If we didn't allocate from within the initialized part of the inode
626          * table then we need to initialize up to this inode. */
627         if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
628
629                 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
630                         gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
631                         /* When marking the block group with
632                          * ~EXT4_BG_INODE_UNINIT we don't want to depend
633                          * on the value of bg_itable_unused even though
634                          * mke2fs could have initialized the same for us.
635                          * Instead we calculated the value below
636                          */
637
638                         free = 0;
639                 } else {
640                         free = EXT4_INODES_PER_GROUP(sb) -
641                                 le16_to_cpu(gdp->bg_itable_unused);
642                 }
643
644                 /*
645                  * Check the relative inode number against the last used
646                  * relative inode number in this group. if it is greater
647                  * we need to  update the bg_itable_unused count
648                  *
649                  */
650                 if (ino > free)
651                         gdp->bg_itable_unused =
652                                 cpu_to_le16(EXT4_INODES_PER_GROUP(sb) - ino);
653         }
654         le16_add_cpu(&gdp->bg_free_inodes_count, -1);
655         if (S_ISDIR(mode)) {
656                 le16_add_cpu(&gdp->bg_used_dirs_count, 1);
657         }
658         gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp);
659 err_ret:
660         spin_unlock(sb_bgl_lock(sbi, group));
661         return retval;
662 }
663
664 /*
665  * There are two policies for allocating an inode.  If the new inode is
666  * a directory, then a forward search is made for a block group with both
667  * free space and a low directory-to-inode ratio; if that fails, then of
668  * the groups with above-average free space, that group with the fewest
669  * directories already is chosen.
670  *
671  * For other inodes, search forward from the parent directory's block
672  * group to find a free inode.
673  */
674 struct inode *ext4_new_inode(handle_t *handle, struct inode * dir, int mode)
675 {
676         struct super_block *sb;
677         struct buffer_head *bitmap_bh = NULL;
678         struct buffer_head *bh2;
679         ext4_group_t group = 0;
680         unsigned long ino = 0;
681         struct inode * inode;
682         struct ext4_group_desc * gdp = NULL;
683         struct ext4_super_block * es;
684         struct ext4_inode_info *ei;
685         struct ext4_sb_info *sbi;
686         int ret2, err = 0;
687         struct inode *ret;
688         ext4_group_t i;
689         int free = 0;
690         static int once = 1;
691         ext4_group_t flex_group;
692
693         /* Cannot create files in a deleted directory */
694         if (!dir || !dir->i_nlink)
695                 return ERR_PTR(-EPERM);
696
697         sb = dir->i_sb;
698         inode = new_inode(sb);
699         if (!inode)
700                 return ERR_PTR(-ENOMEM);
701         ei = EXT4_I(inode);
702
703         sbi = EXT4_SB(sb);
704         es = sbi->s_es;
705
706         if (sbi->s_log_groups_per_flex) {
707                 ret2 = find_group_flex(sb, dir, &group);
708                 if (ret2 == -1) {
709                         ret2 = find_group_other(sb, dir, &group);
710                         if (ret2 == 0 && once)
711                                 once = 0;
712                                 printk(KERN_NOTICE "ext4: find_group_flex "
713                                        "failed, fallback succeeded dir %lu\n",
714                                        dir->i_ino);
715                 }
716                 goto got_group;
717         }
718
719         if (S_ISDIR(mode)) {
720                 if (test_opt (sb, OLDALLOC))
721                         ret2 = find_group_dir(sb, dir, &group);
722                 else
723                         ret2 = find_group_orlov(sb, dir, &group);
724         } else
725                 ret2 = find_group_other(sb, dir, &group);
726
727 got_group:
728         err = -ENOSPC;
729         if (ret2 == -1)
730                 goto out;
731
732         for (i = 0; i < sbi->s_groups_count; i++) {
733                 err = -EIO;
734
735                 gdp = ext4_get_group_desc(sb, group, &bh2);
736                 if (!gdp)
737                         goto fail;
738
739                 brelse(bitmap_bh);
740                 bitmap_bh = ext4_read_inode_bitmap(sb, group);
741                 if (!bitmap_bh)
742                         goto fail;
743
744                 ino = 0;
745
746 repeat_in_this_group:
747                 ino = ext4_find_next_zero_bit((unsigned long *)
748                                 bitmap_bh->b_data, EXT4_INODES_PER_GROUP(sb), ino);
749                 if (ino < EXT4_INODES_PER_GROUP(sb)) {
750
751                         BUFFER_TRACE(bitmap_bh, "get_write_access");
752                         err = ext4_journal_get_write_access(handle, bitmap_bh);
753                         if (err)
754                                 goto fail;
755
756                         BUFFER_TRACE(bh2, "get_write_access");
757                         err = ext4_journal_get_write_access(handle, bh2);
758                         if (err)
759                                 goto fail;
760                         if (!ext4_claim_inode(sb, bitmap_bh,
761                                                 ino, group, mode)) {
762                                 /* we won it */
763                                 BUFFER_TRACE(bitmap_bh,
764                                         "call ext4_journal_dirty_metadata");
765                                 err = ext4_journal_dirty_metadata(handle,
766                                                                 bitmap_bh);
767                                 if (err)
768                                         goto fail;
769                                 /* zero bit is inode number 1*/
770                                 ino++;
771                                 goto got;
772                         }
773                         /* we lost it */
774                         jbd2_journal_release_buffer(handle, bitmap_bh);
775                         jbd2_journal_release_buffer(handle, bh2);
776
777                         if (++ino < EXT4_INODES_PER_GROUP(sb))
778                                 goto repeat_in_this_group;
779                 }
780
781                 /*
782                  * This case is possible in concurrent environment.  It is very
783                  * rare.  We cannot repeat the find_group_xxx() call because
784                  * that will simply return the same blockgroup, because the
785                  * group descriptor metadata has not yet been updated.
786                  * So we just go onto the next blockgroup.
787                  */
788                 if (++group == sbi->s_groups_count)
789                         group = 0;
790         }
791         err = -ENOSPC;
792         goto out;
793
794 got:
795         /* We may have to initialize the block bitmap if it isn't already */
796         if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM) &&
797             gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
798                 struct buffer_head *block_bh = ext4_read_block_bitmap(sb, group);
799
800                 BUFFER_TRACE(block_bh, "get block bitmap access");
801                 err = ext4_journal_get_write_access(handle, block_bh);
802                 if (err) {
803                         brelse(block_bh);
804                         goto fail;
805                 }
806
807                 free = 0;
808                 spin_lock(sb_bgl_lock(sbi, group));
809                 /* recheck and clear flag under lock if we still need to */
810                 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
811                         gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
812                         free = ext4_free_blocks_after_init(sb, group, gdp);
813                         gdp->bg_free_blocks_count = cpu_to_le16(free);
814                         gdp->bg_checksum = ext4_group_desc_csum(sbi, group,
815                                                                 gdp);
816                 }
817                 spin_unlock(sb_bgl_lock(sbi, group));
818
819                 /* Don't need to dirty bitmap block if we didn't change it */
820                 if (free) {
821                         BUFFER_TRACE(block_bh, "dirty block bitmap");
822                         err = ext4_journal_dirty_metadata(handle, block_bh);
823                 }
824
825                 brelse(block_bh);
826                 if (err)
827                         goto fail;
828         }
829         BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata");
830         err = ext4_journal_dirty_metadata(handle, bh2);
831         if (err)
832                 goto fail;
833
834         percpu_counter_dec(&sbi->s_freeinodes_counter);
835         if (S_ISDIR(mode))
836                 percpu_counter_inc(&sbi->s_dirs_counter);
837         sb->s_dirt = 1;
838
839         if (sbi->s_log_groups_per_flex) {
840                 flex_group = ext4_flex_group(sbi, group);
841                 spin_lock(sb_bgl_lock(sbi, flex_group));
842                 sbi->s_flex_groups[flex_group].free_inodes--;
843                 spin_unlock(sb_bgl_lock(sbi, flex_group));
844         }
845
846         inode->i_uid = current->fsuid;
847         if (test_opt (sb, GRPID))
848                 inode->i_gid = dir->i_gid;
849         else if (dir->i_mode & S_ISGID) {
850                 inode->i_gid = dir->i_gid;
851                 if (S_ISDIR(mode))
852                         mode |= S_ISGID;
853         } else
854                 inode->i_gid = current->fsgid;
855         inode->i_mode = mode;
856
857         inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
858         /* This is the optimal IO size (for stat), not the fs block size */
859         inode->i_blocks = 0;
860         inode->i_mtime = inode->i_atime = inode->i_ctime = ei->i_crtime =
861                                                        ext4_current_time(inode);
862
863         memset(ei->i_data, 0, sizeof(ei->i_data));
864         ei->i_dir_start_lookup = 0;
865         ei->i_disksize = 0;
866
867         /*
868          * Don't inherit extent flag from directory, amongst others. We set
869          * extent flag on newly created directory and file only if -o extent
870          * mount option is specified
871          */
872         ei->i_flags =
873                 ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED);
874         ei->i_file_acl = 0;
875         ei->i_dtime = 0;
876         ei->i_block_alloc_info = NULL;
877         ei->i_block_group = group;
878
879         ext4_set_inode_flags(inode);
880         if (IS_DIRSYNC(inode))
881                 handle->h_sync = 1;
882         insert_inode_hash(inode);
883         spin_lock(&sbi->s_next_gen_lock);
884         inode->i_generation = sbi->s_next_generation++;
885         spin_unlock(&sbi->s_next_gen_lock);
886
887         ei->i_state = EXT4_STATE_NEW;
888
889         ei->i_extra_isize = EXT4_SB(sb)->s_want_extra_isize;
890
891         ret = inode;
892         if(DQUOT_ALLOC_INODE(inode)) {
893                 err = -EDQUOT;
894                 goto fail_drop;
895         }
896
897         err = ext4_init_acl(handle, inode, dir);
898         if (err)
899                 goto fail_free_drop;
900
901         err = ext4_init_security(handle,inode, dir);
902         if (err)
903                 goto fail_free_drop;
904
905         if (test_opt(sb, EXTENTS)) {
906                 /* set extent flag only for directory, file and normal symlink*/
907                 if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) {
908                         EXT4_I(inode)->i_flags |= EXT4_EXTENTS_FL;
909                         ext4_ext_tree_init(handle, inode);
910                 }
911         }
912
913         err = ext4_mark_inode_dirty(handle, inode);
914         if (err) {
915                 ext4_std_error(sb, err);
916                 goto fail_free_drop;
917         }
918
919         ext4_debug("allocating inode %lu\n", inode->i_ino);
920         goto really_out;
921 fail:
922         ext4_std_error(sb, err);
923 out:
924         iput(inode);
925         ret = ERR_PTR(err);
926 really_out:
927         brelse(bitmap_bh);
928         return ret;
929
930 fail_free_drop:
931         DQUOT_FREE_INODE(inode);
932
933 fail_drop:
934         DQUOT_DROP(inode);
935         inode->i_flags |= S_NOQUOTA;
936         inode->i_nlink = 0;
937         iput(inode);
938         brelse(bitmap_bh);
939         return ERR_PTR(err);
940 }
941
942 /* Verify that we are loading a valid orphan from disk */
943 struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino)
944 {
945         unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
946         ext4_group_t block_group;
947         int bit;
948         struct buffer_head *bitmap_bh;
949         struct inode *inode = NULL;
950         long err = -EIO;
951
952         /* Error cases - e2fsck has already cleaned up for us */
953         if (ino > max_ino) {
954                 ext4_warning(sb, __func__,
955                              "bad orphan ino %lu!  e2fsck was run?", ino);
956                 goto error;
957         }
958
959         block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
960         bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
961         bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
962         if (!bitmap_bh) {
963                 ext4_warning(sb, __func__,
964                              "inode bitmap error for orphan %lu", ino);
965                 goto error;
966         }
967
968         /* Having the inode bit set should be a 100% indicator that this
969          * is a valid orphan (no e2fsck run on fs).  Orphans also include
970          * inodes that were being truncated, so we can't check i_nlink==0.
971          */
972         if (!ext4_test_bit(bit, bitmap_bh->b_data))
973                 goto bad_orphan;
974
975         inode = ext4_iget(sb, ino);
976         if (IS_ERR(inode))
977                 goto iget_failed;
978
979         /*
980          * If the orphans has i_nlinks > 0 then it should be able to be
981          * truncated, otherwise it won't be removed from the orphan list
982          * during processing and an infinite loop will result.
983          */
984         if (inode->i_nlink && !ext4_can_truncate(inode))
985                 goto bad_orphan;
986
987         if (NEXT_ORPHAN(inode) > max_ino)
988                 goto bad_orphan;
989         brelse(bitmap_bh);
990         return inode;
991
992 iget_failed:
993         err = PTR_ERR(inode);
994         inode = NULL;
995 bad_orphan:
996         ext4_warning(sb, __func__,
997                      "bad orphan inode %lu!  e2fsck was run?", ino);
998         printk(KERN_NOTICE "ext4_test_bit(bit=%d, block=%llu) = %d\n",
999                bit, (unsigned long long)bitmap_bh->b_blocknr,
1000                ext4_test_bit(bit, bitmap_bh->b_data));
1001         printk(KERN_NOTICE "inode=%p\n", inode);
1002         if (inode) {
1003                 printk(KERN_NOTICE "is_bad_inode(inode)=%d\n",
1004                        is_bad_inode(inode));
1005                 printk(KERN_NOTICE "NEXT_ORPHAN(inode)=%u\n",
1006                        NEXT_ORPHAN(inode));
1007                 printk(KERN_NOTICE "max_ino=%lu\n", max_ino);
1008                 printk(KERN_NOTICE "i_nlink=%u\n", inode->i_nlink);
1009                 /* Avoid freeing blocks if we got a bad deleted inode */
1010                 if (inode->i_nlink == 0)
1011                         inode->i_blocks = 0;
1012                 iput(inode);
1013         }
1014         brelse(bitmap_bh);
1015 error:
1016         return ERR_PTR(err);
1017 }
1018
1019 unsigned long ext4_count_free_inodes (struct super_block * sb)
1020 {
1021         unsigned long desc_count;
1022         struct ext4_group_desc *gdp;
1023         ext4_group_t i;
1024 #ifdef EXT4FS_DEBUG
1025         struct ext4_super_block *es;
1026         unsigned long bitmap_count, x;
1027         struct buffer_head *bitmap_bh = NULL;
1028
1029         es = EXT4_SB(sb)->s_es;
1030         desc_count = 0;
1031         bitmap_count = 0;
1032         gdp = NULL;
1033         for (i = 0; i < EXT4_SB(sb)->s_groups_count; i++) {
1034                 gdp = ext4_get_group_desc (sb, i, NULL);
1035                 if (!gdp)
1036                         continue;
1037                 desc_count += le16_to_cpu(gdp->bg_free_inodes_count);
1038                 brelse(bitmap_bh);
1039                 bitmap_bh = ext4_read_inode_bitmap(sb, i);
1040                 if (!bitmap_bh)
1041                         continue;
1042
1043                 x = ext4_count_free(bitmap_bh, EXT4_INODES_PER_GROUP(sb) / 8);
1044                 printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n",
1045                         i, le16_to_cpu(gdp->bg_free_inodes_count), x);
1046                 bitmap_count += x;
1047         }
1048         brelse(bitmap_bh);
1049         printk("ext4_count_free_inodes: stored = %u, computed = %lu, %lu\n",
1050                 le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count);
1051         return desc_count;
1052 #else
1053         desc_count = 0;
1054         for (i = 0; i < EXT4_SB(sb)->s_groups_count; i++) {
1055                 gdp = ext4_get_group_desc (sb, i, NULL);
1056                 if (!gdp)
1057                         continue;
1058                 desc_count += le16_to_cpu(gdp->bg_free_inodes_count);
1059                 cond_resched();
1060         }
1061         return desc_count;
1062 #endif
1063 }
1064
1065 /* Called at mount-time, super-block is locked */
1066 unsigned long ext4_count_dirs (struct super_block * sb)
1067 {
1068         unsigned long count = 0;
1069         ext4_group_t i;
1070
1071         for (i = 0; i < EXT4_SB(sb)->s_groups_count; i++) {
1072                 struct ext4_group_desc *gdp = ext4_get_group_desc (sb, i, NULL);
1073                 if (!gdp)
1074                         continue;
1075                 count += le16_to_cpu(gdp->bg_used_dirs_count);
1076         }
1077         return count;
1078 }
1079