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