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