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