btrfs-progs: utils: Introduce new function for convert
[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  * Create the fs image file.
1444  */
1445 static int create_image(struct btrfs_convert_context *cctx,
1446                         struct btrfs_root *root, const char *name, int datacsum)
1447 {
1448         int ret;
1449         struct btrfs_key key;
1450         struct btrfs_key location;
1451         struct btrfs_path path;
1452         struct btrfs_inode_item btrfs_inode;
1453         struct btrfs_inode_item *inode_item;
1454         struct extent_buffer *leaf;
1455         struct btrfs_fs_info *fs_info = root->fs_info;
1456         struct btrfs_root *extent_root = fs_info->extent_root;
1457         struct btrfs_trans_handle *trans;
1458         struct btrfs_extent_item *ei;
1459         struct btrfs_extent_inline_ref *iref;
1460         struct btrfs_extent_data_ref *dref;
1461         u64 bytenr;
1462         u64 num_bytes;
1463         u64 objectid;
1464         u64 last_byte;
1465         u64 first_free;
1466         u64 total_bytes;
1467         u64 flags = BTRFS_INODE_READONLY;
1468         u32 sectorsize = root->sectorsize;
1469
1470         total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
1471         first_free =  BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
1472         first_free &= ~((u64)sectorsize - 1);
1473         if (!datacsum)
1474                 flags |= BTRFS_INODE_NODATASUM;
1475
1476         memset(&btrfs_inode, 0, sizeof(btrfs_inode));
1477         btrfs_set_stack_inode_generation(&btrfs_inode, 1);
1478         btrfs_set_stack_inode_size(&btrfs_inode, total_bytes);
1479         btrfs_set_stack_inode_nlink(&btrfs_inode, 1);
1480         btrfs_set_stack_inode_nbytes(&btrfs_inode, 0);
1481         btrfs_set_stack_inode_mode(&btrfs_inode, S_IFREG | 0400);
1482         btrfs_set_stack_inode_flags(&btrfs_inode,  flags);
1483         btrfs_init_path(&path);
1484         trans = btrfs_start_transaction(root, 1);
1485         BUG_ON(!trans);
1486
1487         objectid = btrfs_root_dirid(&root->root_item);
1488         ret = btrfs_find_free_objectid(trans, root, objectid, &objectid);
1489         if (ret)
1490                 goto fail;
1491
1492         /*
1493          * copy blocks covered by extent #0 to new positions. extent #0 is
1494          * special, we can't rely on relocate_extents_range to relocate it.
1495          */
1496         for (last_byte = 0; last_byte < first_free; last_byte += sectorsize) {
1497                 ret = custom_alloc_extent(root, sectorsize, 0, &key, 0);
1498                 if (ret)
1499                         goto fail;
1500                 ret = copy_disk_extent(root, key.objectid, last_byte,
1501                                        sectorsize);
1502                 if (ret)
1503                         goto fail;
1504                 ret = btrfs_record_file_extent(trans, root, objectid,
1505                                                &btrfs_inode, last_byte,
1506                                                key.objectid, sectorsize);
1507                 if (ret)
1508                         goto fail;
1509                 if (datacsum) {
1510                         ret = csum_disk_extent(trans, root, key.objectid,
1511                                                sectorsize);
1512                         if (ret)
1513                                 goto fail;
1514                 }
1515         }
1516
1517         while(1) {
1518                 key.objectid = last_byte;
1519                 key.offset = 0;
1520                 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1521                 ret = btrfs_search_slot(trans, fs_info->extent_root,
1522                                         &key, &path, 0, 0);
1523                 if (ret < 0)
1524                         goto fail;
1525 next:
1526                 leaf = path.nodes[0];
1527                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1528                         ret = btrfs_next_leaf(extent_root, &path);
1529                         if (ret < 0)
1530                                 goto fail;
1531                         if (ret > 0)
1532                                 break;
1533                         leaf = path.nodes[0];
1534                 }
1535                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1536                 if (last_byte > key.objectid ||
1537                     key.type != BTRFS_EXTENT_ITEM_KEY) {
1538                         path.slots[0]++;
1539                         goto next;
1540                 }
1541
1542                 bytenr = key.objectid;
1543                 num_bytes = key.offset;
1544                 ei = btrfs_item_ptr(leaf, path.slots[0],
1545                                     struct btrfs_extent_item);
1546                 if (!(btrfs_extent_flags(leaf, ei) & BTRFS_EXTENT_FLAG_DATA)) {
1547                         path.slots[0]++;
1548                         goto next;
1549                 }
1550
1551                 BUG_ON(btrfs_item_size_nr(leaf, path.slots[0]) != sizeof(*ei) +
1552                        btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY));
1553
1554                 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
1555                 key.type = btrfs_extent_inline_ref_type(leaf, iref);
1556                 BUG_ON(key.type != BTRFS_EXTENT_DATA_REF_KEY);
1557                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1558                 if (btrfs_extent_data_ref_root(leaf, dref) !=
1559                     BTRFS_FS_TREE_OBJECTID) {
1560                         path.slots[0]++;
1561                         goto next;
1562                 }
1563
1564                 if (bytenr > last_byte) {
1565                         ret = create_image_file_range(trans, root, objectid,
1566                                                       &btrfs_inode, last_byte,
1567                                                       bytenr, cctx,
1568                                                       datacsum);
1569                         if (ret)
1570                                 goto fail;
1571                 }
1572                 ret = btrfs_record_file_extent(trans, root, objectid,
1573                                                &btrfs_inode, bytenr, bytenr,
1574                                                num_bytes);
1575                 if (ret)
1576                         goto fail;
1577                 last_byte = bytenr + num_bytes;
1578                 btrfs_release_path(&path);
1579
1580                 if (trans->blocks_used >= 4096) {
1581                         ret = btrfs_commit_transaction(trans, root);
1582                         BUG_ON(ret);
1583                         trans = btrfs_start_transaction(root, 1);
1584                         BUG_ON(!trans);
1585                 }
1586         }
1587         btrfs_release_path(&path);
1588         if (total_bytes > last_byte) {
1589                 ret = create_image_file_range(trans, root, objectid,
1590                                               &btrfs_inode, last_byte,
1591                                               total_bytes, cctx,
1592                                               datacsum);
1593                 if (ret)
1594                         goto fail;
1595         }
1596
1597         ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
1598         if (ret)
1599                 goto fail;
1600
1601         location.objectid = objectid;
1602         location.offset = 0;
1603         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
1604         ret = btrfs_insert_dir_item(trans, root, name, strlen(name),
1605                                     btrfs_root_dirid(&root->root_item),
1606                                     &location, BTRFS_FT_REG_FILE, objectid);
1607         if (ret)
1608                 goto fail;
1609         ret = btrfs_insert_inode_ref(trans, root, name, strlen(name),
1610                                      objectid,
1611                                      btrfs_root_dirid(&root->root_item),
1612                                      objectid);
1613         if (ret)
1614                 goto fail;
1615         location.objectid = btrfs_root_dirid(&root->root_item);
1616         location.offset = 0;
1617         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
1618         ret = btrfs_lookup_inode(trans, root, &path, &location, 1);
1619         if (ret)
1620                 goto fail;
1621         leaf = path.nodes[0];
1622         inode_item = btrfs_item_ptr(leaf, path.slots[0],
1623                                     struct btrfs_inode_item);
1624         btrfs_set_inode_size(leaf, inode_item, strlen(name) * 2 +
1625                              btrfs_inode_size(leaf, inode_item));
1626         btrfs_mark_buffer_dirty(leaf);
1627         btrfs_release_path(&path);
1628         ret = btrfs_commit_transaction(trans, root);
1629         BUG_ON(ret);
1630 fail:
1631         btrfs_release_path(&path);
1632         return ret;
1633 }
1634
1635 static struct btrfs_root * link_subvol(struct btrfs_root *root,
1636                 const char *base, u64 root_objectid)
1637 {
1638         struct btrfs_trans_handle *trans;
1639         struct btrfs_fs_info *fs_info = root->fs_info;
1640         struct btrfs_root *tree_root = fs_info->tree_root;
1641         struct btrfs_root *new_root = NULL;
1642         struct btrfs_path *path;
1643         struct btrfs_inode_item *inode_item;
1644         struct extent_buffer *leaf;
1645         struct btrfs_key key;
1646         u64 dirid = btrfs_root_dirid(&root->root_item);
1647         u64 index = 2;
1648         char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1649         int len;
1650         int i;
1651         int ret;
1652
1653         len = strlen(base);
1654         if (len == 0 || len > BTRFS_NAME_LEN)
1655                 return NULL;
1656
1657         path = btrfs_alloc_path();
1658         BUG_ON(!path);
1659
1660         key.objectid = dirid;
1661         key.type = BTRFS_DIR_INDEX_KEY;
1662         key.offset = (u64)-1;
1663
1664         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1665         BUG_ON(ret <= 0);
1666
1667         if (path->slots[0] > 0) {
1668                 path->slots[0]--;
1669                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1670                 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1671                         index = key.offset + 1;
1672         }
1673         btrfs_release_path(path);
1674
1675         trans = btrfs_start_transaction(root, 1);
1676         BUG_ON(!trans);
1677
1678         key.objectid = dirid;
1679         key.offset = 0;
1680         key.type =  BTRFS_INODE_ITEM_KEY;
1681
1682         ret = btrfs_lookup_inode(trans, root, path, &key, 1);
1683         BUG_ON(ret);
1684         leaf = path->nodes[0];
1685         inode_item = btrfs_item_ptr(leaf, path->slots[0],
1686                                     struct btrfs_inode_item);
1687
1688         key.objectid = root_objectid;
1689         key.offset = (u64)-1;
1690         key.type = BTRFS_ROOT_ITEM_KEY;
1691
1692         memcpy(buf, base, len);
1693         for (i = 0; i < 1024; i++) {
1694                 ret = btrfs_insert_dir_item(trans, root, buf, len,
1695                                             dirid, &key, BTRFS_FT_DIR, index);
1696                 if (ret != -EEXIST)
1697                         break;
1698                 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1699                 if (len < 1 || len > BTRFS_NAME_LEN) {
1700                         ret = -EINVAL;
1701                         break;
1702                 }
1703         }
1704         if (ret)
1705                 goto fail;
1706
1707         btrfs_set_inode_size(leaf, inode_item, len * 2 +
1708                              btrfs_inode_size(leaf, inode_item));
1709         btrfs_mark_buffer_dirty(leaf);
1710         btrfs_release_path(path);
1711
1712         /* add the backref first */
1713         ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1714                                  BTRFS_ROOT_BACKREF_KEY,
1715                                  root->root_key.objectid,
1716                                  dirid, index, buf, len);
1717         BUG_ON(ret);
1718
1719         /* now add the forward ref */
1720         ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1721                                  BTRFS_ROOT_REF_KEY, root_objectid,
1722                                  dirid, index, buf, len);
1723
1724         ret = btrfs_commit_transaction(trans, root);
1725         BUG_ON(ret);
1726
1727         new_root = btrfs_read_fs_root(fs_info, &key);
1728         if (IS_ERR(new_root))
1729                 new_root = NULL;
1730 fail:
1731         btrfs_free_path(path);
1732         return new_root;
1733 }
1734
1735 static int create_chunk_mapping(struct btrfs_trans_handle *trans,
1736                                 struct btrfs_root *root)
1737 {
1738         struct btrfs_fs_info *info = root->fs_info;
1739         struct btrfs_root *chunk_root = info->chunk_root;
1740         struct btrfs_root *extent_root = info->extent_root;
1741         struct btrfs_device *device;
1742         struct btrfs_block_group_cache *cache;
1743         struct btrfs_dev_extent *extent;
1744         struct extent_buffer *leaf;
1745         struct btrfs_chunk chunk;
1746         struct btrfs_key key;
1747         struct btrfs_path path;
1748         u64 cur_start;
1749         u64 total_bytes;
1750         u64 chunk_objectid;
1751         int ret;
1752
1753         btrfs_init_path(&path);
1754
1755         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1756         chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1757
1758         BUG_ON(list_empty(&info->fs_devices->devices));
1759         device = list_entry(info->fs_devices->devices.next,
1760                             struct btrfs_device, dev_list);
1761         BUG_ON(device->devid != info->fs_devices->latest_devid);
1762
1763         /* delete device extent created by make_btrfs */
1764         key.objectid = device->devid;
1765         key.offset = 0;
1766         key.type = BTRFS_DEV_EXTENT_KEY;
1767         ret = btrfs_search_slot(trans, device->dev_root, &key, &path, -1, 1);
1768         if (ret < 0)
1769                 goto err;
1770
1771         BUG_ON(ret > 0);
1772         ret = btrfs_del_item(trans, device->dev_root, &path);
1773         if (ret)
1774                 goto err;
1775         btrfs_release_path(&path);
1776
1777         /* delete chunk item created by make_btrfs */
1778         key.objectid = chunk_objectid;
1779         key.offset = 0;
1780         key.type = BTRFS_CHUNK_ITEM_KEY;
1781         ret = btrfs_search_slot(trans, chunk_root, &key, &path, -1, 1);
1782         if (ret < 0)
1783                 goto err;
1784
1785         BUG_ON(ret > 0);
1786         ret = btrfs_del_item(trans, chunk_root, &path);
1787         if (ret)
1788                 goto err;
1789         btrfs_release_path(&path);
1790
1791         /* for each block group, create device extent and chunk item */
1792         cur_start = 0;
1793         while (cur_start < total_bytes) {
1794                 cache = btrfs_lookup_block_group(root->fs_info, cur_start);
1795                 BUG_ON(!cache);
1796
1797                 /* insert device extent */
1798                 key.objectid = device->devid;
1799                 key.offset = cache->key.objectid;
1800                 key.type = BTRFS_DEV_EXTENT_KEY;
1801                 ret = btrfs_insert_empty_item(trans, device->dev_root, &path,
1802                                               &key, sizeof(*extent));
1803                 if (ret)
1804                         goto err;
1805
1806                 leaf = path.nodes[0];
1807                 extent = btrfs_item_ptr(leaf, path.slots[0],
1808                                         struct btrfs_dev_extent);
1809
1810                 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1811                                                 chunk_root->root_key.objectid);
1812                 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1813                                                     chunk_objectid);
1814                 btrfs_set_dev_extent_chunk_offset(leaf, extent,
1815                                                   cache->key.objectid);
1816                 btrfs_set_dev_extent_length(leaf, extent, cache->key.offset);
1817                 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1818                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1819                     BTRFS_UUID_SIZE);
1820                 btrfs_mark_buffer_dirty(leaf);
1821                 btrfs_release_path(&path);
1822
1823                 /* insert chunk item */
1824                 btrfs_set_stack_chunk_length(&chunk, cache->key.offset);
1825                 btrfs_set_stack_chunk_owner(&chunk,
1826                                             extent_root->root_key.objectid);
1827                 btrfs_set_stack_chunk_stripe_len(&chunk, BTRFS_STRIPE_LEN);
1828                 btrfs_set_stack_chunk_type(&chunk, cache->flags);
1829                 btrfs_set_stack_chunk_io_align(&chunk, device->io_align);
1830                 btrfs_set_stack_chunk_io_width(&chunk, device->io_width);
1831                 btrfs_set_stack_chunk_sector_size(&chunk, device->sector_size);
1832                 btrfs_set_stack_chunk_num_stripes(&chunk, 1);
1833                 btrfs_set_stack_chunk_sub_stripes(&chunk, 0);
1834                 btrfs_set_stack_stripe_devid(&chunk.stripe, device->devid);
1835                 btrfs_set_stack_stripe_offset(&chunk.stripe,
1836                                               cache->key.objectid);
1837                 memcpy(&chunk.stripe.dev_uuid, device->uuid, BTRFS_UUID_SIZE);
1838
1839                 key.objectid = chunk_objectid;
1840                 key.offset = cache->key.objectid;
1841                 key.type = BTRFS_CHUNK_ITEM_KEY;
1842
1843                 ret = btrfs_insert_item(trans, chunk_root, &key, &chunk,
1844                                         btrfs_chunk_item_size(1));
1845                 if (ret)
1846                         goto err;
1847
1848                 cur_start = cache->key.objectid + cache->key.offset;
1849         }
1850
1851         device->bytes_used = total_bytes;
1852         ret = btrfs_update_device(trans, device);
1853 err:
1854         btrfs_release_path(&path);
1855         return ret;
1856 }
1857
1858 static int create_subvol(struct btrfs_trans_handle *trans,
1859                          struct btrfs_root *root, u64 root_objectid)
1860 {
1861         struct extent_buffer *tmp;
1862         struct btrfs_root *new_root;
1863         struct btrfs_key key;
1864         struct btrfs_root_item root_item;
1865         int ret;
1866
1867         ret = btrfs_copy_root(trans, root, root->node, &tmp,
1868                               root_objectid);
1869         BUG_ON(ret);
1870
1871         memcpy(&root_item, &root->root_item, sizeof(root_item));
1872         btrfs_set_root_bytenr(&root_item, tmp->start);
1873         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1874         btrfs_set_root_generation(&root_item, trans->transid);
1875         free_extent_buffer(tmp);
1876
1877         key.objectid = root_objectid;
1878         key.type = BTRFS_ROOT_ITEM_KEY;
1879         key.offset = trans->transid;
1880         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1881                                 &key, &root_item);
1882
1883         key.offset = (u64)-1;
1884         new_root = btrfs_read_fs_root(root->fs_info, &key);
1885         BUG_ON(!new_root || IS_ERR(new_root));
1886
1887         ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1888         BUG_ON(ret);
1889
1890         return 0;
1891 }
1892
1893 static int init_btrfs(struct btrfs_root *root)
1894 {
1895         int ret;
1896         struct btrfs_key location;
1897         struct btrfs_trans_handle *trans;
1898         struct btrfs_fs_info *fs_info = root->fs_info;
1899         struct extent_buffer *tmp;
1900
1901         trans = btrfs_start_transaction(root, 1);
1902         BUG_ON(!trans);
1903         ret = btrfs_make_block_groups(trans, root);
1904         if (ret)
1905                 goto err;
1906         ret = btrfs_fix_block_accounting(trans, root);
1907         if (ret)
1908                 goto err;
1909         ret = create_chunk_mapping(trans, root);
1910         if (ret)
1911                 goto err;
1912         ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1913                                   BTRFS_ROOT_TREE_DIR_OBJECTID);
1914         if (ret)
1915                 goto err;
1916         memcpy(&location, &root->root_key, sizeof(location));
1917         location.offset = (u64)-1;
1918         ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1919                                 btrfs_super_root_dir(fs_info->super_copy),
1920                                 &location, BTRFS_FT_DIR, 0);
1921         if (ret)
1922                 goto err;
1923         ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1924                                 location.objectid,
1925                                 btrfs_super_root_dir(fs_info->super_copy), 0);
1926         if (ret)
1927                 goto err;
1928         btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1929                              BTRFS_FIRST_FREE_OBJECTID);
1930
1931         /* subvol for fs image file */
1932         ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1933         BUG_ON(ret);
1934         /* subvol for data relocation */
1935         ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1936         BUG_ON(ret);
1937
1938         extent_buffer_get(fs_info->csum_root->node);
1939         ret = __btrfs_cow_block(trans, fs_info->csum_root,
1940                                 fs_info->csum_root->node, NULL, 0, &tmp, 0, 0);
1941         BUG_ON(ret);
1942         free_extent_buffer(tmp);
1943
1944         ret = btrfs_commit_transaction(trans, root);
1945         BUG_ON(ret);
1946 err:
1947         return ret;
1948 }
1949
1950 /*
1951  * Migrate super block to its default position and zero 0 ~ 16k
1952  */
1953 static int migrate_super_block(int fd, u64 old_bytenr, u32 sectorsize)
1954 {
1955         int ret;
1956         struct extent_buffer *buf;
1957         struct btrfs_super_block *super;
1958         u32 len;
1959         u32 bytenr;
1960
1961         BUG_ON(sectorsize < sizeof(*super));
1962         buf = malloc(sizeof(*buf) + sectorsize);
1963         if (!buf)
1964                 return -ENOMEM;
1965
1966         buf->len = sectorsize;
1967         ret = pread(fd, buf->data, sectorsize, old_bytenr);
1968         if (ret != sectorsize)
1969                 goto fail;
1970
1971         super = (struct btrfs_super_block *)buf->data;
1972         BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1973         btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1974
1975         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1976         ret = pwrite(fd, buf->data, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1977         if (ret != sectorsize)
1978                 goto fail;
1979
1980         ret = fsync(fd);
1981         if (ret)
1982                 goto fail;
1983
1984         memset(buf->data, 0, sectorsize);
1985         for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1986                 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1987                 if (len > sectorsize)
1988                         len = sectorsize;
1989                 ret = pwrite(fd, buf->data, len, bytenr);
1990                 if (ret != len) {
1991                         fprintf(stderr, "unable to zero fill device\n");
1992                         break;
1993                 }
1994                 bytenr += len;
1995         }
1996         ret = 0;
1997         fsync(fd);
1998 fail:
1999         free(buf);
2000         if (ret > 0)
2001                 ret = -1;
2002         return ret;
2003 }
2004
2005 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
2006 {
2007         struct btrfs_chunk *chunk;
2008         struct btrfs_disk_key *key;
2009         u32 sectorsize = btrfs_super_sectorsize(super);
2010
2011         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
2012         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
2013                                        sizeof(struct btrfs_disk_key));
2014
2015         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2016         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
2017         btrfs_set_disk_key_offset(key, 0);
2018
2019         btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
2020         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
2021         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
2022         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
2023         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
2024         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
2025         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
2026         btrfs_set_stack_chunk_num_stripes(chunk, 1);
2027         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
2028         chunk->stripe.devid = super->dev_item.devid;
2029         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
2030         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
2031         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
2032         return 0;
2033 }
2034
2035 static int prepare_system_chunk(int fd, u64 sb_bytenr)
2036 {
2037         int ret;
2038         struct extent_buffer *buf;
2039         struct btrfs_super_block *super;
2040
2041         BUG_ON(BTRFS_SUPER_INFO_SIZE < sizeof(*super));
2042         buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
2043         if (!buf)
2044                 return -ENOMEM;
2045
2046         buf->len = BTRFS_SUPER_INFO_SIZE;
2047         ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
2048         if (ret != BTRFS_SUPER_INFO_SIZE)
2049                 goto fail;
2050
2051         super = (struct btrfs_super_block *)buf->data;
2052         BUG_ON(btrfs_super_bytenr(super) != sb_bytenr);
2053         BUG_ON(btrfs_super_num_devices(super) != 1);
2054
2055         ret = prepare_system_chunk_sb(super);
2056         if (ret)
2057                 goto fail;
2058
2059         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
2060         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
2061         if (ret != BTRFS_SUPER_INFO_SIZE)
2062                 goto fail;
2063
2064         ret = 0;
2065 fail:
2066         free(buf);
2067         if (ret > 0)
2068                 ret = -1;
2069         return ret;
2070 }
2071
2072 static int relocate_one_reference(struct btrfs_trans_handle *trans,
2073                                   struct btrfs_root *root,
2074                                   u64 extent_start, u64 extent_size,
2075                                   struct btrfs_key *extent_key,
2076                                   struct extent_io_tree *reloc_tree)
2077 {
2078         struct extent_buffer *leaf;
2079         struct btrfs_file_extent_item *fi;
2080         struct btrfs_key key;
2081         struct btrfs_path path;
2082         struct btrfs_inode_item inode;
2083         struct blk_iterate_data data;
2084         u64 bytenr;
2085         u64 num_bytes;
2086         u64 cur_offset;
2087         u64 new_pos;
2088         u64 nbytes;
2089         u64 sector_end;
2090         u32 sectorsize = root->sectorsize;
2091         unsigned long ptr;
2092         int datacsum;
2093         int fd;
2094         int ret;
2095
2096         btrfs_init_path(&path);
2097         ret = btrfs_search_slot(trans, root, extent_key, &path, -1, 1);
2098         if (ret)
2099                 goto fail;
2100
2101         leaf = path.nodes[0];
2102         fi = btrfs_item_ptr(leaf, path.slots[0],
2103                             struct btrfs_file_extent_item);
2104         BUG_ON(btrfs_file_extent_offset(leaf, fi) > 0);
2105         if (extent_start != btrfs_file_extent_disk_bytenr(leaf, fi) ||
2106             extent_size != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
2107                 ret = 1;
2108                 goto fail;
2109         }
2110
2111         bytenr = extent_start + btrfs_file_extent_offset(leaf, fi);
2112         num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2113
2114         ret = btrfs_del_item(trans, root, &path);
2115         if (ret)
2116                 goto fail;
2117
2118         ret = btrfs_free_extent(trans, root, extent_start, extent_size, 0,
2119                                 root->root_key.objectid,
2120                                 extent_key->objectid, extent_key->offset);
2121         if (ret)
2122                 goto fail;
2123
2124         btrfs_release_path(&path);
2125
2126         key.objectid = extent_key->objectid;
2127         key.offset = 0;
2128         key.type =  BTRFS_INODE_ITEM_KEY;
2129         ret = btrfs_lookup_inode(trans, root, &path, &key, 0);
2130         if (ret)
2131                 goto fail;
2132
2133         leaf = path.nodes[0];
2134         ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2135         read_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2136         btrfs_release_path(&path);
2137
2138         BUG_ON(num_bytes & (sectorsize - 1));
2139         nbytes = btrfs_stack_inode_nbytes(&inode) - num_bytes;
2140         btrfs_set_stack_inode_nbytes(&inode, nbytes);
2141         datacsum = !(btrfs_stack_inode_flags(&inode) & BTRFS_INODE_NODATASUM);
2142
2143         init_blk_iterate_data(&data, trans, root, &inode, extent_key->objectid,
2144                               datacsum);
2145         data.first_block = extent_key->offset;
2146
2147         cur_offset = extent_key->offset;
2148         while (num_bytes > 0) {
2149                 sector_end = bytenr + sectorsize - 1;
2150                 if (test_range_bit(reloc_tree, bytenr, sector_end,
2151                                    EXTENT_LOCKED, 1)) {
2152                         ret = get_state_private(reloc_tree, bytenr, &new_pos);
2153                         BUG_ON(ret);
2154                 } else {
2155                         ret = custom_alloc_extent(root, sectorsize, 0, &key, 0);
2156                         if (ret)
2157                                 goto fail;
2158                         new_pos = key.objectid;
2159
2160                         if (cur_offset == extent_key->offset) {
2161                                 fd = root->fs_info->fs_devices->latest_bdev;
2162                                 readahead(fd, bytenr, num_bytes);
2163                         }
2164                         ret = copy_disk_extent(root, new_pos, bytenr,
2165                                                sectorsize);
2166                         if (ret)
2167                                 goto fail;
2168                         ret = set_extent_bits(reloc_tree, bytenr, sector_end,
2169                                               EXTENT_LOCKED, GFP_NOFS);
2170                         BUG_ON(ret);
2171                         ret = set_state_private(reloc_tree, bytenr, new_pos);
2172                         BUG_ON(ret);
2173                 }
2174
2175                 ret = block_iterate_proc(new_pos / sectorsize,
2176                                          cur_offset / sectorsize, &data);
2177                 if (ret < 0)
2178                         goto fail;
2179
2180                 cur_offset += sectorsize;
2181                 bytenr += sectorsize;
2182                 num_bytes -= sectorsize;
2183         }
2184
2185         if (data.num_blocks > 0) {
2186                 ret = record_file_blocks(&data, data.first_block,
2187                                          data.disk_block, data.num_blocks);
2188                 if (ret)
2189                         goto fail;
2190         }
2191
2192         key.objectid = extent_key->objectid;
2193         key.offset = 0;
2194         key.type =  BTRFS_INODE_ITEM_KEY;
2195         ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
2196         if (ret)
2197                 goto fail;
2198
2199         leaf = path.nodes[0];
2200         ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2201         write_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2202         btrfs_mark_buffer_dirty(leaf);
2203         btrfs_release_path(&path);
2204
2205 fail:
2206         btrfs_release_path(&path);
2207         return ret;
2208 }
2209
2210 static int relocate_extents_range(struct btrfs_root *fs_root,
2211                                   struct btrfs_root *image_root,
2212                                   u64 start_byte, u64 end_byte)
2213 {
2214         struct btrfs_fs_info *info = fs_root->fs_info;
2215         struct btrfs_root *extent_root = info->extent_root;
2216         struct btrfs_root *cur_root = NULL;
2217         struct btrfs_trans_handle *trans;
2218         struct btrfs_extent_data_ref *dref;
2219         struct btrfs_extent_inline_ref *iref;
2220         struct btrfs_extent_item *ei;
2221         struct extent_buffer *leaf;
2222         struct btrfs_key key;
2223         struct btrfs_key extent_key;
2224         struct btrfs_path path;
2225         struct extent_io_tree reloc_tree;
2226         unsigned long ptr;
2227         unsigned long end;
2228         u64 cur_byte;
2229         u64 num_bytes;
2230         u64 ref_root;
2231         u64 num_extents;
2232         int pass = 0;
2233         int ret;
2234
2235         btrfs_init_path(&path);
2236         extent_io_tree_init(&reloc_tree);
2237
2238         key.objectid = start_byte;
2239         key.offset = 0;
2240         key.type = BTRFS_EXTENT_ITEM_KEY;
2241         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2242         if (ret < 0)
2243                 goto fail;
2244         if (ret > 0) {
2245                 ret = btrfs_previous_item(extent_root, &path, 0,
2246                                           BTRFS_EXTENT_ITEM_KEY);
2247                 if (ret < 0)
2248                         goto fail;
2249                 if (ret == 0) {
2250                         leaf = path.nodes[0];
2251                         btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2252                         if (key.objectid + key.offset > start_byte)
2253                                 start_byte = key.objectid;
2254                 }
2255         }
2256         btrfs_release_path(&path);
2257 again:
2258         cur_root = (pass % 2 == 0) ? image_root : fs_root;
2259         num_extents = 0;
2260
2261         trans = btrfs_start_transaction(cur_root, 1);
2262         BUG_ON(!trans);
2263
2264         cur_byte = start_byte;
2265         while (1) {
2266                 key.objectid = cur_byte;
2267                 key.offset = 0;
2268                 key.type = BTRFS_EXTENT_ITEM_KEY;
2269                 ret = btrfs_search_slot(trans, extent_root,
2270                                         &key, &path, 0, 0);
2271                 if (ret < 0)
2272                         goto fail;
2273 next:
2274                 leaf = path.nodes[0];
2275                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2276                         ret = btrfs_next_leaf(extent_root, &path);
2277                         if (ret < 0)
2278                                 goto fail;
2279                         if (ret > 0)
2280                                 break;
2281                         leaf = path.nodes[0];
2282                 }
2283
2284                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2285                 if (key.objectid < cur_byte ||
2286                     key.type != BTRFS_EXTENT_ITEM_KEY) {
2287                         path.slots[0]++;
2288                         goto next;
2289                 }
2290                 if (key.objectid >= end_byte)
2291                         break;
2292
2293                 num_extents++;
2294
2295                 cur_byte = key.objectid;
2296                 num_bytes = key.offset;
2297                 ei = btrfs_item_ptr(leaf, path.slots[0],
2298                                     struct btrfs_extent_item);
2299                 BUG_ON(!(btrfs_extent_flags(leaf, ei) &
2300                          BTRFS_EXTENT_FLAG_DATA));
2301
2302                 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2303                 end = ptr + btrfs_item_size_nr(leaf, path.slots[0]);
2304
2305                 ptr += sizeof(struct btrfs_extent_item);
2306
2307                 while (ptr < end) {
2308                         iref = (struct btrfs_extent_inline_ref *)ptr;
2309                         key.type = btrfs_extent_inline_ref_type(leaf, iref);
2310                         BUG_ON(key.type != BTRFS_EXTENT_DATA_REF_KEY);
2311                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
2312                         ref_root = btrfs_extent_data_ref_root(leaf, dref);
2313                         extent_key.objectid =
2314                                 btrfs_extent_data_ref_objectid(leaf, dref);
2315                         extent_key.offset =
2316                                 btrfs_extent_data_ref_offset(leaf, dref);
2317                         extent_key.type = BTRFS_EXTENT_DATA_KEY;
2318                         BUG_ON(btrfs_extent_data_ref_count(leaf, dref) != 1);
2319
2320                         if (ref_root == cur_root->root_key.objectid)
2321                                 break;
2322
2323                         ptr += btrfs_extent_inline_ref_size(key.type);
2324                 }
2325
2326                 if (ptr >= end) {
2327                         path.slots[0]++;
2328                         goto next;
2329                 }
2330
2331                 ret = relocate_one_reference(trans, cur_root, cur_byte,
2332                                              num_bytes, &extent_key,
2333                                              &reloc_tree);
2334                 if (ret < 0)
2335                         goto fail;
2336
2337                 cur_byte += num_bytes;
2338                 btrfs_release_path(&path);
2339
2340                 if (trans->blocks_used >= 4096) {
2341                         ret = btrfs_commit_transaction(trans, cur_root);
2342                         BUG_ON(ret);
2343                         trans = btrfs_start_transaction(cur_root, 1);
2344                         BUG_ON(!trans);
2345                 }
2346         }
2347         btrfs_release_path(&path);
2348
2349         ret = btrfs_commit_transaction(trans, cur_root);
2350         BUG_ON(ret);
2351
2352         if (num_extents > 0 && pass++ < 16)
2353                 goto again;
2354
2355         ret = (num_extents > 0) ? -1 : 0;
2356 fail:
2357         btrfs_release_path(&path);
2358         extent_io_tree_cleanup(&reloc_tree);
2359         return ret;
2360 }
2361
2362 /*
2363  * relocate data in system chunk
2364  */
2365 static int cleanup_sys_chunk(struct btrfs_root *fs_root,
2366                              struct btrfs_root *image_root)
2367 {
2368         struct btrfs_block_group_cache *cache;
2369         int i, ret = 0;
2370         u64 offset = 0;
2371         u64 end_byte;
2372
2373         while(1) {
2374                 cache = btrfs_lookup_block_group(fs_root->fs_info, offset);
2375                 if (!cache)
2376                         break;
2377
2378                 end_byte = cache->key.objectid + cache->key.offset;
2379                 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2380                         ret = relocate_extents_range(fs_root, image_root,
2381                                                      cache->key.objectid,
2382                                                      end_byte);
2383                         if (ret)
2384                                 goto fail;
2385                 }
2386                 offset = end_byte;
2387         }
2388         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2389                 offset = btrfs_sb_offset(i);
2390                 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
2391
2392                 ret = relocate_extents_range(fs_root, image_root,
2393                                              offset, offset + BTRFS_STRIPE_LEN);
2394                 if (ret)
2395                         goto fail;
2396         }
2397         ret = 0;
2398 fail:
2399         return ret;
2400 }
2401
2402 static int fixup_chunk_mapping(struct btrfs_root *root)
2403 {
2404         struct btrfs_trans_handle *trans;
2405         struct btrfs_fs_info *info = root->fs_info;
2406         struct btrfs_root *chunk_root = info->chunk_root;
2407         struct extent_buffer *leaf;
2408         struct btrfs_key key;
2409         struct btrfs_path path;
2410         struct btrfs_chunk chunk;
2411         unsigned long ptr;
2412         u32 size;
2413         u64 type;
2414         int ret;
2415
2416         btrfs_init_path(&path);
2417
2418         trans = btrfs_start_transaction(root, 1);
2419         BUG_ON(!trans);
2420
2421         /*
2422          * recow the whole chunk tree. this will move all chunk tree blocks
2423          * into system block group.
2424          */
2425         memset(&key, 0, sizeof(key));
2426         while (1) {
2427                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2428                 if (ret < 0)
2429                         goto err;
2430
2431                 ret = btrfs_next_leaf(chunk_root, &path);
2432                 if (ret < 0)
2433                         goto err;
2434                 if (ret > 0)
2435                         break;
2436
2437                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2438                 btrfs_release_path(&path);
2439         }
2440         btrfs_release_path(&path);
2441
2442         /* fixup the system chunk array in super block */
2443         btrfs_set_super_sys_array_size(info->super_copy, 0);
2444
2445         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2446         key.offset = 0;
2447         key.type = BTRFS_CHUNK_ITEM_KEY;
2448
2449         ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 0);
2450         if (ret < 0)
2451                 goto err;
2452         BUG_ON(ret != 0);
2453         while(1) {
2454                 leaf = path.nodes[0];
2455                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2456                         ret = btrfs_next_leaf(chunk_root, &path);
2457                         if (ret < 0)
2458                                 goto err;
2459                         if (ret > 0)
2460                                 break;
2461                         leaf = path.nodes[0];
2462                 }
2463                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2464                 if (key.type != BTRFS_CHUNK_ITEM_KEY)
2465                         goto next;
2466
2467                 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2468                 size = btrfs_item_size_nr(leaf, path.slots[0]);
2469                 BUG_ON(size != sizeof(chunk));
2470                 read_extent_buffer(leaf, &chunk, ptr, size);
2471                 type = btrfs_stack_chunk_type(&chunk);
2472
2473                 if (!(type & BTRFS_BLOCK_GROUP_SYSTEM))
2474                         goto next;
2475
2476                 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
2477                                              &chunk, size);
2478                 if (ret)
2479                         goto err;
2480 next:
2481                 path.slots[0]++;
2482         }
2483
2484         ret = btrfs_commit_transaction(trans, root);
2485         BUG_ON(ret);
2486 err:
2487         btrfs_release_path(&path);
2488         return ret;
2489 }
2490
2491 static const struct btrfs_convert_operations ext2_convert_ops = {
2492         .name                   = "ext2",
2493         .open_fs                = ext2_open_fs,
2494         .read_used_space        = ext2_read_used_space,
2495         .alloc_block            = ext2_alloc_block,
2496         .alloc_block_range      = ext2_alloc_block_range,
2497         .copy_inodes            = ext2_copy_inodes,
2498         .test_block             = ext2_test_block,
2499         .free_block             = ext2_free_block,
2500         .free_block_range       = ext2_free_block_range,
2501         .close_fs               = ext2_close_fs,
2502 };
2503
2504 static const struct btrfs_convert_operations *convert_operations[] = {
2505         &ext2_convert_ops,
2506 };
2507
2508 static int convert_open_fs(const char *devname,
2509                            struct btrfs_convert_context *cctx)
2510 {
2511         int i;
2512
2513         memset(cctx, 0, sizeof(*cctx));
2514
2515         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2516                 int ret = convert_operations[i]->open_fs(cctx, devname);
2517
2518                 if (ret == 0) {
2519                         cctx->convert_ops = convert_operations[i];
2520                         return ret;
2521                 }
2522         }
2523
2524         fprintf(stderr, "No file system found to convert.\n");
2525         return -1;
2526 }
2527
2528 /*
2529  * Remove one reserve range from given cache tree
2530  * if min_stripe_size is non-zero, it will ensure for split case,
2531  * all its split cache extent is no smaller than @min_strip_size / 2.
2532  */
2533 static int wipe_one_reserved_range(struct cache_tree *tree,
2534                                    u64 start, u64 len, u64 min_stripe_size,
2535                                    int ensure_size)
2536 {
2537         struct cache_extent *cache;
2538         int ret;
2539
2540         BUG_ON(ensure_size && min_stripe_size == 0);
2541         /*
2542          * The logical here is simplified to handle special cases only
2543          * So we don't need to consider merge case for ensure_size
2544          */
2545         BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
2546                min_stripe_size / 2 < BTRFS_STRIPE_LEN));
2547
2548         /* Also, wipe range should already be aligned */
2549         BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
2550                start + len != round_up(start + len, BTRFS_STRIPE_LEN));
2551
2552         min_stripe_size /= 2;
2553
2554         cache = lookup_cache_extent(tree, start, len);
2555         if (!cache)
2556                 return 0;
2557
2558         if (start <= cache->start) {
2559                 /*
2560                  *      |--------cache---------|
2561                  * |-wipe-|
2562                  */
2563                 BUG_ON(start + len <= cache->start);
2564
2565                 /*
2566                  * The wipe size is smaller than min_stripe_size / 2,
2567                  * so the result length should still meet min_stripe_size
2568                  * And no need to do alignment
2569                  */
2570                 cache->size -= (start + len - cache->start);
2571                 if (cache->size == 0) {
2572                         remove_cache_extent(tree, cache);
2573                         free(cache);
2574                         return 0;
2575                 }
2576
2577                 BUG_ON(ensure_size && cache->size < min_stripe_size);
2578
2579                 cache->start = start + len;
2580                 return 0;
2581         } else if (start > cache->start && start + len < cache->start +
2582                    cache->size) {
2583                 /*
2584                  * |-------cache-----|
2585                  *      |-wipe-|
2586                  */
2587                 u64 old_len = cache->size;
2588                 u64 insert_start = start + len;
2589                 u64 insert_len;
2590
2591                 cache->size = start - cache->start;
2592                 if (ensure_size)
2593                         cache->size = max(cache->size, min_stripe_size);
2594                 cache->start = start - cache->size;
2595
2596                 /* And insert the new one */
2597                 insert_len = old_len - start - len;
2598                 if (ensure_size)
2599                         insert_len = max(insert_len, min_stripe_size);
2600
2601                 ret = add_merge_cache_extent(tree, insert_start, insert_len);
2602                 return ret;
2603         }
2604         /*
2605          * |----cache-----|
2606          *              |--wipe-|
2607          * Wipe len should be small enough and no need to expand the
2608          * remaining extent
2609          */
2610         cache->size = start - cache->start;
2611         BUG_ON(ensure_size && cache->size < min_stripe_size);
2612         return 0;
2613 }
2614
2615 /*
2616  * Remove reserved ranges from given cache_tree
2617  *
2618  * It will remove the following ranges
2619  * 1) 0~1M
2620  * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
2621  * 3) 3rd superblock, +64K
2622  *
2623  * @min_stripe must be given for safety check
2624  * and if @ensure_size is given, it will ensure affected cache_extent will be
2625  * larger than min_stripe_size
2626  */
2627 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
2628                                 int ensure_size)
2629 {
2630         int ret;
2631
2632         ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
2633                                       ensure_size);
2634         if (ret < 0)
2635                 return ret;
2636         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
2637                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2638         if (ret < 0)
2639                 return ret;
2640         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
2641                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2642         return ret;
2643 }
2644
2645 static int calculate_available_space(struct btrfs_convert_context *cctx)
2646 {
2647         struct cache_tree *used = &cctx->used;
2648         struct cache_tree *data_chunks = &cctx->data_chunks;
2649         struct cache_tree *free = &cctx->free;
2650         struct cache_extent *cache;
2651         u64 cur_off = 0;
2652         /*
2653          * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
2654          * works without need to consider overlap
2655          */
2656         u64 min_stripe_size = 2 * 16 * 1024 * 1024;
2657         int ret;
2658
2659         /* Calculate data_chunks */
2660         for (cache = first_cache_extent(used); cache;
2661              cache = next_cache_extent(cache)) {
2662                 u64 cur_len;
2663
2664                 if (cache->start + cache->size < cur_off)
2665                         continue;
2666                 if (cache->start > cur_off + min_stripe_size)
2667                         cur_off = cache->start;
2668                 cur_len = max(cache->start + cache->size - cur_off,
2669                               min_stripe_size);
2670                 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
2671                 if (ret < 0)
2672                         goto out;
2673                 cur_off += cur_len;
2674         }
2675         /*
2676          * remove reserved ranges, so we won't ever bother relocating an old
2677          * filesystem extent to other place.
2678          */
2679         ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
2680         if (ret < 0)
2681                 goto out;
2682
2683         cur_off = 0;
2684         /*
2685          * Calculate free space
2686          * Always round up the start bytenr, to avoid metadata extent corss
2687          * stripe boundary, as later mkfs_convert() won't have all the extent
2688          * allocation check
2689          */
2690         for (cache = first_cache_extent(data_chunks); cache;
2691              cache = next_cache_extent(cache)) {
2692                 if (cache->start < cur_off)
2693                         continue;
2694                 if (cache->start > cur_off) {
2695                         u64 insert_start;
2696                         u64 len;
2697
2698                         len = cache->start - round_up(cur_off,
2699                                                       BTRFS_STRIPE_LEN);
2700                         insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2701
2702                         ret = add_merge_cache_extent(free, insert_start, len);
2703                         if (ret < 0)
2704                                 goto out;
2705                 }
2706                 cur_off = cache->start + cache->size;
2707         }
2708         /* Don't forget the last range */
2709         if (cctx->total_bytes > cur_off) {
2710                 u64 len = cctx->total_bytes - cur_off;
2711                 u64 insert_start;
2712
2713                 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2714
2715                 ret = add_merge_cache_extent(free, insert_start, len);
2716                 if (ret < 0)
2717                         goto out;
2718         }
2719
2720         /* Remove reserved bytes */
2721         ret = wipe_reserved_ranges(free, min_stripe_size, 0);
2722 out:
2723         return ret;
2724 }
2725 /*
2726  * Read used space, and since we have the used space,
2727  * calcuate data_chunks and free for later mkfs
2728  */
2729 static int convert_read_used_space(struct btrfs_convert_context *cctx)
2730 {
2731         int ret;
2732
2733         ret = cctx->convert_ops->read_used_space(cctx);
2734         if (ret)
2735                 return ret;
2736
2737         ret = calculate_available_space(cctx);
2738         return ret;
2739 }
2740
2741 static int do_convert(const char *devname, int datacsum, int packing, int noxattr,
2742                 u32 nodesize, int copylabel, const char *fslabel, int progress,
2743                 u64 features)
2744 {
2745         int i, ret, blocks_per_node;
2746         int fd = -1;
2747         int is_btrfs = 0;
2748         u32 blocksize;
2749         u64 blocks[7];
2750         u64 total_bytes;
2751         u64 super_bytenr;
2752         struct btrfs_root *root;
2753         struct btrfs_root *image_root;
2754         struct btrfs_convert_context cctx;
2755         char *subvol_name = NULL;
2756         struct task_ctx ctx;
2757         char features_buf[64];
2758         struct btrfs_mkfs_config mkfs_cfg;
2759
2760         init_convert_context(&cctx);
2761         ret = convert_open_fs(devname, &cctx);
2762         if (ret)
2763                 goto fail;
2764         ret = convert_read_used_space(&cctx);
2765         if (ret)
2766                 goto fail;
2767
2768         blocksize = cctx.blocksize;
2769         total_bytes = (u64)blocksize * (u64)cctx.block_count;
2770         if (blocksize < 4096) {
2771                 fprintf(stderr, "block size is too small\n");
2772                 goto fail;
2773         }
2774         if (btrfs_check_nodesize(nodesize, blocksize, features))
2775                 goto fail;
2776         blocks_per_node = nodesize / blocksize;
2777         ret = -blocks_per_node;
2778         for (i = 0; i < 7; i++) {
2779                 if (nodesize == blocksize)
2780                         ret = convert_alloc_block(&cctx, 0, blocks + i);
2781                 else
2782                         ret = convert_alloc_block_range(&cctx,
2783                                         ret + blocks_per_node, blocks_per_node,
2784                                         blocks + i);
2785                 if (ret) {
2786                         fprintf(stderr, "not enough free space\n");
2787                         goto fail;
2788                 }
2789                 blocks[i] *= blocksize;
2790         }
2791         super_bytenr = blocks[0];
2792         fd = open(devname, O_RDWR);
2793         if (fd < 0) {
2794                 fprintf(stderr, "unable to open %s\n", devname);
2795                 goto fail;
2796         }
2797         btrfs_parse_features_to_string(features_buf, features);
2798         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2799                 strcat(features_buf, " (default)");
2800
2801         printf("create btrfs filesystem:\n");
2802         printf("\tblocksize: %u\n", blocksize);
2803         printf("\tnodesize:  %u\n", nodesize);
2804         printf("\tfeatures:  %s\n", features_buf);
2805
2806         mkfs_cfg.label = cctx.volume_name;
2807         mkfs_cfg.fs_uuid = NULL;
2808         memcpy(mkfs_cfg.blocks, blocks, sizeof(blocks));
2809         mkfs_cfg.num_bytes = total_bytes;
2810         mkfs_cfg.nodesize = nodesize;
2811         mkfs_cfg.sectorsize = blocksize;
2812         mkfs_cfg.stripesize = blocksize;
2813         mkfs_cfg.features = features;
2814
2815         ret = make_btrfs(fd, &mkfs_cfg, NULL);
2816         if (ret) {
2817                 fprintf(stderr, "unable to create initial ctree: %s\n",
2818                         strerror(-ret));
2819                 goto fail;
2820         }
2821         /* create a system chunk that maps the whole device */
2822         ret = prepare_system_chunk(fd, super_bytenr);
2823         if (ret) {
2824                 fprintf(stderr, "unable to update system chunk\n");
2825                 goto fail;
2826         }
2827         root = open_ctree_fd(fd, devname, super_bytenr, OPEN_CTREE_WRITES);
2828         if (!root) {
2829                 fprintf(stderr, "unable to open ctree\n");
2830                 goto fail;
2831         }
2832         ret = cache_free_extents(root, &cctx);
2833         if (ret) {
2834                 fprintf(stderr, "error during cache_free_extents %d\n", ret);
2835                 goto fail;
2836         }
2837         root->fs_info->extent_ops = &extent_ops;
2838         /* recover block allocation bitmap */
2839         for (i = 0; i < 7; i++) {
2840                 blocks[i] /= blocksize;
2841                 if (nodesize == blocksize)
2842                         convert_free_block(&cctx, blocks[i]);
2843                 else
2844                         convert_free_block_range(&cctx, blocks[i],
2845                                         blocks_per_node);
2846         }
2847         ret = init_btrfs(root);
2848         if (ret) {
2849                 fprintf(stderr, "unable to setup the root tree\n");
2850                 goto fail;
2851         }
2852         printf("creating btrfs metadata.\n");
2853         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2854         ctx.cur_copy_inodes = 0;
2855
2856         if (progress) {
2857                 ctx.info = task_init(print_copied_inodes, after_copied_inodes, &ctx);
2858                 task_start(ctx.info);
2859         }
2860         ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2861         if (ret) {
2862                 fprintf(stderr, "error during copy_inodes %d\n", ret);
2863                 goto fail;
2864         }
2865         if (progress) {
2866                 task_stop(ctx.info);
2867                 task_deinit(ctx.info);
2868         }
2869
2870         printf("creating %s image file.\n", cctx.convert_ops->name);
2871         ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2872         if (ret < 0) {
2873                 fprintf(stderr, "error allocating subvolume name: %s_saved\n",
2874                         cctx.convert_ops->name);
2875                 goto fail;
2876         }
2877
2878         image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2879
2880         free(subvol_name);
2881
2882         if (!image_root) {
2883                 fprintf(stderr, "unable to create subvol\n");
2884                 goto fail;
2885         }
2886         ret = create_image(&cctx, image_root, "image", datacsum);
2887         if (ret) {
2888                 fprintf(stderr, "error during create_image %d\n", ret);
2889                 goto fail;
2890         }
2891         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2892         if (copylabel == 1) {
2893                 __strncpy_null(root->fs_info->super_copy->label,
2894                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2895                 fprintf(stderr, "copy label '%s'\n",
2896                                 root->fs_info->super_copy->label);
2897         } else if (copylabel == -1) {
2898                 strcpy(root->fs_info->super_copy->label, fslabel);
2899                 fprintf(stderr, "set label to '%s'\n", fslabel);
2900         }
2901
2902         printf("cleaning up system chunk.\n");
2903         ret = cleanup_sys_chunk(root, image_root);
2904         if (ret) {
2905                 fprintf(stderr, "error during cleanup_sys_chunk %d\n", ret);
2906                 goto fail;
2907         }
2908         ret = close_ctree(root);
2909         if (ret) {
2910                 fprintf(stderr, "error during close_ctree %d\n", ret);
2911                 goto fail;
2912         }
2913         convert_close_fs(&cctx);
2914         clean_convert_context(&cctx);
2915
2916         /*
2917          * If this step succeed, we get a mountable btrfs. Otherwise
2918          * the source fs is left unchanged.
2919          */
2920         ret = migrate_super_block(fd, super_bytenr, blocksize);
2921         if (ret) {
2922                 fprintf(stderr, "unable to migrate super block\n");
2923                 goto fail;
2924         }
2925         is_btrfs = 1;
2926
2927         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2928         if (!root) {
2929                 fprintf(stderr, "unable to open ctree\n");
2930                 goto fail;
2931         }
2932         /* move chunk tree into system chunk. */
2933         ret = fixup_chunk_mapping(root);
2934         if (ret) {
2935                 fprintf(stderr, "error during fixup_chunk_tree\n");
2936                 goto fail;
2937         }
2938         ret = close_ctree(root);
2939         close(fd);
2940
2941         printf("conversion complete.\n");
2942         return 0;
2943 fail:
2944         clean_convert_context(&cctx);
2945         if (fd != -1)
2946                 close(fd);
2947         if (is_btrfs)
2948                 fprintf(stderr,
2949                         "WARNING: an error occured during chunk mapping fixup, filesystem mountable but not finalized\n");
2950         else
2951                 fprintf(stderr, "conversion aborted\n");
2952         return -1;
2953 }
2954
2955 static int may_rollback(struct btrfs_root *root)
2956 {
2957         struct btrfs_fs_info *info = root->fs_info;
2958         struct btrfs_multi_bio *multi = NULL;
2959         u64 bytenr;
2960         u64 length;
2961         u64 physical;
2962         u64 total_bytes;
2963         int num_stripes;
2964         int ret;
2965
2966         if (btrfs_super_num_devices(info->super_copy) != 1)
2967                 goto fail;
2968
2969         bytenr = BTRFS_SUPER_INFO_OFFSET;
2970         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2971
2972         while (1) {
2973                 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2974                                       &length, &multi, 0, NULL);
2975                 if (ret) {
2976                         if (ret == -ENOENT) {
2977                                 /* removed block group at the tail */
2978                                 if (length == (u64)-1)
2979                                         break;
2980
2981                                 /* removed block group in the middle */
2982                                 goto next;
2983                         }
2984                         goto fail;
2985                 }
2986
2987                 num_stripes = multi->num_stripes;
2988                 physical = multi->stripes[0].physical;
2989                 kfree(multi);
2990
2991                 if (num_stripes != 1 || physical != bytenr)
2992                         goto fail;
2993 next:
2994                 bytenr += length;
2995                 if (bytenr >= total_bytes)
2996                         break;
2997         }
2998         return 0;
2999 fail:
3000         return -1;
3001 }
3002
3003 static int do_rollback(const char *devname)
3004 {
3005         int fd = -1;
3006         int ret;
3007         int i;
3008         struct btrfs_root *root;
3009         struct btrfs_root *image_root;
3010         struct btrfs_root *chunk_root;
3011         struct btrfs_dir_item *dir;
3012         struct btrfs_inode_item *inode;
3013         struct btrfs_file_extent_item *fi;
3014         struct btrfs_trans_handle *trans;
3015         struct extent_buffer *leaf;
3016         struct btrfs_block_group_cache *cache1;
3017         struct btrfs_block_group_cache *cache2;
3018         struct btrfs_key key;
3019         struct btrfs_path path;
3020         struct extent_io_tree io_tree;
3021         char *buf = NULL;
3022         char *name;
3023         u64 bytenr;
3024         u64 num_bytes;
3025         u64 root_dir;
3026         u64 objectid;
3027         u64 offset;
3028         u64 start;
3029         u64 end;
3030         u64 sb_bytenr;
3031         u64 first_free;
3032         u64 total_bytes;
3033         u32 sectorsize;
3034
3035         extent_io_tree_init(&io_tree);
3036
3037         fd = open(devname, O_RDWR);
3038         if (fd < 0) {
3039                 fprintf(stderr, "unable to open %s\n", devname);
3040                 goto fail;
3041         }
3042         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
3043         if (!root) {
3044                 fprintf(stderr, "unable to open ctree\n");
3045                 goto fail;
3046         }
3047         ret = may_rollback(root);
3048         if (ret < 0) {
3049                 fprintf(stderr, "unable to do rollback\n");
3050                 goto fail;
3051         }
3052
3053         sectorsize = root->sectorsize;
3054         buf = malloc(sectorsize);
3055         if (!buf) {
3056                 fprintf(stderr, "unable to allocate memory\n");
3057                 goto fail;
3058         }
3059
3060         btrfs_init_path(&path);
3061
3062         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
3063         key.type = BTRFS_ROOT_BACKREF_KEY;
3064         key.offset = BTRFS_FS_TREE_OBJECTID;
3065         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
3066                                 0);
3067         btrfs_release_path(&path);
3068         if (ret > 0) {
3069                 fprintf(stderr,
3070                 "ERROR: unable to convert ext2 image subvolume, is it deleted?\n");
3071                 goto fail;
3072         } else if (ret < 0) {
3073                 fprintf(stderr,
3074                         "ERROR: unable to open ext2_saved, id=%llu: %s\n",
3075                         (unsigned long long)key.objectid, strerror(-ret));
3076                 goto fail;
3077         }
3078
3079         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
3080         key.type = BTRFS_ROOT_ITEM_KEY;
3081         key.offset = (u64)-1;
3082         image_root = btrfs_read_fs_root(root->fs_info, &key);
3083         if (!image_root || IS_ERR(image_root)) {
3084                 fprintf(stderr, "unable to open subvol %llu\n",
3085                         (unsigned long long)key.objectid);
3086                 goto fail;
3087         }
3088
3089         name = "image";
3090         root_dir = btrfs_root_dirid(&root->root_item);
3091         dir = btrfs_lookup_dir_item(NULL, image_root, &path,
3092                                    root_dir, name, strlen(name), 0);
3093         if (!dir || IS_ERR(dir)) {
3094                 fprintf(stderr, "unable to find file %s\n", name);
3095                 goto fail;
3096         }
3097         leaf = path.nodes[0];
3098         btrfs_dir_item_key_to_cpu(leaf, dir, &key);
3099         btrfs_release_path(&path);
3100
3101         objectid = key.objectid;
3102
3103         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
3104         if (ret) {
3105                 fprintf(stderr, "unable to find inode item\n");
3106                 goto fail;
3107         }
3108         leaf = path.nodes[0];
3109         inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
3110         total_bytes = btrfs_inode_size(leaf, inode);
3111         btrfs_release_path(&path);
3112
3113         key.objectid = objectid;
3114         key.offset = 0;
3115         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
3116         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
3117         if (ret != 0) {
3118                 fprintf(stderr, "unable to find first file extent\n");
3119                 btrfs_release_path(&path);
3120                 goto fail;
3121         }
3122
3123         /* build mapping tree for the relocated blocks */
3124         for (offset = 0; offset < total_bytes; ) {
3125                 leaf = path.nodes[0];
3126                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3127                         ret = btrfs_next_leaf(root, &path);
3128                         if (ret != 0)
3129                                 break;  
3130                         continue;
3131                 }
3132
3133                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3134                 if (key.objectid != objectid || key.offset != offset ||
3135                     btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3136                         break;
3137
3138                 fi = btrfs_item_ptr(leaf, path.slots[0],
3139                                     struct btrfs_file_extent_item);
3140                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
3141                         break;
3142                 if (btrfs_file_extent_compression(leaf, fi) ||
3143                     btrfs_file_extent_encryption(leaf, fi) ||
3144                     btrfs_file_extent_other_encoding(leaf, fi))
3145                         break;
3146
3147                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
3148                 /* skip holes and direct mapped extents */
3149                 if (bytenr == 0 || bytenr == offset)
3150                         goto next_extent;
3151
3152                 bytenr += btrfs_file_extent_offset(leaf, fi);
3153                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
3154
3155                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
3156                 cache2 =  btrfs_lookup_block_group(root->fs_info,
3157                                                    offset + num_bytes - 1);
3158                 if (!cache1 || cache1 != cache2 ||
3159                     (!(cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM) &&
3160                      !intersect_with_sb(offset, num_bytes)))
3161                         break;
3162
3163                 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
3164                                 EXTENT_LOCKED, GFP_NOFS);
3165                 set_state_private(&io_tree, offset, bytenr);
3166 next_extent:
3167                 offset += btrfs_file_extent_num_bytes(leaf, fi);
3168                 path.slots[0]++;
3169         }
3170         btrfs_release_path(&path);
3171
3172         if (offset < total_bytes) {
3173                 fprintf(stderr, "unable to build extent mapping\n");
3174                 goto fail;
3175         }
3176
3177         first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
3178         first_free &= ~((u64)sectorsize - 1);
3179         /* backup for extent #0 should exist */
3180         if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
3181                 fprintf(stderr, "no backup for the first extent\n");
3182                 goto fail;
3183         }
3184         /* force no allocation from system block group */
3185         root->fs_info->system_allocs = -1;
3186         trans = btrfs_start_transaction(root, 1);
3187         BUG_ON(!trans);
3188         /*
3189          * recow the whole chunk tree, this will remove all chunk tree blocks
3190          * from system block group
3191          */
3192         chunk_root = root->fs_info->chunk_root;
3193         memset(&key, 0, sizeof(key));
3194         while (1) {
3195                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
3196                 if (ret < 0)
3197                         break;
3198
3199                 ret = btrfs_next_leaf(chunk_root, &path);
3200                 if (ret)
3201                         break;
3202
3203                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
3204                 btrfs_release_path(&path);
3205         }
3206         btrfs_release_path(&path);
3207
3208         offset = 0;
3209         num_bytes = 0;
3210         while(1) {
3211                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
3212                 if (!cache1)
3213                         break;
3214
3215                 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
3216                         num_bytes += btrfs_block_group_used(&cache1->item);
3217
3218                 offset = cache1->key.objectid + cache1->key.offset;
3219         }
3220         /* only extent #0 left in system block group? */
3221         if (num_bytes > first_free) {
3222                 fprintf(stderr, "unable to empty system block group\n");
3223                 goto fail;
3224         }
3225         /* create a system chunk that maps the whole device */
3226         ret = prepare_system_chunk_sb(root->fs_info->super_copy);
3227         if (ret) {
3228                 fprintf(stderr, "unable to update system chunk\n");
3229                 goto fail;
3230         }
3231
3232         ret = btrfs_commit_transaction(trans, root);
3233         BUG_ON(ret);
3234
3235         ret = close_ctree(root);
3236         if (ret) {
3237                 fprintf(stderr, "error during close_ctree %d\n", ret);
3238                 goto fail;
3239         }
3240
3241         /* zero btrfs super block mirrors */
3242         memset(buf, 0, sectorsize);
3243         for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
3244                 bytenr = btrfs_sb_offset(i);
3245                 if (bytenr >= total_bytes)
3246                         break;
3247                 ret = pwrite(fd, buf, sectorsize, bytenr);
3248                 if (ret != sectorsize) {
3249                         fprintf(stderr,
3250                                 "error during zeroing superblock %d: %d\n",
3251                                 i, ret);
3252                         goto fail;
3253                 }
3254         }
3255
3256         sb_bytenr = (u64)-1;
3257         /* copy all relocated blocks back */
3258         while(1) {
3259                 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
3260                                             EXTENT_LOCKED);
3261                 if (ret)
3262                         break;
3263
3264                 ret = get_state_private(&io_tree, start, &bytenr);
3265                 BUG_ON(ret);
3266
3267                 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
3268                                   GFP_NOFS);
3269
3270                 while (start <= end) {
3271                         if (start == BTRFS_SUPER_INFO_OFFSET) {
3272                                 sb_bytenr = bytenr;
3273                                 goto next_sector;
3274                         }
3275                         ret = pread(fd, buf, sectorsize, bytenr);
3276                         if (ret < 0) {
3277                                 fprintf(stderr, "error during pread %d\n", ret);
3278                                 goto fail;
3279                         }
3280                         BUG_ON(ret != sectorsize);
3281                         ret = pwrite(fd, buf, sectorsize, start);
3282                         if (ret < 0) {
3283                                 fprintf(stderr, "error during pwrite %d\n", ret);
3284                                 goto fail;
3285                         }
3286                         BUG_ON(ret != sectorsize);
3287 next_sector:
3288                         start += sectorsize;
3289                         bytenr += sectorsize;
3290                 }
3291         }
3292
3293         ret = fsync(fd);
3294         if (ret) {
3295                 fprintf(stderr, "error during fsync %d\n", ret);
3296                 goto fail;
3297         }
3298         /*
3299          * finally, overwrite btrfs super block.
3300          */
3301         ret = pread(fd, buf, sectorsize, sb_bytenr);
3302         if (ret < 0) {
3303                 fprintf(stderr, "error during pread %d\n", ret);
3304                 goto fail;
3305         }
3306         BUG_ON(ret != sectorsize);
3307         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3308         if (ret < 0) {
3309                 fprintf(stderr, "error during pwrite %d\n", ret);
3310                 goto fail;
3311         }
3312         BUG_ON(ret != sectorsize);
3313         ret = fsync(fd);
3314         if (ret) {
3315                 fprintf(stderr, "error during fsync %d\n", ret);
3316                 goto fail;
3317         }
3318
3319         close(fd);
3320         free(buf);
3321         extent_io_tree_cleanup(&io_tree);
3322         printf("rollback complete.\n");
3323         return 0;
3324
3325 fail:
3326         if (fd != -1)
3327                 close(fd);
3328         free(buf);
3329         fprintf(stderr, "rollback aborted.\n");
3330         return -1;
3331 }
3332
3333 static void print_usage(void)
3334 {
3335         printf("usage: btrfs-convert [options] device\n");
3336         printf("options:\n");
3337         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
3338         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
3339         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
3340         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
3341         printf("\t-r|--rollback          roll back to the original filesystem\n");
3342         printf("\t-l|--label LABEL       set filesystem label\n");
3343         printf("\t-L|--copy-label        use label from converted filesystem\n");
3344         printf("\t-p|--progress          show converting progress (default)\n");
3345         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
3346         printf("\t--no-progress          show only overview, not the detailed progress\n");
3347 }
3348
3349 int main(int argc, char *argv[])
3350 {
3351         int ret;
3352         int packing = 1;
3353         int noxattr = 0;
3354         int datacsum = 1;
3355         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3356                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
3357         int rollback = 0;
3358         int copylabel = 0;
3359         int usage_error = 0;
3360         int progress = 1;
3361         char *file;
3362         char fslabel[BTRFS_LABEL_SIZE];
3363         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3364
3365         while(1) {
3366                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3367                 static const struct option long_options[] = {
3368                         { "no-progress", no_argument, NULL,
3369                                 GETOPT_VAL_NO_PROGRESS },
3370                         { "no-datasum", no_argument, NULL, 'd' },
3371                         { "no-inline", no_argument, NULL, 'n' },
3372                         { "no-xattr", no_argument, NULL, 'i' },
3373                         { "rollback", no_argument, NULL, 'r' },
3374                         { "features", required_argument, NULL, 'O' },
3375                         { "progress", no_argument, NULL, 'p' },
3376                         { "label", required_argument, NULL, 'l' },
3377                         { "copy-label", no_argument, NULL, 'L' },
3378                         { "nodesize", required_argument, NULL, 'N' },
3379                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
3380                         { NULL, 0, NULL, 0 }
3381                 };
3382                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3383
3384                 if (c < 0)
3385                         break;
3386                 switch(c) {
3387                         case 'd':
3388                                 datacsum = 0;
3389                                 break;
3390                         case 'i':
3391                                 noxattr = 1;
3392                                 break;
3393                         case 'n':
3394                                 packing = 0;
3395                                 break;
3396                         case 'N':
3397                                 nodesize = parse_size(optarg);
3398                                 break;
3399                         case 'r':
3400                                 rollback = 1;
3401                                 break;
3402                         case 'l':
3403                                 copylabel = -1;
3404                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3405                                         fprintf(stderr,
3406                                 "WARNING: label too long, trimmed to %d bytes\n",
3407                                                 BTRFS_LABEL_SIZE - 1);
3408                                 }
3409                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3410                                 break;
3411                         case 'L':
3412                                 copylabel = 1;
3413                                 break;
3414                         case 'p':
3415                                 progress = 1;
3416                                 break;
3417                         case 'O': {
3418                                 char *orig = strdup(optarg);
3419                                 char *tmp = orig;
3420
3421                                 tmp = btrfs_parse_fs_features(tmp, &features);
3422                                 if (tmp) {
3423                                         fprintf(stderr,
3424                                                 "Unrecognized filesystem feature '%s'\n",
3425                                                         tmp);
3426                                         free(orig);
3427                                         exit(1);
3428                                 }
3429                                 free(orig);
3430                                 if (features & BTRFS_FEATURE_LIST_ALL) {
3431                                         btrfs_list_all_fs_features(
3432                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3433                                         exit(0);
3434                                 }
3435                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3436                                         char buf[64];
3437
3438                                         btrfs_parse_features_to_string(buf,
3439                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3440                                         fprintf(stderr,
3441                                                 "ERROR: features not allowed for convert: %s\n",
3442                                                 buf);
3443                                         exit(1);
3444                                 }
3445
3446                                 break;
3447                                 }
3448                         case GETOPT_VAL_NO_PROGRESS:
3449                                 progress = 0;
3450                                 break;
3451                         case GETOPT_VAL_HELP:
3452                         default:
3453                                 print_usage();
3454                                 return c != GETOPT_VAL_HELP;
3455                 }
3456         }
3457         set_argv0(argv);
3458         if (check_argc_exact(argc - optind, 1)) {
3459                 print_usage();
3460                 return 1;
3461         }
3462
3463         if (rollback && (!datacsum || noxattr || !packing)) {
3464                 fprintf(stderr,
3465                         "Usage error: -d, -i, -n options do not apply to rollback\n");
3466                 usage_error++;
3467         }
3468
3469         if (usage_error) {
3470                 print_usage();
3471                 return 1;
3472         }
3473
3474         file = argv[optind];
3475         ret = check_mounted(file);
3476         if (ret < 0) {
3477                 fprintf(stderr, "Could not check mount status: %s\n",
3478                         strerror(-ret));
3479                 return 1;
3480         } else if (ret) {
3481                 fprintf(stderr, "%s is mounted\n", file);
3482                 return 1;
3483         }
3484
3485         if (rollback) {
3486                 ret = do_rollback(file);
3487         } else {
3488                 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3489                                 copylabel, fslabel, progress, features);
3490         }
3491         if (ret)
3492                 return 1;
3493         return 0;
3494 }