btrfs-progs: Fix some spelling typos in chunk-recover.c
[platform/upstream/btrfs-progs.git] / chunk-recover.c
1 /*
2  * Copyright (C) 2013 FUJITSU LIMITED.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include "kerncompat.h"
20 #include "androidcompat.h"
21
22 #include <stdio.h>
23 #include <stdio_ext.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <uuid/uuid.h>
30 #include <pthread.h>
31
32 #include "list.h"
33 #include "radix-tree.h"
34 #include "ctree.h"
35 #include "extent-cache.h"
36 #include "disk-io.h"
37 #include "volumes.h"
38 #include "transaction.h"
39 #include "crc32c.h"
40 #include "utils.h"
41 #include "btrfsck.h"
42 #include "commands.h"
43
44 struct recover_control {
45         int verbose;
46         int yes;
47
48         u16 csum_size;
49         u32 sectorsize;
50         u32 leafsize;
51         u64 generation;
52         u64 chunk_root_generation;
53
54         struct btrfs_fs_devices *fs_devices;
55
56         struct cache_tree chunk;
57         struct block_group_tree bg;
58         struct device_extent_tree devext;
59         struct cache_tree eb_cache;
60
61         struct list_head good_chunks;
62         struct list_head bad_chunks;
63         struct list_head rebuild_chunks;
64         struct list_head unrepaired_chunks;
65         pthread_mutex_t rc_lock;
66 };
67
68 struct extent_record {
69         struct cache_extent cache;
70         u64 generation;
71         u8 csum[BTRFS_CSUM_SIZE];
72         struct btrfs_device *devices[BTRFS_MAX_MIRRORS];
73         u64 offsets[BTRFS_MAX_MIRRORS];
74         int nmirrors;
75 };
76
77 struct device_scan {
78         struct recover_control *rc;
79         struct btrfs_device *dev;
80         int fd;
81         u64 bytenr;
82 };
83
84 static struct extent_record *btrfs_new_extent_record(struct extent_buffer *eb)
85 {
86         struct extent_record *rec;
87
88         rec = malloc(sizeof(*rec));
89         if (!rec) {
90                 fprintf(stderr, "Fail to allocate memory for extent record.\n");
91                 exit(1);
92         }
93
94         memset(rec, 0, sizeof(*rec));
95         rec->cache.start = btrfs_header_bytenr(eb);
96         rec->cache.size = eb->len;
97         rec->generation = btrfs_header_generation(eb);
98         read_extent_buffer(eb, rec->csum, (unsigned long)btrfs_header_csum(eb),
99                            BTRFS_CSUM_SIZE);
100         return rec;
101 }
102
103 static int process_extent_buffer(struct cache_tree *eb_cache,
104                                  struct extent_buffer *eb,
105                                  struct btrfs_device *device, u64 offset)
106 {
107         struct extent_record *rec;
108         struct extent_record *exist;
109         struct cache_extent *cache;
110         int ret = 0;
111
112         rec = btrfs_new_extent_record(eb);
113         if (!rec->cache.size)
114                 goto free_out;
115 again:
116         cache = lookup_cache_extent(eb_cache,
117                                     rec->cache.start,
118                                     rec->cache.size);
119         if (cache) {
120                 exist = container_of(cache, struct extent_record, cache);
121
122                 if (exist->generation > rec->generation)
123                         goto free_out;
124                 if (exist->generation == rec->generation) {
125                         if (exist->cache.start != rec->cache.start ||
126                             exist->cache.size != rec->cache.size ||
127                             memcmp(exist->csum, rec->csum, BTRFS_CSUM_SIZE)) {
128                                 ret = -EEXIST;
129                         } else {
130                                 BUG_ON(exist->nmirrors >= BTRFS_MAX_MIRRORS);
131                                 exist->devices[exist->nmirrors] = device;
132                                 exist->offsets[exist->nmirrors] = offset;
133                                 exist->nmirrors++;
134                         }
135                         goto free_out;
136                 }
137                 remove_cache_extent(eb_cache, cache);
138                 free(exist);
139                 goto again;
140         }
141
142         rec->devices[0] = device;
143         rec->offsets[0] = offset;
144         rec->nmirrors++;
145         ret = insert_cache_extent(eb_cache, &rec->cache);
146         BUG_ON(ret);
147 out:
148         return ret;
149 free_out:
150         free(rec);
151         goto out;
152 }
153
154 static void free_extent_record(struct cache_extent *cache)
155 {
156         struct extent_record *er;
157
158         er = container_of(cache, struct extent_record, cache);
159         free(er);
160 }
161
162 FREE_EXTENT_CACHE_BASED_TREE(extent_record, free_extent_record);
163
164 static struct btrfs_chunk *create_chunk_item(struct chunk_record *record)
165 {
166         struct btrfs_chunk *ret;
167         struct btrfs_stripe *chunk_stripe;
168         int i;
169
170         if (!record || record->num_stripes == 0)
171                 return NULL;
172         ret = malloc(btrfs_chunk_item_size(record->num_stripes));
173         if (!ret)
174                 return NULL;
175         btrfs_set_stack_chunk_length(ret, record->length);
176         btrfs_set_stack_chunk_owner(ret, record->owner);
177         btrfs_set_stack_chunk_stripe_len(ret, record->stripe_len);
178         btrfs_set_stack_chunk_type(ret, record->type_flags);
179         btrfs_set_stack_chunk_io_align(ret, record->io_align);
180         btrfs_set_stack_chunk_io_width(ret, record->io_width);
181         btrfs_set_stack_chunk_sector_size(ret, record->sector_size);
182         btrfs_set_stack_chunk_num_stripes(ret, record->num_stripes);
183         btrfs_set_stack_chunk_sub_stripes(ret, record->sub_stripes);
184         for (i = 0, chunk_stripe = &ret->stripe; i < record->num_stripes;
185              i++, chunk_stripe++) {
186                 btrfs_set_stack_stripe_devid(chunk_stripe,
187                                 record->stripes[i].devid);
188                 btrfs_set_stack_stripe_offset(chunk_stripe,
189                                 record->stripes[i].offset);
190                 memcpy(chunk_stripe->dev_uuid, record->stripes[i].dev_uuid,
191                        BTRFS_UUID_SIZE);
192         }
193         return ret;
194 }
195
196 static void init_recover_control(struct recover_control *rc, int verbose,
197                 int yes)
198 {
199         memset(rc, 0, sizeof(struct recover_control));
200         cache_tree_init(&rc->chunk);
201         cache_tree_init(&rc->eb_cache);
202         block_group_tree_init(&rc->bg);
203         device_extent_tree_init(&rc->devext);
204
205         INIT_LIST_HEAD(&rc->good_chunks);
206         INIT_LIST_HEAD(&rc->bad_chunks);
207         INIT_LIST_HEAD(&rc->rebuild_chunks);
208         INIT_LIST_HEAD(&rc->unrepaired_chunks);
209
210         rc->verbose = verbose;
211         rc->yes = yes;
212         pthread_mutex_init(&rc->rc_lock, NULL);
213 }
214
215 static void free_recover_control(struct recover_control *rc)
216 {
217         free_block_group_tree(&rc->bg);
218         free_chunk_cache_tree(&rc->chunk);
219         free_device_extent_tree(&rc->devext);
220         free_extent_record_tree(&rc->eb_cache);
221         pthread_mutex_destroy(&rc->rc_lock);
222 }
223
224 static int process_block_group_item(struct block_group_tree *bg_cache,
225                                     struct extent_buffer *leaf,
226                                     struct btrfs_key *key, int slot)
227 {
228         struct block_group_record *rec;
229         struct block_group_record *exist;
230         struct cache_extent *cache;
231         int ret = 0;
232
233         rec = btrfs_new_block_group_record(leaf, key, slot);
234         if (!rec->cache.size)
235                 goto free_out;
236 again:
237         cache = lookup_cache_extent(&bg_cache->tree,
238                                     rec->cache.start,
239                                     rec->cache.size);
240         if (cache) {
241                 exist = container_of(cache, struct block_group_record, cache);
242
243                 /*check the generation and replace if needed*/
244                 if (exist->generation > rec->generation)
245                         goto free_out;
246                 if (exist->generation == rec->generation) {
247                         int offset = offsetof(struct block_group_record,
248                                               generation);
249                         /*
250                          * According to the current kernel code, the following
251                          * case is impossble, or there is something wrong in
252                          * the kernel code.
253                          */
254                         if (memcmp(((void *)exist) + offset,
255                                    ((void *)rec) + offset,
256                                    sizeof(*rec) - offset))
257                                 ret = -EEXIST;
258                         goto free_out;
259                 }
260                 remove_cache_extent(&bg_cache->tree, cache);
261                 list_del_init(&exist->list);
262                 free(exist);
263                 /*
264                  * We must do search again to avoid the following cache.
265                  * /--old bg 1--//--old bg 2--/
266                  *        /--new bg--/
267                  */
268                 goto again;
269         }
270
271         ret = insert_block_group_record(bg_cache, rec);
272         BUG_ON(ret);
273 out:
274         return ret;
275 free_out:
276         free(rec);
277         goto out;
278 }
279
280 static int process_chunk_item(struct cache_tree *chunk_cache,
281                               struct extent_buffer *leaf, struct btrfs_key *key,
282                               int slot)
283 {
284         struct chunk_record *rec;
285         struct chunk_record *exist;
286         struct cache_extent *cache;
287         int ret = 0;
288
289         rec = btrfs_new_chunk_record(leaf, key, slot);
290         if (!rec->cache.size)
291                 goto free_out;
292 again:
293         cache = lookup_cache_extent(chunk_cache, rec->offset, rec->length);
294         if (cache) {
295                 exist = container_of(cache, struct chunk_record, cache);
296
297                 if (exist->generation > rec->generation)
298                         goto free_out;
299                 if (exist->generation == rec->generation) {
300                         int num_stripes = rec->num_stripes;
301                         int rec_size = btrfs_chunk_record_size(num_stripes);
302                         int offset = offsetof(struct chunk_record, generation);
303
304                         if (exist->num_stripes != rec->num_stripes ||
305                             memcmp(((void *)exist) + offset,
306                                    ((void *)rec) + offset,
307                                    rec_size - offset))
308                                 ret = -EEXIST;
309                         goto free_out;
310                 }
311                 remove_cache_extent(chunk_cache, cache);
312                 free(exist);
313                 goto again;
314         }
315         ret = insert_cache_extent(chunk_cache, &rec->cache);
316         BUG_ON(ret);
317 out:
318         return ret;
319 free_out:
320         free(rec);
321         goto out;
322 }
323
324 static int process_device_extent_item(struct device_extent_tree *devext_cache,
325                                       struct extent_buffer *leaf,
326                                       struct btrfs_key *key, int slot)
327 {
328         struct device_extent_record *rec;
329         struct device_extent_record *exist;
330         struct cache_extent *cache;
331         int ret = 0;
332
333         rec = btrfs_new_device_extent_record(leaf, key, slot);
334         if (!rec->cache.size)
335                 goto free_out;
336 again:
337         cache = lookup_cache_extent2(&devext_cache->tree,
338                                      rec->cache.objectid,
339                                      rec->cache.start,
340                                      rec->cache.size);
341         if (cache) {
342                 exist = container_of(cache, struct device_extent_record, cache);
343                 if (exist->generation > rec->generation)
344                         goto free_out;
345                 if (exist->generation == rec->generation) {
346                         int offset = offsetof(struct device_extent_record,
347                                               generation);
348                         if (memcmp(((void *)exist) + offset,
349                                    ((void *)rec) + offset,
350                                    sizeof(*rec) - offset))
351                                 ret = -EEXIST;
352                         goto free_out;
353                 }
354                 remove_cache_extent(&devext_cache->tree, cache);
355                 list_del_init(&exist->chunk_list);
356                 list_del_init(&exist->device_list);
357                 free(exist);
358                 goto again;
359         }
360
361         ret = insert_device_extent_record(devext_cache, rec);
362         BUG_ON(ret);
363 out:
364         return ret;
365 free_out:
366         free(rec);
367         goto out;
368 }
369
370 static void print_block_group_info(struct block_group_record *rec, char *prefix)
371 {
372         if (prefix)
373                 printf("%s", prefix);
374         printf("Block Group: start = %llu, len = %llu, flag = %llx\n",
375                rec->objectid, rec->offset, rec->flags);
376 }
377
378 static void print_block_group_tree(struct block_group_tree *tree)
379 {
380         struct cache_extent *cache;
381         struct block_group_record *rec;
382
383         printf("All Block Groups:\n");
384         for (cache = first_cache_extent(&tree->tree); cache;
385              cache = next_cache_extent(cache)) {
386                 rec = container_of(cache, struct block_group_record, cache);
387                 print_block_group_info(rec, "\t");
388         }
389         printf("\n");
390 }
391
392 static void print_stripe_info(struct stripe *data, char *prefix1, char *prefix2,
393                               int index)
394 {
395         if (prefix1)
396                 printf("%s", prefix1);
397         if (prefix2)
398                 printf("%s", prefix2);
399         printf("[%2d] Stripe: devid = %llu, offset = %llu\n",
400                index, data->devid, data->offset);
401 }
402
403 static void print_chunk_self_info(struct chunk_record *rec, char *prefix)
404 {
405         int i;
406
407         if (prefix)
408                 printf("%s", prefix);
409         printf("Chunk: start = %llu, len = %llu, type = %llx, num_stripes = %u\n",
410                rec->offset, rec->length, rec->type_flags, rec->num_stripes);
411         if (prefix)
412                 printf("%s", prefix);
413         printf("    Stripes list:\n");
414         for (i = 0; i < rec->num_stripes; i++)
415                 print_stripe_info(&rec->stripes[i], prefix, "    ", i);
416 }
417
418 static void print_chunk_tree(struct cache_tree *tree)
419 {
420         struct cache_extent *n;
421         struct chunk_record *entry;
422
423         printf("All Chunks:\n");
424         for (n = first_cache_extent(tree); n;
425              n = next_cache_extent(n)) {
426                 entry = container_of(n, struct chunk_record, cache);
427                 print_chunk_self_info(entry, "\t");
428         }
429         printf("\n");
430 }
431
432 static void print_device_extent_info(struct device_extent_record *rec,
433                                      char *prefix)
434 {
435         if (prefix)
436                 printf("%s", prefix);
437         printf("Device extent: devid = %llu, start = %llu, len = %llu, chunk offset = %llu\n",
438                rec->objectid, rec->offset, rec->length, rec->chunk_offset);
439 }
440
441 static void print_device_extent_tree(struct device_extent_tree *tree)
442 {
443         struct cache_extent *n;
444         struct device_extent_record *entry;
445
446         printf("All Device Extents:\n");
447         for (n = first_cache_extent(&tree->tree); n;
448              n = next_cache_extent(n)) {
449                 entry = container_of(n, struct device_extent_record, cache);
450                 print_device_extent_info(entry, "\t");
451         }
452         printf("\n");
453 }
454
455 static void print_device_info(struct btrfs_device *device, char *prefix)
456 {
457         if (prefix)
458                 printf("%s", prefix);
459         printf("Device: id = %llu, name = %s\n",
460                device->devid, device->name);
461 }
462
463 static void print_all_devices(struct list_head *devices)
464 {
465         struct btrfs_device *dev;
466
467         printf("All Devices:\n");
468         list_for_each_entry(dev, devices, dev_list)
469                 print_device_info(dev, "\t");
470         printf("\n");
471 }
472
473 static void print_scan_result(struct recover_control *rc)
474 {
475         if (!rc->verbose)
476                 return;
477
478         printf("DEVICE SCAN RESULT:\n");
479         printf("Filesystem Information:\n");
480         printf("\tsectorsize: %d\n", rc->sectorsize);
481         printf("\tleafsize: %d\n", rc->leafsize);
482         printf("\ttree root generation: %llu\n", rc->generation);
483         printf("\tchunk root generation: %llu\n", rc->chunk_root_generation);
484         printf("\n");
485
486         print_all_devices(&rc->fs_devices->devices);
487         print_block_group_tree(&rc->bg);
488         print_chunk_tree(&rc->chunk);
489         print_device_extent_tree(&rc->devext);
490 }
491
492 static void print_chunk_info(struct chunk_record *chunk, char *prefix)
493 {
494         struct device_extent_record *devext;
495         int i;
496
497         print_chunk_self_info(chunk, prefix);
498         if (prefix)
499                 printf("%s", prefix);
500         if (chunk->bg_rec)
501                 print_block_group_info(chunk->bg_rec, "    ");
502         else
503                 printf("    No block group.\n");
504         if (prefix)
505                 printf("%s", prefix);
506         if (list_empty(&chunk->dextents)) {
507                 printf("    No device extent.\n");
508         } else {
509                 printf("    Device extent list:\n");
510                 i = 0;
511                 list_for_each_entry(devext, &chunk->dextents, chunk_list) {
512                         if (prefix)
513                                 printf("%s", prefix);
514                         printf("%s[%2d]", "        ", i);
515                         print_device_extent_info(devext, NULL);
516                         i++;
517                 }
518         }
519 }
520
521 static void print_check_result(struct recover_control *rc)
522 {
523         struct chunk_record *chunk;
524         struct block_group_record *bg;
525         struct device_extent_record *devext;
526         int total = 0;
527         int good = 0;
528         int bad = 0;
529
530         if (!rc->verbose)
531                 return;
532
533         printf("CHECK RESULT:\n");
534         printf("Recoverable Chunks:\n");
535         list_for_each_entry(chunk, &rc->good_chunks, list) {
536                 print_chunk_info(chunk, "  ");
537                 good++;
538                 total++;
539         }
540         list_for_each_entry(chunk, &rc->rebuild_chunks, list) {
541                 print_chunk_info(chunk, "  ");
542                 good++;
543                 total++;
544         }
545         list_for_each_entry(chunk, &rc->unrepaired_chunks, list) {
546                 print_chunk_info(chunk, "  ");
547                 good++;
548                 total++;
549         }
550         printf("Unrecoverable Chunks:\n");
551         list_for_each_entry(chunk, &rc->bad_chunks, list) {
552                 print_chunk_info(chunk, "  ");
553                 bad++;
554                 total++;
555         }
556         printf("\n");
557         printf("Total Chunks:\t\t%d\n", total);
558         printf("  Recoverable:\t\t%d\n", good);
559         printf("  Unrecoverable:\t%d\n", bad);
560
561         printf("\n");
562         printf("Orphan Block Groups:\n");
563         list_for_each_entry(bg, &rc->bg.block_groups, list)
564                 print_block_group_info(bg, "  ");
565
566         printf("\n");
567         printf("Orphan Device Extents:\n");
568         list_for_each_entry(devext, &rc->devext.no_chunk_orphans, chunk_list)
569                 print_device_extent_info(devext, "  ");
570         printf("\n");
571 }
572
573 static int check_chunk_by_metadata(struct recover_control *rc,
574                                    struct btrfs_root *root,
575                                    struct chunk_record *chunk, int bg_only)
576 {
577         int ret;
578         int i;
579         int slot;
580         struct btrfs_path path;
581         struct btrfs_key key;
582         struct btrfs_root *dev_root;
583         struct stripe *stripe;
584         struct btrfs_dev_extent *dev_extent;
585         struct btrfs_block_group_item *bg_ptr;
586         struct extent_buffer *l;
587
588         btrfs_init_path(&path);
589
590         if (bg_only)
591                 goto bg_check;
592
593         dev_root = root->fs_info->dev_root;
594         for (i = 0; i < chunk->num_stripes; i++) {
595                 stripe = &chunk->stripes[i];
596
597                 key.objectid = stripe->devid;
598                 key.offset = stripe->offset;
599                 key.type = BTRFS_DEV_EXTENT_KEY;
600
601                 ret = btrfs_search_slot(NULL, dev_root, &key, &path, 0, 0);
602                 if (ret < 0) {
603                         fprintf(stderr, "Search device extent failed(%d)\n",
604                                 ret);
605                         btrfs_release_path(&path);
606                         return ret;
607                 } else if (ret > 0) {
608                         if (rc->verbose)
609                                 fprintf(stderr,
610                                         "No device extent[%llu, %llu]\n",
611                                         stripe->devid, stripe->offset);
612                         btrfs_release_path(&path);
613                         return -ENOENT;
614                 }
615                 l = path.nodes[0];
616                 slot = path.slots[0];
617                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
618                 if (chunk->offset !=
619                     btrfs_dev_extent_chunk_offset(l, dev_extent)) {
620                         if (rc->verbose)
621                                 fprintf(stderr,
622                                         "Device tree unmatch with chunks dev_extent[%llu, %llu], chunk[%llu, %llu]\n",
623                                         btrfs_dev_extent_chunk_offset(l,
624                                                                 dev_extent),
625                                         btrfs_dev_extent_length(l, dev_extent),
626                                         chunk->offset, chunk->length);
627                         btrfs_release_path(&path);
628                         return -ENOENT;
629                 }
630                 btrfs_release_path(&path);
631         }
632
633 bg_check:
634         key.objectid = chunk->offset;
635         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
636         key.offset = chunk->length;
637
638         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, &path,
639                                 0, 0);
640         if (ret < 0) {
641                 fprintf(stderr, "Search block group failed(%d)\n", ret);
642                 btrfs_release_path(&path);
643                 return ret;
644         } else if (ret > 0) {
645                 if (rc->verbose)
646                         fprintf(stderr, "No block group[%llu, %llu]\n",
647                                 key.objectid, key.offset);
648                 btrfs_release_path(&path);
649                 return -ENOENT;
650         }
651
652         l = path.nodes[0];
653         slot = path.slots[0];
654         bg_ptr = btrfs_item_ptr(l, slot, struct btrfs_block_group_item);
655         if (chunk->type_flags != btrfs_disk_block_group_flags(l, bg_ptr)) {
656                 if (rc->verbose)
657                         fprintf(stderr,
658                                 "Chunk[%llu, %llu]'s type(%llu) is differemt with Block Group's type(%llu)\n",
659                                 chunk->offset, chunk->length, chunk->type_flags,
660                                 btrfs_disk_block_group_flags(l, bg_ptr));
661                 btrfs_release_path(&path);
662                 return -ENOENT;
663         }
664         btrfs_release_path(&path);
665         return 0;
666 }
667
668 static int check_all_chunks_by_metadata(struct recover_control *rc,
669                                         struct btrfs_root *root)
670 {
671         struct chunk_record *chunk;
672         struct chunk_record *next;
673         LIST_HEAD(orphan_chunks);
674         int ret = 0;
675         int err;
676
677         list_for_each_entry_safe(chunk, next, &rc->good_chunks, list) {
678                 err = check_chunk_by_metadata(rc, root, chunk, 0);
679                 if (err) {
680                         if (err == -ENOENT)
681                                 list_move_tail(&chunk->list, &orphan_chunks);
682                         else if (err && !ret)
683                                 ret = err;
684                 }
685         }
686
687         list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
688                 err = check_chunk_by_metadata(rc, root, chunk, 1);
689                 if (err == -ENOENT)
690                         list_move_tail(&chunk->list, &orphan_chunks);
691                 else if (err && !ret)
692                         ret = err;
693         }
694
695         list_for_each_entry(chunk, &rc->bad_chunks, list) {
696                 err = check_chunk_by_metadata(rc, root, chunk, 1);
697                 if (err != -ENOENT && !ret)
698                         ret = err ? err : -EINVAL;
699         }
700         list_splice(&orphan_chunks, &rc->bad_chunks);
701         return ret;
702 }
703
704 static int extract_metadata_record(struct recover_control *rc,
705                                    struct extent_buffer *leaf)
706 {
707         struct btrfs_key key;
708         int ret = 0;
709         int i;
710         u32 nritems;
711
712         nritems = btrfs_header_nritems(leaf);
713         for (i = 0; i < nritems; i++) {
714                 btrfs_item_key_to_cpu(leaf, &key, i);
715                 switch (key.type) {
716                 case BTRFS_BLOCK_GROUP_ITEM_KEY:
717                         pthread_mutex_lock(&rc->rc_lock);
718                         ret = process_block_group_item(&rc->bg, leaf, &key, i);
719                         pthread_mutex_unlock(&rc->rc_lock);
720                         break;
721                 case BTRFS_CHUNK_ITEM_KEY:
722                         pthread_mutex_lock(&rc->rc_lock);
723                         ret = process_chunk_item(&rc->chunk, leaf, &key, i);
724                         pthread_mutex_unlock(&rc->rc_lock);
725                         break;
726                 case BTRFS_DEV_EXTENT_KEY:
727                         pthread_mutex_lock(&rc->rc_lock);
728                         ret = process_device_extent_item(&rc->devext, leaf,
729                                                          &key, i);
730                         pthread_mutex_unlock(&rc->rc_lock);
731                         break;
732                 }
733                 if (ret)
734                         break;
735         }
736         return ret;
737 }
738
739 static inline int is_super_block_address(u64 offset)
740 {
741         int i;
742
743         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
744                 if (offset == btrfs_sb_offset(i))
745                         return 1;
746         }
747         return 0;
748 }
749
750 static int scan_one_device(void *dev_scan_struct)
751 {
752         struct extent_buffer *buf;
753         u64 bytenr;
754         int ret = 0;
755         struct device_scan *dev_scan = (struct device_scan *)dev_scan_struct;
756         struct recover_control *rc = dev_scan->rc;
757         struct btrfs_device *device = dev_scan->dev;
758         int fd = dev_scan->fd;
759         int oldtype;
760
761         ret = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
762         if (ret)
763                 return 1;
764
765         buf = malloc(sizeof(*buf) + rc->leafsize);
766         if (!buf)
767                 return -ENOMEM;
768         buf->len = rc->leafsize;
769
770         bytenr = 0;
771         while (1) {
772                 dev_scan->bytenr = bytenr;
773
774                 if (is_super_block_address(bytenr))
775                         bytenr += rc->sectorsize;
776
777                 if (pread64(fd, buf->data, rc->leafsize, bytenr) <
778                     rc->leafsize)
779                         break;
780
781                 if (memcmp_extent_buffer(buf, rc->fs_devices->fsid,
782                                          btrfs_header_fsid(),
783                                          BTRFS_FSID_SIZE)) {
784                         bytenr += rc->sectorsize;
785                         continue;
786                 }
787
788                 if (verify_tree_block_csum_silent(buf, rc->csum_size)) {
789                         bytenr += rc->sectorsize;
790                         continue;
791                 }
792
793                 pthread_mutex_lock(&rc->rc_lock);
794                 ret = process_extent_buffer(&rc->eb_cache, buf, device, bytenr);
795                 pthread_mutex_unlock(&rc->rc_lock);
796                 if (ret)
797                         goto out;
798
799                 if (btrfs_header_level(buf) != 0)
800                         goto next_node;
801
802                 switch (btrfs_header_owner(buf)) {
803                 case BTRFS_EXTENT_TREE_OBJECTID:
804                 case BTRFS_DEV_TREE_OBJECTID:
805                         /* different tree use different generation */
806                         if (btrfs_header_generation(buf) > rc->generation)
807                                 break;
808                         ret = extract_metadata_record(rc, buf);
809                         if (ret)
810                                 goto out;
811                         break;
812                 case BTRFS_CHUNK_TREE_OBJECTID:
813                         if (btrfs_header_generation(buf) >
814                             rc->chunk_root_generation)
815                                 break;
816                         ret = extract_metadata_record(rc, buf);
817                         if (ret)
818                                 goto out;
819                         break;
820                 }
821 next_node:
822                 bytenr += rc->leafsize;
823         }
824 out:
825         close(fd);
826         free(buf);
827         return ret;
828 }
829
830 static int scan_devices(struct recover_control *rc)
831 {
832         int ret = 0;
833         int fd;
834         struct btrfs_device *dev;
835         struct device_scan *dev_scans;
836         pthread_t *t_scans;
837         long *t_rets;
838         int devnr = 0;
839         int devidx = 0;
840         int i;
841         int all_done;
842
843         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list)
844                 devnr++;
845         dev_scans = (struct device_scan *)malloc(sizeof(struct device_scan)
846                                                  * devnr);
847         if (!dev_scans)
848                 return -ENOMEM;
849         t_scans = (pthread_t *)malloc(sizeof(pthread_t) * devnr);
850         if (!t_scans)
851                 return -ENOMEM;
852         t_rets = (long *)malloc(sizeof(long) * devnr);
853         if (!t_rets)
854                 return -ENOMEM;
855
856         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
857                 fd = open(dev->name, O_RDONLY);
858                 if (fd < 0) {
859                         fprintf(stderr, "Failed to open device %s\n",
860                                 dev->name);
861                         ret = 1;
862                         goto out2;
863                 }
864                 dev_scans[devidx].rc = rc;
865                 dev_scans[devidx].dev = dev;
866                 dev_scans[devidx].fd = fd;
867                 dev_scans[devidx].bytenr = -1;
868                 devidx++;
869         }
870
871         for (i = 0; i < devidx; i++) {
872                 ret = pthread_create(&t_scans[i], NULL,
873                                      (void *)scan_one_device,
874                                      (void *)&dev_scans[i]);
875                 if (ret)
876                         goto out1;
877
878                 dev_scans[i].bytenr = 0;
879         }
880
881         while (1) {
882                 all_done = 1;
883                 for (i = 0; i < devidx; i++) {
884                         if (dev_scans[i].bytenr == -1)
885                                 continue;
886                         ret = pthread_tryjoin_np(t_scans[i],
887                                                  (void **)&t_rets[i]);
888                         if (ret == EBUSY) {
889                                 all_done = 0;
890                                 continue;
891                         }
892                         if (ret || t_rets[i]) {
893                                 ret = 1;
894                                 goto out1;
895                         }
896                         dev_scans[i].bytenr = -1;
897                 }
898
899                 printf("\rScanning: ");
900                 for (i = 0; i < devidx; i++) {
901                         if (dev_scans[i].bytenr == -1)
902                                 printf("%sDONE in dev%d",
903                                        i ? ", " : "", i);
904                         else
905                                 printf("%s%llu in dev%d",
906                                        i ? ", " : "", dev_scans[i].bytenr, i);
907                 }
908                 /* clear chars if exist in tail */
909                 printf("                ");
910                 printf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
911                 fflush(stdout);
912
913                 if (all_done) {
914                         printf("\n");
915                         break;
916                 }
917
918                 sleep(1);
919         }
920 out1:
921         for (i = 0; i < devidx; i++) {
922                 if (dev_scans[i].bytenr == -1)
923                         continue;
924                 pthread_cancel(t_scans[i]);
925         }
926 out2:
927         free(dev_scans);
928         free(t_scans);
929         free(t_rets);
930         return !!ret;
931 }
932
933 static int build_device_map_by_chunk_record(struct btrfs_root *root,
934                                             struct chunk_record *chunk)
935 {
936         int ret = 0;
937         int i;
938         u64 devid;
939         u8 uuid[BTRFS_UUID_SIZE];
940         u16 num_stripes;
941         struct btrfs_mapping_tree *map_tree;
942         struct map_lookup *map;
943         struct stripe *stripe;
944
945         map_tree = &root->fs_info->mapping_tree;
946         num_stripes = chunk->num_stripes;
947         map = malloc(btrfs_map_lookup_size(num_stripes));
948         if (!map)
949                 return -ENOMEM;
950         map->ce.start = chunk->offset;
951         map->ce.size = chunk->length;
952         map->num_stripes = num_stripes;
953         map->io_width = chunk->io_width;
954         map->io_align = chunk->io_align;
955         map->sector_size = chunk->sector_size;
956         map->stripe_len = chunk->stripe_len;
957         map->type = chunk->type_flags;
958         map->sub_stripes = chunk->sub_stripes;
959
960         for (i = 0, stripe = chunk->stripes; i < num_stripes; i++, stripe++) {
961                 devid = stripe->devid;
962                 memcpy(uuid, stripe->dev_uuid, BTRFS_UUID_SIZE);
963                 map->stripes[i].physical = stripe->offset;
964                 map->stripes[i].dev = btrfs_find_device(root, devid,
965                                                         uuid, NULL);
966                 if (!map->stripes[i].dev) {
967                         kfree(map);
968                         return -EIO;
969                 }
970         }
971
972         ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
973         return ret;
974 }
975
976 static int build_device_maps_by_chunk_records(struct recover_control *rc,
977                                               struct btrfs_root *root)
978 {
979         int ret = 0;
980         struct chunk_record *chunk;
981
982         list_for_each_entry(chunk, &rc->good_chunks, list) {
983                 ret = build_device_map_by_chunk_record(root, chunk);
984                 if (ret)
985                         return ret;
986         }
987         list_for_each_entry(chunk, &rc->rebuild_chunks, list) {
988                 ret = build_device_map_by_chunk_record(root, chunk);
989                 if (ret)
990                         return ret;
991         }
992         return ret;
993 }
994
995 static int block_group_remove_all_extent_items(struct btrfs_trans_handle *trans,
996                                                struct btrfs_root *root,
997                                                struct block_group_record *bg)
998 {
999         struct btrfs_fs_info *fs_info = root->fs_info;
1000         struct btrfs_key key;
1001         struct btrfs_path path;
1002         struct extent_buffer *leaf;
1003         u64 start = bg->objectid;
1004         u64 end = bg->objectid + bg->offset;
1005         u64 old_val;
1006         int nitems;
1007         int ret;
1008         int i;
1009         int del_s, del_nr;
1010
1011         btrfs_init_path(&path);
1012         root = root->fs_info->extent_root;
1013
1014         key.objectid = start;
1015         key.offset = 0;
1016         key.type = BTRFS_EXTENT_ITEM_KEY;
1017 again:
1018         ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
1019         if (ret < 0)
1020                 goto err;
1021         else if (ret > 0)
1022                 ret = 0;
1023
1024         leaf = path.nodes[0];
1025         nitems = btrfs_header_nritems(leaf);
1026         if (!nitems) {
1027                 /* The tree is empty. */
1028                 ret = 0;
1029                 goto err;
1030         }
1031
1032         if (path.slots[0] >= nitems) {
1033                 ret = btrfs_next_leaf(root, &path);
1034                 if (ret < 0)
1035                         goto err;
1036                 if (ret > 0) {
1037                         ret = 0;
1038                         goto err;
1039                 }
1040                 leaf = path.nodes[0];
1041                 btrfs_item_key_to_cpu(leaf, &key, 0);
1042                 if (key.objectid >= end)
1043                         goto err;
1044                 btrfs_release_path(&path);
1045                 goto again;
1046         }
1047
1048         del_nr = 0;
1049         del_s = -1;
1050         for (i = path.slots[0]; i < nitems; i++) {
1051                 btrfs_item_key_to_cpu(leaf, &key, i);
1052                 if (key.objectid >= end)
1053                         break;
1054
1055                 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1056                         if (del_nr == 0)
1057                                 continue;
1058                         else
1059                                 break;
1060                 }
1061
1062                 if (del_s == -1)
1063                         del_s = i;
1064                 del_nr++;
1065                 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
1066                     key.type == BTRFS_METADATA_ITEM_KEY) {
1067                         old_val = btrfs_super_bytes_used(fs_info->super_copy);
1068                         if (key.type == BTRFS_METADATA_ITEM_KEY)
1069                                 old_val += root->leafsize;
1070                         else
1071                                 old_val += key.offset;
1072                         btrfs_set_super_bytes_used(fs_info->super_copy,
1073                                                    old_val);
1074                 }
1075         }
1076
1077         if (del_nr) {
1078                 ret = btrfs_del_items(trans, root, &path, del_s, del_nr);
1079                 if (ret)
1080                         goto err;
1081         }
1082
1083         if (key.objectid < end) {
1084                 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1085                         key.objectid += root->sectorsize;
1086                         key.type = BTRFS_EXTENT_ITEM_KEY;
1087                         key.offset = 0;
1088                 }
1089                 btrfs_release_path(&path);
1090                 goto again;
1091         }
1092 err:
1093         btrfs_release_path(&path);
1094         return ret;
1095 }
1096
1097 static int block_group_free_all_extent(struct btrfs_trans_handle *trans,
1098                                        struct btrfs_root *root,
1099                                        struct block_group_record *bg)
1100 {
1101         struct btrfs_block_group_cache *cache;
1102         struct btrfs_fs_info *info;
1103         u64 start;
1104         u64 end;
1105
1106         info = root->fs_info;
1107         cache = btrfs_lookup_block_group(info, bg->objectid);
1108         if (!cache)
1109                 return -ENOENT;
1110
1111         start = cache->key.objectid;
1112         end = start + cache->key.offset - 1;
1113
1114         set_extent_bits(&info->block_group_cache, start, end,
1115                         BLOCK_GROUP_DIRTY, GFP_NOFS);
1116         set_extent_dirty(&info->free_space_cache, start, end, GFP_NOFS);
1117
1118         btrfs_set_block_group_used(&cache->item, 0);
1119
1120         return 0;
1121 }
1122
1123 static int remove_chunk_extent_item(struct btrfs_trans_handle *trans,
1124                                     struct recover_control *rc,
1125                                     struct btrfs_root *root)
1126 {
1127         struct chunk_record *chunk;
1128         int ret = 0;
1129
1130         list_for_each_entry(chunk, &rc->good_chunks, list) {
1131                 if (!(chunk->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1132                         continue;
1133                 ret = block_group_remove_all_extent_items(trans, root,
1134                                                           chunk->bg_rec);
1135                 if (ret)
1136                         return ret;
1137
1138                 ret = block_group_free_all_extent(trans, root, chunk->bg_rec);
1139                 if (ret)
1140                         return ret;
1141         }
1142         return ret;
1143 }
1144
1145 static int __rebuild_chunk_root(struct btrfs_trans_handle *trans,
1146                                 struct recover_control *rc,
1147                                 struct btrfs_root *root)
1148 {
1149         u64 min_devid = -1;
1150         struct btrfs_device *dev;
1151         struct extent_buffer *cow;
1152         struct btrfs_disk_key disk_key;
1153         int ret = 0;
1154
1155         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1156                 if (min_devid > dev->devid)
1157                         min_devid = dev->devid;
1158         }
1159         disk_key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1160         disk_key.type = BTRFS_DEV_ITEM_KEY;
1161         disk_key.offset = min_devid;
1162
1163         cow = btrfs_alloc_free_block(trans, root, root->nodesize,
1164                                      BTRFS_CHUNK_TREE_OBJECTID,
1165                                      &disk_key, 0, 0, 0);
1166         btrfs_set_header_bytenr(cow, cow->start);
1167         btrfs_set_header_generation(cow, trans->transid);
1168         btrfs_set_header_nritems(cow, 0);
1169         btrfs_set_header_level(cow, 0);
1170         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1171         btrfs_set_header_owner(cow, BTRFS_CHUNK_TREE_OBJECTID);
1172         write_extent_buffer(cow, root->fs_info->fsid,
1173                         btrfs_header_fsid(), BTRFS_FSID_SIZE);
1174
1175         write_extent_buffer(cow, root->fs_info->chunk_tree_uuid,
1176                         btrfs_header_chunk_tree_uuid(cow),
1177                         BTRFS_UUID_SIZE);
1178
1179         root->node = cow;
1180         btrfs_mark_buffer_dirty(cow);
1181
1182         return ret;
1183 }
1184
1185 static int __rebuild_device_items(struct btrfs_trans_handle *trans,
1186                                   struct recover_control *rc,
1187                                   struct btrfs_root *root)
1188 {
1189         struct btrfs_device *dev;
1190         struct btrfs_key key;
1191         struct btrfs_dev_item *dev_item;
1192         int ret = 0;
1193
1194         dev_item = malloc(sizeof(struct btrfs_dev_item));
1195         if (!dev_item)
1196                 return -ENOMEM;
1197
1198         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1199                 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1200                 key.type = BTRFS_DEV_ITEM_KEY;
1201                 key.offset = dev->devid;
1202
1203                 btrfs_set_stack_device_generation(dev_item, 0);
1204                 btrfs_set_stack_device_type(dev_item, dev->type);
1205                 btrfs_set_stack_device_id(dev_item, dev->devid);
1206                 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1207                 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1208                 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1209                 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1210                 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1211                 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1212                 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1213
1214                 ret = btrfs_insert_item(trans, root, &key,
1215                                         dev_item, sizeof(*dev_item));
1216         }
1217
1218         free(dev_item);
1219         return ret;
1220 }
1221
1222 static int __insert_chunk_item(struct btrfs_trans_handle *trans,
1223                                 struct chunk_record *chunk_rec,
1224                                 struct btrfs_root *chunk_root)
1225 {
1226         struct btrfs_key key;
1227         struct btrfs_chunk *chunk = NULL;
1228         int ret = 0;
1229
1230         chunk = create_chunk_item(chunk_rec);
1231         if (!chunk)
1232                 return -ENOMEM;
1233         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1234         key.type = BTRFS_CHUNK_ITEM_KEY;
1235         key.offset = chunk_rec->offset;
1236
1237         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1238                                 btrfs_chunk_item_size(chunk->num_stripes));
1239         free(chunk);
1240         return ret;
1241 }
1242
1243 static int __rebuild_chunk_items(struct btrfs_trans_handle *trans,
1244                                  struct recover_control *rc,
1245                                  struct btrfs_root *root)
1246 {
1247         struct btrfs_root *chunk_root;
1248         struct chunk_record *chunk_rec;
1249         int ret;
1250
1251         chunk_root = root->fs_info->chunk_root;
1252
1253         list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1254                 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1255                 if (ret)
1256                         return ret;
1257         }
1258         list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1259                 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1260                 if (ret)
1261                         return ret;
1262         }
1263         return 0;
1264 }
1265
1266 static int rebuild_chunk_tree(struct btrfs_trans_handle *trans,
1267                               struct recover_control *rc,
1268                               struct btrfs_root *root)
1269 {
1270         int ret = 0;
1271
1272         root = root->fs_info->chunk_root;
1273
1274         ret = __rebuild_chunk_root(trans, rc, root);
1275         if (ret)
1276                 return ret;
1277
1278         ret = __rebuild_device_items(trans, rc, root);
1279         if (ret)
1280                 return ret;
1281
1282         ret = __rebuild_chunk_items(trans, rc, root);
1283
1284         return ret;
1285 }
1286
1287 static int rebuild_sys_array(struct recover_control *rc,
1288                              struct btrfs_root *root)
1289 {
1290         struct btrfs_chunk *chunk;
1291         struct btrfs_key key;
1292         struct chunk_record *chunk_rec;
1293         int ret = 0;
1294         u16 num_stripes;
1295
1296         btrfs_set_super_sys_array_size(root->fs_info->super_copy, 0);
1297
1298         list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1299                 if (!(chunk_rec->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1300                         continue;
1301
1302                 num_stripes = chunk_rec->num_stripes;
1303                 chunk = create_chunk_item(chunk_rec);
1304                 if (!chunk) {
1305                         ret = -ENOMEM;
1306                         break;
1307                 }
1308
1309                 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1310                 key.type = BTRFS_CHUNK_ITEM_KEY;
1311                 key.offset = chunk_rec->offset;
1312
1313                 ret = btrfs_add_system_chunk(NULL, root, &key, chunk,
1314                                 btrfs_chunk_item_size(num_stripes));
1315                 free(chunk);
1316                 if (ret)
1317                         break;
1318         }
1319         return ret;
1320
1321 }
1322
1323 static int calculate_bg_used(struct btrfs_root *extent_root,
1324                              struct chunk_record *chunk_rec,
1325                              struct btrfs_path *path,
1326                              u64 *used)
1327 {
1328         struct extent_buffer *node;
1329         struct btrfs_key found_key;
1330         int slot;
1331         int ret = 0;
1332         u64 used_ret = 0;
1333
1334         while (1) {
1335                 node = path->nodes[0];
1336                 slot = path->slots[0];
1337                 btrfs_item_key_to_cpu(node, &found_key, slot);
1338                 if (found_key.objectid >= chunk_rec->offset + chunk_rec->length)
1339                         break;
1340                 if (found_key.type != BTRFS_METADATA_ITEM_KEY &&
1341                     found_key.type != BTRFS_EXTENT_DATA_KEY)
1342                         goto next;
1343                 if (found_key.type == BTRFS_METADATA_ITEM_KEY)
1344                         used_ret += extent_root->nodesize;
1345                 else
1346                         used_ret += found_key.offset;
1347 next:
1348                 if (slot + 1 < btrfs_header_nritems(node)) {
1349                         slot++;
1350                 } else {
1351                         ret = btrfs_next_leaf(extent_root, path);
1352                         if (ret > 0) {
1353                                 ret = 0;
1354                                 break;
1355                         }
1356                         if (ret < 0)
1357                                 break;
1358                 }
1359         }
1360         if (!ret)
1361                 *used = used_ret;
1362         return ret;
1363 }
1364
1365 static int __insert_block_group(struct btrfs_trans_handle *trans,
1366                                 struct chunk_record *chunk_rec,
1367                                 struct btrfs_root *extent_root,
1368                                 u64 used)
1369 {
1370         struct btrfs_block_group_item bg_item;
1371         struct btrfs_key key;
1372         int ret = 0;
1373
1374         btrfs_set_block_group_used(&bg_item, used);
1375         btrfs_set_block_group_chunk_objectid(&bg_item, used);
1376         btrfs_set_block_group_flags(&bg_item, chunk_rec->type_flags);
1377         key.objectid = chunk_rec->offset;
1378         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1379         key.offset = chunk_rec->length;
1380
1381         ret = btrfs_insert_item(trans, extent_root, &key, &bg_item,
1382                                 sizeof(bg_item));
1383         return ret;
1384 }
1385
1386 /*
1387  * Search through the extent tree to rebuild the 'used' member of the block
1388  * group.
1389  * However, since block group and extent item shares the extent tree,
1390  * the extent item may also missing.
1391  * In that case, we fill the 'used' with the length of the block group to
1392  * ensure no write into the block group.
1393  * Btrfsck will hate it but we will inform user to call '--init-extent-tree'
1394  * if possible, or just salvage as much data as possible from the fs.
1395  */
1396 static int rebuild_block_group(struct btrfs_trans_handle *trans,
1397                                struct recover_control *rc,
1398                                struct btrfs_root *root)
1399 {
1400         struct chunk_record *chunk_rec;
1401         struct btrfs_key search_key;
1402         struct btrfs_path *path;
1403         u64 used = 0;
1404         int ret = 0;
1405
1406         if (list_empty(&rc->rebuild_chunks))
1407                 return 0;
1408
1409         path = btrfs_alloc_path();
1410         if (!path)
1411                 return -ENOMEM;
1412         list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1413                 search_key.objectid = chunk_rec->offset;
1414                 search_key.type = BTRFS_EXTENT_ITEM_KEY;
1415                 search_key.offset = 0;
1416                 ret = btrfs_search_slot(NULL, root->fs_info->extent_root,
1417                                         &search_key, path, 0, 0);
1418                 if (ret < 0)
1419                         goto out;
1420                 ret = calculate_bg_used(root->fs_info->extent_root,
1421                                         chunk_rec, path, &used);
1422                 /*
1423                  * Extent tree is damaged, better to rebuild the whole extent
1424                  * tree. Currently, change the used to chunk's len to prevent
1425                  * write/block reserve happening in that block group.
1426                  */
1427                 if (ret < 0) {
1428                         fprintf(stderr,
1429                                 "Fail to search extent tree for block group: [%llu,%llu]\n",
1430                                 chunk_rec->offset,
1431                                 chunk_rec->offset + chunk_rec->length);
1432                         fprintf(stderr,
1433                                 "Mark the block group full to prevent block rsv problems\n");
1434                         used = chunk_rec->length;
1435                 }
1436                 btrfs_release_path(path);
1437                 ret = __insert_block_group(trans, chunk_rec,
1438                                            root->fs_info->extent_root,
1439                                            used);
1440                 if (ret < 0)
1441                         goto out;
1442         }
1443 out:
1444         btrfs_free_path(path);
1445         return ret;
1446 }
1447
1448 static struct btrfs_root *
1449 open_ctree_with_broken_chunk(struct recover_control *rc)
1450 {
1451         struct btrfs_fs_info *fs_info;
1452         struct btrfs_super_block *disk_super;
1453         struct extent_buffer *eb;
1454         u32 sectorsize;
1455         u32 nodesize;
1456         u32 leafsize;
1457         u32 stripesize;
1458         int ret;
1459
1460         fs_info = btrfs_new_fs_info(1, BTRFS_SUPER_INFO_OFFSET);
1461         if (!fs_info) {
1462                 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1463                 return ERR_PTR(-ENOMEM);
1464         }
1465         fs_info->is_chunk_recover = 1;
1466
1467         fs_info->fs_devices = rc->fs_devices;
1468         ret = btrfs_open_devices(fs_info->fs_devices, O_RDWR);
1469         if (ret)
1470                 goto out;
1471
1472         disk_super = fs_info->super_copy;
1473         ret = btrfs_read_dev_super(fs_info->fs_devices->latest_bdev,
1474                                    disk_super, fs_info->super_bytenr, 1);
1475         if (ret) {
1476                 fprintf(stderr, "No valid btrfs found\n");
1477                 goto out_devices;
1478         }
1479
1480         memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1481
1482         ret = btrfs_check_fs_compatibility(disk_super, 1);
1483         if (ret)
1484                 goto out_devices;
1485
1486         nodesize = btrfs_super_nodesize(disk_super);
1487         leafsize = btrfs_super_leafsize(disk_super);
1488         sectorsize = btrfs_super_sectorsize(disk_super);
1489         stripesize = btrfs_super_stripesize(disk_super);
1490
1491         __setup_root(nodesize, leafsize, sectorsize, stripesize,
1492                      fs_info->chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
1493
1494         ret = build_device_maps_by_chunk_records(rc, fs_info->chunk_root);
1495         if (ret)
1496                 goto out_cleanup;
1497
1498         ret = btrfs_setup_all_roots(fs_info, 0, 0);
1499         if (ret)
1500                 goto out_failed;
1501
1502         eb = fs_info->tree_root->node;
1503         read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1504                            btrfs_header_chunk_tree_uuid(eb),
1505                            BTRFS_UUID_SIZE);
1506
1507         return fs_info->fs_root;
1508 out_failed:
1509         btrfs_release_all_roots(fs_info);
1510 out_cleanup:
1511         btrfs_cleanup_all_caches(fs_info);
1512 out_devices:
1513         btrfs_close_devices(fs_info->fs_devices);
1514 out:
1515         btrfs_free_fs_info(fs_info);
1516         return ERR_PTR(ret);
1517 }
1518
1519 static int recover_prepare(struct recover_control *rc, char *path)
1520 {
1521         int ret;
1522         int fd;
1523         struct btrfs_super_block *sb;
1524         struct btrfs_fs_devices *fs_devices;
1525
1526         ret = 0;
1527         fd = open(path, O_RDONLY);
1528         if (fd < 0) {
1529                 fprintf(stderr, "open %s\n error.\n", path);
1530                 return -1;
1531         }
1532
1533         sb = malloc(BTRFS_SUPER_INFO_SIZE);
1534         if (!sb) {
1535                 fprintf(stderr, "allocating memory for sb failed.\n");
1536                 ret = -ENOMEM;
1537                 goto fail_close_fd;
1538         }
1539
1540         ret = btrfs_read_dev_super(fd, sb, BTRFS_SUPER_INFO_OFFSET, 1);
1541         if (ret) {
1542                 fprintf(stderr, "read super block error\n");
1543                 goto fail_free_sb;
1544         }
1545
1546         rc->sectorsize = btrfs_super_sectorsize(sb);
1547         rc->leafsize = btrfs_super_leafsize(sb);
1548         rc->generation = btrfs_super_generation(sb);
1549         rc->chunk_root_generation = btrfs_super_chunk_root_generation(sb);
1550         rc->csum_size = btrfs_super_csum_size(sb);
1551
1552         /* if seed, the result of scanning below will be partial */
1553         if (btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_SEEDING) {
1554                 fprintf(stderr, "this device is seed device\n");
1555                 ret = -1;
1556                 goto fail_free_sb;
1557         }
1558
1559         ret = btrfs_scan_fs_devices(fd, path, &fs_devices, 0, 1, 0);
1560         if (ret)
1561                 goto fail_free_sb;
1562
1563         rc->fs_devices = fs_devices;
1564
1565         if (rc->verbose)
1566                 print_all_devices(&rc->fs_devices->devices);
1567
1568 fail_free_sb:
1569         free(sb);
1570 fail_close_fd:
1571         close(fd);
1572         return ret;
1573 }
1574
1575 static int btrfs_get_device_extents(u64 chunk_object,
1576                                     struct list_head *orphan_devexts,
1577                                     struct list_head *ret_list)
1578 {
1579         struct device_extent_record *devext;
1580         struct device_extent_record *next;
1581         int count = 0;
1582
1583         list_for_each_entry_safe(devext, next, orphan_devexts, chunk_list) {
1584                 if (devext->chunk_offset == chunk_object) {
1585                         list_move_tail(&devext->chunk_list, ret_list);
1586                         count++;
1587                 }
1588         }
1589         return count;
1590 }
1591
1592 static int calc_num_stripes(u64 type)
1593 {
1594         if (type & (BTRFS_BLOCK_GROUP_RAID0 |
1595                     BTRFS_BLOCK_GROUP_RAID10 |
1596                     BTRFS_BLOCK_GROUP_RAID5 |
1597                     BTRFS_BLOCK_GROUP_RAID6))
1598                 return 0;
1599         else if (type & (BTRFS_BLOCK_GROUP_RAID1 |
1600                          BTRFS_BLOCK_GROUP_DUP))
1601                 return 2;
1602         else
1603                 return 1;
1604 }
1605
1606 static inline int calc_sub_nstripes(u64 type)
1607 {
1608         if (type & BTRFS_BLOCK_GROUP_RAID10)
1609                 return 2;
1610         else
1611                 return 1;
1612 }
1613
1614 static int btrfs_verify_device_extents(struct block_group_record *bg,
1615                                        struct list_head *devexts, int ndevexts)
1616 {
1617         struct device_extent_record *devext;
1618         u64 strpie_length;
1619         int expected_num_stripes;
1620
1621         expected_num_stripes = calc_num_stripes(bg->flags);
1622         if (expected_num_stripes && expected_num_stripes != ndevexts)
1623                 return 1;
1624
1625         strpie_length = calc_stripe_length(bg->flags, bg->offset, ndevexts);
1626         list_for_each_entry(devext, devexts, chunk_list) {
1627                 if (devext->length != strpie_length)
1628                         return 1;
1629         }
1630         return 0;
1631 }
1632
1633 static int btrfs_rebuild_unordered_chunk_stripes(struct recover_control *rc,
1634                                                  struct chunk_record *chunk)
1635 {
1636         struct device_extent_record *devext;
1637         struct btrfs_device *device;
1638         int i;
1639
1640         devext = list_first_entry(&chunk->dextents, struct device_extent_record,
1641                                   chunk_list);
1642         for (i = 0; i < chunk->num_stripes; i++) {
1643                 chunk->stripes[i].devid = devext->objectid;
1644                 chunk->stripes[i].offset = devext->offset;
1645                 device = btrfs_find_device_by_devid(rc->fs_devices,
1646                                                     devext->objectid,
1647                                                     0);
1648                 if (!device)
1649                         return -ENOENT;
1650                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1651                                                   devext->objectid,
1652                                                   1));
1653                 memcpy(chunk->stripes[i].dev_uuid, device->uuid,
1654                        BTRFS_UUID_SIZE);
1655                 devext = list_next_entry(devext, chunk_list);
1656         }
1657         return 0;
1658 }
1659
1660 static int btrfs_calc_stripe_index(struct chunk_record *chunk, u64 logical)
1661 {
1662         u64 offset = logical - chunk->offset;
1663         int stripe_nr;
1664         int nr_data_stripes;
1665         int index;
1666
1667         stripe_nr = offset / chunk->stripe_len;
1668         if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID0) {
1669                 index = stripe_nr % chunk->num_stripes;
1670         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID10) {
1671                 index = stripe_nr % (chunk->num_stripes / chunk->sub_stripes);
1672                 index *= chunk->sub_stripes;
1673         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5) {
1674                 nr_data_stripes = chunk->num_stripes - 1;
1675                 index = stripe_nr % nr_data_stripes;
1676                 stripe_nr /= nr_data_stripes;
1677                 index = (index + stripe_nr) % chunk->num_stripes;
1678         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6) {
1679                 nr_data_stripes = chunk->num_stripes - 2;
1680                 index = stripe_nr % nr_data_stripes;
1681                 stripe_nr /= nr_data_stripes;
1682                 index = (index + stripe_nr) % chunk->num_stripes;
1683         } else {
1684                 return -1;
1685         }
1686         return index;
1687 }
1688
1689 /* calc the logical offset which is the start of the next stripe. */
1690 static inline u64 btrfs_next_stripe_logical_offset(struct chunk_record *chunk,
1691                                                    u64 logical)
1692 {
1693         u64 offset = logical - chunk->offset;
1694
1695         offset /= chunk->stripe_len;
1696         offset *= chunk->stripe_len;
1697         offset += chunk->stripe_len;
1698
1699         return offset + chunk->offset;
1700 }
1701
1702 static int is_extent_record_in_device_extent(struct extent_record *er,
1703                                              struct device_extent_record *dext,
1704                                              int *mirror)
1705 {
1706         int i;
1707
1708         for (i = 0; i < er->nmirrors; i++) {
1709                 if (er->devices[i]->devid == dext->objectid &&
1710                     er->offsets[i] >= dext->offset &&
1711                     er->offsets[i] < dext->offset + dext->length) {
1712                         *mirror = i;
1713                         return 1;
1714                 }
1715         }
1716         return 0;
1717 }
1718
1719 static int
1720 btrfs_rebuild_ordered_meta_chunk_stripes(struct recover_control *rc,
1721                                          struct chunk_record *chunk)
1722 {
1723         u64 start = chunk->offset;
1724         u64 end = chunk->offset + chunk->length;
1725         struct cache_extent *cache;
1726         struct extent_record *er;
1727         struct device_extent_record *devext;
1728         struct device_extent_record *next;
1729         struct btrfs_device *device;
1730         LIST_HEAD(devexts);
1731         int index;
1732         int mirror;
1733         int ret;
1734
1735         cache = lookup_cache_extent(&rc->eb_cache,
1736                                     start, chunk->length);
1737         if (!cache) {
1738                 /* No used space, we can reorder the stripes freely. */
1739                 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1740                 return ret;
1741         }
1742
1743         list_splice_init(&chunk->dextents, &devexts);
1744 again:
1745         er = container_of(cache, struct extent_record, cache);
1746         index = btrfs_calc_stripe_index(chunk, er->cache.start);
1747         BUG_ON(index == -1);
1748         if (chunk->stripes[index].devid)
1749                 goto next;
1750         list_for_each_entry_safe(devext, next, &devexts, chunk_list) {
1751                 if (is_extent_record_in_device_extent(er, devext, &mirror)) {
1752                         chunk->stripes[index].devid = devext->objectid;
1753                         chunk->stripes[index].offset = devext->offset;
1754                         memcpy(chunk->stripes[index].dev_uuid,
1755                                er->devices[mirror]->uuid,
1756                                BTRFS_UUID_SIZE);
1757                         index++;
1758                         list_move(&devext->chunk_list, &chunk->dextents);
1759                 }
1760         }
1761 next:
1762         start = btrfs_next_stripe_logical_offset(chunk, er->cache.start);
1763         if (start >= end)
1764                 goto no_extent_record;
1765
1766         cache = lookup_cache_extent(&rc->eb_cache, start, end - start);
1767         if (cache)
1768                 goto again;
1769 no_extent_record:
1770         if (list_empty(&devexts))
1771                 return 0;
1772
1773         if (chunk->type_flags & (BTRFS_BLOCK_GROUP_RAID5 |
1774                                  BTRFS_BLOCK_GROUP_RAID6)) {
1775                 /* Fixme: try to recover the order by the parity block. */
1776                 list_splice_tail(&devexts, &chunk->dextents);
1777                 return -EINVAL;
1778         }
1779
1780         /* There is no data on the lost stripes, we can reorder them freely. */
1781         for (index = 0; index < chunk->num_stripes; index++) {
1782                 if (chunk->stripes[index].devid)
1783                         continue;
1784
1785                 devext = list_first_entry(&devexts,
1786                                           struct device_extent_record,
1787                                            chunk_list);
1788                 list_move(&devext->chunk_list, &chunk->dextents);
1789
1790                 chunk->stripes[index].devid = devext->objectid;
1791                 chunk->stripes[index].offset = devext->offset;
1792                 device = btrfs_find_device_by_devid(rc->fs_devices,
1793                                                     devext->objectid,
1794                                                     0);
1795                 if (!device) {
1796                         list_splice_tail(&devexts, &chunk->dextents);
1797                         return -EINVAL;
1798                 }
1799                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1800                                                   devext->objectid,
1801                                                   1));
1802                 memcpy(chunk->stripes[index].dev_uuid, device->uuid,
1803                        BTRFS_UUID_SIZE);
1804         }
1805         return 0;
1806 }
1807
1808 #define BTRFS_ORDERED_RAID      (BTRFS_BLOCK_GROUP_RAID0 |      \
1809                                  BTRFS_BLOCK_GROUP_RAID10 |     \
1810                                  BTRFS_BLOCK_GROUP_RAID5 |      \
1811                                  BTRFS_BLOCK_GROUP_RAID6)
1812
1813 static int btrfs_rebuild_chunk_stripes(struct recover_control *rc,
1814                                        struct chunk_record *chunk)
1815 {
1816         int ret;
1817
1818         /*
1819          * All the data in the system metadata chunk will be dropped,
1820          * so we need not guarantee that the data is right or not, that
1821          * is we can reorder the stripes in the system metadata chunk.
1822          */
1823         if ((chunk->type_flags & BTRFS_BLOCK_GROUP_METADATA) &&
1824             (chunk->type_flags & BTRFS_ORDERED_RAID))
1825                 ret =btrfs_rebuild_ordered_meta_chunk_stripes(rc, chunk);
1826         else if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA) &&
1827                  (chunk->type_flags & BTRFS_ORDERED_RAID))
1828                 ret = 1;        /* Be handled after the fs is opened. */
1829         else
1830                 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1831
1832         return ret;
1833 }
1834
1835 static int next_csum(struct btrfs_root *root,
1836                      struct extent_buffer **leaf,
1837                      struct btrfs_path *path,
1838                      int *slot,
1839                      u64 *csum_offset,
1840                      u32 *tree_csum,
1841                      u64 end,
1842                      struct btrfs_key *key)
1843 {
1844         int ret = 0;
1845         struct btrfs_root *csum_root = root->fs_info->csum_root;
1846         struct btrfs_csum_item *csum_item;
1847         u32 blocksize = root->sectorsize;
1848         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1849         int csums_in_item = btrfs_item_size_nr(*leaf, *slot) / csum_size;
1850
1851         if (*csum_offset >= csums_in_item) {
1852                 ++(*slot);
1853                 *csum_offset = 0;
1854                 if (*slot >= btrfs_header_nritems(*leaf)) {
1855                         ret = btrfs_next_leaf(csum_root, path);
1856                         if (ret < 0)
1857                                 return -1;
1858                         else if (ret > 0)
1859                                 return 1;
1860                         *leaf = path->nodes[0];
1861                         *slot = path->slots[0];
1862                 }
1863                 btrfs_item_key_to_cpu(*leaf, key, *slot);
1864         }
1865
1866         if (key->offset + (*csum_offset) * blocksize >= end)
1867                 return 2;
1868         csum_item = btrfs_item_ptr(*leaf, *slot, struct btrfs_csum_item);
1869         csum_item = (struct btrfs_csum_item *)((unsigned char *)csum_item
1870                                              + (*csum_offset) * csum_size);
1871         read_extent_buffer(*leaf, tree_csum,
1872                           (unsigned long)csum_item, csum_size);
1873         return ret;
1874 }
1875
1876 static u64 calc_data_offset(struct btrfs_key *key,
1877                             struct chunk_record *chunk,
1878                             u64 dev_offset,
1879                             u64 csum_offset,
1880                             u32 blocksize)
1881 {
1882         u64 data_offset;
1883         int logical_stripe_nr;
1884         int dev_stripe_nr;
1885         int nr_data_stripes;
1886
1887         data_offset = key->offset + csum_offset * blocksize - chunk->offset;
1888         nr_data_stripes = chunk->num_stripes;
1889
1890         if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5)
1891                 nr_data_stripes -= 1;
1892         else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6)
1893                 nr_data_stripes -= 2;
1894
1895         logical_stripe_nr = data_offset / chunk->stripe_len;
1896         dev_stripe_nr = logical_stripe_nr / nr_data_stripes;
1897
1898         data_offset -= logical_stripe_nr * chunk->stripe_len;
1899         data_offset += dev_stripe_nr * chunk->stripe_len;
1900
1901         return dev_offset + data_offset;
1902 }
1903
1904 static int check_one_csum(int fd, u64 start, u32 len, u32 tree_csum)
1905 {
1906         char *data;
1907         int ret = 0;
1908         u32 csum_result = ~(u32)0;
1909
1910         data = malloc(len);
1911         if (!data)
1912                 return -1;
1913         ret = pread64(fd, data, len, start);
1914         if (ret < 0 || ret != len) {
1915                 ret = -1;
1916                 goto out;
1917         }
1918         ret = 0;
1919         csum_result = btrfs_csum_data(NULL, data, csum_result, len);
1920         btrfs_csum_final(csum_result, (char *)&csum_result);
1921         if (csum_result != tree_csum)
1922                 ret = 1;
1923 out:
1924         free(data);
1925         return ret;
1926 }
1927
1928 static u64 item_end_offset(struct btrfs_root *root, struct btrfs_key *key,
1929                            struct extent_buffer *leaf, int slot) {
1930         u32 blocksize = root->sectorsize;
1931         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1932
1933         u64 offset = btrfs_item_size_nr(leaf, slot);
1934         offset /= csum_size;
1935         offset *= blocksize;
1936         offset += key->offset;
1937
1938         return offset;
1939 }
1940
1941 static int insert_stripe(struct list_head *devexts,
1942                          struct recover_control *rc,
1943                          struct chunk_record *chunk,
1944                          int index) {
1945         struct device_extent_record *devext;
1946         struct btrfs_device *dev;
1947
1948         devext = list_entry(devexts->next, struct device_extent_record,
1949                             chunk_list);
1950         dev = btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1951                                         0);
1952         if (!dev)
1953                 return 1;
1954         BUG_ON(btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1955                                         1));
1956
1957         chunk->stripes[index].devid = devext->objectid;
1958         chunk->stripes[index].offset = devext->offset;
1959         memcpy(chunk->stripes[index].dev_uuid, dev->uuid, BTRFS_UUID_SIZE);
1960
1961         list_move(&devext->chunk_list, &chunk->dextents);
1962
1963         return 0;
1964 }
1965
1966 static inline int count_devext_records(struct list_head *record_list)
1967 {
1968         int num_of_records = 0;
1969         struct device_extent_record *devext;
1970
1971         list_for_each_entry(devext, record_list, chunk_list)
1972                 num_of_records++;
1973
1974         return num_of_records;
1975 }
1976
1977 static int fill_chunk_up(struct chunk_record *chunk, struct list_head *devexts,
1978                          struct recover_control *rc)
1979 {
1980         int ret = 0;
1981         int i;
1982
1983         for (i = 0; i < chunk->num_stripes; i++) {
1984                 if (!chunk->stripes[i].devid) {
1985                         ret = insert_stripe(devexts, rc, chunk, i);
1986                         if (ret)
1987                                 break;
1988                 }
1989         }
1990
1991         return ret;
1992 }
1993
1994 #define EQUAL_STRIPE (1 << 0)
1995
1996 static int rebuild_raid_data_chunk_stripes(struct recover_control *rc,
1997                                            struct btrfs_root *root,
1998                                            struct chunk_record *chunk,
1999                                            u8 *flags)
2000 {
2001         int i;
2002         int ret = 0;
2003         int slot;
2004         struct btrfs_path path;
2005         struct btrfs_key prev_key;
2006         struct btrfs_key key;
2007         struct btrfs_root *csum_root;
2008         struct extent_buffer *leaf;
2009         struct device_extent_record *devext;
2010         struct device_extent_record *next;
2011         struct btrfs_device *dev;
2012         u64 start = chunk->offset;
2013         u64 end = start + chunk->stripe_len;
2014         u64 chunk_end = chunk->offset + chunk->length;
2015         u64 csum_offset = 0;
2016         u64 data_offset;
2017         u32 blocksize = root->sectorsize;
2018         u32 tree_csum;
2019         int index = 0;
2020         int num_unordered = 0;
2021         LIST_HEAD(unordered);
2022         LIST_HEAD(candidates);
2023
2024         csum_root = root->fs_info->csum_root;
2025         btrfs_init_path(&path);
2026         list_splice_init(&chunk->dextents, &candidates);
2027 again:
2028         if (list_is_last(candidates.next, &candidates))
2029                 goto out;
2030
2031         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
2032         key.type = BTRFS_EXTENT_CSUM_KEY;
2033         key.offset = start;
2034
2035         ret = btrfs_search_slot(NULL, csum_root, &key, &path, 0, 0);
2036         if (ret < 0) {
2037                 fprintf(stderr, "Search csum failed(%d)\n", ret);
2038                 goto fail_out;
2039         }
2040         leaf = path.nodes[0];
2041         slot = path.slots[0];
2042         if (ret > 0) {
2043                 if (slot >= btrfs_header_nritems(leaf)) {
2044                         ret = btrfs_next_leaf(csum_root, &path);
2045                         if (ret < 0) {
2046                                 fprintf(stderr,
2047                                         "Walk tree failed(%d)\n", ret);
2048                                 goto fail_out;
2049                         } else if (ret > 0) {
2050                                 slot = btrfs_header_nritems(leaf) - 1;
2051                                 btrfs_item_key_to_cpu(leaf, &key, slot);
2052                                 if (item_end_offset(root, &key, leaf, slot)
2053                                                                 > start) {
2054                                         csum_offset = start - key.offset;
2055                                         csum_offset /= blocksize;
2056                                         goto next_csum;
2057                                 }
2058                                 goto next_stripe;
2059                         }
2060                         leaf = path.nodes[0];
2061                         slot = path.slots[0];
2062                 }
2063                 btrfs_item_key_to_cpu(leaf, &key, slot);
2064                 ret = btrfs_previous_item(csum_root, &path, 0,
2065                                           BTRFS_EXTENT_CSUM_KEY);
2066                 if (ret < 0)
2067                         goto fail_out;
2068                 else if (ret > 0) {
2069                         if (key.offset >= end)
2070                                 goto next_stripe;
2071                         else
2072                                 goto next_csum;
2073                 }
2074                 leaf = path.nodes[0];
2075                 slot = path.slots[0];
2076
2077                 btrfs_item_key_to_cpu(leaf, &prev_key, slot);
2078                 if (item_end_offset(root, &prev_key, leaf, slot) > start) {
2079                         csum_offset = start - prev_key.offset;
2080                         csum_offset /= blocksize;
2081                         btrfs_item_key_to_cpu(leaf, &key, slot);
2082                 } else {
2083                         if (key.offset >= end)
2084                                 goto next_stripe;
2085                 }
2086
2087                 if (key.offset + csum_offset * blocksize > chunk_end)
2088                         goto out;
2089         }
2090 next_csum:
2091         ret = next_csum(root, &leaf, &path, &slot, &csum_offset, &tree_csum,
2092                         end, &key);
2093         if (ret < 0) {
2094                 fprintf(stderr, "Fetch csum failed\n");
2095                 goto fail_out;
2096         } else if (ret == 1) {
2097                 if (!(*flags & EQUAL_STRIPE))
2098                         *flags |= EQUAL_STRIPE;
2099                 goto out;
2100         } else if (ret == 2)
2101                 goto next_stripe;
2102
2103         list_for_each_entry_safe(devext, next, &candidates, chunk_list) {
2104                 data_offset = calc_data_offset(&key, chunk, devext->offset,
2105                                                csum_offset, blocksize);
2106                 dev = btrfs_find_device_by_devid(rc->fs_devices,
2107                                                  devext->objectid, 0);
2108                 if (!dev) {
2109                         ret = 1;
2110                         goto fail_out;
2111                 }
2112                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
2113                                                   devext->objectid, 1));
2114
2115                 ret = check_one_csum(dev->fd, data_offset, blocksize,
2116                                      tree_csum);
2117                 if (ret < 0)
2118                         goto fail_out;
2119                 else if (ret > 0)
2120                         list_move(&devext->chunk_list, &unordered);
2121         }
2122
2123         if (list_empty(&candidates)) {
2124                 num_unordered = count_devext_records(&unordered);
2125                 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6
2126                                         && num_unordered == 2) {
2127                         btrfs_release_path(&path);
2128                         ret = fill_chunk_up(chunk, &unordered, rc);
2129                         return ret;
2130                 }
2131
2132                 goto next_stripe;
2133         }
2134
2135         if (list_is_last(candidates.next, &candidates)) {
2136                 index = btrfs_calc_stripe_index(chunk,
2137                         key.offset + csum_offset * blocksize);
2138                 BUG_ON(index == -1);
2139                 if (chunk->stripes[index].devid)
2140                         goto next_stripe;
2141                 ret = insert_stripe(&candidates, rc, chunk, index);
2142                 if (ret)
2143                         goto fail_out;
2144         } else {
2145                 csum_offset++;
2146                 goto next_csum;
2147         }
2148 next_stripe:
2149         start = btrfs_next_stripe_logical_offset(chunk, start);
2150         end = min(start + chunk->stripe_len, chunk_end);
2151         list_splice_init(&unordered, &candidates);
2152         btrfs_release_path(&path);
2153         csum_offset = 0;
2154         if (end < chunk_end)
2155                 goto again;
2156 out:
2157         ret = 0;
2158         list_splice_init(&candidates, &unordered);
2159         num_unordered = count_devext_records(&unordered);
2160         if (num_unordered == 1) {
2161                 for (i = 0; i < chunk->num_stripes; i++) {
2162                         if (!chunk->stripes[i].devid) {
2163                                 index = i;
2164                                 break;
2165                         }
2166                 }
2167                 ret = insert_stripe(&unordered, rc, chunk, index);
2168                 if (ret)
2169                         goto fail_out;
2170         } else {
2171                 if ((num_unordered == 2 && chunk->type_flags
2172                         & BTRFS_BLOCK_GROUP_RAID5)
2173                  || (num_unordered == 3 && chunk->type_flags
2174                         & BTRFS_BLOCK_GROUP_RAID6)) {
2175                         ret = fill_chunk_up(chunk, &unordered, rc);
2176                 }
2177         }
2178 fail_out:
2179         ret = !!ret || (list_empty(&unordered) ? 0 : 1);
2180         list_splice_init(&candidates, &chunk->dextents);
2181         list_splice_init(&unordered, &chunk->dextents);
2182         btrfs_release_path(&path);
2183
2184         return ret;
2185 }
2186
2187 static int btrfs_rebuild_ordered_data_chunk_stripes(struct recover_control *rc,
2188                                            struct btrfs_root *root)
2189 {
2190         struct chunk_record *chunk;
2191         struct chunk_record *next;
2192         int ret = 0;
2193         int err;
2194         u8 flags;
2195
2196         list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
2197                 if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA)
2198                  && (chunk->type_flags & BTRFS_ORDERED_RAID)) {
2199                         flags = 0;
2200                         err = rebuild_raid_data_chunk_stripes(rc, root, chunk,
2201                                                               &flags);
2202                         if (err) {
2203                                 list_move(&chunk->list, &rc->bad_chunks);
2204                                 if (flags & EQUAL_STRIPE)
2205                                         fprintf(stderr,
2206                         "Failure: too many equal stripes in chunk[%llu %llu]\n",
2207                                                 chunk->offset, chunk->length);
2208                                 if (!ret)
2209                                         ret = err;
2210                         } else
2211                                 list_move(&chunk->list, &rc->good_chunks);
2212                 }
2213         }
2214         return ret;
2215 }
2216
2217 static int btrfs_recover_chunks(struct recover_control *rc)
2218 {
2219         struct chunk_record *chunk;
2220         struct block_group_record *bg;
2221         struct block_group_record *next;
2222         LIST_HEAD(new_chunks);
2223         LIST_HEAD(devexts);
2224         int nstripes;
2225         int ret;
2226
2227         /* create the chunk by block group */
2228         list_for_each_entry_safe(bg, next, &rc->bg.block_groups, list) {
2229                 nstripes = btrfs_get_device_extents(bg->objectid,
2230                                                     &rc->devext.no_chunk_orphans,
2231                                                     &devexts);
2232                 chunk = malloc(btrfs_chunk_record_size(nstripes));
2233                 if (!chunk)
2234                         return -ENOMEM;
2235                 memset(chunk, 0, btrfs_chunk_record_size(nstripes));
2236                 INIT_LIST_HEAD(&chunk->dextents);
2237                 chunk->bg_rec = bg;
2238                 chunk->cache.start = bg->objectid;
2239                 chunk->cache.size = bg->offset;
2240                 chunk->objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2241                 chunk->type = BTRFS_CHUNK_ITEM_KEY;
2242                 chunk->offset = bg->objectid;
2243                 chunk->generation = bg->generation;
2244                 chunk->length = bg->offset;
2245                 chunk->owner = BTRFS_CHUNK_TREE_OBJECTID;
2246                 chunk->stripe_len = BTRFS_STRIPE_LEN;
2247                 chunk->type_flags = bg->flags;
2248                 chunk->io_width = BTRFS_STRIPE_LEN;
2249                 chunk->io_align = BTRFS_STRIPE_LEN;
2250                 chunk->sector_size = rc->sectorsize;
2251                 chunk->sub_stripes = calc_sub_nstripes(bg->flags);
2252
2253                 ret = insert_cache_extent(&rc->chunk, &chunk->cache);
2254                 BUG_ON(ret);
2255
2256                 list_del_init(&bg->list);
2257                 if (!nstripes) {
2258                         list_add_tail(&chunk->list, &rc->bad_chunks);
2259                         continue;
2260                 }
2261
2262                 list_splice_init(&devexts, &chunk->dextents);
2263
2264                 ret = btrfs_verify_device_extents(bg, &devexts, nstripes);
2265                 if (ret) {
2266                         list_add_tail(&chunk->list, &rc->bad_chunks);
2267                         continue;
2268                 }
2269
2270                 chunk->num_stripes = nstripes;
2271                 ret = btrfs_rebuild_chunk_stripes(rc, chunk);
2272                 if (ret > 0)
2273                         list_add_tail(&chunk->list, &rc->unrepaired_chunks);
2274                 else if (ret < 0)
2275                         list_add_tail(&chunk->list, &rc->bad_chunks);
2276                 else
2277                         list_add_tail(&chunk->list, &rc->good_chunks);
2278         }
2279         /*
2280          * Don't worry about the lost orphan device extents, they don't
2281          * have its chunk and block group, they must be the old ones that
2282          * we have dropped.
2283          */
2284         return 0;
2285 }
2286
2287 static inline int is_chunk_overlap(struct chunk_record *chunk1,
2288                                    struct chunk_record *chunk2)
2289 {
2290         if (chunk1->offset >= chunk2->offset + chunk2->length ||
2291             chunk1->offset + chunk1->length <= chunk2->offset)
2292                 return 0;
2293         return 1;
2294 }
2295
2296 /* Move invalid(overlap with good chunks) rebuild chunks to bad chunk list */
2297 static void validate_rebuild_chunks(struct recover_control *rc)
2298 {
2299         struct chunk_record *good;
2300         struct chunk_record *rebuild;
2301         struct chunk_record *tmp;
2302
2303         list_for_each_entry_safe(rebuild, tmp, &rc->rebuild_chunks, list) {
2304                 list_for_each_entry(good, &rc->good_chunks, list) {
2305                         if (is_chunk_overlap(rebuild, good)) {
2306                                 list_move_tail(&rebuild->list,
2307                                                &rc->bad_chunks);
2308                                 break;
2309                         }
2310                 }
2311         }
2312 }
2313
2314 /*
2315  * Return 0 when successful, < 0 on error and > 0 if aborted by user
2316  */
2317 int btrfs_recover_chunk_tree(char *path, int verbose, int yes)
2318 {
2319         int ret = 0;
2320         struct btrfs_root *root = NULL;
2321         struct btrfs_trans_handle *trans;
2322         struct recover_control rc;
2323
2324         init_recover_control(&rc, verbose, yes);
2325
2326         ret = recover_prepare(&rc, path);
2327         if (ret) {
2328                 fprintf(stderr, "recover prepare error\n");
2329                 return ret;
2330         }
2331
2332         ret = scan_devices(&rc);
2333         if (ret) {
2334                 fprintf(stderr, "scan chunk headers error\n");
2335                 goto fail_rc;
2336         }
2337
2338         if (cache_tree_empty(&rc.chunk) &&
2339             cache_tree_empty(&rc.bg.tree) &&
2340             cache_tree_empty(&rc.devext.tree)) {
2341                 fprintf(stderr, "no recoverable chunk\n");
2342                 goto fail_rc;
2343         }
2344
2345         print_scan_result(&rc);
2346
2347         ret = check_chunks(&rc.chunk, &rc.bg, &rc.devext, &rc.good_chunks,
2348                            &rc.bad_chunks, &rc.rebuild_chunks, 1);
2349         if (ret) {
2350                 if (!list_empty(&rc.bg.block_groups) ||
2351                     !list_empty(&rc.devext.no_chunk_orphans)) {
2352                         ret = btrfs_recover_chunks(&rc);
2353                         if (ret)
2354                                 goto fail_rc;
2355                 }
2356         } else {
2357                 print_check_result(&rc);
2358                 printf("Check chunks successfully with no orphans\n");
2359                 goto fail_rc;
2360         }
2361         validate_rebuild_chunks(&rc);
2362         print_check_result(&rc);
2363
2364         root = open_ctree_with_broken_chunk(&rc);
2365         if (IS_ERR(root)) {
2366                 fprintf(stderr, "open with broken chunk error\n");
2367                 ret = PTR_ERR(root);
2368                 goto fail_rc;
2369         }
2370
2371         ret = check_all_chunks_by_metadata(&rc, root);
2372         if (ret) {
2373                 fprintf(stderr, "The chunks in memory can not match the metadata of the fs. Repair failed.\n");
2374                 goto fail_close_ctree;
2375         }
2376
2377         ret = btrfs_rebuild_ordered_data_chunk_stripes(&rc, root);
2378         if (ret) {
2379                 fprintf(stderr, "Failed to rebuild ordered chunk stripes.\n");
2380                 goto fail_close_ctree;
2381         }
2382
2383         if (!rc.yes) {
2384                 ret = ask_user("We are going to rebuild the chunk tree on disk, it might destroy the old metadata on the disk, Are you sure?");
2385                 if (!ret) {
2386                         ret = 1;
2387                         goto fail_close_ctree;
2388                 }
2389         }
2390
2391         trans = btrfs_start_transaction(root, 1);
2392         ret = remove_chunk_extent_item(trans, &rc, root);
2393         BUG_ON(ret);
2394
2395         ret = rebuild_chunk_tree(trans, &rc, root);
2396         BUG_ON(ret);
2397
2398         ret = rebuild_sys_array(&rc, root);
2399         BUG_ON(ret);
2400
2401         ret = rebuild_block_group(trans, &rc, root);
2402         if (ret) {
2403                 printf("Fail to rebuild block groups.\n");
2404                 printf("Recommend to run 'btrfs check --init-extent-tree <dev>' after recovery\n");
2405         }
2406
2407         btrfs_commit_transaction(trans, root);
2408 fail_close_ctree:
2409         close_ctree(root);
2410 fail_rc:
2411         free_recover_control(&rc);
2412         return ret;
2413 }