media: dvb: symbol fixup for dvb_attach()
[platform/kernel/linux-starfive.git] / fs / btrfs / qgroup.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2011 STRATO.  All rights reserved.
4  */
5
6 #include <linux/sched.h>
7 #include <linux/pagemap.h>
8 #include <linux/writeback.h>
9 #include <linux/blkdev.h>
10 #include <linux/rbtree.h>
11 #include <linux/slab.h>
12 #include <linux/workqueue.h>
13 #include <linux/btrfs.h>
14 #include <linux/sched/mm.h>
15
16 #include "ctree.h"
17 #include "transaction.h"
18 #include "disk-io.h"
19 #include "locking.h"
20 #include "ulist.h"
21 #include "backref.h"
22 #include "extent_io.h"
23 #include "qgroup.h"
24 #include "block-group.h"
25 #include "sysfs.h"
26 #include "tree-mod-log.h"
27
28 /*
29  * Helpers to access qgroup reservation
30  *
31  * Callers should ensure the lock context and type are valid
32  */
33
34 static u64 qgroup_rsv_total(const struct btrfs_qgroup *qgroup)
35 {
36         u64 ret = 0;
37         int i;
38
39         for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
40                 ret += qgroup->rsv.values[i];
41
42         return ret;
43 }
44
45 #ifdef CONFIG_BTRFS_DEBUG
46 static const char *qgroup_rsv_type_str(enum btrfs_qgroup_rsv_type type)
47 {
48         if (type == BTRFS_QGROUP_RSV_DATA)
49                 return "data";
50         if (type == BTRFS_QGROUP_RSV_META_PERTRANS)
51                 return "meta_pertrans";
52         if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
53                 return "meta_prealloc";
54         return NULL;
55 }
56 #endif
57
58 static void qgroup_rsv_add(struct btrfs_fs_info *fs_info,
59                            struct btrfs_qgroup *qgroup, u64 num_bytes,
60                            enum btrfs_qgroup_rsv_type type)
61 {
62         trace_qgroup_update_reserve(fs_info, qgroup, num_bytes, type);
63         qgroup->rsv.values[type] += num_bytes;
64 }
65
66 static void qgroup_rsv_release(struct btrfs_fs_info *fs_info,
67                                struct btrfs_qgroup *qgroup, u64 num_bytes,
68                                enum btrfs_qgroup_rsv_type type)
69 {
70         trace_qgroup_update_reserve(fs_info, qgroup, -(s64)num_bytes, type);
71         if (qgroup->rsv.values[type] >= num_bytes) {
72                 qgroup->rsv.values[type] -= num_bytes;
73                 return;
74         }
75 #ifdef CONFIG_BTRFS_DEBUG
76         WARN_RATELIMIT(1,
77                 "qgroup %llu %s reserved space underflow, have %llu to free %llu",
78                 qgroup->qgroupid, qgroup_rsv_type_str(type),
79                 qgroup->rsv.values[type], num_bytes);
80 #endif
81         qgroup->rsv.values[type] = 0;
82 }
83
84 static void qgroup_rsv_add_by_qgroup(struct btrfs_fs_info *fs_info,
85                                      struct btrfs_qgroup *dest,
86                                      struct btrfs_qgroup *src)
87 {
88         int i;
89
90         for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
91                 qgroup_rsv_add(fs_info, dest, src->rsv.values[i], i);
92 }
93
94 static void qgroup_rsv_release_by_qgroup(struct btrfs_fs_info *fs_info,
95                                          struct btrfs_qgroup *dest,
96                                           struct btrfs_qgroup *src)
97 {
98         int i;
99
100         for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
101                 qgroup_rsv_release(fs_info, dest, src->rsv.values[i], i);
102 }
103
104 static void btrfs_qgroup_update_old_refcnt(struct btrfs_qgroup *qg, u64 seq,
105                                            int mod)
106 {
107         if (qg->old_refcnt < seq)
108                 qg->old_refcnt = seq;
109         qg->old_refcnt += mod;
110 }
111
112 static void btrfs_qgroup_update_new_refcnt(struct btrfs_qgroup *qg, u64 seq,
113                                            int mod)
114 {
115         if (qg->new_refcnt < seq)
116                 qg->new_refcnt = seq;
117         qg->new_refcnt += mod;
118 }
119
120 static inline u64 btrfs_qgroup_get_old_refcnt(struct btrfs_qgroup *qg, u64 seq)
121 {
122         if (qg->old_refcnt < seq)
123                 return 0;
124         return qg->old_refcnt - seq;
125 }
126
127 static inline u64 btrfs_qgroup_get_new_refcnt(struct btrfs_qgroup *qg, u64 seq)
128 {
129         if (qg->new_refcnt < seq)
130                 return 0;
131         return qg->new_refcnt - seq;
132 }
133
134 /*
135  * glue structure to represent the relations between qgroups.
136  */
137 struct btrfs_qgroup_list {
138         struct list_head next_group;
139         struct list_head next_member;
140         struct btrfs_qgroup *group;
141         struct btrfs_qgroup *member;
142 };
143
144 static inline u64 qgroup_to_aux(struct btrfs_qgroup *qg)
145 {
146         return (u64)(uintptr_t)qg;
147 }
148
149 static inline struct btrfs_qgroup* unode_aux_to_qgroup(struct ulist_node *n)
150 {
151         return (struct btrfs_qgroup *)(uintptr_t)n->aux;
152 }
153
154 static int
155 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
156                    int init_flags);
157 static void qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info);
158
159 /* must be called with qgroup_ioctl_lock held */
160 static struct btrfs_qgroup *find_qgroup_rb(struct btrfs_fs_info *fs_info,
161                                            u64 qgroupid)
162 {
163         struct rb_node *n = fs_info->qgroup_tree.rb_node;
164         struct btrfs_qgroup *qgroup;
165
166         while (n) {
167                 qgroup = rb_entry(n, struct btrfs_qgroup, node);
168                 if (qgroup->qgroupid < qgroupid)
169                         n = n->rb_left;
170                 else if (qgroup->qgroupid > qgroupid)
171                         n = n->rb_right;
172                 else
173                         return qgroup;
174         }
175         return NULL;
176 }
177
178 /* must be called with qgroup_lock held */
179 static struct btrfs_qgroup *add_qgroup_rb(struct btrfs_fs_info *fs_info,
180                                           u64 qgroupid)
181 {
182         struct rb_node **p = &fs_info->qgroup_tree.rb_node;
183         struct rb_node *parent = NULL;
184         struct btrfs_qgroup *qgroup;
185
186         while (*p) {
187                 parent = *p;
188                 qgroup = rb_entry(parent, struct btrfs_qgroup, node);
189
190                 if (qgroup->qgroupid < qgroupid)
191                         p = &(*p)->rb_left;
192                 else if (qgroup->qgroupid > qgroupid)
193                         p = &(*p)->rb_right;
194                 else
195                         return qgroup;
196         }
197
198         qgroup = kzalloc(sizeof(*qgroup), GFP_ATOMIC);
199         if (!qgroup)
200                 return ERR_PTR(-ENOMEM);
201
202         qgroup->qgroupid = qgroupid;
203         INIT_LIST_HEAD(&qgroup->groups);
204         INIT_LIST_HEAD(&qgroup->members);
205         INIT_LIST_HEAD(&qgroup->dirty);
206
207         rb_link_node(&qgroup->node, parent, p);
208         rb_insert_color(&qgroup->node, &fs_info->qgroup_tree);
209
210         return qgroup;
211 }
212
213 static void __del_qgroup_rb(struct btrfs_fs_info *fs_info,
214                             struct btrfs_qgroup *qgroup)
215 {
216         struct btrfs_qgroup_list *list;
217
218         list_del(&qgroup->dirty);
219         while (!list_empty(&qgroup->groups)) {
220                 list = list_first_entry(&qgroup->groups,
221                                         struct btrfs_qgroup_list, next_group);
222                 list_del(&list->next_group);
223                 list_del(&list->next_member);
224                 kfree(list);
225         }
226
227         while (!list_empty(&qgroup->members)) {
228                 list = list_first_entry(&qgroup->members,
229                                         struct btrfs_qgroup_list, next_member);
230                 list_del(&list->next_group);
231                 list_del(&list->next_member);
232                 kfree(list);
233         }
234 }
235
236 /* must be called with qgroup_lock held */
237 static int del_qgroup_rb(struct btrfs_fs_info *fs_info, u64 qgroupid)
238 {
239         struct btrfs_qgroup *qgroup = find_qgroup_rb(fs_info, qgroupid);
240
241         if (!qgroup)
242                 return -ENOENT;
243
244         rb_erase(&qgroup->node, &fs_info->qgroup_tree);
245         __del_qgroup_rb(fs_info, qgroup);
246         return 0;
247 }
248
249 /*
250  * Add relation specified by two qgroups.
251  *
252  * Must be called with qgroup_lock held.
253  *
254  * Return: 0        on success
255  *         -ENOENT  if one of the qgroups is NULL
256  *         <0       other errors
257  */
258 static int __add_relation_rb(struct btrfs_qgroup *member, struct btrfs_qgroup *parent)
259 {
260         struct btrfs_qgroup_list *list;
261
262         if (!member || !parent)
263                 return -ENOENT;
264
265         list = kzalloc(sizeof(*list), GFP_ATOMIC);
266         if (!list)
267                 return -ENOMEM;
268
269         list->group = parent;
270         list->member = member;
271         list_add_tail(&list->next_group, &member->groups);
272         list_add_tail(&list->next_member, &parent->members);
273
274         return 0;
275 }
276
277 /*
278  * Add relation specified by two qgroup ids.
279  *
280  * Must be called with qgroup_lock held.
281  *
282  * Return: 0        on success
283  *         -ENOENT  if one of the ids does not exist
284  *         <0       other errors
285  */
286 static int add_relation_rb(struct btrfs_fs_info *fs_info, u64 memberid, u64 parentid)
287 {
288         struct btrfs_qgroup *member;
289         struct btrfs_qgroup *parent;
290
291         member = find_qgroup_rb(fs_info, memberid);
292         parent = find_qgroup_rb(fs_info, parentid);
293
294         return __add_relation_rb(member, parent);
295 }
296
297 /* Must be called with qgroup_lock held */
298 static int del_relation_rb(struct btrfs_fs_info *fs_info,
299                            u64 memberid, u64 parentid)
300 {
301         struct btrfs_qgroup *member;
302         struct btrfs_qgroup *parent;
303         struct btrfs_qgroup_list *list;
304
305         member = find_qgroup_rb(fs_info, memberid);
306         parent = find_qgroup_rb(fs_info, parentid);
307         if (!member || !parent)
308                 return -ENOENT;
309
310         list_for_each_entry(list, &member->groups, next_group) {
311                 if (list->group == parent) {
312                         list_del(&list->next_group);
313                         list_del(&list->next_member);
314                         kfree(list);
315                         return 0;
316                 }
317         }
318         return -ENOENT;
319 }
320
321 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
322 int btrfs_verify_qgroup_counts(struct btrfs_fs_info *fs_info, u64 qgroupid,
323                                u64 rfer, u64 excl)
324 {
325         struct btrfs_qgroup *qgroup;
326
327         qgroup = find_qgroup_rb(fs_info, qgroupid);
328         if (!qgroup)
329                 return -EINVAL;
330         if (qgroup->rfer != rfer || qgroup->excl != excl)
331                 return -EINVAL;
332         return 0;
333 }
334 #endif
335
336 static void qgroup_mark_inconsistent(struct btrfs_fs_info *fs_info)
337 {
338         fs_info->qgroup_flags |= (BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT |
339                                   BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN |
340                                   BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING);
341 }
342
343 /*
344  * The full config is read in one go, only called from open_ctree()
345  * It doesn't use any locking, as at this point we're still single-threaded
346  */
347 int btrfs_read_qgroup_config(struct btrfs_fs_info *fs_info)
348 {
349         struct btrfs_key key;
350         struct btrfs_key found_key;
351         struct btrfs_root *quota_root = fs_info->quota_root;
352         struct btrfs_path *path = NULL;
353         struct extent_buffer *l;
354         int slot;
355         int ret = 0;
356         u64 flags = 0;
357         u64 rescan_progress = 0;
358
359         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
360                 return 0;
361
362         fs_info->qgroup_ulist = ulist_alloc(GFP_KERNEL);
363         if (!fs_info->qgroup_ulist) {
364                 ret = -ENOMEM;
365                 goto out;
366         }
367
368         path = btrfs_alloc_path();
369         if (!path) {
370                 ret = -ENOMEM;
371                 goto out;
372         }
373
374         ret = btrfs_sysfs_add_qgroups(fs_info);
375         if (ret < 0)
376                 goto out;
377         /* default this to quota off, in case no status key is found */
378         fs_info->qgroup_flags = 0;
379
380         /*
381          * pass 1: read status, all qgroup infos and limits
382          */
383         key.objectid = 0;
384         key.type = 0;
385         key.offset = 0;
386         ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 1);
387         if (ret)
388                 goto out;
389
390         while (1) {
391                 struct btrfs_qgroup *qgroup;
392
393                 slot = path->slots[0];
394                 l = path->nodes[0];
395                 btrfs_item_key_to_cpu(l, &found_key, slot);
396
397                 if (found_key.type == BTRFS_QGROUP_STATUS_KEY) {
398                         struct btrfs_qgroup_status_item *ptr;
399
400                         ptr = btrfs_item_ptr(l, slot,
401                                              struct btrfs_qgroup_status_item);
402
403                         if (btrfs_qgroup_status_version(l, ptr) !=
404                             BTRFS_QGROUP_STATUS_VERSION) {
405                                 btrfs_err(fs_info,
406                                  "old qgroup version, quota disabled");
407                                 goto out;
408                         }
409                         if (btrfs_qgroup_status_generation(l, ptr) !=
410                             fs_info->generation) {
411                                 qgroup_mark_inconsistent(fs_info);
412                                 btrfs_err(fs_info,
413                                         "qgroup generation mismatch, marked as inconsistent");
414                         }
415                         fs_info->qgroup_flags = btrfs_qgroup_status_flags(l,
416                                                                           ptr);
417                         rescan_progress = btrfs_qgroup_status_rescan(l, ptr);
418                         goto next1;
419                 }
420
421                 if (found_key.type != BTRFS_QGROUP_INFO_KEY &&
422                     found_key.type != BTRFS_QGROUP_LIMIT_KEY)
423                         goto next1;
424
425                 qgroup = find_qgroup_rb(fs_info, found_key.offset);
426                 if ((qgroup && found_key.type == BTRFS_QGROUP_INFO_KEY) ||
427                     (!qgroup && found_key.type == BTRFS_QGROUP_LIMIT_KEY)) {
428                         btrfs_err(fs_info, "inconsistent qgroup config");
429                         qgroup_mark_inconsistent(fs_info);
430                 }
431                 if (!qgroup) {
432                         qgroup = add_qgroup_rb(fs_info, found_key.offset);
433                         if (IS_ERR(qgroup)) {
434                                 ret = PTR_ERR(qgroup);
435                                 goto out;
436                         }
437                 }
438                 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
439                 if (ret < 0)
440                         goto out;
441
442                 switch (found_key.type) {
443                 case BTRFS_QGROUP_INFO_KEY: {
444                         struct btrfs_qgroup_info_item *ptr;
445
446                         ptr = btrfs_item_ptr(l, slot,
447                                              struct btrfs_qgroup_info_item);
448                         qgroup->rfer = btrfs_qgroup_info_rfer(l, ptr);
449                         qgroup->rfer_cmpr = btrfs_qgroup_info_rfer_cmpr(l, ptr);
450                         qgroup->excl = btrfs_qgroup_info_excl(l, ptr);
451                         qgroup->excl_cmpr = btrfs_qgroup_info_excl_cmpr(l, ptr);
452                         /* generation currently unused */
453                         break;
454                 }
455                 case BTRFS_QGROUP_LIMIT_KEY: {
456                         struct btrfs_qgroup_limit_item *ptr;
457
458                         ptr = btrfs_item_ptr(l, slot,
459                                              struct btrfs_qgroup_limit_item);
460                         qgroup->lim_flags = btrfs_qgroup_limit_flags(l, ptr);
461                         qgroup->max_rfer = btrfs_qgroup_limit_max_rfer(l, ptr);
462                         qgroup->max_excl = btrfs_qgroup_limit_max_excl(l, ptr);
463                         qgroup->rsv_rfer = btrfs_qgroup_limit_rsv_rfer(l, ptr);
464                         qgroup->rsv_excl = btrfs_qgroup_limit_rsv_excl(l, ptr);
465                         break;
466                 }
467                 }
468 next1:
469                 ret = btrfs_next_item(quota_root, path);
470                 if (ret < 0)
471                         goto out;
472                 if (ret)
473                         break;
474         }
475         btrfs_release_path(path);
476
477         /*
478          * pass 2: read all qgroup relations
479          */
480         key.objectid = 0;
481         key.type = BTRFS_QGROUP_RELATION_KEY;
482         key.offset = 0;
483         ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 0);
484         if (ret)
485                 goto out;
486         while (1) {
487                 slot = path->slots[0];
488                 l = path->nodes[0];
489                 btrfs_item_key_to_cpu(l, &found_key, slot);
490
491                 if (found_key.type != BTRFS_QGROUP_RELATION_KEY)
492                         goto next2;
493
494                 if (found_key.objectid > found_key.offset) {
495                         /* parent <- member, not needed to build config */
496                         /* FIXME should we omit the key completely? */
497                         goto next2;
498                 }
499
500                 ret = add_relation_rb(fs_info, found_key.objectid,
501                                       found_key.offset);
502                 if (ret == -ENOENT) {
503                         btrfs_warn(fs_info,
504                                 "orphan qgroup relation 0x%llx->0x%llx",
505                                 found_key.objectid, found_key.offset);
506                         ret = 0;        /* ignore the error */
507                 }
508                 if (ret)
509                         goto out;
510 next2:
511                 ret = btrfs_next_item(quota_root, path);
512                 if (ret < 0)
513                         goto out;
514                 if (ret)
515                         break;
516         }
517 out:
518         btrfs_free_path(path);
519         fs_info->qgroup_flags |= flags;
520         if (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))
521                 clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
522         else if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN &&
523                  ret >= 0)
524                 ret = qgroup_rescan_init(fs_info, rescan_progress, 0);
525
526         if (ret < 0) {
527                 ulist_free(fs_info->qgroup_ulist);
528                 fs_info->qgroup_ulist = NULL;
529                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
530                 btrfs_sysfs_del_qgroups(fs_info);
531         }
532
533         return ret < 0 ? ret : 0;
534 }
535
536 /*
537  * Called in close_ctree() when quota is still enabled.  This verifies we don't
538  * leak some reserved space.
539  *
540  * Return false if no reserved space is left.
541  * Return true if some reserved space is leaked.
542  */
543 bool btrfs_check_quota_leak(struct btrfs_fs_info *fs_info)
544 {
545         struct rb_node *node;
546         bool ret = false;
547
548         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
549                 return ret;
550         /*
551          * Since we're unmounting, there is no race and no need to grab qgroup
552          * lock.  And here we don't go post-order to provide a more user
553          * friendly sorted result.
554          */
555         for (node = rb_first(&fs_info->qgroup_tree); node; node = rb_next(node)) {
556                 struct btrfs_qgroup *qgroup;
557                 int i;
558
559                 qgroup = rb_entry(node, struct btrfs_qgroup, node);
560                 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++) {
561                         if (qgroup->rsv.values[i]) {
562                                 ret = true;
563                                 btrfs_warn(fs_info,
564                 "qgroup %hu/%llu has unreleased space, type %d rsv %llu",
565                                    btrfs_qgroup_level(qgroup->qgroupid),
566                                    btrfs_qgroup_subvolid(qgroup->qgroupid),
567                                    i, qgroup->rsv.values[i]);
568                         }
569                 }
570         }
571         return ret;
572 }
573
574 /*
575  * This is called from close_ctree() or open_ctree() or btrfs_quota_disable(),
576  * first two are in single-threaded paths.And for the third one, we have set
577  * quota_root to be null with qgroup_lock held before, so it is safe to clean
578  * up the in-memory structures without qgroup_lock held.
579  */
580 void btrfs_free_qgroup_config(struct btrfs_fs_info *fs_info)
581 {
582         struct rb_node *n;
583         struct btrfs_qgroup *qgroup;
584
585         while ((n = rb_first(&fs_info->qgroup_tree))) {
586                 qgroup = rb_entry(n, struct btrfs_qgroup, node);
587                 rb_erase(n, &fs_info->qgroup_tree);
588                 __del_qgroup_rb(fs_info, qgroup);
589                 btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
590                 kfree(qgroup);
591         }
592         /*
593          * We call btrfs_free_qgroup_config() when unmounting
594          * filesystem and disabling quota, so we set qgroup_ulist
595          * to be null here to avoid double free.
596          */
597         ulist_free(fs_info->qgroup_ulist);
598         fs_info->qgroup_ulist = NULL;
599         btrfs_sysfs_del_qgroups(fs_info);
600 }
601
602 static int add_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
603                                     u64 dst)
604 {
605         int ret;
606         struct btrfs_root *quota_root = trans->fs_info->quota_root;
607         struct btrfs_path *path;
608         struct btrfs_key key;
609
610         path = btrfs_alloc_path();
611         if (!path)
612                 return -ENOMEM;
613
614         key.objectid = src;
615         key.type = BTRFS_QGROUP_RELATION_KEY;
616         key.offset = dst;
617
618         ret = btrfs_insert_empty_item(trans, quota_root, path, &key, 0);
619
620         btrfs_mark_buffer_dirty(path->nodes[0]);
621
622         btrfs_free_path(path);
623         return ret;
624 }
625
626 static int del_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
627                                     u64 dst)
628 {
629         int ret;
630         struct btrfs_root *quota_root = trans->fs_info->quota_root;
631         struct btrfs_path *path;
632         struct btrfs_key key;
633
634         path = btrfs_alloc_path();
635         if (!path)
636                 return -ENOMEM;
637
638         key.objectid = src;
639         key.type = BTRFS_QGROUP_RELATION_KEY;
640         key.offset = dst;
641
642         ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
643         if (ret < 0)
644                 goto out;
645
646         if (ret > 0) {
647                 ret = -ENOENT;
648                 goto out;
649         }
650
651         ret = btrfs_del_item(trans, quota_root, path);
652 out:
653         btrfs_free_path(path);
654         return ret;
655 }
656
657 static int add_qgroup_item(struct btrfs_trans_handle *trans,
658                            struct btrfs_root *quota_root, u64 qgroupid)
659 {
660         int ret;
661         struct btrfs_path *path;
662         struct btrfs_qgroup_info_item *qgroup_info;
663         struct btrfs_qgroup_limit_item *qgroup_limit;
664         struct extent_buffer *leaf;
665         struct btrfs_key key;
666
667         if (btrfs_is_testing(quota_root->fs_info))
668                 return 0;
669
670         path = btrfs_alloc_path();
671         if (!path)
672                 return -ENOMEM;
673
674         key.objectid = 0;
675         key.type = BTRFS_QGROUP_INFO_KEY;
676         key.offset = qgroupid;
677
678         /*
679          * Avoid a transaction abort by catching -EEXIST here. In that
680          * case, we proceed by re-initializing the existing structure
681          * on disk.
682          */
683
684         ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
685                                       sizeof(*qgroup_info));
686         if (ret && ret != -EEXIST)
687                 goto out;
688
689         leaf = path->nodes[0];
690         qgroup_info = btrfs_item_ptr(leaf, path->slots[0],
691                                  struct btrfs_qgroup_info_item);
692         btrfs_set_qgroup_info_generation(leaf, qgroup_info, trans->transid);
693         btrfs_set_qgroup_info_rfer(leaf, qgroup_info, 0);
694         btrfs_set_qgroup_info_rfer_cmpr(leaf, qgroup_info, 0);
695         btrfs_set_qgroup_info_excl(leaf, qgroup_info, 0);
696         btrfs_set_qgroup_info_excl_cmpr(leaf, qgroup_info, 0);
697
698         btrfs_mark_buffer_dirty(leaf);
699
700         btrfs_release_path(path);
701
702         key.type = BTRFS_QGROUP_LIMIT_KEY;
703         ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
704                                       sizeof(*qgroup_limit));
705         if (ret && ret != -EEXIST)
706                 goto out;
707
708         leaf = path->nodes[0];
709         qgroup_limit = btrfs_item_ptr(leaf, path->slots[0],
710                                   struct btrfs_qgroup_limit_item);
711         btrfs_set_qgroup_limit_flags(leaf, qgroup_limit, 0);
712         btrfs_set_qgroup_limit_max_rfer(leaf, qgroup_limit, 0);
713         btrfs_set_qgroup_limit_max_excl(leaf, qgroup_limit, 0);
714         btrfs_set_qgroup_limit_rsv_rfer(leaf, qgroup_limit, 0);
715         btrfs_set_qgroup_limit_rsv_excl(leaf, qgroup_limit, 0);
716
717         btrfs_mark_buffer_dirty(leaf);
718
719         ret = 0;
720 out:
721         btrfs_free_path(path);
722         return ret;
723 }
724
725 static int del_qgroup_item(struct btrfs_trans_handle *trans, u64 qgroupid)
726 {
727         int ret;
728         struct btrfs_root *quota_root = trans->fs_info->quota_root;
729         struct btrfs_path *path;
730         struct btrfs_key key;
731
732         path = btrfs_alloc_path();
733         if (!path)
734                 return -ENOMEM;
735
736         key.objectid = 0;
737         key.type = BTRFS_QGROUP_INFO_KEY;
738         key.offset = qgroupid;
739         ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
740         if (ret < 0)
741                 goto out;
742
743         if (ret > 0) {
744                 ret = -ENOENT;
745                 goto out;
746         }
747
748         ret = btrfs_del_item(trans, quota_root, path);
749         if (ret)
750                 goto out;
751
752         btrfs_release_path(path);
753
754         key.type = BTRFS_QGROUP_LIMIT_KEY;
755         ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
756         if (ret < 0)
757                 goto out;
758
759         if (ret > 0) {
760                 ret = -ENOENT;
761                 goto out;
762         }
763
764         ret = btrfs_del_item(trans, quota_root, path);
765
766 out:
767         btrfs_free_path(path);
768         return ret;
769 }
770
771 static int update_qgroup_limit_item(struct btrfs_trans_handle *trans,
772                                     struct btrfs_qgroup *qgroup)
773 {
774         struct btrfs_root *quota_root = trans->fs_info->quota_root;
775         struct btrfs_path *path;
776         struct btrfs_key key;
777         struct extent_buffer *l;
778         struct btrfs_qgroup_limit_item *qgroup_limit;
779         int ret;
780         int slot;
781
782         key.objectid = 0;
783         key.type = BTRFS_QGROUP_LIMIT_KEY;
784         key.offset = qgroup->qgroupid;
785
786         path = btrfs_alloc_path();
787         if (!path)
788                 return -ENOMEM;
789
790         ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
791         if (ret > 0)
792                 ret = -ENOENT;
793
794         if (ret)
795                 goto out;
796
797         l = path->nodes[0];
798         slot = path->slots[0];
799         qgroup_limit = btrfs_item_ptr(l, slot, struct btrfs_qgroup_limit_item);
800         btrfs_set_qgroup_limit_flags(l, qgroup_limit, qgroup->lim_flags);
801         btrfs_set_qgroup_limit_max_rfer(l, qgroup_limit, qgroup->max_rfer);
802         btrfs_set_qgroup_limit_max_excl(l, qgroup_limit, qgroup->max_excl);
803         btrfs_set_qgroup_limit_rsv_rfer(l, qgroup_limit, qgroup->rsv_rfer);
804         btrfs_set_qgroup_limit_rsv_excl(l, qgroup_limit, qgroup->rsv_excl);
805
806         btrfs_mark_buffer_dirty(l);
807
808 out:
809         btrfs_free_path(path);
810         return ret;
811 }
812
813 static int update_qgroup_info_item(struct btrfs_trans_handle *trans,
814                                    struct btrfs_qgroup *qgroup)
815 {
816         struct btrfs_fs_info *fs_info = trans->fs_info;
817         struct btrfs_root *quota_root = fs_info->quota_root;
818         struct btrfs_path *path;
819         struct btrfs_key key;
820         struct extent_buffer *l;
821         struct btrfs_qgroup_info_item *qgroup_info;
822         int ret;
823         int slot;
824
825         if (btrfs_is_testing(fs_info))
826                 return 0;
827
828         key.objectid = 0;
829         key.type = BTRFS_QGROUP_INFO_KEY;
830         key.offset = qgroup->qgroupid;
831
832         path = btrfs_alloc_path();
833         if (!path)
834                 return -ENOMEM;
835
836         ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
837         if (ret > 0)
838                 ret = -ENOENT;
839
840         if (ret)
841                 goto out;
842
843         l = path->nodes[0];
844         slot = path->slots[0];
845         qgroup_info = btrfs_item_ptr(l, slot, struct btrfs_qgroup_info_item);
846         btrfs_set_qgroup_info_generation(l, qgroup_info, trans->transid);
847         btrfs_set_qgroup_info_rfer(l, qgroup_info, qgroup->rfer);
848         btrfs_set_qgroup_info_rfer_cmpr(l, qgroup_info, qgroup->rfer_cmpr);
849         btrfs_set_qgroup_info_excl(l, qgroup_info, qgroup->excl);
850         btrfs_set_qgroup_info_excl_cmpr(l, qgroup_info, qgroup->excl_cmpr);
851
852         btrfs_mark_buffer_dirty(l);
853
854 out:
855         btrfs_free_path(path);
856         return ret;
857 }
858
859 static int update_qgroup_status_item(struct btrfs_trans_handle *trans)
860 {
861         struct btrfs_fs_info *fs_info = trans->fs_info;
862         struct btrfs_root *quota_root = fs_info->quota_root;
863         struct btrfs_path *path;
864         struct btrfs_key key;
865         struct extent_buffer *l;
866         struct btrfs_qgroup_status_item *ptr;
867         int ret;
868         int slot;
869
870         key.objectid = 0;
871         key.type = BTRFS_QGROUP_STATUS_KEY;
872         key.offset = 0;
873
874         path = btrfs_alloc_path();
875         if (!path)
876                 return -ENOMEM;
877
878         ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
879         if (ret > 0)
880                 ret = -ENOENT;
881
882         if (ret)
883                 goto out;
884
885         l = path->nodes[0];
886         slot = path->slots[0];
887         ptr = btrfs_item_ptr(l, slot, struct btrfs_qgroup_status_item);
888         btrfs_set_qgroup_status_flags(l, ptr, fs_info->qgroup_flags &
889                                       BTRFS_QGROUP_STATUS_FLAGS_MASK);
890         btrfs_set_qgroup_status_generation(l, ptr, trans->transid);
891         btrfs_set_qgroup_status_rescan(l, ptr,
892                                 fs_info->qgroup_rescan_progress.objectid);
893
894         btrfs_mark_buffer_dirty(l);
895
896 out:
897         btrfs_free_path(path);
898         return ret;
899 }
900
901 /*
902  * called with qgroup_lock held
903  */
904 static int btrfs_clean_quota_tree(struct btrfs_trans_handle *trans,
905                                   struct btrfs_root *root)
906 {
907         struct btrfs_path *path;
908         struct btrfs_key key;
909         struct extent_buffer *leaf = NULL;
910         int ret;
911         int nr = 0;
912
913         path = btrfs_alloc_path();
914         if (!path)
915                 return -ENOMEM;
916
917         key.objectid = 0;
918         key.offset = 0;
919         key.type = 0;
920
921         while (1) {
922                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
923                 if (ret < 0)
924                         goto out;
925                 leaf = path->nodes[0];
926                 nr = btrfs_header_nritems(leaf);
927                 if (!nr)
928                         break;
929                 /*
930                  * delete the leaf one by one
931                  * since the whole tree is going
932                  * to be deleted.
933                  */
934                 path->slots[0] = 0;
935                 ret = btrfs_del_items(trans, root, path, 0, nr);
936                 if (ret)
937                         goto out;
938
939                 btrfs_release_path(path);
940         }
941         ret = 0;
942 out:
943         btrfs_free_path(path);
944         return ret;
945 }
946
947 int btrfs_quota_enable(struct btrfs_fs_info *fs_info)
948 {
949         struct btrfs_root *quota_root;
950         struct btrfs_root *tree_root = fs_info->tree_root;
951         struct btrfs_path *path = NULL;
952         struct btrfs_qgroup_status_item *ptr;
953         struct extent_buffer *leaf;
954         struct btrfs_key key;
955         struct btrfs_key found_key;
956         struct btrfs_qgroup *qgroup = NULL;
957         struct btrfs_trans_handle *trans = NULL;
958         struct ulist *ulist = NULL;
959         int ret = 0;
960         int slot;
961
962         /*
963          * We need to have subvol_sem write locked, to prevent races between
964          * concurrent tasks trying to enable quotas, because we will unlock
965          * and relock qgroup_ioctl_lock before setting fs_info->quota_root
966          * and before setting BTRFS_FS_QUOTA_ENABLED.
967          */
968         lockdep_assert_held_write(&fs_info->subvol_sem);
969
970         if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
971                 btrfs_err(fs_info,
972                           "qgroups are currently unsupported in extent tree v2");
973                 return -EINVAL;
974         }
975
976         mutex_lock(&fs_info->qgroup_ioctl_lock);
977         if (fs_info->quota_root)
978                 goto out;
979
980         ulist = ulist_alloc(GFP_KERNEL);
981         if (!ulist) {
982                 ret = -ENOMEM;
983                 goto out;
984         }
985
986         ret = btrfs_sysfs_add_qgroups(fs_info);
987         if (ret < 0)
988                 goto out;
989
990         /*
991          * Unlock qgroup_ioctl_lock before starting the transaction. This is to
992          * avoid lock acquisition inversion problems (reported by lockdep) between
993          * qgroup_ioctl_lock and the vfs freeze semaphores, acquired when we
994          * start a transaction.
995          * After we started the transaction lock qgroup_ioctl_lock again and
996          * check if someone else created the quota root in the meanwhile. If so,
997          * just return success and release the transaction handle.
998          *
999          * Also we don't need to worry about someone else calling
1000          * btrfs_sysfs_add_qgroups() after we unlock and getting an error because
1001          * that function returns 0 (success) when the sysfs entries already exist.
1002          */
1003         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1004
1005         /*
1006          * 1 for quota root item
1007          * 1 for BTRFS_QGROUP_STATUS item
1008          *
1009          * Yet we also need 2*n items for a QGROUP_INFO/QGROUP_LIMIT items
1010          * per subvolume. However those are not currently reserved since it
1011          * would be a lot of overkill.
1012          */
1013         trans = btrfs_start_transaction(tree_root, 2);
1014
1015         mutex_lock(&fs_info->qgroup_ioctl_lock);
1016         if (IS_ERR(trans)) {
1017                 ret = PTR_ERR(trans);
1018                 trans = NULL;
1019                 goto out;
1020         }
1021
1022         if (fs_info->quota_root)
1023                 goto out;
1024
1025         fs_info->qgroup_ulist = ulist;
1026         ulist = NULL;
1027
1028         /*
1029          * initially create the quota tree
1030          */
1031         quota_root = btrfs_create_tree(trans, BTRFS_QUOTA_TREE_OBJECTID);
1032         if (IS_ERR(quota_root)) {
1033                 ret =  PTR_ERR(quota_root);
1034                 btrfs_abort_transaction(trans, ret);
1035                 goto out;
1036         }
1037
1038         path = btrfs_alloc_path();
1039         if (!path) {
1040                 ret = -ENOMEM;
1041                 btrfs_abort_transaction(trans, ret);
1042                 goto out_free_root;
1043         }
1044
1045         key.objectid = 0;
1046         key.type = BTRFS_QGROUP_STATUS_KEY;
1047         key.offset = 0;
1048
1049         ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
1050                                       sizeof(*ptr));
1051         if (ret) {
1052                 btrfs_abort_transaction(trans, ret);
1053                 goto out_free_path;
1054         }
1055
1056         leaf = path->nodes[0];
1057         ptr = btrfs_item_ptr(leaf, path->slots[0],
1058                                  struct btrfs_qgroup_status_item);
1059         btrfs_set_qgroup_status_generation(leaf, ptr, trans->transid);
1060         btrfs_set_qgroup_status_version(leaf, ptr, BTRFS_QGROUP_STATUS_VERSION);
1061         fs_info->qgroup_flags = BTRFS_QGROUP_STATUS_FLAG_ON |
1062                                 BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1063         btrfs_set_qgroup_status_flags(leaf, ptr, fs_info->qgroup_flags &
1064                                       BTRFS_QGROUP_STATUS_FLAGS_MASK);
1065         btrfs_set_qgroup_status_rescan(leaf, ptr, 0);
1066
1067         btrfs_mark_buffer_dirty(leaf);
1068
1069         key.objectid = 0;
1070         key.type = BTRFS_ROOT_REF_KEY;
1071         key.offset = 0;
1072
1073         btrfs_release_path(path);
1074         ret = btrfs_search_slot_for_read(tree_root, &key, path, 1, 0);
1075         if (ret > 0)
1076                 goto out_add_root;
1077         if (ret < 0) {
1078                 btrfs_abort_transaction(trans, ret);
1079                 goto out_free_path;
1080         }
1081
1082         while (1) {
1083                 slot = path->slots[0];
1084                 leaf = path->nodes[0];
1085                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1086
1087                 if (found_key.type == BTRFS_ROOT_REF_KEY) {
1088
1089                         /* Release locks on tree_root before we access quota_root */
1090                         btrfs_release_path(path);
1091
1092                         ret = add_qgroup_item(trans, quota_root,
1093                                               found_key.offset);
1094                         if (ret) {
1095                                 btrfs_abort_transaction(trans, ret);
1096                                 goto out_free_path;
1097                         }
1098
1099                         qgroup = add_qgroup_rb(fs_info, found_key.offset);
1100                         if (IS_ERR(qgroup)) {
1101                                 ret = PTR_ERR(qgroup);
1102                                 btrfs_abort_transaction(trans, ret);
1103                                 goto out_free_path;
1104                         }
1105                         ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1106                         if (ret < 0) {
1107                                 btrfs_abort_transaction(trans, ret);
1108                                 goto out_free_path;
1109                         }
1110                         ret = btrfs_search_slot_for_read(tree_root, &found_key,
1111                                                          path, 1, 0);
1112                         if (ret < 0) {
1113                                 btrfs_abort_transaction(trans, ret);
1114                                 goto out_free_path;
1115                         }
1116                         if (ret > 0) {
1117                                 /*
1118                                  * Shouldn't happen, but in case it does we
1119                                  * don't need to do the btrfs_next_item, just
1120                                  * continue.
1121                                  */
1122                                 continue;
1123                         }
1124                 }
1125                 ret = btrfs_next_item(tree_root, path);
1126                 if (ret < 0) {
1127                         btrfs_abort_transaction(trans, ret);
1128                         goto out_free_path;
1129                 }
1130                 if (ret)
1131                         break;
1132         }
1133
1134 out_add_root:
1135         btrfs_release_path(path);
1136         ret = add_qgroup_item(trans, quota_root, BTRFS_FS_TREE_OBJECTID);
1137         if (ret) {
1138                 btrfs_abort_transaction(trans, ret);
1139                 goto out_free_path;
1140         }
1141
1142         qgroup = add_qgroup_rb(fs_info, BTRFS_FS_TREE_OBJECTID);
1143         if (IS_ERR(qgroup)) {
1144                 ret = PTR_ERR(qgroup);
1145                 btrfs_abort_transaction(trans, ret);
1146                 goto out_free_path;
1147         }
1148         ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1149         if (ret < 0) {
1150                 btrfs_abort_transaction(trans, ret);
1151                 goto out_free_path;
1152         }
1153
1154         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1155         /*
1156          * Commit the transaction while not holding qgroup_ioctl_lock, to avoid
1157          * a deadlock with tasks concurrently doing other qgroup operations, such
1158          * adding/removing qgroups or adding/deleting qgroup relations for example,
1159          * because all qgroup operations first start or join a transaction and then
1160          * lock the qgroup_ioctl_lock mutex.
1161          * We are safe from a concurrent task trying to enable quotas, by calling
1162          * this function, since we are serialized by fs_info->subvol_sem.
1163          */
1164         ret = btrfs_commit_transaction(trans);
1165         trans = NULL;
1166         mutex_lock(&fs_info->qgroup_ioctl_lock);
1167         if (ret)
1168                 goto out_free_path;
1169
1170         /*
1171          * Set quota enabled flag after committing the transaction, to avoid
1172          * deadlocks on fs_info->qgroup_ioctl_lock with concurrent snapshot
1173          * creation.
1174          */
1175         spin_lock(&fs_info->qgroup_lock);
1176         fs_info->quota_root = quota_root;
1177         set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1178         spin_unlock(&fs_info->qgroup_lock);
1179
1180         ret = qgroup_rescan_init(fs_info, 0, 1);
1181         if (!ret) {
1182                 qgroup_rescan_zero_tracking(fs_info);
1183                 fs_info->qgroup_rescan_running = true;
1184                 btrfs_queue_work(fs_info->qgroup_rescan_workers,
1185                                  &fs_info->qgroup_rescan_work);
1186         } else {
1187                 /*
1188                  * We have set both BTRFS_FS_QUOTA_ENABLED and
1189                  * BTRFS_QGROUP_STATUS_FLAG_ON, so we can only fail with
1190                  * -EINPROGRESS. That can happen because someone started the
1191                  * rescan worker by calling quota rescan ioctl before we
1192                  * attempted to initialize the rescan worker. Failure due to
1193                  * quotas disabled in the meanwhile is not possible, because
1194                  * we are holding a write lock on fs_info->subvol_sem, which
1195                  * is also acquired when disabling quotas.
1196                  * Ignore such error, and any other error would need to undo
1197                  * everything we did in the transaction we just committed.
1198                  */
1199                 ASSERT(ret == -EINPROGRESS);
1200                 ret = 0;
1201         }
1202
1203 out_free_path:
1204         btrfs_free_path(path);
1205 out_free_root:
1206         if (ret)
1207                 btrfs_put_root(quota_root);
1208 out:
1209         if (ret) {
1210                 ulist_free(fs_info->qgroup_ulist);
1211                 fs_info->qgroup_ulist = NULL;
1212                 btrfs_sysfs_del_qgroups(fs_info);
1213         }
1214         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1215         if (ret && trans)
1216                 btrfs_end_transaction(trans);
1217         else if (trans)
1218                 ret = btrfs_end_transaction(trans);
1219         ulist_free(ulist);
1220         return ret;
1221 }
1222
1223 int btrfs_quota_disable(struct btrfs_fs_info *fs_info)
1224 {
1225         struct btrfs_root *quota_root;
1226         struct btrfs_trans_handle *trans = NULL;
1227         int ret = 0;
1228
1229         /*
1230          * We need to have subvol_sem write locked to prevent races with
1231          * snapshot creation.
1232          */
1233         lockdep_assert_held_write(&fs_info->subvol_sem);
1234
1235         /*
1236          * Lock the cleaner mutex to prevent races with concurrent relocation,
1237          * because relocation may be building backrefs for blocks of the quota
1238          * root while we are deleting the root. This is like dropping fs roots
1239          * of deleted snapshots/subvolumes, we need the same protection.
1240          *
1241          * This also prevents races between concurrent tasks trying to disable
1242          * quotas, because we will unlock and relock qgroup_ioctl_lock across
1243          * BTRFS_FS_QUOTA_ENABLED changes.
1244          */
1245         mutex_lock(&fs_info->cleaner_mutex);
1246
1247         mutex_lock(&fs_info->qgroup_ioctl_lock);
1248         if (!fs_info->quota_root)
1249                 goto out;
1250
1251         /*
1252          * Unlock the qgroup_ioctl_lock mutex before waiting for the rescan worker to
1253          * complete. Otherwise we can deadlock because btrfs_remove_qgroup() needs
1254          * to lock that mutex while holding a transaction handle and the rescan
1255          * worker needs to commit a transaction.
1256          */
1257         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1258
1259         /*
1260          * Request qgroup rescan worker to complete and wait for it. This wait
1261          * must be done before transaction start for quota disable since it may
1262          * deadlock with transaction by the qgroup rescan worker.
1263          */
1264         clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1265         btrfs_qgroup_wait_for_completion(fs_info, false);
1266
1267         /*
1268          * 1 For the root item
1269          *
1270          * We should also reserve enough items for the quota tree deletion in
1271          * btrfs_clean_quota_tree but this is not done.
1272          *
1273          * Also, we must always start a transaction without holding the mutex
1274          * qgroup_ioctl_lock, see btrfs_quota_enable().
1275          */
1276         trans = btrfs_start_transaction(fs_info->tree_root, 1);
1277
1278         mutex_lock(&fs_info->qgroup_ioctl_lock);
1279         if (IS_ERR(trans)) {
1280                 ret = PTR_ERR(trans);
1281                 trans = NULL;
1282                 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1283                 goto out;
1284         }
1285
1286         if (!fs_info->quota_root)
1287                 goto out;
1288
1289         spin_lock(&fs_info->qgroup_lock);
1290         quota_root = fs_info->quota_root;
1291         fs_info->quota_root = NULL;
1292         fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
1293         fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
1294         spin_unlock(&fs_info->qgroup_lock);
1295
1296         btrfs_free_qgroup_config(fs_info);
1297
1298         ret = btrfs_clean_quota_tree(trans, quota_root);
1299         if (ret) {
1300                 btrfs_abort_transaction(trans, ret);
1301                 goto out;
1302         }
1303
1304         ret = btrfs_del_root(trans, &quota_root->root_key);
1305         if (ret) {
1306                 btrfs_abort_transaction(trans, ret);
1307                 goto out;
1308         }
1309
1310         spin_lock(&fs_info->trans_lock);
1311         list_del(&quota_root->dirty_list);
1312         spin_unlock(&fs_info->trans_lock);
1313
1314         btrfs_tree_lock(quota_root->node);
1315         btrfs_clean_tree_block(quota_root->node);
1316         btrfs_tree_unlock(quota_root->node);
1317         btrfs_free_tree_block(trans, btrfs_root_id(quota_root),
1318                               quota_root->node, 0, 1);
1319
1320         btrfs_put_root(quota_root);
1321
1322 out:
1323         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1324         if (ret && trans)
1325                 btrfs_end_transaction(trans);
1326         else if (trans)
1327                 ret = btrfs_end_transaction(trans);
1328         mutex_unlock(&fs_info->cleaner_mutex);
1329
1330         return ret;
1331 }
1332
1333 static void qgroup_dirty(struct btrfs_fs_info *fs_info,
1334                          struct btrfs_qgroup *qgroup)
1335 {
1336         if (list_empty(&qgroup->dirty))
1337                 list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1338 }
1339
1340 /*
1341  * The easy accounting, we're updating qgroup relationship whose child qgroup
1342  * only has exclusive extents.
1343  *
1344  * In this case, all exclusive extents will also be exclusive for parent, so
1345  * excl/rfer just get added/removed.
1346  *
1347  * So is qgroup reservation space, which should also be added/removed to
1348  * parent.
1349  * Or when child tries to release reservation space, parent will underflow its
1350  * reservation (for relationship adding case).
1351  *
1352  * Caller should hold fs_info->qgroup_lock.
1353  */
1354 static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
1355                                     struct ulist *tmp, u64 ref_root,
1356                                     struct btrfs_qgroup *src, int sign)
1357 {
1358         struct btrfs_qgroup *qgroup;
1359         struct btrfs_qgroup_list *glist;
1360         struct ulist_node *unode;
1361         struct ulist_iterator uiter;
1362         u64 num_bytes = src->excl;
1363         int ret = 0;
1364
1365         qgroup = find_qgroup_rb(fs_info, ref_root);
1366         if (!qgroup)
1367                 goto out;
1368
1369         qgroup->rfer += sign * num_bytes;
1370         qgroup->rfer_cmpr += sign * num_bytes;
1371
1372         WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1373         qgroup->excl += sign * num_bytes;
1374         qgroup->excl_cmpr += sign * num_bytes;
1375
1376         if (sign > 0)
1377                 qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1378         else
1379                 qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1380
1381         qgroup_dirty(fs_info, qgroup);
1382
1383         /* Get all of the parent groups that contain this qgroup */
1384         list_for_each_entry(glist, &qgroup->groups, next_group) {
1385                 ret = ulist_add(tmp, glist->group->qgroupid,
1386                                 qgroup_to_aux(glist->group), GFP_ATOMIC);
1387                 if (ret < 0)
1388                         goto out;
1389         }
1390
1391         /* Iterate all of the parents and adjust their reference counts */
1392         ULIST_ITER_INIT(&uiter);
1393         while ((unode = ulist_next(tmp, &uiter))) {
1394                 qgroup = unode_aux_to_qgroup(unode);
1395                 qgroup->rfer += sign * num_bytes;
1396                 qgroup->rfer_cmpr += sign * num_bytes;
1397                 WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1398                 qgroup->excl += sign * num_bytes;
1399                 if (sign > 0)
1400                         qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1401                 else
1402                         qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1403                 qgroup->excl_cmpr += sign * num_bytes;
1404                 qgroup_dirty(fs_info, qgroup);
1405
1406                 /* Add any parents of the parents */
1407                 list_for_each_entry(glist, &qgroup->groups, next_group) {
1408                         ret = ulist_add(tmp, glist->group->qgroupid,
1409                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
1410                         if (ret < 0)
1411                                 goto out;
1412                 }
1413         }
1414         ret = 0;
1415 out:
1416         return ret;
1417 }
1418
1419
1420 /*
1421  * Quick path for updating qgroup with only excl refs.
1422  *
1423  * In that case, just update all parent will be enough.
1424  * Or we needs to do a full rescan.
1425  * Caller should also hold fs_info->qgroup_lock.
1426  *
1427  * Return 0 for quick update, return >0 for need to full rescan
1428  * and mark INCONSISTENT flag.
1429  * Return < 0 for other error.
1430  */
1431 static int quick_update_accounting(struct btrfs_fs_info *fs_info,
1432                                    struct ulist *tmp, u64 src, u64 dst,
1433                                    int sign)
1434 {
1435         struct btrfs_qgroup *qgroup;
1436         int ret = 1;
1437         int err = 0;
1438
1439         qgroup = find_qgroup_rb(fs_info, src);
1440         if (!qgroup)
1441                 goto out;
1442         if (qgroup->excl == qgroup->rfer) {
1443                 ret = 0;
1444                 err = __qgroup_excl_accounting(fs_info, tmp, dst,
1445                                                qgroup, sign);
1446                 if (err < 0) {
1447                         ret = err;
1448                         goto out;
1449                 }
1450         }
1451 out:
1452         if (ret)
1453                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1454         return ret;
1455 }
1456
1457 int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1458                               u64 dst)
1459 {
1460         struct btrfs_fs_info *fs_info = trans->fs_info;
1461         struct btrfs_qgroup *parent;
1462         struct btrfs_qgroup *member;
1463         struct btrfs_qgroup_list *list;
1464         struct ulist *tmp;
1465         unsigned int nofs_flag;
1466         int ret = 0;
1467
1468         /* Check the level of src and dst first */
1469         if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
1470                 return -EINVAL;
1471
1472         /* We hold a transaction handle open, must do a NOFS allocation. */
1473         nofs_flag = memalloc_nofs_save();
1474         tmp = ulist_alloc(GFP_KERNEL);
1475         memalloc_nofs_restore(nofs_flag);
1476         if (!tmp)
1477                 return -ENOMEM;
1478
1479         mutex_lock(&fs_info->qgroup_ioctl_lock);
1480         if (!fs_info->quota_root) {
1481                 ret = -ENOTCONN;
1482                 goto out;
1483         }
1484         member = find_qgroup_rb(fs_info, src);
1485         parent = find_qgroup_rb(fs_info, dst);
1486         if (!member || !parent) {
1487                 ret = -EINVAL;
1488                 goto out;
1489         }
1490
1491         /* check if such qgroup relation exist firstly */
1492         list_for_each_entry(list, &member->groups, next_group) {
1493                 if (list->group == parent) {
1494                         ret = -EEXIST;
1495                         goto out;
1496                 }
1497         }
1498
1499         ret = add_qgroup_relation_item(trans, src, dst);
1500         if (ret)
1501                 goto out;
1502
1503         ret = add_qgroup_relation_item(trans, dst, src);
1504         if (ret) {
1505                 del_qgroup_relation_item(trans, src, dst);
1506                 goto out;
1507         }
1508
1509         spin_lock(&fs_info->qgroup_lock);
1510         ret = __add_relation_rb(member, parent);
1511         if (ret < 0) {
1512                 spin_unlock(&fs_info->qgroup_lock);
1513                 goto out;
1514         }
1515         ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1516         spin_unlock(&fs_info->qgroup_lock);
1517 out:
1518         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1519         ulist_free(tmp);
1520         return ret;
1521 }
1522
1523 static int __del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1524                                  u64 dst)
1525 {
1526         struct btrfs_fs_info *fs_info = trans->fs_info;
1527         struct btrfs_qgroup *parent;
1528         struct btrfs_qgroup *member;
1529         struct btrfs_qgroup_list *list;
1530         struct ulist *tmp;
1531         bool found = false;
1532         unsigned int nofs_flag;
1533         int ret = 0;
1534         int ret2;
1535
1536         /* We hold a transaction handle open, must do a NOFS allocation. */
1537         nofs_flag = memalloc_nofs_save();
1538         tmp = ulist_alloc(GFP_KERNEL);
1539         memalloc_nofs_restore(nofs_flag);
1540         if (!tmp)
1541                 return -ENOMEM;
1542
1543         if (!fs_info->quota_root) {
1544                 ret = -ENOTCONN;
1545                 goto out;
1546         }
1547
1548         member = find_qgroup_rb(fs_info, src);
1549         parent = find_qgroup_rb(fs_info, dst);
1550         /*
1551          * The parent/member pair doesn't exist, then try to delete the dead
1552          * relation items only.
1553          */
1554         if (!member || !parent)
1555                 goto delete_item;
1556
1557         /* check if such qgroup relation exist firstly */
1558         list_for_each_entry(list, &member->groups, next_group) {
1559                 if (list->group == parent) {
1560                         found = true;
1561                         break;
1562                 }
1563         }
1564
1565 delete_item:
1566         ret = del_qgroup_relation_item(trans, src, dst);
1567         if (ret < 0 && ret != -ENOENT)
1568                 goto out;
1569         ret2 = del_qgroup_relation_item(trans, dst, src);
1570         if (ret2 < 0 && ret2 != -ENOENT)
1571                 goto out;
1572
1573         /* At least one deletion succeeded, return 0 */
1574         if (!ret || !ret2)
1575                 ret = 0;
1576
1577         if (found) {
1578                 spin_lock(&fs_info->qgroup_lock);
1579                 del_relation_rb(fs_info, src, dst);
1580                 ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1581                 spin_unlock(&fs_info->qgroup_lock);
1582         }
1583 out:
1584         ulist_free(tmp);
1585         return ret;
1586 }
1587
1588 int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1589                               u64 dst)
1590 {
1591         struct btrfs_fs_info *fs_info = trans->fs_info;
1592         int ret = 0;
1593
1594         mutex_lock(&fs_info->qgroup_ioctl_lock);
1595         ret = __del_qgroup_relation(trans, src, dst);
1596         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1597
1598         return ret;
1599 }
1600
1601 int btrfs_create_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1602 {
1603         struct btrfs_fs_info *fs_info = trans->fs_info;
1604         struct btrfs_root *quota_root;
1605         struct btrfs_qgroup *qgroup;
1606         int ret = 0;
1607
1608         mutex_lock(&fs_info->qgroup_ioctl_lock);
1609         if (!fs_info->quota_root) {
1610                 ret = -ENOTCONN;
1611                 goto out;
1612         }
1613         quota_root = fs_info->quota_root;
1614         qgroup = find_qgroup_rb(fs_info, qgroupid);
1615         if (qgroup) {
1616                 ret = -EEXIST;
1617                 goto out;
1618         }
1619
1620         ret = add_qgroup_item(trans, quota_root, qgroupid);
1621         if (ret)
1622                 goto out;
1623
1624         spin_lock(&fs_info->qgroup_lock);
1625         qgroup = add_qgroup_rb(fs_info, qgroupid);
1626         spin_unlock(&fs_info->qgroup_lock);
1627
1628         if (IS_ERR(qgroup)) {
1629                 ret = PTR_ERR(qgroup);
1630                 goto out;
1631         }
1632         ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1633 out:
1634         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1635         return ret;
1636 }
1637
1638 int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1639 {
1640         struct btrfs_fs_info *fs_info = trans->fs_info;
1641         struct btrfs_qgroup *qgroup;
1642         struct btrfs_qgroup_list *list;
1643         int ret = 0;
1644
1645         mutex_lock(&fs_info->qgroup_ioctl_lock);
1646         if (!fs_info->quota_root) {
1647                 ret = -ENOTCONN;
1648                 goto out;
1649         }
1650
1651         qgroup = find_qgroup_rb(fs_info, qgroupid);
1652         if (!qgroup) {
1653                 ret = -ENOENT;
1654                 goto out;
1655         }
1656
1657         /* Check if there are no children of this qgroup */
1658         if (!list_empty(&qgroup->members)) {
1659                 ret = -EBUSY;
1660                 goto out;
1661         }
1662
1663         ret = del_qgroup_item(trans, qgroupid);
1664         if (ret && ret != -ENOENT)
1665                 goto out;
1666
1667         while (!list_empty(&qgroup->groups)) {
1668                 list = list_first_entry(&qgroup->groups,
1669                                         struct btrfs_qgroup_list, next_group);
1670                 ret = __del_qgroup_relation(trans, qgroupid,
1671                                             list->group->qgroupid);
1672                 if (ret)
1673                         goto out;
1674         }
1675
1676         spin_lock(&fs_info->qgroup_lock);
1677         del_qgroup_rb(fs_info, qgroupid);
1678         spin_unlock(&fs_info->qgroup_lock);
1679
1680         /*
1681          * Remove the qgroup from sysfs now without holding the qgroup_lock
1682          * spinlock, since the sysfs_remove_group() function needs to take
1683          * the mutex kernfs_mutex through kernfs_remove_by_name_ns().
1684          */
1685         btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
1686         kfree(qgroup);
1687 out:
1688         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1689         return ret;
1690 }
1691
1692 int btrfs_limit_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid,
1693                        struct btrfs_qgroup_limit *limit)
1694 {
1695         struct btrfs_fs_info *fs_info = trans->fs_info;
1696         struct btrfs_qgroup *qgroup;
1697         int ret = 0;
1698         /* Sometimes we would want to clear the limit on this qgroup.
1699          * To meet this requirement, we treat the -1 as a special value
1700          * which tell kernel to clear the limit on this qgroup.
1701          */
1702         const u64 CLEAR_VALUE = -1;
1703
1704         mutex_lock(&fs_info->qgroup_ioctl_lock);
1705         if (!fs_info->quota_root) {
1706                 ret = -ENOTCONN;
1707                 goto out;
1708         }
1709
1710         qgroup = find_qgroup_rb(fs_info, qgroupid);
1711         if (!qgroup) {
1712                 ret = -ENOENT;
1713                 goto out;
1714         }
1715
1716         spin_lock(&fs_info->qgroup_lock);
1717         if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
1718                 if (limit->max_rfer == CLEAR_VALUE) {
1719                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1720                         limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1721                         qgroup->max_rfer = 0;
1722                 } else {
1723                         qgroup->max_rfer = limit->max_rfer;
1724                 }
1725         }
1726         if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
1727                 if (limit->max_excl == CLEAR_VALUE) {
1728                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1729                         limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1730                         qgroup->max_excl = 0;
1731                 } else {
1732                         qgroup->max_excl = limit->max_excl;
1733                 }
1734         }
1735         if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
1736                 if (limit->rsv_rfer == CLEAR_VALUE) {
1737                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1738                         limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1739                         qgroup->rsv_rfer = 0;
1740                 } else {
1741                         qgroup->rsv_rfer = limit->rsv_rfer;
1742                 }
1743         }
1744         if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
1745                 if (limit->rsv_excl == CLEAR_VALUE) {
1746                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1747                         limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1748                         qgroup->rsv_excl = 0;
1749                 } else {
1750                         qgroup->rsv_excl = limit->rsv_excl;
1751                 }
1752         }
1753         qgroup->lim_flags |= limit->flags;
1754
1755         spin_unlock(&fs_info->qgroup_lock);
1756
1757         ret = update_qgroup_limit_item(trans, qgroup);
1758         if (ret) {
1759                 qgroup_mark_inconsistent(fs_info);
1760                 btrfs_info(fs_info, "unable to update quota limit for %llu",
1761                        qgroupid);
1762         }
1763
1764 out:
1765         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1766         return ret;
1767 }
1768
1769 int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1770                                 struct btrfs_delayed_ref_root *delayed_refs,
1771                                 struct btrfs_qgroup_extent_record *record)
1772 {
1773         struct rb_node **p = &delayed_refs->dirty_extent_root.rb_node;
1774         struct rb_node *parent_node = NULL;
1775         struct btrfs_qgroup_extent_record *entry;
1776         u64 bytenr = record->bytenr;
1777
1778         lockdep_assert_held(&delayed_refs->lock);
1779         trace_btrfs_qgroup_trace_extent(fs_info, record);
1780
1781         while (*p) {
1782                 parent_node = *p;
1783                 entry = rb_entry(parent_node, struct btrfs_qgroup_extent_record,
1784                                  node);
1785                 if (bytenr < entry->bytenr) {
1786                         p = &(*p)->rb_left;
1787                 } else if (bytenr > entry->bytenr) {
1788                         p = &(*p)->rb_right;
1789                 } else {
1790                         if (record->data_rsv && !entry->data_rsv) {
1791                                 entry->data_rsv = record->data_rsv;
1792                                 entry->data_rsv_refroot =
1793                                         record->data_rsv_refroot;
1794                         }
1795                         return 1;
1796                 }
1797         }
1798
1799         rb_link_node(&record->node, parent_node, p);
1800         rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1801         return 0;
1802 }
1803
1804 int btrfs_qgroup_trace_extent_post(struct btrfs_trans_handle *trans,
1805                                    struct btrfs_qgroup_extent_record *qrecord)
1806 {
1807         struct ulist *old_root;
1808         u64 bytenr = qrecord->bytenr;
1809         int ret;
1810
1811         /*
1812          * We are always called in a context where we are already holding a
1813          * transaction handle. Often we are called when adding a data delayed
1814          * reference from btrfs_truncate_inode_items() (truncating or unlinking),
1815          * in which case we will be holding a write lock on extent buffer from a
1816          * subvolume tree. In this case we can't allow btrfs_find_all_roots() to
1817          * acquire fs_info->commit_root_sem, because that is a higher level lock
1818          * that must be acquired before locking any extent buffers.
1819          *
1820          * So we want btrfs_find_all_roots() to not acquire the commit_root_sem
1821          * but we can't pass it a non-NULL transaction handle, because otherwise
1822          * it would not use commit roots and would lock extent buffers, causing
1823          * a deadlock if it ends up trying to read lock the same extent buffer
1824          * that was previously write locked at btrfs_truncate_inode_items().
1825          *
1826          * So pass a NULL transaction handle to btrfs_find_all_roots() and
1827          * explicitly tell it to not acquire the commit_root_sem - if we are
1828          * holding a transaction handle we don't need its protection.
1829          */
1830         ASSERT(trans != NULL);
1831
1832         if (trans->fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING)
1833                 return 0;
1834
1835         ret = btrfs_find_all_roots(NULL, trans->fs_info, bytenr, 0, &old_root,
1836                                    true);
1837         if (ret < 0) {
1838                 qgroup_mark_inconsistent(trans->fs_info);
1839                 btrfs_warn(trans->fs_info,
1840 "error accounting new delayed refs extent (err code: %d), quota inconsistent",
1841                         ret);
1842                 return 0;
1843         }
1844
1845         /*
1846          * Here we don't need to get the lock of
1847          * trans->transaction->delayed_refs, since inserted qrecord won't
1848          * be deleted, only qrecord->node may be modified (new qrecord insert)
1849          *
1850          * So modifying qrecord->old_roots is safe here
1851          */
1852         qrecord->old_roots = old_root;
1853         return 0;
1854 }
1855
1856 int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans, u64 bytenr,
1857                               u64 num_bytes, gfp_t gfp_flag)
1858 {
1859         struct btrfs_fs_info *fs_info = trans->fs_info;
1860         struct btrfs_qgroup_extent_record *record;
1861         struct btrfs_delayed_ref_root *delayed_refs;
1862         int ret;
1863
1864         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
1865             || bytenr == 0 || num_bytes == 0)
1866                 return 0;
1867         record = kzalloc(sizeof(*record), gfp_flag);
1868         if (!record)
1869                 return -ENOMEM;
1870
1871         delayed_refs = &trans->transaction->delayed_refs;
1872         record->bytenr = bytenr;
1873         record->num_bytes = num_bytes;
1874         record->old_roots = NULL;
1875
1876         spin_lock(&delayed_refs->lock);
1877         ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1878         spin_unlock(&delayed_refs->lock);
1879         if (ret > 0) {
1880                 kfree(record);
1881                 return 0;
1882         }
1883         return btrfs_qgroup_trace_extent_post(trans, record);
1884 }
1885
1886 int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
1887                                   struct extent_buffer *eb)
1888 {
1889         struct btrfs_fs_info *fs_info = trans->fs_info;
1890         int nr = btrfs_header_nritems(eb);
1891         int i, extent_type, ret;
1892         struct btrfs_key key;
1893         struct btrfs_file_extent_item *fi;
1894         u64 bytenr, num_bytes;
1895
1896         /* We can be called directly from walk_up_proc() */
1897         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1898                 return 0;
1899
1900         for (i = 0; i < nr; i++) {
1901                 btrfs_item_key_to_cpu(eb, &key, i);
1902
1903                 if (key.type != BTRFS_EXTENT_DATA_KEY)
1904                         continue;
1905
1906                 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
1907                 /* filter out non qgroup-accountable extents  */
1908                 extent_type = btrfs_file_extent_type(eb, fi);
1909
1910                 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1911                         continue;
1912
1913                 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1914                 if (!bytenr)
1915                         continue;
1916
1917                 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1918
1919                 ret = btrfs_qgroup_trace_extent(trans, bytenr, num_bytes,
1920                                                 GFP_NOFS);
1921                 if (ret)
1922                         return ret;
1923         }
1924         cond_resched();
1925         return 0;
1926 }
1927
1928 /*
1929  * Walk up the tree from the bottom, freeing leaves and any interior
1930  * nodes which have had all slots visited. If a node (leaf or
1931  * interior) is freed, the node above it will have it's slot
1932  * incremented. The root node will never be freed.
1933  *
1934  * At the end of this function, we should have a path which has all
1935  * slots incremented to the next position for a search. If we need to
1936  * read a new node it will be NULL and the node above it will have the
1937  * correct slot selected for a later read.
1938  *
1939  * If we increment the root nodes slot counter past the number of
1940  * elements, 1 is returned to signal completion of the search.
1941  */
1942 static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1943 {
1944         int level = 0;
1945         int nr, slot;
1946         struct extent_buffer *eb;
1947
1948         if (root_level == 0)
1949                 return 1;
1950
1951         while (level <= root_level) {
1952                 eb = path->nodes[level];
1953                 nr = btrfs_header_nritems(eb);
1954                 path->slots[level]++;
1955                 slot = path->slots[level];
1956                 if (slot >= nr || level == 0) {
1957                         /*
1958                          * Don't free the root -  we will detect this
1959                          * condition after our loop and return a
1960                          * positive value for caller to stop walking the tree.
1961                          */
1962                         if (level != root_level) {
1963                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
1964                                 path->locks[level] = 0;
1965
1966                                 free_extent_buffer(eb);
1967                                 path->nodes[level] = NULL;
1968                                 path->slots[level] = 0;
1969                         }
1970                 } else {
1971                         /*
1972                          * We have a valid slot to walk back down
1973                          * from. Stop here so caller can process these
1974                          * new nodes.
1975                          */
1976                         break;
1977                 }
1978
1979                 level++;
1980         }
1981
1982         eb = path->nodes[root_level];
1983         if (path->slots[root_level] >= btrfs_header_nritems(eb))
1984                 return 1;
1985
1986         return 0;
1987 }
1988
1989 /*
1990  * Helper function to trace a subtree tree block swap.
1991  *
1992  * The swap will happen in highest tree block, but there may be a lot of
1993  * tree blocks involved.
1994  *
1995  * For example:
1996  *  OO = Old tree blocks
1997  *  NN = New tree blocks allocated during balance
1998  *
1999  *           File tree (257)                  Reloc tree for 257
2000  * L2              OO                                NN
2001  *               /    \                            /    \
2002  * L1          OO      OO (a)                    OO      NN (a)
2003  *            / \     / \                       / \     / \
2004  * L0       OO   OO OO   OO                   OO   OO NN   NN
2005  *                  (b)  (c)                          (b)  (c)
2006  *
2007  * When calling qgroup_trace_extent_swap(), we will pass:
2008  * @src_eb = OO(a)
2009  * @dst_path = [ nodes[1] = NN(a), nodes[0] = NN(c) ]
2010  * @dst_level = 0
2011  * @root_level = 1
2012  *
2013  * In that case, qgroup_trace_extent_swap() will search from OO(a) to
2014  * reach OO(c), then mark both OO(c) and NN(c) as qgroup dirty.
2015  *
2016  * The main work of qgroup_trace_extent_swap() can be split into 3 parts:
2017  *
2018  * 1) Tree search from @src_eb
2019  *    It should acts as a simplified btrfs_search_slot().
2020  *    The key for search can be extracted from @dst_path->nodes[dst_level]
2021  *    (first key).
2022  *
2023  * 2) Mark the final tree blocks in @src_path and @dst_path qgroup dirty
2024  *    NOTE: In above case, OO(a) and NN(a) won't be marked qgroup dirty.
2025  *    They should be marked during previous (@dst_level = 1) iteration.
2026  *
2027  * 3) Mark file extents in leaves dirty
2028  *    We don't have good way to pick out new file extents only.
2029  *    So we still follow the old method by scanning all file extents in
2030  *    the leave.
2031  *
2032  * This function can free us from keeping two paths, thus later we only need
2033  * to care about how to iterate all new tree blocks in reloc tree.
2034  */
2035 static int qgroup_trace_extent_swap(struct btrfs_trans_handle* trans,
2036                                     struct extent_buffer *src_eb,
2037                                     struct btrfs_path *dst_path,
2038                                     int dst_level, int root_level,
2039                                     bool trace_leaf)
2040 {
2041         struct btrfs_key key;
2042         struct btrfs_path *src_path;
2043         struct btrfs_fs_info *fs_info = trans->fs_info;
2044         u32 nodesize = fs_info->nodesize;
2045         int cur_level = root_level;
2046         int ret;
2047
2048         BUG_ON(dst_level > root_level);
2049         /* Level mismatch */
2050         if (btrfs_header_level(src_eb) != root_level)
2051                 return -EINVAL;
2052
2053         src_path = btrfs_alloc_path();
2054         if (!src_path) {
2055                 ret = -ENOMEM;
2056                 goto out;
2057         }
2058
2059         if (dst_level)
2060                 btrfs_node_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2061         else
2062                 btrfs_item_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2063
2064         /* For src_path */
2065         atomic_inc(&src_eb->refs);
2066         src_path->nodes[root_level] = src_eb;
2067         src_path->slots[root_level] = dst_path->slots[root_level];
2068         src_path->locks[root_level] = 0;
2069
2070         /* A simplified version of btrfs_search_slot() */
2071         while (cur_level >= dst_level) {
2072                 struct btrfs_key src_key;
2073                 struct btrfs_key dst_key;
2074
2075                 if (src_path->nodes[cur_level] == NULL) {
2076                         struct extent_buffer *eb;
2077                         int parent_slot;
2078
2079                         eb = src_path->nodes[cur_level + 1];
2080                         parent_slot = src_path->slots[cur_level + 1];
2081
2082                         eb = btrfs_read_node_slot(eb, parent_slot);
2083                         if (IS_ERR(eb)) {
2084                                 ret = PTR_ERR(eb);
2085                                 goto out;
2086                         }
2087
2088                         src_path->nodes[cur_level] = eb;
2089
2090                         btrfs_tree_read_lock(eb);
2091                         src_path->locks[cur_level] = BTRFS_READ_LOCK;
2092                 }
2093
2094                 src_path->slots[cur_level] = dst_path->slots[cur_level];
2095                 if (cur_level) {
2096                         btrfs_node_key_to_cpu(dst_path->nodes[cur_level],
2097                                         &dst_key, dst_path->slots[cur_level]);
2098                         btrfs_node_key_to_cpu(src_path->nodes[cur_level],
2099                                         &src_key, src_path->slots[cur_level]);
2100                 } else {
2101                         btrfs_item_key_to_cpu(dst_path->nodes[cur_level],
2102                                         &dst_key, dst_path->slots[cur_level]);
2103                         btrfs_item_key_to_cpu(src_path->nodes[cur_level],
2104                                         &src_key, src_path->slots[cur_level]);
2105                 }
2106                 /* Content mismatch, something went wrong */
2107                 if (btrfs_comp_cpu_keys(&dst_key, &src_key)) {
2108                         ret = -ENOENT;
2109                         goto out;
2110                 }
2111                 cur_level--;
2112         }
2113
2114         /*
2115          * Now both @dst_path and @src_path have been populated, record the tree
2116          * blocks for qgroup accounting.
2117          */
2118         ret = btrfs_qgroup_trace_extent(trans, src_path->nodes[dst_level]->start,
2119                         nodesize, GFP_NOFS);
2120         if (ret < 0)
2121                 goto out;
2122         ret = btrfs_qgroup_trace_extent(trans,
2123                         dst_path->nodes[dst_level]->start,
2124                         nodesize, GFP_NOFS);
2125         if (ret < 0)
2126                 goto out;
2127
2128         /* Record leaf file extents */
2129         if (dst_level == 0 && trace_leaf) {
2130                 ret = btrfs_qgroup_trace_leaf_items(trans, src_path->nodes[0]);
2131                 if (ret < 0)
2132                         goto out;
2133                 ret = btrfs_qgroup_trace_leaf_items(trans, dst_path->nodes[0]);
2134         }
2135 out:
2136         btrfs_free_path(src_path);
2137         return ret;
2138 }
2139
2140 /*
2141  * Helper function to do recursive generation-aware depth-first search, to
2142  * locate all new tree blocks in a subtree of reloc tree.
2143  *
2144  * E.g. (OO = Old tree blocks, NN = New tree blocks, whose gen == last_snapshot)
2145  *         reloc tree
2146  * L2         NN (a)
2147  *          /    \
2148  * L1    OO        NN (b)
2149  *      /  \      /  \
2150  * L0  OO  OO    OO  NN
2151  *               (c) (d)
2152  * If we pass:
2153  * @dst_path = [ nodes[1] = NN(b), nodes[0] = NULL ],
2154  * @cur_level = 1
2155  * @root_level = 1
2156  *
2157  * We will iterate through tree blocks NN(b), NN(d) and info qgroup to trace
2158  * above tree blocks along with their counter parts in file tree.
2159  * While during search, old tree blocks OO(c) will be skipped as tree block swap
2160  * won't affect OO(c).
2161  */
2162 static int qgroup_trace_new_subtree_blocks(struct btrfs_trans_handle* trans,
2163                                            struct extent_buffer *src_eb,
2164                                            struct btrfs_path *dst_path,
2165                                            int cur_level, int root_level,
2166                                            u64 last_snapshot, bool trace_leaf)
2167 {
2168         struct btrfs_fs_info *fs_info = trans->fs_info;
2169         struct extent_buffer *eb;
2170         bool need_cleanup = false;
2171         int ret = 0;
2172         int i;
2173
2174         /* Level sanity check */
2175         if (cur_level < 0 || cur_level >= BTRFS_MAX_LEVEL - 1 ||
2176             root_level < 0 || root_level >= BTRFS_MAX_LEVEL - 1 ||
2177             root_level < cur_level) {
2178                 btrfs_err_rl(fs_info,
2179                         "%s: bad levels, cur_level=%d root_level=%d",
2180                         __func__, cur_level, root_level);
2181                 return -EUCLEAN;
2182         }
2183
2184         /* Read the tree block if needed */
2185         if (dst_path->nodes[cur_level] == NULL) {
2186                 int parent_slot;
2187                 u64 child_gen;
2188
2189                 /*
2190                  * dst_path->nodes[root_level] must be initialized before
2191                  * calling this function.
2192                  */
2193                 if (cur_level == root_level) {
2194                         btrfs_err_rl(fs_info,
2195         "%s: dst_path->nodes[%d] not initialized, root_level=%d cur_level=%d",
2196                                 __func__, root_level, root_level, cur_level);
2197                         return -EUCLEAN;
2198                 }
2199
2200                 /*
2201                  * We need to get child blockptr/gen from parent before we can
2202                  * read it.
2203                   */
2204                 eb = dst_path->nodes[cur_level + 1];
2205                 parent_slot = dst_path->slots[cur_level + 1];
2206                 child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2207
2208                 /* This node is old, no need to trace */
2209                 if (child_gen < last_snapshot)
2210                         goto out;
2211
2212                 eb = btrfs_read_node_slot(eb, parent_slot);
2213                 if (IS_ERR(eb)) {
2214                         ret = PTR_ERR(eb);
2215                         goto out;
2216                 }
2217
2218                 dst_path->nodes[cur_level] = eb;
2219                 dst_path->slots[cur_level] = 0;
2220
2221                 btrfs_tree_read_lock(eb);
2222                 dst_path->locks[cur_level] = BTRFS_READ_LOCK;
2223                 need_cleanup = true;
2224         }
2225
2226         /* Now record this tree block and its counter part for qgroups */
2227         ret = qgroup_trace_extent_swap(trans, src_eb, dst_path, cur_level,
2228                                        root_level, trace_leaf);
2229         if (ret < 0)
2230                 goto cleanup;
2231
2232         eb = dst_path->nodes[cur_level];
2233
2234         if (cur_level > 0) {
2235                 /* Iterate all child tree blocks */
2236                 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2237                         /* Skip old tree blocks as they won't be swapped */
2238                         if (btrfs_node_ptr_generation(eb, i) < last_snapshot)
2239                                 continue;
2240                         dst_path->slots[cur_level] = i;
2241
2242                         /* Recursive call (at most 7 times) */
2243                         ret = qgroup_trace_new_subtree_blocks(trans, src_eb,
2244                                         dst_path, cur_level - 1, root_level,
2245                                         last_snapshot, trace_leaf);
2246                         if (ret < 0)
2247                                 goto cleanup;
2248                 }
2249         }
2250
2251 cleanup:
2252         if (need_cleanup) {
2253                 /* Clean up */
2254                 btrfs_tree_unlock_rw(dst_path->nodes[cur_level],
2255                                      dst_path->locks[cur_level]);
2256                 free_extent_buffer(dst_path->nodes[cur_level]);
2257                 dst_path->nodes[cur_level] = NULL;
2258                 dst_path->slots[cur_level] = 0;
2259                 dst_path->locks[cur_level] = 0;
2260         }
2261 out:
2262         return ret;
2263 }
2264
2265 static int qgroup_trace_subtree_swap(struct btrfs_trans_handle *trans,
2266                                 struct extent_buffer *src_eb,
2267                                 struct extent_buffer *dst_eb,
2268                                 u64 last_snapshot, bool trace_leaf)
2269 {
2270         struct btrfs_fs_info *fs_info = trans->fs_info;
2271         struct btrfs_path *dst_path = NULL;
2272         int level;
2273         int ret;
2274
2275         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2276                 return 0;
2277
2278         /* Wrong parameter order */
2279         if (btrfs_header_generation(src_eb) > btrfs_header_generation(dst_eb)) {
2280                 btrfs_err_rl(fs_info,
2281                 "%s: bad parameter order, src_gen=%llu dst_gen=%llu", __func__,
2282                              btrfs_header_generation(src_eb),
2283                              btrfs_header_generation(dst_eb));
2284                 return -EUCLEAN;
2285         }
2286
2287         if (!extent_buffer_uptodate(src_eb) || !extent_buffer_uptodate(dst_eb)) {
2288                 ret = -EIO;
2289                 goto out;
2290         }
2291
2292         level = btrfs_header_level(dst_eb);
2293         dst_path = btrfs_alloc_path();
2294         if (!dst_path) {
2295                 ret = -ENOMEM;
2296                 goto out;
2297         }
2298         /* For dst_path */
2299         atomic_inc(&dst_eb->refs);
2300         dst_path->nodes[level] = dst_eb;
2301         dst_path->slots[level] = 0;
2302         dst_path->locks[level] = 0;
2303
2304         /* Do the generation aware breadth-first search */
2305         ret = qgroup_trace_new_subtree_blocks(trans, src_eb, dst_path, level,
2306                                               level, last_snapshot, trace_leaf);
2307         if (ret < 0)
2308                 goto out;
2309         ret = 0;
2310
2311 out:
2312         btrfs_free_path(dst_path);
2313         if (ret < 0)
2314                 qgroup_mark_inconsistent(fs_info);
2315         return ret;
2316 }
2317
2318 int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
2319                                struct extent_buffer *root_eb,
2320                                u64 root_gen, int root_level)
2321 {
2322         struct btrfs_fs_info *fs_info = trans->fs_info;
2323         int ret = 0;
2324         int level;
2325         u8 drop_subptree_thres;
2326         struct extent_buffer *eb = root_eb;
2327         struct btrfs_path *path = NULL;
2328
2329         BUG_ON(root_level < 0 || root_level >= BTRFS_MAX_LEVEL);
2330         BUG_ON(root_eb == NULL);
2331
2332         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2333                 return 0;
2334
2335         spin_lock(&fs_info->qgroup_lock);
2336         drop_subptree_thres = fs_info->qgroup_drop_subtree_thres;
2337         spin_unlock(&fs_info->qgroup_lock);
2338
2339         /*
2340          * This function only gets called for snapshot drop, if we hit a high
2341          * node here, it means we are going to change ownership for quite a lot
2342          * of extents, which will greatly slow down btrfs_commit_transaction().
2343          *
2344          * So here if we find a high tree here, we just skip the accounting and
2345          * mark qgroup inconsistent.
2346          */
2347         if (root_level >= drop_subptree_thres) {
2348                 qgroup_mark_inconsistent(fs_info);
2349                 return 0;
2350         }
2351
2352         if (!extent_buffer_uptodate(root_eb)) {
2353                 ret = btrfs_read_extent_buffer(root_eb, root_gen, root_level, NULL);
2354                 if (ret)
2355                         goto out;
2356         }
2357
2358         if (root_level == 0) {
2359                 ret = btrfs_qgroup_trace_leaf_items(trans, root_eb);
2360                 goto out;
2361         }
2362
2363         path = btrfs_alloc_path();
2364         if (!path)
2365                 return -ENOMEM;
2366
2367         /*
2368          * Walk down the tree.  Missing extent blocks are filled in as
2369          * we go. Metadata is accounted every time we read a new
2370          * extent block.
2371          *
2372          * When we reach a leaf, we account for file extent items in it,
2373          * walk back up the tree (adjusting slot pointers as we go)
2374          * and restart the search process.
2375          */
2376         atomic_inc(&root_eb->refs);     /* For path */
2377         path->nodes[root_level] = root_eb;
2378         path->slots[root_level] = 0;
2379         path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
2380 walk_down:
2381         level = root_level;
2382         while (level >= 0) {
2383                 if (path->nodes[level] == NULL) {
2384                         int parent_slot;
2385                         u64 child_bytenr;
2386
2387                         /*
2388                          * We need to get child blockptr from parent before we
2389                          * can read it.
2390                           */
2391                         eb = path->nodes[level + 1];
2392                         parent_slot = path->slots[level + 1];
2393                         child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2394
2395                         eb = btrfs_read_node_slot(eb, parent_slot);
2396                         if (IS_ERR(eb)) {
2397                                 ret = PTR_ERR(eb);
2398                                 goto out;
2399                         }
2400
2401                         path->nodes[level] = eb;
2402                         path->slots[level] = 0;
2403
2404                         btrfs_tree_read_lock(eb);
2405                         path->locks[level] = BTRFS_READ_LOCK;
2406
2407                         ret = btrfs_qgroup_trace_extent(trans, child_bytenr,
2408                                                         fs_info->nodesize,
2409                                                         GFP_NOFS);
2410                         if (ret)
2411                                 goto out;
2412                 }
2413
2414                 if (level == 0) {
2415                         ret = btrfs_qgroup_trace_leaf_items(trans,
2416                                                             path->nodes[level]);
2417                         if (ret)
2418                                 goto out;
2419
2420                         /* Nonzero return here means we completed our search */
2421                         ret = adjust_slots_upwards(path, root_level);
2422                         if (ret)
2423                                 break;
2424
2425                         /* Restart search with new slots */
2426                         goto walk_down;
2427                 }
2428
2429                 level--;
2430         }
2431
2432         ret = 0;
2433 out:
2434         btrfs_free_path(path);
2435
2436         return ret;
2437 }
2438
2439 #define UPDATE_NEW      0
2440 #define UPDATE_OLD      1
2441 /*
2442  * Walk all of the roots that points to the bytenr and adjust their refcnts.
2443  */
2444 static int qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
2445                                 struct ulist *roots, struct ulist *tmp,
2446                                 struct ulist *qgroups, u64 seq, int update_old)
2447 {
2448         struct ulist_node *unode;
2449         struct ulist_iterator uiter;
2450         struct ulist_node *tmp_unode;
2451         struct ulist_iterator tmp_uiter;
2452         struct btrfs_qgroup *qg;
2453         int ret = 0;
2454
2455         if (!roots)
2456                 return 0;
2457         ULIST_ITER_INIT(&uiter);
2458         while ((unode = ulist_next(roots, &uiter))) {
2459                 qg = find_qgroup_rb(fs_info, unode->val);
2460                 if (!qg)
2461                         continue;
2462
2463                 ulist_reinit(tmp);
2464                 ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
2465                                 GFP_ATOMIC);
2466                 if (ret < 0)
2467                         return ret;
2468                 ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
2469                 if (ret < 0)
2470                         return ret;
2471                 ULIST_ITER_INIT(&tmp_uiter);
2472                 while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
2473                         struct btrfs_qgroup_list *glist;
2474
2475                         qg = unode_aux_to_qgroup(tmp_unode);
2476                         if (update_old)
2477                                 btrfs_qgroup_update_old_refcnt(qg, seq, 1);
2478                         else
2479                                 btrfs_qgroup_update_new_refcnt(qg, seq, 1);
2480                         list_for_each_entry(glist, &qg->groups, next_group) {
2481                                 ret = ulist_add(qgroups, glist->group->qgroupid,
2482                                                 qgroup_to_aux(glist->group),
2483                                                 GFP_ATOMIC);
2484                                 if (ret < 0)
2485                                         return ret;
2486                                 ret = ulist_add(tmp, glist->group->qgroupid,
2487                                                 qgroup_to_aux(glist->group),
2488                                                 GFP_ATOMIC);
2489                                 if (ret < 0)
2490                                         return ret;
2491                         }
2492                 }
2493         }
2494         return 0;
2495 }
2496
2497 /*
2498  * Update qgroup rfer/excl counters.
2499  * Rfer update is easy, codes can explain themselves.
2500  *
2501  * Excl update is tricky, the update is split into 2 parts.
2502  * Part 1: Possible exclusive <-> sharing detect:
2503  *      |       A       |       !A      |
2504  *  -------------------------------------
2505  *  B   |       *       |       -       |
2506  *  -------------------------------------
2507  *  !B  |       +       |       **      |
2508  *  -------------------------------------
2509  *
2510  * Conditions:
2511  * A:   cur_old_roots < nr_old_roots    (not exclusive before)
2512  * !A:  cur_old_roots == nr_old_roots   (possible exclusive before)
2513  * B:   cur_new_roots < nr_new_roots    (not exclusive now)
2514  * !B:  cur_new_roots == nr_new_roots   (possible exclusive now)
2515  *
2516  * Results:
2517  * +: Possible sharing -> exclusive     -: Possible exclusive -> sharing
2518  * *: Definitely not changed.           **: Possible unchanged.
2519  *
2520  * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
2521  *
2522  * To make the logic clear, we first use condition A and B to split
2523  * combination into 4 results.
2524  *
2525  * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
2526  * only on variant maybe 0.
2527  *
2528  * Lastly, check result **, since there are 2 variants maybe 0, split them
2529  * again(2x2).
2530  * But this time we don't need to consider other things, the codes and logic
2531  * is easy to understand now.
2532  */
2533 static int qgroup_update_counters(struct btrfs_fs_info *fs_info,
2534                                   struct ulist *qgroups,
2535                                   u64 nr_old_roots,
2536                                   u64 nr_new_roots,
2537                                   u64 num_bytes, u64 seq)
2538 {
2539         struct ulist_node *unode;
2540         struct ulist_iterator uiter;
2541         struct btrfs_qgroup *qg;
2542         u64 cur_new_count, cur_old_count;
2543
2544         ULIST_ITER_INIT(&uiter);
2545         while ((unode = ulist_next(qgroups, &uiter))) {
2546                 bool dirty = false;
2547
2548                 qg = unode_aux_to_qgroup(unode);
2549                 cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
2550                 cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);
2551
2552                 trace_qgroup_update_counters(fs_info, qg, cur_old_count,
2553                                              cur_new_count);
2554
2555                 /* Rfer update part */
2556                 if (cur_old_count == 0 && cur_new_count > 0) {
2557                         qg->rfer += num_bytes;
2558                         qg->rfer_cmpr += num_bytes;
2559                         dirty = true;
2560                 }
2561                 if (cur_old_count > 0 && cur_new_count == 0) {
2562                         qg->rfer -= num_bytes;
2563                         qg->rfer_cmpr -= num_bytes;
2564                         dirty = true;
2565                 }
2566
2567                 /* Excl update part */
2568                 /* Exclusive/none -> shared case */
2569                 if (cur_old_count == nr_old_roots &&
2570                     cur_new_count < nr_new_roots) {
2571                         /* Exclusive -> shared */
2572                         if (cur_old_count != 0) {
2573                                 qg->excl -= num_bytes;
2574                                 qg->excl_cmpr -= num_bytes;
2575                                 dirty = true;
2576                         }
2577                 }
2578
2579                 /* Shared -> exclusive/none case */
2580                 if (cur_old_count < nr_old_roots &&
2581                     cur_new_count == nr_new_roots) {
2582                         /* Shared->exclusive */
2583                         if (cur_new_count != 0) {
2584                                 qg->excl += num_bytes;
2585                                 qg->excl_cmpr += num_bytes;
2586                                 dirty = true;
2587                         }
2588                 }
2589
2590                 /* Exclusive/none -> exclusive/none case */
2591                 if (cur_old_count == nr_old_roots &&
2592                     cur_new_count == nr_new_roots) {
2593                         if (cur_old_count == 0) {
2594                                 /* None -> exclusive/none */
2595
2596                                 if (cur_new_count != 0) {
2597                                         /* None -> exclusive */
2598                                         qg->excl += num_bytes;
2599                                         qg->excl_cmpr += num_bytes;
2600                                         dirty = true;
2601                                 }
2602                                 /* None -> none, nothing changed */
2603                         } else {
2604                                 /* Exclusive -> exclusive/none */
2605
2606                                 if (cur_new_count == 0) {
2607                                         /* Exclusive -> none */
2608                                         qg->excl -= num_bytes;
2609                                         qg->excl_cmpr -= num_bytes;
2610                                         dirty = true;
2611                                 }
2612                                 /* Exclusive -> exclusive, nothing changed */
2613                         }
2614                 }
2615
2616                 if (dirty)
2617                         qgroup_dirty(fs_info, qg);
2618         }
2619         return 0;
2620 }
2621
2622 /*
2623  * Check if the @roots potentially is a list of fs tree roots
2624  *
2625  * Return 0 for definitely not a fs/subvol tree roots ulist
2626  * Return 1 for possible fs/subvol tree roots in the list (considering an empty
2627  *          one as well)
2628  */
2629 static int maybe_fs_roots(struct ulist *roots)
2630 {
2631         struct ulist_node *unode;
2632         struct ulist_iterator uiter;
2633
2634         /* Empty one, still possible for fs roots */
2635         if (!roots || roots->nnodes == 0)
2636                 return 1;
2637
2638         ULIST_ITER_INIT(&uiter);
2639         unode = ulist_next(roots, &uiter);
2640         if (!unode)
2641                 return 1;
2642
2643         /*
2644          * If it contains fs tree roots, then it must belong to fs/subvol
2645          * trees.
2646          * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
2647          */
2648         return is_fstree(unode->val);
2649 }
2650
2651 int btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans, u64 bytenr,
2652                                 u64 num_bytes, struct ulist *old_roots,
2653                                 struct ulist *new_roots)
2654 {
2655         struct btrfs_fs_info *fs_info = trans->fs_info;
2656         struct ulist *qgroups = NULL;
2657         struct ulist *tmp = NULL;
2658         u64 seq;
2659         u64 nr_new_roots = 0;
2660         u64 nr_old_roots = 0;
2661         int ret = 0;
2662
2663         /*
2664          * If quotas get disabled meanwhile, the resources need to be freed and
2665          * we can't just exit here.
2666          */
2667         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
2668             fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING)
2669                 goto out_free;
2670
2671         if (new_roots) {
2672                 if (!maybe_fs_roots(new_roots))
2673                         goto out_free;
2674                 nr_new_roots = new_roots->nnodes;
2675         }
2676         if (old_roots) {
2677                 if (!maybe_fs_roots(old_roots))
2678                         goto out_free;
2679                 nr_old_roots = old_roots->nnodes;
2680         }
2681
2682         /* Quick exit, either not fs tree roots, or won't affect any qgroup */
2683         if (nr_old_roots == 0 && nr_new_roots == 0)
2684                 goto out_free;
2685
2686         BUG_ON(!fs_info->quota_root);
2687
2688         trace_btrfs_qgroup_account_extent(fs_info, trans->transid, bytenr,
2689                                         num_bytes, nr_old_roots, nr_new_roots);
2690
2691         qgroups = ulist_alloc(GFP_NOFS);
2692         if (!qgroups) {
2693                 ret = -ENOMEM;
2694                 goto out_free;
2695         }
2696         tmp = ulist_alloc(GFP_NOFS);
2697         if (!tmp) {
2698                 ret = -ENOMEM;
2699                 goto out_free;
2700         }
2701
2702         mutex_lock(&fs_info->qgroup_rescan_lock);
2703         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
2704                 if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
2705                         mutex_unlock(&fs_info->qgroup_rescan_lock);
2706                         ret = 0;
2707                         goto out_free;
2708                 }
2709         }
2710         mutex_unlock(&fs_info->qgroup_rescan_lock);
2711
2712         spin_lock(&fs_info->qgroup_lock);
2713         seq = fs_info->qgroup_seq;
2714
2715         /* Update old refcnts using old_roots */
2716         ret = qgroup_update_refcnt(fs_info, old_roots, tmp, qgroups, seq,
2717                                    UPDATE_OLD);
2718         if (ret < 0)
2719                 goto out;
2720
2721         /* Update new refcnts using new_roots */
2722         ret = qgroup_update_refcnt(fs_info, new_roots, tmp, qgroups, seq,
2723                                    UPDATE_NEW);
2724         if (ret < 0)
2725                 goto out;
2726
2727         qgroup_update_counters(fs_info, qgroups, nr_old_roots, nr_new_roots,
2728                                num_bytes, seq);
2729
2730         /*
2731          * Bump qgroup_seq to avoid seq overlap
2732          */
2733         fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
2734 out:
2735         spin_unlock(&fs_info->qgroup_lock);
2736 out_free:
2737         ulist_free(tmp);
2738         ulist_free(qgroups);
2739         ulist_free(old_roots);
2740         ulist_free(new_roots);
2741         return ret;
2742 }
2743
2744 int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans)
2745 {
2746         struct btrfs_fs_info *fs_info = trans->fs_info;
2747         struct btrfs_qgroup_extent_record *record;
2748         struct btrfs_delayed_ref_root *delayed_refs;
2749         struct ulist *new_roots = NULL;
2750         struct rb_node *node;
2751         u64 num_dirty_extents = 0;
2752         u64 qgroup_to_skip;
2753         int ret = 0;
2754
2755         delayed_refs = &trans->transaction->delayed_refs;
2756         qgroup_to_skip = delayed_refs->qgroup_to_skip;
2757         while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
2758                 record = rb_entry(node, struct btrfs_qgroup_extent_record,
2759                                   node);
2760
2761                 num_dirty_extents++;
2762                 trace_btrfs_qgroup_account_extents(fs_info, record);
2763
2764                 if (!ret && !(fs_info->qgroup_flags &
2765                               BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING)) {
2766                         /*
2767                          * Old roots should be searched when inserting qgroup
2768                          * extent record.
2769                          *
2770                          * But for INCONSISTENT (NO_ACCOUNTING) -> rescan case,
2771                          * we may have some record inserted during
2772                          * NO_ACCOUNTING (thus no old_roots populated), but
2773                          * later we start rescan, which clears NO_ACCOUNTING,
2774                          * leaving some inserted records without old_roots
2775                          * populated.
2776                          *
2777                          * Those cases are rare and should not cause too much
2778                          * time spent during commit_transaction().
2779                          */
2780                         if (!record->old_roots) {
2781                                 /* Search commit root to find old_roots */
2782                                 ret = btrfs_find_all_roots(NULL, fs_info,
2783                                                 record->bytenr, 0,
2784                                                 &record->old_roots, false);
2785                                 if (ret < 0)
2786                                         goto cleanup;
2787                         }
2788
2789                         /* Free the reserved data space */
2790                         btrfs_qgroup_free_refroot(fs_info,
2791                                         record->data_rsv_refroot,
2792                                         record->data_rsv,
2793                                         BTRFS_QGROUP_RSV_DATA);
2794                         /*
2795                          * Use BTRFS_SEQ_LAST as time_seq to do special search,
2796                          * which doesn't lock tree or delayed_refs and search
2797                          * current root. It's safe inside commit_transaction().
2798                          */
2799                         ret = btrfs_find_all_roots(trans, fs_info,
2800                            record->bytenr, BTRFS_SEQ_LAST, &new_roots, false);
2801                         if (ret < 0)
2802                                 goto cleanup;
2803                         if (qgroup_to_skip) {
2804                                 ulist_del(new_roots, qgroup_to_skip, 0);
2805                                 ulist_del(record->old_roots, qgroup_to_skip,
2806                                           0);
2807                         }
2808                         ret = btrfs_qgroup_account_extent(trans, record->bytenr,
2809                                                           record->num_bytes,
2810                                                           record->old_roots,
2811                                                           new_roots);
2812                         record->old_roots = NULL;
2813                         new_roots = NULL;
2814                 }
2815 cleanup:
2816                 ulist_free(record->old_roots);
2817                 ulist_free(new_roots);
2818                 new_roots = NULL;
2819                 rb_erase(node, &delayed_refs->dirty_extent_root);
2820                 kfree(record);
2821
2822         }
2823         trace_qgroup_num_dirty_extents(fs_info, trans->transid,
2824                                        num_dirty_extents);
2825         return ret;
2826 }
2827
2828 /*
2829  * Writes all changed qgroups to disk.
2830  * Called by the transaction commit path and the qgroup assign ioctl.
2831  */
2832 int btrfs_run_qgroups(struct btrfs_trans_handle *trans)
2833 {
2834         struct btrfs_fs_info *fs_info = trans->fs_info;
2835         int ret = 0;
2836
2837         /*
2838          * In case we are called from the qgroup assign ioctl, assert that we
2839          * are holding the qgroup_ioctl_lock, otherwise we can race with a quota
2840          * disable operation (ioctl) and access a freed quota root.
2841          */
2842         if (trans->transaction->state != TRANS_STATE_COMMIT_DOING)
2843                 lockdep_assert_held(&fs_info->qgroup_ioctl_lock);
2844
2845         if (!fs_info->quota_root)
2846                 return ret;
2847
2848         spin_lock(&fs_info->qgroup_lock);
2849         while (!list_empty(&fs_info->dirty_qgroups)) {
2850                 struct btrfs_qgroup *qgroup;
2851                 qgroup = list_first_entry(&fs_info->dirty_qgroups,
2852                                           struct btrfs_qgroup, dirty);
2853                 list_del_init(&qgroup->dirty);
2854                 spin_unlock(&fs_info->qgroup_lock);
2855                 ret = update_qgroup_info_item(trans, qgroup);
2856                 if (ret)
2857                         qgroup_mark_inconsistent(fs_info);
2858                 ret = update_qgroup_limit_item(trans, qgroup);
2859                 if (ret)
2860                         qgroup_mark_inconsistent(fs_info);
2861                 spin_lock(&fs_info->qgroup_lock);
2862         }
2863         if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2864                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_ON;
2865         else
2866                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
2867         spin_unlock(&fs_info->qgroup_lock);
2868
2869         ret = update_qgroup_status_item(trans);
2870         if (ret)
2871                 qgroup_mark_inconsistent(fs_info);
2872
2873         return ret;
2874 }
2875
2876 /*
2877  * Copy the accounting information between qgroups. This is necessary
2878  * when a snapshot or a subvolume is created. Throwing an error will
2879  * cause a transaction abort so we take extra care here to only error
2880  * when a readonly fs is a reasonable outcome.
2881  */
2882 int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans, u64 srcid,
2883                          u64 objectid, struct btrfs_qgroup_inherit *inherit)
2884 {
2885         int ret = 0;
2886         int i;
2887         u64 *i_qgroups;
2888         bool committing = false;
2889         struct btrfs_fs_info *fs_info = trans->fs_info;
2890         struct btrfs_root *quota_root;
2891         struct btrfs_qgroup *srcgroup;
2892         struct btrfs_qgroup *dstgroup;
2893         bool need_rescan = false;
2894         u32 level_size = 0;
2895         u64 nums;
2896
2897         /*
2898          * There are only two callers of this function.
2899          *
2900          * One in create_subvol() in the ioctl context, which needs to hold
2901          * the qgroup_ioctl_lock.
2902          *
2903          * The other one in create_pending_snapshot() where no other qgroup
2904          * code can modify the fs as they all need to either start a new trans
2905          * or hold a trans handler, thus we don't need to hold
2906          * qgroup_ioctl_lock.
2907          * This would avoid long and complex lock chain and make lockdep happy.
2908          */
2909         spin_lock(&fs_info->trans_lock);
2910         if (trans->transaction->state == TRANS_STATE_COMMIT_DOING)
2911                 committing = true;
2912         spin_unlock(&fs_info->trans_lock);
2913
2914         if (!committing)
2915                 mutex_lock(&fs_info->qgroup_ioctl_lock);
2916         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2917                 goto out;
2918
2919         quota_root = fs_info->quota_root;
2920         if (!quota_root) {
2921                 ret = -EINVAL;
2922                 goto out;
2923         }
2924
2925         if (inherit) {
2926                 i_qgroups = (u64 *)(inherit + 1);
2927                 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
2928                        2 * inherit->num_excl_copies;
2929                 for (i = 0; i < nums; ++i) {
2930                         srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
2931
2932                         /*
2933                          * Zero out invalid groups so we can ignore
2934                          * them later.
2935                          */
2936                         if (!srcgroup ||
2937                             ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
2938                                 *i_qgroups = 0ULL;
2939
2940                         ++i_qgroups;
2941                 }
2942         }
2943
2944         /*
2945          * create a tracking group for the subvol itself
2946          */
2947         ret = add_qgroup_item(trans, quota_root, objectid);
2948         if (ret)
2949                 goto out;
2950
2951         /*
2952          * add qgroup to all inherited groups
2953          */
2954         if (inherit) {
2955                 i_qgroups = (u64 *)(inherit + 1);
2956                 for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
2957                         if (*i_qgroups == 0)
2958                                 continue;
2959                         ret = add_qgroup_relation_item(trans, objectid,
2960                                                        *i_qgroups);
2961                         if (ret && ret != -EEXIST)
2962                                 goto out;
2963                         ret = add_qgroup_relation_item(trans, *i_qgroups,
2964                                                        objectid);
2965                         if (ret && ret != -EEXIST)
2966                                 goto out;
2967                 }
2968                 ret = 0;
2969         }
2970
2971
2972         spin_lock(&fs_info->qgroup_lock);
2973
2974         dstgroup = add_qgroup_rb(fs_info, objectid);
2975         if (IS_ERR(dstgroup)) {
2976                 ret = PTR_ERR(dstgroup);
2977                 goto unlock;
2978         }
2979
2980         if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
2981                 dstgroup->lim_flags = inherit->lim.flags;
2982                 dstgroup->max_rfer = inherit->lim.max_rfer;
2983                 dstgroup->max_excl = inherit->lim.max_excl;
2984                 dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
2985                 dstgroup->rsv_excl = inherit->lim.rsv_excl;
2986
2987                 qgroup_dirty(fs_info, dstgroup);
2988         }
2989
2990         if (srcid) {
2991                 srcgroup = find_qgroup_rb(fs_info, srcid);
2992                 if (!srcgroup)
2993                         goto unlock;
2994
2995                 /*
2996                  * We call inherit after we clone the root in order to make sure
2997                  * our counts don't go crazy, so at this point the only
2998                  * difference between the two roots should be the root node.
2999                  */
3000                 level_size = fs_info->nodesize;
3001                 dstgroup->rfer = srcgroup->rfer;
3002                 dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
3003                 dstgroup->excl = level_size;
3004                 dstgroup->excl_cmpr = level_size;
3005                 srcgroup->excl = level_size;
3006                 srcgroup->excl_cmpr = level_size;
3007
3008                 /* inherit the limit info */
3009                 dstgroup->lim_flags = srcgroup->lim_flags;
3010                 dstgroup->max_rfer = srcgroup->max_rfer;
3011                 dstgroup->max_excl = srcgroup->max_excl;
3012                 dstgroup->rsv_rfer = srcgroup->rsv_rfer;
3013                 dstgroup->rsv_excl = srcgroup->rsv_excl;
3014
3015                 qgroup_dirty(fs_info, dstgroup);
3016                 qgroup_dirty(fs_info, srcgroup);
3017         }
3018
3019         if (!inherit)
3020                 goto unlock;
3021
3022         i_qgroups = (u64 *)(inherit + 1);
3023         for (i = 0; i < inherit->num_qgroups; ++i) {
3024                 if (*i_qgroups) {
3025                         ret = add_relation_rb(fs_info, objectid, *i_qgroups);
3026                         if (ret)
3027                                 goto unlock;
3028                 }
3029                 ++i_qgroups;
3030
3031                 /*
3032                  * If we're doing a snapshot, and adding the snapshot to a new
3033                  * qgroup, the numbers are guaranteed to be incorrect.
3034                  */
3035                 if (srcid)
3036                         need_rescan = true;
3037         }
3038
3039         for (i = 0; i <  inherit->num_ref_copies; ++i, i_qgroups += 2) {
3040                 struct btrfs_qgroup *src;
3041                 struct btrfs_qgroup *dst;
3042
3043                 if (!i_qgroups[0] || !i_qgroups[1])
3044                         continue;
3045
3046                 src = find_qgroup_rb(fs_info, i_qgroups[0]);
3047                 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3048
3049                 if (!src || !dst) {
3050                         ret = -EINVAL;
3051                         goto unlock;
3052                 }
3053
3054                 dst->rfer = src->rfer - level_size;
3055                 dst->rfer_cmpr = src->rfer_cmpr - level_size;
3056
3057                 /* Manually tweaking numbers certainly needs a rescan */
3058                 need_rescan = true;
3059         }
3060         for (i = 0; i <  inherit->num_excl_copies; ++i, i_qgroups += 2) {
3061                 struct btrfs_qgroup *src;
3062                 struct btrfs_qgroup *dst;
3063
3064                 if (!i_qgroups[0] || !i_qgroups[1])
3065                         continue;
3066
3067                 src = find_qgroup_rb(fs_info, i_qgroups[0]);
3068                 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3069
3070                 if (!src || !dst) {
3071                         ret = -EINVAL;
3072                         goto unlock;
3073                 }
3074
3075                 dst->excl = src->excl + level_size;
3076                 dst->excl_cmpr = src->excl_cmpr + level_size;
3077                 need_rescan = true;
3078         }
3079
3080 unlock:
3081         spin_unlock(&fs_info->qgroup_lock);
3082         if (!ret)
3083                 ret = btrfs_sysfs_add_one_qgroup(fs_info, dstgroup);
3084 out:
3085         if (!committing)
3086                 mutex_unlock(&fs_info->qgroup_ioctl_lock);
3087         if (need_rescan)
3088                 qgroup_mark_inconsistent(fs_info);
3089         return ret;
3090 }
3091
3092 static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
3093 {
3094         if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
3095             qgroup_rsv_total(qg) + (s64)qg->rfer + num_bytes > qg->max_rfer)
3096                 return false;
3097
3098         if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
3099             qgroup_rsv_total(qg) + (s64)qg->excl + num_bytes > qg->max_excl)
3100                 return false;
3101
3102         return true;
3103 }
3104
3105 static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce,
3106                           enum btrfs_qgroup_rsv_type type)
3107 {
3108         struct btrfs_qgroup *qgroup;
3109         struct btrfs_fs_info *fs_info = root->fs_info;
3110         u64 ref_root = root->root_key.objectid;
3111         int ret = 0;
3112         struct ulist_node *unode;
3113         struct ulist_iterator uiter;
3114
3115         if (!is_fstree(ref_root))
3116                 return 0;
3117
3118         if (num_bytes == 0)
3119                 return 0;
3120
3121         if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
3122             capable(CAP_SYS_RESOURCE))
3123                 enforce = false;
3124
3125         spin_lock(&fs_info->qgroup_lock);
3126         if (!fs_info->quota_root)
3127                 goto out;
3128
3129         qgroup = find_qgroup_rb(fs_info, ref_root);
3130         if (!qgroup)
3131                 goto out;
3132
3133         /*
3134          * in a first step, we check all affected qgroups if any limits would
3135          * be exceeded
3136          */
3137         ulist_reinit(fs_info->qgroup_ulist);
3138         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3139                         qgroup_to_aux(qgroup), GFP_ATOMIC);
3140         if (ret < 0)
3141                 goto out;
3142         ULIST_ITER_INIT(&uiter);
3143         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3144                 struct btrfs_qgroup *qg;
3145                 struct btrfs_qgroup_list *glist;
3146
3147                 qg = unode_aux_to_qgroup(unode);
3148
3149                 if (enforce && !qgroup_check_limits(qg, num_bytes)) {
3150                         ret = -EDQUOT;
3151                         goto out;
3152                 }
3153
3154                 list_for_each_entry(glist, &qg->groups, next_group) {
3155                         ret = ulist_add(fs_info->qgroup_ulist,
3156                                         glist->group->qgroupid,
3157                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
3158                         if (ret < 0)
3159                                 goto out;
3160                 }
3161         }
3162         ret = 0;
3163         /*
3164          * no limits exceeded, now record the reservation into all qgroups
3165          */
3166         ULIST_ITER_INIT(&uiter);
3167         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3168                 struct btrfs_qgroup *qg;
3169
3170                 qg = unode_aux_to_qgroup(unode);
3171
3172                 qgroup_rsv_add(fs_info, qg, num_bytes, type);
3173         }
3174
3175 out:
3176         spin_unlock(&fs_info->qgroup_lock);
3177         return ret;
3178 }
3179
3180 /*
3181  * Free @num_bytes of reserved space with @type for qgroup.  (Normally level 0
3182  * qgroup).
3183  *
3184  * Will handle all higher level qgroup too.
3185  *
3186  * NOTE: If @num_bytes is (u64)-1, this means to free all bytes of this qgroup.
3187  * This special case is only used for META_PERTRANS type.
3188  */
3189 void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
3190                                u64 ref_root, u64 num_bytes,
3191                                enum btrfs_qgroup_rsv_type type)
3192 {
3193         struct btrfs_qgroup *qgroup;
3194         struct ulist_node *unode;
3195         struct ulist_iterator uiter;
3196         int ret = 0;
3197
3198         if (!is_fstree(ref_root))
3199                 return;
3200
3201         if (num_bytes == 0)
3202                 return;
3203
3204         if (num_bytes == (u64)-1 && type != BTRFS_QGROUP_RSV_META_PERTRANS) {
3205                 WARN(1, "%s: Invalid type to free", __func__);
3206                 return;
3207         }
3208         spin_lock(&fs_info->qgroup_lock);
3209
3210         if (!fs_info->quota_root)
3211                 goto out;
3212
3213         qgroup = find_qgroup_rb(fs_info, ref_root);
3214         if (!qgroup)
3215                 goto out;
3216
3217         if (num_bytes == (u64)-1)
3218                 /*
3219                  * We're freeing all pertrans rsv, get reserved value from
3220                  * level 0 qgroup as real num_bytes to free.
3221                  */
3222                 num_bytes = qgroup->rsv.values[type];
3223
3224         ulist_reinit(fs_info->qgroup_ulist);
3225         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3226                         qgroup_to_aux(qgroup), GFP_ATOMIC);
3227         if (ret < 0)
3228                 goto out;
3229         ULIST_ITER_INIT(&uiter);
3230         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3231                 struct btrfs_qgroup *qg;
3232                 struct btrfs_qgroup_list *glist;
3233
3234                 qg = unode_aux_to_qgroup(unode);
3235
3236                 qgroup_rsv_release(fs_info, qg, num_bytes, type);
3237
3238                 list_for_each_entry(glist, &qg->groups, next_group) {
3239                         ret = ulist_add(fs_info->qgroup_ulist,
3240                                         glist->group->qgroupid,
3241                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
3242                         if (ret < 0)
3243                                 goto out;
3244                 }
3245         }
3246
3247 out:
3248         spin_unlock(&fs_info->qgroup_lock);
3249 }
3250
3251 /*
3252  * Check if the leaf is the last leaf. Which means all node pointers
3253  * are at their last position.
3254  */
3255 static bool is_last_leaf(struct btrfs_path *path)
3256 {
3257         int i;
3258
3259         for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
3260                 if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
3261                         return false;
3262         }
3263         return true;
3264 }
3265
3266 /*
3267  * returns < 0 on error, 0 when more leafs are to be scanned.
3268  * returns 1 when done.
3269  */
3270 static int qgroup_rescan_leaf(struct btrfs_trans_handle *trans,
3271                               struct btrfs_path *path)
3272 {
3273         struct btrfs_fs_info *fs_info = trans->fs_info;
3274         struct btrfs_root *extent_root;
3275         struct btrfs_key found;
3276         struct extent_buffer *scratch_leaf = NULL;
3277         struct ulist *roots = NULL;
3278         u64 num_bytes;
3279         bool done;
3280         int slot;
3281         int ret;
3282
3283         mutex_lock(&fs_info->qgroup_rescan_lock);
3284         extent_root = btrfs_extent_root(fs_info,
3285                                 fs_info->qgroup_rescan_progress.objectid);
3286         ret = btrfs_search_slot_for_read(extent_root,
3287                                          &fs_info->qgroup_rescan_progress,
3288                                          path, 1, 0);
3289
3290         btrfs_debug(fs_info,
3291                 "current progress key (%llu %u %llu), search_slot ret %d",
3292                 fs_info->qgroup_rescan_progress.objectid,
3293                 fs_info->qgroup_rescan_progress.type,
3294                 fs_info->qgroup_rescan_progress.offset, ret);
3295
3296         if (ret) {
3297                 /*
3298                  * The rescan is about to end, we will not be scanning any
3299                  * further blocks. We cannot unset the RESCAN flag here, because
3300                  * we want to commit the transaction if everything went well.
3301                  * To make the live accounting work in this phase, we set our
3302                  * scan progress pointer such that every real extent objectid
3303                  * will be smaller.
3304                  */
3305                 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3306                 btrfs_release_path(path);
3307                 mutex_unlock(&fs_info->qgroup_rescan_lock);
3308                 return ret;
3309         }
3310         done = is_last_leaf(path);
3311
3312         btrfs_item_key_to_cpu(path->nodes[0], &found,
3313                               btrfs_header_nritems(path->nodes[0]) - 1);
3314         fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;
3315
3316         scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
3317         if (!scratch_leaf) {
3318                 ret = -ENOMEM;
3319                 mutex_unlock(&fs_info->qgroup_rescan_lock);
3320                 goto out;
3321         }
3322         slot = path->slots[0];
3323         btrfs_release_path(path);
3324         mutex_unlock(&fs_info->qgroup_rescan_lock);
3325
3326         for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
3327                 btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
3328                 if (found.type != BTRFS_EXTENT_ITEM_KEY &&
3329                     found.type != BTRFS_METADATA_ITEM_KEY)
3330                         continue;
3331                 if (found.type == BTRFS_METADATA_ITEM_KEY)
3332                         num_bytes = fs_info->nodesize;
3333                 else
3334                         num_bytes = found.offset;
3335
3336                 ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
3337                                            &roots, false);
3338                 if (ret < 0)
3339                         goto out;
3340                 /* For rescan, just pass old_roots as NULL */
3341                 ret = btrfs_qgroup_account_extent(trans, found.objectid,
3342                                                   num_bytes, NULL, roots);
3343                 if (ret < 0)
3344                         goto out;
3345         }
3346 out:
3347         if (scratch_leaf)
3348                 free_extent_buffer(scratch_leaf);
3349
3350         if (done && !ret) {
3351                 ret = 1;
3352                 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3353         }
3354         return ret;
3355 }
3356
3357 static bool rescan_should_stop(struct btrfs_fs_info *fs_info)
3358 {
3359         return btrfs_fs_closing(fs_info) ||
3360                 test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state) ||
3361                 !test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3362                           fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN;
3363 }
3364
3365 static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
3366 {
3367         struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
3368                                                      qgroup_rescan_work);
3369         struct btrfs_path *path;
3370         struct btrfs_trans_handle *trans = NULL;
3371         int err = -ENOMEM;
3372         int ret = 0;
3373         bool stopped = false;
3374         bool did_leaf_rescans = false;
3375
3376         path = btrfs_alloc_path();
3377         if (!path)
3378                 goto out;
3379         /*
3380          * Rescan should only search for commit root, and any later difference
3381          * should be recorded by qgroup
3382          */
3383         path->search_commit_root = 1;
3384         path->skip_locking = 1;
3385
3386         err = 0;
3387         while (!err && !(stopped = rescan_should_stop(fs_info))) {
3388                 trans = btrfs_start_transaction(fs_info->fs_root, 0);
3389                 if (IS_ERR(trans)) {
3390                         err = PTR_ERR(trans);
3391                         break;
3392                 }
3393
3394                 err = qgroup_rescan_leaf(trans, path);
3395                 did_leaf_rescans = true;
3396
3397                 if (err > 0)
3398                         btrfs_commit_transaction(trans);
3399                 else
3400                         btrfs_end_transaction(trans);
3401         }
3402
3403 out:
3404         btrfs_free_path(path);
3405
3406         mutex_lock(&fs_info->qgroup_rescan_lock);
3407         if (err > 0 &&
3408             fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT) {
3409                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3410         } else if (err < 0 || stopped) {
3411                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3412         }
3413         mutex_unlock(&fs_info->qgroup_rescan_lock);
3414
3415         /*
3416          * Only update status, since the previous part has already updated the
3417          * qgroup info, and only if we did any actual work. This also prevents
3418          * race with a concurrent quota disable, which has already set
3419          * fs_info->quota_root to NULL and cleared BTRFS_FS_QUOTA_ENABLED at
3420          * btrfs_quota_disable().
3421          */
3422         if (did_leaf_rescans) {
3423                 trans = btrfs_start_transaction(fs_info->quota_root, 1);
3424                 if (IS_ERR(trans)) {
3425                         err = PTR_ERR(trans);
3426                         trans = NULL;
3427                         btrfs_err(fs_info,
3428                                   "fail to start transaction for status update: %d",
3429                                   err);
3430                 }
3431         } else {
3432                 trans = NULL;
3433         }
3434
3435         mutex_lock(&fs_info->qgroup_rescan_lock);
3436         if (!stopped ||
3437             fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN)
3438                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3439         if (trans) {
3440                 ret = update_qgroup_status_item(trans);
3441                 if (ret < 0) {
3442                         err = ret;
3443                         btrfs_err(fs_info, "fail to update qgroup status: %d",
3444                                   err);
3445                 }
3446         }
3447         fs_info->qgroup_rescan_running = false;
3448         fs_info->qgroup_flags &= ~BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN;
3449         complete_all(&fs_info->qgroup_rescan_completion);
3450         mutex_unlock(&fs_info->qgroup_rescan_lock);
3451
3452         if (!trans)
3453                 return;
3454
3455         btrfs_end_transaction(trans);
3456
3457         if (stopped) {
3458                 btrfs_info(fs_info, "qgroup scan paused");
3459         } else if (fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN) {
3460                 btrfs_info(fs_info, "qgroup scan cancelled");
3461         } else if (err >= 0) {
3462                 btrfs_info(fs_info, "qgroup scan completed%s",
3463                         err > 0 ? " (inconsistency flag cleared)" : "");
3464         } else {
3465                 btrfs_err(fs_info, "qgroup scan failed with %d", err);
3466         }
3467 }
3468
3469 /*
3470  * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
3471  * memory required for the rescan context.
3472  */
3473 static int
3474 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
3475                    int init_flags)
3476 {
3477         int ret = 0;
3478
3479         if (!init_flags) {
3480                 /* we're resuming qgroup rescan at mount time */
3481                 if (!(fs_info->qgroup_flags &
3482                       BTRFS_QGROUP_STATUS_FLAG_RESCAN)) {
3483                         btrfs_warn(fs_info,
3484                         "qgroup rescan init failed, qgroup rescan is not queued");
3485                         ret = -EINVAL;
3486                 } else if (!(fs_info->qgroup_flags &
3487                              BTRFS_QGROUP_STATUS_FLAG_ON)) {
3488                         btrfs_warn(fs_info,
3489                         "qgroup rescan init failed, qgroup is not enabled");
3490                         ret = -EINVAL;
3491                 }
3492
3493                 if (ret)
3494                         return ret;
3495         }
3496
3497         mutex_lock(&fs_info->qgroup_rescan_lock);
3498
3499         if (init_flags) {
3500                 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3501                         btrfs_warn(fs_info,
3502                                    "qgroup rescan is already in progress");
3503                         ret = -EINPROGRESS;
3504                 } else if (!(fs_info->qgroup_flags &
3505                              BTRFS_QGROUP_STATUS_FLAG_ON)) {
3506                         btrfs_warn(fs_info,
3507                         "qgroup rescan init failed, qgroup is not enabled");
3508                         ret = -EINVAL;
3509                 } else if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
3510                         /* Quota disable is in progress */
3511                         ret = -EBUSY;
3512                 }
3513
3514                 if (ret) {
3515                         mutex_unlock(&fs_info->qgroup_rescan_lock);
3516                         return ret;
3517                 }
3518                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3519         }
3520
3521         memset(&fs_info->qgroup_rescan_progress, 0,
3522                 sizeof(fs_info->qgroup_rescan_progress));
3523         fs_info->qgroup_flags &= ~(BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN |
3524                                    BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING);
3525         fs_info->qgroup_rescan_progress.objectid = progress_objectid;
3526         init_completion(&fs_info->qgroup_rescan_completion);
3527         mutex_unlock(&fs_info->qgroup_rescan_lock);
3528
3529         btrfs_init_work(&fs_info->qgroup_rescan_work,
3530                         btrfs_qgroup_rescan_worker, NULL, NULL);
3531         return 0;
3532 }
3533
3534 static void
3535 qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
3536 {
3537         struct rb_node *n;
3538         struct btrfs_qgroup *qgroup;
3539
3540         spin_lock(&fs_info->qgroup_lock);
3541         /* clear all current qgroup tracking information */
3542         for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
3543                 qgroup = rb_entry(n, struct btrfs_qgroup, node);
3544                 qgroup->rfer = 0;
3545                 qgroup->rfer_cmpr = 0;
3546                 qgroup->excl = 0;
3547                 qgroup->excl_cmpr = 0;
3548                 qgroup_dirty(fs_info, qgroup);
3549         }
3550         spin_unlock(&fs_info->qgroup_lock);
3551 }
3552
3553 int
3554 btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
3555 {
3556         int ret = 0;
3557         struct btrfs_trans_handle *trans;
3558
3559         ret = qgroup_rescan_init(fs_info, 0, 1);
3560         if (ret)
3561                 return ret;
3562
3563         /*
3564          * We have set the rescan_progress to 0, which means no more
3565          * delayed refs will be accounted by btrfs_qgroup_account_ref.
3566          * However, btrfs_qgroup_account_ref may be right after its call
3567          * to btrfs_find_all_roots, in which case it would still do the
3568          * accounting.
3569          * To solve this, we're committing the transaction, which will
3570          * ensure we run all delayed refs and only after that, we are
3571          * going to clear all tracking information for a clean start.
3572          */
3573
3574         trans = btrfs_join_transaction(fs_info->fs_root);
3575         if (IS_ERR(trans)) {
3576                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3577                 return PTR_ERR(trans);
3578         }
3579         ret = btrfs_commit_transaction(trans);
3580         if (ret) {
3581                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3582                 return ret;
3583         }
3584
3585         qgroup_rescan_zero_tracking(fs_info);
3586
3587         mutex_lock(&fs_info->qgroup_rescan_lock);
3588         fs_info->qgroup_rescan_running = true;
3589         btrfs_queue_work(fs_info->qgroup_rescan_workers,
3590                          &fs_info->qgroup_rescan_work);
3591         mutex_unlock(&fs_info->qgroup_rescan_lock);
3592
3593         return 0;
3594 }
3595
3596 int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
3597                                      bool interruptible)
3598 {
3599         int running;
3600         int ret = 0;
3601
3602         mutex_lock(&fs_info->qgroup_rescan_lock);
3603         running = fs_info->qgroup_rescan_running;
3604         mutex_unlock(&fs_info->qgroup_rescan_lock);
3605
3606         if (!running)
3607                 return 0;
3608
3609         if (interruptible)
3610                 ret = wait_for_completion_interruptible(
3611                                         &fs_info->qgroup_rescan_completion);
3612         else
3613                 wait_for_completion(&fs_info->qgroup_rescan_completion);
3614
3615         return ret;
3616 }
3617
3618 /*
3619  * this is only called from open_ctree where we're still single threaded, thus
3620  * locking is omitted here.
3621  */
3622 void
3623 btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
3624 {
3625         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3626                 mutex_lock(&fs_info->qgroup_rescan_lock);
3627                 fs_info->qgroup_rescan_running = true;
3628                 btrfs_queue_work(fs_info->qgroup_rescan_workers,
3629                                  &fs_info->qgroup_rescan_work);
3630                 mutex_unlock(&fs_info->qgroup_rescan_lock);
3631         }
3632 }
3633
3634 #define rbtree_iterate_from_safe(node, next, start)                             \
3635        for (node = start; node && ({ next = rb_next(node); 1;}); node = next)
3636
3637 static int qgroup_unreserve_range(struct btrfs_inode *inode,
3638                                   struct extent_changeset *reserved, u64 start,
3639                                   u64 len)
3640 {
3641         struct rb_node *node;
3642         struct rb_node *next;
3643         struct ulist_node *entry;
3644         int ret = 0;
3645
3646         node = reserved->range_changed.root.rb_node;
3647         if (!node)
3648                 return 0;
3649         while (node) {
3650                 entry = rb_entry(node, struct ulist_node, rb_node);
3651                 if (entry->val < start)
3652                         node = node->rb_right;
3653                 else
3654                         node = node->rb_left;
3655         }
3656
3657         if (entry->val > start && rb_prev(&entry->rb_node))
3658                 entry = rb_entry(rb_prev(&entry->rb_node), struct ulist_node,
3659                                  rb_node);
3660
3661         rbtree_iterate_from_safe(node, next, &entry->rb_node) {
3662                 u64 entry_start;
3663                 u64 entry_end;
3664                 u64 entry_len;
3665                 int clear_ret;
3666
3667                 entry = rb_entry(node, struct ulist_node, rb_node);
3668                 entry_start = entry->val;
3669                 entry_end = entry->aux;
3670                 entry_len = entry_end - entry_start + 1;
3671
3672                 if (entry_start >= start + len)
3673                         break;
3674                 if (entry_start + entry_len <= start)
3675                         continue;
3676                 /*
3677                  * Now the entry is in [start, start + len), revert the
3678                  * EXTENT_QGROUP_RESERVED bit.
3679                  */
3680                 clear_ret = clear_extent_bits(&inode->io_tree, entry_start,
3681                                               entry_end, EXTENT_QGROUP_RESERVED);
3682                 if (!ret && clear_ret < 0)
3683                         ret = clear_ret;
3684
3685                 ulist_del(&reserved->range_changed, entry->val, entry->aux);
3686                 if (likely(reserved->bytes_changed >= entry_len)) {
3687                         reserved->bytes_changed -= entry_len;
3688                 } else {
3689                         WARN_ON(1);
3690                         reserved->bytes_changed = 0;
3691                 }
3692         }
3693
3694         return ret;
3695 }
3696
3697 /*
3698  * Try to free some space for qgroup.
3699  *
3700  * For qgroup, there are only 3 ways to free qgroup space:
3701  * - Flush nodatacow write
3702  *   Any nodatacow write will free its reserved data space at run_delalloc_range().
3703  *   In theory, we should only flush nodatacow inodes, but it's not yet
3704  *   possible, so we need to flush the whole root.
3705  *
3706  * - Wait for ordered extents
3707  *   When ordered extents are finished, their reserved metadata is finally
3708  *   converted to per_trans status, which can be freed by later commit
3709  *   transaction.
3710  *
3711  * - Commit transaction
3712  *   This would free the meta_per_trans space.
3713  *   In theory this shouldn't provide much space, but any more qgroup space
3714  *   is needed.
3715  */
3716 static int try_flush_qgroup(struct btrfs_root *root)
3717 {
3718         struct btrfs_trans_handle *trans;
3719         int ret;
3720
3721         /* Can't hold an open transaction or we run the risk of deadlocking. */
3722         ASSERT(current->journal_info == NULL);
3723         if (WARN_ON(current->journal_info))
3724                 return 0;
3725
3726         /*
3727          * We don't want to run flush again and again, so if there is a running
3728          * one, we won't try to start a new flush, but exit directly.
3729          */
3730         if (test_and_set_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state)) {
3731                 wait_event(root->qgroup_flush_wait,
3732                         !test_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state));
3733                 return 0;
3734         }
3735
3736         ret = btrfs_start_delalloc_snapshot(root, true);
3737         if (ret < 0)
3738                 goto out;
3739         btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
3740
3741         trans = btrfs_join_transaction(root);
3742         if (IS_ERR(trans)) {
3743                 ret = PTR_ERR(trans);
3744                 goto out;
3745         }
3746
3747         ret = btrfs_commit_transaction(trans);
3748 out:
3749         clear_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state);
3750         wake_up(&root->qgroup_flush_wait);
3751         return ret;
3752 }
3753
3754 static int qgroup_reserve_data(struct btrfs_inode *inode,
3755                         struct extent_changeset **reserved_ret, u64 start,
3756                         u64 len)
3757 {
3758         struct btrfs_root *root = inode->root;
3759         struct extent_changeset *reserved;
3760         bool new_reserved = false;
3761         u64 orig_reserved;
3762         u64 to_reserve;
3763         int ret;
3764
3765         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
3766             !is_fstree(root->root_key.objectid) || len == 0)
3767                 return 0;
3768
3769         /* @reserved parameter is mandatory for qgroup */
3770         if (WARN_ON(!reserved_ret))
3771                 return -EINVAL;
3772         if (!*reserved_ret) {
3773                 new_reserved = true;
3774                 *reserved_ret = extent_changeset_alloc();
3775                 if (!*reserved_ret)
3776                         return -ENOMEM;
3777         }
3778         reserved = *reserved_ret;
3779         /* Record already reserved space */
3780         orig_reserved = reserved->bytes_changed;
3781         ret = set_record_extent_bits(&inode->io_tree, start,
3782                         start + len -1, EXTENT_QGROUP_RESERVED, reserved);
3783
3784         /* Newly reserved space */
3785         to_reserve = reserved->bytes_changed - orig_reserved;
3786         trace_btrfs_qgroup_reserve_data(&inode->vfs_inode, start, len,
3787                                         to_reserve, QGROUP_RESERVE);
3788         if (ret < 0)
3789                 goto out;
3790         ret = qgroup_reserve(root, to_reserve, true, BTRFS_QGROUP_RSV_DATA);
3791         if (ret < 0)
3792                 goto cleanup;
3793
3794         return ret;
3795
3796 cleanup:
3797         qgroup_unreserve_range(inode, reserved, start, len);
3798 out:
3799         if (new_reserved) {
3800                 extent_changeset_free(reserved);
3801                 *reserved_ret = NULL;
3802         }
3803         return ret;
3804 }
3805
3806 /*
3807  * Reserve qgroup space for range [start, start + len).
3808  *
3809  * This function will either reserve space from related qgroups or do nothing
3810  * if the range is already reserved.
3811  *
3812  * Return 0 for successful reservation
3813  * Return <0 for error (including -EQUOT)
3814  *
3815  * NOTE: This function may sleep for memory allocation, dirty page flushing and
3816  *       commit transaction. So caller should not hold any dirty page locked.
3817  */
3818 int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
3819                         struct extent_changeset **reserved_ret, u64 start,
3820                         u64 len)
3821 {
3822         int ret;
3823
3824         ret = qgroup_reserve_data(inode, reserved_ret, start, len);
3825         if (ret <= 0 && ret != -EDQUOT)
3826                 return ret;
3827
3828         ret = try_flush_qgroup(inode->root);
3829         if (ret < 0)
3830                 return ret;
3831         return qgroup_reserve_data(inode, reserved_ret, start, len);
3832 }
3833
3834 /* Free ranges specified by @reserved, normally in error path */
3835 static int qgroup_free_reserved_data(struct btrfs_inode *inode,
3836                         struct extent_changeset *reserved, u64 start, u64 len)
3837 {
3838         struct btrfs_root *root = inode->root;
3839         struct ulist_node *unode;
3840         struct ulist_iterator uiter;
3841         struct extent_changeset changeset;
3842         int freed = 0;
3843         int ret;
3844
3845         extent_changeset_init(&changeset);
3846         len = round_up(start + len, root->fs_info->sectorsize);
3847         start = round_down(start, root->fs_info->sectorsize);
3848
3849         ULIST_ITER_INIT(&uiter);
3850         while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
3851                 u64 range_start = unode->val;
3852                 /* unode->aux is the inclusive end */
3853                 u64 range_len = unode->aux - range_start + 1;
3854                 u64 free_start;
3855                 u64 free_len;
3856
3857                 extent_changeset_release(&changeset);
3858
3859                 /* Only free range in range [start, start + len) */
3860                 if (range_start >= start + len ||
3861                     range_start + range_len <= start)
3862                         continue;
3863                 free_start = max(range_start, start);
3864                 free_len = min(start + len, range_start + range_len) -
3865                            free_start;
3866                 /*
3867                  * TODO: To also modify reserved->ranges_reserved to reflect
3868                  * the modification.
3869                  *
3870                  * However as long as we free qgroup reserved according to
3871                  * EXTENT_QGROUP_RESERVED, we won't double free.
3872                  * So not need to rush.
3873                  */
3874                 ret = clear_record_extent_bits(&inode->io_tree, free_start,
3875                                 free_start + free_len - 1,
3876                                 EXTENT_QGROUP_RESERVED, &changeset);
3877                 if (ret < 0)
3878                         goto out;
3879                 freed += changeset.bytes_changed;
3880         }
3881         btrfs_qgroup_free_refroot(root->fs_info, root->root_key.objectid, freed,
3882                                   BTRFS_QGROUP_RSV_DATA);
3883         ret = freed;
3884 out:
3885         extent_changeset_release(&changeset);
3886         return ret;
3887 }
3888
3889 static int __btrfs_qgroup_release_data(struct btrfs_inode *inode,
3890                         struct extent_changeset *reserved, u64 start, u64 len,
3891                         int free)
3892 {
3893         struct extent_changeset changeset;
3894         int trace_op = QGROUP_RELEASE;
3895         int ret;
3896
3897         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &inode->root->fs_info->flags))
3898                 return 0;
3899
3900         /* In release case, we shouldn't have @reserved */
3901         WARN_ON(!free && reserved);
3902         if (free && reserved)
3903                 return qgroup_free_reserved_data(inode, reserved, start, len);
3904         extent_changeset_init(&changeset);
3905         ret = clear_record_extent_bits(&inode->io_tree, start, start + len -1,
3906                                        EXTENT_QGROUP_RESERVED, &changeset);
3907         if (ret < 0)
3908                 goto out;
3909
3910         if (free)
3911                 trace_op = QGROUP_FREE;
3912         trace_btrfs_qgroup_release_data(&inode->vfs_inode, start, len,
3913                                         changeset.bytes_changed, trace_op);
3914         if (free)
3915                 btrfs_qgroup_free_refroot(inode->root->fs_info,
3916                                 inode->root->root_key.objectid,
3917                                 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
3918         ret = changeset.bytes_changed;
3919 out:
3920         extent_changeset_release(&changeset);
3921         return ret;
3922 }
3923
3924 /*
3925  * Free a reserved space range from io_tree and related qgroups
3926  *
3927  * Should be called when a range of pages get invalidated before reaching disk.
3928  * Or for error cleanup case.
3929  * if @reserved is given, only reserved range in [@start, @start + @len) will
3930  * be freed.
3931  *
3932  * For data written to disk, use btrfs_qgroup_release_data().
3933  *
3934  * NOTE: This function may sleep for memory allocation.
3935  */
3936 int btrfs_qgroup_free_data(struct btrfs_inode *inode,
3937                         struct extent_changeset *reserved, u64 start, u64 len)
3938 {
3939         return __btrfs_qgroup_release_data(inode, reserved, start, len, 1);
3940 }
3941
3942 /*
3943  * Release a reserved space range from io_tree only.
3944  *
3945  * Should be called when a range of pages get written to disk and corresponding
3946  * FILE_EXTENT is inserted into corresponding root.
3947  *
3948  * Since new qgroup accounting framework will only update qgroup numbers at
3949  * commit_transaction() time, its reserved space shouldn't be freed from
3950  * related qgroups.
3951  *
3952  * But we should release the range from io_tree, to allow further write to be
3953  * COWed.
3954  *
3955  * NOTE: This function may sleep for memory allocation.
3956  */
3957 int btrfs_qgroup_release_data(struct btrfs_inode *inode, u64 start, u64 len)
3958 {
3959         return __btrfs_qgroup_release_data(inode, NULL, start, len, 0);
3960 }
3961
3962 static void add_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3963                               enum btrfs_qgroup_rsv_type type)
3964 {
3965         if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3966             type != BTRFS_QGROUP_RSV_META_PERTRANS)
3967                 return;
3968         if (num_bytes == 0)
3969                 return;
3970
3971         spin_lock(&root->qgroup_meta_rsv_lock);
3972         if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
3973                 root->qgroup_meta_rsv_prealloc += num_bytes;
3974         else
3975                 root->qgroup_meta_rsv_pertrans += num_bytes;
3976         spin_unlock(&root->qgroup_meta_rsv_lock);
3977 }
3978
3979 static int sub_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3980                              enum btrfs_qgroup_rsv_type type)
3981 {
3982         if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3983             type != BTRFS_QGROUP_RSV_META_PERTRANS)
3984                 return 0;
3985         if (num_bytes == 0)
3986                 return 0;
3987
3988         spin_lock(&root->qgroup_meta_rsv_lock);
3989         if (type == BTRFS_QGROUP_RSV_META_PREALLOC) {
3990                 num_bytes = min_t(u64, root->qgroup_meta_rsv_prealloc,
3991                                   num_bytes);
3992                 root->qgroup_meta_rsv_prealloc -= num_bytes;
3993         } else {
3994                 num_bytes = min_t(u64, root->qgroup_meta_rsv_pertrans,
3995                                   num_bytes);
3996                 root->qgroup_meta_rsv_pertrans -= num_bytes;
3997         }
3998         spin_unlock(&root->qgroup_meta_rsv_lock);
3999         return num_bytes;
4000 }
4001
4002 int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
4003                               enum btrfs_qgroup_rsv_type type, bool enforce)
4004 {
4005         struct btrfs_fs_info *fs_info = root->fs_info;
4006         int ret;
4007
4008         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4009             !is_fstree(root->root_key.objectid) || num_bytes == 0)
4010                 return 0;
4011
4012         BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4013         trace_qgroup_meta_reserve(root, (s64)num_bytes, type);
4014         ret = qgroup_reserve(root, num_bytes, enforce, type);
4015         if (ret < 0)
4016                 return ret;
4017         /*
4018          * Record what we have reserved into root.
4019          *
4020          * To avoid quota disabled->enabled underflow.
4021          * In that case, we may try to free space we haven't reserved
4022          * (since quota was disabled), so record what we reserved into root.
4023          * And ensure later release won't underflow this number.
4024          */
4025         add_root_meta_rsv(root, num_bytes, type);
4026         return ret;
4027 }
4028
4029 int __btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
4030                                 enum btrfs_qgroup_rsv_type type, bool enforce,
4031                                 bool noflush)
4032 {
4033         int ret;
4034
4035         ret = btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4036         if ((ret <= 0 && ret != -EDQUOT) || noflush)
4037                 return ret;
4038
4039         ret = try_flush_qgroup(root);
4040         if (ret < 0)
4041                 return ret;
4042         return btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4043 }
4044
4045 void btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root *root)
4046 {
4047         struct btrfs_fs_info *fs_info = root->fs_info;
4048
4049         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4050             !is_fstree(root->root_key.objectid))
4051                 return;
4052
4053         /* TODO: Update trace point to handle such free */
4054         trace_qgroup_meta_free_all_pertrans(root);
4055         /* Special value -1 means to free all reserved space */
4056         btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid, (u64)-1,
4057                                   BTRFS_QGROUP_RSV_META_PERTRANS);
4058 }
4059
4060 void __btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes,
4061                               enum btrfs_qgroup_rsv_type type)
4062 {
4063         struct btrfs_fs_info *fs_info = root->fs_info;
4064
4065         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4066             !is_fstree(root->root_key.objectid))
4067                 return;
4068
4069         /*
4070          * reservation for META_PREALLOC can happen before quota is enabled,
4071          * which can lead to underflow.
4072          * Here ensure we will only free what we really have reserved.
4073          */
4074         num_bytes = sub_root_meta_rsv(root, num_bytes, type);
4075         BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4076         trace_qgroup_meta_reserve(root, -(s64)num_bytes, type);
4077         btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid,
4078                                   num_bytes, type);
4079 }
4080
4081 static void qgroup_convert_meta(struct btrfs_fs_info *fs_info, u64 ref_root,
4082                                 int num_bytes)
4083 {
4084         struct btrfs_qgroup *qgroup;
4085         struct ulist_node *unode;
4086         struct ulist_iterator uiter;
4087         int ret = 0;
4088
4089         if (num_bytes == 0)
4090                 return;
4091         if (!fs_info->quota_root)
4092                 return;
4093
4094         spin_lock(&fs_info->qgroup_lock);
4095         qgroup = find_qgroup_rb(fs_info, ref_root);
4096         if (!qgroup)
4097                 goto out;
4098         ulist_reinit(fs_info->qgroup_ulist);
4099         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
4100                        qgroup_to_aux(qgroup), GFP_ATOMIC);
4101         if (ret < 0)
4102                 goto out;
4103         ULIST_ITER_INIT(&uiter);
4104         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
4105                 struct btrfs_qgroup *qg;
4106                 struct btrfs_qgroup_list *glist;
4107
4108                 qg = unode_aux_to_qgroup(unode);
4109
4110                 qgroup_rsv_release(fs_info, qg, num_bytes,
4111                                 BTRFS_QGROUP_RSV_META_PREALLOC);
4112                 qgroup_rsv_add(fs_info, qg, num_bytes,
4113                                 BTRFS_QGROUP_RSV_META_PERTRANS);
4114                 list_for_each_entry(glist, &qg->groups, next_group) {
4115                         ret = ulist_add(fs_info->qgroup_ulist,
4116                                         glist->group->qgroupid,
4117                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
4118                         if (ret < 0)
4119                                 goto out;
4120                 }
4121         }
4122 out:
4123         spin_unlock(&fs_info->qgroup_lock);
4124 }
4125
4126 void btrfs_qgroup_convert_reserved_meta(struct btrfs_root *root, int num_bytes)
4127 {
4128         struct btrfs_fs_info *fs_info = root->fs_info;
4129
4130         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4131             !is_fstree(root->root_key.objectid))
4132                 return;
4133         /* Same as btrfs_qgroup_free_meta_prealloc() */
4134         num_bytes = sub_root_meta_rsv(root, num_bytes,
4135                                       BTRFS_QGROUP_RSV_META_PREALLOC);
4136         trace_qgroup_meta_convert(root, num_bytes);
4137         qgroup_convert_meta(fs_info, root->root_key.objectid, num_bytes);
4138 }
4139
4140 /*
4141  * Check qgroup reserved space leaking, normally at destroy inode
4142  * time
4143  */
4144 void btrfs_qgroup_check_reserved_leak(struct btrfs_inode *inode)
4145 {
4146         struct extent_changeset changeset;
4147         struct ulist_node *unode;
4148         struct ulist_iterator iter;
4149         int ret;
4150
4151         extent_changeset_init(&changeset);
4152         ret = clear_record_extent_bits(&inode->io_tree, 0, (u64)-1,
4153                         EXTENT_QGROUP_RESERVED, &changeset);
4154
4155         WARN_ON(ret < 0);
4156         if (WARN_ON(changeset.bytes_changed)) {
4157                 ULIST_ITER_INIT(&iter);
4158                 while ((unode = ulist_next(&changeset.range_changed, &iter))) {
4159                         btrfs_warn(inode->root->fs_info,
4160                 "leaking qgroup reserved space, ino: %llu, start: %llu, end: %llu",
4161                                 btrfs_ino(inode), unode->val, unode->aux);
4162                 }
4163                 btrfs_qgroup_free_refroot(inode->root->fs_info,
4164                                 inode->root->root_key.objectid,
4165                                 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
4166
4167         }
4168         extent_changeset_release(&changeset);
4169 }
4170
4171 void btrfs_qgroup_init_swapped_blocks(
4172         struct btrfs_qgroup_swapped_blocks *swapped_blocks)
4173 {
4174         int i;
4175
4176         spin_lock_init(&swapped_blocks->lock);
4177         for (i = 0; i < BTRFS_MAX_LEVEL; i++)
4178                 swapped_blocks->blocks[i] = RB_ROOT;
4179         swapped_blocks->swapped = false;
4180 }
4181
4182 /*
4183  * Delete all swapped blocks record of @root.
4184  * Every record here means we skipped a full subtree scan for qgroup.
4185  *
4186  * Gets called when committing one transaction.
4187  */
4188 void btrfs_qgroup_clean_swapped_blocks(struct btrfs_root *root)
4189 {
4190         struct btrfs_qgroup_swapped_blocks *swapped_blocks;
4191         int i;
4192
4193         swapped_blocks = &root->swapped_blocks;
4194
4195         spin_lock(&swapped_blocks->lock);
4196         if (!swapped_blocks->swapped)
4197                 goto out;
4198         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4199                 struct rb_root *cur_root = &swapped_blocks->blocks[i];
4200                 struct btrfs_qgroup_swapped_block *entry;
4201                 struct btrfs_qgroup_swapped_block *next;
4202
4203                 rbtree_postorder_for_each_entry_safe(entry, next, cur_root,
4204                                                      node)
4205                         kfree(entry);
4206                 swapped_blocks->blocks[i] = RB_ROOT;
4207         }
4208         swapped_blocks->swapped = false;
4209 out:
4210         spin_unlock(&swapped_blocks->lock);
4211 }
4212
4213 /*
4214  * Add subtree roots record into @subvol_root.
4215  *
4216  * @subvol_root:        tree root of the subvolume tree get swapped
4217  * @bg:                 block group under balance
4218  * @subvol_parent/slot: pointer to the subtree root in subvolume tree
4219  * @reloc_parent/slot:  pointer to the subtree root in reloc tree
4220  *                      BOTH POINTERS ARE BEFORE TREE SWAP
4221  * @last_snapshot:      last snapshot generation of the subvolume tree
4222  */
4223 int btrfs_qgroup_add_swapped_blocks(struct btrfs_trans_handle *trans,
4224                 struct btrfs_root *subvol_root,
4225                 struct btrfs_block_group *bg,
4226                 struct extent_buffer *subvol_parent, int subvol_slot,
4227                 struct extent_buffer *reloc_parent, int reloc_slot,
4228                 u64 last_snapshot)
4229 {
4230         struct btrfs_fs_info *fs_info = subvol_root->fs_info;
4231         struct btrfs_qgroup_swapped_blocks *blocks = &subvol_root->swapped_blocks;
4232         struct btrfs_qgroup_swapped_block *block;
4233         struct rb_node **cur;
4234         struct rb_node *parent = NULL;
4235         int level = btrfs_header_level(subvol_parent) - 1;
4236         int ret = 0;
4237
4238         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4239                 return 0;
4240
4241         if (btrfs_node_ptr_generation(subvol_parent, subvol_slot) >
4242             btrfs_node_ptr_generation(reloc_parent, reloc_slot)) {
4243                 btrfs_err_rl(fs_info,
4244                 "%s: bad parameter order, subvol_gen=%llu reloc_gen=%llu",
4245                         __func__,
4246                         btrfs_node_ptr_generation(subvol_parent, subvol_slot),
4247                         btrfs_node_ptr_generation(reloc_parent, reloc_slot));
4248                 return -EUCLEAN;
4249         }
4250
4251         block = kmalloc(sizeof(*block), GFP_NOFS);
4252         if (!block) {
4253                 ret = -ENOMEM;
4254                 goto out;
4255         }
4256
4257         /*
4258          * @reloc_parent/slot is still before swap, while @block is going to
4259          * record the bytenr after swap, so we do the swap here.
4260          */
4261         block->subvol_bytenr = btrfs_node_blockptr(reloc_parent, reloc_slot);
4262         block->subvol_generation = btrfs_node_ptr_generation(reloc_parent,
4263                                                              reloc_slot);
4264         block->reloc_bytenr = btrfs_node_blockptr(subvol_parent, subvol_slot);
4265         block->reloc_generation = btrfs_node_ptr_generation(subvol_parent,
4266                                                             subvol_slot);
4267         block->last_snapshot = last_snapshot;
4268         block->level = level;
4269
4270         /*
4271          * If we have bg == NULL, we're called from btrfs_recover_relocation(),
4272          * no one else can modify tree blocks thus we qgroup will not change
4273          * no matter the value of trace_leaf.
4274          */
4275         if (bg && bg->flags & BTRFS_BLOCK_GROUP_DATA)
4276                 block->trace_leaf = true;
4277         else
4278                 block->trace_leaf = false;
4279         btrfs_node_key_to_cpu(reloc_parent, &block->first_key, reloc_slot);
4280
4281         /* Insert @block into @blocks */
4282         spin_lock(&blocks->lock);
4283         cur = &blocks->blocks[level].rb_node;
4284         while (*cur) {
4285                 struct btrfs_qgroup_swapped_block *entry;
4286
4287                 parent = *cur;
4288                 entry = rb_entry(parent, struct btrfs_qgroup_swapped_block,
4289                                  node);
4290
4291                 if (entry->subvol_bytenr < block->subvol_bytenr) {
4292                         cur = &(*cur)->rb_left;
4293                 } else if (entry->subvol_bytenr > block->subvol_bytenr) {
4294                         cur = &(*cur)->rb_right;
4295                 } else {
4296                         if (entry->subvol_generation !=
4297                                         block->subvol_generation ||
4298                             entry->reloc_bytenr != block->reloc_bytenr ||
4299                             entry->reloc_generation !=
4300                                         block->reloc_generation) {
4301                                 /*
4302                                  * Duplicated but mismatch entry found.
4303                                  * Shouldn't happen.
4304                                  *
4305                                  * Marking qgroup inconsistent should be enough
4306                                  * for end users.
4307                                  */
4308                                 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4309                                 ret = -EEXIST;
4310                         }
4311                         kfree(block);
4312                         goto out_unlock;
4313                 }
4314         }
4315         rb_link_node(&block->node, parent, cur);
4316         rb_insert_color(&block->node, &blocks->blocks[level]);
4317         blocks->swapped = true;
4318 out_unlock:
4319         spin_unlock(&blocks->lock);
4320 out:
4321         if (ret < 0)
4322                 qgroup_mark_inconsistent(fs_info);
4323         return ret;
4324 }
4325
4326 /*
4327  * Check if the tree block is a subtree root, and if so do the needed
4328  * delayed subtree trace for qgroup.
4329  *
4330  * This is called during btrfs_cow_block().
4331  */
4332 int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans,
4333                                          struct btrfs_root *root,
4334                                          struct extent_buffer *subvol_eb)
4335 {
4336         struct btrfs_fs_info *fs_info = root->fs_info;
4337         struct btrfs_qgroup_swapped_blocks *blocks = &root->swapped_blocks;
4338         struct btrfs_qgroup_swapped_block *block;
4339         struct extent_buffer *reloc_eb = NULL;
4340         struct rb_node *node;
4341         bool found = false;
4342         bool swapped = false;
4343         int level = btrfs_header_level(subvol_eb);
4344         int ret = 0;
4345         int i;
4346
4347         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4348                 return 0;
4349         if (!is_fstree(root->root_key.objectid) || !root->reloc_root)
4350                 return 0;
4351
4352         spin_lock(&blocks->lock);
4353         if (!blocks->swapped) {
4354                 spin_unlock(&blocks->lock);
4355                 return 0;
4356         }
4357         node = blocks->blocks[level].rb_node;
4358
4359         while (node) {
4360                 block = rb_entry(node, struct btrfs_qgroup_swapped_block, node);
4361                 if (block->subvol_bytenr < subvol_eb->start) {
4362                         node = node->rb_left;
4363                 } else if (block->subvol_bytenr > subvol_eb->start) {
4364                         node = node->rb_right;
4365                 } else {
4366                         found = true;
4367                         break;
4368                 }
4369         }
4370         if (!found) {
4371                 spin_unlock(&blocks->lock);
4372                 goto out;
4373         }
4374         /* Found one, remove it from @blocks first and update blocks->swapped */
4375         rb_erase(&block->node, &blocks->blocks[level]);
4376         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4377                 if (RB_EMPTY_ROOT(&blocks->blocks[i])) {
4378                         swapped = true;
4379                         break;
4380                 }
4381         }
4382         blocks->swapped = swapped;
4383         spin_unlock(&blocks->lock);
4384
4385         /* Read out reloc subtree root */
4386         reloc_eb = read_tree_block(fs_info, block->reloc_bytenr, 0,
4387                                    block->reloc_generation, block->level,
4388                                    &block->first_key);
4389         if (IS_ERR(reloc_eb)) {
4390                 ret = PTR_ERR(reloc_eb);
4391                 reloc_eb = NULL;
4392                 goto free_out;
4393         }
4394         if (!extent_buffer_uptodate(reloc_eb)) {
4395                 ret = -EIO;
4396                 goto free_out;
4397         }
4398
4399         ret = qgroup_trace_subtree_swap(trans, reloc_eb, subvol_eb,
4400                         block->last_snapshot, block->trace_leaf);
4401 free_out:
4402         kfree(block);
4403         free_extent_buffer(reloc_eb);
4404 out:
4405         if (ret < 0) {
4406                 btrfs_err_rl(fs_info,
4407                              "failed to account subtree at bytenr %llu: %d",
4408                              subvol_eb->start, ret);
4409                 qgroup_mark_inconsistent(fs_info);
4410         }
4411         return ret;
4412 }
4413
4414 void btrfs_qgroup_destroy_extent_records(struct btrfs_transaction *trans)
4415 {
4416         struct btrfs_qgroup_extent_record *entry;
4417         struct btrfs_qgroup_extent_record *next;
4418         struct rb_root *root;
4419
4420         root = &trans->delayed_refs.dirty_extent_root;
4421         rbtree_postorder_for_each_entry_safe(entry, next, root, node) {
4422                 ulist_free(entry->old_roots);
4423                 kfree(entry);
4424         }
4425         *root = RB_ROOT;
4426 }