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