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