GNU Linux-libre 6.7.9-gnu
[releases.git] / fs / ext4 / resize.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/resize.c
4  *
5  * Support for resizing an ext4 filesystem while it is mounted.
6  *
7  * Copyright (C) 2001, 2002 Andreas Dilger <adilger@clusterfs.com>
8  *
9  * This could probably be made into a module, because it is not often in use.
10  */
11
12
13 #include <linux/errno.h>
14 #include <linux/slab.h>
15 #include <linux/jiffies.h>
16
17 #include "ext4_jbd2.h"
18
19 struct ext4_rcu_ptr {
20         struct rcu_head rcu;
21         void *ptr;
22 };
23
24 static void ext4_rcu_ptr_callback(struct rcu_head *head)
25 {
26         struct ext4_rcu_ptr *ptr;
27
28         ptr = container_of(head, struct ext4_rcu_ptr, rcu);
29         kvfree(ptr->ptr);
30         kfree(ptr);
31 }
32
33 void ext4_kvfree_array_rcu(void *to_free)
34 {
35         struct ext4_rcu_ptr *ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
36
37         if (ptr) {
38                 ptr->ptr = to_free;
39                 call_rcu(&ptr->rcu, ext4_rcu_ptr_callback);
40                 return;
41         }
42         synchronize_rcu();
43         kvfree(to_free);
44 }
45
46 int ext4_resize_begin(struct super_block *sb)
47 {
48         struct ext4_sb_info *sbi = EXT4_SB(sb);
49         int ret = 0;
50
51         if (!capable(CAP_SYS_RESOURCE))
52                 return -EPERM;
53
54         /*
55          * If the reserved GDT blocks is non-zero, the resize_inode feature
56          * should always be set.
57          */
58         if (sbi->s_es->s_reserved_gdt_blocks &&
59             !ext4_has_feature_resize_inode(sb)) {
60                 ext4_error(sb, "resize_inode disabled but reserved GDT blocks non-zero");
61                 return -EFSCORRUPTED;
62         }
63
64         /*
65          * If we are not using the primary superblock/GDT copy don't resize,
66          * because the user tools have no way of handling this.  Probably a
67          * bad time to do it anyways.
68          */
69         if (EXT4_B2C(sbi, sbi->s_sbh->b_blocknr) !=
70             le32_to_cpu(sbi->s_es->s_first_data_block)) {
71                 ext4_warning(sb, "won't resize using backup superblock at %llu",
72                         (unsigned long long)sbi->s_sbh->b_blocknr);
73                 return -EPERM;
74         }
75
76         /*
77          * We are not allowed to do online-resizing on a filesystem mounted
78          * with error, because it can destroy the filesystem easily.
79          */
80         if (sbi->s_mount_state & EXT4_ERROR_FS) {
81                 ext4_warning(sb, "There are errors in the filesystem, "
82                              "so online resizing is not allowed");
83                 return -EPERM;
84         }
85
86         if (ext4_has_feature_sparse_super2(sb)) {
87                 ext4_msg(sb, KERN_ERR, "Online resizing not supported with sparse_super2");
88                 return -EOPNOTSUPP;
89         }
90
91         if (test_and_set_bit_lock(EXT4_FLAGS_RESIZING,
92                                   &sbi->s_ext4_flags))
93                 ret = -EBUSY;
94
95         return ret;
96 }
97
98 int ext4_resize_end(struct super_block *sb, bool update_backups)
99 {
100         clear_bit_unlock(EXT4_FLAGS_RESIZING, &EXT4_SB(sb)->s_ext4_flags);
101         smp_mb__after_atomic();
102         if (update_backups)
103                 return ext4_update_overhead(sb, true);
104         return 0;
105 }
106
107 static ext4_grpblk_t ext4_group_overhead_blocks(struct super_block *sb,
108                                                 ext4_group_t group) {
109         ext4_grpblk_t overhead;
110         overhead = ext4_bg_num_gdb(sb, group);
111         if (ext4_bg_has_super(sb, group))
112                 overhead += 1 +
113                           le16_to_cpu(EXT4_SB(sb)->s_es->s_reserved_gdt_blocks);
114         return overhead;
115 }
116
117 #define outside(b, first, last) ((b) < (first) || (b) >= (last))
118 #define inside(b, first, last)  ((b) >= (first) && (b) < (last))
119
120 static int verify_group_input(struct super_block *sb,
121                               struct ext4_new_group_data *input)
122 {
123         struct ext4_sb_info *sbi = EXT4_SB(sb);
124         struct ext4_super_block *es = sbi->s_es;
125         ext4_fsblk_t start = ext4_blocks_count(es);
126         ext4_fsblk_t end = start + input->blocks_count;
127         ext4_group_t group = input->group;
128         ext4_fsblk_t itend = input->inode_table + sbi->s_itb_per_group;
129         unsigned overhead;
130         ext4_fsblk_t metaend;
131         struct buffer_head *bh = NULL;
132         ext4_grpblk_t free_blocks_count, offset;
133         int err = -EINVAL;
134
135         if (group != sbi->s_groups_count) {
136                 ext4_warning(sb, "Cannot add at group %u (only %u groups)",
137                              input->group, sbi->s_groups_count);
138                 return -EINVAL;
139         }
140
141         overhead = ext4_group_overhead_blocks(sb, group);
142         metaend = start + overhead;
143         free_blocks_count = input->blocks_count - 2 - overhead -
144                             sbi->s_itb_per_group;
145         input->free_clusters_count = EXT4_B2C(sbi, free_blocks_count);
146
147         if (test_opt(sb, DEBUG))
148                 printk(KERN_DEBUG "EXT4-fs: adding %s group %u: %u blocks "
149                        "(%d free, %u reserved)\n",
150                        ext4_bg_has_super(sb, input->group) ? "normal" :
151                        "no-super", input->group, input->blocks_count,
152                        free_blocks_count, input->reserved_blocks);
153
154         ext4_get_group_no_and_offset(sb, start, NULL, &offset);
155         if (offset != 0)
156                         ext4_warning(sb, "Last group not full");
157         else if (input->reserved_blocks > input->blocks_count / 5)
158                 ext4_warning(sb, "Reserved blocks too high (%u)",
159                              input->reserved_blocks);
160         else if (free_blocks_count < 0)
161                 ext4_warning(sb, "Bad blocks count %u",
162                              input->blocks_count);
163         else if (IS_ERR(bh = ext4_sb_bread(sb, end - 1, 0))) {
164                 err = PTR_ERR(bh);
165                 bh = NULL;
166                 ext4_warning(sb, "Cannot read last block (%llu)",
167                              end - 1);
168         } else if (outside(input->block_bitmap, start, end))
169                 ext4_warning(sb, "Block bitmap not in group (block %llu)",
170                              (unsigned long long)input->block_bitmap);
171         else if (outside(input->inode_bitmap, start, end))
172                 ext4_warning(sb, "Inode bitmap not in group (block %llu)",
173                              (unsigned long long)input->inode_bitmap);
174         else if (outside(input->inode_table, start, end) ||
175                  outside(itend - 1, start, end))
176                 ext4_warning(sb, "Inode table not in group (blocks %llu-%llu)",
177                              (unsigned long long)input->inode_table, itend - 1);
178         else if (input->inode_bitmap == input->block_bitmap)
179                 ext4_warning(sb, "Block bitmap same as inode bitmap (%llu)",
180                              (unsigned long long)input->block_bitmap);
181         else if (inside(input->block_bitmap, input->inode_table, itend))
182                 ext4_warning(sb, "Block bitmap (%llu) in inode table "
183                              "(%llu-%llu)",
184                              (unsigned long long)input->block_bitmap,
185                              (unsigned long long)input->inode_table, itend - 1);
186         else if (inside(input->inode_bitmap, input->inode_table, itend))
187                 ext4_warning(sb, "Inode bitmap (%llu) in inode table "
188                              "(%llu-%llu)",
189                              (unsigned long long)input->inode_bitmap,
190                              (unsigned long long)input->inode_table, itend - 1);
191         else if (inside(input->block_bitmap, start, metaend))
192                 ext4_warning(sb, "Block bitmap (%llu) in GDT table (%llu-%llu)",
193                              (unsigned long long)input->block_bitmap,
194                              start, metaend - 1);
195         else if (inside(input->inode_bitmap, start, metaend))
196                 ext4_warning(sb, "Inode bitmap (%llu) in GDT table (%llu-%llu)",
197                              (unsigned long long)input->inode_bitmap,
198                              start, metaend - 1);
199         else if (inside(input->inode_table, start, metaend) ||
200                  inside(itend - 1, start, metaend))
201                 ext4_warning(sb, "Inode table (%llu-%llu) overlaps GDT table "
202                              "(%llu-%llu)",
203                              (unsigned long long)input->inode_table,
204                              itend - 1, start, metaend - 1);
205         else
206                 err = 0;
207         brelse(bh);
208
209         return err;
210 }
211
212 /*
213  * ext4_new_flex_group_data is used by 64bit-resize interface to add a flex
214  * group each time.
215  */
216 struct ext4_new_flex_group_data {
217         struct ext4_new_group_data *groups;     /* new_group_data for groups
218                                                    in the flex group */
219         __u16 *bg_flags;                        /* block group flags of groups
220                                                    in @groups */
221         ext4_group_t resize_bg;                 /* number of allocated
222                                                    new_group_data */
223         ext4_group_t count;                     /* number of groups in @groups
224                                                  */
225 };
226
227 /*
228  * Avoiding memory allocation failures due to too many groups added each time.
229  */
230 #define MAX_RESIZE_BG                           16384
231
232 /*
233  * alloc_flex_gd() allocates a ext4_new_flex_group_data with size of
234  * @flexbg_size.
235  *
236  * Returns NULL on failure otherwise address of the allocated structure.
237  */
238 static struct ext4_new_flex_group_data *alloc_flex_gd(unsigned int flexbg_size)
239 {
240         struct ext4_new_flex_group_data *flex_gd;
241
242         flex_gd = kmalloc(sizeof(*flex_gd), GFP_NOFS);
243         if (flex_gd == NULL)
244                 goto out3;
245
246         if (unlikely(flexbg_size > MAX_RESIZE_BG))
247                 flex_gd->resize_bg = MAX_RESIZE_BG;
248         else
249                 flex_gd->resize_bg = flexbg_size;
250
251         flex_gd->groups = kmalloc_array(flex_gd->resize_bg,
252                                         sizeof(struct ext4_new_group_data),
253                                         GFP_NOFS);
254         if (flex_gd->groups == NULL)
255                 goto out2;
256
257         flex_gd->bg_flags = kmalloc_array(flex_gd->resize_bg, sizeof(__u16),
258                                           GFP_NOFS);
259         if (flex_gd->bg_flags == NULL)
260                 goto out1;
261
262         return flex_gd;
263
264 out1:
265         kfree(flex_gd->groups);
266 out2:
267         kfree(flex_gd);
268 out3:
269         return NULL;
270 }
271
272 static void free_flex_gd(struct ext4_new_flex_group_data *flex_gd)
273 {
274         kfree(flex_gd->bg_flags);
275         kfree(flex_gd->groups);
276         kfree(flex_gd);
277 }
278
279 /*
280  * ext4_alloc_group_tables() allocates block bitmaps, inode bitmaps
281  * and inode tables for a flex group.
282  *
283  * This function is used by 64bit-resize.  Note that this function allocates
284  * group tables from the 1st group of groups contained by @flexgd, which may
285  * be a partial of a flex group.
286  *
287  * @sb: super block of fs to which the groups belongs
288  *
289  * Returns 0 on a successful allocation of the metadata blocks in the
290  * block group.
291  */
292 static int ext4_alloc_group_tables(struct super_block *sb,
293                                 struct ext4_new_flex_group_data *flex_gd,
294                                 unsigned int flexbg_size)
295 {
296         struct ext4_new_group_data *group_data = flex_gd->groups;
297         ext4_fsblk_t start_blk;
298         ext4_fsblk_t last_blk;
299         ext4_group_t src_group;
300         ext4_group_t bb_index = 0;
301         ext4_group_t ib_index = 0;
302         ext4_group_t it_index = 0;
303         ext4_group_t group;
304         ext4_group_t last_group;
305         unsigned overhead;
306         __u16 uninit_mask = (flexbg_size > 1) ? ~EXT4_BG_BLOCK_UNINIT : ~0;
307         int i;
308
309         BUG_ON(flex_gd->count == 0 || group_data == NULL);
310
311         src_group = group_data[0].group;
312         last_group  = src_group + flex_gd->count - 1;
313
314         BUG_ON((flexbg_size > 1) && ((src_group & ~(flexbg_size - 1)) !=
315                (last_group & ~(flexbg_size - 1))));
316 next_group:
317         group = group_data[0].group;
318         if (src_group >= group_data[0].group + flex_gd->count)
319                 return -ENOSPC;
320         start_blk = ext4_group_first_block_no(sb, src_group);
321         last_blk = start_blk + group_data[src_group - group].blocks_count;
322
323         overhead = ext4_group_overhead_blocks(sb, src_group);
324
325         start_blk += overhead;
326
327         /* We collect contiguous blocks as much as possible. */
328         src_group++;
329         for (; src_group <= last_group; src_group++) {
330                 overhead = ext4_group_overhead_blocks(sb, src_group);
331                 if (overhead == 0)
332                         last_blk += group_data[src_group - group].blocks_count;
333                 else
334                         break;
335         }
336
337         /* Allocate block bitmaps */
338         for (; bb_index < flex_gd->count; bb_index++) {
339                 if (start_blk >= last_blk)
340                         goto next_group;
341                 group_data[bb_index].block_bitmap = start_blk++;
342                 group = ext4_get_group_number(sb, start_blk - 1);
343                 group -= group_data[0].group;
344                 group_data[group].mdata_blocks++;
345                 flex_gd->bg_flags[group] &= uninit_mask;
346         }
347
348         /* Allocate inode bitmaps */
349         for (; ib_index < flex_gd->count; ib_index++) {
350                 if (start_blk >= last_blk)
351                         goto next_group;
352                 group_data[ib_index].inode_bitmap = start_blk++;
353                 group = ext4_get_group_number(sb, start_blk - 1);
354                 group -= group_data[0].group;
355                 group_data[group].mdata_blocks++;
356                 flex_gd->bg_flags[group] &= uninit_mask;
357         }
358
359         /* Allocate inode tables */
360         for (; it_index < flex_gd->count; it_index++) {
361                 unsigned int itb = EXT4_SB(sb)->s_itb_per_group;
362                 ext4_fsblk_t next_group_start;
363
364                 if (start_blk + itb > last_blk)
365                         goto next_group;
366                 group_data[it_index].inode_table = start_blk;
367                 group = ext4_get_group_number(sb, start_blk);
368                 next_group_start = ext4_group_first_block_no(sb, group + 1);
369                 group -= group_data[0].group;
370
371                 if (start_blk + itb > next_group_start) {
372                         flex_gd->bg_flags[group + 1] &= uninit_mask;
373                         overhead = start_blk + itb - next_group_start;
374                         group_data[group + 1].mdata_blocks += overhead;
375                         itb -= overhead;
376                 }
377
378                 group_data[group].mdata_blocks += itb;
379                 flex_gd->bg_flags[group] &= uninit_mask;
380                 start_blk += EXT4_SB(sb)->s_itb_per_group;
381         }
382
383         /* Update free clusters count to exclude metadata blocks */
384         for (i = 0; i < flex_gd->count; i++) {
385                 group_data[i].free_clusters_count -=
386                                 EXT4_NUM_B2C(EXT4_SB(sb),
387                                              group_data[i].mdata_blocks);
388         }
389
390         if (test_opt(sb, DEBUG)) {
391                 int i;
392                 group = group_data[0].group;
393
394                 printk(KERN_DEBUG "EXT4-fs: adding a flex group with "
395                        "%u groups, flexbg size is %u:\n", flex_gd->count,
396                        flexbg_size);
397
398                 for (i = 0; i < flex_gd->count; i++) {
399                         ext4_debug(
400                                "adding %s group %u: %u blocks (%u free, %u mdata blocks)\n",
401                                ext4_bg_has_super(sb, group + i) ? "normal" :
402                                "no-super", group + i,
403                                group_data[i].blocks_count,
404                                group_data[i].free_clusters_count,
405                                group_data[i].mdata_blocks);
406                 }
407         }
408         return 0;
409 }
410
411 static struct buffer_head *bclean(handle_t *handle, struct super_block *sb,
412                                   ext4_fsblk_t blk)
413 {
414         struct buffer_head *bh;
415         int err;
416
417         bh = sb_getblk(sb, blk);
418         if (unlikely(!bh))
419                 return ERR_PTR(-ENOMEM);
420         BUFFER_TRACE(bh, "get_write_access");
421         err = ext4_journal_get_write_access(handle, sb, bh, EXT4_JTR_NONE);
422         if (err) {
423                 brelse(bh);
424                 bh = ERR_PTR(err);
425         } else {
426                 memset(bh->b_data, 0, sb->s_blocksize);
427                 set_buffer_uptodate(bh);
428         }
429
430         return bh;
431 }
432
433 static int ext4_resize_ensure_credits_batch(handle_t *handle, int credits)
434 {
435         return ext4_journal_ensure_credits_fn(handle, credits,
436                 EXT4_MAX_TRANS_DATA, 0, 0);
437 }
438
439 /*
440  * set_flexbg_block_bitmap() mark clusters [@first_cluster, @last_cluster] used.
441  *
442  * Helper function for ext4_setup_new_group_blocks() which set .
443  *
444  * @sb: super block
445  * @handle: journal handle
446  * @flex_gd: flex group data
447  */
448 static int set_flexbg_block_bitmap(struct super_block *sb, handle_t *handle,
449                         struct ext4_new_flex_group_data *flex_gd,
450                         ext4_fsblk_t first_cluster, ext4_fsblk_t last_cluster)
451 {
452         struct ext4_sb_info *sbi = EXT4_SB(sb);
453         ext4_group_t count = last_cluster - first_cluster + 1;
454         ext4_group_t count2;
455
456         ext4_debug("mark clusters [%llu-%llu] used\n", first_cluster,
457                    last_cluster);
458         for (; count > 0; count -= count2, first_cluster += count2) {
459                 ext4_fsblk_t start;
460                 struct buffer_head *bh;
461                 ext4_group_t group;
462                 int err;
463
464                 group = ext4_get_group_number(sb, EXT4_C2B(sbi, first_cluster));
465                 start = EXT4_B2C(sbi, ext4_group_first_block_no(sb, group));
466                 group -= flex_gd->groups[0].group;
467
468                 count2 = EXT4_CLUSTERS_PER_GROUP(sb) - (first_cluster - start);
469                 if (count2 > count)
470                         count2 = count;
471
472                 if (flex_gd->bg_flags[group] & EXT4_BG_BLOCK_UNINIT) {
473                         BUG_ON(flex_gd->count > 1);
474                         continue;
475                 }
476
477                 err = ext4_resize_ensure_credits_batch(handle, 1);
478                 if (err < 0)
479                         return err;
480
481                 bh = sb_getblk(sb, flex_gd->groups[group].block_bitmap);
482                 if (unlikely(!bh))
483                         return -ENOMEM;
484
485                 BUFFER_TRACE(bh, "get_write_access");
486                 err = ext4_journal_get_write_access(handle, sb, bh,
487                                                     EXT4_JTR_NONE);
488                 if (err) {
489                         brelse(bh);
490                         return err;
491                 }
492                 ext4_debug("mark block bitmap %#04llx (+%llu/%u)\n",
493                            first_cluster, first_cluster - start, count2);
494                 mb_set_bits(bh->b_data, first_cluster - start, count2);
495
496                 err = ext4_handle_dirty_metadata(handle, NULL, bh);
497                 brelse(bh);
498                 if (unlikely(err))
499                         return err;
500         }
501
502         return 0;
503 }
504
505 /*
506  * Set up the block and inode bitmaps, and the inode table for the new groups.
507  * This doesn't need to be part of the main transaction, since we are only
508  * changing blocks outside the actual filesystem.  We still do journaling to
509  * ensure the recovery is correct in case of a failure just after resize.
510  * If any part of this fails, we simply abort the resize.
511  *
512  * setup_new_flex_group_blocks handles a flex group as follow:
513  *  1. copy super block and GDT, and initialize group tables if necessary.
514  *     In this step, we only set bits in blocks bitmaps for blocks taken by
515  *     super block and GDT.
516  *  2. allocate group tables in block bitmaps, that is, set bits in block
517  *     bitmap for blocks taken by group tables.
518  */
519 static int setup_new_flex_group_blocks(struct super_block *sb,
520                                 struct ext4_new_flex_group_data *flex_gd)
521 {
522         int group_table_count[] = {1, 1, EXT4_SB(sb)->s_itb_per_group};
523         ext4_fsblk_t start;
524         ext4_fsblk_t block;
525         struct ext4_sb_info *sbi = EXT4_SB(sb);
526         struct ext4_super_block *es = sbi->s_es;
527         struct ext4_new_group_data *group_data = flex_gd->groups;
528         __u16 *bg_flags = flex_gd->bg_flags;
529         handle_t *handle;
530         ext4_group_t group, count;
531         struct buffer_head *bh = NULL;
532         int reserved_gdb, i, j, err = 0, err2;
533         int meta_bg;
534
535         BUG_ON(!flex_gd->count || !group_data ||
536                group_data[0].group != sbi->s_groups_count);
537
538         reserved_gdb = le16_to_cpu(es->s_reserved_gdt_blocks);
539         meta_bg = ext4_has_feature_meta_bg(sb);
540
541         /* This transaction may be extended/restarted along the way */
542         handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, EXT4_MAX_TRANS_DATA);
543         if (IS_ERR(handle))
544                 return PTR_ERR(handle);
545
546         group = group_data[0].group;
547         for (i = 0; i < flex_gd->count; i++, group++) {
548                 unsigned long gdblocks;
549                 ext4_grpblk_t overhead;
550
551                 gdblocks = ext4_bg_num_gdb(sb, group);
552                 start = ext4_group_first_block_no(sb, group);
553
554                 if (meta_bg == 0 && !ext4_bg_has_super(sb, group))
555                         goto handle_itb;
556
557                 if (meta_bg == 1)
558                         goto handle_itb;
559
560                 block = start + ext4_bg_has_super(sb, group);
561                 /* Copy all of the GDT blocks into the backup in this group */
562                 for (j = 0; j < gdblocks; j++, block++) {
563                         struct buffer_head *gdb;
564
565                         ext4_debug("update backup group %#04llx\n", block);
566                         err = ext4_resize_ensure_credits_batch(handle, 1);
567                         if (err < 0)
568                                 goto out;
569
570                         gdb = sb_getblk(sb, block);
571                         if (unlikely(!gdb)) {
572                                 err = -ENOMEM;
573                                 goto out;
574                         }
575
576                         BUFFER_TRACE(gdb, "get_write_access");
577                         err = ext4_journal_get_write_access(handle, sb, gdb,
578                                                             EXT4_JTR_NONE);
579                         if (err) {
580                                 brelse(gdb);
581                                 goto out;
582                         }
583                         memcpy(gdb->b_data, sbi_array_rcu_deref(sbi,
584                                 s_group_desc, j)->b_data, gdb->b_size);
585                         set_buffer_uptodate(gdb);
586
587                         err = ext4_handle_dirty_metadata(handle, NULL, gdb);
588                         if (unlikely(err)) {
589                                 brelse(gdb);
590                                 goto out;
591                         }
592                         brelse(gdb);
593                 }
594
595                 /* Zero out all of the reserved backup group descriptor
596                  * table blocks
597                  */
598                 if (ext4_bg_has_super(sb, group)) {
599                         err = sb_issue_zeroout(sb, gdblocks + start + 1,
600                                         reserved_gdb, GFP_NOFS);
601                         if (err)
602                                 goto out;
603                 }
604
605 handle_itb:
606                 /* Initialize group tables of the group @group */
607                 if (!(bg_flags[i] & EXT4_BG_INODE_ZEROED))
608                         goto handle_bb;
609
610                 /* Zero out all of the inode table blocks */
611                 block = group_data[i].inode_table;
612                 ext4_debug("clear inode table blocks %#04llx -> %#04lx\n",
613                            block, sbi->s_itb_per_group);
614                 err = sb_issue_zeroout(sb, block, sbi->s_itb_per_group,
615                                        GFP_NOFS);
616                 if (err)
617                         goto out;
618
619 handle_bb:
620                 if (bg_flags[i] & EXT4_BG_BLOCK_UNINIT)
621                         goto handle_ib;
622
623                 /* Initialize block bitmap of the @group */
624                 block = group_data[i].block_bitmap;
625                 err = ext4_resize_ensure_credits_batch(handle, 1);
626                 if (err < 0)
627                         goto out;
628
629                 bh = bclean(handle, sb, block);
630                 if (IS_ERR(bh)) {
631                         err = PTR_ERR(bh);
632                         goto out;
633                 }
634                 overhead = ext4_group_overhead_blocks(sb, group);
635                 if (overhead != 0) {
636                         ext4_debug("mark backup superblock %#04llx (+0)\n",
637                                    start);
638                         mb_set_bits(bh->b_data, 0,
639                                       EXT4_NUM_B2C(sbi, overhead));
640                 }
641                 ext4_mark_bitmap_end(EXT4_B2C(sbi, group_data[i].blocks_count),
642                                      sb->s_blocksize * 8, bh->b_data);
643                 err = ext4_handle_dirty_metadata(handle, NULL, bh);
644                 brelse(bh);
645                 if (err)
646                         goto out;
647
648 handle_ib:
649                 if (bg_flags[i] & EXT4_BG_INODE_UNINIT)
650                         continue;
651
652                 /* Initialize inode bitmap of the @group */
653                 block = group_data[i].inode_bitmap;
654                 err = ext4_resize_ensure_credits_batch(handle, 1);
655                 if (err < 0)
656                         goto out;
657                 /* Mark unused entries in inode bitmap used */
658                 bh = bclean(handle, sb, block);
659                 if (IS_ERR(bh)) {
660                         err = PTR_ERR(bh);
661                         goto out;
662                 }
663
664                 ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb),
665                                      sb->s_blocksize * 8, bh->b_data);
666                 err = ext4_handle_dirty_metadata(handle, NULL, bh);
667                 brelse(bh);
668                 if (err)
669                         goto out;
670         }
671
672         /* Mark group tables in block bitmap */
673         for (j = 0; j < GROUP_TABLE_COUNT; j++) {
674                 count = group_table_count[j];
675                 start = (&group_data[0].block_bitmap)[j];
676                 block = start;
677                 for (i = 1; i < flex_gd->count; i++) {
678                         block += group_table_count[j];
679                         if (block == (&group_data[i].block_bitmap)[j]) {
680                                 count += group_table_count[j];
681                                 continue;
682                         }
683                         err = set_flexbg_block_bitmap(sb, handle,
684                                                       flex_gd,
685                                                       EXT4_B2C(sbi, start),
686                                                       EXT4_B2C(sbi,
687                                                                start + count
688                                                                - 1));
689                         if (err)
690                                 goto out;
691                         count = group_table_count[j];
692                         start = (&group_data[i].block_bitmap)[j];
693                         block = start;
694                 }
695
696                 err = set_flexbg_block_bitmap(sb, handle,
697                                 flex_gd,
698                                 EXT4_B2C(sbi, start),
699                                 EXT4_B2C(sbi,
700                                         start + count
701                                         - 1));
702                 if (err)
703                         goto out;
704         }
705
706 out:
707         err2 = ext4_journal_stop(handle);
708         if (err2 && !err)
709                 err = err2;
710
711         return err;
712 }
713
714 /*
715  * Iterate through the groups which hold BACKUP superblock/GDT copies in an
716  * ext4 filesystem.  The counters should be initialized to 1, 5, and 7 before
717  * calling this for the first time.  In a sparse filesystem it will be the
718  * sequence of powers of 3, 5, and 7: 1, 3, 5, 7, 9, 25, 27, 49, 81, ...
719  * For a non-sparse filesystem it will be every group: 1, 2, 3, 4, ...
720  */
721 unsigned int ext4_list_backups(struct super_block *sb, unsigned int *three,
722                                unsigned int *five, unsigned int *seven)
723 {
724         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
725         unsigned int *min = three;
726         int mult = 3;
727         unsigned int ret;
728
729         if (ext4_has_feature_sparse_super2(sb)) {
730                 do {
731                         if (*min > 2)
732                                 return UINT_MAX;
733                         ret = le32_to_cpu(es->s_backup_bgs[*min - 1]);
734                         *min += 1;
735                 } while (!ret);
736                 return ret;
737         }
738
739         if (!ext4_has_feature_sparse_super(sb)) {
740                 ret = *min;
741                 *min += 1;
742                 return ret;
743         }
744
745         if (*five < *min) {
746                 min = five;
747                 mult = 5;
748         }
749         if (*seven < *min) {
750                 min = seven;
751                 mult = 7;
752         }
753
754         ret = *min;
755         *min *= mult;
756
757         return ret;
758 }
759
760 /*
761  * Check that all of the backup GDT blocks are held in the primary GDT block.
762  * It is assumed that they are stored in group order.  Returns the number of
763  * groups in current filesystem that have BACKUPS, or -ve error code.
764  */
765 static int verify_reserved_gdb(struct super_block *sb,
766                                ext4_group_t end,
767                                struct buffer_head *primary)
768 {
769         const ext4_fsblk_t blk = primary->b_blocknr;
770         unsigned three = 1;
771         unsigned five = 5;
772         unsigned seven = 7;
773         unsigned grp;
774         __le32 *p = (__le32 *)primary->b_data;
775         int gdbackups = 0;
776
777         while ((grp = ext4_list_backups(sb, &three, &five, &seven)) < end) {
778                 if (le32_to_cpu(*p++) !=
779                     grp * EXT4_BLOCKS_PER_GROUP(sb) + blk){
780                         ext4_warning(sb, "reserved GDT %llu"
781                                      " missing grp %d (%llu)",
782                                      blk, grp,
783                                      grp *
784                                      (ext4_fsblk_t)EXT4_BLOCKS_PER_GROUP(sb) +
785                                      blk);
786                         return -EINVAL;
787                 }
788                 if (++gdbackups > EXT4_ADDR_PER_BLOCK(sb))
789                         return -EFBIG;
790         }
791
792         return gdbackups;
793 }
794
795 /*
796  * Called when we need to bring a reserved group descriptor table block into
797  * use from the resize inode.  The primary copy of the new GDT block currently
798  * is an indirect block (under the double indirect block in the resize inode).
799  * The new backup GDT blocks will be stored as leaf blocks in this indirect
800  * block, in group order.  Even though we know all the block numbers we need,
801  * we check to ensure that the resize inode has actually reserved these blocks.
802  *
803  * Don't need to update the block bitmaps because the blocks are still in use.
804  *
805  * We get all of the error cases out of the way, so that we are sure to not
806  * fail once we start modifying the data on disk, because JBD has no rollback.
807  */
808 static int add_new_gdb(handle_t *handle, struct inode *inode,
809                        ext4_group_t group)
810 {
811         struct super_block *sb = inode->i_sb;
812         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
813         unsigned long gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
814         ext4_fsblk_t gdblock = EXT4_SB(sb)->s_sbh->b_blocknr + 1 + gdb_num;
815         struct buffer_head **o_group_desc, **n_group_desc = NULL;
816         struct buffer_head *dind = NULL;
817         struct buffer_head *gdb_bh = NULL;
818         int gdbackups;
819         struct ext4_iloc iloc = { .bh = NULL };
820         __le32 *data;
821         int err;
822
823         if (test_opt(sb, DEBUG))
824                 printk(KERN_DEBUG
825                        "EXT4-fs: ext4_add_new_gdb: adding group block %lu\n",
826                        gdb_num);
827
828         gdb_bh = ext4_sb_bread(sb, gdblock, 0);
829         if (IS_ERR(gdb_bh))
830                 return PTR_ERR(gdb_bh);
831
832         gdbackups = verify_reserved_gdb(sb, group, gdb_bh);
833         if (gdbackups < 0) {
834                 err = gdbackups;
835                 goto errout;
836         }
837
838         data = EXT4_I(inode)->i_data + EXT4_DIND_BLOCK;
839         dind = ext4_sb_bread(sb, le32_to_cpu(*data), 0);
840         if (IS_ERR(dind)) {
841                 err = PTR_ERR(dind);
842                 dind = NULL;
843                 goto errout;
844         }
845
846         data = (__le32 *)dind->b_data;
847         if (le32_to_cpu(data[gdb_num % EXT4_ADDR_PER_BLOCK(sb)]) != gdblock) {
848                 ext4_warning(sb, "new group %u GDT block %llu not reserved",
849                              group, gdblock);
850                 err = -EINVAL;
851                 goto errout;
852         }
853
854         BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
855         err = ext4_journal_get_write_access(handle, sb, EXT4_SB(sb)->s_sbh,
856                                             EXT4_JTR_NONE);
857         if (unlikely(err))
858                 goto errout;
859
860         BUFFER_TRACE(gdb_bh, "get_write_access");
861         err = ext4_journal_get_write_access(handle, sb, gdb_bh, EXT4_JTR_NONE);
862         if (unlikely(err))
863                 goto errout;
864
865         BUFFER_TRACE(dind, "get_write_access");
866         err = ext4_journal_get_write_access(handle, sb, dind, EXT4_JTR_NONE);
867         if (unlikely(err)) {
868                 ext4_std_error(sb, err);
869                 goto errout;
870         }
871
872         /* ext4_reserve_inode_write() gets a reference on the iloc */
873         err = ext4_reserve_inode_write(handle, inode, &iloc);
874         if (unlikely(err))
875                 goto errout;
876
877         n_group_desc = kvmalloc((gdb_num + 1) * sizeof(struct buffer_head *),
878                                 GFP_KERNEL);
879         if (!n_group_desc) {
880                 err = -ENOMEM;
881                 ext4_warning(sb, "not enough memory for %lu groups",
882                              gdb_num + 1);
883                 goto errout;
884         }
885
886         /*
887          * Finally, we have all of the possible failures behind us...
888          *
889          * Remove new GDT block from inode double-indirect block and clear out
890          * the new GDT block for use (which also "frees" the backup GDT blocks
891          * from the reserved inode).  We don't need to change the bitmaps for
892          * these blocks, because they are marked as in-use from being in the
893          * reserved inode, and will become GDT blocks (primary and backup).
894          */
895         data[gdb_num % EXT4_ADDR_PER_BLOCK(sb)] = 0;
896         err = ext4_handle_dirty_metadata(handle, NULL, dind);
897         if (unlikely(err)) {
898                 ext4_std_error(sb, err);
899                 goto errout;
900         }
901         inode->i_blocks -= (gdbackups + 1) * sb->s_blocksize >>
902                            (9 - EXT4_SB(sb)->s_cluster_bits);
903         ext4_mark_iloc_dirty(handle, inode, &iloc);
904         memset(gdb_bh->b_data, 0, sb->s_blocksize);
905         err = ext4_handle_dirty_metadata(handle, NULL, gdb_bh);
906         if (unlikely(err)) {
907                 ext4_std_error(sb, err);
908                 iloc.bh = NULL;
909                 goto errout;
910         }
911         brelse(dind);
912
913         rcu_read_lock();
914         o_group_desc = rcu_dereference(EXT4_SB(sb)->s_group_desc);
915         memcpy(n_group_desc, o_group_desc,
916                EXT4_SB(sb)->s_gdb_count * sizeof(struct buffer_head *));
917         rcu_read_unlock();
918         n_group_desc[gdb_num] = gdb_bh;
919         rcu_assign_pointer(EXT4_SB(sb)->s_group_desc, n_group_desc);
920         EXT4_SB(sb)->s_gdb_count++;
921         ext4_kvfree_array_rcu(o_group_desc);
922
923         lock_buffer(EXT4_SB(sb)->s_sbh);
924         le16_add_cpu(&es->s_reserved_gdt_blocks, -1);
925         ext4_superblock_csum_set(sb);
926         unlock_buffer(EXT4_SB(sb)->s_sbh);
927         err = ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
928         if (err)
929                 ext4_std_error(sb, err);
930         return err;
931 errout:
932         kvfree(n_group_desc);
933         brelse(iloc.bh);
934         brelse(dind);
935         brelse(gdb_bh);
936
937         ext4_debug("leaving with error %d\n", err);
938         return err;
939 }
940
941 /*
942  * If there is no available space in the existing block group descriptors for
943  * the new block group and there are no reserved block group descriptors, then
944  * the meta_bg feature will get enabled, and es->s_first_meta_bg will get set
945  * to the first block group that is managed using meta_bg and s_first_meta_bg
946  * must be a multiple of EXT4_DESC_PER_BLOCK(sb).
947  * This function will be called when first group of meta_bg is added to bring
948  * new group descriptors block of new added meta_bg.
949  */
950 static int add_new_gdb_meta_bg(struct super_block *sb,
951                                handle_t *handle, ext4_group_t group) {
952         ext4_fsblk_t gdblock;
953         struct buffer_head *gdb_bh;
954         struct buffer_head **o_group_desc, **n_group_desc;
955         unsigned long gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
956         int err;
957
958         gdblock = ext4_group_first_block_no(sb, group) +
959                   ext4_bg_has_super(sb, group);
960         gdb_bh = ext4_sb_bread(sb, gdblock, 0);
961         if (IS_ERR(gdb_bh))
962                 return PTR_ERR(gdb_bh);
963         n_group_desc = kvmalloc((gdb_num + 1) * sizeof(struct buffer_head *),
964                                 GFP_KERNEL);
965         if (!n_group_desc) {
966                 brelse(gdb_bh);
967                 err = -ENOMEM;
968                 ext4_warning(sb, "not enough memory for %lu groups",
969                              gdb_num + 1);
970                 return err;
971         }
972
973         rcu_read_lock();
974         o_group_desc = rcu_dereference(EXT4_SB(sb)->s_group_desc);
975         memcpy(n_group_desc, o_group_desc,
976                EXT4_SB(sb)->s_gdb_count * sizeof(struct buffer_head *));
977         rcu_read_unlock();
978         n_group_desc[gdb_num] = gdb_bh;
979
980         BUFFER_TRACE(gdb_bh, "get_write_access");
981         err = ext4_journal_get_write_access(handle, sb, gdb_bh, EXT4_JTR_NONE);
982         if (err) {
983                 kvfree(n_group_desc);
984                 brelse(gdb_bh);
985                 return err;
986         }
987
988         rcu_assign_pointer(EXT4_SB(sb)->s_group_desc, n_group_desc);
989         EXT4_SB(sb)->s_gdb_count++;
990         ext4_kvfree_array_rcu(o_group_desc);
991         return err;
992 }
993
994 /*
995  * Called when we are adding a new group which has a backup copy of each of
996  * the GDT blocks (i.e. sparse group) and there are reserved GDT blocks.
997  * We need to add these reserved backup GDT blocks to the resize inode, so
998  * that they are kept for future resizing and not allocated to files.
999  *
1000  * Each reserved backup GDT block will go into a different indirect block.
1001  * The indirect blocks are actually the primary reserved GDT blocks,
1002  * so we know in advance what their block numbers are.  We only get the
1003  * double-indirect block to verify it is pointing to the primary reserved
1004  * GDT blocks so we don't overwrite a data block by accident.  The reserved
1005  * backup GDT blocks are stored in their reserved primary GDT block.
1006  */
1007 static int reserve_backup_gdb(handle_t *handle, struct inode *inode,
1008                               ext4_group_t group)
1009 {
1010         struct super_block *sb = inode->i_sb;
1011         int reserved_gdb =le16_to_cpu(EXT4_SB(sb)->s_es->s_reserved_gdt_blocks);
1012         int cluster_bits = EXT4_SB(sb)->s_cluster_bits;
1013         struct buffer_head **primary;
1014         struct buffer_head *dind;
1015         struct ext4_iloc iloc;
1016         ext4_fsblk_t blk;
1017         __le32 *data, *end;
1018         int gdbackups = 0;
1019         int res, i;
1020         int err;
1021
1022         primary = kmalloc_array(reserved_gdb, sizeof(*primary), GFP_NOFS);
1023         if (!primary)
1024                 return -ENOMEM;
1025
1026         data = EXT4_I(inode)->i_data + EXT4_DIND_BLOCK;
1027         dind = ext4_sb_bread(sb, le32_to_cpu(*data), 0);
1028         if (IS_ERR(dind)) {
1029                 err = PTR_ERR(dind);
1030                 dind = NULL;
1031                 goto exit_free;
1032         }
1033
1034         blk = EXT4_SB(sb)->s_sbh->b_blocknr + 1 + EXT4_SB(sb)->s_gdb_count;
1035         data = (__le32 *)dind->b_data + (EXT4_SB(sb)->s_gdb_count %
1036                                          EXT4_ADDR_PER_BLOCK(sb));
1037         end = (__le32 *)dind->b_data + EXT4_ADDR_PER_BLOCK(sb);
1038
1039         /* Get each reserved primary GDT block and verify it holds backups */
1040         for (res = 0; res < reserved_gdb; res++, blk++) {
1041                 if (le32_to_cpu(*data) != blk) {
1042                         ext4_warning(sb, "reserved block %llu"
1043                                      " not at offset %ld",
1044                                      blk,
1045                                      (long)(data - (__le32 *)dind->b_data));
1046                         err = -EINVAL;
1047                         goto exit_bh;
1048                 }
1049                 primary[res] = ext4_sb_bread(sb, blk, 0);
1050                 if (IS_ERR(primary[res])) {
1051                         err = PTR_ERR(primary[res]);
1052                         primary[res] = NULL;
1053                         goto exit_bh;
1054                 }
1055                 gdbackups = verify_reserved_gdb(sb, group, primary[res]);
1056                 if (gdbackups < 0) {
1057                         brelse(primary[res]);
1058                         err = gdbackups;
1059                         goto exit_bh;
1060                 }
1061                 if (++data >= end)
1062                         data = (__le32 *)dind->b_data;
1063         }
1064
1065         for (i = 0; i < reserved_gdb; i++) {
1066                 BUFFER_TRACE(primary[i], "get_write_access");
1067                 if ((err = ext4_journal_get_write_access(handle, sb, primary[i],
1068                                                          EXT4_JTR_NONE)))
1069                         goto exit_bh;
1070         }
1071
1072         if ((err = ext4_reserve_inode_write(handle, inode, &iloc)))
1073                 goto exit_bh;
1074
1075         /*
1076          * Finally we can add each of the reserved backup GDT blocks from
1077          * the new group to its reserved primary GDT block.
1078          */
1079         blk = group * EXT4_BLOCKS_PER_GROUP(sb);
1080         for (i = 0; i < reserved_gdb; i++) {
1081                 int err2;
1082                 data = (__le32 *)primary[i]->b_data;
1083                 data[gdbackups] = cpu_to_le32(blk + primary[i]->b_blocknr);
1084                 err2 = ext4_handle_dirty_metadata(handle, NULL, primary[i]);
1085                 if (!err)
1086                         err = err2;
1087         }
1088
1089         inode->i_blocks += reserved_gdb * sb->s_blocksize >> (9 - cluster_bits);
1090         ext4_mark_iloc_dirty(handle, inode, &iloc);
1091
1092 exit_bh:
1093         while (--res >= 0)
1094                 brelse(primary[res]);
1095         brelse(dind);
1096
1097 exit_free:
1098         kfree(primary);
1099
1100         return err;
1101 }
1102
1103 static inline void ext4_set_block_group_nr(struct super_block *sb, char *data,
1104                                            ext4_group_t group)
1105 {
1106         struct ext4_super_block *es = (struct ext4_super_block *) data;
1107
1108         es->s_block_group_nr = cpu_to_le16(group);
1109         if (ext4_has_metadata_csum(sb))
1110                 es->s_checksum = ext4_superblock_csum(sb, es);
1111 }
1112
1113 /*
1114  * Update the backup copies of the ext4 metadata.  These don't need to be part
1115  * of the main resize transaction, because e2fsck will re-write them if there
1116  * is a problem (basically only OOM will cause a problem).  However, we
1117  * _should_ update the backups if possible, in case the primary gets trashed
1118  * for some reason and we need to run e2fsck from a backup superblock.  The
1119  * important part is that the new block and inode counts are in the backup
1120  * superblocks, and the location of the new group metadata in the GDT backups.
1121  *
1122  * We do not need take the s_resize_lock for this, because these
1123  * blocks are not otherwise touched by the filesystem code when it is
1124  * mounted.  We don't need to worry about last changing from
1125  * sbi->s_groups_count, because the worst that can happen is that we
1126  * do not copy the full number of backups at this time.  The resize
1127  * which changed s_groups_count will backup again.
1128  */
1129 static void update_backups(struct super_block *sb, sector_t blk_off, char *data,
1130                            int size, int meta_bg)
1131 {
1132         struct ext4_sb_info *sbi = EXT4_SB(sb);
1133         ext4_group_t last;
1134         const int bpg = EXT4_BLOCKS_PER_GROUP(sb);
1135         unsigned three = 1;
1136         unsigned five = 5;
1137         unsigned seven = 7;
1138         ext4_group_t group = 0;
1139         int rest = sb->s_blocksize - size;
1140         handle_t *handle;
1141         int err = 0, err2;
1142
1143         handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, EXT4_MAX_TRANS_DATA);
1144         if (IS_ERR(handle)) {
1145                 group = 1;
1146                 err = PTR_ERR(handle);
1147                 goto exit_err;
1148         }
1149
1150         if (meta_bg == 0) {
1151                 group = ext4_list_backups(sb, &three, &five, &seven);
1152                 last = sbi->s_groups_count;
1153         } else {
1154                 group = ext4_get_group_number(sb, blk_off) + 1;
1155                 last = (ext4_group_t)(group + EXT4_DESC_PER_BLOCK(sb) - 2);
1156         }
1157
1158         while (group < sbi->s_groups_count) {
1159                 struct buffer_head *bh;
1160                 ext4_fsblk_t backup_block;
1161                 int has_super = ext4_bg_has_super(sb, group);
1162                 ext4_fsblk_t first_block = ext4_group_first_block_no(sb, group);
1163
1164                 /* Out of journal space, and can't get more - abort - so sad */
1165                 err = ext4_resize_ensure_credits_batch(handle, 1);
1166                 if (err < 0)
1167                         break;
1168
1169                 if (meta_bg == 0)
1170                         backup_block = ((ext4_fsblk_t)group) * bpg + blk_off;
1171                 else
1172                         backup_block = first_block + has_super;
1173
1174                 bh = sb_getblk(sb, backup_block);
1175                 if (unlikely(!bh)) {
1176                         err = -ENOMEM;
1177                         break;
1178                 }
1179                 ext4_debug("update metadata backup %llu(+%llu)\n",
1180                            backup_block, backup_block -
1181                            ext4_group_first_block_no(sb, group));
1182                 BUFFER_TRACE(bh, "get_write_access");
1183                 if ((err = ext4_journal_get_write_access(handle, sb, bh,
1184                                                          EXT4_JTR_NONE))) {
1185                         brelse(bh);
1186                         break;
1187                 }
1188                 lock_buffer(bh);
1189                 memcpy(bh->b_data, data, size);
1190                 if (rest)
1191                         memset(bh->b_data + size, 0, rest);
1192                 if (has_super && (backup_block == first_block))
1193                         ext4_set_block_group_nr(sb, bh->b_data, group);
1194                 set_buffer_uptodate(bh);
1195                 unlock_buffer(bh);
1196                 err = ext4_handle_dirty_metadata(handle, NULL, bh);
1197                 if (unlikely(err))
1198                         ext4_std_error(sb, err);
1199                 brelse(bh);
1200
1201                 if (meta_bg == 0)
1202                         group = ext4_list_backups(sb, &three, &five, &seven);
1203                 else if (group == last)
1204                         break;
1205                 else
1206                         group = last;
1207         }
1208         if ((err2 = ext4_journal_stop(handle)) && !err)
1209                 err = err2;
1210
1211         /*
1212          * Ugh! Need to have e2fsck write the backup copies.  It is too
1213          * late to revert the resize, we shouldn't fail just because of
1214          * the backup copies (they are only needed in case of corruption).
1215          *
1216          * However, if we got here we have a journal problem too, so we
1217          * can't really start a transaction to mark the superblock.
1218          * Chicken out and just set the flag on the hope it will be written
1219          * to disk, and if not - we will simply wait until next fsck.
1220          */
1221 exit_err:
1222         if (err) {
1223                 ext4_warning(sb, "can't update backup for group %u (err %d), "
1224                              "forcing fsck on next reboot", group, err);
1225                 sbi->s_mount_state &= ~EXT4_VALID_FS;
1226                 sbi->s_es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
1227                 mark_buffer_dirty(sbi->s_sbh);
1228         }
1229 }
1230
1231 /*
1232  * ext4_add_new_descs() adds @count group descriptor of groups
1233  * starting at @group
1234  *
1235  * @handle: journal handle
1236  * @sb: super block
1237  * @group: the group no. of the first group desc to be added
1238  * @resize_inode: the resize inode
1239  * @count: number of group descriptors to be added
1240  */
1241 static int ext4_add_new_descs(handle_t *handle, struct super_block *sb,
1242                               ext4_group_t group, struct inode *resize_inode,
1243                               ext4_group_t count)
1244 {
1245         struct ext4_sb_info *sbi = EXT4_SB(sb);
1246         struct ext4_super_block *es = sbi->s_es;
1247         struct buffer_head *gdb_bh;
1248         int i, gdb_off, gdb_num, err = 0;
1249         int meta_bg;
1250
1251         meta_bg = ext4_has_feature_meta_bg(sb);
1252         for (i = 0; i < count; i++, group++) {
1253                 int reserved_gdb = ext4_bg_has_super(sb, group) ?
1254                         le16_to_cpu(es->s_reserved_gdt_blocks) : 0;
1255
1256                 gdb_off = group % EXT4_DESC_PER_BLOCK(sb);
1257                 gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
1258
1259                 /*
1260                  * We will only either add reserved group blocks to a backup group
1261                  * or remove reserved blocks for the first group in a new group block.
1262                  * Doing both would be mean more complex code, and sane people don't
1263                  * use non-sparse filesystems anymore.  This is already checked above.
1264                  */
1265                 if (gdb_off) {
1266                         gdb_bh = sbi_array_rcu_deref(sbi, s_group_desc,
1267                                                      gdb_num);
1268                         BUFFER_TRACE(gdb_bh, "get_write_access");
1269                         err = ext4_journal_get_write_access(handle, sb, gdb_bh,
1270                                                             EXT4_JTR_NONE);
1271
1272                         if (!err && reserved_gdb && ext4_bg_num_gdb(sb, group))
1273                                 err = reserve_backup_gdb(handle, resize_inode, group);
1274                 } else if (meta_bg != 0) {
1275                         err = add_new_gdb_meta_bg(sb, handle, group);
1276                 } else {
1277                         err = add_new_gdb(handle, resize_inode, group);
1278                 }
1279                 if (err)
1280                         break;
1281         }
1282         return err;
1283 }
1284
1285 static struct buffer_head *ext4_get_bitmap(struct super_block *sb, __u64 block)
1286 {
1287         struct buffer_head *bh = sb_getblk(sb, block);
1288         if (unlikely(!bh))
1289                 return NULL;
1290         if (!bh_uptodate_or_lock(bh)) {
1291                 if (ext4_read_bh(bh, 0, NULL) < 0) {
1292                         brelse(bh);
1293                         return NULL;
1294                 }
1295         }
1296
1297         return bh;
1298 }
1299
1300 static int ext4_set_bitmap_checksums(struct super_block *sb,
1301                                      struct ext4_group_desc *gdp,
1302                                      struct ext4_new_group_data *group_data)
1303 {
1304         struct buffer_head *bh;
1305
1306         if (!ext4_has_metadata_csum(sb))
1307                 return 0;
1308
1309         bh = ext4_get_bitmap(sb, group_data->inode_bitmap);
1310         if (!bh)
1311                 return -EIO;
1312         ext4_inode_bitmap_csum_set(sb, gdp, bh,
1313                                    EXT4_INODES_PER_GROUP(sb) / 8);
1314         brelse(bh);
1315
1316         bh = ext4_get_bitmap(sb, group_data->block_bitmap);
1317         if (!bh)
1318                 return -EIO;
1319         ext4_block_bitmap_csum_set(sb, gdp, bh);
1320         brelse(bh);
1321
1322         return 0;
1323 }
1324
1325 /*
1326  * ext4_setup_new_descs() will set up the group descriptor descriptors of a flex bg
1327  */
1328 static int ext4_setup_new_descs(handle_t *handle, struct super_block *sb,
1329                                 struct ext4_new_flex_group_data *flex_gd)
1330 {
1331         struct ext4_new_group_data      *group_data = flex_gd->groups;
1332         struct ext4_group_desc          *gdp;
1333         struct ext4_sb_info             *sbi = EXT4_SB(sb);
1334         struct buffer_head              *gdb_bh;
1335         ext4_group_t                    group;
1336         __u16                           *bg_flags = flex_gd->bg_flags;
1337         int                             i, gdb_off, gdb_num, err = 0;
1338
1339
1340         for (i = 0; i < flex_gd->count; i++, group_data++, bg_flags++) {
1341                 group = group_data->group;
1342
1343                 gdb_off = group % EXT4_DESC_PER_BLOCK(sb);
1344                 gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
1345
1346                 /*
1347                  * get_write_access() has been called on gdb_bh by ext4_add_new_desc().
1348                  */
1349                 gdb_bh = sbi_array_rcu_deref(sbi, s_group_desc, gdb_num);
1350                 /* Update group descriptor block for new group */
1351                 gdp = (struct ext4_group_desc *)(gdb_bh->b_data +
1352                                                  gdb_off * EXT4_DESC_SIZE(sb));
1353
1354                 memset(gdp, 0, EXT4_DESC_SIZE(sb));
1355                 ext4_block_bitmap_set(sb, gdp, group_data->block_bitmap);
1356                 ext4_inode_bitmap_set(sb, gdp, group_data->inode_bitmap);
1357                 err = ext4_set_bitmap_checksums(sb, gdp, group_data);
1358                 if (err) {
1359                         ext4_std_error(sb, err);
1360                         break;
1361                 }
1362
1363                 ext4_inode_table_set(sb, gdp, group_data->inode_table);
1364                 ext4_free_group_clusters_set(sb, gdp,
1365                                              group_data->free_clusters_count);
1366                 ext4_free_inodes_set(sb, gdp, EXT4_INODES_PER_GROUP(sb));
1367                 if (ext4_has_group_desc_csum(sb))
1368                         ext4_itable_unused_set(sb, gdp,
1369                                                EXT4_INODES_PER_GROUP(sb));
1370                 gdp->bg_flags = cpu_to_le16(*bg_flags);
1371                 ext4_group_desc_csum_set(sb, group, gdp);
1372
1373                 err = ext4_handle_dirty_metadata(handle, NULL, gdb_bh);
1374                 if (unlikely(err)) {
1375                         ext4_std_error(sb, err);
1376                         break;
1377                 }
1378
1379                 /*
1380                  * We can allocate memory for mb_alloc based on the new group
1381                  * descriptor
1382                  */
1383                 err = ext4_mb_add_groupinfo(sb, group, gdp);
1384                 if (err)
1385                         break;
1386         }
1387         return err;
1388 }
1389
1390 static void ext4_add_overhead(struct super_block *sb,
1391                               const ext4_fsblk_t overhead)
1392 {
1393        struct ext4_sb_info *sbi = EXT4_SB(sb);
1394        struct ext4_super_block *es = sbi->s_es;
1395
1396        sbi->s_overhead += overhead;
1397        es->s_overhead_clusters = cpu_to_le32(sbi->s_overhead);
1398        smp_wmb();
1399 }
1400
1401 /*
1402  * ext4_update_super() updates the super block so that the newly added
1403  * groups can be seen by the filesystem.
1404  *
1405  * @sb: super block
1406  * @flex_gd: new added groups
1407  */
1408 static void ext4_update_super(struct super_block *sb,
1409                              struct ext4_new_flex_group_data *flex_gd)
1410 {
1411         ext4_fsblk_t blocks_count = 0;
1412         ext4_fsblk_t free_blocks = 0;
1413         ext4_fsblk_t reserved_blocks = 0;
1414         struct ext4_new_group_data *group_data = flex_gd->groups;
1415         struct ext4_sb_info *sbi = EXT4_SB(sb);
1416         struct ext4_super_block *es = sbi->s_es;
1417         int i;
1418
1419         BUG_ON(flex_gd->count == 0 || group_data == NULL);
1420         /*
1421          * Make the new blocks and inodes valid next.  We do this before
1422          * increasing the group count so that once the group is enabled,
1423          * all of its blocks and inodes are already valid.
1424          *
1425          * We always allocate group-by-group, then block-by-block or
1426          * inode-by-inode within a group, so enabling these
1427          * blocks/inodes before the group is live won't actually let us
1428          * allocate the new space yet.
1429          */
1430         for (i = 0; i < flex_gd->count; i++) {
1431                 blocks_count += group_data[i].blocks_count;
1432                 free_blocks += EXT4_C2B(sbi, group_data[i].free_clusters_count);
1433         }
1434
1435         reserved_blocks = ext4_r_blocks_count(es) * 100;
1436         reserved_blocks = div64_u64(reserved_blocks, ext4_blocks_count(es));
1437         reserved_blocks *= blocks_count;
1438         do_div(reserved_blocks, 100);
1439
1440         lock_buffer(sbi->s_sbh);
1441         ext4_blocks_count_set(es, ext4_blocks_count(es) + blocks_count);
1442         ext4_free_blocks_count_set(es, ext4_free_blocks_count(es) + free_blocks);
1443         le32_add_cpu(&es->s_inodes_count, EXT4_INODES_PER_GROUP(sb) *
1444                      flex_gd->count);
1445         le32_add_cpu(&es->s_free_inodes_count, EXT4_INODES_PER_GROUP(sb) *
1446                      flex_gd->count);
1447
1448         ext4_debug("free blocks count %llu", ext4_free_blocks_count(es));
1449         /*
1450          * We need to protect s_groups_count against other CPUs seeing
1451          * inconsistent state in the superblock.
1452          *
1453          * The precise rules we use are:
1454          *
1455          * * Writers must perform a smp_wmb() after updating all
1456          *   dependent data and before modifying the groups count
1457          *
1458          * * Readers must perform an smp_rmb() after reading the groups
1459          *   count and before reading any dependent data.
1460          *
1461          * NB. These rules can be relaxed when checking the group count
1462          * while freeing data, as we can only allocate from a block
1463          * group after serialising against the group count, and we can
1464          * only then free after serialising in turn against that
1465          * allocation.
1466          */
1467         smp_wmb();
1468
1469         /* Update the global fs size fields */
1470         sbi->s_groups_count += flex_gd->count;
1471         sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
1472                         (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
1473
1474         /* Update the reserved block counts only once the new group is
1475          * active. */
1476         ext4_r_blocks_count_set(es, ext4_r_blocks_count(es) +
1477                                 reserved_blocks);
1478
1479         /* Update the free space counts */
1480         percpu_counter_add(&sbi->s_freeclusters_counter,
1481                            EXT4_NUM_B2C(sbi, free_blocks));
1482         percpu_counter_add(&sbi->s_freeinodes_counter,
1483                            EXT4_INODES_PER_GROUP(sb) * flex_gd->count);
1484
1485         ext4_debug("free blocks count %llu",
1486                    percpu_counter_read(&sbi->s_freeclusters_counter));
1487         if (ext4_has_feature_flex_bg(sb) && sbi->s_log_groups_per_flex) {
1488                 ext4_group_t flex_group;
1489                 struct flex_groups *fg;
1490
1491                 flex_group = ext4_flex_group(sbi, group_data[0].group);
1492                 fg = sbi_array_rcu_deref(sbi, s_flex_groups, flex_group);
1493                 atomic64_add(EXT4_NUM_B2C(sbi, free_blocks),
1494                              &fg->free_clusters);
1495                 atomic_add(EXT4_INODES_PER_GROUP(sb) * flex_gd->count,
1496                            &fg->free_inodes);
1497         }
1498
1499         /*
1500          * Update the fs overhead information.
1501          *
1502          * For bigalloc, if the superblock already has a properly calculated
1503          * overhead, update it with a value based on numbers already computed
1504          * above for the newly allocated capacity.
1505          */
1506         if (ext4_has_feature_bigalloc(sb) && (sbi->s_overhead != 0))
1507                 ext4_add_overhead(sb,
1508                         EXT4_NUM_B2C(sbi, blocks_count - free_blocks));
1509         else
1510                 ext4_calculate_overhead(sb);
1511         es->s_overhead_clusters = cpu_to_le32(sbi->s_overhead);
1512
1513         ext4_superblock_csum_set(sb);
1514         unlock_buffer(sbi->s_sbh);
1515         if (test_opt(sb, DEBUG))
1516                 printk(KERN_DEBUG "EXT4-fs: added group %u:"
1517                        "%llu blocks(%llu free %llu reserved)\n", flex_gd->count,
1518                        blocks_count, free_blocks, reserved_blocks);
1519 }
1520
1521 /* Add a flex group to an fs. Ensure we handle all possible error conditions
1522  * _before_ we start modifying the filesystem, because we cannot abort the
1523  * transaction and not have it write the data to disk.
1524  */
1525 static int ext4_flex_group_add(struct super_block *sb,
1526                                struct inode *resize_inode,
1527                                struct ext4_new_flex_group_data *flex_gd)
1528 {
1529         struct ext4_sb_info *sbi = EXT4_SB(sb);
1530         struct ext4_super_block *es = sbi->s_es;
1531         ext4_fsblk_t o_blocks_count;
1532         ext4_grpblk_t last;
1533         ext4_group_t group;
1534         handle_t *handle;
1535         unsigned reserved_gdb;
1536         int err = 0, err2 = 0, credit;
1537
1538         BUG_ON(!flex_gd->count || !flex_gd->groups || !flex_gd->bg_flags);
1539
1540         reserved_gdb = le16_to_cpu(es->s_reserved_gdt_blocks);
1541         o_blocks_count = ext4_blocks_count(es);
1542         ext4_get_group_no_and_offset(sb, o_blocks_count, &group, &last);
1543         BUG_ON(last);
1544
1545         err = setup_new_flex_group_blocks(sb, flex_gd);
1546         if (err)
1547                 goto exit;
1548         /*
1549          * We will always be modifying at least the superblock and  GDT
1550          * blocks.  If we are adding a group past the last current GDT block,
1551          * we will also modify the inode and the dindirect block.  If we
1552          * are adding a group with superblock/GDT backups  we will also
1553          * modify each of the reserved GDT dindirect blocks.
1554          */
1555         credit = 3;     /* sb, resize inode, resize inode dindirect */
1556         /* GDT blocks */
1557         credit += 1 + DIV_ROUND_UP(flex_gd->count, EXT4_DESC_PER_BLOCK(sb));
1558         credit += reserved_gdb; /* Reserved GDT dindirect blocks */
1559         handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, credit);
1560         if (IS_ERR(handle)) {
1561                 err = PTR_ERR(handle);
1562                 goto exit;
1563         }
1564
1565         BUFFER_TRACE(sbi->s_sbh, "get_write_access");
1566         err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
1567                                             EXT4_JTR_NONE);
1568         if (err)
1569                 goto exit_journal;
1570
1571         group = flex_gd->groups[0].group;
1572         BUG_ON(group != sbi->s_groups_count);
1573         err = ext4_add_new_descs(handle, sb, group,
1574                                 resize_inode, flex_gd->count);
1575         if (err)
1576                 goto exit_journal;
1577
1578         err = ext4_setup_new_descs(handle, sb, flex_gd);
1579         if (err)
1580                 goto exit_journal;
1581
1582         ext4_update_super(sb, flex_gd);
1583
1584         err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
1585
1586 exit_journal:
1587         err2 = ext4_journal_stop(handle);
1588         if (!err)
1589                 err = err2;
1590
1591         if (!err) {
1592                 int gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
1593                 int gdb_num_end = ((group + flex_gd->count - 1) /
1594                                    EXT4_DESC_PER_BLOCK(sb));
1595                 int meta_bg = ext4_has_feature_meta_bg(sb);
1596                 sector_t padding_blocks = meta_bg ? 0 : sbi->s_sbh->b_blocknr -
1597                                          ext4_group_first_block_no(sb, 0);
1598
1599                 update_backups(sb, ext4_group_first_block_no(sb, 0),
1600                                (char *)es, sizeof(struct ext4_super_block), 0);
1601                 for (; gdb_num <= gdb_num_end; gdb_num++) {
1602                         struct buffer_head *gdb_bh;
1603
1604                         gdb_bh = sbi_array_rcu_deref(sbi, s_group_desc,
1605                                                      gdb_num);
1606                         update_backups(sb, gdb_bh->b_blocknr - padding_blocks,
1607                                        gdb_bh->b_data, gdb_bh->b_size, meta_bg);
1608                 }
1609         }
1610 exit:
1611         return err;
1612 }
1613
1614 static int ext4_setup_next_flex_gd(struct super_block *sb,
1615                                     struct ext4_new_flex_group_data *flex_gd,
1616                                     ext4_fsblk_t n_blocks_count)
1617 {
1618         struct ext4_sb_info *sbi = EXT4_SB(sb);
1619         struct ext4_super_block *es = sbi->s_es;
1620         struct ext4_new_group_data *group_data = flex_gd->groups;
1621         ext4_fsblk_t o_blocks_count;
1622         ext4_group_t n_group;
1623         ext4_group_t group;
1624         ext4_group_t last_group;
1625         ext4_grpblk_t last;
1626         ext4_grpblk_t clusters_per_group;
1627         unsigned long i;
1628
1629         clusters_per_group = EXT4_CLUSTERS_PER_GROUP(sb);
1630
1631         o_blocks_count = ext4_blocks_count(es);
1632
1633         if (o_blocks_count == n_blocks_count)
1634                 return 0;
1635
1636         ext4_get_group_no_and_offset(sb, o_blocks_count, &group, &last);
1637         BUG_ON(last);
1638         ext4_get_group_no_and_offset(sb, n_blocks_count - 1, &n_group, &last);
1639
1640         last_group = group | (flex_gd->resize_bg - 1);
1641         if (last_group > n_group)
1642                 last_group = n_group;
1643
1644         flex_gd->count = last_group - group + 1;
1645
1646         for (i = 0; i < flex_gd->count; i++) {
1647                 int overhead;
1648
1649                 group_data[i].group = group + i;
1650                 group_data[i].blocks_count = EXT4_BLOCKS_PER_GROUP(sb);
1651                 overhead = ext4_group_overhead_blocks(sb, group + i);
1652                 group_data[i].mdata_blocks = overhead;
1653                 group_data[i].free_clusters_count = EXT4_CLUSTERS_PER_GROUP(sb);
1654                 if (ext4_has_group_desc_csum(sb)) {
1655                         flex_gd->bg_flags[i] = EXT4_BG_BLOCK_UNINIT |
1656                                                EXT4_BG_INODE_UNINIT;
1657                         if (!test_opt(sb, INIT_INODE_TABLE))
1658                                 flex_gd->bg_flags[i] |= EXT4_BG_INODE_ZEROED;
1659                 } else
1660                         flex_gd->bg_flags[i] = EXT4_BG_INODE_ZEROED;
1661         }
1662
1663         if (last_group == n_group && ext4_has_group_desc_csum(sb))
1664                 /* We need to initialize block bitmap of last group. */
1665                 flex_gd->bg_flags[i - 1] &= ~EXT4_BG_BLOCK_UNINIT;
1666
1667         if ((last_group == n_group) && (last != clusters_per_group - 1)) {
1668                 group_data[i - 1].blocks_count = EXT4_C2B(sbi, last + 1);
1669                 group_data[i - 1].free_clusters_count -= clusters_per_group -
1670                                                        last - 1;
1671         }
1672
1673         return 1;
1674 }
1675
1676 /* Add group descriptor data to an existing or new group descriptor block.
1677  * Ensure we handle all possible error conditions _before_ we start modifying
1678  * the filesystem, because we cannot abort the transaction and not have it
1679  * write the data to disk.
1680  *
1681  * If we are on a GDT block boundary, we need to get the reserved GDT block.
1682  * Otherwise, we may need to add backup GDT blocks for a sparse group.
1683  *
1684  * We only need to hold the superblock lock while we are actually adding
1685  * in the new group's counts to the superblock.  Prior to that we have
1686  * not really "added" the group at all.  We re-check that we are still
1687  * adding in the last group in case things have changed since verifying.
1688  */
1689 int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input)
1690 {
1691         struct ext4_new_flex_group_data flex_gd;
1692         struct ext4_sb_info *sbi = EXT4_SB(sb);
1693         struct ext4_super_block *es = sbi->s_es;
1694         int reserved_gdb = ext4_bg_has_super(sb, input->group) ?
1695                 le16_to_cpu(es->s_reserved_gdt_blocks) : 0;
1696         struct inode *inode = NULL;
1697         int gdb_off;
1698         int err;
1699         __u16 bg_flags = 0;
1700
1701         gdb_off = input->group % EXT4_DESC_PER_BLOCK(sb);
1702
1703         if (gdb_off == 0 && !ext4_has_feature_sparse_super(sb)) {
1704                 ext4_warning(sb, "Can't resize non-sparse filesystem further");
1705                 return -EPERM;
1706         }
1707
1708         if (ext4_blocks_count(es) + input->blocks_count <
1709             ext4_blocks_count(es)) {
1710                 ext4_warning(sb, "blocks_count overflow");
1711                 return -EINVAL;
1712         }
1713
1714         if (le32_to_cpu(es->s_inodes_count) + EXT4_INODES_PER_GROUP(sb) <
1715             le32_to_cpu(es->s_inodes_count)) {
1716                 ext4_warning(sb, "inodes_count overflow");
1717                 return -EINVAL;
1718         }
1719
1720         if (reserved_gdb || gdb_off == 0) {
1721                 if (!ext4_has_feature_resize_inode(sb) ||
1722                     !le16_to_cpu(es->s_reserved_gdt_blocks)) {
1723                         ext4_warning(sb,
1724                                      "No reserved GDT blocks, can't resize");
1725                         return -EPERM;
1726                 }
1727                 inode = ext4_iget(sb, EXT4_RESIZE_INO, EXT4_IGET_SPECIAL);
1728                 if (IS_ERR(inode)) {
1729                         ext4_warning(sb, "Error opening resize inode");
1730                         return PTR_ERR(inode);
1731                 }
1732         }
1733
1734
1735         err = verify_group_input(sb, input);
1736         if (err)
1737                 goto out;
1738
1739         err = ext4_alloc_flex_bg_array(sb, input->group + 1);
1740         if (err)
1741                 goto out;
1742
1743         err = ext4_mb_alloc_groupinfo(sb, input->group + 1);
1744         if (err)
1745                 goto out;
1746
1747         flex_gd.count = 1;
1748         flex_gd.groups = input;
1749         flex_gd.bg_flags = &bg_flags;
1750         err = ext4_flex_group_add(sb, inode, &flex_gd);
1751 out:
1752         iput(inode);
1753         return err;
1754 } /* ext4_group_add */
1755
1756 /*
1757  * extend a group without checking assuming that checking has been done.
1758  */
1759 static int ext4_group_extend_no_check(struct super_block *sb,
1760                                       ext4_fsblk_t o_blocks_count, ext4_grpblk_t add)
1761 {
1762         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
1763         handle_t *handle;
1764         int err = 0, err2;
1765
1766         /* We will update the superblock, one block bitmap, and
1767          * one group descriptor via ext4_group_add_blocks().
1768          */
1769         handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, 3);
1770         if (IS_ERR(handle)) {
1771                 err = PTR_ERR(handle);
1772                 ext4_warning(sb, "error %d on journal start", err);
1773                 return err;
1774         }
1775
1776         BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
1777         err = ext4_journal_get_write_access(handle, sb, EXT4_SB(sb)->s_sbh,
1778                                             EXT4_JTR_NONE);
1779         if (err) {
1780                 ext4_warning(sb, "error %d on journal write access", err);
1781                 goto errout;
1782         }
1783
1784         lock_buffer(EXT4_SB(sb)->s_sbh);
1785         ext4_blocks_count_set(es, o_blocks_count + add);
1786         ext4_free_blocks_count_set(es, ext4_free_blocks_count(es) + add);
1787         ext4_superblock_csum_set(sb);
1788         unlock_buffer(EXT4_SB(sb)->s_sbh);
1789         ext4_debug("freeing blocks %llu through %llu\n", o_blocks_count,
1790                    o_blocks_count + add);
1791         /* We add the blocks to the bitmap and set the group need init bit */
1792         err = ext4_group_add_blocks(handle, sb, o_blocks_count, add);
1793         if (err)
1794                 goto errout;
1795         ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
1796         ext4_debug("freed blocks %llu through %llu\n", o_blocks_count,
1797                    o_blocks_count + add);
1798 errout:
1799         err2 = ext4_journal_stop(handle);
1800         if (err2 && !err)
1801                 err = err2;
1802
1803         if (!err) {
1804                 if (test_opt(sb, DEBUG))
1805                         printk(KERN_DEBUG "EXT4-fs: extended group to %llu "
1806                                "blocks\n", ext4_blocks_count(es));
1807                 update_backups(sb, ext4_group_first_block_no(sb, 0),
1808                                (char *)es, sizeof(struct ext4_super_block), 0);
1809         }
1810         return err;
1811 }
1812
1813 /*
1814  * Extend the filesystem to the new number of blocks specified.  This entry
1815  * point is only used to extend the current filesystem to the end of the last
1816  * existing group.  It can be accessed via ioctl, or by "remount,resize=<size>"
1817  * for emergencies (because it has no dependencies on reserved blocks).
1818  *
1819  * If we _really_ wanted, we could use default values to call ext4_group_add()
1820  * allow the "remount" trick to work for arbitrary resizing, assuming enough
1821  * GDT blocks are reserved to grow to the desired size.
1822  */
1823 int ext4_group_extend(struct super_block *sb, struct ext4_super_block *es,
1824                       ext4_fsblk_t n_blocks_count)
1825 {
1826         ext4_fsblk_t o_blocks_count;
1827         ext4_grpblk_t last;
1828         ext4_grpblk_t add;
1829         struct buffer_head *bh;
1830         ext4_group_t group;
1831
1832         o_blocks_count = ext4_blocks_count(es);
1833
1834         if (test_opt(sb, DEBUG))
1835                 ext4_msg(sb, KERN_DEBUG,
1836                          "extending last group from %llu to %llu blocks",
1837                          o_blocks_count, n_blocks_count);
1838
1839         if (n_blocks_count == 0 || n_blocks_count == o_blocks_count)
1840                 return 0;
1841
1842         if (n_blocks_count > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) {
1843                 ext4_msg(sb, KERN_ERR,
1844                          "filesystem too large to resize to %llu blocks safely",
1845                          n_blocks_count);
1846                 return -EINVAL;
1847         }
1848
1849         if (n_blocks_count < o_blocks_count) {
1850                 ext4_warning(sb, "can't shrink FS - resize aborted");
1851                 return -EINVAL;
1852         }
1853
1854         /* Handle the remaining blocks in the last group only. */
1855         ext4_get_group_no_and_offset(sb, o_blocks_count, &group, &last);
1856
1857         if (last == 0) {
1858                 ext4_warning(sb, "need to use ext2online to resize further");
1859                 return -EPERM;
1860         }
1861
1862         add = EXT4_BLOCKS_PER_GROUP(sb) - last;
1863
1864         if (o_blocks_count + add < o_blocks_count) {
1865                 ext4_warning(sb, "blocks_count overflow");
1866                 return -EINVAL;
1867         }
1868
1869         if (o_blocks_count + add > n_blocks_count)
1870                 add = n_blocks_count - o_blocks_count;
1871
1872         if (o_blocks_count + add < n_blocks_count)
1873                 ext4_warning(sb, "will only finish group (%llu blocks, %u new)",
1874                              o_blocks_count + add, add);
1875
1876         /* See if the device is actually as big as what was requested */
1877         bh = ext4_sb_bread(sb, o_blocks_count + add - 1, 0);
1878         if (IS_ERR(bh)) {
1879                 ext4_warning(sb, "can't read last block, resize aborted");
1880                 return -ENOSPC;
1881         }
1882         brelse(bh);
1883
1884         return ext4_group_extend_no_check(sb, o_blocks_count, add);
1885 } /* ext4_group_extend */
1886
1887
1888 static int num_desc_blocks(struct super_block *sb, ext4_group_t groups)
1889 {
1890         return (groups + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb);
1891 }
1892
1893 /*
1894  * Release the resize inode and drop the resize_inode feature if there
1895  * are no more reserved gdt blocks, and then convert the file system
1896  * to enable meta_bg
1897  */
1898 static int ext4_convert_meta_bg(struct super_block *sb, struct inode *inode)
1899 {
1900         handle_t *handle;
1901         struct ext4_sb_info *sbi = EXT4_SB(sb);
1902         struct ext4_super_block *es = sbi->s_es;
1903         struct ext4_inode_info *ei = EXT4_I(inode);
1904         ext4_fsblk_t nr;
1905         int i, ret, err = 0;
1906         int credits = 1;
1907
1908         ext4_msg(sb, KERN_INFO, "Converting file system to meta_bg");
1909         if (inode) {
1910                 if (es->s_reserved_gdt_blocks) {
1911                         ext4_error(sb, "Unexpected non-zero "
1912                                    "s_reserved_gdt_blocks");
1913                         return -EPERM;
1914                 }
1915
1916                 /* Do a quick sanity check of the resize inode */
1917                 if (inode->i_blocks != 1 << (inode->i_blkbits -
1918                                              (9 - sbi->s_cluster_bits)))
1919                         goto invalid_resize_inode;
1920                 for (i = 0; i < EXT4_N_BLOCKS; i++) {
1921                         if (i == EXT4_DIND_BLOCK) {
1922                                 if (ei->i_data[i])
1923                                         continue;
1924                                 else
1925                                         goto invalid_resize_inode;
1926                         }
1927                         if (ei->i_data[i])
1928                                 goto invalid_resize_inode;
1929                 }
1930                 credits += 3;   /* block bitmap, bg descriptor, resize inode */
1931         }
1932
1933         handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, credits);
1934         if (IS_ERR(handle))
1935                 return PTR_ERR(handle);
1936
1937         BUFFER_TRACE(sbi->s_sbh, "get_write_access");
1938         err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
1939                                             EXT4_JTR_NONE);
1940         if (err)
1941                 goto errout;
1942
1943         lock_buffer(sbi->s_sbh);
1944         ext4_clear_feature_resize_inode(sb);
1945         ext4_set_feature_meta_bg(sb);
1946         sbi->s_es->s_first_meta_bg =
1947                 cpu_to_le32(num_desc_blocks(sb, sbi->s_groups_count));
1948         ext4_superblock_csum_set(sb);
1949         unlock_buffer(sbi->s_sbh);
1950
1951         err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
1952         if (err) {
1953                 ext4_std_error(sb, err);
1954                 goto errout;
1955         }
1956
1957         if (inode) {
1958                 nr = le32_to_cpu(ei->i_data[EXT4_DIND_BLOCK]);
1959                 ext4_free_blocks(handle, inode, NULL, nr, 1,
1960                                  EXT4_FREE_BLOCKS_METADATA |
1961                                  EXT4_FREE_BLOCKS_FORGET);
1962                 ei->i_data[EXT4_DIND_BLOCK] = 0;
1963                 inode->i_blocks = 0;
1964
1965                 err = ext4_mark_inode_dirty(handle, inode);
1966                 if (err)
1967                         ext4_std_error(sb, err);
1968         }
1969
1970 errout:
1971         ret = ext4_journal_stop(handle);
1972         return err ? err : ret;
1973
1974 invalid_resize_inode:
1975         ext4_error(sb, "corrupted/inconsistent resize inode");
1976         return -EINVAL;
1977 }
1978
1979 /*
1980  * ext4_resize_fs() resizes a fs to new size specified by @n_blocks_count
1981  *
1982  * @sb: super block of the fs to be resized
1983  * @n_blocks_count: the number of blocks resides in the resized fs
1984  */
1985 int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count)
1986 {
1987         struct ext4_new_flex_group_data *flex_gd = NULL;
1988         struct ext4_sb_info *sbi = EXT4_SB(sb);
1989         struct ext4_super_block *es = sbi->s_es;
1990         struct buffer_head *bh;
1991         struct inode *resize_inode = NULL;
1992         ext4_grpblk_t add, offset;
1993         unsigned long n_desc_blocks;
1994         unsigned long o_desc_blocks;
1995         ext4_group_t o_group;
1996         ext4_group_t n_group;
1997         ext4_fsblk_t o_blocks_count;
1998         ext4_fsblk_t n_blocks_count_retry = 0;
1999         unsigned long last_update_time = 0;
2000         int err = 0;
2001         int meta_bg;
2002         unsigned int flexbg_size = ext4_flex_bg_size(sbi);
2003
2004         /* See if the device is actually as big as what was requested */
2005         bh = ext4_sb_bread(sb, n_blocks_count - 1, 0);
2006         if (IS_ERR(bh)) {
2007                 ext4_warning(sb, "can't read last block, resize aborted");
2008                 return -ENOSPC;
2009         }
2010         brelse(bh);
2011
2012         /*
2013          * For bigalloc, trim the requested size to the nearest cluster
2014          * boundary to avoid creating an unusable filesystem. We do this
2015          * silently, instead of returning an error, to avoid breaking
2016          * callers that blindly resize the filesystem to the full size of
2017          * the underlying block device.
2018          */
2019         if (ext4_has_feature_bigalloc(sb))
2020                 n_blocks_count &= ~((1 << EXT4_CLUSTER_BITS(sb)) - 1);
2021
2022 retry:
2023         o_blocks_count = ext4_blocks_count(es);
2024
2025         ext4_msg(sb, KERN_INFO, "resizing filesystem from %llu "
2026                  "to %llu blocks", o_blocks_count, n_blocks_count);
2027
2028         if (n_blocks_count < o_blocks_count) {
2029                 /* On-line shrinking not supported */
2030                 ext4_warning(sb, "can't shrink FS - resize aborted");
2031                 return -EINVAL;
2032         }
2033
2034         if (n_blocks_count == o_blocks_count)
2035                 /* Nothing need to do */
2036                 return 0;
2037
2038         n_group = ext4_get_group_number(sb, n_blocks_count - 1);
2039         if (n_group >= (0xFFFFFFFFUL / EXT4_INODES_PER_GROUP(sb))) {
2040                 ext4_warning(sb, "resize would cause inodes_count overflow");
2041                 return -EINVAL;
2042         }
2043         ext4_get_group_no_and_offset(sb, o_blocks_count - 1, &o_group, &offset);
2044
2045         n_desc_blocks = num_desc_blocks(sb, n_group + 1);
2046         o_desc_blocks = num_desc_blocks(sb, sbi->s_groups_count);
2047
2048         meta_bg = ext4_has_feature_meta_bg(sb);
2049
2050         if (ext4_has_feature_resize_inode(sb)) {
2051                 if (meta_bg) {
2052                         ext4_error(sb, "resize_inode and meta_bg enabled "
2053                                    "simultaneously");
2054                         return -EINVAL;
2055                 }
2056                 if (n_desc_blocks > o_desc_blocks +
2057                     le16_to_cpu(es->s_reserved_gdt_blocks)) {
2058                         n_blocks_count_retry = n_blocks_count;
2059                         n_desc_blocks = o_desc_blocks +
2060                                 le16_to_cpu(es->s_reserved_gdt_blocks);
2061                         n_group = n_desc_blocks * EXT4_DESC_PER_BLOCK(sb);
2062                         n_blocks_count = (ext4_fsblk_t)n_group *
2063                                 EXT4_BLOCKS_PER_GROUP(sb) +
2064                                 le32_to_cpu(es->s_first_data_block);
2065                         n_group--; /* set to last group number */
2066                 }
2067
2068                 if (!resize_inode)
2069                         resize_inode = ext4_iget(sb, EXT4_RESIZE_INO,
2070                                                  EXT4_IGET_SPECIAL);
2071                 if (IS_ERR(resize_inode)) {
2072                         ext4_warning(sb, "Error opening resize inode");
2073                         return PTR_ERR(resize_inode);
2074                 }
2075         }
2076
2077         if ((!resize_inode && !meta_bg) || n_blocks_count == o_blocks_count) {
2078                 err = ext4_convert_meta_bg(sb, resize_inode);
2079                 if (err)
2080                         goto out;
2081                 if (resize_inode) {
2082                         iput(resize_inode);
2083                         resize_inode = NULL;
2084                 }
2085                 if (n_blocks_count_retry) {
2086                         n_blocks_count = n_blocks_count_retry;
2087                         n_blocks_count_retry = 0;
2088                         goto retry;
2089                 }
2090         }
2091
2092         /*
2093          * Make sure the last group has enough space so that it's
2094          * guaranteed to have enough space for all metadata blocks
2095          * that it might need to hold.  (We might not need to store
2096          * the inode table blocks in the last block group, but there
2097          * will be cases where this might be needed.)
2098          */
2099         if ((ext4_group_first_block_no(sb, n_group) +
2100              ext4_group_overhead_blocks(sb, n_group) + 2 +
2101              sbi->s_itb_per_group + sbi->s_cluster_ratio) >= n_blocks_count) {
2102                 n_blocks_count = ext4_group_first_block_no(sb, n_group);
2103                 n_group--;
2104                 n_blocks_count_retry = 0;
2105                 if (resize_inode) {
2106                         iput(resize_inode);
2107                         resize_inode = NULL;
2108                 }
2109                 goto retry;
2110         }
2111
2112         /* extend the last group */
2113         if (n_group == o_group)
2114                 add = n_blocks_count - o_blocks_count;
2115         else
2116                 add = EXT4_C2B(sbi, EXT4_CLUSTERS_PER_GROUP(sb) - (offset + 1));
2117         if (add > 0) {
2118                 err = ext4_group_extend_no_check(sb, o_blocks_count, add);
2119                 if (err)
2120                         goto out;
2121         }
2122
2123         if (ext4_blocks_count(es) == n_blocks_count && n_blocks_count_retry == 0)
2124                 goto out;
2125
2126         err = ext4_alloc_flex_bg_array(sb, n_group + 1);
2127         if (err)
2128                 goto out;
2129
2130         err = ext4_mb_alloc_groupinfo(sb, n_group + 1);
2131         if (err)
2132                 goto out;
2133
2134         flex_gd = alloc_flex_gd(flexbg_size);
2135         if (flex_gd == NULL) {
2136                 err = -ENOMEM;
2137                 goto out;
2138         }
2139
2140         /* Add flex groups. Note that a regular group is a
2141          * flex group with 1 group.
2142          */
2143         while (ext4_setup_next_flex_gd(sb, flex_gd, n_blocks_count)) {
2144                 if (time_is_before_jiffies(last_update_time + HZ * 10)) {
2145                         if (last_update_time)
2146                                 ext4_msg(sb, KERN_INFO,
2147                                          "resized to %llu blocks",
2148                                          ext4_blocks_count(es));
2149                         last_update_time = jiffies;
2150                 }
2151                 if (ext4_alloc_group_tables(sb, flex_gd, flexbg_size) != 0)
2152                         break;
2153                 err = ext4_flex_group_add(sb, resize_inode, flex_gd);
2154                 if (unlikely(err))
2155                         break;
2156         }
2157
2158         if (!err && n_blocks_count_retry) {
2159                 n_blocks_count = n_blocks_count_retry;
2160                 n_blocks_count_retry = 0;
2161                 free_flex_gd(flex_gd);
2162                 flex_gd = NULL;
2163                 if (resize_inode) {
2164                         iput(resize_inode);
2165                         resize_inode = NULL;
2166                 }
2167                 goto retry;
2168         }
2169
2170 out:
2171         if (flex_gd)
2172                 free_flex_gd(flex_gd);
2173         if (resize_inode != NULL)
2174                 iput(resize_inode);
2175         if (err)
2176                 ext4_warning(sb, "error (%d) occurred during "
2177                              "file system resize", err);
2178         ext4_msg(sb, KERN_INFO, "resized filesystem to %llu",
2179                  ext4_blocks_count(es));
2180         return err;
2181 }