Whamcloud - gitweb
resize2fs: refine minimum required blocks for flex_bg file systems
[tools/e2fsprogs.git] / resize / resize2fs.c
1 /*
2  * resize2fs.c --- ext2 main routine
3  *
4  * Copyright (C) 1997, 1998 by Theodore Ts'o and
5  *      PowerQuest, Inc.
6  *
7  * Copyright (C) 1999, 2000 by Theosore Ts'o
8  *
9  * %Begin-Header%
10  * This file may be redistributed under the terms of the GNU Public
11  * License.
12  * %End-Header%
13  */
14
15 /*
16  * Resizing a filesystem consists of the following phases:
17  *
18  *      1.  Adjust superblock and write out new parts of the inode
19  *              table
20  *      2.  Determine blocks which need to be relocated, and copy the
21  *              contents of blocks from their old locations to the new ones.
22  *      3.  Scan the inode table, doing the following:
23  *              a.  If blocks have been moved, update the block
24  *                      pointers in the inodes and indirect blocks to
25  *                      point at the new block locations.
26  *              b.  If parts of the inode table need to be evacuated,
27  *                      copy inodes from their old locations to their
28  *                      new ones.
29  *              c.  If (b) needs to be done, note which blocks contain
30  *                      directory information, since we will need to
31  *                      update the directory information.
32  *      4.  Update the directory blocks with the new inode locations.
33  *      5.  Move the inode tables, if necessary.
34  */
35
36 #include "config.h"
37 #include "resize2fs.h"
38 #include <time.h>
39
40 #ifdef __linux__                        /* Kludge for debugging */
41 #define RESIZE2FS_DEBUG
42 #endif
43
44 static void fix_uninit_block_bitmaps(ext2_filsys fs);
45 static errcode_t adjust_superblock(ext2_resize_t rfs, blk64_t new_size);
46 static errcode_t blocks_to_move(ext2_resize_t rfs);
47 static errcode_t block_mover(ext2_resize_t rfs);
48 static errcode_t inode_scan_and_fix(ext2_resize_t rfs);
49 static errcode_t inode_ref_fix(ext2_resize_t rfs);
50 static errcode_t move_itables(ext2_resize_t rfs);
51 static errcode_t fix_resize_inode(ext2_filsys fs);
52 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs);
53 static errcode_t fix_sb_journal_backup(ext2_filsys fs);
54 static errcode_t mark_table_blocks(ext2_filsys fs,
55                                    ext2fs_block_bitmap bmap);
56 static errcode_t clear_sparse_super2_last_group(ext2_resize_t rfs);
57 static errcode_t reserve_sparse_super2_last_group(ext2_resize_t rfs,
58                                                  ext2fs_block_bitmap meta_bmap);
59
60 /*
61  * Some helper CPP macros
62  */
63 #define IS_BLOCK_BM(fs, i, blk) ((blk) == ext2fs_block_bitmap_loc((fs),(i)))
64 #define IS_INODE_BM(fs, i, blk) ((blk) == ext2fs_inode_bitmap_loc((fs),(i)))
65
66 #define IS_INODE_TB(fs, i, blk) (((blk) >= ext2fs_inode_table_loc((fs), (i))) && \
67                                  ((blk) < (ext2fs_inode_table_loc((fs), (i)) + \
68                                            (fs)->inode_blocks_per_group)))
69
70 /* Some bigalloc helper macros which are more succint... */
71 #define B2C(x)  EXT2FS_B2C(fs, (x))
72 #define C2B(x)  EXT2FS_C2B(fs, (x))
73 #define EQ_CLSTR(x, y) (B2C(x) == B2C(y))
74 #define LE_CLSTR(x, y) (B2C(x) <= B2C(y))
75 #define LT_CLSTR(x, y) (B2C(x) <  B2C(y))
76 #define GE_CLSTR(x, y) (B2C(x) >= B2C(y))
77 #define GT_CLSTR(x, y) (B2C(x) >  B2C(y))
78
79 static int lazy_itable_init;
80
81 /*
82  * This is the top-level routine which does the dirty deed....
83  */
84 errcode_t resize_fs(ext2_filsys fs, blk64_t *new_size, int flags,
85             errcode_t (*progress)(ext2_resize_t rfs, int pass,
86                                           unsigned long cur,
87                                           unsigned long max_val))
88 {
89         ext2_resize_t   rfs;
90         errcode_t       retval;
91         struct resource_track   rtrack, overall_track;
92
93         /*
94          * Create the data structure
95          */
96         retval = ext2fs_get_mem(sizeof(struct ext2_resize_struct), &rfs);
97         if (retval)
98                 return retval;
99
100         memset(rfs, 0, sizeof(struct ext2_resize_struct));
101         fs->priv_data = rfs;
102         rfs->old_fs = fs;
103         rfs->flags = flags;
104         rfs->itable_buf  = 0;
105         rfs->progress = progress;
106
107         init_resource_track(&overall_track, "overall resize2fs", fs->io);
108         init_resource_track(&rtrack, "read_bitmaps", fs->io);
109         retval = ext2fs_read_bitmaps(fs);
110         if (retval)
111                 goto errout;
112         print_resource_track(rfs, &rtrack, fs->io);
113
114         fs->super->s_state |= EXT2_ERROR_FS;
115         ext2fs_mark_super_dirty(fs);
116         ext2fs_flush(fs);
117
118         init_resource_track(&rtrack, "fix_uninit_block_bitmaps 1", fs->io);
119         fix_uninit_block_bitmaps(fs);
120         print_resource_track(rfs, &rtrack, fs->io);
121         retval = ext2fs_dup_handle(fs, &rfs->new_fs);
122         if (retval)
123                 goto errout;
124
125         init_resource_track(&rtrack, "adjust_superblock", fs->io);
126         retval = adjust_superblock(rfs, *new_size);
127         if (retval)
128                 goto errout;
129         print_resource_track(rfs, &rtrack, fs->io);
130
131
132         init_resource_track(&rtrack, "fix_uninit_block_bitmaps 2", fs->io);
133         fix_uninit_block_bitmaps(rfs->new_fs);
134         print_resource_track(rfs, &rtrack, fs->io);
135         /* Clear the block bitmap uninit flag for the last block group */
136         ext2fs_bg_flags_clear(rfs->new_fs, rfs->new_fs->group_desc_count - 1,
137                              EXT2_BG_BLOCK_UNINIT);
138
139         *new_size = ext2fs_blocks_count(rfs->new_fs->super);
140
141         init_resource_track(&rtrack, "blocks_to_move", fs->io);
142         retval = blocks_to_move(rfs);
143         if (retval)
144                 goto errout;
145         print_resource_track(rfs, &rtrack, fs->io);
146
147 #ifdef RESIZE2FS_DEBUG
148         if (rfs->flags & RESIZE_DEBUG_BMOVE)
149                 printf("Number of free blocks: %llu/%llu, Needed: %llu\n",
150                        ext2fs_free_blocks_count(rfs->old_fs->super),
151                        ext2fs_free_blocks_count(rfs->new_fs->super),
152                        rfs->needed_blocks);
153 #endif
154
155         init_resource_track(&rtrack, "block_mover", fs->io);
156         retval = block_mover(rfs);
157         if (retval)
158                 goto errout;
159         print_resource_track(rfs, &rtrack, fs->io);
160
161         init_resource_track(&rtrack, "inode_scan_and_fix", fs->io);
162         retval = inode_scan_and_fix(rfs);
163         if (retval)
164                 goto errout;
165         print_resource_track(rfs, &rtrack, fs->io);
166
167         init_resource_track(&rtrack, "inode_ref_fix", fs->io);
168         retval = inode_ref_fix(rfs);
169         if (retval)
170                 goto errout;
171         print_resource_track(rfs, &rtrack, fs->io);
172
173         init_resource_track(&rtrack, "move_itables", fs->io);
174         retval = move_itables(rfs);
175         if (retval)
176                 goto errout;
177         print_resource_track(rfs, &rtrack, fs->io);
178
179         init_resource_track(&rtrack, "calculate_summary_stats", fs->io);
180         retval = ext2fs_calculate_summary_stats(rfs->new_fs);
181         if (retval)
182                 goto errout;
183         print_resource_track(rfs, &rtrack, fs->io);
184
185         init_resource_track(&rtrack, "fix_resize_inode", fs->io);
186         retval = fix_resize_inode(rfs->new_fs);
187         if (retval)
188                 goto errout;
189         print_resource_track(rfs, &rtrack, fs->io);
190
191         init_resource_track(&rtrack, "fix_sb_journal_backup", fs->io);
192         retval = fix_sb_journal_backup(rfs->new_fs);
193         if (retval)
194                 goto errout;
195         print_resource_track(rfs, &rtrack, fs->io);
196
197         retval = clear_sparse_super2_last_group(rfs);
198         if (retval)
199                 goto errout;
200
201         rfs->new_fs->super->s_state &= ~EXT2_ERROR_FS;
202         rfs->new_fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
203
204         print_resource_track(rfs, &overall_track, fs->io);
205         retval = ext2fs_close(rfs->new_fs);
206         if (retval)
207                 goto errout;
208
209         rfs->flags = flags;
210
211         ext2fs_free(rfs->old_fs);
212         rfs->old_fs = NULL;
213         if (rfs->itable_buf)
214                 ext2fs_free_mem(&rfs->itable_buf);
215         if (rfs->reserve_blocks)
216                 ext2fs_free_block_bitmap(rfs->reserve_blocks);
217         if (rfs->move_blocks)
218                 ext2fs_free_block_bitmap(rfs->move_blocks);
219         ext2fs_free_mem(&rfs);
220
221         return 0;
222
223 errout:
224         if (rfs->new_fs) {
225                 ext2fs_free(rfs->new_fs);
226                 rfs->new_fs = NULL;
227         }
228         if (rfs->itable_buf)
229                 ext2fs_free_mem(&rfs->itable_buf);
230         ext2fs_free_mem(&rfs);
231         return retval;
232 }
233
234 /*
235  * Clean up the bitmaps for unitialized bitmaps
236  */
237 static void fix_uninit_block_bitmaps(ext2_filsys fs)
238 {
239         blk64_t         blk, lblk;
240         dgrp_t          g;
241         int             i;
242
243         if (!(EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
244                                          EXT4_FEATURE_RO_COMPAT_GDT_CSUM)))
245                 return;
246
247         for (g=0; g < fs->group_desc_count; g++) {
248                 if (!(ext2fs_bg_flags_test(fs, g, EXT2_BG_BLOCK_UNINIT)))
249                         continue;
250
251                 blk = ext2fs_group_first_block2(fs, g);
252                 lblk = ext2fs_group_last_block2(fs, g);
253                 ext2fs_unmark_block_bitmap_range2(fs->block_map, blk,
254                                                   lblk - blk + 1);
255
256                 ext2fs_reserve_super_and_bgd(fs, g, fs->block_map);
257                 ext2fs_mark_block_bitmap2(fs->block_map,
258                                           ext2fs_block_bitmap_loc(fs, g));
259                 ext2fs_mark_block_bitmap2(fs->block_map,
260                                           ext2fs_inode_bitmap_loc(fs, g));
261                 for (i = 0, blk = ext2fs_inode_table_loc(fs, g);
262                      i < (unsigned int) fs->inode_blocks_per_group;
263                      i++, blk++)
264                         ext2fs_mark_block_bitmap2(fs->block_map, blk);
265         }
266 }
267
268 /* --------------------------------------------------------------------
269  *
270  * Resize processing, phase 1.
271  *
272  * In this phase we adjust the in-memory superblock information, and
273  * initialize any new parts of the inode table.  The new parts of the
274  * inode table are created in virgin disk space, so we can abort here
275  * without any side effects.
276  * --------------------------------------------------------------------
277  */
278
279 /*
280  * If the group descriptor's bitmap and inode table blocks are valid,
281  * release them in the new filesystem data structure, and mark them as
282  * reserved so the old inode table blocks don't get overwritten.
283  */
284 static errcode_t free_gdp_blocks(ext2_filsys fs,
285                                  ext2fs_block_bitmap reserve_blocks,
286                                  ext2_filsys old_fs,
287                                  dgrp_t group)
288 {
289         blk64_t blk;
290         int     j;
291         dgrp_t  i;
292         ext2fs_block_bitmap bg_map = NULL;
293         errcode_t retval = 0;
294         dgrp_t count = old_fs->group_desc_count - fs->group_desc_count;
295
296         /* If bigalloc, don't free metadata living in the same cluster */
297         if (EXT2FS_CLUSTER_RATIO(fs) > 1) {
298                 retval = ext2fs_allocate_block_bitmap(fs, "bgdata", &bg_map);
299                 if (retval)
300                         goto out;
301
302                 retval = mark_table_blocks(fs, bg_map);
303                 if (retval)
304                         goto out;
305         }
306
307         for (i = group; i < group + count; i++) {
308                 blk = ext2fs_block_bitmap_loc(old_fs, i);
309                 if (blk &&
310                     (blk < ext2fs_blocks_count(fs->super)) &&
311                     !(bg_map && ext2fs_test_block_bitmap2(bg_map, blk))) {
312                         ext2fs_block_alloc_stats2(fs, blk, -1);
313                         ext2fs_mark_block_bitmap2(reserve_blocks, blk);
314                 }
315
316                 blk = ext2fs_inode_bitmap_loc(old_fs, i);
317                 if (blk &&
318                     (blk < ext2fs_blocks_count(fs->super)) &&
319                     !(bg_map && ext2fs_test_block_bitmap2(bg_map, blk))) {
320                         ext2fs_block_alloc_stats2(fs, blk, -1);
321                         ext2fs_mark_block_bitmap2(reserve_blocks, blk);
322                 }
323
324                 blk = ext2fs_inode_table_loc(old_fs, i);
325                 for (j = 0;
326                      j < fs->inode_blocks_per_group; j++, blk++) {
327                         if (blk >= ext2fs_blocks_count(fs->super) ||
328                             (bg_map && ext2fs_test_block_bitmap2(bg_map, blk)))
329                                 continue;
330                         ext2fs_block_alloc_stats2(fs, blk, -1);
331                         ext2fs_mark_block_bitmap2(reserve_blocks, blk);
332                 }
333         }
334
335 out:
336         if (bg_map)
337                 ext2fs_free_block_bitmap(bg_map);
338         return retval;
339 }
340
341 /*
342  * This routine is shared by the online and offline resize routines.
343  * All of the information which is adjusted in memory is done here.
344  */
345 errcode_t adjust_fs_info(ext2_filsys fs, ext2_filsys old_fs,
346                          ext2fs_block_bitmap reserve_blocks, blk64_t new_size)
347 {
348         errcode_t       retval;
349         blk64_t         overhead = 0;
350         blk64_t         rem;
351         blk64_t         blk, group_block;
352         blk64_t         real_end;
353         blk64_t         old_numblocks, numblocks, adjblocks;
354         unsigned long   i, j, old_desc_blocks;
355         unsigned int    meta_bg, meta_bg_size;
356         int             has_super, csum_flag;
357         unsigned long long new_inodes;  /* u64 to check for overflow */
358         double          percent;
359
360         ext2fs_blocks_count_set(fs->super, new_size);
361
362 retry:
363         fs->group_desc_count = ext2fs_div64_ceil(ext2fs_blocks_count(fs->super) -
364                                        fs->super->s_first_data_block,
365                                        EXT2_BLOCKS_PER_GROUP(fs->super));
366         if (fs->group_desc_count == 0)
367                 return EXT2_ET_TOOSMALL;
368         fs->desc_blocks = ext2fs_div_ceil(fs->group_desc_count,
369                                           EXT2_DESC_PER_BLOCK(fs->super));
370
371         /*
372          * Overhead is the number of bookkeeping blocks per group.  It
373          * includes the superblock backup, the group descriptor
374          * backups, the inode bitmap, the block bitmap, and the inode
375          * table.
376          */
377         overhead = (int) (2 + fs->inode_blocks_per_group);
378
379         if (ext2fs_bg_has_super(fs, fs->group_desc_count - 1))
380                 overhead += 1 + fs->desc_blocks +
381                         fs->super->s_reserved_gdt_blocks;
382
383         /*
384          * See if the last group is big enough to support the
385          * necessary data structures.  If not, we need to get rid of
386          * it.
387          */
388         rem = (ext2fs_blocks_count(fs->super) - fs->super->s_first_data_block) %
389                 fs->super->s_blocks_per_group;
390         if ((fs->group_desc_count == 1) && rem && (rem < overhead))
391                 return EXT2_ET_TOOSMALL;
392         if ((fs->group_desc_count > 1) && rem && (rem < overhead+50)) {
393                 ext2fs_blocks_count_set(fs->super,
394                                         ext2fs_blocks_count(fs->super) - rem);
395                 goto retry;
396         }
397         /*
398          * Adjust the number of inodes
399          */
400         new_inodes =(unsigned long long) fs->super->s_inodes_per_group * fs->group_desc_count;
401         if (new_inodes > ~0U) {
402                 fprintf(stderr, _("inodes (%llu) must be less than %u"),
403                                    new_inodes, ~0U);
404                 return EXT2_ET_TOO_MANY_INODES;
405         }
406         fs->super->s_inodes_count = fs->super->s_inodes_per_group *
407                 fs->group_desc_count;
408
409         /*
410          * Adjust the number of free blocks
411          */
412         blk = ext2fs_blocks_count(old_fs->super);
413         if (blk > ext2fs_blocks_count(fs->super))
414                 ext2fs_free_blocks_count_set(fs->super, 
415                         ext2fs_free_blocks_count(fs->super) -
416                         (blk - ext2fs_blocks_count(fs->super)));
417         else
418                 ext2fs_free_blocks_count_set(fs->super, 
419                         ext2fs_free_blocks_count(fs->super) +
420                         (ext2fs_blocks_count(fs->super) - blk));
421
422         /*
423          * Adjust the number of reserved blocks
424          */
425         percent = (ext2fs_r_blocks_count(old_fs->super) * 100.0) /
426                 ext2fs_blocks_count(old_fs->super);
427         ext2fs_r_blocks_count_set(fs->super,
428                                   (percent * ext2fs_blocks_count(fs->super) /
429                                    100.0));
430
431         /*
432          * Adjust the bitmaps for size
433          */
434         retval = ext2fs_resize_inode_bitmap2(fs->super->s_inodes_count,
435                                             fs->super->s_inodes_count,
436                                             fs->inode_map);
437         if (retval) goto errout;
438
439         real_end = (((blk64_t) EXT2_BLOCKS_PER_GROUP(fs->super) *
440                      fs->group_desc_count)) - 1 +
441                 fs->super->s_first_data_block;
442         retval = ext2fs_resize_block_bitmap2(new_size - 1,
443                                              real_end, fs->block_map);
444         if (retval) goto errout;
445
446         /*
447          * If we are growing the file system, also grow the size of
448          * the reserve_blocks bitmap
449          */
450         if (reserve_blocks && new_size > ext2fs_blocks_count(old_fs->super)) {
451                 retval = ext2fs_resize_block_bitmap2(new_size - 1,
452                                                      real_end, reserve_blocks);
453                 if (retval) goto errout;
454         }
455
456         /*
457          * Reallocate the group descriptors as necessary.
458          */
459         if (old_fs->desc_blocks != fs->desc_blocks) {
460                 retval = ext2fs_resize_mem(old_fs->desc_blocks *
461                                            fs->blocksize,
462                                            fs->desc_blocks * fs->blocksize,
463                                            &fs->group_desc);
464                 if (retval)
465                         goto errout;
466                 if (fs->desc_blocks > old_fs->desc_blocks)
467                         memset((char *) fs->group_desc +
468                                (old_fs->desc_blocks * fs->blocksize), 0,
469                                (fs->desc_blocks - old_fs->desc_blocks) *
470                                fs->blocksize);
471         }
472
473         /*
474          * If the resize_inode feature is set, and we are changing the
475          * number of descriptor blocks, then adjust
476          * s_reserved_gdt_blocks if possible to avoid needing to move
477          * the inode table either now or in the future.
478          */
479         if ((fs->super->s_feature_compat &
480              EXT2_FEATURE_COMPAT_RESIZE_INODE) &&
481             (old_fs->desc_blocks != fs->desc_blocks)) {
482                 int new;
483
484                 new = ((int) fs->super->s_reserved_gdt_blocks) +
485                         (old_fs->desc_blocks - fs->desc_blocks);
486                 if (new < 0)
487                         new = 0;
488                 if (new > (int) fs->blocksize/4)
489                         new = fs->blocksize/4;
490                 fs->super->s_reserved_gdt_blocks = new;
491         }
492
493         /*
494          * Update the location of the backup superblocks if the
495          * sparse_super2 feature is enabled.
496          */
497         if (fs->super->s_feature_compat & EXT4_FEATURE_COMPAT_SPARSE_SUPER2) {
498                 dgrp_t last_bg = fs->group_desc_count - 1;
499                 dgrp_t old_last_bg = old_fs->group_desc_count - 1;
500
501                 if (last_bg > old_last_bg) {
502                         if (old_fs->group_desc_count == 1)
503                                 fs->super->s_backup_bgs[0] = 1;
504                         if (old_fs->group_desc_count == 1 &&
505                             fs->super->s_backup_bgs[0])
506                                 fs->super->s_backup_bgs[0] = last_bg;
507                         else if (fs->super->s_backup_bgs[1])
508                                 fs->super->s_backup_bgs[1] = last_bg;
509                 } else if (last_bg < old_last_bg) {
510                         if (fs->super->s_backup_bgs[0] > last_bg)
511                                 fs->super->s_backup_bgs[0] = 0;
512                         if (fs->super->s_backup_bgs[1] > last_bg)
513                                 fs->super->s_backup_bgs[1] = 0;
514                         if (last_bg > 1 &&
515                             old_fs->super->s_backup_bgs[1] == old_last_bg)
516                                 fs->super->s_backup_bgs[1] = last_bg;
517                 }
518         }
519
520         /*
521          * If we are shrinking the number of block groups, we're done
522          * and can exit now.
523          */
524         if (old_fs->group_desc_count > fs->group_desc_count) {
525                 /*
526                  * Check the block groups that we are chopping off
527                  * and free any blocks associated with their metadata
528                  */
529                 retval = free_gdp_blocks(fs, reserve_blocks, old_fs,
530                                          fs->group_desc_count);
531                 goto errout;
532         }
533
534         /*
535          * Fix the count of the last (old) block group
536          */
537         old_numblocks = (ext2fs_blocks_count(old_fs->super) -
538                          old_fs->super->s_first_data_block) %
539                                  old_fs->super->s_blocks_per_group;
540         if (!old_numblocks)
541                 old_numblocks = old_fs->super->s_blocks_per_group;
542         if (old_fs->group_desc_count == fs->group_desc_count) {
543                 numblocks = (ext2fs_blocks_count(fs->super) -
544                              fs->super->s_first_data_block) %
545                         fs->super->s_blocks_per_group;
546                 if (!numblocks)
547                         numblocks = fs->super->s_blocks_per_group;
548         } else
549                 numblocks = fs->super->s_blocks_per_group;
550         i = old_fs->group_desc_count - 1;
551         ext2fs_bg_free_blocks_count_set(fs, i, ext2fs_bg_free_blocks_count(fs, i) + (numblocks - old_numblocks));
552         ext2fs_group_desc_csum_set(fs, i);
553
554         /*
555          * If the number of block groups is staying the same, we're
556          * done and can exit now.  (If the number block groups is
557          * shrinking, we had exited earlier.)
558          */
559         if (old_fs->group_desc_count >= fs->group_desc_count) {
560                 retval = 0;
561                 goto errout;
562         }
563
564         /*
565          * Initialize the new block group descriptors
566          */
567         group_block = ext2fs_group_first_block2(fs,
568                                                 old_fs->group_desc_count);
569         csum_flag = EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
570                                                EXT4_FEATURE_RO_COMPAT_GDT_CSUM);
571         if (access("/sys/fs/ext4/features/lazy_itable_init", F_OK) == 0)
572                 lazy_itable_init = 1;
573         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG)
574                 old_desc_blocks = fs->super->s_first_meta_bg;
575         else
576                 old_desc_blocks = fs->desc_blocks +
577                         fs->super->s_reserved_gdt_blocks;
578
579         /*
580          * If we changed the number of block_group descriptor blocks,
581          * we need to make sure they are all marked as reserved in the
582          * file systems's block allocation map.
583          */
584         for (i = 0; i < old_fs->group_desc_count; i++)
585                 ext2fs_reserve_super_and_bgd(fs, i, fs->block_map);
586
587         for (i = old_fs->group_desc_count;
588              i < fs->group_desc_count; i++) {
589                 memset(ext2fs_group_desc(fs, fs->group_desc, i), 0,
590                        sizeof(struct ext2_group_desc));
591                 adjblocks = 0;
592
593                 ext2fs_bg_flags_zap(fs, i);
594                 if (csum_flag) {
595                         ext2fs_bg_flags_set(fs, i, EXT2_BG_INODE_UNINIT);
596                         if (!lazy_itable_init)
597                                 ext2fs_bg_flags_set(fs, i,
598                                                     EXT2_BG_INODE_ZEROED);
599                         ext2fs_bg_itable_unused_set(fs, i,
600                                         fs->super->s_inodes_per_group);
601                 }
602
603                 numblocks = ext2fs_group_blocks_count(fs, i);
604                 if ((i < fs->group_desc_count - 1) && csum_flag)
605                         ext2fs_bg_flags_set(fs, i, EXT2_BG_BLOCK_UNINIT);
606
607                 has_super = ext2fs_bg_has_super(fs, i);
608                 if (has_super) {
609                         ext2fs_block_alloc_stats2(fs, group_block, +1);
610                         adjblocks++;
611                 }
612                 meta_bg_size = EXT2_DESC_PER_BLOCK(fs->super);
613                 meta_bg = i / meta_bg_size;
614                 if (!(fs->super->s_feature_incompat &
615                       EXT2_FEATURE_INCOMPAT_META_BG) ||
616                     (meta_bg < fs->super->s_first_meta_bg)) {
617                         if (has_super) {
618                                 for (j=0; j < old_desc_blocks; j++)
619                                         ext2fs_block_alloc_stats2(fs,
620                                                  group_block + 1 + j, +1);
621                                 adjblocks += old_desc_blocks;
622                         }
623                 } else {
624                         if (has_super)
625                                 has_super = 1;
626                         if (((i % meta_bg_size) == 0) ||
627                             ((i % meta_bg_size) == 1) ||
628                             ((i % meta_bg_size) == (meta_bg_size-1)))
629                                 ext2fs_block_alloc_stats2(fs,
630                                                  group_block + has_super, +1);
631                 }
632
633                 adjblocks += 2 + fs->inode_blocks_per_group;
634
635                 numblocks -= adjblocks;
636                 ext2fs_free_blocks_count_set(fs->super,
637                              ext2fs_free_blocks_count(fs->super) - adjblocks);
638                 fs->super->s_free_inodes_count +=
639                         fs->super->s_inodes_per_group;
640                 ext2fs_bg_free_blocks_count_set(fs, i, numblocks);
641                 ext2fs_bg_free_inodes_count_set(fs, i,
642                                                 fs->super->s_inodes_per_group);
643                 ext2fs_bg_used_dirs_count_set(fs, i, 0);
644                 ext2fs_group_desc_csum_set(fs, i);
645
646                 retval = ext2fs_allocate_group_table(fs, i, 0);
647                 if (retval) goto errout;
648
649                 group_block += fs->super->s_blocks_per_group;
650         }
651         retval = 0;
652
653         /*
654          * Mark all of the metadata blocks as reserved so they won't
655          * get allocated by the call to ext2fs_allocate_group_table()
656          * in blocks_to_move(), where we allocate new blocks to
657          * replace those allocation bitmap and inode table blocks
658          * which have to get relocated to make space for an increased
659          * number of the block group descriptors.
660          */
661         if (reserve_blocks)
662                 mark_table_blocks(fs, reserve_blocks);
663
664 errout:
665         return (retval);
666 }
667
668 /*
669  * This routine adjusts the superblock and other data structures, both
670  * in disk as well as in memory...
671  */
672 static errcode_t adjust_superblock(ext2_resize_t rfs, blk64_t new_size)
673 {
674         ext2_filsys     fs = rfs->new_fs;
675         int             adj = 0;
676         errcode_t       retval;
677         blk64_t         group_block;
678         unsigned long   i;
679         unsigned long   max_group;
680
681         ext2fs_mark_super_dirty(fs);
682         ext2fs_mark_bb_dirty(fs);
683         ext2fs_mark_ib_dirty(fs);
684
685         retval = ext2fs_allocate_block_bitmap(fs, _("reserved blocks"),
686                                               &rfs->reserve_blocks);
687         if (retval)
688                 return retval;
689
690         retval = adjust_fs_info(fs, rfs->old_fs, rfs->reserve_blocks, new_size);
691         if (retval)
692                 goto errout;
693
694         /*
695          * Check to make sure there are enough inodes
696          */
697         if ((rfs->old_fs->super->s_inodes_count -
698              rfs->old_fs->super->s_free_inodes_count) >
699             rfs->new_fs->super->s_inodes_count) {
700                 retval = ENOSPC;
701                 goto errout;
702         }
703
704         /*
705          * If we are shrinking the number block groups, we're done and
706          * can exit now.
707          */
708         if (rfs->old_fs->group_desc_count > fs->group_desc_count) {
709                 retval = 0;
710                 goto errout;
711         }
712
713         /*
714          * If the number of block groups is staying the same, we're
715          * done and can exit now.  (If the number block groups is
716          * shrinking, we had exited earlier.)
717          */
718         if (rfs->old_fs->group_desc_count >= fs->group_desc_count) {
719                 retval = 0;
720                 goto errout;
721         }
722
723         /*
724          * If we are using uninit_bg (aka GDT_CSUM) and the kernel
725          * supports lazy inode initialization, we can skip
726          * initializing the inode table.
727          */
728         if (lazy_itable_init &&
729             EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
730                                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
731                 retval = 0;
732                 goto errout;
733         }
734
735         /*
736          * Initialize the inode table
737          */
738         retval = ext2fs_get_array(fs->blocksize, fs->inode_blocks_per_group,
739                                 &rfs->itable_buf);
740         if (retval)
741                 goto errout;
742
743         memset(rfs->itable_buf, 0, fs->blocksize * fs->inode_blocks_per_group);
744         group_block = ext2fs_group_first_block2(fs,
745                                                 rfs->old_fs->group_desc_count);
746         adj = rfs->old_fs->group_desc_count;
747         max_group = fs->group_desc_count - adj;
748         if (rfs->progress) {
749                 retval = rfs->progress(rfs, E2_RSZ_EXTEND_ITABLE_PASS,
750                                        0, max_group);
751                 if (retval)
752                         goto errout;
753         }
754         for (i = rfs->old_fs->group_desc_count;
755              i < fs->group_desc_count; i++) {
756                 /*
757                  * Write out the new inode table
758                  */
759                 retval = io_channel_write_blk64(fs->io,
760                                                 ext2fs_inode_table_loc(fs, i),
761                                                 fs->inode_blocks_per_group,
762                                                 rfs->itable_buf);
763                 if (retval) goto errout;
764
765                 io_channel_flush(fs->io);
766                 if (rfs->progress) {
767                         retval = rfs->progress(rfs, E2_RSZ_EXTEND_ITABLE_PASS,
768                                                i - adj + 1, max_group);
769                         if (retval)
770                                 goto errout;
771                 }
772                 group_block += fs->super->s_blocks_per_group;
773         }
774         io_channel_flush(fs->io);
775         retval = 0;
776
777 errout:
778         return retval;
779 }
780
781 /* --------------------------------------------------------------------
782  *
783  * Resize processing, phase 2.
784  *
785  * In this phase we adjust determine which blocks need to be moved, in
786  * blocks_to_move().  We then copy the blocks to their ultimate new
787  * destinations using block_mover().  Since we are copying blocks to
788  * their new locations, again during this pass we can abort without
789  * any problems.
790  * --------------------------------------------------------------------
791  */
792
793 /*
794  * This helper function creates a block bitmap with all of the
795  * filesystem meta-data blocks.
796  */
797 static errcode_t mark_table_blocks(ext2_filsys fs,
798                                    ext2fs_block_bitmap bmap)
799 {
800         dgrp_t                  i;
801         blk64_t                 blk;
802
803         for (i = 0; i < fs->group_desc_count; i++) {
804                 ext2fs_reserve_super_and_bgd(fs, i, bmap);
805
806                 /*
807                  * Mark the blocks used for the inode table
808                  */
809                 blk = ext2fs_inode_table_loc(fs, i);
810                 if (blk)
811                         ext2fs_mark_block_bitmap_range2(bmap, blk,
812                                                 fs->inode_blocks_per_group);
813
814                 /*
815                  * Mark block used for the block bitmap
816                  */
817                 blk = ext2fs_block_bitmap_loc(fs, i);
818                 if (blk)
819                         ext2fs_mark_block_bitmap2(bmap, blk);
820
821                 /*
822                  * Mark block used for the inode bitmap
823                  */
824                 blk = ext2fs_inode_bitmap_loc(fs, i);
825                 if (blk)
826                         ext2fs_mark_block_bitmap2(bmap, blk);
827         }
828         return 0;
829 }
830
831 /*
832  * This function checks to see if a particular block (either a
833  * superblock or a block group descriptor) overlaps with an inode or
834  * block bitmap block, or with the inode table.
835  */
836 static void mark_fs_metablock(ext2_resize_t rfs,
837                               ext2fs_block_bitmap meta_bmap,
838                               int group, blk64_t blk)
839 {
840         ext2_filsys     fs = rfs->new_fs;
841
842         ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
843         ext2fs_block_alloc_stats2(fs, blk, +1);
844
845         /*
846          * Check to see if we overlap with the inode or block bitmap,
847          * or the inode tables.  If not, and the block is in use, then
848          * mark it as a block to be moved.
849          */
850         if (IS_BLOCK_BM(fs, group, blk)) {
851                 ext2fs_block_bitmap_loc_set(fs, group, 0);
852                 rfs->needed_blocks++;
853                 return;
854         }
855         if (IS_INODE_BM(fs, group, blk)) {
856                 ext2fs_inode_bitmap_loc_set(fs, group, 0);
857                 rfs->needed_blocks++;
858                 return;
859         }
860         if (IS_INODE_TB(fs, group, blk)) {
861                 ext2fs_inode_table_loc_set(fs, group, 0);
862                 rfs->needed_blocks++;
863                 return;
864         }
865         if (fs->super->s_feature_incompat & EXT4_FEATURE_INCOMPAT_FLEX_BG) {
866                 dgrp_t i;
867
868                 for (i=0; i < rfs->old_fs->group_desc_count; i++) {
869                         if (IS_BLOCK_BM(fs, i, blk)) {
870                                 ext2fs_block_bitmap_loc_set(fs, i, 0);
871                                 rfs->needed_blocks++;
872                                 return;
873                         }
874                         if (IS_INODE_BM(fs, i, blk)) {
875                                 ext2fs_inode_bitmap_loc_set(fs, i, 0);
876                                 rfs->needed_blocks++;
877                                 return;
878                         }
879                         if (IS_INODE_TB(fs, i, blk)) {
880                                 ext2fs_inode_table_loc_set(fs, i, 0);
881                                 rfs->needed_blocks++;
882                                 return;
883                         }
884                 }
885         }
886         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
887                                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM) &&
888                    (ext2fs_bg_flags_test(fs, group, EXT2_BG_BLOCK_UNINIT))) {
889                 /*
890                  * If the block bitmap is uninitialized, which means
891                  * nothing other than standard metadata in use.
892                  */
893                 return;
894         } else if (ext2fs_test_block_bitmap2(rfs->old_fs->block_map, blk) &&
895                    !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
896                 ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
897                 rfs->needed_blocks++;
898         }
899 }
900
901
902 /*
903  * This routine marks and unmarks reserved blocks in the new block
904  * bitmap.  It also determines which blocks need to be moved and
905  * places this information into the move_blocks bitmap.
906  */
907 static errcode_t blocks_to_move(ext2_resize_t rfs)
908 {
909         int             j, has_super;
910         dgrp_t          i, max_groups, g;
911         blk64_t         blk, group_blk;
912         blk64_t         old_blocks, new_blocks, group_end, cluster_freed;
913         blk64_t         new_size;
914         unsigned int    meta_bg, meta_bg_size;
915         errcode_t       retval;
916         ext2_filsys     fs, old_fs;
917         ext2fs_block_bitmap     meta_bmap, new_meta_bmap = NULL;
918         int             flex_bg;
919
920         fs = rfs->new_fs;
921         old_fs = rfs->old_fs;
922         if (ext2fs_blocks_count(old_fs->super) > ext2fs_blocks_count(fs->super))
923                 fs = rfs->old_fs;
924
925         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
926                                               &rfs->move_blocks);
927         if (retval)
928                 return retval;
929
930         retval = ext2fs_allocate_block_bitmap(fs, _("meta-data blocks"),
931                                               &meta_bmap);
932         if (retval)
933                 return retval;
934
935         retval = mark_table_blocks(old_fs, meta_bmap);
936         if (retval)
937                 return retval;
938
939         fs = rfs->new_fs;
940
941         /*
942          * If we're shrinking the filesystem, we need to move any
943          * group's metadata blocks (either allocation bitmaps or the
944          * inode table) which are beyond the end of the new
945          * filesystem.
946          */
947         new_size = ext2fs_blocks_count(fs->super);
948         if (new_size < ext2fs_blocks_count(old_fs->super)) {
949                 for (g = 0; g < fs->group_desc_count; g++) {
950                         int realloc = 0;
951                         /*
952                          * ext2fs_allocate_group_table will re-allocate any
953                          * metadata blocks whose location is set to zero.
954                          */
955                         if (ext2fs_block_bitmap_loc(fs, g) >= new_size) {
956                                 ext2fs_block_bitmap_loc_set(fs, g, 0);
957                                 realloc = 1;
958                         }
959                         if (ext2fs_inode_bitmap_loc(fs, g) >= new_size) {
960                                 ext2fs_inode_bitmap_loc_set(fs, g, 0);
961                                 realloc = 1;
962                         }
963                         if ((ext2fs_inode_table_loc(fs, g) +
964                              fs->inode_blocks_per_group) > new_size) {
965                                 ext2fs_inode_table_loc_set(fs, g, 0);
966                                 realloc = 1;
967                         }
968
969                         if (realloc) {
970                                 retval = ext2fs_allocate_group_table(fs, g, 0);
971                                 if (retval)
972                                         return retval;
973                         }
974                 }
975         }
976
977         /*
978          * If we're shrinking the filesystem, we need to move all of
979          * the blocks that don't fit any more
980          */
981         for (blk = ext2fs_blocks_count(fs->super);
982              blk < ext2fs_blocks_count(old_fs->super); blk++) {
983                 g = ext2fs_group_of_blk2(fs, blk);
984                 if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
985                                                EXT4_FEATURE_RO_COMPAT_GDT_CSUM) &&
986                     ext2fs_bg_flags_test(old_fs, g, EXT2_BG_BLOCK_UNINIT)) {
987                         /*
988                          * The block bitmap is uninitialized, so skip
989                          * to the next block group.
990                          */
991                         blk = ext2fs_group_first_block2(fs, g+1) - 1;
992                         continue;
993                 }
994                 if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
995                     !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
996                         ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
997                         rfs->needed_blocks++;
998                 }
999                 ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
1000         }
1001
1002         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG) {
1003                 old_blocks = old_fs->super->s_first_meta_bg;
1004                 new_blocks = fs->super->s_first_meta_bg;
1005         } else {
1006                 old_blocks = old_fs->desc_blocks + old_fs->super->s_reserved_gdt_blocks;
1007                 new_blocks = fs->desc_blocks + fs->super->s_reserved_gdt_blocks;
1008         }
1009
1010         retval = reserve_sparse_super2_last_group(rfs, meta_bmap);
1011         if (retval)
1012                 goto errout;
1013
1014         if (old_blocks == new_blocks) {
1015                 retval = 0;
1016                 goto errout;
1017         }
1018
1019         max_groups = fs->group_desc_count;
1020         if (max_groups > old_fs->group_desc_count)
1021                 max_groups = old_fs->group_desc_count;
1022         group_blk = old_fs->super->s_first_data_block;
1023         /*
1024          * If we're reducing the number of descriptor blocks, this
1025          * makes life easy.  :-)   We just have to mark some extra
1026          * blocks as free.
1027          */
1028         if (old_blocks > new_blocks) {
1029                 if (EXT2FS_CLUSTER_RATIO(fs) > 1) {
1030                         retval = ext2fs_allocate_block_bitmap(fs,
1031                                                         _("new meta blocks"),
1032                                                         &new_meta_bmap);
1033                         if (retval)
1034                                 goto errout;
1035
1036                         retval = mark_table_blocks(fs, new_meta_bmap);
1037                         if (retval)
1038                                 goto errout;
1039                 }
1040
1041                 for (i = 0; i < max_groups; i++) {
1042                         if (!ext2fs_bg_has_super(fs, i)) {
1043                                 group_blk += fs->super->s_blocks_per_group;
1044                                 continue;
1045                         }
1046                         group_end = group_blk + 1 + old_blocks;
1047                         for (blk = group_blk + 1 + new_blocks;
1048                              blk < group_end;) {
1049                                 if (new_meta_bmap == NULL ||
1050                                     !ext2fs_test_block_bitmap2(new_meta_bmap,
1051                                                                blk)) {
1052                                         cluster_freed =
1053                                                 EXT2FS_CLUSTER_RATIO(fs) -
1054                                                 (blk &
1055                                                  EXT2FS_CLUSTER_MASK(fs));
1056                                         if (cluster_freed > group_end - blk)
1057                                                 cluster_freed = group_end - blk;
1058                                         ext2fs_block_alloc_stats2(fs, blk, -1);
1059                                         blk += EXT2FS_CLUSTER_RATIO(fs);
1060                                         rfs->needed_blocks -= cluster_freed;
1061                                         continue;
1062                                 }
1063                                 rfs->needed_blocks--;
1064                                 blk++;
1065                         }
1066                         group_blk += fs->super->s_blocks_per_group;
1067                 }
1068                 retval = 0;
1069                 goto errout;
1070         }
1071         /*
1072          * If we're increasing the number of descriptor blocks, life
1073          * gets interesting....
1074          */
1075         meta_bg_size = EXT2_DESC_PER_BLOCK(fs->super);
1076         flex_bg = fs->super->s_feature_incompat &
1077                 EXT4_FEATURE_INCOMPAT_FLEX_BG;
1078         /* first reserve all of the existing fs meta blocks */
1079         for (i = 0; i < max_groups; i++) {
1080                 has_super = ext2fs_bg_has_super(fs, i);
1081                 if (has_super)
1082                         mark_fs_metablock(rfs, meta_bmap, i, group_blk);
1083
1084                 meta_bg = i / meta_bg_size;
1085                 if (!(fs->super->s_feature_incompat &
1086                       EXT2_FEATURE_INCOMPAT_META_BG) ||
1087                     (meta_bg < fs->super->s_first_meta_bg)) {
1088                         if (has_super) {
1089                                 for (blk = group_blk+1;
1090                                      blk < group_blk + 1 + new_blocks; blk++)
1091                                         mark_fs_metablock(rfs, meta_bmap,
1092                                                           i, blk);
1093                         }
1094                 } else {
1095                         if (has_super)
1096                                 has_super = 1;
1097                         if (((i % meta_bg_size) == 0) ||
1098                             ((i % meta_bg_size) == 1) ||
1099                             ((i % meta_bg_size) == (meta_bg_size-1)))
1100                                 mark_fs_metablock(rfs, meta_bmap, i,
1101                                                   group_blk + has_super);
1102                 }
1103
1104                 /*
1105                  * Reserve the existing meta blocks that we know
1106                  * aren't to be moved.
1107                  *
1108                  * For flex_bg file systems, in order to avoid
1109                  * overwriting fs metadata (especially inode table
1110                  * blocks) belonging to a different block group when
1111                  * we are relocating the inode tables, we need to
1112                  * reserve all existing fs metadata blocks.
1113                  */
1114                 if (ext2fs_block_bitmap_loc(fs, i))
1115                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1116                                  ext2fs_block_bitmap_loc(fs, i));
1117                 else if (flex_bg && i < old_fs->group_desc_count)
1118                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1119                                  ext2fs_block_bitmap_loc(old_fs, i));
1120
1121                 if (ext2fs_inode_bitmap_loc(fs, i))
1122                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1123                                  ext2fs_inode_bitmap_loc(fs, i));
1124                 else if (flex_bg && i < old_fs->group_desc_count)
1125                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1126                                  ext2fs_inode_bitmap_loc(old_fs, i));
1127
1128                 if (ext2fs_inode_table_loc(fs, i))
1129                         ext2fs_mark_block_bitmap_range2(rfs->reserve_blocks,
1130                                         ext2fs_inode_table_loc(fs, i),
1131                                         fs->inode_blocks_per_group);
1132                 else if (flex_bg && i < old_fs->group_desc_count)
1133                         ext2fs_mark_block_bitmap_range2(rfs->reserve_blocks,
1134                                         ext2fs_inode_table_loc(old_fs, i),
1135                                         old_fs->inode_blocks_per_group);
1136
1137                 group_blk += rfs->new_fs->super->s_blocks_per_group;
1138         }
1139
1140         /* Allocate the missing data structures */
1141         for (i = 0; i < max_groups; i++) {
1142                 if (ext2fs_inode_table_loc(fs, i) &&
1143                     ext2fs_inode_bitmap_loc(fs, i) &&
1144                     ext2fs_block_bitmap_loc(fs, i))
1145                         continue;
1146
1147                 retval = ext2fs_allocate_group_table(fs, i,
1148                                                      rfs->reserve_blocks);
1149                 if (retval)
1150                         goto errout;
1151
1152                 /*
1153                  * For those structures that have changed, we need to
1154                  * do bookkeepping.
1155                  */
1156                 if (ext2fs_block_bitmap_loc(old_fs, i) !=
1157                     (blk = ext2fs_block_bitmap_loc(fs, i))) {
1158                         ext2fs_block_alloc_stats2(fs, blk, +1);
1159                         if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
1160                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
1161                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
1162                                                          blk);
1163                 }
1164                 if (ext2fs_inode_bitmap_loc(old_fs, i) !=
1165                     (blk = ext2fs_inode_bitmap_loc(fs, i))) {
1166                         ext2fs_block_alloc_stats2(fs, blk, +1);
1167                         if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
1168                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
1169                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
1170                                                          blk);
1171                 }
1172
1173                 /*
1174                  * The inode table, if we need to relocate it, is
1175                  * handled specially.  We have to reserve the blocks
1176                  * for both the old and the new inode table, since we
1177                  * can't have the inode table be destroyed during the
1178                  * block relocation phase.
1179                  */
1180                 if (ext2fs_inode_table_loc(fs, i) == ext2fs_inode_table_loc(old_fs, i))
1181                         continue;       /* inode table not moved */
1182
1183                 rfs->needed_blocks += fs->inode_blocks_per_group;
1184
1185                 /*
1186                  * Mark the new inode table as in use in the new block
1187                  * allocation bitmap, and move any blocks that might
1188                  * be necessary.
1189                  */
1190                 for (blk = ext2fs_inode_table_loc(fs, i), j=0;
1191                      j < fs->inode_blocks_per_group ; j++, blk++) {
1192                         ext2fs_block_alloc_stats2(fs, blk, +1);
1193                         if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
1194                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
1195                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
1196                                                          blk);
1197                 }
1198
1199                 /*
1200                  * Make sure the old inode table is reserved in the
1201                  * block reservation bitmap.
1202                  */
1203                 for (blk = ext2fs_inode_table_loc(rfs->old_fs, i), j=0;
1204                      j < fs->inode_blocks_per_group ; j++, blk++)
1205                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
1206         }
1207         retval = 0;
1208
1209 errout:
1210         if (new_meta_bmap)
1211                 ext2fs_free_block_bitmap(new_meta_bmap);
1212         if (meta_bmap)
1213                 ext2fs_free_block_bitmap(meta_bmap);
1214
1215         return retval;
1216 }
1217
1218 /*
1219  * This helper function tries to allocate a new block.  We try to
1220  * avoid hitting the original group descriptor blocks at least at
1221  * first, since we want to make it possible to recover from a badly
1222  * aborted resize operation as much as possible.
1223  *
1224  * In the future, I may further modify this routine to balance out
1225  * where we get the new blocks across the various block groups.
1226  * Ideally we would allocate blocks that corresponded with the block
1227  * group of the containing inode, and keep contiguous blocks
1228  * together.  However, this very difficult to do efficiently, since we
1229  * don't have the necessary information up front.
1230  */
1231
1232 #define AVOID_OLD       1
1233 #define DESPERATION     2
1234
1235 static void init_block_alloc(ext2_resize_t rfs)
1236 {
1237         rfs->alloc_state = AVOID_OLD;
1238         rfs->new_blk = rfs->new_fs->super->s_first_data_block;
1239 #if 0
1240         /* HACK for testing */
1241         if (ext2fs_blocks_count(rfs->new_fs->super) >
1242             ext2fs_blocks_count(rfs->old_fs->super))
1243                 rfs->new_blk = ext2fs_blocks_count(rfs->old_fs->super);
1244 #endif
1245 }
1246
1247 static blk64_t get_new_block(ext2_resize_t rfs)
1248 {
1249         ext2_filsys     fs = rfs->new_fs;
1250
1251         while (1) {
1252                 if (rfs->new_blk >= ext2fs_blocks_count(fs->super)) {
1253                         if (rfs->alloc_state == DESPERATION)
1254                                 return 0;
1255
1256 #ifdef RESIZE2FS_DEBUG
1257                         if (rfs->flags & RESIZE_DEBUG_BMOVE)
1258                                 printf("Going into desperation mode "
1259                                        "for block allocations\n");
1260 #endif
1261                         rfs->alloc_state = DESPERATION;
1262                         rfs->new_blk = fs->super->s_first_data_block;
1263                         continue;
1264                 }
1265                 if (ext2fs_test_block_bitmap2(fs->block_map, rfs->new_blk) ||
1266                     ext2fs_test_block_bitmap2(rfs->reserve_blocks,
1267                                              rfs->new_blk) ||
1268                     ((rfs->alloc_state == AVOID_OLD) &&
1269                      (rfs->new_blk < ext2fs_blocks_count(rfs->old_fs->super)) &&
1270                      ext2fs_test_block_bitmap2(rfs->old_fs->block_map,
1271                                               rfs->new_blk))) {
1272                         rfs->new_blk++;
1273                         continue;
1274                 }
1275                 return rfs->new_blk;
1276         }
1277 }
1278
1279 static errcode_t resize2fs_get_alloc_block(ext2_filsys fs, blk64_t goal,
1280                                            blk64_t *ret)
1281 {
1282         ext2_resize_t rfs = (ext2_resize_t) fs->priv_data;
1283         blk64_t blk;
1284
1285         blk = get_new_block(rfs);
1286         if (!blk)
1287                 return ENOSPC;
1288
1289 #ifdef RESIZE2FS_DEBUG
1290         if (rfs->flags & 0xF)
1291                 printf("get_alloc_block allocating %llu\n", blk);
1292 #endif
1293
1294         ext2fs_mark_block_bitmap2(rfs->old_fs->block_map, blk);
1295         ext2fs_mark_block_bitmap2(rfs->new_fs->block_map, blk);
1296         *ret = (blk64_t) blk;
1297         return 0;
1298 }
1299
1300 static errcode_t block_mover(ext2_resize_t rfs)
1301 {
1302         blk64_t                 blk, old_blk, new_blk;
1303         ext2_filsys             fs = rfs->new_fs;
1304         ext2_filsys             old_fs = rfs->old_fs;
1305         errcode_t               retval;
1306         __u64                   size;
1307         int                     c;
1308         int                     to_move, moved;
1309         ext2_badblocks_list     badblock_list = 0;
1310         int                     bb_modified = 0;
1311
1312         fs->get_alloc_block = resize2fs_get_alloc_block;
1313         old_fs->get_alloc_block = resize2fs_get_alloc_block;
1314
1315         retval = ext2fs_read_bb_inode(old_fs, &badblock_list);
1316         if (retval)
1317                 return retval;
1318
1319         new_blk = fs->super->s_first_data_block;
1320         if (!rfs->itable_buf) {
1321                 retval = ext2fs_get_array(fs->blocksize,
1322                                         fs->inode_blocks_per_group,
1323                                         &rfs->itable_buf);
1324                 if (retval)
1325                         return retval;
1326         }
1327         retval = ext2fs_create_extent_table(&rfs->bmap, 0);
1328         if (retval)
1329                 return retval;
1330
1331         /*
1332          * The first step is to figure out where all of the blocks
1333          * will go.
1334          */
1335         to_move = moved = 0;
1336         init_block_alloc(rfs);
1337         for (blk = B2C(old_fs->super->s_first_data_block);
1338              blk < ext2fs_blocks_count(old_fs->super);
1339              blk += EXT2FS_CLUSTER_RATIO(fs)) {
1340                 if (!ext2fs_test_block_bitmap2(old_fs->block_map, blk))
1341                         continue;
1342                 if (!ext2fs_test_block_bitmap2(rfs->move_blocks, blk))
1343                         continue;
1344                 if (ext2fs_badblocks_list_test(badblock_list, blk)) {
1345                         ext2fs_badblocks_list_del(badblock_list, blk);
1346                         bb_modified++;
1347                         continue;
1348                 }
1349
1350                 new_blk = get_new_block(rfs);
1351                 if (!new_blk) {
1352                         retval = ENOSPC;
1353                         goto errout;
1354                 }
1355                 ext2fs_block_alloc_stats2(fs, new_blk, +1);
1356                 ext2fs_add_extent_entry(rfs->bmap, B2C(blk), B2C(new_blk));
1357                 to_move++;
1358         }
1359
1360         if (to_move == 0) {
1361                 if (rfs->bmap) {
1362                         ext2fs_free_extent_table(rfs->bmap);
1363                         rfs->bmap = 0;
1364                 }
1365                 retval = 0;
1366                 goto errout;
1367         }
1368
1369         /*
1370          * Step two is to actually move the blocks
1371          */
1372         retval =  ext2fs_iterate_extent(rfs->bmap, 0, 0, 0);
1373         if (retval) goto errout;
1374
1375         if (rfs->progress) {
1376                 retval = (rfs->progress)(rfs, E2_RSZ_BLOCK_RELOC_PASS,
1377                                          0, to_move);
1378                 if (retval)
1379                         goto errout;
1380         }
1381         while (1) {
1382                 retval = ext2fs_iterate_extent(rfs->bmap, &old_blk, &new_blk, &size);
1383                 if (retval) goto errout;
1384                 if (!size)
1385                         break;
1386                 old_blk = C2B(old_blk);
1387                 new_blk = C2B(new_blk);
1388                 size = C2B(size);
1389 #ifdef RESIZE2FS_DEBUG
1390                 if (rfs->flags & RESIZE_DEBUG_BMOVE)
1391                         printf("Moving %llu blocks %llu->%llu\n",
1392                                size, old_blk, new_blk);
1393 #endif
1394                 do {
1395                         c = size;
1396                         if (c > fs->inode_blocks_per_group)
1397                                 c = fs->inode_blocks_per_group;
1398                         retval = io_channel_read_blk64(fs->io, old_blk, c,
1399                                                        rfs->itable_buf);
1400                         if (retval) goto errout;
1401                         retval = io_channel_write_blk64(fs->io, new_blk, c,
1402                                                         rfs->itable_buf);
1403                         if (retval) goto errout;
1404                         size -= c;
1405                         new_blk += c;
1406                         old_blk += c;
1407                         moved += c;
1408                         if (rfs->progress) {
1409                                 io_channel_flush(fs->io);
1410                                 retval = (rfs->progress)(rfs,
1411                                                 E2_RSZ_BLOCK_RELOC_PASS,
1412                                                 moved, to_move);
1413                                 if (retval)
1414                                         goto errout;
1415                         }
1416                 } while (size > 0);
1417                 io_channel_flush(fs->io);
1418         }
1419
1420 errout:
1421         if (badblock_list) {
1422                 if (!retval && bb_modified)
1423                         retval = ext2fs_update_bb_inode(old_fs,
1424                                                         badblock_list);
1425                 ext2fs_badblocks_list_free(badblock_list);
1426         }
1427         return retval;
1428 }
1429
1430
1431 /* --------------------------------------------------------------------
1432  *
1433  * Resize processing, phase 3
1434  *
1435  * --------------------------------------------------------------------
1436  */
1437
1438
1439 /*
1440  * The extent translation table is stored in clusters so we need to
1441  * take special care when mapping a source block number to its
1442  * destination block number.
1443  */
1444 static __u64 extent_translate(ext2_filsys fs, ext2_extent extent, __u64 old_loc)
1445 {
1446         __u64 new_block = C2B(ext2fs_extent_translate(extent, B2C(old_loc)));
1447
1448         if (new_block != 0)
1449                 new_block += old_loc & (EXT2FS_CLUSTER_RATIO(fs) - 1);
1450         return new_block;
1451 }
1452
1453 struct process_block_struct {
1454         ext2_resize_t           rfs;
1455         ext2_ino_t              ino;
1456         struct ext2_inode *     inode;
1457         errcode_t               error;
1458         int                     is_dir;
1459         int                     changed;
1460 };
1461
1462 static int process_block(ext2_filsys fs, blk64_t        *block_nr,
1463                          e2_blkcnt_t blockcnt,
1464                          blk64_t ref_block EXT2FS_ATTR((unused)),
1465                          int ref_offset EXT2FS_ATTR((unused)), void *priv_data)
1466 {
1467         struct process_block_struct *pb;
1468         errcode_t       retval;
1469         blk64_t         block, new_block;
1470         int             ret = 0;
1471
1472         pb = (struct process_block_struct *) priv_data;
1473         block = *block_nr;
1474         if (pb->rfs->bmap) {
1475                 new_block = extent_translate(fs, pb->rfs->bmap, block);
1476                 if (new_block) {
1477                         *block_nr = new_block;
1478                         ret |= BLOCK_CHANGED;
1479                         pb->changed = 1;
1480 #ifdef RESIZE2FS_DEBUG
1481                         if (pb->rfs->flags & RESIZE_DEBUG_BMOVE)
1482                                 printf("ino=%u, blockcnt=%lld, %llu->%llu\n",
1483                                        pb->ino, blockcnt, block, new_block);
1484 #endif
1485                         block = new_block;
1486                 }
1487         }
1488         if (pb->is_dir) {
1489                 retval = ext2fs_add_dir_block2(fs->dblist, pb->ino,
1490                                                block, (int) blockcnt);
1491                 if (retval) {
1492                         pb->error = retval;
1493                         ret |= BLOCK_ABORT;
1494                 }
1495         }
1496         return ret;
1497 }
1498
1499 /*
1500  * Progress callback
1501  */
1502 static errcode_t progress_callback(ext2_filsys fs,
1503                                    ext2_inode_scan scan EXT2FS_ATTR((unused)),
1504                                    dgrp_t group, void * priv_data)
1505 {
1506         ext2_resize_t rfs = (ext2_resize_t) priv_data;
1507         errcode_t               retval;
1508
1509         /*
1510          * This check is to protect against old ext2 libraries.  It
1511          * shouldn't be needed against new libraries.
1512          */
1513         if ((group+1) == 0)
1514                 return 0;
1515
1516         if (rfs->progress) {
1517                 io_channel_flush(fs->io);
1518                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_SCAN_PASS,
1519                                          group+1, fs->group_desc_count);
1520                 if (retval)
1521                         return retval;
1522         }
1523
1524         return 0;
1525 }
1526
1527 static errcode_t inode_scan_and_fix(ext2_resize_t rfs)
1528 {
1529         struct process_block_struct     pb;
1530         ext2_ino_t              ino, new_inode;
1531         struct ext2_inode       *inode = NULL;
1532         ext2_inode_scan         scan = NULL;
1533         errcode_t               retval;
1534         char                    *block_buf = 0;
1535         ext2_ino_t              start_to_move;
1536         blk64_t                 orig_size;
1537         blk64_t                 new_block;
1538         int                     inode_size;
1539
1540         if ((rfs->old_fs->group_desc_count <=
1541              rfs->new_fs->group_desc_count) &&
1542             !rfs->bmap)
1543                 return 0;
1544
1545         /*
1546          * Save the original size of the old filesystem, and
1547          * temporarily set the size to be the new size if the new size
1548          * is larger.  We need to do this to avoid catching an error
1549          * by the block iterator routines
1550          */
1551         orig_size = ext2fs_blocks_count(rfs->old_fs->super);
1552         if (orig_size < ext2fs_blocks_count(rfs->new_fs->super))
1553                 ext2fs_blocks_count_set(rfs->old_fs->super,
1554                                 ext2fs_blocks_count(rfs->new_fs->super));
1555
1556         retval = ext2fs_open_inode_scan(rfs->old_fs, 0, &scan);
1557         if (retval) goto errout;
1558
1559         retval = ext2fs_init_dblist(rfs->old_fs, 0);
1560         if (retval) goto errout;
1561         retval = ext2fs_get_array(rfs->old_fs->blocksize, 3, &block_buf);
1562         if (retval) goto errout;
1563
1564         start_to_move = (rfs->new_fs->group_desc_count *
1565                          rfs->new_fs->super->s_inodes_per_group);
1566
1567         if (rfs->progress) {
1568                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_SCAN_PASS,
1569                                          0, rfs->old_fs->group_desc_count);
1570                 if (retval)
1571                         goto errout;
1572         }
1573         ext2fs_set_inode_callback(scan, progress_callback, (void *) rfs);
1574         pb.rfs = rfs;
1575         pb.inode = inode;
1576         pb.error = 0;
1577         new_inode = EXT2_FIRST_INODE(rfs->new_fs->super);
1578         inode_size = EXT2_INODE_SIZE(rfs->new_fs->super);
1579         inode = malloc(inode_size);
1580         if (!inode) {
1581                 retval = ENOMEM;
1582                 goto errout;
1583         }
1584         /*
1585          * First, copy all of the inodes that need to be moved
1586          * elsewhere in the inode table
1587          */
1588         while (1) {
1589                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, inode_size);
1590                 if (retval) goto errout;
1591                 if (!ino)
1592                         break;
1593
1594                 if (inode->i_links_count == 0 && ino != EXT2_RESIZE_INO)
1595                         continue; /* inode not in use */
1596
1597                 pb.is_dir = LINUX_S_ISDIR(inode->i_mode);
1598                 pb.changed = 0;
1599
1600                 if (ext2fs_file_acl_block(rfs->old_fs, inode) && rfs->bmap) {
1601                         new_block = extent_translate(rfs->old_fs, rfs->bmap,
1602                                 ext2fs_file_acl_block(rfs->old_fs, inode));
1603                         if (new_block) {
1604                                 ext2fs_file_acl_block_set(rfs->old_fs, inode,
1605                                                           new_block);
1606                                 retval = ext2fs_write_inode_full(rfs->old_fs,
1607                                                             ino, inode, inode_size);
1608                                 if (retval) goto errout;
1609                         }
1610                 }
1611
1612                 if (ext2fs_inode_has_valid_blocks2(rfs->old_fs, inode) &&
1613                     (rfs->bmap || pb.is_dir)) {
1614                         pb.ino = ino;
1615                         retval = ext2fs_block_iterate3(rfs->old_fs,
1616                                                        ino, 0, block_buf,
1617                                                        process_block, &pb);
1618                         if (retval)
1619                                 goto errout;
1620                         if (pb.error) {
1621                                 retval = pb.error;
1622                                 goto errout;
1623                         }
1624                 }
1625
1626                 if (ino <= start_to_move)
1627                         continue; /* Don't need to move it. */
1628
1629                 /*
1630                  * Find a new inode
1631                  */
1632                 retval = ext2fs_new_inode(rfs->new_fs, 0, 0, 0, &new_inode);
1633                 if (retval)
1634                         goto errout;
1635
1636                 ext2fs_inode_alloc_stats2(rfs->new_fs, new_inode, +1,
1637                                           pb.is_dir);
1638                 if (pb.changed) {
1639                         /* Get the new version of the inode */
1640                         retval = ext2fs_read_inode_full(rfs->old_fs, ino,
1641                                                 inode, inode_size);
1642                         if (retval) goto errout;
1643                 }
1644                 inode->i_ctime = time(0);
1645                 retval = ext2fs_write_inode_full(rfs->old_fs, new_inode,
1646                                                 inode, inode_size);
1647                 if (retval) goto errout;
1648
1649 #ifdef RESIZE2FS_DEBUG
1650                 if (rfs->flags & RESIZE_DEBUG_INODEMAP)
1651                         printf("Inode moved %u->%u\n", ino, new_inode);
1652 #endif
1653                 if (!rfs->imap) {
1654                         retval = ext2fs_create_extent_table(&rfs->imap, 0);
1655                         if (retval)
1656                                 goto errout;
1657                 }
1658                 ext2fs_add_extent_entry(rfs->imap, ino, new_inode);
1659         }
1660         io_channel_flush(rfs->old_fs->io);
1661
1662 errout:
1663         ext2fs_blocks_count_set(rfs->old_fs->super, orig_size);
1664         if (rfs->bmap) {
1665                 ext2fs_free_extent_table(rfs->bmap);
1666                 rfs->bmap = 0;
1667         }
1668         if (scan)
1669                 ext2fs_close_inode_scan(scan);
1670         if (block_buf)
1671                 ext2fs_free_mem(&block_buf);
1672         free(inode);
1673         return retval;
1674 }
1675
1676 /* --------------------------------------------------------------------
1677  *
1678  * Resize processing, phase 4.
1679  *
1680  * --------------------------------------------------------------------
1681  */
1682
1683 struct istruct {
1684         ext2_resize_t rfs;
1685         errcode_t       err;
1686         unsigned int    max_dirs;
1687         unsigned int    num;
1688 };
1689
1690 static int check_and_change_inodes(ext2_ino_t dir,
1691                                    int entry EXT2FS_ATTR((unused)),
1692                                    struct ext2_dir_entry *dirent, int offset,
1693                                    int  blocksize EXT2FS_ATTR((unused)),
1694                                    char *buf EXT2FS_ATTR((unused)),
1695                                    void *priv_data)
1696 {
1697         struct istruct *is = (struct istruct *) priv_data;
1698         struct ext2_inode       inode;
1699         ext2_ino_t              new_inode;
1700         errcode_t               retval;
1701
1702         if (is->rfs->progress && offset == 0) {
1703                 io_channel_flush(is->rfs->old_fs->io);
1704                 is->err = (is->rfs->progress)(is->rfs,
1705                                               E2_RSZ_INODE_REF_UPD_PASS,
1706                                               ++is->num, is->max_dirs);
1707                 if (is->err)
1708                         return DIRENT_ABORT;
1709         }
1710
1711         if (!dirent->inode)
1712                 return 0;
1713
1714         new_inode = ext2fs_extent_translate(is->rfs->imap, dirent->inode);
1715
1716         if (!new_inode)
1717                 return 0;
1718 #ifdef RESIZE2FS_DEBUG
1719         if (is->rfs->flags & RESIZE_DEBUG_INODEMAP)
1720                 printf("Inode translate (dir=%u, name=%.*s, %u->%u)\n",
1721                        dir, dirent->name_len&0xFF, dirent->name,
1722                        dirent->inode, new_inode);
1723 #endif
1724
1725         dirent->inode = new_inode;
1726
1727         /* Update the directory mtime and ctime */
1728         retval = ext2fs_read_inode(is->rfs->old_fs, dir, &inode);
1729         if (retval == 0) {
1730                 inode.i_mtime = inode.i_ctime = time(0);
1731                 is->err = ext2fs_write_inode(is->rfs->old_fs, dir, &inode);
1732                 if (is->err)
1733                         return DIRENT_ABORT;
1734         }
1735
1736         return DIRENT_CHANGED;
1737 }
1738
1739 static errcode_t inode_ref_fix(ext2_resize_t rfs)
1740 {
1741         errcode_t               retval;
1742         struct istruct          is;
1743
1744         if (!rfs->imap)
1745                 return 0;
1746
1747         /*
1748          * Now, we iterate over all of the directories to update the
1749          * inode references
1750          */
1751         is.num = 0;
1752         is.max_dirs = ext2fs_dblist_count2(rfs->old_fs->dblist);
1753         is.rfs = rfs;
1754         is.err = 0;
1755
1756         if (rfs->progress) {
1757                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_REF_UPD_PASS,
1758                                          0, is.max_dirs);
1759                 if (retval)
1760                         goto errout;
1761         }
1762
1763         retval = ext2fs_dblist_dir_iterate(rfs->old_fs->dblist,
1764                                            DIRENT_FLAG_INCLUDE_EMPTY, 0,
1765                                            check_and_change_inodes, &is);
1766         if (retval)
1767                 goto errout;
1768         if (is.err) {
1769                 retval = is.err;
1770                 goto errout;
1771         }
1772
1773         if (rfs->progress && (is.num < is.max_dirs))
1774                 (rfs->progress)(rfs, E2_RSZ_INODE_REF_UPD_PASS,
1775                                 is.max_dirs, is.max_dirs);
1776
1777 errout:
1778         ext2fs_free_extent_table(rfs->imap);
1779         rfs->imap = 0;
1780         return retval;
1781 }
1782
1783
1784 /* --------------------------------------------------------------------
1785  *
1786  * Resize processing, phase 5.
1787  *
1788  * In this phase we actually move the inode table around, and then
1789  * update the summary statistics.  This is scary, since aborting here
1790  * will potentially scramble the filesystem.  (We are moving the
1791  * inode tables around in place, and so the potential for lost data,
1792  * or at the very least scrambling the mapping between filenames and
1793  * inode numbers is very high in case of a power failure here.)
1794  * --------------------------------------------------------------------
1795  */
1796
1797
1798 /*
1799  * A very scary routine --- this one moves the inode table around!!!
1800  *
1801  * After this you have to use the rfs->new_fs file handle to read and
1802  * write inodes.
1803  */
1804 static errcode_t move_itables(ext2_resize_t rfs)
1805 {
1806         int             n, num, size;
1807         long long       diff;
1808         dgrp_t          i, max_groups;
1809         ext2_filsys     fs = rfs->new_fs;
1810         char            *cp;
1811         blk64_t         old_blk, new_blk, blk, cluster_freed;
1812         errcode_t       retval;
1813         int             j, to_move, moved;
1814         ext2fs_block_bitmap     new_bmap = NULL;
1815
1816         max_groups = fs->group_desc_count;
1817         if (max_groups > rfs->old_fs->group_desc_count)
1818                 max_groups = rfs->old_fs->group_desc_count;
1819
1820         size = fs->blocksize * fs->inode_blocks_per_group;
1821         if (!rfs->itable_buf) {
1822                 retval = ext2fs_get_mem(size, &rfs->itable_buf);
1823                 if (retval)
1824                         return retval;
1825         }
1826
1827         if (EXT2FS_CLUSTER_RATIO(fs) > 1) {
1828                 retval = ext2fs_allocate_block_bitmap(fs, _("new meta blocks"),
1829                                                       &new_bmap);
1830                 if (retval)
1831                         return retval;
1832
1833                 retval = mark_table_blocks(fs, new_bmap);
1834                 if (retval)
1835                         goto errout;
1836         }
1837
1838         /*
1839          * Figure out how many inode tables we need to move
1840          */
1841         to_move = moved = 0;
1842         for (i=0; i < max_groups; i++)
1843                 if (ext2fs_inode_table_loc(rfs->old_fs, i) !=
1844                     ext2fs_inode_table_loc(fs, i))
1845                         to_move++;
1846
1847         if (to_move == 0)
1848                 return 0;
1849
1850         if (rfs->progress) {
1851                 retval = rfs->progress(rfs, E2_RSZ_MOVE_ITABLE_PASS,
1852                                        0, to_move);
1853                 if (retval)
1854                         goto errout;
1855         }
1856
1857         rfs->old_fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1858
1859         for (i=0; i < max_groups; i++) {
1860                 old_blk = ext2fs_inode_table_loc(rfs->old_fs, i);
1861                 new_blk = ext2fs_inode_table_loc(fs, i);
1862                 diff = new_blk - old_blk;
1863
1864 #ifdef RESIZE2FS_DEBUG
1865                 if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
1866                         printf("Itable move group %d block %llu->%llu (diff %lld)\n",
1867                                i, old_blk, new_blk, diff);
1868 #endif
1869
1870                 if (!diff)
1871                         continue;
1872
1873                 retval = io_channel_read_blk64(fs->io, old_blk,
1874                                                fs->inode_blocks_per_group,
1875                                                rfs->itable_buf);
1876                 if (retval)
1877                         goto errout;
1878                 /*
1879                  * The end of the inode table segment often contains
1880                  * all zeros, and we're often only moving the inode
1881                  * table down a block or two.  If so, we can optimize
1882                  * things by not rewriting blocks that we know to be zero
1883                  * already.
1884                  */
1885                 for (cp = rfs->itable_buf+size-1, n=0; n < size; n++, cp--)
1886                         if (*cp)
1887                                 break;
1888                 n = n >> EXT2_BLOCK_SIZE_BITS(fs->super);
1889 #ifdef RESIZE2FS_DEBUG
1890                 if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
1891                         printf("%d blocks of zeros...\n", n);
1892 #endif
1893                 num = fs->inode_blocks_per_group;
1894                 if (n > diff)
1895                         num -= n;
1896
1897                 retval = io_channel_write_blk64(fs->io, new_blk,
1898                                                 num, rfs->itable_buf);
1899                 if (retval) {
1900                         io_channel_write_blk64(fs->io, old_blk,
1901                                                num, rfs->itable_buf);
1902                         goto errout;
1903                 }
1904                 if (n > diff) {
1905                         retval = io_channel_write_blk64(fs->io,
1906                               old_blk + fs->inode_blocks_per_group,
1907                               diff, (rfs->itable_buf +
1908                                      (fs->inode_blocks_per_group - diff) *
1909                                      fs->blocksize));
1910                         if (retval)
1911                                 goto errout;
1912                 }
1913
1914                 for (blk = ext2fs_inode_table_loc(rfs->old_fs, i), j=0;
1915                      j < fs->inode_blocks_per_group;) {
1916                         if (new_bmap == NULL ||
1917                             !ext2fs_test_block_bitmap2(new_bmap, blk)) {
1918                                 ext2fs_block_alloc_stats2(fs, blk, -1);
1919                                 cluster_freed = EXT2FS_CLUSTER_RATIO(fs) -
1920                                                 (blk & EXT2FS_CLUSTER_MASK(fs));
1921                                 blk += cluster_freed;
1922                                 j += cluster_freed;
1923                                 continue;
1924                         }
1925                         blk++;
1926                         j++;
1927                 }
1928
1929                 ext2fs_inode_table_loc_set(rfs->old_fs, i, new_blk);
1930                 ext2fs_group_desc_csum_set(rfs->old_fs, i);
1931                 ext2fs_mark_super_dirty(rfs->old_fs);
1932                 ext2fs_flush(rfs->old_fs);
1933
1934                 if (rfs->progress) {
1935                         retval = rfs->progress(rfs, E2_RSZ_MOVE_ITABLE_PASS,
1936                                                ++moved, to_move);
1937                         if (retval)
1938                                 goto errout;
1939                 }
1940         }
1941         mark_table_blocks(fs, fs->block_map);
1942         ext2fs_flush(fs);
1943 #ifdef RESIZE2FS_DEBUG
1944         if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
1945                 printf("Inode table move finished.\n");
1946 #endif
1947         retval = 0;
1948
1949 errout:
1950         if (new_bmap)
1951                 ext2fs_free_block_bitmap(new_bmap);
1952         return retval;
1953 }
1954
1955 /*
1956  * This function is used when expanding a file system.  It frees the
1957  * superblock and block group descriptor blocks from the block group
1958  * which is no longer the last block group.
1959  */
1960 static errcode_t clear_sparse_super2_last_group(ext2_resize_t rfs)
1961 {
1962         ext2_filsys     fs = rfs->new_fs;
1963         ext2_filsys     old_fs = rfs->old_fs;
1964         errcode_t       retval;
1965         dgrp_t          old_last_bg = rfs->old_fs->group_desc_count - 1;
1966         dgrp_t          last_bg = fs->group_desc_count - 1;
1967         blk64_t         sb, old_desc;
1968         blk_t           num;
1969
1970         if (!(fs->super->s_feature_compat & EXT4_FEATURE_COMPAT_SPARSE_SUPER2))
1971                 return 0;
1972
1973         if (last_bg <= old_last_bg)
1974                 return 0;
1975
1976         if (fs->super->s_backup_bgs[0] == old_fs->super->s_backup_bgs[0] &&
1977             fs->super->s_backup_bgs[1] == old_fs->super->s_backup_bgs[1])
1978                 return 0;
1979
1980         if (old_fs->super->s_backup_bgs[0] != old_last_bg &&
1981             old_fs->super->s_backup_bgs[1] != old_last_bg)
1982                 return 0;
1983
1984         if (fs->super->s_backup_bgs[0] == old_last_bg ||
1985             fs->super->s_backup_bgs[1] == old_last_bg)
1986                 return 0;
1987
1988         retval = ext2fs_super_and_bgd_loc2(rfs->old_fs, old_last_bg,
1989                                            &sb, &old_desc, NULL, &num);
1990         if (retval)
1991                 return retval;
1992
1993         if (sb)
1994                 ext2fs_unmark_block_bitmap2(fs->block_map, sb);
1995         if (old_desc)
1996                 ext2fs_unmark_block_bitmap_range2(fs->block_map, old_desc, num);
1997         return 0;
1998 }
1999
2000 /*
2001  * This function is used when shrinking a file system.  We need to
2002  * utilize blocks from what will be the new last block group for the
2003  * backup superblock and block group descriptor blocks.
2004  * Unfortunately, those blocks may be used by other files or fs
2005  * metadata blocks.  We need to mark them as being in use.
2006  */
2007 static errcode_t reserve_sparse_super2_last_group(ext2_resize_t rfs,
2008                                                  ext2fs_block_bitmap meta_bmap)
2009 {
2010         ext2_filsys     fs = rfs->new_fs;
2011         ext2_filsys     old_fs = rfs->old_fs;
2012         errcode_t       retval;
2013         dgrp_t          old_last_bg = rfs->old_fs->group_desc_count - 1;
2014         dgrp_t          last_bg = fs->group_desc_count - 1;
2015         dgrp_t          g;
2016         blk64_t         blk, sb, old_desc;
2017         blk_t           i, num;
2018         int             realloc = 0;
2019
2020         if (!(fs->super->s_feature_compat & EXT4_FEATURE_COMPAT_SPARSE_SUPER2))
2021                 return 0;
2022
2023         if (last_bg >= old_last_bg)
2024                 return 0;
2025
2026         if (fs->super->s_backup_bgs[0] == old_fs->super->s_backup_bgs[0] &&
2027             fs->super->s_backup_bgs[1] == old_fs->super->s_backup_bgs[1])
2028                 return 0;
2029
2030         if (fs->super->s_backup_bgs[0] != last_bg &&
2031             fs->super->s_backup_bgs[1] != last_bg)
2032                 return 0;
2033
2034         if (old_fs->super->s_backup_bgs[0] == last_bg ||
2035             old_fs->super->s_backup_bgs[1] == last_bg)
2036                 return 0;
2037
2038         retval = ext2fs_super_and_bgd_loc2(rfs->new_fs, last_bg,
2039                                            &sb, &old_desc, NULL, &num);
2040         if (retval)
2041                 return retval;
2042
2043         if (!sb) {
2044                 fputs(_("Should never happen!  No sb in last super_sparse bg?\n"),
2045                       stderr);
2046                 exit(1);
2047         }
2048         if (old_desc != sb+1) {
2049                 fputs(_("Should never happen!  Unexpected old_desc in "
2050                         "super_sparse bg?\n"),
2051                       stderr);
2052                 exit(1);
2053         }
2054         num = (old_desc) ? num : 1;
2055
2056         /* Reserve the backup blocks */
2057         ext2fs_mark_block_bitmap_range2(fs->block_map, sb, num);
2058
2059         for (g = 0; g < fs->group_desc_count; g++) {
2060                 blk64_t mb;
2061
2062                 mb = ext2fs_block_bitmap_loc(fs, g);
2063                 if ((mb >= sb) && (mb < sb + num)) {
2064                         ext2fs_block_bitmap_loc_set(fs, g, 0);
2065                         realloc = 1;
2066                 }
2067                 mb = ext2fs_inode_bitmap_loc(fs, g);
2068                 if ((mb >= sb) && (mb < sb + num)) {
2069                         ext2fs_inode_bitmap_loc_set(fs, g, 0);
2070                         realloc = 1;
2071                 }
2072                 mb = ext2fs_inode_table_loc(fs, g);
2073                 if ((mb < sb + num) &&
2074                     (sb < mb + fs->inode_blocks_per_group)) {
2075                         ext2fs_inode_table_loc_set(fs, g, 0);
2076                         realloc = 1;
2077                 }
2078                 if (realloc) {
2079                         retval = ext2fs_allocate_group_table(fs, g, 0);
2080                         if (retval)
2081                                 return retval;
2082                 }
2083         }
2084
2085         for (blk = sb, i = 0; i < num; blk++, i++) {
2086                 if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
2087                     !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
2088                         ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
2089                         rfs->needed_blocks++;
2090                 }
2091                 ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
2092         }
2093         return 0;
2094 }
2095
2096 /*
2097  * Fix the resize inode
2098  */
2099 static errcode_t fix_resize_inode(ext2_filsys fs)
2100 {
2101         struct ext2_inode       inode;
2102         errcode_t               retval;
2103         char                    *block_buf = NULL;
2104
2105         if (!(fs->super->s_feature_compat &
2106               EXT2_FEATURE_COMPAT_RESIZE_INODE))
2107                 return 0;
2108
2109         retval = ext2fs_get_mem(fs->blocksize, &block_buf);
2110         if (retval) goto errout;
2111
2112         retval = ext2fs_read_inode(fs, EXT2_RESIZE_INO, &inode);
2113         if (retval) goto errout;
2114
2115         ext2fs_iblk_set(fs, &inode, 1);
2116
2117         retval = ext2fs_write_inode(fs, EXT2_RESIZE_INO, &inode);
2118         if (retval) goto errout;
2119
2120         if (!inode.i_block[EXT2_DIND_BLOCK]) {
2121                 /*
2122                  * Avoid zeroing out block #0; that's rude.  This
2123                  * should never happen anyway since the filesystem
2124                  * should be fsck'ed and we assume it is consistent.
2125                  */
2126                 fprintf(stderr, "%s",
2127                         _("Should never happen: resize inode corrupt!\n"));
2128                 exit(1);
2129         }
2130
2131         memset(block_buf, 0, fs->blocksize);
2132
2133         retval = io_channel_write_blk64(fs->io, inode.i_block[EXT2_DIND_BLOCK],
2134                                         1, block_buf);
2135         if (retval) goto errout;
2136
2137         retval = ext2fs_create_resize_inode(fs);
2138         if (retval)
2139                 goto errout;
2140
2141 errout:
2142         if (block_buf)
2143                 ext2fs_free_mem(&block_buf);
2144         return retval;
2145 }
2146
2147 /*
2148  * Finally, recalculate the summary information
2149  */
2150 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
2151 {
2152         blk64_t         blk;
2153         ext2_ino_t      ino;
2154         unsigned int    group = 0;
2155         unsigned int    count = 0;
2156         blk64_t         total_blocks_free = 0;
2157         int             total_inodes_free = 0;
2158         int             group_free = 0;
2159         int             uninit = 0;
2160         blk64_t         super_blk, old_desc_blk, new_desc_blk;
2161         int             old_desc_blocks;
2162
2163         /*
2164          * First calculate the block statistics
2165          */
2166         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_BLOCK_UNINIT);
2167         ext2fs_super_and_bgd_loc2(fs, group, &super_blk, &old_desc_blk,
2168                                   &new_desc_blk, 0);
2169         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG)
2170                 old_desc_blocks = fs->super->s_first_meta_bg;
2171         else
2172                 old_desc_blocks = fs->desc_blocks +
2173                         fs->super->s_reserved_gdt_blocks;
2174         for (blk = B2C(fs->super->s_first_data_block);
2175              blk < ext2fs_blocks_count(fs->super);
2176              blk += EXT2FS_CLUSTER_RATIO(fs)) {
2177                 if ((uninit &&
2178                      !(EQ_CLSTR(blk, super_blk) ||
2179                        ((old_desc_blk && old_desc_blocks &&
2180                          GE_CLSTR(blk, old_desc_blk) &&
2181                          LT_CLSTR(blk, old_desc_blk + old_desc_blocks))) ||
2182                        ((new_desc_blk && EQ_CLSTR(blk, new_desc_blk))) ||
2183                        EQ_CLSTR(blk, ext2fs_block_bitmap_loc(fs, group)) ||
2184                        EQ_CLSTR(blk, ext2fs_inode_bitmap_loc(fs, group)) ||
2185                        ((GE_CLSTR(blk, ext2fs_inode_table_loc(fs, group)) &&
2186                          LT_CLSTR(blk, ext2fs_inode_table_loc(fs, group)
2187                                   + fs->inode_blocks_per_group))))) ||
2188                     (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk))) {
2189                         group_free++;
2190                         total_blocks_free++;
2191                 }
2192                 count++;
2193                 if ((count == fs->super->s_clusters_per_group) ||
2194                     EQ_CLSTR(blk, ext2fs_blocks_count(fs->super)-1)) {
2195                         ext2fs_bg_free_blocks_count_set(fs, group, group_free);
2196                         ext2fs_group_desc_csum_set(fs, group);
2197                         group++;
2198                         if (group >= fs->group_desc_count)
2199                                 break;
2200                         count = 0;
2201                         group_free = 0;
2202                         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_BLOCK_UNINIT);
2203                         ext2fs_super_and_bgd_loc2(fs, group, &super_blk,
2204                                                   &old_desc_blk,
2205                                                   &new_desc_blk, 0);
2206                         if (fs->super->s_feature_incompat &
2207                             EXT2_FEATURE_INCOMPAT_META_BG)
2208                                 old_desc_blocks = fs->super->s_first_meta_bg;
2209                         else
2210                                 old_desc_blocks = fs->desc_blocks +
2211                                         fs->super->s_reserved_gdt_blocks;
2212                 }
2213         }
2214         total_blocks_free = C2B(total_blocks_free);
2215         ext2fs_free_blocks_count_set(fs->super, total_blocks_free);
2216
2217         /*
2218          * Next, calculate the inode statistics
2219          */
2220         group_free = 0;
2221         count = 0;
2222         group = 0;
2223
2224         /* Protect loop from wrap-around if s_inodes_count maxed */
2225         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT);
2226         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
2227                 if (uninit ||
2228                     !ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
2229                         group_free++;
2230                         total_inodes_free++;
2231                 }
2232                 count++;
2233                 if ((count == fs->super->s_inodes_per_group) ||
2234                     (ino == fs->super->s_inodes_count)) {
2235                         ext2fs_bg_free_inodes_count_set(fs, group, group_free);
2236                         ext2fs_group_desc_csum_set(fs, group);
2237                         group++;
2238                         if (group >= fs->group_desc_count)
2239                                 break;
2240                         count = 0;
2241                         group_free = 0;
2242                         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT);
2243                 }
2244         }
2245         fs->super->s_free_inodes_count = total_inodes_free;
2246         ext2fs_mark_super_dirty(fs);
2247         return 0;
2248 }
2249
2250 /*
2251  *  Journal may have been relocated; update the backup journal blocks
2252  *  in the superblock.
2253  */
2254 static errcode_t fix_sb_journal_backup(ext2_filsys fs)
2255 {
2256         errcode_t         retval;
2257         struct ext2_inode inode;
2258
2259         if (!(fs->super->s_feature_compat & EXT3_FEATURE_COMPAT_HAS_JOURNAL))
2260                 return 0;
2261
2262         /* External journal? Nothing to do. */
2263         if (fs->super->s_journal_dev && !fs->super->s_journal_inum)
2264                 return 0;
2265
2266         retval = ext2fs_read_inode(fs, fs->super->s_journal_inum, &inode);
2267         if (retval)
2268                 return retval;
2269         memcpy(fs->super->s_jnl_blocks, inode.i_block, EXT2_N_BLOCKS*4);
2270         fs->super->s_jnl_blocks[15] = inode.i_size_high;
2271         fs->super->s_jnl_blocks[16] = inode.i_size;
2272         fs->super->s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS;
2273         ext2fs_mark_super_dirty(fs);
2274         return 0;
2275 }
2276
2277 static int calc_group_overhead(ext2_filsys fs, blk64_t grp,
2278                                int old_desc_blocks)
2279 {
2280         blk64_t super_blk, old_desc_blk, new_desc_blk;
2281         int overhead;
2282
2283         /* inode table blocks plus allocation bitmaps */
2284         overhead = fs->inode_blocks_per_group + 2;
2285
2286         ext2fs_super_and_bgd_loc2(fs, grp, &super_blk,
2287                                   &old_desc_blk, &new_desc_blk, 0);
2288         if ((grp == 0) || super_blk)
2289                 overhead++;
2290         if (old_desc_blk)
2291                 overhead += old_desc_blocks;
2292         else if (new_desc_blk)
2293                 overhead++;
2294         return overhead;
2295 }
2296
2297
2298 /*
2299  * calcluate the minimum number of blocks the given fs can be resized to
2300  */
2301 blk64_t calculate_minimum_resize_size(ext2_filsys fs, int flags)
2302 {
2303         ext2_ino_t inode_count;
2304         dgrp_t groups, flex_groups;
2305         blk64_t blks_needed, data_blocks;
2306         blk64_t grp, data_needed, last_start;
2307         blk64_t overhead = 0;
2308         int old_desc_blocks;
2309         int flexbg_size = 1 << fs->super->s_log_groups_per_flex;
2310
2311         /*
2312          * first figure out how many group descriptors we need to
2313          * handle the number of inodes we have
2314          */
2315         inode_count = fs->super->s_inodes_count -
2316                 fs->super->s_free_inodes_count;
2317         blks_needed = ext2fs_div_ceil(inode_count,
2318                                       fs->super->s_inodes_per_group) *
2319                 EXT2_BLOCKS_PER_GROUP(fs->super);
2320         groups = ext2fs_div64_ceil(blks_needed,
2321                                    EXT2_BLOCKS_PER_GROUP(fs->super));
2322 #ifdef RESIZE2FS_DEBUG
2323         if (flags & RESIZE_DEBUG_MIN_CALC)
2324                 printf("fs has %d inodes, %d groups required.\n",
2325                        inode_count, groups);
2326 #endif
2327
2328         /*
2329          * number of old-style block group descriptor blocks
2330          */
2331         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG)
2332                 old_desc_blocks = fs->super->s_first_meta_bg;
2333         else
2334                 old_desc_blocks = fs->desc_blocks +
2335                         fs->super->s_reserved_gdt_blocks;
2336
2337         /* calculate how many blocks are needed for data */
2338         data_needed = ext2fs_blocks_count(fs->super) -
2339                 ext2fs_free_blocks_count(fs->super);
2340
2341         for (grp = 0; grp < fs->group_desc_count; grp++)
2342                 data_needed -= calc_group_overhead(fs, grp, old_desc_blocks);
2343 #ifdef RESIZE2FS_DEBUG
2344         if (flags & RESIZE_DEBUG_MIN_CALC)
2345                 printf("fs requires %llu data blocks.\n", data_needed);
2346 #endif
2347
2348         /*
2349          * For ext4 we need to allow for up to a flex_bg worth of
2350          * inode tables of slack space so the resize operation can be
2351          * guaranteed to finish.
2352          */
2353         flex_groups = groups;
2354         if (fs->super->s_feature_incompat & EXT4_FEATURE_INCOMPAT_FLEX_BG) {
2355                 dgrp_t remainder = groups & (flexbg_size - 1);
2356
2357                 flex_groups += flexbg_size - remainder;
2358                 if (flex_groups > fs->group_desc_count)
2359                         flex_groups = fs->group_desc_count;
2360         }
2361
2362         /*
2363          * figure out how many data blocks we have given the number of groups
2364          * we need for our inodes
2365          */
2366         data_blocks = groups * EXT2_BLOCKS_PER_GROUP(fs->super);
2367         last_start = 0;
2368         for (grp = 0; grp < flex_groups; grp++) {
2369                 overhead = calc_group_overhead(fs, grp, old_desc_blocks);
2370
2371                 /*
2372                  * we want to keep track of how much data we can store in
2373                  * the groups leading up to the last group so we can determine
2374                  * how big the last group needs to be
2375                  */
2376                 if (grp < (groups - 1))
2377                         last_start += EXT2_BLOCKS_PER_GROUP(fs->super) -
2378                                 overhead;
2379
2380                 if (data_blocks > overhead)
2381                         data_blocks -= overhead;
2382                 else
2383                         data_blocks = 0;
2384         }
2385 #ifdef RESIZE2FS_DEBUG
2386         if (flags & RESIZE_DEBUG_MIN_CALC)
2387                 printf("With %d group(s), we have %llu blocks available.\n",
2388                        groups, data_blocks);
2389 #endif
2390
2391         /*
2392          * if we need more group descriptors in order to accomodate our data
2393          * then we need to add them here
2394          */
2395         blks_needed = data_needed;
2396         while (blks_needed > data_blocks) {
2397                 blk64_t remainder = blks_needed - data_blocks;
2398                 dgrp_t extra_grps;
2399
2400                 /* figure out how many more groups we need for the data */
2401                 extra_grps = ext2fs_div64_ceil(remainder,
2402                                                EXT2_BLOCKS_PER_GROUP(fs->super));
2403
2404                 data_blocks += extra_grps * EXT2_BLOCKS_PER_GROUP(fs->super);
2405
2406                 /* ok we have to account for the last group */
2407                 overhead = calc_group_overhead(fs, groups-1, old_desc_blocks);
2408                 last_start += EXT2_BLOCKS_PER_GROUP(fs->super) - overhead;
2409
2410                 grp = flex_groups;
2411                 groups += extra_grps;
2412                 if (!(fs->super->s_feature_incompat &
2413                       EXT4_FEATURE_INCOMPAT_FLEX_BG))
2414                         flex_groups = groups;
2415                 else if (groups > flex_groups) {
2416                         dgrp_t r = groups & (flexbg_size - 1);
2417
2418                         flex_groups = groups + flexbg_size - r;
2419                         if (flex_groups > fs->group_desc_count)
2420                                 flex_groups = fs->group_desc_count;
2421                 }
2422
2423                 for (; grp < flex_groups; grp++) {
2424                         overhead = calc_group_overhead(fs, grp,
2425                                                        old_desc_blocks);
2426
2427                         /*
2428                          * again, we need to see how much data we cram into
2429                          * all of the groups leading up to the last group
2430                          */
2431                         if (grp < groups - 1)
2432                                 last_start += EXT2_BLOCKS_PER_GROUP(fs->super)
2433                                         - overhead;
2434
2435                         data_blocks -= overhead;
2436                 }
2437
2438 #ifdef RESIZE2FS_DEBUG
2439                 if (flags & RESIZE_DEBUG_MIN_CALC)
2440                         printf("Added %d extra group(s), "
2441                                "blks_needed %llu, data_blocks %llu, "
2442                                "last_start %llu\n", extra_grps, blks_needed,
2443                                data_blocks, last_start);
2444 #endif
2445         }
2446
2447         /* now for the fun voodoo */
2448         grp = groups - 1;
2449         if ((fs->super->s_feature_incompat & EXT4_FEATURE_INCOMPAT_FLEX_BG) &&
2450             (grp & ~(flexbg_size - 1)) == 0)
2451                 grp = grp & ~(flexbg_size - 1);
2452         overhead = 0;
2453         for (; grp < flex_groups; grp++)
2454                 overhead += calc_group_overhead(fs, grp, old_desc_blocks);
2455
2456 #ifdef RESIZE2FS_DEBUG
2457         if (flags & RESIZE_DEBUG_MIN_CALC)
2458                 printf("Last group's overhead is %llu\n", overhead);
2459 #endif
2460
2461         /*
2462          * if this is the case then the last group is going to have data in it
2463          * so we need to adjust the size of the last group accordingly
2464          */
2465         if (last_start < blks_needed) {
2466                 blk64_t remainder = blks_needed - last_start;
2467
2468 #ifdef RESIZE2FS_DEBUG
2469                 if (flags & RESIZE_DEBUG_MIN_CALC)
2470                         printf("Need %llu data blocks in last group\n",
2471                                remainder);
2472 #endif
2473                 /*
2474                  * 50 is a magic number that mkfs/resize uses to see if its
2475                  * even worth making/resizing the fs.  basically you need to
2476                  * have at least 50 blocks in addition to the blocks needed
2477                  * for the metadata in the last group
2478                  */
2479                 if (remainder > 50)
2480                         overhead += remainder;
2481                 else
2482                         overhead += 50;
2483         } else
2484                 overhead += 50;
2485
2486         overhead += fs->super->s_first_data_block;
2487 #ifdef RESIZE2FS_DEBUG
2488         if (flags & RESIZE_DEBUG_MIN_CALC)
2489                 printf("Final size of last group is %lld\n", overhead);
2490 #endif
2491
2492         /* Add extra slack for bigalloc file systems */
2493         if (EXT2FS_CLUSTER_RATIO(fs) > 1)
2494                 overhead += EXT2FS_CLUSTER_RATIO(fs) * 2;
2495
2496         /*
2497          * since our last group doesn't have to be BLOCKS_PER_GROUP
2498          * large, we only do groups-1, and then add the number of
2499          * blocks needed to handle the group descriptor metadata+data
2500          * that we need
2501          */
2502         blks_needed = (groups-1) * EXT2_BLOCKS_PER_GROUP(fs->super);
2503         blks_needed += overhead;
2504
2505         /*
2506          * Make sure blks_needed covers the end of the inode table in
2507          * the last block group.
2508          */
2509         overhead = ext2fs_inode_table_loc(fs, groups-1) +
2510                 fs->inode_blocks_per_group;
2511         if (blks_needed < overhead)
2512                 blks_needed = overhead;
2513
2514 #ifdef RESIZE2FS_DEBUG
2515         if (flags & RESIZE_DEBUG_MIN_CALC)
2516                 printf("Estimated blocks needed: %llu\n", blks_needed);
2517 #endif
2518
2519         /*
2520          * If at this point we've already added up more "needed" than
2521          * the current size, just return current size as minimum.
2522          */
2523         if (blks_needed >= ext2fs_blocks_count(fs->super))
2524                 return ext2fs_blocks_count(fs->super);
2525         /*
2526          * We need to reserve a few extra blocks if extents are
2527          * enabled, in case we need to grow the extent tree.  The more
2528          * we shrink the file system, the more space we need.
2529          *
2530          * The absolute worst case is every single data block is in
2531          * the part of the file system that needs to be evacuated,
2532          * with each data block needs to be in its own extent, and
2533          * with each inode needing at least one extent block.
2534          */
2535         if (fs->super->s_feature_incompat & EXT3_FEATURE_INCOMPAT_EXTENTS) {
2536                 blk64_t safe_margin = (ext2fs_blocks_count(fs->super) -
2537                                        blks_needed)/500;
2538                 unsigned int exts_per_blk = (fs->blocksize /
2539                                              sizeof(struct ext3_extent)) - 1;
2540                 blk64_t worst_case = ((data_needed + exts_per_blk - 1) /
2541                                       exts_per_blk);
2542
2543                 if (worst_case < inode_count)
2544                         worst_case = inode_count;
2545
2546                 if (safe_margin > worst_case)
2547                         safe_margin = worst_case;
2548
2549 #ifdef RESIZE2FS_DEBUG
2550                 if (flags & RESIZE_DEBUG_MIN_CALC)
2551                         printf("Extents safety margin: %llu\n", safe_margin);
2552 #endif
2553                 blks_needed += safe_margin;
2554         }
2555
2556         return blks_needed;
2557 }