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