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