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