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