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