root/fs/btrfs/qgroup.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. qgroup_rsv_total
  2. qgroup_rsv_type_str
  3. qgroup_rsv_add
  4. qgroup_rsv_release
  5. qgroup_rsv_add_by_qgroup
  6. qgroup_rsv_release_by_qgroup
  7. btrfs_qgroup_update_old_refcnt
  8. btrfs_qgroup_update_new_refcnt
  9. btrfs_qgroup_get_old_refcnt
  10. btrfs_qgroup_get_new_refcnt
  11. qgroup_to_aux
  12. unode_aux_to_qgroup
  13. find_qgroup_rb
  14. add_qgroup_rb
  15. __del_qgroup_rb
  16. del_qgroup_rb
  17. add_relation_rb
  18. del_relation_rb
  19. btrfs_verify_qgroup_counts
  20. btrfs_read_qgroup_config
  21. btrfs_free_qgroup_config
  22. add_qgroup_relation_item
  23. del_qgroup_relation_item
  24. add_qgroup_item
  25. del_qgroup_item
  26. update_qgroup_limit_item
  27. update_qgroup_info_item
  28. update_qgroup_status_item
  29. btrfs_clean_quota_tree
  30. btrfs_quota_enable
  31. btrfs_quota_disable
  32. qgroup_dirty
  33. __qgroup_excl_accounting
  34. quick_update_accounting
  35. btrfs_add_qgroup_relation
  36. __del_qgroup_relation
  37. btrfs_del_qgroup_relation
  38. btrfs_create_qgroup
  39. btrfs_remove_qgroup
  40. btrfs_limit_qgroup
  41. btrfs_qgroup_trace_extent_nolock
  42. btrfs_qgroup_trace_extent_post
  43. btrfs_qgroup_trace_extent
  44. btrfs_qgroup_trace_leaf_items
  45. adjust_slots_upwards
  46. qgroup_trace_extent_swap
  47. qgroup_trace_new_subtree_blocks
  48. qgroup_trace_subtree_swap
  49. btrfs_qgroup_trace_subtree
  50. qgroup_update_refcnt
  51. qgroup_update_counters
  52. maybe_fs_roots
  53. btrfs_qgroup_account_extent
  54. btrfs_qgroup_account_extents
  55. btrfs_run_qgroups
  56. btrfs_qgroup_inherit
  57. qgroup_check_limits
  58. qgroup_reserve
  59. btrfs_qgroup_free_refroot
  60. is_last_leaf
  61. qgroup_rescan_leaf
  62. btrfs_qgroup_rescan_worker
  63. qgroup_rescan_init
  64. qgroup_rescan_zero_tracking
  65. btrfs_qgroup_rescan
  66. btrfs_qgroup_wait_for_completion
  67. btrfs_qgroup_rescan_resume
  68. btrfs_qgroup_reserve_data
  69. qgroup_free_reserved_data
  70. __btrfs_qgroup_release_data
  71. btrfs_qgroup_free_data
  72. btrfs_qgroup_release_data
  73. add_root_meta_rsv
  74. sub_root_meta_rsv
  75. __btrfs_qgroup_reserve_meta
  76. btrfs_qgroup_free_meta_all_pertrans
  77. __btrfs_qgroup_free_meta
  78. qgroup_convert_meta
  79. btrfs_qgroup_convert_reserved_meta
  80. btrfs_qgroup_check_reserved_leak
  81. btrfs_qgroup_init_swapped_blocks
  82. btrfs_qgroup_clean_swapped_blocks
  83. btrfs_qgroup_add_swapped_blocks
  84. btrfs_qgroup_trace_subtree_after_cow
  85. btrfs_qgroup_destroy_extent_records

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

/* [<][>][^][v][top][bottom][index][help] */