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