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