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