xref: /linux/fs/btrfs/qgroup.c (revision 58e844c3ba387ceb0f527a6ba82aa50c81c4d7b7)
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 	spin_lock(&fs_info->trans_lock);
1444 	list_del(&quota_root->dirty_list);
1445 	spin_unlock(&fs_info->trans_lock);
1446 
1447 	btrfs_tree_lock(quota_root->node);
1448 	btrfs_clear_buffer_dirty(trans, quota_root->node);
1449 	btrfs_tree_unlock(quota_root->node);
1450 	ret = btrfs_free_tree_block(trans, btrfs_root_id(quota_root),
1451 				    quota_root->node, 0, 1);
1452 
1453 	if (ret < 0)
1454 		btrfs_abort_transaction(trans, ret);
1455 
1456 out:
1457 	btrfs_put_root(quota_root);
1458 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1459 	if (ret && trans)
1460 		btrfs_end_transaction(trans);
1461 	else if (trans)
1462 		ret = btrfs_commit_transaction(trans);
1463 	return ret;
1464 }
1465 
1466 static void qgroup_dirty(struct btrfs_fs_info *fs_info,
1467 			 struct btrfs_qgroup *qgroup)
1468 {
1469 	if (list_empty(&qgroup->dirty))
1470 		list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1471 }
1472 
1473 static void qgroup_iterator_add(struct list_head *head, struct btrfs_qgroup *qgroup)
1474 {
1475 	if (!list_empty(&qgroup->iterator))
1476 		return;
1477 
1478 	list_add_tail(&qgroup->iterator, head);
1479 }
1480 
1481 static void qgroup_iterator_clean(struct list_head *head)
1482 {
1483 	while (!list_empty(head)) {
1484 		struct btrfs_qgroup *qgroup;
1485 
1486 		qgroup = list_first_entry(head, struct btrfs_qgroup, iterator);
1487 		list_del_init(&qgroup->iterator);
1488 	}
1489 }
1490 
1491 /*
1492  * The easy accounting, we're updating qgroup relationship whose child qgroup
1493  * only has exclusive extents.
1494  *
1495  * In this case, all exclusive extents will also be exclusive for parent, so
1496  * excl/rfer just get added/removed.
1497  *
1498  * So is qgroup reservation space, which should also be added/removed to
1499  * parent.
1500  * Or when child tries to release reservation space, parent will underflow its
1501  * reservation (for relationship adding case).
1502  *
1503  * Caller should hold fs_info->qgroup_lock.
1504  */
1505 static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info, u64 ref_root,
1506 				    struct btrfs_qgroup *src, int sign)
1507 {
1508 	struct btrfs_qgroup *qgroup;
1509 	LIST_HEAD(qgroup_list);
1510 	u64 num_bytes = src->excl;
1511 	u64 num_bytes_cmpr = src->excl_cmpr;
1512 	int ret = 0;
1513 
1514 	qgroup = find_qgroup_rb(fs_info, ref_root);
1515 	if (!qgroup)
1516 		goto out;
1517 
1518 	qgroup_iterator_add(&qgroup_list, qgroup);
1519 	list_for_each_entry(qgroup, &qgroup_list, iterator) {
1520 		struct btrfs_qgroup_list *glist;
1521 
1522 		qgroup->rfer += sign * num_bytes;
1523 		qgroup->rfer_cmpr += sign * num_bytes_cmpr;
1524 
1525 		WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1526 		WARN_ON(sign < 0 && qgroup->excl_cmpr < num_bytes_cmpr);
1527 		qgroup->excl += sign * num_bytes;
1528 		qgroup->excl_cmpr += sign * num_bytes_cmpr;
1529 
1530 		if (sign > 0)
1531 			qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1532 		else
1533 			qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1534 		qgroup_dirty(fs_info, qgroup);
1535 
1536 		/* Append parent qgroups to @qgroup_list. */
1537 		list_for_each_entry(glist, &qgroup->groups, next_group)
1538 			qgroup_iterator_add(&qgroup_list, glist->group);
1539 	}
1540 	ret = 0;
1541 out:
1542 	qgroup_iterator_clean(&qgroup_list);
1543 	return ret;
1544 }
1545 
1546 
1547 /*
1548  * Quick path for updating qgroup with only excl refs.
1549  *
1550  * In that case, just update all parent will be enough.
1551  * Or we needs to do a full rescan.
1552  * Caller should also hold fs_info->qgroup_lock.
1553  *
1554  * Return 0 for quick update, return >0 for need to full rescan
1555  * and mark INCONSISTENT flag.
1556  * Return < 0 for other error.
1557  */
1558 static int quick_update_accounting(struct btrfs_fs_info *fs_info,
1559 				   u64 src, u64 dst, int sign)
1560 {
1561 	struct btrfs_qgroup *qgroup;
1562 	int ret = 1;
1563 
1564 	qgroup = find_qgroup_rb(fs_info, src);
1565 	if (!qgroup)
1566 		goto out;
1567 	if (qgroup->excl == qgroup->rfer) {
1568 		ret = __qgroup_excl_accounting(fs_info, dst, qgroup, sign);
1569 		if (ret < 0)
1570 			goto out;
1571 		ret = 0;
1572 	}
1573 out:
1574 	if (ret)
1575 		qgroup_mark_inconsistent(fs_info,
1576 	"unable to do quick excl updating for qgroup %hu/%llu, ret=%d",
1577 					 btrfs_qgroup_level(src),
1578 					 btrfs_qgroup_subvolid(src), ret);
1579 	return ret;
1580 }
1581 
1582 /*
1583  * Add relation between @src and @dst qgroup. The @prealloc is allocated by the
1584  * callers and transferred here (either used or freed on error).
1585  */
1586 int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans, u64 src, u64 dst,
1587 			      struct btrfs_qgroup_list *prealloc)
1588 {
1589 	struct btrfs_fs_info *fs_info = trans->fs_info;
1590 	struct btrfs_qgroup *parent;
1591 	struct btrfs_qgroup *member;
1592 	struct btrfs_qgroup_list *list;
1593 	int ret = 0;
1594 
1595 	ASSERT(prealloc);
1596 
1597 	/* Check the level of src and dst first */
1598 	if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst)) {
1599 		kfree(prealloc);
1600 		return -EINVAL;
1601 	}
1602 
1603 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1604 	if (!fs_info->quota_root) {
1605 		ret = -ENOTCONN;
1606 		goto out;
1607 	}
1608 	member = find_qgroup_rb(fs_info, src);
1609 	parent = find_qgroup_rb(fs_info, dst);
1610 	if (!member || !parent) {
1611 		ret = -EINVAL;
1612 		goto out;
1613 	}
1614 
1615 	/* check if such qgroup relation exist firstly */
1616 	list_for_each_entry(list, &member->groups, next_group) {
1617 		if (list->group == parent) {
1618 			ret = -EEXIST;
1619 			goto out;
1620 		}
1621 	}
1622 
1623 	ret = add_qgroup_relation_item(trans, src, dst);
1624 	if (ret)
1625 		goto out;
1626 
1627 	ret = add_qgroup_relation_item(trans, dst, src);
1628 	if (ret) {
1629 		int ret2;
1630 
1631 		ret2 = del_qgroup_relation_item(trans, src, dst);
1632 		if (ret2 < 0)
1633 			btrfs_abort_transaction(trans, ret);
1634 		goto out;
1635 	}
1636 
1637 	spin_lock(&fs_info->qgroup_lock);
1638 	ret = __add_relation_rb(prealloc, member, parent);
1639 	prealloc = NULL;
1640 	if (ret < 0) {
1641 		spin_unlock(&fs_info->qgroup_lock);
1642 		goto out;
1643 	}
1644 	ret = quick_update_accounting(fs_info, src, dst, 1);
1645 	squota_check_parent_usage(fs_info, parent);
1646 	spin_unlock(&fs_info->qgroup_lock);
1647 out:
1648 	kfree(prealloc);
1649 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1650 	return ret;
1651 }
1652 
1653 static int __del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1654 				 u64 dst)
1655 {
1656 	struct btrfs_fs_info *fs_info = trans->fs_info;
1657 	struct btrfs_qgroup *parent;
1658 	struct btrfs_qgroup *member;
1659 	struct btrfs_qgroup_list *list;
1660 	bool found = false;
1661 	int ret = 0;
1662 	int ret2;
1663 
1664 	if (!fs_info->quota_root)
1665 		return -ENOTCONN;
1666 
1667 	member = find_qgroup_rb(fs_info, src);
1668 	parent = find_qgroup_rb(fs_info, dst);
1669 	/*
1670 	 * The parent/member pair doesn't exist, then try to delete the dead
1671 	 * relation items only.
1672 	 */
1673 	if (!member || !parent)
1674 		goto delete_item;
1675 
1676 	/* check if such qgroup relation exist firstly */
1677 	list_for_each_entry(list, &member->groups, next_group) {
1678 		if (list->group == parent) {
1679 			found = true;
1680 			break;
1681 		}
1682 	}
1683 
1684 delete_item:
1685 	ret = del_qgroup_relation_item(trans, src, dst);
1686 	if (ret < 0 && ret != -ENOENT)
1687 		return ret;
1688 	ret2 = del_qgroup_relation_item(trans, dst, src);
1689 	if (ret2 < 0 && ret2 != -ENOENT)
1690 		return ret2;
1691 
1692 	/* At least one deletion succeeded, return 0 */
1693 	if (!ret || !ret2)
1694 		ret = 0;
1695 
1696 	if (found) {
1697 		spin_lock(&fs_info->qgroup_lock);
1698 		del_relation_rb(fs_info, src, dst);
1699 		ret = quick_update_accounting(fs_info, src, dst, -1);
1700 		ASSERT(parent);
1701 		squota_check_parent_usage(fs_info, parent);
1702 		spin_unlock(&fs_info->qgroup_lock);
1703 	}
1704 
1705 	return ret;
1706 }
1707 
1708 int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1709 			      u64 dst)
1710 {
1711 	struct btrfs_fs_info *fs_info = trans->fs_info;
1712 	int ret = 0;
1713 
1714 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1715 	ret = __del_qgroup_relation(trans, src, dst);
1716 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1717 
1718 	return ret;
1719 }
1720 
1721 int btrfs_create_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1722 {
1723 	struct btrfs_fs_info *fs_info = trans->fs_info;
1724 	struct btrfs_root *quota_root;
1725 	struct btrfs_qgroup *qgroup;
1726 	struct btrfs_qgroup *prealloc = NULL;
1727 	int ret = 0;
1728 
1729 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1730 	if (!fs_info->quota_root) {
1731 		ret = -ENOTCONN;
1732 		goto out;
1733 	}
1734 	quota_root = fs_info->quota_root;
1735 	qgroup = find_qgroup_rb(fs_info, qgroupid);
1736 	if (qgroup) {
1737 		ret = -EEXIST;
1738 		goto out;
1739 	}
1740 
1741 	prealloc = kzalloc_obj(*prealloc, GFP_NOFS);
1742 	if (!prealloc) {
1743 		ret = -ENOMEM;
1744 		goto out;
1745 	}
1746 
1747 	ret = add_qgroup_item(trans, quota_root, qgroupid);
1748 	if (ret)
1749 		goto out;
1750 
1751 	spin_lock(&fs_info->qgroup_lock);
1752 	qgroup = add_qgroup_rb(fs_info, prealloc, qgroupid);
1753 	spin_unlock(&fs_info->qgroup_lock);
1754 	prealloc = NULL;
1755 
1756 	ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1757 out:
1758 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1759 	kfree(prealloc);
1760 	return ret;
1761 }
1762 
1763 static bool can_delete_parent_qgroup(struct btrfs_fs_info *fs_info, struct btrfs_qgroup *qgroup)
1764 {
1765 	ASSERT(btrfs_qgroup_level(qgroup->qgroupid));
1766 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE)
1767 		squota_check_parent_usage(fs_info, qgroup);
1768 	return list_empty(&qgroup->members);
1769 }
1770 
1771 /*
1772  * Because a shared extent can outlive its owning subvolume, we cannot delete a
1773  * subvol squota qgroup until all of the extents it owns are gone, even if the
1774  * subvolume itself has been deleted.
1775  */
1776 static bool can_delete_squota_subvol_qgroup(struct btrfs_fs_info *fs_info,
1777 					    struct btrfs_qgroup *qgroup)
1778 {
1779 	ASSERT(btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE);
1780 	ASSERT(btrfs_qgroup_level(qgroup->qgroupid) == 0);
1781 
1782 	return !(qgroup->rfer || qgroup->excl || qgroup->rfer_cmpr || qgroup->excl_cmpr);
1783 }
1784 
1785 /*
1786  * Return 0 if we can not delete the qgroup (not empty or has children etc).
1787  * Return >0 if we can delete the qgroup.
1788  * Return <0 for other errors during tree search.
1789  */
1790 static int can_delete_qgroup(struct btrfs_fs_info *fs_info, struct btrfs_qgroup *qgroup)
1791 {
1792 	struct btrfs_key key;
1793 	BTRFS_PATH_AUTO_FREE(path);
1794 	int ret;
1795 
1796 	/* For higher level qgroup, we can only delete it if it has no child. */
1797 	if (btrfs_qgroup_level(qgroup->qgroupid))
1798 		return can_delete_parent_qgroup(fs_info, qgroup);
1799 
1800 	/*
1801 	 * For level-0 qgroups, we can only delete it if it has no subvolume
1802 	 * for it.
1803 	 * This means even a subvolume is unlinked but not yet fully dropped,
1804 	 * we can not delete the qgroup.
1805 	 */
1806 	key.objectid = qgroup->qgroupid;
1807 	key.type = BTRFS_ROOT_ITEM_KEY;
1808 	key.offset = -1ULL;
1809 	path = btrfs_alloc_path();
1810 	if (!path)
1811 		return -ENOMEM;
1812 
1813 	/*
1814 	 * Any subvol qgroup, regardless of mode, cannot be deleted if the
1815 	 * subvol still exists.
1816 	 */
1817 	ret = btrfs_find_root(fs_info->tree_root, &key, path, NULL, NULL);
1818 	/*
1819 	 * btrfs_find_root returns <0 on error, 0 if found, and >0 if not,
1820 	 * so the "found" and "error" cases match our desired return values.
1821 	 */
1822 	if (ret <= 0)
1823 		return ret;
1824 
1825 	/* Squotas require additional checks, even if the subvol is deleted. */
1826 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE)
1827 		return can_delete_squota_subvol_qgroup(fs_info, qgroup);
1828 	return 1;
1829 }
1830 
1831 int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1832 {
1833 	struct btrfs_fs_info *fs_info = trans->fs_info;
1834 	struct btrfs_qgroup *qgroup;
1835 	struct btrfs_qgroup_list *list;
1836 	int ret = 0;
1837 
1838 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1839 	if (!fs_info->quota_root) {
1840 		ret = -ENOTCONN;
1841 		goto out;
1842 	}
1843 
1844 	qgroup = find_qgroup_rb(fs_info, qgroupid);
1845 	if (!qgroup) {
1846 		ret = -ENOENT;
1847 		goto out;
1848 	}
1849 
1850 	ret = can_delete_qgroup(fs_info, qgroup);
1851 	if (ret < 0)
1852 		goto out;
1853 	if (ret == 0) {
1854 		ret = -EBUSY;
1855 		goto out;
1856 	}
1857 
1858 	/* Check if there are no children of this qgroup */
1859 	if (!list_empty(&qgroup->members)) {
1860 		ret = -EBUSY;
1861 		goto out;
1862 	}
1863 
1864 	ret = del_qgroup_item(trans, qgroupid);
1865 	if (ret && ret != -ENOENT)
1866 		goto out;
1867 	ret = 0;
1868 
1869 	while (!list_empty(&qgroup->groups)) {
1870 		list = list_first_entry(&qgroup->groups,
1871 					struct btrfs_qgroup_list, next_group);
1872 		ret = __del_qgroup_relation(trans, qgroupid,
1873 					    list->group->qgroupid);
1874 		if (ret < 0)
1875 			goto out;
1876 	}
1877 
1878 	spin_lock(&fs_info->qgroup_lock);
1879 	/*
1880 	 * Warn on reserved space. The subvolume should has no child nor
1881 	 * corresponding subvolume.
1882 	 * Thus its reserved space should all be zero, no matter if qgroup
1883 	 * is consistent or the mode.
1884 	 */
1885 	if (unlikely(qgroup->rsv.values[BTRFS_QGROUP_RSV_DATA] ||
1886 		     qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PREALLOC] ||
1887 		     qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PERTRANS])) {
1888 		DEBUG_WARN();
1889 		btrfs_warn_rl(fs_info,
1890 "to be deleted qgroup " BTRFS_QGROUP_FMT " has non-zero numbers, data %llu meta prealloc %llu meta pertrans %llu",
1891 			      BTRFS_QGROUP_FMT_VALUE(qgroup),
1892 			      qgroup->rsv.values[BTRFS_QGROUP_RSV_DATA],
1893 			      qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PREALLOC],
1894 			      qgroup->rsv.values[BTRFS_QGROUP_RSV_META_PERTRANS]);
1895 
1896 	}
1897 	/*
1898 	 * The same for rfer/excl numbers, but that's only if our qgroup is
1899 	 * consistent and if it's in regular qgroup mode.
1900 	 * For simple mode it's not as accurate thus we can hit non-zero values
1901 	 * very frequently.
1902 	 */
1903 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_FULL &&
1904 	    !test_bit(BTRFS_QGROUP_STATUS_BIT_INCONSISTENT, &fs_info->qgroup_flags)) {
1905 		if (unlikely(qgroup->rfer || qgroup->excl ||
1906 			     qgroup->rfer_cmpr || qgroup->excl_cmpr)) {
1907 			DEBUG_WARN();
1908 			qgroup_mark_inconsistent(fs_info,
1909 "to be deleted qgroup " BTRFS_QGROUP_FMT " has non-zero numbers, rfer %llu rfer_cmpr %llu excl %llu excl_cmpr %llu",
1910 				BTRFS_QGROUP_FMT_VALUE(qgroup),
1911 				qgroup->rfer, qgroup->rfer_cmpr,
1912 				qgroup->excl, qgroup->excl_cmpr);
1913 		}
1914 	}
1915 	del_qgroup_rb(fs_info, qgroupid);
1916 	spin_unlock(&fs_info->qgroup_lock);
1917 
1918 	/*
1919 	 * Remove the qgroup from sysfs now without holding the qgroup_lock
1920 	 * spinlock, since the sysfs_remove_group() function needs to take
1921 	 * the mutex kernfs_mutex through kernfs_remove_by_name_ns().
1922 	 */
1923 	btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
1924 	kfree(qgroup);
1925 out:
1926 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1927 	return ret;
1928 }
1929 
1930 int btrfs_qgroup_cleanup_dropped_subvolume(struct btrfs_fs_info *fs_info, u64 subvolid)
1931 {
1932 	struct btrfs_trans_handle *trans;
1933 	int ret;
1934 
1935 	if (!btrfs_is_fstree(subvolid) || !btrfs_qgroup_enabled(fs_info) ||
1936 	    !fs_info->quota_root)
1937 		return 0;
1938 
1939 	/*
1940 	 * Commit current transaction to make sure all the rfer/excl numbers
1941 	 * get updated.
1942 	 */
1943 	ret = btrfs_commit_current_transaction(fs_info->quota_root);
1944 	if (ret < 0)
1945 		return ret;
1946 
1947 	/* Start new trans to delete the qgroup info and limit items. */
1948 	trans = btrfs_start_transaction(fs_info->quota_root, 2);
1949 	if (IS_ERR(trans))
1950 		return PTR_ERR(trans);
1951 	ret = btrfs_remove_qgroup(trans, subvolid);
1952 	btrfs_end_transaction(trans);
1953 	/*
1954 	 * It's squota and the subvolume still has numbers needed for future
1955 	 * accounting, in this case we can not delete it.  Just skip it.
1956 	 *
1957 	 * Or the qgroup is already removed by a qgroup rescan. For both cases we're
1958 	 * safe to ignore them.
1959 	 */
1960 	if (ret == -EBUSY || ret == -ENOENT)
1961 		ret = 0;
1962 	return ret;
1963 }
1964 
1965 int btrfs_limit_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid,
1966 		       struct btrfs_qgroup_limit *limit)
1967 {
1968 	struct btrfs_fs_info *fs_info = trans->fs_info;
1969 	struct btrfs_qgroup *qgroup;
1970 	int ret = 0;
1971 	/* Sometimes we would want to clear the limit on this qgroup.
1972 	 * To meet this requirement, we treat the -1 as a special value
1973 	 * which tell kernel to clear the limit on this qgroup.
1974 	 */
1975 	const u64 CLEAR_VALUE = -1;
1976 
1977 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1978 	if (!fs_info->quota_root) {
1979 		ret = -ENOTCONN;
1980 		goto out;
1981 	}
1982 
1983 	qgroup = find_qgroup_rb(fs_info, qgroupid);
1984 	if (!qgroup) {
1985 		ret = -ENOENT;
1986 		goto out;
1987 	}
1988 
1989 	spin_lock(&fs_info->qgroup_lock);
1990 	if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
1991 		if (limit->max_rfer == CLEAR_VALUE) {
1992 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1993 			limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1994 			qgroup->max_rfer = 0;
1995 		} else {
1996 			qgroup->max_rfer = limit->max_rfer;
1997 		}
1998 	}
1999 	if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
2000 		if (limit->max_excl == CLEAR_VALUE) {
2001 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
2002 			limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
2003 			qgroup->max_excl = 0;
2004 		} else {
2005 			qgroup->max_excl = limit->max_excl;
2006 		}
2007 	}
2008 	if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
2009 		if (limit->rsv_rfer == CLEAR_VALUE) {
2010 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
2011 			limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
2012 			qgroup->rsv_rfer = 0;
2013 		} else {
2014 			qgroup->rsv_rfer = limit->rsv_rfer;
2015 		}
2016 	}
2017 	if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
2018 		if (limit->rsv_excl == CLEAR_VALUE) {
2019 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
2020 			limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
2021 			qgroup->rsv_excl = 0;
2022 		} else {
2023 			qgroup->rsv_excl = limit->rsv_excl;
2024 		}
2025 	}
2026 	qgroup->lim_flags |= limit->flags;
2027 
2028 	spin_unlock(&fs_info->qgroup_lock);
2029 
2030 	ret = update_qgroup_limit_item(trans, qgroup);
2031 	if (ret)
2032 		qgroup_mark_inconsistent(fs_info, "qgroup item update error %d", ret);
2033 
2034 out:
2035 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
2036 	return ret;
2037 }
2038 
2039 /*
2040  * Inform qgroup to trace one dirty extent, its info is recorded in @record.
2041  * So qgroup can account it at transaction committing time.
2042  *
2043  * No lock version, caller must acquire delayed ref lock and allocated memory,
2044  * then call btrfs_qgroup_trace_extent_post() after exiting lock context.
2045  *
2046  * Return 0 for success insert
2047  * Return >0 for existing record, caller can free @record safely.
2048  * Return <0 for insertion failure, caller can free @record safely.
2049  */
2050 int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
2051 				     struct btrfs_delayed_ref_root *delayed_refs,
2052 				     struct btrfs_qgroup_extent_record *record,
2053 				     u64 bytenr)
2054 {
2055 	struct btrfs_qgroup_extent_record *existing, *ret;
2056 	const unsigned long index = (bytenr >> fs_info->sectorsize_bits);
2057 
2058 	if (!btrfs_qgroup_full_accounting(fs_info))
2059 		return 1;
2060 
2061 #if BITS_PER_LONG == 32
2062 	if (bytenr >= MAX_LFS_FILESIZE) {
2063 		btrfs_err_rl(fs_info,
2064 "qgroup record for extent at %llu is beyond 32bit page cache and xarray index limit",
2065 			     bytenr);
2066 		btrfs_err_32bit_limit(fs_info);
2067 		return -EOVERFLOW;
2068 	}
2069 #endif
2070 
2071 	trace_btrfs_qgroup_trace_extent(fs_info, record, bytenr);
2072 
2073 	xa_lock(&delayed_refs->dirty_extents);
2074 	existing = xa_load(&delayed_refs->dirty_extents, index);
2075 	if (existing) {
2076 		if (record->data_rsv && !existing->data_rsv) {
2077 			existing->data_rsv = record->data_rsv;
2078 			existing->data_rsv_refroot = record->data_rsv_refroot;
2079 		}
2080 		xa_unlock(&delayed_refs->dirty_extents);
2081 		return 1;
2082 	}
2083 
2084 	ret = __xa_store(&delayed_refs->dirty_extents, index, record, GFP_ATOMIC);
2085 	xa_unlock(&delayed_refs->dirty_extents);
2086 	if (xa_is_err(ret)) {
2087 		qgroup_mark_inconsistent(fs_info, "xarray insert error: %d", xa_err(ret));
2088 		return xa_err(ret);
2089 	}
2090 
2091 	return 0;
2092 }
2093 
2094 /*
2095  * Post handler after qgroup_trace_extent_nolock().
2096  *
2097  * NOTE: Current qgroup does the expensive backref walk at transaction
2098  * committing time with TRANS_STATE_COMMIT_DOING, this blocks incoming
2099  * new transaction.
2100  * This is designed to allow btrfs_find_all_roots() to get correct new_roots
2101  * result.
2102  *
2103  * However for old_roots there is no need to do backref walk at that time,
2104  * since we search commit roots to walk backref and result will always be
2105  * correct.
2106  *
2107  * Due to the nature of no lock version, we can't do backref there.
2108  * So we must call btrfs_qgroup_trace_extent_post() after exiting
2109  * spinlock context.
2110  *
2111  * TODO: If we can fix and prove btrfs_find_all_roots() can get correct result
2112  * using current root, then we can move all expensive backref walk out of
2113  * transaction committing, but not now as qgroup accounting will be wrong again.
2114  */
2115 int btrfs_qgroup_trace_extent_post(struct btrfs_trans_handle *trans,
2116 				   struct btrfs_qgroup_extent_record *qrecord,
2117 				   u64 bytenr)
2118 {
2119 	struct btrfs_fs_info *fs_info = trans->fs_info;
2120 	struct btrfs_backref_walk_ctx ctx = {
2121 		.bytenr = bytenr,
2122 		.fs_info = fs_info,
2123 	};
2124 	int ret;
2125 
2126 	if (!btrfs_qgroup_full_accounting(fs_info))
2127 		return 0;
2128 	/*
2129 	 * We are always called in a context where we are already holding a
2130 	 * transaction handle. Often we are called when adding a data delayed
2131 	 * reference from btrfs_truncate_inode_items() (truncating or unlinking),
2132 	 * in which case we will be holding a write lock on extent buffer from a
2133 	 * subvolume tree. In this case we can't allow btrfs_find_all_roots() to
2134 	 * acquire fs_info->commit_root_sem, because that is a higher level lock
2135 	 * that must be acquired before locking any extent buffers.
2136 	 *
2137 	 * So we want btrfs_find_all_roots() to not acquire the commit_root_sem
2138 	 * but we can't pass it a non-NULL transaction handle, because otherwise
2139 	 * it would not use commit roots and would lock extent buffers, causing
2140 	 * a deadlock if it ends up trying to read lock the same extent buffer
2141 	 * that was previously write locked at btrfs_truncate_inode_items().
2142 	 *
2143 	 * So pass a NULL transaction handle to btrfs_find_all_roots() and
2144 	 * explicitly tell it to not acquire the commit_root_sem - if we are
2145 	 * holding a transaction handle we don't need its protection.
2146 	 */
2147 	ASSERT(trans != NULL);
2148 
2149 	if (test_bit(BTRFS_QGROUP_RUNTIME_BIT_NO_ACCOUNTING, &fs_info->qgroup_flags))
2150 		return 0;
2151 
2152 	ret = btrfs_find_all_roots(&ctx, true);
2153 	if (ret < 0) {
2154 		qgroup_mark_inconsistent(fs_info,
2155 				"error accounting new delayed refs extent: %d", ret);
2156 		return 0;
2157 	}
2158 
2159 	/*
2160 	 * Here we don't need to get the lock of
2161 	 * trans->transaction->delayed_refs, since inserted qrecord won't
2162 	 * be deleted, only qrecord->node may be modified (new qrecord insert)
2163 	 *
2164 	 * So modifying qrecord->old_roots is safe here
2165 	 */
2166 	qrecord->old_roots = ctx.roots;
2167 	return 0;
2168 }
2169 
2170 /*
2171  * Inform qgroup to trace one dirty extent, specified by @bytenr and
2172  * @num_bytes.
2173  * So qgroup can account it at commit trans time.
2174  *
2175  * Better encapsulated version, with memory allocation and backref walk for
2176  * commit roots.
2177  * So this can sleep.
2178  *
2179  * Return 0 if the operation is done.
2180  * Return <0 for error, like memory allocation failure or invalid parameter
2181  * (NULL trans)
2182  */
2183 int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans, u64 bytenr,
2184 			      u64 num_bytes)
2185 {
2186 	struct btrfs_fs_info *fs_info = trans->fs_info;
2187 	struct btrfs_qgroup_extent_record *record;
2188 	struct btrfs_delayed_ref_root *delayed_refs = &trans->transaction->delayed_refs;
2189 	const unsigned long index = (bytenr >> fs_info->sectorsize_bits);
2190 	int ret;
2191 
2192 	if (!btrfs_qgroup_full_accounting(fs_info) || bytenr == 0 || num_bytes == 0)
2193 		return 0;
2194 	record = kzalloc_obj(*record, GFP_NOFS);
2195 	if (!record)
2196 		return -ENOMEM;
2197 
2198 	if (xa_reserve(&delayed_refs->dirty_extents, index, GFP_NOFS)) {
2199 		kfree(record);
2200 		return -ENOMEM;
2201 	}
2202 
2203 	record->num_bytes = num_bytes;
2204 
2205 	ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record, bytenr);
2206 	if (ret) {
2207 		/* Clean up if insertion fails or item exists. */
2208 		xa_release(&delayed_refs->dirty_extents, index);
2209 		kfree(record);
2210 		return 0;
2211 	}
2212 	return btrfs_qgroup_trace_extent_post(trans, record, bytenr);
2213 }
2214 
2215 /*
2216  * Inform qgroup to trace all leaf items of data
2217  *
2218  * Return 0 for success
2219  * Return <0 for error(ENOMEM)
2220  */
2221 int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
2222 				  struct extent_buffer *eb)
2223 {
2224 	struct btrfs_fs_info *fs_info = trans->fs_info;
2225 	int nr = btrfs_header_nritems(eb);
2226 	int i, extent_type, ret;
2227 	struct btrfs_key key;
2228 	struct btrfs_file_extent_item *fi;
2229 	u64 bytenr, num_bytes;
2230 
2231 	/* We can be called directly from walk_up_proc() */
2232 	if (!btrfs_qgroup_full_accounting(fs_info))
2233 		return 0;
2234 
2235 	for (i = 0; i < nr; i++) {
2236 		btrfs_item_key_to_cpu(eb, &key, i);
2237 
2238 		if (key.type != BTRFS_EXTENT_DATA_KEY)
2239 			continue;
2240 
2241 		fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2242 		/* filter out non qgroup-accountable extents  */
2243 		extent_type = btrfs_file_extent_type(eb, fi);
2244 
2245 		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
2246 			continue;
2247 
2248 		bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
2249 		if (!bytenr)
2250 			continue;
2251 
2252 		num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
2253 
2254 		ret = btrfs_qgroup_trace_extent(trans, bytenr, num_bytes);
2255 		if (ret)
2256 			return ret;
2257 	}
2258 	cond_resched();
2259 	return 0;
2260 }
2261 
2262 /*
2263  * Walk up the tree from the bottom, freeing leaves and any interior
2264  * nodes which have had all slots visited. If a node (leaf or
2265  * interior) is freed, the node above it will have it's slot
2266  * incremented. The root node will never be freed.
2267  *
2268  * At the end of this function, we should have a path which has all
2269  * slots incremented to the next position for a search. If we need to
2270  * read a new node it will be NULL and the node above it will have the
2271  * correct slot selected for a later read.
2272  *
2273  * If we increment the root nodes slot counter past the number of
2274  * elements, 1 is returned to signal completion of the search.
2275  */
2276 static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
2277 {
2278 	int level = 0;
2279 	int nr, slot;
2280 	struct extent_buffer *eb;
2281 
2282 	if (root_level == 0)
2283 		return 1;
2284 
2285 	while (level <= root_level) {
2286 		eb = path->nodes[level];
2287 		nr = btrfs_header_nritems(eb);
2288 		path->slots[level]++;
2289 		slot = path->slots[level];
2290 		if (slot >= nr || level == 0) {
2291 			/*
2292 			 * Don't free the root -  we will detect this
2293 			 * condition after our loop and return a
2294 			 * positive value for caller to stop walking the tree.
2295 			 */
2296 			if (level != root_level) {
2297 				btrfs_tree_unlock_rw(eb, path->locks[level]);
2298 				path->locks[level] = 0;
2299 
2300 				free_extent_buffer(eb);
2301 				path->nodes[level] = NULL;
2302 				path->slots[level] = 0;
2303 			}
2304 		} else {
2305 			/*
2306 			 * We have a valid slot to walk back down
2307 			 * from. Stop here so caller can process these
2308 			 * new nodes.
2309 			 */
2310 			break;
2311 		}
2312 
2313 		level++;
2314 	}
2315 
2316 	eb = path->nodes[root_level];
2317 	if (path->slots[root_level] >= btrfs_header_nritems(eb))
2318 		return 1;
2319 
2320 	return 0;
2321 }
2322 
2323 /*
2324  * Helper function to trace a subtree tree block swap.
2325  *
2326  * The swap will happen in highest tree block, but there may be a lot of
2327  * tree blocks involved.
2328  *
2329  * For example:
2330  *  OO = Old tree blocks
2331  *  NN = New tree blocks allocated during balance
2332  *
2333  *           File tree (257)                  Reloc tree for 257
2334  * L2              OO                                NN
2335  *               /    \                            /    \
2336  * L1          OO      OO (a)                    OO      NN (a)
2337  *            / \     / \                       / \     / \
2338  * L0       OO   OO OO   OO                   OO   OO NN   NN
2339  *                  (b)  (c)                          (b)  (c)
2340  *
2341  * When calling qgroup_trace_extent_swap(), we will pass:
2342  * @src_eb = OO(a)
2343  * @dst_path = [ nodes[1] = NN(a), nodes[0] = NN(c) ]
2344  * @dst_level = 0
2345  * @root_level = 1
2346  *
2347  * In that case, qgroup_trace_extent_swap() will search from OO(a) to
2348  * reach OO(c), then mark both OO(c) and NN(c) as qgroup dirty.
2349  *
2350  * The main work of qgroup_trace_extent_swap() can be split into 3 parts:
2351  *
2352  * 1) Tree search from @src_eb
2353  *    It should acts as a simplified btrfs_search_slot().
2354  *    The key for search can be extracted from @dst_path->nodes[dst_level]
2355  *    (first key).
2356  *
2357  * 2) Mark the final tree blocks in @src_path and @dst_path qgroup dirty
2358  *    NOTE: In above case, OO(a) and NN(a) won't be marked qgroup dirty.
2359  *    They should be marked during previous (@dst_level = 1) iteration.
2360  *
2361  * 3) Mark file extents in leaves dirty
2362  *    We don't have good way to pick out new file extents only.
2363  *    So we still follow the old method by scanning all file extents in
2364  *    the leave.
2365  *
2366  * This function can free us from keeping two paths, thus later we only need
2367  * to care about how to iterate all new tree blocks in reloc tree.
2368  */
2369 static int qgroup_trace_extent_swap(struct btrfs_trans_handle* trans,
2370 				    struct extent_buffer *src_eb,
2371 				    struct btrfs_path *dst_path,
2372 				    int dst_level, int root_level,
2373 				    bool trace_leaf)
2374 {
2375 	struct btrfs_key key;
2376 	BTRFS_PATH_AUTO_FREE(src_path);
2377 	struct btrfs_fs_info *fs_info = trans->fs_info;
2378 	u32 nodesize = fs_info->nodesize;
2379 	int cur_level = root_level;
2380 	int ret;
2381 
2382 	BUG_ON(dst_level > root_level);
2383 	/* Level mismatch */
2384 	if (btrfs_header_level(src_eb) != root_level)
2385 		return -EINVAL;
2386 
2387 	src_path = btrfs_alloc_path();
2388 	if (!src_path)
2389 		return -ENOMEM;
2390 
2391 	if (dst_level)
2392 		btrfs_node_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2393 	else
2394 		btrfs_item_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2395 
2396 	/* For src_path */
2397 	refcount_inc(&src_eb->refs);
2398 	src_path->nodes[root_level] = src_eb;
2399 	src_path->slots[root_level] = dst_path->slots[root_level];
2400 	src_path->locks[root_level] = 0;
2401 
2402 	/* A simplified version of btrfs_search_slot() */
2403 	while (cur_level >= dst_level) {
2404 		struct btrfs_key src_key;
2405 		struct btrfs_key dst_key;
2406 
2407 		if (src_path->nodes[cur_level] == NULL) {
2408 			struct extent_buffer *eb;
2409 			int parent_slot;
2410 
2411 			eb = src_path->nodes[cur_level + 1];
2412 			parent_slot = src_path->slots[cur_level + 1];
2413 
2414 			eb = btrfs_read_node_slot(eb, parent_slot);
2415 			if (IS_ERR(eb))
2416 				return PTR_ERR(eb);
2417 
2418 			src_path->nodes[cur_level] = eb;
2419 
2420 			btrfs_tree_read_lock(eb);
2421 			src_path->locks[cur_level] = BTRFS_READ_LOCK;
2422 		}
2423 
2424 		src_path->slots[cur_level] = dst_path->slots[cur_level];
2425 		if (cur_level) {
2426 			btrfs_node_key_to_cpu(dst_path->nodes[cur_level],
2427 					&dst_key, dst_path->slots[cur_level]);
2428 			btrfs_node_key_to_cpu(src_path->nodes[cur_level],
2429 					&src_key, src_path->slots[cur_level]);
2430 		} else {
2431 			btrfs_item_key_to_cpu(dst_path->nodes[cur_level],
2432 					&dst_key, dst_path->slots[cur_level]);
2433 			btrfs_item_key_to_cpu(src_path->nodes[cur_level],
2434 					&src_key, src_path->slots[cur_level]);
2435 		}
2436 		/* Content mismatch, something went wrong */
2437 		if (btrfs_comp_cpu_keys(&dst_key, &src_key))
2438 			return -ENOENT;
2439 		cur_level--;
2440 	}
2441 
2442 	/*
2443 	 * Now both @dst_path and @src_path have been populated, record the tree
2444 	 * blocks for qgroup accounting.
2445 	 */
2446 	ret = btrfs_qgroup_trace_extent(trans, src_path->nodes[dst_level]->start,
2447 					nodesize);
2448 	if (ret < 0)
2449 		return ret;
2450 	ret = btrfs_qgroup_trace_extent(trans, dst_path->nodes[dst_level]->start,
2451 					nodesize);
2452 	if (ret < 0)
2453 		return ret;
2454 
2455 	/* Record leaf file extents */
2456 	if (dst_level == 0 && trace_leaf) {
2457 		ret = btrfs_qgroup_trace_leaf_items(trans, src_path->nodes[0]);
2458 		if (ret < 0)
2459 			return ret;
2460 		ret = btrfs_qgroup_trace_leaf_items(trans, dst_path->nodes[0]);
2461 	}
2462 
2463 	return ret;
2464 }
2465 
2466 /*
2467  * Helper function to do recursive generation-aware depth-first search, to
2468  * locate all new tree blocks in a subtree of reloc tree.
2469  *
2470  * E.g. (OO = Old tree blocks, NN = New tree blocks, whose gen == last_snapshot)
2471  *         reloc tree
2472  * L2         NN (a)
2473  *          /    \
2474  * L1    OO        NN (b)
2475  *      /  \      /  \
2476  * L0  OO  OO    OO  NN
2477  *               (c) (d)
2478  * If we pass:
2479  * @dst_path = [ nodes[1] = NN(b), nodes[0] = NULL ],
2480  * @cur_level = 1
2481  * @root_level = 1
2482  *
2483  * We will iterate through tree blocks NN(b), NN(d) and info qgroup to trace
2484  * above tree blocks along with their counter parts in file tree.
2485  * While during search, old tree blocks OO(c) will be skipped as tree block swap
2486  * won't affect OO(c).
2487  */
2488 static int qgroup_trace_new_subtree_blocks(struct btrfs_trans_handle* trans,
2489 					   struct extent_buffer *src_eb,
2490 					   struct btrfs_path *dst_path,
2491 					   int cur_level, int root_level,
2492 					   u64 last_snapshot, bool trace_leaf)
2493 {
2494 	struct btrfs_fs_info *fs_info = trans->fs_info;
2495 	struct extent_buffer *eb;
2496 	bool need_cleanup = false;
2497 	int ret = 0;
2498 	int i;
2499 
2500 	/* Level sanity check */
2501 	if (unlikely(cur_level < 0 || cur_level >= BTRFS_MAX_LEVEL ||
2502 		     root_level < 0 || root_level >= BTRFS_MAX_LEVEL ||
2503 		     root_level < cur_level)) {
2504 		btrfs_err_rl(fs_info,
2505 			"%s: bad levels, cur_level=%d root_level=%d",
2506 			__func__, cur_level, root_level);
2507 		return -EUCLEAN;
2508 	}
2509 
2510 	/* Read the tree block if needed */
2511 	if (dst_path->nodes[cur_level] == NULL) {
2512 		int parent_slot;
2513 		u64 child_gen;
2514 
2515 		/*
2516 		 * dst_path->nodes[root_level] must be initialized before
2517 		 * calling this function.
2518 		 */
2519 		if (unlikely(cur_level == root_level)) {
2520 			btrfs_err_rl(fs_info,
2521 	"%s: dst_path->nodes[%d] not initialized, root_level=%d cur_level=%d",
2522 				__func__, root_level, root_level, cur_level);
2523 			return -EUCLEAN;
2524 		}
2525 
2526 		/*
2527 		 * We need to get child blockptr/gen from parent before we can
2528 		 * read it.
2529 		  */
2530 		eb = dst_path->nodes[cur_level + 1];
2531 		parent_slot = dst_path->slots[cur_level + 1];
2532 		child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2533 
2534 		/* This node is old, no need to trace */
2535 		if (child_gen < last_snapshot)
2536 			return ret;
2537 
2538 		eb = btrfs_read_node_slot(eb, parent_slot);
2539 		if (IS_ERR(eb))
2540 			return PTR_ERR(eb);
2541 
2542 		dst_path->nodes[cur_level] = eb;
2543 		dst_path->slots[cur_level] = 0;
2544 
2545 		btrfs_tree_read_lock(eb);
2546 		dst_path->locks[cur_level] = BTRFS_READ_LOCK;
2547 		need_cleanup = true;
2548 	}
2549 
2550 	/* Now record this tree block and its counter part for qgroups */
2551 	ret = qgroup_trace_extent_swap(trans, src_eb, dst_path, cur_level,
2552 				       root_level, trace_leaf);
2553 	if (ret < 0)
2554 		goto cleanup;
2555 
2556 	eb = dst_path->nodes[cur_level];
2557 
2558 	if (cur_level > 0) {
2559 		/* Iterate all child tree blocks */
2560 		for (i = 0; i < btrfs_header_nritems(eb); i++) {
2561 			/* Skip old tree blocks as they won't be swapped */
2562 			if (btrfs_node_ptr_generation(eb, i) < last_snapshot)
2563 				continue;
2564 			dst_path->slots[cur_level] = i;
2565 
2566 			/* Recursive call (at most 7 times) */
2567 			ret = qgroup_trace_new_subtree_blocks(trans, src_eb,
2568 					dst_path, cur_level - 1, root_level,
2569 					last_snapshot, trace_leaf);
2570 			if (ret < 0)
2571 				goto cleanup;
2572 		}
2573 	}
2574 
2575 cleanup:
2576 	if (need_cleanup) {
2577 		/* Clean up */
2578 		btrfs_tree_unlock_rw(dst_path->nodes[cur_level],
2579 				     dst_path->locks[cur_level]);
2580 		free_extent_buffer(dst_path->nodes[cur_level]);
2581 		dst_path->nodes[cur_level] = NULL;
2582 		dst_path->slots[cur_level] = 0;
2583 		dst_path->locks[cur_level] = 0;
2584 	}
2585 
2586 	return ret;
2587 }
2588 
2589 static int qgroup_trace_subtree_swap(struct btrfs_trans_handle *trans,
2590 				struct extent_buffer *src_eb,
2591 				struct extent_buffer *dst_eb,
2592 				u64 last_snapshot, bool trace_leaf)
2593 {
2594 	struct btrfs_fs_info *fs_info = trans->fs_info;
2595 	struct btrfs_path *dst_path = NULL;
2596 	int level;
2597 	int ret;
2598 
2599 	if (!btrfs_qgroup_full_accounting(fs_info))
2600 		return 0;
2601 
2602 	/* Wrong parameter order */
2603 	if (unlikely(btrfs_header_generation(src_eb) > btrfs_header_generation(dst_eb))) {
2604 		btrfs_err_rl(fs_info,
2605 		"%s: bad parameter order, src_gen=%llu dst_gen=%llu", __func__,
2606 			     btrfs_header_generation(src_eb),
2607 			     btrfs_header_generation(dst_eb));
2608 		return -EUCLEAN;
2609 	}
2610 
2611 	if (unlikely(!extent_buffer_uptodate(src_eb) || !extent_buffer_uptodate(dst_eb))) {
2612 		ret = -EIO;
2613 		goto out;
2614 	}
2615 
2616 	level = btrfs_header_level(dst_eb);
2617 	dst_path = btrfs_alloc_path();
2618 	if (!dst_path) {
2619 		ret = -ENOMEM;
2620 		goto out;
2621 	}
2622 	/* For dst_path */
2623 	refcount_inc(&dst_eb->refs);
2624 	dst_path->nodes[level] = dst_eb;
2625 	dst_path->slots[level] = 0;
2626 	dst_path->locks[level] = 0;
2627 
2628 	/* Do the generation aware breadth-first search */
2629 	ret = qgroup_trace_new_subtree_blocks(trans, src_eb, dst_path, level,
2630 					      level, last_snapshot, trace_leaf);
2631 	if (ret < 0)
2632 		goto out;
2633 	ret = 0;
2634 
2635 out:
2636 	btrfs_free_path(dst_path);
2637 	if (ret < 0)
2638 		qgroup_mark_inconsistent(fs_info, "%s error: %d", __func__, ret);
2639 	return ret;
2640 }
2641 
2642 /*
2643  * Inform qgroup to trace a whole subtree, including all its child tree
2644  * blocks and data.
2645  * The root tree block is specified by @root_eb.
2646  *
2647  * Normally used by relocation(tree block swap) and subvolume deletion.
2648  *
2649  * Return 0 for success
2650  * Return <0 for error(ENOMEM or tree search error)
2651  */
2652 int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
2653 			       struct extent_buffer *root_eb,
2654 			       u64 root_gen, int root_level)
2655 {
2656 	struct btrfs_fs_info *fs_info = trans->fs_info;
2657 	int ret = 0;
2658 	int level;
2659 	u8 drop_subptree_thres;
2660 	struct extent_buffer *eb = root_eb;
2661 	BTRFS_PATH_AUTO_FREE(path);
2662 
2663 	ASSERT(0 <= root_level && root_level < BTRFS_MAX_LEVEL);
2664 	ASSERT(root_eb != NULL);
2665 
2666 	if (!btrfs_qgroup_full_accounting(fs_info))
2667 		return 0;
2668 
2669 	spin_lock(&fs_info->qgroup_lock);
2670 	drop_subptree_thres = fs_info->qgroup_drop_subtree_thres;
2671 	spin_unlock(&fs_info->qgroup_lock);
2672 
2673 	/*
2674 	 * This function only gets called for snapshot drop, if we hit a high
2675 	 * node here, it means we are going to change ownership for quite a lot
2676 	 * of extents, which will greatly slow down btrfs_commit_transaction().
2677 	 *
2678 	 * So here if we find a high tree here, we just skip the accounting and
2679 	 * mark qgroup inconsistent.
2680 	 */
2681 	if (root_level >= drop_subptree_thres) {
2682 		qgroup_mark_inconsistent(fs_info, "subtree level reached threshold");
2683 		return 0;
2684 	}
2685 
2686 	if (!extent_buffer_uptodate(root_eb)) {
2687 		struct btrfs_tree_parent_check check = {
2688 			.transid = root_gen,
2689 			.level = root_level
2690 		};
2691 
2692 		ret = btrfs_read_extent_buffer(root_eb, &check);
2693 		if (ret)
2694 			return ret;
2695 	}
2696 
2697 	if (root_level == 0)
2698 		return btrfs_qgroup_trace_leaf_items(trans, root_eb);
2699 
2700 	path = btrfs_alloc_path();
2701 	if (!path)
2702 		return -ENOMEM;
2703 
2704 	/*
2705 	 * Walk down the tree.  Missing extent blocks are filled in as
2706 	 * we go. Metadata is accounted every time we read a new
2707 	 * extent block.
2708 	 *
2709 	 * When we reach a leaf, we account for file extent items in it,
2710 	 * walk back up the tree (adjusting slot pointers as we go)
2711 	 * and restart the search process.
2712 	 */
2713 	refcount_inc(&root_eb->refs);	/* For path */
2714 	path->nodes[root_level] = root_eb;
2715 	path->slots[root_level] = 0;
2716 	path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
2717 walk_down:
2718 	level = root_level;
2719 	while (level >= 0) {
2720 		if (path->nodes[level] == NULL) {
2721 			int parent_slot;
2722 			u64 child_bytenr;
2723 
2724 			/*
2725 			 * We need to get child blockptr from parent before we
2726 			 * can read it.
2727 			  */
2728 			eb = path->nodes[level + 1];
2729 			parent_slot = path->slots[level + 1];
2730 			child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2731 
2732 			eb = btrfs_read_node_slot(eb, parent_slot);
2733 			if (IS_ERR(eb))
2734 				return PTR_ERR(eb);
2735 
2736 			path->nodes[level] = eb;
2737 			path->slots[level] = 0;
2738 
2739 			btrfs_tree_read_lock(eb);
2740 			path->locks[level] = BTRFS_READ_LOCK;
2741 
2742 			ret = btrfs_qgroup_trace_extent(trans, child_bytenr,
2743 							fs_info->nodesize);
2744 			if (ret)
2745 				return ret;
2746 		}
2747 
2748 		if (level == 0) {
2749 			ret = btrfs_qgroup_trace_leaf_items(trans,
2750 							    path->nodes[level]);
2751 			if (ret)
2752 				return ret;
2753 
2754 			/* Nonzero return here means we completed our search */
2755 			ret = adjust_slots_upwards(path, root_level);
2756 			if (ret)
2757 				break;
2758 
2759 			/* Restart search with new slots */
2760 			goto walk_down;
2761 		}
2762 
2763 		level--;
2764 	}
2765 
2766 	return 0;
2767 }
2768 
2769 void btrfs_qgroup_check_tree_drop(struct btrfs_fs_info *fs_info, u64 rootid, u8 level)
2770 {
2771 	u8 drop_subtree_thres;
2772 
2773 	if (btrfs_qgroup_mode(fs_info) != BTRFS_QGROUP_MODE_FULL)
2774 		return;
2775 
2776 	if (!btrfs_is_fstree(rootid))
2777 		return;
2778 
2779 	spin_lock(&fs_info->qgroup_lock);
2780 	drop_subtree_thres = fs_info->qgroup_drop_subtree_thres;
2781 	spin_unlock(&fs_info->qgroup_lock);
2782 
2783 	if (level >= drop_subtree_thres)
2784 		qgroup_mark_inconsistent(fs_info, "subtree level reached threshold");
2785 }
2786 
2787 static void qgroup_iterator_nested_add(struct list_head *head, struct btrfs_qgroup *qgroup)
2788 {
2789 	if (!list_empty(&qgroup->nested_iterator))
2790 		return;
2791 
2792 	list_add_tail(&qgroup->nested_iterator, head);
2793 }
2794 
2795 static void qgroup_iterator_nested_clean(struct list_head *head)
2796 {
2797 	while (!list_empty(head)) {
2798 		struct btrfs_qgroup *qgroup;
2799 
2800 		qgroup = list_first_entry(head, struct btrfs_qgroup, nested_iterator);
2801 		list_del_init(&qgroup->nested_iterator);
2802 	}
2803 }
2804 
2805 /*
2806  * Walk all of the roots that points to the bytenr and adjust their refcnts.
2807  */
2808 static void qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
2809 				 struct ulist *roots, struct list_head *qgroups,
2810 				 u64 seq, bool update_old)
2811 {
2812 	struct ulist_node *unode;
2813 	struct ulist_iterator uiter;
2814 	struct btrfs_qgroup *qg;
2815 
2816 	if (!roots)
2817 		return;
2818 	ULIST_ITER_INIT(&uiter);
2819 	while ((unode = ulist_next(roots, &uiter))) {
2820 		LIST_HEAD(tmp);
2821 
2822 		qg = find_qgroup_rb(fs_info, unode->val);
2823 		if (!qg)
2824 			continue;
2825 
2826 		qgroup_iterator_nested_add(qgroups, qg);
2827 		qgroup_iterator_add(&tmp, qg);
2828 		list_for_each_entry(qg, &tmp, iterator) {
2829 			struct btrfs_qgroup_list *glist;
2830 
2831 			if (update_old)
2832 				btrfs_qgroup_update_old_refcnt(qg, seq, 1);
2833 			else
2834 				btrfs_qgroup_update_new_refcnt(qg, seq, 1);
2835 
2836 			list_for_each_entry(glist, &qg->groups, next_group) {
2837 				qgroup_iterator_nested_add(qgroups, glist->group);
2838 				qgroup_iterator_add(&tmp, glist->group);
2839 			}
2840 		}
2841 		qgroup_iterator_clean(&tmp);
2842 	}
2843 }
2844 
2845 /*
2846  * Update qgroup rfer/excl counters.
2847  * Rfer update is easy, codes can explain themselves.
2848  *
2849  * Excl update is tricky, the update is split into 2 parts.
2850  * Part 1: Possible exclusive <-> sharing detect:
2851  *	|	A	|	!A	|
2852  *  -------------------------------------
2853  *  B	|	*	|	-	|
2854  *  -------------------------------------
2855  *  !B	|	+	|	**	|
2856  *  -------------------------------------
2857  *
2858  * Conditions:
2859  * A:	cur_old_roots < nr_old_roots	(not exclusive before)
2860  * !A:	cur_old_roots == nr_old_roots	(possible exclusive before)
2861  * B:	cur_new_roots < nr_new_roots	(not exclusive now)
2862  * !B:	cur_new_roots == nr_new_roots	(possible exclusive now)
2863  *
2864  * Results:
2865  * +: Possible sharing -> exclusive	-: Possible exclusive -> sharing
2866  * *: Definitely not changed.		**: Possible unchanged.
2867  *
2868  * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
2869  *
2870  * To make the logic clear, we first use condition A and B to split
2871  * combination into 4 results.
2872  *
2873  * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
2874  * only on variant maybe 0.
2875  *
2876  * Lastly, check result **, since there are 2 variants maybe 0, split them
2877  * again(2x2).
2878  * But this time we don't need to consider other things, the codes and logic
2879  * is easy to understand now.
2880  */
2881 static void qgroup_update_counters(struct btrfs_fs_info *fs_info,
2882 				   struct list_head *qgroups, u64 nr_old_roots,
2883 				   u64 nr_new_roots, u64 num_bytes, u64 seq)
2884 {
2885 	struct btrfs_qgroup *qg;
2886 
2887 	list_for_each_entry(qg, qgroups, nested_iterator) {
2888 		u64 cur_new_count, cur_old_count;
2889 		bool dirty = false;
2890 
2891 		cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
2892 		cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);
2893 
2894 		trace_btrfs_qgroup_update_counters(fs_info, qg, cur_old_count,
2895 						   cur_new_count);
2896 
2897 		/* Rfer update part */
2898 		if (cur_old_count == 0 && cur_new_count > 0) {
2899 			qg->rfer += num_bytes;
2900 			qg->rfer_cmpr += num_bytes;
2901 			dirty = true;
2902 		}
2903 		if (cur_old_count > 0 && cur_new_count == 0) {
2904 			qg->rfer -= num_bytes;
2905 			qg->rfer_cmpr -= num_bytes;
2906 			dirty = true;
2907 		}
2908 
2909 		/* Excl update part */
2910 		/* Exclusive/none -> shared case */
2911 		if (cur_old_count == nr_old_roots &&
2912 		    cur_new_count < nr_new_roots) {
2913 			/* Exclusive -> shared */
2914 			if (cur_old_count != 0) {
2915 				qg->excl -= num_bytes;
2916 				qg->excl_cmpr -= num_bytes;
2917 				dirty = true;
2918 			}
2919 		}
2920 
2921 		/* Shared -> exclusive/none case */
2922 		if (cur_old_count < nr_old_roots &&
2923 		    cur_new_count == nr_new_roots) {
2924 			/* Shared->exclusive */
2925 			if (cur_new_count != 0) {
2926 				qg->excl += num_bytes;
2927 				qg->excl_cmpr += num_bytes;
2928 				dirty = true;
2929 			}
2930 		}
2931 
2932 		/* Exclusive/none -> exclusive/none case */
2933 		if (cur_old_count == nr_old_roots &&
2934 		    cur_new_count == nr_new_roots) {
2935 			if (cur_old_count == 0) {
2936 				/* None -> exclusive/none */
2937 
2938 				if (cur_new_count != 0) {
2939 					/* None -> exclusive */
2940 					qg->excl += num_bytes;
2941 					qg->excl_cmpr += num_bytes;
2942 					dirty = true;
2943 				}
2944 				/* None -> none, nothing changed */
2945 			} else {
2946 				/* Exclusive -> exclusive/none */
2947 
2948 				if (cur_new_count == 0) {
2949 					/* Exclusive -> none */
2950 					qg->excl -= num_bytes;
2951 					qg->excl_cmpr -= num_bytes;
2952 					dirty = true;
2953 				}
2954 				/* Exclusive -> exclusive, nothing changed */
2955 			}
2956 		}
2957 
2958 		if (dirty)
2959 			qgroup_dirty(fs_info, qg);
2960 	}
2961 }
2962 
2963 /*
2964  * Check if the @roots potentially is a list of fs tree roots
2965  *
2966  * Return 0 for definitely not a fs/subvol tree roots ulist
2967  * Return 1 for possible fs/subvol tree roots in the list (considering an empty
2968  *          one as well)
2969  */
2970 static int maybe_fs_roots(struct ulist *roots)
2971 {
2972 	struct ulist_node *unode;
2973 	struct ulist_iterator uiter;
2974 
2975 	/* Empty one, still possible for fs roots */
2976 	if (!roots || roots->nnodes == 0)
2977 		return 1;
2978 
2979 	ULIST_ITER_INIT(&uiter);
2980 	unode = ulist_next(roots, &uiter);
2981 	if (!unode)
2982 		return 1;
2983 
2984 	/*
2985 	 * If it contains fs tree roots, then it must belong to fs/subvol
2986 	 * trees.
2987 	 * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
2988 	 */
2989 	return btrfs_is_fstree(unode->val);
2990 }
2991 
2992 int btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans, u64 bytenr,
2993 				u64 num_bytes, struct ulist *old_roots,
2994 				struct ulist *new_roots)
2995 {
2996 	struct btrfs_fs_info *fs_info = trans->fs_info;
2997 	LIST_HEAD(qgroups);
2998 	u64 seq;
2999 	u64 nr_new_roots = 0;
3000 	u64 nr_old_roots = 0;
3001 	int ret = 0;
3002 
3003 	/*
3004 	 * If quotas get disabled meanwhile, the resources need to be freed and
3005 	 * we can't just exit here.
3006 	 */
3007 	if (!btrfs_qgroup_full_accounting(fs_info) ||
3008 	    test_bit(BTRFS_QGROUP_RUNTIME_BIT_NO_ACCOUNTING, &fs_info->qgroup_flags))
3009 		goto out_free;
3010 
3011 	if (new_roots) {
3012 		if (!maybe_fs_roots(new_roots))
3013 			goto out_free;
3014 		nr_new_roots = new_roots->nnodes;
3015 	}
3016 	if (old_roots) {
3017 		if (!maybe_fs_roots(old_roots))
3018 			goto out_free;
3019 		nr_old_roots = old_roots->nnodes;
3020 	}
3021 
3022 	/* Quick exit, either not fs tree roots, or won't affect any qgroup */
3023 	if (nr_old_roots == 0 && nr_new_roots == 0)
3024 		goto out_free;
3025 
3026 	trace_btrfs_qgroup_account_extent(fs_info, trans->transid, bytenr,
3027 					num_bytes, nr_old_roots, nr_new_roots);
3028 
3029 	mutex_lock(&fs_info->qgroup_rescan_lock);
3030 	if (test_bit(BTRFS_QGROUP_STATUS_BIT_RESCAN, &fs_info->qgroup_flags)) {
3031 		if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
3032 			mutex_unlock(&fs_info->qgroup_rescan_lock);
3033 			ret = 0;
3034 			goto out_free;
3035 		}
3036 	}
3037 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3038 
3039 	spin_lock(&fs_info->qgroup_lock);
3040 	seq = fs_info->qgroup_seq;
3041 
3042 	/* Update old refcnts using old_roots */
3043 	qgroup_update_refcnt(fs_info, old_roots, &qgroups, seq, true);
3044 
3045 	/* Update new refcnts using new_roots */
3046 	qgroup_update_refcnt(fs_info, new_roots, &qgroups, seq, false);
3047 
3048 	qgroup_update_counters(fs_info, &qgroups, nr_old_roots, nr_new_roots,
3049 			       num_bytes, seq);
3050 
3051 	/*
3052 	 * We're done using the iterator, release all its qgroups while holding
3053 	 * fs_info->qgroup_lock so that we don't race with btrfs_remove_qgroup()
3054 	 * and trigger use-after-free accesses to qgroups.
3055 	 */
3056 	qgroup_iterator_nested_clean(&qgroups);
3057 
3058 	/*
3059 	 * Bump qgroup_seq to avoid seq overlap
3060 	 */
3061 	fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
3062 	spin_unlock(&fs_info->qgroup_lock);
3063 out_free:
3064 	ulist_free(old_roots);
3065 	ulist_free(new_roots);
3066 	return ret;
3067 }
3068 
3069 int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans)
3070 {
3071 	struct btrfs_fs_info *fs_info = trans->fs_info;
3072 	struct btrfs_qgroup_extent_record *record;
3073 	struct btrfs_delayed_ref_root *delayed_refs;
3074 	struct ulist *new_roots = NULL;
3075 	unsigned long index;
3076 	u64 num_dirty_extents = 0;
3077 	u64 qgroup_to_skip;
3078 	int ret = 0;
3079 
3080 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE)
3081 		return 0;
3082 
3083 	delayed_refs = &trans->transaction->delayed_refs;
3084 	qgroup_to_skip = delayed_refs->qgroup_to_skip;
3085 	xa_for_each(&delayed_refs->dirty_extents, index, record) {
3086 		const u64 bytenr = (((u64)index) << fs_info->sectorsize_bits);
3087 
3088 		num_dirty_extents++;
3089 		trace_btrfs_qgroup_account_extents(fs_info, record, bytenr);
3090 
3091 		if (!ret && !test_bit(BTRFS_QGROUP_RUNTIME_BIT_NO_ACCOUNTING,
3092 				      &fs_info->qgroup_flags)) {
3093 			struct btrfs_backref_walk_ctx ctx = { 0 };
3094 
3095 			ctx.bytenr = bytenr;
3096 			ctx.fs_info = fs_info;
3097 
3098 			/*
3099 			 * Old roots should be searched when inserting qgroup
3100 			 * extent record.
3101 			 *
3102 			 * But for INCONSISTENT (NO_ACCOUNTING) -> rescan case,
3103 			 * we may have some record inserted during
3104 			 * NO_ACCOUNTING (thus no old_roots populated), but
3105 			 * later we start rescan, which clears NO_ACCOUNTING,
3106 			 * leaving some inserted records without old_roots
3107 			 * populated.
3108 			 *
3109 			 * Those cases are rare and should not cause too much
3110 			 * time spent during commit_transaction().
3111 			 */
3112 			if (!record->old_roots) {
3113 				/* Search commit root to find old_roots */
3114 				ret = btrfs_find_all_roots(&ctx, false);
3115 				if (ret < 0)
3116 					goto cleanup;
3117 				record->old_roots = ctx.roots;
3118 				ctx.roots = NULL;
3119 			}
3120 
3121 			/*
3122 			 * Use BTRFS_SEQ_LAST as time_seq to do special search,
3123 			 * which doesn't lock tree or delayed_refs and search
3124 			 * current root. It's safe inside commit_transaction().
3125 			 */
3126 			ctx.trans = trans;
3127 			ctx.time_seq = BTRFS_SEQ_LAST;
3128 			ret = btrfs_find_all_roots(&ctx, false);
3129 			if (ret < 0)
3130 				goto cleanup;
3131 			new_roots = ctx.roots;
3132 			if (qgroup_to_skip) {
3133 				ulist_del(new_roots, qgroup_to_skip, 0);
3134 				ulist_del(record->old_roots, qgroup_to_skip,
3135 					  0);
3136 			}
3137 			ret = btrfs_qgroup_account_extent(trans, bytenr,
3138 							  record->num_bytes,
3139 							  record->old_roots,
3140 							  new_roots);
3141 			record->old_roots = NULL;
3142 			new_roots = NULL;
3143 		}
3144 		/* Free the reserved data space */
3145 		btrfs_qgroup_free_refroot(fs_info,
3146 				record->data_rsv_refroot,
3147 				record->data_rsv,
3148 				BTRFS_QGROUP_RSV_DATA);
3149 cleanup:
3150 		ulist_free(record->old_roots);
3151 		ulist_free(new_roots);
3152 		new_roots = NULL;
3153 		xa_erase(&delayed_refs->dirty_extents, index);
3154 		kfree(record);
3155 
3156 	}
3157 	trace_btrfs_qgroup_num_dirty_extents(fs_info, trans->transid, num_dirty_extents);
3158 	return ret;
3159 }
3160 
3161 /*
3162  * Writes all changed qgroups to disk.
3163  * Called by the transaction commit path and the qgroup assign ioctl.
3164  */
3165 int btrfs_run_qgroups(struct btrfs_trans_handle *trans)
3166 {
3167 	struct btrfs_fs_info *fs_info = trans->fs_info;
3168 	int ret = 0;
3169 
3170 	/*
3171 	 * In case we are called from the qgroup assign ioctl, assert that we
3172 	 * are holding the qgroup_ioctl_lock, otherwise we can race with a quota
3173 	 * disable operation (ioctl) and access a freed quota root.
3174 	 */
3175 	if (trans->transaction->state != TRANS_STATE_COMMIT_DOING)
3176 		lockdep_assert_held(&fs_info->qgroup_ioctl_lock);
3177 
3178 	if (!fs_info->quota_root)
3179 		return ret;
3180 
3181 	spin_lock(&fs_info->qgroup_lock);
3182 	while (!list_empty(&fs_info->dirty_qgroups)) {
3183 		struct btrfs_qgroup *qgroup;
3184 		qgroup = list_first_entry(&fs_info->dirty_qgroups,
3185 					  struct btrfs_qgroup, dirty);
3186 		list_del_init(&qgroup->dirty);
3187 		spin_unlock(&fs_info->qgroup_lock);
3188 		ret = update_qgroup_info_item(trans, qgroup);
3189 		if (ret)
3190 			qgroup_mark_inconsistent(fs_info,
3191 						 "qgroup info item update error %d", ret);
3192 		ret = update_qgroup_limit_item(trans, qgroup);
3193 		if (ret)
3194 			qgroup_mark_inconsistent(fs_info,
3195 						 "qgroup limit item update error %d", ret);
3196 		spin_lock(&fs_info->qgroup_lock);
3197 	}
3198 	assign_bit(BTRFS_QGROUP_STATUS_BIT_ON, &fs_info->qgroup_flags,
3199 		   btrfs_qgroup_enabled(fs_info));
3200 	spin_unlock(&fs_info->qgroup_lock);
3201 
3202 	ret = update_qgroup_status_item(trans);
3203 	if (ret)
3204 		qgroup_mark_inconsistent(fs_info,
3205 					 "qgroup status item update error %d", ret);
3206 
3207 	return ret;
3208 }
3209 
3210 int btrfs_qgroup_check_inherit(struct btrfs_fs_info *fs_info,
3211 			       struct btrfs_qgroup_inherit *inherit,
3212 			       size_t size)
3213 {
3214 	if (inherit->flags & ~BTRFS_QGROUP_INHERIT_FLAGS_SUPP)
3215 		return -EOPNOTSUPP;
3216 	if (size < sizeof(*inherit) || size > PAGE_SIZE)
3217 		return -EINVAL;
3218 
3219 	/*
3220 	 * In the past we allowed btrfs_qgroup_inherit to specify to copy
3221 	 * rfer/excl numbers directly from other qgroups.  This behavior has
3222 	 * been disabled in userspace for a very long time, but here we should
3223 	 * also disable it in kernel, as this behavior is known to mark qgroup
3224 	 * inconsistent, and a rescan would wipe out the changes anyway.
3225 	 *
3226 	 * Reject any btrfs_qgroup_inherit with num_ref_copies or num_excl_copies.
3227 	 */
3228 	if (inherit->num_ref_copies > 0 || inherit->num_excl_copies > 0)
3229 		return -EINVAL;
3230 
3231 	if (size != struct_size(inherit, qgroups, inherit->num_qgroups))
3232 		return -EINVAL;
3233 
3234 	/*
3235 	 * Skip the inherit source qgroups check if qgroup is not enabled.
3236 	 * Qgroup can still be later enabled causing problems, but in that case
3237 	 * btrfs_qgroup_inherit() would just ignore those invalid ones.
3238 	 */
3239 	if (!btrfs_qgroup_enabled(fs_info))
3240 		return 0;
3241 
3242 	/*
3243 	 * Now check all the remaining qgroups, they should all:
3244 	 *
3245 	 * - Exist
3246 	 * - Be higher level qgroups.
3247 	 */
3248 	for (int i = 0; i < inherit->num_qgroups; i++) {
3249 		struct btrfs_qgroup *qgroup;
3250 		u64 qgroupid = inherit->qgroups[i];
3251 
3252 		if (btrfs_qgroup_level(qgroupid) == 0)
3253 			return -EINVAL;
3254 
3255 		spin_lock(&fs_info->qgroup_lock);
3256 		qgroup = find_qgroup_rb(fs_info, qgroupid);
3257 		if (!qgroup) {
3258 			spin_unlock(&fs_info->qgroup_lock);
3259 			return -ENOENT;
3260 		}
3261 		spin_unlock(&fs_info->qgroup_lock);
3262 	}
3263 	return 0;
3264 }
3265 
3266 static int qgroup_auto_inherit(struct btrfs_fs_info *fs_info,
3267 			       u64 inode_rootid,
3268 			       struct btrfs_qgroup_inherit **inherit)
3269 {
3270 	int i = 0;
3271 	u64 num_qgroups = 0;
3272 	struct btrfs_qgroup *inode_qg;
3273 	struct btrfs_qgroup_list *qg_list;
3274 	struct btrfs_qgroup_inherit *res;
3275 	size_t struct_sz;
3276 	u64 *qgids;
3277 
3278 	if (*inherit)
3279 		return -EEXIST;
3280 
3281 	inode_qg = find_qgroup_rb(fs_info, inode_rootid);
3282 	if (!inode_qg)
3283 		return -ENOENT;
3284 
3285 	num_qgroups = list_count_nodes(&inode_qg->groups);
3286 
3287 	if (!num_qgroups)
3288 		return 0;
3289 
3290 	struct_sz = struct_size(res, qgroups, num_qgroups);
3291 	if (struct_sz == SIZE_MAX)
3292 		return -ERANGE;
3293 
3294 	res = kzalloc(struct_sz, GFP_NOFS);
3295 	if (!res)
3296 		return -ENOMEM;
3297 	res->num_qgroups = num_qgroups;
3298 	qgids = res->qgroups;
3299 
3300 	list_for_each_entry(qg_list, &inode_qg->groups, next_group)
3301 		qgids[i++] = qg_list->group->qgroupid;
3302 
3303 	*inherit = res;
3304 	return 0;
3305 }
3306 
3307 /*
3308  * Check if we can skip rescan when inheriting qgroups.  If @src has a single
3309  * @parent, and that @parent is owning all its bytes exclusively, we can skip
3310  * the full rescan, by just adding nodesize to the @parent's excl/rfer.
3311  *
3312  * Return <0 for fatal errors (like srcid/parentid has no qgroup).
3313  * Return 0 if a quick inherit is done.
3314  * Return >0 if a quick inherit is not possible, and a full rescan is needed.
3315  */
3316 static int qgroup_snapshot_quick_inherit(struct btrfs_fs_info *fs_info,
3317 					 u64 srcid, u64 parentid)
3318 {
3319 	struct btrfs_qgroup *src;
3320 	struct btrfs_qgroup *parent;
3321 	struct btrfs_qgroup *qgroup;
3322 	struct btrfs_qgroup_list *list;
3323 	LIST_HEAD(qgroup_list);
3324 	const u32 nodesize = fs_info->nodesize;
3325 	int nr_parents = 0;
3326 
3327 	if (btrfs_qgroup_mode(fs_info) != BTRFS_QGROUP_MODE_FULL)
3328 		return 0;
3329 
3330 	src = find_qgroup_rb(fs_info, srcid);
3331 	if (!src)
3332 		return -ENOENT;
3333 	parent = find_qgroup_rb(fs_info, parentid);
3334 	if (!parent)
3335 		return -ENOENT;
3336 
3337 	/*
3338 	 * Source has no parent qgroup, but our new qgroup would have one.
3339 	 * Qgroup numbers would become inconsistent.
3340 	 */
3341 	if (list_empty(&src->groups))
3342 		return 1;
3343 
3344 	list_for_each_entry(list, &src->groups, next_group) {
3345 		/* The parent is not the same, quick update is not possible. */
3346 		if (list->group->qgroupid != parentid)
3347 			return 1;
3348 		nr_parents++;
3349 		/*
3350 		 * More than one parent qgroup, we can't be sure about accounting
3351 		 * consistency.
3352 		 */
3353 		if (nr_parents > 1)
3354 			return 1;
3355 	}
3356 
3357 	/*
3358 	 * The parent is not exclusively owning all its bytes.  We're not sure
3359 	 * if the source has any bytes not fully owned by the parent.
3360 	 */
3361 	if (parent->excl != parent->rfer)
3362 		return 1;
3363 
3364 	qgroup_iterator_add(&qgroup_list, parent);
3365 	list_for_each_entry(qgroup, &qgroup_list, iterator) {
3366 		qgroup->rfer += nodesize;
3367 		qgroup->rfer_cmpr += nodesize;
3368 		qgroup->excl += nodesize;
3369 		qgroup->excl_cmpr += nodesize;
3370 		qgroup_dirty(fs_info, qgroup);
3371 
3372 		/* Append parent qgroups to @qgroup_list. */
3373 		list_for_each_entry(list, &qgroup->groups, next_group)
3374 			qgroup_iterator_add(&qgroup_list, list->group);
3375 	}
3376 	qgroup_iterator_clean(&qgroup_list);
3377 	return 0;
3378 }
3379 
3380 /*
3381  * Copy the accounting information between qgroups. This is necessary
3382  * when a snapshot or a subvolume is created. Throwing an error will
3383  * cause a transaction abort so we take extra care here to only error
3384  * when a readonly fs is a reasonable outcome.
3385  */
3386 int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans, u64 srcid,
3387 			 u64 objectid, u64 inode_rootid,
3388 			 struct btrfs_qgroup_inherit *inherit)
3389 {
3390 	int ret = 0;
3391 	u64 *i_qgroups;
3392 	bool committing = false;
3393 	struct btrfs_fs_info *fs_info = trans->fs_info;
3394 	struct btrfs_root *quota_root;
3395 	struct btrfs_qgroup *srcgroup;
3396 	struct btrfs_qgroup *dstgroup;
3397 	struct btrfs_qgroup *prealloc;
3398 	struct btrfs_qgroup_list **qlist_prealloc = NULL;
3399 	bool free_inherit = false;
3400 	bool need_rescan = false;
3401 	u32 level_size = 0;
3402 	u64 nums;
3403 
3404 	if (!btrfs_qgroup_enabled(fs_info))
3405 		return 0;
3406 
3407 	prealloc = kzalloc_obj(*prealloc, GFP_NOFS);
3408 	if (!prealloc)
3409 		return -ENOMEM;
3410 
3411 	/*
3412 	 * There are only two callers of this function.
3413 	 *
3414 	 * One in create_subvol() in the ioctl context, which needs to hold
3415 	 * the qgroup_ioctl_lock.
3416 	 *
3417 	 * The other one in create_pending_snapshot() where no other qgroup
3418 	 * code can modify the fs as they all need to either start a new trans
3419 	 * or hold a trans handler, thus we don't need to hold
3420 	 * qgroup_ioctl_lock.
3421 	 * This would avoid long and complex lock chain and make lockdep happy.
3422 	 */
3423 	spin_lock(&fs_info->trans_lock);
3424 	if (trans->transaction->state == TRANS_STATE_COMMIT_DOING)
3425 		committing = true;
3426 	spin_unlock(&fs_info->trans_lock);
3427 
3428 	if (!committing)
3429 		mutex_lock(&fs_info->qgroup_ioctl_lock);
3430 
3431 	quota_root = fs_info->quota_root;
3432 	if (!quota_root) {
3433 		ret = -EINVAL;
3434 		goto out;
3435 	}
3436 
3437 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE && !inherit) {
3438 		ret = qgroup_auto_inherit(fs_info, inode_rootid, &inherit);
3439 		if (ret)
3440 			goto out;
3441 		free_inherit = true;
3442 	}
3443 
3444 	if (inherit) {
3445 		i_qgroups = (u64 *)(inherit + 1);
3446 		nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
3447 		       2 * inherit->num_excl_copies;
3448 		for (int i = 0; i < nums; i++) {
3449 			srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
3450 
3451 			/*
3452 			 * Zero out invalid groups so we can ignore
3453 			 * them later.
3454 			 */
3455 			if (!srcgroup ||
3456 			    ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
3457 				*i_qgroups = 0ULL;
3458 
3459 			++i_qgroups;
3460 		}
3461 	}
3462 
3463 	/*
3464 	 * create a tracking group for the subvol itself
3465 	 */
3466 	ret = add_qgroup_item(trans, quota_root, objectid);
3467 	if (ret)
3468 		goto out;
3469 
3470 	/*
3471 	 * add qgroup to all inherited groups
3472 	 */
3473 	if (inherit) {
3474 		i_qgroups = (u64 *)(inherit + 1);
3475 		for (int i = 0; i < inherit->num_qgroups; i++, i_qgroups++) {
3476 			if (*i_qgroups == 0)
3477 				continue;
3478 			ret = add_qgroup_relation_item(trans, objectid,
3479 						       *i_qgroups);
3480 			if (ret && ret != -EEXIST)
3481 				goto out;
3482 			ret = add_qgroup_relation_item(trans, *i_qgroups,
3483 						       objectid);
3484 			if (ret && ret != -EEXIST)
3485 				goto out;
3486 		}
3487 		ret = 0;
3488 
3489 		qlist_prealloc = kzalloc_objs(struct btrfs_qgroup_list *,
3490 					      inherit->num_qgroups, GFP_NOFS);
3491 		if (!qlist_prealloc) {
3492 			ret = -ENOMEM;
3493 			goto out;
3494 		}
3495 		for (int i = 0; i < inherit->num_qgroups; i++) {
3496 			qlist_prealloc[i] = kzalloc_obj(struct btrfs_qgroup_list,
3497 							GFP_NOFS);
3498 			if (!qlist_prealloc[i]) {
3499 				ret = -ENOMEM;
3500 				goto out;
3501 			}
3502 		}
3503 	}
3504 
3505 	spin_lock(&fs_info->qgroup_lock);
3506 
3507 	dstgroup = add_qgroup_rb(fs_info, prealloc, objectid);
3508 	prealloc = NULL;
3509 
3510 	if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
3511 		dstgroup->lim_flags = inherit->lim.flags;
3512 		dstgroup->max_rfer = inherit->lim.max_rfer;
3513 		dstgroup->max_excl = inherit->lim.max_excl;
3514 		dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
3515 		dstgroup->rsv_excl = inherit->lim.rsv_excl;
3516 
3517 		qgroup_dirty(fs_info, dstgroup);
3518 	}
3519 
3520 	if (srcid && btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_FULL) {
3521 		srcgroup = find_qgroup_rb(fs_info, srcid);
3522 		if (!srcgroup)
3523 			goto unlock;
3524 
3525 		/*
3526 		 * We call inherit after we clone the root in order to make sure
3527 		 * our counts don't go crazy, so at this point the only
3528 		 * difference between the two roots should be the root node.
3529 		 */
3530 		level_size = fs_info->nodesize;
3531 		dstgroup->rfer = srcgroup->rfer;
3532 		dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
3533 		dstgroup->excl = level_size;
3534 		dstgroup->excl_cmpr = level_size;
3535 		srcgroup->excl = level_size;
3536 		srcgroup->excl_cmpr = level_size;
3537 
3538 		/* inherit the limit info */
3539 		dstgroup->lim_flags = srcgroup->lim_flags;
3540 		dstgroup->max_rfer = srcgroup->max_rfer;
3541 		dstgroup->max_excl = srcgroup->max_excl;
3542 		dstgroup->rsv_rfer = srcgroup->rsv_rfer;
3543 		dstgroup->rsv_excl = srcgroup->rsv_excl;
3544 
3545 		qgroup_dirty(fs_info, dstgroup);
3546 		qgroup_dirty(fs_info, srcgroup);
3547 
3548 		/*
3549 		 * If the source qgroup has parent but the new one doesn't,
3550 		 * we need a full rescan.
3551 		 */
3552 		if (!inherit && !list_empty(&srcgroup->groups))
3553 			need_rescan = true;
3554 	}
3555 
3556 	if (!inherit)
3557 		goto unlock;
3558 
3559 	i_qgroups = (u64 *)(inherit + 1);
3560 	for (int i = 0; i < inherit->num_qgroups; i++) {
3561 		if (*i_qgroups) {
3562 			ret = add_relation_rb(fs_info, qlist_prealloc[i], objectid,
3563 					      *i_qgroups);
3564 			qlist_prealloc[i] = NULL;
3565 			if (ret)
3566 				goto unlock;
3567 		}
3568 		if (srcid) {
3569 			/* Check if we can do a quick inherit. */
3570 			ret = qgroup_snapshot_quick_inherit(fs_info, srcid, *i_qgroups);
3571 			if (ret < 0)
3572 				goto unlock;
3573 			if (ret > 0)
3574 				need_rescan = true;
3575 			ret = 0;
3576 		}
3577 		++i_qgroups;
3578 	}
3579 
3580 	for (int i = 0; i < inherit->num_ref_copies; i++, i_qgroups += 2) {
3581 		struct btrfs_qgroup *src;
3582 		struct btrfs_qgroup *dst;
3583 
3584 		if (!i_qgroups[0] || !i_qgroups[1])
3585 			continue;
3586 
3587 		src = find_qgroup_rb(fs_info, i_qgroups[0]);
3588 		dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3589 
3590 		if (!src || !dst) {
3591 			ret = -EINVAL;
3592 			goto unlock;
3593 		}
3594 
3595 		dst->rfer = src->rfer - level_size;
3596 		dst->rfer_cmpr = src->rfer_cmpr - level_size;
3597 
3598 		/* Manually tweaking numbers certainly needs a rescan */
3599 		need_rescan = true;
3600 	}
3601 	for (int i = 0; i < inherit->num_excl_copies; i++, i_qgroups += 2) {
3602 		struct btrfs_qgroup *src;
3603 		struct btrfs_qgroup *dst;
3604 
3605 		if (!i_qgroups[0] || !i_qgroups[1])
3606 			continue;
3607 
3608 		src = find_qgroup_rb(fs_info, i_qgroups[0]);
3609 		dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3610 
3611 		if (!src || !dst) {
3612 			ret = -EINVAL;
3613 			goto unlock;
3614 		}
3615 
3616 		dst->excl = src->excl + level_size;
3617 		dst->excl_cmpr = src->excl_cmpr + level_size;
3618 		need_rescan = true;
3619 	}
3620 
3621 unlock:
3622 	spin_unlock(&fs_info->qgroup_lock);
3623 	if (!ret)
3624 		ret = btrfs_sysfs_add_one_qgroup(fs_info, dstgroup);
3625 out:
3626 	if (!committing)
3627 		mutex_unlock(&fs_info->qgroup_ioctl_lock);
3628 	if (need_rescan)
3629 		qgroup_mark_inconsistent(fs_info, "qgroup inherit needs a rescan");
3630 	if (qlist_prealloc) {
3631 		for (int i = 0; i < inherit->num_qgroups; i++)
3632 			kfree(qlist_prealloc[i]);
3633 		kfree(qlist_prealloc);
3634 	}
3635 	if (free_inherit)
3636 		kfree(inherit);
3637 	kfree(prealloc);
3638 	return ret;
3639 }
3640 
3641 static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
3642 {
3643 	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
3644 	    qgroup_rsv_total(qg) + (s64)qg->rfer + num_bytes > qg->max_rfer)
3645 		return false;
3646 
3647 	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
3648 	    qgroup_rsv_total(qg) + (s64)qg->excl + num_bytes > qg->max_excl)
3649 		return false;
3650 
3651 	return true;
3652 }
3653 
3654 static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce,
3655 			  enum btrfs_qgroup_rsv_type type)
3656 {
3657 	struct btrfs_qgroup *qgroup;
3658 	struct btrfs_fs_info *fs_info = root->fs_info;
3659 	u64 ref_root = btrfs_root_id(root);
3660 	int ret = 0;
3661 	LIST_HEAD(qgroup_list);
3662 
3663 	if (!btrfs_is_fstree(ref_root))
3664 		return 0;
3665 
3666 	if (num_bytes == 0)
3667 		return 0;
3668 
3669 	if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
3670 	    capable(CAP_SYS_RESOURCE))
3671 		enforce = false;
3672 
3673 	spin_lock(&fs_info->qgroup_lock);
3674 	if (!fs_info->quota_root)
3675 		goto out;
3676 
3677 	qgroup = find_qgroup_rb(fs_info, ref_root);
3678 	if (!qgroup)
3679 		goto out;
3680 
3681 	qgroup_iterator_add(&qgroup_list, qgroup);
3682 	list_for_each_entry(qgroup, &qgroup_list, iterator) {
3683 		struct btrfs_qgroup_list *glist;
3684 
3685 		if (enforce && !qgroup_check_limits(qgroup, num_bytes)) {
3686 			ret = -EDQUOT;
3687 			goto out;
3688 		}
3689 
3690 		list_for_each_entry(glist, &qgroup->groups, next_group)
3691 			qgroup_iterator_add(&qgroup_list, glist->group);
3692 	}
3693 
3694 	ret = 0;
3695 	/*
3696 	 * no limits exceeded, now record the reservation into all qgroups
3697 	 */
3698 	list_for_each_entry(qgroup, &qgroup_list, iterator)
3699 		qgroup_rsv_add(fs_info, qgroup, num_bytes, type);
3700 
3701 out:
3702 	qgroup_iterator_clean(&qgroup_list);
3703 	spin_unlock(&fs_info->qgroup_lock);
3704 	return ret;
3705 }
3706 
3707 /*
3708  * Free @num_bytes of reserved space with @type for qgroup.  (Normally level 0
3709  * qgroup).
3710  *
3711  * Will handle all higher level qgroup too.
3712  *
3713  * NOTE: If @num_bytes is (u64)-1, this means to free all bytes of this qgroup.
3714  * This special case is only used for META_PERTRANS type.
3715  */
3716 void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
3717 			       u64 ref_root, u64 num_bytes,
3718 			       enum btrfs_qgroup_rsv_type type)
3719 {
3720 	struct btrfs_qgroup *qgroup;
3721 	LIST_HEAD(qgroup_list);
3722 
3723 	if (!btrfs_is_fstree(ref_root))
3724 		return;
3725 
3726 	if (num_bytes == 0)
3727 		return;
3728 
3729 	if (num_bytes == (u64)-1 && type != BTRFS_QGROUP_RSV_META_PERTRANS) {
3730 		WARN(1, "%s: Invalid type to free", __func__);
3731 		return;
3732 	}
3733 	spin_lock(&fs_info->qgroup_lock);
3734 
3735 	if (!fs_info->quota_root)
3736 		goto out;
3737 
3738 	qgroup = find_qgroup_rb(fs_info, ref_root);
3739 	if (!qgroup)
3740 		goto out;
3741 
3742 	if (num_bytes == (u64)-1)
3743 		/*
3744 		 * We're freeing all pertrans rsv, get reserved value from
3745 		 * level 0 qgroup as real num_bytes to free.
3746 		 */
3747 		num_bytes = qgroup->rsv.values[type];
3748 
3749 	qgroup_iterator_add(&qgroup_list, qgroup);
3750 	list_for_each_entry(qgroup, &qgroup_list, iterator) {
3751 		struct btrfs_qgroup_list *glist;
3752 
3753 		qgroup_rsv_release(fs_info, qgroup, num_bytes, type);
3754 		list_for_each_entry(glist, &qgroup->groups, next_group) {
3755 			qgroup_iterator_add(&qgroup_list, glist->group);
3756 		}
3757 	}
3758 out:
3759 	qgroup_iterator_clean(&qgroup_list);
3760 	spin_unlock(&fs_info->qgroup_lock);
3761 }
3762 
3763 /*
3764  * Check if the leaf is the last leaf. Which means all node pointers
3765  * are at their last position.
3766  */
3767 static bool is_last_leaf(struct btrfs_path *path)
3768 {
3769 	int i;
3770 
3771 	for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
3772 		if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
3773 			return false;
3774 	}
3775 	return true;
3776 }
3777 
3778 /*
3779  * returns < 0 on error, 0 when more leafs are to be scanned.
3780  * returns 1 when done.
3781  */
3782 static int qgroup_rescan_leaf(struct btrfs_trans_handle *trans,
3783 			      struct btrfs_path *path)
3784 {
3785 	struct btrfs_fs_info *fs_info = trans->fs_info;
3786 	struct btrfs_root *extent_root;
3787 	struct btrfs_key found;
3788 	struct extent_buffer *scratch_leaf = NULL;
3789 	u64 num_bytes;
3790 	bool done;
3791 	int slot;
3792 	int ret;
3793 
3794 	if (!btrfs_qgroup_full_accounting(fs_info))
3795 		return 1;
3796 
3797 	mutex_lock(&fs_info->qgroup_rescan_lock);
3798 	extent_root = btrfs_extent_root(fs_info,
3799 				fs_info->qgroup_rescan_progress.objectid);
3800 	if (unlikely(!extent_root)) {
3801 		btrfs_err(fs_info,
3802 			  "missing extent root for extent at bytenr %llu",
3803 			  fs_info->qgroup_rescan_progress.objectid);
3804 		mutex_unlock(&fs_info->qgroup_rescan_lock);
3805 		return -EUCLEAN;
3806 	}
3807 
3808 	ret = btrfs_search_slot_for_read(extent_root,
3809 					 &fs_info->qgroup_rescan_progress,
3810 					 path, 1, 0);
3811 
3812 	btrfs_debug(fs_info,
3813 		    "current progress key " BTRFS_KEY_FMT ", search_slot ret %d",
3814 		    BTRFS_KEY_FMT_VALUE(&fs_info->qgroup_rescan_progress), ret);
3815 
3816 	if (ret) {
3817 		/*
3818 		 * The rescan is about to end, we will not be scanning any
3819 		 * further blocks. We cannot unset the RESCAN flag here, because
3820 		 * we want to commit the transaction if everything went well.
3821 		 * To make the live accounting work in this phase, we set our
3822 		 * scan progress pointer such that every real extent objectid
3823 		 * will be smaller.
3824 		 */
3825 		fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3826 		btrfs_release_path(path);
3827 		mutex_unlock(&fs_info->qgroup_rescan_lock);
3828 		return ret;
3829 	}
3830 	done = is_last_leaf(path);
3831 
3832 	btrfs_item_key_to_cpu(path->nodes[0], &found,
3833 			      btrfs_header_nritems(path->nodes[0]) - 1);
3834 	fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;
3835 
3836 	scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
3837 	if (!scratch_leaf) {
3838 		ret = -ENOMEM;
3839 		mutex_unlock(&fs_info->qgroup_rescan_lock);
3840 		goto out;
3841 	}
3842 	slot = path->slots[0];
3843 	btrfs_release_path(path);
3844 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3845 
3846 	for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
3847 		struct btrfs_backref_walk_ctx ctx = { 0 };
3848 
3849 		btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
3850 		if (found.type != BTRFS_EXTENT_ITEM_KEY &&
3851 		    found.type != BTRFS_METADATA_ITEM_KEY)
3852 			continue;
3853 		if (found.type == BTRFS_METADATA_ITEM_KEY)
3854 			num_bytes = fs_info->nodesize;
3855 		else
3856 			num_bytes = found.offset;
3857 
3858 		ctx.bytenr = found.objectid;
3859 		ctx.fs_info = fs_info;
3860 
3861 		ret = btrfs_find_all_roots(&ctx, false);
3862 		if (ret < 0)
3863 			goto out;
3864 		/* For rescan, just pass old_roots as NULL */
3865 		ret = btrfs_qgroup_account_extent(trans, found.objectid,
3866 						  num_bytes, NULL, ctx.roots);
3867 		if (ret < 0)
3868 			goto out;
3869 	}
3870 out:
3871 	if (scratch_leaf)
3872 		free_extent_buffer(scratch_leaf);
3873 
3874 	if (done && !ret) {
3875 		ret = 1;
3876 		fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3877 	}
3878 	return ret;
3879 }
3880 
3881 static bool rescan_should_stop(struct btrfs_fs_info *fs_info)
3882 {
3883 	if (btrfs_fs_closing(fs_info))
3884 		return true;
3885 	if (test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state))
3886 		return true;
3887 	if (!btrfs_qgroup_enabled(fs_info))
3888 		return true;
3889 	if (test_bit(BTRFS_QGROUP_RUNTIME_BIT_CANCEL_RESCAN, &fs_info->qgroup_flags))
3890 		return true;
3891 	return false;
3892 }
3893 
3894 static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
3895 {
3896 	struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
3897 						     qgroup_rescan_work);
3898 	struct btrfs_path *path;
3899 	struct btrfs_trans_handle *trans = NULL;
3900 	int ret = 0;
3901 	bool stopped = false;
3902 	bool did_leaf_rescans = false;
3903 
3904 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE)
3905 		return;
3906 
3907 	path = btrfs_alloc_path();
3908 	if (!path) {
3909 		ret = -ENOMEM;
3910 		goto out;
3911 	}
3912 	/*
3913 	 * Rescan should only search for commit root, and any later difference
3914 	 * should be recorded by qgroup
3915 	 */
3916 	path->search_commit_root = true;
3917 	path->skip_locking = true;
3918 
3919 	while (!ret && !(stopped = rescan_should_stop(fs_info))) {
3920 		trans = btrfs_start_transaction(fs_info->fs_root, 0);
3921 		if (IS_ERR(trans)) {
3922 			ret = PTR_ERR(trans);
3923 			break;
3924 		}
3925 
3926 		ret = qgroup_rescan_leaf(trans, path);
3927 		did_leaf_rescans = true;
3928 
3929 		if (ret > 0)
3930 			btrfs_commit_transaction(trans);
3931 		else
3932 			btrfs_end_transaction(trans);
3933 	}
3934 
3935 out:
3936 	btrfs_free_path(path);
3937 
3938 	mutex_lock(&fs_info->qgroup_rescan_lock);
3939 	if (ret > 0)
3940 		clear_bit(BTRFS_QGROUP_STATUS_BIT_INCONSISTENT, &fs_info->qgroup_flags);
3941 	else if (ret < 0 || stopped)
3942 		set_bit(BTRFS_QGROUP_STATUS_BIT_INCONSISTENT, &fs_info->qgroup_flags);
3943 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3944 
3945 	/*
3946 	 * Only update status, since the previous part has already updated the
3947 	 * qgroup info, and only if we did any actual work. This also prevents
3948 	 * race with a concurrent quota disable, which has already set
3949 	 * fs_info->quota_root to NULL and cleared BTRFS_FS_QUOTA_ENABLED at
3950 	 * btrfs_quota_disable().
3951 	 */
3952 	if (did_leaf_rescans) {
3953 		trans = btrfs_start_transaction(fs_info->quota_root, 1);
3954 		if (IS_ERR(trans)) {
3955 			ret = PTR_ERR(trans);
3956 			trans = NULL;
3957 			btrfs_err(fs_info,
3958 				  "fail to start transaction for status update: %pe",
3959 				  ERR_PTR(ret));
3960 		}
3961 	} else {
3962 		trans = NULL;
3963 	}
3964 
3965 	mutex_lock(&fs_info->qgroup_rescan_lock);
3966 	if (!stopped || test_bit(BTRFS_QGROUP_RUNTIME_BIT_CANCEL_RESCAN,
3967 				 &fs_info->qgroup_flags))
3968 		clear_bit(BTRFS_QGROUP_STATUS_BIT_RESCAN, &fs_info->qgroup_flags);
3969 	if (trans) {
3970 		int ret2 = update_qgroup_status_item(trans);
3971 
3972 		if (ret2 < 0) {
3973 			ret = ret2;
3974 			btrfs_err(fs_info, "fail to update qgroup status: %pe", ERR_PTR(ret));
3975 		}
3976 	}
3977 	fs_info->qgroup_rescan_running = false;
3978 	clear_bit(BTRFS_QGROUP_RUNTIME_BIT_CANCEL_RESCAN, &fs_info->qgroup_flags);
3979 	complete_all(&fs_info->qgroup_rescan_completion);
3980 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3981 
3982 	if (!trans)
3983 		return;
3984 
3985 	btrfs_end_transaction(trans);
3986 
3987 	if (stopped) {
3988 		btrfs_info(fs_info, "qgroup scan paused");
3989 	} else if (test_bit(BTRFS_QGROUP_RUNTIME_BIT_CANCEL_RESCAN, &fs_info->qgroup_flags)) {
3990 		btrfs_info(fs_info, "qgroup scan cancelled");
3991 	} else if (ret >= 0) {
3992 		btrfs_info(fs_info, "qgroup scan completed%s",
3993 			ret > 0 ? " (inconsistency flag cleared)" : "");
3994 	} else {
3995 		btrfs_err(fs_info, "qgroup scan failed with %pe", ERR_PTR(ret));
3996 	}
3997 }
3998 
3999 /*
4000  * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
4001  * memory required for the rescan context.
4002  */
4003 static int
4004 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
4005 		   int init_flags)
4006 {
4007 	int ret = 0;
4008 
4009 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE) {
4010 		btrfs_warn(fs_info, "qgroup rescan init failed, running in simple mode");
4011 		return -EINVAL;
4012 	}
4013 
4014 	if (!init_flags) {
4015 		/* we're resuming qgroup rescan at mount time */
4016 		if (!(test_bit(BTRFS_QGROUP_STATUS_BIT_RESCAN, &fs_info->qgroup_flags))) {
4017 			btrfs_debug(fs_info,
4018 			"qgroup rescan init failed, qgroup rescan is not queued");
4019 			ret = -EINVAL;
4020 		} else if (!(test_bit(BTRFS_QGROUP_STATUS_BIT_ON, &fs_info->qgroup_flags))) {
4021 			btrfs_debug(fs_info,
4022 			"qgroup rescan init failed, qgroup is not enabled");
4023 			ret = -ENOTCONN;
4024 		}
4025 
4026 		if (ret)
4027 			return ret;
4028 	}
4029 
4030 	mutex_lock(&fs_info->qgroup_rescan_lock);
4031 
4032 	if (init_flags) {
4033 		if (test_bit(BTRFS_QGROUP_STATUS_BIT_RESCAN,
4034 			     &fs_info->qgroup_flags) ||
4035 		    test_bit(BTRFS_QGROUP_RUNTIME_BIT_REJECT_RESCAN,
4036 			     &fs_info->qgroup_flags)) {
4037 			ret = -EINPROGRESS;
4038 		} else if (!test_bit(BTRFS_QGROUP_STATUS_BIT_ON, &fs_info->qgroup_flags)) {
4039 			btrfs_debug(fs_info,
4040 			"qgroup rescan init failed, qgroup is not enabled");
4041 			ret = -ENOTCONN;
4042 		} else if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_DISABLED) {
4043 			/* Quota disable is in progress */
4044 			ret = -EBUSY;
4045 		}
4046 
4047 		if (ret) {
4048 			mutex_unlock(&fs_info->qgroup_rescan_lock);
4049 			return ret;
4050 		}
4051 		set_bit(BTRFS_QGROUP_STATUS_BIT_RESCAN, &fs_info->qgroup_flags);
4052 	}
4053 
4054 	memset(&fs_info->qgroup_rescan_progress, 0,
4055 		sizeof(fs_info->qgroup_rescan_progress));
4056 	clear_bit(BTRFS_QGROUP_RUNTIME_BIT_CANCEL_RESCAN, &fs_info->qgroup_flags);
4057 	clear_bit(BTRFS_QGROUP_RUNTIME_BIT_NO_ACCOUNTING, &fs_info->qgroup_flags);
4058 	fs_info->qgroup_rescan_progress.objectid = progress_objectid;
4059 	init_completion(&fs_info->qgroup_rescan_completion);
4060 	mutex_unlock(&fs_info->qgroup_rescan_lock);
4061 
4062 	btrfs_init_work(&fs_info->qgroup_rescan_work,
4063 			btrfs_qgroup_rescan_worker, NULL);
4064 	return 0;
4065 }
4066 
4067 static void
4068 qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
4069 {
4070 	struct rb_node *n;
4071 	struct btrfs_qgroup *qgroup;
4072 
4073 	spin_lock(&fs_info->qgroup_lock);
4074 	/* clear all current qgroup tracking information */
4075 	for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
4076 		qgroup = rb_entry(n, struct btrfs_qgroup, node);
4077 		qgroup->rfer = 0;
4078 		qgroup->rfer_cmpr = 0;
4079 		qgroup->excl = 0;
4080 		qgroup->excl_cmpr = 0;
4081 		qgroup_dirty(fs_info, qgroup);
4082 	}
4083 	spin_unlock(&fs_info->qgroup_lock);
4084 }
4085 
4086 int
4087 btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
4088 {
4089 	int ret = 0;
4090 
4091 	ret = qgroup_rescan_init(fs_info, 0, 1);
4092 	if (ret)
4093 		return ret;
4094 
4095 	/*
4096 	 * We have set the rescan_progress to 0, which means no more
4097 	 * delayed refs will be accounted by btrfs_qgroup_account_ref.
4098 	 * However, btrfs_qgroup_account_ref may be right after its call
4099 	 * to btrfs_find_all_roots, in which case it would still do the
4100 	 * accounting.
4101 	 * To solve this, we're committing the transaction, which will
4102 	 * ensure we run all delayed refs and only after that, we are
4103 	 * going to clear all tracking information for a clean start.
4104 	 */
4105 
4106 	ret = btrfs_commit_current_transaction(fs_info->fs_root);
4107 	if (ret) {
4108 		clear_bit(BTRFS_QGROUP_STATUS_BIT_RESCAN, &fs_info->qgroup_flags);
4109 		return ret;
4110 	}
4111 
4112 	qgroup_rescan_zero_tracking(fs_info);
4113 
4114 	mutex_lock(&fs_info->qgroup_rescan_lock);
4115 	/*
4116 	 * The rescan worker is only for full accounting qgroups, check if it's
4117 	 * enabled as it is pointless to queue it otherwise. A concurrent quota
4118 	 * disable may also have just cleared BTRFS_FS_QUOTA_ENABLED.
4119 	 */
4120 	if (btrfs_qgroup_full_accounting(fs_info)) {
4121 		fs_info->qgroup_rescan_running = true;
4122 		btrfs_queue_work(fs_info->qgroup_rescan_workers,
4123 				 &fs_info->qgroup_rescan_work);
4124 	} else {
4125 		ret = -ENOTCONN;
4126 	}
4127 	mutex_unlock(&fs_info->qgroup_rescan_lock);
4128 
4129 	return ret;
4130 }
4131 
4132 int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
4133 				     bool interruptible)
4134 {
4135 	int running;
4136 	int ret = 0;
4137 
4138 	mutex_lock(&fs_info->qgroup_rescan_lock);
4139 	running = fs_info->qgroup_rescan_running;
4140 	mutex_unlock(&fs_info->qgroup_rescan_lock);
4141 
4142 	if (!running)
4143 		return 0;
4144 
4145 	if (interruptible)
4146 		ret = wait_for_completion_interruptible(
4147 					&fs_info->qgroup_rescan_completion);
4148 	else
4149 		wait_for_completion(&fs_info->qgroup_rescan_completion);
4150 
4151 	return ret;
4152 }
4153 
4154 /*
4155  * this is only called from open_ctree where we're still single threaded, thus
4156  * locking is omitted here.
4157  */
4158 void
4159 btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
4160 {
4161 	if (test_bit(BTRFS_QGROUP_STATUS_BIT_RESCAN, &fs_info->qgroup_flags)) {
4162 		mutex_lock(&fs_info->qgroup_rescan_lock);
4163 		fs_info->qgroup_rescan_running = true;
4164 		btrfs_queue_work(fs_info->qgroup_rescan_workers,
4165 				 &fs_info->qgroup_rescan_work);
4166 		mutex_unlock(&fs_info->qgroup_rescan_lock);
4167 	}
4168 }
4169 
4170 #define rbtree_iterate_from_safe(node, next, start)				\
4171        for (node = start; node && ({ next = rb_next(node); 1;}); node = next)
4172 
4173 static int qgroup_unreserve_range(struct btrfs_inode *inode,
4174 				  struct extent_changeset *reserved, u64 start,
4175 				  u64 len)
4176 {
4177 	struct rb_node *node;
4178 	struct rb_node *next;
4179 	struct ulist_node *entry;
4180 	int ret = 0;
4181 
4182 	node = reserved->range_changed.root.rb_node;
4183 	if (!node)
4184 		return 0;
4185 	while (node) {
4186 		entry = rb_entry(node, struct ulist_node, rb_node);
4187 		if (entry->val < start)
4188 			node = node->rb_right;
4189 		else
4190 			node = node->rb_left;
4191 	}
4192 
4193 	if (entry->val > start && rb_prev(&entry->rb_node))
4194 		entry = rb_entry(rb_prev(&entry->rb_node), struct ulist_node,
4195 				 rb_node);
4196 
4197 	rbtree_iterate_from_safe(node, next, &entry->rb_node) {
4198 		u64 entry_start;
4199 		u64 entry_end;
4200 		u64 entry_len;
4201 		int clear_ret;
4202 
4203 		entry = rb_entry(node, struct ulist_node, rb_node);
4204 		entry_start = entry->val;
4205 		entry_end = entry->aux;
4206 		entry_len = entry_end - entry_start + 1;
4207 
4208 		if (entry_start >= start + len)
4209 			break;
4210 		if (entry_start + entry_len <= start)
4211 			continue;
4212 		/*
4213 		 * Now the entry is in [start, start + len), revert the
4214 		 * EXTENT_QGROUP_RESERVED bit.
4215 		 */
4216 		clear_ret = btrfs_clear_extent_bit(&inode->io_tree, entry_start, entry_end,
4217 						   EXTENT_QGROUP_RESERVED, NULL);
4218 		if (!ret && clear_ret < 0)
4219 			ret = clear_ret;
4220 
4221 		ulist_del(&reserved->range_changed, entry->val, entry->aux);
4222 		if (likely(reserved->bytes_changed >= entry_len)) {
4223 			reserved->bytes_changed -= entry_len;
4224 		} else {
4225 			WARN_ON(1);
4226 			reserved->bytes_changed = 0;
4227 		}
4228 	}
4229 
4230 	return ret;
4231 }
4232 
4233 /*
4234  * Try to free some space for qgroup.
4235  *
4236  * For qgroup, there are only 3 ways to free qgroup space:
4237  * - Flush nodatacow write
4238  *   Any nodatacow write will free its reserved data space at run_delalloc_range().
4239  *   In theory, we should only flush nodatacow inodes, but it's not yet
4240  *   possible, so we need to flush the whole root.
4241  *
4242  * - Wait for ordered extents
4243  *   When ordered extents are finished, their reserved metadata is finally
4244  *   converted to per_trans status, which can be freed by later commit
4245  *   transaction.
4246  *
4247  * - Commit transaction
4248  *   This would free the meta_per_trans space.
4249  *   In theory this shouldn't provide much space, but any more qgroup space
4250  *   is needed.
4251  */
4252 static int try_flush_qgroup(struct btrfs_root *root)
4253 {
4254 	int ret;
4255 
4256 	/* Can't hold an open transaction or we run the risk of deadlocking. */
4257 	ASSERT(current->journal_info == NULL);
4258 	if (WARN_ON(current->journal_info))
4259 		return 0;
4260 
4261 	/*
4262 	 * We don't want to run flush again and again, so if there is a running
4263 	 * one, we won't try to start a new flush, but exit directly.
4264 	 */
4265 	if (test_and_set_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state)) {
4266 		wait_event(root->qgroup_flush_wait,
4267 			!test_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state));
4268 		return 0;
4269 	}
4270 
4271 	ret = btrfs_start_delalloc_snapshot(root, true);
4272 	if (ret < 0)
4273 		goto out;
4274 	btrfs_wait_ordered_extents(root, U64_MAX, NULL);
4275 
4276 	/*
4277 	 * After waiting for ordered extents run delayed iputs in order to free
4278 	 * space from unlinked files before committing the current transaction,
4279 	 * as ordered extents may have been holding the last reference of an
4280 	 * inode and they add a delayed iput when they complete.
4281 	 */
4282 	btrfs_run_delayed_iputs(root->fs_info);
4283 	btrfs_wait_on_delayed_iputs(root->fs_info);
4284 
4285 	ret = btrfs_commit_current_transaction(root);
4286 out:
4287 	clear_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state);
4288 	wake_up(&root->qgroup_flush_wait);
4289 	return ret;
4290 }
4291 
4292 static int qgroup_reserve_data(struct btrfs_inode *inode,
4293 			struct extent_changeset **reserved_ret, u64 start,
4294 			u64 len)
4295 {
4296 	struct btrfs_root *root = inode->root;
4297 	struct extent_changeset *reserved;
4298 	bool new_reserved = false;
4299 	u64 orig_reserved;
4300 	u64 to_reserve;
4301 	int ret;
4302 
4303 	if (btrfs_qgroup_mode(root->fs_info) == BTRFS_QGROUP_MODE_DISABLED ||
4304 	    !btrfs_is_fstree(btrfs_root_id(root)) || len == 0)
4305 		return 0;
4306 
4307 	/* @reserved parameter is mandatory for qgroup */
4308 	if (WARN_ON(!reserved_ret))
4309 		return -EINVAL;
4310 	if (!*reserved_ret) {
4311 		new_reserved = true;
4312 		*reserved_ret = extent_changeset_alloc();
4313 		if (!*reserved_ret)
4314 			return -ENOMEM;
4315 	}
4316 	reserved = *reserved_ret;
4317 	/* Record already reserved space */
4318 	orig_reserved = reserved->bytes_changed;
4319 	ret = btrfs_set_record_extent_bits(&inode->io_tree, start,
4320 					   start + len - 1, EXTENT_QGROUP_RESERVED,
4321 					   reserved);
4322 
4323 	/* Newly reserved space */
4324 	to_reserve = reserved->bytes_changed - orig_reserved;
4325 	trace_btrfs_qgroup_reserve_data(&inode->vfs_inode, start, len,
4326 					to_reserve, QGROUP_RESERVE);
4327 	if (ret < 0)
4328 		goto out;
4329 	ret = qgroup_reserve(root, to_reserve, true, BTRFS_QGROUP_RSV_DATA);
4330 	if (ret < 0)
4331 		goto cleanup;
4332 
4333 	return ret;
4334 
4335 cleanup:
4336 	qgroup_unreserve_range(inode, reserved, start, len);
4337 out:
4338 	if (new_reserved) {
4339 		extent_changeset_free(reserved);
4340 		*reserved_ret = NULL;
4341 	}
4342 	return ret;
4343 }
4344 
4345 /*
4346  * Reserve qgroup space for range [start, start + len).
4347  *
4348  * This function will either reserve space from related qgroups or do nothing
4349  * if the range is already reserved.
4350  *
4351  * Return 0 for successful reservation
4352  * Return <0 for error (including -EQUOT)
4353  *
4354  * NOTE: This function may sleep for memory allocation, dirty page flushing and
4355  *	 commit transaction. So caller should not hold any dirty page locked.
4356  */
4357 int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
4358 			struct extent_changeset **reserved_ret, u64 start,
4359 			u64 len)
4360 {
4361 	int ret;
4362 
4363 	ret = qgroup_reserve_data(inode, reserved_ret, start, len);
4364 	if (ret <= 0 && ret != -EDQUOT)
4365 		return ret;
4366 
4367 	ret = try_flush_qgroup(inode->root);
4368 	if (ret < 0)
4369 		return ret;
4370 	return qgroup_reserve_data(inode, reserved_ret, start, len);
4371 }
4372 
4373 /* Free ranges specified by @reserved, normally in error path */
4374 static int qgroup_free_reserved_data(struct btrfs_inode *inode,
4375 				     struct extent_changeset *reserved,
4376 				     u64 start, u64 len, u64 *freed_ret)
4377 {
4378 	struct btrfs_root *root = inode->root;
4379 	struct ulist_node *unode;
4380 	struct ulist_iterator uiter;
4381 	struct extent_changeset changeset;
4382 	const u32 sectorsize = root->fs_info->sectorsize;
4383 	const u64 aligned_start = round_down(start, sectorsize);
4384 	const u64 aligned_len = round_up(start + len, sectorsize) - aligned_start;
4385 	u64 freed = 0;
4386 	int ret;
4387 
4388 	extent_changeset_init_bytes_only(&changeset);
4389 
4390 	ULIST_ITER_INIT(&uiter);
4391 	while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
4392 		u64 range_start = unode->val;
4393 		/* unode->aux is the inclusive end */
4394 		u64 range_len = unode->aux - range_start + 1;
4395 		u64 free_start;
4396 		u64 free_len;
4397 
4398 		extent_changeset_release(&changeset);
4399 
4400 		/*
4401 		 * Only free the range within
4402 		 * [aligned_start, aligned_start + aligned_len).
4403 		 */
4404 		if (range_start >= aligned_start + aligned_len ||
4405 		    range_start + range_len <= aligned_start)
4406 			continue;
4407 		free_start = max(range_start, aligned_start);
4408 		free_len = min(aligned_start + aligned_len, range_start + range_len) -
4409 			   free_start;
4410 		/*
4411 		 * TODO: To also modify reserved->ranges_reserved to reflect
4412 		 * the modification.
4413 		 *
4414 		 * However as long as we free qgroup reserved according to
4415 		 * EXTENT_QGROUP_RESERVED, we won't double free.
4416 		 * So not need to rush.
4417 		 */
4418 		ret = btrfs_clear_record_extent_bits(&inode->io_tree, free_start,
4419 						     free_start + free_len - 1,
4420 						     EXTENT_QGROUP_RESERVED,
4421 						     &changeset);
4422 		if (ret < 0)
4423 			goto out;
4424 		freed += changeset.bytes_changed;
4425 	}
4426 	btrfs_qgroup_free_refroot(root->fs_info, btrfs_root_id(root), freed,
4427 				  BTRFS_QGROUP_RSV_DATA);
4428 	if (freed_ret)
4429 		*freed_ret = freed;
4430 	ret = 0;
4431 out:
4432 	extent_changeset_release(&changeset);
4433 	return ret;
4434 }
4435 
4436 static int __btrfs_qgroup_release_data(struct btrfs_inode *inode,
4437 			struct extent_changeset *reserved, u64 start, u64 len,
4438 			u64 *released, int free)
4439 {
4440 	struct extent_changeset changeset;
4441 	int trace_op = QGROUP_RELEASE;
4442 	int ret;
4443 
4444 	if (btrfs_qgroup_mode(inode->root->fs_info) == BTRFS_QGROUP_MODE_DISABLED) {
4445 		return btrfs_clear_record_extent_bits(&inode->io_tree, start,
4446 						      start + len - 1,
4447 						      EXTENT_QGROUP_RESERVED, NULL);
4448 	}
4449 
4450 	/* In release case, we shouldn't have @reserved */
4451 	WARN_ON(!free && reserved);
4452 	if (free && reserved)
4453 		return qgroup_free_reserved_data(inode, reserved, start, len, released);
4454 	extent_changeset_init_bytes_only(&changeset);
4455 	ret = btrfs_clear_record_extent_bits(&inode->io_tree, start, start + len - 1,
4456 					     EXTENT_QGROUP_RESERVED, &changeset);
4457 	if (ret < 0)
4458 		goto out;
4459 
4460 	if (free)
4461 		trace_op = QGROUP_FREE;
4462 	trace_btrfs_qgroup_release_data(&inode->vfs_inode, start, len,
4463 					changeset.bytes_changed, trace_op);
4464 	if (free)
4465 		btrfs_qgroup_free_refroot(inode->root->fs_info,
4466 				btrfs_root_id(inode->root),
4467 				changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
4468 	if (released)
4469 		*released = changeset.bytes_changed;
4470 out:
4471 	extent_changeset_release(&changeset);
4472 	return ret;
4473 }
4474 
4475 /*
4476  * Free a reserved space range from io_tree and related qgroups
4477  *
4478  * Should be called when a range of pages get invalidated before reaching disk.
4479  * Or for error cleanup case.
4480  * if @reserved is given, only reserved range in [@start, @start + @len) will
4481  * be freed.
4482  *
4483  * For data written to disk, use btrfs_qgroup_release_data().
4484  *
4485  * NOTE: This function may sleep for memory allocation.
4486  */
4487 int btrfs_qgroup_free_data(struct btrfs_inode *inode,
4488 			   struct extent_changeset *reserved,
4489 			   u64 start, u64 len, u64 *freed)
4490 {
4491 	return __btrfs_qgroup_release_data(inode, reserved, start, len, freed, 1);
4492 }
4493 
4494 /*
4495  * Release a reserved space range from io_tree only.
4496  *
4497  * Should be called when a range of pages get written to disk and corresponding
4498  * FILE_EXTENT is inserted into corresponding root.
4499  *
4500  * Since new qgroup accounting framework will only update qgroup numbers at
4501  * commit_transaction() time, its reserved space shouldn't be freed from
4502  * related qgroups.
4503  *
4504  * But we should release the range from io_tree, to allow further write to be
4505  * COWed.
4506  *
4507  * NOTE: This function may sleep for memory allocation.
4508  */
4509 int btrfs_qgroup_release_data(struct btrfs_inode *inode, u64 start, u64 len, u64 *released)
4510 {
4511 	return __btrfs_qgroup_release_data(inode, NULL, start, len, released, 0);
4512 }
4513 
4514 static void add_root_meta_rsv(struct btrfs_root *root, int num_bytes,
4515 			      enum btrfs_qgroup_rsv_type type)
4516 {
4517 	if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
4518 	    type != BTRFS_QGROUP_RSV_META_PERTRANS)
4519 		return;
4520 	if (num_bytes == 0)
4521 		return;
4522 
4523 	spin_lock(&root->qgroup_meta_rsv_lock);
4524 	if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
4525 		root->qgroup_meta_rsv_prealloc += num_bytes;
4526 	else
4527 		root->qgroup_meta_rsv_pertrans += num_bytes;
4528 	spin_unlock(&root->qgroup_meta_rsv_lock);
4529 }
4530 
4531 static int sub_root_meta_rsv(struct btrfs_root *root, int num_bytes,
4532 			     enum btrfs_qgroup_rsv_type type)
4533 {
4534 	if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
4535 	    type != BTRFS_QGROUP_RSV_META_PERTRANS)
4536 		return 0;
4537 	if (num_bytes == 0)
4538 		return 0;
4539 
4540 	spin_lock(&root->qgroup_meta_rsv_lock);
4541 	if (type == BTRFS_QGROUP_RSV_META_PREALLOC) {
4542 		num_bytes = min_t(u64, root->qgroup_meta_rsv_prealloc,
4543 				  num_bytes);
4544 		root->qgroup_meta_rsv_prealloc -= num_bytes;
4545 	} else {
4546 		num_bytes = min_t(u64, root->qgroup_meta_rsv_pertrans,
4547 				  num_bytes);
4548 		root->qgroup_meta_rsv_pertrans -= num_bytes;
4549 	}
4550 	spin_unlock(&root->qgroup_meta_rsv_lock);
4551 	return num_bytes;
4552 }
4553 
4554 static int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
4555 				     enum btrfs_qgroup_rsv_type type, bool enforce)
4556 {
4557 	struct btrfs_fs_info *fs_info = root->fs_info;
4558 	int ret;
4559 
4560 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_DISABLED ||
4561 	    !btrfs_is_fstree(btrfs_root_id(root)) || num_bytes == 0)
4562 		return 0;
4563 
4564 	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4565 	trace_btrfs_qgroup_meta_reserve(root, (s64)num_bytes, type);
4566 	ret = qgroup_reserve(root, num_bytes, enforce, type);
4567 	if (ret < 0)
4568 		return ret;
4569 	/*
4570 	 * Record what we have reserved into root.
4571 	 *
4572 	 * To avoid quota disabled->enabled underflow.
4573 	 * In that case, we may try to free space we haven't reserved
4574 	 * (since quota was disabled), so record what we reserved into root.
4575 	 * And ensure later release won't underflow this number.
4576 	 */
4577 	add_root_meta_rsv(root, num_bytes, type);
4578 	return ret;
4579 }
4580 
4581 int btrfs_qgroup_reserve_meta_prealloc(struct btrfs_root *root, int num_bytes,
4582 				       bool enforce, bool noflush)
4583 {
4584 	int ret;
4585 
4586 	ret = btrfs_qgroup_reserve_meta(root, num_bytes,
4587 					BTRFS_QGROUP_RSV_META_PREALLOC, enforce);
4588 	if ((ret <= 0 && ret != -EDQUOT) || noflush)
4589 		return ret;
4590 
4591 	ret = try_flush_qgroup(root);
4592 	if (ret < 0)
4593 		return ret;
4594 	return btrfs_qgroup_reserve_meta(root, num_bytes,
4595 					 BTRFS_QGROUP_RSV_META_PREALLOC, enforce);
4596 }
4597 
4598 /*
4599  * Per-transaction meta reservation should be all freed at transaction commit
4600  * time
4601  */
4602 void btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root *root)
4603 {
4604 	struct btrfs_fs_info *fs_info = root->fs_info;
4605 
4606 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_DISABLED ||
4607 	    !btrfs_is_fstree(btrfs_root_id(root)))
4608 		return;
4609 
4610 	/* TODO: Update trace point to handle such free */
4611 	trace_btrfs_qgroup_meta_free_all_pertrans(root);
4612 	/* Special value -1 means to free all reserved space */
4613 	btrfs_qgroup_free_refroot(fs_info, btrfs_root_id(root), (u64)-1,
4614 				  BTRFS_QGROUP_RSV_META_PERTRANS);
4615 }
4616 
4617 void btrfs_qgroup_free_meta_prealloc(struct btrfs_root *root, int num_bytes)
4618 {
4619 	struct btrfs_fs_info *fs_info = root->fs_info;
4620 
4621 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_DISABLED ||
4622 	    !btrfs_is_fstree(btrfs_root_id(root)))
4623 		return;
4624 
4625 	/*
4626 	 * reservation for META_PREALLOC can happen before quota is enabled,
4627 	 * which can lead to underflow.
4628 	 * Here ensure we will only free what we really have reserved.
4629 	 */
4630 	num_bytes = sub_root_meta_rsv(root, num_bytes,
4631 				      BTRFS_QGROUP_RSV_META_PREALLOC);
4632 	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4633 	trace_btrfs_qgroup_meta_reserve(root, -(s64)num_bytes,
4634 					BTRFS_QGROUP_RSV_META_PREALLOC);
4635 	btrfs_qgroup_free_refroot(fs_info, btrfs_root_id(root), num_bytes,
4636 				  BTRFS_QGROUP_RSV_META_PREALLOC);
4637 }
4638 
4639 static void qgroup_convert_meta(struct btrfs_fs_info *fs_info, u64 ref_root,
4640 				int num_bytes)
4641 {
4642 	struct btrfs_qgroup *qgroup;
4643 	LIST_HEAD(qgroup_list);
4644 
4645 	if (num_bytes == 0)
4646 		return;
4647 	if (!fs_info->quota_root)
4648 		return;
4649 
4650 	spin_lock(&fs_info->qgroup_lock);
4651 	qgroup = find_qgroup_rb(fs_info, ref_root);
4652 	if (!qgroup)
4653 		goto out;
4654 
4655 	qgroup_iterator_add(&qgroup_list, qgroup);
4656 	list_for_each_entry(qgroup, &qgroup_list, iterator) {
4657 		struct btrfs_qgroup_list *glist;
4658 
4659 		qgroup_rsv_release(fs_info, qgroup, num_bytes,
4660 				BTRFS_QGROUP_RSV_META_PREALLOC);
4661 		if (!sb_rdonly(fs_info->sb))
4662 			qgroup_rsv_add(fs_info, qgroup, num_bytes,
4663 				       BTRFS_QGROUP_RSV_META_PERTRANS);
4664 
4665 		list_for_each_entry(glist, &qgroup->groups, next_group)
4666 			qgroup_iterator_add(&qgroup_list, glist->group);
4667 	}
4668 out:
4669 	qgroup_iterator_clean(&qgroup_list);
4670 	spin_unlock(&fs_info->qgroup_lock);
4671 }
4672 
4673 /*
4674  * Convert @num_bytes of META_PREALLOCATED reservation to META_PERTRANS.
4675  *
4676  * This is called when preallocated meta reservation needs to be used.
4677  * Normally after btrfs_join_transaction() call.
4678  */
4679 void btrfs_qgroup_convert_reserved_meta(struct btrfs_root *root, int num_bytes)
4680 {
4681 	struct btrfs_fs_info *fs_info = root->fs_info;
4682 
4683 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_DISABLED ||
4684 	    !btrfs_is_fstree(btrfs_root_id(root)))
4685 		return;
4686 	/* Same as btrfs_qgroup_free_meta_prealloc() */
4687 	num_bytes = sub_root_meta_rsv(root, num_bytes,
4688 				      BTRFS_QGROUP_RSV_META_PREALLOC);
4689 	trace_btrfs_qgroup_meta_convert(root, num_bytes);
4690 	qgroup_convert_meta(fs_info, btrfs_root_id(root), num_bytes);
4691 	if (!sb_rdonly(fs_info->sb))
4692 		add_root_meta_rsv(root, num_bytes, BTRFS_QGROUP_RSV_META_PERTRANS);
4693 }
4694 
4695 /*
4696  * Check qgroup reserved space leaking, normally at destroy inode
4697  * time
4698  */
4699 void btrfs_qgroup_check_reserved_leak(struct btrfs_inode *inode)
4700 {
4701 	struct extent_changeset changeset;
4702 	struct ulist_node *unode;
4703 	struct ulist_iterator iter;
4704 	int ret;
4705 
4706 	extent_changeset_init(&changeset);
4707 	ret = btrfs_clear_record_extent_bits(&inode->io_tree, 0, (u64)-1,
4708 					     EXTENT_QGROUP_RESERVED, &changeset);
4709 
4710 	WARN_ON(ret < 0);
4711 	if (WARN_ON(changeset.bytes_changed)) {
4712 		ASSERT(extent_changeset_tracks_ranges(&changeset));
4713 		ULIST_ITER_INIT(&iter);
4714 		while ((unode = ulist_next(&changeset.range_changed, &iter))) {
4715 			btrfs_warn(inode->root->fs_info,
4716 		"leaking qgroup reserved space, ino: %llu, start: %llu, end: %llu",
4717 				btrfs_ino(inode), unode->val, unode->aux);
4718 		}
4719 		btrfs_qgroup_free_refroot(inode->root->fs_info,
4720 				btrfs_root_id(inode->root),
4721 				changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
4722 
4723 	}
4724 	extent_changeset_release(&changeset);
4725 }
4726 
4727 void btrfs_qgroup_init_swapped_blocks(
4728 	struct btrfs_qgroup_swapped_blocks *swapped_blocks)
4729 {
4730 	int i;
4731 
4732 	spin_lock_init(&swapped_blocks->lock);
4733 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
4734 		swapped_blocks->blocks[i] = RB_ROOT;
4735 	swapped_blocks->swapped = false;
4736 }
4737 
4738 /*
4739  * Delete all swapped blocks record of @root.
4740  * Every record here means we skipped a full subtree scan for qgroup.
4741  *
4742  * Gets called when committing one transaction.
4743  */
4744 void btrfs_qgroup_clean_swapped_blocks(struct btrfs_root *root)
4745 {
4746 	struct btrfs_qgroup_swapped_blocks *swapped_blocks;
4747 	int i;
4748 
4749 	swapped_blocks = &root->swapped_blocks;
4750 
4751 	spin_lock(&swapped_blocks->lock);
4752 	if (!swapped_blocks->swapped)
4753 		goto out;
4754 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4755 		struct rb_root *cur_root = &swapped_blocks->blocks[i];
4756 		struct btrfs_qgroup_swapped_block *entry;
4757 		struct btrfs_qgroup_swapped_block *next;
4758 
4759 		rbtree_postorder_for_each_entry_safe(entry, next, cur_root,
4760 						     node)
4761 			kfree(entry);
4762 		swapped_blocks->blocks[i] = RB_ROOT;
4763 	}
4764 	swapped_blocks->swapped = false;
4765 out:
4766 	spin_unlock(&swapped_blocks->lock);
4767 }
4768 
4769 static int qgroup_swapped_block_bytenr_key_cmp(const void *key, const struct rb_node *node)
4770 {
4771 	const u64 *bytenr = key;
4772 	const struct btrfs_qgroup_swapped_block *block = rb_entry(node,
4773 					  struct btrfs_qgroup_swapped_block, node);
4774 
4775 	if (block->subvol_bytenr < *bytenr)
4776 		return -1;
4777 	else if (block->subvol_bytenr > *bytenr)
4778 		return 1;
4779 
4780 	return 0;
4781 }
4782 
4783 static int qgroup_swapped_block_bytenr_cmp(struct rb_node *new, const struct rb_node *existing)
4784 {
4785 	const struct btrfs_qgroup_swapped_block *new_block = rb_entry(new,
4786 					      struct btrfs_qgroup_swapped_block, node);
4787 
4788 	return qgroup_swapped_block_bytenr_key_cmp(&new_block->subvol_bytenr, existing);
4789 }
4790 
4791 /*
4792  * Add subtree roots record into @subvol_root.
4793  *
4794  * @subvol_root:	tree root of the subvolume tree get swapped
4795  * @bg:			block group under balance
4796  * @subvol_parent/slot:	pointer to the subtree root in subvolume tree
4797  * @reloc_parent/slot:	pointer to the subtree root in reloc tree
4798  *			BOTH POINTERS ARE BEFORE TREE SWAP
4799  * @last_snapshot:	last snapshot generation of the subvolume tree
4800  */
4801 int btrfs_qgroup_add_swapped_blocks(struct btrfs_root *subvol_root,
4802 		struct btrfs_block_group *bg,
4803 		struct extent_buffer *subvol_parent, int subvol_slot,
4804 		struct extent_buffer *reloc_parent, int reloc_slot,
4805 		u64 last_snapshot)
4806 {
4807 	struct btrfs_fs_info *fs_info = subvol_root->fs_info;
4808 	struct btrfs_qgroup_swapped_blocks *blocks = &subvol_root->swapped_blocks;
4809 	struct btrfs_qgroup_swapped_block *block;
4810 	struct rb_node *node;
4811 	int level = btrfs_header_level(subvol_parent) - 1;
4812 	int ret = 0;
4813 
4814 	if (!btrfs_qgroup_full_accounting(fs_info))
4815 		return 0;
4816 
4817 	if (unlikely(btrfs_node_ptr_generation(subvol_parent, subvol_slot) >
4818 		     btrfs_node_ptr_generation(reloc_parent, reloc_slot))) {
4819 		btrfs_err_rl(fs_info,
4820 		"%s: bad parameter order, subvol_gen=%llu reloc_gen=%llu",
4821 			__func__,
4822 			btrfs_node_ptr_generation(subvol_parent, subvol_slot),
4823 			btrfs_node_ptr_generation(reloc_parent, reloc_slot));
4824 		return -EUCLEAN;
4825 	}
4826 
4827 	block = kmalloc_obj(*block, GFP_NOFS);
4828 	if (!block) {
4829 		ret = -ENOMEM;
4830 		goto out;
4831 	}
4832 
4833 	/*
4834 	 * @reloc_parent/slot is still before swap, while @block is going to
4835 	 * record the bytenr after swap, so we do the swap here.
4836 	 */
4837 	block->subvol_bytenr = btrfs_node_blockptr(reloc_parent, reloc_slot);
4838 	block->subvol_generation = btrfs_node_ptr_generation(reloc_parent,
4839 							     reloc_slot);
4840 	block->reloc_bytenr = btrfs_node_blockptr(subvol_parent, subvol_slot);
4841 	block->reloc_generation = btrfs_node_ptr_generation(subvol_parent,
4842 							    subvol_slot);
4843 	block->last_snapshot = last_snapshot;
4844 	block->level = level;
4845 
4846 	/*
4847 	 * If we have bg == NULL, we're called from btrfs_recover_relocation(),
4848 	 * no one else can modify tree blocks thus we qgroup will not change
4849 	 * no matter the value of trace_leaf.
4850 	 */
4851 	if (bg && bg->flags & BTRFS_BLOCK_GROUP_DATA)
4852 		block->trace_leaf = true;
4853 	else
4854 		block->trace_leaf = false;
4855 	btrfs_node_key_to_cpu(reloc_parent, &block->first_key, reloc_slot);
4856 
4857 	/* Insert @block into @blocks */
4858 	spin_lock(&blocks->lock);
4859 	node = rb_find_add(&block->node, &blocks->blocks[level], qgroup_swapped_block_bytenr_cmp);
4860 	if (node) {
4861 		struct btrfs_qgroup_swapped_block *entry;
4862 
4863 		entry = rb_entry(node, struct btrfs_qgroup_swapped_block, node);
4864 
4865 		if (unlikely(entry->subvol_generation != block->subvol_generation ||
4866 			     entry->reloc_bytenr != block->reloc_bytenr ||
4867 			     entry->reloc_generation != block->reloc_generation)) {
4868 			/*
4869 			 * Duplicated but mismatch entry found.  Shouldn't happen.
4870 			 * Marking qgroup inconsistent should be enough for end
4871 			 * users.
4872 			 */
4873 			DEBUG_WARN("duplicated but mismatched entry found");
4874 			ret = -EEXIST;
4875 		}
4876 		kfree(block);
4877 		goto out_unlock;
4878 	}
4879 	blocks->swapped = true;
4880 out_unlock:
4881 	spin_unlock(&blocks->lock);
4882 out:
4883 	if (ret < 0)
4884 		qgroup_mark_inconsistent(fs_info, "%s error: %d", __func__, ret);
4885 	return ret;
4886 }
4887 
4888 /*
4889  * Check if the tree block is a subtree root, and if so do the needed
4890  * delayed subtree trace for qgroup.
4891  *
4892  * This is called during btrfs_cow_block().
4893  */
4894 int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans,
4895 					 struct btrfs_root *root,
4896 					 struct extent_buffer *subvol_eb)
4897 {
4898 	struct btrfs_fs_info *fs_info = root->fs_info;
4899 	struct btrfs_tree_parent_check check = { 0 };
4900 	struct btrfs_qgroup_swapped_blocks *blocks = &root->swapped_blocks;
4901 	struct btrfs_qgroup_swapped_block AUTO_KFREE(block);
4902 	struct extent_buffer *reloc_eb = NULL;
4903 	struct rb_node *node;
4904 	bool swapped = false;
4905 	int level = btrfs_header_level(subvol_eb);
4906 	int ret = 0;
4907 	int i;
4908 
4909 	if (!btrfs_qgroup_full_accounting(fs_info))
4910 		return 0;
4911 	if (!btrfs_is_fstree(btrfs_root_id(root)) || !root->reloc_root)
4912 		return 0;
4913 
4914 	spin_lock(&blocks->lock);
4915 	if (!blocks->swapped) {
4916 		spin_unlock(&blocks->lock);
4917 		return 0;
4918 	}
4919 	node = rb_find(&subvol_eb->start, &blocks->blocks[level],
4920 			qgroup_swapped_block_bytenr_key_cmp);
4921 	if (!node) {
4922 		spin_unlock(&blocks->lock);
4923 		goto out;
4924 	}
4925 	block = rb_entry(node, struct btrfs_qgroup_swapped_block, node);
4926 
4927 	/* Found one, remove it from @blocks first and update blocks->swapped */
4928 	rb_erase(&block->node, &blocks->blocks[level]);
4929 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4930 		if (!RB_EMPTY_ROOT(&blocks->blocks[i])) {
4931 			swapped = true;
4932 			break;
4933 		}
4934 	}
4935 	blocks->swapped = swapped;
4936 	spin_unlock(&blocks->lock);
4937 
4938 	check.level = block->level;
4939 	check.transid = block->reloc_generation;
4940 	check.has_first_key = true;
4941 	memcpy(&check.first_key, &block->first_key, sizeof(check.first_key));
4942 
4943 	/* Read out reloc subtree root */
4944 	reloc_eb = read_tree_block(fs_info, block->reloc_bytenr, &check);
4945 	if (IS_ERR(reloc_eb)) {
4946 		ret = PTR_ERR(reloc_eb);
4947 		reloc_eb = NULL;
4948 		goto free_out;
4949 	}
4950 
4951 	ret = qgroup_trace_subtree_swap(trans, reloc_eb, subvol_eb,
4952 			block->last_snapshot, block->trace_leaf);
4953 free_out:
4954 	free_extent_buffer(reloc_eb);
4955 out:
4956 	if (ret < 0) {
4957 		qgroup_mark_inconsistent(fs_info,
4958 				"failed to account subtree at bytenr %llu: %d",
4959 				subvol_eb->start, ret);
4960 	}
4961 	return ret;
4962 }
4963 
4964 void btrfs_qgroup_destroy_extent_records(struct btrfs_transaction *trans)
4965 {
4966 	struct btrfs_qgroup_extent_record *entry;
4967 	unsigned long index;
4968 
4969 	xa_for_each(&trans->delayed_refs.dirty_extents, index, entry) {
4970 		ulist_free(entry->old_roots);
4971 		kfree(entry);
4972 	}
4973 	xa_destroy(&trans->delayed_refs.dirty_extents);
4974 }
4975 
4976 void btrfs_record_squota_delta(struct btrfs_fs_info *fs_info,
4977 			       const struct btrfs_squota_delta *delta)
4978 {
4979 	struct btrfs_qgroup *qgroup;
4980 	struct btrfs_qgroup *qg;
4981 	LIST_HEAD(qgroup_list);
4982 	u64 root = delta->root;
4983 	u64 num_bytes = delta->num_bytes;
4984 	const int sign = (delta->is_inc ? 1 : -1);
4985 
4986 	if (btrfs_qgroup_mode(fs_info) != BTRFS_QGROUP_MODE_SIMPLE &&
4987 	    !test_bit(BTRFS_FS_SQUOTA_ENABLING, &fs_info->flags))
4988 		return;
4989 
4990 	if (!btrfs_is_fstree(root))
4991 		return;
4992 
4993 	/* If the extent predates enabling quotas, don't count it. */
4994 	if (delta->generation < fs_info->qgroup_enable_gen)
4995 		return;
4996 
4997 	spin_lock(&fs_info->qgroup_lock);
4998 	qgroup = find_qgroup_rb(fs_info, root);
4999 	if (WARN_ON_ONCE(!qgroup)) {
5000 		btrfs_warn(fs_info, "squota failed to find qgroup for root %llu", root);
5001 		goto out;
5002 	}
5003 
5004 	qgroup_iterator_add(&qgroup_list, qgroup);
5005 	list_for_each_entry(qg, &qgroup_list, iterator) {
5006 		struct btrfs_qgroup_list *glist;
5007 
5008 		ASSERT(qg->excl == qg->rfer);
5009 		if (WARN_ON_ONCE(sign < 0 && qg->excl < num_bytes)) {
5010 			btrfs_warn(fs_info,
5011 				   "squota underflow qg " BTRFS_QGROUP_FMT " excl %llu num_bytes %llu",
5012 				   BTRFS_QGROUP_FMT_VALUE(qg),
5013 				   qg->excl, num_bytes);
5014 			qg->excl = 0;
5015 			qg->rfer = 0;
5016 		} else {
5017 			qg->excl += num_bytes * sign;
5018 			qg->rfer += num_bytes * sign;
5019 		}
5020 		qgroup_dirty(fs_info, qg);
5021 
5022 		list_for_each_entry(glist, &qg->groups, next_group)
5023 			qgroup_iterator_add(&qgroup_list, glist->group);
5024 	}
5025 	qgroup_iterator_clean(&qgroup_list);
5026 
5027 out:
5028 	spin_unlock(&fs_info->qgroup_lock);
5029 }
5030