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