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