btrfs-progs: convert: Introduce new function to create converted image
[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 (*alloc_block)(struct btrfs_convert_context *cctx, u64 goal,
98                            u64 *block_ret);
99         int (*alloc_block_range)(struct btrfs_convert_context *cctx, u64 goal,
100                            int num, u64 *block_ret);
101         int (*test_block)(struct btrfs_convert_context *cctx, u64 block);
102         void (*free_block)(struct btrfs_convert_context *cctx, u64 block);
103         void (*free_block_range)(struct btrfs_convert_context *cctx, u64 block,
104                            int num);
105         int (*copy_inodes)(struct btrfs_convert_context *cctx,
106                          struct btrfs_root *root, int datacsum,
107                          int packing, int noxattr, struct task_ctx *p);
108         void (*close_fs)(struct btrfs_convert_context *cctx);
109 };
110
111 static void init_convert_context(struct btrfs_convert_context *cctx)
112 {
113         cache_tree_init(&cctx->used);
114         cache_tree_init(&cctx->data_chunks);
115         cache_tree_init(&cctx->free);
116 }
117
118 static void clean_convert_context(struct btrfs_convert_context *cctx)
119 {
120         free_extent_cache_tree(&cctx->used);
121         free_extent_cache_tree(&cctx->data_chunks);
122         free_extent_cache_tree(&cctx->free);
123 }
124
125 static inline int convert_alloc_block(struct btrfs_convert_context *cctx,
126                                       u64 goal, u64 *ret)
127 {
128         return  cctx->convert_ops->alloc_block(cctx, goal, ret);
129 }
130
131 static inline int convert_alloc_block_range(struct btrfs_convert_context *cctx,
132                                       u64 goal, int num, u64 *ret)
133 {
134         return  cctx->convert_ops->alloc_block_range(cctx, goal, num, ret);
135 }
136
137 static inline int convert_test_block(struct btrfs_convert_context *cctx,
138                                      u64 block)
139 {
140         return cctx->convert_ops->test_block(cctx, block);
141 }
142
143 static inline void convert_free_block(struct btrfs_convert_context *cctx,
144                                       u64 block)
145 {
146         cctx->convert_ops->free_block(cctx, block);
147 }
148
149 static inline void convert_free_block_range(struct btrfs_convert_context *cctx,
150                                       u64 block, int num)
151 {
152         cctx->convert_ops->free_block_range(cctx, block, num);
153 }
154
155 static inline int copy_inodes(struct btrfs_convert_context *cctx,
156                               struct btrfs_root *root, int datacsum,
157                               int packing, int noxattr, struct task_ctx *p)
158 {
159         return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
160                                              noxattr, p);
161 }
162
163 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
164 {
165         cctx->convert_ops->close_fs(cctx);
166 }
167
168 /*
169  * Open Ext2fs in readonly mode, read block allocation bitmap and
170  * inode bitmap into memory.
171  */
172 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
173 {
174         errcode_t ret;
175         ext2_filsys ext2_fs;
176         ext2_ino_t ino;
177         u32 ro_feature;
178
179         ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
180         if (ret) {
181                 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
182                 return -1;
183         }
184         /*
185          * We need to know exactly the used space, some RO compat flags like
186          * BIGALLOC will affect how used space is present.
187          * So we need manuall check any unsupported RO compat flags
188          */
189         ro_feature = ext2_fs->super->s_feature_ro_compat;
190         if (ro_feature & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
191                 error(
192 "unsupported RO features detected: %x, abort convert to avoid possible corruption",
193                       ro_feature & ~EXT2_LIB_FEATURE_COMPAT_SUPP);
194                 goto fail;
195         }
196         ret = ext2fs_read_inode_bitmap(ext2_fs);
197         if (ret) {
198                 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
199                         error_message(ret));
200                 goto fail;
201         }
202         ret = ext2fs_read_block_bitmap(ext2_fs);
203         if (ret) {
204                 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
205                         error_message(ret));
206                 goto fail;
207         }
208         /*
209          * search each block group for a free inode. this set up
210          * uninit block/inode bitmaps appropriately.
211          */
212         ino = 1;
213         while (ino <= ext2_fs->super->s_inodes_count) {
214                 ext2_ino_t foo;
215                 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
216                 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
217         }
218
219         if (!(ext2_fs->super->s_feature_incompat &
220               EXT2_FEATURE_INCOMPAT_FILETYPE)) {
221                 fprintf(stderr, "filetype feature is missing\n");
222                 goto fail;
223         }
224
225         cctx->fs_data = ext2_fs;
226         cctx->blocksize = ext2_fs->blocksize;
227         cctx->block_count = ext2_fs->super->s_blocks_count;
228         cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
229         cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
230         cctx->first_data_block = ext2_fs->super->s_first_data_block;
231         cctx->inodes_count = ext2_fs->super->s_inodes_count;
232         cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
233         return 0;
234 fail:
235         ext2fs_close(ext2_fs);
236         return -1;
237 }
238
239 static int __ext2_add_one_block(ext2_filsys fs, char *bitmap,
240                                 unsigned long group_nr, struct cache_tree *used)
241 {
242         unsigned long offset;
243         unsigned i;
244         int ret = 0;
245
246         offset = fs->super->s_first_data_block;
247         offset /= EXT2FS_CLUSTER_RATIO(fs);
248         offset += group_nr * EXT2_CLUSTERS_PER_GROUP(fs->super);
249         for (i = 0; i < EXT2_CLUSTERS_PER_GROUP(fs->super); i++) {
250                 if (ext2fs_test_bit(i, bitmap)) {
251                         u64 start;
252
253                         start = (i + offset) * EXT2FS_CLUSTER_RATIO(fs);
254                         start *= fs->blocksize;
255                         ret = add_merge_cache_extent(used, start,
256                                                      fs->blocksize);
257                         if (ret < 0)
258                                 break;
259                 }
260         }
261         return ret;
262 }
263
264 /*
265  * Read all used ext2 space into cctx->used cache tree
266  */
267 static int ext2_read_used_space(struct btrfs_convert_context *cctx)
268 {
269         ext2_filsys fs = (ext2_filsys)cctx->fs_data;
270         blk64_t blk_itr = EXT2FS_B2C(fs, fs->super->s_first_data_block);
271         struct cache_tree *used_tree = &cctx->used;
272         char *block_bitmap = NULL;
273         unsigned long i;
274         int block_nbytes;
275         int ret = 0;
276
277         block_nbytes = EXT2_CLUSTERS_PER_GROUP(fs->super) / 8;
278         /* Shouldn't happen */
279         BUG_ON(!fs->block_map);
280
281         block_bitmap = malloc(block_nbytes);
282         if (!block_bitmap)
283                 return -ENOMEM;
284
285         for (i = 0; i < fs->group_desc_count; i++) {
286                 ret = ext2fs_get_block_bitmap_range(fs->block_map, blk_itr,
287                                                 block_nbytes * 8, block_bitmap);
288                 if (ret) {
289                         error("fail to get bitmap from ext2, %s",
290                               strerror(-ret));
291                         break;
292                 }
293                 ret = __ext2_add_one_block(fs, block_bitmap, i, used_tree);
294                 if (ret < 0) {
295                         error("fail to build used space tree, %s",
296                               strerror(-ret));
297                         break;
298                 }
299                 blk_itr += EXT2_CLUSTERS_PER_GROUP(fs->super);
300         }
301
302         free(block_bitmap);
303         return ret;
304 }
305
306 static void ext2_close_fs(struct btrfs_convert_context *cctx)
307 {
308         if (cctx->volume_name) {
309                 free(cctx->volume_name);
310                 cctx->volume_name = NULL;
311         }
312         ext2fs_close(cctx->fs_data);
313 }
314
315 static int ext2_alloc_block(struct btrfs_convert_context *cctx,
316                             u64 goal, u64 *block_ret)
317 {
318         ext2_filsys fs = cctx->fs_data;
319         blk_t block;
320
321         if (!ext2fs_new_block(fs, goal, NULL, &block)) {
322                 ext2fs_fast_mark_block_bitmap(fs->block_map, block);
323                 *block_ret = block;
324                 return 0;
325         }
326         return -ENOSPC;
327 }
328
329 static int ext2_alloc_block_range(struct btrfs_convert_context *cctx, u64 goal,
330                 int num, u64 *block_ret)
331 {
332         ext2_filsys fs = cctx->fs_data;
333         blk_t block;
334         ext2fs_block_bitmap bitmap = fs->block_map;
335         blk_t start = ext2fs_get_block_bitmap_start(bitmap);
336         blk_t end = ext2fs_get_block_bitmap_end(bitmap);
337
338         for (block = max_t(u64, goal, start); block + num < end; block++) {
339                 if (ext2fs_fast_test_block_bitmap_range(bitmap, block, num)) {
340                         ext2fs_fast_mark_block_bitmap_range(bitmap, block,
341                                         num);
342                         *block_ret = block;
343                         return 0;
344                 }
345         }
346         return -ENOSPC;
347 }
348
349 static void ext2_free_block(struct btrfs_convert_context *cctx, u64 block)
350 {
351         ext2_filsys fs = cctx->fs_data;
352
353         BUG_ON(block != (blk_t)block);
354         ext2fs_fast_unmark_block_bitmap(fs->block_map, block);
355 }
356
357 static void ext2_free_block_range(struct btrfs_convert_context *cctx, u64 block, int num)
358 {
359         ext2_filsys fs = cctx->fs_data;
360
361         BUG_ON(block != (blk_t)block);
362         ext2fs_fast_unmark_block_bitmap_range(fs->block_map, block, num);
363 }
364
365 static int cache_free_extents(struct btrfs_root *root,
366                               struct btrfs_convert_context *cctx)
367
368 {
369         int i, ret = 0;
370         blk_t block;
371         u64 bytenr;
372         u64 blocksize = cctx->blocksize;
373
374         block = cctx->first_data_block;
375         for (; block < cctx->block_count; block++) {
376                 if (convert_test_block(cctx, block))
377                         continue;
378                 bytenr = block * blocksize;
379                 ret = set_extent_dirty(&root->fs_info->free_space_cache,
380                                        bytenr, bytenr + blocksize - 1, 0);
381                 BUG_ON(ret);
382         }
383
384         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
385                 bytenr = btrfs_sb_offset(i);
386                 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
387                 if (bytenr >= blocksize * cctx->block_count)
388                         break;
389                 clear_extent_dirty(&root->fs_info->free_space_cache, bytenr,
390                                    bytenr + BTRFS_STRIPE_LEN - 1, 0);
391         }
392
393         clear_extent_dirty(&root->fs_info->free_space_cache,
394                            0, BTRFS_SUPER_INFO_OFFSET - 1, 0);
395
396         return 0;
397 }
398
399 static int custom_alloc_extent(struct btrfs_root *root, u64 num_bytes,
400                                u64 hint_byte, struct btrfs_key *ins,
401                                int metadata)
402 {
403         u64 start;
404         u64 end;
405         u64 last = hint_byte;
406         int ret;
407         int wrapped = 0;
408         struct btrfs_block_group_cache *cache;
409
410         while(1) {
411                 ret = find_first_extent_bit(&root->fs_info->free_space_cache,
412                                             last, &start, &end, EXTENT_DIRTY);
413                 if (ret) {
414                         if (wrapped++ == 0) {
415                                 last = 0;
416                                 continue;
417                         } else {
418                                 goto fail;
419                         }
420                 }
421
422                 start = max(last, start);
423                 last = end + 1;
424                 if (last - start < num_bytes)
425                         continue;
426
427                 last = start + num_bytes;
428                 if (test_range_bit(&root->fs_info->pinned_extents,
429                                    start, last - 1, EXTENT_DIRTY, 0))
430                         continue;
431
432                 cache = btrfs_lookup_block_group(root->fs_info, start);
433                 BUG_ON(!cache);
434                 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM ||
435                     last > cache->key.objectid + cache->key.offset) {
436                         last = cache->key.objectid + cache->key.offset;
437                         continue;
438                 }
439
440                 if (metadata) {
441                         BUG_ON(num_bytes != root->nodesize);
442                         if (check_crossing_stripes(start, num_bytes)) {
443                                 last = round_down(start + num_bytes,
444                                                   BTRFS_STRIPE_LEN);
445                                 continue;
446                         }
447                 }
448                 clear_extent_dirty(&root->fs_info->free_space_cache,
449                                    start, start + num_bytes - 1, 0);
450
451                 ins->objectid = start;
452                 ins->offset = num_bytes;
453                 ins->type = BTRFS_EXTENT_ITEM_KEY;
454                 return 0;
455         }
456 fail:
457         fprintf(stderr, "not enough free space\n");
458         return -ENOSPC;
459 }
460
461 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
462 {
463         int i;
464         u64 offset;
465
466         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
467                 offset = btrfs_sb_offset(i);
468                 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
469
470                 if (bytenr < offset + BTRFS_STRIPE_LEN &&
471                     bytenr + num_bytes > offset)
472                         return 1;
473         }
474         return 0;
475 }
476
477 static int custom_free_extent(struct btrfs_root *root, u64 bytenr,
478                               u64 num_bytes)
479 {
480         return intersect_with_sb(bytenr, num_bytes);
481 }
482
483 static struct btrfs_extent_ops extent_ops = {
484         .alloc_extent = custom_alloc_extent,
485         .free_extent = custom_free_extent,
486 };
487
488 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
489                                  struct btrfs_root *root,
490                                  const char *name, size_t name_len,
491                                  u64 dir, u64 objectid,
492                                  u8 file_type, u64 index_cnt,
493                                  struct btrfs_inode_item *inode)
494 {
495         int ret;
496         u64 inode_size;
497         struct btrfs_key location = {
498                 .objectid = objectid,
499                 .offset = 0,
500                 .type = BTRFS_INODE_ITEM_KEY,
501         };
502
503         ret = btrfs_insert_dir_item(trans, root, name, name_len,
504                                     dir, &location, file_type, index_cnt);
505         if (ret)
506                 return ret;
507         ret = btrfs_insert_inode_ref(trans, root, name, name_len,
508                                      objectid, dir, index_cnt);
509         if (ret)
510                 return ret;
511         inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
512         btrfs_set_stack_inode_size(inode, inode_size);
513
514         return 0;
515 }
516
517 struct dir_iterate_data {
518         struct btrfs_trans_handle *trans;
519         struct btrfs_root *root;
520         struct btrfs_inode_item *inode;
521         u64 objectid;
522         u64 index_cnt;
523         u64 parent;
524         int errcode;
525 };
526
527 static u8 filetype_conversion_table[EXT2_FT_MAX] = {
528         [EXT2_FT_UNKNOWN]       = BTRFS_FT_UNKNOWN,
529         [EXT2_FT_REG_FILE]      = BTRFS_FT_REG_FILE,
530         [EXT2_FT_DIR]           = BTRFS_FT_DIR,
531         [EXT2_FT_CHRDEV]        = BTRFS_FT_CHRDEV,
532         [EXT2_FT_BLKDEV]        = BTRFS_FT_BLKDEV,
533         [EXT2_FT_FIFO]          = BTRFS_FT_FIFO,
534         [EXT2_FT_SOCK]          = BTRFS_FT_SOCK,
535         [EXT2_FT_SYMLINK]       = BTRFS_FT_SYMLINK,
536 };
537
538 static int dir_iterate_proc(ext2_ino_t dir, int entry,
539                             struct ext2_dir_entry *dirent,
540                             int offset, int blocksize,
541                             char *buf,void *priv_data)
542 {
543         int ret;
544         int file_type;
545         u64 objectid;
546         char dotdot[] = "..";
547         struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
548         int name_len;
549
550         name_len = dirent->name_len & 0xFF;
551
552         objectid = dirent->inode + INO_OFFSET;
553         if (!strncmp(dirent->name, dotdot, name_len)) {
554                 if (name_len == 2) {
555                         BUG_ON(idata->parent != 0);
556                         idata->parent = objectid;
557                 }
558                 return 0;
559         }
560         if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
561                 return 0;
562
563         file_type = dirent->name_len >> 8;
564         BUG_ON(file_type > EXT2_FT_SYMLINK);
565
566         ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
567                                     name_len, idata->objectid, objectid,
568                                     filetype_conversion_table[file_type],
569                                     idata->index_cnt, idata->inode);
570         if (ret < 0) {
571                 idata->errcode = ret;
572                 return BLOCK_ABORT;
573         }
574
575         idata->index_cnt++;
576         return 0;
577 }
578
579 static int create_dir_entries(struct btrfs_trans_handle *trans,
580                               struct btrfs_root *root, u64 objectid,
581                               struct btrfs_inode_item *btrfs_inode,
582                               ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
583 {
584         int ret;
585         errcode_t err;
586         struct dir_iterate_data data = {
587                 .trans          = trans,
588                 .root           = root,
589                 .inode          = btrfs_inode,
590                 .objectid       = objectid,
591                 .index_cnt      = 2,
592                 .parent         = 0,
593                 .errcode        = 0,
594         };
595
596         err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
597                                   dir_iterate_proc, &data);
598         if (err)
599                 goto error;
600         ret = data.errcode;
601         if (ret == 0 && data.parent == objectid) {
602                 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
603                                              objectid, objectid, 0);
604         }
605         return ret;
606 error:
607         fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
608         return -1;
609 }
610
611 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
612                             u32 num_bytes, char *buffer)
613 {
614         int ret;
615         struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
616
617         ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
618         if (ret != num_bytes)
619                 goto fail;
620         ret = 0;
621 fail:
622         if (ret > 0)
623                 ret = -1;
624         return ret;
625 }
626
627 static int csum_disk_extent(struct btrfs_trans_handle *trans,
628                             struct btrfs_root *root,
629                             u64 disk_bytenr, u64 num_bytes)
630 {
631         u32 blocksize = root->sectorsize;
632         u64 offset;
633         char *buffer;
634         int ret = 0;
635
636         buffer = malloc(blocksize);
637         if (!buffer)
638                 return -ENOMEM;
639         for (offset = 0; offset < num_bytes; offset += blocksize) {
640                 ret = read_disk_extent(root, disk_bytenr + offset,
641                                         blocksize, buffer);
642                 if (ret)
643                         break;
644                 ret = btrfs_csum_file_block(trans,
645                                             root->fs_info->csum_root,
646                                             disk_bytenr + num_bytes,
647                                             disk_bytenr + offset,
648                                             buffer, blocksize);
649                 if (ret)
650                         break;
651         }
652         free(buffer);
653         return ret;
654 }
655
656 struct blk_iterate_data {
657         struct btrfs_trans_handle *trans;
658         struct btrfs_root *root;
659         struct btrfs_inode_item *inode;
660         u64 objectid;
661         u64 first_block;
662         u64 disk_block;
663         u64 num_blocks;
664         u64 boundary;
665         int checksum;
666         int errcode;
667 };
668
669 static void init_blk_iterate_data(struct blk_iterate_data *data,
670                                   struct btrfs_trans_handle *trans,
671                                   struct btrfs_root *root,
672                                   struct btrfs_inode_item *inode,
673                                   u64 objectid, int checksum)
674 {
675         data->trans             = trans;
676         data->root              = root;
677         data->inode             = inode;
678         data->objectid          = objectid;
679         data->first_block       = 0;
680         data->disk_block        = 0;
681         data->num_blocks        = 0;
682         data->boundary          = (u64)-1;
683         data->checksum          = checksum;
684         data->errcode           = 0;
685 }
686
687 static int record_file_blocks(struct blk_iterate_data *data,
688                               u64 file_block, u64 disk_block, u64 num_blocks)
689 {
690         int ret;
691         struct btrfs_root *root = data->root;
692         u64 file_pos = file_block * root->sectorsize;
693         u64 disk_bytenr = disk_block * root->sectorsize;
694         u64 num_bytes = num_blocks * root->sectorsize;
695         ret = btrfs_record_file_extent(data->trans, data->root,
696                                        data->objectid, data->inode, file_pos,
697                                        disk_bytenr, num_bytes);
698
699         if (ret || !data->checksum || disk_bytenr == 0)
700                 return ret;
701
702         return csum_disk_extent(data->trans, data->root, disk_bytenr,
703                                 num_bytes);
704 }
705
706 static int block_iterate_proc(u64 disk_block, u64 file_block,
707                               struct blk_iterate_data *idata)
708 {
709         int ret = 0;
710         int sb_region;
711         int do_barrier;
712         struct btrfs_root *root = idata->root;
713         struct btrfs_block_group_cache *cache;
714         u64 bytenr = disk_block * root->sectorsize;
715
716         sb_region = intersect_with_sb(bytenr, root->sectorsize);
717         do_barrier = sb_region || disk_block >= idata->boundary;
718         if ((idata->num_blocks > 0 && do_barrier) ||
719             (file_block > idata->first_block + idata->num_blocks) ||
720             (disk_block != idata->disk_block + idata->num_blocks)) {
721                 if (idata->num_blocks > 0) {
722                         ret = record_file_blocks(idata, idata->first_block,
723                                                  idata->disk_block,
724                                                  idata->num_blocks);
725                         if (ret)
726                                 goto fail;
727                         idata->first_block += idata->num_blocks;
728                         idata->num_blocks = 0;
729                 }
730                 if (file_block > idata->first_block) {
731                         ret = record_file_blocks(idata, idata->first_block,
732                                         0, file_block - idata->first_block);
733                         if (ret)
734                                 goto fail;
735                 }
736
737                 if (sb_region) {
738                         bytenr += BTRFS_STRIPE_LEN - 1;
739                         bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
740                 } else {
741                         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
742                         BUG_ON(!cache);
743                         bytenr = cache->key.objectid + cache->key.offset;
744                 }
745
746                 idata->first_block = file_block;
747                 idata->disk_block = disk_block;
748                 idata->boundary = bytenr / root->sectorsize;
749         }
750         idata->num_blocks++;
751 fail:
752         return ret;
753 }
754
755 static int __block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
756                                 e2_blkcnt_t blockcnt, blk_t ref_block,
757                                 int ref_offset, void *priv_data)
758 {
759         int ret;
760         struct blk_iterate_data *idata;
761         idata = (struct blk_iterate_data *)priv_data;
762         ret = block_iterate_proc(*blocknr, blockcnt, idata);
763         if (ret) {
764                 idata->errcode = ret;
765                 return BLOCK_ABORT;
766         }
767         return 0;
768 }
769
770 /*
771  * traverse file's data blocks, record these data blocks as file extents.
772  */
773 static int create_file_extents(struct btrfs_trans_handle *trans,
774                                struct btrfs_root *root, u64 objectid,
775                                struct btrfs_inode_item *btrfs_inode,
776                                ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
777                                int datacsum, int packing)
778 {
779         int ret;
780         char *buffer = NULL;
781         errcode_t err;
782         u32 last_block;
783         u32 sectorsize = root->sectorsize;
784         u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
785         struct blk_iterate_data data;
786
787         init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
788                               datacsum);
789
790         err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
791                                     NULL, __block_iterate_proc, &data);
792         if (err)
793                 goto error;
794         ret = data.errcode;
795         if (ret)
796                 goto fail;
797         if (packing && data.first_block == 0 && data.num_blocks > 0 &&
798             inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
799                 u64 num_bytes = data.num_blocks * sectorsize;
800                 u64 disk_bytenr = data.disk_block * sectorsize;
801                 u64 nbytes;
802
803                 buffer = malloc(num_bytes);
804                 if (!buffer)
805                         return -ENOMEM;
806                 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
807                 if (ret)
808                         goto fail;
809                 if (num_bytes > inode_size)
810                         num_bytes = inode_size;
811                 ret = btrfs_insert_inline_extent(trans, root, objectid,
812                                                  0, buffer, num_bytes);
813                 if (ret)
814                         goto fail;
815                 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
816                 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
817         } else if (data.num_blocks > 0) {
818                 ret = record_file_blocks(&data, data.first_block,
819                                          data.disk_block, data.num_blocks);
820                 if (ret)
821                         goto fail;
822         }
823         data.first_block += data.num_blocks;
824         last_block = (inode_size + sectorsize - 1) / sectorsize;
825         if (last_block > data.first_block) {
826                 ret = record_file_blocks(&data, data.first_block, 0,
827                                          last_block - data.first_block);
828         }
829 fail:
830         free(buffer);
831         return ret;
832 error:
833         fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
834         return -1;
835 }
836
837 static int create_symbol_link(struct btrfs_trans_handle *trans,
838                               struct btrfs_root *root, u64 objectid,
839                               struct btrfs_inode_item *btrfs_inode,
840                               ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
841                               struct ext2_inode *ext2_inode)
842 {
843         int ret;
844         char *pathname;
845         u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
846         if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
847                 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
848                 ret = create_file_extents(trans, root, objectid, btrfs_inode,
849                                           ext2_fs, ext2_ino, 1, 1);
850                 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
851                 return ret;
852         }
853
854         pathname = (char *)&(ext2_inode->i_block[0]);
855         BUG_ON(pathname[inode_size] != 0);
856         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
857                                          pathname, inode_size + 1);
858         btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
859         return ret;
860 }
861
862 /*
863  * Following xattr/acl related codes are based on codes in
864  * fs/ext3/xattr.c and fs/ext3/acl.c
865  */
866 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
867 #define EXT2_XATTR_BFIRST(ptr) \
868         ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
869 #define EXT2_XATTR_IHDR(inode) \
870         ((struct ext2_ext_attr_header *) ((void *)(inode) + \
871                 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
872 #define EXT2_XATTR_IFIRST(inode) \
873         ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
874                 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
875
876 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
877                                   const void *end)
878 {
879         struct ext2_ext_attr_entry *next;
880
881         while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
882                 next = EXT2_EXT_ATTR_NEXT(entry);
883                 if ((void *)next >= end)
884                         return -EIO;
885                 entry = next;
886         }
887         return 0;
888 }
889
890 static int ext2_xattr_check_block(const char *buf, size_t size)
891 {
892         int error;
893         struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
894
895         if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
896             header->h_blocks != 1)
897                 return -EIO;
898         error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
899         return error;
900 }
901
902 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
903                                   size_t size)
904 {
905         size_t value_size = entry->e_value_size;
906
907         if (entry->e_value_block != 0 || value_size > size ||
908             entry->e_value_offs + value_size > size)
909                 return -EIO;
910         return 0;
911 }
912
913 #define EXT2_ACL_VERSION        0x0001
914
915 /* 23.2.5 acl_tag_t values */
916
917 #define ACL_UNDEFINED_TAG       (0x00)
918 #define ACL_USER_OBJ            (0x01)
919 #define ACL_USER                (0x02)
920 #define ACL_GROUP_OBJ           (0x04)
921 #define ACL_GROUP               (0x08)
922 #define ACL_MASK                (0x10)
923 #define ACL_OTHER               (0x20)
924
925 /* 23.2.7 ACL qualifier constants */
926
927 #define ACL_UNDEFINED_ID        ((id_t)-1)
928
929 typedef struct {
930         __le16          e_tag;
931         __le16          e_perm;
932         __le32          e_id;
933 } ext2_acl_entry;
934
935 typedef struct {
936         __le16          e_tag;
937         __le16          e_perm;
938 } ext2_acl_entry_short;
939
940 typedef struct {
941         __le32          a_version;
942 } ext2_acl_header;
943
944 static inline int ext2_acl_count(size_t size)
945 {
946         ssize_t s;
947         size -= sizeof(ext2_acl_header);
948         s = size - 4 * sizeof(ext2_acl_entry_short);
949         if (s < 0) {
950                 if (size % sizeof(ext2_acl_entry_short))
951                         return -1;
952                 return size / sizeof(ext2_acl_entry_short);
953         } else {
954                 if (s % sizeof(ext2_acl_entry))
955                         return -1;
956                 return s / sizeof(ext2_acl_entry) + 4;
957         }
958 }
959
960 #define ACL_EA_VERSION          0x0002
961
962 typedef struct {
963         __le16          e_tag;
964         __le16          e_perm;
965         __le32          e_id;
966 } acl_ea_entry;
967
968 typedef struct {
969         __le32          a_version;
970         acl_ea_entry    a_entries[0];
971 } acl_ea_header;
972
973 static inline size_t acl_ea_size(int count)
974 {
975         return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
976 }
977
978 static int ext2_acl_to_xattr(void *dst, const void *src,
979                              size_t dst_size, size_t src_size)
980 {
981         int i, count;
982         const void *end = src + src_size;
983         acl_ea_header *ext_acl = (acl_ea_header *)dst;
984         acl_ea_entry *dst_entry = ext_acl->a_entries;
985         ext2_acl_entry *src_entry;
986
987         if (src_size < sizeof(ext2_acl_header))
988                 goto fail;
989         if (((ext2_acl_header *)src)->a_version !=
990             cpu_to_le32(EXT2_ACL_VERSION))
991                 goto fail;
992         src += sizeof(ext2_acl_header);
993         count = ext2_acl_count(src_size);
994         if (count <= 0)
995                 goto fail;
996
997         BUG_ON(dst_size < acl_ea_size(count));
998         ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
999         for (i = 0; i < count; i++, dst_entry++) {
1000                 src_entry = (ext2_acl_entry *)src;
1001                 if (src + sizeof(ext2_acl_entry_short) > end)
1002                         goto fail;
1003                 dst_entry->e_tag = src_entry->e_tag;
1004                 dst_entry->e_perm = src_entry->e_perm;
1005                 switch (le16_to_cpu(src_entry->e_tag)) {
1006                 case ACL_USER_OBJ:
1007                 case ACL_GROUP_OBJ:
1008                 case ACL_MASK:
1009                 case ACL_OTHER:
1010                         src += sizeof(ext2_acl_entry_short);
1011                         dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
1012                         break;
1013                 case ACL_USER:
1014                 case ACL_GROUP:
1015                         src += sizeof(ext2_acl_entry);
1016                         if (src > end)
1017                                 goto fail;
1018                         dst_entry->e_id = src_entry->e_id;
1019                         break;
1020                 default:
1021                         goto fail;
1022                 }
1023         }
1024         if (src != end)
1025                 goto fail;
1026         return 0;
1027 fail:
1028         return -EINVAL;
1029 }
1030
1031 static char *xattr_prefix_table[] = {
1032         [1] =   "user.",
1033         [2] =   "system.posix_acl_access",
1034         [3] =   "system.posix_acl_default",
1035         [4] =   "trusted.",
1036         [6] =   "security.",
1037 };
1038
1039 static int copy_single_xattr(struct btrfs_trans_handle *trans,
1040                              struct btrfs_root *root, u64 objectid,
1041                              struct ext2_ext_attr_entry *entry,
1042                              const void *data, u32 datalen)
1043 {
1044         int ret = 0;
1045         int name_len;
1046         int name_index;
1047         void *databuf = NULL;
1048         char namebuf[XATTR_NAME_MAX + 1];
1049
1050         name_index = entry->e_name_index;
1051         if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
1052             xattr_prefix_table[name_index] == NULL)
1053                 return -EOPNOTSUPP;
1054         name_len = strlen(xattr_prefix_table[name_index]) +
1055                    entry->e_name_len;
1056         if (name_len >= sizeof(namebuf))
1057                 return -ERANGE;
1058
1059         if (name_index == 2 || name_index == 3) {
1060                 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
1061                 databuf = malloc(bufsize);
1062                 if (!databuf)
1063                        return -ENOMEM;
1064                 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
1065                 if (ret)
1066                         goto out;
1067                 data = databuf;
1068                 datalen = bufsize;
1069         }
1070         strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
1071         strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
1072         if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
1073             sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
1074                 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
1075                         objectid - INO_OFFSET, name_len, namebuf);
1076                 goto out;
1077         }
1078         ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
1079                                       data, datalen, objectid);
1080 out:
1081         free(databuf);
1082         return ret;
1083 }
1084
1085 static int copy_extended_attrs(struct btrfs_trans_handle *trans,
1086                                struct btrfs_root *root, u64 objectid,
1087                                struct btrfs_inode_item *btrfs_inode,
1088                                ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
1089 {
1090         int ret = 0;
1091         int inline_ea = 0;
1092         errcode_t err;
1093         u32 datalen;
1094         u32 block_size = ext2_fs->blocksize;
1095         u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
1096         struct ext2_inode_large *ext2_inode;
1097         struct ext2_ext_attr_entry *entry;
1098         void *data;
1099         char *buffer = NULL;
1100         char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
1101
1102         if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
1103                 ext2_inode = (struct ext2_inode_large *)inode_buf;
1104         } else {
1105                 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
1106                 if (!ext2_inode)
1107                        return -ENOMEM;
1108         }
1109         err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
1110                                      inode_size);
1111         if (err) {
1112                 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
1113                         error_message(err));
1114                 ret = -1;
1115                 goto out;
1116         }
1117
1118         if (ext2_ino > ext2_fs->super->s_first_ino &&
1119             inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
1120                 if (EXT2_GOOD_OLD_INODE_SIZE +
1121                     ext2_inode->i_extra_isize > inode_size) {
1122                         ret = -EIO;
1123                         goto out;
1124                 }
1125                 if (ext2_inode->i_extra_isize != 0 &&
1126                     EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
1127                     EXT2_EXT_ATTR_MAGIC) {
1128                         inline_ea = 1;
1129                 }
1130         }
1131         if (inline_ea) {
1132                 int total;
1133                 void *end = (void *)ext2_inode + inode_size;
1134                 entry = EXT2_XATTR_IFIRST(ext2_inode);
1135                 total = end - (void *)entry;
1136                 ret = ext2_xattr_check_names(entry, end);
1137                 if (ret)
1138                         goto out;
1139                 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1140                         ret = ext2_xattr_check_entry(entry, total);
1141                         if (ret)
1142                                 goto out;
1143                         data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
1144                                 entry->e_value_offs;
1145                         datalen = entry->e_value_size;
1146                         ret = copy_single_xattr(trans, root, objectid,
1147                                                 entry, data, datalen);
1148                         if (ret)
1149                                 goto out;
1150                         entry = EXT2_EXT_ATTR_NEXT(entry);
1151                 }
1152         }
1153
1154         if (ext2_inode->i_file_acl == 0)
1155                 goto out;
1156
1157         buffer = malloc(block_size);
1158         if (!buffer) {
1159                 ret = -ENOMEM;
1160                 goto out;
1161         }
1162         err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
1163         if (err) {
1164                 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
1165                         error_message(err));
1166                 ret = -1;
1167                 goto out;
1168         }
1169         ret = ext2_xattr_check_block(buffer, block_size);
1170         if (ret)
1171                 goto out;
1172
1173         entry = EXT2_XATTR_BFIRST(buffer);
1174         while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1175                 ret = ext2_xattr_check_entry(entry, block_size);
1176                 if (ret)
1177                         goto out;
1178                 data = buffer + entry->e_value_offs;
1179                 datalen = entry->e_value_size;
1180                 ret = copy_single_xattr(trans, root, objectid,
1181                                         entry, data, datalen);
1182                 if (ret)
1183                         goto out;
1184                 entry = EXT2_EXT_ATTR_NEXT(entry);
1185         }
1186 out:
1187         free(buffer);
1188         if ((void *)ext2_inode != inode_buf)
1189                 free(ext2_inode);
1190         return ret;
1191 }
1192 #define MINORBITS       20
1193 #define MKDEV(ma, mi)   (((ma) << MINORBITS) | (mi))
1194
1195 static inline dev_t old_decode_dev(u16 val)
1196 {
1197         return MKDEV((val >> 8) & 255, val & 255);
1198 }
1199
1200 static inline dev_t new_decode_dev(u32 dev)
1201 {
1202         unsigned major = (dev & 0xfff00) >> 8;
1203         unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
1204         return MKDEV(major, minor);
1205 }
1206
1207 static int copy_inode_item(struct btrfs_inode_item *dst,
1208                            struct ext2_inode *src, u32 blocksize)
1209 {
1210         btrfs_set_stack_inode_generation(dst, 1);
1211         btrfs_set_stack_inode_sequence(dst, 0);
1212         btrfs_set_stack_inode_transid(dst, 1);
1213         btrfs_set_stack_inode_size(dst, src->i_size);
1214         btrfs_set_stack_inode_nbytes(dst, 0);
1215         btrfs_set_stack_inode_block_group(dst, 0);
1216         btrfs_set_stack_inode_nlink(dst, src->i_links_count);
1217         btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
1218         btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
1219         btrfs_set_stack_inode_mode(dst, src->i_mode);
1220         btrfs_set_stack_inode_rdev(dst, 0);
1221         btrfs_set_stack_inode_flags(dst, 0);
1222         btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
1223         btrfs_set_stack_timespec_nsec(&dst->atime, 0);
1224         btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
1225         btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
1226         btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
1227         btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
1228         btrfs_set_stack_timespec_sec(&dst->otime, 0);
1229         btrfs_set_stack_timespec_nsec(&dst->otime, 0);
1230
1231         if (S_ISDIR(src->i_mode)) {
1232                 btrfs_set_stack_inode_size(dst, 0);
1233                 btrfs_set_stack_inode_nlink(dst, 1);
1234         }
1235         if (S_ISREG(src->i_mode)) {
1236                 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
1237                                            (u64)src->i_size);
1238         }
1239         if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
1240             !S_ISLNK(src->i_mode)) {
1241                 if (src->i_block[0]) {
1242                         btrfs_set_stack_inode_rdev(dst,
1243                                 old_decode_dev(src->i_block[0]));
1244                 } else {
1245                         btrfs_set_stack_inode_rdev(dst,
1246                                 new_decode_dev(src->i_block[1]));
1247                 }
1248         }
1249         memset(&dst->reserved, 0, sizeof(dst->reserved));
1250
1251         return 0;
1252 }
1253
1254 /*
1255  * copy a single inode. do all the required works, such as cloning
1256  * inode item, creating file extents and creating directory entries.
1257  */
1258 static int copy_single_inode(struct btrfs_trans_handle *trans,
1259                              struct btrfs_root *root, u64 objectid,
1260                              ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1261                              struct ext2_inode *ext2_inode,
1262                              int datacsum, int packing, int noxattr)
1263 {
1264         int ret;
1265         struct btrfs_inode_item btrfs_inode;
1266
1267         if (ext2_inode->i_links_count == 0)
1268                 return 0;
1269
1270         copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
1271         if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
1272                 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
1273                             BTRFS_INODE_NODATASUM;
1274                 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
1275         }
1276
1277         switch (ext2_inode->i_mode & S_IFMT) {
1278         case S_IFREG:
1279                 ret = create_file_extents(trans, root, objectid, &btrfs_inode,
1280                                         ext2_fs, ext2_ino, datacsum, packing);
1281                 break;
1282         case S_IFDIR:
1283                 ret = create_dir_entries(trans, root, objectid, &btrfs_inode,
1284                                          ext2_fs, ext2_ino);
1285                 break;
1286         case S_IFLNK:
1287                 ret = create_symbol_link(trans, root, objectid, &btrfs_inode,
1288                                          ext2_fs, ext2_ino, ext2_inode);
1289                 break;
1290         default:
1291                 ret = 0;
1292                 break;
1293         }
1294         if (ret)
1295                 return ret;
1296
1297         if (!noxattr) {
1298                 ret = copy_extended_attrs(trans, root, objectid, &btrfs_inode,
1299                                           ext2_fs, ext2_ino);
1300                 if (ret)
1301                         return ret;
1302         }
1303         return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
1304 }
1305
1306 static int copy_disk_extent(struct btrfs_root *root, u64 dst_bytenr,
1307                             u64 src_bytenr, u32 num_bytes)
1308 {
1309         int ret;
1310         char *buffer;
1311         struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
1312
1313         buffer = malloc(num_bytes);
1314         if (!buffer)
1315                 return -ENOMEM;
1316         ret = pread(fs_devs->latest_bdev, buffer, num_bytes, src_bytenr);
1317         if (ret != num_bytes)
1318                 goto fail;
1319         ret = pwrite(fs_devs->latest_bdev, buffer, num_bytes, dst_bytenr);
1320         if (ret != num_bytes)
1321                 goto fail;
1322         ret = 0;
1323 fail:
1324         free(buffer);
1325         if (ret > 0)
1326                 ret = -1;
1327         return ret;
1328 }
1329 /*
1330  * scan ext2's inode bitmap and copy all used inodes.
1331  */
1332 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
1333                             struct btrfs_root *root,
1334                             int datacsum, int packing, int noxattr, struct task_ctx *p)
1335 {
1336         ext2_filsys ext2_fs = cctx->fs_data;
1337         int ret;
1338         errcode_t err;
1339         ext2_inode_scan ext2_scan;
1340         struct ext2_inode ext2_inode;
1341         ext2_ino_t ext2_ino;
1342         u64 objectid;
1343         struct btrfs_trans_handle *trans;
1344
1345         trans = btrfs_start_transaction(root, 1);
1346         if (!trans)
1347                 return -ENOMEM;
1348         err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
1349         if (err) {
1350                 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
1351                 return -1;
1352         }
1353         while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
1354                                              &ext2_inode))) {
1355                 /* no more inodes */
1356                 if (ext2_ino == 0)
1357                         break;
1358                 /* skip special inode in ext2fs */
1359                 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
1360                     ext2_ino != EXT2_ROOT_INO)
1361                         continue;
1362                 objectid = ext2_ino + INO_OFFSET;
1363                 ret = copy_single_inode(trans, root,
1364                                         objectid, ext2_fs, ext2_ino,
1365                                         &ext2_inode, datacsum, packing,
1366                                         noxattr);
1367                 p->cur_copy_inodes++;
1368                 if (ret)
1369                         return ret;
1370                 if (trans->blocks_used >= 4096) {
1371                         ret = btrfs_commit_transaction(trans, root);
1372                         BUG_ON(ret);
1373                         trans = btrfs_start_transaction(root, 1);
1374                         BUG_ON(!trans);
1375                 }
1376         }
1377         if (err) {
1378                 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
1379                 return -1;
1380         }
1381         ret = btrfs_commit_transaction(trans, root);
1382         BUG_ON(ret);
1383         ext2fs_close_inode_scan(ext2_scan);
1384
1385         return ret;
1386 }
1387
1388 static int ext2_test_block(struct btrfs_convert_context *cctx, u64 block)
1389 {
1390         ext2_filsys ext2_fs = cctx->fs_data;
1391
1392         BUG_ON(block != (u32)block);
1393         return ext2fs_fast_test_block_bitmap(ext2_fs->block_map, block);
1394 }
1395
1396 /*
1397  * Construct a range of ext2fs image file.
1398  * scan block allocation bitmap, find all blocks used by the ext2fs
1399  * in this range and create file extents that point to these blocks.
1400  *
1401  * Note: Before calling the function, no file extent points to blocks
1402  *       in this range
1403  */
1404 static int create_image_file_range(struct btrfs_trans_handle *trans,
1405                                    struct btrfs_root *root, u64 objectid,
1406                                    struct btrfs_inode_item *inode,
1407                                    u64 start_byte, u64 end_byte,
1408                                    struct btrfs_convert_context *cctx, int datacsum)
1409 {
1410         u32 blocksize = cctx->blocksize;
1411         u32 block = start_byte / blocksize;
1412         u32 last_block = (end_byte + blocksize - 1) / blocksize;
1413         int ret = 0;
1414         struct blk_iterate_data data;
1415
1416         init_blk_iterate_data(&data, trans, root, inode, objectid, datacsum);
1417         data.first_block = block;
1418
1419         for (; start_byte < end_byte; block++, start_byte += blocksize) {
1420                 if (!convert_test_block(cctx, block))
1421                         continue;
1422                 ret = block_iterate_proc(block, block, &data);
1423                 if (ret < 0)
1424                         goto fail;
1425         }
1426         if (data.num_blocks > 0) {
1427                 ret = record_file_blocks(&data, data.first_block,
1428                                          data.disk_block, data.num_blocks);
1429                 if (ret)
1430                         goto fail;
1431                 data.first_block += data.num_blocks;
1432         }
1433         if (last_block > data.first_block) {
1434                 ret = record_file_blocks(&data, data.first_block, 0,
1435                                          last_block - data.first_block);
1436                 if (ret)
1437                         goto fail;
1438         }
1439 fail:
1440         return ret;
1441 }
1442
1443 /*
1444  * Create the fs image file.
1445  */
1446 static int create_image(struct btrfs_convert_context *cctx,
1447                         struct btrfs_root *root, const char *name, int datacsum)
1448 {
1449         int ret;
1450         struct btrfs_key key;
1451         struct btrfs_key location;
1452         struct btrfs_path path;
1453         struct btrfs_inode_item btrfs_inode;
1454         struct btrfs_inode_item *inode_item;
1455         struct extent_buffer *leaf;
1456         struct btrfs_fs_info *fs_info = root->fs_info;
1457         struct btrfs_root *extent_root = fs_info->extent_root;
1458         struct btrfs_trans_handle *trans;
1459         struct btrfs_extent_item *ei;
1460         struct btrfs_extent_inline_ref *iref;
1461         struct btrfs_extent_data_ref *dref;
1462         u64 bytenr;
1463         u64 num_bytes;
1464         u64 objectid;
1465         u64 last_byte;
1466         u64 first_free;
1467         u64 total_bytes;
1468         u64 flags = BTRFS_INODE_READONLY;
1469         u32 sectorsize = root->sectorsize;
1470
1471         total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
1472         first_free =  BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
1473         first_free &= ~((u64)sectorsize - 1);
1474         if (!datacsum)
1475                 flags |= BTRFS_INODE_NODATASUM;
1476
1477         memset(&btrfs_inode, 0, sizeof(btrfs_inode));
1478         btrfs_set_stack_inode_generation(&btrfs_inode, 1);
1479         btrfs_set_stack_inode_size(&btrfs_inode, total_bytes);
1480         btrfs_set_stack_inode_nlink(&btrfs_inode, 1);
1481         btrfs_set_stack_inode_nbytes(&btrfs_inode, 0);
1482         btrfs_set_stack_inode_mode(&btrfs_inode, S_IFREG | 0400);
1483         btrfs_set_stack_inode_flags(&btrfs_inode,  flags);
1484         btrfs_init_path(&path);
1485         trans = btrfs_start_transaction(root, 1);
1486         BUG_ON(!trans);
1487
1488         objectid = btrfs_root_dirid(&root->root_item);
1489         ret = btrfs_find_free_objectid(trans, root, objectid, &objectid);
1490         if (ret)
1491                 goto fail;
1492
1493         /*
1494          * copy blocks covered by extent #0 to new positions. extent #0 is
1495          * special, we can't rely on relocate_extents_range to relocate it.
1496          */
1497         for (last_byte = 0; last_byte < first_free; last_byte += sectorsize) {
1498                 ret = custom_alloc_extent(root, sectorsize, 0, &key, 0);
1499                 if (ret)
1500                         goto fail;
1501                 ret = copy_disk_extent(root, key.objectid, last_byte,
1502                                        sectorsize);
1503                 if (ret)
1504                         goto fail;
1505                 ret = btrfs_record_file_extent(trans, root, objectid,
1506                                                &btrfs_inode, last_byte,
1507                                                key.objectid, sectorsize);
1508                 if (ret)
1509                         goto fail;
1510                 if (datacsum) {
1511                         ret = csum_disk_extent(trans, root, key.objectid,
1512                                                sectorsize);
1513                         if (ret)
1514                                 goto fail;
1515                 }
1516         }
1517
1518         while(1) {
1519                 key.objectid = last_byte;
1520                 key.offset = 0;
1521                 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1522                 ret = btrfs_search_slot(trans, fs_info->extent_root,
1523                                         &key, &path, 0, 0);
1524                 if (ret < 0)
1525                         goto fail;
1526 next:
1527                 leaf = path.nodes[0];
1528                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1529                         ret = btrfs_next_leaf(extent_root, &path);
1530                         if (ret < 0)
1531                                 goto fail;
1532                         if (ret > 0)
1533                                 break;
1534                         leaf = path.nodes[0];
1535                 }
1536                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1537                 if (last_byte > key.objectid ||
1538                     key.type != BTRFS_EXTENT_ITEM_KEY) {
1539                         path.slots[0]++;
1540                         goto next;
1541                 }
1542
1543                 bytenr = key.objectid;
1544                 num_bytes = key.offset;
1545                 ei = btrfs_item_ptr(leaf, path.slots[0],
1546                                     struct btrfs_extent_item);
1547                 if (!(btrfs_extent_flags(leaf, ei) & BTRFS_EXTENT_FLAG_DATA)) {
1548                         path.slots[0]++;
1549                         goto next;
1550                 }
1551
1552                 BUG_ON(btrfs_item_size_nr(leaf, path.slots[0]) != sizeof(*ei) +
1553                        btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY));
1554
1555                 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
1556                 key.type = btrfs_extent_inline_ref_type(leaf, iref);
1557                 BUG_ON(key.type != BTRFS_EXTENT_DATA_REF_KEY);
1558                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1559                 if (btrfs_extent_data_ref_root(leaf, dref) !=
1560                     BTRFS_FS_TREE_OBJECTID) {
1561                         path.slots[0]++;
1562                         goto next;
1563                 }
1564
1565                 if (bytenr > last_byte) {
1566                         ret = create_image_file_range(trans, root, objectid,
1567                                                       &btrfs_inode, last_byte,
1568                                                       bytenr, cctx,
1569                                                       datacsum);
1570                         if (ret)
1571                                 goto fail;
1572                 }
1573                 ret = btrfs_record_file_extent(trans, root, objectid,
1574                                                &btrfs_inode, bytenr, bytenr,
1575                                                num_bytes);
1576                 if (ret)
1577                         goto fail;
1578                 last_byte = bytenr + num_bytes;
1579                 btrfs_release_path(&path);
1580
1581                 if (trans->blocks_used >= 4096) {
1582                         ret = btrfs_commit_transaction(trans, root);
1583                         BUG_ON(ret);
1584                         trans = btrfs_start_transaction(root, 1);
1585                         BUG_ON(!trans);
1586                 }
1587         }
1588         btrfs_release_path(&path);
1589         if (total_bytes > last_byte) {
1590                 ret = create_image_file_range(trans, root, objectid,
1591                                               &btrfs_inode, last_byte,
1592                                               total_bytes, cctx,
1593                                               datacsum);
1594                 if (ret)
1595                         goto fail;
1596         }
1597
1598         ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
1599         if (ret)
1600                 goto fail;
1601
1602         location.objectid = objectid;
1603         location.offset = 0;
1604         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
1605         ret = btrfs_insert_dir_item(trans, root, name, strlen(name),
1606                                     btrfs_root_dirid(&root->root_item),
1607                                     &location, BTRFS_FT_REG_FILE, objectid);
1608         if (ret)
1609                 goto fail;
1610         ret = btrfs_insert_inode_ref(trans, root, name, strlen(name),
1611                                      objectid,
1612                                      btrfs_root_dirid(&root->root_item),
1613                                      objectid);
1614         if (ret)
1615                 goto fail;
1616         location.objectid = btrfs_root_dirid(&root->root_item);
1617         location.offset = 0;
1618         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
1619         ret = btrfs_lookup_inode(trans, root, &path, &location, 1);
1620         if (ret)
1621                 goto fail;
1622         leaf = path.nodes[0];
1623         inode_item = btrfs_item_ptr(leaf, path.slots[0],
1624                                     struct btrfs_inode_item);
1625         btrfs_set_inode_size(leaf, inode_item, strlen(name) * 2 +
1626                              btrfs_inode_size(leaf, inode_item));
1627         btrfs_mark_buffer_dirty(leaf);
1628         btrfs_release_path(&path);
1629         ret = btrfs_commit_transaction(trans, root);
1630         BUG_ON(ret);
1631 fail:
1632         btrfs_release_path(&path);
1633         return ret;
1634 }
1635
1636 static int create_image_file_range_v2(struct btrfs_trans_handle *trans,
1637                                       struct btrfs_root *root,
1638                                       struct cache_tree *used,
1639                                       struct btrfs_inode_item *inode,
1640                                       u64 ino, u64 bytenr, u64 *ret_len,
1641                                       int datacsum)
1642 {
1643         struct cache_extent *cache;
1644         struct btrfs_block_group_cache *bg_cache;
1645         u64 len = *ret_len;
1646         u64 disk_bytenr;
1647         int ret;
1648
1649         BUG_ON(bytenr != round_down(bytenr, root->sectorsize));
1650         BUG_ON(len != round_down(len, root->sectorsize));
1651         len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
1652
1653         cache = search_cache_extent(used, bytenr);
1654         if (cache) {
1655                 if (cache->start <= bytenr) {
1656                         /*
1657                          * |///////Used///////|
1658                          *      |<--insert--->|
1659                          *      bytenr
1660                          */
1661                         len = min_t(u64, len, cache->start + cache->size -
1662                                     bytenr);
1663                         disk_bytenr = bytenr;
1664                 } else {
1665                         /*
1666                          *              |//Used//|
1667                          *  |<-insert-->|
1668                          *  bytenr
1669                          */
1670                         len = min(len, cache->start - bytenr);
1671                         disk_bytenr = 0;
1672                         datacsum = 0;
1673                 }
1674         } else {
1675                 /*
1676                  * |//Used//|           |EOF
1677                  *          |<-insert-->|
1678                  *          bytenr
1679                  */
1680                 disk_bytenr = 0;
1681                 datacsum = 0;
1682         }
1683
1684         if (disk_bytenr) {
1685                 /* Check if the range is in a data block group */
1686                 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
1687                 if (!bg_cache)
1688                         return -ENOENT;
1689                 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
1690                         return -EINVAL;
1691
1692                 /* The extent should never cross block group boundary */
1693                 len = min_t(u64, len, bg_cache->key.objectid +
1694                             bg_cache->key.offset - bytenr);
1695         }
1696
1697         BUG_ON(len != round_down(len, root->sectorsize));
1698         ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
1699                                        disk_bytenr, len);
1700         if (ret < 0)
1701                 return ret;
1702
1703         if (datacsum)
1704                 ret = csum_disk_extent(trans, root, bytenr, len);
1705         *ret_len = len;
1706         return ret;
1707 }
1708
1709 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
1710                                 int ensure_size);
1711
1712 /*
1713  * Create the fs image file of old filesystem.
1714  *
1715  * This is completely fs independent as we have cctx->used, only
1716  * need to create file extents pointing to all the positions.
1717  * TODO: Add handler for reserved ranges in next patch
1718  */
1719 static int create_image_v2(struct btrfs_root *root,
1720                            struct btrfs_mkfs_config *cfg,
1721                            struct btrfs_convert_context *cctx,
1722                            u64 size, char *name, int datacsum)
1723 {
1724         struct btrfs_inode_item buf;
1725         struct btrfs_trans_handle *trans;
1726         struct btrfs_path *path = NULL;
1727         struct btrfs_key key;
1728         struct cache_extent *cache;
1729         struct cache_tree used_tmp;
1730         u64 cur;
1731         u64 ino;
1732         int ret;
1733
1734         trans = btrfs_start_transaction(root, 1);
1735         if (!trans)
1736                 return -ENOMEM;
1737
1738         cache_tree_init(&used_tmp);
1739
1740         ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
1741                                        &ino);
1742         if (ret < 0)
1743                 goto out;
1744         ret = btrfs_new_inode(trans, root, ino, 0600 | S_IFREG);
1745         if (ret < 0)
1746                 goto out;
1747         ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
1748                              strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
1749         if (ret < 0)
1750                 goto out;
1751
1752         path = btrfs_alloc_path();
1753         if (!path) {
1754                 ret = -ENOMEM;
1755                 goto out;
1756         }
1757         key.objectid = ino;
1758         key.type = BTRFS_INODE_ITEM_KEY;
1759         key.offset = 0;
1760
1761         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1762         if (ret) {
1763                 ret = (ret > 0 ? -ENOENT : ret);
1764                 goto out;
1765         }
1766         read_extent_buffer(path->nodes[0], &buf,
1767                         btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
1768                         sizeof(buf));
1769         btrfs_release_path(path);
1770
1771         /*
1772          * Create a new used space cache, which doesn't contain the reserved
1773          * range
1774          */
1775         for (cache = first_cache_extent(&cctx->used); cache;
1776              cache = next_cache_extent(cache)) {
1777                 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
1778                 if (ret < 0)
1779                         goto out;
1780         }
1781         ret = wipe_reserved_ranges(&used_tmp, 0, 0);
1782         if (ret < 0)
1783                 goto out;
1784
1785         /*
1786          * Start from 1M, as 0~1M is reserved, and create_image_file_range_v2()
1787          * can't handle bytenr 0(will consider it as a hole)
1788          */
1789         cur = 1024 * 1024;
1790         while (cur < size) {
1791                 u64 len = size - cur;
1792
1793                 ret = create_image_file_range_v2(trans, root, &used_tmp,
1794                                                 &buf, ino, cur, &len, datacsum);
1795                 if (ret < 0)
1796                         goto out;
1797                 cur += len;
1798         }
1799
1800         key.objectid = ino;
1801         key.type = BTRFS_INODE_ITEM_KEY;
1802         key.offset = 0;
1803         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1804         if (ret) {
1805                 ret = (ret > 0 ? -ENOENT : ret);
1806                 goto out;
1807         }
1808         btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
1809         write_extent_buffer(path->nodes[0], &buf,
1810                         btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
1811                         sizeof(buf));
1812 out:
1813         free_extent_cache_tree(&used_tmp);
1814         btrfs_free_path(path);
1815         btrfs_commit_transaction(trans, root);
1816         return ret;
1817 }
1818
1819 static struct btrfs_root * link_subvol(struct btrfs_root *root,
1820                 const char *base, u64 root_objectid)
1821 {
1822         struct btrfs_trans_handle *trans;
1823         struct btrfs_fs_info *fs_info = root->fs_info;
1824         struct btrfs_root *tree_root = fs_info->tree_root;
1825         struct btrfs_root *new_root = NULL;
1826         struct btrfs_path *path;
1827         struct btrfs_inode_item *inode_item;
1828         struct extent_buffer *leaf;
1829         struct btrfs_key key;
1830         u64 dirid = btrfs_root_dirid(&root->root_item);
1831         u64 index = 2;
1832         char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1833         int len;
1834         int i;
1835         int ret;
1836
1837         len = strlen(base);
1838         if (len == 0 || len > BTRFS_NAME_LEN)
1839                 return NULL;
1840
1841         path = btrfs_alloc_path();
1842         BUG_ON(!path);
1843
1844         key.objectid = dirid;
1845         key.type = BTRFS_DIR_INDEX_KEY;
1846         key.offset = (u64)-1;
1847
1848         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1849         BUG_ON(ret <= 0);
1850
1851         if (path->slots[0] > 0) {
1852                 path->slots[0]--;
1853                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1854                 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1855                         index = key.offset + 1;
1856         }
1857         btrfs_release_path(path);
1858
1859         trans = btrfs_start_transaction(root, 1);
1860         BUG_ON(!trans);
1861
1862         key.objectid = dirid;
1863         key.offset = 0;
1864         key.type =  BTRFS_INODE_ITEM_KEY;
1865
1866         ret = btrfs_lookup_inode(trans, root, path, &key, 1);
1867         BUG_ON(ret);
1868         leaf = path->nodes[0];
1869         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1870                                     struct btrfs_inode_item);
1871
1872         key.objectid = root_objectid;
1873         key.offset = (u64)-1;
1874         key.type = BTRFS_ROOT_ITEM_KEY;
1875
1876         memcpy(buf, base, len);
1877         for (i = 0; i < 1024; i++) {
1878                 ret = btrfs_insert_dir_item(trans, root, buf, len,
1879                                             dirid, &key, BTRFS_FT_DIR, index);
1880                 if (ret != -EEXIST)
1881                         break;
1882                 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1883                 if (len < 1 || len > BTRFS_NAME_LEN) {
1884                         ret = -EINVAL;
1885                         break;
1886                 }
1887         }
1888         if (ret)
1889                 goto fail;
1890
1891         btrfs_set_inode_size(leaf, inode_item, len * 2 +
1892                              btrfs_inode_size(leaf, inode_item));
1893         btrfs_mark_buffer_dirty(leaf);
1894         btrfs_release_path(path);
1895
1896         /* add the backref first */
1897         ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1898                                  BTRFS_ROOT_BACKREF_KEY,
1899                                  root->root_key.objectid,
1900                                  dirid, index, buf, len);
1901         BUG_ON(ret);
1902
1903         /* now add the forward ref */
1904         ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1905                                  BTRFS_ROOT_REF_KEY, root_objectid,
1906                                  dirid, index, buf, len);
1907
1908         ret = btrfs_commit_transaction(trans, root);
1909         BUG_ON(ret);
1910
1911         new_root = btrfs_read_fs_root(fs_info, &key);
1912         if (IS_ERR(new_root))
1913                 new_root = NULL;
1914 fail:
1915         btrfs_free_path(path);
1916         return new_root;
1917 }
1918
1919 static int create_chunk_mapping(struct btrfs_trans_handle *trans,
1920                                 struct btrfs_root *root)
1921 {
1922         struct btrfs_fs_info *info = root->fs_info;
1923         struct btrfs_root *chunk_root = info->chunk_root;
1924         struct btrfs_root *extent_root = info->extent_root;
1925         struct btrfs_device *device;
1926         struct btrfs_block_group_cache *cache;
1927         struct btrfs_dev_extent *extent;
1928         struct extent_buffer *leaf;
1929         struct btrfs_chunk chunk;
1930         struct btrfs_key key;
1931         struct btrfs_path path;
1932         u64 cur_start;
1933         u64 total_bytes;
1934         u64 chunk_objectid;
1935         int ret;
1936
1937         btrfs_init_path(&path);
1938
1939         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1940         chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1941
1942         BUG_ON(list_empty(&info->fs_devices->devices));
1943         device = list_entry(info->fs_devices->devices.next,
1944                             struct btrfs_device, dev_list);
1945         BUG_ON(device->devid != info->fs_devices->latest_devid);
1946
1947         /* delete device extent created by make_btrfs */
1948         key.objectid = device->devid;
1949         key.offset = 0;
1950         key.type = BTRFS_DEV_EXTENT_KEY;
1951         ret = btrfs_search_slot(trans, device->dev_root, &key, &path, -1, 1);
1952         if (ret < 0)
1953                 goto err;
1954
1955         BUG_ON(ret > 0);
1956         ret = btrfs_del_item(trans, device->dev_root, &path);
1957         if (ret)
1958                 goto err;
1959         btrfs_release_path(&path);
1960
1961         /* delete chunk item created by make_btrfs */
1962         key.objectid = chunk_objectid;
1963         key.offset = 0;
1964         key.type = BTRFS_CHUNK_ITEM_KEY;
1965         ret = btrfs_search_slot(trans, chunk_root, &key, &path, -1, 1);
1966         if (ret < 0)
1967                 goto err;
1968
1969         BUG_ON(ret > 0);
1970         ret = btrfs_del_item(trans, chunk_root, &path);
1971         if (ret)
1972                 goto err;
1973         btrfs_release_path(&path);
1974
1975         /* for each block group, create device extent and chunk item */
1976         cur_start = 0;
1977         while (cur_start < total_bytes) {
1978                 cache = btrfs_lookup_block_group(root->fs_info, cur_start);
1979                 BUG_ON(!cache);
1980
1981                 /* insert device extent */
1982                 key.objectid = device->devid;
1983                 key.offset = cache->key.objectid;
1984                 key.type = BTRFS_DEV_EXTENT_KEY;
1985                 ret = btrfs_insert_empty_item(trans, device->dev_root, &path,
1986                                               &key, sizeof(*extent));
1987                 if (ret)
1988                         goto err;
1989
1990                 leaf = path.nodes[0];
1991                 extent = btrfs_item_ptr(leaf, path.slots[0],
1992                                         struct btrfs_dev_extent);
1993
1994                 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1995                                                 chunk_root->root_key.objectid);
1996                 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1997                                                     chunk_objectid);
1998                 btrfs_set_dev_extent_chunk_offset(leaf, extent,
1999                                                   cache->key.objectid);
2000                 btrfs_set_dev_extent_length(leaf, extent, cache->key.offset);
2001                 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
2002                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
2003                     BTRFS_UUID_SIZE);
2004                 btrfs_mark_buffer_dirty(leaf);
2005                 btrfs_release_path(&path);
2006
2007                 /* insert chunk item */
2008                 btrfs_set_stack_chunk_length(&chunk, cache->key.offset);
2009                 btrfs_set_stack_chunk_owner(&chunk,
2010                                             extent_root->root_key.objectid);
2011                 btrfs_set_stack_chunk_stripe_len(&chunk, BTRFS_STRIPE_LEN);
2012                 btrfs_set_stack_chunk_type(&chunk, cache->flags);
2013                 btrfs_set_stack_chunk_io_align(&chunk, device->io_align);
2014                 btrfs_set_stack_chunk_io_width(&chunk, device->io_width);
2015                 btrfs_set_stack_chunk_sector_size(&chunk, device->sector_size);
2016                 btrfs_set_stack_chunk_num_stripes(&chunk, 1);
2017                 btrfs_set_stack_chunk_sub_stripes(&chunk, 0);
2018                 btrfs_set_stack_stripe_devid(&chunk.stripe, device->devid);
2019                 btrfs_set_stack_stripe_offset(&chunk.stripe,
2020                                               cache->key.objectid);
2021                 memcpy(&chunk.stripe.dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2022
2023                 key.objectid = chunk_objectid;
2024                 key.offset = cache->key.objectid;
2025                 key.type = BTRFS_CHUNK_ITEM_KEY;
2026
2027                 ret = btrfs_insert_item(trans, chunk_root, &key, &chunk,
2028                                         btrfs_chunk_item_size(1));
2029                 if (ret)
2030                         goto err;
2031
2032                 cur_start = cache->key.objectid + cache->key.offset;
2033         }
2034
2035         device->bytes_used = total_bytes;
2036         ret = btrfs_update_device(trans, device);
2037 err:
2038         btrfs_release_path(&path);
2039         return ret;
2040 }
2041
2042 static int create_subvol(struct btrfs_trans_handle *trans,
2043                          struct btrfs_root *root, u64 root_objectid)
2044 {
2045         struct extent_buffer *tmp;
2046         struct btrfs_root *new_root;
2047         struct btrfs_key key;
2048         struct btrfs_root_item root_item;
2049         int ret;
2050
2051         ret = btrfs_copy_root(trans, root, root->node, &tmp,
2052                               root_objectid);
2053         BUG_ON(ret);
2054
2055         memcpy(&root_item, &root->root_item, sizeof(root_item));
2056         btrfs_set_root_bytenr(&root_item, tmp->start);
2057         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
2058         btrfs_set_root_generation(&root_item, trans->transid);
2059         free_extent_buffer(tmp);
2060
2061         key.objectid = root_objectid;
2062         key.type = BTRFS_ROOT_ITEM_KEY;
2063         key.offset = trans->transid;
2064         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
2065                                 &key, &root_item);
2066
2067         key.offset = (u64)-1;
2068         new_root = btrfs_read_fs_root(root->fs_info, &key);
2069         BUG_ON(!new_root || IS_ERR(new_root));
2070
2071         ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
2072         BUG_ON(ret);
2073
2074         return 0;
2075 }
2076
2077 /*
2078  * New make_btrfs_v2() has handle system and meta chunks quite well.
2079  * So only need to add remaining data chunks.
2080  */
2081 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
2082                                           struct btrfs_fs_info *fs_info,
2083                                           struct btrfs_mkfs_config *cfg,
2084                                           struct btrfs_convert_context *cctx)
2085 {
2086         struct btrfs_root *extent_root = fs_info->extent_root;
2087         struct cache_tree *data_chunks = &cctx->data_chunks;
2088         struct cache_extent *cache;
2089         u64 max_chunk_size;
2090         int ret = 0;
2091
2092         /*
2093          * Don't create data chunk over 10% of the convert device
2094          * And for single chunk, don't create chunk larger than 1G.
2095          */
2096         max_chunk_size = cfg->num_bytes / 10;
2097         max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
2098         max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
2099
2100         for (cache = first_cache_extent(data_chunks); cache;
2101              cache = next_cache_extent(cache)) {
2102                 u64 cur = cache->start;
2103
2104                 while (cur < cache->start + cache->size) {
2105                         u64 len;
2106                         u64 cur_backup = cur;
2107
2108                         len = min(max_chunk_size,
2109                                   cache->start + cache->size - cur);
2110                         ret = btrfs_alloc_data_chunk(trans, extent_root,
2111                                         &cur_backup, len,
2112                                         BTRFS_BLOCK_GROUP_DATA, 1);
2113                         if (ret < 0)
2114                                 break;
2115                         ret = btrfs_make_block_group(trans, extent_root, 0,
2116                                         BTRFS_BLOCK_GROUP_DATA,
2117                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2118                                         cur, len);
2119                         if (ret < 0)
2120                                 break;
2121                         cur += len;
2122                 }
2123         }
2124         return ret;
2125 }
2126
2127 static int init_btrfs(struct btrfs_root *root)
2128 {
2129         int ret;
2130         struct btrfs_key location;
2131         struct btrfs_trans_handle *trans;
2132         struct btrfs_fs_info *fs_info = root->fs_info;
2133         struct extent_buffer *tmp;
2134
2135         trans = btrfs_start_transaction(root, 1);
2136         BUG_ON(!trans);
2137         ret = btrfs_make_block_groups(trans, root);
2138         if (ret)
2139                 goto err;
2140         ret = btrfs_fix_block_accounting(trans, root);
2141         if (ret)
2142                 goto err;
2143         ret = create_chunk_mapping(trans, root);
2144         if (ret)
2145                 goto err;
2146         ret = btrfs_make_root_dir(trans, fs_info->tree_root,
2147                                   BTRFS_ROOT_TREE_DIR_OBJECTID);
2148         if (ret)
2149                 goto err;
2150         memcpy(&location, &root->root_key, sizeof(location));
2151         location.offset = (u64)-1;
2152         ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
2153                                 btrfs_super_root_dir(fs_info->super_copy),
2154                                 &location, BTRFS_FT_DIR, 0);
2155         if (ret)
2156                 goto err;
2157         ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
2158                                 location.objectid,
2159                                 btrfs_super_root_dir(fs_info->super_copy), 0);
2160         if (ret)
2161                 goto err;
2162         btrfs_set_root_dirid(&fs_info->fs_root->root_item,
2163                              BTRFS_FIRST_FREE_OBJECTID);
2164
2165         /* subvol for fs image file */
2166         ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
2167         BUG_ON(ret);
2168         /* subvol for data relocation */
2169         ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
2170         BUG_ON(ret);
2171
2172         extent_buffer_get(fs_info->csum_root->node);
2173         ret = __btrfs_cow_block(trans, fs_info->csum_root,
2174                                 fs_info->csum_root->node, NULL, 0, &tmp, 0, 0);
2175         BUG_ON(ret);
2176         free_extent_buffer(tmp);
2177
2178         ret = btrfs_commit_transaction(trans, root);
2179         BUG_ON(ret);
2180 err:
2181         return ret;
2182 }
2183
2184 /*
2185  * Migrate super block to its default position and zero 0 ~ 16k
2186  */
2187 static int migrate_super_block(int fd, u64 old_bytenr, u32 sectorsize)
2188 {
2189         int ret;
2190         struct extent_buffer *buf;
2191         struct btrfs_super_block *super;
2192         u32 len;
2193         u32 bytenr;
2194
2195         BUG_ON(sectorsize < sizeof(*super));
2196         buf = malloc(sizeof(*buf) + sectorsize);
2197         if (!buf)
2198                 return -ENOMEM;
2199
2200         buf->len = sectorsize;
2201         ret = pread(fd, buf->data, sectorsize, old_bytenr);
2202         if (ret != sectorsize)
2203                 goto fail;
2204
2205         super = (struct btrfs_super_block *)buf->data;
2206         BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
2207         btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
2208
2209         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
2210         ret = pwrite(fd, buf->data, sectorsize, BTRFS_SUPER_INFO_OFFSET);
2211         if (ret != sectorsize)
2212                 goto fail;
2213
2214         ret = fsync(fd);
2215         if (ret)
2216                 goto fail;
2217
2218         memset(buf->data, 0, sectorsize);
2219         for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
2220                 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
2221                 if (len > sectorsize)
2222                         len = sectorsize;
2223                 ret = pwrite(fd, buf->data, len, bytenr);
2224                 if (ret != len) {
2225                         fprintf(stderr, "unable to zero fill device\n");
2226                         break;
2227                 }
2228                 bytenr += len;
2229         }
2230         ret = 0;
2231         fsync(fd);
2232 fail:
2233         free(buf);
2234         if (ret > 0)
2235                 ret = -1;
2236         return ret;
2237 }
2238
2239 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
2240 {
2241         struct btrfs_chunk *chunk;
2242         struct btrfs_disk_key *key;
2243         u32 sectorsize = btrfs_super_sectorsize(super);
2244
2245         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
2246         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
2247                                        sizeof(struct btrfs_disk_key));
2248
2249         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2250         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
2251         btrfs_set_disk_key_offset(key, 0);
2252
2253         btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
2254         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
2255         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
2256         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
2257         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
2258         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
2259         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
2260         btrfs_set_stack_chunk_num_stripes(chunk, 1);
2261         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
2262         chunk->stripe.devid = super->dev_item.devid;
2263         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
2264         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
2265         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
2266         return 0;
2267 }
2268
2269 static int prepare_system_chunk(int fd, u64 sb_bytenr)
2270 {
2271         int ret;
2272         struct extent_buffer *buf;
2273         struct btrfs_super_block *super;
2274
2275         BUG_ON(BTRFS_SUPER_INFO_SIZE < sizeof(*super));
2276         buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
2277         if (!buf)
2278                 return -ENOMEM;
2279
2280         buf->len = BTRFS_SUPER_INFO_SIZE;
2281         ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
2282         if (ret != BTRFS_SUPER_INFO_SIZE)
2283                 goto fail;
2284
2285         super = (struct btrfs_super_block *)buf->data;
2286         BUG_ON(btrfs_super_bytenr(super) != sb_bytenr);
2287         BUG_ON(btrfs_super_num_devices(super) != 1);
2288
2289         ret = prepare_system_chunk_sb(super);
2290         if (ret)
2291                 goto fail;
2292
2293         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
2294         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
2295         if (ret != BTRFS_SUPER_INFO_SIZE)
2296                 goto fail;
2297
2298         ret = 0;
2299 fail:
2300         free(buf);
2301         if (ret > 0)
2302                 ret = -1;
2303         return ret;
2304 }
2305
2306 static int relocate_one_reference(struct btrfs_trans_handle *trans,
2307                                   struct btrfs_root *root,
2308                                   u64 extent_start, u64 extent_size,
2309                                   struct btrfs_key *extent_key,
2310                                   struct extent_io_tree *reloc_tree)
2311 {
2312         struct extent_buffer *leaf;
2313         struct btrfs_file_extent_item *fi;
2314         struct btrfs_key key;
2315         struct btrfs_path path;
2316         struct btrfs_inode_item inode;
2317         struct blk_iterate_data data;
2318         u64 bytenr;
2319         u64 num_bytes;
2320         u64 cur_offset;
2321         u64 new_pos;
2322         u64 nbytes;
2323         u64 sector_end;
2324         u32 sectorsize = root->sectorsize;
2325         unsigned long ptr;
2326         int datacsum;
2327         int fd;
2328         int ret;
2329
2330         btrfs_init_path(&path);
2331         ret = btrfs_search_slot(trans, root, extent_key, &path, -1, 1);
2332         if (ret)
2333                 goto fail;
2334
2335         leaf = path.nodes[0];
2336         fi = btrfs_item_ptr(leaf, path.slots[0],
2337                             struct btrfs_file_extent_item);
2338         BUG_ON(btrfs_file_extent_offset(leaf, fi) > 0);
2339         if (extent_start != btrfs_file_extent_disk_bytenr(leaf, fi) ||
2340             extent_size != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
2341                 ret = 1;
2342                 goto fail;
2343         }
2344
2345         bytenr = extent_start + btrfs_file_extent_offset(leaf, fi);
2346         num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2347
2348         ret = btrfs_del_item(trans, root, &path);
2349         if (ret)
2350                 goto fail;
2351
2352         ret = btrfs_free_extent(trans, root, extent_start, extent_size, 0,
2353                                 root->root_key.objectid,
2354                                 extent_key->objectid, extent_key->offset);
2355         if (ret)
2356                 goto fail;
2357
2358         btrfs_release_path(&path);
2359
2360         key.objectid = extent_key->objectid;
2361         key.offset = 0;
2362         key.type =  BTRFS_INODE_ITEM_KEY;
2363         ret = btrfs_lookup_inode(trans, root, &path, &key, 0);
2364         if (ret)
2365                 goto fail;
2366
2367         leaf = path.nodes[0];
2368         ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2369         read_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2370         btrfs_release_path(&path);
2371
2372         BUG_ON(num_bytes & (sectorsize - 1));
2373         nbytes = btrfs_stack_inode_nbytes(&inode) - num_bytes;
2374         btrfs_set_stack_inode_nbytes(&inode, nbytes);
2375         datacsum = !(btrfs_stack_inode_flags(&inode) & BTRFS_INODE_NODATASUM);
2376
2377         init_blk_iterate_data(&data, trans, root, &inode, extent_key->objectid,
2378                               datacsum);
2379         data.first_block = extent_key->offset;
2380
2381         cur_offset = extent_key->offset;
2382         while (num_bytes > 0) {
2383                 sector_end = bytenr + sectorsize - 1;
2384                 if (test_range_bit(reloc_tree, bytenr, sector_end,
2385                                    EXTENT_LOCKED, 1)) {
2386                         ret = get_state_private(reloc_tree, bytenr, &new_pos);
2387                         BUG_ON(ret);
2388                 } else {
2389                         ret = custom_alloc_extent(root, sectorsize, 0, &key, 0);
2390                         if (ret)
2391                                 goto fail;
2392                         new_pos = key.objectid;
2393
2394                         if (cur_offset == extent_key->offset) {
2395                                 fd = root->fs_info->fs_devices->latest_bdev;
2396                                 readahead(fd, bytenr, num_bytes);
2397                         }
2398                         ret = copy_disk_extent(root, new_pos, bytenr,
2399                                                sectorsize);
2400                         if (ret)
2401                                 goto fail;
2402                         ret = set_extent_bits(reloc_tree, bytenr, sector_end,
2403                                               EXTENT_LOCKED, GFP_NOFS);
2404                         BUG_ON(ret);
2405                         ret = set_state_private(reloc_tree, bytenr, new_pos);
2406                         BUG_ON(ret);
2407                 }
2408
2409                 ret = block_iterate_proc(new_pos / sectorsize,
2410                                          cur_offset / sectorsize, &data);
2411                 if (ret < 0)
2412                         goto fail;
2413
2414                 cur_offset += sectorsize;
2415                 bytenr += sectorsize;
2416                 num_bytes -= sectorsize;
2417         }
2418
2419         if (data.num_blocks > 0) {
2420                 ret = record_file_blocks(&data, data.first_block,
2421                                          data.disk_block, data.num_blocks);
2422                 if (ret)
2423                         goto fail;
2424         }
2425
2426         key.objectid = extent_key->objectid;
2427         key.offset = 0;
2428         key.type =  BTRFS_INODE_ITEM_KEY;
2429         ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
2430         if (ret)
2431                 goto fail;
2432
2433         leaf = path.nodes[0];
2434         ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2435         write_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2436         btrfs_mark_buffer_dirty(leaf);
2437         btrfs_release_path(&path);
2438
2439 fail:
2440         btrfs_release_path(&path);
2441         return ret;
2442 }
2443
2444 static int relocate_extents_range(struct btrfs_root *fs_root,
2445                                   struct btrfs_root *image_root,
2446                                   u64 start_byte, u64 end_byte)
2447 {
2448         struct btrfs_fs_info *info = fs_root->fs_info;
2449         struct btrfs_root *extent_root = info->extent_root;
2450         struct btrfs_root *cur_root = NULL;
2451         struct btrfs_trans_handle *trans;
2452         struct btrfs_extent_data_ref *dref;
2453         struct btrfs_extent_inline_ref *iref;
2454         struct btrfs_extent_item *ei;
2455         struct extent_buffer *leaf;
2456         struct btrfs_key key;
2457         struct btrfs_key extent_key;
2458         struct btrfs_path path;
2459         struct extent_io_tree reloc_tree;
2460         unsigned long ptr;
2461         unsigned long end;
2462         u64 cur_byte;
2463         u64 num_bytes;
2464         u64 ref_root;
2465         u64 num_extents;
2466         int pass = 0;
2467         int ret;
2468
2469         btrfs_init_path(&path);
2470         extent_io_tree_init(&reloc_tree);
2471
2472         key.objectid = start_byte;
2473         key.offset = 0;
2474         key.type = BTRFS_EXTENT_ITEM_KEY;
2475         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2476         if (ret < 0)
2477                 goto fail;
2478         if (ret > 0) {
2479                 ret = btrfs_previous_item(extent_root, &path, 0,
2480                                           BTRFS_EXTENT_ITEM_KEY);
2481                 if (ret < 0)
2482                         goto fail;
2483                 if (ret == 0) {
2484                         leaf = path.nodes[0];
2485                         btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2486                         if (key.objectid + key.offset > start_byte)
2487                                 start_byte = key.objectid;
2488                 }
2489         }
2490         btrfs_release_path(&path);
2491 again:
2492         cur_root = (pass % 2 == 0) ? image_root : fs_root;
2493         num_extents = 0;
2494
2495         trans = btrfs_start_transaction(cur_root, 1);
2496         BUG_ON(!trans);
2497
2498         cur_byte = start_byte;
2499         while (1) {
2500                 key.objectid = cur_byte;
2501                 key.offset = 0;
2502                 key.type = BTRFS_EXTENT_ITEM_KEY;
2503                 ret = btrfs_search_slot(trans, extent_root,
2504                                         &key, &path, 0, 0);
2505                 if (ret < 0)
2506                         goto fail;
2507 next:
2508                 leaf = path.nodes[0];
2509                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2510                         ret = btrfs_next_leaf(extent_root, &path);
2511                         if (ret < 0)
2512                                 goto fail;
2513                         if (ret > 0)
2514                                 break;
2515                         leaf = path.nodes[0];
2516                 }
2517
2518                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2519                 if (key.objectid < cur_byte ||
2520                     key.type != BTRFS_EXTENT_ITEM_KEY) {
2521                         path.slots[0]++;
2522                         goto next;
2523                 }
2524                 if (key.objectid >= end_byte)
2525                         break;
2526
2527                 num_extents++;
2528
2529                 cur_byte = key.objectid;
2530                 num_bytes = key.offset;
2531                 ei = btrfs_item_ptr(leaf, path.slots[0],
2532                                     struct btrfs_extent_item);
2533                 BUG_ON(!(btrfs_extent_flags(leaf, ei) &
2534                          BTRFS_EXTENT_FLAG_DATA));
2535
2536                 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2537                 end = ptr + btrfs_item_size_nr(leaf, path.slots[0]);
2538
2539                 ptr += sizeof(struct btrfs_extent_item);
2540
2541                 while (ptr < end) {
2542                         iref = (struct btrfs_extent_inline_ref *)ptr;
2543                         key.type = btrfs_extent_inline_ref_type(leaf, iref);
2544                         BUG_ON(key.type != BTRFS_EXTENT_DATA_REF_KEY);
2545                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
2546                         ref_root = btrfs_extent_data_ref_root(leaf, dref);
2547                         extent_key.objectid =
2548                                 btrfs_extent_data_ref_objectid(leaf, dref);
2549                         extent_key.offset =
2550                                 btrfs_extent_data_ref_offset(leaf, dref);
2551                         extent_key.type = BTRFS_EXTENT_DATA_KEY;
2552                         BUG_ON(btrfs_extent_data_ref_count(leaf, dref) != 1);
2553
2554                         if (ref_root == cur_root->root_key.objectid)
2555                                 break;
2556
2557                         ptr += btrfs_extent_inline_ref_size(key.type);
2558                 }
2559
2560                 if (ptr >= end) {
2561                         path.slots[0]++;
2562                         goto next;
2563                 }
2564
2565                 ret = relocate_one_reference(trans, cur_root, cur_byte,
2566                                              num_bytes, &extent_key,
2567                                              &reloc_tree);
2568                 if (ret < 0)
2569                         goto fail;
2570
2571                 cur_byte += num_bytes;
2572                 btrfs_release_path(&path);
2573
2574                 if (trans->blocks_used >= 4096) {
2575                         ret = btrfs_commit_transaction(trans, cur_root);
2576                         BUG_ON(ret);
2577                         trans = btrfs_start_transaction(cur_root, 1);
2578                         BUG_ON(!trans);
2579                 }
2580         }
2581         btrfs_release_path(&path);
2582
2583         ret = btrfs_commit_transaction(trans, cur_root);
2584         BUG_ON(ret);
2585
2586         if (num_extents > 0 && pass++ < 16)
2587                 goto again;
2588
2589         ret = (num_extents > 0) ? -1 : 0;
2590 fail:
2591         btrfs_release_path(&path);
2592         extent_io_tree_cleanup(&reloc_tree);
2593         return ret;
2594 }
2595
2596 /*
2597  * relocate data in system chunk
2598  */
2599 static int cleanup_sys_chunk(struct btrfs_root *fs_root,
2600                              struct btrfs_root *image_root)
2601 {
2602         struct btrfs_block_group_cache *cache;
2603         int i, ret = 0;
2604         u64 offset = 0;
2605         u64 end_byte;
2606
2607         while(1) {
2608                 cache = btrfs_lookup_block_group(fs_root->fs_info, offset);
2609                 if (!cache)
2610                         break;
2611
2612                 end_byte = cache->key.objectid + cache->key.offset;
2613                 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2614                         ret = relocate_extents_range(fs_root, image_root,
2615                                                      cache->key.objectid,
2616                                                      end_byte);
2617                         if (ret)
2618                                 goto fail;
2619                 }
2620                 offset = end_byte;
2621         }
2622         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2623                 offset = btrfs_sb_offset(i);
2624                 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
2625
2626                 ret = relocate_extents_range(fs_root, image_root,
2627                                              offset, offset + BTRFS_STRIPE_LEN);
2628                 if (ret)
2629                         goto fail;
2630         }
2631         ret = 0;
2632 fail:
2633         return ret;
2634 }
2635
2636 static int fixup_chunk_mapping(struct btrfs_root *root)
2637 {
2638         struct btrfs_trans_handle *trans;
2639         struct btrfs_fs_info *info = root->fs_info;
2640         struct btrfs_root *chunk_root = info->chunk_root;
2641         struct extent_buffer *leaf;
2642         struct btrfs_key key;
2643         struct btrfs_path path;
2644         struct btrfs_chunk chunk;
2645         unsigned long ptr;
2646         u32 size;
2647         u64 type;
2648         int ret;
2649
2650         btrfs_init_path(&path);
2651
2652         trans = btrfs_start_transaction(root, 1);
2653         BUG_ON(!trans);
2654
2655         /*
2656          * recow the whole chunk tree. this will move all chunk tree blocks
2657          * into system block group.
2658          */
2659         memset(&key, 0, sizeof(key));
2660         while (1) {
2661                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2662                 if (ret < 0)
2663                         goto err;
2664
2665                 ret = btrfs_next_leaf(chunk_root, &path);
2666                 if (ret < 0)
2667                         goto err;
2668                 if (ret > 0)
2669                         break;
2670
2671                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2672                 btrfs_release_path(&path);
2673         }
2674         btrfs_release_path(&path);
2675
2676         /* fixup the system chunk array in super block */
2677         btrfs_set_super_sys_array_size(info->super_copy, 0);
2678
2679         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2680         key.offset = 0;
2681         key.type = BTRFS_CHUNK_ITEM_KEY;
2682
2683         ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 0);
2684         if (ret < 0)
2685                 goto err;
2686         BUG_ON(ret != 0);
2687         while(1) {
2688                 leaf = path.nodes[0];
2689                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2690                         ret = btrfs_next_leaf(chunk_root, &path);
2691                         if (ret < 0)
2692                                 goto err;
2693                         if (ret > 0)
2694                                 break;
2695                         leaf = path.nodes[0];
2696                 }
2697                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2698                 if (key.type != BTRFS_CHUNK_ITEM_KEY)
2699                         goto next;
2700
2701                 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2702                 size = btrfs_item_size_nr(leaf, path.slots[0]);
2703                 BUG_ON(size != sizeof(chunk));
2704                 read_extent_buffer(leaf, &chunk, ptr, size);
2705                 type = btrfs_stack_chunk_type(&chunk);
2706
2707                 if (!(type & BTRFS_BLOCK_GROUP_SYSTEM))
2708                         goto next;
2709
2710                 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
2711                                              &chunk, size);
2712                 if (ret)
2713                         goto err;
2714 next:
2715                 path.slots[0]++;
2716         }
2717
2718         ret = btrfs_commit_transaction(trans, root);
2719         BUG_ON(ret);
2720 err:
2721         btrfs_release_path(&path);
2722         return ret;
2723 }
2724
2725 static const struct btrfs_convert_operations ext2_convert_ops = {
2726         .name                   = "ext2",
2727         .open_fs                = ext2_open_fs,
2728         .read_used_space        = ext2_read_used_space,
2729         .alloc_block            = ext2_alloc_block,
2730         .alloc_block_range      = ext2_alloc_block_range,
2731         .copy_inodes            = ext2_copy_inodes,
2732         .test_block             = ext2_test_block,
2733         .free_block             = ext2_free_block,
2734         .free_block_range       = ext2_free_block_range,
2735         .close_fs               = ext2_close_fs,
2736 };
2737
2738 static const struct btrfs_convert_operations *convert_operations[] = {
2739         &ext2_convert_ops,
2740 };
2741
2742 static int convert_open_fs(const char *devname,
2743                            struct btrfs_convert_context *cctx)
2744 {
2745         int i;
2746
2747         memset(cctx, 0, sizeof(*cctx));
2748
2749         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2750                 int ret = convert_operations[i]->open_fs(cctx, devname);
2751
2752                 if (ret == 0) {
2753                         cctx->convert_ops = convert_operations[i];
2754                         return ret;
2755                 }
2756         }
2757
2758         fprintf(stderr, "No file system found to convert.\n");
2759         return -1;
2760 }
2761
2762 /*
2763  * Remove one reserve range from given cache tree
2764  * if min_stripe_size is non-zero, it will ensure for split case,
2765  * all its split cache extent is no smaller than @min_strip_size / 2.
2766  */
2767 static int wipe_one_reserved_range(struct cache_tree *tree,
2768                                    u64 start, u64 len, u64 min_stripe_size,
2769                                    int ensure_size)
2770 {
2771         struct cache_extent *cache;
2772         int ret;
2773
2774         BUG_ON(ensure_size && min_stripe_size == 0);
2775         /*
2776          * The logical here is simplified to handle special cases only
2777          * So we don't need to consider merge case for ensure_size
2778          */
2779         BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
2780                min_stripe_size / 2 < BTRFS_STRIPE_LEN));
2781
2782         /* Also, wipe range should already be aligned */
2783         BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
2784                start + len != round_up(start + len, BTRFS_STRIPE_LEN));
2785
2786         min_stripe_size /= 2;
2787
2788         cache = lookup_cache_extent(tree, start, len);
2789         if (!cache)
2790                 return 0;
2791
2792         if (start <= cache->start) {
2793                 /*
2794                  *      |--------cache---------|
2795                  * |-wipe-|
2796                  */
2797                 BUG_ON(start + len <= cache->start);
2798
2799                 /*
2800                  * The wipe size is smaller than min_stripe_size / 2,
2801                  * so the result length should still meet min_stripe_size
2802                  * And no need to do alignment
2803                  */
2804                 cache->size -= (start + len - cache->start);
2805                 if (cache->size == 0) {
2806                         remove_cache_extent(tree, cache);
2807                         free(cache);
2808                         return 0;
2809                 }
2810
2811                 BUG_ON(ensure_size && cache->size < min_stripe_size);
2812
2813                 cache->start = start + len;
2814                 return 0;
2815         } else if (start > cache->start && start + len < cache->start +
2816                    cache->size) {
2817                 /*
2818                  * |-------cache-----|
2819                  *      |-wipe-|
2820                  */
2821                 u64 old_len = cache->size;
2822                 u64 insert_start = start + len;
2823                 u64 insert_len;
2824
2825                 cache->size = start - cache->start;
2826                 if (ensure_size)
2827                         cache->size = max(cache->size, min_stripe_size);
2828                 cache->start = start - cache->size;
2829
2830                 /* And insert the new one */
2831                 insert_len = old_len - start - len;
2832                 if (ensure_size)
2833                         insert_len = max(insert_len, min_stripe_size);
2834
2835                 ret = add_merge_cache_extent(tree, insert_start, insert_len);
2836                 return ret;
2837         }
2838         /*
2839          * |----cache-----|
2840          *              |--wipe-|
2841          * Wipe len should be small enough and no need to expand the
2842          * remaining extent
2843          */
2844         cache->size = start - cache->start;
2845         BUG_ON(ensure_size && cache->size < min_stripe_size);
2846         return 0;
2847 }
2848
2849 /*
2850  * Remove reserved ranges from given cache_tree
2851  *
2852  * It will remove the following ranges
2853  * 1) 0~1M
2854  * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
2855  * 3) 3rd superblock, +64K
2856  *
2857  * @min_stripe must be given for safety check
2858  * and if @ensure_size is given, it will ensure affected cache_extent will be
2859  * larger than min_stripe_size
2860  */
2861 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
2862                                 int ensure_size)
2863 {
2864         int ret;
2865
2866         ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
2867                                       ensure_size);
2868         if (ret < 0)
2869                 return ret;
2870         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
2871                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2872         if (ret < 0)
2873                 return ret;
2874         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
2875                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2876         return ret;
2877 }
2878
2879 static int calculate_available_space(struct btrfs_convert_context *cctx)
2880 {
2881         struct cache_tree *used = &cctx->used;
2882         struct cache_tree *data_chunks = &cctx->data_chunks;
2883         struct cache_tree *free = &cctx->free;
2884         struct cache_extent *cache;
2885         u64 cur_off = 0;
2886         /*
2887          * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
2888          * works without need to consider overlap
2889          */
2890         u64 min_stripe_size = 2 * 16 * 1024 * 1024;
2891         int ret;
2892
2893         /* Calculate data_chunks */
2894         for (cache = first_cache_extent(used); cache;
2895              cache = next_cache_extent(cache)) {
2896                 u64 cur_len;
2897
2898                 if (cache->start + cache->size < cur_off)
2899                         continue;
2900                 if (cache->start > cur_off + min_stripe_size)
2901                         cur_off = cache->start;
2902                 cur_len = max(cache->start + cache->size - cur_off,
2903                               min_stripe_size);
2904                 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
2905                 if (ret < 0)
2906                         goto out;
2907                 cur_off += cur_len;
2908         }
2909         /*
2910          * remove reserved ranges, so we won't ever bother relocating an old
2911          * filesystem extent to other place.
2912          */
2913         ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
2914         if (ret < 0)
2915                 goto out;
2916
2917         cur_off = 0;
2918         /*
2919          * Calculate free space
2920          * Always round up the start bytenr, to avoid metadata extent corss
2921          * stripe boundary, as later mkfs_convert() won't have all the extent
2922          * allocation check
2923          */
2924         for (cache = first_cache_extent(data_chunks); cache;
2925              cache = next_cache_extent(cache)) {
2926                 if (cache->start < cur_off)
2927                         continue;
2928                 if (cache->start > cur_off) {
2929                         u64 insert_start;
2930                         u64 len;
2931
2932                         len = cache->start - round_up(cur_off,
2933                                                       BTRFS_STRIPE_LEN);
2934                         insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2935
2936                         ret = add_merge_cache_extent(free, insert_start, len);
2937                         if (ret < 0)
2938                                 goto out;
2939                 }
2940                 cur_off = cache->start + cache->size;
2941         }
2942         /* Don't forget the last range */
2943         if (cctx->total_bytes > cur_off) {
2944                 u64 len = cctx->total_bytes - cur_off;
2945                 u64 insert_start;
2946
2947                 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2948
2949                 ret = add_merge_cache_extent(free, insert_start, len);
2950                 if (ret < 0)
2951                         goto out;
2952         }
2953
2954         /* Remove reserved bytes */
2955         ret = wipe_reserved_ranges(free, min_stripe_size, 0);
2956 out:
2957         return ret;
2958 }
2959 /*
2960  * Read used space, and since we have the used space,
2961  * calcuate data_chunks and free for later mkfs
2962  */
2963 static int convert_read_used_space(struct btrfs_convert_context *cctx)
2964 {
2965         int ret;
2966
2967         ret = cctx->convert_ops->read_used_space(cctx);
2968         if (ret)
2969                 return ret;
2970
2971         ret = calculate_available_space(cctx);
2972         return ret;
2973 }
2974
2975 static int do_convert(const char *devname, int datacsum, int packing, int noxattr,
2976                 u32 nodesize, int copylabel, const char *fslabel, int progress,
2977                 u64 features)
2978 {
2979         int i, ret, blocks_per_node;
2980         int fd = -1;
2981         int is_btrfs = 0;
2982         u32 blocksize;
2983         u64 blocks[7];
2984         u64 total_bytes;
2985         u64 super_bytenr;
2986         struct btrfs_root *root;
2987         struct btrfs_root *image_root;
2988         struct btrfs_convert_context cctx;
2989         char *subvol_name = NULL;
2990         struct task_ctx ctx;
2991         char features_buf[64];
2992         struct btrfs_mkfs_config mkfs_cfg;
2993
2994         init_convert_context(&cctx);
2995         ret = convert_open_fs(devname, &cctx);
2996         if (ret)
2997                 goto fail;
2998         ret = convert_read_used_space(&cctx);
2999         if (ret)
3000                 goto fail;
3001
3002         blocksize = cctx.blocksize;
3003         total_bytes = (u64)blocksize * (u64)cctx.block_count;
3004         if (blocksize < 4096) {
3005                 fprintf(stderr, "block size is too small\n");
3006                 goto fail;
3007         }
3008         if (btrfs_check_nodesize(nodesize, blocksize, features))
3009                 goto fail;
3010         blocks_per_node = nodesize / blocksize;
3011         ret = -blocks_per_node;
3012         for (i = 0; i < 7; i++) {
3013                 if (nodesize == blocksize)
3014                         ret = convert_alloc_block(&cctx, 0, blocks + i);
3015                 else
3016                         ret = convert_alloc_block_range(&cctx,
3017                                         ret + blocks_per_node, blocks_per_node,
3018                                         blocks + i);
3019                 if (ret) {
3020                         fprintf(stderr, "not enough free space\n");
3021                         goto fail;
3022                 }
3023                 blocks[i] *= blocksize;
3024         }
3025         super_bytenr = blocks[0];
3026         fd = open(devname, O_RDWR);
3027         if (fd < 0) {
3028                 fprintf(stderr, "unable to open %s\n", devname);
3029                 goto fail;
3030         }
3031         btrfs_parse_features_to_string(features_buf, features);
3032         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
3033                 strcat(features_buf, " (default)");
3034
3035         printf("create btrfs filesystem:\n");
3036         printf("\tblocksize: %u\n", blocksize);
3037         printf("\tnodesize:  %u\n", nodesize);
3038         printf("\tfeatures:  %s\n", features_buf);
3039
3040         mkfs_cfg.label = cctx.volume_name;
3041         mkfs_cfg.fs_uuid = NULL;
3042         memcpy(mkfs_cfg.blocks, blocks, sizeof(blocks));
3043         mkfs_cfg.num_bytes = total_bytes;
3044         mkfs_cfg.nodesize = nodesize;
3045         mkfs_cfg.sectorsize = blocksize;
3046         mkfs_cfg.stripesize = blocksize;
3047         mkfs_cfg.features = features;
3048
3049         ret = make_btrfs(fd, &mkfs_cfg, NULL);
3050         if (ret) {
3051                 fprintf(stderr, "unable to create initial ctree: %s\n",
3052                         strerror(-ret));
3053                 goto fail;
3054         }
3055         /* create a system chunk that maps the whole device */
3056         ret = prepare_system_chunk(fd, super_bytenr);
3057         if (ret) {
3058                 fprintf(stderr, "unable to update system chunk\n");
3059                 goto fail;
3060         }
3061         root = open_ctree_fd(fd, devname, super_bytenr, OPEN_CTREE_WRITES);
3062         if (!root) {
3063                 fprintf(stderr, "unable to open ctree\n");
3064                 goto fail;
3065         }
3066         ret = cache_free_extents(root, &cctx);
3067         if (ret) {
3068                 fprintf(stderr, "error during cache_free_extents %d\n", ret);
3069                 goto fail;
3070         }
3071         root->fs_info->extent_ops = &extent_ops;
3072         /* recover block allocation bitmap */
3073         for (i = 0; i < 7; i++) {
3074                 blocks[i] /= blocksize;
3075                 if (nodesize == blocksize)
3076                         convert_free_block(&cctx, blocks[i]);
3077                 else
3078                         convert_free_block_range(&cctx, blocks[i],
3079                                         blocks_per_node);
3080         }
3081         ret = init_btrfs(root);
3082         if (ret) {
3083                 fprintf(stderr, "unable to setup the root tree\n");
3084                 goto fail;
3085         }
3086         printf("creating btrfs metadata.\n");
3087         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
3088         ctx.cur_copy_inodes = 0;
3089
3090         if (progress) {
3091                 ctx.info = task_init(print_copied_inodes, after_copied_inodes, &ctx);
3092                 task_start(ctx.info);
3093         }
3094         ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
3095         if (ret) {
3096                 fprintf(stderr, "error during copy_inodes %d\n", ret);
3097                 goto fail;
3098         }
3099         if (progress) {
3100                 task_stop(ctx.info);
3101                 task_deinit(ctx.info);
3102         }
3103
3104         printf("creating %s image file.\n", cctx.convert_ops->name);
3105         ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
3106         if (ret < 0) {
3107                 fprintf(stderr, "error allocating subvolume name: %s_saved\n",
3108                         cctx.convert_ops->name);
3109                 goto fail;
3110         }
3111
3112         image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
3113
3114         free(subvol_name);
3115
3116         if (!image_root) {
3117                 fprintf(stderr, "unable to create subvol\n");
3118                 goto fail;
3119         }
3120         ret = create_image(&cctx, image_root, "image", datacsum);
3121         if (ret) {
3122                 fprintf(stderr, "error during create_image %d\n", ret);
3123                 goto fail;
3124         }
3125         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
3126         if (copylabel == 1) {
3127                 __strncpy_null(root->fs_info->super_copy->label,
3128                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
3129                 fprintf(stderr, "copy label '%s'\n",
3130                                 root->fs_info->super_copy->label);
3131         } else if (copylabel == -1) {
3132                 strcpy(root->fs_info->super_copy->label, fslabel);
3133                 fprintf(stderr, "set label to '%s'\n", fslabel);
3134         }
3135
3136         printf("cleaning up system chunk.\n");
3137         ret = cleanup_sys_chunk(root, image_root);
3138         if (ret) {
3139                 fprintf(stderr, "error during cleanup_sys_chunk %d\n", ret);
3140                 goto fail;
3141         }
3142         ret = close_ctree(root);
3143         if (ret) {
3144                 fprintf(stderr, "error during close_ctree %d\n", ret);
3145                 goto fail;
3146         }
3147         convert_close_fs(&cctx);
3148         clean_convert_context(&cctx);
3149
3150         /*
3151          * If this step succeed, we get a mountable btrfs. Otherwise
3152          * the source fs is left unchanged.
3153          */
3154         ret = migrate_super_block(fd, super_bytenr, blocksize);
3155         if (ret) {
3156                 fprintf(stderr, "unable to migrate super block\n");
3157                 goto fail;
3158         }
3159         is_btrfs = 1;
3160
3161         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
3162         if (!root) {
3163                 fprintf(stderr, "unable to open ctree\n");
3164                 goto fail;
3165         }
3166         /* move chunk tree into system chunk. */
3167         ret = fixup_chunk_mapping(root);
3168         if (ret) {
3169                 fprintf(stderr, "error during fixup_chunk_tree\n");
3170                 goto fail;
3171         }
3172         ret = close_ctree(root);
3173         close(fd);
3174
3175         printf("conversion complete.\n");
3176         return 0;
3177 fail:
3178         clean_convert_context(&cctx);
3179         if (fd != -1)
3180                 close(fd);
3181         if (is_btrfs)
3182                 fprintf(stderr,
3183                         "WARNING: an error occured during chunk mapping fixup, filesystem mountable but not finalized\n");
3184         else
3185                 fprintf(stderr, "conversion aborted\n");
3186         return -1;
3187 }
3188
3189 static int may_rollback(struct btrfs_root *root)
3190 {
3191         struct btrfs_fs_info *info = root->fs_info;
3192         struct btrfs_multi_bio *multi = NULL;
3193         u64 bytenr;
3194         u64 length;
3195         u64 physical;
3196         u64 total_bytes;
3197         int num_stripes;
3198         int ret;
3199
3200         if (btrfs_super_num_devices(info->super_copy) != 1)
3201                 goto fail;
3202
3203         bytenr = BTRFS_SUPER_INFO_OFFSET;
3204         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
3205
3206         while (1) {
3207                 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
3208                                       &length, &multi, 0, NULL);
3209                 if (ret) {
3210                         if (ret == -ENOENT) {
3211                                 /* removed block group at the tail */
3212                                 if (length == (u64)-1)
3213                                         break;
3214
3215                                 /* removed block group in the middle */
3216                                 goto next;
3217                         }
3218                         goto fail;
3219                 }
3220
3221                 num_stripes = multi->num_stripes;
3222                 physical = multi->stripes[0].physical;
3223                 kfree(multi);
3224
3225                 if (num_stripes != 1 || physical != bytenr)
3226                         goto fail;
3227 next:
3228                 bytenr += length;
3229                 if (bytenr >= total_bytes)
3230                         break;
3231         }
3232         return 0;
3233 fail:
3234         return -1;
3235 }
3236
3237 static int do_rollback(const char *devname)
3238 {
3239         int fd = -1;
3240         int ret;
3241         int i;
3242         struct btrfs_root *root;
3243         struct btrfs_root *image_root;
3244         struct btrfs_root *chunk_root;
3245         struct btrfs_dir_item *dir;
3246         struct btrfs_inode_item *inode;
3247         struct btrfs_file_extent_item *fi;
3248         struct btrfs_trans_handle *trans;
3249         struct extent_buffer *leaf;
3250         struct btrfs_block_group_cache *cache1;
3251         struct btrfs_block_group_cache *cache2;
3252         struct btrfs_key key;
3253         struct btrfs_path path;
3254         struct extent_io_tree io_tree;
3255         char *buf = NULL;
3256         char *name;
3257         u64 bytenr;
3258         u64 num_bytes;
3259         u64 root_dir;
3260         u64 objectid;
3261         u64 offset;
3262         u64 start;
3263         u64 end;
3264         u64 sb_bytenr;
3265         u64 first_free;
3266         u64 total_bytes;
3267         u32 sectorsize;
3268
3269         extent_io_tree_init(&io_tree);
3270
3271         fd = open(devname, O_RDWR);
3272         if (fd < 0) {
3273                 fprintf(stderr, "unable to open %s\n", devname);
3274                 goto fail;
3275         }
3276         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
3277         if (!root) {
3278                 fprintf(stderr, "unable to open ctree\n");
3279                 goto fail;
3280         }
3281         ret = may_rollback(root);
3282         if (ret < 0) {
3283                 fprintf(stderr, "unable to do rollback\n");
3284                 goto fail;
3285         }
3286
3287         sectorsize = root->sectorsize;
3288         buf = malloc(sectorsize);
3289         if (!buf) {
3290                 fprintf(stderr, "unable to allocate memory\n");
3291                 goto fail;
3292         }
3293
3294         btrfs_init_path(&path);
3295
3296         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
3297         key.type = BTRFS_ROOT_BACKREF_KEY;
3298         key.offset = BTRFS_FS_TREE_OBJECTID;
3299         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
3300                                 0);
3301         btrfs_release_path(&path);
3302         if (ret > 0) {
3303                 fprintf(stderr,
3304                 "ERROR: unable to convert ext2 image subvolume, is it deleted?\n");
3305                 goto fail;
3306         } else if (ret < 0) {
3307                 fprintf(stderr,
3308                         "ERROR: unable to open ext2_saved, id=%llu: %s\n",
3309                         (unsigned long long)key.objectid, strerror(-ret));
3310                 goto fail;
3311         }
3312
3313         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
3314         key.type = BTRFS_ROOT_ITEM_KEY;
3315         key.offset = (u64)-1;
3316         image_root = btrfs_read_fs_root(root->fs_info, &key);
3317         if (!image_root || IS_ERR(image_root)) {
3318                 fprintf(stderr, "unable to open subvol %llu\n",
3319                         (unsigned long long)key.objectid);
3320                 goto fail;
3321         }
3322
3323         name = "image";
3324         root_dir = btrfs_root_dirid(&root->root_item);
3325         dir = btrfs_lookup_dir_item(NULL, image_root, &path,
3326                                    root_dir, name, strlen(name), 0);
3327         if (!dir || IS_ERR(dir)) {
3328                 fprintf(stderr, "unable to find file %s\n", name);
3329                 goto fail;
3330         }
3331         leaf = path.nodes[0];
3332         btrfs_dir_item_key_to_cpu(leaf, dir, &key);
3333         btrfs_release_path(&path);
3334
3335         objectid = key.objectid;
3336
3337         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
3338         if (ret) {
3339                 fprintf(stderr, "unable to find inode item\n");
3340                 goto fail;
3341         }
3342         leaf = path.nodes[0];
3343         inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
3344         total_bytes = btrfs_inode_size(leaf, inode);
3345         btrfs_release_path(&path);
3346
3347         key.objectid = objectid;
3348         key.offset = 0;
3349         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
3350         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
3351         if (ret != 0) {
3352                 fprintf(stderr, "unable to find first file extent\n");
3353                 btrfs_release_path(&path);
3354                 goto fail;
3355         }
3356
3357         /* build mapping tree for the relocated blocks */
3358         for (offset = 0; offset < total_bytes; ) {
3359                 leaf = path.nodes[0];
3360                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3361                         ret = btrfs_next_leaf(root, &path);
3362                         if (ret != 0)
3363                                 break;  
3364                         continue;
3365                 }
3366
3367                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3368                 if (key.objectid != objectid || key.offset != offset ||
3369                     btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3370                         break;
3371
3372                 fi = btrfs_item_ptr(leaf, path.slots[0],
3373                                     struct btrfs_file_extent_item);
3374                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
3375                         break;
3376                 if (btrfs_file_extent_compression(leaf, fi) ||
3377                     btrfs_file_extent_encryption(leaf, fi) ||
3378                     btrfs_file_extent_other_encoding(leaf, fi))
3379                         break;
3380
3381                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
3382                 /* skip holes and direct mapped extents */
3383                 if (bytenr == 0 || bytenr == offset)
3384                         goto next_extent;
3385
3386                 bytenr += btrfs_file_extent_offset(leaf, fi);
3387                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
3388
3389                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
3390                 cache2 =  btrfs_lookup_block_group(root->fs_info,
3391                                                    offset + num_bytes - 1);
3392                 if (!cache1 || cache1 != cache2 ||
3393                     (!(cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM) &&
3394                      !intersect_with_sb(offset, num_bytes)))
3395                         break;
3396
3397                 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
3398                                 EXTENT_LOCKED, GFP_NOFS);
3399                 set_state_private(&io_tree, offset, bytenr);
3400 next_extent:
3401                 offset += btrfs_file_extent_num_bytes(leaf, fi);
3402                 path.slots[0]++;
3403         }
3404         btrfs_release_path(&path);
3405
3406         if (offset < total_bytes) {
3407                 fprintf(stderr, "unable to build extent mapping\n");
3408                 goto fail;
3409         }
3410
3411         first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
3412         first_free &= ~((u64)sectorsize - 1);
3413         /* backup for extent #0 should exist */
3414         if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
3415                 fprintf(stderr, "no backup for the first extent\n");
3416                 goto fail;
3417         }
3418         /* force no allocation from system block group */
3419         root->fs_info->system_allocs = -1;
3420         trans = btrfs_start_transaction(root, 1);
3421         BUG_ON(!trans);
3422         /*
3423          * recow the whole chunk tree, this will remove all chunk tree blocks
3424          * from system block group
3425          */
3426         chunk_root = root->fs_info->chunk_root;
3427         memset(&key, 0, sizeof(key));
3428         while (1) {
3429                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
3430                 if (ret < 0)
3431                         break;
3432
3433                 ret = btrfs_next_leaf(chunk_root, &path);
3434                 if (ret)
3435                         break;
3436
3437                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
3438                 btrfs_release_path(&path);
3439         }
3440         btrfs_release_path(&path);
3441
3442         offset = 0;
3443         num_bytes = 0;
3444         while(1) {
3445                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
3446                 if (!cache1)
3447                         break;
3448
3449                 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
3450                         num_bytes += btrfs_block_group_used(&cache1->item);
3451
3452                 offset = cache1->key.objectid + cache1->key.offset;
3453         }
3454         /* only extent #0 left in system block group? */
3455         if (num_bytes > first_free) {
3456                 fprintf(stderr, "unable to empty system block group\n");
3457                 goto fail;
3458         }
3459         /* create a system chunk that maps the whole device */
3460         ret = prepare_system_chunk_sb(root->fs_info->super_copy);
3461         if (ret) {
3462                 fprintf(stderr, "unable to update system chunk\n");
3463                 goto fail;
3464         }
3465
3466         ret = btrfs_commit_transaction(trans, root);
3467         BUG_ON(ret);
3468
3469         ret = close_ctree(root);
3470         if (ret) {
3471                 fprintf(stderr, "error during close_ctree %d\n", ret);
3472                 goto fail;
3473         }
3474
3475         /* zero btrfs super block mirrors */
3476         memset(buf, 0, sectorsize);
3477         for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
3478                 bytenr = btrfs_sb_offset(i);
3479                 if (bytenr >= total_bytes)
3480                         break;
3481                 ret = pwrite(fd, buf, sectorsize, bytenr);
3482                 if (ret != sectorsize) {
3483                         fprintf(stderr,
3484                                 "error during zeroing superblock %d: %d\n",
3485                                 i, ret);
3486                         goto fail;
3487                 }
3488         }
3489
3490         sb_bytenr = (u64)-1;
3491         /* copy all relocated blocks back */
3492         while(1) {
3493                 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
3494                                             EXTENT_LOCKED);
3495                 if (ret)
3496                         break;
3497
3498                 ret = get_state_private(&io_tree, start, &bytenr);
3499                 BUG_ON(ret);
3500
3501                 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
3502                                   GFP_NOFS);
3503
3504                 while (start <= end) {
3505                         if (start == BTRFS_SUPER_INFO_OFFSET) {
3506                                 sb_bytenr = bytenr;
3507                                 goto next_sector;
3508                         }
3509                         ret = pread(fd, buf, sectorsize, bytenr);
3510                         if (ret < 0) {
3511                                 fprintf(stderr, "error during pread %d\n", ret);
3512                                 goto fail;
3513                         }
3514                         BUG_ON(ret != sectorsize);
3515                         ret = pwrite(fd, buf, sectorsize, start);
3516                         if (ret < 0) {
3517                                 fprintf(stderr, "error during pwrite %d\n", ret);
3518                                 goto fail;
3519                         }
3520                         BUG_ON(ret != sectorsize);
3521 next_sector:
3522                         start += sectorsize;
3523                         bytenr += sectorsize;
3524                 }
3525         }
3526
3527         ret = fsync(fd);
3528         if (ret) {
3529                 fprintf(stderr, "error during fsync %d\n", ret);
3530                 goto fail;
3531         }
3532         /*
3533          * finally, overwrite btrfs super block.
3534          */
3535         ret = pread(fd, buf, sectorsize, sb_bytenr);
3536         if (ret < 0) {
3537                 fprintf(stderr, "error during pread %d\n", ret);
3538                 goto fail;
3539         }
3540         BUG_ON(ret != sectorsize);
3541         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3542         if (ret < 0) {
3543                 fprintf(stderr, "error during pwrite %d\n", ret);
3544                 goto fail;
3545         }
3546         BUG_ON(ret != sectorsize);
3547         ret = fsync(fd);
3548         if (ret) {
3549                 fprintf(stderr, "error during fsync %d\n", ret);
3550                 goto fail;
3551         }
3552
3553         close(fd);
3554         free(buf);
3555         extent_io_tree_cleanup(&io_tree);
3556         printf("rollback complete.\n");
3557         return 0;
3558
3559 fail:
3560         if (fd != -1)
3561                 close(fd);
3562         free(buf);
3563         fprintf(stderr, "rollback aborted.\n");
3564         return -1;
3565 }
3566
3567 static void print_usage(void)
3568 {
3569         printf("usage: btrfs-convert [options] device\n");
3570         printf("options:\n");
3571         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
3572         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
3573         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
3574         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
3575         printf("\t-r|--rollback          roll back to the original filesystem\n");
3576         printf("\t-l|--label LABEL       set filesystem label\n");
3577         printf("\t-L|--copy-label        use label from converted filesystem\n");
3578         printf("\t-p|--progress          show converting progress (default)\n");
3579         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
3580         printf("\t--no-progress          show only overview, not the detailed progress\n");
3581 }
3582
3583 int main(int argc, char *argv[])
3584 {
3585         int ret;
3586         int packing = 1;
3587         int noxattr = 0;
3588         int datacsum = 1;
3589         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3590                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
3591         int rollback = 0;
3592         int copylabel = 0;
3593         int usage_error = 0;
3594         int progress = 1;
3595         char *file;
3596         char fslabel[BTRFS_LABEL_SIZE];
3597         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3598
3599         while(1) {
3600                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3601                 static const struct option long_options[] = {
3602                         { "no-progress", no_argument, NULL,
3603                                 GETOPT_VAL_NO_PROGRESS },
3604                         { "no-datasum", no_argument, NULL, 'd' },
3605                         { "no-inline", no_argument, NULL, 'n' },
3606                         { "no-xattr", no_argument, NULL, 'i' },
3607                         { "rollback", no_argument, NULL, 'r' },
3608                         { "features", required_argument, NULL, 'O' },
3609                         { "progress", no_argument, NULL, 'p' },
3610                         { "label", required_argument, NULL, 'l' },
3611                         { "copy-label", no_argument, NULL, 'L' },
3612                         { "nodesize", required_argument, NULL, 'N' },
3613                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
3614                         { NULL, 0, NULL, 0 }
3615                 };
3616                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3617
3618                 if (c < 0)
3619                         break;
3620                 switch(c) {
3621                         case 'd':
3622                                 datacsum = 0;
3623                                 break;
3624                         case 'i':
3625                                 noxattr = 1;
3626                                 break;
3627                         case 'n':
3628                                 packing = 0;
3629                                 break;
3630                         case 'N':
3631                                 nodesize = parse_size(optarg);
3632                                 break;
3633                         case 'r':
3634                                 rollback = 1;
3635                                 break;
3636                         case 'l':
3637                                 copylabel = -1;
3638                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3639                                         fprintf(stderr,
3640                                 "WARNING: label too long, trimmed to %d bytes\n",
3641                                                 BTRFS_LABEL_SIZE - 1);
3642                                 }
3643                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3644                                 break;
3645                         case 'L':
3646                                 copylabel = 1;
3647                                 break;
3648                         case 'p':
3649                                 progress = 1;
3650                                 break;
3651                         case 'O': {
3652                                 char *orig = strdup(optarg);
3653                                 char *tmp = orig;
3654
3655                                 tmp = btrfs_parse_fs_features(tmp, &features);
3656                                 if (tmp) {
3657                                         fprintf(stderr,
3658                                                 "Unrecognized filesystem feature '%s'\n",
3659                                                         tmp);
3660                                         free(orig);
3661                                         exit(1);
3662                                 }
3663                                 free(orig);
3664                                 if (features & BTRFS_FEATURE_LIST_ALL) {
3665                                         btrfs_list_all_fs_features(
3666                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3667                                         exit(0);
3668                                 }
3669                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3670                                         char buf[64];
3671
3672                                         btrfs_parse_features_to_string(buf,
3673                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3674                                         fprintf(stderr,
3675                                                 "ERROR: features not allowed for convert: %s\n",
3676                                                 buf);
3677                                         exit(1);
3678                                 }
3679
3680                                 break;
3681                                 }
3682                         case GETOPT_VAL_NO_PROGRESS:
3683                                 progress = 0;
3684                                 break;
3685                         case GETOPT_VAL_HELP:
3686                         default:
3687                                 print_usage();
3688                                 return c != GETOPT_VAL_HELP;
3689                 }
3690         }
3691         set_argv0(argv);
3692         if (check_argc_exact(argc - optind, 1)) {
3693                 print_usage();
3694                 return 1;
3695         }
3696
3697         if (rollback && (!datacsum || noxattr || !packing)) {
3698                 fprintf(stderr,
3699                         "Usage error: -d, -i, -n options do not apply to rollback\n");
3700                 usage_error++;
3701         }
3702
3703         if (usage_error) {
3704                 print_usage();
3705                 return 1;
3706         }
3707
3708         file = argv[optind];
3709         ret = check_mounted(file);
3710         if (ret < 0) {
3711                 fprintf(stderr, "Could not check mount status: %s\n",
3712                         strerror(-ret));
3713                 return 1;
3714         } else if (ret) {
3715                 fprintf(stderr, "%s is mounted\n", file);
3716                 return 1;
3717         }
3718
3719         if (rollback) {
3720                 ret = do_rollback(file);
3721         } else {
3722                 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3723                                 copylabel, fslabel, progress, features);
3724         }
3725         if (ret)
3726                 return 1;
3727         return 0;
3728 }