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