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