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