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