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