btrfs-progs: ioctl: make build-time structure size checks optional
[platform/upstream/btrfs-progs.git] / btrfs-image.c
1 /*
2  * Copyright (C) 2008 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <pthread.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #include <dirent.h>
27 #include <zlib.h>
28 #include <getopt.h>
29
30 #include "kerncompat.h"
31 #include "crc32c.h"
32 #include "ctree.h"
33 #include "disk-io.h"
34 #include "transaction.h"
35 #include "utils.h"
36 #include "volumes.h"
37 #include "extent_io.h"
38
39 #define HEADER_MAGIC            0xbd5c25e27295668bULL
40 #define MAX_PENDING_SIZE        (256 * 1024)
41 #define BLOCK_SIZE              1024
42 #define BLOCK_MASK              (BLOCK_SIZE - 1)
43
44 #define COMPRESS_NONE           0
45 #define COMPRESS_ZLIB           1
46
47 struct meta_cluster_item {
48         __le64 bytenr;
49         __le32 size;
50 } __attribute__ ((__packed__));
51
52 struct meta_cluster_header {
53         __le64 magic;
54         __le64 bytenr;
55         __le32 nritems;
56         u8 compress;
57 } __attribute__ ((__packed__));
58
59 /* cluster header + index items + buffers */
60 struct meta_cluster {
61         struct meta_cluster_header header;
62         struct meta_cluster_item items[];
63 } __attribute__ ((__packed__));
64
65 #define ITEMS_PER_CLUSTER ((BLOCK_SIZE - sizeof(struct meta_cluster)) / \
66                            sizeof(struct meta_cluster_item))
67
68 struct fs_chunk {
69         u64 logical;
70         u64 physical;
71         /*
72          * physical_dup only store additonal physical for BTRFS_BLOCK_GROUP_DUP
73          * currently restore only support single and DUP
74          * TODO: modify this structure and the function related to this
75          * structure for support RAID*
76          */
77         u64 physical_dup;
78         u64 bytes;
79         struct rb_node l;
80         struct rb_node p;
81         struct list_head list;
82 };
83
84 struct async_work {
85         struct list_head list;
86         struct list_head ordered;
87         u64 start;
88         u64 size;
89         u8 *buffer;
90         size_t bufsize;
91         int error;
92 };
93
94 struct metadump_struct {
95         struct btrfs_root *root;
96         FILE *out;
97
98         struct meta_cluster *cluster;
99
100         pthread_t *threads;
101         size_t num_threads;
102         pthread_mutex_t mutex;
103         pthread_cond_t cond;
104         struct rb_root name_tree;
105
106         struct list_head list;
107         struct list_head ordered;
108         size_t num_items;
109         size_t num_ready;
110
111         u64 pending_start;
112         u64 pending_size;
113
114         int compress_level;
115         int done;
116         int data;
117         int sanitize_names;
118
119         int error;
120 };
121
122 struct name {
123         struct rb_node n;
124         char *val;
125         char *sub;
126         u32 len;
127 };
128
129 struct mdrestore_struct {
130         FILE *in;
131         FILE *out;
132
133         pthread_t *threads;
134         size_t num_threads;
135         pthread_mutex_t mutex;
136         pthread_cond_t cond;
137
138         struct rb_root chunk_tree;
139         struct rb_root physical_tree;
140         struct list_head list;
141         struct list_head overlapping_chunks;
142         size_t num_items;
143         u32 nodesize;
144         u64 devid;
145         u64 alloced_chunks;
146         u64 last_physical_offset;
147         u8 uuid[BTRFS_UUID_SIZE];
148         u8 fsid[BTRFS_FSID_SIZE];
149
150         int compress_method;
151         int done;
152         int error;
153         int old_restore;
154         int fixup_offset;
155         int multi_devices;
156         int clear_space_cache;
157         struct btrfs_fs_info *info;
158 };
159
160 static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
161                                    u64 search, u64 cluster_bytenr);
162 static struct extent_buffer *alloc_dummy_eb(u64 bytenr, u32 size);
163
164 static void csum_block(u8 *buf, size_t len)
165 {
166         u8 result[BTRFS_CRC32_SIZE];
167         u32 crc = ~(u32)0;
168         crc = crc32c(crc, buf + BTRFS_CSUM_SIZE, len - BTRFS_CSUM_SIZE);
169         btrfs_csum_final(crc, result);
170         memcpy(buf, result, BTRFS_CRC32_SIZE);
171 }
172
173 static int has_name(struct btrfs_key *key)
174 {
175         switch (key->type) {
176         case BTRFS_DIR_ITEM_KEY:
177         case BTRFS_DIR_INDEX_KEY:
178         case BTRFS_INODE_REF_KEY:
179         case BTRFS_INODE_EXTREF_KEY:
180         case BTRFS_XATTR_ITEM_KEY:
181                 return 1;
182         default:
183                 break;
184         }
185
186         return 0;
187 }
188
189 static char *generate_garbage(u32 name_len)
190 {
191         char *buf = malloc(name_len);
192         int i;
193
194         if (!buf)
195                 return NULL;
196
197         for (i = 0; i < name_len; i++) {
198                 char c = rand_range(94) + 33;
199
200                 if (c == '/')
201                         c++;
202                 buf[i] = c;
203         }
204
205         return buf;
206 }
207
208 static int name_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
209 {
210         struct name *entry = rb_entry(a, struct name, n);
211         struct name *ins = rb_entry(b, struct name, n);
212         u32 len;
213
214         len = min(ins->len, entry->len);
215         return memcmp(ins->val, entry->val, len);
216 }
217
218 static int chunk_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
219 {
220         struct fs_chunk *entry = rb_entry(a, struct fs_chunk, l);
221         struct fs_chunk *ins = rb_entry(b, struct fs_chunk, l);
222
223         if (fuzz && ins->logical >= entry->logical &&
224             ins->logical < entry->logical + entry->bytes)
225                 return 0;
226
227         if (ins->logical < entry->logical)
228                 return -1;
229         else if (ins->logical > entry->logical)
230                 return 1;
231         return 0;
232 }
233
234 static int physical_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
235 {
236         struct fs_chunk *entry = rb_entry(a, struct fs_chunk, p);
237         struct fs_chunk *ins = rb_entry(b, struct fs_chunk, p);
238
239         if (fuzz && ins->physical >= entry->physical &&
240             ins->physical < entry->physical + entry->bytes)
241                 return 0;
242
243         if (fuzz && entry->physical >= ins->physical &&
244             entry->physical < ins->physical + ins->bytes)
245                 return 0;
246
247         if (ins->physical < entry->physical)
248                 return -1;
249         else if (ins->physical > entry->physical)
250                 return 1;
251         return 0;
252 }
253
254 static void tree_insert(struct rb_root *root, struct rb_node *ins,
255                         int (*cmp)(struct rb_node *a, struct rb_node *b,
256                                    int fuzz))
257 {
258         struct rb_node ** p = &root->rb_node;
259         struct rb_node * parent = NULL;
260         int dir;
261
262         while(*p) {
263                 parent = *p;
264
265                 dir = cmp(*p, ins, 1);
266                 if (dir < 0)
267                         p = &(*p)->rb_left;
268                 else if (dir > 0)
269                         p = &(*p)->rb_right;
270                 else
271                         BUG();
272         }
273
274         rb_link_node(ins, parent, p);
275         rb_insert_color(ins, root);
276 }
277
278 static struct rb_node *tree_search(struct rb_root *root,
279                                    struct rb_node *search,
280                                    int (*cmp)(struct rb_node *a,
281                                               struct rb_node *b, int fuzz),
282                                    int fuzz)
283 {
284         struct rb_node *n = root->rb_node;
285         int dir;
286
287         while (n) {
288                 dir = cmp(n, search, fuzz);
289                 if (dir < 0)
290                         n = n->rb_left;
291                 else if (dir > 0)
292                         n = n->rb_right;
293                 else
294                         return n;
295         }
296
297         return NULL;
298 }
299
300 static u64 logical_to_physical(struct mdrestore_struct *mdres, u64 logical,
301                                u64 *size, u64 *physical_dup)
302 {
303         struct fs_chunk *fs_chunk;
304         struct rb_node *entry;
305         struct fs_chunk search;
306         u64 offset;
307
308         if (logical == BTRFS_SUPER_INFO_OFFSET)
309                 return logical;
310
311         search.logical = logical;
312         entry = tree_search(&mdres->chunk_tree, &search.l, chunk_cmp, 1);
313         if (!entry) {
314                 if (mdres->in != stdin)
315                         warning("cannot find a chunk, using logical");
316                 return logical;
317         }
318         fs_chunk = rb_entry(entry, struct fs_chunk, l);
319         if (fs_chunk->logical > logical || fs_chunk->logical + fs_chunk->bytes < logical)
320                 BUG();
321         offset = search.logical - fs_chunk->logical;
322
323         if (physical_dup) {
324                 /* Only in dup case, physical_dup is not equal to 0 */
325                 if (fs_chunk->physical_dup)
326                         *physical_dup = fs_chunk->physical_dup + offset;
327                 else
328                         *physical_dup = 0;
329         }
330
331         *size = min(*size, fs_chunk->bytes + fs_chunk->logical - logical);
332         return fs_chunk->physical + offset;
333 }
334
335
336 static char *find_collision(struct metadump_struct *md, char *name,
337                             u32 name_len)
338 {
339         struct name *val;
340         struct rb_node *entry;
341         struct name tmp;
342         unsigned long checksum;
343         int found = 0;
344         int i;
345
346         tmp.val = name;
347         tmp.len = name_len;
348         entry = tree_search(&md->name_tree, &tmp.n, name_cmp, 0);
349         if (entry) {
350                 val = rb_entry(entry, struct name, n);
351                 free(name);
352                 return val->sub;
353         }
354
355         val = malloc(sizeof(struct name));
356         if (!val) {
357                 error("cannot sanitize name, not enough memory");
358                 free(name);
359                 return NULL;
360         }
361
362         memset(val, 0, sizeof(*val));
363
364         val->val = name;
365         val->len = name_len;
366         val->sub = malloc(name_len);
367         if (!val->sub) {
368                 error("cannot sanitize name, not enough memory");
369                 free(val);
370                 free(name);
371                 return NULL;
372         }
373
374         checksum = crc32c(~1, val->val, name_len);
375         memset(val->sub, ' ', name_len);
376         i = 0;
377         while (1) {
378                 if (crc32c(~1, val->sub, name_len) == checksum &&
379                     memcmp(val->sub, val->val, val->len)) {
380                         found = 1;
381                         break;
382                 }
383
384                 if (val->sub[i] == 127) {
385                         do {
386                                 i++;
387                                 if (i >= name_len)
388                                         break;
389                         } while (val->sub[i] == 127);
390
391                         if (i >= name_len)
392                                 break;
393                         val->sub[i]++;
394                         if (val->sub[i] == '/')
395                                 val->sub[i]++;
396                         memset(val->sub, ' ', i);
397                         i = 0;
398                         continue;
399                 } else {
400                         val->sub[i]++;
401                         if (val->sub[i] == '/')
402                                 val->sub[i]++;
403                 }
404         }
405
406         if (!found) {
407                 warning(
408 "cannot find a hash collision for '%.*s', generating garbage, it won't match indexes",
409                         val->len, val->val);
410                 for (i = 0; i < name_len; i++) {
411                         char c = rand_range(94) + 33;
412
413                         if (c == '/')
414                                 c++;
415                         val->sub[i] = c;
416                 }
417         }
418
419         tree_insert(&md->name_tree, &val->n, name_cmp);
420         return val->sub;
421 }
422
423 static void sanitize_dir_item(struct metadump_struct *md, struct extent_buffer *eb,
424                               int slot)
425 {
426         struct btrfs_dir_item *dir_item;
427         char *buf;
428         char *garbage;
429         unsigned long name_ptr;
430         u32 total_len;
431         u32 cur = 0;
432         u32 this_len;
433         u32 name_len;
434         int free_garbage = (md->sanitize_names == 1);
435
436         dir_item = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
437         total_len = btrfs_item_size_nr(eb, slot);
438         while (cur < total_len) {
439                 this_len = sizeof(*dir_item) +
440                         btrfs_dir_name_len(eb, dir_item) +
441                         btrfs_dir_data_len(eb, dir_item);
442                 name_ptr = (unsigned long)(dir_item + 1);
443                 name_len = btrfs_dir_name_len(eb, dir_item);
444
445                 if (md->sanitize_names > 1) {
446                         buf = malloc(name_len);
447                         if (!buf) {
448                                 error("cannot sanitize name, not enough memory");
449                                 return;
450                         }
451                         read_extent_buffer(eb, buf, name_ptr, name_len);
452                         garbage = find_collision(md, buf, name_len);
453                 } else {
454                         garbage = generate_garbage(name_len);
455                 }
456                 if (!garbage) {
457                         error("cannot sanitize name, not enough memory");
458                         return;
459                 }
460                 write_extent_buffer(eb, garbage, name_ptr, name_len);
461                 cur += this_len;
462                 dir_item = (struct btrfs_dir_item *)((char *)dir_item +
463                                                      this_len);
464                 if (free_garbage)
465                         free(garbage);
466         }
467 }
468
469 static void sanitize_inode_ref(struct metadump_struct *md,
470                                struct extent_buffer *eb, int slot, int ext)
471 {
472         struct btrfs_inode_extref *extref;
473         struct btrfs_inode_ref *ref;
474         char *garbage, *buf;
475         unsigned long ptr;
476         unsigned long name_ptr;
477         u32 item_size;
478         u32 cur_offset = 0;
479         int len;
480         int free_garbage = (md->sanitize_names == 1);
481
482         item_size = btrfs_item_size_nr(eb, slot);
483         ptr = btrfs_item_ptr_offset(eb, slot);
484         while (cur_offset < item_size) {
485                 if (ext) {
486                         extref = (struct btrfs_inode_extref *)(ptr +
487                                                                cur_offset);
488                         name_ptr = (unsigned long)(&extref->name);
489                         len = btrfs_inode_extref_name_len(eb, extref);
490                         cur_offset += sizeof(*extref);
491                 } else {
492                         ref = (struct btrfs_inode_ref *)(ptr + cur_offset);
493                         len = btrfs_inode_ref_name_len(eb, ref);
494                         name_ptr = (unsigned long)(ref + 1);
495                         cur_offset += sizeof(*ref);
496                 }
497                 cur_offset += len;
498
499                 if (md->sanitize_names > 1) {
500                         buf = malloc(len);
501                         if (!buf) {
502                                 error("cannot sanitize name, not enough memory");
503                                 return;
504                         }
505                         read_extent_buffer(eb, buf, name_ptr, len);
506                         garbage = find_collision(md, buf, len);
507                 } else {
508                         garbage = generate_garbage(len);
509                 }
510
511                 if (!garbage) {
512                         error("cannot sanitize name, not enough memory");
513                         return;
514                 }
515                 write_extent_buffer(eb, garbage, name_ptr, len);
516                 if (free_garbage)
517                         free(garbage);
518         }
519 }
520
521 static void sanitize_xattr(struct metadump_struct *md,
522                            struct extent_buffer *eb, int slot)
523 {
524         struct btrfs_dir_item *dir_item;
525         unsigned long data_ptr;
526         u32 data_len;
527
528         dir_item = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
529         data_len = btrfs_dir_data_len(eb, dir_item);
530
531         data_ptr = (unsigned long)((char *)(dir_item + 1) +
532                                    btrfs_dir_name_len(eb, dir_item));
533         memset_extent_buffer(eb, 0, data_ptr, data_len);
534 }
535
536 static void sanitize_name(struct metadump_struct *md, u8 *dst,
537                           struct extent_buffer *src, struct btrfs_key *key,
538                           int slot)
539 {
540         struct extent_buffer *eb;
541
542         eb = alloc_dummy_eb(src->start, src->len);
543         if (!eb) {
544                 error("cannot sanitize name, not enough memory");
545                 return;
546         }
547
548         memcpy(eb->data, dst, eb->len);
549
550         switch (key->type) {
551         case BTRFS_DIR_ITEM_KEY:
552         case BTRFS_DIR_INDEX_KEY:
553                 sanitize_dir_item(md, eb, slot);
554                 break;
555         case BTRFS_INODE_REF_KEY:
556                 sanitize_inode_ref(md, eb, slot, 0);
557                 break;
558         case BTRFS_INODE_EXTREF_KEY:
559                 sanitize_inode_ref(md, eb, slot, 1);
560                 break;
561         case BTRFS_XATTR_ITEM_KEY:
562                 sanitize_xattr(md, eb, slot);
563                 break;
564         default:
565                 break;
566         }
567
568         memcpy(dst, eb->data, eb->len);
569         free(eb);
570 }
571
572 /*
573  * zero inline extents and csum items
574  */
575 static void zero_items(struct metadump_struct *md, u8 *dst,
576                        struct extent_buffer *src)
577 {
578         struct btrfs_file_extent_item *fi;
579         struct btrfs_item *item;
580         struct btrfs_key key;
581         u32 nritems = btrfs_header_nritems(src);
582         size_t size;
583         unsigned long ptr;
584         int i, extent_type;
585
586         for (i = 0; i < nritems; i++) {
587                 item = btrfs_item_nr(i);
588                 btrfs_item_key_to_cpu(src, &key, i);
589                 if (key.type == BTRFS_CSUM_ITEM_KEY) {
590                         size = btrfs_item_size_nr(src, i);
591                         memset(dst + btrfs_leaf_data(src) +
592                                btrfs_item_offset_nr(src, i), 0, size);
593                         continue;
594                 }
595
596                 if (md->sanitize_names && has_name(&key)) {
597                         sanitize_name(md, dst, src, &key, i);
598                         continue;
599                 }
600
601                 if (key.type != BTRFS_EXTENT_DATA_KEY)
602                         continue;
603
604                 fi = btrfs_item_ptr(src, i, struct btrfs_file_extent_item);
605                 extent_type = btrfs_file_extent_type(src, fi);
606                 if (extent_type != BTRFS_FILE_EXTENT_INLINE)
607                         continue;
608
609                 ptr = btrfs_file_extent_inline_start(fi);
610                 size = btrfs_file_extent_inline_item_len(src, item);
611                 memset(dst + ptr, 0, size);
612         }
613 }
614
615 /*
616  * copy buffer and zero useless data in the buffer
617  */
618 static void copy_buffer(struct metadump_struct *md, u8 *dst,
619                         struct extent_buffer *src)
620 {
621         int level;
622         size_t size;
623         u32 nritems;
624
625         memcpy(dst, src->data, src->len);
626         if (src->start == BTRFS_SUPER_INFO_OFFSET)
627                 return;
628
629         level = btrfs_header_level(src);
630         nritems = btrfs_header_nritems(src);
631
632         if (nritems == 0) {
633                 size = sizeof(struct btrfs_header);
634                 memset(dst + size, 0, src->len - size);
635         } else if (level == 0) {
636                 size = btrfs_leaf_data(src) +
637                         btrfs_item_offset_nr(src, nritems - 1) -
638                         btrfs_item_nr_offset(nritems);
639                 memset(dst + btrfs_item_nr_offset(nritems), 0, size);
640                 zero_items(md, dst, src);
641         } else {
642                 size = offsetof(struct btrfs_node, ptrs) +
643                         sizeof(struct btrfs_key_ptr) * nritems;
644                 memset(dst + size, 0, src->len - size);
645         }
646         csum_block(dst, src->len);
647 }
648
649 static void *dump_worker(void *data)
650 {
651         struct metadump_struct *md = (struct metadump_struct *)data;
652         struct async_work *async;
653         int ret;
654
655         while (1) {
656                 pthread_mutex_lock(&md->mutex);
657                 while (list_empty(&md->list)) {
658                         if (md->done) {
659                                 pthread_mutex_unlock(&md->mutex);
660                                 goto out;
661                         }
662                         pthread_cond_wait(&md->cond, &md->mutex);
663                 }
664                 async = list_entry(md->list.next, struct async_work, list);
665                 list_del_init(&async->list);
666                 pthread_mutex_unlock(&md->mutex);
667
668                 if (md->compress_level > 0) {
669                         u8 *orig = async->buffer;
670
671                         async->bufsize = compressBound(async->size);
672                         async->buffer = malloc(async->bufsize);
673                         if (!async->buffer) {
674                                 error("not enough memory for async buffer");
675                                 pthread_mutex_lock(&md->mutex);
676                                 if (!md->error)
677                                         md->error = -ENOMEM;
678                                 pthread_mutex_unlock(&md->mutex);
679                                 pthread_exit(NULL);
680                         }
681
682                         ret = compress2(async->buffer,
683                                          (unsigned long *)&async->bufsize,
684                                          orig, async->size, md->compress_level);
685
686                         if (ret != Z_OK)
687                                 async->error = 1;
688
689                         free(orig);
690                 }
691
692                 pthread_mutex_lock(&md->mutex);
693                 md->num_ready++;
694                 pthread_mutex_unlock(&md->mutex);
695         }
696 out:
697         pthread_exit(NULL);
698 }
699
700 static void meta_cluster_init(struct metadump_struct *md, u64 start)
701 {
702         struct meta_cluster_header *header;
703
704         md->num_items = 0;
705         md->num_ready = 0;
706         header = &md->cluster->header;
707         header->magic = cpu_to_le64(HEADER_MAGIC);
708         header->bytenr = cpu_to_le64(start);
709         header->nritems = cpu_to_le32(0);
710         header->compress = md->compress_level > 0 ?
711                            COMPRESS_ZLIB : COMPRESS_NONE;
712 }
713
714 static void metadump_destroy(struct metadump_struct *md, int num_threads)
715 {
716         int i;
717         struct rb_node *n;
718
719         pthread_mutex_lock(&md->mutex);
720         md->done = 1;
721         pthread_cond_broadcast(&md->cond);
722         pthread_mutex_unlock(&md->mutex);
723
724         for (i = 0; i < num_threads; i++)
725                 pthread_join(md->threads[i], NULL);
726
727         pthread_cond_destroy(&md->cond);
728         pthread_mutex_destroy(&md->mutex);
729
730         while ((n = rb_first(&md->name_tree))) {
731                 struct name *name;
732
733                 name = rb_entry(n, struct name, n);
734                 rb_erase(n, &md->name_tree);
735                 free(name->val);
736                 free(name->sub);
737                 free(name);
738         }
739         free(md->threads);
740         free(md->cluster);
741 }
742
743 static int metadump_init(struct metadump_struct *md, struct btrfs_root *root,
744                          FILE *out, int num_threads, int compress_level,
745                          int sanitize_names)
746 {
747         int i, ret = 0;
748
749         memset(md, 0, sizeof(*md));
750         md->cluster = calloc(1, BLOCK_SIZE);
751         if (!md->cluster)
752                 return -ENOMEM;
753         md->threads = calloc(num_threads, sizeof(pthread_t));
754         if (!md->threads) {
755                 free(md->cluster);
756                 return -ENOMEM;
757         }
758         INIT_LIST_HEAD(&md->list);
759         INIT_LIST_HEAD(&md->ordered);
760         md->root = root;
761         md->out = out;
762         md->pending_start = (u64)-1;
763         md->compress_level = compress_level;
764         md->sanitize_names = sanitize_names;
765         if (sanitize_names > 1)
766                 crc32c_optimization_init();
767
768         md->name_tree.rb_node = NULL;
769         md->num_threads = num_threads;
770         pthread_cond_init(&md->cond, NULL);
771         pthread_mutex_init(&md->mutex, NULL);
772         meta_cluster_init(md, 0);
773
774         if (!num_threads)
775                 return 0;
776
777         for (i = 0; i < num_threads; i++) {
778                 ret = pthread_create(md->threads + i, NULL, dump_worker, md);
779                 if (ret)
780                         break;
781         }
782
783         if (ret)
784                 metadump_destroy(md, i + 1);
785
786         return ret;
787 }
788
789 static int write_zero(FILE *out, size_t size)
790 {
791         static char zero[BLOCK_SIZE];
792         return fwrite(zero, size, 1, out);
793 }
794
795 static int write_buffers(struct metadump_struct *md, u64 *next)
796 {
797         struct meta_cluster_header *header = &md->cluster->header;
798         struct meta_cluster_item *item;
799         struct async_work *async;
800         u64 bytenr = 0;
801         u32 nritems = 0;
802         int ret;
803         int err = 0;
804
805         if (list_empty(&md->ordered))
806                 goto out;
807
808         /* wait until all buffers are compressed */
809         while (!err && md->num_items > md->num_ready) {
810                 struct timespec ts = {
811                         .tv_sec = 0,
812                         .tv_nsec = 10000000,
813                 };
814                 pthread_mutex_unlock(&md->mutex);
815                 nanosleep(&ts, NULL);
816                 pthread_mutex_lock(&md->mutex);
817                 err = md->error;
818         }
819
820         if (err) {
821                 error("one of the threads failed: %s", strerror(-err));
822                 goto out;
823         }
824
825         /* setup and write index block */
826         list_for_each_entry(async, &md->ordered, ordered) {
827                 item = md->cluster->items + nritems;
828                 item->bytenr = cpu_to_le64(async->start);
829                 item->size = cpu_to_le32(async->bufsize);
830                 nritems++;
831         }
832         header->nritems = cpu_to_le32(nritems);
833
834         ret = fwrite(md->cluster, BLOCK_SIZE, 1, md->out);
835         if (ret != 1) {
836                 error("unable to write out cluster: %s", strerror(errno));
837                 return -errno;
838         }
839
840         /* write buffers */
841         bytenr += le64_to_cpu(header->bytenr) + BLOCK_SIZE;
842         while (!list_empty(&md->ordered)) {
843                 async = list_entry(md->ordered.next, struct async_work,
844                                    ordered);
845                 list_del_init(&async->ordered);
846
847                 bytenr += async->bufsize;
848                 if (!err)
849                         ret = fwrite(async->buffer, async->bufsize, 1,
850                                      md->out);
851                 if (ret != 1) {
852                         error("unable to write out cluster: %s",
853                                 strerror(errno));
854                         err = -errno;
855                         ret = 0;
856                 }
857
858                 free(async->buffer);
859                 free(async);
860         }
861
862         /* zero unused space in the last block */
863         if (!err && bytenr & BLOCK_MASK) {
864                 size_t size = BLOCK_SIZE - (bytenr & BLOCK_MASK);
865
866                 bytenr += size;
867                 ret = write_zero(md->out, size);
868                 if (ret != 1) {
869                         error("unable to zero out buffer: %s",
870                                 strerror(errno));
871                         err = -errno;
872                 }
873         }
874 out:
875         *next = bytenr;
876         return err;
877 }
878
879 static int read_data_extent(struct metadump_struct *md,
880                             struct async_work *async)
881 {
882         struct btrfs_root *root = md->root;
883         u64 bytes_left = async->size;
884         u64 logical = async->start;
885         u64 offset = 0;
886         u64 read_len;
887         int num_copies;
888         int cur_mirror;
889         int ret;
890
891         num_copies = btrfs_num_copies(&root->fs_info->mapping_tree, logical,
892                                       bytes_left);
893
894         /* Try our best to read data, just like read_tree_block() */
895         for (cur_mirror = 0; cur_mirror < num_copies; cur_mirror++) {
896                 while (bytes_left) {
897                         read_len = bytes_left;
898                         ret = read_extent_data(root,
899                                         (char *)(async->buffer + offset),
900                                         logical, &read_len, cur_mirror);
901                         if (ret < 0)
902                                 break;
903                         offset += read_len;
904                         logical += read_len;
905                         bytes_left -= read_len;
906                 }
907         }
908         if (bytes_left)
909                 return -EIO;
910         return 0;
911 }
912
913 static int get_dev_fd(struct btrfs_root *root)
914 {
915         struct btrfs_device *dev;
916
917         dev = list_first_entry(&root->fs_info->fs_devices->devices,
918                                struct btrfs_device, dev_list);
919         return dev->fd;
920 }
921
922 static int flush_pending(struct metadump_struct *md, int done)
923 {
924         struct async_work *async = NULL;
925         struct extent_buffer *eb;
926         u64 blocksize = md->root->nodesize;
927         u64 start;
928         u64 size;
929         size_t offset;
930         int ret = 0;
931
932         if (md->pending_size) {
933                 async = calloc(1, sizeof(*async));
934                 if (!async)
935                         return -ENOMEM;
936
937                 async->start = md->pending_start;
938                 async->size = md->pending_size;
939                 async->bufsize = async->size;
940                 async->buffer = malloc(async->bufsize);
941                 if (!async->buffer) {
942                         free(async);
943                         return -ENOMEM;
944                 }
945                 offset = 0;
946                 start = async->start;
947                 size = async->size;
948
949                 if (md->data) {
950                         ret = read_data_extent(md, async);
951                         if (ret) {
952                                 free(async->buffer);
953                                 free(async);
954                                 return ret;
955                         }
956                 }
957
958                 /*
959                  * Balance can make the mapping not cover the super block, so
960                  * just copy directly from one of the devices.
961                  */
962                 if (start == BTRFS_SUPER_INFO_OFFSET) {
963                         int fd = get_dev_fd(md->root);
964
965                         ret = pread64(fd, async->buffer, size, start);
966                         if (ret < size) {
967                                 free(async->buffer);
968                                 free(async);
969                                 error("unable to read superblock at %llu: %s",
970                                                 (unsigned long long)start,
971                                                 strerror(errno));
972                                 return -errno;
973                         }
974                         size = 0;
975                         ret = 0;
976                 }
977
978                 while (!md->data && size > 0) {
979                         u64 this_read = min(blocksize, size);
980                         eb = read_tree_block(md->root, start, this_read, 0);
981                         if (!extent_buffer_uptodate(eb)) {
982                                 free(async->buffer);
983                                 free(async);
984                                 error("unable to read metadata block %llu",
985                                         (unsigned long long)start);
986                                 return -EIO;
987                         }
988                         copy_buffer(md, async->buffer + offset, eb);
989                         free_extent_buffer(eb);
990                         start += this_read;
991                         offset += this_read;
992                         size -= this_read;
993                 }
994
995                 md->pending_start = (u64)-1;
996                 md->pending_size = 0;
997         } else if (!done) {
998                 return 0;
999         }
1000
1001         pthread_mutex_lock(&md->mutex);
1002         if (async) {
1003                 list_add_tail(&async->ordered, &md->ordered);
1004                 md->num_items++;
1005                 if (md->compress_level > 0) {
1006                         list_add_tail(&async->list, &md->list);
1007                         pthread_cond_signal(&md->cond);
1008                 } else {
1009                         md->num_ready++;
1010                 }
1011         }
1012         if (md->num_items >= ITEMS_PER_CLUSTER || done) {
1013                 ret = write_buffers(md, &start);
1014                 if (ret)
1015                         error("unable to write buffers: %s", strerror(-ret));
1016                 else
1017                         meta_cluster_init(md, start);
1018         }
1019         pthread_mutex_unlock(&md->mutex);
1020         return ret;
1021 }
1022
1023 static int add_extent(u64 start, u64 size, struct metadump_struct *md,
1024                       int data)
1025 {
1026         int ret;
1027         if (md->data != data ||
1028             md->pending_size + size > MAX_PENDING_SIZE ||
1029             md->pending_start + md->pending_size != start) {
1030                 ret = flush_pending(md, 0);
1031                 if (ret)
1032                         return ret;
1033                 md->pending_start = start;
1034         }
1035         readahead_tree_block(md->root, start, size, 0);
1036         md->pending_size += size;
1037         md->data = data;
1038         return 0;
1039 }
1040
1041 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1042 static int is_tree_block(struct btrfs_root *extent_root,
1043                          struct btrfs_path *path, u64 bytenr)
1044 {
1045         struct extent_buffer *leaf;
1046         struct btrfs_key key;
1047         u64 ref_objectid;
1048         int ret;
1049
1050         leaf = path->nodes[0];
1051         while (1) {
1052                 struct btrfs_extent_ref_v0 *ref_item;
1053                 path->slots[0]++;
1054                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1055                         ret = btrfs_next_leaf(extent_root, path);
1056                         if (ret < 0)
1057                                 return ret;
1058                         if (ret > 0)
1059                                 break;
1060                         leaf = path->nodes[0];
1061                 }
1062                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1063                 if (key.objectid != bytenr)
1064                         break;
1065                 if (key.type != BTRFS_EXTENT_REF_V0_KEY)
1066                         continue;
1067                 ref_item = btrfs_item_ptr(leaf, path->slots[0],
1068                                           struct btrfs_extent_ref_v0);
1069                 ref_objectid = btrfs_ref_objectid_v0(leaf, ref_item);
1070                 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID)
1071                         return 1;
1072                 break;
1073         }
1074         return 0;
1075 }
1076 #endif
1077
1078 static int copy_tree_blocks(struct btrfs_root *root, struct extent_buffer *eb,
1079                             struct metadump_struct *metadump, int root_tree)
1080 {
1081         struct extent_buffer *tmp;
1082         struct btrfs_root_item *ri;
1083         struct btrfs_key key;
1084         u64 bytenr;
1085         int level;
1086         int nritems = 0;
1087         int i = 0;
1088         int ret;
1089
1090         ret = add_extent(btrfs_header_bytenr(eb), root->nodesize, metadump, 0);
1091         if (ret) {
1092                 error("unable to add metadata block %llu: %d",
1093                                 btrfs_header_bytenr(eb), ret);
1094                 return ret;
1095         }
1096
1097         if (btrfs_header_level(eb) == 0 && !root_tree)
1098                 return 0;
1099
1100         level = btrfs_header_level(eb);
1101         nritems = btrfs_header_nritems(eb);
1102         for (i = 0; i < nritems; i++) {
1103                 if (level == 0) {
1104                         btrfs_item_key_to_cpu(eb, &key, i);
1105                         if (key.type != BTRFS_ROOT_ITEM_KEY)
1106                                 continue;
1107                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
1108                         bytenr = btrfs_disk_root_bytenr(eb, ri);
1109                         tmp = read_tree_block(root, bytenr, root->nodesize, 0);
1110                         if (!extent_buffer_uptodate(tmp)) {
1111                                 error("unable to read log root block");
1112                                 return -EIO;
1113                         }
1114                         ret = copy_tree_blocks(root, tmp, metadump, 0);
1115                         free_extent_buffer(tmp);
1116                         if (ret)
1117                                 return ret;
1118                 } else {
1119                         bytenr = btrfs_node_blockptr(eb, i);
1120                         tmp = read_tree_block(root, bytenr, root->nodesize, 0);
1121                         if (!extent_buffer_uptodate(tmp)) {
1122                                 error("unable to read log root block");
1123                                 return -EIO;
1124                         }
1125                         ret = copy_tree_blocks(root, tmp, metadump, root_tree);
1126                         free_extent_buffer(tmp);
1127                         if (ret)
1128                                 return ret;
1129                 }
1130         }
1131
1132         return 0;
1133 }
1134
1135 static int copy_log_trees(struct btrfs_root *root,
1136                           struct metadump_struct *metadump,
1137                           struct btrfs_path *path)
1138 {
1139         u64 blocknr = btrfs_super_log_root(root->fs_info->super_copy);
1140
1141         if (blocknr == 0)
1142                 return 0;
1143
1144         if (!root->fs_info->log_root_tree ||
1145             !root->fs_info->log_root_tree->node) {
1146                 error("unable to copy tree log, it has not been setup");
1147                 return -EIO;
1148         }
1149
1150         return copy_tree_blocks(root, root->fs_info->log_root_tree->node,
1151                                 metadump, 1);
1152 }
1153
1154 static int copy_space_cache(struct btrfs_root *root,
1155                             struct metadump_struct *metadump,
1156                             struct btrfs_path *path)
1157 {
1158         struct extent_buffer *leaf;
1159         struct btrfs_file_extent_item *fi;
1160         struct btrfs_key key;
1161         u64 bytenr, num_bytes;
1162         int ret;
1163
1164         root = root->fs_info->tree_root;
1165
1166         key.objectid = 0;
1167         key.type = BTRFS_EXTENT_DATA_KEY;
1168         key.offset = 0;
1169
1170         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1171         if (ret < 0) {
1172                 error("free space inode not found: %d", ret);
1173                 return ret;
1174         }
1175
1176         leaf = path->nodes[0];
1177
1178         while (1) {
1179                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1180                         ret = btrfs_next_leaf(root, path);
1181                         if (ret < 0) {
1182                                 error("cannot go to next leaf %d", ret);
1183                                 return ret;
1184                         }
1185                         if (ret > 0)
1186                                 break;
1187                         leaf = path->nodes[0];
1188                 }
1189
1190                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1191                 if (key.type != BTRFS_EXTENT_DATA_KEY) {
1192                         path->slots[0]++;
1193                         continue;
1194                 }
1195
1196                 fi = btrfs_item_ptr(leaf, path->slots[0],
1197                                     struct btrfs_file_extent_item);
1198                 if (btrfs_file_extent_type(leaf, fi) !=
1199                     BTRFS_FILE_EXTENT_REG) {
1200                         path->slots[0]++;
1201                         continue;
1202                 }
1203
1204                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1205                 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1206                 ret = add_extent(bytenr, num_bytes, metadump, 1);
1207                 if (ret) {
1208                         error("unable to add space cache blocks %d", ret);
1209                         btrfs_release_path(path);
1210                         return ret;
1211                 }
1212                 path->slots[0]++;
1213         }
1214
1215         return 0;
1216 }
1217
1218 static int copy_from_extent_tree(struct metadump_struct *metadump,
1219                                  struct btrfs_path *path)
1220 {
1221         struct btrfs_root *extent_root;
1222         struct extent_buffer *leaf;
1223         struct btrfs_extent_item *ei;
1224         struct btrfs_key key;
1225         u64 bytenr;
1226         u64 num_bytes;
1227         int ret;
1228
1229         extent_root = metadump->root->fs_info->extent_root;
1230         bytenr = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
1231         key.objectid = bytenr;
1232         key.type = BTRFS_EXTENT_ITEM_KEY;
1233         key.offset = 0;
1234
1235         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
1236         if (ret < 0) {
1237                 error("extent root not found: %d", ret);
1238                 return ret;
1239         }
1240         ret = 0;
1241
1242         leaf = path->nodes[0];
1243
1244         while (1) {
1245                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1246                         ret = btrfs_next_leaf(extent_root, path);
1247                         if (ret < 0) {
1248                                 error("cannot go to next leaf %d", ret);
1249                                 break;
1250                         }
1251                         if (ret > 0) {
1252                                 ret = 0;
1253                                 break;
1254                         }
1255                         leaf = path->nodes[0];
1256                 }
1257
1258                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1259                 if (key.objectid < bytenr ||
1260                     (key.type != BTRFS_EXTENT_ITEM_KEY &&
1261                      key.type != BTRFS_METADATA_ITEM_KEY)) {
1262                         path->slots[0]++;
1263                         continue;
1264                 }
1265
1266                 bytenr = key.objectid;
1267                 if (key.type == BTRFS_METADATA_ITEM_KEY) {
1268                         num_bytes = extent_root->nodesize;
1269                 } else {
1270                         num_bytes = key.offset;
1271                 }
1272
1273                 if (num_bytes == 0) {
1274                         error("extent length 0 at bytenr %llu key type %d",
1275                                         (unsigned long long)bytenr, key.type);
1276                         ret = -EIO;
1277                         break;
1278                 }
1279
1280                 if (btrfs_item_size_nr(leaf, path->slots[0]) > sizeof(*ei)) {
1281                         ei = btrfs_item_ptr(leaf, path->slots[0],
1282                                             struct btrfs_extent_item);
1283                         if (btrfs_extent_flags(leaf, ei) &
1284                             BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1285                                 ret = add_extent(bytenr, num_bytes, metadump,
1286                                                  0);
1287                                 if (ret) {
1288                                         error("unable to add block %llu: %d",
1289                                                 (unsigned long long)bytenr, ret);
1290                                         break;
1291                                 }
1292                         }
1293                 } else {
1294 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1295                         ret = is_tree_block(extent_root, path, bytenr);
1296                         if (ret < 0) {
1297                                 error("failed to check tree block %llu: %d",
1298                                         (unsigned long long)bytenr, ret);
1299                                 break;
1300                         }
1301
1302                         if (ret) {
1303                                 ret = add_extent(bytenr, num_bytes, metadump,
1304                                                  0);
1305                                 if (ret) {
1306                                         error("unable to add block %llu: %d",
1307                                                 (unsigned long long)bytenr, ret);
1308                                         break;
1309                                 }
1310                         }
1311                         ret = 0;
1312 #else
1313                         error(
1314         "either extent tree is corrupted or you haven't built with V0 support");
1315                         ret = -EIO;
1316                         break;
1317 #endif
1318                 }
1319                 bytenr += num_bytes;
1320         }
1321
1322         btrfs_release_path(path);
1323
1324         return ret;
1325 }
1326
1327 static int create_metadump(const char *input, FILE *out, int num_threads,
1328                            int compress_level, int sanitize, int walk_trees)
1329 {
1330         struct btrfs_root *root;
1331         struct btrfs_path *path = NULL;
1332         struct metadump_struct metadump;
1333         int ret;
1334         int err = 0;
1335
1336         root = open_ctree(input, 0, 0);
1337         if (!root) {
1338                 error("open ctree failed");
1339                 return -EIO;
1340         }
1341
1342         ret = metadump_init(&metadump, root, out, num_threads,
1343                             compress_level, sanitize);
1344         if (ret) {
1345                 error("failed to initialize metadump: %d", ret);
1346                 close_ctree(root);
1347                 return ret;
1348         }
1349
1350         ret = add_extent(BTRFS_SUPER_INFO_OFFSET, BTRFS_SUPER_INFO_SIZE,
1351                         &metadump, 0);
1352         if (ret) {
1353                 error("unable to add metadata: %d", ret);
1354                 err = ret;
1355                 goto out;
1356         }
1357
1358         path = btrfs_alloc_path();
1359         if (!path) {
1360                 error("not enough memory to allocate path");
1361                 err = -ENOMEM;
1362                 goto out;
1363         }
1364
1365         if (walk_trees) {
1366                 ret = copy_tree_blocks(root, root->fs_info->chunk_root->node,
1367                                        &metadump, 1);
1368                 if (ret) {
1369                         err = ret;
1370                         goto out;
1371                 }
1372
1373                 ret = copy_tree_blocks(root, root->fs_info->tree_root->node,
1374                                        &metadump, 1);
1375                 if (ret) {
1376                         err = ret;
1377                         goto out;
1378                 }
1379         } else {
1380                 ret = copy_from_extent_tree(&metadump, path);
1381                 if (ret) {
1382                         err = ret;
1383                         goto out;
1384                 }
1385         }
1386
1387         ret = copy_log_trees(root, &metadump, path);
1388         if (ret) {
1389                 err = ret;
1390                 goto out;
1391         }
1392
1393         ret = copy_space_cache(root, &metadump, path);
1394 out:
1395         ret = flush_pending(&metadump, 1);
1396         if (ret) {
1397                 if (!err)
1398                         err = ret;
1399                 error("failed to flush pending data: %d", ret);
1400         }
1401
1402         metadump_destroy(&metadump, num_threads);
1403
1404         btrfs_free_path(path);
1405         ret = close_ctree(root);
1406         return err ? err : ret;
1407 }
1408
1409 static void update_super_old(u8 *buffer)
1410 {
1411         struct btrfs_super_block *super = (struct btrfs_super_block *)buffer;
1412         struct btrfs_chunk *chunk;
1413         struct btrfs_disk_key *key;
1414         u32 sectorsize = btrfs_super_sectorsize(super);
1415         u64 flags = btrfs_super_flags(super);
1416
1417         flags |= BTRFS_SUPER_FLAG_METADUMP;
1418         btrfs_set_super_flags(super, flags);
1419
1420         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1421         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1422                                        sizeof(struct btrfs_disk_key));
1423
1424         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1425         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1426         btrfs_set_disk_key_offset(key, 0);
1427
1428         btrfs_set_stack_chunk_length(chunk, (u64)-1);
1429         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1430         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1431         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1432         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1433         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1434         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1435         btrfs_set_stack_chunk_num_stripes(chunk, 1);
1436         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1437         chunk->stripe.devid = super->dev_item.devid;
1438         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1439         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1440         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1441         csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
1442 }
1443
1444 static int update_super(struct mdrestore_struct *mdres, u8 *buffer)
1445 {
1446         struct btrfs_super_block *super = (struct btrfs_super_block *)buffer;
1447         struct btrfs_chunk *chunk;
1448         struct btrfs_disk_key *disk_key;
1449         struct btrfs_key key;
1450         u64 flags = btrfs_super_flags(super);
1451         u32 new_array_size = 0;
1452         u32 array_size;
1453         u32 cur = 0;
1454         u8 *ptr, *write_ptr;
1455         int old_num_stripes;
1456
1457         write_ptr = ptr = super->sys_chunk_array;
1458         array_size = btrfs_super_sys_array_size(super);
1459
1460         while (cur < array_size) {
1461                 disk_key = (struct btrfs_disk_key *)ptr;
1462                 btrfs_disk_key_to_cpu(&key, disk_key);
1463
1464                 new_array_size += sizeof(*disk_key);
1465                 memmove(write_ptr, ptr, sizeof(*disk_key));
1466
1467                 write_ptr += sizeof(*disk_key);
1468                 ptr += sizeof(*disk_key);
1469                 cur += sizeof(*disk_key);
1470
1471                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1472                         u64 type, physical, physical_dup, size = 0;
1473
1474                         chunk = (struct btrfs_chunk *)ptr;
1475                         old_num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1476                         chunk = (struct btrfs_chunk *)write_ptr;
1477
1478                         memmove(write_ptr, ptr, sizeof(*chunk));
1479                         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1480                         type = btrfs_stack_chunk_type(chunk);
1481                         if (type & BTRFS_BLOCK_GROUP_DUP) {
1482                                 new_array_size += sizeof(struct btrfs_stripe);
1483                                 write_ptr += sizeof(struct btrfs_stripe);
1484                         } else {
1485                                 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1486                                 btrfs_set_stack_chunk_type(chunk,
1487                                                 BTRFS_BLOCK_GROUP_SYSTEM);
1488                         }
1489                         chunk->stripe.devid = super->dev_item.devid;
1490                         physical = logical_to_physical(mdres, key.offset,
1491                                                        &size, &physical_dup);
1492                         if (size != (u64)-1)
1493                                 btrfs_set_stack_stripe_offset(&chunk->stripe,
1494                                                               physical);
1495                         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid,
1496                                BTRFS_UUID_SIZE);
1497                         new_array_size += sizeof(*chunk);
1498                 } else {
1499                         error("bogus key in the sys array %d", key.type);
1500                         return -EIO;
1501                 }
1502                 write_ptr += sizeof(*chunk);
1503                 ptr += btrfs_chunk_item_size(old_num_stripes);
1504                 cur += btrfs_chunk_item_size(old_num_stripes);
1505         }
1506
1507         if (mdres->clear_space_cache)
1508                 btrfs_set_super_cache_generation(super, 0);
1509
1510         flags |= BTRFS_SUPER_FLAG_METADUMP_V2;
1511         btrfs_set_super_flags(super, flags);
1512         btrfs_set_super_sys_array_size(super, new_array_size);
1513         csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
1514
1515         return 0;
1516 }
1517
1518 static struct extent_buffer *alloc_dummy_eb(u64 bytenr, u32 size)
1519 {
1520         struct extent_buffer *eb;
1521
1522         eb = calloc(1, sizeof(struct extent_buffer) + size);
1523         if (!eb)
1524                 return NULL;
1525
1526         eb->start = bytenr;
1527         eb->len = size;
1528         return eb;
1529 }
1530
1531 static void truncate_item(struct extent_buffer *eb, int slot, u32 new_size)
1532 {
1533         struct btrfs_item *item;
1534         u32 nritems;
1535         u32 old_size;
1536         u32 old_data_start;
1537         u32 size_diff;
1538         u32 data_end;
1539         int i;
1540
1541         old_size = btrfs_item_size_nr(eb, slot);
1542         if (old_size == new_size)
1543                 return;
1544
1545         nritems = btrfs_header_nritems(eb);
1546         data_end = btrfs_item_offset_nr(eb, nritems - 1);
1547
1548         old_data_start = btrfs_item_offset_nr(eb, slot);
1549         size_diff = old_size - new_size;
1550
1551         for (i = slot; i < nritems; i++) {
1552                 u32 ioff;
1553                 item = btrfs_item_nr(i);
1554                 ioff = btrfs_item_offset(eb, item);
1555                 btrfs_set_item_offset(eb, item, ioff + size_diff);
1556         }
1557
1558         memmove_extent_buffer(eb, btrfs_leaf_data(eb) + data_end + size_diff,
1559                               btrfs_leaf_data(eb) + data_end,
1560                               old_data_start + new_size - data_end);
1561         item = btrfs_item_nr(slot);
1562         btrfs_set_item_size(eb, item, new_size);
1563 }
1564
1565 static int fixup_chunk_tree_block(struct mdrestore_struct *mdres,
1566                                   struct async_work *async, u8 *buffer,
1567                                   size_t size)
1568 {
1569         struct extent_buffer *eb;
1570         size_t size_left = size;
1571         u64 bytenr = async->start;
1572         int i;
1573
1574         if (size_left % mdres->nodesize)
1575                 return 0;
1576
1577         eb = alloc_dummy_eb(bytenr, mdres->nodesize);
1578         if (!eb)
1579                 return -ENOMEM;
1580
1581         while (size_left) {
1582                 eb->start = bytenr;
1583                 memcpy(eb->data, buffer, mdres->nodesize);
1584
1585                 if (btrfs_header_bytenr(eb) != bytenr)
1586                         break;
1587                 if (memcmp(mdres->fsid,
1588                            eb->data + offsetof(struct btrfs_header, fsid),
1589                            BTRFS_FSID_SIZE))
1590                         break;
1591
1592                 if (btrfs_header_owner(eb) != BTRFS_CHUNK_TREE_OBJECTID)
1593                         goto next;
1594
1595                 if (btrfs_header_level(eb) != 0)
1596                         goto next;
1597
1598                 for (i = 0; i < btrfs_header_nritems(eb); i++) {
1599                         struct btrfs_chunk *chunk;
1600                         struct btrfs_key key;
1601                         u64 type, physical, physical_dup, size = (u64)-1;
1602
1603                         btrfs_item_key_to_cpu(eb, &key, i);
1604                         if (key.type != BTRFS_CHUNK_ITEM_KEY)
1605                                 continue;
1606
1607                         size = 0;
1608                         physical = logical_to_physical(mdres, key.offset,
1609                                                        &size, &physical_dup);
1610
1611                         if (!physical_dup)
1612                                 truncate_item(eb, i, sizeof(*chunk));
1613                         chunk = btrfs_item_ptr(eb, i, struct btrfs_chunk);
1614
1615
1616                         /* Zero out the RAID profile */
1617                         type = btrfs_chunk_type(eb, chunk);
1618                         type &= (BTRFS_BLOCK_GROUP_DATA |
1619                                  BTRFS_BLOCK_GROUP_SYSTEM |
1620                                  BTRFS_BLOCK_GROUP_METADATA |
1621                                  BTRFS_BLOCK_GROUP_DUP);
1622                         btrfs_set_chunk_type(eb, chunk, type);
1623
1624                         if (!physical_dup)
1625                                 btrfs_set_chunk_num_stripes(eb, chunk, 1);
1626                         btrfs_set_chunk_sub_stripes(eb, chunk, 0);
1627                         btrfs_set_stripe_devid_nr(eb, chunk, 0, mdres->devid);
1628                         if (size != (u64)-1)
1629                                 btrfs_set_stripe_offset_nr(eb, chunk, 0,
1630                                                            physical);
1631                         /* update stripe 2 offset */
1632                         if (physical_dup)
1633                                 btrfs_set_stripe_offset_nr(eb, chunk, 1,
1634                                                            physical_dup);
1635
1636                         write_extent_buffer(eb, mdres->uuid,
1637                                         (unsigned long)btrfs_stripe_dev_uuid_nr(
1638                                                 chunk, 0),
1639                                         BTRFS_UUID_SIZE);
1640                 }
1641                 memcpy(buffer, eb->data, eb->len);
1642                 csum_block(buffer, eb->len);
1643 next:
1644                 size_left -= mdres->nodesize;
1645                 buffer += mdres->nodesize;
1646                 bytenr += mdres->nodesize;
1647         }
1648
1649         free(eb);
1650         return 0;
1651 }
1652
1653 static void write_backup_supers(int fd, u8 *buf)
1654 {
1655         struct btrfs_super_block *super = (struct btrfs_super_block *)buf;
1656         struct stat st;
1657         u64 size;
1658         u64 bytenr;
1659         int i;
1660         int ret;
1661
1662         if (fstat(fd, &st)) {
1663                 error(
1664         "cannot stat restore point, won't be able to write backup supers: %s",
1665                         strerror(errno));
1666                 return;
1667         }
1668
1669         size = btrfs_device_size(fd, &st);
1670
1671         for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1672                 bytenr = btrfs_sb_offset(i);
1673                 if (bytenr + BTRFS_SUPER_INFO_SIZE > size)
1674                         break;
1675                 btrfs_set_super_bytenr(super, bytenr);
1676                 csum_block(buf, BTRFS_SUPER_INFO_SIZE);
1677                 ret = pwrite64(fd, buf, BTRFS_SUPER_INFO_SIZE, bytenr);
1678                 if (ret < BTRFS_SUPER_INFO_SIZE) {
1679                         if (ret < 0)
1680                                 error(
1681                                 "problem writing out backup super block %d: %s",
1682                                                 i, strerror(errno));
1683                         else
1684                                 error("short write writing out backup super block");
1685                         break;
1686                 }
1687         }
1688 }
1689
1690 static void *restore_worker(void *data)
1691 {
1692         struct mdrestore_struct *mdres = (struct mdrestore_struct *)data;
1693         struct async_work *async;
1694         size_t size;
1695         u8 *buffer;
1696         u8 *outbuf;
1697         int outfd;
1698         int ret;
1699         int compress_size = MAX_PENDING_SIZE * 4;
1700
1701         outfd = fileno(mdres->out);
1702         buffer = malloc(compress_size);
1703         if (!buffer) {
1704                 error("not enough memory for restore worker buffer");
1705                 pthread_mutex_lock(&mdres->mutex);
1706                 if (!mdres->error)
1707                         mdres->error = -ENOMEM;
1708                 pthread_mutex_unlock(&mdres->mutex);
1709                 pthread_exit(NULL);
1710         }
1711
1712         while (1) {
1713                 u64 bytenr, physical_dup;
1714                 off_t offset = 0;
1715                 int err = 0;
1716
1717                 pthread_mutex_lock(&mdres->mutex);
1718                 while (!mdres->nodesize || list_empty(&mdres->list)) {
1719                         if (mdres->done) {
1720                                 pthread_mutex_unlock(&mdres->mutex);
1721                                 goto out;
1722                         }
1723                         pthread_cond_wait(&mdres->cond, &mdres->mutex);
1724                 }
1725                 async = list_entry(mdres->list.next, struct async_work, list);
1726                 list_del_init(&async->list);
1727                 pthread_mutex_unlock(&mdres->mutex);
1728
1729                 if (mdres->compress_method == COMPRESS_ZLIB) {
1730                         size = compress_size; 
1731                         ret = uncompress(buffer, (unsigned long *)&size,
1732                                          async->buffer, async->bufsize);
1733                         if (ret != Z_OK) {
1734                                 error("decompressiion failed with %d", ret);
1735                                 err = -EIO;
1736                         }
1737                         outbuf = buffer;
1738                 } else {
1739                         outbuf = async->buffer;
1740                         size = async->bufsize;
1741                 }
1742
1743                 if (!mdres->multi_devices) {
1744                         if (async->start == BTRFS_SUPER_INFO_OFFSET) {
1745                                 if (mdres->old_restore) {
1746                                         update_super_old(outbuf);
1747                                 } else {
1748                                         ret = update_super(mdres, outbuf);
1749                                         if (ret)
1750                                                 err = ret;
1751                                 }
1752                         } else if (!mdres->old_restore) {
1753                                 ret = fixup_chunk_tree_block(mdres, async, outbuf, size);
1754                                 if (ret)
1755                                         err = ret;
1756                         }
1757                 }
1758
1759                 if (!mdres->fixup_offset) {
1760                         while (size) {
1761                                 u64 chunk_size = size;
1762                                 physical_dup = 0;
1763                                 if (!mdres->multi_devices && !mdres->old_restore)
1764                                         bytenr = logical_to_physical(mdres,
1765                                                      async->start + offset,
1766                                                      &chunk_size,
1767                                                      &physical_dup);
1768                                 else
1769                                         bytenr = async->start + offset;
1770
1771                                 ret = pwrite64(outfd, outbuf+offset, chunk_size,
1772                                                bytenr);
1773                                 if (ret != chunk_size)
1774                                         goto error;
1775
1776                                 if (physical_dup)
1777                                         ret = pwrite64(outfd, outbuf+offset,
1778                                                        chunk_size,
1779                                                        physical_dup);
1780                                 if (ret != chunk_size)
1781                                         goto error;
1782
1783                                 size -= chunk_size;
1784                                 offset += chunk_size;
1785                                 continue;
1786
1787 error:
1788                                 if (ret < 0) {
1789                                         error("unable to write to device: %s",
1790                                                         strerror(errno));
1791                                         err = errno;
1792                                 } else {
1793                                         error("short write");
1794                                         err = -EIO;
1795                                 }
1796                         }
1797                 } else if (async->start != BTRFS_SUPER_INFO_OFFSET) {
1798                         ret = write_data_to_disk(mdres->info, outbuf, async->start, size, 0);
1799                         if (ret) {
1800                                 error("failed to write data");
1801                                 exit(1);
1802                         }
1803                 }
1804
1805
1806                 /* backup super blocks are already there at fixup_offset stage */
1807                 if (!mdres->multi_devices && async->start == BTRFS_SUPER_INFO_OFFSET)
1808                         write_backup_supers(outfd, outbuf);
1809
1810                 pthread_mutex_lock(&mdres->mutex);
1811                 if (err && !mdres->error)
1812                         mdres->error = err;
1813                 mdres->num_items--;
1814                 pthread_mutex_unlock(&mdres->mutex);
1815
1816                 free(async->buffer);
1817                 free(async);
1818         }
1819 out:
1820         free(buffer);
1821         pthread_exit(NULL);
1822 }
1823
1824 static void mdrestore_destroy(struct mdrestore_struct *mdres, int num_threads)
1825 {
1826         struct rb_node *n;
1827         int i;
1828
1829         while ((n = rb_first(&mdres->chunk_tree))) {
1830                 struct fs_chunk *entry;
1831
1832                 entry = rb_entry(n, struct fs_chunk, l);
1833                 rb_erase(n, &mdres->chunk_tree);
1834                 rb_erase(&entry->p, &mdres->physical_tree);
1835                 free(entry);
1836         }
1837         pthread_mutex_lock(&mdres->mutex);
1838         mdres->done = 1;
1839         pthread_cond_broadcast(&mdres->cond);
1840         pthread_mutex_unlock(&mdres->mutex);
1841
1842         for (i = 0; i < num_threads; i++)
1843                 pthread_join(mdres->threads[i], NULL);
1844
1845         pthread_cond_destroy(&mdres->cond);
1846         pthread_mutex_destroy(&mdres->mutex);
1847         free(mdres->threads);
1848 }
1849
1850 static int mdrestore_init(struct mdrestore_struct *mdres,
1851                           FILE *in, FILE *out, int old_restore,
1852                           int num_threads, int fixup_offset,
1853                           struct btrfs_fs_info *info, int multi_devices)
1854 {
1855         int i, ret = 0;
1856
1857         memset(mdres, 0, sizeof(*mdres));
1858         pthread_cond_init(&mdres->cond, NULL);
1859         pthread_mutex_init(&mdres->mutex, NULL);
1860         INIT_LIST_HEAD(&mdres->list);
1861         INIT_LIST_HEAD(&mdres->overlapping_chunks);
1862         mdres->in = in;
1863         mdres->out = out;
1864         mdres->old_restore = old_restore;
1865         mdres->chunk_tree.rb_node = NULL;
1866         mdres->fixup_offset = fixup_offset;
1867         mdres->info = info;
1868         mdres->multi_devices = multi_devices;
1869         mdres->clear_space_cache = 0;
1870         mdres->last_physical_offset = 0;
1871         mdres->alloced_chunks = 0;
1872
1873         if (!num_threads)
1874                 return 0;
1875
1876         mdres->num_threads = num_threads;
1877         mdres->threads = calloc(num_threads, sizeof(pthread_t));
1878         if (!mdres->threads)
1879                 return -ENOMEM;
1880         for (i = 0; i < num_threads; i++) {
1881                 ret = pthread_create(mdres->threads + i, NULL, restore_worker,
1882                                      mdres);
1883                 if (ret) {
1884                         /* pthread_create returns errno directly */
1885                         ret = -ret;
1886                         break;
1887                 }
1888         }
1889         if (ret)
1890                 mdrestore_destroy(mdres, i + 1);
1891         return ret;
1892 }
1893
1894 static int fill_mdres_info(struct mdrestore_struct *mdres,
1895                            struct async_work *async)
1896 {
1897         struct btrfs_super_block *super;
1898         u8 *buffer = NULL;
1899         u8 *outbuf;
1900         int ret;
1901
1902         /* We've already been initialized */
1903         if (mdres->nodesize)
1904                 return 0;
1905
1906         if (mdres->compress_method == COMPRESS_ZLIB) {
1907                 size_t size = MAX_PENDING_SIZE * 2;
1908
1909                 buffer = malloc(MAX_PENDING_SIZE * 2);
1910                 if (!buffer)
1911                         return -ENOMEM;
1912                 ret = uncompress(buffer, (unsigned long *)&size,
1913                                  async->buffer, async->bufsize);
1914                 if (ret != Z_OK) {
1915                         error("decompressiion failed with %d", ret);
1916                         free(buffer);
1917                         return -EIO;
1918                 }
1919                 outbuf = buffer;
1920         } else {
1921                 outbuf = async->buffer;
1922         }
1923
1924         super = (struct btrfs_super_block *)outbuf;
1925         mdres->nodesize = btrfs_super_nodesize(super);
1926         memcpy(mdres->fsid, super->fsid, BTRFS_FSID_SIZE);
1927         memcpy(mdres->uuid, super->dev_item.uuid,
1928                        BTRFS_UUID_SIZE);
1929         mdres->devid = le64_to_cpu(super->dev_item.devid);
1930         free(buffer);
1931         return 0;
1932 }
1933
1934 static int add_cluster(struct meta_cluster *cluster,
1935                        struct mdrestore_struct *mdres, u64 *next)
1936 {
1937         struct meta_cluster_item *item;
1938         struct meta_cluster_header *header = &cluster->header;
1939         struct async_work *async;
1940         u64 bytenr;
1941         u32 i, nritems;
1942         int ret;
1943
1944         mdres->compress_method = header->compress;
1945
1946         bytenr = le64_to_cpu(header->bytenr) + BLOCK_SIZE;
1947         nritems = le32_to_cpu(header->nritems);
1948         for (i = 0; i < nritems; i++) {
1949                 item = &cluster->items[i];
1950                 async = calloc(1, sizeof(*async));
1951                 if (!async) {
1952                         error("not enough memory for async data");
1953                         return -ENOMEM;
1954                 }
1955                 async->start = le64_to_cpu(item->bytenr);
1956                 async->bufsize = le32_to_cpu(item->size);
1957                 async->buffer = malloc(async->bufsize);
1958                 if (!async->buffer) {
1959                         error("not enough memory for async buffer");
1960                         free(async);
1961                         return -ENOMEM;
1962                 }
1963                 ret = fread(async->buffer, async->bufsize, 1, mdres->in);
1964                 if (ret != 1) {
1965                         error("unable to read buffer: %s", strerror(errno));
1966                         free(async->buffer);
1967                         free(async);
1968                         return -EIO;
1969                 }
1970                 bytenr += async->bufsize;
1971
1972                 pthread_mutex_lock(&mdres->mutex);
1973                 if (async->start == BTRFS_SUPER_INFO_OFFSET) {
1974                         ret = fill_mdres_info(mdres, async);
1975                         if (ret) {
1976                                 error("unable to set up restore state");
1977                                 pthread_mutex_unlock(&mdres->mutex);
1978                                 free(async->buffer);
1979                                 free(async);
1980                                 return ret;
1981                         }
1982                 }
1983                 list_add_tail(&async->list, &mdres->list);
1984                 mdres->num_items++;
1985                 pthread_cond_signal(&mdres->cond);
1986                 pthread_mutex_unlock(&mdres->mutex);
1987         }
1988         if (bytenr & BLOCK_MASK) {
1989                 char buffer[BLOCK_MASK];
1990                 size_t size = BLOCK_SIZE - (bytenr & BLOCK_MASK);
1991
1992                 bytenr += size;
1993                 ret = fread(buffer, size, 1, mdres->in);
1994                 if (ret != 1) {
1995                         error("failed to read buffer: %s", strerror(errno));
1996                         return -EIO;
1997                 }
1998         }
1999         *next = bytenr;
2000         return 0;
2001 }
2002
2003 static int wait_for_worker(struct mdrestore_struct *mdres)
2004 {
2005         int ret = 0;
2006
2007         pthread_mutex_lock(&mdres->mutex);
2008         ret = mdres->error;
2009         while (!ret && mdres->num_items > 0) {
2010                 struct timespec ts = {
2011                         .tv_sec = 0,
2012                         .tv_nsec = 10000000,
2013                 };
2014                 pthread_mutex_unlock(&mdres->mutex);
2015                 nanosleep(&ts, NULL);
2016                 pthread_mutex_lock(&mdres->mutex);
2017                 ret = mdres->error;
2018         }
2019         pthread_mutex_unlock(&mdres->mutex);
2020         return ret;
2021 }
2022
2023 static int read_chunk_block(struct mdrestore_struct *mdres, u8 *buffer,
2024                             u64 bytenr, u64 item_bytenr, u32 bufsize,
2025                             u64 cluster_bytenr)
2026 {
2027         struct extent_buffer *eb;
2028         int ret = 0;
2029         int i;
2030
2031         eb = alloc_dummy_eb(bytenr, mdres->nodesize);
2032         if (!eb) {
2033                 ret = -ENOMEM;
2034                 goto out;
2035         }
2036
2037         while (item_bytenr != bytenr) {
2038                 buffer += mdres->nodesize;
2039                 item_bytenr += mdres->nodesize;
2040         }
2041
2042         memcpy(eb->data, buffer, mdres->nodesize);
2043         if (btrfs_header_bytenr(eb) != bytenr) {
2044                 error("eb bytenr does not match found bytenr: %llu != %llu",
2045                                 (unsigned long long)btrfs_header_bytenr(eb),
2046                                 (unsigned long long)bytenr);
2047                 ret = -EIO;
2048                 goto out;
2049         }
2050
2051         if (memcmp(mdres->fsid, eb->data + offsetof(struct btrfs_header, fsid),
2052                    BTRFS_FSID_SIZE)) {
2053                 error("filesystem UUID of eb %llu does not match",
2054                                 (unsigned long long)bytenr);
2055                 ret = -EIO;
2056                 goto out;
2057         }
2058
2059         if (btrfs_header_owner(eb) != BTRFS_CHUNK_TREE_OBJECTID) {
2060                 error("wrong eb %llu owner %llu",
2061                                 (unsigned long long)bytenr,
2062                                 (unsigned long long)btrfs_header_owner(eb));
2063                 ret = -EIO;
2064                 goto out;
2065         }
2066
2067         for (i = 0; i < btrfs_header_nritems(eb); i++) {
2068                 struct btrfs_chunk *chunk;
2069                 struct fs_chunk *fs_chunk;
2070                 struct btrfs_key key;
2071                 u64 type;
2072
2073                 if (btrfs_header_level(eb)) {
2074                         u64 blockptr = btrfs_node_blockptr(eb, i);
2075
2076                         ret = search_for_chunk_blocks(mdres, blockptr,
2077                                                       cluster_bytenr);
2078                         if (ret)
2079                                 break;
2080                         continue;
2081                 }
2082
2083                 /* Yay a leaf!  We loves leafs! */
2084                 btrfs_item_key_to_cpu(eb, &key, i);
2085                 if (key.type != BTRFS_CHUNK_ITEM_KEY)
2086                         continue;
2087
2088                 fs_chunk = malloc(sizeof(struct fs_chunk));
2089                 if (!fs_chunk) {
2090                         error("not enough memory to allocate chunk");
2091                         ret = -ENOMEM;
2092                         break;
2093                 }
2094                 memset(fs_chunk, 0, sizeof(*fs_chunk));
2095                 chunk = btrfs_item_ptr(eb, i, struct btrfs_chunk);
2096
2097                 fs_chunk->logical = key.offset;
2098                 fs_chunk->physical = btrfs_stripe_offset_nr(eb, chunk, 0);
2099                 fs_chunk->bytes = btrfs_chunk_length(eb, chunk);
2100                 INIT_LIST_HEAD(&fs_chunk->list);
2101                 if (tree_search(&mdres->physical_tree, &fs_chunk->p,
2102                                 physical_cmp, 1) != NULL)
2103                         list_add(&fs_chunk->list, &mdres->overlapping_chunks);
2104                 else
2105                         tree_insert(&mdres->physical_tree, &fs_chunk->p,
2106                                     physical_cmp);
2107
2108                 type = btrfs_chunk_type(eb, chunk);
2109                 if (type & BTRFS_BLOCK_GROUP_DUP) {
2110                         fs_chunk->physical_dup =
2111                                         btrfs_stripe_offset_nr(eb, chunk, 1);
2112                 }
2113
2114                 if (fs_chunk->physical_dup + fs_chunk->bytes >
2115                     mdres->last_physical_offset)
2116                         mdres->last_physical_offset = fs_chunk->physical_dup +
2117                                 fs_chunk->bytes;
2118                 else if (fs_chunk->physical + fs_chunk->bytes >
2119                     mdres->last_physical_offset)
2120                         mdres->last_physical_offset = fs_chunk->physical +
2121                                 fs_chunk->bytes;
2122                 mdres->alloced_chunks += fs_chunk->bytes;
2123                 /* in dup case, fs_chunk->bytes should add twice */
2124                 if (fs_chunk->physical_dup)
2125                         mdres->alloced_chunks += fs_chunk->bytes;
2126                 tree_insert(&mdres->chunk_tree, &fs_chunk->l, chunk_cmp);
2127         }
2128 out:
2129         free(eb);
2130         return ret;
2131 }
2132
2133 /* If you have to ask you aren't worthy */
2134 static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
2135                                    u64 search, u64 cluster_bytenr)
2136 {
2137         struct meta_cluster *cluster;
2138         struct meta_cluster_header *header;
2139         struct meta_cluster_item *item;
2140         u64 current_cluster = cluster_bytenr, bytenr;
2141         u64 item_bytenr;
2142         u32 bufsize, nritems, i;
2143         u32 max_size = MAX_PENDING_SIZE * 2;
2144         u8 *buffer, *tmp = NULL;
2145         int ret = 0;
2146
2147         cluster = malloc(BLOCK_SIZE);
2148         if (!cluster) {
2149                 error("not enough memory for cluster");
2150                 return -ENOMEM;
2151         }
2152
2153         buffer = malloc(max_size);
2154         if (!buffer) {
2155                 error("not enough memory for buffer");
2156                 free(cluster);
2157                 return -ENOMEM;
2158         }
2159
2160         if (mdres->compress_method == COMPRESS_ZLIB) {
2161                 tmp = malloc(max_size);
2162                 if (!tmp) {
2163                         error("not enough memory for buffer");
2164                         free(cluster);
2165                         free(buffer);
2166                         return -ENOMEM;
2167                 }
2168         }
2169
2170         bytenr = current_cluster;
2171         while (1) {
2172                 if (fseek(mdres->in, current_cluster, SEEK_SET)) {
2173                         error("seek failed: %s\n", strerror(errno));
2174                         ret = -EIO;
2175                         break;
2176                 }
2177
2178                 ret = fread(cluster, BLOCK_SIZE, 1, mdres->in);
2179                 if (ret == 0) {
2180                         if (cluster_bytenr != 0) {
2181                                 cluster_bytenr = 0;
2182                                 current_cluster = 0;
2183                                 bytenr = 0;
2184                                 continue;
2185                         }
2186                         error(
2187         "unknown state after reading cluster at %llu, probably crrupted data",
2188                                         cluster_bytenr);
2189                         ret = -EIO;
2190                         break;
2191                 } else if (ret < 0) {
2192                         error("unable to read image at %llu: %s",
2193                                         (unsigned long long)cluster_bytenr,
2194                                         strerror(errno));
2195                         break;
2196                 }
2197                 ret = 0;
2198
2199                 header = &cluster->header;
2200                 if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2201                     le64_to_cpu(header->bytenr) != current_cluster) {
2202                         error("bad header in metadump image");
2203                         ret = -EIO;
2204                         break;
2205                 }
2206
2207                 bytenr += BLOCK_SIZE;
2208                 nritems = le32_to_cpu(header->nritems);
2209                 for (i = 0; i < nritems; i++) {
2210                         size_t size;
2211
2212                         item = &cluster->items[i];
2213                         bufsize = le32_to_cpu(item->size);
2214                         item_bytenr = le64_to_cpu(item->bytenr);
2215
2216                         if (bufsize > max_size) {
2217                                 error("item %u too big: %u > %u", i, bufsize,
2218                                                 max_size);
2219                                 ret = -EIO;
2220                                 break;
2221                         }
2222
2223                         if (mdres->compress_method == COMPRESS_ZLIB) {
2224                                 ret = fread(tmp, bufsize, 1, mdres->in);
2225                                 if (ret != 1) {
2226                                         error("read error: %s", strerror(errno));
2227                                         ret = -EIO;
2228                                         break;
2229                                 }
2230
2231                                 size = max_size;
2232                                 ret = uncompress(buffer,
2233                                                  (unsigned long *)&size, tmp,
2234                                                  bufsize);
2235                                 if (ret != Z_OK) {
2236                                         error("decompressiion failed with %d",
2237                                                         ret);
2238                                         ret = -EIO;
2239                                         break;
2240                                 }
2241                         } else {
2242                                 ret = fread(buffer, bufsize, 1, mdres->in);
2243                                 if (ret != 1) {
2244                                         error("read error: %s",
2245                                                         strerror(errno));
2246                                         ret = -EIO;
2247                                         break;
2248                                 }
2249                                 size = bufsize;
2250                         }
2251                         ret = 0;
2252
2253                         if (item_bytenr <= search &&
2254                             item_bytenr + size > search) {
2255                                 ret = read_chunk_block(mdres, buffer, search,
2256                                                        item_bytenr, size,
2257                                                        current_cluster);
2258                                 if (!ret)
2259                                         ret = 1;
2260                                 break;
2261                         }
2262                         bytenr += bufsize;
2263                 }
2264                 if (ret) {
2265                         if (ret > 0)
2266                                 ret = 0;
2267                         break;
2268                 }
2269                 if (bytenr & BLOCK_MASK)
2270                         bytenr += BLOCK_SIZE - (bytenr & BLOCK_MASK);
2271                 current_cluster = bytenr;
2272         }
2273
2274         free(tmp);
2275         free(buffer);
2276         free(cluster);
2277         return ret;
2278 }
2279
2280 static int build_chunk_tree(struct mdrestore_struct *mdres,
2281                             struct meta_cluster *cluster)
2282 {
2283         struct btrfs_super_block *super;
2284         struct meta_cluster_header *header;
2285         struct meta_cluster_item *item = NULL;
2286         u64 chunk_root_bytenr = 0;
2287         u32 i, nritems;
2288         u64 bytenr = 0;
2289         u8 *buffer;
2290         int ret;
2291
2292         /* We can't seek with stdin so don't bother doing this */
2293         if (mdres->in == stdin)
2294                 return 0;
2295
2296         ret = fread(cluster, BLOCK_SIZE, 1, mdres->in);
2297         if (ret <= 0) {
2298                 error("unable to read cluster: %s", strerror(errno));
2299                 return -EIO;
2300         }
2301         ret = 0;
2302
2303         header = &cluster->header;
2304         if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2305             le64_to_cpu(header->bytenr) != 0) {
2306                 error("bad header in metadump image");
2307                 return -EIO;
2308         }
2309
2310         bytenr += BLOCK_SIZE;
2311         mdres->compress_method = header->compress;
2312         nritems = le32_to_cpu(header->nritems);
2313         for (i = 0; i < nritems; i++) {
2314                 item = &cluster->items[i];
2315
2316                 if (le64_to_cpu(item->bytenr) == BTRFS_SUPER_INFO_OFFSET)
2317                         break;
2318                 bytenr += le32_to_cpu(item->size);
2319                 if (fseek(mdres->in, le32_to_cpu(item->size), SEEK_CUR)) {
2320                         error("seek failed: %s\n", strerror(errno));
2321                         return -EIO;
2322                 }
2323         }
2324
2325         if (!item || le64_to_cpu(item->bytenr) != BTRFS_SUPER_INFO_OFFSET) {
2326                 error("did not find superblock at %llu",
2327                                 le64_to_cpu(item->bytenr));
2328                 return -EINVAL;
2329         }
2330
2331         buffer = malloc(le32_to_cpu(item->size));
2332         if (!buffer) {
2333                 error("not enough memory to allocate buffer");
2334                 return -ENOMEM;
2335         }
2336
2337         ret = fread(buffer, le32_to_cpu(item->size), 1, mdres->in);
2338         if (ret != 1) {
2339                 error("unable to read buffer: %s", strerror(errno));
2340                 free(buffer);
2341                 return -EIO;
2342         }
2343
2344         if (mdres->compress_method == COMPRESS_ZLIB) {
2345                 size_t size = MAX_PENDING_SIZE * 2;
2346                 u8 *tmp;
2347
2348                 tmp = malloc(MAX_PENDING_SIZE * 2);
2349                 if (!tmp) {
2350                         free(buffer);
2351                         return -ENOMEM;
2352                 }
2353                 ret = uncompress(tmp, (unsigned long *)&size,
2354                                  buffer, le32_to_cpu(item->size));
2355                 if (ret != Z_OK) {
2356                         error("decompressiion failed with %d", ret);
2357                         free(buffer);
2358                         free(tmp);
2359                         return -EIO;
2360                 }
2361                 free(buffer);
2362                 buffer = tmp;
2363         }
2364
2365         pthread_mutex_lock(&mdres->mutex);
2366         super = (struct btrfs_super_block *)buffer;
2367         chunk_root_bytenr = btrfs_super_chunk_root(super);
2368         mdres->nodesize = btrfs_super_nodesize(super);
2369         memcpy(mdres->fsid, super->fsid, BTRFS_FSID_SIZE);
2370         memcpy(mdres->uuid, super->dev_item.uuid,
2371                        BTRFS_UUID_SIZE);
2372         mdres->devid = le64_to_cpu(super->dev_item.devid);
2373         free(buffer);
2374         pthread_mutex_unlock(&mdres->mutex);
2375
2376         return search_for_chunk_blocks(mdres, chunk_root_bytenr, 0);
2377 }
2378
2379 static int range_contains_super(u64 physical, u64 bytes)
2380 {
2381         u64 super_bytenr;
2382         int i;
2383
2384         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2385                 super_bytenr = btrfs_sb_offset(i);
2386                 if (super_bytenr >= physical &&
2387                     super_bytenr < physical + bytes)
2388                         return 1;
2389         }
2390
2391         return 0;
2392 }
2393
2394 static void remap_overlapping_chunks(struct mdrestore_struct *mdres)
2395 {
2396         struct fs_chunk *fs_chunk;
2397
2398         while (!list_empty(&mdres->overlapping_chunks)) {
2399                 fs_chunk = list_first_entry(&mdres->overlapping_chunks,
2400                                             struct fs_chunk, list);
2401                 list_del_init(&fs_chunk->list);
2402                 if (range_contains_super(fs_chunk->physical,
2403                                          fs_chunk->bytes)) {
2404                         warning(
2405 "remapping a chunk that had a super mirror inside of it, clearing space cache so we don't end up with corruption");
2406                         mdres->clear_space_cache = 1;
2407                 }
2408                 fs_chunk->physical = mdres->last_physical_offset;
2409                 tree_insert(&mdres->physical_tree, &fs_chunk->p, physical_cmp);
2410                 mdres->last_physical_offset += fs_chunk->bytes;
2411         }
2412 }
2413
2414 static int fixup_devices(struct btrfs_fs_info *fs_info,
2415                          struct mdrestore_struct *mdres, off_t dev_size)
2416 {
2417         struct btrfs_trans_handle *trans;
2418         struct btrfs_dev_item *dev_item;
2419         struct btrfs_path *path;
2420         struct extent_buffer *leaf;
2421         struct btrfs_root *root = fs_info->chunk_root;
2422         struct btrfs_key key;
2423         u64 devid, cur_devid;
2424         int ret;
2425
2426         path = btrfs_alloc_path();
2427         if (!path) {
2428                 error("not enough memory to allocate path");
2429                 return -ENOMEM;
2430         }
2431
2432         trans = btrfs_start_transaction(fs_info->tree_root, 1);
2433         if (IS_ERR(trans)) {
2434                 error("cannot starting transaction %ld", PTR_ERR(trans));
2435                 btrfs_free_path(path);
2436                 return PTR_ERR(trans);
2437         }
2438
2439         dev_item = &fs_info->super_copy->dev_item;
2440
2441         devid = btrfs_stack_device_id(dev_item);
2442
2443         btrfs_set_stack_device_total_bytes(dev_item, dev_size);
2444         btrfs_set_stack_device_bytes_used(dev_item, mdres->alloced_chunks);
2445
2446         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2447         key.type = BTRFS_DEV_ITEM_KEY;
2448         key.offset = 0;
2449
2450 again:
2451         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2452         if (ret < 0) {
2453                 error("search failed: %d", ret);
2454                 exit(1);
2455         }
2456
2457         while (1) {
2458                 leaf = path->nodes[0];
2459                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2460                         ret = btrfs_next_leaf(root, path);
2461                         if (ret < 0) {
2462                                 error("cannot go to next leaf %d", ret);
2463                                 exit(1);
2464                         }
2465                         if (ret > 0) {
2466                                 ret = 0;
2467                                 break;
2468                         }
2469                         leaf = path->nodes[0];
2470                 }
2471
2472                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2473                 if (key.type > BTRFS_DEV_ITEM_KEY)
2474                         break;
2475                 if (key.type != BTRFS_DEV_ITEM_KEY) {
2476                         path->slots[0]++;
2477                         continue;
2478                 }
2479
2480                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2481                                           struct btrfs_dev_item);
2482                 cur_devid = btrfs_device_id(leaf, dev_item);
2483                 if (devid != cur_devid) {
2484                         ret = btrfs_del_item(trans, root, path);
2485                         if (ret) {
2486                                 error("cannot delete item: %d", ret);
2487                                 exit(1);
2488                         }
2489                         btrfs_release_path(path);
2490                         goto again;
2491                 }
2492
2493                 btrfs_set_device_total_bytes(leaf, dev_item, dev_size);
2494                 btrfs_set_device_bytes_used(leaf, dev_item,
2495                                             mdres->alloced_chunks);
2496                 btrfs_mark_buffer_dirty(leaf);
2497                 path->slots[0]++;
2498         }
2499
2500         btrfs_free_path(path);
2501         ret = btrfs_commit_transaction(trans, fs_info->tree_root);
2502         if (ret) {
2503                 error("unable to commit transaction: %d", ret);
2504                 return ret;
2505         }
2506         return 0;
2507 }
2508
2509 static int restore_metadump(const char *input, FILE *out, int old_restore,
2510                             int num_threads, int fixup_offset,
2511                             const char *target, int multi_devices)
2512 {
2513         struct meta_cluster *cluster = NULL;
2514         struct meta_cluster_header *header;
2515         struct mdrestore_struct mdrestore;
2516         struct btrfs_fs_info *info = NULL;
2517         u64 bytenr = 0;
2518         FILE *in = NULL;
2519         int ret = 0;
2520
2521         if (!strcmp(input, "-")) {
2522                 in = stdin;
2523         } else {
2524                 in = fopen(input, "r");
2525                 if (!in) {
2526                         error("unable to open metadump image: %s",
2527                                         strerror(errno));
2528                         return 1;
2529                 }
2530         }
2531
2532         /* NOTE: open with write mode */
2533         if (fixup_offset) {
2534                 info = open_ctree_fs_info(target, 0, 0, 0,
2535                                           OPEN_CTREE_WRITES |
2536                                           OPEN_CTREE_RESTORE |
2537                                           OPEN_CTREE_PARTIAL);
2538                 if (!info) {
2539                         error("open ctree failed");
2540                         ret = -EIO;
2541                         goto failed_open;
2542                 }
2543         }
2544
2545         cluster = malloc(BLOCK_SIZE);
2546         if (!cluster) {
2547                 error("not enough memory for cluster");
2548                 ret = -ENOMEM;
2549                 goto failed_info;
2550         }
2551
2552         ret = mdrestore_init(&mdrestore, in, out, old_restore, num_threads,
2553                              fixup_offset, info, multi_devices);
2554         if (ret) {
2555                 error("failed to intialize metadata restore state: %d", ret);
2556                 goto failed_cluster;
2557         }
2558
2559         if (!multi_devices && !old_restore) {
2560                 ret = build_chunk_tree(&mdrestore, cluster);
2561                 if (ret)
2562                         goto out;
2563                 if (!list_empty(&mdrestore.overlapping_chunks))
2564                         remap_overlapping_chunks(&mdrestore);
2565         }
2566
2567         if (in != stdin && fseek(in, 0, SEEK_SET)) {
2568                 error("seek failed: %s\n", strerror(errno));
2569                 goto out;
2570         }
2571
2572         while (!mdrestore.error) {
2573                 ret = fread(cluster, BLOCK_SIZE, 1, in);
2574                 if (!ret)
2575                         break;
2576
2577                 header = &cluster->header;
2578                 if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2579                     le64_to_cpu(header->bytenr) != bytenr) {
2580                         error("bad header in metadump image");
2581                         ret = -EIO;
2582                         break;
2583                 }
2584                 ret = add_cluster(cluster, &mdrestore, &bytenr);
2585                 if (ret) {
2586                         error("failed to add cluster: %d", ret);
2587                         break;
2588                 }
2589         }
2590         ret = wait_for_worker(&mdrestore);
2591
2592         if (!ret && !multi_devices && !old_restore) {
2593                 struct btrfs_root *root;
2594                 struct stat st;
2595
2596                 root = open_ctree_fd(fileno(out), target, 0,
2597                                           OPEN_CTREE_PARTIAL |
2598                                           OPEN_CTREE_WRITES |
2599                                           OPEN_CTREE_NO_DEVICES);
2600                 if (!root) {
2601                         error("open ctree failed in %s", target);
2602                         ret = -EIO;
2603                         goto out;
2604                 }
2605                 info = root->fs_info;
2606
2607                 if (stat(target, &st)) {
2608                         error("stat %s failed: %s", target, strerror(errno));
2609                         close_ctree(info->chunk_root);
2610                         free(cluster);
2611                         return 1;
2612                 }
2613
2614                 ret = fixup_devices(info, &mdrestore, st.st_size);
2615                 close_ctree(info->chunk_root);
2616                 if (ret)
2617                         goto out;
2618         }
2619 out:
2620         mdrestore_destroy(&mdrestore, num_threads);
2621 failed_cluster:
2622         free(cluster);
2623 failed_info:
2624         if (fixup_offset && info)
2625                 close_ctree(info->chunk_root);
2626 failed_open:
2627         if (in != stdin)
2628                 fclose(in);
2629         return ret;
2630 }
2631
2632 static int update_disk_super_on_device(struct btrfs_fs_info *info,
2633                                        const char *other_dev, u64 cur_devid)
2634 {
2635         struct btrfs_key key;
2636         struct extent_buffer *leaf;
2637         struct btrfs_path path;
2638         struct btrfs_dev_item *dev_item;
2639         struct btrfs_super_block *disk_super;
2640         char dev_uuid[BTRFS_UUID_SIZE];
2641         char fs_uuid[BTRFS_UUID_SIZE];
2642         u64 devid, type, io_align, io_width;
2643         u64 sector_size, total_bytes, bytes_used;
2644         char buf[BTRFS_SUPER_INFO_SIZE];
2645         int fp = -1;
2646         int ret;
2647
2648         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2649         key.type = BTRFS_DEV_ITEM_KEY;
2650         key.offset = cur_devid;
2651
2652         btrfs_init_path(&path);
2653         ret = btrfs_search_slot(NULL, info->chunk_root, &key, &path, 0, 0); 
2654         if (ret) {
2655                 error("search key failed: %d", ret);
2656                 ret = -EIO;
2657                 goto out;
2658         }
2659
2660         leaf = path.nodes[0];
2661         dev_item = btrfs_item_ptr(leaf, path.slots[0],
2662                                   struct btrfs_dev_item);
2663
2664         devid = btrfs_device_id(leaf, dev_item);
2665         if (devid != cur_devid) {
2666                 error("devid mismatch: %llu != %llu",
2667                                 (unsigned long long)devid,
2668                                 (unsigned long long)cur_devid);
2669                 ret = -EIO;
2670                 goto out;
2671         }
2672
2673         type = btrfs_device_type(leaf, dev_item);
2674         io_align = btrfs_device_io_align(leaf, dev_item);
2675         io_width = btrfs_device_io_width(leaf, dev_item);
2676         sector_size = btrfs_device_sector_size(leaf, dev_item);
2677         total_bytes = btrfs_device_total_bytes(leaf, dev_item);
2678         bytes_used = btrfs_device_bytes_used(leaf, dev_item);
2679         read_extent_buffer(leaf, dev_uuid, (unsigned long)btrfs_device_uuid(dev_item), BTRFS_UUID_SIZE);
2680         read_extent_buffer(leaf, fs_uuid, (unsigned long)btrfs_device_fsid(dev_item), BTRFS_UUID_SIZE);
2681
2682         btrfs_release_path(&path);
2683
2684         printf("update disk super on %s devid=%llu\n", other_dev, devid);
2685
2686         /* update other devices' super block */
2687         fp = open(other_dev, O_CREAT | O_RDWR, 0600);
2688         if (fp < 0) {
2689                 error("could not open %s: %s", other_dev, strerror(errno));
2690                 ret = -EIO;
2691                 goto out;
2692         }
2693
2694         memcpy(buf, info->super_copy, BTRFS_SUPER_INFO_SIZE);
2695
2696         disk_super = (struct btrfs_super_block *)buf;
2697         dev_item = &disk_super->dev_item;
2698
2699         btrfs_set_stack_device_type(dev_item, type);
2700         btrfs_set_stack_device_id(dev_item, devid);
2701         btrfs_set_stack_device_total_bytes(dev_item, total_bytes);
2702         btrfs_set_stack_device_bytes_used(dev_item, bytes_used);
2703         btrfs_set_stack_device_io_align(dev_item, io_align);
2704         btrfs_set_stack_device_io_width(dev_item, io_width);
2705         btrfs_set_stack_device_sector_size(dev_item, sector_size);
2706         memcpy(dev_item->uuid, dev_uuid, BTRFS_UUID_SIZE);
2707         memcpy(dev_item->fsid, fs_uuid, BTRFS_UUID_SIZE);
2708         csum_block((u8 *)buf, BTRFS_SUPER_INFO_SIZE);
2709
2710         ret = pwrite64(fp, buf, BTRFS_SUPER_INFO_SIZE, BTRFS_SUPER_INFO_OFFSET);
2711         if (ret != BTRFS_SUPER_INFO_SIZE) {
2712                 if (ret < 0)
2713                         error("cannot write superblock: %s", strerror(ret));
2714                 else
2715                         error("cannot write superblock");
2716                 ret = -EIO;
2717                 goto out;
2718         }
2719
2720         write_backup_supers(fp, (u8 *)buf);
2721
2722 out:
2723         if (fp != -1)
2724                 close(fp);
2725         return ret;
2726 }
2727
2728 static void print_usage(int ret)
2729 {
2730         printf("usage: btrfs-image [options] source target\n");
2731         printf("\t-r      \trestore metadump image\n");
2732         printf("\t-c value\tcompression level (0 ~ 9)\n");
2733         printf("\t-t value\tnumber of threads (1 ~ 32)\n");
2734         printf("\t-o      \tdon't mess with the chunk tree when restoring\n");
2735         printf("\t-s      \tsanitize file names, use once to just use garbage, use twice if you want crc collisions\n");
2736         printf("\t-w      \twalk all trees instead of using extent tree, do this if your extent tree is broken\n");
2737         printf("\t-m       \trestore for multiple devices\n");
2738         printf("\n");
2739         printf("\tIn the dump mode, source is the btrfs device and target is the output file (use '-' for stdout).\n");
2740         printf("\tIn the restore mode, source is the dumped image and target is the btrfs device/file.\n");
2741         exit(ret);
2742 }
2743
2744 int main(int argc, char *argv[])
2745 {
2746         char *source;
2747         char *target;
2748         u64 num_threads = 0;
2749         u64 compress_level = 0;
2750         int create = 1;
2751         int old_restore = 0;
2752         int walk_trees = 0;
2753         int multi_devices = 0;
2754         int ret;
2755         int sanitize = 0;
2756         int dev_cnt = 0;
2757         int usage_error = 0;
2758         FILE *out;
2759
2760         while (1) {
2761                 static const struct option long_options[] = {
2762                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
2763                         { NULL, 0, NULL, 0 }
2764                 };
2765                 int c = getopt_long(argc, argv, "rc:t:oswm", long_options, NULL);
2766                 if (c < 0)
2767                         break;
2768                 switch (c) {
2769                 case 'r':
2770                         create = 0;
2771                         break;
2772                 case 't':
2773                         num_threads = arg_strtou64(optarg);
2774                         if (num_threads > 32) {
2775                                 error("number of threads out of range: %llu",
2776                                         (unsigned long long)num_threads);
2777                                 return 1;
2778                         }
2779                         break;
2780                 case 'c':
2781                         compress_level = arg_strtou64(optarg);
2782                         if (compress_level > 9) {
2783                                 error("compression level out of range: %llu",
2784                                         (unsigned long long)compress_level);
2785                                 return 1;
2786                         }
2787                         break;
2788                 case 'o':
2789                         old_restore = 1;
2790                         break;
2791                 case 's':
2792                         sanitize++;
2793                         break;
2794                 case 'w':
2795                         walk_trees = 1;
2796                         break;
2797                 case 'm':
2798                         create = 0;
2799                         multi_devices = 1;
2800                         break;
2801                         case GETOPT_VAL_HELP:
2802                 default:
2803                         print_usage(c != GETOPT_VAL_HELP);
2804                 }
2805         }
2806
2807         set_argv0(argv);
2808         if (check_argc_min(argc - optind, 2))
2809                 print_usage(1);
2810
2811         dev_cnt = argc - optind - 1;
2812
2813         if (create) {
2814                 if (old_restore) {
2815                         error(
2816                         "create and restore cannot be used at the same time");
2817                         usage_error++;
2818                 }
2819         } else {
2820                 if (walk_trees || sanitize || compress_level) {
2821                         error(
2822                         "useing -w, -s, -c options for restore makes no sense");
2823                         usage_error++;
2824                 }
2825                 if (multi_devices && dev_cnt < 2) {
2826                         error("not enough devices specified for -m option");
2827                         usage_error++;
2828                 }
2829                 if (!multi_devices && dev_cnt != 1) {
2830                         error("accepts only 1 device without -m option");
2831                         usage_error++;
2832                 }
2833         }
2834
2835         if (usage_error)
2836                 print_usage(1);
2837
2838         source = argv[optind];
2839         target = argv[optind + 1];
2840
2841         if (create && !strcmp(target, "-")) {
2842                 out = stdout;
2843         } else {
2844                 out = fopen(target, "w+");
2845                 if (!out) {
2846                         error("unable to create target file %s", target);
2847                         exit(1);
2848                 }
2849         }
2850
2851         if (compress_level > 0 || create == 0) {
2852                 if (num_threads == 0) {
2853                         long tmp = sysconf(_SC_NPROCESSORS_ONLN);
2854
2855                         if (tmp <= 0)
2856                                 tmp = 1;
2857                         num_threads = tmp;
2858                 }
2859         } else {
2860                 num_threads = 0;
2861         }
2862
2863         if (create) {
2864                 ret = check_mounted(source);
2865                 if (ret < 0) {
2866                         warning("unable to check mount status of: %s",
2867                                         strerror(-ret));
2868                 } else if (ret) {
2869                         warning("%s already mounted, results may be inaccurate",
2870                                         source);
2871                 }
2872
2873                 ret = create_metadump(source, out, num_threads,
2874                                       compress_level, sanitize, walk_trees);
2875         } else {
2876                 ret = restore_metadump(source, out, old_restore, num_threads,
2877                                        0, target, multi_devices);
2878         }
2879         if (ret) {
2880                 error("%s failed: %s", (create) ? "create" : "restore",
2881                        strerror(errno));
2882                 goto out;
2883         }
2884
2885          /* extended support for multiple devices */
2886         if (!create && multi_devices) {
2887                 struct btrfs_fs_info *info;
2888                 u64 total_devs;
2889                 int i;
2890
2891                 info = open_ctree_fs_info(target, 0, 0, 0,
2892                                           OPEN_CTREE_PARTIAL |
2893                                           OPEN_CTREE_RESTORE);
2894                 if (!info) {
2895                         error("open ctree failed at %s", target);
2896                         return 1;
2897                 }
2898
2899                 total_devs = btrfs_super_num_devices(info->super_copy);
2900                 if (total_devs != dev_cnt) {
2901                         error("it needs %llu devices but has only %d",
2902                                 total_devs, dev_cnt);
2903                         close_ctree(info->chunk_root);
2904                         goto out;
2905                 }
2906
2907                 /* update super block on other disks */
2908                 for (i = 2; i <= dev_cnt; i++) {
2909                         ret = update_disk_super_on_device(info,
2910                                         argv[optind + i], (u64)i);
2911                         if (ret) {
2912                                 error("update disk superblock failed devid %d: %d",
2913                                         i, ret);
2914                                 close_ctree(info->chunk_root);
2915                                 exit(1);
2916                         }
2917                 }
2918
2919                 close_ctree(info->chunk_root);
2920
2921                 /* fix metadata block to map correct chunk */
2922                 ret = restore_metadump(source, out, 0, num_threads, 1,
2923                                        target, 1);
2924                 if (ret) {
2925                         error("unable to fixup metadump: %d", ret);
2926                         exit(1);
2927                 }
2928         }
2929 out:
2930         if (out == stdout) {
2931                 fflush(out);
2932         } else {
2933                 fclose(out);
2934                 if (ret && create) {
2935                         int unlink_ret;
2936
2937                         unlink_ret = unlink(target);
2938                         if (unlink_ret)
2939                                 error("unlink output file %s failed: %s",
2940                                                 target, strerror(errno));
2941                 }
2942         }
2943
2944         btrfs_close_all_devices();
2945
2946         return !!ret;
2947 }