18ad398e1a8aea228e833b77c6eb4846a1e4753d
[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         pthread_cond_init(&md->cond, NULL);
737         pthread_mutex_init(&md->mutex, NULL);
738         INIT_LIST_HEAD(&md->list);
739         INIT_LIST_HEAD(&md->ordered);
740         md->root = root;
741         md->out = out;
742         md->pending_start = (u64)-1;
743         md->compress_level = compress_level;
744         md->cluster = calloc(1, BLOCK_SIZE);
745         md->sanitize_names = sanitize_names;
746         if (sanitize_names > 1)
747                 crc32c_optimization_init();
748
749         if (!md->cluster) {
750                 pthread_cond_destroy(&md->cond);
751                 pthread_mutex_destroy(&md->mutex);
752                 return -ENOMEM;
753         }
754
755         meta_cluster_init(md, 0);
756         if (!num_threads)
757                 return 0;
758
759         md->name_tree.rb_node = NULL;
760         md->num_threads = num_threads;
761         md->threads = calloc(num_threads, sizeof(pthread_t));
762         if (!md->threads) {
763                 free(md->cluster);
764                 pthread_cond_destroy(&md->cond);
765                 pthread_mutex_destroy(&md->mutex);
766                 return -ENOMEM;
767         }
768
769         for (i = 0; i < num_threads; i++) {
770                 ret = pthread_create(md->threads + i, NULL, dump_worker, md);
771                 if (ret)
772                         break;
773         }
774
775         if (ret)
776                 metadump_destroy(md, i + 1);
777
778         return ret;
779 }
780
781 static int write_zero(FILE *out, size_t size)
782 {
783         static char zero[BLOCK_SIZE];
784         return fwrite(zero, size, 1, out);
785 }
786
787 static int write_buffers(struct metadump_struct *md, u64 *next)
788 {
789         struct meta_cluster_header *header = &md->cluster->header;
790         struct meta_cluster_item *item;
791         struct async_work *async;
792         u64 bytenr = 0;
793         u32 nritems = 0;
794         int ret;
795         int err = 0;
796
797         if (list_empty(&md->ordered))
798                 goto out;
799
800         /* wait until all buffers are compressed */
801         while (!err && md->num_items > md->num_ready) {
802                 struct timespec ts = {
803                         .tv_sec = 0,
804                         .tv_nsec = 10000000,
805                 };
806                 pthread_mutex_unlock(&md->mutex);
807                 nanosleep(&ts, NULL);
808                 pthread_mutex_lock(&md->mutex);
809                 err = md->error;
810         }
811
812         if (err) {
813                 fprintf(stderr, "One of the threads errored out %s\n",
814                                 strerror(err));
815                 goto out;
816         }
817
818         /* setup and write index block */
819         list_for_each_entry(async, &md->ordered, ordered) {
820                 item = md->cluster->items + nritems;
821                 item->bytenr = cpu_to_le64(async->start);
822                 item->size = cpu_to_le32(async->bufsize);
823                 nritems++;
824         }
825         header->nritems = cpu_to_le32(nritems);
826
827         ret = fwrite(md->cluster, BLOCK_SIZE, 1, md->out);
828         if (ret != 1) {
829                 fprintf(stderr, "Error writing out cluster: %d\n", errno);
830                 return -EIO;
831         }
832
833         /* write buffers */
834         bytenr += le64_to_cpu(header->bytenr) + BLOCK_SIZE;
835         while (!list_empty(&md->ordered)) {
836                 async = list_entry(md->ordered.next, struct async_work,
837                                    ordered);
838                 list_del_init(&async->ordered);
839
840                 bytenr += async->bufsize;
841                 if (!err)
842                         ret = fwrite(async->buffer, async->bufsize, 1,
843                                      md->out);
844                 if (ret != 1) {
845                         err = -EIO;
846                         ret = 0;
847                         fprintf(stderr, "Error writing out cluster: %d\n",
848                                 errno);
849                 }
850
851                 free(async->buffer);
852                 free(async);
853         }
854
855         /* zero unused space in the last block */
856         if (!err && bytenr & BLOCK_MASK) {
857                 size_t size = BLOCK_SIZE - (bytenr & BLOCK_MASK);
858
859                 bytenr += size;
860                 ret = write_zero(md->out, size);
861                 if (ret != 1) {
862                         fprintf(stderr, "Error zeroing out buffer: %d\n",
863                                 errno);
864                         err = -EIO;
865                 }
866         }
867 out:
868         *next = bytenr;
869         return err;
870 }
871
872 static int read_data_extent(struct metadump_struct *md,
873                             struct async_work *async)
874 {
875         struct btrfs_root *root = md->root;
876         u64 bytes_left = async->size;
877         u64 logical = async->start;
878         u64 offset = 0;
879         u64 read_len;
880         int num_copies;
881         int cur_mirror;
882         int ret;
883
884         num_copies = btrfs_num_copies(&root->fs_info->mapping_tree, logical,
885                                       bytes_left);
886
887         /* Try our best to read data, just like read_tree_block() */
888         for (cur_mirror = 0; cur_mirror < num_copies; cur_mirror++) {
889                 while (bytes_left) {
890                         read_len = bytes_left;
891                         ret = read_extent_data(root,
892                                         (char *)(async->buffer + offset),
893                                         logical, &read_len, cur_mirror);
894                         if (ret < 0)
895                                 break;
896                         offset += read_len;
897                         logical += read_len;
898                         bytes_left -= read_len;
899                 }
900         }
901         if (bytes_left)
902                 return -EIO;
903         return 0;
904 }
905
906 static int get_dev_fd(struct btrfs_root *root)
907 {
908         struct btrfs_device *dev;
909
910         dev = list_first_entry(&root->fs_info->fs_devices->devices,
911                                struct btrfs_device, dev_list);
912         return dev->fd;
913 }
914
915 static int flush_pending(struct metadump_struct *md, int done)
916 {
917         struct async_work *async = NULL;
918         struct extent_buffer *eb;
919         u64 blocksize = md->root->nodesize;
920         u64 start;
921         u64 size;
922         size_t offset;
923         int ret = 0;
924
925         if (md->pending_size) {
926                 async = calloc(1, sizeof(*async));
927                 if (!async)
928                         return -ENOMEM;
929
930                 async->start = md->pending_start;
931                 async->size = md->pending_size;
932                 async->bufsize = async->size;
933                 async->buffer = malloc(async->bufsize);
934                 if (!async->buffer) {
935                         free(async);
936                         return -ENOMEM;
937                 }
938                 offset = 0;
939                 start = async->start;
940                 size = async->size;
941
942                 if (md->data) {
943                         ret = read_data_extent(md, async);
944                         if (ret) {
945                                 free(async->buffer);
946                                 free(async);
947                                 return ret;
948                         }
949                 }
950
951                 /*
952                  * Balance can make the mapping not cover the super block, so
953                  * just copy directly from one of the devices.
954                  */
955                 if (start == BTRFS_SUPER_INFO_OFFSET) {
956                         int fd = get_dev_fd(md->root);
957
958                         ret = pread64(fd, async->buffer, size, start);
959                         if (ret < size) {
960                                 free(async->buffer);
961                                 free(async);
962                                 fprintf(stderr, "Error reading superblock\n");
963                                 return -EIO;
964                         }
965                         size = 0;
966                         ret = 0;
967                 }
968
969                 while (!md->data && size > 0) {
970                         u64 this_read = min(blocksize, size);
971                         eb = read_tree_block(md->root, start, this_read, 0);
972                         if (!extent_buffer_uptodate(eb)) {
973                                 free(async->buffer);
974                                 free(async);
975                                 fprintf(stderr,
976                                         "Error reading metadata block\n");
977                                 return -EIO;
978                         }
979                         copy_buffer(md, async->buffer + offset, eb);
980                         free_extent_buffer(eb);
981                         start += this_read;
982                         offset += this_read;
983                         size -= this_read;
984                 }
985
986                 md->pending_start = (u64)-1;
987                 md->pending_size = 0;
988         } else if (!done) {
989                 return 0;
990         }
991
992         pthread_mutex_lock(&md->mutex);
993         if (async) {
994                 list_add_tail(&async->ordered, &md->ordered);
995                 md->num_items++;
996                 if (md->compress_level > 0) {
997                         list_add_tail(&async->list, &md->list);
998                         pthread_cond_signal(&md->cond);
999                 } else {
1000                         md->num_ready++;
1001                 }
1002         }
1003         if (md->num_items >= ITEMS_PER_CLUSTER || done) {
1004                 ret = write_buffers(md, &start);
1005                 if (ret)
1006                         fprintf(stderr, "Error writing buffers %d\n",
1007                                 errno);
1008                 else
1009                         meta_cluster_init(md, start);
1010         }
1011         pthread_mutex_unlock(&md->mutex);
1012         return ret;
1013 }
1014
1015 static int add_extent(u64 start, u64 size, struct metadump_struct *md,
1016                       int data)
1017 {
1018         int ret;
1019         if (md->data != data ||
1020             md->pending_size + size > MAX_PENDING_SIZE ||
1021             md->pending_start + md->pending_size != start) {
1022                 ret = flush_pending(md, 0);
1023                 if (ret)
1024                         return ret;
1025                 md->pending_start = start;
1026         }
1027         readahead_tree_block(md->root, start, size, 0);
1028         md->pending_size += size;
1029         md->data = data;
1030         return 0;
1031 }
1032
1033 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1034 static int is_tree_block(struct btrfs_root *extent_root,
1035                          struct btrfs_path *path, u64 bytenr)
1036 {
1037         struct extent_buffer *leaf;
1038         struct btrfs_key key;
1039         u64 ref_objectid;
1040         int ret;
1041
1042         leaf = path->nodes[0];
1043         while (1) {
1044                 struct btrfs_extent_ref_v0 *ref_item;
1045                 path->slots[0]++;
1046                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1047                         ret = btrfs_next_leaf(extent_root, path);
1048                         if (ret < 0)
1049                                 return ret;
1050                         if (ret > 0)
1051                                 break;
1052                         leaf = path->nodes[0];
1053                 }
1054                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1055                 if (key.objectid != bytenr)
1056                         break;
1057                 if (key.type != BTRFS_EXTENT_REF_V0_KEY)
1058                         continue;
1059                 ref_item = btrfs_item_ptr(leaf, path->slots[0],
1060                                           struct btrfs_extent_ref_v0);
1061                 ref_objectid = btrfs_ref_objectid_v0(leaf, ref_item);
1062                 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID)
1063                         return 1;
1064                 break;
1065         }
1066         return 0;
1067 }
1068 #endif
1069
1070 static int copy_tree_blocks(struct btrfs_root *root, struct extent_buffer *eb,
1071                             struct metadump_struct *metadump, int root_tree)
1072 {
1073         struct extent_buffer *tmp;
1074         struct btrfs_root_item *ri;
1075         struct btrfs_key key;
1076         u64 bytenr;
1077         int level;
1078         int nritems = 0;
1079         int i = 0;
1080         int ret;
1081
1082         ret = add_extent(btrfs_header_bytenr(eb), root->leafsize, metadump, 0);
1083         if (ret) {
1084                 fprintf(stderr, "Error adding metadata block\n");
1085                 return ret;
1086         }
1087
1088         if (btrfs_header_level(eb) == 0 && !root_tree)
1089                 return 0;
1090
1091         level = btrfs_header_level(eb);
1092         nritems = btrfs_header_nritems(eb);
1093         for (i = 0; i < nritems; i++) {
1094                 if (level == 0) {
1095                         btrfs_item_key_to_cpu(eb, &key, i);
1096                         if (key.type != BTRFS_ROOT_ITEM_KEY)
1097                                 continue;
1098                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
1099                         bytenr = btrfs_disk_root_bytenr(eb, ri);
1100                         tmp = read_tree_block(root, bytenr, root->leafsize, 0);
1101                         if (!extent_buffer_uptodate(tmp)) {
1102                                 fprintf(stderr,
1103                                         "Error reading log root block\n");
1104                                 return -EIO;
1105                         }
1106                         ret = copy_tree_blocks(root, tmp, metadump, 0);
1107                         free_extent_buffer(tmp);
1108                         if (ret)
1109                                 return ret;
1110                 } else {
1111                         bytenr = btrfs_node_blockptr(eb, i);
1112                         tmp = read_tree_block(root, bytenr, root->leafsize, 0);
1113                         if (!extent_buffer_uptodate(tmp)) {
1114                                 fprintf(stderr, "Error reading log block\n");
1115                                 return -EIO;
1116                         }
1117                         ret = copy_tree_blocks(root, tmp, metadump, root_tree);
1118                         free_extent_buffer(tmp);
1119                         if (ret)
1120                                 return ret;
1121                 }
1122         }
1123
1124         return 0;
1125 }
1126
1127 static int copy_log_trees(struct btrfs_root *root,
1128                           struct metadump_struct *metadump,
1129                           struct btrfs_path *path)
1130 {
1131         u64 blocknr = btrfs_super_log_root(root->fs_info->super_copy);
1132
1133         if (blocknr == 0)
1134                 return 0;
1135
1136         if (!root->fs_info->log_root_tree ||
1137             !root->fs_info->log_root_tree->node) {
1138                 fprintf(stderr, "Error copying tree log, it wasn't setup\n");
1139                 return -EIO;
1140         }
1141
1142         return copy_tree_blocks(root, root->fs_info->log_root_tree->node,
1143                                 metadump, 1);
1144 }
1145
1146 static int copy_space_cache(struct btrfs_root *root,
1147                             struct metadump_struct *metadump,
1148                             struct btrfs_path *path)
1149 {
1150         struct extent_buffer *leaf;
1151         struct btrfs_file_extent_item *fi;
1152         struct btrfs_key key;
1153         u64 bytenr, num_bytes;
1154         int ret;
1155
1156         root = root->fs_info->tree_root;
1157
1158         key.objectid = 0;
1159         key.type = BTRFS_EXTENT_DATA_KEY;
1160         key.offset = 0;
1161
1162         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1163         if (ret < 0) {
1164                 fprintf(stderr, "Error searching for free space inode %d\n",
1165                         ret);
1166                 return ret;
1167         }
1168
1169         leaf = path->nodes[0];
1170
1171         while (1) {
1172                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1173                         ret = btrfs_next_leaf(root, path);
1174                         if (ret < 0) {
1175                                 fprintf(stderr, "Error going to next leaf "
1176                                         "%d\n", ret);
1177                                 return ret;
1178                         }
1179                         if (ret > 0)
1180                                 break;
1181                         leaf = path->nodes[0];
1182                 }
1183
1184                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1185                 if (key.type != BTRFS_EXTENT_DATA_KEY) {
1186                         path->slots[0]++;
1187                         continue;
1188                 }
1189
1190                 fi = btrfs_item_ptr(leaf, path->slots[0],
1191                                     struct btrfs_file_extent_item);
1192                 if (btrfs_file_extent_type(leaf, fi) !=
1193                     BTRFS_FILE_EXTENT_REG) {
1194                         path->slots[0]++;
1195                         continue;
1196                 }
1197
1198                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1199                 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1200                 ret = add_extent(bytenr, num_bytes, metadump, 1);
1201                 if (ret) {
1202                         fprintf(stderr, "Error adding space cache blocks %d\n",
1203                                 ret);
1204                         btrfs_release_path(path);
1205                         return ret;
1206                 }
1207                 path->slots[0]++;
1208         }
1209
1210         return 0;
1211 }
1212
1213 static int copy_from_extent_tree(struct metadump_struct *metadump,
1214                                  struct btrfs_path *path)
1215 {
1216         struct btrfs_root *extent_root;
1217         struct extent_buffer *leaf;
1218         struct btrfs_extent_item *ei;
1219         struct btrfs_key key;
1220         u64 bytenr;
1221         u64 num_bytes;
1222         int ret;
1223
1224         extent_root = metadump->root->fs_info->extent_root;
1225         bytenr = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
1226         key.objectid = bytenr;
1227         key.type = BTRFS_EXTENT_ITEM_KEY;
1228         key.offset = 0;
1229
1230         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
1231         if (ret < 0) {
1232                 fprintf(stderr, "Error searching extent root %d\n", ret);
1233                 return ret;
1234         }
1235         ret = 0;
1236
1237         leaf = path->nodes[0];
1238
1239         while (1) {
1240                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1241                         ret = btrfs_next_leaf(extent_root, path);
1242                         if (ret < 0) {
1243                                 fprintf(stderr, "Error going to next leaf %d"
1244                                         "\n", ret);
1245                                 break;
1246                         }
1247                         if (ret > 0) {
1248                                 ret = 0;
1249                                 break;
1250                         }
1251                         leaf = path->nodes[0];
1252                 }
1253
1254                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1255                 if (key.objectid < bytenr ||
1256                     (key.type != BTRFS_EXTENT_ITEM_KEY &&
1257                      key.type != BTRFS_METADATA_ITEM_KEY)) {
1258                         path->slots[0]++;
1259                         continue;
1260                 }
1261
1262                 bytenr = key.objectid;
1263                 if (key.type == BTRFS_METADATA_ITEM_KEY)
1264                         num_bytes = extent_root->leafsize;
1265                 else
1266                         num_bytes = key.offset;
1267
1268                 if (btrfs_item_size_nr(leaf, path->slots[0]) > sizeof(*ei)) {
1269                         ei = btrfs_item_ptr(leaf, path->slots[0],
1270                                             struct btrfs_extent_item);
1271                         if (btrfs_extent_flags(leaf, ei) &
1272                             BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1273                                 ret = add_extent(bytenr, num_bytes, metadump,
1274                                                  0);
1275                                 if (ret) {
1276                                         fprintf(stderr, "Error adding block "
1277                                                 "%d\n", ret);
1278                                         break;
1279                                 }
1280                         }
1281                 } else {
1282 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1283                         ret = is_tree_block(extent_root, path, bytenr);
1284                         if (ret < 0) {
1285                                 fprintf(stderr, "Error checking tree block "
1286                                         "%d\n", ret);
1287                                 break;
1288                         }
1289
1290                         if (ret) {
1291                                 ret = add_extent(bytenr, num_bytes, metadump,
1292                                                  0);
1293                                 if (ret) {
1294                                         fprintf(stderr, "Error adding block "
1295                                                 "%d\n", ret);
1296                                         break;
1297                                 }
1298                         }
1299                         ret = 0;
1300 #else
1301                         fprintf(stderr, "Either extent tree corruption or "
1302                                 "you haven't built with V0 support\n");
1303                         ret = -EIO;
1304                         break;
1305 #endif
1306                 }
1307                 bytenr += num_bytes;
1308         }
1309
1310         btrfs_release_path(path);
1311
1312         return ret;
1313 }
1314
1315 static int create_metadump(const char *input, FILE *out, int num_threads,
1316                            int compress_level, int sanitize, int walk_trees)
1317 {
1318         struct btrfs_root *root;
1319         struct btrfs_path *path = NULL;
1320         struct metadump_struct metadump;
1321         int ret;
1322         int err = 0;
1323
1324         root = open_ctree(input, 0, 0);
1325         if (!root) {
1326                 fprintf(stderr, "Open ctree failed\n");
1327                 return -EIO;
1328         }
1329
1330         BUG_ON(root->nodesize != root->leafsize);
1331
1332         ret = metadump_init(&metadump, root, out, num_threads,
1333                             compress_level, sanitize);
1334         if (ret) {
1335                 fprintf(stderr, "Error initing metadump %d\n", ret);
1336                 close_ctree(root);
1337                 return ret;
1338         }
1339
1340         ret = add_extent(BTRFS_SUPER_INFO_OFFSET, BTRFS_SUPER_INFO_SIZE,
1341                         &metadump, 0);
1342         if (ret) {
1343                 fprintf(stderr, "Error adding metadata %d\n", ret);
1344                 err = ret;
1345                 goto out;
1346         }
1347
1348         path = btrfs_alloc_path();
1349         if (!path) {
1350                 fprintf(stderr, "Out of memory allocing path\n");
1351                 err = -ENOMEM;
1352                 goto out;
1353         }
1354
1355         if (walk_trees) {
1356                 ret = copy_tree_blocks(root, root->fs_info->chunk_root->node,
1357                                        &metadump, 1);
1358                 if (ret) {
1359                         err = ret;
1360                         goto out;
1361                 }
1362
1363                 ret = copy_tree_blocks(root, root->fs_info->tree_root->node,
1364                                        &metadump, 1);
1365                 if (ret) {
1366                         err = ret;
1367                         goto out;
1368                 }
1369         } else {
1370                 ret = copy_from_extent_tree(&metadump, path);
1371                 if (ret) {
1372                         err = ret;
1373                         goto out;
1374                 }
1375         }
1376
1377         ret = copy_log_trees(root, &metadump, path);
1378         if (ret) {
1379                 err = ret;
1380                 goto out;
1381         }
1382
1383         ret = copy_space_cache(root, &metadump, path);
1384 out:
1385         ret = flush_pending(&metadump, 1);
1386         if (ret) {
1387                 if (!err)
1388                         err = ret;
1389                 fprintf(stderr, "Error flushing pending %d\n", ret);
1390         }
1391
1392         metadump_destroy(&metadump, num_threads);
1393
1394         btrfs_free_path(path);
1395         ret = close_ctree(root);
1396         return err ? err : ret;
1397 }
1398
1399 static void update_super_old(u8 *buffer)
1400 {
1401         struct btrfs_super_block *super = (struct btrfs_super_block *)buffer;
1402         struct btrfs_chunk *chunk;
1403         struct btrfs_disk_key *key;
1404         u32 sectorsize = btrfs_super_sectorsize(super);
1405         u64 flags = btrfs_super_flags(super);
1406
1407         flags |= BTRFS_SUPER_FLAG_METADUMP;
1408         btrfs_set_super_flags(super, flags);
1409
1410         key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1411         chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1412                                        sizeof(struct btrfs_disk_key));
1413
1414         btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1415         btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1416         btrfs_set_disk_key_offset(key, 0);
1417
1418         btrfs_set_stack_chunk_length(chunk, (u64)-1);
1419         btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1420         btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1421         btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1422         btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1423         btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1424         btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1425         btrfs_set_stack_chunk_num_stripes(chunk, 1);
1426         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1427         chunk->stripe.devid = super->dev_item.devid;
1428         btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1429         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1430         btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1431         csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
1432 }
1433
1434 static int update_super(struct mdrestore_struct *mdres, u8 *buffer)
1435 {
1436         struct btrfs_super_block *super = (struct btrfs_super_block *)buffer;
1437         struct btrfs_chunk *chunk;
1438         struct btrfs_disk_key *disk_key;
1439         struct btrfs_key key;
1440         u64 flags = btrfs_super_flags(super);
1441         u32 new_array_size = 0;
1442         u32 array_size;
1443         u32 cur = 0;
1444         u8 *ptr, *write_ptr;
1445         int old_num_stripes;
1446
1447         write_ptr = ptr = super->sys_chunk_array;
1448         array_size = btrfs_super_sys_array_size(super);
1449
1450         while (cur < array_size) {
1451                 disk_key = (struct btrfs_disk_key *)ptr;
1452                 btrfs_disk_key_to_cpu(&key, disk_key);
1453
1454                 new_array_size += sizeof(*disk_key);
1455                 memmove(write_ptr, ptr, sizeof(*disk_key));
1456
1457                 write_ptr += sizeof(*disk_key);
1458                 ptr += sizeof(*disk_key);
1459                 cur += sizeof(*disk_key);
1460
1461                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1462                         u64 physical, size = 0;
1463
1464                         chunk = (struct btrfs_chunk *)ptr;
1465                         old_num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1466                         chunk = (struct btrfs_chunk *)write_ptr;
1467
1468                         memmove(write_ptr, ptr, sizeof(*chunk));
1469                         btrfs_set_stack_chunk_num_stripes(chunk, 1);
1470                         btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1471                         btrfs_set_stack_chunk_type(chunk,
1472                                                    BTRFS_BLOCK_GROUP_SYSTEM);
1473                         btrfs_set_stack_stripe_devid(&chunk->stripe,
1474                                                      super->dev_item.devid);
1475                         physical = logical_to_physical(mdres, key.offset,
1476                                                        &size);
1477                         if (size != (u64)-1)
1478                                 btrfs_set_stack_stripe_offset(&chunk->stripe,
1479                                                               physical);
1480                         memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid,
1481                                BTRFS_UUID_SIZE);
1482                         new_array_size += sizeof(*chunk);
1483                 } else {
1484                         fprintf(stderr, "Bogus key in the sys chunk array "
1485                                 "%d\n", key.type);
1486                         return -EIO;
1487                 }
1488                 write_ptr += sizeof(*chunk);
1489                 ptr += btrfs_chunk_item_size(old_num_stripes);
1490                 cur += btrfs_chunk_item_size(old_num_stripes);
1491         }
1492
1493         if (mdres->clear_space_cache)
1494                 btrfs_set_super_cache_generation(super, 0);
1495
1496         flags |= BTRFS_SUPER_FLAG_METADUMP_V2;
1497         btrfs_set_super_flags(super, flags);
1498         btrfs_set_super_sys_array_size(super, new_array_size);
1499         csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
1500
1501         return 0;
1502 }
1503
1504 static struct extent_buffer *alloc_dummy_eb(u64 bytenr, u32 size)
1505 {
1506         struct extent_buffer *eb;
1507
1508         eb = malloc(sizeof(struct extent_buffer) + size);
1509         if (!eb)
1510                 return NULL;
1511         memset(eb, 0, sizeof(struct extent_buffer) + size);
1512
1513         eb->start = bytenr;
1514         eb->len = size;
1515         return eb;
1516 }
1517
1518 static void truncate_item(struct extent_buffer *eb, int slot, u32 new_size)
1519 {
1520         struct btrfs_item *item;
1521         u32 nritems;
1522         u32 old_size;
1523         u32 old_data_start;
1524         u32 size_diff;
1525         u32 data_end;
1526         int i;
1527
1528         old_size = btrfs_item_size_nr(eb, slot);
1529         if (old_size == new_size)
1530                 return;
1531
1532         nritems = btrfs_header_nritems(eb);
1533         data_end = btrfs_item_offset_nr(eb, nritems - 1);
1534
1535         old_data_start = btrfs_item_offset_nr(eb, slot);
1536         size_diff = old_size - new_size;
1537
1538         for (i = slot; i < nritems; i++) {
1539                 u32 ioff;
1540                 item = btrfs_item_nr(i);
1541                 ioff = btrfs_item_offset(eb, item);
1542                 btrfs_set_item_offset(eb, item, ioff + size_diff);
1543         }
1544
1545         memmove_extent_buffer(eb, btrfs_leaf_data(eb) + data_end + size_diff,
1546                               btrfs_leaf_data(eb) + data_end,
1547                               old_data_start + new_size - data_end);
1548         item = btrfs_item_nr(slot);
1549         btrfs_set_item_size(eb, item, new_size);
1550 }
1551
1552 static int fixup_chunk_tree_block(struct mdrestore_struct *mdres,
1553                                   struct async_work *async, u8 *buffer,
1554                                   size_t size)
1555 {
1556         struct extent_buffer *eb;
1557         size_t size_left = size;
1558         u64 bytenr = async->start;
1559         int i;
1560
1561         if (size_left % mdres->leafsize)
1562                 return 0;
1563
1564         eb = alloc_dummy_eb(bytenr, mdres->leafsize);
1565         if (!eb)
1566                 return -ENOMEM;
1567
1568         while (size_left) {
1569                 eb->start = bytenr;
1570                 memcpy(eb->data, buffer, mdres->leafsize);
1571
1572                 if (btrfs_header_bytenr(eb) != bytenr)
1573                         break;
1574                 if (memcmp(mdres->fsid,
1575                            eb->data + offsetof(struct btrfs_header, fsid),
1576                            BTRFS_FSID_SIZE))
1577                         break;
1578
1579                 if (btrfs_header_owner(eb) != BTRFS_CHUNK_TREE_OBJECTID)
1580                         goto next;
1581
1582                 if (btrfs_header_level(eb) != 0)
1583                         goto next;
1584
1585                 for (i = 0; i < btrfs_header_nritems(eb); i++) {
1586                         struct btrfs_chunk chunk;
1587                         struct btrfs_key key;
1588                         u64 type, physical, size = (u64)-1;
1589
1590                         btrfs_item_key_to_cpu(eb, &key, i);
1591                         if (key.type != BTRFS_CHUNK_ITEM_KEY)
1592                                 continue;
1593                         truncate_item(eb, i, sizeof(chunk));
1594                         read_extent_buffer(eb, &chunk,
1595                                            btrfs_item_ptr_offset(eb, i),
1596                                            sizeof(chunk));
1597
1598                         size = 0;
1599                         physical = logical_to_physical(mdres, key.offset,
1600                                                        &size);
1601
1602                         /* Zero out the RAID profile */
1603                         type = btrfs_stack_chunk_type(&chunk);
1604                         type &= (BTRFS_BLOCK_GROUP_DATA |
1605                                  BTRFS_BLOCK_GROUP_SYSTEM |
1606                                  BTRFS_BLOCK_GROUP_METADATA |
1607                                  BTRFS_BLOCK_GROUP_DUP);
1608                         btrfs_set_stack_chunk_type(&chunk, type);
1609
1610                         btrfs_set_stack_chunk_num_stripes(&chunk, 1);
1611                         btrfs_set_stack_chunk_sub_stripes(&chunk, 0);
1612                         btrfs_set_stack_stripe_devid(&chunk.stripe, mdres->devid);
1613                         if (size != (u64)-1)
1614                                 btrfs_set_stack_stripe_offset(&chunk.stripe,
1615                                                               physical);
1616                         memcpy(chunk.stripe.dev_uuid, mdres->uuid,
1617                                BTRFS_UUID_SIZE);
1618                         write_extent_buffer(eb, &chunk,
1619                                             btrfs_item_ptr_offset(eb, i),
1620                                             sizeof(chunk));
1621                 }
1622                 memcpy(buffer, eb->data, eb->len);
1623                 csum_block(buffer, eb->len);
1624 next:
1625                 size_left -= mdres->leafsize;
1626                 buffer += mdres->leafsize;
1627                 bytenr += mdres->leafsize;
1628         }
1629
1630         free(eb);
1631         return 0;
1632 }
1633
1634 static void write_backup_supers(int fd, u8 *buf)
1635 {
1636         struct btrfs_super_block *super = (struct btrfs_super_block *)buf;
1637         struct stat st;
1638         u64 size;
1639         u64 bytenr;
1640         int i;
1641         int ret;
1642
1643         if (fstat(fd, &st)) {
1644                 fprintf(stderr, "Couldn't stat restore point, won't be able "
1645                         "to write backup supers: %d\n", errno);
1646                 return;
1647         }
1648
1649         size = btrfs_device_size(fd, &st);
1650
1651         for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1652                 bytenr = btrfs_sb_offset(i);
1653                 if (bytenr + BTRFS_SUPER_INFO_SIZE > size)
1654                         break;
1655                 btrfs_set_super_bytenr(super, bytenr);
1656                 csum_block(buf, BTRFS_SUPER_INFO_SIZE);
1657                 ret = pwrite64(fd, buf, BTRFS_SUPER_INFO_SIZE, bytenr);
1658                 if (ret < BTRFS_SUPER_INFO_SIZE) {
1659                         if (ret < 0)
1660                                 fprintf(stderr, "Problem writing out backup "
1661                                         "super block %d, err %d\n", i, errno);
1662                         else
1663                                 fprintf(stderr, "Short write writing out "
1664                                         "backup super block\n");
1665                         break;
1666                 }
1667         }
1668 }
1669
1670 static void *restore_worker(void *data)
1671 {
1672         struct mdrestore_struct *mdres = (struct mdrestore_struct *)data;
1673         struct async_work *async;
1674         size_t size;
1675         u8 *buffer;
1676         u8 *outbuf;
1677         int outfd;
1678         int ret;
1679         int compress_size = MAX_PENDING_SIZE * 4;
1680
1681         outfd = fileno(mdres->out);
1682         buffer = malloc(compress_size);
1683         if (!buffer) {
1684                 fprintf(stderr, "Error allocing buffer\n");
1685                 pthread_mutex_lock(&mdres->mutex);
1686                 if (!mdres->error)
1687                         mdres->error = -ENOMEM;
1688                 pthread_mutex_unlock(&mdres->mutex);
1689                 pthread_exit(NULL);
1690         }
1691
1692         while (1) {
1693                 u64 bytenr;
1694                 off_t offset = 0;
1695                 int err = 0;
1696
1697                 pthread_mutex_lock(&mdres->mutex);
1698                 while (!mdres->leafsize || list_empty(&mdres->list)) {
1699                         if (mdres->done) {
1700                                 pthread_mutex_unlock(&mdres->mutex);
1701                                 goto out;
1702                         }
1703                         pthread_cond_wait(&mdres->cond, &mdres->mutex);
1704                 }
1705                 async = list_entry(mdres->list.next, struct async_work, list);
1706                 list_del_init(&async->list);
1707                 pthread_mutex_unlock(&mdres->mutex);
1708
1709                 if (mdres->compress_method == COMPRESS_ZLIB) {
1710                         size = compress_size; 
1711                         ret = uncompress(buffer, (unsigned long *)&size,
1712                                          async->buffer, async->bufsize);
1713                         if (ret != Z_OK) {
1714                                 fprintf(stderr, "Error decompressing %d\n",
1715                                         ret);
1716                                 err = -EIO;
1717                         }
1718                         outbuf = buffer;
1719                 } else {
1720                         outbuf = async->buffer;
1721                         size = async->bufsize;
1722                 }
1723
1724                 if (!mdres->multi_devices) {
1725                         if (async->start == BTRFS_SUPER_INFO_OFFSET) {
1726                                 if (mdres->old_restore) {
1727                                         update_super_old(outbuf);
1728                                 } else {
1729                                         ret = update_super(mdres, outbuf);
1730                                         if (ret)
1731                                                 err = ret;
1732                                 }
1733                         } else if (!mdres->old_restore) {
1734                                 ret = fixup_chunk_tree_block(mdres, async, outbuf, size);
1735                                 if (ret)
1736                                         err = ret;
1737                         }
1738                 }
1739
1740                 if (!mdres->fixup_offset) {
1741                         while (size) {
1742                                 u64 chunk_size = size;
1743                                 if (!mdres->multi_devices && !mdres->old_restore)
1744                                         bytenr = logical_to_physical(mdres,
1745                                                                      async->start + offset,
1746                                                                      &chunk_size);
1747                                 else
1748                                         bytenr = async->start + offset;
1749
1750                                 ret = pwrite64(outfd, outbuf+offset, chunk_size,
1751                                                bytenr);
1752                                 if (ret != chunk_size) {
1753                                         if (ret < 0) {
1754                                                 fprintf(stderr, "Error writing to "
1755                                                         "device %d\n", errno);
1756                                                 err = errno;
1757                                                 break;
1758                                         } else {
1759                                                 fprintf(stderr, "Short write\n");
1760                                                 err = -EIO;
1761                                                 break;
1762                                         }
1763                                 }
1764                                 size -= chunk_size;
1765                                 offset += chunk_size;
1766                         }
1767                 } else if (async->start != BTRFS_SUPER_INFO_OFFSET) {
1768                         ret = write_data_to_disk(mdres->info, outbuf, async->start, size, 0);
1769                         if (ret) {
1770                                 printk("Error write data\n");
1771                                 exit(1);
1772                         }
1773                 }
1774
1775
1776                 /* backup super blocks are already there at fixup_offset stage */
1777                 if (!mdres->multi_devices && async->start == BTRFS_SUPER_INFO_OFFSET)
1778                         write_backup_supers(outfd, outbuf);
1779
1780                 pthread_mutex_lock(&mdres->mutex);
1781                 if (err && !mdres->error)
1782                         mdres->error = err;
1783                 mdres->num_items--;
1784                 pthread_mutex_unlock(&mdres->mutex);
1785
1786                 free(async->buffer);
1787                 free(async);
1788         }
1789 out:
1790         free(buffer);
1791         pthread_exit(NULL);
1792 }
1793
1794 static void mdrestore_destroy(struct mdrestore_struct *mdres, int num_threads)
1795 {
1796         struct rb_node *n;
1797         int i;
1798
1799         while ((n = rb_first(&mdres->chunk_tree))) {
1800                 struct fs_chunk *entry;
1801
1802                 entry = rb_entry(n, struct fs_chunk, l);
1803                 rb_erase(n, &mdres->chunk_tree);
1804                 rb_erase(&entry->p, &mdres->physical_tree);
1805                 free(entry);
1806         }
1807         pthread_mutex_lock(&mdres->mutex);
1808         mdres->done = 1;
1809         pthread_cond_broadcast(&mdres->cond);
1810         pthread_mutex_unlock(&mdres->mutex);
1811
1812         for (i = 0; i < num_threads; i++)
1813                 pthread_join(mdres->threads[i], NULL);
1814
1815         pthread_cond_destroy(&mdres->cond);
1816         pthread_mutex_destroy(&mdres->mutex);
1817         free(mdres->threads);
1818 }
1819
1820 static int mdrestore_init(struct mdrestore_struct *mdres,
1821                           FILE *in, FILE *out, int old_restore,
1822                           int num_threads, int fixup_offset,
1823                           struct btrfs_fs_info *info, int multi_devices)
1824 {
1825         int i, ret = 0;
1826
1827         memset(mdres, 0, sizeof(*mdres));
1828         pthread_cond_init(&mdres->cond, NULL);
1829         pthread_mutex_init(&mdres->mutex, NULL);
1830         INIT_LIST_HEAD(&mdres->list);
1831         INIT_LIST_HEAD(&mdres->overlapping_chunks);
1832         mdres->in = in;
1833         mdres->out = out;
1834         mdres->old_restore = old_restore;
1835         mdres->chunk_tree.rb_node = NULL;
1836         mdres->fixup_offset = fixup_offset;
1837         mdres->info = info;
1838         mdres->multi_devices = multi_devices;
1839         mdres->clear_space_cache = 0;
1840         mdres->last_physical_offset = 0;
1841         mdres->alloced_chunks = 0;
1842
1843         if (!num_threads)
1844                 return 0;
1845
1846         mdres->num_threads = num_threads;
1847         mdres->threads = calloc(num_threads, sizeof(pthread_t));
1848         if (!mdres->threads)
1849                 return -ENOMEM;
1850         for (i = 0; i < num_threads; i++) {
1851                 ret = pthread_create(mdres->threads + i, NULL, restore_worker,
1852                                      mdres);
1853                 if (ret)
1854                         break;
1855         }
1856         if (ret)
1857                 mdrestore_destroy(mdres, i + 1);
1858         return ret;
1859 }
1860
1861 static int fill_mdres_info(struct mdrestore_struct *mdres,
1862                            struct async_work *async)
1863 {
1864         struct btrfs_super_block *super;
1865         u8 *buffer = NULL;
1866         u8 *outbuf;
1867         int ret;
1868
1869         /* We've already been initialized */
1870         if (mdres->leafsize)
1871                 return 0;
1872
1873         if (mdres->compress_method == COMPRESS_ZLIB) {
1874                 size_t size = MAX_PENDING_SIZE * 2;
1875
1876                 buffer = malloc(MAX_PENDING_SIZE * 2);
1877                 if (!buffer)
1878                         return -ENOMEM;
1879                 ret = uncompress(buffer, (unsigned long *)&size,
1880                                  async->buffer, async->bufsize);
1881                 if (ret != Z_OK) {
1882                         fprintf(stderr, "Error decompressing %d\n", ret);
1883                         free(buffer);
1884                         return -EIO;
1885                 }
1886                 outbuf = buffer;
1887         } else {
1888                 outbuf = async->buffer;
1889         }
1890
1891         super = (struct btrfs_super_block *)outbuf;
1892         mdres->leafsize = btrfs_super_leafsize(super);
1893         memcpy(mdres->fsid, super->fsid, BTRFS_FSID_SIZE);
1894         memcpy(mdres->uuid, super->dev_item.uuid,
1895                        BTRFS_UUID_SIZE);
1896         mdres->devid = le64_to_cpu(super->dev_item.devid);
1897         free(buffer);
1898         return 0;
1899 }
1900
1901 static int add_cluster(struct meta_cluster *cluster,
1902                        struct mdrestore_struct *mdres, u64 *next)
1903 {
1904         struct meta_cluster_item *item;
1905         struct meta_cluster_header *header = &cluster->header;
1906         struct async_work *async;
1907         u64 bytenr;
1908         u32 i, nritems;
1909         int ret;
1910
1911         mdres->compress_method = header->compress;
1912
1913         bytenr = le64_to_cpu(header->bytenr) + BLOCK_SIZE;
1914         nritems = le32_to_cpu(header->nritems);
1915         for (i = 0; i < nritems; i++) {
1916                 item = &cluster->items[i];
1917                 async = calloc(1, sizeof(*async));
1918                 if (!async) {
1919                         fprintf(stderr, "Error allocating async\n");
1920                         return -ENOMEM;
1921                 }
1922                 async->start = le64_to_cpu(item->bytenr);
1923                 async->bufsize = le32_to_cpu(item->size);
1924                 async->buffer = malloc(async->bufsize);
1925                 if (!async->buffer) {
1926                         fprintf(stderr, "Error allocing async buffer\n");
1927                         free(async);
1928                         return -ENOMEM;
1929                 }
1930                 ret = fread(async->buffer, async->bufsize, 1, mdres->in);
1931                 if (ret != 1) {
1932                         fprintf(stderr, "Error reading buffer %d\n", errno);
1933                         free(async->buffer);
1934                         free(async);
1935                         return -EIO;
1936                 }
1937                 bytenr += async->bufsize;
1938
1939                 pthread_mutex_lock(&mdres->mutex);
1940                 if (async->start == BTRFS_SUPER_INFO_OFFSET) {
1941                         ret = fill_mdres_info(mdres, async);
1942                         if (ret) {
1943                                 fprintf(stderr, "Error setting up restore\n");
1944                                 pthread_mutex_unlock(&mdres->mutex);
1945                                 free(async->buffer);
1946                                 free(async);
1947                                 return ret;
1948                         }
1949                 }
1950                 list_add_tail(&async->list, &mdres->list);
1951                 mdres->num_items++;
1952                 pthread_cond_signal(&mdres->cond);
1953                 pthread_mutex_unlock(&mdres->mutex);
1954         }
1955         if (bytenr & BLOCK_MASK) {
1956                 char buffer[BLOCK_MASK];
1957                 size_t size = BLOCK_SIZE - (bytenr & BLOCK_MASK);
1958
1959                 bytenr += size;
1960                 ret = fread(buffer, size, 1, mdres->in);
1961                 if (ret != 1) {
1962                         fprintf(stderr, "Error reading in buffer %d\n", errno);
1963                         return -EIO;
1964                 }
1965         }
1966         *next = bytenr;
1967         return 0;
1968 }
1969
1970 static int wait_for_worker(struct mdrestore_struct *mdres)
1971 {
1972         int ret = 0;
1973
1974         pthread_mutex_lock(&mdres->mutex);
1975         ret = mdres->error;
1976         while (!ret && mdres->num_items > 0) {
1977                 struct timespec ts = {
1978                         .tv_sec = 0,
1979                         .tv_nsec = 10000000,
1980                 };
1981                 pthread_mutex_unlock(&mdres->mutex);
1982                 nanosleep(&ts, NULL);
1983                 pthread_mutex_lock(&mdres->mutex);
1984                 ret = mdres->error;
1985         }
1986         pthread_mutex_unlock(&mdres->mutex);
1987         return ret;
1988 }
1989
1990 static int read_chunk_block(struct mdrestore_struct *mdres, u8 *buffer,
1991                             u64 bytenr, u64 item_bytenr, u32 bufsize,
1992                             u64 cluster_bytenr)
1993 {
1994         struct extent_buffer *eb;
1995         int ret = 0;
1996         int i;
1997
1998         eb = alloc_dummy_eb(bytenr, mdres->leafsize);
1999         if (!eb) {
2000                 ret = -ENOMEM;
2001                 goto out;
2002         }
2003
2004         while (item_bytenr != bytenr) {
2005                 buffer += mdres->leafsize;
2006                 item_bytenr += mdres->leafsize;
2007         }
2008
2009         memcpy(eb->data, buffer, mdres->leafsize);
2010         if (btrfs_header_bytenr(eb) != bytenr) {
2011                 fprintf(stderr, "Eb bytenr doesn't match found bytenr\n");
2012                 ret = -EIO;
2013                 goto out;
2014         }
2015
2016         if (memcmp(mdres->fsid, eb->data + offsetof(struct btrfs_header, fsid),
2017                    BTRFS_FSID_SIZE)) {
2018                 fprintf(stderr, "Fsid doesn't match\n");
2019                 ret = -EIO;
2020                 goto out;
2021         }
2022
2023         if (btrfs_header_owner(eb) != BTRFS_CHUNK_TREE_OBJECTID) {
2024                 fprintf(stderr, "Does not belong to the chunk tree\n");
2025                 ret = -EIO;
2026                 goto out;
2027         }
2028
2029         for (i = 0; i < btrfs_header_nritems(eb); i++) {
2030                 struct btrfs_chunk chunk;
2031                 struct fs_chunk *fs_chunk;
2032                 struct btrfs_key key;
2033
2034                 if (btrfs_header_level(eb)) {
2035                         u64 blockptr = btrfs_node_blockptr(eb, i);
2036
2037                         ret = search_for_chunk_blocks(mdres, blockptr,
2038                                                       cluster_bytenr);
2039                         if (ret)
2040                                 break;
2041                         continue;
2042                 }
2043
2044                 /* Yay a leaf!  We loves leafs! */
2045                 btrfs_item_key_to_cpu(eb, &key, i);
2046                 if (key.type != BTRFS_CHUNK_ITEM_KEY)
2047                         continue;
2048
2049                 fs_chunk = malloc(sizeof(struct fs_chunk));
2050                 if (!fs_chunk) {
2051                         fprintf(stderr, "Erorr allocating chunk\n");
2052                         ret = -ENOMEM;
2053                         break;
2054                 }
2055                 memset(fs_chunk, 0, sizeof(*fs_chunk));
2056                 read_extent_buffer(eb, &chunk, btrfs_item_ptr_offset(eb, i),
2057                                    sizeof(chunk));
2058
2059                 fs_chunk->logical = key.offset;
2060                 fs_chunk->physical = btrfs_stack_stripe_offset(&chunk.stripe);
2061                 fs_chunk->bytes = btrfs_stack_chunk_length(&chunk);
2062                 INIT_LIST_HEAD(&fs_chunk->list);
2063                 if (tree_search(&mdres->physical_tree, &fs_chunk->p,
2064                                 physical_cmp, 1) != NULL)
2065                         list_add(&fs_chunk->list, &mdres->overlapping_chunks);
2066                 else
2067                         tree_insert(&mdres->physical_tree, &fs_chunk->p,
2068                                     physical_cmp);
2069                 if (fs_chunk->physical + fs_chunk->bytes >
2070                     mdres->last_physical_offset)
2071                         mdres->last_physical_offset = fs_chunk->physical +
2072                                 fs_chunk->bytes;
2073                 mdres->alloced_chunks += fs_chunk->bytes;
2074                 tree_insert(&mdres->chunk_tree, &fs_chunk->l, chunk_cmp);
2075         }
2076 out:
2077         free(eb);
2078         return ret;
2079 }
2080
2081 /* If you have to ask you aren't worthy */
2082 static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
2083                                    u64 search, u64 cluster_bytenr)
2084 {
2085         struct meta_cluster *cluster;
2086         struct meta_cluster_header *header;
2087         struct meta_cluster_item *item;
2088         u64 current_cluster = cluster_bytenr, bytenr;
2089         u64 item_bytenr;
2090         u32 bufsize, nritems, i;
2091         u32 max_size = MAX_PENDING_SIZE * 2;
2092         u8 *buffer, *tmp = NULL;
2093         int ret = 0;
2094
2095         cluster = malloc(BLOCK_SIZE);
2096         if (!cluster) {
2097                 fprintf(stderr, "Error allocating cluster\n");
2098                 return -ENOMEM;
2099         }
2100
2101         buffer = malloc(max_size);
2102         if (!buffer) {
2103                 fprintf(stderr, "Error allocing buffer\n");
2104                 free(cluster);
2105                 return -ENOMEM;
2106         }
2107
2108         if (mdres->compress_method == COMPRESS_ZLIB) {
2109                 tmp = malloc(max_size);
2110                 if (!tmp) {
2111                         fprintf(stderr, "Error allocing tmp buffer\n");
2112                         free(cluster);
2113                         free(buffer);
2114                         return -ENOMEM;
2115                 }
2116         }
2117
2118         bytenr = current_cluster;
2119         while (1) {
2120                 if (fseek(mdres->in, current_cluster, SEEK_SET)) {
2121                         fprintf(stderr, "Error seeking: %d\n", errno);
2122                         ret = -EIO;
2123                         break;
2124                 }
2125
2126                 ret = fread(cluster, BLOCK_SIZE, 1, mdres->in);
2127                 if (ret == 0) {
2128                         if (cluster_bytenr != 0) {
2129                                 cluster_bytenr = 0;
2130                                 current_cluster = 0;
2131                                 bytenr = 0;
2132                                 continue;
2133                         }
2134                         printf("ok this is where we screwed up?\n");
2135                         ret = -EIO;
2136                         break;
2137                 } else if (ret < 0) {
2138                         fprintf(stderr, "Error reading image\n");
2139                         break;
2140                 }
2141                 ret = 0;
2142
2143                 header = &cluster->header;
2144                 if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2145                     le64_to_cpu(header->bytenr) != current_cluster) {
2146                         fprintf(stderr, "bad header in metadump image\n");
2147                         ret = -EIO;
2148                         break;
2149                 }
2150
2151                 bytenr += BLOCK_SIZE;
2152                 nritems = le32_to_cpu(header->nritems);
2153                 for (i = 0; i < nritems; i++) {
2154                         size_t size;
2155
2156                         item = &cluster->items[i];
2157                         bufsize = le32_to_cpu(item->size);
2158                         item_bytenr = le64_to_cpu(item->bytenr);
2159
2160                         if (bufsize > max_size) {
2161                                 fprintf(stderr, "item %u size %u too big\n",
2162                                         i, bufsize);
2163                                 ret = -EIO;
2164                                 break;
2165                         }
2166
2167                         if (mdres->compress_method == COMPRESS_ZLIB) {
2168                                 ret = fread(tmp, bufsize, 1, mdres->in);
2169                                 if (ret != 1) {
2170                                         fprintf(stderr, "Error reading: %d\n",
2171                                                 errno);
2172                                         ret = -EIO;
2173                                         break;
2174                                 }
2175
2176                                 size = max_size;
2177                                 ret = uncompress(buffer,
2178                                                  (unsigned long *)&size, tmp,
2179                                                  bufsize);
2180                                 if (ret != Z_OK) {
2181                                         fprintf(stderr, "Error decompressing "
2182                                                 "%d\n", ret);
2183                                         ret = -EIO;
2184                                         break;
2185                                 }
2186                         } else {
2187                                 ret = fread(buffer, bufsize, 1, mdres->in);
2188                                 if (ret != 1) {
2189                                         fprintf(stderr, "Error reading: %d\n",
2190                                                 errno);
2191                                         ret = -EIO;
2192                                         break;
2193                                 }
2194                                 size = bufsize;
2195                         }
2196                         ret = 0;
2197
2198                         if (item_bytenr <= search &&
2199                             item_bytenr + size > search) {
2200                                 ret = read_chunk_block(mdres, buffer, search,
2201                                                        item_bytenr, size,
2202                                                        current_cluster);
2203                                 if (!ret)
2204                                         ret = 1;
2205                                 break;
2206                         }
2207                         bytenr += bufsize;
2208                 }
2209                 if (ret) {
2210                         if (ret > 0)
2211                                 ret = 0;
2212                         break;
2213                 }
2214                 if (bytenr & BLOCK_MASK)
2215                         bytenr += BLOCK_SIZE - (bytenr & BLOCK_MASK);
2216                 current_cluster = bytenr;
2217         }
2218
2219         free(tmp);
2220         free(buffer);
2221         free(cluster);
2222         return ret;
2223 }
2224
2225 static int build_chunk_tree(struct mdrestore_struct *mdres,
2226                             struct meta_cluster *cluster)
2227 {
2228         struct btrfs_super_block *super;
2229         struct meta_cluster_header *header;
2230         struct meta_cluster_item *item = NULL;
2231         u64 chunk_root_bytenr = 0;
2232         u32 i, nritems;
2233         u64 bytenr = 0;
2234         u8 *buffer;
2235         int ret;
2236
2237         /* We can't seek with stdin so don't bother doing this */
2238         if (mdres->in == stdin)
2239                 return 0;
2240
2241         ret = fread(cluster, BLOCK_SIZE, 1, mdres->in);
2242         if (ret <= 0) {
2243                 fprintf(stderr, "Error reading in cluster: %d\n", errno);
2244                 return -EIO;
2245         }
2246         ret = 0;
2247
2248         header = &cluster->header;
2249         if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2250             le64_to_cpu(header->bytenr) != 0) {
2251                 fprintf(stderr, "bad header in metadump image\n");
2252                 return -EIO;
2253         }
2254
2255         bytenr += BLOCK_SIZE;
2256         mdres->compress_method = header->compress;
2257         nritems = le32_to_cpu(header->nritems);
2258         for (i = 0; i < nritems; i++) {
2259                 item = &cluster->items[i];
2260
2261                 if (le64_to_cpu(item->bytenr) == BTRFS_SUPER_INFO_OFFSET)
2262                         break;
2263                 bytenr += le32_to_cpu(item->size);
2264                 if (fseek(mdres->in, le32_to_cpu(item->size), SEEK_CUR)) {
2265                         fprintf(stderr, "Error seeking: %d\n", errno);
2266                         return -EIO;
2267                 }
2268         }
2269
2270         if (!item || le64_to_cpu(item->bytenr) != BTRFS_SUPER_INFO_OFFSET) {
2271                 fprintf(stderr, "Huh, didn't find the super?\n");
2272                 return -EINVAL;
2273         }
2274
2275         buffer = malloc(le32_to_cpu(item->size));
2276         if (!buffer) {
2277                 fprintf(stderr, "Error allocing buffer\n");
2278                 return -ENOMEM;
2279         }
2280
2281         ret = fread(buffer, le32_to_cpu(item->size), 1, mdres->in);
2282         if (ret != 1) {
2283                 fprintf(stderr, "Error reading buffer: %d\n", errno);
2284                 free(buffer);
2285                 return -EIO;
2286         }
2287
2288         if (mdres->compress_method == COMPRESS_ZLIB) {
2289                 size_t size = MAX_PENDING_SIZE * 2;
2290                 u8 *tmp;
2291
2292                 tmp = malloc(MAX_PENDING_SIZE * 2);
2293                 if (!tmp) {
2294                         free(buffer);
2295                         return -ENOMEM;
2296                 }
2297                 ret = uncompress(tmp, (unsigned long *)&size,
2298                                  buffer, le32_to_cpu(item->size));
2299                 if (ret != Z_OK) {
2300                         fprintf(stderr, "Error decompressing %d\n", ret);
2301                         free(buffer);
2302                         free(tmp);
2303                         return -EIO;
2304                 }
2305                 free(buffer);
2306                 buffer = tmp;
2307         }
2308
2309         pthread_mutex_lock(&mdres->mutex);
2310         super = (struct btrfs_super_block *)buffer;
2311         chunk_root_bytenr = btrfs_super_chunk_root(super);
2312         mdres->leafsize = btrfs_super_leafsize(super);
2313         memcpy(mdres->fsid, super->fsid, BTRFS_FSID_SIZE);
2314         memcpy(mdres->uuid, super->dev_item.uuid,
2315                        BTRFS_UUID_SIZE);
2316         mdres->devid = le64_to_cpu(super->dev_item.devid);
2317         free(buffer);
2318         pthread_mutex_unlock(&mdres->mutex);
2319
2320         return search_for_chunk_blocks(mdres, chunk_root_bytenr, 0);
2321 }
2322
2323 static int range_contains_super(u64 physical, u64 bytes)
2324 {
2325         u64 super_bytenr;
2326         int i;
2327
2328         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2329                 super_bytenr = btrfs_sb_offset(i);
2330                 if (super_bytenr >= physical &&
2331                     super_bytenr < physical + bytes)
2332                         return 1;
2333         }
2334
2335         return 0;
2336 }
2337
2338 static void remap_overlapping_chunks(struct mdrestore_struct *mdres)
2339 {
2340         struct fs_chunk *fs_chunk;
2341
2342         while (!list_empty(&mdres->overlapping_chunks)) {
2343                 fs_chunk = list_first_entry(&mdres->overlapping_chunks,
2344                                             struct fs_chunk, list);
2345                 list_del_init(&fs_chunk->list);
2346                 if (range_contains_super(fs_chunk->physical,
2347                                          fs_chunk->bytes)) {
2348                         fprintf(stderr, "Remapping a chunk that had a super "
2349                                 "mirror inside of it, clearing space cache "
2350                                 "so we don't end up with corruption\n");
2351                         mdres->clear_space_cache = 1;
2352                 }
2353                 fs_chunk->physical = mdres->last_physical_offset;
2354                 tree_insert(&mdres->physical_tree, &fs_chunk->p, physical_cmp);
2355                 mdres->last_physical_offset += fs_chunk->bytes;
2356         }
2357 }
2358
2359 static int fixup_devices(struct btrfs_fs_info *fs_info,
2360                          struct mdrestore_struct *mdres, off_t dev_size)
2361 {
2362         struct btrfs_trans_handle *trans;
2363         struct btrfs_dev_item *dev_item;
2364         struct btrfs_path *path;
2365         struct extent_buffer *leaf;
2366         struct btrfs_root *root = fs_info->chunk_root;
2367         struct btrfs_key key;
2368         u64 devid, cur_devid;
2369         int ret;
2370
2371         path = btrfs_alloc_path();
2372         if (!path) {
2373                 fprintf(stderr, "Error alloc'ing path\n");
2374                 return -ENOMEM;
2375         }
2376
2377         trans = btrfs_start_transaction(fs_info->tree_root, 1);
2378         if (IS_ERR(trans)) {
2379                 fprintf(stderr, "Error starting transaction %ld\n",
2380                         PTR_ERR(trans));
2381                 btrfs_free_path(path);
2382                 return PTR_ERR(trans);
2383         }
2384
2385         dev_item = &fs_info->super_copy->dev_item;
2386
2387         devid = btrfs_stack_device_id(dev_item);
2388
2389         btrfs_set_stack_device_total_bytes(dev_item, dev_size);
2390         btrfs_set_stack_device_bytes_used(dev_item, mdres->alloced_chunks);
2391
2392         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2393         key.type = BTRFS_DEV_ITEM_KEY;
2394         key.offset = 0;
2395
2396 again:
2397         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2398         if (ret < 0) {
2399                 fprintf(stderr, "search failed %d\n", ret);
2400                 exit(1);
2401         }
2402
2403         while (1) {
2404                 leaf = path->nodes[0];
2405                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2406                         ret = btrfs_next_leaf(root, path);
2407                         if (ret < 0) {
2408                                 fprintf(stderr, "Error going to next leaf "
2409                                         "%d\n", ret);
2410                                 exit(1);
2411                         }
2412                         if (ret > 0) {
2413                                 ret = 0;
2414                                 break;
2415                         }
2416                         leaf = path->nodes[0];
2417                 }
2418
2419                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2420                 if (key.type > BTRFS_DEV_ITEM_KEY)
2421                         break;
2422                 if (key.type != BTRFS_DEV_ITEM_KEY) {
2423                         path->slots[0]++;
2424                         continue;
2425                 }
2426
2427                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2428                                           struct btrfs_dev_item);
2429                 cur_devid = btrfs_device_id(leaf, dev_item);
2430                 if (devid != cur_devid) {
2431                         ret = btrfs_del_item(trans, root, path);
2432                         if (ret) {
2433                                 fprintf(stderr, "Error deleting item %d\n",
2434                                         ret);
2435                                 exit(1);
2436                         }
2437                         btrfs_release_path(path);
2438                         goto again;
2439                 }
2440
2441                 btrfs_set_device_total_bytes(leaf, dev_item, dev_size);
2442                 btrfs_set_device_bytes_used(leaf, dev_item,
2443                                             mdres->alloced_chunks);
2444                 btrfs_mark_buffer_dirty(leaf);
2445                 path->slots[0]++;
2446         }
2447
2448         btrfs_free_path(path);
2449         ret = btrfs_commit_transaction(trans, fs_info->tree_root);
2450         if (ret) {
2451                 fprintf(stderr, "Commit failed %d\n", ret);
2452                 return ret;
2453         }
2454         return 0;
2455 }
2456
2457 static int restore_metadump(const char *input, FILE *out, int old_restore,
2458                             int num_threads, int fixup_offset,
2459                             const char *target, int multi_devices)
2460 {
2461         struct meta_cluster *cluster = NULL;
2462         struct meta_cluster_header *header;
2463         struct mdrestore_struct mdrestore;
2464         struct btrfs_fs_info *info = NULL;
2465         u64 bytenr = 0;
2466         FILE *in = NULL;
2467         int ret = 0;
2468
2469         if (!strcmp(input, "-")) {
2470                 in = stdin;
2471         } else {
2472                 in = fopen(input, "r");
2473                 if (!in) {
2474                         perror("unable to open metadump image");
2475                         return 1;
2476                 }
2477         }
2478
2479         /* NOTE: open with write mode */
2480         if (fixup_offset) {
2481                 BUG_ON(!target);
2482                 info = open_ctree_fs_info(target, 0, 0,
2483                                           OPEN_CTREE_WRITES |
2484                                           OPEN_CTREE_RESTORE |
2485                                           OPEN_CTREE_PARTIAL);
2486                 if (!info) {
2487                         fprintf(stderr, "%s: open ctree failed\n", __func__);
2488                         ret = -EIO;
2489                         goto failed_open;
2490                 }
2491         }
2492
2493         cluster = malloc(BLOCK_SIZE);
2494         if (!cluster) {
2495                 fprintf(stderr, "Error allocating cluster\n");
2496                 ret = -ENOMEM;
2497                 goto failed_info;
2498         }
2499
2500         ret = mdrestore_init(&mdrestore, in, out, old_restore, num_threads,
2501                              fixup_offset, info, multi_devices);
2502         if (ret) {
2503                 fprintf(stderr, "Error initing mdrestore %d\n", ret);
2504                 goto failed_cluster;
2505         }
2506
2507         if (!multi_devices && !old_restore) {
2508                 ret = build_chunk_tree(&mdrestore, cluster);
2509                 if (ret)
2510                         goto out;
2511                 if (!list_empty(&mdrestore.overlapping_chunks))
2512                         remap_overlapping_chunks(&mdrestore);
2513         }
2514
2515         if (in != stdin && fseek(in, 0, SEEK_SET)) {
2516                 fprintf(stderr, "Error seeking %d\n", errno);
2517                 goto out;
2518         }
2519
2520         while (!mdrestore.error) {
2521                 ret = fread(cluster, BLOCK_SIZE, 1, in);
2522                 if (!ret)
2523                         break;
2524
2525                 header = &cluster->header;
2526                 if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2527                     le64_to_cpu(header->bytenr) != bytenr) {
2528                         fprintf(stderr, "bad header in metadump image\n");
2529                         ret = -EIO;
2530                         break;
2531                 }
2532                 ret = add_cluster(cluster, &mdrestore, &bytenr);
2533                 if (ret) {
2534                         fprintf(stderr, "Error adding cluster\n");
2535                         break;
2536                 }
2537         }
2538         ret = wait_for_worker(&mdrestore);
2539
2540         if (!ret && !multi_devices && !old_restore) {
2541                 struct btrfs_root *root;
2542                 struct stat st;
2543
2544                 root = open_ctree_fd(fileno(out), target, 0,
2545                                           OPEN_CTREE_PARTIAL |
2546                                           OPEN_CTREE_WRITES |
2547                                           OPEN_CTREE_NO_DEVICES);
2548                 if (!root) {
2549                         fprintf(stderr, "unable to open %s\n", target);
2550                         ret = -EIO;
2551                         goto out;
2552                 }
2553                 info = root->fs_info;
2554
2555                 if (stat(target, &st)) {
2556                         fprintf(stderr, "statting %s failed\n", target);
2557                         close_ctree(info->chunk_root);
2558                         return 1;
2559                 }
2560
2561                 ret = fixup_devices(info, &mdrestore, st.st_size);
2562                 close_ctree(info->chunk_root);
2563                 if (ret)
2564                         goto out;
2565         }
2566 out:
2567         mdrestore_destroy(&mdrestore, num_threads);
2568 failed_cluster:
2569         free(cluster);
2570 failed_info:
2571         if (fixup_offset && info)
2572                 close_ctree(info->chunk_root);
2573 failed_open:
2574         if (in != stdin)
2575                 fclose(in);
2576         return ret;
2577 }
2578
2579 static int update_disk_super_on_device(struct btrfs_fs_info *info,
2580                                        const char *other_dev, u64 cur_devid)
2581 {
2582         struct btrfs_key key;
2583         struct extent_buffer *leaf;
2584         struct btrfs_path path;
2585         struct btrfs_dev_item *dev_item;
2586         struct btrfs_super_block *disk_super;
2587         char dev_uuid[BTRFS_UUID_SIZE];
2588         char fs_uuid[BTRFS_UUID_SIZE];
2589         u64 devid, type, io_align, io_width;
2590         u64 sector_size, total_bytes, bytes_used;
2591         char *buf = NULL;
2592         int fp = -1;
2593         int ret;
2594
2595         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2596         key.type = BTRFS_DEV_ITEM_KEY;
2597         key.offset = cur_devid;
2598
2599         btrfs_init_path(&path);
2600         ret = btrfs_search_slot(NULL, info->chunk_root, &key, &path, 0, 0); 
2601         if (ret) {
2602                 fprintf(stderr, "ERROR: search key failed\n");
2603                 ret = -EIO;
2604                 goto out;
2605         }
2606
2607         leaf = path.nodes[0];
2608         dev_item = btrfs_item_ptr(leaf, path.slots[0],
2609                                   struct btrfs_dev_item);
2610
2611         devid = btrfs_device_id(leaf, dev_item);
2612         if (devid != cur_devid) {
2613                 printk("ERROR: devid %llu mismatch with %llu\n", devid, cur_devid);
2614                 ret = -EIO;
2615                 goto out;
2616         }
2617
2618         type = btrfs_device_type(leaf, dev_item);
2619         io_align = btrfs_device_io_align(leaf, dev_item);
2620         io_width = btrfs_device_io_width(leaf, dev_item);
2621         sector_size = btrfs_device_sector_size(leaf, dev_item);
2622         total_bytes = btrfs_device_total_bytes(leaf, dev_item);
2623         bytes_used = btrfs_device_bytes_used(leaf, dev_item);
2624         read_extent_buffer(leaf, dev_uuid, (unsigned long)btrfs_device_uuid(dev_item), BTRFS_UUID_SIZE);
2625         read_extent_buffer(leaf, fs_uuid, (unsigned long)btrfs_device_fsid(dev_item), BTRFS_UUID_SIZE);
2626
2627         btrfs_release_path(&path);
2628
2629         printk("update disk super on %s devid=%llu\n", other_dev, devid);
2630
2631         /* update other devices' super block */
2632         fp = open(other_dev, O_CREAT | O_RDWR, 0600);
2633         if (fp < 0) {
2634                 fprintf(stderr, "ERROR: could not open %s\n", other_dev);
2635                 ret = -EIO;
2636                 goto out;
2637         }
2638
2639         buf = malloc(BTRFS_SUPER_INFO_SIZE);
2640         if (!buf) {
2641                 ret = -ENOMEM;
2642                 close(fp);
2643                 return ret;
2644         }
2645
2646         memcpy(buf, info->super_copy, BTRFS_SUPER_INFO_SIZE);
2647
2648         disk_super = (struct btrfs_super_block *)buf;
2649         dev_item = &disk_super->dev_item;
2650
2651         btrfs_set_stack_device_type(dev_item, type);
2652         btrfs_set_stack_device_id(dev_item, devid);
2653         btrfs_set_stack_device_total_bytes(dev_item, total_bytes);
2654         btrfs_set_stack_device_bytes_used(dev_item, bytes_used);
2655         btrfs_set_stack_device_io_align(dev_item, io_align);
2656         btrfs_set_stack_device_io_width(dev_item, io_width);
2657         btrfs_set_stack_device_sector_size(dev_item, sector_size);
2658         memcpy(dev_item->uuid, dev_uuid, BTRFS_UUID_SIZE);
2659         memcpy(dev_item->fsid, fs_uuid, BTRFS_UUID_SIZE);
2660         csum_block((u8 *)buf, BTRFS_SUPER_INFO_SIZE);
2661
2662         ret = pwrite64(fp, buf, BTRFS_SUPER_INFO_SIZE, BTRFS_SUPER_INFO_OFFSET);
2663         if (ret != BTRFS_SUPER_INFO_SIZE) {
2664                 if (ret < 0)
2665                         fprintf(stderr, "ERROR: cannot write superblock: %s\n", strerror(ret));
2666                 else
2667                         fprintf(stderr, "ERROR: cannot write superblock\n");
2668                 ret = -EIO;
2669                 goto out;
2670         }
2671
2672         write_backup_supers(fp, (u8 *)buf);
2673
2674 out:
2675         free(buf);
2676         if (fp != -1)
2677                 close(fp);
2678         return ret;
2679 }
2680
2681 static void print_usage(int ret)
2682 {
2683         fprintf(stderr, "usage: btrfs-image [options] source target\n");
2684         fprintf(stderr, "\t-r      \trestore metadump image\n");
2685         fprintf(stderr, "\t-c value\tcompression level (0 ~ 9)\n");
2686         fprintf(stderr, "\t-t value\tnumber of threads (1 ~ 32)\n");
2687         fprintf(stderr, "\t-o      \tdon't mess with the chunk tree when restoring\n");
2688         fprintf(stderr, "\t-s      \tsanitize file names, use once to just use garbage, use twice if you want crc collisions\n");
2689         fprintf(stderr, "\t-w      \twalk all trees instead of using extent tree, do this if your extent tree is broken\n");
2690         fprintf(stderr, "\t-m      \trestore for multiple devices\n");
2691         fprintf(stderr, "\n");
2692         fprintf(stderr, "\tIn the dump mode, source is the btrfs device and target is the output file (use '-' for stdout).\n");
2693         fprintf(stderr, "\tIn the restore mode, source is the dumped image and target is the btrfs device/file.\n");
2694         exit(ret);
2695 }
2696
2697 int main(int argc, char *argv[])
2698 {
2699         char *source;
2700         char *target;
2701         u64 num_threads = 1;
2702         u64 compress_level = 0;
2703         int create = 1;
2704         int old_restore = 0;
2705         int walk_trees = 0;
2706         int multi_devices = 0;
2707         int ret;
2708         int sanitize = 0;
2709         int dev_cnt = 0;
2710         int usage_error = 0;
2711         FILE *out;
2712
2713         while (1) {
2714                 static const struct option long_options[] = {
2715                         { "help", no_argument, NULL, GETOPT_VAL_HELP},
2716                         { NULL, 0, NULL, 0 }
2717                 };
2718                 int c = getopt_long(argc, argv, "rc:t:oswm", long_options, NULL);
2719                 if (c < 0)
2720                         break;
2721                 switch (c) {
2722                 case 'r':
2723                         create = 0;
2724                         break;
2725                 case 't':
2726                         num_threads = arg_strtou64(optarg);
2727                         if (num_threads > 32)
2728                                 print_usage(1);
2729                         break;
2730                 case 'c':
2731                         compress_level = arg_strtou64(optarg);
2732                         if (compress_level > 9)
2733                                 print_usage(1);
2734                         break;
2735                 case 'o':
2736                         old_restore = 1;
2737                         break;
2738                 case 's':
2739                         sanitize++;
2740                         break;
2741                 case 'w':
2742                         walk_trees = 1;
2743                         break;
2744                 case 'm':
2745                         create = 0;
2746                         multi_devices = 1;
2747                         break;
2748                         case GETOPT_VAL_HELP:
2749                 default:
2750                         print_usage(c != GETOPT_VAL_HELP);
2751                 }
2752         }
2753
2754         argc = argc - optind;
2755         set_argv0(argv);
2756         if (check_argc_min(argc, 2))
2757                 print_usage(1);
2758
2759         dev_cnt = argc - 1;
2760
2761         if (create) {
2762                 if (old_restore) {
2763                         fprintf(stderr, "Usage error: create and restore cannot be used at the same time\n");
2764                         usage_error++;
2765                 }
2766         } else {
2767                 if (walk_trees || sanitize || compress_level) {
2768                         fprintf(stderr, "Usage error: use -w, -s, -c options for restore makes no sense\n");
2769                         usage_error++;
2770                 }
2771                 if (multi_devices && dev_cnt < 2) {
2772                         fprintf(stderr, "Usage error: not enough devices specified for -m option\n");
2773                         usage_error++;
2774                 }
2775                 if (!multi_devices && dev_cnt != 1) {
2776                         fprintf(stderr, "Usage error: accepts only 1 device without -m option\n");
2777                         usage_error++;
2778                 }
2779         }
2780
2781         if (usage_error)
2782                 print_usage(1);
2783
2784         source = argv[optind];
2785         target = argv[optind + 1];
2786
2787         if (create && !strcmp(target, "-")) {
2788                 out = stdout;
2789         } else {
2790                 out = fopen(target, "w+");
2791                 if (!out) {
2792                         perror("unable to create target file");
2793                         exit(1);
2794                 }
2795         }
2796
2797         if (num_threads == 1 && compress_level > 0) {
2798                 num_threads = sysconf(_SC_NPROCESSORS_ONLN);
2799                 if (num_threads <= 0)
2800                         num_threads = 1;
2801         }
2802
2803         if (create) {
2804                 ret = check_mounted(source);
2805                 if (ret < 0) {
2806                         fprintf(stderr, "Could not check mount status: %s\n",
2807                                 strerror(-ret));
2808                         exit(1);
2809                 } else if (ret)
2810                         fprintf(stderr,
2811                 "WARNING: The device is mounted. Make sure the filesystem is quiescent.\n");
2812
2813                 ret = create_metadump(source, out, num_threads,
2814                                       compress_level, sanitize, walk_trees);
2815         } else {
2816                 ret = restore_metadump(source, out, old_restore, num_threads,
2817                                        0, target, multi_devices);
2818         }
2819         if (ret) {
2820                 printk("%s failed (%s)\n", (create) ? "create" : "restore",
2821                        strerror(errno));
2822                 goto out;
2823         }
2824
2825          /* extended support for multiple devices */
2826         if (!create && multi_devices) {
2827                 struct btrfs_fs_info *info;
2828                 u64 total_devs;
2829                 int i;
2830
2831                 info = open_ctree_fs_info(target, 0, 0,
2832                                           OPEN_CTREE_PARTIAL |
2833                                           OPEN_CTREE_RESTORE);
2834                 if (!info) {
2835                         int e = errno;
2836                         fprintf(stderr, "unable to open %s error = %s\n",
2837                                 target, strerror(e));
2838                         return 1;
2839                 }
2840
2841                 total_devs = btrfs_super_num_devices(info->super_copy);
2842                 if (total_devs != dev_cnt) {
2843                         printk("it needs %llu devices but has only %d\n",
2844                                 total_devs, dev_cnt);
2845                         close_ctree(info->chunk_root);
2846                         goto out;
2847                 }
2848
2849                 /* update super block on other disks */
2850                 for (i = 2; i <= dev_cnt; i++) {
2851                         ret = update_disk_super_on_device(info,
2852                                         argv[optind + i], (u64)i);
2853                         if (ret) {
2854                                 printk("update disk super failed devid=%d (error=%d)\n",
2855                                         i, ret);
2856                                 close_ctree(info->chunk_root);
2857                                 exit(1);
2858                         }
2859                 }
2860
2861                 close_ctree(info->chunk_root);
2862
2863                 /* fix metadata block to map correct chunk */
2864                 ret = restore_metadump(source, out, 0, num_threads, 1,
2865                                        target, 1);
2866                 if (ret) {
2867                         fprintf(stderr, "fix metadump failed (error=%d)\n",
2868                                 ret);
2869                         exit(1);
2870                 }
2871         }
2872 out:
2873         if (out == stdout) {
2874                 fflush(out);
2875         } else {
2876                 fclose(out);
2877                 if (ret && create) {
2878                         int unlink_ret;
2879
2880                         unlink_ret = unlink(target);
2881                         if (unlink_ret)
2882                                 fprintf(stderr,
2883                                         "unlink output file failed : %s\n",
2884                                         strerror(errno));
2885                 }
2886         }
2887
2888         return !!ret;
2889 }