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