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