btrfs-progs: use on-stack buffer in recover_prepare
[platform/upstream/btrfs-progs.git] / chunk-recover.c
1 /*
2  * Copyright (C) 2013 FUJITSU LIMITED.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include "kerncompat.h"
20 #include "androidcompat.h"
21
22 #include <stdio.h>
23 #include <stdio_ext.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <uuid/uuid.h>
30 #include <pthread.h>
31
32 #include "list.h"
33 #include "radix-tree.h"
34 #include "ctree.h"
35 #include "extent-cache.h"
36 #include "disk-io.h"
37 #include "volumes.h"
38 #include "transaction.h"
39 #include "crc32c.h"
40 #include "utils.h"
41 #include "btrfsck.h"
42 #include "commands.h"
43
44 struct recover_control {
45         int verbose;
46         int yes;
47
48         u16 csum_size;
49         u32 sectorsize;
50         u32 leafsize;
51         u64 generation;
52         u64 chunk_root_generation;
53
54         struct btrfs_fs_devices *fs_devices;
55
56         struct cache_tree chunk;
57         struct block_group_tree bg;
58         struct device_extent_tree devext;
59         struct cache_tree eb_cache;
60
61         struct list_head good_chunks;
62         struct list_head bad_chunks;
63         struct list_head rebuild_chunks;
64         struct list_head unrepaired_chunks;
65         pthread_mutex_t rc_lock;
66 };
67
68 struct extent_record {
69         struct cache_extent cache;
70         u64 generation;
71         u8 csum[BTRFS_CSUM_SIZE];
72         struct btrfs_device *devices[BTRFS_MAX_MIRRORS];
73         u64 offsets[BTRFS_MAX_MIRRORS];
74         int nmirrors;
75 };
76
77 struct device_scan {
78         struct recover_control *rc;
79         struct btrfs_device *dev;
80         int fd;
81         u64 bytenr;
82 };
83
84 static struct extent_record *btrfs_new_extent_record(struct extent_buffer *eb)
85 {
86         struct extent_record *rec;
87
88         rec = calloc(1, sizeof(*rec));
89         if (!rec) {
90                 fprintf(stderr, "Fail to allocate memory for extent record.\n");
91                 exit(1);
92         }
93
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 search 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                 dev_scan->bytenr = bytenr;
772
773                 if (is_super_block_address(bytenr))
774                         bytenr += rc->sectorsize;
775
776                 if (pread64(fd, buf->data, rc->leafsize, bytenr) <
777                     rc->leafsize)
778                         break;
779
780                 if (memcmp_extent_buffer(buf, rc->fs_devices->fsid,
781                                          btrfs_header_fsid(),
782                                          BTRFS_FSID_SIZE)) {
783                         bytenr += rc->sectorsize;
784                         continue;
785                 }
786
787                 if (verify_tree_block_csum_silent(buf, rc->csum_size)) {
788                         bytenr += rc->sectorsize;
789                         continue;
790                 }
791
792                 pthread_mutex_lock(&rc->rc_lock);
793                 ret = process_extent_buffer(&rc->eb_cache, buf, device, bytenr);
794                 pthread_mutex_unlock(&rc->rc_lock);
795                 if (ret)
796                         goto out;
797
798                 if (btrfs_header_level(buf) != 0)
799                         goto next_node;
800
801                 switch (btrfs_header_owner(buf)) {
802                 case BTRFS_EXTENT_TREE_OBJECTID:
803                 case BTRFS_DEV_TREE_OBJECTID:
804                         /* different tree use different generation */
805                         if (btrfs_header_generation(buf) > rc->generation)
806                                 break;
807                         ret = extract_metadata_record(rc, buf);
808                         if (ret)
809                                 goto out;
810                         break;
811                 case BTRFS_CHUNK_TREE_OBJECTID:
812                         if (btrfs_header_generation(buf) >
813                             rc->chunk_root_generation)
814                                 break;
815                         ret = extract_metadata_record(rc, buf);
816                         if (ret)
817                                 goto out;
818                         break;
819                 }
820 next_node:
821                 bytenr += rc->leafsize;
822         }
823 out:
824         close(fd);
825         free(buf);
826         return ret;
827 }
828
829 static int scan_devices(struct recover_control *rc)
830 {
831         int ret = 0;
832         int fd;
833         struct btrfs_device *dev;
834         struct device_scan *dev_scans;
835         pthread_t *t_scans;
836         long *t_rets;
837         int devnr = 0;
838         int devidx = 0;
839         int i;
840         int all_done;
841
842         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list)
843                 devnr++;
844         dev_scans = (struct device_scan *)malloc(sizeof(struct device_scan)
845                                                  * devnr);
846         if (!dev_scans)
847                 return -ENOMEM;
848         t_scans = (pthread_t *)malloc(sizeof(pthread_t) * devnr);
849         if (!t_scans) {
850                 free(dev_scans);
851                 return -ENOMEM;
852         }
853         t_rets = (long *)malloc(sizeof(long) * devnr);
854         if (!t_rets) {
855                 free(dev_scans);
856                 free(t_scans);
857                 return -ENOMEM;
858         }
859
860         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
861                 fd = open(dev->name, O_RDONLY);
862                 if (fd < 0) {
863                         fprintf(stderr, "Failed to open device %s\n",
864                                 dev->name);
865                         ret = 1;
866                         goto out2;
867                 }
868                 dev_scans[devidx].rc = rc;
869                 dev_scans[devidx].dev = dev;
870                 dev_scans[devidx].fd = fd;
871                 dev_scans[devidx].bytenr = -1;
872                 devidx++;
873         }
874
875         for (i = 0; i < devidx; i++) {
876                 ret = pthread_create(&t_scans[i], NULL,
877                                      (void *)scan_one_device,
878                                      (void *)&dev_scans[i]);
879                 if (ret)
880                         goto out1;
881
882                 dev_scans[i].bytenr = 0;
883         }
884
885         while (1) {
886                 all_done = 1;
887                 for (i = 0; i < devidx; i++) {
888                         if (dev_scans[i].bytenr == -1)
889                                 continue;
890                         ret = pthread_tryjoin_np(t_scans[i],
891                                                  (void **)&t_rets[i]);
892                         if (ret == EBUSY) {
893                                 all_done = 0;
894                                 continue;
895                         }
896                         if (ret || t_rets[i]) {
897                                 ret = 1;
898                                 goto out1;
899                         }
900                         dev_scans[i].bytenr = -1;
901                 }
902
903                 printf("\rScanning: ");
904                 for (i = 0; i < devidx; i++) {
905                         if (dev_scans[i].bytenr == -1)
906                                 printf("%sDONE in dev%d",
907                                        i ? ", " : "", i);
908                         else
909                                 printf("%s%llu in dev%d",
910                                        i ? ", " : "", dev_scans[i].bytenr, i);
911                 }
912                 /* clear chars if exist in tail */
913                 printf("                ");
914                 printf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
915                 fflush(stdout);
916
917                 if (all_done) {
918                         printf("\n");
919                         break;
920                 }
921
922                 sleep(1);
923         }
924 out1:
925         for (i = 0; i < devidx; i++) {
926                 if (dev_scans[i].bytenr == -1)
927                         continue;
928                 pthread_cancel(t_scans[i]);
929         }
930 out2:
931         free(dev_scans);
932         free(t_scans);
933         free(t_rets);
934         return !!ret;
935 }
936
937 static int build_device_map_by_chunk_record(struct btrfs_root *root,
938                                             struct chunk_record *chunk)
939 {
940         int ret = 0;
941         int i;
942         u64 devid;
943         u8 uuid[BTRFS_UUID_SIZE];
944         u16 num_stripes;
945         struct btrfs_mapping_tree *map_tree;
946         struct map_lookup *map;
947         struct stripe *stripe;
948
949         map_tree = &root->fs_info->mapping_tree;
950         num_stripes = chunk->num_stripes;
951         map = malloc(btrfs_map_lookup_size(num_stripes));
952         if (!map)
953                 return -ENOMEM;
954         map->ce.start = chunk->offset;
955         map->ce.size = chunk->length;
956         map->num_stripes = num_stripes;
957         map->io_width = chunk->io_width;
958         map->io_align = chunk->io_align;
959         map->sector_size = chunk->sector_size;
960         map->stripe_len = chunk->stripe_len;
961         map->type = chunk->type_flags;
962         map->sub_stripes = chunk->sub_stripes;
963
964         for (i = 0, stripe = chunk->stripes; i < num_stripes; i++, stripe++) {
965                 devid = stripe->devid;
966                 memcpy(uuid, stripe->dev_uuid, BTRFS_UUID_SIZE);
967                 map->stripes[i].physical = stripe->offset;
968                 map->stripes[i].dev = btrfs_find_device(root, devid,
969                                                         uuid, NULL);
970                 if (!map->stripes[i].dev) {
971                         kfree(map);
972                         return -EIO;
973                 }
974         }
975
976         ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
977         return ret;
978 }
979
980 static int build_device_maps_by_chunk_records(struct recover_control *rc,
981                                               struct btrfs_root *root)
982 {
983         int ret = 0;
984         struct chunk_record *chunk;
985
986         list_for_each_entry(chunk, &rc->good_chunks, list) {
987                 ret = build_device_map_by_chunk_record(root, chunk);
988                 if (ret)
989                         return ret;
990         }
991         list_for_each_entry(chunk, &rc->rebuild_chunks, list) {
992                 ret = build_device_map_by_chunk_record(root, chunk);
993                 if (ret)
994                         return ret;
995         }
996         return ret;
997 }
998
999 static int block_group_remove_all_extent_items(struct btrfs_trans_handle *trans,
1000                                                struct btrfs_root *root,
1001                                                struct block_group_record *bg)
1002 {
1003         struct btrfs_fs_info *fs_info = root->fs_info;
1004         struct btrfs_key key;
1005         struct btrfs_path path;
1006         struct extent_buffer *leaf;
1007         u64 start = bg->objectid;
1008         u64 end = bg->objectid + bg->offset;
1009         u64 old_val;
1010         int nitems;
1011         int ret;
1012         int i;
1013         int del_s, del_nr;
1014
1015         btrfs_init_path(&path);
1016         root = root->fs_info->extent_root;
1017
1018         key.objectid = start;
1019         key.offset = 0;
1020         key.type = BTRFS_EXTENT_ITEM_KEY;
1021 again:
1022         ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
1023         if (ret < 0)
1024                 goto err;
1025         else if (ret > 0)
1026                 ret = 0;
1027
1028         leaf = path.nodes[0];
1029         nitems = btrfs_header_nritems(leaf);
1030         if (!nitems) {
1031                 /* The tree is empty. */
1032                 ret = 0;
1033                 goto err;
1034         }
1035
1036         if (path.slots[0] >= nitems) {
1037                 ret = btrfs_next_leaf(root, &path);
1038                 if (ret < 0)
1039                         goto err;
1040                 if (ret > 0) {
1041                         ret = 0;
1042                         goto err;
1043                 }
1044                 leaf = path.nodes[0];
1045                 btrfs_item_key_to_cpu(leaf, &key, 0);
1046                 if (key.objectid >= end)
1047                         goto err;
1048                 btrfs_release_path(&path);
1049                 goto again;
1050         }
1051
1052         del_nr = 0;
1053         del_s = -1;
1054         for (i = path.slots[0]; i < nitems; i++) {
1055                 btrfs_item_key_to_cpu(leaf, &key, i);
1056                 if (key.objectid >= end)
1057                         break;
1058
1059                 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1060                         if (del_nr == 0)
1061                                 continue;
1062                         else
1063                                 break;
1064                 }
1065
1066                 if (del_s == -1)
1067                         del_s = i;
1068                 del_nr++;
1069                 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
1070                     key.type == BTRFS_METADATA_ITEM_KEY) {
1071                         old_val = btrfs_super_bytes_used(fs_info->super_copy);
1072                         if (key.type == BTRFS_METADATA_ITEM_KEY)
1073                                 old_val += root->leafsize;
1074                         else
1075                                 old_val += key.offset;
1076                         btrfs_set_super_bytes_used(fs_info->super_copy,
1077                                                    old_val);
1078                 }
1079         }
1080
1081         if (del_nr) {
1082                 ret = btrfs_del_items(trans, root, &path, del_s, del_nr);
1083                 if (ret)
1084                         goto err;
1085         }
1086
1087         if (key.objectid < end) {
1088                 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1089                         key.objectid += root->sectorsize;
1090                         key.type = BTRFS_EXTENT_ITEM_KEY;
1091                         key.offset = 0;
1092                 }
1093                 btrfs_release_path(&path);
1094                 goto again;
1095         }
1096 err:
1097         btrfs_release_path(&path);
1098         return ret;
1099 }
1100
1101 static int block_group_free_all_extent(struct btrfs_root *root,
1102                                        struct block_group_record *bg)
1103 {
1104         struct btrfs_block_group_cache *cache;
1105         struct btrfs_fs_info *info;
1106         u64 start;
1107         u64 end;
1108
1109         info = root->fs_info;
1110         cache = btrfs_lookup_block_group(info, bg->objectid);
1111         if (!cache)
1112                 return -ENOENT;
1113
1114         start = cache->key.objectid;
1115         end = start + cache->key.offset - 1;
1116
1117         set_extent_bits(&info->block_group_cache, start, end,
1118                         BLOCK_GROUP_DIRTY, GFP_NOFS);
1119         set_extent_dirty(&info->free_space_cache, start, end, GFP_NOFS);
1120
1121         btrfs_set_block_group_used(&cache->item, 0);
1122
1123         return 0;
1124 }
1125
1126 static int remove_chunk_extent_item(struct btrfs_trans_handle *trans,
1127                                     struct recover_control *rc,
1128                                     struct btrfs_root *root)
1129 {
1130         struct chunk_record *chunk;
1131         int ret = 0;
1132
1133         list_for_each_entry(chunk, &rc->good_chunks, list) {
1134                 if (!(chunk->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1135                         continue;
1136                 ret = block_group_remove_all_extent_items(trans, root,
1137                                                           chunk->bg_rec);
1138                 if (ret)
1139                         return ret;
1140
1141                 ret = block_group_free_all_extent(root, chunk->bg_rec);
1142                 if (ret)
1143                         return ret;
1144         }
1145         return ret;
1146 }
1147
1148 static int __rebuild_chunk_root(struct btrfs_trans_handle *trans,
1149                                 struct recover_control *rc,
1150                                 struct btrfs_root *root)
1151 {
1152         u64 min_devid = -1;
1153         struct btrfs_device *dev;
1154         struct extent_buffer *cow;
1155         struct btrfs_disk_key disk_key;
1156         int ret = 0;
1157
1158         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1159                 if (min_devid > dev->devid)
1160                         min_devid = dev->devid;
1161         }
1162         disk_key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1163         disk_key.type = BTRFS_DEV_ITEM_KEY;
1164         disk_key.offset = min_devid;
1165
1166         cow = btrfs_alloc_free_block(trans, root, root->nodesize,
1167                                      BTRFS_CHUNK_TREE_OBJECTID,
1168                                      &disk_key, 0, 0, 0);
1169         btrfs_set_header_bytenr(cow, cow->start);
1170         btrfs_set_header_generation(cow, trans->transid);
1171         btrfs_set_header_nritems(cow, 0);
1172         btrfs_set_header_level(cow, 0);
1173         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1174         btrfs_set_header_owner(cow, BTRFS_CHUNK_TREE_OBJECTID);
1175         write_extent_buffer(cow, root->fs_info->fsid,
1176                         btrfs_header_fsid(), BTRFS_FSID_SIZE);
1177
1178         write_extent_buffer(cow, root->fs_info->chunk_tree_uuid,
1179                         btrfs_header_chunk_tree_uuid(cow),
1180                         BTRFS_UUID_SIZE);
1181
1182         root->node = cow;
1183         btrfs_mark_buffer_dirty(cow);
1184
1185         return ret;
1186 }
1187
1188 static int __rebuild_device_items(struct btrfs_trans_handle *trans,
1189                                   struct recover_control *rc,
1190                                   struct btrfs_root *root)
1191 {
1192         struct btrfs_device *dev;
1193         struct btrfs_key key;
1194         struct btrfs_dev_item dev_item_tmp;
1195         struct btrfs_dev_item *dev_item = &dev_item_tmp;
1196         int ret = 0;
1197
1198         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1199                 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1200                 key.type = BTRFS_DEV_ITEM_KEY;
1201                 key.offset = dev->devid;
1202
1203                 btrfs_set_stack_device_generation(dev_item, 0);
1204                 btrfs_set_stack_device_type(dev_item, dev->type);
1205                 btrfs_set_stack_device_id(dev_item, dev->devid);
1206                 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1207                 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1208                 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1209                 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1210                 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1211                 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1212                 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1213
1214                 ret = btrfs_insert_item(trans, root, &key,
1215                                         dev_item, sizeof(*dev_item));
1216         }
1217
1218         return ret;
1219 }
1220
1221 static int __insert_chunk_item(struct btrfs_trans_handle *trans,
1222                                 struct chunk_record *chunk_rec,
1223                                 struct btrfs_root *chunk_root)
1224 {
1225         struct btrfs_key key;
1226         struct btrfs_chunk *chunk = NULL;
1227         int ret = 0;
1228
1229         chunk = create_chunk_item(chunk_rec);
1230         if (!chunk)
1231                 return -ENOMEM;
1232         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1233         key.type = BTRFS_CHUNK_ITEM_KEY;
1234         key.offset = chunk_rec->offset;
1235
1236         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1237                                 btrfs_chunk_item_size(chunk->num_stripes));
1238         free(chunk);
1239         return ret;
1240 }
1241
1242 static int __rebuild_chunk_items(struct btrfs_trans_handle *trans,
1243                                  struct recover_control *rc,
1244                                  struct btrfs_root *root)
1245 {
1246         struct btrfs_root *chunk_root;
1247         struct chunk_record *chunk_rec;
1248         int ret;
1249
1250         chunk_root = root->fs_info->chunk_root;
1251
1252         list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1253                 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1254                 if (ret)
1255                         return ret;
1256         }
1257         list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1258                 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1259                 if (ret)
1260                         return ret;
1261         }
1262         return 0;
1263 }
1264
1265 static int rebuild_chunk_tree(struct btrfs_trans_handle *trans,
1266                               struct recover_control *rc,
1267                               struct btrfs_root *root)
1268 {
1269         int ret = 0;
1270
1271         root = root->fs_info->chunk_root;
1272
1273         ret = __rebuild_chunk_root(trans, rc, root);
1274         if (ret)
1275                 return ret;
1276
1277         ret = __rebuild_device_items(trans, rc, root);
1278         if (ret)
1279                 return ret;
1280
1281         ret = __rebuild_chunk_items(trans, rc, root);
1282
1283         return ret;
1284 }
1285
1286 static int rebuild_sys_array(struct recover_control *rc,
1287                              struct btrfs_root *root)
1288 {
1289         struct btrfs_chunk *chunk;
1290         struct btrfs_key key;
1291         struct chunk_record *chunk_rec;
1292         int ret = 0;
1293         u16 num_stripes;
1294
1295         btrfs_set_super_sys_array_size(root->fs_info->super_copy, 0);
1296
1297         list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1298                 if (!(chunk_rec->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1299                         continue;
1300
1301                 num_stripes = chunk_rec->num_stripes;
1302                 chunk = create_chunk_item(chunk_rec);
1303                 if (!chunk) {
1304                         ret = -ENOMEM;
1305                         break;
1306                 }
1307
1308                 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1309                 key.type = BTRFS_CHUNK_ITEM_KEY;
1310                 key.offset = chunk_rec->offset;
1311
1312                 ret = btrfs_add_system_chunk(NULL, root, &key, chunk,
1313                                 btrfs_chunk_item_size(num_stripes));
1314                 free(chunk);
1315                 if (ret)
1316                         break;
1317         }
1318         return ret;
1319
1320 }
1321
1322 static int calculate_bg_used(struct btrfs_root *extent_root,
1323                              struct chunk_record *chunk_rec,
1324                              struct btrfs_path *path,
1325                              u64 *used)
1326 {
1327         struct extent_buffer *node;
1328         struct btrfs_key found_key;
1329         int slot;
1330         int ret = 0;
1331         u64 used_ret = 0;
1332
1333         while (1) {
1334                 node = path->nodes[0];
1335                 slot = path->slots[0];
1336                 btrfs_item_key_to_cpu(node, &found_key, slot);
1337                 if (found_key.objectid >= chunk_rec->offset + chunk_rec->length)
1338                         break;
1339                 if (found_key.type != BTRFS_METADATA_ITEM_KEY &&
1340                     found_key.type != BTRFS_EXTENT_DATA_KEY)
1341                         goto next;
1342                 if (found_key.type == BTRFS_METADATA_ITEM_KEY)
1343                         used_ret += extent_root->nodesize;
1344                 else
1345                         used_ret += found_key.offset;
1346 next:
1347                 if (slot + 1 < btrfs_header_nritems(node)) {
1348                         slot++;
1349                 } else {
1350                         ret = btrfs_next_leaf(extent_root, path);
1351                         if (ret > 0) {
1352                                 ret = 0;
1353                                 break;
1354                         }
1355                         if (ret < 0)
1356                                 break;
1357                 }
1358         }
1359         if (!ret)
1360                 *used = used_ret;
1361         return ret;
1362 }
1363
1364 static int __insert_block_group(struct btrfs_trans_handle *trans,
1365                                 struct chunk_record *chunk_rec,
1366                                 struct btrfs_root *extent_root,
1367                                 u64 used)
1368 {
1369         struct btrfs_block_group_item bg_item;
1370         struct btrfs_key key;
1371         int ret = 0;
1372
1373         btrfs_set_block_group_used(&bg_item, used);
1374         btrfs_set_block_group_chunk_objectid(&bg_item, used);
1375         btrfs_set_block_group_flags(&bg_item, chunk_rec->type_flags);
1376         key.objectid = chunk_rec->offset;
1377         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1378         key.offset = chunk_rec->length;
1379
1380         ret = btrfs_insert_item(trans, extent_root, &key, &bg_item,
1381                                 sizeof(bg_item));
1382         return ret;
1383 }
1384
1385 /*
1386  * Search through the extent tree to rebuild the 'used' member of the block
1387  * group.
1388  * However, since block group and extent item shares the extent tree,
1389  * the extent item may also missing.
1390  * In that case, we fill the 'used' with the length of the block group to
1391  * ensure no write into the block group.
1392  * Btrfsck will hate it but we will inform user to call '--init-extent-tree'
1393  * if possible, or just salvage as much data as possible from the fs.
1394  */
1395 static int rebuild_block_group(struct btrfs_trans_handle *trans,
1396                                struct recover_control *rc,
1397                                struct btrfs_root *root)
1398 {
1399         struct chunk_record *chunk_rec;
1400         struct btrfs_key search_key;
1401         struct btrfs_path *path;
1402         u64 used = 0;
1403         int ret = 0;
1404
1405         if (list_empty(&rc->rebuild_chunks))
1406                 return 0;
1407
1408         path = btrfs_alloc_path();
1409         if (!path)
1410                 return -ENOMEM;
1411         list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1412                 search_key.objectid = chunk_rec->offset;
1413                 search_key.type = BTRFS_EXTENT_ITEM_KEY;
1414                 search_key.offset = 0;
1415                 ret = btrfs_search_slot(NULL, root->fs_info->extent_root,
1416                                         &search_key, path, 0, 0);
1417                 if (ret < 0)
1418                         goto out;
1419                 ret = calculate_bg_used(root->fs_info->extent_root,
1420                                         chunk_rec, path, &used);
1421                 /*
1422                  * Extent tree is damaged, better to rebuild the whole extent
1423                  * tree. Currently, change the used to chunk's len to prevent
1424                  * write/block reserve happening in that block group.
1425                  */
1426                 if (ret < 0) {
1427                         fprintf(stderr,
1428                                 "Fail to search extent tree for block group: [%llu,%llu]\n",
1429                                 chunk_rec->offset,
1430                                 chunk_rec->offset + chunk_rec->length);
1431                         fprintf(stderr,
1432                                 "Mark the block group full to prevent block rsv problems\n");
1433                         used = chunk_rec->length;
1434                 }
1435                 btrfs_release_path(path);
1436                 ret = __insert_block_group(trans, chunk_rec,
1437                                            root->fs_info->extent_root,
1438                                            used);
1439                 if (ret < 0)
1440                         goto out;
1441         }
1442 out:
1443         btrfs_free_path(path);
1444         return ret;
1445 }
1446
1447 static struct btrfs_root *
1448 open_ctree_with_broken_chunk(struct recover_control *rc)
1449 {
1450         struct btrfs_fs_info *fs_info;
1451         struct btrfs_super_block *disk_super;
1452         struct extent_buffer *eb;
1453         u32 sectorsize;
1454         u32 nodesize;
1455         u32 leafsize;
1456         u32 stripesize;
1457         int ret;
1458
1459         fs_info = btrfs_new_fs_info(1, BTRFS_SUPER_INFO_OFFSET);
1460         if (!fs_info) {
1461                 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1462                 return ERR_PTR(-ENOMEM);
1463         }
1464         fs_info->is_chunk_recover = 1;
1465
1466         fs_info->fs_devices = rc->fs_devices;
1467         ret = btrfs_open_devices(fs_info->fs_devices, O_RDWR);
1468         if (ret)
1469                 goto out;
1470
1471         disk_super = fs_info->super_copy;
1472         ret = btrfs_read_dev_super(fs_info->fs_devices->latest_bdev,
1473                                    disk_super, fs_info->super_bytenr, 1);
1474         if (ret) {
1475                 fprintf(stderr, "No valid btrfs found\n");
1476                 goto out_devices;
1477         }
1478
1479         memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1480
1481         ret = btrfs_check_fs_compatibility(disk_super, 1);
1482         if (ret)
1483                 goto out_devices;
1484
1485         nodesize = btrfs_super_nodesize(disk_super);
1486         leafsize = btrfs_super_leafsize(disk_super);
1487         sectorsize = btrfs_super_sectorsize(disk_super);
1488         stripesize = btrfs_super_stripesize(disk_super);
1489
1490         __setup_root(nodesize, leafsize, sectorsize, stripesize,
1491                      fs_info->chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
1492
1493         ret = build_device_maps_by_chunk_records(rc, fs_info->chunk_root);
1494         if (ret)
1495                 goto out_cleanup;
1496
1497         ret = btrfs_setup_all_roots(fs_info, 0, 0);
1498         if (ret)
1499                 goto out_failed;
1500
1501         eb = fs_info->tree_root->node;
1502         read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1503                            btrfs_header_chunk_tree_uuid(eb),
1504                            BTRFS_UUID_SIZE);
1505
1506         return fs_info->fs_root;
1507 out_failed:
1508         btrfs_release_all_roots(fs_info);
1509 out_cleanup:
1510         btrfs_cleanup_all_caches(fs_info);
1511 out_devices:
1512         btrfs_close_devices(fs_info->fs_devices);
1513 out:
1514         btrfs_free_fs_info(fs_info);
1515         return ERR_PTR(ret);
1516 }
1517
1518 static int recover_prepare(struct recover_control *rc, char *path)
1519 {
1520         int ret;
1521         int fd;
1522         struct btrfs_super_block *sb;
1523         char buf[BTRFS_SUPER_INFO_SIZE];
1524         struct btrfs_fs_devices *fs_devices;
1525
1526         ret = 0;
1527         fd = open(path, O_RDONLY);
1528         if (fd < 0) {
1529                 fprintf(stderr, "open %s\n error.\n", path);
1530                 return -1;
1531         }
1532
1533         sb = (struct btrfs_super_block*)buf;
1534         ret = btrfs_read_dev_super(fd, sb, BTRFS_SUPER_INFO_OFFSET, 1);
1535         if (ret) {
1536                 fprintf(stderr, "read super block error\n");
1537                 goto out_close_fd;
1538         }
1539
1540         rc->sectorsize = btrfs_super_sectorsize(sb);
1541         rc->leafsize = btrfs_super_leafsize(sb);
1542         rc->generation = btrfs_super_generation(sb);
1543         rc->chunk_root_generation = btrfs_super_chunk_root_generation(sb);
1544         rc->csum_size = btrfs_super_csum_size(sb);
1545
1546         /* if seed, the result of scanning below will be partial */
1547         if (btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_SEEDING) {
1548                 fprintf(stderr, "this device is seed device\n");
1549                 ret = -1;
1550                 goto out_close_fd;
1551         }
1552
1553         ret = btrfs_scan_fs_devices(fd, path, &fs_devices, 0, 1, 0);
1554         if (ret)
1555                 goto out_close_fd;
1556
1557         rc->fs_devices = fs_devices;
1558
1559         if (rc->verbose)
1560                 print_all_devices(&rc->fs_devices->devices);
1561
1562 out_close_fd:
1563         close(fd);
1564         return ret;
1565 }
1566
1567 static int btrfs_get_device_extents(u64 chunk_object,
1568                                     struct list_head *orphan_devexts,
1569                                     struct list_head *ret_list)
1570 {
1571         struct device_extent_record *devext;
1572         struct device_extent_record *next;
1573         int count = 0;
1574
1575         list_for_each_entry_safe(devext, next, orphan_devexts, chunk_list) {
1576                 if (devext->chunk_offset == chunk_object) {
1577                         list_move_tail(&devext->chunk_list, ret_list);
1578                         count++;
1579                 }
1580         }
1581         return count;
1582 }
1583
1584 static int calc_num_stripes(u64 type)
1585 {
1586         if (type & (BTRFS_BLOCK_GROUP_RAID0 |
1587                     BTRFS_BLOCK_GROUP_RAID10 |
1588                     BTRFS_BLOCK_GROUP_RAID5 |
1589                     BTRFS_BLOCK_GROUP_RAID6))
1590                 return 0;
1591         else if (type & (BTRFS_BLOCK_GROUP_RAID1 |
1592                          BTRFS_BLOCK_GROUP_DUP))
1593                 return 2;
1594         else
1595                 return 1;
1596 }
1597
1598 static inline int calc_sub_nstripes(u64 type)
1599 {
1600         if (type & BTRFS_BLOCK_GROUP_RAID10)
1601                 return 2;
1602         else
1603                 return 1;
1604 }
1605
1606 static int btrfs_verify_device_extents(struct block_group_record *bg,
1607                                        struct list_head *devexts, int ndevexts)
1608 {
1609         struct device_extent_record *devext;
1610         u64 strpie_length;
1611         int expected_num_stripes;
1612
1613         expected_num_stripes = calc_num_stripes(bg->flags);
1614         if (expected_num_stripes && expected_num_stripes != ndevexts)
1615                 return 1;
1616
1617         strpie_length = calc_stripe_length(bg->flags, bg->offset, ndevexts);
1618         list_for_each_entry(devext, devexts, chunk_list) {
1619                 if (devext->length != strpie_length)
1620                         return 1;
1621         }
1622         return 0;
1623 }
1624
1625 static int btrfs_rebuild_unordered_chunk_stripes(struct recover_control *rc,
1626                                                  struct chunk_record *chunk)
1627 {
1628         struct device_extent_record *devext;
1629         struct btrfs_device *device;
1630         int i;
1631
1632         devext = list_first_entry(&chunk->dextents, struct device_extent_record,
1633                                   chunk_list);
1634         for (i = 0; i < chunk->num_stripes; i++) {
1635                 chunk->stripes[i].devid = devext->objectid;
1636                 chunk->stripes[i].offset = devext->offset;
1637                 device = btrfs_find_device_by_devid(rc->fs_devices,
1638                                                     devext->objectid,
1639                                                     0);
1640                 if (!device)
1641                         return -ENOENT;
1642                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1643                                                   devext->objectid,
1644                                                   1));
1645                 memcpy(chunk->stripes[i].dev_uuid, device->uuid,
1646                        BTRFS_UUID_SIZE);
1647                 devext = list_next_entry(devext, chunk_list);
1648         }
1649         return 0;
1650 }
1651
1652 static int btrfs_calc_stripe_index(struct chunk_record *chunk, u64 logical)
1653 {
1654         u64 offset = logical - chunk->offset;
1655         int stripe_nr;
1656         int nr_data_stripes;
1657         int index;
1658
1659         stripe_nr = offset / chunk->stripe_len;
1660         if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID0) {
1661                 index = stripe_nr % chunk->num_stripes;
1662         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID10) {
1663                 index = stripe_nr % (chunk->num_stripes / chunk->sub_stripes);
1664                 index *= chunk->sub_stripes;
1665         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5) {
1666                 nr_data_stripes = chunk->num_stripes - 1;
1667                 index = stripe_nr % nr_data_stripes;
1668                 stripe_nr /= nr_data_stripes;
1669                 index = (index + stripe_nr) % chunk->num_stripes;
1670         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6) {
1671                 nr_data_stripes = chunk->num_stripes - 2;
1672                 index = stripe_nr % nr_data_stripes;
1673                 stripe_nr /= nr_data_stripes;
1674                 index = (index + stripe_nr) % chunk->num_stripes;
1675         } else {
1676                 return -1;
1677         }
1678         return index;
1679 }
1680
1681 /* calc the logical offset which is the start of the next stripe. */
1682 static inline u64 btrfs_next_stripe_logical_offset(struct chunk_record *chunk,
1683                                                    u64 logical)
1684 {
1685         u64 offset = logical - chunk->offset;
1686
1687         offset /= chunk->stripe_len;
1688         offset *= chunk->stripe_len;
1689         offset += chunk->stripe_len;
1690
1691         return offset + chunk->offset;
1692 }
1693
1694 static int is_extent_record_in_device_extent(struct extent_record *er,
1695                                              struct device_extent_record *dext,
1696                                              int *mirror)
1697 {
1698         int i;
1699
1700         for (i = 0; i < er->nmirrors; i++) {
1701                 if (er->devices[i]->devid == dext->objectid &&
1702                     er->offsets[i] >= dext->offset &&
1703                     er->offsets[i] < dext->offset + dext->length) {
1704                         *mirror = i;
1705                         return 1;
1706                 }
1707         }
1708         return 0;
1709 }
1710
1711 static int
1712 btrfs_rebuild_ordered_meta_chunk_stripes(struct recover_control *rc,
1713                                          struct chunk_record *chunk)
1714 {
1715         u64 start = chunk->offset;
1716         u64 end = chunk->offset + chunk->length;
1717         struct cache_extent *cache;
1718         struct extent_record *er;
1719         struct device_extent_record *devext;
1720         struct device_extent_record *next;
1721         struct btrfs_device *device;
1722         LIST_HEAD(devexts);
1723         int index;
1724         int mirror;
1725         int ret;
1726
1727         cache = lookup_cache_extent(&rc->eb_cache,
1728                                     start, chunk->length);
1729         if (!cache) {
1730                 /* No used space, we can reorder the stripes freely. */
1731                 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1732                 return ret;
1733         }
1734
1735         list_splice_init(&chunk->dextents, &devexts);
1736 again:
1737         er = container_of(cache, struct extent_record, cache);
1738         index = btrfs_calc_stripe_index(chunk, er->cache.start);
1739         BUG_ON(index == -1);
1740         if (chunk->stripes[index].devid)
1741                 goto next;
1742         list_for_each_entry_safe(devext, next, &devexts, chunk_list) {
1743                 if (is_extent_record_in_device_extent(er, devext, &mirror)) {
1744                         chunk->stripes[index].devid = devext->objectid;
1745                         chunk->stripes[index].offset = devext->offset;
1746                         memcpy(chunk->stripes[index].dev_uuid,
1747                                er->devices[mirror]->uuid,
1748                                BTRFS_UUID_SIZE);
1749                         index++;
1750                         list_move(&devext->chunk_list, &chunk->dextents);
1751                 }
1752         }
1753 next:
1754         start = btrfs_next_stripe_logical_offset(chunk, er->cache.start);
1755         if (start >= end)
1756                 goto no_extent_record;
1757
1758         cache = lookup_cache_extent(&rc->eb_cache, start, end - start);
1759         if (cache)
1760                 goto again;
1761 no_extent_record:
1762         if (list_empty(&devexts))
1763                 return 0;
1764
1765         if (chunk->type_flags & (BTRFS_BLOCK_GROUP_RAID5 |
1766                                  BTRFS_BLOCK_GROUP_RAID6)) {
1767                 /* Fixme: try to recover the order by the parity block. */
1768                 list_splice_tail(&devexts, &chunk->dextents);
1769                 return -EINVAL;
1770         }
1771
1772         /* There is no data on the lost stripes, we can reorder them freely. */
1773         for (index = 0; index < chunk->num_stripes; index++) {
1774                 if (chunk->stripes[index].devid)
1775                         continue;
1776
1777                 devext = list_first_entry(&devexts,
1778                                           struct device_extent_record,
1779                                            chunk_list);
1780                 list_move(&devext->chunk_list, &chunk->dextents);
1781
1782                 chunk->stripes[index].devid = devext->objectid;
1783                 chunk->stripes[index].offset = devext->offset;
1784                 device = btrfs_find_device_by_devid(rc->fs_devices,
1785                                                     devext->objectid,
1786                                                     0);
1787                 if (!device) {
1788                         list_splice_tail(&devexts, &chunk->dextents);
1789                         return -EINVAL;
1790                 }
1791                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1792                                                   devext->objectid,
1793                                                   1));
1794                 memcpy(chunk->stripes[index].dev_uuid, device->uuid,
1795                        BTRFS_UUID_SIZE);
1796         }
1797         return 0;
1798 }
1799
1800 #define BTRFS_ORDERED_RAID      (BTRFS_BLOCK_GROUP_RAID0 |      \
1801                                  BTRFS_BLOCK_GROUP_RAID10 |     \
1802                                  BTRFS_BLOCK_GROUP_RAID5 |      \
1803                                  BTRFS_BLOCK_GROUP_RAID6)
1804
1805 static int btrfs_rebuild_chunk_stripes(struct recover_control *rc,
1806                                        struct chunk_record *chunk)
1807 {
1808         int ret;
1809
1810         /*
1811          * All the data in the system metadata chunk will be dropped,
1812          * so we need not guarantee that the data is right or not, that
1813          * is we can reorder the stripes in the system metadata chunk.
1814          */
1815         if ((chunk->type_flags & BTRFS_BLOCK_GROUP_METADATA) &&
1816             (chunk->type_flags & BTRFS_ORDERED_RAID))
1817                 ret =btrfs_rebuild_ordered_meta_chunk_stripes(rc, chunk);
1818         else if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA) &&
1819                  (chunk->type_flags & BTRFS_ORDERED_RAID))
1820                 ret = 1;        /* Be handled after the fs is opened. */
1821         else
1822                 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1823
1824         return ret;
1825 }
1826
1827 static int next_csum(struct btrfs_root *root,
1828                      struct extent_buffer **leaf,
1829                      struct btrfs_path *path,
1830                      int *slot,
1831                      u64 *csum_offset,
1832                      u32 *tree_csum,
1833                      u64 end,
1834                      struct btrfs_key *key)
1835 {
1836         int ret = 0;
1837         struct btrfs_root *csum_root = root->fs_info->csum_root;
1838         struct btrfs_csum_item *csum_item;
1839         u32 blocksize = root->sectorsize;
1840         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1841         int csums_in_item = btrfs_item_size_nr(*leaf, *slot) / csum_size;
1842
1843         if (*csum_offset >= csums_in_item) {
1844                 ++(*slot);
1845                 *csum_offset = 0;
1846                 if (*slot >= btrfs_header_nritems(*leaf)) {
1847                         ret = btrfs_next_leaf(csum_root, path);
1848                         if (ret < 0)
1849                                 return -1;
1850                         else if (ret > 0)
1851                                 return 1;
1852                         *leaf = path->nodes[0];
1853                         *slot = path->slots[0];
1854                 }
1855                 btrfs_item_key_to_cpu(*leaf, key, *slot);
1856         }
1857
1858         if (key->offset + (*csum_offset) * blocksize >= end)
1859                 return 2;
1860         csum_item = btrfs_item_ptr(*leaf, *slot, struct btrfs_csum_item);
1861         csum_item = (struct btrfs_csum_item *)((unsigned char *)csum_item
1862                                              + (*csum_offset) * csum_size);
1863         read_extent_buffer(*leaf, tree_csum,
1864                           (unsigned long)csum_item, csum_size);
1865         return ret;
1866 }
1867
1868 static u64 calc_data_offset(struct btrfs_key *key,
1869                             struct chunk_record *chunk,
1870                             u64 dev_offset,
1871                             u64 csum_offset,
1872                             u32 blocksize)
1873 {
1874         u64 data_offset;
1875         int logical_stripe_nr;
1876         int dev_stripe_nr;
1877         int nr_data_stripes;
1878
1879         data_offset = key->offset + csum_offset * blocksize - chunk->offset;
1880         nr_data_stripes = chunk->num_stripes;
1881
1882         if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5)
1883                 nr_data_stripes -= 1;
1884         else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6)
1885                 nr_data_stripes -= 2;
1886
1887         logical_stripe_nr = data_offset / chunk->stripe_len;
1888         dev_stripe_nr = logical_stripe_nr / nr_data_stripes;
1889
1890         data_offset -= logical_stripe_nr * chunk->stripe_len;
1891         data_offset += dev_stripe_nr * chunk->stripe_len;
1892
1893         return dev_offset + data_offset;
1894 }
1895
1896 static int check_one_csum(int fd, u64 start, u32 len, u32 tree_csum)
1897 {
1898         char *data;
1899         int ret = 0;
1900         u32 csum_result = ~(u32)0;
1901
1902         data = malloc(len);
1903         if (!data)
1904                 return -1;
1905         ret = pread64(fd, data, len, start);
1906         if (ret < 0 || ret != len) {
1907                 ret = -1;
1908                 goto out;
1909         }
1910         ret = 0;
1911         csum_result = btrfs_csum_data(NULL, data, csum_result, len);
1912         btrfs_csum_final(csum_result, (char *)&csum_result);
1913         if (csum_result != tree_csum)
1914                 ret = 1;
1915 out:
1916         free(data);
1917         return ret;
1918 }
1919
1920 static u64 item_end_offset(struct btrfs_root *root, struct btrfs_key *key,
1921                            struct extent_buffer *leaf, int slot) {
1922         u32 blocksize = root->sectorsize;
1923         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1924
1925         u64 offset = btrfs_item_size_nr(leaf, slot);
1926         offset /= csum_size;
1927         offset *= blocksize;
1928         offset += key->offset;
1929
1930         return offset;
1931 }
1932
1933 static int insert_stripe(struct list_head *devexts,
1934                          struct recover_control *rc,
1935                          struct chunk_record *chunk,
1936                          int index) {
1937         struct device_extent_record *devext;
1938         struct btrfs_device *dev;
1939
1940         devext = list_entry(devexts->next, struct device_extent_record,
1941                             chunk_list);
1942         dev = btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1943                                         0);
1944         if (!dev)
1945                 return 1;
1946         BUG_ON(btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1947                                         1));
1948
1949         chunk->stripes[index].devid = devext->objectid;
1950         chunk->stripes[index].offset = devext->offset;
1951         memcpy(chunk->stripes[index].dev_uuid, dev->uuid, BTRFS_UUID_SIZE);
1952
1953         list_move(&devext->chunk_list, &chunk->dextents);
1954
1955         return 0;
1956 }
1957
1958 static inline int count_devext_records(struct list_head *record_list)
1959 {
1960         int num_of_records = 0;
1961         struct device_extent_record *devext;
1962
1963         list_for_each_entry(devext, record_list, chunk_list)
1964                 num_of_records++;
1965
1966         return num_of_records;
1967 }
1968
1969 static int fill_chunk_up(struct chunk_record *chunk, struct list_head *devexts,
1970                          struct recover_control *rc)
1971 {
1972         int ret = 0;
1973         int i;
1974
1975         for (i = 0; i < chunk->num_stripes; i++) {
1976                 if (!chunk->stripes[i].devid) {
1977                         ret = insert_stripe(devexts, rc, chunk, i);
1978                         if (ret)
1979                                 break;
1980                 }
1981         }
1982
1983         return ret;
1984 }
1985
1986 #define EQUAL_STRIPE (1 << 0)
1987
1988 static int rebuild_raid_data_chunk_stripes(struct recover_control *rc,
1989                                            struct btrfs_root *root,
1990                                            struct chunk_record *chunk,
1991                                            u8 *flags)
1992 {
1993         int i;
1994         int ret = 0;
1995         int slot;
1996         struct btrfs_path path;
1997         struct btrfs_key prev_key;
1998         struct btrfs_key key;
1999         struct btrfs_root *csum_root;
2000         struct extent_buffer *leaf;
2001         struct device_extent_record *devext;
2002         struct device_extent_record *next;
2003         struct btrfs_device *dev;
2004         u64 start = chunk->offset;
2005         u64 end = start + chunk->stripe_len;
2006         u64 chunk_end = chunk->offset + chunk->length;
2007         u64 csum_offset = 0;
2008         u64 data_offset;
2009         u32 blocksize = root->sectorsize;
2010         u32 tree_csum;
2011         int index = 0;
2012         int num_unordered = 0;
2013         LIST_HEAD(unordered);
2014         LIST_HEAD(candidates);
2015
2016         csum_root = root->fs_info->csum_root;
2017         btrfs_init_path(&path);
2018         list_splice_init(&chunk->dextents, &candidates);
2019 again:
2020         if (list_is_last(candidates.next, &candidates))
2021                 goto out;
2022
2023         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
2024         key.type = BTRFS_EXTENT_CSUM_KEY;
2025         key.offset = start;
2026
2027         ret = btrfs_search_slot(NULL, csum_root, &key, &path, 0, 0);
2028         if (ret < 0) {
2029                 fprintf(stderr, "Search csum failed(%d)\n", ret);
2030                 goto fail_out;
2031         }
2032         leaf = path.nodes[0];
2033         slot = path.slots[0];
2034         if (ret > 0) {
2035                 if (slot >= btrfs_header_nritems(leaf)) {
2036                         ret = btrfs_next_leaf(csum_root, &path);
2037                         if (ret < 0) {
2038                                 fprintf(stderr,
2039                                         "Walk tree failed(%d)\n", ret);
2040                                 goto fail_out;
2041                         } else if (ret > 0) {
2042                                 slot = btrfs_header_nritems(leaf) - 1;
2043                                 btrfs_item_key_to_cpu(leaf, &key, slot);
2044                                 if (item_end_offset(root, &key, leaf, slot)
2045                                                                 > start) {
2046                                         csum_offset = start - key.offset;
2047                                         csum_offset /= blocksize;
2048                                         goto next_csum;
2049                                 }
2050                                 goto next_stripe;
2051                         }
2052                         leaf = path.nodes[0];
2053                         slot = path.slots[0];
2054                 }
2055                 btrfs_item_key_to_cpu(leaf, &key, slot);
2056                 ret = btrfs_previous_item(csum_root, &path, 0,
2057                                           BTRFS_EXTENT_CSUM_KEY);
2058                 if (ret < 0)
2059                         goto fail_out;
2060                 else if (ret > 0) {
2061                         if (key.offset >= end)
2062                                 goto next_stripe;
2063                         else
2064                                 goto next_csum;
2065                 }
2066                 leaf = path.nodes[0];
2067                 slot = path.slots[0];
2068
2069                 btrfs_item_key_to_cpu(leaf, &prev_key, slot);
2070                 if (item_end_offset(root, &prev_key, leaf, slot) > start) {
2071                         csum_offset = start - prev_key.offset;
2072                         csum_offset /= blocksize;
2073                         btrfs_item_key_to_cpu(leaf, &key, slot);
2074                 } else {
2075                         if (key.offset >= end)
2076                                 goto next_stripe;
2077                 }
2078
2079                 if (key.offset + csum_offset * blocksize > chunk_end)
2080                         goto out;
2081         }
2082 next_csum:
2083         ret = next_csum(root, &leaf, &path, &slot, &csum_offset, &tree_csum,
2084                         end, &key);
2085         if (ret < 0) {
2086                 fprintf(stderr, "Fetch csum failed\n");
2087                 goto fail_out;
2088         } else if (ret == 1) {
2089                 if (!(*flags & EQUAL_STRIPE))
2090                         *flags |= EQUAL_STRIPE;
2091                 goto out;
2092         } else if (ret == 2)
2093                 goto next_stripe;
2094
2095         list_for_each_entry_safe(devext, next, &candidates, chunk_list) {
2096                 data_offset = calc_data_offset(&key, chunk, devext->offset,
2097                                                csum_offset, blocksize);
2098                 dev = btrfs_find_device_by_devid(rc->fs_devices,
2099                                                  devext->objectid, 0);
2100                 if (!dev) {
2101                         ret = 1;
2102                         goto fail_out;
2103                 }
2104                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
2105                                                   devext->objectid, 1));
2106
2107                 ret = check_one_csum(dev->fd, data_offset, blocksize,
2108                                      tree_csum);
2109                 if (ret < 0)
2110                         goto fail_out;
2111                 else if (ret > 0)
2112                         list_move(&devext->chunk_list, &unordered);
2113         }
2114
2115         if (list_empty(&candidates)) {
2116                 num_unordered = count_devext_records(&unordered);
2117                 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6
2118                                         && num_unordered == 2) {
2119                         btrfs_release_path(&path);
2120                         ret = fill_chunk_up(chunk, &unordered, rc);
2121                         return ret;
2122                 }
2123
2124                 goto next_stripe;
2125         }
2126
2127         if (list_is_last(candidates.next, &candidates)) {
2128                 index = btrfs_calc_stripe_index(chunk,
2129                         key.offset + csum_offset * blocksize);
2130                 BUG_ON(index == -1);
2131                 if (chunk->stripes[index].devid)
2132                         goto next_stripe;
2133                 ret = insert_stripe(&candidates, rc, chunk, index);
2134                 if (ret)
2135                         goto fail_out;
2136         } else {
2137                 csum_offset++;
2138                 goto next_csum;
2139         }
2140 next_stripe:
2141         start = btrfs_next_stripe_logical_offset(chunk, start);
2142         end = min(start + chunk->stripe_len, chunk_end);
2143         list_splice_init(&unordered, &candidates);
2144         btrfs_release_path(&path);
2145         csum_offset = 0;
2146         if (end < chunk_end)
2147                 goto again;
2148 out:
2149         ret = 0;
2150         list_splice_init(&candidates, &unordered);
2151         num_unordered = count_devext_records(&unordered);
2152         if (num_unordered == 1) {
2153                 for (i = 0; i < chunk->num_stripes; i++) {
2154                         if (!chunk->stripes[i].devid) {
2155                                 index = i;
2156                                 break;
2157                         }
2158                 }
2159                 ret = insert_stripe(&unordered, rc, chunk, index);
2160                 if (ret)
2161                         goto fail_out;
2162         } else {
2163                 if ((num_unordered == 2 && chunk->type_flags
2164                         & BTRFS_BLOCK_GROUP_RAID5)
2165                  || (num_unordered == 3 && chunk->type_flags
2166                         & BTRFS_BLOCK_GROUP_RAID6)) {
2167                         ret = fill_chunk_up(chunk, &unordered, rc);
2168                 }
2169         }
2170 fail_out:
2171         ret = !!ret || (list_empty(&unordered) ? 0 : 1);
2172         list_splice_init(&candidates, &chunk->dextents);
2173         list_splice_init(&unordered, &chunk->dextents);
2174         btrfs_release_path(&path);
2175
2176         return ret;
2177 }
2178
2179 static int btrfs_rebuild_ordered_data_chunk_stripes(struct recover_control *rc,
2180                                            struct btrfs_root *root)
2181 {
2182         struct chunk_record *chunk;
2183         struct chunk_record *next;
2184         int ret = 0;
2185         int err;
2186         u8 flags;
2187
2188         list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
2189                 if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA)
2190                  && (chunk->type_flags & BTRFS_ORDERED_RAID)) {
2191                         flags = 0;
2192                         err = rebuild_raid_data_chunk_stripes(rc, root, chunk,
2193                                                               &flags);
2194                         if (err) {
2195                                 list_move(&chunk->list, &rc->bad_chunks);
2196                                 if (flags & EQUAL_STRIPE)
2197                                         fprintf(stderr,
2198                         "Failure: too many equal stripes in chunk[%llu %llu]\n",
2199                                                 chunk->offset, chunk->length);
2200                                 if (!ret)
2201                                         ret = err;
2202                         } else
2203                                 list_move(&chunk->list, &rc->good_chunks);
2204                 }
2205         }
2206         return ret;
2207 }
2208
2209 static int btrfs_recover_chunks(struct recover_control *rc)
2210 {
2211         struct chunk_record *chunk;
2212         struct block_group_record *bg;
2213         struct block_group_record *next;
2214         LIST_HEAD(new_chunks);
2215         LIST_HEAD(devexts);
2216         int nstripes;
2217         int ret;
2218
2219         /* create the chunk by block group */
2220         list_for_each_entry_safe(bg, next, &rc->bg.block_groups, list) {
2221                 nstripes = btrfs_get_device_extents(bg->objectid,
2222                                                     &rc->devext.no_chunk_orphans,
2223                                                     &devexts);
2224                 chunk = calloc(1, btrfs_chunk_record_size(nstripes));
2225                 if (!chunk)
2226                         return -ENOMEM;
2227                 INIT_LIST_HEAD(&chunk->dextents);
2228                 chunk->bg_rec = bg;
2229                 chunk->cache.start = bg->objectid;
2230                 chunk->cache.size = bg->offset;
2231                 chunk->objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2232                 chunk->type = BTRFS_CHUNK_ITEM_KEY;
2233                 chunk->offset = bg->objectid;
2234                 chunk->generation = bg->generation;
2235                 chunk->length = bg->offset;
2236                 chunk->owner = BTRFS_CHUNK_TREE_OBJECTID;
2237                 chunk->stripe_len = BTRFS_STRIPE_LEN;
2238                 chunk->type_flags = bg->flags;
2239                 chunk->io_width = BTRFS_STRIPE_LEN;
2240                 chunk->io_align = BTRFS_STRIPE_LEN;
2241                 chunk->sector_size = rc->sectorsize;
2242                 chunk->sub_stripes = calc_sub_nstripes(bg->flags);
2243
2244                 ret = insert_cache_extent(&rc->chunk, &chunk->cache);
2245                 BUG_ON(ret);
2246
2247                 list_del_init(&bg->list);
2248                 if (!nstripes) {
2249                         list_add_tail(&chunk->list, &rc->bad_chunks);
2250                         continue;
2251                 }
2252
2253                 list_splice_init(&devexts, &chunk->dextents);
2254
2255                 ret = btrfs_verify_device_extents(bg, &devexts, nstripes);
2256                 if (ret) {
2257                         list_add_tail(&chunk->list, &rc->bad_chunks);
2258                         continue;
2259                 }
2260
2261                 chunk->num_stripes = nstripes;
2262                 ret = btrfs_rebuild_chunk_stripes(rc, chunk);
2263                 if (ret > 0)
2264                         list_add_tail(&chunk->list, &rc->unrepaired_chunks);
2265                 else if (ret < 0)
2266                         list_add_tail(&chunk->list, &rc->bad_chunks);
2267                 else
2268                         list_add_tail(&chunk->list, &rc->good_chunks);
2269         }
2270         /*
2271          * Don't worry about the lost orphan device extents, they don't
2272          * have its chunk and block group, they must be the old ones that
2273          * we have dropped.
2274          */
2275         return 0;
2276 }
2277
2278 static inline int is_chunk_overlap(struct chunk_record *chunk1,
2279                                    struct chunk_record *chunk2)
2280 {
2281         if (chunk1->offset >= chunk2->offset + chunk2->length ||
2282             chunk1->offset + chunk1->length <= chunk2->offset)
2283                 return 0;
2284         return 1;
2285 }
2286
2287 /* Move invalid(overlap with good chunks) rebuild chunks to bad chunk list */
2288 static void validate_rebuild_chunks(struct recover_control *rc)
2289 {
2290         struct chunk_record *good;
2291         struct chunk_record *rebuild;
2292         struct chunk_record *tmp;
2293
2294         list_for_each_entry_safe(rebuild, tmp, &rc->rebuild_chunks, list) {
2295                 list_for_each_entry(good, &rc->good_chunks, list) {
2296                         if (is_chunk_overlap(rebuild, good)) {
2297                                 list_move_tail(&rebuild->list,
2298                                                &rc->bad_chunks);
2299                                 break;
2300                         }
2301                 }
2302         }
2303 }
2304
2305 /*
2306  * Return 0 when successful, < 0 on error and > 0 if aborted by user
2307  */
2308 int btrfs_recover_chunk_tree(char *path, int verbose, int yes)
2309 {
2310         int ret = 0;
2311         struct btrfs_root *root = NULL;
2312         struct btrfs_trans_handle *trans;
2313         struct recover_control rc;
2314
2315         init_recover_control(&rc, verbose, yes);
2316
2317         ret = recover_prepare(&rc, path);
2318         if (ret) {
2319                 fprintf(stderr, "recover prepare error\n");
2320                 return ret;
2321         }
2322
2323         ret = scan_devices(&rc);
2324         if (ret) {
2325                 fprintf(stderr, "scan chunk headers error\n");
2326                 goto fail_rc;
2327         }
2328
2329         if (cache_tree_empty(&rc.chunk) &&
2330             cache_tree_empty(&rc.bg.tree) &&
2331             cache_tree_empty(&rc.devext.tree)) {
2332                 fprintf(stderr, "no recoverable chunk\n");
2333                 goto fail_rc;
2334         }
2335
2336         print_scan_result(&rc);
2337
2338         ret = check_chunks(&rc.chunk, &rc.bg, &rc.devext, &rc.good_chunks,
2339                            &rc.bad_chunks, &rc.rebuild_chunks, 1);
2340         if (ret) {
2341                 if (!list_empty(&rc.bg.block_groups) ||
2342                     !list_empty(&rc.devext.no_chunk_orphans)) {
2343                         ret = btrfs_recover_chunks(&rc);
2344                         if (ret)
2345                                 goto fail_rc;
2346                 }
2347         } else {
2348                 print_check_result(&rc);
2349                 printf("Check chunks successfully with no orphans\n");
2350                 goto fail_rc;
2351         }
2352         validate_rebuild_chunks(&rc);
2353         print_check_result(&rc);
2354
2355         root = open_ctree_with_broken_chunk(&rc);
2356         if (IS_ERR(root)) {
2357                 fprintf(stderr, "open with broken chunk error\n");
2358                 ret = PTR_ERR(root);
2359                 goto fail_rc;
2360         }
2361
2362         ret = check_all_chunks_by_metadata(&rc, root);
2363         if (ret) {
2364                 fprintf(stderr, "The chunks in memory can not match the metadata of the fs. Repair failed.\n");
2365                 goto fail_close_ctree;
2366         }
2367
2368         ret = btrfs_rebuild_ordered_data_chunk_stripes(&rc, root);
2369         if (ret) {
2370                 fprintf(stderr, "Failed to rebuild ordered chunk stripes.\n");
2371                 goto fail_close_ctree;
2372         }
2373
2374         if (!rc.yes) {
2375                 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?");
2376                 if (!ret) {
2377                         ret = 1;
2378                         goto fail_close_ctree;
2379                 }
2380         }
2381
2382         trans = btrfs_start_transaction(root, 1);
2383         ret = remove_chunk_extent_item(trans, &rc, root);
2384         BUG_ON(ret);
2385
2386         ret = rebuild_chunk_tree(trans, &rc, root);
2387         BUG_ON(ret);
2388
2389         ret = rebuild_sys_array(&rc, root);
2390         BUG_ON(ret);
2391
2392         ret = rebuild_block_group(trans, &rc, root);
2393         if (ret) {
2394                 printf("Fail to rebuild block groups.\n");
2395                 printf("Recommend to run 'btrfs check --init-extent-tree <dev>' after recovery\n");
2396         }
2397
2398         btrfs_commit_transaction(trans, root);
2399 fail_close_ctree:
2400         close_ctree(root);
2401 fail_rc:
2402         free_recover_control(&rc);
2403         return ret;
2404 }