btrfs-progs: tests: add fuzzed images with bad blocksize/lengh of eb
[platform/upstream/btrfs-progs.git] / qgroup-verify.c
1 /*
2  * Copyright (C) 2014 SUSE.  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  * Authors: Mark Fasheh <mfasheh@suse.de>
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <uuid/uuid.h>
24 #include "kerncompat.h"
25 #include "radix-tree.h"
26 #include "ctree.h"
27 #include "disk-io.h"
28 #include "print-tree.h"
29 #include "utils.h"
30 #include "ulist.h"
31 #include "rbtree-utils.h"
32 #include "transaction.h"
33 #include "repair.h"
34
35 #include "qgroup-verify.h"
36
37 /*#define QGROUP_VERIFY_DEBUG*/
38 static unsigned long tot_extents_scanned = 0;
39
40 struct qgroup_count;
41 static struct qgroup_count *find_count(u64 qgroupid);
42
43 struct qgroup_info {
44         u64 referenced;
45         u64 referenced_compressed;
46         u64 exclusive;
47         u64 exclusive_compressed;
48 };
49
50 struct qgroup_count {
51         u64 qgroupid;
52         int subvol_exists;
53
54         struct btrfs_disk_key key;
55         struct qgroup_info diskinfo;
56
57         struct qgroup_info info;
58
59         struct rb_node rb_node;
60
61         /* Parents when we are a child group */
62         struct list_head groups;
63
64         /*
65          * Children when we are a parent group (not currently used but
66          * maintained to mirror kernel handling of qgroups)
67          */
68         struct list_head members;
69
70         u64 cur_refcnt;
71
72         struct list_head bad_list;
73 };
74
75 static struct counts_tree {
76         struct rb_root          root;
77         unsigned int            num_groups;
78         unsigned int            rescan_running:1;
79         unsigned int            qgroup_inconsist:1;
80 } counts = { .root = RB_ROOT };
81
82 static LIST_HEAD(bad_qgroups);
83
84 static struct rb_root by_bytenr = RB_ROOT;
85
86 /*
87  * Glue structure to represent the relations between qgroups. Mirrored
88  * from kernel.
89  */
90 struct btrfs_qgroup_list {
91         struct list_head next_group;
92         struct list_head next_member;
93         struct qgroup_count *group; /* Parent group */
94         struct qgroup_count *member;
95 };
96
97 /* Allow us to reset ref counts during accounting without zeroing each group. */
98 static u64 qgroup_seq = 1ULL;
99
100 static inline void update_cur_refcnt(struct qgroup_count *c)
101 {
102         if (c->cur_refcnt < qgroup_seq)
103                 c->cur_refcnt = qgroup_seq;
104         c->cur_refcnt++;
105 }
106
107 static inline u64 group_get_cur_refcnt(struct qgroup_count *c)
108 {
109         if (c->cur_refcnt < qgroup_seq)
110                 return 0;
111         return c->cur_refcnt - qgroup_seq;
112 }
113
114 static void inc_qgroup_seq(int root_count)
115 {
116         qgroup_seq += root_count + 1;
117 }
118
119 /*
120  * List of interior tree blocks. We walk this list after loading the
121  * extent tree to resolve implied refs. For each interior node we'll
122  * place a shared ref in the ref tree against each child object. This
123  * allows the shared ref resolving code to do the actual work later of
124  * finding roots to account against.
125  *
126  * An implied ref is when a tree block has refs on it that may not
127  * exist in any of its child nodes. Even though the refs might not
128  * exist further down the tree, the fact that our interior node has a
129  * ref means we need to account anything below it to all its roots.
130  */
131 static struct ulist *tree_blocks = NULL;        /* unode->val = bytenr, ->aux
132                                                  * = tree_block pointer */
133 struct tree_block {
134         int                     level;
135         u64                     num_bytes;
136 };
137
138 struct ref {
139         u64                     bytenr;
140         u64                     num_bytes;
141         u64                     parent;
142         u64                     root;
143
144         struct rb_node          bytenr_node;
145 };
146
147 #ifdef QGROUP_VERIFY_DEBUG
148 static void print_ref(struct ref *ref)
149 {
150         printf("bytenr: %llu\t\tnum_bytes: %llu\t\t parent: %llu\t\t"
151                "root: %llu\n", ref->bytenr, ref->num_bytes,
152                ref->parent, ref->root);
153 }
154
155 static void print_all_refs(void)
156 {
157         unsigned long count = 0;
158         struct ref *ref;
159         struct rb_node *node;
160
161         node = rb_first(&by_bytenr);
162         while (node) {
163                 ref = rb_entry(node, struct ref, bytenr_node);
164
165                 print_ref(ref);
166
167                 count++;
168                 node = rb_next(node);
169         }
170
171         printf("%lu extents scanned with %lu refs in total.\n",
172                tot_extents_scanned, count);
173 }
174 #endif
175
176 /*
177  * Store by bytenr in rbtree
178  *
179  * The tree is sorted in ascending order by bytenr, then parent, then
180  * root. Since full refs have a parent == 0, those will come before
181  * shared refs.
182  */
183 static int compare_ref(struct ref *orig, u64 bytenr, u64 root, u64 parent)
184 {
185         if (bytenr < orig->bytenr)
186                 return -1;
187         if (bytenr > orig->bytenr)
188                 return 1;
189
190         if (parent < orig->parent)
191                 return -1;
192         if (parent > orig->parent)
193                 return 1;
194
195         if (root < orig->root)
196                 return -1;
197         if (root > orig->root)
198                 return 1;
199
200         return 0;
201 }
202
203 /*
204  * insert a new ref into the tree.  returns the existing ref entry
205  * if one is already there.
206  */
207 static struct ref *insert_ref(struct ref *ref)
208 {
209         int ret;
210         struct rb_node **p = &by_bytenr.rb_node;
211         struct rb_node *parent = NULL;
212         struct ref *curr;
213
214         while (*p) {
215                 parent = *p;
216                 curr = rb_entry(parent, struct ref, bytenr_node);
217
218                 ret = compare_ref(curr, ref->bytenr, ref->root, ref->parent);
219                 if (ret < 0)
220                         p = &(*p)->rb_left;
221                 else if (ret > 0)
222                         p = &(*p)->rb_right;
223                 else
224                         return curr;
225         }
226
227         rb_link_node(&ref->bytenr_node, parent, p);
228         rb_insert_color(&ref->bytenr_node, &by_bytenr);
229         return ref;
230 }
231
232 /*
233  * Partial search, returns the first ref with matching bytenr. Caller
234  * can walk forward from there.
235  *
236  * Leftmost refs will be full refs - this is used to our advantage
237  * when resolving roots.
238  */
239 static struct ref *find_ref_bytenr(u64 bytenr)
240 {
241         struct rb_node *n = by_bytenr.rb_node;
242         struct ref *ref;
243
244         while (n) {
245                 ref = rb_entry(n, struct ref, bytenr_node);
246
247                 if (bytenr < ref->bytenr)
248                         n = n->rb_left;
249                 else if (bytenr > ref->bytenr)
250                         n = n->rb_right;
251                 else {
252                         /* Walk to the left to find the first item */
253                         struct rb_node *node_left = rb_prev(&ref->bytenr_node);
254                         struct ref *ref_left;
255
256                         while (node_left) {
257                                 ref_left = rb_entry(node_left, struct ref,
258                                                     bytenr_node);
259                                 if (ref_left->bytenr != ref->bytenr)
260                                         break;
261                                 ref = ref_left;
262                                 node_left = rb_prev(node_left);
263                         }
264                         return ref;
265                 }
266         }
267         return NULL;
268 }
269
270 static struct ref *find_ref(u64 bytenr, u64 root, u64 parent)
271 {
272         struct rb_node *n = by_bytenr.rb_node;
273         struct ref *ref;
274         int ret;
275
276         while (n) {
277                 ref = rb_entry(n, struct ref, bytenr_node);
278
279                 ret = compare_ref(ref, bytenr, root, parent);
280                 if (ret < 0)
281                         n = n->rb_left;
282                 else if (ret > 0)
283                         n = n->rb_right;
284                 else
285                         return ref;
286         }
287         return NULL;
288 }
289
290 static struct ref *alloc_ref(u64 bytenr, u64 root, u64 parent, u64 num_bytes)
291 {
292         struct ref *ref = find_ref(bytenr, root, parent);
293
294         BUG_ON(parent && root);
295
296         if (ref == NULL) {
297                 ref = calloc(1, sizeof(*ref));
298                 if (ref) {
299                         ref->bytenr = bytenr;
300                         ref->root = root;
301                         ref->parent = parent;
302                         ref->num_bytes = num_bytes;
303
304                         insert_ref(ref);
305                 }
306         }
307         return ref;
308 }
309
310 static void free_ref_node(struct rb_node *node)
311 {
312         struct ref *ref = rb_entry(node, struct ref, bytenr_node);
313         free(ref);
314 }
315
316 FREE_RB_BASED_TREE(ref, free_ref_node);
317
318 /*
319  * Resolves all the possible roots for the ref at parent.
320  */
321 static int find_parent_roots(struct ulist *roots, u64 parent)
322 {
323         struct ref *ref;
324         struct rb_node *node;
325         int ret;
326
327         /*
328          * Search the rbtree for the first ref with bytenr == parent.
329          * Walk forward so long as bytenr == parent, adding resolved root ids.
330          * For each unresolved root, we recurse
331          */
332         ref = find_ref_bytenr(parent);
333         node = &ref->bytenr_node;
334         BUG_ON(ref == NULL);
335         BUG_ON(ref->bytenr != parent);
336
337         {
338                 /*
339                  * Random sanity check, are we actually getting the
340                  * leftmost node?
341                  */
342                 struct rb_node *prev_node = rb_prev(&ref->bytenr_node);
343                 struct ref *prev;
344                 if (prev_node) {
345                         prev = rb_entry(prev_node, struct ref, bytenr_node);
346                         BUG_ON(prev->bytenr == parent);
347                 }
348         }
349
350         do {
351                 if (ref->root) {
352                         if (is_fstree(ref->root)) {
353                                 ret = ulist_add(roots, ref->root, 0, 0);
354                                 if (ret < 0)
355                                         goto out;
356                         }
357                 } else {
358                         ret = find_parent_roots(roots, ref->parent);
359                         if (ret < 0)
360                                 goto out;
361                 }
362
363                 node = rb_next(node);
364                 if (node)
365                         ref = rb_entry(node, struct ref, bytenr_node);
366         } while (node && ref->bytenr == parent);
367
368         ret = 0;
369 out:
370         return ret;
371 }
372
373 static int account_one_extent(struct ulist *roots, u64 bytenr, u64 num_bytes)
374 {
375         int ret;
376         u64 id, nr_roots, nr_refs;
377         struct qgroup_count *count;
378         struct ulist *counts = ulist_alloc(0);
379         struct ulist *tmp = ulist_alloc(0);
380         struct ulist_iterator uiter;
381         struct ulist_iterator tmp_uiter;
382         struct ulist_node *unode;
383         struct ulist_node *tmp_unode;
384         struct btrfs_qgroup_list *glist;
385
386         if (!counts || !tmp) {
387                 ulist_free(counts);
388                 ulist_free(tmp);
389                 return ENOMEM;
390         }
391
392         ULIST_ITER_INIT(&uiter);
393         while ((unode = ulist_next(roots, &uiter))) {
394                 BUG_ON(unode->val == 0ULL);
395
396                 /*
397                  * For each root, find their corresponding tracking group and
398                  * add it to our qgroups list.
399                  */
400                 count = find_count(unode->val);
401                 if (!count)
402                         continue;
403
404                 BUG_ON(!is_fstree(unode->val));
405                 ret = ulist_add(counts, count->qgroupid, ptr_to_u64(count), 0);
406                 if (ret < 0)
407                         goto out;
408
409                 /*
410                  * Now we look for parents (and parents of those...). Use a tmp
411                  * ulist here to avoid re-walking (and re-incrementing) our
412                  * already added items on every loop iteration.
413                  */
414                 ulist_reinit(tmp);
415                 ret = ulist_add(tmp, count->qgroupid, ptr_to_u64(count), 0);
416                 if (ret < 0)
417                         goto out;
418
419                 ULIST_ITER_INIT(&tmp_uiter);
420                 while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
421                         /* Bump the refcount on a node every time we see it. */
422                         count = u64_to_ptr(tmp_unode->aux);
423                         update_cur_refcnt(count);
424
425                         list_for_each_entry(glist, &count->groups, next_group) {
426                                 struct qgroup_count *parent;
427                                 parent = glist->group;
428                                 id = parent->qgroupid;
429
430                                 BUG_ON(!count);
431
432                                 ret = ulist_add(counts, id, ptr_to_u64(parent),
433                                                 0);
434                                 if (ret < 0)
435                                         goto out;
436                                 ret = ulist_add(tmp, id, ptr_to_u64(parent),
437                                                 0);
438                                 if (ret < 0)
439                                         goto out;
440                         }
441                 }
442         }
443
444         /*
445          * Now that we have gathered up and counted all the groups, we
446          * can add bytes for this ref.
447          */
448         nr_roots = roots->nnodes;
449         ULIST_ITER_INIT(&uiter);
450         while ((unode = ulist_next(counts, &uiter))) {
451                 count = u64_to_ptr(unode->aux);
452
453                 nr_refs = group_get_cur_refcnt(count);
454                 if (nr_refs) {
455                         count->info.referenced += num_bytes;
456                         count->info.referenced_compressed += num_bytes;
457
458                         if (nr_refs == nr_roots) {
459                                 count->info.exclusive += num_bytes;
460                                 count->info.exclusive_compressed += num_bytes;
461                         }
462                 }
463 #ifdef QGROUP_VERIFY_DEBUG
464                 printf("account (%llu, %llu), qgroup %llu/%llu, rfer %llu,"
465                        " excl %llu, refs %llu, roots %llu\n", bytenr, num_bytes,
466                        btrfs_qgroup_level(count->qgroupid),
467                        btrfs_qgroup_subvid(count->qgroupid),
468                        count->info.referenced, count->info.exclusive, nr_refs,
469                        nr_roots);
470 #endif
471         }
472
473         inc_qgroup_seq(roots->nnodes);
474         ret = 0;
475 out:
476         ulist_free(counts);
477         ulist_free(tmp);
478         return ret;
479 }
480
481 static void print_subvol_info(u64 subvolid, u64 bytenr, u64 num_bytes,
482                               struct ulist *roots);
483 /*
484  * Account each ref. Walk the refs, for each set of refs in a
485  * given bytenr:
486  *
487  * - add the roots for direct refs to the ref roots ulist
488  *
489  * - resolve all possible roots for shared refs, insert each
490  *   of those into ref_roots ulist (this is a recursive process)
491  *
492  * - With all roots resolved we can account the ref - this is done in
493  *   account_one_extent().
494  */
495 static int account_all_refs(int do_qgroups, u64 search_subvol)
496 {
497         struct ref *ref;
498         struct rb_node *node;
499         u64 bytenr, num_bytes;
500         struct ulist *roots = ulist_alloc(0);
501         int ret;
502
503         node = rb_first(&by_bytenr);
504         while (node) {
505                 ulist_reinit(roots);
506
507                 ref = rb_entry(node, struct ref, bytenr_node);
508                 /*
509                  * Walk forward through the list of refs for this
510                  * bytenr, adding roots to our ulist. If it's a full
511                  * ref, then we have the easy case. Otherwise we need
512                  * to search for roots.
513                  */
514                 bytenr = ref->bytenr;
515                 num_bytes = ref->num_bytes;
516                 do {
517                         BUG_ON(ref->bytenr != bytenr);
518                         BUG_ON(ref->num_bytes != num_bytes);
519                         if (ref->root) {
520                                 if (is_fstree(ref->root)) {
521                                         if (ulist_add(roots, ref->root, 0, 0) < 0)
522                                                 goto enomem;
523                                 }
524                         } else {
525                                 ret = find_parent_roots(roots, ref->parent);
526                                 if (ret < 0)
527                                         goto enomem;
528                         }
529
530                         /*
531                          * When we leave this inner loop, node is set
532                          * to next in our tree and will be turned into
533                          * a ref object up top
534                          */
535                         node = rb_next(node);
536                         if (node)
537                                 ref = rb_entry(node, struct ref, bytenr_node);
538                 } while (node && ref->bytenr == bytenr);
539
540                 if (search_subvol)
541                         print_subvol_info(search_subvol, bytenr, num_bytes,
542                                           roots);
543
544                 if (!do_qgroups)
545                         continue;
546
547                 if (account_one_extent(roots, bytenr, num_bytes))
548                         goto enomem;
549         }
550
551         ulist_free(roots);
552         return 0;
553 enomem:
554         error("Out of memory while accounting refs for qgroups");
555         return -ENOMEM;
556 }
557
558 static u64 resolve_one_root(u64 bytenr)
559 {
560         struct ref *ref = find_ref_bytenr(bytenr);
561
562         BUG_ON(ref == NULL);
563
564         if (ref->root)
565                 return ref->root;
566         return resolve_one_root(ref->parent);
567 }
568
569 static inline struct tree_block *unode_tree_block(struct ulist_node *unode)
570 {
571         return u64_to_ptr(unode->aux);
572 }
573 static inline u64 unode_bytenr(struct ulist_node *unode)
574 {
575         return unode->val;
576 }
577
578 static int alloc_tree_block(u64 bytenr, u64 num_bytes, int level)
579 {
580         struct tree_block *block = calloc(1, sizeof(*block));
581
582         if (block) {
583                 block->num_bytes = num_bytes;
584                 block->level = level;
585                 if (ulist_add(tree_blocks, bytenr, ptr_to_u64(block), 0) >= 0)
586                         return 0;
587                 free(block);
588         }
589         return -ENOMEM;
590 }
591
592 static void free_tree_blocks(void)
593 {
594         struct ulist_iterator uiter;
595         struct ulist_node *unode;
596
597         if (!tree_blocks)
598                 return;
599
600         ULIST_ITER_INIT(&uiter);
601         while ((unode = ulist_next(tree_blocks, &uiter)))
602                 free(unode_tree_block(unode));
603         ulist_free(tree_blocks);        
604         tree_blocks = NULL;
605 }
606
607 #ifdef QGROUP_VERIFY_DEBUG
608 static void print_tree_block(u64 bytenr, struct tree_block *block)
609 {
610         struct ref *ref;
611         struct rb_node *node;
612
613         printf("tree block: %llu\t\tlevel: %d\n", (unsigned long long)bytenr,
614                block->level);
615
616         ref = find_ref_bytenr(bytenr);
617         node = &ref->bytenr_node;
618         do {
619                 print_ref(ref);
620                 node = rb_next(node);
621                 if (node)
622                         ref = rb_entry(node, struct ref, bytenr_node);
623         } while (node && ref->bytenr == bytenr);
624
625         printf("\n");
626 }
627
628 static void print_all_tree_blocks(void)
629 {
630         struct ulist_iterator uiter;
631         struct ulist_node *unode;
632
633         if (!tree_blocks)
634                 return;
635
636         printf("Listing all found interior tree nodes:\n");
637
638         ULIST_ITER_INIT(&uiter);
639         while ((unode = ulist_next(tree_blocks, &uiter)))
640                 print_tree_block(unode_bytenr(unode), unode_tree_block(unode));
641 }
642 #endif
643
644 static int add_refs_for_leaf_items(struct extent_buffer *eb, u64 ref_parent)
645 {
646         int nr, i;
647         int extent_type;
648         u64 bytenr, num_bytes;
649         struct btrfs_key key;
650         struct btrfs_disk_key disk_key;
651         struct btrfs_file_extent_item *fi;
652
653         nr = btrfs_header_nritems(eb);
654         for (i = 0; i < nr; i++) {
655                 btrfs_item_key(eb, &disk_key, i);
656                 btrfs_disk_key_to_cpu(&key, &disk_key);
657
658                 if (key.type != BTRFS_EXTENT_DATA_KEY)
659                         continue;
660
661                 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
662                 /* filter out: inline, disk_bytenr == 0, compressed?
663                  * not if we can avoid it */
664                 extent_type = btrfs_file_extent_type(eb, fi);
665
666                 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
667                         continue;
668
669                 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
670                 if (!bytenr)
671                         continue;
672
673                 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
674                 if (alloc_ref(bytenr, 0, ref_parent, num_bytes) == NULL)
675                         return ENOMEM;
676         }
677
678         return 0;
679 }
680
681 static int travel_tree(struct btrfs_fs_info *info, struct btrfs_root *root,
682                        u64 bytenr, u64 num_bytes, u64 ref_parent)
683 {
684         int ret, nr, i;
685         struct extent_buffer *eb;
686         u64 new_bytenr;
687         u64 new_num_bytes;
688
689 //      printf("travel_tree: bytenr: %llu\tnum_bytes: %llu\tref_parent: %llu\n",
690 //             bytenr, num_bytes, ref_parent);
691
692         eb = read_tree_block(root, bytenr, num_bytes, 0);
693         if (!extent_buffer_uptodate(eb))
694                 return -EIO;
695
696         ret = 0;
697         /* Don't add a ref for our starting tree block to itself */
698         if (bytenr != ref_parent) {
699                 if (alloc_ref(bytenr, 0, ref_parent, num_bytes) == NULL)
700                         return ENOMEM;
701         }
702
703         if (btrfs_is_leaf(eb)) {
704                 ret = add_refs_for_leaf_items(eb, ref_parent);
705                 goto out;
706         }
707
708         /*
709          * Interior nodes are tuples of (key, bytenr) where key is the
710          * leftmost key in the tree block pointed to by bytenr. We
711          * don't have to care about key here, just follow the bytenr
712          * pointer.
713          */
714         nr = btrfs_header_nritems(eb);
715         for (i = 0; i < nr; i++) {
716                 new_bytenr = btrfs_node_blockptr(eb, i);
717                 new_num_bytes = root->nodesize;
718
719                 ret = travel_tree(info, root, new_bytenr, new_num_bytes,
720                                   ref_parent);
721         }
722
723 out:
724         free_extent_buffer(eb);
725         return ret;
726 }
727
728 static int add_refs_for_implied(struct btrfs_fs_info *info, u64 bytenr,
729                                 struct tree_block *block)
730 {
731         int ret;
732         u64 root_id = resolve_one_root(bytenr);
733         struct btrfs_root *root;
734         struct btrfs_key key;
735
736         key.objectid = root_id;
737         key.type = BTRFS_ROOT_ITEM_KEY;
738         key.offset = (u64)-1;
739
740         /*
741          * XXX: Don't free the root object as we don't know whether it
742          * came off our fs_info struct or not.
743          */
744         root = btrfs_read_fs_root(info, &key);
745         if (!root || IS_ERR(root))
746                 return ENOENT;
747
748         ret = travel_tree(info, root, bytenr, block->num_bytes, bytenr);
749         if (ret)
750                 return ret;
751
752         return 0;
753 }
754
755 /*
756  * Place shared refs in the ref tree for each child of an interior tree node.
757  */
758 static int map_implied_refs(struct btrfs_fs_info *info)
759 {
760         int ret = 0;
761         struct ulist_iterator uiter;
762         struct ulist_node *unode;
763
764         ULIST_ITER_INIT(&uiter);
765         while ((unode = ulist_next(tree_blocks, &uiter))) {
766                 ret = add_refs_for_implied(info, unode_bytenr(unode),
767                                            unode_tree_block(unode));
768                 if (ret)
769                         goto out;
770         }
771 out:
772         return ret;
773 }
774
775 /*
776  * insert a new root into the tree.  returns the existing root entry
777  * if one is already there.  qgroupid is used
778  * as the key
779  */
780 static int insert_count(struct qgroup_count *qc)
781 {
782         struct rb_node **p = &counts.root.rb_node;
783         struct rb_node *parent = NULL;
784         struct qgroup_count *curr;
785
786         while (*p) {
787                 parent = *p;
788                 curr = rb_entry(parent, struct qgroup_count, rb_node);
789
790                 if (qc->qgroupid < curr->qgroupid)
791                         p = &(*p)->rb_left;
792                 else if (qc->qgroupid > curr->qgroupid)
793                         p = &(*p)->rb_right;
794                 else
795                         return EEXIST;
796         }
797         counts.num_groups++;
798         rb_link_node(&qc->rb_node, parent, p);
799         rb_insert_color(&qc->rb_node, &counts.root);
800         return 0;
801 }
802
803 static struct qgroup_count *find_count(u64 qgroupid)
804 {
805         struct rb_node *n = counts.root.rb_node;
806         struct qgroup_count *count;
807
808         while (n) {
809                 count = rb_entry(n, struct qgroup_count, rb_node);
810
811                 if (qgroupid < count->qgroupid)
812                         n = n->rb_left;
813                 else if (qgroupid > count->qgroupid)
814                         n = n->rb_right;
815                 else
816                         return count;
817         }
818         return NULL;
819 }
820
821 static struct qgroup_count *alloc_count(struct btrfs_disk_key *key,
822                                         struct extent_buffer *leaf,
823                                         struct btrfs_qgroup_info_item *disk)
824 {
825         struct qgroup_count *c = calloc(1, sizeof(*c));
826         struct qgroup_info *item;
827
828         if (c) {
829                 c->qgroupid = btrfs_disk_key_offset(key);
830                 c->key = *key;
831
832                 item = &c->diskinfo;
833                 item->referenced = btrfs_qgroup_info_referenced(leaf, disk);
834                 item->referenced_compressed =
835                         btrfs_qgroup_info_referenced_compressed(leaf, disk);
836                 item->exclusive = btrfs_qgroup_info_exclusive(leaf, disk);
837                 item->exclusive_compressed =
838                         btrfs_qgroup_info_exclusive_compressed(leaf, disk);
839                 INIT_LIST_HEAD(&c->groups);
840                 INIT_LIST_HEAD(&c->members);
841                 INIT_LIST_HEAD(&c->bad_list);
842
843                 if (insert_count(c)) {
844                         free(c);
845                         c = NULL;
846                 }
847         }
848         return c;
849 }
850
851 static int add_qgroup_relation(u64 memberid, u64 parentid)
852 {
853         struct qgroup_count *member;
854         struct qgroup_count *parent;
855         struct btrfs_qgroup_list *list;
856
857         if (memberid > parentid)
858                 return 0;
859
860         member = find_count(memberid);
861         parent = find_count(parentid);
862         if (!member || !parent)
863                 return -ENOENT;
864
865         list = calloc(1, sizeof(*list));
866         if (!list)
867                 return -ENOMEM;
868
869         list->group = parent;
870         list->member = member;
871         list_add_tail(&list->next_group, &member->groups);
872         list_add_tail(&list->next_member, &parent->members);
873
874         return 0;
875 }
876
877 static void read_qgroup_status(struct extent_buffer *eb, int slot,
878                               struct counts_tree *counts)
879 {
880         struct btrfs_qgroup_status_item *status_item;
881         u64 flags;
882
883         status_item = btrfs_item_ptr(eb, slot, struct btrfs_qgroup_status_item);
884         flags = btrfs_qgroup_status_flags(eb, status_item);
885         /*
886          * Since qgroup_inconsist/rescan_running is just one bit,
887          * assign value directly won't work.
888          */
889         counts->qgroup_inconsist = !!(flags &
890                         BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT);
891         counts->rescan_running = !!(flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN);
892 }
893
894 static int load_quota_info(struct btrfs_fs_info *info)
895 {
896         int ret;
897         struct btrfs_root *root = info->quota_root;
898         struct btrfs_root *tmproot;
899         struct btrfs_path path;
900         struct btrfs_key key;
901         struct btrfs_key root_key;
902         struct btrfs_disk_key disk_key;
903         struct extent_buffer *leaf;
904         struct btrfs_qgroup_info_item *item;
905         struct qgroup_count *count;
906         int i, nr;
907         int search_relations = 0;
908
909 loop:
910         /*
911          * Do 2 passes, the first allocates group counts and reads status
912          * items. The 2nd pass picks up relation items and glues them to their
913          * respective count structures.
914          */
915         btrfs_init_path(&path);
916
917         key.offset = 0;
918         key.objectid = search_relations ? 0 : BTRFS_QGROUP_RELATION_KEY;
919         key.type = 0;
920
921         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
922         if (ret < 0) {
923                 fprintf(stderr, "ERROR: Couldn't search slot: %d\n", ret);
924                 goto out;
925         }
926
927         while (1) {
928                 leaf = path.nodes[0];
929
930                 nr = btrfs_header_nritems(leaf);
931                 for(i = 0; i < nr; i++) {
932                         btrfs_item_key(leaf, &disk_key, i);
933                         btrfs_disk_key_to_cpu(&key, &disk_key);
934
935                         if (search_relations) {
936                                 if (key.type == BTRFS_QGROUP_RELATION_KEY) {
937                                         ret = add_qgroup_relation(key.objectid,
938                                                                   key.offset);
939                                         if (ret) {
940                                                 error("out of memory");
941                                                 goto out;
942                                         }
943                                 }
944                                 continue;
945                         }
946
947                         if (key.type == BTRFS_QGROUP_STATUS_KEY) {
948                                 read_qgroup_status(leaf, i, &counts);
949                                 continue;
950                         }
951
952                         /*
953                          * At this point, we can ignore anything that
954                          * isn't a qgroup info.
955                          */
956                         if (key.type != BTRFS_QGROUP_INFO_KEY)
957                                 continue;
958
959                         item = btrfs_item_ptr(leaf, i,
960                                               struct btrfs_qgroup_info_item);
961
962                         count = alloc_count(&disk_key, leaf, item);
963                         if (!count) {
964                                 ret = ENOMEM;
965                                 fprintf(stderr, "ERROR: out of memory\n");
966                                 goto out;
967                         }
968
969                         root_key.objectid = key.offset;
970                         root_key.type = BTRFS_ROOT_ITEM_KEY;
971                         root_key.offset = (u64)-1;
972                         tmproot = btrfs_read_fs_root_no_cache(info, &root_key);
973                         if (tmproot && !IS_ERR(tmproot)) {
974                                 count->subvol_exists = 1;
975                                 btrfs_free_fs_root(tmproot);
976                         }
977                 }
978
979                 ret = btrfs_next_leaf(root, &path);
980                 if (ret != 0)
981                         break;
982         }
983
984         ret = 0;
985         btrfs_release_path(&path);
986
987         if (!search_relations) {
988                 search_relations = 1;
989                 goto loop;
990         }
991
992 out:
993         return ret;
994 }
995
996 static int add_inline_refs(struct btrfs_fs_info *info,
997                            struct extent_buffer *ei_leaf, int slot,
998                            u64 bytenr, u64 num_bytes, int meta_item)
999 {
1000         struct btrfs_extent_item *ei;
1001         struct btrfs_extent_inline_ref *iref;
1002         struct btrfs_extent_data_ref *dref;
1003         u64 flags, root_obj, offset, parent;
1004         u32 item_size = btrfs_item_size_nr(ei_leaf, slot);
1005         int type;
1006         unsigned long end;
1007         unsigned long ptr;
1008
1009         ei = btrfs_item_ptr(ei_leaf, slot, struct btrfs_extent_item);
1010         flags = btrfs_extent_flags(ei_leaf, ei);
1011
1012         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !meta_item) {
1013                 struct btrfs_tree_block_info *tbinfo;
1014                 tbinfo = (struct btrfs_tree_block_info *)(ei + 1);
1015                 iref = (struct btrfs_extent_inline_ref *)(tbinfo + 1);
1016         } else {
1017                 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
1018         }
1019
1020         ptr = (unsigned long)iref;
1021         end = (unsigned long)ei + item_size;
1022         while (ptr < end) {
1023                 iref = (struct btrfs_extent_inline_ref *)ptr;
1024
1025                 parent = root_obj = 0;
1026                 offset = btrfs_extent_inline_ref_offset(ei_leaf, iref);
1027                 type = btrfs_extent_inline_ref_type(ei_leaf, iref);
1028                 switch (type) {
1029                 case BTRFS_TREE_BLOCK_REF_KEY:
1030                         root_obj = offset;
1031                         break;
1032                 case BTRFS_EXTENT_DATA_REF_KEY:
1033                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1034                         root_obj = btrfs_extent_data_ref_root(ei_leaf, dref);
1035                         break;
1036                 case BTRFS_SHARED_DATA_REF_KEY:
1037                 case BTRFS_SHARED_BLOCK_REF_KEY:
1038                         parent = offset;
1039                         break;
1040                 default:
1041                         return 1;
1042                 }
1043
1044                 if (alloc_ref(bytenr, root_obj, parent, num_bytes) == NULL)
1045                         return ENOMEM;
1046
1047                 ptr += btrfs_extent_inline_ref_size(type);
1048         }
1049
1050         return 0;
1051 }
1052
1053 static int add_keyed_ref(struct btrfs_fs_info *info,
1054                          struct btrfs_key *key,
1055                          struct extent_buffer *leaf, int slot,
1056                          u64 bytenr, u64 num_bytes)
1057 {
1058         u64 root_obj = 0, parent = 0;
1059         struct btrfs_extent_data_ref *dref;
1060
1061         switch(key->type) {
1062         case BTRFS_TREE_BLOCK_REF_KEY:
1063                 root_obj = key->offset;
1064                 break;
1065         case BTRFS_EXTENT_DATA_REF_KEY:
1066                 dref = btrfs_item_ptr(leaf, slot, struct btrfs_extent_data_ref);
1067                 root_obj = btrfs_extent_data_ref_root(leaf, dref);
1068                 break;
1069         case BTRFS_SHARED_DATA_REF_KEY:
1070         case BTRFS_SHARED_BLOCK_REF_KEY:
1071                 parent = key->offset;
1072                 break;
1073         default:
1074                 return 1;
1075         }
1076
1077         if (alloc_ref(bytenr, root_obj, parent, num_bytes) == NULL)
1078                 return ENOMEM;
1079
1080         return 0;
1081 }
1082
1083 /*
1084  * return value of 0 indicates leaf or not meta data. The code that
1085  * calls this does not need to make a distinction between the two as
1086  * it is only concerned with intermediate blocks which will always
1087  * have level > 0.
1088  */
1089 static int get_tree_block_level(struct btrfs_key *key,
1090                                 struct extent_buffer *ei_leaf,
1091                                 int slot)
1092 {
1093         int level = 0;
1094         int meta_key = key->type == BTRFS_METADATA_ITEM_KEY;
1095         u64 flags;
1096         struct btrfs_extent_item *ei;
1097
1098         ei = btrfs_item_ptr(ei_leaf, slot, struct btrfs_extent_item);
1099         flags = btrfs_extent_flags(ei_leaf, ei);
1100
1101         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !meta_key) {
1102                 struct btrfs_tree_block_info *tbinfo;
1103                 tbinfo = (struct btrfs_tree_block_info *)(ei + 1);
1104                 level = btrfs_tree_block_level(ei_leaf, tbinfo);
1105         } else if (meta_key) {
1106                 /* skinny metadata */
1107                 level = (int)key->offset;
1108         }
1109         return level;
1110 }
1111
1112 /*
1113  * Walk the extent tree, allocating a ref item for every ref and
1114  * storing it in the bytenr tree.
1115  */
1116 static int scan_extents(struct btrfs_fs_info *info,
1117                         u64 start, u64 end)
1118 {
1119         int ret, i, nr, level;
1120         struct btrfs_root *root = info->extent_root;
1121         struct btrfs_key key;
1122         struct btrfs_path path;
1123         struct btrfs_disk_key disk_key;
1124         struct extent_buffer *leaf;
1125         u64 bytenr = 0, num_bytes = 0;
1126
1127         btrfs_init_path(&path);
1128
1129         key.objectid = start;
1130         key.type = 0;
1131         key.offset = 0;
1132
1133         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1134         if (ret < 0) {
1135                 fprintf(stderr, "ERROR: Couldn't search slot: %d\n", ret);
1136                 goto out;
1137         }
1138         path.reada = 1;
1139
1140         while (1) {
1141                 leaf = path.nodes[0];
1142
1143                 nr = btrfs_header_nritems(leaf);
1144                 for(i = 0; i < nr; i++) {
1145                         btrfs_item_key(leaf, &disk_key, i);
1146                         btrfs_disk_key_to_cpu(&key, &disk_key);
1147
1148                         if (key.objectid < start)
1149                                 continue;
1150
1151                         if (key.objectid > end)
1152                                 goto done;
1153
1154                         if (key.type == BTRFS_EXTENT_ITEM_KEY ||
1155                             key.type == BTRFS_METADATA_ITEM_KEY) {
1156                                 int meta = 0;
1157
1158                                 tot_extents_scanned++;
1159
1160                                 bytenr = key.objectid;
1161                                 num_bytes = key.offset;
1162                                 if (key.type == BTRFS_METADATA_ITEM_KEY) {
1163                                         num_bytes = info->extent_root->nodesize;
1164                                         meta = 1;
1165                                 }
1166
1167                                 ret = add_inline_refs(info, leaf, i, bytenr,
1168                                                       num_bytes, meta);
1169                                 if (ret)
1170                                         goto out;
1171
1172                                 level = get_tree_block_level(&key, leaf, i);
1173                                 if (level) {
1174                                         if (alloc_tree_block(bytenr, num_bytes,
1175                                                              level))
1176                                                 return ENOMEM;
1177                                 }
1178
1179                                 continue;
1180                         }
1181
1182                         if (key.type > BTRFS_SHARED_DATA_REF_KEY)
1183                                 continue;
1184                         if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
1185                                 continue;
1186
1187                         /*
1188                          * Keyed refs should come after their extent
1189                          * item in the tree. As a result, the value of
1190                          * bytenr and num_bytes should be unchanged
1191                          * from the above block that catches the
1192                          * original extent item.
1193                          */
1194                         BUG_ON(key.objectid != bytenr);
1195
1196                         ret = add_keyed_ref(info, &key, leaf, i, bytenr,
1197                                             num_bytes);
1198                         if (ret)
1199                                 goto out;
1200                 }
1201
1202                 ret = btrfs_next_leaf(root, &path);
1203                 if (ret != 0) {
1204                         if (ret < 0) {
1205                                 fprintf(stderr,
1206                                         "ERROR: Next leaf failed: %d\n", ret);
1207                                 goto out;
1208                         }
1209                         break;
1210                 }
1211         }
1212 done:
1213         ret = 0;
1214 out:
1215         btrfs_release_path(&path);
1216
1217         return ret;
1218 }
1219
1220 static void print_fields(u64 bytes, u64 bytes_compressed, char *prefix,
1221                          char *type)
1222 {
1223         printf("%s\t\t%s %llu %s compressed %llu\n",
1224                prefix, type, (unsigned long long)bytes, type,
1225                (unsigned long long)bytes_compressed);
1226 }
1227
1228 static void print_fields_signed(long long bytes,
1229                                 long long bytes_compressed,
1230                                 char *prefix, char *type)
1231 {
1232         printf("%s\t\t%s %lld %s compressed %lld\n",
1233                prefix, type, bytes, type, bytes_compressed);
1234 }
1235
1236 static inline int qgroup_printable(struct qgroup_count *c)
1237 {
1238         return !!(c->subvol_exists || btrfs_qgroup_level(c->qgroupid));
1239 }
1240
1241 static int report_qgroup_difference(struct qgroup_count *count, int verbose)
1242 {
1243         int is_different;
1244         struct qgroup_info *info = &count->info;
1245         struct qgroup_info *disk = &count->diskinfo;
1246         long long excl_diff = info->exclusive - disk->exclusive;
1247         long long ref_diff = info->referenced - disk->referenced;
1248
1249         is_different = excl_diff || ref_diff;
1250
1251         if (verbose || (is_different && qgroup_printable(count))) {
1252                 printf("Counts for qgroup id: %llu/%llu %s\n",
1253                        btrfs_qgroup_level(count->qgroupid),
1254                        btrfs_qgroup_subvid(count->qgroupid),
1255                        is_different ? "are different" : "");
1256
1257                 print_fields(info->referenced, info->referenced_compressed,
1258                              "our:", "referenced");
1259                 print_fields(disk->referenced, disk->referenced_compressed,
1260                              "disk:", "referenced");
1261                 if (ref_diff)
1262                         print_fields_signed(ref_diff, ref_diff,
1263                                             "diff:", "referenced");
1264                 print_fields(info->exclusive, info->exclusive_compressed,
1265                              "our:", "exclusive");
1266                 print_fields(disk->exclusive, disk->exclusive_compressed,
1267                              "disk:", "exclusive");
1268                 if (excl_diff)
1269                         print_fields_signed(excl_diff, excl_diff,
1270                                             "diff:", "exclusive");
1271         }
1272
1273         return is_different;
1274 }
1275
1276 void report_qgroups(int all)
1277 {
1278         struct rb_node *node;
1279         struct qgroup_count *c;
1280
1281         if (!repair && counts.rescan_running) {
1282                 if (all) {
1283                         printf(
1284         "Qgroup rescan is running, a difference in qgroup counts is expected\n");
1285                 } else {
1286                         printf(
1287         "Qgroup rescan is running, qgroups will not be printed.\n");
1288                         return;
1289                 }
1290         }
1291         if (counts.qgroup_inconsist && !counts.rescan_running)
1292                 fprintf(stderr, "Qgroup are marked as inconsistent.\n");
1293         node = rb_first(&counts.root);
1294         while (node) {
1295                 c = rb_entry(node, struct qgroup_count, rb_node);
1296
1297                 if (report_qgroup_difference(c, all))
1298                         list_add_tail(&c->bad_list, &bad_qgroups);
1299
1300                 node = rb_next(node);
1301         }
1302 }
1303
1304 void free_qgroup_counts(void)
1305 {
1306         struct rb_node *node;
1307         struct qgroup_count *c;
1308         struct btrfs_qgroup_list *glist, *tmpglist;
1309
1310         node = rb_first(&counts.root);
1311         while (node) {
1312                 c = rb_entry(node, struct qgroup_count, rb_node);
1313
1314                 list_del(&c->bad_list);
1315
1316                 list_for_each_entry_safe(glist, tmpglist, &c->groups,
1317                                          next_group) {
1318                         list_del(&glist->next_group);
1319                         list_del(&glist->next_member);
1320                         free(glist);
1321                 }
1322                 list_for_each_entry_safe(glist, tmpglist, &c->members,
1323                                          next_group) {
1324                         list_del(&glist->next_group);
1325                         list_del(&glist->next_member);
1326                         free(glist);
1327                 }
1328
1329                 node = rb_next(node);
1330
1331                 rb_erase(&c->rb_node, &counts.root);
1332                 free(c);
1333         }
1334 }
1335
1336 int qgroup_verify_all(struct btrfs_fs_info *info)
1337 {
1338         int ret;
1339
1340         if (!info->quota_enabled)
1341                 return 0;
1342
1343         tree_blocks = ulist_alloc(0);
1344         if (!tree_blocks) {
1345                 fprintf(stderr,
1346                         "ERROR: Out of memory while allocating ulist.\n");
1347                 return ENOMEM;
1348         }
1349
1350         ret = load_quota_info(info);
1351         if (ret) {
1352                 fprintf(stderr, "ERROR: Loading qgroups from disk: %d\n", ret);
1353                 goto out;
1354         }
1355
1356         /*
1357          * Put all extent refs into our rbtree
1358          */
1359         ret = scan_extents(info, 0, ~0ULL);
1360         if (ret) {
1361                 fprintf(stderr, "ERROR: while scanning extent tree: %d\n", ret);
1362                 goto out;
1363         }
1364
1365         ret = map_implied_refs(info);
1366         if (ret) {
1367                 fprintf(stderr, "ERROR: while mapping refs: %d\n", ret);
1368                 goto out;
1369         }
1370
1371         ret = account_all_refs(1, 0);
1372
1373 out:
1374         /*
1375          * Don't free the qgroup count records as they will be walked
1376          * later via the print function.
1377          */
1378         free_tree_blocks();
1379         free_ref_tree(&by_bytenr);
1380         return ret;
1381 }
1382
1383 static void __print_subvol_info(u64 bytenr, u64 num_bytes, struct ulist *roots)
1384 {
1385         int n = roots->nnodes;
1386         struct ulist_iterator uiter;
1387         struct ulist_node *unode;
1388
1389         printf("%llu\t%llu\t%d\t", bytenr, num_bytes, n);
1390
1391         ULIST_ITER_INIT(&uiter);
1392         while ((unode = ulist_next(roots, &uiter))) {
1393                 printf("%llu ", unode->val);
1394         }
1395         printf("\n");
1396 }
1397
1398 static void print_subvol_info(u64 subvolid, u64 bytenr, u64 num_bytes,
1399                               struct ulist *roots)
1400 {
1401         struct ulist_iterator uiter;
1402         struct ulist_node *unode;
1403
1404         ULIST_ITER_INIT(&uiter);
1405         while ((unode = ulist_next(roots, &uiter))) {
1406                 BUG_ON(unode->val == 0ULL);
1407                 if (unode->val == subvolid) {
1408                         __print_subvol_info(bytenr, num_bytes, roots);
1409                         return;
1410                 }
1411         }
1412
1413
1414 }
1415
1416 int print_extent_state(struct btrfs_fs_info *info, u64 subvol)
1417 {
1418         int ret;
1419
1420         tree_blocks = ulist_alloc(0);
1421         if (!tree_blocks) {
1422                 fprintf(stderr,
1423                         "ERROR: Out of memory while allocating ulist.\n");
1424                 return ENOMEM;
1425         }
1426
1427         /*
1428          * Put all extent refs into our rbtree
1429          */
1430         ret = scan_extents(info, 0, ~0ULL);
1431         if (ret) {
1432                 fprintf(stderr, "ERROR: while scanning extent tree: %d\n", ret);
1433                 goto out;
1434         }
1435
1436         ret = map_implied_refs(info);
1437         if (ret) {
1438                 fprintf(stderr, "ERROR: while mapping refs: %d\n", ret);
1439                 goto out;
1440         }
1441
1442         printf("Offset\t\tLen\tRoot Refs\tRoots\n");
1443         ret = account_all_refs(0, subvol);
1444
1445 out:
1446         free_tree_blocks();
1447         free_ref_tree(&by_bytenr);
1448         return ret;
1449 }
1450
1451 static int repair_qgroup_info(struct btrfs_fs_info *info,
1452                               struct qgroup_count *count)
1453 {
1454         int ret;
1455         struct btrfs_root *root = info->quota_root;
1456         struct btrfs_trans_handle *trans;
1457         struct btrfs_path *path;
1458         struct btrfs_qgroup_info_item *info_item;
1459         struct btrfs_key key;
1460
1461         printf("Repair qgroup %llu/%llu\n", btrfs_qgroup_level(count->qgroupid),
1462                btrfs_qgroup_subvid(count->qgroupid));
1463
1464         path = btrfs_alloc_path();
1465         if (!path)
1466                 return -ENOMEM;
1467
1468         trans = btrfs_start_transaction(root, 1);
1469         if (IS_ERR(trans)) {
1470                 btrfs_free_path(path);
1471                 return PTR_ERR(trans);
1472         }
1473
1474         key.objectid = 0;
1475         key.type = BTRFS_QGROUP_INFO_KEY;
1476         key.offset = count->qgroupid;
1477         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1478         if (ret) {
1479                 error("Could not find disk item for qgroup %llu/%llu.\n",
1480                       btrfs_qgroup_level(count->qgroupid),
1481                       btrfs_qgroup_subvid(count->qgroupid));
1482                 if (ret > 0)
1483                         ret = -ENOENT;
1484                 goto out;
1485         }
1486
1487         info_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1488                                    struct btrfs_qgroup_info_item);
1489
1490         btrfs_set_qgroup_info_generation(path->nodes[0], info_item,
1491                                          trans->transid);
1492
1493         btrfs_set_qgroup_info_referenced(path->nodes[0], info_item,
1494                                          count->info.referenced);
1495         btrfs_set_qgroup_info_referenced_compressed(path->nodes[0], info_item,
1496                                             count->info.referenced_compressed);
1497
1498         btrfs_set_qgroup_info_exclusive(path->nodes[0], info_item,
1499                                         count->info.exclusive);
1500         btrfs_set_qgroup_info_exclusive_compressed(path->nodes[0], info_item,
1501                                            count->info.exclusive_compressed);
1502
1503         btrfs_mark_buffer_dirty(path->nodes[0]);
1504
1505 out:
1506         btrfs_commit_transaction(trans, root);
1507         btrfs_free_path(path);
1508
1509         return ret;
1510 }
1511
1512 static int repair_qgroup_status(struct btrfs_fs_info *info)
1513 {
1514         int ret;
1515         struct btrfs_root *root = info->quota_root;
1516         struct btrfs_trans_handle *trans;
1517         struct btrfs_path *path;
1518         struct btrfs_key key;
1519         struct btrfs_qgroup_status_item *status_item;
1520
1521         printf("Repair qgroup status item\n");
1522
1523         path = btrfs_alloc_path();
1524         if (!path)
1525                 return -ENOMEM;
1526
1527         trans = btrfs_start_transaction(root, 1);
1528         if (IS_ERR(trans)) {
1529                 btrfs_free_path(path);
1530                 return PTR_ERR(trans);
1531         }
1532
1533         key.objectid = 0;
1534         key.type = BTRFS_QGROUP_STATUS_KEY;
1535         key.offset = 0;
1536         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1537         if (ret) {
1538                 error("Could not find qgroup status item\n");
1539                 if (ret > 0)
1540                         ret = -ENOENT;
1541                 goto out;
1542         }
1543
1544         status_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1545                                      struct btrfs_qgroup_status_item);
1546         btrfs_set_qgroup_status_flags(path->nodes[0], status_item,
1547                                       BTRFS_QGROUP_STATUS_FLAG_ON);
1548         btrfs_set_qgroup_status_rescan(path->nodes[0], status_item, 0);
1549         btrfs_set_qgroup_status_generation(path->nodes[0], status_item,
1550                                            trans->transid);
1551
1552         btrfs_mark_buffer_dirty(path->nodes[0]);
1553
1554 out:
1555         btrfs_commit_transaction(trans, root);
1556         btrfs_free_path(path);
1557
1558         return ret;
1559 }
1560
1561 int repair_qgroups(struct btrfs_fs_info *info, int *repaired)
1562 {
1563         int ret;
1564         struct qgroup_count *count, *tmpcount;
1565
1566         *repaired = 0;
1567
1568         if (!repair)
1569                 return 0;
1570
1571         list_for_each_entry_safe(count, tmpcount, &bad_qgroups, bad_list) {
1572                 ret = repair_qgroup_info(info, count);
1573                 if (ret) {
1574                         goto out;
1575                 }
1576
1577                 (*repaired)++;
1578
1579                 list_del_init(&count->bad_list);
1580         }
1581
1582         /*
1583          * Do this step last as we want the latest transaction id on
1584          * our qgroup status to avoid a (useless) warning after
1585          * mount.
1586          */
1587         if (*repaired || counts.qgroup_inconsist || counts.rescan_running) {
1588                 ret = repair_qgroup_status(info);
1589                 if (ret)
1590                         goto out;
1591
1592                 (*repaired)++;
1593         }
1594
1595 out:
1596         return ret;
1597 }