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