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