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