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