Whamcloud - gitweb
resize2fs: reserve fs metadata blocks first in blocks_to_move()
[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         } else if (IS_INODE_BM(fs, group, blk)) {
749                 ext2fs_inode_bitmap_loc_set(fs, group, 0);
750                 rfs->needed_blocks++;
751         } else if (IS_INODE_TB(fs, group, blk)) {
752                 ext2fs_inode_table_loc_set(fs, group, 0);
753                 rfs->needed_blocks++;
754         } else if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
755                                               EXT4_FEATURE_RO_COMPAT_GDT_CSUM) &&
756                    (ext2fs_bg_flags_test(fs, group, EXT2_BG_BLOCK_UNINIT))) {
757                 /*
758                  * If the block bitmap is uninitialized, which means
759                  * nothing other than standard metadata in use.
760                  */
761                 return;
762         } else if (ext2fs_test_block_bitmap2(rfs->old_fs->block_map, blk) &&
763                    !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
764                 ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
765                 rfs->needed_blocks++;
766         }
767 }
768
769
770 /*
771  * This routine marks and unmarks reserved blocks in the new block
772  * bitmap.  It also determines which blocks need to be moved and
773  * places this information into the move_blocks bitmap.
774  */
775 static errcode_t blocks_to_move(ext2_resize_t rfs)
776 {
777         int             j, has_super;
778         dgrp_t          i, max_groups, g;
779         blk64_t         blk, group_blk;
780         blk64_t         old_blocks, new_blocks;
781         unsigned int    meta_bg, meta_bg_size;
782         errcode_t       retval;
783         ext2_filsys     fs, old_fs;
784         ext2fs_block_bitmap     meta_bmap;
785         __u32           save_incompat_flag;
786
787         fs = rfs->new_fs;
788         old_fs = rfs->old_fs;
789         if (ext2fs_blocks_count(old_fs->super) > ext2fs_blocks_count(fs->super))
790                 fs = rfs->old_fs;
791
792         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
793                                               &rfs->move_blocks);
794         if (retval)
795                 return retval;
796
797         retval = ext2fs_allocate_block_bitmap(fs, _("meta-data blocks"),
798                                               &meta_bmap);
799         if (retval)
800                 return retval;
801
802         retval = mark_table_blocks(old_fs, meta_bmap);
803         if (retval)
804                 return retval;
805
806         fs = rfs->new_fs;
807
808         /*
809          * If we're shrinking the filesystem, we need to move all of
810          * the blocks that don't fit any more
811          */
812         for (blk = ext2fs_blocks_count(fs->super);
813              blk < ext2fs_blocks_count(old_fs->super); blk++) {
814                 g = ext2fs_group_of_blk2(fs, blk);
815                 if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
816                                                EXT4_FEATURE_RO_COMPAT_GDT_CSUM) &&
817                     ext2fs_bg_flags_test(old_fs, g, EXT2_BG_BLOCK_UNINIT)) {
818                         /*
819                          * The block bitmap is uninitialized, so skip
820                          * to the next block group.
821                          */
822                         blk = ((g+1) * fs->super->s_blocks_per_group) +
823                                 fs->super->s_first_data_block - 1;
824                         continue;
825                 }
826                 if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
827                     !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
828                         ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
829                         rfs->needed_blocks++;
830                 }
831                 ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
832         }
833
834         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG) {
835                 old_blocks = old_fs->super->s_first_meta_bg;
836                 new_blocks = fs->super->s_first_meta_bg;
837         } else {
838                 old_blocks = old_fs->desc_blocks + old_fs->super->s_reserved_gdt_blocks;
839                 new_blocks = fs->desc_blocks + fs->super->s_reserved_gdt_blocks;
840         }
841
842         if (old_blocks == new_blocks) {
843                 retval = 0;
844                 goto errout;
845         }
846
847         max_groups = fs->group_desc_count;
848         if (max_groups > old_fs->group_desc_count)
849                 max_groups = old_fs->group_desc_count;
850         group_blk = old_fs->super->s_first_data_block;
851         /*
852          * If we're reducing the number of descriptor blocks, this
853          * makes life easy.  :-)   We just have to mark some extra
854          * blocks as free.
855          */
856         if (old_blocks > new_blocks) {
857                 for (i = 0; i < max_groups; i++) {
858                         if (!ext2fs_bg_has_super(fs, i)) {
859                                 group_blk += fs->super->s_blocks_per_group;
860                                 continue;
861                         }
862                         for (blk = group_blk+1+new_blocks;
863                              blk < group_blk+1+old_blocks; blk++) {
864                                 ext2fs_block_alloc_stats2(fs, blk, -1);
865                                 rfs->needed_blocks--;
866                         }
867                         group_blk += fs->super->s_blocks_per_group;
868                 }
869                 retval = 0;
870                 goto errout;
871         }
872         /*
873          * If we're increasing the number of descriptor blocks, life
874          * gets interesting....
875          */
876         meta_bg_size = EXT2_DESC_PER_BLOCK(fs->super);
877         /* first reserve all of the existing fs meta blocks */
878         for (i = 0; i < max_groups; i++) {
879                 has_super = ext2fs_bg_has_super(fs, i);
880                 if (has_super)
881                         mark_fs_metablock(rfs, meta_bmap, i, group_blk);
882
883                 meta_bg = i / meta_bg_size;
884                 if (!(fs->super->s_feature_incompat &
885                       EXT2_FEATURE_INCOMPAT_META_BG) ||
886                     (meta_bg < fs->super->s_first_meta_bg)) {
887                         if (has_super) {
888                                 for (blk = group_blk+1;
889                                      blk < group_blk + 1 + new_blocks; blk++)
890                                         mark_fs_metablock(rfs, meta_bmap,
891                                                           i, blk);
892                         }
893                 } else {
894                         if (has_super)
895                                 has_super = 1;
896                         if (((i % meta_bg_size) == 0) ||
897                             ((i % meta_bg_size) == 1) ||
898                             ((i % meta_bg_size) == (meta_bg_size-1)))
899                                 mark_fs_metablock(rfs, meta_bmap, i,
900                                                   group_blk + has_super);
901                 }
902
903                 /*
904                  * Reserve the existing meta blocks that we know
905                  * aren't to be moved.
906                  */
907                 if (ext2fs_block_bitmap_loc(fs, i))
908                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
909                                  ext2fs_block_bitmap_loc(fs, i));
910                 if (ext2fs_inode_bitmap_loc(fs, i))
911                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
912                                  ext2fs_inode_bitmap_loc(fs, i));
913                 if (ext2fs_inode_table_loc(fs, i))
914                         for (blk = ext2fs_inode_table_loc(fs, i), j=0;
915                              j < fs->inode_blocks_per_group ; j++, blk++)
916                                 ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
917                                                          blk);
918
919                 group_blk += rfs->new_fs->super->s_blocks_per_group;
920         }
921
922         /* Allocate the missing data structures */
923         for (i = 0; i < max_groups; i++) {
924                 if (ext2fs_inode_table_loc(fs, i) &&
925                     ext2fs_inode_bitmap_loc(fs, i) &&
926                     ext2fs_block_bitmap_loc(fs, i))
927                         continue;
928
929                 /*
930                  * XXX We have a problem with FLEX_BG and off-line
931                  * resizing where we are growing the size of the
932                  * filesystem.  ext2fs_allocate_group_table() will try
933                  * to reserve the inode table in the desired flex_bg
934                  * location.  However, passing rfs->reserve_blocks
935                  * doesn't work since it only has reserved the blocks
936                  * that will be used in the new block group -- and
937                  * with flex_bg, we can and will allocate the tables
938                  * outside of the block group.  And we can't pass in
939                  * the fs->block_map because it doesn't handle
940                  * overlapping inode table movements right.  So for
941                  * now, we temporarily disable flex_bg to force
942                  * ext2fs_allocate_group_tables() to allocate the bg
943                  * metadata in side the block group, and the restore
944                  * it afterwards.  Ugly, until we can fix this up
945                  * right later.
946                  */
947                 save_incompat_flag = fs->super->s_feature_incompat;
948                 fs->super->s_feature_incompat &= ~EXT4_FEATURE_INCOMPAT_FLEX_BG;
949                 retval = ext2fs_allocate_group_table(fs, i,
950                                                      rfs->reserve_blocks);
951                 fs->super->s_feature_incompat = save_incompat_flag;
952                 if (retval)
953                         goto errout;
954
955                 /*
956                  * For those structures that have changed, we need to
957                  * do bookkeepping.
958                  */
959                 if (ext2fs_block_bitmap_loc(old_fs, i) !=
960                     (blk = ext2fs_block_bitmap_loc(fs, i))) {
961                         ext2fs_block_alloc_stats2(fs, blk, +1);
962                         if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
963                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
964                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
965                                                          blk);
966                 }
967                 if (ext2fs_inode_bitmap_loc(old_fs, i) !=
968                     (blk = ext2fs_inode_bitmap_loc(fs, i))) {
969                         ext2fs_block_alloc_stats2(fs, blk, +1);
970                         if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
971                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
972                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
973                                                          blk);
974                 }
975
976                 /*
977                  * The inode table, if we need to relocate it, is
978                  * handled specially.  We have to reserve the blocks
979                  * for both the old and the new inode table, since we
980                  * can't have the inode table be destroyed during the
981                  * block relocation phase.
982                  */
983                 if (ext2fs_inode_table_loc(fs, i) == ext2fs_inode_table_loc(old_fs, i))
984                         continue;       /* inode table not moved */
985
986                 rfs->needed_blocks += fs->inode_blocks_per_group;
987
988                 /*
989                  * Mark the new inode table as in use in the new block
990                  * allocation bitmap, and move any blocks that might
991                  * be necessary.
992                  */
993                 for (blk = ext2fs_inode_table_loc(fs, i), j=0;
994                      j < fs->inode_blocks_per_group ; j++, blk++) {
995                         ext2fs_block_alloc_stats2(fs, blk, +1);
996                         if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
997                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
998                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
999                                                          blk);
1000                 }
1001
1002                 /*
1003                  * Make sure the old inode table is reserved in the
1004                  * block reservation bitmap.
1005                  */
1006                 for (blk = ext2fs_inode_table_loc(rfs->old_fs, i), j=0;
1007                      j < fs->inode_blocks_per_group ; j++, blk++)
1008                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
1009         }
1010         retval = 0;
1011
1012 errout:
1013         if (meta_bmap)
1014                 ext2fs_free_block_bitmap(meta_bmap);
1015
1016         return retval;
1017 }
1018
1019 /*
1020  * This helper function tries to allocate a new block.  We try to
1021  * avoid hitting the original group descriptor blocks at least at
1022  * first, since we want to make it possible to recover from a badly
1023  * aborted resize operation as much as possible.
1024  *
1025  * In the future, I may further modify this routine to balance out
1026  * where we get the new blocks across the various block groups.
1027  * Ideally we would allocate blocks that corresponded with the block
1028  * group of the containing inode, and keep contiguous blocks
1029  * together.  However, this very difficult to do efficiently, since we
1030  * don't have the necessary information up front.
1031  */
1032
1033 #define AVOID_OLD       1
1034 #define DESPERATION     2
1035
1036 static void init_block_alloc(ext2_resize_t rfs)
1037 {
1038         rfs->alloc_state = AVOID_OLD;
1039         rfs->new_blk = rfs->new_fs->super->s_first_data_block;
1040 #if 0
1041         /* HACK for testing */
1042         if (ext2fs_blocks_count(rfs->new_fs->super) >
1043             ext2fs_blocks_count(rfs->old_fs->super))
1044                 rfs->new_blk = ext2fs_blocks_count(rfs->old_fs->super);
1045 #endif
1046 }
1047
1048 static blk64_t get_new_block(ext2_resize_t rfs)
1049 {
1050         ext2_filsys     fs = rfs->new_fs;
1051
1052         while (1) {
1053                 if (rfs->new_blk >= ext2fs_blocks_count(fs->super)) {
1054                         if (rfs->alloc_state == DESPERATION)
1055                                 return 0;
1056
1057 #ifdef RESIZE2FS_DEBUG
1058                         if (rfs->flags & RESIZE_DEBUG_BMOVE)
1059                                 printf("Going into desperation mode "
1060                                        "for block allocations\n");
1061 #endif
1062                         rfs->alloc_state = DESPERATION;
1063                         rfs->new_blk = fs->super->s_first_data_block;
1064                         continue;
1065                 }
1066                 if (ext2fs_test_block_bitmap2(fs->block_map, rfs->new_blk) ||
1067                     ext2fs_test_block_bitmap2(rfs->reserve_blocks,
1068                                              rfs->new_blk) ||
1069                     ((rfs->alloc_state == AVOID_OLD) &&
1070                      (rfs->new_blk < ext2fs_blocks_count(rfs->old_fs->super)) &&
1071                      ext2fs_test_block_bitmap2(rfs->old_fs->block_map,
1072                                               rfs->new_blk))) {
1073                         rfs->new_blk++;
1074                         continue;
1075                 }
1076                 return rfs->new_blk;
1077         }
1078 }
1079
1080 static errcode_t resize2fs_get_alloc_block(ext2_filsys fs, blk64_t goal,
1081                                            blk64_t *ret)
1082 {
1083         ext2_resize_t rfs = (ext2_resize_t) fs->priv_data;
1084         blk64_t blk;
1085
1086         blk = get_new_block(rfs);
1087         if (!blk)
1088                 return ENOSPC;
1089
1090 #ifdef RESIZE2FS_DEBUG
1091         if (rfs->flags & 0xF)
1092                 printf("get_alloc_block allocating %llu\n", blk);
1093 #endif
1094
1095         ext2fs_mark_block_bitmap2(rfs->old_fs->block_map, blk);
1096         ext2fs_mark_block_bitmap2(rfs->new_fs->block_map, blk);
1097         *ret = (blk64_t) blk;
1098         return 0;
1099 }
1100
1101 static errcode_t block_mover(ext2_resize_t rfs)
1102 {
1103         blk64_t                 blk, old_blk, new_blk;
1104         ext2_filsys             fs = rfs->new_fs;
1105         ext2_filsys             old_fs = rfs->old_fs;
1106         errcode_t               retval;
1107         __u64                   size;
1108         int                     c;
1109         int                     to_move, moved;
1110         ext2_badblocks_list     badblock_list = 0;
1111         int                     bb_modified = 0;
1112
1113         fs->get_alloc_block = resize2fs_get_alloc_block;
1114         old_fs->get_alloc_block = resize2fs_get_alloc_block;
1115
1116         retval = ext2fs_read_bb_inode(old_fs, &badblock_list);
1117         if (retval)
1118                 return retval;
1119
1120         new_blk = fs->super->s_first_data_block;
1121         if (!rfs->itable_buf) {
1122                 retval = ext2fs_get_array(fs->blocksize,
1123                                         fs->inode_blocks_per_group,
1124                                         &rfs->itable_buf);
1125                 if (retval)
1126                         return retval;
1127         }
1128         retval = ext2fs_create_extent_table(&rfs->bmap, 0);
1129         if (retval)
1130                 return retval;
1131
1132         /*
1133          * The first step is to figure out where all of the blocks
1134          * will go.
1135          */
1136         to_move = moved = 0;
1137         init_block_alloc(rfs);
1138         for (blk = old_fs->super->s_first_data_block;
1139              blk < ext2fs_blocks_count(old_fs->super); blk++) {
1140                 if (!ext2fs_test_block_bitmap2(old_fs->block_map, blk))
1141                         continue;
1142                 if (!ext2fs_test_block_bitmap2(rfs->move_blocks, blk))
1143                         continue;
1144                 if (ext2fs_badblocks_list_test(badblock_list, blk)) {
1145                         ext2fs_badblocks_list_del(badblock_list, blk);
1146                         bb_modified++;
1147                         continue;
1148                 }
1149
1150                 new_blk = get_new_block(rfs);
1151                 if (!new_blk) {
1152                         retval = ENOSPC;
1153                         goto errout;
1154                 }
1155                 ext2fs_block_alloc_stats2(fs, new_blk, +1);
1156                 ext2fs_add_extent_entry(rfs->bmap, blk, new_blk);
1157                 to_move++;
1158         }
1159
1160         if (to_move == 0) {
1161                 if (rfs->bmap) {
1162                         ext2fs_free_extent_table(rfs->bmap);
1163                         rfs->bmap = 0;
1164                 }
1165                 retval = 0;
1166                 goto errout;
1167         }
1168
1169         /*
1170          * Step two is to actually move the blocks
1171          */
1172         retval =  ext2fs_iterate_extent(rfs->bmap, 0, 0, 0);
1173         if (retval) goto errout;
1174
1175         if (rfs->progress) {
1176                 retval = (rfs->progress)(rfs, E2_RSZ_BLOCK_RELOC_PASS,
1177                                          0, to_move);
1178                 if (retval)
1179                         goto errout;
1180         }
1181         while (1) {
1182                 retval = ext2fs_iterate_extent(rfs->bmap, &old_blk, &new_blk, &size);
1183                 if (retval) goto errout;
1184                 if (!size)
1185                         break;
1186 #ifdef RESIZE2FS_DEBUG
1187                 if (rfs->flags & RESIZE_DEBUG_BMOVE)
1188                         printf("Moving %llu blocks %llu->%llu\n",
1189                                size, old_blk, new_blk);
1190 #endif
1191                 do {
1192                         c = size;
1193                         if (c > fs->inode_blocks_per_group)
1194                                 c = fs->inode_blocks_per_group;
1195                         retval = io_channel_read_blk64(fs->io, old_blk, c,
1196                                                        rfs->itable_buf);
1197                         if (retval) goto errout;
1198                         retval = io_channel_write_blk64(fs->io, new_blk, c,
1199                                                         rfs->itable_buf);
1200                         if (retval) goto errout;
1201                         size -= c;
1202                         new_blk += c;
1203                         old_blk += c;
1204                         moved += c;
1205                         if (rfs->progress) {
1206                                 io_channel_flush(fs->io);
1207                                 retval = (rfs->progress)(rfs,
1208                                                 E2_RSZ_BLOCK_RELOC_PASS,
1209                                                 moved, to_move);
1210                                 if (retval)
1211                                         goto errout;
1212                         }
1213                 } while (size > 0);
1214                 io_channel_flush(fs->io);
1215         }
1216
1217 errout:
1218         if (badblock_list) {
1219                 if (!retval && bb_modified)
1220                         retval = ext2fs_update_bb_inode(old_fs,
1221                                                         badblock_list);
1222                 ext2fs_badblocks_list_free(badblock_list);
1223         }
1224         return retval;
1225 }
1226
1227
1228 /* --------------------------------------------------------------------
1229  *
1230  * Resize processing, phase 3
1231  *
1232  * --------------------------------------------------------------------
1233  */
1234
1235
1236 struct process_block_struct {
1237         ext2_resize_t           rfs;
1238         ext2_ino_t              ino;
1239         struct ext2_inode *     inode;
1240         errcode_t               error;
1241         int                     is_dir;
1242         int                     changed;
1243 };
1244
1245 static int process_block(ext2_filsys fs, blk64_t        *block_nr,
1246                          e2_blkcnt_t blockcnt,
1247                          blk64_t ref_block EXT2FS_ATTR((unused)),
1248                          int ref_offset EXT2FS_ATTR((unused)), void *priv_data)
1249 {
1250         struct process_block_struct *pb;
1251         errcode_t       retval;
1252         blk64_t         block, new_block;
1253         int             ret = 0;
1254
1255         pb = (struct process_block_struct *) priv_data;
1256         block = *block_nr;
1257         if (pb->rfs->bmap) {
1258                 new_block = ext2fs_extent_translate(pb->rfs->bmap, block);
1259                 if (new_block) {
1260                         *block_nr = new_block;
1261                         ret |= BLOCK_CHANGED;
1262                         pb->changed = 1;
1263 #ifdef RESIZE2FS_DEBUG
1264                         if (pb->rfs->flags & RESIZE_DEBUG_BMOVE)
1265                                 printf("ino=%u, blockcnt=%lld, %llu->%llu\n",
1266                                        pb->ino, blockcnt, block, new_block);
1267 #endif
1268                         block = new_block;
1269                 }
1270         }
1271         if (pb->is_dir) {
1272                 retval = ext2fs_add_dir_block2(fs->dblist, pb->ino,
1273                                                block, (int) blockcnt);
1274                 if (retval) {
1275                         pb->error = retval;
1276                         ret |= BLOCK_ABORT;
1277                 }
1278         }
1279         return ret;
1280 }
1281
1282 /*
1283  * Progress callback
1284  */
1285 static errcode_t progress_callback(ext2_filsys fs,
1286                                    ext2_inode_scan scan EXT2FS_ATTR((unused)),
1287                                    dgrp_t group, void * priv_data)
1288 {
1289         ext2_resize_t rfs = (ext2_resize_t) priv_data;
1290         errcode_t               retval;
1291
1292         /*
1293          * This check is to protect against old ext2 libraries.  It
1294          * shouldn't be needed against new libraries.
1295          */
1296         if ((group+1) == 0)
1297                 return 0;
1298
1299         if (rfs->progress) {
1300                 io_channel_flush(fs->io);
1301                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_SCAN_PASS,
1302                                          group+1, fs->group_desc_count);
1303                 if (retval)
1304                         return retval;
1305         }
1306
1307         return 0;
1308 }
1309
1310 static errcode_t inode_scan_and_fix(ext2_resize_t rfs)
1311 {
1312         struct process_block_struct     pb;
1313         ext2_ino_t              ino, new_inode;
1314         struct ext2_inode       *inode = NULL;
1315         ext2_inode_scan         scan = NULL;
1316         errcode_t               retval;
1317         char                    *block_buf = 0;
1318         ext2_ino_t              start_to_move;
1319         blk64_t                 orig_size;
1320         blk64_t                 new_block;
1321         int                     inode_size;
1322
1323         if ((rfs->old_fs->group_desc_count <=
1324              rfs->new_fs->group_desc_count) &&
1325             !rfs->bmap)
1326                 return 0;
1327
1328         /*
1329          * Save the original size of the old filesystem, and
1330          * temporarily set the size to be the new size if the new size
1331          * is larger.  We need to do this to avoid catching an error
1332          * by the block iterator routines
1333          */
1334         orig_size = ext2fs_blocks_count(rfs->old_fs->super);
1335         if (orig_size < ext2fs_blocks_count(rfs->new_fs->super))
1336                 ext2fs_blocks_count_set(rfs->old_fs->super,
1337                                 ext2fs_blocks_count(rfs->new_fs->super));
1338
1339         retval = ext2fs_open_inode_scan(rfs->old_fs, 0, &scan);
1340         if (retval) goto errout;
1341
1342         retval = ext2fs_init_dblist(rfs->old_fs, 0);
1343         if (retval) goto errout;
1344         retval = ext2fs_get_array(rfs->old_fs->blocksize, 3, &block_buf);
1345         if (retval) goto errout;
1346
1347         start_to_move = (rfs->new_fs->group_desc_count *
1348                          rfs->new_fs->super->s_inodes_per_group);
1349
1350         if (rfs->progress) {
1351                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_SCAN_PASS,
1352                                          0, rfs->old_fs->group_desc_count);
1353                 if (retval)
1354                         goto errout;
1355         }
1356         ext2fs_set_inode_callback(scan, progress_callback, (void *) rfs);
1357         pb.rfs = rfs;
1358         pb.inode = inode;
1359         pb.error = 0;
1360         new_inode = EXT2_FIRST_INODE(rfs->new_fs->super);
1361         inode_size = EXT2_INODE_SIZE(rfs->new_fs->super);
1362         inode = malloc(inode_size);
1363         if (!inode) {
1364                 retval = ENOMEM;
1365                 goto errout;
1366         }
1367         /*
1368          * First, copy all of the inodes that need to be moved
1369          * elsewhere in the inode table
1370          */
1371         while (1) {
1372                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, inode_size);
1373                 if (retval) goto errout;
1374                 if (!ino)
1375                         break;
1376
1377                 if (inode->i_links_count == 0 && ino != EXT2_RESIZE_INO)
1378                         continue; /* inode not in use */
1379
1380                 pb.is_dir = LINUX_S_ISDIR(inode->i_mode);
1381                 pb.changed = 0;
1382
1383                 if (ext2fs_file_acl_block(rfs->old_fs, inode) && rfs->bmap) {
1384                         new_block = ext2fs_extent_translate(rfs->bmap,
1385                                 ext2fs_file_acl_block(rfs->old_fs, inode));
1386                         if (new_block) {
1387                                 ext2fs_file_acl_block_set(rfs->old_fs, inode,
1388                                                           new_block);
1389                                 retval = ext2fs_write_inode_full(rfs->old_fs,
1390                                                             ino, inode, inode_size);
1391                                 if (retval) goto errout;
1392                         }
1393                 }
1394
1395                 if (ext2fs_inode_has_valid_blocks2(rfs->old_fs, inode) &&
1396                     (rfs->bmap || pb.is_dir)) {
1397                         pb.ino = ino;
1398                         retval = ext2fs_block_iterate3(rfs->old_fs,
1399                                                        ino, 0, block_buf,
1400                                                        process_block, &pb);
1401                         if (retval)
1402                                 goto errout;
1403                         if (pb.error) {
1404                                 retval = pb.error;
1405                                 goto errout;
1406                         }
1407                 }
1408
1409                 if (ino <= start_to_move)
1410                         continue; /* Don't need to move it. */
1411
1412                 /*
1413                  * Find a new inode
1414                  */
1415                 retval = ext2fs_new_inode(rfs->new_fs, 0, 0, 0, &new_inode);
1416                 if (retval)
1417                         goto errout;
1418
1419                 ext2fs_inode_alloc_stats2(rfs->new_fs, new_inode, +1,
1420                                           pb.is_dir);
1421                 if (pb.changed) {
1422                         /* Get the new version of the inode */
1423                         retval = ext2fs_read_inode_full(rfs->old_fs, ino,
1424                                                 inode, inode_size);
1425                         if (retval) goto errout;
1426                 }
1427                 inode->i_ctime = time(0);
1428                 retval = ext2fs_write_inode_full(rfs->old_fs, new_inode,
1429                                                 inode, inode_size);
1430                 if (retval) goto errout;
1431
1432 #ifdef RESIZE2FS_DEBUG
1433                 if (rfs->flags & RESIZE_DEBUG_INODEMAP)
1434                         printf("Inode moved %u->%u\n", ino, new_inode);
1435 #endif
1436                 if (!rfs->imap) {
1437                         retval = ext2fs_create_extent_table(&rfs->imap, 0);
1438                         if (retval)
1439                                 goto errout;
1440                 }
1441                 ext2fs_add_extent_entry(rfs->imap, ino, new_inode);
1442         }
1443         io_channel_flush(rfs->old_fs->io);
1444
1445 errout:
1446         ext2fs_blocks_count_set(rfs->old_fs->super, orig_size);
1447         if (rfs->bmap) {
1448                 ext2fs_free_extent_table(rfs->bmap);
1449                 rfs->bmap = 0;
1450         }
1451         if (scan)
1452                 ext2fs_close_inode_scan(scan);
1453         if (block_buf)
1454                 ext2fs_free_mem(&block_buf);
1455         free(inode);
1456         return retval;
1457 }
1458
1459 /* --------------------------------------------------------------------
1460  *
1461  * Resize processing, phase 4.
1462  *
1463  * --------------------------------------------------------------------
1464  */
1465
1466 struct istruct {
1467         ext2_resize_t rfs;
1468         errcode_t       err;
1469         unsigned int    max_dirs;
1470         unsigned int    num;
1471 };
1472
1473 static int check_and_change_inodes(ext2_ino_t dir,
1474                                    int entry EXT2FS_ATTR((unused)),
1475                                    struct ext2_dir_entry *dirent, int offset,
1476                                    int  blocksize EXT2FS_ATTR((unused)),
1477                                    char *buf EXT2FS_ATTR((unused)),
1478                                    void *priv_data)
1479 {
1480         struct istruct *is = (struct istruct *) priv_data;
1481         struct ext2_inode       inode;
1482         ext2_ino_t              new_inode;
1483         errcode_t               retval;
1484
1485         if (is->rfs->progress && offset == 0) {
1486                 io_channel_flush(is->rfs->old_fs->io);
1487                 is->err = (is->rfs->progress)(is->rfs,
1488                                               E2_RSZ_INODE_REF_UPD_PASS,
1489                                               ++is->num, is->max_dirs);
1490                 if (is->err)
1491                         return DIRENT_ABORT;
1492         }
1493
1494         if (!dirent->inode)
1495                 return 0;
1496
1497         new_inode = ext2fs_extent_translate(is->rfs->imap, dirent->inode);
1498
1499         if (!new_inode)
1500                 return 0;
1501 #ifdef RESIZE2FS_DEBUG
1502         if (is->rfs->flags & RESIZE_DEBUG_INODEMAP)
1503                 printf("Inode translate (dir=%u, name=%.*s, %u->%u)\n",
1504                        dir, dirent->name_len&0xFF, dirent->name,
1505                        dirent->inode, new_inode);
1506 #endif
1507
1508         dirent->inode = new_inode;
1509
1510         /* Update the directory mtime and ctime */
1511         retval = ext2fs_read_inode(is->rfs->old_fs, dir, &inode);
1512         if (retval == 0) {
1513                 inode.i_mtime = inode.i_ctime = time(0);
1514                 is->err = ext2fs_write_inode(is->rfs->old_fs, dir, &inode);
1515                 if (is->err)
1516                         return DIRENT_ABORT;
1517         }
1518
1519         return DIRENT_CHANGED;
1520 }
1521
1522 static errcode_t inode_ref_fix(ext2_resize_t rfs)
1523 {
1524         errcode_t               retval;
1525         struct istruct          is;
1526
1527         if (!rfs->imap)
1528                 return 0;
1529
1530         /*
1531          * Now, we iterate over all of the directories to update the
1532          * inode references
1533          */
1534         is.num = 0;
1535         is.max_dirs = ext2fs_dblist_count2(rfs->old_fs->dblist);
1536         is.rfs = rfs;
1537         is.err = 0;
1538
1539         if (rfs->progress) {
1540                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_REF_UPD_PASS,
1541                                          0, is.max_dirs);
1542                 if (retval)
1543                         goto errout;
1544         }
1545
1546         retval = ext2fs_dblist_dir_iterate(rfs->old_fs->dblist,
1547                                            DIRENT_FLAG_INCLUDE_EMPTY, 0,
1548                                            check_and_change_inodes, &is);
1549         if (retval)
1550                 goto errout;
1551         if (is.err) {
1552                 retval = is.err;
1553                 goto errout;
1554         }
1555
1556         if (rfs->progress && (is.num < is.max_dirs))
1557                 (rfs->progress)(rfs, E2_RSZ_INODE_REF_UPD_PASS,
1558                                 is.max_dirs, is.max_dirs);
1559
1560 errout:
1561         ext2fs_free_extent_table(rfs->imap);
1562         rfs->imap = 0;
1563         return retval;
1564 }
1565
1566
1567 /* --------------------------------------------------------------------
1568  *
1569  * Resize processing, phase 5.
1570  *
1571  * In this phase we actually move the inode table around, and then
1572  * update the summary statistics.  This is scary, since aborting here
1573  * will potentially scramble the filesystem.  (We are moving the
1574  * inode tables around in place, and so the potential for lost data,
1575  * or at the very least scrambling the mapping between filenames and
1576  * inode numbers is very high in case of a power failure here.)
1577  * --------------------------------------------------------------------
1578  */
1579
1580
1581 /*
1582  * A very scary routine --- this one moves the inode table around!!!
1583  *
1584  * After this you have to use the rfs->new_fs file handle to read and
1585  * write inodes.
1586  */
1587 static errcode_t move_itables(ext2_resize_t rfs)
1588 {
1589         int             n, num, size;
1590         long long       diff;
1591         dgrp_t          i, max_groups;
1592         ext2_filsys     fs = rfs->new_fs;
1593         char            *cp;
1594         blk64_t         old_blk, new_blk, blk;
1595         errcode_t       retval;
1596         int             j, to_move, moved;
1597
1598         max_groups = fs->group_desc_count;
1599         if (max_groups > rfs->old_fs->group_desc_count)
1600                 max_groups = rfs->old_fs->group_desc_count;
1601
1602         size = fs->blocksize * fs->inode_blocks_per_group;
1603         if (!rfs->itable_buf) {
1604                 retval = ext2fs_get_mem(size, &rfs->itable_buf);
1605                 if (retval)
1606                         return retval;
1607         }
1608
1609         /*
1610          * Figure out how many inode tables we need to move
1611          */
1612         to_move = moved = 0;
1613         for (i=0; i < max_groups; i++)
1614                 if (ext2fs_inode_table_loc(rfs->old_fs, i) !=
1615                     ext2fs_inode_table_loc(fs, i))
1616                         to_move++;
1617
1618         if (to_move == 0)
1619                 return 0;
1620
1621         if (rfs->progress) {
1622                 retval = rfs->progress(rfs, E2_RSZ_MOVE_ITABLE_PASS,
1623                                        0, to_move);
1624                 if (retval)
1625                         goto errout;
1626         }
1627
1628         rfs->old_fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1629
1630         for (i=0; i < max_groups; i++) {
1631                 old_blk = ext2fs_inode_table_loc(rfs->old_fs, i);
1632                 new_blk = ext2fs_inode_table_loc(fs, i);
1633                 diff = new_blk - old_blk;
1634
1635 #ifdef RESIZE2FS_DEBUG
1636                 if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
1637                         printf("Itable move group %d block %llu->%llu (diff %lld)\n",
1638                                i, old_blk, new_blk, diff);
1639 #endif
1640
1641                 if (!diff)
1642                         continue;
1643
1644                 retval = io_channel_read_blk64(fs->io, old_blk,
1645                                                fs->inode_blocks_per_group,
1646                                                rfs->itable_buf);
1647                 if (retval)
1648                         goto errout;
1649                 /*
1650                  * The end of the inode table segment often contains
1651                  * all zeros, and we're often only moving the inode
1652                  * table down a block or two.  If so, we can optimize
1653                  * things by not rewriting blocks that we know to be zero
1654                  * already.
1655                  */
1656                 for (cp = rfs->itable_buf+size-1, n=0; n < size; n++, cp--)
1657                         if (*cp)
1658                                 break;
1659                 n = n >> EXT2_BLOCK_SIZE_BITS(fs->super);
1660 #ifdef RESIZE2FS_DEBUG
1661                 if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
1662                         printf("%d blocks of zeros...\n", n);
1663 #endif
1664                 num = fs->inode_blocks_per_group;
1665                 if (n > diff)
1666                         num -= n;
1667
1668                 retval = io_channel_write_blk64(fs->io, new_blk,
1669                                                 num, rfs->itable_buf);
1670                 if (retval) {
1671                         io_channel_write_blk64(fs->io, old_blk,
1672                                                num, rfs->itable_buf);
1673                         goto errout;
1674                 }
1675                 if (n > diff) {
1676                         retval = io_channel_write_blk64(fs->io,
1677                               old_blk + fs->inode_blocks_per_group,
1678                               diff, (rfs->itable_buf +
1679                                      (fs->inode_blocks_per_group - diff) *
1680                                      fs->blocksize));
1681                         if (retval)
1682                                 goto errout;
1683                 }
1684
1685                 for (blk = ext2fs_inode_table_loc(rfs->old_fs, i), j=0;
1686                      j < fs->inode_blocks_per_group ; j++, blk++)
1687                         ext2fs_block_alloc_stats2(fs, blk, -1);
1688
1689                 ext2fs_inode_table_loc_set(rfs->old_fs, i, new_blk);
1690                 ext2fs_group_desc_csum_set(rfs->old_fs, i);
1691                 ext2fs_mark_super_dirty(rfs->old_fs);
1692                 ext2fs_flush(rfs->old_fs);
1693
1694                 if (rfs->progress) {
1695                         retval = rfs->progress(rfs, E2_RSZ_MOVE_ITABLE_PASS,
1696                                                ++moved, to_move);
1697                         if (retval)
1698                                 goto errout;
1699                 }
1700         }
1701         mark_table_blocks(fs, fs->block_map);
1702         ext2fs_flush(fs);
1703 #ifdef RESIZE2FS_DEBUG
1704         if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
1705                 printf("Inode table move finished.\n");
1706 #endif
1707         return 0;
1708
1709 errout:
1710         return retval;
1711 }
1712
1713 /*
1714  * Fix the resize inode
1715  */
1716 static errcode_t fix_resize_inode(ext2_filsys fs)
1717 {
1718         struct ext2_inode       inode;
1719         errcode_t               retval;
1720         char                    *block_buf = NULL;
1721
1722         if (!(fs->super->s_feature_compat &
1723               EXT2_FEATURE_COMPAT_RESIZE_INODE))
1724                 return 0;
1725
1726         retval = ext2fs_get_mem(fs->blocksize, &block_buf);
1727         if (retval) goto errout;
1728
1729         retval = ext2fs_read_inode(fs, EXT2_RESIZE_INO, &inode);
1730         if (retval) goto errout;
1731
1732         ext2fs_iblk_set(fs, &inode, 1);
1733
1734         retval = ext2fs_write_inode(fs, EXT2_RESIZE_INO, &inode);
1735         if (retval) goto errout;
1736
1737         if (!inode.i_block[EXT2_DIND_BLOCK]) {
1738                 /*
1739                  * Avoid zeroing out block #0; that's rude.  This
1740                  * should never happen anyway since the filesystem
1741                  * should be fsck'ed and we assume it is consistent.
1742                  */
1743                 fprintf(stderr,
1744                         _("Should never happen: resize inode corrupt!\n"));
1745                 exit(1);
1746         }
1747
1748         memset(block_buf, 0, fs->blocksize);
1749
1750         retval = io_channel_write_blk64(fs->io, inode.i_block[EXT2_DIND_BLOCK],
1751                                         1, block_buf);
1752         if (retval) goto errout;
1753
1754         retval = ext2fs_create_resize_inode(fs);
1755         if (retval)
1756                 goto errout;
1757
1758 errout:
1759         if (block_buf)
1760                 ext2fs_free_mem(&block_buf);
1761         return retval;
1762 }
1763
1764 /*
1765  * Finally, recalculate the summary information
1766  */
1767 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
1768 {
1769         blk64_t         blk;
1770         ext2_ino_t      ino;
1771         unsigned int    group = 0;
1772         unsigned int    count = 0;
1773         int             total_free = 0;
1774         int             group_free = 0;
1775         int             uninit = 0;
1776         blk64_t         super_blk, old_desc_blk, new_desc_blk;
1777         int             old_desc_blocks;
1778
1779         /*
1780          * First calculate the block statistics
1781          */
1782         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_BLOCK_UNINIT);
1783         ext2fs_super_and_bgd_loc2(fs, group, &super_blk, &old_desc_blk,
1784                                   &new_desc_blk, 0);
1785         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG)
1786                 old_desc_blocks = fs->super->s_first_meta_bg;
1787         else
1788                 old_desc_blocks = fs->desc_blocks +
1789                         fs->super->s_reserved_gdt_blocks;
1790         for (blk = fs->super->s_first_data_block;
1791              blk < ext2fs_blocks_count(fs->super); blk++) {
1792                 if ((uninit &&
1793                      !((blk == super_blk) ||
1794                        ((old_desc_blk && old_desc_blocks &&
1795                          (blk >= old_desc_blk) &&
1796                          (blk < old_desc_blk + old_desc_blocks))) ||
1797                        ((new_desc_blk && (blk == new_desc_blk))) ||
1798                        (blk == ext2fs_block_bitmap_loc(fs, group)) ||
1799                        (blk == ext2fs_inode_bitmap_loc(fs, group)) ||
1800                        ((blk >= ext2fs_inode_table_loc(fs, group) &&
1801                          (blk < ext2fs_inode_table_loc(fs, group)
1802                           + fs->inode_blocks_per_group))))) ||
1803                     (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk))) {
1804                         group_free++;
1805                         total_free++;
1806                 }
1807                 count++;
1808                 if ((count == fs->super->s_blocks_per_group) ||
1809                     (blk == ext2fs_blocks_count(fs->super)-1)) {
1810                         ext2fs_bg_free_blocks_count_set(fs, group, group_free);
1811                         ext2fs_group_desc_csum_set(fs, group);
1812                         group++;
1813                         if (group >= fs->group_desc_count)
1814                                 break;
1815                         count = 0;
1816                         group_free = 0;
1817                         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_BLOCK_UNINIT);
1818                         ext2fs_super_and_bgd_loc2(fs, group, &super_blk,
1819                                                   &old_desc_blk,
1820                                                   &new_desc_blk, 0);
1821                         if (fs->super->s_feature_incompat &
1822                             EXT2_FEATURE_INCOMPAT_META_BG)
1823                                 old_desc_blocks = fs->super->s_first_meta_bg;
1824                         else
1825                                 old_desc_blocks = fs->desc_blocks +
1826                                         fs->super->s_reserved_gdt_blocks;
1827                 }
1828         }
1829         ext2fs_free_blocks_count_set(fs->super, total_free);
1830
1831         /*
1832          * Next, calculate the inode statistics
1833          */
1834         group_free = 0;
1835         total_free = 0;
1836         count = 0;
1837         group = 0;
1838
1839         /* Protect loop from wrap-around if s_inodes_count maxed */
1840         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT);
1841         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
1842                 if (uninit ||
1843                     !ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
1844                         group_free++;
1845                         total_free++;
1846                 }
1847                 count++;
1848                 if ((count == fs->super->s_inodes_per_group) ||
1849                     (ino == fs->super->s_inodes_count)) {
1850                         ext2fs_bg_free_inodes_count_set(fs, group, group_free);
1851                         ext2fs_group_desc_csum_set(fs, group);
1852                         group++;
1853                         if (group >= fs->group_desc_count)
1854                                 break;
1855                         count = 0;
1856                         group_free = 0;
1857                         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT);
1858                 }
1859         }
1860         fs->super->s_free_inodes_count = total_free;
1861         ext2fs_mark_super_dirty(fs);
1862         return 0;
1863 }
1864
1865 /*
1866  *  Journal may have been relocated; update the backup journal blocks
1867  *  in the superblock.
1868  */
1869 static errcode_t fix_sb_journal_backup(ext2_filsys fs)
1870 {
1871         errcode_t         retval;
1872         struct ext2_inode inode;
1873
1874         if (!(fs->super->s_feature_compat & EXT3_FEATURE_COMPAT_HAS_JOURNAL))
1875                 return 0;
1876
1877         /* External journal? Nothing to do. */
1878         if (fs->super->s_journal_dev && !fs->super->s_journal_inum)
1879                 return 0;
1880
1881         retval = ext2fs_read_inode(fs, fs->super->s_journal_inum, &inode);
1882         if (retval)
1883                 return retval;
1884         memcpy(fs->super->s_jnl_blocks, inode.i_block, EXT2_N_BLOCKS*4);
1885         fs->super->s_jnl_blocks[15] = inode.i_size_high;
1886         fs->super->s_jnl_blocks[16] = inode.i_size;
1887         fs->super->s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS;
1888         ext2fs_mark_super_dirty(fs);
1889         return 0;
1890 }
1891
1892 static int calc_group_overhead(ext2_filsys fs, blk64_t grp,
1893                                int old_desc_blocks)
1894 {
1895         blk64_t super_blk, old_desc_blk, new_desc_blk;
1896         int overhead;
1897
1898         /* inode table blocks plus allocation bitmaps */
1899         overhead = fs->inode_blocks_per_group + 2;
1900
1901         ext2fs_super_and_bgd_loc2(fs, grp, &super_blk,
1902                                   &old_desc_blk, &new_desc_blk, 0);
1903         if ((grp == 0) || super_blk)
1904                 overhead++;
1905         if (old_desc_blk)
1906                 overhead += old_desc_blocks;
1907         else if (new_desc_blk)
1908                 overhead++;
1909         return overhead;
1910 }
1911
1912
1913 /*
1914  * calcluate the minimum number of blocks the given fs can be resized to
1915  */
1916 blk64_t calculate_minimum_resize_size(ext2_filsys fs)
1917 {
1918         ext2_ino_t inode_count;
1919         blk64_t blks_needed, groups, data_blocks;
1920         blk64_t grp, data_needed, last_start;
1921         blk64_t overhead = 0;
1922         int old_desc_blocks;
1923         int extra_groups = 0;
1924         int flexbg_size = 1 << fs->super->s_log_groups_per_flex;
1925
1926         /*
1927          * first figure out how many group descriptors we need to
1928          * handle the number of inodes we have
1929          */
1930         inode_count = fs->super->s_inodes_count -
1931                 fs->super->s_free_inodes_count;
1932         blks_needed = ext2fs_div_ceil(inode_count,
1933                                       fs->super->s_inodes_per_group) *
1934                 EXT2_BLOCKS_PER_GROUP(fs->super);
1935         groups = ext2fs_div64_ceil(blks_needed,
1936                                    EXT2_BLOCKS_PER_GROUP(fs->super));
1937
1938         /*
1939          * number of old-style block group descriptor blocks
1940          */
1941         if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG)
1942                 old_desc_blocks = fs->super->s_first_meta_bg;
1943         else
1944                 old_desc_blocks = fs->desc_blocks +
1945                         fs->super->s_reserved_gdt_blocks;
1946
1947         /* calculate how many blocks are needed for data */
1948         data_needed = ext2fs_blocks_count(fs->super) -
1949                 ext2fs_free_blocks_count(fs->super);
1950
1951         for (grp = 0; grp < fs->group_desc_count; grp++)
1952                 data_needed -= calc_group_overhead(fs, grp, old_desc_blocks);
1953
1954         /*
1955          * For ext4 we need to allow for up to a flex_bg worth of
1956          * inode tables of slack space so the resize operation can be
1957          * guaranteed to finish.
1958          */
1959         if (fs->super->s_feature_incompat & EXT4_FEATURE_INCOMPAT_FLEX_BG) {
1960                 extra_groups = flexbg_size - (groups & (flexbg_size - 1));
1961                 data_needed += fs->inode_blocks_per_group * extra_groups;
1962                 extra_groups = groups % flexbg_size;
1963         }
1964
1965         /*
1966          * figure out how many data blocks we have given the number of groups
1967          * we need for our inodes
1968          */
1969         data_blocks = groups * EXT2_BLOCKS_PER_GROUP(fs->super);
1970         last_start = 0;
1971         for (grp = 0; grp < groups; grp++) {
1972                 overhead = calc_group_overhead(fs, grp, old_desc_blocks);
1973
1974                 /*
1975                  * we want to keep track of how much data we can store in
1976                  * the groups leading up to the last group so we can determine
1977                  * how big the last group needs to be
1978                  */
1979                 if (grp != (groups - 1))
1980                         last_start += EXT2_BLOCKS_PER_GROUP(fs->super) -
1981                                 overhead;
1982
1983                 data_blocks -= overhead;
1984         }
1985
1986         /*
1987          * if we need more group descriptors in order to accomodate our data
1988          * then we need to add them here
1989          */
1990         while (data_needed > data_blocks) {
1991                 blk64_t remainder = data_needed - data_blocks;
1992                 blk64_t extra_grps;
1993
1994                 /* figure out how many more groups we need for the data */
1995                 extra_grps = ext2fs_div64_ceil(remainder,
1996                                                EXT2_BLOCKS_PER_GROUP(fs->super));
1997
1998                 data_blocks += extra_grps * EXT2_BLOCKS_PER_GROUP(fs->super);
1999
2000                 /* ok we have to account for the last group */
2001                 overhead = calc_group_overhead(fs, groups-1, old_desc_blocks);
2002                 last_start += EXT2_BLOCKS_PER_GROUP(fs->super) - overhead;
2003
2004                 for (grp = groups; grp < groups+extra_grps; grp++) {
2005                         overhead = calc_group_overhead(fs, grp,
2006                                                        old_desc_blocks);
2007
2008                         /*
2009                          * again, we need to see how much data we cram into
2010                          * all of the groups leading up to the last group
2011                          */
2012                         if (grp != (groups + extra_grps - 1))
2013                                 last_start += EXT2_BLOCKS_PER_GROUP(fs->super)
2014                                         - overhead;
2015
2016                         data_blocks -= overhead;
2017                 }
2018
2019                 groups += extra_grps;
2020                 extra_groups += extra_grps;
2021                 if (fs->super->s_feature_incompat
2022                         & EXT4_FEATURE_INCOMPAT_FLEX_BG
2023                     && extra_groups > flexbg_size) {
2024                         /*
2025                          * For ext4 we need to allow for up to a flex_bg worth
2026                          * of inode tables of slack space so the resize
2027                          * operation can be guaranteed to finish.
2028                          */
2029                         extra_groups = flexbg_size -
2030                                                 (groups & (flexbg_size - 1));
2031                         data_needed += (fs->inode_blocks_per_group *
2032                                         extra_groups);
2033                         extra_groups = groups % flexbg_size;
2034                 }
2035         }
2036
2037         /* now for the fun voodoo */
2038         overhead = calc_group_overhead(fs, groups-1, old_desc_blocks);
2039
2040         /*
2041          * if this is the case then the last group is going to have data in it
2042          * so we need to adjust the size of the last group accordingly
2043          */
2044         if (last_start < data_needed) {
2045                 blk64_t remainder = data_needed - last_start;
2046
2047                 /*
2048                  * 50 is a magic number that mkfs/resize uses to see if its
2049                  * even worth making/resizing the fs.  basically you need to
2050                  * have at least 50 blocks in addition to the blocks needed
2051                  * for the metadata in the last group
2052                  */
2053                 if (remainder > 50)
2054                         overhead += remainder;
2055                 else
2056                         overhead += 50;
2057         } else
2058                 overhead += 50;
2059
2060         overhead += fs->super->s_first_data_block;
2061
2062         /*
2063          * since our last group doesn't have to be BLOCKS_PER_GROUP large, we
2064          * only do groups-1, and then add the number of blocks needed to
2065          * handle the group descriptor metadata+data that we need
2066          */
2067         blks_needed = (groups-1) * EXT2_BLOCKS_PER_GROUP(fs->super);
2068         blks_needed += overhead;
2069
2070         /*
2071          * If at this point we've already added up more "needed" than
2072          * the current size, just return current size as minimum.
2073          */
2074         if (blks_needed >= ext2fs_blocks_count(fs->super))
2075                 return ext2fs_blocks_count(fs->super);
2076         /*
2077          * We need to reserve a few extra blocks if extents are
2078          * enabled, in case we need to grow the extent tree.  The more
2079          * we shrink the file system, the more space we need.
2080          */
2081         if (fs->super->s_feature_incompat & EXT3_FEATURE_INCOMPAT_EXTENTS)
2082                 blks_needed += (ext2fs_blocks_count(fs->super) - 
2083                                 blks_needed)/500;
2084
2085         return blks_needed;
2086 }