Whamcloud - gitweb
resize2fs: fix r_bigalloc_big_expand test failure
[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 Theodore 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 resize2fs_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 static errcode_t clear_sparse_super2_last_group(ext2_resize_t rfs);
57 static errcode_t reserve_sparse_super2_last_group(ext2_resize_t rfs,
58                                                  ext2fs_block_bitmap meta_bmap);
59 static errcode_t resize_group_descriptors(ext2_resize_t rfs, blk64_t new_size);
60 static errcode_t move_bg_metadata(ext2_resize_t rfs);
61 static errcode_t zero_high_bits_in_inodes(ext2_resize_t rfs);
62
63 /*
64  * Some helper functions to check if a block is in a metadata area
65  */
66 static inline int is_block_bm(ext2_filsys fs, unsigned int grp, blk64_t blk)
67 {
68         return blk == ext2fs_block_bitmap_loc(fs, grp);
69 }
70
71 static inline int is_inode_bm(ext2_filsys fs, unsigned int grp, blk64_t blk)
72 {
73         return blk == ext2fs_inode_bitmap_loc(fs, grp);
74 }
75
76 static int is_inode_tb(ext2_filsys fs, unsigned int grp, blk64_t blk)
77 {
78         return blk >= ext2fs_inode_table_loc(fs, grp) &&
79                blk < (ext2fs_inode_table_loc(fs, grp) +
80                       fs->inode_blocks_per_group);
81 }
82
83 /* Some bigalloc helper macros which are more succinct... */
84 #define B2C(x)  EXT2FS_B2C(fs, (x))
85 #define C2B(x)  EXT2FS_C2B(fs, (x))
86 #define EQ_CLSTR(x, y) (B2C(x) == B2C(y))
87 #define LE_CLSTR(x, y) (B2C(x) <= B2C(y))
88 #define LT_CLSTR(x, y) (B2C(x) <  B2C(y))
89 #define GE_CLSTR(x, y) (B2C(x) >= B2C(y))
90 #define GT_CLSTR(x, y) (B2C(x) >  B2C(y))
91
92 static int lazy_itable_init;
93
94 /*
95  * This is the top-level routine which does the dirty deed....
96  */
97 errcode_t resize_fs(ext2_filsys fs, blk64_t *new_size, int flags,
98             errcode_t (*progress)(ext2_resize_t rfs, int pass,
99                                           unsigned long cur,
100                                           unsigned long max_val))
101 {
102         ext2_resize_t   rfs;
103         errcode_t       retval;
104         struct resource_track   rtrack, overall_track;
105
106         /*
107          * Create the data structure
108          */
109         retval = ext2fs_get_mem(sizeof(struct ext2_resize_struct), &rfs);
110         if (retval)
111                 return retval;
112
113         memset(rfs, 0, sizeof(struct ext2_resize_struct));
114         fs->priv_data = rfs;
115         rfs->old_fs = fs;
116         rfs->flags = flags;
117         rfs->itable_buf  = 0;
118         rfs->progress = progress;
119
120         init_resource_track(&overall_track, "overall resize2fs", fs->io);
121         init_resource_track(&rtrack, "read_bitmaps", fs->io);
122         retval = ext2fs_read_bitmaps(fs);
123         if (retval)
124                 goto errout;
125         print_resource_track(rfs, &rtrack, fs->io);
126
127         fs->super->s_state |= EXT2_ERROR_FS;
128         ext2fs_mark_super_dirty(fs);
129         ext2fs_flush(fs);
130
131         init_resource_track(&rtrack, "fix_uninit_block_bitmaps 1", fs->io);
132         fix_uninit_block_bitmaps(fs);
133         print_resource_track(rfs, &rtrack, fs->io);
134         retval = ext2fs_dup_handle(fs, &rfs->new_fs);
135         if (retval)
136                 goto errout;
137
138         init_resource_track(&rtrack, "resize_group_descriptors", fs->io);
139         retval = resize_group_descriptors(rfs, *new_size);
140         if (retval)
141                 goto errout;
142         print_resource_track(rfs, &rtrack, fs->io);
143
144         init_resource_track(&rtrack, "move_bg_metadata", fs->io);
145         retval = move_bg_metadata(rfs);
146         if (retval)
147                 goto errout;
148         print_resource_track(rfs, &rtrack, fs->io);
149
150         init_resource_track(&rtrack, "zero_high_bits_in_metadata", fs->io);
151         retval = zero_high_bits_in_inodes(rfs);
152         if (retval)
153                 goto errout;
154         print_resource_track(rfs, &rtrack, fs->io);
155
156         init_resource_track(&rtrack, "adjust_superblock", fs->io);
157         retval = adjust_superblock(rfs, *new_size);
158         if (retval)
159                 goto errout;
160         print_resource_track(rfs, &rtrack, fs->io);
161
162         init_resource_track(&rtrack, "fix_uninit_block_bitmaps 2", fs->io);
163         fix_uninit_block_bitmaps(rfs->new_fs);
164         print_resource_track(rfs, &rtrack, fs->io);
165         /* Clear the block bitmap uninit flag for the last block group */
166         ext2fs_bg_flags_clear(rfs->new_fs, rfs->new_fs->group_desc_count - 1,
167                              EXT2_BG_BLOCK_UNINIT);
168
169         *new_size = ext2fs_blocks_count(rfs->new_fs->super);
170
171         init_resource_track(&rtrack, "blocks_to_move", fs->io);
172         retval = blocks_to_move(rfs);
173         if (retval)
174                 goto errout;
175         print_resource_track(rfs, &rtrack, fs->io);
176
177 #ifdef RESIZE2FS_DEBUG
178         if (rfs->flags & RESIZE_DEBUG_BMOVE)
179                 printf("Number of free blocks: %llu/%llu, Needed: %llu\n",
180                        (unsigned long long) ext2fs_free_blocks_count(rfs->old_fs->super),
181                        (unsigned long long) ext2fs_free_blocks_count(rfs->new_fs->super),
182                        (unsigned long long) rfs->needed_blocks);
183 #endif
184
185         init_resource_track(&rtrack, "block_mover", fs->io);
186         retval = block_mover(rfs);
187         if (retval)
188                 goto errout;
189         print_resource_track(rfs, &rtrack, fs->io);
190
191         init_resource_track(&rtrack, "inode_scan_and_fix", fs->io);
192         retval = inode_scan_and_fix(rfs);
193         if (retval)
194                 goto errout;
195         print_resource_track(rfs, &rtrack, fs->io);
196
197         init_resource_track(&rtrack, "inode_ref_fix", fs->io);
198         retval = inode_ref_fix(rfs);
199         if (retval)
200                 goto errout;
201         print_resource_track(rfs, &rtrack, fs->io);
202
203         init_resource_track(&rtrack, "move_itables", fs->io);
204         retval = move_itables(rfs);
205         if (retval)
206                 goto errout;
207         print_resource_track(rfs, &rtrack, fs->io);
208
209         retval = clear_sparse_super2_last_group(rfs);
210         if (retval)
211                 goto errout;
212
213         init_resource_track(&rtrack, "calculate_summary_stats", fs->io);
214         retval = resize2fs_calculate_summary_stats(rfs->new_fs);
215         if (retval)
216                 goto errout;
217         print_resource_track(rfs, &rtrack, fs->io);
218
219         init_resource_track(&rtrack, "fix_resize_inode", fs->io);
220         retval = fix_resize_inode(rfs->new_fs);
221         if (retval)
222                 goto errout;
223         print_resource_track(rfs, &rtrack, fs->io);
224
225         init_resource_track(&rtrack, "fix_sb_journal_backup", fs->io);
226         retval = fix_sb_journal_backup(rfs->new_fs);
227         if (retval)
228                 goto errout;
229         print_resource_track(rfs, &rtrack, fs->io);
230
231         retval = ext2fs_set_gdt_csum(rfs->new_fs);
232         if (retval)
233                 goto errout;
234
235         rfs->new_fs->super->s_state &= ~EXT2_ERROR_FS;
236         rfs->new_fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
237
238         print_resource_track(rfs, &overall_track, fs->io);
239         retval = ext2fs_close_free(&rfs->new_fs);
240         if (retval)
241                 goto errout;
242
243         rfs->flags = flags;
244
245         ext2fs_free(rfs->old_fs);
246         rfs->old_fs = NULL;
247         if (rfs->itable_buf)
248                 ext2fs_free_mem(&rfs->itable_buf);
249         if (rfs->reserve_blocks)
250                 ext2fs_free_block_bitmap(rfs->reserve_blocks);
251         if (rfs->move_blocks)
252                 ext2fs_free_block_bitmap(rfs->move_blocks);
253         ext2fs_free_mem(&rfs);
254
255         return 0;
256
257 errout:
258         if (rfs->new_fs) {
259                 ext2fs_free(rfs->new_fs);
260                 rfs->new_fs = NULL;
261         }
262         if (rfs->itable_buf)
263                 ext2fs_free_mem(&rfs->itable_buf);
264         ext2fs_free_mem(&rfs);
265         return retval;
266 }
267
268 /* Keep the size of the group descriptor region constant */
269 static void adjust_reserved_gdt_blocks(ext2_filsys old_fs, ext2_filsys fs)
270 {
271         if (ext2fs_has_feature_resize_inode(fs->super) &&
272             (old_fs->desc_blocks != fs->desc_blocks)) {
273                 int new;
274
275                 new = ((int) fs->super->s_reserved_gdt_blocks) +
276                         (old_fs->desc_blocks - fs->desc_blocks);
277                 if (new < 0)
278                         new = 0;
279                 if (new > (int) fs->blocksize/4)
280                         new = fs->blocksize/4;
281                 fs->super->s_reserved_gdt_blocks = new;
282         }
283 }
284
285 /* Toggle 64bit mode */
286 static errcode_t resize_group_descriptors(ext2_resize_t rfs, blk64_t new_size)
287 {
288         void *o, *n, *new_group_desc;
289         dgrp_t i;
290         int copy_size;
291         errcode_t retval;
292
293         if (!(rfs->flags & (RESIZE_DISABLE_64BIT | RESIZE_ENABLE_64BIT)))
294                 return 0;
295
296         if (new_size != ext2fs_blocks_count(rfs->new_fs->super) ||
297             ext2fs_blocks_count(rfs->new_fs->super) >= (1ULL << 32) ||
298             (rfs->flags & RESIZE_DISABLE_64BIT &&
299              rfs->flags & RESIZE_ENABLE_64BIT))
300                 return EXT2_ET_INVALID_ARGUMENT;
301
302         if (rfs->flags & RESIZE_DISABLE_64BIT) {
303                 ext2fs_clear_feature_64bit(rfs->new_fs->super);
304                 rfs->new_fs->super->s_desc_size = EXT2_MIN_DESC_SIZE;
305         } else if (rfs->flags & RESIZE_ENABLE_64BIT) {
306                 ext2fs_set_feature_64bit(rfs->new_fs->super);
307                 rfs->new_fs->super->s_desc_size = EXT2_MIN_DESC_SIZE_64BIT;
308         }
309
310         if (EXT2_DESC_SIZE(rfs->old_fs->super) ==
311             EXT2_DESC_SIZE(rfs->new_fs->super))
312                 return 0;
313
314         o = rfs->new_fs->group_desc;
315         rfs->new_fs->desc_blocks = ext2fs_div_ceil(
316                         rfs->old_fs->group_desc_count,
317                         EXT2_DESC_PER_BLOCK(rfs->new_fs->super));
318         retval = ext2fs_get_arrayzero(rfs->new_fs->desc_blocks,
319                                       rfs->old_fs->blocksize, &new_group_desc);
320         if (retval)
321                 return retval;
322
323         n = new_group_desc;
324
325         if (EXT2_DESC_SIZE(rfs->old_fs->super) <=
326             EXT2_DESC_SIZE(rfs->new_fs->super))
327                 copy_size = EXT2_DESC_SIZE(rfs->old_fs->super);
328         else
329                 copy_size = EXT2_DESC_SIZE(rfs->new_fs->super);
330         for (i = 0; i < rfs->old_fs->group_desc_count; i++) {
331                 memcpy(n, o, copy_size);
332                 n = (char *)n + EXT2_DESC_SIZE(rfs->new_fs->super);
333                 o = (char *)o + EXT2_DESC_SIZE(rfs->old_fs->super);
334         }
335
336         ext2fs_free_mem(&rfs->new_fs->group_desc);
337         rfs->new_fs->group_desc = new_group_desc;
338
339         for (i = 0; i < rfs->old_fs->group_desc_count; i++)
340                 ext2fs_group_desc_csum_set(rfs->new_fs, i);
341
342         adjust_reserved_gdt_blocks(rfs->old_fs, rfs->new_fs);
343
344         return 0;
345 }
346
347 /* Move bitmaps/inode tables out of the way. */
348 static errcode_t move_bg_metadata(ext2_resize_t rfs)
349 {
350         dgrp_t i;
351         blk64_t b, c, d, old_desc_blocks, new_desc_blocks, j;
352         ext2fs_block_bitmap old_map, new_map;
353         int old, new;
354         errcode_t retval;
355         int cluster_ratio;
356
357         if (!(rfs->flags & (RESIZE_DISABLE_64BIT | RESIZE_ENABLE_64BIT)))
358                 return 0;
359
360         retval = ext2fs_allocate_block_bitmap(rfs->old_fs, "oldfs", &old_map);
361         if (retval)
362                 return retval;
363
364         retval = ext2fs_allocate_block_bitmap(rfs->new_fs, "newfs", &new_map);
365         if (retval)
366                 goto out;
367
368         if (ext2fs_has_feature_meta_bg(rfs->old_fs->super)) {
369                 old_desc_blocks = rfs->old_fs->super->s_first_meta_bg;
370                 new_desc_blocks = rfs->new_fs->super->s_first_meta_bg;
371         } else {
372                 old_desc_blocks = rfs->old_fs->desc_blocks +
373                                 rfs->old_fs->super->s_reserved_gdt_blocks;
374                 new_desc_blocks = rfs->new_fs->desc_blocks +
375                                 rfs->new_fs->super->s_reserved_gdt_blocks;
376         }
377
378         /* Construct bitmaps of super/descriptor blocks in old and new fs */
379         for (i = 0; i < rfs->old_fs->group_desc_count; i++) {
380                 retval = ext2fs_super_and_bgd_loc2(rfs->old_fs, i, &b, &c, &d,
381                                                    NULL);
382                 if (retval)
383                         goto out;
384                 if (b)
385                         ext2fs_mark_block_bitmap2(old_map, b);
386                 for (j = 0; c != 0 && j < old_desc_blocks; j++)
387                         ext2fs_mark_block_bitmap2(old_map, c + j);
388                 if (d)
389                         ext2fs_mark_block_bitmap2(old_map, d);
390
391                 retval = ext2fs_super_and_bgd_loc2(rfs->new_fs, i, &b, &c, &d,
392                                                    NULL);
393                 if (retval)
394                         goto out;
395                 if (b)
396                         ext2fs_mark_block_bitmap2(new_map, b);
397                 for (j = 0; c != 0 && j < new_desc_blocks; j++)
398                         ext2fs_mark_block_bitmap2(new_map, c + j);
399                 if (d)
400                         ext2fs_mark_block_bitmap2(new_map, d);
401         }
402
403         cluster_ratio = EXT2FS_CLUSTER_RATIO(rfs->new_fs);
404
405         /* Find changes in block allocations for bg metadata */
406         for (b = EXT2FS_B2C(rfs->old_fs,
407                             rfs->old_fs->super->s_first_data_block);
408              b < ext2fs_blocks_count(rfs->new_fs->super);
409              b += cluster_ratio) {
410                 old = ext2fs_test_block_bitmap2(old_map, b);
411                 new = ext2fs_test_block_bitmap2(new_map, b);
412
413                 if (old && !new) {
414                         /* mark old_map, unmark new_map */
415                         if (cluster_ratio == 1)
416                                 ext2fs_unmark_block_bitmap2(
417                                                 rfs->new_fs->block_map, b);
418                 } else if (!old && new)
419                         ; /* unmark old_map, mark new_map */
420                 else {
421                         ext2fs_unmark_block_bitmap2(old_map, b);
422                         ext2fs_unmark_block_bitmap2(new_map, b);
423                 }
424         }
425
426         /*
427          * new_map now shows blocks that have been newly allocated.
428          * old_map now shows blocks that have been newly freed.
429          */
430
431         /*
432          * Move any conflicting bitmaps and inode tables.  Ensure that we
433          * don't try to free clusters associated with bitmaps or tables.
434          */
435         for (i = 0; i < rfs->old_fs->group_desc_count; i++) {
436                 b = ext2fs_block_bitmap_loc(rfs->new_fs, i);
437                 if (ext2fs_test_block_bitmap2(new_map, b))
438                         ext2fs_block_bitmap_loc_set(rfs->new_fs, i, 0);
439                 else if (ext2fs_test_block_bitmap2(old_map, b))
440                         ext2fs_unmark_block_bitmap2(old_map, b);
441
442                 b = ext2fs_inode_bitmap_loc(rfs->new_fs, i);
443                 if (ext2fs_test_block_bitmap2(new_map, b))
444                         ext2fs_inode_bitmap_loc_set(rfs->new_fs, i, 0);
445                 else if (ext2fs_test_block_bitmap2(old_map, b))
446                         ext2fs_unmark_block_bitmap2(old_map, b);
447
448                 c = ext2fs_inode_table_loc(rfs->new_fs, i);
449                 for (b = 0;
450                      b < rfs->new_fs->inode_blocks_per_group;
451                      b++) {
452                         if (ext2fs_test_block_bitmap2(new_map, b + c))
453                                 ext2fs_inode_table_loc_set(rfs->new_fs, i, 0);
454                         else if (ext2fs_test_block_bitmap2(old_map, b + c))
455                                 ext2fs_unmark_block_bitmap2(old_map, b + c);
456                 }
457         }
458
459         /* Free unused clusters */
460         for (b = 0;
461              cluster_ratio > 1 && b < ext2fs_blocks_count(rfs->new_fs->super);
462              b += cluster_ratio)
463                 if (ext2fs_test_block_bitmap2(old_map, b))
464                         ext2fs_unmark_block_bitmap2(rfs->new_fs->block_map, b);
465 out:
466         if (old_map)
467                 ext2fs_free_block_bitmap(old_map);
468         if (new_map)
469                 ext2fs_free_block_bitmap(new_map);
470         return retval;
471 }
472
473 /* Zero out the high bits of extent fields */
474 static errcode_t zero_high_bits_in_extents(ext2_filsys fs, ext2_ino_t ino,
475                                  struct ext2_inode *inode)
476 {
477         ext2_extent_handle_t    handle;
478         struct ext2fs_extent    extent;
479         int                     op = EXT2_EXTENT_ROOT;
480         errcode_t               errcode;
481
482         if (!(inode->i_flags & EXT4_EXTENTS_FL))
483                 return 0;
484
485         errcode = ext2fs_extent_open(fs, ino, &handle);
486         if (errcode)
487                 return errcode;
488
489         while (1) {
490                 errcode = ext2fs_extent_get(handle, op, &extent);
491                 if (errcode)
492                         break;
493
494                 op = EXT2_EXTENT_NEXT_SIB;
495
496                 if (extent.e_pblk > (1ULL << 32)) {
497                         extent.e_pblk &= (1ULL << 32) - 1;
498                         errcode = ext2fs_extent_replace(handle, 0, &extent);
499                         if (errcode)
500                                 break;
501                 }
502         }
503
504         /* Ok if we run off the end */
505         if (errcode == EXT2_ET_EXTENT_NO_NEXT)
506                 errcode = 0;
507         ext2fs_extent_free(handle);
508         return errcode;
509 }
510
511 /* Zero out the high bits of inodes. */
512 static errcode_t zero_high_bits_in_inodes(ext2_resize_t rfs)
513 {
514         ext2_filsys     fs = rfs->old_fs;
515         int length = EXT2_INODE_SIZE(fs->super);
516         struct ext2_inode *inode = NULL;
517         ext2_inode_scan scan = NULL;
518         errcode_t       retval;
519         ext2_ino_t      ino;
520
521         if (!(rfs->flags & (RESIZE_DISABLE_64BIT | RESIZE_ENABLE_64BIT)))
522                 return 0;
523
524         if (fs->super->s_creator_os == EXT2_OS_HURD)
525                 return 0;
526
527         retval = ext2fs_open_inode_scan(fs, 0, &scan);
528         if (retval)
529                 return retval;
530
531         retval = ext2fs_get_mem(length, &inode);
532         if (retval)
533                 goto out;
534
535         do {
536                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, length);
537                 if (retval)
538                         goto out;
539                 if (!ino)
540                         break;
541                 if (!ext2fs_test_inode_bitmap2(fs->inode_map, ino))
542                         continue;
543
544                 /*
545                  * Here's how we deal with high block number fields:
546                  *
547                  *  - i_size_high has been been written out with i_size_lo
548                  *    since the ext2 days, so no conversion is needed.
549                  *
550                  *  - i_blocks_hi is guarded by both the huge_file feature and
551                  *    inode flags and has always been written out with
552                  *    i_blocks_lo if the feature is set.  The field is only
553                  *    ever read if both feature and inode flag are set, so
554                  *    we don't need to zero it now.
555                  *
556                  *  - i_file_acl_high can be uninitialized, so zero it if
557                  *    it isn't already.
558                  */
559                 if (inode->osd2.linux2.l_i_file_acl_high) {
560                         inode->osd2.linux2.l_i_file_acl_high = 0;
561                         retval = ext2fs_write_inode_full(fs, ino, inode,
562                                                          length);
563                         if (retval)
564                                 goto out;
565                 }
566
567                 retval = zero_high_bits_in_extents(fs, ino, inode);
568                 if (retval)
569                         goto out;
570         } while (ino);
571
572 out:
573         if (inode)
574                 ext2fs_free_mem(&inode);
575         if (scan)
576                 ext2fs_close_inode_scan(scan);
577         return retval;
578 }
579
580 /*
581  * Clean up the bitmaps for uninitialized bitmaps
582  */
583 static void fix_uninit_block_bitmaps(ext2_filsys fs)
584 {
585         blk64_t         blk, lblk;
586         dgrp_t          g;
587         unsigned int    i;
588
589         if (!ext2fs_has_group_desc_csum(fs))
590                 return;
591
592         for (g=0; g < fs->group_desc_count; g++) {
593                 if (!(ext2fs_bg_flags_test(fs, g, EXT2_BG_BLOCK_UNINIT)))
594                         continue;
595
596                 blk = ext2fs_group_first_block2(fs, g);
597                 lblk = ext2fs_group_last_block2(fs, g);
598                 ext2fs_unmark_block_bitmap_range2(fs->block_map, blk,
599                                                   lblk - blk + 1);
600
601                 ext2fs_reserve_super_and_bgd(fs, g, fs->block_map);
602                 ext2fs_mark_block_bitmap2(fs->block_map,
603                                           ext2fs_block_bitmap_loc(fs, g));
604                 ext2fs_mark_block_bitmap2(fs->block_map,
605                                           ext2fs_inode_bitmap_loc(fs, g));
606                 for (i = 0, blk = ext2fs_inode_table_loc(fs, g);
607                      i < fs->inode_blocks_per_group;
608                      i++, blk++)
609                         ext2fs_mark_block_bitmap2(fs->block_map, blk);
610         }
611 }
612
613 /* --------------------------------------------------------------------
614  *
615  * Resize processing, phase 1.
616  *
617  * In this phase we adjust the in-memory superblock information, and
618  * initialize any new parts of the inode table.  The new parts of the
619  * inode table are created in virgin disk space, so we can abort here
620  * without any side effects.
621  * --------------------------------------------------------------------
622  */
623
624 /*
625  * If the group descriptor's bitmap and inode table blocks are valid,
626  * release them in the new filesystem data structure, and mark them as
627  * reserved so the old inode table blocks don't get overwritten.
628  */
629 static errcode_t free_gdp_blocks(ext2_filsys fs,
630                                  ext2fs_block_bitmap reserve_blocks,
631                                  ext2_filsys old_fs,
632                                  dgrp_t group)
633 {
634         blk64_t         blk;
635         unsigned int    j;
636         dgrp_t          i;
637         ext2fs_block_bitmap bg_map = NULL;
638         errcode_t       retval = 0;
639         dgrp_t          count = old_fs->group_desc_count - fs->group_desc_count;
640
641         /* If bigalloc, don't free metadata living in the same cluster */
642         if (EXT2FS_CLUSTER_RATIO(fs) > 1) {
643                 retval = ext2fs_allocate_block_bitmap(fs, "bgdata", &bg_map);
644                 if (retval)
645                         goto out;
646
647                 retval = mark_table_blocks(fs, bg_map);
648                 if (retval)
649                         goto out;
650         }
651
652         for (i = group; i < group + count; i++) {
653                 blk = ext2fs_block_bitmap_loc(old_fs, i);
654                 if (blk &&
655                     (blk < ext2fs_blocks_count(fs->super)) &&
656                     !(bg_map && ext2fs_test_block_bitmap2(bg_map, blk))) {
657                         ext2fs_block_alloc_stats2(fs, blk, -1);
658                         ext2fs_mark_block_bitmap2(reserve_blocks, blk);
659                 }
660
661                 blk = ext2fs_inode_bitmap_loc(old_fs, i);
662                 if (blk &&
663                     (blk < ext2fs_blocks_count(fs->super)) &&
664                     !(bg_map && ext2fs_test_block_bitmap2(bg_map, blk))) {
665                         ext2fs_block_alloc_stats2(fs, blk, -1);
666                         ext2fs_mark_block_bitmap2(reserve_blocks, blk);
667                 }
668
669                 blk = ext2fs_inode_table_loc(old_fs, i);
670                 for (j = 0;
671                      j < fs->inode_blocks_per_group; j++, blk++) {
672                         if (blk >= ext2fs_blocks_count(fs->super) ||
673                             (bg_map && ext2fs_test_block_bitmap2(bg_map, blk)))
674                                 continue;
675                         ext2fs_block_alloc_stats2(fs, blk, -1);
676                         ext2fs_mark_block_bitmap2(reserve_blocks, blk);
677                 }
678         }
679
680 out:
681         if (bg_map)
682                 ext2fs_free_block_bitmap(bg_map);
683         return retval;
684 }
685
686 /*
687  * This routine is shared by the online and offline resize routines.
688  * All of the information which is adjusted in memory is done here.
689  */
690 errcode_t adjust_fs_info(ext2_filsys fs, ext2_filsys old_fs,
691                          ext2fs_block_bitmap reserve_blocks, blk64_t new_size)
692 {
693         errcode_t       retval;
694         blk64_t         overhead = 0;
695         blk64_t         rem;
696         blk64_t         blk, group_block;
697         blk64_t         real_end;
698         blk64_t         old_numblocks, numblocks, adjblocks;
699         unsigned long   i, j, old_desc_blocks;
700         unsigned int    meta_bg, meta_bg_size;
701         int             has_super, csum_flag, has_bg;
702         unsigned long long new_inodes;  /* u64 to check for overflow */
703         double          percent;
704
705         ext2fs_blocks_count_set(fs->super, new_size);
706         fs->super->s_overhead_clusters = 0;
707
708 retry:
709         fs->group_desc_count = ext2fs_div64_ceil(ext2fs_blocks_count(fs->super) -
710                                        fs->super->s_first_data_block,
711                                        EXT2_BLOCKS_PER_GROUP(fs->super));
712         if (fs->group_desc_count == 0)
713                 return EXT2_ET_TOOSMALL;
714         fs->desc_blocks = ext2fs_div_ceil(fs->group_desc_count,
715                                           EXT2_DESC_PER_BLOCK(fs->super));
716
717         /*
718          * Overhead is the number of bookkeeping blocks per group.  It
719          * includes the superblock backup, the group descriptor
720          * backups, the inode bitmap, the block bitmap, and the inode
721          * table.
722          */
723         overhead = (int) (2 + fs->inode_blocks_per_group);
724
725         has_bg = 0;
726         if (ext2fs_has_feature_sparse_super2(fs->super)) {
727                 /*
728                  * We have to do this manually since
729                  * super->s_backup_bgs hasn't been set up yet.
730                  */
731                 if (fs->group_desc_count == 2)
732                         has_bg = fs->super->s_backup_bgs[0] != 0;
733                 else
734                         has_bg = fs->super->s_backup_bgs[1] != 0;
735         } else
736                 has_bg = ext2fs_bg_has_super(fs, fs->group_desc_count - 1);
737         if (has_bg)
738                 overhead += 1 + fs->desc_blocks +
739                         fs->super->s_reserved_gdt_blocks;
740
741         /*
742          * See if the last group is big enough to support the
743          * necessary data structures.  If not, we need to get rid of
744          * it.
745          */
746         rem = (ext2fs_blocks_count(fs->super) - fs->super->s_first_data_block) %
747                 fs->super->s_blocks_per_group;
748         if ((fs->group_desc_count == 1) && rem && (rem < overhead))
749                 return EXT2_ET_TOOSMALL;
750         if ((fs->group_desc_count > 1) && rem && (rem < overhead+50)) {
751                 ext2fs_blocks_count_set(fs->super,
752                                         ext2fs_blocks_count(fs->super) - rem);
753                 goto retry;
754         }
755         /*
756          * Adjust the number of inodes
757          */
758         new_inodes =(unsigned long long) fs->super->s_inodes_per_group * fs->group_desc_count;
759         if (new_inodes > ~0U) {
760                 new_inodes = (unsigned long long) fs->super->s_inodes_per_group * (fs->group_desc_count - 1);
761                 if (new_inodes <= ~0U) {
762                         unsigned long long new_blocks =
763                 ((unsigned long long) fs->super->s_blocks_per_group *
764                  (fs->group_desc_count - 1)) + fs->super->s_first_data_block;
765
766                         ext2fs_blocks_count_set(fs->super, new_blocks);
767                         goto retry;
768                 }
769                 fprintf(stderr, _("inodes (%llu) must be less than %u\n"),
770                         (unsigned long long) new_inodes, ~0U);
771                 return EXT2_ET_TOO_MANY_INODES;
772         }
773         fs->super->s_inodes_count = fs->super->s_inodes_per_group *
774                 fs->group_desc_count;
775
776         /*
777          * Adjust the number of free blocks
778          */
779         blk = ext2fs_blocks_count(old_fs->super);
780         if (blk > ext2fs_blocks_count(fs->super))
781                 ext2fs_free_blocks_count_set(fs->super, 
782                         ext2fs_free_blocks_count(fs->super) -
783                         (blk - ext2fs_blocks_count(fs->super)));
784         else
785                 ext2fs_free_blocks_count_set(fs->super, 
786                         ext2fs_free_blocks_count(fs->super) +
787                         (ext2fs_blocks_count(fs->super) - blk));
788
789         /*
790          * Adjust the number of reserved blocks
791          */
792         percent = (ext2fs_r_blocks_count(old_fs->super) * 100.0) /
793                 ext2fs_blocks_count(old_fs->super);
794         ext2fs_r_blocks_count_set(fs->super,
795                                   (percent * ext2fs_blocks_count(fs->super) /
796                                    100.0));
797
798         /*
799          * Adjust the bitmaps for size
800          */
801         retval = ext2fs_resize_inode_bitmap2(fs->super->s_inodes_count,
802                                             fs->super->s_inodes_count,
803                                             fs->inode_map);
804         if (retval) goto errout;
805
806         real_end = EXT2_GROUPS_TO_CLUSTERS(fs->super, fs->group_desc_count) -
807                 1 + EXT2FS_B2C(fs, fs->super->s_first_data_block);
808         retval = ext2fs_resize_block_bitmap2(new_size - 1,
809                                              real_end, fs->block_map);
810         if (retval) goto errout;
811
812         /*
813          * If we are growing the file system, also grow the size of
814          * the reserve_blocks bitmap
815          */
816         if (reserve_blocks && new_size > ext2fs_blocks_count(old_fs->super)) {
817                 retval = ext2fs_resize_block_bitmap2(new_size - 1,
818                                                      real_end, reserve_blocks);
819                 if (retval) goto errout;
820         }
821
822         /*
823          * Reallocate the group descriptors as necessary.
824          */
825         if (EXT2_DESC_SIZE(old_fs->super) == EXT2_DESC_SIZE(fs->super) &&
826             old_fs->desc_blocks != fs->desc_blocks) {
827                 retval = ext2fs_resize_mem(old_fs->desc_blocks *
828                                            fs->blocksize,
829                                            fs->desc_blocks * fs->blocksize,
830                                            &fs->group_desc);
831                 if (retval)
832                         goto errout;
833                 if (fs->desc_blocks > old_fs->desc_blocks)
834                         memset((char *) fs->group_desc +
835                                (old_fs->desc_blocks * fs->blocksize), 0,
836                                (fs->desc_blocks - old_fs->desc_blocks) *
837                                fs->blocksize);
838         }
839
840         /*
841          * If the resize_inode feature is set, and we are changing the
842          * number of descriptor blocks, then adjust
843          * s_reserved_gdt_blocks if possible to avoid needing to move
844          * the inode table either now or in the future.
845          *
846          * Note: If we're converting to 64bit mode, we did this earlier.
847          */
848         if (EXT2_DESC_SIZE(old_fs->super) == EXT2_DESC_SIZE(fs->super))
849                 adjust_reserved_gdt_blocks(old_fs, fs);
850
851         if (ext2fs_has_feature_meta_bg(fs->super) &&
852             (fs->super->s_first_meta_bg > fs->desc_blocks)) {
853                 ext2fs_clear_feature_meta_bg(fs->super);
854                 fs->super->s_first_meta_bg = 0;
855         }
856
857         /*
858          * Update the location of the backup superblocks if the
859          * sparse_super2 feature is enabled.
860          */
861         if (ext2fs_has_feature_sparse_super2(fs->super)) {
862                 dgrp_t last_bg = fs->group_desc_count - 1;
863                 dgrp_t old_last_bg = old_fs->group_desc_count - 1;
864
865                 if (last_bg > old_last_bg) {
866                         if (old_fs->group_desc_count == 1)
867                                 fs->super->s_backup_bgs[0] = 1;
868                         if ((old_fs->group_desc_count < 3 &&
869                              fs->group_desc_count > 2) ||
870                             fs->super->s_backup_bgs[1])
871                                 fs->super->s_backup_bgs[1] = last_bg;
872                 } else if (last_bg < old_last_bg) {
873                         if (fs->super->s_backup_bgs[0] > last_bg)
874                                 fs->super->s_backup_bgs[0] = 0;
875                         if (fs->super->s_backup_bgs[1] > last_bg)
876                                 fs->super->s_backup_bgs[1] = 0;
877                         if (last_bg > 1 &&
878                             old_fs->super->s_backup_bgs[1] == old_last_bg)
879                                 fs->super->s_backup_bgs[1] = last_bg;
880                 }
881         }
882
883         /*
884          * If we are shrinking the number of block groups, we're done
885          * and can exit now.
886          */
887         if (old_fs->group_desc_count > fs->group_desc_count) {
888                 /*
889                  * Check the block groups that we are chopping off
890                  * and free any blocks associated with their metadata
891                  */
892                 retval = free_gdp_blocks(fs, reserve_blocks, old_fs,
893                                          fs->group_desc_count);
894                 goto errout;
895         }
896
897         /*
898          * Fix the count of the last (old) block group
899          */
900         old_numblocks = (ext2fs_blocks_count(old_fs->super) -
901                          old_fs->super->s_first_data_block) %
902                                  old_fs->super->s_blocks_per_group;
903         if (!old_numblocks)
904                 old_numblocks = old_fs->super->s_blocks_per_group;
905         if (old_fs->group_desc_count == fs->group_desc_count) {
906                 numblocks = (ext2fs_blocks_count(fs->super) -
907                              fs->super->s_first_data_block) %
908                         fs->super->s_blocks_per_group;
909                 if (!numblocks)
910                         numblocks = fs->super->s_blocks_per_group;
911         } else
912                 numblocks = fs->super->s_blocks_per_group;
913         i = old_fs->group_desc_count - 1;
914         ext2fs_bg_free_blocks_count_set(fs, i, ext2fs_bg_free_blocks_count(fs, i) + (numblocks - old_numblocks));
915         ext2fs_group_desc_csum_set(fs, i);
916
917         /*
918          * If the number of block groups is staying the same, we're
919          * done and can exit now.  (If the number block groups is
920          * shrinking, we had exited earlier.)
921          */
922         if (old_fs->group_desc_count >= fs->group_desc_count) {
923                 retval = 0;
924                 goto errout;
925         }
926
927         /*
928          * Initialize the new block group descriptors
929          */
930         group_block = ext2fs_group_first_block2(fs,
931                                                 old_fs->group_desc_count);
932         csum_flag = ext2fs_has_group_desc_csum(fs);
933         if (getenv("RESIZE2FS_FORCE_LAZY_ITABLE_INIT") ||
934             (!getenv("RESIZE2FS_FORCE_ITABLE_INIT") &&
935              access("/sys/fs/ext4/features/lazy_itable_init", F_OK) == 0))
936                 lazy_itable_init = 1;
937         if (ext2fs_has_feature_meta_bg(fs->super))
938                 old_desc_blocks = fs->super->s_first_meta_bg;
939         else
940                 old_desc_blocks = fs->desc_blocks +
941                         fs->super->s_reserved_gdt_blocks;
942
943         /*
944          * If we changed the number of block_group descriptor blocks,
945          * we need to make sure they are all marked as reserved in the
946          * filesystem's block allocation map.
947          */
948         for (i = 0; i < old_fs->group_desc_count; i++)
949                 ext2fs_reserve_super_and_bgd(fs, i, fs->block_map);
950
951         for (i = old_fs->group_desc_count;
952              i < fs->group_desc_count; i++) {
953                 memset(ext2fs_group_desc(fs, fs->group_desc, i), 0,
954                        sizeof(struct ext2_group_desc));
955                 adjblocks = 0;
956
957                 ext2fs_bg_flags_zap(fs, i);
958                 if (csum_flag) {
959                         ext2fs_bg_flags_set(fs, i, EXT2_BG_INODE_UNINIT);
960                         if (!lazy_itable_init)
961                                 ext2fs_bg_flags_set(fs, i,
962                                                     EXT2_BG_INODE_ZEROED);
963                         ext2fs_bg_itable_unused_set(fs, i,
964                                         fs->super->s_inodes_per_group);
965                 }
966
967                 numblocks = ext2fs_group_blocks_count(fs, i);
968                 if ((i < fs->group_desc_count - 1) && csum_flag)
969                         ext2fs_bg_flags_set(fs, i, EXT2_BG_BLOCK_UNINIT);
970
971                 has_super = ext2fs_bg_has_super(fs, i);
972                 if (has_super) {
973                         ext2fs_block_alloc_stats2(fs, group_block, +1);
974                         adjblocks++;
975                 }
976                 meta_bg_size = EXT2_DESC_PER_BLOCK(fs->super);
977                 meta_bg = i / meta_bg_size;
978                 if (!ext2fs_has_feature_meta_bg(fs->super) ||
979                     (meta_bg < fs->super->s_first_meta_bg)) {
980                         if (has_super) {
981                                 for (j=0; j < old_desc_blocks; j++)
982                                         ext2fs_block_alloc_stats2(fs,
983                                                  group_block + 1 + j, +1);
984                                 adjblocks += old_desc_blocks;
985                         }
986                 } else {
987                         if (has_super)
988                                 has_super = 1;
989                         if (((i % meta_bg_size) == 0) ||
990                             ((i % meta_bg_size) == 1) ||
991                             ((i % meta_bg_size) == (meta_bg_size-1)))
992                                 ext2fs_block_alloc_stats2(fs,
993                                                  group_block + has_super, +1);
994                 }
995
996                 adjblocks += 2 + fs->inode_blocks_per_group;
997
998                 numblocks -= adjblocks;
999                 ext2fs_free_blocks_count_set(fs->super,
1000                              ext2fs_free_blocks_count(fs->super) - adjblocks);
1001                 fs->super->s_free_inodes_count +=
1002                         fs->super->s_inodes_per_group;
1003                 ext2fs_bg_free_blocks_count_set(fs, i, numblocks);
1004                 ext2fs_bg_free_inodes_count_set(fs, i,
1005                                                 fs->super->s_inodes_per_group);
1006                 ext2fs_bg_used_dirs_count_set(fs, i, 0);
1007                 ext2fs_group_desc_csum_set(fs, i);
1008
1009                 retval = ext2fs_allocate_group_table(fs, i, 0);
1010                 if (retval) goto errout;
1011
1012                 group_block += fs->super->s_blocks_per_group;
1013         }
1014         retval = 0;
1015
1016         /*
1017          * Mark all of the metadata blocks as reserved so they won't
1018          * get allocated by the call to ext2fs_allocate_group_table()
1019          * in blocks_to_move(), where we allocate new blocks to
1020          * replace those allocation bitmap and inode table blocks
1021          * which have to get relocated to make space for an increased
1022          * number of the block group descriptors.
1023          */
1024         if (reserve_blocks)
1025                 mark_table_blocks(fs, reserve_blocks);
1026
1027 errout:
1028         return (retval);
1029 }
1030
1031 /*
1032  * Replicate the first part of adjust_fs_info to determine what the
1033  * new size of the file system should be.  This allows resize2fs to
1034  * exit early if we aren't going to make any changes to the file
1035  * system.
1036  */
1037 void adjust_new_size(ext2_filsys fs, blk64_t *sizep)
1038 {
1039         blk64_t         size, rem, overhead = 0;
1040         unsigned long   desc_blocks;
1041         dgrp_t          group_desc_count;
1042         int             has_bg;
1043         unsigned long long new_inodes;  /* u64 to check for overflow */
1044
1045         size = *sizep;
1046 retry:
1047         group_desc_count = ext2fs_div64_ceil(size -
1048                                              fs->super->s_first_data_block,
1049                                              EXT2_BLOCKS_PER_GROUP(fs->super));
1050         if (group_desc_count == 0)
1051                 return;
1052         desc_blocks = ext2fs_div_ceil(group_desc_count,
1053                                       EXT2_DESC_PER_BLOCK(fs->super));
1054
1055         /*
1056          * Overhead is the number of bookkeeping blocks per group.  It
1057          * includes the superblock backup, the group descriptor
1058          * backups, the inode bitmap, the block bitmap, and the inode
1059          * table.
1060          */
1061         overhead = (int) (2 + fs->inode_blocks_per_group);
1062
1063         has_bg = 0;
1064         if (ext2fs_has_feature_sparse_super2(fs->super)) {
1065                 /*
1066                  * We have to do this manually since
1067                  * super->s_backup_bgs hasn't been set up yet.
1068                  */
1069                 if (group_desc_count == 2)
1070                         has_bg = fs->super->s_backup_bgs[0] != 0;
1071                 else
1072                         has_bg = fs->super->s_backup_bgs[1] != 0;
1073         } else
1074                 has_bg = ext2fs_bg_has_super(fs, group_desc_count - 1);
1075         if (has_bg)
1076                 overhead += 1 + desc_blocks +
1077                         fs->super->s_reserved_gdt_blocks;
1078
1079         /*
1080          * See if the last group is big enough to support the
1081          * necessary data structures.  If not, we need to get rid of
1082          * it.
1083          */
1084         rem = (size - fs->super->s_first_data_block) %
1085                 fs->super->s_blocks_per_group;
1086         if ((group_desc_count == 1) && rem && (rem < overhead))
1087                 return;
1088         if ((group_desc_count > 1) && rem && (rem < overhead+50)) {
1089                 size -= rem;
1090                 goto retry;
1091         }
1092
1093         /*
1094          * If we need to reduce the size by no more than a block
1095          * group to avoid overrunning the max inode limit, do it.
1096          */
1097         new_inodes =(unsigned long long) fs->super->s_inodes_per_group * group_desc_count;
1098         if (new_inodes > ~0U) {
1099                 new_inodes = (unsigned long long) fs->super->s_inodes_per_group * (group_desc_count - 1);
1100                 if (new_inodes > ~0U)
1101                         return;
1102                 size = ((unsigned long long) fs->super->s_blocks_per_group *
1103                         (group_desc_count - 1)) + fs->super->s_first_data_block;
1104
1105                 goto retry;
1106         }
1107         *sizep = size;
1108 }
1109
1110 /*
1111  * This routine adjusts the superblock and other data structures, both
1112  * in disk as well as in memory...
1113  */
1114 static errcode_t adjust_superblock(ext2_resize_t rfs, blk64_t new_size)
1115 {
1116         ext2_filsys     fs = rfs->new_fs;
1117         int             adj = 0;
1118         errcode_t       retval;
1119         unsigned long   i;
1120         unsigned long   max_group;
1121
1122         ext2fs_mark_super_dirty(fs);
1123         ext2fs_mark_bb_dirty(fs);
1124         ext2fs_mark_ib_dirty(fs);
1125
1126         retval = ext2fs_allocate_block_bitmap(fs, _("reserved blocks"),
1127                                               &rfs->reserve_blocks);
1128         if (retval)
1129                 return retval;
1130
1131         retval = adjust_fs_info(fs, rfs->old_fs, rfs->reserve_blocks, new_size);
1132         if (retval)
1133                 goto errout;
1134
1135         /*
1136          * Check to make sure there are enough inodes
1137          */
1138         if ((rfs->old_fs->super->s_inodes_count -
1139              rfs->old_fs->super->s_free_inodes_count) >
1140             rfs->new_fs->super->s_inodes_count) {
1141                 retval = ENOSPC;
1142                 goto errout;
1143         }
1144
1145         /*
1146          * If we are shrinking the number block groups, we're done and
1147          * can exit now.
1148          */
1149         if (rfs->old_fs->group_desc_count > fs->group_desc_count) {
1150                 retval = 0;
1151                 goto errout;
1152         }
1153
1154         /*
1155          * If the number of block groups is staying the same, we're
1156          * done and can exit now.  (If the number block groups is
1157          * shrinking, we had exited earlier.)
1158          */
1159         if (rfs->old_fs->group_desc_count >= fs->group_desc_count) {
1160                 retval = 0;
1161                 goto errout;
1162         }
1163
1164         /*
1165          * If we are using uninit_bg (aka GDT_CSUM) and the kernel
1166          * supports lazy inode initialization, we can skip
1167          * initializing the inode table.
1168          */
1169         if (lazy_itable_init && ext2fs_has_group_desc_csum(fs)) {
1170                 retval = 0;
1171                 goto errout;
1172         }
1173
1174         /*
1175          * Initialize the inode table
1176          */
1177         retval = ext2fs_get_array(fs->blocksize, fs->inode_blocks_per_group,
1178                                 &rfs->itable_buf);
1179         if (retval)
1180                 goto errout;
1181
1182         memset(rfs->itable_buf, 0, fs->blocksize * fs->inode_blocks_per_group);
1183         adj = rfs->old_fs->group_desc_count;
1184         max_group = fs->group_desc_count - adj;
1185         if (rfs->progress) {
1186                 retval = rfs->progress(rfs, E2_RSZ_EXTEND_ITABLE_PASS,
1187                                        0, max_group);
1188                 if (retval)
1189                         goto errout;
1190         }
1191         for (i = rfs->old_fs->group_desc_count;
1192              i < fs->group_desc_count; i++) {
1193                 /*
1194                  * Write out the new inode table
1195                  */
1196                 retval = ext2fs_zero_blocks2(fs, ext2fs_inode_table_loc(fs, i),
1197                                              fs->inode_blocks_per_group, NULL,
1198                                              NULL);
1199                 if (retval)
1200                         goto errout;
1201
1202                 io_channel_flush(fs->io);
1203                 if (rfs->progress) {
1204                         retval = rfs->progress(rfs, E2_RSZ_EXTEND_ITABLE_PASS,
1205                                                i - adj + 1, max_group);
1206                         if (retval)
1207                                 goto errout;
1208                 }
1209         }
1210         io_channel_flush(fs->io);
1211         retval = 0;
1212
1213 errout:
1214         return retval;
1215 }
1216
1217 /* --------------------------------------------------------------------
1218  *
1219  * Resize processing, phase 2.
1220  *
1221  * In this phase we adjust determine which blocks need to be moved, in
1222  * blocks_to_move().  We then copy the blocks to their ultimate new
1223  * destinations using block_mover().  Since we are copying blocks to
1224  * their new locations, again during this pass we can abort without
1225  * any problems.
1226  * --------------------------------------------------------------------
1227  */
1228
1229 /*
1230  * This helper function creates a block bitmap with all of the
1231  * filesystem meta-data blocks.
1232  */
1233 static errcode_t mark_table_blocks(ext2_filsys fs,
1234                                    ext2fs_block_bitmap bmap)
1235 {
1236         dgrp_t                  i;
1237         blk64_t                 blk;
1238
1239         for (i = 0; i < fs->group_desc_count; i++) {
1240                 ext2fs_reserve_super_and_bgd(fs, i, bmap);
1241
1242                 /*
1243                  * Mark the blocks used for the inode table
1244                  */
1245                 blk = ext2fs_inode_table_loc(fs, i);
1246                 if (blk)
1247                         ext2fs_mark_block_bitmap_range2(bmap, blk,
1248                                                 fs->inode_blocks_per_group);
1249
1250                 /*
1251                  * Mark block used for the block bitmap
1252                  */
1253                 blk = ext2fs_block_bitmap_loc(fs, i);
1254                 if (blk)
1255                         ext2fs_mark_block_bitmap2(bmap, blk);
1256
1257                 /*
1258                  * Mark block used for the inode bitmap
1259                  */
1260                 blk = ext2fs_inode_bitmap_loc(fs, i);
1261                 if (blk)
1262                         ext2fs_mark_block_bitmap2(bmap, blk);
1263         }
1264         /* Reserve the MMP block */
1265         if (ext2fs_has_feature_mmp(fs->super) &&
1266             fs->super->s_mmp_block > fs->super->s_first_data_block &&
1267             fs->super->s_mmp_block < ext2fs_blocks_count(fs->super))
1268                 ext2fs_mark_block_bitmap2(bmap, fs->super->s_mmp_block);
1269         return 0;
1270 }
1271
1272 /*
1273  * This function checks to see if a particular block (either a
1274  * superblock or a block group descriptor) overlaps with an inode or
1275  * block bitmap block, or with the inode table.
1276  */
1277 static void mark_fs_metablock(ext2_resize_t rfs,
1278                               ext2fs_block_bitmap meta_bmap,
1279                               int group, blk64_t blk)
1280 {
1281         ext2_filsys fs = rfs->new_fs;
1282
1283         ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
1284         ext2fs_block_alloc_stats2(fs, blk, +1);
1285
1286         /*
1287          * Check to see if we overlap with the inode or block bitmap,
1288          * or the inode tables.  If not, and the block is in use, then
1289          * mark it as a block to be moved.
1290          */
1291         if (is_block_bm(fs, group, blk)) {
1292                 ext2fs_block_bitmap_loc_set(fs, group, 0);
1293                 rfs->needed_blocks++;
1294                 return;
1295         }
1296         if (is_inode_bm(fs, group, blk)) {
1297                 ext2fs_inode_bitmap_loc_set(fs, group, 0);
1298                 rfs->needed_blocks++;
1299                 return;
1300         }
1301         if (is_inode_tb(fs, group, blk)) {
1302                 ext2fs_inode_table_loc_set(fs, group, 0);
1303                 rfs->needed_blocks++;
1304                 return;
1305         }
1306         if (ext2fs_has_feature_flex_bg(fs->super)) {
1307                 dgrp_t i;
1308
1309                 for (i = 0; i < rfs->old_fs->group_desc_count; i++) {
1310                         if (is_block_bm(fs, i, blk)) {
1311                                 ext2fs_block_bitmap_loc_set(fs, i, 0);
1312                                 rfs->needed_blocks++;
1313                                 return;
1314                         }
1315                         if (is_inode_bm(fs, i, blk)) {
1316                                 ext2fs_inode_bitmap_loc_set(fs, i, 0);
1317                                 rfs->needed_blocks++;
1318                                 return;
1319                         }
1320                         if (is_inode_tb(fs, i, blk)) {
1321                                 ext2fs_inode_table_loc_set(fs, i, 0);
1322                                 rfs->needed_blocks++;
1323                                 return;
1324                         }
1325                 }
1326         }
1327
1328         if (ext2fs_has_group_desc_csum(fs) &&
1329             (ext2fs_bg_flags_test(fs, group, EXT2_BG_BLOCK_UNINIT))) {
1330                 /*
1331                  * If the block bitmap is uninitialized, which means
1332                  * nothing other than standard metadata in use.
1333                  */
1334                 return;
1335         } else if (blk < ext2fs_blocks_count(rfs->old_fs->super) &&
1336                    ext2fs_test_block_bitmap2(rfs->old_fs->block_map, blk) &&
1337                    !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
1338                 ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
1339                 rfs->needed_blocks++;
1340         }
1341 }
1342
1343
1344 /*
1345  * This routine marks and unmarks reserved blocks in the new block
1346  * bitmap.  It also determines which blocks need to be moved and
1347  * places this information into the move_blocks bitmap.
1348  */
1349 static errcode_t blocks_to_move(ext2_resize_t rfs)
1350 {
1351         unsigned int    j;
1352         int             has_super;
1353         dgrp_t          i, max_groups, g;
1354         blk64_t         blk, group_blk;
1355         blk64_t         old_blocks, new_blocks, group_end, cluster_freed;
1356         blk64_t         new_size;
1357         unsigned int    meta_bg, meta_bg_size;
1358         errcode_t       retval;
1359         ext2_filsys     fs, old_fs;
1360         ext2fs_block_bitmap     meta_bmap, new_meta_bmap = NULL;
1361         int             flex_bg;
1362
1363         fs = rfs->new_fs;
1364         old_fs = rfs->old_fs;
1365         if (ext2fs_blocks_count(old_fs->super) > ext2fs_blocks_count(fs->super))
1366                 fs = rfs->old_fs;
1367
1368         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1369                                               &rfs->move_blocks);
1370         if (retval)
1371                 return retval;
1372
1373         retval = ext2fs_allocate_block_bitmap(fs, _("meta-data blocks"),
1374                                               &meta_bmap);
1375         if (retval)
1376                 return retval;
1377
1378         retval = mark_table_blocks(old_fs, meta_bmap);
1379         if (retval)
1380                 return retval;
1381
1382         fs = rfs->new_fs;
1383
1384         /*
1385          * If we're shrinking the filesystem, we need to move any
1386          * group's metadata blocks (either allocation bitmaps or the
1387          * inode table) which are beyond the end of the new
1388          * filesystem.
1389          */
1390         new_size = ext2fs_blocks_count(fs->super);
1391         if (new_size < ext2fs_blocks_count(old_fs->super)) {
1392                 for (g = 0; g < fs->group_desc_count; g++) {
1393                         int realloc = 0;
1394                         /*
1395                          * ext2fs_allocate_group_table will re-allocate any
1396                          * metadata blocks whose location is set to zero.
1397                          */
1398                         if (ext2fs_block_bitmap_loc(fs, g) >= new_size) {
1399                                 ext2fs_block_bitmap_loc_set(fs, g, 0);
1400                                 realloc = 1;
1401                         }
1402                         if (ext2fs_inode_bitmap_loc(fs, g) >= new_size) {
1403                                 ext2fs_inode_bitmap_loc_set(fs, g, 0);
1404                                 realloc = 1;
1405                         }
1406                         if ((ext2fs_inode_table_loc(fs, g) +
1407                              fs->inode_blocks_per_group) > new_size) {
1408                                 ext2fs_inode_table_loc_set(fs, g, 0);
1409                                 realloc = 1;
1410                         }
1411
1412                         if (realloc) {
1413                                 retval = ext2fs_allocate_group_table(fs, g, 0);
1414                                 if (retval)
1415                                         return retval;
1416                         }
1417                 }
1418         }
1419
1420         /*
1421          * If we're shrinking the filesystem, we need to move all of
1422          * the blocks that don't fit any more
1423          */
1424         for (blk = ext2fs_blocks_count(fs->super);
1425              blk < ext2fs_blocks_count(old_fs->super); blk++) {
1426                 g = ext2fs_group_of_blk2(fs, blk);
1427                 if (ext2fs_has_group_desc_csum(fs) &&
1428                     ext2fs_bg_flags_test(old_fs, g, EXT2_BG_BLOCK_UNINIT)) {
1429                         /*
1430                          * The block bitmap is uninitialized, so skip
1431                          * to the next block group.
1432                          */
1433                         blk = ext2fs_group_first_block2(fs, g+1) - 1;
1434                         continue;
1435                 }
1436                 if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
1437                     !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
1438                         ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
1439                         rfs->needed_blocks++;
1440                 }
1441                 ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
1442         }
1443
1444         if (ext2fs_has_feature_meta_bg(old_fs->super))
1445                 old_blocks = old_fs->super->s_first_meta_bg;
1446         else
1447                 old_blocks = old_fs->desc_blocks +
1448                         old_fs->super->s_reserved_gdt_blocks;
1449         if (ext2fs_has_feature_meta_bg(fs->super))
1450                 new_blocks = fs->super->s_first_meta_bg;
1451         else
1452                 new_blocks = fs->desc_blocks + fs->super->s_reserved_gdt_blocks;
1453
1454         retval = reserve_sparse_super2_last_group(rfs, meta_bmap);
1455         if (retval)
1456                 goto errout;
1457
1458         if (EXT2_DESC_SIZE(rfs->old_fs->super) ==
1459             EXT2_DESC_SIZE(rfs->new_fs->super) &&
1460             old_blocks == new_blocks) {
1461                 retval = 0;
1462                 goto errout;
1463         }
1464
1465         max_groups = fs->group_desc_count;
1466         if (max_groups > old_fs->group_desc_count)
1467                 max_groups = old_fs->group_desc_count;
1468         group_blk = old_fs->super->s_first_data_block;
1469         /*
1470          * If we're reducing the number of descriptor blocks, this
1471          * makes life easy.  :-)   We just have to mark some extra
1472          * blocks as free.
1473          */
1474         if (old_blocks > new_blocks) {
1475                 if (EXT2FS_CLUSTER_RATIO(fs) > 1) {
1476                         retval = ext2fs_allocate_block_bitmap(fs,
1477                                                         _("new meta blocks"),
1478                                                         &new_meta_bmap);
1479                         if (retval)
1480                                 goto errout;
1481
1482                         retval = mark_table_blocks(fs, new_meta_bmap);
1483                         if (retval)
1484                                 goto errout;
1485                 }
1486
1487                 for (i = 0; i < max_groups; i++) {
1488                         if (!ext2fs_bg_has_super(old_fs, i)) {
1489                                 group_blk += fs->super->s_blocks_per_group;
1490                                 continue;
1491                         }
1492                         group_end = group_blk + 1 + old_blocks;
1493                         for (blk = group_blk + 1 + new_blocks;
1494                              blk < group_end;) {
1495                                 if (new_meta_bmap == NULL ||
1496                                     !ext2fs_test_block_bitmap2(new_meta_bmap,
1497                                                                blk)) {
1498                                         cluster_freed =
1499                                                 EXT2FS_CLUSTER_RATIO(fs) -
1500                                                 (blk &
1501                                                  EXT2FS_CLUSTER_MASK(fs));
1502                                         if (cluster_freed > group_end - blk)
1503                                                 cluster_freed = group_end - blk;
1504                                         ext2fs_block_alloc_stats2(fs, blk, -1);
1505                                         blk += EXT2FS_CLUSTER_RATIO(fs);
1506                                         rfs->needed_blocks -= cluster_freed;
1507                                         continue;
1508                                 }
1509                                 rfs->needed_blocks--;
1510                                 blk++;
1511                         }
1512                         group_blk += fs->super->s_blocks_per_group;
1513                 }
1514                 retval = 0;
1515                 goto errout;
1516         }
1517         /*
1518          * If we're increasing the number of descriptor blocks, life
1519          * gets interesting....
1520          */
1521         meta_bg_size = EXT2_DESC_PER_BLOCK(fs->super);
1522         flex_bg = ext2fs_has_feature_flex_bg(fs->super);
1523         /* first reserve all of the existing fs meta blocks */
1524         for (i = 0; i < max_groups; i++) {
1525                 has_super = ext2fs_bg_has_super(fs, i);
1526                 if (has_super)
1527                         mark_fs_metablock(rfs, meta_bmap, i, group_blk);
1528
1529                 meta_bg = i / meta_bg_size;
1530                 if (!ext2fs_has_feature_meta_bg(fs->super) ||
1531                     (meta_bg < fs->super->s_first_meta_bg)) {
1532                         if (has_super) {
1533                                 for (blk = group_blk+1;
1534                                      blk < group_blk + 1 + new_blocks; blk++)
1535                                         mark_fs_metablock(rfs, meta_bmap,
1536                                                           i, blk);
1537                         }
1538                 } else {
1539                         if (has_super)
1540                                 has_super = 1;
1541                         if (((i % meta_bg_size) == 0) ||
1542                             ((i % meta_bg_size) == 1) ||
1543                             ((i % meta_bg_size) == (meta_bg_size-1)))
1544                                 mark_fs_metablock(rfs, meta_bmap, i,
1545                                                   group_blk + has_super);
1546                 }
1547
1548                 /*
1549                  * Reserve the existing meta blocks that we know
1550                  * aren't to be moved.
1551                  *
1552                  * For flex_bg file systems, in order to avoid
1553                  * overwriting fs metadata (especially inode table
1554                  * blocks) belonging to a different block group when
1555                  * we are relocating the inode tables, we need to
1556                  * reserve all existing fs metadata blocks.
1557                  */
1558                 if (ext2fs_block_bitmap_loc(fs, i))
1559                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1560                                  ext2fs_block_bitmap_loc(fs, i));
1561                 else if (flex_bg && i < old_fs->group_desc_count)
1562                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1563                                  ext2fs_block_bitmap_loc(old_fs, i));
1564
1565                 if (ext2fs_inode_bitmap_loc(fs, i))
1566                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1567                                  ext2fs_inode_bitmap_loc(fs, i));
1568                 else if (flex_bg && i < old_fs->group_desc_count)
1569                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks,
1570                                  ext2fs_inode_bitmap_loc(old_fs, i));
1571
1572                 if (ext2fs_inode_table_loc(fs, i))
1573                         ext2fs_mark_block_bitmap_range2(rfs->reserve_blocks,
1574                                         ext2fs_inode_table_loc(fs, i),
1575                                         fs->inode_blocks_per_group);
1576                 else if (flex_bg && i < old_fs->group_desc_count)
1577                         ext2fs_mark_block_bitmap_range2(rfs->reserve_blocks,
1578                                         ext2fs_inode_table_loc(old_fs, i),
1579                                         old_fs->inode_blocks_per_group);
1580
1581                 group_blk += rfs->new_fs->super->s_blocks_per_group;
1582         }
1583
1584         /* Allocate the missing data structures */
1585         for (i = 0; i < max_groups; i++) {
1586                 if (ext2fs_inode_table_loc(fs, i) &&
1587                     ext2fs_inode_bitmap_loc(fs, i) &&
1588                     ext2fs_block_bitmap_loc(fs, i))
1589                         continue;
1590
1591                 retval = ext2fs_allocate_group_table(fs, i,
1592                                                      rfs->reserve_blocks);
1593                 if (retval)
1594                         goto errout;
1595
1596                 /*
1597                  * For those structures that have changed, we need to
1598                  * do bookkeeping.
1599                  */
1600                 if (ext2fs_block_bitmap_loc(old_fs, i) !=
1601                     (blk = ext2fs_block_bitmap_loc(fs, i))) {
1602                         ext2fs_block_alloc_stats2(fs, blk, +1);
1603                         if (blk < ext2fs_blocks_count(old_fs->super) &&
1604                             ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
1605                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
1606                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
1607                                                          blk);
1608                 }
1609                 if (ext2fs_inode_bitmap_loc(old_fs, i) !=
1610                     (blk = ext2fs_inode_bitmap_loc(fs, i))) {
1611                         ext2fs_block_alloc_stats2(fs, blk, +1);
1612                         if (blk < ext2fs_blocks_count(old_fs->super) &&
1613                             ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
1614                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
1615                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
1616                                                          blk);
1617                 }
1618
1619                 /*
1620                  * The inode table, if we need to relocate it, is
1621                  * handled specially.  We have to reserve the blocks
1622                  * for both the old and the new inode table, since we
1623                  * can't have the inode table be destroyed during the
1624                  * block relocation phase.
1625                  */
1626                 if (ext2fs_inode_table_loc(fs, i) == ext2fs_inode_table_loc(old_fs, i))
1627                         continue;       /* inode table not moved */
1628
1629                 rfs->needed_blocks += fs->inode_blocks_per_group;
1630
1631                 /*
1632                  * Mark the new inode table as in use in the new block
1633                  * allocation bitmap, and move any blocks that might
1634                  * be necessary.
1635                  */
1636                 for (blk = ext2fs_inode_table_loc(fs, i), j=0;
1637                      j < fs->inode_blocks_per_group ; j++, blk++) {
1638                         ext2fs_block_alloc_stats2(fs, blk, +1);
1639                         if (blk < ext2fs_blocks_count(old_fs->super) &&
1640                             ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
1641                             !ext2fs_test_block_bitmap2(meta_bmap, blk))
1642                                 ext2fs_mark_block_bitmap2(rfs->move_blocks,
1643                                                          blk);
1644                 }
1645
1646                 /*
1647                  * Make sure the old inode table is reserved in the
1648                  * block reservation bitmap.
1649                  */
1650                 for (blk = ext2fs_inode_table_loc(rfs->old_fs, i), j=0;
1651                      j < fs->inode_blocks_per_group ; j++, blk++)
1652                         ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
1653         }
1654         retval = 0;
1655
1656 errout:
1657         if (new_meta_bmap)
1658                 ext2fs_free_block_bitmap(new_meta_bmap);
1659         if (meta_bmap)
1660                 ext2fs_free_block_bitmap(meta_bmap);
1661
1662         return retval;
1663 }
1664
1665 /*
1666  * This helper function tries to allocate a new block.  We try to
1667  * avoid hitting the original group descriptor blocks at least at
1668  * first, since we want to make it possible to recover from a badly
1669  * aborted resize operation as much as possible.
1670  *
1671  * In the future, I may further modify this routine to balance out
1672  * where we get the new blocks across the various block groups.
1673  * Ideally we would allocate blocks that corresponded with the block
1674  * group of the containing inode, and keep contiguous blocks
1675  * together.  However, this very difficult to do efficiently, since we
1676  * don't have the necessary information up front.
1677  */
1678
1679 #define AVOID_OLD       1
1680 #define DESPERATION     2
1681
1682 static void init_block_alloc(ext2_resize_t rfs)
1683 {
1684         rfs->alloc_state = AVOID_OLD;
1685         rfs->new_blk = rfs->new_fs->super->s_first_data_block;
1686 #if 0
1687         /* HACK for testing */
1688         if (ext2fs_blocks_count(rfs->new_fs->super) >
1689             ext2fs_blocks_count(rfs->old_fs->super))
1690                 rfs->new_blk = ext2fs_blocks_count(rfs->old_fs->super);
1691 #endif
1692 }
1693
1694 static blk64_t get_new_block(ext2_resize_t rfs)
1695 {
1696         ext2_filsys     fs = rfs->new_fs;
1697
1698         while (1) {
1699                 if (rfs->new_blk >= ext2fs_blocks_count(fs->super)) {
1700                         if (rfs->alloc_state == DESPERATION)
1701                                 return 0;
1702
1703 #ifdef RESIZE2FS_DEBUG
1704                         if (rfs->flags & RESIZE_DEBUG_BMOVE)
1705                                 printf("Going into desperation mode "
1706                                        "for block allocations\n");
1707 #endif
1708                         rfs->alloc_state = DESPERATION;
1709                         rfs->new_blk = fs->super->s_first_data_block;
1710                         continue;
1711                 }
1712                 if (ext2fs_test_block_bitmap2(fs->block_map, rfs->new_blk) ||
1713                     ext2fs_test_block_bitmap2(rfs->reserve_blocks,
1714                                              rfs->new_blk) ||
1715                     ((rfs->alloc_state == AVOID_OLD) &&
1716                      (rfs->new_blk < ext2fs_blocks_count(rfs->old_fs->super)) &&
1717                      ext2fs_test_block_bitmap2(rfs->old_fs->block_map,
1718                                               rfs->new_blk))) {
1719                         rfs->new_blk++;
1720                         continue;
1721                 }
1722                 return rfs->new_blk;
1723         }
1724 }
1725
1726 static errcode_t resize2fs_get_alloc_block(ext2_filsys fs,
1727                                            blk64_t goal EXT2FS_ATTR((unused)),
1728                                            blk64_t *ret)
1729 {
1730         ext2_resize_t rfs = (ext2_resize_t) fs->priv_data;
1731         blk64_t blk;
1732         int group;
1733
1734         blk = get_new_block(rfs);
1735         if (!blk)
1736                 return ENOSPC;
1737
1738 #ifdef RESIZE2FS_DEBUG
1739         if (rfs->flags & 0xF)
1740                 printf("get_alloc_block allocating %llu\n",
1741                        (unsigned long long) blk);
1742 #endif
1743
1744         ext2fs_mark_block_bitmap2(rfs->old_fs->block_map, blk);
1745         ext2fs_mark_block_bitmap2(rfs->new_fs->block_map, blk);
1746
1747         group = ext2fs_group_of_blk2(rfs->old_fs, blk);
1748         ext2fs_clear_block_uninit(rfs->old_fs, group);
1749         group = ext2fs_group_of_blk2(rfs->new_fs, blk);
1750         ext2fs_clear_block_uninit(rfs->new_fs, group);
1751
1752         *ret = (blk64_t) blk;
1753         return 0;
1754 }
1755
1756 static errcode_t block_mover(ext2_resize_t rfs)
1757 {
1758         blk64_t                 blk, old_blk, new_blk;
1759         ext2_filsys             fs = rfs->new_fs;
1760         ext2_filsys             old_fs = rfs->old_fs;
1761         errcode_t               retval;
1762         __u64                   c, size;
1763         int                     to_move, moved;
1764         ext2_badblocks_list     badblock_list = 0;
1765         int                     bb_modified = 0;
1766
1767         fs->get_alloc_block = resize2fs_get_alloc_block;
1768         old_fs->get_alloc_block = resize2fs_get_alloc_block;
1769
1770         retval = ext2fs_read_bb_inode(old_fs, &badblock_list);
1771         if (retval)
1772                 return retval;
1773
1774         new_blk = fs->super->s_first_data_block;
1775         if (!rfs->itable_buf) {
1776                 retval = ext2fs_get_array(fs->blocksize,
1777                                         fs->inode_blocks_per_group,
1778                                         &rfs->itable_buf);
1779                 if (retval)
1780                         goto errout;
1781         }
1782         retval = ext2fs_create_extent_table(&rfs->bmap, 0);
1783         if (retval)
1784                 goto errout;
1785
1786         /*
1787          * The first step is to figure out where all of the blocks
1788          * will go.
1789          */
1790         to_move = moved = 0;
1791         init_block_alloc(rfs);
1792         for (blk = B2C(old_fs->super->s_first_data_block);
1793              blk < ext2fs_blocks_count(old_fs->super);
1794              blk += EXT2FS_CLUSTER_RATIO(fs)) {
1795                 if (!ext2fs_test_block_bitmap2(old_fs->block_map, blk))
1796                         continue;
1797                 if (!ext2fs_test_block_bitmap2(rfs->move_blocks, blk))
1798                         continue;
1799                 if (ext2fs_badblocks_list_test(badblock_list, blk)) {
1800                         ext2fs_badblocks_list_del(badblock_list, blk);
1801                         bb_modified++;
1802                         continue;
1803                 }
1804
1805                 new_blk = get_new_block(rfs);
1806                 if (!new_blk) {
1807                         retval = ENOSPC;
1808                         goto errout;
1809                 }
1810                 ext2fs_block_alloc_stats2(fs, new_blk, +1);
1811                 ext2fs_add_extent_entry(rfs->bmap, B2C(blk), B2C(new_blk));
1812                 to_move++;
1813         }
1814
1815         if (to_move == 0) {
1816                 if (rfs->bmap) {
1817                         ext2fs_free_extent_table(rfs->bmap);
1818                         rfs->bmap = 0;
1819                 }
1820                 retval = 0;
1821                 goto errout;
1822         }
1823
1824         /*
1825          * Step two is to actually move the blocks
1826          */
1827         retval =  ext2fs_iterate_extent(rfs->bmap, 0, 0, 0);
1828         if (retval) goto errout;
1829
1830         if (rfs->progress) {
1831                 retval = (rfs->progress)(rfs, E2_RSZ_BLOCK_RELOC_PASS,
1832                                          0, to_move);
1833                 if (retval)
1834                         goto errout;
1835         }
1836         while (1) {
1837                 retval = ext2fs_iterate_extent(rfs->bmap, &old_blk, &new_blk, &size);
1838                 if (retval) goto errout;
1839                 if (!size)
1840                         break;
1841                 old_blk = C2B(old_blk);
1842                 new_blk = C2B(new_blk);
1843                 size = C2B(size);
1844 #ifdef RESIZE2FS_DEBUG
1845                 if (rfs->flags & RESIZE_DEBUG_BMOVE)
1846                         printf("Moving %llu blocks %llu->%llu\n",
1847                                (unsigned long long) size,
1848                                (unsigned long long) old_blk,
1849                                (unsigned long long) new_blk);
1850 #endif
1851                 do {
1852                         c = size;
1853                         if (c > fs->inode_blocks_per_group)
1854                                 c = fs->inode_blocks_per_group;
1855                         retval = io_channel_read_blk64(fs->io, old_blk, c,
1856                                                        rfs->itable_buf);
1857                         if (retval) goto errout;
1858                         retval = io_channel_write_blk64(fs->io, new_blk, c,
1859                                                         rfs->itable_buf);
1860                         if (retval) goto errout;
1861                         size -= c;
1862                         new_blk += c;
1863                         old_blk += c;
1864                         moved += c;
1865                         if (rfs->progress) {
1866                                 retval = (rfs->progress)(rfs,
1867                                                 E2_RSZ_BLOCK_RELOC_PASS,
1868                                                 moved, to_move);
1869                                 if (retval)
1870                                         goto errout;
1871                         }
1872                 } while (size > 0);
1873         }
1874
1875         io_channel_flush(fs->io);
1876
1877 errout:
1878         if (badblock_list) {
1879                 if (!retval && bb_modified)
1880                         retval = ext2fs_update_bb_inode(old_fs,
1881                                                         badblock_list);
1882                 ext2fs_badblocks_list_free(badblock_list);
1883         }
1884         return retval;
1885 }
1886
1887
1888 /* --------------------------------------------------------------------
1889  *
1890  * Resize processing, phase 3
1891  *
1892  * --------------------------------------------------------------------
1893  */
1894
1895
1896 /*
1897  * The extent translation table is stored in clusters so we need to
1898  * take special care when mapping a source block number to its
1899  * destination block number.
1900  */
1901 static __u64 extent_translate(ext2_filsys fs, ext2_extent extent, __u64 old_loc)
1902 {
1903         __u64 new_block = C2B(ext2fs_extent_translate(extent, B2C(old_loc)));
1904
1905         if (new_block != 0)
1906                 new_block += old_loc & (EXT2FS_CLUSTER_RATIO(fs) - 1);
1907         return new_block;
1908 }
1909
1910 struct process_block_struct {
1911         ext2_resize_t           rfs;
1912         ext2_ino_t              ino;
1913         ext2_ino_t              old_ino;
1914         struct ext2_inode *     inode;
1915         errcode_t               error;
1916         int                     is_dir;
1917         int                     changed;
1918         int                     has_extents;
1919 };
1920
1921 static int process_block(ext2_filsys fs, blk64_t        *block_nr,
1922                          e2_blkcnt_t blockcnt,
1923                          blk64_t ref_block EXT2FS_ATTR((unused)),
1924                          int ref_offset EXT2FS_ATTR((unused)), void *priv_data)
1925 {
1926         struct process_block_struct *pb;
1927         errcode_t       retval;
1928         blk64_t         block, new_block;
1929         int             ret = 0;
1930
1931         pb = (struct process_block_struct *) priv_data;
1932         block = *block_nr;
1933         if (pb->rfs->bmap) {
1934                 new_block = extent_translate(fs, pb->rfs->bmap, block);
1935                 if (new_block) {
1936                         *block_nr = new_block;
1937                         ret |= BLOCK_CHANGED;
1938                         pb->changed = 1;
1939 #ifdef RESIZE2FS_DEBUG
1940                         if (pb->rfs->flags & RESIZE_DEBUG_BMOVE)
1941                                 printf("ino=%u, blockcnt=%lld, %llu->%llu\n",
1942                                        pb->old_ino, (long long) blockcnt,
1943                                        (unsigned long long) block,
1944                                        (unsigned long long) new_block);
1945 #endif
1946                         block = new_block;
1947                 }
1948         }
1949
1950         if (pb->is_dir) {
1951                 retval = ext2fs_add_dir_block2(fs->dblist, pb->ino,
1952                                                block, (int) blockcnt);
1953                 if (retval) {
1954                         pb->error = retval;
1955                         ret |= BLOCK_ABORT;
1956                 }
1957         }
1958         return ret;
1959 }
1960
1961 /*
1962  * Progress callback
1963  */
1964 static errcode_t progress_callback(ext2_filsys fs,
1965                                    ext2_inode_scan scan EXT2FS_ATTR((unused)),
1966                                    dgrp_t group, void * priv_data)
1967 {
1968         ext2_resize_t rfs = (ext2_resize_t) priv_data;
1969         errcode_t               retval;
1970
1971         /*
1972          * This check is to protect against old ext2 libraries.  It
1973          * shouldn't be needed against new libraries.
1974          */
1975         if ((group+1) == 0)
1976                 return 0;
1977
1978         if (rfs->progress) {
1979                 io_channel_flush(fs->io);
1980                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_SCAN_PASS,
1981                                          group+1, fs->group_desc_count);
1982                 if (retval)
1983                         return retval;
1984         }
1985
1986         return 0;
1987 }
1988
1989 static errcode_t migrate_ea_block(ext2_resize_t rfs, ext2_ino_t ino,
1990                                   struct ext2_inode *inode, int *changed)
1991 {
1992         char *buf = NULL;
1993         blk64_t new_block;
1994         errcode_t err = 0;
1995
1996         /* No EA block or no remapping?  Quit early. */
1997         if (ext2fs_file_acl_block(rfs->old_fs, inode) == 0 || !rfs->bmap)
1998                 return 0;
1999         new_block = extent_translate(rfs->old_fs, rfs->bmap,
2000                 ext2fs_file_acl_block(rfs->old_fs, inode));
2001         if (new_block == 0)
2002                 return 0;
2003
2004         /* Set the new ACL block */
2005         ext2fs_file_acl_block_set(rfs->old_fs, inode, new_block);
2006
2007         /* Update checksum */
2008         if (ext2fs_has_feature_metadata_csum(rfs->new_fs->super)) {
2009                 err = ext2fs_get_mem(rfs->old_fs->blocksize, &buf);
2010                 if (err)
2011                         return err;
2012                 rfs->old_fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
2013                 err = ext2fs_read_ext_attr3(rfs->old_fs, new_block, buf, ino);
2014                 rfs->old_fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
2015                 if (err)
2016                         goto out;
2017                 err = ext2fs_write_ext_attr3(rfs->old_fs, new_block, buf, ino);
2018                 if (err)
2019                         goto out;
2020         }
2021         *changed = 1;
2022
2023 out:
2024         ext2fs_free_mem(&buf);
2025         return err;
2026 }
2027
2028 static void quiet_com_err_proc(const char *whoami EXT2FS_ATTR((unused)),
2029                                errcode_t code EXT2FS_ATTR((unused)),
2030                                const char *fmt EXT2FS_ATTR((unused)),
2031                                va_list args EXT2FS_ATTR((unused)))
2032 {
2033 }
2034
2035 static int fix_ea_entries(ext2_extent imap, struct ext2_ext_attr_entry *entry,
2036                           struct ext2_ext_attr_entry *end, ext2_ino_t last_ino)
2037 {
2038         int modified = 0;
2039         ext2_ino_t new_ino;
2040
2041         while (entry < end && !EXT2_EXT_IS_LAST_ENTRY(entry)) {
2042                 if (entry->e_value_inum > last_ino) {
2043                         new_ino = ext2fs_extent_translate(imap,
2044                                                           entry->e_value_inum);
2045                         entry->e_value_inum = new_ino;
2046                         modified = 1;
2047                 }
2048                 entry = EXT2_EXT_ATTR_NEXT(entry);
2049         }
2050         return modified;
2051 }
2052
2053 static int fix_ea_ibody_entries(ext2_extent imap,
2054                                 struct ext2_inode_large *inode, int inode_size,
2055                                 ext2_ino_t last_ino)
2056 {
2057         struct ext2_ext_attr_entry *start, *end;
2058         __u32 *ea_magic;
2059
2060         if (inode->i_extra_isize == 0)
2061                 return 0;
2062
2063         ea_magic = (__u32 *)((char *)inode + EXT2_GOOD_OLD_INODE_SIZE +
2064                                 inode->i_extra_isize);
2065         if (*ea_magic != EXT2_EXT_ATTR_MAGIC)
2066                 return 0;
2067
2068         start = (struct ext2_ext_attr_entry *)(ea_magic + 1);
2069         end = (struct ext2_ext_attr_entry *)((char *)inode + inode_size);
2070
2071         return fix_ea_entries(imap, start, end, last_ino);
2072 }
2073
2074 static int fix_ea_block_entries(ext2_extent imap, char *block_buf,
2075                                 unsigned int blocksize, ext2_ino_t last_ino)
2076 {
2077         struct ext2_ext_attr_header *header;
2078         struct ext2_ext_attr_entry *start, *end;
2079
2080         header = (struct ext2_ext_attr_header *)block_buf;
2081         start = (struct ext2_ext_attr_entry *)(header+1);
2082         end = (struct ext2_ext_attr_entry *)(block_buf + blocksize);
2083
2084         return fix_ea_entries(imap, start, end, last_ino);
2085 }
2086
2087 /* A simple LRU cache to check recently processed blocks. */
2088 struct blk_cache {
2089         int cursor;
2090         blk64_t blks[4];
2091 };
2092
2093 #define BLK_IN_CACHE(b,c) ((b) == (c).blks[0] || (b) == (c).blks[1] || \
2094                            (b) == (c).blks[2] || (b) == (c).blks[3])
2095 #define BLK_ADD_CACHE(b,c) {                    \
2096         (c).blks[(c).cursor] = (b);             \
2097         (c).cursor = ((c).cursor + 1) % 4;      \
2098 }
2099
2100 static errcode_t fix_ea_inode_refs(ext2_resize_t rfs, struct ext2_inode *inode,
2101                                    char *block_buf, ext2_ino_t last_ino)
2102 {
2103         ext2_filsys     fs = rfs->new_fs;
2104         ext2_inode_scan scan = NULL;
2105         ext2_ino_t      ino;
2106         int             inode_size = EXT2_INODE_SIZE(fs->super);
2107         blk64_t         blk;
2108         int             modified;
2109         struct blk_cache blk_cache;
2110         struct ext2_ext_attr_header *header;
2111         errcode_t               retval;
2112
2113         memset(&blk_cache, 0, sizeof(blk_cache));
2114
2115         header = (struct ext2_ext_attr_header *)block_buf;
2116
2117         retval = ext2fs_open_inode_scan(fs, 0, &scan);
2118         if (retval)
2119                 goto out;
2120
2121         while (1) {
2122                 retval = ext2fs_get_next_inode_full(scan, &ino, inode,
2123                                                     inode_size);
2124                 if (retval)
2125                         goto out;
2126                 if (!ino)
2127                         break;
2128
2129                 if (inode->i_links_count == 0 && ino != EXT2_RESIZE_INO)
2130                         continue; /* inode not in use */
2131
2132                 if (inode_size != EXT2_GOOD_OLD_INODE_SIZE) {
2133                         modified = fix_ea_ibody_entries(rfs->imap,
2134                                         (struct ext2_inode_large *)inode,
2135                                         inode_size, last_ino);
2136                         if (modified) {
2137                                 retval = ext2fs_write_inode_full(fs, ino, inode,
2138                                                                  inode_size);
2139                                 if (retval)
2140                                         goto out;
2141                         }
2142                 }
2143
2144                 blk = ext2fs_file_acl_block(fs, inode);
2145                 if (blk && !BLK_IN_CACHE(blk, blk_cache)) {
2146                         retval = ext2fs_read_ext_attr3(fs, blk, block_buf, ino);
2147                         if (retval)
2148                                 goto out;
2149
2150                         modified = fix_ea_block_entries(rfs->imap, block_buf,
2151                                                         fs->blocksize,
2152                                                         last_ino);
2153                         if (modified) {
2154                                 retval = ext2fs_write_ext_attr3(fs, blk,
2155                                                                 block_buf, ino);
2156                                 if (retval)
2157                                         goto out;
2158                                 /*
2159                                  * If refcount is greater than 1, we might see
2160                                  * the same block referenced by other inodes
2161                                  * later.
2162                                  */
2163                                 if (header->h_refcount > 1)
2164                                         BLK_ADD_CACHE(blk, blk_cache);
2165                         }
2166                 }
2167         }
2168         retval = 0;
2169 out:
2170         if (scan)
2171                 ext2fs_close_inode_scan(scan);
2172         return retval;
2173
2174 }
2175 static errcode_t inode_scan_and_fix(ext2_resize_t rfs)
2176 {
2177         struct process_block_struct     pb;
2178         ext2_ino_t              ino, new_inode;
2179         struct ext2_inode       *inode = NULL;
2180         ext2_inode_scan         scan = NULL;
2181         errcode_t               retval;
2182         char                    *block_buf = 0;
2183         ext2_ino_t              start_to_move;
2184         int                     inode_size;
2185         int                     update_ea_inode_refs = 0;
2186
2187         if ((rfs->old_fs->group_desc_count <=
2188              rfs->new_fs->group_desc_count) &&
2189             !rfs->bmap)
2190                 return 0;
2191
2192         set_com_err_hook(quiet_com_err_proc);
2193
2194         retval = ext2fs_open_inode_scan(rfs->old_fs, 0, &scan);
2195         if (retval) goto errout;
2196
2197         retval = ext2fs_init_dblist(rfs->old_fs, 0);
2198         if (retval) goto errout;
2199         retval = ext2fs_get_array(rfs->old_fs->blocksize, 3, &block_buf);
2200         if (retval) goto errout;
2201
2202         start_to_move = (rfs->new_fs->group_desc_count *
2203                          rfs->new_fs->super->s_inodes_per_group);
2204
2205         if (rfs->progress) {
2206                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_SCAN_PASS,
2207                                          0, rfs->old_fs->group_desc_count);
2208                 if (retval)
2209                         goto errout;
2210         }
2211         ext2fs_set_inode_callback(scan, progress_callback, (void *) rfs);
2212         pb.rfs = rfs;
2213         pb.inode = inode;
2214         pb.error = 0;
2215         new_inode = EXT2_FIRST_INODE(rfs->new_fs->super);
2216         inode_size = EXT2_INODE_SIZE(rfs->new_fs->super);
2217         inode = malloc(inode_size);
2218         if (!inode) {
2219                 retval = ENOMEM;
2220                 goto errout;
2221         }
2222         /*
2223          * First, copy all of the inodes that need to be moved
2224          * elsewhere in the inode table
2225          */
2226         while (1) {
2227                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, inode_size);
2228                 if (retval) goto errout;
2229                 if (!ino)
2230                         break;
2231
2232                 if (inode->i_links_count == 0 && ino != EXT2_RESIZE_INO)
2233                         continue; /* inode not in use */
2234
2235                 pb.is_dir = LINUX_S_ISDIR(inode->i_mode);
2236                 pb.changed = 0;
2237
2238                 /* Remap EA block */
2239                 retval = migrate_ea_block(rfs, ino, inode, &pb.changed);
2240                 if (retval)
2241                         goto errout;
2242
2243                 new_inode = ino;
2244                 if (ino <= start_to_move)
2245                         goto remap_blocks; /* Don't need to move inode. */
2246
2247                 /*
2248                  * Find a new inode.  Now that extents and directory blocks
2249                  * are tied to the inode number through the checksum, we must
2250                  * set up the new inode before we start rewriting blocks.
2251                  */
2252                 retval = ext2fs_new_inode(rfs->new_fs, 0, 0, 0, &new_inode);
2253                 if (retval)
2254                         goto errout;
2255
2256                 ext2fs_inode_alloc_stats2(rfs->new_fs, new_inode, +1,
2257                                           pb.is_dir);
2258                 /*
2259                  * i_ctime field in xattr inodes contain a portion of the ref
2260                  * count, do not overwrite.
2261                  */
2262                 if (inode->i_flags & EXT4_EA_INODE_FL)
2263                         update_ea_inode_refs = 1;
2264                 else
2265                         inode->i_ctime = rfs->old_fs->now ?
2266                                 rfs->old_fs->now : time(0);
2267
2268                 retval = ext2fs_write_inode_full(rfs->old_fs, new_inode,
2269                                                 inode, inode_size);
2270                 if (retval)
2271                         goto errout;
2272                 pb.changed = 0;
2273
2274 #ifdef RESIZE2FS_DEBUG
2275                 if (rfs->flags & RESIZE_DEBUG_INODEMAP)
2276                         printf("Inode moved %u->%u\n", ino, new_inode);
2277 #endif
2278                 if (!rfs->imap) {
2279                         retval = ext2fs_create_extent_table(&rfs->imap, 0);
2280                         if (retval)
2281                                 goto errout;
2282                 }
2283                 ext2fs_add_extent_entry(rfs->imap, ino, new_inode);
2284
2285 remap_blocks:
2286                 if (pb.changed)
2287                         retval = ext2fs_write_inode_full(rfs->old_fs,
2288                                                          new_inode,
2289                                                          inode, inode_size);
2290                 if (retval)
2291                         goto errout;
2292
2293                 /*
2294                  * Update inodes to point to new blocks; schedule directory
2295                  * blocks for inode remapping.  Need to write out dir blocks
2296                  * with new inode numbers if we have metadata_csum enabled.
2297                  */
2298                 rfs->old_fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
2299                 if (ext2fs_inode_has_valid_blocks2(rfs->old_fs, inode) &&
2300                     (rfs->bmap || pb.is_dir)) {
2301                         pb.ino = new_inode;
2302                         pb.old_ino = ino;
2303                         pb.has_extents = inode->i_flags & EXT4_EXTENTS_FL;
2304                         retval = ext2fs_block_iterate3(rfs->old_fs,
2305                                                        new_inode, 0, block_buf,
2306                                                        process_block, &pb);
2307                         if (retval)
2308                                 goto errout;
2309                         if (pb.error) {
2310                                 retval = pb.error;
2311                                 goto errout;
2312                         }
2313                 } else if ((inode->i_flags & EXT4_INLINE_DATA_FL) &&
2314                            (rfs->bmap || pb.is_dir)) {
2315                         /* inline data dir; update it too */
2316                         retval = ext2fs_add_dir_block2(rfs->old_fs->dblist,
2317                                                        new_inode, 0, 0);
2318                         if (retval)
2319                                 goto errout;
2320                 }
2321
2322                 /* Fix up extent block checksums with the new inode number */
2323                 if (ext2fs_has_feature_metadata_csum(rfs->old_fs->super) &&
2324                     (inode->i_flags & EXT4_EXTENTS_FL)) {
2325                         retval = ext2fs_fix_extents_checksums(rfs->old_fs,
2326                                                               new_inode, NULL);
2327                         if (retval)
2328                                 goto errout;
2329                 }
2330         }
2331
2332         if (update_ea_inode_refs &&
2333             ext2fs_has_feature_ea_inode(rfs->new_fs->super)) {
2334                 retval = fix_ea_inode_refs(rfs, inode, block_buf,
2335                                            start_to_move);
2336                 if (retval)
2337                         goto errout;
2338         }
2339         io_channel_flush(rfs->old_fs->io);
2340
2341 errout:
2342         reset_com_err_hook();
2343         rfs->old_fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
2344         if (rfs->bmap) {
2345                 ext2fs_free_extent_table(rfs->bmap);
2346                 rfs->bmap = 0;
2347         }
2348         if (scan)
2349                 ext2fs_close_inode_scan(scan);
2350         if (block_buf)
2351                 ext2fs_free_mem(&block_buf);
2352         free(inode);
2353         return retval;
2354 }
2355
2356 /* --------------------------------------------------------------------
2357  *
2358  * Resize processing, phase 4.
2359  *
2360  * --------------------------------------------------------------------
2361  */
2362
2363 struct istruct {
2364         ext2_resize_t rfs;
2365         errcode_t       err;
2366         unsigned int    max_dirs;
2367         unsigned int    num;
2368 };
2369
2370 static int check_and_change_inodes(ext2_ino_t dir,
2371                                    int entry EXT2FS_ATTR((unused)),
2372                                    struct ext2_dir_entry *dirent, int offset,
2373                                    int  blocksize EXT2FS_ATTR((unused)),
2374                                    char *buf EXT2FS_ATTR((unused)),
2375                                    void *priv_data)
2376 {
2377         struct istruct *is = (struct istruct *) priv_data;
2378         struct ext2_inode       inode;
2379         ext2_ino_t              new_inode;
2380         errcode_t               retval;
2381         int                     ret = 0;
2382
2383         if (is->rfs->progress && offset == 0) {
2384                 io_channel_flush(is->rfs->old_fs->io);
2385                 is->err = (is->rfs->progress)(is->rfs,
2386                                               E2_RSZ_INODE_REF_UPD_PASS,
2387                                               ++is->num, is->max_dirs);
2388                 if (is->err)
2389                         return DIRENT_ABORT;
2390         }
2391
2392         /*
2393          * If we have checksums enabled and the inode wasn't present in the
2394          * old fs, then we must rewrite all dir blocks with new checksums.
2395          */
2396         if (ext2fs_has_feature_metadata_csum(is->rfs->old_fs->super) &&
2397             !ext2fs_test_inode_bitmap2(is->rfs->old_fs->inode_map, dir))
2398                 ret |= DIRENT_CHANGED;
2399
2400         if (!dirent->inode)
2401                 return ret;
2402
2403         new_inode = ext2fs_extent_translate(is->rfs->imap, dirent->inode);
2404
2405         if (!new_inode)
2406                 return ret;
2407 #ifdef RESIZE2FS_DEBUG
2408         if (is->rfs->flags & RESIZE_DEBUG_INODEMAP)
2409                 printf("Inode translate (dir=%u, name=%.*s, %u->%u)\n",
2410                        dir, ext2fs_dirent_name_len(dirent), dirent->name,
2411                        dirent->inode, new_inode);
2412 #endif
2413
2414         dirent->inode = new_inode;
2415
2416         /* Update the directory mtime and ctime */
2417         retval = ext2fs_read_inode(is->rfs->old_fs, dir, &inode);
2418         if (retval == 0) {
2419                 inode.i_mtime = inode.i_ctime = is->rfs->old_fs->now ?
2420                         is->rfs->old_fs->now : time(0);
2421                 is->err = ext2fs_write_inode(is->rfs->old_fs, dir, &inode);
2422                 if (is->err)
2423                         return ret | DIRENT_ABORT;
2424         }
2425
2426         return ret | DIRENT_CHANGED;
2427 }
2428
2429 static errcode_t inode_ref_fix(ext2_resize_t rfs)
2430 {
2431         errcode_t               retval;
2432         struct istruct          is;
2433
2434         if (!rfs->imap)
2435                 return 0;
2436
2437         /*
2438          * Now, we iterate over all of the directories to update the
2439          * inode references
2440          */
2441         is.num = 0;
2442         is.max_dirs = ext2fs_dblist_count2(rfs->old_fs->dblist);
2443         is.rfs = rfs;
2444         is.err = 0;
2445
2446         if (rfs->progress) {
2447                 retval = (rfs->progress)(rfs, E2_RSZ_INODE_REF_UPD_PASS,
2448                                          0, is.max_dirs);
2449                 if (retval)
2450                         goto errout;
2451         }
2452
2453         rfs->old_fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
2454         retval = ext2fs_dblist_dir_iterate(rfs->old_fs->dblist,
2455                                            DIRENT_FLAG_INCLUDE_EMPTY, 0,
2456                                            check_and_change_inodes, &is);
2457         rfs->old_fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
2458         if (retval)
2459                 goto errout;
2460         if (is.err) {
2461                 retval = is.err;
2462                 goto errout;
2463         }
2464
2465         if (rfs->progress && (is.num < is.max_dirs))
2466                 (rfs->progress)(rfs, E2_RSZ_INODE_REF_UPD_PASS,
2467                                 is.max_dirs, is.max_dirs);
2468
2469 errout:
2470         ext2fs_free_extent_table(rfs->imap);
2471         rfs->imap = 0;
2472         return retval;
2473 }
2474
2475
2476 /* --------------------------------------------------------------------
2477  *
2478  * Resize processing, phase 5.
2479  *
2480  * In this phase we actually move the inode table around, and then
2481  * update the summary statistics.  This is scary, since aborting here
2482  * will potentially scramble the filesystem.  (We are moving the
2483  * inode tables around in place, and so the potential for lost data,
2484  * or at the very least scrambling the mapping between filenames and
2485  * inode numbers is very high in case of a power failure here.)
2486  * --------------------------------------------------------------------
2487  */
2488
2489
2490 /*
2491  * A very scary routine --- this one moves the inode table around!!!
2492  *
2493  * After this you have to use the rfs->new_fs file handle to read and
2494  * write inodes.
2495  */
2496 static errcode_t move_itables(ext2_resize_t rfs)
2497 {
2498         int             n, num, size;
2499         long long       diff;
2500         dgrp_t          i, max_groups;
2501         ext2_filsys     fs = rfs->new_fs;
2502         char            *cp;
2503         blk64_t         old_blk, new_blk, blk, cluster_freed;
2504         errcode_t       retval;
2505         int             to_move, moved;
2506         unsigned int    j;
2507         ext2fs_block_bitmap     new_bmap = NULL;
2508
2509         max_groups = fs->group_desc_count;
2510         if (max_groups > rfs->old_fs->group_desc_count)
2511                 max_groups = rfs->old_fs->group_desc_count;
2512
2513         size = fs->blocksize * fs->inode_blocks_per_group;
2514         if (!rfs->itable_buf) {
2515                 retval = ext2fs_get_mem(size, &rfs->itable_buf);
2516                 if (retval)
2517                         return retval;
2518         }
2519
2520         if (EXT2FS_CLUSTER_RATIO(fs) > 1) {
2521                 retval = ext2fs_allocate_block_bitmap(fs, _("new meta blocks"),
2522                                                       &new_bmap);
2523                 if (retval)
2524                         return retval;
2525
2526                 retval = mark_table_blocks(fs, new_bmap);
2527                 if (retval)
2528                         goto errout;
2529         }
2530
2531         /*
2532          * Figure out how many inode tables we need to move
2533          */
2534         to_move = moved = 0;
2535         for (i=0; i < max_groups; i++)
2536                 if (ext2fs_inode_table_loc(rfs->old_fs, i) !=
2537                     ext2fs_inode_table_loc(fs, i))
2538                         to_move++;
2539
2540         if (to_move == 0) {
2541                 retval = 0;
2542                 goto errout;
2543         }
2544
2545         if (rfs->progress) {
2546                 retval = rfs->progress(rfs, E2_RSZ_MOVE_ITABLE_PASS,
2547                                        0, to_move);
2548                 if (retval)
2549                         goto errout;
2550         }
2551
2552         rfs->old_fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
2553
2554         for (i=0; i < max_groups; i++) {
2555                 old_blk = ext2fs_inode_table_loc(rfs->old_fs, i);
2556                 new_blk = ext2fs_inode_table_loc(fs, i);
2557                 diff = new_blk - old_blk;
2558
2559 #ifdef RESIZE2FS_DEBUG
2560                 if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
2561                         printf("Itable move group %d block %llu->%llu (diff %lld)\n",
2562                                i, (unsigned long long) old_blk,
2563                                (unsigned long long) new_blk, diff);
2564 #endif
2565
2566                 if (!diff)
2567                         continue;
2568                 if (diff < 0)
2569                         diff = 0;
2570
2571                 retval = io_channel_read_blk64(fs->io, old_blk,
2572                                                fs->inode_blocks_per_group,
2573                                                rfs->itable_buf);
2574                 if (retval)
2575                         goto errout;
2576                 /*
2577                  * The end of the inode table segment often contains
2578                  * all zeros, and we're often only moving the inode
2579                  * table down a block or two.  If so, we can optimize
2580                  * things by not rewriting blocks that we know to be zero
2581                  * already.
2582                  */
2583                 for (cp = rfs->itable_buf+size-1, n=0; n < size; n++, cp--)
2584                         if (*cp)
2585                                 break;
2586                 n = n >> EXT2_BLOCK_SIZE_BITS(fs->super);
2587 #ifdef RESIZE2FS_DEBUG
2588                 if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
2589                         printf("%d blocks of zeros...\n", n);
2590 #endif
2591                 num = fs->inode_blocks_per_group;
2592                 if (n > diff)
2593                         num -= n;
2594
2595                 retval = io_channel_write_blk64(fs->io, new_blk,
2596                                                 num, rfs->itable_buf);
2597                 if (retval) {
2598                         io_channel_write_blk64(fs->io, old_blk,
2599                                                num, rfs->itable_buf);
2600                         goto errout;
2601                 }
2602                 if (n > diff) {
2603                         retval = io_channel_write_blk64(fs->io,
2604                               old_blk + fs->inode_blocks_per_group,
2605                               diff, (rfs->itable_buf +
2606                                      (fs->inode_blocks_per_group - diff) *
2607                                      fs->blocksize));
2608                         if (retval)
2609                                 goto errout;
2610                 }
2611
2612                 for (blk = ext2fs_inode_table_loc(rfs->old_fs, i), j=0;
2613                      j < fs->inode_blocks_per_group;) {
2614                         if (new_bmap == NULL ||
2615                             !ext2fs_test_block_bitmap2(new_bmap, blk)) {
2616                                 ext2fs_block_alloc_stats2(fs, blk, -1);
2617                                 cluster_freed = EXT2FS_CLUSTER_RATIO(fs) -
2618                                                 (blk & EXT2FS_CLUSTER_MASK(fs));
2619                                 blk += cluster_freed;
2620                                 j += cluster_freed;
2621                                 continue;
2622                         }
2623                         blk++;
2624                         j++;
2625                 }
2626
2627                 ext2fs_inode_table_loc_set(rfs->old_fs, i, new_blk);
2628                 ext2fs_group_desc_csum_set(rfs->old_fs, i);
2629                 ext2fs_mark_super_dirty(rfs->old_fs);
2630                 ext2fs_flush(rfs->old_fs);
2631
2632                 if (rfs->progress) {
2633                         retval = rfs->progress(rfs, E2_RSZ_MOVE_ITABLE_PASS,
2634                                                ++moved, to_move);
2635                         if (retval)
2636                                 goto errout;
2637                 }
2638         }
2639         mark_table_blocks(fs, fs->block_map);
2640         ext2fs_flush(fs);
2641 #ifdef RESIZE2FS_DEBUG
2642         if (rfs->flags & RESIZE_DEBUG_ITABLEMOVE)
2643                 printf("Inode table move finished.\n");
2644 #endif
2645         retval = 0;
2646
2647 errout:
2648         if (new_bmap)
2649                 ext2fs_free_block_bitmap(new_bmap);
2650         return retval;
2651 }
2652
2653 /*
2654  * This function is used when expanding a file system.  It frees the
2655  * superblock and block group descriptor blocks from the block group
2656  * which is no longer the last block group.
2657  */
2658 static errcode_t clear_sparse_super2_last_group(ext2_resize_t rfs)
2659 {
2660         ext2_filsys     fs = rfs->new_fs;
2661         ext2_filsys     old_fs = rfs->old_fs;
2662         errcode_t       retval;
2663         dgrp_t          old_last_bg = rfs->old_fs->group_desc_count - 1;
2664         dgrp_t          last_bg = fs->group_desc_count - 1;
2665         blk64_t         sb, old_desc;
2666         blk_t           num;
2667
2668         if (!ext2fs_has_feature_sparse_super2(fs->super))
2669                 return 0;
2670
2671         if (last_bg <= old_last_bg)
2672                 return 0;
2673
2674         if (fs->super->s_backup_bgs[0] == old_fs->super->s_backup_bgs[0] &&
2675             fs->super->s_backup_bgs[1] == old_fs->super->s_backup_bgs[1])
2676                 return 0;
2677
2678         if (old_fs->super->s_backup_bgs[0] != old_last_bg &&
2679             old_fs->super->s_backup_bgs[1] != old_last_bg)
2680                 return 0;
2681
2682         if (fs->super->s_backup_bgs[0] == old_last_bg ||
2683             fs->super->s_backup_bgs[1] == old_last_bg)
2684                 return 0;
2685
2686         if (old_last_bg == 0)
2687                 return 0;
2688
2689         retval = ext2fs_super_and_bgd_loc2(rfs->old_fs, old_last_bg,
2690                                            &sb, &old_desc, NULL, &num);
2691         if (retval)
2692                 return retval;
2693
2694         if (sb)
2695                 ext2fs_unmark_block_bitmap2(fs->block_map, sb);
2696         if (old_desc)
2697                 ext2fs_unmark_block_bitmap_range2(fs->block_map, old_desc, num);
2698         return 0;
2699 }
2700
2701 /*
2702  * This function is used when shrinking a file system.  We need to
2703  * utilize blocks from what will be the new last block group for the
2704  * backup superblock and block group descriptor blocks.
2705  * Unfortunately, those blocks may be used by other files or fs
2706  * metadata blocks.  We need to mark them as being in use.
2707  */
2708 static errcode_t reserve_sparse_super2_last_group(ext2_resize_t rfs,
2709                                                  ext2fs_block_bitmap meta_bmap)
2710 {
2711         ext2_filsys     fs = rfs->new_fs;
2712         ext2_filsys     old_fs = rfs->old_fs;
2713         errcode_t       retval;
2714         dgrp_t          old_last_bg = rfs->old_fs->group_desc_count - 1;
2715         dgrp_t          last_bg = fs->group_desc_count - 1;
2716         dgrp_t          g;
2717         blk64_t         blk, sb, old_desc;
2718         blk_t           i, num;
2719         int             realloc = 0;
2720
2721         if (!ext2fs_has_feature_sparse_super2(fs->super))
2722                 return 0;
2723
2724         if (last_bg >= old_last_bg)
2725                 return 0;
2726
2727         if (fs->super->s_backup_bgs[0] == old_fs->super->s_backup_bgs[0] &&
2728             fs->super->s_backup_bgs[1] == old_fs->super->s_backup_bgs[1])
2729                 return 0;
2730
2731         if (fs->super->s_backup_bgs[0] != last_bg &&
2732             fs->super->s_backup_bgs[1] != last_bg)
2733                 return 0;
2734
2735         if (old_fs->super->s_backup_bgs[0] == last_bg ||
2736             old_fs->super->s_backup_bgs[1] == last_bg)
2737                 return 0;
2738
2739         retval = ext2fs_super_and_bgd_loc2(rfs->new_fs, last_bg,
2740                                            &sb, &old_desc, NULL, &num);
2741         if (retval)
2742                 return retval;
2743
2744         if (last_bg && !sb) {
2745                 fputs(_("Should never happen!  No sb in last super_sparse bg?\n"),
2746                       stderr);
2747                 exit(1);
2748         }
2749         if (old_desc && old_desc != sb+1) {
2750                 fputs(_("Should never happen!  Unexpected old_desc in "
2751                         "super_sparse bg?\n"),
2752                       stderr);
2753                 exit(1);
2754         }
2755         num = (old_desc) ? num : 1;
2756
2757         /* Reserve the backup blocks */
2758         ext2fs_mark_block_bitmap_range2(fs->block_map, sb, num);
2759
2760         for (g = 0; g < fs->group_desc_count; g++) {
2761                 blk64_t mb;
2762
2763                 mb = ext2fs_block_bitmap_loc(fs, g);
2764                 if ((mb >= sb) && (mb < sb + num)) {
2765                         ext2fs_block_bitmap_loc_set(fs, g, 0);
2766                         realloc = 1;
2767                 }
2768                 mb = ext2fs_inode_bitmap_loc(fs, g);
2769                 if ((mb >= sb) && (mb < sb + num)) {
2770                         ext2fs_inode_bitmap_loc_set(fs, g, 0);
2771                         realloc = 1;
2772                 }
2773                 mb = ext2fs_inode_table_loc(fs, g);
2774                 if ((mb < sb + num) &&
2775                     (sb < mb + fs->inode_blocks_per_group)) {
2776                         ext2fs_inode_table_loc_set(fs, g, 0);
2777                         realloc = 1;
2778                 }
2779                 if (realloc) {
2780                         retval = ext2fs_allocate_group_table(fs, g, 0);
2781                         if (retval)
2782                                 return retval;
2783                 }
2784         }
2785
2786         for (blk = sb, i = 0; i < num; blk++, i++) {
2787                 if (ext2fs_test_block_bitmap2(old_fs->block_map, blk) &&
2788                     !ext2fs_test_block_bitmap2(meta_bmap, blk)) {
2789                         ext2fs_mark_block_bitmap2(rfs->move_blocks, blk);
2790                         rfs->needed_blocks++;
2791                 }
2792                 ext2fs_mark_block_bitmap2(rfs->reserve_blocks, blk);
2793         }
2794         return 0;
2795 }
2796
2797 /*
2798  * Fix the resize inode
2799  */
2800 static errcode_t fix_resize_inode(ext2_filsys fs)
2801 {
2802         struct ext2_inode       inode;
2803         errcode_t               retval;
2804
2805         if (!ext2fs_has_feature_resize_inode(fs->super))
2806                 return 0;
2807
2808         retval = ext2fs_read_inode(fs, EXT2_RESIZE_INO, &inode);
2809         if (retval) goto errout;
2810
2811         ext2fs_iblk_set(fs, &inode, 1);
2812
2813         retval = ext2fs_write_inode(fs, EXT2_RESIZE_INO, &inode);
2814         if (retval) goto errout;
2815
2816         if (!inode.i_block[EXT2_DIND_BLOCK]) {
2817                 /*
2818                  * Avoid zeroing out block #0; that's rude.  This
2819                  * should never happen anyway since the filesystem
2820                  * should be fsck'ed and we assume it is consistent.
2821                  */
2822                 fprintf(stderr, "%s",
2823                         _("Should never happen: resize inode corrupt!\n"));
2824                 exit(1);
2825         }
2826
2827         retval = ext2fs_zero_blocks2(fs, inode.i_block[EXT2_DIND_BLOCK], 1,
2828                                      NULL, NULL);
2829         if (retval)
2830                 goto errout;
2831
2832         retval = ext2fs_create_resize_inode(fs);
2833         if (retval)
2834                 goto errout;
2835
2836 errout:
2837         return retval;
2838 }
2839
2840 /*
2841  * Finally, recalculate the summary information
2842  */
2843 static errcode_t resize2fs_calculate_summary_stats(ext2_filsys fs)
2844 {
2845         errcode_t       retval;
2846         blk64_t         b, blk = fs->super->s_first_data_block;
2847         ext2_ino_t      ino;
2848         unsigned int    n, max, group, count;
2849         blk64_t         total_clusters_free = 0;
2850         int             total_inodes_free = 0;
2851         int             group_free = 0;
2852         int             uninit = 0;
2853         char            *bitmap_buf;
2854
2855         /*
2856          * First calculate the block statistics
2857          */
2858         bitmap_buf = malloc(fs->blocksize);
2859         if (!bitmap_buf)
2860                 return ENOMEM;
2861         for (group = 0; group < fs->group_desc_count; group++) {
2862                 retval = ext2fs_get_block_bitmap_range2(fs->block_map,
2863                         B2C(blk), fs->super->s_clusters_per_group, bitmap_buf);
2864                 if (retval) {
2865                         free(bitmap_buf);
2866                         return retval;
2867                 }
2868                 max = ext2fs_group_blocks_count(fs, group) >>
2869                        fs->cluster_ratio_bits;
2870                 if ((group == fs->group_desc_count - 1) && (max & 7)) {
2871                         n = 0;
2872                         for (b = (fs->super->s_first_data_block +
2873                                   (fs->super->s_blocks_per_group * group));
2874                              b < ext2fs_blocks_count(fs->super);
2875                              b += EXT2FS_CLUSTER_RATIO(fs)) {
2876                                 if (ext2fs_test_block_bitmap2(fs->block_map, b))
2877                                         n++;
2878                         }
2879                 } else {
2880                         n = ext2fs_bitcount(bitmap_buf, (max + 7) / 8);
2881                 }
2882                 group_free = max - n;
2883                 total_clusters_free += group_free;
2884                 ext2fs_bg_free_blocks_count_set(fs, group, group_free);
2885                 ext2fs_group_desc_csum_set(fs, group);
2886                 blk += fs->super->s_blocks_per_group;
2887         }
2888         free(bitmap_buf);
2889         ext2fs_free_blocks_count_set(fs->super, C2B(total_clusters_free));
2890
2891         /*
2892          * Next, calculate the inode statistics
2893          */
2894         group_free = 0;
2895         count = 0;
2896         group = 0;
2897
2898         /* Protect loop from wrap-around if s_inodes_count maxed */
2899         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT);
2900         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
2901                 if (uninit ||
2902                     !ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
2903                         group_free++;
2904                         total_inodes_free++;
2905                 }
2906                 count++;
2907                 if ((count == fs->super->s_inodes_per_group) ||
2908                     (ino == fs->super->s_inodes_count)) {
2909                         ext2fs_bg_free_inodes_count_set(fs, group, group_free);
2910                         ext2fs_group_desc_csum_set(fs, group);
2911                         group++;
2912                         if (group >= fs->group_desc_count)
2913                                 break;
2914                         count = 0;
2915                         group_free = 0;
2916                         uninit = ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT);
2917                 }
2918         }
2919         fs->super->s_free_inodes_count = total_inodes_free;
2920         ext2fs_mark_super_dirty(fs);
2921         return 0;
2922 }
2923
2924 /*
2925  *  Journal may have been relocated; update the backup journal blocks
2926  *  in the superblock.
2927  */
2928 static errcode_t fix_sb_journal_backup(ext2_filsys fs)
2929 {
2930         errcode_t         retval;
2931         struct ext2_inode inode;
2932
2933         if (!ext2fs_has_feature_journal(fs->super))
2934                 return 0;
2935
2936         /* External journal? Nothing to do. */
2937         if (fs->super->s_journal_dev && !fs->super->s_journal_inum)
2938                 return 0;
2939
2940         retval = ext2fs_read_inode(fs, fs->super->s_journal_inum, &inode);
2941         if (retval)
2942                 return retval;
2943         memcpy(fs->super->s_jnl_blocks, inode.i_block, EXT2_N_BLOCKS*4);
2944         fs->super->s_jnl_blocks[15] = inode.i_size_high;
2945         fs->super->s_jnl_blocks[16] = inode.i_size;
2946         fs->super->s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS;
2947         ext2fs_mark_super_dirty(fs);
2948         return 0;
2949 }
2950
2951 static int calc_group_overhead(ext2_filsys fs, blk64_t grp,
2952                                int old_desc_blocks)
2953 {
2954         blk64_t super_blk, old_desc_blk, new_desc_blk;
2955         int overhead;
2956
2957         /* inode table blocks plus allocation bitmaps */
2958         overhead = fs->inode_blocks_per_group + 2;
2959
2960         ext2fs_super_and_bgd_loc2(fs, grp, &super_blk,
2961                                   &old_desc_blk, &new_desc_blk, 0);
2962         if ((grp == 0) || super_blk)
2963                 overhead++;
2964         if (old_desc_blk)
2965                 overhead += old_desc_blocks;
2966         else if (new_desc_blk)
2967                 overhead++;
2968         return overhead;
2969 }
2970
2971
2972 /*
2973  * calculate the minimum number of blocks the given fs can be resized to
2974  */
2975 blk64_t calculate_minimum_resize_size(ext2_filsys fs, int flags)
2976 {
2977         ext2_ino_t inode_count;
2978         dgrp_t groups, flex_groups;
2979         blk64_t blks_needed, data_blocks;
2980         blk64_t grp, data_needed, last_start;
2981         blk64_t overhead = 0;
2982         int old_desc_blocks;
2983         unsigned flexbg_size = 1U << fs->super->s_log_groups_per_flex;
2984
2985         /*
2986          * first figure out how many group descriptors we need to
2987          * handle the number of inodes we have
2988          */
2989         inode_count = fs->super->s_inodes_count -
2990                 fs->super->s_free_inodes_count;
2991         blks_needed = ext2fs_div_ceil(inode_count,
2992                                       fs->super->s_inodes_per_group) *
2993                 (blk64_t) EXT2_BLOCKS_PER_GROUP(fs->super);
2994         groups = ext2fs_div64_ceil(blks_needed,
2995                                    EXT2_BLOCKS_PER_GROUP(fs->super));
2996 #ifdef RESIZE2FS_DEBUG
2997         if (flags & RESIZE_DEBUG_MIN_CALC)
2998                 printf("fs has %d inodes, %d groups required.\n",
2999                        inode_count, groups);
3000 #endif
3001
3002         /*
3003          * number of old-style block group descriptor blocks
3004          */
3005         if (ext2fs_has_feature_meta_bg(fs->super))
3006                 old_desc_blocks = fs->super->s_first_meta_bg;
3007         else
3008                 old_desc_blocks = fs->desc_blocks +
3009                         fs->super->s_reserved_gdt_blocks;
3010
3011         /* calculate how many blocks are needed for data */
3012         data_needed = ext2fs_blocks_count(fs->super);
3013         for (grp = 0; grp < fs->group_desc_count; grp++) {
3014                 __u32 n = ext2fs_bg_free_blocks_count(fs, grp);
3015
3016                 if (n > EXT2_BLOCKS_PER_GROUP(fs->super))
3017                         n = EXT2_BLOCKS_PER_GROUP(fs->super);
3018                 n += calc_group_overhead(fs, grp, old_desc_blocks);
3019                 if (data_needed < n) {
3020                         if (flags & RESIZE_DEBUG_MIN_CALC)
3021                                 printf("file system appears inconsistent?!?\n");
3022                         return ext2fs_blocks_count(fs->super);
3023                 }
3024                 data_needed -= n;
3025         }
3026 #ifdef RESIZE2FS_DEBUG
3027         if (flags & RESIZE_DEBUG_MIN_CALC)
3028                 printf("fs requires %llu data blocks.\n",
3029                        (unsigned long long) data_needed);
3030 #endif
3031
3032         /*
3033          * For ext4 we need to allow for up to a flex_bg worth of
3034          * inode tables of slack space so the resize operation can be
3035          * guaranteed to finish.
3036          */
3037         flex_groups = groups;
3038         if (ext2fs_has_feature_flex_bg(fs->super)) {
3039                 dgrp_t remainder = groups & (flexbg_size - 1);
3040
3041                 flex_groups += flexbg_size - remainder;
3042                 if (flex_groups > fs->group_desc_count)
3043                         flex_groups = fs->group_desc_count;
3044         }
3045
3046         /*
3047          * figure out how many data blocks we have given the number of groups
3048          * we need for our inodes
3049          */
3050         data_blocks = EXT2_GROUPS_TO_BLOCKS(fs->super, groups);
3051         last_start = 0;
3052         for (grp = 0; grp < flex_groups; grp++) {
3053                 overhead = calc_group_overhead(fs, grp, old_desc_blocks);
3054
3055                 /*
3056                  * we want to keep track of how much data we can store in
3057                  * the groups leading up to the last group so we can determine
3058                  * how big the last group needs to be
3059                  */
3060                 if (grp < (groups - 1))
3061                         last_start += EXT2_BLOCKS_PER_GROUP(fs->super) -
3062                                 overhead;
3063
3064                 if (data_blocks > overhead)
3065                         data_blocks -= overhead;
3066                 else
3067                         data_blocks = 0;
3068         }
3069 #ifdef RESIZE2FS_DEBUG
3070         if (flags & RESIZE_DEBUG_MIN_CALC)
3071                 printf("With %d group(s), we have %llu blocks available.\n",
3072                        groups, (unsigned long long) data_blocks);
3073 #endif
3074
3075         /*
3076          * if we need more group descriptors in order to accommodate our data
3077          * then we need to add them here
3078          */
3079         blks_needed = data_needed;
3080         while (blks_needed > data_blocks) {
3081                 blk64_t remainder = blks_needed - data_blocks;
3082                 dgrp_t extra_grps;
3083
3084                 /* figure out how many more groups we need for the data */
3085                 extra_grps = ext2fs_div64_ceil(remainder,
3086                                                EXT2_BLOCKS_PER_GROUP(fs->super));
3087
3088                 data_blocks += EXT2_GROUPS_TO_BLOCKS(fs->super, extra_grps);
3089
3090                 /* ok we have to account for the last group */
3091                 overhead = calc_group_overhead(fs, groups-1, old_desc_blocks);
3092                 last_start += EXT2_BLOCKS_PER_GROUP(fs->super) - overhead;
3093
3094                 grp = flex_groups;
3095                 groups += extra_grps;
3096                 if (!ext2fs_has_feature_flex_bg(fs->super))
3097                         flex_groups = groups;
3098                 else if (groups > flex_groups) {
3099                         dgrp_t r = groups & (flexbg_size - 1);
3100
3101                         flex_groups = groups + flexbg_size - r;
3102                         if (flex_groups > fs->group_desc_count)
3103                                 flex_groups = fs->group_desc_count;
3104                 }
3105
3106                 for (; grp < flex_groups; grp++) {
3107                         overhead = calc_group_overhead(fs, grp,
3108                                                        old_desc_blocks);
3109
3110                         /*
3111                          * again, we need to see how much data we cram into
3112                          * all of the groups leading up to the last group
3113                          */
3114                         if (grp < groups - 1)
3115                                 last_start += EXT2_BLOCKS_PER_GROUP(fs->super)
3116                                         - overhead;
3117
3118                         data_blocks -= overhead;
3119                 }
3120
3121 #ifdef RESIZE2FS_DEBUG
3122                 if (flags & RESIZE_DEBUG_MIN_CALC)
3123                         printf("Added %d extra group(s), "
3124                                "blks_needed %llu, data_blocks %llu, "
3125                                "last_start %llu\n", extra_grps,
3126                                (unsigned long long) blks_needed,
3127                                (unsigned long long) data_blocks,
3128                                (unsigned long long) last_start);
3129 #endif
3130         }
3131
3132         /* now for the fun voodoo */
3133         grp = groups - 1;
3134         if (ext2fs_has_feature_flex_bg(fs->super) &&
3135             (grp & ~(flexbg_size - 1)) == 0)
3136                 grp = grp & ~(flexbg_size - 1);
3137         overhead = 0;
3138         for (; grp < flex_groups; grp++)
3139                 overhead += calc_group_overhead(fs, grp, old_desc_blocks);
3140
3141 #ifdef RESIZE2FS_DEBUG
3142         if (flags & RESIZE_DEBUG_MIN_CALC)
3143                 printf("Last group's overhead is %llu\n",
3144                        (unsigned long long) overhead);
3145 #endif
3146
3147         /*
3148          * if this is the case then the last group is going to have data in it
3149          * so we need to adjust the size of the last group accordingly
3150          */
3151         if (last_start < blks_needed) {
3152                 blk64_t remainder = blks_needed - last_start;
3153
3154 #ifdef RESIZE2FS_DEBUG
3155                 if (flags & RESIZE_DEBUG_MIN_CALC)
3156                         printf("Need %llu data blocks in last group\n",
3157                                (unsigned long long) remainder);
3158 #endif
3159                 /*
3160                  * 50 is a magic number that mkfs/resize uses to see if its
3161                  * even worth making/resizing the fs.  basically you need to
3162                  * have at least 50 blocks in addition to the blocks needed
3163                  * for the metadata in the last group
3164                  */
3165                 if (remainder > 50)
3166                         overhead += remainder;
3167                 else
3168                         overhead += 50;
3169         } else
3170                 overhead += 50;
3171
3172         overhead += fs->super->s_first_data_block;
3173 #ifdef RESIZE2FS_DEBUG
3174         if (flags & RESIZE_DEBUG_MIN_CALC)
3175                 printf("Final size of last group is %llu\n",
3176                        (unsigned long long) overhead);
3177 #endif
3178
3179         /* Add extra slack for bigalloc file systems */
3180         if (EXT2FS_CLUSTER_RATIO(fs) > 1)
3181                 overhead += EXT2FS_CLUSTER_RATIO(fs) * 2;
3182
3183         /*
3184          * since our last group doesn't have to be BLOCKS_PER_GROUP
3185          * large, we only do groups-1, and then add the number of
3186          * blocks needed to handle the group descriptor metadata+data
3187          * that we need
3188          */
3189         blks_needed = EXT2_GROUPS_TO_BLOCKS(fs->super, groups - 1);
3190         blks_needed += overhead;
3191
3192         /*
3193          * Make sure blks_needed covers the end of the inode table in
3194          * the last block group.
3195          */
3196         overhead = ext2fs_inode_table_loc(fs, groups-1) +
3197                 fs->inode_blocks_per_group;
3198         if (blks_needed < overhead)
3199                 blks_needed = overhead;
3200
3201 #ifdef RESIZE2FS_DEBUG
3202         if (flags & RESIZE_DEBUG_MIN_CALC)
3203                 printf("Estimated blocks needed: %llu\n",
3204                        (unsigned long long) blks_needed);
3205 #endif
3206
3207         /*
3208          * If at this point we've already added up more "needed" than
3209          * the current size, just return current size as minimum.
3210          */
3211         if (blks_needed >= ext2fs_blocks_count(fs->super))
3212                 return ext2fs_blocks_count(fs->super);
3213         /*
3214          * We need to reserve a few extra blocks if extents are
3215          * enabled, in case we need to grow the extent tree.  The more
3216          * we shrink the file system, the more space we need.
3217          *
3218          * The absolute worst case is every single data block is in
3219          * the part of the file system that needs to be evacuated,
3220          * with each data block needs to be in its own extent, and
3221          * with each inode needing at least one extent block.
3222          */
3223         if (ext2fs_has_feature_extents(fs->super)) {
3224                 blk64_t safe_margin = (ext2fs_blocks_count(fs->super) -
3225                                        blks_needed)/500;
3226                 unsigned int exts_per_blk = (fs->blocksize /
3227                                              sizeof(struct ext3_extent)) - 1;
3228                 blk64_t worst_case = ((data_needed + exts_per_blk - 1) /
3229                                       exts_per_blk);
3230
3231                 if (worst_case < inode_count)
3232                         worst_case = inode_count;
3233
3234                 if (safe_margin > worst_case)
3235                         safe_margin = worst_case;
3236
3237 #ifdef RESIZE2FS_DEBUG
3238                 if (flags & RESIZE_DEBUG_MIN_CALC)
3239                         printf("Extents safety margin: %llu\n",
3240                                (unsigned long long) safe_margin);
3241 #endif
3242                 blks_needed += safe_margin;
3243         }
3244
3245         return blks_needed;
3246 }