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