btrfs-progs: convert: Fix a bug in rollback check which overwrite return value
[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 /*
20  * Btrfs convert design:
21  *
22  * The overall design of btrfs convert is like the following:
23  *
24  * |<------------------Old fs----------------------------->|
25  * |<- used ->| |<- used ->|                    |<- used ->|
26  *                           ||
27  *                           \/
28  * |<---------------Btrfs fs------------------------------>|
29  * |<-   Old data chunk  ->|< new chunk (D/M/S)>|<- ODC  ->|
30  * |<-Old-FE->| |<-Old-FE->|<- Btrfs extents  ->|<-Old-FE->|
31  *
32  * ODC    = Old data chunk, btrfs chunks containing old fs data
33  *          Mapped 1:1 (logical address == device offset)
34  * Old-FE = file extents pointing to old fs.
35  *
36  * So old fs used space is (mostly) kept as is, while btrfs will insert
37  * its chunk (Data/Meta/Sys) into large enough free space.
38  * In this way, we can create different profiles for metadata/data for
39  * converted fs.
40  *
41  * We must reserve and relocate 3 ranges for btrfs:
42  * * [0, 1M)                    - area never used for any data except the first
43  *                                superblock
44  * * [btrfs_sb_offset(1), +64K) - 1st superblock backup copy
45  * * [btrfs_sb_offset(2), +64K) - 2nd, dtto
46  *
47  * Most work is spent handling corner cases around these reserved ranges.
48  *
49  * Detailed workflow is:
50  * 1)   Scan old fs used space and calculate data chunk layout
51  * 1.1) Scan old fs
52  *      We can a map used space of old fs
53  *
54  * 1.2) Calculate data chunk layout - this is the hard part
55  *      New data chunks must meet 3 conditions using result fomr 1.1
56  *      a. Large enough to be a chunk
57  *      b. Doesn't intersect reserved ranges
58  *      c. Covers all the remaining old fs used space
59  *
60  *      NOTE: This can be simplified if we don't need to handle backup supers
61  *
62  * 1.3) Calculate usable space for new btrfs chunks
63  *      Btrfs chunk usable space must meet 3 conditions using result from 1.2
64  *      a. Large enough to be a chunk
65  *      b. Doesn't intersect reserved ranges
66  *      c. Doesn't cover any data chunks in 1.1
67  *
68  * 2)   Create basic btrfs filesystem structure
69  *      Initial metadata and sys chunks are inserted in the first availabe
70  *      space found in step 1.3
71  *      Then insert all data chunks into the basic btrfs
72  *
73  * 3)   Create convert image
74  *      We need to relocate reserved ranges here.
75  *      After this step, the convert image is done, and we can use the image
76  *      as reflink source to create old files
77  *
78  * 4)   Iterate old fs to create files
79  *      We just reflink file extents from old fs to newly created files on
80  *      btrfs.
81  */
82
83 #include "kerncompat.h"
84
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <sys/types.h>
88 #include <fcntl.h>
89 #include <unistd.h>
90 #include <getopt.h>
91 #include <pthread.h>
92 #include <stdbool.h>
93
94 #include "ctree.h"
95 #include "disk-io.h"
96 #include "volumes.h"
97 #include "transaction.h"
98 #include "utils.h"
99 #include "task-utils.h"
100 #include "help.h"
101 #include "mkfs/common.h"
102 #include "convert/common.h"
103 #include "convert/source-fs.h"
104 #include "fsfeatures.h"
105
106 extern const struct btrfs_convert_operations ext2_convert_ops;
107 extern const struct btrfs_convert_operations reiserfs_convert_ops;
108
109 static const struct btrfs_convert_operations *convert_operations[] = {
110 #if BTRFSCONVERT_EXT2
111         &ext2_convert_ops,
112 #endif
113 #if BTRFSCONVERT_REISERFS
114         &reiserfs_convert_ops,
115 #endif
116 };
117
118 static void *print_copied_inodes(void *p)
119 {
120         struct task_ctx *priv = p;
121         const char work_indicator[] = { '.', 'o', 'O', 'o' };
122         u64 count = 0;
123
124         task_period_start(priv->info, 1000 /* 1s */);
125         while (1) {
126                 count++;
127                 pthread_mutex_lock(&priv->mutex);
128                 printf("copy inodes [%c] [%10llu/%10llu]\r",
129                        work_indicator[count % 4],
130                        (unsigned long long)priv->cur_copy_inodes,
131                        (unsigned long long)priv->max_copy_inodes);
132                 pthread_mutex_unlock(&priv->mutex);
133                 fflush(stdout);
134                 task_period_wait(priv->info);
135         }
136
137         return NULL;
138 }
139
140 static int after_copied_inodes(void *p)
141 {
142         printf("\n");
143         fflush(stdout);
144
145         return 0;
146 }
147
148 static inline int copy_inodes(struct btrfs_convert_context *cctx,
149                               struct btrfs_root *root, u32 convert_flags,
150                               struct task_ctx *p)
151 {
152         return cctx->convert_ops->copy_inodes(cctx, root, convert_flags, p);
153 }
154
155 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
156 {
157         cctx->convert_ops->close_fs(cctx);
158 }
159
160 static inline int convert_check_state(struct btrfs_convert_context *cctx)
161 {
162         return cctx->convert_ops->check_state(cctx);
163 }
164
165 static int csum_disk_extent(struct btrfs_trans_handle *trans,
166                             struct btrfs_root *root,
167                             u64 disk_bytenr, u64 num_bytes)
168 {
169         u32 blocksize = root->fs_info->sectorsize;
170         u64 offset;
171         char *buffer;
172         int ret = 0;
173
174         buffer = malloc(blocksize);
175         if (!buffer)
176                 return -ENOMEM;
177         for (offset = 0; offset < num_bytes; offset += blocksize) {
178                 ret = read_disk_extent(root, disk_bytenr + offset,
179                                         blocksize, buffer);
180                 if (ret)
181                         break;
182                 ret = btrfs_csum_file_block(trans,
183                                             root->fs_info->csum_root,
184                                             disk_bytenr + num_bytes,
185                                             disk_bytenr + offset,
186                                             buffer, blocksize);
187                 if (ret)
188                         break;
189         }
190         free(buffer);
191         return ret;
192 }
193
194 static int create_image_file_range(struct btrfs_trans_handle *trans,
195                                       struct btrfs_root *root,
196                                       struct cache_tree *used,
197                                       struct btrfs_inode_item *inode,
198                                       u64 ino, u64 bytenr, u64 *ret_len,
199                                       u32 convert_flags)
200 {
201         struct cache_extent *cache;
202         struct btrfs_block_group_cache *bg_cache;
203         u64 len = *ret_len;
204         u64 disk_bytenr;
205         int i;
206         int ret;
207         u32 datacsum = convert_flags & CONVERT_FLAG_DATACSUM;
208
209         if (bytenr != round_down(bytenr, root->fs_info->sectorsize)) {
210                 error("bytenr not sectorsize aligned: %llu",
211                                 (unsigned long long)bytenr);
212                 return -EINVAL;
213         }
214         if (len != round_down(len, root->fs_info->sectorsize)) {
215                 error("length not sectorsize aligned: %llu",
216                                 (unsigned long long)len);
217                 return -EINVAL;
218         }
219         len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
220
221         /*
222          * Skip reserved ranges first
223          *
224          * Or we will insert a hole into current image file, and later
225          * migrate block will fail as there is already a file extent.
226          */
227         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
228                 const struct simple_range *reserved = &btrfs_reserved_ranges[i];
229
230                 /*
231                  * |-- reserved --|
232                  *         |--range---|
233                  * or
234                  * |---- reserved ----|
235                  *    |-- range --|
236                  * Skip to reserved range end
237                  */
238                 if (bytenr >= reserved->start && bytenr < range_end(reserved)) {
239                         *ret_len = range_end(reserved) - bytenr;
240                         return 0;
241                 }
242
243                 /*
244                  *      |---reserved---|
245                  * |----range-------|
246                  * Leading part may still create a file extent
247                  */
248                 if (bytenr < reserved->start &&
249                     bytenr + len >= range_end(reserved)) {
250                         len = min_t(u64, len, reserved->start - bytenr);
251                         break;
252                 }
253         }
254
255         /* Check if we are going to insert regular file extent, or hole */
256         cache = search_cache_extent(used, bytenr);
257         if (cache) {
258                 if (cache->start <= bytenr) {
259                         /*
260                          * |///////Used///////|
261                          *      |<--insert--->|
262                          *      bytenr
263                          * Insert one real file extent
264                          */
265                         len = min_t(u64, len, cache->start + cache->size -
266                                     bytenr);
267                         disk_bytenr = bytenr;
268                 } else {
269                         /*
270                          *              |//Used//|
271                          *  |<-insert-->|
272                          *  bytenr
273                          *  Insert one hole
274                          */
275                         len = min(len, cache->start - bytenr);
276                         disk_bytenr = 0;
277                         datacsum = 0;
278                 }
279         } else {
280                 /*
281                  * |//Used//|           |EOF
282                  *          |<-insert-->|
283                  *          bytenr
284                  * Insert one hole
285                  */
286                 disk_bytenr = 0;
287                 datacsum = 0;
288         }
289
290         if (disk_bytenr) {
291                 /* Check if the range is in a data block group */
292                 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
293                 if (!bg_cache)
294                         return -ENOENT;
295                 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
296                         return -EINVAL;
297
298                 /* The extent should never cross block group boundary */
299                 len = min_t(u64, len, bg_cache->key.objectid +
300                             bg_cache->key.offset - bytenr);
301         }
302
303         if (len != round_down(len, root->fs_info->sectorsize)) {
304                 error("remaining length not sectorsize aligned: %llu",
305                                 (unsigned long long)len);
306                 return -EINVAL;
307         }
308         ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
309                                        disk_bytenr, len);
310         if (ret < 0)
311                 return ret;
312
313         if (datacsum)
314                 ret = csum_disk_extent(trans, root, bytenr, len);
315         *ret_len = len;
316         return ret;
317 }
318
319 /*
320  * Relocate old fs data in one reserved ranges
321  *
322  * Since all old fs data in reserved range is not covered by any chunk nor
323  * data extent, we don't need to handle any reference but add new
324  * extent/reference, which makes codes more clear
325  */
326 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
327                                       struct btrfs_root *root,
328                                       struct cache_tree *used,
329                                       struct btrfs_inode_item *inode, int fd,
330                                       u64 ino, const struct simple_range *range,
331                                       u32 convert_flags)
332 {
333         u64 cur_off = range->start;
334         u64 cur_len = range->len;
335         u64 hole_start = range->start;
336         u64 hole_len;
337         struct cache_extent *cache;
338         struct btrfs_key key;
339         struct extent_buffer *eb;
340         int ret = 0;
341
342         /*
343          * It's possible that there are holes in reserved range:
344          * |<---------------- Reserved range ---------------------->|
345          *      |<- Old fs data ->|   |<- Old fs data ->|
346          * So here we need to iterate through old fs used space and only
347          * migrate ranges that covered by old fs data.
348          */
349         while (cur_off < range_end(range)) {
350                 cache = search_cache_extent(used, cur_off);
351                 if (!cache)
352                         break;
353                 cur_off = max(cache->start, cur_off);
354                 if (cur_off >= range_end(range))
355                         break;
356                 cur_len = min(cache->start + cache->size, range_end(range)) -
357                           cur_off;
358                 BUG_ON(cur_len < root->fs_info->sectorsize);
359
360                 /* reserve extent for the data */
361                 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
362                                            &key, 1);
363                 if (ret < 0)
364                         break;
365
366                 eb = malloc(sizeof(*eb) + cur_len);
367                 if (!eb) {
368                         ret = -ENOMEM;
369                         break;
370                 }
371
372                 ret = pread(fd, eb->data, cur_len, cur_off);
373                 if (ret < cur_len) {
374                         ret = (ret < 0 ? ret : -EIO);
375                         free(eb);
376                         break;
377                 }
378                 eb->start = key.objectid;
379                 eb->len = key.offset;
380
381                 /* Write the data */
382                 ret = write_and_map_eb(root->fs_info, eb);
383                 free(eb);
384                 if (ret < 0)
385                         break;
386
387                 /* Now handle extent item and file extent things */
388                 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
389                                                key.objectid, key.offset);
390                 if (ret < 0)
391                         break;
392                 /* Finally, insert csum items */
393                 if (convert_flags & CONVERT_FLAG_DATACSUM)
394                         ret = csum_disk_extent(trans, root, key.objectid,
395                                                key.offset);
396
397                 /* Don't forget to insert hole */
398                 hole_len = cur_off - hole_start;
399                 if (hole_len) {
400                         ret = btrfs_record_file_extent(trans, root, ino, inode,
401                                         hole_start, 0, hole_len);
402                         if (ret < 0)
403                                 break;
404                 }
405
406                 cur_off += key.offset;
407                 hole_start = cur_off;
408                 cur_len = range_end(range) - cur_off;
409         }
410         /*
411          * Last hole
412          * |<---- reserved -------->|
413          * |<- Old fs data ->|      |
414          *                   | Hole |
415          */
416         if (range_end(range) - hole_start > 0)
417                 ret = btrfs_record_file_extent(trans, root, ino, inode,
418                                 hole_start, 0, range_end(range) - hole_start);
419         return ret;
420 }
421
422 /*
423  * Relocate the used source fs data in reserved ranges
424  */
425 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
426                                    struct btrfs_root *root,
427                                    struct cache_tree *used,
428                                    struct btrfs_inode_item *inode, int fd,
429                                    u64 ino, u64 total_bytes, u32 convert_flags)
430 {
431         int i;
432         int ret = 0;
433
434         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
435                 const struct simple_range *range = &btrfs_reserved_ranges[i];
436
437                 if (range->start > total_bytes)
438                         return ret;
439                 ret = migrate_one_reserved_range(trans, root, used, inode, fd,
440                                                  ino, range, convert_flags);
441                 if (ret < 0)
442                         return ret;
443         }
444
445         return ret;
446 }
447
448 /*
449  * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
450  * handle wiping a range that exists in cache.
451  */
452 static int _expand_extent_cache(struct cache_tree *tree,
453                                 struct cache_extent *entry,
454                                 u64 min_stripe_size, int backward)
455 {
456         struct cache_extent *ce;
457         int diff;
458
459         if (entry->size >= min_stripe_size)
460                 return 0;
461         diff = min_stripe_size - entry->size;
462
463         if (backward) {
464                 ce = prev_cache_extent(entry);
465                 if (!ce)
466                         goto expand_back;
467                 if (ce->start + ce->size >= entry->start - diff) {
468                         /* Directly merge with previous extent */
469                         ce->size = entry->start + entry->size - ce->start;
470                         remove_cache_extent(tree, entry);
471                         free(entry);
472                         return 0;
473                 }
474 expand_back:
475                 /* No overlap, normal extent */
476                 if (entry->start < diff) {
477                         error("cannot find space for data chunk layout");
478                         return -ENOSPC;
479                 }
480                 entry->start -= diff;
481                 entry->size += diff;
482                 return 0;
483         }
484         ce = next_cache_extent(entry);
485         if (!ce)
486                 goto expand_after;
487         if (entry->start + entry->size + diff >= ce->start) {
488                 /* Directly merge with next extent */
489                 entry->size = ce->start + ce->size - entry->start;
490                 remove_cache_extent(tree, ce);
491                 free(ce);
492                 return 0;
493         }
494 expand_after:
495         entry->size += diff;
496         return 0;
497 }
498
499 /*
500  * Remove one reserve range from given cache tree
501  * if min_stripe_size is non-zero, it will ensure for split case,
502  * all its split cache extent is no smaller than @min_strip_size / 2.
503  */
504 static int wipe_one_reserved_range(struct cache_tree *tree,
505                                    u64 start, u64 len, u64 min_stripe_size,
506                                    int ensure_size)
507 {
508         struct cache_extent *cache;
509         int ret;
510
511         BUG_ON(ensure_size && min_stripe_size == 0);
512         /*
513          * The logical here is simplified to handle special cases only
514          * So we don't need to consider merge case for ensure_size
515          */
516         BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
517                min_stripe_size / 2 < BTRFS_STRIPE_LEN));
518
519         /* Also, wipe range should already be aligned */
520         BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
521                start + len != round_up(start + len, BTRFS_STRIPE_LEN));
522
523         min_stripe_size /= 2;
524
525         cache = lookup_cache_extent(tree, start, len);
526         if (!cache)
527                 return 0;
528
529         if (start <= cache->start) {
530                 /*
531                  *      |--------cache---------|
532                  * |-wipe-|
533                  */
534                 BUG_ON(start + len <= cache->start);
535
536                 /*
537                  * The wipe size is smaller than min_stripe_size / 2,
538                  * so the result length should still meet min_stripe_size
539                  * And no need to do alignment
540                  */
541                 cache->size -= (start + len - cache->start);
542                 if (cache->size == 0) {
543                         remove_cache_extent(tree, cache);
544                         free(cache);
545                         return 0;
546                 }
547
548                 BUG_ON(ensure_size && cache->size < min_stripe_size);
549
550                 cache->start = start + len;
551                 return 0;
552         } else if (start > cache->start && start + len < cache->start +
553                    cache->size) {
554                 /*
555                  * |-------cache-----|
556                  *      |-wipe-|
557                  */
558                 u64 old_start = cache->start;
559                 u64 old_len = cache->size;
560                 u64 insert_start = start + len;
561                 u64 insert_len;
562
563                 cache->size = start - cache->start;
564                 /* Expand the leading half part if needed */
565                 if (ensure_size && cache->size < min_stripe_size) {
566                         ret = _expand_extent_cache(tree, cache,
567                                         min_stripe_size, 1);
568                         if (ret < 0)
569                                 return ret;
570                 }
571
572                 /* And insert the new one */
573                 insert_len = old_start + old_len - start - len;
574                 ret = add_merge_cache_extent(tree, insert_start, insert_len);
575                 if (ret < 0)
576                         return ret;
577
578                 /* Expand the last half part if needed */
579                 if (ensure_size && insert_len < min_stripe_size) {
580                         cache = lookup_cache_extent(tree, insert_start,
581                                                     insert_len);
582                         if (!cache || cache->start != insert_start ||
583                             cache->size != insert_len)
584                                 return -ENOENT;
585                         ret = _expand_extent_cache(tree, cache,
586                                         min_stripe_size, 0);
587                 }
588
589                 return ret;
590         }
591         /*
592          * |----cache-----|
593          *              |--wipe-|
594          * Wipe len should be small enough and no need to expand the
595          * remaining extent
596          */
597         cache->size = start - cache->start;
598         BUG_ON(ensure_size && cache->size < min_stripe_size);
599         return 0;
600 }
601
602 /*
603  * Remove reserved ranges from given cache_tree
604  *
605  * It will remove the following ranges
606  * 1) 0~1M
607  * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
608  * 3) 3rd superblock, +64K
609  *
610  * @min_stripe must be given for safety check
611  * and if @ensure_size is given, it will ensure affected cache_extent will be
612  * larger than min_stripe_size
613  */
614 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
615                                 int ensure_size)
616 {
617         int i;
618         int ret;
619
620         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
621                 const struct simple_range *range = &btrfs_reserved_ranges[i];
622
623                 ret = wipe_one_reserved_range(tree, range->start, range->len,
624                                               min_stripe_size, ensure_size);
625                 if (ret < 0)
626                         return ret;
627         }
628         return ret;
629 }
630
631 static int calculate_available_space(struct btrfs_convert_context *cctx)
632 {
633         struct cache_tree *used = &cctx->used_space;
634         struct cache_tree *data_chunks = &cctx->data_chunks;
635         struct cache_tree *free = &cctx->free_space;
636         struct cache_extent *cache;
637         u64 cur_off = 0;
638         /*
639          * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
640          * works without need to consider overlap
641          */
642         u64 min_stripe_size = SZ_32M;
643         int ret;
644
645         /* Calculate data_chunks */
646         for (cache = first_cache_extent(used); cache;
647              cache = next_cache_extent(cache)) {
648                 u64 cur_len;
649
650                 if (cache->start + cache->size < cur_off)
651                         continue;
652                 if (cache->start > cur_off + min_stripe_size)
653                         cur_off = cache->start;
654                 cur_len = max(cache->start + cache->size - cur_off,
655                               min_stripe_size);
656                 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
657                 if (ret < 0)
658                         goto out;
659                 cur_off += cur_len;
660         }
661         /*
662          * remove reserved ranges, so we won't ever bother relocating an old
663          * filesystem extent to other place.
664          */
665         ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
666         if (ret < 0)
667                 goto out;
668
669         cur_off = 0;
670         /*
671          * Calculate free space
672          * Always round up the start bytenr, to avoid metadata extent corss
673          * stripe boundary, as later mkfs_convert() won't have all the extent
674          * allocation check
675          */
676         for (cache = first_cache_extent(data_chunks); cache;
677              cache = next_cache_extent(cache)) {
678                 if (cache->start < cur_off)
679                         continue;
680                 if (cache->start > cur_off) {
681                         u64 insert_start;
682                         u64 len;
683
684                         len = cache->start - round_up(cur_off,
685                                                       BTRFS_STRIPE_LEN);
686                         insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
687
688                         ret = add_merge_cache_extent(free, insert_start, len);
689                         if (ret < 0)
690                                 goto out;
691                 }
692                 cur_off = cache->start + cache->size;
693         }
694         /* Don't forget the last range */
695         if (cctx->total_bytes > cur_off) {
696                 u64 len = cctx->total_bytes - cur_off;
697                 u64 insert_start;
698
699                 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
700
701                 ret = add_merge_cache_extent(free, insert_start, len);
702                 if (ret < 0)
703                         goto out;
704         }
705
706         /* Remove reserved bytes */
707         ret = wipe_reserved_ranges(free, min_stripe_size, 0);
708 out:
709         return ret;
710 }
711
712 /*
713  * Read used space, and since we have the used space,
714  * calcuate data_chunks and free for later mkfs
715  */
716 static int convert_read_used_space(struct btrfs_convert_context *cctx)
717 {
718         int ret;
719
720         ret = cctx->convert_ops->read_used_space(cctx);
721         if (ret)
722                 return ret;
723
724         ret = calculate_available_space(cctx);
725         return ret;
726 }
727
728 /*
729  * Create the fs image file of old filesystem.
730  *
731  * This is completely fs independent as we have cctx->used, only
732  * need to create file extents pointing to all the positions.
733  */
734 static int create_image(struct btrfs_root *root,
735                            struct btrfs_mkfs_config *cfg,
736                            struct btrfs_convert_context *cctx, int fd,
737                            u64 size, char *name, u32 convert_flags)
738 {
739         struct btrfs_inode_item buf;
740         struct btrfs_trans_handle *trans;
741         struct btrfs_path path;
742         struct btrfs_key key;
743         struct cache_extent *cache;
744         struct cache_tree used_tmp;
745         u64 cur;
746         u64 ino;
747         u64 flags = BTRFS_INODE_READONLY;
748         int ret;
749
750         if (!(convert_flags & CONVERT_FLAG_DATACSUM))
751                 flags |= BTRFS_INODE_NODATASUM;
752
753         trans = btrfs_start_transaction(root, 1);
754         if (IS_ERR(trans))
755                 return PTR_ERR(trans);
756
757         cache_tree_init(&used_tmp);
758         btrfs_init_path(&path);
759
760         ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
761                                        &ino);
762         if (ret < 0)
763                 goto out;
764         ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
765         if (ret < 0)
766                 goto out;
767         ret = btrfs_change_inode_flags(trans, root, ino, flags);
768         if (ret < 0)
769                 goto out;
770         ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
771                              strlen(name), BTRFS_FT_REG_FILE, NULL, 1, 0);
772         if (ret < 0)
773                 goto out;
774
775         key.objectid = ino;
776         key.type = BTRFS_INODE_ITEM_KEY;
777         key.offset = 0;
778
779         ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
780         if (ret) {
781                 ret = (ret > 0 ? -ENOENT : ret);
782                 goto out;
783         }
784         read_extent_buffer(path.nodes[0], &buf,
785                         btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
786                         sizeof(buf));
787         btrfs_release_path(&path);
788
789         /*
790          * Create a new used space cache, which doesn't contain the reserved
791          * range
792          */
793         for (cache = first_cache_extent(&cctx->used_space); cache;
794              cache = next_cache_extent(cache)) {
795                 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
796                 if (ret < 0)
797                         goto out;
798         }
799         ret = wipe_reserved_ranges(&used_tmp, 0, 0);
800         if (ret < 0)
801                 goto out;
802
803         /*
804          * Start from 1M, as 0~1M is reserved, and create_image_file_range()
805          * can't handle bytenr 0(will consider it as a hole)
806          */
807         cur = SZ_1M;
808         while (cur < size) {
809                 u64 len = size - cur;
810
811                 ret = create_image_file_range(trans, root, &used_tmp,
812                                                 &buf, ino, cur, &len,
813                                                 convert_flags);
814                 if (ret < 0)
815                         goto out;
816                 cur += len;
817         }
818         /* Handle the reserved ranges */
819         ret = migrate_reserved_ranges(trans, root, &cctx->used_space, &buf, fd,
820                         ino, cfg->num_bytes, convert_flags);
821
822         key.objectid = ino;
823         key.type = BTRFS_INODE_ITEM_KEY;
824         key.offset = 0;
825         ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
826         if (ret) {
827                 ret = (ret > 0 ? -ENOENT : ret);
828                 goto out;
829         }
830         btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
831         write_extent_buffer(path.nodes[0], &buf,
832                         btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
833                         sizeof(buf));
834 out:
835         free_extent_cache_tree(&used_tmp);
836         btrfs_release_path(&path);
837         btrfs_commit_transaction(trans, root);
838         return ret;
839 }
840
841 static int create_subvol(struct btrfs_trans_handle *trans,
842                          struct btrfs_root *root, u64 root_objectid)
843 {
844         struct extent_buffer *tmp;
845         struct btrfs_root *new_root;
846         struct btrfs_key key;
847         struct btrfs_root_item root_item;
848         int ret;
849
850         ret = btrfs_copy_root(trans, root, root->node, &tmp,
851                               root_objectid);
852         if (ret)
853                 return ret;
854
855         memcpy(&root_item, &root->root_item, sizeof(root_item));
856         btrfs_set_root_bytenr(&root_item, tmp->start);
857         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
858         btrfs_set_root_generation(&root_item, trans->transid);
859         free_extent_buffer(tmp);
860
861         key.objectid = root_objectid;
862         key.type = BTRFS_ROOT_ITEM_KEY;
863         key.offset = trans->transid;
864         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
865                                 &key, &root_item);
866
867         key.offset = (u64)-1;
868         new_root = btrfs_read_fs_root(root->fs_info, &key);
869         if (!new_root || IS_ERR(new_root)) {
870                 error("unable to fs read root: %lu", PTR_ERR(new_root));
871                 return PTR_ERR(new_root);
872         }
873
874         ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
875
876         return ret;
877 }
878
879 /*
880  * New make_btrfs() has handle system and meta chunks quite well.
881  * So only need to add remaining data chunks.
882  */
883 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
884                                           struct btrfs_fs_info *fs_info,
885                                           struct btrfs_mkfs_config *cfg,
886                                           struct btrfs_convert_context *cctx)
887 {
888         struct btrfs_root *extent_root = fs_info->extent_root;
889         struct cache_tree *data_chunks = &cctx->data_chunks;
890         struct cache_extent *cache;
891         u64 max_chunk_size;
892         int ret = 0;
893
894         /*
895          * Don't create data chunk over 10% of the convert device
896          * And for single chunk, don't create chunk larger than 1G.
897          */
898         max_chunk_size = cfg->num_bytes / 10;
899         max_chunk_size = min((u64)(SZ_1G), max_chunk_size);
900         max_chunk_size = round_down(max_chunk_size,
901                                     extent_root->fs_info->sectorsize);
902
903         for (cache = first_cache_extent(data_chunks); cache;
904              cache = next_cache_extent(cache)) {
905                 u64 cur = cache->start;
906
907                 while (cur < cache->start + cache->size) {
908                         u64 len;
909                         u64 cur_backup = cur;
910
911                         len = min(max_chunk_size,
912                                   cache->start + cache->size - cur);
913                         ret = btrfs_alloc_data_chunk(trans, fs_info,
914                                         &cur_backup, len,
915                                         BTRFS_BLOCK_GROUP_DATA, 1);
916                         if (ret < 0)
917                                 break;
918                         ret = btrfs_make_block_group(trans, fs_info, 0,
919                                         BTRFS_BLOCK_GROUP_DATA,
920                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID,
921                                         cur, len);
922                         if (ret < 0)
923                                 break;
924                         cur += len;
925                 }
926         }
927         return ret;
928 }
929
930 /*
931  * Init the temp btrfs to a operational status.
932  *
933  * It will fix the extent usage accounting(XXX: Do we really need?) and
934  * insert needed data chunks, to ensure all old fs data extents are covered
935  * by DATA chunks, preventing wrong chunks are allocated.
936  *
937  * And also create convert image subvolume and relocation tree.
938  * (XXX: Not need again?)
939  * But the convert image subvolume is *NOT* linked to fs tree yet.
940  */
941 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
942                          struct btrfs_convert_context *cctx, u32 convert_flags)
943 {
944         struct btrfs_key location;
945         struct btrfs_trans_handle *trans;
946         struct btrfs_fs_info *fs_info = root->fs_info;
947         int ret;
948
949         /*
950          * Don't alloc any metadata/system chunk, as we don't want
951          * any meta/sys chunk allcated before all data chunks are inserted.
952          * Or we screw up the chunk layout just like the old implement.
953          */
954         fs_info->avoid_sys_chunk_alloc = 1;
955         fs_info->avoid_meta_chunk_alloc = 1;
956         trans = btrfs_start_transaction(root, 1);
957         if (IS_ERR(trans)) {
958                 error("unable to start transaction");
959                 ret = PTR_ERR(trans);
960                 goto err;
961         }
962         ret = btrfs_fix_block_accounting(trans, root);
963         if (ret)
964                 goto err;
965         ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
966         if (ret)
967                 goto err;
968         ret = btrfs_make_root_dir(trans, fs_info->tree_root,
969                                   BTRFS_ROOT_TREE_DIR_OBJECTID);
970         if (ret)
971                 goto err;
972         memcpy(&location, &root->root_key, sizeof(location));
973         location.offset = (u64)-1;
974         ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
975                                 btrfs_super_root_dir(fs_info->super_copy),
976                                 &location, BTRFS_FT_DIR, 0);
977         if (ret)
978                 goto err;
979         ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
980                                 location.objectid,
981                                 btrfs_super_root_dir(fs_info->super_copy), 0);
982         if (ret)
983                 goto err;
984         btrfs_set_root_dirid(&fs_info->fs_root->root_item,
985                              BTRFS_FIRST_FREE_OBJECTID);
986
987         /* subvol for fs image file */
988         ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
989         if (ret < 0) {
990                 error("failed to create subvolume image root: %d", ret);
991                 goto err;
992         }
993         /* subvol for data relocation tree */
994         ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
995         if (ret < 0) {
996                 error("failed to create DATA_RELOC root: %d", ret);
997                 goto err;
998         }
999
1000         ret = btrfs_commit_transaction(trans, root);
1001         fs_info->avoid_sys_chunk_alloc = 0;
1002         fs_info->avoid_meta_chunk_alloc = 0;
1003 err:
1004         return ret;
1005 }
1006
1007 /*
1008  * Migrate super block to its default position and zero 0 ~ 16k
1009  */
1010 static int migrate_super_block(int fd, u64 old_bytenr)
1011 {
1012         int ret;
1013         struct extent_buffer *buf;
1014         struct btrfs_super_block *super;
1015         u32 len;
1016         u32 bytenr;
1017
1018         buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1019         if (!buf)
1020                 return -ENOMEM;
1021
1022         buf->len = BTRFS_SUPER_INFO_SIZE;
1023         ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, old_bytenr);
1024         if (ret != BTRFS_SUPER_INFO_SIZE)
1025                 goto fail;
1026
1027         super = (struct btrfs_super_block *)buf->data;
1028         BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1029         btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1030
1031         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1032         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
1033                 BTRFS_SUPER_INFO_OFFSET);
1034         if (ret != BTRFS_SUPER_INFO_SIZE)
1035                 goto fail;
1036
1037         ret = fsync(fd);
1038         if (ret)
1039                 goto fail;
1040
1041         memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1042         for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1043                 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1044                 if (len > BTRFS_SUPER_INFO_SIZE)
1045                         len = BTRFS_SUPER_INFO_SIZE;
1046                 ret = pwrite(fd, buf->data, len, bytenr);
1047                 if (ret != len) {
1048                         fprintf(stderr, "unable to zero fill device\n");
1049                         break;
1050                 }
1051                 bytenr += len;
1052         }
1053         ret = 0;
1054         fsync(fd);
1055 fail:
1056         free(buf);
1057         if (ret > 0)
1058                 ret = -1;
1059         return ret;
1060 }
1061
1062 static int convert_open_fs(const char *devname,
1063                            struct btrfs_convert_context *cctx)
1064 {
1065         int i;
1066
1067         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
1068                 int ret = convert_operations[i]->open_fs(cctx, devname);
1069
1070                 if (ret == 0) {
1071                         cctx->convert_ops = convert_operations[i];
1072                         return ret;
1073                 }
1074         }
1075
1076         error("no file system found to convert");
1077         return -1;
1078 }
1079
1080 static int do_convert(const char *devname, u32 convert_flags, u32 nodesize,
1081                 const char *fslabel, int progress, u64 features)
1082 {
1083         int ret;
1084         int fd = -1;
1085         u32 blocksize;
1086         u64 total_bytes;
1087         struct btrfs_root *root;
1088         struct btrfs_root *image_root;
1089         struct btrfs_convert_context cctx;
1090         struct btrfs_key key;
1091         char subvol_name[SOURCE_FS_NAME_LEN + 8];
1092         struct task_ctx ctx;
1093         char features_buf[64];
1094         struct btrfs_mkfs_config mkfs_cfg;
1095
1096         init_convert_context(&cctx);
1097         ret = convert_open_fs(devname, &cctx);
1098         if (ret)
1099                 goto fail;
1100         ret = convert_check_state(&cctx);
1101         if (ret)
1102                 warning(
1103                 "source filesystem is not clean, running filesystem check is recommended");
1104         ret = convert_read_used_space(&cctx);
1105         if (ret)
1106                 goto fail;
1107
1108         blocksize = cctx.blocksize;
1109         total_bytes = (u64)blocksize * (u64)cctx.block_count;
1110         if (blocksize < 4096) {
1111                 error("block size is too small: %u < 4096", blocksize);
1112                 goto fail;
1113         }
1114         if (btrfs_check_nodesize(nodesize, blocksize, features))
1115                 goto fail;
1116         fd = open(devname, O_RDWR);
1117         if (fd < 0) {
1118                 error("unable to open %s: %s", devname, strerror(errno));
1119                 goto fail;
1120         }
1121         btrfs_parse_features_to_string(features_buf, features);
1122         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
1123                 strcat(features_buf, " (default)");
1124
1125         printf("create btrfs filesystem:\n");
1126         printf("\tblocksize: %u\n", blocksize);
1127         printf("\tnodesize:  %u\n", nodesize);
1128         printf("\tfeatures:  %s\n", features_buf);
1129
1130         memset(&mkfs_cfg, 0, sizeof(mkfs_cfg));
1131         mkfs_cfg.label = cctx.volume_name;
1132         mkfs_cfg.num_bytes = total_bytes;
1133         mkfs_cfg.nodesize = nodesize;
1134         mkfs_cfg.sectorsize = blocksize;
1135         mkfs_cfg.stripesize = blocksize;
1136         mkfs_cfg.features = features;
1137
1138         ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
1139         if (ret) {
1140                 error("unable to create initial ctree: %s", strerror(-ret));
1141                 goto fail;
1142         }
1143
1144         root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
1145                              OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1146         if (!root) {
1147                 error("unable to open ctree");
1148                 goto fail;
1149         }
1150         ret = init_btrfs(&mkfs_cfg, root, &cctx, convert_flags);
1151         if (ret) {
1152                 error("unable to setup the root tree: %d", ret);
1153                 goto fail;
1154         }
1155
1156         printf("creating %s image file\n", cctx.convert_ops->name);
1157         snprintf(subvol_name, sizeof(subvol_name), "%s_saved",
1158                         cctx.convert_ops->name);
1159         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1160         key.offset = (u64)-1;
1161         key.type = BTRFS_ROOT_ITEM_KEY;
1162         image_root = btrfs_read_fs_root(root->fs_info, &key);
1163         if (!image_root) {
1164                 error("unable to create image subvolume");
1165                 goto fail;
1166         }
1167         ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
1168                               mkfs_cfg.num_bytes, "image",
1169                               convert_flags);
1170         if (ret) {
1171                 error("failed to create %s/image: %d", subvol_name, ret);
1172                 goto fail;
1173         }
1174
1175         printf("creating btrfs metadata\n");
1176         ret = pthread_mutex_init(&ctx.mutex, NULL);
1177         if (ret) {
1178                 error("failed to initialize mutex: %d", ret);
1179                 goto fail;
1180         }
1181         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
1182         ctx.cur_copy_inodes = 0;
1183
1184         if (progress) {
1185                 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
1186                                      &ctx);
1187                 task_start(ctx.info);
1188         }
1189         ret = copy_inodes(&cctx, root, convert_flags, &ctx);
1190         if (ret) {
1191                 error("error during copy_inodes %d", ret);
1192                 goto fail;
1193         }
1194         if (progress) {
1195                 task_stop(ctx.info);
1196                 task_deinit(ctx.info);
1197         }
1198
1199         image_root = btrfs_mksubvol(root, subvol_name,
1200                                     CONV_IMAGE_SUBVOL_OBJECTID, true);
1201         if (!image_root) {
1202                 error("unable to link subvolume %s", subvol_name);
1203                 goto fail;
1204         }
1205
1206         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
1207         if (convert_flags & CONVERT_FLAG_COPY_LABEL) {
1208                 __strncpy_null(root->fs_info->super_copy->label,
1209                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
1210                 printf("copy label '%s'\n", root->fs_info->super_copy->label);
1211         } else if (convert_flags & CONVERT_FLAG_SET_LABEL) {
1212                 strcpy(root->fs_info->super_copy->label, fslabel);
1213                 printf("set label to '%s'\n", fslabel);
1214         }
1215
1216         ret = close_ctree(root);
1217         if (ret) {
1218                 error("close_ctree failed: %d", ret);
1219                 goto fail;
1220         }
1221         convert_close_fs(&cctx);
1222         clean_convert_context(&cctx);
1223
1224         /*
1225          * If this step succeed, we get a mountable btrfs. Otherwise
1226          * the source fs is left unchanged.
1227          */
1228         ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
1229         if (ret) {
1230                 error("unable to migrate super block: %d", ret);
1231                 goto fail;
1232         }
1233
1234         root = open_ctree_fd(fd, devname, 0,
1235                         OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1236         if (!root) {
1237                 error("unable to open ctree for finalization");
1238                 goto fail;
1239         }
1240         root->fs_info->finalize_on_close = 1;
1241         close_ctree(root);
1242         close(fd);
1243
1244         printf("conversion complete\n");
1245         return 0;
1246 fail:
1247         clean_convert_context(&cctx);
1248         if (fd != -1)
1249                 close(fd);
1250         warning(
1251 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
1252         return -1;
1253 }
1254
1255 /*
1256  * Read out data of convert image which is in btrfs reserved ranges so we can
1257  * use them to overwrite the ranges during rollback.
1258  */
1259 static int read_reserved_ranges(struct btrfs_root *root, u64 ino,
1260                                 u64 total_bytes, char *reserved_ranges[])
1261 {
1262         int i;
1263         int ret = 0;
1264
1265         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
1266                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1267
1268                 if (range->start + range->len >= total_bytes)
1269                         break;
1270                 ret = btrfs_read_file(root, ino, range->start, range->len,
1271                                       reserved_ranges[i]);
1272                 if (ret < range->len) {
1273                         error(
1274         "failed to read data of convert image, offset=%llu len=%llu ret=%d",
1275                               range->start, range->len, ret);
1276                         if (ret >= 0)
1277                                 ret = -EIO;
1278                         break;
1279                 }
1280                 ret = 0;
1281         }
1282         return ret;
1283 }
1284
1285 static bool is_subset_of_reserved_ranges(u64 start, u64 len)
1286 {
1287         int i;
1288         bool ret = false;
1289
1290         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
1291                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1292
1293                 if (start >= range->start && start + len <= range_end(range)) {
1294                         ret = true;
1295                         break;
1296                 }
1297         }
1298         return ret;
1299 }
1300
1301 static bool is_chunk_direct_mapped(struct btrfs_fs_info *fs_info, u64 start)
1302 {
1303         struct cache_extent *ce;
1304         struct map_lookup *map;
1305         bool ret = false;
1306
1307         ce = search_cache_extent(&fs_info->mapping_tree.cache_tree, start);
1308         if (!ce)
1309                 goto out;
1310         if (ce->start > start || ce->start + ce->size < start)
1311                 goto out;
1312
1313         map = container_of(ce, struct map_lookup, ce);
1314
1315         /* Not SINGLE chunk */
1316         if (map->num_stripes != 1)
1317                 goto out;
1318
1319         /* Chunk's logical doesn't match with phisical, not 1:1 mapped */
1320         if (map->ce.start != map->stripes[0].physical)
1321                 goto out;
1322         ret = true;
1323 out:
1324         return ret;
1325 }
1326
1327 /*
1328  * Iterate all file extents of the convert image.
1329  *
1330  * All file extents except ones in btrfs_reserved_ranges must be mapped 1:1
1331  * on disk. (Means thier file_offset must match their on disk bytenr)
1332  *
1333  * File extents in reserved ranges can be relocated to other place, and in
1334  * that case we will read them out for later use.
1335  */
1336 static int check_convert_image(struct btrfs_root *image_root, u64 ino,
1337                                u64 total_size, char *reserved_ranges[])
1338 {
1339         struct btrfs_key key;
1340         struct btrfs_path path;
1341         struct btrfs_fs_info *fs_info = image_root->fs_info;
1342         u64 checked_bytes = 0;
1343         int ret;
1344
1345         key.objectid = ino;
1346         key.offset = 0;
1347         key.type = BTRFS_EXTENT_DATA_KEY;
1348
1349         btrfs_init_path(&path);
1350         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
1351         /*
1352          * It's possible that some fs doesn't store any (including sb)
1353          * data into 0~1M range, and NO_HOLES is enabled.
1354          *
1355          * So we only need to check if ret < 0
1356          */
1357         if (ret < 0) {
1358                 error("failed to iterate file extents at offset 0: %s",
1359                         strerror(-ret));
1360                 btrfs_release_path(&path);
1361                 return ret;
1362         }
1363
1364         /* Loop from the first file extents */
1365         while (1) {
1366                 struct btrfs_file_extent_item *fi;
1367                 struct extent_buffer *leaf = path.nodes[0];
1368                 u64 disk_bytenr;
1369                 u64 file_offset;
1370                 u64 ram_bytes;
1371                 int slot = path.slots[0];
1372
1373                 if (slot >= btrfs_header_nritems(leaf))
1374                         goto next;
1375                 btrfs_item_key_to_cpu(leaf, &key, slot);
1376
1377                 /*
1378                  * Iteration is done, exit normally, we have extra check out of
1379                  * the loop
1380                  */
1381                 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
1382                         ret = 0;
1383                         break;
1384                 }
1385                 file_offset = key.offset;
1386                 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1387                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG) {
1388                         ret = -EINVAL;
1389                         error(
1390                 "ino %llu offset %llu doesn't have a regular file extent",
1391                                 ino, file_offset);
1392                         break;
1393                 }
1394                 if (btrfs_file_extent_compression(leaf, fi) ||
1395                     btrfs_file_extent_encryption(leaf, fi) ||
1396                     btrfs_file_extent_other_encoding(leaf, fi)) {
1397                         ret = -EINVAL;
1398                         error(
1399                         "ino %llu offset %llu doesn't have a plain file extent",
1400                                 ino, file_offset);
1401                         break;
1402                 }
1403
1404                 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1405                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1406
1407                 checked_bytes += ram_bytes;
1408                 /* Skip hole */
1409                 if (disk_bytenr == 0)
1410                         goto next;
1411
1412                 /*
1413                  * Most file extents must be 1:1 mapped, which means 2 things:
1414                  * 1) File extent file offset == disk_bytenr
1415                  * 2) That data chunk's logical == chunk's physical
1416                  *
1417                  * So file extent's file offset == physical position on disk.
1418                  *
1419                  * And after rolling back btrfs reserved range, other part
1420                  * remains what old fs used to be.
1421                  */
1422                 if (file_offset != disk_bytenr ||
1423                     !is_chunk_direct_mapped(fs_info, disk_bytenr)) {
1424                         /*
1425                          * Only file extent in btrfs reserved ranges are
1426                          * allowed to be non-1:1 mapped
1427                          */
1428                         if (!is_subset_of_reserved_ranges(file_offset,
1429                                                         ram_bytes)) {
1430                                 ret = -EINVAL;
1431                                 error(
1432                 "ino %llu offset %llu file extent should not be relocated",
1433                                         ino, file_offset);
1434                                 break;
1435                         }
1436                 }
1437 next:
1438                 ret = btrfs_next_item(image_root, &path);
1439                 if (ret) {
1440                         if (ret > 0)
1441                                 ret = 0;
1442                         break;
1443                 }
1444         }
1445         btrfs_release_path(&path);
1446         if (ret)
1447                 return ret;
1448         /*
1449          * For HOLES mode (without NO_HOLES), we must ensure file extents
1450          * cover the whole range of the image
1451          */
1452         if (!ret && !btrfs_fs_incompat(fs_info, NO_HOLES)) {
1453                 if (checked_bytes != total_size) {
1454                         ret = -EINVAL;
1455                         error("inode %llu has some file extents not checked",
1456                                 ino);
1457                         return ret;
1458                 }
1459         }
1460
1461         /* So far so good, read old data located in btrfs reserved ranges */
1462         ret = read_reserved_ranges(image_root, ino, total_size,
1463                                    reserved_ranges);
1464         return ret;
1465 }
1466
1467 /*
1468  * btrfs rollback is just reverted convert:
1469  * |<---------------Btrfs fs------------------------------>|
1470  * |<-   Old data chunk  ->|< new chunk (D/M/S)>|<- ODC  ->|
1471  * |<-Old-FE->| |<-Old-FE->|<- Btrfs extents  ->|<-Old-FE->|
1472  *                           ||
1473  *                           \/
1474  * |<------------------Old fs----------------------------->|
1475  * |<- used ->| |<- used ->|                    |<- used ->|
1476  *
1477  * However things are much easier than convert, we don't really need to
1478  * do the complex space calculation, but only to handle btrfs reserved space
1479  *
1480  * |<---------------------------Btrfs fs----------------------------->|
1481  * |   RSV 1   |  | Old  |   |    RSV 2  | | Old  | |   RSV 3   |
1482  * |   0~1M    |  | Fs   |   | SB2 + 64K | | Fs   | | SB3 + 64K |
1483  *
1484  * On the other hand, the converted fs image in btrfs is a completely
1485  * valid old fs.
1486  *
1487  * |<-----------------Converted fs image in btrfs-------------------->|
1488  * |   RSV 1   |  | Old  |   |    RSV 2  | | Old  | |   RSV 3   |
1489  * | Relocated |  | Fs   |   | Relocated | | Fs   | | Relocated |
1490  *
1491  * Used space in fs image should be at the same physical position on disk.
1492  * We only need to recover the data in reserved ranges, so the whole
1493  * old fs is back.
1494  *
1495  * The idea to rollback is also straightforward, we just "read" out the data
1496  * of reserved ranges, and write them back to there they should be.
1497  * Then the old fs is back.
1498  */
1499 static int do_rollback(const char *devname)
1500 {
1501         struct btrfs_root *root;
1502         struct btrfs_root *image_root;
1503         struct btrfs_fs_info *fs_info;
1504         struct btrfs_key key;
1505         struct btrfs_path path;
1506         struct btrfs_dir_item *dir;
1507         struct btrfs_inode_item *inode_item;
1508         char *image_name = "image";
1509         char *reserved_ranges[ARRAY_SIZE(btrfs_reserved_ranges)] = { NULL };
1510         u64 total_bytes;
1511         u64 fsize;
1512         u64 root_dir;
1513         u64 ino;
1514         int fd = -1;
1515         int ret;
1516         int i;
1517
1518         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
1519                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1520
1521                 reserved_ranges[i] = calloc(1, range->len);
1522                 if (!reserved_ranges[i]) {
1523                         ret = -ENOMEM;
1524                         goto free_mem;
1525                 }
1526         }
1527         fd = open(devname, O_RDWR);
1528         if (fd < 0) {
1529                 error("unable to open %s: %s", devname, strerror(errno));
1530                 ret = -EIO;
1531                 goto free_mem;
1532         }
1533         fsize = lseek(fd, 0, SEEK_END);
1534
1535         /*
1536          * For rollback, we don't really need to write anything so open it
1537          * read-only.  The write part will happen after we close the
1538          * filesystem.
1539          */
1540         root = open_ctree_fd(fd, devname, 0, 0);
1541         if (!root) {
1542                 error("unable to open ctree");
1543                 ret = -EIO;
1544                 goto free_mem;
1545         }
1546         fs_info = root->fs_info;
1547
1548         /*
1549          * Search root backref first, or after subvolume deletion (orphan),
1550          * we can still rollback the image.
1551          */
1552         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1553         key.type = BTRFS_ROOT_BACKREF_KEY;
1554         key.offset = BTRFS_FS_TREE_OBJECTID;
1555         btrfs_init_path(&path);
1556         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, &path, 0, 0);
1557         btrfs_release_path(&path);
1558         if (ret > 0) {
1559                 error("unable to find source fs image subvolume, is it deleted?");
1560                 ret = -ENOENT;
1561                 goto close_fs;
1562         } else if (ret < 0) {
1563                 error("failed to find source fs image subvolume: %s",
1564                         strerror(-ret));
1565                 goto close_fs;
1566         }
1567
1568         /* Search convert subvolume */
1569         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1570         key.type = BTRFS_ROOT_ITEM_KEY;
1571         key.offset = (u64)-1;
1572         image_root = btrfs_read_fs_root(fs_info, &key);
1573         if (IS_ERR(image_root)) {
1574                 ret = PTR_ERR(image_root);
1575                 error("failed to open convert image subvolume: %s",
1576                         strerror(-ret));
1577                 goto close_fs;
1578         }
1579
1580         /* Search the image file */
1581         root_dir = btrfs_root_dirid(&image_root->root_item);
1582         dir = btrfs_lookup_dir_item(NULL, image_root, &path, root_dir,
1583                         image_name, strlen(image_name), 0);
1584
1585         if (!dir || IS_ERR(dir)) {
1586                 btrfs_release_path(&path);
1587                 if (dir)
1588                         ret = PTR_ERR(dir);
1589                 else
1590                         ret = -ENOENT;
1591                 error("failed to locate file %s: %s", image_name,
1592                         strerror(-ret));
1593                 goto close_fs;
1594         }
1595         btrfs_dir_item_key_to_cpu(path.nodes[0], dir, &key);
1596         btrfs_release_path(&path);
1597
1598         /* Get total size of the original image */
1599         ino = key.objectid;
1600
1601         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
1602
1603         if (ret < 0) {
1604                 btrfs_release_path(&path);
1605                 error("unable to find inode %llu: %s", ino, strerror(-ret));
1606                 goto close_fs;
1607         }
1608         inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
1609                                     struct btrfs_inode_item);
1610         total_bytes = btrfs_inode_size(path.nodes[0], inode_item);
1611         btrfs_release_path(&path);
1612
1613         /* Check if we can rollback the image */
1614         ret = check_convert_image(image_root, ino, total_bytes, reserved_ranges);
1615         if (ret < 0) {
1616                 error("old fs image can't be rolled back");
1617                 goto close_fs;
1618         }
1619 close_fs:
1620         btrfs_release_path(&path);
1621         close_ctree_fs_info(fs_info);
1622         if (ret)
1623                 goto free_mem;
1624
1625         /*
1626          * Everything is OK, just write back old fs data into btrfs reserved
1627          * ranges
1628          *
1629          * Here, we starts from the backup blocks first, so if something goes
1630          * wrong, the fs is still mountable
1631          */
1632
1633         for (i = ARRAY_SIZE(btrfs_reserved_ranges) - 1; i >= 0; i--) {
1634                 u64 real_size;
1635                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1636
1637                 if (range_end(range) >= fsize)
1638                         continue;
1639
1640                 real_size = min(range_end(range), fsize) - range->start;
1641                 ret = pwrite(fd, reserved_ranges[i], real_size, range->start);
1642                 if (ret < real_size) {
1643                         if (ret < 0)
1644                                 ret = -errno;
1645                         else
1646                                 ret = -EIO;
1647                         error("failed to recover range [%llu, %llu): %s",
1648                               range->start, real_size, strerror(-ret));
1649                         goto free_mem;
1650                 }
1651                 ret = 0;
1652         }
1653
1654 free_mem:
1655         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++)
1656                 free(reserved_ranges[i]);
1657         if (ret)
1658                 error("rollback failed");
1659         else
1660                 printf("rollback succeeded\n");
1661         return ret;
1662 }
1663
1664 static void print_usage(void)
1665 {
1666         printf("usage: btrfs-convert [options] device\n");
1667         printf("options:\n");
1668         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
1669         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
1670         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
1671         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
1672         printf("\t-r|--rollback          roll back to the original filesystem\n");
1673         printf("\t-l|--label LABEL       set filesystem label\n");
1674         printf("\t-L|--copy-label        use label from converted filesystem\n");
1675         printf("\t-p|--progress          show converting progress (default)\n");
1676         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
1677         printf("\t--no-progress          show only overview, not the detailed progress\n");
1678         printf("\n");
1679         printf("Supported filesystems:\n");
1680         printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
1681         printf("\treiserfs: %s\n", BTRFSCONVERT_REISERFS ? "yes" : "no");
1682 }
1683
1684 int main(int argc, char *argv[])
1685 {
1686         int ret;
1687         int packing = 1;
1688         int noxattr = 0;
1689         int datacsum = 1;
1690         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
1691                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
1692         int rollback = 0;
1693         int copylabel = 0;
1694         int usage_error = 0;
1695         int progress = 1;
1696         char *file;
1697         char fslabel[BTRFS_LABEL_SIZE];
1698         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
1699
1700         while(1) {
1701                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
1702                 static const struct option long_options[] = {
1703                         { "no-progress", no_argument, NULL,
1704                                 GETOPT_VAL_NO_PROGRESS },
1705                         { "no-datasum", no_argument, NULL, 'd' },
1706                         { "no-inline", no_argument, NULL, 'n' },
1707                         { "no-xattr", no_argument, NULL, 'i' },
1708                         { "rollback", no_argument, NULL, 'r' },
1709                         { "features", required_argument, NULL, 'O' },
1710                         { "progress", no_argument, NULL, 'p' },
1711                         { "label", required_argument, NULL, 'l' },
1712                         { "copy-label", no_argument, NULL, 'L' },
1713                         { "nodesize", required_argument, NULL, 'N' },
1714                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
1715                         { NULL, 0, NULL, 0 }
1716                 };
1717                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
1718
1719                 if (c < 0)
1720                         break;
1721                 switch(c) {
1722                         case 'd':
1723                                 datacsum = 0;
1724                                 break;
1725                         case 'i':
1726                                 noxattr = 1;
1727                                 break;
1728                         case 'n':
1729                                 packing = 0;
1730                                 break;
1731                         case 'N':
1732                                 nodesize = parse_size(optarg);
1733                                 break;
1734                         case 'r':
1735                                 rollback = 1;
1736                                 break;
1737                         case 'l':
1738                                 copylabel = CONVERT_FLAG_SET_LABEL;
1739                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
1740                                         warning(
1741                                         "label too long, trimmed to %d bytes",
1742                                                 BTRFS_LABEL_SIZE - 1);
1743                                 }
1744                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
1745                                 break;
1746                         case 'L':
1747                                 copylabel = CONVERT_FLAG_COPY_LABEL;
1748                                 break;
1749                         case 'p':
1750                                 progress = 1;
1751                                 break;
1752                         case 'O': {
1753                                 char *orig = strdup(optarg);
1754                                 char *tmp = orig;
1755
1756                                 tmp = btrfs_parse_fs_features(tmp, &features);
1757                                 if (tmp) {
1758                                         error("unrecognized filesystem feature: %s",
1759                                                         tmp);
1760                                         free(orig);
1761                                         exit(1);
1762                                 }
1763                                 free(orig);
1764                                 if (features & BTRFS_FEATURE_LIST_ALL) {
1765                                         btrfs_list_all_fs_features(
1766                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
1767                                         exit(0);
1768                                 }
1769                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
1770                                         char buf[64];
1771
1772                                         btrfs_parse_features_to_string(buf,
1773                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
1774                                         error("features not allowed for convert: %s",
1775                                                 buf);
1776                                         exit(1);
1777                                 }
1778
1779                                 break;
1780                                 }
1781                         case GETOPT_VAL_NO_PROGRESS:
1782                                 progress = 0;
1783                                 break;
1784                         case GETOPT_VAL_HELP:
1785                         default:
1786                                 print_usage();
1787                                 return c != GETOPT_VAL_HELP;
1788                 }
1789         }
1790         set_argv0(argv);
1791         if (check_argc_exact(argc - optind, 1)) {
1792                 print_usage();
1793                 return 1;
1794         }
1795
1796         if (rollback && (!datacsum || noxattr || !packing)) {
1797                 fprintf(stderr,
1798                         "Usage error: -d, -i, -n options do not apply to rollback\n");
1799                 usage_error++;
1800         }
1801
1802         if (usage_error) {
1803                 print_usage();
1804                 return 1;
1805         }
1806
1807         file = argv[optind];
1808         ret = check_mounted(file);
1809         if (ret < 0) {
1810                 error("could not check mount status: %s", strerror(-ret));
1811                 return 1;
1812         } else if (ret) {
1813                 error("%s is mounted", file);
1814                 return 1;
1815         }
1816
1817         if (rollback) {
1818                 ret = do_rollback(file);
1819         } else {
1820                 u32 cf = 0;
1821
1822                 cf |= datacsum ? CONVERT_FLAG_DATACSUM : 0;
1823                 cf |= packing ? CONVERT_FLAG_INLINE_DATA : 0;
1824                 cf |= noxattr ? 0 : CONVERT_FLAG_XATTR;
1825                 cf |= copylabel;
1826                 ret = do_convert(file, cf, nodesize, fslabel, progress, features);
1827         }
1828         if (ret)
1829                 return 1;
1830         return 0;
1831 }