btrfs-progs: convert: move intersect_with_sb
[platform/upstream/btrfs-progs.git] / btrfs-convert.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include "kerncompat.h"
20
21 #include <sys/ioctl.h>
22 #include <sys/mount.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <uuid/uuid.h>
30 #include <linux/limits.h>
31 #include <getopt.h>
32
33 #include "ctree.h"
34 #include "disk-io.h"
35 #include "volumes.h"
36 #include "transaction.h"
37 #include "crc32c.h"
38 #include "utils.h"
39 #include "task-utils.h"
40
41 #include <ext2fs/ext2_fs.h>
42 #include <ext2fs/ext2fs.h>
43 #include <ext2fs/ext2_ext_attr.h>
44
45 #define INO_OFFSET (BTRFS_FIRST_FREE_OBJECTID - EXT2_ROOT_INO)
46 #define CONV_IMAGE_SUBVOL_OBJECTID BTRFS_FIRST_FREE_OBJECTID
47
48 /*
49  * Compatibility code for e2fsprogs 1.41 which doesn't support RO compat flag
50  * BIGALLOC.
51  * Unlike normal RO compat flag, BIGALLOC affects how e2fsprogs check used
52  * space, and btrfs-convert heavily relies on it.
53  */
54 #ifdef HAVE_OLD_E2FSPROGS
55 #define EXT2FS_CLUSTER_RATIO(fs)        (1)
56 #define EXT2_CLUSTERS_PER_GROUP(s)      (EXT2_BLOCKS_PER_GROUP(s))
57 #define EXT2FS_B2C(fs, blk)             (blk)
58 #endif
59
60 struct task_ctx {
61         uint32_t max_copy_inodes;
62         uint32_t cur_copy_inodes;
63         struct task_info *info;
64 };
65
66 static void *print_copied_inodes(void *p)
67 {
68         struct task_ctx *priv = p;
69         const char work_indicator[] = { '.', 'o', 'O', 'o' };
70         uint32_t count = 0;
71
72         task_period_start(priv->info, 1000 /* 1s */);
73         while (1) {
74                 count++;
75                 printf("copy inodes [%c] [%10d/%10d]\r",
76                        work_indicator[count % 4], priv->cur_copy_inodes,
77                        priv->max_copy_inodes);
78                 fflush(stdout);
79                 task_period_wait(priv->info);
80         }
81
82         return NULL;
83 }
84
85 static int after_copied_inodes(void *p)
86 {
87         printf("\n");
88         fflush(stdout);
89
90         return 0;
91 }
92
93 struct btrfs_convert_context;
94 struct btrfs_convert_operations {
95         const char *name;
96         int (*open_fs)(struct btrfs_convert_context *cctx, const char *devname);
97         int (*read_used_space)(struct btrfs_convert_context *cctx);
98         int (*copy_inodes)(struct btrfs_convert_context *cctx,
99                          struct btrfs_root *root, int datacsum,
100                          int packing, int noxattr, struct task_ctx *p);
101         void (*close_fs)(struct btrfs_convert_context *cctx);
102 };
103
104 static void init_convert_context(struct btrfs_convert_context *cctx)
105 {
106         cache_tree_init(&cctx->used);
107         cache_tree_init(&cctx->data_chunks);
108         cache_tree_init(&cctx->free);
109 }
110
111 static void clean_convert_context(struct btrfs_convert_context *cctx)
112 {
113         free_extent_cache_tree(&cctx->used);
114         free_extent_cache_tree(&cctx->data_chunks);
115         free_extent_cache_tree(&cctx->free);
116 }
117
118 static inline int copy_inodes(struct btrfs_convert_context *cctx,
119                               struct btrfs_root *root, int datacsum,
120                               int packing, int noxattr, struct task_ctx *p)
121 {
122         return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
123                                              noxattr, p);
124 }
125
126 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
127 {
128         cctx->convert_ops->close_fs(cctx);
129 }
130
131 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
132 {
133         int i;
134         u64 offset;
135
136         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
137                 offset = btrfs_sb_offset(i);
138                 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
139
140                 if (bytenr < offset + BTRFS_STRIPE_LEN &&
141                     bytenr + num_bytes > offset)
142                         return 1;
143         }
144         return 0;
145 }
146
147 /*
148  * Open Ext2fs in readonly mode, read block allocation bitmap and
149  * inode bitmap into memory.
150  */
151 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
152 {
153         errcode_t ret;
154         ext2_filsys ext2_fs;
155         ext2_ino_t ino;
156         u32 ro_feature;
157
158         ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
159         if (ret) {
160                 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
161                 return -1;
162         }
163         /*
164          * We need to know exactly the used space, some RO compat flags like
165          * BIGALLOC will affect how used space is present.
166          * So we need manuall check any unsupported RO compat flags
167          */
168         ro_feature = ext2_fs->super->s_feature_ro_compat;
169         if (ro_feature & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
170                 error(
171 "unsupported RO features detected: %x, abort convert to avoid possible corruption",
172                       ro_feature & ~EXT2_LIB_FEATURE_COMPAT_SUPP);
173                 goto fail;
174         }
175         ret = ext2fs_read_inode_bitmap(ext2_fs);
176         if (ret) {
177                 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
178                         error_message(ret));
179                 goto fail;
180         }
181         ret = ext2fs_read_block_bitmap(ext2_fs);
182         if (ret) {
183                 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
184                         error_message(ret));
185                 goto fail;
186         }
187         /*
188          * search each block group for a free inode. this set up
189          * uninit block/inode bitmaps appropriately.
190          */
191         ino = 1;
192         while (ino <= ext2_fs->super->s_inodes_count) {
193                 ext2_ino_t foo;
194                 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
195                 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
196         }
197
198         if (!(ext2_fs->super->s_feature_incompat &
199               EXT2_FEATURE_INCOMPAT_FILETYPE)) {
200                 fprintf(stderr, "filetype feature is missing\n");
201                 goto fail;
202         }
203
204         cctx->fs_data = ext2_fs;
205         cctx->blocksize = ext2_fs->blocksize;
206         cctx->block_count = ext2_fs->super->s_blocks_count;
207         cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
208         cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
209         cctx->first_data_block = ext2_fs->super->s_first_data_block;
210         cctx->inodes_count = ext2_fs->super->s_inodes_count;
211         cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
212         return 0;
213 fail:
214         ext2fs_close(ext2_fs);
215         return -1;
216 }
217
218 static int __ext2_add_one_block(ext2_filsys fs, char *bitmap,
219                                 unsigned long group_nr, struct cache_tree *used)
220 {
221         unsigned long offset;
222         unsigned i;
223         int ret = 0;
224
225         offset = fs->super->s_first_data_block;
226         offset /= EXT2FS_CLUSTER_RATIO(fs);
227         offset += group_nr * EXT2_CLUSTERS_PER_GROUP(fs->super);
228         for (i = 0; i < EXT2_CLUSTERS_PER_GROUP(fs->super); i++) {
229                 if (ext2fs_test_bit(i, bitmap)) {
230                         u64 start;
231
232                         start = (i + offset) * EXT2FS_CLUSTER_RATIO(fs);
233                         start *= fs->blocksize;
234                         ret = add_merge_cache_extent(used, start,
235                                                      fs->blocksize);
236                         if (ret < 0)
237                                 break;
238                 }
239         }
240         return ret;
241 }
242
243 /*
244  * Read all used ext2 space into cctx->used cache tree
245  */
246 static int ext2_read_used_space(struct btrfs_convert_context *cctx)
247 {
248         ext2_filsys fs = (ext2_filsys)cctx->fs_data;
249         blk64_t blk_itr = EXT2FS_B2C(fs, fs->super->s_first_data_block);
250         struct cache_tree *used_tree = &cctx->used;
251         char *block_bitmap = NULL;
252         unsigned long i;
253         int block_nbytes;
254         int ret = 0;
255
256         block_nbytes = EXT2_CLUSTERS_PER_GROUP(fs->super) / 8;
257         /* Shouldn't happen */
258         BUG_ON(!fs->block_map);
259
260         block_bitmap = malloc(block_nbytes);
261         if (!block_bitmap)
262                 return -ENOMEM;
263
264         for (i = 0; i < fs->group_desc_count; i++) {
265                 ret = ext2fs_get_block_bitmap_range(fs->block_map, blk_itr,
266                                                 block_nbytes * 8, block_bitmap);
267                 if (ret) {
268                         error("fail to get bitmap from ext2, %s",
269                               strerror(-ret));
270                         break;
271                 }
272                 ret = __ext2_add_one_block(fs, block_bitmap, i, used_tree);
273                 if (ret < 0) {
274                         error("fail to build used space tree, %s",
275                               strerror(-ret));
276                         break;
277                 }
278                 blk_itr += EXT2_CLUSTERS_PER_GROUP(fs->super);
279         }
280
281         free(block_bitmap);
282         return ret;
283 }
284
285 static void ext2_close_fs(struct btrfs_convert_context *cctx)
286 {
287         if (cctx->volume_name) {
288                 free(cctx->volume_name);
289                 cctx->volume_name = NULL;
290         }
291         ext2fs_close(cctx->fs_data);
292 }
293
294 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
295                                  struct btrfs_root *root,
296                                  const char *name, size_t name_len,
297                                  u64 dir, u64 objectid,
298                                  u8 file_type, u64 index_cnt,
299                                  struct btrfs_inode_item *inode)
300 {
301         int ret;
302         u64 inode_size;
303         struct btrfs_key location = {
304                 .objectid = objectid,
305                 .offset = 0,
306                 .type = BTRFS_INODE_ITEM_KEY,
307         };
308
309         ret = btrfs_insert_dir_item(trans, root, name, name_len,
310                                     dir, &location, file_type, index_cnt);
311         if (ret)
312                 return ret;
313         ret = btrfs_insert_inode_ref(trans, root, name, name_len,
314                                      objectid, dir, index_cnt);
315         if (ret)
316                 return ret;
317         inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
318         btrfs_set_stack_inode_size(inode, inode_size);
319
320         return 0;
321 }
322
323 struct dir_iterate_data {
324         struct btrfs_trans_handle *trans;
325         struct btrfs_root *root;
326         struct btrfs_inode_item *inode;
327         u64 objectid;
328         u64 index_cnt;
329         u64 parent;
330         int errcode;
331 };
332
333 static u8 ext2_filetype_conversion_table[EXT2_FT_MAX] = {
334         [EXT2_FT_UNKNOWN]       = BTRFS_FT_UNKNOWN,
335         [EXT2_FT_REG_FILE]      = BTRFS_FT_REG_FILE,
336         [EXT2_FT_DIR]           = BTRFS_FT_DIR,
337         [EXT2_FT_CHRDEV]        = BTRFS_FT_CHRDEV,
338         [EXT2_FT_BLKDEV]        = BTRFS_FT_BLKDEV,
339         [EXT2_FT_FIFO]          = BTRFS_FT_FIFO,
340         [EXT2_FT_SOCK]          = BTRFS_FT_SOCK,
341         [EXT2_FT_SYMLINK]       = BTRFS_FT_SYMLINK,
342 };
343
344 static int ext2_dir_iterate_proc(ext2_ino_t dir, int entry,
345                             struct ext2_dir_entry *dirent,
346                             int offset, int blocksize,
347                             char *buf,void *priv_data)
348 {
349         int ret;
350         int file_type;
351         u64 objectid;
352         char dotdot[] = "..";
353         struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
354         int name_len;
355
356         name_len = dirent->name_len & 0xFF;
357
358         objectid = dirent->inode + INO_OFFSET;
359         if (!strncmp(dirent->name, dotdot, name_len)) {
360                 if (name_len == 2) {
361                         BUG_ON(idata->parent != 0);
362                         idata->parent = objectid;
363                 }
364                 return 0;
365         }
366         if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
367                 return 0;
368
369         file_type = dirent->name_len >> 8;
370         BUG_ON(file_type > EXT2_FT_SYMLINK);
371
372         ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
373                                     name_len, idata->objectid, objectid,
374                                     ext2_filetype_conversion_table[file_type],
375                                     idata->index_cnt, idata->inode);
376         if (ret < 0) {
377                 idata->errcode = ret;
378                 return BLOCK_ABORT;
379         }
380
381         idata->index_cnt++;
382         return 0;
383 }
384
385 static int ext2_create_dir_entries(struct btrfs_trans_handle *trans,
386                               struct btrfs_root *root, u64 objectid,
387                               struct btrfs_inode_item *btrfs_inode,
388                               ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
389 {
390         int ret;
391         errcode_t err;
392         struct dir_iterate_data data = {
393                 .trans          = trans,
394                 .root           = root,
395                 .inode          = btrfs_inode,
396                 .objectid       = objectid,
397                 .index_cnt      = 2,
398                 .parent         = 0,
399                 .errcode        = 0,
400         };
401
402         err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
403                                   ext2_dir_iterate_proc, &data);
404         if (err)
405                 goto error;
406         ret = data.errcode;
407         if (ret == 0 && data.parent == objectid) {
408                 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
409                                              objectid, objectid, 0);
410         }
411         return ret;
412 error:
413         fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
414         return -1;
415 }
416
417 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
418                             u32 num_bytes, char *buffer)
419 {
420         int ret;
421         struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
422
423         ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
424         if (ret != num_bytes)
425                 goto fail;
426         ret = 0;
427 fail:
428         if (ret > 0)
429                 ret = -1;
430         return ret;
431 }
432
433 static int csum_disk_extent(struct btrfs_trans_handle *trans,
434                             struct btrfs_root *root,
435                             u64 disk_bytenr, u64 num_bytes)
436 {
437         u32 blocksize = root->sectorsize;
438         u64 offset;
439         char *buffer;
440         int ret = 0;
441
442         buffer = malloc(blocksize);
443         if (!buffer)
444                 return -ENOMEM;
445         for (offset = 0; offset < num_bytes; offset += blocksize) {
446                 ret = read_disk_extent(root, disk_bytenr + offset,
447                                         blocksize, buffer);
448                 if (ret)
449                         break;
450                 ret = btrfs_csum_file_block(trans,
451                                             root->fs_info->csum_root,
452                                             disk_bytenr + num_bytes,
453                                             disk_bytenr + offset,
454                                             buffer, blocksize);
455                 if (ret)
456                         break;
457         }
458         free(buffer);
459         return ret;
460 }
461
462 struct blk_iterate_data {
463         struct btrfs_trans_handle *trans;
464         struct btrfs_root *root;
465         struct btrfs_root *convert_root;
466         struct btrfs_inode_item *inode;
467         u64 convert_ino;
468         u64 objectid;
469         u64 first_block;
470         u64 disk_block;
471         u64 num_blocks;
472         u64 boundary;
473         int checksum;
474         int errcode;
475 };
476
477 static void init_blk_iterate_data(struct blk_iterate_data *data,
478                                   struct btrfs_trans_handle *trans,
479                                   struct btrfs_root *root,
480                                   struct btrfs_inode_item *inode,
481                                   u64 objectid, int checksum)
482 {
483         struct btrfs_key key;
484
485         data->trans             = trans;
486         data->root              = root;
487         data->inode             = inode;
488         data->objectid          = objectid;
489         data->first_block       = 0;
490         data->disk_block        = 0;
491         data->num_blocks        = 0;
492         data->boundary          = (u64)-1;
493         data->checksum          = checksum;
494         data->errcode           = 0;
495
496         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
497         key.type = BTRFS_ROOT_ITEM_KEY;
498         key.offset = (u64)-1;
499         data->convert_root = btrfs_read_fs_root(root->fs_info, &key);
500         /* Impossible as we just opened it before */
501         BUG_ON(!data->convert_root || IS_ERR(data->convert_root));
502         data->convert_ino = BTRFS_FIRST_FREE_OBJECTID + 1;
503 }
504
505 /*
506  * Record a file extent in original filesystem into btrfs one.
507  * The special point is, old disk_block can point to a reserved range.
508  * So here, we don't use disk_block directly but search convert_root
509  * to get the real disk_bytenr.
510  */
511 static int record_file_blocks(struct blk_iterate_data *data,
512                               u64 file_block, u64 disk_block, u64 num_blocks)
513 {
514         int ret = 0;
515         struct btrfs_root *root = data->root;
516         struct btrfs_root *convert_root = data->convert_root;
517         struct btrfs_path *path;
518         u64 file_pos = file_block * root->sectorsize;
519         u64 old_disk_bytenr = disk_block * root->sectorsize;
520         u64 num_bytes = num_blocks * root->sectorsize;
521         u64 cur_off = old_disk_bytenr;
522
523         /* Hole, pass it to record_file_extent directly */
524         if (old_disk_bytenr == 0)
525                 return btrfs_record_file_extent(data->trans, root,
526                                 data->objectid, data->inode, file_pos, 0,
527                                 num_bytes);
528
529         path = btrfs_alloc_path();
530         if (!path)
531                 return -ENOMEM;
532
533         /*
534          * Search real disk bytenr from convert root
535          */
536         while (cur_off < old_disk_bytenr + num_bytes) {
537                 struct btrfs_key key;
538                 struct btrfs_file_extent_item *fi;
539                 struct extent_buffer *node;
540                 int slot;
541                 u64 extent_disk_bytenr;
542                 u64 extent_num_bytes;
543                 u64 real_disk_bytenr;
544                 u64 cur_len;
545
546                 key.objectid = data->convert_ino;
547                 key.type = BTRFS_EXTENT_DATA_KEY;
548                 key.offset = cur_off;
549
550                 ret = btrfs_search_slot(NULL, convert_root, &key, path, 0, 0);
551                 if (ret < 0)
552                         break;
553                 if (ret > 0) {
554                         ret = btrfs_previous_item(convert_root, path,
555                                                   data->convert_ino,
556                                                   BTRFS_EXTENT_DATA_KEY);
557                         if (ret < 0)
558                                 break;
559                         if (ret > 0) {
560                                 ret = -ENOENT;
561                                 break;
562                         }
563                 }
564                 node = path->nodes[0];
565                 slot = path->slots[0];
566                 btrfs_item_key_to_cpu(node, &key, slot);
567                 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY ||
568                        key.objectid != data->convert_ino ||
569                        key.offset > cur_off);
570                 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
571                 extent_disk_bytenr = btrfs_file_extent_disk_bytenr(node, fi);
572                 extent_num_bytes = btrfs_file_extent_disk_num_bytes(node, fi);
573                 BUG_ON(cur_off - key.offset >= extent_num_bytes);
574                 btrfs_release_path(path);
575
576                 if (extent_disk_bytenr)
577                         real_disk_bytenr = cur_off - key.offset +
578                                            extent_disk_bytenr;
579                 else
580                         real_disk_bytenr = 0;
581                 cur_len = min(key.offset + extent_num_bytes,
582                               old_disk_bytenr + num_bytes) - cur_off;
583                 ret = btrfs_record_file_extent(data->trans, data->root,
584                                         data->objectid, data->inode, file_pos,
585                                         real_disk_bytenr, cur_len);
586                 if (ret < 0)
587                         break;
588                 cur_off += cur_len;
589                 file_pos += cur_len;
590
591                 /*
592                  * No need to care about csum
593                  * As every byte of old fs image is calculated for csum, no
594                  * need to waste CPU cycles now.
595                  */
596         }
597         btrfs_free_path(path);
598         return ret;
599 }
600
601 static int block_iterate_proc(u64 disk_block, u64 file_block,
602                               struct blk_iterate_data *idata)
603 {
604         int ret = 0;
605         int sb_region;
606         int do_barrier;
607         struct btrfs_root *root = idata->root;
608         struct btrfs_block_group_cache *cache;
609         u64 bytenr = disk_block * root->sectorsize;
610
611         sb_region = intersect_with_sb(bytenr, root->sectorsize);
612         do_barrier = sb_region || disk_block >= idata->boundary;
613         if ((idata->num_blocks > 0 && do_barrier) ||
614             (file_block > idata->first_block + idata->num_blocks) ||
615             (disk_block != idata->disk_block + idata->num_blocks)) {
616                 if (idata->num_blocks > 0) {
617                         ret = record_file_blocks(idata, idata->first_block,
618                                                  idata->disk_block,
619                                                  idata->num_blocks);
620                         if (ret)
621                                 goto fail;
622                         idata->first_block += idata->num_blocks;
623                         idata->num_blocks = 0;
624                 }
625                 if (file_block > idata->first_block) {
626                         ret = record_file_blocks(idata, idata->first_block,
627                                         0, file_block - idata->first_block);
628                         if (ret)
629                                 goto fail;
630                 }
631
632                 if (sb_region) {
633                         bytenr += BTRFS_STRIPE_LEN - 1;
634                         bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
635                 } else {
636                         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
637                         BUG_ON(!cache);
638                         bytenr = cache->key.objectid + cache->key.offset;
639                 }
640
641                 idata->first_block = file_block;
642                 idata->disk_block = disk_block;
643                 idata->boundary = bytenr / root->sectorsize;
644         }
645         idata->num_blocks++;
646 fail:
647         return ret;
648 }
649
650 static int ext2_block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
651                                 e2_blkcnt_t blockcnt, blk_t ref_block,
652                                 int ref_offset, void *priv_data)
653 {
654         int ret;
655         struct blk_iterate_data *idata;
656         idata = (struct blk_iterate_data *)priv_data;
657         ret = block_iterate_proc(*blocknr, blockcnt, idata);
658         if (ret) {
659                 idata->errcode = ret;
660                 return BLOCK_ABORT;
661         }
662         return 0;
663 }
664
665 /*
666  * traverse file's data blocks, record these data blocks as file extents.
667  */
668 static int ext2_create_file_extents(struct btrfs_trans_handle *trans,
669                                struct btrfs_root *root, u64 objectid,
670                                struct btrfs_inode_item *btrfs_inode,
671                                ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
672                                int datacsum, int packing)
673 {
674         int ret;
675         char *buffer = NULL;
676         errcode_t err;
677         u32 last_block;
678         u32 sectorsize = root->sectorsize;
679         u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
680         struct blk_iterate_data data;
681
682         init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
683                               datacsum);
684
685         err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
686                                     NULL, ext2_block_iterate_proc, &data);
687         if (err)
688                 goto error;
689         ret = data.errcode;
690         if (ret)
691                 goto fail;
692         if (packing && data.first_block == 0 && data.num_blocks > 0 &&
693             inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
694                 u64 num_bytes = data.num_blocks * sectorsize;
695                 u64 disk_bytenr = data.disk_block * sectorsize;
696                 u64 nbytes;
697
698                 buffer = malloc(num_bytes);
699                 if (!buffer)
700                         return -ENOMEM;
701                 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
702                 if (ret)
703                         goto fail;
704                 if (num_bytes > inode_size)
705                         num_bytes = inode_size;
706                 ret = btrfs_insert_inline_extent(trans, root, objectid,
707                                                  0, buffer, num_bytes);
708                 if (ret)
709                         goto fail;
710                 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
711                 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
712         } else if (data.num_blocks > 0) {
713                 ret = record_file_blocks(&data, data.first_block,
714                                          data.disk_block, data.num_blocks);
715                 if (ret)
716                         goto fail;
717         }
718         data.first_block += data.num_blocks;
719         last_block = (inode_size + sectorsize - 1) / sectorsize;
720         if (last_block > data.first_block) {
721                 ret = record_file_blocks(&data, data.first_block, 0,
722                                          last_block - data.first_block);
723         }
724 fail:
725         free(buffer);
726         return ret;
727 error:
728         fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
729         return -1;
730 }
731
732 static int ext2_create_symbol_link(struct btrfs_trans_handle *trans,
733                               struct btrfs_root *root, u64 objectid,
734                               struct btrfs_inode_item *btrfs_inode,
735                               ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
736                               struct ext2_inode *ext2_inode)
737 {
738         int ret;
739         char *pathname;
740         u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
741         if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
742                 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
743                 ret = ext2_create_file_extents(trans, root, objectid,
744                                 btrfs_inode, ext2_fs, ext2_ino, 1, 1);
745                 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
746                 return ret;
747         }
748
749         pathname = (char *)&(ext2_inode->i_block[0]);
750         BUG_ON(pathname[inode_size] != 0);
751         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
752                                          pathname, inode_size + 1);
753         btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
754         return ret;
755 }
756
757 /*
758  * Following xattr/acl related codes are based on codes in
759  * fs/ext3/xattr.c and fs/ext3/acl.c
760  */
761 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
762 #define EXT2_XATTR_BFIRST(ptr) \
763         ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
764 #define EXT2_XATTR_IHDR(inode) \
765         ((struct ext2_ext_attr_header *) ((void *)(inode) + \
766                 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
767 #define EXT2_XATTR_IFIRST(inode) \
768         ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
769                 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
770
771 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
772                                   const void *end)
773 {
774         struct ext2_ext_attr_entry *next;
775
776         while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
777                 next = EXT2_EXT_ATTR_NEXT(entry);
778                 if ((void *)next >= end)
779                         return -EIO;
780                 entry = next;
781         }
782         return 0;
783 }
784
785 static int ext2_xattr_check_block(const char *buf, size_t size)
786 {
787         int error;
788         struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
789
790         if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
791             header->h_blocks != 1)
792                 return -EIO;
793         error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
794         return error;
795 }
796
797 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
798                                   size_t size)
799 {
800         size_t value_size = entry->e_value_size;
801
802         if (entry->e_value_block != 0 || value_size > size ||
803             entry->e_value_offs + value_size > size)
804                 return -EIO;
805         return 0;
806 }
807
808 #define EXT2_ACL_VERSION        0x0001
809
810 /* 23.2.5 acl_tag_t values */
811
812 #define ACL_UNDEFINED_TAG       (0x00)
813 #define ACL_USER_OBJ            (0x01)
814 #define ACL_USER                (0x02)
815 #define ACL_GROUP_OBJ           (0x04)
816 #define ACL_GROUP               (0x08)
817 #define ACL_MASK                (0x10)
818 #define ACL_OTHER               (0x20)
819
820 /* 23.2.7 ACL qualifier constants */
821
822 #define ACL_UNDEFINED_ID        ((id_t)-1)
823
824 typedef struct {
825         __le16          e_tag;
826         __le16          e_perm;
827         __le32          e_id;
828 } ext2_acl_entry;
829
830 typedef struct {
831         __le16          e_tag;
832         __le16          e_perm;
833 } ext2_acl_entry_short;
834
835 typedef struct {
836         __le32          a_version;
837 } ext2_acl_header;
838
839 static inline int ext2_acl_count(size_t size)
840 {
841         ssize_t s;
842         size -= sizeof(ext2_acl_header);
843         s = size - 4 * sizeof(ext2_acl_entry_short);
844         if (s < 0) {
845                 if (size % sizeof(ext2_acl_entry_short))
846                         return -1;
847                 return size / sizeof(ext2_acl_entry_short);
848         } else {
849                 if (s % sizeof(ext2_acl_entry))
850                         return -1;
851                 return s / sizeof(ext2_acl_entry) + 4;
852         }
853 }
854
855 #define ACL_EA_VERSION          0x0002
856
857 typedef struct {
858         __le16          e_tag;
859         __le16          e_perm;
860         __le32          e_id;
861 } acl_ea_entry;
862
863 typedef struct {
864         __le32          a_version;
865         acl_ea_entry    a_entries[0];
866 } acl_ea_header;
867
868 static inline size_t acl_ea_size(int count)
869 {
870         return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
871 }
872
873 static int ext2_acl_to_xattr(void *dst, const void *src,
874                              size_t dst_size, size_t src_size)
875 {
876         int i, count;
877         const void *end = src + src_size;
878         acl_ea_header *ext_acl = (acl_ea_header *)dst;
879         acl_ea_entry *dst_entry = ext_acl->a_entries;
880         ext2_acl_entry *src_entry;
881
882         if (src_size < sizeof(ext2_acl_header))
883                 goto fail;
884         if (((ext2_acl_header *)src)->a_version !=
885             cpu_to_le32(EXT2_ACL_VERSION))
886                 goto fail;
887         src += sizeof(ext2_acl_header);
888         count = ext2_acl_count(src_size);
889         if (count <= 0)
890                 goto fail;
891
892         BUG_ON(dst_size < acl_ea_size(count));
893         ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
894         for (i = 0; i < count; i++, dst_entry++) {
895                 src_entry = (ext2_acl_entry *)src;
896                 if (src + sizeof(ext2_acl_entry_short) > end)
897                         goto fail;
898                 dst_entry->e_tag = src_entry->e_tag;
899                 dst_entry->e_perm = src_entry->e_perm;
900                 switch (le16_to_cpu(src_entry->e_tag)) {
901                 case ACL_USER_OBJ:
902                 case ACL_GROUP_OBJ:
903                 case ACL_MASK:
904                 case ACL_OTHER:
905                         src += sizeof(ext2_acl_entry_short);
906                         dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
907                         break;
908                 case ACL_USER:
909                 case ACL_GROUP:
910                         src += sizeof(ext2_acl_entry);
911                         if (src > end)
912                                 goto fail;
913                         dst_entry->e_id = src_entry->e_id;
914                         break;
915                 default:
916                         goto fail;
917                 }
918         }
919         if (src != end)
920                 goto fail;
921         return 0;
922 fail:
923         return -EINVAL;
924 }
925
926 static char *xattr_prefix_table[] = {
927         [1] =   "user.",
928         [2] =   "system.posix_acl_access",
929         [3] =   "system.posix_acl_default",
930         [4] =   "trusted.",
931         [6] =   "security.",
932 };
933
934 static int ext2_copy_single_xattr(struct btrfs_trans_handle *trans,
935                              struct btrfs_root *root, u64 objectid,
936                              struct ext2_ext_attr_entry *entry,
937                              const void *data, u32 datalen)
938 {
939         int ret = 0;
940         int name_len;
941         int name_index;
942         void *databuf = NULL;
943         char namebuf[XATTR_NAME_MAX + 1];
944
945         name_index = entry->e_name_index;
946         if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
947             xattr_prefix_table[name_index] == NULL)
948                 return -EOPNOTSUPP;
949         name_len = strlen(xattr_prefix_table[name_index]) +
950                    entry->e_name_len;
951         if (name_len >= sizeof(namebuf))
952                 return -ERANGE;
953
954         if (name_index == 2 || name_index == 3) {
955                 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
956                 databuf = malloc(bufsize);
957                 if (!databuf)
958                        return -ENOMEM;
959                 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
960                 if (ret)
961                         goto out;
962                 data = databuf;
963                 datalen = bufsize;
964         }
965         strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
966         strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
967         if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
968             sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
969                 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
970                         objectid - INO_OFFSET, name_len, namebuf);
971                 goto out;
972         }
973         ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
974                                       data, datalen, objectid);
975 out:
976         free(databuf);
977         return ret;
978 }
979
980 static int ext2_copy_extended_attrs(struct btrfs_trans_handle *trans,
981                                struct btrfs_root *root, u64 objectid,
982                                struct btrfs_inode_item *btrfs_inode,
983                                ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
984 {
985         int ret = 0;
986         int inline_ea = 0;
987         errcode_t err;
988         u32 datalen;
989         u32 block_size = ext2_fs->blocksize;
990         u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
991         struct ext2_inode_large *ext2_inode;
992         struct ext2_ext_attr_entry *entry;
993         void *data;
994         char *buffer = NULL;
995         char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
996
997         if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
998                 ext2_inode = (struct ext2_inode_large *)inode_buf;
999         } else {
1000                 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
1001                 if (!ext2_inode)
1002                        return -ENOMEM;
1003         }
1004         err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
1005                                      inode_size);
1006         if (err) {
1007                 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
1008                         error_message(err));
1009                 ret = -1;
1010                 goto out;
1011         }
1012
1013         if (ext2_ino > ext2_fs->super->s_first_ino &&
1014             inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
1015                 if (EXT2_GOOD_OLD_INODE_SIZE +
1016                     ext2_inode->i_extra_isize > inode_size) {
1017                         ret = -EIO;
1018                         goto out;
1019                 }
1020                 if (ext2_inode->i_extra_isize != 0 &&
1021                     EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
1022                     EXT2_EXT_ATTR_MAGIC) {
1023                         inline_ea = 1;
1024                 }
1025         }
1026         if (inline_ea) {
1027                 int total;
1028                 void *end = (void *)ext2_inode + inode_size;
1029                 entry = EXT2_XATTR_IFIRST(ext2_inode);
1030                 total = end - (void *)entry;
1031                 ret = ext2_xattr_check_names(entry, end);
1032                 if (ret)
1033                         goto out;
1034                 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1035                         ret = ext2_xattr_check_entry(entry, total);
1036                         if (ret)
1037                                 goto out;
1038                         data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
1039                                 entry->e_value_offs;
1040                         datalen = entry->e_value_size;
1041                         ret = ext2_copy_single_xattr(trans, root, objectid,
1042                                                 entry, data, datalen);
1043                         if (ret)
1044                                 goto out;
1045                         entry = EXT2_EXT_ATTR_NEXT(entry);
1046                 }
1047         }
1048
1049         if (ext2_inode->i_file_acl == 0)
1050                 goto out;
1051
1052         buffer = malloc(block_size);
1053         if (!buffer) {
1054                 ret = -ENOMEM;
1055                 goto out;
1056         }
1057         err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
1058         if (err) {
1059                 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
1060                         error_message(err));
1061                 ret = -1;
1062                 goto out;
1063         }
1064         ret = ext2_xattr_check_block(buffer, block_size);
1065         if (ret)
1066                 goto out;
1067
1068         entry = EXT2_XATTR_BFIRST(buffer);
1069         while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1070                 ret = ext2_xattr_check_entry(entry, block_size);
1071                 if (ret)
1072                         goto out;
1073                 data = buffer + entry->e_value_offs;
1074                 datalen = entry->e_value_size;
1075                 ret = ext2_copy_single_xattr(trans, root, objectid,
1076                                         entry, data, datalen);
1077                 if (ret)
1078                         goto out;
1079                 entry = EXT2_EXT_ATTR_NEXT(entry);
1080         }
1081 out:
1082         free(buffer);
1083         if ((void *)ext2_inode != inode_buf)
1084                 free(ext2_inode);
1085         return ret;
1086 }
1087 #define MINORBITS       20
1088 #define MKDEV(ma, mi)   (((ma) << MINORBITS) | (mi))
1089
1090 static inline dev_t old_decode_dev(u16 val)
1091 {
1092         return MKDEV((val >> 8) & 255, val & 255);
1093 }
1094
1095 static inline dev_t new_decode_dev(u32 dev)
1096 {
1097         unsigned major = (dev & 0xfff00) >> 8;
1098         unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
1099         return MKDEV(major, minor);
1100 }
1101
1102 static void ext2_copy_inode_item(struct btrfs_inode_item *dst,
1103                            struct ext2_inode *src, u32 blocksize)
1104 {
1105         btrfs_set_stack_inode_generation(dst, 1);
1106         btrfs_set_stack_inode_sequence(dst, 0);
1107         btrfs_set_stack_inode_transid(dst, 1);
1108         btrfs_set_stack_inode_size(dst, src->i_size);
1109         btrfs_set_stack_inode_nbytes(dst, 0);
1110         btrfs_set_stack_inode_block_group(dst, 0);
1111         btrfs_set_stack_inode_nlink(dst, src->i_links_count);
1112         btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
1113         btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
1114         btrfs_set_stack_inode_mode(dst, src->i_mode);
1115         btrfs_set_stack_inode_rdev(dst, 0);
1116         btrfs_set_stack_inode_flags(dst, 0);
1117         btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
1118         btrfs_set_stack_timespec_nsec(&dst->atime, 0);
1119         btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
1120         btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
1121         btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
1122         btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
1123         btrfs_set_stack_timespec_sec(&dst->otime, 0);
1124         btrfs_set_stack_timespec_nsec(&dst->otime, 0);
1125
1126         if (S_ISDIR(src->i_mode)) {
1127                 btrfs_set_stack_inode_size(dst, 0);
1128                 btrfs_set_stack_inode_nlink(dst, 1);
1129         }
1130         if (S_ISREG(src->i_mode)) {
1131                 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
1132                                            (u64)src->i_size);
1133         }
1134         if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
1135             !S_ISLNK(src->i_mode)) {
1136                 if (src->i_block[0]) {
1137                         btrfs_set_stack_inode_rdev(dst,
1138                                 old_decode_dev(src->i_block[0]));
1139                 } else {
1140                         btrfs_set_stack_inode_rdev(dst,
1141                                 new_decode_dev(src->i_block[1]));
1142                 }
1143         }
1144         memset(&dst->reserved, 0, sizeof(dst->reserved));
1145 }
1146
1147 /*
1148  * copy a single inode. do all the required works, such as cloning
1149  * inode item, creating file extents and creating directory entries.
1150  */
1151 static int ext2_copy_single_inode(struct btrfs_trans_handle *trans,
1152                              struct btrfs_root *root, u64 objectid,
1153                              ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1154                              struct ext2_inode *ext2_inode,
1155                              int datacsum, int packing, int noxattr)
1156 {
1157         int ret;
1158         struct btrfs_inode_item btrfs_inode;
1159
1160         if (ext2_inode->i_links_count == 0)
1161                 return 0;
1162
1163         ext2_copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
1164         if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
1165                 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
1166                             BTRFS_INODE_NODATASUM;
1167                 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
1168         }
1169
1170         switch (ext2_inode->i_mode & S_IFMT) {
1171         case S_IFREG:
1172                 ret = ext2_create_file_extents(trans, root, objectid,
1173                         &btrfs_inode, ext2_fs, ext2_ino, datacsum, packing);
1174                 break;
1175         case S_IFDIR:
1176                 ret = ext2_create_dir_entries(trans, root, objectid,
1177                                 &btrfs_inode, ext2_fs, ext2_ino);
1178                 break;
1179         case S_IFLNK:
1180                 ret = ext2_create_symbol_link(trans, root, objectid,
1181                                 &btrfs_inode, ext2_fs, ext2_ino, ext2_inode);
1182                 break;
1183         default:
1184                 ret = 0;
1185                 break;
1186         }
1187         if (ret)
1188                 return ret;
1189
1190         if (!noxattr) {
1191                 ret = ext2_copy_extended_attrs(trans, root, objectid,
1192                                 &btrfs_inode, ext2_fs, ext2_ino);
1193                 if (ret)
1194                         return ret;
1195         }
1196         return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
1197 }
1198
1199 /*
1200  * scan ext2's inode bitmap and copy all used inodes.
1201  */
1202 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
1203                             struct btrfs_root *root,
1204                             int datacsum, int packing, int noxattr, struct task_ctx *p)
1205 {
1206         ext2_filsys ext2_fs = cctx->fs_data;
1207         int ret;
1208         errcode_t err;
1209         ext2_inode_scan ext2_scan;
1210         struct ext2_inode ext2_inode;
1211         ext2_ino_t ext2_ino;
1212         u64 objectid;
1213         struct btrfs_trans_handle *trans;
1214
1215         trans = btrfs_start_transaction(root, 1);
1216         if (!trans)
1217                 return -ENOMEM;
1218         err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
1219         if (err) {
1220                 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
1221                 return -1;
1222         }
1223         while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
1224                                              &ext2_inode))) {
1225                 /* no more inodes */
1226                 if (ext2_ino == 0)
1227                         break;
1228                 /* skip special inode in ext2fs */
1229                 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
1230                     ext2_ino != EXT2_ROOT_INO)
1231                         continue;
1232                 objectid = ext2_ino + INO_OFFSET;
1233                 ret = ext2_copy_single_inode(trans, root,
1234                                         objectid, ext2_fs, ext2_ino,
1235                                         &ext2_inode, datacsum, packing,
1236                                         noxattr);
1237                 p->cur_copy_inodes++;
1238                 if (ret)
1239                         return ret;
1240                 if (trans->blocks_used >= 4096) {
1241                         ret = btrfs_commit_transaction(trans, root);
1242                         BUG_ON(ret);
1243                         trans = btrfs_start_transaction(root, 1);
1244                         BUG_ON(!trans);
1245                 }
1246         }
1247         if (err) {
1248                 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
1249                 return -1;
1250         }
1251         ret = btrfs_commit_transaction(trans, root);
1252         BUG_ON(ret);
1253         ext2fs_close_inode_scan(ext2_scan);
1254
1255         return ret;
1256 }
1257
1258 static int create_image_file_range(struct btrfs_trans_handle *trans,
1259                                       struct btrfs_root *root,
1260                                       struct cache_tree *used,
1261                                       struct btrfs_inode_item *inode,
1262                                       u64 ino, u64 bytenr, u64 *ret_len,
1263                                       int datacsum)
1264 {
1265         struct cache_extent *cache;
1266         struct btrfs_block_group_cache *bg_cache;
1267         u64 len = *ret_len;
1268         u64 disk_bytenr;
1269         int i;
1270         int ret;
1271
1272         BUG_ON(bytenr != round_down(bytenr, root->sectorsize));
1273         BUG_ON(len != round_down(len, root->sectorsize));
1274         len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
1275
1276         /*
1277          * Skip sb ranges first
1278          * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
1279          *
1280          * Or we will insert a hole into current image file, and later
1281          * migrate block will fail as there is already a file extent.
1282          */
1283         if (bytenr < 1024 * 1024) {
1284                 *ret_len = 1024 * 1024 - bytenr;
1285                 return 0;
1286         }
1287         for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1288                 u64 cur = btrfs_sb_offset(i);
1289
1290                 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
1291                         *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
1292                         return 0;
1293                 }
1294         }
1295         for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1296                 u64 cur = btrfs_sb_offset(i);
1297
1298                 /*
1299                  *      |--reserved--|
1300                  * |----range-------|
1301                  * May still need to go through file extent inserts
1302                  */
1303                 if (bytenr < cur && bytenr + len >= cur) {
1304                         len = min_t(u64, len, cur - bytenr);
1305                         break;
1306                 }
1307                 /*
1308                  * |--reserved--|
1309                  *      |---range---|
1310                  * Drop out, no need to insert anything
1311                  */
1312                 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
1313                         *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
1314                         return 0;
1315                 }
1316         }
1317
1318         cache = search_cache_extent(used, bytenr);
1319         if (cache) {
1320                 if (cache->start <= bytenr) {
1321                         /*
1322                          * |///////Used///////|
1323                          *      |<--insert--->|
1324                          *      bytenr
1325                          */
1326                         len = min_t(u64, len, cache->start + cache->size -
1327                                     bytenr);
1328                         disk_bytenr = bytenr;
1329                 } else {
1330                         /*
1331                          *              |//Used//|
1332                          *  |<-insert-->|
1333                          *  bytenr
1334                          */
1335                         len = min(len, cache->start - bytenr);
1336                         disk_bytenr = 0;
1337                         datacsum = 0;
1338                 }
1339         } else {
1340                 /*
1341                  * |//Used//|           |EOF
1342                  *          |<-insert-->|
1343                  *          bytenr
1344                  */
1345                 disk_bytenr = 0;
1346                 datacsum = 0;
1347         }
1348
1349         if (disk_bytenr) {
1350                 /* Check if the range is in a data block group */
1351                 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
1352                 if (!bg_cache)
1353                         return -ENOENT;
1354                 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
1355                         return -EINVAL;
1356
1357                 /* The extent should never cross block group boundary */
1358                 len = min_t(u64, len, bg_cache->key.objectid +
1359                             bg_cache->key.offset - bytenr);
1360         }
1361
1362         BUG_ON(len != round_down(len, root->sectorsize));
1363         ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
1364                                        disk_bytenr, len);
1365         if (ret < 0)
1366                 return ret;
1367
1368         if (datacsum)
1369                 ret = csum_disk_extent(trans, root, bytenr, len);
1370         *ret_len = len;
1371         return ret;
1372 }
1373
1374
1375 /*
1376  * Relocate old fs data in one reserved ranges
1377  *
1378  * Since all old fs data in reserved range is not covered by any chunk nor
1379  * data extent, we don't need to handle any reference but add new
1380  * extent/reference, which makes codes more clear
1381  */
1382 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
1383                                       struct btrfs_root *root,
1384                                       struct cache_tree *used,
1385                                       struct btrfs_inode_item *inode, int fd,
1386                                       u64 ino, u64 start, u64 len, int datacsum)
1387 {
1388         u64 cur_off = start;
1389         u64 cur_len = len;
1390         u64 hole_start = start;
1391         u64 hole_len;
1392         struct cache_extent *cache;
1393         struct btrfs_key key;
1394         struct extent_buffer *eb;
1395         int ret = 0;
1396
1397         while (cur_off < start + len) {
1398                 cache = lookup_cache_extent(used, cur_off, cur_len);
1399                 if (!cache)
1400                         break;
1401                 cur_off = max(cache->start, cur_off);
1402                 cur_len = min(cache->start + cache->size, start + len) -
1403                           cur_off;
1404                 BUG_ON(cur_len < root->sectorsize);
1405
1406                 /* reserve extent for the data */
1407                 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
1408                                            &key, 1);
1409                 if (ret < 0)
1410                         break;
1411
1412                 eb = malloc(sizeof(*eb) + cur_len);
1413                 if (!eb) {
1414                         ret = -ENOMEM;
1415                         break;
1416                 }
1417
1418                 ret = pread(fd, eb->data, cur_len, cur_off);
1419                 if (ret < cur_len) {
1420                         ret = (ret < 0 ? ret : -EIO);
1421                         free(eb);
1422                         break;
1423                 }
1424                 eb->start = key.objectid;
1425                 eb->len = key.offset;
1426
1427                 /* Write the data */
1428                 ret = write_and_map_eb(trans, root, eb);
1429                 free(eb);
1430                 if (ret < 0)
1431                         break;
1432
1433                 /* Now handle extent item and file extent things */
1434                 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
1435                                                key.objectid, key.offset);
1436                 if (ret < 0)
1437                         break;
1438                 /* Finally, insert csum items */
1439                 if (datacsum)
1440                         ret = csum_disk_extent(trans, root, key.objectid,
1441                                                key.offset);
1442
1443                 /* Don't forget to insert hole */
1444                 hole_len = cur_off - hole_start;
1445                 if (hole_len) {
1446                         ret = btrfs_record_file_extent(trans, root, ino, inode,
1447                                         hole_start, 0, hole_len);
1448                         if (ret < 0)
1449                                 break;
1450                 }
1451
1452                 cur_off += key.offset;
1453                 hole_start = cur_off;
1454                 cur_len = start + len - cur_off;
1455         }
1456         /* Last hole */
1457         if (start + len - hole_start > 0)
1458                 ret = btrfs_record_file_extent(trans, root, ino, inode,
1459                                 hole_start, 0, start + len - hole_start);
1460         return ret;
1461 }
1462
1463 /*
1464  * Relocate the used ext2 data in reserved ranges
1465  * [0,1M)
1466  * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
1467  * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
1468  */
1469 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
1470                                    struct btrfs_root *root,
1471                                    struct cache_tree *used,
1472                                    struct btrfs_inode_item *inode, int fd,
1473                                    u64 ino, u64 total_bytes, int datacsum)
1474 {
1475         u64 cur_off;
1476         u64 cur_len;
1477         int ret = 0;
1478
1479         /* 0 ~ 1M */
1480         cur_off = 0;
1481         cur_len = 1024 * 1024;
1482         ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
1483                                          cur_off, cur_len, datacsum);
1484         if (ret < 0)
1485                 return ret;
1486
1487         /* second sb(fisrt sb is included in 0~1M) */
1488         cur_off = btrfs_sb_offset(1);
1489         cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
1490         if (cur_off > total_bytes)
1491                 return ret;
1492         ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
1493                                          cur_off, cur_len, datacsum);
1494         if (ret < 0)
1495                 return ret;
1496
1497         /* Last sb */
1498         cur_off = btrfs_sb_offset(2);
1499         cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
1500         if (cur_off > total_bytes)
1501                 return ret;
1502         ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
1503                                          cur_off, cur_len, datacsum);
1504         return ret;
1505 }
1506
1507 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
1508                                 int ensure_size);
1509
1510 /*
1511  * Create the fs image file of old filesystem.
1512  *
1513  * This is completely fs independent as we have cctx->used, only
1514  * need to create file extents pointing to all the positions.
1515  */
1516 static int create_image(struct btrfs_root *root,
1517                            struct btrfs_mkfs_config *cfg,
1518                            struct btrfs_convert_context *cctx, int fd,
1519                            u64 size, char *name, int datacsum)
1520 {
1521         struct btrfs_inode_item buf;
1522         struct btrfs_trans_handle *trans;
1523         struct btrfs_path *path = NULL;
1524         struct btrfs_key key;
1525         struct cache_extent *cache;
1526         struct cache_tree used_tmp;
1527         u64 cur;
1528         u64 ino;
1529         u64 flags = BTRFS_INODE_READONLY;
1530         int ret;
1531
1532         if (!datacsum)
1533                 flags |= BTRFS_INODE_NODATASUM;
1534
1535         trans = btrfs_start_transaction(root, 1);
1536         if (!trans)
1537                 return -ENOMEM;
1538
1539         cache_tree_init(&used_tmp);
1540
1541         ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
1542                                        &ino);
1543         if (ret < 0)
1544                 goto out;
1545         ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
1546         if (ret < 0)
1547                 goto out;
1548         ret = btrfs_change_inode_flags(trans, root, ino, flags);
1549         if (ret < 0)
1550                 goto out;
1551         ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
1552                              strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
1553         if (ret < 0)
1554                 goto out;
1555
1556         path = btrfs_alloc_path();
1557         if (!path) {
1558                 ret = -ENOMEM;
1559                 goto out;
1560         }
1561         key.objectid = ino;
1562         key.type = BTRFS_INODE_ITEM_KEY;
1563         key.offset = 0;
1564
1565         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1566         if (ret) {
1567                 ret = (ret > 0 ? -ENOENT : ret);
1568                 goto out;
1569         }
1570         read_extent_buffer(path->nodes[0], &buf,
1571                         btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
1572                         sizeof(buf));
1573         btrfs_release_path(path);
1574
1575         /*
1576          * Create a new used space cache, which doesn't contain the reserved
1577          * range
1578          */
1579         for (cache = first_cache_extent(&cctx->used); cache;
1580              cache = next_cache_extent(cache)) {
1581                 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
1582                 if (ret < 0)
1583                         goto out;
1584         }
1585         ret = wipe_reserved_ranges(&used_tmp, 0, 0);
1586         if (ret < 0)
1587                 goto out;
1588
1589         /*
1590          * Start from 1M, as 0~1M is reserved, and create_image_file_range()
1591          * can't handle bytenr 0(will consider it as a hole)
1592          */
1593         cur = 1024 * 1024;
1594         while (cur < size) {
1595                 u64 len = size - cur;
1596
1597                 ret = create_image_file_range(trans, root, &used_tmp,
1598                                                 &buf, ino, cur, &len, datacsum);
1599                 if (ret < 0)
1600                         goto out;
1601                 cur += len;
1602         }
1603         /* Handle the reserved ranges */
1604         ret = migrate_reserved_ranges(trans, root, &cctx->used, &buf, fd, ino,
1605                                       cfg->num_bytes, datacsum);
1606
1607
1608         key.objectid = ino;
1609         key.type = BTRFS_INODE_ITEM_KEY;
1610         key.offset = 0;
1611         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1612         if (ret) {
1613                 ret = (ret > 0 ? -ENOENT : ret);
1614                 goto out;
1615         }
1616         btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
1617         write_extent_buffer(path->nodes[0], &buf,
1618                         btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
1619                         sizeof(buf));
1620 out:
1621         free_extent_cache_tree(&used_tmp);
1622         btrfs_free_path(path);
1623         btrfs_commit_transaction(trans, root);
1624         return ret;
1625 }
1626
1627 static struct btrfs_root * link_subvol(struct btrfs_root *root,
1628                 const char *base, u64 root_objectid)
1629 {
1630         struct btrfs_trans_handle *trans;
1631         struct btrfs_fs_info *fs_info = root->fs_info;
1632         struct btrfs_root *tree_root = fs_info->tree_root;
1633         struct btrfs_root *new_root = NULL;
1634         struct btrfs_path *path;
1635         struct btrfs_inode_item *inode_item;
1636         struct extent_buffer *leaf;
1637         struct btrfs_key key;
1638         u64 dirid = btrfs_root_dirid(&root->root_item);
1639         u64 index = 2;
1640         char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1641         int len;
1642         int i;
1643         int ret;
1644
1645         len = strlen(base);
1646         if (len == 0 || len > BTRFS_NAME_LEN)
1647                 return NULL;
1648
1649         path = btrfs_alloc_path();
1650         BUG_ON(!path);
1651
1652         key.objectid = dirid;
1653         key.type = BTRFS_DIR_INDEX_KEY;
1654         key.offset = (u64)-1;
1655
1656         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1657         BUG_ON(ret <= 0);
1658
1659         if (path->slots[0] > 0) {
1660                 path->slots[0]--;
1661                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1662                 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1663                         index = key.offset + 1;
1664         }
1665         btrfs_release_path(path);
1666
1667         trans = btrfs_start_transaction(root, 1);
1668         BUG_ON(!trans);
1669
1670         key.objectid = dirid;
1671         key.offset = 0;
1672         key.type =  BTRFS_INODE_ITEM_KEY;
1673
1674         ret = btrfs_lookup_inode(trans, root, path, &key, 1);
1675         BUG_ON(ret);
1676         leaf = path->nodes[0];
1677         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1678                                     struct btrfs_inode_item);
1679
1680         key.objectid = root_objectid;
1681         key.offset = (u64)-1;
1682         key.type = BTRFS_ROOT_ITEM_KEY;
1683
1684         memcpy(buf, base, len);
1685         for (i = 0; i < 1024; i++) {
1686                 ret = btrfs_insert_dir_item(trans, root, buf, len,
1687                                             dirid, &key, BTRFS_FT_DIR, index);
1688                 if (ret != -EEXIST)
1689                         break;
1690                 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1691                 if (len < 1 || len > BTRFS_NAME_LEN) {
1692                         ret = -EINVAL;
1693                         break;
1694                 }
1695         }
1696         if (ret)
1697                 goto fail;
1698
1699         btrfs_set_inode_size(leaf, inode_item, len * 2 +
1700                              btrfs_inode_size(leaf, inode_item));
1701         btrfs_mark_buffer_dirty(leaf);
1702         btrfs_release_path(path);
1703
1704         /* add the backref first */
1705         ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1706                                  BTRFS_ROOT_BACKREF_KEY,
1707                                  root->root_key.objectid,
1708                                  dirid, index, buf, len);
1709         BUG_ON(ret);
1710
1711         /* now add the forward ref */
1712         ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1713                                  BTRFS_ROOT_REF_KEY, root_objectid,
1714                                  dirid, index, buf, len);
1715
1716         ret = btrfs_commit_transaction(trans, root);
1717         BUG_ON(ret);
1718
1719         new_root = btrfs_read_fs_root(fs_info, &key);
1720         if (IS_ERR(new_root))
1721                 new_root = NULL;
1722 fail:
1723         btrfs_free_path(path);
1724         return new_root;
1725 }
1726
1727 static int create_subvol(struct btrfs_trans_handle *trans,
1728                          struct btrfs_root *root, u64 root_objectid)
1729 {
1730         struct extent_buffer *tmp;
1731         struct btrfs_root *new_root;
1732         struct btrfs_key key;
1733         struct btrfs_root_item root_item;
1734         int ret;
1735
1736         ret = btrfs_copy_root(trans, root, root->node, &tmp,
1737                               root_objectid);
1738         BUG_ON(ret);
1739
1740         memcpy(&root_item, &root->root_item, sizeof(root_item));
1741         btrfs_set_root_bytenr(&root_item, tmp->start);
1742         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1743         btrfs_set_root_generation(&root_item, trans->transid);
1744         free_extent_buffer(tmp);
1745
1746         key.objectid = root_objectid;
1747         key.type = BTRFS_ROOT_ITEM_KEY;
1748         key.offset = trans->transid;
1749         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1750                                 &key, &root_item);
1751
1752         key.offset = (u64)-1;
1753         new_root = btrfs_read_fs_root(root->fs_info, &key);
1754         BUG_ON(!new_root || IS_ERR(new_root));
1755
1756         ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1757         BUG_ON(ret);
1758
1759         return 0;
1760 }
1761
1762 /*
1763  * New make_btrfs() has handle system and meta chunks quite well.
1764  * So only need to add remaining data chunks.
1765  */
1766 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1767                                           struct btrfs_fs_info *fs_info,
1768                                           struct btrfs_mkfs_config *cfg,
1769                                           struct btrfs_convert_context *cctx)
1770 {
1771         struct btrfs_root *extent_root = fs_info->extent_root;
1772         struct cache_tree *data_chunks = &cctx->data_chunks;
1773         struct cache_extent *cache;
1774         u64 max_chunk_size;
1775         int ret = 0;
1776
1777         /*
1778          * Don't create data chunk over 10% of the convert device
1779          * And for single chunk, don't create chunk larger than 1G.
1780          */
1781         max_chunk_size = cfg->num_bytes / 10;
1782         max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1783         max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1784
1785         for (cache = first_cache_extent(data_chunks); cache;
1786              cache = next_cache_extent(cache)) {
1787                 u64 cur = cache->start;
1788
1789                 while (cur < cache->start + cache->size) {
1790                         u64 len;
1791                         u64 cur_backup = cur;
1792
1793                         len = min(max_chunk_size,
1794                                   cache->start + cache->size - cur);
1795                         ret = btrfs_alloc_data_chunk(trans, extent_root,
1796                                         &cur_backup, len,
1797                                         BTRFS_BLOCK_GROUP_DATA, 1);
1798                         if (ret < 0)
1799                                 break;
1800                         ret = btrfs_make_block_group(trans, extent_root, 0,
1801                                         BTRFS_BLOCK_GROUP_DATA,
1802                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1803                                         cur, len);
1804                         if (ret < 0)
1805                                 break;
1806                         cur += len;
1807                 }
1808         }
1809         return ret;
1810 }
1811
1812 /*
1813  * Init the temp btrfs to a operational status.
1814  *
1815  * It will fix the extent usage accounting(XXX: Do we really need?) and
1816  * insert needed data chunks, to ensure all old fs data extents are covered
1817  * by DATA chunks, preventing wrong chunks are allocated.
1818  *
1819  * And also create convert image subvolume and relocation tree.
1820  * (XXX: Not need again?)
1821  * But the convert image subvolume is *NOT* linked to fs tree yet.
1822  */
1823 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1824                          struct btrfs_convert_context *cctx, int datacsum,
1825                          int packing, int noxattr)
1826 {
1827         struct btrfs_key location;
1828         struct btrfs_trans_handle *trans;
1829         struct btrfs_fs_info *fs_info = root->fs_info;
1830         int ret;
1831
1832         /*
1833          * Don't alloc any metadata/system chunk, as we don't want
1834          * any meta/sys chunk allcated before all data chunks are inserted.
1835          * Or we screw up the chunk layout just like the old implement.
1836          */
1837         fs_info->avoid_sys_chunk_alloc = 1;
1838         fs_info->avoid_meta_chunk_alloc = 1;
1839         trans = btrfs_start_transaction(root, 1);
1840         BUG_ON(!trans);
1841         ret = btrfs_fix_block_accounting(trans, root);
1842         if (ret)
1843                 goto err;
1844         ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1845         if (ret)
1846                 goto err;
1847         ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1848                                   BTRFS_ROOT_TREE_DIR_OBJECTID);
1849         if (ret)
1850                 goto err;
1851         memcpy(&location, &root->root_key, sizeof(location));
1852         location.offset = (u64)-1;
1853         ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1854                                 btrfs_super_root_dir(fs_info->super_copy),
1855                                 &location, BTRFS_FT_DIR, 0);
1856         if (ret)
1857                 goto err;
1858         ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1859                                 location.objectid,
1860                                 btrfs_super_root_dir(fs_info->super_copy), 0);
1861         if (ret)
1862                 goto err;
1863         btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1864                              BTRFS_FIRST_FREE_OBJECTID);
1865
1866         /* subvol for fs image file */
1867         ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1868         if (ret < 0)
1869                 goto err;
1870         /* subvol for data relocation tree */
1871         ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1872         if (ret < 0)
1873                 goto err;
1874
1875         ret = btrfs_commit_transaction(trans, root);
1876         fs_info->avoid_sys_chunk_alloc = 0;
1877         fs_info->avoid_meta_chunk_alloc = 0;
1878 err:
1879         return ret;
1880 }
1881
1882 /*
1883  * Migrate super block to its default position and zero 0 ~ 16k
1884  */
1885 static int migrate_super_block(int fd, u64 old_bytenr, u32 sectorsize)
1886 {
1887         int ret;
1888         struct extent_buffer *buf;
1889         struct btrfs_super_block *super;
1890         u32 len;
1891         u32 bytenr;
1892
1893         BUG_ON(sectorsize < sizeof(*super));
1894         buf = malloc(sizeof(*buf) + sectorsize);
1895         if (!buf)
1896                 return -ENOMEM;
1897
1898         buf->len = sectorsize;
1899         ret = pread(fd, buf->data, sectorsize, old_bytenr);
1900         if (ret != sectorsize)
1901                 goto fail;
1902
1903         super = (struct btrfs_super_block *)buf->data;
1904         BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1905         btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1906
1907         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1908         ret = pwrite(fd, buf->data, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1909         if (ret != sectorsize)
1910                 goto fail;
1911
1912         ret = fsync(fd);
1913         if (ret)
1914                 goto fail;
1915
1916         memset(buf->data, 0, sectorsize);
1917         for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1918                 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1919                 if (len > sectorsize)
1920                         len = sectorsize;
1921                 ret = pwrite(fd, buf->data, len, bytenr);
1922                 if (ret != len) {
1923                         fprintf(stderr, "unable to zero fill device\n");
1924                         break;
1925                 }
1926                 bytenr += len;
1927         }
1928         ret = 0;
1929         fsync(fd);
1930 fail:
1931         free(buf);
1932         if (ret > 0)
1933                 ret = -1;
1934         return ret;
1935 }
1936
1937 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1938 {
1939         struct btrfs_chunk *chunk;
1940         struct btrfs_disk_key *key;
1941         u32 sectorsize = btrfs_super_sectorsize(super);
1942
1943         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1944         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1945                                        sizeof(struct btrfs_disk_key));
1946
1947         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1948         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1949         btrfs_set_disk_key_offset(key, 0);
1950
1951         btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1952         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1953         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1954         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1955         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1956         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1957         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1958         btrfs_set_stack_chunk_num_stripes(chunk, 1);
1959         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1960         chunk->stripe.devid = super->dev_item.devid;
1961         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1962         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1963         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1964         return 0;
1965 }
1966
1967 static const struct btrfs_convert_operations ext2_convert_ops = {
1968         .name                   = "ext2",
1969         .open_fs                = ext2_open_fs,
1970         .read_used_space        = ext2_read_used_space,
1971         .copy_inodes            = ext2_copy_inodes,
1972         .close_fs               = ext2_close_fs,
1973 };
1974
1975 static const struct btrfs_convert_operations *convert_operations[] = {
1976         &ext2_convert_ops,
1977 };
1978
1979 static int convert_open_fs(const char *devname,
1980                            struct btrfs_convert_context *cctx)
1981 {
1982         int i;
1983
1984         memset(cctx, 0, sizeof(*cctx));
1985
1986         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
1987                 int ret = convert_operations[i]->open_fs(cctx, devname);
1988
1989                 if (ret == 0) {
1990                         cctx->convert_ops = convert_operations[i];
1991                         return ret;
1992                 }
1993         }
1994
1995         fprintf(stderr, "No file system found to convert.\n");
1996         return -1;
1997 }
1998
1999 /*
2000  * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
2001  * handle wiping a range that exists in cache.
2002  */
2003 static int _expand_extent_cache(struct cache_tree *tree,
2004                                 struct cache_extent *entry,
2005                                 u64 min_stripe_size, int backward)
2006 {
2007         struct cache_extent *ce;
2008         int diff;
2009
2010         if (entry->size >= min_stripe_size)
2011                 return 0;
2012         diff = min_stripe_size - entry->size;
2013
2014         if (backward) {
2015                 ce = prev_cache_extent(entry);
2016                 if (!ce)
2017                         goto expand_back;
2018                 if (ce->start + ce->size >= entry->start - diff) {
2019                         /* Directly merge with previous extent */
2020                         ce->size = entry->start + entry->size - ce->start;
2021                         remove_cache_extent(tree, entry);
2022                         free(entry);
2023                         return 0;
2024                 }
2025 expand_back:
2026                 /* No overlap, normal extent */
2027                 if (entry->start < diff) {
2028                         error("cannot find space for data chunk layout");
2029                         return -ENOSPC;
2030                 }
2031                 entry->start -= diff;
2032                 entry->size += diff;
2033                 return 0;
2034         }
2035         ce = next_cache_extent(entry);
2036         if (!ce)
2037                 goto expand_after;
2038         if (entry->start + entry->size + diff >= ce->start) {
2039                 /* Directly merge with next extent */
2040                 entry->size = ce->start + ce->size - entry->start;
2041                 remove_cache_extent(tree, ce);
2042                 free(ce);
2043                 return 0;
2044         }
2045 expand_after:
2046         entry->size += diff;
2047         return 0;
2048 }
2049
2050 /*
2051  * Remove one reserve range from given cache tree
2052  * if min_stripe_size is non-zero, it will ensure for split case,
2053  * all its split cache extent is no smaller than @min_strip_size / 2.
2054  */
2055 static int wipe_one_reserved_range(struct cache_tree *tree,
2056                                    u64 start, u64 len, u64 min_stripe_size,
2057                                    int ensure_size)
2058 {
2059         struct cache_extent *cache;
2060         int ret;
2061
2062         BUG_ON(ensure_size && min_stripe_size == 0);
2063         /*
2064          * The logical here is simplified to handle special cases only
2065          * So we don't need to consider merge case for ensure_size
2066          */
2067         BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
2068                min_stripe_size / 2 < BTRFS_STRIPE_LEN));
2069
2070         /* Also, wipe range should already be aligned */
2071         BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
2072                start + len != round_up(start + len, BTRFS_STRIPE_LEN));
2073
2074         min_stripe_size /= 2;
2075
2076         cache = lookup_cache_extent(tree, start, len);
2077         if (!cache)
2078                 return 0;
2079
2080         if (start <= cache->start) {
2081                 /*
2082                  *      |--------cache---------|
2083                  * |-wipe-|
2084                  */
2085                 BUG_ON(start + len <= cache->start);
2086
2087                 /*
2088                  * The wipe size is smaller than min_stripe_size / 2,
2089                  * so the result length should still meet min_stripe_size
2090                  * And no need to do alignment
2091                  */
2092                 cache->size -= (start + len - cache->start);
2093                 if (cache->size == 0) {
2094                         remove_cache_extent(tree, cache);
2095                         free(cache);
2096                         return 0;
2097                 }
2098
2099                 BUG_ON(ensure_size && cache->size < min_stripe_size);
2100
2101                 cache->start = start + len;
2102                 return 0;
2103         } else if (start > cache->start && start + len < cache->start +
2104                    cache->size) {
2105                 /*
2106                  * |-------cache-----|
2107                  *      |-wipe-|
2108                  */
2109                 u64 old_start = cache->start;
2110                 u64 old_len = cache->size;
2111                 u64 insert_start = start + len;
2112                 u64 insert_len;
2113
2114                 cache->size = start - cache->start;
2115                 /* Expand the leading half part if needed */
2116                 if (ensure_size && cache->size < min_stripe_size) {
2117                         ret = _expand_extent_cache(tree, cache,
2118                                         min_stripe_size, 1);
2119                         if (ret < 0)
2120                                 return ret;
2121                 }
2122
2123                 /* And insert the new one */
2124                 insert_len = old_start + old_len - start - len;
2125                 ret = add_merge_cache_extent(tree, insert_start, insert_len);
2126                 if (ret < 0)
2127                         return ret;
2128
2129                 /* Expand the last half part if needed */
2130                 if (ensure_size && insert_len < min_stripe_size) {
2131                         cache = lookup_cache_extent(tree, insert_start,
2132                                                     insert_len);
2133                         if (!cache || cache->start != insert_start ||
2134                             cache->size != insert_len)
2135                                 return -ENOENT;
2136                         ret = _expand_extent_cache(tree, cache,
2137                                         min_stripe_size, 0);
2138                 }
2139
2140                 return ret;
2141         }
2142         /*
2143          * |----cache-----|
2144          *              |--wipe-|
2145          * Wipe len should be small enough and no need to expand the
2146          * remaining extent
2147          */
2148         cache->size = start - cache->start;
2149         BUG_ON(ensure_size && cache->size < min_stripe_size);
2150         return 0;
2151 }
2152
2153 /*
2154  * Remove reserved ranges from given cache_tree
2155  *
2156  * It will remove the following ranges
2157  * 1) 0~1M
2158  * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
2159  * 3) 3rd superblock, +64K
2160  *
2161  * @min_stripe must be given for safety check
2162  * and if @ensure_size is given, it will ensure affected cache_extent will be
2163  * larger than min_stripe_size
2164  */
2165 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
2166                                 int ensure_size)
2167 {
2168         int ret;
2169
2170         ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
2171                                       ensure_size);
2172         if (ret < 0)
2173                 return ret;
2174         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
2175                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2176         if (ret < 0)
2177                 return ret;
2178         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
2179                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2180         return ret;
2181 }
2182
2183 static int calculate_available_space(struct btrfs_convert_context *cctx)
2184 {
2185         struct cache_tree *used = &cctx->used;
2186         struct cache_tree *data_chunks = &cctx->data_chunks;
2187         struct cache_tree *free = &cctx->free;
2188         struct cache_extent *cache;
2189         u64 cur_off = 0;
2190         /*
2191          * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
2192          * works without need to consider overlap
2193          */
2194         u64 min_stripe_size = 2 * 16 * 1024 * 1024;
2195         int ret;
2196
2197         /* Calculate data_chunks */
2198         for (cache = first_cache_extent(used); cache;
2199              cache = next_cache_extent(cache)) {
2200                 u64 cur_len;
2201
2202                 if (cache->start + cache->size < cur_off)
2203                         continue;
2204                 if (cache->start > cur_off + min_stripe_size)
2205                         cur_off = cache->start;
2206                 cur_len = max(cache->start + cache->size - cur_off,
2207                               min_stripe_size);
2208                 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
2209                 if (ret < 0)
2210                         goto out;
2211                 cur_off += cur_len;
2212         }
2213         /*
2214          * remove reserved ranges, so we won't ever bother relocating an old
2215          * filesystem extent to other place.
2216          */
2217         ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
2218         if (ret < 0)
2219                 goto out;
2220
2221         cur_off = 0;
2222         /*
2223          * Calculate free space
2224          * Always round up the start bytenr, to avoid metadata extent corss
2225          * stripe boundary, as later mkfs_convert() won't have all the extent
2226          * allocation check
2227          */
2228         for (cache = first_cache_extent(data_chunks); cache;
2229              cache = next_cache_extent(cache)) {
2230                 if (cache->start < cur_off)
2231                         continue;
2232                 if (cache->start > cur_off) {
2233                         u64 insert_start;
2234                         u64 len;
2235
2236                         len = cache->start - round_up(cur_off,
2237                                                       BTRFS_STRIPE_LEN);
2238                         insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2239
2240                         ret = add_merge_cache_extent(free, insert_start, len);
2241                         if (ret < 0)
2242                                 goto out;
2243                 }
2244                 cur_off = cache->start + cache->size;
2245         }
2246         /* Don't forget the last range */
2247         if (cctx->total_bytes > cur_off) {
2248                 u64 len = cctx->total_bytes - cur_off;
2249                 u64 insert_start;
2250
2251                 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2252
2253                 ret = add_merge_cache_extent(free, insert_start, len);
2254                 if (ret < 0)
2255                         goto out;
2256         }
2257
2258         /* Remove reserved bytes */
2259         ret = wipe_reserved_ranges(free, min_stripe_size, 0);
2260 out:
2261         return ret;
2262 }
2263 /*
2264  * Read used space, and since we have the used space,
2265  * calcuate data_chunks and free for later mkfs
2266  */
2267 static int convert_read_used_space(struct btrfs_convert_context *cctx)
2268 {
2269         int ret;
2270
2271         ret = cctx->convert_ops->read_used_space(cctx);
2272         if (ret)
2273                 return ret;
2274
2275         ret = calculate_available_space(cctx);
2276         return ret;
2277 }
2278
2279 static int do_convert(const char *devname, int datacsum, int packing,
2280                 int noxattr, u32 nodesize, int copylabel, const char *fslabel,
2281                 int progress, u64 features)
2282 {
2283         int ret;
2284         int fd = -1;
2285         int is_btrfs = 0;
2286         u32 blocksize;
2287         u64 total_bytes;
2288         struct btrfs_root *root;
2289         struct btrfs_root *image_root;
2290         struct btrfs_convert_context cctx;
2291         struct btrfs_key key;
2292         char *subvol_name = NULL;
2293         struct task_ctx ctx;
2294         char features_buf[64];
2295         struct btrfs_mkfs_config mkfs_cfg;
2296
2297         init_convert_context(&cctx);
2298         ret = convert_open_fs(devname, &cctx);
2299         if (ret)
2300                 goto fail;
2301         ret = convert_read_used_space(&cctx);
2302         if (ret)
2303                 goto fail;
2304
2305         blocksize = cctx.blocksize;
2306         total_bytes = (u64)blocksize * (u64)cctx.block_count;
2307         if (blocksize < 4096) {
2308                 fprintf(stderr, "block size is too small\n");
2309                 goto fail;
2310         }
2311         if (btrfs_check_nodesize(nodesize, blocksize, features))
2312                 goto fail;
2313         fd = open(devname, O_RDWR);
2314         if (fd < 0) {
2315                 fprintf(stderr, "unable to open %s\n", devname);
2316                 goto fail;
2317         }
2318         btrfs_parse_features_to_string(features_buf, features);
2319         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2320                 strcat(features_buf, " (default)");
2321
2322         printf("create btrfs filesystem:\n");
2323         printf("\tblocksize: %u\n", blocksize);
2324         printf("\tnodesize:  %u\n", nodesize);
2325         printf("\tfeatures:  %s\n", features_buf);
2326
2327         mkfs_cfg.label = cctx.volume_name;
2328         mkfs_cfg.num_bytes = total_bytes;
2329         mkfs_cfg.nodesize = nodesize;
2330         mkfs_cfg.sectorsize = blocksize;
2331         mkfs_cfg.stripesize = blocksize;
2332         mkfs_cfg.features = features;
2333         /* New convert need these space */
2334         mkfs_cfg.fs_uuid = malloc(BTRFS_UUID_UNPARSED_SIZE);
2335         mkfs_cfg.chunk_uuid = malloc(BTRFS_UUID_UNPARSED_SIZE);
2336         *(mkfs_cfg.fs_uuid) = '\0';
2337         *(mkfs_cfg.chunk_uuid) = '\0';
2338
2339         ret = make_btrfs(fd, &mkfs_cfg, &cctx);
2340         if (ret) {
2341                 fprintf(stderr, "unable to create initial ctree: %s\n",
2342                         strerror(-ret));
2343                 goto fail;
2344         }
2345
2346         root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
2347                              OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2348         if (!root) {
2349                 fprintf(stderr, "unable to open ctree\n");
2350                 goto fail;
2351         }
2352         ret = init_btrfs(&mkfs_cfg, root, &cctx, datacsum, packing, noxattr);
2353         if (ret) {
2354                 fprintf(stderr, "unable to setup the root tree\n");
2355                 goto fail;
2356         }
2357
2358         printf("creating %s image file.\n", cctx.convert_ops->name);
2359         ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2360         if (ret < 0) {
2361                 fprintf(stderr, "error allocating subvolume name: %s_saved\n",
2362                         cctx.convert_ops->name);
2363                 goto fail;
2364         }
2365         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2366         key.offset = (u64)-1;
2367         key.type = BTRFS_ROOT_ITEM_KEY;
2368         image_root = btrfs_read_fs_root(root->fs_info, &key);
2369         if (!image_root) {
2370                 fprintf(stderr, "unable to create subvol\n");
2371                 goto fail;
2372         }
2373         ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
2374                               mkfs_cfg.num_bytes, "image", datacsum);
2375         if (ret) {
2376                 fprintf(stderr, "error during create_image %d\n", ret);
2377                 goto fail;
2378         }
2379
2380         printf("creating btrfs metadata.\n");
2381         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2382         ctx.cur_copy_inodes = 0;
2383
2384         if (progress) {
2385                 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
2386                                      &ctx);
2387                 task_start(ctx.info);
2388         }
2389         ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2390         if (ret) {
2391                 fprintf(stderr, "error during copy_inodes %d\n", ret);
2392                 goto fail;
2393         }
2394         if (progress) {
2395                 task_stop(ctx.info);
2396                 task_deinit(ctx.info);
2397         }
2398
2399         image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2400
2401         free(subvol_name);
2402
2403         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2404         if (copylabel == 1) {
2405                 __strncpy_null(root->fs_info->super_copy->label,
2406                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2407                 fprintf(stderr, "copy label '%s'\n",
2408                                 root->fs_info->super_copy->label);
2409         } else if (copylabel == -1) {
2410                 strcpy(root->fs_info->super_copy->label, fslabel);
2411                 fprintf(stderr, "set label to '%s'\n", fslabel);
2412         }
2413
2414         ret = close_ctree(root);
2415         if (ret) {
2416                 fprintf(stderr, "error during close_ctree %d\n", ret);
2417                 goto fail;
2418         }
2419         convert_close_fs(&cctx);
2420         clean_convert_context(&cctx);
2421
2422         /*
2423          * If this step succeed, we get a mountable btrfs. Otherwise
2424          * the source fs is left unchanged.
2425          */
2426         ret = migrate_super_block(fd, mkfs_cfg.super_bytenr, blocksize);
2427         if (ret) {
2428                 fprintf(stderr, "unable to migrate super block\n");
2429                 goto fail;
2430         }
2431         is_btrfs = 1;
2432
2433         root = open_ctree_fd(fd, devname, 0,
2434                         OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2435         if (!root) {
2436                 fprintf(stderr, "unable to open ctree\n");
2437                 goto fail;
2438         }
2439         root->fs_info->finalize_on_close = 1;
2440         close_ctree(root);
2441         close(fd);
2442
2443         printf("conversion complete.\n");
2444         return 0;
2445 fail:
2446         clean_convert_context(&cctx);
2447         if (fd != -1)
2448                 close(fd);
2449         if (is_btrfs)
2450                 fprintf(stderr,
2451                         "WARNING: an error occurred during chunk mapping fixup, filesystem mountable but not finalized\n");
2452         else
2453                 fprintf(stderr, "conversion aborted\n");
2454         return -1;
2455 }
2456
2457 /*
2458  * Check if a non 1:1 mapped chunk can be rolled back.
2459  * For new convert, it's OK while for old convert it's not.
2460  */
2461 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
2462 {
2463         struct btrfs_block_group_cache *bg;
2464         struct btrfs_key key;
2465         struct btrfs_path path;
2466         struct btrfs_root *extent_root = fs_info->extent_root;
2467         u64 bg_start;
2468         u64 bg_end;
2469         int ret;
2470
2471         bg = btrfs_lookup_first_block_group(fs_info, bytenr);
2472         if (!bg)
2473                 return -ENOENT;
2474         bg_start = bg->key.objectid;
2475         bg_end = bg->key.objectid + bg->key.offset;
2476
2477         key.objectid = bg_end;
2478         key.type = BTRFS_METADATA_ITEM_KEY;
2479         key.offset = 0;
2480         btrfs_init_path(&path);
2481
2482         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2483         if (ret < 0)
2484                 return ret;
2485
2486         while (1) {
2487                 struct btrfs_extent_item *ei;
2488
2489                 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
2490                 if (ret > 0) {
2491                         ret = 0;
2492                         break;
2493                 }
2494                 if (ret < 0)
2495                         break;
2496
2497                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2498                 if (key.type == BTRFS_METADATA_ITEM_KEY)
2499                         continue;
2500                 /* Now it's EXTENT_ITEM_KEY only */
2501                 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
2502                                     struct btrfs_extent_item);
2503                 /*
2504                  * Found data extent, means this is old convert must follow 1:1
2505                  * mapping.
2506                  */
2507                 if (btrfs_extent_flags(path.nodes[0], ei)
2508                                 & BTRFS_EXTENT_FLAG_DATA) {
2509                         ret = -EINVAL;
2510                         break;
2511                 }
2512         }
2513         btrfs_release_path(&path);
2514         return ret;
2515 }
2516
2517 static int may_rollback(struct btrfs_root *root)
2518 {
2519         struct btrfs_fs_info *info = root->fs_info;
2520         struct btrfs_multi_bio *multi = NULL;
2521         u64 bytenr;
2522         u64 length;
2523         u64 physical;
2524         u64 total_bytes;
2525         int num_stripes;
2526         int ret;
2527
2528         if (btrfs_super_num_devices(info->super_copy) != 1)
2529                 goto fail;
2530
2531         bytenr = BTRFS_SUPER_INFO_OFFSET;
2532         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2533
2534         while (1) {
2535                 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2536                                       &length, &multi, 0, NULL);
2537                 if (ret) {
2538                         if (ret == -ENOENT) {
2539                                 /* removed block group at the tail */
2540                                 if (length == (u64)-1)
2541                                         break;
2542
2543                                 /* removed block group in the middle */
2544                                 goto next;
2545                         }
2546                         goto fail;
2547                 }
2548
2549                 num_stripes = multi->num_stripes;
2550                 physical = multi->stripes[0].physical;
2551                 kfree(multi);
2552
2553                 if (num_stripes != 1) {
2554                         error("num stripes for bytenr %llu is not 1", bytenr);
2555                         goto fail;
2556                 }
2557
2558                 /*
2559                  * Extra check for new convert, as metadata chunk from new
2560                  * convert is much more free than old convert, it doesn't need
2561                  * to do 1:1 mapping.
2562                  */
2563                 if (physical != bytenr) {
2564                         /*
2565                          * Check if it's a metadata chunk and has only metadata
2566                          * extent.
2567                          */
2568                         ret = may_rollback_chunk(info, bytenr);
2569                         if (ret < 0)
2570                                 goto fail;
2571                 }
2572 next:
2573                 bytenr += length;
2574                 if (bytenr >= total_bytes)
2575                         break;
2576         }
2577         return 0;
2578 fail:
2579         return -1;
2580 }
2581
2582 static int do_rollback(const char *devname)
2583 {
2584         int fd = -1;
2585         int ret;
2586         int i;
2587         struct btrfs_root *root;
2588         struct btrfs_root *image_root;
2589         struct btrfs_root *chunk_root;
2590         struct btrfs_dir_item *dir;
2591         struct btrfs_inode_item *inode;
2592         struct btrfs_file_extent_item *fi;
2593         struct btrfs_trans_handle *trans;
2594         struct extent_buffer *leaf;
2595         struct btrfs_block_group_cache *cache1;
2596         struct btrfs_block_group_cache *cache2;
2597         struct btrfs_key key;
2598         struct btrfs_path path;
2599         struct extent_io_tree io_tree;
2600         char *buf = NULL;
2601         char *name;
2602         u64 bytenr;
2603         u64 num_bytes;
2604         u64 root_dir;
2605         u64 objectid;
2606         u64 offset;
2607         u64 start;
2608         u64 end;
2609         u64 sb_bytenr;
2610         u64 first_free;
2611         u64 total_bytes;
2612         u32 sectorsize;
2613
2614         extent_io_tree_init(&io_tree);
2615
2616         fd = open(devname, O_RDWR);
2617         if (fd < 0) {
2618                 fprintf(stderr, "unable to open %s\n", devname);
2619                 goto fail;
2620         }
2621         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2622         if (!root) {
2623                 fprintf(stderr, "unable to open ctree\n");
2624                 goto fail;
2625         }
2626         ret = may_rollback(root);
2627         if (ret < 0) {
2628                 fprintf(stderr, "unable to do rollback\n");
2629                 goto fail;
2630         }
2631
2632         sectorsize = root->sectorsize;
2633         buf = malloc(sectorsize);
2634         if (!buf) {
2635                 fprintf(stderr, "unable to allocate memory\n");
2636                 goto fail;
2637         }
2638
2639         btrfs_init_path(&path);
2640
2641         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2642         key.type = BTRFS_ROOT_BACKREF_KEY;
2643         key.offset = BTRFS_FS_TREE_OBJECTID;
2644         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
2645                                 0);
2646         btrfs_release_path(&path);
2647         if (ret > 0) {
2648                 fprintf(stderr,
2649                 "ERROR: unable to convert ext2 image subvolume, is it deleted?\n");
2650                 goto fail;
2651         } else if (ret < 0) {
2652                 fprintf(stderr,
2653                         "ERROR: unable to open ext2_saved, id=%llu: %s\n",
2654                         (unsigned long long)key.objectid, strerror(-ret));
2655                 goto fail;
2656         }
2657
2658         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2659         key.type = BTRFS_ROOT_ITEM_KEY;
2660         key.offset = (u64)-1;
2661         image_root = btrfs_read_fs_root(root->fs_info, &key);
2662         if (!image_root || IS_ERR(image_root)) {
2663                 fprintf(stderr, "unable to open subvol %llu\n",
2664                         (unsigned long long)key.objectid);
2665                 goto fail;
2666         }
2667
2668         name = "image";
2669         root_dir = btrfs_root_dirid(&root->root_item);
2670         dir = btrfs_lookup_dir_item(NULL, image_root, &path,
2671                                    root_dir, name, strlen(name), 0);
2672         if (!dir || IS_ERR(dir)) {
2673                 fprintf(stderr, "unable to find file %s\n", name);
2674                 goto fail;
2675         }
2676         leaf = path.nodes[0];
2677         btrfs_dir_item_key_to_cpu(leaf, dir, &key);
2678         btrfs_release_path(&path);
2679
2680         objectid = key.objectid;
2681
2682         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
2683         if (ret) {
2684                 fprintf(stderr, "unable to find inode item\n");
2685                 goto fail;
2686         }
2687         leaf = path.nodes[0];
2688         inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
2689         total_bytes = btrfs_inode_size(leaf, inode);
2690         btrfs_release_path(&path);
2691
2692         key.objectid = objectid;
2693         key.offset = 0;
2694         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
2695         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
2696         if (ret != 0) {
2697                 fprintf(stderr, "unable to find first file extent\n");
2698                 btrfs_release_path(&path);
2699                 goto fail;
2700         }
2701
2702         /* build mapping tree for the relocated blocks */
2703         for (offset = 0; offset < total_bytes; ) {
2704                 leaf = path.nodes[0];
2705                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2706                         ret = btrfs_next_leaf(root, &path);
2707                         if (ret != 0)
2708                                 break;  
2709                         continue;
2710                 }
2711
2712                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2713                 if (key.objectid != objectid || key.offset != offset ||
2714                     btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2715                         break;
2716
2717                 fi = btrfs_item_ptr(leaf, path.slots[0],
2718                                     struct btrfs_file_extent_item);
2719                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2720                         break;
2721                 if (btrfs_file_extent_compression(leaf, fi) ||
2722                     btrfs_file_extent_encryption(leaf, fi) ||
2723                     btrfs_file_extent_other_encoding(leaf, fi))
2724                         break;
2725
2726                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2727                 /* skip holes and direct mapped extents */
2728                 if (bytenr == 0 || bytenr == offset)
2729                         goto next_extent;
2730
2731                 bytenr += btrfs_file_extent_offset(leaf, fi);
2732                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2733
2734                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2735                 cache2 = btrfs_lookup_block_group(root->fs_info,
2736                                                   offset + num_bytes - 1);
2737                 /*
2738                  * Here we must take consideration of old and new convert
2739                  * behavior.
2740                  * For old convert case, sign, there is no consist chunk type
2741                  * that will cover the extent. META/DATA/SYS are all possible.
2742                  * Just ensure relocate one is in SYS chunk.
2743                  * For new convert case, they are all covered by DATA chunk.
2744                  *
2745                  * So, there is not valid chunk type check for it now.
2746                  */
2747                 if (cache1 != cache2)
2748                         break;
2749
2750                 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
2751                                 EXTENT_LOCKED, GFP_NOFS);
2752                 set_state_private(&io_tree, offset, bytenr);
2753 next_extent:
2754                 offset += btrfs_file_extent_num_bytes(leaf, fi);
2755                 path.slots[0]++;
2756         }
2757         btrfs_release_path(&path);
2758
2759         if (offset < total_bytes) {
2760                 fprintf(stderr, "unable to build extent mapping\n");
2761                 fprintf(stderr, "converted filesystem after balance is unable to rollback\n");
2762                 goto fail;
2763         }
2764
2765         first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
2766         first_free &= ~((u64)sectorsize - 1);
2767         /* backup for extent #0 should exist */
2768         if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
2769                 fprintf(stderr, "no backup for the first extent\n");
2770                 goto fail;
2771         }
2772         /* force no allocation from system block group */
2773         root->fs_info->system_allocs = -1;
2774         trans = btrfs_start_transaction(root, 1);
2775         BUG_ON(!trans);
2776         /*
2777          * recow the whole chunk tree, this will remove all chunk tree blocks
2778          * from system block group
2779          */
2780         chunk_root = root->fs_info->chunk_root;
2781         memset(&key, 0, sizeof(key));
2782         while (1) {
2783                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2784                 if (ret < 0)
2785                         break;
2786
2787                 ret = btrfs_next_leaf(chunk_root, &path);
2788                 if (ret)
2789                         break;
2790
2791                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2792                 btrfs_release_path(&path);
2793         }
2794         btrfs_release_path(&path);
2795
2796         offset = 0;
2797         num_bytes = 0;
2798         while(1) {
2799                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2800                 if (!cache1)
2801                         break;
2802
2803                 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2804                         num_bytes += btrfs_block_group_used(&cache1->item);
2805
2806                 offset = cache1->key.objectid + cache1->key.offset;
2807         }
2808         /* only extent #0 left in system block group? */
2809         if (num_bytes > first_free) {
2810                 fprintf(stderr, "unable to empty system block group\n");
2811                 goto fail;
2812         }
2813         /* create a system chunk that maps the whole device */
2814         ret = prepare_system_chunk_sb(root->fs_info->super_copy);
2815         if (ret) {
2816                 fprintf(stderr, "unable to update system chunk\n");
2817                 goto fail;
2818         }
2819
2820         ret = btrfs_commit_transaction(trans, root);
2821         BUG_ON(ret);
2822
2823         ret = close_ctree(root);
2824         if (ret) {
2825                 fprintf(stderr, "error during close_ctree %d\n", ret);
2826                 goto fail;
2827         }
2828
2829         /* zero btrfs super block mirrors */
2830         memset(buf, 0, sectorsize);
2831         for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2832                 bytenr = btrfs_sb_offset(i);
2833                 if (bytenr >= total_bytes)
2834                         break;
2835                 ret = pwrite(fd, buf, sectorsize, bytenr);
2836                 if (ret != sectorsize) {
2837                         fprintf(stderr,
2838                                 "error during zeroing superblock %d: %d\n",
2839                                 i, ret);
2840                         goto fail;
2841                 }
2842         }
2843
2844         sb_bytenr = (u64)-1;
2845         /* copy all relocated blocks back */
2846         while(1) {
2847                 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2848                                             EXTENT_LOCKED);
2849                 if (ret)
2850                         break;
2851
2852                 ret = get_state_private(&io_tree, start, &bytenr);
2853                 BUG_ON(ret);
2854
2855                 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2856                                   GFP_NOFS);
2857
2858                 while (start <= end) {
2859                         if (start == BTRFS_SUPER_INFO_OFFSET) {
2860                                 sb_bytenr = bytenr;
2861                                 goto next_sector;
2862                         }
2863                         ret = pread(fd, buf, sectorsize, bytenr);
2864                         if (ret < 0) {
2865                                 fprintf(stderr, "error during pread %d\n", ret);
2866                                 goto fail;
2867                         }
2868                         BUG_ON(ret != sectorsize);
2869                         ret = pwrite(fd, buf, sectorsize, start);
2870                         if (ret < 0) {
2871                                 fprintf(stderr, "error during pwrite %d\n", ret);
2872                                 goto fail;
2873                         }
2874                         BUG_ON(ret != sectorsize);
2875 next_sector:
2876                         start += sectorsize;
2877                         bytenr += sectorsize;
2878                 }
2879         }
2880
2881         ret = fsync(fd);
2882         if (ret) {
2883                 fprintf(stderr, "error during fsync %d\n", ret);
2884                 goto fail;
2885         }
2886         /*
2887          * finally, overwrite btrfs super block.
2888          */
2889         ret = pread(fd, buf, sectorsize, sb_bytenr);
2890         if (ret < 0) {
2891                 fprintf(stderr, "error during pread %d\n", ret);
2892                 goto fail;
2893         }
2894         BUG_ON(ret != sectorsize);
2895         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
2896         if (ret < 0) {
2897                 fprintf(stderr, "error during pwrite %d\n", ret);
2898                 goto fail;
2899         }
2900         BUG_ON(ret != sectorsize);
2901         ret = fsync(fd);
2902         if (ret) {
2903                 fprintf(stderr, "error during fsync %d\n", ret);
2904                 goto fail;
2905         }
2906
2907         close(fd);
2908         free(buf);
2909         extent_io_tree_cleanup(&io_tree);
2910         printf("rollback complete.\n");
2911         return 0;
2912
2913 fail:
2914         if (fd != -1)
2915                 close(fd);
2916         free(buf);
2917         fprintf(stderr, "rollback aborted.\n");
2918         return -1;
2919 }
2920
2921 static void print_usage(void)
2922 {
2923         printf("usage: btrfs-convert [options] device\n");
2924         printf("options:\n");
2925         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
2926         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
2927         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
2928         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
2929         printf("\t-r|--rollback          roll back to the original filesystem\n");
2930         printf("\t-l|--label LABEL       set filesystem label\n");
2931         printf("\t-L|--copy-label        use label from converted filesystem\n");
2932         printf("\t-p|--progress          show converting progress (default)\n");
2933         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
2934         printf("\t--no-progress          show only overview, not the detailed progress\n");
2935 }
2936
2937 int main(int argc, char *argv[])
2938 {
2939         int ret;
2940         int packing = 1;
2941         int noxattr = 0;
2942         int datacsum = 1;
2943         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
2944                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
2945         int rollback = 0;
2946         int copylabel = 0;
2947         int usage_error = 0;
2948         int progress = 1;
2949         char *file;
2950         char fslabel[BTRFS_LABEL_SIZE];
2951         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
2952
2953         while(1) {
2954                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
2955                 static const struct option long_options[] = {
2956                         { "no-progress", no_argument, NULL,
2957                                 GETOPT_VAL_NO_PROGRESS },
2958                         { "no-datasum", no_argument, NULL, 'd' },
2959                         { "no-inline", no_argument, NULL, 'n' },
2960                         { "no-xattr", no_argument, NULL, 'i' },
2961                         { "rollback", no_argument, NULL, 'r' },
2962                         { "features", required_argument, NULL, 'O' },
2963                         { "progress", no_argument, NULL, 'p' },
2964                         { "label", required_argument, NULL, 'l' },
2965                         { "copy-label", no_argument, NULL, 'L' },
2966                         { "nodesize", required_argument, NULL, 'N' },
2967                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
2968                         { NULL, 0, NULL, 0 }
2969                 };
2970                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
2971
2972                 if (c < 0)
2973                         break;
2974                 switch(c) {
2975                         case 'd':
2976                                 datacsum = 0;
2977                                 break;
2978                         case 'i':
2979                                 noxattr = 1;
2980                                 break;
2981                         case 'n':
2982                                 packing = 0;
2983                                 break;
2984                         case 'N':
2985                                 nodesize = parse_size(optarg);
2986                                 break;
2987                         case 'r':
2988                                 rollback = 1;
2989                                 break;
2990                         case 'l':
2991                                 copylabel = -1;
2992                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
2993                                         fprintf(stderr,
2994                                 "WARNING: label too long, trimmed to %d bytes\n",
2995                                                 BTRFS_LABEL_SIZE - 1);
2996                                 }
2997                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
2998                                 break;
2999                         case 'L':
3000                                 copylabel = 1;
3001                                 break;
3002                         case 'p':
3003                                 progress = 1;
3004                                 break;
3005                         case 'O': {
3006                                 char *orig = strdup(optarg);
3007                                 char *tmp = orig;
3008
3009                                 tmp = btrfs_parse_fs_features(tmp, &features);
3010                                 if (tmp) {
3011                                         fprintf(stderr,
3012                                                 "Unrecognized filesystem feature '%s'\n",
3013                                                         tmp);
3014                                         free(orig);
3015                                         exit(1);
3016                                 }
3017                                 free(orig);
3018                                 if (features & BTRFS_FEATURE_LIST_ALL) {
3019                                         btrfs_list_all_fs_features(
3020                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3021                                         exit(0);
3022                                 }
3023                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3024                                         char buf[64];
3025
3026                                         btrfs_parse_features_to_string(buf,
3027                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3028                                         fprintf(stderr,
3029                                                 "ERROR: features not allowed for convert: %s\n",
3030                                                 buf);
3031                                         exit(1);
3032                                 }
3033
3034                                 break;
3035                                 }
3036                         case GETOPT_VAL_NO_PROGRESS:
3037                                 progress = 0;
3038                                 break;
3039                         case GETOPT_VAL_HELP:
3040                         default:
3041                                 print_usage();
3042                                 return c != GETOPT_VAL_HELP;
3043                 }
3044         }
3045         set_argv0(argv);
3046         if (check_argc_exact(argc - optind, 1)) {
3047                 print_usage();
3048                 return 1;
3049         }
3050
3051         if (rollback && (!datacsum || noxattr || !packing)) {
3052                 fprintf(stderr,
3053                         "Usage error: -d, -i, -n options do not apply to rollback\n");
3054                 usage_error++;
3055         }
3056
3057         if (usage_error) {
3058                 print_usage();
3059                 return 1;
3060         }
3061
3062         file = argv[optind];
3063         ret = check_mounted(file);
3064         if (ret < 0) {
3065                 fprintf(stderr, "Could not check mount status: %s\n",
3066                         strerror(-ret));
3067                 return 1;
3068         } else if (ret) {
3069                 fprintf(stderr, "%s is mounted\n", file);
3070                 return 1;
3071         }
3072
3073         if (rollback) {
3074                 ret = do_rollback(file);
3075         } else {
3076                 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3077                                 copylabel, fslabel, progress, features);
3078         }
3079         if (ret)
3080                 return 1;
3081         return 0;
3082 }