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