3e960677c2f285c1ceacf402efa8574b0bfdf2b9
[pandora-kernel.git] / fs / ext4 / resize.c
1 /*
2  *  linux/fs/ext4/resize.c
3  *
4  * Support for resizing an ext4 filesystem while it is mounted.
5  *
6  * Copyright (C) 2001, 2002 Andreas Dilger <adilger@clusterfs.com>
7  *
8  * This could probably be made into a module, because it is not often in use.
9  */
10
11
12 #define EXT4FS_DEBUG
13
14 #include <linux/sched.h>
15 #include <linux/smp_lock.h>
16 #include <linux/ext4_jbd2.h>
17
18 #include <linux/errno.h>
19 #include <linux/slab.h>
20
21
22 #define outside(b, first, last) ((b) < (first) || (b) >= (last))
23 #define inside(b, first, last)  ((b) >= (first) && (b) < (last))
24
25 static int verify_group_input(struct super_block *sb,
26                               struct ext4_new_group_data *input)
27 {
28         struct ext4_sb_info *sbi = EXT4_SB(sb);
29         struct ext4_super_block *es = sbi->s_es;
30         ext4_fsblk_t start = ext4_blocks_count(es);
31         ext4_fsblk_t end = start + input->blocks_count;
32         unsigned group = input->group;
33         ext4_fsblk_t itend = input->inode_table + sbi->s_itb_per_group;
34         unsigned overhead = ext4_bg_has_super(sb, group) ?
35                 (1 + ext4_bg_num_gdb(sb, group) +
36                  le16_to_cpu(es->s_reserved_gdt_blocks)) : 0;
37         ext4_fsblk_t metaend = start + overhead;
38         struct buffer_head *bh = NULL;
39         ext4_grpblk_t free_blocks_count, offset;
40         int err = -EINVAL;
41
42         input->free_blocks_count = free_blocks_count =
43                 input->blocks_count - 2 - overhead - sbi->s_itb_per_group;
44
45         if (test_opt(sb, DEBUG))
46                 printk(KERN_DEBUG "EXT4-fs: adding %s group %u: %u blocks "
47                        "(%d free, %u reserved)\n",
48                        ext4_bg_has_super(sb, input->group) ? "normal" :
49                        "no-super", input->group, input->blocks_count,
50                        free_blocks_count, input->reserved_blocks);
51
52         ext4_get_group_no_and_offset(sb, start, NULL, &offset);
53         if (group != sbi->s_groups_count)
54                 ext4_warning(sb, __FUNCTION__,
55                              "Cannot add at group %u (only %lu groups)",
56                              input->group, sbi->s_groups_count);
57         else if (offset != 0)
58                         ext4_warning(sb, __FUNCTION__, "Last group not full");
59         else if (input->reserved_blocks > input->blocks_count / 5)
60                 ext4_warning(sb, __FUNCTION__, "Reserved blocks too high (%u)",
61                              input->reserved_blocks);
62         else if (free_blocks_count < 0)
63                 ext4_warning(sb, __FUNCTION__, "Bad blocks count %u",
64                              input->blocks_count);
65         else if (!(bh = sb_bread(sb, end - 1)))
66                 ext4_warning(sb, __FUNCTION__,
67                              "Cannot read last block (%llu)",
68                              end - 1);
69         else if (outside(input->block_bitmap, start, end))
70                 ext4_warning(sb, __FUNCTION__,
71                              "Block bitmap not in group (block %llu)",
72                              input->block_bitmap);
73         else if (outside(input->inode_bitmap, start, end))
74                 ext4_warning(sb, __FUNCTION__,
75                              "Inode bitmap not in group (block %llu)",
76                              input->inode_bitmap);
77         else if (outside(input->inode_table, start, end) ||
78                  outside(itend - 1, start, end))
79                 ext4_warning(sb, __FUNCTION__,
80                              "Inode table not in group (blocks %llu-%llu)",
81                              input->inode_table, itend - 1);
82         else if (input->inode_bitmap == input->block_bitmap)
83                 ext4_warning(sb, __FUNCTION__,
84                              "Block bitmap same as inode bitmap (%llu)",
85                              input->block_bitmap);
86         else if (inside(input->block_bitmap, input->inode_table, itend))
87                 ext4_warning(sb, __FUNCTION__,
88                              "Block bitmap (%llu) in inode table (%llu-%llu)",
89                              input->block_bitmap, input->inode_table, itend-1);
90         else if (inside(input->inode_bitmap, input->inode_table, itend))
91                 ext4_warning(sb, __FUNCTION__,
92                              "Inode bitmap (%llu) in inode table (%llu-%llu)",
93                              input->inode_bitmap, input->inode_table, itend-1);
94         else if (inside(input->block_bitmap, start, metaend))
95                 ext4_warning(sb, __FUNCTION__,
96                              "Block bitmap (%llu) in GDT table"
97                              " (%llu-%llu)",
98                              input->block_bitmap, start, metaend - 1);
99         else if (inside(input->inode_bitmap, start, metaend))
100                 ext4_warning(sb, __FUNCTION__,
101                              "Inode bitmap (%llu) in GDT table"
102                              " (%llu-%llu)",
103                              input->inode_bitmap, start, metaend - 1);
104         else if (inside(input->inode_table, start, metaend) ||
105                  inside(itend - 1, start, metaend))
106                 ext4_warning(sb, __FUNCTION__,
107                              "Inode table (%llu-%llu) overlaps"
108                              "GDT table (%llu-%llu)",
109                              input->inode_table, itend - 1, start, metaend - 1);
110         else
111                 err = 0;
112         brelse(bh);
113
114         return err;
115 }
116
117 static struct buffer_head *bclean(handle_t *handle, struct super_block *sb,
118                                   ext4_fsblk_t blk)
119 {
120         struct buffer_head *bh;
121         int err;
122
123         bh = sb_getblk(sb, blk);
124         if (!bh)
125                 return ERR_PTR(-EIO);
126         if ((err = ext4_journal_get_write_access(handle, bh))) {
127                 brelse(bh);
128                 bh = ERR_PTR(err);
129         } else {
130                 lock_buffer(bh);
131                 memset(bh->b_data, 0, sb->s_blocksize);
132                 set_buffer_uptodate(bh);
133                 unlock_buffer(bh);
134         }
135
136         return bh;
137 }
138
139 /*
140  * To avoid calling the atomic setbit hundreds or thousands of times, we only
141  * need to use it within a single byte (to ensure we get endianness right).
142  * We can use memset for the rest of the bitmap as there are no other users.
143  */
144 static void mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
145 {
146         int i;
147
148         if (start_bit >= end_bit)
149                 return;
150
151         ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit);
152         for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
153                 ext4_set_bit(i, bitmap);
154         if (i < end_bit)
155                 memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
156 }
157
158 /*
159  * Set up the block and inode bitmaps, and the inode table for the new group.
160  * This doesn't need to be part of the main transaction, since we are only
161  * changing blocks outside the actual filesystem.  We still do journaling to
162  * ensure the recovery is correct in case of a failure just after resize.
163  * If any part of this fails, we simply abort the resize.
164  */
165 static int setup_new_group_blocks(struct super_block *sb,
166                                   struct ext4_new_group_data *input)
167 {
168         struct ext4_sb_info *sbi = EXT4_SB(sb);
169         ext4_fsblk_t start = ext4_group_first_block_no(sb, input->group);
170         int reserved_gdb = ext4_bg_has_super(sb, input->group) ?
171                 le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) : 0;
172         unsigned long gdblocks = ext4_bg_num_gdb(sb, input->group);
173         struct buffer_head *bh;
174         handle_t *handle;
175         ext4_fsblk_t block;
176         ext4_grpblk_t bit;
177         int i;
178         int err = 0, err2;
179
180         handle = ext4_journal_start_sb(sb, reserved_gdb + gdblocks +
181                                        2 + sbi->s_itb_per_group);
182         if (IS_ERR(handle))
183                 return PTR_ERR(handle);
184
185         lock_super(sb);
186         if (input->group != sbi->s_groups_count) {
187                 err = -EBUSY;
188                 goto exit_journal;
189         }
190
191         if (IS_ERR(bh = bclean(handle, sb, input->block_bitmap))) {
192                 err = PTR_ERR(bh);
193                 goto exit_journal;
194         }
195
196         if (ext4_bg_has_super(sb, input->group)) {
197                 ext4_debug("mark backup superblock %#04lx (+0)\n", start);
198                 ext4_set_bit(0, bh->b_data);
199         }
200
201         /* Copy all of the GDT blocks into the backup in this group */
202         for (i = 0, bit = 1, block = start + 1;
203              i < gdblocks; i++, block++, bit++) {
204                 struct buffer_head *gdb;
205
206                 ext4_debug("update backup group %#04lx (+%d)\n", block, bit);
207
208                 gdb = sb_getblk(sb, block);
209                 if (!gdb) {
210                         err = -EIO;
211                         goto exit_bh;
212                 }
213                 if ((err = ext4_journal_get_write_access(handle, gdb))) {
214                         brelse(gdb);
215                         goto exit_bh;
216                 }
217                 lock_buffer(bh);
218                 memcpy(gdb->b_data, sbi->s_group_desc[i]->b_data, bh->b_size);
219                 set_buffer_uptodate(gdb);
220                 unlock_buffer(bh);
221                 ext4_journal_dirty_metadata(handle, gdb);
222                 ext4_set_bit(bit, bh->b_data);
223                 brelse(gdb);
224         }
225
226         /* Zero out all of the reserved backup group descriptor table blocks */
227         for (i = 0, bit = gdblocks + 1, block = start + bit;
228              i < reserved_gdb; i++, block++, bit++) {
229                 struct buffer_head *gdb;
230
231                 ext4_debug("clear reserved block %#04lx (+%d)\n", block, bit);
232
233                 if (IS_ERR(gdb = bclean(handle, sb, block))) {
234                         err = PTR_ERR(bh);
235                         goto exit_bh;
236                 }
237                 ext4_journal_dirty_metadata(handle, gdb);
238                 ext4_set_bit(bit, bh->b_data);
239                 brelse(gdb);
240         }
241         ext4_debug("mark block bitmap %#04x (+%ld)\n", input->block_bitmap,
242                    input->block_bitmap - start);
243         ext4_set_bit(input->block_bitmap - start, bh->b_data);
244         ext4_debug("mark inode bitmap %#04x (+%ld)\n", input->inode_bitmap,
245                    input->inode_bitmap - start);
246         ext4_set_bit(input->inode_bitmap - start, bh->b_data);
247
248         /* Zero out all of the inode table blocks */
249         for (i = 0, block = input->inode_table, bit = block - start;
250              i < sbi->s_itb_per_group; i++, bit++, block++) {
251                 struct buffer_head *it;
252
253                 ext4_debug("clear inode block %#04lx (+%d)\n", block, bit);
254                 if (IS_ERR(it = bclean(handle, sb, block))) {
255                         err = PTR_ERR(it);
256                         goto exit_bh;
257                 }
258                 ext4_journal_dirty_metadata(handle, it);
259                 brelse(it);
260                 ext4_set_bit(bit, bh->b_data);
261         }
262         mark_bitmap_end(input->blocks_count, EXT4_BLOCKS_PER_GROUP(sb),
263                         bh->b_data);
264         ext4_journal_dirty_metadata(handle, bh);
265         brelse(bh);
266
267         /* Mark unused entries in inode bitmap used */
268         ext4_debug("clear inode bitmap %#04x (+%ld)\n",
269                    input->inode_bitmap, input->inode_bitmap - start);
270         if (IS_ERR(bh = bclean(handle, sb, input->inode_bitmap))) {
271                 err = PTR_ERR(bh);
272                 goto exit_journal;
273         }
274
275         mark_bitmap_end(EXT4_INODES_PER_GROUP(sb), EXT4_BLOCKS_PER_GROUP(sb),
276                         bh->b_data);
277         ext4_journal_dirty_metadata(handle, bh);
278 exit_bh:
279         brelse(bh);
280
281 exit_journal:
282         unlock_super(sb);
283         if ((err2 = ext4_journal_stop(handle)) && !err)
284                 err = err2;
285
286         return err;
287 }
288
289
290 /*
291  * Iterate through the groups which hold BACKUP superblock/GDT copies in an
292  * ext4 filesystem.  The counters should be initialized to 1, 5, and 7 before
293  * calling this for the first time.  In a sparse filesystem it will be the
294  * sequence of powers of 3, 5, and 7: 1, 3, 5, 7, 9, 25, 27, 49, 81, ...
295  * For a non-sparse filesystem it will be every group: 1, 2, 3, 4, ...
296  */
297 static unsigned ext4_list_backups(struct super_block *sb, unsigned *three,
298                                   unsigned *five, unsigned *seven)
299 {
300         unsigned *min = three;
301         int mult = 3;
302         unsigned ret;
303
304         if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
305                                         EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
306                 ret = *min;
307                 *min += 1;
308                 return ret;
309         }
310
311         if (*five < *min) {
312                 min = five;
313                 mult = 5;
314         }
315         if (*seven < *min) {
316                 min = seven;
317                 mult = 7;
318         }
319
320         ret = *min;
321         *min *= mult;
322
323         return ret;
324 }
325
326 /*
327  * Check that all of the backup GDT blocks are held in the primary GDT block.
328  * It is assumed that they are stored in group order.  Returns the number of
329  * groups in current filesystem that have BACKUPS, or -ve error code.
330  */
331 static int verify_reserved_gdb(struct super_block *sb,
332                                struct buffer_head *primary)
333 {
334         const ext4_fsblk_t blk = primary->b_blocknr;
335         const unsigned long end = EXT4_SB(sb)->s_groups_count;
336         unsigned three = 1;
337         unsigned five = 5;
338         unsigned seven = 7;
339         unsigned grp;
340         __le32 *p = (__le32 *)primary->b_data;
341         int gdbackups = 0;
342
343         while ((grp = ext4_list_backups(sb, &three, &five, &seven)) < end) {
344                 if (le32_to_cpu(*p++) !=
345                     grp * EXT4_BLOCKS_PER_GROUP(sb) + blk){
346                         ext4_warning(sb, __FUNCTION__,
347                                      "reserved GDT %llu"
348                                      " missing grp %d (%llu)",
349                                      blk, grp,
350                                      grp *
351                                      (ext4_fsblk_t)EXT4_BLOCKS_PER_GROUP(sb) +
352                                      blk);
353                         return -EINVAL;
354                 }
355                 if (++gdbackups > EXT4_ADDR_PER_BLOCK(sb))
356                         return -EFBIG;
357         }
358
359         return gdbackups;
360 }
361
362 /*
363  * Called when we need to bring a reserved group descriptor table block into
364  * use from the resize inode.  The primary copy of the new GDT block currently
365  * is an indirect block (under the double indirect block in the resize inode).
366  * The new backup GDT blocks will be stored as leaf blocks in this indirect
367  * block, in group order.  Even though we know all the block numbers we need,
368  * we check to ensure that the resize inode has actually reserved these blocks.
369  *
370  * Don't need to update the block bitmaps because the blocks are still in use.
371  *
372  * We get all of the error cases out of the way, so that we are sure to not
373  * fail once we start modifying the data on disk, because JBD has no rollback.
374  */
375 static int add_new_gdb(handle_t *handle, struct inode *inode,
376                        struct ext4_new_group_data *input,
377                        struct buffer_head **primary)
378 {
379         struct super_block *sb = inode->i_sb;
380         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
381         unsigned long gdb_num = input->group / EXT4_DESC_PER_BLOCK(sb);
382         ext4_fsblk_t gdblock = EXT4_SB(sb)->s_sbh->b_blocknr + 1 + gdb_num;
383         struct buffer_head **o_group_desc, **n_group_desc;
384         struct buffer_head *dind;
385         int gdbackups;
386         struct ext4_iloc iloc;
387         __le32 *data;
388         int err;
389
390         if (test_opt(sb, DEBUG))
391                 printk(KERN_DEBUG
392                        "EXT4-fs: ext4_add_new_gdb: adding group block %lu\n",
393                        gdb_num);
394
395         /*
396          * If we are not using the primary superblock/GDT copy don't resize,
397          * because the user tools have no way of handling this.  Probably a
398          * bad time to do it anyways.
399          */
400         if (EXT4_SB(sb)->s_sbh->b_blocknr !=
401             le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) {
402                 ext4_warning(sb, __FUNCTION__,
403                         "won't resize using backup superblock at %llu",
404                         (unsigned long long)EXT4_SB(sb)->s_sbh->b_blocknr);
405                 return -EPERM;
406         }
407
408         *primary = sb_bread(sb, gdblock);
409         if (!*primary)
410                 return -EIO;
411
412         if ((gdbackups = verify_reserved_gdb(sb, *primary)) < 0) {
413                 err = gdbackups;
414                 goto exit_bh;
415         }
416
417         data = EXT4_I(inode)->i_data + EXT4_DIND_BLOCK;
418         dind = sb_bread(sb, le32_to_cpu(*data));
419         if (!dind) {
420                 err = -EIO;
421                 goto exit_bh;
422         }
423
424         data = (__le32 *)dind->b_data;
425         if (le32_to_cpu(data[gdb_num % EXT4_ADDR_PER_BLOCK(sb)]) != gdblock) {
426                 ext4_warning(sb, __FUNCTION__,
427                              "new group %u GDT block %llu not reserved",
428                              input->group, gdblock);
429                 err = -EINVAL;
430                 goto exit_dind;
431         }
432
433         if ((err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh)))
434                 goto exit_dind;
435
436         if ((err = ext4_journal_get_write_access(handle, *primary)))
437                 goto exit_sbh;
438
439         if ((err = ext4_journal_get_write_access(handle, dind)))
440                 goto exit_primary;
441
442         /* ext4_reserve_inode_write() gets a reference on the iloc */
443         if ((err = ext4_reserve_inode_write(handle, inode, &iloc)))
444                 goto exit_dindj;
445
446         n_group_desc = kmalloc((gdb_num + 1) * sizeof(struct buffer_head *),
447                         GFP_KERNEL);
448         if (!n_group_desc) {
449                 err = -ENOMEM;
450                 ext4_warning (sb, __FUNCTION__,
451                               "not enough memory for %lu groups", gdb_num + 1);
452                 goto exit_inode;
453         }
454
455         /*
456          * Finally, we have all of the possible failures behind us...
457          *
458          * Remove new GDT block from inode double-indirect block and clear out
459          * the new GDT block for use (which also "frees" the backup GDT blocks
460          * from the reserved inode).  We don't need to change the bitmaps for
461          * these blocks, because they are marked as in-use from being in the
462          * reserved inode, and will become GDT blocks (primary and backup).
463          */
464         data[gdb_num % EXT4_ADDR_PER_BLOCK(sb)] = 0;
465         ext4_journal_dirty_metadata(handle, dind);
466         brelse(dind);
467         inode->i_blocks -= (gdbackups + 1) * sb->s_blocksize >> 9;
468         ext4_mark_iloc_dirty(handle, inode, &iloc);
469         memset((*primary)->b_data, 0, sb->s_blocksize);
470         ext4_journal_dirty_metadata(handle, *primary);
471
472         o_group_desc = EXT4_SB(sb)->s_group_desc;
473         memcpy(n_group_desc, o_group_desc,
474                EXT4_SB(sb)->s_gdb_count * sizeof(struct buffer_head *));
475         n_group_desc[gdb_num] = *primary;
476         EXT4_SB(sb)->s_group_desc = n_group_desc;
477         EXT4_SB(sb)->s_gdb_count++;
478         kfree(o_group_desc);
479
480         es->s_reserved_gdt_blocks =
481                 cpu_to_le16(le16_to_cpu(es->s_reserved_gdt_blocks) - 1);
482         ext4_journal_dirty_metadata(handle, EXT4_SB(sb)->s_sbh);
483
484         return 0;
485
486 exit_inode:
487         //ext4_journal_release_buffer(handle, iloc.bh);
488         brelse(iloc.bh);
489 exit_dindj:
490         //ext4_journal_release_buffer(handle, dind);
491 exit_primary:
492         //ext4_journal_release_buffer(handle, *primary);
493 exit_sbh:
494         //ext4_journal_release_buffer(handle, *primary);
495 exit_dind:
496         brelse(dind);
497 exit_bh:
498         brelse(*primary);
499
500         ext4_debug("leaving with error %d\n", err);
501         return err;
502 }
503
504 /*
505  * Called when we are adding a new group which has a backup copy of each of
506  * the GDT blocks (i.e. sparse group) and there are reserved GDT blocks.
507  * We need to add these reserved backup GDT blocks to the resize inode, so
508  * that they are kept for future resizing and not allocated to files.
509  *
510  * Each reserved backup GDT block will go into a different indirect block.
511  * The indirect blocks are actually the primary reserved GDT blocks,
512  * so we know in advance what their block numbers are.  We only get the
513  * double-indirect block to verify it is pointing to the primary reserved
514  * GDT blocks so we don't overwrite a data block by accident.  The reserved
515  * backup GDT blocks are stored in their reserved primary GDT block.
516  */
517 static int reserve_backup_gdb(handle_t *handle, struct inode *inode,
518                               struct ext4_new_group_data *input)
519 {
520         struct super_block *sb = inode->i_sb;
521         int reserved_gdb =le16_to_cpu(EXT4_SB(sb)->s_es->s_reserved_gdt_blocks);
522         struct buffer_head **primary;
523         struct buffer_head *dind;
524         struct ext4_iloc iloc;
525         ext4_fsblk_t blk;
526         __le32 *data, *end;
527         int gdbackups = 0;
528         int res, i;
529         int err;
530
531         primary = kmalloc(reserved_gdb * sizeof(*primary), GFP_KERNEL);
532         if (!primary)
533                 return -ENOMEM;
534
535         data = EXT4_I(inode)->i_data + EXT4_DIND_BLOCK;
536         dind = sb_bread(sb, le32_to_cpu(*data));
537         if (!dind) {
538                 err = -EIO;
539                 goto exit_free;
540         }
541
542         blk = EXT4_SB(sb)->s_sbh->b_blocknr + 1 + EXT4_SB(sb)->s_gdb_count;
543         data = (__le32 *)dind->b_data + EXT4_SB(sb)->s_gdb_count;
544         end = (__le32 *)dind->b_data + EXT4_ADDR_PER_BLOCK(sb);
545
546         /* Get each reserved primary GDT block and verify it holds backups */
547         for (res = 0; res < reserved_gdb; res++, blk++) {
548                 if (le32_to_cpu(*data) != blk) {
549                         ext4_warning(sb, __FUNCTION__,
550                                      "reserved block %llu"
551                                      " not at offset %ld",
552                                      blk,
553                                      (long)(data - (__le32 *)dind->b_data));
554                         err = -EINVAL;
555                         goto exit_bh;
556                 }
557                 primary[res] = sb_bread(sb, blk);
558                 if (!primary[res]) {
559                         err = -EIO;
560                         goto exit_bh;
561                 }
562                 if ((gdbackups = verify_reserved_gdb(sb, primary[res])) < 0) {
563                         brelse(primary[res]);
564                         err = gdbackups;
565                         goto exit_bh;
566                 }
567                 if (++data >= end)
568                         data = (__le32 *)dind->b_data;
569         }
570
571         for (i = 0; i < reserved_gdb; i++) {
572                 if ((err = ext4_journal_get_write_access(handle, primary[i]))) {
573                         /*
574                         int j;
575                         for (j = 0; j < i; j++)
576                                 ext4_journal_release_buffer(handle, primary[j]);
577                          */
578                         goto exit_bh;
579                 }
580         }
581
582         if ((err = ext4_reserve_inode_write(handle, inode, &iloc)))
583                 goto exit_bh;
584
585         /*
586          * Finally we can add each of the reserved backup GDT blocks from
587          * the new group to its reserved primary GDT block.
588          */
589         blk = input->group * EXT4_BLOCKS_PER_GROUP(sb);
590         for (i = 0; i < reserved_gdb; i++) {
591                 int err2;
592                 data = (__le32 *)primary[i]->b_data;
593                 /* printk("reserving backup %lu[%u] = %lu\n",
594                        primary[i]->b_blocknr, gdbackups,
595                        blk + primary[i]->b_blocknr); */
596                 data[gdbackups] = cpu_to_le32(blk + primary[i]->b_blocknr);
597                 err2 = ext4_journal_dirty_metadata(handle, primary[i]);
598                 if (!err)
599                         err = err2;
600         }
601         inode->i_blocks += reserved_gdb * sb->s_blocksize >> 9;
602         ext4_mark_iloc_dirty(handle, inode, &iloc);
603
604 exit_bh:
605         while (--res >= 0)
606                 brelse(primary[res]);
607         brelse(dind);
608
609 exit_free:
610         kfree(primary);
611
612         return err;
613 }
614
615 /*
616  * Update the backup copies of the ext4 metadata.  These don't need to be part
617  * of the main resize transaction, because e2fsck will re-write them if there
618  * is a problem (basically only OOM will cause a problem).  However, we
619  * _should_ update the backups if possible, in case the primary gets trashed
620  * for some reason and we need to run e2fsck from a backup superblock.  The
621  * important part is that the new block and inode counts are in the backup
622  * superblocks, and the location of the new group metadata in the GDT backups.
623  *
624  * We do not need lock_super() for this, because these blocks are not
625  * otherwise touched by the filesystem code when it is mounted.  We don't
626  * need to worry about last changing from sbi->s_groups_count, because the
627  * worst that can happen is that we do not copy the full number of backups
628  * at this time.  The resize which changed s_groups_count will backup again.
629  */
630 static void update_backups(struct super_block *sb,
631                            int blk_off, char *data, int size)
632 {
633         struct ext4_sb_info *sbi = EXT4_SB(sb);
634         const unsigned long last = sbi->s_groups_count;
635         const int bpg = EXT4_BLOCKS_PER_GROUP(sb);
636         unsigned three = 1;
637         unsigned five = 5;
638         unsigned seven = 7;
639         unsigned group;
640         int rest = sb->s_blocksize - size;
641         handle_t *handle;
642         int err = 0, err2;
643
644         handle = ext4_journal_start_sb(sb, EXT4_MAX_TRANS_DATA);
645         if (IS_ERR(handle)) {
646                 group = 1;
647                 err = PTR_ERR(handle);
648                 goto exit_err;
649         }
650
651         while ((group = ext4_list_backups(sb, &three, &five, &seven)) < last) {
652                 struct buffer_head *bh;
653
654                 /* Out of journal space, and can't get more - abort - so sad */
655                 if (handle->h_buffer_credits == 0 &&
656                     ext4_journal_extend(handle, EXT4_MAX_TRANS_DATA) &&
657                     (err = ext4_journal_restart(handle, EXT4_MAX_TRANS_DATA)))
658                         break;
659
660                 bh = sb_getblk(sb, group * bpg + blk_off);
661                 if (!bh) {
662                         err = -EIO;
663                         break;
664                 }
665                 ext4_debug("update metadata backup %#04lx\n",
666                           (unsigned long)bh->b_blocknr);
667                 if ((err = ext4_journal_get_write_access(handle, bh)))
668                         break;
669                 lock_buffer(bh);
670                 memcpy(bh->b_data, data, size);
671                 if (rest)
672                         memset(bh->b_data + size, 0, rest);
673                 set_buffer_uptodate(bh);
674                 unlock_buffer(bh);
675                 ext4_journal_dirty_metadata(handle, bh);
676                 brelse(bh);
677         }
678         if ((err2 = ext4_journal_stop(handle)) && !err)
679                 err = err2;
680
681         /*
682          * Ugh! Need to have e2fsck write the backup copies.  It is too
683          * late to revert the resize, we shouldn't fail just because of
684          * the backup copies (they are only needed in case of corruption).
685          *
686          * However, if we got here we have a journal problem too, so we
687          * can't really start a transaction to mark the superblock.
688          * Chicken out and just set the flag on the hope it will be written
689          * to disk, and if not - we will simply wait until next fsck.
690          */
691 exit_err:
692         if (err) {
693                 ext4_warning(sb, __FUNCTION__,
694                              "can't update backup for group %d (err %d), "
695                              "forcing fsck on next reboot", group, err);
696                 sbi->s_mount_state &= ~EXT4_VALID_FS;
697                 sbi->s_es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
698                 mark_buffer_dirty(sbi->s_sbh);
699         }
700 }
701
702 /* Add group descriptor data to an existing or new group descriptor block.
703  * Ensure we handle all possible error conditions _before_ we start modifying
704  * the filesystem, because we cannot abort the transaction and not have it
705  * write the data to disk.
706  *
707  * If we are on a GDT block boundary, we need to get the reserved GDT block.
708  * Otherwise, we may need to add backup GDT blocks for a sparse group.
709  *
710  * We only need to hold the superblock lock while we are actually adding
711  * in the new group's counts to the superblock.  Prior to that we have
712  * not really "added" the group at all.  We re-check that we are still
713  * adding in the last group in case things have changed since verifying.
714  */
715 int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input)
716 {
717         struct ext4_sb_info *sbi = EXT4_SB(sb);
718         struct ext4_super_block *es = sbi->s_es;
719         int reserved_gdb = ext4_bg_has_super(sb, input->group) ?
720                 le16_to_cpu(es->s_reserved_gdt_blocks) : 0;
721         struct buffer_head *primary = NULL;
722         struct ext4_group_desc *gdp;
723         struct inode *inode = NULL;
724         handle_t *handle;
725         int gdb_off, gdb_num;
726         int err, err2;
727
728         gdb_num = input->group / EXT4_DESC_PER_BLOCK(sb);
729         gdb_off = input->group % EXT4_DESC_PER_BLOCK(sb);
730
731         if (gdb_off == 0 && !EXT4_HAS_RO_COMPAT_FEATURE(sb,
732                                         EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
733                 ext4_warning(sb, __FUNCTION__,
734                              "Can't resize non-sparse filesystem further");
735                 return -EPERM;
736         }
737
738         if (ext4_blocks_count(es) + input->blocks_count <
739             ext4_blocks_count(es)) {
740                 ext4_warning(sb, __FUNCTION__, "blocks_count overflow\n");
741                 return -EINVAL;
742         }
743
744         if (le32_to_cpu(es->s_inodes_count) + EXT4_INODES_PER_GROUP(sb) <
745             le32_to_cpu(es->s_inodes_count)) {
746                 ext4_warning(sb, __FUNCTION__, "inodes_count overflow\n");
747                 return -EINVAL;
748         }
749
750         if (reserved_gdb || gdb_off == 0) {
751                 if (!EXT4_HAS_COMPAT_FEATURE(sb,
752                                              EXT4_FEATURE_COMPAT_RESIZE_INODE)){
753                         ext4_warning(sb, __FUNCTION__,
754                                      "No reserved GDT blocks, can't resize");
755                         return -EPERM;
756                 }
757                 inode = iget(sb, EXT4_RESIZE_INO);
758                 if (!inode || is_bad_inode(inode)) {
759                         ext4_warning(sb, __FUNCTION__,
760                                      "Error opening resize inode");
761                         iput(inode);
762                         return -ENOENT;
763                 }
764         }
765
766         if ((err = verify_group_input(sb, input)))
767                 goto exit_put;
768
769         if ((err = setup_new_group_blocks(sb, input)))
770                 goto exit_put;
771
772         /*
773          * We will always be modifying at least the superblock and a GDT
774          * block.  If we are adding a group past the last current GDT block,
775          * we will also modify the inode and the dindirect block.  If we
776          * are adding a group with superblock/GDT backups  we will also
777          * modify each of the reserved GDT dindirect blocks.
778          */
779         handle = ext4_journal_start_sb(sb,
780                                        ext4_bg_has_super(sb, input->group) ?
781                                        3 + reserved_gdb : 4);
782         if (IS_ERR(handle)) {
783                 err = PTR_ERR(handle);
784                 goto exit_put;
785         }
786
787         lock_super(sb);
788         if (input->group != sbi->s_groups_count) {
789                 ext4_warning(sb, __FUNCTION__,
790                              "multiple resizers run on filesystem!");
791                 err = -EBUSY;
792                 goto exit_journal;
793         }
794
795         if ((err = ext4_journal_get_write_access(handle, sbi->s_sbh)))
796                 goto exit_journal;
797
798         /*
799          * We will only either add reserved group blocks to a backup group
800          * or remove reserved blocks for the first group in a new group block.
801          * Doing both would be mean more complex code, and sane people don't
802          * use non-sparse filesystems anymore.  This is already checked above.
803          */
804         if (gdb_off) {
805                 primary = sbi->s_group_desc[gdb_num];
806                 if ((err = ext4_journal_get_write_access(handle, primary)))
807                         goto exit_journal;
808
809                 if (reserved_gdb && ext4_bg_num_gdb(sb, input->group) &&
810                     (err = reserve_backup_gdb(handle, inode, input)))
811                         goto exit_journal;
812         } else if ((err = add_new_gdb(handle, inode, input, &primary)))
813                 goto exit_journal;
814
815         /*
816          * OK, now we've set up the new group.  Time to make it active.
817          *
818          * Current kernels don't lock all allocations via lock_super(),
819          * so we have to be safe wrt. concurrent accesses the group
820          * data.  So we need to be careful to set all of the relevant
821          * group descriptor data etc. *before* we enable the group.
822          *
823          * The key field here is sbi->s_groups_count: as long as
824          * that retains its old value, nobody is going to access the new
825          * group.
826          *
827          * So first we update all the descriptor metadata for the new
828          * group; then we update the total disk blocks count; then we
829          * update the groups count to enable the group; then finally we
830          * update the free space counts so that the system can start
831          * using the new disk blocks.
832          */
833
834         /* Update group descriptor block for new group */
835         gdp = (struct ext4_group_desc *)primary->b_data + gdb_off;
836
837         ext4_block_bitmap_set(gdp, input->block_bitmap); /* LV FIXME */
838         ext4_inode_bitmap_set(gdp, input->inode_bitmap); /* LV FIXME */
839         ext4_inode_table_set(gdp, input->inode_table); /* LV FIXME */
840         gdp->bg_free_blocks_count = cpu_to_le16(input->free_blocks_count);
841         gdp->bg_free_inodes_count = cpu_to_le16(EXT4_INODES_PER_GROUP(sb));
842
843         /*
844          * Make the new blocks and inodes valid next.  We do this before
845          * increasing the group count so that once the group is enabled,
846          * all of its blocks and inodes are already valid.
847          *
848          * We always allocate group-by-group, then block-by-block or
849          * inode-by-inode within a group, so enabling these
850          * blocks/inodes before the group is live won't actually let us
851          * allocate the new space yet.
852          */
853         ext4_blocks_count_set(es, ext4_blocks_count(es) +
854                 input->blocks_count);
855         es->s_inodes_count = cpu_to_le32(le32_to_cpu(es->s_inodes_count) +
856                 EXT4_INODES_PER_GROUP(sb));
857
858         /*
859          * We need to protect s_groups_count against other CPUs seeing
860          * inconsistent state in the superblock.
861          *
862          * The precise rules we use are:
863          *
864          * * Writers of s_groups_count *must* hold lock_super
865          * AND
866          * * Writers must perform a smp_wmb() after updating all dependent
867          *   data and before modifying the groups count
868          *
869          * * Readers must hold lock_super() over the access
870          * OR
871          * * Readers must perform an smp_rmb() after reading the groups count
872          *   and before reading any dependent data.
873          *
874          * NB. These rules can be relaxed when checking the group count
875          * while freeing data, as we can only allocate from a block
876          * group after serialising against the group count, and we can
877          * only then free after serialising in turn against that
878          * allocation.
879          */
880         smp_wmb();
881
882         /* Update the global fs size fields */
883         sbi->s_groups_count++;
884
885         ext4_journal_dirty_metadata(handle, primary);
886
887         /* Update the reserved block counts only once the new group is
888          * active. */
889         ext4_r_blocks_count_set(es, ext4_r_blocks_count(es) +
890                 input->reserved_blocks);
891
892         /* Update the free space counts */
893         percpu_counter_mod(&sbi->s_freeblocks_counter,
894                            input->free_blocks_count);
895         percpu_counter_mod(&sbi->s_freeinodes_counter,
896                            EXT4_INODES_PER_GROUP(sb));
897
898         ext4_journal_dirty_metadata(handle, sbi->s_sbh);
899         sb->s_dirt = 1;
900
901 exit_journal:
902         unlock_super(sb);
903         if ((err2 = ext4_journal_stop(handle)) && !err)
904                 err = err2;
905         if (!err) {
906                 update_backups(sb, sbi->s_sbh->b_blocknr, (char *)es,
907                                sizeof(struct ext4_super_block));
908                 update_backups(sb, primary->b_blocknr, primary->b_data,
909                                primary->b_size);
910         }
911 exit_put:
912         iput(inode);
913         return err;
914 } /* ext4_group_add */
915
916 /* Extend the filesystem to the new number of blocks specified.  This entry
917  * point is only used to extend the current filesystem to the end of the last
918  * existing group.  It can be accessed via ioctl, or by "remount,resize=<size>"
919  * for emergencies (because it has no dependencies on reserved blocks).
920  *
921  * If we _really_ wanted, we could use default values to call ext4_group_add()
922  * allow the "remount" trick to work for arbitrary resizing, assuming enough
923  * GDT blocks are reserved to grow to the desired size.
924  */
925 int ext4_group_extend(struct super_block *sb, struct ext4_super_block *es,
926                       ext4_fsblk_t n_blocks_count)
927 {
928         ext4_fsblk_t o_blocks_count;
929         unsigned long o_groups_count;
930         ext4_grpblk_t last;
931         ext4_grpblk_t add;
932         struct buffer_head * bh;
933         handle_t *handle;
934         int err;
935         unsigned long freed_blocks;
936
937         /* We don't need to worry about locking wrt other resizers just
938          * yet: we're going to revalidate es->s_blocks_count after
939          * taking lock_super() below. */
940         o_blocks_count = ext4_blocks_count(es);
941         o_groups_count = EXT4_SB(sb)->s_groups_count;
942
943         if (test_opt(sb, DEBUG))
944                 printk(KERN_DEBUG "EXT4-fs: extending last group from %llu uto %llu blocks\n",
945                        o_blocks_count, n_blocks_count);
946
947         if (n_blocks_count == 0 || n_blocks_count == o_blocks_count)
948                 return 0;
949
950         if (n_blocks_count > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) {
951                 printk(KERN_ERR "EXT4-fs: filesystem on %s:"
952                         " too large to resize to %llu blocks safely\n",
953                         sb->s_id, n_blocks_count);
954                 if (sizeof(sector_t) < 8)
955                         ext4_warning(sb, __FUNCTION__,
956                         "CONFIG_LBD not enabled\n");
957                 return -EINVAL;
958         }
959
960         if (n_blocks_count < o_blocks_count) {
961                 ext4_warning(sb, __FUNCTION__,
962                              "can't shrink FS - resize aborted");
963                 return -EBUSY;
964         }
965
966         /* Handle the remaining blocks in the last group only. */
967         ext4_get_group_no_and_offset(sb, o_blocks_count, NULL, &last);
968
969         if (last == 0) {
970                 ext4_warning(sb, __FUNCTION__,
971                              "need to use ext2online to resize further");
972                 return -EPERM;
973         }
974
975         add = EXT4_BLOCKS_PER_GROUP(sb) - last;
976
977         if (o_blocks_count + add < o_blocks_count) {
978                 ext4_warning(sb, __FUNCTION__, "blocks_count overflow");
979                 return -EINVAL;
980         }
981
982         if (o_blocks_count + add > n_blocks_count)
983                 add = n_blocks_count - o_blocks_count;
984
985         if (o_blocks_count + add < n_blocks_count)
986                 ext4_warning(sb, __FUNCTION__,
987                              "will only finish group (%llu"
988                              " blocks, %u new)",
989                              o_blocks_count + add, add);
990
991         /* See if the device is actually as big as what was requested */
992         bh = sb_bread(sb, o_blocks_count + add -1);
993         if (!bh) {
994                 ext4_warning(sb, __FUNCTION__,
995                              "can't read last block, resize aborted");
996                 return -ENOSPC;
997         }
998         brelse(bh);
999
1000         /* We will update the superblock, one block bitmap, and
1001          * one group descriptor via ext4_free_blocks().
1002          */
1003         handle = ext4_journal_start_sb(sb, 3);
1004         if (IS_ERR(handle)) {
1005                 err = PTR_ERR(handle);
1006                 ext4_warning(sb, __FUNCTION__, "error %d on journal start",err);
1007                 goto exit_put;
1008         }
1009
1010         lock_super(sb);
1011         if (o_blocks_count != ext4_blocks_count(es)) {
1012                 ext4_warning(sb, __FUNCTION__,
1013                              "multiple resizers run on filesystem!");
1014                 unlock_super(sb);
1015                 err = -EBUSY;
1016                 goto exit_put;
1017         }
1018
1019         if ((err = ext4_journal_get_write_access(handle,
1020                                                  EXT4_SB(sb)->s_sbh))) {
1021                 ext4_warning(sb, __FUNCTION__,
1022                              "error %d on journal write access", err);
1023                 unlock_super(sb);
1024                 ext4_journal_stop(handle);
1025                 goto exit_put;
1026         }
1027         ext4_blocks_count_set(es, o_blocks_count + add);
1028         ext4_journal_dirty_metadata(handle, EXT4_SB(sb)->s_sbh);
1029         sb->s_dirt = 1;
1030         unlock_super(sb);
1031         ext4_debug("freeing blocks %lu through %llu\n", o_blocks_count,
1032                    o_blocks_count + add);
1033         ext4_free_blocks_sb(handle, sb, o_blocks_count, add, &freed_blocks);
1034         ext4_debug("freed blocks %llu through %llu\n", o_blocks_count,
1035                    o_blocks_count + add);
1036         if ((err = ext4_journal_stop(handle)))
1037                 goto exit_put;
1038         if (test_opt(sb, DEBUG))
1039                 printk(KERN_DEBUG "EXT4-fs: extended group to %llu blocks\n",
1040                        ext4_blocks_count(es));
1041         update_backups(sb, EXT4_SB(sb)->s_sbh->b_blocknr, (char *)es,
1042                        sizeof(struct ext4_super_block));
1043 exit_put:
1044         return err;
1045 } /* ext4_group_extend */