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