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