btrfs: fix deadlock between quota enable and other quota operations
[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         mutex_lock(&fs_info->qgroup_ioctl_lock);
1189         if (!fs_info->quota_root)
1190                 goto out;
1191         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1192
1193         /*
1194          * 1 For the root item
1195          *
1196          * We should also reserve enough items for the quota tree deletion in
1197          * btrfs_clean_quota_tree but this is not done.
1198          *
1199          * Also, we must always start a transaction without holding the mutex
1200          * qgroup_ioctl_lock, see btrfs_quota_enable().
1201          */
1202         trans = btrfs_start_transaction(fs_info->tree_root, 1);
1203
1204         mutex_lock(&fs_info->qgroup_ioctl_lock);
1205         if (IS_ERR(trans)) {
1206                 ret = PTR_ERR(trans);
1207                 trans = NULL;
1208                 goto out;
1209         }
1210
1211         if (!fs_info->quota_root)
1212                 goto out;
1213
1214         clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1215         btrfs_qgroup_wait_for_completion(fs_info, false);
1216         spin_lock(&fs_info->qgroup_lock);
1217         quota_root = fs_info->quota_root;
1218         fs_info->quota_root = NULL;
1219         fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
1220         spin_unlock(&fs_info->qgroup_lock);
1221
1222         btrfs_free_qgroup_config(fs_info);
1223
1224         ret = btrfs_clean_quota_tree(trans, quota_root);
1225         if (ret) {
1226                 btrfs_abort_transaction(trans, ret);
1227                 goto out;
1228         }
1229
1230         ret = btrfs_del_root(trans, &quota_root->root_key);
1231         if (ret) {
1232                 btrfs_abort_transaction(trans, ret);
1233                 goto out;
1234         }
1235
1236         list_del(&quota_root->dirty_list);
1237
1238         btrfs_tree_lock(quota_root->node);
1239         btrfs_clean_tree_block(quota_root->node);
1240         btrfs_tree_unlock(quota_root->node);
1241         btrfs_free_tree_block(trans, quota_root, quota_root->node, 0, 1);
1242
1243         btrfs_put_root(quota_root);
1244
1245 out:
1246         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1247         if (ret && trans)
1248                 btrfs_end_transaction(trans);
1249         else if (trans)
1250                 ret = btrfs_end_transaction(trans);
1251
1252         return ret;
1253 }
1254
1255 static void qgroup_dirty(struct btrfs_fs_info *fs_info,
1256                          struct btrfs_qgroup *qgroup)
1257 {
1258         if (list_empty(&qgroup->dirty))
1259                 list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1260 }
1261
1262 /*
1263  * The easy accounting, we're updating qgroup relationship whose child qgroup
1264  * only has exclusive extents.
1265  *
1266  * In this case, all exclusive extents will also be exclusive for parent, so
1267  * excl/rfer just get added/removed.
1268  *
1269  * So is qgroup reservation space, which should also be added/removed to
1270  * parent.
1271  * Or when child tries to release reservation space, parent will underflow its
1272  * reservation (for relationship adding case).
1273  *
1274  * Caller should hold fs_info->qgroup_lock.
1275  */
1276 static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
1277                                     struct ulist *tmp, u64 ref_root,
1278                                     struct btrfs_qgroup *src, int sign)
1279 {
1280         struct btrfs_qgroup *qgroup;
1281         struct btrfs_qgroup_list *glist;
1282         struct ulist_node *unode;
1283         struct ulist_iterator uiter;
1284         u64 num_bytes = src->excl;
1285         int ret = 0;
1286
1287         qgroup = find_qgroup_rb(fs_info, ref_root);
1288         if (!qgroup)
1289                 goto out;
1290
1291         qgroup->rfer += sign * num_bytes;
1292         qgroup->rfer_cmpr += sign * num_bytes;
1293
1294         WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1295         qgroup->excl += sign * num_bytes;
1296         qgroup->excl_cmpr += sign * num_bytes;
1297
1298         if (sign > 0)
1299                 qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1300         else
1301                 qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1302
1303         qgroup_dirty(fs_info, qgroup);
1304
1305         /* Get all of the parent groups that contain this qgroup */
1306         list_for_each_entry(glist, &qgroup->groups, next_group) {
1307                 ret = ulist_add(tmp, glist->group->qgroupid,
1308                                 qgroup_to_aux(glist->group), GFP_ATOMIC);
1309                 if (ret < 0)
1310                         goto out;
1311         }
1312
1313         /* Iterate all of the parents and adjust their reference counts */
1314         ULIST_ITER_INIT(&uiter);
1315         while ((unode = ulist_next(tmp, &uiter))) {
1316                 qgroup = unode_aux_to_qgroup(unode);
1317                 qgroup->rfer += sign * num_bytes;
1318                 qgroup->rfer_cmpr += sign * num_bytes;
1319                 WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1320                 qgroup->excl += sign * num_bytes;
1321                 if (sign > 0)
1322                         qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1323                 else
1324                         qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1325                 qgroup->excl_cmpr += sign * num_bytes;
1326                 qgroup_dirty(fs_info, qgroup);
1327
1328                 /* Add any parents of the parents */
1329                 list_for_each_entry(glist, &qgroup->groups, next_group) {
1330                         ret = ulist_add(tmp, glist->group->qgroupid,
1331                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
1332                         if (ret < 0)
1333                                 goto out;
1334                 }
1335         }
1336         ret = 0;
1337 out:
1338         return ret;
1339 }
1340
1341
1342 /*
1343  * Quick path for updating qgroup with only excl refs.
1344  *
1345  * In that case, just update all parent will be enough.
1346  * Or we needs to do a full rescan.
1347  * Caller should also hold fs_info->qgroup_lock.
1348  *
1349  * Return 0 for quick update, return >0 for need to full rescan
1350  * and mark INCONSISTENT flag.
1351  * Return < 0 for other error.
1352  */
1353 static int quick_update_accounting(struct btrfs_fs_info *fs_info,
1354                                    struct ulist *tmp, u64 src, u64 dst,
1355                                    int sign)
1356 {
1357         struct btrfs_qgroup *qgroup;
1358         int ret = 1;
1359         int err = 0;
1360
1361         qgroup = find_qgroup_rb(fs_info, src);
1362         if (!qgroup)
1363                 goto out;
1364         if (qgroup->excl == qgroup->rfer) {
1365                 ret = 0;
1366                 err = __qgroup_excl_accounting(fs_info, tmp, dst,
1367                                                qgroup, sign);
1368                 if (err < 0) {
1369                         ret = err;
1370                         goto out;
1371                 }
1372         }
1373 out:
1374         if (ret)
1375                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1376         return ret;
1377 }
1378
1379 int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1380                               u64 dst)
1381 {
1382         struct btrfs_fs_info *fs_info = trans->fs_info;
1383         struct btrfs_qgroup *parent;
1384         struct btrfs_qgroup *member;
1385         struct btrfs_qgroup_list *list;
1386         struct ulist *tmp;
1387         unsigned int nofs_flag;
1388         int ret = 0;
1389
1390         /* Check the level of src and dst first */
1391         if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
1392                 return -EINVAL;
1393
1394         /* We hold a transaction handle open, must do a NOFS allocation. */
1395         nofs_flag = memalloc_nofs_save();
1396         tmp = ulist_alloc(GFP_KERNEL);
1397         memalloc_nofs_restore(nofs_flag);
1398         if (!tmp)
1399                 return -ENOMEM;
1400
1401         mutex_lock(&fs_info->qgroup_ioctl_lock);
1402         if (!fs_info->quota_root) {
1403                 ret = -ENOTCONN;
1404                 goto out;
1405         }
1406         member = find_qgroup_rb(fs_info, src);
1407         parent = find_qgroup_rb(fs_info, dst);
1408         if (!member || !parent) {
1409                 ret = -EINVAL;
1410                 goto out;
1411         }
1412
1413         /* check if such qgroup relation exist firstly */
1414         list_for_each_entry(list, &member->groups, next_group) {
1415                 if (list->group == parent) {
1416                         ret = -EEXIST;
1417                         goto out;
1418                 }
1419         }
1420
1421         ret = add_qgroup_relation_item(trans, src, dst);
1422         if (ret)
1423                 goto out;
1424
1425         ret = add_qgroup_relation_item(trans, dst, src);
1426         if (ret) {
1427                 del_qgroup_relation_item(trans, src, dst);
1428                 goto out;
1429         }
1430
1431         spin_lock(&fs_info->qgroup_lock);
1432         ret = add_relation_rb(fs_info, src, dst);
1433         if (ret < 0) {
1434                 spin_unlock(&fs_info->qgroup_lock);
1435                 goto out;
1436         }
1437         ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1438         spin_unlock(&fs_info->qgroup_lock);
1439 out:
1440         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1441         ulist_free(tmp);
1442         return ret;
1443 }
1444
1445 static int __del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1446                                  u64 dst)
1447 {
1448         struct btrfs_fs_info *fs_info = trans->fs_info;
1449         struct btrfs_qgroup *parent;
1450         struct btrfs_qgroup *member;
1451         struct btrfs_qgroup_list *list;
1452         struct ulist *tmp;
1453         bool found = false;
1454         unsigned int nofs_flag;
1455         int ret = 0;
1456         int ret2;
1457
1458         /* We hold a transaction handle open, must do a NOFS allocation. */
1459         nofs_flag = memalloc_nofs_save();
1460         tmp = ulist_alloc(GFP_KERNEL);
1461         memalloc_nofs_restore(nofs_flag);
1462         if (!tmp)
1463                 return -ENOMEM;
1464
1465         if (!fs_info->quota_root) {
1466                 ret = -ENOTCONN;
1467                 goto out;
1468         }
1469
1470         member = find_qgroup_rb(fs_info, src);
1471         parent = find_qgroup_rb(fs_info, dst);
1472         /*
1473          * The parent/member pair doesn't exist, then try to delete the dead
1474          * relation items only.
1475          */
1476         if (!member || !parent)
1477                 goto delete_item;
1478
1479         /* check if such qgroup relation exist firstly */
1480         list_for_each_entry(list, &member->groups, next_group) {
1481                 if (list->group == parent) {
1482                         found = true;
1483                         break;
1484                 }
1485         }
1486
1487 delete_item:
1488         ret = del_qgroup_relation_item(trans, src, dst);
1489         if (ret < 0 && ret != -ENOENT)
1490                 goto out;
1491         ret2 = del_qgroup_relation_item(trans, dst, src);
1492         if (ret2 < 0 && ret2 != -ENOENT)
1493                 goto out;
1494
1495         /* At least one deletion succeeded, return 0 */
1496         if (!ret || !ret2)
1497                 ret = 0;
1498
1499         if (found) {
1500                 spin_lock(&fs_info->qgroup_lock);
1501                 del_relation_rb(fs_info, src, dst);
1502                 ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1503                 spin_unlock(&fs_info->qgroup_lock);
1504         }
1505 out:
1506         ulist_free(tmp);
1507         return ret;
1508 }
1509
1510 int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1511                               u64 dst)
1512 {
1513         struct btrfs_fs_info *fs_info = trans->fs_info;
1514         int ret = 0;
1515
1516         mutex_lock(&fs_info->qgroup_ioctl_lock);
1517         ret = __del_qgroup_relation(trans, src, dst);
1518         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1519
1520         return ret;
1521 }
1522
1523 int btrfs_create_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1524 {
1525         struct btrfs_fs_info *fs_info = trans->fs_info;
1526         struct btrfs_root *quota_root;
1527         struct btrfs_qgroup *qgroup;
1528         int ret = 0;
1529
1530         mutex_lock(&fs_info->qgroup_ioctl_lock);
1531         if (!fs_info->quota_root) {
1532                 ret = -ENOTCONN;
1533                 goto out;
1534         }
1535         quota_root = fs_info->quota_root;
1536         qgroup = find_qgroup_rb(fs_info, qgroupid);
1537         if (qgroup) {
1538                 ret = -EEXIST;
1539                 goto out;
1540         }
1541
1542         ret = add_qgroup_item(trans, quota_root, qgroupid);
1543         if (ret)
1544                 goto out;
1545
1546         spin_lock(&fs_info->qgroup_lock);
1547         qgroup = add_qgroup_rb(fs_info, qgroupid);
1548         spin_unlock(&fs_info->qgroup_lock);
1549
1550         if (IS_ERR(qgroup)) {
1551                 ret = PTR_ERR(qgroup);
1552                 goto out;
1553         }
1554         ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1555 out:
1556         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1557         return ret;
1558 }
1559
1560 int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1561 {
1562         struct btrfs_fs_info *fs_info = trans->fs_info;
1563         struct btrfs_qgroup *qgroup;
1564         struct btrfs_qgroup_list *list;
1565         int ret = 0;
1566
1567         mutex_lock(&fs_info->qgroup_ioctl_lock);
1568         if (!fs_info->quota_root) {
1569                 ret = -ENOTCONN;
1570                 goto out;
1571         }
1572
1573         qgroup = find_qgroup_rb(fs_info, qgroupid);
1574         if (!qgroup) {
1575                 ret = -ENOENT;
1576                 goto out;
1577         }
1578
1579         /* Check if there are no children of this qgroup */
1580         if (!list_empty(&qgroup->members)) {
1581                 ret = -EBUSY;
1582                 goto out;
1583         }
1584
1585         ret = del_qgroup_item(trans, qgroupid);
1586         if (ret && ret != -ENOENT)
1587                 goto out;
1588
1589         while (!list_empty(&qgroup->groups)) {
1590                 list = list_first_entry(&qgroup->groups,
1591                                         struct btrfs_qgroup_list, next_group);
1592                 ret = __del_qgroup_relation(trans, qgroupid,
1593                                             list->group->qgroupid);
1594                 if (ret)
1595                         goto out;
1596         }
1597
1598         spin_lock(&fs_info->qgroup_lock);
1599         del_qgroup_rb(fs_info, qgroupid);
1600         spin_unlock(&fs_info->qgroup_lock);
1601
1602         /*
1603          * Remove the qgroup from sysfs now without holding the qgroup_lock
1604          * spinlock, since the sysfs_remove_group() function needs to take
1605          * the mutex kernfs_mutex through kernfs_remove_by_name_ns().
1606          */
1607         btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
1608         kfree(qgroup);
1609 out:
1610         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1611         return ret;
1612 }
1613
1614 int btrfs_limit_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid,
1615                        struct btrfs_qgroup_limit *limit)
1616 {
1617         struct btrfs_fs_info *fs_info = trans->fs_info;
1618         struct btrfs_qgroup *qgroup;
1619         int ret = 0;
1620         /* Sometimes we would want to clear the limit on this qgroup.
1621          * To meet this requirement, we treat the -1 as a special value
1622          * which tell kernel to clear the limit on this qgroup.
1623          */
1624         const u64 CLEAR_VALUE = -1;
1625
1626         mutex_lock(&fs_info->qgroup_ioctl_lock);
1627         if (!fs_info->quota_root) {
1628                 ret = -ENOTCONN;
1629                 goto out;
1630         }
1631
1632         qgroup = find_qgroup_rb(fs_info, qgroupid);
1633         if (!qgroup) {
1634                 ret = -ENOENT;
1635                 goto out;
1636         }
1637
1638         spin_lock(&fs_info->qgroup_lock);
1639         if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
1640                 if (limit->max_rfer == CLEAR_VALUE) {
1641                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1642                         limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1643                         qgroup->max_rfer = 0;
1644                 } else {
1645                         qgroup->max_rfer = limit->max_rfer;
1646                 }
1647         }
1648         if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
1649                 if (limit->max_excl == CLEAR_VALUE) {
1650                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1651                         limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1652                         qgroup->max_excl = 0;
1653                 } else {
1654                         qgroup->max_excl = limit->max_excl;
1655                 }
1656         }
1657         if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
1658                 if (limit->rsv_rfer == CLEAR_VALUE) {
1659                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1660                         limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1661                         qgroup->rsv_rfer = 0;
1662                 } else {
1663                         qgroup->rsv_rfer = limit->rsv_rfer;
1664                 }
1665         }
1666         if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
1667                 if (limit->rsv_excl == CLEAR_VALUE) {
1668                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1669                         limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1670                         qgroup->rsv_excl = 0;
1671                 } else {
1672                         qgroup->rsv_excl = limit->rsv_excl;
1673                 }
1674         }
1675         qgroup->lim_flags |= limit->flags;
1676
1677         spin_unlock(&fs_info->qgroup_lock);
1678
1679         ret = update_qgroup_limit_item(trans, qgroup);
1680         if (ret) {
1681                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1682                 btrfs_info(fs_info, "unable to update quota limit for %llu",
1683                        qgroupid);
1684         }
1685
1686 out:
1687         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1688         return ret;
1689 }
1690
1691 int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1692                                 struct btrfs_delayed_ref_root *delayed_refs,
1693                                 struct btrfs_qgroup_extent_record *record)
1694 {
1695         struct rb_node **p = &delayed_refs->dirty_extent_root.rb_node;
1696         struct rb_node *parent_node = NULL;
1697         struct btrfs_qgroup_extent_record *entry;
1698         u64 bytenr = record->bytenr;
1699
1700         lockdep_assert_held(&delayed_refs->lock);
1701         trace_btrfs_qgroup_trace_extent(fs_info, record);
1702
1703         while (*p) {
1704                 parent_node = *p;
1705                 entry = rb_entry(parent_node, struct btrfs_qgroup_extent_record,
1706                                  node);
1707                 if (bytenr < entry->bytenr) {
1708                         p = &(*p)->rb_left;
1709                 } else if (bytenr > entry->bytenr) {
1710                         p = &(*p)->rb_right;
1711                 } else {
1712                         if (record->data_rsv && !entry->data_rsv) {
1713                                 entry->data_rsv = record->data_rsv;
1714                                 entry->data_rsv_refroot =
1715                                         record->data_rsv_refroot;
1716                         }
1717                         return 1;
1718                 }
1719         }
1720
1721         rb_link_node(&record->node, parent_node, p);
1722         rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1723         return 0;
1724 }
1725
1726 int btrfs_qgroup_trace_extent_post(struct btrfs_trans_handle *trans,
1727                                    struct btrfs_qgroup_extent_record *qrecord)
1728 {
1729         struct ulist *old_root;
1730         u64 bytenr = qrecord->bytenr;
1731         int ret;
1732
1733         /*
1734          * We are always called in a context where we are already holding a
1735          * transaction handle. Often we are called when adding a data delayed
1736          * reference from btrfs_truncate_inode_items() (truncating or unlinking),
1737          * in which case we will be holding a write lock on extent buffer from a
1738          * subvolume tree. In this case we can't allow btrfs_find_all_roots() to
1739          * acquire fs_info->commit_root_sem, because that is a higher level lock
1740          * that must be acquired before locking any extent buffers.
1741          *
1742          * So we want btrfs_find_all_roots() to not acquire the commit_root_sem
1743          * but we can't pass it a non-NULL transaction handle, because otherwise
1744          * it would not use commit roots and would lock extent buffers, causing
1745          * a deadlock if it ends up trying to read lock the same extent buffer
1746          * that was previously write locked at btrfs_truncate_inode_items().
1747          *
1748          * So pass a NULL transaction handle to btrfs_find_all_roots() and
1749          * explicitly tell it to not acquire the commit_root_sem - if we are
1750          * holding a transaction handle we don't need its protection.
1751          */
1752         ASSERT(trans != NULL);
1753
1754         ret = btrfs_find_all_roots(NULL, trans->fs_info, bytenr, 0, &old_root,
1755                                    true);
1756         if (ret < 0) {
1757                 trans->fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1758                 btrfs_warn(trans->fs_info,
1759 "error accounting new delayed refs extent (err code: %d), quota inconsistent",
1760                         ret);
1761                 return 0;
1762         }
1763
1764         /*
1765          * Here we don't need to get the lock of
1766          * trans->transaction->delayed_refs, since inserted qrecord won't
1767          * be deleted, only qrecord->node may be modified (new qrecord insert)
1768          *
1769          * So modifying qrecord->old_roots is safe here
1770          */
1771         qrecord->old_roots = old_root;
1772         return 0;
1773 }
1774
1775 int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans, u64 bytenr,
1776                               u64 num_bytes, gfp_t gfp_flag)
1777 {
1778         struct btrfs_fs_info *fs_info = trans->fs_info;
1779         struct btrfs_qgroup_extent_record *record;
1780         struct btrfs_delayed_ref_root *delayed_refs;
1781         int ret;
1782
1783         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
1784             || bytenr == 0 || num_bytes == 0)
1785                 return 0;
1786         record = kzalloc(sizeof(*record), gfp_flag);
1787         if (!record)
1788                 return -ENOMEM;
1789
1790         delayed_refs = &trans->transaction->delayed_refs;
1791         record->bytenr = bytenr;
1792         record->num_bytes = num_bytes;
1793         record->old_roots = NULL;
1794
1795         spin_lock(&delayed_refs->lock);
1796         ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1797         spin_unlock(&delayed_refs->lock);
1798         if (ret > 0) {
1799                 kfree(record);
1800                 return 0;
1801         }
1802         return btrfs_qgroup_trace_extent_post(trans, record);
1803 }
1804
1805 int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
1806                                   struct extent_buffer *eb)
1807 {
1808         struct btrfs_fs_info *fs_info = trans->fs_info;
1809         int nr = btrfs_header_nritems(eb);
1810         int i, extent_type, ret;
1811         struct btrfs_key key;
1812         struct btrfs_file_extent_item *fi;
1813         u64 bytenr, num_bytes;
1814
1815         /* We can be called directly from walk_up_proc() */
1816         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1817                 return 0;
1818
1819         for (i = 0; i < nr; i++) {
1820                 btrfs_item_key_to_cpu(eb, &key, i);
1821
1822                 if (key.type != BTRFS_EXTENT_DATA_KEY)
1823                         continue;
1824
1825                 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
1826                 /* filter out non qgroup-accountable extents  */
1827                 extent_type = btrfs_file_extent_type(eb, fi);
1828
1829                 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1830                         continue;
1831
1832                 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1833                 if (!bytenr)
1834                         continue;
1835
1836                 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1837
1838                 ret = btrfs_qgroup_trace_extent(trans, bytenr, num_bytes,
1839                                                 GFP_NOFS);
1840                 if (ret)
1841                         return ret;
1842         }
1843         cond_resched();
1844         return 0;
1845 }
1846
1847 /*
1848  * Walk up the tree from the bottom, freeing leaves and any interior
1849  * nodes which have had all slots visited. If a node (leaf or
1850  * interior) is freed, the node above it will have it's slot
1851  * incremented. The root node will never be freed.
1852  *
1853  * At the end of this function, we should have a path which has all
1854  * slots incremented to the next position for a search. If we need to
1855  * read a new node it will be NULL and the node above it will have the
1856  * correct slot selected for a later read.
1857  *
1858  * If we increment the root nodes slot counter past the number of
1859  * elements, 1 is returned to signal completion of the search.
1860  */
1861 static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1862 {
1863         int level = 0;
1864         int nr, slot;
1865         struct extent_buffer *eb;
1866
1867         if (root_level == 0)
1868                 return 1;
1869
1870         while (level <= root_level) {
1871                 eb = path->nodes[level];
1872                 nr = btrfs_header_nritems(eb);
1873                 path->slots[level]++;
1874                 slot = path->slots[level];
1875                 if (slot >= nr || level == 0) {
1876                         /*
1877                          * Don't free the root -  we will detect this
1878                          * condition after our loop and return a
1879                          * positive value for caller to stop walking the tree.
1880                          */
1881                         if (level != root_level) {
1882                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
1883                                 path->locks[level] = 0;
1884
1885                                 free_extent_buffer(eb);
1886                                 path->nodes[level] = NULL;
1887                                 path->slots[level] = 0;
1888                         }
1889                 } else {
1890                         /*
1891                          * We have a valid slot to walk back down
1892                          * from. Stop here so caller can process these
1893                          * new nodes.
1894                          */
1895                         break;
1896                 }
1897
1898                 level++;
1899         }
1900
1901         eb = path->nodes[root_level];
1902         if (path->slots[root_level] >= btrfs_header_nritems(eb))
1903                 return 1;
1904
1905         return 0;
1906 }
1907
1908 /*
1909  * Helper function to trace a subtree tree block swap.
1910  *
1911  * The swap will happen in highest tree block, but there may be a lot of
1912  * tree blocks involved.
1913  *
1914  * For example:
1915  *  OO = Old tree blocks
1916  *  NN = New tree blocks allocated during balance
1917  *
1918  *           File tree (257)                  Reloc tree for 257
1919  * L2              OO                                NN
1920  *               /    \                            /    \
1921  * L1          OO      OO (a)                    OO      NN (a)
1922  *            / \     / \                       / \     / \
1923  * L0       OO   OO OO   OO                   OO   OO NN   NN
1924  *                  (b)  (c)                          (b)  (c)
1925  *
1926  * When calling qgroup_trace_extent_swap(), we will pass:
1927  * @src_eb = OO(a)
1928  * @dst_path = [ nodes[1] = NN(a), nodes[0] = NN(c) ]
1929  * @dst_level = 0
1930  * @root_level = 1
1931  *
1932  * In that case, qgroup_trace_extent_swap() will search from OO(a) to
1933  * reach OO(c), then mark both OO(c) and NN(c) as qgroup dirty.
1934  *
1935  * The main work of qgroup_trace_extent_swap() can be split into 3 parts:
1936  *
1937  * 1) Tree search from @src_eb
1938  *    It should acts as a simplified btrfs_search_slot().
1939  *    The key for search can be extracted from @dst_path->nodes[dst_level]
1940  *    (first key).
1941  *
1942  * 2) Mark the final tree blocks in @src_path and @dst_path qgroup dirty
1943  *    NOTE: In above case, OO(a) and NN(a) won't be marked qgroup dirty.
1944  *    They should be marked during previous (@dst_level = 1) iteration.
1945  *
1946  * 3) Mark file extents in leaves dirty
1947  *    We don't have good way to pick out new file extents only.
1948  *    So we still follow the old method by scanning all file extents in
1949  *    the leave.
1950  *
1951  * This function can free us from keeping two paths, thus later we only need
1952  * to care about how to iterate all new tree blocks in reloc tree.
1953  */
1954 static int qgroup_trace_extent_swap(struct btrfs_trans_handle* trans,
1955                                     struct extent_buffer *src_eb,
1956                                     struct btrfs_path *dst_path,
1957                                     int dst_level, int root_level,
1958                                     bool trace_leaf)
1959 {
1960         struct btrfs_key key;
1961         struct btrfs_path *src_path;
1962         struct btrfs_fs_info *fs_info = trans->fs_info;
1963         u32 nodesize = fs_info->nodesize;
1964         int cur_level = root_level;
1965         int ret;
1966
1967         BUG_ON(dst_level > root_level);
1968         /* Level mismatch */
1969         if (btrfs_header_level(src_eb) != root_level)
1970                 return -EINVAL;
1971
1972         src_path = btrfs_alloc_path();
1973         if (!src_path) {
1974                 ret = -ENOMEM;
1975                 goto out;
1976         }
1977
1978         if (dst_level)
1979                 btrfs_node_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
1980         else
1981                 btrfs_item_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
1982
1983         /* For src_path */
1984         atomic_inc(&src_eb->refs);
1985         src_path->nodes[root_level] = src_eb;
1986         src_path->slots[root_level] = dst_path->slots[root_level];
1987         src_path->locks[root_level] = 0;
1988
1989         /* A simplified version of btrfs_search_slot() */
1990         while (cur_level >= dst_level) {
1991                 struct btrfs_key src_key;
1992                 struct btrfs_key dst_key;
1993
1994                 if (src_path->nodes[cur_level] == NULL) {
1995                         struct extent_buffer *eb;
1996                         int parent_slot;
1997
1998                         eb = src_path->nodes[cur_level + 1];
1999                         parent_slot = src_path->slots[cur_level + 1];
2000
2001                         eb = btrfs_read_node_slot(eb, parent_slot);
2002                         if (IS_ERR(eb)) {
2003                                 ret = PTR_ERR(eb);
2004                                 goto out;
2005                         }
2006
2007                         src_path->nodes[cur_level] = eb;
2008
2009                         btrfs_tree_read_lock(eb);
2010                         src_path->locks[cur_level] = BTRFS_READ_LOCK;
2011                 }
2012
2013                 src_path->slots[cur_level] = dst_path->slots[cur_level];
2014                 if (cur_level) {
2015                         btrfs_node_key_to_cpu(dst_path->nodes[cur_level],
2016                                         &dst_key, dst_path->slots[cur_level]);
2017                         btrfs_node_key_to_cpu(src_path->nodes[cur_level],
2018                                         &src_key, src_path->slots[cur_level]);
2019                 } else {
2020                         btrfs_item_key_to_cpu(dst_path->nodes[cur_level],
2021                                         &dst_key, dst_path->slots[cur_level]);
2022                         btrfs_item_key_to_cpu(src_path->nodes[cur_level],
2023                                         &src_key, src_path->slots[cur_level]);
2024                 }
2025                 /* Content mismatch, something went wrong */
2026                 if (btrfs_comp_cpu_keys(&dst_key, &src_key)) {
2027                         ret = -ENOENT;
2028                         goto out;
2029                 }
2030                 cur_level--;
2031         }
2032
2033         /*
2034          * Now both @dst_path and @src_path have been populated, record the tree
2035          * blocks for qgroup accounting.
2036          */
2037         ret = btrfs_qgroup_trace_extent(trans, src_path->nodes[dst_level]->start,
2038                         nodesize, GFP_NOFS);
2039         if (ret < 0)
2040                 goto out;
2041         ret = btrfs_qgroup_trace_extent(trans,
2042                         dst_path->nodes[dst_level]->start,
2043                         nodesize, GFP_NOFS);
2044         if (ret < 0)
2045                 goto out;
2046
2047         /* Record leaf file extents */
2048         if (dst_level == 0 && trace_leaf) {
2049                 ret = btrfs_qgroup_trace_leaf_items(trans, src_path->nodes[0]);
2050                 if (ret < 0)
2051                         goto out;
2052                 ret = btrfs_qgroup_trace_leaf_items(trans, dst_path->nodes[0]);
2053         }
2054 out:
2055         btrfs_free_path(src_path);
2056         return ret;
2057 }
2058
2059 /*
2060  * Helper function to do recursive generation-aware depth-first search, to
2061  * locate all new tree blocks in a subtree of reloc tree.
2062  *
2063  * E.g. (OO = Old tree blocks, NN = New tree blocks, whose gen == last_snapshot)
2064  *         reloc tree
2065  * L2         NN (a)
2066  *          /    \
2067  * L1    OO        NN (b)
2068  *      /  \      /  \
2069  * L0  OO  OO    OO  NN
2070  *               (c) (d)
2071  * If we pass:
2072  * @dst_path = [ nodes[1] = NN(b), nodes[0] = NULL ],
2073  * @cur_level = 1
2074  * @root_level = 1
2075  *
2076  * We will iterate through tree blocks NN(b), NN(d) and info qgroup to trace
2077  * above tree blocks along with their counter parts in file tree.
2078  * While during search, old tree blocks OO(c) will be skipped as tree block swap
2079  * won't affect OO(c).
2080  */
2081 static int qgroup_trace_new_subtree_blocks(struct btrfs_trans_handle* trans,
2082                                            struct extent_buffer *src_eb,
2083                                            struct btrfs_path *dst_path,
2084                                            int cur_level, int root_level,
2085                                            u64 last_snapshot, bool trace_leaf)
2086 {
2087         struct btrfs_fs_info *fs_info = trans->fs_info;
2088         struct extent_buffer *eb;
2089         bool need_cleanup = false;
2090         int ret = 0;
2091         int i;
2092
2093         /* Level sanity check */
2094         if (cur_level < 0 || cur_level >= BTRFS_MAX_LEVEL - 1 ||
2095             root_level < 0 || root_level >= BTRFS_MAX_LEVEL - 1 ||
2096             root_level < cur_level) {
2097                 btrfs_err_rl(fs_info,
2098                         "%s: bad levels, cur_level=%d root_level=%d",
2099                         __func__, cur_level, root_level);
2100                 return -EUCLEAN;
2101         }
2102
2103         /* Read the tree block if needed */
2104         if (dst_path->nodes[cur_level] == NULL) {
2105                 int parent_slot;
2106                 u64 child_gen;
2107
2108                 /*
2109                  * dst_path->nodes[root_level] must be initialized before
2110                  * calling this function.
2111                  */
2112                 if (cur_level == root_level) {
2113                         btrfs_err_rl(fs_info,
2114         "%s: dst_path->nodes[%d] not initialized, root_level=%d cur_level=%d",
2115                                 __func__, root_level, root_level, cur_level);
2116                         return -EUCLEAN;
2117                 }
2118
2119                 /*
2120                  * We need to get child blockptr/gen from parent before we can
2121                  * read it.
2122                   */
2123                 eb = dst_path->nodes[cur_level + 1];
2124                 parent_slot = dst_path->slots[cur_level + 1];
2125                 child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2126
2127                 /* This node is old, no need to trace */
2128                 if (child_gen < last_snapshot)
2129                         goto out;
2130
2131                 eb = btrfs_read_node_slot(eb, parent_slot);
2132                 if (IS_ERR(eb)) {
2133                         ret = PTR_ERR(eb);
2134                         goto out;
2135                 }
2136
2137                 dst_path->nodes[cur_level] = eb;
2138                 dst_path->slots[cur_level] = 0;
2139
2140                 btrfs_tree_read_lock(eb);
2141                 dst_path->locks[cur_level] = BTRFS_READ_LOCK;
2142                 need_cleanup = true;
2143         }
2144
2145         /* Now record this tree block and its counter part for qgroups */
2146         ret = qgroup_trace_extent_swap(trans, src_eb, dst_path, cur_level,
2147                                        root_level, trace_leaf);
2148         if (ret < 0)
2149                 goto cleanup;
2150
2151         eb = dst_path->nodes[cur_level];
2152
2153         if (cur_level > 0) {
2154                 /* Iterate all child tree blocks */
2155                 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2156                         /* Skip old tree blocks as they won't be swapped */
2157                         if (btrfs_node_ptr_generation(eb, i) < last_snapshot)
2158                                 continue;
2159                         dst_path->slots[cur_level] = i;
2160
2161                         /* Recursive call (at most 7 times) */
2162                         ret = qgroup_trace_new_subtree_blocks(trans, src_eb,
2163                                         dst_path, cur_level - 1, root_level,
2164                                         last_snapshot, trace_leaf);
2165                         if (ret < 0)
2166                                 goto cleanup;
2167                 }
2168         }
2169
2170 cleanup:
2171         if (need_cleanup) {
2172                 /* Clean up */
2173                 btrfs_tree_unlock_rw(dst_path->nodes[cur_level],
2174                                      dst_path->locks[cur_level]);
2175                 free_extent_buffer(dst_path->nodes[cur_level]);
2176                 dst_path->nodes[cur_level] = NULL;
2177                 dst_path->slots[cur_level] = 0;
2178                 dst_path->locks[cur_level] = 0;
2179         }
2180 out:
2181         return ret;
2182 }
2183
2184 static int qgroup_trace_subtree_swap(struct btrfs_trans_handle *trans,
2185                                 struct extent_buffer *src_eb,
2186                                 struct extent_buffer *dst_eb,
2187                                 u64 last_snapshot, bool trace_leaf)
2188 {
2189         struct btrfs_fs_info *fs_info = trans->fs_info;
2190         struct btrfs_path *dst_path = NULL;
2191         int level;
2192         int ret;
2193
2194         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2195                 return 0;
2196
2197         /* Wrong parameter order */
2198         if (btrfs_header_generation(src_eb) > btrfs_header_generation(dst_eb)) {
2199                 btrfs_err_rl(fs_info,
2200                 "%s: bad parameter order, src_gen=%llu dst_gen=%llu", __func__,
2201                              btrfs_header_generation(src_eb),
2202                              btrfs_header_generation(dst_eb));
2203                 return -EUCLEAN;
2204         }
2205
2206         if (!extent_buffer_uptodate(src_eb) || !extent_buffer_uptodate(dst_eb)) {
2207                 ret = -EIO;
2208                 goto out;
2209         }
2210
2211         level = btrfs_header_level(dst_eb);
2212         dst_path = btrfs_alloc_path();
2213         if (!dst_path) {
2214                 ret = -ENOMEM;
2215                 goto out;
2216         }
2217         /* For dst_path */
2218         atomic_inc(&dst_eb->refs);
2219         dst_path->nodes[level] = dst_eb;
2220         dst_path->slots[level] = 0;
2221         dst_path->locks[level] = 0;
2222
2223         /* Do the generation aware breadth-first search */
2224         ret = qgroup_trace_new_subtree_blocks(trans, src_eb, dst_path, level,
2225                                               level, last_snapshot, trace_leaf);
2226         if (ret < 0)
2227                 goto out;
2228         ret = 0;
2229
2230 out:
2231         btrfs_free_path(dst_path);
2232         if (ret < 0)
2233                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2234         return ret;
2235 }
2236
2237 int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
2238                                struct extent_buffer *root_eb,
2239                                u64 root_gen, int root_level)
2240 {
2241         struct btrfs_fs_info *fs_info = trans->fs_info;
2242         int ret = 0;
2243         int level;
2244         struct extent_buffer *eb = root_eb;
2245         struct btrfs_path *path = NULL;
2246
2247         BUG_ON(root_level < 0 || root_level >= BTRFS_MAX_LEVEL);
2248         BUG_ON(root_eb == NULL);
2249
2250         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2251                 return 0;
2252
2253         if (!extent_buffer_uptodate(root_eb)) {
2254                 ret = btrfs_read_buffer(root_eb, root_gen, root_level, NULL);
2255                 if (ret)
2256                         goto out;
2257         }
2258
2259         if (root_level == 0) {
2260                 ret = btrfs_qgroup_trace_leaf_items(trans, root_eb);
2261                 goto out;
2262         }
2263
2264         path = btrfs_alloc_path();
2265         if (!path)
2266                 return -ENOMEM;
2267
2268         /*
2269          * Walk down the tree.  Missing extent blocks are filled in as
2270          * we go. Metadata is accounted every time we read a new
2271          * extent block.
2272          *
2273          * When we reach a leaf, we account for file extent items in it,
2274          * walk back up the tree (adjusting slot pointers as we go)
2275          * and restart the search process.
2276          */
2277         atomic_inc(&root_eb->refs);     /* For path */
2278         path->nodes[root_level] = root_eb;
2279         path->slots[root_level] = 0;
2280         path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
2281 walk_down:
2282         level = root_level;
2283         while (level >= 0) {
2284                 if (path->nodes[level] == NULL) {
2285                         int parent_slot;
2286                         u64 child_bytenr;
2287
2288                         /*
2289                          * We need to get child blockptr from parent before we
2290                          * can read it.
2291                           */
2292                         eb = path->nodes[level + 1];
2293                         parent_slot = path->slots[level + 1];
2294                         child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2295
2296                         eb = btrfs_read_node_slot(eb, parent_slot);
2297                         if (IS_ERR(eb)) {
2298                                 ret = PTR_ERR(eb);
2299                                 goto out;
2300                         }
2301
2302                         path->nodes[level] = eb;
2303                         path->slots[level] = 0;
2304
2305                         btrfs_tree_read_lock(eb);
2306                         path->locks[level] = BTRFS_READ_LOCK;
2307
2308                         ret = btrfs_qgroup_trace_extent(trans, child_bytenr,
2309                                                         fs_info->nodesize,
2310                                                         GFP_NOFS);
2311                         if (ret)
2312                                 goto out;
2313                 }
2314
2315                 if (level == 0) {
2316                         ret = btrfs_qgroup_trace_leaf_items(trans,
2317                                                             path->nodes[level]);
2318                         if (ret)
2319                                 goto out;
2320
2321                         /* Nonzero return here means we completed our search */
2322                         ret = adjust_slots_upwards(path, root_level);
2323                         if (ret)
2324                                 break;
2325
2326                         /* Restart search with new slots */
2327                         goto walk_down;
2328                 }
2329
2330                 level--;
2331         }
2332
2333         ret = 0;
2334 out:
2335         btrfs_free_path(path);
2336
2337         return ret;
2338 }
2339
2340 #define UPDATE_NEW      0
2341 #define UPDATE_OLD      1
2342 /*
2343  * Walk all of the roots that points to the bytenr and adjust their refcnts.
2344  */
2345 static int qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
2346                                 struct ulist *roots, struct ulist *tmp,
2347                                 struct ulist *qgroups, u64 seq, int update_old)
2348 {
2349         struct ulist_node *unode;
2350         struct ulist_iterator uiter;
2351         struct ulist_node *tmp_unode;
2352         struct ulist_iterator tmp_uiter;
2353         struct btrfs_qgroup *qg;
2354         int ret = 0;
2355
2356         if (!roots)
2357                 return 0;
2358         ULIST_ITER_INIT(&uiter);
2359         while ((unode = ulist_next(roots, &uiter))) {
2360                 qg = find_qgroup_rb(fs_info, unode->val);
2361                 if (!qg)
2362                         continue;
2363
2364                 ulist_reinit(tmp);
2365                 ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
2366                                 GFP_ATOMIC);
2367                 if (ret < 0)
2368                         return ret;
2369                 ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
2370                 if (ret < 0)
2371                         return ret;
2372                 ULIST_ITER_INIT(&tmp_uiter);
2373                 while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
2374                         struct btrfs_qgroup_list *glist;
2375
2376                         qg = unode_aux_to_qgroup(tmp_unode);
2377                         if (update_old)
2378                                 btrfs_qgroup_update_old_refcnt(qg, seq, 1);
2379                         else
2380                                 btrfs_qgroup_update_new_refcnt(qg, seq, 1);
2381                         list_for_each_entry(glist, &qg->groups, next_group) {
2382                                 ret = ulist_add(qgroups, glist->group->qgroupid,
2383                                                 qgroup_to_aux(glist->group),
2384                                                 GFP_ATOMIC);
2385                                 if (ret < 0)
2386                                         return ret;
2387                                 ret = ulist_add(tmp, glist->group->qgroupid,
2388                                                 qgroup_to_aux(glist->group),
2389                                                 GFP_ATOMIC);
2390                                 if (ret < 0)
2391                                         return ret;
2392                         }
2393                 }
2394         }
2395         return 0;
2396 }
2397
2398 /*
2399  * Update qgroup rfer/excl counters.
2400  * Rfer update is easy, codes can explain themselves.
2401  *
2402  * Excl update is tricky, the update is split into 2 parts.
2403  * Part 1: Possible exclusive <-> sharing detect:
2404  *      |       A       |       !A      |
2405  *  -------------------------------------
2406  *  B   |       *       |       -       |
2407  *  -------------------------------------
2408  *  !B  |       +       |       **      |
2409  *  -------------------------------------
2410  *
2411  * Conditions:
2412  * A:   cur_old_roots < nr_old_roots    (not exclusive before)
2413  * !A:  cur_old_roots == nr_old_roots   (possible exclusive before)
2414  * B:   cur_new_roots < nr_new_roots    (not exclusive now)
2415  * !B:  cur_new_roots == nr_new_roots   (possible exclusive now)
2416  *
2417  * Results:
2418  * +: Possible sharing -> exclusive     -: Possible exclusive -> sharing
2419  * *: Definitely not changed.           **: Possible unchanged.
2420  *
2421  * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
2422  *
2423  * To make the logic clear, we first use condition A and B to split
2424  * combination into 4 results.
2425  *
2426  * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
2427  * only on variant maybe 0.
2428  *
2429  * Lastly, check result **, since there are 2 variants maybe 0, split them
2430  * again(2x2).
2431  * But this time we don't need to consider other things, the codes and logic
2432  * is easy to understand now.
2433  */
2434 static int qgroup_update_counters(struct btrfs_fs_info *fs_info,
2435                                   struct ulist *qgroups,
2436                                   u64 nr_old_roots,
2437                                   u64 nr_new_roots,
2438                                   u64 num_bytes, u64 seq)
2439 {
2440         struct ulist_node *unode;
2441         struct ulist_iterator uiter;
2442         struct btrfs_qgroup *qg;
2443         u64 cur_new_count, cur_old_count;
2444
2445         ULIST_ITER_INIT(&uiter);
2446         while ((unode = ulist_next(qgroups, &uiter))) {
2447                 bool dirty = false;
2448
2449                 qg = unode_aux_to_qgroup(unode);
2450                 cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
2451                 cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);
2452
2453                 trace_qgroup_update_counters(fs_info, qg, cur_old_count,
2454                                              cur_new_count);
2455
2456                 /* Rfer update part */
2457                 if (cur_old_count == 0 && cur_new_count > 0) {
2458                         qg->rfer += num_bytes;
2459                         qg->rfer_cmpr += num_bytes;
2460                         dirty = true;
2461                 }
2462                 if (cur_old_count > 0 && cur_new_count == 0) {
2463                         qg->rfer -= num_bytes;
2464                         qg->rfer_cmpr -= num_bytes;
2465                         dirty = true;
2466                 }
2467
2468                 /* Excl update part */
2469                 /* Exclusive/none -> shared case */
2470                 if (cur_old_count == nr_old_roots &&
2471                     cur_new_count < nr_new_roots) {
2472                         /* Exclusive -> shared */
2473                         if (cur_old_count != 0) {
2474                                 qg->excl -= num_bytes;
2475                                 qg->excl_cmpr -= num_bytes;
2476                                 dirty = true;
2477                         }
2478                 }
2479
2480                 /* Shared -> exclusive/none case */
2481                 if (cur_old_count < nr_old_roots &&
2482                     cur_new_count == nr_new_roots) {
2483                         /* Shared->exclusive */
2484                         if (cur_new_count != 0) {
2485                                 qg->excl += num_bytes;
2486                                 qg->excl_cmpr += num_bytes;
2487                                 dirty = true;
2488                         }
2489                 }
2490
2491                 /* Exclusive/none -> exclusive/none case */
2492                 if (cur_old_count == nr_old_roots &&
2493                     cur_new_count == nr_new_roots) {
2494                         if (cur_old_count == 0) {
2495                                 /* None -> exclusive/none */
2496
2497                                 if (cur_new_count != 0) {
2498                                         /* None -> exclusive */
2499                                         qg->excl += num_bytes;
2500                                         qg->excl_cmpr += num_bytes;
2501                                         dirty = true;
2502                                 }
2503                                 /* None -> none, nothing changed */
2504                         } else {
2505                                 /* Exclusive -> exclusive/none */
2506
2507                                 if (cur_new_count == 0) {
2508                                         /* Exclusive -> none */
2509                                         qg->excl -= num_bytes;
2510                                         qg->excl_cmpr -= num_bytes;
2511                                         dirty = true;
2512                                 }
2513                                 /* Exclusive -> exclusive, nothing changed */
2514                         }
2515                 }
2516
2517                 if (dirty)
2518                         qgroup_dirty(fs_info, qg);
2519         }
2520         return 0;
2521 }
2522
2523 /*
2524  * Check if the @roots potentially is a list of fs tree roots
2525  *
2526  * Return 0 for definitely not a fs/subvol tree roots ulist
2527  * Return 1 for possible fs/subvol tree roots in the list (considering an empty
2528  *          one as well)
2529  */
2530 static int maybe_fs_roots(struct ulist *roots)
2531 {
2532         struct ulist_node *unode;
2533         struct ulist_iterator uiter;
2534
2535         /* Empty one, still possible for fs roots */
2536         if (!roots || roots->nnodes == 0)
2537                 return 1;
2538
2539         ULIST_ITER_INIT(&uiter);
2540         unode = ulist_next(roots, &uiter);
2541         if (!unode)
2542                 return 1;
2543
2544         /*
2545          * If it contains fs tree roots, then it must belong to fs/subvol
2546          * trees.
2547          * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
2548          */
2549         return is_fstree(unode->val);
2550 }
2551
2552 int btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans, u64 bytenr,
2553                                 u64 num_bytes, struct ulist *old_roots,
2554                                 struct ulist *new_roots)
2555 {
2556         struct btrfs_fs_info *fs_info = trans->fs_info;
2557         struct ulist *qgroups = NULL;
2558         struct ulist *tmp = NULL;
2559         u64 seq;
2560         u64 nr_new_roots = 0;
2561         u64 nr_old_roots = 0;
2562         int ret = 0;
2563
2564         /*
2565          * If quotas get disabled meanwhile, the resources need to be freed and
2566          * we can't just exit here.
2567          */
2568         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2569                 goto out_free;
2570
2571         if (new_roots) {
2572                 if (!maybe_fs_roots(new_roots))
2573                         goto out_free;
2574                 nr_new_roots = new_roots->nnodes;
2575         }
2576         if (old_roots) {
2577                 if (!maybe_fs_roots(old_roots))
2578                         goto out_free;
2579                 nr_old_roots = old_roots->nnodes;
2580         }
2581
2582         /* Quick exit, either not fs tree roots, or won't affect any qgroup */
2583         if (nr_old_roots == 0 && nr_new_roots == 0)
2584                 goto out_free;
2585
2586         BUG_ON(!fs_info->quota_root);
2587
2588         trace_btrfs_qgroup_account_extent(fs_info, trans->transid, bytenr,
2589                                         num_bytes, nr_old_roots, nr_new_roots);
2590
2591         qgroups = ulist_alloc(GFP_NOFS);
2592         if (!qgroups) {
2593                 ret = -ENOMEM;
2594                 goto out_free;
2595         }
2596         tmp = ulist_alloc(GFP_NOFS);
2597         if (!tmp) {
2598                 ret = -ENOMEM;
2599                 goto out_free;
2600         }
2601
2602         mutex_lock(&fs_info->qgroup_rescan_lock);
2603         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
2604                 if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
2605                         mutex_unlock(&fs_info->qgroup_rescan_lock);
2606                         ret = 0;
2607                         goto out_free;
2608                 }
2609         }
2610         mutex_unlock(&fs_info->qgroup_rescan_lock);
2611
2612         spin_lock(&fs_info->qgroup_lock);
2613         seq = fs_info->qgroup_seq;
2614
2615         /* Update old refcnts using old_roots */
2616         ret = qgroup_update_refcnt(fs_info, old_roots, tmp, qgroups, seq,
2617                                    UPDATE_OLD);
2618         if (ret < 0)
2619                 goto out;
2620
2621         /* Update new refcnts using new_roots */
2622         ret = qgroup_update_refcnt(fs_info, new_roots, tmp, qgroups, seq,
2623                                    UPDATE_NEW);
2624         if (ret < 0)
2625                 goto out;
2626
2627         qgroup_update_counters(fs_info, qgroups, nr_old_roots, nr_new_roots,
2628                                num_bytes, seq);
2629
2630         /*
2631          * Bump qgroup_seq to avoid seq overlap
2632          */
2633         fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
2634 out:
2635         spin_unlock(&fs_info->qgroup_lock);
2636 out_free:
2637         ulist_free(tmp);
2638         ulist_free(qgroups);
2639         ulist_free(old_roots);
2640         ulist_free(new_roots);
2641         return ret;
2642 }
2643
2644 int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans)
2645 {
2646         struct btrfs_fs_info *fs_info = trans->fs_info;
2647         struct btrfs_qgroup_extent_record *record;
2648         struct btrfs_delayed_ref_root *delayed_refs;
2649         struct ulist *new_roots = NULL;
2650         struct rb_node *node;
2651         u64 num_dirty_extents = 0;
2652         u64 qgroup_to_skip;
2653         int ret = 0;
2654
2655         delayed_refs = &trans->transaction->delayed_refs;
2656         qgroup_to_skip = delayed_refs->qgroup_to_skip;
2657         while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
2658                 record = rb_entry(node, struct btrfs_qgroup_extent_record,
2659                                   node);
2660
2661                 num_dirty_extents++;
2662                 trace_btrfs_qgroup_account_extents(fs_info, record);
2663
2664                 if (!ret) {
2665                         /*
2666                          * Old roots should be searched when inserting qgroup
2667                          * extent record
2668                          */
2669                         if (WARN_ON(!record->old_roots)) {
2670                                 /* Search commit root to find old_roots */
2671                                 ret = btrfs_find_all_roots(NULL, fs_info,
2672                                                 record->bytenr, 0,
2673                                                 &record->old_roots, false);
2674                                 if (ret < 0)
2675                                         goto cleanup;
2676                         }
2677
2678                         /* Free the reserved data space */
2679                         btrfs_qgroup_free_refroot(fs_info,
2680                                         record->data_rsv_refroot,
2681                                         record->data_rsv,
2682                                         BTRFS_QGROUP_RSV_DATA);
2683                         /*
2684                          * Use BTRFS_SEQ_LAST as time_seq to do special search,
2685                          * which doesn't lock tree or delayed_refs and search
2686                          * current root. It's safe inside commit_transaction().
2687                          */
2688                         ret = btrfs_find_all_roots(trans, fs_info,
2689                            record->bytenr, BTRFS_SEQ_LAST, &new_roots, false);
2690                         if (ret < 0)
2691                                 goto cleanup;
2692                         if (qgroup_to_skip) {
2693                                 ulist_del(new_roots, qgroup_to_skip, 0);
2694                                 ulist_del(record->old_roots, qgroup_to_skip,
2695                                           0);
2696                         }
2697                         ret = btrfs_qgroup_account_extent(trans, record->bytenr,
2698                                                           record->num_bytes,
2699                                                           record->old_roots,
2700                                                           new_roots);
2701                         record->old_roots = NULL;
2702                         new_roots = NULL;
2703                 }
2704 cleanup:
2705                 ulist_free(record->old_roots);
2706                 ulist_free(new_roots);
2707                 new_roots = NULL;
2708                 rb_erase(node, &delayed_refs->dirty_extent_root);
2709                 kfree(record);
2710
2711         }
2712         trace_qgroup_num_dirty_extents(fs_info, trans->transid,
2713                                        num_dirty_extents);
2714         return ret;
2715 }
2716
2717 /*
2718  * called from commit_transaction. Writes all changed qgroups to disk.
2719  */
2720 int btrfs_run_qgroups(struct btrfs_trans_handle *trans)
2721 {
2722         struct btrfs_fs_info *fs_info = trans->fs_info;
2723         int ret = 0;
2724
2725         if (!fs_info->quota_root)
2726                 return ret;
2727
2728         spin_lock(&fs_info->qgroup_lock);
2729         while (!list_empty(&fs_info->dirty_qgroups)) {
2730                 struct btrfs_qgroup *qgroup;
2731                 qgroup = list_first_entry(&fs_info->dirty_qgroups,
2732                                           struct btrfs_qgroup, dirty);
2733                 list_del_init(&qgroup->dirty);
2734                 spin_unlock(&fs_info->qgroup_lock);
2735                 ret = update_qgroup_info_item(trans, qgroup);
2736                 if (ret)
2737                         fs_info->qgroup_flags |=
2738                                         BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2739                 ret = update_qgroup_limit_item(trans, qgroup);
2740                 if (ret)
2741                         fs_info->qgroup_flags |=
2742                                         BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2743                 spin_lock(&fs_info->qgroup_lock);
2744         }
2745         if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2746                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_ON;
2747         else
2748                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
2749         spin_unlock(&fs_info->qgroup_lock);
2750
2751         ret = update_qgroup_status_item(trans);
2752         if (ret)
2753                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2754
2755         return ret;
2756 }
2757
2758 /*
2759  * Copy the accounting information between qgroups. This is necessary
2760  * when a snapshot or a subvolume is created. Throwing an error will
2761  * cause a transaction abort so we take extra care here to only error
2762  * when a readonly fs is a reasonable outcome.
2763  */
2764 int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans, u64 srcid,
2765                          u64 objectid, struct btrfs_qgroup_inherit *inherit)
2766 {
2767         int ret = 0;
2768         int i;
2769         u64 *i_qgroups;
2770         bool committing = false;
2771         struct btrfs_fs_info *fs_info = trans->fs_info;
2772         struct btrfs_root *quota_root;
2773         struct btrfs_qgroup *srcgroup;
2774         struct btrfs_qgroup *dstgroup;
2775         bool need_rescan = false;
2776         u32 level_size = 0;
2777         u64 nums;
2778
2779         /*
2780          * There are only two callers of this function.
2781          *
2782          * One in create_subvol() in the ioctl context, which needs to hold
2783          * the qgroup_ioctl_lock.
2784          *
2785          * The other one in create_pending_snapshot() where no other qgroup
2786          * code can modify the fs as they all need to either start a new trans
2787          * or hold a trans handler, thus we don't need to hold
2788          * qgroup_ioctl_lock.
2789          * This would avoid long and complex lock chain and make lockdep happy.
2790          */
2791         spin_lock(&fs_info->trans_lock);
2792         if (trans->transaction->state == TRANS_STATE_COMMIT_DOING)
2793                 committing = true;
2794         spin_unlock(&fs_info->trans_lock);
2795
2796         if (!committing)
2797                 mutex_lock(&fs_info->qgroup_ioctl_lock);
2798         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2799                 goto out;
2800
2801         quota_root = fs_info->quota_root;
2802         if (!quota_root) {
2803                 ret = -EINVAL;
2804                 goto out;
2805         }
2806
2807         if (inherit) {
2808                 i_qgroups = (u64 *)(inherit + 1);
2809                 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
2810                        2 * inherit->num_excl_copies;
2811                 for (i = 0; i < nums; ++i) {
2812                         srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
2813
2814                         /*
2815                          * Zero out invalid groups so we can ignore
2816                          * them later.
2817                          */
2818                         if (!srcgroup ||
2819                             ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
2820                                 *i_qgroups = 0ULL;
2821
2822                         ++i_qgroups;
2823                 }
2824         }
2825
2826         /*
2827          * create a tracking group for the subvol itself
2828          */
2829         ret = add_qgroup_item(trans, quota_root, objectid);
2830         if (ret)
2831                 goto out;
2832
2833         /*
2834          * add qgroup to all inherited groups
2835          */
2836         if (inherit) {
2837                 i_qgroups = (u64 *)(inherit + 1);
2838                 for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
2839                         if (*i_qgroups == 0)
2840                                 continue;
2841                         ret = add_qgroup_relation_item(trans, objectid,
2842                                                        *i_qgroups);
2843                         if (ret && ret != -EEXIST)
2844                                 goto out;
2845                         ret = add_qgroup_relation_item(trans, *i_qgroups,
2846                                                        objectid);
2847                         if (ret && ret != -EEXIST)
2848                                 goto out;
2849                 }
2850                 ret = 0;
2851         }
2852
2853
2854         spin_lock(&fs_info->qgroup_lock);
2855
2856         dstgroup = add_qgroup_rb(fs_info, objectid);
2857         if (IS_ERR(dstgroup)) {
2858                 ret = PTR_ERR(dstgroup);
2859                 goto unlock;
2860         }
2861
2862         if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
2863                 dstgroup->lim_flags = inherit->lim.flags;
2864                 dstgroup->max_rfer = inherit->lim.max_rfer;
2865                 dstgroup->max_excl = inherit->lim.max_excl;
2866                 dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
2867                 dstgroup->rsv_excl = inherit->lim.rsv_excl;
2868
2869                 ret = update_qgroup_limit_item(trans, dstgroup);
2870                 if (ret) {
2871                         fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2872                         btrfs_info(fs_info,
2873                                    "unable to update quota limit for %llu",
2874                                    dstgroup->qgroupid);
2875                         goto unlock;
2876                 }
2877         }
2878
2879         if (srcid) {
2880                 srcgroup = find_qgroup_rb(fs_info, srcid);
2881                 if (!srcgroup)
2882                         goto unlock;
2883
2884                 /*
2885                  * We call inherit after we clone the root in order to make sure
2886                  * our counts don't go crazy, so at this point the only
2887                  * difference between the two roots should be the root node.
2888                  */
2889                 level_size = fs_info->nodesize;
2890                 dstgroup->rfer = srcgroup->rfer;
2891                 dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
2892                 dstgroup->excl = level_size;
2893                 dstgroup->excl_cmpr = level_size;
2894                 srcgroup->excl = level_size;
2895                 srcgroup->excl_cmpr = level_size;
2896
2897                 /* inherit the limit info */
2898                 dstgroup->lim_flags = srcgroup->lim_flags;
2899                 dstgroup->max_rfer = srcgroup->max_rfer;
2900                 dstgroup->max_excl = srcgroup->max_excl;
2901                 dstgroup->rsv_rfer = srcgroup->rsv_rfer;
2902                 dstgroup->rsv_excl = srcgroup->rsv_excl;
2903
2904                 qgroup_dirty(fs_info, dstgroup);
2905                 qgroup_dirty(fs_info, srcgroup);
2906         }
2907
2908         if (!inherit)
2909                 goto unlock;
2910
2911         i_qgroups = (u64 *)(inherit + 1);
2912         for (i = 0; i < inherit->num_qgroups; ++i) {
2913                 if (*i_qgroups) {
2914                         ret = add_relation_rb(fs_info, objectid, *i_qgroups);
2915                         if (ret)
2916                                 goto unlock;
2917                 }
2918                 ++i_qgroups;
2919
2920                 /*
2921                  * If we're doing a snapshot, and adding the snapshot to a new
2922                  * qgroup, the numbers are guaranteed to be incorrect.
2923                  */
2924                 if (srcid)
2925                         need_rescan = true;
2926         }
2927
2928         for (i = 0; i <  inherit->num_ref_copies; ++i, i_qgroups += 2) {
2929                 struct btrfs_qgroup *src;
2930                 struct btrfs_qgroup *dst;
2931
2932                 if (!i_qgroups[0] || !i_qgroups[1])
2933                         continue;
2934
2935                 src = find_qgroup_rb(fs_info, i_qgroups[0]);
2936                 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
2937
2938                 if (!src || !dst) {
2939                         ret = -EINVAL;
2940                         goto unlock;
2941                 }
2942
2943                 dst->rfer = src->rfer - level_size;
2944                 dst->rfer_cmpr = src->rfer_cmpr - level_size;
2945
2946                 /* Manually tweaking numbers certainly needs a rescan */
2947                 need_rescan = true;
2948         }
2949         for (i = 0; i <  inherit->num_excl_copies; ++i, i_qgroups += 2) {
2950                 struct btrfs_qgroup *src;
2951                 struct btrfs_qgroup *dst;
2952
2953                 if (!i_qgroups[0] || !i_qgroups[1])
2954                         continue;
2955
2956                 src = find_qgroup_rb(fs_info, i_qgroups[0]);
2957                 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
2958
2959                 if (!src || !dst) {
2960                         ret = -EINVAL;
2961                         goto unlock;
2962                 }
2963
2964                 dst->excl = src->excl + level_size;
2965                 dst->excl_cmpr = src->excl_cmpr + level_size;
2966                 need_rescan = true;
2967         }
2968
2969 unlock:
2970         spin_unlock(&fs_info->qgroup_lock);
2971         if (!ret)
2972                 ret = btrfs_sysfs_add_one_qgroup(fs_info, dstgroup);
2973 out:
2974         if (!committing)
2975                 mutex_unlock(&fs_info->qgroup_ioctl_lock);
2976         if (need_rescan)
2977                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2978         return ret;
2979 }
2980
2981 static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
2982 {
2983         if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
2984             qgroup_rsv_total(qg) + (s64)qg->rfer + num_bytes > qg->max_rfer)
2985                 return false;
2986
2987         if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
2988             qgroup_rsv_total(qg) + (s64)qg->excl + num_bytes > qg->max_excl)
2989                 return false;
2990
2991         return true;
2992 }
2993
2994 static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce,
2995                           enum btrfs_qgroup_rsv_type type)
2996 {
2997         struct btrfs_qgroup *qgroup;
2998         struct btrfs_fs_info *fs_info = root->fs_info;
2999         u64 ref_root = root->root_key.objectid;
3000         int ret = 0;
3001         struct ulist_node *unode;
3002         struct ulist_iterator uiter;
3003
3004         if (!is_fstree(ref_root))
3005                 return 0;
3006
3007         if (num_bytes == 0)
3008                 return 0;
3009
3010         if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
3011             capable(CAP_SYS_RESOURCE))
3012                 enforce = false;
3013
3014         spin_lock(&fs_info->qgroup_lock);
3015         if (!fs_info->quota_root)
3016                 goto out;
3017
3018         qgroup = find_qgroup_rb(fs_info, ref_root);
3019         if (!qgroup)
3020                 goto out;
3021
3022         /*
3023          * in a first step, we check all affected qgroups if any limits would
3024          * be exceeded
3025          */
3026         ulist_reinit(fs_info->qgroup_ulist);
3027         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3028                         qgroup_to_aux(qgroup), GFP_ATOMIC);
3029         if (ret < 0)
3030                 goto out;
3031         ULIST_ITER_INIT(&uiter);
3032         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3033                 struct btrfs_qgroup *qg;
3034                 struct btrfs_qgroup_list *glist;
3035
3036                 qg = unode_aux_to_qgroup(unode);
3037
3038                 if (enforce && !qgroup_check_limits(qg, num_bytes)) {
3039                         ret = -EDQUOT;
3040                         goto out;
3041                 }
3042
3043                 list_for_each_entry(glist, &qg->groups, next_group) {
3044                         ret = ulist_add(fs_info->qgroup_ulist,
3045                                         glist->group->qgroupid,
3046                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
3047                         if (ret < 0)
3048                                 goto out;
3049                 }
3050         }
3051         ret = 0;
3052         /*
3053          * no limits exceeded, now record the reservation into all qgroups
3054          */
3055         ULIST_ITER_INIT(&uiter);
3056         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3057                 struct btrfs_qgroup *qg;
3058
3059                 qg = unode_aux_to_qgroup(unode);
3060
3061                 qgroup_rsv_add(fs_info, qg, num_bytes, type);
3062         }
3063
3064 out:
3065         spin_unlock(&fs_info->qgroup_lock);
3066         return ret;
3067 }
3068
3069 /*
3070  * Free @num_bytes of reserved space with @type for qgroup.  (Normally level 0
3071  * qgroup).
3072  *
3073  * Will handle all higher level qgroup too.
3074  *
3075  * NOTE: If @num_bytes is (u64)-1, this means to free all bytes of this qgroup.
3076  * This special case is only used for META_PERTRANS type.
3077  */
3078 void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
3079                                u64 ref_root, u64 num_bytes,
3080                                enum btrfs_qgroup_rsv_type type)
3081 {
3082         struct btrfs_qgroup *qgroup;
3083         struct ulist_node *unode;
3084         struct ulist_iterator uiter;
3085         int ret = 0;
3086
3087         if (!is_fstree(ref_root))
3088                 return;
3089
3090         if (num_bytes == 0)
3091                 return;
3092
3093         if (num_bytes == (u64)-1 && type != BTRFS_QGROUP_RSV_META_PERTRANS) {
3094                 WARN(1, "%s: Invalid type to free", __func__);
3095                 return;
3096         }
3097         spin_lock(&fs_info->qgroup_lock);
3098
3099         if (!fs_info->quota_root)
3100                 goto out;
3101
3102         qgroup = find_qgroup_rb(fs_info, ref_root);
3103         if (!qgroup)
3104                 goto out;
3105
3106         if (num_bytes == (u64)-1)
3107                 /*
3108                  * We're freeing all pertrans rsv, get reserved value from
3109                  * level 0 qgroup as real num_bytes to free.
3110                  */
3111                 num_bytes = qgroup->rsv.values[type];
3112
3113         ulist_reinit(fs_info->qgroup_ulist);
3114         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3115                         qgroup_to_aux(qgroup), GFP_ATOMIC);
3116         if (ret < 0)
3117                 goto out;
3118         ULIST_ITER_INIT(&uiter);
3119         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3120                 struct btrfs_qgroup *qg;
3121                 struct btrfs_qgroup_list *glist;
3122
3123                 qg = unode_aux_to_qgroup(unode);
3124
3125                 qgroup_rsv_release(fs_info, qg, num_bytes, type);
3126
3127                 list_for_each_entry(glist, &qg->groups, next_group) {
3128                         ret = ulist_add(fs_info->qgroup_ulist,
3129                                         glist->group->qgroupid,
3130                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
3131                         if (ret < 0)
3132                                 goto out;
3133                 }
3134         }
3135
3136 out:
3137         spin_unlock(&fs_info->qgroup_lock);
3138 }
3139
3140 /*
3141  * Check if the leaf is the last leaf. Which means all node pointers
3142  * are at their last position.
3143  */
3144 static bool is_last_leaf(struct btrfs_path *path)
3145 {
3146         int i;
3147
3148         for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
3149                 if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
3150                         return false;
3151         }
3152         return true;
3153 }
3154
3155 /*
3156  * returns < 0 on error, 0 when more leafs are to be scanned.
3157  * returns 1 when done.
3158  */
3159 static int qgroup_rescan_leaf(struct btrfs_trans_handle *trans,
3160                               struct btrfs_path *path)
3161 {
3162         struct btrfs_fs_info *fs_info = trans->fs_info;
3163         struct btrfs_key found;
3164         struct extent_buffer *scratch_leaf = NULL;
3165         struct ulist *roots = NULL;
3166         u64 num_bytes;
3167         bool done;
3168         int slot;
3169         int ret;
3170
3171         mutex_lock(&fs_info->qgroup_rescan_lock);
3172         ret = btrfs_search_slot_for_read(fs_info->extent_root,
3173                                          &fs_info->qgroup_rescan_progress,
3174                                          path, 1, 0);
3175
3176         btrfs_debug(fs_info,
3177                 "current progress key (%llu %u %llu), search_slot ret %d",
3178                 fs_info->qgroup_rescan_progress.objectid,
3179                 fs_info->qgroup_rescan_progress.type,
3180                 fs_info->qgroup_rescan_progress.offset, ret);
3181
3182         if (ret) {
3183                 /*
3184                  * The rescan is about to end, we will not be scanning any
3185                  * further blocks. We cannot unset the RESCAN flag here, because
3186                  * we want to commit the transaction if everything went well.
3187                  * To make the live accounting work in this phase, we set our
3188                  * scan progress pointer such that every real extent objectid
3189                  * will be smaller.
3190                  */
3191                 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3192                 btrfs_release_path(path);
3193                 mutex_unlock(&fs_info->qgroup_rescan_lock);
3194                 return ret;
3195         }
3196         done = is_last_leaf(path);
3197
3198         btrfs_item_key_to_cpu(path->nodes[0], &found,
3199                               btrfs_header_nritems(path->nodes[0]) - 1);
3200         fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;
3201
3202         scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
3203         if (!scratch_leaf) {
3204                 ret = -ENOMEM;
3205                 mutex_unlock(&fs_info->qgroup_rescan_lock);
3206                 goto out;
3207         }
3208         slot = path->slots[0];
3209         btrfs_release_path(path);
3210         mutex_unlock(&fs_info->qgroup_rescan_lock);
3211
3212         for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
3213                 btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
3214                 if (found.type != BTRFS_EXTENT_ITEM_KEY &&
3215                     found.type != BTRFS_METADATA_ITEM_KEY)
3216                         continue;
3217                 if (found.type == BTRFS_METADATA_ITEM_KEY)
3218                         num_bytes = fs_info->nodesize;
3219                 else
3220                         num_bytes = found.offset;
3221
3222                 ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
3223                                            &roots, false);
3224                 if (ret < 0)
3225                         goto out;
3226                 /* For rescan, just pass old_roots as NULL */
3227                 ret = btrfs_qgroup_account_extent(trans, found.objectid,
3228                                                   num_bytes, NULL, roots);
3229                 if (ret < 0)
3230                         goto out;
3231         }
3232 out:
3233         if (scratch_leaf)
3234                 free_extent_buffer(scratch_leaf);
3235
3236         if (done && !ret) {
3237                 ret = 1;
3238                 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3239         }
3240         return ret;
3241 }
3242
3243 static bool rescan_should_stop(struct btrfs_fs_info *fs_info)
3244 {
3245         return btrfs_fs_closing(fs_info) ||
3246                 test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
3247 }
3248
3249 static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
3250 {
3251         struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
3252                                                      qgroup_rescan_work);
3253         struct btrfs_path *path;
3254         struct btrfs_trans_handle *trans = NULL;
3255         int err = -ENOMEM;
3256         int ret = 0;
3257         bool stopped = false;
3258
3259         path = btrfs_alloc_path();
3260         if (!path)
3261                 goto out;
3262         /*
3263          * Rescan should only search for commit root, and any later difference
3264          * should be recorded by qgroup
3265          */
3266         path->search_commit_root = 1;
3267         path->skip_locking = 1;
3268
3269         err = 0;
3270         while (!err && !(stopped = rescan_should_stop(fs_info))) {
3271                 trans = btrfs_start_transaction(fs_info->fs_root, 0);
3272                 if (IS_ERR(trans)) {
3273                         err = PTR_ERR(trans);
3274                         break;
3275                 }
3276                 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
3277                         err = -EINTR;
3278                 } else {
3279                         err = qgroup_rescan_leaf(trans, path);
3280                 }
3281                 if (err > 0)
3282                         btrfs_commit_transaction(trans);
3283                 else
3284                         btrfs_end_transaction(trans);
3285         }
3286
3287 out:
3288         btrfs_free_path(path);
3289
3290         mutex_lock(&fs_info->qgroup_rescan_lock);
3291         if (err > 0 &&
3292             fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT) {
3293                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3294         } else if (err < 0) {
3295                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3296         }
3297         mutex_unlock(&fs_info->qgroup_rescan_lock);
3298
3299         /*
3300          * only update status, since the previous part has already updated the
3301          * qgroup info.
3302          */
3303         trans = btrfs_start_transaction(fs_info->quota_root, 1);
3304         if (IS_ERR(trans)) {
3305                 err = PTR_ERR(trans);
3306                 trans = NULL;
3307                 btrfs_err(fs_info,
3308                           "fail to start transaction for status update: %d",
3309                           err);
3310         }
3311
3312         mutex_lock(&fs_info->qgroup_rescan_lock);
3313         if (!stopped)
3314                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3315         if (trans) {
3316                 ret = update_qgroup_status_item(trans);
3317                 if (ret < 0) {
3318                         err = ret;
3319                         btrfs_err(fs_info, "fail to update qgroup status: %d",
3320                                   err);
3321                 }
3322         }
3323         fs_info->qgroup_rescan_running = false;
3324         complete_all(&fs_info->qgroup_rescan_completion);
3325         mutex_unlock(&fs_info->qgroup_rescan_lock);
3326
3327         if (!trans)
3328                 return;
3329
3330         btrfs_end_transaction(trans);
3331
3332         if (stopped) {
3333                 btrfs_info(fs_info, "qgroup scan paused");
3334         } else if (err >= 0) {
3335                 btrfs_info(fs_info, "qgroup scan completed%s",
3336                         err > 0 ? " (inconsistency flag cleared)" : "");
3337         } else {
3338                 btrfs_err(fs_info, "qgroup scan failed with %d", err);
3339         }
3340 }
3341
3342 /*
3343  * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
3344  * memory required for the rescan context.
3345  */
3346 static int
3347 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
3348                    int init_flags)
3349 {
3350         int ret = 0;
3351
3352         if (!init_flags) {
3353                 /* we're resuming qgroup rescan at mount time */
3354                 if (!(fs_info->qgroup_flags &
3355                       BTRFS_QGROUP_STATUS_FLAG_RESCAN)) {
3356                         btrfs_warn(fs_info,
3357                         "qgroup rescan init failed, qgroup rescan is not queued");
3358                         ret = -EINVAL;
3359                 } else if (!(fs_info->qgroup_flags &
3360                              BTRFS_QGROUP_STATUS_FLAG_ON)) {
3361                         btrfs_warn(fs_info,
3362                         "qgroup rescan init failed, qgroup is not enabled");
3363                         ret = -EINVAL;
3364                 }
3365
3366                 if (ret)
3367                         return ret;
3368         }
3369
3370         mutex_lock(&fs_info->qgroup_rescan_lock);
3371
3372         if (init_flags) {
3373                 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3374                         btrfs_warn(fs_info,
3375                                    "qgroup rescan is already in progress");
3376                         ret = -EINPROGRESS;
3377                 } else if (!(fs_info->qgroup_flags &
3378                              BTRFS_QGROUP_STATUS_FLAG_ON)) {
3379                         btrfs_warn(fs_info,
3380                         "qgroup rescan init failed, qgroup is not enabled");
3381                         ret = -EINVAL;
3382                 }
3383
3384                 if (ret) {
3385                         mutex_unlock(&fs_info->qgroup_rescan_lock);
3386                         return ret;
3387                 }
3388                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3389         }
3390
3391         memset(&fs_info->qgroup_rescan_progress, 0,
3392                 sizeof(fs_info->qgroup_rescan_progress));
3393         fs_info->qgroup_rescan_progress.objectid = progress_objectid;
3394         init_completion(&fs_info->qgroup_rescan_completion);
3395         mutex_unlock(&fs_info->qgroup_rescan_lock);
3396
3397         btrfs_init_work(&fs_info->qgroup_rescan_work,
3398                         btrfs_qgroup_rescan_worker, NULL, NULL);
3399         return 0;
3400 }
3401
3402 static void
3403 qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
3404 {
3405         struct rb_node *n;
3406         struct btrfs_qgroup *qgroup;
3407
3408         spin_lock(&fs_info->qgroup_lock);
3409         /* clear all current qgroup tracking information */
3410         for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
3411                 qgroup = rb_entry(n, struct btrfs_qgroup, node);
3412                 qgroup->rfer = 0;
3413                 qgroup->rfer_cmpr = 0;
3414                 qgroup->excl = 0;
3415                 qgroup->excl_cmpr = 0;
3416                 qgroup_dirty(fs_info, qgroup);
3417         }
3418         spin_unlock(&fs_info->qgroup_lock);
3419 }
3420
3421 int
3422 btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
3423 {
3424         int ret = 0;
3425         struct btrfs_trans_handle *trans;
3426
3427         ret = qgroup_rescan_init(fs_info, 0, 1);
3428         if (ret)
3429                 return ret;
3430
3431         /*
3432          * We have set the rescan_progress to 0, which means no more
3433          * delayed refs will be accounted by btrfs_qgroup_account_ref.
3434          * However, btrfs_qgroup_account_ref may be right after its call
3435          * to btrfs_find_all_roots, in which case it would still do the
3436          * accounting.
3437          * To solve this, we're committing the transaction, which will
3438          * ensure we run all delayed refs and only after that, we are
3439          * going to clear all tracking information for a clean start.
3440          */
3441
3442         trans = btrfs_join_transaction(fs_info->fs_root);
3443         if (IS_ERR(trans)) {
3444                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3445                 return PTR_ERR(trans);
3446         }
3447         ret = btrfs_commit_transaction(trans);
3448         if (ret) {
3449                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3450                 return ret;
3451         }
3452
3453         qgroup_rescan_zero_tracking(fs_info);
3454
3455         mutex_lock(&fs_info->qgroup_rescan_lock);
3456         fs_info->qgroup_rescan_running = true;
3457         btrfs_queue_work(fs_info->qgroup_rescan_workers,
3458                          &fs_info->qgroup_rescan_work);
3459         mutex_unlock(&fs_info->qgroup_rescan_lock);
3460
3461         return 0;
3462 }
3463
3464 int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
3465                                      bool interruptible)
3466 {
3467         int running;
3468         int ret = 0;
3469
3470         mutex_lock(&fs_info->qgroup_rescan_lock);
3471         running = fs_info->qgroup_rescan_running;
3472         mutex_unlock(&fs_info->qgroup_rescan_lock);
3473
3474         if (!running)
3475                 return 0;
3476
3477         if (interruptible)
3478                 ret = wait_for_completion_interruptible(
3479                                         &fs_info->qgroup_rescan_completion);
3480         else
3481                 wait_for_completion(&fs_info->qgroup_rescan_completion);
3482
3483         return ret;
3484 }
3485
3486 /*
3487  * this is only called from open_ctree where we're still single threaded, thus
3488  * locking is omitted here.
3489  */
3490 void
3491 btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
3492 {
3493         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3494                 mutex_lock(&fs_info->qgroup_rescan_lock);
3495                 fs_info->qgroup_rescan_running = true;
3496                 btrfs_queue_work(fs_info->qgroup_rescan_workers,
3497                                  &fs_info->qgroup_rescan_work);
3498                 mutex_unlock(&fs_info->qgroup_rescan_lock);
3499         }
3500 }
3501
3502 #define rbtree_iterate_from_safe(node, next, start)                             \
3503        for (node = start; node && ({ next = rb_next(node); 1;}); node = next)
3504
3505 static int qgroup_unreserve_range(struct btrfs_inode *inode,
3506                                   struct extent_changeset *reserved, u64 start,
3507                                   u64 len)
3508 {
3509         struct rb_node *node;
3510         struct rb_node *next;
3511         struct ulist_node *entry;
3512         int ret = 0;
3513
3514         node = reserved->range_changed.root.rb_node;
3515         if (!node)
3516                 return 0;
3517         while (node) {
3518                 entry = rb_entry(node, struct ulist_node, rb_node);
3519                 if (entry->val < start)
3520                         node = node->rb_right;
3521                 else
3522                         node = node->rb_left;
3523         }
3524
3525         if (entry->val > start && rb_prev(&entry->rb_node))
3526                 entry = rb_entry(rb_prev(&entry->rb_node), struct ulist_node,
3527                                  rb_node);
3528
3529         rbtree_iterate_from_safe(node, next, &entry->rb_node) {
3530                 u64 entry_start;
3531                 u64 entry_end;
3532                 u64 entry_len;
3533                 int clear_ret;
3534
3535                 entry = rb_entry(node, struct ulist_node, rb_node);
3536                 entry_start = entry->val;
3537                 entry_end = entry->aux;
3538                 entry_len = entry_end - entry_start + 1;
3539
3540                 if (entry_start >= start + len)
3541                         break;
3542                 if (entry_start + entry_len <= start)
3543                         continue;
3544                 /*
3545                  * Now the entry is in [start, start + len), revert the
3546                  * EXTENT_QGROUP_RESERVED bit.
3547                  */
3548                 clear_ret = clear_extent_bits(&inode->io_tree, entry_start,
3549                                               entry_end, EXTENT_QGROUP_RESERVED);
3550                 if (!ret && clear_ret < 0)
3551                         ret = clear_ret;
3552
3553                 ulist_del(&reserved->range_changed, entry->val, entry->aux);
3554                 if (likely(reserved->bytes_changed >= entry_len)) {
3555                         reserved->bytes_changed -= entry_len;
3556                 } else {
3557                         WARN_ON(1);
3558                         reserved->bytes_changed = 0;
3559                 }
3560         }
3561
3562         return ret;
3563 }
3564
3565 /*
3566  * Try to free some space for qgroup.
3567  *
3568  * For qgroup, there are only 3 ways to free qgroup space:
3569  * - Flush nodatacow write
3570  *   Any nodatacow write will free its reserved data space at run_delalloc_range().
3571  *   In theory, we should only flush nodatacow inodes, but it's not yet
3572  *   possible, so we need to flush the whole root.
3573  *
3574  * - Wait for ordered extents
3575  *   When ordered extents are finished, their reserved metadata is finally
3576  *   converted to per_trans status, which can be freed by later commit
3577  *   transaction.
3578  *
3579  * - Commit transaction
3580  *   This would free the meta_per_trans space.
3581  *   In theory this shouldn't provide much space, but any more qgroup space
3582  *   is needed.
3583  */
3584 static int try_flush_qgroup(struct btrfs_root *root)
3585 {
3586         struct btrfs_trans_handle *trans;
3587         int ret;
3588
3589         /* Can't hold an open transaction or we run the risk of deadlocking. */
3590         ASSERT(current->journal_info == NULL);
3591         if (WARN_ON(current->journal_info))
3592                 return 0;
3593
3594         /*
3595          * We don't want to run flush again and again, so if there is a running
3596          * one, we won't try to start a new flush, but exit directly.
3597          */
3598         if (test_and_set_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state)) {
3599                 wait_event(root->qgroup_flush_wait,
3600                         !test_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state));
3601                 return 0;
3602         }
3603
3604         ret = btrfs_start_delalloc_snapshot(root, true);
3605         if (ret < 0)
3606                 goto out;
3607         btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
3608
3609         trans = btrfs_join_transaction(root);
3610         if (IS_ERR(trans)) {
3611                 ret = PTR_ERR(trans);
3612                 goto out;
3613         }
3614
3615         ret = btrfs_commit_transaction(trans);
3616 out:
3617         clear_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state);
3618         wake_up(&root->qgroup_flush_wait);
3619         return ret;
3620 }
3621
3622 static int qgroup_reserve_data(struct btrfs_inode *inode,
3623                         struct extent_changeset **reserved_ret, u64 start,
3624                         u64 len)
3625 {
3626         struct btrfs_root *root = inode->root;
3627         struct extent_changeset *reserved;
3628         bool new_reserved = false;
3629         u64 orig_reserved;
3630         u64 to_reserve;
3631         int ret;
3632
3633         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
3634             !is_fstree(root->root_key.objectid) || len == 0)
3635                 return 0;
3636
3637         /* @reserved parameter is mandatory for qgroup */
3638         if (WARN_ON(!reserved_ret))
3639                 return -EINVAL;
3640         if (!*reserved_ret) {
3641                 new_reserved = true;
3642                 *reserved_ret = extent_changeset_alloc();
3643                 if (!*reserved_ret)
3644                         return -ENOMEM;
3645         }
3646         reserved = *reserved_ret;
3647         /* Record already reserved space */
3648         orig_reserved = reserved->bytes_changed;
3649         ret = set_record_extent_bits(&inode->io_tree, start,
3650                         start + len -1, EXTENT_QGROUP_RESERVED, reserved);
3651
3652         /* Newly reserved space */
3653         to_reserve = reserved->bytes_changed - orig_reserved;
3654         trace_btrfs_qgroup_reserve_data(&inode->vfs_inode, start, len,
3655                                         to_reserve, QGROUP_RESERVE);
3656         if (ret < 0)
3657                 goto out;
3658         ret = qgroup_reserve(root, to_reserve, true, BTRFS_QGROUP_RSV_DATA);
3659         if (ret < 0)
3660                 goto cleanup;
3661
3662         return ret;
3663
3664 cleanup:
3665         qgroup_unreserve_range(inode, reserved, start, len);
3666 out:
3667         if (new_reserved) {
3668                 extent_changeset_free(reserved);
3669                 *reserved_ret = NULL;
3670         }
3671         return ret;
3672 }
3673
3674 /*
3675  * Reserve qgroup space for range [start, start + len).
3676  *
3677  * This function will either reserve space from related qgroups or do nothing
3678  * if the range is already reserved.
3679  *
3680  * Return 0 for successful reservation
3681  * Return <0 for error (including -EQUOT)
3682  *
3683  * NOTE: This function may sleep for memory allocation, dirty page flushing and
3684  *       commit transaction. So caller should not hold any dirty page locked.
3685  */
3686 int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
3687                         struct extent_changeset **reserved_ret, u64 start,
3688                         u64 len)
3689 {
3690         int ret;
3691
3692         ret = qgroup_reserve_data(inode, reserved_ret, start, len);
3693         if (ret <= 0 && ret != -EDQUOT)
3694                 return ret;
3695
3696         ret = try_flush_qgroup(inode->root);
3697         if (ret < 0)
3698                 return ret;
3699         return qgroup_reserve_data(inode, reserved_ret, start, len);
3700 }
3701
3702 /* Free ranges specified by @reserved, normally in error path */
3703 static int qgroup_free_reserved_data(struct btrfs_inode *inode,
3704                         struct extent_changeset *reserved, u64 start, u64 len)
3705 {
3706         struct btrfs_root *root = inode->root;
3707         struct ulist_node *unode;
3708         struct ulist_iterator uiter;
3709         struct extent_changeset changeset;
3710         int freed = 0;
3711         int ret;
3712
3713         extent_changeset_init(&changeset);
3714         len = round_up(start + len, root->fs_info->sectorsize);
3715         start = round_down(start, root->fs_info->sectorsize);
3716
3717         ULIST_ITER_INIT(&uiter);
3718         while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
3719                 u64 range_start = unode->val;
3720                 /* unode->aux is the inclusive end */
3721                 u64 range_len = unode->aux - range_start + 1;
3722                 u64 free_start;
3723                 u64 free_len;
3724
3725                 extent_changeset_release(&changeset);
3726
3727                 /* Only free range in range [start, start + len) */
3728                 if (range_start >= start + len ||
3729                     range_start + range_len <= start)
3730                         continue;
3731                 free_start = max(range_start, start);
3732                 free_len = min(start + len, range_start + range_len) -
3733                            free_start;
3734                 /*
3735                  * TODO: To also modify reserved->ranges_reserved to reflect
3736                  * the modification.
3737                  *
3738                  * However as long as we free qgroup reserved according to
3739                  * EXTENT_QGROUP_RESERVED, we won't double free.
3740                  * So not need to rush.
3741                  */
3742                 ret = clear_record_extent_bits(&inode->io_tree, free_start,
3743                                 free_start + free_len - 1,
3744                                 EXTENT_QGROUP_RESERVED, &changeset);
3745                 if (ret < 0)
3746                         goto out;
3747                 freed += changeset.bytes_changed;
3748         }
3749         btrfs_qgroup_free_refroot(root->fs_info, root->root_key.objectid, freed,
3750                                   BTRFS_QGROUP_RSV_DATA);
3751         ret = freed;
3752 out:
3753         extent_changeset_release(&changeset);
3754         return ret;
3755 }
3756
3757 static int __btrfs_qgroup_release_data(struct btrfs_inode *inode,
3758                         struct extent_changeset *reserved, u64 start, u64 len,
3759                         int free)
3760 {
3761         struct extent_changeset changeset;
3762         int trace_op = QGROUP_RELEASE;
3763         int ret;
3764
3765         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &inode->root->fs_info->flags))
3766                 return 0;
3767
3768         /* In release case, we shouldn't have @reserved */
3769         WARN_ON(!free && reserved);
3770         if (free && reserved)
3771                 return qgroup_free_reserved_data(inode, reserved, start, len);
3772         extent_changeset_init(&changeset);
3773         ret = clear_record_extent_bits(&inode->io_tree, start, start + len -1,
3774                                        EXTENT_QGROUP_RESERVED, &changeset);
3775         if (ret < 0)
3776                 goto out;
3777
3778         if (free)
3779                 trace_op = QGROUP_FREE;
3780         trace_btrfs_qgroup_release_data(&inode->vfs_inode, start, len,
3781                                         changeset.bytes_changed, trace_op);
3782         if (free)
3783                 btrfs_qgroup_free_refroot(inode->root->fs_info,
3784                                 inode->root->root_key.objectid,
3785                                 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
3786         ret = changeset.bytes_changed;
3787 out:
3788         extent_changeset_release(&changeset);
3789         return ret;
3790 }
3791
3792 /*
3793  * Free a reserved space range from io_tree and related qgroups
3794  *
3795  * Should be called when a range of pages get invalidated before reaching disk.
3796  * Or for error cleanup case.
3797  * if @reserved is given, only reserved range in [@start, @start + @len) will
3798  * be freed.
3799  *
3800  * For data written to disk, use btrfs_qgroup_release_data().
3801  *
3802  * NOTE: This function may sleep for memory allocation.
3803  */
3804 int btrfs_qgroup_free_data(struct btrfs_inode *inode,
3805                         struct extent_changeset *reserved, u64 start, u64 len)
3806 {
3807         return __btrfs_qgroup_release_data(inode, reserved, start, len, 1);
3808 }
3809
3810 /*
3811  * Release a reserved space range from io_tree only.
3812  *
3813  * Should be called when a range of pages get written to disk and corresponding
3814  * FILE_EXTENT is inserted into corresponding root.
3815  *
3816  * Since new qgroup accounting framework will only update qgroup numbers at
3817  * commit_transaction() time, its reserved space shouldn't be freed from
3818  * related qgroups.
3819  *
3820  * But we should release the range from io_tree, to allow further write to be
3821  * COWed.
3822  *
3823  * NOTE: This function may sleep for memory allocation.
3824  */
3825 int btrfs_qgroup_release_data(struct btrfs_inode *inode, u64 start, u64 len)
3826 {
3827         return __btrfs_qgroup_release_data(inode, NULL, start, len, 0);
3828 }
3829
3830 static void add_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3831                               enum btrfs_qgroup_rsv_type type)
3832 {
3833         if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3834             type != BTRFS_QGROUP_RSV_META_PERTRANS)
3835                 return;
3836         if (num_bytes == 0)
3837                 return;
3838
3839         spin_lock(&root->qgroup_meta_rsv_lock);
3840         if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
3841                 root->qgroup_meta_rsv_prealloc += num_bytes;
3842         else
3843                 root->qgroup_meta_rsv_pertrans += num_bytes;
3844         spin_unlock(&root->qgroup_meta_rsv_lock);
3845 }
3846
3847 static int sub_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 0;
3853         if (num_bytes == 0)
3854                 return 0;
3855
3856         spin_lock(&root->qgroup_meta_rsv_lock);
3857         if (type == BTRFS_QGROUP_RSV_META_PREALLOC) {
3858                 num_bytes = min_t(u64, root->qgroup_meta_rsv_prealloc,
3859                                   num_bytes);
3860                 root->qgroup_meta_rsv_prealloc -= num_bytes;
3861         } else {
3862                 num_bytes = min_t(u64, root->qgroup_meta_rsv_pertrans,
3863                                   num_bytes);
3864                 root->qgroup_meta_rsv_pertrans -= num_bytes;
3865         }
3866         spin_unlock(&root->qgroup_meta_rsv_lock);
3867         return num_bytes;
3868 }
3869
3870 int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
3871                               enum btrfs_qgroup_rsv_type type, bool enforce)
3872 {
3873         struct btrfs_fs_info *fs_info = root->fs_info;
3874         int ret;
3875
3876         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3877             !is_fstree(root->root_key.objectid) || num_bytes == 0)
3878                 return 0;
3879
3880         BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3881         trace_qgroup_meta_reserve(root, (s64)num_bytes, type);
3882         ret = qgroup_reserve(root, num_bytes, enforce, type);
3883         if (ret < 0)
3884                 return ret;
3885         /*
3886          * Record what we have reserved into root.
3887          *
3888          * To avoid quota disabled->enabled underflow.
3889          * In that case, we may try to free space we haven't reserved
3890          * (since quota was disabled), so record what we reserved into root.
3891          * And ensure later release won't underflow this number.
3892          */
3893         add_root_meta_rsv(root, num_bytes, type);
3894         return ret;
3895 }
3896
3897 int __btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
3898                                 enum btrfs_qgroup_rsv_type type, bool enforce)
3899 {
3900         int ret;
3901
3902         ret = btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
3903         if (ret <= 0 && ret != -EDQUOT)
3904                 return ret;
3905
3906         ret = try_flush_qgroup(root);
3907         if (ret < 0)
3908                 return ret;
3909         return btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
3910 }
3911
3912 void btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root *root)
3913 {
3914         struct btrfs_fs_info *fs_info = root->fs_info;
3915
3916         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3917             !is_fstree(root->root_key.objectid))
3918                 return;
3919
3920         /* TODO: Update trace point to handle such free */
3921         trace_qgroup_meta_free_all_pertrans(root);
3922         /* Special value -1 means to free all reserved space */
3923         btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid, (u64)-1,
3924                                   BTRFS_QGROUP_RSV_META_PERTRANS);
3925 }
3926
3927 void __btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes,
3928                               enum btrfs_qgroup_rsv_type type)
3929 {
3930         struct btrfs_fs_info *fs_info = root->fs_info;
3931
3932         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3933             !is_fstree(root->root_key.objectid))
3934                 return;
3935
3936         /*
3937          * reservation for META_PREALLOC can happen before quota is enabled,
3938          * which can lead to underflow.
3939          * Here ensure we will only free what we really have reserved.
3940          */
3941         num_bytes = sub_root_meta_rsv(root, num_bytes, type);
3942         BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3943         trace_qgroup_meta_reserve(root, -(s64)num_bytes, type);
3944         btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid,
3945                                   num_bytes, type);
3946 }
3947
3948 static void qgroup_convert_meta(struct btrfs_fs_info *fs_info, u64 ref_root,
3949                                 int num_bytes)
3950 {
3951         struct btrfs_qgroup *qgroup;
3952         struct ulist_node *unode;
3953         struct ulist_iterator uiter;
3954         int ret = 0;
3955
3956         if (num_bytes == 0)
3957                 return;
3958         if (!fs_info->quota_root)
3959                 return;
3960
3961         spin_lock(&fs_info->qgroup_lock);
3962         qgroup = find_qgroup_rb(fs_info, ref_root);
3963         if (!qgroup)
3964                 goto out;
3965         ulist_reinit(fs_info->qgroup_ulist);
3966         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3967                        qgroup_to_aux(qgroup), GFP_ATOMIC);
3968         if (ret < 0)
3969                 goto out;
3970         ULIST_ITER_INIT(&uiter);
3971         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3972                 struct btrfs_qgroup *qg;
3973                 struct btrfs_qgroup_list *glist;
3974
3975                 qg = unode_aux_to_qgroup(unode);
3976
3977                 qgroup_rsv_release(fs_info, qg, num_bytes,
3978                                 BTRFS_QGROUP_RSV_META_PREALLOC);
3979                 qgroup_rsv_add(fs_info, qg, num_bytes,
3980                                 BTRFS_QGROUP_RSV_META_PERTRANS);
3981                 list_for_each_entry(glist, &qg->groups, next_group) {
3982                         ret = ulist_add(fs_info->qgroup_ulist,
3983                                         glist->group->qgroupid,
3984                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
3985                         if (ret < 0)
3986                                 goto out;
3987                 }
3988         }
3989 out:
3990         spin_unlock(&fs_info->qgroup_lock);
3991 }
3992
3993 void btrfs_qgroup_convert_reserved_meta(struct btrfs_root *root, int num_bytes)
3994 {
3995         struct btrfs_fs_info *fs_info = root->fs_info;
3996
3997         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3998             !is_fstree(root->root_key.objectid))
3999                 return;
4000         /* Same as btrfs_qgroup_free_meta_prealloc() */
4001         num_bytes = sub_root_meta_rsv(root, num_bytes,
4002                                       BTRFS_QGROUP_RSV_META_PREALLOC);
4003         trace_qgroup_meta_convert(root, num_bytes);
4004         qgroup_convert_meta(fs_info, root->root_key.objectid, num_bytes);
4005 }
4006
4007 /*
4008  * Check qgroup reserved space leaking, normally at destroy inode
4009  * time
4010  */
4011 void btrfs_qgroup_check_reserved_leak(struct btrfs_inode *inode)
4012 {
4013         struct extent_changeset changeset;
4014         struct ulist_node *unode;
4015         struct ulist_iterator iter;
4016         int ret;
4017
4018         extent_changeset_init(&changeset);
4019         ret = clear_record_extent_bits(&inode->io_tree, 0, (u64)-1,
4020                         EXTENT_QGROUP_RESERVED, &changeset);
4021
4022         WARN_ON(ret < 0);
4023         if (WARN_ON(changeset.bytes_changed)) {
4024                 ULIST_ITER_INIT(&iter);
4025                 while ((unode = ulist_next(&changeset.range_changed, &iter))) {
4026                         btrfs_warn(inode->root->fs_info,
4027                 "leaking qgroup reserved space, ino: %llu, start: %llu, end: %llu",
4028                                 btrfs_ino(inode), unode->val, unode->aux);
4029                 }
4030                 btrfs_qgroup_free_refroot(inode->root->fs_info,
4031                                 inode->root->root_key.objectid,
4032                                 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
4033
4034         }
4035         extent_changeset_release(&changeset);
4036 }
4037
4038 void btrfs_qgroup_init_swapped_blocks(
4039         struct btrfs_qgroup_swapped_blocks *swapped_blocks)
4040 {
4041         int i;
4042
4043         spin_lock_init(&swapped_blocks->lock);
4044         for (i = 0; i < BTRFS_MAX_LEVEL; i++)
4045                 swapped_blocks->blocks[i] = RB_ROOT;
4046         swapped_blocks->swapped = false;
4047 }
4048
4049 /*
4050  * Delete all swapped blocks record of @root.
4051  * Every record here means we skipped a full subtree scan for qgroup.
4052  *
4053  * Gets called when committing one transaction.
4054  */
4055 void btrfs_qgroup_clean_swapped_blocks(struct btrfs_root *root)
4056 {
4057         struct btrfs_qgroup_swapped_blocks *swapped_blocks;
4058         int i;
4059
4060         swapped_blocks = &root->swapped_blocks;
4061
4062         spin_lock(&swapped_blocks->lock);
4063         if (!swapped_blocks->swapped)
4064                 goto out;
4065         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4066                 struct rb_root *cur_root = &swapped_blocks->blocks[i];
4067                 struct btrfs_qgroup_swapped_block *entry;
4068                 struct btrfs_qgroup_swapped_block *next;
4069
4070                 rbtree_postorder_for_each_entry_safe(entry, next, cur_root,
4071                                                      node)
4072                         kfree(entry);
4073                 swapped_blocks->blocks[i] = RB_ROOT;
4074         }
4075         swapped_blocks->swapped = false;
4076 out:
4077         spin_unlock(&swapped_blocks->lock);
4078 }
4079
4080 /*
4081  * Add subtree roots record into @subvol_root.
4082  *
4083  * @subvol_root:        tree root of the subvolume tree get swapped
4084  * @bg:                 block group under balance
4085  * @subvol_parent/slot: pointer to the subtree root in subvolume tree
4086  * @reloc_parent/slot:  pointer to the subtree root in reloc tree
4087  *                      BOTH POINTERS ARE BEFORE TREE SWAP
4088  * @last_snapshot:      last snapshot generation of the subvolume tree
4089  */
4090 int btrfs_qgroup_add_swapped_blocks(struct btrfs_trans_handle *trans,
4091                 struct btrfs_root *subvol_root,
4092                 struct btrfs_block_group *bg,
4093                 struct extent_buffer *subvol_parent, int subvol_slot,
4094                 struct extent_buffer *reloc_parent, int reloc_slot,
4095                 u64 last_snapshot)
4096 {
4097         struct btrfs_fs_info *fs_info = subvol_root->fs_info;
4098         struct btrfs_qgroup_swapped_blocks *blocks = &subvol_root->swapped_blocks;
4099         struct btrfs_qgroup_swapped_block *block;
4100         struct rb_node **cur;
4101         struct rb_node *parent = NULL;
4102         int level = btrfs_header_level(subvol_parent) - 1;
4103         int ret = 0;
4104
4105         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4106                 return 0;
4107
4108         if (btrfs_node_ptr_generation(subvol_parent, subvol_slot) >
4109             btrfs_node_ptr_generation(reloc_parent, reloc_slot)) {
4110                 btrfs_err_rl(fs_info,
4111                 "%s: bad parameter order, subvol_gen=%llu reloc_gen=%llu",
4112                         __func__,
4113                         btrfs_node_ptr_generation(subvol_parent, subvol_slot),
4114                         btrfs_node_ptr_generation(reloc_parent, reloc_slot));
4115                 return -EUCLEAN;
4116         }
4117
4118         block = kmalloc(sizeof(*block), GFP_NOFS);
4119         if (!block) {
4120                 ret = -ENOMEM;
4121                 goto out;
4122         }
4123
4124         /*
4125          * @reloc_parent/slot is still before swap, while @block is going to
4126          * record the bytenr after swap, so we do the swap here.
4127          */
4128         block->subvol_bytenr = btrfs_node_blockptr(reloc_parent, reloc_slot);
4129         block->subvol_generation = btrfs_node_ptr_generation(reloc_parent,
4130                                                              reloc_slot);
4131         block->reloc_bytenr = btrfs_node_blockptr(subvol_parent, subvol_slot);
4132         block->reloc_generation = btrfs_node_ptr_generation(subvol_parent,
4133                                                             subvol_slot);
4134         block->last_snapshot = last_snapshot;
4135         block->level = level;
4136
4137         /*
4138          * If we have bg == NULL, we're called from btrfs_recover_relocation(),
4139          * no one else can modify tree blocks thus we qgroup will not change
4140          * no matter the value of trace_leaf.
4141          */
4142         if (bg && bg->flags & BTRFS_BLOCK_GROUP_DATA)
4143                 block->trace_leaf = true;
4144         else
4145                 block->trace_leaf = false;
4146         btrfs_node_key_to_cpu(reloc_parent, &block->first_key, reloc_slot);
4147
4148         /* Insert @block into @blocks */
4149         spin_lock(&blocks->lock);
4150         cur = &blocks->blocks[level].rb_node;
4151         while (*cur) {
4152                 struct btrfs_qgroup_swapped_block *entry;
4153
4154                 parent = *cur;
4155                 entry = rb_entry(parent, struct btrfs_qgroup_swapped_block,
4156                                  node);
4157
4158                 if (entry->subvol_bytenr < block->subvol_bytenr) {
4159                         cur = &(*cur)->rb_left;
4160                 } else if (entry->subvol_bytenr > block->subvol_bytenr) {
4161                         cur = &(*cur)->rb_right;
4162                 } else {
4163                         if (entry->subvol_generation !=
4164                                         block->subvol_generation ||
4165                             entry->reloc_bytenr != block->reloc_bytenr ||
4166                             entry->reloc_generation !=
4167                                         block->reloc_generation) {
4168                                 /*
4169                                  * Duplicated but mismatch entry found.
4170                                  * Shouldn't happen.
4171                                  *
4172                                  * Marking qgroup inconsistent should be enough
4173                                  * for end users.
4174                                  */
4175                                 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4176                                 ret = -EEXIST;
4177                         }
4178                         kfree(block);
4179                         goto out_unlock;
4180                 }
4181         }
4182         rb_link_node(&block->node, parent, cur);
4183         rb_insert_color(&block->node, &blocks->blocks[level]);
4184         blocks->swapped = true;
4185 out_unlock:
4186         spin_unlock(&blocks->lock);
4187 out:
4188         if (ret < 0)
4189                 fs_info->qgroup_flags |=
4190                         BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
4191         return ret;
4192 }
4193
4194 /*
4195  * Check if the tree block is a subtree root, and if so do the needed
4196  * delayed subtree trace for qgroup.
4197  *
4198  * This is called during btrfs_cow_block().
4199  */
4200 int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans,
4201                                          struct btrfs_root *root,
4202                                          struct extent_buffer *subvol_eb)
4203 {
4204         struct btrfs_fs_info *fs_info = root->fs_info;
4205         struct btrfs_qgroup_swapped_blocks *blocks = &root->swapped_blocks;
4206         struct btrfs_qgroup_swapped_block *block;
4207         struct extent_buffer *reloc_eb = NULL;
4208         struct rb_node *node;
4209         bool found = false;
4210         bool swapped = false;
4211         int level = btrfs_header_level(subvol_eb);
4212         int ret = 0;
4213         int i;
4214
4215         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4216                 return 0;
4217         if (!is_fstree(root->root_key.objectid) || !root->reloc_root)
4218                 return 0;
4219
4220         spin_lock(&blocks->lock);
4221         if (!blocks->swapped) {
4222                 spin_unlock(&blocks->lock);
4223                 return 0;
4224         }
4225         node = blocks->blocks[level].rb_node;
4226
4227         while (node) {
4228                 block = rb_entry(node, struct btrfs_qgroup_swapped_block, node);
4229                 if (block->subvol_bytenr < subvol_eb->start) {
4230                         node = node->rb_left;
4231                 } else if (block->subvol_bytenr > subvol_eb->start) {
4232                         node = node->rb_right;
4233                 } else {
4234                         found = true;
4235                         break;
4236                 }
4237         }
4238         if (!found) {
4239                 spin_unlock(&blocks->lock);
4240                 goto out;
4241         }
4242         /* Found one, remove it from @blocks first and update blocks->swapped */
4243         rb_erase(&block->node, &blocks->blocks[level]);
4244         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4245                 if (RB_EMPTY_ROOT(&blocks->blocks[i])) {
4246                         swapped = true;
4247                         break;
4248                 }
4249         }
4250         blocks->swapped = swapped;
4251         spin_unlock(&blocks->lock);
4252
4253         /* Read out reloc subtree root */
4254         reloc_eb = read_tree_block(fs_info, block->reloc_bytenr, 0,
4255                                    block->reloc_generation, block->level,
4256                                    &block->first_key);
4257         if (IS_ERR(reloc_eb)) {
4258                 ret = PTR_ERR(reloc_eb);
4259                 reloc_eb = NULL;
4260                 goto free_out;
4261         }
4262         if (!extent_buffer_uptodate(reloc_eb)) {
4263                 ret = -EIO;
4264                 goto free_out;
4265         }
4266
4267         ret = qgroup_trace_subtree_swap(trans, reloc_eb, subvol_eb,
4268                         block->last_snapshot, block->trace_leaf);
4269 free_out:
4270         kfree(block);
4271         free_extent_buffer(reloc_eb);
4272 out:
4273         if (ret < 0) {
4274                 btrfs_err_rl(fs_info,
4275                              "failed to account subtree at bytenr %llu: %d",
4276                              subvol_eb->start, ret);
4277                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
4278         }
4279         return ret;
4280 }
4281
4282 void btrfs_qgroup_destroy_extent_records(struct btrfs_transaction *trans)
4283 {
4284         struct btrfs_qgroup_extent_record *entry;
4285         struct btrfs_qgroup_extent_record *next;
4286         struct rb_root *root;
4287
4288         root = &trans->delayed_refs.dirty_extent_root;
4289         rbtree_postorder_for_each_entry_safe(entry, next, root, node) {
4290                 ulist_free(entry->old_roots);
4291                 kfree(entry);
4292         }
4293 }