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