ext4: Add fallback for find_group_flex
[pandora-kernel.git] / fs / ext4 / ialloc.c
1 /*
2  *  linux/fs/ext4/ialloc.c
3  *
4  * Copyright (C) 1992, 1993, 1994, 1995
5  * Remy Card (card@masi.ibp.fr)
6  * Laboratoire MASI - Institut Blaise Pascal
7  * Universite Pierre et Marie Curie (Paris VI)
8  *
9  *  BSD ufs-inspired inode and directory allocation by
10  *  Stephen Tweedie (sct@redhat.com), 1993
11  *  Big-endian to little-endian byte-swapping/bitmaps by
12  *        David S. Miller (davem@caip.rutgers.edu), 1995
13  */
14
15 #include <linux/time.h>
16 #include <linux/fs.h>
17 #include <linux/jbd2.h>
18 #include <linux/stat.h>
19 #include <linux/string.h>
20 #include <linux/quotaops.h>
21 #include <linux/buffer_head.h>
22 #include <linux/random.h>
23 #include <linux/bitops.h>
24 #include <linux/blkdev.h>
25 #include <asm/byteorder.h>
26 #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;
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         if (!ext4_clear_bit_atomic(sb_bgl_lock(sbi, block_group),
246                                         bit, bitmap_bh->b_data))
247                 ext4_error (sb, "ext4_free_inode",
248                               "bit already cleared for inode %lu", ino);
249         else {
250                 gdp = ext4_get_group_desc (sb, block_group, &bh2);
251
252                 BUFFER_TRACE(bh2, "get_write_access");
253                 fatal = ext4_journal_get_write_access(handle, bh2);
254                 if (fatal) goto error_return;
255
256                 if (gdp) {
257                         spin_lock(sb_bgl_lock(sbi, block_group));
258                         le16_add_cpu(&gdp->bg_free_inodes_count, 1);
259                         if (is_directory)
260                                 le16_add_cpu(&gdp->bg_used_dirs_count, -1);
261                         gdp->bg_checksum = ext4_group_desc_csum(sbi,
262                                                         block_group, gdp);
263                         spin_unlock(sb_bgl_lock(sbi, block_group));
264                         percpu_counter_inc(&sbi->s_freeinodes_counter);
265                         if (is_directory)
266                                 percpu_counter_dec(&sbi->s_dirs_counter);
267
268                         if (sbi->s_log_groups_per_flex) {
269                                 flex_group = ext4_flex_group(sbi, block_group);
270                                 spin_lock(sb_bgl_lock(sbi, flex_group));
271                                 sbi->s_flex_groups[flex_group].free_inodes++;
272                                 spin_unlock(sb_bgl_lock(sbi, flex_group));
273                         }
274                 }
275                 BUFFER_TRACE(bh2, "call ext4_journal_dirty_metadata");
276                 err = ext4_journal_dirty_metadata(handle, bh2);
277                 if (!fatal) fatal = err;
278         }
279         BUFFER_TRACE(bitmap_bh, "call ext4_journal_dirty_metadata");
280         err = ext4_journal_dirty_metadata(handle, bitmap_bh);
281         if (!fatal)
282                 fatal = err;
283         sb->s_dirt = 1;
284 error_return:
285         brelse(bitmap_bh);
286         ext4_std_error(sb, fatal);
287 }
288
289 /*
290  * There are two policies for allocating an inode.  If the new inode is
291  * a directory, then a forward search is made for a block group with both
292  * free space and a low directory-to-inode ratio; if that fails, then of
293  * the groups with above-average free space, that group with the fewest
294  * directories already is chosen.
295  *
296  * For other inodes, search forward from the parent directory\'s block
297  * group to find a free inode.
298  */
299 static int find_group_dir(struct super_block *sb, struct inode *parent,
300                                 ext4_group_t *best_group)
301 {
302         ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
303         unsigned int freei, avefreei;
304         struct ext4_group_desc *desc, *best_desc = NULL;
305         ext4_group_t group;
306         int ret = -1;
307
308         freei = percpu_counter_read_positive(&EXT4_SB(sb)->s_freeinodes_counter);
309         avefreei = freei / ngroups;
310
311         for (group = 0; group < ngroups; group++) {
312                 desc = ext4_get_group_desc (sb, group, NULL);
313                 if (!desc || !desc->bg_free_inodes_count)
314                         continue;
315                 if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
316                         continue;
317                 if (!best_desc ||
318                     (le16_to_cpu(desc->bg_free_blocks_count) >
319                      le16_to_cpu(best_desc->bg_free_blocks_count))) {
320                         *best_group = group;
321                         best_desc = desc;
322                         ret = 0;
323                 }
324         }
325         return ret;
326 }
327
328 #define free_block_ratio 10
329
330 static int find_group_flex(struct super_block *sb, struct inode *parent,
331                            ext4_group_t *best_group)
332 {
333         struct ext4_sb_info *sbi = EXT4_SB(sb);
334         struct ext4_group_desc *desc;
335         struct buffer_head *bh;
336         struct flex_groups *flex_group = sbi->s_flex_groups;
337         ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
338         ext4_group_t parent_fbg_group = ext4_flex_group(sbi, parent_group);
339         ext4_group_t ngroups = sbi->s_groups_count;
340         int flex_size = ext4_flex_bg_size(sbi);
341         ext4_group_t best_flex = parent_fbg_group;
342         int blocks_per_flex = sbi->s_blocks_per_group * flex_size;
343         int flexbg_free_blocks;
344         int flex_freeb_ratio;
345         ext4_group_t n_fbg_groups;
346         ext4_group_t i;
347
348         n_fbg_groups = (sbi->s_groups_count + flex_size - 1) >>
349                 sbi->s_log_groups_per_flex;
350
351 find_close_to_parent:
352         flexbg_free_blocks = flex_group[best_flex].free_blocks;
353         flex_freeb_ratio = flexbg_free_blocks * 100 / blocks_per_flex;
354         if (flex_group[best_flex].free_inodes &&
355             flex_freeb_ratio > free_block_ratio)
356                 goto found_flexbg;
357
358         if (best_flex && best_flex == parent_fbg_group) {
359                 best_flex--;
360                 goto find_close_to_parent;
361         }
362
363         for (i = 0; i < n_fbg_groups; i++) {
364                 if (i == parent_fbg_group || i == parent_fbg_group - 1)
365                         continue;
366
367                 flexbg_free_blocks = flex_group[i].free_blocks;
368                 flex_freeb_ratio = flexbg_free_blocks * 100 / blocks_per_flex;
369
370                 if (flex_freeb_ratio > free_block_ratio &&
371                     flex_group[i].free_inodes) {
372                         best_flex = i;
373                         goto found_flexbg;
374                 }
375
376                 if (flex_group[best_flex].free_inodes == 0 ||
377                     (flex_group[i].free_blocks >
378                      flex_group[best_flex].free_blocks &&
379                      flex_group[i].free_inodes))
380                         best_flex = i;
381         }
382
383         if (!flex_group[best_flex].free_inodes ||
384             !flex_group[best_flex].free_blocks)
385                 return -1;
386
387 found_flexbg:
388         for (i = best_flex * flex_size; i < ngroups &&
389                      i < (best_flex + 1) * flex_size; i++) {
390                 desc = ext4_get_group_desc(sb, i, &bh);
391                 if (le16_to_cpu(desc->bg_free_inodes_count)) {
392                         *best_group = i;
393                         goto out;
394                 }
395         }
396
397         return -1;
398 out:
399         return 0;
400 }
401
402 /*
403  * Orlov's allocator for directories.
404  *
405  * We always try to spread first-level directories.
406  *
407  * If there are blockgroups with both free inodes and free blocks counts
408  * not worse than average we return one with smallest directory count.
409  * Otherwise we simply return a random group.
410  *
411  * For the rest rules look so:
412  *
413  * It's OK to put directory into a group unless
414  * it has too many directories already (max_dirs) or
415  * it has too few free inodes left (min_inodes) or
416  * it has too few free blocks left (min_blocks) or
417  * it's already running too large debt (max_debt).
418  * Parent's group is preferred, if it doesn't satisfy these
419  * conditions we search cyclically through the rest. If none
420  * of the groups look good we just look for a group with more
421  * free inodes than average (starting at parent's group).
422  *
423  * Debt is incremented each time we allocate a directory and decremented
424  * when we allocate an inode, within 0--255.
425  */
426
427 #define INODE_COST 64
428 #define BLOCK_COST 256
429
430 static int find_group_orlov(struct super_block *sb, struct inode *parent,
431                                 ext4_group_t *group)
432 {
433         ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
434         struct ext4_sb_info *sbi = EXT4_SB(sb);
435         struct ext4_super_block *es = sbi->s_es;
436         ext4_group_t ngroups = sbi->s_groups_count;
437         int inodes_per_group = EXT4_INODES_PER_GROUP(sb);
438         unsigned int freei, avefreei;
439         ext4_fsblk_t freeb, avefreeb;
440         ext4_fsblk_t blocks_per_dir;
441         unsigned int ndirs;
442         int max_debt, max_dirs, min_inodes;
443         ext4_grpblk_t min_blocks;
444         ext4_group_t i;
445         struct ext4_group_desc *desc;
446
447         freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
448         avefreei = freei / ngroups;
449         freeb = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
450         avefreeb = freeb;
451         do_div(avefreeb, ngroups);
452         ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
453
454         if ((parent == sb->s_root->d_inode) ||
455             (EXT4_I(parent)->i_flags & EXT4_TOPDIR_FL)) {
456                 int best_ndir = inodes_per_group;
457                 ext4_group_t grp;
458                 int ret = -1;
459
460                 get_random_bytes(&grp, sizeof(grp));
461                 parent_group = (unsigned)grp % ngroups;
462                 for (i = 0; i < ngroups; i++) {
463                         grp = (parent_group + i) % ngroups;
464                         desc = ext4_get_group_desc(sb, grp, NULL);
465                         if (!desc || !desc->bg_free_inodes_count)
466                                 continue;
467                         if (le16_to_cpu(desc->bg_used_dirs_count) >= best_ndir)
468                                 continue;
469                         if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
470                                 continue;
471                         if (le16_to_cpu(desc->bg_free_blocks_count) < avefreeb)
472                                 continue;
473                         *group = grp;
474                         ret = 0;
475                         best_ndir = le16_to_cpu(desc->bg_used_dirs_count);
476                 }
477                 if (ret == 0)
478                         return ret;
479                 goto fallback;
480         }
481
482         blocks_per_dir = ext4_blocks_count(es) - freeb;
483         do_div(blocks_per_dir, ndirs);
484
485         max_dirs = ndirs / ngroups + inodes_per_group / 16;
486         min_inodes = avefreei - inodes_per_group / 4;
487         min_blocks = avefreeb - EXT4_BLOCKS_PER_GROUP(sb) / 4;
488
489         max_debt = EXT4_BLOCKS_PER_GROUP(sb);
490         max_debt /= max_t(int, blocks_per_dir, BLOCK_COST);
491         if (max_debt * INODE_COST > inodes_per_group)
492                 max_debt = inodes_per_group / INODE_COST;
493         if (max_debt > 255)
494                 max_debt = 255;
495         if (max_debt == 0)
496                 max_debt = 1;
497
498         for (i = 0; i < ngroups; i++) {
499                 *group = (parent_group + i) % ngroups;
500                 desc = ext4_get_group_desc(sb, *group, NULL);
501                 if (!desc || !desc->bg_free_inodes_count)
502                         continue;
503                 if (le16_to_cpu(desc->bg_used_dirs_count) >= max_dirs)
504                         continue;
505                 if (le16_to_cpu(desc->bg_free_inodes_count) < min_inodes)
506                         continue;
507                 if (le16_to_cpu(desc->bg_free_blocks_count) < min_blocks)
508                         continue;
509                 return 0;
510         }
511
512 fallback:
513         for (i = 0; i < ngroups; i++) {
514                 *group = (parent_group + i) % ngroups;
515                 desc = ext4_get_group_desc(sb, *group, NULL);
516                 if (desc && desc->bg_free_inodes_count &&
517                         le16_to_cpu(desc->bg_free_inodes_count) >= avefreei)
518                         return 0;
519         }
520
521         if (avefreei) {
522                 /*
523                  * The free-inodes counter is approximate, and for really small
524                  * filesystems the above test can fail to find any blockgroups
525                  */
526                 avefreei = 0;
527                 goto fallback;
528         }
529
530         return -1;
531 }
532
533 static int find_group_other(struct super_block *sb, struct inode *parent,
534                                 ext4_group_t *group)
535 {
536         ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
537         ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
538         struct ext4_group_desc *desc;
539         ext4_group_t i;
540
541         /*
542          * Try to place the inode in its parent directory
543          */
544         *group = parent_group;
545         desc = ext4_get_group_desc(sb, *group, NULL);
546         if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
547                         le16_to_cpu(desc->bg_free_blocks_count))
548                 return 0;
549
550         /*
551          * We're going to place this inode in a different blockgroup from its
552          * parent.  We want to cause files in a common directory to all land in
553          * the same blockgroup.  But we want files which are in a different
554          * directory which shares a blockgroup with our parent to land in a
555          * different blockgroup.
556          *
557          * So add our directory's i_ino into the starting point for the hash.
558          */
559         *group = (*group + parent->i_ino) % ngroups;
560
561         /*
562          * Use a quadratic hash to find a group with a free inode and some free
563          * blocks.
564          */
565         for (i = 1; i < ngroups; i <<= 1) {
566                 *group += i;
567                 if (*group >= ngroups)
568                         *group -= ngroups;
569                 desc = ext4_get_group_desc(sb, *group, NULL);
570                 if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
571                                 le16_to_cpu(desc->bg_free_blocks_count))
572                         return 0;
573         }
574
575         /*
576          * That failed: try linear search for a free inode, even if that group
577          * has no free blocks.
578          */
579         *group = parent_group;
580         for (i = 0; i < ngroups; i++) {
581                 if (++*group >= ngroups)
582                         *group = 0;
583                 desc = ext4_get_group_desc(sb, *group, NULL);
584                 if (desc && le16_to_cpu(desc->bg_free_inodes_count))
585                         return 0;
586         }
587
588         return -1;
589 }
590
591 /*
592  * claim the inode from the inode bitmap. If the group
593  * is uninit we need to take the groups's sb_bgl_lock
594  * and clear the uninit flag. The inode bitmap update
595  * and group desc uninit flag clear should be done
596  * after holding sb_bgl_lock so that ext4_read_inode_bitmap
597  * doesn't race with the ext4_claim_inode
598  */
599 static int ext4_claim_inode(struct super_block *sb,
600                         struct buffer_head *inode_bitmap_bh,
601                         unsigned long ino, ext4_group_t group, int mode)
602 {
603         int free = 0, retval = 0;
604         struct ext4_sb_info *sbi = EXT4_SB(sb);
605         struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group, NULL);
606
607         spin_lock(sb_bgl_lock(sbi, group));
608         if (ext4_set_bit(ino, inode_bitmap_bh->b_data)) {
609                 /* not a free inode */
610                 retval = 1;
611                 goto err_ret;
612         }
613         ino++;
614         if ((group == 0 && ino < EXT4_FIRST_INO(sb)) ||
615                         ino > EXT4_INODES_PER_GROUP(sb)) {
616                 spin_unlock(sb_bgl_lock(sbi, group));
617                 ext4_error(sb, __func__,
618                            "reserved inode or inode > inodes count - "
619                            "block_group = %lu, inode=%lu", group,
620                            ino + group * EXT4_INODES_PER_GROUP(sb));
621                 return 1;
622         }
623         /* If we didn't allocate from within the initialized part of the inode
624          * table then we need to initialize up to this inode. */
625         if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
626
627                 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
628                         gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
629                         /* When marking the block group with
630                          * ~EXT4_BG_INODE_UNINIT we don't want to depend
631                          * on the value of bg_itable_unused even though
632                          * mke2fs could have initialized the same for us.
633                          * Instead we calculated the value below
634                          */
635
636                         free = 0;
637                 } else {
638                         free = EXT4_INODES_PER_GROUP(sb) -
639                                 le16_to_cpu(gdp->bg_itable_unused);
640                 }
641
642                 /*
643                  * Check the relative inode number against the last used
644                  * relative inode number in this group. if it is greater
645                  * we need to  update the bg_itable_unused count
646                  *
647                  */
648                 if (ino > free)
649                         gdp->bg_itable_unused =
650                                 cpu_to_le16(EXT4_INODES_PER_GROUP(sb) - ino);
651         }
652         le16_add_cpu(&gdp->bg_free_inodes_count, -1);
653         if (S_ISDIR(mode)) {
654                 le16_add_cpu(&gdp->bg_used_dirs_count, 1);
655         }
656         gdp->bg_checksum = ext4_group_desc_csum(sbi, group, gdp);
657 err_ret:
658         spin_unlock(sb_bgl_lock(sbi, group));
659         return retval;
660 }
661
662 /*
663  * There are two policies for allocating an inode.  If the new inode is
664  * a directory, then a forward search is made for a block group with both
665  * free space and a low directory-to-inode ratio; if that fails, then of
666  * the groups with above-average free space, that group with the fewest
667  * directories already is chosen.
668  *
669  * For other inodes, search forward from the parent directory's block
670  * group to find a free inode.
671  */
672 struct inode *ext4_new_inode(handle_t *handle, struct inode * dir, int mode)
673 {
674         struct super_block *sb;
675         struct buffer_head *bitmap_bh = NULL;
676         struct buffer_head *bh2;
677         ext4_group_t group = 0;
678         unsigned long ino = 0;
679         struct inode * inode;
680         struct ext4_group_desc * gdp = NULL;
681         struct ext4_super_block * es;
682         struct ext4_inode_info *ei;
683         struct ext4_sb_info *sbi;
684         int ret2, err = 0;
685         struct inode *ret;
686         ext4_group_t i;
687         int free = 0;
688         ext4_group_t flex_group;
689
690         /* Cannot create files in a deleted directory */
691         if (!dir || !dir->i_nlink)
692                 return ERR_PTR(-EPERM);
693
694         sb = dir->i_sb;
695         inode = new_inode(sb);
696         if (!inode)
697                 return ERR_PTR(-ENOMEM);
698         ei = EXT4_I(inode);
699
700         sbi = EXT4_SB(sb);
701         es = sbi->s_es;
702
703         if (sbi->s_log_groups_per_flex) {
704                 ret2 = find_group_flex(sb, dir, &group);
705                 if (ret2 == -1) {
706                         ret2 = find_group_other(sb, dir, &group);
707                         if (ret2 == 0 && printk_ratelimit())
708                                 printk(KERN_NOTICE "ext4: find_group_flex "
709                                        "failed, fallback succeeded dir %lu\n",
710                                        dir->i_ino);
711                 }
712                 goto got_group;
713         }
714
715         if (S_ISDIR(mode)) {
716                 if (test_opt (sb, OLDALLOC))
717                         ret2 = find_group_dir(sb, dir, &group);
718                 else
719                         ret2 = find_group_orlov(sb, dir, &group);
720         } else
721                 ret2 = find_group_other(sb, dir, &group);
722
723 got_group:
724         err = -ENOSPC;
725         if (ret2 == -1)
726                 goto out;
727
728         for (i = 0; i < sbi->s_groups_count; i++) {
729                 err = -EIO;
730
731                 gdp = ext4_get_group_desc(sb, group, &bh2);
732                 if (!gdp)
733                         goto fail;
734
735                 brelse(bitmap_bh);
736                 bitmap_bh = ext4_read_inode_bitmap(sb, group);
737                 if (!bitmap_bh)
738                         goto fail;
739
740                 ino = 0;
741
742 repeat_in_this_group:
743                 ino = ext4_find_next_zero_bit((unsigned long *)
744                                 bitmap_bh->b_data, EXT4_INODES_PER_GROUP(sb), ino);
745                 if (ino < EXT4_INODES_PER_GROUP(sb)) {
746
747                         BUFFER_TRACE(bitmap_bh, "get_write_access");
748                         err = ext4_journal_get_write_access(handle, bitmap_bh);
749                         if (err)
750                                 goto fail;
751
752                         BUFFER_TRACE(bh2, "get_write_access");
753                         err = ext4_journal_get_write_access(handle, bh2);
754                         if (err)
755                                 goto fail;
756                         if (!ext4_claim_inode(sb, bitmap_bh,
757                                                 ino, group, mode)) {
758                                 /* we won it */
759                                 BUFFER_TRACE(bitmap_bh,
760                                         "call ext4_journal_dirty_metadata");
761                                 err = ext4_journal_dirty_metadata(handle,
762                                                                 bitmap_bh);
763                                 if (err)
764                                         goto fail;
765                                 /* zero bit is inode number 1*/
766                                 ino++;
767                                 goto got;
768                         }
769                         /* we lost it */
770                         jbd2_journal_release_buffer(handle, bitmap_bh);
771                         jbd2_journal_release_buffer(handle, bh2);
772
773                         if (++ino < EXT4_INODES_PER_GROUP(sb))
774                                 goto repeat_in_this_group;
775                 }
776
777                 /*
778                  * This case is possible in concurrent environment.  It is very
779                  * rare.  We cannot repeat the find_group_xxx() call because
780                  * that will simply return the same blockgroup, because the
781                  * group descriptor metadata has not yet been updated.
782                  * So we just go onto the next blockgroup.
783                  */
784                 if (++group == sbi->s_groups_count)
785                         group = 0;
786         }
787         err = -ENOSPC;
788         goto out;
789
790 got:
791         /* We may have to initialize the block bitmap if it isn't already */
792         if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM) &&
793             gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
794                 struct buffer_head *block_bh = ext4_read_block_bitmap(sb, group);
795
796                 BUFFER_TRACE(block_bh, "get block bitmap access");
797                 err = ext4_journal_get_write_access(handle, block_bh);
798                 if (err) {
799                         brelse(block_bh);
800                         goto fail;
801                 }
802
803                 free = 0;
804                 spin_lock(sb_bgl_lock(sbi, group));
805                 /* recheck and clear flag under lock if we still need to */
806                 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
807                         gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
808                         free = ext4_free_blocks_after_init(sb, group, gdp);
809                         gdp->bg_free_blocks_count = cpu_to_le16(free);
810                         gdp->bg_checksum = ext4_group_desc_csum(sbi, group,
811                                                                 gdp);
812                 }
813                 spin_unlock(sb_bgl_lock(sbi, group));
814
815                 /* Don't need to dirty bitmap block if we didn't change it */
816                 if (free) {
817                         BUFFER_TRACE(block_bh, "dirty block bitmap");
818                         err = ext4_journal_dirty_metadata(handle, block_bh);
819                 }
820
821                 brelse(block_bh);
822                 if (err)
823                         goto fail;
824         }
825         BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata");
826         err = ext4_journal_dirty_metadata(handle, bh2);
827         if (err)
828                 goto fail;
829
830         percpu_counter_dec(&sbi->s_freeinodes_counter);
831         if (S_ISDIR(mode))
832                 percpu_counter_inc(&sbi->s_dirs_counter);
833         sb->s_dirt = 1;
834
835         if (sbi->s_log_groups_per_flex) {
836                 flex_group = ext4_flex_group(sbi, group);
837                 spin_lock(sb_bgl_lock(sbi, flex_group));
838                 sbi->s_flex_groups[flex_group].free_inodes--;
839                 spin_unlock(sb_bgl_lock(sbi, flex_group));
840         }
841
842         inode->i_uid = current->fsuid;
843         if (test_opt (sb, GRPID))
844                 inode->i_gid = dir->i_gid;
845         else if (dir->i_mode & S_ISGID) {
846                 inode->i_gid = dir->i_gid;
847                 if (S_ISDIR(mode))
848                         mode |= S_ISGID;
849         } else
850                 inode->i_gid = current->fsgid;
851         inode->i_mode = mode;
852
853         inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
854         /* This is the optimal IO size (for stat), not the fs block size */
855         inode->i_blocks = 0;
856         inode->i_mtime = inode->i_atime = inode->i_ctime = ei->i_crtime =
857                                                        ext4_current_time(inode);
858
859         memset(ei->i_data, 0, sizeof(ei->i_data));
860         ei->i_dir_start_lookup = 0;
861         ei->i_disksize = 0;
862
863         /*
864          * Don't inherit extent flag from directory. We set extent flag on
865          * newly created directory and file only if -o extent mount option is
866          * specified
867          */
868         ei->i_flags = EXT4_I(dir)->i_flags & ~(EXT4_INDEX_FL|EXT4_EXTENTS_FL);
869         if (S_ISLNK(mode))
870                 ei->i_flags &= ~(EXT4_IMMUTABLE_FL|EXT4_APPEND_FL);
871         /* dirsync only applies to directories */
872         if (!S_ISDIR(mode))
873                 ei->i_flags &= ~EXT4_DIRSYNC_FL;
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