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