Btrfs-progs: enhance btrfs qgroup to print the result as a table
[platform/upstream/btrfs-progs.git] / cmds-chunk.c
1 /*
2  * Copyright (C) 2013 Fujitsu.  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 #define _XOPEN_SOURCE 500
19 #define _GNU_SOURCE
20
21 #include <stdio.h>
22 #include <stdio_ext.h>
23 #include <stdlib.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <uuid/uuid.h>
29
30 #include "kerncompat.h"
31 #include "list.h"
32 #include "radix-tree.h"
33 #include "ctree.h"
34 #include "extent-cache.h"
35 #include "disk-io.h"
36 #include "volumes.h"
37 #include "transaction.h"
38 #include "crc32c.h"
39 #include "utils.h"
40 #include "version.h"
41 #include "btrfsck.h"
42 #include "commands.h"
43
44 #define BTRFS_CHUNK_TREE_REBUILD_ABORTED        -7500
45 #define BTRFS_STRIPE_LEN                        (64 * 1024)
46 #define BTRFS_NUM_MIRRORS                       2
47
48 struct recover_control {
49         int verbose;
50         int yes;
51
52         u16 csum_size;
53         u32 sectorsize;
54         u32 leafsize;
55         u64 generation;
56         u64 chunk_root_generation;
57
58         struct btrfs_fs_devices *fs_devices;
59
60         struct cache_tree chunk;
61         struct block_group_tree bg;
62         struct device_extent_tree devext;
63         struct cache_tree eb_cache;
64
65         struct list_head good_chunks;
66         struct list_head bad_chunks;
67         struct list_head unrepaired_chunks;
68 };
69
70 struct extent_record {
71         struct cache_extent cache;
72         u64 generation;
73         u8 csum[BTRFS_CSUM_SIZE];
74         struct btrfs_device *devices[BTRFS_NUM_MIRRORS];
75         u64 offsets[BTRFS_NUM_MIRRORS];
76         int nmirrors;
77 };
78
79 static struct extent_record *btrfs_new_extent_record(struct extent_buffer *eb)
80 {
81         struct extent_record *rec;
82
83         rec = malloc(sizeof(*rec));
84         if (!rec) {
85                 fprintf(stderr, "Fail to allocate memory for extent record.\n");
86                 exit(1);
87         }
88
89         memset(rec, 0, sizeof(*rec));
90         rec->cache.start = btrfs_header_bytenr(eb);
91         rec->cache.size = eb->len;
92         rec->generation = btrfs_header_generation(eb);
93         read_extent_buffer(eb, rec->csum, (unsigned long)btrfs_header_csum(eb),
94                            BTRFS_CSUM_SIZE);
95         return rec;
96 }
97
98 static int process_extent_buffer(struct cache_tree *eb_cache,
99                                  struct extent_buffer *eb,
100                                  struct btrfs_device *device, u64 offset)
101 {
102         struct extent_record *rec;
103         struct extent_record *exist;
104         struct cache_extent *cache;
105         int ret = 0;
106
107         rec = btrfs_new_extent_record(eb);
108         if (!rec->cache.size)
109                 goto free_out;
110 again:
111         cache = lookup_cache_extent(eb_cache,
112                                     rec->cache.start,
113                                     rec->cache.size);
114         if (cache) {
115                 exist = container_of(cache, struct extent_record, cache);
116
117                 if (exist->generation > rec->generation)
118                         goto free_out;
119                 if (exist->generation == rec->generation) {
120                         if (exist->cache.start != rec->cache.start ||
121                             exist->cache.size != rec->cache.size ||
122                             memcmp(exist->csum, rec->csum, BTRFS_CSUM_SIZE)) {
123                                 ret = -EEXIST;
124                         } else {
125                                 BUG_ON(exist->nmirrors >= BTRFS_NUM_MIRRORS);
126                                 exist->devices[exist->nmirrors] = device;
127                                 exist->offsets[exist->nmirrors] = offset;
128                                 exist->nmirrors++;
129                         }
130                         goto free_out;
131                 }
132                 remove_cache_extent(eb_cache, cache);
133                 free(exist);
134                 goto again;
135         }
136
137         rec->devices[0] = device;
138         rec->offsets[0] = offset;
139         rec->nmirrors++;
140         ret = insert_cache_extent(eb_cache, &rec->cache);
141         BUG_ON(ret);
142 out:
143         return ret;
144 free_out:
145         free(rec);
146         goto out;
147 }
148
149 static void free_extent_record(struct cache_extent *cache)
150 {
151         struct extent_record *er;
152
153         er = container_of(cache, struct extent_record, cache);
154         free(er);
155 }
156
157 FREE_EXTENT_CACHE_BASED_TREE(extent_record, free_extent_record);
158
159 static struct btrfs_chunk *create_chunk_item(struct chunk_record *record)
160 {
161         struct btrfs_chunk *ret;
162         struct btrfs_stripe *chunk_stripe;
163         int i;
164
165         if (!record || record->num_stripes == 0)
166                 return NULL;
167         ret = malloc(btrfs_chunk_item_size(record->num_stripes));
168         if (!ret)
169                 return NULL;
170         btrfs_set_stack_chunk_length(ret, record->length);
171         btrfs_set_stack_chunk_owner(ret, record->owner);
172         btrfs_set_stack_chunk_stripe_len(ret, record->stripe_len);
173         btrfs_set_stack_chunk_type(ret, record->type_flags);
174         btrfs_set_stack_chunk_io_align(ret, record->io_align);
175         btrfs_set_stack_chunk_io_width(ret, record->io_width);
176         btrfs_set_stack_chunk_sector_size(ret, record->sector_size);
177         btrfs_set_stack_chunk_num_stripes(ret, record->num_stripes);
178         btrfs_set_stack_chunk_sub_stripes(ret, record->sub_stripes);
179         for (i = 0, chunk_stripe = &ret->stripe; i < record->num_stripes;
180              i++, chunk_stripe++) {
181                 btrfs_set_stack_stripe_devid(chunk_stripe,
182                                 record->stripes[i].devid);
183                 btrfs_set_stack_stripe_offset(chunk_stripe,
184                                 record->stripes[i].offset);
185                 memcpy(chunk_stripe->dev_uuid, record->stripes[i].dev_uuid,
186                        BTRFS_UUID_SIZE);
187         }
188         return ret;
189 }
190
191 static void init_recover_control(struct recover_control *rc, int verbose,
192                 int yes)
193 {
194         memset(rc, 0, sizeof(struct recover_control));
195         cache_tree_init(&rc->chunk);
196         cache_tree_init(&rc->eb_cache);
197         block_group_tree_init(&rc->bg);
198         device_extent_tree_init(&rc->devext);
199
200         INIT_LIST_HEAD(&rc->good_chunks);
201         INIT_LIST_HEAD(&rc->bad_chunks);
202         INIT_LIST_HEAD(&rc->unrepaired_chunks);
203
204         rc->verbose = verbose;
205         rc->yes = yes;
206 }
207
208 static void free_recover_control(struct recover_control *rc)
209 {
210         free_block_group_tree(&rc->bg);
211         free_chunk_cache_tree(&rc->chunk);
212         free_device_extent_tree(&rc->devext);
213         free_extent_record_tree(&rc->eb_cache);
214 }
215
216 static int process_block_group_item(struct block_group_tree *bg_cache,
217                                     struct extent_buffer *leaf,
218                                     struct btrfs_key *key, int slot)
219 {
220         struct block_group_record *rec;
221         struct block_group_record *exist;
222         struct cache_extent *cache;
223         int ret = 0;
224
225         rec = btrfs_new_block_group_record(leaf, key, slot);
226         if (!rec->cache.size)
227                 goto free_out;
228 again:
229         cache = lookup_cache_extent(&bg_cache->tree,
230                                     rec->cache.start,
231                                     rec->cache.size);
232         if (cache) {
233                 exist = container_of(cache, struct block_group_record, cache);
234
235                 /*check the generation and replace if needed*/
236                 if (exist->generation > rec->generation)
237                         goto free_out;
238                 if (exist->generation == rec->generation) {
239                         int offset = offsetof(struct block_group_record,
240                                               generation);
241                         /*
242                          * According to the current kernel code, the following
243                          * case is impossble, or there is something wrong in
244                          * the kernel code.
245                          */
246                         if (memcmp(((void *)exist) + offset,
247                                    ((void *)rec) + offset,
248                                    sizeof(*rec) - offset))
249                                 ret = -EEXIST;
250                         goto free_out;
251                 }
252                 remove_cache_extent(&bg_cache->tree, cache);
253                 list_del_init(&exist->list);
254                 free(exist);
255                 /*
256                  * We must do seach again to avoid the following cache.
257                  * /--old bg 1--//--old bg 2--/
258                  *        /--new bg--/
259                  */
260                 goto again;
261         }
262
263         ret = insert_block_group_record(bg_cache, rec);
264         BUG_ON(ret);
265 out:
266         return ret;
267 free_out:
268         free(rec);
269         goto out;
270 }
271
272 static int process_chunk_item(struct cache_tree *chunk_cache,
273                               struct extent_buffer *leaf, struct btrfs_key *key,
274                               int slot)
275 {
276         struct chunk_record *rec;
277         struct chunk_record *exist;
278         struct cache_extent *cache;
279         int ret = 0;
280
281         rec = btrfs_new_chunk_record(leaf, key, slot);
282         if (!rec->cache.size)
283                 goto free_out;
284 again:
285         cache = lookup_cache_extent(chunk_cache, rec->offset, rec->length);
286         if (cache) {
287                 exist = container_of(cache, struct chunk_record, cache);
288
289                 if (exist->generation > rec->generation)
290                         goto free_out;
291                 if (exist->generation == rec->generation) {
292                         int num_stripes = rec->num_stripes;
293                         int rec_size = btrfs_chunk_record_size(num_stripes);
294                         int offset = offsetof(struct chunk_record, generation);
295
296                         if (exist->num_stripes != rec->num_stripes ||
297                             memcmp(((void *)exist) + offset,
298                                    ((void *)rec) + offset,
299                                    rec_size - offset))
300                                 ret = -EEXIST;
301                         goto free_out;
302                 }
303                 remove_cache_extent(chunk_cache, cache);
304                 free(exist);
305                 goto again;
306         }
307         ret = insert_cache_extent(chunk_cache, &rec->cache);
308         BUG_ON(ret);
309 out:
310         return ret;
311 free_out:
312         free(rec);
313         goto out;
314 }
315
316 static int process_device_extent_item(struct device_extent_tree *devext_cache,
317                                       struct extent_buffer *leaf,
318                                       struct btrfs_key *key, int slot)
319 {
320         struct device_extent_record *rec;
321         struct device_extent_record *exist;
322         struct cache_extent *cache;
323         int ret = 0;
324
325         rec = btrfs_new_device_extent_record(leaf, key, slot);
326         if (!rec->cache.size)
327                 goto free_out;
328 again:
329         cache = lookup_cache_extent2(&devext_cache->tree,
330                                      rec->cache.objectid,
331                                      rec->cache.start,
332                                      rec->cache.size);
333         if (cache) {
334                 exist = container_of(cache, struct device_extent_record, cache);
335                 if (exist->generation > rec->generation)
336                         goto free_out;
337                 if (exist->generation == rec->generation) {
338                         int offset = offsetof(struct device_extent_record,
339                                               generation);
340                         if (memcmp(((void *)exist) + offset,
341                                    ((void *)rec) + offset,
342                                    sizeof(*rec) - offset))
343                                 ret = -EEXIST;
344                         goto free_out;
345                 }
346                 remove_cache_extent(&devext_cache->tree, cache);
347                 list_del_init(&exist->chunk_list);
348                 list_del_init(&exist->device_list);
349                 free(exist);
350                 goto again;
351         }
352
353         ret = insert_device_extent_record(devext_cache, rec);
354         BUG_ON(ret);
355 out:
356         return ret;
357 free_out:
358         free(rec);
359         goto out;
360 }
361
362 static void print_block_group_info(struct block_group_record *rec, char *prefix)
363 {
364         if (prefix)
365                 printf("%s", prefix);
366         printf("Block Group: start = %llu, len = %llu, flag = %llx\n",
367                rec->objectid, rec->offset, rec->flags);
368 }
369
370 static void print_block_group_tree(struct block_group_tree *tree)
371 {
372         struct cache_extent *cache;
373         struct block_group_record *rec;
374
375         printf("All Block Groups:\n");
376         for (cache = first_cache_extent(&tree->tree); cache;
377              cache = next_cache_extent(cache)) {
378                 rec = container_of(cache, struct block_group_record, cache);
379                 print_block_group_info(rec, "\t");
380         }
381         printf("\n");
382 }
383
384 static void print_stripe_info(struct stripe *data, char *prefix1, char *prefix2,
385                               int index)
386 {
387         if (prefix1)
388                 printf("%s", prefix1);
389         if (prefix2)
390                 printf("%s", prefix2);
391         printf("[%2d] Stripe: devid = %llu, offset = %llu\n",
392                index, data->devid, data->offset);
393 }
394
395 static void print_chunk_self_info(struct chunk_record *rec, char *prefix)
396 {
397         int i;
398
399         if (prefix)
400                 printf("%s", prefix);
401         printf("Chunk: start = %llu, len = %llu, type = %llx, num_stripes = %u\n",
402                rec->offset, rec->length, rec->type_flags, rec->num_stripes);
403         if (prefix)
404                 printf("%s", prefix);
405         printf("    Stripes list:\n");
406         for (i = 0; i < rec->num_stripes; i++)
407                 print_stripe_info(&rec->stripes[i], prefix, "    ", i);
408 }
409
410 static void print_chunk_tree(struct cache_tree *tree)
411 {
412         struct cache_extent *n;
413         struct chunk_record *entry;
414
415         printf("All Chunks:\n");
416         for (n = first_cache_extent(tree); n;
417              n = next_cache_extent(n)) {
418                 entry = container_of(n, struct chunk_record, cache);
419                 print_chunk_self_info(entry, "\t");
420         }
421         printf("\n");
422 }
423
424 static void print_device_extent_info(struct device_extent_record *rec,
425                                      char *prefix)
426 {
427         if (prefix)
428                 printf("%s", prefix);
429         printf("Device extent: devid = %llu, start = %llu, len = %llu, chunk offset = %llu\n",
430                rec->objectid, rec->offset, rec->length, rec->chunk_offset);
431 }
432
433 static void print_device_extent_tree(struct device_extent_tree *tree)
434 {
435         struct cache_extent *n;
436         struct device_extent_record *entry;
437
438         printf("All Device Extents:\n");
439         for (n = first_cache_extent(&tree->tree); n;
440              n = next_cache_extent(n)) {
441                 entry = container_of(n, struct device_extent_record, cache);
442                 print_device_extent_info(entry, "\t");
443         }
444         printf("\n");
445 }
446
447 static void print_device_info(struct btrfs_device *device, char *prefix)
448 {
449         if (prefix)
450                 printf("%s", prefix);
451         printf("Device: id = %llu, name = %s\n",
452                device->devid, device->name);
453 }
454
455 static void print_all_devices(struct list_head *devices)
456 {
457         struct btrfs_device *dev;
458
459         printf("All Devices:\n");
460         list_for_each_entry(dev, devices, dev_list)
461                 print_device_info(dev, "\t");
462         printf("\n");
463 }
464
465 static void print_scan_result(struct recover_control *rc)
466 {
467         if (!rc->verbose)
468                 return;
469
470         printf("DEVICE SCAN RESULT:\n");
471         printf("Filesystem Information:\n");
472         printf("\tsectorsize: %d\n", rc->sectorsize);
473         printf("\tleafsize: %d\n", rc->leafsize);
474         printf("\ttree root generation: %llu\n", rc->generation);
475         printf("\tchunk root generation: %llu\n", rc->chunk_root_generation);
476         printf("\n");
477
478         print_all_devices(&rc->fs_devices->devices);
479         print_block_group_tree(&rc->bg);
480         print_chunk_tree(&rc->chunk);
481         print_device_extent_tree(&rc->devext);
482 }
483
484 static void print_chunk_info(struct chunk_record *chunk, char *prefix)
485 {
486         struct device_extent_record *devext;
487         int i;
488
489         print_chunk_self_info(chunk, prefix);
490         if (prefix)
491                 printf("%s", prefix);
492         if (chunk->bg_rec)
493                 print_block_group_info(chunk->bg_rec, "    ");
494         else
495                 printf("    No block group.\n");
496         if (prefix)
497                 printf("%s", prefix);
498         if (list_empty(&chunk->dextents)) {
499                 printf("    No device extent.\n");
500         } else {
501                 printf("    Device extent list:\n");
502                 i = 0;
503                 list_for_each_entry(devext, &chunk->dextents, chunk_list) {
504                         if (prefix)
505                                 printf("%s", prefix);
506                         printf("%s[%2d]", "        ", i);
507                         print_device_extent_info(devext, NULL);
508                         i++;
509                 }
510         }
511 }
512
513 static void print_check_result(struct recover_control *rc)
514 {
515         struct chunk_record *chunk;
516         struct block_group_record *bg;
517         struct device_extent_record *devext;
518         int total = 0;
519         int good = 0;
520         int bad = 0;
521
522         if (!rc->verbose)
523                 return;
524
525         printf("CHECK RESULT:\n");
526         printf("Healthy Chunks:\n");
527         list_for_each_entry(chunk, &rc->good_chunks, list) {
528                 print_chunk_info(chunk, "  ");
529                 good++;
530                 total++;
531         }
532         printf("Bad Chunks:\n");
533         list_for_each_entry(chunk, &rc->bad_chunks, list) {
534                 print_chunk_info(chunk, "  ");
535                 bad++;
536                 total++;
537         }
538         printf("\n");
539         printf("Total Chunks:\t%d\n", total);
540         printf("  Heathy:\t%d\n", good);
541         printf("  Bad:\t%d\n", bad);
542
543         printf("\n");
544         printf("Orphan Block Groups:\n");
545         list_for_each_entry(bg, &rc->bg.block_groups, list)
546                 print_block_group_info(bg, "  ");
547
548         printf("\n");
549         printf("Orphan Device Extents:\n");
550         list_for_each_entry(devext, &rc->devext.no_chunk_orphans, chunk_list)
551                 print_device_extent_info(devext, "  ");
552 }
553
554 static int check_chunk_by_metadata(struct recover_control *rc,
555                                    struct btrfs_root *root,
556                                    struct chunk_record *chunk, int bg_only)
557 {
558         int ret;
559         int i;
560         int slot;
561         struct btrfs_path path;
562         struct btrfs_key key;
563         struct btrfs_root *dev_root;
564         struct stripe *stripe;
565         struct btrfs_dev_extent *dev_extent;
566         struct btrfs_block_group_item *bg_ptr;
567         struct extent_buffer *l;
568
569         btrfs_init_path(&path);
570
571         if (bg_only)
572                 goto bg_check;
573
574         dev_root = root->fs_info->dev_root;
575         for (i = 0; i < chunk->num_stripes; i++) {
576                 stripe = &chunk->stripes[i];
577
578                 key.objectid = stripe->devid;
579                 key.offset = stripe->offset;
580                 key.type = BTRFS_DEV_EXTENT_KEY;
581
582                 ret = btrfs_search_slot(NULL, dev_root, &key, &path, 0, 0);
583                 if (ret < 0) {
584                         fprintf(stderr, "Search device extent failed(%d)\n",
585                                 ret);
586                         btrfs_release_path(&path);
587                         return ret;
588                 } else if (ret > 0) {
589                         if (rc->verbose)
590                                 fprintf(stderr,
591                                         "No device extent[%llu, %llu]\n",
592                                         stripe->devid, stripe->offset);
593                         btrfs_release_path(&path);
594                         return -ENOENT;
595                 }
596                 l = path.nodes[0];
597                 slot = path.slots[0];
598                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
599                 if (chunk->offset !=
600                     btrfs_dev_extent_chunk_offset(l, dev_extent)) {
601                         if (rc->verbose)
602                                 fprintf(stderr,
603                                         "Device tree unmatch with chunks dev_extent[%llu, %llu], chunk[%llu, %llu]\n",
604                                         btrfs_dev_extent_chunk_offset(l,
605                                                                 dev_extent),
606                                         btrfs_dev_extent_length(l, dev_extent),
607                                         chunk->offset, chunk->length);
608                         btrfs_release_path(&path);
609                         return -ENOENT;
610                 }
611                 btrfs_release_path(&path);
612         }
613
614 bg_check:
615         key.objectid = chunk->offset;
616         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
617         key.offset = chunk->length;
618
619         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, &path,
620                                 0, 0);
621         if (ret < 0) {
622                 fprintf(stderr, "Search block group failed(%d)\n", ret);
623                 btrfs_release_path(&path);
624                 return ret;
625         } else if (ret > 0) {
626                 if (rc->verbose)
627                         fprintf(stderr, "No block group[%llu, %llu]\n",
628                                 key.objectid, key.offset);
629                 btrfs_release_path(&path);
630                 return -ENOENT;
631         }
632
633         l = path.nodes[0];
634         slot = path.slots[0];
635         bg_ptr = btrfs_item_ptr(l, slot, struct btrfs_block_group_item);
636         if (chunk->type_flags != btrfs_disk_block_group_flags(l, bg_ptr)) {
637                 if (rc->verbose)
638                         fprintf(stderr,
639                                 "Chunk[%llu, %llu]'s type(%llu) is differemt with Block Group's type(%llu)\n",
640                                 chunk->offset, chunk->length, chunk->type_flags,
641                                 btrfs_disk_block_group_flags(l, bg_ptr));
642                 btrfs_release_path(&path);
643                 return -ENOENT;
644         }
645         btrfs_release_path(&path);
646         return 0;
647 }
648
649 static int check_all_chunks_by_metadata(struct recover_control *rc,
650                                         struct btrfs_root *root)
651 {
652         struct chunk_record *chunk;
653         struct chunk_record *next;
654         LIST_HEAD(orphan_chunks);
655         int ret = 0;
656         int err;
657
658         list_for_each_entry_safe(chunk, next, &rc->good_chunks, list) {
659                 err = check_chunk_by_metadata(rc, root, chunk, 0);
660                 if (err) {
661                         if (err == -ENOENT)
662                                 list_move_tail(&chunk->list, &orphan_chunks);
663                         else if (err && !ret)
664                                 ret = err;
665                 }
666         }
667
668         list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
669                 err = check_chunk_by_metadata(rc, root, chunk, 1);
670                 if (err == -ENOENT)
671                         list_move_tail(&chunk->list, &orphan_chunks);
672                 else if (err && !ret)
673                         ret = err;
674         }
675
676         list_for_each_entry(chunk, &rc->bad_chunks, list) {
677                 err = check_chunk_by_metadata(rc, root, chunk, 1);
678                 if (err != -ENOENT && !ret)
679                         ret = err ? err : -EINVAL;
680         }
681         list_splice(&orphan_chunks, &rc->bad_chunks);
682         return ret;
683 }
684
685 static int extract_metadata_record(struct recover_control *rc,
686                                    struct extent_buffer *leaf)
687 {
688         struct btrfs_key key;
689         int ret = 0;
690         int i;
691         u32 nritems;
692
693         nritems = btrfs_header_nritems(leaf);
694         for (i = 0; i < nritems; i++) {
695                 btrfs_item_key_to_cpu(leaf, &key, i);
696                 switch (key.type) {
697                 case BTRFS_BLOCK_GROUP_ITEM_KEY:
698                         ret = process_block_group_item(&rc->bg, leaf, &key, i);
699                         break;
700                 case BTRFS_CHUNK_ITEM_KEY:
701                         ret = process_chunk_item(&rc->chunk, leaf, &key, i);
702                         break;
703                 case BTRFS_DEV_EXTENT_KEY:
704                         ret = process_device_extent_item(&rc->devext, leaf,
705                                                          &key, i);
706                         break;
707                 }
708                 if (ret)
709                         break;
710         }
711         return ret;
712 }
713
714 static inline int is_super_block_address(u64 offset)
715 {
716         int i;
717
718         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
719                 if (offset == btrfs_sb_offset(i))
720                         return 1;
721         }
722         return 0;
723 }
724
725 static int scan_one_device(struct recover_control *rc, int fd,
726                            struct btrfs_device *device)
727 {
728         struct extent_buffer *buf;
729         u64 bytenr;
730         int ret = 0;
731
732         buf = malloc(sizeof(*buf) + rc->leafsize);
733         if (!buf)
734                 return -ENOMEM;
735         buf->len = rc->leafsize;
736
737         bytenr = 0;
738         while (1) {
739                 if (is_super_block_address(bytenr))
740                         bytenr += rc->sectorsize;
741
742                 if (pread64(fd, buf->data, rc->leafsize, bytenr) <
743                     rc->leafsize)
744                         break;
745
746                 if (memcmp_extent_buffer(buf, rc->fs_devices->fsid,
747                                          btrfs_header_fsid(), BTRFS_FSID_SIZE)) {
748                         bytenr += rc->sectorsize;
749                         continue;
750                 }
751
752                 if (verify_tree_block_csum_silent(buf, rc->csum_size)) {
753                         bytenr += rc->sectorsize;
754                         continue;
755                 }
756
757                 ret = process_extent_buffer(&rc->eb_cache, buf, device, bytenr);
758                 if (ret)
759                         goto out;
760
761                 if (btrfs_header_level(buf) != 0)
762                         goto next_node;
763
764                 switch (btrfs_header_owner(buf)) {
765                 case BTRFS_EXTENT_TREE_OBJECTID:
766                 case BTRFS_DEV_TREE_OBJECTID:
767                         /* different tree use different generation */
768                         if (btrfs_header_generation(buf) > rc->generation)
769                                 break;
770                         ret = extract_metadata_record(rc, buf);
771                         if (ret)
772                                 goto out;
773                         break;
774                 case BTRFS_CHUNK_TREE_OBJECTID:
775                         if (btrfs_header_generation(buf) >
776                             rc->chunk_root_generation)
777                                 break;
778                         ret = extract_metadata_record(rc, buf);
779                         if (ret)
780                                 goto out;
781                         break;
782                 }
783 next_node:
784                 bytenr += rc->leafsize;
785         }
786 out:
787         free(buf);
788         return ret;
789 }
790
791 static int scan_devices(struct recover_control *rc)
792 {
793         int ret = 0;
794         int fd;
795         struct btrfs_device *dev;
796         int e;
797
798         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
799                 fd = open(dev->name, O_RDONLY);
800                 if (fd < 0) {
801                         e = errno;
802                         fprintf(stderr, "Failed to open device %s\n",
803                                 dev->name);
804                         return -e;
805                 }
806                 ret = scan_one_device(rc, fd, dev);
807                 close(fd);
808                 if (ret)
809                         return ret;
810         }
811         return ret;
812 }
813
814 static int build_device_map_by_chunk_record(struct btrfs_root *root,
815                                             struct chunk_record *chunk)
816 {
817         int ret = 0;
818         int i;
819         u64 devid;
820         u8 uuid[BTRFS_UUID_SIZE];
821         u16 num_stripes;
822         struct btrfs_mapping_tree *map_tree;
823         struct map_lookup *map;
824         struct stripe *stripe;
825
826         map_tree = &root->fs_info->mapping_tree;
827         num_stripes = chunk->num_stripes;
828         map = malloc(btrfs_map_lookup_size(num_stripes));
829         if (!map)
830                 return -ENOMEM;
831         map->ce.start = chunk->offset;
832         map->ce.size = chunk->length;
833         map->num_stripes = num_stripes;
834         map->io_width = chunk->io_width;
835         map->io_align = chunk->io_align;
836         map->sector_size = chunk->sector_size;
837         map->stripe_len = chunk->stripe_len;
838         map->type = chunk->type_flags;
839         map->sub_stripes = chunk->sub_stripes;
840
841         for (i = 0, stripe = chunk->stripes; i < num_stripes; i++, stripe++) {
842                 devid = stripe->devid;
843                 memcpy(uuid, stripe->dev_uuid, BTRFS_UUID_SIZE);
844                 map->stripes[i].physical = stripe->offset;
845                 map->stripes[i].dev = btrfs_find_device(root, devid,
846                                                         uuid, NULL);
847                 if (!map->stripes[i].dev) {
848                         kfree(map);
849                         return -EIO;
850                 }
851         }
852
853         ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
854         return ret;
855 }
856
857 static int build_device_maps_by_chunk_records(struct recover_control *rc,
858                                               struct btrfs_root *root)
859 {
860         int ret = 0;
861         struct chunk_record *chunk;
862
863         list_for_each_entry(chunk, &rc->good_chunks, list) {
864                 ret = build_device_map_by_chunk_record(root, chunk);
865                 if (ret)
866                         return ret;
867         }
868         return ret;
869 }
870
871 static int block_group_remove_all_extent_items(struct btrfs_trans_handle *trans,
872                                                struct btrfs_root *root,
873                                                struct block_group_record *bg)
874 {
875         struct btrfs_fs_info *fs_info = root->fs_info;
876         struct btrfs_key key;
877         struct btrfs_path path;
878         struct extent_buffer *leaf;
879         u64 start = bg->objectid;
880         u64 end = bg->objectid + bg->offset;
881         u64 old_val;
882         int nitems;
883         int ret;
884         int i;
885         int del_s, del_nr;
886
887         btrfs_init_path(&path);
888         root = root->fs_info->extent_root;
889
890         key.objectid = start;
891         key.offset = 0;
892         key.type = BTRFS_EXTENT_ITEM_KEY;
893 again:
894         ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
895         if (ret < 0)
896                 goto err;
897         else if (ret > 0)
898                 ret = 0;
899
900         leaf = path.nodes[0];
901         nitems = btrfs_header_nritems(leaf);
902         if (!nitems) {
903                 /* The tree is empty. */
904                 ret = 0;
905                 goto err;
906         }
907
908         if (path.slots[0] >= nitems) {
909                 ret = btrfs_next_leaf(root, &path);
910                 if (ret < 0)
911                         goto err;
912                 if (ret > 0) {
913                         ret = 0;
914                         goto err;
915                 }
916                 leaf = path.nodes[0];
917                 btrfs_item_key_to_cpu(leaf, &key, 0);
918                 if (key.objectid >= end)
919                         goto err;
920                 btrfs_release_path(&path);
921                 goto again;
922         }
923
924         del_nr = 0;
925         del_s = -1;
926         for (i = path.slots[0]; i < nitems; i++) {
927                 btrfs_item_key_to_cpu(leaf, &key, i);
928                 if (key.objectid >= end)
929                         break;
930
931                 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
932                         if (del_nr == 0)
933                                 continue;
934                         else
935                                 break;
936                 }
937
938                 if (del_s == -1)
939                         del_s = i;
940                 del_nr++;
941                 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
942                     key.type == BTRFS_METADATA_ITEM_KEY) {
943                         old_val = btrfs_super_bytes_used(fs_info->super_copy);
944                         if (key.type == BTRFS_METADATA_ITEM_KEY)
945                                 old_val += root->leafsize;
946                         else
947                                 old_val += key.offset;
948                         btrfs_set_super_bytes_used(fs_info->super_copy,
949                                                    old_val);
950                 }
951         }
952
953         if (del_nr) {
954                 ret = btrfs_del_items(trans, root, &path, del_s, del_nr);
955                 if (ret)
956                         goto err;
957         }
958
959         if (key.objectid < end) {
960                 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
961                         key.objectid += root->sectorsize;
962                         key.type = BTRFS_EXTENT_ITEM_KEY;
963                         key.offset = 0;
964                 }
965                 btrfs_release_path(&path);
966                 goto again;
967         }
968 err:
969         btrfs_release_path(&path);
970         return ret;
971 }
972
973 static int block_group_free_all_extent(struct btrfs_trans_handle *trans,
974                                        struct btrfs_root *root,
975                                        struct block_group_record *bg)
976 {
977         struct btrfs_block_group_cache *cache;
978         struct btrfs_fs_info *info;
979         u64 start;
980         u64 end;
981
982         info = root->fs_info;
983         cache = btrfs_lookup_block_group(info, bg->objectid);
984         if (!cache)
985                 return -ENOENT;
986
987         start = cache->key.objectid;
988         end = start + cache->key.offset - 1;
989
990         set_extent_bits(&info->block_group_cache, start, end,
991                         BLOCK_GROUP_DIRTY, GFP_NOFS);
992         set_extent_dirty(&info->free_space_cache, start, end, GFP_NOFS);
993
994         btrfs_set_block_group_used(&cache->item, 0);
995
996         return 0;
997 }
998
999 static int remove_chunk_extent_item(struct btrfs_trans_handle *trans,
1000                                     struct recover_control *rc,
1001                                     struct btrfs_root *root)
1002 {
1003         struct chunk_record *chunk;
1004         int ret = 0;
1005
1006         list_for_each_entry(chunk, &rc->good_chunks, list) {
1007                 if (!(chunk->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1008                         continue;
1009                 ret = block_group_remove_all_extent_items(trans, root,
1010                                                           chunk->bg_rec);
1011                 if (ret)
1012                         return ret;
1013
1014                 ret = block_group_free_all_extent(trans, root, chunk->bg_rec);
1015                 if (ret)
1016                         return ret;
1017         }
1018         return ret;
1019 }
1020
1021 static int __rebuild_chunk_root(struct btrfs_trans_handle *trans,
1022                                 struct recover_control *rc,
1023                                 struct btrfs_root *root)
1024 {
1025         u64 min_devid = -1;
1026         struct btrfs_device *dev;
1027         struct extent_buffer *cow;
1028         struct btrfs_disk_key disk_key;
1029         int ret = 0;
1030
1031         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1032                 if (min_devid > dev->devid)
1033                         min_devid = dev->devid;
1034         }
1035         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
1036         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
1037         btrfs_set_disk_key_offset(&disk_key, min_devid);
1038
1039         cow = btrfs_alloc_free_block(trans, root, root->sectorsize,
1040                                      BTRFS_CHUNK_TREE_OBJECTID,
1041                                      &disk_key, 0, 0, 0);
1042         btrfs_set_header_bytenr(cow, cow->start);
1043         btrfs_set_header_generation(cow, trans->transid);
1044         btrfs_set_header_nritems(cow, 0);
1045         btrfs_set_header_level(cow, 0);
1046         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1047         btrfs_set_header_owner(cow, BTRFS_CHUNK_TREE_OBJECTID);
1048         write_extent_buffer(cow, root->fs_info->fsid,
1049                         btrfs_header_fsid(), BTRFS_FSID_SIZE);
1050
1051         write_extent_buffer(cow, root->fs_info->chunk_tree_uuid,
1052                         (unsigned long)btrfs_header_chunk_tree_uuid(cow),
1053                         BTRFS_UUID_SIZE);
1054
1055         root->node = cow;
1056         btrfs_mark_buffer_dirty(cow);
1057
1058         return ret;
1059 }
1060
1061 static int __rebuild_device_items(struct btrfs_trans_handle *trans,
1062                                   struct recover_control *rc,
1063                                   struct btrfs_root *root)
1064 {
1065         struct btrfs_device *dev;
1066         struct btrfs_key key;
1067         struct btrfs_dev_item *dev_item;
1068         int ret = 0;
1069
1070         dev_item = malloc(sizeof(struct btrfs_dev_item));
1071         if (!dev_item)
1072                 return -ENOMEM;
1073
1074         list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1075                 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1076                 key.type = BTRFS_DEV_ITEM_KEY;
1077                 key.offset = dev->devid;
1078
1079                 btrfs_set_stack_device_generation(dev_item, 0);
1080                 btrfs_set_stack_device_type(dev_item, dev->type);
1081                 btrfs_set_stack_device_id(dev_item, dev->devid);
1082                 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1083                 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1084                 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1085                 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1086                 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1087                 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1088                 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1089
1090                 ret = btrfs_insert_item(trans, root, &key,
1091                                         dev_item, sizeof(*dev_item));
1092         }
1093
1094         free(dev_item);
1095         return ret;
1096 }
1097
1098 static int __rebuild_chunk_items(struct btrfs_trans_handle *trans,
1099                                  struct recover_control *rc,
1100                                  struct btrfs_root *root)
1101 {
1102         struct btrfs_key key;
1103         struct btrfs_chunk *chunk = NULL;
1104         struct btrfs_root *chunk_root;
1105         struct chunk_record *chunk_rec;
1106         int ret;
1107
1108         chunk_root = root->fs_info->chunk_root;
1109
1110         list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1111                 chunk = create_chunk_item(chunk_rec);
1112                 if (!chunk)
1113                         return -ENOMEM;
1114
1115                 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1116                 key.type = BTRFS_CHUNK_ITEM_KEY;
1117                 key.offset = chunk_rec->offset;
1118
1119                 ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1120                                 btrfs_chunk_item_size(chunk_rec->num_stripes));
1121                 free(chunk);
1122                 if (ret)
1123                         return ret;
1124         }
1125         return 0;
1126 }
1127
1128 static int rebuild_chunk_tree(struct btrfs_trans_handle *trans,
1129                               struct recover_control *rc,
1130                               struct btrfs_root *root)
1131 {
1132         int ret = 0;
1133
1134         root = root->fs_info->chunk_root;
1135
1136         ret = __rebuild_chunk_root(trans, rc, root);
1137         if (ret)
1138                 return ret;
1139
1140         ret = __rebuild_device_items(trans, rc, root);
1141         if (ret)
1142                 return ret;
1143
1144         ret = __rebuild_chunk_items(trans, rc, root);
1145
1146         return ret;
1147 }
1148
1149 static int rebuild_sys_array(struct recover_control *rc,
1150                              struct btrfs_root *root)
1151 {
1152         struct btrfs_chunk *chunk;
1153         struct btrfs_key key;
1154         struct chunk_record *chunk_rec;
1155         int ret = 0;
1156         u16 num_stripes;
1157
1158         btrfs_set_super_sys_array_size(root->fs_info->super_copy, 0);
1159
1160         list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1161                 if (!(chunk_rec->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1162                         continue;
1163
1164                 num_stripes = chunk_rec->num_stripes;
1165                 chunk = create_chunk_item(chunk_rec);
1166                 if (!chunk) {
1167                         ret = -ENOMEM;
1168                         break;
1169                 }
1170
1171                 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1172                 key.type = BTRFS_CHUNK_ITEM_KEY;
1173                 key.offset = chunk_rec->offset;
1174
1175                 ret = btrfs_add_system_chunk(NULL, root, &key, chunk,
1176                                 btrfs_chunk_item_size(num_stripes));
1177                 free(chunk);
1178                 if (ret)
1179                         break;
1180         }
1181         return ret;
1182
1183 }
1184
1185 static struct btrfs_root *
1186 open_ctree_with_broken_chunk(struct recover_control *rc)
1187 {
1188         struct btrfs_fs_info *fs_info;
1189         struct btrfs_super_block *disk_super;
1190         struct extent_buffer *eb;
1191         u32 sectorsize;
1192         u32 nodesize;
1193         u32 leafsize;
1194         u32 stripesize;
1195         int ret;
1196
1197         fs_info = btrfs_new_fs_info(1, BTRFS_SUPER_INFO_OFFSET);
1198         if (!fs_info) {
1199                 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1200                 return ERR_PTR(-ENOMEM);
1201         }
1202
1203         fs_info->fs_devices = rc->fs_devices;
1204         ret = btrfs_open_devices(fs_info->fs_devices, O_RDWR);
1205         if (ret)
1206                 goto out;
1207
1208         disk_super = fs_info->super_copy;
1209         ret = btrfs_read_dev_super(fs_info->fs_devices->latest_bdev,
1210                                    disk_super, fs_info->super_bytenr);
1211         if (ret) {
1212                 fprintf(stderr, "No valid btrfs found\n");
1213                 goto out_devices;
1214         }
1215
1216         memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1217
1218         ret = btrfs_check_fs_compatibility(disk_super, 1);
1219         if (ret)
1220                 goto out_devices;
1221
1222         nodesize = btrfs_super_nodesize(disk_super);
1223         leafsize = btrfs_super_leafsize(disk_super);
1224         sectorsize = btrfs_super_sectorsize(disk_super);
1225         stripesize = btrfs_super_stripesize(disk_super);
1226
1227         __setup_root(nodesize, leafsize, sectorsize, stripesize,
1228                      fs_info->chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
1229
1230         ret = build_device_maps_by_chunk_records(rc, fs_info->chunk_root);
1231         if (ret)
1232                 goto out_cleanup;
1233
1234         ret = btrfs_setup_all_roots(fs_info, 0, 0);
1235         if (ret)
1236                 goto out_failed;
1237
1238         eb = fs_info->tree_root->node;
1239         read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1240                            (unsigned long)btrfs_header_chunk_tree_uuid(eb),
1241                            BTRFS_UUID_SIZE);
1242
1243         return fs_info->fs_root;
1244 out_failed:
1245         btrfs_release_all_roots(fs_info);
1246 out_cleanup:
1247         btrfs_cleanup_all_caches(fs_info);
1248 out_devices:
1249         btrfs_close_devices(fs_info->fs_devices);
1250 out:
1251         btrfs_free_fs_info(fs_info);
1252         return ERR_PTR(ret);
1253 }
1254
1255 static int recover_prepare(struct recover_control *rc, char *path)
1256 {
1257         int ret;
1258         int fd;
1259         struct btrfs_super_block *sb;
1260         struct btrfs_fs_devices *fs_devices;
1261
1262         ret = 0;
1263         fd = open(path, O_RDONLY);
1264         if (fd < 0) {
1265                 fprintf(stderr, "open %s\n error.\n", path);
1266                 return -1;
1267         }
1268
1269         sb = malloc(sizeof(struct btrfs_super_block));
1270         if (!sb) {
1271                 fprintf(stderr, "allocating memory for sb failed.\n");
1272                 ret = -ENOMEM;
1273                 goto fail_close_fd;
1274         }
1275
1276         ret = btrfs_read_dev_super(fd, sb, BTRFS_SUPER_INFO_OFFSET);
1277         if (ret) {
1278                 fprintf(stderr, "read super block error\n");
1279                 goto fail_free_sb;
1280         }
1281
1282         rc->sectorsize = btrfs_super_sectorsize(sb);
1283         rc->leafsize = btrfs_super_leafsize(sb);
1284         rc->generation = btrfs_super_generation(sb);
1285         rc->chunk_root_generation = btrfs_super_chunk_root_generation(sb);
1286         rc->csum_size = btrfs_super_csum_size(sb);
1287
1288         /* if seed, the result of scanning below will be partial */
1289         if (btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_SEEDING) {
1290                 fprintf(stderr, "this device is seed device\n");
1291                 ret = -1;
1292                 goto fail_free_sb;
1293         }
1294
1295         ret = btrfs_scan_fs_devices(fd, path, &fs_devices, 0);
1296         if (ret)
1297                 goto fail_free_sb;
1298
1299         rc->fs_devices = fs_devices;
1300
1301         if (rc->verbose)
1302                 print_all_devices(&rc->fs_devices->devices);
1303
1304 fail_free_sb:
1305         free(sb);
1306 fail_close_fd:
1307         close(fd);
1308         return ret;
1309 }
1310
1311 /*
1312  * This reads a line from the stdin and only returns non-zero if the
1313  * first whitespace delimited token is a case insensitive match with yes
1314  * or y.
1315  */
1316 static int ask_user(char *question)
1317 {
1318         char buf[30] = {0,};
1319         char *saveptr = NULL;
1320         char *answer;
1321
1322         printf("%s [y/N]: ", question);
1323
1324         return fgets(buf, sizeof(buf) - 1, stdin) &&
1325                (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
1326                (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
1327 }
1328
1329 static int btrfs_get_device_extents(u64 chunk_object,
1330                                     struct list_head *orphan_devexts,
1331                                     struct list_head *ret_list)
1332 {
1333         struct device_extent_record *devext;
1334         struct device_extent_record *next;
1335         int count = 0;
1336
1337         list_for_each_entry_safe(devext, next, orphan_devexts, chunk_list) {
1338                 if (devext->chunk_offset == chunk_object) {
1339                         list_move_tail(&devext->chunk_list, ret_list);
1340                         count++;
1341                 }
1342         }
1343         return count;
1344 }
1345
1346 static int calc_num_stripes(u64 type)
1347 {
1348         if (type & (BTRFS_BLOCK_GROUP_RAID0 |
1349                     BTRFS_BLOCK_GROUP_RAID10 |
1350                     BTRFS_BLOCK_GROUP_RAID5 |
1351                     BTRFS_BLOCK_GROUP_RAID6))
1352                 return 0;
1353         else if (type & (BTRFS_BLOCK_GROUP_RAID1 |
1354                          BTRFS_BLOCK_GROUP_DUP))
1355                 return 2;
1356         else
1357                 return 1;
1358 }
1359
1360 static inline int calc_sub_nstripes(u64 type)
1361 {
1362         if (type & BTRFS_BLOCK_GROUP_RAID10)
1363                 return 2;
1364         else
1365                 return 1;
1366 }
1367
1368 static int btrfs_verify_device_extents(struct block_group_record *bg,
1369                                        struct list_head *devexts, int ndevexts)
1370 {
1371         struct device_extent_record *devext;
1372         u64 strpie_length;
1373         int expected_num_stripes;
1374
1375         expected_num_stripes = calc_num_stripes(bg->flags);
1376         if (expected_num_stripes && expected_num_stripes != ndevexts)
1377                 return 1;
1378
1379         strpie_length = calc_stripe_length(bg->flags, bg->offset, ndevexts);
1380         list_for_each_entry(devext, devexts, chunk_list) {
1381                 if (devext->length != strpie_length)
1382                         return 1;
1383         }
1384         return 0;
1385 }
1386
1387 static int btrfs_rebuild_unordered_chunk_stripes(struct recover_control *rc,
1388                                                  struct chunk_record *chunk)
1389 {
1390         struct device_extent_record *devext;
1391         struct btrfs_device *device;
1392         int i;
1393
1394         devext = list_first_entry(&chunk->dextents, struct device_extent_record,
1395                                   chunk_list);
1396         for (i = 0; i < chunk->num_stripes; i++) {
1397                 chunk->stripes[i].devid = devext->objectid;
1398                 chunk->stripes[i].offset = devext->offset;
1399                 device = btrfs_find_device_by_devid(rc->fs_devices,
1400                                                     devext->objectid,
1401                                                     0);
1402                 if (!device)
1403                         return -ENOENT;
1404                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1405                                                   devext->objectid,
1406                                                   1));
1407                 memcpy(chunk->stripes[i].dev_uuid, device->uuid,
1408                        BTRFS_UUID_SIZE);
1409                 devext = list_next_entry(devext, chunk_list);
1410         }
1411         return 0;
1412 }
1413
1414 static int btrfs_calc_stripe_index(struct chunk_record *chunk, u64 logical)
1415 {
1416         u64 offset = logical - chunk->offset;
1417         int stripe_nr;
1418         int nr_data_stripes;
1419         int index;
1420
1421         stripe_nr = offset / chunk->stripe_len;
1422         if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID0) {
1423                 index = stripe_nr % chunk->num_stripes;
1424         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID10) {
1425                 index = stripe_nr % (chunk->num_stripes / chunk->sub_stripes);
1426                 index *= chunk->sub_stripes;
1427         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5) {
1428                 nr_data_stripes = chunk->num_stripes - 1;
1429                 index = stripe_nr % nr_data_stripes;
1430                 stripe_nr /= nr_data_stripes;
1431                 index = (index + stripe_nr) % chunk->num_stripes;
1432         } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6) {
1433                 nr_data_stripes = chunk->num_stripes - 2;
1434                 index = stripe_nr % nr_data_stripes;
1435                 stripe_nr /= nr_data_stripes;
1436                 index = (index + stripe_nr) % chunk->num_stripes;
1437         } else {
1438                 BUG_ON(1);
1439         }
1440         return index;
1441 }
1442
1443 /* calc the logical offset which is the start of the next stripe. */
1444 static inline u64 btrfs_next_stripe_logical_offset(struct chunk_record *chunk,
1445                                                    u64 logical)
1446 {
1447         u64 offset = logical - chunk->offset;
1448
1449         offset /= chunk->stripe_len;
1450         offset *= chunk->stripe_len;
1451         offset += chunk->stripe_len;
1452
1453         return offset + chunk->offset;
1454 }
1455
1456 static int is_extent_record_in_device_extent(struct extent_record *er,
1457                                              struct device_extent_record *dext,
1458                                              int *mirror)
1459 {
1460         int i;
1461
1462         for (i = 0; i < er->nmirrors; i++) {
1463                 if (er->devices[i]->devid == dext->objectid &&
1464                     er->offsets[i] >= dext->offset &&
1465                     er->offsets[i] < dext->offset + dext->length) {
1466                         *mirror = i;
1467                         return 1;
1468                 }
1469         }
1470         return 0;
1471 }
1472
1473 static int
1474 btrfs_rebuild_ordered_meta_chunk_stripes(struct recover_control *rc,
1475                                          struct chunk_record *chunk)
1476 {
1477         u64 start = chunk->offset;
1478         u64 end = chunk->offset + chunk->length;
1479         struct cache_extent *cache;
1480         struct extent_record *er;
1481         struct device_extent_record *devext;
1482         struct device_extent_record *next;
1483         struct btrfs_device *device;
1484         LIST_HEAD(devexts);
1485         int index;
1486         int mirror;
1487         int ret;
1488
1489         cache = lookup_cache_extent(&rc->eb_cache,
1490                                     start, chunk->length);
1491         if (!cache) {
1492                 /* No used space, we can reorder the stripes freely. */
1493                 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1494                 return ret;
1495         }
1496
1497         list_splice_init(&chunk->dextents, &devexts);
1498 again:
1499         er = container_of(cache, struct extent_record, cache);
1500         index = btrfs_calc_stripe_index(chunk, er->cache.start);
1501         if (chunk->stripes[index].devid)
1502                 goto next;
1503         list_for_each_entry_safe(devext, next, &devexts, chunk_list) {
1504                 if (is_extent_record_in_device_extent(er, devext, &mirror)) {
1505                         chunk->stripes[index].devid = devext->objectid;
1506                         chunk->stripes[index].offset = devext->offset;
1507                         memcpy(chunk->stripes[index].dev_uuid,
1508                                er->devices[mirror]->uuid,
1509                                BTRFS_UUID_SIZE);
1510                         index++;
1511                         list_move(&devext->chunk_list, &chunk->dextents);
1512                 }
1513         }
1514 next:
1515         start = btrfs_next_stripe_logical_offset(chunk, er->cache.start);
1516         if (start >= end)
1517                 goto no_extent_record;
1518
1519         cache = lookup_cache_extent(&rc->eb_cache, start, end - start);
1520         if (cache)
1521                 goto again;
1522 no_extent_record:
1523         if (list_empty(&devexts))
1524                 return 0;
1525
1526         if (chunk->type_flags & (BTRFS_BLOCK_GROUP_RAID5 |
1527                                  BTRFS_BLOCK_GROUP_RAID6)) {
1528                 /* Fixme: try to recover the order by the parity block. */
1529                 list_splice_tail(&devexts, &chunk->dextents);
1530                 return -EINVAL;
1531         }
1532
1533         /* There is no data on the lost stripes, we can reorder them freely. */
1534         for (index = 0; index < chunk->num_stripes; index++) {
1535                 if (chunk->stripes[index].devid)
1536                         continue;
1537
1538                 devext = list_first_entry(&devexts,
1539                                           struct device_extent_record,
1540                                            chunk_list);
1541                 list_move(&devext->chunk_list, &chunk->dextents);
1542
1543                 chunk->stripes[index].devid = devext->objectid;
1544                 chunk->stripes[index].offset = devext->offset;
1545                 device = btrfs_find_device_by_devid(rc->fs_devices,
1546                                                     devext->objectid,
1547                                                     0);
1548                 if (!device) {
1549                         list_splice_tail(&devexts, &chunk->dextents);
1550                         return -EINVAL;
1551                 }
1552                 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1553                                                   devext->objectid,
1554                                                   1));
1555                 memcpy(chunk->stripes[index].dev_uuid, device->uuid,
1556                        BTRFS_UUID_SIZE);
1557         }
1558         return 0;
1559 }
1560
1561 #define BTRFS_ORDERED_RAID      (BTRFS_BLOCK_GROUP_RAID0 |      \
1562                                  BTRFS_BLOCK_GROUP_RAID10 |     \
1563                                  BTRFS_BLOCK_GROUP_RAID5 |      \
1564                                  BTRFS_BLOCK_GROUP_RAID6)
1565
1566 static int btrfs_rebuild_chunk_stripes(struct recover_control *rc,
1567                                        struct chunk_record *chunk)
1568 {
1569         int ret;
1570
1571         /*
1572          * All the data in the system metadata chunk will be dropped,
1573          * so we need not guarantee that the data is right or not, that
1574          * is we can reorder the stripes in the system metadata chunk.
1575          */
1576         if ((chunk->type_flags & BTRFS_BLOCK_GROUP_METADATA) &&
1577             (chunk->type_flags & BTRFS_ORDERED_RAID))
1578                 ret =btrfs_rebuild_ordered_meta_chunk_stripes(rc, chunk);
1579         else if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA) &&
1580                  (chunk->type_flags & BTRFS_ORDERED_RAID))
1581                 ret = 1;        /* Be handled after the fs is opened. */
1582         else
1583                 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1584
1585         return ret;
1586 }
1587
1588 static int btrfs_recover_chunks(struct recover_control *rc)
1589 {
1590         struct chunk_record *chunk;
1591         struct block_group_record *bg;
1592         struct block_group_record *next;
1593         LIST_HEAD(new_chunks);
1594         LIST_HEAD(devexts);
1595         int nstripes;
1596         int ret;
1597
1598         /* create the chunk by block group */
1599         list_for_each_entry_safe(bg, next, &rc->bg.block_groups, list) {
1600                 nstripes = btrfs_get_device_extents(bg->objectid,
1601                                                     &rc->devext.no_chunk_orphans,
1602                                                     &devexts);
1603                 chunk = malloc(btrfs_chunk_record_size(nstripes));
1604                 if (!chunk)
1605                         return -ENOMEM;
1606                 memset(chunk, 0, btrfs_chunk_record_size(nstripes));
1607                 INIT_LIST_HEAD(&chunk->dextents);
1608                 chunk->bg_rec = bg;
1609                 chunk->cache.start = bg->objectid;
1610                 chunk->cache.size = bg->offset;
1611                 chunk->objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1612                 chunk->type = BTRFS_CHUNK_ITEM_KEY;
1613                 chunk->offset = bg->objectid;
1614                 chunk->generation = bg->generation;
1615                 chunk->length = bg->offset;
1616                 chunk->owner = BTRFS_CHUNK_TREE_OBJECTID;
1617                 chunk->stripe_len = BTRFS_STRIPE_LEN;
1618                 chunk->type_flags = bg->flags;
1619                 chunk->io_width = BTRFS_STRIPE_LEN;
1620                 chunk->io_align = BTRFS_STRIPE_LEN;
1621                 chunk->sector_size = rc->sectorsize;
1622                 chunk->sub_stripes = calc_sub_nstripes(bg->flags);
1623
1624                 ret = insert_cache_extent(&rc->chunk, &chunk->cache);
1625                 BUG_ON(ret);
1626
1627                 if (!nstripes) {
1628                         list_add_tail(&chunk->list, &rc->bad_chunks);
1629                         continue;
1630                 }
1631
1632                 list_splice_init(&devexts, &chunk->dextents);
1633
1634                 ret = btrfs_verify_device_extents(bg, &devexts, nstripes);
1635                 if (ret) {
1636                         list_add_tail(&chunk->list, &rc->bad_chunks);
1637                         continue;
1638                 }
1639
1640                 chunk->num_stripes = nstripes;
1641                 ret = btrfs_rebuild_chunk_stripes(rc, chunk);
1642                 if (ret > 0)
1643                         list_add_tail(&chunk->list, &rc->unrepaired_chunks);
1644                 else if (ret < 0)
1645                         list_add_tail(&chunk->list, &rc->bad_chunks);
1646                 else
1647                         list_add_tail(&chunk->list, &rc->good_chunks);
1648         }
1649         /*
1650          * Don't worry about the lost orphan device extents, they don't
1651          * have its chunk and block group, they must be the old ones that
1652          * we have dropped.
1653          */
1654         return 0;
1655 }
1656
1657 static int btrfs_recover_chunk_tree(char *path, int verbose, int yes)
1658 {
1659         int ret = 0;
1660         struct btrfs_root *root = NULL;
1661         struct btrfs_trans_handle *trans;
1662         struct recover_control rc;
1663
1664         init_recover_control(&rc, verbose, yes);
1665
1666         ret = recover_prepare(&rc, path);
1667         if (ret) {
1668                 fprintf(stderr, "recover prepare error\n");
1669                 return ret;
1670         }
1671
1672         ret = scan_devices(&rc);
1673         if (ret) {
1674                 fprintf(stderr, "scan chunk headers error\n");
1675                 goto fail_rc;
1676         }
1677
1678         if (cache_tree_empty(&rc.chunk) &&
1679             cache_tree_empty(&rc.bg.tree) &&
1680             cache_tree_empty(&rc.devext.tree)) {
1681                 fprintf(stderr, "no recoverable chunk\n");
1682                 goto fail_rc;
1683         }
1684
1685         print_scan_result(&rc);
1686
1687         ret = check_chunks(&rc.chunk, &rc.bg, &rc.devext, &rc.good_chunks,
1688                            &rc.bad_chunks, 1);
1689         print_check_result(&rc);
1690         if (ret) {
1691                 if (!list_empty(&rc.bg.block_groups) ||
1692                     !list_empty(&rc.devext.no_chunk_orphans)) {
1693                         ret = btrfs_recover_chunks(&rc);
1694                         if (ret)
1695                                 goto fail_rc;
1696                 }
1697                 /*
1698                  * If the chunk is healthy, its block group item and device
1699                  * extent item should be written on the disks. So, it is very
1700                  * likely that the bad chunk is a old one that has been
1701                  * droppped from the fs. Don't deal with them now, we will
1702                  * check it after the fs is opened.
1703                  */
1704         }
1705
1706         root = open_ctree_with_broken_chunk(&rc);
1707         if (IS_ERR(root)) {
1708                 fprintf(stderr, "open with broken chunk error\n");
1709                 ret = PTR_ERR(root);
1710                 goto fail_rc;
1711         }
1712
1713         ret = check_all_chunks_by_metadata(&rc, root);
1714         if (ret) {
1715                 fprintf(stderr, "The chunks in memory can not match the metadata of the fs. Repair failed.\n");
1716                 goto fail_close_ctree;
1717         }
1718
1719         if (!rc.yes) {
1720                 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?");
1721                 if (!ret) {
1722                         ret = BTRFS_CHUNK_TREE_REBUILD_ABORTED;
1723                         goto fail_close_ctree;
1724                 }
1725         }
1726
1727         trans = btrfs_start_transaction(root, 1);
1728         ret = remove_chunk_extent_item(trans, &rc, root);
1729         BUG_ON(ret);
1730
1731         ret = rebuild_chunk_tree(trans, &rc, root);
1732         BUG_ON(ret);
1733
1734         ret = rebuild_sys_array(&rc, root);
1735         BUG_ON(ret);
1736
1737         btrfs_commit_transaction(trans, root);
1738 fail_close_ctree:
1739         close_ctree(root);
1740 fail_rc:
1741         free_recover_control(&rc);
1742         return ret;
1743 }
1744
1745 const char * const cmd_chunk_recover_usage[] = {
1746         "btrfs rescue chunk-recover [options] <device>",
1747         "Recover the chunk tree by scanning the devices one by one.",
1748         "",
1749         "-y     Assume an answer of `yes' to all questions",
1750         "-v     Verbose mode",
1751         "-h     Help",
1752         NULL
1753 };
1754
1755 int cmd_chunk_recover(int argc, char *argv[])
1756 {
1757         int ret = 0;
1758         char *file;
1759         int yes = 0;
1760         int verbose = 0;
1761
1762         while (1) {
1763                 int c = getopt(argc, argv, "yvh");
1764                 if (c < 0)
1765                         break;
1766                 switch (c) {
1767                 case 'y':
1768                         yes = 1;
1769                         break;
1770                 case 'v':
1771                         verbose = 1;
1772                         break;
1773                 case 'h':
1774                 default:
1775                         usage(cmd_chunk_recover_usage);
1776                 }
1777         }
1778
1779         argc = argc - optind;
1780         if (argc == 0)
1781                 usage(cmd_chunk_recover_usage);
1782
1783         file = argv[optind];
1784
1785         ret = check_mounted(file);
1786         if (ret) {
1787                 fprintf(stderr, "the device is busy\n");
1788                 goto out;
1789         }
1790
1791         ret = btrfs_recover_chunk_tree(file, verbose, yes);
1792         if (!ret) {
1793                 fprintf(stdout, "Recover the chunk tree successfully.\n");
1794         } else if (ret == BTRFS_CHUNK_TREE_REBUILD_ABORTED) {
1795                 ret = 0;
1796                 fprintf(stdout, "Abort to rebuild the on-disk chunk tree.\n");
1797         } else {
1798                 fprintf(stdout, "Fail to recover the chunk tree.\n");
1799         }
1800 out:
1801         return !!ret;
1802 }