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