btrfs-progs: convert: add support for converting reiserfs
[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 (!trans)
755                 return -ENOMEM;
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);
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 struct btrfs_root* link_subvol(struct btrfs_root *root,
842                 const char *base, u64 root_objectid)
843 {
844         struct btrfs_trans_handle *trans;
845         struct btrfs_fs_info *fs_info = root->fs_info;
846         struct btrfs_root *tree_root = fs_info->tree_root;
847         struct btrfs_root *new_root = NULL;
848         struct btrfs_path path;
849         struct btrfs_inode_item *inode_item;
850         struct extent_buffer *leaf;
851         struct btrfs_key key;
852         u64 dirid = btrfs_root_dirid(&root->root_item);
853         u64 index = 2;
854         char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
855         int len;
856         int i;
857         int ret;
858
859         len = strlen(base);
860         if (len == 0 || len > BTRFS_NAME_LEN)
861                 return NULL;
862
863         btrfs_init_path(&path);
864         key.objectid = dirid;
865         key.type = BTRFS_DIR_INDEX_KEY;
866         key.offset = (u64)-1;
867
868         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
869         if (ret <= 0) {
870                 error("search for DIR_INDEX dirid %llu failed: %d",
871                                 (unsigned long long)dirid, ret);
872                 goto fail;
873         }
874
875         if (path.slots[0] > 0) {
876                 path.slots[0]--;
877                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
878                 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
879                         index = key.offset + 1;
880         }
881         btrfs_release_path(&path);
882
883         trans = btrfs_start_transaction(root, 1);
884         if (!trans) {
885                 error("unable to start transaction");
886                 goto fail;
887         }
888
889         key.objectid = dirid;
890         key.offset = 0;
891         key.type =  BTRFS_INODE_ITEM_KEY;
892
893         ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
894         if (ret) {
895                 error("search for INODE_ITEM %llu failed: %d",
896                                 (unsigned long long)dirid, ret);
897                 goto fail;
898         }
899         leaf = path.nodes[0];
900         inode_item = btrfs_item_ptr(leaf, path.slots[0],
901                                     struct btrfs_inode_item);
902
903         key.objectid = root_objectid;
904         key.offset = (u64)-1;
905         key.type = BTRFS_ROOT_ITEM_KEY;
906
907         memcpy(buf, base, len);
908         for (i = 0; i < 1024; i++) {
909                 ret = btrfs_insert_dir_item(trans, root, buf, len,
910                                             dirid, &key, BTRFS_FT_DIR, index);
911                 if (ret != -EEXIST)
912                         break;
913                 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
914                 if (len < 1 || len > BTRFS_NAME_LEN) {
915                         ret = -EINVAL;
916                         break;
917                 }
918         }
919         if (ret)
920                 goto fail;
921
922         btrfs_set_inode_size(leaf, inode_item, len * 2 +
923                              btrfs_inode_size(leaf, inode_item));
924         btrfs_mark_buffer_dirty(leaf);
925         btrfs_release_path(&path);
926
927         /* add the backref first */
928         ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
929                                  BTRFS_ROOT_BACKREF_KEY,
930                                  root->root_key.objectid,
931                                  dirid, index, buf, len);
932         if (ret) {
933                 error("unable to add root backref for %llu: %d",
934                                 root->root_key.objectid, ret);
935                 goto fail;
936         }
937
938         /* now add the forward ref */
939         ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
940                                  BTRFS_ROOT_REF_KEY, root_objectid,
941                                  dirid, index, buf, len);
942         if (ret) {
943                 error("unable to add root ref for %llu: %d",
944                                 root->root_key.objectid, ret);
945                 goto fail;
946         }
947
948         ret = btrfs_commit_transaction(trans, root);
949         if (ret) {
950                 error("transaction commit failed: %d", ret);
951                 goto fail;
952         }
953
954         new_root = btrfs_read_fs_root(fs_info, &key);
955         if (IS_ERR(new_root)) {
956                 error("unable to fs read root: %lu", PTR_ERR(new_root));
957                 new_root = NULL;
958         }
959 fail:
960         btrfs_init_path(&path);
961         return new_root;
962 }
963
964 static int create_subvol(struct btrfs_trans_handle *trans,
965                          struct btrfs_root *root, u64 root_objectid)
966 {
967         struct extent_buffer *tmp;
968         struct btrfs_root *new_root;
969         struct btrfs_key key;
970         struct btrfs_root_item root_item;
971         int ret;
972
973         ret = btrfs_copy_root(trans, root, root->node, &tmp,
974                               root_objectid);
975         if (ret)
976                 return ret;
977
978         memcpy(&root_item, &root->root_item, sizeof(root_item));
979         btrfs_set_root_bytenr(&root_item, tmp->start);
980         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
981         btrfs_set_root_generation(&root_item, trans->transid);
982         free_extent_buffer(tmp);
983
984         key.objectid = root_objectid;
985         key.type = BTRFS_ROOT_ITEM_KEY;
986         key.offset = trans->transid;
987         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
988                                 &key, &root_item);
989
990         key.offset = (u64)-1;
991         new_root = btrfs_read_fs_root(root->fs_info, &key);
992         if (!new_root || IS_ERR(new_root)) {
993                 error("unable to fs read root: %lu", PTR_ERR(new_root));
994                 return PTR_ERR(new_root);
995         }
996
997         ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
998
999         return ret;
1000 }
1001
1002 /*
1003  * New make_btrfs() has handle system and meta chunks quite well.
1004  * So only need to add remaining data chunks.
1005  */
1006 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1007                                           struct btrfs_fs_info *fs_info,
1008                                           struct btrfs_mkfs_config *cfg,
1009                                           struct btrfs_convert_context *cctx)
1010 {
1011         struct btrfs_root *extent_root = fs_info->extent_root;
1012         struct cache_tree *data_chunks = &cctx->data_chunks;
1013         struct cache_extent *cache;
1014         u64 max_chunk_size;
1015         int ret = 0;
1016
1017         /*
1018          * Don't create data chunk over 10% of the convert device
1019          * And for single chunk, don't create chunk larger than 1G.
1020          */
1021         max_chunk_size = cfg->num_bytes / 10;
1022         max_chunk_size = min((u64)(SZ_1G), max_chunk_size);
1023         max_chunk_size = round_down(max_chunk_size,
1024                                     extent_root->fs_info->sectorsize);
1025
1026         for (cache = first_cache_extent(data_chunks); cache;
1027              cache = next_cache_extent(cache)) {
1028                 u64 cur = cache->start;
1029
1030                 while (cur < cache->start + cache->size) {
1031                         u64 len;
1032                         u64 cur_backup = cur;
1033
1034                         len = min(max_chunk_size,
1035                                   cache->start + cache->size - cur);
1036                         ret = btrfs_alloc_data_chunk(trans, fs_info,
1037                                         &cur_backup, len,
1038                                         BTRFS_BLOCK_GROUP_DATA, 1);
1039                         if (ret < 0)
1040                                 break;
1041                         ret = btrfs_make_block_group(trans, fs_info, 0,
1042                                         BTRFS_BLOCK_GROUP_DATA,
1043                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1044                                         cur, len);
1045                         if (ret < 0)
1046                                 break;
1047                         cur += len;
1048                 }
1049         }
1050         return ret;
1051 }
1052
1053 /*
1054  * Init the temp btrfs to a operational status.
1055  *
1056  * It will fix the extent usage accounting(XXX: Do we really need?) and
1057  * insert needed data chunks, to ensure all old fs data extents are covered
1058  * by DATA chunks, preventing wrong chunks are allocated.
1059  *
1060  * And also create convert image subvolume and relocation tree.
1061  * (XXX: Not need again?)
1062  * But the convert image subvolume is *NOT* linked to fs tree yet.
1063  */
1064 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1065                          struct btrfs_convert_context *cctx, u32 convert_flags)
1066 {
1067         struct btrfs_key location;
1068         struct btrfs_trans_handle *trans;
1069         struct btrfs_fs_info *fs_info = root->fs_info;
1070         int ret;
1071
1072         /*
1073          * Don't alloc any metadata/system chunk, as we don't want
1074          * any meta/sys chunk allcated before all data chunks are inserted.
1075          * Or we screw up the chunk layout just like the old implement.
1076          */
1077         fs_info->avoid_sys_chunk_alloc = 1;
1078         fs_info->avoid_meta_chunk_alloc = 1;
1079         trans = btrfs_start_transaction(root, 1);
1080         if (!trans) {
1081                 error("unable to start transaction");
1082                 ret = -EINVAL;
1083                 goto err;
1084         }
1085         ret = btrfs_fix_block_accounting(trans, root);
1086         if (ret)
1087                 goto err;
1088         ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1089         if (ret)
1090                 goto err;
1091         ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1092                                   BTRFS_ROOT_TREE_DIR_OBJECTID);
1093         if (ret)
1094                 goto err;
1095         memcpy(&location, &root->root_key, sizeof(location));
1096         location.offset = (u64)-1;
1097         ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1098                                 btrfs_super_root_dir(fs_info->super_copy),
1099                                 &location, BTRFS_FT_DIR, 0);
1100         if (ret)
1101                 goto err;
1102         ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1103                                 location.objectid,
1104                                 btrfs_super_root_dir(fs_info->super_copy), 0);
1105         if (ret)
1106                 goto err;
1107         btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1108                              BTRFS_FIRST_FREE_OBJECTID);
1109
1110         /* subvol for fs image file */
1111         ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1112         if (ret < 0) {
1113                 error("failed to create subvolume image root: %d", ret);
1114                 goto err;
1115         }
1116         /* subvol for data relocation tree */
1117         ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1118         if (ret < 0) {
1119                 error("failed to create DATA_RELOC root: %d", ret);
1120                 goto err;
1121         }
1122
1123         ret = btrfs_commit_transaction(trans, root);
1124         fs_info->avoid_sys_chunk_alloc = 0;
1125         fs_info->avoid_meta_chunk_alloc = 0;
1126 err:
1127         return ret;
1128 }
1129
1130 /*
1131  * Migrate super block to its default position and zero 0 ~ 16k
1132  */
1133 static int migrate_super_block(int fd, u64 old_bytenr)
1134 {
1135         int ret;
1136         struct extent_buffer *buf;
1137         struct btrfs_super_block *super;
1138         u32 len;
1139         u32 bytenr;
1140
1141         buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1142         if (!buf)
1143                 return -ENOMEM;
1144
1145         buf->len = BTRFS_SUPER_INFO_SIZE;
1146         ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, old_bytenr);
1147         if (ret != BTRFS_SUPER_INFO_SIZE)
1148                 goto fail;
1149
1150         super = (struct btrfs_super_block *)buf->data;
1151         BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1152         btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1153
1154         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1155         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
1156                 BTRFS_SUPER_INFO_OFFSET);
1157         if (ret != BTRFS_SUPER_INFO_SIZE)
1158                 goto fail;
1159
1160         ret = fsync(fd);
1161         if (ret)
1162                 goto fail;
1163
1164         memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1165         for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1166                 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1167                 if (len > BTRFS_SUPER_INFO_SIZE)
1168                         len = BTRFS_SUPER_INFO_SIZE;
1169                 ret = pwrite(fd, buf->data, len, bytenr);
1170                 if (ret != len) {
1171                         fprintf(stderr, "unable to zero fill device\n");
1172                         break;
1173                 }
1174                 bytenr += len;
1175         }
1176         ret = 0;
1177         fsync(fd);
1178 fail:
1179         free(buf);
1180         if (ret > 0)
1181                 ret = -1;
1182         return ret;
1183 }
1184
1185 static int convert_open_fs(const char *devname,
1186                            struct btrfs_convert_context *cctx)
1187 {
1188         int i;
1189
1190         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
1191                 int ret = convert_operations[i]->open_fs(cctx, devname);
1192
1193                 if (ret == 0) {
1194                         cctx->convert_ops = convert_operations[i];
1195                         return ret;
1196                 }
1197         }
1198
1199         error("no file system found to convert");
1200         return -1;
1201 }
1202
1203 static int do_convert(const char *devname, u32 convert_flags, u32 nodesize,
1204                 const char *fslabel, int progress, u64 features)
1205 {
1206         int ret;
1207         int fd = -1;
1208         u32 blocksize;
1209         u64 total_bytes;
1210         struct btrfs_root *root;
1211         struct btrfs_root *image_root;
1212         struct btrfs_convert_context cctx;
1213         struct btrfs_key key;
1214         char subvol_name[SOURCE_FS_NAME_LEN + 8];
1215         struct task_ctx ctx;
1216         char features_buf[64];
1217         struct btrfs_mkfs_config mkfs_cfg;
1218
1219         init_convert_context(&cctx);
1220         ret = convert_open_fs(devname, &cctx);
1221         if (ret)
1222                 goto fail;
1223         ret = convert_check_state(&cctx);
1224         if (ret)
1225                 warning(
1226                 "source filesystem is not clean, running filesystem check is recommended");
1227         ret = convert_read_used_space(&cctx);
1228         if (ret)
1229                 goto fail;
1230
1231         blocksize = cctx.blocksize;
1232         total_bytes = (u64)blocksize * (u64)cctx.block_count;
1233         if (blocksize < 4096) {
1234                 error("block size is too small: %u < 4096", blocksize);
1235                 goto fail;
1236         }
1237         if (btrfs_check_nodesize(nodesize, blocksize, features))
1238                 goto fail;
1239         fd = open(devname, O_RDWR);
1240         if (fd < 0) {
1241                 error("unable to open %s: %s", devname, strerror(errno));
1242                 goto fail;
1243         }
1244         btrfs_parse_features_to_string(features_buf, features);
1245         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
1246                 strcat(features_buf, " (default)");
1247
1248         printf("create btrfs filesystem:\n");
1249         printf("\tblocksize: %u\n", blocksize);
1250         printf("\tnodesize:  %u\n", nodesize);
1251         printf("\tfeatures:  %s\n", features_buf);
1252
1253         memset(&mkfs_cfg, 0, sizeof(mkfs_cfg));
1254         mkfs_cfg.label = cctx.volume_name;
1255         mkfs_cfg.num_bytes = total_bytes;
1256         mkfs_cfg.nodesize = nodesize;
1257         mkfs_cfg.sectorsize = blocksize;
1258         mkfs_cfg.stripesize = blocksize;
1259         mkfs_cfg.features = features;
1260
1261         ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
1262         if (ret) {
1263                 error("unable to create initial ctree: %s", strerror(-ret));
1264                 goto fail;
1265         }
1266
1267         root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
1268                              OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1269         if (!root) {
1270                 error("unable to open ctree");
1271                 goto fail;
1272         }
1273         ret = init_btrfs(&mkfs_cfg, root, &cctx, convert_flags);
1274         if (ret) {
1275                 error("unable to setup the root tree: %d", ret);
1276                 goto fail;
1277         }
1278
1279         printf("creating %s image file\n", cctx.convert_ops->name);
1280         snprintf(subvol_name, sizeof(subvol_name), "%s_saved",
1281                         cctx.convert_ops->name);
1282         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1283         key.offset = (u64)-1;
1284         key.type = BTRFS_ROOT_ITEM_KEY;
1285         image_root = btrfs_read_fs_root(root->fs_info, &key);
1286         if (!image_root) {
1287                 error("unable to create image subvolume");
1288                 goto fail;
1289         }
1290         ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
1291                               mkfs_cfg.num_bytes, "image",
1292                               convert_flags);
1293         if (ret) {
1294                 error("failed to create %s/image: %d", subvol_name, ret);
1295                 goto fail;
1296         }
1297
1298         printf("creating btrfs metadata\n");
1299         ret = pthread_mutex_init(&ctx.mutex, NULL);
1300         if (ret) {
1301                 error("failed to initialize mutex: %d", ret);
1302                 goto fail;
1303         }
1304         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
1305         ctx.cur_copy_inodes = 0;
1306
1307         if (progress) {
1308                 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
1309                                      &ctx);
1310                 task_start(ctx.info);
1311         }
1312         ret = copy_inodes(&cctx, root, convert_flags, &ctx);
1313         if (ret) {
1314                 error("error during copy_inodes %d", ret);
1315                 goto fail;
1316         }
1317         if (progress) {
1318                 task_stop(ctx.info);
1319                 task_deinit(ctx.info);
1320         }
1321
1322         image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
1323         if (!image_root) {
1324                 error("unable to link subvolume %s", subvol_name);
1325                 goto fail;
1326         }
1327
1328         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
1329         if (convert_flags & CONVERT_FLAG_COPY_LABEL) {
1330                 __strncpy_null(root->fs_info->super_copy->label,
1331                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
1332                 printf("copy label '%s'\n", root->fs_info->super_copy->label);
1333         } else if (convert_flags & CONVERT_FLAG_SET_LABEL) {
1334                 strcpy(root->fs_info->super_copy->label, fslabel);
1335                 printf("set label to '%s'\n", fslabel);
1336         }
1337
1338         ret = close_ctree(root);
1339         if (ret) {
1340                 error("close_ctree failed: %d", ret);
1341                 goto fail;
1342         }
1343         convert_close_fs(&cctx);
1344         clean_convert_context(&cctx);
1345
1346         /*
1347          * If this step succeed, we get a mountable btrfs. Otherwise
1348          * the source fs is left unchanged.
1349          */
1350         ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
1351         if (ret) {
1352                 error("unable to migrate super block: %d", ret);
1353                 goto fail;
1354         }
1355
1356         root = open_ctree_fd(fd, devname, 0,
1357                         OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1358         if (!root) {
1359                 error("unable to open ctree for finalization");
1360                 goto fail;
1361         }
1362         root->fs_info->finalize_on_close = 1;
1363         close_ctree(root);
1364         close(fd);
1365
1366         printf("conversion complete\n");
1367         return 0;
1368 fail:
1369         clean_convert_context(&cctx);
1370         if (fd != -1)
1371                 close(fd);
1372         warning(
1373 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
1374         return -1;
1375 }
1376
1377 /*
1378  * Read out data of convert image which is in btrfs reserved ranges so we can
1379  * use them to overwrite the ranges during rollback.
1380  */
1381 static int read_reserved_ranges(struct btrfs_root *root, u64 ino,
1382                                 u64 total_bytes, char *reserved_ranges[])
1383 {
1384         int i;
1385         int ret = 0;
1386
1387         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
1388                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1389
1390                 if (range->start + range->len >= total_bytes)
1391                         break;
1392                 ret = btrfs_read_file(root, ino, range->start, range->len,
1393                                       reserved_ranges[i]);
1394                 if (ret < range->len) {
1395                         error(
1396         "failed to read data of convert image, offset=%llu len=%llu ret=%d",
1397                               range->start, range->len, ret);
1398                         if (ret >= 0)
1399                                 ret = -EIO;
1400                         break;
1401                 }
1402                 ret = 0;
1403         }
1404         return ret;
1405 }
1406
1407 static bool is_subset_of_reserved_ranges(u64 start, u64 len)
1408 {
1409         int i;
1410         bool ret = false;
1411
1412         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
1413                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1414
1415                 if (start >= range->start && start + len <= range_end(range)) {
1416                         ret = true;
1417                         break;
1418                 }
1419         }
1420         return ret;
1421 }
1422
1423 static bool is_chunk_direct_mapped(struct btrfs_fs_info *fs_info, u64 start)
1424 {
1425         struct cache_extent *ce;
1426         struct map_lookup *map;
1427         bool ret = false;
1428
1429         ce = search_cache_extent(&fs_info->mapping_tree.cache_tree, start);
1430         if (!ce)
1431                 goto out;
1432         if (ce->start > start || ce->start + ce->size < start)
1433                 goto out;
1434
1435         map = container_of(ce, struct map_lookup, ce);
1436
1437         /* Not SINGLE chunk */
1438         if (map->num_stripes != 1)
1439                 goto out;
1440
1441         /* Chunk's logical doesn't match with phisical, not 1:1 mapped */
1442         if (map->ce.start != map->stripes[0].physical)
1443                 goto out;
1444         ret = true;
1445 out:
1446         return ret;
1447 }
1448
1449 /*
1450  * Iterate all file extents of the convert image.
1451  *
1452  * All file extents except ones in btrfs_reserved_ranges must be mapped 1:1
1453  * on disk. (Means thier file_offset must match their on disk bytenr)
1454  *
1455  * File extents in reserved ranges can be relocated to other place, and in
1456  * that case we will read them out for later use.
1457  */
1458 static int check_convert_image(struct btrfs_root *image_root, u64 ino,
1459                                u64 total_size, char *reserved_ranges[])
1460 {
1461         struct btrfs_key key;
1462         struct btrfs_path path;
1463         struct btrfs_fs_info *fs_info = image_root->fs_info;
1464         u64 checked_bytes = 0;
1465         int ret;
1466
1467         key.objectid = ino;
1468         key.offset = 0;
1469         key.type = BTRFS_EXTENT_DATA_KEY;
1470
1471         btrfs_init_path(&path);
1472         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
1473         /*
1474          * It's possible that some fs doesn't store any (including sb)
1475          * data into 0~1M range, and NO_HOLES is enabled.
1476          *
1477          * So we only need to check if ret < 0
1478          */
1479         if (ret < 0) {
1480                 error("failed to iterate file extents at offset 0: %s",
1481                         strerror(-ret));
1482                 btrfs_release_path(&path);
1483                 return ret;
1484         }
1485
1486         /* Loop from the first file extents */
1487         while (1) {
1488                 struct btrfs_file_extent_item *fi;
1489                 struct extent_buffer *leaf = path.nodes[0];
1490                 u64 disk_bytenr;
1491                 u64 file_offset;
1492                 u64 ram_bytes;
1493                 int slot = path.slots[0];
1494
1495                 if (slot >= btrfs_header_nritems(leaf))
1496                         goto next;
1497                 btrfs_item_key_to_cpu(leaf, &key, slot);
1498
1499                 /*
1500                  * Iteration is done, exit normally, we have extra check out of
1501                  * the loop
1502                  */
1503                 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
1504                         ret = 0;
1505                         break;
1506                 }
1507                 file_offset = key.offset;
1508                 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1509                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG) {
1510                         ret = -EINVAL;
1511                         error(
1512                 "ino %llu offset %llu doesn't have a regular file extent",
1513                                 ino, file_offset);
1514                         break;
1515                 }
1516                 if (btrfs_file_extent_compression(leaf, fi) ||
1517                     btrfs_file_extent_encryption(leaf, fi) ||
1518                     btrfs_file_extent_other_encoding(leaf, fi)) {
1519                         ret = -EINVAL;
1520                         error(
1521                         "ino %llu offset %llu doesn't have a plain file extent",
1522                                 ino, file_offset);
1523                         break;
1524                 }
1525
1526                 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1527                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1528
1529                 checked_bytes += ram_bytes;
1530                 /* Skip hole */
1531                 if (disk_bytenr == 0)
1532                         goto next;
1533
1534                 /*
1535                  * Most file extents must be 1:1 mapped, which means 2 things:
1536                  * 1) File extent file offset == disk_bytenr
1537                  * 2) That data chunk's logical == chunk's physical
1538                  *
1539                  * So file extent's file offset == physical position on disk.
1540                  *
1541                  * And after rolling back btrfs reserved range, other part
1542                  * remains what old fs used to be.
1543                  */
1544                 if (file_offset != disk_bytenr ||
1545                     !is_chunk_direct_mapped(fs_info, disk_bytenr)) {
1546                         /*
1547                          * Only file extent in btrfs reserved ranges are
1548                          * allowed to be non-1:1 mapped
1549                          */
1550                         if (!is_subset_of_reserved_ranges(file_offset,
1551                                                         ram_bytes)) {
1552                                 ret = -EINVAL;
1553                                 error(
1554                 "ino %llu offset %llu file extent should not be relocated",
1555                                         ino, file_offset);
1556                                 break;
1557                         }
1558                 }
1559 next:
1560                 ret = btrfs_next_item(image_root, &path);
1561                 if (ret) {
1562                         if (ret > 0)
1563                                 ret = 0;
1564                         break;
1565                 }
1566         }
1567         btrfs_release_path(&path);
1568         /*
1569          * For HOLES mode (without NO_HOLES), we must ensure file extents
1570          * cover the whole range of the image
1571          */
1572         if (!ret && !btrfs_fs_incompat(fs_info, NO_HOLES)) {
1573                 if (checked_bytes != total_size) {
1574                         ret = -EINVAL;
1575                         error("inode %llu has some file extents not checked",
1576                                 ino);
1577                         return ret;
1578                 }
1579         }
1580
1581         /* So far so good, read old data located in btrfs reserved ranges */
1582         ret = read_reserved_ranges(image_root, ino, total_size,
1583                                    reserved_ranges);
1584         return ret;
1585 }
1586
1587 /*
1588  * btrfs rollback is just reverted convert:
1589  * |<---------------Btrfs fs------------------------------>|
1590  * |<-   Old data chunk  ->|< new chunk (D/M/S)>|<- ODC  ->|
1591  * |<-Old-FE->| |<-Old-FE->|<- Btrfs extents  ->|<-Old-FE->|
1592  *                           ||
1593  *                           \/
1594  * |<------------------Old fs----------------------------->|
1595  * |<- used ->| |<- used ->|                    |<- used ->|
1596  *
1597  * However things are much easier than convert, we don't really need to
1598  * do the complex space calculation, but only to handle btrfs reserved space
1599  *
1600  * |<---------------------------Btrfs fs----------------------------->|
1601  * |   RSV 1   |  | Old  |   |    RSV 2  | | Old  | |   RSV 3   |
1602  * |   0~1M    |  | Fs   |   | SB2 + 64K | | Fs   | | SB3 + 64K |
1603  *
1604  * On the other hand, the converted fs image in btrfs is a completely
1605  * valid old fs.
1606  *
1607  * |<-----------------Converted fs image in btrfs-------------------->|
1608  * |   RSV 1   |  | Old  |   |    RSV 2  | | Old  | |   RSV 3   |
1609  * | Relocated |  | Fs   |   | Relocated | | Fs   | | Relocated |
1610  *
1611  * Used space in fs image should be at the same physical position on disk.
1612  * We only need to recover the data in reserved ranges, so the whole
1613  * old fs is back.
1614  *
1615  * The idea to rollback is also straightforward, we just "read" out the data
1616  * of reserved ranges, and write them back to there they should be.
1617  * Then the old fs is back.
1618  */
1619 static int do_rollback(const char *devname)
1620 {
1621         struct btrfs_root *root;
1622         struct btrfs_root *image_root;
1623         struct btrfs_fs_info *fs_info;
1624         struct btrfs_key key;
1625         struct btrfs_path path;
1626         struct btrfs_dir_item *dir;
1627         struct btrfs_inode_item *inode_item;
1628         char *image_name = "image";
1629         char *reserved_ranges[ARRAY_SIZE(btrfs_reserved_ranges)] = { NULL };
1630         u64 total_bytes;
1631         u64 fsize;
1632         u64 root_dir;
1633         u64 ino;
1634         int fd = -1;
1635         int ret;
1636         int i;
1637
1638         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
1639                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1640
1641                 reserved_ranges[i] = calloc(1, range->len);
1642                 if (!reserved_ranges[i]) {
1643                         ret = -ENOMEM;
1644                         goto free_mem;
1645                 }
1646         }
1647         fd = open(devname, O_RDWR);
1648         if (fd < 0) {
1649                 error("unable to open %s: %s", devname, strerror(errno));
1650                 ret = -EIO;
1651                 goto free_mem;
1652         }
1653         fsize = lseek(fd, 0, SEEK_END);
1654         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
1655         if (!root) {
1656                 error("unable to open ctree");
1657                 ret = -EIO;
1658                 goto free_mem;
1659         }
1660         fs_info = root->fs_info;
1661
1662         /*
1663          * Search root backref first, or after subvolume deletion (orphan),
1664          * we can still rollback the image.
1665          */
1666         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1667         key.type = BTRFS_ROOT_BACKREF_KEY;
1668         key.offset = BTRFS_FS_TREE_OBJECTID;
1669         btrfs_init_path(&path);
1670         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, &path, 0, 0);
1671         btrfs_release_path(&path);
1672         if (ret > 0) {
1673                 error("unable to find source fs image subvolume, is it deleted?");
1674                 ret = -ENOENT;
1675                 goto close_fs;
1676         } else if (ret < 0) {
1677                 error("failed to find source fs image subvolume: %s",
1678                         strerror(-ret));
1679                 goto close_fs;
1680         }
1681
1682         /* Search convert subvolume */
1683         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1684         key.type = BTRFS_ROOT_ITEM_KEY;
1685         key.offset = (u64)-1;
1686         image_root = btrfs_read_fs_root(fs_info, &key);
1687         if (IS_ERR(image_root)) {
1688                 ret = PTR_ERR(image_root);
1689                 error("failed to open convert image subvolume: %s",
1690                         strerror(-ret));
1691                 goto close_fs;
1692         }
1693
1694         /* Search the image file */
1695         root_dir = btrfs_root_dirid(&image_root->root_item);
1696         dir = btrfs_lookup_dir_item(NULL, image_root, &path, root_dir,
1697                         image_name, strlen(image_name), 0);
1698
1699         if (!dir || IS_ERR(dir)) {
1700                 btrfs_release_path(&path);
1701                 if (dir)
1702                         ret = PTR_ERR(dir);
1703                 else
1704                         ret = -ENOENT;
1705                 error("failed to locate file %s: %s", image_name,
1706                         strerror(-ret));
1707                 goto close_fs;
1708         }
1709         btrfs_dir_item_key_to_cpu(path.nodes[0], dir, &key);
1710         btrfs_release_path(&path);
1711
1712         /* Get total size of the original image */
1713         ino = key.objectid;
1714
1715         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
1716
1717         if (ret < 0) {
1718                 btrfs_release_path(&path);
1719                 error("unable to find inode %llu: %s", ino, strerror(-ret));
1720                 goto close_fs;
1721         }
1722         inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
1723                                     struct btrfs_inode_item);
1724         total_bytes = btrfs_inode_size(path.nodes[0], inode_item);
1725         btrfs_release_path(&path);
1726
1727         /* Check if we can rollback the image */
1728         ret = check_convert_image(image_root, ino, total_bytes, reserved_ranges);
1729         if (ret < 0) {
1730                 error("old fs image can't be rolled back");
1731                 goto close_fs;
1732         }
1733 close_fs:
1734         btrfs_release_path(&path);
1735         close_ctree_fs_info(fs_info);
1736         if (ret)
1737                 goto free_mem;
1738
1739         /*
1740          * Everything is OK, just write back old fs data into btrfs reserved
1741          * ranges
1742          *
1743          * Here, we starts from the backup blocks first, so if something goes
1744          * wrong, the fs is still mountable
1745          */
1746
1747         for (i = ARRAY_SIZE(btrfs_reserved_ranges) - 1; i >= 0; i--) {
1748                 u64 real_size;
1749                 const struct simple_range *range = &btrfs_reserved_ranges[i];
1750
1751                 if (range_end(range) >= fsize)
1752                         continue;
1753
1754                 real_size = min(range_end(range), fsize) - range->start;
1755                 ret = pwrite(fd, reserved_ranges[i], real_size, range->start);
1756                 if (ret < real_size) {
1757                         if (ret < 0)
1758                                 ret = -errno;
1759                         else
1760                                 ret = -EIO;
1761                         error("failed to recover range [%llu, %llu): %s",
1762                               range->start, real_size, strerror(-ret));
1763                         goto free_mem;
1764                 }
1765                 ret = 0;
1766         }
1767
1768 free_mem:
1769         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++)
1770                 free(reserved_ranges[i]);
1771         if (ret)
1772                 error("rollback failed");
1773         else
1774                 printf("rollback succeeded\n");
1775         return ret;
1776 }
1777
1778 static void print_usage(void)
1779 {
1780         printf("usage: btrfs-convert [options] device\n");
1781         printf("options:\n");
1782         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
1783         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
1784         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
1785         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
1786         printf("\t-r|--rollback          roll back to the original filesystem\n");
1787         printf("\t-l|--label LABEL       set filesystem label\n");
1788         printf("\t-L|--copy-label        use label from converted filesystem\n");
1789         printf("\t-p|--progress          show converting progress (default)\n");
1790         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
1791         printf("\t--no-progress          show only overview, not the detailed progress\n");
1792         printf("\n");
1793         printf("Supported filesystems:\n");
1794         printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
1795         printf("\treiserfs: %s\n", BTRFSCONVERT_REISERFS ? "yes" : "no");
1796 }
1797
1798 int main(int argc, char *argv[])
1799 {
1800         int ret;
1801         int packing = 1;
1802         int noxattr = 0;
1803         int datacsum = 1;
1804         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
1805                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
1806         int rollback = 0;
1807         int copylabel = 0;
1808         int usage_error = 0;
1809         int progress = 1;
1810         char *file;
1811         char fslabel[BTRFS_LABEL_SIZE];
1812         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
1813
1814         while(1) {
1815                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
1816                 static const struct option long_options[] = {
1817                         { "no-progress", no_argument, NULL,
1818                                 GETOPT_VAL_NO_PROGRESS },
1819                         { "no-datasum", no_argument, NULL, 'd' },
1820                         { "no-inline", no_argument, NULL, 'n' },
1821                         { "no-xattr", no_argument, NULL, 'i' },
1822                         { "rollback", no_argument, NULL, 'r' },
1823                         { "features", required_argument, NULL, 'O' },
1824                         { "progress", no_argument, NULL, 'p' },
1825                         { "label", required_argument, NULL, 'l' },
1826                         { "copy-label", no_argument, NULL, 'L' },
1827                         { "nodesize", required_argument, NULL, 'N' },
1828                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
1829                         { NULL, 0, NULL, 0 }
1830                 };
1831                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
1832
1833                 if (c < 0)
1834                         break;
1835                 switch(c) {
1836                         case 'd':
1837                                 datacsum = 0;
1838                                 break;
1839                         case 'i':
1840                                 noxattr = 1;
1841                                 break;
1842                         case 'n':
1843                                 packing = 0;
1844                                 break;
1845                         case 'N':
1846                                 nodesize = parse_size(optarg);
1847                                 break;
1848                         case 'r':
1849                                 rollback = 1;
1850                                 break;
1851                         case 'l':
1852                                 copylabel = CONVERT_FLAG_SET_LABEL;
1853                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
1854                                         warning(
1855                                         "label too long, trimmed to %d bytes",
1856                                                 BTRFS_LABEL_SIZE - 1);
1857                                 }
1858                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
1859                                 break;
1860                         case 'L':
1861                                 copylabel = CONVERT_FLAG_COPY_LABEL;
1862                                 break;
1863                         case 'p':
1864                                 progress = 1;
1865                                 break;
1866                         case 'O': {
1867                                 char *orig = strdup(optarg);
1868                                 char *tmp = orig;
1869
1870                                 tmp = btrfs_parse_fs_features(tmp, &features);
1871                                 if (tmp) {
1872                                         error("unrecognized filesystem feature: %s",
1873                                                         tmp);
1874                                         free(orig);
1875                                         exit(1);
1876                                 }
1877                                 free(orig);
1878                                 if (features & BTRFS_FEATURE_LIST_ALL) {
1879                                         btrfs_list_all_fs_features(
1880                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
1881                                         exit(0);
1882                                 }
1883                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
1884                                         char buf[64];
1885
1886                                         btrfs_parse_features_to_string(buf,
1887                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
1888                                         error("features not allowed for convert: %s",
1889                                                 buf);
1890                                         exit(1);
1891                                 }
1892
1893                                 break;
1894                                 }
1895                         case GETOPT_VAL_NO_PROGRESS:
1896                                 progress = 0;
1897                                 break;
1898                         case GETOPT_VAL_HELP:
1899                         default:
1900                                 print_usage();
1901                                 return c != GETOPT_VAL_HELP;
1902                 }
1903         }
1904         set_argv0(argv);
1905         if (check_argc_exact(argc - optind, 1)) {
1906                 print_usage();
1907                 return 1;
1908         }
1909
1910         if (rollback && (!datacsum || noxattr || !packing)) {
1911                 fprintf(stderr,
1912                         "Usage error: -d, -i, -n options do not apply to rollback\n");
1913                 usage_error++;
1914         }
1915
1916         if (usage_error) {
1917                 print_usage();
1918                 return 1;
1919         }
1920
1921         file = argv[optind];
1922         ret = check_mounted(file);
1923         if (ret < 0) {
1924                 error("could not check mount status: %s", strerror(-ret));
1925                 return 1;
1926         } else if (ret) {
1927                 error("%s is mounted", file);
1928                 return 1;
1929         }
1930
1931         if (rollback) {
1932                 ret = do_rollback(file);
1933         } else {
1934                 u32 cf = 0;
1935
1936                 cf |= datacsum ? CONVERT_FLAG_DATACSUM : 0;
1937                 cf |= packing ? CONVERT_FLAG_INLINE_DATA : 0;
1938                 cf |= noxattr ? 0 : CONVERT_FLAG_XATTR;
1939                 cf |= copylabel;
1940                 ret = do_convert(file, cf, nodesize, fslabel, progress, features);
1941         }
1942         if (ret)
1943                 return 1;
1944         return 0;
1945 }