btrfs-progs: convert: Introduce function to read out btrfs reserved range
[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 reserved ranges first
215          *
216          * Or we will insert a hole into current image file, and later
217          * migrate block will fail as there is already a file extent.
218          */
219         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
220                 struct simple_range *reserved = &btrfs_reserved_ranges[i];
221
222                 /*
223                  * |-- reserved --|
224                  *         |--range---|
225                  * or
226                  * |---- reserved ----|
227                  *    |-- range --|
228                  * Skip to reserved range end
229                  */
230                 if (bytenr >= reserved->start && bytenr < range_end(reserved)) {
231                         *ret_len = range_end(reserved) - bytenr;
232                         return 0;
233                 }
234
235                 /*
236                  *      |---reserved---|
237                  * |----range-------|
238                  * Leading part may still create a file extent
239                  */
240                 if (bytenr < reserved->start &&
241                     bytenr + len >= range_end(reserved)) {
242                         len = min_t(u64, len, reserved->start - bytenr);
243                         break;
244                 }
245         }
246
247         /* Check if we are going to insert regular file extent, or hole */
248         cache = search_cache_extent(used, bytenr);
249         if (cache) {
250                 if (cache->start <= bytenr) {
251                         /*
252                          * |///////Used///////|
253                          *      |<--insert--->|
254                          *      bytenr
255                          * Insert one real file extent
256                          */
257                         len = min_t(u64, len, cache->start + cache->size -
258                                     bytenr);
259                         disk_bytenr = bytenr;
260                 } else {
261                         /*
262                          *              |//Used//|
263                          *  |<-insert-->|
264                          *  bytenr
265                          *  Insert one hole
266                          */
267                         len = min(len, cache->start - bytenr);
268                         disk_bytenr = 0;
269                         datacsum = 0;
270                 }
271         } else {
272                 /*
273                  * |//Used//|           |EOF
274                  *          |<-insert-->|
275                  *          bytenr
276                  * Insert one hole
277                  */
278                 disk_bytenr = 0;
279                 datacsum = 0;
280         }
281
282         if (disk_bytenr) {
283                 /* Check if the range is in a data block group */
284                 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
285                 if (!bg_cache)
286                         return -ENOENT;
287                 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
288                         return -EINVAL;
289
290                 /* The extent should never cross block group boundary */
291                 len = min_t(u64, len, bg_cache->key.objectid +
292                             bg_cache->key.offset - bytenr);
293         }
294
295         if (len != round_down(len, root->sectorsize)) {
296                 error("remaining length not sectorsize aligned: %llu",
297                                 (unsigned long long)len);
298                 return -EINVAL;
299         }
300         ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
301                                        disk_bytenr, len);
302         if (ret < 0)
303                 return ret;
304
305         if (datacsum)
306                 ret = csum_disk_extent(trans, root, bytenr, len);
307         *ret_len = len;
308         return ret;
309 }
310
311 /*
312  * Relocate old fs data in one reserved ranges
313  *
314  * Since all old fs data in reserved range is not covered by any chunk nor
315  * data extent, we don't need to handle any reference but add new
316  * extent/reference, which makes codes more clear
317  */
318 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
319                                       struct btrfs_root *root,
320                                       struct cache_tree *used,
321                                       struct btrfs_inode_item *inode, int fd,
322                                       u64 ino, struct simple_range *range,
323                                       u32 convert_flags)
324 {
325         u64 cur_off = range->start;
326         u64 cur_len = range->len;
327         u64 hole_start = range->start;
328         u64 hole_len;
329         struct cache_extent *cache;
330         struct btrfs_key key;
331         struct extent_buffer *eb;
332         int ret = 0;
333
334         /*
335          * It's possible that there are holes in reserved range:
336          * |<---------------- Reserved range ---------------------->|
337          *      |<- Old fs data ->|   |<- Old fs data ->|
338          * So here we need to iterate through old fs used space and only
339          * migrate ranges that covered by old fs data.
340          */
341         while (cur_off < range_end(range)) {
342                 cache = lookup_cache_extent(used, cur_off, cur_len);
343                 if (!cache)
344                         break;
345                 cur_off = max(cache->start, cur_off);
346                 cur_len = min(cache->start + cache->size, range_end(range)) -
347                           cur_off;
348                 BUG_ON(cur_len < root->sectorsize);
349
350                 /* reserve extent for the data */
351                 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
352                                            &key, 1);
353                 if (ret < 0)
354                         break;
355
356                 eb = malloc(sizeof(*eb) + cur_len);
357                 if (!eb) {
358                         ret = -ENOMEM;
359                         break;
360                 }
361
362                 ret = pread(fd, eb->data, cur_len, cur_off);
363                 if (ret < cur_len) {
364                         ret = (ret < 0 ? ret : -EIO);
365                         free(eb);
366                         break;
367                 }
368                 eb->start = key.objectid;
369                 eb->len = key.offset;
370
371                 /* Write the data */
372                 ret = write_and_map_eb(root, eb);
373                 free(eb);
374                 if (ret < 0)
375                         break;
376
377                 /* Now handle extent item and file extent things */
378                 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
379                                                key.objectid, key.offset);
380                 if (ret < 0)
381                         break;
382                 /* Finally, insert csum items */
383                 if (convert_flags & CONVERT_FLAG_DATACSUM)
384                         ret = csum_disk_extent(trans, root, key.objectid,
385                                                key.offset);
386
387                 /* Don't forget to insert hole */
388                 hole_len = cur_off - hole_start;
389                 if (hole_len) {
390                         ret = btrfs_record_file_extent(trans, root, ino, inode,
391                                         hole_start, 0, hole_len);
392                         if (ret < 0)
393                                 break;
394                 }
395
396                 cur_off += key.offset;
397                 hole_start = cur_off;
398                 cur_len = range_end(range) - cur_off;
399         }
400         /*
401          * Last hole
402          * |<---- reserved -------->|
403          * |<- Old fs data ->|      |
404          *                   | Hole |
405          */
406         if (range_end(range) - hole_start > 0)
407                 ret = btrfs_record_file_extent(trans, root, ino, inode,
408                                 hole_start, 0, range_end(range) - hole_start);
409         return ret;
410 }
411
412 /*
413  * Relocate the used ext2 data in reserved ranges
414  */
415 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
416                                    struct btrfs_root *root,
417                                    struct cache_tree *used,
418                                    struct btrfs_inode_item *inode, int fd,
419                                    u64 ino, u64 total_bytes, u32 convert_flags)
420 {
421         int i;
422         int ret = 0;
423
424         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
425                 struct simple_range *range = &btrfs_reserved_ranges[i];
426
427                 if (range->start > total_bytes)
428                         return ret;
429                 ret = migrate_one_reserved_range(trans, root, used, inode, fd,
430                                                  ino, range, convert_flags);
431                 if (ret < 0)
432                         return ret;
433         }
434
435         return ret;
436 }
437
438 /*
439  * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
440  * handle wiping a range that exists in cache.
441  */
442 static int _expand_extent_cache(struct cache_tree *tree,
443                                 struct cache_extent *entry,
444                                 u64 min_stripe_size, int backward)
445 {
446         struct cache_extent *ce;
447         int diff;
448
449         if (entry->size >= min_stripe_size)
450                 return 0;
451         diff = min_stripe_size - entry->size;
452
453         if (backward) {
454                 ce = prev_cache_extent(entry);
455                 if (!ce)
456                         goto expand_back;
457                 if (ce->start + ce->size >= entry->start - diff) {
458                         /* Directly merge with previous extent */
459                         ce->size = entry->start + entry->size - ce->start;
460                         remove_cache_extent(tree, entry);
461                         free(entry);
462                         return 0;
463                 }
464 expand_back:
465                 /* No overlap, normal extent */
466                 if (entry->start < diff) {
467                         error("cannot find space for data chunk layout");
468                         return -ENOSPC;
469                 }
470                 entry->start -= diff;
471                 entry->size += diff;
472                 return 0;
473         }
474         ce = next_cache_extent(entry);
475         if (!ce)
476                 goto expand_after;
477         if (entry->start + entry->size + diff >= ce->start) {
478                 /* Directly merge with next extent */
479                 entry->size = ce->start + ce->size - entry->start;
480                 remove_cache_extent(tree, ce);
481                 free(ce);
482                 return 0;
483         }
484 expand_after:
485         entry->size += diff;
486         return 0;
487 }
488
489 /*
490  * Remove one reserve range from given cache tree
491  * if min_stripe_size is non-zero, it will ensure for split case,
492  * all its split cache extent is no smaller than @min_strip_size / 2.
493  */
494 static int wipe_one_reserved_range(struct cache_tree *tree,
495                                    u64 start, u64 len, u64 min_stripe_size,
496                                    int ensure_size)
497 {
498         struct cache_extent *cache;
499         int ret;
500
501         BUG_ON(ensure_size && min_stripe_size == 0);
502         /*
503          * The logical here is simplified to handle special cases only
504          * So we don't need to consider merge case for ensure_size
505          */
506         BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
507                min_stripe_size / 2 < BTRFS_STRIPE_LEN));
508
509         /* Also, wipe range should already be aligned */
510         BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
511                start + len != round_up(start + len, BTRFS_STRIPE_LEN));
512
513         min_stripe_size /= 2;
514
515         cache = lookup_cache_extent(tree, start, len);
516         if (!cache)
517                 return 0;
518
519         if (start <= cache->start) {
520                 /*
521                  *      |--------cache---------|
522                  * |-wipe-|
523                  */
524                 BUG_ON(start + len <= cache->start);
525
526                 /*
527                  * The wipe size is smaller than min_stripe_size / 2,
528                  * so the result length should still meet min_stripe_size
529                  * And no need to do alignment
530                  */
531                 cache->size -= (start + len - cache->start);
532                 if (cache->size == 0) {
533                         remove_cache_extent(tree, cache);
534                         free(cache);
535                         return 0;
536                 }
537
538                 BUG_ON(ensure_size && cache->size < min_stripe_size);
539
540                 cache->start = start + len;
541                 return 0;
542         } else if (start > cache->start && start + len < cache->start +
543                    cache->size) {
544                 /*
545                  * |-------cache-----|
546                  *      |-wipe-|
547                  */
548                 u64 old_start = cache->start;
549                 u64 old_len = cache->size;
550                 u64 insert_start = start + len;
551                 u64 insert_len;
552
553                 cache->size = start - cache->start;
554                 /* Expand the leading half part if needed */
555                 if (ensure_size && cache->size < min_stripe_size) {
556                         ret = _expand_extent_cache(tree, cache,
557                                         min_stripe_size, 1);
558                         if (ret < 0)
559                                 return ret;
560                 }
561
562                 /* And insert the new one */
563                 insert_len = old_start + old_len - start - len;
564                 ret = add_merge_cache_extent(tree, insert_start, insert_len);
565                 if (ret < 0)
566                         return ret;
567
568                 /* Expand the last half part if needed */
569                 if (ensure_size && insert_len < min_stripe_size) {
570                         cache = lookup_cache_extent(tree, insert_start,
571                                                     insert_len);
572                         if (!cache || cache->start != insert_start ||
573                             cache->size != insert_len)
574                                 return -ENOENT;
575                         ret = _expand_extent_cache(tree, cache,
576                                         min_stripe_size, 0);
577                 }
578
579                 return ret;
580         }
581         /*
582          * |----cache-----|
583          *              |--wipe-|
584          * Wipe len should be small enough and no need to expand the
585          * remaining extent
586          */
587         cache->size = start - cache->start;
588         BUG_ON(ensure_size && cache->size < min_stripe_size);
589         return 0;
590 }
591
592 /*
593  * Remove reserved ranges from given cache_tree
594  *
595  * It will remove the following ranges
596  * 1) 0~1M
597  * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
598  * 3) 3rd superblock, +64K
599  *
600  * @min_stripe must be given for safety check
601  * and if @ensure_size is given, it will ensure affected cache_extent will be
602  * larger than min_stripe_size
603  */
604 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
605                                 int ensure_size)
606 {
607         int i;
608         int ret;
609
610         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
611                 struct simple_range *range = &btrfs_reserved_ranges[i];
612
613                 ret = wipe_one_reserved_range(tree, range->start, range->len,
614                                               min_stripe_size, ensure_size);
615                 if (ret < 0)
616                         return ret;
617         }
618         return ret;
619 }
620
621 static int calculate_available_space(struct btrfs_convert_context *cctx)
622 {
623         struct cache_tree *used = &cctx->used_space;
624         struct cache_tree *data_chunks = &cctx->data_chunks;
625         struct cache_tree *free = &cctx->free_space;
626         struct cache_extent *cache;
627         u64 cur_off = 0;
628         /*
629          * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
630          * works without need to consider overlap
631          */
632         u64 min_stripe_size = 2 * 16 * 1024 * 1024;
633         int ret;
634
635         /* Calculate data_chunks */
636         for (cache = first_cache_extent(used); cache;
637              cache = next_cache_extent(cache)) {
638                 u64 cur_len;
639
640                 if (cache->start + cache->size < cur_off)
641                         continue;
642                 if (cache->start > cur_off + min_stripe_size)
643                         cur_off = cache->start;
644                 cur_len = max(cache->start + cache->size - cur_off,
645                               min_stripe_size);
646                 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
647                 if (ret < 0)
648                         goto out;
649                 cur_off += cur_len;
650         }
651         /*
652          * remove reserved ranges, so we won't ever bother relocating an old
653          * filesystem extent to other place.
654          */
655         ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
656         if (ret < 0)
657                 goto out;
658
659         cur_off = 0;
660         /*
661          * Calculate free space
662          * Always round up the start bytenr, to avoid metadata extent corss
663          * stripe boundary, as later mkfs_convert() won't have all the extent
664          * allocation check
665          */
666         for (cache = first_cache_extent(data_chunks); cache;
667              cache = next_cache_extent(cache)) {
668                 if (cache->start < cur_off)
669                         continue;
670                 if (cache->start > cur_off) {
671                         u64 insert_start;
672                         u64 len;
673
674                         len = cache->start - round_up(cur_off,
675                                                       BTRFS_STRIPE_LEN);
676                         insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
677
678                         ret = add_merge_cache_extent(free, insert_start, len);
679                         if (ret < 0)
680                                 goto out;
681                 }
682                 cur_off = cache->start + cache->size;
683         }
684         /* Don't forget the last range */
685         if (cctx->total_bytes > cur_off) {
686                 u64 len = cctx->total_bytes - cur_off;
687                 u64 insert_start;
688
689                 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
690
691                 ret = add_merge_cache_extent(free, insert_start, len);
692                 if (ret < 0)
693                         goto out;
694         }
695
696         /* Remove reserved bytes */
697         ret = wipe_reserved_ranges(free, min_stripe_size, 0);
698 out:
699         return ret;
700 }
701
702 /*
703  * Read used space, and since we have the used space,
704  * calcuate data_chunks and free for later mkfs
705  */
706 static int convert_read_used_space(struct btrfs_convert_context *cctx)
707 {
708         int ret;
709
710         ret = cctx->convert_ops->read_used_space(cctx);
711         if (ret)
712                 return ret;
713
714         ret = calculate_available_space(cctx);
715         return ret;
716 }
717
718 /*
719  * Create the fs image file of old filesystem.
720  *
721  * This is completely fs independent as we have cctx->used, only
722  * need to create file extents pointing to all the positions.
723  */
724 static int create_image(struct btrfs_root *root,
725                            struct btrfs_mkfs_config *cfg,
726                            struct btrfs_convert_context *cctx, int fd,
727                            u64 size, char *name, u32 convert_flags)
728 {
729         struct btrfs_inode_item buf;
730         struct btrfs_trans_handle *trans;
731         struct btrfs_path path;
732         struct btrfs_key key;
733         struct cache_extent *cache;
734         struct cache_tree used_tmp;
735         u64 cur;
736         u64 ino;
737         u64 flags = BTRFS_INODE_READONLY;
738         int ret;
739
740         if (!(convert_flags & CONVERT_FLAG_DATACSUM))
741                 flags |= BTRFS_INODE_NODATASUM;
742
743         trans = btrfs_start_transaction(root, 1);
744         if (!trans)
745                 return -ENOMEM;
746
747         cache_tree_init(&used_tmp);
748         btrfs_init_path(&path);
749
750         ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
751                                        &ino);
752         if (ret < 0)
753                 goto out;
754         ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
755         if (ret < 0)
756                 goto out;
757         ret = btrfs_change_inode_flags(trans, root, ino, flags);
758         if (ret < 0)
759                 goto out;
760         ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
761                              strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
762         if (ret < 0)
763                 goto out;
764
765         key.objectid = ino;
766         key.type = BTRFS_INODE_ITEM_KEY;
767         key.offset = 0;
768
769         ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
770         if (ret) {
771                 ret = (ret > 0 ? -ENOENT : ret);
772                 goto out;
773         }
774         read_extent_buffer(path.nodes[0], &buf,
775                         btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
776                         sizeof(buf));
777         btrfs_release_path(&path);
778
779         /*
780          * Create a new used space cache, which doesn't contain the reserved
781          * range
782          */
783         for (cache = first_cache_extent(&cctx->used_space); cache;
784              cache = next_cache_extent(cache)) {
785                 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
786                 if (ret < 0)
787                         goto out;
788         }
789         ret = wipe_reserved_ranges(&used_tmp, 0, 0);
790         if (ret < 0)
791                 goto out;
792
793         /*
794          * Start from 1M, as 0~1M is reserved, and create_image_file_range()
795          * can't handle bytenr 0(will consider it as a hole)
796          */
797         cur = 1024 * 1024;
798         while (cur < size) {
799                 u64 len = size - cur;
800
801                 ret = create_image_file_range(trans, root, &used_tmp,
802                                                 &buf, ino, cur, &len,
803                                                 convert_flags);
804                 if (ret < 0)
805                         goto out;
806                 cur += len;
807         }
808         /* Handle the reserved ranges */
809         ret = migrate_reserved_ranges(trans, root, &cctx->used_space, &buf, fd,
810                         ino, cfg->num_bytes, convert_flags);
811
812         key.objectid = ino;
813         key.type = BTRFS_INODE_ITEM_KEY;
814         key.offset = 0;
815         ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
816         if (ret) {
817                 ret = (ret > 0 ? -ENOENT : ret);
818                 goto out;
819         }
820         btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
821         write_extent_buffer(path.nodes[0], &buf,
822                         btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
823                         sizeof(buf));
824 out:
825         free_extent_cache_tree(&used_tmp);
826         btrfs_release_path(&path);
827         btrfs_commit_transaction(trans, root);
828         return ret;
829 }
830
831 static struct btrfs_root* link_subvol(struct btrfs_root *root,
832                 const char *base, u64 root_objectid)
833 {
834         struct btrfs_trans_handle *trans;
835         struct btrfs_fs_info *fs_info = root->fs_info;
836         struct btrfs_root *tree_root = fs_info->tree_root;
837         struct btrfs_root *new_root = NULL;
838         struct btrfs_path path;
839         struct btrfs_inode_item *inode_item;
840         struct extent_buffer *leaf;
841         struct btrfs_key key;
842         u64 dirid = btrfs_root_dirid(&root->root_item);
843         u64 index = 2;
844         char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
845         int len;
846         int i;
847         int ret;
848
849         len = strlen(base);
850         if (len == 0 || len > BTRFS_NAME_LEN)
851                 return NULL;
852
853         btrfs_init_path(&path);
854         key.objectid = dirid;
855         key.type = BTRFS_DIR_INDEX_KEY;
856         key.offset = (u64)-1;
857
858         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
859         if (ret <= 0) {
860                 error("search for DIR_INDEX dirid %llu failed: %d",
861                                 (unsigned long long)dirid, ret);
862                 goto fail;
863         }
864
865         if (path.slots[0] > 0) {
866                 path.slots[0]--;
867                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
868                 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
869                         index = key.offset + 1;
870         }
871         btrfs_release_path(&path);
872
873         trans = btrfs_start_transaction(root, 1);
874         if (!trans) {
875                 error("unable to start transaction");
876                 goto fail;
877         }
878
879         key.objectid = dirid;
880         key.offset = 0;
881         key.type =  BTRFS_INODE_ITEM_KEY;
882
883         ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
884         if (ret) {
885                 error("search for INODE_ITEM %llu failed: %d",
886                                 (unsigned long long)dirid, ret);
887                 goto fail;
888         }
889         leaf = path.nodes[0];
890         inode_item = btrfs_item_ptr(leaf, path.slots[0],
891                                     struct btrfs_inode_item);
892
893         key.objectid = root_objectid;
894         key.offset = (u64)-1;
895         key.type = BTRFS_ROOT_ITEM_KEY;
896
897         memcpy(buf, base, len);
898         for (i = 0; i < 1024; i++) {
899                 ret = btrfs_insert_dir_item(trans, root, buf, len,
900                                             dirid, &key, BTRFS_FT_DIR, index);
901                 if (ret != -EEXIST)
902                         break;
903                 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
904                 if (len < 1 || len > BTRFS_NAME_LEN) {
905                         ret = -EINVAL;
906                         break;
907                 }
908         }
909         if (ret)
910                 goto fail;
911
912         btrfs_set_inode_size(leaf, inode_item, len * 2 +
913                              btrfs_inode_size(leaf, inode_item));
914         btrfs_mark_buffer_dirty(leaf);
915         btrfs_release_path(&path);
916
917         /* add the backref first */
918         ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
919                                  BTRFS_ROOT_BACKREF_KEY,
920                                  root->root_key.objectid,
921                                  dirid, index, buf, len);
922         if (ret) {
923                 error("unable to add root backref for %llu: %d",
924                                 root->root_key.objectid, ret);
925                 goto fail;
926         }
927
928         /* now add the forward ref */
929         ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
930                                  BTRFS_ROOT_REF_KEY, root_objectid,
931                                  dirid, index, buf, len);
932         if (ret) {
933                 error("unable to add root ref for %llu: %d",
934                                 root->root_key.objectid, ret);
935                 goto fail;
936         }
937
938         ret = btrfs_commit_transaction(trans, root);
939         if (ret) {
940                 error("transaction commit failed: %d", ret);
941                 goto fail;
942         }
943
944         new_root = btrfs_read_fs_root(fs_info, &key);
945         if (IS_ERR(new_root)) {
946                 error("unable to fs read root: %lu", PTR_ERR(new_root));
947                 new_root = NULL;
948         }
949 fail:
950         btrfs_init_path(&path);
951         return new_root;
952 }
953
954 static int create_subvol(struct btrfs_trans_handle *trans,
955                          struct btrfs_root *root, u64 root_objectid)
956 {
957         struct extent_buffer *tmp;
958         struct btrfs_root *new_root;
959         struct btrfs_key key;
960         struct btrfs_root_item root_item;
961         int ret;
962
963         ret = btrfs_copy_root(trans, root, root->node, &tmp,
964                               root_objectid);
965         if (ret)
966                 return ret;
967
968         memcpy(&root_item, &root->root_item, sizeof(root_item));
969         btrfs_set_root_bytenr(&root_item, tmp->start);
970         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
971         btrfs_set_root_generation(&root_item, trans->transid);
972         free_extent_buffer(tmp);
973
974         key.objectid = root_objectid;
975         key.type = BTRFS_ROOT_ITEM_KEY;
976         key.offset = trans->transid;
977         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
978                                 &key, &root_item);
979
980         key.offset = (u64)-1;
981         new_root = btrfs_read_fs_root(root->fs_info, &key);
982         if (!new_root || IS_ERR(new_root)) {
983                 error("unable to fs read root: %lu", PTR_ERR(new_root));
984                 return PTR_ERR(new_root);
985         }
986
987         ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
988
989         return ret;
990 }
991
992 /*
993  * New make_btrfs() has handle system and meta chunks quite well.
994  * So only need to add remaining data chunks.
995  */
996 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
997                                           struct btrfs_fs_info *fs_info,
998                                           struct btrfs_mkfs_config *cfg,
999                                           struct btrfs_convert_context *cctx)
1000 {
1001         struct btrfs_root *extent_root = fs_info->extent_root;
1002         struct cache_tree *data_chunks = &cctx->data_chunks;
1003         struct cache_extent *cache;
1004         u64 max_chunk_size;
1005         int ret = 0;
1006
1007         /*
1008          * Don't create data chunk over 10% of the convert device
1009          * And for single chunk, don't create chunk larger than 1G.
1010          */
1011         max_chunk_size = cfg->num_bytes / 10;
1012         max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1013         max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1014
1015         for (cache = first_cache_extent(data_chunks); cache;
1016              cache = next_cache_extent(cache)) {
1017                 u64 cur = cache->start;
1018
1019                 while (cur < cache->start + cache->size) {
1020                         u64 len;
1021                         u64 cur_backup = cur;
1022
1023                         len = min(max_chunk_size,
1024                                   cache->start + cache->size - cur);
1025                         ret = btrfs_alloc_data_chunk(trans, extent_root,
1026                                         &cur_backup, len,
1027                                         BTRFS_BLOCK_GROUP_DATA, 1);
1028                         if (ret < 0)
1029                                 break;
1030                         ret = btrfs_make_block_group(trans, extent_root, 0,
1031                                         BTRFS_BLOCK_GROUP_DATA,
1032                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1033                                         cur, len);
1034                         if (ret < 0)
1035                                 break;
1036                         cur += len;
1037                 }
1038         }
1039         return ret;
1040 }
1041
1042 /*
1043  * Init the temp btrfs to a operational status.
1044  *
1045  * It will fix the extent usage accounting(XXX: Do we really need?) and
1046  * insert needed data chunks, to ensure all old fs data extents are covered
1047  * by DATA chunks, preventing wrong chunks are allocated.
1048  *
1049  * And also create convert image subvolume and relocation tree.
1050  * (XXX: Not need again?)
1051  * But the convert image subvolume is *NOT* linked to fs tree yet.
1052  */
1053 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1054                          struct btrfs_convert_context *cctx, u32 convert_flags)
1055 {
1056         struct btrfs_key location;
1057         struct btrfs_trans_handle *trans;
1058         struct btrfs_fs_info *fs_info = root->fs_info;
1059         int ret;
1060
1061         /*
1062          * Don't alloc any metadata/system chunk, as we don't want
1063          * any meta/sys chunk allcated before all data chunks are inserted.
1064          * Or we screw up the chunk layout just like the old implement.
1065          */
1066         fs_info->avoid_sys_chunk_alloc = 1;
1067         fs_info->avoid_meta_chunk_alloc = 1;
1068         trans = btrfs_start_transaction(root, 1);
1069         if (!trans) {
1070                 error("unable to start transaction");
1071                 ret = -EINVAL;
1072                 goto err;
1073         }
1074         ret = btrfs_fix_block_accounting(trans, root);
1075         if (ret)
1076                 goto err;
1077         ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1078         if (ret)
1079                 goto err;
1080         ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1081                                   BTRFS_ROOT_TREE_DIR_OBJECTID);
1082         if (ret)
1083                 goto err;
1084         memcpy(&location, &root->root_key, sizeof(location));
1085         location.offset = (u64)-1;
1086         ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1087                                 btrfs_super_root_dir(fs_info->super_copy),
1088                                 &location, BTRFS_FT_DIR, 0);
1089         if (ret)
1090                 goto err;
1091         ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1092                                 location.objectid,
1093                                 btrfs_super_root_dir(fs_info->super_copy), 0);
1094         if (ret)
1095                 goto err;
1096         btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1097                              BTRFS_FIRST_FREE_OBJECTID);
1098
1099         /* subvol for fs image file */
1100         ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1101         if (ret < 0) {
1102                 error("failed to create subvolume image root: %d", ret);
1103                 goto err;
1104         }
1105         /* subvol for data relocation tree */
1106         ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1107         if (ret < 0) {
1108                 error("failed to create DATA_RELOC root: %d", ret);
1109                 goto err;
1110         }
1111
1112         ret = btrfs_commit_transaction(trans, root);
1113         fs_info->avoid_sys_chunk_alloc = 0;
1114         fs_info->avoid_meta_chunk_alloc = 0;
1115 err:
1116         return ret;
1117 }
1118
1119 /*
1120  * Migrate super block to its default position and zero 0 ~ 16k
1121  */
1122 static int migrate_super_block(int fd, u64 old_bytenr)
1123 {
1124         int ret;
1125         struct extent_buffer *buf;
1126         struct btrfs_super_block *super;
1127         u32 len;
1128         u32 bytenr;
1129
1130         buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1131         if (!buf)
1132                 return -ENOMEM;
1133
1134         buf->len = BTRFS_SUPER_INFO_SIZE;
1135         ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, old_bytenr);
1136         if (ret != BTRFS_SUPER_INFO_SIZE)
1137                 goto fail;
1138
1139         super = (struct btrfs_super_block *)buf->data;
1140         BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1141         btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1142
1143         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1144         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
1145                 BTRFS_SUPER_INFO_OFFSET);
1146         if (ret != BTRFS_SUPER_INFO_SIZE)
1147                 goto fail;
1148
1149         ret = fsync(fd);
1150         if (ret)
1151                 goto fail;
1152
1153         memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1154         for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1155                 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1156                 if (len > BTRFS_SUPER_INFO_SIZE)
1157                         len = BTRFS_SUPER_INFO_SIZE;
1158                 ret = pwrite(fd, buf->data, len, bytenr);
1159                 if (ret != len) {
1160                         fprintf(stderr, "unable to zero fill device\n");
1161                         break;
1162                 }
1163                 bytenr += len;
1164         }
1165         ret = 0;
1166         fsync(fd);
1167 fail:
1168         free(buf);
1169         if (ret > 0)
1170                 ret = -1;
1171         return ret;
1172 }
1173
1174 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1175 {
1176         struct btrfs_chunk *chunk;
1177         struct btrfs_disk_key *key;
1178         u32 sectorsize = btrfs_super_sectorsize(super);
1179
1180         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1181         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1182                                        sizeof(struct btrfs_disk_key));
1183
1184         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1185         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1186         btrfs_set_disk_key_offset(key, 0);
1187
1188         btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1189         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1190         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1191         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1192         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1193         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1194         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1195         btrfs_set_stack_chunk_num_stripes(chunk, 1);
1196         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1197         chunk->stripe.devid = super->dev_item.devid;
1198         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1199         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1200         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1201         return 0;
1202 }
1203
1204 static int convert_open_fs(const char *devname,
1205                            struct btrfs_convert_context *cctx)
1206 {
1207         int i;
1208
1209         for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
1210                 int ret = convert_operations[i]->open_fs(cctx, devname);
1211
1212                 if (ret == 0) {
1213                         cctx->convert_ops = convert_operations[i];
1214                         return ret;
1215                 }
1216         }
1217
1218         error("no file system found to convert");
1219         return -1;
1220 }
1221
1222 static int do_convert(const char *devname, u32 convert_flags, u32 nodesize,
1223                 const char *fslabel, int progress, u64 features)
1224 {
1225         int ret;
1226         int fd = -1;
1227         u32 blocksize;
1228         u64 total_bytes;
1229         struct btrfs_root *root;
1230         struct btrfs_root *image_root;
1231         struct btrfs_convert_context cctx;
1232         struct btrfs_key key;
1233         char subvol_name[SOURCE_FS_NAME_LEN + 8];
1234         struct task_ctx ctx;
1235         char features_buf[64];
1236         struct btrfs_mkfs_config mkfs_cfg;
1237
1238         init_convert_context(&cctx);
1239         ret = convert_open_fs(devname, &cctx);
1240         if (ret)
1241                 goto fail;
1242         ret = convert_check_state(&cctx);
1243         if (ret)
1244                 warning(
1245                 "source filesystem is not clean, running filesystem check is recommended");
1246         ret = convert_read_used_space(&cctx);
1247         if (ret)
1248                 goto fail;
1249
1250         blocksize = cctx.blocksize;
1251         total_bytes = (u64)blocksize * (u64)cctx.block_count;
1252         if (blocksize < 4096) {
1253                 error("block size is too small: %u < 4096", blocksize);
1254                 goto fail;
1255         }
1256         if (btrfs_check_nodesize(nodesize, blocksize, features))
1257                 goto fail;
1258         fd = open(devname, O_RDWR);
1259         if (fd < 0) {
1260                 error("unable to open %s: %s", devname, strerror(errno));
1261                 goto fail;
1262         }
1263         btrfs_parse_features_to_string(features_buf, features);
1264         if (features == BTRFS_MKFS_DEFAULT_FEATURES)
1265                 strcat(features_buf, " (default)");
1266
1267         printf("create btrfs filesystem:\n");
1268         printf("\tblocksize: %u\n", blocksize);
1269         printf("\tnodesize:  %u\n", nodesize);
1270         printf("\tfeatures:  %s\n", features_buf);
1271
1272         memset(&mkfs_cfg, 0, sizeof(mkfs_cfg));
1273         mkfs_cfg.label = cctx.volume_name;
1274         mkfs_cfg.num_bytes = total_bytes;
1275         mkfs_cfg.nodesize = nodesize;
1276         mkfs_cfg.sectorsize = blocksize;
1277         mkfs_cfg.stripesize = blocksize;
1278         mkfs_cfg.features = features;
1279
1280         ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
1281         if (ret) {
1282                 error("unable to create initial ctree: %s", strerror(-ret));
1283                 goto fail;
1284         }
1285
1286         root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
1287                              OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1288         if (!root) {
1289                 error("unable to open ctree");
1290                 goto fail;
1291         }
1292         ret = init_btrfs(&mkfs_cfg, root, &cctx, convert_flags);
1293         if (ret) {
1294                 error("unable to setup the root tree: %d", ret);
1295                 goto fail;
1296         }
1297
1298         printf("creating %s image file\n", cctx.convert_ops->name);
1299         snprintf(subvol_name, sizeof(subvol_name), "%s_saved",
1300                         cctx.convert_ops->name);
1301         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1302         key.offset = (u64)-1;
1303         key.type = BTRFS_ROOT_ITEM_KEY;
1304         image_root = btrfs_read_fs_root(root->fs_info, &key);
1305         if (!image_root) {
1306                 error("unable to create image subvolume");
1307                 goto fail;
1308         }
1309         ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
1310                               mkfs_cfg.num_bytes, "image",
1311                               convert_flags);
1312         if (ret) {
1313                 error("failed to create %s/image: %d", subvol_name, ret);
1314                 goto fail;
1315         }
1316
1317         printf("creating btrfs metadata");
1318         ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
1319         ctx.cur_copy_inodes = 0;
1320
1321         if (progress) {
1322                 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
1323                                      &ctx);
1324                 task_start(ctx.info);
1325         }
1326         ret = copy_inodes(&cctx, root, convert_flags, &ctx);
1327         if (ret) {
1328                 error("error during copy_inodes %d", ret);
1329                 goto fail;
1330         }
1331         if (progress) {
1332                 task_stop(ctx.info);
1333                 task_deinit(ctx.info);
1334         }
1335
1336         image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
1337         if (!image_root) {
1338                 error("unable to link subvolume %s", subvol_name);
1339                 goto fail;
1340         }
1341
1342         memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
1343         if (convert_flags & CONVERT_FLAG_COPY_LABEL) {
1344                 __strncpy_null(root->fs_info->super_copy->label,
1345                                 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
1346                 printf("copy label '%s'\n", root->fs_info->super_copy->label);
1347         } else if (convert_flags & CONVERT_FLAG_SET_LABEL) {
1348                 strcpy(root->fs_info->super_copy->label, fslabel);
1349                 printf("set label to '%s'\n", fslabel);
1350         }
1351
1352         ret = close_ctree(root);
1353         if (ret) {
1354                 error("close_ctree failed: %d", ret);
1355                 goto fail;
1356         }
1357         convert_close_fs(&cctx);
1358         clean_convert_context(&cctx);
1359
1360         /*
1361          * If this step succeed, we get a mountable btrfs. Otherwise
1362          * the source fs is left unchanged.
1363          */
1364         ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
1365         if (ret) {
1366                 error("unable to migrate super block: %d", ret);
1367                 goto fail;
1368         }
1369
1370         root = open_ctree_fd(fd, devname, 0,
1371                         OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1372         if (!root) {
1373                 error("unable to open ctree for finalization");
1374                 goto fail;
1375         }
1376         root->fs_info->finalize_on_close = 1;
1377         close_ctree(root);
1378         close(fd);
1379
1380         printf("conversion complete");
1381         return 0;
1382 fail:
1383         clean_convert_context(&cctx);
1384         if (fd != -1)
1385                 close(fd);
1386         warning(
1387 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
1388         return -1;
1389 }
1390
1391 /*
1392  * Check if a non 1:1 mapped chunk can be rolled back.
1393  * For new convert, it's OK while for old convert it's not.
1394  */
1395 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
1396 {
1397         struct btrfs_block_group_cache *bg;
1398         struct btrfs_key key;
1399         struct btrfs_path path;
1400         struct btrfs_root *extent_root = fs_info->extent_root;
1401         u64 bg_start;
1402         u64 bg_end;
1403         int ret;
1404
1405         bg = btrfs_lookup_first_block_group(fs_info, bytenr);
1406         if (!bg)
1407                 return -ENOENT;
1408         bg_start = bg->key.objectid;
1409         bg_end = bg->key.objectid + bg->key.offset;
1410
1411         key.objectid = bg_end;
1412         key.type = BTRFS_METADATA_ITEM_KEY;
1413         key.offset = 0;
1414         btrfs_init_path(&path);
1415
1416         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
1417         if (ret < 0)
1418                 return ret;
1419
1420         while (1) {
1421                 struct btrfs_extent_item *ei;
1422
1423                 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
1424                 if (ret > 0) {
1425                         ret = 0;
1426                         break;
1427                 }
1428                 if (ret < 0)
1429                         break;
1430
1431                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1432                 if (key.type == BTRFS_METADATA_ITEM_KEY)
1433                         continue;
1434                 /* Now it's EXTENT_ITEM_KEY only */
1435                 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
1436                                     struct btrfs_extent_item);
1437                 /*
1438                  * Found data extent, means this is old convert must follow 1:1
1439                  * mapping.
1440                  */
1441                 if (btrfs_extent_flags(path.nodes[0], ei)
1442                                 & BTRFS_EXTENT_FLAG_DATA) {
1443                         ret = -EINVAL;
1444                         break;
1445                 }
1446         }
1447         btrfs_release_path(&path);
1448         return ret;
1449 }
1450
1451 static int may_rollback(struct btrfs_root *root)
1452 {
1453         struct btrfs_fs_info *info = root->fs_info;
1454         struct btrfs_multi_bio *multi = NULL;
1455         u64 bytenr;
1456         u64 length;
1457         u64 physical;
1458         u64 total_bytes;
1459         int num_stripes;
1460         int ret;
1461
1462         if (btrfs_super_num_devices(info->super_copy) != 1)
1463                 goto fail;
1464
1465         bytenr = BTRFS_SUPER_INFO_OFFSET;
1466         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1467
1468         while (1) {
1469                 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
1470                                       &length, &multi, 0, NULL);
1471                 if (ret) {
1472                         if (ret == -ENOENT) {
1473                                 /* removed block group at the tail */
1474                                 if (length == (u64)-1)
1475                                         break;
1476
1477                                 /* removed block group in the middle */
1478                                 goto next;
1479                         }
1480                         goto fail;
1481                 }
1482
1483                 num_stripes = multi->num_stripes;
1484                 physical = multi->stripes[0].physical;
1485                 free(multi);
1486
1487                 if (num_stripes != 1) {
1488                         error("num stripes for bytenr %llu is not 1", bytenr);
1489                         goto fail;
1490                 }
1491
1492                 /*
1493                  * Extra check for new convert, as metadata chunk from new
1494                  * convert is much more free than old convert, it doesn't need
1495                  * to do 1:1 mapping.
1496                  */
1497                 if (physical != bytenr) {
1498                         /*
1499                          * Check if it's a metadata chunk and has only metadata
1500                          * extent.
1501                          */
1502                         ret = may_rollback_chunk(info, bytenr);
1503                         if (ret < 0)
1504                                 goto fail;
1505                 }
1506 next:
1507                 bytenr += length;
1508                 if (bytenr >= total_bytes)
1509                         break;
1510         }
1511         return 0;
1512 fail:
1513         return -1;
1514 }
1515
1516 /*
1517  * Read out data of convert image which is in btrfs reserved ranges so we can
1518  * use them to overwrite the ranges during rollback.
1519  */
1520 static int read_reserved_ranges(struct btrfs_root *root, u64 ino,
1521                                 u64 total_bytes, char *reserved_ranges[])
1522 {
1523         int i;
1524         int ret = 0;
1525
1526         for (i = 0; i < ARRAY_SIZE(btrfs_reserved_ranges); i++) {
1527                 struct simple_range *range = &btrfs_reserved_ranges[i];
1528
1529                 if (range->start + range->len >= total_bytes)
1530                         break;
1531                 ret = btrfs_read_file(root, ino, range->start, range->len,
1532                                       reserved_ranges[i]);
1533                 if (ret < range->len) {
1534                         error(
1535         "failed to read data of convert image, offset=%llu len=%llu ret=%d",
1536                               range->start, range->len, ret);
1537                         if (ret >= 0)
1538                                 ret = -EIO;
1539                         break;
1540                 }
1541                 ret = 0;
1542         }
1543         return ret;
1544 }
1545
1546 static int do_rollback(const char *devname)
1547 {
1548         int fd = -1;
1549         int ret;
1550         int i;
1551         struct btrfs_root *root;
1552         struct btrfs_root *image_root;
1553         struct btrfs_root *chunk_root;
1554         struct btrfs_dir_item *dir;
1555         struct btrfs_inode_item *inode;
1556         struct btrfs_file_extent_item *fi;
1557         struct btrfs_trans_handle *trans;
1558         struct extent_buffer *leaf;
1559         struct btrfs_block_group_cache *cache1;
1560         struct btrfs_block_group_cache *cache2;
1561         struct btrfs_key key;
1562         struct btrfs_path path;
1563         struct extent_io_tree io_tree;
1564         char *buf = NULL;
1565         char *name;
1566         u64 bytenr;
1567         u64 num_bytes;
1568         u64 root_dir;
1569         u64 objectid;
1570         u64 offset;
1571         u64 start;
1572         u64 end;
1573         u64 sb_bytenr;
1574         u64 first_free;
1575         u64 total_bytes;
1576         u32 sectorsize;
1577
1578         extent_io_tree_init(&io_tree);
1579
1580         fd = open(devname, O_RDWR);
1581         if (fd < 0) {
1582                 error("unable to open %s: %s", devname, strerror(errno));
1583                 goto fail;
1584         }
1585         root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
1586         if (!root) {
1587                 error("unable to open ctree");
1588                 goto fail;
1589         }
1590         ret = may_rollback(root);
1591         if (ret < 0) {
1592                 error("unable to do rollback: %d", ret);
1593                 goto fail;
1594         }
1595
1596         sectorsize = root->sectorsize;
1597         buf = malloc(sectorsize);
1598         if (!buf) {
1599                 error("unable to allocate memory");
1600                 goto fail;
1601         }
1602
1603         btrfs_init_path(&path);
1604
1605         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1606         key.type = BTRFS_ROOT_BACKREF_KEY;
1607         key.offset = BTRFS_FS_TREE_OBJECTID;
1608         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
1609                                 0);
1610         btrfs_release_path(&path);
1611         if (ret > 0) {
1612                 error("unable to convert ext2 image subvolume, is it deleted?");
1613                 goto fail;
1614         } else if (ret < 0) {
1615                 error("unable to open ext2_saved, id %llu: %s",
1616                         (unsigned long long)key.objectid, strerror(-ret));
1617                 goto fail;
1618         }
1619
1620         key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1621         key.type = BTRFS_ROOT_ITEM_KEY;
1622         key.offset = (u64)-1;
1623         image_root = btrfs_read_fs_root(root->fs_info, &key);
1624         if (!image_root || IS_ERR(image_root)) {
1625                 error("unable to open subvolume %llu: %ld",
1626                         (unsigned long long)key.objectid, PTR_ERR(image_root));
1627                 goto fail;
1628         }
1629
1630         name = "image";
1631         root_dir = btrfs_root_dirid(&root->root_item);
1632         dir = btrfs_lookup_dir_item(NULL, image_root, &path,
1633                                    root_dir, name, strlen(name), 0);
1634         if (!dir || IS_ERR(dir)) {
1635                 error("unable to find file %s: %ld", name, PTR_ERR(dir));
1636                 goto fail;
1637         }
1638         leaf = path.nodes[0];
1639         btrfs_dir_item_key_to_cpu(leaf, dir, &key);
1640         btrfs_release_path(&path);
1641
1642         objectid = key.objectid;
1643
1644         ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
1645         if (ret) {
1646                 error("unable to find inode item: %d", ret);
1647                 goto fail;
1648         }
1649         leaf = path.nodes[0];
1650         inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
1651         total_bytes = btrfs_inode_size(leaf, inode);
1652         btrfs_release_path(&path);
1653
1654         key.objectid = objectid;
1655         key.offset = 0;
1656         key.type = BTRFS_EXTENT_DATA_KEY;
1657         ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
1658         if (ret != 0) {
1659                 error("unable to find first file extent: %d", ret);
1660                 btrfs_release_path(&path);
1661                 goto fail;
1662         }
1663
1664         /* build mapping tree for the relocated blocks */
1665         for (offset = 0; offset < total_bytes; ) {
1666                 leaf = path.nodes[0];
1667                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1668                         ret = btrfs_next_leaf(root, &path);
1669                         if (ret != 0)
1670                                 break;  
1671                         continue;
1672                 }
1673
1674                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1675                 if (key.objectid != objectid || key.offset != offset ||
1676                     key.type != BTRFS_EXTENT_DATA_KEY)
1677                         break;
1678
1679                 fi = btrfs_item_ptr(leaf, path.slots[0],
1680                                     struct btrfs_file_extent_item);
1681                 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
1682                         break;
1683                 if (btrfs_file_extent_compression(leaf, fi) ||
1684                     btrfs_file_extent_encryption(leaf, fi) ||
1685                     btrfs_file_extent_other_encoding(leaf, fi))
1686                         break;
1687
1688                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1689                 /* skip holes and direct mapped extents */
1690                 if (bytenr == 0 || bytenr == offset)
1691                         goto next_extent;
1692
1693                 bytenr += btrfs_file_extent_offset(leaf, fi);
1694                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
1695
1696                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
1697                 cache2 = btrfs_lookup_block_group(root->fs_info,
1698                                                   offset + num_bytes - 1);
1699                 /*
1700                  * Here we must take consideration of old and new convert
1701                  * behavior.
1702                  * For old convert case, sign, there is no consist chunk type
1703                  * that will cover the extent. META/DATA/SYS are all possible.
1704                  * Just ensure relocate one is in SYS chunk.
1705                  * For new convert case, they are all covered by DATA chunk.
1706                  *
1707                  * So, there is not valid chunk type check for it now.
1708                  */
1709                 if (cache1 != cache2)
1710                         break;
1711
1712                 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
1713                                 EXTENT_LOCKED);
1714                 set_state_private(&io_tree, offset, bytenr);
1715 next_extent:
1716                 offset += btrfs_file_extent_num_bytes(leaf, fi);
1717                 path.slots[0]++;
1718         }
1719         btrfs_release_path(&path);
1720
1721         if (offset < total_bytes) {
1722                 error("unable to build extent mapping (offset %llu, total_bytes %llu)",
1723                                 (unsigned long long)offset,
1724                                 (unsigned long long)total_bytes);
1725                 error("converted filesystem after balance is unable to rollback");
1726                 goto fail;
1727         }
1728
1729         first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
1730         first_free &= ~((u64)sectorsize - 1);
1731         /* backup for extent #0 should exist */
1732         if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
1733                 error("no backup for the first extent");
1734                 goto fail;
1735         }
1736         /* force no allocation from system block group */
1737         root->fs_info->system_allocs = -1;
1738         trans = btrfs_start_transaction(root, 1);
1739         if (!trans) {
1740                 error("unable to start transaction");
1741                 goto fail;
1742         }
1743         /*
1744          * recow the whole chunk tree, this will remove all chunk tree blocks
1745          * from system block group
1746          */
1747         chunk_root = root->fs_info->chunk_root;
1748         memset(&key, 0, sizeof(key));
1749         while (1) {
1750                 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
1751                 if (ret < 0)
1752                         break;
1753
1754                 ret = btrfs_next_leaf(chunk_root, &path);
1755                 if (ret)
1756                         break;
1757
1758                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1759                 btrfs_release_path(&path);
1760         }
1761         btrfs_release_path(&path);
1762
1763         offset = 0;
1764         num_bytes = 0;
1765         while(1) {
1766                 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
1767                 if (!cache1)
1768                         break;
1769
1770                 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
1771                         num_bytes += btrfs_block_group_used(&cache1->item);
1772
1773                 offset = cache1->key.objectid + cache1->key.offset;
1774         }
1775         /* only extent #0 left in system block group? */
1776         if (num_bytes > first_free) {
1777                 error(
1778         "unable to empty system block group (num_bytes %llu, first_free %llu",
1779                                 (unsigned long long)num_bytes,
1780                                 (unsigned long long)first_free);
1781                 goto fail;
1782         }
1783         /* create a system chunk that maps the whole device */
1784         ret = prepare_system_chunk_sb(root->fs_info->super_copy);
1785         if (ret) {
1786                 error("unable to update system chunk: %d", ret);
1787                 goto fail;
1788         }
1789
1790         ret = btrfs_commit_transaction(trans, root);
1791         if (ret) {
1792                 error("transaction commit failed: %d", ret);
1793                 goto fail;
1794         }
1795
1796         ret = close_ctree(root);
1797         if (ret) {
1798                 error("close_ctree failed: %d", ret);
1799                 goto fail;
1800         }
1801
1802         /* zero btrfs super block mirrors */
1803         memset(buf, 0, sectorsize);
1804         for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1805                 bytenr = btrfs_sb_offset(i);
1806                 if (bytenr >= total_bytes)
1807                         break;
1808                 ret = pwrite(fd, buf, sectorsize, bytenr);
1809                 if (ret != sectorsize) {
1810                         error("zeroing superblock mirror %d failed: %d",
1811                                         i, ret);
1812                         goto fail;
1813                 }
1814         }
1815
1816         sb_bytenr = (u64)-1;
1817         /* copy all relocated blocks back */
1818         while(1) {
1819                 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
1820                                             EXTENT_LOCKED);
1821                 if (ret)
1822                         break;
1823
1824                 ret = get_state_private(&io_tree, start, &bytenr);
1825                 BUG_ON(ret);
1826
1827                 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED);
1828
1829                 while (start <= end) {
1830                         if (start == BTRFS_SUPER_INFO_OFFSET) {
1831                                 sb_bytenr = bytenr;
1832                                 goto next_sector;
1833                         }
1834                         ret = pread(fd, buf, sectorsize, bytenr);
1835                         if (ret < 0) {
1836                                 error("reading superblock at %llu failed: %d",
1837                                                 (unsigned long long)bytenr, ret);
1838                                 goto fail;
1839                         }
1840                         BUG_ON(ret != sectorsize);
1841                         ret = pwrite(fd, buf, sectorsize, start);
1842                         if (ret < 0) {
1843                                 error("writing superblock at %llu failed: %d",
1844                                                 (unsigned long long)start, ret);
1845                                 goto fail;
1846                         }
1847                         BUG_ON(ret != sectorsize);
1848 next_sector:
1849                         start += sectorsize;
1850                         bytenr += sectorsize;
1851                 }
1852         }
1853
1854         ret = fsync(fd);
1855         if (ret < 0) {
1856                 error("fsync failed: %s", strerror(errno));
1857                 goto fail;
1858         }
1859         /*
1860          * finally, overwrite btrfs super block.
1861          */
1862         ret = pread(fd, buf, sectorsize, sb_bytenr);
1863         if (ret < 0) {
1864                 error("reading primary superblock failed: %s",
1865                                 strerror(errno));
1866                 goto fail;
1867         }
1868         BUG_ON(ret != sectorsize);
1869         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1870         if (ret < 0) {
1871                 error("writing primary superblock failed: %s",
1872                                 strerror(errno));
1873                 goto fail;
1874         }
1875         BUG_ON(ret != sectorsize);
1876         ret = fsync(fd);
1877         if (ret < 0) {
1878                 error("fsync failed: %s", strerror(errno));
1879                 goto fail;
1880         }
1881
1882         close(fd);
1883         free(buf);
1884         extent_io_tree_cleanup(&io_tree);
1885         printf("rollback complete\n");
1886         return 0;
1887
1888 fail:
1889         if (fd != -1)
1890                 close(fd);
1891         free(buf);
1892         error("rollback aborted");
1893         return -1;
1894 }
1895
1896 static void print_usage(void)
1897 {
1898         printf("usage: btrfs-convert [options] device\n");
1899         printf("options:\n");
1900         printf("\t-d|--no-datasum        disable data checksum, sets NODATASUM\n");
1901         printf("\t-i|--no-xattr          ignore xattrs and ACLs\n");
1902         printf("\t-n|--no-inline         disable inlining of small files to metadata\n");
1903         printf("\t-N|--nodesize SIZE     set filesystem metadata nodesize\n");
1904         printf("\t-r|--rollback          roll back to the original filesystem\n");
1905         printf("\t-l|--label LABEL       set filesystem label\n");
1906         printf("\t-L|--copy-label        use label from converted filesystem\n");
1907         printf("\t-p|--progress          show converting progress (default)\n");
1908         printf("\t-O|--features LIST     comma separated list of filesystem features\n");
1909         printf("\t--no-progress          show only overview, not the detailed progress\n");
1910         printf("\n");
1911         printf("Supported filesystems:\n");
1912         printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
1913 }
1914
1915 int main(int argc, char *argv[])
1916 {
1917         int ret;
1918         int packing = 1;
1919         int noxattr = 0;
1920         int datacsum = 1;
1921         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
1922                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
1923         int rollback = 0;
1924         int copylabel = 0;
1925         int usage_error = 0;
1926         int progress = 1;
1927         char *file;
1928         char fslabel[BTRFS_LABEL_SIZE];
1929         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
1930
1931         while(1) {
1932                 enum { GETOPT_VAL_NO_PROGRESS = 256 };
1933                 static const struct option long_options[] = {
1934                         { "no-progress", no_argument, NULL,
1935                                 GETOPT_VAL_NO_PROGRESS },
1936                         { "no-datasum", no_argument, NULL, 'd' },
1937                         { "no-inline", no_argument, NULL, 'n' },
1938                         { "no-xattr", no_argument, NULL, 'i' },
1939                         { "rollback", no_argument, NULL, 'r' },
1940                         { "features", required_argument, NULL, 'O' },
1941                         { "progress", no_argument, NULL, 'p' },
1942                         { "label", required_argument, NULL, 'l' },
1943                         { "copy-label", no_argument, NULL, 'L' },
1944                         { "nodesize", required_argument, NULL, 'N' },
1945                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
1946                         { NULL, 0, NULL, 0 }
1947                 };
1948                 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
1949
1950                 if (c < 0)
1951                         break;
1952                 switch(c) {
1953                         case 'd':
1954                                 datacsum = 0;
1955                                 break;
1956                         case 'i':
1957                                 noxattr = 1;
1958                                 break;
1959                         case 'n':
1960                                 packing = 0;
1961                                 break;
1962                         case 'N':
1963                                 nodesize = parse_size(optarg);
1964                                 break;
1965                         case 'r':
1966                                 rollback = 1;
1967                                 break;
1968                         case 'l':
1969                                 copylabel = CONVERT_FLAG_SET_LABEL;
1970                                 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
1971                                         warning(
1972                                         "label too long, trimmed to %d bytes",
1973                                                 BTRFS_LABEL_SIZE - 1);
1974                                 }
1975                                 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
1976                                 break;
1977                         case 'L':
1978                                 copylabel = CONVERT_FLAG_COPY_LABEL;
1979                                 break;
1980                         case 'p':
1981                                 progress = 1;
1982                                 break;
1983                         case 'O': {
1984                                 char *orig = strdup(optarg);
1985                                 char *tmp = orig;
1986
1987                                 tmp = btrfs_parse_fs_features(tmp, &features);
1988                                 if (tmp) {
1989                                         error("unrecognized filesystem feature: %s",
1990                                                         tmp);
1991                                         free(orig);
1992                                         exit(1);
1993                                 }
1994                                 free(orig);
1995                                 if (features & BTRFS_FEATURE_LIST_ALL) {
1996                                         btrfs_list_all_fs_features(
1997                                                 ~BTRFS_CONVERT_ALLOWED_FEATURES);
1998                                         exit(0);
1999                                 }
2000                                 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
2001                                         char buf[64];
2002
2003                                         btrfs_parse_features_to_string(buf,
2004                                                 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
2005                                         error("features not allowed for convert: %s",
2006                                                 buf);
2007                                         exit(1);
2008                                 }
2009
2010                                 break;
2011                                 }
2012                         case GETOPT_VAL_NO_PROGRESS:
2013                                 progress = 0;
2014                                 break;
2015                         case GETOPT_VAL_HELP:
2016                         default:
2017                                 print_usage();
2018                                 return c != GETOPT_VAL_HELP;
2019                 }
2020         }
2021         set_argv0(argv);
2022         if (check_argc_exact(argc - optind, 1)) {
2023                 print_usage();
2024                 return 1;
2025         }
2026
2027         if (rollback && (!datacsum || noxattr || !packing)) {
2028                 fprintf(stderr,
2029                         "Usage error: -d, -i, -n options do not apply to rollback\n");
2030                 usage_error++;
2031         }
2032
2033         if (usage_error) {
2034                 print_usage();
2035                 return 1;
2036         }
2037
2038         file = argv[optind];
2039         ret = check_mounted(file);
2040         if (ret < 0) {
2041                 error("could not check mount status: %s", strerror(-ret));
2042                 return 1;
2043         } else if (ret) {
2044                 error("%s is mounted", file);
2045                 return 1;
2046         }
2047
2048         if (rollback) {
2049                 ret = do_rollback(file);
2050         } else {
2051                 u32 cf = 0;
2052
2053                 cf |= datacsum ? CONVERT_FLAG_DATACSUM : 0;
2054                 cf |= packing ? CONVERT_FLAG_INLINE_DATA : 0;
2055                 cf |= noxattr ? 0 : CONVERT_FLAG_XATTR;
2056                 cf |= copylabel;
2057                 ret = do_convert(file, cf, nodesize, fslabel, progress, features);
2058         }
2059         if (ret)
2060                 return 1;
2061         return 0;
2062 }