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