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