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