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