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