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