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