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