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