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