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