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