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