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