1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2011 STRATO. All rights reserved.
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>
17 #include "transaction.h"
22 #include "extent_io.h"
24 #include "block-group.h"
28 * - subvol delete -> delete when ref goes to 0? delete limits also?
32 * - copy also limits on subvol creation
35 * - performance benchmarks
36 * - check all ioctl parameters
40 * Helpers to access qgroup reservation
42 * Callers should ensure the lock context and type are valid
45 static u64 qgroup_rsv_total(const struct btrfs_qgroup *qgroup)
50 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
51 ret += qgroup->rsv.values[i];
56 #ifdef CONFIG_BTRFS_DEBUG
57 static const char *qgroup_rsv_type_str(enum btrfs_qgroup_rsv_type type)
59 if (type == BTRFS_QGROUP_RSV_DATA)
61 if (type == BTRFS_QGROUP_RSV_META_PERTRANS)
62 return "meta_pertrans";
63 if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
64 return "meta_prealloc";
69 static void qgroup_rsv_add(struct btrfs_fs_info *fs_info,
70 struct btrfs_qgroup *qgroup, u64 num_bytes,
71 enum btrfs_qgroup_rsv_type type)
73 trace_qgroup_update_reserve(fs_info, qgroup, num_bytes, type);
74 qgroup->rsv.values[type] += num_bytes;
77 static void qgroup_rsv_release(struct btrfs_fs_info *fs_info,
78 struct btrfs_qgroup *qgroup, u64 num_bytes,
79 enum btrfs_qgroup_rsv_type type)
81 trace_qgroup_update_reserve(fs_info, qgroup, -(s64)num_bytes, type);
82 if (qgroup->rsv.values[type] >= num_bytes) {
83 qgroup->rsv.values[type] -= num_bytes;
86 #ifdef CONFIG_BTRFS_DEBUG
88 "qgroup %llu %s reserved space underflow, have %llu to free %llu",
89 qgroup->qgroupid, qgroup_rsv_type_str(type),
90 qgroup->rsv.values[type], num_bytes);
92 qgroup->rsv.values[type] = 0;
95 static void qgroup_rsv_add_by_qgroup(struct btrfs_fs_info *fs_info,
96 struct btrfs_qgroup *dest,
97 struct btrfs_qgroup *src)
101 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
102 qgroup_rsv_add(fs_info, dest, src->rsv.values[i], i);
105 static void qgroup_rsv_release_by_qgroup(struct btrfs_fs_info *fs_info,
106 struct btrfs_qgroup *dest,
107 struct btrfs_qgroup *src)
111 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
112 qgroup_rsv_release(fs_info, dest, src->rsv.values[i], i);
115 static void btrfs_qgroup_update_old_refcnt(struct btrfs_qgroup *qg, u64 seq,
118 if (qg->old_refcnt < seq)
119 qg->old_refcnt = seq;
120 qg->old_refcnt += mod;
123 static void btrfs_qgroup_update_new_refcnt(struct btrfs_qgroup *qg, u64 seq,
126 if (qg->new_refcnt < seq)
127 qg->new_refcnt = seq;
128 qg->new_refcnt += mod;
131 static inline u64 btrfs_qgroup_get_old_refcnt(struct btrfs_qgroup *qg, u64 seq)
133 if (qg->old_refcnt < seq)
135 return qg->old_refcnt - seq;
138 static inline u64 btrfs_qgroup_get_new_refcnt(struct btrfs_qgroup *qg, u64 seq)
140 if (qg->new_refcnt < seq)
142 return qg->new_refcnt - seq;
146 * glue structure to represent the relations between qgroups.
148 struct btrfs_qgroup_list {
149 struct list_head next_group;
150 struct list_head next_member;
151 struct btrfs_qgroup *group;
152 struct btrfs_qgroup *member;
155 static inline u64 qgroup_to_aux(struct btrfs_qgroup *qg)
157 return (u64)(uintptr_t)qg;
160 static inline struct btrfs_qgroup* unode_aux_to_qgroup(struct ulist_node *n)
162 return (struct btrfs_qgroup *)(uintptr_t)n->aux;
166 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
168 static void qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info);
170 /* must be called with qgroup_ioctl_lock held */
171 static struct btrfs_qgroup *find_qgroup_rb(struct btrfs_fs_info *fs_info,
174 struct rb_node *n = fs_info->qgroup_tree.rb_node;
175 struct btrfs_qgroup *qgroup;
178 qgroup = rb_entry(n, struct btrfs_qgroup, node);
179 if (qgroup->qgroupid < qgroupid)
181 else if (qgroup->qgroupid > qgroupid)
189 /* must be called with qgroup_lock held */
190 static struct btrfs_qgroup *add_qgroup_rb(struct btrfs_fs_info *fs_info,
193 struct rb_node **p = &fs_info->qgroup_tree.rb_node;
194 struct rb_node *parent = NULL;
195 struct btrfs_qgroup *qgroup;
199 qgroup = rb_entry(parent, struct btrfs_qgroup, node);
201 if (qgroup->qgroupid < qgroupid)
203 else if (qgroup->qgroupid > qgroupid)
209 qgroup = kzalloc(sizeof(*qgroup), GFP_ATOMIC);
211 return ERR_PTR(-ENOMEM);
213 qgroup->qgroupid = qgroupid;
214 INIT_LIST_HEAD(&qgroup->groups);
215 INIT_LIST_HEAD(&qgroup->members);
216 INIT_LIST_HEAD(&qgroup->dirty);
218 rb_link_node(&qgroup->node, parent, p);
219 rb_insert_color(&qgroup->node, &fs_info->qgroup_tree);
224 static void __del_qgroup_rb(struct btrfs_fs_info *fs_info,
225 struct btrfs_qgroup *qgroup)
227 struct btrfs_qgroup_list *list;
229 list_del(&qgroup->dirty);
230 while (!list_empty(&qgroup->groups)) {
231 list = list_first_entry(&qgroup->groups,
232 struct btrfs_qgroup_list, next_group);
233 list_del(&list->next_group);
234 list_del(&list->next_member);
238 while (!list_empty(&qgroup->members)) {
239 list = list_first_entry(&qgroup->members,
240 struct btrfs_qgroup_list, next_member);
241 list_del(&list->next_group);
242 list_del(&list->next_member);
247 /* must be called with qgroup_lock held */
248 static int del_qgroup_rb(struct btrfs_fs_info *fs_info, u64 qgroupid)
250 struct btrfs_qgroup *qgroup = find_qgroup_rb(fs_info, qgroupid);
255 rb_erase(&qgroup->node, &fs_info->qgroup_tree);
256 __del_qgroup_rb(fs_info, qgroup);
260 /* must be called with qgroup_lock held */
261 static int add_relation_rb(struct btrfs_fs_info *fs_info,
262 u64 memberid, u64 parentid)
264 struct btrfs_qgroup *member;
265 struct btrfs_qgroup *parent;
266 struct btrfs_qgroup_list *list;
268 member = find_qgroup_rb(fs_info, memberid);
269 parent = find_qgroup_rb(fs_info, parentid);
270 if (!member || !parent)
273 list = kzalloc(sizeof(*list), GFP_ATOMIC);
277 list->group = parent;
278 list->member = member;
279 list_add_tail(&list->next_group, &member->groups);
280 list_add_tail(&list->next_member, &parent->members);
285 /* must be called with qgroup_lock held */
286 static int del_relation_rb(struct btrfs_fs_info *fs_info,
287 u64 memberid, u64 parentid)
289 struct btrfs_qgroup *member;
290 struct btrfs_qgroup *parent;
291 struct btrfs_qgroup_list *list;
293 member = find_qgroup_rb(fs_info, memberid);
294 parent = find_qgroup_rb(fs_info, parentid);
295 if (!member || !parent)
298 list_for_each_entry(list, &member->groups, next_group) {
299 if (list->group == parent) {
300 list_del(&list->next_group);
301 list_del(&list->next_member);
309 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
310 int btrfs_verify_qgroup_counts(struct btrfs_fs_info *fs_info, u64 qgroupid,
313 struct btrfs_qgroup *qgroup;
315 qgroup = find_qgroup_rb(fs_info, qgroupid);
318 if (qgroup->rfer != rfer || qgroup->excl != excl)
325 * The full config is read in one go, only called from open_ctree()
326 * It doesn't use any locking, as at this point we're still single-threaded
328 int btrfs_read_qgroup_config(struct btrfs_fs_info *fs_info)
330 struct btrfs_key key;
331 struct btrfs_key found_key;
332 struct btrfs_root *quota_root = fs_info->quota_root;
333 struct btrfs_path *path = NULL;
334 struct extent_buffer *l;
338 u64 rescan_progress = 0;
340 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
343 fs_info->qgroup_ulist = ulist_alloc(GFP_KERNEL);
344 if (!fs_info->qgroup_ulist) {
349 path = btrfs_alloc_path();
355 ret = btrfs_sysfs_add_qgroups(fs_info);
358 /* default this to quota off, in case no status key is found */
359 fs_info->qgroup_flags = 0;
362 * pass 1: read status, all qgroup infos and limits
367 ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 1);
372 struct btrfs_qgroup *qgroup;
374 slot = path->slots[0];
376 btrfs_item_key_to_cpu(l, &found_key, slot);
378 if (found_key.type == BTRFS_QGROUP_STATUS_KEY) {
379 struct btrfs_qgroup_status_item *ptr;
381 ptr = btrfs_item_ptr(l, slot,
382 struct btrfs_qgroup_status_item);
384 if (btrfs_qgroup_status_version(l, ptr) !=
385 BTRFS_QGROUP_STATUS_VERSION) {
387 "old qgroup version, quota disabled");
390 if (btrfs_qgroup_status_generation(l, ptr) !=
391 fs_info->generation) {
392 flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
394 "qgroup generation mismatch, marked as inconsistent");
396 fs_info->qgroup_flags = btrfs_qgroup_status_flags(l,
398 rescan_progress = btrfs_qgroup_status_rescan(l, ptr);
402 if (found_key.type != BTRFS_QGROUP_INFO_KEY &&
403 found_key.type != BTRFS_QGROUP_LIMIT_KEY)
406 qgroup = find_qgroup_rb(fs_info, found_key.offset);
407 if ((qgroup && found_key.type == BTRFS_QGROUP_INFO_KEY) ||
408 (!qgroup && found_key.type == BTRFS_QGROUP_LIMIT_KEY)) {
409 btrfs_err(fs_info, "inconsistent qgroup config");
410 flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
413 qgroup = add_qgroup_rb(fs_info, found_key.offset);
414 if (IS_ERR(qgroup)) {
415 ret = PTR_ERR(qgroup);
419 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
423 switch (found_key.type) {
424 case BTRFS_QGROUP_INFO_KEY: {
425 struct btrfs_qgroup_info_item *ptr;
427 ptr = btrfs_item_ptr(l, slot,
428 struct btrfs_qgroup_info_item);
429 qgroup->rfer = btrfs_qgroup_info_rfer(l, ptr);
430 qgroup->rfer_cmpr = btrfs_qgroup_info_rfer_cmpr(l, ptr);
431 qgroup->excl = btrfs_qgroup_info_excl(l, ptr);
432 qgroup->excl_cmpr = btrfs_qgroup_info_excl_cmpr(l, ptr);
433 /* generation currently unused */
436 case BTRFS_QGROUP_LIMIT_KEY: {
437 struct btrfs_qgroup_limit_item *ptr;
439 ptr = btrfs_item_ptr(l, slot,
440 struct btrfs_qgroup_limit_item);
441 qgroup->lim_flags = btrfs_qgroup_limit_flags(l, ptr);
442 qgroup->max_rfer = btrfs_qgroup_limit_max_rfer(l, ptr);
443 qgroup->max_excl = btrfs_qgroup_limit_max_excl(l, ptr);
444 qgroup->rsv_rfer = btrfs_qgroup_limit_rsv_rfer(l, ptr);
445 qgroup->rsv_excl = btrfs_qgroup_limit_rsv_excl(l, ptr);
450 ret = btrfs_next_item(quota_root, path);
456 btrfs_release_path(path);
459 * pass 2: read all qgroup relations
462 key.type = BTRFS_QGROUP_RELATION_KEY;
464 ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 0);
468 slot = path->slots[0];
470 btrfs_item_key_to_cpu(l, &found_key, slot);
472 if (found_key.type != BTRFS_QGROUP_RELATION_KEY)
475 if (found_key.objectid > found_key.offset) {
476 /* parent <- member, not needed to build config */
477 /* FIXME should we omit the key completely? */
481 ret = add_relation_rb(fs_info, found_key.objectid,
483 if (ret == -ENOENT) {
485 "orphan qgroup relation 0x%llx->0x%llx",
486 found_key.objectid, found_key.offset);
487 ret = 0; /* ignore the error */
492 ret = btrfs_next_item(quota_root, path);
499 btrfs_free_path(path);
500 fs_info->qgroup_flags |= flags;
501 if (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))
502 clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
503 else if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN &&
505 ret = qgroup_rescan_init(fs_info, rescan_progress, 0);
508 ulist_free(fs_info->qgroup_ulist);
509 fs_info->qgroup_ulist = NULL;
510 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
511 btrfs_sysfs_del_qgroups(fs_info);
514 return ret < 0 ? ret : 0;
518 * Called in close_ctree() when quota is still enabled. This verifies we don't
519 * leak some reserved space.
521 * Return false if no reserved space is left.
522 * Return true if some reserved space is leaked.
524 bool btrfs_check_quota_leak(struct btrfs_fs_info *fs_info)
526 struct rb_node *node;
529 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
532 * Since we're unmounting, there is no race and no need to grab qgroup
533 * lock. And here we don't go post-order to provide a more user
534 * friendly sorted result.
536 for (node = rb_first(&fs_info->qgroup_tree); node; node = rb_next(node)) {
537 struct btrfs_qgroup *qgroup;
540 qgroup = rb_entry(node, struct btrfs_qgroup, node);
541 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++) {
542 if (qgroup->rsv.values[i]) {
545 "qgroup %hu/%llu has unreleased space, type %d rsv %llu",
546 btrfs_qgroup_level(qgroup->qgroupid),
547 btrfs_qgroup_subvolid(qgroup->qgroupid),
548 i, qgroup->rsv.values[i]);
556 * This is called from close_ctree() or open_ctree() or btrfs_quota_disable(),
557 * first two are in single-threaded paths.And for the third one, we have set
558 * quota_root to be null with qgroup_lock held before, so it is safe to clean
559 * up the in-memory structures without qgroup_lock held.
561 void btrfs_free_qgroup_config(struct btrfs_fs_info *fs_info)
564 struct btrfs_qgroup *qgroup;
566 while ((n = rb_first(&fs_info->qgroup_tree))) {
567 qgroup = rb_entry(n, struct btrfs_qgroup, node);
568 rb_erase(n, &fs_info->qgroup_tree);
569 __del_qgroup_rb(fs_info, qgroup);
570 btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
574 * We call btrfs_free_qgroup_config() when unmounting
575 * filesystem and disabling quota, so we set qgroup_ulist
576 * to be null here to avoid double free.
578 ulist_free(fs_info->qgroup_ulist);
579 fs_info->qgroup_ulist = NULL;
580 btrfs_sysfs_del_qgroups(fs_info);
583 static int add_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
587 struct btrfs_root *quota_root = trans->fs_info->quota_root;
588 struct btrfs_path *path;
589 struct btrfs_key key;
591 path = btrfs_alloc_path();
596 key.type = BTRFS_QGROUP_RELATION_KEY;
599 ret = btrfs_insert_empty_item(trans, quota_root, path, &key, 0);
601 btrfs_mark_buffer_dirty(path->nodes[0]);
603 btrfs_free_path(path);
607 static int del_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
611 struct btrfs_root *quota_root = trans->fs_info->quota_root;
612 struct btrfs_path *path;
613 struct btrfs_key key;
615 path = btrfs_alloc_path();
620 key.type = BTRFS_QGROUP_RELATION_KEY;
623 ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
632 ret = btrfs_del_item(trans, quota_root, path);
634 btrfs_free_path(path);
638 static int add_qgroup_item(struct btrfs_trans_handle *trans,
639 struct btrfs_root *quota_root, u64 qgroupid)
642 struct btrfs_path *path;
643 struct btrfs_qgroup_info_item *qgroup_info;
644 struct btrfs_qgroup_limit_item *qgroup_limit;
645 struct extent_buffer *leaf;
646 struct btrfs_key key;
648 if (btrfs_is_testing(quota_root->fs_info))
651 path = btrfs_alloc_path();
656 key.type = BTRFS_QGROUP_INFO_KEY;
657 key.offset = qgroupid;
660 * Avoid a transaction abort by catching -EEXIST here. In that
661 * case, we proceed by re-initializing the existing structure
665 ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
666 sizeof(*qgroup_info));
667 if (ret && ret != -EEXIST)
670 leaf = path->nodes[0];
671 qgroup_info = btrfs_item_ptr(leaf, path->slots[0],
672 struct btrfs_qgroup_info_item);
673 btrfs_set_qgroup_info_generation(leaf, qgroup_info, trans->transid);
674 btrfs_set_qgroup_info_rfer(leaf, qgroup_info, 0);
675 btrfs_set_qgroup_info_rfer_cmpr(leaf, qgroup_info, 0);
676 btrfs_set_qgroup_info_excl(leaf, qgroup_info, 0);
677 btrfs_set_qgroup_info_excl_cmpr(leaf, qgroup_info, 0);
679 btrfs_mark_buffer_dirty(leaf);
681 btrfs_release_path(path);
683 key.type = BTRFS_QGROUP_LIMIT_KEY;
684 ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
685 sizeof(*qgroup_limit));
686 if (ret && ret != -EEXIST)
689 leaf = path->nodes[0];
690 qgroup_limit = btrfs_item_ptr(leaf, path->slots[0],
691 struct btrfs_qgroup_limit_item);
692 btrfs_set_qgroup_limit_flags(leaf, qgroup_limit, 0);
693 btrfs_set_qgroup_limit_max_rfer(leaf, qgroup_limit, 0);
694 btrfs_set_qgroup_limit_max_excl(leaf, qgroup_limit, 0);
695 btrfs_set_qgroup_limit_rsv_rfer(leaf, qgroup_limit, 0);
696 btrfs_set_qgroup_limit_rsv_excl(leaf, qgroup_limit, 0);
698 btrfs_mark_buffer_dirty(leaf);
702 btrfs_free_path(path);
706 static int del_qgroup_item(struct btrfs_trans_handle *trans, u64 qgroupid)
709 struct btrfs_root *quota_root = trans->fs_info->quota_root;
710 struct btrfs_path *path;
711 struct btrfs_key key;
713 path = btrfs_alloc_path();
718 key.type = BTRFS_QGROUP_INFO_KEY;
719 key.offset = qgroupid;
720 ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
729 ret = btrfs_del_item(trans, quota_root, path);
733 btrfs_release_path(path);
735 key.type = BTRFS_QGROUP_LIMIT_KEY;
736 ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
745 ret = btrfs_del_item(trans, quota_root, path);
748 btrfs_free_path(path);
752 static int update_qgroup_limit_item(struct btrfs_trans_handle *trans,
753 struct btrfs_qgroup *qgroup)
755 struct btrfs_root *quota_root = trans->fs_info->quota_root;
756 struct btrfs_path *path;
757 struct btrfs_key key;
758 struct extent_buffer *l;
759 struct btrfs_qgroup_limit_item *qgroup_limit;
764 key.type = BTRFS_QGROUP_LIMIT_KEY;
765 key.offset = qgroup->qgroupid;
767 path = btrfs_alloc_path();
771 ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
779 slot = path->slots[0];
780 qgroup_limit = btrfs_item_ptr(l, slot, struct btrfs_qgroup_limit_item);
781 btrfs_set_qgroup_limit_flags(l, qgroup_limit, qgroup->lim_flags);
782 btrfs_set_qgroup_limit_max_rfer(l, qgroup_limit, qgroup->max_rfer);
783 btrfs_set_qgroup_limit_max_excl(l, qgroup_limit, qgroup->max_excl);
784 btrfs_set_qgroup_limit_rsv_rfer(l, qgroup_limit, qgroup->rsv_rfer);
785 btrfs_set_qgroup_limit_rsv_excl(l, qgroup_limit, qgroup->rsv_excl);
787 btrfs_mark_buffer_dirty(l);
790 btrfs_free_path(path);
794 static int update_qgroup_info_item(struct btrfs_trans_handle *trans,
795 struct btrfs_qgroup *qgroup)
797 struct btrfs_fs_info *fs_info = trans->fs_info;
798 struct btrfs_root *quota_root = fs_info->quota_root;
799 struct btrfs_path *path;
800 struct btrfs_key key;
801 struct extent_buffer *l;
802 struct btrfs_qgroup_info_item *qgroup_info;
806 if (btrfs_is_testing(fs_info))
810 key.type = BTRFS_QGROUP_INFO_KEY;
811 key.offset = qgroup->qgroupid;
813 path = btrfs_alloc_path();
817 ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
825 slot = path->slots[0];
826 qgroup_info = btrfs_item_ptr(l, slot, struct btrfs_qgroup_info_item);
827 btrfs_set_qgroup_info_generation(l, qgroup_info, trans->transid);
828 btrfs_set_qgroup_info_rfer(l, qgroup_info, qgroup->rfer);
829 btrfs_set_qgroup_info_rfer_cmpr(l, qgroup_info, qgroup->rfer_cmpr);
830 btrfs_set_qgroup_info_excl(l, qgroup_info, qgroup->excl);
831 btrfs_set_qgroup_info_excl_cmpr(l, qgroup_info, qgroup->excl_cmpr);
833 btrfs_mark_buffer_dirty(l);
836 btrfs_free_path(path);
840 static int update_qgroup_status_item(struct btrfs_trans_handle *trans)
842 struct btrfs_fs_info *fs_info = trans->fs_info;
843 struct btrfs_root *quota_root = fs_info->quota_root;
844 struct btrfs_path *path;
845 struct btrfs_key key;
846 struct extent_buffer *l;
847 struct btrfs_qgroup_status_item *ptr;
852 key.type = BTRFS_QGROUP_STATUS_KEY;
855 path = btrfs_alloc_path();
859 ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
867 slot = path->slots[0];
868 ptr = btrfs_item_ptr(l, slot, struct btrfs_qgroup_status_item);
869 btrfs_set_qgroup_status_flags(l, ptr, fs_info->qgroup_flags);
870 btrfs_set_qgroup_status_generation(l, ptr, trans->transid);
871 btrfs_set_qgroup_status_rescan(l, ptr,
872 fs_info->qgroup_rescan_progress.objectid);
874 btrfs_mark_buffer_dirty(l);
877 btrfs_free_path(path);
882 * called with qgroup_lock held
884 static int btrfs_clean_quota_tree(struct btrfs_trans_handle *trans,
885 struct btrfs_root *root)
887 struct btrfs_path *path;
888 struct btrfs_key key;
889 struct extent_buffer *leaf = NULL;
893 path = btrfs_alloc_path();
897 path->leave_spinning = 1;
904 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
907 leaf = path->nodes[0];
908 nr = btrfs_header_nritems(leaf);
912 * delete the leaf one by one
913 * since the whole tree is going
917 ret = btrfs_del_items(trans, root, path, 0, nr);
921 btrfs_release_path(path);
925 btrfs_free_path(path);
929 int btrfs_quota_enable(struct btrfs_fs_info *fs_info)
931 struct btrfs_root *quota_root;
932 struct btrfs_root *tree_root = fs_info->tree_root;
933 struct btrfs_path *path = NULL;
934 struct btrfs_qgroup_status_item *ptr;
935 struct extent_buffer *leaf;
936 struct btrfs_key key;
937 struct btrfs_key found_key;
938 struct btrfs_qgroup *qgroup = NULL;
939 struct btrfs_trans_handle *trans = NULL;
940 struct ulist *ulist = NULL;
945 * We need to have subvol_sem write locked, to prevent races between
946 * concurrent tasks trying to enable quotas, because we will unlock
947 * and relock qgroup_ioctl_lock before setting fs_info->quota_root
948 * and before setting BTRFS_FS_QUOTA_ENABLED.
950 lockdep_assert_held_write(&fs_info->subvol_sem);
952 mutex_lock(&fs_info->qgroup_ioctl_lock);
953 if (fs_info->quota_root)
956 ulist = ulist_alloc(GFP_KERNEL);
962 ret = btrfs_sysfs_add_qgroups(fs_info);
967 * Unlock qgroup_ioctl_lock before starting the transaction. This is to
968 * avoid lock acquisition inversion problems (reported by lockdep) between
969 * qgroup_ioctl_lock and the vfs freeze semaphores, acquired when we
970 * start a transaction.
971 * After we started the transaction lock qgroup_ioctl_lock again and
972 * check if someone else created the quota root in the meanwhile. If so,
973 * just return success and release the transaction handle.
975 * Also we don't need to worry about someone else calling
976 * btrfs_sysfs_add_qgroups() after we unlock and getting an error because
977 * that function returns 0 (success) when the sysfs entries already exist.
979 mutex_unlock(&fs_info->qgroup_ioctl_lock);
982 * 1 for quota root item
983 * 1 for BTRFS_QGROUP_STATUS item
985 * Yet we also need 2*n items for a QGROUP_INFO/QGROUP_LIMIT items
986 * per subvolume. However those are not currently reserved since it
987 * would be a lot of overkill.
989 trans = btrfs_start_transaction(tree_root, 2);
991 mutex_lock(&fs_info->qgroup_ioctl_lock);
993 ret = PTR_ERR(trans);
998 if (fs_info->quota_root)
1001 fs_info->qgroup_ulist = ulist;
1005 * initially create the quota tree
1007 quota_root = btrfs_create_tree(trans, BTRFS_QUOTA_TREE_OBJECTID);
1008 if (IS_ERR(quota_root)) {
1009 ret = PTR_ERR(quota_root);
1010 btrfs_abort_transaction(trans, ret);
1014 path = btrfs_alloc_path();
1017 btrfs_abort_transaction(trans, ret);
1022 key.type = BTRFS_QGROUP_STATUS_KEY;
1025 ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
1028 btrfs_abort_transaction(trans, ret);
1032 leaf = path->nodes[0];
1033 ptr = btrfs_item_ptr(leaf, path->slots[0],
1034 struct btrfs_qgroup_status_item);
1035 btrfs_set_qgroup_status_generation(leaf, ptr, trans->transid);
1036 btrfs_set_qgroup_status_version(leaf, ptr, BTRFS_QGROUP_STATUS_VERSION);
1037 fs_info->qgroup_flags = BTRFS_QGROUP_STATUS_FLAG_ON |
1038 BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1039 btrfs_set_qgroup_status_flags(leaf, ptr, fs_info->qgroup_flags);
1040 btrfs_set_qgroup_status_rescan(leaf, ptr, 0);
1042 btrfs_mark_buffer_dirty(leaf);
1045 key.type = BTRFS_ROOT_REF_KEY;
1048 btrfs_release_path(path);
1049 ret = btrfs_search_slot_for_read(tree_root, &key, path, 1, 0);
1053 btrfs_abort_transaction(trans, ret);
1058 slot = path->slots[0];
1059 leaf = path->nodes[0];
1060 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1062 if (found_key.type == BTRFS_ROOT_REF_KEY) {
1064 /* Release locks on tree_root before we access quota_root */
1065 btrfs_release_path(path);
1067 ret = add_qgroup_item(trans, quota_root,
1070 btrfs_abort_transaction(trans, ret);
1074 qgroup = add_qgroup_rb(fs_info, found_key.offset);
1075 if (IS_ERR(qgroup)) {
1076 ret = PTR_ERR(qgroup);
1077 btrfs_abort_transaction(trans, ret);
1080 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1082 btrfs_abort_transaction(trans, ret);
1085 ret = btrfs_search_slot_for_read(tree_root, &found_key,
1088 btrfs_abort_transaction(trans, ret);
1093 * Shouldn't happen, but in case it does we
1094 * don't need to do the btrfs_next_item, just
1100 ret = btrfs_next_item(tree_root, path);
1102 btrfs_abort_transaction(trans, ret);
1110 btrfs_release_path(path);
1111 ret = add_qgroup_item(trans, quota_root, BTRFS_FS_TREE_OBJECTID);
1113 btrfs_abort_transaction(trans, ret);
1117 qgroup = add_qgroup_rb(fs_info, BTRFS_FS_TREE_OBJECTID);
1118 if (IS_ERR(qgroup)) {
1119 ret = PTR_ERR(qgroup);
1120 btrfs_abort_transaction(trans, ret);
1123 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1125 btrfs_abort_transaction(trans, ret);
1129 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1131 * Commit the transaction while not holding qgroup_ioctl_lock, to avoid
1132 * a deadlock with tasks concurrently doing other qgroup operations, such
1133 * adding/removing qgroups or adding/deleting qgroup relations for example,
1134 * because all qgroup operations first start or join a transaction and then
1135 * lock the qgroup_ioctl_lock mutex.
1136 * We are safe from a concurrent task trying to enable quotas, by calling
1137 * this function, since we are serialized by fs_info->subvol_sem.
1139 ret = btrfs_commit_transaction(trans);
1141 mutex_lock(&fs_info->qgroup_ioctl_lock);
1146 * Set quota enabled flag after committing the transaction, to avoid
1147 * deadlocks on fs_info->qgroup_ioctl_lock with concurrent snapshot
1150 spin_lock(&fs_info->qgroup_lock);
1151 fs_info->quota_root = quota_root;
1152 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1153 spin_unlock(&fs_info->qgroup_lock);
1155 ret = qgroup_rescan_init(fs_info, 0, 1);
1157 qgroup_rescan_zero_tracking(fs_info);
1158 fs_info->qgroup_rescan_running = true;
1159 btrfs_queue_work(fs_info->qgroup_rescan_workers,
1160 &fs_info->qgroup_rescan_work);
1163 * We have set both BTRFS_FS_QUOTA_ENABLED and
1164 * BTRFS_QGROUP_STATUS_FLAG_ON, so we can only fail with
1165 * -EINPROGRESS. That can happen because someone started the
1166 * rescan worker by calling quota rescan ioctl before we
1167 * attempted to initialize the rescan worker. Failure due to
1168 * quotas disabled in the meanwhile is not possible, because
1169 * we are holding a write lock on fs_info->subvol_sem, which
1170 * is also acquired when disabling quotas.
1171 * Ignore such error, and any other error would need to undo
1172 * everything we did in the transaction we just committed.
1174 ASSERT(ret == -EINPROGRESS);
1179 btrfs_free_path(path);
1182 btrfs_put_root(quota_root);
1185 ulist_free(fs_info->qgroup_ulist);
1186 fs_info->qgroup_ulist = NULL;
1187 btrfs_sysfs_del_qgroups(fs_info);
1189 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1191 btrfs_end_transaction(trans);
1193 ret = btrfs_end_transaction(trans);
1198 int btrfs_quota_disable(struct btrfs_fs_info *fs_info)
1200 struct btrfs_root *quota_root;
1201 struct btrfs_trans_handle *trans = NULL;
1205 * We need to have subvol_sem write locked to prevent races with
1206 * snapshot creation.
1208 lockdep_assert_held_write(&fs_info->subvol_sem);
1211 * Lock the cleaner mutex to prevent races with concurrent relocation,
1212 * because relocation may be building backrefs for blocks of the quota
1213 * root while we are deleting the root. This is like dropping fs roots
1214 * of deleted snapshots/subvolumes, we need the same protection.
1216 * This also prevents races between concurrent tasks trying to disable
1217 * quotas, because we will unlock and relock qgroup_ioctl_lock across
1218 * BTRFS_FS_QUOTA_ENABLED changes.
1220 mutex_lock(&fs_info->cleaner_mutex);
1222 mutex_lock(&fs_info->qgroup_ioctl_lock);
1223 if (!fs_info->quota_root)
1227 * Unlock the qgroup_ioctl_lock mutex before waiting for the rescan worker to
1228 * complete. Otherwise we can deadlock because btrfs_remove_qgroup() needs
1229 * to lock that mutex while holding a transaction handle and the rescan
1230 * worker needs to commit a transaction.
1232 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1235 * Request qgroup rescan worker to complete and wait for it. This wait
1236 * must be done before transaction start for quota disable since it may
1237 * deadlock with transaction by the qgroup rescan worker.
1239 clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1240 btrfs_qgroup_wait_for_completion(fs_info, false);
1243 * 1 For the root item
1245 * We should also reserve enough items for the quota tree deletion in
1246 * btrfs_clean_quota_tree but this is not done.
1248 * Also, we must always start a transaction without holding the mutex
1249 * qgroup_ioctl_lock, see btrfs_quota_enable().
1251 trans = btrfs_start_transaction(fs_info->tree_root, 1);
1253 mutex_lock(&fs_info->qgroup_ioctl_lock);
1254 if (IS_ERR(trans)) {
1255 ret = PTR_ERR(trans);
1257 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1261 if (!fs_info->quota_root)
1264 spin_lock(&fs_info->qgroup_lock);
1265 quota_root = fs_info->quota_root;
1266 fs_info->quota_root = NULL;
1267 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
1268 spin_unlock(&fs_info->qgroup_lock);
1270 btrfs_free_qgroup_config(fs_info);
1272 ret = btrfs_clean_quota_tree(trans, quota_root);
1274 btrfs_abort_transaction(trans, ret);
1278 ret = btrfs_del_root(trans, "a_root->root_key);
1280 btrfs_abort_transaction(trans, ret);
1284 spin_lock(&fs_info->trans_lock);
1285 list_del("a_root->dirty_list);
1286 spin_unlock(&fs_info->trans_lock);
1288 btrfs_tree_lock(quota_root->node);
1289 btrfs_clean_tree_block(quota_root->node);
1290 btrfs_tree_unlock(quota_root->node);
1291 btrfs_free_tree_block(trans, quota_root, quota_root->node, 0, 1);
1293 btrfs_put_root(quota_root);
1296 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1298 btrfs_end_transaction(trans);
1300 ret = btrfs_end_transaction(trans);
1301 mutex_unlock(&fs_info->cleaner_mutex);
1306 static void qgroup_dirty(struct btrfs_fs_info *fs_info,
1307 struct btrfs_qgroup *qgroup)
1309 if (list_empty(&qgroup->dirty))
1310 list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1314 * The easy accounting, we're updating qgroup relationship whose child qgroup
1315 * only has exclusive extents.
1317 * In this case, all exclusive extents will also be exclusive for parent, so
1318 * excl/rfer just get added/removed.
1320 * So is qgroup reservation space, which should also be added/removed to
1322 * Or when child tries to release reservation space, parent will underflow its
1323 * reservation (for relationship adding case).
1325 * Caller should hold fs_info->qgroup_lock.
1327 static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
1328 struct ulist *tmp, u64 ref_root,
1329 struct btrfs_qgroup *src, int sign)
1331 struct btrfs_qgroup *qgroup;
1332 struct btrfs_qgroup_list *glist;
1333 struct ulist_node *unode;
1334 struct ulist_iterator uiter;
1335 u64 num_bytes = src->excl;
1338 qgroup = find_qgroup_rb(fs_info, ref_root);
1342 qgroup->rfer += sign * num_bytes;
1343 qgroup->rfer_cmpr += sign * num_bytes;
1345 WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1346 qgroup->excl += sign * num_bytes;
1347 qgroup->excl_cmpr += sign * num_bytes;
1350 qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1352 qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1354 qgroup_dirty(fs_info, qgroup);
1356 /* Get all of the parent groups that contain this qgroup */
1357 list_for_each_entry(glist, &qgroup->groups, next_group) {
1358 ret = ulist_add(tmp, glist->group->qgroupid,
1359 qgroup_to_aux(glist->group), GFP_ATOMIC);
1364 /* Iterate all of the parents and adjust their reference counts */
1365 ULIST_ITER_INIT(&uiter);
1366 while ((unode = ulist_next(tmp, &uiter))) {
1367 qgroup = unode_aux_to_qgroup(unode);
1368 qgroup->rfer += sign * num_bytes;
1369 qgroup->rfer_cmpr += sign * num_bytes;
1370 WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1371 qgroup->excl += sign * num_bytes;
1373 qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1375 qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1376 qgroup->excl_cmpr += sign * num_bytes;
1377 qgroup_dirty(fs_info, qgroup);
1379 /* Add any parents of the parents */
1380 list_for_each_entry(glist, &qgroup->groups, next_group) {
1381 ret = ulist_add(tmp, glist->group->qgroupid,
1382 qgroup_to_aux(glist->group), GFP_ATOMIC);
1394 * Quick path for updating qgroup with only excl refs.
1396 * In that case, just update all parent will be enough.
1397 * Or we needs to do a full rescan.
1398 * Caller should also hold fs_info->qgroup_lock.
1400 * Return 0 for quick update, return >0 for need to full rescan
1401 * and mark INCONSISTENT flag.
1402 * Return < 0 for other error.
1404 static int quick_update_accounting(struct btrfs_fs_info *fs_info,
1405 struct ulist *tmp, u64 src, u64 dst,
1408 struct btrfs_qgroup *qgroup;
1412 qgroup = find_qgroup_rb(fs_info, src);
1415 if (qgroup->excl == qgroup->rfer) {
1417 err = __qgroup_excl_accounting(fs_info, tmp, dst,
1426 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1430 int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1433 struct btrfs_fs_info *fs_info = trans->fs_info;
1434 struct btrfs_qgroup *parent;
1435 struct btrfs_qgroup *member;
1436 struct btrfs_qgroup_list *list;
1438 unsigned int nofs_flag;
1441 /* Check the level of src and dst first */
1442 if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
1445 /* We hold a transaction handle open, must do a NOFS allocation. */
1446 nofs_flag = memalloc_nofs_save();
1447 tmp = ulist_alloc(GFP_KERNEL);
1448 memalloc_nofs_restore(nofs_flag);
1452 mutex_lock(&fs_info->qgroup_ioctl_lock);
1453 if (!fs_info->quota_root) {
1457 member = find_qgroup_rb(fs_info, src);
1458 parent = find_qgroup_rb(fs_info, dst);
1459 if (!member || !parent) {
1464 /* check if such qgroup relation exist firstly */
1465 list_for_each_entry(list, &member->groups, next_group) {
1466 if (list->group == parent) {
1472 ret = add_qgroup_relation_item(trans, src, dst);
1476 ret = add_qgroup_relation_item(trans, dst, src);
1478 del_qgroup_relation_item(trans, src, dst);
1482 spin_lock(&fs_info->qgroup_lock);
1483 ret = add_relation_rb(fs_info, src, dst);
1485 spin_unlock(&fs_info->qgroup_lock);
1488 ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1489 spin_unlock(&fs_info->qgroup_lock);
1491 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1496 static int __del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1499 struct btrfs_fs_info *fs_info = trans->fs_info;
1500 struct btrfs_qgroup *parent;
1501 struct btrfs_qgroup *member;
1502 struct btrfs_qgroup_list *list;
1505 unsigned int nofs_flag;
1509 /* We hold a transaction handle open, must do a NOFS allocation. */
1510 nofs_flag = memalloc_nofs_save();
1511 tmp = ulist_alloc(GFP_KERNEL);
1512 memalloc_nofs_restore(nofs_flag);
1516 if (!fs_info->quota_root) {
1521 member = find_qgroup_rb(fs_info, src);
1522 parent = find_qgroup_rb(fs_info, dst);
1524 * The parent/member pair doesn't exist, then try to delete the dead
1525 * relation items only.
1527 if (!member || !parent)
1530 /* check if such qgroup relation exist firstly */
1531 list_for_each_entry(list, &member->groups, next_group) {
1532 if (list->group == parent) {
1539 ret = del_qgroup_relation_item(trans, src, dst);
1540 if (ret < 0 && ret != -ENOENT)
1542 ret2 = del_qgroup_relation_item(trans, dst, src);
1543 if (ret2 < 0 && ret2 != -ENOENT)
1546 /* At least one deletion succeeded, return 0 */
1551 spin_lock(&fs_info->qgroup_lock);
1552 del_relation_rb(fs_info, src, dst);
1553 ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1554 spin_unlock(&fs_info->qgroup_lock);
1561 int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1564 struct btrfs_fs_info *fs_info = trans->fs_info;
1567 mutex_lock(&fs_info->qgroup_ioctl_lock);
1568 ret = __del_qgroup_relation(trans, src, dst);
1569 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1574 int btrfs_create_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1576 struct btrfs_fs_info *fs_info = trans->fs_info;
1577 struct btrfs_root *quota_root;
1578 struct btrfs_qgroup *qgroup;
1581 mutex_lock(&fs_info->qgroup_ioctl_lock);
1582 if (!fs_info->quota_root) {
1586 quota_root = fs_info->quota_root;
1587 qgroup = find_qgroup_rb(fs_info, qgroupid);
1593 ret = add_qgroup_item(trans, quota_root, qgroupid);
1597 spin_lock(&fs_info->qgroup_lock);
1598 qgroup = add_qgroup_rb(fs_info, qgroupid);
1599 spin_unlock(&fs_info->qgroup_lock);
1601 if (IS_ERR(qgroup)) {
1602 ret = PTR_ERR(qgroup);
1605 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1607 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1611 static bool qgroup_has_usage(struct btrfs_qgroup *qgroup)
1613 return (qgroup->rfer > 0 || qgroup->rfer_cmpr > 0 ||
1614 qgroup->excl > 0 || qgroup->excl_cmpr > 0 ||
1615 qgroup->rsv.values[BTRFS_QGROUP_RSV_DATA] > 0 ||
1616 qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PREALLOC] > 0 ||
1617 qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PERTRANS] > 0);
1620 int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1622 struct btrfs_fs_info *fs_info = trans->fs_info;
1623 struct btrfs_qgroup *qgroup;
1624 struct btrfs_qgroup_list *list;
1627 mutex_lock(&fs_info->qgroup_ioctl_lock);
1628 if (!fs_info->quota_root) {
1633 qgroup = find_qgroup_rb(fs_info, qgroupid);
1639 if (is_fstree(qgroupid) && qgroup_has_usage(qgroup)) {
1644 /* Check if there are no children of this qgroup */
1645 if (!list_empty(&qgroup->members)) {
1650 ret = del_qgroup_item(trans, qgroupid);
1651 if (ret && ret != -ENOENT)
1654 while (!list_empty(&qgroup->groups)) {
1655 list = list_first_entry(&qgroup->groups,
1656 struct btrfs_qgroup_list, next_group);
1657 ret = __del_qgroup_relation(trans, qgroupid,
1658 list->group->qgroupid);
1663 spin_lock(&fs_info->qgroup_lock);
1664 del_qgroup_rb(fs_info, qgroupid);
1665 spin_unlock(&fs_info->qgroup_lock);
1668 * Remove the qgroup from sysfs now without holding the qgroup_lock
1669 * spinlock, since the sysfs_remove_group() function needs to take
1670 * the mutex kernfs_mutex through kernfs_remove_by_name_ns().
1672 btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
1675 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1679 int btrfs_limit_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid,
1680 struct btrfs_qgroup_limit *limit)
1682 struct btrfs_fs_info *fs_info = trans->fs_info;
1683 struct btrfs_qgroup *qgroup;
1685 /* Sometimes we would want to clear the limit on this qgroup.
1686 * To meet this requirement, we treat the -1 as a special value
1687 * which tell kernel to clear the limit on this qgroup.
1689 const u64 CLEAR_VALUE = -1;
1691 mutex_lock(&fs_info->qgroup_ioctl_lock);
1692 if (!fs_info->quota_root) {
1697 qgroup = find_qgroup_rb(fs_info, qgroupid);
1703 spin_lock(&fs_info->qgroup_lock);
1704 if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
1705 if (limit->max_rfer == CLEAR_VALUE) {
1706 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1707 limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1708 qgroup->max_rfer = 0;
1710 qgroup->max_rfer = limit->max_rfer;
1713 if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
1714 if (limit->max_excl == CLEAR_VALUE) {
1715 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1716 limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1717 qgroup->max_excl = 0;
1719 qgroup->max_excl = limit->max_excl;
1722 if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
1723 if (limit->rsv_rfer == CLEAR_VALUE) {
1724 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1725 limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1726 qgroup->rsv_rfer = 0;
1728 qgroup->rsv_rfer = limit->rsv_rfer;
1731 if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
1732 if (limit->rsv_excl == CLEAR_VALUE) {
1733 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1734 limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1735 qgroup->rsv_excl = 0;
1737 qgroup->rsv_excl = limit->rsv_excl;
1740 qgroup->lim_flags |= limit->flags;
1742 spin_unlock(&fs_info->qgroup_lock);
1744 ret = update_qgroup_limit_item(trans, qgroup);
1746 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1747 btrfs_info(fs_info, "unable to update quota limit for %llu",
1752 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1756 int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1757 struct btrfs_delayed_ref_root *delayed_refs,
1758 struct btrfs_qgroup_extent_record *record)
1760 struct rb_node **p = &delayed_refs->dirty_extent_root.rb_node;
1761 struct rb_node *parent_node = NULL;
1762 struct btrfs_qgroup_extent_record *entry;
1763 u64 bytenr = record->bytenr;
1765 lockdep_assert_held(&delayed_refs->lock);
1766 trace_btrfs_qgroup_trace_extent(fs_info, record);
1770 entry = rb_entry(parent_node, struct btrfs_qgroup_extent_record,
1772 if (bytenr < entry->bytenr) {
1774 } else if (bytenr > entry->bytenr) {
1775 p = &(*p)->rb_right;
1777 if (record->data_rsv && !entry->data_rsv) {
1778 entry->data_rsv = record->data_rsv;
1779 entry->data_rsv_refroot =
1780 record->data_rsv_refroot;
1786 rb_link_node(&record->node, parent_node, p);
1787 rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1791 int btrfs_qgroup_trace_extent_post(struct btrfs_fs_info *fs_info,
1792 struct btrfs_qgroup_extent_record *qrecord)
1794 struct ulist *old_root;
1795 u64 bytenr = qrecord->bytenr;
1798 ret = btrfs_find_all_roots(NULL, fs_info, bytenr, 0, &old_root, false);
1800 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1802 "error accounting new delayed refs extent (err code: %d), quota inconsistent",
1808 * Here we don't need to get the lock of
1809 * trans->transaction->delayed_refs, since inserted qrecord won't
1810 * be deleted, only qrecord->node may be modified (new qrecord insert)
1812 * So modifying qrecord->old_roots is safe here
1814 qrecord->old_roots = old_root;
1818 int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans, u64 bytenr,
1819 u64 num_bytes, gfp_t gfp_flag)
1821 struct btrfs_fs_info *fs_info = trans->fs_info;
1822 struct btrfs_qgroup_extent_record *record;
1823 struct btrfs_delayed_ref_root *delayed_refs;
1826 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
1827 || bytenr == 0 || num_bytes == 0)
1829 record = kzalloc(sizeof(*record), gfp_flag);
1833 delayed_refs = &trans->transaction->delayed_refs;
1834 record->bytenr = bytenr;
1835 record->num_bytes = num_bytes;
1836 record->old_roots = NULL;
1838 spin_lock(&delayed_refs->lock);
1839 ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1840 spin_unlock(&delayed_refs->lock);
1845 return btrfs_qgroup_trace_extent_post(fs_info, record);
1848 int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
1849 struct extent_buffer *eb)
1851 struct btrfs_fs_info *fs_info = trans->fs_info;
1852 int nr = btrfs_header_nritems(eb);
1853 int i, extent_type, ret;
1854 struct btrfs_key key;
1855 struct btrfs_file_extent_item *fi;
1856 u64 bytenr, num_bytes;
1858 /* We can be called directly from walk_up_proc() */
1859 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1862 for (i = 0; i < nr; i++) {
1863 btrfs_item_key_to_cpu(eb, &key, i);
1865 if (key.type != BTRFS_EXTENT_DATA_KEY)
1868 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
1869 /* filter out non qgroup-accountable extents */
1870 extent_type = btrfs_file_extent_type(eb, fi);
1872 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1875 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1879 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1881 ret = btrfs_qgroup_trace_extent(trans, bytenr, num_bytes,
1891 * Walk up the tree from the bottom, freeing leaves and any interior
1892 * nodes which have had all slots visited. If a node (leaf or
1893 * interior) is freed, the node above it will have it's slot
1894 * incremented. The root node will never be freed.
1896 * At the end of this function, we should have a path which has all
1897 * slots incremented to the next position for a search. If we need to
1898 * read a new node it will be NULL and the node above it will have the
1899 * correct slot selected for a later read.
1901 * If we increment the root nodes slot counter past the number of
1902 * elements, 1 is returned to signal completion of the search.
1904 static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1908 struct extent_buffer *eb;
1910 if (root_level == 0)
1913 while (level <= root_level) {
1914 eb = path->nodes[level];
1915 nr = btrfs_header_nritems(eb);
1916 path->slots[level]++;
1917 slot = path->slots[level];
1918 if (slot >= nr || level == 0) {
1920 * Don't free the root - we will detect this
1921 * condition after our loop and return a
1922 * positive value for caller to stop walking the tree.
1924 if (level != root_level) {
1925 btrfs_tree_unlock_rw(eb, path->locks[level]);
1926 path->locks[level] = 0;
1928 free_extent_buffer(eb);
1929 path->nodes[level] = NULL;
1930 path->slots[level] = 0;
1934 * We have a valid slot to walk back down
1935 * from. Stop here so caller can process these
1944 eb = path->nodes[root_level];
1945 if (path->slots[root_level] >= btrfs_header_nritems(eb))
1952 * Helper function to trace a subtree tree block swap.
1954 * The swap will happen in highest tree block, but there may be a lot of
1955 * tree blocks involved.
1958 * OO = Old tree blocks
1959 * NN = New tree blocks allocated during balance
1961 * File tree (257) Reloc tree for 257
1964 * L1 OO OO (a) OO NN (a)
1966 * L0 OO OO OO OO OO OO NN NN
1969 * When calling qgroup_trace_extent_swap(), we will pass:
1971 * @dst_path = [ nodes[1] = NN(a), nodes[0] = NN(c) ]
1975 * In that case, qgroup_trace_extent_swap() will search from OO(a) to
1976 * reach OO(c), then mark both OO(c) and NN(c) as qgroup dirty.
1978 * The main work of qgroup_trace_extent_swap() can be split into 3 parts:
1980 * 1) Tree search from @src_eb
1981 * It should acts as a simplified btrfs_search_slot().
1982 * The key for search can be extracted from @dst_path->nodes[dst_level]
1985 * 2) Mark the final tree blocks in @src_path and @dst_path qgroup dirty
1986 * NOTE: In above case, OO(a) and NN(a) won't be marked qgroup dirty.
1987 * They should be marked during previous (@dst_level = 1) iteration.
1989 * 3) Mark file extents in leaves dirty
1990 * We don't have good way to pick out new file extents only.
1991 * So we still follow the old method by scanning all file extents in
1994 * This function can free us from keeping two paths, thus later we only need
1995 * to care about how to iterate all new tree blocks in reloc tree.
1997 static int qgroup_trace_extent_swap(struct btrfs_trans_handle* trans,
1998 struct extent_buffer *src_eb,
1999 struct btrfs_path *dst_path,
2000 int dst_level, int root_level,
2003 struct btrfs_key key;
2004 struct btrfs_path *src_path;
2005 struct btrfs_fs_info *fs_info = trans->fs_info;
2006 u32 nodesize = fs_info->nodesize;
2007 int cur_level = root_level;
2010 BUG_ON(dst_level > root_level);
2011 /* Level mismatch */
2012 if (btrfs_header_level(src_eb) != root_level)
2015 src_path = btrfs_alloc_path();
2022 btrfs_node_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2024 btrfs_item_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2027 atomic_inc(&src_eb->refs);
2028 src_path->nodes[root_level] = src_eb;
2029 src_path->slots[root_level] = dst_path->slots[root_level];
2030 src_path->locks[root_level] = 0;
2032 /* A simplified version of btrfs_search_slot() */
2033 while (cur_level >= dst_level) {
2034 struct btrfs_key src_key;
2035 struct btrfs_key dst_key;
2037 if (src_path->nodes[cur_level] == NULL) {
2038 struct btrfs_key first_key;
2039 struct extent_buffer *eb;
2044 eb = src_path->nodes[cur_level + 1];
2045 parent_slot = src_path->slots[cur_level + 1];
2046 child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2047 child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2048 btrfs_node_key_to_cpu(eb, &first_key, parent_slot);
2050 eb = read_tree_block(fs_info, child_bytenr, child_gen,
2051 cur_level, &first_key);
2055 } else if (!extent_buffer_uptodate(eb)) {
2056 free_extent_buffer(eb);
2061 src_path->nodes[cur_level] = eb;
2063 btrfs_tree_read_lock(eb);
2064 btrfs_set_lock_blocking_read(eb);
2065 src_path->locks[cur_level] = BTRFS_READ_LOCK_BLOCKING;
2068 src_path->slots[cur_level] = dst_path->slots[cur_level];
2070 btrfs_node_key_to_cpu(dst_path->nodes[cur_level],
2071 &dst_key, dst_path->slots[cur_level]);
2072 btrfs_node_key_to_cpu(src_path->nodes[cur_level],
2073 &src_key, src_path->slots[cur_level]);
2075 btrfs_item_key_to_cpu(dst_path->nodes[cur_level],
2076 &dst_key, dst_path->slots[cur_level]);
2077 btrfs_item_key_to_cpu(src_path->nodes[cur_level],
2078 &src_key, src_path->slots[cur_level]);
2080 /* Content mismatch, something went wrong */
2081 if (btrfs_comp_cpu_keys(&dst_key, &src_key)) {
2089 * Now both @dst_path and @src_path have been populated, record the tree
2090 * blocks for qgroup accounting.
2092 ret = btrfs_qgroup_trace_extent(trans, src_path->nodes[dst_level]->start,
2093 nodesize, GFP_NOFS);
2096 ret = btrfs_qgroup_trace_extent(trans,
2097 dst_path->nodes[dst_level]->start,
2098 nodesize, GFP_NOFS);
2102 /* Record leaf file extents */
2103 if (dst_level == 0 && trace_leaf) {
2104 ret = btrfs_qgroup_trace_leaf_items(trans, src_path->nodes[0]);
2107 ret = btrfs_qgroup_trace_leaf_items(trans, dst_path->nodes[0]);
2110 btrfs_free_path(src_path);
2115 * Helper function to do recursive generation-aware depth-first search, to
2116 * locate all new tree blocks in a subtree of reloc tree.
2118 * E.g. (OO = Old tree blocks, NN = New tree blocks, whose gen == last_snapshot)
2127 * @dst_path = [ nodes[1] = NN(b), nodes[0] = NULL ],
2131 * We will iterate through tree blocks NN(b), NN(d) and info qgroup to trace
2132 * above tree blocks along with their counter parts in file tree.
2133 * While during search, old tree blocks OO(c) will be skipped as tree block swap
2134 * won't affect OO(c).
2136 static int qgroup_trace_new_subtree_blocks(struct btrfs_trans_handle* trans,
2137 struct extent_buffer *src_eb,
2138 struct btrfs_path *dst_path,
2139 int cur_level, int root_level,
2140 u64 last_snapshot, bool trace_leaf)
2142 struct btrfs_fs_info *fs_info = trans->fs_info;
2143 struct extent_buffer *eb;
2144 bool need_cleanup = false;
2148 /* Level sanity check */
2149 if (cur_level < 0 || cur_level >= BTRFS_MAX_LEVEL - 1 ||
2150 root_level < 0 || root_level >= BTRFS_MAX_LEVEL - 1 ||
2151 root_level < cur_level) {
2152 btrfs_err_rl(fs_info,
2153 "%s: bad levels, cur_level=%d root_level=%d",
2154 __func__, cur_level, root_level);
2158 /* Read the tree block if needed */
2159 if (dst_path->nodes[cur_level] == NULL) {
2160 struct btrfs_key first_key;
2166 * dst_path->nodes[root_level] must be initialized before
2167 * calling this function.
2169 if (cur_level == root_level) {
2170 btrfs_err_rl(fs_info,
2171 "%s: dst_path->nodes[%d] not initialized, root_level=%d cur_level=%d",
2172 __func__, root_level, root_level, cur_level);
2177 * We need to get child blockptr/gen from parent before we can
2180 eb = dst_path->nodes[cur_level + 1];
2181 parent_slot = dst_path->slots[cur_level + 1];
2182 child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2183 child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2184 btrfs_node_key_to_cpu(eb, &first_key, parent_slot);
2186 /* This node is old, no need to trace */
2187 if (child_gen < last_snapshot)
2190 eb = read_tree_block(fs_info, child_bytenr, child_gen,
2191 cur_level, &first_key);
2195 } else if (!extent_buffer_uptodate(eb)) {
2196 free_extent_buffer(eb);
2201 dst_path->nodes[cur_level] = eb;
2202 dst_path->slots[cur_level] = 0;
2204 btrfs_tree_read_lock(eb);
2205 btrfs_set_lock_blocking_read(eb);
2206 dst_path->locks[cur_level] = BTRFS_READ_LOCK_BLOCKING;
2207 need_cleanup = true;
2210 /* Now record this tree block and its counter part for qgroups */
2211 ret = qgroup_trace_extent_swap(trans, src_eb, dst_path, cur_level,
2212 root_level, trace_leaf);
2216 eb = dst_path->nodes[cur_level];
2218 if (cur_level > 0) {
2219 /* Iterate all child tree blocks */
2220 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2221 /* Skip old tree blocks as they won't be swapped */
2222 if (btrfs_node_ptr_generation(eb, i) < last_snapshot)
2224 dst_path->slots[cur_level] = i;
2226 /* Recursive call (at most 7 times) */
2227 ret = qgroup_trace_new_subtree_blocks(trans, src_eb,
2228 dst_path, cur_level - 1, root_level,
2229 last_snapshot, trace_leaf);
2238 btrfs_tree_unlock_rw(dst_path->nodes[cur_level],
2239 dst_path->locks[cur_level]);
2240 free_extent_buffer(dst_path->nodes[cur_level]);
2241 dst_path->nodes[cur_level] = NULL;
2242 dst_path->slots[cur_level] = 0;
2243 dst_path->locks[cur_level] = 0;
2249 static int qgroup_trace_subtree_swap(struct btrfs_trans_handle *trans,
2250 struct extent_buffer *src_eb,
2251 struct extent_buffer *dst_eb,
2252 u64 last_snapshot, bool trace_leaf)
2254 struct btrfs_fs_info *fs_info = trans->fs_info;
2255 struct btrfs_path *dst_path = NULL;
2259 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2262 /* Wrong parameter order */
2263 if (btrfs_header_generation(src_eb) > btrfs_header_generation(dst_eb)) {
2264 btrfs_err_rl(fs_info,
2265 "%s: bad parameter order, src_gen=%llu dst_gen=%llu", __func__,
2266 btrfs_header_generation(src_eb),
2267 btrfs_header_generation(dst_eb));
2271 if (!extent_buffer_uptodate(src_eb) || !extent_buffer_uptodate(dst_eb)) {
2276 level = btrfs_header_level(dst_eb);
2277 dst_path = btrfs_alloc_path();
2283 atomic_inc(&dst_eb->refs);
2284 dst_path->nodes[level] = dst_eb;
2285 dst_path->slots[level] = 0;
2286 dst_path->locks[level] = 0;
2288 /* Do the generation aware breadth-first search */
2289 ret = qgroup_trace_new_subtree_blocks(trans, src_eb, dst_path, level,
2290 level, last_snapshot, trace_leaf);
2296 btrfs_free_path(dst_path);
2298 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2302 int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
2303 struct extent_buffer *root_eb,
2304 u64 root_gen, int root_level)
2306 struct btrfs_fs_info *fs_info = trans->fs_info;
2309 struct extent_buffer *eb = root_eb;
2310 struct btrfs_path *path = NULL;
2312 BUG_ON(root_level < 0 || root_level >= BTRFS_MAX_LEVEL);
2313 BUG_ON(root_eb == NULL);
2315 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2318 if (!extent_buffer_uptodate(root_eb)) {
2319 ret = btrfs_read_buffer(root_eb, root_gen, root_level, NULL);
2324 if (root_level == 0) {
2325 ret = btrfs_qgroup_trace_leaf_items(trans, root_eb);
2329 path = btrfs_alloc_path();
2334 * Walk down the tree. Missing extent blocks are filled in as
2335 * we go. Metadata is accounted every time we read a new
2338 * When we reach a leaf, we account for file extent items in it,
2339 * walk back up the tree (adjusting slot pointers as we go)
2340 * and restart the search process.
2342 atomic_inc(&root_eb->refs); /* For path */
2343 path->nodes[root_level] = root_eb;
2344 path->slots[root_level] = 0;
2345 path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
2348 while (level >= 0) {
2349 if (path->nodes[level] == NULL) {
2350 struct btrfs_key first_key;
2356 * We need to get child blockptr/gen from parent before
2359 eb = path->nodes[level + 1];
2360 parent_slot = path->slots[level + 1];
2361 child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2362 child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2363 btrfs_node_key_to_cpu(eb, &first_key, parent_slot);
2365 eb = read_tree_block(fs_info, child_bytenr, child_gen,
2370 } else if (!extent_buffer_uptodate(eb)) {
2371 free_extent_buffer(eb);
2376 path->nodes[level] = eb;
2377 path->slots[level] = 0;
2379 btrfs_tree_read_lock(eb);
2380 btrfs_set_lock_blocking_read(eb);
2381 path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
2383 ret = btrfs_qgroup_trace_extent(trans, child_bytenr,
2391 ret = btrfs_qgroup_trace_leaf_items(trans,
2392 path->nodes[level]);
2396 /* Nonzero return here means we completed our search */
2397 ret = adjust_slots_upwards(path, root_level);
2401 /* Restart search with new slots */
2410 btrfs_free_path(path);
2415 #define UPDATE_NEW 0
2416 #define UPDATE_OLD 1
2418 * Walk all of the roots that points to the bytenr and adjust their refcnts.
2420 static int qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
2421 struct ulist *roots, struct ulist *tmp,
2422 struct ulist *qgroups, u64 seq, int update_old)
2424 struct ulist_node *unode;
2425 struct ulist_iterator uiter;
2426 struct ulist_node *tmp_unode;
2427 struct ulist_iterator tmp_uiter;
2428 struct btrfs_qgroup *qg;
2433 ULIST_ITER_INIT(&uiter);
2434 while ((unode = ulist_next(roots, &uiter))) {
2435 qg = find_qgroup_rb(fs_info, unode->val);
2440 ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
2444 ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
2447 ULIST_ITER_INIT(&tmp_uiter);
2448 while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
2449 struct btrfs_qgroup_list *glist;
2451 qg = unode_aux_to_qgroup(tmp_unode);
2453 btrfs_qgroup_update_old_refcnt(qg, seq, 1);
2455 btrfs_qgroup_update_new_refcnt(qg, seq, 1);
2456 list_for_each_entry(glist, &qg->groups, next_group) {
2457 ret = ulist_add(qgroups, glist->group->qgroupid,
2458 qgroup_to_aux(glist->group),
2462 ret = ulist_add(tmp, glist->group->qgroupid,
2463 qgroup_to_aux(glist->group),
2474 * Update qgroup rfer/excl counters.
2475 * Rfer update is easy, codes can explain themselves.
2477 * Excl update is tricky, the update is split into 2 parts.
2478 * Part 1: Possible exclusive <-> sharing detect:
2480 * -------------------------------------
2482 * -------------------------------------
2484 * -------------------------------------
2487 * A: cur_old_roots < nr_old_roots (not exclusive before)
2488 * !A: cur_old_roots == nr_old_roots (possible exclusive before)
2489 * B: cur_new_roots < nr_new_roots (not exclusive now)
2490 * !B: cur_new_roots == nr_new_roots (possible exclusive now)
2493 * +: Possible sharing -> exclusive -: Possible exclusive -> sharing
2494 * *: Definitely not changed. **: Possible unchanged.
2496 * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
2498 * To make the logic clear, we first use condition A and B to split
2499 * combination into 4 results.
2501 * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
2502 * only on variant maybe 0.
2504 * Lastly, check result **, since there are 2 variants maybe 0, split them
2506 * But this time we don't need to consider other things, the codes and logic
2507 * is easy to understand now.
2509 static int qgroup_update_counters(struct btrfs_fs_info *fs_info,
2510 struct ulist *qgroups,
2513 u64 num_bytes, u64 seq)
2515 struct ulist_node *unode;
2516 struct ulist_iterator uiter;
2517 struct btrfs_qgroup *qg;
2518 u64 cur_new_count, cur_old_count;
2520 ULIST_ITER_INIT(&uiter);
2521 while ((unode = ulist_next(qgroups, &uiter))) {
2524 qg = unode_aux_to_qgroup(unode);
2525 cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
2526 cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);
2528 trace_qgroup_update_counters(fs_info, qg, cur_old_count,
2531 /* Rfer update part */
2532 if (cur_old_count == 0 && cur_new_count > 0) {
2533 qg->rfer += num_bytes;
2534 qg->rfer_cmpr += num_bytes;
2537 if (cur_old_count > 0 && cur_new_count == 0) {
2538 qg->rfer -= num_bytes;
2539 qg->rfer_cmpr -= num_bytes;
2543 /* Excl update part */
2544 /* Exclusive/none -> shared case */
2545 if (cur_old_count == nr_old_roots &&
2546 cur_new_count < nr_new_roots) {
2547 /* Exclusive -> shared */
2548 if (cur_old_count != 0) {
2549 qg->excl -= num_bytes;
2550 qg->excl_cmpr -= num_bytes;
2555 /* Shared -> exclusive/none case */
2556 if (cur_old_count < nr_old_roots &&
2557 cur_new_count == nr_new_roots) {
2558 /* Shared->exclusive */
2559 if (cur_new_count != 0) {
2560 qg->excl += num_bytes;
2561 qg->excl_cmpr += num_bytes;
2566 /* Exclusive/none -> exclusive/none case */
2567 if (cur_old_count == nr_old_roots &&
2568 cur_new_count == nr_new_roots) {
2569 if (cur_old_count == 0) {
2570 /* None -> exclusive/none */
2572 if (cur_new_count != 0) {
2573 /* None -> exclusive */
2574 qg->excl += num_bytes;
2575 qg->excl_cmpr += num_bytes;
2578 /* None -> none, nothing changed */
2580 /* Exclusive -> exclusive/none */
2582 if (cur_new_count == 0) {
2583 /* Exclusive -> none */
2584 qg->excl -= num_bytes;
2585 qg->excl_cmpr -= num_bytes;
2588 /* Exclusive -> exclusive, nothing changed */
2593 qgroup_dirty(fs_info, qg);
2599 * Check if the @roots potentially is a list of fs tree roots
2601 * Return 0 for definitely not a fs/subvol tree roots ulist
2602 * Return 1 for possible fs/subvol tree roots in the list (considering an empty
2605 static int maybe_fs_roots(struct ulist *roots)
2607 struct ulist_node *unode;
2608 struct ulist_iterator uiter;
2610 /* Empty one, still possible for fs roots */
2611 if (!roots || roots->nnodes == 0)
2614 ULIST_ITER_INIT(&uiter);
2615 unode = ulist_next(roots, &uiter);
2620 * If it contains fs tree roots, then it must belong to fs/subvol
2622 * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
2624 return is_fstree(unode->val);
2627 int btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans, u64 bytenr,
2628 u64 num_bytes, struct ulist *old_roots,
2629 struct ulist *new_roots)
2631 struct btrfs_fs_info *fs_info = trans->fs_info;
2632 struct ulist *qgroups = NULL;
2633 struct ulist *tmp = NULL;
2635 u64 nr_new_roots = 0;
2636 u64 nr_old_roots = 0;
2640 * If quotas get disabled meanwhile, the resouces need to be freed and
2641 * we can't just exit here.
2643 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2647 if (!maybe_fs_roots(new_roots))
2649 nr_new_roots = new_roots->nnodes;
2652 if (!maybe_fs_roots(old_roots))
2654 nr_old_roots = old_roots->nnodes;
2657 /* Quick exit, either not fs tree roots, or won't affect any qgroup */
2658 if (nr_old_roots == 0 && nr_new_roots == 0)
2661 BUG_ON(!fs_info->quota_root);
2663 trace_btrfs_qgroup_account_extent(fs_info, trans->transid, bytenr,
2664 num_bytes, nr_old_roots, nr_new_roots);
2666 qgroups = ulist_alloc(GFP_NOFS);
2671 tmp = ulist_alloc(GFP_NOFS);
2677 mutex_lock(&fs_info->qgroup_rescan_lock);
2678 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
2679 if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
2680 mutex_unlock(&fs_info->qgroup_rescan_lock);
2685 mutex_unlock(&fs_info->qgroup_rescan_lock);
2687 spin_lock(&fs_info->qgroup_lock);
2688 seq = fs_info->qgroup_seq;
2690 /* Update old refcnts using old_roots */
2691 ret = qgroup_update_refcnt(fs_info, old_roots, tmp, qgroups, seq,
2696 /* Update new refcnts using new_roots */
2697 ret = qgroup_update_refcnt(fs_info, new_roots, tmp, qgroups, seq,
2702 qgroup_update_counters(fs_info, qgroups, nr_old_roots, nr_new_roots,
2706 * Bump qgroup_seq to avoid seq overlap
2708 fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
2710 spin_unlock(&fs_info->qgroup_lock);
2713 ulist_free(qgroups);
2714 ulist_free(old_roots);
2715 ulist_free(new_roots);
2719 int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans)
2721 struct btrfs_fs_info *fs_info = trans->fs_info;
2722 struct btrfs_qgroup_extent_record *record;
2723 struct btrfs_delayed_ref_root *delayed_refs;
2724 struct ulist *new_roots = NULL;
2725 struct rb_node *node;
2726 u64 num_dirty_extents = 0;
2730 delayed_refs = &trans->transaction->delayed_refs;
2731 qgroup_to_skip = delayed_refs->qgroup_to_skip;
2732 while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
2733 record = rb_entry(node, struct btrfs_qgroup_extent_record,
2736 num_dirty_extents++;
2737 trace_btrfs_qgroup_account_extents(fs_info, record);
2741 * Old roots should be searched when inserting qgroup
2744 if (WARN_ON(!record->old_roots)) {
2745 /* Search commit root to find old_roots */
2746 ret = btrfs_find_all_roots(NULL, fs_info,
2748 &record->old_roots, false);
2753 /* Free the reserved data space */
2754 btrfs_qgroup_free_refroot(fs_info,
2755 record->data_rsv_refroot,
2757 BTRFS_QGROUP_RSV_DATA);
2759 * Use SEQ_LAST as time_seq to do special search, which
2760 * doesn't lock tree or delayed_refs and search current
2761 * root. It's safe inside commit_transaction().
2763 ret = btrfs_find_all_roots(trans, fs_info,
2764 record->bytenr, SEQ_LAST, &new_roots, false);
2767 if (qgroup_to_skip) {
2768 ulist_del(new_roots, qgroup_to_skip, 0);
2769 ulist_del(record->old_roots, qgroup_to_skip,
2772 ret = btrfs_qgroup_account_extent(trans, record->bytenr,
2776 record->old_roots = NULL;
2780 ulist_free(record->old_roots);
2781 ulist_free(new_roots);
2783 rb_erase(node, &delayed_refs->dirty_extent_root);
2787 trace_qgroup_num_dirty_extents(fs_info, trans->transid,
2793 * Writes all changed qgroups to disk.
2794 * Called by the transaction commit path and the qgroup assign ioctl.
2796 int btrfs_run_qgroups(struct btrfs_trans_handle *trans)
2798 struct btrfs_fs_info *fs_info = trans->fs_info;
2802 * In case we are called from the qgroup assign ioctl, assert that we
2803 * are holding the qgroup_ioctl_lock, otherwise we can race with a quota
2804 * disable operation (ioctl) and access a freed quota root.
2806 if (trans->transaction->state != TRANS_STATE_COMMIT_DOING)
2807 lockdep_assert_held(&fs_info->qgroup_ioctl_lock);
2809 if (!fs_info->quota_root)
2812 spin_lock(&fs_info->qgroup_lock);
2813 while (!list_empty(&fs_info->dirty_qgroups)) {
2814 struct btrfs_qgroup *qgroup;
2815 qgroup = list_first_entry(&fs_info->dirty_qgroups,
2816 struct btrfs_qgroup, dirty);
2817 list_del_init(&qgroup->dirty);
2818 spin_unlock(&fs_info->qgroup_lock);
2819 ret = update_qgroup_info_item(trans, qgroup);
2821 fs_info->qgroup_flags |=
2822 BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2823 ret = update_qgroup_limit_item(trans, qgroup);
2825 fs_info->qgroup_flags |=
2826 BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2827 spin_lock(&fs_info->qgroup_lock);
2829 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2830 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_ON;
2832 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
2833 spin_unlock(&fs_info->qgroup_lock);
2835 ret = update_qgroup_status_item(trans);
2837 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2843 * Copy the accounting information between qgroups. This is necessary
2844 * when a snapshot or a subvolume is created. Throwing an error will
2845 * cause a transaction abort so we take extra care here to only error
2846 * when a readonly fs is a reasonable outcome.
2848 int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans, u64 srcid,
2849 u64 objectid, struct btrfs_qgroup_inherit *inherit)
2854 bool committing = false;
2855 struct btrfs_fs_info *fs_info = trans->fs_info;
2856 struct btrfs_root *quota_root;
2857 struct btrfs_qgroup *srcgroup;
2858 struct btrfs_qgroup *dstgroup;
2859 bool need_rescan = false;
2864 * There are only two callers of this function.
2866 * One in create_subvol() in the ioctl context, which needs to hold
2867 * the qgroup_ioctl_lock.
2869 * The other one in create_pending_snapshot() where no other qgroup
2870 * code can modify the fs as they all need to either start a new trans
2871 * or hold a trans handler, thus we don't need to hold
2872 * qgroup_ioctl_lock.
2873 * This would avoid long and complex lock chain and make lockdep happy.
2875 spin_lock(&fs_info->trans_lock);
2876 if (trans->transaction->state == TRANS_STATE_COMMIT_DOING)
2878 spin_unlock(&fs_info->trans_lock);
2881 mutex_lock(&fs_info->qgroup_ioctl_lock);
2882 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2885 quota_root = fs_info->quota_root;
2892 i_qgroups = (u64 *)(inherit + 1);
2893 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
2894 2 * inherit->num_excl_copies;
2895 for (i = 0; i < nums; ++i) {
2896 srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
2899 * Zero out invalid groups so we can ignore
2903 ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
2911 * create a tracking group for the subvol itself
2913 ret = add_qgroup_item(trans, quota_root, objectid);
2918 * add qgroup to all inherited groups
2921 i_qgroups = (u64 *)(inherit + 1);
2922 for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
2923 if (*i_qgroups == 0)
2925 ret = add_qgroup_relation_item(trans, objectid,
2927 if (ret && ret != -EEXIST)
2929 ret = add_qgroup_relation_item(trans, *i_qgroups,
2931 if (ret && ret != -EEXIST)
2938 spin_lock(&fs_info->qgroup_lock);
2940 dstgroup = add_qgroup_rb(fs_info, objectid);
2941 if (IS_ERR(dstgroup)) {
2942 ret = PTR_ERR(dstgroup);
2946 if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
2947 dstgroup->lim_flags = inherit->lim.flags;
2948 dstgroup->max_rfer = inherit->lim.max_rfer;
2949 dstgroup->max_excl = inherit->lim.max_excl;
2950 dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
2951 dstgroup->rsv_excl = inherit->lim.rsv_excl;
2953 qgroup_dirty(fs_info, dstgroup);
2957 srcgroup = find_qgroup_rb(fs_info, srcid);
2962 * We call inherit after we clone the root in order to make sure
2963 * our counts don't go crazy, so at this point the only
2964 * difference between the two roots should be the root node.
2966 level_size = fs_info->nodesize;
2967 dstgroup->rfer = srcgroup->rfer;
2968 dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
2969 dstgroup->excl = level_size;
2970 dstgroup->excl_cmpr = level_size;
2971 srcgroup->excl = level_size;
2972 srcgroup->excl_cmpr = level_size;
2974 /* inherit the limit info */
2975 dstgroup->lim_flags = srcgroup->lim_flags;
2976 dstgroup->max_rfer = srcgroup->max_rfer;
2977 dstgroup->max_excl = srcgroup->max_excl;
2978 dstgroup->rsv_rfer = srcgroup->rsv_rfer;
2979 dstgroup->rsv_excl = srcgroup->rsv_excl;
2981 qgroup_dirty(fs_info, dstgroup);
2982 qgroup_dirty(fs_info, srcgroup);
2988 i_qgroups = (u64 *)(inherit + 1);
2989 for (i = 0; i < inherit->num_qgroups; ++i) {
2991 ret = add_relation_rb(fs_info, objectid, *i_qgroups);
2998 * If we're doing a snapshot, and adding the snapshot to a new
2999 * qgroup, the numbers are guaranteed to be incorrect.
3005 for (i = 0; i < inherit->num_ref_copies; ++i, i_qgroups += 2) {
3006 struct btrfs_qgroup *src;
3007 struct btrfs_qgroup *dst;
3009 if (!i_qgroups[0] || !i_qgroups[1])
3012 src = find_qgroup_rb(fs_info, i_qgroups[0]);
3013 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3020 dst->rfer = src->rfer - level_size;
3021 dst->rfer_cmpr = src->rfer_cmpr - level_size;
3023 /* Manually tweaking numbers certainly needs a rescan */
3026 for (i = 0; i < inherit->num_excl_copies; ++i, i_qgroups += 2) {
3027 struct btrfs_qgroup *src;
3028 struct btrfs_qgroup *dst;
3030 if (!i_qgroups[0] || !i_qgroups[1])
3033 src = find_qgroup_rb(fs_info, i_qgroups[0]);
3034 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3041 dst->excl = src->excl + level_size;
3042 dst->excl_cmpr = src->excl_cmpr + level_size;
3047 spin_unlock(&fs_info->qgroup_lock);
3049 ret = btrfs_sysfs_add_one_qgroup(fs_info, dstgroup);
3052 mutex_unlock(&fs_info->qgroup_ioctl_lock);
3054 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3058 static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
3060 if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
3061 qgroup_rsv_total(qg) + (s64)qg->rfer + num_bytes > qg->max_rfer)
3064 if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
3065 qgroup_rsv_total(qg) + (s64)qg->excl + num_bytes > qg->max_excl)
3071 static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce,
3072 enum btrfs_qgroup_rsv_type type)
3074 struct btrfs_qgroup *qgroup;
3075 struct btrfs_fs_info *fs_info = root->fs_info;
3076 u64 ref_root = root->root_key.objectid;
3078 struct ulist_node *unode;
3079 struct ulist_iterator uiter;
3081 if (!is_fstree(ref_root))
3087 if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
3088 capable(CAP_SYS_RESOURCE))
3091 spin_lock(&fs_info->qgroup_lock);
3092 if (!fs_info->quota_root)
3095 qgroup = find_qgroup_rb(fs_info, ref_root);
3100 * in a first step, we check all affected qgroups if any limits would
3103 ulist_reinit(fs_info->qgroup_ulist);
3104 ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3105 qgroup_to_aux(qgroup), GFP_ATOMIC);
3108 ULIST_ITER_INIT(&uiter);
3109 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3110 struct btrfs_qgroup *qg;
3111 struct btrfs_qgroup_list *glist;
3113 qg = unode_aux_to_qgroup(unode);
3115 if (enforce && !qgroup_check_limits(qg, num_bytes)) {
3120 list_for_each_entry(glist, &qg->groups, next_group) {
3121 ret = ulist_add(fs_info->qgroup_ulist,
3122 glist->group->qgroupid,
3123 qgroup_to_aux(glist->group), GFP_ATOMIC);
3130 * no limits exceeded, now record the reservation into all qgroups
3132 ULIST_ITER_INIT(&uiter);
3133 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3134 struct btrfs_qgroup *qg;
3136 qg = unode_aux_to_qgroup(unode);
3138 qgroup_rsv_add(fs_info, qg, num_bytes, type);
3142 spin_unlock(&fs_info->qgroup_lock);
3147 * Free @num_bytes of reserved space with @type for qgroup. (Normally level 0
3150 * Will handle all higher level qgroup too.
3152 * NOTE: If @num_bytes is (u64)-1, this means to free all bytes of this qgroup.
3153 * This special case is only used for META_PERTRANS type.
3155 void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
3156 u64 ref_root, u64 num_bytes,
3157 enum btrfs_qgroup_rsv_type type)
3159 struct btrfs_qgroup *qgroup;
3160 struct ulist_node *unode;
3161 struct ulist_iterator uiter;
3164 if (!is_fstree(ref_root))
3170 if (num_bytes == (u64)-1 && type != BTRFS_QGROUP_RSV_META_PERTRANS) {
3171 WARN(1, "%s: Invalid type to free", __func__);
3174 spin_lock(&fs_info->qgroup_lock);
3176 if (!fs_info->quota_root)
3179 qgroup = find_qgroup_rb(fs_info, ref_root);
3183 if (num_bytes == (u64)-1)
3185 * We're freeing all pertrans rsv, get reserved value from
3186 * level 0 qgroup as real num_bytes to free.
3188 num_bytes = qgroup->rsv.values[type];
3190 ulist_reinit(fs_info->qgroup_ulist);
3191 ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3192 qgroup_to_aux(qgroup), GFP_ATOMIC);
3195 ULIST_ITER_INIT(&uiter);
3196 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3197 struct btrfs_qgroup *qg;
3198 struct btrfs_qgroup_list *glist;
3200 qg = unode_aux_to_qgroup(unode);
3202 qgroup_rsv_release(fs_info, qg, num_bytes, type);
3204 list_for_each_entry(glist, &qg->groups, next_group) {
3205 ret = ulist_add(fs_info->qgroup_ulist,
3206 glist->group->qgroupid,
3207 qgroup_to_aux(glist->group), GFP_ATOMIC);
3214 spin_unlock(&fs_info->qgroup_lock);
3218 * Check if the leaf is the last leaf. Which means all node pointers
3219 * are at their last position.
3221 static bool is_last_leaf(struct btrfs_path *path)
3225 for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
3226 if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
3233 * returns < 0 on error, 0 when more leafs are to be scanned.
3234 * returns 1 when done.
3236 static int qgroup_rescan_leaf(struct btrfs_trans_handle *trans,
3237 struct btrfs_path *path)
3239 struct btrfs_fs_info *fs_info = trans->fs_info;
3240 struct btrfs_key found;
3241 struct extent_buffer *scratch_leaf = NULL;
3242 struct ulist *roots = NULL;
3248 mutex_lock(&fs_info->qgroup_rescan_lock);
3249 ret = btrfs_search_slot_for_read(fs_info->extent_root,
3250 &fs_info->qgroup_rescan_progress,
3253 btrfs_debug(fs_info,
3254 "current progress key (%llu %u %llu), search_slot ret %d",
3255 fs_info->qgroup_rescan_progress.objectid,
3256 fs_info->qgroup_rescan_progress.type,
3257 fs_info->qgroup_rescan_progress.offset, ret);
3261 * The rescan is about to end, we will not be scanning any
3262 * further blocks. We cannot unset the RESCAN flag here, because
3263 * we want to commit the transaction if everything went well.
3264 * To make the live accounting work in this phase, we set our
3265 * scan progress pointer such that every real extent objectid
3268 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3269 btrfs_release_path(path);
3270 mutex_unlock(&fs_info->qgroup_rescan_lock);
3273 done = is_last_leaf(path);
3275 btrfs_item_key_to_cpu(path->nodes[0], &found,
3276 btrfs_header_nritems(path->nodes[0]) - 1);
3277 fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;
3279 scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
3280 if (!scratch_leaf) {
3282 mutex_unlock(&fs_info->qgroup_rescan_lock);
3285 slot = path->slots[0];
3286 btrfs_release_path(path);
3287 mutex_unlock(&fs_info->qgroup_rescan_lock);
3289 for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
3290 btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
3291 if (found.type != BTRFS_EXTENT_ITEM_KEY &&
3292 found.type != BTRFS_METADATA_ITEM_KEY)
3294 if (found.type == BTRFS_METADATA_ITEM_KEY)
3295 num_bytes = fs_info->nodesize;
3297 num_bytes = found.offset;
3299 ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
3303 /* For rescan, just pass old_roots as NULL */
3304 ret = btrfs_qgroup_account_extent(trans, found.objectid,
3305 num_bytes, NULL, roots);
3311 free_extent_buffer(scratch_leaf);
3315 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3320 static bool rescan_should_stop(struct btrfs_fs_info *fs_info)
3322 return btrfs_fs_closing(fs_info) ||
3323 test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state) ||
3324 !test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
3327 static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
3329 struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
3330 qgroup_rescan_work);
3331 struct btrfs_path *path;
3332 struct btrfs_trans_handle *trans = NULL;
3335 bool stopped = false;
3336 bool did_leaf_rescans = false;
3338 path = btrfs_alloc_path();
3342 * Rescan should only search for commit root, and any later difference
3343 * should be recorded by qgroup
3345 path->search_commit_root = 1;
3346 path->skip_locking = 1;
3349 while (!err && !(stopped = rescan_should_stop(fs_info))) {
3350 trans = btrfs_start_transaction(fs_info->fs_root, 0);
3351 if (IS_ERR(trans)) {
3352 err = PTR_ERR(trans);
3356 err = qgroup_rescan_leaf(trans, path);
3357 did_leaf_rescans = true;
3360 btrfs_commit_transaction(trans);
3362 btrfs_end_transaction(trans);
3366 btrfs_free_path(path);
3368 mutex_lock(&fs_info->qgroup_rescan_lock);
3370 fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT) {
3371 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3372 } else if (err < 0 || stopped) {
3373 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3375 mutex_unlock(&fs_info->qgroup_rescan_lock);
3378 * Only update status, since the previous part has already updated the
3379 * qgroup info, and only if we did any actual work. This also prevents
3380 * race with a concurrent quota disable, which has already set
3381 * fs_info->quota_root to NULL and cleared BTRFS_FS_QUOTA_ENABLED at
3382 * btrfs_quota_disable().
3384 if (did_leaf_rescans) {
3385 trans = btrfs_start_transaction(fs_info->quota_root, 1);
3386 if (IS_ERR(trans)) {
3387 err = PTR_ERR(trans);
3390 "fail to start transaction for status update: %d",
3397 mutex_lock(&fs_info->qgroup_rescan_lock);
3399 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3401 ret = update_qgroup_status_item(trans);
3404 btrfs_err(fs_info, "fail to update qgroup status: %d",
3408 fs_info->qgroup_rescan_running = false;
3409 complete_all(&fs_info->qgroup_rescan_completion);
3410 mutex_unlock(&fs_info->qgroup_rescan_lock);
3415 btrfs_end_transaction(trans);
3418 btrfs_info(fs_info, "qgroup scan paused");
3419 } else if (err >= 0) {
3420 btrfs_info(fs_info, "qgroup scan completed%s",
3421 err > 0 ? " (inconsistency flag cleared)" : "");
3423 btrfs_err(fs_info, "qgroup scan failed with %d", err);
3428 * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
3429 * memory required for the rescan context.
3432 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
3438 /* we're resuming qgroup rescan at mount time */
3439 if (!(fs_info->qgroup_flags &
3440 BTRFS_QGROUP_STATUS_FLAG_RESCAN)) {
3442 "qgroup rescan init failed, qgroup rescan is not queued");
3444 } else if (!(fs_info->qgroup_flags &
3445 BTRFS_QGROUP_STATUS_FLAG_ON)) {
3447 "qgroup rescan init failed, qgroup is not enabled");
3455 mutex_lock(&fs_info->qgroup_rescan_lock);
3458 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3460 "qgroup rescan is already in progress");
3462 } else if (!(fs_info->qgroup_flags &
3463 BTRFS_QGROUP_STATUS_FLAG_ON)) {
3465 "qgroup rescan init failed, qgroup is not enabled");
3467 } else if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
3468 /* Quota disable is in progress */
3473 mutex_unlock(&fs_info->qgroup_rescan_lock);
3476 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3479 memset(&fs_info->qgroup_rescan_progress, 0,
3480 sizeof(fs_info->qgroup_rescan_progress));
3481 fs_info->qgroup_rescan_progress.objectid = progress_objectid;
3482 init_completion(&fs_info->qgroup_rescan_completion);
3483 mutex_unlock(&fs_info->qgroup_rescan_lock);
3485 btrfs_init_work(&fs_info->qgroup_rescan_work,
3486 btrfs_qgroup_rescan_worker, NULL, NULL);
3491 qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
3494 struct btrfs_qgroup *qgroup;
3496 spin_lock(&fs_info->qgroup_lock);
3497 /* clear all current qgroup tracking information */
3498 for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
3499 qgroup = rb_entry(n, struct btrfs_qgroup, node);
3501 qgroup->rfer_cmpr = 0;
3503 qgroup->excl_cmpr = 0;
3504 qgroup_dirty(fs_info, qgroup);
3506 spin_unlock(&fs_info->qgroup_lock);
3510 btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
3513 struct btrfs_trans_handle *trans;
3515 ret = qgroup_rescan_init(fs_info, 0, 1);
3520 * We have set the rescan_progress to 0, which means no more
3521 * delayed refs will be accounted by btrfs_qgroup_account_ref.
3522 * However, btrfs_qgroup_account_ref may be right after its call
3523 * to btrfs_find_all_roots, in which case it would still do the
3525 * To solve this, we're committing the transaction, which will
3526 * ensure we run all delayed refs and only after that, we are
3527 * going to clear all tracking information for a clean start.
3530 trans = btrfs_join_transaction(fs_info->fs_root);
3531 if (IS_ERR(trans)) {
3532 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3533 return PTR_ERR(trans);
3535 ret = btrfs_commit_transaction(trans);
3537 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3541 qgroup_rescan_zero_tracking(fs_info);
3543 mutex_lock(&fs_info->qgroup_rescan_lock);
3544 fs_info->qgroup_rescan_running = true;
3545 btrfs_queue_work(fs_info->qgroup_rescan_workers,
3546 &fs_info->qgroup_rescan_work);
3547 mutex_unlock(&fs_info->qgroup_rescan_lock);
3552 int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
3558 mutex_lock(&fs_info->qgroup_rescan_lock);
3559 running = fs_info->qgroup_rescan_running;
3560 mutex_unlock(&fs_info->qgroup_rescan_lock);
3566 ret = wait_for_completion_interruptible(
3567 &fs_info->qgroup_rescan_completion);
3569 wait_for_completion(&fs_info->qgroup_rescan_completion);
3575 * this is only called from open_ctree where we're still single threaded, thus
3576 * locking is omitted here.
3579 btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
3581 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3582 mutex_lock(&fs_info->qgroup_rescan_lock);
3583 fs_info->qgroup_rescan_running = true;
3584 btrfs_queue_work(fs_info->qgroup_rescan_workers,
3585 &fs_info->qgroup_rescan_work);
3586 mutex_unlock(&fs_info->qgroup_rescan_lock);
3590 #define rbtree_iterate_from_safe(node, next, start) \
3591 for (node = start; node && ({ next = rb_next(node); 1;}); node = next)
3593 static int qgroup_unreserve_range(struct btrfs_inode *inode,
3594 struct extent_changeset *reserved, u64 start,
3597 struct rb_node *node;
3598 struct rb_node *next;
3599 struct ulist_node *entry;
3602 node = reserved->range_changed.root.rb_node;
3606 entry = rb_entry(node, struct ulist_node, rb_node);
3607 if (entry->val < start)
3608 node = node->rb_right;
3610 node = node->rb_left;
3613 if (entry->val > start && rb_prev(&entry->rb_node))
3614 entry = rb_entry(rb_prev(&entry->rb_node), struct ulist_node,
3617 rbtree_iterate_from_safe(node, next, &entry->rb_node) {
3623 entry = rb_entry(node, struct ulist_node, rb_node);
3624 entry_start = entry->val;
3625 entry_end = entry->aux;
3626 entry_len = entry_end - entry_start + 1;
3628 if (entry_start >= start + len)
3630 if (entry_start + entry_len <= start)
3633 * Now the entry is in [start, start + len), revert the
3634 * EXTENT_QGROUP_RESERVED bit.
3636 clear_ret = clear_extent_bits(&inode->io_tree, entry_start,
3637 entry_end, EXTENT_QGROUP_RESERVED);
3638 if (!ret && clear_ret < 0)
3641 ulist_del(&reserved->range_changed, entry->val, entry->aux);
3642 if (likely(reserved->bytes_changed >= entry_len)) {
3643 reserved->bytes_changed -= entry_len;
3646 reserved->bytes_changed = 0;
3654 * Try to free some space for qgroup.
3656 * For qgroup, there are only 3 ways to free qgroup space:
3657 * - Flush nodatacow write
3658 * Any nodatacow write will free its reserved data space at run_delalloc_range().
3659 * In theory, we should only flush nodatacow inodes, but it's not yet
3660 * possible, so we need to flush the whole root.
3662 * - Wait for ordered extents
3663 * When ordered extents are finished, their reserved metadata is finally
3664 * converted to per_trans status, which can be freed by later commit
3667 * - Commit transaction
3668 * This would free the meta_per_trans space.
3669 * In theory this shouldn't provide much space, but any more qgroup space
3672 static int try_flush_qgroup(struct btrfs_root *root)
3674 struct btrfs_trans_handle *trans;
3676 bool can_commit = true;
3679 * If current process holds a transaction, we shouldn't flush, as we
3680 * assume all space reservation happens before a transaction handle is
3683 * But there are cases like btrfs_delayed_item_reserve_metadata() where
3684 * we try to reserve space with one transction handle already held.
3685 * In that case we can't commit transaction, but at least try to end it
3686 * and hope the started data writes can free some space.
3688 if (current->journal_info &&
3689 current->journal_info != BTRFS_SEND_TRANS_STUB)
3693 * We don't want to run flush again and again, so if there is a running
3694 * one, we won't try to start a new flush, but exit directly.
3696 if (test_and_set_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state)) {
3698 * We are already holding a transaction, thus we can block other
3699 * threads from flushing. So exit right now. This increases
3700 * the chance of EDQUOT for heavy load and near limit cases.
3701 * But we can argue that if we're already near limit, EDQUOT is
3702 * unavoidable anyway.
3707 wait_event(root->qgroup_flush_wait,
3708 !test_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state));
3712 ret = btrfs_start_delalloc_snapshot(root);
3715 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
3717 trans = btrfs_join_transaction(root);
3718 if (IS_ERR(trans)) {
3719 ret = PTR_ERR(trans);
3724 ret = btrfs_commit_transaction(trans);
3726 ret = btrfs_end_transaction(trans);
3728 clear_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state);
3729 wake_up(&root->qgroup_flush_wait);
3733 static int qgroup_reserve_data(struct btrfs_inode *inode,
3734 struct extent_changeset **reserved_ret, u64 start,
3737 struct btrfs_root *root = inode->root;
3738 struct extent_changeset *reserved;
3739 bool new_reserved = false;
3744 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
3745 !is_fstree(root->root_key.objectid) || len == 0)
3748 /* @reserved parameter is mandatory for qgroup */
3749 if (WARN_ON(!reserved_ret))
3751 if (!*reserved_ret) {
3752 new_reserved = true;
3753 *reserved_ret = extent_changeset_alloc();
3757 reserved = *reserved_ret;
3758 /* Record already reserved space */
3759 orig_reserved = reserved->bytes_changed;
3760 ret = set_record_extent_bits(&inode->io_tree, start,
3761 start + len -1, EXTENT_QGROUP_RESERVED, reserved);
3763 /* Newly reserved space */
3764 to_reserve = reserved->bytes_changed - orig_reserved;
3765 trace_btrfs_qgroup_reserve_data(&inode->vfs_inode, start, len,
3766 to_reserve, QGROUP_RESERVE);
3769 ret = qgroup_reserve(root, to_reserve, true, BTRFS_QGROUP_RSV_DATA);
3776 qgroup_unreserve_range(inode, reserved, start, len);
3779 extent_changeset_release(reserved);
3781 *reserved_ret = NULL;
3787 * Reserve qgroup space for range [start, start + len).
3789 * This function will either reserve space from related qgroups or do nothing
3790 * if the range is already reserved.
3792 * Return 0 for successful reservation
3793 * Return <0 for error (including -EQUOT)
3795 * NOTE: This function may sleep for memory allocation, dirty page flushing and
3796 * commit transaction. So caller should not hold any dirty page locked.
3798 int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
3799 struct extent_changeset **reserved_ret, u64 start,
3804 ret = qgroup_reserve_data(inode, reserved_ret, start, len);
3805 if (ret <= 0 && ret != -EDQUOT)
3808 ret = try_flush_qgroup(inode->root);
3811 return qgroup_reserve_data(inode, reserved_ret, start, len);
3814 /* Free ranges specified by @reserved, normally in error path */
3815 static int qgroup_free_reserved_data(struct btrfs_inode *inode,
3816 struct extent_changeset *reserved, u64 start, u64 len)
3818 struct btrfs_root *root = inode->root;
3819 struct ulist_node *unode;
3820 struct ulist_iterator uiter;
3821 struct extent_changeset changeset;
3825 extent_changeset_init(&changeset);
3826 len = round_up(start + len, root->fs_info->sectorsize);
3827 start = round_down(start, root->fs_info->sectorsize);
3829 ULIST_ITER_INIT(&uiter);
3830 while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
3831 u64 range_start = unode->val;
3832 /* unode->aux is the inclusive end */
3833 u64 range_len = unode->aux - range_start + 1;
3837 extent_changeset_release(&changeset);
3839 /* Only free range in range [start, start + len) */
3840 if (range_start >= start + len ||
3841 range_start + range_len <= start)
3843 free_start = max(range_start, start);
3844 free_len = min(start + len, range_start + range_len) -
3847 * TODO: To also modify reserved->ranges_reserved to reflect
3850 * However as long as we free qgroup reserved according to
3851 * EXTENT_QGROUP_RESERVED, we won't double free.
3852 * So not need to rush.
3854 ret = clear_record_extent_bits(&inode->io_tree, free_start,
3855 free_start + free_len - 1,
3856 EXTENT_QGROUP_RESERVED, &changeset);
3859 freed += changeset.bytes_changed;
3861 btrfs_qgroup_free_refroot(root->fs_info, root->root_key.objectid, freed,
3862 BTRFS_QGROUP_RSV_DATA);
3865 extent_changeset_release(&changeset);
3869 static int __btrfs_qgroup_release_data(struct btrfs_inode *inode,
3870 struct extent_changeset *reserved, u64 start, u64 len,
3873 struct extent_changeset changeset;
3874 int trace_op = QGROUP_RELEASE;
3877 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &inode->root->fs_info->flags))
3880 /* In release case, we shouldn't have @reserved */
3881 WARN_ON(!free && reserved);
3882 if (free && reserved)
3883 return qgroup_free_reserved_data(inode, reserved, start, len);
3884 extent_changeset_init(&changeset);
3885 ret = clear_record_extent_bits(&inode->io_tree, start, start + len -1,
3886 EXTENT_QGROUP_RESERVED, &changeset);
3891 trace_op = QGROUP_FREE;
3892 trace_btrfs_qgroup_release_data(&inode->vfs_inode, start, len,
3893 changeset.bytes_changed, trace_op);
3895 btrfs_qgroup_free_refroot(inode->root->fs_info,
3896 inode->root->root_key.objectid,
3897 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
3898 ret = changeset.bytes_changed;
3900 extent_changeset_release(&changeset);
3905 * Free a reserved space range from io_tree and related qgroups
3907 * Should be called when a range of pages get invalidated before reaching disk.
3908 * Or for error cleanup case.
3909 * if @reserved is given, only reserved range in [@start, @start + @len) will
3912 * For data written to disk, use btrfs_qgroup_release_data().
3914 * NOTE: This function may sleep for memory allocation.
3916 int btrfs_qgroup_free_data(struct btrfs_inode *inode,
3917 struct extent_changeset *reserved, u64 start, u64 len)
3919 return __btrfs_qgroup_release_data(inode, reserved, start, len, 1);
3923 * Release a reserved space range from io_tree only.
3925 * Should be called when a range of pages get written to disk and corresponding
3926 * FILE_EXTENT is inserted into corresponding root.
3928 * Since new qgroup accounting framework will only update qgroup numbers at
3929 * commit_transaction() time, its reserved space shouldn't be freed from
3932 * But we should release the range from io_tree, to allow further write to be
3935 * NOTE: This function may sleep for memory allocation.
3937 int btrfs_qgroup_release_data(struct btrfs_inode *inode, u64 start, u64 len)
3939 return __btrfs_qgroup_release_data(inode, NULL, start, len, 0);
3942 static void add_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3943 enum btrfs_qgroup_rsv_type type)
3945 if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3946 type != BTRFS_QGROUP_RSV_META_PERTRANS)
3951 spin_lock(&root->qgroup_meta_rsv_lock);
3952 if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
3953 root->qgroup_meta_rsv_prealloc += num_bytes;
3955 root->qgroup_meta_rsv_pertrans += num_bytes;
3956 spin_unlock(&root->qgroup_meta_rsv_lock);
3959 static int sub_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3960 enum btrfs_qgroup_rsv_type type)
3962 if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3963 type != BTRFS_QGROUP_RSV_META_PERTRANS)
3968 spin_lock(&root->qgroup_meta_rsv_lock);
3969 if (type == BTRFS_QGROUP_RSV_META_PREALLOC) {
3970 num_bytes = min_t(u64, root->qgroup_meta_rsv_prealloc,
3972 root->qgroup_meta_rsv_prealloc -= num_bytes;
3974 num_bytes = min_t(u64, root->qgroup_meta_rsv_pertrans,
3976 root->qgroup_meta_rsv_pertrans -= num_bytes;
3978 spin_unlock(&root->qgroup_meta_rsv_lock);
3982 int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
3983 enum btrfs_qgroup_rsv_type type, bool enforce)
3985 struct btrfs_fs_info *fs_info = root->fs_info;
3988 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3989 !is_fstree(root->root_key.objectid) || num_bytes == 0)
3992 BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3993 trace_qgroup_meta_reserve(root, (s64)num_bytes, type);
3994 ret = qgroup_reserve(root, num_bytes, enforce, type);
3998 * Record what we have reserved into root.
4000 * To avoid quota disabled->enabled underflow.
4001 * In that case, we may try to free space we haven't reserved
4002 * (since quota was disabled), so record what we reserved into root.
4003 * And ensure later release won't underflow this number.
4005 add_root_meta_rsv(root, num_bytes, type);
4009 int __btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
4010 enum btrfs_qgroup_rsv_type type, bool enforce)
4014 ret = btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4015 if (ret <= 0 && ret != -EDQUOT)
4018 ret = try_flush_qgroup(root);
4021 return btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4024 void btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root *root)
4026 struct btrfs_fs_info *fs_info = root->fs_info;
4028 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4029 !is_fstree(root->root_key.objectid))
4032 /* TODO: Update trace point to handle such free */
4033 trace_qgroup_meta_free_all_pertrans(root);
4034 /* Special value -1 means to free all reserved space */
4035 btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid, (u64)-1,
4036 BTRFS_QGROUP_RSV_META_PERTRANS);
4039 void __btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes,
4040 enum btrfs_qgroup_rsv_type type)
4042 struct btrfs_fs_info *fs_info = root->fs_info;
4044 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4045 !is_fstree(root->root_key.objectid))
4049 * reservation for META_PREALLOC can happen before quota is enabled,
4050 * which can lead to underflow.
4051 * Here ensure we will only free what we really have reserved.
4053 num_bytes = sub_root_meta_rsv(root, num_bytes, type);
4054 BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4055 trace_qgroup_meta_reserve(root, -(s64)num_bytes, type);
4056 btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid,
4060 static void qgroup_convert_meta(struct btrfs_fs_info *fs_info, u64 ref_root,
4063 struct btrfs_qgroup *qgroup;
4064 struct ulist_node *unode;
4065 struct ulist_iterator uiter;
4070 if (!fs_info->quota_root)
4073 spin_lock(&fs_info->qgroup_lock);
4074 qgroup = find_qgroup_rb(fs_info, ref_root);
4077 ulist_reinit(fs_info->qgroup_ulist);
4078 ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
4079 qgroup_to_aux(qgroup), GFP_ATOMIC);
4082 ULIST_ITER_INIT(&uiter);
4083 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
4084 struct btrfs_qgroup *qg;
4085 struct btrfs_qgroup_list *glist;
4087 qg = unode_aux_to_qgroup(unode);
4089 qgroup_rsv_release(fs_info, qg, num_bytes,
4090 BTRFS_QGROUP_RSV_META_PREALLOC);
4091 qgroup_rsv_add(fs_info, qg, num_bytes,
4092 BTRFS_QGROUP_RSV_META_PERTRANS);
4093 list_for_each_entry(glist, &qg->groups, next_group) {
4094 ret = ulist_add(fs_info->qgroup_ulist,
4095 glist->group->qgroupid,
4096 qgroup_to_aux(glist->group), GFP_ATOMIC);
4102 spin_unlock(&fs_info->qgroup_lock);
4105 void btrfs_qgroup_convert_reserved_meta(struct btrfs_root *root, int num_bytes)
4107 struct btrfs_fs_info *fs_info = root->fs_info;
4109 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4110 !is_fstree(root->root_key.objectid))
4112 /* Same as btrfs_qgroup_free_meta_prealloc() */
4113 num_bytes = sub_root_meta_rsv(root, num_bytes,
4114 BTRFS_QGROUP_RSV_META_PREALLOC);
4115 trace_qgroup_meta_convert(root, num_bytes);
4116 qgroup_convert_meta(fs_info, root->root_key.objectid, num_bytes);
4117 if (!sb_rdonly(fs_info->sb))
4118 add_root_meta_rsv(root, num_bytes, BTRFS_QGROUP_RSV_META_PERTRANS);
4122 * Check qgroup reserved space leaking, normally at destroy inode
4125 void btrfs_qgroup_check_reserved_leak(struct btrfs_inode *inode)
4127 struct extent_changeset changeset;
4128 struct ulist_node *unode;
4129 struct ulist_iterator iter;
4132 extent_changeset_init(&changeset);
4133 ret = clear_record_extent_bits(&inode->io_tree, 0, (u64)-1,
4134 EXTENT_QGROUP_RESERVED, &changeset);
4137 if (WARN_ON(changeset.bytes_changed)) {
4138 ULIST_ITER_INIT(&iter);
4139 while ((unode = ulist_next(&changeset.range_changed, &iter))) {
4140 btrfs_warn(inode->root->fs_info,
4141 "leaking qgroup reserved space, ino: %llu, start: %llu, end: %llu",
4142 btrfs_ino(inode), unode->val, unode->aux);
4144 btrfs_qgroup_free_refroot(inode->root->fs_info,
4145 inode->root->root_key.objectid,
4146 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
4149 extent_changeset_release(&changeset);
4152 void btrfs_qgroup_init_swapped_blocks(
4153 struct btrfs_qgroup_swapped_blocks *swapped_blocks)
4157 spin_lock_init(&swapped_blocks->lock);
4158 for (i = 0; i < BTRFS_MAX_LEVEL; i++)
4159 swapped_blocks->blocks[i] = RB_ROOT;
4160 swapped_blocks->swapped = false;
4164 * Delete all swapped blocks record of @root.
4165 * Every record here means we skipped a full subtree scan for qgroup.
4167 * Gets called when committing one transaction.
4169 void btrfs_qgroup_clean_swapped_blocks(struct btrfs_root *root)
4171 struct btrfs_qgroup_swapped_blocks *swapped_blocks;
4174 swapped_blocks = &root->swapped_blocks;
4176 spin_lock(&swapped_blocks->lock);
4177 if (!swapped_blocks->swapped)
4179 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4180 struct rb_root *cur_root = &swapped_blocks->blocks[i];
4181 struct btrfs_qgroup_swapped_block *entry;
4182 struct btrfs_qgroup_swapped_block *next;
4184 rbtree_postorder_for_each_entry_safe(entry, next, cur_root,
4187 swapped_blocks->blocks[i] = RB_ROOT;
4189 swapped_blocks->swapped = false;
4191 spin_unlock(&swapped_blocks->lock);
4195 * Add subtree roots record into @subvol_root.
4197 * @subvol_root: tree root of the subvolume tree get swapped
4198 * @bg: block group under balance
4199 * @subvol_parent/slot: pointer to the subtree root in subvolume tree
4200 * @reloc_parent/slot: pointer to the subtree root in reloc tree
4201 * BOTH POINTERS ARE BEFORE TREE SWAP
4202 * @last_snapshot: last snapshot generation of the subvolume tree
4204 int btrfs_qgroup_add_swapped_blocks(struct btrfs_trans_handle *trans,
4205 struct btrfs_root *subvol_root,
4206 struct btrfs_block_group *bg,
4207 struct extent_buffer *subvol_parent, int subvol_slot,
4208 struct extent_buffer *reloc_parent, int reloc_slot,
4211 struct btrfs_fs_info *fs_info = subvol_root->fs_info;
4212 struct btrfs_qgroup_swapped_blocks *blocks = &subvol_root->swapped_blocks;
4213 struct btrfs_qgroup_swapped_block *block;
4214 struct rb_node **cur;
4215 struct rb_node *parent = NULL;
4216 int level = btrfs_header_level(subvol_parent) - 1;
4219 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4222 if (btrfs_node_ptr_generation(subvol_parent, subvol_slot) >
4223 btrfs_node_ptr_generation(reloc_parent, reloc_slot)) {
4224 btrfs_err_rl(fs_info,
4225 "%s: bad parameter order, subvol_gen=%llu reloc_gen=%llu",
4227 btrfs_node_ptr_generation(subvol_parent, subvol_slot),
4228 btrfs_node_ptr_generation(reloc_parent, reloc_slot));
4232 block = kmalloc(sizeof(*block), GFP_NOFS);
4239 * @reloc_parent/slot is still before swap, while @block is going to
4240 * record the bytenr after swap, so we do the swap here.
4242 block->subvol_bytenr = btrfs_node_blockptr(reloc_parent, reloc_slot);
4243 block->subvol_generation = btrfs_node_ptr_generation(reloc_parent,
4245 block->reloc_bytenr = btrfs_node_blockptr(subvol_parent, subvol_slot);
4246 block->reloc_generation = btrfs_node_ptr_generation(subvol_parent,
4248 block->last_snapshot = last_snapshot;
4249 block->level = level;
4252 * If we have bg == NULL, we're called from btrfs_recover_relocation(),
4253 * no one else can modify tree blocks thus we qgroup will not change
4254 * no matter the value of trace_leaf.
4256 if (bg && bg->flags & BTRFS_BLOCK_GROUP_DATA)
4257 block->trace_leaf = true;
4259 block->trace_leaf = false;
4260 btrfs_node_key_to_cpu(reloc_parent, &block->first_key, reloc_slot);
4262 /* Insert @block into @blocks */
4263 spin_lock(&blocks->lock);
4264 cur = &blocks->blocks[level].rb_node;
4266 struct btrfs_qgroup_swapped_block *entry;
4269 entry = rb_entry(parent, struct btrfs_qgroup_swapped_block,
4272 if (entry->subvol_bytenr < block->subvol_bytenr) {
4273 cur = &(*cur)->rb_left;
4274 } else if (entry->subvol_bytenr > block->subvol_bytenr) {
4275 cur = &(*cur)->rb_right;
4277 if (entry->subvol_generation !=
4278 block->subvol_generation ||
4279 entry->reloc_bytenr != block->reloc_bytenr ||
4280 entry->reloc_generation !=
4281 block->reloc_generation) {
4283 * Duplicated but mismatch entry found.
4286 * Marking qgroup inconsistent should be enough
4289 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4296 rb_link_node(&block->node, parent, cur);
4297 rb_insert_color(&block->node, &blocks->blocks[level]);
4298 blocks->swapped = true;
4300 spin_unlock(&blocks->lock);
4303 fs_info->qgroup_flags |=
4304 BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
4309 * Check if the tree block is a subtree root, and if so do the needed
4310 * delayed subtree trace for qgroup.
4312 * This is called during btrfs_cow_block().
4314 int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans,
4315 struct btrfs_root *root,
4316 struct extent_buffer *subvol_eb)
4318 struct btrfs_fs_info *fs_info = root->fs_info;
4319 struct btrfs_qgroup_swapped_blocks *blocks = &root->swapped_blocks;
4320 struct btrfs_qgroup_swapped_block *block;
4321 struct extent_buffer *reloc_eb = NULL;
4322 struct rb_node *node;
4324 bool swapped = false;
4325 int level = btrfs_header_level(subvol_eb);
4329 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4331 if (!is_fstree(root->root_key.objectid) || !root->reloc_root)
4334 spin_lock(&blocks->lock);
4335 if (!blocks->swapped) {
4336 spin_unlock(&blocks->lock);
4339 node = blocks->blocks[level].rb_node;
4342 block = rb_entry(node, struct btrfs_qgroup_swapped_block, node);
4343 if (block->subvol_bytenr < subvol_eb->start) {
4344 node = node->rb_left;
4345 } else if (block->subvol_bytenr > subvol_eb->start) {
4346 node = node->rb_right;
4353 spin_unlock(&blocks->lock);
4356 /* Found one, remove it from @blocks first and update blocks->swapped */
4357 rb_erase(&block->node, &blocks->blocks[level]);
4358 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4359 if (RB_EMPTY_ROOT(&blocks->blocks[i])) {
4364 blocks->swapped = swapped;
4365 spin_unlock(&blocks->lock);
4367 /* Read out reloc subtree root */
4368 reloc_eb = read_tree_block(fs_info, block->reloc_bytenr,
4369 block->reloc_generation, block->level,
4371 if (IS_ERR(reloc_eb)) {
4372 ret = PTR_ERR(reloc_eb);
4376 if (!extent_buffer_uptodate(reloc_eb)) {
4381 ret = qgroup_trace_subtree_swap(trans, reloc_eb, subvol_eb,
4382 block->last_snapshot, block->trace_leaf);
4385 free_extent_buffer(reloc_eb);
4388 btrfs_err_rl(fs_info,
4389 "failed to account subtree at bytenr %llu: %d",
4390 subvol_eb->start, ret);
4391 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
4396 void btrfs_qgroup_destroy_extent_records(struct btrfs_transaction *trans)
4398 struct btrfs_qgroup_extent_record *entry;
4399 struct btrfs_qgroup_extent_record *next;
4400 struct rb_root *root;
4402 root = &trans->delayed_refs.dirty_extent_root;
4403 rbtree_postorder_for_each_entry_safe(entry, next, root, node) {
4404 ulist_free(entry->old_roots);