GNU Linux-libre 4.14.328-gnu1
[releases.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         btrfs_free_path(path);
428         fs_info->qgroup_flags |= flags;
429         if (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))
430                 clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
431         else if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN &&
432                  ret >= 0)
433                 ret = qgroup_rescan_init(fs_info, rescan_progress, 0);
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 {
727         struct btrfs_fs_info *fs_info = trans->fs_info;
728         struct btrfs_root *quota_root = fs_info->quota_root;
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, quota_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         spin_lock(&fs_info->trans_lock);
973         list_del(&quota_root->dirty_list);
974         spin_unlock(&fs_info->trans_lock);
975
976         btrfs_tree_lock(quota_root->node);
977         clean_tree_block(fs_info, quota_root->node);
978         btrfs_tree_unlock(quota_root->node);
979         btrfs_free_tree_block(trans, quota_root, quota_root->node, 0, 1);
980
981         free_extent_buffer(quota_root->node);
982         free_extent_buffer(quota_root->commit_root);
983         kfree(quota_root);
984 out:
985         mutex_unlock(&fs_info->qgroup_ioctl_lock);
986         return ret;
987 }
988
989 static void qgroup_dirty(struct btrfs_fs_info *fs_info,
990                          struct btrfs_qgroup *qgroup)
991 {
992         if (list_empty(&qgroup->dirty))
993                 list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
994 }
995
996 static void report_reserved_underflow(struct btrfs_fs_info *fs_info,
997                                       struct btrfs_qgroup *qgroup,
998                                       u64 num_bytes)
999 {
1000 #ifdef CONFIG_BTRFS_DEBUG
1001         WARN_ON(qgroup->reserved < num_bytes);
1002         btrfs_debug(fs_info,
1003                 "qgroup %llu reserved space underflow, have: %llu, to free: %llu",
1004                 qgroup->qgroupid, qgroup->reserved, num_bytes);
1005 #endif
1006         qgroup->reserved = 0;
1007 }
1008 /*
1009  * The easy accounting, if we are adding/removing the only ref for an extent
1010  * then this qgroup and all of the parent qgroups get their reference and
1011  * exclusive counts adjusted.
1012  *
1013  * Caller should hold fs_info->qgroup_lock.
1014  */
1015 static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
1016                                     struct ulist *tmp, u64 ref_root,
1017                                     u64 num_bytes, int sign)
1018 {
1019         struct btrfs_qgroup *qgroup;
1020         struct btrfs_qgroup_list *glist;
1021         struct ulist_node *unode;
1022         struct ulist_iterator uiter;
1023         int ret = 0;
1024
1025         qgroup = find_qgroup_rb(fs_info, ref_root);
1026         if (!qgroup)
1027                 goto out;
1028
1029         qgroup->rfer += sign * num_bytes;
1030         qgroup->rfer_cmpr += sign * num_bytes;
1031
1032         WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1033         qgroup->excl += sign * num_bytes;
1034         qgroup->excl_cmpr += sign * num_bytes;
1035         if (sign > 0) {
1036                 trace_qgroup_update_reserve(fs_info, qgroup, -(s64)num_bytes);
1037                 if (qgroup->reserved < num_bytes)
1038                         report_reserved_underflow(fs_info, qgroup, num_bytes);
1039                 else
1040                         qgroup->reserved -= num_bytes;
1041         }
1042
1043         qgroup_dirty(fs_info, qgroup);
1044
1045         /* Get all of the parent groups that contain this qgroup */
1046         list_for_each_entry(glist, &qgroup->groups, next_group) {
1047                 ret = ulist_add(tmp, glist->group->qgroupid,
1048                                 qgroup_to_aux(glist->group), GFP_ATOMIC);
1049                 if (ret < 0)
1050                         goto out;
1051         }
1052
1053         /* Iterate all of the parents and adjust their reference counts */
1054         ULIST_ITER_INIT(&uiter);
1055         while ((unode = ulist_next(tmp, &uiter))) {
1056                 qgroup = unode_aux_to_qgroup(unode);
1057                 qgroup->rfer += sign * num_bytes;
1058                 qgroup->rfer_cmpr += sign * num_bytes;
1059                 WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1060                 qgroup->excl += sign * num_bytes;
1061                 if (sign > 0) {
1062                         trace_qgroup_update_reserve(fs_info, qgroup,
1063                                                     -(s64)num_bytes);
1064                         if (qgroup->reserved < num_bytes)
1065                                 report_reserved_underflow(fs_info, qgroup,
1066                                                           num_bytes);
1067                         else
1068                                 qgroup->reserved -= num_bytes;
1069                 }
1070                 qgroup->excl_cmpr += sign * num_bytes;
1071                 qgroup_dirty(fs_info, qgroup);
1072
1073                 /* Add any parents of the parents */
1074                 list_for_each_entry(glist, &qgroup->groups, next_group) {
1075                         ret = ulist_add(tmp, glist->group->qgroupid,
1076                                         qgroup_to_aux(glist->group), GFP_ATOMIC);
1077                         if (ret < 0)
1078                                 goto out;
1079                 }
1080         }
1081         ret = 0;
1082 out:
1083         return ret;
1084 }
1085
1086
1087 /*
1088  * Quick path for updating qgroup with only excl refs.
1089  *
1090  * In that case, just update all parent will be enough.
1091  * Or we needs to do a full rescan.
1092  * Caller should also hold fs_info->qgroup_lock.
1093  *
1094  * Return 0 for quick update, return >0 for need to full rescan
1095  * and mark INCONSISTENT flag.
1096  * Return < 0 for other error.
1097  */
1098 static int quick_update_accounting(struct btrfs_fs_info *fs_info,
1099                                    struct ulist *tmp, u64 src, u64 dst,
1100                                    int sign)
1101 {
1102         struct btrfs_qgroup *qgroup;
1103         int ret = 1;
1104         int err = 0;
1105
1106         qgroup = find_qgroup_rb(fs_info, src);
1107         if (!qgroup)
1108                 goto out;
1109         if (qgroup->excl == qgroup->rfer) {
1110                 ret = 0;
1111                 err = __qgroup_excl_accounting(fs_info, tmp, dst,
1112                                                qgroup->excl, sign);
1113                 if (err < 0) {
1114                         ret = err;
1115                         goto out;
1116                 }
1117         }
1118 out:
1119         if (ret)
1120                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1121         return ret;
1122 }
1123
1124 int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans,
1125                               struct btrfs_fs_info *fs_info, u64 src, u64 dst)
1126 {
1127         struct btrfs_root *quota_root;
1128         struct btrfs_qgroup *parent;
1129         struct btrfs_qgroup *member;
1130         struct btrfs_qgroup_list *list;
1131         struct ulist *tmp;
1132         int ret = 0;
1133
1134         /* Check the level of src and dst first */
1135         if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
1136                 return -EINVAL;
1137
1138         tmp = ulist_alloc(GFP_KERNEL);
1139         if (!tmp)
1140                 return -ENOMEM;
1141
1142         mutex_lock(&fs_info->qgroup_ioctl_lock);
1143         quota_root = fs_info->quota_root;
1144         if (!quota_root) {
1145                 ret = -EINVAL;
1146                 goto out;
1147         }
1148         member = find_qgroup_rb(fs_info, src);
1149         parent = find_qgroup_rb(fs_info, dst);
1150         if (!member || !parent) {
1151                 ret = -EINVAL;
1152                 goto out;
1153         }
1154
1155         /* check if such qgroup relation exist firstly */
1156         list_for_each_entry(list, &member->groups, next_group) {
1157                 if (list->group == parent) {
1158                         ret = -EEXIST;
1159                         goto out;
1160                 }
1161         }
1162
1163         ret = add_qgroup_relation_item(trans, quota_root, src, dst);
1164         if (ret)
1165                 goto out;
1166
1167         ret = add_qgroup_relation_item(trans, quota_root, dst, src);
1168         if (ret) {
1169                 del_qgroup_relation_item(trans, quota_root, src, dst);
1170                 goto out;
1171         }
1172
1173         spin_lock(&fs_info->qgroup_lock);
1174         ret = add_relation_rb(fs_info, src, dst);
1175         if (ret < 0) {
1176                 spin_unlock(&fs_info->qgroup_lock);
1177                 goto out;
1178         }
1179         ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1180         spin_unlock(&fs_info->qgroup_lock);
1181 out:
1182         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1183         ulist_free(tmp);
1184         return ret;
1185 }
1186
1187 static int __del_qgroup_relation(struct btrfs_trans_handle *trans,
1188                               struct btrfs_fs_info *fs_info, u64 src, u64 dst)
1189 {
1190         struct btrfs_root *quota_root;
1191         struct btrfs_qgroup *parent;
1192         struct btrfs_qgroup *member;
1193         struct btrfs_qgroup_list *list;
1194         struct ulist *tmp;
1195         int ret = 0;
1196         int err;
1197
1198         tmp = ulist_alloc(GFP_KERNEL);
1199         if (!tmp)
1200                 return -ENOMEM;
1201
1202         quota_root = fs_info->quota_root;
1203         if (!quota_root) {
1204                 ret = -EINVAL;
1205                 goto out;
1206         }
1207
1208         member = find_qgroup_rb(fs_info, src);
1209         parent = find_qgroup_rb(fs_info, dst);
1210         if (!member || !parent) {
1211                 ret = -EINVAL;
1212                 goto out;
1213         }
1214
1215         /* check if such qgroup relation exist firstly */
1216         list_for_each_entry(list, &member->groups, next_group) {
1217                 if (list->group == parent)
1218                         goto exist;
1219         }
1220         ret = -ENOENT;
1221         goto out;
1222 exist:
1223         ret = del_qgroup_relation_item(trans, quota_root, src, dst);
1224         err = del_qgroup_relation_item(trans, quota_root, dst, src);
1225         if (err && !ret)
1226                 ret = err;
1227
1228         spin_lock(&fs_info->qgroup_lock);
1229         del_relation_rb(fs_info, src, dst);
1230         ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1231         spin_unlock(&fs_info->qgroup_lock);
1232 out:
1233         ulist_free(tmp);
1234         return ret;
1235 }
1236
1237 int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans,
1238                               struct btrfs_fs_info *fs_info, u64 src, u64 dst)
1239 {
1240         int ret = 0;
1241
1242         mutex_lock(&fs_info->qgroup_ioctl_lock);
1243         ret = __del_qgroup_relation(trans, fs_info, src, dst);
1244         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1245
1246         return ret;
1247 }
1248
1249 int btrfs_create_qgroup(struct btrfs_trans_handle *trans,
1250                         struct btrfs_fs_info *fs_info, u64 qgroupid)
1251 {
1252         struct btrfs_root *quota_root;
1253         struct btrfs_qgroup *qgroup;
1254         int ret = 0;
1255
1256         mutex_lock(&fs_info->qgroup_ioctl_lock);
1257         quota_root = fs_info->quota_root;
1258         if (!quota_root) {
1259                 ret = -EINVAL;
1260                 goto out;
1261         }
1262         qgroup = find_qgroup_rb(fs_info, qgroupid);
1263         if (qgroup) {
1264                 ret = -EEXIST;
1265                 goto out;
1266         }
1267
1268         ret = add_qgroup_item(trans, quota_root, qgroupid);
1269         if (ret)
1270                 goto out;
1271
1272         spin_lock(&fs_info->qgroup_lock);
1273         qgroup = add_qgroup_rb(fs_info, qgroupid);
1274         spin_unlock(&fs_info->qgroup_lock);
1275
1276         if (IS_ERR(qgroup))
1277                 ret = PTR_ERR(qgroup);
1278 out:
1279         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1280         return ret;
1281 }
1282
1283 int btrfs_remove_qgroup(struct btrfs_trans_handle *trans,
1284                         struct btrfs_fs_info *fs_info, u64 qgroupid)
1285 {
1286         struct btrfs_root *quota_root;
1287         struct btrfs_qgroup *qgroup;
1288         struct btrfs_qgroup_list *list;
1289         int ret = 0;
1290
1291         mutex_lock(&fs_info->qgroup_ioctl_lock);
1292         quota_root = fs_info->quota_root;
1293         if (!quota_root) {
1294                 ret = -EINVAL;
1295                 goto out;
1296         }
1297
1298         qgroup = find_qgroup_rb(fs_info, qgroupid);
1299         if (!qgroup) {
1300                 ret = -ENOENT;
1301                 goto out;
1302         } else {
1303                 /* check if there are no children of this qgroup */
1304                 if (!list_empty(&qgroup->members)) {
1305                         ret = -EBUSY;
1306                         goto out;
1307                 }
1308         }
1309         ret = del_qgroup_item(trans, quota_root, qgroupid);
1310         if (ret && ret != -ENOENT)
1311                 goto out;
1312
1313         while (!list_empty(&qgroup->groups)) {
1314                 list = list_first_entry(&qgroup->groups,
1315                                         struct btrfs_qgroup_list, next_group);
1316                 ret = __del_qgroup_relation(trans, fs_info,
1317                                            qgroupid,
1318                                            list->group->qgroupid);
1319                 if (ret)
1320                         goto out;
1321         }
1322
1323         spin_lock(&fs_info->qgroup_lock);
1324         del_qgroup_rb(fs_info, qgroupid);
1325         spin_unlock(&fs_info->qgroup_lock);
1326 out:
1327         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1328         return ret;
1329 }
1330
1331 int btrfs_limit_qgroup(struct btrfs_trans_handle *trans,
1332                        struct btrfs_fs_info *fs_info, u64 qgroupid,
1333                        struct btrfs_qgroup_limit *limit)
1334 {
1335         struct btrfs_root *quota_root;
1336         struct btrfs_qgroup *qgroup;
1337         int ret = 0;
1338         /* Sometimes we would want to clear the limit on this qgroup.
1339          * To meet this requirement, we treat the -1 as a special value
1340          * which tell kernel to clear the limit on this qgroup.
1341          */
1342         const u64 CLEAR_VALUE = -1;
1343
1344         mutex_lock(&fs_info->qgroup_ioctl_lock);
1345         quota_root = fs_info->quota_root;
1346         if (!quota_root) {
1347                 ret = -EINVAL;
1348                 goto out;
1349         }
1350
1351         qgroup = find_qgroup_rb(fs_info, qgroupid);
1352         if (!qgroup) {
1353                 ret = -ENOENT;
1354                 goto out;
1355         }
1356
1357         spin_lock(&fs_info->qgroup_lock);
1358         if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
1359                 if (limit->max_rfer == CLEAR_VALUE) {
1360                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1361                         limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1362                         qgroup->max_rfer = 0;
1363                 } else {
1364                         qgroup->max_rfer = limit->max_rfer;
1365                 }
1366         }
1367         if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
1368                 if (limit->max_excl == CLEAR_VALUE) {
1369                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1370                         limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1371                         qgroup->max_excl = 0;
1372                 } else {
1373                         qgroup->max_excl = limit->max_excl;
1374                 }
1375         }
1376         if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
1377                 if (limit->rsv_rfer == CLEAR_VALUE) {
1378                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1379                         limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1380                         qgroup->rsv_rfer = 0;
1381                 } else {
1382                         qgroup->rsv_rfer = limit->rsv_rfer;
1383                 }
1384         }
1385         if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
1386                 if (limit->rsv_excl == CLEAR_VALUE) {
1387                         qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1388                         limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1389                         qgroup->rsv_excl = 0;
1390                 } else {
1391                         qgroup->rsv_excl = limit->rsv_excl;
1392                 }
1393         }
1394         qgroup->lim_flags |= limit->flags;
1395
1396         spin_unlock(&fs_info->qgroup_lock);
1397
1398         ret = update_qgroup_limit_item(trans, quota_root, qgroup);
1399         if (ret) {
1400                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1401                 btrfs_info(fs_info, "unable to update quota limit for %llu",
1402                        qgroupid);
1403         }
1404
1405 out:
1406         mutex_unlock(&fs_info->qgroup_ioctl_lock);
1407         return ret;
1408 }
1409
1410 int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1411                                 struct btrfs_delayed_ref_root *delayed_refs,
1412                                 struct btrfs_qgroup_extent_record *record)
1413 {
1414         struct rb_node **p = &delayed_refs->dirty_extent_root.rb_node;
1415         struct rb_node *parent_node = NULL;
1416         struct btrfs_qgroup_extent_record *entry;
1417         u64 bytenr = record->bytenr;
1418
1419         assert_spin_locked(&delayed_refs->lock);
1420         trace_btrfs_qgroup_trace_extent(fs_info, record);
1421
1422         while (*p) {
1423                 parent_node = *p;
1424                 entry = rb_entry(parent_node, struct btrfs_qgroup_extent_record,
1425                                  node);
1426                 if (bytenr < entry->bytenr)
1427                         p = &(*p)->rb_left;
1428                 else if (bytenr > entry->bytenr)
1429                         p = &(*p)->rb_right;
1430                 else
1431                         return 1;
1432         }
1433
1434         rb_link_node(&record->node, parent_node, p);
1435         rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1436         return 0;
1437 }
1438
1439 int btrfs_qgroup_trace_extent_post(struct btrfs_fs_info *fs_info,
1440                                    struct btrfs_qgroup_extent_record *qrecord)
1441 {
1442         struct ulist *old_root;
1443         u64 bytenr = qrecord->bytenr;
1444         int ret;
1445
1446         ret = btrfs_find_all_roots(NULL, fs_info, bytenr, 0, &old_root);
1447         if (ret < 0)
1448                 return ret;
1449
1450         /*
1451          * Here we don't need to get the lock of
1452          * trans->transaction->delayed_refs, since inserted qrecord won't
1453          * be deleted, only qrecord->node may be modified (new qrecord insert)
1454          *
1455          * So modifying qrecord->old_roots is safe here
1456          */
1457         qrecord->old_roots = old_root;
1458         return 0;
1459 }
1460
1461 int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans,
1462                 struct btrfs_fs_info *fs_info, u64 bytenr, u64 num_bytes,
1463                 gfp_t gfp_flag)
1464 {
1465         struct btrfs_qgroup_extent_record *record;
1466         struct btrfs_delayed_ref_root *delayed_refs;
1467         int ret;
1468
1469         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
1470             || bytenr == 0 || num_bytes == 0)
1471                 return 0;
1472         if (WARN_ON(trans == NULL))
1473                 return -EINVAL;
1474         record = kmalloc(sizeof(*record), gfp_flag);
1475         if (!record)
1476                 return -ENOMEM;
1477
1478         delayed_refs = &trans->transaction->delayed_refs;
1479         record->bytenr = bytenr;
1480         record->num_bytes = num_bytes;
1481         record->old_roots = NULL;
1482
1483         spin_lock(&delayed_refs->lock);
1484         ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1485         spin_unlock(&delayed_refs->lock);
1486         if (ret > 0) {
1487                 kfree(record);
1488                 return 0;
1489         }
1490         return btrfs_qgroup_trace_extent_post(fs_info, record);
1491 }
1492
1493 int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
1494                                   struct btrfs_fs_info *fs_info,
1495                                   struct extent_buffer *eb)
1496 {
1497         int nr = btrfs_header_nritems(eb);
1498         int i, extent_type, ret;
1499         struct btrfs_key key;
1500         struct btrfs_file_extent_item *fi;
1501         u64 bytenr, num_bytes;
1502
1503         /* We can be called directly from walk_up_proc() */
1504         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1505                 return 0;
1506
1507         for (i = 0; i < nr; i++) {
1508                 btrfs_item_key_to_cpu(eb, &key, i);
1509
1510                 if (key.type != BTRFS_EXTENT_DATA_KEY)
1511                         continue;
1512
1513                 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
1514                 /* filter out non qgroup-accountable extents  */
1515                 extent_type = btrfs_file_extent_type(eb, fi);
1516
1517                 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1518                         continue;
1519
1520                 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1521                 if (!bytenr)
1522                         continue;
1523
1524                 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1525
1526                 ret = btrfs_qgroup_trace_extent(trans, fs_info, bytenr,
1527                                                 num_bytes, GFP_NOFS);
1528                 if (ret)
1529                         return ret;
1530         }
1531         cond_resched();
1532         return 0;
1533 }
1534
1535 /*
1536  * Walk up the tree from the bottom, freeing leaves and any interior
1537  * nodes which have had all slots visited. If a node (leaf or
1538  * interior) is freed, the node above it will have it's slot
1539  * incremented. The root node will never be freed.
1540  *
1541  * At the end of this function, we should have a path which has all
1542  * slots incremented to the next position for a search. If we need to
1543  * read a new node it will be NULL and the node above it will have the
1544  * correct slot selected for a later read.
1545  *
1546  * If we increment the root nodes slot counter past the number of
1547  * elements, 1 is returned to signal completion of the search.
1548  */
1549 static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1550 {
1551         int level = 0;
1552         int nr, slot;
1553         struct extent_buffer *eb;
1554
1555         if (root_level == 0)
1556                 return 1;
1557
1558         while (level <= root_level) {
1559                 eb = path->nodes[level];
1560                 nr = btrfs_header_nritems(eb);
1561                 path->slots[level]++;
1562                 slot = path->slots[level];
1563                 if (slot >= nr || level == 0) {
1564                         /*
1565                          * Don't free the root -  we will detect this
1566                          * condition after our loop and return a
1567                          * positive value for caller to stop walking the tree.
1568                          */
1569                         if (level != root_level) {
1570                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
1571                                 path->locks[level] = 0;
1572
1573                                 free_extent_buffer(eb);
1574                                 path->nodes[level] = NULL;
1575                                 path->slots[level] = 0;
1576                         }
1577                 } else {
1578                         /*
1579                          * We have a valid slot to walk back down
1580                          * from. Stop here so caller can process these
1581                          * new nodes.
1582                          */
1583                         break;
1584                 }
1585
1586                 level++;
1587         }
1588
1589         eb = path->nodes[root_level];
1590         if (path->slots[root_level] >= btrfs_header_nritems(eb))
1591                 return 1;
1592
1593         return 0;
1594 }
1595
1596 int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
1597                                struct btrfs_root *root,
1598                                struct extent_buffer *root_eb,
1599                                u64 root_gen, int root_level)
1600 {
1601         struct btrfs_fs_info *fs_info = root->fs_info;
1602         int ret = 0;
1603         int level;
1604         struct extent_buffer *eb = root_eb;
1605         struct btrfs_path *path = NULL;
1606
1607         BUG_ON(root_level < 0 || root_level >= BTRFS_MAX_LEVEL);
1608         BUG_ON(root_eb == NULL);
1609
1610         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1611                 return 0;
1612
1613         if (!extent_buffer_uptodate(root_eb)) {
1614                 ret = btrfs_read_buffer(root_eb, root_gen);
1615                 if (ret)
1616                         goto out;
1617         }
1618
1619         if (root_level == 0) {
1620                 ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, root_eb);
1621                 goto out;
1622         }
1623
1624         path = btrfs_alloc_path();
1625         if (!path)
1626                 return -ENOMEM;
1627
1628         /*
1629          * Walk down the tree.  Missing extent blocks are filled in as
1630          * we go. Metadata is accounted every time we read a new
1631          * extent block.
1632          *
1633          * When we reach a leaf, we account for file extent items in it,
1634          * walk back up the tree (adjusting slot pointers as we go)
1635          * and restart the search process.
1636          */
1637         extent_buffer_get(root_eb); /* For path */
1638         path->nodes[root_level] = root_eb;
1639         path->slots[root_level] = 0;
1640         path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
1641 walk_down:
1642         level = root_level;
1643         while (level >= 0) {
1644                 if (path->nodes[level] == NULL) {
1645                         int parent_slot;
1646                         u64 child_gen;
1647                         u64 child_bytenr;
1648
1649                         /*
1650                          * We need to get child blockptr/gen from parent before
1651                          * we can read it.
1652                           */
1653                         eb = path->nodes[level + 1];
1654                         parent_slot = path->slots[level + 1];
1655                         child_bytenr = btrfs_node_blockptr(eb, parent_slot);
1656                         child_gen = btrfs_node_ptr_generation(eb, parent_slot);
1657
1658                         eb = read_tree_block(fs_info, child_bytenr, child_gen);
1659                         if (IS_ERR(eb)) {
1660                                 ret = PTR_ERR(eb);
1661                                 goto out;
1662                         } else if (!extent_buffer_uptodate(eb)) {
1663                                 free_extent_buffer(eb);
1664                                 ret = -EIO;
1665                                 goto out;
1666                         }
1667
1668                         path->nodes[level] = eb;
1669                         path->slots[level] = 0;
1670
1671                         btrfs_tree_read_lock(eb);
1672                         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1673                         path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
1674
1675                         ret = btrfs_qgroup_trace_extent(trans, fs_info,
1676                                                         child_bytenr,
1677                                                         fs_info->nodesize,
1678                                                         GFP_NOFS);
1679                         if (ret)
1680                                 goto out;
1681                 }
1682
1683                 if (level == 0) {
1684                         ret = btrfs_qgroup_trace_leaf_items(trans,fs_info,
1685                                                            path->nodes[level]);
1686                         if (ret)
1687                                 goto out;
1688
1689                         /* Nonzero return here means we completed our search */
1690                         ret = adjust_slots_upwards(path, root_level);
1691                         if (ret)
1692                                 break;
1693
1694                         /* Restart search with new slots */
1695                         goto walk_down;
1696                 }
1697
1698                 level--;
1699         }
1700
1701         ret = 0;
1702 out:
1703         btrfs_free_path(path);
1704
1705         return ret;
1706 }
1707
1708 #define UPDATE_NEW      0
1709 #define UPDATE_OLD      1
1710 /*
1711  * Walk all of the roots that points to the bytenr and adjust their refcnts.
1712  */
1713 static int qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
1714                                 struct ulist *roots, struct ulist *tmp,
1715                                 struct ulist *qgroups, u64 seq, int update_old)
1716 {
1717         struct ulist_node *unode;
1718         struct ulist_iterator uiter;
1719         struct ulist_node *tmp_unode;
1720         struct ulist_iterator tmp_uiter;
1721         struct btrfs_qgroup *qg;
1722         int ret = 0;
1723
1724         if (!roots)
1725                 return 0;
1726         ULIST_ITER_INIT(&uiter);
1727         while ((unode = ulist_next(roots, &uiter))) {
1728                 qg = find_qgroup_rb(fs_info, unode->val);
1729                 if (!qg)
1730                         continue;
1731
1732                 ulist_reinit(tmp);
1733                 ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
1734                                 GFP_ATOMIC);
1735                 if (ret < 0)
1736                         return ret;
1737                 ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
1738                 if (ret < 0)
1739                         return ret;
1740                 ULIST_ITER_INIT(&tmp_uiter);
1741                 while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
1742                         struct btrfs_qgroup_list *glist;
1743
1744                         qg = unode_aux_to_qgroup(tmp_unode);
1745                         if (update_old)
1746                                 btrfs_qgroup_update_old_refcnt(qg, seq, 1);
1747                         else
1748                                 btrfs_qgroup_update_new_refcnt(qg, seq, 1);
1749                         list_for_each_entry(glist, &qg->groups, next_group) {
1750                                 ret = ulist_add(qgroups, glist->group->qgroupid,
1751                                                 qgroup_to_aux(glist->group),
1752                                                 GFP_ATOMIC);
1753                                 if (ret < 0)
1754                                         return ret;
1755                                 ret = ulist_add(tmp, glist->group->qgroupid,
1756                                                 qgroup_to_aux(glist->group),
1757                                                 GFP_ATOMIC);
1758                                 if (ret < 0)
1759                                         return ret;
1760                         }
1761                 }
1762         }
1763         return 0;
1764 }
1765
1766 /*
1767  * Update qgroup rfer/excl counters.
1768  * Rfer update is easy, codes can explain themselves.
1769  *
1770  * Excl update is tricky, the update is split into 2 part.
1771  * Part 1: Possible exclusive <-> sharing detect:
1772  *      |       A       |       !A      |
1773  *  -------------------------------------
1774  *  B   |       *       |       -       |
1775  *  -------------------------------------
1776  *  !B  |       +       |       **      |
1777  *  -------------------------------------
1778  *
1779  * Conditions:
1780  * A:   cur_old_roots < nr_old_roots    (not exclusive before)
1781  * !A:  cur_old_roots == nr_old_roots   (possible exclusive before)
1782  * B:   cur_new_roots < nr_new_roots    (not exclusive now)
1783  * !B:  cur_new_roots == nr_new_roots   (possible exclusive now)
1784  *
1785  * Results:
1786  * +: Possible sharing -> exclusive     -: Possible exclusive -> sharing
1787  * *: Definitely not changed.           **: Possible unchanged.
1788  *
1789  * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
1790  *
1791  * To make the logic clear, we first use condition A and B to split
1792  * combination into 4 results.
1793  *
1794  * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
1795  * only on variant maybe 0.
1796  *
1797  * Lastly, check result **, since there are 2 variants maybe 0, split them
1798  * again(2x2).
1799  * But this time we don't need to consider other things, the codes and logic
1800  * is easy to understand now.
1801  */
1802 static int qgroup_update_counters(struct btrfs_fs_info *fs_info,
1803                                   struct ulist *qgroups,
1804                                   u64 nr_old_roots,
1805                                   u64 nr_new_roots,
1806                                   u64 num_bytes, u64 seq)
1807 {
1808         struct ulist_node *unode;
1809         struct ulist_iterator uiter;
1810         struct btrfs_qgroup *qg;
1811         u64 cur_new_count, cur_old_count;
1812
1813         ULIST_ITER_INIT(&uiter);
1814         while ((unode = ulist_next(qgroups, &uiter))) {
1815                 bool dirty = false;
1816
1817                 qg = unode_aux_to_qgroup(unode);
1818                 cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
1819                 cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);
1820
1821                 trace_qgroup_update_counters(fs_info, qg->qgroupid,
1822                                              cur_old_count, cur_new_count);
1823
1824                 /* Rfer update part */
1825                 if (cur_old_count == 0 && cur_new_count > 0) {
1826                         qg->rfer += num_bytes;
1827                         qg->rfer_cmpr += num_bytes;
1828                         dirty = true;
1829                 }
1830                 if (cur_old_count > 0 && cur_new_count == 0) {
1831                         qg->rfer -= num_bytes;
1832                         qg->rfer_cmpr -= num_bytes;
1833                         dirty = true;
1834                 }
1835
1836                 /* Excl update part */
1837                 /* Exclusive/none -> shared case */
1838                 if (cur_old_count == nr_old_roots &&
1839                     cur_new_count < nr_new_roots) {
1840                         /* Exclusive -> shared */
1841                         if (cur_old_count != 0) {
1842                                 qg->excl -= num_bytes;
1843                                 qg->excl_cmpr -= num_bytes;
1844                                 dirty = true;
1845                         }
1846                 }
1847
1848                 /* Shared -> exclusive/none case */
1849                 if (cur_old_count < nr_old_roots &&
1850                     cur_new_count == nr_new_roots) {
1851                         /* Shared->exclusive */
1852                         if (cur_new_count != 0) {
1853                                 qg->excl += num_bytes;
1854                                 qg->excl_cmpr += num_bytes;
1855                                 dirty = true;
1856                         }
1857                 }
1858
1859                 /* Exclusive/none -> exclusive/none case */
1860                 if (cur_old_count == nr_old_roots &&
1861                     cur_new_count == nr_new_roots) {
1862                         if (cur_old_count == 0) {
1863                                 /* None -> exclusive/none */
1864
1865                                 if (cur_new_count != 0) {
1866                                         /* None -> exclusive */
1867                                         qg->excl += num_bytes;
1868                                         qg->excl_cmpr += num_bytes;
1869                                         dirty = true;
1870                                 }
1871                                 /* None -> none, nothing changed */
1872                         } else {
1873                                 /* Exclusive -> exclusive/none */
1874
1875                                 if (cur_new_count == 0) {
1876                                         /* Exclusive -> none */
1877                                         qg->excl -= num_bytes;
1878                                         qg->excl_cmpr -= num_bytes;
1879                                         dirty = true;
1880                                 }
1881                                 /* Exclusive -> exclusive, nothing changed */
1882                         }
1883                 }
1884
1885                 if (dirty)
1886                         qgroup_dirty(fs_info, qg);
1887         }
1888         return 0;
1889 }
1890
1891 /*
1892  * Check if the @roots potentially is a list of fs tree roots
1893  *
1894  * Return 0 for definitely not a fs/subvol tree roots ulist
1895  * Return 1 for possible fs/subvol tree roots in the list (considering an empty
1896  *          one as well)
1897  */
1898 static int maybe_fs_roots(struct ulist *roots)
1899 {
1900         struct ulist_node *unode;
1901         struct ulist_iterator uiter;
1902
1903         /* Empty one, still possible for fs roots */
1904         if (!roots || roots->nnodes == 0)
1905                 return 1;
1906
1907         ULIST_ITER_INIT(&uiter);
1908         unode = ulist_next(roots, &uiter);
1909         if (!unode)
1910                 return 1;
1911
1912         /*
1913          * If it contains fs tree roots, then it must belong to fs/subvol
1914          * trees.
1915          * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
1916          */
1917         return is_fstree(unode->val);
1918 }
1919
1920 int
1921 btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans,
1922                             struct btrfs_fs_info *fs_info,
1923                             u64 bytenr, u64 num_bytes,
1924                             struct ulist *old_roots, struct ulist *new_roots)
1925 {
1926         struct ulist *qgroups = NULL;
1927         struct ulist *tmp = NULL;
1928         u64 seq;
1929         u64 nr_new_roots = 0;
1930         u64 nr_old_roots = 0;
1931         int ret = 0;
1932
1933         /*
1934          * If quotas get disabled meanwhile, the resouces need to be freed and
1935          * we can't just exit here.
1936          */
1937         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1938                 goto out_free;
1939
1940         if (new_roots) {
1941                 if (!maybe_fs_roots(new_roots))
1942                         goto out_free;
1943                 nr_new_roots = new_roots->nnodes;
1944         }
1945         if (old_roots) {
1946                 if (!maybe_fs_roots(old_roots))
1947                         goto out_free;
1948                 nr_old_roots = old_roots->nnodes;
1949         }
1950
1951         /* Quick exit, either not fs tree roots, or won't affect any qgroup */
1952         if (nr_old_roots == 0 && nr_new_roots == 0)
1953                 goto out_free;
1954
1955         BUG_ON(!fs_info->quota_root);
1956
1957         trace_btrfs_qgroup_account_extent(fs_info, bytenr, num_bytes,
1958                                           nr_old_roots, nr_new_roots);
1959
1960         qgroups = ulist_alloc(GFP_NOFS);
1961         if (!qgroups) {
1962                 ret = -ENOMEM;
1963                 goto out_free;
1964         }
1965         tmp = ulist_alloc(GFP_NOFS);
1966         if (!tmp) {
1967                 ret = -ENOMEM;
1968                 goto out_free;
1969         }
1970
1971         mutex_lock(&fs_info->qgroup_rescan_lock);
1972         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
1973                 if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
1974                         mutex_unlock(&fs_info->qgroup_rescan_lock);
1975                         ret = 0;
1976                         goto out_free;
1977                 }
1978         }
1979         mutex_unlock(&fs_info->qgroup_rescan_lock);
1980
1981         spin_lock(&fs_info->qgroup_lock);
1982         seq = fs_info->qgroup_seq;
1983
1984         /* Update old refcnts using old_roots */
1985         ret = qgroup_update_refcnt(fs_info, old_roots, tmp, qgroups, seq,
1986                                    UPDATE_OLD);
1987         if (ret < 0)
1988                 goto out;
1989
1990         /* Update new refcnts using new_roots */
1991         ret = qgroup_update_refcnt(fs_info, new_roots, tmp, qgroups, seq,
1992                                    UPDATE_NEW);
1993         if (ret < 0)
1994                 goto out;
1995
1996         qgroup_update_counters(fs_info, qgroups, nr_old_roots, nr_new_roots,
1997                                num_bytes, seq);
1998
1999         /*
2000          * Bump qgroup_seq to avoid seq overlap
2001          */
2002         fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
2003 out:
2004         spin_unlock(&fs_info->qgroup_lock);
2005 out_free:
2006         ulist_free(tmp);
2007         ulist_free(qgroups);
2008         ulist_free(old_roots);
2009         ulist_free(new_roots);
2010         return ret;
2011 }
2012
2013 int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans,
2014                                  struct btrfs_fs_info *fs_info)
2015 {
2016         struct btrfs_qgroup_extent_record *record;
2017         struct btrfs_delayed_ref_root *delayed_refs;
2018         struct ulist *new_roots = NULL;
2019         struct rb_node *node;
2020         u64 qgroup_to_skip;
2021         int ret = 0;
2022
2023         delayed_refs = &trans->transaction->delayed_refs;
2024         qgroup_to_skip = delayed_refs->qgroup_to_skip;
2025         while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
2026                 record = rb_entry(node, struct btrfs_qgroup_extent_record,
2027                                   node);
2028
2029                 trace_btrfs_qgroup_account_extents(fs_info, record);
2030
2031                 if (!ret) {
2032                         /*
2033                          * Old roots should be searched when inserting qgroup
2034                          * extent record
2035                          */
2036                         if (WARN_ON(!record->old_roots)) {
2037                                 /* Search commit root to find old_roots */
2038                                 ret = btrfs_find_all_roots(NULL, fs_info,
2039                                                 record->bytenr, 0,
2040                                                 &record->old_roots);
2041                                 if (ret < 0)
2042                                         goto cleanup;
2043                         }
2044
2045                         /*
2046                          * Use SEQ_LAST as time_seq to do special search, which
2047                          * doesn't lock tree or delayed_refs and search current
2048                          * root. It's safe inside commit_transaction().
2049                          */
2050                         ret = btrfs_find_all_roots(trans, fs_info,
2051                                         record->bytenr, SEQ_LAST, &new_roots);
2052                         if (ret < 0)
2053                                 goto cleanup;
2054                         if (qgroup_to_skip) {
2055                                 ulist_del(new_roots, qgroup_to_skip, 0);
2056                                 ulist_del(record->old_roots, qgroup_to_skip,
2057                                           0);
2058                         }
2059                         ret = btrfs_qgroup_account_extent(trans, fs_info,
2060                                         record->bytenr, record->num_bytes,
2061                                         record->old_roots, new_roots);
2062                         record->old_roots = NULL;
2063                         new_roots = NULL;
2064                 }
2065 cleanup:
2066                 ulist_free(record->old_roots);
2067                 ulist_free(new_roots);
2068                 new_roots = NULL;
2069                 rb_erase(node, &delayed_refs->dirty_extent_root);
2070                 kfree(record);
2071
2072         }
2073         return ret;
2074 }
2075
2076 /*
2077  * called from commit_transaction. Writes all changed qgroups to disk.
2078  */
2079 int btrfs_run_qgroups(struct btrfs_trans_handle *trans,
2080                       struct btrfs_fs_info *fs_info)
2081 {
2082         struct btrfs_root *quota_root = fs_info->quota_root;
2083         int ret = 0;
2084         int start_rescan_worker = 0;
2085
2086         if (!quota_root)
2087                 goto out;
2088
2089         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) &&
2090             test_bit(BTRFS_FS_QUOTA_ENABLING, &fs_info->flags))
2091                 start_rescan_worker = 1;
2092
2093         if (test_and_clear_bit(BTRFS_FS_QUOTA_ENABLING, &fs_info->flags))
2094                 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2095
2096         spin_lock(&fs_info->qgroup_lock);
2097         while (!list_empty(&fs_info->dirty_qgroups)) {
2098                 struct btrfs_qgroup *qgroup;
2099                 qgroup = list_first_entry(&fs_info->dirty_qgroups,
2100                                           struct btrfs_qgroup, dirty);
2101                 list_del_init(&qgroup->dirty);
2102                 spin_unlock(&fs_info->qgroup_lock);
2103                 ret = update_qgroup_info_item(trans, quota_root, qgroup);
2104                 if (ret)
2105                         fs_info->qgroup_flags |=
2106                                         BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2107                 ret = update_qgroup_limit_item(trans, quota_root, qgroup);
2108                 if (ret)
2109                         fs_info->qgroup_flags |=
2110                                         BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2111                 spin_lock(&fs_info->qgroup_lock);
2112         }
2113         if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2114                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_ON;
2115         else
2116                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
2117         spin_unlock(&fs_info->qgroup_lock);
2118
2119         ret = update_qgroup_status_item(trans);
2120         if (ret)
2121                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2122
2123         if (!ret && start_rescan_worker) {
2124                 ret = qgroup_rescan_init(fs_info, 0, 1);
2125                 if (!ret) {
2126                         qgroup_rescan_zero_tracking(fs_info);
2127                         btrfs_queue_work(fs_info->qgroup_rescan_workers,
2128                                          &fs_info->qgroup_rescan_work);
2129                 }
2130                 ret = 0;
2131         }
2132
2133 out:
2134
2135         return ret;
2136 }
2137
2138 /*
2139  * Copy the accounting information between qgroups. This is necessary
2140  * when a snapshot or a subvolume is created. Throwing an error will
2141  * cause a transaction abort so we take extra care here to only error
2142  * when a readonly fs is a reasonable outcome.
2143  */
2144 int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans,
2145                          struct btrfs_fs_info *fs_info, u64 srcid, u64 objectid,
2146                          struct btrfs_qgroup_inherit *inherit)
2147 {
2148         int ret = 0;
2149         int i;
2150         u64 *i_qgroups;
2151         struct btrfs_root *quota_root = fs_info->quota_root;
2152         struct btrfs_qgroup *srcgroup;
2153         struct btrfs_qgroup *dstgroup;
2154         u32 level_size = 0;
2155         u64 nums;
2156
2157         mutex_lock(&fs_info->qgroup_ioctl_lock);
2158         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2159                 goto out;
2160
2161         if (!quota_root) {
2162                 ret = -EINVAL;
2163                 goto out;
2164         }
2165
2166         if (inherit) {
2167                 i_qgroups = (u64 *)(inherit + 1);
2168                 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
2169                        2 * inherit->num_excl_copies;
2170                 for (i = 0; i < nums; ++i) {
2171                         srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
2172
2173                         /*
2174                          * Zero out invalid groups so we can ignore
2175                          * them later.
2176                          */
2177                         if (!srcgroup ||
2178                             ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
2179                                 *i_qgroups = 0ULL;
2180
2181                         ++i_qgroups;
2182                 }
2183         }
2184
2185         /*
2186          * create a tracking group for the subvol itself
2187          */
2188         ret = add_qgroup_item(trans, quota_root, objectid);
2189         if (ret)
2190                 goto out;
2191
2192         if (srcid) {
2193                 struct btrfs_root *srcroot;
2194                 struct btrfs_key srckey;
2195
2196                 srckey.objectid = srcid;
2197                 srckey.type = BTRFS_ROOT_ITEM_KEY;
2198                 srckey.offset = (u64)-1;
2199                 srcroot = btrfs_read_fs_root_no_name(fs_info, &srckey);
2200                 if (IS_ERR(srcroot)) {
2201                         ret = PTR_ERR(srcroot);
2202                         goto out;
2203                 }
2204
2205                 level_size = fs_info->nodesize;
2206         }
2207
2208         /*
2209          * add qgroup to all inherited groups
2210          */
2211         if (inherit) {
2212                 i_qgroups = (u64 *)(inherit + 1);
2213                 for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
2214                         if (*i_qgroups == 0)
2215                                 continue;
2216                         ret = add_qgroup_relation_item(trans, quota_root,
2217                                                        objectid, *i_qgroups);
2218                         if (ret && ret != -EEXIST)
2219                                 goto out;
2220                         ret = add_qgroup_relation_item(trans, quota_root,
2221                                                        *i_qgroups, objectid);
2222                         if (ret && ret != -EEXIST)
2223                                 goto out;
2224                 }
2225                 ret = 0;
2226         }
2227
2228
2229         spin_lock(&fs_info->qgroup_lock);
2230
2231         dstgroup = add_qgroup_rb(fs_info, objectid);
2232         if (IS_ERR(dstgroup)) {
2233                 ret = PTR_ERR(dstgroup);
2234                 goto unlock;
2235         }
2236
2237         if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
2238                 dstgroup->lim_flags = inherit->lim.flags;
2239                 dstgroup->max_rfer = inherit->lim.max_rfer;
2240                 dstgroup->max_excl = inherit->lim.max_excl;
2241                 dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
2242                 dstgroup->rsv_excl = inherit->lim.rsv_excl;
2243
2244                 qgroup_dirty(fs_info, dstgroup);
2245         }
2246
2247         if (srcid) {
2248                 srcgroup = find_qgroup_rb(fs_info, srcid);
2249                 if (!srcgroup)
2250                         goto unlock;
2251
2252                 /*
2253                  * We call inherit after we clone the root in order to make sure
2254                  * our counts don't go crazy, so at this point the only
2255                  * difference between the two roots should be the root node.
2256                  */
2257                 dstgroup->rfer = srcgroup->rfer;
2258                 dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
2259                 dstgroup->excl = level_size;
2260                 dstgroup->excl_cmpr = level_size;
2261                 srcgroup->excl = level_size;
2262                 srcgroup->excl_cmpr = level_size;
2263
2264                 /* inherit the limit info */
2265                 dstgroup->lim_flags = srcgroup->lim_flags;
2266                 dstgroup->max_rfer = srcgroup->max_rfer;
2267                 dstgroup->max_excl = srcgroup->max_excl;
2268                 dstgroup->rsv_rfer = srcgroup->rsv_rfer;
2269                 dstgroup->rsv_excl = srcgroup->rsv_excl;
2270
2271                 qgroup_dirty(fs_info, dstgroup);
2272                 qgroup_dirty(fs_info, srcgroup);
2273         }
2274
2275         if (!inherit)
2276                 goto unlock;
2277
2278         i_qgroups = (u64 *)(inherit + 1);
2279         for (i = 0; i < inherit->num_qgroups; ++i) {
2280                 if (*i_qgroups) {
2281                         ret = add_relation_rb(fs_info, objectid, *i_qgroups);
2282                         if (ret)
2283                                 goto unlock;
2284                 }
2285                 ++i_qgroups;
2286         }
2287
2288         for (i = 0; i <  inherit->num_ref_copies; ++i, i_qgroups += 2) {
2289                 struct btrfs_qgroup *src;
2290                 struct btrfs_qgroup *dst;
2291
2292                 if (!i_qgroups[0] || !i_qgroups[1])
2293                         continue;
2294
2295                 src = find_qgroup_rb(fs_info, i_qgroups[0]);
2296                 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
2297
2298                 if (!src || !dst) {
2299                         ret = -EINVAL;
2300                         goto unlock;
2301                 }
2302
2303                 dst->rfer = src->rfer - level_size;
2304                 dst->rfer_cmpr = src->rfer_cmpr - level_size;
2305         }
2306         for (i = 0; i <  inherit->num_excl_copies; ++i, i_qgroups += 2) {
2307                 struct btrfs_qgroup *src;
2308                 struct btrfs_qgroup *dst;
2309
2310                 if (!i_qgroups[0] || !i_qgroups[1])
2311                         continue;
2312
2313                 src = find_qgroup_rb(fs_info, i_qgroups[0]);
2314                 dst = find_qgroup_rb(fs_info, i_qgroups[1]);
2315
2316                 if (!src || !dst) {
2317                         ret = -EINVAL;
2318                         goto unlock;
2319                 }
2320
2321                 dst->excl = src->excl + level_size;
2322                 dst->excl_cmpr = src->excl_cmpr + level_size;
2323         }
2324
2325 unlock:
2326         spin_unlock(&fs_info->qgroup_lock);
2327 out:
2328         mutex_unlock(&fs_info->qgroup_ioctl_lock);
2329         return ret;
2330 }
2331
2332 static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
2333 {
2334         if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
2335             qg->reserved + (s64)qg->rfer + num_bytes > qg->max_rfer)
2336                 return false;
2337
2338         if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
2339             qg->reserved + (s64)qg->excl + num_bytes > qg->max_excl)
2340                 return false;
2341
2342         return true;
2343 }
2344
2345 static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce)
2346 {
2347         struct btrfs_root *quota_root;
2348         struct btrfs_qgroup *qgroup;
2349         struct btrfs_fs_info *fs_info = root->fs_info;
2350         u64 ref_root = root->root_key.objectid;
2351         int ret = 0;
2352         int retried = 0;
2353         struct ulist_node *unode;
2354         struct ulist_iterator uiter;
2355
2356         if (!is_fstree(ref_root))
2357                 return 0;
2358
2359         if (num_bytes == 0)
2360                 return 0;
2361
2362         if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
2363             capable(CAP_SYS_RESOURCE))
2364                 enforce = false;
2365
2366 retry:
2367         spin_lock(&fs_info->qgroup_lock);
2368         quota_root = fs_info->quota_root;
2369         if (!quota_root)
2370                 goto out;
2371
2372         qgroup = find_qgroup_rb(fs_info, ref_root);
2373         if (!qgroup)
2374                 goto out;
2375
2376         /*
2377          * in a first step, we check all affected qgroups if any limits would
2378          * be exceeded
2379          */
2380         ulist_reinit(fs_info->qgroup_ulist);
2381         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
2382                         (uintptr_t)qgroup, GFP_ATOMIC);
2383         if (ret < 0)
2384                 goto out;
2385         ULIST_ITER_INIT(&uiter);
2386         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2387                 struct btrfs_qgroup *qg;
2388                 struct btrfs_qgroup_list *glist;
2389
2390                 qg = unode_aux_to_qgroup(unode);
2391
2392                 if (enforce && !qgroup_check_limits(qg, num_bytes)) {
2393                         /*
2394                          * Commit the tree and retry, since we may have
2395                          * deletions which would free up space.
2396                          */
2397                         if (!retried && qg->reserved > 0) {
2398                                 struct btrfs_trans_handle *trans;
2399
2400                                 spin_unlock(&fs_info->qgroup_lock);
2401                                 ret = btrfs_start_delalloc_inodes(root, 0);
2402                                 if (ret)
2403                                         return ret;
2404                                 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
2405                                 trans = btrfs_join_transaction(root);
2406                                 if (IS_ERR(trans))
2407                                         return PTR_ERR(trans);
2408                                 ret = btrfs_commit_transaction(trans);
2409                                 if (ret)
2410                                         return ret;
2411                                 retried++;
2412                                 goto retry;
2413                         }
2414                         ret = -EDQUOT;
2415                         goto out;
2416                 }
2417
2418                 list_for_each_entry(glist, &qg->groups, next_group) {
2419                         ret = ulist_add(fs_info->qgroup_ulist,
2420                                         glist->group->qgroupid,
2421                                         (uintptr_t)glist->group, GFP_ATOMIC);
2422                         if (ret < 0)
2423                                 goto out;
2424                 }
2425         }
2426         ret = 0;
2427         /*
2428          * no limits exceeded, now record the reservation into all qgroups
2429          */
2430         ULIST_ITER_INIT(&uiter);
2431         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2432                 struct btrfs_qgroup *qg;
2433
2434                 qg = unode_aux_to_qgroup(unode);
2435
2436                 trace_qgroup_update_reserve(fs_info, qg, num_bytes);
2437                 qg->reserved += num_bytes;
2438         }
2439
2440 out:
2441         spin_unlock(&fs_info->qgroup_lock);
2442         return ret;
2443 }
2444
2445 void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
2446                                u64 ref_root, u64 num_bytes)
2447 {
2448         struct btrfs_root *quota_root;
2449         struct btrfs_qgroup *qgroup;
2450         struct ulist_node *unode;
2451         struct ulist_iterator uiter;
2452         int ret = 0;
2453
2454         if (!is_fstree(ref_root))
2455                 return;
2456
2457         if (num_bytes == 0)
2458                 return;
2459
2460         spin_lock(&fs_info->qgroup_lock);
2461
2462         quota_root = fs_info->quota_root;
2463         if (!quota_root)
2464                 goto out;
2465
2466         qgroup = find_qgroup_rb(fs_info, ref_root);
2467         if (!qgroup)
2468                 goto out;
2469
2470         ulist_reinit(fs_info->qgroup_ulist);
2471         ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
2472                         (uintptr_t)qgroup, GFP_ATOMIC);
2473         if (ret < 0)
2474                 goto out;
2475         ULIST_ITER_INIT(&uiter);
2476         while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2477                 struct btrfs_qgroup *qg;
2478                 struct btrfs_qgroup_list *glist;
2479
2480                 qg = unode_aux_to_qgroup(unode);
2481
2482                 trace_qgroup_update_reserve(fs_info, qg, -(s64)num_bytes);
2483                 if (qg->reserved < num_bytes)
2484                         report_reserved_underflow(fs_info, qg, num_bytes);
2485                 else
2486                         qg->reserved -= num_bytes;
2487
2488                 list_for_each_entry(glist, &qg->groups, next_group) {
2489                         ret = ulist_add(fs_info->qgroup_ulist,
2490                                         glist->group->qgroupid,
2491                                         (uintptr_t)glist->group, GFP_ATOMIC);
2492                         if (ret < 0)
2493                                 goto out;
2494                 }
2495         }
2496
2497 out:
2498         spin_unlock(&fs_info->qgroup_lock);
2499 }
2500
2501 /*
2502  * Check if the leaf is the last leaf. Which means all node pointers
2503  * are at their last position.
2504  */
2505 static bool is_last_leaf(struct btrfs_path *path)
2506 {
2507         int i;
2508
2509         for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
2510                 if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
2511                         return false;
2512         }
2513         return true;
2514 }
2515
2516 /*
2517  * returns < 0 on error, 0 when more leafs are to be scanned.
2518  * returns 1 when done.
2519  */
2520 static int
2521 qgroup_rescan_leaf(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
2522                    struct btrfs_trans_handle *trans)
2523 {
2524         struct btrfs_key found;
2525         struct extent_buffer *scratch_leaf = NULL;
2526         struct ulist *roots = NULL;
2527         struct seq_list tree_mod_seq_elem = SEQ_LIST_INIT(tree_mod_seq_elem);
2528         u64 num_bytes;
2529         bool done;
2530         int slot;
2531         int ret;
2532
2533         mutex_lock(&fs_info->qgroup_rescan_lock);
2534         ret = btrfs_search_slot_for_read(fs_info->extent_root,
2535                                          &fs_info->qgroup_rescan_progress,
2536                                          path, 1, 0);
2537
2538         btrfs_debug(fs_info,
2539                 "current progress key (%llu %u %llu), search_slot ret %d",
2540                 fs_info->qgroup_rescan_progress.objectid,
2541                 fs_info->qgroup_rescan_progress.type,
2542                 fs_info->qgroup_rescan_progress.offset, ret);
2543
2544         if (ret) {
2545                 /*
2546                  * The rescan is about to end, we will not be scanning any
2547                  * further blocks. We cannot unset the RESCAN flag here, because
2548                  * we want to commit the transaction if everything went well.
2549                  * To make the live accounting work in this phase, we set our
2550                  * scan progress pointer such that every real extent objectid
2551                  * will be smaller.
2552                  */
2553                 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
2554                 btrfs_release_path(path);
2555                 mutex_unlock(&fs_info->qgroup_rescan_lock);
2556                 return ret;
2557         }
2558         done = is_last_leaf(path);
2559
2560         btrfs_item_key_to_cpu(path->nodes[0], &found,
2561                               btrfs_header_nritems(path->nodes[0]) - 1);
2562         fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;
2563
2564         btrfs_get_tree_mod_seq(fs_info, &tree_mod_seq_elem);
2565         scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
2566         if (!scratch_leaf) {
2567                 ret = -ENOMEM;
2568                 mutex_unlock(&fs_info->qgroup_rescan_lock);
2569                 goto out;
2570         }
2571         extent_buffer_get(scratch_leaf);
2572         btrfs_tree_read_lock(scratch_leaf);
2573         btrfs_set_lock_blocking_rw(scratch_leaf, BTRFS_READ_LOCK);
2574         slot = path->slots[0];
2575         btrfs_release_path(path);
2576         mutex_unlock(&fs_info->qgroup_rescan_lock);
2577
2578         for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
2579                 btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
2580                 if (found.type != BTRFS_EXTENT_ITEM_KEY &&
2581                     found.type != BTRFS_METADATA_ITEM_KEY)
2582                         continue;
2583                 if (found.type == BTRFS_METADATA_ITEM_KEY)
2584                         num_bytes = fs_info->nodesize;
2585                 else
2586                         num_bytes = found.offset;
2587
2588                 ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
2589                                            &roots);
2590                 if (ret < 0)
2591                         goto out;
2592                 /* For rescan, just pass old_roots as NULL */
2593                 ret = btrfs_qgroup_account_extent(trans, fs_info,
2594                                 found.objectid, num_bytes, NULL, roots);
2595                 if (ret < 0)
2596                         goto out;
2597         }
2598 out:
2599         if (scratch_leaf) {
2600                 btrfs_tree_read_unlock_blocking(scratch_leaf);
2601                 free_extent_buffer(scratch_leaf);
2602         }
2603         btrfs_put_tree_mod_seq(fs_info, &tree_mod_seq_elem);
2604
2605         if (done && !ret) {
2606                 ret = 1;
2607                 fs_info->qgroup_rescan_progress.objectid = (u64)-1;
2608         }
2609         return ret;
2610 }
2611
2612 static bool rescan_should_stop(struct btrfs_fs_info *fs_info)
2613 {
2614         return btrfs_fs_closing(fs_info) ||
2615                 test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
2616 }
2617
2618 static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
2619 {
2620         struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
2621                                                      qgroup_rescan_work);
2622         struct btrfs_path *path;
2623         struct btrfs_trans_handle *trans = NULL;
2624         int err = -ENOMEM;
2625         int ret = 0;
2626         bool stopped = false;
2627
2628         path = btrfs_alloc_path();
2629         if (!path)
2630                 goto out;
2631
2632         err = 0;
2633         while (!err && !(stopped = rescan_should_stop(fs_info))) {
2634                 trans = btrfs_start_transaction(fs_info->fs_root, 0);
2635                 if (IS_ERR(trans)) {
2636                         err = PTR_ERR(trans);
2637                         break;
2638                 }
2639                 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
2640                         err = -EINTR;
2641                 } else {
2642                         err = qgroup_rescan_leaf(fs_info, path, trans);
2643                 }
2644                 if (err > 0)
2645                         btrfs_commit_transaction(trans);
2646                 else
2647                         btrfs_end_transaction(trans);
2648         }
2649
2650 out:
2651         btrfs_free_path(path);
2652
2653         mutex_lock(&fs_info->qgroup_rescan_lock);
2654         if (err > 0 &&
2655             fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT) {
2656                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2657         } else if (err < 0) {
2658                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2659         }
2660         mutex_unlock(&fs_info->qgroup_rescan_lock);
2661
2662         /*
2663          * only update status, since the previous part has already updated the
2664          * qgroup info.
2665          */
2666         trans = btrfs_start_transaction(fs_info->quota_root, 1);
2667         if (IS_ERR(trans)) {
2668                 err = PTR_ERR(trans);
2669                 trans = NULL;
2670                 btrfs_err(fs_info,
2671                           "fail to start transaction for status update: %d",
2672                           err);
2673         }
2674
2675         mutex_lock(&fs_info->qgroup_rescan_lock);
2676         if (!stopped)
2677                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
2678         if (trans) {
2679                 ret = update_qgroup_status_item(trans);
2680                 if (ret < 0) {
2681                         err = ret;
2682                         btrfs_err(fs_info, "fail to update qgroup status: %d",
2683                                   err);
2684                 }
2685         }
2686         fs_info->qgroup_rescan_running = false;
2687         complete_all(&fs_info->qgroup_rescan_completion);
2688         mutex_unlock(&fs_info->qgroup_rescan_lock);
2689
2690         if (!trans)
2691                 return;
2692
2693         btrfs_end_transaction(trans);
2694
2695         if (stopped) {
2696                 btrfs_info(fs_info, "qgroup scan paused");
2697         } else if (err >= 0) {
2698                 btrfs_info(fs_info, "qgroup scan completed%s",
2699                         err > 0 ? " (inconsistency flag cleared)" : "");
2700         } else {
2701                 btrfs_err(fs_info, "qgroup scan failed with %d", err);
2702         }
2703 }
2704
2705 /*
2706  * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
2707  * memory required for the rescan context.
2708  */
2709 static int
2710 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
2711                    int init_flags)
2712 {
2713         int ret = 0;
2714
2715         if (!init_flags &&
2716             (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) ||
2717              !(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))) {
2718                 ret = -EINVAL;
2719                 goto err;
2720         }
2721
2722         mutex_lock(&fs_info->qgroup_rescan_lock);
2723         spin_lock(&fs_info->qgroup_lock);
2724
2725         if (init_flags) {
2726                 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN)
2727                         ret = -EINPROGRESS;
2728                 else if (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))
2729                         ret = -EINVAL;
2730
2731                 if (ret) {
2732                         spin_unlock(&fs_info->qgroup_lock);
2733                         mutex_unlock(&fs_info->qgroup_rescan_lock);
2734                         goto err;
2735                 }
2736                 fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
2737         }
2738
2739         memset(&fs_info->qgroup_rescan_progress, 0,
2740                 sizeof(fs_info->qgroup_rescan_progress));
2741         fs_info->qgroup_rescan_progress.objectid = progress_objectid;
2742         init_completion(&fs_info->qgroup_rescan_completion);
2743         fs_info->qgroup_rescan_running = true;
2744
2745         spin_unlock(&fs_info->qgroup_lock);
2746         mutex_unlock(&fs_info->qgroup_rescan_lock);
2747
2748         memset(&fs_info->qgroup_rescan_work, 0,
2749                sizeof(fs_info->qgroup_rescan_work));
2750         btrfs_init_work(&fs_info->qgroup_rescan_work,
2751                         btrfs_qgroup_rescan_helper,
2752                         btrfs_qgroup_rescan_worker, NULL, NULL);
2753
2754         if (ret) {
2755 err:
2756                 btrfs_info(fs_info, "qgroup_rescan_init failed with %d", ret);
2757                 return ret;
2758         }
2759
2760         return 0;
2761 }
2762
2763 static void
2764 qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
2765 {
2766         struct rb_node *n;
2767         struct btrfs_qgroup *qgroup;
2768
2769         spin_lock(&fs_info->qgroup_lock);
2770         /* clear all current qgroup tracking information */
2771         for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
2772                 qgroup = rb_entry(n, struct btrfs_qgroup, node);
2773                 qgroup->rfer = 0;
2774                 qgroup->rfer_cmpr = 0;
2775                 qgroup->excl = 0;
2776                 qgroup->excl_cmpr = 0;
2777                 qgroup_dirty(fs_info, qgroup);
2778         }
2779         spin_unlock(&fs_info->qgroup_lock);
2780 }
2781
2782 int
2783 btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
2784 {
2785         int ret = 0;
2786         struct btrfs_trans_handle *trans;
2787
2788         ret = qgroup_rescan_init(fs_info, 0, 1);
2789         if (ret)
2790                 return ret;
2791
2792         /*
2793          * We have set the rescan_progress to 0, which means no more
2794          * delayed refs will be accounted by btrfs_qgroup_account_ref.
2795          * However, btrfs_qgroup_account_ref may be right after its call
2796          * to btrfs_find_all_roots, in which case it would still do the
2797          * accounting.
2798          * To solve this, we're committing the transaction, which will
2799          * ensure we run all delayed refs and only after that, we are
2800          * going to clear all tracking information for a clean start.
2801          */
2802
2803         trans = btrfs_join_transaction(fs_info->fs_root);
2804         if (IS_ERR(trans)) {
2805                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
2806                 return PTR_ERR(trans);
2807         }
2808         ret = btrfs_commit_transaction(trans);
2809         if (ret) {
2810                 fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
2811                 return ret;
2812         }
2813
2814         qgroup_rescan_zero_tracking(fs_info);
2815
2816         btrfs_queue_work(fs_info->qgroup_rescan_workers,
2817                          &fs_info->qgroup_rescan_work);
2818
2819         return 0;
2820 }
2821
2822 int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
2823                                      bool interruptible)
2824 {
2825         int running;
2826         int ret = 0;
2827
2828         mutex_lock(&fs_info->qgroup_rescan_lock);
2829         spin_lock(&fs_info->qgroup_lock);
2830         running = fs_info->qgroup_rescan_running;
2831         spin_unlock(&fs_info->qgroup_lock);
2832         mutex_unlock(&fs_info->qgroup_rescan_lock);
2833
2834         if (!running)
2835                 return 0;
2836
2837         if (interruptible)
2838                 ret = wait_for_completion_interruptible(
2839                                         &fs_info->qgroup_rescan_completion);
2840         else
2841                 wait_for_completion(&fs_info->qgroup_rescan_completion);
2842
2843         return ret;
2844 }
2845
2846 /*
2847  * this is only called from open_ctree where we're still single threaded, thus
2848  * locking is omitted here.
2849  */
2850 void
2851 btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
2852 {
2853         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN)
2854                 btrfs_queue_work(fs_info->qgroup_rescan_workers,
2855                                  &fs_info->qgroup_rescan_work);
2856 }
2857
2858 /*
2859  * Reserve qgroup space for range [start, start + len).
2860  *
2861  * This function will either reserve space from related qgroups or doing
2862  * nothing if the range is already reserved.
2863  *
2864  * Return 0 for successful reserve
2865  * Return <0 for error (including -EQUOT)
2866  *
2867  * NOTE: this function may sleep for memory allocation.
2868  *       if btrfs_qgroup_reserve_data() is called multiple times with
2869  *       same @reserved, caller must ensure when error happens it's OK
2870  *       to free *ALL* reserved space.
2871  */
2872 int btrfs_qgroup_reserve_data(struct inode *inode,
2873                         struct extent_changeset **reserved_ret, u64 start,
2874                         u64 len)
2875 {
2876         struct btrfs_root *root = BTRFS_I(inode)->root;
2877         struct ulist_node *unode;
2878         struct ulist_iterator uiter;
2879         struct extent_changeset *reserved;
2880         u64 orig_reserved;
2881         u64 to_reserve;
2882         int ret;
2883
2884         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
2885             !is_fstree(root->objectid) || len == 0)
2886                 return 0;
2887
2888         /* @reserved parameter is mandatory for qgroup */
2889         if (WARN_ON(!reserved_ret))
2890                 return -EINVAL;
2891         if (!*reserved_ret) {
2892                 *reserved_ret = extent_changeset_alloc();
2893                 if (!*reserved_ret)
2894                         return -ENOMEM;
2895         }
2896         reserved = *reserved_ret;
2897         /* Record already reserved space */
2898         orig_reserved = reserved->bytes_changed;
2899         ret = set_record_extent_bits(&BTRFS_I(inode)->io_tree, start,
2900                         start + len -1, EXTENT_QGROUP_RESERVED, reserved);
2901
2902         /* Newly reserved space */
2903         to_reserve = reserved->bytes_changed - orig_reserved;
2904         trace_btrfs_qgroup_reserve_data(inode, start, len,
2905                                         to_reserve, QGROUP_RESERVE);
2906         if (ret < 0)
2907                 goto cleanup;
2908         ret = qgroup_reserve(root, to_reserve, true);
2909         if (ret < 0)
2910                 goto cleanup;
2911
2912         return ret;
2913
2914 cleanup:
2915         /* cleanup *ALL* already reserved ranges */
2916         ULIST_ITER_INIT(&uiter);
2917         while ((unode = ulist_next(&reserved->range_changed, &uiter)))
2918                 clear_extent_bit(&BTRFS_I(inode)->io_tree, unode->val,
2919                                  unode->aux, EXTENT_QGROUP_RESERVED, 0, 0, NULL,
2920                                  GFP_NOFS);
2921         extent_changeset_release(reserved);
2922         return ret;
2923 }
2924
2925 /* Free ranges specified by @reserved, normally in error path */
2926 static int qgroup_free_reserved_data(struct inode *inode,
2927                         struct extent_changeset *reserved, u64 start, u64 len)
2928 {
2929         struct btrfs_root *root = BTRFS_I(inode)->root;
2930         struct ulist_node *unode;
2931         struct ulist_iterator uiter;
2932         struct extent_changeset changeset;
2933         int freed = 0;
2934         int ret;
2935
2936         extent_changeset_init(&changeset);
2937         len = round_up(start + len, root->fs_info->sectorsize);
2938         start = round_down(start, root->fs_info->sectorsize);
2939
2940         ULIST_ITER_INIT(&uiter);
2941         while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
2942                 u64 range_start = unode->val;
2943                 /* unode->aux is the inclusive end */
2944                 u64 range_len = unode->aux - range_start + 1;
2945                 u64 free_start;
2946                 u64 free_len;
2947
2948                 extent_changeset_release(&changeset);
2949
2950                 /* Only free range in range [start, start + len) */
2951                 if (range_start >= start + len ||
2952                     range_start + range_len <= start)
2953                         continue;
2954                 free_start = max(range_start, start);
2955                 free_len = min(start + len, range_start + range_len) -
2956                            free_start;
2957                 /*
2958                  * TODO: To also modify reserved->ranges_reserved to reflect
2959                  * the modification.
2960                  *
2961                  * However as long as we free qgroup reserved according to
2962                  * EXTENT_QGROUP_RESERVED, we won't double free.
2963                  * So not need to rush.
2964                  */
2965                 ret = clear_record_extent_bits(&BTRFS_I(inode)->io_tree,
2966                                 free_start, free_start + free_len - 1,
2967                                 EXTENT_QGROUP_RESERVED, &changeset);
2968                 if (ret < 0)
2969                         goto out;
2970                 freed += changeset.bytes_changed;
2971         }
2972         btrfs_qgroup_free_refroot(root->fs_info, root->objectid, freed);
2973         ret = freed;
2974 out:
2975         extent_changeset_release(&changeset);
2976         return ret;
2977 }
2978
2979 static int __btrfs_qgroup_release_data(struct inode *inode,
2980                         struct extent_changeset *reserved, u64 start, u64 len,
2981                         int free)
2982 {
2983         struct extent_changeset changeset;
2984         int trace_op = QGROUP_RELEASE;
2985         int ret;
2986
2987         if (!test_bit(BTRFS_FS_QUOTA_ENABLED,
2988                       &BTRFS_I(inode)->root->fs_info->flags))
2989                 return 0;
2990
2991         /* In release case, we shouldn't have @reserved */
2992         WARN_ON(!free && reserved);
2993         if (free && reserved)
2994                 return qgroup_free_reserved_data(inode, reserved, start, len);
2995         extent_changeset_init(&changeset);
2996         ret = clear_record_extent_bits(&BTRFS_I(inode)->io_tree, start, 
2997                         start + len -1, EXTENT_QGROUP_RESERVED, &changeset);
2998         if (ret < 0)
2999                 goto out;
3000
3001         if (free)
3002                 trace_op = QGROUP_FREE;
3003         trace_btrfs_qgroup_release_data(inode, start, len,
3004                                         changeset.bytes_changed, trace_op);
3005         if (free)
3006                 btrfs_qgroup_free_refroot(BTRFS_I(inode)->root->fs_info,
3007                                 BTRFS_I(inode)->root->objectid,
3008                                 changeset.bytes_changed);
3009         ret = changeset.bytes_changed;
3010 out:
3011         extent_changeset_release(&changeset);
3012         return ret;
3013 }
3014
3015 /*
3016  * Free a reserved space range from io_tree and related qgroups
3017  *
3018  * Should be called when a range of pages get invalidated before reaching disk.
3019  * Or for error cleanup case.
3020  * if @reserved is given, only reserved range in [@start, @start + @len) will
3021  * be freed.
3022  *
3023  * For data written to disk, use btrfs_qgroup_release_data().
3024  *
3025  * NOTE: This function may sleep for memory allocation.
3026  */
3027 int btrfs_qgroup_free_data(struct inode *inode,
3028                         struct extent_changeset *reserved, u64 start, u64 len)
3029 {
3030         return __btrfs_qgroup_release_data(inode, reserved, start, len, 1);
3031 }
3032
3033 /*
3034  * Release a reserved space range from io_tree only.
3035  *
3036  * Should be called when a range of pages get written to disk and corresponding
3037  * FILE_EXTENT is inserted into corresponding root.
3038  *
3039  * Since new qgroup accounting framework will only update qgroup numbers at
3040  * commit_transaction() time, its reserved space shouldn't be freed from
3041  * related qgroups.
3042  *
3043  * But we should release the range from io_tree, to allow further write to be
3044  * COWed.
3045  *
3046  * NOTE: This function may sleep for memory allocation.
3047  */
3048 int btrfs_qgroup_release_data(struct inode *inode, u64 start, u64 len)
3049 {
3050         return __btrfs_qgroup_release_data(inode, NULL, start, len, 0);
3051 }
3052
3053 int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
3054                               bool enforce)
3055 {
3056         struct btrfs_fs_info *fs_info = root->fs_info;
3057         int ret;
3058
3059         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3060             !is_fstree(root->objectid) || num_bytes == 0)
3061                 return 0;
3062
3063         BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3064         trace_qgroup_meta_reserve(root, (s64)num_bytes);
3065         ret = qgroup_reserve(root, num_bytes, enforce);
3066         if (ret < 0)
3067                 return ret;
3068         atomic64_add(num_bytes, &root->qgroup_meta_rsv);
3069         return ret;
3070 }
3071
3072 void btrfs_qgroup_free_meta_all(struct btrfs_root *root)
3073 {
3074         struct btrfs_fs_info *fs_info = root->fs_info;
3075         u64 reserved;
3076
3077         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3078             !is_fstree(root->objectid))
3079                 return;
3080
3081         reserved = atomic64_xchg(&root->qgroup_meta_rsv, 0);
3082         if (reserved == 0)
3083                 return;
3084         trace_qgroup_meta_reserve(root, -(s64)reserved);
3085         btrfs_qgroup_free_refroot(fs_info, root->objectid, reserved);
3086 }
3087
3088 void btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes)
3089 {
3090         struct btrfs_fs_info *fs_info = root->fs_info;
3091
3092         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3093             !is_fstree(root->objectid))
3094                 return;
3095
3096         BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3097         WARN_ON(atomic64_read(&root->qgroup_meta_rsv) < num_bytes);
3098         atomic64_sub(num_bytes, &root->qgroup_meta_rsv);
3099         trace_qgroup_meta_reserve(root, -(s64)num_bytes);
3100         btrfs_qgroup_free_refroot(fs_info, root->objectid, num_bytes);
3101 }
3102
3103 /*
3104  * Check qgroup reserved space leaking, normally at destroy inode
3105  * time
3106  */
3107 void btrfs_qgroup_check_reserved_leak(struct inode *inode)
3108 {
3109         struct extent_changeset changeset;
3110         struct ulist_node *unode;
3111         struct ulist_iterator iter;
3112         int ret;
3113
3114         extent_changeset_init(&changeset);
3115         ret = clear_record_extent_bits(&BTRFS_I(inode)->io_tree, 0, (u64)-1,
3116                         EXTENT_QGROUP_RESERVED, &changeset);
3117
3118         WARN_ON(ret < 0);
3119         if (WARN_ON(changeset.bytes_changed)) {
3120                 ULIST_ITER_INIT(&iter);
3121                 while ((unode = ulist_next(&changeset.range_changed, &iter))) {
3122                         btrfs_warn(BTRFS_I(inode)->root->fs_info,
3123                                 "leaking qgroup reserved space, ino: %lu, start: %llu, end: %llu",
3124                                 inode->i_ino, unode->val, unode->aux);
3125                 }
3126                 btrfs_qgroup_free_refroot(BTRFS_I(inode)->root->fs_info,
3127                                 BTRFS_I(inode)->root->objectid,
3128                                 changeset.bytes_changed);
3129
3130         }
3131         extent_changeset_release(&changeset);
3132 }