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