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