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