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