btrfs-progs: Introduce function to create convert data chunks
[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 /*
1894  * New make_btrfs_v2() has handle system and meta chunks quite well.
1895  * So only need to add remaining data chunks.
1896  */
1897 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1898                                           struct btrfs_fs_info *fs_info,
1899                                           struct btrfs_mkfs_config *cfg,
1900                                           struct btrfs_convert_context *cctx)
1901 {
1902         struct btrfs_root *extent_root = fs_info->extent_root;
1903         struct cache_tree *data_chunks = &cctx->data_chunks;
1904         struct cache_extent *cache;
1905         u64 max_chunk_size;
1906         int ret = 0;
1907
1908         /*
1909          * Don't create data chunk over 10% of the convert device
1910          * And for single chunk, don't create chunk larger than 1G.
1911          */
1912         max_chunk_size = cfg->num_bytes / 10;
1913         max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1914         max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1915
1916         for (cache = first_cache_extent(data_chunks); cache;
1917              cache = next_cache_extent(cache)) {
1918                 u64 cur = cache->start;
1919
1920                 while (cur < cache->start + cache->size) {
1921                         u64 len;
1922                         u64 cur_backup = cur;
1923
1924                         len = min(max_chunk_size,
1925                                   cache->start + cache->size - cur);
1926                         ret = btrfs_alloc_data_chunk(trans, extent_root,
1927                                         &cur_backup, len,
1928                                         BTRFS_BLOCK_GROUP_DATA, 1);
1929                         if (ret < 0)
1930                                 break;
1931                         ret = btrfs_make_block_group(trans, extent_root, 0,
1932                                         BTRFS_BLOCK_GROUP_DATA,
1933                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1934                                         cur, len);
1935                         if (ret < 0)
1936                                 break;
1937                         cur += len;
1938                 }
1939         }
1940         return ret;
1941 }
1942
1943 static int init_btrfs(struct btrfs_root *root)
1944 {
1945         int ret;
1946         struct btrfs_key location;
1947         struct btrfs_trans_handle *trans;
1948         struct btrfs_fs_info *fs_info = root->fs_info;
1949         struct extent_buffer *tmp;
1950
1951         trans = btrfs_start_transaction(root, 1);
1952         BUG_ON(!trans);
1953         ret = btrfs_make_block_groups(trans, root);
1954         if (ret)
1955                 goto err;
1956         ret = btrfs_fix_block_accounting(trans, root);
1957         if (ret)
1958                 goto err;
1959         ret = create_chunk_mapping(trans, root);
1960         if (ret)
1961                 goto err;
1962         ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1963                                   BTRFS_ROOT_TREE_DIR_OBJECTID);
1964         if (ret)
1965                 goto err;
1966         memcpy(&location, &root->root_key, sizeof(location));
1967         location.offset = (u64)-1;
1968         ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1969                                 btrfs_super_root_dir(fs_info->super_copy),
1970                                 &location, BTRFS_FT_DIR, 0);
1971         if (ret)
1972                 goto err;
1973         ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1974                                 location.objectid,
1975                                 btrfs_super_root_dir(fs_info->super_copy), 0);
1976         if (ret)
1977                 goto err;
1978         btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1979                              BTRFS_FIRST_FREE_OBJECTID);
1980
1981         /* subvol for fs image file */
1982         ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1983         BUG_ON(ret);
1984         /* subvol for data relocation */
1985         ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1986         BUG_ON(ret);
1987
1988         extent_buffer_get(fs_info->csum_root->node);
1989         ret = __btrfs_cow_block(trans, fs_info->csum_root,
1990                                 fs_info->csum_root->node, NULL, 0, &tmp, 0, 0);
1991         BUG_ON(ret);
1992         free_extent_buffer(tmp);
1993
1994         ret = btrfs_commit_transaction(trans, root);
1995         BUG_ON(ret);
1996 err:
1997         return ret;
1998 }
1999
2000 /*
2001  * Migrate super block to its default position and zero 0 ~ 16k
2002  */
2003 static int migrate_super_block(int fd, u64 old_bytenr, u32 sectorsize)
2004 {
2005         int ret;
2006         struct extent_buffer *buf;
2007         struct btrfs_super_block *super;
2008         u32 len;
2009         u32 bytenr;
2010
2011         BUG_ON(sectorsize < sizeof(*super));
2012         buf = malloc(sizeof(*buf) + sectorsize);
2013         if (!buf)
2014                 return -ENOMEM;
2015
2016         buf->len = sectorsize;
2017         ret = pread(fd, buf->data, sectorsize, old_bytenr);
2018         if (ret != sectorsize)
2019                 goto fail;
2020
2021         super = (struct btrfs_super_block *)buf->data;
2022         BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
2023         btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
2024
2025         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
2026         ret = pwrite(fd, buf->data, sectorsize, BTRFS_SUPER_INFO_OFFSET);
2027         if (ret != sectorsize)
2028                 goto fail;
2029
2030         ret = fsync(fd);
2031         if (ret)
2032                 goto fail;
2033
2034         memset(buf->data, 0, sectorsize);
2035         for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
2036                 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
2037                 if (len > sectorsize)
2038                         len = sectorsize;
2039                 ret = pwrite(fd, buf->data, len, bytenr);
2040                 if (ret != len) {
2041                         fprintf(stderr, "unable to zero fill device\n");
2042                         break;
2043                 }
2044                 bytenr += len;
2045         }
2046         ret = 0;
2047         fsync(fd);
2048 fail:
2049         free(buf);
2050         if (ret > 0)
2051                 ret = -1;
2052         return ret;
2053 }
2054
2055 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
2056 {
2057         struct btrfs_chunk *chunk;
2058         struct btrfs_disk_key *key;
2059         u32 sectorsize = btrfs_super_sectorsize(super);
2060
2061         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
2062         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
2063                                        sizeof(struct btrfs_disk_key));
2064
2065         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2066         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
2067         btrfs_set_disk_key_offset(key, 0);
2068
2069         btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
2070         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
2071         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
2072         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
2073         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
2074         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
2075         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
2076         btrfs_set_stack_chunk_num_stripes(chunk, 1);
2077         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
2078         chunk->stripe.devid = super->dev_item.devid;
2079         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
2080         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
2081         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
2082         return 0;
2083 }
2084
2085 static int prepare_system_chunk(int fd, u64 sb_bytenr)
2086 {
2087         int ret;
2088         struct extent_buffer *buf;
2089         struct btrfs_super_block *super;
2090
2091         BUG_ON(BTRFS_SUPER_INFO_SIZE < sizeof(*super));
2092         buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
2093         if (!buf)
2094                 return -ENOMEM;
2095
2096         buf->len = BTRFS_SUPER_INFO_SIZE;
2097         ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
2098         if (ret != BTRFS_SUPER_INFO_SIZE)
2099                 goto fail;
2100
2101         super = (struct btrfs_super_block *)buf->data;
2102         BUG_ON(btrfs_super_bytenr(super) != sb_bytenr);
2103         BUG_ON(btrfs_super_num_devices(super) != 1);
2104
2105         ret = prepare_system_chunk_sb(super);
2106         if (ret)
2107                 goto fail;
2108
2109         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
2110         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
2111         if (ret != BTRFS_SUPER_INFO_SIZE)
2112                 goto fail;
2113
2114         ret = 0;
2115 fail:
2116         free(buf);
2117         if (ret > 0)
2118                 ret = -1;
2119         return ret;
2120 }
2121
2122 static int relocate_one_reference(struct btrfs_trans_handle *trans,
2123                                   struct btrfs_root *root,
2124                                   u64 extent_start, u64 extent_size,
2125                                   struct btrfs_key *extent_key,
2126                                   struct extent_io_tree *reloc_tree)
2127 {
2128         struct extent_buffer *leaf;
2129         struct btrfs_file_extent_item *fi;
2130         struct btrfs_key key;
2131         struct btrfs_path path;
2132         struct btrfs_inode_item inode;
2133         struct blk_iterate_data data;
2134         u64 bytenr;
2135         u64 num_bytes;
2136         u64 cur_offset;
2137         u64 new_pos;
2138         u64 nbytes;
2139         u64 sector_end;
2140         u32 sectorsize = root->sectorsize;
2141         unsigned long ptr;
2142         int datacsum;
2143         int fd;
2144         int ret;
2145
2146         btrfs_init_path(&path);
2147         ret = btrfs_search_slot(trans, root, extent_key, &path, -1, 1);
2148         if (ret)
2149                 goto fail;
2150
2151         leaf = path.nodes[0];
2152         fi = btrfs_item_ptr(leaf, path.slots[0],
2153                             struct btrfs_file_extent_item);
2154         BUG_ON(btrfs_file_extent_offset(leaf, fi) > 0);
2155         if (extent_start != btrfs_file_extent_disk_bytenr(leaf, fi) ||
2156             extent_size != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
2157                 ret = 1;
2158                 goto fail;
2159         }
2160
2161         bytenr = extent_start + btrfs_file_extent_offset(leaf, fi);
2162         num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2163
2164         ret = btrfs_del_item(trans, root, &path);
2165         if (ret)
2166                 goto fail;
2167
2168         ret = btrfs_free_extent(trans, root, extent_start, extent_size, 0,
2169                                 root->root_key.objectid,
2170                                 extent_key->objectid, extent_key->offset);
2171         if (ret)
2172                 goto fail;
2173
2174         btrfs_release_path(&path);
2175
2176         key.objectid = extent_key->objectid;
2177         key.offset = 0;
2178         key.type =  BTRFS_INODE_ITEM_KEY;
2179         ret = btrfs_lookup_inode(trans, root, &path, &key, 0);
2180         if (ret)
2181                 goto fail;
2182
2183         leaf = path.nodes[0];
2184         ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2185         read_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2186         btrfs_release_path(&path);
2187
2188         BUG_ON(num_bytes & (sectorsize - 1));
2189         nbytes = btrfs_stack_inode_nbytes(&inode) - num_bytes;
2190         btrfs_set_stack_inode_nbytes(&inode, nbytes);
2191         datacsum = !(btrfs_stack_inode_flags(&inode) & BTRFS_INODE_NODATASUM);
2192
2193         init_blk_iterate_data(&data, trans, root, &inode, extent_key->objectid,
2194                               datacsum);
2195         data.first_block = extent_key->offset;
2196
2197         cur_offset = extent_key->offset;
2198         while (num_bytes > 0) {
2199                 sector_end = bytenr + sectorsize - 1;
2200                 if (test_range_bit(reloc_tree, bytenr, sector_end,
2201                                    EXTENT_LOCKED, 1)) {
2202                         ret = get_state_private(reloc_tree, bytenr, &new_pos);
2203                         BUG_ON(ret);
2204                 } else {
2205                         ret = custom_alloc_extent(root, sectorsize, 0, &key, 0);
2206                         if (ret)
2207                                 goto fail;
2208                         new_pos = key.objectid;
2209
2210                         if (cur_offset == extent_key->offset) {
2211                                 fd = root->fs_info->fs_devices->latest_bdev;
2212                                 readahead(fd, bytenr, num_bytes);
2213                         }
2214                         ret = copy_disk_extent(root, new_pos, bytenr,
2215                                                sectorsize);
2216                         if (ret)
2217                                 goto fail;
2218                         ret = set_extent_bits(reloc_tree, bytenr, sector_end,
2219                                               EXTENT_LOCKED, GFP_NOFS);
2220                         BUG_ON(ret);
2221                         ret = set_state_private(reloc_tree, bytenr, new_pos);
2222                         BUG_ON(ret);
2223                 }
2224
2225                 ret = block_iterate_proc(new_pos / sectorsize,
2226                                          cur_offset / sectorsize, &data);
2227                 if (ret < 0)
2228                         goto fail;
2229
2230                 cur_offset += sectorsize;
2231                 bytenr += sectorsize;
2232                 num_bytes -= sectorsize;
2233         }
2234
2235         if (data.num_blocks > 0) {
2236                 ret = record_file_blocks(&data, data.first_block,
2237                                          data.disk_block, data.num_blocks);
2238                 if (ret)
2239                         goto fail;
2240         }
2241
2242         key.objectid = extent_key->objectid;
2243         key.offset = 0;
2244         key.type =  BTRFS_INODE_ITEM_KEY;
2245         ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
2246         if (ret)
2247                 goto fail;
2248
2249         leaf = path.nodes[0];
2250         ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2251         write_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2252         btrfs_mark_buffer_dirty(leaf);
2253         btrfs_release_path(&path);
2254
2255 fail:
2256         btrfs_release_path(&path);
2257         return ret;
2258 }
2259
2260 static int relocate_extents_range(struct btrfs_root *fs_root,
2261                                   struct btrfs_root *image_root,
2262                                   u64 start_byte, u64 end_byte)
2263 {
2264         struct btrfs_fs_info *info = fs_root->fs_info;
2265         struct btrfs_root *extent_root = info->extent_root;
2266         struct btrfs_root *cur_root = NULL;
2267         struct btrfs_trans_handle *trans;
2268         struct btrfs_extent_data_ref *dref;
2269         struct btrfs_extent_inline_ref *iref;
2270         struct btrfs_extent_item *ei;
2271         struct extent_buffer *leaf;
2272         struct btrfs_key key;
2273         struct btrfs_key extent_key;
2274         struct btrfs_path path;
2275         struct extent_io_tree reloc_tree;
2276         unsigned long ptr;
2277         unsigned long end;
2278         u64 cur_byte;
2279         u64 num_bytes;
2280         u64 ref_root;
2281         u64 num_extents;
2282         int pass = 0;
2283         int ret;
2284
2285         btrfs_init_path(&path);
2286         extent_io_tree_init(&reloc_tree);
2287
2288         key.objectid = start_byte;
2289         key.offset = 0;
2290         key.type = BTRFS_EXTENT_ITEM_KEY;
2291         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2292         if (ret < 0)
2293                 goto fail;
2294         if (ret > 0) {
2295                 ret = btrfs_previous_item(extent_root, &path, 0,
2296                                           BTRFS_EXTENT_ITEM_KEY);
2297                 if (ret < 0)
2298                         goto fail;
2299                 if (ret == 0) {
2300                         leaf = path.nodes[0];
2301                         btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2302                         if (key.objectid + key.offset > start_byte)
2303                                 start_byte = key.objectid;
2304                 }
2305         }
2306         btrfs_release_path(&path);
2307 again:
2308         cur_root = (pass % 2 == 0) ? image_root : fs_root;
2309         num_extents = 0;
2310
2311         trans = btrfs_start_transaction(cur_root, 1);
2312         BUG_ON(!trans);
2313
2314         cur_byte = start_byte;
2315         while (1) {
2316                 key.objectid = cur_byte;
2317                 key.offset = 0;
2318                 key.type = BTRFS_EXTENT_ITEM_KEY;
2319                 ret = btrfs_search_slot(trans, extent_root,
2320                                         &key, &path, 0, 0);
2321                 if (ret < 0)
2322                         goto fail;
2323 next:
2324                 leaf = path.nodes[0];
2325                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2326                         ret = btrfs_next_leaf(extent_root, &path);
2327                         if (ret < 0)
2328                                 goto fail;
2329                         if (ret > 0)
2330                                 break;
2331                         leaf = path.nodes[0];
2332                 }
2333
2334                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2335                 if (key.objectid < cur_byte ||
2336                     key.type != BTRFS_EXTENT_ITEM_KEY) {
2337                         path.slots[0]++;
2338                         goto next;
2339                 }
2340                 if (key.objectid >= end_byte)
2341                         break;
2342
2343                 num_extents++;
2344
2345                 cur_byte = key.objectid;
2346                 num_bytes = key.offset;
2347                 ei = btrfs_item_ptr(leaf, path.slots[0],
2348                                     struct btrfs_extent_item);
2349                 BUG_ON(!(btrfs_extent_flags(leaf, ei) &
2350                          BTRFS_EXTENT_FLAG_DATA));
2351
2352                 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2353                 end = ptr + btrfs_item_size_nr(leaf, path.slots[0]);
2354
2355                 ptr += sizeof(struct btrfs_extent_item);
2356
2357                 while (ptr < end) {
2358                         iref = (struct btrfs_extent_inline_ref *)ptr;
2359                         key.type = btrfs_extent_inline_ref_type(leaf, iref);
2360                         BUG_ON(key.type != BTRFS_EXTENT_DATA_REF_KEY);
2361                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
2362                         ref_root = btrfs_extent_data_ref_root(leaf, dref);
2363                         extent_key.objectid =
2364                                 btrfs_extent_data_ref_objectid(leaf, dref);
2365                         extent_key.offset =
2366                                 btrfs_extent_data_ref_offset(leaf, dref);
2367                         extent_key.type = BTRFS_EXTENT_DATA_KEY;
2368                         BUG_ON(btrfs_extent_data_ref_count(leaf, dref) != 1);
2369
2370                         if (ref_root == cur_root->root_key.objectid)
2371                                 break;
2372
2373                         ptr += btrfs_extent_inline_ref_size(key.type);
2374                 }
2375
2376                 if (ptr >= end) {
2377                         path.slots[0]++;
2378                         goto next;
2379                 }
2380
2381                 ret = relocate_one_reference(trans, cur_root, cur_byte,
2382                                              num_bytes, &extent_key,
2383                                              &reloc_tree);
2384                 if (ret < 0)
2385                         goto fail;
2386
2387                 cur_byte += num_bytes;
2388                 btrfs_release_path(&path);
2389
2390                 if (trans->blocks_used >= 4096) {
2391                         ret = btrfs_commit_transaction(trans, cur_root);
2392                         BUG_ON(ret);
2393                         trans = btrfs_start_transaction(cur_root, 1);
2394                         BUG_ON(!trans);
2395                 }
2396         }
2397         btrfs_release_path(&path);
2398
2399         ret = btrfs_commit_transaction(trans, cur_root);
2400         BUG_ON(ret);
2401
2402         if (num_extents > 0 && pass++ < 16)
2403                 goto again;
2404
2405         ret = (num_extents > 0) ? -1 : 0;
2406 fail:
2407         btrfs_release_path(&path);
2408         extent_io_tree_cleanup(&reloc_tree);
2409         return ret;
2410 }
2411
2412 /*
2413  * relocate data in system chunk
2414  */
2415 static int cleanup_sys_chunk(struct btrfs_root *fs_root,
2416                              struct btrfs_root *image_root)
2417 {
2418         struct btrfs_block_group_cache *cache;
2419         int i, ret = 0;
2420         u64 offset = 0;
2421         u64 end_byte;
2422
2423         while(1) {
2424                 cache = btrfs_lookup_block_group(fs_root->fs_info, offset);
2425                 if (!cache)
2426                         break;
2427
2428                 end_byte = cache->key.objectid + cache->key.offset;
2429                 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2430                         ret = relocate_extents_range(fs_root, image_root,
2431                                                      cache->key.objectid,
2432                                                      end_byte);
2433                         if (ret)
2434                                 goto fail;
2435                 }
2436                 offset = end_byte;
2437         }
2438         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2439                 offset = btrfs_sb_offset(i);
2440                 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
2441
2442                 ret = relocate_extents_range(fs_root, image_root,
2443                                              offset, offset + BTRFS_STRIPE_LEN);
2444                 if (ret)
2445                         goto fail;
2446         }
2447         ret = 0;
2448 fail:
2449         return ret;
2450 }
2451
2452 static int fixup_chunk_mapping(struct btrfs_root *root)
2453 {
2454         struct btrfs_trans_handle *trans;
2455         struct btrfs_fs_info *info = root->fs_info;
2456         struct btrfs_root *chunk_root = info->chunk_root;
2457         struct extent_buffer *leaf;
2458         struct btrfs_key key;
2459         struct btrfs_path path;
2460         struct btrfs_chunk chunk;
2461         unsigned long ptr;
2462         u32 size;
2463         u64 type;
2464         int ret;
2465
2466         btrfs_init_path(&path);
2467
2468         trans = btrfs_start_transaction(root, 1);
2469         BUG_ON(!trans);
2470
2471         /*
2472          * recow the whole chunk tree. this will move all chunk tree blocks
2473          * into system block group.
2474          */
2475         memset(&key, 0, sizeof(key));
2476         while (1) {
2477                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2478                 if (ret < 0)
2479                         goto err;
2480
2481                 ret = btrfs_next_leaf(chunk_root, &path);
2482                 if (ret < 0)
2483                         goto err;
2484                 if (ret > 0)
2485                         break;
2486
2487                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2488                 btrfs_release_path(&path);
2489         }
2490         btrfs_release_path(&path);
2491
2492         /* fixup the system chunk array in super block */
2493         btrfs_set_super_sys_array_size(info->super_copy, 0);
2494
2495         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2496         key.offset = 0;
2497         key.type = BTRFS_CHUNK_ITEM_KEY;
2498
2499         ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 0);
2500         if (ret < 0)
2501                 goto err;
2502         BUG_ON(ret != 0);
2503         while(1) {
2504                 leaf = path.nodes[0];
2505                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2506                         ret = btrfs_next_leaf(chunk_root, &path);
2507                         if (ret < 0)
2508                                 goto err;
2509                         if (ret > 0)
2510                                 break;
2511                         leaf = path.nodes[0];
2512                 }
2513                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2514                 if (key.type != BTRFS_CHUNK_ITEM_KEY)
2515                         goto next;
2516
2517                 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2518                 size = btrfs_item_size_nr(leaf, path.slots[0]);
2519                 BUG_ON(size != sizeof(chunk));
2520                 read_extent_buffer(leaf, &chunk, ptr, size);
2521                 type = btrfs_stack_chunk_type(&chunk);
2522
2523                 if (!(type & BTRFS_BLOCK_GROUP_SYSTEM))
2524                         goto next;
2525
2526                 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
2527                                              &chunk, size);
2528                 if (ret)
2529                         goto err;
2530 next:
2531                 path.slots[0]++;
2532         }
2533
2534         ret = btrfs_commit_transaction(trans, root);
2535         BUG_ON(ret);
2536 err:
2537         btrfs_release_path(&path);
2538         return ret;
2539 }
2540
2541 static const struct btrfs_convert_operations ext2_convert_ops = {
2542         .name                   = "ext2",
2543         .open_fs                = ext2_open_fs,
2544         .read_used_space        = ext2_read_used_space,
2545         .alloc_block            = ext2_alloc_block,
2546         .alloc_block_range      = ext2_alloc_block_range,
2547         .copy_inodes            = ext2_copy_inodes,
2548         .test_block             = ext2_test_block,
2549         .free_block             = ext2_free_block,
2550         .free_block_range       = ext2_free_block_range,
2551         .close_fs               = ext2_close_fs,
2552 };
2553
2554 static const struct btrfs_convert_operations *convert_operations[] = {
2555         &ext2_convert_ops,
2556 };
2557
2558 static int convert_open_fs(const char *devname,
2559                            struct btrfs_convert_context *cctx)
2560 {
2561         int i;
2562
2563         memset(cctx, 0, sizeof(*cctx));
2564
2565         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2566                 int ret = convert_operations[i]->open_fs(cctx, devname);
2567
2568                 if (ret == 0) {
2569                         cctx->convert_ops = convert_operations[i];
2570                         return ret;
2571                 }
2572         }
2573
2574         fprintf(stderr, "No file system found to convert.\n");
2575         return -1;
2576 }
2577
2578 /*
2579  * Remove one reserve range from given cache tree
2580  * if min_stripe_size is non-zero, it will ensure for split case,
2581  * all its split cache extent is no smaller than @min_strip_size / 2.
2582  */
2583 static int wipe_one_reserved_range(struct cache_tree *tree,
2584                                    u64 start, u64 len, u64 min_stripe_size,
2585                                    int ensure_size)
2586 {
2587         struct cache_extent *cache;
2588         int ret;
2589
2590         BUG_ON(ensure_size && min_stripe_size == 0);
2591         /*
2592          * The logical here is simplified to handle special cases only
2593          * So we don't need to consider merge case for ensure_size
2594          */
2595         BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
2596                min_stripe_size / 2 < BTRFS_STRIPE_LEN));
2597
2598         /* Also, wipe range should already be aligned */
2599         BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
2600                start + len != round_up(start + len, BTRFS_STRIPE_LEN));
2601
2602         min_stripe_size /= 2;
2603
2604         cache = lookup_cache_extent(tree, start, len);
2605         if (!cache)
2606                 return 0;
2607
2608         if (start <= cache->start) {
2609                 /*
2610                  *      |--------cache---------|
2611                  * |-wipe-|
2612                  */
2613                 BUG_ON(start + len <= cache->start);
2614
2615                 /*
2616                  * The wipe size is smaller than min_stripe_size / 2,
2617                  * so the result length should still meet min_stripe_size
2618                  * And no need to do alignment
2619                  */
2620                 cache->size -= (start + len - cache->start);
2621                 if (cache->size == 0) {
2622                         remove_cache_extent(tree, cache);
2623                         free(cache);
2624                         return 0;
2625                 }
2626
2627                 BUG_ON(ensure_size && cache->size < min_stripe_size);
2628
2629                 cache->start = start + len;
2630                 return 0;
2631         } else if (start > cache->start && start + len < cache->start +
2632                    cache->size) {
2633                 /*
2634                  * |-------cache-----|
2635                  *      |-wipe-|
2636                  */
2637                 u64 old_len = cache->size;
2638                 u64 insert_start = start + len;
2639                 u64 insert_len;
2640
2641                 cache->size = start - cache->start;
2642                 if (ensure_size)
2643                         cache->size = max(cache->size, min_stripe_size);
2644                 cache->start = start - cache->size;
2645
2646                 /* And insert the new one */
2647                 insert_len = old_len - start - len;
2648                 if (ensure_size)
2649                         insert_len = max(insert_len, min_stripe_size);
2650
2651                 ret = add_merge_cache_extent(tree, insert_start, insert_len);
2652                 return ret;
2653         }
2654         /*
2655          * |----cache-----|
2656          *              |--wipe-|
2657          * Wipe len should be small enough and no need to expand the
2658          * remaining extent
2659          */
2660         cache->size = start - cache->start;
2661         BUG_ON(ensure_size && cache->size < min_stripe_size);
2662         return 0;
2663 }
2664
2665 /*
2666  * Remove reserved ranges from given cache_tree
2667  *
2668  * It will remove the following ranges
2669  * 1) 0~1M
2670  * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
2671  * 3) 3rd superblock, +64K
2672  *
2673  * @min_stripe must be given for safety check
2674  * and if @ensure_size is given, it will ensure affected cache_extent will be
2675  * larger than min_stripe_size
2676  */
2677 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
2678                                 int ensure_size)
2679 {
2680         int ret;
2681
2682         ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
2683                                       ensure_size);
2684         if (ret < 0)
2685                 return ret;
2686         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
2687                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2688         if (ret < 0)
2689                 return ret;
2690         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
2691                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2692         return ret;
2693 }
2694
2695 static int calculate_available_space(struct btrfs_convert_context *cctx)
2696 {
2697         struct cache_tree *used = &cctx->used;
2698         struct cache_tree *data_chunks = &cctx->data_chunks;
2699         struct cache_tree *free = &cctx->free;
2700         struct cache_extent *cache;
2701         u64 cur_off = 0;
2702         /*
2703          * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
2704          * works without need to consider overlap
2705          */
2706         u64 min_stripe_size = 2 * 16 * 1024 * 1024;
2707         int ret;
2708
2709         /* Calculate data_chunks */
2710         for (cache = first_cache_extent(used); cache;
2711              cache = next_cache_extent(cache)) {
2712                 u64 cur_len;
2713
2714                 if (cache->start + cache->size < cur_off)
2715                         continue;
2716                 if (cache->start > cur_off + min_stripe_size)
2717                         cur_off = cache->start;
2718                 cur_len = max(cache->start + cache->size - cur_off,
2719                               min_stripe_size);
2720                 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
2721                 if (ret < 0)
2722                         goto out;
2723                 cur_off += cur_len;
2724         }
2725         /*
2726          * remove reserved ranges, so we won't ever bother relocating an old
2727          * filesystem extent to other place.
2728          */
2729         ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
2730         if (ret < 0)
2731                 goto out;
2732
2733         cur_off = 0;
2734         /*
2735          * Calculate free space
2736          * Always round up the start bytenr, to avoid metadata extent corss
2737          * stripe boundary, as later mkfs_convert() won't have all the extent
2738          * allocation check
2739          */
2740         for (cache = first_cache_extent(data_chunks); cache;
2741              cache = next_cache_extent(cache)) {
2742                 if (cache->start < cur_off)
2743                         continue;
2744                 if (cache->start > cur_off) {
2745                         u64 insert_start;
2746                         u64 len;
2747
2748                         len = cache->start - round_up(cur_off,
2749                                                       BTRFS_STRIPE_LEN);
2750                         insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2751
2752                         ret = add_merge_cache_extent(free, insert_start, len);
2753                         if (ret < 0)
2754                                 goto out;
2755                 }
2756                 cur_off = cache->start + cache->size;
2757         }
2758         /* Don't forget the last range */
2759         if (cctx->total_bytes > cur_off) {
2760                 u64 len = cctx->total_bytes - cur_off;
2761                 u64 insert_start;
2762
2763                 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2764
2765                 ret = add_merge_cache_extent(free, insert_start, len);
2766                 if (ret < 0)
2767                         goto out;
2768         }
2769
2770         /* Remove reserved bytes */
2771         ret = wipe_reserved_ranges(free, min_stripe_size, 0);
2772 out:
2773         return ret;
2774 }
2775 /*
2776  * Read used space, and since we have the used space,
2777  * calcuate data_chunks and free for later mkfs
2778  */
2779 static int convert_read_used_space(struct btrfs_convert_context *cctx)
2780 {
2781         int ret;
2782
2783         ret = cctx->convert_ops->read_used_space(cctx);
2784         if (ret)
2785                 return ret;
2786
2787         ret = calculate_available_space(cctx);
2788         return ret;
2789 }
2790
2791 static int do_convert(const char *devname, int datacsum, int packing, int noxattr,
2792                 u32 nodesize, int copylabel, const char *fslabel, int progress,
2793                 u64 features)
2794 {
2795         int i, ret, blocks_per_node;
2796         int fd = -1;
2797         int is_btrfs = 0;
2798         u32 blocksize;
2799         u64 blocks[7];
2800         u64 total_bytes;
2801         u64 super_bytenr;
2802         struct btrfs_root *root;
2803         struct btrfs_root *image_root;
2804         struct btrfs_convert_context cctx;
2805         char *subvol_name = NULL;
2806         struct task_ctx ctx;
2807         char features_buf[64];
2808         struct btrfs_mkfs_config mkfs_cfg;
2809
2810         init_convert_context(&cctx);
2811         ret = convert_open_fs(devname, &cctx);
2812         if (ret)
2813                 goto fail;
2814         ret = convert_read_used_space(&cctx);
2815         if (ret)
2816                 goto fail;
2817
2818         blocksize = cctx.blocksize;
2819         total_bytes = (u64)blocksize * (u64)cctx.block_count;
2820         if (blocksize < 4096) {
2821                 fprintf(stderr, "block size is too small\n");
2822                 goto fail;
2823         }
2824         if (btrfs_check_nodesize(nodesize, blocksize, features))
2825                 goto fail;
2826         blocks_per_node = nodesize / blocksize;
2827         ret = -blocks_per_node;
2828         for (i = 0; i < 7; i++) {
2829                 if (nodesize == blocksize)
2830                         ret = convert_alloc_block(&cctx, 0, blocks + i);
2831                 else
2832                         ret = convert_alloc_block_range(&cctx,
2833                                         ret + blocks_per_node, blocks_per_node,
2834                                         blocks + i);
2835                 if (ret) {
2836                         fprintf(stderr, "not enough free space\n");
2837                         goto fail;
2838                 }
2839                 blocks[i] *= blocksize;
2840         }
2841         super_bytenr = blocks[0];
2842         fd = open(devname, O_RDWR);
2843         if (fd < 0) {
2844                 fprintf(stderr, "unable to open %s\n", devname);
2845                 goto fail;
2846         }
2847         btrfs_parse_features_to_string(features_buf, features);
2848         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2849                 strcat(features_buf, " (default)");
2850
2851         printf("create btrfs filesystem:\n");
2852         printf("\tblocksize: %u\n", blocksize);
2853         printf("\tnodesize:  %u\n", nodesize);
2854         printf("\tfeatures:  %s\n", features_buf);
2855
2856         mkfs_cfg.label = cctx.volume_name;
2857         mkfs_cfg.fs_uuid = NULL;
2858         memcpy(mkfs_cfg.blocks, blocks, sizeof(blocks));
2859         mkfs_cfg.num_bytes = total_bytes;
2860         mkfs_cfg.nodesize = nodesize;
2861         mkfs_cfg.sectorsize = blocksize;
2862         mkfs_cfg.stripesize = blocksize;
2863         mkfs_cfg.features = features;
2864
2865         ret = make_btrfs(fd, &mkfs_cfg, NULL);
2866         if (ret) {
2867                 fprintf(stderr, "unable to create initial ctree: %s\n",
2868                         strerror(-ret));
2869                 goto fail;
2870         }
2871         /* create a system chunk that maps the whole device */
2872         ret = prepare_system_chunk(fd, super_bytenr);
2873         if (ret) {
2874                 fprintf(stderr, "unable to update system chunk\n");
2875                 goto fail;
2876         }
2877         root = open_ctree_fd(fd, devname, super_bytenr, OPEN_CTREE_WRITES);
2878         if (!root) {
2879                 fprintf(stderr, "unable to open ctree\n");
2880                 goto fail;
2881         }
2882         ret = cache_free_extents(root, &cctx);
2883         if (ret) {
2884                 fprintf(stderr, "error during cache_free_extents %d\n", ret);
2885                 goto fail;
2886         }
2887         root->fs_info->extent_ops = &extent_ops;
2888         /* recover block allocation bitmap */
2889         for (i = 0; i < 7; i++) {
2890                 blocks[i] /= blocksize;
2891                 if (nodesize == blocksize)
2892                         convert_free_block(&cctx, blocks[i]);
2893                 else
2894                         convert_free_block_range(&cctx, blocks[i],
2895                                         blocks_per_node);
2896         }
2897         ret = init_btrfs(root);
2898         if (ret) {
2899                 fprintf(stderr, "unable to setup the root tree\n");
2900                 goto fail;
2901         }
2902         printf("creating btrfs metadata.\n");
2903         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2904         ctx.cur_copy_inodes = 0;
2905
2906         if (progress) {
2907                 ctx.info = task_init(print_copied_inodes, after_copied_inodes, &ctx);
2908                 task_start(ctx.info);
2909         }
2910         ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2911         if (ret) {
2912                 fprintf(stderr, "error during copy_inodes %d\n", ret);
2913                 goto fail;
2914         }
2915         if (progress) {
2916                 task_stop(ctx.info);
2917                 task_deinit(ctx.info);
2918         }
2919
2920         printf("creating %s image file.\n", cctx.convert_ops->name);
2921         ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2922         if (ret < 0) {
2923                 fprintf(stderr, "error allocating subvolume name: %s_saved\n",
2924                         cctx.convert_ops->name);
2925                 goto fail;
2926         }
2927
2928         image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2929
2930         free(subvol_name);
2931
2932         if (!image_root) {
2933                 fprintf(stderr, "unable to create subvol\n");
2934                 goto fail;
2935         }
2936         ret = create_image(&cctx, image_root, "image", datacsum);
2937         if (ret) {
2938                 fprintf(stderr, "error during create_image %d\n", ret);
2939                 goto fail;
2940         }
2941         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2942         if (copylabel == 1) {
2943                 __strncpy_null(root->fs_info->super_copy->label,
2944                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2945                 fprintf(stderr, "copy label '%s'\n",
2946                                 root->fs_info->super_copy->label);
2947         } else if (copylabel == -1) {
2948                 strcpy(root->fs_info->super_copy->label, fslabel);
2949                 fprintf(stderr, "set label to '%s'\n", fslabel);
2950         }
2951
2952         printf("cleaning up system chunk.\n");
2953         ret = cleanup_sys_chunk(root, image_root);
2954         if (ret) {
2955                 fprintf(stderr, "error during cleanup_sys_chunk %d\n", ret);
2956                 goto fail;
2957         }
2958         ret = close_ctree(root);
2959         if (ret) {
2960                 fprintf(stderr, "error during close_ctree %d\n", ret);
2961                 goto fail;
2962         }
2963         convert_close_fs(&cctx);
2964         clean_convert_context(&cctx);
2965
2966         /*
2967          * If this step succeed, we get a mountable btrfs. Otherwise
2968          * the source fs is left unchanged.
2969          */
2970         ret = migrate_super_block(fd, super_bytenr, blocksize);
2971         if (ret) {
2972                 fprintf(stderr, "unable to migrate super block\n");
2973                 goto fail;
2974         }
2975         is_btrfs = 1;
2976
2977         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2978         if (!root) {
2979                 fprintf(stderr, "unable to open ctree\n");
2980                 goto fail;
2981         }
2982         /* move chunk tree into system chunk. */
2983         ret = fixup_chunk_mapping(root);
2984         if (ret) {
2985                 fprintf(stderr, "error during fixup_chunk_tree\n");
2986                 goto fail;
2987         }
2988         ret = close_ctree(root);
2989         close(fd);
2990
2991         printf("conversion complete.\n");
2992         return 0;
2993 fail:
2994         clean_convert_context(&cctx);
2995         if (fd != -1)
2996                 close(fd);
2997         if (is_btrfs)
2998                 fprintf(stderr,
2999                         "WARNING: an error occured during chunk mapping fixup, filesystem mountable but not finalized\n");
3000         else
3001                 fprintf(stderr, "conversion aborted\n");
3002         return -1;
3003 }
3004
3005 static int may_rollback(struct btrfs_root *root)
3006 {
3007         struct btrfs_fs_info *info = root->fs_info;
3008         struct btrfs_multi_bio *multi = NULL;
3009         u64 bytenr;
3010         u64 length;
3011         u64 physical;
3012         u64 total_bytes;
3013         int num_stripes;
3014         int ret;
3015
3016         if (btrfs_super_num_devices(info->super_copy) != 1)
3017                 goto fail;
3018
3019         bytenr = BTRFS_SUPER_INFO_OFFSET;
3020         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
3021
3022         while (1) {
3023                 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
3024                                       &length, &multi, 0, NULL);
3025                 if (ret) {
3026                         if (ret == -ENOENT) {
3027                                 /* removed block group at the tail */
3028                                 if (length == (u64)-1)
3029                                         break;
3030
3031                                 /* removed block group in the middle */
3032                                 goto next;
3033                         }
3034                         goto fail;
3035                 }
3036
3037                 num_stripes = multi->num_stripes;
3038                 physical = multi->stripes[0].physical;
3039                 kfree(multi);
3040
3041                 if (num_stripes != 1 || physical != bytenr)
3042                         goto fail;
3043 next:
3044                 bytenr += length;
3045                 if (bytenr >= total_bytes)
3046                         break;
3047         }
3048         return 0;
3049 fail:
3050         return -1;
3051 }
3052
3053 static int do_rollback(const char *devname)
3054 {
3055         int fd = -1;
3056         int ret;
3057         int i;
3058         struct btrfs_root *root;
3059         struct btrfs_root *image_root;
3060         struct btrfs_root *chunk_root;
3061         struct btrfs_dir_item *dir;
3062         struct btrfs_inode_item *inode;
3063         struct btrfs_file_extent_item *fi;
3064         struct btrfs_trans_handle *trans;
3065         struct extent_buffer *leaf;
3066         struct btrfs_block_group_cache *cache1;
3067         struct btrfs_block_group_cache *cache2;
3068         struct btrfs_key key;
3069         struct btrfs_path path;
3070         struct extent_io_tree io_tree;
3071         char *buf = NULL;
3072         char *name;
3073         u64 bytenr;
3074         u64 num_bytes;
3075         u64 root_dir;
3076         u64 objectid;
3077         u64 offset;
3078         u64 start;
3079         u64 end;
3080         u64 sb_bytenr;
3081         u64 first_free;
3082         u64 total_bytes;
3083         u32 sectorsize;
3084
3085         extent_io_tree_init(&io_tree);
3086
3087         fd = open(devname, O_RDWR);
3088         if (fd < 0) {
3089                 fprintf(stderr, "unable to open %s\n", devname);
3090                 goto fail;
3091         }
3092         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
3093         if (!root) {
3094                 fprintf(stderr, "unable to open ctree\n");
3095                 goto fail;
3096         }
3097         ret = may_rollback(root);
3098         if (ret < 0) {
3099                 fprintf(stderr, "unable to do rollback\n");
3100                 goto fail;
3101         }
3102
3103         sectorsize = root->sectorsize;
3104         buf = malloc(sectorsize);
3105         if (!buf) {
3106                 fprintf(stderr, "unable to allocate memory\n");
3107                 goto fail;
3108         }
3109
3110         btrfs_init_path(&path);
3111
3112         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
3113         key.type = BTRFS_ROOT_BACKREF_KEY;
3114         key.offset = BTRFS_FS_TREE_OBJECTID;
3115         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
3116                                 0);
3117         btrfs_release_path(&path);
3118         if (ret > 0) {
3119                 fprintf(stderr,
3120                 "ERROR: unable to convert ext2 image subvolume, is it deleted?\n");
3121                 goto fail;
3122         } else if (ret < 0) {
3123                 fprintf(stderr,
3124                         "ERROR: unable to open ext2_saved, id=%llu: %s\n",
3125                         (unsigned long long)key.objectid, strerror(-ret));
3126                 goto fail;
3127         }
3128
3129         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
3130         key.type = BTRFS_ROOT_ITEM_KEY;
3131         key.offset = (u64)-1;
3132         image_root = btrfs_read_fs_root(root->fs_info, &key);
3133         if (!image_root || IS_ERR(image_root)) {
3134                 fprintf(stderr, "unable to open subvol %llu\n",
3135                         (unsigned long long)key.objectid);
3136                 goto fail;
3137         }
3138
3139         name = "image";
3140         root_dir = btrfs_root_dirid(&root->root_item);
3141         dir = btrfs_lookup_dir_item(NULL, image_root, &path,
3142                                    root_dir, name, strlen(name), 0);
3143         if (!dir || IS_ERR(dir)) {
3144                 fprintf(stderr, "unable to find file %s\n", name);
3145                 goto fail;
3146         }
3147         leaf = path.nodes[0];
3148         btrfs_dir_item_key_to_cpu(leaf, dir, &key);
3149         btrfs_release_path(&path);
3150
3151         objectid = key.objectid;
3152
3153         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
3154         if (ret) {
3155                 fprintf(stderr, "unable to find inode item\n");
3156                 goto fail;
3157         }
3158         leaf = path.nodes[0];
3159         inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
3160         total_bytes = btrfs_inode_size(leaf, inode);
3161         btrfs_release_path(&path);
3162
3163         key.objectid = objectid;
3164         key.offset = 0;
3165         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
3166         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
3167         if (ret != 0) {
3168                 fprintf(stderr, "unable to find first file extent\n");
3169                 btrfs_release_path(&path);
3170                 goto fail;
3171         }
3172
3173         /* build mapping tree for the relocated blocks */
3174         for (offset = 0; offset < total_bytes; ) {
3175                 leaf = path.nodes[0];
3176                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3177                         ret = btrfs_next_leaf(root, &path);
3178                         if (ret != 0)
3179                                 break;  
3180                         continue;
3181                 }
3182
3183                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3184                 if (key.objectid != objectid || key.offset != offset ||
3185                     btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3186                         break;
3187
3188                 fi = btrfs_item_ptr(leaf, path.slots[0],
3189                                     struct btrfs_file_extent_item);
3190                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
3191                         break;
3192                 if (btrfs_file_extent_compression(leaf, fi) ||
3193                     btrfs_file_extent_encryption(leaf, fi) ||
3194                     btrfs_file_extent_other_encoding(leaf, fi))
3195                         break;
3196
3197                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
3198                 /* skip holes and direct mapped extents */
3199                 if (bytenr == 0 || bytenr == offset)
3200                         goto next_extent;
3201
3202                 bytenr += btrfs_file_extent_offset(leaf, fi);
3203                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
3204
3205                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
3206                 cache2 =  btrfs_lookup_block_group(root->fs_info,
3207                                                    offset + num_bytes - 1);
3208                 if (!cache1 || cache1 != cache2 ||
3209                     (!(cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM) &&
3210                      !intersect_with_sb(offset, num_bytes)))
3211                         break;
3212
3213                 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
3214                                 EXTENT_LOCKED, GFP_NOFS);
3215                 set_state_private(&io_tree, offset, bytenr);
3216 next_extent:
3217                 offset += btrfs_file_extent_num_bytes(leaf, fi);
3218                 path.slots[0]++;
3219         }
3220         btrfs_release_path(&path);
3221
3222         if (offset < total_bytes) {
3223                 fprintf(stderr, "unable to build extent mapping\n");
3224                 goto fail;
3225         }
3226
3227         first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
3228         first_free &= ~((u64)sectorsize - 1);
3229         /* backup for extent #0 should exist */
3230         if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
3231                 fprintf(stderr, "no backup for the first extent\n");
3232                 goto fail;
3233         }
3234         /* force no allocation from system block group */
3235         root->fs_info->system_allocs = -1;
3236         trans = btrfs_start_transaction(root, 1);
3237         BUG_ON(!trans);
3238         /*
3239          * recow the whole chunk tree, this will remove all chunk tree blocks
3240          * from system block group
3241          */
3242         chunk_root = root->fs_info->chunk_root;
3243         memset(&key, 0, sizeof(key));
3244         while (1) {
3245                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
3246                 if (ret < 0)
3247                         break;
3248
3249                 ret = btrfs_next_leaf(chunk_root, &path);
3250                 if (ret)
3251                         break;
3252
3253                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
3254                 btrfs_release_path(&path);
3255         }
3256         btrfs_release_path(&path);
3257
3258         offset = 0;
3259         num_bytes = 0;
3260         while(1) {
3261                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
3262                 if (!cache1)
3263                         break;
3264
3265                 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
3266                         num_bytes += btrfs_block_group_used(&cache1->item);
3267
3268                 offset = cache1->key.objectid + cache1->key.offset;
3269         }
3270         /* only extent #0 left in system block group? */
3271         if (num_bytes > first_free) {
3272                 fprintf(stderr, "unable to empty system block group\n");
3273                 goto fail;
3274         }
3275         /* create a system chunk that maps the whole device */
3276         ret = prepare_system_chunk_sb(root->fs_info->super_copy);
3277         if (ret) {
3278                 fprintf(stderr, "unable to update system chunk\n");
3279                 goto fail;
3280         }
3281
3282         ret = btrfs_commit_transaction(trans, root);
3283         BUG_ON(ret);
3284
3285         ret = close_ctree(root);
3286         if (ret) {
3287                 fprintf(stderr, "error during close_ctree %d\n", ret);
3288                 goto fail;
3289         }
3290
3291         /* zero btrfs super block mirrors */
3292         memset(buf, 0, sectorsize);
3293         for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
3294                 bytenr = btrfs_sb_offset(i);
3295                 if (bytenr >= total_bytes)
3296                         break;
3297                 ret = pwrite(fd, buf, sectorsize, bytenr);
3298                 if (ret != sectorsize) {
3299                         fprintf(stderr,
3300                                 "error during zeroing superblock %d: %d\n",
3301                                 i, ret);
3302                         goto fail;
3303                 }
3304         }
3305
3306         sb_bytenr = (u64)-1;
3307         /* copy all relocated blocks back */
3308         while(1) {
3309                 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
3310                                             EXTENT_LOCKED);
3311                 if (ret)
3312                         break;
3313
3314                 ret = get_state_private(&io_tree, start, &bytenr);
3315                 BUG_ON(ret);
3316
3317                 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
3318                                   GFP_NOFS);
3319
3320                 while (start <= end) {
3321                         if (start == BTRFS_SUPER_INFO_OFFSET) {
3322                                 sb_bytenr = bytenr;
3323                                 goto next_sector;
3324                         }
3325                         ret = pread(fd, buf, sectorsize, bytenr);
3326                         if (ret < 0) {
3327                                 fprintf(stderr, "error during pread %d\n", ret);
3328                                 goto fail;
3329                         }
3330                         BUG_ON(ret != sectorsize);
3331                         ret = pwrite(fd, buf, sectorsize, start);
3332                         if (ret < 0) {
3333                                 fprintf(stderr, "error during pwrite %d\n", ret);
3334                                 goto fail;
3335                         }
3336                         BUG_ON(ret != sectorsize);
3337 next_sector:
3338                         start += sectorsize;
3339                         bytenr += sectorsize;
3340                 }
3341         }
3342
3343         ret = fsync(fd);
3344         if (ret) {
3345                 fprintf(stderr, "error during fsync %d\n", ret);
3346                 goto fail;
3347         }
3348         /*
3349          * finally, overwrite btrfs super block.
3350          */
3351         ret = pread(fd, buf, sectorsize, sb_bytenr);
3352         if (ret < 0) {
3353                 fprintf(stderr, "error during pread %d\n", ret);
3354                 goto fail;
3355         }
3356         BUG_ON(ret != sectorsize);
3357         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3358         if (ret < 0) {
3359                 fprintf(stderr, "error during pwrite %d\n", ret);
3360                 goto fail;
3361         }
3362         BUG_ON(ret != sectorsize);
3363         ret = fsync(fd);
3364         if (ret) {
3365                 fprintf(stderr, "error during fsync %d\n", ret);
3366                 goto fail;
3367         }
3368
3369         close(fd);
3370         free(buf);
3371         extent_io_tree_cleanup(&io_tree);
3372         printf("rollback complete.\n");
3373         return 0;
3374
3375 fail:
3376         if (fd != -1)
3377                 close(fd);
3378         free(buf);
3379         fprintf(stderr, "rollback aborted.\n");
3380         return -1;
3381 }
3382
3383 static void print_usage(void)
3384 {
3385         printf("usage: btrfs-convert [options] device\n");
3386         printf("options:\n");
3387         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
3388         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
3389         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
3390         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
3391         printf("\t-r|--rollback          roll back to the original filesystem\n");
3392         printf("\t-l|--label LABEL       set filesystem label\n");
3393         printf("\t-L|--copy-label        use label from converted filesystem\n");
3394         printf("\t-p|--progress          show converting progress (default)\n");
3395         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
3396         printf("\t--no-progress          show only overview, not the detailed progress\n");
3397 }
3398
3399 int main(int argc, char *argv[])
3400 {
3401         int ret;
3402         int packing = 1;
3403         int noxattr = 0;
3404         int datacsum = 1;
3405         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3406                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
3407         int rollback = 0;
3408         int copylabel = 0;
3409         int usage_error = 0;
3410         int progress = 1;
3411         char *file;
3412         char fslabel[BTRFS_LABEL_SIZE];
3413         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3414
3415         while(1) {
3416                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3417                 static const struct option long_options[] = {
3418                         { "no-progress", no_argument, NULL,
3419                                 GETOPT_VAL_NO_PROGRESS },
3420                         { "no-datasum", no_argument, NULL, 'd' },
3421                         { "no-inline", no_argument, NULL, 'n' },
3422                         { "no-xattr", no_argument, NULL, 'i' },
3423                         { "rollback", no_argument, NULL, 'r' },
3424                         { "features", required_argument, NULL, 'O' },
3425                         { "progress", no_argument, NULL, 'p' },
3426                         { "label", required_argument, NULL, 'l' },
3427                         { "copy-label", no_argument, NULL, 'L' },
3428                         { "nodesize", required_argument, NULL, 'N' },
3429                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
3430                         { NULL, 0, NULL, 0 }
3431                 };
3432                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3433
3434                 if (c < 0)
3435                         break;
3436                 switch(c) {
3437                         case 'd':
3438                                 datacsum = 0;
3439                                 break;
3440                         case 'i':
3441                                 noxattr = 1;
3442                                 break;
3443                         case 'n':
3444                                 packing = 0;
3445                                 break;
3446                         case 'N':
3447                                 nodesize = parse_size(optarg);
3448                                 break;
3449                         case 'r':
3450                                 rollback = 1;
3451                                 break;
3452                         case 'l':
3453                                 copylabel = -1;
3454                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3455                                         fprintf(stderr,
3456                                 "WARNING: label too long, trimmed to %d bytes\n",
3457                                                 BTRFS_LABEL_SIZE - 1);
3458                                 }
3459                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3460                                 break;
3461                         case 'L':
3462                                 copylabel = 1;
3463                                 break;
3464                         case 'p':
3465                                 progress = 1;
3466                                 break;
3467                         case 'O': {
3468                                 char *orig = strdup(optarg);
3469                                 char *tmp = orig;
3470
3471                                 tmp = btrfs_parse_fs_features(tmp, &features);
3472                                 if (tmp) {
3473                                         fprintf(stderr,
3474                                                 "Unrecognized filesystem feature '%s'\n",
3475                                                         tmp);
3476                                         free(orig);
3477                                         exit(1);
3478                                 }
3479                                 free(orig);
3480                                 if (features & BTRFS_FEATURE_LIST_ALL) {
3481                                         btrfs_list_all_fs_features(
3482                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3483                                         exit(0);
3484                                 }
3485                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3486                                         char buf[64];
3487
3488                                         btrfs_parse_features_to_string(buf,
3489                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3490                                         fprintf(stderr,
3491                                                 "ERROR: features not allowed for convert: %s\n",
3492                                                 buf);
3493                                         exit(1);
3494                                 }
3495
3496                                 break;
3497                                 }
3498                         case GETOPT_VAL_NO_PROGRESS:
3499                                 progress = 0;
3500                                 break;
3501                         case GETOPT_VAL_HELP:
3502                         default:
3503                                 print_usage();
3504                                 return c != GETOPT_VAL_HELP;
3505                 }
3506         }
3507         set_argv0(argv);
3508         if (check_argc_exact(argc - optind, 1)) {
3509                 print_usage();
3510                 return 1;
3511         }
3512
3513         if (rollback && (!datacsum || noxattr || !packing)) {
3514                 fprintf(stderr,
3515                         "Usage error: -d, -i, -n options do not apply to rollback\n");
3516                 usage_error++;
3517         }
3518
3519         if (usage_error) {
3520                 print_usage();
3521                 return 1;
3522         }
3523
3524         file = argv[optind];
3525         ret = check_mounted(file);
3526         if (ret < 0) {
3527                 fprintf(stderr, "Could not check mount status: %s\n",
3528                         strerror(-ret));
3529                 return 1;
3530         } else if (ret) {
3531                 fprintf(stderr, "%s is mounted\n", file);
3532                 return 1;
3533         }
3534
3535         if (rollback) {
3536                 ret = do_rollback(file);
3537         } else {
3538                 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3539                                 copylabel, fslabel, progress, features);
3540         }
3541         if (ret)
3542                 return 1;
3543         return 0;
3544 }