btrfs-progs: convert: Add comment for the overall convert design
[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
92 #include "ctree.h"
93 #include "disk-io.h"
94 #include "volumes.h"
95 #include "transaction.h"
96 #include "utils.h"
97 #include "task-utils.h"
98 #include "help.h"
99 #include "mkfs/common.h"
100 #include "convert/common.h"
101 #include "convert/source-fs.h"
102 #include "fsfeatures.h"
103
104 const struct btrfs_convert_operations ext2_convert_ops;
105
106 static const struct btrfs_convert_operations *convert_operations[] = {
107 #if BTRFSCONVERT_EXT2
108         &ext2_convert_ops,
109 #endif
110 };
111
112 static void *print_copied_inodes(void *p)
113 {
114         struct task_ctx *priv = p;
115         const char work_indicator[] = { '.', 'o', 'O', 'o' };
116         u64 count = 0;
117
118         task_period_start(priv->info, 1000 /* 1s */);
119         while (1) {
120                 count++;
121                 printf("copy inodes [%c] [%10llu/%10llu]\r",
122                        work_indicator[count % 4],
123                        (unsigned long long)priv->cur_copy_inodes,
124                        (unsigned long long)priv->max_copy_inodes);
125                 fflush(stdout);
126                 task_period_wait(priv->info);
127         }
128
129         return NULL;
130 }
131
132 static int after_copied_inodes(void *p)
133 {
134         printf("\n");
135         fflush(stdout);
136
137         return 0;
138 }
139
140 static inline int copy_inodes(struct btrfs_convert_context *cctx,
141                               struct btrfs_root *root, u32 convert_flags,
142                               struct task_ctx *p)
143 {
144         return cctx->convert_ops->copy_inodes(cctx, root, convert_flags, p);
145 }
146
147 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
148 {
149         cctx->convert_ops->close_fs(cctx);
150 }
151
152 static inline int convert_check_state(struct btrfs_convert_context *cctx)
153 {
154         return cctx->convert_ops->check_state(cctx);
155 }
156
157 static int csum_disk_extent(struct btrfs_trans_handle *trans,
158                             struct btrfs_root *root,
159                             u64 disk_bytenr, u64 num_bytes)
160 {
161         u32 blocksize = root->sectorsize;
162         u64 offset;
163         char *buffer;
164         int ret = 0;
165
166         buffer = malloc(blocksize);
167         if (!buffer)
168                 return -ENOMEM;
169         for (offset = 0; offset < num_bytes; offset += blocksize) {
170                 ret = read_disk_extent(root, disk_bytenr + offset,
171                                         blocksize, buffer);
172                 if (ret)
173                         break;
174                 ret = btrfs_csum_file_block(trans,
175                                             root->fs_info->csum_root,
176                                             disk_bytenr + num_bytes,
177                                             disk_bytenr + offset,
178                                             buffer, blocksize);
179                 if (ret)
180                         break;
181         }
182         free(buffer);
183         return ret;
184 }
185
186 static int create_image_file_range(struct btrfs_trans_handle *trans,
187                                       struct btrfs_root *root,
188                                       struct cache_tree *used,
189                                       struct btrfs_inode_item *inode,
190                                       u64 ino, u64 bytenr, u64 *ret_len,
191                                       u32 convert_flags)
192 {
193         struct cache_extent *cache;
194         struct btrfs_block_group_cache *bg_cache;
195         u64 len = *ret_len;
196         u64 disk_bytenr;
197         int i;
198         int ret;
199         u32 datacsum = convert_flags & CONVERT_FLAG_DATACSUM;
200
201         if (bytenr != round_down(bytenr, root->sectorsize)) {
202                 error("bytenr not sectorsize aligned: %llu",
203                                 (unsigned long long)bytenr);
204                 return -EINVAL;
205         }
206         if (len != round_down(len, root->sectorsize)) {
207                 error("length not sectorsize aligned: %llu",
208                                 (unsigned long long)len);
209                 return -EINVAL;
210         }
211         len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
212
213         /*
214          * Skip sb ranges first
215          * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
216          *
217          * Or we will insert a hole into current image file, and later
218          * migrate block will fail as there is already a file extent.
219          */
220         if (bytenr < 1024 * 1024) {
221                 *ret_len = 1024 * 1024 - bytenr;
222                 return 0;
223         }
224         for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
225                 u64 cur = btrfs_sb_offset(i);
226
227                 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
228                         *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
229                         return 0;
230                 }
231         }
232         for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
233                 u64 cur = btrfs_sb_offset(i);
234
235                 /*
236                  *      |--reserved--|
237                  * |----range-------|
238                  * May still need to go through file extent inserts
239                  */
240                 if (bytenr < cur && bytenr + len >= cur) {
241                         len = min_t(u64, len, cur - bytenr);
242                         break;
243                 }
244                 /*
245                  * |--reserved--|
246                  *      |---range---|
247                  * Drop out, no need to insert anything
248                  */
249                 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
250                         *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
251                         return 0;
252                 }
253         }
254
255         cache = search_cache_extent(used, bytenr);
256         if (cache) {
257                 if (cache->start <= bytenr) {
258                         /*
259                          * |///////Used///////|
260                          *      |<--insert--->|
261                          *      bytenr
262                          */
263                         len = min_t(u64, len, cache->start + cache->size -
264                                     bytenr);
265                         disk_bytenr = bytenr;
266                 } else {
267                         /*
268                          *              |//Used//|
269                          *  |<-insert-->|
270                          *  bytenr
271                          */
272                         len = min(len, cache->start - bytenr);
273                         disk_bytenr = 0;
274                         datacsum = 0;
275                 }
276         } else {
277                 /*
278                  * |//Used//|           |EOF
279                  *          |<-insert-->|
280                  *          bytenr
281                  */
282                 disk_bytenr = 0;
283                 datacsum = 0;
284         }
285
286         if (disk_bytenr) {
287                 /* Check if the range is in a data block group */
288                 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
289                 if (!bg_cache)
290                         return -ENOENT;
291                 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
292                         return -EINVAL;
293
294                 /* The extent should never cross block group boundary */
295                 len = min_t(u64, len, bg_cache->key.objectid +
296                             bg_cache->key.offset - bytenr);
297         }
298
299         if (len != round_down(len, root->sectorsize)) {
300                 error("remaining length not sectorsize aligned: %llu",
301                                 (unsigned long long)len);
302                 return -EINVAL;
303         }
304         ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
305                                        disk_bytenr, len);
306         if (ret < 0)
307                 return ret;
308
309         if (datacsum)
310                 ret = csum_disk_extent(trans, root, bytenr, len);
311         *ret_len = len;
312         return ret;
313 }
314
315 /*
316  * Relocate old fs data in one reserved ranges
317  *
318  * Since all old fs data in reserved range is not covered by any chunk nor
319  * data extent, we don't need to handle any reference but add new
320  * extent/reference, which makes codes more clear
321  */
322 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
323                                       struct btrfs_root *root,
324                                       struct cache_tree *used,
325                                       struct btrfs_inode_item *inode, int fd,
326                                       u64 ino, u64 start, u64 len,
327                                       u32 convert_flags)
328 {
329         u64 cur_off = start;
330         u64 cur_len = len;
331         u64 hole_start = start;
332         u64 hole_len;
333         struct cache_extent *cache;
334         struct btrfs_key key;
335         struct extent_buffer *eb;
336         int ret = 0;
337
338         while (cur_off < start + len) {
339                 cache = lookup_cache_extent(used, cur_off, cur_len);
340                 if (!cache)
341                         break;
342                 cur_off = max(cache->start, cur_off);
343                 cur_len = min(cache->start + cache->size, start + len) -
344                           cur_off;
345                 BUG_ON(cur_len < root->sectorsize);
346
347                 /* reserve extent for the data */
348                 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
349                                            &key, 1);
350                 if (ret < 0)
351                         break;
352
353                 eb = malloc(sizeof(*eb) + cur_len);
354                 if (!eb) {
355                         ret = -ENOMEM;
356                         break;
357                 }
358
359                 ret = pread(fd, eb->data, cur_len, cur_off);
360                 if (ret < cur_len) {
361                         ret = (ret < 0 ? ret : -EIO);
362                         free(eb);
363                         break;
364                 }
365                 eb->start = key.objectid;
366                 eb->len = key.offset;
367
368                 /* Write the data */
369                 ret = write_and_map_eb(root, eb);
370                 free(eb);
371                 if (ret < 0)
372                         break;
373
374                 /* Now handle extent item and file extent things */
375                 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
376                                                key.objectid, key.offset);
377                 if (ret < 0)
378                         break;
379                 /* Finally, insert csum items */
380                 if (convert_flags & CONVERT_FLAG_DATACSUM)
381                         ret = csum_disk_extent(trans, root, key.objectid,
382                                                key.offset);
383
384                 /* Don't forget to insert hole */
385                 hole_len = cur_off - hole_start;
386                 if (hole_len) {
387                         ret = btrfs_record_file_extent(trans, root, ino, inode,
388                                         hole_start, 0, hole_len);
389                         if (ret < 0)
390                                 break;
391                 }
392
393                 cur_off += key.offset;
394                 hole_start = cur_off;
395                 cur_len = start + len - cur_off;
396         }
397         /* Last hole */
398         if (start + len - hole_start > 0)
399                 ret = btrfs_record_file_extent(trans, root, ino, inode,
400                                 hole_start, 0, start + len - hole_start);
401         return ret;
402 }
403
404 /*
405  * Relocate the used ext2 data in reserved ranges
406  * [0,1M)
407  * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
408  * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
409  */
410 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
411                                    struct btrfs_root *root,
412                                    struct cache_tree *used,
413                                    struct btrfs_inode_item *inode, int fd,
414                                    u64 ino, u64 total_bytes, u32 convert_flags)
415 {
416         u64 cur_off;
417         u64 cur_len;
418         int ret = 0;
419
420         /* 0 ~ 1M */
421         cur_off = 0;
422         cur_len = 1024 * 1024;
423         ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
424                                          cur_off, cur_len, convert_flags);
425         if (ret < 0)
426                 return ret;
427
428         /* second sb(fisrt sb is included in 0~1M) */
429         cur_off = btrfs_sb_offset(1);
430         cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
431         if (cur_off > total_bytes)
432                 return ret;
433         ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
434                                          cur_off, cur_len, convert_flags);
435         if (ret < 0)
436                 return ret;
437
438         /* Last sb */
439         cur_off = btrfs_sb_offset(2);
440         cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
441         if (cur_off > total_bytes)
442                 return ret;
443         ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
444                                          cur_off, cur_len, convert_flags);
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 ret;
618
619         ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
620                                       ensure_size);
621         if (ret < 0)
622                 return ret;
623         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
624                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
625         if (ret < 0)
626                 return ret;
627         ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
628                         BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
629         return ret;
630 }
631
632 static int calculate_available_space(struct btrfs_convert_context *cctx)
633 {
634         struct cache_tree *used = &cctx->used_space;
635         struct cache_tree *data_chunks = &cctx->data_chunks;
636         struct cache_tree *free = &cctx->free_space;
637         struct cache_extent *cache;
638         u64 cur_off = 0;
639         /*
640          * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
641          * works without need to consider overlap
642          */
643         u64 min_stripe_size = 2 * 16 * 1024 * 1024;
644         int ret;
645
646         /* Calculate data_chunks */
647         for (cache = first_cache_extent(used); cache;
648              cache = next_cache_extent(cache)) {
649                 u64 cur_len;
650
651                 if (cache->start + cache->size < cur_off)
652                         continue;
653                 if (cache->start > cur_off + min_stripe_size)
654                         cur_off = cache->start;
655                 cur_len = max(cache->start + cache->size - cur_off,
656                               min_stripe_size);
657                 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
658                 if (ret < 0)
659                         goto out;
660                 cur_off += cur_len;
661         }
662         /*
663          * remove reserved ranges, so we won't ever bother relocating an old
664          * filesystem extent to other place.
665          */
666         ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
667         if (ret < 0)
668                 goto out;
669
670         cur_off = 0;
671         /*
672          * Calculate free space
673          * Always round up the start bytenr, to avoid metadata extent corss
674          * stripe boundary, as later mkfs_convert() won't have all the extent
675          * allocation check
676          */
677         for (cache = first_cache_extent(data_chunks); cache;
678              cache = next_cache_extent(cache)) {
679                 if (cache->start < cur_off)
680                         continue;
681                 if (cache->start > cur_off) {
682                         u64 insert_start;
683                         u64 len;
684
685                         len = cache->start - round_up(cur_off,
686                                                       BTRFS_STRIPE_LEN);
687                         insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
688
689                         ret = add_merge_cache_extent(free, insert_start, len);
690                         if (ret < 0)
691                                 goto out;
692                 }
693                 cur_off = cache->start + cache->size;
694         }
695         /* Don't forget the last range */
696         if (cctx->total_bytes > cur_off) {
697                 u64 len = cctx->total_bytes - cur_off;
698                 u64 insert_start;
699
700                 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
701
702                 ret = add_merge_cache_extent(free, insert_start, len);
703                 if (ret < 0)
704                         goto out;
705         }
706
707         /* Remove reserved bytes */
708         ret = wipe_reserved_ranges(free, min_stripe_size, 0);
709 out:
710         return ret;
711 }
712
713 /*
714  * Read used space, and since we have the used space,
715  * calcuate data_chunks and free for later mkfs
716  */
717 static int convert_read_used_space(struct btrfs_convert_context *cctx)
718 {
719         int ret;
720
721         ret = cctx->convert_ops->read_used_space(cctx);
722         if (ret)
723                 return ret;
724
725         ret = calculate_available_space(cctx);
726         return ret;
727 }
728
729 /*
730  * Create the fs image file of old filesystem.
731  *
732  * This is completely fs independent as we have cctx->used, only
733  * need to create file extents pointing to all the positions.
734  */
735 static int create_image(struct btrfs_root *root,
736                            struct btrfs_mkfs_config *cfg,
737                            struct btrfs_convert_context *cctx, int fd,
738                            u64 size, char *name, u32 convert_flags)
739 {
740         struct btrfs_inode_item buf;
741         struct btrfs_trans_handle *trans;
742         struct btrfs_path path;
743         struct btrfs_key key;
744         struct cache_extent *cache;
745         struct cache_tree used_tmp;
746         u64 cur;
747         u64 ino;
748         u64 flags = BTRFS_INODE_READONLY;
749         int ret;
750
751         if (!(convert_flags & CONVERT_FLAG_DATACSUM))
752                 flags |= BTRFS_INODE_NODATASUM;
753
754         trans = btrfs_start_transaction(root, 1);
755         if (!trans)
756                 return -ENOMEM;
757
758         cache_tree_init(&used_tmp);
759         btrfs_init_path(&path);
760
761         ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
762                                        &ino);
763         if (ret < 0)
764                 goto out;
765         ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
766         if (ret < 0)
767                 goto out;
768         ret = btrfs_change_inode_flags(trans, root, ino, flags);
769         if (ret < 0)
770                 goto out;
771         ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
772                              strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
773         if (ret < 0)
774                 goto out;
775
776         key.objectid = ino;
777         key.type = BTRFS_INODE_ITEM_KEY;
778         key.offset = 0;
779
780         ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
781         if (ret) {
782                 ret = (ret > 0 ? -ENOENT : ret);
783                 goto out;
784         }
785         read_extent_buffer(path.nodes[0], &buf,
786                         btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
787                         sizeof(buf));
788         btrfs_release_path(&path);
789
790         /*
791          * Create a new used space cache, which doesn't contain the reserved
792          * range
793          */
794         for (cache = first_cache_extent(&cctx->used_space); cache;
795              cache = next_cache_extent(cache)) {
796                 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
797                 if (ret < 0)
798                         goto out;
799         }
800         ret = wipe_reserved_ranges(&used_tmp, 0, 0);
801         if (ret < 0)
802                 goto out;
803
804         /*
805          * Start from 1M, as 0~1M is reserved, and create_image_file_range()
806          * can't handle bytenr 0(will consider it as a hole)
807          */
808         cur = 1024 * 1024;
809         while (cur < size) {
810                 u64 len = size - cur;
811
812                 ret = create_image_file_range(trans, root, &used_tmp,
813                                                 &buf, ino, cur, &len,
814                                                 convert_flags);
815                 if (ret < 0)
816                         goto out;
817                 cur += len;
818         }
819         /* Handle the reserved ranges */
820         ret = migrate_reserved_ranges(trans, root, &cctx->used_space, &buf, fd,
821                         ino, cfg->num_bytes, convert_flags);
822
823         key.objectid = ino;
824         key.type = BTRFS_INODE_ITEM_KEY;
825         key.offset = 0;
826         ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
827         if (ret) {
828                 ret = (ret > 0 ? -ENOENT : ret);
829                 goto out;
830         }
831         btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
832         write_extent_buffer(path.nodes[0], &buf,
833                         btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
834                         sizeof(buf));
835 out:
836         free_extent_cache_tree(&used_tmp);
837         btrfs_release_path(&path);
838         btrfs_commit_transaction(trans, root);
839         return ret;
840 }
841
842 static struct btrfs_root* link_subvol(struct btrfs_root *root,
843                 const char *base, u64 root_objectid)
844 {
845         struct btrfs_trans_handle *trans;
846         struct btrfs_fs_info *fs_info = root->fs_info;
847         struct btrfs_root *tree_root = fs_info->tree_root;
848         struct btrfs_root *new_root = NULL;
849         struct btrfs_path path;
850         struct btrfs_inode_item *inode_item;
851         struct extent_buffer *leaf;
852         struct btrfs_key key;
853         u64 dirid = btrfs_root_dirid(&root->root_item);
854         u64 index = 2;
855         char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
856         int len;
857         int i;
858         int ret;
859
860         len = strlen(base);
861         if (len == 0 || len > BTRFS_NAME_LEN)
862                 return NULL;
863
864         btrfs_init_path(&path);
865         key.objectid = dirid;
866         key.type = BTRFS_DIR_INDEX_KEY;
867         key.offset = (u64)-1;
868
869         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
870         if (ret <= 0) {
871                 error("search for DIR_INDEX dirid %llu failed: %d",
872                                 (unsigned long long)dirid, ret);
873                 goto fail;
874         }
875
876         if (path.slots[0] > 0) {
877                 path.slots[0]--;
878                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
879                 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
880                         index = key.offset + 1;
881         }
882         btrfs_release_path(&path);
883
884         trans = btrfs_start_transaction(root, 1);
885         if (!trans) {
886                 error("unable to start transaction");
887                 goto fail;
888         }
889
890         key.objectid = dirid;
891         key.offset = 0;
892         key.type =  BTRFS_INODE_ITEM_KEY;
893
894         ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
895         if (ret) {
896                 error("search for INODE_ITEM %llu failed: %d",
897                                 (unsigned long long)dirid, ret);
898                 goto fail;
899         }
900         leaf = path.nodes[0];
901         inode_item = btrfs_item_ptr(leaf, path.slots[0],
902                                     struct btrfs_inode_item);
903
904         key.objectid = root_objectid;
905         key.offset = (u64)-1;
906         key.type = BTRFS_ROOT_ITEM_KEY;
907
908         memcpy(buf, base, len);
909         for (i = 0; i < 1024; i++) {
910                 ret = btrfs_insert_dir_item(trans, root, buf, len,
911                                             dirid, &key, BTRFS_FT_DIR, index);
912                 if (ret != -EEXIST)
913                         break;
914                 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
915                 if (len < 1 || len > BTRFS_NAME_LEN) {
916                         ret = -EINVAL;
917                         break;
918                 }
919         }
920         if (ret)
921                 goto fail;
922
923         btrfs_set_inode_size(leaf, inode_item, len * 2 +
924                              btrfs_inode_size(leaf, inode_item));
925         btrfs_mark_buffer_dirty(leaf);
926         btrfs_release_path(&path);
927
928         /* add the backref first */
929         ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
930                                  BTRFS_ROOT_BACKREF_KEY,
931                                  root->root_key.objectid,
932                                  dirid, index, buf, len);
933         if (ret) {
934                 error("unable to add root backref for %llu: %d",
935                                 root->root_key.objectid, ret);
936                 goto fail;
937         }
938
939         /* now add the forward ref */
940         ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
941                                  BTRFS_ROOT_REF_KEY, root_objectid,
942                                  dirid, index, buf, len);
943         if (ret) {
944                 error("unable to add root ref for %llu: %d",
945                                 root->root_key.objectid, ret);
946                 goto fail;
947         }
948
949         ret = btrfs_commit_transaction(trans, root);
950         if (ret) {
951                 error("transaction commit failed: %d", ret);
952                 goto fail;
953         }
954
955         new_root = btrfs_read_fs_root(fs_info, &key);
956         if (IS_ERR(new_root)) {
957                 error("unable to fs read root: %lu", PTR_ERR(new_root));
958                 new_root = NULL;
959         }
960 fail:
961         btrfs_init_path(&path);
962         return new_root;
963 }
964
965 static int create_subvol(struct btrfs_trans_handle *trans,
966                          struct btrfs_root *root, u64 root_objectid)
967 {
968         struct extent_buffer *tmp;
969         struct btrfs_root *new_root;
970         struct btrfs_key key;
971         struct btrfs_root_item root_item;
972         int ret;
973
974         ret = btrfs_copy_root(trans, root, root->node, &tmp,
975                               root_objectid);
976         if (ret)
977                 return ret;
978
979         memcpy(&root_item, &root->root_item, sizeof(root_item));
980         btrfs_set_root_bytenr(&root_item, tmp->start);
981         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
982         btrfs_set_root_generation(&root_item, trans->transid);
983         free_extent_buffer(tmp);
984
985         key.objectid = root_objectid;
986         key.type = BTRFS_ROOT_ITEM_KEY;
987         key.offset = trans->transid;
988         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
989                                 &key, &root_item);
990
991         key.offset = (u64)-1;
992         new_root = btrfs_read_fs_root(root->fs_info, &key);
993         if (!new_root || IS_ERR(new_root)) {
994                 error("unable to fs read root: %lu", PTR_ERR(new_root));
995                 return PTR_ERR(new_root);
996         }
997
998         ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
999
1000         return ret;
1001 }
1002
1003 /*
1004  * New make_btrfs() has handle system and meta chunks quite well.
1005  * So only need to add remaining data chunks.
1006  */
1007 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1008                                           struct btrfs_fs_info *fs_info,
1009                                           struct btrfs_mkfs_config *cfg,
1010                                           struct btrfs_convert_context *cctx)
1011 {
1012         struct btrfs_root *extent_root = fs_info->extent_root;
1013         struct cache_tree *data_chunks = &cctx->data_chunks;
1014         struct cache_extent *cache;
1015         u64 max_chunk_size;
1016         int ret = 0;
1017
1018         /*
1019          * Don't create data chunk over 10% of the convert device
1020          * And for single chunk, don't create chunk larger than 1G.
1021          */
1022         max_chunk_size = cfg->num_bytes / 10;
1023         max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1024         max_chunk_size = round_down(max_chunk_size, extent_root->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, extent_root,
1037                                         &cur_backup, len,
1038                                         BTRFS_BLOCK_GROUP_DATA, 1);
1039                         if (ret < 0)
1040                                 break;
1041                         ret = btrfs_make_block_group(trans, extent_root, 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 prepare_system_chunk_sb(struct btrfs_super_block *super)
1186 {
1187         struct btrfs_chunk *chunk;
1188         struct btrfs_disk_key *key;
1189         u32 sectorsize = btrfs_super_sectorsize(super);
1190
1191         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1192         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1193                                        sizeof(struct btrfs_disk_key));
1194
1195         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1196         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1197         btrfs_set_disk_key_offset(key, 0);
1198
1199         btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1200         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1201         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1202         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1203         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1204         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1205         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1206         btrfs_set_stack_chunk_num_stripes(chunk, 1);
1207         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1208         chunk->stripe.devid = super->dev_item.devid;
1209         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1210         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1211         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1212         return 0;
1213 }
1214
1215 static int convert_open_fs(const char *devname,
1216                            struct btrfs_convert_context *cctx)
1217 {
1218         int i;
1219
1220         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
1221                 int ret = convert_operations[i]->open_fs(cctx, devname);
1222
1223                 if (ret == 0) {
1224                         cctx->convert_ops = convert_operations[i];
1225                         return ret;
1226                 }
1227         }
1228
1229         error("no file system found to convert");
1230         return -1;
1231 }
1232
1233 static int do_convert(const char *devname, u32 convert_flags, u32 nodesize,
1234                 const char *fslabel, int progress, u64 features)
1235 {
1236         int ret;
1237         int fd = -1;
1238         u32 blocksize;
1239         u64 total_bytes;
1240         struct btrfs_root *root;
1241         struct btrfs_root *image_root;
1242         struct btrfs_convert_context cctx;
1243         struct btrfs_key key;
1244         char subvol_name[SOURCE_FS_NAME_LEN + 8];
1245         struct task_ctx ctx;
1246         char features_buf[64];
1247         struct btrfs_mkfs_config mkfs_cfg;
1248
1249         init_convert_context(&cctx);
1250         ret = convert_open_fs(devname, &cctx);
1251         if (ret)
1252                 goto fail;
1253         ret = convert_check_state(&cctx);
1254         if (ret)
1255                 warning(
1256                 "source filesystem is not clean, running filesystem check is recommended");
1257         ret = convert_read_used_space(&cctx);
1258         if (ret)
1259                 goto fail;
1260
1261         blocksize = cctx.blocksize;
1262         total_bytes = (u64)blocksize * (u64)cctx.block_count;
1263         if (blocksize < 4096) {
1264                 error("block size is too small: %u < 4096", blocksize);
1265                 goto fail;
1266         }
1267         if (btrfs_check_nodesize(nodesize, blocksize, features))
1268                 goto fail;
1269         fd = open(devname, O_RDWR);
1270         if (fd < 0) {
1271                 error("unable to open %s: %s", devname, strerror(errno));
1272                 goto fail;
1273         }
1274         btrfs_parse_features_to_string(features_buf, features);
1275         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
1276                 strcat(features_buf, " (default)");
1277
1278         printf("create btrfs filesystem:\n");
1279         printf("\tblocksize: %u\n", blocksize);
1280         printf("\tnodesize:  %u\n", nodesize);
1281         printf("\tfeatures:  %s\n", features_buf);
1282
1283         memset(&mkfs_cfg, 0, sizeof(mkfs_cfg));
1284         mkfs_cfg.label = cctx.volume_name;
1285         mkfs_cfg.num_bytes = total_bytes;
1286         mkfs_cfg.nodesize = nodesize;
1287         mkfs_cfg.sectorsize = blocksize;
1288         mkfs_cfg.stripesize = blocksize;
1289         mkfs_cfg.features = features;
1290
1291         ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
1292         if (ret) {
1293                 error("unable to create initial ctree: %s", strerror(-ret));
1294                 goto fail;
1295         }
1296
1297         root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
1298                              OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1299         if (!root) {
1300                 error("unable to open ctree");
1301                 goto fail;
1302         }
1303         ret = init_btrfs(&mkfs_cfg, root, &cctx, convert_flags);
1304         if (ret) {
1305                 error("unable to setup the root tree: %d", ret);
1306                 goto fail;
1307         }
1308
1309         printf("creating %s image file\n", cctx.convert_ops->name);
1310         snprintf(subvol_name, sizeof(subvol_name), "%s_saved",
1311                         cctx.convert_ops->name);
1312         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1313         key.offset = (u64)-1;
1314         key.type = BTRFS_ROOT_ITEM_KEY;
1315         image_root = btrfs_read_fs_root(root->fs_info, &key);
1316         if (!image_root) {
1317                 error("unable to create image subvolume");
1318                 goto fail;
1319         }
1320         ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
1321                               mkfs_cfg.num_bytes, "image",
1322                               convert_flags);
1323         if (ret) {
1324                 error("failed to create %s/image: %d", subvol_name, ret);
1325                 goto fail;
1326         }
1327
1328         printf("creating btrfs metadata");
1329         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
1330         ctx.cur_copy_inodes = 0;
1331
1332         if (progress) {
1333                 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
1334                                      &ctx);
1335                 task_start(ctx.info);
1336         }
1337         ret = copy_inodes(&cctx, root, convert_flags, &ctx);
1338         if (ret) {
1339                 error("error during copy_inodes %d", ret);
1340                 goto fail;
1341         }
1342         if (progress) {
1343                 task_stop(ctx.info);
1344                 task_deinit(ctx.info);
1345         }
1346
1347         image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
1348         if (!image_root) {
1349                 error("unable to link subvolume %s", subvol_name);
1350                 goto fail;
1351         }
1352
1353         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
1354         if (convert_flags & CONVERT_FLAG_COPY_LABEL) {
1355                 __strncpy_null(root->fs_info->super_copy->label,
1356                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
1357                 printf("copy label '%s'\n", root->fs_info->super_copy->label);
1358         } else if (convert_flags & CONVERT_FLAG_SET_LABEL) {
1359                 strcpy(root->fs_info->super_copy->label, fslabel);
1360                 printf("set label to '%s'\n", fslabel);
1361         }
1362
1363         ret = close_ctree(root);
1364         if (ret) {
1365                 error("close_ctree failed: %d", ret);
1366                 goto fail;
1367         }
1368         convert_close_fs(&cctx);
1369         clean_convert_context(&cctx);
1370
1371         /*
1372          * If this step succeed, we get a mountable btrfs. Otherwise
1373          * the source fs is left unchanged.
1374          */
1375         ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
1376         if (ret) {
1377                 error("unable to migrate super block: %d", ret);
1378                 goto fail;
1379         }
1380
1381         root = open_ctree_fd(fd, devname, 0,
1382                         OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1383         if (!root) {
1384                 error("unable to open ctree for finalization");
1385                 goto fail;
1386         }
1387         root->fs_info->finalize_on_close = 1;
1388         close_ctree(root);
1389         close(fd);
1390
1391         printf("conversion complete");
1392         return 0;
1393 fail:
1394         clean_convert_context(&cctx);
1395         if (fd != -1)
1396                 close(fd);
1397         warning(
1398 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
1399         return -1;
1400 }
1401
1402 /*
1403  * Check if a non 1:1 mapped chunk can be rolled back.
1404  * For new convert, it's OK while for old convert it's not.
1405  */
1406 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
1407 {
1408         struct btrfs_block_group_cache *bg;
1409         struct btrfs_key key;
1410         struct btrfs_path path;
1411         struct btrfs_root *extent_root = fs_info->extent_root;
1412         u64 bg_start;
1413         u64 bg_end;
1414         int ret;
1415
1416         bg = btrfs_lookup_first_block_group(fs_info, bytenr);
1417         if (!bg)
1418                 return -ENOENT;
1419         bg_start = bg->key.objectid;
1420         bg_end = bg->key.objectid + bg->key.offset;
1421
1422         key.objectid = bg_end;
1423         key.type = BTRFS_METADATA_ITEM_KEY;
1424         key.offset = 0;
1425         btrfs_init_path(&path);
1426
1427         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
1428         if (ret < 0)
1429                 return ret;
1430
1431         while (1) {
1432                 struct btrfs_extent_item *ei;
1433
1434                 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
1435                 if (ret > 0) {
1436                         ret = 0;
1437                         break;
1438                 }
1439                 if (ret < 0)
1440                         break;
1441
1442                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1443                 if (key.type == BTRFS_METADATA_ITEM_KEY)
1444                         continue;
1445                 /* Now it's EXTENT_ITEM_KEY only */
1446                 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
1447                                     struct btrfs_extent_item);
1448                 /*
1449                  * Found data extent, means this is old convert must follow 1:1
1450                  * mapping.
1451                  */
1452                 if (btrfs_extent_flags(path.nodes[0], ei)
1453                                 & BTRFS_EXTENT_FLAG_DATA) {
1454                         ret = -EINVAL;
1455                         break;
1456                 }
1457         }
1458         btrfs_release_path(&path);
1459         return ret;
1460 }
1461
1462 static int may_rollback(struct btrfs_root *root)
1463 {
1464         struct btrfs_fs_info *info = root->fs_info;
1465         struct btrfs_multi_bio *multi = NULL;
1466         u64 bytenr;
1467         u64 length;
1468         u64 physical;
1469         u64 total_bytes;
1470         int num_stripes;
1471         int ret;
1472
1473         if (btrfs_super_num_devices(info->super_copy) != 1)
1474                 goto fail;
1475
1476         bytenr = BTRFS_SUPER_INFO_OFFSET;
1477         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1478
1479         while (1) {
1480                 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
1481                                       &length, &multi, 0, NULL);
1482                 if (ret) {
1483                         if (ret == -ENOENT) {
1484                                 /* removed block group at the tail */
1485                                 if (length == (u64)-1)
1486                                         break;
1487
1488                                 /* removed block group in the middle */
1489                                 goto next;
1490                         }
1491                         goto fail;
1492                 }
1493
1494                 num_stripes = multi->num_stripes;
1495                 physical = multi->stripes[0].physical;
1496                 free(multi);
1497
1498                 if (num_stripes != 1) {
1499                         error("num stripes for bytenr %llu is not 1", bytenr);
1500                         goto fail;
1501                 }
1502
1503                 /*
1504                  * Extra check for new convert, as metadata chunk from new
1505                  * convert is much more free than old convert, it doesn't need
1506                  * to do 1:1 mapping.
1507                  */
1508                 if (physical != bytenr) {
1509                         /*
1510                          * Check if it's a metadata chunk and has only metadata
1511                          * extent.
1512                          */
1513                         ret = may_rollback_chunk(info, bytenr);
1514                         if (ret < 0)
1515                                 goto fail;
1516                 }
1517 next:
1518                 bytenr += length;
1519                 if (bytenr >= total_bytes)
1520                         break;
1521         }
1522         return 0;
1523 fail:
1524         return -1;
1525 }
1526
1527 static int do_rollback(const char *devname)
1528 {
1529         int fd = -1;
1530         int ret;
1531         int i;
1532         struct btrfs_root *root;
1533         struct btrfs_root *image_root;
1534         struct btrfs_root *chunk_root;
1535         struct btrfs_dir_item *dir;
1536         struct btrfs_inode_item *inode;
1537         struct btrfs_file_extent_item *fi;
1538         struct btrfs_trans_handle *trans;
1539         struct extent_buffer *leaf;
1540         struct btrfs_block_group_cache *cache1;
1541         struct btrfs_block_group_cache *cache2;
1542         struct btrfs_key key;
1543         struct btrfs_path path;
1544         struct extent_io_tree io_tree;
1545         char *buf = NULL;
1546         char *name;
1547         u64 bytenr;
1548         u64 num_bytes;
1549         u64 root_dir;
1550         u64 objectid;
1551         u64 offset;
1552         u64 start;
1553         u64 end;
1554         u64 sb_bytenr;
1555         u64 first_free;
1556         u64 total_bytes;
1557         u32 sectorsize;
1558
1559         extent_io_tree_init(&io_tree);
1560
1561         fd = open(devname, O_RDWR);
1562         if (fd < 0) {
1563                 error("unable to open %s: %s", devname, strerror(errno));
1564                 goto fail;
1565         }
1566         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
1567         if (!root) {
1568                 error("unable to open ctree");
1569                 goto fail;
1570         }
1571         ret = may_rollback(root);
1572         if (ret < 0) {
1573                 error("unable to do rollback: %d", ret);
1574                 goto fail;
1575         }
1576
1577         sectorsize = root->sectorsize;
1578         buf = malloc(sectorsize);
1579         if (!buf) {
1580                 error("unable to allocate memory");
1581                 goto fail;
1582         }
1583
1584         btrfs_init_path(&path);
1585
1586         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1587         key.type = BTRFS_ROOT_BACKREF_KEY;
1588         key.offset = BTRFS_FS_TREE_OBJECTID;
1589         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
1590                                 0);
1591         btrfs_release_path(&path);
1592         if (ret > 0) {
1593                 error("unable to convert ext2 image subvolume, is it deleted?");
1594                 goto fail;
1595         } else if (ret < 0) {
1596                 error("unable to open ext2_saved, id %llu: %s",
1597                         (unsigned long long)key.objectid, strerror(-ret));
1598                 goto fail;
1599         }
1600
1601         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1602         key.type = BTRFS_ROOT_ITEM_KEY;
1603         key.offset = (u64)-1;
1604         image_root = btrfs_read_fs_root(root->fs_info, &key);
1605         if (!image_root || IS_ERR(image_root)) {
1606                 error("unable to open subvolume %llu: %ld",
1607                         (unsigned long long)key.objectid, PTR_ERR(image_root));
1608                 goto fail;
1609         }
1610
1611         name = "image";
1612         root_dir = btrfs_root_dirid(&root->root_item);
1613         dir = btrfs_lookup_dir_item(NULL, image_root, &path,
1614                                    root_dir, name, strlen(name), 0);
1615         if (!dir || IS_ERR(dir)) {
1616                 error("unable to find file %s: %ld", name, PTR_ERR(dir));
1617                 goto fail;
1618         }
1619         leaf = path.nodes[0];
1620         btrfs_dir_item_key_to_cpu(leaf, dir, &key);
1621         btrfs_release_path(&path);
1622
1623         objectid = key.objectid;
1624
1625         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
1626         if (ret) {
1627                 error("unable to find inode item: %d", ret);
1628                 goto fail;
1629         }
1630         leaf = path.nodes[0];
1631         inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
1632         total_bytes = btrfs_inode_size(leaf, inode);
1633         btrfs_release_path(&path);
1634
1635         key.objectid = objectid;
1636         key.offset = 0;
1637         key.type = BTRFS_EXTENT_DATA_KEY;
1638         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
1639         if (ret != 0) {
1640                 error("unable to find first file extent: %d", ret);
1641                 btrfs_release_path(&path);
1642                 goto fail;
1643         }
1644
1645         /* build mapping tree for the relocated blocks */
1646         for (offset = 0; offset < total_bytes; ) {
1647                 leaf = path.nodes[0];
1648                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1649                         ret = btrfs_next_leaf(root, &path);
1650                         if (ret != 0)
1651                                 break;  
1652                         continue;
1653                 }
1654
1655                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1656                 if (key.objectid != objectid || key.offset != offset ||
1657                     key.type != BTRFS_EXTENT_DATA_KEY)
1658                         break;
1659
1660                 fi = btrfs_item_ptr(leaf, path.slots[0],
1661                                     struct btrfs_file_extent_item);
1662                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
1663                         break;
1664                 if (btrfs_file_extent_compression(leaf, fi) ||
1665                     btrfs_file_extent_encryption(leaf, fi) ||
1666                     btrfs_file_extent_other_encoding(leaf, fi))
1667                         break;
1668
1669                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1670                 /* skip holes and direct mapped extents */
1671                 if (bytenr == 0 || bytenr == offset)
1672                         goto next_extent;
1673
1674                 bytenr += btrfs_file_extent_offset(leaf, fi);
1675                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
1676
1677                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
1678                 cache2 = btrfs_lookup_block_group(root->fs_info,
1679                                                   offset + num_bytes - 1);
1680                 /*
1681                  * Here we must take consideration of old and new convert
1682                  * behavior.
1683                  * For old convert case, sign, there is no consist chunk type
1684                  * that will cover the extent. META/DATA/SYS are all possible.
1685                  * Just ensure relocate one is in SYS chunk.
1686                  * For new convert case, they are all covered by DATA chunk.
1687                  *
1688                  * So, there is not valid chunk type check for it now.
1689                  */
1690                 if (cache1 != cache2)
1691                         break;
1692
1693                 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
1694                                 EXTENT_LOCKED);
1695                 set_state_private(&io_tree, offset, bytenr);
1696 next_extent:
1697                 offset += btrfs_file_extent_num_bytes(leaf, fi);
1698                 path.slots[0]++;
1699         }
1700         btrfs_release_path(&path);
1701
1702         if (offset < total_bytes) {
1703                 error("unable to build extent mapping (offset %llu, total_bytes %llu)",
1704                                 (unsigned long long)offset,
1705                                 (unsigned long long)total_bytes);
1706                 error("converted filesystem after balance is unable to rollback");
1707                 goto fail;
1708         }
1709
1710         first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
1711         first_free &= ~((u64)sectorsize - 1);
1712         /* backup for extent #0 should exist */
1713         if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
1714                 error("no backup for the first extent");
1715                 goto fail;
1716         }
1717         /* force no allocation from system block group */
1718         root->fs_info->system_allocs = -1;
1719         trans = btrfs_start_transaction(root, 1);
1720         if (!trans) {
1721                 error("unable to start transaction");
1722                 goto fail;
1723         }
1724         /*
1725          * recow the whole chunk tree, this will remove all chunk tree blocks
1726          * from system block group
1727          */
1728         chunk_root = root->fs_info->chunk_root;
1729         memset(&key, 0, sizeof(key));
1730         while (1) {
1731                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
1732                 if (ret < 0)
1733                         break;
1734
1735                 ret = btrfs_next_leaf(chunk_root, &path);
1736                 if (ret)
1737                         break;
1738
1739                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1740                 btrfs_release_path(&path);
1741         }
1742         btrfs_release_path(&path);
1743
1744         offset = 0;
1745         num_bytes = 0;
1746         while(1) {
1747                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
1748                 if (!cache1)
1749                         break;
1750
1751                 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
1752                         num_bytes += btrfs_block_group_used(&cache1->item);
1753
1754                 offset = cache1->key.objectid + cache1->key.offset;
1755         }
1756         /* only extent #0 left in system block group? */
1757         if (num_bytes > first_free) {
1758                 error(
1759         "unable to empty system block group (num_bytes %llu, first_free %llu",
1760                                 (unsigned long long)num_bytes,
1761                                 (unsigned long long)first_free);
1762                 goto fail;
1763         }
1764         /* create a system chunk that maps the whole device */
1765         ret = prepare_system_chunk_sb(root->fs_info->super_copy);
1766         if (ret) {
1767                 error("unable to update system chunk: %d", ret);
1768                 goto fail;
1769         }
1770
1771         ret = btrfs_commit_transaction(trans, root);
1772         if (ret) {
1773                 error("transaction commit failed: %d", ret);
1774                 goto fail;
1775         }
1776
1777         ret = close_ctree(root);
1778         if (ret) {
1779                 error("close_ctree failed: %d", ret);
1780                 goto fail;
1781         }
1782
1783         /* zero btrfs super block mirrors */
1784         memset(buf, 0, sectorsize);
1785         for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1786                 bytenr = btrfs_sb_offset(i);
1787                 if (bytenr >= total_bytes)
1788                         break;
1789                 ret = pwrite(fd, buf, sectorsize, bytenr);
1790                 if (ret != sectorsize) {
1791                         error("zeroing superblock mirror %d failed: %d",
1792                                         i, ret);
1793                         goto fail;
1794                 }
1795         }
1796
1797         sb_bytenr = (u64)-1;
1798         /* copy all relocated blocks back */
1799         while(1) {
1800                 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
1801                                             EXTENT_LOCKED);
1802                 if (ret)
1803                         break;
1804
1805                 ret = get_state_private(&io_tree, start, &bytenr);
1806                 BUG_ON(ret);
1807
1808                 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED);
1809
1810                 while (start <= end) {
1811                         if (start == BTRFS_SUPER_INFO_OFFSET) {
1812                                 sb_bytenr = bytenr;
1813                                 goto next_sector;
1814                         }
1815                         ret = pread(fd, buf, sectorsize, bytenr);
1816                         if (ret < 0) {
1817                                 error("reading superblock at %llu failed: %d",
1818                                                 (unsigned long long)bytenr, ret);
1819                                 goto fail;
1820                         }
1821                         BUG_ON(ret != sectorsize);
1822                         ret = pwrite(fd, buf, sectorsize, start);
1823                         if (ret < 0) {
1824                                 error("writing superblock at %llu failed: %d",
1825                                                 (unsigned long long)start, ret);
1826                                 goto fail;
1827                         }
1828                         BUG_ON(ret != sectorsize);
1829 next_sector:
1830                         start += sectorsize;
1831                         bytenr += sectorsize;
1832                 }
1833         }
1834
1835         ret = fsync(fd);
1836         if (ret < 0) {
1837                 error("fsync failed: %s", strerror(errno));
1838                 goto fail;
1839         }
1840         /*
1841          * finally, overwrite btrfs super block.
1842          */
1843         ret = pread(fd, buf, sectorsize, sb_bytenr);
1844         if (ret < 0) {
1845                 error("reading primary superblock failed: %s",
1846                                 strerror(errno));
1847                 goto fail;
1848         }
1849         BUG_ON(ret != sectorsize);
1850         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1851         if (ret < 0) {
1852                 error("writing primary superblock failed: %s",
1853                                 strerror(errno));
1854                 goto fail;
1855         }
1856         BUG_ON(ret != sectorsize);
1857         ret = fsync(fd);
1858         if (ret < 0) {
1859                 error("fsync failed: %s", strerror(errno));
1860                 goto fail;
1861         }
1862
1863         close(fd);
1864         free(buf);
1865         extent_io_tree_cleanup(&io_tree);
1866         printf("rollback complete\n");
1867         return 0;
1868
1869 fail:
1870         if (fd != -1)
1871                 close(fd);
1872         free(buf);
1873         error("rollback aborted");
1874         return -1;
1875 }
1876
1877 static void print_usage(void)
1878 {
1879         printf("usage: btrfs-convert [options] device\n");
1880         printf("options:\n");
1881         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
1882         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
1883         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
1884         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
1885         printf("\t-r|--rollback          roll back to the original filesystem\n");
1886         printf("\t-l|--label LABEL       set filesystem label\n");
1887         printf("\t-L|--copy-label        use label from converted filesystem\n");
1888         printf("\t-p|--progress          show converting progress (default)\n");
1889         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
1890         printf("\t--no-progress          show only overview, not the detailed progress\n");
1891         printf("\n");
1892         printf("Supported filesystems:\n");
1893         printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
1894 }
1895
1896 int main(int argc, char *argv[])
1897 {
1898         int ret;
1899         int packing = 1;
1900         int noxattr = 0;
1901         int datacsum = 1;
1902         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
1903                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
1904         int rollback = 0;
1905         int copylabel = 0;
1906         int usage_error = 0;
1907         int progress = 1;
1908         char *file;
1909         char fslabel[BTRFS_LABEL_SIZE];
1910         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
1911
1912         while(1) {
1913                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
1914                 static const struct option long_options[] = {
1915                         { "no-progress", no_argument, NULL,
1916                                 GETOPT_VAL_NO_PROGRESS },
1917                         { "no-datasum", no_argument, NULL, 'd' },
1918                         { "no-inline", no_argument, NULL, 'n' },
1919                         { "no-xattr", no_argument, NULL, 'i' },
1920                         { "rollback", no_argument, NULL, 'r' },
1921                         { "features", required_argument, NULL, 'O' },
1922                         { "progress", no_argument, NULL, 'p' },
1923                         { "label", required_argument, NULL, 'l' },
1924                         { "copy-label", no_argument, NULL, 'L' },
1925                         { "nodesize", required_argument, NULL, 'N' },
1926                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
1927                         { NULL, 0, NULL, 0 }
1928                 };
1929                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
1930
1931                 if (c < 0)
1932                         break;
1933                 switch(c) {
1934                         case 'd':
1935                                 datacsum = 0;
1936                                 break;
1937                         case 'i':
1938                                 noxattr = 1;
1939                                 break;
1940                         case 'n':
1941                                 packing = 0;
1942                                 break;
1943                         case 'N':
1944                                 nodesize = parse_size(optarg);
1945                                 break;
1946                         case 'r':
1947                                 rollback = 1;
1948                                 break;
1949                         case 'l':
1950                                 copylabel = CONVERT_FLAG_SET_LABEL;
1951                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
1952                                         warning(
1953                                         "label too long, trimmed to %d bytes",
1954                                                 BTRFS_LABEL_SIZE - 1);
1955                                 }
1956                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
1957                                 break;
1958                         case 'L':
1959                                 copylabel = CONVERT_FLAG_COPY_LABEL;
1960                                 break;
1961                         case 'p':
1962                                 progress = 1;
1963                                 break;
1964                         case 'O': {
1965                                 char *orig = strdup(optarg);
1966                                 char *tmp = orig;
1967
1968                                 tmp = btrfs_parse_fs_features(tmp, &features);
1969                                 if (tmp) {
1970                                         error("unrecognized filesystem feature: %s",
1971                                                         tmp);
1972                                         free(orig);
1973                                         exit(1);
1974                                 }
1975                                 free(orig);
1976                                 if (features & BTRFS_FEATURE_LIST_ALL) {
1977                                         btrfs_list_all_fs_features(
1978                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
1979                                         exit(0);
1980                                 }
1981                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
1982                                         char buf[64];
1983
1984                                         btrfs_parse_features_to_string(buf,
1985                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
1986                                         error("features not allowed for convert: %s",
1987                                                 buf);
1988                                         exit(1);
1989                                 }
1990
1991                                 break;
1992                                 }
1993                         case GETOPT_VAL_NO_PROGRESS:
1994                                 progress = 0;
1995                                 break;
1996                         case GETOPT_VAL_HELP:
1997                         default:
1998                                 print_usage();
1999                                 return c != GETOPT_VAL_HELP;
2000                 }
2001         }
2002         set_argv0(argv);
2003         if (check_argc_exact(argc - optind, 1)) {
2004                 print_usage();
2005                 return 1;
2006         }
2007
2008         if (rollback && (!datacsum || noxattr || !packing)) {
2009                 fprintf(stderr,
2010                         "Usage error: -d, -i, -n options do not apply to rollback\n");
2011                 usage_error++;
2012         }
2013
2014         if (usage_error) {
2015                 print_usage();
2016                 return 1;
2017         }
2018
2019         file = argv[optind];
2020         ret = check_mounted(file);
2021         if (ret < 0) {
2022                 error("could not check mount status: %s", strerror(-ret));
2023                 return 1;
2024         } else if (ret) {
2025                 error("%s is mounted", file);
2026                 return 1;
2027         }
2028
2029         if (rollback) {
2030                 ret = do_rollback(file);
2031         } else {
2032                 u32 cf = 0;
2033
2034                 cf |= datacsum ? CONVERT_FLAG_DATACSUM : 0;
2035                 cf |= packing ? CONVERT_FLAG_INLINE_DATA : 0;
2036                 cf |= noxattr ? 0 : CONVERT_FLAG_XATTR;
2037                 cf |= copylabel;
2038                 ret = do_convert(file, cf, nodesize, fslabel, progress, features);
2039         }
2040         if (ret)
2041                 return 1;
2042         return 0;
2043 }