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"
26 #include "tree-mod-log.h"
29 * Helpers to access qgroup reservation
31 * Callers should ensure the lock context and type are valid
34 static u64 qgroup_rsv_total(const struct btrfs_qgroup *qgroup)
39 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
40 ret += qgroup->rsv.values[i];
45 #ifdef CONFIG_BTRFS_DEBUG
46 static const char *qgroup_rsv_type_str(enum btrfs_qgroup_rsv_type type)
48 if (type == BTRFS_QGROUP_RSV_DATA)
50 if (type == BTRFS_QGROUP_RSV_META_PERTRANS)
51 return "meta_pertrans";
52 if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
53 return "meta_prealloc";
58 static void qgroup_rsv_add(struct btrfs_fs_info *fs_info,
59 struct btrfs_qgroup *qgroup, u64 num_bytes,
60 enum btrfs_qgroup_rsv_type type)
62 trace_qgroup_update_reserve(fs_info, qgroup, num_bytes, type);
63 qgroup->rsv.values[type] += num_bytes;
66 static void qgroup_rsv_release(struct btrfs_fs_info *fs_info,
67 struct btrfs_qgroup *qgroup, u64 num_bytes,
68 enum btrfs_qgroup_rsv_type type)
70 trace_qgroup_update_reserve(fs_info, qgroup, -(s64)num_bytes, type);
71 if (qgroup->rsv.values[type] >= num_bytes) {
72 qgroup->rsv.values[type] -= num_bytes;
75 #ifdef CONFIG_BTRFS_DEBUG
77 "qgroup %llu %s reserved space underflow, have %llu to free %llu",
78 qgroup->qgroupid, qgroup_rsv_type_str(type),
79 qgroup->rsv.values[type], num_bytes);
81 qgroup->rsv.values[type] = 0;
84 static void qgroup_rsv_add_by_qgroup(struct btrfs_fs_info *fs_info,
85 struct btrfs_qgroup *dest,
86 struct btrfs_qgroup *src)
90 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
91 qgroup_rsv_add(fs_info, dest, src->rsv.values[i], i);
94 static void qgroup_rsv_release_by_qgroup(struct btrfs_fs_info *fs_info,
95 struct btrfs_qgroup *dest,
96 struct btrfs_qgroup *src)
100 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
101 qgroup_rsv_release(fs_info, dest, src->rsv.values[i], i);
104 static void btrfs_qgroup_update_old_refcnt(struct btrfs_qgroup *qg, u64 seq,
107 if (qg->old_refcnt < seq)
108 qg->old_refcnt = seq;
109 qg->old_refcnt += mod;
112 static void btrfs_qgroup_update_new_refcnt(struct btrfs_qgroup *qg, u64 seq,
115 if (qg->new_refcnt < seq)
116 qg->new_refcnt = seq;
117 qg->new_refcnt += mod;
120 static inline u64 btrfs_qgroup_get_old_refcnt(struct btrfs_qgroup *qg, u64 seq)
122 if (qg->old_refcnt < seq)
124 return qg->old_refcnt - seq;
127 static inline u64 btrfs_qgroup_get_new_refcnt(struct btrfs_qgroup *qg, u64 seq)
129 if (qg->new_refcnt < seq)
131 return qg->new_refcnt - seq;
135 * glue structure to represent the relations between qgroups.
137 struct btrfs_qgroup_list {
138 struct list_head next_group;
139 struct list_head next_member;
140 struct btrfs_qgroup *group;
141 struct btrfs_qgroup *member;
144 static inline u64 qgroup_to_aux(struct btrfs_qgroup *qg)
146 return (u64)(uintptr_t)qg;
149 static inline struct btrfs_qgroup* unode_aux_to_qgroup(struct ulist_node *n)
151 return (struct btrfs_qgroup *)(uintptr_t)n->aux;
155 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
157 static void qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info);
159 /* must be called with qgroup_ioctl_lock held */
160 static struct btrfs_qgroup *find_qgroup_rb(struct btrfs_fs_info *fs_info,
163 struct rb_node *n = fs_info->qgroup_tree.rb_node;
164 struct btrfs_qgroup *qgroup;
167 qgroup = rb_entry(n, struct btrfs_qgroup, node);
168 if (qgroup->qgroupid < qgroupid)
170 else if (qgroup->qgroupid > qgroupid)
178 /* must be called with qgroup_lock held */
179 static struct btrfs_qgroup *add_qgroup_rb(struct btrfs_fs_info *fs_info,
182 struct rb_node **p = &fs_info->qgroup_tree.rb_node;
183 struct rb_node *parent = NULL;
184 struct btrfs_qgroup *qgroup;
188 qgroup = rb_entry(parent, struct btrfs_qgroup, node);
190 if (qgroup->qgroupid < qgroupid)
192 else if (qgroup->qgroupid > qgroupid)
198 qgroup = kzalloc(sizeof(*qgroup), GFP_ATOMIC);
200 return ERR_PTR(-ENOMEM);
202 qgroup->qgroupid = qgroupid;
203 INIT_LIST_HEAD(&qgroup->groups);
204 INIT_LIST_HEAD(&qgroup->members);
205 INIT_LIST_HEAD(&qgroup->dirty);
207 rb_link_node(&qgroup->node, parent, p);
208 rb_insert_color(&qgroup->node, &fs_info->qgroup_tree);
213 static void __del_qgroup_rb(struct btrfs_fs_info *fs_info,
214 struct btrfs_qgroup *qgroup)
216 struct btrfs_qgroup_list *list;
218 list_del(&qgroup->dirty);
219 while (!list_empty(&qgroup->groups)) {
220 list = list_first_entry(&qgroup->groups,
221 struct btrfs_qgroup_list, next_group);
222 list_del(&list->next_group);
223 list_del(&list->next_member);
227 while (!list_empty(&qgroup->members)) {
228 list = list_first_entry(&qgroup->members,
229 struct btrfs_qgroup_list, next_member);
230 list_del(&list->next_group);
231 list_del(&list->next_member);
236 /* must be called with qgroup_lock held */
237 static int del_qgroup_rb(struct btrfs_fs_info *fs_info, u64 qgroupid)
239 struct btrfs_qgroup *qgroup = find_qgroup_rb(fs_info, qgroupid);
244 rb_erase(&qgroup->node, &fs_info->qgroup_tree);
245 __del_qgroup_rb(fs_info, qgroup);
250 * Add relation specified by two qgroups.
252 * Must be called with qgroup_lock held.
254 * Return: 0 on success
255 * -ENOENT if one of the qgroups is NULL
258 static int __add_relation_rb(struct btrfs_qgroup *member, struct btrfs_qgroup *parent)
260 struct btrfs_qgroup_list *list;
262 if (!member || !parent)
265 list = kzalloc(sizeof(*list), GFP_ATOMIC);
269 list->group = parent;
270 list->member = member;
271 list_add_tail(&list->next_group, &member->groups);
272 list_add_tail(&list->next_member, &parent->members);
278 * Add relation specified by two qgroup ids.
280 * Must be called with qgroup_lock held.
282 * Return: 0 on success
283 * -ENOENT if one of the ids does not exist
286 static int add_relation_rb(struct btrfs_fs_info *fs_info, u64 memberid, u64 parentid)
288 struct btrfs_qgroup *member;
289 struct btrfs_qgroup *parent;
291 member = find_qgroup_rb(fs_info, memberid);
292 parent = find_qgroup_rb(fs_info, parentid);
294 return __add_relation_rb(member, parent);
297 /* Must be called with qgroup_lock held */
298 static int del_relation_rb(struct btrfs_fs_info *fs_info,
299 u64 memberid, u64 parentid)
301 struct btrfs_qgroup *member;
302 struct btrfs_qgroup *parent;
303 struct btrfs_qgroup_list *list;
305 member = find_qgroup_rb(fs_info, memberid);
306 parent = find_qgroup_rb(fs_info, parentid);
307 if (!member || !parent)
310 list_for_each_entry(list, &member->groups, next_group) {
311 if (list->group == parent) {
312 list_del(&list->next_group);
313 list_del(&list->next_member);
321 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
322 int btrfs_verify_qgroup_counts(struct btrfs_fs_info *fs_info, u64 qgroupid,
325 struct btrfs_qgroup *qgroup;
327 qgroup = find_qgroup_rb(fs_info, qgroupid);
330 if (qgroup->rfer != rfer || qgroup->excl != excl)
336 static void qgroup_mark_inconsistent(struct btrfs_fs_info *fs_info)
338 fs_info->qgroup_flags |= (BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT |
339 BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN |
340 BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING);
344 * The full config is read in one go, only called from open_ctree()
345 * It doesn't use any locking, as at this point we're still single-threaded
347 int btrfs_read_qgroup_config(struct btrfs_fs_info *fs_info)
349 struct btrfs_key key;
350 struct btrfs_key found_key;
351 struct btrfs_root *quota_root = fs_info->quota_root;
352 struct btrfs_path *path = NULL;
353 struct extent_buffer *l;
357 u64 rescan_progress = 0;
359 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
362 fs_info->qgroup_ulist = ulist_alloc(GFP_KERNEL);
363 if (!fs_info->qgroup_ulist) {
368 path = btrfs_alloc_path();
374 ret = btrfs_sysfs_add_qgroups(fs_info);
377 /* default this to quota off, in case no status key is found */
378 fs_info->qgroup_flags = 0;
381 * pass 1: read status, all qgroup infos and limits
386 ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 1);
391 struct btrfs_qgroup *qgroup;
393 slot = path->slots[0];
395 btrfs_item_key_to_cpu(l, &found_key, slot);
397 if (found_key.type == BTRFS_QGROUP_STATUS_KEY) {
398 struct btrfs_qgroup_status_item *ptr;
400 ptr = btrfs_item_ptr(l, slot,
401 struct btrfs_qgroup_status_item);
403 if (btrfs_qgroup_status_version(l, ptr) !=
404 BTRFS_QGROUP_STATUS_VERSION) {
406 "old qgroup version, quota disabled");
409 if (btrfs_qgroup_status_generation(l, ptr) !=
410 fs_info->generation) {
411 qgroup_mark_inconsistent(fs_info);
413 "qgroup generation mismatch, marked as inconsistent");
415 fs_info->qgroup_flags = btrfs_qgroup_status_flags(l,
417 rescan_progress = btrfs_qgroup_status_rescan(l, ptr);
421 if (found_key.type != BTRFS_QGROUP_INFO_KEY &&
422 found_key.type != BTRFS_QGROUP_LIMIT_KEY)
425 qgroup = find_qgroup_rb(fs_info, found_key.offset);
426 if ((qgroup && found_key.type == BTRFS_QGROUP_INFO_KEY) ||
427 (!qgroup && found_key.type == BTRFS_QGROUP_LIMIT_KEY)) {
428 btrfs_err(fs_info, "inconsistent qgroup config");
429 qgroup_mark_inconsistent(fs_info);
432 qgroup = add_qgroup_rb(fs_info, found_key.offset);
433 if (IS_ERR(qgroup)) {
434 ret = PTR_ERR(qgroup);
438 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
442 switch (found_key.type) {
443 case BTRFS_QGROUP_INFO_KEY: {
444 struct btrfs_qgroup_info_item *ptr;
446 ptr = btrfs_item_ptr(l, slot,
447 struct btrfs_qgroup_info_item);
448 qgroup->rfer = btrfs_qgroup_info_rfer(l, ptr);
449 qgroup->rfer_cmpr = btrfs_qgroup_info_rfer_cmpr(l, ptr);
450 qgroup->excl = btrfs_qgroup_info_excl(l, ptr);
451 qgroup->excl_cmpr = btrfs_qgroup_info_excl_cmpr(l, ptr);
452 /* generation currently unused */
455 case BTRFS_QGROUP_LIMIT_KEY: {
456 struct btrfs_qgroup_limit_item *ptr;
458 ptr = btrfs_item_ptr(l, slot,
459 struct btrfs_qgroup_limit_item);
460 qgroup->lim_flags = btrfs_qgroup_limit_flags(l, ptr);
461 qgroup->max_rfer = btrfs_qgroup_limit_max_rfer(l, ptr);
462 qgroup->max_excl = btrfs_qgroup_limit_max_excl(l, ptr);
463 qgroup->rsv_rfer = btrfs_qgroup_limit_rsv_rfer(l, ptr);
464 qgroup->rsv_excl = btrfs_qgroup_limit_rsv_excl(l, ptr);
469 ret = btrfs_next_item(quota_root, path);
475 btrfs_release_path(path);
478 * pass 2: read all qgroup relations
481 key.type = BTRFS_QGROUP_RELATION_KEY;
483 ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 0);
487 slot = path->slots[0];
489 btrfs_item_key_to_cpu(l, &found_key, slot);
491 if (found_key.type != BTRFS_QGROUP_RELATION_KEY)
494 if (found_key.objectid > found_key.offset) {
495 /* parent <- member, not needed to build config */
496 /* FIXME should we omit the key completely? */
500 ret = add_relation_rb(fs_info, found_key.objectid,
502 if (ret == -ENOENT) {
504 "orphan qgroup relation 0x%llx->0x%llx",
505 found_key.objectid, found_key.offset);
506 ret = 0; /* ignore the error */
511 ret = btrfs_next_item(quota_root, path);
518 btrfs_free_path(path);
519 fs_info->qgroup_flags |= flags;
520 if (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))
521 clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
522 else if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN &&
524 ret = qgroup_rescan_init(fs_info, rescan_progress, 0);
527 ulist_free(fs_info->qgroup_ulist);
528 fs_info->qgroup_ulist = NULL;
529 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
530 btrfs_sysfs_del_qgroups(fs_info);
533 return ret < 0 ? ret : 0;
537 * Called in close_ctree() when quota is still enabled. This verifies we don't
538 * leak some reserved space.
540 * Return false if no reserved space is left.
541 * Return true if some reserved space is leaked.
543 bool btrfs_check_quota_leak(struct btrfs_fs_info *fs_info)
545 struct rb_node *node;
548 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
551 * Since we're unmounting, there is no race and no need to grab qgroup
552 * lock. And here we don't go post-order to provide a more user
553 * friendly sorted result.
555 for (node = rb_first(&fs_info->qgroup_tree); node; node = rb_next(node)) {
556 struct btrfs_qgroup *qgroup;
559 qgroup = rb_entry(node, struct btrfs_qgroup, node);
560 for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++) {
561 if (qgroup->rsv.values[i]) {
564 "qgroup %hu/%llu has unreleased space, type %d rsv %llu",
565 btrfs_qgroup_level(qgroup->qgroupid),
566 btrfs_qgroup_subvolid(qgroup->qgroupid),
567 i, qgroup->rsv.values[i]);
575 * This is called from close_ctree() or open_ctree() or btrfs_quota_disable(),
576 * first two are in single-threaded paths.And for the third one, we have set
577 * quota_root to be null with qgroup_lock held before, so it is safe to clean
578 * up the in-memory structures without qgroup_lock held.
580 void btrfs_free_qgroup_config(struct btrfs_fs_info *fs_info)
583 struct btrfs_qgroup *qgroup;
585 while ((n = rb_first(&fs_info->qgroup_tree))) {
586 qgroup = rb_entry(n, struct btrfs_qgroup, node);
587 rb_erase(n, &fs_info->qgroup_tree);
588 __del_qgroup_rb(fs_info, qgroup);
589 btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
593 * We call btrfs_free_qgroup_config() when unmounting
594 * filesystem and disabling quota, so we set qgroup_ulist
595 * to be null here to avoid double free.
597 ulist_free(fs_info->qgroup_ulist);
598 fs_info->qgroup_ulist = NULL;
599 btrfs_sysfs_del_qgroups(fs_info);
602 static int add_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
606 struct btrfs_root *quota_root = trans->fs_info->quota_root;
607 struct btrfs_path *path;
608 struct btrfs_key key;
610 path = btrfs_alloc_path();
615 key.type = BTRFS_QGROUP_RELATION_KEY;
618 ret = btrfs_insert_empty_item(trans, quota_root, path, &key, 0);
620 btrfs_mark_buffer_dirty(path->nodes[0]);
622 btrfs_free_path(path);
626 static int del_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
630 struct btrfs_root *quota_root = trans->fs_info->quota_root;
631 struct btrfs_path *path;
632 struct btrfs_key key;
634 path = btrfs_alloc_path();
639 key.type = BTRFS_QGROUP_RELATION_KEY;
642 ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
651 ret = btrfs_del_item(trans, quota_root, path);
653 btrfs_free_path(path);
657 static int add_qgroup_item(struct btrfs_trans_handle *trans,
658 struct btrfs_root *quota_root, u64 qgroupid)
661 struct btrfs_path *path;
662 struct btrfs_qgroup_info_item *qgroup_info;
663 struct btrfs_qgroup_limit_item *qgroup_limit;
664 struct extent_buffer *leaf;
665 struct btrfs_key key;
667 if (btrfs_is_testing(quota_root->fs_info))
670 path = btrfs_alloc_path();
675 key.type = BTRFS_QGROUP_INFO_KEY;
676 key.offset = qgroupid;
679 * Avoid a transaction abort by catching -EEXIST here. In that
680 * case, we proceed by re-initializing the existing structure
684 ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
685 sizeof(*qgroup_info));
686 if (ret && ret != -EEXIST)
689 leaf = path->nodes[0];
690 qgroup_info = btrfs_item_ptr(leaf, path->slots[0],
691 struct btrfs_qgroup_info_item);
692 btrfs_set_qgroup_info_generation(leaf, qgroup_info, trans->transid);
693 btrfs_set_qgroup_info_rfer(leaf, qgroup_info, 0);
694 btrfs_set_qgroup_info_rfer_cmpr(leaf, qgroup_info, 0);
695 btrfs_set_qgroup_info_excl(leaf, qgroup_info, 0);
696 btrfs_set_qgroup_info_excl_cmpr(leaf, qgroup_info, 0);
698 btrfs_mark_buffer_dirty(leaf);
700 btrfs_release_path(path);
702 key.type = BTRFS_QGROUP_LIMIT_KEY;
703 ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
704 sizeof(*qgroup_limit));
705 if (ret && ret != -EEXIST)
708 leaf = path->nodes[0];
709 qgroup_limit = btrfs_item_ptr(leaf, path->slots[0],
710 struct btrfs_qgroup_limit_item);
711 btrfs_set_qgroup_limit_flags(leaf, qgroup_limit, 0);
712 btrfs_set_qgroup_limit_max_rfer(leaf, qgroup_limit, 0);
713 btrfs_set_qgroup_limit_max_excl(leaf, qgroup_limit, 0);
714 btrfs_set_qgroup_limit_rsv_rfer(leaf, qgroup_limit, 0);
715 btrfs_set_qgroup_limit_rsv_excl(leaf, qgroup_limit, 0);
717 btrfs_mark_buffer_dirty(leaf);
721 btrfs_free_path(path);
725 static int del_qgroup_item(struct btrfs_trans_handle *trans, u64 qgroupid)
728 struct btrfs_root *quota_root = trans->fs_info->quota_root;
729 struct btrfs_path *path;
730 struct btrfs_key key;
732 path = btrfs_alloc_path();
737 key.type = BTRFS_QGROUP_INFO_KEY;
738 key.offset = qgroupid;
739 ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
748 ret = btrfs_del_item(trans, quota_root, path);
752 btrfs_release_path(path);
754 key.type = BTRFS_QGROUP_LIMIT_KEY;
755 ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
764 ret = btrfs_del_item(trans, quota_root, path);
767 btrfs_free_path(path);
771 static int update_qgroup_limit_item(struct btrfs_trans_handle *trans,
772 struct btrfs_qgroup *qgroup)
774 struct btrfs_root *quota_root = trans->fs_info->quota_root;
775 struct btrfs_path *path;
776 struct btrfs_key key;
777 struct extent_buffer *l;
778 struct btrfs_qgroup_limit_item *qgroup_limit;
783 key.type = BTRFS_QGROUP_LIMIT_KEY;
784 key.offset = qgroup->qgroupid;
786 path = btrfs_alloc_path();
790 ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
798 slot = path->slots[0];
799 qgroup_limit = btrfs_item_ptr(l, slot, struct btrfs_qgroup_limit_item);
800 btrfs_set_qgroup_limit_flags(l, qgroup_limit, qgroup->lim_flags);
801 btrfs_set_qgroup_limit_max_rfer(l, qgroup_limit, qgroup->max_rfer);
802 btrfs_set_qgroup_limit_max_excl(l, qgroup_limit, qgroup->max_excl);
803 btrfs_set_qgroup_limit_rsv_rfer(l, qgroup_limit, qgroup->rsv_rfer);
804 btrfs_set_qgroup_limit_rsv_excl(l, qgroup_limit, qgroup->rsv_excl);
806 btrfs_mark_buffer_dirty(l);
809 btrfs_free_path(path);
813 static int update_qgroup_info_item(struct btrfs_trans_handle *trans,
814 struct btrfs_qgroup *qgroup)
816 struct btrfs_fs_info *fs_info = trans->fs_info;
817 struct btrfs_root *quota_root = fs_info->quota_root;
818 struct btrfs_path *path;
819 struct btrfs_key key;
820 struct extent_buffer *l;
821 struct btrfs_qgroup_info_item *qgroup_info;
825 if (btrfs_is_testing(fs_info))
829 key.type = BTRFS_QGROUP_INFO_KEY;
830 key.offset = qgroup->qgroupid;
832 path = btrfs_alloc_path();
836 ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
844 slot = path->slots[0];
845 qgroup_info = btrfs_item_ptr(l, slot, struct btrfs_qgroup_info_item);
846 btrfs_set_qgroup_info_generation(l, qgroup_info, trans->transid);
847 btrfs_set_qgroup_info_rfer(l, qgroup_info, qgroup->rfer);
848 btrfs_set_qgroup_info_rfer_cmpr(l, qgroup_info, qgroup->rfer_cmpr);
849 btrfs_set_qgroup_info_excl(l, qgroup_info, qgroup->excl);
850 btrfs_set_qgroup_info_excl_cmpr(l, qgroup_info, qgroup->excl_cmpr);
852 btrfs_mark_buffer_dirty(l);
855 btrfs_free_path(path);
859 static int update_qgroup_status_item(struct btrfs_trans_handle *trans)
861 struct btrfs_fs_info *fs_info = trans->fs_info;
862 struct btrfs_root *quota_root = fs_info->quota_root;
863 struct btrfs_path *path;
864 struct btrfs_key key;
865 struct extent_buffer *l;
866 struct btrfs_qgroup_status_item *ptr;
871 key.type = BTRFS_QGROUP_STATUS_KEY;
874 path = btrfs_alloc_path();
878 ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
886 slot = path->slots[0];
887 ptr = btrfs_item_ptr(l, slot, struct btrfs_qgroup_status_item);
888 btrfs_set_qgroup_status_flags(l, ptr, fs_info->qgroup_flags &
889 BTRFS_QGROUP_STATUS_FLAGS_MASK);
890 btrfs_set_qgroup_status_generation(l, ptr, trans->transid);
891 btrfs_set_qgroup_status_rescan(l, ptr,
892 fs_info->qgroup_rescan_progress.objectid);
894 btrfs_mark_buffer_dirty(l);
897 btrfs_free_path(path);
902 * called with qgroup_lock held
904 static int btrfs_clean_quota_tree(struct btrfs_trans_handle *trans,
905 struct btrfs_root *root)
907 struct btrfs_path *path;
908 struct btrfs_key key;
909 struct extent_buffer *leaf = NULL;
913 path = btrfs_alloc_path();
922 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
925 leaf = path->nodes[0];
926 nr = btrfs_header_nritems(leaf);
930 * delete the leaf one by one
931 * since the whole tree is going
935 ret = btrfs_del_items(trans, root, path, 0, nr);
939 btrfs_release_path(path);
943 btrfs_free_path(path);
947 int btrfs_quota_enable(struct btrfs_fs_info *fs_info)
949 struct btrfs_root *quota_root;
950 struct btrfs_root *tree_root = fs_info->tree_root;
951 struct btrfs_path *path = NULL;
952 struct btrfs_qgroup_status_item *ptr;
953 struct extent_buffer *leaf;
954 struct btrfs_key key;
955 struct btrfs_key found_key;
956 struct btrfs_qgroup *qgroup = NULL;
957 struct btrfs_trans_handle *trans = NULL;
958 struct ulist *ulist = NULL;
963 * We need to have subvol_sem write locked, to prevent races between
964 * concurrent tasks trying to enable quotas, because we will unlock
965 * and relock qgroup_ioctl_lock before setting fs_info->quota_root
966 * and before setting BTRFS_FS_QUOTA_ENABLED.
968 lockdep_assert_held_write(&fs_info->subvol_sem);
970 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
972 "qgroups are currently unsupported in extent tree v2");
976 mutex_lock(&fs_info->qgroup_ioctl_lock);
977 if (fs_info->quota_root)
980 ulist = ulist_alloc(GFP_KERNEL);
986 ret = btrfs_sysfs_add_qgroups(fs_info);
991 * Unlock qgroup_ioctl_lock before starting the transaction. This is to
992 * avoid lock acquisition inversion problems (reported by lockdep) between
993 * qgroup_ioctl_lock and the vfs freeze semaphores, acquired when we
994 * start a transaction.
995 * After we started the transaction lock qgroup_ioctl_lock again and
996 * check if someone else created the quota root in the meanwhile. If so,
997 * just return success and release the transaction handle.
999 * Also we don't need to worry about someone else calling
1000 * btrfs_sysfs_add_qgroups() after we unlock and getting an error because
1001 * that function returns 0 (success) when the sysfs entries already exist.
1003 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1006 * 1 for quota root item
1007 * 1 for BTRFS_QGROUP_STATUS item
1009 * Yet we also need 2*n items for a QGROUP_INFO/QGROUP_LIMIT items
1010 * per subvolume. However those are not currently reserved since it
1011 * would be a lot of overkill.
1013 trans = btrfs_start_transaction(tree_root, 2);
1015 mutex_lock(&fs_info->qgroup_ioctl_lock);
1016 if (IS_ERR(trans)) {
1017 ret = PTR_ERR(trans);
1022 if (fs_info->quota_root)
1025 fs_info->qgroup_ulist = ulist;
1029 * initially create the quota tree
1031 quota_root = btrfs_create_tree(trans, BTRFS_QUOTA_TREE_OBJECTID);
1032 if (IS_ERR(quota_root)) {
1033 ret = PTR_ERR(quota_root);
1034 btrfs_abort_transaction(trans, ret);
1038 path = btrfs_alloc_path();
1041 btrfs_abort_transaction(trans, ret);
1046 key.type = BTRFS_QGROUP_STATUS_KEY;
1049 ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
1052 btrfs_abort_transaction(trans, ret);
1056 leaf = path->nodes[0];
1057 ptr = btrfs_item_ptr(leaf, path->slots[0],
1058 struct btrfs_qgroup_status_item);
1059 btrfs_set_qgroup_status_generation(leaf, ptr, trans->transid);
1060 btrfs_set_qgroup_status_version(leaf, ptr, BTRFS_QGROUP_STATUS_VERSION);
1061 fs_info->qgroup_flags = BTRFS_QGROUP_STATUS_FLAG_ON |
1062 BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1063 btrfs_set_qgroup_status_flags(leaf, ptr, fs_info->qgroup_flags &
1064 BTRFS_QGROUP_STATUS_FLAGS_MASK);
1065 btrfs_set_qgroup_status_rescan(leaf, ptr, 0);
1067 btrfs_mark_buffer_dirty(leaf);
1070 key.type = BTRFS_ROOT_REF_KEY;
1073 btrfs_release_path(path);
1074 ret = btrfs_search_slot_for_read(tree_root, &key, path, 1, 0);
1078 btrfs_abort_transaction(trans, ret);
1083 slot = path->slots[0];
1084 leaf = path->nodes[0];
1085 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1087 if (found_key.type == BTRFS_ROOT_REF_KEY) {
1089 /* Release locks on tree_root before we access quota_root */
1090 btrfs_release_path(path);
1092 ret = add_qgroup_item(trans, quota_root,
1095 btrfs_abort_transaction(trans, ret);
1099 qgroup = add_qgroup_rb(fs_info, found_key.offset);
1100 if (IS_ERR(qgroup)) {
1101 ret = PTR_ERR(qgroup);
1102 btrfs_abort_transaction(trans, ret);
1105 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1107 btrfs_abort_transaction(trans, ret);
1110 ret = btrfs_search_slot_for_read(tree_root, &found_key,
1113 btrfs_abort_transaction(trans, ret);
1118 * Shouldn't happen, but in case it does we
1119 * don't need to do the btrfs_next_item, just
1125 ret = btrfs_next_item(tree_root, path);
1127 btrfs_abort_transaction(trans, ret);
1135 btrfs_release_path(path);
1136 ret = add_qgroup_item(trans, quota_root, BTRFS_FS_TREE_OBJECTID);
1138 btrfs_abort_transaction(trans, ret);
1142 qgroup = add_qgroup_rb(fs_info, BTRFS_FS_TREE_OBJECTID);
1143 if (IS_ERR(qgroup)) {
1144 ret = PTR_ERR(qgroup);
1145 btrfs_abort_transaction(trans, ret);
1148 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1150 btrfs_abort_transaction(trans, ret);
1154 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1156 * Commit the transaction while not holding qgroup_ioctl_lock, to avoid
1157 * a deadlock with tasks concurrently doing other qgroup operations, such
1158 * adding/removing qgroups or adding/deleting qgroup relations for example,
1159 * because all qgroup operations first start or join a transaction and then
1160 * lock the qgroup_ioctl_lock mutex.
1161 * We are safe from a concurrent task trying to enable quotas, by calling
1162 * this function, since we are serialized by fs_info->subvol_sem.
1164 ret = btrfs_commit_transaction(trans);
1166 mutex_lock(&fs_info->qgroup_ioctl_lock);
1171 * Set quota enabled flag after committing the transaction, to avoid
1172 * deadlocks on fs_info->qgroup_ioctl_lock with concurrent snapshot
1175 spin_lock(&fs_info->qgroup_lock);
1176 fs_info->quota_root = quota_root;
1177 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1178 spin_unlock(&fs_info->qgroup_lock);
1180 ret = qgroup_rescan_init(fs_info, 0, 1);
1182 qgroup_rescan_zero_tracking(fs_info);
1183 fs_info->qgroup_rescan_running = true;
1184 btrfs_queue_work(fs_info->qgroup_rescan_workers,
1185 &fs_info->qgroup_rescan_work);
1188 * We have set both BTRFS_FS_QUOTA_ENABLED and
1189 * BTRFS_QGROUP_STATUS_FLAG_ON, so we can only fail with
1190 * -EINPROGRESS. That can happen because someone started the
1191 * rescan worker by calling quota rescan ioctl before we
1192 * attempted to initialize the rescan worker. Failure due to
1193 * quotas disabled in the meanwhile is not possible, because
1194 * we are holding a write lock on fs_info->subvol_sem, which
1195 * is also acquired when disabling quotas.
1196 * Ignore such error, and any other error would need to undo
1197 * everything we did in the transaction we just committed.
1199 ASSERT(ret == -EINPROGRESS);
1204 btrfs_free_path(path);
1207 btrfs_put_root(quota_root);
1210 ulist_free(fs_info->qgroup_ulist);
1211 fs_info->qgroup_ulist = NULL;
1212 btrfs_sysfs_del_qgroups(fs_info);
1214 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1216 btrfs_end_transaction(trans);
1218 ret = btrfs_end_transaction(trans);
1223 int btrfs_quota_disable(struct btrfs_fs_info *fs_info)
1225 struct btrfs_root *quota_root;
1226 struct btrfs_trans_handle *trans = NULL;
1230 * We need to have subvol_sem write locked to prevent races with
1231 * snapshot creation.
1233 lockdep_assert_held_write(&fs_info->subvol_sem);
1236 * Lock the cleaner mutex to prevent races with concurrent relocation,
1237 * because relocation may be building backrefs for blocks of the quota
1238 * root while we are deleting the root. This is like dropping fs roots
1239 * of deleted snapshots/subvolumes, we need the same protection.
1241 * This also prevents races between concurrent tasks trying to disable
1242 * quotas, because we will unlock and relock qgroup_ioctl_lock across
1243 * BTRFS_FS_QUOTA_ENABLED changes.
1245 mutex_lock(&fs_info->cleaner_mutex);
1247 mutex_lock(&fs_info->qgroup_ioctl_lock);
1248 if (!fs_info->quota_root)
1252 * Unlock the qgroup_ioctl_lock mutex before waiting for the rescan worker to
1253 * complete. Otherwise we can deadlock because btrfs_remove_qgroup() needs
1254 * to lock that mutex while holding a transaction handle and the rescan
1255 * worker needs to commit a transaction.
1257 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1260 * Request qgroup rescan worker to complete and wait for it. This wait
1261 * must be done before transaction start for quota disable since it may
1262 * deadlock with transaction by the qgroup rescan worker.
1264 clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1265 btrfs_qgroup_wait_for_completion(fs_info, false);
1268 * 1 For the root item
1270 * We should also reserve enough items for the quota tree deletion in
1271 * btrfs_clean_quota_tree but this is not done.
1273 * Also, we must always start a transaction without holding the mutex
1274 * qgroup_ioctl_lock, see btrfs_quota_enable().
1276 trans = btrfs_start_transaction(fs_info->tree_root, 1);
1278 mutex_lock(&fs_info->qgroup_ioctl_lock);
1279 if (IS_ERR(trans)) {
1280 ret = PTR_ERR(trans);
1282 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1286 if (!fs_info->quota_root)
1289 spin_lock(&fs_info->qgroup_lock);
1290 quota_root = fs_info->quota_root;
1291 fs_info->quota_root = NULL;
1292 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
1293 fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
1294 spin_unlock(&fs_info->qgroup_lock);
1296 btrfs_free_qgroup_config(fs_info);
1298 ret = btrfs_clean_quota_tree(trans, quota_root);
1300 btrfs_abort_transaction(trans, ret);
1304 ret = btrfs_del_root(trans, "a_root->root_key);
1306 btrfs_abort_transaction(trans, ret);
1310 spin_lock(&fs_info->trans_lock);
1311 list_del("a_root->dirty_list);
1312 spin_unlock(&fs_info->trans_lock);
1314 btrfs_tree_lock(quota_root->node);
1315 btrfs_clean_tree_block(quota_root->node);
1316 btrfs_tree_unlock(quota_root->node);
1317 btrfs_free_tree_block(trans, btrfs_root_id(quota_root),
1318 quota_root->node, 0, 1);
1320 btrfs_put_root(quota_root);
1323 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1325 btrfs_end_transaction(trans);
1327 ret = btrfs_end_transaction(trans);
1328 mutex_unlock(&fs_info->cleaner_mutex);
1333 static void qgroup_dirty(struct btrfs_fs_info *fs_info,
1334 struct btrfs_qgroup *qgroup)
1336 if (list_empty(&qgroup->dirty))
1337 list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1341 * The easy accounting, we're updating qgroup relationship whose child qgroup
1342 * only has exclusive extents.
1344 * In this case, all exclusive extents will also be exclusive for parent, so
1345 * excl/rfer just get added/removed.
1347 * So is qgroup reservation space, which should also be added/removed to
1349 * Or when child tries to release reservation space, parent will underflow its
1350 * reservation (for relationship adding case).
1352 * Caller should hold fs_info->qgroup_lock.
1354 static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
1355 struct ulist *tmp, u64 ref_root,
1356 struct btrfs_qgroup *src, int sign)
1358 struct btrfs_qgroup *qgroup;
1359 struct btrfs_qgroup_list *glist;
1360 struct ulist_node *unode;
1361 struct ulist_iterator uiter;
1362 u64 num_bytes = src->excl;
1365 qgroup = find_qgroup_rb(fs_info, ref_root);
1369 qgroup->rfer += sign * num_bytes;
1370 qgroup->rfer_cmpr += sign * num_bytes;
1372 WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1373 qgroup->excl += sign * num_bytes;
1374 qgroup->excl_cmpr += sign * num_bytes;
1377 qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1379 qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1381 qgroup_dirty(fs_info, qgroup);
1383 /* Get all of the parent groups that contain this qgroup */
1384 list_for_each_entry(glist, &qgroup->groups, next_group) {
1385 ret = ulist_add(tmp, glist->group->qgroupid,
1386 qgroup_to_aux(glist->group), GFP_ATOMIC);
1391 /* Iterate all of the parents and adjust their reference counts */
1392 ULIST_ITER_INIT(&uiter);
1393 while ((unode = ulist_next(tmp, &uiter))) {
1394 qgroup = unode_aux_to_qgroup(unode);
1395 qgroup->rfer += sign * num_bytes;
1396 qgroup->rfer_cmpr += sign * num_bytes;
1397 WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1398 qgroup->excl += sign * num_bytes;
1400 qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1402 qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1403 qgroup->excl_cmpr += sign * num_bytes;
1404 qgroup_dirty(fs_info, qgroup);
1406 /* Add any parents of the parents */
1407 list_for_each_entry(glist, &qgroup->groups, next_group) {
1408 ret = ulist_add(tmp, glist->group->qgroupid,
1409 qgroup_to_aux(glist->group), GFP_ATOMIC);
1421 * Quick path for updating qgroup with only excl refs.
1423 * In that case, just update all parent will be enough.
1424 * Or we needs to do a full rescan.
1425 * Caller should also hold fs_info->qgroup_lock.
1427 * Return 0 for quick update, return >0 for need to full rescan
1428 * and mark INCONSISTENT flag.
1429 * Return < 0 for other error.
1431 static int quick_update_accounting(struct btrfs_fs_info *fs_info,
1432 struct ulist *tmp, u64 src, u64 dst,
1435 struct btrfs_qgroup *qgroup;
1439 qgroup = find_qgroup_rb(fs_info, src);
1442 if (qgroup->excl == qgroup->rfer) {
1444 err = __qgroup_excl_accounting(fs_info, tmp, dst,
1453 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1457 int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1460 struct btrfs_fs_info *fs_info = trans->fs_info;
1461 struct btrfs_qgroup *parent;
1462 struct btrfs_qgroup *member;
1463 struct btrfs_qgroup_list *list;
1465 unsigned int nofs_flag;
1468 /* Check the level of src and dst first */
1469 if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
1472 /* We hold a transaction handle open, must do a NOFS allocation. */
1473 nofs_flag = memalloc_nofs_save();
1474 tmp = ulist_alloc(GFP_KERNEL);
1475 memalloc_nofs_restore(nofs_flag);
1479 mutex_lock(&fs_info->qgroup_ioctl_lock);
1480 if (!fs_info->quota_root) {
1484 member = find_qgroup_rb(fs_info, src);
1485 parent = find_qgroup_rb(fs_info, dst);
1486 if (!member || !parent) {
1491 /* check if such qgroup relation exist firstly */
1492 list_for_each_entry(list, &member->groups, next_group) {
1493 if (list->group == parent) {
1499 ret = add_qgroup_relation_item(trans, src, dst);
1503 ret = add_qgroup_relation_item(trans, dst, src);
1505 del_qgroup_relation_item(trans, src, dst);
1509 spin_lock(&fs_info->qgroup_lock);
1510 ret = __add_relation_rb(member, parent);
1512 spin_unlock(&fs_info->qgroup_lock);
1515 ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1516 spin_unlock(&fs_info->qgroup_lock);
1518 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1523 static int __del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1526 struct btrfs_fs_info *fs_info = trans->fs_info;
1527 struct btrfs_qgroup *parent;
1528 struct btrfs_qgroup *member;
1529 struct btrfs_qgroup_list *list;
1532 unsigned int nofs_flag;
1536 /* We hold a transaction handle open, must do a NOFS allocation. */
1537 nofs_flag = memalloc_nofs_save();
1538 tmp = ulist_alloc(GFP_KERNEL);
1539 memalloc_nofs_restore(nofs_flag);
1543 if (!fs_info->quota_root) {
1548 member = find_qgroup_rb(fs_info, src);
1549 parent = find_qgroup_rb(fs_info, dst);
1551 * The parent/member pair doesn't exist, then try to delete the dead
1552 * relation items only.
1554 if (!member || !parent)
1557 /* check if such qgroup relation exist firstly */
1558 list_for_each_entry(list, &member->groups, next_group) {
1559 if (list->group == parent) {
1566 ret = del_qgroup_relation_item(trans, src, dst);
1567 if (ret < 0 && ret != -ENOENT)
1569 ret2 = del_qgroup_relation_item(trans, dst, src);
1570 if (ret2 < 0 && ret2 != -ENOENT)
1573 /* At least one deletion succeeded, return 0 */
1578 spin_lock(&fs_info->qgroup_lock);
1579 del_relation_rb(fs_info, src, dst);
1580 ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1581 spin_unlock(&fs_info->qgroup_lock);
1588 int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1591 struct btrfs_fs_info *fs_info = trans->fs_info;
1594 mutex_lock(&fs_info->qgroup_ioctl_lock);
1595 ret = __del_qgroup_relation(trans, src, dst);
1596 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1601 int btrfs_create_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1603 struct btrfs_fs_info *fs_info = trans->fs_info;
1604 struct btrfs_root *quota_root;
1605 struct btrfs_qgroup *qgroup;
1608 mutex_lock(&fs_info->qgroup_ioctl_lock);
1609 if (!fs_info->quota_root) {
1613 quota_root = fs_info->quota_root;
1614 qgroup = find_qgroup_rb(fs_info, qgroupid);
1620 ret = add_qgroup_item(trans, quota_root, qgroupid);
1624 spin_lock(&fs_info->qgroup_lock);
1625 qgroup = add_qgroup_rb(fs_info, qgroupid);
1626 spin_unlock(&fs_info->qgroup_lock);
1628 if (IS_ERR(qgroup)) {
1629 ret = PTR_ERR(qgroup);
1632 ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1634 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1638 static bool qgroup_has_usage(struct btrfs_qgroup *qgroup)
1640 return (qgroup->rfer > 0 || qgroup->rfer_cmpr > 0 ||
1641 qgroup->excl > 0 || qgroup->excl_cmpr > 0 ||
1642 qgroup->rsv.values[BTRFS_QGROUP_RSV_DATA] > 0 ||
1643 qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PREALLOC] > 0 ||
1644 qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PERTRANS] > 0);
1647 int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1649 struct btrfs_fs_info *fs_info = trans->fs_info;
1650 struct btrfs_qgroup *qgroup;
1651 struct btrfs_qgroup_list *list;
1654 mutex_lock(&fs_info->qgroup_ioctl_lock);
1655 if (!fs_info->quota_root) {
1660 qgroup = find_qgroup_rb(fs_info, qgroupid);
1666 if (is_fstree(qgroupid) && qgroup_has_usage(qgroup)) {
1671 /* Check if there are no children of this qgroup */
1672 if (!list_empty(&qgroup->members)) {
1677 ret = del_qgroup_item(trans, qgroupid);
1678 if (ret && ret != -ENOENT)
1681 while (!list_empty(&qgroup->groups)) {
1682 list = list_first_entry(&qgroup->groups,
1683 struct btrfs_qgroup_list, next_group);
1684 ret = __del_qgroup_relation(trans, qgroupid,
1685 list->group->qgroupid);
1690 spin_lock(&fs_info->qgroup_lock);
1691 del_qgroup_rb(fs_info, qgroupid);
1692 spin_unlock(&fs_info->qgroup_lock);
1695 * Remove the qgroup from sysfs now without holding the qgroup_lock
1696 * spinlock, since the sysfs_remove_group() function needs to take
1697 * the mutex kernfs_mutex through kernfs_remove_by_name_ns().
1699 btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
1702 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1706 int btrfs_limit_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid,
1707 struct btrfs_qgroup_limit *limit)
1709 struct btrfs_fs_info *fs_info = trans->fs_info;
1710 struct btrfs_qgroup *qgroup;
1712 /* Sometimes we would want to clear the limit on this qgroup.
1713 * To meet this requirement, we treat the -1 as a special value
1714 * which tell kernel to clear the limit on this qgroup.
1716 const u64 CLEAR_VALUE = -1;
1718 mutex_lock(&fs_info->qgroup_ioctl_lock);
1719 if (!fs_info->quota_root) {
1724 qgroup = find_qgroup_rb(fs_info, qgroupid);
1730 spin_lock(&fs_info->qgroup_lock);
1731 if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
1732 if (limit->max_rfer == CLEAR_VALUE) {
1733 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1734 limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1735 qgroup->max_rfer = 0;
1737 qgroup->max_rfer = limit->max_rfer;
1740 if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
1741 if (limit->max_excl == CLEAR_VALUE) {
1742 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1743 limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1744 qgroup->max_excl = 0;
1746 qgroup->max_excl = limit->max_excl;
1749 if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
1750 if (limit->rsv_rfer == CLEAR_VALUE) {
1751 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1752 limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1753 qgroup->rsv_rfer = 0;
1755 qgroup->rsv_rfer = limit->rsv_rfer;
1758 if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
1759 if (limit->rsv_excl == CLEAR_VALUE) {
1760 qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1761 limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1762 qgroup->rsv_excl = 0;
1764 qgroup->rsv_excl = limit->rsv_excl;
1767 qgroup->lim_flags |= limit->flags;
1769 spin_unlock(&fs_info->qgroup_lock);
1771 ret = update_qgroup_limit_item(trans, qgroup);
1773 qgroup_mark_inconsistent(fs_info);
1774 btrfs_info(fs_info, "unable to update quota limit for %llu",
1779 mutex_unlock(&fs_info->qgroup_ioctl_lock);
1783 int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1784 struct btrfs_delayed_ref_root *delayed_refs,
1785 struct btrfs_qgroup_extent_record *record)
1787 struct rb_node **p = &delayed_refs->dirty_extent_root.rb_node;
1788 struct rb_node *parent_node = NULL;
1789 struct btrfs_qgroup_extent_record *entry;
1790 u64 bytenr = record->bytenr;
1792 lockdep_assert_held(&delayed_refs->lock);
1793 trace_btrfs_qgroup_trace_extent(fs_info, record);
1797 entry = rb_entry(parent_node, struct btrfs_qgroup_extent_record,
1799 if (bytenr < entry->bytenr) {
1801 } else if (bytenr > entry->bytenr) {
1802 p = &(*p)->rb_right;
1804 if (record->data_rsv && !entry->data_rsv) {
1805 entry->data_rsv = record->data_rsv;
1806 entry->data_rsv_refroot =
1807 record->data_rsv_refroot;
1813 rb_link_node(&record->node, parent_node, p);
1814 rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1818 int btrfs_qgroup_trace_extent_post(struct btrfs_trans_handle *trans,
1819 struct btrfs_qgroup_extent_record *qrecord)
1821 struct ulist *old_root;
1822 u64 bytenr = qrecord->bytenr;
1826 * We are always called in a context where we are already holding a
1827 * transaction handle. Often we are called when adding a data delayed
1828 * reference from btrfs_truncate_inode_items() (truncating or unlinking),
1829 * in which case we will be holding a write lock on extent buffer from a
1830 * subvolume tree. In this case we can't allow btrfs_find_all_roots() to
1831 * acquire fs_info->commit_root_sem, because that is a higher level lock
1832 * that must be acquired before locking any extent buffers.
1834 * So we want btrfs_find_all_roots() to not acquire the commit_root_sem
1835 * but we can't pass it a non-NULL transaction handle, because otherwise
1836 * it would not use commit roots and would lock extent buffers, causing
1837 * a deadlock if it ends up trying to read lock the same extent buffer
1838 * that was previously write locked at btrfs_truncate_inode_items().
1840 * So pass a NULL transaction handle to btrfs_find_all_roots() and
1841 * explicitly tell it to not acquire the commit_root_sem - if we are
1842 * holding a transaction handle we don't need its protection.
1844 ASSERT(trans != NULL);
1846 if (trans->fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING)
1849 ret = btrfs_find_all_roots(NULL, trans->fs_info, bytenr, 0, &old_root,
1852 qgroup_mark_inconsistent(trans->fs_info);
1853 btrfs_warn(trans->fs_info,
1854 "error accounting new delayed refs extent (err code: %d), quota inconsistent",
1860 * Here we don't need to get the lock of
1861 * trans->transaction->delayed_refs, since inserted qrecord won't
1862 * be deleted, only qrecord->node may be modified (new qrecord insert)
1864 * So modifying qrecord->old_roots is safe here
1866 qrecord->old_roots = old_root;
1870 int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans, u64 bytenr,
1871 u64 num_bytes, gfp_t gfp_flag)
1873 struct btrfs_fs_info *fs_info = trans->fs_info;
1874 struct btrfs_qgroup_extent_record *record;
1875 struct btrfs_delayed_ref_root *delayed_refs;
1878 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
1879 || bytenr == 0 || num_bytes == 0)
1881 record = kzalloc(sizeof(*record), gfp_flag);
1885 delayed_refs = &trans->transaction->delayed_refs;
1886 record->bytenr = bytenr;
1887 record->num_bytes = num_bytes;
1888 record->old_roots = NULL;
1890 spin_lock(&delayed_refs->lock);
1891 ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1892 spin_unlock(&delayed_refs->lock);
1897 return btrfs_qgroup_trace_extent_post(trans, record);
1900 int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
1901 struct extent_buffer *eb)
1903 struct btrfs_fs_info *fs_info = trans->fs_info;
1904 int nr = btrfs_header_nritems(eb);
1905 int i, extent_type, ret;
1906 struct btrfs_key key;
1907 struct btrfs_file_extent_item *fi;
1908 u64 bytenr, num_bytes;
1910 /* We can be called directly from walk_up_proc() */
1911 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1914 for (i = 0; i < nr; i++) {
1915 btrfs_item_key_to_cpu(eb, &key, i);
1917 if (key.type != BTRFS_EXTENT_DATA_KEY)
1920 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
1921 /* filter out non qgroup-accountable extents */
1922 extent_type = btrfs_file_extent_type(eb, fi);
1924 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1927 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1931 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1933 ret = btrfs_qgroup_trace_extent(trans, bytenr, num_bytes,
1943 * Walk up the tree from the bottom, freeing leaves and any interior
1944 * nodes which have had all slots visited. If a node (leaf or
1945 * interior) is freed, the node above it will have it's slot
1946 * incremented. The root node will never be freed.
1948 * At the end of this function, we should have a path which has all
1949 * slots incremented to the next position for a search. If we need to
1950 * read a new node it will be NULL and the node above it will have the
1951 * correct slot selected for a later read.
1953 * If we increment the root nodes slot counter past the number of
1954 * elements, 1 is returned to signal completion of the search.
1956 static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1960 struct extent_buffer *eb;
1962 if (root_level == 0)
1965 while (level <= root_level) {
1966 eb = path->nodes[level];
1967 nr = btrfs_header_nritems(eb);
1968 path->slots[level]++;
1969 slot = path->slots[level];
1970 if (slot >= nr || level == 0) {
1972 * Don't free the root - we will detect this
1973 * condition after our loop and return a
1974 * positive value for caller to stop walking the tree.
1976 if (level != root_level) {
1977 btrfs_tree_unlock_rw(eb, path->locks[level]);
1978 path->locks[level] = 0;
1980 free_extent_buffer(eb);
1981 path->nodes[level] = NULL;
1982 path->slots[level] = 0;
1986 * We have a valid slot to walk back down
1987 * from. Stop here so caller can process these
1996 eb = path->nodes[root_level];
1997 if (path->slots[root_level] >= btrfs_header_nritems(eb))
2004 * Helper function to trace a subtree tree block swap.
2006 * The swap will happen in highest tree block, but there may be a lot of
2007 * tree blocks involved.
2010 * OO = Old tree blocks
2011 * NN = New tree blocks allocated during balance
2013 * File tree (257) Reloc tree for 257
2016 * L1 OO OO (a) OO NN (a)
2018 * L0 OO OO OO OO OO OO NN NN
2021 * When calling qgroup_trace_extent_swap(), we will pass:
2023 * @dst_path = [ nodes[1] = NN(a), nodes[0] = NN(c) ]
2027 * In that case, qgroup_trace_extent_swap() will search from OO(a) to
2028 * reach OO(c), then mark both OO(c) and NN(c) as qgroup dirty.
2030 * The main work of qgroup_trace_extent_swap() can be split into 3 parts:
2032 * 1) Tree search from @src_eb
2033 * It should acts as a simplified btrfs_search_slot().
2034 * The key for search can be extracted from @dst_path->nodes[dst_level]
2037 * 2) Mark the final tree blocks in @src_path and @dst_path qgroup dirty
2038 * NOTE: In above case, OO(a) and NN(a) won't be marked qgroup dirty.
2039 * They should be marked during previous (@dst_level = 1) iteration.
2041 * 3) Mark file extents in leaves dirty
2042 * We don't have good way to pick out new file extents only.
2043 * So we still follow the old method by scanning all file extents in
2046 * This function can free us from keeping two paths, thus later we only need
2047 * to care about how to iterate all new tree blocks in reloc tree.
2049 static int qgroup_trace_extent_swap(struct btrfs_trans_handle* trans,
2050 struct extent_buffer *src_eb,
2051 struct btrfs_path *dst_path,
2052 int dst_level, int root_level,
2055 struct btrfs_key key;
2056 struct btrfs_path *src_path;
2057 struct btrfs_fs_info *fs_info = trans->fs_info;
2058 u32 nodesize = fs_info->nodesize;
2059 int cur_level = root_level;
2062 BUG_ON(dst_level > root_level);
2063 /* Level mismatch */
2064 if (btrfs_header_level(src_eb) != root_level)
2067 src_path = btrfs_alloc_path();
2074 btrfs_node_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2076 btrfs_item_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2079 atomic_inc(&src_eb->refs);
2080 src_path->nodes[root_level] = src_eb;
2081 src_path->slots[root_level] = dst_path->slots[root_level];
2082 src_path->locks[root_level] = 0;
2084 /* A simplified version of btrfs_search_slot() */
2085 while (cur_level >= dst_level) {
2086 struct btrfs_key src_key;
2087 struct btrfs_key dst_key;
2089 if (src_path->nodes[cur_level] == NULL) {
2090 struct extent_buffer *eb;
2093 eb = src_path->nodes[cur_level + 1];
2094 parent_slot = src_path->slots[cur_level + 1];
2096 eb = btrfs_read_node_slot(eb, parent_slot);
2102 src_path->nodes[cur_level] = eb;
2104 btrfs_tree_read_lock(eb);
2105 src_path->locks[cur_level] = BTRFS_READ_LOCK;
2108 src_path->slots[cur_level] = dst_path->slots[cur_level];
2110 btrfs_node_key_to_cpu(dst_path->nodes[cur_level],
2111 &dst_key, dst_path->slots[cur_level]);
2112 btrfs_node_key_to_cpu(src_path->nodes[cur_level],
2113 &src_key, src_path->slots[cur_level]);
2115 btrfs_item_key_to_cpu(dst_path->nodes[cur_level],
2116 &dst_key, dst_path->slots[cur_level]);
2117 btrfs_item_key_to_cpu(src_path->nodes[cur_level],
2118 &src_key, src_path->slots[cur_level]);
2120 /* Content mismatch, something went wrong */
2121 if (btrfs_comp_cpu_keys(&dst_key, &src_key)) {
2129 * Now both @dst_path and @src_path have been populated, record the tree
2130 * blocks for qgroup accounting.
2132 ret = btrfs_qgroup_trace_extent(trans, src_path->nodes[dst_level]->start,
2133 nodesize, GFP_NOFS);
2136 ret = btrfs_qgroup_trace_extent(trans,
2137 dst_path->nodes[dst_level]->start,
2138 nodesize, GFP_NOFS);
2142 /* Record leaf file extents */
2143 if (dst_level == 0 && trace_leaf) {
2144 ret = btrfs_qgroup_trace_leaf_items(trans, src_path->nodes[0]);
2147 ret = btrfs_qgroup_trace_leaf_items(trans, dst_path->nodes[0]);
2150 btrfs_free_path(src_path);
2155 * Helper function to do recursive generation-aware depth-first search, to
2156 * locate all new tree blocks in a subtree of reloc tree.
2158 * E.g. (OO = Old tree blocks, NN = New tree blocks, whose gen == last_snapshot)
2167 * @dst_path = [ nodes[1] = NN(b), nodes[0] = NULL ],
2171 * We will iterate through tree blocks NN(b), NN(d) and info qgroup to trace
2172 * above tree blocks along with their counter parts in file tree.
2173 * While during search, old tree blocks OO(c) will be skipped as tree block swap
2174 * won't affect OO(c).
2176 static int qgroup_trace_new_subtree_blocks(struct btrfs_trans_handle* trans,
2177 struct extent_buffer *src_eb,
2178 struct btrfs_path *dst_path,
2179 int cur_level, int root_level,
2180 u64 last_snapshot, bool trace_leaf)
2182 struct btrfs_fs_info *fs_info = trans->fs_info;
2183 struct extent_buffer *eb;
2184 bool need_cleanup = false;
2188 /* Level sanity check */
2189 if (cur_level < 0 || cur_level >= BTRFS_MAX_LEVEL - 1 ||
2190 root_level < 0 || root_level >= BTRFS_MAX_LEVEL - 1 ||
2191 root_level < cur_level) {
2192 btrfs_err_rl(fs_info,
2193 "%s: bad levels, cur_level=%d root_level=%d",
2194 __func__, cur_level, root_level);
2198 /* Read the tree block if needed */
2199 if (dst_path->nodes[cur_level] == NULL) {
2204 * dst_path->nodes[root_level] must be initialized before
2205 * calling this function.
2207 if (cur_level == root_level) {
2208 btrfs_err_rl(fs_info,
2209 "%s: dst_path->nodes[%d] not initialized, root_level=%d cur_level=%d",
2210 __func__, root_level, root_level, cur_level);
2215 * We need to get child blockptr/gen from parent before we can
2218 eb = dst_path->nodes[cur_level + 1];
2219 parent_slot = dst_path->slots[cur_level + 1];
2220 child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2222 /* This node is old, no need to trace */
2223 if (child_gen < last_snapshot)
2226 eb = btrfs_read_node_slot(eb, parent_slot);
2232 dst_path->nodes[cur_level] = eb;
2233 dst_path->slots[cur_level] = 0;
2235 btrfs_tree_read_lock(eb);
2236 dst_path->locks[cur_level] = BTRFS_READ_LOCK;
2237 need_cleanup = true;
2240 /* Now record this tree block and its counter part for qgroups */
2241 ret = qgroup_trace_extent_swap(trans, src_eb, dst_path, cur_level,
2242 root_level, trace_leaf);
2246 eb = dst_path->nodes[cur_level];
2248 if (cur_level > 0) {
2249 /* Iterate all child tree blocks */
2250 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2251 /* Skip old tree blocks as they won't be swapped */
2252 if (btrfs_node_ptr_generation(eb, i) < last_snapshot)
2254 dst_path->slots[cur_level] = i;
2256 /* Recursive call (at most 7 times) */
2257 ret = qgroup_trace_new_subtree_blocks(trans, src_eb,
2258 dst_path, cur_level - 1, root_level,
2259 last_snapshot, trace_leaf);
2268 btrfs_tree_unlock_rw(dst_path->nodes[cur_level],
2269 dst_path->locks[cur_level]);
2270 free_extent_buffer(dst_path->nodes[cur_level]);
2271 dst_path->nodes[cur_level] = NULL;
2272 dst_path->slots[cur_level] = 0;
2273 dst_path->locks[cur_level] = 0;
2279 static int qgroup_trace_subtree_swap(struct btrfs_trans_handle *trans,
2280 struct extent_buffer *src_eb,
2281 struct extent_buffer *dst_eb,
2282 u64 last_snapshot, bool trace_leaf)
2284 struct btrfs_fs_info *fs_info = trans->fs_info;
2285 struct btrfs_path *dst_path = NULL;
2289 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2292 /* Wrong parameter order */
2293 if (btrfs_header_generation(src_eb) > btrfs_header_generation(dst_eb)) {
2294 btrfs_err_rl(fs_info,
2295 "%s: bad parameter order, src_gen=%llu dst_gen=%llu", __func__,
2296 btrfs_header_generation(src_eb),
2297 btrfs_header_generation(dst_eb));
2301 if (!extent_buffer_uptodate(src_eb) || !extent_buffer_uptodate(dst_eb)) {
2306 level = btrfs_header_level(dst_eb);
2307 dst_path = btrfs_alloc_path();
2313 atomic_inc(&dst_eb->refs);
2314 dst_path->nodes[level] = dst_eb;
2315 dst_path->slots[level] = 0;
2316 dst_path->locks[level] = 0;
2318 /* Do the generation aware breadth-first search */
2319 ret = qgroup_trace_new_subtree_blocks(trans, src_eb, dst_path, level,
2320 level, last_snapshot, trace_leaf);
2326 btrfs_free_path(dst_path);
2328 qgroup_mark_inconsistent(fs_info);
2332 int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
2333 struct extent_buffer *root_eb,
2334 u64 root_gen, int root_level)
2336 struct btrfs_fs_info *fs_info = trans->fs_info;
2339 u8 drop_subptree_thres;
2340 struct extent_buffer *eb = root_eb;
2341 struct btrfs_path *path = NULL;
2343 BUG_ON(root_level < 0 || root_level >= BTRFS_MAX_LEVEL);
2344 BUG_ON(root_eb == NULL);
2346 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2349 spin_lock(&fs_info->qgroup_lock);
2350 drop_subptree_thres = fs_info->qgroup_drop_subtree_thres;
2351 spin_unlock(&fs_info->qgroup_lock);
2354 * This function only gets called for snapshot drop, if we hit a high
2355 * node here, it means we are going to change ownership for quite a lot
2356 * of extents, which will greatly slow down btrfs_commit_transaction().
2358 * So here if we find a high tree here, we just skip the accounting and
2359 * mark qgroup inconsistent.
2361 if (root_level >= drop_subptree_thres) {
2362 qgroup_mark_inconsistent(fs_info);
2366 if (!extent_buffer_uptodate(root_eb)) {
2367 ret = btrfs_read_extent_buffer(root_eb, root_gen, root_level, NULL);
2372 if (root_level == 0) {
2373 ret = btrfs_qgroup_trace_leaf_items(trans, root_eb);
2377 path = btrfs_alloc_path();
2382 * Walk down the tree. Missing extent blocks are filled in as
2383 * we go. Metadata is accounted every time we read a new
2386 * When we reach a leaf, we account for file extent items in it,
2387 * walk back up the tree (adjusting slot pointers as we go)
2388 * and restart the search process.
2390 atomic_inc(&root_eb->refs); /* For path */
2391 path->nodes[root_level] = root_eb;
2392 path->slots[root_level] = 0;
2393 path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
2396 while (level >= 0) {
2397 if (path->nodes[level] == NULL) {
2402 * We need to get child blockptr from parent before we
2405 eb = path->nodes[level + 1];
2406 parent_slot = path->slots[level + 1];
2407 child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2409 eb = btrfs_read_node_slot(eb, parent_slot);
2415 path->nodes[level] = eb;
2416 path->slots[level] = 0;
2418 btrfs_tree_read_lock(eb);
2419 path->locks[level] = BTRFS_READ_LOCK;
2421 ret = btrfs_qgroup_trace_extent(trans, child_bytenr,
2429 ret = btrfs_qgroup_trace_leaf_items(trans,
2430 path->nodes[level]);
2434 /* Nonzero return here means we completed our search */
2435 ret = adjust_slots_upwards(path, root_level);
2439 /* Restart search with new slots */
2448 btrfs_free_path(path);
2453 #define UPDATE_NEW 0
2454 #define UPDATE_OLD 1
2456 * Walk all of the roots that points to the bytenr and adjust their refcnts.
2458 static int qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
2459 struct ulist *roots, struct ulist *tmp,
2460 struct ulist *qgroups, u64 seq, int update_old)
2462 struct ulist_node *unode;
2463 struct ulist_iterator uiter;
2464 struct ulist_node *tmp_unode;
2465 struct ulist_iterator tmp_uiter;
2466 struct btrfs_qgroup *qg;
2471 ULIST_ITER_INIT(&uiter);
2472 while ((unode = ulist_next(roots, &uiter))) {
2473 qg = find_qgroup_rb(fs_info, unode->val);
2478 ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
2482 ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
2485 ULIST_ITER_INIT(&tmp_uiter);
2486 while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
2487 struct btrfs_qgroup_list *glist;
2489 qg = unode_aux_to_qgroup(tmp_unode);
2491 btrfs_qgroup_update_old_refcnt(qg, seq, 1);
2493 btrfs_qgroup_update_new_refcnt(qg, seq, 1);
2494 list_for_each_entry(glist, &qg->groups, next_group) {
2495 ret = ulist_add(qgroups, glist->group->qgroupid,
2496 qgroup_to_aux(glist->group),
2500 ret = ulist_add(tmp, glist->group->qgroupid,
2501 qgroup_to_aux(glist->group),
2512 * Update qgroup rfer/excl counters.
2513 * Rfer update is easy, codes can explain themselves.
2515 * Excl update is tricky, the update is split into 2 parts.
2516 * Part 1: Possible exclusive <-> sharing detect:
2518 * -------------------------------------
2520 * -------------------------------------
2522 * -------------------------------------
2525 * A: cur_old_roots < nr_old_roots (not exclusive before)
2526 * !A: cur_old_roots == nr_old_roots (possible exclusive before)
2527 * B: cur_new_roots < nr_new_roots (not exclusive now)
2528 * !B: cur_new_roots == nr_new_roots (possible exclusive now)
2531 * +: Possible sharing -> exclusive -: Possible exclusive -> sharing
2532 * *: Definitely not changed. **: Possible unchanged.
2534 * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
2536 * To make the logic clear, we first use condition A and B to split
2537 * combination into 4 results.
2539 * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
2540 * only on variant maybe 0.
2542 * Lastly, check result **, since there are 2 variants maybe 0, split them
2544 * But this time we don't need to consider other things, the codes and logic
2545 * is easy to understand now.
2547 static int qgroup_update_counters(struct btrfs_fs_info *fs_info,
2548 struct ulist *qgroups,
2551 u64 num_bytes, u64 seq)
2553 struct ulist_node *unode;
2554 struct ulist_iterator uiter;
2555 struct btrfs_qgroup *qg;
2556 u64 cur_new_count, cur_old_count;
2558 ULIST_ITER_INIT(&uiter);
2559 while ((unode = ulist_next(qgroups, &uiter))) {
2562 qg = unode_aux_to_qgroup(unode);
2563 cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
2564 cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);
2566 trace_qgroup_update_counters(fs_info, qg, cur_old_count,
2569 /* Rfer update part */
2570 if (cur_old_count == 0 && cur_new_count > 0) {
2571 qg->rfer += num_bytes;
2572 qg->rfer_cmpr += num_bytes;
2575 if (cur_old_count > 0 && cur_new_count == 0) {
2576 qg->rfer -= num_bytes;
2577 qg->rfer_cmpr -= num_bytes;
2581 /* Excl update part */
2582 /* Exclusive/none -> shared case */
2583 if (cur_old_count == nr_old_roots &&
2584 cur_new_count < nr_new_roots) {
2585 /* Exclusive -> shared */
2586 if (cur_old_count != 0) {
2587 qg->excl -= num_bytes;
2588 qg->excl_cmpr -= num_bytes;
2593 /* Shared -> exclusive/none case */
2594 if (cur_old_count < nr_old_roots &&
2595 cur_new_count == nr_new_roots) {
2596 /* Shared->exclusive */
2597 if (cur_new_count != 0) {
2598 qg->excl += num_bytes;
2599 qg->excl_cmpr += num_bytes;
2604 /* Exclusive/none -> exclusive/none case */
2605 if (cur_old_count == nr_old_roots &&
2606 cur_new_count == nr_new_roots) {
2607 if (cur_old_count == 0) {
2608 /* None -> exclusive/none */
2610 if (cur_new_count != 0) {
2611 /* None -> exclusive */
2612 qg->excl += num_bytes;
2613 qg->excl_cmpr += num_bytes;
2616 /* None -> none, nothing changed */
2618 /* Exclusive -> exclusive/none */
2620 if (cur_new_count == 0) {
2621 /* Exclusive -> none */
2622 qg->excl -= num_bytes;
2623 qg->excl_cmpr -= num_bytes;
2626 /* Exclusive -> exclusive, nothing changed */
2631 qgroup_dirty(fs_info, qg);
2637 * Check if the @roots potentially is a list of fs tree roots
2639 * Return 0 for definitely not a fs/subvol tree roots ulist
2640 * Return 1 for possible fs/subvol tree roots in the list (considering an empty
2643 static int maybe_fs_roots(struct ulist *roots)
2645 struct ulist_node *unode;
2646 struct ulist_iterator uiter;
2648 /* Empty one, still possible for fs roots */
2649 if (!roots || roots->nnodes == 0)
2652 ULIST_ITER_INIT(&uiter);
2653 unode = ulist_next(roots, &uiter);
2658 * If it contains fs tree roots, then it must belong to fs/subvol
2660 * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
2662 return is_fstree(unode->val);
2665 int btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans, u64 bytenr,
2666 u64 num_bytes, struct ulist *old_roots,
2667 struct ulist *new_roots)
2669 struct btrfs_fs_info *fs_info = trans->fs_info;
2670 struct ulist *qgroups = NULL;
2671 struct ulist *tmp = NULL;
2673 u64 nr_new_roots = 0;
2674 u64 nr_old_roots = 0;
2678 * If quotas get disabled meanwhile, the resources need to be freed and
2679 * we can't just exit here.
2681 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
2682 fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING)
2686 if (!maybe_fs_roots(new_roots))
2688 nr_new_roots = new_roots->nnodes;
2691 if (!maybe_fs_roots(old_roots))
2693 nr_old_roots = old_roots->nnodes;
2696 /* Quick exit, either not fs tree roots, or won't affect any qgroup */
2697 if (nr_old_roots == 0 && nr_new_roots == 0)
2700 BUG_ON(!fs_info->quota_root);
2702 trace_btrfs_qgroup_account_extent(fs_info, trans->transid, bytenr,
2703 num_bytes, nr_old_roots, nr_new_roots);
2705 qgroups = ulist_alloc(GFP_NOFS);
2710 tmp = ulist_alloc(GFP_NOFS);
2716 mutex_lock(&fs_info->qgroup_rescan_lock);
2717 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
2718 if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
2719 mutex_unlock(&fs_info->qgroup_rescan_lock);
2724 mutex_unlock(&fs_info->qgroup_rescan_lock);
2726 spin_lock(&fs_info->qgroup_lock);
2727 seq = fs_info->qgroup_seq;
2729 /* Update old refcnts using old_roots */
2730 ret = qgroup_update_refcnt(fs_info, old_roots, tmp, qgroups, seq,
2735 /* Update new refcnts using new_roots */
2736 ret = qgroup_update_refcnt(fs_info, new_roots, tmp, qgroups, seq,
2741 qgroup_update_counters(fs_info, qgroups, nr_old_roots, nr_new_roots,
2745 * Bump qgroup_seq to avoid seq overlap
2747 fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
2749 spin_unlock(&fs_info->qgroup_lock);
2752 ulist_free(qgroups);
2753 ulist_free(old_roots);
2754 ulist_free(new_roots);
2758 int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans)
2760 struct btrfs_fs_info *fs_info = trans->fs_info;
2761 struct btrfs_qgroup_extent_record *record;
2762 struct btrfs_delayed_ref_root *delayed_refs;
2763 struct ulist *new_roots = NULL;
2764 struct rb_node *node;
2765 u64 num_dirty_extents = 0;
2769 delayed_refs = &trans->transaction->delayed_refs;
2770 qgroup_to_skip = delayed_refs->qgroup_to_skip;
2771 while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
2772 record = rb_entry(node, struct btrfs_qgroup_extent_record,
2775 num_dirty_extents++;
2776 trace_btrfs_qgroup_account_extents(fs_info, record);
2778 if (!ret && !(fs_info->qgroup_flags &
2779 BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING)) {
2781 * Old roots should be searched when inserting qgroup
2784 * But for INCONSISTENT (NO_ACCOUNTING) -> rescan case,
2785 * we may have some record inserted during
2786 * NO_ACCOUNTING (thus no old_roots populated), but
2787 * later we start rescan, which clears NO_ACCOUNTING,
2788 * leaving some inserted records without old_roots
2791 * Those cases are rare and should not cause too much
2792 * time spent during commit_transaction().
2794 if (!record->old_roots) {
2795 /* Search commit root to find old_roots */
2796 ret = btrfs_find_all_roots(NULL, fs_info,
2798 &record->old_roots, false);
2804 * Use BTRFS_SEQ_LAST as time_seq to do special search,
2805 * which doesn't lock tree or delayed_refs and search
2806 * current root. It's safe inside commit_transaction().
2808 ret = btrfs_find_all_roots(trans, fs_info,
2809 record->bytenr, BTRFS_SEQ_LAST, &new_roots, false);
2812 if (qgroup_to_skip) {
2813 ulist_del(new_roots, qgroup_to_skip, 0);
2814 ulist_del(record->old_roots, qgroup_to_skip,
2817 ret = btrfs_qgroup_account_extent(trans, record->bytenr,
2821 record->old_roots = NULL;
2824 /* Free the reserved data space */
2825 btrfs_qgroup_free_refroot(fs_info,
2826 record->data_rsv_refroot,
2828 BTRFS_QGROUP_RSV_DATA);
2830 ulist_free(record->old_roots);
2831 ulist_free(new_roots);
2833 rb_erase(node, &delayed_refs->dirty_extent_root);
2837 trace_qgroup_num_dirty_extents(fs_info, trans->transid,
2843 * Writes all changed qgroups to disk.
2844 * Called by the transaction commit path and the qgroup assign ioctl.
2846 int btrfs_run_qgroups(struct btrfs_trans_handle *trans)
2848 struct btrfs_fs_info *fs_info = trans->fs_info;
2852 * In case we are called from the qgroup assign ioctl, assert that we
2853 * are holding the qgroup_ioctl_lock, otherwise we can race with a quota
2854 * disable operation (ioctl) and access a freed quota root.
2856 if (trans->transaction->state != TRANS_STATE_COMMIT_DOING)
2857 lockdep_assert_held(&fs_info->qgroup_ioctl_lock);
2859 if (!fs_info->quota_root)
2862 spin_lock(&fs_info->qgroup_lock);
2863 while (!list_empty(&fs_info->dirty_qgroups)) {
2864 struct btrfs_qgroup *qgroup;
2865 qgroup = list_first_entry(&fs_info->dirty_qgroups,
2866 struct btrfs_qgroup, dirty);
2867 list_del_init(&qgroup->dirty);
2868 spin_unlock(&fs_info->qgroup_lock);
2869 ret = update_qgroup_info_item(trans, qgroup);
2871 qgroup_mark_inconsistent(fs_info);
2872 ret = update_qgroup_limit_item(trans, qgroup);
2874 qgroup_mark_inconsistent(fs_info);
2875 spin_lock(&fs_info->qgroup_lock);
2877 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2878 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_ON;
2880 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
2881 spin_unlock(&fs_info->qgroup_lock);
2883 ret = update_qgroup_status_item(trans);
2885 qgroup_mark_inconsistent(fs_info);
2891 * Copy the accounting information between qgroups. This is necessary
2892 * when a snapshot or a subvolume is created. Throwing an error will
2893 * cause a transaction abort so we take extra care here to only error
2894 * when a readonly fs is a reasonable outcome.
2896 int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans, u64 srcid,
2897 u64 objectid, struct btrfs_qgroup_inherit *inherit)
2902 bool committing = false;
2903 struct btrfs_fs_info *fs_info = trans->fs_info;
2904 struct btrfs_root *quota_root;
2905 struct btrfs_qgroup *srcgroup;
2906 struct btrfs_qgroup *dstgroup;
2907 bool need_rescan = false;
2912 * There are only two callers of this function.
2914 * One in create_subvol() in the ioctl context, which needs to hold
2915 * the qgroup_ioctl_lock.
2917 * The other one in create_pending_snapshot() where no other qgroup
2918 * code can modify the fs as they all need to either start a new trans
2919 * or hold a trans handler, thus we don't need to hold
2920 * qgroup_ioctl_lock.
2921 * This would avoid long and complex lock chain and make lockdep happy.
2923 spin_lock(&fs_info->trans_lock);
2924 if (trans->transaction->state == TRANS_STATE_COMMIT_DOING)
2926 spin_unlock(&fs_info->trans_lock);
2929 mutex_lock(&fs_info->qgroup_ioctl_lock);
2930 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2933 quota_root = fs_info->quota_root;
2940 i_qgroups = (u64 *)(inherit + 1);
2941 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
2942 2 * inherit->num_excl_copies;
2943 for (i = 0; i < nums; ++i) {
2944 srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
2947 * Zero out invalid groups so we can ignore
2951 ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
2959 * create a tracking group for the subvol itself
2961 ret = add_qgroup_item(trans, quota_root, objectid);
2966 * add qgroup to all inherited groups
2969 i_qgroups = (u64 *)(inherit + 1);
2970 for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
2971 if (*i_qgroups == 0)
2973 ret = add_qgroup_relation_item(trans, objectid,
2975 if (ret && ret != -EEXIST)
2977 ret = add_qgroup_relation_item(trans, *i_qgroups,
2979 if (ret && ret != -EEXIST)
2986 spin_lock(&fs_info->qgroup_lock);
2988 dstgroup = add_qgroup_rb(fs_info, objectid);
2989 if (IS_ERR(dstgroup)) {
2990 ret = PTR_ERR(dstgroup);
2994 if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
2995 dstgroup->lim_flags = inherit->lim.flags;
2996 dstgroup->max_rfer = inherit->lim.max_rfer;
2997 dstgroup->max_excl = inherit->lim.max_excl;
2998 dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
2999 dstgroup->rsv_excl = inherit->lim.rsv_excl;
3001 qgroup_dirty(fs_info, dstgroup);
3005 srcgroup = find_qgroup_rb(fs_info, srcid);
3010 * We call inherit after we clone the root in order to make sure
3011 * our counts don't go crazy, so at this point the only
3012 * difference between the two roots should be the root node.
3014 level_size = fs_info->nodesize;
3015 dstgroup->rfer = srcgroup->rfer;
3016 dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
3017 dstgroup->excl = level_size;
3018 dstgroup->excl_cmpr = level_size;
3019 srcgroup->excl = level_size;
3020 srcgroup->excl_cmpr = level_size;
3022 /* inherit the limit info */
3023 dstgroup->lim_flags = srcgroup->lim_flags;
3024 dstgroup->max_rfer = srcgroup->max_rfer;
3025 dstgroup->max_excl = srcgroup->max_excl;
3026 dstgroup->rsv_rfer = srcgroup->rsv_rfer;
3027 dstgroup->rsv_excl = srcgroup->rsv_excl;
3029 qgroup_dirty(fs_info, dstgroup);
3030 qgroup_dirty(fs_info, srcgroup);
3036 i_qgroups = (u64 *)(inherit + 1);
3037 for (i = 0; i < inherit->num_qgroups; ++i) {
3039 ret = add_relation_rb(fs_info, objectid, *i_qgroups);
3046 * If we're doing a snapshot, and adding the snapshot to a new
3047 * qgroup, the numbers are guaranteed to be incorrect.
3053 for (i = 0; i < inherit->num_ref_copies; ++i, i_qgroups += 2) {
3054 struct btrfs_qgroup *src;
3055 struct btrfs_qgroup *dst;
3057 if (!i_qgroups[0] || !i_qgroups[1])
3060 src = find_qgroup_rb(fs_info, i_qgroups[0]);
3061 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3068 dst->rfer = src->rfer - level_size;
3069 dst->rfer_cmpr = src->rfer_cmpr - level_size;
3071 /* Manually tweaking numbers certainly needs a rescan */
3074 for (i = 0; i < inherit->num_excl_copies; ++i, i_qgroups += 2) {
3075 struct btrfs_qgroup *src;
3076 struct btrfs_qgroup *dst;
3078 if (!i_qgroups[0] || !i_qgroups[1])
3081 src = find_qgroup_rb(fs_info, i_qgroups[0]);
3082 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3089 dst->excl = src->excl + level_size;
3090 dst->excl_cmpr = src->excl_cmpr + level_size;
3095 spin_unlock(&fs_info->qgroup_lock);
3097 ret = btrfs_sysfs_add_one_qgroup(fs_info, dstgroup);
3100 mutex_unlock(&fs_info->qgroup_ioctl_lock);
3102 qgroup_mark_inconsistent(fs_info);
3106 static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
3108 if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
3109 qgroup_rsv_total(qg) + (s64)qg->rfer + num_bytes > qg->max_rfer)
3112 if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
3113 qgroup_rsv_total(qg) + (s64)qg->excl + num_bytes > qg->max_excl)
3119 static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce,
3120 enum btrfs_qgroup_rsv_type type)
3122 struct btrfs_qgroup *qgroup;
3123 struct btrfs_fs_info *fs_info = root->fs_info;
3124 u64 ref_root = root->root_key.objectid;
3126 struct ulist_node *unode;
3127 struct ulist_iterator uiter;
3129 if (!is_fstree(ref_root))
3135 if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
3136 capable(CAP_SYS_RESOURCE))
3139 spin_lock(&fs_info->qgroup_lock);
3140 if (!fs_info->quota_root)
3143 qgroup = find_qgroup_rb(fs_info, ref_root);
3148 * in a first step, we check all affected qgroups if any limits would
3151 ulist_reinit(fs_info->qgroup_ulist);
3152 ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3153 qgroup_to_aux(qgroup), GFP_ATOMIC);
3156 ULIST_ITER_INIT(&uiter);
3157 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3158 struct btrfs_qgroup *qg;
3159 struct btrfs_qgroup_list *glist;
3161 qg = unode_aux_to_qgroup(unode);
3163 if (enforce && !qgroup_check_limits(qg, num_bytes)) {
3168 list_for_each_entry(glist, &qg->groups, next_group) {
3169 ret = ulist_add(fs_info->qgroup_ulist,
3170 glist->group->qgroupid,
3171 qgroup_to_aux(glist->group), GFP_ATOMIC);
3178 * no limits exceeded, now record the reservation into all qgroups
3180 ULIST_ITER_INIT(&uiter);
3181 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3182 struct btrfs_qgroup *qg;
3184 qg = unode_aux_to_qgroup(unode);
3186 qgroup_rsv_add(fs_info, qg, num_bytes, type);
3190 spin_unlock(&fs_info->qgroup_lock);
3195 * Free @num_bytes of reserved space with @type for qgroup. (Normally level 0
3198 * Will handle all higher level qgroup too.
3200 * NOTE: If @num_bytes is (u64)-1, this means to free all bytes of this qgroup.
3201 * This special case is only used for META_PERTRANS type.
3203 void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
3204 u64 ref_root, u64 num_bytes,
3205 enum btrfs_qgroup_rsv_type type)
3207 struct btrfs_qgroup *qgroup;
3208 struct ulist_node *unode;
3209 struct ulist_iterator uiter;
3212 if (!is_fstree(ref_root))
3218 if (num_bytes == (u64)-1 && type != BTRFS_QGROUP_RSV_META_PERTRANS) {
3219 WARN(1, "%s: Invalid type to free", __func__);
3222 spin_lock(&fs_info->qgroup_lock);
3224 if (!fs_info->quota_root)
3227 qgroup = find_qgroup_rb(fs_info, ref_root);
3231 if (num_bytes == (u64)-1)
3233 * We're freeing all pertrans rsv, get reserved value from
3234 * level 0 qgroup as real num_bytes to free.
3236 num_bytes = qgroup->rsv.values[type];
3238 ulist_reinit(fs_info->qgroup_ulist);
3239 ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3240 qgroup_to_aux(qgroup), GFP_ATOMIC);
3243 ULIST_ITER_INIT(&uiter);
3244 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3245 struct btrfs_qgroup *qg;
3246 struct btrfs_qgroup_list *glist;
3248 qg = unode_aux_to_qgroup(unode);
3250 qgroup_rsv_release(fs_info, qg, num_bytes, type);
3252 list_for_each_entry(glist, &qg->groups, next_group) {
3253 ret = ulist_add(fs_info->qgroup_ulist,
3254 glist->group->qgroupid,
3255 qgroup_to_aux(glist->group), GFP_ATOMIC);
3262 spin_unlock(&fs_info->qgroup_lock);
3266 * Check if the leaf is the last leaf. Which means all node pointers
3267 * are at their last position.
3269 static bool is_last_leaf(struct btrfs_path *path)
3273 for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
3274 if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
3281 * returns < 0 on error, 0 when more leafs are to be scanned.
3282 * returns 1 when done.
3284 static int qgroup_rescan_leaf(struct btrfs_trans_handle *trans,
3285 struct btrfs_path *path)
3287 struct btrfs_fs_info *fs_info = trans->fs_info;
3288 struct btrfs_root *extent_root;
3289 struct btrfs_key found;
3290 struct extent_buffer *scratch_leaf = NULL;
3291 struct ulist *roots = NULL;
3297 mutex_lock(&fs_info->qgroup_rescan_lock);
3298 extent_root = btrfs_extent_root(fs_info,
3299 fs_info->qgroup_rescan_progress.objectid);
3300 ret = btrfs_search_slot_for_read(extent_root,
3301 &fs_info->qgroup_rescan_progress,
3304 btrfs_debug(fs_info,
3305 "current progress key (%llu %u %llu), search_slot ret %d",
3306 fs_info->qgroup_rescan_progress.objectid,
3307 fs_info->qgroup_rescan_progress.type,
3308 fs_info->qgroup_rescan_progress.offset, ret);
3312 * The rescan is about to end, we will not be scanning any
3313 * further blocks. We cannot unset the RESCAN flag here, because
3314 * we want to commit the transaction if everything went well.
3315 * To make the live accounting work in this phase, we set our
3316 * scan progress pointer such that every real extent objectid
3319 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3320 btrfs_release_path(path);
3321 mutex_unlock(&fs_info->qgroup_rescan_lock);
3324 done = is_last_leaf(path);
3326 btrfs_item_key_to_cpu(path->nodes[0], &found,
3327 btrfs_header_nritems(path->nodes[0]) - 1);
3328 fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;
3330 scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
3331 if (!scratch_leaf) {
3333 mutex_unlock(&fs_info->qgroup_rescan_lock);
3336 slot = path->slots[0];
3337 btrfs_release_path(path);
3338 mutex_unlock(&fs_info->qgroup_rescan_lock);
3340 for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
3341 btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
3342 if (found.type != BTRFS_EXTENT_ITEM_KEY &&
3343 found.type != BTRFS_METADATA_ITEM_KEY)
3345 if (found.type == BTRFS_METADATA_ITEM_KEY)
3346 num_bytes = fs_info->nodesize;
3348 num_bytes = found.offset;
3350 ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
3354 /* For rescan, just pass old_roots as NULL */
3355 ret = btrfs_qgroup_account_extent(trans, found.objectid,
3356 num_bytes, NULL, roots);
3362 free_extent_buffer(scratch_leaf);
3366 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3371 static bool rescan_should_stop(struct btrfs_fs_info *fs_info)
3373 return btrfs_fs_closing(fs_info) ||
3374 test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state) ||
3375 !test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3376 fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN;
3379 static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
3381 struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
3382 qgroup_rescan_work);
3383 struct btrfs_path *path;
3384 struct btrfs_trans_handle *trans = NULL;
3387 bool stopped = false;
3388 bool did_leaf_rescans = false;
3390 path = btrfs_alloc_path();
3394 * Rescan should only search for commit root, and any later difference
3395 * should be recorded by qgroup
3397 path->search_commit_root = 1;
3398 path->skip_locking = 1;
3401 while (!err && !(stopped = rescan_should_stop(fs_info))) {
3402 trans = btrfs_start_transaction(fs_info->fs_root, 0);
3403 if (IS_ERR(trans)) {
3404 err = PTR_ERR(trans);
3408 err = qgroup_rescan_leaf(trans, path);
3409 did_leaf_rescans = true;
3412 btrfs_commit_transaction(trans);
3414 btrfs_end_transaction(trans);
3418 btrfs_free_path(path);
3420 mutex_lock(&fs_info->qgroup_rescan_lock);
3422 fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT) {
3423 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3424 } else if (err < 0 || stopped) {
3425 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3427 mutex_unlock(&fs_info->qgroup_rescan_lock);
3430 * Only update status, since the previous part has already updated the
3431 * qgroup info, and only if we did any actual work. This also prevents
3432 * race with a concurrent quota disable, which has already set
3433 * fs_info->quota_root to NULL and cleared BTRFS_FS_QUOTA_ENABLED at
3434 * btrfs_quota_disable().
3436 if (did_leaf_rescans) {
3437 trans = btrfs_start_transaction(fs_info->quota_root, 1);
3438 if (IS_ERR(trans)) {
3439 err = PTR_ERR(trans);
3442 "fail to start transaction for status update: %d",
3449 mutex_lock(&fs_info->qgroup_rescan_lock);
3451 fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN)
3452 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3454 ret = update_qgroup_status_item(trans);
3457 btrfs_err(fs_info, "fail to update qgroup status: %d",
3461 fs_info->qgroup_rescan_running = false;
3462 fs_info->qgroup_flags &= ~BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN;
3463 complete_all(&fs_info->qgroup_rescan_completion);
3464 mutex_unlock(&fs_info->qgroup_rescan_lock);
3469 btrfs_end_transaction(trans);
3472 btrfs_info(fs_info, "qgroup scan paused");
3473 } else if (fs_info->qgroup_flags & BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN) {
3474 btrfs_info(fs_info, "qgroup scan cancelled");
3475 } else if (err >= 0) {
3476 btrfs_info(fs_info, "qgroup scan completed%s",
3477 err > 0 ? " (inconsistency flag cleared)" : "");
3479 btrfs_err(fs_info, "qgroup scan failed with %d", err);
3484 * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
3485 * memory required for the rescan context.
3488 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
3494 /* we're resuming qgroup rescan at mount time */
3495 if (!(fs_info->qgroup_flags &
3496 BTRFS_QGROUP_STATUS_FLAG_RESCAN)) {
3498 "qgroup rescan init failed, qgroup rescan is not queued");
3500 } else if (!(fs_info->qgroup_flags &
3501 BTRFS_QGROUP_STATUS_FLAG_ON)) {
3503 "qgroup rescan init failed, qgroup is not enabled");
3511 mutex_lock(&fs_info->qgroup_rescan_lock);
3514 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3516 "qgroup rescan is already in progress");
3518 } else if (!(fs_info->qgroup_flags &
3519 BTRFS_QGROUP_STATUS_FLAG_ON)) {
3521 "qgroup rescan init failed, qgroup is not enabled");
3523 } else if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
3524 /* Quota disable is in progress */
3529 mutex_unlock(&fs_info->qgroup_rescan_lock);
3532 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3535 memset(&fs_info->qgroup_rescan_progress, 0,
3536 sizeof(fs_info->qgroup_rescan_progress));
3537 fs_info->qgroup_flags &= ~(BTRFS_QGROUP_RUNTIME_FLAG_CANCEL_RESCAN |
3538 BTRFS_QGROUP_RUNTIME_FLAG_NO_ACCOUNTING);
3539 fs_info->qgroup_rescan_progress.objectid = progress_objectid;
3540 init_completion(&fs_info->qgroup_rescan_completion);
3541 mutex_unlock(&fs_info->qgroup_rescan_lock);
3543 btrfs_init_work(&fs_info->qgroup_rescan_work,
3544 btrfs_qgroup_rescan_worker, NULL, NULL);
3549 qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
3552 struct btrfs_qgroup *qgroup;
3554 spin_lock(&fs_info->qgroup_lock);
3555 /* clear all current qgroup tracking information */
3556 for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
3557 qgroup = rb_entry(n, struct btrfs_qgroup, node);
3559 qgroup->rfer_cmpr = 0;
3561 qgroup->excl_cmpr = 0;
3562 qgroup_dirty(fs_info, qgroup);
3564 spin_unlock(&fs_info->qgroup_lock);
3568 btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
3571 struct btrfs_trans_handle *trans;
3573 ret = qgroup_rescan_init(fs_info, 0, 1);
3578 * We have set the rescan_progress to 0, which means no more
3579 * delayed refs will be accounted by btrfs_qgroup_account_ref.
3580 * However, btrfs_qgroup_account_ref may be right after its call
3581 * to btrfs_find_all_roots, in which case it would still do the
3583 * To solve this, we're committing the transaction, which will
3584 * ensure we run all delayed refs and only after that, we are
3585 * going to clear all tracking information for a clean start.
3588 trans = btrfs_join_transaction(fs_info->fs_root);
3589 if (IS_ERR(trans)) {
3590 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3591 return PTR_ERR(trans);
3593 ret = btrfs_commit_transaction(trans);
3595 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3599 qgroup_rescan_zero_tracking(fs_info);
3601 mutex_lock(&fs_info->qgroup_rescan_lock);
3602 fs_info->qgroup_rescan_running = true;
3603 btrfs_queue_work(fs_info->qgroup_rescan_workers,
3604 &fs_info->qgroup_rescan_work);
3605 mutex_unlock(&fs_info->qgroup_rescan_lock);
3610 int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
3616 mutex_lock(&fs_info->qgroup_rescan_lock);
3617 running = fs_info->qgroup_rescan_running;
3618 mutex_unlock(&fs_info->qgroup_rescan_lock);
3624 ret = wait_for_completion_interruptible(
3625 &fs_info->qgroup_rescan_completion);
3627 wait_for_completion(&fs_info->qgroup_rescan_completion);
3633 * this is only called from open_ctree where we're still single threaded, thus
3634 * locking is omitted here.
3637 btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
3639 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3640 mutex_lock(&fs_info->qgroup_rescan_lock);
3641 fs_info->qgroup_rescan_running = true;
3642 btrfs_queue_work(fs_info->qgroup_rescan_workers,
3643 &fs_info->qgroup_rescan_work);
3644 mutex_unlock(&fs_info->qgroup_rescan_lock);
3648 #define rbtree_iterate_from_safe(node, next, start) \
3649 for (node = start; node && ({ next = rb_next(node); 1;}); node = next)
3651 static int qgroup_unreserve_range(struct btrfs_inode *inode,
3652 struct extent_changeset *reserved, u64 start,
3655 struct rb_node *node;
3656 struct rb_node *next;
3657 struct ulist_node *entry;
3660 node = reserved->range_changed.root.rb_node;
3664 entry = rb_entry(node, struct ulist_node, rb_node);
3665 if (entry->val < start)
3666 node = node->rb_right;
3668 node = node->rb_left;
3671 if (entry->val > start && rb_prev(&entry->rb_node))
3672 entry = rb_entry(rb_prev(&entry->rb_node), struct ulist_node,
3675 rbtree_iterate_from_safe(node, next, &entry->rb_node) {
3681 entry = rb_entry(node, struct ulist_node, rb_node);
3682 entry_start = entry->val;
3683 entry_end = entry->aux;
3684 entry_len = entry_end - entry_start + 1;
3686 if (entry_start >= start + len)
3688 if (entry_start + entry_len <= start)
3691 * Now the entry is in [start, start + len), revert the
3692 * EXTENT_QGROUP_RESERVED bit.
3694 clear_ret = clear_extent_bits(&inode->io_tree, entry_start,
3695 entry_end, EXTENT_QGROUP_RESERVED);
3696 if (!ret && clear_ret < 0)
3699 ulist_del(&reserved->range_changed, entry->val, entry->aux);
3700 if (likely(reserved->bytes_changed >= entry_len)) {
3701 reserved->bytes_changed -= entry_len;
3704 reserved->bytes_changed = 0;
3712 * Try to free some space for qgroup.
3714 * For qgroup, there are only 3 ways to free qgroup space:
3715 * - Flush nodatacow write
3716 * Any nodatacow write will free its reserved data space at run_delalloc_range().
3717 * In theory, we should only flush nodatacow inodes, but it's not yet
3718 * possible, so we need to flush the whole root.
3720 * - Wait for ordered extents
3721 * When ordered extents are finished, their reserved metadata is finally
3722 * converted to per_trans status, which can be freed by later commit
3725 * - Commit transaction
3726 * This would free the meta_per_trans space.
3727 * In theory this shouldn't provide much space, but any more qgroup space
3730 static int try_flush_qgroup(struct btrfs_root *root)
3732 struct btrfs_trans_handle *trans;
3735 /* Can't hold an open transaction or we run the risk of deadlocking. */
3736 ASSERT(current->journal_info == NULL);
3737 if (WARN_ON(current->journal_info))
3741 * We don't want to run flush again and again, so if there is a running
3742 * one, we won't try to start a new flush, but exit directly.
3744 if (test_and_set_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state)) {
3745 wait_event(root->qgroup_flush_wait,
3746 !test_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state));
3750 ret = btrfs_start_delalloc_snapshot(root, true);
3753 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
3755 trans = btrfs_join_transaction(root);
3756 if (IS_ERR(trans)) {
3757 ret = PTR_ERR(trans);
3761 ret = btrfs_commit_transaction(trans);
3763 clear_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state);
3764 wake_up(&root->qgroup_flush_wait);
3768 static int qgroup_reserve_data(struct btrfs_inode *inode,
3769 struct extent_changeset **reserved_ret, u64 start,
3772 struct btrfs_root *root = inode->root;
3773 struct extent_changeset *reserved;
3774 bool new_reserved = false;
3779 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
3780 !is_fstree(root->root_key.objectid) || len == 0)
3783 /* @reserved parameter is mandatory for qgroup */
3784 if (WARN_ON(!reserved_ret))
3786 if (!*reserved_ret) {
3787 new_reserved = true;
3788 *reserved_ret = extent_changeset_alloc();
3792 reserved = *reserved_ret;
3793 /* Record already reserved space */
3794 orig_reserved = reserved->bytes_changed;
3795 ret = set_record_extent_bits(&inode->io_tree, start,
3796 start + len -1, EXTENT_QGROUP_RESERVED, reserved);
3798 /* Newly reserved space */
3799 to_reserve = reserved->bytes_changed - orig_reserved;
3800 trace_btrfs_qgroup_reserve_data(&inode->vfs_inode, start, len,
3801 to_reserve, QGROUP_RESERVE);
3804 ret = qgroup_reserve(root, to_reserve, true, BTRFS_QGROUP_RSV_DATA);
3811 qgroup_unreserve_range(inode, reserved, start, len);
3814 extent_changeset_free(reserved);
3815 *reserved_ret = NULL;
3821 * Reserve qgroup space for range [start, start + len).
3823 * This function will either reserve space from related qgroups or do nothing
3824 * if the range is already reserved.
3826 * Return 0 for successful reservation
3827 * Return <0 for error (including -EQUOT)
3829 * NOTE: This function may sleep for memory allocation, dirty page flushing and
3830 * commit transaction. So caller should not hold any dirty page locked.
3832 int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
3833 struct extent_changeset **reserved_ret, u64 start,
3838 ret = qgroup_reserve_data(inode, reserved_ret, start, len);
3839 if (ret <= 0 && ret != -EDQUOT)
3842 ret = try_flush_qgroup(inode->root);
3845 return qgroup_reserve_data(inode, reserved_ret, start, len);
3848 /* Free ranges specified by @reserved, normally in error path */
3849 static int qgroup_free_reserved_data(struct btrfs_inode *inode,
3850 struct extent_changeset *reserved,
3851 u64 start, u64 len, u64 *freed_ret)
3853 struct btrfs_root *root = inode->root;
3854 struct ulist_node *unode;
3855 struct ulist_iterator uiter;
3856 struct extent_changeset changeset;
3860 extent_changeset_init(&changeset);
3861 len = round_up(start + len, root->fs_info->sectorsize);
3862 start = round_down(start, root->fs_info->sectorsize);
3864 ULIST_ITER_INIT(&uiter);
3865 while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
3866 u64 range_start = unode->val;
3867 /* unode->aux is the inclusive end */
3868 u64 range_len = unode->aux - range_start + 1;
3872 extent_changeset_release(&changeset);
3874 /* Only free range in range [start, start + len) */
3875 if (range_start >= start + len ||
3876 range_start + range_len <= start)
3878 free_start = max(range_start, start);
3879 free_len = min(start + len, range_start + range_len) -
3882 * TODO: To also modify reserved->ranges_reserved to reflect
3885 * However as long as we free qgroup reserved according to
3886 * EXTENT_QGROUP_RESERVED, we won't double free.
3887 * So not need to rush.
3889 ret = clear_record_extent_bits(&inode->io_tree, free_start,
3890 free_start + free_len - 1,
3891 EXTENT_QGROUP_RESERVED, &changeset);
3894 freed += changeset.bytes_changed;
3896 btrfs_qgroup_free_refroot(root->fs_info, root->root_key.objectid, freed,
3897 BTRFS_QGROUP_RSV_DATA);
3902 extent_changeset_release(&changeset);
3906 static int __btrfs_qgroup_release_data(struct btrfs_inode *inode,
3907 struct extent_changeset *reserved, u64 start, u64 len,
3908 u64 *released, int free)
3910 struct extent_changeset changeset;
3911 int trace_op = QGROUP_RELEASE;
3914 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &inode->root->fs_info->flags))
3917 /* In release case, we shouldn't have @reserved */
3918 WARN_ON(!free && reserved);
3919 if (free && reserved)
3920 return qgroup_free_reserved_data(inode, reserved, start, len, released);
3921 extent_changeset_init(&changeset);
3922 ret = clear_record_extent_bits(&inode->io_tree, start, start + len -1,
3923 EXTENT_QGROUP_RESERVED, &changeset);
3928 trace_op = QGROUP_FREE;
3929 trace_btrfs_qgroup_release_data(&inode->vfs_inode, start, len,
3930 changeset.bytes_changed, trace_op);
3932 btrfs_qgroup_free_refroot(inode->root->fs_info,
3933 inode->root->root_key.objectid,
3934 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
3936 *released = changeset.bytes_changed;
3938 extent_changeset_release(&changeset);
3943 * Free a reserved space range from io_tree and related qgroups
3945 * Should be called when a range of pages get invalidated before reaching disk.
3946 * Or for error cleanup case.
3947 * if @reserved is given, only reserved range in [@start, @start + @len) will
3950 * For data written to disk, use btrfs_qgroup_release_data().
3952 * NOTE: This function may sleep for memory allocation.
3954 int btrfs_qgroup_free_data(struct btrfs_inode *inode,
3955 struct extent_changeset *reserved,
3956 u64 start, u64 len, u64 *freed)
3958 return __btrfs_qgroup_release_data(inode, reserved, start, len, freed, 1);
3962 * Release a reserved space range from io_tree only.
3964 * Should be called when a range of pages get written to disk and corresponding
3965 * FILE_EXTENT is inserted into corresponding root.
3967 * Since new qgroup accounting framework will only update qgroup numbers at
3968 * commit_transaction() time, its reserved space shouldn't be freed from
3971 * But we should release the range from io_tree, to allow further write to be
3974 * NOTE: This function may sleep for memory allocation.
3976 int btrfs_qgroup_release_data(struct btrfs_inode *inode, u64 start, u64 len, u64 *released)
3978 return __btrfs_qgroup_release_data(inode, NULL, start, len, released, 0);
3981 static void add_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3982 enum btrfs_qgroup_rsv_type type)
3984 if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3985 type != BTRFS_QGROUP_RSV_META_PERTRANS)
3990 spin_lock(&root->qgroup_meta_rsv_lock);
3991 if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
3992 root->qgroup_meta_rsv_prealloc += num_bytes;
3994 root->qgroup_meta_rsv_pertrans += num_bytes;
3995 spin_unlock(&root->qgroup_meta_rsv_lock);
3998 static int sub_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3999 enum btrfs_qgroup_rsv_type type)
4001 if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
4002 type != BTRFS_QGROUP_RSV_META_PERTRANS)
4007 spin_lock(&root->qgroup_meta_rsv_lock);
4008 if (type == BTRFS_QGROUP_RSV_META_PREALLOC) {
4009 num_bytes = min_t(u64, root->qgroup_meta_rsv_prealloc,
4011 root->qgroup_meta_rsv_prealloc -= num_bytes;
4013 num_bytes = min_t(u64, root->qgroup_meta_rsv_pertrans,
4015 root->qgroup_meta_rsv_pertrans -= num_bytes;
4017 spin_unlock(&root->qgroup_meta_rsv_lock);
4021 int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
4022 enum btrfs_qgroup_rsv_type type, bool enforce)
4024 struct btrfs_fs_info *fs_info = root->fs_info;
4027 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4028 !is_fstree(root->root_key.objectid) || num_bytes == 0)
4031 BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4032 trace_qgroup_meta_reserve(root, (s64)num_bytes, type);
4033 ret = qgroup_reserve(root, num_bytes, enforce, type);
4037 * Record what we have reserved into root.
4039 * To avoid quota disabled->enabled underflow.
4040 * In that case, we may try to free space we haven't reserved
4041 * (since quota was disabled), so record what we reserved into root.
4042 * And ensure later release won't underflow this number.
4044 add_root_meta_rsv(root, num_bytes, type);
4048 int __btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
4049 enum btrfs_qgroup_rsv_type type, bool enforce,
4054 ret = btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4055 if ((ret <= 0 && ret != -EDQUOT) || noflush)
4058 ret = try_flush_qgroup(root);
4061 return btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4064 void btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root *root)
4066 struct btrfs_fs_info *fs_info = root->fs_info;
4068 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4069 !is_fstree(root->root_key.objectid))
4072 /* TODO: Update trace point to handle such free */
4073 trace_qgroup_meta_free_all_pertrans(root);
4074 /* Special value -1 means to free all reserved space */
4075 btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid, (u64)-1,
4076 BTRFS_QGROUP_RSV_META_PERTRANS);
4079 void __btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes,
4080 enum btrfs_qgroup_rsv_type type)
4082 struct btrfs_fs_info *fs_info = root->fs_info;
4084 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4085 !is_fstree(root->root_key.objectid))
4089 * reservation for META_PREALLOC can happen before quota is enabled,
4090 * which can lead to underflow.
4091 * Here ensure we will only free what we really have reserved.
4093 num_bytes = sub_root_meta_rsv(root, num_bytes, type);
4094 BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4095 trace_qgroup_meta_reserve(root, -(s64)num_bytes, type);
4096 btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid,
4100 static void qgroup_convert_meta(struct btrfs_fs_info *fs_info, u64 ref_root,
4103 struct btrfs_qgroup *qgroup;
4104 struct ulist_node *unode;
4105 struct ulist_iterator uiter;
4110 if (!fs_info->quota_root)
4113 spin_lock(&fs_info->qgroup_lock);
4114 qgroup = find_qgroup_rb(fs_info, ref_root);
4117 ulist_reinit(fs_info->qgroup_ulist);
4118 ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
4119 qgroup_to_aux(qgroup), GFP_ATOMIC);
4122 ULIST_ITER_INIT(&uiter);
4123 while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
4124 struct btrfs_qgroup *qg;
4125 struct btrfs_qgroup_list *glist;
4127 qg = unode_aux_to_qgroup(unode);
4129 qgroup_rsv_release(fs_info, qg, num_bytes,
4130 BTRFS_QGROUP_RSV_META_PREALLOC);
4131 qgroup_rsv_add(fs_info, qg, num_bytes,
4132 BTRFS_QGROUP_RSV_META_PERTRANS);
4133 list_for_each_entry(glist, &qg->groups, next_group) {
4134 ret = ulist_add(fs_info->qgroup_ulist,
4135 glist->group->qgroupid,
4136 qgroup_to_aux(glist->group), GFP_ATOMIC);
4142 spin_unlock(&fs_info->qgroup_lock);
4145 void btrfs_qgroup_convert_reserved_meta(struct btrfs_root *root, int num_bytes)
4147 struct btrfs_fs_info *fs_info = root->fs_info;
4149 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4150 !is_fstree(root->root_key.objectid))
4152 /* Same as btrfs_qgroup_free_meta_prealloc() */
4153 num_bytes = sub_root_meta_rsv(root, num_bytes,
4154 BTRFS_QGROUP_RSV_META_PREALLOC);
4155 trace_qgroup_meta_convert(root, num_bytes);
4156 qgroup_convert_meta(fs_info, root->root_key.objectid, num_bytes);
4157 if (!sb_rdonly(fs_info->sb))
4158 add_root_meta_rsv(root, num_bytes, BTRFS_QGROUP_RSV_META_PERTRANS);
4162 * Check qgroup reserved space leaking, normally at destroy inode
4165 void btrfs_qgroup_check_reserved_leak(struct btrfs_inode *inode)
4167 struct extent_changeset changeset;
4168 struct ulist_node *unode;
4169 struct ulist_iterator iter;
4172 extent_changeset_init(&changeset);
4173 ret = clear_record_extent_bits(&inode->io_tree, 0, (u64)-1,
4174 EXTENT_QGROUP_RESERVED, &changeset);
4177 if (WARN_ON(changeset.bytes_changed)) {
4178 ULIST_ITER_INIT(&iter);
4179 while ((unode = ulist_next(&changeset.range_changed, &iter))) {
4180 btrfs_warn(inode->root->fs_info,
4181 "leaking qgroup reserved space, ino: %llu, start: %llu, end: %llu",
4182 btrfs_ino(inode), unode->val, unode->aux);
4184 btrfs_qgroup_free_refroot(inode->root->fs_info,
4185 inode->root->root_key.objectid,
4186 changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
4189 extent_changeset_release(&changeset);
4192 void btrfs_qgroup_init_swapped_blocks(
4193 struct btrfs_qgroup_swapped_blocks *swapped_blocks)
4197 spin_lock_init(&swapped_blocks->lock);
4198 for (i = 0; i < BTRFS_MAX_LEVEL; i++)
4199 swapped_blocks->blocks[i] = RB_ROOT;
4200 swapped_blocks->swapped = false;
4204 * Delete all swapped blocks record of @root.
4205 * Every record here means we skipped a full subtree scan for qgroup.
4207 * Gets called when committing one transaction.
4209 void btrfs_qgroup_clean_swapped_blocks(struct btrfs_root *root)
4211 struct btrfs_qgroup_swapped_blocks *swapped_blocks;
4214 swapped_blocks = &root->swapped_blocks;
4216 spin_lock(&swapped_blocks->lock);
4217 if (!swapped_blocks->swapped)
4219 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4220 struct rb_root *cur_root = &swapped_blocks->blocks[i];
4221 struct btrfs_qgroup_swapped_block *entry;
4222 struct btrfs_qgroup_swapped_block *next;
4224 rbtree_postorder_for_each_entry_safe(entry, next, cur_root,
4227 swapped_blocks->blocks[i] = RB_ROOT;
4229 swapped_blocks->swapped = false;
4231 spin_unlock(&swapped_blocks->lock);
4235 * Add subtree roots record into @subvol_root.
4237 * @subvol_root: tree root of the subvolume tree get swapped
4238 * @bg: block group under balance
4239 * @subvol_parent/slot: pointer to the subtree root in subvolume tree
4240 * @reloc_parent/slot: pointer to the subtree root in reloc tree
4241 * BOTH POINTERS ARE BEFORE TREE SWAP
4242 * @last_snapshot: last snapshot generation of the subvolume tree
4244 int btrfs_qgroup_add_swapped_blocks(struct btrfs_trans_handle *trans,
4245 struct btrfs_root *subvol_root,
4246 struct btrfs_block_group *bg,
4247 struct extent_buffer *subvol_parent, int subvol_slot,
4248 struct extent_buffer *reloc_parent, int reloc_slot,
4251 struct btrfs_fs_info *fs_info = subvol_root->fs_info;
4252 struct btrfs_qgroup_swapped_blocks *blocks = &subvol_root->swapped_blocks;
4253 struct btrfs_qgroup_swapped_block *block;
4254 struct rb_node **cur;
4255 struct rb_node *parent = NULL;
4256 int level = btrfs_header_level(subvol_parent) - 1;
4259 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4262 if (btrfs_node_ptr_generation(subvol_parent, subvol_slot) >
4263 btrfs_node_ptr_generation(reloc_parent, reloc_slot)) {
4264 btrfs_err_rl(fs_info,
4265 "%s: bad parameter order, subvol_gen=%llu reloc_gen=%llu",
4267 btrfs_node_ptr_generation(subvol_parent, subvol_slot),
4268 btrfs_node_ptr_generation(reloc_parent, reloc_slot));
4272 block = kmalloc(sizeof(*block), GFP_NOFS);
4279 * @reloc_parent/slot is still before swap, while @block is going to
4280 * record the bytenr after swap, so we do the swap here.
4282 block->subvol_bytenr = btrfs_node_blockptr(reloc_parent, reloc_slot);
4283 block->subvol_generation = btrfs_node_ptr_generation(reloc_parent,
4285 block->reloc_bytenr = btrfs_node_blockptr(subvol_parent, subvol_slot);
4286 block->reloc_generation = btrfs_node_ptr_generation(subvol_parent,
4288 block->last_snapshot = last_snapshot;
4289 block->level = level;
4292 * If we have bg == NULL, we're called from btrfs_recover_relocation(),
4293 * no one else can modify tree blocks thus we qgroup will not change
4294 * no matter the value of trace_leaf.
4296 if (bg && bg->flags & BTRFS_BLOCK_GROUP_DATA)
4297 block->trace_leaf = true;
4299 block->trace_leaf = false;
4300 btrfs_node_key_to_cpu(reloc_parent, &block->first_key, reloc_slot);
4302 /* Insert @block into @blocks */
4303 spin_lock(&blocks->lock);
4304 cur = &blocks->blocks[level].rb_node;
4306 struct btrfs_qgroup_swapped_block *entry;
4309 entry = rb_entry(parent, struct btrfs_qgroup_swapped_block,
4312 if (entry->subvol_bytenr < block->subvol_bytenr) {
4313 cur = &(*cur)->rb_left;
4314 } else if (entry->subvol_bytenr > block->subvol_bytenr) {
4315 cur = &(*cur)->rb_right;
4317 if (entry->subvol_generation !=
4318 block->subvol_generation ||
4319 entry->reloc_bytenr != block->reloc_bytenr ||
4320 entry->reloc_generation !=
4321 block->reloc_generation) {
4323 * Duplicated but mismatch entry found.
4326 * Marking qgroup inconsistent should be enough
4329 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4336 rb_link_node(&block->node, parent, cur);
4337 rb_insert_color(&block->node, &blocks->blocks[level]);
4338 blocks->swapped = true;
4340 spin_unlock(&blocks->lock);
4343 qgroup_mark_inconsistent(fs_info);
4348 * Check if the tree block is a subtree root, and if so do the needed
4349 * delayed subtree trace for qgroup.
4351 * This is called during btrfs_cow_block().
4353 int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans,
4354 struct btrfs_root *root,
4355 struct extent_buffer *subvol_eb)
4357 struct btrfs_fs_info *fs_info = root->fs_info;
4358 struct btrfs_qgroup_swapped_blocks *blocks = &root->swapped_blocks;
4359 struct btrfs_qgroup_swapped_block *block;
4360 struct extent_buffer *reloc_eb = NULL;
4361 struct rb_node *node;
4363 bool swapped = false;
4364 int level = btrfs_header_level(subvol_eb);
4368 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4370 if (!is_fstree(root->root_key.objectid) || !root->reloc_root)
4373 spin_lock(&blocks->lock);
4374 if (!blocks->swapped) {
4375 spin_unlock(&blocks->lock);
4378 node = blocks->blocks[level].rb_node;
4381 block = rb_entry(node, struct btrfs_qgroup_swapped_block, node);
4382 if (block->subvol_bytenr < subvol_eb->start) {
4383 node = node->rb_left;
4384 } else if (block->subvol_bytenr > subvol_eb->start) {
4385 node = node->rb_right;
4392 spin_unlock(&blocks->lock);
4395 /* Found one, remove it from @blocks first and update blocks->swapped */
4396 rb_erase(&block->node, &blocks->blocks[level]);
4397 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4398 if (RB_EMPTY_ROOT(&blocks->blocks[i])) {
4403 blocks->swapped = swapped;
4404 spin_unlock(&blocks->lock);
4406 /* Read out reloc subtree root */
4407 reloc_eb = read_tree_block(fs_info, block->reloc_bytenr, 0,
4408 block->reloc_generation, block->level,
4410 if (IS_ERR(reloc_eb)) {
4411 ret = PTR_ERR(reloc_eb);
4415 if (!extent_buffer_uptodate(reloc_eb)) {
4420 ret = qgroup_trace_subtree_swap(trans, reloc_eb, subvol_eb,
4421 block->last_snapshot, block->trace_leaf);
4424 free_extent_buffer(reloc_eb);
4427 btrfs_err_rl(fs_info,
4428 "failed to account subtree at bytenr %llu: %d",
4429 subvol_eb->start, ret);
4430 qgroup_mark_inconsistent(fs_info);
4435 void btrfs_qgroup_destroy_extent_records(struct btrfs_transaction *trans)
4437 struct btrfs_qgroup_extent_record *entry;
4438 struct btrfs_qgroup_extent_record *next;
4439 struct rb_root *root;
4441 root = &trans->delayed_refs.dirty_extent_root;
4442 rbtree_postorder_for_each_entry_safe(entry, next, root, node) {
4443 ulist_free(entry->old_roots);