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